diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobStatus.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobStatus.h index f56c2d8081..01ed86c6cd 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobStatus.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobStatus.h @@ -1,45 +1,45 @@ /*=================================================================== BlueBerry Platform 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 _BERRYIJOBSTATUS_H #define _BERRYIJOBSTATUS_H #include "berryIStatus.h" #include "berryObject.h" #include "berryJob.h" namespace berry { /** * Represents status relating to the execution of jobs. * @see IStatus * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ struct IJobStatus : public IStatus { berryObjectMacro(IJobStatus) /** * Returns the job associated with this status. * @return the job associated with this status */ virtual Job::Pointer GetJob() = 0; }; } -#endif /*_BERRYIJOBSTATUS_H */ \ No newline at end of file +#endif /*_BERRYIJOBSTATUS_H */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJobStatus.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJobStatus.h index b09be80d00..98d87988aa 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJobStatus.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJobStatus.h @@ -1,105 +1,105 @@ /*=================================================================== BlueBerry Platform 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 _BERRYJOBSTATUS_H #define _BERRYJOBSTATUS_H #include "berryIJobStatus.h" #include "berryStatus.h" #include "berryJob.h" #include namespace berry { class BERRY_JOBS JobStatus : public IJobStatus { public: berryObjectMacro(JobStatus) /** * Creates a new job status with no interesting error code or exception. * @param severity * @param job * @param message */ JobStatus( const Status::Severity& severity, Job::Pointer sptr_job, const std::string& message) ; /** * @see IJobStatus#GetJob() */ Job::Pointer GetJob() ; /** * @see org.blueberry.solstice.common IStatus GetChildren() */ std::vector GetChildren() const ; /** * @see org.blueberry.solstice.common IStatus GetCode() */ int GetCode() const ; /** *@see org.blueberry.solstice.common IStatus GetException () */ std::exception GetException() const ; /** * @see org.blueberry.solstice.common GetMessage () */ std::string GetMessage() const ; /** * @see org.blueberry.solstice.common IStatus GetPlugin() */ std::string GetPlugin() const ; /** * @see org.blueberry.solstice.common IStatus GetSeverity () */ Severity GetSeverity() const ; /** * @see org.blueberry.solstice.common IsMultiStatus () */ bool IsMultiStatus() const ; /** * @see org.blueberry.solstice.common IStatus IsOk () */ bool IsOK() const ; /** * @see org.blueberry.solstice.common IStatus Matches () */ bool Matches(const Severities& severityMask) const ; private: Job::Pointer m_myJob ; Status::Pointer m_internalStatus ; }; } -#endif /* _BERRYJOBSTATUS_H */ \ No newline at end of file +#endif /* _BERRYJOBSTATUS_H */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorkerPool.cpp b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorkerPool.cpp index c57dc20b4c..2b0b01ca74 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorkerPool.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorkerPool.cpp @@ -1,219 +1,219 @@ /*=================================================================== BlueBerry Platform 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 NOMINMAX #include "berryWorkerPool.h" #include "berryJobManager.h" #include #include #include namespace berry { WorkerPool::WorkerPool(JobManager* myJobManager) : m_ptrManager(myJobManager), m_numThreads(0), m_sleepingThreads(0), m_threads( 10), m_busyThreads(0) // m_isDaemon(false), { } const long WorkerPool::BEST_BEFORE = 60000; const int WorkerPool::MIN_THREADS = 1; void WorkerPool::Shutdown() { Poco::ScopedLock LockMe(m_mutexOne); for(int i = 0; i<= m_numThreads; i++) { notify(); } } void WorkerPool::Add(Worker::Pointer worker) { Poco::Mutex::ScopedLock lock(m_mutexOne); m_threads.push_back(worker); } void WorkerPool::DecrementBusyThreads() { Poco::ScopedLock lockOne(m_mutexOne); //impossible to have less than zero busy threads if (--m_busyThreads < 0) { //TODO Decrementbusythreads if (jobmanager.debug) assert.istrue(false, integer.tostring(busythreads)); m_busyThreads = 0; } } void WorkerPool::IncrementBusyThreads() { Poco::ScopedLock lockOne(m_mutexOne); if (++m_busyThreads > m_numThreads) { m_busyThreads = m_numThreads; } } bool WorkerPool::Remove(Worker::Pointer worker) { Poco::ScopedLock lockOne(m_mutexOne); std::vector::iterator end = std::remove(m_threads.begin(), m_threads.end(), worker); bool removed = end != m_threads.end(); m_threads.erase(end); return removed; } void WorkerPool::EndWorker(Worker::Pointer sptr_worker) { Poco::ScopedLock lock(m_mutexOne); Remove(sptr_worker); } void WorkerPool::Sleep(long duration) { Poco::ScopedLock lock(m_mutexOne); m_sleepingThreads++; m_busyThreads--; try { wait(duration); throw FinallyThrowException(); } catch (FinallyThrowException&) { m_sleepingThreads--; m_busyThreads++; } catch (...) { m_sleepingThreads--; m_busyThreads++; } } InternalJob::Pointer WorkerPool::StartJob(Worker* worker) { // if we're above capacity, kill the thread { Poco::Mutex::ScopedLock lockOne(m_mutexOne); if (!m_ptrManager->IsActive()) { // must remove the worker immediately to prevent all threads from expiring Worker::Pointer sptr_worker(worker); EndWorker(sptr_worker); return InternalJob::Pointer(0); } //set the thread to be busy now in case of reentrant scheduling IncrementBusyThreads(); } Job::Pointer ptr_job(0); try { ptr_job = m_ptrManager->StartJob(); //spin until a job is found or until we have been idle for too long Poco::Timestamp idleStart; while (m_ptrManager->IsActive() && ptr_job == 0) { long tmpSleepTime = long(m_ptrManager->SleepHint()); if (tmpSleepTime > 0) Sleep(std::min(tmpSleepTime, BEST_BEFORE)); ptr_job = m_ptrManager->StartJob(); //if we were already idle, and there are still no new jobs, then the thread can expire { Poco::Mutex::ScopedLock lockOne(m_mutexOne); Poco::Timestamp tmpCurrentTime; long long tmpTime = tmpCurrentTime - idleStart; if (ptr_job == 0 && (tmpTime > BEST_BEFORE) && (m_numThreads - m_busyThreads) > MIN_THREADS) { //must remove the worker immediately to prevent all threads from expiring Worker::Pointer sptr_worker(worker); EndWorker(sptr_worker); return InternalJob::Pointer(0); } } } if (ptr_job != 0) { //if this job has a rule, then we are essentially acquiring a lock //if ((job.getRule() != 0) && !(job instanceof ThreadJob)) { // //don't need to re-aquire locks because it was not recorded in the graph // //that this thread waited to get this rule // manager.getLockManager().addLockThread(Thread.currentThread(), job.getRule()); // } //see if we need to wake another worker if (m_ptrManager->SleepHint() <= 0) JobQueued(); } throw FinallyThrowException(); } catch (FinallyThrowException&) { //decrement busy thread count if we're not running a job if (ptr_job == 0) DecrementBusyThreads(); } catch (...) { DecrementBusyThreads(); } return ptr_job; } void WorkerPool::JobQueued() { Poco::ScopedLock lockOne(m_mutexOne); //if there is a sleeping thread, wake it up if (m_sleepingThreads > 0) { notify(); return; } //create a thread if all threads are busy if (m_busyThreads >= m_numThreads) { WorkerPool::WeakPtr wp_WorkerPool(WorkerPool::Pointer(this)); Worker::Pointer sptr_worker(new Worker(wp_WorkerPool)); Add(sptr_worker); sptr_worker->Start(); return; } } void WorkerPool::EndJob(InternalJob::Pointer job, IStatus::Pointer result) { DecrementBusyThreads(); //TODO LockManager // //need to end rule in graph before ending job so that 2 threads // //do not become the owners of the same rule in the graph // if ((job.getRule() != null) && !(job instanceof ThreadJob)) { // //remove any locks this thread may be owning on that rule // manager.getLockManager().removeLockCompletely(Thread.currentThread(), job.getRule()); // } m_ptrManager->EndJob(job, result, true); // //ensure this thread no longer owns any scheduling rules // manager.implicitJobs.endJob(job); } -} \ No newline at end of file +} diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryBackingStoreException.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryBackingStoreException.cpp index 2c184c90e7..78f896e529 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryBackingStoreException.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryBackingStoreException.cpp @@ -1,24 +1,24 @@ /*=================================================================== BlueBerry Platform 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 "berryBackingStoreException.h" #include namespace berry { POCO_IMPLEMENT_EXCEPTION(BackingStoreException, Poco::RuntimeException, "BackingStore Exception") -} \ No newline at end of file +} diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryBackingStoreException.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryBackingStoreException.h index f68488349c..11edc2e4a8 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryBackingStoreException.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryBackingStoreException.h @@ -1,33 +1,33 @@ /*=================================================================== BlueBerry Platform 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 BERRYBACKINGSTOREEXCEPTION_H_ #define BERRYBACKINGSTOREEXCEPTION_H_ #include #include namespace berry { /** * Thrown to indicate that a preferences operation could not complete because of * a failure in the backing store, or a failure to contact the backing store. * * @version $Revision$ */ POCO_DECLARE_EXCEPTION(BERRY_RUNTIME, BackingStoreException, Poco::RuntimeException); } -#endif /* BERRYBACKINGSTOREEXCEPTION_H_ */ \ No newline at end of file +#endif /* BERRYBACKINGSTOREEXCEPTION_H_ */ diff --git a/BlueBerry/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesServiceTest.cpp b/BlueBerry/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesServiceTest.cpp index 029cfc10cc..7c62e00c22 100644 --- a/BlueBerry/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesServiceTest.cpp +++ b/BlueBerry/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesServiceTest.cpp @@ -1,140 +1,140 @@ /*=================================================================== BlueBerry Platform 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 "berryPreferencesServiceTest.h" #include #include #include #include "berryLog.h" #include #include #include "Poco/File.h" #include "Poco/Path.h" #include "Poco/AutoPtr.h" #include #include #include using namespace std; namespace berry { PreferencesServiceTest::PreferencesServiceTest(const std::string& testName) : berry::TestCase(testName) {} CppUnit::Test* PreferencesServiceTest::Suite() { CppUnit::TestSuite* suite = new CppUnit::TestSuite("PreferencesServiceTest"); CppUnit_addTest(suite, PreferencesServiceTest, TestAll); return suite; } void PreferencesServiceTest::TestAll() { try { IPreferencesService::Pointer prefService = Platform::GetServiceRegistry().GetServiceById(IPreferencesService::ID); assert(prefService.IsNotNull()); /// Test for: IPreferences::GetSystemPreferences() IPreferences::Pointer sysPrefs = prefService->GetSystemPreferences(); assert(sysPrefs.IsNotNull()); /// Test for: IPreferences::GetUserPreferences(std::string name) IPreferences::Pointer testUserPrefs = prefService->GetUserPreferences("testUser"); assert(testUserPrefs.IsNotNull()); /// Test for: IPreferences::GetUsers() std::vector userList = prefService->GetUsers(); // userList should now contain "testUser" bool userListContainsTestUser = false; for (std::vector::iterator it = userList.begin() ; it != userList.end(); it++) { if(*it == "testUser") { userListContainsTestUser = true; break; } } assert(userListContainsTestUser); IBerryPreferencesService::Pointer berryPrefService = prefService.Cast(); // optional test for IBerryPreferencesService if(berryPrefService.IsNotNull()) { /// Test for: IBerryPreferencesService::ExportPreferences(Poco::File f, std::string name="") // write general prefs std::string sysPrefsExportFilePath = Poco::Path::temp() + Poco::Path::separator() + "systemBerryPreferences"; Poco::File sysPrefsExportFile(sysPrefsExportFilePath); sysPrefs->PutInt("testNumber", 1); berryPrefService->ExportPreferences(sysPrefsExportFile); // assert somethings was written assert(sysPrefsExportFile.getSize() > 0); // write testUser prefs std::string testUserPrefsExportFilePath = Poco::Path::temp() + Poco::Path::separator() + "testUserBerryPreferences"; Poco::File testUserPrefsExportFile(testUserPrefsExportFilePath); testUserPrefs->PutInt("testNumber", 2); berryPrefService->ExportPreferences(testUserPrefsExportFile, "testUser"); assert(testUserPrefsExportFile.getSize() > 0); /// Test for: IBerryPreferencesService::ImportPreferences(Poco::File f, std::string name="") // import general prefs // change testNumber value sysPrefs->PutInt("testNumber", 3); berryPrefService->ImportPreferences(sysPrefsExportFile); // "testNumber" preference should now again be overwritten with its old value 1 assert(sysPrefs->GetInt("testNumber", 3) == 1); // import testUser prefs // change testNumber value testUserPrefs->PutInt("testNumber", 4); berryPrefService->ImportPreferences(testUserPrefsExportFile, "testUser"); // "testNumber" preference should now again be overwritten with its old value 2 assert(testUserPrefs->GetInt("testNumber", 4) == 2); // delete files again sysPrefsExportFile.remove(); testUserPrefsExportFile.remove(); } } catch (Poco::CreateFileException& e) { std::string msg = "Failed to create preferences file: "; msg.append(e.what()); this->fail( msg ); } catch (std::exception& e) { this->fail( e.what() ); } catch (...) { this->fail( "unknown exception occured" ); } } -} \ No newline at end of file +} diff --git a/BlueBerry/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesTest.cpp b/BlueBerry/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesTest.cpp index 6798a4bb9e..289f23744a 100644 --- a/BlueBerry/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesTest.cpp +++ b/BlueBerry/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesTest.cpp @@ -1,177 +1,177 @@ /*=================================================================== BlueBerry Platform 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 "berryPreferencesTest.h" #include #include #include #include #include #include "berryLog.h" #include "Poco/File.h" #include "Poco/Path.h" #include #include #include using namespace std; namespace berry { PreferencesTest::PreferencesTest(const std::string& testName) : berry::TestCase(testName) {} CppUnit::Test* PreferencesTest::Suite() { CppUnit::TestSuite* suite = new CppUnit::TestSuite("PreferencesTest"); CppUnit_addTest(suite, PreferencesTest, TestAll); return suite; } // simple class for testing berry changed events class TestPreferencesChangedListener { public: TestPreferencesChangedListener(IBerryPreferences* _berryPrefNode) : numCalled(0), berryPrefNode(_berryPrefNode) { berryPrefNode->OnChanged.AddListener( berry::MessageDelegate1 ( this, &TestPreferencesChangedListener::PreferencesChanged ) ); }; ~TestPreferencesChangedListener() { berryPrefNode->OnChanged.RemoveListener( berry::MessageDelegate1 ( this, &TestPreferencesChangedListener::PreferencesChanged ) ); }; void PreferencesChanged(const IBerryPreferences*) { ++numCalled; } int numCalled; IBerryPreferences* berryPrefNode; }; void PreferencesTest::TestAll() { IPreferencesService::Pointer prefService = Platform::GetServiceRegistry().GetServiceById(IPreferencesService::ID); assert(prefService.IsNotNull()); /// Test for: IPreferences::GetSystemPreferences() IPreferences::Pointer root = prefService->GetSystemPreferences(); assert(root.IsNotNull()); { BERRY_INFO << "testing Preferences::Node(), Preferences::NodeExists(), Preferences::Parent(), " "Preferences::ChildrenNames(), Preferences::RemoveNode()"; berry::IPreferences::Pointer editorsNode(0); editorsNode = root->Node("/editors"); assert(editorsNode.IsNotNull()); assert(editorsNode->NodeExists("/editors")); assert(editorsNode->Parent() == root); berry::IPreferences::Pointer editorsGeneralNode = root->Node("/editors/general"); assert(editorsNode->NodeExists("/editors/general")); berry::IPreferences::Pointer editorsSyntaxNode = root->Node("/editors/syntax"); assert(editorsGeneralNode->NodeExists("/editors/syntax")); berry::IPreferences::Pointer editorsFontNode = root->Node("/editors/font"); assert(editorsSyntaxNode->NodeExists("/editors/font")); vector childrenNames; childrenNames.push_back("general"); childrenNames.push_back("syntax"); childrenNames.push_back("font"); assert(editorsNode->ChildrenNames() == childrenNames); editorsFontNode->RemoveNode(); try { editorsFontNode->Parent(); failmsg("this should throw a Poco::IllegalStateException"); } catch (Poco::IllegalStateException) { // expected } } // testing methods // Preferences::put*() // Preferences::get*() { BERRY_INFO << "testing Preferences::put*(), Preferences::get*(), OnChanged"; assert(root->NodeExists("/editors/general")); berry::IPreferences::Pointer editorsGeneralNode = root->Node("/editors/general"); IBerryPreferences::Pointer berryEditorsGeneralNode = editorsGeneralNode.Cast< IBerryPreferences >(); assert(berryEditorsGeneralNode.IsNotNull()); TestPreferencesChangedListener listener(berryEditorsGeneralNode.GetPointer()); std::string strKey = "Bad words";std::string strValue = "badword1 badword2"; editorsGeneralNode->Put(strKey, strValue); assert(listener.numCalled == 1); assert(editorsGeneralNode->Get(strKey, "") == strValue); assert(editorsGeneralNode->Get("wrong key", "default value") == "default value"); strKey = "Show Line Numbers";bool bValue = true; editorsGeneralNode->PutBool(strKey, bValue); assert(listener.numCalled == 2); assert(editorsGeneralNode->GetBool(strKey, !bValue) == bValue); strKey = "backgroundcolor"; strValue = "#00FF00"; editorsGeneralNode->PutByteArray(strKey, strValue); assert(listener.numCalled == 3); assert(editorsGeneralNode->GetByteArray(strKey, "") == strValue); strKey = "update time"; double dValue = 1.23; editorsGeneralNode->PutDouble(strKey, dValue); assert(editorsGeneralNode->GetDouble(strKey, 0.0) == dValue); strKey = "update time float"; float fValue = 1.23f; editorsGeneralNode->PutFloat(strKey, fValue); assert(editorsGeneralNode->GetFloat(strKey, 0.0f) == fValue); strKey = "Break on column"; int iValue = 80; editorsGeneralNode->PutInt(strKey, iValue); assert(editorsGeneralNode->GetInt(strKey, 0) == iValue); strKey = "Maximum number of words"; long lValue = 11000000; editorsGeneralNode->PutLong(strKey, lValue); assert(editorsGeneralNode->GetLong(strKey, 0) == lValue); } } -} \ No newline at end of file +} diff --git a/CMake/MITKDashboardSetup.cmake b/CMake/MITKDashboardSetup.cmake index e9ff5a92ff..814e87bdfd 100644 --- a/CMake/MITKDashboardSetup.cmake +++ b/CMake/MITKDashboardSetup.cmake @@ -1,121 +1,125 @@ # 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 "${CMAKE_HOST_SYSTEM}") # Windows 7, Linux-2.6.32, Darwin... site_name(CTEST_SITE) if(QT_BINARY_DIR) set(QT_QMAKE_EXECUTABLE "${QT_BINARY_DIR}/qmake") else() set(QT_QMAKE_EXECUTABLE "qmake") 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}) # # Project specific properties # if(NOT CTEST_BUILD_NAME) set(CTEST_BUILD_NAME "${MY_OPERATING_SYSTEM}-${MY_COMPILER}-Qt-${MY_QT_VERSION}-${CTEST_BUILD_CONFIGURATION}") endif() set(PROJECT_BUILD_DIR "MITK-build") set(CTEST_PATH "$ENV{PATH}") if(WIN32) set(VTK_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/VTK-build/bin/${CTEST_BUILD_CONFIGURATION}") set(ITK_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/ITK-build/bin/${CTEST_BUILD_CONFIGURATION}") set(BOOST_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/Boost-src/stage/lib") set(GDCM_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/GDCM-build/bin/${CTEST_BUILD_CONFIGURATION}") set(OPENCV_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/OpenCV-build/bin/${CTEST_BUILD_CONFIGURATION}") set(BLUEBERRY_OSGI_DIR "${CTEST_BINARY_DIRECTORY}/MITK-build/bin/BlueBerry/org.blueberry.osgi/bin/${CTEST_BUILD_CONFIGURATION}") set(CTEST_PATH "${CTEST_PATH};${QT_BINARY_DIR};${VTK_BINARY_DIR};${ITK_BINARY_DIR};${BOOST_BINARY_DIR};${GDCM_BINARY_DIR};${OPENCV_BINARY_DIR};${BLUEBERRY_OSGI_DIR}") endif() set(ENV{PATH} "${CTEST_PATH}") set(SUPERBUILD_TARGETS "") # 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 "http://git.mitk.org/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(CMAKE_GENERATOR MATCHES "[Mm]ake") set(CTEST_USE_LAUNCHERS 1) else() set(CTEST_USE_LAUNCHERS 0) endif() # 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_USE_Boost) set(MITK_USE_Boost 1) endif() if(NOT DEFINED MITK_USE_OpenCV) set(MITK_USE_OpenCV 1) endif() +if(NOT DEFINED MITK_BUILD_ALL_APPS) + set(MITK_BUILD_ALL_APPS TRUE) +endif() + set(INITIAL_CMAKECACHE_OPTIONS " BLUEBERRY_BUILD_TESTING:BOOL=TRUE BLUEBERRY_BUILD_ALL_PLUGINS:BOOL=TRUE MITK_BUILD_ALL_PLUGINS:BOOL=TRUE -MITK_BUILD_ALL_APPS:BOOL=TRUE +MITK_BUILD_ALL_APPS:BOOL=${MITK_BUILD_ALL_APPS} MITK_BUILD_EXAMPLES:BOOL=TRUE SUPERBUILD_EXCLUDE_MITKBUILD_TARGET:BOOL=TRUE MITK_USE_Boost:BOOL=${MITK_USE_Boost} MITK_USE_OpenCV:BOOL=${MITK_USE_OpenCV} ${ADDITIONAL_CMAKECACHE_OPTION} ") # 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(NOT DEFINED GIT_BRANCH OR GIT_BRANCH STREQUAL "") set(hb "HEAD") else() set(hb "refs/heads/${GIT_BRANCH}") endif() set(url "http://mitk.org/git/?p=MITK.git;a=blob_plain;f=CMake/MITKDashboardDriverScript.cmake;hb=${hb}") set(dest ${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}.driver) downloadFile("${url}" "${dest}") include(${dest}) diff --git a/CMake/mitkFunctionCheckPackageHeader.cmake b/CMake/mitkFunctionCheckPackageHeader.cmake new file mode 100644 index 0000000000..0834326883 --- /dev/null +++ b/CMake/mitkFunctionCheckPackageHeader.cmake @@ -0,0 +1,7 @@ +function(mitkFunctionCheckPackageHeader _header _provider) + find_file(${_header}_FILE ${_header} ${ARGN}) + mark_as_advanced(${_header}_FILE) + if(NOT ${_header}_FILE) + message(FATAL_ERROR "Could not find ${_header} provided by ${_provider}. Please install the missing package.") + endif() +endfunction() diff --git a/CMake/mitkPackageTest.cmake b/CMake/mitkPackageTest.cmake index 7be402234f..793e208208 100644 --- a/CMake/mitkPackageTest.cmake +++ b/CMake/mitkPackageTest.cmake @@ -1,26 +1,26 @@ if(BUILD_TESTING) #package testing if(NOT MITK_FAST_TESTING) # package testing in windows only for release if(WIN32) add_test(NAME mitkPackageTest CONFIGURATIONS Release COMMAND ${CMAKE_COMMAND} --build ${MITK_BINARY_DIR} --config Release --target package) set_tests_properties( mitkPackageTest PROPERTIES - TIMEOUT 3600 + TIMEOUT 6000 LABELS "MITK;MITK-Plugins") elseif(CMAKE_BUILD_TYPE) add_test( NAME mitkPackageTest COMMAND ${CMAKE_COMMAND} --build ${MITK_BINARY_DIR} --config ${CMAKE_BUILD_TYPE} --target package) set_tests_properties( mitkPackageTest PROPERTIES - TIMEOUT 3600 + TIMEOUT 6000 LABELS "MITK;MITK-Plugins" RUN_SERIAL TRUE) endif() endif() # NOT MITK_FAST_TESTING endif(BUILD_TESTING) diff --git a/CMake/mitkTestPluginGenerator.cmake b/CMake/mitkTestPluginGenerator.cmake index ed3dcbbe04..a7e216a0eb 100644 --- a/CMake/mitkTestPluginGenerator.cmake +++ b/CMake/mitkTestPluginGenerator.cmake @@ -1,99 +1,99 @@ if(BUILD_TESTING) set(proj GP) # Means GenerateProject (use a short name due to Windows limitations) set(test_project_out_dir "${MITK_BINARY_DIR}") set(test_project_source_dir "${MITK_BINARY_DIR}/${proj}") set(test_project_binary_dir "${MITK_BINARY_DIR}/${proj}-bin") add_test(NAME mitkPluginGeneratorCleanTest COMMAND ${CMAKE_COMMAND} -E remove_directory "${test_project_source_dir}" ) set_tests_properties(mitkPluginGeneratorCleanTest PROPERTIES LABELS "MITK;BlueBerry") add_test(NAME mitkPluginGeneratorCleanTest2 COMMAND ${CMAKE_COMMAND} -E remove_directory "${test_project_binary_dir}" ) set_tests_properties(mitkPluginGeneratorCleanTest2 PROPERTIES LABELS "MITK;BlueBerry") add_test(NAME mitkPluginGeneratorCleanTest3 COMMAND ${CMAKE_COMMAND} -E make_directory "${test_project_binary_dir}" ) set_tests_properties(mitkPluginGeneratorCleanTest3 PROPERTIES DEPENDS mitkPluginGeneratorCleanTest2 LABELS "MITK;BlueBerry") add_test(NAME mitkPluginGeneratorCreateTest COMMAND ${exec_target} --project-name "${proj}" --project-app-name "TestApp" -ps org.test.plugin -pn "Test Plugin" -vn "Test View" -o ${test_project_out_dir} -y -n ) set_tests_properties(mitkPluginGeneratorCreateTest PROPERTIES DEPENDS "${exec_target};mitkPluginGeneratorCleanTest;mitkPluginGeneratorCleanTest3" LABELS "MITK;BlueBerry") if(CMAKE_CONFIGURATION_TYPES) foreach(config ${CMAKE_CONFIGURATION_TYPES}) add_test(NAME mitkPluginGeneratorConfigureTest-${config} CONFIGURATIONS ${config} WORKING_DIRECTORY "${test_project_binary_dir}" COMMAND ${CMAKE_COMMAND} -D MITK_DIR:PATH=${MITK_BINARY_DIR} -G ${CMAKE_GENERATOR} "${test_project_source_dir}") set_tests_properties(mitkPluginGeneratorConfigureTest-${config} PROPERTIES DEPENDS mitkPluginGeneratorCreateTest LABELS "MITK;BlueBerry") add_test(NAME mitkPluginGeneratorBuildTest-${config} CONFIGURATIONS ${config} COMMAND ${CMAKE_COMMAND} --build ${test_project_binary_dir} --config ${config}) set_tests_properties(mitkPluginGeneratorBuildTest-${config} PROPERTIES DEPENDS mitkPluginGeneratorConfigureTest-${config} LABELS "MITK;BlueBerry") endforeach() else() add_test(NAME mitkPluginGeneratorConfigureTest-${CMAKE_BUILD_TYPE} WORKING_DIRECTORY "${test_project_binary_dir}" COMMAND ${CMAKE_COMMAND} -D MITK_DIR:PATH=${MITK_BINARY_DIR} -D CMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} -G ${CMAKE_GENERATOR} "${test_project_source_dir}") set_tests_properties(mitkPluginGeneratorConfigureTest-${CMAKE_BUILD_TYPE} PROPERTIES DEPENDS mitkPluginGeneratorCreateTest LABELS "MITK;BlueBerry") add_test(NAME mitkPluginGeneratorBuildTest-${CMAKE_BUILD_TYPE} COMMAND ${CMAKE_COMMAND} --build ${test_project_binary_dir} --config ${CMAKE_BUILD_TYPE}) set_tests_properties(mitkPluginGeneratorBuildTest-${CMAKE_BUILD_TYPE} PROPERTIES DEPENDS mitkPluginGeneratorConfigureTest-${CMAKE_BUILD_TYPE} LABELS "MITK;BlueBerry") endif() set(package_test_configurations) if(WIN32) # Only test packaging if build type is "Release" on Windows set(package_test_configurations CONFIGURATIONS Release) endif() if(NOT MITK_FAST_TESTING) if(WIN32) # Only test packaging if build type is "Release" on Windows add_test(NAME mitkPluginGeneratorPackageTest CONFIGURATIONS Release COMMAND ${CMAKE_COMMAND} --build ${test_project_binary_dir}/${proj}-build --config Release --target package) set_tests_properties(mitkPluginGeneratorPackageTest PROPERTIES DEPENDS mitkPluginGeneratorBuildTest-Release - TIMEOUT 3600 + TIMEOUT 6000 LABELS "MITK;BlueBerry") elseif(CMAKE_BUILD_TYPE) add_test(mitkPluginGeneratorPackageTest ${CMAKE_COMMAND} --build ${test_project_binary_dir}/${proj}-build --config ${CMAKE_BUILD_TYPE} --target package) set_tests_properties(mitkPluginGeneratorPackageTest PROPERTIES DEPENDS mitkPluginGeneratorBuildTest-${CMAKE_BUILD_TYPE} - TIMEOUT 3600 + TIMEOUT 6000 LABELS "MITK;BlueBerry") endif() endif() endif() diff --git a/CMake/mitkTestProjectTemplate.cmake b/CMake/mitkTestProjectTemplate.cmake index f74fd8d026..caf70a3dd5 100644 --- a/CMake/mitkTestProjectTemplate.cmake +++ b/CMake/mitkTestProjectTemplate.cmake @@ -1,103 +1,103 @@ if(BUILD_TESTING) include(ExternalProject) set(proj PT) # Means ProjectTemplate (use a short name due to Windows limitations) set(MITK-ProjectTemplate_SOURCE_DIR "${MITK_BINARY_DIR}/${proj}") set(MITK-ProjectTemplate_BINARY_DIR "${MITK_BINARY_DIR}/${proj}-bin") add_test(NAME mitkProjectTemplateRmSrcTest COMMAND ${CMAKE_COMMAND} -E remove_directory "${MITK-ProjectTemplate_SOURCE_DIR}" ) set_tests_properties(mitkProjectTemplateRmSrcTest PROPERTIES LABELS "MITK;BlueBerry") add_test(NAME mitkProjectTemplateRmBinTest COMMAND ${CMAKE_COMMAND} -E remove_directory "${MITK-ProjectTemplate_BINARY_DIR}" ) set_tests_properties(mitkProjectTemplateRmBinTest PROPERTIES LABELS "MITK;BlueBerry") add_test(NAME mitkProjectTemplateMakeBinTest COMMAND ${CMAKE_COMMAND} -E make_directory "${MITK-ProjectTemplate_BINARY_DIR}" ) set_tests_properties(mitkProjectTemplateMakeBinTest PROPERTIES DEPENDS mitkProjectTemplateRmBinTest LABELS "MITK;BlueBerry") add_test(NAME mitkProjectTemplateCloneTest COMMAND ${GIT_EXECUTABLE} clone http://git.mitk.org/MITK-ProjectTemplate.git ${MITK-ProjectTemplate_SOURCE_DIR} ) set_tests_properties(mitkProjectTemplateCloneTest PROPERTIES DEPENDS mitkProjectTemplateRmSrcTest LABELS "MITK;BlueBerry") if(CMAKE_CONFIGURATION_TYPES) foreach(config ${CMAKE_CONFIGURATION_TYPES}) add_test(NAME mitkProjectTemplateConfigureTest-${config} CONFIGURATIONS ${config} WORKING_DIRECTORY "${MITK-ProjectTemplate_BINARY_DIR}" COMMAND ${CMAKE_COMMAND} -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE} -DMITK_DIR:PATH=${MITK_BINARY_DIR} -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} -DCMAKE_GENERATOR=${CMAKE_GENERATOR} -DAwesomeProject_BUILD_ALL_PLUGINS:BOOL=ON -DAwesomeProject_BUILD_ALL_APPS:BOOL=ON "${MITK-ProjectTemplate_SOURCE_DIR}") set_tests_properties(mitkProjectTemplateConfigureTest-${config} PROPERTIES DEPENDS "mitkProjectTemplateCloneTest;mitkProjectTemplateMakeBinTest" LABELS "MITK;BlueBerry") add_test(NAME mitkProjectTemplateBuildTest-${config} CONFIGURATIONS ${config} COMMAND ${CMAKE_COMMAND} --build ${MITK-ProjectTemplate_BINARY_DIR} --config ${config}) set_tests_properties(mitkProjectTemplateBuildTest-${config} PROPERTIES DEPENDS mitkProjectTemplateConfigureTest-${config} LABELS "MITK;BlueBerry") endforeach() else() add_test(NAME mitkProjectTemplateConfigureTest-${CMAKE_BUILD_TYPE} WORKING_DIRECTORY "${MITK-ProjectTemplate_BINARY_DIR}" COMMAND ${CMAKE_COMMAND} -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE} -DMITK_DIR:PATH=${MITK_BINARY_DIR} -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} -DAwesomeProject_BUILD_ALL_PLUGINS:BOOL=ON -DAwesomeProject_BUILD_ALL_APPS:BOOL=ON "${MITK-ProjectTemplate_SOURCE_DIR}") set_tests_properties(mitkProjectTemplateConfigureTest-${CMAKE_BUILD_TYPE} PROPERTIES DEPENDS "mitkProjectTemplateCloneTest;mitkProjectTemplateMakeBinTest" LABELS "MITK;BlueBerry") add_test(NAME mitkProjectTemplateBuildTest-${CMAKE_BUILD_TYPE} COMMAND ${CMAKE_COMMAND} --build ${MITK-ProjectTemplate_BINARY_DIR} --config ${CMAKE_BUILD_TYPE}) set_tests_properties(mitkProjectTemplateBuildTest-${CMAKE_BUILD_TYPE} PROPERTIES DEPENDS mitkProjectTemplateConfigureTest-${CMAKE_BUILD_TYPE} LABELS "MITK;BlueBerry") endif() set(package_test_configurations) if(WIN32) # Only test packaging if build type is "Release" on Windows set(package_test_configurations CONFIGURATIONS Release) endif() if(NOT MITK_FAST_TESTING) if(WIN32) # Only test packaging if build type is "Release" on Windows add_test(NAME mitkProjectTemplatePackageTest CONFIGURATIONS Release COMMAND ${CMAKE_COMMAND} --build ${MITK-ProjectTemplate_BINARY_DIR}/AwesomeProject-build --config Release --target package) set_tests_properties(mitkProjectTemplatePackageTest PROPERTIES DEPENDS mitkProjectTemplateBuildTest-Release - TIMEOUT 3600 + TIMEOUT 6000 LABELS "MITK;BlueBerry") elseif(CMAKE_BUILD_TYPE) add_test(NAME mitkProjectTemplatePackageTest COMMAND ${CMAKE_COMMAND} --build ${MITK-ProjectTemplate_BINARY_DIR}/AwesomeProject-build --config ${CMAKE_BUILD_TYPE} --target package) set_tests_properties(mitkProjectTemplatePackageTest PROPERTIES DEPENDS mitkProjectTemplateBuildTest-${CMAKE_BUILD_TYPE} - TIMEOUT 3600 + TIMEOUT 6000 LABELS "MITK;BlueBerry") endif() endif() endif() diff --git a/CMakeExternals/VTK.cmake b/CMakeExternals/VTK.cmake index 8e95245707..b25a27cd58 100644 --- a/CMakeExternals/VTK.cmake +++ b/CMakeExternals/VTK.cmake @@ -1,94 +1,104 @@ #----------------------------------------------------------------------------- # 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(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() if(MITK_USE_Python) list(APPEND additional_cmake_args -DVTK_WRAP_PYTHON:BOOL=ON -DVTK_USE_TK:BOOL=OFF -DVTK_WINDOWS_PYTHON_DEBUGGABLE:BOOL=OFF ) endif() if(MITK_USE_QT) list(APPEND additional_cmake_args -DDESIRED_QT_VERSION:STRING=4 -DVTK_USE_GUISUPPORT:BOOL=ON -DVTK_USE_QVTK_QTOPENGL:BOOL=ON -DVTK_USE_QT:BOOL=ON -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE} ) endif() - option(MITK_USE_VTK_5_8_IN_SUPERBUILD OFF) + option(MITK_USE_VTK_5_8_IN_SUPERBUILD "Use VTK 5.8 in MITK superbuild" OFF) + + include(mitkFunctionGetGccVersion) + mitkFunctionGetGccVersion(${CMAKE_CXX_COMPILER} GCC_VERSION) + if(GCC_VERSION AND NOT ${GCC_VERSION} VERSION_LESS "4.6") + if(NOT MITK_USE_VTK_5_8_IN_SUPERBUILD) + message("Forcing VTK 5.8 since we're using gcc ${GCC_VERSION}") + endif() + set(MITK_USE_VTK_5_8_IN_SUPERBUILD ON CACHE BOOL "Use VTK 5.8 in MITK superbuild" FORCE) + endif() + if(CMAKE_CXX_COMPILER MATCHES clang) if(NOT MITK_USE_VTK_5_8_IN_SUPERBUILD) - MESSAGE(STATUS "Forcing VTK 5.8 since we're using clang") + message("Forcing VTK 5.8 since we're using clang") endif() - SET(MITK_USE_VTK_5_8_IN_SUPERBUILD ON CACHE BOOL "Use VTK 5.8 in MITK superbuild" FORCE) + set(MITK_USE_VTK_5_8_IN_SUPERBUILD ON CACHE BOOL "Use VTK 5.8 in MITK superbuild" FORCE) endif() if(MITK_USE_VTK_5_8_IN_SUPERBUILD) set(VTK_URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/vtk-5.8.0.tar.gz) set(VTK_URL_MD5 37b7297d02d647cc6ca95b38174cb41f) else() set(VTK_URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/vtk-5.6.1.tar.gz) set(VTK_URL_MD5 b80a76435207c5d0f74dfcab15b75181) endif() ExternalProject_Add(${proj} SOURCE_DIR ${CMAKE_BINARY_DIR}/${proj}-src BINARY_DIR ${proj}-build PREFIX ${proj}-cmake URL ${VTK_URL} URL_MD5 ${VTK_URL_MD5} INSTALL_COMMAND "" CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} -DVTK_WRAP_TCL:BOOL=OFF -DVTK_WRAP_PYTHON:BOOL=OFF -DVTK_WRAP_JAVA:BOOL=OFF -DBUILD_SHARED_LIBS:BOOL=ON -DVTK_USE_PARALLEL:BOOL=ON -DVTK_USE_CHARTS:BOOL=OFF -DVTK_USE_QTCHARTS:BOOL=ON -DVTK_USE_GEOVIS:BOOL=OFF -DVTK_USE_SYSTEM_FREETYPE:BOOL=${VTK_USE_SYSTEM_FREETYPE} -DVTK_USE_QVTK_QTOPENGL:BOOL=OFF -DVTK_LEGACY_REMOVE:BOOL=ON ${additional_cmake_args} DEPENDS ${proj_DEPENDENCIES} ) set(VTK_DIR ${CMAKE_CURRENT_BINARY_DIR}/${proj}-build) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() diff --git a/Core/Code/Algorithms/mitkExtractSliceFilter.h b/Core/Code/Algorithms/mitkExtractSliceFilter.h index 7645d8432a..b2423feaeb 100644 --- a/Core/Code/Algorithms/mitkExtractSliceFilter.h +++ b/Core/Code/Algorithms/mitkExtractSliceFilter.h @@ -1,185 +1,185 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information. =========================================================================*/ #ifndef mitkExtractSliceFilter_h_Included #define mitkExtractSliceFilter_h_Included #include "MitkExports.h" #include "mitkImageToImageFilter.h" #include #include #include #include #include #include #include namespace mitk { /** \brief ExtractSliceFilter extracts a 2D abitrary oriented slice from a 3D volume. The filter can reslice in all orthogonal planes such as sagittal, coronal and transversal, and is also able to reslice a abitrary oriented oblique plane. Curved planes are specified via an AbstractTransformGeometry as the input worldgeometry. The convinient workflow is: 1. Set an image as input. 2. Set the worldGeometry2D. This defines a grid where the slice is being extracted 3. And then start the pipeline. There are a few more properties that can be set to modify the behavior of the slicing. The properties are: - interpolation mode either Nearestneighbor, Linear or Cubic. - a transform this is a convinient way to adapt the reslice axis for the case that the image is transformed e.g. rotated. - time step the time step in a timesliced volume. - resample by geometry wether the resampling grid corresponds to the specs of the worldgeometry or is directly derived from the input image By default the properties are set to: - interpolation mode Nearestneighbor. - a transform NULL (No transform is set). - time step 0. - resample by geometry false (Corresponds to input image). */ class MITK_CORE_EXPORT ExtractSliceFilter : public ImageToImageFilter { public: mitkClassMacro(ExtractSliceFilter, ImageToImageFilter); itkNewMacro(ExtractSliceFilter); mitkNewMacro1Param(Self, vtkImageReslice*); /** \brief Set the axis where to reslice at.*/ void SetWorldGeometry(const Geometry2D* geometry ){ this->m_WorldGeometry = geometry; } /** \brief Set the time step in the 4D volume */ void SetTimeStep( unsigned int timestep){ this->m_TimeStep = timestep; } unsigned int GetTimeStep(){ return this->m_TimeStep; } /** \brief Set a transform for the reslice axes. * This transform is needed if the image volume itself is transformed. (Effects the reslice axis) */ void SetResliceTransformByGeometry(const Geometry3D* transform){ this->m_ResliceTransform = transform; } /** \brief Resampling grid corresponds to: false->image true->worldgeometry*/ void SetInPlaneResampleExtentByGeometry(bool inPlaneResampleExtentByGeometry){ this->m_InPlaneResampleExtentByGeometry = inPlaneResampleExtentByGeometry; } /** \brief Sets the output dimension of the slice*/ void SetOutputDimensionality(unsigned int dimension){ this->m_OutputDimension = dimension; } /** \brief Set the spacing in z direction manually. * Required if the outputDimension is > 2. */ void SetOutputSpacingZDirection(double zSpacing){ this->m_ZSpacing = zSpacing; } /** \brief Set the extent in pixel for direction z manualy. Required if the output dimension is > 2. */ void SetOutputExtentZDirection(int zMin, int zMax) { this->m_ZMin = zMin; this->m_ZMax = zMax; } /** \brief Get the bounding box of the slice [xMin, xMax, yMin, yMax, zMin, zMax] * The method uses the input of the filter to calculate the bounds. * It is recommended to use * GetClippedPlaneBounds(const Geometry3D*, const PlaneGeometry*, vtkFloatingPointType*) * if you are not sure about the input. */ bool GetClippedPlaneBounds(double bounds[6]); /** \brief Get the bounding box of the slice [xMin, xMax, yMin, yMax, zMin, zMax]*/ bool GetClippedPlaneBounds( const Geometry3D *boundingGeometry, const PlaneGeometry *planeGeometry, vtkFloatingPointType *bounds ); /** \brief Get the spacing of the slice. returns mitk::ScalarType[2] */ mitk::ScalarType* GetOutputSpacing(); /** \brief Get Output as vtkImageData. * Note: * SetVtkOutputRequest(true) has to be called at least once before * GetVtkOutput(). Otherwise the output is empty for the first update step. */ vtkImageData* GetVtkOutput(){ m_VtkOutputRequested = true; return m_Reslicer->GetOutput(); } /** Set VtkOutPutRequest to suppress the convertion of the image. * It is suggested to use this with GetVtkOutput(). * Note: * SetVtkOutputRequest(true) has to be called at least once before * GetVtkOutput(). Otherwise the output is empty for the first update step. */ void SetVtkOutputRequest(bool isRequested){ m_VtkOutputRequested = isRequested; } /** \brief Get the reslices axis matrix. * Note: the axis are recalculated when calling SetResliceTransformByGeometry. */ vtkMatrix4x4* GetResliceAxes(){ return this->m_Reslicer->GetResliceAxes(); } enum ResliceInterpolation { RESLICE_NEAREST, RESLICE_LINEAR, RESLICE_CUBIC }; void SetInterpolationMode( ExtractSliceFilter::ResliceInterpolation interpolation){ this->m_InterpolationMode = interpolation; } protected: ExtractSliceFilter(vtkImageReslice* reslicer = NULL); virtual ~ExtractSliceFilter(); virtual void GenerateData(); virtual void GenerateOutputInformation(); virtual void GenerateInputRequestedRegion(); const Geometry2D* m_WorldGeometry; vtkSmartPointer m_Reslicer; unsigned int m_TimeStep; unsigned int m_OutputDimension; double m_ZSpacing; int m_ZMin; int m_ZMax; ResliceInterpolation m_InterpolationMode; const Geometry3D* m_ResliceTransform; bool m_InPlaneResampleExtentByGeometry;//Resampling grid corresponds to: false->image true->worldgeometry mitk::ScalarType* m_OutPutSpacing; bool m_VtkOutputRequested; /** \brief Internal helper method for intersection testing used only in CalculateClippedPlaneBounds() */ bool LineIntersectZero( vtkPoints *points, int p1, int p2, vtkFloatingPointType *bounds ); /** \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. */ bool CalculateClippedPlaneBounds( const Geometry3D *boundingGeometry, const PlaneGeometry *planeGeometry, vtkFloatingPointType *bounds ); }; } -#endif // mitkExtractSliceFilter_h_Included \ No newline at end of file +#endif // mitkExtractSliceFilter_h_Included diff --git a/Core/Code/Algorithms/mitkSurfaceToSurfaceFilter.cpp b/Core/Code/Algorithms/mitkSurfaceToSurfaceFilter.cpp index 4a08e9e4f9..64f43ba622 100644 --- a/Core/Code/Algorithms/mitkSurfaceToSurfaceFilter.cpp +++ b/Core/Code/Algorithms/mitkSurfaceToSurfaceFilter.cpp @@ -1,85 +1,85 @@ /*=================================================================== 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 "mitkSurfaceToSurfaceFilter.h" #include "mitkSurface.h" mitk::SurfaceToSurfaceFilter::SurfaceToSurfaceFilter() : SurfaceSource() { } mitk::SurfaceToSurfaceFilter::~SurfaceToSurfaceFilter() { } void mitk::SurfaceToSurfaceFilter::SetInput( const mitk::Surface* surface ) { this->SetInput( 0, const_cast( surface ) ); } void mitk::SurfaceToSurfaceFilter::SetInput( unsigned int idx, const mitk::Surface* surface ) { if ( this->GetInput(idx) != surface ) { this->SetNthInput( idx, const_cast( surface ) ); this->CreateOutputsForAllInputs(idx); this->Modified(); } } const mitk::Surface* mitk::SurfaceToSurfaceFilter::GetInput() { if (this->GetNumberOfInputs() < 1) return NULL; return static_cast(this->ProcessObject::GetInput(0)); } const mitk::Surface* mitk::SurfaceToSurfaceFilter::GetInput( unsigned int idx) { if (this->GetNumberOfInputs() < 1) return NULL; return static_cast(this->ProcessObject::GetInput(idx)); } void mitk::SurfaceToSurfaceFilter::CreateOutputsForAllInputs(unsigned int /*idx*/) { this->SetNumberOfOutputs( this->GetNumberOfInputs() ); for (unsigned int idx = 0; idx < this->GetNumberOfOutputs(); ++idx) { if (this->GetOutput(idx) == NULL) { DataObjectPointer newOutput = this->MakeOutput(idx); this->SetNthOutput(idx, newOutput); } this->GetOutput( idx )->Graft( this->GetInput( idx) ); } this->Modified(); } void mitk::SurfaceToSurfaceFilter::RemoveInputs(mitk::Surface* input) { this->RemoveInput(input); -} \ No newline at end of file +} diff --git a/Core/Code/DataManagement/mitkCommon.h b/Core/Code/Common/mitkCommon.h similarity index 99% rename from Core/Code/DataManagement/mitkCommon.h rename to Core/Code/Common/mitkCommon.h index ebeeee2e4b..42bbcc65d5 100644 --- a/Core/Code/DataManagement/mitkCommon.h +++ b/Core/Code/Common/mitkCommon.h @@ -1,122 +1,122 @@ /*=================================================================== 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_COMMON_H_DEFINED #define MITK_COMMON_H_DEFINED #ifdef _MSC_VER // This warns about truncation to 255 characters in debug/browse info #pragma warning (disable : 4786) #pragma warning (disable : 4068 ) /* disable unknown pragma warnings */ #endif //add only those headers here that are really necessary for all classes! #include "itkObject.h" #include "mitkConfig.h" #include "mitkLogMacros.h" #include "mitkExportMacros.h" #include "mitkExceptionMacro.h" #ifndef MITK_UNMANGLE_IPPIC #define mitkIpPicDescriptor mitkIpPicDescriptor #endif typedef unsigned int MapperSlotId; #define mitkClassMacro(className,SuperClassName) \ typedef className Self; \ typedef SuperClassName Superclass; \ typedef itk::SmartPointer Pointer; \ typedef itk::SmartPointer ConstPointer; \ itkTypeMacro(className,SuperClassName) /** * Macro for Constructors with one parameter for classes derived from itk::Lightobject **/ #define mitkNewMacro1Param(classname,type) \ static Pointer New(type _arg) \ { \ Pointer smartPtr = new classname ( _arg ); \ smartPtr->UnRegister(); \ return smartPtr; \ } \ /** * Macro for Constructors with two parameters for classes derived from itk::Lightobject **/ #define mitkNewMacro2Param(classname,typea,typeb) \ static Pointer New(typea _arga, typeb _argb) \ { \ Pointer smartPtr = new classname ( _arga, _argb ); \ smartPtr->UnRegister(); \ return smartPtr; \ } \ /** * Macro for Constructors with three parameters for classes derived from itk::Lightobject **/ #define mitkNewMacro3Param(classname,typea,typeb,typec) \ static Pointer New(typea _arga, typeb _argb, typec _argc) \ { \ Pointer smartPtr = new classname ( _arga, _argb, _argc ); \ smartPtr->UnRegister(); \ return smartPtr; \ } \ /** * Macro for Constructors with three parameters for classes derived from itk::Lightobject **/ #define mitkNewMacro4Param(classname,typea,typeb,typec,typed) \ static Pointer New(typea _arga, typeb _argb, typec _argc, typed _argd) \ { \ Pointer smartPtr = new classname ( _arga, _argb, _argc, _argd ); \ smartPtr->UnRegister(); \ return smartPtr; \ } \ /** Get a smart const pointer to an object. Creates the member * Get"name"() (e.g., GetPoints()). */ #define mitkGetObjectMacroConst(name,type) \ virtual type * Get##name () const \ { \ itkDebugMacro("returning " #name " address " << this->m_##name ); \ return this->m_##name.GetPointer(); \ } /** Creates a Clone() method for "Classname". Returns a smartPtr of a clone of the calling object*/ #define mitkCloneMacro(classname) \ virtual Pointer Clone() const \ { \ Pointer smartPtr = new classname(*this); \ smartPtr->UnRegister(); \ return smartPtr; \ } /** cross-platform deprecation macro \todo maybe there is something in external toolkits (ITK, VTK,...) that we could reulse -- would be much preferable */ #ifdef __GNUC__ #define DEPRECATED(func) func __attribute__ ((deprecated)) #elif defined(_MSC_VER) #define DEPRECATED(func) __declspec(deprecated) func #else #pragma message("WARNING: You need to implement DEPRECATED for your compiler!") #define DEPRECATED(func) func #endif -#endif // MITK_COMMON_H_DEFINED \ No newline at end of file +#endif // MITK_COMMON_H_DEFINED diff --git a/Core/Code/Algorithms/mitkCoreObjectFactory.cpp b/Core/Code/Common/mitkCoreObjectFactory.cpp old mode 100755 new mode 100644 similarity index 100% rename from Core/Code/Algorithms/mitkCoreObjectFactory.cpp rename to Core/Code/Common/mitkCoreObjectFactory.cpp diff --git a/Core/Code/Algorithms/mitkCoreObjectFactory.h b/Core/Code/Common/mitkCoreObjectFactory.h old mode 100755 new mode 100644 similarity index 100% rename from Core/Code/Algorithms/mitkCoreObjectFactory.h rename to Core/Code/Common/mitkCoreObjectFactory.h diff --git a/Core/Code/Algorithms/mitkCoreObjectFactoryBase.cpp b/Core/Code/Common/mitkCoreObjectFactoryBase.cpp similarity index 100% rename from Core/Code/Algorithms/mitkCoreObjectFactoryBase.cpp rename to Core/Code/Common/mitkCoreObjectFactoryBase.cpp diff --git a/Core/Code/Algorithms/mitkCoreObjectFactoryBase.h b/Core/Code/Common/mitkCoreObjectFactoryBase.h similarity index 100% rename from Core/Code/Algorithms/mitkCoreObjectFactoryBase.h rename to Core/Code/Common/mitkCoreObjectFactoryBase.h diff --git a/Core/Code/Common/mitkException.cpp b/Core/Code/Common/mitkException.cpp index 150ced1897..26e39bb838 100644 --- a/Core/Code/Common/mitkException.cpp +++ b/Core/Code/Common/mitkException.cpp @@ -1,17 +1,17 @@ /*=================================================================== 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 "mitkException.h" \ No newline at end of file +#include "mitkException.h" diff --git a/Core/Code/Common/mitkExceptionMacro.h b/Core/Code/Common/mitkExceptionMacro.h index 516776c735..cad5321ffa 100644 --- a/Core/Code/Common/mitkExceptionMacro.h +++ b/Core/Code/Common/mitkExceptionMacro.h @@ -1,76 +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_EXCEPTIONMACRO_H_DEFINED #define MITK_EXCEPTIONMACRO_H_DEFINED #include #include #include #include "mitkException.h" /** The exception macro is used to print error information / throw an exception * (i.e., usually a condition that results in program failure). * * Example usage looks like: * mitkThrow() << "this is error info"; */ #define mitkThrow() throw mitk::Exception(__FILE__,__LINE__,"",ITK_LOCATION) /** The specialized exception macro is used to print error information / throw exceptions * in cases of specialized errors. This means the second parameter must be a class which * inherits from mitk::Exception. An object of this exception is thrown when using the macro. * Thus, more differentiated excaptions can be thrown, when needed. * * Example usage: * mitkSpecializedExceptionMacro(mitk::MySpecializedException) << "this is error info"; */ #define mitkThrowException(classname) throw classname(__FILE__,__LINE__,"",ITK_LOCATION) /** Class macro for MITK exception classes. * All MITK exception classes should derive from MITK::Exception. */ #define mitkExceptionClassMacro(ClassName,SuperClassName) \ ClassName(const char *file, unsigned int lineNumber, const char *desc, const char *loc) :\ SuperClassName(file,lineNumber,desc,loc){}\ itkTypeMacro(ClassName, SuperClassName);\ /** \brief Definition of the bit shift operator for this class. It can be used to add messages.*/\ template inline ClassName& operator<<(const T& data)\ {\ std::stringstream ss;\ ss << this->GetDescription() << data;\ this->SetDescription(ss.str());\ return *this;\ }\ /** \brief Definition of the bit shift operator for this class (for non const data).*/\ template inline ClassName& operator<<(T& data)\ {\ std::stringstream ss;\ ss << this->GetDescription() << data;\ this->SetDescription(ss.str());\ return *this;\ }\ /** \brief Definition of the bit shift operator for this class (for functions).*/\ inline ClassName& operator<<(std::ostream& (*func)(std::ostream&))\ {\ std::stringstream ss;\ ss << this->GetDescription() << func;\ this->SetDescription(ss.str());\ return *this;\ }\ -#endif \ No newline at end of file +#endif diff --git a/Core/Code/Controllers/mitkTestingMacros.h b/Core/Code/Common/mitkTestingMacros.h similarity index 100% rename from Core/Code/Controllers/mitkTestingMacros.h rename to Core/Code/Common/mitkTestingMacros.h diff --git a/Core/Code/Controllers/mitkRenderingManager.cpp b/Core/Code/Controllers/mitkRenderingManager.cpp index 17146e6cd4..d7d6fe8fd3 100644 --- a/Core/Code/Controllers/mitkRenderingManager.cpp +++ b/Core/Code/Controllers/mitkRenderingManager.cpp @@ -1,1036 +1,1044 @@ /*=================================================================== 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 "mitkRenderingManager.h" #include "mitkRenderingManagerFactory.h" #include "mitkBaseRenderer.h" #include "mitkGlobalInteraction.h" #include #include #include "mitkVector.h" #include #include #include #include namespace mitk { RenderingManager::Pointer RenderingManager::s_Instance = 0; RenderingManagerFactory *RenderingManager::s_RenderingManagerFactory = 0; RenderingManager ::RenderingManager() : m_UpdatePending( false ), m_MaxLOD( 1 ), m_LODIncreaseBlocked( false ), m_LODAbortMechanismEnabled( false ), m_ClippingPlaneEnabled( false ), m_TimeNavigationController( NULL ), m_DataStorage( NULL ), m_ConstrainedPaddingZooming ( true ) { m_ShadingEnabled.assign( 3, false ); m_ShadingValues.assign( 4, 0.0 ); m_GlobalInteraction = mitk::GlobalInteraction::GetInstance(); InitializePropertyList(); } RenderingManager ::~RenderingManager() { // Decrease reference counts of all registered vtkRenderWindows for // proper destruction RenderWindowVector::iterator it; for ( it = m_AllRenderWindows.begin(); it != m_AllRenderWindows.end(); ++it ) { (*it)->UnRegister( NULL ); RenderWindowCallbacksList::iterator callbacks_it = this->m_RenderWindowCallbacksList.find(*it); - (*it)->RemoveObserver(callbacks_it->second.commands[0u]); - (*it)->RemoveObserver(callbacks_it->second.commands[1u]); - (*it)->RemoveObserver(callbacks_it->second.commands[2u]); + if (callbacks_it != this->m_RenderWindowCallbacksList.end()) + { + (*it)->RemoveObserver(callbacks_it->second.commands[0u]); + (*it)->RemoveObserver(callbacks_it->second.commands[1u]); + (*it)->RemoveObserver(callbacks_it->second.commands[2u]); + } } } void RenderingManager ::SetFactory( RenderingManagerFactory *factory ) { s_RenderingManagerFactory = factory; } const RenderingManagerFactory * RenderingManager ::GetFactory() { return s_RenderingManagerFactory; } bool RenderingManager ::HasFactory() { if ( RenderingManager::s_RenderingManagerFactory ) { return true; } else { return false; } } RenderingManager::Pointer RenderingManager ::New() { const RenderingManagerFactory* factory = GetFactory(); if(factory == NULL) return NULL; return factory->CreateRenderingManager(); } RenderingManager * RenderingManager ::GetInstance() { if ( !RenderingManager::s_Instance ) { if ( s_RenderingManagerFactory ) { s_Instance = s_RenderingManagerFactory->CreateRenderingManager(); } } return s_Instance; } bool RenderingManager ::IsInstantiated() { if ( RenderingManager::s_Instance ) return true; else return false; } void RenderingManager ::AddRenderWindow( vtkRenderWindow *renderWindow ) { if ( renderWindow && (m_RenderWindowList.find( renderWindow ) == m_RenderWindowList.end()) ) { m_RenderWindowList[renderWindow] = RENDERING_INACTIVE; m_AllRenderWindows.push_back( renderWindow ); if ( m_DataStorage.IsNotNull() ) mitk::BaseRenderer::GetInstance( renderWindow )->SetDataStorage( m_DataStorage.GetPointer() ); // Register vtkRenderWindow instance renderWindow->Register( NULL ); typedef itk::MemberCommand< RenderingManager > MemberCommandType; // Add callbacks for rendering abort mechanism //BaseRenderer *renderer = BaseRenderer::GetInstance( renderWindow ); vtkCallbackCommand *startCallbackCommand = vtkCallbackCommand::New(); startCallbackCommand->SetCallback( RenderingManager::RenderingStartCallback ); renderWindow->AddObserver( vtkCommand::StartEvent, startCallbackCommand ); vtkCallbackCommand *progressCallbackCommand = vtkCallbackCommand::New(); progressCallbackCommand->SetCallback( RenderingManager::RenderingProgressCallback ); renderWindow->AddObserver( vtkCommand::AbortCheckEvent, progressCallbackCommand ); vtkCallbackCommand *endCallbackCommand = vtkCallbackCommand::New(); endCallbackCommand->SetCallback( RenderingManager::RenderingEndCallback ); renderWindow->AddObserver( vtkCommand::EndEvent, endCallbackCommand ); RenderWindowCallbacks callbacks; callbacks.commands[0u] = startCallbackCommand; callbacks.commands[1u] = progressCallbackCommand; callbacks.commands[2u] = endCallbackCommand; this->m_RenderWindowCallbacksList[renderWindow] = callbacks; //Delete vtk variables correctly startCallbackCommand->Delete(); progressCallbackCommand->Delete(); endCallbackCommand->Delete(); } } void RenderingManager ::RemoveRenderWindow( vtkRenderWindow *renderWindow ) { if (m_RenderWindowList.erase( renderWindow )) { RenderWindowCallbacksList::iterator callbacks_it = this->m_RenderWindowCallbacksList.find(renderWindow); - - renderWindow->RemoveObserver(callbacks_it->second.commands[0u]); - renderWindow->RemoveObserver(callbacks_it->second.commands[1u]); - renderWindow->RemoveObserver(callbacks_it->second.commands[2u]); - this->m_RenderWindowCallbacksList.erase(callbacks_it); + if(callbacks_it != this->m_RenderWindowCallbacksList.end()) + { + renderWindow->RemoveObserver(callbacks_it->second.commands[0u]); + renderWindow->RemoveObserver(callbacks_it->second.commands[1u]); + renderWindow->RemoveObserver(callbacks_it->second.commands[2u]); + this->m_RenderWindowCallbacksList.erase(callbacks_it); + } RenderWindowVector::iterator rw_it = std::find( m_AllRenderWindows.begin(), m_AllRenderWindows.end(), renderWindow ); - // Decrease reference count for proper destruction - (*rw_it)->UnRegister(NULL); - m_AllRenderWindows.erase( rw_it ); + if(rw_it != m_AllRenderWindows.end()) + { + // Decrease reference count for proper destruction + (*rw_it)->UnRegister(NULL); + m_AllRenderWindows.erase( rw_it ); + } } } const RenderingManager::RenderWindowVector& RenderingManager ::GetAllRegisteredRenderWindows() { return m_AllRenderWindows; } void RenderingManager ::RequestUpdate( vtkRenderWindow *renderWindow ) { // If the renderWindow is not valid, we do not want to inadvertantly create // an entry in the m_RenderWindowList map. It is possible if the user is // regularly calling AddRenderer and RemoveRenderer for a rendering update // to come into this method with a renderWindow pointer that is valid in the // sense that the window does exist within the application, but that // renderWindow has been temporarily removed from this RenderingManager for // performance reasons. if (m_RenderWindowList.find( renderWindow ) == m_RenderWindowList.end()) { return; } m_RenderWindowList[renderWindow] = RENDERING_REQUESTED; if ( !m_UpdatePending ) { m_UpdatePending = true; this->GenerateRenderingRequestEvent(); } } void RenderingManager ::ForceImmediateUpdate( vtkRenderWindow *renderWindow ) { // If the renderWindow is not valid, we do not want to inadvertantly create // an entry in the m_RenderWindowList map. It is possible if the user is // regularly calling AddRenderer and RemoveRenderer for a rendering update // to come into this method with a renderWindow pointer that is valid in the // sense that the window does exist within the application, but that // renderWindow has been temporarily removed from this RenderingManager for // performance reasons. if (m_RenderWindowList.find( renderWindow ) == m_RenderWindowList.end()) { return; } // Erase potentially pending requests for this window m_RenderWindowList[renderWindow] = RENDERING_INACTIVE; m_UpdatePending = false; // Immediately repaint this window (implementation platform specific) // If the size is 0 it crahses int *size = renderWindow->GetSize(); if ( 0 != size[0] && 0 != size[1] ) { //prepare the camera etc. before rendering //Note: this is a very important step which should be called before the VTK render! //If you modify the camera anywhere else or after the render call, the scene cannot be seen. mitk::VtkPropRenderer *vPR = dynamic_cast(mitk::BaseRenderer::GetInstance( renderWindow )); if(vPR) vPR->PrepareRender(); // Execute rendering renderWindow->Render(); } } void RenderingManager ::RequestUpdateAll( RequestType type ) { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { int id = BaseRenderer::GetInstance(it->first)->GetMapperID(); if ( (type == REQUEST_UPDATE_ALL) || ((type == REQUEST_UPDATE_2DWINDOWS) && (id == 1)) || ((type == REQUEST_UPDATE_3DWINDOWS) && (id == 2)) ) { this->RequestUpdate( it->first ); } } } void RenderingManager ::ForceImmediateUpdateAll( RequestType type ) { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { int id = BaseRenderer::GetInstance(it->first)->GetMapperID(); if ( (type == REQUEST_UPDATE_ALL) || ((type == REQUEST_UPDATE_2DWINDOWS) && (id == 1)) || ((type == REQUEST_UPDATE_3DWINDOWS) && (id == 2)) ) { // Immediately repaint this window (implementation platform specific) // If the size is 0, it crashes this->ForceImmediateUpdate(it->first); // int *size = it->first->GetSize(); // if ( 0 != size[0] && 0 != size[1] ) // { // //prepare the camera before rendering // //Note: this is a very important step which should be called before the VTK render! // //If you modify the camera anywhere else or after the render call, the scene cannot be seen. // mitk::VtkPropRenderer *vPR = // dynamic_cast(mitk::BaseRenderer::GetInstance( it->first )); // if(vPR) // vPR->PrepareRender(); // // Execute rendering // it->first->Render(); // } // it->second = RENDERING_INACTIVE; } } //m_UpdatePending = false; } //bool RenderingManager::InitializeViews( const mitk::DataStorage * storage, const DataNode* node = NULL, RequestType type, bool preserveRoughOrientationInWorldSpace ) //{ // mitk::Geometry3D::Pointer geometry; // if ( storage != NULL ) // { // geometry = storage->ComputeVisibleBoundingGeometry3D(node, "visible", NULL, "includeInBoundingBox" ); // // if ( geometry.IsNotNull() ) // { // // let's see if we have data with a limited live-span ... // mitk::TimeBounds timebounds = geometry->GetTimeBounds(); // if ( timebounds[1] < mitk::ScalarTypeNumericTraits::max() ) // { // mitk::ScalarType duration = timebounds[1]-timebounds[0]; // // mitk::TimeSlicedGeometry::Pointer timegeometry = // mitk::TimeSlicedGeometry::New(); // timegeometry->InitializeEvenlyTimed( // geometry, (unsigned int) duration ); // timegeometry->SetTimeBounds( timebounds ); // // timebounds[1] = timebounds[0] + 1.0; // geometry->SetTimeBounds( timebounds ); // // geometry = timegeometry; // } // } // } // // // Use geometry for initialization // return this->InitializeViews( geometry.GetPointer(), type ); //} bool RenderingManager ::InitializeViews( const Geometry3D * dataGeometry, RequestType type, bool preserveRoughOrientationInWorldSpace ) { MITK_DEBUG << "initializing views"; bool boundingBoxInitialized = false; Geometry3D::ConstPointer geometry = dataGeometry; if (dataGeometry && preserveRoughOrientationInWorldSpace) { // clone the input geometry Geometry3D::Pointer modifiedGeometry = dynamic_cast( dataGeometry->Clone().GetPointer() ); assert(modifiedGeometry.IsNotNull()); // construct an affine transform from it AffineGeometryFrame3D::TransformType::Pointer transform = AffineGeometryFrame3D::TransformType::New(); assert( modifiedGeometry->GetIndexToWorldTransform() ); transform->SetMatrix( modifiedGeometry->GetIndexToWorldTransform()->GetMatrix() ); transform->SetOffset( modifiedGeometry->GetIndexToWorldTransform()->GetOffset() ); // get transform matrix AffineGeometryFrame3D::TransformType::MatrixType::InternalMatrixType& oldMatrix = const_cast< AffineGeometryFrame3D::TransformType::MatrixType::InternalMatrixType& > ( transform->GetMatrix().GetVnlMatrix() ); AffineGeometryFrame3D::TransformType::MatrixType::InternalMatrixType newMatrix(oldMatrix); // get offset and bound Vector3D offset = modifiedGeometry->GetIndexToWorldTransform()->GetOffset(); Geometry3D::BoundsArrayType oldBounds = modifiedGeometry->GetBounds(); Geometry3D::BoundsArrayType newBounds = modifiedGeometry->GetBounds(); // get rid of rotation other than pi/2 degree for ( unsigned int i = 0; i < 3; ++i ) { // i-th column of the direction matrix Vector3D currentVector; currentVector[0] = oldMatrix(0,i); currentVector[1] = oldMatrix(1,i); currentVector[2] = oldMatrix(2,i); // matchingRow will store the row that holds the biggest // value in the column unsigned int matchingRow = 0; // maximum value in the column float max = std::numeric_limits::min(); // sign of the maximum value (-1 or 1) int sign = 1; // iterate through the column vector for (unsigned int dim = 0; dim < 3; ++dim) { if ( fabs(currentVector[dim]) > max ) { matchingRow = dim; max = fabs(currentVector[dim]); if(currentVector[dim]<0) sign = -1; else sign = 1; } } // in case we found a negative maximum, // we negate the column and adjust the offset // (in order to run through the dimension in the opposite direction) if(sign == -1) { currentVector *= sign; offset += modifiedGeometry->GetAxisVector(i); } // matchingRow is now used as column index to place currentVector // correctly in the new matrix vnl_vector newMatrixColumn(3); newMatrixColumn[0] = currentVector[0]; newMatrixColumn[1] = currentVector[1]; newMatrixColumn[2] = currentVector[2]; newMatrix.set_column( matchingRow, newMatrixColumn ); // if a column is moved, we also have to adjust the bounding // box accordingly, this is done here newBounds[2*matchingRow ] = oldBounds[2*i ]; newBounds[2*matchingRow+1] = oldBounds[2*i+1]; } // set the newly calculated bounds array modifiedGeometry->SetBounds(newBounds); // set new offset and direction matrix AffineGeometryFrame3D::TransformType::MatrixType newMatrixITK( newMatrix ); transform->SetMatrix( newMatrixITK ); transform->SetOffset( offset ); modifiedGeometry->SetIndexToWorldTransform( transform ); geometry = modifiedGeometry; } int warningLevel = vtkObject::GetGlobalWarningDisplay(); vtkObject::GlobalWarningDisplayOff(); if ( (geometry.IsNotNull() ) && (const_cast< mitk::BoundingBox * >( geometry->GetBoundingBox())->GetDiagonalLength2() > mitk::eps) ) { boundingBoxInitialized = true; } if (geometry.IsNotNull() ) {// make sure bounding box has an extent bigger than zero in any direction // clone the input geometry Geometry3D::Pointer modifiedGeometry = dynamic_cast( dataGeometry->Clone().GetPointer() ); assert(modifiedGeometry.IsNotNull()); Geometry3D::BoundsArrayType newBounds = modifiedGeometry->GetBounds(); for( unsigned int dimension = 0; ( 2 * dimension ) < newBounds.Size() ; dimension++ ) { //check for equality but for an epsilon if( Equal( newBounds[ 2 * dimension ], newBounds[ 2 * dimension + 1 ] ) ) { newBounds[ 2 * dimension + 1 ] += 1; } } // set the newly calculated bounds array modifiedGeometry->SetBounds(newBounds); geometry = modifiedGeometry; } RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { mitk::BaseRenderer *baseRenderer = mitk::BaseRenderer::GetInstance( it->first ); baseRenderer->GetDisplayGeometry()->SetConstrainZoomingAndPanning(m_ConstrainedPaddingZooming); int id = baseRenderer->GetMapperID(); if ( ((type == REQUEST_UPDATE_ALL) || ((type == REQUEST_UPDATE_2DWINDOWS) && (id == 1)) || ((type == REQUEST_UPDATE_3DWINDOWS) && (id == 2))) ) { this->InternalViewInitialization( baseRenderer, geometry, boundingBoxInitialized, id ); } } if ( m_TimeNavigationController != NULL ) { if ( boundingBoxInitialized ) { m_TimeNavigationController->SetInputWorldGeometry( geometry ); } m_TimeNavigationController->Update(); } this->RequestUpdateAll( type ); vtkObject::SetGlobalWarningDisplay( warningLevel ); // Inform listeners that views have been initialized this->InvokeEvent( mitk::RenderingManagerViewsInitializedEvent() ); return boundingBoxInitialized; } bool RenderingManager ::InitializeViews( RequestType type ) { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { mitk::BaseRenderer *baseRenderer = mitk::BaseRenderer::GetInstance( it->first ); int id = baseRenderer->GetMapperID(); if ( (type == REQUEST_UPDATE_ALL) || ((type == REQUEST_UPDATE_2DWINDOWS) && (id == 1)) || ((type == REQUEST_UPDATE_3DWINDOWS) && (id == 2)) ) { mitk::SliceNavigationController *nc = baseRenderer->GetSliceNavigationController(); // Re-initialize view direction nc->SetViewDirectionToDefault(); // Update the SNC nc->Update(); } } this->RequestUpdateAll( type ); return true; } //bool RenderingManager::InitializeView( vtkRenderWindow * renderWindow, const DataStorage* ds, const DataNode node = NULL, bool initializeGlobalTimeSNC ) //{ // mitk::Geometry3D::Pointer geometry; // if ( ds != NULL ) // { // geometry = ds->ComputeVisibleBoundingGeometry3D(node, NULL, "includeInBoundingBox" ); // // if ( geometry.IsNotNull() ) // { // // let's see if we have data with a limited live-span ... // mitk::TimeBounds timebounds = geometry->GetTimeBounds(); // if ( timebounds[1] < mitk::ScalarTypeNumericTraits::max() ) // { // mitk::ScalarType duration = timebounds[1]-timebounds[0]; // // mitk::TimeSlicedGeometry::Pointer timegeometry = // mitk::TimeSlicedGeometry::New(); // timegeometry->InitializeEvenlyTimed( // geometry, (unsigned int) duration ); // timegeometry->SetTimeBounds( timebounds ); // // timebounds[1] = timebounds[0] + 1.0; // geometry->SetTimeBounds( timebounds ); // // geometry = timegeometry; // } // } // } // // // Use geometry for initialization // return this->InitializeView( renderWindow, // geometry.GetPointer(), initializeGlobalTimeSNC ); //} bool RenderingManager::InitializeView( vtkRenderWindow * renderWindow, const Geometry3D * geometry, bool initializeGlobalTimeSNC ) { bool boundingBoxInitialized = false; int warningLevel = vtkObject::GetGlobalWarningDisplay(); vtkObject::GlobalWarningDisplayOff(); if ( (geometry != NULL ) && (const_cast< mitk::BoundingBox * >( geometry->GetBoundingBox())->GetDiagonalLength2() > mitk::eps) ) { boundingBoxInitialized = true; } mitk::BaseRenderer *baseRenderer = mitk::BaseRenderer::GetInstance( renderWindow ); int id = baseRenderer->GetMapperID(); this->InternalViewInitialization( baseRenderer, geometry, boundingBoxInitialized, id ); if ( m_TimeNavigationController != NULL ) { if ( boundingBoxInitialized && initializeGlobalTimeSNC ) { m_TimeNavigationController->SetInputWorldGeometry( geometry ); } m_TimeNavigationController->Update(); } this->RequestUpdate( renderWindow ); vtkObject::SetGlobalWarningDisplay( warningLevel ); return boundingBoxInitialized; } bool RenderingManager::InitializeView( vtkRenderWindow * renderWindow ) { mitk::BaseRenderer *baseRenderer = mitk::BaseRenderer::GetInstance( renderWindow ); mitk::SliceNavigationController *nc = baseRenderer->GetSliceNavigationController(); // Re-initialize view direction nc->SetViewDirectionToDefault(); // Update the SNC nc->Update(); this->RequestUpdate( renderWindow ); return true; } void RenderingManager::InternalViewInitialization(mitk::BaseRenderer *baseRenderer, const mitk::Geometry3D *geometry, bool boundingBoxInitialized, int mapperID ) { mitk::SliceNavigationController *nc = baseRenderer->GetSliceNavigationController(); // Re-initialize view direction nc->SetViewDirectionToDefault(); if ( boundingBoxInitialized ) { // Set geometry for NC nc->SetInputWorldGeometry( geometry ); nc->Update(); if ( mapperID == 1 ) { // For 2D SNCs, steppers are set so that the cross is centered // in the image nc->GetSlice()->SetPos( nc->GetSlice()->GetSteps() / 2 ); } // Fit the render window DisplayGeometry baseRenderer->GetDisplayGeometry()->Fit(); baseRenderer->GetCameraController()->SetViewToAnterior(); } else { nc->Update(); } } void RenderingManager::SetTimeNavigationController( SliceNavigationController *nc ) { m_TimeNavigationController = nc; } const SliceNavigationController* RenderingManager::GetTimeNavigationController() const { return m_TimeNavigationController; } SliceNavigationController* RenderingManager::GetTimeNavigationController() { return m_TimeNavigationController; } void RenderingManager::ExecutePendingRequests() { m_UpdatePending = false; // Satisfy all pending update requests RenderWindowList::iterator it; int i = 0; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it, ++i ) { if ( it->second == RENDERING_REQUESTED ) { this->ForceImmediateUpdate( it->first ); } } } void RenderingManager::RenderingStartCallback( vtkObject *caller, unsigned long , void *, void * ) { vtkRenderWindow *renderWindow = dynamic_cast< vtkRenderWindow * >( caller ); mitk::RenderingManager* renman = mitk::BaseRenderer::GetInstance(renderWindow)->GetRenderingManager(); RenderWindowList &renderWindowList = renman->m_RenderWindowList; if ( renderWindow ) { renderWindowList[renderWindow] = RENDERING_INPROGRESS; } renman->m_UpdatePending = false; } void RenderingManager ::RenderingProgressCallback( vtkObject *caller, unsigned long , void *, void * ) { vtkRenderWindow *renderWindow = dynamic_cast< vtkRenderWindow * >( caller ); mitk::RenderingManager* renman = mitk::BaseRenderer::GetInstance(renderWindow)->GetRenderingManager(); if ( renman->m_LODAbortMechanismEnabled ) { vtkRenderWindow *renderWindow = dynamic_cast< vtkRenderWindow * >( caller ); if ( renderWindow ) { BaseRenderer *renderer = BaseRenderer::GetInstance( renderWindow ); if ( renderer && (renderer->GetNumberOfVisibleLODEnabledMappers() > 0) ) { renman->DoMonitorRendering(); } } } } void RenderingManager ::RenderingEndCallback( vtkObject *caller, unsigned long , void *, void * ) { vtkRenderWindow *renderWindow = dynamic_cast< vtkRenderWindow * >( caller ); mitk::RenderingManager* renman = mitk::BaseRenderer::GetInstance(renderWindow)->GetRenderingManager(); RenderWindowList &renderWindowList = renman->m_RenderWindowList; RendererIntMap &nextLODMap = renman->m_NextLODMap; if ( renderWindow ) { BaseRenderer *renderer = BaseRenderer::GetInstance( renderWindow ); if ( renderer ) { renderWindowList[renderer->GetRenderWindow()] = RENDERING_INACTIVE; // Level-of-Detail handling if ( renderer->GetNumberOfVisibleLODEnabledMappers() > 0 ) { if(nextLODMap[renderer]==0) renman->StartOrResetTimer(); else nextLODMap[renderer] = 0; } } } } bool RenderingManager ::IsRendering() const { RenderWindowList::const_iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { if ( it->second == RENDERING_INPROGRESS ) { return true; } } return false; } void RenderingManager ::AbortRendering() { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { if ( it->second == RENDERING_INPROGRESS ) { it->first->SetAbortRender( true ); m_RenderingAbortedMap[BaseRenderer::GetInstance(it->first)] = true; } } } int RenderingManager ::GetNextLOD( BaseRenderer *renderer ) { if ( renderer != NULL ) { return m_NextLODMap[renderer]; } else { return 0; } } void RenderingManager ::ExecutePendingHighResRenderingRequest() { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { BaseRenderer *renderer = BaseRenderer::GetInstance( it->first ); if(renderer->GetNumberOfVisibleLODEnabledMappers()>0) { if(m_NextLODMap[renderer]==0) { m_NextLODMap[renderer]=1; RequestUpdate( it->first ); } } } } void RenderingManager ::SetMaximumLOD( unsigned int max ) { m_MaxLOD = max; } //enable/disable shading void RenderingManager ::SetShading(bool state, unsigned int lod) { if(lod>m_MaxLOD) { itkWarningMacro(<<"LOD out of range requested: " << lod << " maxLOD: " << m_MaxLOD); return; } m_ShadingEnabled[lod] = state; } bool RenderingManager ::GetShading(unsigned int lod) { if(lod>m_MaxLOD) { itkWarningMacro(<<"LOD out of range requested: " << lod << " maxLOD: " << m_MaxLOD); return false; } return m_ShadingEnabled[lod]; } //enable/disable the clipping plane void RenderingManager ::SetClippingPlaneStatus(bool status) { m_ClippingPlaneEnabled = status; } bool RenderingManager ::GetClippingPlaneStatus() { return m_ClippingPlaneEnabled; } void RenderingManager ::SetShadingValues(float ambient, float diffuse, float specular, float specpower) { m_ShadingValues[0] = ambient; m_ShadingValues[1] = diffuse; m_ShadingValues[2] = specular; m_ShadingValues[3] = specpower; } RenderingManager::FloatVector & RenderingManager ::GetShadingValues() { return m_ShadingValues; } void RenderingManager::SetDepthPeelingEnabled( bool enabled ) { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { mitk::BaseRenderer *baseRenderer = mitk::BaseRenderer::GetInstance( it->first ); baseRenderer->SetDepthPeelingEnabled(enabled); } } void RenderingManager::SetMaxNumberOfPeels( int maxNumber ) { RenderWindowList::iterator it; for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it ) { mitk::BaseRenderer *baseRenderer = mitk::BaseRenderer::GetInstance( it->first ); baseRenderer->SetMaxNumberOfPeels(maxNumber); } } void RenderingManager::InitializePropertyList() { if (m_PropertyList.IsNull()) { m_PropertyList = PropertyList::New(); } this->SetProperty("coupled-zoom", BoolProperty::New(false)); this->SetProperty("coupled-plane-rotation", BoolProperty::New(false)); this->SetProperty("MIP-slice-rendering", BoolProperty::New(false)); } PropertyList::Pointer RenderingManager::GetPropertyList() const { return m_PropertyList; } BaseProperty* RenderingManager::GetProperty(const char *propertyKey) const { return m_PropertyList->GetProperty(propertyKey); } void RenderingManager::SetProperty(const char *propertyKey, BaseProperty* propertyValue) { m_PropertyList->SetProperty(propertyKey, propertyValue); } void RenderingManager::SetDataStorage( DataStorage* storage ) { if ( storage != NULL ) { m_DataStorage = storage; RenderingManager::RenderWindowVector::iterator iter; for ( iter = m_AllRenderWindows.begin(); iterSetDataStorage( m_DataStorage.GetPointer() ); } } } mitk::DataStorage* RenderingManager::GetDataStorage() { return m_DataStorage; } void RenderingManager::SetGlobalInteraction( mitk::GlobalInteraction* globalInteraction ) { if ( globalInteraction != NULL ) { m_GlobalInteraction = globalInteraction; } } mitk::GlobalInteraction* RenderingManager::GetGlobalInteraction() { return m_GlobalInteraction; } // Create and register generic RenderingManagerFactory. TestingRenderingManagerFactory renderingManagerFactory; } // namespace diff --git a/Core/Code/DataManagement/mitkBaseDataTestImplementation.h b/Core/Code/DataManagement/mitkBaseDataTestImplementation.h index e3a24e0ac4..390021489e 100644 --- a/Core/Code/DataManagement/mitkBaseDataTestImplementation.h +++ b/Core/Code/DataManagement/mitkBaseDataTestImplementation.h @@ -1,59 +1,59 @@ /*=================================================================== 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 BASEDATAIMPLEMENTATION_H_HEADER_INCLUDED #define BASEDATAIMPLEMENTATION_H_HEADER_INCLUDED #include "mitkBaseData.h" namespace mitk { //##Documentation //## @brief Implementation of BaseData (for testing) //## //## As BaseData is an abstract class, we need an implementation for testing its methods //## @ingroup Data class BaseDataTestImplementation : public BaseData { public: mitkClassMacro(BaseDataTestImplementation, BaseData); itkNewMacro(Self); mitkCloneMacro(BaseDataTestImplementation); virtual void InitializeTimeSlicedGeometry( unsigned int timeSteps /* = 1 */ ) { Superclass::InitializeTimeSlicedGeometry(timeSteps); } protected: virtual bool VerifyRequestedRegion(){return false;}; virtual bool RequestedRegionIsOutsideOfTheBufferedRegion(){return false;}; virtual void SetRequestedRegionToLargestPossibleRegion(){}; virtual void SetRequestedRegion(itk::DataObject * /*data*/){}; BaseDataTestImplementation(){}; virtual ~BaseDataTestImplementation(){}; }; } // namespace -#endif // BASEDATA_H_HEADER_INCLUDED \ No newline at end of file +#endif // BASEDATA_H_HEADER_INCLUDED diff --git a/Core/Code/Algorithms/mitkDataNodeFactory.cpp b/Core/Code/DataManagement/mitkDataNodeFactory.cpp similarity index 100% rename from Core/Code/Algorithms/mitkDataNodeFactory.cpp rename to Core/Code/DataManagement/mitkDataNodeFactory.cpp diff --git a/Core/Code/Algorithms/mitkDataNodeFactory.h b/Core/Code/DataManagement/mitkDataNodeFactory.h similarity index 100% rename from Core/Code/Algorithms/mitkDataNodeFactory.h rename to Core/Code/DataManagement/mitkDataNodeFactory.h diff --git a/Core/Code/Algorithms/mitkITKImageImport.h b/Core/Code/DataManagement/mitkITKImageImport.h similarity index 100% rename from Core/Code/Algorithms/mitkITKImageImport.h rename to Core/Code/DataManagement/mitkITKImageImport.h diff --git a/Core/Code/Algorithms/mitkITKImageImport.txx b/Core/Code/DataManagement/mitkITKImageImport.txx similarity index 100% rename from Core/Code/Algorithms/mitkITKImageImport.txx rename to Core/Code/DataManagement/mitkITKImageImport.txx diff --git a/Core/Code/Algorithms/mitkImageAccessByItk.h b/Core/Code/DataManagement/mitkImageAccessByItk.h similarity index 100% rename from Core/Code/Algorithms/mitkImageAccessByItk.h rename to Core/Code/DataManagement/mitkImageAccessByItk.h diff --git a/Core/Code/Algorithms/mitkImageCast.h b/Core/Code/DataManagement/mitkImageCast.h similarity index 100% rename from Core/Code/Algorithms/mitkImageCast.h rename to Core/Code/DataManagement/mitkImageCast.h diff --git a/Core/Code/Algorithms/mitkImageCastPart1.cpp b/Core/Code/DataManagement/mitkImageCastPart1.cpp similarity index 100% rename from Core/Code/Algorithms/mitkImageCastPart1.cpp rename to Core/Code/DataManagement/mitkImageCastPart1.cpp diff --git a/Core/Code/Algorithms/mitkImageCastPart2.cpp b/Core/Code/DataManagement/mitkImageCastPart2.cpp similarity index 100% rename from Core/Code/Algorithms/mitkImageCastPart2.cpp rename to Core/Code/DataManagement/mitkImageCastPart2.cpp diff --git a/Core/Code/Algorithms/mitkImageCastPart3.cpp b/Core/Code/DataManagement/mitkImageCastPart3.cpp similarity index 100% rename from Core/Code/Algorithms/mitkImageCastPart3.cpp rename to Core/Code/DataManagement/mitkImageCastPart3.cpp diff --git a/Core/Code/Algorithms/mitkImageCastPart4.cpp b/Core/Code/DataManagement/mitkImageCastPart4.cpp similarity index 100% rename from Core/Code/Algorithms/mitkImageCastPart4.cpp rename to Core/Code/DataManagement/mitkImageCastPart4.cpp diff --git a/Core/Code/Algorithms/mitkImageCaster.cpp b/Core/Code/DataManagement/mitkImageCaster.cpp similarity index 100% rename from Core/Code/Algorithms/mitkImageCaster.cpp rename to Core/Code/DataManagement/mitkImageCaster.cpp diff --git a/Core/Code/Algorithms/mitkImageCaster.h b/Core/Code/DataManagement/mitkImageCaster.h similarity index 100% rename from Core/Code/Algorithms/mitkImageCaster.h rename to Core/Code/DataManagement/mitkImageCaster.h diff --git a/Core/Code/Algorithms/mitkImageToItk.h b/Core/Code/DataManagement/mitkImageToItk.h similarity index 100% rename from Core/Code/Algorithms/mitkImageToItk.h rename to Core/Code/DataManagement/mitkImageToItk.h diff --git a/Core/Code/Algorithms/mitkImageToItk.txx b/Core/Code/DataManagement/mitkImageToItk.txx similarity index 100% rename from Core/Code/Algorithms/mitkImageToItk.txx rename to Core/Code/DataManagement/mitkImageToItk.txx diff --git a/Core/Code/Rendering/mitkVtkEventProvider.cpp b/Core/Code/Rendering/mitkVtkEventProvider.cpp index 2a5b4b62d7..6062f885b5 100644 --- a/Core/Code/Rendering/mitkVtkEventProvider.cpp +++ b/Core/Code/Rendering/mitkVtkEventProvider.cpp @@ -1,248 +1,248 @@ /*=================================================================== 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 "mitkVtkEventProvider.h" #include "mitkVtkEventAdapter.h" #include #include #include #include #include #define VTKEVENTPROVIDER_INFO MBI_INFO("mitk.core.vtkeventprovider") #define VTKEVENTPROVIDER_WARN MBI_WARN("mitk.core.vtkeventprovider") #define VTKEVENTPROVIDER_ERROR MBI_ERROR("mitk.core.vtkeventprovider") #define VTKEVENTPROVIDER_DEBUG MBI_DEBUG("mitk.core.vtkeventprovider") namespace mitk { vtkCxxRevisionMacro(vtkEventProvider, "$Revision: 1.18 $"); vtkStandardNewMacro(vtkEventProvider); } //---------------------------------------------------------------------------- mitk::vtkEventProvider::vtkEventProvider() { // priority of the observer/command; we want MITK events processed in the very beginning this->Priority = 99999.99; //take over the processing of delete and keypress events from the superclass this->EventCallbackCommand->SetCallback( vtkEventProvider::ProcessEvents); // Set/Get the passive observer flag. If this is set to true, this // indicates that this command does not change the state of the // system in any way. Passive observers are processed first, and // are not called even when another command has focus. this->EventCallbackCommand->SetPassiveObserver(1); // get events first // mouse move AddInteractionEvent(vtkCommand::MouseMoveEvent); // mouse press AddInteractionEvent(vtkCommand::LeftButtonPressEvent); AddInteractionEvent(vtkCommand::MiddleButtonPressEvent); AddInteractionEvent(vtkCommand::RightButtonPressEvent); // mouse release AddInteractionEvent(vtkCommand::LeftButtonReleaseEvent); AddInteractionEvent(vtkCommand::MiddleButtonReleaseEvent); AddInteractionEvent(vtkCommand::RightButtonReleaseEvent); // wheel event AddInteractionEvent(vtkCommand::MouseWheelBackwardEvent); AddInteractionEvent(vtkCommand::MouseWheelForwardEvent); // key press event AddInteractionEvent(vtkCommand::KeyPressEvent); } mitk::vtkEventProvider::~vtkEventProvider() { this->SetInteractor(0); } void mitk::vtkEventProvider::SetMitkRenderWindow(mitk::RenderWindow* renWin) { m_RenderWindow = renWin; } mitk::RenderWindow* mitk::vtkEventProvider::GetRenderWindow() { return m_RenderWindow; } void mitk::vtkEventProvider::SetEnabled(int enabling) { if ( ! this->Interactor ) { VTKEVENTPROVIDER_ERROR <<"The interactor must be set prior to enabling/disabling widget"; return; } if ( enabling ) //---------------------------------------------------------- { VTKEVENTPROVIDER_DEBUG << "Enabling widget"; if ( this->Enabled ) //already enabled, just return { return; } this->Enabled = 1; // listen to all event types specified in m_InteractionEventsVector vtkRenderWindowInteractor *i = this->Interactor; InteractionEventsVectorType::iterator it; for(it = m_InteractionEventsVector.begin(); it != m_InteractionEventsVector.end(); it++) { // add observer to interactorStyle i->GetInteractorStyle()->AddObserver((vtkCommand::EventIds) (*it), this->EventCallbackCommand, this->Priority); } this->InvokeEvent(vtkCommand::EnableEvent,NULL); } else //disabling----------------------------------------------------------- { VTKEVENTPROVIDER_DEBUG <<"Disabling widget"; if ( ! this->Enabled ) //already disabled, just return { return; } this->Enabled = 0; // don't listen for events any more this->Interactor->RemoveObserver(this->EventCallbackCommand); //this->Interactor->HandleEventLoop = 0; this->InvokeEvent(vtkCommand::DisableEvent,NULL); } } //---------------------------------------------------------------------------- // This adds the keypress event observer and the delete event observer void mitk::vtkEventProvider::SetInteractor(vtkRenderWindowInteractor* i) { if (i == this->Interactor) { return; } // if we already have an Interactor then stop observing it if (this->Interactor) this->SetEnabled(0); //disable the old interactor this->Interactor = i; this->Modified(); } //---------------------------------------------------------------------------- void mitk::vtkEventProvider::ProcessEvents(vtkObject* object, unsigned long event, void* clientData, void* vtkNotUsed(callData)) { vtkEventProvider* self = reinterpret_cast( clientData ); vtkRenderWindowInteractor* rwi = static_cast( object )->GetInteractor(); // base renderer mitk::BaseRenderer* baseRenderer = mitk::BaseRenderer::GetInstance(self->GetRenderWindow()->GetVtkRenderWindow()); switch(event) { // key press case vtkCommand::KeyPressEvent: { VTKEVENTPROVIDER_DEBUG << "key press event"; mitk::KeyEvent mke(mitk::VtkEventAdapter::AdaptKeyEvent(baseRenderer,event,rwi)); self->GetRenderWindow()->keyPressMitkEvent(&mke); break; } // mouse events case vtkCommand::MouseMoveEvent: { VTKEVENTPROVIDER_DEBUG << "mouse move event"; mitk::MouseEvent me(mitk::VtkEventAdapter::AdaptMouseEvent(baseRenderer,event,rwi)); self->GetRenderWindow()->mouseMoveMitkEvent(&me); break; } case vtkCommand::LeftButtonPressEvent: case vtkCommand::MiddleButtonPressEvent: case vtkCommand::RightButtonPressEvent: { VTKEVENTPROVIDER_DEBUG << "mouse press event"; mitk::MouseEvent me(mitk::VtkEventAdapter::AdaptMouseEvent(baseRenderer,event,rwi)); self->GetRenderWindow()->mousePressMitkEvent(&me); break; } case vtkCommand::LeftButtonReleaseEvent: case vtkCommand::MiddleButtonReleaseEvent: case vtkCommand::RightButtonReleaseEvent: { VTKEVENTPROVIDER_DEBUG << "mouse release event"; mitk::MouseEvent me(mitk::VtkEventAdapter::AdaptMouseEvent(baseRenderer,event,rwi)); self->GetRenderWindow()->mouseReleaseMitkEvent(&me); break; } // mouse WHEEL case vtkCommand::MouseWheelForwardEvent: case vtkCommand::MouseWheelBackwardEvent: { VTKEVENTPROVIDER_DEBUG << "mouse wheel event"; mitk::WheelEvent we(mitk::VtkEventAdapter::AdaptWheelEvent(baseRenderer,event,rwi)); self->GetRenderWindow()->wheelMitkEvent(&we); break; } default: VTKEVENTPROVIDER_INFO << "VTK event not mapped properly."; break; } } void mitk::vtkEventProvider::RemoveInteractionEvent(unsigned long ievent) { InteractionEventsVectorType::iterator it; if(m_InteractionEventsVector.size() > 0) { it = std::find(m_InteractionEventsVector.begin(),m_InteractionEventsVector.end(),ievent); if(it != m_InteractionEventsVector.end()) { m_InteractionEventsVector.erase(it); return; } } } void mitk::vtkEventProvider::AddInteractionEvent(unsigned long ievent) { // Remove event if it already exists RemoveInteractionEvent(ievent); m_InteractionEventsVector.push_back(ievent); -} \ No newline at end of file +} diff --git a/Core/Code/Testing/files.cmake b/Core/Code/Testing/files.cmake index 8f24b6f0bc..059107ca32 100644 --- a/Core/Code/Testing/files.cmake +++ b/Core/Code/Testing/files.cmake @@ -1,113 +1,114 @@ + # tests with no extra command line parameter set(MODULE_TESTS mitkAccessByItkTest.cpp mitkCoreObjectFactoryTest.cpp mitkMaterialTest.cpp mitkActionTest.cpp mitkEnumerationPropertyTest.cpp mitkEventTest.cpp mitkFocusManagerTest.cpp mitkGenericPropertyTest.cpp mitkGeometry3DTest.cpp mitkGeometryDataToSurfaceFilterTest.cpp mitkGlobalInteractionTest.cpp mitkImageDataItemTest.cpp #mitkImageMapper2DTest.cpp mitkImageGeneratorTest.cpp mitkBaseDataTest.cpp #mitkImageToItkTest.cpp mitkInstantiateAccessFunctionTest.cpp mitkInteractorTest.cpp mitkITKThreadingTest.cpp # mitkLevelWindowManagerTest.cpp mitkLevelWindowTest.cpp mitkMessageTest.cpp #mitkPipelineSmartPointerCorrectnessTest.cpp mitkPixelTypeTest.cpp mitkPlaneGeometryTest.cpp mitkPointSetFileIOTest.cpp mitkPointSetTest.cpp mitkPointSetWriterTest.cpp mitkPointSetReaderTest.cpp mitkPointSetInteractorTest.cpp mitkPropertyTest.cpp mitkPropertyListTest.cpp #mitkRegistrationBaseTest.cpp #mitkSegmentationInterpolationTest.cpp mitkSlicedGeometry3DTest.cpp mitkSliceNavigationControllerTest.cpp mitkStateMachineTest.cpp mitkStateTest.cpp mitkSurfaceTest.cpp mitkSurfaceToSurfaceFilterTest.cpp mitkTimeSlicedGeometryTest.cpp mitkTransitionTest.cpp mitkUndoControllerTest.cpp mitkVtkWidgetRenderingTest.cpp mitkVerboseLimitedLinearUndoTest.cpp mitkWeakPointerTest.cpp mitkTransferFunctionTest.cpp #mitkAbstractTransformGeometryTest.cpp mitkStepperTest.cpp itkTotalVariationDenoisingImageFilterTest.cpp mitkRenderingManagerTest.cpp vtkMitkThickSlicesFilterTest.cpp mitkNodePredicateSourceTest.cpp mitkVectorTest.cpp mitkClippedSurfaceBoundsCalculatorTest.cpp #QmitkRenderingTestHelper.cpp mitkExceptionTest.cpp mitkExtractSliceFilterTest.cpp ) # test with image filename as an extra command line parameter set(MODULE_IMAGE_TESTS mitkPlanePositionManagerTest.cpp mitkSurfaceVtkWriterTest.cpp #mitkImageSliceSelectorTest.cpp mitkImageTimeSelectorTest.cpp # mitkVtkPropRendererTest.cpp mitkDataNodeFactoryTest.cpp #mitkSTLFileReaderTest.cpp ) # list of images for which the tests are run set(MODULE_TESTIMAGES # Pic-Factory no more available in Core, test images now in .nrrd format US4DCyl.nrrd Pic3D.nrrd Pic2DplusT.nrrd BallBinary30x30x30.nrrd binary.stl ball.stl ) set(MODULE_CUSTOM_TESTS #mitkLabeledImageToSurfaceFilterTest.cpp #mitkExternalToolsTest.cpp mitkDataStorageTest.cpp mitkDataNodeTest.cpp mitkDicomSeriesReaderTest.cpp mitkDICOMLocaleTest.cpp mitkEventMapperTest.cpp mitkNodeDependentPointSetInteractorTest.cpp mitkStateMachineFactoryTest.cpp mitkPointSetLocaleTest.cpp mitkImageTest.cpp mitkImageWriterTest.cpp mitkImageVtkMapper2DTest.cpp mitkImageVtkMapper2DLevelWindowTest.cpp mitkImageVtkMapper2DOpacityTest.cpp mitkImageVtkMapper2DColorTest.cpp ) # Create an artificial module initializing class for # the usServiceListenerTest.cpp usFunctionGenerateModuleInit(testdriver_init_file NAME ${MODULE_NAME}TestDriver DEPENDS "Mitk" VERSION "0.1.0" EXECUTABLE ) set(TEST_CPP_FILES ${testdriver_init_file} mitkRenderingTestHelper.cpp) diff --git a/Core/Code/Testing/mitkExceptionTest.cpp b/Core/Code/Testing/mitkExceptionTest.cpp index 4101f85cd0..825595a898 100644 --- a/Core/Code/Testing/mitkExceptionTest.cpp +++ b/Core/Code/Testing/mitkExceptionTest.cpp @@ -1,222 +1,222 @@ /*=================================================================== 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 "mitkExceptionMacro.h" #include "mitkTestingMacros.h" #include #include #include class SpecializedTestException : public mitk::Exception { public: mitkExceptionClassMacro(SpecializedTestException,mitk::Exception); }; class ExceptionTestClass : public itk::Object { public: mitkClassMacro( ExceptionTestClass , itk::Object ); itkNewMacro(Self); void throwExceptionManually() //this method is ONLY to test the constructor and no code example //normally exceptions should only be thrown by using the exception macro! { throw mitk::Exception("test.cpp",155,"",""); } void throwSpecializedExceptionManually() //this method is ONLY to test the constructor and no code example //normally exceptions should only be thrown by using the exception macro! { throw SpecializedTestException("test.cpp",155,"",""); } void throwExceptionManually(std::string message1, std::string message2) //this method is ONLY to test methods of mitk::Exception and no code example //normally exceptions should only be thrown by using the exception macro! { throw mitk::Exception("testfile.cpp",155,message1.c_str(),"") << message2; } void throwExceptionWithThrowMacro() { mitkThrow()<<"TEST EXCEPION THROWING WITH mitkThrow()"; } void throwExceptionWithThrowMacro(std::string message) { mitkThrow()<throwExceptionManually(); } catch(mitk::Exception) { exceptionThrown = true; } MITK_TEST_CONDITION_REQUIRED(exceptionThrown,"Testing constructor of mitkException"); exceptionThrown = false; try { myExceptionTestObject->throwSpecializedExceptionManually(); } catch(SpecializedTestException) { exceptionThrown = true; } MITK_TEST_CONDITION_REQUIRED(exceptionThrown,"Testing constructor specialized exception (deriving from mitkException)"); } static void TestExceptionMessageStream() { //##### this method is ONLY to test the streaming operators of the exceptions and //##### NO code example. Please do not instantiate exceptions by yourself in normal code! //##### Normally exceptions should only be thrown by using the exception macro! mitk::Exception myException = mitk::Exception("testfile.cpp",111,"testmessage"); myException << " and additional stream"; MITK_TEST_CONDITION_REQUIRED(myException.GetDescription() == std::string("testmessage and additional stream"),"Testing mitkException message stream (adding std::string)"); myException.SetDescription("testmessage2"); myException << ' ' << 'a' << 'n' << 'd' << ' ' << 'c' << 'h' << 'a' << 'r' << 's'; MITK_TEST_CONDITION_REQUIRED(myException.GetDescription() == std::string("testmessage2 and chars"),"Testing mitkException message stream (adding single chars)"); myException.SetDescription("testmessage3"); myException << myException; //adding the object itself makes no sense but should work MITK_TEST_CONDITION_REQUIRED(myException.GetDescription() != std::string(""),"Testing mitkException message stream (adding object)"); SpecializedTestException mySpecializedException = SpecializedTestException("testfile.cpp",111,"testmessage","test"); mySpecializedException << " and additional stream"; MITK_TEST_CONDITION_REQUIRED(mySpecializedException.GetDescription() == std::string("testmessage and additional stream"),"Testing specialized exception message stream (adding std::string)"); } static void TestExceptionMessageStreamThrowing() { bool exceptionThrown = false; ExceptionTestClass::Pointer myExceptionTestObject = ExceptionTestClass::New(); std::string thrownMessage = ""; try { myExceptionTestObject->throwExceptionManually("message1"," and message2"); } catch(mitk::Exception e) { thrownMessage = e.GetDescription(); exceptionThrown = true; } MITK_TEST_CONDITION_REQUIRED(exceptionThrown && (thrownMessage == std::string("message1 and message2")),"Testing throwing and streaming of mitk::Exception together.") } static void TestMitkThrowMacro() { bool exceptionThrown = false; ExceptionTestClass::Pointer myExceptionTestObject = ExceptionTestClass::New(); //case 1: test throwing try { myExceptionTestObject->throwExceptionWithThrowMacro(); } catch(mitk::Exception) { exceptionThrown = true; } MITK_TEST_CONDITION_REQUIRED(exceptionThrown,"Testing mitkThrow()"); //case 2: test message text exceptionThrown = false; std::string messageText = ""; try { myExceptionTestObject->throwExceptionWithThrowMacro("test123"); } catch(mitk::Exception e) { exceptionThrown = true; messageText = e.GetDescription(); } MITK_TEST_CONDITION_REQUIRED((exceptionThrown && (messageText=="test123")),"Testing message test of mitkThrow()"); //case 3: specialized exception / command mitkThrow(mitk::Exception) exceptionThrown = false; messageText = ""; try { myExceptionTestObject->throwSpecializedExceptionWithThrowMacro("test123"); } catch(mitk::Exception e) { exceptionThrown = true; messageText = e.GetDescription(); } MITK_TEST_CONDITION_REQUIRED(exceptionThrown && messageText=="test123","Testing special exception with mitkThrow(mitk::Exception)"); //case 4: specialized exception / command mitkThrow(mitk::SpecializedException) exceptionThrown = false; messageText = ""; try { myExceptionTestObject->throwSpecializedExceptionWithThrowMacro2("test123"); } catch(SpecializedTestException e) { exceptionThrown = true; messageText = e.GetDescription(); } MITK_TEST_CONDITION_REQUIRED(exceptionThrown && messageText=="test123","Testing special exception with mitkThrow(mitk::SpecializedException)"); } }; int mitkExceptionTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN("MITKException"); ExceptionTestClass::TestExceptionConstructor(); ExceptionTestClass::TestExceptionMessageStream(); ExceptionTestClass::TestExceptionMessageStreamThrowing(); ExceptionTestClass::TestMitkThrowMacro(); MITK_TEST_END(); -} \ No newline at end of file +} diff --git a/Core/Code/Testing/mitkFocusManagerTest.cpp b/Core/Code/Testing/mitkFocusManagerTest.cpp index 56b9412be1..8699ea78fa 100644 --- a/Core/Code/Testing/mitkFocusManagerTest.cpp +++ b/Core/Code/Testing/mitkFocusManagerTest.cpp @@ -1,91 +1,91 @@ /*=================================================================== 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 "mitkFocusManager.h" #include "mitkTestingMacros.h" #include "mitkVtkPropRenderer.h" #include "mitkGlobalInteraction.h" int mitkFocusManagerTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN("FocusManager"); // Global interaction must(!) be initialized if used mitk::GlobalInteraction::GetInstance()->Initialize("global"); mitk::RenderingManager::Pointer rm = mitk::RenderingManager::GetInstance(); //building up necessary objects vtkRenderWindow* renderWindow = vtkRenderWindow::New(); mitk::VtkPropRenderer::Pointer element1 = mitk::VtkPropRenderer::New( "renderer1", renderWindow, rm ); mitk::VtkPropRenderer::Pointer element2 = mitk::VtkPropRenderer::New( "renderer2", renderWindow, rm ); mitk::VtkPropRenderer::Pointer element3 = mitk::VtkPropRenderer::New( "renderer3", renderWindow, rm ); //the FocusManager itself mitk::FocusManager::Pointer focusManager = mitk::FocusManager::New(); //testing MITK_TEST_CONDITION_REQUIRED(focusManager.IsNotNull(), "Testing Instatiation"); MITK_TEST_CONDITION_REQUIRED(element1.IsNotNull(), "Testing Instatiation of an element"); MITK_TEST_CONDITION_REQUIRED(focusManager->AddElement(element1), "Testing addition of an element"); MITK_TEST_CONDITION_REQUIRED(focusManager->GetFocused() == element1, "Testing if the added element is focused on"); MITK_TEST_CONDITION_REQUIRED(focusManager->RemoveElement(element1), "Testing removing of an element"); MITK_TEST_CONDITION_REQUIRED(focusManager->GetFocused() == NULL, "Testing focused on an empty list"); MITK_TEST_CONDITION_REQUIRED(focusManager->AddElement(element1), "Testing addition of an element; Elements in list: 1"); MITK_TEST_CONDITION_REQUIRED(focusManager->AddElement(element2), "Testing addition of a second element; Elements in list: 1 2"); MITK_TEST_CONDITION_REQUIRED(focusManager->GetFocused() == element1, "Testing if the added element still is element 1"); MITK_TEST_CONDITION_REQUIRED(focusManager->AddElement(element3), "Testing addition of a third element; Elements in list: 1 2 3"); MITK_TEST_CONDITION_REQUIRED(focusManager->GetFocused() == element1, "Testing if the added element still is element 1"); MITK_TEST_CONDITION_REQUIRED(focusManager->SetFocused(element1), "Testing setting focused to element 1"); MITK_TEST_CONDITION_REQUIRED(focusManager->GetFocused() == element1, "focus on element 1"); MITK_TEST_CONDITION_REQUIRED(focusManager->SetFocused(element2), "Testing setting focused to element 2"); MITK_TEST_CONDITION_REQUIRED(focusManager->GetFocused() == element2, "focus on element 2"); MITK_TEST_CONDITION_REQUIRED(focusManager->SetFocused(element3), "Testing setting focused to element 3"); MITK_TEST_CONDITION_REQUIRED(focusManager->GetFocused() == element3, "focus on element 3"); MITK_TEST_CONDITION_REQUIRED(focusManager->RemoveElement(element1), "Testing removing first element; Elements in list: 2 3"); MITK_TEST_CONDITION_REQUIRED(focusManager->GetFocused() == element2, "Testing if focused element is the one behind the deleted one: 2"); MITK_TEST_CONDITION_REQUIRED(focusManager->AddElement(element1), "Testing addition of an element again; Elements in list: 2 3 1"); MITK_TEST_CONDITION_REQUIRED(focusManager->RemoveElement(element3), "Testing removing element 3; Elements in list: 2 1"); MITK_TEST_CONDITION_REQUIRED(focusManager->GetFocused() == element1, "Testing if focused element is the one behind the deleted one: 1"); MITK_TEST_CONDITION_REQUIRED(focusManager->RemoveElement(element1), "Testing removing last element 1; Elements in list: 2 "); MITK_TEST_CONDITION_REQUIRED(focusManager->GetFocused() == element2, "Testing if focused element is 2"); MITK_TEST_CONDITION_REQUIRED(!focusManager->RemoveElement(element1), "Testing removing same element"); MITK_TEST_CONDITION_REQUIRED(focusManager->RemoveElement(element2), "Testing removing last element in list (2)"); MITK_TEST_CONDITION_REQUIRED(!focusManager->RemoveElement(element3), "Testing removing from empty list "); MITK_TEST_CONDITION_REQUIRED(!focusManager->RemoveElement(element2), "Testing removing from empty list with different object"); MITK_TEST_CONDITION_REQUIRED(!focusManager->RemoveElement(element1), "Testing removing from empty list with different object again"); focusManager = NULL; //TODO: test IsLast() IsFirst() GetFirst() GetLast() GoToNext() GetIter() SetLoop(bool loop) //Delete renderWindo correctly renderWindow->Delete(); MITK_TEST_END(); -} \ No newline at end of file +} diff --git a/Core/Code/Testing/mitkNodePredicateSourceTest.cpp b/Core/Code/Testing/mitkNodePredicateSourceTest.cpp index 92130cfbac..13fea04668 100644 --- a/Core/Code/Testing/mitkNodePredicateSourceTest.cpp +++ b/Core/Code/Testing/mitkNodePredicateSourceTest.cpp @@ -1,51 +1,51 @@ /*=================================================================== 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 "mitkNodePredicateSource.h" #include "mitkTestingMacros.h" #include "mitkStandaloneDataStorage.h" int mitkNodePredicateSourceTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("Testing nodePredicateSource") // Create a DataStorage mitk::DataStorage::Pointer myDataStorage(mitk::StandaloneDataStorage::New().GetPointer()); mitk::DataNode::Pointer godfather, grandMother, mother, daughter; godfather = mitk::DataNode::New(); grandMother = mitk::DataNode::New(); mother = mitk::DataNode::New(); daughter = mitk::DataNode::New(); myDataStorage->Add(godfather); myDataStorage->Add(grandMother); myDataStorage->Add(mother, grandMother); myDataStorage->Add(daughter, mother); mitk::NodePredicateSource::Pointer testPredicate = mitk::NodePredicateSource::New(grandMother, false, myDataStorage); ; MITK_TEST_CONDITION_REQUIRED(true, "Testing instantiation"); MITK_TEST_CONDITION_REQUIRED(testPredicate->CheckNode(mother), "Node is derivative"); MITK_TEST_CONDITION_REQUIRED(!testPredicate->CheckNode(godfather), "Node is not derivative"); MITK_TEST_CONDITION_REQUIRED(!testPredicate->CheckNode(daughter), "Node is derivative but only direct derivatives are wanted"); testPredicate = NULL; testPredicate = mitk::NodePredicateSource::New(grandMother, true, myDataStorage); MITK_TEST_CONDITION_REQUIRED(testPredicate->CheckNode(daughter), "Node is not direct derivative and all derivatives are wanted "); MITK_TEST_CONDITION_REQUIRED(!testPredicate->CheckNode(grandMother), "Self is not a derivative!"); MITK_TEST_END(); - } \ No newline at end of file + } diff --git a/Core/Code/Testing/mitkRegistrationBaseTest.cpp b/Core/Code/Testing/mitkRegistrationBaseTest.cpp index 6478c091b8..751945f59a 100644 --- a/Core/Code/Testing/mitkRegistrationBaseTest.cpp +++ b/Core/Code/Testing/mitkRegistrationBaseTest.cpp @@ -1,48 +1,48 @@ /*=================================================================== 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 "mitkImage.h" #include "mitkRegistrationBase.h" int mitkRegistrationBaseTest(int /*argc*/, char* /*argv*/[]) { //Create Image out of nowhere mitk::Image::Pointer image; mitk::PixelType pt(typeid(int)); unsigned int dim[]={100,100,20}; std::cout << "Creating image: "; image = mitk::Image::New(); //image->DebugOn(); image->Initialize(mitk::PixelType(typeid(int)), 3, dim); int *p = (int*)image->GetData(); int size = dim[0]*dim[1]*dim[2]; int i; for(i=0; iSetReferenceImage(image); std::cout<<"[PASSED]"< #include - +/** Documentation + * @brief This template is used to test the C++ micro services in MITK. + */ template<> inline const char* us_service_impl_name(itk::LightObject* impl) { return impl->GetNameOfClass(); } #endif // USERVICESBASEOBJECT_H diff --git a/Core/Code/files.cmake b/Core/Code/files.cmake index d2d4b34679..fd463e7704 100644 --- a/Core/Code/files.cmake +++ b/Core/Code/files.cmake @@ -1,302 +1,302 @@ set(H_FILES Algorithms/itkImportMitkImageContainer.h Algorithms/itkImportMitkImageContainer.txx Algorithms/itkLocalVariationImageFilter.h Algorithms/itkLocalVariationImageFilter.txx Algorithms/itkMITKScalarImageToHistogramGenerator.h Algorithms/itkMITKScalarImageToHistogramGenerator.txx Algorithms/itkTotalVariationDenoisingImageFilter.h Algorithms/itkTotalVariationDenoisingImageFilter.txx Algorithms/itkTotalVariationSingleIterationImageFilter.h Algorithms/itkTotalVariationSingleIterationImageFilter.txx Algorithms/mitkBilateralFilter.h Algorithms/mitkBilateralFilter.cpp - - Algorithms/mitkImageAccessByItk.h - Algorithms/mitkImageCast.h - Algorithms/mitkImageToItk.h - Algorithms/mitkImageToItk.txx Algorithms/mitkInstantiateAccessFunctions.h - Algorithms/mitkITKImageImport.h - Algorithms/mitkITKImageImport.txx Algorithms/mitkPixelTypeList.h - # Preprocessor macros taken from Boost Algorithms/mitkPPArithmeticDec.h Algorithms/mitkPPArgCount.h Algorithms/mitkPPCat.h Algorithms/mitkPPConfig.h Algorithms/mitkPPControlExprIIf.h Algorithms/mitkPPControlIf.h Algorithms/mitkPPControlIIf.h Algorithms/mitkPPDebugError.h Algorithms/mitkPPDetailAutoRec.h Algorithms/mitkPPDetailDMCAutoRec.h Algorithms/mitkPPExpand.h Algorithms/mitkPPFacilitiesEmpty.h Algorithms/mitkPPFacilitiesExpand.h Algorithms/mitkPPLogicalBool.h Algorithms/mitkPPRepetitionDetailDMCFor.h Algorithms/mitkPPRepetitionDetailEDGFor.h Algorithms/mitkPPRepetitionDetailFor.h Algorithms/mitkPPRepetitionDetailMSVCFor.h Algorithms/mitkPPRepetitionFor.h Algorithms/mitkPPSeqElem.h Algorithms/mitkPPSeqForEach.h Algorithms/mitkPPSeqForEachProduct.h Algorithms/mitkPPSeq.h Algorithms/mitkPPSeqEnum.h Algorithms/mitkPPSeqSize.h Algorithms/mitkPPSeqToTuple.h Algorithms/mitkPPStringize.h Algorithms/mitkPPTupleEat.h Algorithms/mitkPPTupleElem.h Algorithms/mitkPPTupleRem.h Algorithms/mitkClippedSurfaceBoundsCalculator.h Algorithms/mitkExtractSliceFilter.h + DataManagement/mitkImageAccessByItk.h + DataManagement/mitkImageCast.h + DataManagement/mitkITKImageImport.h + DataManagement/mitkITKImageImport.txx + DataManagement/mitkImageToItk.h + DataManagement/mitkImageToItk.txx + Interfaces/mitkIDataNodeReader.h - + IO/mitkPixelTypeTraits.h - - DataManagement/mitkCommon.h + Interactions/mitkEventMapperAddOn.h - + Common/mitkExceptionMacro.h + Common/mitkTestingMacros.h ) set(CPP_FILES Algorithms/mitkBaseDataSource.cpp Algorithms/mitkBaseProcess.cpp - Algorithms/mitkCoreObjectFactoryBase.cpp - Algorithms/mitkCoreObjectFactory.cpp - Algorithms/mitkDataNodeFactory.cpp Algorithms/mitkDataNodeSource.cpp Algorithms/mitkGeometry2DDataToSurfaceFilter.cpp Algorithms/mitkHistogramGenerator.cpp - Algorithms/mitkImageCaster.cpp - Algorithms/mitkImageCastPart1.cpp - Algorithms/mitkImageCastPart2.cpp - Algorithms/mitkImageCastPart3.cpp - Algorithms/mitkImageCastPart4.cpp Algorithms/mitkImageChannelSelector.cpp Algorithms/mitkImageSliceSelector.cpp Algorithms/mitkImageSource.cpp Algorithms/mitkImageTimeSelector.cpp Algorithms/mitkImageToImageFilter.cpp Algorithms/mitkPointSetSource.cpp Algorithms/mitkPointSetToPointSetFilter.cpp Algorithms/mitkRGBToRGBACastImageFilter.cpp Algorithms/mitkSubImageSelector.cpp Algorithms/mitkSurfaceSource.cpp Algorithms/mitkSurfaceToSurfaceFilter.cpp Algorithms/mitkUIDGenerator.cpp Algorithms/mitkVolumeCalculator.cpp Algorithms/mitkClippedSurfaceBoundsCalculator.cpp Algorithms/mitkExtractSliceFilter.cpp Controllers/mitkBaseController.cpp Controllers/mitkCallbackFromGUIThread.cpp Controllers/mitkCameraController.cpp Controllers/mitkCameraRotationController.cpp Controllers/mitkCoreActivator.cpp Controllers/mitkFocusManager.cpp Controllers/mitkLimitedLinearUndo.cpp Controllers/mitkOperationEvent.cpp Controllers/mitkPlanePositionManager.cpp Controllers/mitkProgressBar.cpp Controllers/mitkRenderingManager.cpp Controllers/mitkSliceNavigationController.cpp Controllers/mitkSlicesCoordinator.cpp Controllers/mitkSlicesRotator.cpp Controllers/mitkSlicesSwiveller.cpp Controllers/mitkStatusBar.cpp Controllers/mitkStepper.cpp Controllers/mitkTestManager.cpp Controllers/mitkUndoController.cpp Controllers/mitkVerboseLimitedLinearUndo.cpp Controllers/mitkVtkInteractorCameraController.cpp Controllers/mitkVtkLayerController.cpp DataManagement/mitkAbstractTransformGeometry.cpp DataManagement/mitkAnnotationProperty.cpp DataManagement/mitkApplicationCursor.cpp DataManagement/mitkBaseData.cpp DataManagement/mitkBaseProperty.cpp DataManagement/mitkClippingProperty.cpp DataManagement/mitkChannelDescriptor.cpp DataManagement/mitkColorProperty.cpp DataManagement/mitkDataStorage.cpp #DataManagement/mitkDataTree.cpp DataManagement/mitkDataNode.cpp + DataManagement/mitkDataNodeFactory.cpp #DataManagement/mitkDataTreeStorage.cpp DataManagement/mitkDisplayGeometry.cpp DataManagement/mitkEnumerationProperty.cpp DataManagement/mitkGeometry2D.cpp DataManagement/mitkGeometry2DData.cpp DataManagement/mitkGeometry3D.cpp DataManagement/mitkGeometryData.cpp DataManagement/mitkGroupTagProperty.cpp DataManagement/mitkImage.cpp + DataManagement/mitkImageCaster.cpp + DataManagement/mitkImageCastPart1.cpp + DataManagement/mitkImageCastPart2.cpp + DataManagement/mitkImageCastPart3.cpp + DataManagement/mitkImageCastPart4.cpp DataManagement/mitkImageDataItem.cpp DataManagement/mitkImageDescriptor.cpp DataManagement/mitkImageStatisticsHolder.cpp DataManagement/mitkLandmarkBasedCurvedGeometry.cpp DataManagement/mitkLandmarkProjectorBasedCurvedGeometry.cpp DataManagement/mitkLandmarkProjector.cpp DataManagement/mitkLevelWindow.cpp DataManagement/mitkLevelWindowManager.cpp DataManagement/mitkLevelWindowPreset.cpp DataManagement/mitkLevelWindowProperty.cpp DataManagement/mitkLookupTable.cpp DataManagement/mitkLookupTables.cpp # specializations of GenericLookupTable DataManagement/mitkMemoryUtilities.cpp DataManagement/mitkModalityProperty.cpp DataManagement/mitkModeOperation.cpp DataManagement/mitkNodePredicateAnd.cpp DataManagement/mitkNodePredicateBase.cpp DataManagement/mitkNodePredicateCompositeBase.cpp DataManagement/mitkNodePredicateData.cpp DataManagement/mitkNodePredicateDataType.cpp DataManagement/mitkNodePredicateDimension.cpp DataManagement/mitkNodePredicateFirstLevel.cpp DataManagement/mitkNodePredicateNot.cpp DataManagement/mitkNodePredicateOr.cpp DataManagement/mitkNodePredicateProperty.cpp DataManagement/mitkNodePredicateSource.cpp DataManagement/mitkPlaneOrientationProperty.cpp DataManagement/mitkPlaneGeometry.cpp DataManagement/mitkPlaneOperation.cpp DataManagement/mitkPointOperation.cpp DataManagement/mitkPointSet.cpp DataManagement/mitkProperties.cpp DataManagement/mitkPropertyList.cpp DataManagement/mitkRestorePlanePositionOperation.cpp DataManagement/mitkRotationOperation.cpp DataManagement/mitkSlicedData.cpp DataManagement/mitkSlicedGeometry3D.cpp DataManagement/mitkSmartPointerProperty.cpp DataManagement/mitkStandaloneDataStorage.cpp DataManagement/mitkStateTransitionOperation.cpp DataManagement/mitkStringProperty.cpp DataManagement/mitkSurface.cpp DataManagement/mitkSurfaceOperation.cpp DataManagement/mitkThinPlateSplineCurvedGeometry.cpp DataManagement/mitkTimeSlicedGeometry.cpp DataManagement/mitkTransferFunction.cpp DataManagement/mitkTransferFunctionProperty.cpp DataManagement/mitkTransferFunctionInitializer.cpp DataManagement/mitkVector.cpp DataManagement/mitkVtkInterpolationProperty.cpp DataManagement/mitkVtkRepresentationProperty.cpp DataManagement/mitkVtkResliceInterpolationProperty.cpp DataManagement/mitkVtkScalarModeProperty.cpp DataManagement/mitkVtkVolumeRenderingProperty.cpp DataManagement/mitkWeakPointerProperty.cpp DataManagement/mitkShaderProperty.cpp DataManagement/mitkResliceMethodProperty.cpp DataManagement/mitkMaterial.cpp Interactions/mitkAction.cpp Interactions/mitkAffineInteractor.cpp Interactions/mitkCoordinateSupplier.cpp Interactions/mitkDisplayCoordinateOperation.cpp Interactions/mitkDisplayInteractor.cpp Interactions/mitkDisplayPositionEvent.cpp Interactions/mitkDisplayVectorInteractor.cpp Interactions/mitkDisplayVectorInteractorLevelWindow.cpp Interactions/mitkDisplayVectorInteractorScroll.cpp Interactions/mitkEvent.cpp Interactions/mitkEventDescription.cpp Interactions/mitkEventMapper.cpp Interactions/mitkGlobalInteraction.cpp Interactions/mitkInteractor.cpp Interactions/mitkMouseModeSwitcher.cpp Interactions/mitkMouseMovePointSetInteractor.cpp Interactions/mitkMoveSurfaceInteractor.cpp Interactions/mitkNodeDepententPointSetInteractor.cpp Interactions/mitkPointSetInteractor.cpp Interactions/mitkPositionEvent.cpp Interactions/mitkPositionTracker.cpp Interactions/mitkState.cpp Interactions/mitkStateEvent.cpp Interactions/mitkStateMachine.cpp Interactions/mitkStateMachineFactory.cpp Interactions/mitkTransition.cpp Interactions/mitkWheelEvent.cpp Interactions/mitkKeyEvent.cpp Interactions/mitkVtkEventAdapter.cpp Interactions/mitkVtkInteractorStyle.cxx Interactions/mitkCrosshairPositionEvent.cpp IO/mitkBaseDataIOFactory.cpp IO/mitkCoreDataNodeReader.cpp IO/mitkDicomSeriesReader.cpp IO/mitkFileReader.cpp IO/mitkFileSeriesReader.cpp IO/mitkFileWriter.cpp #IO/mitkIpPicGet.c IO/mitkImageGenerator.cpp IO/mitkImageWriter.cpp IO/mitkImageWriterFactory.cpp IO/mitkItkImageFileIOFactory.cpp IO/mitkItkImageFileReader.cpp IO/mitkItkPictureWrite.cpp IO/mitkIOUtil.cpp IO/mitkLookupTableProperty.cpp IO/mitkOperation.cpp #IO/mitkPicFileIOFactory.cpp #IO/mitkPicFileReader.cpp #IO/mitkPicFileWriter.cpp #IO/mitkPicHelper.cpp #IO/mitkPicVolumeTimeSeriesIOFactory.cpp #IO/mitkPicVolumeTimeSeriesReader.cpp IO/mitkPixelType.cpp IO/mitkPointSetIOFactory.cpp IO/mitkPointSetReader.cpp IO/mitkPointSetWriter.cpp IO/mitkPointSetWriterFactory.cpp IO/mitkRawImageFileReader.cpp IO/mitkStandardFileLocations.cpp IO/mitkSTLFileIOFactory.cpp IO/mitkSTLFileReader.cpp IO/mitkSurfaceVtkWriter.cpp IO/mitkSurfaceVtkWriterFactory.cpp IO/mitkVtiFileIOFactory.cpp IO/mitkVtiFileReader.cpp IO/mitkVtkImageIOFactory.cpp IO/mitkVtkImageReader.cpp IO/mitkVtkSurfaceIOFactory.cpp IO/mitkVtkSurfaceReader.cpp IO/vtkPointSetXMLParser.cpp IO/mitkLog.cpp Rendering/mitkBaseRenderer.cpp Rendering/mitkVtkMapper2D.cpp Rendering/mitkVtkMapper3D.cpp Rendering/mitkRenderWindowFrame.cpp Rendering/mitkGeometry2DDataMapper2D.cpp Rendering/mitkGeometry2DDataVtkMapper3D.cpp Rendering/mitkGLMapper2D.cpp Rendering/mitkGradientBackground.cpp Rendering/mitkManufacturerLogo.cpp Rendering/mitkMapper2D.cpp Rendering/mitkMapper3D.cpp Rendering/mitkMapper.cpp Rendering/mitkPointSetGLMapper2D.cpp Rendering/mitkPointSetVtkMapper3D.cpp Rendering/mitkPolyDataGLMapper2D.cpp Rendering/mitkSurfaceGLMapper2D.cpp Rendering/mitkSurfaceVtkMapper3D.cpp Rendering/mitkVolumeDataVtkMapper3D.cpp Rendering/mitkVtkPropRenderer.cpp Rendering/mitkVtkWidgetRendering.cpp Rendering/vtkMitkRectangleProp.cpp Rendering/vtkMitkRenderProp.cpp Rendering/mitkVtkEventProvider.cpp Rendering/mitkRenderWindow.cpp Rendering/mitkRenderWindowBase.cpp Rendering/mitkShaderRepository.cpp Rendering/mitkImageVtkMapper2D.cpp Rendering/vtkMitkThickSlicesFilter.cpp Rendering/vtkMitkApplyLevelWindowToRGBFilter.cpp Common/mitkException.cpp + Common/mitkCommon.h + Common/mitkCoreObjectFactoryBase.cpp + Common/mitkCoreObjectFactory.cpp ) list(APPEND CPP_FILES ${CppMicroServices_SOURCES}) diff --git a/Modules/ClippingTools/mitkClippingPlaneDeformationTool.cpp b/Modules/ClippingTools/mitkClippingPlaneDeformationTool.cpp index 364a054ee4..f61e24bf58 100644 --- a/Modules/ClippingTools/mitkClippingPlaneDeformationTool.cpp +++ b/Modules/ClippingTools/mitkClippingPlaneDeformationTool.cpp @@ -1,81 +1,81 @@ /*=================================================================== 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 "mitkClippingPlaneDeformationTool.h" #include "mitkClippingPlaneDeformationTool.xpm" #include "mitkBaseRenderer.h" #include "mitkGlobalInteraction.h" #include "mitkRenderingManager.h" #include "mitkToolManager.h" namespace mitk{ MITK_TOOL_MACRO(ClippingTools_EXPORT, ClippingPlaneDeformationTool, "Clipping Tool Deformation"); } mitk::ClippingPlaneDeformationTool::ClippingPlaneDeformationTool() : Tool( "global" ) { } mitk::ClippingPlaneDeformationTool::~ClippingPlaneDeformationTool() { } const char** mitk::ClippingPlaneDeformationTool::GetXPM() const { return mitkClippingPlaneDeformationTool_xpm; } const char* mitk::ClippingPlaneDeformationTool::GetName() const { return "Deformation"; } const char* mitk::ClippingPlaneDeformationTool::GetGroup() const { return "ClippingTool"; } void mitk::ClippingPlaneDeformationTool::Activated() { Superclass::Activated(); //check if the Clipping plane is changed. if(m_ClippingPlaneNode != m_ToolManager->GetWorkingData(0)) { mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_SurfaceInteractor); this->ClippingPlaneChanged(); } mitk::GlobalInteraction::GetInstance()->AddInteractor(m_SurfaceInteractor); } void mitk::ClippingPlaneDeformationTool::Deactivated() { Superclass::Deactivated(); mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_SurfaceInteractor); } //Checks the working data node, if it has an interactor. Otherwise initial a new one. void mitk::ClippingPlaneDeformationTool::ClippingPlaneChanged() { m_ClippingPlaneNode = m_ToolManager->GetWorkingData(0); m_SurfaceInteractor = dynamic_cast(m_ClippingPlaneNode->GetInteractor()); if (m_SurfaceInteractor.IsNull()) m_SurfaceInteractor = mitk::SurfaceDeformationInteractor3D::New("AffineInteractor3D", m_ClippingPlaneNode); -} \ No newline at end of file +} diff --git a/Modules/ClippingTools/mitkClippingPlaneRotationTool.cpp b/Modules/ClippingTools/mitkClippingPlaneRotationTool.cpp index 3515960098..423cf4ecd8 100644 --- a/Modules/ClippingTools/mitkClippingPlaneRotationTool.cpp +++ b/Modules/ClippingTools/mitkClippingPlaneRotationTool.cpp @@ -1,84 +1,84 @@ /*=================================================================== 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 "mitkClippingPlaneRotationTool.h" #include "mitkClippingPlaneRotationTool.xpm" #include "mitkBaseRenderer.h" #include "mitkGlobalInteraction.h" #include "mitkRenderingManager.h" #include "mitkToolManager.h" namespace mitk { MITK_TOOL_MACRO(ClippingTools_EXPORT, ClippingPlaneRotationTool, "Clipping Tool Rotation"); } mitk::ClippingPlaneRotationTool::ClippingPlaneRotationTool() : Tool( "global" ) { } mitk::ClippingPlaneRotationTool::~ClippingPlaneRotationTool() { } const char** mitk::ClippingPlaneRotationTool::GetXPM() const { return mitkClippingPlaneRotationTool_xpm; } const char* mitk::ClippingPlaneRotationTool::GetName() const { return "Rotation"; } const char* mitk::ClippingPlaneRotationTool::GetGroup() const { return "ClippingTool"; } void mitk::ClippingPlaneRotationTool::Activated() { Superclass::Activated(); //check if the Clipping plane is changed. if(m_ClippingPlaneNode != m_ToolManager->GetWorkingData(0)) { mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_AffineInteractor); this->ClippingPlaneChanged(); } m_AffineInteractor->SetInteractionModeToRotation(); mitk::GlobalInteraction::GetInstance()->AddInteractor(m_AffineInteractor); } void mitk::ClippingPlaneRotationTool::Deactivated() { Superclass::Deactivated(); mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_AffineInteractor); } //Checks the working data node, if it has an interactor. Otherwise initial a new one. void mitk::ClippingPlaneRotationTool::ClippingPlaneChanged() { m_ClippingPlaneNode = m_ToolManager->GetWorkingData(0); m_AffineInteractor = dynamic_cast(m_ClippingPlaneNode->GetInteractor()); if (m_AffineInteractor.IsNull()) m_AffineInteractor = mitk::AffineInteractor3D::New("AffineInteractor3D", m_ClippingPlaneNode); -} \ No newline at end of file +} diff --git a/Modules/ClippingTools/mitkClippingPlaneTranslationTool.cpp b/Modules/ClippingTools/mitkClippingPlaneTranslationTool.cpp index 33e967c431..f1592ac66e 100644 --- a/Modules/ClippingTools/mitkClippingPlaneTranslationTool.cpp +++ b/Modules/ClippingTools/mitkClippingPlaneTranslationTool.cpp @@ -1,83 +1,83 @@ /*=================================================================== 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 "mitkClippingPlaneTranslationTool.h" #include "mitkClippingPlaneTranslationTool.xpm" #include "mitkBaseRenderer.h" #include "mitkGlobalInteraction.h" #include "mitkRenderingManager.h" #include "mitkToolManager.h" namespace mitk { MITK_TOOL_MACRO(ClippingTools_EXPORT, ClippingPlaneTranslationTool, "Clipping Tool Translation"); } mitk::ClippingPlaneTranslationTool::ClippingPlaneTranslationTool() : Tool( "global" ) { } mitk::ClippingPlaneTranslationTool::~ClippingPlaneTranslationTool() { } const char** mitk::ClippingPlaneTranslationTool::GetXPM() const { return mitkClippingPlaneTranslationTool_xpm; } const char* mitk::ClippingPlaneTranslationTool::GetName() const { return "Translation"; } const char* mitk::ClippingPlaneTranslationTool::GetGroup() const { return "ClippingTool"; } void mitk::ClippingPlaneTranslationTool::Activated() { Superclass::Activated(); //check if the Clipping plane is changed. if(m_ClippingPlaneNode != m_ToolManager->GetWorkingData(0)) { mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_AffineInteractor); this->ClippingPlaneChanged(); } m_AffineInteractor->SetInteractionModeToTranslation(); mitk::GlobalInteraction::GetInstance()->AddInteractor(m_AffineInteractor); } void mitk::ClippingPlaneTranslationTool::Deactivated() { Superclass::Deactivated(); mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_AffineInteractor); } //Checks the working data node, if it has an interactor. Otherwise initial a new one. void mitk::ClippingPlaneTranslationTool::ClippingPlaneChanged() { m_ClippingPlaneNode = m_ToolManager->GetWorkingData(0); m_AffineInteractor = dynamic_cast(m_ClippingPlaneNode->GetInteractor()); if (m_AffineInteractor.IsNull()) m_AffineInteractor = mitk::AffineInteractor3D::New("AffineInteractor3D", m_ClippingPlaneNode); -} \ No newline at end of file +} diff --git a/Modules/DeformableRegistrationUI/QmitkBSplineRegistrationView.h b/Modules/DeformableRegistrationUI/QmitkBSplineRegistrationView.h index c7dd2ca8bf..a126008da1 100644 --- a/Modules/DeformableRegistrationUI/QmitkBSplineRegistrationView.h +++ b/Modules/DeformableRegistrationUI/QmitkBSplineRegistrationView.h @@ -1,80 +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. ===================================================================*/ #ifndef QmitkBSplineRegistrationViewWidgetHIncluded #define QmitkBSplineRegistrationViewWidgetHIncluded #include "mitkDataNode.h" #include "MitkDeformableRegistrationUIExports.h" #include "ui_QmitkBSplineRegistrationViewControls.h" #include "mitkOptimizerParameters.h" /*! * \brief Widget for deformable demons registration * * Displays options for demons registration. */ class MITK_DEFORMABLEREGISTRATION_UI_EXPORT QmitkBSplineRegistrationView : public QWidget { Q_OBJECT public: QmitkBSplineRegistrationView( QWidget* parent = 0, Qt::WindowFlags f = 0 ); ~QmitkBSplineRegistrationView(); int GetNumberOfIterations(); Ui::QmitkBSplineRegistrationViewControls m_Controls; void SetFixedNode( mitk::DataNode * fixedNode ); void SetMovingNode( mitk::DataNode * movingNode ); public slots: void CalculateTransformation(); protected slots: /*! * Prints the values of the deformationfield */ void PrintDeformationField(); /*! * Select a deformation field */ void SelectDeformationField(); void OptimizerSelected(int optimizer); void HideAllOptimizerFrames(); protected: mitk::DataNode* m_FixedNode; mitk::DataNode* m_MovingNode; mitk::OptimizerParameters::Pointer m_OptimizerParameters; void setOptimizerParameters(); }; -#endif \ No newline at end of file +#endif diff --git a/Modules/DeformableRegistrationUI/QmitkDemonsRegistrationView.h b/Modules/DeformableRegistrationUI/QmitkDemonsRegistrationView.h index 3edc174fc4..74dd1cad87 100644 --- a/Modules/DeformableRegistrationUI/QmitkDemonsRegistrationView.h +++ b/Modules/DeformableRegistrationUI/QmitkDemonsRegistrationView.h @@ -1,58 +1,58 @@ /*=================================================================== 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 QmitkDemonsRegistrationViewWidgetHIncluded #define QmitkDemonsRegistrationViewWidgetHIncluded #include "mitkDataNode.h" #include "ui_QmitkDemonsRegistrationViewControls.h" #include "MitkDeformableRegistrationUIExports.h" /*! * \brief Widget for deformable demons registration * * Displays options for demons registration. */ class MITK_DEFORMABLEREGISTRATION_UI_EXPORT QmitkDemonsRegistrationView : public QWidget { Q_OBJECT public: QmitkDemonsRegistrationView( QWidget* parent = 0, Qt::WindowFlags f = 0 ); ~QmitkDemonsRegistrationView(); int GetNumberOfIterations(); float GetStandardDeviation(); void SetFixedNode( mitk::DataNode * fixedNode ); void SetMovingNode( mitk::DataNode * movingNode ); void UseHistogramMatching( bool useHM ); mitk::Image::Pointer GetResultImage(); mitk::Image::Pointer GetResultDeformationfield(); public slots: void CalculateTransformation(); protected: Ui::QmitkDemonsRegistrationViewControls m_Controls; mitk::DataNode::Pointer m_FixedNode; mitk::DataNode::Pointer m_MovingNode; mitk::Image::Pointer m_ResultImage; mitk::Image::Pointer m_ResultDeformationField; }; -#endif \ No newline at end of file +#endif diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsBetweennessHistogram.cpp b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsBetweennessHistogram.cpp index 3ec21c507b..123cee76c6 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsBetweennessHistogram.cpp +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsBetweennessHistogram.cpp @@ -1,130 +1,130 @@ /*=================================================================== 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 mitk::ConnectomicsBetweennessHistogram::ConnectomicsBetweennessHistogram() : m_Mode( UnweightedUndirectedMode ) , m_CentralityMap() { m_Subject = "Node Betweenness"; } mitk::ConnectomicsBetweennessHistogram::~ConnectomicsBetweennessHistogram() { } void mitk::ConnectomicsBetweennessHistogram::SetBetweennessCalculationMode( const mitk::ConnectomicsBetweennessHistogram::BetweennessCalculationMode & mode ) { m_Mode = mode; } mitk::ConnectomicsBetweennessHistogram::BetweennessCalculationMode mitk::ConnectomicsBetweennessHistogram::GetBetweennessCalculationMode() { return m_Mode; } void mitk::ConnectomicsBetweennessHistogram::ComputeFromConnectomicsNetwork( ConnectomicsNetwork* source ) { NetworkType* boostGraph = source->GetBoostGraph(); IteratorType vertex_iterator_begin, vertex_iterator_end; m_CentralityMap.clear(); m_CentralityMap.resize( source->GetNumberOfVertices() ); switch( m_Mode ) { case UnweightedUndirectedMode: { CalculateUnweightedUndirectedBetweennessCentrality( boostGraph, vertex_iterator_begin, vertex_iterator_end ); break; } case WeightedUndirectedMode: { CalculateWeightedUndirectedBetweennessCentrality( boostGraph, vertex_iterator_begin, vertex_iterator_end ); break; } } ConvertCentralityMapToHistogram(); } void mitk::ConnectomicsBetweennessHistogram::CalculateUnweightedUndirectedBetweennessCentrality( NetworkType* boostGraph, IteratorType vertex_iterator_begin, IteratorType vertex_iterator_end ) { boost::brandes_betweenness_centrality( *boostGraph, boost::centrality_map( boost::make_iterator_property_map( m_CentralityMap.begin(), boost::get( &mitk::ConnectomicsNetwork::NetworkNode::id, *boostGraph ), double() ) ).vertex_index_map( boost::get( &mitk::ConnectomicsNetwork::NetworkNode::id, *boostGraph ) ) ); } void mitk::ConnectomicsBetweennessHistogram::CalculateWeightedUndirectedBetweennessCentrality( NetworkType* boostGraph, IteratorType vertex_iterator_begin, IteratorType vertex_iterator_end ) { MBI_WARN << mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_UNIMPLEMENTED_FEATURE; } void mitk::ConnectomicsBetweennessHistogram::ConvertCentralityMapToHistogram() { double maximumFloat( 0.0 ); for ( int index( 0 ); index < m_CentralityMap.size(); index++ ) { if( m_CentralityMap[ index ] > maximumFloat ) { maximumFloat = m_CentralityMap[ index ]; } - } + } // use the boost double to int converter // it defaults to trunc typedef boost::numeric::converter Double2Int ; // for rounding, reduces the number of nodes classed as zero maximumFloat += 0.5; int maximumInt( 0 ); try { maximumInt = Double2Int::convert( maximumFloat ); } catch ( boost::numeric::positive_overflow const& ) { MBI_WARN << mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_OUTSIDE_INTEGER_RANGE; } m_HistogramVector.resize( maximumInt + 1 ); for ( int index( 0 ); index < m_CentralityMap.size(); index++ ) { int value( 0 ); value = Double2Int::convert( ( m_CentralityMap[index ] + 0.5 ) ); m_HistogramVector[ value ]++; } UpdateYMax(); m_Valid = true; -} \ No newline at end of file +} diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsBetweennessHistogram.h b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsBetweennessHistogram.h index a8214e4313..06e9c92b40 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsBetweennessHistogram.h +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsBetweennessHistogram.h @@ -1,80 +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. ===================================================================*/ #ifndef _MITK_ConnectomicsBetweennessHistogram_H #define _MITK_ConnectomicsBetweennessHistogram_H #include #include namespace mitk { /** * \brief A class to calculate and store the betweenness of each node */ class ConnectomicsBetweennessHistogram : public mitk::ConnectomicsHistogramBase { public: /** Enum for different ways to calculate betweenness centrality */ enum BetweennessCalculationMode { UnweightedUndirectedMode, WeightedUndirectedMode }; ConnectomicsBetweennessHistogram(); virtual ~ConnectomicsBetweennessHistogram(); /** Set the calucaltion mode */ void SetBetweennessCalculationMode( const BetweennessCalculationMode & ); /** Get the calculation mode */ BetweennessCalculationMode GetBetweennessCalculationMode(); protected: /* Typedefs */ typedef mitk::ConnectomicsNetwork::NetworkType NetworkType; typedef boost::graph_traits< NetworkType >::vertex_iterator IteratorType; typedef std::vector< double > BCMapType; /** @brief Creates a new histogram from the network source. */ virtual void ComputeFromConnectomicsNetwork( ConnectomicsNetwork* source ); /** Calculate betweenness centrality ignoring the weight of the edges */ void CalculateUnweightedUndirectedBetweennessCentrality( NetworkType*, IteratorType, IteratorType ); /** Calculate betweenness centrality taking into consideration the weight of the edges */ void CalculateWeightedUndirectedBetweennessCentrality( NetworkType*, IteratorType, IteratorType ); /** Converts the centrality map to a histogram by binning */ void ConvertCentralityMapToHistogram(); /** Stores which mode has been selected for betweenness centrality calculation */ BetweennessCalculationMode m_Mode; /** Stores the betweenness centralities for each node */ BCMapType m_CentralityMap; }; } -#endif /* _MITK_ConnectomicsBetweennessHistogram_H */ \ No newline at end of file +#endif /* _MITK_ConnectomicsBetweennessHistogram_H */ diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsDegreeHistogram.cpp b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsDegreeHistogram.cpp index 4c97e907ce..1201ada085 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsDegreeHistogram.cpp +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsDegreeHistogram.cpp @@ -1,58 +1,58 @@ /*=================================================================== 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 mitk::ConnectomicsDegreeHistogram::ConnectomicsDegreeHistogram() { m_Subject = "Node degree"; } mitk::ConnectomicsDegreeHistogram::~ConnectomicsDegreeHistogram() { } void mitk::ConnectomicsDegreeHistogram::ComputeFromConnectomicsNetwork( ConnectomicsNetwork* source ) { std::vector< int > degreeOfNodesVector = source->GetDegreeOfNodes(); int maximumDegree( 0 ); for( int index( 0 ); index < degreeOfNodesVector.size(); index++ ) { if( maximumDegree < degreeOfNodesVector[ index ] ) { maximumDegree = degreeOfNodesVector[ index ]; } } this->m_HistogramVector.resize( maximumDegree + 1 ); for( int index( 0 ); index < m_HistogramVector.size(); index++ ) { this->m_HistogramVector[ index ] = 0; } this->m_TopValue = maximumDegree; for( int index( 0 ); index < degreeOfNodesVector.size(); index++ ) { this->m_HistogramVector[ degreeOfNodesVector[ index ] ]++; } // successfully created a valid histogram this->m_Valid = true; -} \ No newline at end of file +} diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsDegreeHistogram.h b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsDegreeHistogram.h index b50804ce56..3973000151 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsDegreeHistogram.h +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsDegreeHistogram.h @@ -1,47 +1,47 @@ /*=================================================================== 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_ConnectomicsDegreeHistogram_H #define _MITK_ConnectomicsDegreeHistogram_H #include namespace mitk { /** * \brief A class to calculate and store the degree of each node */ class ConnectomicsDegreeHistogram : public mitk::ConnectomicsHistogramBase { public: ConnectomicsDegreeHistogram(); virtual ~ConnectomicsDegreeHistogram(); protected: /** @brief Creates a new histogram from the network source. */ virtual void ComputeFromConnectomicsNetwork( ConnectomicsNetwork* source ); }; } -#endif /* _MITK_ConnectomicsDegreeHistogram_H */ \ No newline at end of file +#endif /* _MITK_ConnectomicsDegreeHistogram_H */ diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsHistogramBase.cpp b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsHistogramBase.cpp index f105d9288c..5c163e841b 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsHistogramBase.cpp +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsHistogramBase.cpp @@ -1,226 +1,226 @@ /*=================================================================== 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 mitk::ConnectomicsHistogramBase::ConnectomicsHistogramBase() : m_Valid( false ) , m_BaselineValue( 0 ) , m_TopValue( 1 ) , m_StartValue( 0 ) , m_Subject( "" ) { } mitk::ConnectomicsHistogramBase::~ConnectomicsHistogramBase() { } double mitk::ConnectomicsHistogramBase::GetYMin() const { return m_BaselineValue; } double mitk::ConnectomicsHistogramBase::GetYMax() const { return m_TopValue; } double mitk::ConnectomicsHistogramBase::GetMin() const { return this->GetXMin(); } double mitk::ConnectomicsHistogramBase::GetMax() const { return this->GetXMax(); } double mitk::ConnectomicsHistogramBase::GetXMin() const { return m_StartValue; } double mitk::ConnectomicsHistogramBase::GetXMax() const { return ( m_StartValue + this->GetRange() ); } int mitk::ConnectomicsHistogramBase::GetRange() const { return m_HistogramVector.size(); } bool mitk::ConnectomicsHistogramBase::IsValid() const { return m_Valid; } void mitk::ConnectomicsHistogramBase::PrintToConsole() const { MITK_INFO << "Histogram - Maximum " << this->GetYMax() << " Minimum " << this->GetYMin() << " Range " << this->GetRange(); for( int index( 0 ); index < m_HistogramVector.size(); index++ ) { MITK_INFO << " Bin: " << index << " Value: " << m_HistogramVector[ index ]; } } std::string mitk::ConnectomicsHistogramBase::GetSubject() const { return m_Subject; } void mitk::ConnectomicsHistogramBase::SetSubject( std::string subject ) { m_Subject = subject; } void mitk::ConnectomicsHistogramBase::ComputeFromBaseData( BaseData* source ) { m_Valid = false; m_HistogramVector.clear(); //check if input is valid if (source==NULL) { // empty base data return; } mitk::ConnectomicsNetwork* networkSource = dynamic_cast(source); if (networkSource==NULL) { // base data but no network return; } ComputeFromConnectomicsNetwork( networkSource ); } float mitk::ConnectomicsHistogramBase::GetRelativeBin( double start, double end ) const { // use the boost double to int converter // it defaults to trunc typedef boost::numeric::converter Double2Int ; float result( 0.0 ); if( !m_Valid ) { MITK_ERROR << mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_TRIED_TO_ACCESS_INVALID_HISTOGRAM; return result; } if( ( start < 0.0 ) || ( end < 0.0 ) ) { MITK_ERROR << mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_PASSED_NEGATIVE_INDEX_TO_HISTOGRAM; return result; } // calculate result if( std::abs( end - start ) <= 1.0 ) { // if the bin size is one or less, we can do not need to interpolate int index( 0 ); try { // show the value for n between n - .5 and n + .5 double temp = ( start + end ) / 2.0; index = Double2Int::convert( temp ); // By default throws positive_overflow() } catch ( boost::numeric::positive_overflow const& ) { MBI_WARN << mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_OUTSIDE_INTEGER_RANGE; } if( index < m_HistogramVector.size() ) { result = m_HistogramVector[ index ]; } else { MBI_WARN << mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_BEYOND_SCOPE << index << " on vector sized: " << m_HistogramVector.size(); } } else { // if the bin size is more than one we need to interpolate int indexStart( 0 ), indexEnd( 0 ); try { indexStart = Double2Int::convert( start ); indexEnd = Double2Int::convert( end ); } catch ( boost::numeric::positive_overflow const& ) { MBI_WARN << mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_OUTSIDE_INTEGER_RANGE; } if( ( indexStart < m_HistogramVector.size() ) && ( indexEnd < m_HistogramVector.size() ) ) { // add up weighted values and divide by range // add partial start and end bin double startPercentage = 1.0 - start + indexStart; double endPercentage = end - indexEnd; result += startPercentage * m_HistogramVector[ indexStart ]; result += endPercentage * m_HistogramVector[ indexEnd ]; // add whole inbetween bins for( int tempIndex = indexStart + 1; tempIndex < indexEnd; tempIndex++ ) { result += m_HistogramVector[ tempIndex ]; } } else { MBI_WARN << mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_BEYOND_SCOPE << indexStart << " to " << indexEnd << " on vector sized: " << m_HistogramVector.size(); } } // normalizeresult by dividing through maximum degree result = result / GetYMax(); return result; } void mitk::ConnectomicsHistogramBase::UpdateYMax() { for ( int index( 0 ); index < m_HistogramVector.size(); index++ ) { if( m_HistogramVector[ index ] > m_TopValue ) { m_TopValue = m_HistogramVector[ index ]; } } } std::vector< double > mitk::ConnectomicsHistogramBase::GetHistogramVector() { return m_HistogramVector; -} \ No newline at end of file +} diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsHistogramBase.h b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsHistogramBase.h index bf488461c0..1ee7cf294b 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsHistogramBase.h +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsHistogramBase.h @@ -1,101 +1,101 @@ /*=================================================================== 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_ConnectomicsHistogramBase_H #define _MITK_ConnectomicsHistogramBase_H #include "mitkSimpleHistogram.h" #include "mitkCommon.h" #include "mitkConnectomicsNetwork.h" namespace mitk { //##Documentation //## @brief Superclass for histograms working with connectomic networks class ConnectomicsHistogramBase : public mitk::SimpleHistogram { public: ConnectomicsHistogramBase(); virtual ~ConnectomicsHistogramBase(); /** @brief Returns the minimal y=f(x) value of the histogram. */ virtual double GetYMin() const; /** @brief Returns the maximum y=f(x) value of the histogram. */ virtual double GetYMax() const; /** @brief Returns the minimal x value of the histogram. */ virtual double GetXMin() const; /** @brief Returns the maximum x value of the histogram. */ virtual double GetXMax() const; /** @brief Returns the range of the histogram. */ virtual int GetRange() const; /** @brief Update the Y maximum to the maximal value in the histogram */ virtual void UpdateYMax(); /** @brief Creates a new histogram from the source. */ virtual void ComputeFromBaseData( BaseData* source ); /** @brief Print values to console. */ virtual void PrintToConsole( ) const; /** @brief Returns whether the histogram can be considered valid. */ virtual bool IsValid() const; /** @brief Returns the subject of the histogram as a string. */ virtual std::string GetSubject() const; /** @brief Set the subject of the histogram as a string. */ virtual void SetSubject( std::string ); /** @brief Get bin height for the bin between start and end*/ virtual float GetRelativeBin( double start, double end ) const; /** @brief Get the double vector*/ virtual std::vector< double > GetHistogramVector(); protected: // Functions /** @brief Creates a new histogram from the network source. */ virtual void ComputeFromConnectomicsNetwork( ConnectomicsNetwork* source ) = 0; /** @brief Legacy method, do no use */ virtual double GetMin() const; /** @brief Legacy method, do no use */ virtual double GetMax() const; // Variables /** @brief Is this a valid histogram*/ bool m_Valid; /** @brief Which is the baseline value for the histogram /* /* This value should be zero for all network histograms */ int m_BaselineValue; /** @brief Which is the top value for the histogram */ int m_TopValue; /** @brief Which is the starting x value for the histogram */ int m_StartValue; /** @brief We expect not continuous but discrete histograms */ std::vector< double > m_HistogramVector; /** @brief Subject of the histogram as a string. */ std::string m_Subject; }; } -#endif /* _MITK_ConnectomicsHistogramBase_H */ \ No newline at end of file +#endif /* _MITK_ConnectomicsHistogramBase_H */ diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsNetworkCreator.h b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsNetworkCreator.h index 1027d4a7c5..8bb4d26f05 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsNetworkCreator.h +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsNetworkCreator.h @@ -1,191 +1,191 @@ /*=================================================================== 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 mitkConnectomicsNetworkCreator_h #define mitkConnectomicsNetworkCreator_h #include #include #include #include "mitkCommon.h" #include "mitkImage.h" #include "mitkFiberBundleX.h" #include "mitkConnectomicsNetwork.h" #include "MitkDiffusionImagingExports.h" namespace mitk { class MitkDiffusionImaging_EXPORT ConnectomicsNetworkCreator : public itk::Object { public: /** Enum for different ways to create the mapping from fibers to network */ enum MappingStrategy { EndElementPosition, PrecomputeAndDistance, JustEndPointVerticesNoLabel, EndElementPositionAvoidingWhiteMatter }; /** Standard class typedefs. */ /** Method for creation through the object factory. */ mitkClassMacro(ConnectomicsNetworkCreator, itk::Object); itkNewMacro(Self); /** Types for the standardized Tract **/ typedef itk::Point PointType; typedef itk::VectorContainer TractType; typedef itk::VectorContainer< unsigned int, TractType::Pointer > TractContainerType; //init via smartpointer /** Types for Network **/ typedef mitk::ConnectomicsNetwork::VertexDescriptorType VertexType; typedef mitk::ConnectomicsNetwork::EdgeDescriptorType EdgeType; typedef mitk::ConnectomicsNetwork::NetworkNode NetworkNode; typedef std::pair< VertexType, VertexType > ConnectionType; /** Types for labels **/ typedef int ImageLabelType; typedef std::pair< ImageLabelType, ImageLabelType > ImageLabelPairType; void CreateNetworkFromFibersAndSegmentation(); void SetFiberBundle(mitk::FiberBundleX::Pointer fiberBundle); void SetSegmentation(mitk::Image::Pointer segmentation); mitk::ConnectomicsNetwork::Pointer GetNetwork(); protected: //////////////////// Functions /////////////////////// ConnectomicsNetworkCreator(); ConnectomicsNetworkCreator( mitk::Image::Pointer segmentation, mitk::FiberBundleX::Pointer fiberBundle ); ~ConnectomicsNetworkCreator(); /** Add a connection to the network */ void AddConnectionToNetwork(ConnectionType newConnection); /** Determine if a label is already identified with a vertex, otherwise create a new one */ VertexType ReturnAssociatedVertexForLabel( ImageLabelType label ); /** Return the vertexes associated with a pair of labels */ ConnectionType ReturnAssociatedVertexPairForLabelPair( ImageLabelPairType labelpair ); /** Return the pair of labels which identify the areas connected by a single fiber */ ImageLabelPairType ReturnLabelForFiberTract( TractType::Pointer singleTract, MappingStrategy strategy ); /** Assign the additional information which should be part of the vertex */ void SupplyVertexWithInformation( ImageLabelType& label, VertexType& vertex ); /** Create a string from the label */ std::string LabelToString( ImageLabelType& label ); /** Check whether the label in question belongs to white matter according to the freesurfer table */ bool IsNonWhiteMatterLabel( int labelInQuestion ); /** Check whether the label in question belongs to background according to the freesurfer table */ bool IsBackgroundLabel( int labelInQuestion ); /** Extend a straight line through the given points and look for the first non white matter label It will try extend in the direction of the points in the vector so a vector {B,C} will result in extending from C in the direction C-B */ void LinearExtensionUntilGreyMatter( std::vector & indexVectorOfPointsToUse, TractType::Pointer singleTract, int & label, mitk::Index3D & mitkIndex ); /** Retract fiber until the first brain matter label is hit The bool parameter controls whether the front or the end is retracted */ void RetractionUntilBrainMatter( bool retractFront, TractType::Pointer singleTract, int & label, mitk::Index3D & mitkIndex ); /** Convert point to itk point */ itk::Point GetItkPoint(double point[3]); ///////// Mapping strategies ////////// /** Use the position of the end and starting element only to map to labels Map a fiber to a vertex by taking the value of the parcellation image at the same world coordinates as the last and first element of the tract.*/ ImageLabelPairType EndElementPositionLabel( TractType::Pointer singleTract ); /** Map by distance between elements and vertices depending on their volume First go through the parcellation and compute the coordinates of the future vertices. Assign a radius according on their volume. Then map an edge to a label by considering the nearest vertices and comparing the distance to them to their radii. */ ImageLabelPairType PrecomputeVertexLocationsBySegmentation( TractType::Pointer singleTract ); /** Use the position of the end and starting element only to map to labels Just take first and last position, no labelling, nothing */ ImageLabelPairType JustEndPointVerticesNoLabelTest( TractType::Pointer singleTract ); /** Use the position of the end and starting element unless it is in white matter, then search for nearby parcellation to map to labels Map a fiber to a vertex by taking the value of the parcellation image at the same world coordinates as the last and first element of the tract. If this happens to be white matter, then try to extend the fiber in a line and take the first non-white matter parcel, that is intersected. */ ImageLabelPairType EndElementPositionLabelAvoidingWhiteMatter( TractType::Pointer singleTract ); ///////// Conversions ////////// /** Convert fiber index to segmentation index coordinates */ void FiberToSegmentationCoords( mitk::Point3D& fiberCoord, mitk::Point3D& segCoord ); /** Convert segmentation index to fiber index coordinates */ void SegmentationToFiberCoords( mitk::Point3D& segCoord, mitk::Point3D& fiberCoord ); /////////////////////// Variables //////////////////////// mitk::FiberBundleX::Pointer m_FiberBundle; mitk::Image::Pointer m_Segmentation; // the graph itself mitk::ConnectomicsNetwork::Pointer m_ConNetwork; // the id counter int idCounter; // the map mapping labels to vertices std::map< ImageLabelType, VertexType > m_LabelToVertexMap; // mapping labels to additional information std::map< ImageLabelType, NetworkNode > m_LabelToNodePropertyMap; // toggles whether edges between a node and itself can exist bool allowLoops; //////////////////////// IDs //////////////////////////// // These IDs are the freesurfer ids used in parcellation static const int freesurfer_Left_Cerebral_White_Matter = 2; static const int freesurfer_Left_Cerebellum_White_Matter = 7; static const int freesurfer_Right_Cerebral_White_Matter = 41; static const int freesurfer_Right_Cerebellum_White_Matter = 46; }; }// end namespace mitk -#endif // _mitkConnectomicsNetworkCreator_H_INCLUDED \ No newline at end of file +#endif // _mitkConnectomicsNetworkCreator_H_INCLUDED diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsShortestPathHistogram.h b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsShortestPathHistogram.h index 6406a90752..972a88574b 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsShortestPathHistogram.h +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsShortestPathHistogram.h @@ -1,86 +1,86 @@ /*=================================================================== 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_ConnectomicsShortestPathHistogram_H #define _MITK_ConnectomicsShortestPathHistogram_H #include #include "MitkDiffusionImagingExports.h" namespace mitk { /** * \brief A class to calculate and store the shortest path between each pair of nodes */ class MitkDiffusionImaging_EXPORT ConnectomicsShortestPathHistogram : public mitk::ConnectomicsHistogramBase { public: /** Enum for different ways to calculate shortest paths */ enum ShortestPathCalculationMode { UnweightedUndirectedMode, WeightedUndirectedMode }; ConnectomicsShortestPathHistogram(); virtual ~ConnectomicsShortestPathHistogram(); /** Set the calucaltion mode */ void SetShortestPathCalculationMode( const ShortestPathCalculationMode & ); /** Get the calculation mode */ ShortestPathCalculationMode GetShortestPathCalculationMode(); /** Get efficiency */ double GetEfficiency(); protected: /* Typedefs */ typedef mitk::ConnectomicsNetwork::NetworkType NetworkType; typedef boost::graph_traits< NetworkType >::vertex_descriptor DescriptorType; typedef boost::graph_traits< NetworkType >::vertex_iterator IteratorType; /** @brief Creates a new histogram from the network source. */ virtual void ComputeFromConnectomicsNetwork( ConnectomicsNetwork* source ); /** Calculate shortest paths ignoring the weight of the edges */ void CalculateUnweightedUndirectedShortestPaths( NetworkType* boostGraph ); /** Calculate shortest paths taking into consideration the weight of the edges */ void CalculateWeightedUndirectedShortestPaths( NetworkType* boostGraph ); /** Converts the distance map to a histogram */ void ConvertDistanceMapToHistogram(); /** Stores which mode has been selected for shortest path calculation */ ShortestPathCalculationMode m_Mode; /** Stores the shortest paths between the nodes */ std::vector< std::vector< int > > m_DistanceMatrix; /** Stores, whether the graph has disconnected components */ bool m_EverythingConnected; }; } -#endif /* _MITK_ConnectomicsShortestPathHistogram_H */ \ No newline at end of file +#endif /* _MITK_ConnectomicsShortestPathHistogram_H */ diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingCostFunctionBase.h b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingCostFunctionBase.h index e2dff47502..424d367596 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingCostFunctionBase.h +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingCostFunctionBase.h @@ -1,54 +1,54 @@ /*=================================================================== 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 mitkConnectomicsSimulatedAnnealingCostFunctionBase_h #define mitkConnectomicsSimulatedAnnealingCostFunctionBase_h #include #include #include #include "mitkCommon.h" #include "MitkDiffusionImagingExports.h" namespace mitk { /** * \brief A generic base class for cost functions for use in simulated annealing */ class MitkDiffusionImaging_EXPORT ConnectomicsSimulatedAnnealingCostFunctionBase : public itk::Object { public: /** Standard class typedefs. */ /** Method for creation through the object factory. */ mitkClassMacro(ConnectomicsSimulatedAnnealingCostFunctionBase, itk::Object); itkNewMacro(Self); protected: //////////////////// Functions /////////////////////// ConnectomicsSimulatedAnnealingCostFunctionBase(); ~ConnectomicsSimulatedAnnealingCostFunctionBase(); }; }// end namespace mitk -#endif // mitkConnectomicsSimulatedAnnealingCostFunctionBase_h \ No newline at end of file +#endif // mitkConnectomicsSimulatedAnnealingCostFunctionBase_h diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingCostFunctionModularity.cpp b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingCostFunctionModularity.cpp index 5013f172b0..3bdff32ada 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingCostFunctionModularity.cpp +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingCostFunctionModularity.cpp @@ -1,125 +1,125 @@ /*=================================================================== 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 "mitkConnectomicsSimulatedAnnealingCostFunctionModularity.h" mitk::ConnectomicsSimulatedAnnealingCostFunctionModularity::ConnectomicsSimulatedAnnealingCostFunctionModularity() { } mitk::ConnectomicsSimulatedAnnealingCostFunctionModularity::~ConnectomicsSimulatedAnnealingCostFunctionModularity() { } double mitk::ConnectomicsSimulatedAnnealingCostFunctionModularity::Evaluate( mitk::ConnectomicsNetwork::Pointer network, ToModuleMapType* vertexToModuleMap ) const { double cost( 0.0 ); cost = 100.0 * ( 1.0 - CalculateModularity( network, vertexToModuleMap ) ); return cost; } double mitk::ConnectomicsSimulatedAnnealingCostFunctionModularity::CalculateModularity( mitk::ConnectomicsNetwork::Pointer network, ToModuleMapType* vertexToModuleMap ) const { double modularity( 0.0 ); int numberOfModules = getNumberOfModules( vertexToModuleMap ); if( network->GetNumberOfVertices() != vertexToModuleMap->size() ) { MBI_ERROR << "Number of vertices and vertex to module map size do not match!"; return modularity; } int numberOfLinksInNetwork( 0 ); std::vector< int > numberOfLinksInModule, sumOfDegreesInModule; numberOfLinksInModule.resize( numberOfModules, 0 ); sumOfDegreesInModule.resize( numberOfModules, 0 ); // get vector of all vertex descriptors in the network const std::vector< VertexDescriptorType > allNodesVector = network->GetVectorOfAllVertexDescriptors(); for( int nodeNumber( 0 ); nodeNumber < allNodesVector.size() ; nodeNumber++) { int correspondingModule = vertexToModuleMap->find( allNodesVector[ nodeNumber ] )->second; const std::vector< VertexDescriptorType > adjacentNodexVector = network->GetVectorOfAdjacentNodes( allNodesVector[ nodeNumber ] ); numberOfLinksInNetwork += adjacentNodexVector.size(); sumOfDegreesInModule[ correspondingModule ] += adjacentNodexVector.size(); for( int adjacentNodeNumber( 0 ); adjacentNodeNumber < adjacentNodexVector.size() ; adjacentNodeNumber++) { if( correspondingModule == vertexToModuleMap->find( adjacentNodexVector[ adjacentNodeNumber ] )->second ) { numberOfLinksInModule[ correspondingModule ]++; } } } // the numbers for links have to be halved, as each edge was counted twice numberOfLinksInNetwork = numberOfLinksInNetwork / 2; // if the network contains no links return 0 if( numberOfLinksInNetwork < 1) { return 0; } for( int index( 0 ); index < numberOfModules ; index++) { numberOfLinksInModule[ index ] = numberOfLinksInModule[ index ] / 2; } //Calculate modularity M: //M = sum_{s=1}^{N_{M}} [ (l_{s} / L) - (d_{s} / ( 2L ))^2 ] //where N_{M} is the number of modules //L is the number of links in the network //l_{s} is the number of links between nodes in the module //s is the module //d_{s} is the sum of degrees of the nodes in the module //( taken from Guimera, R. AND Amaral, L. A. N. // Cartography of complex networks: modules and universal roles // Journal of Statistical Mechanics: Theory and Experiment, 2005, 2005, P02001 ) for( int moduleID( 0 ); moduleID < numberOfModules; moduleID++ ) { modularity += (((double) numberOfLinksInModule[ moduleID ]) / ((double) numberOfLinksInNetwork)) - ( (((double) sumOfDegreesInModule[ moduleID ]) / ((double) 2 * numberOfLinksInNetwork) ) * (((double) sumOfDegreesInModule[ moduleID ]) / ((double) 2 * numberOfLinksInNetwork) ) ); } return modularity; } int mitk::ConnectomicsSimulatedAnnealingCostFunctionModularity::getNumberOfModules( ToModuleMapType *vertexToModuleMap ) const { int maxModule( 0 ); ToModuleMapType::iterator iter = vertexToModuleMap->begin(); ToModuleMapType::iterator end = vertexToModuleMap->end(); while( iter != end ) { if( iter->second > maxModule ) { maxModule = iter->second; } iter++; } return maxModule + 1; -} \ No newline at end of file +} diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingCostFunctionModularity.h b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingCostFunctionModularity.h index 9c4ab01747..636695b232 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingCostFunctionModularity.h +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingCostFunctionModularity.h @@ -1,62 +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 mitkConnectomicsSimulatedAnnealingCostFunctionModularity_h #define mitkConnectomicsSimulatedAnnealingCostFunctionModularity_h #include "mitkConnectomicsSimulatedAnnealingCostFunctionBase.h" #include "mitkConnectomicsNetwork.h" namespace mitk { /** * \brief A cost function using the modularity of the network */ class MitkDiffusionImaging_EXPORT ConnectomicsSimulatedAnnealingCostFunctionModularity : public mitk::ConnectomicsSimulatedAnnealingCostFunctionBase { public: typedef mitk::ConnectomicsNetwork::VertexDescriptorType VertexDescriptorType; typedef std::map< VertexDescriptorType, int > ToModuleMapType; typedef std::map< VertexDescriptorType, VertexDescriptorType > VertexToVertexMapType; /** Standard class typedefs. */ /** Method for creation through the object factory. */ mitkClassMacro(ConnectomicsSimulatedAnnealingCostFunctionModularity, itk::Object); itkNewMacro(Self); // Evaluate the network according to the set cost function double Evaluate( mitk::ConnectomicsNetwork::Pointer network, ToModuleMapType *vertexToModuleMap ) const; // Will calculate and return the modularity of the network double CalculateModularity( mitk::ConnectomicsNetwork::Pointer network, ToModuleMapType *vertexToModuleMap ) const; protected: // returns the number of modules int getNumberOfModules( ToModuleMapType *vertexToModuleMap ) const; //////////////////// Functions /////////////////////// ConnectomicsSimulatedAnnealingCostFunctionModularity(); ~ConnectomicsSimulatedAnnealingCostFunctionModularity(); }; }// end namespace mitk -#endif // mitkConnectomicsSimulatedAnnealingCostFunctionModularity_h \ No newline at end of file +#endif // mitkConnectomicsSimulatedAnnealingCostFunctionModularity_h diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingManager.cpp b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingManager.cpp index 8849d32612..4d07fd7d73 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingManager.cpp +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingManager.cpp @@ -1,180 +1,180 @@ /*=================================================================== 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 "mitkConnectomicsSimulatedAnnealingManager.h" //for random number generation #include "vxl/core/vnl/vnl_random.h" #include "vxl/core/vnl/vnl_math.h" mitk::ConnectomicsSimulatedAnnealingManager::ConnectomicsSimulatedAnnealingManager() : m_Permutation( 0 ) { } mitk::ConnectomicsSimulatedAnnealingManager::~ConnectomicsSimulatedAnnealingManager() { } bool mitk::ConnectomicsSimulatedAnnealingManager::AcceptChange( double costBefore, double costAfter, double temperature ) { if( costAfter <= costBefore ) {// if cost is lower after return true; } //the random number generators vnl_random rng( (unsigned int) rand() ); //randomly generate threshold const double threshold = rng.drand64( 0.0 , 1.0); //the likelihood of acceptance double likelihood = std::exp( - ( costAfter - costBefore ) / temperature ); if( threshold < likelihood ) { return true; } return false; } void mitk::ConnectomicsSimulatedAnnealingManager::SetPermutation( mitk::ConnectomicsSimulatedAnnealingPermutationBase::Pointer permutation ) { m_Permutation = permutation; } void mitk::ConnectomicsSimulatedAnnealingManager::RunSimulatedAnnealing( double temperature, double stepSize ) { if( m_Permutation.IsNull() ) { MBI_ERROR << "Trying to run simulated annealing on empty permutation."; return; } if( !m_Permutation->HasCostFunction() ) { MBI_ERROR << "Trying to run simulated annealing on empty cost function."; return; } // Initialize the associated permutation m_Permutation->Initialize(); for( double currentTemperature( temperature ); currentTemperature > 0.00001; currentTemperature = currentTemperature / stepSize ) { // Run Permutations at the current temperature m_Permutation->Permutate( currentTemperature ); } // Clean up result m_Permutation->CleanUp(); } //void mitk::ConnectomicsSimulatedAnnealingManager::Testing( mitk::ConnectomicsNetwork::Pointer network ) //{ // // precursor to an actual test, this will assign a to module map which is only valid for a // // specific network and whose modularity is known // ToModuleMapType threeModuleSolution; // std::vector< VertexDescriptorType > vertexVector = network->GetVectorOfAllVertexDescriptors(); // // threeModuleSolution.insert( std::pair( vertexVector[ 0 ], 0 ) ); // threeModuleSolution.insert( std::pair( vertexVector[ 1 ], 0 ) ); // threeModuleSolution.insert( std::pair( vertexVector[ 2 ], 0 ) ); // threeModuleSolution.insert( std::pair( vertexVector[ 3 ], 0 ) ); // threeModuleSolution.insert( std::pair( vertexVector[ 4 ], 0 ) ); // threeModuleSolution.insert( std::pair( vertexVector[ 5 ], 1 ) ); // threeModuleSolution.insert( std::pair( vertexVector[ 6 ], 1 ) ); // threeModuleSolution.insert( std::pair( vertexVector[ 7 ], 1 ) ); // threeModuleSolution.insert( std::pair( vertexVector[ 8 ], 1 ) ); // threeModuleSolution.insert( std::pair( vertexVector[ 9 ], 2 ) ); // threeModuleSolution.insert( std::pair( vertexVector[ 10 ], 2 ) ); // threeModuleSolution.insert( std::pair( vertexVector[ 11 ], 2 ) ); // // std::cout << "Modularity is " << CalculateModularity( network, &threeModuleSolution ) << " and should be " << 0.4753 << std::endl; // // std::cout << " Module 0 contains " << getNumberOfVerticesInModule( &threeModuleSolution, 0 ) << " nodes, should be 5.\n"; // std::cout << " Module 1 contains " << getNumberOfVerticesInModule( &threeModuleSolution, 1 ) << " nodes, should be 4.\n"; // std::cout << " Module 2 contains " << getNumberOfVerticesInModule( &threeModuleSolution, 2 ) << " nodes, should be 3.\n"; // // ToModuleMapType oneModuleSolution; // oneModuleSolution.insert( std::pair( vertexVector[ 0 ], 0 ) ); // oneModuleSolution.insert( std::pair( vertexVector[ 1 ], 0 ) ); // oneModuleSolution.insert( std::pair( vertexVector[ 2 ], 0 ) ); // oneModuleSolution.insert( std::pair( vertexVector[ 3 ], 0 ) ); // oneModuleSolution.insert( std::pair( vertexVector[ 4 ], 0 ) ); // oneModuleSolution.insert( std::pair( vertexVector[ 5 ], 0 ) ); // oneModuleSolution.insert( std::pair( vertexVector[ 6 ], 0 ) ); // oneModuleSolution.insert( std::pair( vertexVector[ 7 ], 0 ) ); // oneModuleSolution.insert( std::pair( vertexVector[ 8 ], 0 ) ); // oneModuleSolution.insert( std::pair( vertexVector[ 9 ], 0 ) ); // oneModuleSolution.insert( std::pair( vertexVector[ 10 ], 0 ) ); // oneModuleSolution.insert( std::pair( vertexVector[ 11 ], 0 ) ); // // std::cout << "Modularity is " << CalculateModularity( network, &oneModuleSolution ) << " and should be " << 0.0 << std::endl; // // std::cout << " Module 0 contains " << getNumberOfVerticesInModule( &oneModuleSolution, 0 ) << " nodes, should be 12.\n"; // // ToModuleMapType badTwoModuleSolution; // badTwoModuleSolution.insert( std::pair( vertexVector[ 0 ], 0 ) ); // badTwoModuleSolution.insert( std::pair( vertexVector[ 1 ], 0 ) ); // badTwoModuleSolution.insert( std::pair( vertexVector[ 2 ], 0 ) ); // badTwoModuleSolution.insert( std::pair( vertexVector[ 3 ], 0 ) ); // badTwoModuleSolution.insert( std::pair( vertexVector[ 4 ], 0 ) ); // badTwoModuleSolution.insert( std::pair( vertexVector[ 5 ], 1 ) ); // badTwoModuleSolution.insert( std::pair( vertexVector[ 6 ], 1 ) ); // badTwoModuleSolution.insert( std::pair( vertexVector[ 7 ], 1 ) ); // badTwoModuleSolution.insert( std::pair( vertexVector[ 8 ], 0 ) ); // badTwoModuleSolution.insert( std::pair( vertexVector[ 9 ], 1 ) ); // badTwoModuleSolution.insert( std::pair( vertexVector[ 10 ], 1 ) ); // badTwoModuleSolution.insert( std::pair( vertexVector[ 11 ], 0 ) ); // // std::cout << "Modularity is " << CalculateModularity( network, &badTwoModuleSolution ) << " and should be " << 0.10 << std::endl; // std::cout << " Module 0 contains " << getNumberOfVerticesInModule( &badTwoModuleSolution, 0 ) << " nodes, should be 7.\n"; // std::cout << " Module 1 contains " << getNumberOfVerticesInModule( &badTwoModuleSolution, 1 ) << " nodes, should be 5.\n"; // // ToModuleMapType noInternalLinksThreeModuleSolution; // noInternalLinksThreeModuleSolution.insert( std::pair( vertexVector[ 0 ], 0 ) ); // noInternalLinksThreeModuleSolution.insert( std::pair( vertexVector[ 1 ], 2 ) ); // noInternalLinksThreeModuleSolution.insert( std::pair( vertexVector[ 2 ], 1 ) ); // noInternalLinksThreeModuleSolution.insert( std::pair( vertexVector[ 3 ], 0 ) ); // noInternalLinksThreeModuleSolution.insert( std::pair( vertexVector[ 4 ], 1 ) ); // noInternalLinksThreeModuleSolution.insert( std::pair( vertexVector[ 5 ], 2 ) ); // noInternalLinksThreeModuleSolution.insert( std::pair( vertexVector[ 6 ], 0 ) ); // noInternalLinksThreeModuleSolution.insert( std::pair( vertexVector[ 7 ], 0 ) ); // noInternalLinksThreeModuleSolution.insert( std::pair( vertexVector[ 8 ], 1 ) ); // noInternalLinksThreeModuleSolution.insert( std::pair( vertexVector[ 9 ], 2 ) ); // noInternalLinksThreeModuleSolution.insert( std::pair( vertexVector[ 10 ], 1 ) ); // noInternalLinksThreeModuleSolution.insert( std::pair( vertexVector[ 11 ], 0 ) ); // // std::cout << "Modularity is " << CalculateModularity( network, &noInternalLinksThreeModuleSolution ) << " and should be " << -0.34 << std::endl; // // std::cout << " Module 0 contains " << getNumberOfVerticesInModule( &noInternalLinksThreeModuleSolution, 0 ) << " nodes, should be 5.\n"; // std::cout << " Module 1 contains " << getNumberOfVerticesInModule( &noInternalLinksThreeModuleSolution, 1 ) << " nodes, should be 4.\n"; // std::cout << " Module 2 contains " << getNumberOfVerticesInModule( &noInternalLinksThreeModuleSolution, 2 ) << " nodes, should be 3.\n"; // -//} \ No newline at end of file +//} diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingManager.h b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingManager.h index 51767b3475..ab9a167fcf 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingManager.h +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingManager.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 mitkConnectomicsSimulatedAnnealingManager_h #define mitkConnectomicsSimulatedAnnealingManager_h #include #include #include #include "mitkCommon.h" #include "MitkDiffusionImagingExports.h" #include "mitkConnectomicsSimulatedAnnealingPermutationBase.h" namespace mitk { /** * \brief A class allow generic simulated annealing by using classes derived from ConnectomicsSimulatedAnnealingPermutationBase */ class MitkDiffusionImaging_EXPORT ConnectomicsSimulatedAnnealingManager : public itk::Object { public: /** Standard class typedefs. */ /** Method for creation through the object factory. */ mitkClassMacro(ConnectomicsSimulatedAnnealingManager, itk::Object); itkNewMacro(Self); // Decide whether to accept the change or not bool AcceptChange( double costBefore, double costAfter, double temperature ); // Run the permutations at different temperatures, where t_n = t_n-1 / stepSize void RunSimulatedAnnealing( double temperature, double stepSize ); // Set the permutation to be used void SetPermutation( mitk::ConnectomicsSimulatedAnnealingPermutationBase::Pointer permutation ); //void Testing( mitk::ConnectomicsNetwork::Pointer network ); protected: //////////////////// Functions /////////////////////// ConnectomicsSimulatedAnnealingManager(); ~ConnectomicsSimulatedAnnealingManager(); /////////////////////// Variables //////////////////////// // The permutation assigned to the simulated annealing manager mitk::ConnectomicsSimulatedAnnealingPermutationBase::Pointer m_Permutation; }; }// end namespace mitk -#endif // mitkConnectomicsSimulatedAnnealingManager_h \ No newline at end of file +#endif // mitkConnectomicsSimulatedAnnealingManager_h diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingPermutationBase.h b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingPermutationBase.h index ed540d53de..9d1b63b4a9 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingPermutationBase.h +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingPermutationBase.h @@ -1,74 +1,74 @@ /*=================================================================== 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 mitkConnectomicsSimulatedAnnealingPermutationBase_h #define mitkConnectomicsSimulatedAnnealingPermutationBase_h #include #include #include #include "mitkCommon.h" #include "MitkDiffusionImagingExports.h" #include "mitkConnectomicsSimulatedAnnealingCostFunctionBase.h" namespace mitk { /** * \brief Base class of a permutation to be used in simulated annealing */ class MitkDiffusionImaging_EXPORT ConnectomicsSimulatedAnnealingPermutationBase : public itk::Object { public: /** Standard class typedefs. */ /** Method for creation through the object factory. */ mitkClassMacro(ConnectomicsSimulatedAnnealingPermutationBase, itk::Object); itkNewMacro(Self); // Set the cost function void SetCostFunction( mitk::ConnectomicsSimulatedAnnealingCostFunctionBase::Pointer costFunction ); // Returns true if a cost function is assigned bool HasCostFunction( ); // Initialize the permutation virtual void Initialize(){}; // Do a permutation for a specific temperature virtual void Permutate( double temperature ){}; // Do clean up necessary after a permutation virtual void CleanUp(){}; protected: //////////////////// Functions /////////////////////// ConnectomicsSimulatedAnnealingPermutationBase(); ~ConnectomicsSimulatedAnnealingPermutationBase(); /////////////////////// Variables //////////////////////// // The cost function assigned to the permutation mitk::ConnectomicsSimulatedAnnealingCostFunctionBase::Pointer m_CostFunction; }; }// end namespace mitk -#endif // mitkConnectomicsSimulatedAnnealingPermutationBase_h \ No newline at end of file +#endif // mitkConnectomicsSimulatedAnnealingPermutationBase_h diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingPermutationModularity.cpp b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingPermutationModularity.cpp index 906badef35..74782ac528 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingPermutationModularity.cpp +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingPermutationModularity.cpp @@ -1,544 +1,544 @@ /*=================================================================== 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 "mitkConnectomicsSimulatedAnnealingPermutationModularity.h" #include "mitkConnectomicsSimulatedAnnealingCostFunctionModularity.h" #include "mitkConnectomicsSimulatedAnnealingManager.h" //for random number generation #include "vxl/core/vnl/vnl_random.h" #include "vxl/core/vnl/vnl_math.h" mitk::ConnectomicsSimulatedAnnealingPermutationModularity::ConnectomicsSimulatedAnnealingPermutationModularity() { } mitk::ConnectomicsSimulatedAnnealingPermutationModularity::~ConnectomicsSimulatedAnnealingPermutationModularity() { } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::SetNetwork( mitk::ConnectomicsNetwork::Pointer theNetwork ) { m_Network = theNetwork; } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::Initialize() { // create entry for every vertex std::vector< VertexDescriptorType > vertexVector = m_Network->GetVectorOfAllVertexDescriptors(); const int vectorSize = vertexVector.size(); for( int index( 0 ); index < vectorSize; index++) { m_BestSolution.insert( std::pair( vertexVector[ index ], 0 ) ); } // initialize with random distribution of n modules int n( 5 ); randomlyAssignNodesToModules( &m_BestSolution, n ); } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::Permutate( double temperature ) { ToModuleMapType currentSolution = m_BestSolution; ToModuleMapType currentBestSolution = m_BestSolution; int factor = 1; int numberOfVertices = m_BestSolution.size(); int singleNodeMaxNumber = factor * numberOfVertices * numberOfVertices; int moduleMaxNumber = factor * numberOfVertices; double currentBestCost = Evaluate( ¤tBestSolution ); // do singleNodeMaxNumber node permutations and evaluate for(int loop( 0 ); loop < singleNodeMaxNumber; loop++) { permutateMappingSingleNodeShift( ¤tSolution, m_Network ); if( AcceptChange( currentBestCost, Evaluate( ¤tSolution ), temperature ) ) { currentBestSolution = currentSolution; currentBestCost = Evaluate( ¤tBestSolution ); } } // do moduleMaxNumber module permutations for(int loop( 0 ); loop < moduleMaxNumber; loop++) { permutateMappingModuleChange( ¤tSolution, temperature, m_Network ); if( AcceptChange( currentBestCost, Evaluate( ¤tSolution ), temperature ) ) { currentBestSolution = currentSolution; currentBestCost = Evaluate( ¤tBestSolution ); } } // store the best solution after the run m_BestSolution = currentBestSolution; } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::CleanUp() { // delete empty modules, if any for( int loop( 0 ); loop < getNumberOfModules( &m_BestSolution ) ; loop++ ) { if( getNumberOfVerticesInModule( &m_BestSolution, loop ) < 1 ) { removeModule( &m_BestSolution, loop ); } } } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::permutateMappingSingleNodeShift( ToModuleMapType *vertexToModuleMap, mitk::ConnectomicsNetwork::Pointer network ) { const int nodeCount = vertexToModuleMap->size(); const int moduleCount = getNumberOfModules( vertexToModuleMap ); // the random number generators vnl_random rng( (unsigned int) rand() ); unsigned long randomNode = rng.lrand32( nodeCount - 1 ); // move the node either to any existing module, or to its own //unsigned long randomModule = rng.lrand32( moduleCount ); unsigned long randomModule = rng.lrand32( moduleCount - 1 ); // do some sanity checks if ( nodeCount < 2 ) { // no sense in doing anything return; } const std::vector< VertexDescriptorType > allNodesVector = network->GetVectorOfAllVertexDescriptors(); ToModuleMapType::iterator iter = vertexToModuleMap->find( allNodesVector[ randomNode ] ); const int previousModuleNumber = iter->second; // if we move the node to its own module, do nothing if( previousModuleNumber == randomModule ) { return; } iter->second = randomModule; if( getNumberOfVerticesInModule( vertexToModuleMap, previousModuleNumber ) < 1 ) { removeModule( vertexToModuleMap, previousModuleNumber ); } } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::permutateMappingModuleChange( ToModuleMapType *vertexToModuleMap, double currentTemperature, mitk::ConnectomicsNetwork::Pointer network ) { //the random number generators vnl_random rng( (unsigned int) rand() ); //randomly generate threshold const double threshold = rng.drand64( 0.0 , 1.0); //for deciding whether to join two modules or split one double splitThreshold = 0.5; //stores whether to join or two split bool joinModules( false ); //select random module int numberOfModules = getNumberOfModules( vertexToModuleMap ); unsigned long randomModuleA = rng.lrand32( numberOfModules - 1 ); //select the second module to join, if joining unsigned long randomModuleB = rng.lrand32( numberOfModules - 1 ); if( ( threshold < splitThreshold ) && ( randomModuleA != randomModuleB ) ) { joinModules = true; } if( joinModules ) { // this being an kommutative operation, we will always join B to A joinTwoModules( vertexToModuleMap, randomModuleA, randomModuleB ); //eliminate the empty module removeModule( vertexToModuleMap, randomModuleB ); } else { //split module splitModule( vertexToModuleMap, currentTemperature, network, randomModuleA ); } } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::joinTwoModules( ToModuleMapType *vertexToModuleMap, int moduleA, int moduleB ) { ToModuleMapType::iterator iter = vertexToModuleMap->begin(); ToModuleMapType::iterator end = vertexToModuleMap->end(); while( iter != end ) { // if vertex belongs to module B move it to A if( iter->second == moduleB ) { iter->second = moduleA; } iter++; }// end while( iter != end ) } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::splitModule( ToModuleMapType *vertexToModuleMap, double currentTemperature, mitk::ConnectomicsNetwork::Pointer network, int moduleToSplit ) { if( m_Depth == 0 ) { // do nothing return; } // if the module contains only one node, no more division is sensible if( getNumberOfVerticesInModule( vertexToModuleMap, moduleToSplit ) < 2 ) { // do nothing return; } // create subgraph of the module, that is to be splitted mitk::ConnectomicsNetwork::Pointer subNetwork = mitk::ConnectomicsNetwork::New(); VertexToVertexMapType graphToSubgraphVertexMap; VertexToVertexMapType subgraphToGraphVertexMap; extractModuleSubgraph( vertexToModuleMap, network, moduleToSplit, subNetwork, &graphToSubgraphVertexMap, &subgraphToGraphVertexMap ); // The submap ToModuleMapType vertexToModuleSubMap; // copy vertices VertexToVertexMapType::iterator iter = graphToSubgraphVertexMap.begin(); VertexToVertexMapType::iterator end = graphToSubgraphVertexMap.end(); // run simulated annealing on the subgraph to determine how the module should be split if( m_Depth > 0 && m_StepSize > 0 ) { mitk::ConnectomicsSimulatedAnnealingManager::Pointer manager = mitk::ConnectomicsSimulatedAnnealingManager::New(); mitk::ConnectomicsSimulatedAnnealingPermutationModularity::Pointer permutation = mitk::ConnectomicsSimulatedAnnealingPermutationModularity::New(); mitk::ConnectomicsSimulatedAnnealingCostFunctionModularity::Pointer costFunction = mitk::ConnectomicsSimulatedAnnealingCostFunctionModularity::New(); permutation->SetCostFunction( costFunction.GetPointer() ); permutation->SetNetwork( subNetwork ); permutation->SetDepth( m_Depth - 1 ); permutation->SetStepSize( m_StepSize * 2 ); manager->SetPermutation( permutation.GetPointer() ); manager->RunSimulatedAnnealing( currentTemperature, m_StepSize * 2 ); vertexToModuleSubMap = permutation->GetMapping(); } // now carry the information over to the original map std::vector< int > moduleTranslationVector; moduleTranslationVector.resize( getNumberOfModules( &vertexToModuleSubMap ), 0 ); int originalNumber = getNumberOfModules( vertexToModuleMap ); // the new parts are added at the end for(int index( 0 ); index < moduleTranslationVector.size() ; index++) { moduleTranslationVector[ index ] = originalNumber + index; } ToModuleMapType::iterator iter2 = vertexToModuleSubMap.begin(); ToModuleMapType::iterator end2 = vertexToModuleSubMap.end(); while( iter2 != end2 ) { // translate vertex descriptor from subgraph to graph VertexDescriptorType key = subgraphToGraphVertexMap.find( iter2->first )->second; // translate module number from subgraph to graph int value = moduleTranslationVector[ iter2->second ]; // change the corresponding entry vertexToModuleMap->find( key )->second = value; iter2++; } // remove the now empty module, that was splitted removeModule( vertexToModuleMap, moduleToSplit ); } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::extractModuleSubgraph( ToModuleMapType *vertexToModuleMap, mitk::ConnectomicsNetwork::Pointer network, int moduleToSplit, mitk::ConnectomicsNetwork::Pointer subNetwork, VertexToVertexMapType* graphToSubgraphVertexMap, VertexToVertexMapType* subgraphToGraphVertexMap ) { const std::vector< VertexDescriptorType > allNodesVector = network->GetVectorOfAllVertexDescriptors(); // add vertices to subgraph for( int nodeNumber( 0 ); nodeNumber < allNodesVector.size() ; nodeNumber++) { int correspondingModule = vertexToModuleMap->find( allNodesVector[ nodeNumber ] )->second; if( moduleToSplit == vertexToModuleMap->find( allNodesVector[ nodeNumber ] )->second ) { int id = network->GetNode( allNodesVector[ nodeNumber ] ).id; VertexDescriptorType newVertex = subNetwork->AddVertex( id ); graphToSubgraphVertexMap->insert( std::pair( allNodesVector[ nodeNumber ], newVertex ) ); subgraphToGraphVertexMap->insert( std::pair( newVertex, allNodesVector[ nodeNumber ] ) ); } } // add edges to subgraph VertexToVertexMapType::iterator iter = graphToSubgraphVertexMap->begin(); VertexToVertexMapType::iterator end = graphToSubgraphVertexMap->end(); while( iter != end ) { const std::vector< VertexDescriptorType > adjacentNodexVector = network->GetVectorOfAdjacentNodes( iter->first ); for( int adjacentNodeNumber( 0 ); adjacentNodeNumber < adjacentNodexVector.size() ; adjacentNodeNumber++) { // if the adjacent vertex is part of the subgraph, // add edge, if it does not exist yet, else do nothing VertexDescriptorType adjacentVertex = adjacentNodexVector[ adjacentNodeNumber ]; if( graphToSubgraphVertexMap->count( adjacentVertex ) > 0 ) { if( !subNetwork->EdgeExists( iter->second, graphToSubgraphVertexMap->find( adjacentVertex )->second ) ) { //edge exists in parent network, but not yet in sub network const VertexDescriptorType vertexA = iter->second; const VertexDescriptorType vertexB = graphToSubgraphVertexMap->find( adjacentVertex )->second; const int sourceID = network->GetNode( vertexA ).id; const int targetID = network->GetNode( vertexB ).id; const int weight = network->GetEdge( iter->first, graphToSubgraphVertexMap->find( adjacentVertex )->first ).weight; subNetwork->AddEdge( vertexA , vertexB, sourceID, targetID, weight ); } } } iter++; }// end while( iter != end ) } int mitk::ConnectomicsSimulatedAnnealingPermutationModularity::getNumberOfModules( ToModuleMapType *vertexToModuleMap ) const { int maxModule( 0 ); ToModuleMapType::iterator iter = vertexToModuleMap->begin(); ToModuleMapType::iterator end = vertexToModuleMap->end(); while( iter != end ) { if( iter->second > maxModule ) { maxModule = iter->second; } iter++; } return maxModule + 1; } int mitk::ConnectomicsSimulatedAnnealingPermutationModularity::getNumberOfVerticesInModule( ToModuleMapType *vertexToModuleMap, int module ) const { int number( 0 ); ToModuleMapType::iterator iter = vertexToModuleMap->begin(); ToModuleMapType::iterator end = vertexToModuleMap->end(); while( iter != end ) { if( iter->second == module ) { number++; } iter++; } return number; } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::removeModule( ToModuleMapType *vertexToModuleMap, int module ) { int lastModuleNumber = getNumberOfModules( vertexToModuleMap ) - 1; if( module == lastModuleNumber ) { // no need to do anything, the last module is deleted "automatically" return; } if( getNumberOfVerticesInModule( vertexToModuleMap, module ) > 0 ) { MBI_WARN << "Trying to remove non-empty module"; return; } ToModuleMapType::iterator iter = vertexToModuleMap->begin(); ToModuleMapType::iterator end = vertexToModuleMap->end(); while( iter != end ) { if( iter->second == lastModuleNumber ) { // renumber last module to to-be-deleted module iter->second = module; } iter++; } } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::randomlyAssignNodesToModules( ToModuleMapType *vertexToModuleMap, int numberOfIntendedModules ) { // we make sure that each intended module contains *at least* one node // thus if more modules are asked for than node exists we will only generate // as many modules as there are nodes if( numberOfIntendedModules > vertexToModuleMap->size() ) { MBI_ERROR << "Tried to generate more modules than vertices were provided"; numberOfIntendedModules = vertexToModuleMap->size(); } //the random number generators vnl_random rng( (unsigned int) rand() ); std::vector< int > histogram; std::vector< int > nodeList; histogram.resize( numberOfIntendedModules, 0 ); nodeList.resize( vertexToModuleMap->size(), 0 ); int numberOfVertices = vertexToModuleMap->size(); //randomly distribute nodes to modules for( int nodeIndex( 0 ); nodeIndex < nodeList.size(); nodeIndex++ ) { //select random module nodeList[ nodeIndex ] = rng.lrand32( numberOfIntendedModules - 1 ); histogram[ nodeList[ nodeIndex ] ]++; } // make sure no module contains no node, if one does assign it one of a random module // that does contain at least two for( int moduleIndex( 0 ); moduleIndex < histogram.size(); moduleIndex++ ) { while( histogram[ moduleIndex ] == 0 ) { int randomNodeIndex = rng.lrand32( numberOfVertices - 1 ); if( histogram[ nodeList[ randomNodeIndex ] ] > 1 ) { histogram[ moduleIndex ]++; histogram[ nodeList[ randomNodeIndex ] ]--; nodeList[ randomNodeIndex ] = moduleIndex; } } } ToModuleMapType::iterator iter = vertexToModuleMap->begin(); ToModuleMapType::iterator end = vertexToModuleMap->end(); for( int index( 0 ); ( iter != end ) && ( index < nodeList.size() ); index++, iter++ ) { iter->second = nodeList[ index ] ; } } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::SetMapping( ToModuleMapType mapping ) { m_BestSolution = mapping; } mitk::ConnectomicsSimulatedAnnealingPermutationModularity::ToModuleMapType mitk::ConnectomicsSimulatedAnnealingPermutationModularity::GetMapping() { return m_BestSolution; } double mitk::ConnectomicsSimulatedAnnealingPermutationModularity::Evaluate( ToModuleMapType* mapping ) const { mitk::ConnectomicsSimulatedAnnealingCostFunctionModularity* costMapping = dynamic_cast( m_CostFunction.GetPointer() ); if( costMapping ) { return costMapping->Evaluate( m_Network, mapping ); } else { return 0; } } bool mitk::ConnectomicsSimulatedAnnealingPermutationModularity::AcceptChange( double costBefore, double costAfter, double temperature ) const { if( costAfter <= costBefore ) {// if cost is lower after return true; } //the random number generators vnl_random rng( (unsigned int) rand() ); //randomly generate threshold const double threshold = rng.drand64( 0.0 , 1.0); //the likelihood of acceptance double likelihood = std::exp( - ( costAfter - costBefore ) / temperature ); if( threshold < likelihood ) { return true; } return false; } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::SetDepth( int depth ) { m_Depth = depth; } void mitk::ConnectomicsSimulatedAnnealingPermutationModularity::SetStepSize( double size ) { m_StepSize = size; -} \ No newline at end of file +} diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingPermutationModularity.h b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingPermutationModularity.h index 8e3401f57a..c88a3cc1b6 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingPermutationModularity.h +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSimulatedAnnealingPermutationModularity.h @@ -1,139 +1,139 @@ /*=================================================================== 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 mitkConnectomicsSimulatedAnnealingPermutationModularity_h #define mitkConnectomicsSimulatedAnnealingPermutationModularity_h #include "mitkConnectomicsSimulatedAnnealingPermutationBase.h" #include "mitkConnectomicsNetwork.h" namespace mitk { /** * \brief A class providing permutations for the calculation of modularity using simulated annealing */ class MitkDiffusionImaging_EXPORT ConnectomicsSimulatedAnnealingPermutationModularity : public mitk::ConnectomicsSimulatedAnnealingPermutationBase { public: typedef mitk::ConnectomicsNetwork::VertexDescriptorType VertexDescriptorType; typedef std::map< VertexDescriptorType, int > ToModuleMapType; typedef std::map< VertexDescriptorType, VertexDescriptorType > VertexToVertexMapType; /** Standard class typedefs. */ /** Method for creation through the object factory. */ mitkClassMacro(ConnectomicsSimulatedAnnealingPermutationModularity, itk::Object); itkNewMacro(Self); // Initialize the permutation virtual void Initialize(); // Do a permutation for a specific temperature virtual void Permutate( double temperature ); // Do clean up necessary after a permutation virtual void CleanUp(); // set the network permutation is to be run upon void SetNetwork( mitk::ConnectomicsNetwork::Pointer theNetwork ); // Get the number of modules the graph has ( highest number - 1 ) int getNumberOfModules( ToModuleMapType *vertexToModuleMap ) const; // Get the number of vertices belonging to a given module int getNumberOfVerticesInModule( ToModuleMapType *vertexToModuleMap, int module ) const; // Set the mapping void SetMapping( ToModuleMapType mapping ); // Get the mapping ToModuleMapType GetMapping(); // Set depth void SetDepth( int depth ); // Set stepSize void SetStepSize( double size ); protected: //////////////////// Functions /////////////////////// ConnectomicsSimulatedAnnealingPermutationModularity(); ~ConnectomicsSimulatedAnnealingPermutationModularity(); // This function moves one single node from a module to another void permutateMappingSingleNodeShift( ToModuleMapType *vertexToModuleMap, mitk::ConnectomicsNetwork::Pointer network ); // This function splits and joins modules void permutateMappingModuleChange( ToModuleMapType *vertexToModuleMap, double currentTemperature, mitk::ConnectomicsNetwork::Pointer network ); // join the two given modules to a single one void joinTwoModules( ToModuleMapType *vertexToModuleMap, int moduleA, int moduleB ); // split the given module recursively up to a certain level // first randomly assigns nodes and then starts another simulated annealing // on the sub network, as long as depthOfModuleChange > 0 void splitModule( ToModuleMapType *vertexToModuleMap, double currentTemperature, mitk::ConnectomicsNetwork::Pointer network, int moduleToSplit ); // Extract the subgraph of a network containing all nodes // of a given module and the egdes between them void extractModuleSubgraph( ToModuleMapType *vertexToModuleMap, mitk::ConnectomicsNetwork::Pointer network, int moduleToSplit, mitk::ConnectomicsNetwork::Pointer subNetwork, VertexToVertexMapType* graphToSubgraphVertexMap, VertexToVertexMapType* subgraphToGraphVertexMap ); // Remove empty modules by moving all nodes of the highest module to the given module void removeModule( ToModuleMapType *vertexToModuleMap, int module ); // Randomly assign nodes to modules, this makes sure each module contains at least one node // as long as numberOfIntendedModules < number of nodes void randomlyAssignNodesToModules(ToModuleMapType *vertexToModuleMap, int numberOfIntendedModules ); // Evaluate mapping using a modularity cost function double Evaluate( ToModuleMapType* mapping ) const; // Whether to accept the permutation bool AcceptChange( double costBefore, double costAfter, double temperature ) const; // the current best solution ToModuleMapType m_BestSolution; // the network mitk::ConnectomicsNetwork::Pointer m_Network; // How many levels of recursive calls can be gone down int m_Depth; // The step size for recursive configuring of simulated annealing manager double m_StepSize; }; }// end namespace mitk -#endif // mitkConnectomicsSimulatedAnnealingPermutationModularity_h \ No newline at end of file +#endif // mitkConnectomicsSimulatedAnnealingPermutationModularity_h diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSyntheticNetworkGenerator.cpp b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSyntheticNetworkGenerator.cpp index 49f19f5fda..9dff9036c6 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSyntheticNetworkGenerator.cpp +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSyntheticNetworkGenerator.cpp @@ -1,363 +1,363 @@ /*=================================================================== 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 "mitkConnectomicsSyntheticNetworkGenerator.h" #include #include #include "mitkConnectomicsConstantsManager.h" #include //for random number generation #include "vxl/core/vnl/vnl_random.h" #include "vxl/core/vnl/vnl_math.h" mitk::ConnectomicsSyntheticNetworkGenerator::ConnectomicsSyntheticNetworkGenerator() : m_LastGenerationWasSuccess( false ) { } mitk::ConnectomicsSyntheticNetworkGenerator::~ConnectomicsSyntheticNetworkGenerator() { } mitk::ConnectomicsNetwork::Pointer mitk::ConnectomicsSyntheticNetworkGenerator::CreateSyntheticNetwork(int networkTypeId, int paramterOne, double parameterTwo) { mitk::ConnectomicsNetwork::Pointer network = mitk::ConnectomicsNetwork::New(); m_LastGenerationWasSuccess = false; // give the network an artificial geometry network->SetGeometry( this->GenerateDefaultGeometry() ); switch (networkTypeId) { case 0: GenerateSyntheticCubeNetwork( network, paramterOne, parameterTwo ); break; case 1: GenerateSyntheticCenterToSurfaceNetwork( network, paramterOne, parameterTwo ); break; case 2: GenerateSyntheticRandomNetwork( network, paramterOne, parameterTwo ); break; case 3: //GenerateSyntheticScaleFreeNetwork( network, 1000 ); break; case 4: //GenerateSyntheticSmallWorldNetwork( network, 1000 ); break; default: MBI_ERROR << "Unrecognized Network ID"; } network->UpdateBounds(); return network; } mitk::Geometry3D::Pointer mitk::ConnectomicsSyntheticNetworkGenerator::GenerateDefaultGeometry() { mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); double zero( 0.0 ); double one( 1.0 ); // origin = {0,0,0} mitk::Point3D origin; origin[0] = zero; origin[1] = zero; origin[2] = zero; geometry->SetOrigin(origin); // spacing = {1,1,1} float spacing[3]; spacing[0] = one; spacing[1] = one; spacing[2] = one; geometry->SetSpacing(spacing); // transform vtkMatrix4x4* transformMatrix = vtkMatrix4x4::New(); transformMatrix->SetElement(0,0,one); transformMatrix->SetElement(1,0,zero); transformMatrix->SetElement(2,0,zero); transformMatrix->SetElement(0,1,zero); transformMatrix->SetElement(1,1,one); transformMatrix->SetElement(2,1,zero); transformMatrix->SetElement(0,2,zero); transformMatrix->SetElement(1,2,zero); transformMatrix->SetElement(2,2,one); transformMatrix->SetElement(0,3,origin[0]); transformMatrix->SetElement(1,3,origin[1]); transformMatrix->SetElement(2,3,origin[2]); transformMatrix->SetElement(3,3,1); geometry->SetIndexToWorldTransformByVtkMatrix( transformMatrix ); geometry->SetImageGeometry(true); return geometry; } void mitk::ConnectomicsSyntheticNetworkGenerator::GenerateSyntheticCubeNetwork( mitk::ConnectomicsNetwork::Pointer network, int cubeExtent, double distance ) { // map for storing the conversion from indices to vertex descriptor std::map< int, mitk::ConnectomicsNetwork::VertexDescriptorType > idToVertexMap; int vertexID(0); for( int loopX( 0 ); loopX < cubeExtent; loopX++ ) { for( int loopY( 0 ); loopY < cubeExtent; loopY++ ) { for( int loopZ( 0 ); loopZ < cubeExtent; loopZ++ ) { std::vector< float > position; std::string label; std::stringstream labelStream; labelStream << vertexID; label = labelStream.str(); position.push_back( loopX * distance ); position.push_back( loopY * distance ); position.push_back( loopZ * distance ); mitk::ConnectomicsNetwork::VertexDescriptorType newVertex = network->AddVertex( vertexID ); network->SetLabel( newVertex, label ); network->SetCoordinates( newVertex, position ); if ( idToVertexMap.count( vertexID ) > 0 ) { MITK_ERROR << "Aborting network creation, duplicate vertex ID generated."; m_LastGenerationWasSuccess = false; return; } idToVertexMap.insert( std::pair< int, mitk::ConnectomicsNetwork::VertexDescriptorType >( vertexID, newVertex) ); vertexID++; } } } int edgeID(0), edgeSourceID(0), edgeTargetID(0); // uniform weight of one int edgeWeight(1); mitk::ConnectomicsNetwork::VertexDescriptorType source; mitk::ConnectomicsNetwork::VertexDescriptorType target; for( int loopX( 0 ); loopX < cubeExtent; loopX++ ) { for( int loopY( 0 ); loopY < cubeExtent; loopY++ ) { for( int loopZ( 0 ); loopZ < cubeExtent; loopZ++ ) { // to avoid creating an edge twice (this being an undirected graph) we only generate // edges in three directions, the others will be supplied by the corresponding nodes if( loopX != 0 ) { edgeTargetID = edgeSourceID - cubeExtent * cubeExtent; source = idToVertexMap.find( edgeSourceID )->second; target = idToVertexMap.find( edgeTargetID )->second; network->AddEdge( source, target, edgeSourceID, edgeTargetID, edgeWeight); edgeID++; } if( loopY != 0 ) { edgeTargetID = edgeSourceID - cubeExtent; source = idToVertexMap.find( edgeSourceID )->second; target = idToVertexMap.find( edgeTargetID )->second; network->AddEdge( source, target, edgeSourceID, edgeTargetID, edgeWeight); edgeID++; } if( loopZ != 0 ) { edgeTargetID = edgeSourceID - 1; source = idToVertexMap.find( edgeSourceID )->second; target = idToVertexMap.find( edgeTargetID )->second; network->AddEdge( source, target, edgeSourceID, edgeTargetID, edgeWeight); edgeID++; } edgeSourceID++; } // end for( int loopZ( 0 ); loopZ < cubeExtent; loopZ++ ) } // end for( int loopY( 0 ); loopY < cubeExtent; loopY++ ) } // end for( int loopX( 0 ); loopX < cubeExtent; loopX++ ) m_LastGenerationWasSuccess = true; } void mitk::ConnectomicsSyntheticNetworkGenerator::GenerateSyntheticCenterToSurfaceNetwork( mitk::ConnectomicsNetwork::Pointer network, int numberOfPoints, double radius ) { //the random number generators unsigned int randomOne = (unsigned int) rand(); unsigned int randomTwo = (unsigned int) rand(); vnl_random rng( (unsigned int) rand() ); vnl_random rng2( (unsigned int) rand() ); mitk::ConnectomicsNetwork::VertexDescriptorType centerVertex; int vertexID(0); { //add center vertex std::vector< float > position; std::string label; std::stringstream labelStream; labelStream << vertexID; label = labelStream.str(); position.push_back( 0 ); position.push_back( 0 ); position.push_back( 0 ); centerVertex = network->AddVertex( vertexID ); network->SetLabel( centerVertex, label ); network->SetCoordinates( centerVertex, position ); }//end add center vertex // uniform weight of one int edgeWeight(1); mitk::ConnectomicsNetwork::VertexDescriptorType source; mitk::ConnectomicsNetwork::VertexDescriptorType target; //add vertices on sphere surface for( int loopID( 1 ); loopID < numberOfPoints; loopID++ ) { std::vector< float > position; std::string label; std::stringstream labelStream; labelStream << loopID; label = labelStream.str(); //generate random, uniformly distributed points on a sphere surface const double uVariable = rng.drand64( 0.0 , 1.0); const double vVariable = rng.drand64( 0.0 , 1.0); const double phi = 2 * vnl_math::pi * uVariable; const double theta = std::acos( 2 * vVariable - 1 ); double xpos = radius * std::cos( phi ) * std::sin( theta ); double ypos = radius * std::sin( phi ) * std::sin( theta ); double zpos = radius * std::cos( theta ); position.push_back( xpos ); position.push_back( ypos ); position.push_back( zpos ); mitk::ConnectomicsNetwork::VertexDescriptorType newVertex = network->AddVertex( loopID ); network->SetLabel( newVertex, label ); network->SetCoordinates( newVertex, position ); network->AddEdge( newVertex, centerVertex, loopID, 0, edgeWeight); } m_LastGenerationWasSuccess = true; } void mitk::ConnectomicsSyntheticNetworkGenerator::GenerateSyntheticRandomNetwork( mitk::ConnectomicsNetwork::Pointer network, int numberOfPoints, double threshold ) { // as the surface is proportional to the square of the radius the density stays the same double radius = 5 * std::sqrt( (float) numberOfPoints ); //the random number generators unsigned int randomOne = (unsigned int) rand(); unsigned int randomTwo = (unsigned int) rand(); vnl_random rng( (unsigned int) rand() ); vnl_random rng2( (unsigned int) rand() ); // map for storing the conversion from indices to vertex descriptor std::map< int, mitk::ConnectomicsNetwork::VertexDescriptorType > idToVertexMap; //add vertices on sphere surface for( int loopID( 0 ); loopID < numberOfPoints; loopID++ ) { std::vector< float > position; std::string label; std::stringstream labelStream; labelStream << loopID; label = labelStream.str(); //generate random, uniformly distributed points on a sphere surface const double uVariable = rng.drand64( 0.0 , 1.0); const double vVariable = rng.drand64( 0.0 , 1.0); const double phi = 2 * vnl_math::pi * uVariable; const double theta = std::acos( 2 * vVariable - 1 ); double xpos = radius * std::cos( phi ) * std::sin( theta ); double ypos = radius * std::sin( phi ) * std::sin( theta ); double zpos = radius * std::cos( theta ); position.push_back( xpos ); position.push_back( ypos ); position.push_back( zpos ); mitk::ConnectomicsNetwork::VertexDescriptorType newVertex = network->AddVertex( loopID ); network->SetLabel( newVertex, label ); network->SetCoordinates( newVertex, position ); if ( idToVertexMap.count( loopID ) > 0 ) { MITK_ERROR << "Aborting network creation, duplicate vertex ID generated."; m_LastGenerationWasSuccess = false; return; } idToVertexMap.insert( std::pair< int, mitk::ConnectomicsNetwork::VertexDescriptorType >( loopID, newVertex) ); } int edgeID(0); // uniform weight of one int edgeWeight(1); mitk::ConnectomicsNetwork::VertexDescriptorType source; mitk::ConnectomicsNetwork::VertexDescriptorType target; for( int loopID( 0 ); loopID < numberOfPoints; loopID++ ) { // to avoid creating an edge twice (this being an undirected graph) we only // potentially generate edges with all nodes with a bigger ID for( int innerLoopID( loopID ); innerLoopID < numberOfPoints; innerLoopID++ ) { if( rng.drand64( 0.0 , 1.0) > threshold) { // do nothing } else { source = idToVertexMap.find( loopID )->second; target = idToVertexMap.find( innerLoopID )->second; network->AddEdge( source, target, loopID, innerLoopID, edgeWeight); edgeID++; } } // end for( int innerLoopID( loopID ); innerLoopID < numberOfPoints; innerLoopID++ ) } // end for( int loopID( 0 ); loopID < numberOfPoints; loopID++ ) m_LastGenerationWasSuccess = true; } bool mitk::ConnectomicsSyntheticNetworkGenerator::WasGenerationSuccessfull() { return m_LastGenerationWasSuccess; -} \ No newline at end of file +} diff --git a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSyntheticNetworkGenerator.h b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSyntheticNetworkGenerator.h index f56bdd0b82..793d068c6b 100644 --- a/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSyntheticNetworkGenerator.h +++ b/Modules/DiffusionImaging/Algorithms/Connectomics/mitkConnectomicsSyntheticNetworkGenerator.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 mitkConnectomicsSyntheticNetworkGenerator_h #define mitkConnectomicsSyntheticNetworkGenerator_h #include #include #include #include "mitkCommon.h" #include "mitkImage.h" #include "mitkConnectomicsNetwork.h" #include "MitkDiffusionImagingExports.h" namespace mitk { /** * \brief A class to generate synthetic networks */ class MitkDiffusionImaging_EXPORT ConnectomicsSyntheticNetworkGenerator : public itk::Object { public: /** Standard class typedefs. */ /** Method for creation through the object factory. */ mitkClassMacro(ConnectomicsSyntheticNetworkGenerator, itk::Object); itkNewMacro(Self); /** Create Synthetic Networks */ mitk::ConnectomicsNetwork::Pointer CreateSyntheticNetwork(int networkTypeId, int paramterOne, double parameterTwo); /** Return whether the last attempted network generation was a success*/ bool WasGenerationSuccessfull(); protected: //////////////////// Functions /////////////////////// ConnectomicsSyntheticNetworkGenerator(); ~ConnectomicsSyntheticNetworkGenerator(); /** Generate a default geometry for synthetic images */ mitk::Geometry3D::Pointer GenerateDefaultGeometry(); /** Generate a synthetic cube (regular lattice) network */ void GenerateSyntheticCubeNetwork( mitk::ConnectomicsNetwork::Pointer network, int cubeExtent, double distance ); /** Generate a highly heterogenic network * * This is achieved by generating a center vertex and vertices on * a sphere surface, which are all only connected to the center * vertex. */ void GenerateSyntheticCenterToSurfaceNetwork( mitk::ConnectomicsNetwork::Pointer network, int numberOfPoints, double radius ); /** Generate a random network without specific characteristics * * This is achieved by generating vertices and then deciding whether to * specific vertices are connected by comparing a random number to the threshold */ void GenerateSyntheticRandomNetwork( mitk::ConnectomicsNetwork::Pointer network, int numberOfPoints, double threshold ); /////////////////////// Variables //////////////////////// /** Store whether the network generated last was generated properly */ bool m_LastGenerationWasSuccess; }; }// end namespace mitk -#endif // _mitkConnectomicsSyntheticNetworkGenerator_H_INCLUDED \ No newline at end of file +#endif // _mitkConnectomicsSyntheticNetworkGenerator_H_INCLUDED diff --git a/Modules/DiffusionImaging/Algorithms/itkDistanceMapFilter.txx b/Modules/DiffusionImaging/Algorithms/itkDistanceMapFilter.txx index 786d50a1d8..bc432c64fe 100644 --- a/Modules/DiffusionImaging/Algorithms/itkDistanceMapFilter.txx +++ b/Modules/DiffusionImaging/Algorithms/itkDistanceMapFilter.txx @@ -1,85 +1,85 @@ /*=================================================================== 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 _itkDistanceMapFilter_txx #define _itkDistanceMapFilter_txx #include "itkDistanceMapFilter.h" #include "mitkProgressBar.h" #include namespace itk { template< class TInputImage, class TOutputImage > DistanceMapFilter::DistanceMapFilter() { } template< class TInputImage, class TOutputImage > DistanceMapFilter::~DistanceMapFilter() { } template< class TInputImage, class TOutputImage > void DistanceMapFilter::GenerateData() { //----------------------------------------------------------------------// // Progress bar // //----------------------------------------------------------------------// //mitk::ProgressBar::GetInstance()->AddStepsToDo( 3 ); typedef itk::SignedMaurerDistanceMapImageFilter DistanceFilterType; typename DistanceFilterType::Pointer dFilter = DistanceFilterType::New(); dFilter->SetInput(this->GetInput()); dFilter->SetUseImageSpacing(true); dFilter->SetSquaredDistance(false); dFilter->SetInsideIsPositive(true); dFilter->Update(); typename OutputImageType::Pointer outputImg = dFilter->GetOutput(); typedef itk::ImageRegionIterator ImageIteratorType; ImageIteratorType outIt(outputImg, outputImg->GetRequestedRegion()); outIt.GoToBegin(); while(!outIt.IsAtEnd()) { typename OutputImageType::PixelType p = outIt.Get(); p *= -1; outIt.Set(p); ++outIt; } Superclass::SetNthOutput( 0, outputImg ); } } -#endif // _itkDistanceMapFilter_txx \ No newline at end of file +#endif // _itkDistanceMapFilter_txx diff --git a/Modules/DiffusionImaging/IODataStructures/ConnectomicsNetwork/mitkConnectomicsConstantsManager.cpp b/Modules/DiffusionImaging/IODataStructures/ConnectomicsNetwork/mitkConnectomicsConstantsManager.cpp index e29ce90417..941d746299 100644 --- a/Modules/DiffusionImaging/IODataStructures/ConnectomicsNetwork/mitkConnectomicsConstantsManager.cpp +++ b/Modules/DiffusionImaging/IODataStructures/ConnectomicsNetwork/mitkConnectomicsConstantsManager.cpp @@ -1,59 +1,59 @@ /*=================================================================== 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_ConnectomicsConstantsManager_CPP //#define _MITK_ConnectomicsConstantsManager_CPP #include "mitkConnectomicsConstantsManager.h" //============== String and other constants =================== //==== Error messages ==== const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_TRIED_TO_ACCESS_INVALID_HISTOGRAM = "Tried to access invalid histogram."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_PASSED_NEGATIVE_INDEX_TO_HISTOGRAM = "Passed negative index to histogram."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_OUTSIDE_INTEGER_RANGE = "Tried to access histogram vector outside integer range."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_BEYOND_SCOPE = "Tried to access histogram vector for value beyond scope: "; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_INVALID_MAPPING = "Invalid mapping strategy selected."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_INVALID_DIMENSION_NEED_3 = "Invalid dimension, need dimension 3."; //==== Warnings ==== const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_ZERO_DISTANCE_NODES = "There are nodes which are not distance 0 to themselves."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_UNIMPLEMENTED_FEATURE = "You are trying to use an as of yet unimplemented feature."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_MORE_POINTS_THAN_PRESENT = "Trying to estimate using more points than are present."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_ESTIMATING_LESS_THAN_2 = "Trying to estimate using less than two points."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_ESTIMATING_BEYOND_END = "Trying to estimate using points beyond track end."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_ESTIMATING_BEYOND_START = "Trying to estimate using points beyond track start."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_DID_NOT_FIND_WHITE = "Did not find a non white matter label."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_NOT_EXTEND_TO_WHITE = "Could not extend to non white matter."; //==== Information ==== const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_INFO_NETWORK_CREATED = "Network has been created."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_NETWORK_NOT_VALID = "Network not valid."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_NETWORK_DISCONNECTED = "Network is disconnected."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_CAN_NOT_COMPUTE_EFFICIENCY = "Can not compute efficiency. "; //==== GUI ==== const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_DASH = "-"; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_CONNECTOMICS_CREATION = "Connectomics Creation"; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_SELECTION_WARNING = "Please load and select exactly one parcellation image and one fiber image before starting network creation."; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_PERFORMING_IMAGE_PROCESSING_FOR_IMAGE = "Performing image processing for image "; //==== Properties ==== const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_PROPERTY_DEFAULT_RGBA_NAME = "rgbaImage"; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_PROPERTY_NAME = "name"; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_PROPERTY_VOLUMERENDERING = "volumerendering"; const char* mitk::ConnectomicsConstantsManager::CONNECTOMICS_PROPERTY_DEFAULT_CNF_NAME = "Connectomics network"; -//#endif /* _MITK_ConnectomicsConstantsManager_CPP */ \ No newline at end of file +//#endif /* _MITK_ConnectomicsConstantsManager_CPP */ diff --git a/Modules/DiffusionImaging/IODataStructures/ConnectomicsNetwork/mitkConnectomicsConstantsManager.h b/Modules/DiffusionImaging/IODataStructures/ConnectomicsNetwork/mitkConnectomicsConstantsManager.h index fc889dce9e..c74bdbbba2 100644 --- a/Modules/DiffusionImaging/IODataStructures/ConnectomicsNetwork/mitkConnectomicsConstantsManager.h +++ b/Modules/DiffusionImaging/IODataStructures/ConnectomicsNetwork/mitkConnectomicsConstantsManager.h @@ -1,84 +1,84 @@ /*=================================================================== 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_ConnectomicsConstantsManager_H #define _MITK_ConnectomicsConstantsManager_H #include "MitkDiffusionImagingExports.h" namespace mitk { /** \brief The XML consts for reading and writing */ class MitkDiffusionImaging_EXPORT ConnectomicsConstantsManager { public: //============== String and other constants =================== //==== Error messages ==== static const char* CONNECTOMICS_ERROR_TRIED_TO_ACCESS_INVALID_HISTOGRAM; static const char* CONNECTOMICS_ERROR_PASSED_NEGATIVE_INDEX_TO_HISTOGRAM; static const char* CONNECTOMICS_ERROR_OUTSIDE_INTEGER_RANGE; static const char* CONNECTOMICS_ERROR_BEYOND_SCOPE; static const char* CONNECTOMICS_ERROR_INVALID_MAPPING; static const char* CONNECTOMICS_ERROR_INVALID_DIMENSION_NEED_3; //==== Warnings ==== static const char* CONNECTOMICS_WARNING_ZERO_DISTANCE_NODES; static const char* CONNECTOMICS_WARNING_UNIMPLEMENTED_FEATURE; static const char* CONNECTOMICS_WARNING_MORE_POINTS_THAN_PRESENT; static const char* CONNECTOMICS_WARNING_ESTIMATING_LESS_THAN_2; static const char* CONNECTOMICS_WARNING_ESTIMATING_BEYOND_END; static const char* CONNECTOMICS_WARNING_ESTIMATING_BEYOND_START; static const char* CONNECTOMICS_WARNING_DID_NOT_FIND_WHITE; static const char* CONNECTOMICS_WARNING_NOT_EXTEND_TO_WHITE; //==== Information ==== static const char* CONNECTOMICS_WARNING_INFO_NETWORK_CREATED; static const char* CONNECTOMICS_WARNING_NETWORK_NOT_VALID; static const char* CONNECTOMICS_WARNING_NETWORK_DISCONNECTED; static const char* CONNECTOMICS_WARNING_CAN_NOT_COMPUTE_EFFICIENCY; //==== GUI ==== static const char* CONNECTOMICS_GUI_DASH; static const char* CONNECTOMICS_GUI_CONNECTOMICS_CREATION; static const char* CONNECTOMICS_GUI_SELECTION_WARNING; static const char* CONNECTOMICS_GUI_PERFORMING_IMAGE_PROCESSING_FOR_IMAGE; //==== Properties ==== static const char* CONNECTOMICS_PROPERTY_DEFAULT_RGBA_NAME; static const char* CONNECTOMICS_PROPERTY_NAME; static const char* CONNECTOMICS_PROPERTY_VOLUMERENDERING; static const char* CONNECTOMICS_PROPERTY_DEFAULT_CNF_NAME; private: ConnectomicsConstantsManager(); ~ConnectomicsConstantsManager(); }; } //namespace MITK // include cpp //#include -#endif /* _MITK_ConnectomicsConstantsManager_H */ \ No newline at end of file +#endif /* _MITK_ConnectomicsConstantsManager_H */ diff --git a/Modules/DiffusionImaging/IODataStructures/ConnectomicsNetwork/mitkConnectomicsNetwork.cpp b/Modules/DiffusionImaging/IODataStructures/ConnectomicsNetwork/mitkConnectomicsNetwork.cpp index 8261ea81b4..55d44dad68 100644 --- a/Modules/DiffusionImaging/IODataStructures/ConnectomicsNetwork/mitkConnectomicsNetwork.cpp +++ b/Modules/DiffusionImaging/IODataStructures/ConnectomicsNetwork/mitkConnectomicsNetwork.cpp @@ -1,503 +1,503 @@ /*=================================================================== 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 "mitkConnectomicsNetwork.h" #include /* Constructor and Destructor */ mitk::ConnectomicsNetwork::ConnectomicsNetwork() : m_IsModified( false ) { } mitk::ConnectomicsNetwork::~ConnectomicsNetwork() { } /* Wrapper methods */ bool mitk::ConnectomicsNetwork::EdgeExists( mitk::ConnectomicsNetwork::VertexDescriptorType vertexA, mitk::ConnectomicsNetwork::VertexDescriptorType vertexB ) const { return boost::edge(vertexA, vertexB, m_Network ).second; } void mitk::ConnectomicsNetwork::IncreaseEdgeWeight( mitk::ConnectomicsNetwork::VertexDescriptorType vertexA, mitk::ConnectomicsNetwork::VertexDescriptorType vertexB ) { m_Network[ boost::edge(vertexA, vertexB, m_Network ).first ].weight++; SetIsModified( true ); } void mitk::ConnectomicsNetwork::AddEdge( mitk::ConnectomicsNetwork::VertexDescriptorType vertexA, mitk::ConnectomicsNetwork::VertexDescriptorType vertexB ) { AddEdge(vertexA, vertexB, m_Network[ vertexA ].id, m_Network[ vertexB ].id ); } void mitk::ConnectomicsNetwork::AddEdge( mitk::ConnectomicsNetwork::VertexDescriptorType vertexA, mitk::ConnectomicsNetwork::VertexDescriptorType vertexB, int sourceID, int targetID, int weight ) { boost::add_edge( vertexA, vertexB, m_Network ); m_Network[ boost::edge(vertexA, vertexB, m_Network ).first ].sourceId = sourceID; m_Network[ boost::edge(vertexA, vertexB, m_Network ).first ].targetId = targetID; m_Network[ boost::edge(vertexA, vertexB, m_Network ).first ].weight = weight; m_Network[ boost::edge(vertexA, vertexB, m_Network ).first ].edge_weight = 1.0; SetIsModified( true ); } mitk::ConnectomicsNetwork::VertexDescriptorType mitk::ConnectomicsNetwork::AddVertex( int id ) { VertexDescriptorType vertex = boost::add_vertex( m_Network ); m_Network[vertex].id = id; SetIsModified( true ); return vertex; } void mitk::ConnectomicsNetwork::SetLabel( mitk::ConnectomicsNetwork::VertexDescriptorType vertex, std::string inLabel ) { m_Network[vertex].label = inLabel; SetIsModified( true ); } void mitk::ConnectomicsNetwork::SetCoordinates( mitk::ConnectomicsNetwork::VertexDescriptorType vertex, std::vector< float > inCoordinates ) { m_Network[vertex].coordinates = inCoordinates; SetIsModified( true ); } void mitk::ConnectomicsNetwork::clear() { m_Network.clear(); SetIsModified( true ); } /* Superclass methods, that need to be implemented */ void mitk::ConnectomicsNetwork::UpdateOutputInformation() { } void mitk::ConnectomicsNetwork::SetRequestedRegionToLargestPossibleRegion() { } bool mitk::ConnectomicsNetwork::RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool mitk::ConnectomicsNetwork::VerifyRequestedRegion() { return true; } void mitk::ConnectomicsNetwork::SetRequestedRegion( itk::DataObject *data ) { } std::vector< mitk::ConnectomicsNetwork::NetworkNode > mitk::ConnectomicsNetwork::GetVectorOfAllNodes() const { boost::graph_traits::vertex_iterator iterator, end; // sets iterator to start end end to end boost::tie(iterator, end) = boost::vertices( m_Network ); std::vector< NetworkNode > vectorOfNodes; for ( ; iterator != end; ++iterator) { NetworkNode tempNode; // the value of an iterator is a descriptor tempNode = m_Network[ *iterator ]; vectorOfNodes.push_back( tempNode ); } return vectorOfNodes; } std::vector< mitk::ConnectomicsNetwork::VertexDescriptorType > mitk::ConnectomicsNetwork::GetVectorOfAllVertexDescriptors() const { boost::graph_traits::vertex_iterator iterator, end; // sets iterator to start end end to end boost::tie(iterator, end) = boost::vertices( m_Network ); std::vector< VertexDescriptorType > vectorOfDescriptors; for ( ; iterator != end; ++iterator) { vectorOfDescriptors.push_back( *iterator ); } return vectorOfDescriptors; } std::vector< std::pair< std::pair< mitk::ConnectomicsNetwork::NetworkNode, mitk::ConnectomicsNetwork::NetworkNode > , mitk::ConnectomicsNetwork::NetworkEdge > > mitk::ConnectomicsNetwork::GetVectorOfAllEdges() const { boost::graph_traits::edge_iterator iterator, end; // sets iterator to start end end to end boost::tie(iterator, end) = boost::edges( m_Network ); std::vector< std::pair< std::pair< NetworkNode, NetworkNode > , NetworkEdge > > vectorOfEdges; for ( ; iterator != end; ++iterator) { NetworkNode sourceNode, targetNode; NetworkEdge tempEdge; // the value of an iterator is a descriptor tempEdge = m_Network[ *iterator ]; sourceNode = m_Network[ boost::source( *iterator, m_Network ) ]; targetNode = m_Network[ boost::target( *iterator, m_Network ) ]; std::pair< NetworkNode, NetworkNode > nodePair( sourceNode, targetNode ); std::pair< std::pair< NetworkNode, NetworkNode > , NetworkEdge > edgePair( nodePair, tempEdge); vectorOfEdges.push_back( edgePair ); } return vectorOfEdges; } int mitk::ConnectomicsNetwork::GetNumberOfVertices() const { return boost::num_vertices( m_Network ); } int mitk::ConnectomicsNetwork::GetNumberOfEdges() { return boost::num_edges( m_Network ); } int mitk::ConnectomicsNetwork::GetMaximumWeight() const { int maxWeight( 0 ); boost::graph_traits::edge_iterator iterator, end; // sets iterator to start end end to end boost::tie(iterator, end) = boost::edges( m_Network ); for ( ; iterator != end; ++iterator) { int tempWeight; // the value of an iterator is a descriptor tempWeight = m_Network[ *iterator ].weight; if( tempWeight > maxWeight ) { maxWeight = tempWeight; } } return maxWeight; } int mitk::ConnectomicsNetwork::GetNumberOfSelfLoops() { int noOfSelfLoops( 0 ); std::vector< std::pair< std::pair< NetworkNode, NetworkNode > , NetworkEdge > > edgeVector = GetVectorOfAllEdges(); for( int index = 0; index < edgeVector.size() ; index++ ) { double sourceX, sourceY, sourceZ, targetX, targetY, targetZ; sourceX = edgeVector[ index ].first.first.coordinates[0] ; sourceY = edgeVector[ index ].first.first.coordinates[1] ; sourceZ = edgeVector[ index ].first.first.coordinates[2] ; targetX = edgeVector[ index ].first.second.coordinates[0] ; targetY = edgeVector[ index ].first.second.coordinates[1] ; targetZ = edgeVector[ index ].first.second.coordinates[2] ; // if the coordinates are the same if( sourceX > ( targetX - 0.01 ) && sourceX < ( targetX + 0.01 ) && sourceY > ( targetY - 0.01 ) && sourceY < ( targetY + 0.01 ) && sourceZ > ( targetZ - 0.01 ) && sourceZ < ( targetZ + 0.01 ) ) { noOfSelfLoops++; } } return noOfSelfLoops; } double mitk::ConnectomicsNetwork::GetAverageDegree() { double vertices = (double) GetNumberOfVertices(); double edges = (double) GetNumberOfEdges(); return ( ( edges * 2.0 ) / vertices ); } double mitk::ConnectomicsNetwork::GetConnectionDensity() { double vertices = (double) GetNumberOfVertices(); double edges = (double) GetNumberOfEdges(); double numberOfPossibleEdges = vertices * ( vertices - 1 ) / 2 ; return ( edges / numberOfPossibleEdges ); } std::vector< int > mitk::ConnectomicsNetwork::GetDegreeOfNodes( ) const { std::vector< int > vectorOfDegree; boost::graph_traits::vertex_iterator iterator, end; // sets iterator to start end end to end boost::tie( iterator, end ) = boost::vertices( m_Network ); vectorOfDegree.resize( this->GetNumberOfVertices() ); for ( ; iterator != end; ++iterator) { // the value of an iterator is a descriptor vectorOfDegree[ m_Network[ *iterator ].id ] = GetVectorOfAdjacentNodes( *iterator ).size(); } return vectorOfDegree; } std::vector< mitk::ConnectomicsNetwork::VertexDescriptorType > mitk::ConnectomicsNetwork::GetVectorOfAdjacentNodes( mitk::ConnectomicsNetwork::VertexDescriptorType vertex ) const { std::vector< mitk::ConnectomicsNetwork::VertexDescriptorType > vectorOfAdjacentNodes; boost::graph_traits::adjacency_iterator adjIter, adjEnd; boost::tie( adjIter, adjEnd ) = boost::adjacent_vertices( vertex, m_Network); for ( ; adjIter != adjEnd; ++adjIter) { vectorOfAdjacentNodes.push_back( *adjIter ); } return vectorOfAdjacentNodes; } int mitk::ConnectomicsNetwork::GetMaximumDegree() const { int maximumDegree( 0 ); std::vector< int > vectorOfDegree = GetDegreeOfNodes(); for( int index( 0 ); index < vectorOfDegree.size(); ++index ) { if( maximumDegree < vectorOfDegree[ index ] ) { maximumDegree = vectorOfDegree[ index ]; } } return maximumDegree; } std::vector< double > mitk::ConnectomicsNetwork::GetLocalClusteringCoefficients( ) { std::vector< double > vectorOfClusteringCoefficients; typedef boost::graph_traits::vertex_iterator vertexIter; vectorOfClusteringCoefficients.resize( this->GetNumberOfVertices() ); std::pair vertexPair; //for every vertex calculate the clustering coefficient for (vertexPair = vertices(m_Network); vertexPair.first != vertexPair.second; ++vertexPair.first) { vectorOfClusteringCoefficients[ m_Network[ *vertexPair.first ].id ] = boost::clustering_coefficient(m_Network,*vertexPair.first) ; } return vectorOfClusteringCoefficients; } std::vector< double > mitk::ConnectomicsNetwork::GetClusteringCoefficientsByDegree( ) { std::vector< double > vectorOfClusteringCoefficients = GetLocalClusteringCoefficients(); std::vector< int > vectorOfDegree = GetDegreeOfNodes(); std::vector< double > vectorOfClusteringCoefficientsByDegree; vectorOfClusteringCoefficientsByDegree.resize( GetMaximumDegree() + 1, 0 ); // c_{mean}(k) = frac{1}_{N_{k}} sum_{i in Y(k)} c_{i} // where N_{k} is the number of vertices of degree k // Y(k) is the set of vertices of degree k // c_{i} is the local clustering coefficient of vertex i for( int degree( 0 ); degree < vectorOfClusteringCoefficientsByDegree.size(); ++degree ) { vectorOfClusteringCoefficientsByDegree[ degree ] = 0; int n_k( 0 ); for( int index( 0 ); index < vectorOfDegree.size(); ++index ) { if( degree == vectorOfDegree[ index ] ) {// if in Y( degree ) vectorOfClusteringCoefficientsByDegree[ degree ] += vectorOfClusteringCoefficients[ index ]; n_k++; } } if( n_k != 0 ) { vectorOfClusteringCoefficientsByDegree[ degree ] = vectorOfClusteringCoefficientsByDegree[ degree ] / n_k; } } return vectorOfClusteringCoefficientsByDegree; } double mitk::ConnectomicsNetwork::GetGlobalClusteringCoefficient( ) { double globalClusteringCoefficient( 0.0 ); std::vector< double > vectorOfClusteringCoefficientsByDegree = GetClusteringCoefficientsByDegree(); std::vector< int > vectorOfDegree = GetDegreeOfNodes(); std::vector< int > degreeDistribution; degreeDistribution.resize( vectorOfClusteringCoefficientsByDegree.size(), 0 ); int normalizationParameter( 0 ); for( int index( 0 ); index < vectorOfDegree.size(); ++index ) { degreeDistribution[ vectorOfDegree[ index ] ]++; normalizationParameter++; } // c_{mean} = sum_{k} P_{k} c_{mean}(k) // where P_{k} is the degree distribution // k is the degree for( int degree( 0 ); degree < degreeDistribution.size(); ++degree ) { globalClusteringCoefficient += degreeDistribution[ degree ] / ( (double) normalizationParameter) * vectorOfClusteringCoefficientsByDegree[ degree ]; } return globalClusteringCoefficient; } mitk::ConnectomicsNetwork::NetworkType* mitk::ConnectomicsNetwork::GetBoostGraph() { return &m_Network; } bool mitk::ConnectomicsNetwork::GetIsModified() const { return m_IsModified; } void mitk::ConnectomicsNetwork::SetIsModified( bool value) { m_IsModified = value; } mitk::ConnectomicsNetwork::NetworkNode mitk::ConnectomicsNetwork::GetNode( VertexDescriptorType vertex ) const { return m_Network[ vertex ]; } mitk::ConnectomicsNetwork::NetworkEdge mitk::ConnectomicsNetwork::GetEdge( VertexDescriptorType vertexA, VertexDescriptorType vertexB ) const { return m_Network[ boost::edge(vertexA, vertexB, m_Network ).first ]; } void mitk::ConnectomicsNetwork::UpdateBounds( ) { float min = itk::NumericTraits::min(); float max = itk::NumericTraits::max(); float bounds[] = {max, min, max, min, max, min}; std::vector< mitk::ConnectomicsNetwork::NetworkNode > nodeVector = this->GetVectorOfAllNodes(); if( nodeVector.size() == 0 ) { bounds[0] = 0; bounds[1] = 1; bounds[2] = 0; bounds[3] = 1; bounds[4] = 0; bounds[5] = 1; } // for each direction, make certain the point is in between for( int index(0), end(nodeVector.size()) ; index < end; index++ ) { for( int direction(0); direction < nodeVector.at( index ).coordinates.size(); direction++ ) { if( nodeVector.at( index ).coordinates.at(direction) < bounds[ 2 * direction ] ) { bounds[ 2 * direction ] = nodeVector.at( index ).coordinates.at(direction); } if( nodeVector.at( index ).coordinates.at(direction) > bounds[ 2 * direction + 1] ) { bounds[ 2 * direction + 1] = nodeVector.at( index ).coordinates.at(direction); } } } // provide some border margin for(int i=0; i<=4; i+=2) { bounds[i] -=10; } for(int i=1; i<=5; i+=2) { bounds[i] +=10; } this->GetGeometry()->SetFloatBounds(bounds); this->GetTimeSlicedGeometry()->UpdateInformation(); -} \ No newline at end of file +} diff --git a/Modules/DiffusionImaging/IODataStructures/DiffusionWeightedImages/mitkDiffusionImageSource.cpp b/Modules/DiffusionImaging/IODataStructures/DiffusionWeightedImages/mitkDiffusionImageSource.cpp index d1fff7ddf7..bb34303f76 100644 --- a/Modules/DiffusionImaging/IODataStructures/DiffusionWeightedImages/mitkDiffusionImageSource.cpp +++ b/Modules/DiffusionImaging/IODataStructures/DiffusionWeightedImages/mitkDiffusionImageSource.cpp @@ -1,103 +1,103 @@ /*=================================================================== 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_NRRD_DIFFUSION_VOULMES_IO_FACTORY_CPP__ #define __MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_CPP__ #include "mitkDiffusionImageSource.h" #include "mitkDiffusionImage.h" template mitk::DiffusionImageSource::DiffusionImageSource() { // Create the output. We use static_cast<> here because we know the default // output must be of type DiffusionImage typename mitk::DiffusionImage::Pointer output = static_cast*>(this->MakeOutput(0).GetPointer()); Superclass::SetNumberOfRequiredOutputs(1); Superclass::SetNthOutput(0, output.GetPointer()); } template mitk::DiffusionImageSource::~DiffusionImageSource() { } template itk::DataObject::Pointer mitk::DiffusionImageSource::MakeOutput( unsigned int /*idx*/ ) { return static_cast(mitk::DiffusionImage::New().GetPointer()); } //template //mitk::DiffusionImage* mitk::DiffusionImageSource::GetOutput() //{ // if (this->GetNumberOfOutputs() < 1) // { // return 0; // } // // return static_cast*> // (this->BaseProcess::GetOutput(0)); //} // //template //mitk::DiffusionImage* mitk::DiffusionImageSource::GetOutput(unsigned int idx) //{ // return static_cast*> // (this->ProcessObject::GetOutput(idx)); //} // //template //void mitk::DiffusionImageSource::SetOutput(mitk::DiffusionImage* output) //{ // itkWarningMacro(<< "SetOutput(): This method is slated to be removed from ITK. Please use GraftOutput() in possible combination with DisconnectPipeline() instead." ); // BaseProcess::SetNthOutput(0, output); //} // //template //void mitk::DiffusionImageSource::GraftOutput(mitk::DiffusionImage* graft) //{ // this->GraftNthOutput(0, graft); //} // //template //void mitk::DiffusionImageSource::GraftNthOutput(unsigned int idx, mitk::DiffusionImage *graft) //{ // if (idx < this->GetNumberOfOutputs()) // { // mitk::DiffusionImage * output = this->GetOutput(idx); // // if (output && graft) // { // // grab a handle to the bulk data of the specified data object // // output->SetPixelContainer( graft->GetPixelContainer() ); @FIXME!!!! // // // copy the region ivars of the specified data object // output->SetRequestedRegion( graft );//graft->GetRequestedRegion() ); // // output->SetLargestPossibleRegion( graft->GetLargestPossibleRegion() ); @FIXME!!!! // // output->SetBufferedRegion( graft->GetBufferedRegion() ); @FIXME!!!! // // // copy the meta-information // output->CopyInformation( graft ); // } // } //} -#endif //__MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_CPP__ \ No newline at end of file +#endif //__MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_CPP__ diff --git a/Modules/DiffusionImaging/Rendering/mitkConnectomicsNetworkMapper3D.cpp b/Modules/DiffusionImaging/Rendering/mitkConnectomicsNetworkMapper3D.cpp index 860646c196..c54e3431ca 100644 --- a/Modules/DiffusionImaging/Rendering/mitkConnectomicsNetworkMapper3D.cpp +++ b/Modules/DiffusionImaging/Rendering/mitkConnectomicsNetworkMapper3D.cpp @@ -1,180 +1,180 @@ /*=================================================================== 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 "mitkConnectomicsNetworkMapper3D.h" mitk::ConnectomicsNetworkMapper3D::ConnectomicsNetworkMapper3D() { //TODO: implement m_NetworkAssembly = vtkPropAssembly::New(); } mitk::ConnectomicsNetworkMapper3D:: ~ConnectomicsNetworkMapper3D() { //TODO: implement m_NetworkAssembly->Delete(); } void mitk::ConnectomicsNetworkMapper3D::GenerateDataForRenderer(mitk::BaseRenderer* renderer) { //TODO: implement if( this->GetInput() == NULL ) { return; } if( this->GetInput()->GetIsModified( ) ) { GenerateData(); } } void mitk::ConnectomicsNetworkMapper3D::GenerateData() { //TODO: implement // Here is the part where a graph is given and converted to points and connections between points... std::vector< mitk::ConnectomicsNetwork::NetworkNode > vectorOfNodes = this->GetInput()->GetVectorOfAllNodes(); std::vector< std::pair< std::pair< mitk::ConnectomicsNetwork::NetworkNode, mitk::ConnectomicsNetwork::NetworkNode > , mitk::ConnectomicsNetwork::NetworkEdge > > vectorOfEdges = this->GetInput()->GetVectorOfAllEdges(); mitk::Point3D tempWorldPoint, tempCNFGeometryPoint; //////////////////////Create Spheres///////////////////////// for(unsigned int i = 0; i < vectorOfNodes.size(); i++) { vtkSmartPointer sphereSource = vtkSmartPointer::New(); for(unsigned int dimension = 0; dimension < 3; dimension++) { tempCNFGeometryPoint.SetElement( dimension , vectorOfNodes[i].coordinates[dimension] ); } this->GetData()->GetGeometry()->IndexToWorld( tempCNFGeometryPoint, tempWorldPoint ); sphereSource->SetCenter( tempWorldPoint[0] , tempWorldPoint[1], tempWorldPoint[2] ); sphereSource->SetRadius(1.0); vtkSmartPointer mapper = vtkSmartPointer::New(); mapper->SetInput(sphereSource->GetOutput()); vtkSmartPointer actor = vtkSmartPointer::New(); actor->SetMapper(mapper); m_NetworkAssembly->AddPart(actor); } //////////////////////Create Tubes///////////////////////// for(unsigned int i = 0; i < vectorOfEdges.size(); i++) { vtkSmartPointer lineSource = vtkSmartPointer::New(); for(unsigned int dimension = 0; dimension < 3; dimension++) { tempCNFGeometryPoint[ dimension ] = vectorOfEdges[i].first.first.coordinates[dimension]; } this->GetData()->GetGeometry()->IndexToWorld( tempCNFGeometryPoint, tempWorldPoint ); lineSource->SetPoint1(tempWorldPoint[0], tempWorldPoint[1],tempWorldPoint[2] ); for(unsigned int dimension = 0; dimension < 3; dimension++) { tempCNFGeometryPoint[ dimension ] = vectorOfEdges[i].first.second.coordinates[dimension]; } this->GetData()->GetGeometry()->IndexToWorld( tempCNFGeometryPoint, tempWorldPoint ); lineSource->SetPoint2(tempWorldPoint[0], tempWorldPoint[1], tempWorldPoint[2] ); vtkSmartPointer tubes = vtkSmartPointer::New(); tubes->SetInput( lineSource->GetOutput() ); tubes->SetNumberOfSides( 12 ); double radiusFactor = 1.0 + ((double) vectorOfEdges[i].second.weight) / 10.0 ; tubes->SetRadius( std::log10( radiusFactor ) ); vtkSmartPointer mapper2 = vtkSmartPointer::New(); mapper2->SetInput( tubes->GetOutput() ); vtkSmartPointer actor = vtkSmartPointer::New(); actor->SetMapper(mapper2); double maxWeight = (double) this->GetInput()->GetMaximumWeight(); double colourFactor = vectorOfEdges[i].second.weight / maxWeight; actor->GetProperty()->SetColor( colourFactor, colourFactor, colourFactor); m_NetworkAssembly->AddPart(actor); } (static_cast ( GetData() ) )->SetIsModified( false ); //this->UpdateVtkObjects(); } const mitk::ConnectomicsNetwork* mitk::ConnectomicsNetworkMapper3D::GetInput() { return static_cast ( GetData() ); } void mitk::ConnectomicsNetworkMapper3D::SetDefaultProperties(DataNode* node, BaseRenderer* renderer , bool overwrite) { //TODO: implement // hand it to the superclass for base default properties Superclass::SetDefaultProperties(node, renderer, overwrite); } void mitk::ConnectomicsNetworkMapper3D::ApplyProperties(mitk::BaseRenderer* renderer) { //TODO: implement } void mitk::ConnectomicsNetworkMapper3D::SetVtkMapperImmediateModeRendering(vtkMapper *mapper) { //TODO: implement } void mitk::ConnectomicsNetworkMapper3D::UpdateVtkObjects() { //TODO: implement } vtkProp* mitk::ConnectomicsNetworkMapper3D::GetVtkProp(mitk::BaseRenderer *renderer) { return m_NetworkAssembly; -} \ No newline at end of file +} diff --git a/Modules/DiffusionImaging/Testing/CMakeLists.txt b/Modules/DiffusionImaging/Testing/CMakeLists.txt index 27763457ee..7880dc4d2c 100644 --- a/Modules/DiffusionImaging/Testing/CMakeLists.txt +++ b/Modules/DiffusionImaging/Testing/CMakeLists.txt @@ -1,4 +1,5 @@ MITK_CREATE_MODULE_TESTS() mitkAddCustomModuleTest(mitkFiberBundleXReaderWriterTest mitkFiberBundleXReaderWriterTest ${MITK_DATA_DIR}/DiffusionImaging/fiberBundleX.fib) -mitkAddCustomModuleTest(mitkFiberBundleXTest mitkFiberBundleXTest ${MITK_DATA_DIR}/DiffusionImaging/fiberBundleX.fib) +## deactivated, see bug 12017 +# mitkAddCustomModuleTest(mitkFiberBundleXTest mitkFiberBundleXTest ${MITK_DATA_DIR}/DiffusionImaging/fiberBundleX.fib) diff --git a/Modules/DiffusionImaging/Testing/files.cmake b/Modules/DiffusionImaging/Testing/files.cmake index 545e2e6ab2..d4797a0809 100644 --- a/Modules/DiffusionImaging/Testing/files.cmake +++ b/Modules/DiffusionImaging/Testing/files.cmake @@ -1,8 +1,8 @@ SET(MODULE_TESTS mitkFactoryRegistrationTest.cpp ) SET(MODULE_CUSTOM_TESTS mitkFiberBundleXReaderWriterTest.cpp - mitkFiberBundleXTest.cpp + # mitkFiberBundleXTest.cpp ## deactivated, see bug 12017 ) diff --git a/Modules/GraphAlgorithms/itkShortestPathImageFilter.txx b/Modules/GraphAlgorithms/itkShortestPathImageFilter.txx index 311f5fc82a..8bb19373a0 100644 --- a/Modules/GraphAlgorithms/itkShortestPathImageFilter.txx +++ b/Modules/GraphAlgorithms/itkShortestPathImageFilter.txx @@ -1,939 +1,939 @@ /*=================================================================== 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 __itkShortestPathImageFilter_txx #define __itkShortestPathImageFilter_txx #include "time.h" #include "mitkMemoryUtilities.h" #include #include #include namespace itk { // Constructor (initialize standard values) template ShortestPathImageFilter ::ShortestPathImageFilter() : m_FullNeighborsMode(false), m_MakeOutputImage(true), m_StoreVectorOrder(false), m_CalcAllDistances(false), m_ActivateTimeOut(false), multipleEndPoints(false), m_Nodes(0), m_Graph_NumberOfNodes(0) { m_endPoints.clear(); m_endPointsClosed.clear(); if (m_MakeOutputImage) { this->SetNumberOfRequiredOutputs(1); this->SetNthOutput( 0, OutputImageType::New() ); } } template inline typename ShortestPathImageFilter::IndexType ShortestPathImageFilter ::NodeToCoord (NodeNumType node) { const InputImageSizeType &size = this->GetInput()->GetRequestedRegion().GetSize(); int dim = InputImageType::ImageDimension; IndexType coord; if (dim == 2) { coord[1] = node / size[0]; coord[0] = node % size[0]; if ((coord[0] >= size[0]) || (coord[1] >= size[1])) { coord[0] = 0; coord[1] = 0; } } if (dim == 3) { coord[2] = node / (size[0]*size[1]); coord[1] = (node % (size[0]*size[1])) / size[0]; coord[0] = (node % (size[0]*size[1])) % size[0]; if ((coord[0] >= size[0]) || (coord[1] >= size[1]) || (coord[2] >= size[2])) { coord[0] = 0; coord[1] = 0; coord[2] = 0; } } return coord; } template inline typename itk::NodeNumType ShortestPathImageFilter:: CoordToNode (IndexType coord) { const InputImageSizeType &size = this->GetInput()->GetRequestedRegion().GetSize(); int dim = InputImageType::ImageDimension; NodeNumType node = 0; if (dim == 2) { node = (coord[1]*size[0]) + coord[0]; } if (dim == 3) { node = (coord[2]*size[0]*size[1]) + (coord[1]*size[0]) + coord[0]; } if ((m_Graph_NumberOfNodes > 0) && (node >= m_Graph_NumberOfNodes)) { MITK_INFO << "WARNING! Coordinates outside image!"; MITK_INFO << "Coords = " << coord ; MITK_INFO << "ImageDim = " << dim ; MITK_INFO << "RequestedRegionSize = " << size ; node = 0; } return node; } template inline bool ShortestPathImageFilter:: CoordIsInBounds (IndexType coord) { const InputImageSizeType &size = this->GetInput()->GetRequestedRegion().GetSize(); int dim = InputImageType::ImageDimension; if (dim == 2) { if ((coord[0] >= 0) && (coord[0] < size[0]) && (coord[1] >= 0 ) && (coord[1] < size[1] )) { return true; } } if (dim == 3) { if ((coord[0] >= 0) && (coord[0] < size[0]) && (coord[1] >= 0 ) && (coord[1] < size[1] ) && (coord[2] >= 0 ) && (coord[2] < size[2] )) { return true; } } return false; } template inline std::vector< ShortestPathNode* > ShortestPathImageFilter:: GetNeighbors (unsigned int nodeNum, bool FullNeighbors) { // returns a vector of nodepointers.. these nodes are the neighbors int dim = InputImageType::ImageDimension; IndexType Coord = NodeToCoord(nodeNum); IndexType NeighborCoord; std::vector nodeList; int neighborDistance = 1; //if i increase that, i might not hit the endnote // maybe use itkNeighborhoodIterator here, might be faster if ( dim == 2) { // N4 NeighborCoord[0] = Coord[0]; NeighborCoord[1] = Coord[1]-neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]+neighborDistance; NeighborCoord[1] = Coord[1]; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]; NeighborCoord[1] = Coord[1]+neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]-neighborDistance; NeighborCoord[1] = Coord[1]; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); if (FullNeighbors) { // N8 NeighborCoord[0] = Coord[0]-neighborDistance; NeighborCoord[1] = Coord[1]-neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]+neighborDistance; NeighborCoord[1] = Coord[1]-neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]-neighborDistance; NeighborCoord[1] = Coord[1]+neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]+neighborDistance; NeighborCoord[1] = Coord[1]+neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); } } if ( dim == 3) { // N6 NeighborCoord[0] = Coord[0]; NeighborCoord[1] = Coord[1]-neighborDistance; NeighborCoord[2] = Coord[2]; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]+neighborDistance; NeighborCoord[1] = Coord[1]; NeighborCoord[2] = Coord[2]; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]; NeighborCoord[1] = Coord[1]+neighborDistance; NeighborCoord[2] = Coord[2]; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]-neighborDistance; NeighborCoord[1] = Coord[1]; NeighborCoord[2] = Coord[2]; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]; NeighborCoord[1] = Coord[1]; NeighborCoord[2] = Coord[2]+neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]; NeighborCoord[1] = Coord[1]; NeighborCoord[2] = Coord[2]-neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); if (FullNeighbors) { // N26 // Middle Slice NeighborCoord[0] = Coord[0]-neighborDistance; NeighborCoord[1] = Coord[1]-neighborDistance; NeighborCoord[2] = Coord[2]; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]+neighborDistance; NeighborCoord[1] = Coord[1]-neighborDistance; NeighborCoord[2] = Coord[2]; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]-neighborDistance; NeighborCoord[1] = Coord[1]+neighborDistance; NeighborCoord[2] = Coord[2]; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]+neighborDistance; NeighborCoord[1] = Coord[1]+neighborDistance; NeighborCoord[2] = Coord[2]; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); // BackSlice (Diagonal) NeighborCoord[0] = Coord[0]-neighborDistance; NeighborCoord[1] = Coord[1]-neighborDistance; NeighborCoord[2] = Coord[2]-neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]+neighborDistance; NeighborCoord[1] = Coord[1]-neighborDistance; NeighborCoord[2] = Coord[2]-neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]-neighborDistance; NeighborCoord[1] = Coord[1]+neighborDistance; NeighborCoord[2] = Coord[2]-neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]+neighborDistance; NeighborCoord[1] = Coord[1]+neighborDistance; NeighborCoord[2] = Coord[2]-neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); //BackSlice (Non-Diag) NeighborCoord[0] = Coord[0]; NeighborCoord[1] = Coord[1]-neighborDistance; NeighborCoord[2] = Coord[2]-neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]+neighborDistance; NeighborCoord[1] = Coord[1]; NeighborCoord[2] = Coord[2]-neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]; NeighborCoord[1] = Coord[1]+neighborDistance; NeighborCoord[2] = Coord[2]-neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]-neighborDistance; NeighborCoord[1] = Coord[1]; NeighborCoord[2] = Coord[2]-neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); // FrontSlice (Diagonal) NeighborCoord[0] = Coord[0]-neighborDistance; NeighborCoord[1] = Coord[1]-neighborDistance; NeighborCoord[2] = Coord[2]+neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]+neighborDistance; NeighborCoord[1] = Coord[1]-neighborDistance; NeighborCoord[2] = Coord[2]+neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]-neighborDistance; NeighborCoord[1] = Coord[1]+neighborDistance; NeighborCoord[2] = Coord[2]+neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]+neighborDistance; NeighborCoord[1] = Coord[1]+neighborDistance; NeighborCoord[2] = Coord[2]+neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); //FrontSlice(Non-Diag) NeighborCoord[0] = Coord[0]; NeighborCoord[1] = Coord[1]-neighborDistance; NeighborCoord[2] = Coord[2]+neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]+neighborDistance; NeighborCoord[1] = Coord[1]; NeighborCoord[2] = Coord[2]+neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]; NeighborCoord[1] = Coord[1]+neighborDistance; NeighborCoord[2] = Coord[2]+neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); NeighborCoord[0] = Coord[0]-neighborDistance; NeighborCoord[1] = Coord[1]; NeighborCoord[2] = Coord[2]+neighborDistance; if (CoordIsInBounds(NeighborCoord)) nodeList.push_back(&m_Nodes[CoordToNode(NeighborCoord)]); } } return nodeList; } template void ShortestPathImageFilter:: SetStartIndex (const typename TInputImageType::IndexType &StartIndex) { for (unsigned int i=0;i v; v[0] = m_EndIndex[0]-a[0]; v[1] = m_EndIndex[1]-a[1]; v[2] = m_EndIndex[2]-a[2]; return m_CostFunction->GetMinCost() * v.GetNorm(); } template void ShortestPathImageFilter:: InitGraph() { // Clean up previous stuff CleanUp(); // initalize cost function m_CostFunction->Initialize(); // Calc Number of nodes m_ImageDimensions = TInputImageType::ImageDimension; const InputImageSizeType &size = this->GetInput()->GetRequestedRegion().GetSize(); m_Graph_NumberOfNodes = 1; for (NodeNumType i=0; i void ShortestPathImageFilter:: StartShortestPathSearch() { // Setup Timer clock_t startAll = clock(); clock_t stopAll = clock(); // init variables double durationAll = 0; bool timeout = false; bool makeNewHeapNecessary = false; NodeNumType mainNodeListIndex = 0; DistanceType curNodeDistance = 0; DistanceType curNodeDistAndEst = 0; NodeNumType numberOfNodesChecked = 0; // Create Multimap (tree structure for fast searching) std::multimap myMap; std::pair< std::multimap::iterator, std::multimap::iterator> ret; std::multimap::iterator it; // At first, only startNote is discovered. myMap.insert( std::pair (m_Nodes[m_Graph_StartNode].distAndEst, &m_Nodes[m_Graph_StartNode]) ); // While there are discovered Nodes, pick the one with lowest distance, // update its neighbors and eventually delete it from the discovered Nodes list. while(!myMap.empty()) { numberOfNodesChecked++; if ( (numberOfNodesChecked % (m_Graph_NumberOfNodes/100)) == 0) { MITK_INFO << "Checked " << ( numberOfNodesChecked / (m_Graph_NumberOfNodes/100) ) << "% List: " << myMap.size() << "\n"; } // Get element with lowest score mainNodeListIndex = myMap.begin()->second->mainListIndex; curNodeDistAndEst = myMap.begin()->second->distAndEst; curNodeDistance = myMap.begin()->second->distance; myMap.begin()->second->closed = true; // close it // Debug: //MITK_INFO << "INFO: size " << myMap.size(); /* for (it = myMap.begin(); it != myMap.end(); ++it) { MITK_INFO << "(1) " << it->first << "|" << it->second->distAndEst << "|"<second->mainListIndex; } */ // Kicks out element with lowest score myMap.erase( myMap.begin() ); // if wanted, store vector order if (m_StoreVectorOrder) { m_VectorOrder.push_back(mainNodeListIndex); } // Check neighbors std::vector neighborNodes = GetNeighbors(mainNodeListIndex, m_Graph_fullNeighbors); for (NodeNumType i=0; iclosed) continue; // this nodes is already closed, go to next neighbor IndexType coordCurNode = NodeToCoord(mainNodeListIndex); IndexType coordNeighborNode = NodeToCoord(neighborNodes[i]->mainListIndex); // calculate the new Distance to the current neighbor double newDistance = curNodeDistance + (m_CostFunction->GetCost(coordCurNode, coordNeighborNode)); // if it is shorter than any yet known path to this neighbor, than the current path is better. Save that! if ((newDistance < neighborNodes[i]->distance) || (neighborNodes[i]->distance == -1) ) { // if that neighbornode is not in discoverednodeList yet, Push it there and update if (neighborNodes[i]->distance == -1) { neighborNodes[i]->distance = newDistance; neighborNodes[i]->distAndEst = newDistance + getEstimatedCostsToTarget(coordNeighborNode); neighborNodes[i]->prevNode = mainNodeListIndex; myMap.insert( std::pair (m_Nodes[neighborNodes[i]->mainListIndex].distAndEst, &m_Nodes[neighborNodes[i]->mainListIndex]) ); /* MITK_INFO << "Inserted: " << m_Nodes[neighborNodes[i]->mainListIndex].distAndEst << "|" << m_Nodes[neighborNodes[i]->mainListIndex].mainListIndex; MITK_INFO << "INFO: size " << myMap.size(); for (it = myMap.begin(); it != myMap.end(); ++it) { MITK_INFO << "(1) " << it->first << "|" << it->second->distAndEst << "|"<second->mainListIndex; } */ } // or if is already in discoverednodelist, update else { /* it = myMap.find(neighborNodes[i]->distAndEst); if (it == myMap.end() ) { MITK_INFO << "Nothing!"; // look further for (it = myMap.begin(); it != myMap.end(); ++it) { if ((*it).second->mainListIndex == lookForId) { MITK_INFO << "But it is there!!!"; MITK_INFO << "Searched for: " << lookFor << " but had: " << (*it).second->distAndEst; } } } */ // 1st : find and delete old element bool found = false; double lookFor = neighborNodes[i]->distAndEst; unsigned int lookForId = neighborNodes[i]->mainListIndex; ret = myMap.equal_range(neighborNodes[i]->distAndEst); if ((ret.first == ret.second)) { MITK_INFO << "No exact match!"; // if this happens, you are screwed /* MITK_INFO << "Was looking for: " << lookFor << " ID: " << lookForId; if (ret.first != myMap.end() ) { it = ret.first; MITK_INFO << "Found: " << it->first << " ID: " << it->second->mainListIndex; ++it; MITK_INFO << "Found: " << it->first << " ID: " << it->second->mainListIndex; --it; --it; MITK_INFO << "Found: " << it->first << " ID: " << it->second->mainListIndex; } // look if that ID is found in the map for (it = myMap.begin(); it != myMap.end(); ++it) { if ((*it).second->mainListIndex == lookForId) { MITK_INFO << "But it is there!!!"; MITK_INFO << "Searched dist: " << lookFor << " found dist: " << (*it).second->distAndEst; } } */ } else { for (it=ret.first; it!=ret.second; ++it) { if (it->second->mainListIndex == neighborNodes[i]->mainListIndex) { found = true; myMap.erase(it); /* MITK_INFO << "INFO: size " << myMap.size(); MITK_INFO << "Erase: " << it->first << "|" << it->second->mainListIndex; MITK_INFO << "INFO: size " << myMap.size(); for (it = myMap.begin(); it != myMap.end(); ++it) { MITK_INFO << "(1) " << it->first << "|" << it->second->distAndEst << "|"<second->mainListIndex; } */ break; } } } if (!found) { MITK_INFO << "Could not find it! :("; continue; } // 2nd: update and insert new element neighborNodes[i]->distance = newDistance; neighborNodes[i]->distAndEst = newDistance + getEstimatedCostsToTarget(coordNeighborNode); neighborNodes[i]->prevNode = mainNodeListIndex; //myMap.insert( std::pair (neighborNodes[i]->distAndEst, neighborNodes[i])); myMap.insert( std::pair (m_Nodes[neighborNodes[i]->mainListIndex].distAndEst, &m_Nodes[neighborNodes[i]->mainListIndex]) ); //MITK_INFO << "Re-Inserted: " << m_Nodes[neighborNodes[i]->mainListIndex].distAndEst << "|" << m_Nodes[neighborNodes[i]->mainListIndex].mainListIndex; //MITK_INFO << "INFO: size " << myMap.size(); /*for (it = myMap.begin(); it != myMap.end(); ++it) { MITK_INFO << "(1) " << it->first << "|" << it->second->distAndEst << "|"<second->mainListIndex; }*/ } } } // finished with checking all neighbors. // Check Timeout, if activated if (m_ActivateTimeOut) { stopAll = clock(); durationAll = (double)(stopAll - startAll) / CLOCKS_PER_SEC; if (durationAll >= 30) { MITK_INFO << "TIMEOUT!! Search took over 30 seconds"; timeout = true ; } } // Check end criteria: // For multiple points if ( multipleEndPoints ) { // super slow, make it faster for (int i=0 ;i void ShortestPathImageFilter:: MakeOutputs() { MITK_INFO << "Make Output"; if (m_MakeOutputImage) { OutputImagePointer output0 = this->GetOutput(0); output0->SetRegions( this->GetInput()->GetLargestPossibleRegion() ); output0->Allocate(); OutputImageIteratorType shortestPathImageIt (output0, output0->GetRequestedRegion()); // Create ShortestPathImage (Output 0) for (shortestPathImageIt.GoToBegin(); !shortestPathImageIt.IsAtEnd(); ++shortestPathImageIt) { // First intialize with background color shortestPathImageIt.Set( BACKGROUND ) ; } if (!multipleEndPoints) // Only one path was calculated { for (int i=0; i< m_VectorPath.size(); i++) { shortestPathImageIt.SetIndex( m_VectorPath[i] ); shortestPathImageIt.Set( FOREGROUND ) ; } } else // multiple pathes has been calculated, draw all { for (int i =0; i typename ShortestPathImageFilter::OutputImagePointer ShortestPathImageFilter:: GetVectorOrderImage() { // Create Vector Order Image // Return it OutputImagePointer image = OutputImageType::New(); image->SetRegions( this->GetInput()->GetLargestPossibleRegion() ); image->Allocate(); OutputImageIteratorType vectorOrderImageIt (image, image->GetRequestedRegion()); MITK_INFO << "GetVectorOrderImage"; for (vectorOrderImageIt.GoToBegin(); !vectorOrderImageIt.IsAtEnd(); ++vectorOrderImageIt) { // First intialize with background color vectorOrderImageIt.Value() = BACKGROUND ; } for (int i=0; i< m_VectorOrder.size(); i++) { vectorOrderImageIt.SetIndex(NodeToCoord(m_VectorOrder[i]) ); vectorOrderImageIt.Set( BACKGROUND+i) ; } return image; } template typename ShortestPathImageFilter::OutputImagePointer ShortestPathImageFilter:: GetDistanceImage() { // Create Distance Image // Return it OutputImagePointer image = OutputImageType::New(); image->SetRegions( this->GetInput()->GetLargestPossibleRegion() ); image->Allocate();; OutputImageIteratorType distanceImageIt (image, image->GetRequestedRegion()); // Create Distance Image (Output 1) NodeNumType myNodeNum; for (distanceImageIt.GoToBegin(); !distanceImageIt.IsAtEnd(); ++distanceImageIt) { IndexType index = distanceImageIt.GetIndex(); myNodeNum = CoordToNode(index); double newVal = m_Nodes[myNodeNum].distance; distanceImageIt.Set(newVal); } } template std::vector< itk::Index<3> > ShortestPathImageFilter:: GetVectorPath() { return m_VectorPath; } template std::vector< std::vector< itk::Index<3> > > ShortestPathImageFilter:: GetMultipleVectorPaths() { return m_MultipleVectorPaths; } template void ShortestPathImageFilter:: MakeShortestPathVector() { MITK_INFO << "Make ShortestPath Vec"; // single end point if ( !multipleEndPoints ) { // fill m_VectorPath with the Shortest Path m_VectorPath.clear(); // Go backwards from endnote to startnode NodeNumType prevNode = m_Graph_EndNode; while (prevNode != -1) { m_VectorPath.push_back( NodeToCoord(prevNode) ); if (prevNode == m_Graph_StartNode) break; prevNode = m_Nodes[prevNode].prevNode; } // reverse it std::reverse(m_VectorPath.begin(), m_VectorPath.end() ); } // Multiple end end points and pathes else { for (int i=0; i void ShortestPathImageFilter:: CleanUp() { m_VectorPath.clear(); //TODO: if multiple Path, clear all multiple Paths /* for (NodeNumType i=0; i void ShortestPathImageFilter:: GenerateData() { // Build Graph InitGraph(); // Calc Shortest Parth StartShortestPathSearch(); // Fill Shortest Path MakeShortestPathVector(); // Make Outputs MakeOutputs(); } template void ShortestPathImageFilter:: PrintSelf( std::ostream& os, Indent indent ) const { Superclass::PrintSelf(os,indent); } } /* end namespace itk */ -#endif \ No newline at end of file +#endif diff --git a/Modules/IGT/IGTFilters/mitkNavigationDataEvaluationFilter.cpp b/Modules/IGT/IGTFilters/mitkNavigationDataEvaluationFilter.cpp index ec0e73547b..1c58a49a18 100644 --- a/Modules/IGT/IGTFilters/mitkNavigationDataEvaluationFilter.cpp +++ b/Modules/IGT/IGTFilters/mitkNavigationDataEvaluationFilter.cpp @@ -1,314 +1,314 @@ /*=================================================================== 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 "mitkNavigationDataEvaluationFilter.h" #include #define _USE_MATH_DEFINES #include mitk::NavigationDataEvaluationFilter::NavigationDataEvaluationFilter() : mitk::NavigationDataToNavigationDataFilter() { } mitk::NavigationDataEvaluationFilter::~NavigationDataEvaluationFilter() { } void mitk::NavigationDataEvaluationFilter::GenerateData() { this->CreateOutputsForAllInputs(); // make sure that we have the same number of outputs as inputs this->CreateMembersForAllInputs(); /* update outputs with tracking data from tools */ for (unsigned int i = 0; i < this->GetNumberOfOutputs() ; ++i) { //first copy outputs to inputs mitk::NavigationData* output = this->GetOutput(i); assert(output); const mitk::NavigationData* input = this->GetInput(i); assert(input); if (input->IsDataValid() == false) {output->SetDataValid(false);} else {output->Graft(input);} //then save statistics if(input->IsDataValid()) { m_LoggedPositions[i].push_back(input->GetPosition()); m_LoggedQuaternions[i].push_back(input->GetOrientation()); } else { m_InavildSamples[i]++; } } } void mitk::NavigationDataEvaluationFilter::CreateMembersForAllInputs() { while(this->m_LoggedPositions.size() < this->GetNumberOfInputs()) { std::pair > newElement(m_LoggedPositions.size(),std::vector()); m_LoggedPositions.insert(newElement); } while(this->m_LoggedQuaternions.size() < this->GetNumberOfInputs()) { std::pair > newElement(m_LoggedQuaternions.size(),std::vector()); m_LoggedQuaternions.insert(newElement); } while(this->m_InavildSamples.size() < this->GetNumberOfInputs()) { std::pair newElement(m_LoggedQuaternions.size(),0); m_InavildSamples.insert(newElement); } } void mitk::NavigationDataEvaluationFilter::ResetStatistic() { for (int i = 0; i < m_LoggedPositions.size(); i++) m_LoggedPositions[i] = std::vector(); for (int i = 0; i < m_LoggedQuaternions.size(); i++) m_LoggedQuaternions[i] = std::vector(); for (int i = 0; i < m_InavildSamples.size(); i++) m_InavildSamples[i] = 0; } int mitk::NavigationDataEvaluationFilter::GetNumberOfAnalysedNavigationData(int input) { return this->m_LoggedPositions[input].size(); } mitk::Point3D mitk::NavigationDataEvaluationFilter::GetPositionMean(int input) { mitk::PointSetStatisticsCalculator::Pointer myCalculator = mitk::PointSetStatisticsCalculator::New(VectorToPointSet(m_LoggedPositions[input])); return myCalculator->GetPositionMean(); } mitk::Vector3D mitk::NavigationDataEvaluationFilter::GetPositionStandardDeviation(int input) { mitk::PointSetStatisticsCalculator::Pointer myCalculator = mitk::PointSetStatisticsCalculator::New(VectorToPointSet(m_LoggedPositions[input])); return myCalculator->GetPositionStandardDeviation(); } mitk::Vector3D mitk::NavigationDataEvaluationFilter::GetPositionSampleStandardDeviation(int input) { mitk::PointSetStatisticsCalculator::Pointer myCalculator = mitk::PointSetStatisticsCalculator::New(VectorToPointSet(m_LoggedPositions[input])); return myCalculator->GetPositionSampleStandardDeviation(); } mitk::Quaternion mitk::NavigationDataEvaluationFilter::GetQuaternionMean(int input) { return GetMean(m_LoggedQuaternions[input]); } mitk::Quaternion mitk::NavigationDataEvaluationFilter::GetQuaternionStandardDeviation(int input) { mitk::Quaternion returnValue; std::vector list1 = std::vector(); std::vector list2 = std::vector(); std::vector list3 = std::vector(); std::vector list4 = std::vector(); for (int i=0; iGetStabw(list1); returnValue[1] = myCalculator->GetStabw(list2); returnValue[2] = myCalculator->GetStabw(list3); returnValue[3] = myCalculator->GetStabw(list4); return returnValue; } mitk::Vector3D mitk::NavigationDataEvaluationFilter::GetEulerAnglesMean(int input) { mitk::PointSetStatisticsCalculator::Pointer myCalculator = mitk::PointSetStatisticsCalculator::New(VectorToPointSet(QuaternionsToEulerAngles(m_LoggedQuaternions[input]))); mitk::Vector3D returnValue; returnValue[0] = myCalculator->GetPositionMean()[0]; returnValue[1] = myCalculator->GetPositionMean()[1]; returnValue[2] = myCalculator->GetPositionMean()[2]; return returnValue; } double mitk::NavigationDataEvaluationFilter::GetEulerAnglesRMS(int input) { mitk::PointSetStatisticsCalculator::Pointer myCalculator = mitk::PointSetStatisticsCalculator::New(VectorToPointSet(QuaternionsToEulerAngles(m_LoggedQuaternions[input]))); return myCalculator->GetPositionErrorRMS(); } double mitk::NavigationDataEvaluationFilter::GetEulerAnglesRMSDegree(int input) { mitk::PointSetStatisticsCalculator::Pointer myCalculator = mitk::PointSetStatisticsCalculator::New(VectorToPointSet(QuaternionsToEulerAnglesGrad(m_LoggedQuaternions[input]))); return myCalculator->GetPositionErrorRMS(); } double mitk::NavigationDataEvaluationFilter::GetPositionErrorMean(int input) { mitk::PointSetStatisticsCalculator::Pointer myCalculator = mitk::PointSetStatisticsCalculator::New(VectorToPointSet(m_LoggedPositions[input])); return myCalculator->GetPositionErrorMean(); } double mitk::NavigationDataEvaluationFilter::GetPositionErrorStandardDeviation(int input) { mitk::PointSetStatisticsCalculator::Pointer myCalculator = mitk::PointSetStatisticsCalculator::New(VectorToPointSet(m_LoggedPositions[input])); return myCalculator->GetPositionErrorStandardDeviation(); } double mitk::NavigationDataEvaluationFilter::GetPositionErrorSampleStandardDeviation(int input) { mitk::PointSetStatisticsCalculator::Pointer myCalculator = mitk::PointSetStatisticsCalculator::New(VectorToPointSet(m_LoggedPositions[input])); return myCalculator->GetPositionErrorSampleStandardDeviation(); } double mitk::NavigationDataEvaluationFilter::GetPositionErrorRMS(int input) { mitk::PointSetStatisticsCalculator::Pointer myCalculator = mitk::PointSetStatisticsCalculator::New(VectorToPointSet(m_LoggedPositions[input])); return myCalculator->GetPositionErrorRMS(); } double mitk::NavigationDataEvaluationFilter::GetPositionErrorMedian(int input) { mitk::PointSetStatisticsCalculator::Pointer myCalculator = mitk::PointSetStatisticsCalculator::New(VectorToPointSet(m_LoggedPositions[input])); return myCalculator->GetPositionErrorMedian(); } double mitk::NavigationDataEvaluationFilter::GetPositionErrorMax(int input) { mitk::PointSetStatisticsCalculator::Pointer myCalculator = mitk::PointSetStatisticsCalculator::New(VectorToPointSet(m_LoggedPositions[input])); return myCalculator->GetPositionErrorMax(); } double mitk::NavigationDataEvaluationFilter::GetPositionErrorMin(int input) { mitk::PointSetStatisticsCalculator::Pointer myCalculator = mitk::PointSetStatisticsCalculator::New(VectorToPointSet(m_LoggedPositions[input])); return myCalculator->GetPositionErrorMin(); } int mitk::NavigationDataEvaluationFilter::GetNumberOfInvalidSamples(int input) { return m_InavildSamples[input]; } double mitk::NavigationDataEvaluationFilter::GetPercentageOfInvalidSamples(int input) { return (m_InavildSamples[input]/(m_InavildSamples[input]+((double)m_LoggedPositions[input].size())))*100.0; } mitk::Quaternion mitk::NavigationDataEvaluationFilter::GetMean(std::vector list) { //calculate mean mitk::Quaternion mean; mean[0] = 0; mean[1] = 0; mean[2] = 0; mean[3] = 0; for (int i=0; i pSet) { mitk::PointSet::Pointer returnValue = mitk::PointSet::New(); for (int i=0; iInsertPoint(i,pSet.at(i)); return returnValue; } mitk::PointSet::Pointer mitk::NavigationDataEvaluationFilter::VectorToPointSet(std::vector pSet) { mitk::PointSet::Pointer returnValue = mitk::PointSet::New(); for (int i=0; iInsertPoint(i,thisPoint); } return returnValue; } std::vector mitk::NavigationDataEvaluationFilter::QuaternionsToEulerAngles(std::vector quaterions) { std::vector returnValue = std::vector(); for (int i=0; i mitk::NavigationDataEvaluationFilter::QuaternionsToEulerAnglesGrad(std::vector quaterions) { double PI = M_PI; std::vector returnValue = std::vector(); std::vector eulerAnglesRadians = QuaternionsToEulerAngles(quaterions); for (int i=0; i #include #include #include namespace mitk { /**Documentation * \brief NavigationDataEvaluationFilter calculates statistical data (mean value, mean error, etc.) on the input navigation data. * Input navigation data are set 1:1 on output navigation data. * * \ingroup IGT */ class MitkIGT_EXPORT NavigationDataEvaluationFilter : public NavigationDataToNavigationDataFilter { public: mitkClassMacro(NavigationDataEvaluationFilter, NavigationDataToNavigationDataFilter); itkNewMacro(Self); /** @brief Resets all statistics and starts again. */ void ResetStatistic(); /** @return Returns the number of analysed navigation datas for the specified input (without invalid samples). */ int GetNumberOfAnalysedNavigationData(int input); /** @return Returns the number of invalid samples for the specified input. Invalid samples are ignored for the statistical calculation.*/ int GetNumberOfInvalidSamples(int input); /** @return Returns the percentage of invalid samples in relation to all samples for the specified input.*/ double GetPercentageOfInvalidSamples(int input); /** @return Returns the mean position of the specified input since the start of the statistic (last call of ResetStatistic()) */ mitk::Point3D GetPositionMean(int input); /** @return Returns the standard derivation of each component (x, y and z) of the specified input since the start of the statistic (last call of ResetStatistic()) */ mitk::Vector3D GetPositionStandardDeviation(int input); /** @return Returns the sample standard derivation of each component (x, y and z) of the specified input since the start of the statistic (last call of ResetStatistic()) */ mitk::Vector3D GetPositionSampleStandardDeviation(int input); /** @return Returns the mean quaternion of the specified input since the start of the statistic (last call of ResetStatistic()) */ mitk::Quaternion GetQuaternionMean(int input); /** @return Returns the standard derivation of each component of the specified input since the start of the statistic (last call of ResetStatistic()) */ mitk::Quaternion GetQuaternionStandardDeviation(int input); /** @return Returns the mean euler angles (theta_x, theta_y, theta_z) of the specified input since the start of the statistic (last call of ResetStatistic()) */ mitk::Vector3D GetEulerAnglesMean(int input); /** @return Returns the RMS of the error of the euler angles (theta_x, theta_y, theta_z) in radians of the specified input since the start of the statistic (last call of ResetStatistic()) */ double GetEulerAnglesRMS(int input); /** @return Returns the RMS of the error of the euler angles (theta_x, theta_y, theta_z) in degree of the specified input since the start of the statistic (last call of ResetStatistic()) */ double GetEulerAnglesRMSDegree(int input); /** @return Returns the mean distance to the mean postion (=mean error) to the specified input. */ double GetPositionErrorMean(int input); /** @return Returns the standard derivation of the errors of all positions to the specified input. */ double GetPositionErrorStandardDeviation(int input); /** @return Returns the sample standard derivation of the errors of all positions to the specified input. */ double GetPositionErrorSampleStandardDeviation(int input); /** @return Returns the RMS of the errors of all positions to the specified input. */ double GetPositionErrorRMS(int input); /** @return Returns the median of the errors of all positions to the specified input. */ double GetPositionErrorMedian(int input); /** @return Returns the maximum of the errors of all positions to the specified input. */ double GetPositionErrorMax(int input); /** @return Returns the minimum of the errors of all positions to the specified input. */ double GetPositionErrorMin(int input); /** @return Returns a logged point on position i of the specified input. If there is no point on position i the method returns [0,0,0] */ mitk::Point3D GetLoggedPosition(int i, int input); /** @return Returns a logged orientation on position i of the specified input. If there is no orientation on position i the method returns [0,0,0,0] */ mitk::Quaternion GetLoggedOrientation(int i, int input); protected: NavigationDataEvaluationFilter(); virtual ~NavigationDataEvaluationFilter(); /**Documentation * \brief filter execute method * * transforms navigation data */ virtual void GenerateData(); /** @brief Creates the member variables which store all the statistical data for every input. */ void CreateMembersForAllInputs(); std::map > m_LoggedPositions; //a map here, to have one list for every navigation data std::map > m_LoggedQuaternions; std::map m_InavildSamples; mitk::Quaternion GetMean(std::vector list); mitk::PointSet::Pointer VectorToPointSet(std::vector pSet); mitk::PointSet::Pointer VectorToPointSet(std::vector pSet); /** @brief Converts a list of quaterions to a list of euler angles (theta_x, theta_y, theta_z) */ std::vector QuaternionsToEulerAngles(std::vector quaterions); //in radians std::vector QuaternionsToEulerAnglesGrad(std::vector quaterions); //in degree }; } // namespace mitk -#endif /* MITKNavigationDataEvaluationFilter_H_HEADER_INCLUDED_ */ \ No newline at end of file +#endif /* MITKNavigationDataEvaluationFilter_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/IGTFilters/mitkNavigationDataPlayer.cpp b/Modules/IGT/IGTFilters/mitkNavigationDataPlayer.cpp index b9a8cc4802..aad1e3bc7c 100644 --- a/Modules/IGT/IGTFilters/mitkNavigationDataPlayer.cpp +++ b/Modules/IGT/IGTFilters/mitkNavigationDataPlayer.cpp @@ -1,536 +1,536 @@ /*=================================================================== 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 "mitkNavigationDataPlayer.h" //for the pause #include #include #include mitk::NavigationDataPlayer::NavigationDataPlayer() : mitk::NavigationDataPlayerBase() { m_NumberOfOutputs = 0; m_Pause = false; m_Playing = false; m_Stream = NULL; m_PlayerMode = NormalFile; m_FileName = ""; m_FileVersion = 1; m_Playing = false; m_Pause = false; m_NumberOfOutputs = 0; m_StartPlayingTimeStamp = 0.0; m_PauseTimeStamp = 0.0; m_parentElement = NULL; m_currentNode = NULL; m_StreamEnd = false; m_StreamSetOutsideFromClass = false; //To get a start time mitk::TimeStamp::GetInstance()->Start(this); } mitk::NavigationDataPlayer::~NavigationDataPlayer() { StopPlaying(); delete m_parentElement; } void mitk::NavigationDataPlayer::GenerateData() { //Only produce new output if the player is started if (!m_Playing) { //The output is not valid anymore for (unsigned int index = 0; index < m_NumberOfOutputs; index++) { mitk::NavigationData* output = this->GetOutput(index); assert(output); mitk::NavigationData::Pointer nd = mitk::NavigationData::New(); mitk::NavigationData::PositionType position; mitk::NavigationData::OrientationType orientation(0.0,0.0,0.0,0.0); position.Fill(0.0); nd->SetPosition(position); nd->SetOrientation(orientation); nd->SetDataValid(false); output->Graft(nd); } return; } //first of all get current time TimeStampType now = mitk::TimeStamp::GetInstance()->GetElapsed(); //now we make a little time arithmetic //to get the elapsed time since the start of the player TimeStampType timeSinceStart = now - m_StartPlayingTimeStamp; //init the vectors std::vector< NavigationData::Pointer > nextCandidates; std::vector< NavigationData::Pointer > lastCandidates; std::vector< NavigationData::TimeStampType > currentTimeOfData; for (unsigned int index=0; index < m_NumberOfOutputs; index++) { nextCandidates.push_back(m_NextToPlayNavigationData.at(index)); lastCandidates.push_back(m_NextToPlayNavigationData.at(index)); currentTimeOfData.push_back(timeSinceStart + m_StartTimeOfData.at(index)); } if (m_NextToPlayNavigationData.size() != m_NumberOfOutputs) { MITK_ERROR << "Mismatch in data"; return; } // Now we try to find next NavigationData in the stream: // This means we step through the stream of NavigationDatas until we find // a NavigationData which has a current timestamp (currentTimeOfData) greater // then the current playing time. Then we store the data in // m_NextToPlayNavigationData and take the last data (lastCandidates) for the // output of this filter. // // The loop will stop when a suitable NavigationData is found or we reach EOF. // The timestamps of each recorded NavigationData should be equal // therefore we take always the time from the first. while( nextCandidates[0]->GetTimeStamp() < currentTimeOfData[0]) { for (unsigned int index=0; index < m_NumberOfOutputs; index++) { lastCandidates[index] = nextCandidates.at(index); switch(m_FileVersion) { case 1: nextCandidates[index] = ReadVersion1(); break; default: //this case should not happen! therefore the return at this point return; break; } //check if the input stream delivered a correct NavigationData object for (unsigned int i = 0; i < m_NumberOfOutputs; i++) { if (nextCandidates.at(index).IsNull()) { m_StreamEnd = true; StopPlaying(); return; //the case if no NavigationData is found, e.g. EOF, bad stream } } } } //Now lastCandidates stores the new output and nextCandidates is stored to the m_NextToPlay vector for (unsigned int index = 0; index < m_NumberOfOutputs; index++) { mitk::NavigationData* output = this->GetOutput(index); assert(output); output->Graft(lastCandidates.at(index)); m_NextToPlayNavigationData[index] = nextCandidates.at(index); } } void mitk::NavigationDataPlayer::UpdateOutputInformation() { this->Modified(); // make sure that we need to be updated Superclass::UpdateOutputInformation(); } void mitk::NavigationDataPlayer::InitPlayer() { if (m_Stream == NULL) { StreamInvalid("Playing not possible. Wrong file name or path?"); return; } if (!m_Stream->good()) { StreamInvalid("Playing not possible. Stream is not good!"); return; } m_FileVersion = GetFileVersion(m_Stream); //first get the file version //check if we have a valid version if (m_FileVersion < 1) { StreamInvalid("Playing not possible. Invalid file version!"); return; } //now read the number of Tracked Tools if(m_NumberOfOutputs == 0){m_NumberOfOutputs = GetNumberOfNavigationDatas(m_Stream);} //with the information about the tracked tool number we can generate the output if (m_NumberOfOutputs > 0) { //Generate the output only if there are changes to the amount of outputs //This happens when the player is stopped and start again with different file if (this->GetNumberOfOutputs() != m_NumberOfOutputs) {SetNumberOfOutputs(m_NumberOfOutputs);} //initialize the player with first data GetFirstData(); //set stream valid m_ErrorMessage = ""; m_StreamValid = true; } else { StreamInvalid("The input stream seems to have NavigationData incompatible format"); return; } } unsigned int mitk::NavigationDataPlayer::GetFileVersion(std::istream* stream) { if (stream==NULL) { MITK_ERROR << "No input stream set!"; return 0; } if (!stream->good()) { MITK_ERROR << "Stream not good!"; return 0; } int version = 1; TiXmlDeclaration* dec = new TiXmlDeclaration(); *stream >> *dec; if(strcmp(dec->Version(),"") == 0){ MITK_ERROR << "The input stream seems to have XML incompatible format"; return 0; } m_parentElement = new TiXmlElement(""); *stream >> *m_parentElement; //2nd line this is the file version std::string tempValue = m_parentElement->Value(); if(tempValue != "Version") { if(tempValue == "Data"){ m_parentElement->QueryIntAttribute("version",&version); } } else { m_parentElement->QueryIntAttribute("Ver",&version); } if (version > 0) return version; else return 0; } unsigned int mitk::NavigationDataPlayer::GetNumberOfNavigationDatas(std::istream* stream) { if (stream == NULL) { MITK_ERROR << "No input stream set!"; return 0; } if (!stream->good()) { MITK_ERROR << "Stream not good!"; return 0; } //If something has changed in a future version of the XML definition e.g. navigationcount or addional parameters //catch this here with a select case block (see GenerateData() method) int numberOfTools = 0; std::string tempValue = m_parentElement->Value(); if(tempValue == "Version"){ *stream >> *m_parentElement; } m_parentElement->QueryIntAttribute("ToolCount",&numberOfTools); if (numberOfTools > 0) return numberOfTools; return 0; } mitk::NavigationData::Pointer mitk::NavigationDataPlayer::ReadVersion1() { if (m_Stream == NULL) { m_Playing = false; MITK_ERROR << "Playing not possible. Wrong file name or path? "; return NULL; } if (!m_Stream->good()) { m_Playing = false; MITK_ERROR << "Playing not possible. Stream is not good!"; return NULL; } /*TiXmlElement* elem = new TiXmlElement(""); m_currentNode = m_parentElement->IterateChildren(m_currentNode); if(m_currentNode) { elem = m_currentNode->ToElement(); }*/ TiXmlElement* elem; m_currentNode = m_parentElement->IterateChildren(m_currentNode); bool delElem; if(m_currentNode) { elem = m_currentNode->ToElement(); delElem = false; } else { elem = new TiXmlElement(""); delElem = true; } mitk::NavigationData::Pointer nd = this->ReadNavigationData(elem); if(delElem) delete elem; return nd; } void mitk::NavigationDataPlayer::StartPlaying() { if (m_Stream == NULL) { m_Playing = false; //Perhaps the SetStream method was not called so we do this when a FileName is set with SetStream(PlayerMode) if (m_FileName != "") { //The PlayerMode is initialized with LastSetStream //SetStream also calls InitPlayer() SetStream(m_PlayerMode); } //now check again if (m_Stream == NULL) { StopPlaying(); MITK_ERROR << "Playing not possible. Wrong file name or path?"; return; } } if (!m_Playing && m_Stream->good()) { m_Playing = true; //starts the player m_StartPlayingTimeStamp = mitk::TimeStamp::GetInstance()->GetElapsed(); } else { MITK_ERROR << "Player already started or stream is not good!"; StopPlaying(); } } void mitk::NavigationDataPlayer::StopPlaying() { //re init all data!! for playing again with different data //only PlayerMode and FileName are not changed m_Pause = false; m_Playing = false; if (!m_StreamSetOutsideFromClass) {delete m_Stream;} m_Stream = NULL; m_FileVersion = 1; m_Playing = false; m_Pause = false; m_StartPlayingTimeStamp = 0.0; m_PauseTimeStamp = 0.0; m_NextToPlayNavigationData.clear(); m_StartTimeOfData.clear(); } void mitk::NavigationDataPlayer::GetFirstData() { //Here we read the first lines of input (dependend on the number of inputs) for (unsigned int index=0; index < m_NumberOfOutputs; index++) { //Here we init the vector for later use m_NextToPlayNavigationData.push_back(NULL); m_StartTimeOfData.push_back(0.0); mitk::NavigationData::Pointer nd = this->GetOutput(index); switch(m_FileVersion) { case 1: m_NextToPlayNavigationData[index] = ReadVersion1(); //check if there is valid data in it if (m_NextToPlayNavigationData[index].IsNull()) { m_StreamEnd = true; StopPlaying(); MITK_ERROR << "XML File is corrupt or has no NavigationData" << std::endl; return; } //Have a look it the output was set already without this check the pipline will disconnect after a start/stop cycle if (nd.IsNull()) this->SetNthOutput(index, m_NextToPlayNavigationData[index]); m_StartTimeOfData[index] = m_NextToPlayNavigationData[index]->GetTimeStamp(); break; default: //this case should not happen! therefore the return at this point return; break; } } } void mitk::NavigationDataPlayer::Pause() { //player runs and pause was called -> pause the player if(m_Playing && !m_Pause) { m_Playing = false; m_Pause = true; m_PauseTimeStamp = mitk::TimeStamp::GetInstance()->GetElapsed(); } else { MITK_ERROR << "Player is either not started or already is paused" << std::endl; } } void mitk::NavigationDataPlayer::Resume() { //player is in pause mode -> play at the last position if(!m_Playing && m_Pause) { m_Playing = true; m_Pause = false; mitk::NavigationData::TimeStampType now = mitk::TimeStamp::GetInstance()->GetElapsed(); // in this case m_StartPlayingTimeStamp is set to the total elapsed time with NO playback m_StartPlayingTimeStamp = now - (m_PauseTimeStamp - m_StartPlayingTimeStamp); } else { MITK_ERROR << "Player is not paused!" << std::endl; } } void mitk::NavigationDataPlayer::SetStream( PlayerMode /*mode*/ ) { m_Stream = NULL; if (!itksys::SystemTools::FileExists(m_FileName.c_str())) { MITK_ERROR << "File dont exist!" << std::endl; return; } switch(m_PlayerMode) { case NormalFile: m_Stream = new std::ifstream(m_FileName.c_str()); m_StreamSetOutsideFromClass = false; break; case ZipFile: m_Stream = NULL; MITK_ERROR << "Sorry no ZipFile support yet"; break; default: m_Stream = NULL; break; } this->Modified(); InitPlayer(); } void mitk::NavigationDataPlayer::SetStream( std::istream* stream ) { if ( (stream == NULL) || (!stream->good())) { m_StreamEnd = true; MITK_ERROR << "The stream is not good"; return; } m_Stream = stream; m_StreamSetOutsideFromClass = true; this->Modified(); InitPlayer(); } bool mitk::NavigationDataPlayer::IsAtEnd() { return this->m_StreamEnd; } void mitk::NavigationDataPlayer::StreamInvalid(std::string message) { m_StreamEnd = true; StopPlaying(); m_ErrorMessage = message; m_StreamValid = false; MITK_ERROR << m_ErrorMessage; return; -} \ No newline at end of file +} diff --git a/Modules/IGT/IGTFilters/mitkRealTimeClock.cpp b/Modules/IGT/IGTFilters/mitkRealTimeClock.cpp index 88823bad84..744620b16b 100644 --- a/Modules/IGT/IGTFilters/mitkRealTimeClock.cpp +++ b/Modules/IGT/IGTFilters/mitkRealTimeClock.cpp @@ -1,37 +1,37 @@ /*=================================================================== 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 "mitkRealTimeClock.h" // check if MITK runs on a Windows-System #ifdef _WIN32 #include "mitkWindowsRealTimeClock.h" #else // should be Linux or Mac OSX #include "mitkLinuxRealTimeClock.h" #endif mitk::RealTimeClock::Pointer mitk::RealTimeClock::New() { mitk::RealTimeClock::Pointer smartPtr; #ifdef _WIN32 smartPtr = mitk::WindowsRealTimeClock::New(); #else smartPtr = mitk::LinuxRealTimeClock::New(); #endif return smartPtr; -} \ No newline at end of file +} diff --git a/Modules/IGT/IGTFilters/mitkTrackingDeviceSourceConfigurator.cpp b/Modules/IGT/IGTFilters/mitkTrackingDeviceSourceConfigurator.cpp index 96a0932987..d9e9326059 100644 --- a/Modules/IGT/IGTFilters/mitkTrackingDeviceSourceConfigurator.cpp +++ b/Modules/IGT/IGTFilters/mitkTrackingDeviceSourceConfigurator.cpp @@ -1,250 +1,250 @@ /*=================================================================== 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 "mitkTrackingDeviceSourceConfigurator.h" #include "mitkNDITrackingDevice.h" #include "mitkClaronTrackingDevice.h" mitk::TrackingDeviceSourceConfigurator::TrackingDeviceSourceConfigurator(mitk::NavigationToolStorage::Pointer NavigationTools, mitk::TrackingDevice::Pointer TrackingDevice) { //make a copy of the navigation tool storage because we will modify the storage if (NavigationTools.IsNotNull()) { m_NavigationTools = mitk::NavigationToolStorage::New(); for (int i=0; iGetToolCount(); i++) { m_NavigationTools->AddTool(NavigationTools->GetTool(i)); } } m_TrackingDevice = TrackingDevice; m_ToolCorrespondencesInToolStorage = std::vector(); m_ErrorMessage = ""; } mitk::NavigationToolStorage::Pointer mitk::TrackingDeviceSourceConfigurator::GetUpdatedNavigationToolStorage() { return m_NavigationTools; } mitk::TrackingDeviceSourceConfigurator::~TrackingDeviceSourceConfigurator() { } bool mitk::TrackingDeviceSourceConfigurator::IsCreateTrackingDeviceSourcePossible() { if (m_NavigationTools.IsNull()) { m_ErrorMessage = "NavigationToolStorage is NULL!"; return false; } else if (m_TrackingDevice.IsNull()) { m_ErrorMessage = "TrackingDevice is NULL!"; return false; } else { for (int i=0; iGetToolCount(); i++) { if (m_NavigationTools->GetTool(i)->GetTrackingDeviceType() != m_TrackingDevice->GetType()) { m_ErrorMessage = "At least one tool is not of the same type like the tracking device."; return false; } } //TODO in case of Aurora: check if the tools are automatically detected by comparing the serial number return true; } } mitk::TrackingDeviceSource::Pointer mitk::TrackingDeviceSourceConfigurator::CreateTrackingDeviceSource() { mitk::NavigationDataObjectVisualizationFilter::Pointer dummy; return this->CreateTrackingDeviceSource(dummy); } mitk::TrackingDeviceSource::Pointer mitk::TrackingDeviceSourceConfigurator::CreateTrackingDeviceSource(mitk::NavigationDataObjectVisualizationFilter::Pointer &visualizationFilter) { if (!this->IsCreateTrackingDeviceSourcePossible()) return NULL; mitk::TrackingDeviceSource::Pointer returnValue; //create tracking device source if (m_TrackingDevice->GetType()==mitk::NDIAurora) {returnValue = CreateNDIAuroraTrackingDeviceSource(m_TrackingDevice,m_NavigationTools);} else if (m_TrackingDevice->GetType()==mitk::NDIPolaris) {returnValue = CreateNDIPolarisTrackingDeviceSource(m_TrackingDevice,m_NavigationTools);} else if (m_TrackingDevice->GetType()==mitk::ClaronMicron) {returnValue = CreateMicronTrackerTrackingDeviceSource(m_TrackingDevice,m_NavigationTools);} //TODO: insert other tracking systems? if (returnValue.IsNull()) return NULL; //create visualization filter visualizationFilter = CreateNavigationDataObjectVisualizationFilter(returnValue,m_NavigationTools); if (visualizationFilter.IsNull()) return NULL; return returnValue; } std::string mitk::TrackingDeviceSourceConfigurator::GetErrorMessage() { return this->m_ErrorMessage; } //############################ internal help methods ######################################## mitk::TrackingDeviceSource::Pointer mitk::TrackingDeviceSourceConfigurator::CreateNDIPolarisTrackingDeviceSource(mitk::TrackingDevice::Pointer trackingDevice, mitk::NavigationToolStorage::Pointer navigationTools) { mitk::TrackingDeviceSource::Pointer returnValue = mitk::TrackingDeviceSource::New(); mitk::NDITrackingDevice::Pointer thisDevice = dynamic_cast(trackingDevice.GetPointer()); m_ToolCorrespondencesInToolStorage = std::vector(); //add the tools to the tracking device for (int i=0; iGetToolCount(); i++) { mitk::NavigationTool::Pointer thisNavigationTool = m_NavigationTools->GetTool(i); m_ToolCorrespondencesInToolStorage.push_back(i); bool toolAddSuccess = thisDevice->AddTool(thisNavigationTool->GetToolName().c_str(),thisNavigationTool->GetCalibrationFile().c_str()); if (!toolAddSuccess) { this->m_ErrorMessage = "Can't add tool, is the SROM-file valid?"; return NULL; } } returnValue->SetTrackingDevice(thisDevice); return returnValue; } mitk::TrackingDeviceSource::Pointer mitk::TrackingDeviceSourceConfigurator::CreateNDIAuroraTrackingDeviceSource(mitk::TrackingDevice::Pointer trackingDevice, mitk::NavigationToolStorage::Pointer navigationTools) { mitk::TrackingDeviceSource::Pointer returnValue = mitk::TrackingDeviceSource::New(); mitk::NDITrackingDevice::Pointer thisDevice = dynamic_cast(trackingDevice.GetPointer()); //connect to aurora to dectect tools automatically thisDevice->OpenConnection(); thisDevice->StartTracking(); //now search for automatically detected tools in the tool storage and save them mitk::NavigationToolStorage::Pointer newToolStorageInRightOrder = mitk::NavigationToolStorage::New(); std::vector alreadyFoundTools = std::vector(); m_ToolCorrespondencesInToolStorage = std::vector(); for (int i=0; iGetToolCount(); i++) { bool toolFound = false; for (int j=0; jGetToolCount(); j++) { //check if the serial number is the same to identify the tool if ((dynamic_cast(thisDevice->GetTool(i)))->GetSerialNumber() == navigationTools->GetTool(j)->GetSerialNumber()) { //check if this tool was already added to make sure that every tool is only added once (in case of same serial numbers) bool toolAlreadyAdded = false; for(int k=0; kAddTool(navigationTools->GetTool(j)); m_ToolCorrespondencesInToolStorage.push_back(j); //adapt name of tool dynamic_cast(thisDevice->GetTool(i))->SetToolName(navigationTools->GetTool(j)->GetToolName()); //rember that this tool was already found alreadyFoundTools.push_back(j); toolFound = true; break; } } } if (!toolFound) { this->m_ErrorMessage = "Error: did not find every automatically detected tool in the loaded tool storage: aborting initialization."; return NULL; } } //delete all tools from the tool storage navigationTools->DeleteAllTools(); //and add only the detected tools in the right order for (int i=0; iGetToolCount(); i++) { navigationTools->AddTool(newToolStorageInRightOrder->GetTool(i)); } returnValue->SetTrackingDevice(thisDevice); return returnValue; } mitk::TrackingDeviceSource::Pointer mitk::TrackingDeviceSourceConfigurator::CreateMicronTrackerTrackingDeviceSource(mitk::TrackingDevice::Pointer trackingDevice, mitk::NavigationToolStorage::Pointer navigationTools) { mitk::TrackingDeviceSource::Pointer returnValue = mitk::TrackingDeviceSource::New(); mitk::ClaronTrackingDevice::Pointer thisDevice = dynamic_cast(trackingDevice.GetPointer()); m_ToolCorrespondencesInToolStorage = std::vector(); //add the tools to the tracking device for (int i=0; iGetToolCount(); i++) { mitk::NavigationTool::Pointer thisNavigationTool = m_NavigationTools->GetTool(i); m_ToolCorrespondencesInToolStorage.push_back(i); bool toolAddSuccess = thisDevice->AddTool(thisNavigationTool->GetToolName().c_str(),thisNavigationTool->GetCalibrationFile().c_str()); if (!toolAddSuccess) { this->m_ErrorMessage = "Can't add tool, is the toolfile valid?"; return NULL; } } returnValue->SetTrackingDevice(thisDevice); return returnValue; } mitk::NavigationDataObjectVisualizationFilter::Pointer mitk::TrackingDeviceSourceConfigurator::CreateNavigationDataObjectVisualizationFilter(mitk::TrackingDeviceSource::Pointer trackingDeviceSource, mitk::NavigationToolStorage::Pointer navigationTools) { mitk::NavigationDataObjectVisualizationFilter::Pointer returnValue = mitk::NavigationDataObjectVisualizationFilter::New(); for (int i=0; iGetNumberOfOutputs(); i++) { mitk::NavigationTool::Pointer currentTool = navigationTools->GetToolByName(trackingDeviceSource->GetOutput(i)->GetName()); if (currentTool.IsNull()) { this->m_ErrorMessage = "Error: did not find correspondig tool in tracking device after initialization."; return NULL; } returnValue->SetInput(i,trackingDeviceSource->GetOutput(i)); returnValue->SetRepresentationObject(i,currentTool->GetDataNode()->GetData()); } return returnValue; } int mitk::TrackingDeviceSourceConfigurator::GetToolNumberInToolStorage(int outputID) { if (outputID < m_ToolCorrespondencesInToolStorage.size()) return m_ToolCorrespondencesInToolStorage.at(outputID); else return -1; } std::string mitk::TrackingDeviceSourceConfigurator::GetToolIdentifierInToolStorage(int outputID) { if (outputID < m_ToolCorrespondencesInToolStorage.size()) return m_NavigationTools->GetTool(m_ToolCorrespondencesInToolStorage.at(outputID))->GetIdentifier(); else return ""; } std::vector mitk::TrackingDeviceSourceConfigurator::GetToolNumbersInToolStorage() { return m_ToolCorrespondencesInToolStorage; } std::vector mitk::TrackingDeviceSourceConfigurator::GetToolIdentifiersInToolStorage() { std::vector returnValue = std::vector(); for (int i=0; iGetTool(m_ToolCorrespondencesInToolStorage.at(i))->GetIdentifier());} return returnValue; - } \ No newline at end of file + } diff --git a/Modules/IGT/IGTFilters/mitkTrackingDeviceSourceConfigurator.h b/Modules/IGT/IGTFilters/mitkTrackingDeviceSourceConfigurator.h index 8c4d5a679d..17befb16c3 100644 --- a/Modules/IGT/IGTFilters/mitkTrackingDeviceSourceConfigurator.h +++ b/Modules/IGT/IGTFilters/mitkTrackingDeviceSourceConfigurator.h @@ -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. ===================================================================*/ #ifndef MITKTRACKINGDEVICESOURCECONFIGURATOR_H_HEADER_INCLUDED_ #define MITKTRACKINGDEVICESOURCECONFIGURATOR_H_HEADER_INCLUDED_ #include //itk includes #include //mitk IGT includes #include "mitkTrackingDeviceSource.h" #include "mitkNavigationToolStorage.h" #include "mitkNavigationDataObjectVisualizationFilter.h" namespace mitk { /**Documentation * \brief This class offers a factory method for objects of the class TrackingDeviceSource. It initializes this TrackingDeviceSource with * the given navigation tools and the given tracking device. The factory method also checks if all tools are valid and of the same * type like the TrackingDevice. You can do this check before trying to create the TrackingDeviceSource by calling the method * IsCreateTrackingDeviceSourcePossible(), if it returns false you might want to get the error message by calling the method * GetErrorMessage(). * \ingroup IGT */ class MitkIGT_EXPORT TrackingDeviceSourceConfigurator : public itk::Object { public: mitkClassMacro(TrackingDeviceSourceConfigurator, itk::Object); mitkNewMacro2Param(Self,mitk::NavigationToolStorage::Pointer,mitk::TrackingDevice::Pointer); /** @return Returns if it's possible to create a tracking device source, which means the tools are checked * if they are of the same type like the tracking device, etc. If it returns false you can get * the reason for this by getting the error message. */ bool IsCreateTrackingDeviceSourcePossible(); /** @return Returns a new TrackingDeviceSource. Returns NULL if there was an error on creating the * TrackingDeviceSource. If there was an error it's availiable as error message. */ mitk::TrackingDeviceSource::Pointer CreateTrackingDeviceSource(); /** @return Returns a new TrackingDeviceSource. Returns NULL if there was an error on creating the * TrackingDeviceSource. If there was an error it's availiable as error message. * @param visualizationFilter (return value) returns a visualization filter which is already connected to the tracking device source. * This filter visualises the surfaces which are availiable by the navigation tool storage. */ mitk::TrackingDeviceSource::Pointer CreateTrackingDeviceSource(mitk::NavigationDataObjectVisualizationFilter::Pointer &visualizationFilter); /** @return Returns the internal number of the corresponding tool in the tool storage of a output navigation data. Returns -1 if there was an error. */ int GetToolNumberInToolStorage(int outputID); /** @return Returns the identifier of the corresponding tool in the tool storage of a output navigation data. Returns an empty string if there was an error.*/ std::string GetToolIdentifierInToolStorage(int outputID); /** @return Returns a vector with all internal numbers of the corresponding tools in the tool storage of all outputs. * The order is the same like the order of the outputs. Returns an empty vector if there was an error. */ std::vector GetToolNumbersInToolStorage(); /** @return Returns a vector with all identifier of the corresponding tools in the tool storage of all outputs. * The order is the same like the order of the outputs. Returns an empty vector if there was an error. */ std::vector GetToolIdentifiersInToolStorage(); /** @return Returns a modified navigation tool storage which holds the tools currently in use in * the same order like the output ids of the pipline. */ mitk::NavigationToolStorage::Pointer GetUpdatedNavigationToolStorage(); /** @return Returns the current error message. Returns an empty string if there was no error. */ std::string GetErrorMessage(); protected: TrackingDeviceSourceConfigurator(mitk::NavigationToolStorage::Pointer NavigationTools, mitk::TrackingDevice::Pointer TrackingDevice); virtual ~TrackingDeviceSourceConfigurator(); mitk::NavigationToolStorage::Pointer m_NavigationTools; mitk::TrackingDevice::Pointer m_TrackingDevice; std::string m_ErrorMessage; std::vector m_ToolCorrespondencesInToolStorage; mitk::TrackingDeviceSource::Pointer CreateNDIPolarisTrackingDeviceSource(mitk::TrackingDevice::Pointer trackingDevice, mitk::NavigationToolStorage::Pointer navigationTools); mitk::TrackingDeviceSource::Pointer CreateNDIAuroraTrackingDeviceSource(mitk::TrackingDevice::Pointer trackingDevice, mitk::NavigationToolStorage::Pointer navigationTools); mitk::TrackingDeviceSource::Pointer CreateMicronTrackerTrackingDeviceSource(mitk::TrackingDevice::Pointer trackingDevice, mitk::NavigationToolStorage::Pointer navigationTools); mitk::NavigationDataObjectVisualizationFilter::Pointer CreateNavigationDataObjectVisualizationFilter(mitk::TrackingDeviceSource::Pointer trackingDeviceSource, mitk::NavigationToolStorage::Pointer navigationTools); }; } // namespace mitk -#endif /* MITKTrackingDeviceSource_H_HEADER_INCLUDED_ */ \ No newline at end of file +#endif /* MITKTrackingDeviceSource_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/IGTFilters/mitkWindowsRealTimeClock.h b/Modules/IGT/IGTFilters/mitkWindowsRealTimeClock.h index dad96e8a43..376a9e7889 100644 --- a/Modules/IGT/IGTFilters/mitkWindowsRealTimeClock.h +++ b/Modules/IGT/IGTFilters/mitkWindowsRealTimeClock.h @@ -1,83 +1,83 @@ /*=================================================================== 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 MITKWINDOWSREALTIMECLOCK_H_HEADER_INCLUDED_ #define MITKWINDOWSREALTIMECLOCK_H_HEADER_INCLUDED_ #include "MitkIGTExports.h" #include "mitkRealTimeClock.h" namespace mitk { /** * \brief realtimeclock implementation for windows-systems * * This class provides a RealTimeClock for windows-systems. * Internally, it uses the QueryPerformanceCounter and the QueryPerformaceFrequency. * It polls the current tick-counter, that counts from bootup. * is supposed to be the most accurate time you can get on a windows-system. * * \ingroup Navigation */ class MitkIGT_EXPORT WindowsRealTimeClock : public RealTimeClock { public: mitkClassMacro(WindowsRealTimeClock, mitk::RealTimeClock); itkNewMacro(Self); /** * \brief basic contructor */ WindowsRealTimeClock(); /** * \brief basic destructor */ virtual ~WindowsRealTimeClock(); /** * \brief returns the current time in milliseconds as a double * * Uses the QueryPerformanceCounter to acquire an accurate time. * (Ticks counted / Frequency) = time in ms */ virtual double GetCurrentStamp(); /** * \brief returns the QueryPerformanceFrequency */ virtual LARGE_INTEGER GetFrequency(); protected: void SetFrequency(); /** * \brief Frequency needed to calculate time from tick-counter */ LARGE_INTEGER m_Frequency; }; //namespace } -#endif /* MITKWINDOWSREALTIMECLOCK_H_HEADER_INCLUDED_ */ \ No newline at end of file +#endif /* MITKWINDOWSREALTIMECLOCK_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/IGTToolManagement/mitkNavigationTool.cpp b/Modules/IGT/IGTToolManagement/mitkNavigationTool.cpp index 7b304e9c34..05eab9538f 100644 --- a/Modules/IGT/IGTToolManagement/mitkNavigationTool.cpp +++ b/Modules/IGT/IGTToolManagement/mitkNavigationTool.cpp @@ -1,62 +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. ===================================================================*/ #include "mitkNavigationTool.h" #include "Poco/File.h" mitk::NavigationTool::NavigationTool() { m_Type = mitk::NavigationTool::Unknown; m_Identifier = "None"; m_TrackingDeviceType = mitk::TrackingSystemNotSpecified; m_CalibrationFile = "none"; m_SerialNumber = ""; } mitk::NavigationTool::~NavigationTool() { } void mitk::NavigationTool::SetCalibrationFile(const std::string filename) { //check if file does exist: if (filename=="") { m_CalibrationFile = "none"; } else { Poco::File myFile(filename); if (myFile.exists()) m_CalibrationFile = filename; else m_CalibrationFile = "none"; } } std::string mitk::NavigationTool::GetToolName() { if (this->m_DataNode.IsNull()) {return "";} else {return m_DataNode->GetName();} } mitk::Surface::Pointer mitk::NavigationTool::GetToolSurface() { if (this->m_DataNode.IsNull()) {return NULL;} else if (this->m_DataNode->GetData() == NULL) {return NULL;} else {return dynamic_cast(m_DataNode->GetData());} - } \ No newline at end of file + } diff --git a/Modules/IGT/IGTToolManagement/mitkNavigationTool.h b/Modules/IGT/IGTToolManagement/mitkNavigationTool.h index 61660f8538..482efcdf87 100644 --- a/Modules/IGT/IGTToolManagement/mitkNavigationTool.h +++ b/Modules/IGT/IGTToolManagement/mitkNavigationTool.h @@ -1,122 +1,122 @@ /*=================================================================== 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 NAVIGATIONTOOL_H_INCLUDED #define NAVIGATIONTOOL_H_INCLUDED //itk headers #include #include //mitk headers #include #include #include #include #include #include namespace mitk { /**Documentation * \brief An object of this class represents a navigation tool in the view of the software. * A few informations like an identifier, a toolname, a surface and a itk spatial * object are stored in such an object. The classes NavigationToolReader and * are availiable to write/read tools to/from the harddisc. If you need a collection * of navigation tools the class NavigationToolStorage could be used. * * \ingroup IGT */ class MitkIGT_EXPORT NavigationTool : public itk::Object { public: mitkClassMacro(NavigationTool,itk::Object); itkNewMacro(Self); enum NavigationToolType {Instrument, Fiducial, Skinmarker, Unknown}; //## getter and setter ## //NavigationToolType: itkGetMacro(Type,NavigationToolType); itkSetMacro(Type,NavigationToolType); //Identifier: itkGetMacro(Identifier,std::string); itkSetMacro(Identifier,std::string); //Datatreenode: itkGetMacro(DataNode,mitk::DataNode::Pointer); itkSetMacro(DataNode,mitk::DataNode::Pointer); //SpatialObject: itkGetMacro(SpatialObject,itk::SpatialObject<3>::Pointer); itkSetMacro(SpatialObject,itk::SpatialObject<3>::Pointer); //TrackingTool: itkGetMacro(TrackingTool,mitk::TrackingTool::Pointer); itkSetMacro(TrackingTool,mitk::TrackingTool::Pointer); //CalibrationFile: itkGetMacro(CalibrationFile,std::string); void SetCalibrationFile(const std::string filename); //itkSetMacro(CalibrationFile,std::string); //SerialNumber: itkGetMacro(SerialNumber,std::string); itkSetMacro(SerialNumber,std::string); //TrackingDeviceType: itkGetMacro(TrackingDeviceType,mitk::TrackingDeviceType); itkSetMacro(TrackingDeviceType,mitk::TrackingDeviceType); //ToolName (only getter): /** @return Returns the name of this navigation tool. Returns an empty string if there is * no name (for example because the data node has not been set yet). * * Note: There is no setter for the name, * because the name of the corresponding data node is used as tool name. So if you * want to modify the name of this navigation tool only get the data node and modify * its name. */ std::string GetToolName(); //ToolSurface (only getter): /** @return Returns the surface of this navigation tool. Returns NULL if there is * no surface (for example because the data node has not been set yet). * * Note: There is no setter for the surface, * because the surface is the data of the corresponding data node. So if you * want to set a new surface only get the data node and modify its data. */ mitk::Surface::Pointer GetToolSurface(); //####################### protected: NavigationTool(); ~NavigationTool(); //## data structure of a navigation tool object ## std::string m_Identifier; NavigationToolType m_Type; /** @brief This DataNode holds a toolname and a tool surface */ mitk::DataNode::Pointer m_DataNode; /** @brief This member variable holds a mathamatical description of the tool */ itk::SpatialObject<3>::Pointer m_SpatialObject; /** @brief This member variable holds a pointer to the corresponding tracking tool in the hardware. */ mitk::TrackingTool::Pointer m_TrackingTool; /** @brief The path to the calibration file of the tool. */ std::string m_CalibrationFile; /** @brief A unique serial number of the tool which is needed to identify the tool correctly. This is very important * in case of the NDI Aurora System. */ std::string m_SerialNumber; /** @brief This member holds the tracking device type of the tool. */ mitk::TrackingDeviceType m_TrackingDeviceType; //################################################# }; } // namespace mitk -#endif //NAVIGATIONTOOL \ No newline at end of file +#endif //NAVIGATIONTOOL diff --git a/Modules/IGT/IGTToolManagement/mitkNavigationToolStorageDeserializer.cpp b/Modules/IGT/IGTToolManagement/mitkNavigationToolStorageDeserializer.cpp index 8b31babf8c..1f5da4113f 100644 --- a/Modules/IGT/IGTToolManagement/mitkNavigationToolStorageDeserializer.cpp +++ b/Modules/IGT/IGTToolManagement/mitkNavigationToolStorageDeserializer.cpp @@ -1,116 +1,116 @@ /*=================================================================== 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. ===================================================================*/ //Poco headers #include "Poco/Zip/Decompress.h" #include "Poco/Path.h" #include "Poco/File.h" #include "mitkNavigationToolStorageDeserializer.h" #include #include #include "mitkNavigationToolReader.h" //POCO #include mitk::NavigationToolStorageDeserializer::NavigationToolStorageDeserializer(mitk::DataStorage::Pointer dataStorage) { m_DataStorage = dataStorage; //create temp directory for this reader m_tempDirectory = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + Poco::Path::separator() + "tempNavigationToolDeserializer"; Poco::File myFile(m_tempDirectory); myFile.createDirectory(); } mitk::NavigationToolStorageDeserializer::~NavigationToolStorageDeserializer() { //remove temp directory Poco::File myFile(m_tempDirectory); try { if (myFile.exists()) myFile.remove(); } catch(...) { MITK_ERROR << "Can't remove temp directory " << m_tempDirectory << "!"; } } mitk::NavigationToolStorage::Pointer mitk::NavigationToolStorageDeserializer::Deserialize(std::string filename) { bool success = false; //decomress zip file into temporary directory success = decomressFiles(filename,m_tempDirectory); //currently returns an empty storage in case of an error. TODO when exception handling is availiable in MITK: Throw an exception? if (!success) {return mitk::NavigationToolStorage::New();} //now read all files and convert them to navigation tools mitk::NavigationToolStorage::Pointer returnValue = mitk::NavigationToolStorage::New(m_DataStorage); bool cont = true; int i; for (i=0; cont==true; i++) { std::string fileName = m_tempDirectory + Poco::Path::separator() + "NavigationTool" + convertIntToString(i) + ".tool"; mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New(); mitk::NavigationTool::Pointer readTool = myReader->DoRead(fileName); if (readTool.IsNull()) cont = false; else returnValue->AddTool(readTool); //delete file std::remove(fileName.c_str()); } if(i==1) { m_ErrorMessage = "Error: did not find any tool. \n Is this a tool storage file?"; MITK_ERROR << "Error: did not find any tool. Is this a tool storage file?"; } return returnValue; } std::string mitk::NavigationToolStorageDeserializer::convertIntToString(int i) { std::string s; std::stringstream out; out << i; s = out.str(); return s; } bool mitk::NavigationToolStorageDeserializer::decomressFiles(std::string filename,std::string path) { std::ifstream file( filename.c_str(), std::ios::binary ); if (!file.good()) { m_ErrorMessage = "Cannot open '" + filename + "' for reading"; return false; } try { Poco::Zip::Decompress unzipper( file, Poco::Path( path ) ); unzipper.decompressAllFiles(); file.close(); } catch(Poco::IllegalStateException e) //temporary solution: replace this by defined exception handling later! { m_ErrorMessage = "Error: wrong file format! \n (please only load tool storage files)"; MITK_ERROR << "Error: wrong file format! (please only load tool storage files)"; return false; } return true; - } \ No newline at end of file + } diff --git a/Modules/IGT/IGTToolManagement/mitkNavigationToolStorageDeserializer.h b/Modules/IGT/IGTToolManagement/mitkNavigationToolStorageDeserializer.h index c92eee13db..0dfb1e4a07 100644 --- a/Modules/IGT/IGTToolManagement/mitkNavigationToolStorageDeserializer.h +++ b/Modules/IGT/IGTToolManagement/mitkNavigationToolStorageDeserializer.h @@ -1,68 +1,68 @@ /*=================================================================== 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 NAVIGATIONTOOLSTORAGEDESERIALIZER_H_INCLUDED #define NAVIGATIONTOOLSTORAGEDESERIALIZER_H_INCLUDED //itk headers #include //mitk headers #include #include #include "mitkNavigationToolStorage.h" #include namespace mitk { /**Documentation * \brief This class offers methods to load an object of the class NavigationToolStorage * from the harddisc. * * \ingroup IGT */ class MitkIGT_EXPORT NavigationToolStorageDeserializer : public itk::Object { public: mitkClassMacro(NavigationToolStorageDeserializer,itk::Object); mitkNewMacro1Param(Self,mitk::DataStorage::Pointer); /** * @brief Loads a collection of navigation tools represented by a mitk::NavigationToolStorage * from a file. * @return Returns the storage which was loaded or an empty storage if there was an error in the loading process. * */ mitk::NavigationToolStorage::Pointer Deserialize(std::string filename); itkGetMacro(ErrorMessage,std::string); protected: NavigationToolStorageDeserializer(mitk::DataStorage::Pointer dataStorage); ~NavigationToolStorageDeserializer(); std::string m_ErrorMessage; mitk::DataStorage::Pointer m_DataStorage; std::string m_tempDirectory; std::string convertIntToString(int i); bool decomressFiles(std::string file,std::string path); }; } // namespace mitk -#endif //NAVIGATIONTOOLSTORAGEDESERIALIZER \ No newline at end of file +#endif //NAVIGATIONTOOLSTORAGEDESERIALIZER diff --git a/Modules/IGT/IGTToolManagement/mitkNavigationToolStorageSerializer.h b/Modules/IGT/IGTToolManagement/mitkNavigationToolStorageSerializer.h index 9835884825..cd2ce9dd34 100644 --- a/Modules/IGT/IGTToolManagement/mitkNavigationToolStorageSerializer.h +++ b/Modules/IGT/IGTToolManagement/mitkNavigationToolStorageSerializer.h @@ -1,62 +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 NAVIGATIONTOOLSTORAGESERIALIZER_H_INCLUDED #define NAVIGATIONTOOLSTORAGESERIALIZER_H_INCLUDED //itk headers #include //mitk headers #include #include "mitkNavigationToolStorage.h" #include namespace mitk { /**Documentation * \brief This class offers methods to save an object of the class NavigationToolStorage * to the harddisc. * * \ingroup IGT */ class MitkIGT_EXPORT NavigationToolStorageSerializer : public itk::Object { public: mitkClassMacro(NavigationToolStorageSerializer,itk::Object); itkNewMacro(Self); /** * @brief Saves a mitk navigation tool storage to a file. * @return Returns true if the file was saved successfully. False if not. */ bool Serialize(std::string filename, mitk::NavigationToolStorage::Pointer storage); itkGetMacro(ErrorMessage,std::string); protected: NavigationToolStorageSerializer(); ~NavigationToolStorageSerializer(); std::string m_ErrorMessage; std::string convertIntToString(int i); std::string m_tempDirectory; }; } // namespace mitk -#endif //NAVIGATIONTOOLSTORAGESERIALIZER \ No newline at end of file +#endif //NAVIGATIONTOOLSTORAGESERIALIZER diff --git a/Modules/IGT/IGTToolManagement/mitkNavigationToolWriter.h b/Modules/IGT/IGTToolManagement/mitkNavigationToolWriter.h index aeae3378e0..661c7c84fd 100644 --- a/Modules/IGT/IGTToolManagement/mitkNavigationToolWriter.h +++ b/Modules/IGT/IGTToolManagement/mitkNavigationToolWriter.h @@ -1,66 +1,66 @@ /*=================================================================== 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 NAVIGATIONTOOLWRITER_H_INCLUDED #define NAVIGATIONTOOLWRITER_H_INCLUDED //itk headers #include //mitk headers #include #include "mitkNavigationTool.h" #include "mitkNavigationToolStorageSerializer.h" #include namespace mitk { /**Documentation * \brief This class offers methods to write objects of the class navigation tool permanently * to the harddisk. The objects are saved in a special fileformat which can be read * by the class NavigationToolReader to restore the object. * * \ingroup IGT */ class MitkIGT_EXPORT NavigationToolWriter : public itk::Object { friend class mitk::NavigationToolStorageSerializer; public: mitkClassMacro(NavigationToolWriter,itk::Object); itkNewMacro(Self); /** * @brief Writes a navigation tool to a file. * @param FileName The filename (complete, with path, C:\temp\myTool.igtTool for example) * @param Tool The tool which should be written to the file. * @return Returns true if the file was written successfully, false if not. In the second * case you can get the error message by using the method GetErrorMessage(). */ bool DoWrite(std::string FileName,mitk::NavigationTool::Pointer Tool); itkGetMacro(ErrorMessage,std::string); protected: NavigationToolWriter(); ~NavigationToolWriter(); std::string m_ErrorMessage; mitk::DataNode::Pointer ConvertToDataNode(mitk::NavigationTool::Pointer Tool); std::string GetFileWithoutPath(std::string FileWithPath); }; } // namespace mitk -#endif //NAVIGATIONTOOLWRITER \ No newline at end of file +#endif //NAVIGATIONTOOLWRITER diff --git a/Modules/IGT/IGTTrackingDevices/mitkClaronInterfaceStub.h b/Modules/IGT/IGTTrackingDevices/mitkClaronInterfaceStub.h index 7333b98751..7dfb00c090 100644 --- a/Modules/IGT/IGTTrackingDevices/mitkClaronInterfaceStub.h +++ b/Modules/IGT/IGTTrackingDevices/mitkClaronInterfaceStub.h @@ -1,118 +1,118 @@ /*=================================================================== 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 MITKCLARONINTERFACE_H_HEADER_INCLUDED_ #define MITKCLARONINTERFACE_H_HEADER_INCLUDED_ #include #include #include #include #include #include "mitkCommon.h" typedef int mtHandle; namespace mitk { typedef int claronToolHandle; /** Documentation: * \brief An object of this class represents the interface to the MicronTracker. Normally the methods of this class * are calling the c-functions which are provided by the MTC-library. But in this case the MicronTracker is * not installed and so we only have stubs here. These stubs send error messages when you try to call the * methods. * \ingroup IGT */ class MitkIGT_EXPORT ClaronInterface : public itk::Object { public: mitkClassMacro(ClaronInterface, itk::Object); itkNewMacro(Self); /** * \brief Initialization of claroninterface. * \param calibrationDir The directory where the device can find the camera calibration file. * \param toolFilesDir The directory for the tool files. */ void Initialize(std::string calibrationDir, std::string toolFilesDir); /** * \brief This is only a stub, please switch the cmake variable USE_MICRON_TRACKER to on if you want to use the Microntracker. */ bool StartTracking(); /** * \brief This is only a stub, please switch the cmake variable USE_MICRON_TRACKER to on if you want to use the Microntracker. */ bool StopTracking(); /** * \brief This is only a stub, please switch the cmake variable USE_MICRON_TRACKER to on if you want to use the Microntracker. */ std::vector GetAllActiveTools(); /** * \brief This is only a stub, please switch the cmake variable USE_MICRON_TRACKER to on if you want to use the Microntracker. */ std::vector GetTipPosition(claronToolHandle c); /** * \brief This is only a stub, please switch the cmake variable USE_MICRON_TRACKER to on if you want to use the Microntracker. */ std::vector GetTipQuaternions(claronToolHandle c); /** * \brief This is only a stub, please switch the cmake variable USE_MICRON_TRACKER to on if you want to use the Microntracker. */ std::vector GetPosition(claronToolHandle c); /** * \brief This is only a stub, please switch the cmake variable USE_MICRON_TRACKER to on if you want to use the Microntracker. */ std::vector GetQuaternions(claronToolHandle c); /** * \brief This is only a stub, please switch the cmake variable USE_MICRON_TRACKER to on if you want to use the Microntracker. */ const char* GetName(claronToolHandle c); /** * \brief This is only a stub, please switch the cmake variable USE_MICRON_TRACKER to on if you want to use the Microntracker. */ void GrabFrame(); /** * \return Returns wether the MicronTracker is installed (means wether the C-Make-Variable "MITK_USE_MICRON_TRACKER" is set), * so returns false in this case. */ bool IsMicronTrackerInstalled(); protected: /** * \brief standard constructor */ ClaronInterface(); /** * \brief standard destructor */ ~ClaronInterface(); }; }//mitk -#endif \ No newline at end of file +#endif diff --git a/Modules/IGT/IGTTrackingDevices/mitkClaronTrackingDevice.cpp b/Modules/IGT/IGTTrackingDevices/mitkClaronTrackingDevice.cpp index 83a0d3e8cc..1ddf729ed3 100644 --- a/Modules/IGT/IGTTrackingDevices/mitkClaronTrackingDevice.cpp +++ b/Modules/IGT/IGTTrackingDevices/mitkClaronTrackingDevice.cpp @@ -1,327 +1,327 @@ /*=================================================================== 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 "mitkClaronTrackingDevice.h" #include "mitkClaronTool.h" #include "mitkIGTConfig.h" #include "mitkTimeStamp.h" #include #include #include typedef itk::MutexLockHolder MutexLockHolder; mitk::ClaronTrackingDevice::ClaronTrackingDevice(): mitk::TrackingDevice() { //set the type of this tracking device this->m_Data = mitk::DeviceDataMicronTrackerH40; this->m_MultiThreader = itk::MultiThreader::New(); m_ThreadID = 0; m_Device = mitk::ClaronInterface::New(); //############################# standard directories (from cmake) ################################## if (m_Device->IsMicronTrackerInstalled()) { #ifdef MITK_MICRON_TRACKER_TEMP_DIR m_ToolfilesDir = std::string(MITK_MICRON_TRACKER_TEMP_DIR); - m_ToolfilesDir.append("/MT-tools"); + m_ToolfilesDir.append("/MT-tools"); #endif #ifdef MITK_MICRON_TRACKER_CALIBRATION_DIR m_CalibrationDir = std::string(MITK_MICRON_TRACKER_CALIBRATION_DIR); #endif } else { m_ToolfilesDir = "Error - No Microntracker installed"; m_CalibrationDir = "Error - No Microntracker installed"; } //################################################################################################## m_Device->Initialize(m_CalibrationDir, m_ToolfilesDir); } mitk::ClaronTrackingDevice::~ClaronTrackingDevice() { } mitk::TrackingTool* mitk::ClaronTrackingDevice::AddTool( const char* toolName, const char* fileName ) { mitk::ClaronTool::Pointer t = mitk::ClaronTool::New(); if (t->LoadFile(fileName) == false) { return NULL; } t->SetToolName(toolName); if (this->InternalAddTool(t) == false) return NULL; return t.GetPointer(); } bool mitk::ClaronTrackingDevice::InternalAddTool(ClaronTool::Pointer tool) { m_AllTools.push_back(tool); return true; } std::vector mitk::ClaronTrackingDevice::DetectTools() { std::vector returnValue; std::vector allHandles = m_Device->GetAllActiveTools(); for (std::vector::iterator iter = allHandles.begin(); iter != allHandles.end(); ++iter) { ClaronTool::Pointer newTool = ClaronTool::New(); newTool->SetToolName(m_Device->GetName(*iter)); newTool->SetCalibrationName(m_Device->GetName(*iter)); newTool->SetToolHandle(*iter); returnValue.push_back(newTool); } return returnValue; } bool mitk::ClaronTrackingDevice::StartTracking() { //By Alfred: next line because no temp directory is set if MicronTracker is not installed if (!m_Device->IsMicronTrackerInstalled()) return false; //################################################################################## //be sure that the temp-directory is empty at start: delete all files in the tool files directory itksys::SystemTools::RemoveADirectory(m_ToolfilesDir.c_str()); itksys::SystemTools::MakeDirectory(m_ToolfilesDir.c_str()); //copy all toolfiles into the temp directory for (unsigned int i=0; iGetFile().c_str(), m_ToolfilesDir.c_str()); } this->SetState(Tracking); // go to mode Tracking this->m_StopTrackingMutex->Lock(); // update the local copy of m_StopTracking this->m_StopTracking = false; this->m_StopTrackingMutex->Unlock(); //restart the Microntracker, so it will load the new tool files m_Device->StopTracking(); m_Device->Initialize(m_CalibrationDir,m_ToolfilesDir); m_TrackingFinishedMutex->Unlock(); // transfer the execution rights to tracking thread if (m_Device->StartTracking()) { mitk::TimeStamp::GetInstance()->Start(this); m_ThreadID = m_MultiThreader->SpawnThread(this->ThreadStartTracking, this); // start a new thread that executes the TrackTools() method return true; } else { m_ErrorMessage = "Error while trying to start the device!"; return false; } } bool mitk::ClaronTrackingDevice::StopTracking() { Superclass::StopTracking(); //delete all files in the tool files directory itksys::SystemTools::RemoveADirectory(m_ToolfilesDir.c_str()); return true; } unsigned int mitk::ClaronTrackingDevice::GetToolCount() const { return (unsigned int)this->m_AllTools.size(); } mitk::TrackingTool* mitk::ClaronTrackingDevice::GetTool(unsigned int toolNumber) const { if ( toolNumber >= this->GetToolCount()) return NULL; else return this->m_AllTools[toolNumber]; } bool mitk::ClaronTrackingDevice::OpenConnection() { bool returnValue; //Create the temp directory itksys::SystemTools::MakeDirectory(m_ToolfilesDir.c_str()); m_Device->Initialize(m_CalibrationDir,m_ToolfilesDir); returnValue = m_Device->StartTracking(); if (returnValue) { this->SetState(Ready); } else { //reset everything if (m_Device.IsNull()) { m_Device = mitk::ClaronInterface::New(); m_Device->Initialize(m_CalibrationDir, m_ToolfilesDir); } m_Device->StopTracking(); this->SetState(Setup); m_ErrorMessage = "Error while trying to open connection to the MicronTracker."; } return returnValue; } bool mitk::ClaronTrackingDevice::CloseConnection() { bool returnValue = true; if (this->GetState() == Setup) return true; returnValue = m_Device->StopTracking(); //delete the temporary directory itksys::SystemTools::RemoveADirectory(m_ToolfilesDir.c_str()); this->SetState(Setup); return returnValue; } mitk::ClaronInterface* mitk::ClaronTrackingDevice::GetDevice() { return m_Device; } std::vector mitk::ClaronTrackingDevice::GetAllTools() { return this->m_AllTools; } void mitk::ClaronTrackingDevice::TrackTools() { try { /* lock the TrackingFinishedMutex to signal that the execution rights are now transfered to the tracking thread */ MutexLockHolder trackingFinishedLockHolder(*m_TrackingFinishedMutex); // keep lock until end of scope bool localStopTracking; // Because m_StopTracking is used by two threads, access has to be guarded by a mutex. To minimize thread locking, a local copy is used here this->m_StopTrackingMutex->Lock(); // update the local copy of m_StopTracking localStopTracking = this->m_StopTracking; this->m_StopTrackingMutex->Unlock(); while ((this->GetState() == Tracking) && (localStopTracking == false)) { this->GetDevice()->GrabFrame(); std::vector detectedTools = this->DetectTools(); std::vector allTools = this->GetAllTools(); std::vector::iterator itAllTools; for(itAllTools = allTools.begin(); itAllTools != allTools.end(); itAllTools++) { mitk::ClaronTool::Pointer currentTool = *itAllTools; //test if current tool was detected std::vector::iterator itDetectedTools; bool foundTool = false; for(itDetectedTools = detectedTools.begin(); itDetectedTools != detectedTools.end(); itDetectedTools++) { mitk::ClaronTool::Pointer aktuDet = *itDetectedTools; std::string tempString(currentTool->GetCalibrationName()); if (tempString.compare(aktuDet->GetCalibrationName())==0) { currentTool->SetToolHandle(aktuDet->GetToolHandle()); foundTool = true; } } if (!foundTool) { currentTool->SetToolHandle(0); } if (currentTool->GetToolHandle() != 0) { currentTool->SetDataValid(true); //get tip position of tool: std::vector pos_vector = this->GetDevice()->GetTipPosition(currentTool->GetToolHandle()); //write tip position into tool: mitk::Point3D pos; pos[0] = pos_vector[0]; pos[1] = pos_vector[1]; pos[2] = pos_vector[2]; currentTool->SetPosition(pos); //get tip quaternion of tool std::vector quat = this->GetDevice()->GetTipQuaternions(currentTool->GetToolHandle()); //write tip quaternion into tool mitk::Quaternion orientation(quat[1], quat[2], quat[3], quat[0]); currentTool->SetOrientation(orientation); } else { mitk::Point3D origin; origin.Fill(0); currentTool->SetPosition(origin); currentTool->SetOrientation(mitk::Quaternion(0,0,0,0)); currentTool->SetDataValid(false); } } /* Update the local copy of m_StopTracking */ this->m_StopTrackingMutex->Lock(); localStopTracking = m_StopTracking; this->m_StopTrackingMutex->Unlock(); } } catch(...) { this->StopTracking(); this->SetErrorMessage("Error while trying to track tools. Thread stopped."); } } bool mitk::ClaronTrackingDevice::IsMicronTrackerInstalled() { return this->m_Device->IsMicronTrackerInstalled(); } ITK_THREAD_RETURN_TYPE mitk::ClaronTrackingDevice::ThreadStartTracking(void* pInfoStruct) { /* extract this pointer from Thread Info structure */ struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct; if (pInfo == NULL) { return ITK_THREAD_RETURN_VALUE; } if (pInfo->UserData == NULL) { return ITK_THREAD_RETURN_VALUE; } ClaronTrackingDevice *trackingDevice = (ClaronTrackingDevice*)pInfo->UserData; if (trackingDevice != NULL) trackingDevice->TrackTools(); return ITK_THREAD_RETURN_VALUE; -} \ No newline at end of file +} diff --git a/Modules/IGT/Testing/mitkClaronTrackingDeviceTest.cpp b/Modules/IGT/Testing/mitkClaronTrackingDeviceTest.cpp index de6abafcc1..7dc6d8088a 100644 --- a/Modules/IGT/Testing/mitkClaronTrackingDeviceTest.cpp +++ b/Modules/IGT/Testing/mitkClaronTrackingDeviceTest.cpp @@ -1,148 +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 "mitkClaronTrackingDevice.h" #include "mitkClaronTool.h" #include "mitkTestingMacros.h" #include "mitkStandardFileLocations.h" class mitkClaronTrackingDeviceTestClass { public: static bool TestIsMicronTrackerInstalled() { mitk::ClaronTrackingDevice::Pointer myClaronTrackingDevice = mitk::ClaronTrackingDevice::New(); bool returnValue = myClaronTrackingDevice->IsMicronTrackerInstalled(); if (returnValue) {MITK_TEST_OUTPUT(<< "MicronTracker is installed on this system!")} else {MITK_TEST_OUTPUT(<< "MicronTracker is not installed on this system!")} return returnValue; } static void TestInstantiation() { // let's create an object of our class mitk::ClaronTrackingDevice::Pointer testInstance; testInstance = mitk::ClaronTrackingDevice::New(); MITK_TEST_CONDITION_REQUIRED(testInstance.IsNotNull(),"Testing instantiation:") } static void TestToolConfiguration() { std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Modules/IGT/Testing/Data/"); MITK_TEST_CONDITION(toolFileName.empty() == false, "Check if tool calibration file exists"); mitk::ClaronTrackingDevice::Pointer testInstance = mitk::ClaronTrackingDevice::New(); MITK_TEST_CONDITION(testInstance->AddTool("Tool1", toolFileName.c_str()) != NULL, "Testing AddTool() for tool 1"); MITK_TEST_CONDITION(testInstance->GetToolCount() == 1, "Testing adding tool 1"); MITK_TEST_CONDITION(testInstance->AddTool("Tool2", toolFileName.c_str()) != NULL, "Testing AddTool() for tool 2"); MITK_TEST_CONDITION(testInstance->GetToolCount() == 2, "Testing adding tool 2"); MITK_TEST_CONDITION(testInstance->AddTool("Tool3", toolFileName.c_str()) != NULL, "Testing AddTool() for tool 3"); MITK_TEST_CONDITION(testInstance->GetToolCount() == 3, "Testing adding tool 3"); //std::vector myTools = testInstance->GetAllTools(); MITK_TEST_CONDITION(testInstance->GetTool(0)->GetToolName() == std::string("Tool1"), "Testing GetTool() for tool 1"); MITK_TEST_CONDITION(testInstance->GetTool(1)->GetToolName() == std::string("Tool2"), "Testing GetTool() for tool 2"); MITK_TEST_CONDITION(testInstance->GetTool(2)->GetToolName() == std::string("Tool3"), "Testing GetTool() for tool 3"); //Testing 100 tools (maximum by MicronTracker) testInstance = NULL; testInstance = mitk::ClaronTrackingDevice::New(); for (unsigned int i = 0; i < 100; i++) testInstance->AddTool("Tool", toolFileName.c_str()); MITK_TEST_CONDITION(testInstance->GetToolCount() == 100, "Testing adding 100 tools"); bool failed = false; unsigned int max = 100; testInstance = mitk::ClaronTrackingDevice::New(); for (unsigned int i = 0; i < max; i++) testInstance->AddTool("Tool", toolFileName.c_str()); if ((testInstance->GetToolCount() != max)) failed = true; MITK_TEST_CONDITION(!failed, "Testing tool configuration (maximum of 100 tools):"); } static void TestAllMethodsOnSystemsWithoutMicronTracker() { //In this case we won't receive valid data but defined invalid return values. //initialize mitk::ClaronTrackingDevice::Pointer myClaronTrackingDevice = mitk::ClaronTrackingDevice::New(); //OpenConnection MITK_TEST_CONDITION( (!myClaronTrackingDevice->OpenConnection()), "Testing behavior of method OpenConnection() (Errors should occur because MicronTracker is not activated).\n"); std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Testing/Data/"); MITK_TEST_CONDITION(toolFileName.empty() == false, "Check if tool calibration file exists"); //add a few tools myClaronTrackingDevice->AddTool("Tool1", toolFileName.c_str()); myClaronTrackingDevice->AddTool("Tool2", toolFileName.c_str()); myClaronTrackingDevice->AddTool("Tool3", toolFileName.c_str()); //test IsMicronTrackerInstalled MITK_TEST_CONDITION(!myClaronTrackingDevice->IsMicronTrackerInstalled(),"Testing method IsMicronTrackerInstalled().\n") //test getToolCount int toolCount = myClaronTrackingDevice->GetToolCount(); MITK_TEST_CONDITION((toolCount==3), "Testing method GetToolCount().\n"); //test getTool mitk::TrackingTool* myTool = myClaronTrackingDevice->GetTool(2); MITK_TEST_CONDITION((std::string(myTool->GetToolName()) == "Tool3"), "Testing method GetTool().\n"); //StartTracking MITK_TEST_CONDITION( (!myClaronTrackingDevice->StartTracking()), "Testing behavior of method StartTracking().\n"); //StopTracking MITK_TEST_CONDITION( (myClaronTrackingDevice->StopTracking()), "Testing behavior of method StopTracking().\n"); //CloseConnection MITK_TEST_CONDITION( (myClaronTrackingDevice->CloseConnection()), "Testing behavior of method CloseConnection().\n"); } }; /** * This function is testing methods of the class ClaronTrackingDevice which are independent from the hardware. For more tests we would need * the MicronTracker hardware, so only a few simple tests, which can run without the hardware are tested here. More tests can be found in the * class ClaronTrackingDeviceHardwareTests which tests the interaction with the hardware. */ int mitkClaronTrackingDeviceTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("ClaronTrackingDevice"); mitkClaronTrackingDeviceTestClass::TestInstantiation(); mitkClaronTrackingDeviceTestClass::TestToolConfiguration(); /* The following tests don't run under linux environments. This is or could be caused by the fact that the MicronTracker interface * is developed under windows and not tested under linux yet (26.2.2009). So - in my opinion - the best approach is to first test * the MicronTracker code under linux (and make the necessary changes of course) and in parallel write the linux tests or make this * tests runnable under linux. */ #ifdef WIN32 if (mitkClaronTrackingDeviceTestClass::TestIsMicronTrackerInstalled()) { MITK_TEST_OUTPUT(<< "... MicronTracker is installed on your System, so we don't run any further tests. (All tests run on systems without MicronTracker)"); } else { MITK_TEST_OUTPUT(<< ".Test"); mitkClaronTrackingDeviceTestClass::TestAllMethodsOnSystemsWithoutMicronTracker(); } #endif MITK_TEST_END(); -} \ No newline at end of file +} diff --git a/Modules/IGT/Testing/mitkNDITrackingDeviceTest.cpp b/Modules/IGT/Testing/mitkNDITrackingDeviceTest.cpp index 6ae40985dd..e61f98ac58 100644 --- a/Modules/IGT/Testing/mitkNDITrackingDeviceTest.cpp +++ b/Modules/IGT/Testing/mitkNDITrackingDeviceTest.cpp @@ -1,90 +1,90 @@ /*=================================================================== 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 "mitkNDITrackingDevice.h" #include "mitkNDIPassiveTool.h" #include "mitkTestingMacros.h" #include "mitkTrackingTypes.h" #include "mitkTrackingTool.h" #include "mitkStandardFileLocations.h" /** @brief This test makes general tests of the methods of class NDITrackingDevice. The tracking device need not to be connected to the system to run this tests. * A few methods which needs the tracking device to be connected are not tested here. */ int mitkNDITrackingDeviceTest(int /* argc */, char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("NDITrackingDevice"); // let's create an object of our class mitk::NDITrackingDevice::Pointer myNDITrackingDevice = mitk::NDITrackingDevice::New(); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. MITK_TEST_CONDITION_REQUIRED(myNDITrackingDevice.IsNotNull(),"Testing instantiation\n"); //test method GetState MITK_TEST_CONDITION_REQUIRED(myNDITrackingDevice->GetState() == mitk::TrackingDevice::Setup ,"Checking tracking device state == setup.\n"); //test method CloseConnection MITK_TEST_CONDITION( (myNDITrackingDevice->CloseConnection()), "Testing behavior of method CloseConnection()."); //test method StartTracking MITK_TEST_CONDITION( (!myNDITrackingDevice->StartTracking()), "Testing behavior of method StartTracking()."); //test method Beep(unsigned char count) MITK_TEST_CONDITION( (myNDITrackingDevice->Beep(3)== false), "Testing behavior of method Beep(). No Tracking device initialized!"); //test method AddTool( const char* toolName, const char* fileName, TrackingPriority p /*= NDIPassiveTool::Dynamic*/ ) std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("SROMFile.rom", "Modules/IGT/Testing/Data"); const char *name = file.c_str(); MITK_TEST_CONDITION( (myNDITrackingDevice->AddTool("Tool0", name))!=NULL, "Testing AddTool() for tool 0."); //test method GetToolCount() MITK_TEST_CONDITION( (myNDITrackingDevice->GetToolCount())==1, "Testing GetToolCount() for one tool."); //test method GetTool(unsigned int toolNumber) MITK_TEST_CONDITION( (myNDITrackingDevice->GetTool(0))!=NULL, "Testing GetTool() for tool 0."); mitk::TrackingTool::Pointer testtool = myNDITrackingDevice->GetTool(0); //test method UpdateTool(mitk::TrackingTool* tool) MITK_TEST_CONDITION( (!myNDITrackingDevice->UpdateTool(testtool)), "Testing behavior of method UpdateTool().\n"); //test method RemoveTool(mitk::TrackingTool* tool) MITK_TEST_CONDITION( (myNDITrackingDevice->RemoveTool(testtool)), "Testing RemoveTool()for tool 0."); //test method SetOperationMode(OperationMode mode) MITK_TEST_CONDITION( (myNDITrackingDevice->SetOperationMode( mitk::MarkerTracking3D )== true ), "Testing behavior of method SetOperationMode().\n"); //test method GetOperationMode() myNDITrackingDevice->SetOperationMode(mitk::MarkerTracking3D); MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==2),"" ); myNDITrackingDevice->SetOperationMode(mitk::ToolTracking5D); MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==1),"" ); myNDITrackingDevice->SetOperationMode(mitk::HybridTracking); MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==3), "Testing behavior of method GetOperationMode().\n"); //test method GetMarkerPositions(MarkerPointContainerType* markerpositions) mitk::MarkerPointContainerType* markerpositions = new mitk::MarkerPointContainerType(); MITK_TEST_CONDITION( (!myNDITrackingDevice->GetMarkerPositions(markerpositions)), "Testing behavior of method GetMarkerPositions().\n"); delete markerpositions; // always end with this! MITK_TEST_END(); -} \ No newline at end of file +} diff --git a/Modules/IGT/Testing/mitkNavigationDataPlayerTest.cpp b/Modules/IGT/Testing/mitkNavigationDataPlayerTest.cpp index de4bd99540..4af31878ad 100644 --- a/Modules/IGT/Testing/mitkNavigationDataPlayerTest.cpp +++ b/Modules/IGT/Testing/mitkNavigationDataPlayerTest.cpp @@ -1,351 +1,351 @@ /*=================================================================== 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 "mitkNavigationDataPlayer.h" #include "mitkNavigationData.h" #include "mitkTestingMacros.h" #include "mitkStandardFileLocations.h" #include "mitkTimeStamp.h" #include #include #include class mitkNavigationDataPlayerTestClass { public: static void TestInstantiation() { // let's create an object of our class mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New(); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. MITK_TEST_CONDITION_REQUIRED(player.IsNotNull(), "Testing instantiation"); } static void TestSimpleDataPlay() { std::string tmp = ""; // let's create an object of our class mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New(); std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData.xml", "Modules/IGT/Testing/Data"); player->SetFileName( file ); MITK_TEST_CONDITION_REQUIRED( strcmp(player->GetFileName(), file.c_str()) == 0, "Testing SetFileName and GetFileName"); player->SetStream( mitk::NavigationDataPlayer::NormalFile ); player->StartPlaying(); player->Update(); player->StopPlaying(); mitk::NavigationData::Pointer nd = player->GetOutput(); mitk::Point3D pnt; pnt[0] = 1; pnt[1] = 0; pnt[2] = 3; MITK_TEST_CONDITION_REQUIRED( nd->GetPosition() == pnt, "Testing position of replayed NavigaionData" ); player = mitk::NavigationDataPlayer::New(); player->SetFileName( file ); player->SetStream( mitk::NavigationDataPlayer::NormalFile ); std::vector times, refTimes; refTimes.resize(5); refTimes[0] = 3.9; refTimes[1] = 83.6; refTimes[2] = 174.4; refTimes[3] = 275.0; refTimes[4] = 385.39; std::vector points, refPoints; refPoints.resize(5); refPoints[0][0] = 1; refPoints[0][1] = 0; refPoints[0][2] = 3; refPoints[1][0] = 2; refPoints[1][1] = 1; refPoints[1][2] = 4; refPoints[2][0] = 3; refPoints[2][1] = 2; refPoints[2][2] = 5; refPoints[3][0] = 4; refPoints[3][1] = 3; refPoints[3][2] = 6; refPoints[4][0] = 5; refPoints[4][1] = 4; refPoints[4][2] = 7; mitk::TimeStamp::Pointer timer = mitk::TimeStamp::GetInstance(); timer->Initialize(); itk::Object::Pointer obj = itk::Object::New(); mitk::Point3D oldPos; oldPos[0] = 1; oldPos[1] = 0; oldPos[2] = 3; timer->Start( obj ); player->StartPlaying(); while( times.size()<5 ) { player->Update(); pnt = player->GetOutput()->GetPosition(); if ( pnt != oldPos ) { times.push_back( timer->GetElapsed(obj) ); points.push_back(oldPos); oldPos = pnt; } } player->StopPlaying(); // if this test fails, it may be because the dartclient runs on a virtual machine. // Under these circumstances, it may be impossible to achieve a time-accuracy of 10ms for ( int i=0;i<5;i++ ) { if ((times[i]>refTimes[i]-150 && times[i]refTimes[i]-150 && times[i]FindFile("NavigationDataTestData.xml", "Modules/IGT/Testing/Data"); player->SetFileName( file ); MITK_TEST_CONDITION_REQUIRED( strcmp(player->GetFileName(), file.c_str()) == 0, "Testing SetFileName and GetFileName"); player->SetStream( mitk::NavigationDataPlayer::NormalFile ); player->StartPlaying(); player->Update(); MITK_TEST_OUTPUT(<<"Test double call of Pause() method!"); player->Pause(); //test pause method player->Pause(); //call again to see if this causes an error MITK_TEST_OUTPUT(<<"Test double call of Resume() method!"); player->Resume(); //test resume method player->Resume(); //call again to see if this causes an error player->Update(); player->StopPlaying(); mitk::NavigationData::Pointer nd = player->GetOutput(); mitk::Point3D pnt; pnt[0] = 1; pnt[1] = 0; pnt[2] = 3; MITK_TEST_CONDITION_REQUIRED( nd->GetPosition() == pnt, "Testing position of replayed NavigaionData" ); player = mitk::NavigationDataPlayer::New(); player->SetFileName( file ); player->SetStream( mitk::NavigationDataPlayer::NormalFile ); std::vector times, refTimes; refTimes.resize(5); refTimes[0] = 3.9; refTimes[1] = 83.6; refTimes[2] = 174.4; refTimes[3] = 275.0; refTimes[4] = 385.39; std::vector points, refPoints; refPoints.resize(5); refPoints[0][0] = 1; refPoints[0][1] = 0; refPoints[0][2] = 3; refPoints[1][0] = 2; refPoints[1][1] = 1; refPoints[1][2] = 4; refPoints[2][0] = 3; refPoints[2][1] = 2; refPoints[2][2] = 5; refPoints[3][0] = 4; refPoints[3][1] = 3; refPoints[3][2] = 6; refPoints[4][0] = 5; refPoints[4][1] = 4; refPoints[4][2] = 7; mitk::TimeStamp::Pointer timer = mitk::TimeStamp::GetInstance(); timer->Initialize(); itk::Object::Pointer obj = itk::Object::New(); mitk::Point3D oldPos; oldPos[0] = 1; oldPos[1] = 0; oldPos[2] = 3; timer->Start( obj ); player->StartPlaying(); MITK_TEST_CONDITION_REQUIRED(!player->IsAtEnd(), "Testing method IsAtEnd() #0"); while( times.size()<3 ) { player->Update(); pnt = player->GetOutput()->GetPosition(); if ( pnt != oldPos ) { times.push_back( timer->GetElapsed(obj) ); points.push_back(oldPos); oldPos = pnt; } } MITK_TEST_OUTPUT(<<"Test pause method!"); player->Pause(); MITK_TEST_CONDITION_REQUIRED(!player->IsAtEnd(), "Testing method IsAtEnd() #1"); MITK_TEST_OUTPUT(<<"Test resume method!"); player->Resume(); while( times.size()<5 ) { player->Update(); pnt = player->GetOutput()->GetPosition(); if ( pnt != oldPos ) { times.push_back( timer->GetElapsed(obj) ); points.push_back(oldPos); oldPos = pnt; } } player->StopPlaying(); // if this test fails, it may be because the dartclient runs on a virtual machine. // Under these circumstances, it may be impossible to achieve a time-accuracy of 10ms for ( int i=0;i<5;i++ ) { if ((times[i]>refTimes[i]-150 && times[i]refTimes[i]-150 && times[i]IsAtEnd(), "Testing method IsAtEnd() #2"); } static void TestInvalidStream() { MITK_TEST_OUTPUT(<<"#### Testing invalid input data: errors are expected. ####"); //declarate test variables mitk::NavigationDataPlayer::Pointer player; std::string file; //case 0: stream not set player = mitk::NavigationDataPlayer::New(); player->SetStream( mitk::NavigationDataPlayer::ZipFile ); player->StartPlaying(); player->Update(); player->StopPlaying(); MITK_TEST_OUTPUT(<<"#0: Tested stream not set. Application should not crash."); //case 1: non-existing file player = mitk::NavigationDataPlayer::New(); player->SetFileName( "ffdsd" ); player->SetStream( mitk::NavigationDataPlayer::NormalFile ); player->StartPlaying(); player->Update(); player->StopPlaying(); MITK_TEST_OUTPUT(<<"#1: Tested non-existing file. Application should not crash."); //case 2: wrong file format player = mitk::NavigationDataPlayer::New(); file = mitk::StandardFileLocations::GetInstance()->FindFile("SROMFile.rom", "Modules/IGT/Testing/Data"); player->SetFileName( file ); player->SetStream( mitk::NavigationDataPlayer::NormalFile ); player->StartPlaying(); player->Update(); player->StopPlaying(); MITK_TEST_OUTPUT(<<"#2: Tested wrong file format. Application should not crash."); //case 3: wrong file version player = mitk::NavigationDataPlayer::New(); file = mitk::StandardFileLocations::GetInstance()->FindFile("InvalidVersionNavigationDataTestData.xml", "Modules/IGT/Testing/Data"); player->SetFileName( file ); player->SetStream( mitk::NavigationDataPlayer::NormalFile ); player->StartPlaying(); player->Update(); player->StopPlaying(); MITK_TEST_OUTPUT(<<"#3: Tested wrong file version. Application should not crash."); //case 4: wrong file player = mitk::NavigationDataPlayer::New(); player->SetFileName( "cs:\fsd/$%§²³ffdsd" ); player->SetStream( mitk::NavigationDataPlayer::NormalFile ); player->StartPlaying(); player->Update(); player->StopPlaying(); MITK_TEST_OUTPUT(<<"#4: Tested wrong file. Application should not crash."); //case 5: null stream player = mitk::NavigationDataPlayer::New(); player->SetStream( NULL ); player->StartPlaying(); player->Update(); player->StopPlaying(); MITK_TEST_OUTPUT(<<"#5: Tested null stream. Application should not crash."); //case 6: empty stream player = mitk::NavigationDataPlayer::New(); std::ifstream* myEmptyStream = new std::ifstream(""); player->SetStream( myEmptyStream ); player->StartPlaying(); player->Update(); player->StopPlaying(); MITK_TEST_OUTPUT(<<"#6: Tested empty stream. Application should not crash."); //case 7: wrong stream player = mitk::NavigationDataPlayer::New(); file = mitk::StandardFileLocations::GetInstance()->FindFile("SROMFile.rom", "Modules/IGT/Testing/Data"); std::ifstream* myWrongStream = new std::ifstream(file.c_str()); player->SetStream( myWrongStream ); player->StartPlaying(); player->Update(); player->StopPlaying(); MITK_TEST_OUTPUT(<<"#7: Tested wrong stream. Application should not crash."); //case 8: invalid player = mitk::NavigationDataPlayer::New(); file = mitk::StandardFileLocations::GetInstance()->FindFile("InvalidDataNavigationDataTestData.xml", "Modules/IGT/Testing/Data"); player->SetFileName( file ); player->SetStream( mitk::NavigationDataPlayer::NormalFile ); player->StartPlaying(); player->Update(); player->StopPlaying(); MITK_TEST_OUTPUT(<<"#8: Tested invalid file version. Application should not crash."); - //clean up - delete myEmptyStream; - delete myWrongStream; + //clean up + delete myEmptyStream; + delete myWrongStream; } }; /**Documentation * test for the class "NavigationDataPlayer". */ int mitkNavigationDataPlayerTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("NavigationDataPlayer"); std::string tmp = ""; mitkNavigationDataPlayerTestClass::TestInstantiation(); mitkNavigationDataPlayerTestClass::TestSimpleDataPlay(); mitkNavigationDataPlayerTestClass::TestPauseAndResume(); mitkNavigationDataPlayerTestClass::TestInvalidStream(); // always end with this! MITK_TEST_END(); -} \ No newline at end of file +} diff --git a/Modules/IGT/Testing/mitkNavigationDataRecorderTest.cpp b/Modules/IGT/Testing/mitkNavigationDataRecorderTest.cpp index f2e46b2de9..c8e84f216b 100644 --- a/Modules/IGT/Testing/mitkNavigationDataRecorderTest.cpp +++ b/Modules/IGT/Testing/mitkNavigationDataRecorderTest.cpp @@ -1,313 +1,313 @@ /*=================================================================== 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 class mitkNavigationDataRecorderTestClass { public: static void TestInstantiation() { // let's create an object of our class mitk::NavigationDataRecorder::Pointer recorder = mitk::NavigationDataRecorder::New(); MITK_TEST_CONDITION( recorder.IsNotNull(), "Testing instatiation of NavigationDataRecorder"); } static void TestRecordingWithGivenStream() { std::string tmp = ""; std::ostringstream* stream = new std::ostringstream( std::ostringstream::trunc ); stream->setf( std::ios::fixed, std::ios::floatfield ); // let's create an object of our class mitk::NavigationDataRecorder::Pointer recorder = mitk::NavigationDataRecorder::New(); MITK_TEST_CONDITION(recorder->GetInputs().size() == 0, "testing initial number of inputs"); MITK_TEST_CONDITION(recorder->GetOutputs().size() == 0, "testing initial number of outputs"); mitk::NavigationData::Pointer naviData = mitk::NavigationData::New(); recorder->AddNavigationData( naviData ); //recorder->SetFileName("e:/test"); //recorder->SetRecordingMode( mitk::NavigationDataRecorder::NormalFile ); recorder->StartRecording( stream ); for ( unsigned int i=0; i<5; i++ ) { mitk::Point3D pnt; pnt[0] = i + 1; pnt[1] = i + 1/2; pnt[2] = i +1*3; naviData->SetPosition(pnt); //naviData->Modified(); recorder->Update(); //Sleep(80 + i*10); } recorder->StopRecording(); std::string str = stream->str(); int pos = str.find( "ToolCount=" ); std::string sub = stream->str().substr(pos+11, 1); MITK_TEST_CONDITION( sub.compare("1") == 0, "check if number of inputs is correct by stringstream"); pos = str.find( "X=" ); sub = stream->str().substr(pos+3, 1); MITK_TEST_CONDITION( sub.compare("1") == 0, "check if the X coordinate is correct"); pos = str.find( "Y=" ); sub = stream->str().substr(pos+3, 1); MITK_TEST_CONDITION( sub.compare("0") == 0, "check if the Y coordinate is correct"); pos = str.find( "Z=" ); sub = stream->str().substr(pos+3, 1); MITK_TEST_CONDITION( sub.compare("3") == 0, "check if the Z coordinate is correct"); recorder->SetFileName("blablabla"); const char* string = recorder->GetFileName(); MITK_TEST_CONDITION( strcmp(string, "blablabla") == 0, "check if set- and getName-methods work"); } static void TestRecordingOnHarddiscXML() { mitk::NavigationDataRecorder::Pointer recorder = mitk::NavigationDataRecorder::New(); //create filename std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+"Recordertest.xml"; recorder->SetFileName(filename.c_str()); mitk::NavigationData::Pointer naviData = mitk::NavigationData::New(); recorder->AddNavigationData( naviData ); recorder->StartRecording(); for ( unsigned int i=0; i<5; i++ ) { mitk::Point3D pnt; pnt[0] = i + 1; pnt[1] = i + 1/2; pnt[2] = i +1*3; naviData->SetPosition(pnt); recorder->Update(); } recorder->StopRecording(); std::string prooffilename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+"Recordertest-0.xml"; Poco::File myFile(prooffilename); MITK_TEST_CONDITION(myFile.exists(),"Testing XML recording on harddisc (does file exist?)."); } static void TestRecordingOnHarddiscXMLZIP() { mitk::NavigationDataRecorder::Pointer recorder = mitk::NavigationDataRecorder::New(); //create filename std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+"Recordertestzip.xml"; recorder->SetFileName(filename.c_str()); recorder->SetRecordingMode(mitk::NavigationDataRecorder::ZipFile); MITK_TEST_CONDITION(recorder->GetRecordingMode()==mitk::NavigationDataRecorder::ZipFile,"Testing setter of recording mode."); /* Zip file not supported yet, activate later mitk::NavigationData::Pointer naviData = mitk::NavigationData::New(); recorder->AddNavigationData( naviData ); recorder->StartRecording(); for ( unsigned int i=0; i<5; i++ ) { mitk::Point3D pnt; pnt[0] = i + 1; pnt[1] = i + 1/2; pnt[2] = i +1*3; naviData->SetPosition(pnt); recorder->Update(); } recorder->StopRecording(); std::string prooffilename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+"Recordertest-0.xml"; Poco::File myFile(prooffilename); MITK_TEST_CONDITION(myFile.exists(),"Testing XML Zip recording on harddisc (does file exist?)."); */ } static void TestRecordingOnHarddiscCSV() { mitk::NavigationDataRecorder::Pointer recorder = mitk::NavigationDataRecorder::New(); //create filename std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+"Recordertest.xml"; recorder->SetFileName(filename.c_str()); recorder->SetOutputFormat(mitk::NavigationDataRecorder::csv); mitk::NavigationData::Pointer naviData = mitk::NavigationData::New(); recorder->AddNavigationData( naviData ); recorder->StartRecording(); for ( unsigned int i=0; i<5; i++ ) { mitk::Point3D pnt; pnt[0] = i + 1; pnt[1] = i + 1/2; pnt[2] = i +1*3; naviData->SetPosition(pnt); recorder->Update(); } recorder->StopRecording(); std::string prooffilename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+"Recordertest-0.csv"; Poco::File myFile(prooffilename); MITK_TEST_CONDITION(myFile.exists(),"Testing CSV recording on harddisc (does file exist?)."); } static void TestLoadingRecordedXMLFile() { mitk::NavigationDataPlayer::Pointer myPlayer = mitk::NavigationDataPlayer::New(); std::string filenameXML = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+"Recordertest-0.xml"; myPlayer->SetFileName(filenameXML.c_str()); myPlayer->StartPlaying(); //only testing first position at the moment myPlayer->Update(); mitk::NavigationData::Pointer thisData = myPlayer->GetOutput(); mitk::Point3D reference_pnt; reference_pnt[0] = 1; reference_pnt[1] = 1/2; reference_pnt[2] = 1*3; myPlayer->StopPlaying(); MITK_TEST_CONDITION((thisData->GetPosition() == reference_pnt),"Testing load data from xml file."); } static void TestRecordingInvalidData() { std::string tmp = ""; std::ostringstream* stream = new std::ostringstream( std::ostringstream::trunc ); stream->setf( std::ios::fixed, std::ios::floatfield ); // let's create an object of our class mitk::NavigationDataRecorder::Pointer recorder = mitk::NavigationDataRecorder::New(); mitk::NavigationData::Pointer naviData = mitk::NavigationData::New(); recorder->AddNavigationData( naviData ); naviData->SetDataValid(false); //recorder->SetFileName("e:/test"); //recorder->SetRecordingMode( mitk::NavigationDataRecorder::NormalFile ); recorder->StartRecording( stream ); for ( unsigned int i=0; i<5; i++ ) { mitk::Point3D pnt; pnt[0] = i + 1; pnt[1] = i + 1/2; pnt[2] = i +1*3; naviData->SetPosition(pnt); //naviData->Modified(); recorder->Update(); //Sleep(80 + i*10); } recorder->StopRecording(); bool record_success = true; std::string str = stream->str(); int pos = str.find( "ToolCount=" ); std::string sub = stream->str().substr(pos+11, 1); if (sub.compare("1") != 0) {record_success = false;} pos = str.find( "X=" ); sub = stream->str().substr(pos+3, 1); if (sub.compare("1") != 0) {record_success = false;} pos = str.find( "Y=" ); sub = stream->str().substr(pos+3, 1); if (sub.compare("0") != 0) {record_success = false;} pos = str.find( "Z=" ); sub = stream->str().substr(pos+3, 1); if (sub.compare("3") != 0) {record_success = false;} MITK_TEST_CONDITION(record_success,"Testing recording of invalid data."); } static void CleanUp() { std::string filenameXML = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+"Recordertest-0.xml"; std::string filenameCSV = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+"Recordertest-0.csv"; Poco::File myFileXML(filenameXML); if (myFileXML.exists()) {myFileXML.remove();} Poco::File myFileCSV(filenameCSV); if (myFileCSV.exists()) {myFileCSV.remove();} } }; /**Documentation * test for the class "NavigationDataRecorder". */ int mitkNavigationDataRecorderTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("NavigationDataRecorder"); mitkNavigationDataRecorderTestClass::TestInstantiation(); mitkNavigationDataRecorderTestClass::TestRecordingWithGivenStream(); mitkNavigationDataRecorderTestClass::TestRecordingOnHarddiscXML(); mitkNavigationDataRecorderTestClass::TestRecordingOnHarddiscXMLZIP(); mitkNavigationDataRecorderTestClass::TestRecordingOnHarddiscCSV(); mitkNavigationDataRecorderTestClass::TestRecordingInvalidData(); //Test fails under linux, perhaps reading permission problems, deactivated it temporary //mitkNavigationDataRecorderTestClass::TestLoadingRecordedXMLFile(); mitkNavigationDataRecorderTestClass::CleanUp(); // always end with this! MITK_TEST_END(); -} \ No newline at end of file +} diff --git a/Modules/IGT/Testing/mitkTrackingDeviceSourceConfiguratorTest.cpp b/Modules/IGT/Testing/mitkTrackingDeviceSourceConfiguratorTest.cpp index 2879791a5e..41d18296d8 100644 --- a/Modules/IGT/Testing/mitkTrackingDeviceSourceConfiguratorTest.cpp +++ b/Modules/IGT/Testing/mitkTrackingDeviceSourceConfiguratorTest.cpp @@ -1,233 +1,233 @@ /*=================================================================== 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 "mitkTrackingDeviceSourceConfigurator.h" #include #include #include #include #include class mitkTrackingDeviceSourceConfiguratorTestClass { public: static void TestInstantiation() { // let's create an object of our class mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer emptyStorage = mitk::NavigationToolStorage::New(); mitk::TrackingDevice::Pointer dummyDevice = dynamic_cast(mitk::ClaronTrackingDevice::New().GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(emptyStorage,dummyDevice); MITK_TEST_CONDITION_REQUIRED(testInstance.IsNotNull(),"Testing instantiation:"); } static void TestInvalidClaronTrackingDevice() { MITK_TEST_OUTPUT(<<"Testing simple claron tracking device with 2 invalid tools"); mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New(); //create invalid tool 1 mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New(); firstTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer firstNode = mitk::DataNode::New(); firstNode->SetName("Tool1"); firstTool->SetDataNode(firstNode); claronStorage->AddTool(firstTool); //create invalid tool 2 mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New(); secondTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer secondNode = mitk::DataNode::New(); secondNode->SetName("Tool2"); secondTool->SetDataNode(secondNode); claronStorage->AddTool(secondTool); mitk::TrackingDevice::Pointer testDevice = dynamic_cast(mitk::ClaronTrackingDevice::New().GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice); mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource(); MITK_TEST_CONDITION_REQUIRED(testSource.IsNull(),"..testing return value"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetErrorMessage().size()>1,"..testing if there is an error message"); MITK_TEST_OUTPUT(<<"Testing simple claron tracking device with another 2 invalid tools"); secondTool->SetTrackingDeviceType(mitk::NDIAurora); claronStorage = mitk::NavigationToolStorage::New(); claronStorage->AddTool(secondTool); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice); MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),"..testing if factory class detects the invalid data"); testSource = testInstance->CreateTrackingDeviceSource(); MITK_TEST_CONDITION_REQUIRED(testSource.IsNull(),"..testing return value"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetErrorMessage().size()>1,"..testing if there is an error message"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetUpdatedNavigationToolStorage()->GetToolCount()==1,"..testing if navigation tool storage is still there"); MITK_TEST_OUTPUT(<<"Testing other invalid test cases"); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,NULL); MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),"..(1) testing if factory class detects the invalid data"); testInstance = mitk::TrackingDeviceSourceConfigurator::New(NULL,testDevice); MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),"..(2) testing if factory class detects the invalid data"); } static void TestValidClaronTrackingDevice() { MITK_TEST_OUTPUT(<<"Testing simple claron tracking device with 2 valid tools"); std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Modules/IGT/Testing/Data"); MITK_TEST_CONDITION(toolFileName.empty() == false, "Check if tool calibration of claron tool file exists"); mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New(); //create valid tool 1 mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New(); firstTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer firstNode = mitk::DataNode::New(); firstNode->SetName("Tool1"); firstTool->SetDataNode(firstNode); firstTool->SetCalibrationFile(toolFileName); firstTool->SetIdentifier("Tool#1"); claronStorage->AddTool(firstTool); //create valid tool 2 mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New(); secondTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer secondNode = mitk::DataNode::New(); secondNode->SetName("Tool2"); secondTool->SetDataNode(secondNode); secondTool->SetCalibrationFile(toolFileName); secondTool->SetIdentifier("Tool#2"); claronStorage->AddTool(secondTool); mitk::TrackingDevice::Pointer testDevice = dynamic_cast(mitk::ClaronTrackingDevice::New().GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice); mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource(); MITK_TEST_CONDITION_REQUIRED(testSource->GetNumberOfOutputs()==2,"testing number of outputs"); MITK_TEST_CONDITION_REQUIRED(testSource->GetTrackingDevice()->GetToolCount()==2,"testing tracking device"); } static void TestNDIAuroraTrackingDevice() { } static void TestNDIPolarisTrackingDevice() { MITK_TEST_OUTPUT(<<"Testing simple NDI Polaris tracking device with 1 valid tool"); std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("SROMFile.rom", "Modules/IGT/Testing/Data"); MITK_TEST_CONDITION(toolFileName.empty() == false, "..check if tool calibration of claron tool file exists"); mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer polarisStorage = mitk::NavigationToolStorage::New(); //create valid tool 1 mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New(); firstTool->SetTrackingDeviceType(mitk::NDIPolaris); mitk::DataNode::Pointer firstNode = mitk::DataNode::New(); firstNode->SetName("Tool1"); firstTool->SetDataNode(firstNode); firstTool->SetCalibrationFile(toolFileName); firstTool->SetIdentifier("Tool#1"); polarisStorage->AddTool(firstTool); mitk::NDITrackingDevice::Pointer ndiDevice = mitk::NDITrackingDevice::New(); ndiDevice->SetType(mitk::NDIPolaris); mitk::TrackingDevice::Pointer testDevice = dynamic_cast(ndiDevice.GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(polarisStorage,testDevice); mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource(); MITK_TEST_CONDITION_REQUIRED(testSource->GetNumberOfOutputs()==1,"..testing number of outputs"); MITK_TEST_CONDITION_REQUIRED(testSource->GetTrackingDevice()->GetToolCount()==1,"..testing tracking device"); } static void TestAdditionalMethods() { MITK_TEST_OUTPUT(<<"Testing additional methods of TrackingDeviceSourceCOnfigurator"); MITK_TEST_OUTPUT(<<"..using claron tracking device for testing"); std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Modules/IGT/Testing/Data"); MITK_TEST_CONDITION(toolFileName.empty() == false, "..check if tool calibration of claron tool file exists"); mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New(); //create valid tool 1 mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New(); firstTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer firstNode = mitk::DataNode::New(); firstNode->SetName("Tool1"); firstTool->SetDataNode(firstNode); firstTool->SetCalibrationFile(toolFileName); firstTool->SetIdentifier("Tool#1"); claronStorage->AddTool(firstTool); //create valid tool 2 mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New(); secondTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer secondNode = mitk::DataNode::New(); secondNode->SetName("Tool2"); secondTool->SetDataNode(secondNode); secondTool->SetCalibrationFile(toolFileName); secondTool->SetIdentifier("Tool#2"); claronStorage->AddTool(secondTool); mitk::TrackingDevice::Pointer testDevice = dynamic_cast(mitk::ClaronTrackingDevice::New().GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice); mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource(); //numbers must be the same in case of MicronTracker MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolNumberInToolStorage(0)==0,"..testing method GetToolNumberInToolStorage()"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolIdentifierInToolStorage(0)=="Tool#1","..testing method GetToolIdentifierInToolStorage()"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolNumbersInToolStorage().at(0)==0,"..testing method GetToolNumbersInToolStorage()"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolIdentifiersInToolStorage().at(0)=="Tool#1","..testing method GetToolIdentifiersInToolStorage()"); } }; int mitkTrackingDeviceSourceConfiguratorTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("TrackingDeviceConfigurator"); mitkTrackingDeviceSourceConfiguratorTestClass::TestInstantiation(); mitkTrackingDeviceSourceConfiguratorTestClass::TestInvalidClaronTrackingDevice(); mitkTrackingDeviceSourceConfiguratorTestClass::TestValidClaronTrackingDevice(); mitkTrackingDeviceSourceConfiguratorTestClass::TestAdditionalMethods(); MITK_TEST_END(); -} \ No newline at end of file +} diff --git a/Modules/IGTUI/Qmitk/QmitkIGTConnectionWidget.h b/Modules/IGTUI/Qmitk/QmitkIGTConnectionWidget.h index 3b7a9664b3..0dd6f3b046 100644 --- a/Modules/IGTUI/Qmitk/QmitkIGTConnectionWidget.h +++ b/Modules/IGTUI/Qmitk/QmitkIGTConnectionWidget.h @@ -1,113 +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 QmitkIGTConnectionWidget_H #define QmitkIGTConnectionWidget_H #include #include "MitkIGTUIExports.h" #include "ui_QmitkIGTConnectionWidgetControls.h" #include "mitkDataStorage.h" #include "mitkNavigationToolStorage.h" #include "mitkTrackingDevice.h" #include "mitkTrackingDeviceSource.h" //itk headers /** Documentation: * \brief Simple and fast access to a pre-configured TrackingDeviceSource. * * This widget creates a fully configured, connected and started TrackingDeviceSource. * Clicking "Connect" requires to specify a NavigationToolStorage that holds all tools to be used * in the application. Corresponding surfaces are added to the DataStorage that has to be set for * the widget. * * Inputs: DataStorage * Outputs: TrackingDeviceSource, NavigationToolStorage * Signals: TrackingDeviceConnected, TrackingDeviceDisconnected * * \ingroup IGTUI */ class MitkIGTUI_EXPORT QmitkIGTConnectionWidget : public QWidget { Q_OBJECT public: static const std::string VIEW_ID; QmitkIGTConnectionWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); ~QmitkIGTConnectionWidget(); /* @return Returns the preconfigured and connected TrackingDeviceSource ready to use in an IGT pipeline. */ mitk::TrackingDeviceSource::Pointer GetTrackingDeviceSource(); /*! \brief Get the NavigationToolStorage holding all tools with corresponding surface objects */ mitk::NavigationToolStorage::Pointer GetNavigationToolStorage(); /*! \brief set DataStorage that is used to put the navigation tools */ void SetDataStorage(mitk::DataStorage::Pointer dataStorage); signals: /*! \brief signal emitted when TrackingDevice was successfully connected */ void TrackingDeviceConnected(); /*! \brief signal emitted when TrackingDevice was successfully disconnected */ void TrackingDeviceDisconnected(); protected slots: /*! \brief Asks the user to specify a tool file and finally connects the TrackingDeviceSource */ void OnConnect(); protected: /// \brief Creation of the connections virtual void CreateConnections(); virtual void CreateQtPartControl(QWidget *parent); /*! \brief Load NavigationToolStorage from given filename and set according member \param qFilename file location of the NavigationToolStorage \return success of load operation (true if load successful, false otherwise) m_ErrorMessage holds the problem description */ bool LoadToolfile(QString qFilename); /*! \brief Remove the tool nodes currently associated to the tools hold in the NavigationToolStorage from the DataStorage */ void RemoveToolNodes(); Ui::QmitkIGTConnectionWidgetControls* m_Controls; mitk::DataStorage::Pointer m_DataStorage; ///< data storage to put navigation tools mitk::TrackingDevice::Pointer m_TrackingDevice; ///< tracking device currently connected mitk::TrackingDeviceSource::Pointer m_TrackingDeviceSource; ///< holds the preconfigured source of the IGT pipeline which is provided by this widget for further processing mitk::NavigationToolStorage::Pointer m_NavigationToolStorage; ///< holds all navigation tools currently loaded std::string m_ErrorMessage; ///< current problem description }; -#endif \ No newline at end of file +#endif diff --git a/Modules/IGTUI/Qmitk/QmitkIGTLoggerWidget.h b/Modules/IGTUI/Qmitk/QmitkIGTLoggerWidget.h index c08e269867..fe160164da 100644 --- a/Modules/IGTUI/Qmitk/QmitkIGTLoggerWidget.h +++ b/Modules/IGTUI/Qmitk/QmitkIGTLoggerWidget.h @@ -1,90 +1,90 @@ /*=================================================================== 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 QmitkIGTLoggerWidget_H #define QmitkIGTLoggerWidget_H //QT headers #include //mitk headers #include "MitkIGTUIExports.h" #include "mitkNavigationTool.h" #include #include "mitkNavigationDataRecorder.h" //ui header #include "ui_QmitkIGTLoggerWidgetControls.h" /** Documentation: * \brief GUI to access the IGT recorder. * User can specify the file name where the output shall be stored and * how long the recording shall be performed. * * \ingroup IGTUI */ class MitkIGTUI_EXPORT QmitkIGTLoggerWidget : public QWidget { Q_OBJECT public: static const std::string VIEW_ID; QmitkIGTLoggerWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); ~QmitkIGTLoggerWidget(); void SetDataStorage(mitk::DataStorage* dataStorage); void SetRecorder(mitk::NavigationDataRecorder::Pointer recorder); signals: void SignalRecordingStarted(); void SignalRecordingStopped(); protected slots: void OnChangePressed(); void OnStartRecording(bool recording); void OnRecording(); void UpdateRecordingTime(); void StopRecording(); void UpdateOutputFileName(); protected: /// \brief Creation of the connections virtual void CreateConnections(); virtual void CreateQtPartControl(QWidget *parent); void SetDefaultRecordingSettings(); void SetOutputFileName(); Ui::QmitkIGTLoggerWidgetControls* m_Controls; /** @brief holds the DataStorage */ mitk::DataStorage::Pointer m_DataStorage; mitk::NavigationDataRecorder::Pointer m_Recorder; ///< records NDs to a XML file QString m_CmpFilename; QString m_Dir; QTimer* m_RecordingTimer; QString m_MilliSeconds; QString m_Samples; bool m_RecordingActivated; }; -#endif \ No newline at end of file +#endif diff --git a/Modules/IGTUI/Qmitk/QmitkIGTPlayerWidget.cpp b/Modules/IGTUI/Qmitk/QmitkIGTPlayerWidget.cpp index f17c267742..00eb05729e 100644 --- a/Modules/IGTUI/Qmitk/QmitkIGTPlayerWidget.cpp +++ b/Modules/IGTUI/Qmitk/QmitkIGTPlayerWidget.cpp @@ -1,548 +1,548 @@ /*=================================================================== 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 "QmitkIGTPlayerWidget.h" //mitk headers #include "mitkTrackingTypes.h" #include #include #include #include #include #include #include //qt headers #include #include #include QmitkIGTPlayerWidget::QmitkIGTPlayerWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) ,m_RealTimePlayer(NULL) ,m_SequentialPlayer(NULL) ,m_StartTime(-1.0) ,m_CurrentSequentialPointNumber(0) { m_Controls = NULL; CreateQtPartControl(this); CreateConnections(); m_Controls->samplePositionHorizontalSlider->setVisible(false); this->ResetLCDNumbers(); // reset lcd numbers at start } QmitkIGTPlayerWidget::~QmitkIGTPlayerWidget() { m_PlayingTimer->stop(); m_RealTimePlayer = NULL; m_PlayingTimer = NULL; } void QmitkIGTPlayerWidget::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkIGTPlayerWidgetControls; m_Controls->setupUi(parent); m_PlayingTimer = new QTimer(this); // initialize update timer } } void QmitkIGTPlayerWidget::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->selectPushButton), SIGNAL(clicked()), this, SLOT(OnSelectPressed()) ); // open file dialog connect( (QObject*)(m_Controls->playPushButton), SIGNAL(clicked(bool)), this, SLOT(OnPlayButtonClicked(bool)) ); // play button connect( (QObject*)(m_PlayingTimer), SIGNAL(timeout()), this, SLOT(OnPlaying()) ); // update timer connect( (QObject*) (m_Controls->beginPushButton), SIGNAL(clicked()), this, SLOT(OnGoToBegin()) ); // reset player and go to begin connect( (QObject*) (m_Controls->stopPushButton), SIGNAL(clicked()), this, SLOT(OnGoToEnd()) ); // reset player // pass this widgets protected combobox signal to public signal connect( (QObject*) (m_Controls->trajectorySelectComboBox), SIGNAL(currentIndexChanged(int)), this, SIGNAL(SignalCurrentTrajectoryChanged(int)) ); // pass this widgets protected checkbox signal to public signal connect( m_Controls->splineModeCheckBox, SIGNAL(toggled(bool)), this, SIGNAL(SignalSplineModeToggled(bool)) ); connect( m_Controls->sequencialModeCheckBox, SIGNAL(toggled(bool)), this, SLOT(OnSequencialModeToggled(bool)) ); connect( m_Controls->samplePositionHorizontalSlider, SIGNAL(sliderPressed()), this, SLOT(OnSliderPressed()) ); connect( m_Controls->samplePositionHorizontalSlider, SIGNAL(sliderReleased()), this, SLOT(OnSliderReleased()) ); } } bool QmitkIGTPlayerWidget::IsTrajectoryInSplineMode() { return m_Controls->splineModeCheckBox->isChecked(); } bool QmitkIGTPlayerWidget::CheckInputFileValid() { QFile file(m_CmpFilename); // check if file exists if(!file.exists()) { QMessageBox::warning(NULL, "IGTPlayer: Error", "No valid input file was loaded. Please load input file first!"); return false; } return true; } unsigned int QmitkIGTPlayerWidget::GetNumberOfTools() { unsigned int result = 0; if(this->GetCurrentPlaybackMode() == RealTimeMode) { if(m_RealTimePlayer.IsNotNull()) result = m_RealTimePlayer->GetNumberOfOutputs(); } else if(this->GetCurrentPlaybackMode() == SequentialMode) { if(m_SequentialPlayer.IsNotNull()) result = m_SequentialPlayer->GetNumberOfOutputs(); } // at the moment this works only if player is initialized return result; } void QmitkIGTPlayerWidget::SetUpdateRate(unsigned int msecs) { m_PlayingTimer->setInterval((int) msecs); // set update timer update rate } void QmitkIGTPlayerWidget::OnPlayButtonClicked(bool checked) { if(CheckInputFileValid()) // no playing possible without valid input file { PlaybackMode currentMode = this->GetCurrentPlaybackMode(); bool isRealTimeMode = currentMode == RealTimeMode; bool isSequentialMode = currentMode == SequentialMode; if(checked) // play { if( (isRealTimeMode && m_RealTimePlayer.IsNull()) || (isSequentialMode && m_SequentialPlayer.IsNull())) // start play { if(isRealTimeMode) { m_RealTimePlayer = mitk::NavigationDataPlayer::New(); m_RealTimePlayer->SetFileName(m_CmpFilename.toStdString()); m_RealTimePlayer->StartPlaying(); } else if(isSequentialMode) { m_SequentialPlayer = mitk::NavigationDataSequentialPlayer::New(); m_SequentialPlayer->SetFileName(m_CmpFilename.toStdString()); m_Controls->samplePositionHorizontalSlider->setMinimum(0); m_Controls->samplePositionHorizontalSlider->setMaximum(m_SequentialPlayer->GetNumberOfSnapshots()); m_Controls->samplePositionHorizontalSlider->setEnabled(true); } m_PlayingTimer->start(100); emit SignalPlayingStarted(); } else // resume play { if(isRealTimeMode) m_RealTimePlayer->Resume(); m_PlayingTimer->start(100); emit SignalPlayingResumed(); } } else // pause { if(isRealTimeMode) m_RealTimePlayer->Pause(); m_PlayingTimer->stop(); emit SignalPlayingPaused(); } } else m_Controls->playPushButton->setChecked(false); // uncheck play button if file unvalid } QmitkIGTPlayerWidget::PlaybackMode QmitkIGTPlayerWidget::GetCurrentPlaybackMode() { if(m_Controls->sequencialModeCheckBox->isChecked()) return SequentialMode; else return RealTimeMode; } QTimer* QmitkIGTPlayerWidget::GetPlayingTimer() { return m_PlayingTimer; } void QmitkIGTPlayerWidget::OnStopPlaying() { this->StopPlaying(); } void QmitkIGTPlayerWidget::StopPlaying() { m_PlayingTimer->stop(); emit SignalPlayingStopped(); if(m_RealTimePlayer.IsNotNull()) m_RealTimePlayer->StopPlaying(); m_RealTimePlayer = NULL; m_SequentialPlayer = NULL; m_StartTime = -1; // set starttime back m_CurrentSequentialPointNumber = 0; m_Controls->samplePositionHorizontalSlider->setSliderPosition(m_CurrentSequentialPointNumber); m_Controls->sampleLCDNumber->display(static_cast(m_CurrentSequentialPointNumber)); this->ResetLCDNumbers(); m_Controls->playPushButton->setChecked(false); // set play button unchecked } void QmitkIGTPlayerWidget::OnPlaying() { PlaybackMode currentMode = this->GetCurrentPlaybackMode(); bool isRealTimeMode = currentMode == RealTimeMode; bool isSequentialMode = currentMode == SequentialMode; if(isRealTimeMode && m_RealTimePlayer.IsNull()) return; else if(isSequentialMode && m_SequentialPlayer.IsNull()) return; if(isRealTimeMode && m_StartTime < 0) m_StartTime = m_RealTimePlayer->GetOutput()->GetTimeStamp(); // get playback start time if(isRealTimeMode && !m_RealTimePlayer->IsAtEnd()) { m_RealTimePlayer->Update(); // update player int msc = (int) (m_RealTimePlayer->GetOutput()->GetTimeStamp() - m_StartTime); // calculation for playing time display int ms = msc % 1000; msc = (msc - ms) / 1000; int s = msc % 60; int min = (msc-s) / 60; // set lcd numbers m_Controls->msecLCDNumber->display(ms); m_Controls->secLCDNumber->display(s); m_Controls->minLCDNumber->display(min); emit SignalPlayerUpdated(); // player successfully updated } else if(isSequentialMode && (m_CurrentSequentialPointNumber < m_SequentialPlayer->GetNumberOfSnapshots())) { m_SequentialPlayer->Update(); // update sequential player m_Controls->samplePositionHorizontalSlider->setSliderPosition(m_CurrentSequentialPointNumber++); // refresh slider position m_Controls->sampleLCDNumber->display(static_cast(m_CurrentSequentialPointNumber)); //for debugging purposes //std::cout << "Sample: " << m_CurrentSequentialPointNumber << " X: " << m_SequentialPlayer->GetOutput(0)->GetPosition()[0] << " Y: " << m_SequentialPlayer->GetOutput(0)->GetPosition()[1] << " Y: " << m_SequentialPlayer->GetOutput(0)->GetPosition()[2] << std::endl; emit SignalPlayerUpdated(); // player successfully updated } else this->StopPlaying(); // if player is at EOF } const std::vector QmitkIGTPlayerWidget::GetNavigationDatas() { std::vector navDatas; if(this->GetCurrentPlaybackMode() == RealTimeMode && m_RealTimePlayer.IsNotNull()) { for(unsigned int i=0; i < m_RealTimePlayer->GetNumberOfOutputs(); ++i) { navDatas.push_back(m_RealTimePlayer->GetOutput(i)); // push back current navigation data for each tool } } else if(this->GetCurrentPlaybackMode() == SequentialMode && m_SequentialPlayer.IsNotNull()) { for(unsigned int i=0; i < m_SequentialPlayer->GetNumberOfOutputs(); ++i) { navDatas.push_back(m_SequentialPlayer->GetOutput(i)); // push back current navigation data for each tool } } return navDatas; } const mitk::PointSet::Pointer QmitkIGTPlayerWidget::GetNavigationDatasPointSet() { mitk::PointSet::Pointer result = mitk::PointSet::New(); mitk::PointSet::PointType pointType; PlaybackMode currentMode = this->GetCurrentPlaybackMode(); bool isRealTimeMode = currentMode == RealTimeMode; bool isSequentialMode = currentMode == SequentialMode; if( (isRealTimeMode && m_RealTimePlayer.IsNotNull()) || (isSequentialMode && m_SequentialPlayer.IsNotNull())) { int numberOfOutputs = 0; if(isRealTimeMode) numberOfOutputs = m_RealTimePlayer->GetNumberOfOutputs(); else if(isSequentialMode) numberOfOutputs = m_SequentialPlayer->GetNumberOfOutputs(); for(unsigned int i=0; i < m_RealTimePlayer->GetNumberOfOutputs(); ++i) { mitk::NavigationData::PositionType position; if(isRealTimeMode) position = m_RealTimePlayer->GetOutput(i)->GetPosition(); else if(isSequentialMode) position = m_SequentialPlayer->GetOutput(i)->GetPosition(); pointType[0] = position[0]; pointType[1] = position[1]; pointType[2] = position[2]; result->InsertPoint(i,pointType); // insert current ND as Pointtype in PointSet for return } } return result; } const mitk::PointSet::PointType QmitkIGTPlayerWidget::GetNavigationDataPoint(unsigned int index) { if( index > this->GetNumberOfTools() || index < 0 ) throw std::out_of_range("Tool Index out of range!"); PlaybackMode currentMode = this->GetCurrentPlaybackMode(); bool isRealTimeMode = currentMode == RealTimeMode; bool isSequentialMode = currentMode == SequentialMode; // create return PointType from current ND for tool index mitk::PointSet::PointType result; if( (isRealTimeMode && m_RealTimePlayer.IsNotNull()) || (isSequentialMode && m_SequentialPlayer.IsNotNull())) { mitk::NavigationData::PositionType position; if(isRealTimeMode) position = m_RealTimePlayer->GetOutput(index)->GetPosition(); else if(isSequentialMode) position = m_SequentialPlayer->GetOutput(index)->GetPosition(); result[0] = position[0]; result[1] = position[1]; result[2] = position[2]; } return result; } void QmitkIGTPlayerWidget::SetInputFileName(const QString& inputFileName) { this->OnGoToEnd(); /// stops playing and resets lcd numbers QString oldName = m_CmpFilename; m_CmpFilename.clear(); m_CmpFilename = inputFileName; QFile file(m_CmpFilename); if(m_CmpFilename.isEmpty() || !file.exists()) { QMessageBox::warning(NULL, "Warning", QString("Please enter valid path! Using previous path again.")); m_CmpFilename=oldName; m_Controls->inputFileLineEdit->setText(m_CmpFilename); } } void QmitkIGTPlayerWidget::SetRealTimePlayer( mitk::NavigationDataPlayer::Pointer player ) { if(player.IsNotNull()) m_RealTimePlayer = player; } void QmitkIGTPlayerWidget::SetSequentialPlayer( mitk::NavigationDataSequentialPlayer::Pointer player ) { if(player.IsNotNull()) m_SequentialPlayer = player; } void QmitkIGTPlayerWidget::OnSelectPressed() { QString oldName = m_CmpFilename; m_CmpFilename.clear(); m_CmpFilename = QFileDialog::getOpenFileName(this, "Load tracking data", QDir::currentPath(),"XML files (*.xml)"); if (m_CmpFilename.isEmpty())//if something went wrong or user pressed cancel in the save dialog m_CmpFilename=oldName; else { this->OnGoToEnd(); /// stops playing and resets lcd numbers emit SignalInputFileChanged(); } m_Controls->inputFileLineEdit->setText(m_CmpFilename); } void QmitkIGTPlayerWidget::OnGoToEnd() { this->StopPlaying(); // reset lcd numbers this->ResetLCDNumbers(); } void QmitkIGTPlayerWidget::OnGoToBegin() { // stop player manual so no PlayingStopped() m_PlayingTimer->stop(); if(this->GetCurrentPlaybackMode() == RealTimeMode && m_RealTimePlayer.IsNotNull()) { m_RealTimePlayer->StopPlaying(); m_RealTimePlayer = NULL; // set player to NULL so it can be initialized again if playback is called afterwards } m_StartTime = -1; // set starttime back //reset view elements m_Controls->playPushButton->setChecked(false); this->ResetLCDNumbers(); } void QmitkIGTPlayerWidget::ResetLCDNumbers() { m_Controls->minLCDNumber->display(QString("00")); m_Controls->secLCDNumber->display(QString("00")); m_Controls->msecLCDNumber->display(QString("000")); } void QmitkIGTPlayerWidget::SetTrajectoryNames(const QStringList toolNames) { QComboBox* cBox = m_Controls->trajectorySelectComboBox; if(cBox->count() > 0) this->ClearTrajectorySelectCombobox(); // before making changed to QComboBox it is recommended to disconnet it's SIGNALS and SLOTS disconnect( (QObject*) (m_Controls->trajectorySelectComboBox), SIGNAL(currentIndexChanged(int)), this, SIGNAL(SignalCurrentTrajectoryChanged(int)) ); if(!toolNames.isEmpty()) m_Controls->trajectorySelectComboBox->insertItems(0, toolNames); // adding current tool names to combobox // reconnect after performed changes connect( (QObject*) (m_Controls->trajectorySelectComboBox), SIGNAL(currentIndexChanged(int)), this, SIGNAL(SignalCurrentTrajectoryChanged(int)) ); } int QmitkIGTPlayerWidget::GetResolution() { return m_Controls->resolutionSpinBox->value(); // return currently selected trajectory resolution } void QmitkIGTPlayerWidget::ClearTrajectorySelectCombobox() { // before making changed to QComboBox it is recommended to disconnet it's SIGNALS and SLOTS disconnect( (QObject*) (m_Controls->trajectorySelectComboBox), SIGNAL(currentIndexChanged(int)), this, SIGNAL(SignalCurrentTrajectoryChanged(int)) ); m_Controls->trajectorySelectComboBox->clear(); // reconnect after performed changes connect( (QObject*) (m_Controls->trajectorySelectComboBox), SIGNAL(currentIndexChanged(int)), this, SIGNAL(SignalCurrentTrajectoryChanged(int)) ); } void QmitkIGTPlayerWidget::OnSequencialModeToggled(bool toggled) { this->StopPlaying(); // stop playing when mode is changed if(toggled) { m_Controls->samplePositionHorizontalSlider->setEnabled(true); // enable slider if sequential mode } else if(!toggled) { m_Controls->samplePositionHorizontalSlider->setSliderPosition(0); // set back and disable slider m_Controls->samplePositionHorizontalSlider->setDisabled(true); } } void QmitkIGTPlayerWidget::OnSliderReleased() { int currentSliderValue = m_Controls->samplePositionHorizontalSlider->value(); // current slider value selected through user movement if(currentSliderValue > m_CurrentSequentialPointNumber) // at the moment only forward scrolling is possible { m_SequentialPlayer->GoToSnapshot(currentSliderValue); // move player to selected snapshot m_CurrentSequentialPointNumber = currentSliderValue; m_Controls->sampleLCDNumber->display(currentSliderValue); // update lcdnumber in widget } else m_Controls->samplePositionHorizontalSlider->setValue(m_CurrentSequentialPointNumber); } void QmitkIGTPlayerWidget::OnSliderPressed() { if(m_Controls->playPushButton->isChecked()) // check if widget is playing m_Controls->playPushButton->click(); // perform click to pause the play -} \ No newline at end of file +} diff --git a/Modules/IGTUI/Qmitk/QmitkIGTPlayerWidget.h b/Modules/IGTUI/Qmitk/QmitkIGTPlayerWidget.h index 902084f125..a5d7821088 100644 --- a/Modules/IGTUI/Qmitk/QmitkIGTPlayerWidget.h +++ b/Modules/IGTUI/Qmitk/QmitkIGTPlayerWidget.h @@ -1,261 +1,261 @@ /*=================================================================== 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 QmitkIGTPlayerWidget_H #define QmitkIGTPlayerWidget_H //QT headers #include //mitk headers #include "MitkIGTUIExports.h" #include "mitkNavigationTool.h" #include "mitkNavigationDataPlayer.h" #include "mitkNavigationDataSequentialPlayer.h" #include #include //ui header #include "ui_QmitkIGTPlayerWidgetControls.h" /** Documentation: * \brief GUI to access the IGT Player. * User must specify the file name where the input xml-file is located. The NavigationDatas from the xml-file can be * played in normal mode or in PointSet mode. * * In normal mode the player updates the NavigationDatas every 100ms (can be changed in SetUpdateRate()) and returns * them when GetNavigationDatas() is called. * In PointSet mode the player generates a PointSet with all NavigationDatas from the xml-file. So the playback is * performed on this ND PointSet. * * \ingroup IGTUI */ class MitkIGTUI_EXPORT QmitkIGTPlayerWidget : public QWidget { Q_OBJECT public: static const std::string VIEW_ID; /*! \brief default constructor */ QmitkIGTPlayerWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); /*! \brief default deconstructor */ ~QmitkIGTPlayerWidget(); /*! \brief Sets the real time player for this player widget */ void SetRealTimePlayer(mitk::NavigationDataPlayer::Pointer player); /*! \brief Sets the sequential player for this player widget */ void SetSequentialPlayer(mitk::NavigationDataSequentialPlayer::Pointer player); /*! \brief Returns the playing timer of this widget */ QTimer* GetPlayingTimer(); /*! \brief Returns the current playback NavigationDatas from the xml-file */ const std::vector GetNavigationDatas(); /*! \brief Returns a PointSet of the current NavigationDatas for all recorded tools. */ const mitk::PointSet::Pointer GetNavigationDatasPointSet(); /*! \brief Returns a PointType of the current NavigationData for a specific tool with the given index. */ const mitk::PointSet::PointType GetNavigationDataPoint(unsigned int index); /*! \brief Sets the update rate of this widget's playing timer */ void SetUpdateRate(unsigned int msecs); /*! \brief Returns the number of different tools from the current playing stream. * * Retuns 0 if playback file is invalid. */ unsigned int GetNumberOfTools(); /*! \brief Stops the playback */ void StopPlaying(); /*! \brief Sets the given tool names list to the trajectory select combobox. */ void SetTrajectoryNames(const QStringList toolNames); /*! \brief Returns the current resolution value from the resolution spinbox. */ int GetResolution(); /*! \brief Clears all items in the trajectory selection combobox. */ void ClearTrajectorySelectCombobox(); /*! \brief Returns whether spline mode checkbox is selected. */ bool IsTrajectoryInSplineMode(); enum PlaybackMode { ///< playback mode enum RealTimeMode = 1, SequentialMode = 2 }; PlaybackMode GetCurrentPlaybackMode(); signals: /*! \brief This signal is emitted when the player starts the playback. */ void SignalPlayingStarted(); /*! \brief This signal is emitted when the player resumes after a pause. */ void SignalPlayingResumed(); /*! \brief This signal is emitted when the player stops. */ void SignalPlayingStopped(); /*! \brief This signal is emitted when the player is paused. */ void SignalPlayingPaused(); /*! \brief This signal is emitted when the player reaches the end of the playback. */ void SignalPlayingEnded(); /*! \brief This signal is emitted every time the player updated the NavigationDatas. */ void SignalPlayerUpdated(); /*! \brief This signal is emitted if the input file for the replay was changed. */ void SignalInputFileChanged(); /*! \brief This signal is emitted if the index of the current selected trajectory select combobox item changes. */ void SignalCurrentTrajectoryChanged(int index); /*! \brief This signal is emitted if the spline mode checkbox is toggled or untoggled. */ void SignalSplineModeToggled(bool toggled); protected slots: /*! \brief Starts or pauses the playback */ void OnPlayButtonClicked(bool toggled); /*! \brief Updates the playback data */ void OnPlaying(); /*! \brief Stops the playback */ void OnStopPlaying(); /*! \brief Updates the input filename */ void SetInputFileName(const QString& inputFileName); /*! \brief Opens file open dialog for searching the input file */ void OnSelectPressed(); /*! \brief Stops the playback */ void OnGoToEnd(); /*! \brief Stops the playback and resets the player to the beginning */ void OnGoToBegin(); /*! \brief Switches widget between realtime and sequential mode */ void OnSequencialModeToggled(bool toggled); /*! \brief Pauses playback when slider is pressed by user */ void OnSliderPressed(); /*! \brief Moves player position to the position selected with the slider */ void OnSliderReleased(); protected: /// \brief Creation of the connections virtual void CreateConnections(); /// \brief Creation of the Qt control virtual void CreateQtPartControl(QWidget *parent); /*! \brief Checks if an imput file with the set filename exists */ bool CheckInputFileValid(); /*! \brief Sets all LCD numbers to 0 */ void ResetLCDNumbers(); Ui::QmitkIGTPlayerWidgetControls* m_Controls; mitk::NavigationDataPlayer::Pointer m_RealTimePlayer; ///< plays NDs from a XML file mitk::NavigationDataSequentialPlayer::Pointer m_SequentialPlayer; QString m_CmpFilename; ///< filename of the input file QTimer* m_PlayingTimer; ///< update timer mitk::NavigationData::TimeStampType m_StartTime; ///< start time of playback needed for time display unsigned int m_CurrentSequentialPointNumber; ///< current point number }; -#endif \ No newline at end of file +#endif diff --git a/Modules/IGTUI/Qmitk/QmitkNavigationToolCreationWidget.cpp b/Modules/IGTUI/Qmitk/QmitkNavigationToolCreationWidget.cpp index 7a738241ce..1839a34b0e 100644 --- a/Modules/IGTUI/Qmitk/QmitkNavigationToolCreationWidget.cpp +++ b/Modules/IGTUI/Qmitk/QmitkNavigationToolCreationWidget.cpp @@ -1,236 +1,236 @@ /*=================================================================== 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 "QmitkNavigationToolCreationWidget.h" //mitk headers #include "mitkTrackingTypes.h" #include #include //qt headers #include #include //poco headers #include // vtk #include const std::string QmitkNavigationToolCreationWidget::VIEW_ID = "org.mitk.views.navigationtoolcreationwizardwidget"; QmitkNavigationToolCreationWidget::QmitkNavigationToolCreationWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { m_Controls = NULL; CreateQtPartControl(this); CreateConnections(); } QmitkNavigationToolCreationWidget::~QmitkNavigationToolCreationWidget() { } void QmitkNavigationToolCreationWidget::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkNavigationToolCreationWidgetControls; m_Controls->setupUi(parent); } } void QmitkNavigationToolCreationWidget::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_cancel), SIGNAL(clicked()), this, SLOT(OnCancel()) ); connect( (QObject*)(m_Controls->m_finished), SIGNAL(clicked()), this, SLOT(OnFinished()) ); connect( (QObject*)(m_Controls->m_LoadSurface), SIGNAL(clicked()), this, SLOT(OnLoadSurface()) ); connect( (QObject*)(m_Controls->m_LoadCalibrationFile), SIGNAL(clicked()), this, SLOT(OnLoadCalibrationFile()) ); } } void QmitkNavigationToolCreationWidget::Initialize(mitk::DataStorage* dataStorage, std::string supposedIdentifier) { m_DataStorage = dataStorage; m_Controls->m_IdentifierEdit->setText(QString(supposedIdentifier.c_str())); //initialize UI components m_Controls->m_SurfaceChooser->SetDataStorage(m_DataStorage); m_Controls->m_SurfaceChooser->SetAutoSelectNewItems(true); m_Controls->m_SurfaceChooser->SetPredicate(mitk::NodePredicateDataType::New("Surface")); //set default data m_Controls->m_ToolNameEdit->setText("NewTool"); m_Controls->m_CalibrationFileName->setText(""); m_Controls->m_SerialNumberEdit->setText(""); m_Controls->m_Surface_Use_Sphere->setChecked(true); m_Controls->m_ToolTypeChooser->setCurrentIndex(0); } void QmitkNavigationToolCreationWidget::SetTrackingDeviceType(mitk::TrackingDeviceType type, bool changeable) { switch(type) { case mitk::NDIAurora: m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break; case mitk::NDIPolaris: m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break; case mitk::ClaronMicron: m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break; default: m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0); } m_Controls->m_TrackingDeviceTypeChooser->setEnabled(changeable); } mitk::NavigationTool::Pointer QmitkNavigationToolCreationWidget::GetCreatedTool() { return m_CreatedTool; } //################################################################################## //############################## slots ############################ //################################################################################## void QmitkNavigationToolCreationWidget::OnFinished() { //here we create a new tool m_CreatedTool = mitk::NavigationTool::New(); //create DataNode... mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetName(m_Controls->m_ToolNameEdit->text().toLatin1()); if(m_Controls->m_Surface_Use_Sphere->isChecked()) { //create small sphere and use it as surface mitk::Surface::Pointer mySphere = mitk::Surface::New(); vtkSphereSource *vtkData = vtkSphereSource::New(); vtkData->SetRadius(6.0f); vtkData->SetCenter(0.0, 0.0, 0.0); vtkData->Update(); mySphere->SetVtkPolyData(vtkData->GetOutput()); vtkData->Delete(); newNode->SetData(mySphere); } else {newNode->SetData(m_Controls->m_SurfaceChooser->GetSelectedNode()->GetData());} m_CreatedTool->SetDataNode(newNode); //fill NavigationTool object m_CreatedTool->SetCalibrationFile(m_Controls->m_CalibrationFileName->text().toAscii().data()); m_CreatedTool->SetIdentifier(m_Controls->m_IdentifierEdit->text().toAscii().data()); m_CreatedTool->SetSerialNumber(m_Controls->m_SerialNumberEdit->text().toAscii().data()); //Tracking Device if (m_Controls->m_TrackingDeviceTypeChooser->currentText()=="NDI Aurora") m_CreatedTool->SetTrackingDeviceType(mitk::NDIAurora); else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()=="NDI Polaris") m_CreatedTool->SetTrackingDeviceType(mitk::NDIPolaris); else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()=="Claron Technology Micron Tracker") m_CreatedTool->SetTrackingDeviceType(mitk::ClaronMicron); else m_CreatedTool->SetTrackingDeviceType(mitk::TrackingSystemNotSpecified); //ToolType if (m_Controls->m_ToolTypeChooser->currentText()=="Instrument") m_CreatedTool->SetType(mitk::NavigationTool::Instrument); else if (m_Controls->m_ToolTypeChooser->currentText()=="Fiducial") m_CreatedTool->SetType(mitk::NavigationTool::Fiducial); else if (m_Controls->m_ToolTypeChooser->currentText()=="Skinmarker") m_CreatedTool->SetType(mitk::NavigationTool::Skinmarker); else m_CreatedTool->SetType(mitk::NavigationTool::Unknown); emit NavigationToolFinished(); } void QmitkNavigationToolCreationWidget::OnCancel() { m_CreatedTool = NULL; emit Canceled(); } void QmitkNavigationToolCreationWidget::OnLoadSurface() { std::string filename = QFileDialog::getOpenFileName(NULL,tr("Open Surface"), "/", "*.stl").toLatin1().data(); mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New(); try { stlReader->SetFileName( filename.c_str() ); stlReader->Update(); } catch (...) { } if ( stlReader->GetOutput() == NULL ); else { mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetName(filename); newNode->SetData(stlReader->GetOutput()); m_DataStorage->Add(newNode); } } void QmitkNavigationToolCreationWidget::OnLoadCalibrationFile() { m_Controls->m_CalibrationFileName->setText(QFileDialog::getOpenFileName(NULL,tr("Open Calibration File"), "/", "*.*")); } void QmitkNavigationToolCreationWidget::SetDefaultData(mitk::NavigationTool::Pointer DefaultTool) { m_Controls->m_ToolNameEdit->setText(QString(DefaultTool->GetDataNode()->GetName().c_str())); m_Controls->m_IdentifierEdit->setText(QString(DefaultTool->GetIdentifier().c_str())); m_Controls->m_SerialNumberEdit->setText(QString(DefaultTool->GetSerialNumber().c_str())); switch(DefaultTool->GetTrackingDeviceType()) { case mitk::NDIAurora: m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break; case mitk::NDIPolaris: m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break; case mitk::ClaronMicron: m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break; default: m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0); } m_Controls->m_CalibrationFileName->setText(QString(DefaultTool->GetCalibrationFile().c_str())); m_Controls->m_Surface_Use_Other->setChecked(true); switch(DefaultTool->GetType()) { case mitk::NavigationTool::Instrument: m_Controls->m_ToolTypeChooser->setCurrentIndex(0); break; case mitk::NavigationTool::Fiducial: m_Controls->m_ToolTypeChooser->setCurrentIndex(1); break; case mitk::NavigationTool::Skinmarker: m_Controls->m_ToolTypeChooser->setCurrentIndex(2); break; case mitk::NavigationTool::Unknown: m_Controls->m_ToolTypeChooser->setCurrentIndex(3); break; } m_Controls->m_SurfaceChooser->SetSelectedNode(DefaultTool->GetDataNode()); } //################################################################################## //############################## internal help methods ############################# //################################################################################## void QmitkNavigationToolCreationWidget::MessageBox(std::string s) { QMessageBox msgBox; msgBox.setText(s.c_str()); msgBox.exec(); -} \ No newline at end of file +} diff --git a/Modules/IGTUI/Qmitk/QmitkNavigationToolCreationWidget.h b/Modules/IGTUI/Qmitk/QmitkNavigationToolCreationWidget.h index dc03a8d8d1..60b5696cdf 100644 --- a/Modules/IGTUI/Qmitk/QmitkNavigationToolCreationWidget.h +++ b/Modules/IGTUI/Qmitk/QmitkNavigationToolCreationWidget.h @@ -1,101 +1,101 @@ /*=================================================================== 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 QmitkNavigationToolCreationWidget_H #define QmitkNavigationToolCreationWidget_H //QT headers #include //mitk headers #include "MitkIGTUIExports.h" #include #include #include //ui header #include "ui_QmitkNavigationToolCreationWidget.h" /** Documentation: * \brief An object of this class offers an UI to create new NavigationTools * * Be sure to call the Initialize-methode before you start the widget * otherwise some errors might occure. * * \ingroup IGTUI */ class MitkIGTUI_EXPORT QmitkNavigationToolCreationWidget : public QWidget { Q_OBJECT public: static const std::string VIEW_ID; /** @brief Initializes the widget. * @param dataStorage The data storage is needed to offer the possibility to choose surfaces from the data storage for tool visualization. * @param supposedIdentifier This Identifier is supposed for the user. It is needed because every identifier in a navigation tool storage must be unique and we don't know the others. */ void Initialize(mitk::DataStorage* dataStorage, std::string supposedIdentifier); /** @brief Sets the default tracking device type. You may also define if it is changeable or not.*/ void SetTrackingDeviceType(mitk::TrackingDeviceType type, bool changeable = true); /** @brief Sets the default data of all input fields. The default data is used from the default tool which is given as parameter. */ void SetDefaultData(mitk::NavigationTool::Pointer DefaultTool); QmitkNavigationToolCreationWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); ~QmitkNavigationToolCreationWidget(); /** @return Returns the created tool. Returns NULL if no tool was created yet. */ mitk::NavigationTool::Pointer GetCreatedTool(); signals: /** @brief This signal is emited if the user finished the creation of the tool. */ void NavigationToolFinished(); /** @brief This signal is emited if the user canceld the creation of the tool. */ void Canceled(); protected slots: void OnCancel(); void OnFinished(); void OnLoadSurface(); void OnLoadCalibrationFile(); protected: /// \brief Creation of the connections virtual void CreateConnections(); virtual void CreateQtPartControl(QWidget *parent); Ui::QmitkNavigationToolCreationWidgetControls* m_Controls; /** @brief holds the DataStorage */ mitk::DataStorage* m_DataStorage; /** @brief this pointer holds the tool which is created */ mitk::NavigationTool::Pointer m_CreatedTool; //############## private help methods ####################### void MessageBox(std::string s); }; -#endif \ No newline at end of file +#endif diff --git a/Modules/IGTUI/Qmitk/QmitkTrackingDeviceConfigurationWidget.h b/Modules/IGTUI/Qmitk/QmitkTrackingDeviceConfigurationWidget.h index 59b8e10c2f..1f05941a0a 100644 --- a/Modules/IGTUI/Qmitk/QmitkTrackingDeviceConfigurationWidget.h +++ b/Modules/IGTUI/Qmitk/QmitkTrackingDeviceConfigurationWidget.h @@ -1,189 +1,189 @@ /*=================================================================== 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 QMITKTRACKINGDEVICECONFIGURATIONWIDGET_H #define QMITKTRACKINGDEVICECONFIGURATIONWIDGET_H #include #include "MitkIGTUIExports.h" #include "ui_QmitkTrackingDeviceConfigurationWidgetControls.h" #include "mitkTrackingDevice.h" //itk headers /** Documentation: * \brief An object of this class offers an UI to configurate * a tracking device. If the user finished the configuration process and * a fully configurated tracking device is availiabe the object emits a * signal "TrackingDeviceConfigurationFinished()". You can then get the * tracking device by calling the method GetTrackingDevice(). * * Once the tracking device is configurated there are two ways to reset * the UI to allow the user for configuring a new device. The method Reset() * can be called and there is also a button "reset" which can be pressed by * the user. In both cases a signal "TrackingDeviceConfigurationReseted()" * is emitted and you may wait for a new configurated tracking device. * * The possibility to reset the configuration by the user can also be switched * of by calling the method EnableUserReset(boolean enable). * * \ingroup IGTUI */ class MitkIGTUI_EXPORT QmitkTrackingDeviceConfigurationWidget : public QWidget { Q_OBJECT public: static const std::string VIEW_ID; QmitkTrackingDeviceConfigurationWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); ~QmitkTrackingDeviceConfigurationWidget(); /* @return Returns the current configurated tracking device. If the user didn't finished the * configuration process NULL is returned. */ mitk::TrackingDevice::Pointer GetTrackingDevice(); enum Style { SIMPLE, ADVANCED, }; /* @brief Resets the UI to allow the user for configurating a new tracking device. */ void Reset(); /** @brief External call to disable this widget when configuration is finished. This is also called by the "finished" button, * but if you disable the advanced user control you might want to call this when the configuration is finished. * If you want to configure a new device call the Reset() funktion later. */ void ConfigurationFinished(); /* @brief Sets our unsets the possibility to reset the UI and start * a new configuration by the user. Concretely this means the * button "reset" is shown or not. */ void EnableUserReset(bool enable); - /** @return Returns true if the tracking device is completely configured (you can get it by calling GetTrackingDevice() in this case). - * Returns false if configuration is not finished. - */ - bool GetTrackingDeviceConfigured(); + /** @return Returns true if the tracking device is completely configured (you can get it by calling GetTrackingDevice() in this case). + * Returns false if configuration is not finished. + */ + bool GetTrackingDeviceConfigured(); /** @brief Sets the style of this widget. Default is ADVANCED. Caution: The style can only be set once at startup! */ void SetGUIStyle(Style style); /** @brief Enables/disables the advanced user controls which means the reset and finished button. When disabled you'll get NO * signals from this widget and you've to check by yourself if the configuration is finished. Default value is false. * Advanced user control is only availiable when style is ADVANCED. */ void EnableAdvancedUserControl(bool enable); signals: /* @brief This signal is sent if the user has finished the configuration of the tracking device. * The device is now availiable if the method GetTrackingDevice() is called. The tracking * device you'll get is completly configurated but no tools are added yet. */ void TrackingDeviceConfigurationFinished(); /* @brief This signal is sent if the UI was reseted and the user is required to configurate * a new tracking device. */ void TrackingDeviceConfigurationReseted(); /* @brief This signal is sent if the tracking device was changed. */ void TrackingDeviceSelectionChanged(); protected: /// \brief Creation of the connections virtual void CreateConnections(); virtual void CreateQtPartControl(QWidget *parent); Ui::QmitkTrackingDeviceConfigurationWidgetControls* m_Controls; std::stringstream m_output; mitk::TrackingDevice::Pointer m_TrackingDevice; std::string m_MTCalibrationFile; bool m_TrackingDeviceConfigurated; bool m_AdvancedUserControl; // key is port name (e.g. "COM1", "/dev/ttyS0"), value will be filled with the type of tracking device at this port typedef QMap PortDeviceMap; //######################### internal help methods ####################################### void ResetOutput(); void AddOutput(std::string s); mitk::TrackingDevice::Pointer ConstructTrackingDevice(); /** @brief Scans the given port for a NDI tracking device. * @return Returns the type of the device if one was found. Returns TrackingSystemNotSpecified if none was found. */ mitk::TrackingDeviceType ScanPort(QString port); protected slots: /* @brief This method is called when the user changes the selection of the trackingdevice (m_trackingDeviceChooser). It then sets the correct widget for the selected tracking device.*/ void TrackingDeviceChanged(); /* @brief This method is called when the user presses the button "test connection". The method will then create a temporary tracking device, * try to open a connection and start tracking. The user can see the result of the connection test on the small output window. */ void TestConnection(); /* @brief This method is called when the user presses the button "finished". A new tracking device will be created in this case and will then * then be availiable by calling GetTrackingDevice(). Also a signal TrackingDeviceConfigurationFinished() will be emitted. After this the * UI will be disablet until the widget is reseted to configure a new tracking device. */ void Finished(); /* @brief This method is called when the user presses the button "reset". He can configure a new tracking device then. The signal * TrackingDeviceConfigurationReseted() will be emitted if this method is called. The method GetTrackingDevice() will return * NULL until a new tracking device is configured. */ void ResetByUser(); /* @return Returns a configured NDI 5D tracking device. Unfortunately the NDI 5D tracking device is not yet in the open source part * so this method only returns NULL at the moment. */ virtual mitk::TrackingDevice::Pointer ConfigureNDI5DTrackingDevice(); /* @return Returns a configured NDI 6D tracking device. * The type (which means Aurora/Polaris) will not be set in the returnvalue. You have to this later. */ mitk::TrackingDevice::Pointer ConfigureNDI6DTrackingDevice(); /* @brief Scans the serial ports automatically for a connected tracking device. If the method finds a device * it selects the right type and sets the corresponding port in the widget. */ void AutoScanPorts(); /* @brief Opens a file dialog. The users sets the calibration file which location is then stored in the member m_MTCalibrationFile.*/ void SetMTCalibrationFileClicked(); }; -#endif \ No newline at end of file +#endif diff --git a/Modules/IGTUI/Qmitk/QmitkTrackingDeviceWidget.h b/Modules/IGTUI/Qmitk/QmitkTrackingDeviceWidget.h index 5952b7daa5..a49adea322 100644 --- a/Modules/IGTUI/Qmitk/QmitkTrackingDeviceWidget.h +++ b/Modules/IGTUI/Qmitk/QmitkTrackingDeviceWidget.h @@ -1,33 +1,33 @@ /*=================================================================== 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 QMITKTRACKINGDEVICEWIDGET_H #define QMITKTRACKINGDEVICEWIDGET_H #include #include "MitkIGTUIExports.h" class MitkIGTUI_EXPORT QmitkTrackingDeviceWidget : public QWidget //MitkIGTUI_EXPORT { Q_OBJECT public: QmitkTrackingDeviceWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); ~QmitkTrackingDeviceWidget(); }; -#endif \ No newline at end of file +#endif diff --git a/Modules/IGTUI/Qmitk/QmitkTrackingSourcesCheckBoxPanelWidget.cpp b/Modules/IGTUI/Qmitk/QmitkTrackingSourcesCheckBoxPanelWidget.cpp index e79792ceb2..160845ac8d 100644 --- a/Modules/IGTUI/Qmitk/QmitkTrackingSourcesCheckBoxPanelWidget.cpp +++ b/Modules/IGTUI/Qmitk/QmitkTrackingSourcesCheckBoxPanelWidget.cpp @@ -1,276 +1,276 @@ /*=================================================================== 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 "QmitkTrackingSourcesCheckBoxPanelWidget.h" #include QmitkTrackingSourcesCheckBoxPanelWidget::QmitkTrackingSourcesCheckBoxPanelWidget(QWidget* parent) : QWidget(parent), m_Controls(NULL), m_SourceCheckboxes(NULL), m_NavigationDatas(NULL), m_SelectedIds(NULL) { this->CreateQtPartControl( this ); m_SourceCheckboxes = new TrackingSourcesCheckboxes(); } QmitkTrackingSourcesCheckBoxPanelWidget::~QmitkTrackingSourcesCheckBoxPanelWidget() { delete m_SelectedIds; delete m_SourceCheckboxes; delete m_NavigationDatas; } void QmitkTrackingSourcesCheckBoxPanelWidget::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkTrackingSourcesCheckBoxPanelWidgetControls; m_Controls->setupUi(parent); this->CreateConnections(); } } void QmitkTrackingSourcesCheckBoxPanelWidget::CreateConnections() { connect( (QPushButton*) m_Controls->m_ActionButton, SIGNAL(toggled(bool)), this, SLOT(OnPerformActionClicked(bool)) ) ; connect( (QPushButton*) m_Controls->m_ActionButton, SIGNAL(clicked()), this, SLOT(OnPerformActionClicked()) ) ; } void QmitkTrackingSourcesCheckBoxPanelWidget::SetNavigationDatas(std::vector* navDatas) { if( navDatas != NULL ) m_NavigationDatas = navDatas; } void QmitkTrackingSourcesCheckBoxPanelWidget::AddNavigationData(mitk::NavigationData::Pointer nd) { if(m_NavigationDatas == NULL) m_NavigationDatas = new std::vector(); if( nd.IsNotNull() ) m_NavigationDatas->push_back(nd); } bool QmitkTrackingSourcesCheckBoxPanelWidget::IsActionButtonChecked(){ return m_Controls->m_ActionButton->isChecked(); } const std::vector* QmitkTrackingSourcesCheckBoxPanelWidget::GetSelectedTrackingSourcesIDs() { if(m_SelectedIds == NULL) m_SelectedIds = new std::vector(); else m_SelectedIds->clear(); for (unsigned int i=0; i < m_SourceCheckboxes->size(); i++) { if(m_SourceCheckboxes->at(i)->isChecked()) m_SelectedIds->push_back(i); } return m_SelectedIds; } void QmitkTrackingSourcesCheckBoxPanelWidget::ClearPanel() { while(m_Controls->m_GridLayout->count() > 0) { QWidget* actWidget = m_Controls->m_GridLayout->itemAt(0)->widget(); m_Controls->m_GridLayout->removeWidget(actWidget); delete actWidget; } if(m_SourceCheckboxes != NULL) m_SourceCheckboxes->clear(); if(m_NavigationDatas != NULL) m_NavigationDatas->clear(); } void QmitkTrackingSourcesCheckBoxPanelWidget::ClearSelectedIDs() { if(m_SelectedIds != NULL && !m_SelectedIds->empty()) m_SelectedIds->clear(); } void QmitkTrackingSourcesCheckBoxPanelWidget::ShowSourceCheckboxes() { if( m_SourceCheckboxes != NULL ) m_SourceCheckboxes->clear(); if( m_NavigationDatas == NULL ) return; QCheckBox* checkBox; int row = 0; int column; for(unsigned int i=0; i < m_NavigationDatas->size(); i++) // puts a radiobutton for every tracking source output in a 2 columns QGridLayout { column = i % 4; if( i>0 && i%4==0 ) row++; QString name(m_NavigationDatas->at(i).GetPointer()->GetName()); checkBox = new QCheckBox(name, this); connect( checkBox, SIGNAL(toggled(bool)), this , SLOT(OnCheckboxClicked(bool)) ); m_SourceCheckboxes->push_back(checkBox); m_Controls->m_GridLayout->addWidget(checkBox,row,column); } } void QmitkTrackingSourcesCheckBoxPanelWidget::EnableCheckboxes(bool enable) { for(unsigned int i=0; i< m_SourceCheckboxes->size(); i++) { m_SourceCheckboxes->at(i)->setEnabled(enable); } } void QmitkTrackingSourcesCheckBoxPanelWidget::SelectAll() { for(unsigned int i=0; i< m_SourceCheckboxes->size(); i++) { m_SourceCheckboxes->at(i)->setChecked(true); } } void QmitkTrackingSourcesCheckBoxPanelWidget::DeselectAll() { for(unsigned int i=0; i< m_SourceCheckboxes->size(); i++) { m_SourceCheckboxes->at(i)->setChecked(false); } } void QmitkTrackingSourcesCheckBoxPanelWidget::SelectCheckbox(unsigned int idx) { m_SourceCheckboxes->at(idx)->setChecked(true); } void QmitkTrackingSourcesCheckBoxPanelWidget::DeselectCheckbox(unsigned int idx) { m_SourceCheckboxes->at(idx)->setChecked(false); } void QmitkTrackingSourcesCheckBoxPanelWidget::OnCheckboxClicked(bool checked) { QCheckBox* sender = qobject_cast< QCheckBox* > (QObject::sender()); if( sender == NULL ) throw std::invalid_argument("No sender found!"); int idx = -1; for(unsigned int i=0 ;i < m_SourceCheckboxes->size(); i++) { if(sender == m_SourceCheckboxes->at(i)) { idx=i; break; } } if(idx>-1) { if(checked) emit Selected(idx); else emit Deselected(idx); } } void QmitkTrackingSourcesCheckBoxPanelWidget::SetInfoText(QString text) { m_Controls->m_InfoLabel->setText(text); } void QmitkTrackingSourcesCheckBoxPanelWidget::SetActionPerformButtonText(QString text) { m_Controls->m_ActionButton->setText(text); } void QmitkTrackingSourcesCheckBoxPanelWidget::HideActionPerformButton(bool hide) { if(hide) m_Controls->m_ActionButton->hide(); else m_Controls->m_ActionButton->show(); } void QmitkTrackingSourcesCheckBoxPanelWidget::SetActionPerformButtonCheckable(bool checkable) { if(checkable) m_Controls->m_ActionButton->setCheckable(true); else m_Controls->m_ActionButton->setCheckable(false); } void QmitkTrackingSourcesCheckBoxPanelWidget::OnPerformActionClicked(bool toggled) { if(this->GetSelectedTrackingSourcesIDs()->empty()) { m_Controls->m_ActionButton->setChecked(false); return; } if(toggled) { bool invalidND = false; for(int i=0; i < this->GetSelectedTrackingSourcesIDs()->size(); ++i) { if(!(m_NavigationDatas->at(this->GetSelectedTrackingSourcesIDs()->at(i))->IsDataValid())) invalidND = true; } if(invalidND) { QMessageBox::warning(NULL, "Invalid Tracking Data", "One or more instruments are in invalid tracking state! Requested action can not be performed!"); m_Controls->m_ActionButton->setChecked(false); return; } emit PerformAction(); } else emit StopAction(); } void QmitkTrackingSourcesCheckBoxPanelWidget::OnPerformActionClicked() { if(this->GetSelectedTrackingSourcesIDs()->empty()){ m_Controls->m_ActionButton->setChecked(false); return; } emit Action(); -} \ No newline at end of file +} diff --git a/Modules/ImageExtraction/Testing/mitkExtractDirectedPlaneImageFilterTest.cpp b/Modules/ImageExtraction/Testing/mitkExtractDirectedPlaneImageFilterTest.cpp index 93846b8217..9312793c19 100644 --- a/Modules/ImageExtraction/Testing/mitkExtractDirectedPlaneImageFilterTest.cpp +++ b/Modules/ImageExtraction/Testing/mitkExtractDirectedPlaneImageFilterTest.cpp @@ -1,297 +1,297 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information. =========================================================================*/ // //#include "mitkExtractDirectedPlaneImageFilter.h" //#include "mitkStandardFileLocations.h" // //#include //#include //#include //#include //#include // //#include "mitkTestingMacros.h" // //#include // // //class ExtractionTesting{ // //public: // // struct Testcase // { // int number; // std::string name; // std::string imageFilename; // std::string referenceImageFilename; // bool success; // mitk::Geometry2D::Pointer (*GetPlane) (void); // }; // // static void DoTesting(Testcase &testcase) // { // mitk::Image::Pointer image = GetImageToTest(testcase.imageFilename); // if ( image.IsNull){ // testcase.success = false; // return; // } // // /*mitk::Image::Pointer referenceImage = GetImageToTest(testcase.referenceImageFilename); // if ( referenceImage.IsNull){ // testcase.success = false; // return; // } // // mitk::Geometry2D::Pointer directedGeometry2D = testcase.GetPlane(); // if(directedGeometry2D.IsNull){ // testcase.success = false;*/ // } // // //put testing here // //TODO vtkIMageREslice setup // //vtkSmartPointer colorImage = image->GetVtkImageData(); // // vtkSmartPointer imageMapper = vtkSmartPointer::New(); // imageMapper->SetInput(colorImage); // // // vtkSmartPointer imageActor = vtkSmartPointer::New(); // imageActor->SetMapper(imageMapper); // //imageActor->SetPosition(20, 20); // // // Setup renderers // vtkSmartPointer renderer = vtkSmartPointer::New(); // // // Setup render window // vtkSmartPointer renderWindow = vtkSmartPointer::New(); // renderWindow->AddRenderer(renderer); // // // Setup render window interactor // vtkSmartPointer renderWindowInteractor = vtkSmartPointer::New(); // vtkSmartPointer style = vtkSmartPointer::New(); // renderWindowInteractor->SetInteractorStyle(style); // // // Render and start interaction // renderWindowInteractor->SetRenderWindow(renderWindow); // //renderer->AddViewProp(imageActor); // renderer->AddActor(imageActor); // // renderWindow->Render(); // renderWindowInteractor->Start(); // } // // // static std::vector InitializeTestCases() // { // int testcounter = 0; // std::vector tests= // // //#BEGIN setup TestCases // // { // { // ++testcounter, // "TestCoronal", // "image.nrrd", // "coronalReference.nrrd", // false, // &TestCoronal // }, // { // ++testcounter, // "TestSagital", // "image.nrrd", // "sagitalReference.nrrd", // false, // &TestSagital // }, // { // ++testcounter, // "TestCoronal", // "image.nrrd", // "coronalReference.nrrd", // false, // &TestCoronal // }, // { // ++testcounter, // "Test_u_Rotation", // "image.nrrd", // "uRotationReference.nrrd", // false, // &Test_u_Rotation // }, // { // ++testcounter, // "Test_v_Rotation", // "image.nrrd", // "vRotationReference.nrrd", // false, // &Test_v_Rotation // }, // { // ++testcounter, // "TestTwoDirectionalRation", // "image.nrrd", // "twoDirectionalRationReference.nrrd", // false, // &TestTwoDirectionalRotation // }, // { // ++testcounter, // "Test4D", // "image.nrrd", // "twoDirectionalRationReference.nrrd", // false, // &Test4D // }, // { // ++testcounter, // "Test2D", // "coronalReference.nrrd", // "coronalReference.nrrd", // false, // &Test2D // }, // { // ++testcounter, // "Test2D", // NULL, // NULL, // false, // &Test1D // } // // }; // // //#END setup TestCases // // return tests; // } // //protected: // // static mitk::Image::Pointer GetImageToTest(std::string filename){ // //retrieve referenceImage // //// mitk::StandardFileLocations::Pointer locator = mitk::StandardFileLocations::GetInstance(); //// //// const std::string filepath = locator->FindFile(filename, "Modules/MitkExt/Testing/Data"); //// //// if (filepath.empty()) //// { //// return NULL; //// } //// //////TODO read imge from file //// itk::FilenamesContainer file; //// file.push_back( filename ); // mitk::ItkImageFileReader::Pointer reader = mitk::ItkImageFileReader::New(); // reader->SetFileName("C:\home\Pics\Pic3D.nrrd"); // // reader->Update(); // // mitk::Image::Pointer image = reader->GetOutput(); // // return image; // } // // // static mitk::Geometry2D::Pointer TestSagital() // { // // return NULL; // } // // static mitk::Geometry2D::Pointer TestCoronal() // { //return NULL; // } // // static mitk::Geometry2D::Pointer TestTransversal() // { //return NULL; // } // // static mitk::Geometry2D::Pointer Test_u_Rotation() // { //return NULL; // } // // static mitk::Geometry2D::Pointer Test_v_Rotation() // { //return NULL; // } // // static mitk::Geometry2D::Pointer TestTwoDirectionalRotation() // { //return NULL; // } // // static mitk::Geometry2D::Pointer Test4DImage() // {return NULL; // // } // // static mitk::Geometry2D::Pointer Test2DImage() // { //return NULL; // } // // static mitk::Geometry2D::Pointer Test1DImage() // { //return NULL; // } // //}; // // //** // * Tests for the class "mitkExtractDirectedPlaneImageFilter". // * // * argc and argv are the command line parameters which were passed to // * the ADD_TEST command in the CMakeLists.txt file. For the automatic // * tests, argv is either empty for the simple tests or contains the filename // * of a test image for the image tests (see CMakeLists.txt). // */ //int mitkExtractDirectedPlaneImageFilterTest(int /* argc */, char* /*argv*/[]) //{ // // always start with this! // MITK_TEST_BEGIN("mitkExtractDirectedPlaneImageFilter") // // // mitk::ExtractDirectedPlaneImageFilter::Pointer extractor = mitk::ExtractDirectedPlaneImageFilter::New(); // MITK_TEST_CONDITION_REQUIRED(extractor.IsNotNull(),"Testing instantiation") // // // std::vector allTests = ExtractionTesting::InitializeTestCases(); // // for( int i = 0; i < allTests.size(); i++);{ // // ExtractionTesting::Testcase testCase = allTest[i]; // // ExtractionTesting::DoTesting(testCase); // // MITK_TEST_CONDITION(testCase.success, "Testcase #'" << testCase.number << " " << testCase.name); // } // // // always end with this! // MITK_TEST_END() -//} \ No newline at end of file +//} diff --git a/Modules/ImageStatistics/mitkPointSetStatisticsCalculator.h b/Modules/ImageStatistics/mitkPointSetStatisticsCalculator.h index b65fa8d982..f0be32f03c 100644 --- a/Modules/ImageStatistics/mitkPointSetStatisticsCalculator.h +++ b/Modules/ImageStatistics/mitkPointSetStatisticsCalculator.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 _MITK_PointSetSTATISTICSCALCULATOR_H #define _MITK_PointSetSTATISTICSCALCULATOR_H #include #include "ImageStatisticsExports.h" #include namespace mitk { /** * \brief Class for calculating statistics (like standard derivation, RMS, mean, etc.) for a PointSet. */ class ImageStatistics_EXPORT PointSetStatisticsCalculator : public itk::Object { public: mitkClassMacro( PointSetStatisticsCalculator, itk::Object ); itkNewMacro( PointSetStatisticsCalculator ); mitkNewMacro1Param(PointSetStatisticsCalculator,mitk::PointSet::Pointer) /** @brief Sets the point set which will be analysed. */ void SetPointSet(mitk::PointSet::Pointer pSet); /** @return Returns the mean position of the analysed point set (only valid navigation data). Returns [0;0;0] if there is no valid navigation data.*/ mitk::Point3D GetPositionMean(); /** @return Returns the standard derivation of each component (x, y and z) of the analysed point set (only valid navigation data). Returns [0;0;0] if there is no valid navigation data.*/ mitk::Vector3D GetPositionStandardDeviation(); /** @return Returns the sample standard derivation of each component (x, y and z) of the analysed point set (only valid navigation data). Returns [0;0;0] if there is no valid navigation data.*/ mitk::Vector3D GetPositionSampleStandardDeviation(); /** @return Returns the mean distance to the mean postion (=mean error) of the analysed point set (only valid navigation data). Returns 0 if there is no valid navigation data. */ double GetPositionErrorMean(); /** @return Returns the standard derivation of the errors of all positions of the analysed point set (only valid navigation data). Returns 0 if there is no valid navigation data. */ double GetPositionErrorStandardDeviation(); /** @return Returns the sample standard derivation of the errors of all positions of the analysed point set (only valid navigation data). Returns 0 if there is no valid navigation data. */ double GetPositionErrorSampleStandardDeviation(); /** @return Returns the RMS of the errors of all positions of the analysed point set (only valid navigation data). Returns 0 if there is no valid navigation data. */ double GetPositionErrorRMS(); /** @return Returns the median of the errors of all positions of the analysed point set (only valid navigation data). Returns 0 if there is no valid navigation data. */ double GetPositionErrorMedian(); /** @return Returns the maximum of the errors of all positions of the analysed point set (only valid navigation data). Returns 0 if there is no valid navigation data. */ double GetPositionErrorMax(); /** @return Returns the minimum of the errors of all positions of the analysed point set (only valid navigation data). Returns 0 if there is no valid navigation data. */ double GetPositionErrorMin(); //##################################################################################################### //this both methods are used by another class an so they are public... perhaps we want to move them //out of this class because they have nothing to do with point sets. /** @return returns the standard derivation of the given list (NOT of the point set).*/ double GetStabw(std::vector list); /** @return returns the sample standard derivation of the given list (NOT of the point set).*/ double GetSampleStabw(std::vector list); //##################################################################################################### protected: PointSetStatisticsCalculator(); PointSetStatisticsCalculator(mitk::PointSet::Pointer); virtual ~PointSetStatisticsCalculator(); // TODO: Remove the std::vector data structure and use mitk::PointSet everywhere /** @return Returns a list with the distances to the mean of the list */ std::vector GetErrorList(std::vector list); /** @return Returns the mean of the point list. Returns [0;0;0] if the list is empty. */ mitk::Point3D GetMean(std::vector list); /** @brief Converts a point set to a vector of Point3D. */ std::vector PointSetToVector(mitk::PointSet::Pointer pSet); /** @return Returns true if all positions in the evaluated points set are equal. False if not. */ bool CheckIfAllPositionsAreEqual(); mitk::PointSet::Pointer m_PointSet; double GetMean(std::vector list); double GetMedian(std::vector list); double GetMax(std::vector list); double GetMin(std::vector list); }; } -#endif // #define _MITK_PointSetSTATISTICSCALCULATOR_H \ No newline at end of file +#endif // #define _MITK_PointSetSTATISTICSCALCULATOR_H diff --git a/Modules/InputDevices/WiiMote/mitkKalmanFilter.cpp b/Modules/InputDevices/WiiMote/mitkKalmanFilter.cpp index 8de4cf3637..3623d3a330 100644 --- a/Modules/InputDevices/WiiMote/mitkKalmanFilter.cpp +++ b/Modules/InputDevices/WiiMote/mitkKalmanFilter.cpp @@ -1,150 +1,150 @@ /*=================================================================== 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 "mitkKalmanFilter.h" mitk::KalmanFilter::KalmanFilter(): m_IsInitialized( false ) { m_cvKalman = cvCreateKalman( 2, 1, 0 ); m_StateVector = cvCreateMat( 2, 1, CV_32FC1); } mitk::KalmanFilter::~KalmanFilter() { } float mitk::KalmanFilter::ProcessValue( float input ) { if( m_IsInitialized ) { //// predicted value //const CvMat* y_k = cvKalmanPredict( m_cvKalman, 0 ); // measured value CvMat* z_k = cvCreateMat( 1, 1, CV_32FC1 ); float Z[] ={ (float)input }; cvInitMatHeader( z_k, 1, 1, CV_32FC1, Z ); float test123 = m_cvKalman->measurement_matrix->data.fl[0]; float test234 = m_cvKalman->measurement_matrix->data.fl[1]; // zk=H•xk+vk, cvMatMulAdd( m_cvKalman->measurement_matrix, m_StateVector /* = x_k */, z_k, z_k ); // adjust Kalman filter state cvKalmanCorrect( m_cvKalman, z_k ); // apply the transition matrix A and apply "process noise" w_k // xk=A•xk-1+wk cvMatMulAdd( m_cvKalman->transition_matrix , m_StateVector /* = x_k */ , m_cvKalman->process_noise_cov , m_StateVector /* = x_k */ ); } return 0; } void mitk::KalmanFilter::SetMeasurementNoise( float measurementNoise ) { // R - measurement noise covariance matrix // , represents position variance float r = measurementNoise; float R[]= { (float)r }; cvInitMatHeader( m_cvKalman->measurement_noise_cov, 1, 1, CV_32FC1, R ); } void mitk::KalmanFilter::SetProcessNoise( float processNoise ) { ///// SYSTEM NOISE //// // Q - process noise covariance matrix Q float q = processNoise; float Q[] = { (float)q, (float)0 }; cvInitMatHeader( m_cvKalman->process_noise_cov, 2, 1, CV_32FC1, Q ); } void mitk::KalmanFilter::ResetFilter() { // Initialize Standard Kalman Filter Variables: A,B,H,Q and R // A - (or F) relates the state at previous time step k-1 to the state at current time step k // B - control matrix, it is not used if there is no control // H - measurement matrix, // Q - process noise covariance matrix, constant or variable, // R - measurement noise covariance matrix, constant or variable // xk=A•xk-1+B•uk+wk // zk=H•xk+vk, // where: // xk (xk-1) - state of the system at the moment k (k-1) // zk - measurement of the system state at the moment k // uk - external control applied at the moment k // wk and vk are normally-distributed process and measurement noise, respectively: // p(w) ~ N(0,Q) // p(v) ~ N(0,R), // B - Optional: initialize control matrix B here /*CvMat* cvInitMatHeader( CvMat* mat , int rows , int cols , int type , void* data=NULL , int step=CV_AUTOSTEP );*/ // reset state cvSetIdentity( m_StateVector ); //// OBSERVATIONS //// // measurement matrix H float H[] = { (float)1.0, (float)12.0}; cvInitMatHeader(m_cvKalman->measurement_matrix, 1, 2, CV_32FC1, H ); float test11 = m_cvKalman->measurement_matrix->data.fl[0]; float test22 = m_cvKalman->measurement_matrix->data.fl[1]; memcpy(m_cvKalman->measurement_matrix->data.fl, H, sizeof(H)); float test1 = m_cvKalman->measurement_matrix->data.fl[0]; float test2 = m_cvKalman->measurement_matrix->data.fl[1]; //// PREDICTION MATRICES //// // P - initial prediction covariance matrix (posteriori error estimate covariance matrix) float P[] = { (float)1, (float)0 }; cvInitMatHeader(m_cvKalman->error_cov_post, 2, 1, CV_32FC1, P ); // A - relates the time states double dt = 1; double A[] = { (float)1,(float)dt, (float)0, (float)1, }; cvInitMatHeader(m_cvKalman->transition_matrix, 2, 2, CV_32FC1, A); memcpy(m_cvKalman->transition_matrix->data.fl, A, sizeof(A)); // what about kalman->state_post -> corrected state (x(k)=x'(k)+K(k)*(z(k)-H*x'(k)) CvRNG rng = cvRNG(-1); //// init random prediction state //cvRandArr( &rng // , m_cvKalman->state_post // , CV_RAND_NORMAL // , cvRealScalar(0) // , cvRealScalar(0.1) ); m_IsInitialized = true; -} \ No newline at end of file +} diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteButtonEvent.h b/Modules/InputDevices/WiiMote/mitkWiiMoteButtonEvent.h index 03d355bb5f..5be08de6e4 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteButtonEvent.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteButtonEvent.h @@ -1,58 +1,58 @@ /*=================================================================== 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_WIIMOTEBUTTONEVENT_H #define MITK_WIIMOTEBUTTONEVENT_H #include "mitkEvent.h" #include "mitkVector.h" #include "mitkInteractionConst.h" #include "mitkWiiMoteExports.h" namespace mitk { /** * This event type is used for button events triggered by the
* the Wiimote driver. */ class mitkWiiMote_EXPORT WiiMoteButtonEvent : public Event, itk::EventObject { public: typedef WiiMoteButtonEvent Self; typedef itk::EventObject Superclass; /** * Initializes a Wiimote Event, that stores additional information.
* * @see mitk::Event::Event(mitk::BaseRenderer* sender, int type, int button, int buttonState, int key); */ WiiMoteButtonEvent(int type, int button, int buttonState, int key); ~WiiMoteButtonEvent(); //itk::EventObject implementation const char * GetEventName() const; bool CheckEvent(const ::itk::EventObject* e) const; ::itk::EventObject* MakeObject() const; protected: private: }; // end class } // end namespace mitk -#endif // MITK_WIIMOTEBUTTONEVENT_H \ No newline at end of file +#endif // MITK_WIIMOTEBUTTONEVENT_H diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.cpp b/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.cpp index 239692af76..ff053b9497 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.cpp +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.cpp @@ -1,52 +1,52 @@ /*=================================================================== 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 "mitkWiiMoteCalibrationEvent.h" mitk::WiiMoteCalibrationEvent::WiiMoteCalibrationEvent(double rawX, double rawY) : Event(NULL, mitk::Type_WiiMoteInput, mitk::BS_NoButton, mitk::BS_NoButton, Key_none) { m_RawX = rawX; m_RawY = rawY; } mitk::WiiMoteCalibrationEvent::~WiiMoteCalibrationEvent() { } double mitk::WiiMoteCalibrationEvent::GetXCoordinate() const { return m_RawX; } double mitk::WiiMoteCalibrationEvent::GetYCoordinate() const { return m_RawY; } const char* mitk::WiiMoteCalibrationEvent::GetEventName() const { return "WiiMoteCalibrationEvent"; } bool mitk::WiiMoteCalibrationEvent::CheckEvent(const itk::EventObject *e) const { return dynamic_cast(e); } itk::EventObject* mitk::WiiMoteCalibrationEvent::MakeObject() const { return new Self(m_RawX, m_RawY); -} \ No newline at end of file +} diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.h b/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.h index e4b15953ee..5ee80e5272 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.h @@ -1,66 +1,66 @@ /*=================================================================== 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_WIIMOTECALIBRATIONEVENT_H #define MITK_WIIMOTECALIBRATIONEVENT_H #include "mitkWiiMoteExports.h" #include "mitkEvent.h" #include "mitkVector.h" #include "mitkInteractionConst.h" namespace mitk { class mitkWiiMote_EXPORT WiiMoteCalibrationEvent : public Event, itk::EventObject { public: typedef WiiMoteCalibrationEvent Self; typedef itk::EventObject Superclass; /** * Initializes a Wiimote Event, that stores additional information.
* Such as a the raw x and y coordinates of the IR input.
* * @param rawX * x coordinate of the IR sensor input * @param rawY * y coordinate of the IR sensor input */ WiiMoteCalibrationEvent(double rawX, double rawY); ~WiiMoteCalibrationEvent(); double GetXCoordinate() const; double GetYCoordinate() const; //itk::EventObject implementation const char * GetEventName() const; bool CheckEvent(const ::itk::EventObject* e) const; ::itk::EventObject* MakeObject() const; protected: private: double m_RawX; double m_RawY; }; } -#endif // MITK_WIIMOTECALIBRATIONEVENT_H \ No newline at end of file +#endif // MITK_WIIMOTECALIBRATIONEVENT_H diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteIREvent.h b/Modules/InputDevices/WiiMote/mitkWiiMoteIREvent.h index a4270b58fa..760cc6fbb5 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteIREvent.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteIREvent.h @@ -1,75 +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 MITK_WIIMOTEIREVENT_H #define MITK_WIIMOTEIREVENT_H #include "mitkEvent.h" #include "mitkVector.h" #include "mitkInteractionConst.h" #include "mitkWiiMoteExports.h" namespace mitk { /** * This event type is used for IR events triggered by the
* the Wiimote driver. */ class mitkWiiMote_EXPORT WiiMoteIREvent : public Event, itk::EventObject { public: typedef WiiMoteIREvent Self; typedef itk::EventObject Superclass; /** * Initializes a Wiimote Event, that stores additional information.
* Such as a vector and the time of the recording
* * @param inputData * the movement of the IR sensor computed in a vector * @param recordTime * the time at which the data was recorded */ WiiMoteIREvent( mitk::Vector2D inputData , double recordTime , int sliceNavigationValue); ~WiiMoteIREvent(); /** * Returns the current movement vector with the coordinates
* in the following order: x, y, z */ mitk::Vector2D GetMovementVector() const; double GetRecordTime() const; int GetSliceNavigationValue() const; //itk::EventObject implementation const char * GetEventName() const; bool CheckEvent(const ::itk::EventObject* e) const; ::itk::EventObject* MakeObject() const; private: mitk::Vector2D m_MovementVector; double m_RecordTime; int m_SliceNavigationValue; }; // end class } // end namespace mitk -#endif // MITK_WIIMOTEIREVENT_H \ No newline at end of file +#endif // MITK_WIIMOTEIREVENT_H diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.cpp b/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.cpp index cd7701dc29..917037f5d0 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.cpp +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.cpp @@ -1,776 +1,776 @@ /*=================================================================== 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 // mitk #include #include #include #include #include #include #include #include #include // vtk #include #include #include #include #include // vnl #include #include #define _USE_MATH_DEFINES // otherwise, constants will not work #include const double DELTATIME = 0.01; mitk::WiiMoteInteractor::WiiMoteInteractor(const char* type, DataNode* dataNode) : Interactor(type, dataNode) , m_OrientationX(0) , m_OrientationY(0) , m_OrientationZ(0) , m_xVelocity (0) , m_yVelocity (0) , m_zVelocity (0) , m_xAngle (0) , m_yAngle (0) , m_zAngle (0) , m_xValue (0) , m_yValue (0) , m_zValue (0) , m_InRotation(false) , m_TranslationMode(1) , m_OriginalGeometry(NULL) , m_SurfaceInteractionMode(1) { // save original geometry mitk::Geometry3D* temp = this->TransformCurrentDataInGeometry3D(); try { m_OriginalGeometry = dynamic_cast(temp->Clone().GetPointer()); } catch(...) { MITK_WARN << "Original geometry could not be stored!"; } // connect actions to methods CONNECT_ACTION(mitk::AcONWIIMOTEINPUT,OnWiiMoteInput); CONNECT_ACTION(mitk::AcONWIIMOTEBUTTONRELEASED,OnWiiMoteReleaseButton); CONNECT_ACTION(mitk::AcRESETVIEW,OnWiiMoteResetButton); } mitk::WiiMoteInteractor::~WiiMoteInteractor() { } bool mitk::WiiMoteInteractor::OnWiiMoteResetButton(Action* action, const mitk::StateEvent* stateEvent) { // resets the geometry, so that the // object will be returned to its // initial state try { mitk::Surface* surface = dynamic_cast(m_DataNode->GetData()); mitk::Geometry3D::Pointer temp = dynamic_cast(m_OriginalGeometry->Clone().GetPointer()); surface->SetGeometry(temp); if(surface == NULL) { MITK_WARN << "Original geometry could not be used for reset!"; } m_DataNode->SetData(surface); m_DataNode->Modified(); } catch(...) { MITK_ERROR << "Original geometry could not be retrieved"; } //reset the camera, so that the objects shown in the scene can be seen. const mitk::BaseRenderer* br = mitk::GlobalInteraction::GetInstance()->GetFocus(); const mitk::VtkPropRenderer* glRenderer = dynamic_cast(br); if (glRenderer) { vtkRenderer* vtkRenderer = glRenderer->GetVtkRenderer(); mitk::DataStorage* ds = br->GetDataStorage(); if (ds == NULL) return false; mitk::BoundingBox::Pointer bb = ds->ComputeBoundingBox(); mitk::Point3D middle = bb->GetCenter(); vtkRenderer->GetActiveCamera()->SetFocalPoint(middle[0],middle[1],middle[2]); vtkRenderer->ResetCamera(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return true; } return false; } bool mitk::WiiMoteInteractor::OnWiiMoteInput(Action* action, const mitk::StateEvent* stateEvent) { const mitk::WiiMoteAllDataEvent* wiiMoteEvent; try { wiiMoteEvent = dynamic_cast(stateEvent->GetEvent()); } catch(...) { MITK_ERROR << "Event is not wiimote event and could not be transformed\n"; } m_SurfaceInteractionMode = wiiMoteEvent->GetSurfaceInteractionMode(); //this->FixedRotationAndTranslation(wiiMoteEvent); // -------------------- values for translation -------------------- float xAccel = wiiMoteEvent->GetXAcceleration(); float yAccel = wiiMoteEvent->GetYAcceleration(); float zAccel = wiiMoteEvent->GetZAcceleration(); float pitch = wiiMoteEvent->GetPitch(); float roll = wiiMoteEvent->GetRoll(); m_OrientationX = wiiMoteEvent->GetOrientationX(); m_OrientationY = wiiMoteEvent->GetOrientationY(); m_OrientationZ = wiiMoteEvent->GetOrientationZ(); // substracts the proportionate force // applied by gravity depending on the // orientation float sinP = sin(pitch/180.0 * M_PI); float cosP = cos(pitch/180.0 * M_PI); float sinR = sin(roll/180.0 * M_PI); float cosR = cos(roll/180.0 * M_PI); // x acceleration if(m_OrientationZ >= 0) { m_xValue = xAccel - sinR * cosP; } else { m_xValue = xAccel + sinR * cosP; } //// against drift //if(std::abs(xAccel) < 0.2) //{ // m_xValue = 0; //} // y acceleration m_yValue = yAccel + sinP; //// against drift //if(std::abs(yAccel) < 0.2) //{ // m_yValue = 0; //} // z acceleration m_zValue = zAccel - cosP * cosR; //// against drift //if(std::abs(zAccel) < 0.3) //{ // m_zValue = 0; //} m_xVelocity += m_xValue; m_yVelocity += m_yValue; m_zVelocity -= m_zValue; // -------------------- values for rotation -------------------- ScalarType pitchSpeed = wiiMoteEvent->GetPitchSpeed(); ScalarType rollSpeed = wiiMoteEvent->GetRollSpeed(); ScalarType yawSpeed = wiiMoteEvent->GetYawSpeed(); // x angle if(std::abs(pitchSpeed) > 50 && std::abs(pitchSpeed) < 1000) { if(m_SurfaceInteractionMode == 1) { m_xAngle = (pitchSpeed * DELTATIME); } else { m_xAngle = (-pitchSpeed * DELTATIME); } } else { m_xAngle = 0; } // y angle if(std::abs(rollSpeed) > 50 && std::abs(rollSpeed) < 1000) { m_yAngle = (rollSpeed * DELTATIME); } else { m_yAngle = 0; } // z angle if(std::abs(yawSpeed) > 50 && std::abs(yawSpeed) < 1000) { if(m_SurfaceInteractionMode == 1) { m_zAngle = (yawSpeed * DELTATIME); } else { m_zAngle = (-yawSpeed * DELTATIME); } } else { m_zAngle = 0; } // -------------------- rotation and translation -------------------- bool result = false; result = this->DynamicRotationAndTranslation(this->TransformCurrentDataInGeometry3D()); return result; } bool mitk::WiiMoteInteractor::OnWiiMoteReleaseButton(Action* action, const mitk::StateEvent* stateEvent) { m_xVelocity = 0; m_yVelocity = 0; m_zVelocity = 0; m_xValue = 0; m_yValue = 0; m_zValue = 0; m_xAngle = 0; m_yAngle = 0; m_zAngle = 0; // only for fixed translation m_InRotation = false; m_TranslationMode = 1; return true; } mitk::Geometry3D* mitk::WiiMoteInteractor::TransformCurrentDataInGeometry3D() { //checking corresponding Data; has to be a surface or a subclass mitk::Surface* surface = dynamic_cast(m_DataNode->GetData()); if ( surface == NULL ) { MITK_WARN<<"Wiimote Interactor got wrong type of data! Aborting interaction!\n"; return NULL; } Geometry3D* geometry = surface->GetUpdatedTimeSlicedGeometry()->GetGeometry3D( m_TimeStep ); return geometry; } vnl_matrix_fixed mitk::WiiMoteInteractor::ComputeCurrentCameraPosition( vtkCamera* vtkCamera ) { vnl_matrix_fixed cameraMat; //first we need the position of the camera mitk::Vector3D camPosition; double camPositionTemp[3]; vtkCamera->GetPosition(camPositionTemp); camPosition[0] = camPositionTemp[0]; camPosition[1] = camPositionTemp[1]; camPosition[2] = camPositionTemp[2]; //then the upvector of the camera mitk::Vector3D upCamVector; double upCamTemp[3]; vtkCamera->GetViewUp(upCamTemp); upCamVector[0] = upCamTemp[0]; upCamVector[1] = upCamTemp[1]; upCamVector[2] = upCamTemp[2]; upCamVector.Normalize(); //then the vector to which the camera is heading at (focalpoint) mitk::Vector3D focalPoint; double focalPointTemp[3]; vtkCamera->GetFocalPoint(focalPointTemp); focalPoint[0] = focalPointTemp[0]; focalPoint[1] = focalPointTemp[1]; focalPoint[2] = focalPointTemp[2]; mitk::Vector3D focalVector; focalVector = focalPoint - camPosition; focalVector.Normalize(); //orthogonal vector to focalVector and upCamVector mitk::Vector3D crossVector; crossVector = CrossProduct(upCamVector, focalVector); crossVector.Normalize(); cameraMat.put(0,0,crossVector[0]); cameraMat.put(1,0,crossVector[1]); cameraMat.put(2,0,crossVector[2]); cameraMat.put(3,0,0); cameraMat.put(0,1,focalVector[0]); cameraMat.put(1,1,focalVector[1]); cameraMat.put(2,1,focalVector[2]); cameraMat.put(3,1,0); cameraMat.put(0,2,upCamVector[0]); cameraMat.put(1,2,upCamVector[1]); cameraMat.put(2,2,upCamVector[2]); cameraMat.put(3,2,0); cameraMat.put(0,3,camPosition[0]); cameraMat.put(1,3,camPosition[1]); cameraMat.put(2,3,camPosition[2]); cameraMat.put(3,3,1); return cameraMat; } bool mitk::WiiMoteInteractor::DynamicRotationAndTranslation(Geometry3D* geometry) { // computation of the delta transformation if(m_SurfaceInteractionMode == 1) { // necessary because the wiimote has // a different orientation when loaded // as an object file ScalarType temp = m_yAngle; m_yAngle = m_zAngle; m_zAngle = temp; } //vnl_quaternion Rx(m_OrientationX // ,m_OrientationY // ,m_OrientationZ // , m_xAngle); //vnl_quaternion Ry(Rx.axis()[0] // , Rx.axis()[1] // , Rx.axis()[2] // , m_yAngle); //vnl_quaternion Rz(Ry.axis()[0] // , Ry.axis()[1] // , Ry.axis()[2] // , m_zAngle); vnl_quaternion q( vtkMath::RadiansFromDegrees( m_xAngle ), vtkMath::RadiansFromDegrees( m_yAngle ), vtkMath::RadiansFromDegrees( m_zAngle ) ); //q = Rz * Ry * Rx; //q.normalize(); vnl_matrix_fixed deltaTransformMat = q.rotation_matrix_transpose_4(); // fill translation column deltaTransformMat(0,3) = m_xVelocity; deltaTransformMat(1,3) = m_yVelocity; deltaTransformMat(2,3) = m_zVelocity; // invert matrix to apply // correct order for the transformation deltaTransformMat = vnl_inverse(deltaTransformMat); vtkMatrix4x4* deltaTransform = vtkMatrix4x4::New(); // copy into matrix for(size_t i=0; i<4; ++i) for(size_t j=0; j<4; ++j) deltaTransform->SetElement(i,j, deltaTransformMat(i,j)); vtkMatrix4x4* objectTransform = vtkMatrix4x4::New(); if(m_SurfaceInteractionMode == 2) { // additional computation for transformation // relative to the camera view // get renderer const RenderingManager::RenderWindowVector& renderWindows = RenderingManager::GetInstance()->GetAllRegisteredRenderWindows(); for ( RenderingManager::RenderWindowVector::const_iterator iter = renderWindows.begin(); iter != renderWindows.end(); ++iter ) { if ( mitk::BaseRenderer::GetInstance((*iter))->GetMapperID() == BaseRenderer::Standard3D ) { m_BaseRenderer = mitk::BaseRenderer::GetInstance((*iter)); } } vtkCamera* camera = m_BaseRenderer->GetVtkRenderer()->GetActiveCamera(); //vtkMatrix4x4* cameraMat = vtkMatrix4x4::New(); vnl_matrix_fixed cameraMat; vnl_matrix_fixed objectMat; // copy object matrix for(size_t i=0; i<4; ++i) for(size_t j=0; j<4; ++j) objectMat.put(i,j, geometry->GetVtkTransform()->GetMatrix()->GetElement(i,j)); cameraMat = this->ComputeCurrentCameraPosition(camera); vnl_matrix_fixed newObjectMat; vnl_matrix_fixed objectToCameraMat; objectToCameraMat = vnl_inverse(cameraMat) * objectMat; newObjectMat = vnl_inverse(objectToCameraMat) * deltaTransformMat * objectToCameraMat * vnl_inverse(objectMat); newObjectMat = vnl_inverse(newObjectMat); newObjectMat.put(0,3,objectMat(0,3)+deltaTransformMat(0,3)); newObjectMat.put(1,3,objectMat(1,3)+deltaTransformMat(1,3)); newObjectMat.put(2,3,objectMat(2,3)+deltaTransformMat(2,3)); // copy result for(size_t i=0; i<4; ++i) for(size_t j=0; j<4; ++j) objectTransform->SetElement(i,j, newObjectMat(i,j)); } //copy m_vtkMatrix to m_VtkIndexToWorldTransform geometry->TransferItkToVtkTransform(); vtkTransform* vtkTransform = vtkTransform::New(); if(m_SurfaceInteractionMode == 1) { //m_VtkIndexToWorldTransform as vtkLinearTransform* vtkTransform->SetMatrix( geometry->GetVtkTransform()->GetMatrix() ); vtkTransform->Concatenate( deltaTransform ); geometry->SetIndexToWorldTransformByVtkMatrix( vtkTransform->GetMatrix() ); } else { geometry->SetIndexToWorldTransformByVtkMatrix( objectTransform ); } geometry->Modified(); m_DataNode->Modified(); vtkTransform->Delete(); objectTransform->Delete(); deltaTransform->Delete(); //update rendering mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return true; } bool mitk::WiiMoteInteractor::FixedRotationAndTranslation(const mitk::WiiMoteAllDataEvent* wiiMoteEvent) { Geometry3D* geometry = this->TransformCurrentDataInGeometry3D(); m_OrientationX = wiiMoteEvent->GetOrientationX(); m_OrientationY = wiiMoteEvent->GetOrientationY(); m_OrientationZ = wiiMoteEvent->GetOrientationZ(); ScalarType pitchSpeed = wiiMoteEvent->GetPitchSpeed(); ScalarType rollSpeed = wiiMoteEvent->GetRollSpeed(); ScalarType yawSpeed = wiiMoteEvent->GetYawSpeed(); // angle x if(std::abs(pitchSpeed) < 200) pitchSpeed = 0; m_xAngle += (pitchSpeed / 1500); // angle y if(std::abs(rollSpeed) < 200) rollSpeed = 0; m_yAngle += (rollSpeed / 1500); // angle z if(std::abs(yawSpeed) < 200) yawSpeed = 0; m_zAngle += (yawSpeed / 1500); if( std::abs(pitchSpeed) > 200 || std::abs(rollSpeed) > 200 || std::abs(yawSpeed) > 200) { m_InRotation = true; //// depending on a combination of the //// orientation the angleX wil be altered //// because the range from roll is limited //// range: -90° to 90° by the wiimote //if(wiiMoteEvent->GetOrientationZ() < 0) //{ // // value is positive // if(wiiMoteEvent->GetOrientationX() > 0) // { // // the degree measured decreases after it reaches // // in the "real" world the 90 degree angle // // (rotation to the right side) // // therefore it needs to artificially increased // // measured value drops -> computated angle increases // angleX = 90 - angleX; // // now add the "new" angle to 90 degree threshold // angleX += 90; // } // // value is negative // else if(wiiMoteEvent->GetOrientationX() < 0) // { // // the degree measured increases after it reaches // // in the "real" world -90 degree // // (rotation to the left side) // // therefore it needs to be artificially decreased // // (example -90 -> -70, but -110 is needed) // // measured value increases -> computated angle decreases // angleX = 90 + angleX; // // invert the algebraic sign, because it is the "negative" // // side of the rotation // angleX = -angleX; // // now add the negative value to the -90 degree threshold // // to decrease the value further // angleX -= 90; // } // else if(wiiMoteEvent->GetOrientationX() == 0) // { // // i.e. wiimote is flipped upside down // angleX = 180; // } //} //rotation vtkTransform *vtkTransform = vtkTransform::New(); //copy m_vtkMatrix to m_VtkIndexToWorldTransform geometry->TransferItkToVtkTransform(); //////m_VtkIndexToWorldTransform as vtkLinearTransform* vtkTransform->SetMatrix(geometry->GetVtkTransform()->GetMatrix()); // rotation from center is different // from rotation while translated // hence one needs the center of the object Point3D center = geometry->GetOrigin(); vtkTransform->PostMultiply(); vtkTransform->Translate(-center[0], -center[1], -center[2]); //vtkTransform->RotateWXYZ(angle, rotationVector[0], rotationVector[1], rotationVector[2]); vtkTransform->RotateX(m_xAngle); vtkTransform->RotateY(m_zAngle); vtkTransform->RotateZ(m_yAngle); vtkTransform->Translate(center[0], center[1], center[2]); vtkTransform->PreMultiply(); geometry->SetIndexToWorldTransformByVtkMatrix(vtkTransform->GetMatrix()); geometry->Modified(); // indicate modification of data tree node m_DataNode->Modified(); vtkTransform->Delete(); //update rendering mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return true; } else if(!m_InRotation) { float xValue = wiiMoteEvent->GetXAcceleration(); float yValue = wiiMoteEvent->GetYAcceleration(); float zValue = wiiMoteEvent->GetZAcceleration(); float pitch = wiiMoteEvent->GetPitch(); float roll = wiiMoteEvent->GetRoll(); // substracts the proportionate force // applied by gravity depending on the // orientation float sinP = sin(pitch/180.0 * M_PI); float cosP = cos(pitch/180.0 * M_PI); float sinR = sin(roll/180.0 * M_PI); float cosR = cos(roll/180.0 * M_PI); // x acceleration if(m_OrientationZ >= 0) xValue = xValue - sinR * cosP; else xValue = xValue + sinR * cosP; // against drift if(std::abs(xValue) < 0.2) xValue = 0; // y acceleration yValue = yValue + sinP; // against drift if(std::abs(yValue) < 0.2) yValue = 0; // z acceleration zValue = zValue - cosP * cosR; // against drift if(std::abs(zValue) < 0.3) zValue = 0; // simple integration over time // resulting in velocity switch(m_TranslationMode) { case 1: m_xVelocity -= xValue; m_yVelocity -= yValue; m_zVelocity += zValue; // 1 = movement to the right // initially starts with negative acceleration // 2 = movement to the left // initially starts with positive acceleration if( m_xVelocity > 0 && xValue > 0 // 1 || m_xVelocity < 0 && xValue < 0) // 2 { m_xVelocity += xValue; } else if( m_xVelocity > 0 && xValue < 0 // 1 || m_xVelocity < 0 && xValue > 0) // 2 { m_xVelocity -= xValue; } break; case 3: m_yVelocity -= yValue; break; case 4: // 1 = movement up // initially starts with positive acceleration // 2 = movement down // initially starts with negative acceleration if( m_zVelocity > 0 && zValue < 0 // 1 || m_zVelocity < 0 && zValue > 0) // 2 { m_zVelocity -= zValue; } else if(m_zVelocity > 0 && zValue > 0 // 1 || m_zVelocity < 0 && zValue < 0) // 2 { m_zVelocity += zValue; } break; } // sets the mode of the translation // depending on the initial velocity if( std::abs(m_xVelocity) > std::abs(m_yVelocity) && std::abs(m_xVelocity) > std::abs(m_zVelocity) ) { m_TranslationMode = 2; m_yVelocity = 0; m_zVelocity = 0; } else if( std::abs(m_yVelocity) > std::abs(m_xVelocity) && std::abs(m_yVelocity) > std::abs(m_zVelocity) ) { m_TranslationMode = 3; m_xVelocity = 0; m_zVelocity = 0; } else if(std::abs(m_zVelocity) > std::abs(m_xVelocity) && std::abs(m_zVelocity) > std::abs(m_yVelocity) ) { m_TranslationMode = 4; m_xVelocity = 0; m_yVelocity = 0; } // translation mitk::Vector3D movementVector; movementVector.SetElement(0,m_xVelocity); movementVector.SetElement(1,m_yVelocity); movementVector.SetElement(2,m_zVelocity); geometry->Translate(movementVector); // indicate modification of data tree node m_DataNode->Modified(); // update rendering mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return true; } return false; -} \ No newline at end of file +} diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.h b/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.h index 701e60e309..2b47299db5 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.h @@ -1,103 +1,103 @@ /*=================================================================== 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_WIIMOTEINTERACTOR_H #define MITK_WIIMOTEINTERACTOR_H // mitk #include #include #include #include #include #include #include // export macro #include namespace mitk { class mitkWiiMote_EXPORT WiiMoteInteractor: public mitk::Interactor { public: // SmartPointer macros mitkClassMacro(WiiMoteInteractor, Interactor); mitkNewMacro2Param(Self, const char*, DataNode*); protected: // SmartPointer conventions WiiMoteInteractor(const char* type, DataNode* dataNode); virtual ~WiiMoteInteractor(); // allow movement virtual bool OnWiiMoteResetButton(Action* action, const mitk::StateEvent* event); // movement virtual bool OnWiiMoteInput(Action* action, const mitk::StateEvent* event); // stopping movement virtual bool OnWiiMoteReleaseButton(Action* action, const mitk::StateEvent* event); private: mitk::Geometry3D* TransformCurrentDataInGeometry3D(); // all movements are separated and fixed bool FixedRotationAndTranslation(const mitk::WiiMoteAllDataEvent* event); vnl_matrix_fixed ComputeCurrentCameraPosition(vtkCamera* vtkCamera); // combined movements and different interaction modes bool DynamicRotationAndTranslation(Geometry3D* geometry); float m_OrientationX; float m_OrientationY; float m_OrientationZ; float m_xVelocity; float m_yVelocity; float m_zVelocity; float m_xValue; float m_yValue; float m_zValue; // refering to an angle around an axis // which is defined in the wiimote ScalarType m_xAngle; ScalarType m_yAngle; ScalarType m_zAngle; // modes bool m_InRotation; int m_TranslationMode; // default: 1 = relative to object // 2 = relative to camera view int m_SurfaceInteractionMode; // to reset the geometry mitk::Geometry3D::Pointer m_OriginalGeometry; mitk::BaseRenderer::Pointer m_BaseRenderer; }; } -#endif // MITK_WIIMOTEINTERACTOR_H \ No newline at end of file +#endif // MITK_WIIMOTEINTERACTOR_H diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.cpp b/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.cpp index 6e0afe33b9..86fe773759 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.cpp +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.cpp @@ -1,47 +1,47 @@ /*=================================================================== 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 "mitkWiiMoteMultiIREvent.h" mitk::WiiMoteMultiIREvent::WiiMoteMultiIREvent(mitk::Point3D Coordinate3D) : Event(NULL, mitk::Type_WiiMoteInput, mitk::BS_NoButton, mitk::BS_NoButton, Key_none) { m_3DCoordinate = Coordinate3D; } mitk::WiiMoteMultiIREvent::~WiiMoteMultiIREvent() { } mitk::Point3D mitk::WiiMoteMultiIREvent::Get3DCoordinate() const { return m_3DCoordinate; } const char* mitk::WiiMoteMultiIREvent::GetEventName() const { return "WiiMoteMultiIREvent"; } bool mitk::WiiMoteMultiIREvent::CheckEvent(const itk::EventObject *e) const { return dynamic_cast(e); } itk::EventObject* mitk::WiiMoteMultiIREvent::MakeObject() const { return new Self(m_3DCoordinate); -} \ No newline at end of file +} diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.h b/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.h index 463d99fb03..c3632ce1fa 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.h @@ -1,53 +1,53 @@ /*=================================================================== 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_WIIMOTEMULTIIREVENT_H #define MITK_WIIMOTEMULITIREVENT_H #include "mitkInputDevicesExports.h" #include "mitkEvent.h" #include "mitkVector.h" #include "mitkInteractionConst.h" namespace mitk { class mitkInputDevices_EXPORT WiiMoteMultiIREvent : public Event, itk::EventObject { public: typedef WiiMoteMultiIREvent Self; typedef itk::EventObject Superclass; WiiMoteMultiIREvent(mitk::Point3D Coordinate3D); ~WiiMoteMultiIREvent(); mitk::Point3D Get3DCoordinate() const; //itk::EventObject implementation const char * GetEventName() const; bool CheckEvent(const ::itk::EventObject* e) const; ::itk::EventObject* MakeObject() const; protected: private: mitk::Point3D m_3DCoordinate; }; // end class } // end namspace -#endif // MITK_WIIMOTEMULITIREVENT_H \ No newline at end of file +#endif // MITK_WIIMOTEMULITIREVENT_H diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteThread.h b/Modules/InputDevices/WiiMote/mitkWiiMoteThread.h index 295a099dc7..7a555dda2e 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteThread.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteThread.h @@ -1,218 +1,218 @@ /*=================================================================== 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_WIIMOTEHTREAD_H #define MITK_WIIMOTEHTREAD_H #include "wiimote.h" // mitk #include "mitkCommon.h" #include "mitkCallbackFromGUIThread.h" #include "mitkVector.h" #include "mitkKalmanFilter.h" // itk #include "itkObject.h" #include "itkMultiThreader.h" #include "itkFastMutexLock.h" #include "itksys/SystemTools.hxx" // used for GetTime() and Delay(); namespace mitk { // instead of include, enables this class to know the addon class WiiMoteAddOn; class WiiMoteThread : public itk::Object { public: // typedefs are used in context with CallbackFromGUIThread typedef itk::ReceptorMemberCommand ReceptorCommand; // eventually probs with Linux -> typename typedef ReceptorCommand::Pointer ReceptorCommandPointer; WiiMoteThread(); ~WiiMoteThread(); /** * Allows to set report types, detects extensions and responds to connect/disconnect
* events of extension, such as MotionPlus. * * NOTE: don't access the public state from the 'remote' object here, as it will * be out-of-date (it's only updated via RefreshState() calls, and these * are reserved for the main application so it can be sure the values * stay consistent between calls). Instead query 'new_state' only. * * @param remote * the old state of the connected Wii remote * @param changed * the state change of the Wii remote * @param newState * the new state, after the change is applied (i.e. new extension connected) * */ static void OnStateChange(wiimote &remote, state_change_flags changed, const wiimote_state &newState); /** * Starts the thread for the Wiimote. */ void Run(); /** * Helper function, because the itk::MultiThreader can only
* start a new thread with a static member function. */ static ITK_THREAD_RETURN_TYPE StartWiiMoteThread(void* data); /** * Connects the Wiimote and allows access to its functionality. */ void StartWiiMote(); /** * Stops the running thread. */ void StopWiiMote(); /** * Reconnects the Wiimote in case the connection is lost. */ void ReconnectWiiMote(); /** * Detects all available Wiimotes. * * TODO: more detailed regarding the mode and led lighting */ bool DetectWiiMotes(); /** * Disconnects all connected Wiimotes. */ void DisconnectWiiMotes(); /** * Reads incoming data from the IR camera. After processing the data
* (e.g. computations, assigning commands...) fires Wiimote events accordingly. * */ void WiiMoteIRInput(); /** * Reads incoming data from buttons. After processing the data
* (e.g. computations, assigning commands...) fires Wiimote events
* that indicate a button was pressed. * * @param buttonType * the type of button, that was used to trigger this event */ void WiiMoteButtonPressed(int buttonType); /** * Reads incoming data from buttons. After processing the data
* (e.g. computations, assigning commands...) fires Wiimote events
* that indicate a button release. * * @param buttonType * the type of button, that was used to trigger this event */ void WiiMoteButtonReleased(int buttonType); /** * Reads incoming data from the IR camera. Afterwards the raw x and y coordinates
* are stored in an event and fired as an event. * */ void WiiMoteCalibrationInput(); /** * Constantly refreshes the state of a single wiimote. Also changes between
* the calibration mode and the IR input mode through button push. * * TODO: more detailed explanation of calibration * */ void SingleWiiMoteUpdate(); /** * Constantly refreshes the state of multiple wiimotes. */ void MultiWiiMoteUpdate(); /** * Processes the different IR inputs from multiple wiimotes. */ void MultiWiiMoteIRInput(); /** * Sets the modus for the first connected Wiimote depending
* on the given parameter. * * @param activated * true, the Surface Interaction modus will be activated * false, the Surface Interaction modus will be deactivated */ void SetWiiMoteSurfaceIModus(bool activated); // TODO void SurfaceInteraction(); protected: private: // threading int m_ThreadID; itk::MultiThreader::Pointer m_MultiThreader; // mutex to control the flow of the method StartWiiMote() itk::FastMutexLock::Pointer m_WiiMoteThreadFinished; bool m_StopWiiMote; // access to the wiimote and parameter for callbackfromguithread ReceptorCommandPointer m_Command; // required for computation of movement Point2D m_LastReadData; double m_LastRecordTime; bool m_ReadDataOnce; // modes bool m_InCalibrationMode; bool m_SurfaceInteraction; bool m_ButtonBPressed; // Default: 1 = relative to object // 2 = relative to camera view int m_SurfaceInteractionMode; //store all connected Wiimotes wiimote m_WiiMotes[4]; int m_NumberDetectedWiiMotes; // used for measuring movement int m_TimeStep; // Kalman filter mitk::KalmanFilter::Pointer m_Kalman; }; } -#endif // MITK_WIIMOTEHTREAD_H \ No newline at end of file +#endif // MITK_WIIMOTEHTREAD_H diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteVtkCameraController.h b/Modules/InputDevices/WiiMote/mitkWiiMoteVtkCameraController.h index ce0404df9b..38a132c555 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteVtkCameraController.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteVtkCameraController.h @@ -1,76 +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_WIIMOTEVTKCAMERACONTROLLER_H #define MITK_WIIMOTEVTKCAMERACONTROLLER_H // export #include "mitkWiiMoteExports.h" // mitk #include "mitkCameraController.h" #include "mitkAction.h" #include "mitkEvent.h" #include "mitkBaseRenderer.h" #include "mitkWiiMoteIREvent.h" #include "mitkWiiMoteCalibrationEvent.h" namespace mitk { class mitkWiiMote_EXPORT WiiMoteVtkCameraController : public CameraController { public: //SmartPointer Macros mitkClassMacro(WiiMoteVtkCameraController, CameraController); itkNewMacro(Self); protected: WiiMoteVtkCameraController(); ~WiiMoteVtkCameraController(); private: // head tracking bool OnWiiMoteInput(mitk::Action* a, const mitk::StateEvent* e); bool ResetView(mitk::Action* a, const mitk::StateEvent* e); bool m_ClippingRangeIsSet; double m_CurrentElevationAngle; double m_CurrentAzimuthAngle; // calibration bool m_Calibrated; double m_SensitivityXMAX; double m_SensitivityXMIN; double m_SensitivityYMAX; double m_SensitivityYMIN; double m_SensitivityX; double m_SensitivityY; bool InitCalibration(mitk::Action* a, const mitk::StateEvent* e); bool Calibration(mitk::Action* a, const mitk::StateEvent* e); bool FinishCalibration(mitk::Action* a, const mitk::StateEvent* e); // slice scrolling mitk::BaseRenderer::Pointer m_TransversalBR; double m_InitialScrollValue; int m_UpdateFrequency; }; // end class } // end namespace mitk -#endif // MITK_WIIMOTEVTKCAMERACONTROLLER_H \ No newline at end of file +#endif // MITK_WIIMOTEVTKCAMERACONTROLLER_H diff --git a/Modules/InputDevices/WiiMote/wiiyourself/wiimote.h b/Modules/InputDevices/WiiMote/wiiyourself/wiimote.h index b7c0769f16..d6b82e54ac 100644 --- a/Modules/InputDevices/WiiMote/wiiyourself/wiimote.h +++ b/Modules/InputDevices/WiiMote/wiiyourself/wiimote.h @@ -1,510 +1,510 @@ /*=================================================================== 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. ===================================================================*/ // _______________________________________________________________________________ // // - WiiYourself! - native C++ Wiimote library v1.15 // (c) gl.tter 2007-10 - http://gl.tter.org // // see License.txt for conditions of use. see History.txt for change log. // _______________________________________________________________________________ // // wiimote.h (tab = 4 spaces) #ifdef _MSC_VER // VC # pragma once #endif #ifndef _WIIMOTE_H # define _WIIMOTE_H #define WIN32_LEAN_AND_MEAN #include #include // auto Unicode/Ansi support #include // for HID write method #include // for state recording #ifndef QWORD typedef unsigned __int64 QWORD; #endif #ifdef _MSC_VER // VC-specific: _DEBUG build only _ASSERT() sanity checks # include #elif defined(__MINGW32__) // define NDEBUG to disable assert # include # define _ASSERT assert #else # define _ASSERT(x) ((void)0) // (add your compiler's implementation if you like) #endif // #ifdef SWIGWRAPPER // Python Wrapper // #include "Python/wiimote_state.i" // #else #include "wiimote_state.h" // #endif // configs: //#define USE_DYNAMIC_HIDQUEUE // deprecated // we request periodic status report updates to refresh the battery level // and to detect connection loss (through failed writes) #define REQUEST_STATUS_EVERY_MS 1000 #define DETECT_MPLUS_EVERY_MS 1000 #define DETECT_MPLUS_COUNT 1 // # of tries in quick succession // all threads (read/parse, audio streaming, async rumble...) use this priority #define WORKER_THREAD_PRIORITY THREAD_PRIORITY_HIGHEST // internals #define WIIYOURSELF_VERSION_MAJOR 1 #define WIIYOURSELF_VERSION_MINOR1 1 #define WIIYOURSELF_VERSION_MINOR2 5 //#define WIIYOURSELF_VERSION_BETA // not defined for non-beta releases #define WIIYOURSELF_VERSION_STR _T("1.15") // array sizes #define TOTAL_BUTTON_BITS 16 // Number of bits for (Classic)ButtonNameFromBit[] #define TOTAL_FREQUENCIES 10 // Number of frequencies (see speaker_freq[]) // clarity typedef HANDLE EVENT; // state data changes can be signalled to the app via a callback. Set the wiimote // object's 'ChangedCallback' any time to enable them, or alternatively inherit // from the wiimote object and override the ChangedNotifier() virtual method. // of flags indicating which state has changed since the last callback. typedef void (*state_changed_callback) (class wiimote &owner, state_change_flags changed, const wiimote_state &new_state); // internals typedef BOOLEAN (__stdcall *hidwrite_ptr)(HANDLE HidDeviceObject, PVOID ReportBuffer, ULONG ReportBufferLength); // (global due to Python wrapper) struct wiimote_state_event { DWORD time_ms; // system timestamp in milliseconds wiimote_state state; }; // wiimote class - connects and manages a wiimote and its optional extensions // (Nunchuk/Classic Controller), and exposes their state class wiimote : public wiimote_state { public: wiimote (); virtual ~wiimote (); public: // these can be used to identify Connect()ed wiimote objects (if both // are unconnected they will pass the compare as their handles are invalid) inline bool operator == (const wiimote& remote) { return Handle == remote.Handle; } inline bool operator != (const wiimote& remote) { return Handle != remote.Handle; } // wiimote data input mode (use with SetReportType()) // (only enable what you need to save battery power) enum input_report { // combinations if buttons/acceleration/IR/Extension data IN_BUTTONS = 0x30, IN_BUTTONS_ACCEL = 0x31, IN_BUTTONS_ACCEL_IR = 0x33, // reports IR EXTENDED data (dot sizes) IN_BUTTONS_ACCEL_EXT = 0x35, IN_BUTTONS_ACCEL_IR_EXT = 0x37, // reports IR BASIC data (no dot sizes) IN_BUTTONS_BALANCE_BOARD = 0x32, // must use this for the balance board }; // string versions static const TCHAR* ReportTypeName []; public: // convenience accessors: inline bool IsConnected () const { return bStatusReceived; } // if IsConnected() unexpectedly returns false, connection was probably lost inline bool ConnectionLost () const { return bConnectionLost; } inline bool IsBalanceBoard () const { return (Internal.bExtension && (Internal.ExtensionType==wiimote_state::BALANCE_BOARD)); } inline bool NunchukConnected () const { return (Internal.bExtension && (Internal.ExtensionType==wiimote_state::NUNCHUK)); } inline bool ClassicConnected () const { return (Internal.bExtension && (Internal.ExtensionType==wiimote_state::CLASSIC)); } inline bool MotionPlusConnected () const { return bMotionPlusDetected; } inline bool MotionPlusEnabled () const { return bMotionPlusEnabled; } inline bool MotionPlusHasExtension() const { return bMotionPlusExtension; } inline bool IsPlayingAudio () const { return (Internal.Speaker.Freq && Internal.Speaker.Volume); } inline bool IsPlayingSample () const { return IsPlayingAudio() && (CurrentSample != NULL); } inline bool IsUsingHIDwrites () const { return bUseHIDwrite; } inline bool IsRecordingState () const { return Recording.bEnabled; } static inline unsigned TotalConnected() { return _TotalConnected; } public: // data QWORD UniqueID; // constructed from device-specific calibration info. // Note this is not guaranteed to be truly unique // as several devices may contain the same calibration // vluaes - but unique amongst a small number of // devices. #ifdef ID2_FROM_DEVICEPATH QWORD UniqueID2; // (low-reliabilty, left for reference) // constructed from the 'device path' string (as // reported by the OS/stack). This is hopefully // unique as long as the devices remain installed // (or at least paired). #endif // optional callbacks - set these to your own fuctions (if required) state_changed_callback ChangedCallback; // you can avoid unnecessary callback overhead by specifying a mask // of which state changes should trigger them (default is any) state_change_flags CallbackTriggerFlags; // alternatively, inherit from this class and override this virtual function: virtual void ChangedNotifier (state_change_flags changed, const wiimote_state &new_state) {}; // get the button name from its bit index (some bits are unused) static const TCHAR* ButtonNameFromBit [TOTAL_BUTTON_BITS]; static const TCHAR* GetButtonNameFromBit (unsigned index) { _ASSERT(index < TOTAL_BUTTON_BITS); if(index >= TOTAL_BUTTON_BITS) return _T("[invalid index]"); return ButtonNameFromBit[index]; } // same for the Classic Controller static const TCHAR* ClassicButtonNameFromBit [TOTAL_BUTTON_BITS]; static const TCHAR* GetClassicButtonNameFromBit (unsigned index) { _ASSERT(index < TOTAL_BUTTON_BITS); if(index >= TOTAL_BUTTON_BITS) return _T("[invalid index]"); return ClassicButtonNameFromBit[index]; } // get the frequency from speaker_freq enum static const unsigned FreqLookup [TOTAL_FREQUENCIES]; static const unsigned GetFreqLookup (unsigned index) { _ASSERT(index < TOTAL_FREQUENCIES); if(index >= TOTAL_FREQUENCIES) return 0; return FreqLookup[index]; } public: // methods // call Connect() first - returns true if wiimote was found & enabled // - 'wiimote_index' specifies which *installed* (not necessarily // *connected*) wiimote should be tried (1 = first, 2 = 2nd etc). // if you just want the first *available* wiimote that isn't already // in use, pass in FIRST_AVAILABLE (default). // - 'force_hidwrites' forces HID output method (it's auto-selected // when needed and less efficient, so only force for testing). static const unsigned FIRST_AVAILABLE = 0xffffffff; bool Connect (unsigned wiimote_index = FIRST_AVAILABLE, bool force_hidwrites = false); // disconnect from the controller and stop reading data from it void Disconnect (); // set wiimote reporting mode (call after Connnect()) // continous = true forces the wiimote to send constant updates, even when // nothing has changed. // = false only sends data when something has changed (note that // acceleration data will cause frequent updates anyway as it // jitters even when the wiimote is stationary) void SetReportType (input_report type, bool continuous = false); // toggle the MotionPlus extension. Call MotionPlusDetected() first to // see if it's attached. Unlike normal extensions, the MotionPlus does // not report itself as one until enabled. Once done, it then replaces // any standard extension attached to it, so be sure to disable it // if you want to read those (it's not currently known of both can // be read simultaneously). bool EnableMotionPlus (); bool DisableMotionPlus (); // this is used to remove unwanted 'at rest' offsets, currently only from // the Balance Board. make sure there is no weight on the board before // calling this. it reads the current sensor values and then removes them // offsets from all subsequent KG and LB state values (the 'raw' values // are never modified). void CalibrateAtRest (); // NOTE: the library automatically calls this when the first weight values // come in after Connect()ion, but if the device wasn't at rest at // the time the app can call it again later. // to read the state via polling (reading the public state data direct from // the wiimote object) you must call RefreshState() at the top of every pass. // returns a combination of flags to indicate which state (if any) has // changed since the last call. state_change_flags RefreshState (); // reset the wiimote (changes report type to non-continuous buttons-only, // clears LEDs & rumble, mutes & disables speaker) void Reset (); // set/clear the wiimote LEDs void SetLEDs (BYTE led_bits); // bits 0-3 are valid // set/clear rumble void SetRumble (bool on); // alternative - rumble for a fixed amount of time (asynchronous) void RumbleForAsync (unsigned milliseconds); // *experimental* speaker support: bool MuteSpeaker (bool on); bool EnableSpeaker (bool on); bool PlaySquareWave (speaker_freq freq, BYTE volume = 0x40); // note: PlaySample currently streams from the passed-in wiimote_sample - // don't delete it until playback has stopped. bool PlaySample (const wiimote_sample &sample, BYTE volume = 0x40, speaker_freq freq_override = FREQ_NONE); // 16bit mono sample loading/conversion to native format: // .wav sample static bool Load16bitMonoSampleWAV (const TCHAR* filepath, wiimote_sample &out); // raw 16bit mono audio data (can be signed or unsigned) static bool Load16BitMonoSampleRAW (const TCHAR* filepath, bool _signed, speaker_freq freq, wiimote_sample &out); // converts a 16bit mono sample array to a wiimote_sample static bool Convert16bitMonoSamples (const short* samples, bool _signed, DWORD length, speaker_freq freq, wiimote_sample &out); // state recording - records state snapshots to a 'state_history' supplied // by the caller. states are timestamped and only added // to the list when the specified state changes. #ifndef SWIG // !Python Wrapper typedef wiimote_state_event state_event; #endif typedef std::list state_history; static const unsigned UNTIL_STOP = 0xffffffff; // - pass in a 'state_history' list, and don't destroy/change it until // recording is stopped. note the list will be cleared first. // - you can request a specific duration (and use IsRecordingState() to detect // the end), or UNTIL_STOP. StopRecording() can be called either way. // - you can use 'change trigger' to specify specific state changes that will // trigger an insert into the history (others are then ignored). void RecordState (state_history &events_out, unsigned max_time_ms = UNTIL_STOP, state_change_flags change_trigger = CHANGED_ALL); void StopRecording (); private: // methods // start reading asynchronously from the controller bool BeginAsyncRead (); // request status update (battery level, extension status etc) void RequestStatusReport (); // read address or register from Wiimote asynchronously (the result is // parsed internally whenever it arrives) bool ReadAddress (int address, short size); // write a single BYTE to a wiimote address or register inline void WriteData (int address, BYTE data) { WriteData(address, 1, &data); } // write a BYTE array to a wiimote address or register void WriteData (int address, BYTE size, const BYTE* buff); // callback when data is ready to be processed void OnReadData (DWORD bytes_read); // parse individual reports by type int ParseInput (BYTE* buff); // detects if MotionPlus is attached (it doesn't report as a normal // extesnion until it is enabled) void DetectMotionPlusExtensionAsync (); // initializes an extension when plugged in. void InitializeExtension (); // parses a status report int ParseStatus (BYTE* buff); // parses the buttons int ParseButtons (BYTE* buff); // parses accelerometer data int ParseAccel (BYTE* buff); bool EstimateOrientationFrom(wiimote_state::acceleration &accel); void ApplyJoystickDeadZones (wiimote_state::joystick &joy); // parses IR data from report int ParseIR (BYTE* buff); // parses data from an extension. int ParseExtension (BYTE* buff, unsigned offset); // parses data returned from a read report int ParseReadAddress (BYTE* buff); // reads calibration information stored on Wiimote void ReadCalibration (); float GetBalanceValue(short sensor, short min, short mid, short max); // turns on the IR sensor (the mode must match the reporting mode caps) void EnableIR (wiimote_state::ir::mode mode); // disables the IR sensor void DisableIR (); // writes a report to the Wiimote (NULL = use 'WriteBuff') bool WriteReport (BYTE* buff); bool StartSampleThread (); // returns the rumble BYTE that needs to be sent with reports. inline BYTE GetRumbleBit () const { return Internal.bRumble? 0x01 : 0x00; } // static thread funcs: static unsigned __stdcall ReadParseThreadfunc (void* param); static unsigned __stdcall AsyncRumbleThreadfunc (void* param); static unsigned __stdcall SampleStreamThreadfunc(void* param); static unsigned __stdcall HIDwriteThreadfunc (void* param); private: // data // wiimote output comands enum output_report { OUT_NONE = 0x00, OUT_LEDs = 0x11, OUT_TYPE = 0x12, OUT_IR = 0x13, OUT_SPEAKER_ENABLE = 0x14, OUT_STATUS = 0x15, OUT_WRITEMEMORY = 0x16, OUT_READMEMORY = 0x17, OUT_SPEAKER_DATA = 0x18, OUT_SPEAKER_MUTE = 0x19, OUT_IR2 = 0x1a, }; // input reports used only internally: static const int IN_STATUS = 0x20; static const int IN_READADDRESS = 0x21; // wiimote device IDs: static const int VID = 0x057e; // 'Nintendo' static const int PID = 0x0306; // 'Wiimote' // we could find this out the hard way using HID, but it's 22 static const int REPORT_LENGTH = 22; // wiimote registers static const int REGISTER_CALIBRATION = 0x0016; static const int REGISTER_IR = 0x4b00030; static const int REGISTER_IR_SENSITIVITY_1 = 0x4b00000; static const int REGISTER_IR_SENSITIVITY_2 = 0x4b0001a; static const int REGISTER_IR_MODE = 0x4b00033; static const int REGISTER_EXTENSION_INIT1 = 0x4a400f0; static const int REGISTER_EXTENSION_INIT2 = 0x4a400fb; static const int REGISTER_EXTENSION_TYPE = 0x4a400fa; static const int REGISTER_EXTENSION_CALIBRATION = 0x4a40020; static const int REGISTER_BALANCE_CALIBRATION = 0x4a40024; static const int REGISTER_MOTIONPLUS_DETECT = 0x4a600fa; static const int REGISTER_MOTIONPLUS_INIT = 0x4a600f0; static const int REGISTER_MOTIONPLUS_ENABLE = 0x4a600fe; HANDLE Handle; // read/write device handle OVERLAPPED Overlapped; // for async Read/WriteFile() IO HANDLE ReadParseThread; // waits for overlapped reads & parses result EVENT DataRead; // signals overlapped read complete bool bUseHIDwrite; // alternative write method (less efficient // but required for some BT stacks (eg. MS') // HidD_SetOutputReport is only supported from XP onwards, so detect & // load it dynamically: static HMODULE HidDLL; static hidwrite_ptr _HidD_SetOutputReport; volatile bool bStatusReceived; // for output method detection volatile bool bConnectInProgress; // don't handle extensions until complete volatile bool bInitInProgress; // stop regular requests until complete volatile bool bEnablingMotionPlus; // for special init codepath volatile bool bConnectionLost; // auto-Disconnect()s if set volatile int MotionPlusDetectCount; // waiting for the result volatile bool bMotionPlusDetected; volatile bool bMotionPlusEnabled; volatile bool bMotionPlusExtension;// detected one plugged into MotionPlus volatile bool bCalibrateAtRest; // as soon as the first sensor values // come in after a Connect() call. static unsigned _TotalCreated; static unsigned _TotalConnected; input_report ReportType; // type of data the wiimote delivers // read buffer BYTE ReadBuff [REPORT_LENGTH]; // for polling: state is updated on a thread internally, and made only // made public via RefreshState() CRITICAL_SECTION StateLock; wiimote_state Internal; state_change_flags InternalChanged; // state changes since last RefreshState() // periodic status report requests (for battery level and connection loss // detection) DWORD NextStatusTime; DWORD NextMPlusDetectTime;// gap between motion plus detections DWORD MPlusDetectCount; // # of detection tries in quick succesion // async Hidd_WriteReport() thread HANDLE HIDwriteThread; #ifdef USE_DYNAMIC_HIDQUEUE std::queue HIDwriteQueue; #else // fixed-size queue (to eliminate glitches caused by frequent dynamic memory // allocations) struct hid { hid () : Queue(NULL), ReadIndex(0), WriteIndex(0) {} // Increase the static queue size if you get ASSERTs signalling an // overflow (too many reports queued up before being sent by the write // thread). These asserts are harmless though if caused as a result of // loosing the wiimote connection (eg. battery runs out, or wiimote is // unpaired by holding the power button). // Note: MAX_QUEUE_ENTRIES _must_ be a power-of-2, as it // uses index wraparound optimisations. static const unsigned MAX_QUEUE_ENTRIES = 1<<7; inline bool IsEmpty() const { return (ReadIndex == WriteIndex); } bool Allocate () { // allocate memory (only when needed) _ASSERT(!Queue); if(Queue) return true; ReadIndex = WriteIndex = 0; Queue = new queue_entry[MAX_QUEUE_ENTRIES]; _ASSERT(Queue); return (Queue != NULL); } void Deallocate () { if(!Queue) return; delete[] Queue; Queue = NULL; ReadIndex = WriteIndex = 0; } struct queue_entry { queue_entry() { memset(Report, 0, sizeof(Report)); } BYTE Report [REPORT_LENGTH]; } *Queue; unsigned ReadIndex, WriteIndex; } HID; #endif CRITICAL_SECTION HIDwriteQueueLock; // queue must be locked before being modified // async rumble HANDLE AsyncRumbleThread; // automatically disables rumble if requested volatile DWORD AsyncRumbleTimeout; // orientation estimation unsigned WiimoteNearGUpdates; unsigned NunchukNearGUpdates; // audio HANDLE SampleThread; const wiimote_sample* volatile CurrentSample; // otherwise playing square wave // state recording struct recording { volatile bool bEnabled; state_history *StateHistory; volatile DWORD StartTimeMS; volatile DWORD EndTimeMS; // can be UNTIL_STOP unsigned TriggerFlags; // wiimote changes trigger a state event unsigned ExtTriggerFlags;// extension changes " } Recording; }; -#endif // _WIIMOTE_H \ No newline at end of file +#endif // _WIIMOTE_H diff --git a/Modules/InputDevices/WiiMote/wiiyourself/wiimote_state.h b/Modules/InputDevices/WiiMote/wiiyourself/wiimote_state.h index 972b8765c0..c15f3d0763 100644 --- a/Modules/InputDevices/WiiMote/wiiyourself/wiimote_state.h +++ b/Modules/InputDevices/WiiMote/wiiyourself/wiimote_state.h @@ -1,394 +1,394 @@ /*=================================================================== 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. ===================================================================*/ // _______________________________________________________________________________ // // - WiiYourself! - native C++ Wiimote library v1.15 // (c) gl.tter 2007-10 - http://gl.tter.org // // see License.txt for conditions of use. see History.txt for change log. // _______________________________________________________________________________ // // wiimote_state.h (tab = 4 spaces) // the 'wiimote_state' struct contains all the Wiimote and Extension state data // (buttons etc) - the wiimote class inherits from this and the app can poll // the data there at any time. #ifdef _MSC_VER // VC # pragma once #endif #ifndef _WIIMOTE_STATE_H # define _WIIMOTE_STATE_H #include "wiimote_common.h" // wiimote_state (contains the Wiimote and Extension data and settings) struct wiimote_state { friend class wiimote; // for Clear() // calibration information (stored on the Wiimote) struct calibration_info { BYTE X0, Y0, Z0; BYTE XG, YG, ZG; } CalibrationInfo; // button state: struct buttons { // convenience accessors inline bool A () const { return (Bits & _A) != 0; } inline bool B () const { return (Bits & _B) != 0; } inline bool Plus () const { return (Bits & PLUS) != 0; } inline bool Home () const { return (Bits & HOME) != 0; } inline bool Minus () const { return (Bits & MINUS) != 0; } inline bool One () const { return (Bits & ONE) != 0; } inline bool Two () const { return (Bits & TWO) != 0; } inline bool Up () const { return (Bits & UP) != 0; } inline bool Down () const { return (Bits & DOWN) != 0; } inline bool Left () const { return (Bits & LEFT) != 0; } inline bool Right () const { return (Bits & RIGHT) != 0; } // all 11 buttons stored as bits (set = pressed) WORD Bits; // button bit masks (little-endian order) enum mask { LEFT = 0x0001, RIGHT = 0x0002, DOWN = 0x0004, UP = 0x0008, PLUS = 0x0010, TWO = 0x0100, ONE = 0x0200, _B = 0x0400, // ie. trigger _A = 0x0800, MINUS = 0x1000, HOME = 0x8000, // ALL = LEFT|RIGHT|DOWN|UP|PLUS|TWO|ONE|_A|_B|MINUS|HOME, }; } Button; // accelerometers state: struct acceleration { BYTE RawX, RawY, RawZ, RawXLSB, RawYLSB, RawZLSB; float X, Y, Z; // note: experimental! the orientation values can only be safely estimated // if the controller isn't accelerating (otherwise there is no // simple way to seperate orientation from acceleration - except // perhaps using the IR reference and/or some clever assumptions). // so for now the code only updates orientation if the controller // appear to be stationary (by checking if the acceleration vector // length is near 1G for several updates in a row). // also note that there is no way to detect Yaw from the accelerometer // alone when it's pointing at the screen (and I'm not curently // processing IR): struct orientation { float X, Y, Z; unsigned UpdateAge; // how many acceleration updates ago the last // orientation estimate was made (if this // value is high, the values are out-of-date // and probably shouldn't be used). // Euler angle support (useful for some things). // * note that decomposing to Euler angles is complex, not always reliable, // and also depends on your assumptions about the order each component // is applied in. you may need to handle this yourself for more // complex scenarios * float Pitch; // in degrees (-180 - +180) float Roll; // " // float Yaw; } Orientation; } Acceleration; // IR camera state: struct ir { // in theory the IR imager is 1024x768 and so should report raw coords // 0-1023 x 0-767. in practice I have never seen them exceed the values // below, so I'm using them instead to give the full 0-1 float range // (it's possible that the edge pixels are used for processing, or masked // out due to being unreliable). let me know if your wiimote reports // a different range. static const unsigned MAX_RAW_X = 1016; static const unsigned MAX_RAW_Y = 760; // data mode reported by the IR sensor enum mode { OFF = 0x00, BASIC = 0x01, // 10 bytes EXTENDED = 0x03, // 12 bytes FULL = 0x05, // 16 bytes * 2 (format unknown) }; mode Mode; // read-only (depends on ReportType set) struct dot { bool bVisible; // other values are not valid if == false unsigned RawX; unsigned RawY; float X; // 0-1 (left-right) float Y; // " (top -bottom) int Size; // (not available in BASIC mode) } Dot[4]; } IR; struct leds { // all LEDs stored in bits 0-3 (1 = lit) BYTE Bits; // convenience accessors: inline bool Lit (unsigned index) { _ASSERT(index < 4); return (index >= 4)? false : ((Bits & (1< #include namespace mitk{ class MitkExt_EXPORT BoundingObjectToSegmentationFilter : public ImageToImageFilter { public: mitkClassMacro(BoundingObjectToSegmentationFilter, ImageToImageFilter); itkNewMacro(BoundingObjectToSegmentationFilter); void SetBoundingObject(mitk::BoundingObject::Pointer boundingObject); protected: BoundingObjectToSegmentationFilter(); virtual ~BoundingObjectToSegmentationFilter(); virtual void GenerateData(); mitk::BoundingObjectGroup::Pointer m_boundingObjectGroup; };//class }//namespace -#endif \ No newline at end of file +#endif diff --git a/Modules/MitkExt/Interactions/mitkClosingTool.cpp b/Modules/MitkExt/Interactions/mitkClosingTool.cpp index adc80ceff0..cf719f5564 100644 --- a/Modules/MitkExt/Interactions/mitkClosingTool.cpp +++ b/Modules/MitkExt/Interactions/mitkClosingTool.cpp @@ -1,88 +1,88 @@ /*=================================================================== 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 "mitkClosingTool.h" #include "mitkImageCast.h" #include "mitkRenderingManager.h" namespace mitk{ MITK_TOOL_MACRO(MitkExt_EXPORT, ClosingTool, "Closing Tool"); } mitk::ClosingTool::ClosingTool() { } mitk::ClosingTool::~ClosingTool() { } const char* mitk::ClosingTool::GetName() const { return "Closing Tool"; } const char** mitk::ClosingTool::GetXPM() const { return mitkClosingTool_xpm; } mitk::Image::Pointer mitk::ClosingTool::ApplyFilter(mitk::Image::Pointer image) { SegmentationType::Pointer itkImage = SegmentationType::New(); mitk::CastToItkImage(image, itkImage); mitk::Image::Pointer new_image = mitk::Image::New(); switch(m_StructElement) { case(BALL): m_Ball.SetRadius( m_Radius); m_Ball.CreateStructuringElement(); m_BallClosingFilter = BallClosingFilterType::New(); m_BallClosingFilter->SetKernel(m_Ball); m_BallClosingFilter->SetInput(itkImage); //m_BallClosingFilter->SetForegroundValue(1); //m_BallClosingFilter->SetBackgroundValue(0); m_BallClosingFilter->UpdateLargestPossibleRegion(); mitk::CastToMitkImage(m_BallClosingFilter->GetOutput(), new_image); break; case(CROSS): m_Cross.SetRadius(m_Radius); m_Cross.CreateStructuringElement(); m_CrossClosingFilter = CrossClosingFilterType::New(); m_CrossClosingFilter->SetKernel(m_Cross); m_CrossClosingFilter->SetInput(itkImage); //m_CrossClosingFilter->SetForegroundValue(1); //m_CrossClosingFilter->SetBackgroundValue(0); m_CrossClosingFilter->SetSafeBorder(true); m_CrossClosingFilter->UpdateLargestPossibleRegion(); mitk::CastToMitkImage(m_CrossClosingFilter->GetOutput(), new_image); break; default: break; } return new_image; -} \ No newline at end of file +} diff --git a/Modules/MitkExt/Interactions/mitkClosingTool.h b/Modules/MitkExt/Interactions/mitkClosingTool.h index 86eab497e1..51f88652d3 100644 --- a/Modules/MitkExt/Interactions/mitkClosingTool.h +++ b/Modules/MitkExt/Interactions/mitkClosingTool.h @@ -1,64 +1,64 @@ /*=================================================================== 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 MITKClOSINGTOOL_H #define MITKClOSINGTOOL_H #include "mitkMorphologicTool.h" #include "MitkExtExports.h" //itk #include #include #include #include "mitkClosingTool.xpm" namespace mitk { class MitkExt_EXPORT ClosingTool : public MorphologicTool { typedef itk::Image< unsigned char, 3 > SegmentationType; typedef itk::BinaryBallStructuringElement< SegmentationType::PixelType, 3 > BallType; typedef itk::BinaryCrossStructuringElement< SegmentationType::PixelType, 3 > CrossType; typedef itk::GrayscaleMorphologicalClosingImageFilter< SegmentationType, SegmentationType, BallType > BallClosingFilterType; typedef itk::GrayscaleMorphologicalClosingImageFilter< SegmentationType, SegmentationType, CrossType > CrossClosingFilterType; public: mitkClassMacro(ClosingTool, MorphologicTool); itkNewMacro(ClosingTool); virtual const char* GetName() const; virtual const char** GetXPM() const; protected: ClosingTool(); virtual ~ClosingTool(); mitk::Image::Pointer ApplyFilter(mitk::Image::Pointer image); BallType m_Ball; BallClosingFilterType::Pointer m_BallClosingFilter; CrossType m_Cross; CrossClosingFilterType::Pointer m_CrossClosingFilter; };//class }//namespace -#endif \ No newline at end of file +#endif diff --git a/Modules/MitkExt/Interactions/mitkDilateTool.h b/Modules/MitkExt/Interactions/mitkDilateTool.h index 7686952c8f..e6d8756697 100644 --- a/Modules/MitkExt/Interactions/mitkDilateTool.h +++ b/Modules/MitkExt/Interactions/mitkDilateTool.h @@ -1,64 +1,64 @@ /*=================================================================== 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 MITKERODETOOL_H #define MITKERODETOOL_H #include "mitkMorphologicTool.h" #include "MitkExtExports.h" //itk #include #include #include #include "mitkDilateTool.xpm" namespace mitk { class MitkExt_EXPORT DilateTool : public MorphologicTool { typedef itk::Image< unsigned char, 3 > SegmentationType; typedef itk::BinaryBallStructuringElement< SegmentationType::PixelType, 3 > BallType; typedef itk::BinaryCrossStructuringElement< SegmentationType::PixelType, 3 > CrossType; typedef itk::BinaryDilateImageFilter< SegmentationType, SegmentationType, BallType > BallDilateFilterType; typedef itk::BinaryDilateImageFilter< SegmentationType, SegmentationType, CrossType > CrossDilateFilterType; public: mitkClassMacro(DilateTool, MorphologicTool); itkNewMacro(DilateTool); virtual const char* GetName() const; virtual const char** GetXPM() const; protected: DilateTool(); virtual ~DilateTool(); mitk::Image::Pointer ApplyFilter(mitk::Image::Pointer image); BallType m_Ball; BallDilateFilterType::Pointer m_BallDilateFilter; CrossType m_Cross; CrossDilateFilterType::Pointer m_CrossDilateFilter; };//class }//namespace -#endif \ No newline at end of file +#endif diff --git a/Modules/MitkExt/Interactions/mitkErodeTool.cpp b/Modules/MitkExt/Interactions/mitkErodeTool.cpp index 2fc738e0ea..56b2051356 100644 --- a/Modules/MitkExt/Interactions/mitkErodeTool.cpp +++ b/Modules/MitkExt/Interactions/mitkErodeTool.cpp @@ -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. ===================================================================*/ #include "mitkErodeTool.h" #include "mitkImageCast.h" #include "mitkRenderingManager.h" namespace mitk{ MITK_TOOL_MACRO(MitkExt_EXPORT, ErodeTool, "Erode Tool"); } mitk::ErodeTool::ErodeTool() { } mitk::ErodeTool::~ErodeTool() { } const char* mitk::ErodeTool::GetName() const { return "Erode Tool"; } const char** mitk::ErodeTool::GetXPM() const { return mitkErodeTool_xpm; } mitk::Image::Pointer mitk::ErodeTool::ApplyFilter(mitk::Image::Pointer image) { SegmentationType::Pointer itkImage = SegmentationType::New(); mitk::CastToItkImage(image, itkImage); mitk::Image::Pointer new_image = mitk::Image::New(); switch(m_StructElement) { case(BALL): m_Ball.SetRadius( m_Radius); m_Ball.CreateStructuringElement(); m_BallErodeFilter = BallErodeFilterType::New(); m_BallErodeFilter->SetKernel(m_Ball); m_BallErodeFilter->SetInput(itkImage); m_BallErodeFilter->SetErodeValue(1); m_BallErodeFilter->BoundaryToForegroundOn(); m_BallErodeFilter->UpdateLargestPossibleRegion(); mitk::CastToMitkImage(m_BallErodeFilter->GetOutput(), new_image); break; case(CROSS): m_Cross.SetRadius(m_Radius); m_Cross.CreateStructuringElement(); m_CrossErodeFilter = CrossErodeFilterType::New(); m_CrossErodeFilter->SetKernel(m_Cross); m_CrossErodeFilter->SetInput(itkImage); m_CrossErodeFilter->SetErodeValue(1); m_CrossErodeFilter->BoundaryToForegroundOn(); m_CrossErodeFilter->UpdateLargestPossibleRegion(); mitk::CastToMitkImage(m_CrossErodeFilter->GetOutput(), new_image); break; default: break; } return new_image; -} \ No newline at end of file +} diff --git a/Modules/MitkExt/Interactions/mitkErodeTool.h b/Modules/MitkExt/Interactions/mitkErodeTool.h index 949c3aa21a..b3dc5927ec 100644 --- a/Modules/MitkExt/Interactions/mitkErodeTool.h +++ b/Modules/MitkExt/Interactions/mitkErodeTool.h @@ -1,63 +1,63 @@ /*=================================================================== 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 MITKERODETOOL_H #define MITKERODETOOL_H #include "mitkMorphologicTool.h" #include "MitkExtExports.h" //itk #include #include #include #include "mitkErodeTool.xpm" namespace mitk { class MitkExt_EXPORT ErodeTool : public MorphologicTool { typedef itk::Image< unsigned char, 3 > SegmentationType; typedef itk::BinaryBallStructuringElement< SegmentationType::PixelType, 3 > BallType; typedef itk::BinaryCrossStructuringElement< SegmentationType::PixelType, 3 > CrossType; typedef itk::BinaryErodeImageFilter< SegmentationType, SegmentationType, BallType > BallErodeFilterType; typedef itk::BinaryErodeImageFilter< SegmentationType, SegmentationType, CrossType > CrossErodeFilterType; public: mitkClassMacro(ErodeTool, MorphologicTool); itkNewMacro(ErodeTool); virtual const char* GetName() const; virtual const char** GetXPM() const; protected: ErodeTool(); virtual ~ErodeTool(); mitk::Image::Pointer ApplyFilter(mitk::Image::Pointer); BallType m_Ball; CrossType m_Cross; BallErodeFilterType::Pointer m_BallErodeFilter; CrossErodeFilterType::Pointer m_CrossErodeFilter; };//class }//namespace -#endif \ No newline at end of file +#endif diff --git a/Modules/MitkExt/Interactions/mitkMorphologicTool.h b/Modules/MitkExt/Interactions/mitkMorphologicTool.h index bf23e33005..aa21061485 100644 --- a/Modules/MitkExt/Interactions/mitkMorphologicTool.h +++ b/Modules/MitkExt/Interactions/mitkMorphologicTool.h @@ -1,68 +1,68 @@ /*=================================================================== 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 MITKMORPHOLOGICTOOL_H #define MITKMORPHOLOGICTOOL_H #include "mitkTool.h" #include "MitkExports.h" namespace mitk { /** \brief Superclass for tools using morphologic operations to modify a segmentation */ class MitkExt_EXPORT MorphologicTool : public Tool { public: mitkClassMacro(MorphologicTool, Tool); const char* GetGroup() const; itkGetMacro(Radius, unsigned int); void SetRadius(unsigned int); itkGetMacro(Preview, bool); itkSetMacro(Preview, bool); itkBooleanMacro(Preview); void SetStructuringElementType(int id); virtual void Activated(); virtual void Deactivated(); void AcceptPreview(const std::string& name, const Color& color); virtual void CancelPreviewing(); protected: MorphologicTool(); MorphologicTool(const char*); virtual ~MorphologicTool(); virtual void UpdatePreview(); virtual mitk::Image::Pointer ApplyFilter(mitk::Image::Pointer image); unsigned int m_Radius; bool m_Preview; enum StructuringElementType{BALL, CROSS}; StructuringElementType m_StructElement; mitk::DataNode::Pointer m_FeedbackNode; mitk::DataNode::Pointer m_NodeToProceed; mitk::DataNode::Pointer m_OriginalNode; };//class }//namespace -#endif \ No newline at end of file +#endif diff --git a/Modules/MitkExt/Interactions/mitkOpeningTool.cpp b/Modules/MitkExt/Interactions/mitkOpeningTool.cpp index f9d9651e28..55a4e0922a 100644 --- a/Modules/MitkExt/Interactions/mitkOpeningTool.cpp +++ b/Modules/MitkExt/Interactions/mitkOpeningTool.cpp @@ -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. ===================================================================*/ #include "mitkOpeningTool.h" #include "mitkImageCast.h" #include "mitkRenderingManager.h" namespace mitk{ MITK_TOOL_MACRO(MitkExt_EXPORT, OpeningTool, "Opening Tool"); } mitk::OpeningTool::OpeningTool() { } mitk::OpeningTool::~OpeningTool() { } const char* mitk::OpeningTool::GetName() const { return "Opening Tool"; } const char** mitk::OpeningTool::GetXPM() const { return mitkOpeningTool_xpm; } mitk::Image::Pointer mitk::OpeningTool::ApplyFilter(mitk::Image::Pointer image) { SegmentationType::Pointer itkImage = SegmentationType::New(); mitk::CastToItkImage(image, itkImage); mitk::Image::Pointer new_image = mitk::Image::New(); switch(m_StructElement) { case(BALL): m_Ball.SetRadius( m_Radius); m_Ball.CreateStructuringElement(); m_BallOpeningFilter = BallOpeningFilterType::New(); m_BallOpeningFilter->SetKernel(m_Ball); m_BallOpeningFilter->SetInput(itkImage); //m_BallOpeningFilter->SetForegroundValue(1); //m_BallOpeningFilter->SetBackgroundValue(0); m_BallOpeningFilter->UpdateLargestPossibleRegion(); mitk::CastToMitkImage(m_BallOpeningFilter->GetOutput(), new_image); break; case(CROSS): m_Cross.SetRadius(m_Radius); m_Cross.CreateStructuringElement(); m_CrossOpeningFilter = CrossOpeningFilterType::New(); m_CrossOpeningFilter->SetKernel(m_Cross); m_CrossOpeningFilter->SetInput(itkImage); //m_CrossOpeningFilter->SetForegroundValue(1); //m_CrossOpeningFilter->SetBackgroundValue(0); m_CrossOpeningFilter->UpdateLargestPossibleRegion(); mitk::CastToMitkImage(m_CrossOpeningFilter->GetOutput(), new_image); break; default: break; } return new_image; -} \ No newline at end of file +} diff --git a/Modules/MitkExt/Interactions/mitkOpeningTool.h b/Modules/MitkExt/Interactions/mitkOpeningTool.h index a3159f6f09..fa82878ac8 100644 --- a/Modules/MitkExt/Interactions/mitkOpeningTool.h +++ b/Modules/MitkExt/Interactions/mitkOpeningTool.h @@ -1,64 +1,64 @@ /*=================================================================== 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 MITKOPENINGTOOL_H #define MITKOPENINGTOOL_H #include "mitkMorphologicTool.h" #include "MitkExtExports.h" //itk #include #include #include #include "mitkOpeningTool.xpm" namespace mitk { class MitkExt_EXPORT OpeningTool : public MorphologicTool { typedef itk::Image< unsigned char, 3 > SegmentationType; typedef itk::BinaryBallStructuringElement< SegmentationType::PixelType, 3 > BallType; typedef itk::BinaryCrossStructuringElement< SegmentationType::PixelType, 3 > CrossType; typedef itk::GrayscaleMorphologicalOpeningImageFilter BallOpeningFilterType; typedef itk::GrayscaleMorphologicalOpeningImageFilter< SegmentationType, SegmentationType, CrossType > CrossOpeningFilterType; public: mitkClassMacro(OpeningTool, MorphologicTool); itkNewMacro(OpeningTool); virtual const char* GetName() const; virtual const char** GetXPM() const; protected: OpeningTool(); virtual ~OpeningTool(); mitk::Image::Pointer ApplyFilter(mitk::Image::Pointer image); BallType m_Ball; BallOpeningFilterType::Pointer m_BallOpeningFilter; CrossType m_Cross; CrossOpeningFilterType::Pointer m_CrossOpeningFilter; };//class }//namespace -#endif \ No newline at end of file +#endif diff --git a/Modules/MitkExt/Rendering/vtkMitkGPUVolumeRayCastMapper.cpp b/Modules/MitkExt/Rendering/vtkMitkGPUVolumeRayCastMapper.cpp index 147cf36aae..bfcbd72247 100644 --- a/Modules/MitkExt/Rendering/vtkMitkGPUVolumeRayCastMapper.cpp +++ b/Modules/MitkExt/Rendering/vtkMitkGPUVolumeRayCastMapper.cpp @@ -1,667 +1,667 @@ /*=================================================================== 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 "vtkVolumeRenderingFactory.h" #include "vtkImageData.h" #include "vtkPointData.h" #include "vtkCellData.h" #include "vtkDataArray.h" #include "vtkTimerLog.h" #include "vtkImageResample.h" #include "vtkVolume.h" #include "vtkVolumeProperty.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include #include "vtkCommand.h" // for VolumeMapperRender{Start|End|Progress}Event #include "vtkCamera.h" #include "vtkRendererCollection.h" #include "vtkMultiThreader.h" #include "vtkGPUInfoList.h" #include "vtkGPUInfo.h" vtkCxxRevisionMacro(vtkMitkGPUVolumeRayCastMapper, "$Revision: 1.7 $"); 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 = NULL; this->MaskInput = NULL; 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 = NULL; this->LastInput = NULL; } // ---------------------------------------------------------------------------- vtkMitkGPUVolumeRayCastMapper::~vtkMitkGPUVolumeRayCastMapper() { this->SetMaskInput(NULL); this->SetTransformedInput(NULL); this->LastInput = NULL; } // ---------------------------------------------------------------------------- vtkMitkGPUVolumeRayCastMapper *vtkMitkGPUVolumeRayCastMapper::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkVolumeRenderingFactory::CreateInstance("vtkMitkGPUVolumeRayCastMapper"); return static_cast(ret); } // ---------------------------------------------------------------------------- // 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,0); // 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,0); } // ---------------------------------------------------------------------------- // 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 NULL 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 = NULL; if ( goodSoFar ) { // Here is where we update the input this->TransformedInput->UpdateInformation(); 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->SetScalarTypeToUnsignedChar(); bigImage->SetNumberOfScalarComponents(3); bigImage->AllocateScalars(); 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(); bool *rendererVisibilities=new bool[numberOfRenderers]; renderers->InitTraversal(); int i=0; while(iGetNextItem(); 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(); bool *propVisibilities=new bool[numberOfProps]; props->InitTraversal(); i=0; while(iGetNextProp(); 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->SetInput( 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(iGetNextProp(); p->SetVisibility(propVisibilities[i]); ++i; } delete[] propVisibilities; // Restore the visibility flags of the renderers renderers->InitTraversal(); i=0; while(iGetNextItem(); r->SetDraw(rendererVisibilities[i]); ++i; } delete[] rendererVisibilities; ren->GetRenderWindow()->SetSwapBuffers(oldSwap); this->CanonicalViewImageData = NULL; 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()!=0); assert("pre: valid_cropping" && this->Cropping && this->CroppingRegionPlanes[0]CroppingRegionPlanes[1] && this->CroppingRegionPlanes[2]CroppingRegionPlanes[3] && this->CroppingRegionPlanes[4]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]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 \ No newline at end of file +#endif diff --git a/Modules/MitkExt/Rendering/vtkMitkOpenGLGPUVolumeRayCastMapper.cpp b/Modules/MitkExt/Rendering/vtkMitkOpenGLGPUVolumeRayCastMapper.cpp index 37c17d4873..4e1164516e 100644 --- a/Modules/MitkExt/Rendering/vtkMitkOpenGLGPUVolumeRayCastMapper.cpp +++ b/Modules/MitkExt/Rendering/vtkMitkOpenGLGPUVolumeRayCastMapper.cpp @@ -1,7357 +1,7357 @@ /*=================================================================== 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: vtkMitkOpenGLGPUVolumeRayCastMapper.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 "vtkMitkOpenGLGPUVolumeRayCastMapper.h" // Only with VTK 5.6 or above #if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) )) #include "vtkObjectFactory.h" #include "vtkVolume.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkCamera.h" #include "vtkMatrix4x4.h" #include "vtkImageData.h" #include "vtkTimerLog.h" #include "vtkVolumeProperty.h" #include "vtkColorTransferFunction.h" #include "vtkPiecewiseFunction.h" #include "vtkOpenGLExtensionManager.h" #include "vtkgl.h" #ifndef VTK_IMPLEMENT_MESA_CXX # include "vtkOpenGL.h" #endif #include #include #include #include #include #include "vtkClipDataSet.h" #include "vtkCellArray.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkGeometryFilter.h" #include "vtkMath.h" #include "vtkPlane.h" #include "vtkPlaneCollection.h" #include "vtkPlanes.h" #include "vtkPolyData.h" #include "vtkPointData.h" #include "vtkCellData.h" #include "vtkPoints.h" #include "vtkUnsignedCharArray.h" #include "vtkUnsignedShortArray.h" #include "vtkUnsignedIntArray.h" #include "vtkUnstructuredGrid.h" #include "vtkVoxel.h" #include "vtkClipConvexPolyData.h" #include "vtkClipPolyData.h" #include "vtkDensifyPolyData.h" #include "vtkImageResample.h" #include #include // qsort() #include "vtkDataSetTriangleFilter.h" #include "vtkAbstractArray.h" // required if compiled against VTK 5.0 #include "vtkTessellatedBoxSource.h" #include "vtkCleanPolyData.h" #include "vtkCommand.h" // for VolumeMapperRender{Start|End|Progress}Event #include "vtkPerlinNoise.h" #include #include "vtkStdString.h" //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- class vtkUnsupportedRequiredExtensionsStringStream { public: vtkstd::ostringstream Stream; vtkUnsupportedRequiredExtensionsStringStream() { } private: // undefined copy constructor. vtkUnsupportedRequiredExtensionsStringStream(const vtkUnsupportedRequiredExtensionsStringStream &other); // undefined assignment operator. vtkUnsupportedRequiredExtensionsStringStream &operator=(const vtkUnsupportedRequiredExtensionsStringStream &other); }; class vtkMapDataArrayTextureId { public: vtkstd::map Map; vtkMapDataArrayTextureId() { } private: // undefined copy constructor. vtkMapDataArrayTextureId(const vtkMapDataArrayTextureId &other); // undefined assignment operator. vtkMapDataArrayTextureId &operator=(const vtkMapDataArrayTextureId &other); }; class vtkMapMaskTextureId { public: vtkstd::map Map; vtkMapMaskTextureId() { } private: // undefined copy constructor. vtkMapMaskTextureId(const vtkMapMaskTextureId &other); // undefined assignment operator. vtkMapMaskTextureId &operator=(const vtkMapMaskTextureId &other); }; //----------------------------------------------------------------------------- extern const char *vtkMitkGPUVolumeRayCastMapper_CompositeFS; extern const char *vtkMitkGPUVolumeRayCastMapper_CompositeCroppingFS; extern const char *vtkMitkGPUVolumeRayCastMapper_CompositeNoCroppingFS; extern const char *vtkMitkGPUVolumeRayCastMapper_HeaderFS; extern const char *vtkMitkGPUVolumeRayCastMapper_MIPFS; extern const char *vtkMitkGPUVolumeRayCastMapper_MIPFourDependentFS; extern const char *vtkMitkGPUVolumeRayCastMapper_MIPFourDependentCroppingFS; extern const char *vtkMitkGPUVolumeRayCastMapper_MIPFourDependentNoCroppingFS; extern const char *vtkMitkGPUVolumeRayCastMapper_MIPCroppingFS; extern const char *vtkMitkGPUVolumeRayCastMapper_MIPNoCroppingFS; extern const char *vtkMitkGPUVolumeRayCastMapper_ParallelProjectionFS; extern const char *vtkMitkGPUVolumeRayCastMapper_PerspectiveProjectionFS; extern const char *vtkMitkGPUVolumeRayCastMapper_ScaleBiasFS; extern const char *vtkMitkGPUVolumeRayCastMapper_MinIPFS; extern const char *vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentFS; extern const char *vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentCroppingFS; extern const char *vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentNoCroppingFS; extern const char *vtkMitkGPUVolumeRayCastMapper_MinIPCroppingFS; extern const char *vtkMitkGPUVolumeRayCastMapper_MinIPNoCroppingFS; extern const char *vtkMitkGPUVolumeRayCastMapper_CompositeMaskFS; extern const char *vtkMitkGPUVolumeRayCastMapper_NoShadeFS; extern const char *vtkMitkGPUVolumeRayCastMapper_ShadeFS; extern const char *vtkMitkGPUVolumeRayCastMapper_OneComponentFS; extern const char *vtkMitkGPUVolumeRayCastMapper_FourComponentsFS; enum { vtkMitkOpenGLGPUVolumeRayCastMapperProjectionNotInitialized=-1, // not init vtkMitkOpenGLGPUVolumeRayCastMapperProjectionPerspective=0, // false vtkMitkOpenGLGPUVolumeRayCastMapperProjectionParallel=1 // true }; enum { vtkMitkOpenGLGPUVolumeRayCastMapperMethodNotInitialized, vtkMitkOpenGLGPUVolumeRayCastMapperMethodMIP, vtkMitkOpenGLGPUVolumeRayCastMapperMethodMIPFourDependent, vtkMitkOpenGLGPUVolumeRayCastMapperMethodComposite, vtkMitkOpenGLGPUVolumeRayCastMapperMethodMinIP, vtkMitkOpenGLGPUVolumeRayCastMapperMethodMinIPFourDependent, vtkMitkOpenGLGPUVolumeRayCastMapperMethodCompositeMask }; // component implementation enum { vtkMitkOpenGLGPUVolumeRayCastMapperComponentNotInitialized=-1, // not init vtkMitkOpenGLGPUVolumeRayCastMapperComponentOne=0, // false vtkMitkOpenGLGPUVolumeRayCastMapperComponentFour=1, // true vtkMitkOpenGLGPUVolumeRayCastMapperComponentNotUsed=2 // when not composite }; // Shade implementation enum { vtkMitkOpenGLGPUVolumeRayCastMapperShadeNotInitialized=-1, // not init vtkMitkOpenGLGPUVolumeRayCastMapperShadeNo=0, // false vtkMitkOpenGLGPUVolumeRayCastMapperShadeYes=1, // true vtkMitkOpenGLGPUVolumeRayCastMapperShadeNotUsed=2 // when not composite }; // Cropping implementation enum { vtkMitkOpenGLGPUVolumeRayCastMapperCroppingNotInitialized, vtkMitkOpenGLGPUVolumeRayCastMapperCompositeCropping, vtkMitkOpenGLGPUVolumeRayCastMapperCompositeNoCropping, vtkMitkOpenGLGPUVolumeRayCastMapperMIPCropping, vtkMitkOpenGLGPUVolumeRayCastMapperMIPNoCropping, vtkMitkOpenGLGPUVolumeRayCastMapperMIPFourDependentCropping, vtkMitkOpenGLGPUVolumeRayCastMapperMIPFourDependentNoCropping, vtkMitkOpenGLGPUVolumeRayCastMapperMinIPCropping, vtkMitkOpenGLGPUVolumeRayCastMapperMinIPNoCropping, vtkMitkOpenGLGPUVolumeRayCastMapperMinIPFourDependentCropping, vtkMitkOpenGLGPUVolumeRayCastMapperMinIPFourDependentNoCropping }; enum { vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectDepthMap=0, // 2d texture vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront // 2d texture }; const int vtkMitkOpenGLGPUVolumeRayCastMapperNumberOfTextureObjects=vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront+2; const int vtkMitkOpenGLGPUVolumeRayCastMapperOpacityTableSize=1024; //power of two #ifndef VTK_IMPLEMENT_MESA_CXX vtkCxxRevisionMacro(vtkMitkOpenGLGPUVolumeRayCastMapper, "$Revision: 1.9 $"); vtkStandardNewMacro(vtkMitkOpenGLGPUVolumeRayCastMapper); #endif //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- class vtkOpacityTable { public: vtkOpacityTable() { this->TextureId=0; this->LastBlendMode=vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND; this->LastSampleDistance=1.0; this->Table=0; this->Loaded=false; this->LastLinearInterpolation=false; } ~vtkOpacityTable() { if(this->TextureId!=0) { glDeleteTextures(1,&this->TextureId); this->TextureId=0; } if(this->Table!=0) { delete[] this->Table; this->Table=0; } } bool IsLoaded() { return this->Loaded; } void Bind() { assert("pre: uptodate" && this->Loaded); glBindTexture(GL_TEXTURE_1D,this->TextureId); } // \pre the active texture is set to TEXTURE2 void Update(vtkPiecewiseFunction *scalarOpacity, int blendMode, double sampleDistance, double range[2], double unitDistance, bool linearInterpolation) { assert("pre: scalarOpacity_exists" && scalarOpacity!=0); bool needUpdate=false; if(this->TextureId==0) { glGenTextures(1,&this->TextureId); needUpdate=true; } glBindTexture(GL_TEXTURE_1D,this->TextureId); if(needUpdate) { glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, vtkgl::CLAMP_TO_EDGE); } if(scalarOpacity->GetMTime() > this->BuildTime || (this->LastBlendMode!=blendMode) || (blendMode==vtkVolumeMapper::COMPOSITE_BLEND && this->LastSampleDistance!=sampleDistance) || needUpdate || !this->Loaded) { this->Loaded=false; if(this->Table==0) { this->Table= new float[vtkMitkOpenGLGPUVolumeRayCastMapperOpacityTableSize]; } scalarOpacity->GetTable(range[0],range[1], vtkMitkOpenGLGPUVolumeRayCastMapperOpacityTableSize, this->Table); this->LastBlendMode=blendMode; // Correct the opacity array for the spacing between the planes if we // are using a composite blending operation if(blendMode==vtkVolumeMapper::COMPOSITE_BLEND) { float *ptr=this->Table; double factor=sampleDistance/unitDistance; int i=0; while(i0.0001f) { *ptr=static_cast(1.0-pow(1.0-static_cast(*ptr), factor)); } ++ptr; ++i; } this->LastSampleDistance=sampleDistance; } glTexImage1D(GL_TEXTURE_1D,0,GL_ALPHA16, vtkMitkOpenGLGPUVolumeRayCastMapperOpacityTableSize,0, GL_ALPHA,GL_FLOAT,this->Table); vtkMitkOpenGLGPUVolumeRayCastMapper::PrintError("1d opacity texture is too large"); this->Loaded=true; this->BuildTime.Modified(); } needUpdate=needUpdate || this->LastLinearInterpolation!=linearInterpolation; if(needUpdate) { this->LastLinearInterpolation=linearInterpolation; GLint value; if(linearInterpolation) { value=GL_LINEAR; } else { value=GL_NEAREST; } glTexParameteri(GL_TEXTURE_1D,GL_TEXTURE_MIN_FILTER,value); glTexParameteri(GL_TEXTURE_1D,GL_TEXTURE_MAG_FILTER,value); } } protected: GLuint TextureId; int LastBlendMode; double LastSampleDistance; vtkTimeStamp BuildTime; float *Table; bool Loaded; bool LastLinearInterpolation; }; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- class vtkOpacityTables { public: vtkstd::vector Vector; vtkOpacityTables(size_t numberOfLevels) : Vector(numberOfLevels) { } private: // undefined copy constructor. vtkOpacityTables(const vtkOpacityTables &other); // undefined assignment operator. vtkOpacityTables &operator=(const vtkOpacityTables &other); }; //----------------------------------------------------------------------------- class vtkRGBTable { public: vtkRGBTable() { this->TextureId=0; this->Table=0; this->Loaded=false; this->LastLinearInterpolation=false; } ~vtkRGBTable() { if(this->TextureId!=0) { glDeleteTextures(1,&this->TextureId); this->TextureId=0; } if(this->Table!=0) { delete[] this->Table; this->Table=0; } } bool IsLoaded() { return this->Loaded; } void Bind() { assert("pre: uptodate" && this->Loaded); glBindTexture(GL_TEXTURE_1D,this->TextureId); } // \pre the active texture is set properly. (default color, // mask1, mask2,..) void Update(vtkColorTransferFunction *scalarRGB, double range[2], bool linearInterpolation) { assert("pre: scalarRGB_exists" && scalarRGB!=0); bool needUpdate=false; if(this->TextureId==0) { glGenTextures(1,&this->TextureId); needUpdate=true; } glBindTexture(GL_TEXTURE_1D,this->TextureId); if(needUpdate) { glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, vtkgl::CLAMP_TO_EDGE); } if(scalarRGB->GetMTime() > this->BuildTime || needUpdate || !this->Loaded) { this->Loaded=false; if(this->Table==0) { this->Table= new float[vtkMitkOpenGLGPUVolumeRayCastMapperOpacityTableSize*3]; } scalarRGB->GetTable(range[0],range[1], vtkMitkOpenGLGPUVolumeRayCastMapperOpacityTableSize, this->Table); glTexImage1D(GL_TEXTURE_1D,0,GL_RGB16, vtkMitkOpenGLGPUVolumeRayCastMapperOpacityTableSize,0, GL_RGB,GL_FLOAT,this->Table); vtkMitkOpenGLGPUVolumeRayCastMapper::PrintError("1d RGB texture is too large"); this->Loaded=true; this->BuildTime.Modified(); } needUpdate=needUpdate || this->LastLinearInterpolation!=linearInterpolation; if(needUpdate) { this->LastLinearInterpolation=linearInterpolation; GLint value; if(linearInterpolation) { value=GL_LINEAR; } else { value=GL_NEAREST; } glTexParameteri(GL_TEXTURE_1D,GL_TEXTURE_MIN_FILTER,value); glTexParameteri(GL_TEXTURE_1D,GL_TEXTURE_MAG_FILTER,value); } } protected: GLuint TextureId; vtkTimeStamp BuildTime; float *Table; bool Loaded; bool LastLinearInterpolation; }; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- class vtkKWScalarField { public: vtkKWScalarField() { this->TextureId=0; this->Loaded=false; this->Supports_GL_ARB_texture_float=false; this->LoadedTableRange[0]=0.0; this->LoadedTableRange[1]=1.0; this->LoadedExtent[0]=VTK_INT_MAX; this->LoadedExtent[1]=VTK_INT_MIN; this->LoadedExtent[2]=VTK_INT_MAX; this->LoadedExtent[3]=VTK_INT_MIN; this->LoadedExtent[4]=VTK_INT_MAX; this->LoadedExtent[5]=VTK_INT_MIN; } ~vtkKWScalarField() { if(this->TextureId!=0) { glDeleteTextures(1,&this->TextureId); this->TextureId=0; } } vtkTimeStamp GetBuildTime() { return this->BuildTime; } void Bind() { assert("pre: uptodate" && this->Loaded); glBindTexture(vtkgl::TEXTURE_3D,this->TextureId); } void Update(vtkImageData *input, int cellFlag, int textureExtent[6], int scalarMode, int arrayAccessMode, int arrayId, const char *arrayName, bool linearInterpolation, double tableRange[2], int maxMemoryInBytes) { bool needUpdate=false; bool modified=false; if(this->TextureId==0) { glGenTextures(1,&this->TextureId); needUpdate=true; } glBindTexture(vtkgl::TEXTURE_3D,this->TextureId); int obsolete=needUpdate || !this->Loaded || input->GetMTime()>this->BuildTime; if(!obsolete) { obsolete=cellFlag!=this->LoadedCellFlag; int i=0; while(!obsolete && i<6) { obsolete=obsolete || this->LoadedExtent[i]>textureExtent[i]; ++i; obsolete=obsolete || this->LoadedExtent[i]LoadedTableRange[0]!=tableRange[0] || this->LoadedTableRange[1]!=tableRange[1]; } if(obsolete) { this->Loaded=false; int dim[3]; input->GetDimensions(dim); GLint internalFormat=0; GLenum format=0; GLenum type=0; // shift then scale: y:=(x+shift)*scale double shift=0.0; double scale=1.0; int needTypeConversion=0; vtkDataArray *sliceArray=0; vtkDataArray *scalars= vtkAbstractMapper::GetScalars(input,scalarMode,arrayAccessMode, arrayId,arrayName, this->LoadedCellFlag); // DONT USE GetScalarType() or GetNumberOfScalarComponents() on // ImageData as it deals only with point data... int scalarType=scalars->GetDataType(); if(scalars->GetNumberOfComponents()==4) { // this is RGBA, unsigned char only internalFormat=GL_RGBA16; format=GL_RGBA; type=GL_UNSIGNED_BYTE; } else { // input->GetNumberOfScalarComponents()==1 switch(scalarType) { case VTK_FLOAT: if(this->Supports_GL_ARB_texture_float) { internalFormat=vtkgl::INTENSITY16F_ARB; } else { internalFormat=GL_INTENSITY16; } format=GL_RED; type=GL_FLOAT; shift=-tableRange[0]; scale=1/(tableRange[1]-tableRange[0]); break; case VTK_UNSIGNED_CHAR: internalFormat=GL_INTENSITY8; format=GL_RED; type=GL_UNSIGNED_BYTE; shift=-tableRange[0]/VTK_UNSIGNED_CHAR_MAX; scale= VTK_UNSIGNED_CHAR_MAX/(tableRange[1]-tableRange[0]); break; case VTK_SIGNED_CHAR: internalFormat=GL_INTENSITY8; format=GL_RED; type=GL_BYTE; shift=-(2*tableRange[0]+1)/VTK_UNSIGNED_CHAR_MAX; scale=VTK_SIGNED_CHAR_MAX/(tableRange[1]-tableRange[0]); break; case VTK_CHAR: // not supported assert("check: impossible case" && 0); break; case VTK_BIT: // not supported assert("check: impossible case" && 0); break; case VTK_ID_TYPE: // not supported assert("check: impossible case" && 0); break; case VTK_INT: internalFormat=GL_INTENSITY16; format=GL_RED; type=GL_INT; shift=-(2*tableRange[0]+1)/VTK_UNSIGNED_INT_MAX; scale=VTK_INT_MAX/(tableRange[1]-tableRange[0]); break; case VTK_DOUBLE: case VTK___INT64: case VTK_LONG: case VTK_LONG_LONG: case VTK_UNSIGNED___INT64: case VTK_UNSIGNED_LONG: case VTK_UNSIGNED_LONG_LONG: needTypeConversion=1; // to float if(this->Supports_GL_ARB_texture_float) { internalFormat=vtkgl::INTENSITY16F_ARB; } else { internalFormat=GL_INTENSITY16; } format=GL_RED; type=GL_FLOAT; shift=-tableRange[0]; scale=1/(tableRange[1]-tableRange[0]); sliceArray=vtkFloatArray::New(); break; case VTK_SHORT: internalFormat=GL_INTENSITY16; format=GL_RED; type=GL_SHORT; shift=-(2*tableRange[0]+1)/VTK_UNSIGNED_SHORT_MAX; scale=VTK_SHORT_MAX/(tableRange[1]-tableRange[0]); break; case VTK_STRING: // not supported assert("check: impossible case" && 0); break; case VTK_UNSIGNED_SHORT: internalFormat=GL_INTENSITY16; format=GL_RED; type=GL_UNSIGNED_SHORT; shift=-tableRange[0]/VTK_UNSIGNED_SHORT_MAX; scale= VTK_UNSIGNED_SHORT_MAX/(tableRange[1]-tableRange[0]); break; case VTK_UNSIGNED_INT: internalFormat=GL_INTENSITY16; format=GL_RED; type=GL_UNSIGNED_INT; shift=-tableRange[0]/VTK_UNSIGNED_INT_MAX; scale=VTK_UNSIGNED_INT_MAX/(tableRange[1]-tableRange[0]); break; default: assert("check: impossible case" && 0); break; } } // Enough memory? int textureSize[3]; int i=0; while(i<3) { textureSize[i]=textureExtent[2*i+1]-textureExtent[2*i]+1; ++i; } GLint width; glGetIntegerv(vtkgl::MAX_3D_TEXTURE_SIZE,&width); this->Loaded=textureSize[0]<=width && textureSize[1]<=width && textureSize[2]<=width; if(this->Loaded) { // so far, so good. the texture size is theorically small enough // for OpenGL vtkgl::TexImage3D(vtkgl::PROXY_TEXTURE_3D,0,internalFormat, textureSize[0],textureSize[1],textureSize[2],0, format,type,0); glGetTexLevelParameteriv(vtkgl::PROXY_TEXTURE_3D,0,GL_TEXTURE_WIDTH, &width); this->Loaded=width!=0; if(this->Loaded) { // so far, so good but some cards always succeed with a proxy texture // let's try to actually allocate.. vtkgl::TexImage3D(vtkgl::TEXTURE_3D,0,internalFormat,textureSize[0], textureSize[1],textureSize[2],0,format,type,0); GLenum errorCode=glGetError(); this->Loaded=errorCode!=GL_OUT_OF_MEMORY; if(this->Loaded) { // so far, so good, actual allocation succeeded. if(errorCode!=GL_NO_ERROR) { cout<<"after try to load the texture"; cout<<" ERROR (x"<(errorCode)); cout<Loaded=textureSize[0]*textureSize[1]* textureSize[2]*vtkAbstractArray::GetDataTypeSize(scalarType)* scalars->GetNumberOfComponents()<=maxMemoryInBytes; if(this->Loaded) { // OK, we consider the allocation above succeeded... // If it actually didn't the only to fix it for the user // is to decrease the value of this->MaxMemoryInBytes. // enough memory! We can load the scalars! double bias=shift*scale; // we don't clamp to edge because for the computation of the // gradient on the border we need some external value. glTexParameterf(vtkgl::TEXTURE_3D,vtkgl::TEXTURE_WRAP_R,vtkgl::CLAMP_TO_EDGE); glTexParameterf(vtkgl::TEXTURE_3D,GL_TEXTURE_WRAP_S,vtkgl::CLAMP_TO_EDGE); glTexParameterf(vtkgl::TEXTURE_3D,GL_TEXTURE_WRAP_T,vtkgl::CLAMP_TO_EDGE); GLfloat borderColor[4]={0.0,0.0,0.0,0.0}; glTexParameterfv(vtkgl::TEXTURE_3D,GL_TEXTURE_BORDER_COLOR, borderColor); if(needTypeConversion) { // Convert and send to the GPU, z-slice by z-slice. // Allocate memory on the GPU (NULL data pointer with the right // dimensions) // Here we are assuming that GL_ARB_texture_non_power_of_two is // available glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); // memory allocation is already done. // Send the slices: // allocate CPU memory for a slice. sliceArray->SetNumberOfComponents(1); // FB TODO CHECK THAT sliceArray->SetNumberOfTuples(textureSize[0]*textureSize[1]); void *slicePtr=sliceArray->GetVoidPointer(0); int k=0; int kInc=(dim[0]-cellFlag)*(dim[1]-cellFlag); int kOffset=(textureExtent[4]*(dim[1]-cellFlag) +textureExtent[2])*(dim[0]-cellFlag) +textureExtent[0]; while(kSetTuple1(jDestOffset+i, (scalars->GetTuple1(kOffset+jOffset +i) +shift)*scale); ++i; } ++j; jOffset+=dim[0]-cellFlag; jDestOffset+=textureSize[0]; } // Here we are assuming that GL_ARB_texture_non_power_of_two is // available vtkgl::TexSubImage3D(vtkgl::TEXTURE_3D, 0, 0,0,k, textureSize[0],textureSize[1], 1, // depth is 1, not 0! format,type, slicePtr); ++k; kOffset+=kInc; } sliceArray->Delete(); } else { // One chunk of data to the GPU. // It works for the whole volume or for a subvolume. // Here we are assuming that GL_ARB_texture_non_power_of_two is // available // make sure any previous OpenGL call is executed and will not // be disturbed by our PixelTransfer value glFinish(); glPixelTransferf(GL_RED_SCALE,static_cast(scale)); glPixelTransferf(GL_RED_BIAS,static_cast(bias)); glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); if(!(textureExtent[1]-textureExtent[0]+cellFlag==dim[0])) { glPixelStorei(GL_UNPACK_ROW_LENGTH,dim[0]-cellFlag); } if(!(textureExtent[3]-textureExtent[2]+cellFlag==dim[1])) { glPixelStorei(vtkgl::UNPACK_IMAGE_HEIGHT_EXT, dim[1]-cellFlag); } void *dataPtr=scalars->GetVoidPointer( ((textureExtent[4]*(dim[1]-cellFlag)+textureExtent[2]) *(dim[0]-cellFlag)+textureExtent[0]) *scalars->GetNumberOfComponents()); if(1) // !this->SupportsPixelBufferObjects) { vtkgl::TexImage3D(vtkgl::TEXTURE_3D, 0, internalFormat, textureSize[0],textureSize[1],textureSize[2], 0,format,type,dataPtr); } else { GLuint pbo=0; vtkgl::GenBuffers(1,&pbo); vtkMitkOpenGLGPUVolumeRayCastMapper::PrintError("genbuffer"); vtkgl::BindBuffer(vtkgl::PIXEL_UNPACK_BUFFER,pbo); vtkMitkOpenGLGPUVolumeRayCastMapper::PrintError("binbuffer"); vtkgl::GLsizeiptr texSize= textureSize[0]*textureSize[1]*textureSize[2]* vtkAbstractArray::GetDataTypeSize(scalarType)* scalars->GetNumberOfComponents(); vtkgl::BufferData(vtkgl::PIXEL_UNPACK_BUFFER,texSize,dataPtr, vtkgl::STREAM_DRAW); vtkMitkOpenGLGPUVolumeRayCastMapper::PrintError("bufferdata"); vtkgl::TexImage3D(vtkgl::TEXTURE_3D, 0, internalFormat, textureSize[0],textureSize[1],textureSize[2], 0,format,type,0); vtkMitkOpenGLGPUVolumeRayCastMapper::PrintError("teximage3d"); vtkgl::BindBuffer(vtkgl::PIXEL_UNPACK_BUFFER,0); vtkMitkOpenGLGPUVolumeRayCastMapper::PrintError("bindbuffer to 0"); vtkgl::DeleteBuffers(1,&pbo); } vtkMitkOpenGLGPUVolumeRayCastMapper::PrintError("3d texture is too large2"); // make sure TexImage3D is executed with our PixelTransfer mode glFinish(); // Restore the default values. glPixelStorei(GL_UNPACK_ROW_LENGTH,0); glPixelStorei(vtkgl::UNPACK_IMAGE_HEIGHT_EXT,0); glPixelTransferf(GL_RED_SCALE,1.0); glPixelTransferf(GL_RED_BIAS,0.0); } this->LoadedCellFlag=cellFlag; i=0; while(i<6) { this->LoadedExtent[i]=textureExtent[i]; ++i; } double spacing[3]; double origin[3]; input->GetSpacing(spacing); input->GetOrigin(origin); int swapBounds[3]; swapBounds[0]=(spacing[0]<0); swapBounds[1]=(spacing[1]<0); swapBounds[2]=(spacing[2]<0); if(!this->LoadedCellFlag) // loaded extents represent points { // slabsPoints[i]=(slabsDataSet[i] - origin[i/2]) / spacing[i/2]; // in general, x=o+i*spacing. // if spacing is positive min extent match the min of the // bounding box // and the max extent match the max of the bounding box // if spacing is negative min extent match the max of the // bounding box // and the max extent match the min of the bounding box // if spacing is negative, we may have to rethink the equation // between real point and texture coordinate... this->LoadedBounds[0]=origin[0]+ static_cast(this->LoadedExtent[0+swapBounds[0]])*spacing[0]; this->LoadedBounds[2]=origin[1]+ static_cast(this->LoadedExtent[2+swapBounds[1]])*spacing[1]; this->LoadedBounds[4]=origin[2]+ static_cast(this->LoadedExtent[4+swapBounds[2]])*spacing[2]; this->LoadedBounds[1]=origin[0]+ static_cast(this->LoadedExtent[1-swapBounds[0]])*spacing[0]; this->LoadedBounds[3]=origin[1]+ static_cast(this->LoadedExtent[3-swapBounds[1]])*spacing[1]; this->LoadedBounds[5]=origin[2]+ static_cast(this->LoadedExtent[5-swapBounds[2]])*spacing[2]; } else // loaded extents represent cells { int wholeTextureExtent[6]; input->GetExtent(wholeTextureExtent); i=1; while(i<6) { wholeTextureExtent[i]--; i+=2; } i=0; while(i<3) { if(this->LoadedExtent[2*i]==wholeTextureExtent[2*i]) { this->LoadedBounds[2*i+swapBounds[i]]=origin[i]; } else { this->LoadedBounds[2*i+swapBounds[i]]=origin[i]+ (static_cast(this->LoadedExtent[2*i])+0.5)*spacing[i]; } if(this->LoadedExtent[2*i+1]==wholeTextureExtent[2*i+1]) { this->LoadedBounds[2*i+1-swapBounds[i]]=origin[i]+ (static_cast(this->LoadedExtent[2*i+1])+1.0)*spacing[i]; } else { this->LoadedBounds[2*i+1-swapBounds[i]]=origin[i]+ (static_cast(this->LoadedExtent[2*i+1])+0.5)*spacing[i]; } ++i; } } this->LoadedTableRange[0]=tableRange[0]; this->LoadedTableRange[1]=tableRange[1]; modified=true; } // if enough memory else { } } //load fail with out of memory else { } } // proxy ok else { // proxy failed } } else { // out of therical limitationa } } // if obsolete if(this->Loaded && (needUpdate || modified || linearInterpolation!=this->LinearInterpolation)) { this->LinearInterpolation=linearInterpolation; if(this->LinearInterpolation) { glTexParameterf(vtkgl::TEXTURE_3D,GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(vtkgl::TEXTURE_3D,GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameterf(vtkgl::TEXTURE_3D,GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameterf(vtkgl::TEXTURE_3D,GL_TEXTURE_MAG_FILTER, GL_NEAREST ); } modified=true; } if(modified) { this->BuildTime.Modified(); } } double *GetLoadedBounds() { assert("pre: loaded" && this->Loaded); return this->LoadedBounds; } vtkIdType *GetLoadedExtent() { assert("pre: loaded" && this->Loaded); return this->LoadedExtent; } int GetLoadedCellFlag() { assert("pre: loaded" && this->Loaded); return this->LoadedCellFlag; } bool IsLoaded() { return this->Loaded; } bool GetSupports_GL_ARB_texture_float() { return this->Supports_GL_ARB_texture_float; } void SetSupports_GL_ARB_texture_float(bool value) { this->Supports_GL_ARB_texture_float=value; } protected: GLuint TextureId; vtkTimeStamp BuildTime; double LoadedBounds[6]; vtkIdType LoadedExtent[6]; int LoadedCellFlag; bool Loaded; bool LinearInterpolation; bool Supports_GL_ARB_texture_float; double LoadedTableRange[2]; }; //----------------------------------------------------------------------------- class vtkKWMask { public: vtkKWMask() { this->TextureId=0; this->Loaded=false; this->LoadedExtent[0]=VTK_INT_MAX; this->LoadedExtent[1]=VTK_INT_MIN; this->LoadedExtent[2]=VTK_INT_MAX; this->LoadedExtent[3]=VTK_INT_MIN; this->LoadedExtent[4]=VTK_INT_MAX; this->LoadedExtent[5]=VTK_INT_MIN; } ~vtkKWMask() { if(this->TextureId!=0) { glDeleteTextures(1,&this->TextureId); this->TextureId=0; } } vtkTimeStamp GetBuildTime() { return this->BuildTime; } // \pre vtkgl::ActiveTexture(vtkgl::TEXTURE7) has to be called first. void Bind() { assert("pre: uptodate" && this->Loaded); glBindTexture(vtkgl::TEXTURE_3D,this->TextureId); } // \pre vtkgl::ActiveTexture(vtkgl::TEXTURE7) has to be called first. void Update(vtkImageData *input, int cellFlag, int textureExtent[6], int scalarMode, int arrayAccessMode, int arrayId, const char *arrayName, int maxMemoryInBytes) { bool needUpdate=false; bool modified=false; if(this->TextureId==0) { glGenTextures(1,&this->TextureId); needUpdate=true; } glBindTexture(vtkgl::TEXTURE_3D,this->TextureId); int obsolete=needUpdate || !this->Loaded || input->GetMTime()>this->BuildTime; if(!obsolete) { obsolete=cellFlag!=this->LoadedCellFlag; int i=0; while(!obsolete && i<6) { obsolete=obsolete || this->LoadedExtent[i]>textureExtent[i]; ++i; obsolete=obsolete || this->LoadedExtent[i]Loaded=false; int dim[3]; input->GetDimensions(dim); vtkDataArray *scalars= vtkAbstractMapper::GetScalars(input,scalarMode,arrayAccessMode, arrayId,arrayName, this->LoadedCellFlag); // DONT USE GetScalarType() or GetNumberOfScalarComponents() on // ImageData as it deals only with point data... int scalarType=scalars->GetDataType(); if(scalarType!=VTK_UNSIGNED_CHAR) { cout <<"mask should be VTK_UNSIGNED_CHAR." << endl; } if(scalars->GetNumberOfComponents()!=1) { cout <<"mask should be a one-component scalar field." << endl; } GLint internalFormat=GL_ALPHA8; GLenum format=GL_ALPHA; GLenum type=GL_UNSIGNED_BYTE; // Enough memory? int textureSize[3]; int i=0; while(i<3) { textureSize[i]=textureExtent[2*i+1]-textureExtent[2*i]+1; ++i; } GLint width; glGetIntegerv(vtkgl::MAX_3D_TEXTURE_SIZE,&width); this->Loaded=textureSize[0]<=width && textureSize[1]<=width && textureSize[2]<=width; if(this->Loaded) { // so far, so good. the texture size is theorically small enough // for OpenGL vtkgl::TexImage3D(vtkgl::PROXY_TEXTURE_3D,0,internalFormat, textureSize[0],textureSize[1],textureSize[2],0, format,type,0); glGetTexLevelParameteriv(vtkgl::PROXY_TEXTURE_3D,0,GL_TEXTURE_WIDTH, &width); this->Loaded=width!=0; if(this->Loaded) { // so far, so good but some cards always succeed with a proxy texture // let's try to actually allocate.. vtkgl::TexImage3D(vtkgl::TEXTURE_3D,0,internalFormat,textureSize[0], textureSize[1],textureSize[2],0,format,type,0); GLenum errorCode=glGetError(); this->Loaded=errorCode!=GL_OUT_OF_MEMORY; if(this->Loaded) { // so far, so good, actual allocation succeeded. if(errorCode!=GL_NO_ERROR) { cout<<"after try to load the texture"; cout<<" ERROR (x"<(errorCode)); cout<Loaded=textureSize[0]*textureSize[1]* textureSize[2]*vtkAbstractArray::GetDataTypeSize(scalarType)* scalars->GetNumberOfComponents()<=maxMemoryInBytes; if(this->Loaded) { // OK, we consider the allocation above succeeded... // If it actually didn't the only to fix it for the user // is to decrease the value of this->MaxMemoryInBytes. // enough memory! We can load the scalars! // we don't clamp to edge because for the computation of the // gradient on the border we need some external value. glTexParameterf(vtkgl::TEXTURE_3D,vtkgl::TEXTURE_WRAP_R,vtkgl::CLAMP_TO_EDGE); glTexParameterf(vtkgl::TEXTURE_3D,GL_TEXTURE_WRAP_S,vtkgl::CLAMP_TO_EDGE); glTexParameterf(vtkgl::TEXTURE_3D,GL_TEXTURE_WRAP_T,vtkgl::CLAMP_TO_EDGE); GLfloat borderColor[4]={0.0,0.0,0.0,0.0}; glTexParameterfv(vtkgl::TEXTURE_3D,GL_TEXTURE_BORDER_COLOR, borderColor); glPixelTransferf(GL_ALPHA_SCALE,1.0); glPixelTransferf(GL_ALPHA_BIAS,0.0); glPixelStorei(GL_UNPACK_ALIGNMENT,1); if(!(textureExtent[1]-textureExtent[0]+cellFlag==dim[0])) { glPixelStorei(GL_UNPACK_ROW_LENGTH,dim[0]-cellFlag); } if(!(textureExtent[3]-textureExtent[2]+cellFlag==dim[1])) { glPixelStorei(vtkgl::UNPACK_IMAGE_HEIGHT_EXT, dim[1]-cellFlag); } void *dataPtr=scalars->GetVoidPointer( ((textureExtent[4]*(dim[1]-cellFlag)+textureExtent[2]) *(dim[0]-cellFlag)+textureExtent[0]) *scalars->GetNumberOfComponents()); vtkgl::TexImage3D(vtkgl::TEXTURE_3D, 0, internalFormat, textureSize[0],textureSize[1],textureSize[2], 0,format,type,dataPtr); // Restore the default values. glPixelStorei(GL_UNPACK_ROW_LENGTH,0); glPixelStorei(vtkgl::UNPACK_IMAGE_HEIGHT_EXT,0); glPixelTransferf(GL_ALPHA_SCALE,1.0); glPixelTransferf(GL_ALPHA_BIAS,0.0); this->LoadedCellFlag=cellFlag; i=0; while(i<6) { this->LoadedExtent[i]=textureExtent[i]; ++i; } double spacing[3]; double origin[3]; input->GetSpacing(spacing); input->GetOrigin(origin); int swapBounds[3]; swapBounds[0]=(spacing[0]<0); swapBounds[1]=(spacing[1]<0); swapBounds[2]=(spacing[2]<0); if(!this->LoadedCellFlag) // loaded extents represent points { // slabsPoints[i]=(slabsDataSet[i] - origin[i/2]) / spacing[i/2]; // in general, x=o+i*spacing. // if spacing is positive min extent match the min of the // bounding box // and the max extent match the max of the bounding box // if spacing is negative min extent match the max of the // bounding box // and the max extent match the min of the bounding box // if spacing is negative, we may have to rethink the equation // between real point and texture coordinate... this->LoadedBounds[0]=origin[0]+ static_cast(this->LoadedExtent[0+swapBounds[0]])*spacing[0]; this->LoadedBounds[2]=origin[1]+ static_cast(this->LoadedExtent[2+swapBounds[1]])*spacing[1]; this->LoadedBounds[4]=origin[2]+ static_cast(this->LoadedExtent[4+swapBounds[2]])*spacing[2]; this->LoadedBounds[1]=origin[0]+ static_cast(this->LoadedExtent[1-swapBounds[0]])*spacing[0]; this->LoadedBounds[3]=origin[1]+ static_cast(this->LoadedExtent[3-swapBounds[1]])*spacing[1]; this->LoadedBounds[5]=origin[2]+ static_cast(this->LoadedExtent[5-swapBounds[2]])*spacing[2]; } else // loaded extents represent cells { int wholeTextureExtent[6]; input->GetExtent(wholeTextureExtent); i=1; while(i<6) { wholeTextureExtent[i]--; i+=2; } i=0; while(i<3) { if(this->LoadedExtent[2*i]==wholeTextureExtent[2*i]) { this->LoadedBounds[2*i+swapBounds[i]]=origin[i]; } else { this->LoadedBounds[2*i+swapBounds[i]]=origin[i]+ (static_cast(this->LoadedExtent[2*i])+0.5)*spacing[i]; } if(this->LoadedExtent[2*i+1]==wholeTextureExtent[2*i+1]) { this->LoadedBounds[2*i+1-swapBounds[i]]=origin[i]+ (static_cast(this->LoadedExtent[2*i+1])+1.0)*spacing[i]; } else { this->LoadedBounds[2*i+1-swapBounds[i]]=origin[i]+ (static_cast(this->LoadedExtent[2*i+1])+0.5)*spacing[i]; } ++i; } } modified=true; } // if enough memory else { } } //load fail with out of memory else { } } // proxy ok else { // proxy failed } } else { // out of therical limitationa } } // if obsolete if(this->Loaded && (needUpdate || modified)) { glTexParameterf(vtkgl::TEXTURE_3D,GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameterf(vtkgl::TEXTURE_3D,GL_TEXTURE_MAG_FILTER, GL_NEAREST ); modified=true; } if(modified) { this->BuildTime.Modified(); } } double *GetLoadedBounds() { assert("pre: loaded" && this->Loaded); return this->LoadedBounds; } vtkIdType *GetLoadedExtent() { assert("pre: loaded" && this->Loaded); return this->LoadedExtent; } int GetLoadedCellFlag() { assert("pre: loaded" && this->Loaded); return this->LoadedCellFlag; } bool IsLoaded() { return this->Loaded; } protected: GLuint TextureId; vtkTimeStamp BuildTime; double LoadedBounds[6]; vtkIdType LoadedExtent[6]; int LoadedCellFlag; bool Loaded; }; //----------------------------------------------------------------------------- // Display the status of the current framebuffer on the standard output. //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::CheckFrameBufferStatus() { GLenum status; status = vtkgl::CheckFramebufferStatusEXT(vtkgl::FRAMEBUFFER_EXT); switch(status) { case 0: cout << "call to vtkgl::CheckFramebufferStatusEXT generates an error." << endl; break; case vtkgl::FRAMEBUFFER_COMPLETE_EXT: break; case vtkgl::FRAMEBUFFER_UNSUPPORTED_EXT: cout << "framebuffer is unsupported" << endl; break; case vtkgl::FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: cout << "framebuffer has an attachment error"<DisplayFrameBufferAttachments(); // this->DisplayReadAndDrawBuffers(); } //----------------------------------------------------------------------------- vtkStdString vtkMitkOpenGLGPUVolumeRayCastMapper::BufferToString(int buffer) { vtkStdString result; vtksys_ios::ostringstream ost; GLint size; GLint b=static_cast(buffer); switch(b) { case GL_NONE: ost << "GL_NONE"; break; case GL_FRONT_LEFT: ost << "GL_FRONT_LEFT"; break; case GL_FRONT_RIGHT: ost << "GL_FRONT_RIGHT"; break; case GL_BACK_LEFT: ost << "GL_BACK_LEFT"; break; case GL_BACK_RIGHT: ost << "GL_BACK_RIGHT"; break; case GL_FRONT: ost << "GL_FRONT"; break; case GL_BACK: ost << "GL_BACK"; break; case GL_LEFT: ost << "GL_LEFT"; break; case GL_RIGHT: ost << "GL_RIGHT"; break; case GL_FRONT_AND_BACK: ost << "GL_FRONT_AND_BACK"; break; default: glGetIntegerv(GL_AUX_BUFFERS,&size); if(buffer>=GL_AUX0 && buffer<(GL_AUX0+size)) { ost << "GL_AUX" << (buffer-GL_AUX0); } else { glGetIntegerv(vtkgl::MAX_COLOR_ATTACHMENTS_EXT,&size); if(static_cast(buffer)>=vtkgl::COLOR_ATTACHMENT0_EXT && static_cast(buffer)< (vtkgl::COLOR_ATTACHMENT0_EXT+static_cast(size))) { ost << "GL_COLOR_ATTACHMENT" << (static_cast(buffer)-vtkgl::COLOR_ATTACHMENT0_EXT) << "_EXT"; } else { ost << "unknown color buffer type=0x"<(value); vtkStdString s; GLenum i=0; while(iBufferToString(static_cast(value)); cout << "draw buffer " << i << "=" << s << endl; ++i; } glGetIntegerv(GL_READ_BUFFER,&value); s=this->BufferToString(static_cast(value)); cout << "read buffer=" << s << endl; } // ---------------------------------------------------------------------------- // Description: // Display all the attachments of the current framebuffer object. // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::DisplayFrameBufferAttachments() { GLint framebufferBinding; glGetIntegerv(vtkgl::FRAMEBUFFER_BINDING_EXT,&framebufferBinding); this->PrintError("after getting FRAMEBUFFER_BINDING_EXT"); if(framebufferBinding==0) { cout<<"Current framebuffer is bind to the system one"<(value); this->PrintError("after getting MAX_COLOR_ATTACHMENTS_EXT"); GLenum i=0; while(iDisplayFrameBufferAttachment(vtkgl::COLOR_ATTACHMENT0_EXT+i); ++i; } cout<<"depth attachement :"<DisplayFrameBufferAttachment(vtkgl::DEPTH_ATTACHMENT_EXT); cout<<"stencil attachement :"<DisplayFrameBufferAttachment(vtkgl::STENCIL_ATTACHMENT_EXT); } } // ---------------------------------------------------------------------------- // Description: // Display a given attachment for the current framebuffer object. //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::DisplayFrameBufferAttachment( unsigned int uattachment) { GLenum attachment=static_cast(uattachment); GLint params; vtkgl::GetFramebufferAttachmentParameterivEXT( vtkgl::FRAMEBUFFER_EXT,attachment, vtkgl::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT,¶ms); this->PrintError("after getting FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT"); switch(params) { case GL_NONE: cout<<" this attachment is empty"<PrintError("after getting FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT"); cout<<" this attachment is a texture with name: "<PrintError( "after getting FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT"); cout<<" its mipmap level is: "<PrintError( "after getting FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT"); if(params==0) { cout<<" this is not a cube map texture."<PrintError( "after getting FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT"); if(params==0) { cout<<" this is not 3D texture."<PrintError("after getting FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT"); cout<<" this attachment is a renderbuffer with name: "<(params)); this->PrintError( "after getting binding the current RENDERBUFFER_EXT to params"); vtkgl::GetRenderbufferParameterivEXT(vtkgl::RENDERBUFFER_EXT, vtkgl::RENDERBUFFER_WIDTH_EXT, ¶ms); this->PrintError("after getting RENDERBUFFER_WIDTH_EXT"); cout<<" renderbuffer width="<PrintError("after getting RENDERBUFFER_HEIGHT_EXT"); cout<<" renderbuffer height="<PrintError("after getting RENDERBUFFER_INTERNAL_FORMAT_EXT"); cout<<" renderbuffer internal format=0x"<< hex<PrintError("after getting RENDERBUFFER_RED_SIZE_EXT"); cout<<" renderbuffer actual resolution for the red component="<PrintError("after getting RENDERBUFFER_GREEN_SIZE_EXT"); cout<<" renderbuffer actual resolution for the green component="<PrintError("after getting RENDERBUFFER_BLUE_SIZE_EXT"); cout<<" renderbuffer actual resolution for the blue component="<PrintError("after getting RENDERBUFFER_ALPHA_SIZE_EXT"); cout<<" renderbuffer actual resolution for the alpha component="<PrintError("after getting RENDERBUFFER_DEPTH_SIZE_EXT"); cout<<" renderbuffer actual resolution for the depth component="<PrintError("after getting RENDERBUFFER_STENCIL_SIZE_EXT"); cout<<" renderbuffer actual resolution for the stencil component=" <(errorCode)) { case GL_NO_ERROR: result="No error"; break; case GL_INVALID_ENUM: result="Invalid enum"; break; case GL_INVALID_VALUE: result="Invalid value"; break; case GL_INVALID_OPERATION: result="Invalid operation"; break; case GL_STACK_OVERFLOW: result="stack overflow"; break; case GL_STACK_UNDERFLOW: result="stack underflow"; break; case GL_OUT_OF_MEMORY: result="out of memory"; break; case vtkgl::TABLE_TOO_LARGE: // GL_ARB_imaging result="Table too large"; break; case vtkgl::INVALID_FRAMEBUFFER_OPERATION_EXT: // GL_EXT_framebuffer_object, 310 result="invalid framebuffer operation ext"; break; case vtkgl::TEXTURE_TOO_LARGE_EXT: // GL_EXT_texture result="Texture too large"; break; default: result="unknown error"; } assert("post: result_exists" && result!=0); return result; } //----------------------------------------------------------------------------- // Display headerMessage on the standard output and the last OpenGL error // message if any. //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::PrintError(const char *headerMessage) { GLenum errorCode=glGetError(); if(errorCode!=GL_NO_ERROR) { if ( headerMessage ) { cout<(errorCode)); cout<UnsupportedRequiredExtensions=0; this->OpenGLObjectsCreated=0; this->LoadExtensionsSucceeded=0; this->NumberOfFrameBuffers=0; this->m_BindMax = false; // up to 2 frame buffer 2D textures (left/right) // 1 dataset 3D texture // 1 colormap 1D texture // 1 opacitymap 1d texture // 1 grabbed depth buffer 2d texture int i=0; while(iTextureObjects[i]=0; ++i; } this->DepthRenderBufferObject=0; this->FrameBufferObject=0; for ( int j = 0; j < 8; j++ ) { for (i = 0; i < 3; i++ ) { this->BoundingBox[j][i] = 0.0; } } this->LastSize[0]=0; this->LastSize[1]=0; this->ReductionFactor = 1.0; this->Supports_GL_ARB_texture_float=0; this->SupportsPixelBufferObjects=0; i=0; while(i<3) { this->TempMatrix[i]=vtkMatrix4x4::New(); ++i; } this->ErrorLine=0; this->ErrorColumn=0; this->ErrorString=0; this->LastParallelProjection= vtkMitkOpenGLGPUVolumeRayCastMapperProjectionNotInitialized; this->LastRayCastMethod= vtkMitkOpenGLGPUVolumeRayCastMapperMethodNotInitialized; this->LastCroppingMode= vtkMitkOpenGLGPUVolumeRayCastMapperCroppingNotInitialized; this->LastComponent= vtkMitkOpenGLGPUVolumeRayCastMapperComponentNotInitialized; this->LastShade=vtkMitkOpenGLGPUVolumeRayCastMapperShadeNotInitialized; this->ClippedBoundingBox = NULL; this->SmallInput = NULL; this->MaxValueFrameBuffer=0; this->MaxValueFrameBuffer2=0; this->ReducedSize[0]=0; this->ReducedSize[1]=0; this->NumberOfCroppingRegions=0; this->PolyDataBoundingBox=0; this->Planes=0; this->NearPlane=0; this->Clip=0; this->Densify=0; this->InvVolumeMatrix=vtkMatrix4x4::New(); this->ScaleBiasProgramShader=0; this->UFrameBufferTexture=-1; this->UScale=-1; this->UBias=-1; this->SavedFrameBuffer=0; this->BoxSource=0; this->NoiseTexture=0; this->NoiseTextureSize=0; this->NoiseTextureId=0; this->IgnoreSampleDistancePerPixel=true; this->ScalarsTextures=new vtkMapDataArrayTextureId; this->MaskTextures=new vtkMapMaskTextureId; this->RGBTable=0; this->Mask1RGBTable=0; this->Mask2RGBTable=0; this->OpacityTables=0; this->CurrentScalar=0; this->CurrentMask=0; this->ActualSampleDistance=1.0; this->LastProgressEventTime=0.0; // date in seconds this->PreserveOrientation=true; } //----------------------------------------------------------------------------- // Destruct a vtkMitkOpenGLGPUVolumeRayCastMapper - clean up any memory used //----------------------------------------------------------------------------- vtkMitkOpenGLGPUVolumeRayCastMapper::~vtkMitkOpenGLGPUVolumeRayCastMapper() { if(this->UnsupportedRequiredExtensions!=0) { delete this->UnsupportedRequiredExtensions; this->UnsupportedRequiredExtensions=0; } int i=0; while(i<3) { this->TempMatrix[i]->Delete(); this->TempMatrix[i]=0; ++i; } if(this->ErrorString!=0) { delete[] this->ErrorString; this->ErrorString=0; } if ( this->SmallInput ) { this->SmallInput->UnRegister(this); } if(this->PolyDataBoundingBox!=0) { this->PolyDataBoundingBox->UnRegister(this); this->PolyDataBoundingBox=0; } if(this->Planes!=0) { this->Planes->UnRegister(this); this->Planes=0; } if(this->NearPlane!=0) { this->NearPlane->UnRegister(this); this->NearPlane=0; } if(this->Clip!=0) { this->Clip->UnRegister(this); this->Clip=0; } if(this->Densify!=0) { this->Densify->UnRegister(this); this->Densify=0; } if(this->BoxSource!=0) { this->BoxSource->UnRegister(this); this->BoxSource=0; } this->InvVolumeMatrix->UnRegister(this); this->InvVolumeMatrix=0; if(this->NoiseTexture!=0) { delete[] this->NoiseTexture; this->NoiseTexture=0; this->NoiseTextureSize=0; } if(this->ScalarsTextures!=0) { delete this->ScalarsTextures; this->ScalarsTextures=0; } if(this->MaskTextures!=0) { delete this->MaskTextures; this->MaskTextures=0; } } //----------------------------------------------------------------------------- // 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. // //----------------------------------------------------------------------------- int vtkMitkOpenGLGPUVolumeRayCastMapper::IsRenderSupported( vtkRenderWindow *window, vtkVolumeProperty *vtkNotUsed(property)) { window->MakeCurrent(); if(!this->LoadExtensionsSucceeded) { this->LoadExtensions(window); } if(!this->LoadExtensionsSucceeded) { vtkDebugMacro( "The following OpenGL extensions are required but not supported: " << (this->UnsupportedRequiredExtensions->Stream.str()).c_str()); return 0; } return 1; } //----------------------------------------------------------------------------- // Return if the required OpenGL extension `extensionName' is supported. // If not, its name is added to the string of unsupported but required // extensions. // \pre extensions_exist: extensions!=0 // \pre extensionName_exists: extensionName!=0 //----------------------------------------------------------------------------- int vtkMitkOpenGLGPUVolumeRayCastMapper::TestRequiredExtension( vtkOpenGLExtensionManager *extensions, const char *extensionName) { assert("pre: extensions_exist" && extensions!=0); assert("pre: extensionName_exists" && extensionName!=0); int result=extensions->ExtensionSupported(extensionName); if(!result) { if(this->LoadExtensionsSucceeded) { this->UnsupportedRequiredExtensions->Stream<LoadExtensionsSucceeded=0; } else { this->UnsupportedRequiredExtensions->Stream<<", "<LoadExtensionsSucceeded will be set to 0 or 1 // - this->UnsupportedRequiredExtensions will have a message indicating // any failure codes //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::LoadExtensions( vtkRenderWindow *window) { // We may already have a string stream for the unsupported extensions // from the last time this method was called. If so, delete it. if(this->UnsupportedRequiredExtensions!=0) { delete this->UnsupportedRequiredExtensions; } // Create a string stream to hold the unsupported extensions so we can // report something meaningful back this->UnsupportedRequiredExtensions = new vtkUnsupportedRequiredExtensionsStringStream; // It does not work on Apple OS X Snow Leopard with nVidia. // There is a bug in the OpenGL driver with an error in the // Cg compiler about an infinite loop. #ifdef __APPLE__ this->LoadExtensionsSucceeded=0; return; #endif // Assume success this->LoadExtensionsSucceeded=1; const char *gl_vendor=reinterpret_cast(glGetString(GL_VENDOR)); /* if(strstr(gl_vendor,"ATI")!=0) { this->LoadExtensionsSucceeded=0; return; }*/ const char *gl_version=reinterpret_cast(glGetString(GL_VERSION)); if(strstr(gl_version,"Mesa")!=0) { // - GL_VENDOR cannot be used because it can be "Brian Paul" or // "Mesa project" // - GL_RENDERER cannot be used because it can be "Software Rasterizer" or // "Mesa X11" // - GL_VERSION is more robust. It has things like "2.0 Mesa 7.0.4" or // "2.1 Mesa 7.2" or "2.1 Mesa 7.3-devel" // Mesa does not work with multiple draw buffers: // "framebuffer has bad draw buffer" // "render clipped 1 ERROR (x506) invalid framebuffer operation ext" this->LoadExtensionsSucceeded=0; return; } // Create an extension manager vtkOpenGLExtensionManager *extensions=vtkOpenGLExtensionManager::New(); extensions->SetRenderWindow(window); // GL_ARB_draw_buffers requires OpenGL 1.3, so we must have OpenGL 1.3 // We don't need to check for some extensions that become part of OpenGL // core after 1.3. Among them: // - texture_3d is in core OpenGL since 1.2 // - texture_edge_clamp is in core OpenGL since 1.2 // (GL_SGIS_texture_edge_clamp or GL_EXT_texture_edge_clamp (nVidia) ) // - multitexture is in core OpenGL since 1.3 int supports_GL_1_3=extensions->ExtensionSupported("GL_VERSION_1_3"); int supports_GL_2_0=0; // No 1.3 support - give up if(!supports_GL_1_3) { this->LoadExtensionsSucceeded=0; this->UnsupportedRequiredExtensions->Stream<< " OpenGL 1.3 is required but not supported"; extensions->Delete(); return; } // Check for 2.0 support supports_GL_2_0=extensions->ExtensionSupported("GL_VERSION_2_0"); // Some extensions that are supported in 2.0, but if we don't // have 2.0 we'll need to check further int supports_shading_language_100 = 1; int supports_shader_objects = 1; int supports_fragment_shader = 1; int supports_texture_non_power_of_two = 1; int supports_draw_buffers = 1; if(!supports_GL_2_0) { supports_shading_language_100= extensions->ExtensionSupported("GL_ARB_shading_language_100"); supports_shader_objects= extensions->ExtensionSupported("GL_ARB_shader_objects"); supports_fragment_shader= extensions->ExtensionSupported("GL_ARB_fragment_shader"); supports_texture_non_power_of_two= extensions->ExtensionSupported("GL_ARB_texture_non_power_of_two"); supports_draw_buffers= extensions->ExtensionSupported("GL_ARB_draw_buffers"); } // We have to check for framebuffer objects int supports_GL_EXT_framebuffer_object= extensions->ExtensionSupported("GL_EXT_framebuffer_object" ); // Find out if we have OpenGL 1.4 support int supports_GL_1_4=extensions->ExtensionSupported("GL_VERSION_1_4"); // Find out if we have the depth texture ARB extension int supports_GL_ARB_depth_texture= extensions->ExtensionSupported("GL_ARB_depth_texture"); // Depth textures are support if we either have OpenGL 1.4 // or if the depth texture ARB extension is supported int supports_depth_texture = supports_GL_1_4 || supports_GL_ARB_depth_texture; // Now start adding messages to the UnsupportedRequiredExtensions string // Log message if shading language 100 is not supported if(!supports_shading_language_100) { this->UnsupportedRequiredExtensions->Stream<< " shading_language_100 (or OpenGL 2.0) is required but not supported"; this->LoadExtensionsSucceeded=0; } else { // We can query the GLSL version, we need >=1.20 const char *glsl_version= reinterpret_cast(glGetString(vtkgl::SHADING_LANGUAGE_VERSION)); int glslMajor, glslMinor; vtksys_ios::istringstream ist(glsl_version); ist >> glslMajor; char c; ist.get(c); // '.' ist >> glslMinor; //sscanf(version, "%d.%d", &glslMajor, &glslMinor); if(glslMajor<1 || (glslMajor==1 && glslMinor<20)) { this->LoadExtensionsSucceeded=0; } } // Log message if shader objects are not supported if(!supports_shader_objects) { this->UnsupportedRequiredExtensions->Stream<< " shader_objects (or OpenGL 2.0) is required but not supported"; this->LoadExtensionsSucceeded=0; } // Log message if fragment shaders are not supported if(!supports_fragment_shader) { this->UnsupportedRequiredExtensions->Stream<< " fragment_shader (or OpenGL 2.0) is required but not supported"; this->LoadExtensionsSucceeded=0; } // Log message if non power of two textures are not supported if(!supports_texture_non_power_of_two) { this->UnsupportedRequiredExtensions->Stream<< " texture_non_power_of_two (or OpenGL 2.0) is required but not " << "supported"; this->LoadExtensionsSucceeded=0; } // Log message if draw buffers are not supported if(!supports_draw_buffers) { this->UnsupportedRequiredExtensions->Stream<< " draw_buffers (or OpenGL 2.0) is required but not supported"; this->LoadExtensionsSucceeded=0; } // Log message if depth textures are not supported if(!supports_depth_texture) { this->UnsupportedRequiredExtensions->Stream<< " depth_texture (or OpenGL 1.4) is required but not supported"; this->LoadExtensionsSucceeded=0; } // Log message if framebuffer objects are not supported if(!supports_GL_EXT_framebuffer_object) { this->UnsupportedRequiredExtensions->Stream<< " framebuffer_object is required but not supported"; this->LoadExtensionsSucceeded=0; } // Have we succeeded so far? If not, just return. if(!this->LoadExtensionsSucceeded) { extensions->Delete(); return; } // Now start loading the extensions // First load all 1.2 and 1.3 extensions (we know we // support at least up to 1.3) extensions->LoadExtension("GL_VERSION_1_2"); extensions->LoadExtension("GL_VERSION_1_3"); // Load the 2.0 extensions if supported if(supports_GL_2_0) { extensions->LoadExtension("GL_VERSION_2_0"); } // Otherwise, we'll need to specifically load the // shader objects, fragment shader, and draw buffers // extensions else { extensions->LoadCorePromotedExtension("GL_ARB_shader_objects"); extensions->LoadCorePromotedExtension("GL_ARB_fragment_shader"); extensions->LoadCorePromotedExtension("GL_ARB_draw_buffers"); } // Load the framebuffer object extension extensions->LoadExtension("GL_EXT_framebuffer_object"); // Optional extension (does not fail if not present) // Load it if supported which will allow us to store // textures as floats this->Supports_GL_ARB_texture_float= extensions->ExtensionSupported("GL_ARB_texture_float" ); if(this->Supports_GL_ARB_texture_float) { extensions->LoadExtension( "GL_ARB_texture_float" ); } // Optional extension (does not fail if not present) // Used to minimize memory footprint when loading large 3D textures // of scalars. // VBO or 1.5 is required by PBO or 2.1 int supports_GL_1_5=extensions->ExtensionSupported("GL_VERSION_1_5"); int supports_vertex_buffer_object=supports_GL_1_5 || extensions->ExtensionSupported("GL_ARB_vertex_buffer_object"); int supports_GL_2_1=extensions->ExtensionSupported("GL_VERSION_2_1"); this->SupportsPixelBufferObjects=supports_vertex_buffer_object && (supports_GL_2_1 || extensions->ExtensionSupported("GL_ARB_pixel_buffer_object")); if(this->SupportsPixelBufferObjects) { if(supports_GL_1_5) { extensions->LoadExtension("GL_VERSION_1_5"); } else { extensions->LoadCorePromotedExtension("GL_ARB_vertex_buffer_object"); } if(supports_GL_2_1) { extensions->LoadExtension("GL_VERSION_2_1"); } else { extensions->LoadCorePromotedExtension("GL_ARB_pixel_buffer_object"); } } // Ultimate test. Some old cards support OpenGL 2.0 but not while // statements in a fragment shader (example: nVidia GeForce FX 5200) // It does not fail when compiling each shader source but at linking // stage because the parser underneath only check for syntax during // compilation and the actual native code generation happens during // the linking stage. this->CreateGLSLObjects(); this->NumberOfCroppingRegions=1; this->BuildProgram(1,vtkMitkOpenGLGPUVolumeRayCastMapperMethodComposite, vtkMitkOpenGLGPUVolumeRayCastMapperShadeNo, vtkMitkOpenGLGPUVolumeRayCastMapperComponentOne); GLint params; vtkgl::GetProgramiv(static_cast(this->ProgramShader), vtkgl::LINK_STATUS,¶ms); if(params==GL_FALSE) { this->LoadExtensionsSucceeded=0; this->UnsupportedRequiredExtensions->Stream<< " this card does not support while statements in fragment shaders."; } // FB debug this->CheckLinkage(this->ProgramShader); // Release GLSL Objects. GLuint programShader=static_cast(this->ProgramShader); vtkgl::DeleteProgram(programShader); this->LastParallelProjection= vtkMitkOpenGLGPUVolumeRayCastMapperProjectionNotInitialized; this->LastRayCastMethod= vtkMitkOpenGLGPUVolumeRayCastMapperMethodNotInitialized; this->LastCroppingMode= vtkMitkOpenGLGPUVolumeRayCastMapperCroppingNotInitialized; this->LastComponent= vtkMitkOpenGLGPUVolumeRayCastMapperComponentNotInitialized; this->LastShade=vtkMitkOpenGLGPUVolumeRayCastMapperShadeNotInitialized; extensions->Delete(); } //----------------------------------------------------------------------------- // Create GLSL OpenGL objects such fragment program Ids. //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::CreateGLSLObjects() { GLuint programShader; GLuint fragmentMainShader; programShader=vtkgl::CreateProgram(); fragmentMainShader=vtkgl::CreateShader(vtkgl::FRAGMENT_SHADER); vtkgl::AttachShader(programShader,fragmentMainShader); vtkgl::DeleteShader(fragmentMainShader); // reference counting vtkgl::ShaderSource( fragmentMainShader,1, const_cast(&vtkMitkGPUVolumeRayCastMapper_HeaderFS),0); vtkgl::CompileShader(fragmentMainShader); this->CheckCompilation(static_cast(fragmentMainShader)); GLuint fragmentProjectionShader; GLuint fragmentTraceShader; GLuint fragmentCroppingShader; GLuint fragmentComponentShader; GLuint fragmentShadeShader; fragmentProjectionShader=vtkgl::CreateShader(vtkgl::FRAGMENT_SHADER); vtkgl::AttachShader(programShader,fragmentProjectionShader); vtkgl::DeleteShader(fragmentProjectionShader); // reference counting fragmentTraceShader=vtkgl::CreateShader(vtkgl::FRAGMENT_SHADER); vtkgl::AttachShader(programShader,fragmentTraceShader); vtkgl::DeleteShader(fragmentTraceShader); // reference counting fragmentCroppingShader=vtkgl::CreateShader(vtkgl::FRAGMENT_SHADER); vtkgl::AttachShader(programShader,fragmentCroppingShader); vtkgl::DeleteShader(fragmentCroppingShader); // reference counting fragmentComponentShader=vtkgl::CreateShader(vtkgl::FRAGMENT_SHADER); // don't delete it, it is optionally attached. fragmentShadeShader=vtkgl::CreateShader(vtkgl::FRAGMENT_SHADER); // Save GL objects by static casting to standard C types. GL* types // are not allowed in VTK header files. this->ProgramShader=static_cast(programShader); this->FragmentMainShader=static_cast(fragmentMainShader); this->FragmentProjectionShader= static_cast(fragmentProjectionShader); this->FragmentTraceShader=static_cast(fragmentTraceShader); this->FragmentCroppingShader= static_cast(fragmentCroppingShader); this->FragmentComponentShader= static_cast(fragmentComponentShader); this->FragmentShadeShader= static_cast(fragmentShadeShader); } void vtkMitkOpenGLGPUVolumeRayCastMapper::BindFramebuffer() { vtkgl::FramebufferTexture2DEXT(vtkgl::FRAMEBUFFER_EXT, vtkgl::COLOR_ATTACHMENT0_EXT,GL_TEXTURE_2D, this->TextureObjects[vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront], 0); GLenum err = glGetError(); if(m_BindMax) { vtkgl::FramebufferTexture2DEXT(vtkgl::FRAMEBUFFER_EXT, vtkgl::COLOR_ATTACHMENT0_EXT+1, GL_TEXTURE_2D,this->MaxValueFrameBuffer,0); } } //----------------------------------------------------------------------------- // Create OpenGL objects such as textures, buffers and fragment program Ids. // It only registers Ids, there is no actual initialization of textures or // fragment program. // // Pre-conditions: // This method assumes that this->LoadedExtensionsSucceeded is 1. // // Post-conditions: // When this method completes successfully, this->OpenGLObjectsCreated // will be 1. //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::CreateOpenGLObjects() { // Do nothing if the OpenGL objects have already been created if ( this->OpenGLObjectsCreated ) { return; } // We need only two color buffers (ping-pong) this->NumberOfFrameBuffers=2; // TODO: clean this up! // 2*Frame buffers(2d textures)+colorMap (1d texture) +dataset (3d texture) // + opacitymap (1d texture) + grabbed depthMap (2d texture) // Frame buffers(2d textures)+colorMap (1d texture) +dataset (3d texture) // + opacity (1d texture)+grabbed depth buffer (2d texture) GLuint frameBufferObject; GLuint depthRenderBufferObject; GLuint textureObjects[vtkMitkOpenGLGPUVolumeRayCastMapperNumberOfTextureObjects]; // Create the various objects we will need - one frame buffer // which will contain a render buffer for depth and a texture // for color. vtkgl::GenFramebuffersEXT(1, &frameBufferObject); // color vtkgl::GenRenderbuffersEXT(1, &depthRenderBufferObject); // depth glGenTextures(vtkMitkOpenGLGPUVolumeRayCastMapperNumberOfTextureObjects,textureObjects); // Color buffers GLint value; glGetIntegerv(vtkgl::FRAMEBUFFER_BINDING_EXT,&value); GLuint savedFrameBuffer=static_cast(value); vtkgl::BindFramebufferEXT(vtkgl::FRAMEBUFFER_EXT,frameBufferObject); // Depth buffer vtkgl::BindRenderbufferEXT(vtkgl::RENDERBUFFER_EXT, depthRenderBufferObject); vtkgl::FramebufferRenderbufferEXT(vtkgl::FRAMEBUFFER_EXT, vtkgl::DEPTH_ATTACHMENT_EXT, vtkgl::RENDERBUFFER_EXT, depthRenderBufferObject); // Restore default frame buffer. vtkgl::BindFramebufferEXT(vtkgl::FRAMEBUFFER_EXT,savedFrameBuffer); this->CreateGLSLObjects(); // Save GL objects by static casting to standard C types. GL* types // are not allowed in VTK header files. this->FrameBufferObject=static_cast(frameBufferObject); this->DepthRenderBufferObject=static_cast(depthRenderBufferObject); int i=0; while(iTextureObjects[i]=static_cast(textureObjects[i]); ++i; } this->OpenGLObjectsCreated=1; } //----------------------------------------------------------------------------- // Check the compilation status of some fragment shader source. //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::CheckCompilation( unsigned int fragmentShader) { GLuint fs=static_cast(fragmentShader); GLint params; vtkgl::GetShaderiv(fs,vtkgl::COMPILE_STATUS,¶ms); if(params==GL_TRUE) { vtkDebugMacro(<<"shader source compiled successfully"); } else { vtkErrorMacro(<<"shader source compile error"); // include null terminator vtkgl::GetShaderiv(fs,vtkgl::INFO_LOG_LENGTH,¶ms); if(params>0) { char *buffer=new char[params]; vtkgl::GetShaderInfoLog(fs,params,0,buffer); vtkErrorMacro(<<"log: "<(programShader); // info about the list of active uniform variables vtkgl::GetProgramiv(prog,vtkgl::ACTIVE_UNIFORMS,¶ms); cout<<"There are "<(params); vtkgl::GetProgramiv(prog,vtkgl::OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB, ¶ms); GLint buffSize=params; char *name=new char[buffSize+1]; GLint size; GLenum type; while(i(programShader); vtkgl::GetProgramiv(prog,vtkgl::LINK_STATUS,¶ms); int status = 0; if(params==GL_TRUE) { status = 1; vtkDebugMacro(<<"program linked successfully"); } else { vtkErrorMacro(<<"program link error"); vtkgl::GetProgramiv(prog,vtkgl::INFO_LOG_LENGTH,¶ms); if(params>0) { char *buffer=new char[params]; vtkgl::GetProgramInfoLog(prog,params,0,buffer); vtkErrorMacro(<<"log: "<OpenGLObjectsCreated==0 //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::ReleaseGraphicsResources( vtkWindow *window) { if(this->OpenGLObjectsCreated) { window->MakeCurrent(); this->LastSize[0]=0; this->LastSize[1]=0; GLuint frameBufferObject=static_cast(this->FrameBufferObject); vtkgl::DeleteFramebuffersEXT(1,&frameBufferObject); GLuint depthRenderBufferObject= static_cast(this->DepthRenderBufferObject); vtkgl::DeleteRenderbuffersEXT(1,&depthRenderBufferObject); GLuint textureObjects[vtkMitkOpenGLGPUVolumeRayCastMapperNumberOfTextureObjects]; int i=0; while(i<(vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront+this->NumberOfFrameBuffers)) { textureObjects[i]=static_cast(this->TextureObjects[i]); ++i; } glDeleteTextures(vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront+this->NumberOfFrameBuffers,textureObjects); if(this->MaxValueFrameBuffer!=0) { GLuint maxValueFrameBuffer= static_cast(this->MaxValueFrameBuffer); glDeleteTextures(1,&maxValueFrameBuffer); this->MaxValueFrameBuffer=0; } if(this->MaxValueFrameBuffer2!=0) { GLuint maxValueFrameBuffer2= static_cast(this->MaxValueFrameBuffer2); glDeleteTextures(1,&maxValueFrameBuffer2); this->MaxValueFrameBuffer2=0; } GLuint programShader=static_cast(this->ProgramShader); vtkgl::DeleteProgram(programShader); this->ProgramShader=0; GLuint fragmentComponentShader= static_cast(this->FragmentComponentShader); vtkgl::DeleteShader(fragmentComponentShader); GLuint fragmentShadeShader= static_cast(this->FragmentShadeShader); vtkgl::DeleteShader(fragmentShadeShader); GLuint scaleBiasProgramShader= static_cast(this->ScaleBiasProgramShader); if(scaleBiasProgramShader!=0) { vtkgl::DeleteProgram(scaleBiasProgramShader); this->ScaleBiasProgramShader=0; } this->LastParallelProjection= vtkMitkOpenGLGPUVolumeRayCastMapperProjectionNotInitialized; this->LastRayCastMethod= vtkMitkOpenGLGPUVolumeRayCastMapperMethodNotInitialized; this->LastCroppingMode= vtkMitkOpenGLGPUVolumeRayCastMapperCroppingNotInitialized; this->LastComponent= vtkMitkOpenGLGPUVolumeRayCastMapperComponentNotInitialized; this->LastShade=vtkMitkOpenGLGPUVolumeRayCastMapperShadeNotInitialized; this->OpenGLObjectsCreated=0; } if(this->NoiseTextureId!=0) { window->MakeCurrent(); GLuint noiseTextureObjects=static_cast(this->NoiseTextureId); glDeleteTextures(1,&noiseTextureObjects); this->NoiseTextureId=0; } if(this->ScalarsTextures!=0) { if(!this->ScalarsTextures->Map.empty()) { vtkstd::map::iterator it=this->ScalarsTextures->Map.begin(); while(it!=this->ScalarsTextures->Map.end()) { vtkKWScalarField *texture=(*it).second; delete texture; ++it; } this->ScalarsTextures->Map.clear(); } } if(this->MaskTextures!=0) { if(!this->MaskTextures->Map.empty()) { vtkstd::map::iterator it=this->MaskTextures->Map.begin(); while(it!=this->MaskTextures->Map.end()) { vtkKWMask *texture=(*it).second; delete texture; ++it; } this->MaskTextures->Map.clear(); } } if(this->RGBTable!=0) { delete this->RGBTable; this->RGBTable=0; } if(this->Mask1RGBTable!=0) { delete this->Mask1RGBTable; this->Mask1RGBTable=0; } if(this->Mask2RGBTable!=0) { delete this->Mask2RGBTable; this->Mask2RGBTable=0; } if(this->OpacityTables!=0) { delete this->OpacityTables; this->OpacityTables=0; } } //----------------------------------------------------------------------------- // Allocate memory on the GPU for the framebuffers according to the size of // the window or reallocate if the size has changed. Return true if // allocation succeeded. // \pre ren_exists: ren!=0 // \pre opengl_objects_created: this->OpenGLObjectsCreated // \post right_size: LastSize[]=window size. //----------------------------------------------------------------------------- int vtkMitkOpenGLGPUVolumeRayCastMapper::AllocateFrameBuffers(vtkRenderer *ren) { assert("pre: ren_exists" && ren!=0); assert("pre: opengl_objects_created" && this->OpenGLObjectsCreated); int result=1; int size[2]; ren->GetTiledSize(&size[0],&size[1]); int sizeChanged=this->LastSize[0]!=size[0] || this->LastSize[1]!=size[1]; GLenum errorCode=glGetError(); // Need allocation? if(sizeChanged) { int i=0; GLenum errorCode=glGetError(); while(i NumberOfFrameBuffers && errorCode==GL_NO_ERROR) { glBindTexture(GL_TEXTURE_2D,static_cast(this->TextureObjects[vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront+i])); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, vtkgl::CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, vtkgl::CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Here we are assuming that GL_ARB_texture_non_power_of_two is available if(this->Supports_GL_ARB_texture_float) { glTexImage2D(GL_TEXTURE_2D,0,vtkgl::RGBA16F_ARB,size[0],size[1], 0, GL_RGBA, GL_FLOAT, NULL ); } else { glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA16,size[0],size[1], 0, GL_RGBA, GL_FLOAT, NULL ); } errorCode=glGetError(); ++i; } if(errorCode==GL_NO_ERROR) { // grabbed depth buffer glBindTexture(GL_TEXTURE_2D,static_cast(this->TextureObjects[vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectDepthMap])); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, vtkgl::CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, vtkgl::CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri(GL_TEXTURE_2D, vtkgl::DEPTH_TEXTURE_MODE, GL_LUMINANCE); glTexImage2D(GL_TEXTURE_2D, 0, vtkgl::DEPTH_COMPONENT32, size[0],size[1], 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL ); // Set up the depth render buffer GLint savedFrameBuffer; glGetIntegerv(vtkgl::FRAMEBUFFER_BINDING_EXT,&savedFrameBuffer); vtkgl::BindFramebufferEXT(vtkgl::FRAMEBUFFER_EXT, static_cast(this->FrameBufferObject)); this->BindFramebuffer(); vtkgl::BindRenderbufferEXT( vtkgl::RENDERBUFFER_EXT, static_cast(this->DepthRenderBufferObject)); vtkgl::RenderbufferStorageEXT(vtkgl::RENDERBUFFER_EXT, vtkgl::DEPTH_COMPONENT24,size[0],size[1]); vtkgl::BindFramebufferEXT(vtkgl::FRAMEBUFFER_EXT, static_cast(savedFrameBuffer)); errorCode=glGetError(); if(errorCode==GL_NO_ERROR) { this->LastSize[0]=size[0]; this->LastSize[1]=size[1]; } } result=errorCode==GL_NO_ERROR; } int needNewMaxValueBuffer=this->MaxValueFrameBuffer==0 && (this->BlendMode==vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND || this->BlendMode==vtkMitkGPUVolumeRayCastMapper::MINIMUM_INTENSITY_BLEND); if(needNewMaxValueBuffer) { // blend mode changed and need max value buffer. // create and bind second color buffer (we use only the red component // to store the max scalar). We cant use a one component color buffer // because all color buffer have to have the same format. // max scalar frame buffer GLuint maxValueFrameBuffer; glGenTextures(1,&maxValueFrameBuffer); this->MaxValueFrameBuffer= static_cast(maxValueFrameBuffer); // Color buffers this->m_BindMax = true; // max scalar frame buffer2 GLuint maxValueFrameBuffer2; glGenTextures(1,&maxValueFrameBuffer2); glBindTexture(GL_TEXTURE_2D,maxValueFrameBuffer2); this->MaxValueFrameBuffer2= static_cast(maxValueFrameBuffer2); } else { if(this->MaxValueFrameBuffer!=0 && (this->BlendMode!=vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND && this->BlendMode!=vtkMitkGPUVolumeRayCastMapper::MINIMUM_INTENSITY_BLEND)) { // blend mode changed and does not need max value buffer anymore. GLint savedFrameBuffer; glGetIntegerv(vtkgl::FRAMEBUFFER_BINDING_EXT,&savedFrameBuffer); vtkgl::BindFramebufferEXT(vtkgl::FRAMEBUFFER_EXT, static_cast(this->FrameBufferObject)); vtkgl::FramebufferTexture2DEXT(vtkgl::FRAMEBUFFER_EXT, vtkgl::COLOR_ATTACHMENT0_EXT+1, GL_TEXTURE_2D,0,0); // not scalar buffer vtkgl::BindFramebufferEXT(vtkgl::FRAMEBUFFER_EXT, static_cast(savedFrameBuffer)); GLuint maxValueFrameBuffer= static_cast(this->MaxValueFrameBuffer); glDeleteTextures(1,&maxValueFrameBuffer); this->MaxValueFrameBuffer=0; m_BindMax = false; GLuint maxValueFrameBuffer2= static_cast(this->MaxValueFrameBuffer2); glDeleteTextures(1,&maxValueFrameBuffer2); this->MaxValueFrameBuffer2=0; } } if((this->BlendMode==vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND || this->BlendMode==vtkMitkGPUVolumeRayCastMapper::MINIMUM_INTENSITY_BLEND) && (sizeChanged || needNewMaxValueBuffer)) { // max scalar frame buffer GLuint maxValueFrameBuffer=static_cast(this->MaxValueFrameBuffer); glBindTexture(GL_TEXTURE_2D,maxValueFrameBuffer); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, vtkgl::CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, vtkgl::CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Here we are assuming that GL_ARB_texture_non_power_of_two is available if(this->Supports_GL_ARB_texture_float) { glTexImage2D(GL_TEXTURE_2D,0,vtkgl::RGBA16F_ARB,size[0],size[1], 0, GL_RGBA, GL_FLOAT, NULL ); } else { glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA16,size[0],size[1], 0, GL_RGBA, GL_FLOAT, NULL ); } // max scalar frame buffer 2 GLuint maxValueFrameBuffer2=static_cast(this->MaxValueFrameBuffer2); glBindTexture(GL_TEXTURE_2D,maxValueFrameBuffer2); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, vtkgl::CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, vtkgl::CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Here we are assuming that GL_ARB_texture_non_power_of_two is available if(this->Supports_GL_ARB_texture_float) { glTexImage2D(GL_TEXTURE_2D,0,vtkgl::RGBA16F_ARB,size[0],size[1], 0, GL_RGBA, GL_FLOAT, NULL ); } else { glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA16,size[0],size[1], 0, GL_RGBA, GL_FLOAT, NULL ); } } PrintError("AllocateFrameBuffers"); return result; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::GetTextureFormat( vtkImageData *input, unsigned int *internalFormat, unsigned int *format, unsigned int *type, int *componentSize) { *internalFormat=0; *format=0; *type=0; *componentSize=0; vtkDataArray *scalars=this->GetScalars(input,this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, this->CellFlag); int scalarType=scalars->GetDataType(); int components=scalars->GetNumberOfComponents(); *componentSize=vtkAbstractArray::GetDataTypeSize(scalarType)*components; if(components==4) { // this is RGBA, unsigned char only *internalFormat=GL_RGBA16; *format=GL_RGBA; *type=GL_UNSIGNED_BYTE; } else { // components==1 switch(scalarType) { case VTK_FLOAT: if(this->Supports_GL_ARB_texture_float) { *internalFormat=vtkgl::INTENSITY16F_ARB; } else { *internalFormat=GL_INTENSITY16; } *format=GL_RED; *type=GL_FLOAT; break; case VTK_UNSIGNED_CHAR: *internalFormat=GL_INTENSITY8; *format=GL_RED; *type=GL_UNSIGNED_BYTE; break; case VTK_SIGNED_CHAR: *internalFormat=GL_INTENSITY8; *format=GL_RED; *type=GL_BYTE; break; case VTK_CHAR: // not supported assert("check: impossible case" && 0); break; case VTK_BIT: // not supported assert("check: impossible case" && 0); break; case VTK_ID_TYPE: // not supported assert("check: impossible case" && 0); break; case VTK_INT: *internalFormat=GL_INTENSITY16; *format=GL_RED; *type=GL_INT; break; case VTK_DOUBLE: case VTK___INT64: case VTK_LONG: case VTK_LONG_LONG: case VTK_UNSIGNED___INT64: case VTK_UNSIGNED_LONG: case VTK_UNSIGNED_LONG_LONG: if(this->Supports_GL_ARB_texture_float) { *internalFormat=vtkgl::INTENSITY16F_ARB; } else { *internalFormat=GL_INTENSITY16; } *format=GL_RED; *type=GL_FLOAT; break; case VTK_SHORT: *internalFormat=GL_INTENSITY16; *format=GL_RED; *type=GL_SHORT; break; case VTK_STRING: // not supported assert("check: impossible case" && 0); break; case VTK_UNSIGNED_SHORT: *internalFormat=GL_INTENSITY16; *format=GL_RED; *type=GL_UNSIGNED_SHORT; break; case VTK_UNSIGNED_INT: *internalFormat=GL_INTENSITY16; *format=GL_RED; *type=GL_UNSIGNED_INT; break; default: assert("check: impossible case" && 0); break; } } } //----------------------------------------------------------------------------- // Assuming the textureSize[3] is less of equal to the maximum size of an // OpenGL 3D texture, try to see if the texture can fit on the card. //----------------------------------------------------------------------------- bool vtkMitkOpenGLGPUVolumeRayCastMapper::TestLoadingScalar( unsigned int internalFormat, unsigned int format, unsigned int type, int textureSize[3], int componentSize) { // componentSize=vtkAbstractArray::GetDataTypeSize(scalarType)*input->GetNumberOfScalarComponents() bool result; vtkgl::TexImage3D(vtkgl::PROXY_TEXTURE_3D,0, static_cast(internalFormat), textureSize[0],textureSize[1],textureSize[2],0, format, type,0); GLint width; glGetTexLevelParameteriv(vtkgl::PROXY_TEXTURE_3D,0,GL_TEXTURE_WIDTH, &width); result=width!=0; if(result) { // so far, so good but some cards always succeed with a proxy texture // let's try to actually allocate.. vtkgl::TexImage3D(vtkgl::TEXTURE_3D,0,static_cast(internalFormat), textureSize[0], textureSize[1],textureSize[2],0, format, type,0); GLenum errorCode=glGetError(); result=errorCode!=GL_OUT_OF_MEMORY; if(result) { if(errorCode!=GL_NO_ERROR) { cout<<"after try to load the texture"; cout<<" ERROR (x"<(errorCode)); cout<(this->MaxMemoryInBytes)*this->MaxMemoryFraction; } } return result; } //----------------------------------------------------------------------------- // Load the scalar field (one or four component scalar field), cell or point // based for a given subextent of the whole extent (can be the whole extent) // as a 3D texture on the GPU. // Extents are expressed in point if the cell flag is false or in cells of // the cell flag is true. // It returns true if it succeeded, false if there is not enough memory on // the GPU. // If succeeded, it updates the LoadedExtent, LoadedBounds, LoadedCellFlag // and LoadedTime. It also succeed if the scalar field is already loaded // (ie since last load, input has not changed and cell flag has not changed // and requested texture extents are enclosed in the loaded extent). // \pre input_exists: input!=0 // \pre valid_point_extent: (this->CellFlag || // (textureExtent[0]CellFlag || // (textureExtent[0]<=textureExtent[1] && // textureExtent[2]<=textureExtent[3] && // textureExtent[4]<=textureExtent[5]))) //----------------------------------------------------------------------------- int vtkMitkOpenGLGPUVolumeRayCastMapper::LoadScalarField(vtkImageData *input, vtkImageData *maskInput, int textureExtent[6], vtkVolume *volume) { assert("pre: input_exists" && input!=0); assert("pre: valid_point_extent" && (this->CellFlag || (textureExtent[0]CellFlag || (textureExtent[0]<=textureExtent[1] && textureExtent[2]<=textureExtent[3] && textureExtent[4]<=textureExtent[5]))); int result=1; // succeeded // make sure we rebind our texture object to texture0 even if we don't have // to load the data themselves because the binding might be changed by // another mapper between two rendering calls. vtkgl::ActiveTexture(vtkgl::TEXTURE0); // Find the texture. vtkstd::map::iterator it= this->ScalarsTextures->Map.find(input); vtkKWScalarField *texture; if(it==this->ScalarsTextures->Map.end()) { texture=new vtkKWScalarField; this->ScalarsTextures->Map[input]=texture; texture->SetSupports_GL_ARB_texture_float(this->Supports_GL_ARB_texture_float==1); } else { texture=(*it).second; } texture->Update(input,this->CellFlag,textureExtent,this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, volume->GetProperty()->GetInterpolationType() ==VTK_LINEAR_INTERPOLATION, this->TableRange, static_cast(static_cast(this->MaxMemoryInBytes)*this->MaxMemoryFraction)); result=texture->IsLoaded(); this->CurrentScalar=texture; // Mask if(maskInput!=0) { vtkgl::ActiveTexture(vtkgl::TEXTURE7); // Find the texture. vtkstd::map::iterator it2= this->MaskTextures->Map.find(maskInput); vtkKWMask *mask; if(it2==this->MaskTextures->Map.end()) { mask=new vtkKWMask; this->MaskTextures->Map[maskInput]=mask; } else { mask=(*it2).second; } mask->Update(maskInput,this->CellFlag,textureExtent,this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, static_cast(static_cast(this->MaxMemoryInBytes)*this->MaxMemoryFraction)); result=result && mask->IsLoaded(); this->CurrentMask=mask; vtkgl::ActiveTexture(vtkgl::TEXTURE0); } return result; } //----------------------------------------------------------------------------- // Allocate memory and load color table on the GPU or // reload it if the transfer function changed. // \pre vol_exists: vol!=0 // \pre valid_numberOfScalarComponents: numberOfScalarComponents==1 || numberOfScalarComponents==4 //----------------------------------------------------------------------------- int vtkMitkOpenGLGPUVolumeRayCastMapper::UpdateColorTransferFunction( vtkVolume *vol, int numberOfScalarComponents) { assert("pre: vol_exists" && vol!=0); assert("pre: valid_numberOfScalarComponents" && (numberOfScalarComponents==1 || numberOfScalarComponents==4)); // Build the colormap in a 1D texture. // 1D RGB-texture=mapping from scalar values to color values // build the table if(numberOfScalarComponents==1) { vtkVolumeProperty *volumeProperty=vol->GetProperty(); vtkColorTransferFunction *colorTransferFunction=volumeProperty->GetRGBTransferFunction(0); vtkgl::ActiveTexture(vtkgl::TEXTURE1); this->RGBTable->Update( colorTransferFunction,this->TableRange, volumeProperty->GetInterpolationType()==VTK_LINEAR_INTERPOLATION); // Restore default vtkgl::ActiveTexture( vtkgl::TEXTURE0); } if(this->MaskInput!=0) { vtkVolumeProperty *volumeProperty=vol->GetProperty(); vtkColorTransferFunction *c=volumeProperty->GetRGBTransferFunction(1); vtkgl::ActiveTexture(vtkgl::TEXTURE8); this->Mask1RGBTable->Update(c,this->TableRange,false); c=volumeProperty->GetRGBTransferFunction(2); vtkgl::ActiveTexture(vtkgl::TEXTURE9); this->Mask2RGBTable->Update(c,this->TableRange,false); // Restore default vtkgl::ActiveTexture( vtkgl::TEXTURE0); } return 1; } //----------------------------------------------------------------------------- // Allocate memory and load opacity table on the GPU or // reload it if the transfert function changed. // \pre vol_exists: vol!=0 // \pre valid_numberOfScalarComponents: numberOfScalarComponents==1 || numberOfScalarComponents==4 //----------------------------------------------------------------------------- int vtkMitkOpenGLGPUVolumeRayCastMapper::UpdateOpacityTransferFunction( vtkVolume *vol, int numberOfScalarComponents, unsigned int level) { assert("pre: vol_exists" && vol!=0); assert("pre: valid_numberOfScalarComponents" && (numberOfScalarComponents==1 || numberOfScalarComponents==4)); (void)numberOfScalarComponents; // remove warning in release mode. vtkVolumeProperty *volumeProperty=vol->GetProperty(); vtkPiecewiseFunction *scalarOpacity=volumeProperty->GetScalarOpacity(); vtkgl::ActiveTexture( vtkgl::TEXTURE2); //stay here this->OpacityTables->Vector[level].Update( scalarOpacity,this->BlendMode, this->ActualSampleDistance, this->TableRange, volumeProperty->GetScalarOpacityUnitDistance(0), volumeProperty->GetInterpolationType()==VTK_LINEAR_INTERPOLATION); // Restore default active texture vtkgl::ActiveTexture( vtkgl::TEXTURE0); return 1; } //----------------------------------------------------------------------------- // Prepare rendering in the offscreen framebuffer. // \pre ren_exists: ren!=0 // \pre vol_exists: vol!=0 //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::SetupRender(vtkRenderer *ren, vtkVolume *vol) { assert("pre: ren_exists" && ren!=0); assert("pre: vol_exists" && vol!=0); double aspect[2]; int lowerLeft[2]; int usize, vsize; ren->GetTiledSizeAndOrigin(&usize,&vsize,lowerLeft,lowerLeft+1); usize = static_cast(usize*this->ReductionFactor); vsize = static_cast(vsize*this->ReductionFactor); this->ReducedSize[0]=usize; this->ReducedSize[1]=vsize; // the FBO has the size of the renderer (not the renderwindow), // we always starts at 0,0. glViewport(0,0, usize, vsize); glEnable( GL_SCISSOR_TEST ); // scissor on the FBO, on the reduced part. glScissor(0,0, usize, vsize); glClearColor(0.0, 0.0, 0.0, 0.0); // maxvalue is 1 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ren->ComputeAspect(); ren->GetAspect(aspect); double aspect2[2]; ren->vtkViewport::ComputeAspect(); ren->vtkViewport::GetAspect(aspect2); double aspectModification = aspect[0]*aspect2[1]/(aspect[1]*aspect2[0]); vtkCamera *cam = ren->GetActiveCamera(); glMatrixMode( GL_PROJECTION); if(usize && vsize) { this->TempMatrix[0]->DeepCopy(cam->GetProjectionTransformMatrix( aspectModification*usize/vsize, -1,1)); this->TempMatrix[0]->Transpose(); glLoadMatrixd(this->TempMatrix[0]->Element[0]); } else { glLoadIdentity(); } // push the model view matrix onto the stack, make sure we // adjust the mode first glMatrixMode(GL_MODELVIEW); glPushMatrix(); this->TempMatrix[0]->DeepCopy(vol->GetMatrix()); this->TempMatrix[0]->Transpose(); // insert camera view transformation glMultMatrixd(this->TempMatrix[0]->Element[0]); glShadeModel(GL_SMOOTH); glDisable( GL_LIGHTING); glEnable (GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); // very important, otherwise the first image looks dark. this->PrintError("SetupRender"); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::DebugDisplayBox(vtkPolyData *box) { vtkPoints *points=box->GetPoints(); vtkCellArray *polys=box->GetPolys(); cout<<"npts="<GetNumberOfPoints()<GetNumberOfPoints()) { double coords[3]; points->GetPoint(pointId,coords); cout<<"pointId="<GetMatrix( this->InvVolumeMatrix ); this->InvVolumeMatrix->Invert(); if(this->BoxSource==0) { this->BoxSource=vtkTessellatedBoxSource::New(); } this->BoxSource->SetBounds(worldBounds); this->BoxSource->SetLevel(0); this->BoxSource->QuadsOn(); if(this->Planes==0) { this->Planes=vtkPlaneCollection::New(); } this->Planes->RemoveAllItems(); vtkCamera *cam = ren->GetActiveCamera(); double camWorldRange[2]; double camWorldPos[4]; double camFocalWorldPoint[4]; double camWorldDirection[3]; double range[2]; double camPos[4]; double focalPoint[4]; double direction[3]; cam->GetPosition(camWorldPos); camWorldPos[3] = 1.0; this->InvVolumeMatrix->MultiplyPoint( camWorldPos, camPos ); if ( camPos[3] ) { camPos[0] /= camPos[3]; camPos[1] /= camPos[3]; camPos[2] /= camPos[3]; } cam->GetFocalPoint(camFocalWorldPoint); camFocalWorldPoint[3]=1.0; this->InvVolumeMatrix->MultiplyPoint( camFocalWorldPoint,focalPoint ); if ( focalPoint[3] ) { focalPoint[0] /= focalPoint[3]; focalPoint[1] /= focalPoint[3]; focalPoint[2] /= focalPoint[3]; } // Compute the normalized view direction direction[0] = focalPoint[0] - camPos[0]; direction[1] = focalPoint[1] - camPos[1]; direction[2] = focalPoint[2] - camPos[2]; vtkMath::Normalize(direction); // The range (near/far) must also be transformed // into the local coordinate system. camWorldDirection[0] = camFocalWorldPoint[0] - camWorldPos[0]; camWorldDirection[1] = camFocalWorldPoint[1] - camWorldPos[1]; camWorldDirection[2] = camFocalWorldPoint[2] - camWorldPos[2]; vtkMath::Normalize(camWorldDirection); double camNearWorldPoint[4]; double camFarWorldPoint[4]; double camNearPoint[4]; double camFarPoint[4]; cam->GetClippingRange(camWorldRange); camNearWorldPoint[0] = camWorldPos[0] + camWorldRange[0]*camWorldDirection[0]; camNearWorldPoint[1] = camWorldPos[1] + camWorldRange[0]*camWorldDirection[1]; camNearWorldPoint[2] = camWorldPos[2] + camWorldRange[0]*camWorldDirection[2]; camNearWorldPoint[3] = 1.; camFarWorldPoint[0] = camWorldPos[0] + camWorldRange[1]*camWorldDirection[0]; camFarWorldPoint[1] = camWorldPos[1] + camWorldRange[1]*camWorldDirection[1]; camFarWorldPoint[2] = camWorldPos[2] + camWorldRange[1]*camWorldDirection[2]; camFarWorldPoint[3] = 1.; this->InvVolumeMatrix->MultiplyPoint( camNearWorldPoint, camNearPoint ); if (camNearPoint[3]) { camNearPoint[0] /= camNearPoint[3]; camNearPoint[1] /= camNearPoint[3]; camNearPoint[2] /= camNearPoint[3]; } this->InvVolumeMatrix->MultiplyPoint( camFarWorldPoint, camFarPoint ); if (camFarPoint[3]) { camFarPoint[0] /= camFarPoint[3]; camFarPoint[1] /= camFarPoint[3]; camFarPoint[2] /= camFarPoint[3]; } range[0] = sqrt(vtkMath::Distance2BetweenPoints(camNearPoint, camPos)); range[1] = sqrt(vtkMath::Distance2BetweenPoints(camFarPoint, camPos)); //double nearPoint[3], farPoint[3]; double dist = range[1] - range[0]; range[0] += dist / (2<<16); range[1] -= dist / (2<<16); if(this->NearPlane==0) { this->NearPlane= vtkPlane::New(); } //this->NearPlane->SetOrigin( nearPoint ); this->NearPlane->SetOrigin( camNearPoint ); this->NearPlane->SetNormal( direction ); this->Planes->AddItem(this->NearPlane); if ( this->ClippingPlanes ) { this->ClippingPlanes->InitTraversal(); vtkPlane *plane; while ( (plane = this->ClippingPlanes->GetNextItem()) ) { // Planes are in world coordinates, we need to // convert them in local coordinates double planeOrigin[4], planeNormal[4], planeP1[4]; plane->GetOrigin(planeOrigin); planeOrigin[3] = 1.; plane->GetNormal(planeNormal); planeP1[0] = planeOrigin[0] + planeNormal[0]; planeP1[1] = planeOrigin[1] + planeNormal[1]; planeP1[2] = planeOrigin[2] + planeNormal[2]; planeP1[3] = 1.; this->InvVolumeMatrix->MultiplyPoint(planeOrigin, planeOrigin); this->InvVolumeMatrix->MultiplyPoint(planeP1, planeP1); if( planeOrigin[3]) { planeOrigin[0] /= planeOrigin[3]; planeOrigin[1] /= planeOrigin[3]; planeOrigin[2] /= planeOrigin[3]; } if( planeP1[3]) { planeP1[0] /= planeP1[3]; planeP1[1] /= planeP1[3]; planeP1[2] /= planeP1[3]; } planeNormal[0] = planeP1[0] - planeOrigin[0]; planeNormal[1] = planeP1[1] - planeOrigin[1]; planeNormal[2] = planeP1[2] - planeOrigin[2]; vtkMath::Normalize(planeNormal); vtkPlane* localPlane = vtkPlane::New(); localPlane->SetOrigin(planeOrigin); localPlane->SetNormal(planeNormal); this->Planes->AddItem(localPlane); localPlane->Delete(); } } if(this->Clip==0) { this->Clip=vtkClipConvexPolyData::New(); this->Clip->SetInputConnection(this->BoxSource->GetOutputPort()); this->Clip->SetPlanes( this->Planes ); } this->Clip->Update(); if(this->Densify==0) { this->Densify=vtkDensifyPolyData::New(); this->Densify->SetInputConnection(this->Clip->GetOutputPort()); this->Densify->SetNumberOfSubdivisions(2); } this->Densify->Update(); this->ClippedBoundingBox = this->Densify->GetOutput(); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- int vtkMitkOpenGLGPUVolumeRayCastMapper::RenderClippedBoundingBox( int tcoordFlag, size_t currentBlock, size_t numberOfBlocks, vtkRenderWindow *renWin ) { assert("pre: valid_currentBlock" && currentBlockClippedBoundingBox->GetPoints(); vtkCellArray *polys = this->ClippedBoundingBox->GetPolys(); vtkIdType npts; vtkIdType *pts; vtkIdType i, j; double center[3] = {0,0,0}; double min[3] = {VTK_DOUBLE_MAX, VTK_DOUBLE_MAX, VTK_DOUBLE_MAX}; double max[3] = {VTK_DOUBLE_MIN, VTK_DOUBLE_MIN, VTK_DOUBLE_MIN}; // First compute center point npts = points->GetNumberOfPoints(); for ( i = 0; i < npts; i++ ) { double pt[3]; points->GetPoint( i, pt ); for ( j = 0; j < 3; j++ ) { min[j] = (pt[j]max[j])?(pt[j]):(max[j]); } } center[0] = 0.5*(min[0]+max[0]); center[1] = 0.5*(min[1]+max[1]); center[2] = 0.5*(min[2]+max[2]); double *loadedBounds=0; vtkIdType *loadedExtent=0; if ( tcoordFlag ) { loadedBounds=this->CurrentScalar->GetLoadedBounds(); loadedExtent=this->CurrentScalar->GetLoadedExtent(); } double *spacing=this->GetInput()->GetSpacing(); double spacingSign[3]; i=0; while(i<3) { if(spacing[i]<0) { spacingSign[i]=-1.0; } else { spacingSign[i]=1.0; } ++i; } // make it double for the ratio of the progress. int polyId=0; double polyCount=static_cast(polys->GetNumberOfCells()); polys->InitTraversal(); int abort=0; while ( !abort && polys->GetNextCell(npts, pts) ) { vtkIdType start, end, inc; // Need to have at least a triangle if ( npts > 2 ) { // Check the cross product of the first two // vectors dotted with the vector from the // center to the second point. Is it positive or // negative? double p1[3], p2[3], p3[3]; double v1[3], v2[3], v3[3], v4[3]; points->GetPoint(pts[0], p1 ); points->GetPoint(pts[1], p2 ); points->GetPoint(pts[2], p3 ); v1[0] = p2[0] - p1[0]; v1[1] = p2[1] - p1[1]; v1[2] = p2[2] - p1[2]; v2[0] = p2[0] - p3[0]; v2[1] = p2[1] - p3[1]; v2[2] = p2[2] - p3[2]; vtkMath::Cross( v1, v2, v3 ); vtkMath::Normalize(v3); v4[0] = p2[0] - center[0]; v4[1] = p2[1] - center[1]; v4[2] = p2[2] - center[2]; vtkMath::Normalize(v4); double dot = vtkMath::Dot( v3, v4 ); if (( dot < 0) && this->PreserveOrientation) { start = 0; end = npts; inc = 1; } else { start = npts-1; end = -1; inc = -1; } glBegin( GL_TRIANGLE_FAN ); // GL_POLYGON -> GL_TRIANGLE_FAN double vert[3]; double tcoord[3]; for ( i = start; i != end; i += inc ) { points->GetPoint(pts[i], vert); if ( tcoordFlag ) { for ( j = 0; j < 3; j++ ) { // loaded bounds take both cell data and point date cases into // account if(this->CellFlag) // texcoords between 0 and 1. More complex // depends on the loaded texture { tcoord[j] = spacingSign[j]*(vert[j] - loadedBounds[j*2]) / (loadedBounds[j*2+1] - loadedBounds[j*2]); } else // texcoords between 1/2N and 1-1/2N. { double tmp; // between 0 and 1 tmp = spacingSign[j]*(vert[j] - loadedBounds[j*2]) / (loadedBounds[j*2+1] - loadedBounds[j*2]); double delta=static_cast( loadedExtent[j*2+1]-loadedExtent[j*2]+1); tcoord[j]=(tmp*(delta-1)+0.5)/delta; } } vtkgl::MultiTexCoord3dv(vtkgl::TEXTURE0, tcoord); } glVertex3dv(vert); } glEnd(); } if(tcoordFlag) { // otherwise, we are rendering back face to initialize the zbuffer. if (!this->GeneratingCanonicalView && this->ReportProgress) { glFinish(); // Only invoke an event at most one every second. double currentTime=vtkTimerLog::GetUniversalTime(); if(currentTime - this->LastProgressEventTime > 1.0) { double progress=(static_cast(currentBlock)+polyId/polyCount)/ static_cast(numberOfBlocks); this->InvokeEvent(vtkCommand::VolumeMapperRenderProgressEvent, &progress); renWin->MakeCurrent(); this->LastProgressEventTime = currentTime; } } abort=renWin->CheckAbortStatus(); } ++polyId; } return abort; } void vtkMitkOpenGLGPUVolumeRayCastMapper::CopyFBOToTexture() { // in OpenGL copy texture to texture does not exist but // framebuffer to texture exists (and our FB is an FBO). // we have to copy and not just to switch color textures because the // colorbuffer has to accumulate color or values step after step. // Switching would not work because two different steps can draw different // polygons that don't overlap vtkgl::ActiveTexture(vtkgl::TEXTURE4); glBindTexture( GL_TEXTURE_2D, this->TextureObjects[ vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront+1]); glReadBuffer(vtkgl::COLOR_ATTACHMENT0_EXT); glCopyTexSubImage2D(GL_TEXTURE_2D,0,0,0,0,0,this->ReducedSize[0], this->ReducedSize[1]); if(this->BlendMode==vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND || this->BlendMode==vtkMitkGPUVolumeRayCastMapper::MINIMUM_INTENSITY_BLEND) { vtkgl::ActiveTexture(vtkgl::TEXTURE5); glBindTexture(GL_TEXTURE_2D,this->MaxValueFrameBuffer2); glReadBuffer(vtkgl::COLOR_ATTACHMENT0_EXT+1); glCopyTexSubImage2D(GL_TEXTURE_2D,0,0,0,0,0,this->ReducedSize[0], this->ReducedSize[1]); } vtkgl::ActiveTexture(vtkgl::TEXTURE0); } //----------------------------------------------------------------------------- // Restore OpenGL state after rendering of the dataset. //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::CleanupRender() { glPopMatrix(); glDisable(GL_CULL_FACE); } //----------------------------------------------------------------------------- // Build the fragment shader program that scale and bias a texture // for window/level purpose. //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::BuildScaleBiasProgram() { if(this->ScaleBiasProgramShader==0) { GLuint programShader; GLuint fragmentShader; programShader=vtkgl::CreateProgram(); fragmentShader=vtkgl::CreateShader(vtkgl::FRAGMENT_SHADER); vtkgl::AttachShader(programShader,fragmentShader); vtkgl::DeleteShader(fragmentShader); // reference counting vtkgl::ShaderSource( fragmentShader,1, const_cast(&vtkMitkGPUVolumeRayCastMapper_ScaleBiasFS),0); vtkgl::CompileShader(fragmentShader); this->CheckCompilation(static_cast(fragmentShader)); vtkgl::LinkProgram(programShader); this->CheckLinkage(static_cast(programShader)); this->ScaleBiasProgramShader=static_cast(programShader); this->UFrameBufferTexture= static_cast(vtkgl::GetUniformLocation(programShader, "frameBufferTexture")); this->UScale=static_cast(vtkgl::GetUniformLocation(programShader, "scale")); this->UBias=static_cast(vtkgl::GetUniformLocation(programShader, "bias")); } } //----------------------------------------------------------------------------- // Render the offscreen buffer to the screen. // \pre ren_exists: ren!=0 //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::RenderTextureToScreen(vtkRenderer *ren) { assert("pre: ren_exists" && ren!=0); if ( this->GeneratingCanonicalView ) { // We just need to copy of the data, not render it glBindTexture(GL_TEXTURE_2D, this->TextureObjects[ vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glPixelStorei( GL_PACK_ALIGNMENT, 1 ); unsigned char *outPtr = static_cast(this->CanonicalViewImageData->GetScalarPointer()); glGetTexImage( GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, outPtr ); return; } int lowerLeft[2]; int usize, vsize; ren->GetTiledSizeAndOrigin(&usize,&vsize,lowerLeft,lowerLeft+1); glViewport(lowerLeft[0],lowerLeft[1], usize, vsize); glEnable( GL_SCISSOR_TEST ); glScissor(lowerLeft[0],lowerLeft[1], usize, vsize); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0.0, usize, 0.0, vsize, -1.0, 1.0 ); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glBindTexture(GL_TEXTURE_2D, this->TextureObjects[vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glEnable(GL_BLEND); glBlendFunc( GL_ONE,GL_ONE_MINUS_SRC_ALPHA); // As we use replace mode, we don't need to set the color value. glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE); glDisable(GL_DEPTH_TEST); double xOffset = 1.0 / usize; double yOffset = 1.0 / vsize; glDepthMask(GL_FALSE); double scale=1.0/this->FinalColorWindow; double bias=0.5-this->FinalColorLevel/this->FinalColorWindow; if(scale!=1.0 || bias!=0.0) { this->BuildScaleBiasProgram(); vtkgl::UseProgram(this->ScaleBiasProgramShader); if(this->UFrameBufferTexture!=-1) { vtkgl::Uniform1i(this->UFrameBufferTexture,0); } else { vtkErrorMacro(<<"uFrameBufferTexture is not a uniform variable."); } if(this->UScale!=-1) { vtkgl::Uniform1f(this->UScale,static_cast(scale)); } else { vtkErrorMacro(<<"uScale is not a uniform variable."); } if(this->UBias!=-1) { vtkgl::Uniform1f(this->UBias,static_cast(bias)); } else { vtkErrorMacro(<<"uBias is not a uniform variable."); } } else { glEnable(GL_TEXTURE_2D); // fixed pipeline } glBegin(GL_QUADS); glTexCoord2f(static_cast(xOffset),static_cast(yOffset)); glVertex2f(0.0,0.0); glTexCoord2f(static_cast(this->ReductionFactor-xOffset), static_cast(yOffset)); glVertex2f(static_cast(usize),0.0); glTexCoord2f(static_cast(this->ReductionFactor-xOffset), static_cast(this->ReductionFactor-yOffset)); glVertex2f(static_cast(usize),static_cast(vsize)); glTexCoord2f(static_cast(xOffset), static_cast(this->ReductionFactor-yOffset)); glVertex2f(0.0,static_cast(vsize)); glEnd(); // Restore the default mode. Used in overlay. glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE); if(scale!=1.0 || bias!=0.0) { vtkgl::UseProgram(0); } else { glDisable(GL_TEXTURE_2D); } glDepthMask(GL_TRUE); glDisable(GL_BLEND); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } //----------------------------------------------------------------------------- // Update the reduction factor of the render viewport (this->ReductionFactor) // according to the time spent in seconds to render the previous frame // (this->TimeToDraw) and a time in seconds allocated to render the next // frame (allocatedTime). // \pre valid_current_reduction_range: this->ReductionFactor>0.0 && this->ReductionFactor<=1.0 // \pre positive_TimeToDraw: this->TimeToDraw>=0.0 // \pre positive_time: allocatedTime>0.0 // \post valid_new_reduction_range: this->ReductionFactor>0.0 && this->ReductionFactor<=1.0 //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::ComputeReductionFactor( double allocatedTime) { assert("pre: valid_current_reduction_range" && this->ReductionFactor>0.0 && this->ReductionFactor<=1.0); assert("pre: positive_TimeToDraw" && this->TimeToDraw>=0.0); assert("pre: positive_time" && allocatedTime>0.0); if ( this->GeneratingCanonicalView ) { this->ReductionFactor = 1.0; return; } if ( !this->AutoAdjustSampleDistances ) { this->ReductionFactor = 1.0 / this->ImageSampleDistance; return; } if ( this->TimeToDraw ) { double oldFactor = this->ReductionFactor; double timeToDraw; if (allocatedTime < 1.0) { timeToDraw = this->SmallTimeToDraw; if ( timeToDraw == 0.0 ) { timeToDraw = this->BigTimeToDraw/3.0; } } else { timeToDraw = this->BigTimeToDraw; } if ( timeToDraw == 0.0 ) { timeToDraw = 10.0; } double fullTime = timeToDraw / this->ReductionFactor; double newFactor = allocatedTime / fullTime; if ( oldFactor == 1.0 || newFactor / oldFactor > 1.3 || newFactor / oldFactor < .95 ) { this->ReductionFactor = (newFactor+oldFactor)/2.0; this->ReductionFactor = (this->ReductionFactor > 5.0)?(1.00):(this->ReductionFactor); this->ReductionFactor = (this->ReductionFactor > 1.0)?(0.99):(this->ReductionFactor); this->ReductionFactor = (this->ReductionFactor < 0.1)?(0.10):(this->ReductionFactor); if ( 1.0/this->ReductionFactor > this->MaximumImageSampleDistance ) { this->ReductionFactor = 1.0 / this->MaximumImageSampleDistance; } if ( 1.0/this->ReductionFactor < this->MinimumImageSampleDistance ) { this->ReductionFactor = 1.0 / this->MinimumImageSampleDistance; } } } else { this->ReductionFactor = 1.0; } assert("post: valid_new_reduction_range" && this->ReductionFactor>0.0 && this->ReductionFactor<=1.0); } //----------------------------------------------------------------------------- // Rendering initialization including making the context current, loading // necessary extensions, allocating frame buffers, updating transfer function, // computing clipping regions, and building the fragment shader. // // Pre-conditions: // - ren != NULL // - vol != NULL // - ren->GetRenderWindow() != NULL // - 1 <= numberOfScalarComponents <= 4 // - numberOfLevels >= 1 //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::PreRender(vtkRenderer *ren, vtkVolume *vol, double datasetBounds[6], double scalarRange[2], int numberOfScalarComponents, unsigned int numberOfLevels) { // make sure our window is the current OpenGL context. ren->GetRenderWindow()->MakeCurrent(); // If we haven't already succeeded in loading the extensions, // try to load them if(!this->LoadExtensionsSucceeded) { this->LoadExtensions(ren->GetRenderWindow()); } // If we can't load the necessary extensions, provide // feedback on why it failed. if(!this->LoadExtensionsSucceeded) { vtkErrorMacro( "Rendering failed because the following OpenGL extensions " "are required but not supported: " << (this->UnsupportedRequiredExtensions->Stream.str()).c_str()); return; } // Create the OpenGL object that we need this->CreateOpenGLObjects(); // Compute the reduction factor that may be necessary to get // the interactive rendering rate that we want this->ComputeReductionFactor(vol->GetAllocatedRenderTime()); // Allocate the frame buffers if(!this->AllocateFrameBuffers(ren)) { vtkErrorMacro("Not enough GPU memory to create a framebuffer."); return; } // Save the scalar range - this is what we will use for the range // of the transfer functions this->TableRange[0]=scalarRange[0]; this->TableRange[1]=scalarRange[1]; if(this->RGBTable==0) { this->RGBTable=new vtkRGBTable; } if(this->MaskInput!=0) { if(this->Mask1RGBTable==0) { this->Mask1RGBTable=new vtkRGBTable; } if(this->Mask2RGBTable==0) { this->Mask2RGBTable=new vtkRGBTable; } } // Update the color transfer function this->UpdateColorTransferFunction(vol,numberOfScalarComponents); // Update the noise texture that will be used to jitter rays to // reduce alliasing artifacts this->UpdateNoiseTexture(); // We are going to change the blending mode and blending function - // so lets push here so we can pop later glPushAttrib(GL_COLOR_BUFFER_BIT); // If this is the canonical view - we don't want to intermix so we'll just // start by clearing the z buffer. if ( this->GeneratingCanonicalView ) { glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } // See if the volume transform is orientation-preserving vtkMatrix4x4 *m=vol->GetMatrix(); double det=vtkMath::Determinant3x3( m->GetElement(0,0),m->GetElement(0,1),m->GetElement(0,2), m->GetElement(1,0),m->GetElement(1,1),m->GetElement(1,2), m->GetElement(2,0),m->GetElement(2,1),m->GetElement(2,2)); this->PreserveOrientation=det>0; // If we have clipping planes, render the back faces of the clipped // bounding box of the whole dataset to set the zbuffer. if(this->ClippingPlanes && this->ClippingPlanes->GetNumberOfItems()!=0) { // push the model view matrix onto the stack, make sure we // adjust the mode first glMatrixMode(GL_MODELVIEW); glPushMatrix(); this->TempMatrix[0]->DeepCopy(vol->GetMatrix()); this->TempMatrix[0]->Transpose(); glMultMatrixd(this->TempMatrix[0]->Element[0]); this->ClipBoundingBox(ren,datasetBounds,vol); glEnable (GL_CULL_FACE); glCullFace (GL_FRONT); glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE); this->RenderClippedBoundingBox(0,0,1,ren->GetRenderWindow()); glDisable (GL_CULL_FACE); glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE); //glMatrixMode(GL_MODELVIEW); glPopMatrix(); } // Check if everything is OK this->CheckFrameBufferStatus(); // Intermixed geometry: Grab the depth buffer into a texture int size[2]; int lowerLeft[2]; ren->GetTiledSizeAndOrigin(size,size+1,lowerLeft,lowerLeft+1); vtkgl::ActiveTexture( vtkgl::TEXTURE3 ); glBindTexture(GL_TEXTURE_2D, static_cast( this->TextureObjects[ vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectDepthMap])); glCopyTexSubImage2D(GL_TEXTURE_2D,0,0,0,lowerLeft[0],lowerLeft[1],size[0], size[1]); vtkgl::ActiveTexture( vtkgl::TEXTURE0 ); int parallelProjection=ren->GetActiveCamera()->GetParallelProjection(); // initialize variables to prevent compiler warnings. int rayCastMethod=vtkMitkOpenGLGPUVolumeRayCastMapperMethodMIP; int shadeMethod=vtkMitkOpenGLGPUVolumeRayCastMapperShadeNotUsed; int componentMethod=vtkMitkOpenGLGPUVolumeRayCastMapperComponentNotUsed; switch(this->BlendMode) { case vtkVolumeMapper::COMPOSITE_BLEND: switch(numberOfScalarComponents) { case 1: componentMethod=vtkMitkOpenGLGPUVolumeRayCastMapperComponentOne; break; case 4: componentMethod=vtkMitkOpenGLGPUVolumeRayCastMapperComponentFour; break; default: assert("check: impossible case" && false); break; } if(this->MaskInput!=0) { rayCastMethod= vtkMitkOpenGLGPUVolumeRayCastMapperMethodCompositeMask; } else { //cout<<"program is composite+shade"<GetProperty()->GetShade() ) { shadeMethod=vtkMitkOpenGLGPUVolumeRayCastMapperShadeYes; assert("check: only_1_component_todo" && numberOfScalarComponents==1); } else { shadeMethod=vtkMitkOpenGLGPUVolumeRayCastMapperShadeNo; //cout<<"program is composite"<ComputeNumberOfCroppingRegions(); // TODO AMR vs single block if(this->AMRMode) { NumberOfCroppingRegions=2; // >1, means use do compositing between blocks } this->BuildProgram(parallelProjection,rayCastMethod,shadeMethod, componentMethod); this->CheckLinkage(this->ProgramShader); vtkgl::UseProgram(this->ProgramShader); // for active texture 0, dataset if(numberOfScalarComponents==1) { // colortable vtkgl::ActiveTexture(vtkgl::TEXTURE1); this->RGBTable->Bind(); if(this->MaskInput!=0) { vtkgl::ActiveTexture(vtkgl::TEXTURE8); this->Mask1RGBTable->Bind(); vtkgl::ActiveTexture(vtkgl::TEXTURE9); this->Mask2RGBTable->Bind(); } } GLint uDataSetTexture; uDataSetTexture=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"dataSetTexture"); if(uDataSetTexture!=-1) { vtkgl::Uniform1i(uDataSetTexture,0); } else { vtkErrorMacro(<<"dataSetTexture is not a uniform variable."); } if ( this->MaskInput) { // Make the mask texture available on texture unit 7 GLint uMaskTexture; uMaskTexture=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"maskTexture"); if(uMaskTexture!=-1) { vtkgl::Uniform1i(uMaskTexture,7); } else { vtkErrorMacro(<<"maskTexture is not a uniform variable."); } } if(numberOfScalarComponents==1) { GLint uColorTexture; uColorTexture=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"colorTexture"); if(uColorTexture!=-1) { vtkgl::Uniform1i(uColorTexture,1); } else { vtkErrorMacro(<<"colorTexture is not a uniform variable."); } if(this->MaskInput!=0) { GLint uMask1ColorTexture; uMask1ColorTexture=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"mask1ColorTexture"); if(uMask1ColorTexture!=-1) { vtkgl::Uniform1i(uMask1ColorTexture,8); } else { vtkErrorMacro(<<"mask1ColorTexture is not a uniform variable."); } GLint uMask2ColorTexture; uMask2ColorTexture=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"mask2ColorTexture"); if(uMask2ColorTexture!=-1) { vtkgl::Uniform1i(uMask2ColorTexture,9); } else { vtkErrorMacro(<<"mask2ColorTexture is not a uniform variable."); } GLint uMaskBlendFactor; uMaskBlendFactor=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"maskBlendFactor"); if(uMaskBlendFactor!=-1) { vtkgl::Uniform1f(uMaskBlendFactor,this->MaskBlendFactor); } else { vtkErrorMacro(<<"maskBlendFactor is not a uniform variable."); } } } GLint uOpacityTexture; uOpacityTexture=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"opacityTexture"); if(uOpacityTexture!=-1) { vtkgl::Uniform1i(uOpacityTexture,2); } else { vtkErrorMacro(<<"opacityTexture is not a uniform variable."); } // depthtexture vtkgl::ActiveTexture( vtkgl::TEXTURE3 ); glBindTexture(GL_TEXTURE_2D,static_cast(this->TextureObjects[vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectDepthMap])); GLint uDepthTexture; uDepthTexture=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"depthTexture"); if(uDepthTexture!=-1) { vtkgl::Uniform1i(uDepthTexture,3); } else { vtkErrorMacro(<<"depthTexture is not a uniform variable."); } // noise texture vtkgl::ActiveTexture( vtkgl::TEXTURE6 ); glBindTexture(GL_TEXTURE_2D,static_cast(this->NoiseTextureId)); GLint uNoiseTexture; uNoiseTexture=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"noiseTexture"); if(uNoiseTexture!=-1) { vtkgl::Uniform1i(uNoiseTexture,6); } else { vtkErrorMacro(<<"noiseTexture is not a uniform variable."); } this->CheckFrameBufferStatus(); if(this->NumberOfCroppingRegions>1) { // framebuffer texture if(rayCastMethod!=vtkMitkOpenGLGPUVolumeRayCastMapperMethodMIP && rayCastMethod!=vtkMitkOpenGLGPUVolumeRayCastMapperMethodMinIP) { vtkgl::ActiveTexture( vtkgl::TEXTURE4 ); glBindTexture(GL_TEXTURE_2D,static_cast(this->TextureObjects[vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront])); GLint uFrameBufferTexture; uFrameBufferTexture=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"frameBufferTexture"); this->PrintError("framebuffertexture 1"); if(uFrameBufferTexture!=-1) { vtkgl::Uniform1i(uFrameBufferTexture,4); } else { vtkErrorMacro(<<"frameBufferTexture is not a uniform variable."); } this->PrintError("framebuffertexture 2"); } this->CheckFrameBufferStatus(); // max scalar value framebuffer texture if(this->BlendMode==vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND || this->BlendMode==vtkMitkGPUVolumeRayCastMapper::MINIMUM_INTENSITY_BLEND) { vtkgl::ActiveTexture( vtkgl::TEXTURE5 ); glBindTexture(GL_TEXTURE_2D,static_cast(this->MaxValueFrameBuffer2)); GLint uScalarBufferTexture; uScalarBufferTexture=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"scalarBufferTexture"); this->PrintError("scalarbuffertexture 1"); if(uScalarBufferTexture!=-1) { vtkgl::Uniform1i(uScalarBufferTexture,5); } else { vtkErrorMacro(<<"scalarBufferTexture is not a uniform variable."); } this->PrintError("scalarbuffertexture 2"); } } this->CheckFrameBufferStatus(); GLint uWindowLowerLeftCorner; uWindowLowerLeftCorner=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"windowLowerLeftCorner"); if(uWindowLowerLeftCorner!=-1) { vtkgl::Uniform2f(uWindowLowerLeftCorner,static_cast(lowerLeft[0]), static_cast(lowerLeft[1])); } else { vtkErrorMacro(<<"windowLowerLeftCorner is not a uniform variable."); } GLint uInvOriginalWindowSize; uInvOriginalWindowSize=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"invOriginalWindowSize"); if(uInvOriginalWindowSize!=-1) { vtkgl::Uniform2f(uInvOriginalWindowSize, static_cast(1.0/size[0]), static_cast(1.0/size[1])); } else { // yes it is not error. It is only actually used when there is some // complex cropping (this->NumberOfCroppingRegions>1). Some GLSL compilers // may remove the uniform variable for optimization when it is not used. vtkDebugMacro( <<"invOriginalWindowSize is not an active uniform variable."); } size[0] = static_cast(size[0]*this->ReductionFactor); size[1] = static_cast(size[1]*this->ReductionFactor); GLint uInvWindowSize; uInvWindowSize=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"invWindowSize"); if(uInvWindowSize!=-1) { vtkgl::Uniform2f(uInvWindowSize,static_cast(1.0/size[0]), static_cast(1.0/size[1])); } else { vtkErrorMacro(<<"invWindowSize is not a uniform variable."); } this->PrintError("after uniforms for textures"); this->CheckFrameBufferStatus(); GLint savedFrameBuffer; glGetIntegerv(vtkgl::FRAMEBUFFER_BINDING_EXT,&savedFrameBuffer); this->SavedFrameBuffer=static_cast(savedFrameBuffer); vtkgl::BindFramebufferEXT(vtkgl::FRAMEBUFFER_EXT, static_cast(this->FrameBufferObject)); this->BindFramebuffer(); GLenum buffer[4]; buffer[0] = vtkgl::COLOR_ATTACHMENT0_EXT; if(this->NumberOfCroppingRegions>1 && this->BlendMode==vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND) { // max scalar frame buffer buffer[1] = vtkgl::COLOR_ATTACHMENT1_EXT; } else { buffer[1] = GL_NONE; } vtkgl::DrawBuffers(2,buffer); this->CheckFrameBufferStatus(); // Use by the composite+shade program double shininess=vol->GetProperty()->GetSpecularPower(); if(shininess>128.0) { shininess=128.0; // upper limit for the OpenGL shininess. } glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,static_cast(shininess)); glDisable(GL_COLOR_MATERIAL); // other mapper may have enable that. GLfloat values[4]; values[3]=1.0; values[0]=0.0; values[1]=values[0]; values[2]=values[0]; glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,values); values[0]=static_cast(vol->GetProperty()->GetAmbient()); values[1]=values[0]; values[2]=values[0]; glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,values); values[0]=static_cast(vol->GetProperty()->GetDiffuse()); values[1]=values[0]; values[2]=values[0]; glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,values); values[0]=static_cast(vol->GetProperty()->GetSpecular()); values[1]=values[0]; values[2]=values[0]; glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,values); // cout << "pingpong=" << this->PingPongFlag << endl; // To initialize the second color buffer vtkgl::FramebufferTexture2DEXT(vtkgl::FRAMEBUFFER_EXT, vtkgl::COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, this->TextureObjects[vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront], 0); vtkgl::FramebufferTexture2DEXT(vtkgl::FRAMEBUFFER_EXT, vtkgl::COLOR_ATTACHMENT0_EXT+1, GL_TEXTURE_2D, this->TextureObjects[vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront+1], 0); buffer[0] = vtkgl::COLOR_ATTACHMENT0_EXT; buffer[1] = vtkgl::COLOR_ATTACHMENT1_EXT; vtkgl::DrawBuffers(2,buffer); // cout << "check before setup" << endl; this->CheckFrameBufferStatus(); this->SetupRender(ren,vol); // restore in case of composite with no cropping or streaming. buffer[0] = vtkgl::COLOR_ATTACHMENT0_EXT; buffer[1] = GL_NONE; vtkgl::DrawBuffers(2,buffer); vtkgl::FramebufferTexture2DEXT(vtkgl::FRAMEBUFFER_EXT, vtkgl::COLOR_ATTACHMENT0_EXT+1, GL_TEXTURE_2D,0,0); // cout << "check after color init" << endl; this->CheckFrameBufferStatus(); if(this->NumberOfCroppingRegions>1 && (this->BlendMode==vtkMitkGPUVolumeRayCastMapper::MINIMUM_INTENSITY_BLEND || this->BlendMode==vtkMitkGPUVolumeRayCastMapper::MAXIMUM_INTENSITY_BLEND)) { // cout << "this->MaxValueFrameBuffer="<< this->MaxValueFrameBuffer <MaxValueFrameBuffer2="<< this->MaxValueFrameBuffer2 <MaxValueFrameBuffer,0); vtkgl::FramebufferTexture2DEXT(vtkgl::FRAMEBUFFER_EXT, vtkgl::COLOR_ATTACHMENT0_EXT+1, GL_TEXTURE_2D, this->MaxValueFrameBuffer2,0); buffer[0] = vtkgl::COLOR_ATTACHMENT0_EXT; buffer[1] = vtkgl::COLOR_ATTACHMENT1_EXT; vtkgl::DrawBuffers(2,buffer); if(this->BlendMode==vtkMitkGPUVolumeRayCastMapper::MINIMUM_INTENSITY_BLEND) { glClearColor(1.0, 0.0, 0.0, 0.0); } else { glClearColor(0.0, 0.0, 0.0, 0.0); // for MAXIMUM_INTENSITY_BLEND } // cout << "check before clear on max" << endl; this->CheckFrameBufferStatus(); glClear(GL_COLOR_BUFFER_BIT); } if(this->NumberOfCroppingRegions>1) { // color buffer target in the color attachement 0 vtkgl::FramebufferTexture2DEXT(vtkgl::FRAMEBUFFER_EXT, vtkgl::COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, this->TextureObjects[vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront], 0); // color buffer input is on texture unit 4. vtkgl::ActiveTexture(vtkgl::TEXTURE4); glBindTexture(GL_TEXTURE_2D,this->TextureObjects[vtkMitkOpenGLGPUVolumeRayCastMapperTextureObjectFrameBufferLeftFront+1]); if(this->BlendMode==vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND || this->BlendMode==vtkMitkGPUVolumeRayCastMapper::MINIMUM_INTENSITY_BLEND) { // max buffer target in the color attachment 1 vtkgl::FramebufferTexture2DEXT(vtkgl::FRAMEBUFFER_EXT, vtkgl::COLOR_ATTACHMENT0_EXT+1, GL_TEXTURE_2D, this->MaxValueFrameBuffer,0); // max buffer input is on texture unit 5. vtkgl::ActiveTexture(vtkgl::TEXTURE5); glBindTexture(GL_TEXTURE_2D,this->MaxValueFrameBuffer2); } vtkgl::ActiveTexture(vtkgl::TEXTURE0); } this->CheckFrameBufferStatus(); if(this->OpacityTables!=0 && this->OpacityTables->Vector.size()!=numberOfLevels) { delete this->OpacityTables; this->OpacityTables=0; } if(this->OpacityTables==0) { this->OpacityTables=new vtkOpacityTables(numberOfLevels); } // debug code // DO NOT REMOVE the following commented line // this->ValidateProgram(); glCullFace (GL_BACK); // otherwise, we are rendering back face to initialize the zbuffer. if(!this->GeneratingCanonicalView && this->ReportProgress) { // initialize the time to avoid a progress event at the beginning. this->LastProgressEventTime=vtkTimerLog::GetUniversalTime(); } this->PrintError("PreRender end"); } //----------------------------------------------------------------------------- // Compute how each axis of a cell is projected on the viewport in pixel. // This requires to have information about the camera and about the volume. // It set the value of IgnoreSampleDistancePerPixel to true in case of // degenerated case (axes aligned with the view). //----------------------------------------------------------------------------- double vtkMitkOpenGLGPUVolumeRayCastMapper::ComputeMinimalSampleDistancePerPixel( vtkRenderer *renderer, vtkVolume *volume) { // For each of the 3 directions of a cell, compute the step in z // (world coordinate, not eye/camera coordinate) // to go to the next pixel in x. // Same for the next pixel in y. // Keep the minimum of both zstep // Then keep the minimum for the 3 directions. // in case of either the numerator or the denominator of each ratio is 0. this->IgnoreSampleDistancePerPixel=true; double result=0.0; vtkMatrix4x4 *worldToDataset=volume->GetMatrix(); vtkCamera *camera=renderer->GetActiveCamera(); vtkMatrix4x4 *eyeToWorld=camera->GetViewTransformMatrix(); vtkMatrix4x4 *eyeToDataset=vtkMatrix4x4::New(); vtkMatrix4x4::Multiply4x4(eyeToWorld,worldToDataset,eyeToDataset); int usize; int vsize; renderer->GetTiledSize(&usize,&vsize); vtkMatrix4x4 *viewportToEye=camera->GetProjectionTransformMatrix( usize/static_cast(vsize),0.0,1.0); double volBounds[6]; this->GetInput()->GetBounds(volBounds); int dims[3]; this->GetInput()->GetDimensions(dims); double v0[4]; v0[0]=volBounds[0]; v0[1]=volBounds[2]; v0[2]=volBounds[4]; v0[3]=1.0; double w0[4]; eyeToDataset->MultiplyPoint(v0,w0); double z0; if(w0[3]!=0.0) { z0=w0[2]/w0[3]; } else { z0=0.0; vtkGenericWarningMacro( "eyeToWorld transformation has some projective component." ); } double p0[4]; viewportToEye->MultiplyPoint(w0,p0); p0[0]/=p0[3]; p0[1]/=p0[3]; p0[2]/=p0[3]; bool inFrustum=p0[0]>=-1.0 && p0[0]<=1.0 && p0[1]>=-1.0 && p0[1]<=1.0 && p0[2]>=-1.0 && p0[2]<=1.0; if(inFrustum) { int dim=0; while(dim<3) { double v1[4]; int coord=0; while(coord<3) { if(coord==dim) { v1[coord]=volBounds[2*coord+1]; } else { v1[coord]=volBounds[2*coord]; // same as v0[coord]; } ++coord; } v1[3]=1.0; double w1[4]; eyeToDataset->MultiplyPoint(v1,w1); double z1; if(w1[3]!=0.0) { z1=w1[2]/w1[3]; } else { z1=0.0; vtkGenericWarningMacro( "eyeToWorld transformation has some projective component." ); } double p1[4]; viewportToEye->MultiplyPoint(w1,p1); p1[0]/=p1[3]; p1[1]/=p1[3]; p1[2]/=p1[3]; inFrustum=p1[0]>=-1.0 && p1[0]<=1.0 && p1[1]>=-1.0 && p1[1]<=1.0 && p1[2]>=-1.0 && p1[2]<=1.0; if(inFrustum) { double dx=fabs(p1[0]-p0[0]); double dy=fabs(p1[1]-p0[1]); double dz=fabs(z1-z0); dz=dz/(dims[dim]-1); dx=dx/(dims[dim]-1)*usize; dy=dy/(dims[dim]-1)*vsize; if(dz!=0.0) { if(dx!=0.0) { double d=dz/dx; if(!this->IgnoreSampleDistancePerPixel) { if(result>d) { result=d; } } else { this->IgnoreSampleDistancePerPixel=false; result=d; } } if(dy!=0.0) { double d=dz/dy; if(!this->IgnoreSampleDistancePerPixel) { if(result>d) { result=d; } } else { this->IgnoreSampleDistancePerPixel=false; result=d; } } } } ++dim; } } eyeToDataset->Delete(); if(this->IgnoreSampleDistancePerPixel) { // cout<<"ignore SampleDistancePerPixel"<ValidateProgram(); this->PrintError("before render"); if(!this->Cropping) { this->RenderWholeVolume(ren,vol); } else { this->ClipCroppingRegionPlanes(); this->RenderRegions(ren,vol); } this->PrintError("after render"); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::PostRender( vtkRenderer *ren, int numberOfScalarComponents) { this->PrintError("PostRender1"); if(this->NumberOfCroppingRegions>1) { if(this->BlendMode==vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND || this->BlendMode==vtkMitkGPUVolumeRayCastMapper::MINIMUM_INTENSITY_BLEND) { vtkgl::ActiveTexture( vtkgl::TEXTURE5 ); glBindTexture(GL_TEXTURE_2D,0); } if(this->LastRayCastMethod!=vtkMitkOpenGLGPUVolumeRayCastMapperMethodMIP && this->LastRayCastMethod!=vtkMitkOpenGLGPUVolumeRayCastMapperMethodMinIP) { vtkgl::ActiveTexture( vtkgl::TEXTURE4 ); glBindTexture(GL_TEXTURE_2D,0); } } // noisetexture vtkgl::ActiveTexture(vtkgl::TEXTURE6); glBindTexture(GL_TEXTURE_2D,0); // depthtexture vtkgl::ActiveTexture(vtkgl::TEXTURE3); glBindTexture(GL_TEXTURE_2D,0); // opacity vtkgl::ActiveTexture(vtkgl::TEXTURE2); glBindTexture(GL_TEXTURE_1D,0); if(numberOfScalarComponents==1) { vtkgl::ActiveTexture(vtkgl::TEXTURE1); glBindTexture(GL_TEXTURE_1D,0); } // mask, if any if(this->MaskInput!=0) { vtkgl::ActiveTexture(vtkgl::TEXTURE7); glBindTexture(vtkgl::TEXTURE_3D_EXT,0); } // back to active texture 0. vtkgl::ActiveTexture(vtkgl::TEXTURE0); glBindTexture(vtkgl::TEXTURE_3D_EXT,0); vtkgl::UseProgram(0); this->PrintError("after UseProgram(0)"); this->CleanupRender(); this->PrintError("after CleanupRender"); vtkgl::BindFramebufferEXT(vtkgl::FRAMEBUFFER_EXT, static_cast(this->SavedFrameBuffer)); this->SavedFrameBuffer=0; // Undo the viewport change we made to reduce resolution int size[2]; int lowerLeft[2]; ren->GetTiledSizeAndOrigin(size,size+1,lowerLeft,lowerLeft+1); glViewport(lowerLeft[0],lowerLeft[1], size[0], size[1]); glEnable( GL_SCISSOR_TEST ); glScissor(lowerLeft[0],lowerLeft[1], size[0], size[1]); // Render the texture to the screen - this copies the offscreen buffer // onto the screen as a texture mapped polygon this->RenderTextureToScreen(ren); this->PrintError("after RenderTextureToScreen"); glEnable(GL_DEPTH_TEST); glPopAttrib(); // restore the blending mode and function glFinish(); this->PrintError("PostRender2"); } //----------------------------------------------------------------------------- // The main render method called from the superclass //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer *ren, vtkVolume *vol) { // We've already checked that we have input vtkImageData *input = this->GetTransformedInput(); // Get the bounds of this data double bounds[6]; this->GetBounds(bounds); // Get the scalar range. First we have to get the scalars. double range[2]; vtkDataArray *scalars=this->GetScalars(input,this->ScalarMode, this->ArrayAccessMode, this->ArrayId,this->ArrayName, this->CellFlag); // How many components are there? int numberOfScalarComponents=scalars->GetNumberOfComponents(); // If it is just one, then get the range from the scalars if(numberOfScalarComponents==1) { // Warning: here, we ignore the blank cells. scalars->GetRange(range); } // If it is 3, then use the 4th component's range since that is // the component that will be passed through the scalar opacity // transfer function to look up opacity else { // Note that we've already checked data type and we know this is // unsigned char scalars->GetRange(range,3); } // The rendering work has been broken into 3 stages to support AMR // volume rendering in blocks. Here we are simply rendering the // whole volume as one block. Note that if the volume is too big // to fix into texture memory, it will be streamed through in the // RenderBlock method. this->PreRender(ren,vol,bounds,range,numberOfScalarComponents,1); if(!this->OpacityTables) this->PreRender(ren,vol,bounds,range,numberOfScalarComponents,1); if(this->LoadExtensionsSucceeded) { this->RenderBlock(ren,vol,0); this->PostRender(ren,numberOfScalarComponents); } // Let's just make sure no OpenGL errors occurred during this render this->PrintError("End GPU Render"); // If this isn't a canonical view render, then update the progress to // 1 because we are done. if (!this->GeneratingCanonicalView ) { double progress=1.0; this->InvokeEvent(vtkCommand::VolumeMapperRenderProgressEvent,&progress); ren->GetRenderWindow()->MakeCurrent(); } } //----------------------------------------------------------------------------- // Render a the whole volume. // \pre this->ProgramShader!=0 and is linked. //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::RenderWholeVolume(vtkRenderer *ren, vtkVolume *vol) { double volBounds[6]; this->GetTransformedInput()->GetBounds(volBounds); this->RenderSubVolume(ren,volBounds,vol); } //----------------------------------------------------------------------------- // Sort regions from front to back. //----------------------------------------------------------------------------- class vtkRegionDistance2 { public: size_t Id; // 0<=Id<27 // square distance between camera center to region center: >=0 double Distance2; }; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- extern "C" int vtkRegionComparisonFunction(const void *x, const void *y) { double dx=static_cast(x)->Distance2; double dy=static_cast(y)->Distance2; int result; if(dxdy) { result=1; } else { result=0; } } return result; } //----------------------------------------------------------------------------- // Render a subvolume. // \pre this->ProgramShader!=0 and is linked. //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::RenderRegions(vtkRenderer *ren, vtkVolume *vol) { double bounds[27][6]; double distance2[27]; double camPos[4]; ren->GetActiveCamera()->GetPosition(camPos); double volBounds[6]; this->GetInput()->GetBounds(volBounds); // Pass camera through inverse volume matrix // so that we are in the same coordinate system vol->GetMatrix( this->InvVolumeMatrix ); camPos[3] = 1.0; this->InvVolumeMatrix->Invert(); this->InvVolumeMatrix->MultiplyPoint( camPos, camPos ); if ( camPos[3] ) { camPos[0] /= camPos[3]; camPos[1] /= camPos[3]; camPos[2] /= camPos[3]; } // These are the region limits for x (first four), y (next four) and // z (last four). The first region limit is the lower bound for // that axis, the next two are the region planes along that axis, and // the final one in the upper bound for that axis. double limit[12]; size_t i; for ( i = 0; i < 3; i++ ) { limit[i*4 ] = volBounds[i*2]; limit[i*4+1] = this->ClippedCroppingRegionPlanes[i*2]; limit[i*4+2] = this->ClippedCroppingRegionPlanes[i*2+1]; limit[i*4+3] = volBounds[i*2+1]; } // For each of the 27 possible regions, find out if it is enabled, // and if so, compute the bounds and the distance from the camera // to the center of the region. size_t numRegions = 0; size_t region; for ( region = 0; region < 27; region++ ) { int regionFlag = 1<CroppingRegionFlags & regionFlag ) { // what is the coordinate in the 3x3x3 grid size_t loc[3]; loc[0] = region%3; loc[1] = (region/3)%3; loc[2] = (region/9)%3; // make sure the cropping region is not empty NEW // otherwise, we skip the region. if((limit[loc[0]]!=limit[loc[0]+1]) && (limit[loc[1]+4]!=limit[loc[1]+5]) && (limit[loc[2]+8]!=limit[loc[2]+9])) { // compute the bounds and center double center[3]; for ( i = 0; i < 3; i++ ) { bounds[numRegions][i*2 ] = limit[4*i+loc[i]]; bounds[numRegions][i*2+1] = limit[4*i+loc[i]+1]; center[i]=(bounds[numRegions][i*2]+bounds[numRegions][i*2+1])*0.5; } // compute the distance squared to the center distance2[numRegions] = (camPos[0]-center[0])*(camPos[0]-center[0]) + (camPos[1]-center[1])*(camPos[1]-center[1]) + (camPos[2]-center[2])*(camPos[2]-center[2]); // we've added one region numRegions++; } } } vtkRegionDistance2 regions[27]; i=0; while(iNumberOfCroppingRegions>=0); } //----------------------------------------------------------------------------- // slabsDataSet are position of the slabs in dataset coordinates. // slabsPoints are position of the slabs in points coordinates. // For instance, slabsDataSet[0] is the position of the plane bounding the slab // on the left of x axis of the dataset. slabsPoints[0]=0.3 means that // this plane lies between point 0 and point 1 along the x-axis. // There is no clamping/clipping according to the dataset bounds so, // slabsPoints can be negative or excess the number of points along the // corresponding axis. //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::SlabsFromDatasetToIndex( double slabsDataSet[6], double slabsPoints[6]) { double *spacing=this->GetInput()->GetSpacing(); double origin[3]; // take spacing sign into account double *bds = this->GetInput()->GetBounds(); origin[0] = bds[0]; origin[1] = bds[2]; origin[2] = bds[4]; int i=0; while(i<6) { slabsPoints[i]=(slabsDataSet[i] - origin[i/2]) / spacing[i/2]; ++i; } } //----------------------------------------------------------------------------- // slabsDataSet are position of the slabs in dataset coordinates. // slabsPoints are position of the slabs in points coordinates. // For instance, slabsDataSet[0] is the position of the plane bounding the slab // on the left of x axis of the dataset. slabsPoints[0]=0.3 means that // this plane lies between point 0 and point 1 along the x-axis. // There is no clamping/clipping according to the dataset bounds so, // slabsPoints can be negative or excess the number of points along the // corresponding axis. //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::SlabsFromIndexToDataset( double slabsPoints[6], double slabsDataSet[6]) { double *spacing=this->GetInput()->GetSpacing(); double origin[3]; // take spacing sign into account double *bds = this->GetInput()->GetBounds(); origin[0] = bds[0]; origin[1] = bds[2]; origin[2] = bds[4]; int i=0; while(i<6) { slabsDataSet[i]=slabsPoints[i]*spacing[i/2]+origin[i/2]; ++i; } } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- class vtkStreamBlock { public: double Bounds[6]; double Extent[6]; }; //----------------------------------------------------------------------------- // Render a subvolume. bounds are in world coordinates. // \pre this->ProgramShader!=0 and is linked. //----------------------------------------------------------------------------- int vtkMitkOpenGLGPUVolumeRayCastMapper::RenderSubVolume(vtkRenderer *ren, double bounds[6], vtkVolume *volume) { // Time to load scalar field size_t i; int wholeTextureExtent[6]; this->GetTransformedInput()->GetExtent(wholeTextureExtent); if(this->CellFlag) { i=1; while(i<6) { wholeTextureExtent[i]--; i+=2; } } // 1. Found out the extent of the subvolume double realExtent[6]; int subvolumeTextureExtent[6]; this->SlabsFromDatasetToIndex(bounds,realExtent); if(this->CellFlag) // 3D texture are celldata { // texture extents are expressed in cells in this case i=0; while(i<6) { subvolumeTextureExtent[i]=vtkMath::Floor(realExtent[i]-0.5); ++i; subvolumeTextureExtent[i]=vtkMath::Floor(realExtent[i]-0.5)+1; ++i; } } else { // texture extents are expressed in points in this case i=0; while(i<6) { subvolumeTextureExtent[i]=vtkMath::Floor(realExtent[i]); ++i; subvolumeTextureExtent[i]=vtkMath::Floor(realExtent[i])+1; // used to not have +1 ++i; } } i=0; while(i<6) { assert("check: wholeTextureExtent" && wholeTextureExtent[i]==0); if(subvolumeTextureExtent[i]wholeTextureExtent[i]) { subvolumeTextureExtent[i]=wholeTextureExtent[i]; } ++i; } assert("check: subvolume_inside_wholevolume" && subvolumeTextureExtent[0]>=wholeTextureExtent[0] && subvolumeTextureExtent[1]<=wholeTextureExtent[1] && subvolumeTextureExtent[2]>=wholeTextureExtent[2] && subvolumeTextureExtent[3]<=wholeTextureExtent[3] && subvolumeTextureExtent[4]>=wholeTextureExtent[4] && subvolumeTextureExtent[5]<=wholeTextureExtent[5]); // 2. Is this subvolume already on the GPU? // ie are the extent of the subvolume inside the loaded extent? // Find the texture (and mask). vtkstd::map::iterator it= this->ScalarsTextures->Map.find(this->GetTransformedInput()); vtkKWScalarField *texture; if(it==this->ScalarsTextures->Map.end()) { texture=0; } else { texture=(*it).second; } vtkKWMask *mask=0; if(this->MaskInput!=0) { vtkstd::map::iterator it2= this->MaskTextures->Map.find(this->MaskInput); if(it2==this->MaskTextures->Map.end()) { mask=0; } else { mask=(*it2).second; } } int loaded = texture!=0 && texture->IsLoaded() && this->GetTransformedInput()->GetMTime()<=texture->GetBuildTime() && (this->GetMaskInput() ? this->GetMaskInput()->GetMTime() <= texture->GetBuildTime() : true) && texture->GetLoadedCellFlag()==this->CellFlag; vtkIdType *loadedExtent; if(loaded) { loadedExtent=texture->GetLoadedExtent(); i=0; while(loaded && i<6) { loaded=loaded && loadedExtent[i]<=subvolumeTextureExtent[i]; ++i; loaded=loaded && loadedExtent[i]>=subvolumeTextureExtent[i]; ++i; } } if(loaded) { this->CurrentScalar=texture; vtkgl::ActiveTexture(vtkgl::TEXTURE0); this->CurrentScalar->Bind(); vtkgl::ActiveTexture(vtkgl::TEXTURE7); this->CurrentMask=mask; if(this->CurrentMask!=0) { this->CurrentMask->Bind(); } } if(!loaded) { // 3. Not loaded: try to load the whole dataset if(!this->LoadScalarField(this->GetTransformedInput(),this->MaskInput,wholeTextureExtent,volume)) { // 4. loading the whole dataset failed: try to load the subvolume if(!this->LoadScalarField(this->GetTransformedInput(),this->MaskInput, subvolumeTextureExtent, volume)) { // 5. loading the subvolume failed: stream the subvolume // 5.1 do zslabs first, if too large then cut with x or y with the // largest dimension. order of zlabs depends on sign of spacing[2] int streamTextureExtent[6]; i=0; while(i<6) { streamTextureExtent[i]=subvolumeTextureExtent[i]; ++i; } unsigned int internalFormat; unsigned int format; unsigned int type; int componentSize; this->GetTextureFormat(this->GetInput(),&internalFormat,&format,&type, &componentSize); // Enough memory? int originalTextureSize[3]; int textureSize[3]; i=0; while(i<3) { textureSize[i]=subvolumeTextureExtent[2*i+1]-subvolumeTextureExtent[2*i]+1; originalTextureSize[i]=textureSize[i]; ++i; } // Make sure loading did not fail because of theorical limits GLint width; glGetIntegerv(vtkgl::MAX_3D_TEXTURE_SIZE,&width); int clippedXY=0; int clippedZ=0; if(textureSize[0]>width) { textureSize[0]=width; clippedXY=1; } if(textureSize[1]>width) { textureSize[1]=width; clippedXY=1; } if(textureSize[2]>width) { textureSize[2]=width; clippedZ=1; } int minSize; if(this->CellFlag) { minSize=1; } else { minSize=2; } if(clippedXY) { // We cannot expect to first divide as z-slabs because it is already // clipped in another dimension. From now, just divide in the largest // dimension. bool foundSize=false; while(!foundSize && textureSize[0]>=minSize && textureSize[1]>=minSize) { foundSize=this->TestLoadingScalar(internalFormat,format,type, textureSize,componentSize); if(!foundSize) { int maxDim=0; if(textureSize[1]>textureSize[0]) { maxDim=1; } if(textureSize[2]>textureSize[maxDim]) { maxDim=2; } textureSize[maxDim]>>=1; // /=2 } } } else { // we are in cropping mode, it will be slow anyway. the case we want // to optimize is stream the all scalar field. With that in mine, // it is better to first try to send z-slabs. If even a minimal // z-slab is too big, we have to divide by x or y dimensions. In // this case, it will be slow and we can choose to keep blocks as // square as possible by dividing by the largest dimension at each // iteration. if(!clippedZ) { // we start by subdividing only if we did not already clipped // the z dimension according to the theorical limits. textureSize[2]>>=1; // /=2 } bool foundSize=false; while(!foundSize && textureSize[2]>=minSize) { foundSize=this->TestLoadingScalar(internalFormat,format,type, textureSize,componentSize); if(!foundSize) { textureSize[2]>>=1; // /=2 } } if(!foundSize) { textureSize[2]=minSize; if(textureSize[0]>textureSize[1]) { textureSize[0]>>=1; // /=2 } else { textureSize[1]>>=1; // /=2 } while(!foundSize && textureSize[0]>=minSize && textureSize[1]>=minSize) { foundSize=this->TestLoadingScalar(internalFormat,format,type, textureSize,componentSize); if(!foundSize) { if(textureSize[0]>textureSize[1]) { textureSize[0]>>=1; // /=2 } else { textureSize[1]>>=1; // /=2 } } } } if(!foundSize) { vtkErrorMacro( <<"No memory left on the GPU even for a minimal block."); return 1; // abort } } // except for the last bound. // front to back ordering // Pass camera through inverse volume matrix // so that we are in the same coordinate system double camPos[4]; vtkCamera *cam = ren->GetActiveCamera(); cam->GetPosition(camPos); volume->GetMatrix( this->InvVolumeMatrix ); camPos[3] = 1.0; this->InvVolumeMatrix->Invert(); this->InvVolumeMatrix->MultiplyPoint( camPos, camPos ); if ( camPos[3] ) { camPos[0] /= camPos[3]; camPos[1] /= camPos[3]; camPos[2] /= camPos[3]; } // 5.2 iterate of each stream of the subvolume and render it: // point scalar: on the first block, the first point is not shared // blockExtent is always expressed in point, not in texture // extent. size_t remainder[3]; i=0; while(i<3) { remainder[i]=static_cast( (originalTextureSize[i]-textureSize[i])%(textureSize[i]-1)); if(remainder[i]>0) { remainder[i]=1; } ++i; } size_t counts[3]; counts[0]=static_cast((originalTextureSize[0]-textureSize[0]) /(textureSize[0]-1)); counts[0]+=remainder[0]+1; counts[1]=static_cast((originalTextureSize[1]-textureSize[1]) /(textureSize[1]-1)); counts[1]+=remainder[1]+1; counts[2]=static_cast((originalTextureSize[2]-textureSize[2]) /(textureSize[2]-1)); counts[2]+=remainder[2]+1; size_t count=counts[0]*counts[1]*counts[2]; double blockExtent[6]; vtkStreamBlock *blocks=new vtkStreamBlock[count]; vtkRegionDistance2 *sortedBlocks=new vtkRegionDistance2[count]; // iterate over z,y,x size_t blockId=0; size_t zIndex=0; blockExtent[4]=realExtent[4]; blockExtent[5]=vtkMath::Floor(blockExtent[4])+textureSize[2]; if(!this->CellFlag) { blockExtent[5]--; } if(blockExtent[5]>realExtent[5]) { blockExtent[5]=realExtent[5]; } while(zIndexCellFlag) { blockExtent[3]--; } if(blockExtent[3]>realExtent[3]) { blockExtent[3]=realExtent[3]; } size_t yIndex=0; while(yIndexCellFlag) { blockExtent[1]--; } if(blockExtent[1]>realExtent[1]) { blockExtent[1]=realExtent[1]; } size_t xIndex=0; while(xIndexSlabsFromIndexToDataset(blockExtent,blockBounds); // compute the bounds and center double center[3]; i=0; while(i<3) { center[i]=(blockBounds[i*2]+blockBounds[i*2+1])*0.5; ++i; } // compute the distance squared to the center double distance2=(camPos[0]-center[0])*(camPos[0]-center[0])+ (camPos[1]-center[1])*(camPos[1]-center[1]) + (camPos[2]-center[2])*(camPos[2]-center[2]); i=0; while(i<6) { blocks[blockId].Bounds[i]=blockBounds[i]; blocks[blockId].Extent[i]=blockExtent[i]; ++i; } sortedBlocks[blockId].Id=blockId; sortedBlocks[blockId].Distance2=distance2; ++blockId; blockExtent[0]=blockExtent[1]; blockExtent[1]=blockExtent[0]+textureSize[0]; if(!this->CellFlag) { blockExtent[1]--; } if(blockExtent[1]>realExtent[1]) { blockExtent[1]=realExtent[1]; } ++xIndex; } // while x blockExtent[2]=blockExtent[3]; blockExtent[3]=blockExtent[2]+textureSize[1]; if(!this->CellFlag) { blockExtent[3]--; } if(blockExtent[3]>realExtent[3]) { blockExtent[3]=realExtent[3]; } ++yIndex; } // while y blockExtent[4]=blockExtent[5]; blockExtent[5]=blockExtent[4]+textureSize[2]; if(!this->CellFlag) { blockExtent[5]--; } if(blockExtent[5]>realExtent[5]) { blockExtent[5]=realExtent[5]; } ++zIndex; } // while z assert("check: valid_number_of_blocks" && blockId==count); qsort(sortedBlocks,static_cast(count), sizeof(vtkRegionDistance2), vtkRegionComparisonFunction); // loop over all blocks we need to render i=0; int abort=0; while(!abort && i < count) // 1) //count) { size_t k=sortedBlocks[i].Id; int blockTextureExtent[6]; int j; if(this->CellFlag) // 3D texture are celldata { // texture extents are expressed in cells in this case j=0; while(j<6) { blockTextureExtent[j]=vtkMath::Floor(blocks[k].Extent[j]); ++j; } } else { // texture extents are expressed in points in this case j=0; while(j<6) { blockTextureExtent[j]=vtkMath::Floor(blocks[k].Extent[j]); ++j; blockTextureExtent[j]=vtkMath::Floor(blocks[k].Extent[j]); if(blockTextureExtent[j]LoadScalarField(this->GetInput(),this->MaskInput, blockTextureExtent, volume)) { cout<<"Loading the streamed block FAILED!!!!!"<CurrentScalar->GetLoadedExtent(); float lowBounds[3]; float highBounds[3]; if(!this->CurrentScalar->GetLoadedCellFlag()) // points { j=0; while(j<3) { double delta= static_cast(loadedExtent[j*2+1]-loadedExtent[j*2]); lowBounds[j]=static_cast((blocks[k].Extent[j*2]-static_cast(loadedExtent[j*2]))/delta); highBounds[j]=static_cast((blocks[k].Extent[j*2+1]-static_cast(loadedExtent[j*2]))/delta); ++j; } } else // cells { j=0; while(j<3) { double delta= static_cast(loadedExtent[j*2+1]-loadedExtent[j*2]); lowBounds[j]=static_cast((blocks[k].Extent[j*2]-0.5-static_cast(loadedExtent[j*2]))/delta); highBounds[j]=static_cast((blocks[k].Extent[j*2+1]-0.5-static_cast(loadedExtent[j*2]))/delta); ++j; } } // bounds have to be normalized. There are used in the shader // as bounds to a value used to sample a texture. assert("check: positive_low_bounds0" && lowBounds[0]>=0.0); assert("check: positive_low_bounds1" && lowBounds[1]>=0.0); assert("check: positive_low_bounds2" && lowBounds[2]>=0.0); assert("check: increasing_bounds0" && lowBounds[0]<=highBounds[0]); assert("check: increasing_bounds1" && lowBounds[1]<=highBounds[1]); assert("check: increasing_bounds2" && lowBounds[2]<=highBounds[2]); assert("check: high_bounds0_less_than1" && highBounds[0]<=1.0); assert("check: high_bounds1_less_than1" && highBounds[1]<=1.0); assert("check: high_bounds2_less_than1" && highBounds[2]<=1.0); GLint lb; lb=vtkgl::GetUniformLocation(static_cast(this->ProgramShader), "lowBounds"); this->PrintError("get uniform low bounds"); if(lb!=-1) { vtkgl::Uniform3f(lb, lowBounds[0],lowBounds[1],lowBounds[2]); this->PrintError("set uniform low bounds"); } else { vtkErrorMacro(<<" lowBounds is not a uniform variable."); } GLint hb; hb=vtkgl::GetUniformLocation(static_cast(this->ProgramShader), "highBounds"); this->PrintError("get uniform high bounds"); if(hb!=-1) { vtkgl::Uniform3f(hb, highBounds[0],highBounds[1],highBounds[2]); this->PrintError("set uniform high bounds"); } else { vtkErrorMacro(<<" highBounds is not a uniform variable."); } this->PrintError("uniform low/high bounds block"); // other sub-volume rendering code this->LoadProjectionParameters(ren,volume); this->ClipBoundingBox(ren,blocks[k].Bounds,volume); abort=this->RenderClippedBoundingBox(1,i,count,ren->GetRenderWindow()); if (!abort) { this->CopyFBOToTexture(); } this->PrintError("render clipped block 1"); ++i; } delete[] blocks; delete[] sortedBlocks; return abort; } } } loadedExtent=this->CurrentScalar->GetLoadedExtent(); // low bounds and high bounds are in texture coordinates. float lowBounds[3]; float highBounds[3]; if(!this->CurrentScalar->GetLoadedCellFlag()) // points { i=0; while(i<3) { double delta= static_cast(loadedExtent[i*2+1]-loadedExtent[i*2]+1); lowBounds[i]=static_cast((realExtent[i*2]+0.5-static_cast(loadedExtent[i*2]))/delta); highBounds[i]=static_cast((realExtent[i*2+1]+0.5-static_cast(loadedExtent[i*2]))/delta); ++i; } } else // cells { i=0; while(i<3) { double delta= static_cast(loadedExtent[i*2+1]-loadedExtent[i*2]+1); // this->LoadedExtent[i*2]==0, texcoord starts at 0, if realExtent==0 // otherwise, texcoord start at 1/2N // this->LoadedExtent[i*2]==wholeTextureExtent[i*2+1], texcoord stops at 1, if realExtent==wholeTextureExtent[i*2+1]+1 // otherwise it stop at 1-1/2N // N is the number of texels in the loadedtexture not the number of // texels in the whole texture. lowBounds[i]=static_cast((realExtent[i*2]-static_cast(loadedExtent[i*2]))/delta); highBounds[i]=static_cast((realExtent[i*2+1]-static_cast(loadedExtent[i*2]))/delta); ++i; } } assert("check: positive_low_bounds0" && lowBounds[0]>=0.0); assert("check: positive_low_bounds1" && lowBounds[1]>=0.0); assert("check: positive_low_bounds2" && lowBounds[2]>=0.0); assert("check: increasing_bounds0" && lowBounds[0]<=highBounds[0]); assert("check: increasing_bounds1" && lowBounds[1]<=highBounds[1]); assert("check: increasing_bounds2" && lowBounds[2]<=highBounds[2]); assert("check: high_bounds0_less_than1" && highBounds[0]<=1.0); assert("check: high_bounds1_less_than1" && highBounds[1]<=1.0); assert("check: high_bounds2_less_than1" && highBounds[2]<=1.0); GLint lb; lb=vtkgl::GetUniformLocation(static_cast(this->ProgramShader), "lowBounds"); this->PrintError("get uniform low bounds"); if(lb!=-1) { vtkgl::Uniform3f(lb, lowBounds[0],lowBounds[1],lowBounds[2]); this->PrintError("set uniform low bounds"); } else { vtkErrorMacro(<<" lowBounds is not a uniform variable."); } GLint hb; hb=vtkgl::GetUniformLocation(static_cast(this->ProgramShader), "highBounds"); this->PrintError("get uniform high bounds"); if(hb!=-1) { vtkgl::Uniform3f(hb, highBounds[0],highBounds[1],highBounds[2]); this->PrintError("set uniform high bounds"); } else { vtkErrorMacro(<<" highBounds is not a uniform variable."); } this->PrintError("uniform low/high bounds"); // other sub-volume rendering code this->LoadProjectionParameters(ren,volume); this->ClipBoundingBox(ren,bounds,volume); int abort=this->RenderClippedBoundingBox(1,0,1,ren->GetRenderWindow()); if (!abort) { this->CopyFBOToTexture(); } this->PrintError("render clipped 1"); return abort; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::LoadProjectionParameters( vtkRenderer *ren, vtkVolume *vol) { vtkMatrix4x4 *worldToDataset=vol->GetMatrix(); vtkMatrix4x4 *datasetToWorld=this->TempMatrix[0]; vtkMatrix4x4::Invert(worldToDataset,datasetToWorld); double *bounds=this->CurrentScalar->GetLoadedBounds(); double dx=bounds[1]-bounds[0]; double dy=bounds[3]-bounds[2]; double dz=bounds[5]-bounds[4]; // worldToTexture matrix is needed // Compute change-of-coordinate matrix from world space to texture space. vtkMatrix4x4 *worldToTexture=this->TempMatrix[2]; vtkMatrix4x4 *datasetToTexture=this->TempMatrix[1]; // Set the matrix datasetToTexture->Zero(); datasetToTexture->SetElement(0,0,dx); datasetToTexture->SetElement(1,1,dy); datasetToTexture->SetElement(2,2,dz); datasetToTexture->SetElement(3,3,1.0); datasetToTexture->SetElement(0,3,bounds[0]); datasetToTexture->SetElement(1,3,bounds[2]); datasetToTexture->SetElement(2,3,bounds[4]); // worldToTexture=worldToDataSet*dataSetToTexture vtkMatrix4x4::Multiply4x4(worldToDataset,datasetToTexture,worldToTexture); // NEW int parallelProjection=ren->GetActiveCamera()->GetParallelProjection(); // cout << "actualSampleDistance=" << this->ActualSampleDistance << endl; if(parallelProjection) { // Unit vector of the direction of projection in world space. double dirWorld[4]; double dir[4]; ren->GetActiveCamera()->GetDirectionOfProjection(dirWorld); dirWorld[3]=0.0; // direction in dataset space. datasetToWorld->MultiplyPoint(dirWorld,dir); // incremental vector: // direction in texture space times sample distance in world space. dir[0]=dir[0]*this->ActualSampleDistance/dx; dir[1]=dir[1]*this->ActualSampleDistance/dy; dir[2]=dir[2]*this->ActualSampleDistance/dz; GLint rayDir; rayDir=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"parallelRayDirection"); if(rayDir!=-1) { vtkgl::Uniform3f(rayDir,static_cast(dir[0]), static_cast(dir[1]), static_cast(dir[2])); } else { vtkErrorMacro(<<"parallelRayDirection is not a uniform variable."); } //cout<<"rayDir="<GetActiveCamera()->GetPosition(cameraPosWorld); cameraPosWorld[3]=1.0; // we use homogeneous coordinates. datasetToWorld->MultiplyPoint(cameraPosWorld,cameraPosDataset); // From homogeneous to cartesian coordinates. if(cameraPosDataset[3]!=1.0) { double ratio=1/cameraPosDataset[3]; cameraPosDataset[0]*=ratio; cameraPosDataset[1]*=ratio; cameraPosDataset[2]*=ratio; } cameraPosTexture[0] = (cameraPosDataset[0]-bounds[0])/dx; cameraPosTexture[1] = (cameraPosDataset[1]-bounds[2])/dy; cameraPosTexture[2] = (cameraPosDataset[2]-bounds[4])/dz; // Only make sense for the vectorial part of the homogeneous matrix. // coefMatrix=transposeWorldToTexture*worldToTexture // we re-cycle the datasetToWorld pointer with a different name vtkMatrix4x4 *transposeWorldToTexture=this->TempMatrix[1]; // transposeWorldToTexture={^t}worldToTexture vtkMatrix4x4::Transpose(worldToTexture,transposeWorldToTexture); vtkMatrix4x4 *coefMatrix=this->TempMatrix[1]; vtkMatrix4x4::Multiply4x4(transposeWorldToTexture,worldToTexture, coefMatrix); GLint uCameraPosition; uCameraPosition=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"cameraPosition"); if(uCameraPosition!=-1) { vtkgl::Uniform3f(uCameraPosition, static_cast(cameraPosTexture[0]), static_cast(cameraPosTexture[1]), static_cast(cameraPosTexture[2])); } else { vtkErrorMacro(<<"cameraPosition is not a uniform variable."); } GLint uSampleDistance; uSampleDistance=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"sampleDistance"); if(uSampleDistance!=-1) { vtkgl::Uniform1f(uSampleDistance,this->ActualSampleDistance); } else { vtkErrorMacro(<<"sampleDistance is not a uniform variable."); } GLint uMatrix1; uMatrix1=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"matrix1"); if(uMatrix1!=-1) { vtkgl::Uniform3f(uMatrix1, static_cast(coefMatrix->GetElement(0,0)), static_cast(coefMatrix->GetElement(1,1)), static_cast(coefMatrix->GetElement(2,2))); } else { vtkErrorMacro(<<"matrix1 is not a uniform variable."); } GLint uMatrix2; uMatrix2=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"matrix2"); if(uMatrix2!=-1) { vtkgl::Uniform3f(uMatrix2, static_cast(2*coefMatrix->GetElement(0,1)), static_cast(2*coefMatrix->GetElement(1,2)), static_cast(2*coefMatrix->GetElement(0,2))); } else { vtkErrorMacro(<<"matrix2 is not a uniform variable."); } } this->PrintError("after uniforms for projection"); // Change-of-coordinate matrix from Eye space to texture space. vtkMatrix4x4 *eyeToTexture=this->TempMatrix[1]; vtkMatrix4x4 *eyeToWorld=ren->GetActiveCamera()->GetViewTransformMatrix(); vtkMatrix4x4::Multiply4x4(eyeToWorld,worldToTexture,eyeToTexture); GLfloat matrix[16];// used sometimes as 3x3, sometimes as 4x4. double *raw=eyeToTexture->Element[0]; int index; int column; int row; int shadeMethod=this->LastShade; if(shadeMethod==vtkMitkOpenGLGPUVolumeRayCastMapperShadeYes) { index=0; column=0; while(column<3) { row=0; while(row<3) { // cout << "index=" << index << " row*4+column=" << row*4+column << endl; matrix[index]=static_cast(raw[row*4+column]); ++index; ++row; } ++column; } GLint uEyeToTexture3; uEyeToTexture3=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"eyeToTexture3"); this->PrintError("after getUniform eyeToTexture3"); if(uEyeToTexture3!=-1) { vtkgl::UniformMatrix3fv(uEyeToTexture3,1,GL_FALSE,matrix); } else { vtkErrorMacro(<<"eyeToTexture3 is not a uniform variable."); } this->PrintError("after Uniform eyeToTexture3"); index=0; column=0; while(column<4) { row=0; while(row<4) { // cout << "index=" << index << " row*4+column=" << row*4+column << endl; matrix[index]=static_cast(raw[row*4+column]); ++index; ++row; } ++column; } GLint uEyeToTexture4; uEyeToTexture4=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"eyeToTexture4"); if(uEyeToTexture4!=-1) { vtkgl::UniformMatrix4fv(uEyeToTexture4,1,GL_FALSE,matrix); } else { vtkErrorMacro(<<"eyeToTexture4 is not a uniform variable."); } } eyeToTexture->Invert(); index=0; column=0; while(column<4) { row=0; while(row<4) { // cout << "index=" << index << " row*4+column=" << row*4+column << endl; matrix[index]=static_cast(raw[row*4+column]); ++index; ++row; } ++column; } this->PrintError("before GetUniformLocation TextureToEye"); GLint uTextureToEye; uTextureToEye=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"textureToEye"); this->PrintError("after GetUniformLocation TextureToEye"); if(uTextureToEye!=-1) { vtkgl::UniformMatrix4fv(uTextureToEye,1,GL_FALSE,matrix); } else { vtkErrorMacro(<<"textureToEye is not a uniform variable."); } this->PrintError("after UniformMatrxix TextureToEye"); if(shadeMethod==vtkMitkOpenGLGPUVolumeRayCastMapperShadeYes) { eyeToTexture->Transpose(); index=0; column=0; while(column<3) { row=0; while(row<3) { // cout << "index=" << index << " row*4+column=" << row*4+column << endl; matrix[index]=static_cast(raw[row*4+column]); ++index; ++row; } ++column; } GLint uTranposeTextureToEye; uTranposeTextureToEye=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"transposeTextureToEye"); if(uTranposeTextureToEye!=-1) { vtkgl::UniformMatrix3fv(uTranposeTextureToEye,1,GL_FALSE,matrix); } else { vtkErrorMacro(<<"transposeTextureToEye is not a uniform variable."); } float cellScale[3]; // 1/(2*Step) float cellStep[3]; // Step vtkIdType *loadedExtent=this->CurrentScalar->GetLoadedExtent(); cellScale[0]=static_cast(static_cast( loadedExtent[1]-loadedExtent[0])*0.5); cellScale[1]=static_cast(static_cast( loadedExtent[3]-loadedExtent[2])*0.5); cellScale[2]=static_cast(static_cast( loadedExtent[5]-loadedExtent[4])*0.5); cellStep[0]=static_cast(1.0/static_cast( loadedExtent[1]-loadedExtent[0])); cellStep[1]=static_cast(1.0/static_cast( loadedExtent[3]-loadedExtent[2])); cellStep[2]=static_cast(1.0/static_cast( loadedExtent[5]-loadedExtent[4])); GLint uCellScale; uCellScale=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"cellScale"); if(uCellScale!=-1) { vtkgl::Uniform3f(uCellScale,cellScale[0],cellScale[1],cellScale[2]); } else { vtkErrorMacro(<<"error: cellScale is not a uniform variable."); } GLint uCellStep; uCellStep=vtkgl::GetUniformLocation( static_cast(this->ProgramShader),"cellStep"); if(uCellStep!=-1) { vtkgl::Uniform3f(uCellStep,cellStep[0],cellStep[1],cellStep[2]); } else { vtkErrorMacro(<<"error: cellStep is not a uniform variable."); } } } //----------------------------------------------------------------------------- // Concatenate the header string, projection type code and method to the // final fragment code in this->FragmentCode. // \pre valid_raycastMethod: raycastMethod>= // vtkMitkOpenGLGPUVolumeRayCastMapperMethodMIP && // raycastMethod<=vtkMitkOpenGLGPUVolumeRayCastMapperMethodMinIPFourDependent //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::BuildProgram(int parallelProjection, int raycastMethod, int shadeMethod, int componentMethod) { assert("pre: valid_raycastMethod" && raycastMethod>= vtkMitkOpenGLGPUVolumeRayCastMapperMethodMIP && raycastMethod<=vtkMitkOpenGLGPUVolumeRayCastMapperMethodCompositeMask); GLuint fs; // cout<<"projection="<ProgramShader, vtkgl::INFO_LOG_LENGTH,¶ms); if(params>0) { char *buffer=new char[params]; vtkgl::GetProgramInfoLog(this->ProgramShader,params,0,buffer); cout<<"validation log: "<GetEnabledString(glIsEnabled(GL_LIGHTING))<GetEnabledString(glIsEnabled(GL_LIGHTING))<(value); cout<<"active texture is "<<(activeTexture-vtkgl::TEXTURE0)<(value); cout<<"light\t| status\t| ambient\t| diffuse\t| specular\t| position\t| spot direction\t| spot exponent\t| spot cutoff\t| k0\t| k1\t| k2"<=0 // \post valid_result: result>=x //----------------------------------------------------------------------------- int vtkMitkOpenGLGPUVolumeRayCastMapper::PowerOfTwoGreaterOrEqual(int x) { assert("pre: positive_x" && x>=0); int result=1; while(result=x); return result; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::UpdateNoiseTexture() { if(this->NoiseTextureId==0) { GLuint noiseTextureObject; glGenTextures(1,&noiseTextureObject); this->NoiseTextureId=static_cast(noiseTextureObject); vtkgl::ActiveTexture(vtkgl::TEXTURE6); glBindTexture(GL_TEXTURE_2D,noiseTextureObject); GLsizei size=128; // 1024; // Power of two value GLint maxSize; const float factor=0.1f; // const float factor=1.0f; const float amplitude=0.5f*factor; // something positive. // amplitude=0.5. noise between -0.5 +0.5. add some +0.5 shift. glGetIntegerv(GL_MAX_TEXTURE_SIZE,&maxSize); if(size>maxSize) { size=maxSize; } if(this->NoiseTexture!=0 && this->NoiseTextureSize!=size) { delete[] this->NoiseTexture; this->NoiseTexture=0; } if(this->NoiseTexture==0) { this->NoiseTexture=new float[size*size]; this->NoiseTextureSize=size; vtkPerlinNoise *noiseGenerator=vtkPerlinNoise::New(); noiseGenerator->SetFrequency(size,1.0,1.0); noiseGenerator->SetPhase(0.0,0.0,0.0); noiseGenerator->SetAmplitude(amplitude); int j=0; while(jNoiseTexture[j*size+i]=0.0; //amplitude+static_cast(noiseGenerator->EvaluateFunction(i,j,0.0)); ++i; } ++j; } noiseGenerator->Delete(); } glTexImage2D(GL_TEXTURE_2D,0,GL_LUMINANCE,size,size,0,GL_RED,GL_FLOAT, this->NoiseTexture); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT); GLfloat borderColor[4]={0.0,0.0,0.0,0.0}; glTexParameterfv(GL_TEXTURE_2D,GL_TEXTURE_BORDER_COLOR,borderColor); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); vtkgl::ActiveTexture(vtkgl::TEXTURE0); } } // ---------------------------------------------------------------------------- // 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 void vtkMitkOpenGLGPUVolumeRayCastMapper::GetReductionRatio(double ratio[3]) { // Compute texture size int i; int wholeTextureExtent[6]; this->GetInput()->GetExtent(wholeTextureExtent); if(this->CellFlag) // if we deal with cell data { i=1; while(i<6) { wholeTextureExtent[i]--; i+=2; } } // Indexable hardware limits GLint maxSize; glGetIntegerv(vtkgl::MAX_3D_TEXTURE_SIZE,&maxSize); vtkIdType rTextureSize[3]; double dMaxSize=static_cast(maxSize); i=0; while(i<3) { double textureSize=wholeTextureExtent[2*i+1]-wholeTextureExtent[2*i]+1; if(textureSize>maxSize) { ratio[i]=dMaxSize/textureSize; } else { ratio[i]=1.0; // no reduction } rTextureSize[i]=static_cast(floor(textureSize*ratio[i])); ++i; } // Data memory limits. vtkDataArray *scalars=this->GetScalars(this->GetInput(),this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, this->CellFlag); int scalarType=scalars->GetDataType(); vtkIdType size=rTextureSize[0]*rTextureSize[1]*rTextureSize[2] *vtkAbstractArray::GetDataTypeSize(scalarType) *scalars->GetNumberOfComponents(); if(size>static_cast(this->MaxMemoryInBytes) *static_cast(this->MaxMemoryFraction)) { double r=static_cast(this->MaxMemoryInBytes) *static_cast(this->MaxMemoryFraction)/static_cast(size); double r3=pow(r,1.0/3.0); // try the keep reduction ratio uniform to avoid artifacts. bool reduced[3]; i=0; int count=0; while(i<3) { vtkIdType newSize=static_cast( floor(static_cast(rTextureSize[i])*r3)); reduced[i]=newSize>=1; if(reduced[i]) { ++count; } ++i; } if(count<3) // some axis cannot be reduced { double r2=sqrt(r); count=0; i=0; while(i<3) { if(reduced[i]) { vtkIdType newSize=static_cast( floor(static_cast(rTextureSize[i])*r2)); reduced[i]=newSize>=1; if(reduced[i]) { ++count; } } ++i; } if(count<2) // we can only reduce one axis { i=0; while(i<3) { if(reduced[i]) { ratio[i]*=r; } ++i; } } else // we can reduce two axes { i=0; while(i<3) { if(reduced[i]) { ratio[i]*=r2; } ++i; } } } else // we can reduce all three axes { i=0; while(i<3) { ratio[i]*=r3; ++i; } } } assert("post: valid_i_ratio" && ratio[0]>0 && ratio[0]<=1.0); assert("post: valid_j_ratio" && ratio[1]>0 && ratio[1]<=1.0); assert("post: valid_k_ratio" && ratio[2]>0 && ratio[2]<=1.0); } //----------------------------------------------------------------------------- // Standard print method //----------------------------------------------------------------------------- void vtkMitkOpenGLGPUVolumeRayCastMapper::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } -#endif \ No newline at end of file +#endif diff --git a/Modules/MitkExt/Rendering/vtkMitkOpenGLGPUVolumeRayCastMapperShaders.cpp b/Modules/MitkExt/Rendering/vtkMitkOpenGLGPUVolumeRayCastMapperShaders.cpp index ffa82705c9..519cda5672 100644 --- a/Modules/MitkExt/Rendering/vtkMitkOpenGLGPUVolumeRayCastMapperShaders.cpp +++ b/Modules/MitkExt/Rendering/vtkMitkOpenGLGPUVolumeRayCastMapperShaders.cpp @@ -1,1814 +1,1814 @@ /*=================================================================== 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 // Only with VTK 5.6 or above #if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) )) /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_CompositeCroppingFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_CompositeCroppingFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_CompositeCroppingFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_CompositeCroppingFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Implementation of some function used by the composite method when cropping\n" "// is on.\n" "\n" "#version 110\n" "\n" "// color buffer as an input\n" "uniform sampler2D frameBufferTexture;\n" "// 2D Texture fragment coordinates [0,1] from fragment coordinates\n" "// the frame buffer texture has the size of the plain buffer but\n" "// we use a fraction of it. The texture coordinates is less than 1 if\n" "// the reduction factor is less than 1.\n" "vec2 fragTexCoord;\n" "\n" "vec4 initialColor()\n" "{\n" " return texture2D(frameBufferTexture,fragTexCoord);\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_CompositeFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_CompositeFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_CompositeFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_CompositeFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Fragment program part with ray cast and composite method.\n" "\n" "#version 110\n" "\n" "uniform sampler3D dataSetTexture;\n" "uniform sampler1D opacityTexture;\n" "\n" "uniform vec3 lowBounds;\n" "uniform vec3 highBounds;\n" "\n" "// Entry position (global scope)\n" "vec3 pos;\n" "// Incremental vector in texture space (global scope)\n" "vec3 rayDir;\n" "\n" "float tMax;\n" "\n" "// from cropping vs no cropping\n" "vec4 initialColor();\n" "\n" "// from 1 vs 4 component shader.\n" "float scalarFromValue(vec4 value);\n" "vec4 colorFromValue(vec4 value);\n" "\n" "// from noshade vs shade.\n" "void initShade();\n" "vec4 shade(vec4 value);\n" "\n" "void trace(void)\n" "{\n" " vec4 destColor=initialColor();\n" " float remainOpacity=1.0-destColor.a;\n" "\n" " bool inside=true;\n" " \n" " vec4 color;\n" " vec4 opacity;\n" "\n" " initShade();\n" " \n" " float t=0.0;\n" " \n" " // We NEED two nested while loops. It is trick to work around hardware\n" " // limitation about the maximum number of loops.\n" "\n" " while(inside)\n" " { \n" " while(inside)\n" " {\n" " vec4 value=texture3D(dataSetTexture,pos);\n" " float scalar=scalarFromValue(value);\n" " // opacity is the sampled texture value in the 1D opacity texture at\n" " // scalarValue\n" " opacity=texture1D(opacityTexture,scalar);\n" " if(opacity.a>0.0)\n" " {\n" " color=shade(value);\n" " color=color*opacity.a;\n" " destColor=destColor+color*remainOpacity;\n" " remainOpacity=remainOpacity*(1.0-opacity.a);\n" " }\n" " pos=pos+rayDir;\n" " t+=1.0;\n" " inside=t=0.0039); // 1/255=0.0039\n" " }\n" " }\n" " gl_FragColor = destColor;\n" " gl_FragColor.a = 1.0-remainOpacity;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_CompositeMaskFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_CompositeMaskFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_CompositeMaskFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_CompositeMaskFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Fragment program part with ray cast and composite method with masks.\n" "\n" "#version 110\n" "\n" "uniform sampler3D dataSetTexture;\n" "uniform sampler3D maskTexture;\n" "uniform sampler1D mask1ColorTexture;\n" "uniform sampler1D mask2ColorTexture;\n" "uniform sampler1D opacityTexture;\n" "\n" "uniform vec3 lowBounds;\n" "uniform vec3 highBounds;\n" "\n" "uniform float maskBlendFactor;\n" "\n" "// Entry position (global scope)\n" "vec3 pos;\n" "// Incremental vector in texture space (global scope)\n" "vec3 rayDir;\n" "\n" "float tMax;\n" "\n" "// from cropping vs no cropping\n" "vec4 initialColor();\n" "\n" "// from 1 vs 4 component shader.\n" "float scalarFromValue(vec4 value);\n" "vec4 colorFromValue(vec4 value);\n" "\n" "// from noshade vs shade.\n" "void initShade();\n" "vec4 shade(vec4 value);\n" "\n" "void trace(void)\n" "{\n" " vec4 destColor=initialColor();\n" " float remainOpacity=1.0-destColor.a;\n" "\n" " bool inside=true;\n" " \n" " vec4 maskValue;\n" " vec4 color;\n" " vec4 opacity;\n" "\n" " initShade();\n" " \n" " float t=0.0;\n" " \n" " // We NEED two nested while loops. It is trick to work around hardware\n" " // limitation about the maximum number of loops.\n" "\n" " while(inside)\n" " { \n" " while(inside)\n" " {\n" " vec4 value=texture3D(dataSetTexture,pos);\n" " float scalar=scalarFromValue(value);\n" " opacity=texture1D(opacityTexture,scalar);\n" " \n" " if(maskBlendFactor==0.0)\n" " {\n" " color=shade(value);\n" " }\n" " else\n" " {\n" " // get the mask value at this same location\n" " maskValue=texture3D(maskTexture,pos);\n" " if(maskValue.a==0.0)\n" " {\n" " color=shade(value);\n" " }\n" " else\n" " {\n" " if(maskValue.a==1.0/255.0)\n" " {\n" " color=texture1D(mask1ColorTexture,scalar);\n" " }\n" " else\n" " {\n" " // maskValue.a == 2.0/255.0\n" " color=texture1D(mask2ColorTexture,scalar);\n" " }\n" " color.a=1.0;\n" " if(maskBlendFactor<1.0)\n" " {\n" " color=(1.0-maskBlendFactor)*shade(value)+maskBlendFactor*color;\n" " }\n" "// color.r = 1;\n" "// color.g = 0;\n" "// color.b = 0;\n" "// color.a = 1;\n" " }\n" " }\n" " \n" " color=color*opacity.a;\n" " destColor=destColor+color*remainOpacity;\n" " remainOpacity=remainOpacity*(1.0-opacity.a);\n" " \n" " pos=pos+rayDir;\n" " t+=1.0;\n" " inside=t=0.0039); // 1/255=0.0039\n" " }\n" " }\n" " gl_FragColor = destColor;\n" " gl_FragColor.a = 1.0-remainOpacity;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_CompositeNoCroppingFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_CompositeNoCroppingFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_CompositeNoCroppingFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_CompositeNoCroppingFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Implementation of some function used by the composite method when cropping\n" "// is off.\n" "\n" "#version 110\n" "\n" "// Max intensity is the lowest value.\n" "vec4 initialColor()\n" "{\n" " return vec4(0.0,0.0,0.0,0.0);\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_MinIPCroppingFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_MinIPCroppingFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_MinIPCroppingFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_MinIPCroppingFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Implementation of some functions used by the Minimum Intensity Projection\n" "// (MinIP) method when cropping is on.\n" "\n" "#version 110\n" "\n" "// GLSL Spec 1.10 rev 59 30-April-2004 defines gl_FragData[] but implementation\n" "// older than the spec only has it as an extension\n" "// (nVidia Linux driver 100.14.13, OpenGL version 2.1.1,\n" "// on Quadro FX 3500/PCI/SSE2)\n" "#extension GL_ARB_draw_buffers : enable\n" "\n" "// max scalar buffer as an input\n" "uniform sampler2D scalarBufferTexture;\n" "// 2D Texture fragment coordinates [0,1] from fragment coordinates\n" "// the scalar frame buffer texture has the size of the plain buffer but\n" "// we use a fraction of it. The texture coordinates is less than 1 if\n" "// the reduction factor is less than 1.\n" "vec2 fragTexCoord;\n" "\n" "float initialMinValue()\n" "{\n" " return texture2D(scalarBufferTexture,fragTexCoord).r;\n" "}\n" "\n" "void writeColorAndMinScalar(vec4 sample,\n" " vec4 opacity,\n" " float minValue)\n" "{\n" " // color framebuffer\n" " gl_FragData[0].r =sample.r * opacity.a;\n" " gl_FragData[0].g =sample.g * opacity.a;\n" " gl_FragData[0].b =sample.b * opacity.a;\n" " gl_FragData[0].a=opacity.a;\n" " \n" " // min scalar framebuffer\n" " gl_FragData[1].r=minValue;\n" " gl_FragData[1].g=0.0;\n" " gl_FragData[1].b=0.0;\n" " gl_FragData[1].a=0.0;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentCroppingFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentCroppingFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentCroppingFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentCroppingFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Implementation of some functions used by the 4-component Minimum Intensity\n" "// Projection (MinIP) method when cropping is on.\n" "\n" "#version 110\n" "\n" "// GLSL Spec 1.10 rev 59 30-April-2004 defines gl_FragData[] but implementation\n" "// older than the spec only has it as an extension\n" "// (nVidia Linux driver 100.14.13, OpenGL version 2.1.1,\n" "// on Quadro FX 3500/PCI/SSE2)\n" "#extension GL_ARB_draw_buffers : enable\n" "\n" "// max scalar buffer as an input\n" "uniform sampler2D scalarBufferTexture;\n" "\n" "// color buffer as an input\n" "uniform sampler2D frameBufferTexture;\n" "\n" "// 2D Texture fragment coordinates [0,1] from fragment coordinates\n" "// the scalar frame buffer texture has the size of the plain buffer but\n" "// we use a fraction of it. The texture coordinates is less than 1 if\n" "// the reduction factor is less than 1.\n" "vec2 fragTexCoord;\n" "\n" "float initialMinValue()\n" "{\n" " return texture2D(scalarBufferTexture,fragTexCoord).r;\n" "}\n" "\n" "vec4 initialColor()\n" "{\n" " return texture2D(frameBufferTexture,fragTexCoord);\n" "}\n" "\n" "void writeColorAndMinScalar(vec4 color,\n" " vec4 opacity,\n" " float minValue)\n" "{\n" " // color framebuffer\n" " gl_FragData[0].r = color.r*opacity.a;\n" " gl_FragData[0].g = color.g*opacity.a;\n" " gl_FragData[0].b = color.b*opacity.a;\n" " gl_FragData[0].a=opacity.a;\n" " \n" " // min scalar framebuffer\n" " gl_FragData[1].r=minValue;\n" " gl_FragData[1].g=0.0;\n" " gl_FragData[1].b=0.0;\n" " gl_FragData[1].a=0.0;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Fragment program with ray cast and 4-dependent-component Minimum Intensity\n" "// Projection (MinIP) method.\n" "// Compilation: header part and the projection part are inserted first.\n" "// pos is defined and initialized in header\n" "// rayDir is defined in header and initialized in the projection part\n" "\n" "#version 110\n" "\n" "uniform sampler3D dataSetTexture;\n" "uniform sampler1D opacityTexture;\n" "\n" "uniform vec3 lowBounds;\n" "uniform vec3 highBounds;\n" "\n" "// Entry position (global scope)\n" "vec3 pos;\n" "// Incremental vector in texture space (global scope)\n" "vec3 rayDir;\n" "\n" "float tMax;\n" "\n" "// Sub-functions, depending on cropping mode\n" "float initialMinValue();\n" "vec4 initialColor();\n" "void writeColorAndMinScalar(vec4 color,\n" " vec4 opacity,\n" " float minValue);\n" "\n" "void trace(void)\n" "{\n" " // Max intensity is the lowest value.\n" " float minValue=initialMinValue();\n" " vec4 color=initialColor();\n" " bool inside=true;\n" " float t=0.0;\n" " vec4 sample;\n" " bool changed=false;\n" " \n" " // We NEED two nested while loops. It is a trick to work around hardware\n" " // limitation about the maximum number of loops.\n" " while(inside)\n" " {\n" " while(inside)\n" " {\n" " sample=texture3D(dataSetTexture,pos);\n" " if(sample.w=lowBounds.x && pos.y>=lowBounds.y\n" " && pos.z>=lowBounds.z && pos.x<=highBounds.x && pos.y<=highBounds.y\n" " && pos.z<=highBounds.z;\n" " }\n" " }\n" " \n" " if(changed)\n" " {\n" " vec4 opacity=texture1D(opacityTexture,minValue);\n" " writeColorAndMinScalar(color,opacity,minValue);\n" " }\n" " else\n" " {\n" " discard;\n" " }\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentNoCroppingFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentNoCroppingFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentNoCroppingFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_MinIPFourDependentNoCroppingFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Implementation of some functions used by the 4-component Minimum Intensity\n" "// Projection (MinIP) method when cropping is off.\n" "\n" "#version 110\n" "\n" "float initialMinValue()\n" "{\n" " return 1.0;\n" "}\n" "\n" "vec4 initialColor()\n" "{\n" " return vec4(0.0,0.0,0.0,0.0);\n" "}\n" "\n" "void writeColorAndMinScalar(vec4 color,\n" " vec4 opacity,\n" " float minValue)\n" "{\n" " // minValue is not used\n" " \n" " // color framebuffer\n" " gl_FragColor.r = color.r*opacity.a;\n" " gl_FragColor.g = color.g*opacity.a;\n" " gl_FragColor.b = color.b*opacity.a;\n" " gl_FragColor.a=opacity.a;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_MinIPFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_MinIPFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_MinIPFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_MinIPFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Fragment program with ray cast and Minimum Intensity Projection (MinIP)\n" "// method.\n" "// Compilation: header part and the projection part are inserted first.\n" "// pos is defined and initialized in header\n" "// rayDir is defined in header and initialized in the projection part\n" "// initMinValue() and writeColorAndMinScalar are defined in some specific\n" "// file depending on cropping flag being on or off.\n" "\n" "#version 110\n" "\n" "uniform sampler3D dataSetTexture;\n" "uniform sampler1D colorTexture;\n" "uniform sampler1D opacityTexture;\n" "\n" "uniform vec3 lowBounds;\n" "uniform vec3 highBounds;\n" "\n" "// Entry position (global scope)\n" "vec3 pos;\n" "// Incremental vector in texture space (global scope)\n" "vec3 rayDir;\n" "\n" "float tMax;\n" "\n" "// Sub-functions, depending on cropping mode\n" "float initialMinValue();\n" "void writeColorAndMinScalar(vec4 sample,\n" " vec4 opacity,\n" " float minValue);\n" "\n" "void trace(void)\n" "{\n" " // Max intensity is the lowest value.\n" " float minValue=initialMinValue();\n" " bool inside=true;\n" " vec4 sample;\n" " \n" " float t=0.0;\n" " // We NEED two nested while loops. It is trick to work around hardware\n" " // limitation about the maximum number of loops.\n" " while(inside)\n" " {\n" " while(inside)\n" " {\n" " sample=texture3D(dataSetTexture,pos);\n" " minValue=min(minValue,sample.r);\n" " pos=pos+rayDir;\n" " t+=1.0;\n" " inside=t=lowBounds.x && pos.y>=lowBounds.y\n" " && pos.z>=lowBounds.z && pos.x<=highBounds.x && pos.y<=highBounds.y\n" " && pos.z<=highBounds.z;\n" " \n" " \n" " }\n" " }\n" "\n" " sample=texture1D(colorTexture,minValue);\n" " vec4 opacity=texture1D(opacityTexture,minValue);\n" " \n" " writeColorAndMinScalar(sample,opacity,minValue);\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_MinIPNoCroppingFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_MinIPNoCroppingFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_MinIPNoCroppingFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_MinIPNoCroppingFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Implementation of some functions used by the Minimum Intensity projection\n" "// (MinIP) method when cropping is off.\n" "\n" "#version 110\n" "\n" "float initialMinValue()\n" "{\n" " return 1.0;\n" "}\n" "\n" "void writeColorAndMinScalar(vec4 sample,\n" " vec4 opacity,\n" " float minValue)\n" "{\n" " // we don't need to write minValue to a buffer when there is no cropping.\n" " // color framebuffer\n" " gl_FragColor.r =sample.r * opacity.a;\n" " gl_FragColor.g =sample.g * opacity.a;\n" " gl_FragColor.b =sample.b * opacity.a;\n" " gl_FragColor.a=opacity.a;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_MIPCroppingFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_MIPCroppingFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_MIPCroppingFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_MIPCroppingFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Implementation of some functions used by the Maximum Intensity Projection\n" "// (MIP) method when cropping is on.\n" "\n" "#version 110\n" "\n" "// GLSL Spec 1.10 rev 59 30-April-2004 defines gl_FragData[] but implementation\n" "// older than the spec only has it as an extension\n" "// (nVidia Linux driver 100.14.13, OpenGL version 2.1.1,\n" "// on Quadro FX 3500/PCI/SSE2)\n" "#extension GL_ARB_draw_buffers : enable\n" "\n" "// max scalar buffer as an input\n" "uniform sampler2D scalarBufferTexture;\n" "// 2D Texture fragment coordinates [0,1] from fragment coordinates\n" "// the scalar frame buffer texture has the size of the plain buffer but\n" "// we use a fraction of it. The texture coordinates is less than 1 if\n" "// the reduction factor is less than 1.\n" "vec2 fragTexCoord;\n" "\n" "float initialMaxValue()\n" "{\n" " return texture2D(scalarBufferTexture,fragTexCoord).r;\n" "}\n" "\n" "void writeColorAndMaxScalar(vec4 sample,\n" " vec4 opacity,\n" " float maxValue)\n" "{\n" " // color framebuffer\n" " gl_FragData[0].r =sample.r * opacity.a;\n" " gl_FragData[0].g =sample.g * opacity.a;\n" " gl_FragData[0].b =sample.b * opacity.a;\n" " gl_FragData[0].a=opacity.a;\n" " \n" " // max scalar framebuffer\n" " gl_FragData[1].r=maxValue;\n" " gl_FragData[1].g=0.0;\n" " gl_FragData[1].b=0.0;\n" " gl_FragData[1].a=0.0;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_MIPFourDependentCroppingFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_MIPFourDependentCroppingFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_MIPFourDependentCroppingFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_MIPFourDependentCroppingFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Implementation of some functions used by the 4-component Maximum Intensity\n" "// Projection (MIP) method when cropping is on.\n" "\n" "#version 110\n" "\n" "// GLSL Spec 1.10 rev 59 30-April-2004 defines gl_FragData[] but implementation\n" "// older than the spec only has it as an extension\n" "// (nVidia Linux driver 100.14.13, OpenGL version 2.1.1,\n" "// on Quadro FX 3500/PCI/SSE2)\n" "#extension GL_ARB_draw_buffers : enable\n" "\n" "// max scalar buffer as an input\n" "uniform sampler2D scalarBufferTexture;\n" "\n" "// color buffer as an input\n" "uniform sampler2D frameBufferTexture;\n" "\n" "// 2D Texture fragment coordinates [0,1] from fragment coordinates\n" "// the scalar frame buffer texture has the size of the plain buffer but\n" "// we use a fraction of it. The texture coordinates is less than 1 if\n" "// the reduction factor is less than 1.\n" "vec2 fragTexCoord;\n" "\n" "float initialMaxValue()\n" "{\n" " return texture2D(scalarBufferTexture,fragTexCoord).r;\n" "}\n" "\n" "vec4 initialColor()\n" "{\n" " return texture2D(frameBufferTexture,fragTexCoord);\n" "}\n" "\n" "void writeColorAndMaxScalar(vec4 color,\n" " vec4 opacity,\n" " float maxValue)\n" "{\n" " // color framebuffer\n" " gl_FragData[0].r = color.r*opacity.a;\n" " gl_FragData[0].g = color.g*opacity.a;\n" " gl_FragData[0].b = color.b*opacity.a;\n" " gl_FragData[0].a=opacity.a;\n" " \n" " // max scalar framebuffer\n" " gl_FragData[1].r=maxValue;\n" " gl_FragData[1].g=0.0;\n" " gl_FragData[1].b=0.0;\n" " gl_FragData[1].a=0.0;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_MIPFourDependentFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_MIPFourDependentFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_MIPFourDependentFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_MIPFourDependentFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Fragment program with ray cast and 4-dependent-component Maximum Intensity\n" "// Projection (MIP) method.\n" "// Compilation: header part and the projection part are inserted first.\n" "// pos is defined and initialized in header\n" "// rayDir is defined in header and initialized in the projection part\n" "\n" "#version 110\n" "\n" "uniform sampler3D dataSetTexture;\n" "uniform sampler1D opacityTexture;\n" "\n" "uniform vec3 lowBounds;\n" "uniform vec3 highBounds;\n" "\n" "// Entry position (global scope)\n" "vec3 pos;\n" "// Incremental vector in texture space (global scope)\n" "vec3 rayDir;\n" "\n" "float tMax;\n" "\n" "// Sub-functions, depending on cropping mode\n" "float initialMaxValue();\n" "vec4 initialColor();\n" "void writeColorAndMaxScalar(vec4 color,\n" " vec4 opacity,\n" " float maxValue);\n" "\n" "void trace(void)\n" "{\n" " // Max intensity is the lowest value.\n" " float maxValue=initialMaxValue();\n" " vec4 color=initialColor();\n" " bool inside=true;\n" " float t=0.0;\n" " vec4 sample;\n" " bool changed=false;\n" " \n" " // We NEED two nested while loops. It is a trick to work around hardware\n" " // limitation about the maximum number of loops.\n" " while(inside)\n" " {\n" " while(inside)\n" " {\n" " sample=texture3D(dataSetTexture,pos);\n" " if(sample.w>maxValue)\n" " {\n" " changed=true;\n" " maxValue=sample.w;\n" " color=sample;\n" " }\n" " pos=pos+rayDir;\n" " t+=1.0;\n" " \n" " // yes, t=lowBounds.x && pos.y>=lowBounds.y\n" " && pos.z>=lowBounds.z && pos.x<=highBounds.x && pos.y<=highBounds.y\n" " && pos.z<=highBounds.z;\n" " }\n" " }\n" " \n" " if(changed)\n" " {\n" " vec4 opacity=texture1D(opacityTexture,maxValue);\n" " writeColorAndMaxScalar(color,opacity,maxValue);\n" " }\n" " else\n" " {\n" " discard;\n" " }\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_MIPFourDependentNoCroppingFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_MIPFourDependentNoCroppingFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_MIPFourDependentNoCroppingFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_MIPFourDependentNoCroppingFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Implementation of some functions used by the 4-component Maximum Intensity\n" "// Projection (MIP) method when cropping is off.\n" "\n" "#version 110\n" "\n" "float initialMaxValue()\n" "{\n" " return 0.0;\n" "}\n" "\n" "vec4 initialColor()\n" "{\n" " return vec4(0.0,0.0,0.0,0.0);\n" "}\n" "\n" "void writeColorAndMaxScalar(vec4 color,\n" " vec4 opacity,\n" " float maxValue)\n" "{\n" " // maxValue is not used\n" " \n" " // color framebuffer\n" " gl_FragColor.r = color.r*opacity.a;\n" " gl_FragColor.g = color.g*opacity.a;\n" " gl_FragColor.b = color.b*opacity.a;\n" " gl_FragColor.a=opacity.a;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_MIPFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_MIPFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_MIPFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_MIPFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Fragment program with ray cast and Maximum Intensity Projection (MIP)\n" "// method.\n" "// Compilation: header part and the projection part are inserted first.\n" "// pos is defined and initialized in header\n" "// rayDir is defined in header and initialized in the projection part\n" "// initMaxValue() and writeColorAndMaxScalar are defined in some specific\n" "// file depending on cropping flag being on or off.\n" "\n" "#version 110\n" "\n" "uniform sampler3D dataSetTexture;\n" "uniform sampler1D colorTexture;\n" "uniform sampler1D opacityTexture;\n" "\n" "uniform vec3 lowBounds;\n" "uniform vec3 highBounds;\n" "\n" "// Entry position (global scope)\n" "vec3 pos;\n" "// Incremental vector in texture space (global scope)\n" "vec3 rayDir;\n" "\n" "float tMax;\n" "\n" "// Sub-functions, depending on cropping mode\n" "float initialMaxValue();\n" "void writeColorAndMaxScalar(vec4 sample,\n" " vec4 opacity,\n" " float maxValue);\n" "\n" "void trace(void)\n" "{\n" " // Max intensity is the lowest value.\n" " float maxValue=initialMaxValue();\n" " bool inside=true;\n" " vec4 sample;\n" " \n" " float t=0.0;\n" " // We NEED two nested while loops. It is trick to work around hardware\n" " // limitation about the maximum number of loops.\n" " while(inside)\n" " {\n" " while(inside)\n" " {\n" " sample=texture3D(dataSetTexture,pos);\n" " maxValue=max(maxValue,sample.r);\n" " pos=pos+rayDir;\n" " t+=1.0;\n" " \n" " // yes, t=lowBounds.x && pos.y>=lowBounds.y\n" " && pos.z>=lowBounds.z && pos.x<=highBounds.x && pos.y<=highBounds.y\n" " && pos.z<=highBounds.z;\n" " }\n" " }\n" "\n" " sample=texture1D(colorTexture,maxValue);\n" " vec4 opacity=texture1D(opacityTexture,maxValue);\n" " \n" " writeColorAndMaxScalar(sample,opacity,maxValue);\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_MIPNoCroppingFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_MIPNoCroppingFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_MIPNoCroppingFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_MIPNoCroppingFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Implementation of some functions used by the Maximum Intensity projection\n" "// (MIP) method when cropping is off.\n" "\n" "#version 110\n" "\n" "float initialMaxValue()\n" "{\n" " return 0.0;\n" "}\n" "\n" "void writeColorAndMaxScalar(vec4 sample,\n" " vec4 opacity,\n" " float maxValue)\n" "{\n" " // we don't need to write maxValue to a buffer when there is no cropping.\n" " // color framebuffer\n" " gl_FragColor.r =sample.r * opacity.a;\n" " gl_FragColor.g =sample.g * opacity.a;\n" " gl_FragColor.b =sample.b * opacity.a;\n" " gl_FragColor.a=opacity.a;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_OneComponentFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_OneComponentFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_OneComponentFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_OneComponentFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Fragment shader that implements scalarFromValue() and colorFromValue() in\n" "// the case of a one-component dataset.\n" "// The functions are used in composite mode.\n" "\n" "#version 110\n" "\n" "// \"value\" is a sample of the dataset.\n" "// Think of \"value\" as an object.\n" "\n" "uniform sampler1D colorTexture;\n" "\n" "float scalarFromValue(vec4 value)\n" "{\n" " return value.x;\n" "}\n" "\n" "vec4 colorFromValue(vec4 value)\n" "{\n" " return texture1D(colorTexture,value.x);\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_ParallelProjectionFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_ParallelProjectionFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_ParallelProjectionFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_ParallelProjectionFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Parallel projection.\n" "\n" "#version 110\n" "\n" "uniform vec3 parallelRayDirection;\n" "\n" "// Incremental vector in texture space (global scope)\n" "vec3 rayDir;\n" "\n" "// Defined in the right projection method.\n" "void incrementalRayDirection()\n" "{\n" " rayDir=parallelRayDirection;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_PerspectiveProjectionFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_PerspectiveProjectionFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_PerspectiveProjectionFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_PerspectiveProjectionFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Perspective projection.\n" "\n" "#version 110\n" "\n" "// Entry position (global scope)\n" "vec3 pos;\n" "// Incremental vector in texture space (global scope)\n" "vec3 rayDir;\n" "\n" "// Camera position in texture space\n" "uniform vec3 cameraPosition;\n" "// Sample distance in world space\n" "uniform float sampleDistance;\n" "// Matrix coefficients: diagonal (a11,a22,a33)\n" "uniform vec3 matrix1;\n" "// Matrix coefficients: others (2a12,2a23,2a13)\n" "uniform vec3 matrix2;\n" "\n" "// Defined in the right projection method.\n" "void incrementalRayDirection()\n" "{\n" " // Direction of the ray in texture space, not normalized.\n" " rayDir=pos-cameraPosition;\n" " \n" " // x^2, y^2, z^2\n" " vec3 normDir=rayDir*rayDir;\n" " normDir.x=dot(normDir,matrix1);\n" " \n" " // xy,yz,zx\n" " vec3 coefs=rayDir*rayDir.yxz;\n" " coefs.x=dot(coefs,matrix2);\n" "\n" " // n^2\n" " normDir.x=normDir.x+coefs.x;\n" " \n" " // 1/n\n" " // normDir=1/sqrt(normDir)\n" " normDir.x=inversesqrt(normDir.x);\n" " \n" " // Final scale factor for the ray direction in texture space\n" " // normDir=normDir*sampleDistance\n" " normDir.x=normDir.x*sampleDistance;\n" " // Now, rayDir is the incremental direction in texture space\n" " rayDir=rayDir*normDir.x;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_ScaleBiasFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_ScaleBiasFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_ScaleBiasFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_ScaleBiasFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// This fragment shader scales and biases a framebuffer passed as a texture.\n" "// Incoming color from the texture is pre-multiplied by alpha.\n" "// It does not affect the alpha component.\n" "// Passing the framebuffer as a texture allows the use of a reduction factor\n" "// compared to the size of the final image.\n" "\n" "#version 110\n" "\n" "// Framebuffer to scale.\n" "uniform sampler2D frameBufferTexture;\n" "uniform float scale;\n" "uniform float bias;\n" "\n" "void main()\n" "{\n" " vec4 color=texture2D(frameBufferTexture,gl_TexCoord[0].xy);\n" " if(color.a==0.0)\n" " {\n" " discard;\n" " }\n" " // As incoming color is pre-multiplied by alpha, the bias has to be\n" " // multiplied by alpha before adding it.\n" " gl_FragColor.r=color.r*scale+bias*color.a;\n" " gl_FragColor.g=color.g*scale+bias*color.a;\n" " gl_FragColor.b=color.b*scale+bias*color.a;\n" " gl_FragColor.a=color.a;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_ShadeFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_ShadeFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_ShadeFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_ShadeFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "// Fragment shader that implements initShade() and shade() in the case of\n" "// shading.\n" "// The functions are used in composite mode.\n" "\n" "#version 110\n" "\n" "// \"value\" is a sample of the dataset.\n" "// Think of \"value\" as an object.\n" "\n" "// from 1- vs 4-component shader.\n" "vec4 colorFromValue(vec4 value);\n" "\n" "uniform sampler3D dataSetTexture; // need neighbors for gradient\n" "\n" "// Change-of-coordinate matrix from eye space to texture space\n" "uniform mat3 eyeToTexture3;\n" "uniform mat4 eyeToTexture4;\n" "\n" "// Tranpose of Change-of-coordinate matrix from texture space to eye space\n" "uniform mat3 transposeTextureToEye;\n" "\n" "// Used to compute the gradient.\n" "uniform vec3 cellStep;\n" "uniform vec3 cellScale;\n" "\n" "\n" "// Entry position (global scope), updated in the loop\n" "vec3 pos;\n" "// Incremental vector in texture space (global scope)\n" "vec3 rayDir;\n" "\n" "\n" "// local to the implementation, shared between initShade() and shade()\n" "const vec3 minusOne=vec3(-1.0,-1.0,-1.0);\n" "const vec4 clampMin=vec4(0.0,0.0,0.0,0.0);\n" "const vec4 clampMax=vec4(1.0,1.0,1.0,1.0);\n" "\n" "vec3 xvec;\n" "vec3 yvec;\n" "vec3 zvec;\n" "vec3 wReverseRayDir;\n" "vec3 lightPos;\n" "vec3 ldir;\n" "vec3 h;\n" "vec4 hPos; // homogeneous position\n" "\n" "// ----------------------------------------------------------------------------\n" "void initShade()\n" "{\n" " xvec=vec3(cellStep.x,0.0,0.0); // 0.01\n" " yvec=vec3(0.0,cellStep.y,0.0);\n" " zvec=vec3(0.0,0.0,cellStep.z);\n" " \n" " // Reverse ray direction in eye space\n" " wReverseRayDir=eyeToTexture3*rayDir;\n" " wReverseRayDir=wReverseRayDir*minusOne;\n" " wReverseRayDir=normalize(wReverseRayDir);\n" " \n" " // Directonal light: w==0\n" " if(gl_LightSource[0].position.w==0.0)\n" " {\n" " ldir=gl_LightSource[0].position.xyz;\n" " ldir=normalize(ldir);\n" " h=normalize(ldir+wReverseRayDir);\n" " }\n" " else\n" " {\n" " lightPos=gl_LightSource[0].position.xyz/gl_LightSource[0].position.w;\n" " hPos.w=1.0; // used later\n" " }\n" "}\n" "\n" "// ----------------------------------------------------------------------------\n" "vec4 shade(vec4 value)\n" "{\n" " vec3 g1;\n" " vec3 g2;\n" " vec4 tmp;\n" " float att;\n" " float spot;\n" " \n" " g1.x=texture3D(dataSetTexture,pos+xvec).x;\n" " g1.y=texture3D(dataSetTexture,pos+yvec).x;\n" " g1.z=texture3D(dataSetTexture,pos+zvec).x;\n" " g2.x=texture3D(dataSetTexture,pos-xvec).x;\n" " g2.y=texture3D(dataSetTexture,pos-yvec).x;\n" " g2.z=texture3D(dataSetTexture,pos-zvec).x;\n" " // g1-g2 is the gradient in texture coordinates\n" " // the result is the normalized gradient in eye coordinates.\n" " \n" " g2=g1-g2;\n" " g2=g2*cellScale;\n" " \n" " float normalLength=length(g2);\n" " if(normalLength>0.0)\n" " {\n" " g2=normalize(transposeTextureToEye*g2);\n" " }\n" " else\n" " {\n" " g2=vec3(0.0,0.0,0.0);\n" " }\n" " \n" " vec4 color=colorFromValue(value);\n" " \n" " // initialize color to 0.0\n" " vec4 finalColor=vec4(0.0,0.0,0.0,0.0); \n" " \n" " if(gl_LightSource[0].position.w!=0.0)\n" " {\n" " // We need to know the eye position only if light is positional\n" " // ldir= vertex position in eye coordinates\n" " hPos.xyz=pos;\n" " tmp=eyeToTexture4*hPos;\n" " ldir=tmp.xyz/tmp.w;\n" " // ldir=light direction\n" " ldir=lightPos-ldir;\n" " float sqrDistance=dot(ldir,ldir);\n" " ldir=normalize(ldir);\n" " h=normalize(ldir+wReverseRayDir);\n" " att=1.0/(gl_LightSource[0].constantAttenuation+gl_LightSource[0].linearAttenuation*sqrt(sqrDistance)+gl_LightSource[0].quadraticAttenuation*sqrDistance);\n" " }\n" " else\n" " {\n" " att=1.0;\n" " }\n" " \n" " if(att>0.0)\n" " {\n" " if(gl_LightSource[0].spotCutoff==180.0)\n" " {\n" " spot=1.0;\n" " }\n" " else\n" " {\n" " float coef=-dot(ldir,gl_LightSource[0].spotDirection);\n" " if(coef>=gl_LightSource[0].spotCosCutoff)\n" " {\n" " spot=pow(coef,gl_LightSource[0].spotExponent);\n" " }\n" " else\n" " {\n" " spot=0.0;\n" " }\n" " }\n" " if(spot>0.0)\n" " {\n" " // LIT operation...\n" " float nDotL=dot(g2,ldir);\n" " float nDotH=dot(g2,h);\n" " \n" " // separate nDotL and nDotH for two-sided shading, otherwise we\n" " // get black spots.\n" " \n" " if(nDotL<0.0) // two-sided shading\n" " {\n" " nDotL=-nDotL;\n" " }\n" " \n" " if(nDotH<0.0) // two-sided shading\n" " {\n" " nDotH=-nDotH;\n" " }\n" " // ambient term for this light\n" " finalColor+=gl_FrontLightProduct[0].ambient;\n" " \n" " // diffuse term for this light\n" " if(nDotL>0.0)\n" " {\n" // WORKAROUND FIX: gl_FrontLightProduct[0].diffuse seems to be not transferred to ATI cards //" finalColor+=(gl_FrontLightProduct[0].diffuse*nDotL)*color;\n" // just using a white light now " finalColor+=(0.8*nDotL)*color;\n" " }\n" " \n" " // specular term for this light\n" " float shininessFactor=pow(nDotH,gl_FrontMaterial.shininess);\n" " finalColor+=gl_FrontLightProduct[0].specular*shininessFactor;\n" " finalColor*=att*spot;\n" " }\n" " }\n" " \n" " // scene ambient term\n" // WORKAROUND FIX: gl_FrontLightModelProduct.sceneColor seems to be not transferred to ATI cards //" finalColor+=gl_FrontLightModelProduct.sceneColor*color;\n" // just using a dim ambient light " finalColor+=0.3*color;\n" " \n" " // clamp. otherwise we get black spots\n" " finalColor=clamp(finalColor,clampMin,clampMax);\n" " \n" " return finalColor;\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_NoShadeFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_NoShadeFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_NoShadeFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_NoShadeFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Fragment shader that implements initShade() and shade() in the case of no\n" "// shading.\n" "// The functions are used in composite mode.\n" "\n" "#version 110\n" "\n" "// \"value\" is a sample of the dataset.\n" "// Think of \"value\" as an object.\n" "\n" "// from 1- vs 4-component shader.\n" "vec4 colorFromValue(vec4 value);\n" "\n" "// ----------------------------------------------------------------------------\n" "void initShade()\n" "{\n" " // empty, nothing to do.\n" "}\n" "\n" "// ----------------------------------------------------------------------------\n" "vec4 shade(vec4 value)\n" "{\n" " return colorFromValue(value);\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_HeaderFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_HeaderFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_HeaderFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_HeaderFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "#version 110\n" "\n" "// Depth map of the polygonal geometry\n" "uniform sampler2D depthTexture;\n" "\n" "// 2D noise texture to jitter the starting point of the ray in order to\n" "// remove patterns when the opacity transfer function make the data on the\n" "// border of the dataset to be visible.\n" "uniform sampler2D noiseTexture;\n" "\n" "uniform vec2 windowLowerLeftCorner;\n" "uniform vec2 invOriginalWindowSize;\n" "uniform vec2 invWindowSize;\n" "\n" "// Change-of-coordinate matrix from eye space to texture space\n" "uniform mat4 textureToEye;\n" "\n" "// Entry position (global scope)\n" "vec3 pos;\n" "// Incremental vector in texture space (global scope)\n" "vec3 rayDir;\n" "\n" "// Abscissa along the ray of the point on the depth map\n" "// tracing stops when t>=tMax\n" "float tMax;\n" "\n" "// 2D Texture fragment coordinates [0,1] from fragment coordinates\n" "// the frame buffer texture has the size of the plain buffer but\n" "// we use a fraction of it. The texture coordinates is less than 1 if\n" "// the reduction factor is less than 1.\n" "vec2 fragTexCoord;\n" "\n" "// Defined in the right projection method.\n" "// May use pos in global scope as input.\n" "// Use rayDir in global scope as output.\n" "void incrementalRayDirection();\n" "void trace();\n" "\n" "void main()\n" "{\n" "\n" " // device coordinates are between -1 and 1\n" " // we need texture coordinates between 0 and 1\n" " // the depth buffer has the original size buffer.\n" " fragTexCoord=(gl_FragCoord.xy-windowLowerLeftCorner)*invWindowSize;\n" " vec4 depth=texture2D(depthTexture,fragTexCoord);\n" " if(gl_FragCoord.z>=depth.x) // depth test\n" " {\n" " discard;\n" " }\n" " \n" " // color buffer or max scalar buffer have a reduced size.\n" " fragTexCoord=(gl_FragCoord.xy-windowLowerLeftCorner)*invOriginalWindowSize;\n" " // Abscissa of the point on the depth buffer along the ray.\n" " // point in texture coordinates\n" " vec4 maxPoint;\n" " \n" " // from window coordinates to normalized device coordinates\n" " maxPoint.x=(gl_FragCoord.x-windowLowerLeftCorner.x)*2.0*invWindowSize.x-1.0;\n" " maxPoint.y=(gl_FragCoord.y-windowLowerLeftCorner.y)*2.0*invWindowSize.y-1.0;\n" " maxPoint.z=(2.0*depth.x-(gl_DepthRange.near+gl_DepthRange.far))/gl_DepthRange.diff;\n" " maxPoint.w=1.0;\n" " \n" " // from normalized device coordinates to eye coordinates\n" " maxPoint=gl_ProjectionMatrixInverse*maxPoint;\n" " \n" " // from eye coordinates to texture coordinates\n" " maxPoint=textureToEye*maxPoint;\n" " // homogeneous to cartesian coordinates\n" " maxPoint/=maxPoint.w;\n" " \n" " // Entry position. divide by q.\n" " // pos=gl_TexCoord[0].xyz/gl_TexCoord[0].w;\n" " \n" " pos.x=gl_TexCoord[0].x/gl_TexCoord[0].w;\n" " pos.y=gl_TexCoord[0].y/gl_TexCoord[0].w;\n" " pos.z=gl_TexCoord[0].z/gl_TexCoord[0].w;\n" " \n" " // Incremental vector in texture space. Computation depends on the\n" " // type of projection (parallel or perspective)\n" " incrementalRayDirection();\n" " \n" " vec4 noiseValue=texture2D(noiseTexture,pos.xy*100.0); // with repeat/tiling mode on the noise texture.\n" " \n" " pos+=(noiseValue.x)*rayDir;\n" "\n" " tMax=length(maxPoint.xyz-pos.xyz) /length(rayDir);\n" "\n" "\n" " // Tracing method. Set the final fragment color.\n" " trace();\n" "}\n" "\n"; /* DO NOT EDIT. * Generated by ..\bin\Release\vtkEncodeString.exe * * Define the vtkMitkGPUVolumeRayCastMapper_FourComponentsFS string. * * Generated from file: V:/windows/source/VTK560/VolumeRendering/vtkMitkGPUVolumeRayCastMapper_FourComponentsFS.glsl */ const char *vtkMitkGPUVolumeRayCastMapper_FourComponentsFS = "/*=========================================================================\n" "\n" " Program: Visualization Toolkit\n" " Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper_FourComponentsFS.glsl,v $\n" "\n" " Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" " All rights reserved.\n" " See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "\n" " This software is distributed WITHOUT ANY WARRANTY; without even\n" " the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" " PURPOSE. See the above copyright notice for more information.\n" "\n" "=========================================================================*/\n" "\n" "// Fragment shader that implements scalarFromValue() and colorFromValue() in\n" "// the case of a one-component dataset.\n" "// The functions are used in composite mode.\n" "\n" "#version 110\n" "\n" "// \"value\" is a sample of the dataset.\n" "// Think of \"value\" as an object.\n" "\n" "float scalarFromValue(vec4 value)\n" "{\n" " return value.w;\n" "}\n" "\n" "vec4 colorFromValue(vec4 value)\n" "{\n" " return vec4(value.xyz,1.0);\n" "}\n" "\n"; -#endif \ No newline at end of file +#endif diff --git a/Modules/MitkExt/Testing/mitkSimpleHistogramTest.cpp b/Modules/MitkExt/Testing/mitkSimpleHistogramTest.cpp index d234d79934..9700f52845 100644 --- a/Modules/MitkExt/Testing/mitkSimpleHistogramTest.cpp +++ b/Modules/MitkExt/Testing/mitkSimpleHistogramTest.cpp @@ -1,46 +1,46 @@ /*=================================================================== 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 int mitkSimpleHistogramTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN("mitkSimpleHistogram"); mitk::SimpleImageHistogram* myTestSimpleImageHistogram = new mitk::SimpleImageHistogram(); MITK_TEST_CONDITION_REQUIRED(myTestSimpleImageHistogram!=NULL,"Testing instanciation."); MITK_TEST_CONDITION_REQUIRED(myTestSimpleImageHistogram->GetMax()==1,"Testing GetMax()."); MITK_TEST_CONDITION_REQUIRED(myTestSimpleImageHistogram->GetMin()==0,"Testing GetMin()."); MITK_TEST_CONDITION_REQUIRED(myTestSimpleImageHistogram->GetRelativeBin(1.0,5.0) ==0,"Testing GetRelativeBin()."); bool success = true; try { myTestSimpleImageHistogram->ComputeFromBaseData(NULL); myTestSimpleImageHistogram->ComputeFromBaseData(mitk::Image::New()); //an empty image myTestSimpleImageHistogram->ComputeFromBaseData(mitk::Surface::New()); //an invalid value } catch(...) { success = false; } MITK_TEST_CONDITION_REQUIRED(success,"Testing ComputeFromBaseData() with invalid input values."); MITK_TEST_CONDITION_REQUIRED(!myTestSimpleImageHistogram->GetValid(),"Testing if histogram is invalid after invalid input."); MITK_TEST_END(); -} \ No newline at end of file +} diff --git a/Modules/Overlays/QmitkOverlayController.cpp b/Modules/Overlays/QmitkOverlayController.cpp index 8873301a7f..e821cdd43f 100644 --- a/Modules/Overlays/QmitkOverlayController.cpp +++ b/Modules/Overlays/QmitkOverlayController.cpp @@ -1,403 +1,403 @@ /*=================================================================== 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 "QmitkOverlayController.h" #include "QmitkRenderWindow.h" #include "QmitkOverlay.h" #include #include #include QmitkOverlayController::QmitkOverlayController( QmitkRenderWindow* rw, mitk::PropertyList* pl ) : QObject(), m_RenderWindow( rw ), m_PropertyList( pl ) { if ( m_RenderWindow == NULL ) { MITK_ERROR << "invalid QmitkRenderWindow"; return; } connect( rw, SIGNAL( moved() ), this, SLOT( AdjustOverlayPosition() ) ); this->InitializeOverlayLayout(); this->AdjustOverlayPosition(); this->SetOverlayVisibility( true ); if ( m_PropertyList.IsNull() ) m_PropertyList = mitk::PropertyList::New(); } QmitkOverlayController::~QmitkOverlayController() { } void QmitkOverlayController::InitializeOverlayLayout() { // setup widget for each position this->InitializeWidget( QmitkOverlay::top_Left ); this->InitializeWidget( QmitkOverlay::top_Center ); this->InitializeWidget( QmitkOverlay::top_Right ); this->InitializeWidget( QmitkOverlay::middle_Left ); this->InitializeWidget( QmitkOverlay::middle_Right ); this->InitializeWidget( QmitkOverlay::bottom_Left ); this->InitializeWidget( QmitkOverlay::bottom_Center ); this->InitializeWidget( QmitkOverlay::bottom_Right ); } void QmitkOverlayController::InitializeWidget( QmitkOverlay::DisplayPosition pos ) { // create a new QWidget as Tool & FramelessWindowHint m_PositionedOverlays[ pos ] = new QWidget( m_RenderWindow, Qt::Tool | Qt::FramelessWindowHint ); // autoFillBackGround(false) and WA_TranslucentBackground = true are needed to have a translucent background // transparency does NOT work under Win-XP 32-Bit --> paint black background #if !defined(_WIN32) || defined(_WIN64) m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_TranslucentBackground, true ); #else m_PositionedOverlays[ pos ]->setStyleSheet( "QWidget { background: black }" ); m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_TranslucentBackground, false ); #endif // X11 specific attributes m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_X11NetWmWindowTypeUtility, true ); // mac-specific attributes: // making sure overlays are even visible if RenderWindow does not have the focus (not default for Qt::Tool on mac) m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_MacAlwaysShowToolWindow, true ); // testing something m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_MacShowFocusRect, false ); // overlays should not get the focus m_PositionedOverlays[ pos ]->setFocusPolicy( Qt::NoFocus ); // setting the color of the background to transparent - not sure it's needed after the attributes have been set above QPalette p = QPalette(); p.setColor( QPalette::Window, Qt::transparent ); m_PositionedOverlays[ pos ]->setPalette( p ); // setting position-specific properties switch ( pos ) { case QmitkOverlay::top_Left : { // adding left-aligned top-to-bottom layout QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::TopToBottom ); layout->setAlignment( Qt::AlignLeft ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::top_Center : { // adding center-aligned top-to-bottom layout QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::TopToBottom ); layout->setAlignment( Qt::AlignCenter ); layout->setAlignment( Qt::AlignLeft ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::top_Right : { // adding right-aligned top-to-bottom layout QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::TopToBottom ); layout->setAlignment( Qt::AlignRight ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::middle_Left : { // adding left-aligned left-to-right layout QHBoxLayout* layout = new QHBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::LeftToRight ); layout->setAlignment( Qt::AlignLeft ); layout->setSpacing( 3 ); break; } case QmitkOverlay::middle_Right : { // adding right-aligned right-to-left layout QHBoxLayout* layout = new QHBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::RightToLeft ); layout->setAlignment( Qt::AlignRight ); layout->setSpacing( 3 ); break; } case QmitkOverlay::bottom_Left : { // adding left-aligned bottom-to-top layout QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::BottomToTop ); layout->setAlignment( Qt::AlignLeft ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::bottom_Center : { QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::BottomToTop ); layout->setAlignment( Qt::AlignCenter ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::bottom_Right : { QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::BottomToTop ); layout->setAlignment( Qt::AlignRight ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } } } void QmitkOverlayController::AdjustOverlayPosition() { QWidget* widget; QPoint pos; // setting position of top-left overlay-container pos = m_RenderWindow->mapToGlobal( QPoint(0,0) ); m_PositionedOverlays[ QmitkOverlay::top_Left ]->move( pos.x(), pos.y() ); // setting position of top-center overlay-container widget = m_PositionedOverlays[ QmitkOverlay::top_Center ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width()/2, 0 ) ) ; widget->move( pos.x() - widget->size().width()/2, pos.y() ); // setting position of top-right overlay-container widget = m_PositionedOverlays[ QmitkOverlay::top_Right ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width(), 0 ) ) ; widget->move( pos.x() - widget->size().width(), pos.y() ); // setting position of middle-left overlay-container widget = m_PositionedOverlays[ QmitkOverlay::middle_Left ]; pos = m_RenderWindow->mapToGlobal( QPoint( 0, m_RenderWindow->size().height()/2 ) ) ; widget->move( pos.x(), pos.y() - widget->size().height()/2 ); // setting position of middle-right overlay-container widget = m_PositionedOverlays[ QmitkOverlay::middle_Right ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width(), m_RenderWindow->size().height()/2 ) ) ; widget->move( pos.x() - widget->size().width(), pos.y() - widget->size().height()/2 ); // setting position of bottom-left overlay-container widget = m_PositionedOverlays[ QmitkOverlay::bottom_Left ]; pos = m_RenderWindow->mapToGlobal( QPoint( 0, m_RenderWindow->size().height() ) ) ; widget->move( pos.x(), pos.y() - widget->size().height() ); // setting position of bottom-center overlay-container widget = m_PositionedOverlays[ QmitkOverlay::bottom_Center ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width()/2, m_RenderWindow->size().height() ) ) ; widget->move( pos.x() - widget->size().width()/2, pos.y() - widget->size().height() ); // setting position of bottom-right overlay-container widget = m_PositionedOverlays[ QmitkOverlay::bottom_Right ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width(), m_RenderWindow->size().height() ) ) ; widget->move( pos.x() - widget->size().width(), pos.y() - widget->size().height() ); } void QmitkOverlayController::SetOverlayVisibility( bool visible ) { OverlayPositionMap::iterator overlayIter; for ( overlayIter=m_PositionedOverlays.begin(); overlayIter!=m_PositionedOverlays.end(); overlayIter++ ) { if ( visible ) { (overlayIter->second)->show(); } else { (overlayIter->second)->hide(); } } OverlayVector::iterator allOverlaysIter; for( allOverlaysIter=m_AllOverlays.begin(); allOverlaysIter!=m_AllOverlays.end(); allOverlaysIter++ ) { if ( visible ) { (*allOverlaysIter)->GetWidget()->show(); } else { (*allOverlaysIter)->GetWidget()->hide(); } } } void QmitkOverlayController::AddOverlay( QmitkOverlay* overlay ) { // if no renderwindow has been set, it's not possible to add overlays... if ( m_RenderWindow == NULL ) { MITK_ERROR << "invalid QmitkRenderWindow"; return; } if ( overlay != NULL ) { // get desired position and layer of the overlay QmitkOverlay::DisplayPosition pos = overlay->GetPosition(); // concatenate local propertyList and propertyList of the RenderingManager // local properties have priority as they are not overwritten if preset in both m_PropertyList->ConcatenatePropertyList( m_RenderWindow->GetRenderer()->GetRenderingManager()->GetPropertyList(), false ); // add the overlay to the OverlayContainer in the RenderWindow ... overlay->GetWidget()->setParent( m_PositionedOverlays[ pos ] ); // ... and set it up with the correct properties this->UpdateOverlayData( overlay ); // add overlay to list of all overlays and correctly put it into the layering m_AllOverlays.push_back( overlay ); this->RestackOverlays( pos ); // ... and reset the position of the widgets this->AdjustOverlayPosition(); } } void QmitkOverlayController::UpdateOverlayData( QmitkOverlay* overlay ) { overlay->GenerateData( m_PropertyList ); } void QmitkOverlayController::RemoveOverlay( QmitkOverlay* overlay ) { if ( overlay != NULL ) { // get desired position and layer of the overlay QmitkOverlay::DisplayPosition pos = overlay->GetPosition(); OverlayVector::iterator iter = std::find( m_AllOverlays.begin(), m_AllOverlays.end(), overlay ); if ( iter != m_AllOverlays.end() ) { m_AllOverlays.erase( iter ); overlay->GetWidget()->setParent( NULL ); overlay->GetWidget()->hide(); if ( m_PositionedOverlays[ pos ]->layout()->isEmpty() ) { m_PositionedOverlays[ pos ]->hide(); } else { this->RestackOverlays( pos ); // reset the position of the widgets this->AdjustOverlayPosition(); } } overlay->deleteLater(); } } void QmitkOverlayController::AlignOverlays() { //OverlayVector::iterator overlayIter; //for ( overlayIter=m_AllOverlays.begin(); overlayIter!=m_AllOverlays.end(); overlayIter++ ) //{ // int stackLayer = dynamic_cast( m_PositionedOverlays[ (*overlayIter)->GetPosition() ]->layout() )->isEmpty() ? 0 : layer; // dynamic_cast( m_PositionedOverlays[ (*overlayIter)->GetPosition() ]->layout() )->addWidget( (*overlayIter)->GetWidget(), stackLayer, Qt::AlignLeft ); //} } void QmitkOverlayController::RestackOverlays( QmitkOverlay::DisplayPosition pos ) { OverlayVector::iterator overlayIter; QBoxLayout* layout = dynamic_cast( m_PositionedOverlays[ pos ]->layout() ); std::sort( m_AllOverlays.begin(), m_AllOverlays.end() ); for ( overlayIter=m_AllOverlays.begin(); overlayIter!=m_AllOverlays.end(); overlayIter++ ) { // do nothing if the overlay is not in the right position if ( (*overlayIter)->GetPosition() != pos ) { continue; } // determine the desired stacking layer // if the overlay-container is empty, simply append the overlay to the list // if it's not empty, use the layer of the overlay unsigned int layer = (*overlayIter)->GetLayer(); int stackLayer = 0; if ( !layout->isEmpty() ) { stackLayer = layer; } switch ( pos ) { // same alignment for all lefts, ... case QmitkOverlay::top_Left : {} case QmitkOverlay::middle_Left : {} case QmitkOverlay::bottom_Left : { layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignLeft ); break; } // ... for all centers, ... case QmitkOverlay::top_Center : {} case QmitkOverlay::bottom_Center : { layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignCenter ); break; } // ... and for all rights case QmitkOverlay::top_Right : {} case QmitkOverlay::middle_Right : {} case QmitkOverlay::bottom_Right : { layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignRight ); break; } } } } void QmitkOverlayController::UpdateAllOverlays() { foreach( QmitkOverlay* overlay, m_AllOverlays ) { this->UpdateOverlayData( overlay ); } -} \ No newline at end of file +} diff --git a/Modules/Qmitk/QmitkDataStorageListModel.cpp b/Modules/Qmitk/QmitkDataStorageListModel.cpp index e3b8f791e5..0434b6c6ef 100755 --- a/Modules/Qmitk/QmitkDataStorageListModel.cpp +++ b/Modules/Qmitk/QmitkDataStorageListModel.cpp @@ -1,273 +1,273 @@ /*=================================================================== 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 "QmitkDataStorageListModel.h" //# Own includes // mitk #include "mitkStringProperty.h" //# Toolkit includes // itk #include "itkCommand.h" QmitkDataStorageListModel::QmitkDataStorageListModel(mitk::DataStorage::Pointer dataStorage , mitk::NodePredicateBase* pred, QObject* parent) : QAbstractListModel(parent), m_NodePredicate(0), m_DataStorage(0), m_BlockEvents(false) { this->SetPredicate(pred); this->SetDataStorage(dataStorage); } QmitkDataStorageListModel::~QmitkDataStorageListModel() { // set data storage to 0 so that event listener get removed this->SetDataStorage(0); if (m_NodePredicate) delete m_NodePredicate; } void QmitkDataStorageListModel::SetDataStorage(mitk::DataStorage::Pointer dataStorage) { if( m_DataStorage != dataStorage) { // remove old listeners if(m_DataStorage != 0) { this->m_DataStorage->AddNodeEvent.RemoveListener( mitk::MessageDelegate1( this, &QmitkDataStorageListModel::NodeAdded ) ); this->m_DataStorage->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1( this, &QmitkDataStorageListModel::NodeRemoved ) ); // remove delete observer m_DataStorage->RemoveObserver(m_DataStorageDeleteObserverTag); // this is good coding style ! reset variables whenever they are not used anymore. m_DataStorageDeleteObserverTag = 0; } m_DataStorage = dataStorage; // remove event listeners if(m_DataStorage != 0) { // subscribe for node added/removed events this->m_DataStorage->AddNodeEvent.AddListener( mitk::MessageDelegate1( this, &QmitkDataStorageListModel::NodeAdded ) ); this->m_DataStorage->RemoveNodeEvent.AddListener( mitk::MessageDelegate1( this, &QmitkDataStorageListModel::NodeRemoved ) ); // add itk delete listener on datastorage itk::MemberCommand::Pointer deleteCommand = itk::MemberCommand::New(); deleteCommand->SetCallbackFunction(this, &QmitkDataStorageListModel::OnDelete); // add observer m_DataStorageDeleteObserverTag = m_DataStorage->AddObserver(itk::DeleteEvent(), deleteCommand); } // reset model reset(); } } Qt::ItemFlags QmitkDataStorageListModel::flags(const QModelIndex&) const { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } QVariant QmitkDataStorageListModel::data(const QModelIndex& index, int role) const { if(index.isValid()) { switch ( role ) { case Qt::DisplayRole: { const mitk::DataNode* node = m_DataNodes.at(index.row()); std::string name = node->GetName(); return QVariant(QString::fromStdString(name)); } break; } } // index.isValid() return QVariant(); } QVariant QmitkDataStorageListModel::headerData(int /*section*/, Qt::Orientation /*orientation*/, int /*role*/) const { return QVariant("Nodes"); } int QmitkDataStorageListModel::rowCount(const QModelIndex& /*parent*/) const { return m_DataNodes.size(); } std::vector QmitkDataStorageListModel::GetDataNodes() const { return m_DataNodes; } mitk::DataStorage::Pointer QmitkDataStorageListModel::GetDataStorage() const { return m_DataStorage; } void QmitkDataStorageListModel::SetPredicate(mitk::NodePredicateBase* pred) { m_NodePredicate = pred; reset(); QAbstractListModel::reset(); } mitk::NodePredicateBase* QmitkDataStorageListModel::GetPredicate() const { return m_NodePredicate; } void QmitkDataStorageListModel::reset() { if(m_DataStorage != 0) { mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects; if (m_NodePredicate) setOfObjects = m_DataStorage->GetSubset(m_NodePredicate); else setOfObjects = m_DataStorage->GetAll(); // remove all observes unsigned int i = 0; for(std::vector::iterator it=m_DataNodes.begin() ; it!=m_DataNodes.end() ; ++it, ++i) { (*it)->RemoveObserver(m_DataNodesModifiedObserversTags[i]); } // clear vector with nodes m_DataNodesModifiedObserversTags.clear(); m_DataNodes.clear(); itk::MemberCommand::Pointer modifiedCommand; // copy all selected nodes the vector for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt, ++i) // for each node { // add modified observer modifiedCommand = itk::MemberCommand::New(); modifiedCommand->SetCallbackFunction(this, &QmitkDataStorageListModel::OnModified); m_DataNodesModifiedObserversTags.push_back( m_DataStorage->AddObserver(itk::ModifiedEvent(), modifiedCommand) ); m_DataNodes.push_back( nodeIt.Value().GetPointer()); } // for } // m_DataStorage != 0 } // reset() void QmitkDataStorageListModel::NodeAdded( const mitk::DataNode* node ) { // garantuee no recursions when a new node event is thrown if(!m_BlockEvents) { m_BlockEvents = true; // check if node should be added to the model bool addNode = true; if(m_NodePredicate && !m_NodePredicate->CheckNode(node)) addNode = false; if(addNode) { beginInsertRows(QModelIndex(), m_DataNodes.size(), m_DataNodes.size()); //reset(); m_DataNodes.push_back(const_cast(node)); endInsertRows(); } m_BlockEvents = false; } } void QmitkDataStorageListModel::NodeRemoved( const mitk::DataNode* node ) { // garantuee no recursions when a new node event is thrown if(!m_BlockEvents) { m_BlockEvents = true; int row = -1; //bool removeNode = false; // check if node is contained in current list, if yes: reset model for (std::vector::const_iterator nodeIt = m_DataNodes.begin() ; nodeIt != m_DataNodes.end(); nodeIt++) // for each node { row++; if( (*nodeIt) == node ) { // node found, remove it beginRemoveRows(QModelIndex(), row, row); m_DataNodes.erase(std::find(m_DataNodes.begin(), m_DataNodes.end(), (*nodeIt))); endRemoveRows(); break; } } m_BlockEvents = false; } } void QmitkDataStorageListModel::OnModified( const itk::Object *caller, const itk::EventObject & /*event*/ ) { if(m_BlockEvents) return; const mitk::DataNode* modifiedNode = dynamic_cast(caller); if(modifiedNode) { int row = std::distance(std::find(m_DataNodes.begin(), m_DataNodes.end(), modifiedNode), m_DataNodes.end()); QModelIndex indexOfChangedProperty = index(row, 1); emit dataChanged(indexOfChangedProperty, indexOfChangedProperty); } } void QmitkDataStorageListModel::OnDelete( const itk::Object *caller, const itk::EventObject & /*event*/ ) { if(m_BlockEvents) return; const mitk::DataStorage* dataStorage = dynamic_cast(caller); if(dataStorage) { // set datastorage to 0 -> empty model this->SetDataStorage(0); } } mitk::DataNode::Pointer QmitkDataStorageListModel::getNode( const QModelIndex &index ) const { mitk::DataNode::Pointer node; if(index.isValid()) { node = m_DataNodes.at(index.row()); } return node; -} \ No newline at end of file +} diff --git a/Modules/Qmitk/QmitkNodeDescriptor.cpp b/Modules/Qmitk/QmitkNodeDescriptor.cpp index a52afe2b46..c1f6e2fa8d 100644 --- a/Modules/Qmitk/QmitkNodeDescriptor.cpp +++ b/Modules/Qmitk/QmitkNodeDescriptor.cpp @@ -1,109 +1,109 @@ /*=================================================================== 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 "QmitkNodeDescriptor.h" #include #include #include #include #include QmitkNodeDescriptor::QmitkNodeDescriptor( const QString& _ClassName, const QString& _PathToIcon , mitk::NodePredicateBase* _Predicate, QObject* parent ) : QObject(parent) , m_ClassName(_ClassName) , m_PathToIcon(_PathToIcon) , m_Predicate(_Predicate) , m_Separator(new QAction(this)) { m_Separator->setSeparator(true); } QString QmitkNodeDescriptor::GetClassName() const { return m_ClassName; } QIcon QmitkNodeDescriptor::GetIcon() const { return QIcon(m_PathToIcon); } QList QmitkNodeDescriptor::GetActions() const { return m_Actions; } bool QmitkNodeDescriptor::CheckNode( const mitk::DataNode* node ) const { if(m_Predicate.IsNotNull()) return m_Predicate->CheckNode(node); return false; } void QmitkNodeDescriptor::AddAction( QAction* action, bool isBatchAction ) { if(!action) return; if(isBatchAction) m_BatchActions.push_back(action); else m_Actions.push_back(action); QObject::connect( action, SIGNAL( destroyed(QObject *) ) , this, SLOT( ActionDestroyed(QObject *) ) ); } void QmitkNodeDescriptor::RemoveAction( QAction* _Action ) { int index = m_Actions.indexOf(_Action); int indexOfWidgetAction = m_BatchActions.indexOf(_Action); if(index != -1) { m_Actions.removeAt(index); } else if(indexOfWidgetAction != -1) { m_BatchActions.removeAt(indexOfWidgetAction); } if( _Action != 0) { QObject::disconnect( _Action, SIGNAL( destroyed(QObject *) ) , this, SLOT( ActionDestroyed(QObject *) ) ); } } QmitkNodeDescriptor::~QmitkNodeDescriptor() { // all children are destroyed here by Qt } QAction* QmitkNodeDescriptor::GetSeparator() const { return m_Separator; } QList QmitkNodeDescriptor::GetBatchActions() const { return m_BatchActions; } void QmitkNodeDescriptor::ActionDestroyed( QObject * obj /*= 0 */ ) { this->RemoveAction( qobject_cast(obj) ); -} \ No newline at end of file +} diff --git a/Modules/QmitkExt/QmitkBinaryThresholdToolGUI.cpp b/Modules/QmitkExt/QmitkBinaryThresholdToolGUI.cpp index 55b5ddc50e..15497af410 100644 --- a/Modules/QmitkExt/QmitkBinaryThresholdToolGUI.cpp +++ b/Modules/QmitkExt/QmitkBinaryThresholdToolGUI.cpp @@ -1,210 +1,210 @@ /*=================================================================== 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 "QmitkBinaryThresholdToolGUI.h" #include "QmitkNewSegmentationDialog.h" #include #include #include #include MITK_TOOL_GUI_MACRO(QmitkExt_EXPORT, QmitkBinaryThresholdToolGUI, "") QmitkBinaryThresholdToolGUI::QmitkBinaryThresholdToolGUI() :QmitkToolGUI(), m_Slider(NULL), m_Spinner(NULL), m_isFloat(false), m_RangeMin(0), m_RangeMax(0), m_ChangingSlider(false), m_ChangingSpinner(false) { // create the visible widgets QBoxLayout* mainLayout = new QVBoxLayout(this); QLabel* label = new QLabel( "Threshold :", this ); QFont f = label->font(); f.setBold(false); label->setFont( f ); mainLayout->addWidget(label); QBoxLayout* layout = new QHBoxLayout(); m_Spinner = new QDoubleSpinBox(); m_Spinner->setMaximum(20); m_Spinner->setMinimum(5); m_Spinner->setValue(1); connect(m_Spinner, SIGNAL(valueChanged(double)), this, SLOT(OnSpinnerValueChanged()) ); layout->addWidget(m_Spinner); //m_Slider = new QSlider( 5, 20, 1, 1, Qt::Horizontal, this ); m_Slider = new QSlider( Qt::Horizontal, this ); m_Slider->setMinimum(5); m_Slider->setMaximum(20); m_Slider->setPageStep(1); m_Slider->setValue(1); connect( m_Slider, SIGNAL(valueChanged(int)), this, SLOT(OnSliderValueChanged(int))); layout->addWidget( m_Slider ); QPushButton* okButton = new QPushButton("Ok", this); connect( okButton, SIGNAL(clicked()), this, SLOT(OnAcceptThresholdPreview())); okButton->setFont( f ); layout->addWidget( okButton ); mainLayout->addLayout(layout); connect( this, SIGNAL(NewToolAssociated(mitk::Tool*)), this, SLOT(OnNewToolAssociated(mitk::Tool*)) ); } QmitkBinaryThresholdToolGUI::~QmitkBinaryThresholdToolGUI() { // !!! if (m_BinaryThresholdTool.IsNotNull()) { m_BinaryThresholdTool->IntervalBordersChanged -= mitk::MessageDelegate3( this, &QmitkBinaryThresholdToolGUI::OnThresholdingIntervalBordersChanged ); m_BinaryThresholdTool->ThresholdingValueChanged -= mitk::MessageDelegate1( this, &QmitkBinaryThresholdToolGUI::OnThresholdingValueChanged ); } } void QmitkBinaryThresholdToolGUI::OnNewToolAssociated(mitk::Tool* tool) { if (m_BinaryThresholdTool.IsNotNull()) { m_BinaryThresholdTool->IntervalBordersChanged -= mitk::MessageDelegate3( this, &QmitkBinaryThresholdToolGUI::OnThresholdingIntervalBordersChanged ); m_BinaryThresholdTool->ThresholdingValueChanged -= mitk::MessageDelegate1( this, &QmitkBinaryThresholdToolGUI::OnThresholdingValueChanged ); } m_BinaryThresholdTool = dynamic_cast( tool ); if (m_BinaryThresholdTool.IsNotNull()) { m_BinaryThresholdTool->IntervalBordersChanged += mitk::MessageDelegate3( this, &QmitkBinaryThresholdToolGUI::OnThresholdingIntervalBordersChanged ); m_BinaryThresholdTool->ThresholdingValueChanged += mitk::MessageDelegate1( this, &QmitkBinaryThresholdToolGUI::OnThresholdingValueChanged ); } } void QmitkBinaryThresholdToolGUI::OnSpinnerValueChanged() { if (m_BinaryThresholdTool.IsNotNull()) { m_ChangingSpinner = true; double doubleVal = m_Spinner->value(); int intVal = this->DoubleToSliderInt(doubleVal); m_BinaryThresholdTool->SetThresholdValue( doubleVal ); if (m_ChangingSlider == false) m_Slider->setValue( intVal ); m_ChangingSpinner = false; } } void QmitkBinaryThresholdToolGUI::OnSliderValueChanged(int value) { if (m_BinaryThresholdTool.IsNotNull()) { m_ChangingSlider = true; double doubleVal = SliderIntToDouble(value); if (m_ChangingSpinner == false) m_Spinner->setValue(doubleVal); m_ChangingSlider = false; } } void QmitkBinaryThresholdToolGUI::OnAcceptThresholdPreview() { if (m_BinaryThresholdTool.IsNotNull()) { QmitkNewSegmentationDialog* dialog = new QmitkNewSegmentationDialog( this ); // needs a QWidget as parent, "this" is not QWidget dialog->setPrompt("What did you just segment?"); int dialogReturnValue = dialog->exec(); std::string organName = dialog->GetSegmentationName().toStdString(); mitk::Color color = dialog->GetColor(); delete dialog; if ( dialogReturnValue != QDialog::Rejected ) // user clicked cancel or pressed Esc or something similar { m_BinaryThresholdTool->AcceptCurrentThresholdValue( organName, color ); } else { m_BinaryThresholdTool->CancelThresholding(); } } } void QmitkBinaryThresholdToolGUI::OnThresholdingIntervalBordersChanged(double lower, double upper, bool isFloat) { m_isFloat = isFloat; m_RangeMin = lower; m_RangeMax = upper; m_Spinner->setRange(lower, upper); if (!m_isFloat) { m_Slider->setRange(int(lower), int(upper)); m_Spinner->setDecimals(0); m_Spinner->setSingleStep(1); } else { m_Slider->setRange(0, 99); m_Spinner->setDecimals(2); m_Range = upper-lower; m_Spinner->setSingleStep(m_Range/100); } } void QmitkBinaryThresholdToolGUI::OnThresholdingValueChanged(double current) { m_Slider->setValue(DoubleToSliderInt(current)); m_Spinner->setValue(current); } double QmitkBinaryThresholdToolGUI::SliderIntToDouble(int val) { if (!m_isFloat) { return double(val); } else { return double(val*(m_Range)/100 + m_RangeMin); } } int QmitkBinaryThresholdToolGUI::DoubleToSliderInt(double val) { if (!m_isFloat) { return int(val); } else { int intVal = int( ((val-m_RangeMin) / m_Range)*100); return intVal; } -} \ No newline at end of file +} diff --git a/Modules/QmitkExt/QmitkBoundingObjectWidget.cpp b/Modules/QmitkExt/QmitkBoundingObjectWidget.cpp index 7cd8faa6fe..e0e321ae24 100644 --- a/Modules/QmitkExt/QmitkBoundingObjectWidget.cpp +++ b/Modules/QmitkExt/QmitkBoundingObjectWidget.cpp @@ -1,468 +1,468 @@ /*=================================================================== 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 "QmitkBoundingObjectWidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "btnCube.xpm" #include "btnCylinder.xpm" #include "btnEllipsoid.xpm" #include "btnPyramid.xpm" QmitkBoundingObjectWidget::QmitkBoundingObjectWidget (QWidget* parent, Qt::WindowFlags f ):QWidget( parent, f ), m_DataStorage(NULL), m_lastSelectedItem(NULL), m_lastAffineObserver(NULL), m_ItemNodeMap(), m_BoundingObjectCounter(1) { QBoxLayout* mainLayout = new QVBoxLayout(this); QHBoxLayout* buttonLayout = new QHBoxLayout(); QStringList boList; boList << tr("add") << tr("cube") << tr("cone") << tr("ellipse") << tr("cylinder"); m_addComboBox = new QComboBox(); m_addComboBox->addItems(boList); m_addComboBox->setItemIcon(1, QIcon(btnCube_xpm)); m_addComboBox->setItemIcon(2, QIcon(btnPyramid_xpm)); m_addComboBox->setItemIcon(3, QIcon(btnEllipsoid_xpm)); m_addComboBox->setItemIcon(4, QIcon(btnCylinder_xpm)); buttonLayout->addWidget(m_addComboBox); m_DelButton = new QPushButton("del"); buttonLayout->addWidget(m_DelButton); m_SaveButton = new QPushButton("save"); buttonLayout->addWidget(m_SaveButton); m_SaveButton->setEnabled(false); m_LoadButton = new QPushButton("load"); buttonLayout->addWidget(m_LoadButton); m_LoadButton->setEnabled(false); m_TreeWidget = new QTreeWidget(this); m_TreeWidget->setColumnCount(3); QStringList sList; sList << tr("name") << tr("inverted") << tr("visible"); m_TreeWidget->setHeaderLabels(sList); m_TreeWidget->setColumnWidth(0, 250); m_TreeWidget->setColumnWidth(1, 50); m_TreeWidget->setColumnWidth(2, 50); m_TreeWidget->setAutoScroll(true); m_TreeWidget->setSelectionMode(QAbstractItemView::SingleSelection); mainLayout->addWidget(m_TreeWidget); mainLayout->addLayout(buttonLayout); connect( m_addComboBox , SIGNAL(currentIndexChanged(int)), this, SLOT(CreateBoundingObject(int)) ); connect( m_TreeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(SelectionChanged()) ); /*connect( m_SaveButton, SIGNAL(clicked()), this, SLOT(OnSaveButtonClicked()) ); connect( m_LoadButton, SIGNAL(clicked()), this, SLOT(OnLoadButtonClicked()) );*/ connect( m_DelButton, SIGNAL(clicked()), this, SLOT(OnDelButtonClicked()) ); connect(m_TreeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(OnItemDoubleClicked(QTreeWidgetItem*, int)) ); connect(m_TreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(OnItemDataChanged(QTreeWidgetItem*, int)) ); } QmitkBoundingObjectWidget::~QmitkBoundingObjectWidget() { } void QmitkBoundingObjectWidget::setEnabled(bool flag) { ItemNodeMapType::iterator it = m_ItemNodeMap.begin(); while( it != m_ItemNodeMap.end()) { mitk::DataNode* node = it->second; QTreeWidgetItem* item = it->first; if (flag) node->SetVisibility(item->checkState(2)); else node->SetVisibility(flag); ++it; } QWidget::setEnabled(flag); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkBoundingObjectWidget::SelectionChanged() { QList selectedItems = m_TreeWidget->selectedItems(); if (selectedItems.size() < 1) return; QTreeWidgetItem* selectedItem = selectedItems.first(); if (selectedItem == m_lastSelectedItem) return; if (m_lastSelectedItem != NULL) { m_TreeWidget->closePersistentEditor(m_lastSelectedItem, 0); ItemNodeMapType::iterator it = m_ItemNodeMap.find(m_lastSelectedItem); if (it != m_ItemNodeMap.end()) { mitk::DataNode* last_node = it->second; //remove observer last_node->RemoveObserver(m_lastAffineObserver); //get and remove interactor mitk::AffineInteractor::Pointer last_interactor = dynamic_cast (last_node->GetInteractor()); if (last_interactor) mitk::GlobalInteraction::GetInstance()->RemoveInteractor(last_interactor); } } ItemNodeMapType::iterator it = m_ItemNodeMap.find(selectedItem); if (it == m_ItemNodeMap.end()) return; mitk::DataNode* new_node = it->second; mitk::AffineInteractor::Pointer new_interactor = mitk::AffineInteractor::New("AffineInteractions ctrl-drag", new_node); new_node->SetInteractor(new_interactor); mitk::GlobalInteraction::GetInstance()->AddInteractor(new_interactor); //create observer for node itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction(this, &QmitkBoundingObjectWidget::OnBoundingObjectModified); m_lastAffineObserver = new_node->AddObserver(mitk::AffineInteractionEvent(), command); m_lastSelectedItem = selectedItem; } void QmitkBoundingObjectWidget::AddItem(mitk::DataNode* node) { mitk::BoundingObject* boundingObject; boundingObject = dynamic_cast (node->GetData()); std::string name; node->GetStringProperty("name", name); if (boundingObject) { QTreeWidgetItem* item = new QTreeWidgetItem(); item->setData(0, Qt::EditRole, QString::fromLocal8Bit(name.c_str())); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable); //checkbox for positive flag item->setData(1, Qt::CheckStateRole, tr("")); item->setCheckState(1, Qt::Unchecked); //checkbox for visibleflag item->setData(2, Qt::CheckStateRole, tr("")); item->setCheckState(2, Qt::Checked); m_TreeWidget->addTopLevelItem(item); m_ItemNodeMap.insert(std::make_pair(item, node)); m_TreeWidget->selectAll(); QList items = m_TreeWidget->selectedItems(); for( int i = 0; isetItemSelected(items.at(i), false); } m_TreeWidget->setItemSelected(item, true); } else MITK_ERROR << name << " is not a bounding object or does not exist in data storage" << endl; } void QmitkBoundingObjectWidget::OnItemDoubleClicked(QTreeWidgetItem* item, int col) { if (col == 0) { m_TreeWidget->openPersistentEditor(item, col); } } void QmitkBoundingObjectWidget::OnItemDataChanged(QTreeWidgetItem *item, int col) { if (m_ItemNodeMap.size() < 1) return; ItemNodeMapType::iterator it = m_ItemNodeMap.find(item); if (it == m_ItemNodeMap.end()) return; mitk::DataNode* node = it->second; //name if (col == 0) { m_TreeWidget->closePersistentEditor(item, col); node->SetName(item->text(0).toLocal8Bit().data()); } //positive else if (col == 1) { mitk::BoundingObject* boundingObject = dynamic_cast (node->GetData()); if (boundingObject) boundingObject->SetPositive(!(item->checkState(1))); emit BoundingObjectsChanged(); } //visible else if (col == 2) { node->SetVisibility(item->checkState(2)); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkBoundingObjectWidget::RemoveItem() { //selection mode is set to single selection, so there should not be more than one selected item QList selectedItems = m_TreeWidget->selectedItems(); QTreeWidgetItem* item = selectedItems.first(); QString str = item->text(0); ItemNodeMapType::iterator it = m_ItemNodeMap.find(item); if (it == m_ItemNodeMap.end()) return; mitk::DataNode* node = it->second; mitk::BoundingObject* boundingObject; if (node) { boundingObject = dynamic_cast (node->GetData()); if (boundingObject) { //delete item; m_TreeWidget->takeTopLevelItem(m_TreeWidget->indexOfTopLevelItem(item)); m_ItemNodeMap.erase(m_ItemNodeMap.find(item)); m_DataStorage->Remove(node); } } } void QmitkBoundingObjectWidget::RemoveAllItems() { ItemNodeMapType::iterator it = m_ItemNodeMap.begin(); while( it != m_ItemNodeMap.end() ) { m_TreeWidget->takeTopLevelItem( m_TreeWidget->indexOfTopLevelItem(it->first) ); m_ItemNodeMap.erase(m_ItemNodeMap.find(it->first)); ++it; } m_BoundingObjectCounter = 1; } mitk::BoundingObject::Pointer QmitkBoundingObjectWidget::GetSelectedBoundingObject() { mitk::BoundingObject* boundingObject; mitk::DataNode* node = this->GetSelectedBoundingObjectNode(); if (node) { boundingObject = dynamic_cast (node->GetData()); if (boundingObject) return boundingObject; } return NULL; } void QmitkBoundingObjectWidget::SetDataStorage(mitk::DataStorage* dataStorage) { m_DataStorage = dataStorage; } mitk::DataStorage* QmitkBoundingObjectWidget::GetDataStorage() { return m_DataStorage; } //void QmitkBoundingObjectWidget::OnSaveButtonClicked() //{ // //} // //void QmitkBoundingObjectWidget::OnLoadButtonClicked() //{ // //} void QmitkBoundingObjectWidget::OnDelButtonClicked() { RemoveItem(); } void QmitkBoundingObjectWidget::CreateBoundingObject(int type) { //get cross position mitk::Point3D pos; mitk::RenderingManager::RenderWindowVector windows = mitk::RenderingManager::GetInstance()->GetAllRegisteredRenderWindows(); //hopefully we have the renderwindows in the "normal" order const mitk::PlaneGeometry *plane1 = mitk::BaseRenderer::GetInstance(windows.at(0))->GetSliceNavigationController()->GetCurrentPlaneGeometry(); const mitk::PlaneGeometry *plane2 = mitk::BaseRenderer::GetInstance(windows.at(1))->GetSliceNavigationController()->GetCurrentPlaneGeometry(); const mitk::PlaneGeometry *plane3 = mitk::BaseRenderer::GetInstance(windows.at(2))->GetSliceNavigationController()->GetCurrentPlaneGeometry(); mitk::Line3D line; if ( (plane1 != NULL) && (plane2 != NULL) && (plane1->IntersectionLine( plane2, line )) ) { if ( !((plane3 != NULL) && (plane3->IntersectionPoint( line, pos ))) ) { return; } } if (type != 0) { mitk::BoundingObject::Pointer boundingObject; QString name; name.setNum(m_BoundingObjectCounter); switch (type-1) { case CUBOID: boundingObject = mitk::Cuboid::New(); name.prepend("Cube_"); break; case CONE: boundingObject = mitk::Cone::New(); name.prepend("Cone_"); break; case ELLIPSOID: boundingObject = mitk::Ellipsoid::New(); name.prepend("Ellipse_"); break; case CYLINDER: boundingObject = mitk::Cylinder::New(); name.prepend("Cylinder_"); break; default: return; break; } m_BoundingObjectCounter++; m_addComboBox->setCurrentIndex(0); // set initial size mitk::Vector3D size; size.Fill(10); boundingObject->GetGeometry()->SetSpacing( size ); boundingObject->GetGeometry()->Translate(pos.GetVectorFromOrigin()); boundingObject->GetTimeSlicedGeometry()->UpdateInformation(); //create node mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( boundingObject); node->SetProperty("name", mitk::StringProperty::New( name.toLocal8Bit().data())); node->SetProperty("color", mitk::ColorProperty::New(0.0, 0.0, 1.0)); node->SetProperty("opacity", mitk::FloatProperty::New(0.7)); node->SetProperty("bounding object", mitk::BoolProperty::New(true)); node->SetProperty("helper object", mitk::BoolProperty::New(true)); m_DataStorage->Add(node); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); emit BoundingObjectsChanged(); AddItem(node); } } mitk::DataNode::Pointer QmitkBoundingObjectWidget::GetAllBoundingObjects() { mitk::DataNode::Pointer boundingObjectGroupNode = mitk::DataNode::New(); mitk::BoundingObjectGroup::Pointer boundingObjectGroup = mitk::BoundingObjectGroup::New(); boundingObjectGroup->SetCSGMode(mitk::BoundingObjectGroup::Union); mitk::NodePredicateProperty::Pointer prop = mitk::NodePredicateProperty::New("bounding object", mitk::BoolProperty::New(true)); mitk::DataStorage::SetOfObjects::ConstPointer allBO = m_DataStorage->GetSubset(prop); for (mitk::DataStorage::SetOfObjects::const_iterator it = allBO->begin(); it != allBO->end(); ++it) { mitk::DataNode::Pointer node = *it; mitk::BoundingObject::Pointer boundingObject = dynamic_cast (node->GetData()); if (boundingObject) boundingObjectGroup->AddBoundingObject(boundingObject); } boundingObjectGroupNode->SetData(boundingObjectGroup); if (boundingObjectGroup->GetCount() >0) return boundingObjectGroupNode; return NULL; } mitk::DataNode::Pointer QmitkBoundingObjectWidget::GetSelectedBoundingObjectNode() { QList selectedItems = m_TreeWidget->selectedItems(); if (selectedItems.size() <1) return NULL; QTreeWidgetItem* item = selectedItems.first(); mitk::DataNode* node = m_ItemNodeMap.find(item)->second; return node; } void QmitkBoundingObjectWidget::OnBoundingObjectModified(const itk::EventObject& e) { emit BoundingObjectsChanged(); -} \ No newline at end of file +} diff --git a/Modules/QmitkExt/QmitkClosingToolGUI.cpp b/Modules/QmitkExt/QmitkClosingToolGUI.cpp index 98f6da4ce1..514506a95b 100644 --- a/Modules/QmitkExt/QmitkClosingToolGUI.cpp +++ b/Modules/QmitkExt/QmitkClosingToolGUI.cpp @@ -1,28 +1,28 @@ /*=================================================================== 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 "QmitkClosingToolGUI.h" MITK_TOOL_GUI_MACRO( , QmitkClosingToolGUI, "") QmitkClosingToolGUI::QmitkClosingToolGUI() { } QmitkClosingToolGUI::~QmitkClosingToolGUI() { -} \ No newline at end of file +} diff --git a/Modules/QmitkExt/QmitkClosingToolGUI.h b/Modules/QmitkExt/QmitkClosingToolGUI.h index 855708bf54..3f07c837ab 100644 --- a/Modules/QmitkExt/QmitkClosingToolGUI.h +++ b/Modules/QmitkExt/QmitkClosingToolGUI.h @@ -1,37 +1,37 @@ /*=================================================================== 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 QMITKCLOSINGTOOLGUI_H #define QMITKCLOSINGTOOLGUI_H #include "QmitkMorphologicToolGUI.h" #include "QmitkExtExports.h" class /*QmitkExt_EXPORTS*/ QmitkClosingToolGUI : public QmitkMorphologicToolGUI { Q_OBJECT public: mitkClassMacro(QmitkClosingToolGUI, QmitkMorphologicToolGUI); itkNewMacro(QmitkClosingToolGUI); protected: virtual ~QmitkClosingToolGUI(); QmitkClosingToolGUI(); }; -#endif \ No newline at end of file +#endif diff --git a/Modules/QmitkExt/QmitkDilateToolGUI.h b/Modules/QmitkExt/QmitkDilateToolGUI.h index c76085f1a3..4742fd1db7 100644 --- a/Modules/QmitkExt/QmitkDilateToolGUI.h +++ b/Modules/QmitkExt/QmitkDilateToolGUI.h @@ -1,37 +1,37 @@ /*=================================================================== 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 QMITKDILATETOOLGUI_H #define QMITKDILATETOOLGUI_H #include "QmitkMorphologicToolGUI.h" #include "QmitkExtExports.h" class /*QmitkExt_EXPORTS*/ QmitkDilateToolGUI : public QmitkMorphologicToolGUI { Q_OBJECT public: mitkClassMacro(QmitkDilateToolGUI, QmitkMorphologicToolGUI); itkNewMacro(QmitkDilateToolGUI); protected: virtual ~QmitkDilateToolGUI(); QmitkDilateToolGUI(); }; -#endif \ No newline at end of file +#endif diff --git a/Modules/QmitkExt/QmitkErodeToolGUI.cpp b/Modules/QmitkExt/QmitkErodeToolGUI.cpp index 4a0685378b..49d1fa4d01 100644 --- a/Modules/QmitkExt/QmitkErodeToolGUI.cpp +++ b/Modules/QmitkExt/QmitkErodeToolGUI.cpp @@ -1,28 +1,28 @@ /*=================================================================== 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 "QmitkErodeToolGUI.h" MITK_TOOL_GUI_MACRO( , QmitkErodeToolGUI, "") QmitkErodeToolGUI::QmitkErodeToolGUI() { } QmitkErodeToolGUI::~QmitkErodeToolGUI() { -} \ No newline at end of file +} diff --git a/Modules/QmitkExt/QmitkErodeToolGUI.h b/Modules/QmitkExt/QmitkErodeToolGUI.h index 5811166594..49d23efa69 100644 --- a/Modules/QmitkExt/QmitkErodeToolGUI.h +++ b/Modules/QmitkExt/QmitkErodeToolGUI.h @@ -1,37 +1,37 @@ /*=================================================================== 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 QMITKERODETOOLGUI_H #define QMITKERODETOOLGUI_H #include "QmitkMorphologicToolGUI.h" #include "QmitkExtExports.h" class /*QmitkExt_EXPORTS*/ QmitkErodeToolGUI : public QmitkMorphologicToolGUI { Q_OBJECT public: mitkClassMacro(QmitkErodeToolGUI, QmitkMorphologicToolGUI); itkNewMacro(QmitkErodeToolGUI); protected: virtual ~QmitkErodeToolGUI(); QmitkErodeToolGUI(); }; -#endif \ No newline at end of file +#endif diff --git a/Modules/QmitkExt/QmitkFileChooser.cpp b/Modules/QmitkExt/QmitkFileChooser.cpp index e9e901ab19..829b2ebfca 100644 --- a/Modules/QmitkExt/QmitkFileChooser.cpp +++ b/Modules/QmitkExt/QmitkFileChooser.cpp @@ -1,122 +1,122 @@ /*=================================================================== 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 "QmitkFileChooser.h" #include #include #include #include #include #include QmitkFileChooser::QmitkFileChooser(QWidget* parent, Qt::WindowFlags f ) : QWidget( parent, f ) , m_SelectDir( false ) , m_FileMustExist( true ) , m_SelectFile(new QPushButton("Select File")) , m_File( new QLineEdit ) { m_File->setReadOnly( true ); this->SetHorizotalLayout(false); connect( m_SelectFile, SIGNAL(clicked(bool)), this, SLOT( OnSelectFileClicked( bool ) ) ); connect( m_File, SIGNAL( editingFinished () ), this, SLOT( OnFileEditingFinished() ) ); } void QmitkFileChooser::SetHorizotalLayout(bool horizontalLayout) { QBoxLayout* layout = 0; if(horizontalLayout) layout = new QHBoxLayout; else layout = new QVBoxLayout; layout->setContentsMargins(0,0,0,0); layout->addWidget( m_File ); layout->addWidget( m_SelectFile ); this->setLayout( layout ); } void QmitkFileChooser::SetSelectDir( bool selectDir ) { m_SelectDir = selectDir; } void QmitkFileChooser::SetFileMustExist( bool fileMustExist ) { m_FileMustExist = fileMustExist; } void QmitkFileChooser::SetReadOnly( bool ReadOnly ) { m_File->setReadOnly( ReadOnly ); } void QmitkFileChooser::SetFile( const std::string& file ) { QFileInfo info( QString::fromStdString(file) ); if(info.exists() || m_FileMustExist == false) { m_File->setText( QString::fromStdString(file) ); emit NewFileSelected( file ); } } void QmitkFileChooser::SetFilePattern( const std::string& filepattern ) { m_FilePattern = QString::fromStdString(filepattern); } bool QmitkFileChooser::IsValidFile() const { QFileInfo info( m_File->text() ); return info.exists(); } std::string QmitkFileChooser::GetFile() const { return m_File->text().toStdString(); } void QmitkFileChooser::OnSelectFileClicked( bool /*checked*/ ) { QString filename; if( m_SelectDir ) filename = QFileDialog::getExistingDirectory( QApplication::activeWindow() , "Open directory", m_File->text() ); else { if (m_FileMustExist) filename = QFileDialog::getOpenFileName( QApplication::activeWindow() , "Open file", m_File->text(), m_FilePattern ); else filename = QFileDialog::getSaveFileName( QApplication::activeWindow() , "Open file", m_File->text(), m_FilePattern ); } if(!filename.isEmpty()) m_File->setText( filename ); emit NewFileSelected(filename.toStdString()); } void QmitkFileChooser::OnFileEditingFinished() { emit NewFileSelected( m_File->text().toStdString() ); -} \ No newline at end of file +} diff --git a/Modules/QmitkExt/QmitkMorphologicToolGUI.cpp b/Modules/QmitkExt/QmitkMorphologicToolGUI.cpp index b2c69dff95..c4e0e2e6e0 100644 --- a/Modules/QmitkExt/QmitkMorphologicToolGUI.cpp +++ b/Modules/QmitkExt/QmitkMorphologicToolGUI.cpp @@ -1,146 +1,146 @@ /*=================================================================== 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 "QmitkMorphologicToolGUI.h" #include "QmitkNewSegmentationDialog.h" #include #include #include #include #include MITK_TOOL_GUI_MACRO( , QmitkMorphologicToolGUI, "") QmitkMorphologicToolGUI::QmitkMorphologicToolGUI(): QmitkToolGUI(), m_Slider(NULL) { QBoxLayout* mainLayout = new QVBoxLayout(this); QBoxLayout* layout1 = new QHBoxLayout(); QBoxLayout* layout2 = new QHBoxLayout(); QBoxLayout* layout3 = new QHBoxLayout(); QLabel* label = new QLabel( "radius:", this ); QFont f = label->font(); f.setBold(false); label->setFont( f ); layout1->addWidget(label); m_Slider = new QSlider(Qt::Horizontal, this ); m_Slider->setMaximum(15); m_Slider->setMinimum(0); m_Slider->setPageStep(1); connect( m_Slider, SIGNAL(valueChanged(int)), this, SLOT(OnSliderValueChanged(int))); m_Slider->setValue( 0 ); layout1->addWidget( m_Slider ); m_SpinBox = new QSpinBox(this); m_SpinBox->setSuffix(tr(" pixel")); m_SpinBox->setMaximum(15); m_SpinBox->setMinimum(0); m_SpinBox->setSingleStep(1); connect(m_SpinBox, SIGNAL(editingFinished()), this, SLOT(OnSpinBoxValueChanged()) ); m_SpinBox->setValue(0); layout1->addWidget(m_SpinBox); QLabel* label1 = new QLabel("structuring element:", this); QButtonGroup* group = new QButtonGroup(this); QRadioButton* crossRadioButton = new QRadioButton("cross"); QRadioButton* ballRadioButton = new QRadioButton("ball"); ballRadioButton->setChecked(true); group->addButton(ballRadioButton, 1); group->addButton(crossRadioButton, 2); layout3->addWidget(label1); layout3->addWidget(ballRadioButton); layout3->addWidget(crossRadioButton); connect(group, SIGNAL(buttonClicked(int)), this, SLOT(OnStructElementChanged(int)) ); m_CheckBox = new QCheckBox("Preview" ,this); m_CheckBox->setCheckState(Qt::Checked); connect(m_CheckBox, SIGNAL(stateChanged(int)), this, SLOT(OnCheckStateChanged(int)) ); layout2->addWidget(m_CheckBox); QPushButton* okButton = new QPushButton("OK", this); connect(okButton, SIGNAL(clicked()), this, SLOT(OnAcceptPreview()) ); layout2->addWidget(okButton); mainLayout->addLayout(layout3); mainLayout->addLayout(layout1); mainLayout->addLayout(layout2); connect( this, SIGNAL(NewToolAssociated(mitk::Tool*)), this, SLOT(OnNewToolAssociated(mitk::Tool*)) ); } QmitkMorphologicToolGUI::~QmitkMorphologicToolGUI() { } void QmitkMorphologicToolGUI::OnSliderValueChanged(int value) { m_SpinBox->setValue(value); if (m_MorphologicTool.IsNotNull()) m_MorphologicTool->SetRadius(value); } void QmitkMorphologicToolGUI::OnSpinBoxValueChanged() { m_Slider->setValue(m_SpinBox->value()); } void QmitkMorphologicToolGUI::OnCheckStateChanged(int state) { if (m_MorphologicTool.IsNotNull()) m_MorphologicTool->SetPreview(state); } void QmitkMorphologicToolGUI::OnNewToolAssociated(mitk::Tool* tool) { m_MorphologicTool = dynamic_cast( tool ); } void QmitkMorphologicToolGUI::OnAcceptPreview() { if (m_MorphologicTool.IsNotNull()) { QmitkNewSegmentationDialog* dialog = new QmitkNewSegmentationDialog( this ); dialog->setPrompt("What did you just segment?"); int dialogReturnValue = dialog->exec(); std::string name = dialog->GetSegmentationName().toLocal8Bit().data(); mitk::Color color = dialog->GetColor(); delete dialog; if ( dialogReturnValue != QDialog::Rejected ) { m_MorphologicTool->AcceptPreview( name, color ); } else { m_MorphologicTool->CancelPreviewing(); } } } void QmitkMorphologicToolGUI::OnStructElementChanged(int id) { if (m_MorphologicTool.IsNotNull()) m_MorphologicTool->SetStructuringElementType(id); -} \ No newline at end of file +} diff --git a/Modules/QmitkExt/QmitkMorphologicToolGUI.h b/Modules/QmitkExt/QmitkMorphologicToolGUI.h index 58591b663d..e9b00336cb 100644 --- a/Modules/QmitkExt/QmitkMorphologicToolGUI.h +++ b/Modules/QmitkExt/QmitkMorphologicToolGUI.h @@ -1,55 +1,55 @@ /*=================================================================== 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 QMITKMORPHOLOGICTOOLGUI_H #define QMITKMORPHOLOGICTOOLGUI_H #include "QmitkToolGUI.h" #include "mitkMorphologicTool.h" #include "QmitkExtExports.h" #include #include #include class /*QmitkExt_EXPORTS*/ QmitkMorphologicToolGUI : public QmitkToolGUI { Q_OBJECT public: mitkClassMacro(QmitkMorphologicToolGUI, QmitkToolGUI); itkNewMacro(QmitkMorphologicToolGUI); protected slots: void OnNewToolAssociated(mitk::Tool*); void OnSliderValueChanged(int value); void OnSpinBoxValueChanged(); void OnCheckStateChanged(int state); void OnStructElementChanged(int id); void OnAcceptPreview(); protected: virtual ~QmitkMorphologicToolGUI(); QmitkMorphologicToolGUI(); mitk::MorphologicTool::Pointer m_MorphologicTool; QSlider* m_Slider; QSpinBox* m_SpinBox; QCheckBox* m_CheckBox; }; -#endif \ No newline at end of file +#endif diff --git a/Modules/QmitkExt/QmitkOpeningToolGUI.cpp b/Modules/QmitkExt/QmitkOpeningToolGUI.cpp index 8f46ade9d4..11f1b0cc0d 100644 --- a/Modules/QmitkExt/QmitkOpeningToolGUI.cpp +++ b/Modules/QmitkExt/QmitkOpeningToolGUI.cpp @@ -1,28 +1,28 @@ /*=================================================================== 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 "QmitkOpeningToolGUI.h" MITK_TOOL_GUI_MACRO( , QmitkOpeningToolGUI, "") QmitkOpeningToolGUI::QmitkOpeningToolGUI() { } QmitkOpeningToolGUI::~QmitkOpeningToolGUI() { -} \ No newline at end of file +} diff --git a/Modules/QmitkExt/QmitkOpeningToolGUI.h b/Modules/QmitkExt/QmitkOpeningToolGUI.h index 98b04b96a9..81a0938b94 100644 --- a/Modules/QmitkExt/QmitkOpeningToolGUI.h +++ b/Modules/QmitkExt/QmitkOpeningToolGUI.h @@ -1,37 +1,37 @@ /*=================================================================== 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 QMITKOPENINGTOOLGUI_H #define QMITKOPENINGTOOLGUI_H #include "QmitkMorphologicToolGUI.h" #include "QmitkExtExports.h" class /*QmitkExt_EXPORTS*/ QmitkOpeningToolGUI : public QmitkMorphologicToolGUI { Q_OBJECT public: mitkClassMacro(QmitkOpeningToolGUI, QmitkMorphologicToolGUI); itkNewMacro(QmitkOpeningToolGUI); protected: virtual ~QmitkOpeningToolGUI(); QmitkOpeningToolGUI(); }; -#endif \ No newline at end of file +#endif diff --git a/Modules/QmitkExt/QmitkPixelManipulationToolGUI.cpp b/Modules/QmitkExt/QmitkPixelManipulationToolGUI.cpp index 3f154c2589..11711ebba5 100644 --- a/Modules/QmitkExt/QmitkPixelManipulationToolGUI.cpp +++ b/Modules/QmitkExt/QmitkPixelManipulationToolGUI.cpp @@ -1,122 +1,122 @@ /*=================================================================== 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 "QmitkPixelManipulationToolGUI.h" #include #include #include MITK_TOOL_GUI_MACRO (, QmitkPixelManipulationToolGUI, ""); QmitkPixelManipulationToolGUI::QmitkPixelManipulationToolGUI() : QmitkToolGUI() { QBoxLayout* mainLayout = new QVBoxLayout(this); QRadioButton* radio1 = new QRadioButton("change the masked pixels by value: ", this); QRadioButton* radio2 = new QRadioButton("set the masked pixels to value: ", this); radio1->setChecked(true); connect(radio1, SIGNAL(toggled(bool)), this, SLOT(SetFixedValueOff(bool))); connect(radio2, SIGNAL(toggled(bool)), this, SLOT(SetFixedValueOn(bool))); mainLayout->addWidget(radio1); mainLayout->addWidget(radio2); m_Slider = new QSlider(Qt::Horizontal, this); m_Slider->setRange(-5000, 5000); m_Slider->setValue(0); connect(m_Slider, SIGNAL(valueChanged(int)), this, SLOT(OnSliderValueChanged(int)) ); m_Spinner = new QSpinBox(this); m_Spinner->setRange(-5000, 5000); m_Spinner->setValue(0); connect(m_Spinner, SIGNAL(editingFinished()), this, SLOT(OnSpinBoxChanged()) ); QBoxLayout* layout1 = new QHBoxLayout(); layout1->addWidget(m_Slider); layout1->addWidget(m_Spinner); QPushButton* okButton = new QPushButton("Ok"); connect(okButton, SIGNAL(clicked()), this, SLOT(OnOkButtonClicked()) ); mainLayout->addLayout(layout1); mainLayout->addWidget(okButton); connect( this, SIGNAL(NewToolAssociated(mitk::Tool*)), this, SLOT(OnNewToolAssociated(mitk::Tool*)) ); } QmitkPixelManipulationToolGUI::~QmitkPixelManipulationToolGUI() { if (m_PixelManipulationTool.IsNotNull()) { } } void QmitkPixelManipulationToolGUI::OnNewToolAssociated(mitk::Tool* tool) { if (m_PixelManipulationTool.IsNotNull()) { } m_PixelManipulationTool = dynamic_cast (tool); if (m_PixelManipulationTool.IsNotNull()) { } } void QmitkPixelManipulationToolGUI::SetFixedValueOff(bool flag) { if (flag) { if (m_PixelManipulationTool.IsNotNull()) m_PixelManipulationTool->FixedValueOff(); } } void QmitkPixelManipulationToolGUI::SetFixedValueOn(bool flag) { if (flag) { if (m_PixelManipulationTool.IsNotNull()) m_PixelManipulationTool->FixedValueOn(); } } void QmitkPixelManipulationToolGUI::OnSpinBoxChanged() { m_Slider->setValue(m_Spinner->value()); } void QmitkPixelManipulationToolGUI::OnSliderValueChanged(int value) { if (m_PixelManipulationTool.IsNotNull()) { m_PixelManipulationTool->SetValue(value); m_Spinner->setValue(value); } } void QmitkPixelManipulationToolGUI::OnOkButtonClicked() { if (m_PixelManipulationTool.IsNotNull()) { m_PixelManipulationTool->CalculateImage(); } -} \ No newline at end of file +} diff --git a/Modules/QmitkExt/QmitkPixelManipulationToolGUI.h b/Modules/QmitkExt/QmitkPixelManipulationToolGUI.h index 6a25f9c54c..f0c41cea89 100644 --- a/Modules/QmitkExt/QmitkPixelManipulationToolGUI.h +++ b/Modules/QmitkExt/QmitkPixelManipulationToolGUI.h @@ -1,52 +1,52 @@ /*=================================================================== 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 QMITKPIXELMANIPULATIONTOOLGUI_H #define QMITKPIXELMANIPULATIONTOOLGUI_H #include "QmitkToolGUI.h" #include "mitkPixelManipulationTool.h" #include "QmitkDataStorageComboBox.h" #include #include class QmitkPixelManipulationToolGUI : public QmitkToolGUI { Q_OBJECT public: mitkClassMacro(QmitkPixelManipulationToolGUI, QmitkToolGUI); itkNewMacro(QmitkPixelManipulationToolGUI); protected slots: void OnNewToolAssociated(mitk::Tool*); void OnSliderValueChanged(int); void OnSpinBoxChanged(); void OnOkButtonClicked(); void SetFixedValueOn(bool); void SetFixedValueOff(bool); protected: QmitkPixelManipulationToolGUI(); virtual ~QmitkPixelManipulationToolGUI(); mitk::PixelManipulationTool::Pointer m_PixelManipulationTool; QSlider* m_Slider; QSpinBox* m_Spinner; };//class -#endif \ No newline at end of file +#endif diff --git a/Modules/QmitkExt/QmitkToolRoiDataSelectionBox.cpp b/Modules/QmitkExt/QmitkToolRoiDataSelectionBox.cpp index fa6f17c6cf..613f455460 100644 --- a/Modules/QmitkExt/QmitkToolRoiDataSelectionBox.cpp +++ b/Modules/QmitkExt/QmitkToolRoiDataSelectionBox.cpp @@ -1,197 +1,197 @@ /*=================================================================== 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 "QmitkToolRoiDataSelectionBox.h" #include #include #include QmitkToolRoiDataSelectionBox::QmitkToolRoiDataSelectionBox(QWidget* parent, mitk::DataStorage* storage) :QWidget(parent), m_SelfCall(false), m_lastSelection(mitk::DataNode::New()), m_lastSelectedName(tr("none")) { QBoxLayout* mainLayout = new QVBoxLayout(this); m_segmentationComboBox = new QComboBox(this); QLabel* label = new QLabel("region of interest:", this); m_boundingObjectWidget = new QmitkBoundingObjectWidget(); mainLayout->addWidget(label); mainLayout->addWidget(m_segmentationComboBox); mainLayout->addWidget(m_boundingObjectWidget); //connect signals connect(m_segmentationComboBox, SIGNAL(activated(const QString&)), this, SLOT(OnRoiDataSelectionChanged(const QString&)) ); connect(m_boundingObjectWidget, SIGNAL(BoundingObjectsChanged()), this, SLOT(OnRoiDataSelectionChanged())); //create ToolManager m_ToolManager = mitk::ToolManager::New(storage); //setup message delegates m_ToolManager->RoiDataChanged += mitk::MessageDelegate (this, &QmitkToolRoiDataSelectionBox::OnToolManagerRoiDataModified); mainLayout->deleteLater(); label->deleteLater(); } QmitkToolRoiDataSelectionBox::~QmitkToolRoiDataSelectionBox() { delete m_segmentationComboBox; delete m_boundingObjectWidget; m_ToolManager->GetDataStorage()->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1( this, &QmitkToolRoiDataSelectionBox::DataStorageChanged ) ); } void QmitkToolRoiDataSelectionBox::SetDataStorage(mitk::DataStorage &storage) { m_ToolManager->SetDataStorage(storage); m_boundingObjectWidget->SetDataStorage(&storage); UpdateComboBoxData(); storage.RemoveNodeEvent.AddListener( mitk::MessageDelegate1( this, &QmitkToolRoiDataSelectionBox::DataStorageChanged ) ); } mitk::DataStorage* QmitkToolRoiDataSelectionBox::GetDataStorage() { return m_ToolManager->GetDataStorage(); } void QmitkToolRoiDataSelectionBox::SetToolManager(mitk::ToolManager& manager) { //remove old messagedelegates m_ToolManager->RoiDataChanged -= mitk::MessageDelegate (this, &QmitkToolRoiDataSelectionBox::OnToolManagerRoiDataModified); //set new toolmanager m_ToolManager = &manager; //add new message delegates m_ToolManager->RoiDataChanged += mitk::MessageDelegate (this, &QmitkToolRoiDataSelectionBox::OnToolManagerRoiDataModified); } mitk::ToolManager* QmitkToolRoiDataSelectionBox::GetToolManager() { return m_ToolManager; } void QmitkToolRoiDataSelectionBox::OnToolManagerRoiDataModified() { if (m_SelfCall) return; UpdateComboBoxData(); } void QmitkToolRoiDataSelectionBox::DataStorageChanged(const mitk::DataNode* node ) { if (m_SelfCall) return; if ( this->GetDataStorage()->GetAll()->size() == 1 ) { m_boundingObjectWidget->RemoveAllItems(); } } void QmitkToolRoiDataSelectionBox::OnRoiDataSelectionChanged() { this->OnRoiDataSelectionChanged(tr("bounding objects")); } void QmitkToolRoiDataSelectionBox::OnRoiDataSelectionChanged(const QString& name) { if (name.compare(tr("")) == 0) return; m_lastSelectedName = name; m_boundingObjectWidget->setEnabled(false); mitk::DataNode::Pointer selection = NULL; if ( name.compare(tr("none"))==0) m_segmentationComboBox->setCurrentIndex(0); else if (name.compare(tr("bounding objects"))==0) { m_boundingObjectWidget->setEnabled(true); selection = m_boundingObjectWidget->GetAllBoundingObjects(); } else { selection = m_ToolManager->GetDataStorage()->GetNamedNode(name.toLocal8Bit().data()); if (m_lastSelection.IsNotNull()) m_lastSelection->SetProperty("outline binary", mitk::BoolProperty::New(false)); } if (selection == m_lastSelection) return; m_lastSelection = selection; if (m_lastSelection.IsNotNull()) { m_lastSelection->SetProperty("outline binary", mitk::BoolProperty::New(true)); m_lastSelection->SetProperty("outline width", mitk::FloatProperty::New(2.0)); } m_SelfCall = true; m_ToolManager->SetRoiData(selection); m_SelfCall = false; } void QmitkToolRoiDataSelectionBox::UpdateComboBoxData() { m_segmentationComboBox->clear(); m_segmentationComboBox->addItem(tr("none")); m_segmentationComboBox->insertSeparator(1); //predicates for combobox mitk::NodePredicateProperty::Pointer isBinary= mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)); mitk::NodePredicateDataType::Pointer isImage= mitk::NodePredicateDataType::New("Image"); mitk::NodePredicateProperty::Pointer isHelperObject= mitk::NodePredicateProperty::New("helper object", mitk::BoolProperty::New(true)); mitk::NodePredicateNot::Pointer isNotHelperObject = mitk::NodePredicateNot::New(isHelperObject); mitk::NodePredicateAnd::Pointer segmentationPredicate = mitk::NodePredicateAnd::New(isImage, isBinary, isNotHelperObject); mitk::DataStorage::SetOfObjects::ConstPointer allSegmentations = m_ToolManager->GetDataStorage()->GetSubset(segmentationPredicate); QStringList names; for (mitk::DataStorage::SetOfObjects::const_iterator it = allSegmentations->begin(); it != allSegmentations->end(); ++it) { mitk::DataNode::Pointer node = *it; QString name = QString::fromLocal8Bit(node->GetName().c_str()); names.append(name); } if (names.length() > 0) { m_segmentationComboBox->addItems(names); m_segmentationComboBox->insertSeparator(names.length()+2); } m_segmentationComboBox->addItem(tr("bounding objects")); int id = m_segmentationComboBox->findText(m_lastSelectedName); if (id < 0) this->OnRoiDataSelectionChanged(tr("none")); else m_segmentationComboBox->setCurrentIndex(id); } void QmitkToolRoiDataSelectionBox::setEnabled(bool flag) { if (!flag) this->OnRoiDataSelectionChanged(tr("none")); m_segmentationComboBox->setEnabled(flag); -} \ No newline at end of file +} diff --git a/Modules/QmitkExt/QmitkToolRoiDataSelectionBox.h b/Modules/QmitkExt/QmitkToolRoiDataSelectionBox.h index 48ae1e8b57..d79de9d6de 100644 --- a/Modules/QmitkExt/QmitkToolRoiDataSelectionBox.h +++ b/Modules/QmitkExt/QmitkToolRoiDataSelectionBox.h @@ -1,80 +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. ===================================================================*/ #ifndef QMITK_TOOLROIDATASELECTIONBOX_H #define QMITK_TOOLROIDATASELECTIONBOX_H #include "QmitkExtExports.h" #include "mitkToolManager.h" #include "QmitkBoundingObjectWidget.h" #include /** \brief Widget for defining a ROI inside the Interactive Segmentation Framwork \ingroup ToolManagerEtAl \ingroup Widgets Allows to define a Region of interest (ROI) either by existing segmentations or by bounding objects. Selection is possible via a combobox, listing all available segmentations. Item "bounding objects" activates the \ref QmitkBoundingObjectWidget. */ class QmitkExt_EXPORT QmitkToolRoiDataSelectionBox : public QWidget { Q_OBJECT public: QmitkToolRoiDataSelectionBox(QWidget* parent = 0, mitk::DataStorage* storage = 0); virtual ~QmitkToolRoiDataSelectionBox(); mitk::DataStorage* GetDataStorage(); void SetDataStorage(mitk::DataStorage& storage); mitk::ToolManager* GetToolManager(); void SetToolManager(mitk::ToolManager& manager); void OnToolManagerRoiDataModified(); void DataStorageChanged(const mitk::DataNode* node ); mitk::ToolManager::DataVectorType GetSelection(); void UpdateComboBoxData(); void setEnabled(bool); signals: void RoiDataSelected(const mitk::DataNode* node); protected slots: void OnRoiDataSelectionChanged(const QString& name); void OnRoiDataSelectionChanged(); protected: QmitkBoundingObjectWidget* m_boundingObjectWidget; QComboBox* m_segmentationComboBox; mitk::ToolManager::Pointer m_ToolManager; bool m_SelfCall; mitk::DataNode::Pointer m_lastSelection; QString m_lastSelectedName; }; -#endif \ No newline at end of file +#endif diff --git a/Modules/QmitkExt/QmitkVideoBackground.cpp b/Modules/QmitkExt/QmitkVideoBackground.cpp index e5e5890cf0..fb212fc568 100644 --- a/Modules/QmitkExt/QmitkVideoBackground.cpp +++ b/Modules/QmitkExt/QmitkVideoBackground.cpp @@ -1,302 +1,302 @@ /*=================================================================== 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 "QmitkVideoBackground.h" // MITK includes #include "mitkVtkLayerController.h" #include "mitkRenderingManager.h" // QT includes #include // itk includes #include // VTK includes #include #include #include #include #include #include #include #include #include #include #include #include QmitkVideoBackground::QmitkVideoBackground( QObject *parent ) : QObject(parent) , m_QTimer(new QTimer(this)) , m_VideoSource(0) , m_VideoSourceObserverTag(0) { this->ResetVideoBackground(); } QmitkVideoBackground::QmitkVideoBackground(mitk::VideoSource* v, int TimerDelay) : QObject(0) , m_QTimer(new QTimer(this)) , m_VideoSource(0) , m_VideoSourceObserverTag(0) { this->SetVideoSource( v ); this->ResetVideoBackground(); } void QmitkVideoBackground::ResetVideoBackground() { m_QTimer->setInterval(25); connect( m_QTimer, SIGNAL(timeout()), SLOT(UpdateVideo()) ); m_renderWindowVectorInfo.clear(); } QmitkVideoBackground::~QmitkVideoBackground() { this->Disable(); } void QmitkVideoBackground::AddRenderWindow(vtkRenderWindow* renderWindow ) { if(!renderWindow || !m_VideoSource) { MITK_WARN << "No Renderwindow or VideoSource set!"; return; } this->RemoveRenderWindow(renderWindow); vtkRenderer* videoRenderer = vtkRenderer::New(); vtkImageActor* videoActor = vtkImageActor::New(); vtkImageImport* videoImport = vtkImageImport::New(); videoImport->SetDataScalarTypeToUnsignedChar(); videoImport->SetNumberOfScalarComponents(3); if(m_VideoSource->GetImageWidth() == 0) m_VideoSource->FetchFrame(); videoImport->SetWholeExtent(0, m_VideoSource->GetImageWidth()-1, 0, m_VideoSource->GetImageHeight()-1, 0, 1-1); videoImport->SetDataExtentToWholeExtent(); VideoBackgroundVectorInfo v; v.renWin = renderWindow; v.videoRenderer = videoRenderer; v.videoActor = videoActor; v.videoImport = videoImport; // callback for the deletion of the renderwindow vtkSmartPointer deleteCallback = vtkSmartPointer::New(); deleteCallback->SetCallback ( QmitkVideoBackground::OnRenderWindowDelete ); deleteCallback->SetClientData(this); v.renderWindowObserverTag = renderWindow->AddObserver( vtkCommand::DeleteEvent, deleteCallback ); m_renderWindowVectorInfo.push_back(v); // completes the initialization this->Modified(); } void QmitkVideoBackground::RemoveRenderWindow( vtkRenderWindow* renderWindow ) { this->RemoveRenderWindow(renderWindow, true); } void QmitkVideoBackground::RemoveRenderWindow( vtkRenderWindow* renderWindow, bool removeObserver ) { // search for renderwindow and remove it for(RenderWindowVectorInfoType::iterator it = m_renderWindowVectorInfo.begin(); it != m_renderWindowVectorInfo.end(); it++) { if((*it).renWin == renderWindow) { mitk::VtkLayerController* layerController = mitk::VtkLayerController::GetInstance((*it).renWin); // unregister video backround renderer from renderwindow if( layerController ) layerController->RemoveRenderer((*it).videoRenderer); (*it).videoRenderer->Delete(); (*it).videoActor->Delete(); (*it).videoImport->Delete(); // remove listener if(removeObserver) renderWindow->RemoveObserver( (*it).renderWindowObserverTag ); m_renderWindowVectorInfo.erase(it); break; } } } bool QmitkVideoBackground::IsRenderWindowIncluded(vtkRenderWindow* renderWindow ) { for(RenderWindowVectorInfoType::iterator it = m_renderWindowVectorInfo.begin(); it != m_renderWindowVectorInfo.end(); it++) { if((*it).renWin == renderWindow) return true; } return false; } void QmitkVideoBackground::Pause() { m_QTimer->stop(); } void QmitkVideoBackground::Resume() { m_QTimer->start(); } /** * Enables drawing of the color Video background. * If you want to disable it, call the Disable() function. */ void QmitkVideoBackground::Enable() { UpdateVideo(); Modified(); m_QTimer->start(); } /** * Disables drawing of the color Video background. * If you want to enable it, call the Enable() function. */ void QmitkVideoBackground::Disable() { if ( this->IsEnabled() ) { mitk::VtkLayerController* layerController = 0; for(RenderWindowVectorInfoType::iterator it = m_renderWindowVectorInfo.begin(); it != m_renderWindowVectorInfo.end(); it++) { layerController = mitk::VtkLayerController::GetInstance((*it).renWin); if(layerController) layerController->RemoveRenderer((*it).videoRenderer); } m_QTimer->stop(); } } bool QmitkVideoBackground::IsEnabled() { return m_QTimer->isActive(); } void QmitkVideoBackground::UpdateVideo() { if( m_renderWindowVectorInfo.size() > 0 ) { unsigned char *src = 0; src = m_VideoSource->GetVideoTexture(); if(src) { for(RenderWindowVectorInfoType::iterator it = m_renderWindowVectorInfo.begin(); it != m_renderWindowVectorInfo.end(); it++) { (*it).videoImport->SetImportVoidPointer(src); (*it).videoImport->Modified(); (*it).videoImport->Update(); mitk::RenderingManager::GetInstance()->RequestUpdate((*it).renWin); } emit NewFrameAvailable ( m_VideoSource ); } else MITK_WARN << "No video texture available"; } } void QmitkVideoBackground::Modified() { // ensures registration of video backrounds in each renderwindow for(RenderWindowVectorInfoType::iterator it = m_renderWindowVectorInfo.begin(); it != m_renderWindowVectorInfo.end(); it++) { (*it).videoActor->SetInput((*it).videoImport->GetOutput()); (*it).videoRenderer->AddActor2D((*it).videoActor); (*it).videoRenderer->ResetCamera(); (*it).videoRenderer->InteractiveOff(); (*it).videoRenderer->GetActiveCamera()->ParallelProjectionOn(); (*it).videoRenderer->GetActiveCamera()->SetParallelScale(m_VideoSource->GetImageHeight()/2); mitk::VtkLayerController* layerController = mitk::VtkLayerController::GetInstance((*it).renWin); if( layerController && !layerController->IsRendererInserted((*it).videoRenderer) ) layerController->InsertBackgroundRenderer((*it).videoRenderer,true); } } void QmitkVideoBackground::SetVideoSource( mitk::VideoSource* videoSource ) { if( m_VideoSource == videoSource ) return; if( m_VideoSource ) m_VideoSource->RemoveObserver( m_VideoSourceObserverTag ); m_VideoSource = videoSource; if( m_VideoSource ) { itk::MemberCommand::Pointer _ModifiedCommand = itk::MemberCommand::New(); _ModifiedCommand->SetCallbackFunction(this, &QmitkVideoBackground::OnVideoSourceDelete); m_VideoSourceObserverTag = m_VideoSource->AddObserver(itk::DeleteEvent(), _ModifiedCommand); } } void QmitkVideoBackground::SetTimerDelay( int ms ) { m_QTimer->setInterval( ms ); //ResetVideoBackground(); } mitk::VideoSource* QmitkVideoBackground::GetVideoSource() { return m_VideoSource; } int QmitkVideoBackground::GetTimerDelay() { return m_QTimer->interval(); } void QmitkVideoBackground::OnVideoSourceDelete( const itk::Object* caller, const itk::EventObject &event ) { this->Disable(); // will only disable if enabled m_VideoSource = 0; } void QmitkVideoBackground::OnRenderWindowDelete( vtkObject * object, unsigned long eid, void* clientdata, void * /*calldata*/ ) { QmitkVideoBackground* instance = static_cast( clientdata ); instance->RemoveRenderWindow( static_cast(object), false ); -} \ No newline at end of file +} diff --git a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkCorrelationCoefficientHistogramMetricView.cpp b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkCorrelationCoefficientHistogramMetricView.cpp index 9144257265..cc71e16409 100644 --- a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkCorrelationCoefficientHistogramMetricView.cpp +++ b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkCorrelationCoefficientHistogramMetricView.cpp @@ -1,94 +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 "QmitkCorrelationCoefficientHistogramMetricView.h" #include #include "mitkImageAccessByItk.h" #include "QValidator" QmitkCorrelationCoefficientHistogramMetricView::QmitkCorrelationCoefficientHistogramMetricView(QWidget* parent, Qt::WindowFlags f ) : QmitkRigidRegistrationMetricsGUIBase (parent, f) { } QmitkCorrelationCoefficientHistogramMetricView::~QmitkCorrelationCoefficientHistogramMetricView() { } mitk::MetricParameters::MetricType QmitkCorrelationCoefficientHistogramMetricView::GetMetricType() { return mitk::MetricParameters::CORRELATIONCOEFFICIENTHISTOGRAMIMAGETOIMAGEMETRIC; } itk::Object::Pointer QmitkCorrelationCoefficientHistogramMetricView::GetMetric() { if (m_MovingImage.IsNotNull()) { AccessByItk(m_MovingImage, GetMetric2); return m_MetricObject; } return NULL; } template < class TPixelType, unsigned int VImageDimension > itk::Object::Pointer QmitkCorrelationCoefficientHistogramMetricView::GetMetric2(itk::Image* /*itkImage1*/) { typedef typename itk::Image< TPixelType, VImageDimension > FixedImageType; typedef typename itk::Image< TPixelType, VImageDimension > MovingImageType; typename itk::CorrelationCoefficientHistogramImageToImageMetric::Pointer MetricPointer = itk::CorrelationCoefficientHistogramImageToImageMetric::New(); unsigned int nBins = m_Controls.m_NumberOfHistogramBinsCorrelationCoefficientHistogram->text().toInt(); typename itk::CorrelationCoefficientHistogramImageToImageMetric::HistogramType::SizeType histogramSize; histogramSize[0] = nBins; histogramSize[1] = nBins; MetricPointer->SetHistogramSize(histogramSize); MetricPointer->SetComputeGradient(m_Controls.m_ComputeGradient->isChecked()); m_MetricObject = MetricPointer.GetPointer(); return MetricPointer.GetPointer(); } itk::Array QmitkCorrelationCoefficientHistogramMetricView::GetMetricParameters() { itk::Array metricValues; metricValues.SetSize(2); metricValues.fill(0); metricValues[0] = m_Controls.m_ComputeGradient->isChecked(); metricValues[1] = m_Controls.m_NumberOfHistogramBinsCorrelationCoefficientHistogram->text().toInt(); return metricValues; } void QmitkCorrelationCoefficientHistogramMetricView::SetMetricParameters(itk::Array metricValues) { m_Controls.m_ComputeGradient->setChecked(metricValues[0]); m_Controls.m_NumberOfHistogramBinsCorrelationCoefficientHistogram->setText(QString::number(metricValues[1])); } QString QmitkCorrelationCoefficientHistogramMetricView::GetName() { return "CorrelationCoefficientHistogram"; } void QmitkCorrelationCoefficientHistogramMetricView::SetupUI(QWidget* parent) { m_Controls.setupUi(parent); QValidator* validatorLineEditInput = new QIntValidator(0, 20000000, this); m_Controls.m_NumberOfHistogramBinsCorrelationCoefficientHistogram->setValidator(validatorLineEditInput); } bool QmitkCorrelationCoefficientHistogramMetricView::Maximize() { return true; -} \ No newline at end of file +} diff --git a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkGradientDifferenceMetricView.cpp b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkGradientDifferenceMetricView.cpp index 15dfd72b84..d0a091a46e 100644 --- a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkGradientDifferenceMetricView.cpp +++ b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkGradientDifferenceMetricView.cpp @@ -1,84 +1,84 @@ /*=================================================================== 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 "QmitkGradientDifferenceMetricView.h" #include #include "mitkImageAccessByItk.h" #include "QValidator" QmitkGradientDifferenceMetricView::QmitkGradientDifferenceMetricView(QWidget* parent, Qt::WindowFlags f ) : QmitkRigidRegistrationMetricsGUIBase (parent, f) { } QmitkGradientDifferenceMetricView::~QmitkGradientDifferenceMetricView() { } mitk::MetricParameters::MetricType QmitkGradientDifferenceMetricView::GetMetricType() { return mitk::MetricParameters::GRADIENTDIFFERENCEIMAGETOIMAGEMETRIC; } itk::Object::Pointer QmitkGradientDifferenceMetricView::GetMetric() { if (m_MovingImage.IsNotNull()) { AccessByItk(m_MovingImage, GetMetric2); return m_MetricObject; } return NULL; } template < class TPixelType, unsigned int VImageDimension > itk::Object::Pointer QmitkGradientDifferenceMetricView::GetMetric2(itk::Image* /*itkImage1*/) { typedef typename itk::Image< TPixelType, VImageDimension > FixedImageType; typedef typename itk::Image< TPixelType, VImageDimension > MovingImageType; typename itk::GradientDifferenceImageToImageMetric::Pointer MetricPointer = itk::GradientDifferenceImageToImageMetric::New(); MetricPointer->SetComputeGradient(m_Controls.m_ComputeGradient->isChecked()); m_MetricObject = MetricPointer.GetPointer(); return MetricPointer.GetPointer(); } itk::Array QmitkGradientDifferenceMetricView::GetMetricParameters() { itk::Array metricValues; metricValues.SetSize(1); metricValues.fill(0); metricValues[0] = m_Controls.m_ComputeGradient->isChecked(); return metricValues; } void QmitkGradientDifferenceMetricView::SetMetricParameters(itk::Array metricValues) { m_Controls.m_ComputeGradient->setChecked(metricValues[0]); } QString QmitkGradientDifferenceMetricView::GetName() { return "GradientDifference"; } void QmitkGradientDifferenceMetricView::SetupUI(QWidget* parent) { m_Controls.setupUi(parent); } bool QmitkGradientDifferenceMetricView::Maximize() { return false; -} \ No newline at end of file +} diff --git a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMatchCardinalityMetricView.cpp b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMatchCardinalityMetricView.cpp index d79558ec93..ee2729bac3 100644 --- a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMatchCardinalityMetricView.cpp +++ b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMatchCardinalityMetricView.cpp @@ -1,83 +1,83 @@ /*=================================================================== 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 "QmitkMatchCardinalityMetricView.h" #include #include "mitkImageAccessByItk.h" QmitkMatchCardinalityMetricView::QmitkMatchCardinalityMetricView(QWidget* parent, Qt::WindowFlags f ) : QmitkRigidRegistrationMetricsGUIBase (parent, f) { } QmitkMatchCardinalityMetricView::~QmitkMatchCardinalityMetricView() { } mitk::MetricParameters::MetricType QmitkMatchCardinalityMetricView::GetMetricType() { return mitk::MetricParameters::MATCHCARDINALITYIMAGETOIMAGEMETRIC; } itk::Object::Pointer QmitkMatchCardinalityMetricView::GetMetric() { if (m_MovingImage.IsNotNull()) { AccessByItk(m_MovingImage, GetMetric2); return m_MetricObject; } return NULL; } template < class TPixelType, unsigned int VImageDimension > itk::Object::Pointer QmitkMatchCardinalityMetricView::GetMetric2(itk::Image* /*itkImage1*/) { typedef typename itk::Image< TPixelType, VImageDimension > FixedImageType; typedef typename itk::Image< TPixelType, VImageDimension > MovingImageType; typename itk::MatchCardinalityImageToImageMetric::Pointer MetricPointer = itk::MatchCardinalityImageToImageMetric::New(); MetricPointer->SetComputeGradient(m_Controls.m_ComputeGradient->isChecked()); m_MetricObject = MetricPointer.GetPointer(); return MetricPointer.GetPointer(); } itk::Array QmitkMatchCardinalityMetricView::GetMetricParameters() { itk::Array metricValues; metricValues.SetSize(1); metricValues.fill(0); metricValues[0] = m_Controls.m_ComputeGradient->isChecked(); return metricValues; } void QmitkMatchCardinalityMetricView::SetMetricParameters(itk::Array metricValues) { m_Controls.m_ComputeGradient->setChecked(metricValues[0]); } QString QmitkMatchCardinalityMetricView::GetName() { return "MatchCardinality"; } void QmitkMatchCardinalityMetricView::SetupUI(QWidget* parent) { m_Controls.setupUi(parent); } bool QmitkMatchCardinalityMetricView::Maximize() { return false; -} \ No newline at end of file +} diff --git a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMattesMutualInformationMetricView.cpp b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMattesMutualInformationMetricView.cpp index c0f20baba9..ca0c54bda0 100644 --- a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMattesMutualInformationMetricView.cpp +++ b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMattesMutualInformationMetricView.cpp @@ -1,104 +1,104 @@ /*=================================================================== 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 "QmitkMattesMutualInformationMetricView.h" #include #include "mitkImageAccessByItk.h" QmitkMattesMutualInformationMetricView::QmitkMattesMutualInformationMetricView(QWidget* parent, Qt::WindowFlags f ) : QmitkRigidRegistrationMetricsGUIBase (parent, f) { } QmitkMattesMutualInformationMetricView::~QmitkMattesMutualInformationMetricView() { } mitk::MetricParameters::MetricType QmitkMattesMutualInformationMetricView::GetMetricType() { return mitk::MetricParameters::MATTESMUTUALINFORMATIONIMAGETOIMAGEMETRIC; } itk::Object::Pointer QmitkMattesMutualInformationMetricView::GetMetric() { if (m_MovingImage.IsNotNull()) { AccessByItk(m_MovingImage, GetMetric2); return m_MetricObject; } return NULL; } template < class TPixelType, unsigned int VImageDimension > itk::Object::Pointer QmitkMattesMutualInformationMetricView::GetMetric2(itk::Image* /*itkImage1*/) { typedef typename itk::Image< TPixelType, VImageDimension > FixedImageType; typedef typename itk::Image< TPixelType, VImageDimension > MovingImageType; typename itk::MattesMutualInformationImageToImageMetric::Pointer MetricPointer = itk::MattesMutualInformationImageToImageMetric::New(); bool useSampling = m_Controls.m_UseSamplingMattesMutualInformation->isChecked(); if( useSampling ) { // set the number of samples to use MetricPointer->SetNumberOfSpatialSamples( m_Controls.m_NumberOfSpatialSamplesMattesMutualInformation->text().toInt() ); } else { MetricPointer->UseAllPixelsOn(); } MetricPointer->SetNumberOfHistogramBins(m_Controls.m_NumberOfHistogramBinsMattesMutualInformation->text().toInt()); MetricPointer->ReinitializeSeed( 76926294 ); MetricPointer->SetComputeGradient(m_Controls.m_ComputeGradient->isChecked()); m_MetricObject = MetricPointer.GetPointer(); return MetricPointer.GetPointer(); } itk::Array QmitkMattesMutualInformationMetricView::GetMetricParameters() { itk::Array metricValues; metricValues.SetSize(4); metricValues.fill(0); metricValues[0] = m_Controls.m_ComputeGradient->isChecked(); metricValues[1] = m_Controls.m_UseSamplingMattesMutualInformation->isChecked(); metricValues[2] = m_Controls.m_NumberOfSpatialSamplesMattesMutualInformation->text().toInt(); metricValues[3] = m_Controls.m_NumberOfHistogramBinsMattesMutualInformation->text().toInt(); return metricValues; } void QmitkMattesMutualInformationMetricView::SetMetricParameters(itk::Array metricValues) { m_Controls.m_ComputeGradient->setChecked(metricValues[0]); m_Controls.m_UseSamplingMattesMutualInformation->setChecked(metricValues[1]); m_Controls.m_NumberOfSpatialSamplesMattesMutualInformation->setText(QString::number(metricValues[2])); m_Controls.m_NumberOfHistogramBinsMattesMutualInformation->setText(QString::number(metricValues[3])); } QString QmitkMattesMutualInformationMetricView::GetName() { return "MattesMutualInformation"; } void QmitkMattesMutualInformationMetricView::SetupUI(QWidget* parent) { m_Controls.setupUi(parent); QValidator* validatorLineEditInput = new QIntValidator(0, 20000000, this); m_Controls.m_NumberOfSpatialSamplesMattesMutualInformation->setValidator(validatorLineEditInput); m_Controls.m_NumberOfHistogramBinsMattesMutualInformation->setValidator(validatorLineEditInput); } bool QmitkMattesMutualInformationMetricView::Maximize() { return true; -} \ No newline at end of file +} diff --git a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMeanSquaresHistogramMetricView.cpp b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMeanSquaresHistogramMetricView.cpp index f2f8462aae..a70fcda28e 100644 --- a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMeanSquaresHistogramMetricView.cpp +++ b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMeanSquaresHistogramMetricView.cpp @@ -1,93 +1,93 @@ /*=================================================================== 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 "QmitkMeanSquaresHistogramMetricView.h" #include #include "mitkImageAccessByItk.h" #include "QValidator" QmitkMeanSquaresHistogramMetricView::QmitkMeanSquaresHistogramMetricView(QWidget* parent, Qt::WindowFlags f ) : QmitkRigidRegistrationMetricsGUIBase (parent, f) { } QmitkMeanSquaresHistogramMetricView::~QmitkMeanSquaresHistogramMetricView() { } mitk::MetricParameters::MetricType QmitkMeanSquaresHistogramMetricView::GetMetricType() { return mitk::MetricParameters::MEANSQUARESHISTOGRAMIMAGETOIMAGEMETRIC; } itk::Object::Pointer QmitkMeanSquaresHistogramMetricView::GetMetric() { if (m_MovingImage.IsNotNull()) { AccessByItk(m_MovingImage, GetMetric2); return m_MetricObject; } return NULL; } template < class TPixelType, unsigned int VImageDimension > itk::Object::Pointer QmitkMeanSquaresHistogramMetricView::GetMetric2(itk::Image* /*itkImage1*/) { typedef typename itk::Image< TPixelType, VImageDimension > FixedImageType; typedef typename itk::Image< TPixelType, VImageDimension > MovingImageType; typename itk::MeanSquaresHistogramImageToImageMetric::Pointer MetricPointer = itk::MeanSquaresHistogramImageToImageMetric::New(); unsigned int nBins = m_Controls.m_NumberOfHistogramBinsMeanSquaresHistogram->text().toInt(); typename itk::MeanSquaresHistogramImageToImageMetric::HistogramType::SizeType histogramSize; histogramSize[0] = nBins; histogramSize[1] = nBins; MetricPointer->SetHistogramSize(histogramSize); MetricPointer->SetComputeGradient(m_Controls.m_ComputeGradient->isChecked()); m_MetricObject = MetricPointer.GetPointer(); return MetricPointer.GetPointer(); } itk::Array QmitkMeanSquaresHistogramMetricView::GetMetricParameters() { itk::Array metricValues; metricValues.SetSize(2); metricValues.fill(0); metricValues[0] = m_Controls.m_ComputeGradient->isChecked(); metricValues[1] = m_Controls.m_NumberOfHistogramBinsMeanSquaresHistogram->text().toInt(); return metricValues; } void QmitkMeanSquaresHistogramMetricView::SetMetricParameters(itk::Array metricValues) { m_Controls.m_ComputeGradient->setChecked(metricValues[0]); m_Controls.m_NumberOfHistogramBinsMeanSquaresHistogram->setText(QString::number(metricValues[1])); } QString QmitkMeanSquaresHistogramMetricView::GetName() { return "MeanSquaresHistogram"; } void QmitkMeanSquaresHistogramMetricView::SetupUI(QWidget* parent) { m_Controls.setupUi(parent); QValidator* validatorLineEditInput = new QIntValidator(0, 20000000, this); m_Controls.m_NumberOfHistogramBinsMeanSquaresHistogram->setValidator(validatorLineEditInput); } bool QmitkMeanSquaresHistogramMetricView::Maximize() { return false; -} \ No newline at end of file +} diff --git a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMeanSquaresMetricView.cpp b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMeanSquaresMetricView.cpp index 207f0f2c66..76553a8f54 100644 --- a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMeanSquaresMetricView.cpp +++ b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMeanSquaresMetricView.cpp @@ -1,83 +1,83 @@ /*=================================================================== 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 "QmitkMeanSquaresMetricView.h" #include #include "mitkImageAccessByItk.h" QmitkMeanSquaresMetricView::QmitkMeanSquaresMetricView(QWidget* parent, Qt::WindowFlags f ) : QmitkRigidRegistrationMetricsGUIBase (parent, f) { } QmitkMeanSquaresMetricView::~QmitkMeanSquaresMetricView() { } mitk::MetricParameters::MetricType QmitkMeanSquaresMetricView::GetMetricType() { return mitk::MetricParameters::MEANSQUARESIMAGETOIMAGEMETRIC; } itk::Object::Pointer QmitkMeanSquaresMetricView::GetMetric() { if (m_MovingImage.IsNotNull()) { AccessByItk(m_MovingImage, GetMetric2); return m_MetricObject; } return NULL; } template < class TPixelType, unsigned int VImageDimension > itk::Object::Pointer QmitkMeanSquaresMetricView::GetMetric2(itk::Image* /*itkImage1*/) { typedef typename itk::Image< TPixelType, VImageDimension > FixedImageType; typedef typename itk::Image< TPixelType, VImageDimension > MovingImageType; typename itk::MeanSquaresImageToImageMetric::Pointer MetricPointer = itk::MeanSquaresImageToImageMetric::New(); MetricPointer->SetComputeGradient(m_Controls.m_ComputeGradient->isChecked()); m_MetricObject = MetricPointer.GetPointer(); return MetricPointer.GetPointer(); } itk::Array QmitkMeanSquaresMetricView::GetMetricParameters() { itk::Array metricValues; metricValues.SetSize(1); metricValues.fill(0); metricValues[0] = m_Controls.m_ComputeGradient->isChecked(); return metricValues; } void QmitkMeanSquaresMetricView::SetMetricParameters(itk::Array metricValues) { m_Controls.m_ComputeGradient->setChecked(metricValues[0]); } QString QmitkMeanSquaresMetricView::GetName() { return "MeanSquares"; } void QmitkMeanSquaresMetricView::SetupUI(QWidget* parent) { m_Controls.setupUi(parent); } bool QmitkMeanSquaresMetricView::Maximize() { return false; -} \ No newline at end of file +} diff --git a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMutualInformationHistogramMetricView.cpp b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMutualInformationHistogramMetricView.cpp index 31777d14b1..92564faaf2 100644 --- a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMutualInformationHistogramMetricView.cpp +++ b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMutualInformationHistogramMetricView.cpp @@ -1,93 +1,93 @@ /*=================================================================== 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 "QmitkMutualInformationHistogramMetricView.h" #include #include "mitkImageAccessByItk.h" #include "QValidator" QmitkMutualInformationHistogramMetricView::QmitkMutualInformationHistogramMetricView(QWidget* parent, Qt::WindowFlags f ) : QmitkRigidRegistrationMetricsGUIBase (parent, f) { } QmitkMutualInformationHistogramMetricView::~QmitkMutualInformationHistogramMetricView() { } mitk::MetricParameters::MetricType QmitkMutualInformationHistogramMetricView::GetMetricType() { return mitk::MetricParameters::MUTUALINFORMATIONHISTOGRAMIMAGETOIMAGEMETRIC; } itk::Object::Pointer QmitkMutualInformationHistogramMetricView::GetMetric() { if (m_MovingImage.IsNotNull()) { AccessByItk(m_MovingImage, GetMetric2); return m_MetricObject; } return NULL; } template < class TPixelType, unsigned int VImageDimension > itk::Object::Pointer QmitkMutualInformationHistogramMetricView::GetMetric2(itk::Image* /*itkImage1*/) { typedef typename itk::Image< TPixelType, VImageDimension > FixedImageType; typedef typename itk::Image< TPixelType, VImageDimension > MovingImageType; typename itk::MutualInformationHistogramImageToImageMetric::Pointer MetricPointer = itk::MutualInformationHistogramImageToImageMetric::New(); unsigned int nBins = m_Controls.m_NumberOfHistogramBinsMutualInformationHistogram->text().toInt(); typename itk::MutualInformationHistogramImageToImageMetric::HistogramType::SizeType histogramSize; histogramSize[0] = nBins; histogramSize[1] = nBins; MetricPointer->SetHistogramSize(histogramSize); MetricPointer->SetComputeGradient(m_Controls.m_ComputeGradient->isChecked()); m_MetricObject = MetricPointer.GetPointer(); return MetricPointer.GetPointer(); } itk::Array QmitkMutualInformationHistogramMetricView::GetMetricParameters() { itk::Array metricValues; metricValues.SetSize(2); metricValues.fill(0); metricValues[0] = m_Controls.m_ComputeGradient->isChecked(); metricValues[1] = m_Controls.m_NumberOfHistogramBinsMutualInformationHistogram->text().toInt(); return metricValues; } void QmitkMutualInformationHistogramMetricView::SetMetricParameters(itk::Array metricValues) { m_Controls.m_ComputeGradient->setChecked(metricValues[0]); m_Controls.m_NumberOfHistogramBinsMutualInformationHistogram->setText(QString::number(metricValues[1])); } QString QmitkMutualInformationHistogramMetricView::GetName() { return "MutualInformationHistogram"; } void QmitkMutualInformationHistogramMetricView::SetupUI(QWidget* parent) { m_Controls.setupUi(parent); QValidator* validatorLineEditInput = new QIntValidator(0, 20000000, this); m_Controls.m_NumberOfHistogramBinsMutualInformationHistogram->setValidator(validatorLineEditInput); } bool QmitkMutualInformationHistogramMetricView::Maximize() { return false; -} \ No newline at end of file +} diff --git a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMutualInformationMetricView.cpp b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMutualInformationMetricView.cpp index 1cbdc067ed..d163292d36 100644 --- a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMutualInformationMetricView.cpp +++ b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkMutualInformationMetricView.cpp @@ -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. ===================================================================*/ #include "QmitkMutualInformationMetricView.h" #include #include "mitkImageAccessByItk.h" QmitkMutualInformationMetricView::QmitkMutualInformationMetricView(QWidget* parent, Qt::WindowFlags f ) : QmitkRigidRegistrationMetricsGUIBase (parent, f) { } QmitkMutualInformationMetricView::~QmitkMutualInformationMetricView() { } mitk::MetricParameters::MetricType QmitkMutualInformationMetricView::GetMetricType() { return mitk::MetricParameters::MUTUALINFORMATIONIMAGETOIMAGEMETRIC; } itk::Object::Pointer QmitkMutualInformationMetricView::GetMetric() { if (m_MovingImage.IsNotNull()) { AccessByItk(m_MovingImage, GetMetric2); return m_MetricObject; } return NULL; } template < class TPixelType, unsigned int VImageDimension > itk::Object::Pointer QmitkMutualInformationMetricView::GetMetric2(itk::Image* /*itkImage1*/) { typedef typename itk::Image< TPixelType, VImageDimension > FixedImageType; typedef typename itk::Image< TPixelType, VImageDimension > MovingImageType; typename itk::MutualInformationImageToImageMetric::Pointer MetricPointer = itk::MutualInformationImageToImageMetric::New(); MetricPointer->SetNumberOfSpatialSamples(m_Controls.m_NumberOfSpatialSamplesMutualInformation->text().toInt()); MetricPointer->SetFixedImageStandardDeviation(m_Controls.m_FixedImageStandardDeviationMutualInformation->text().toFloat()); MetricPointer->SetMovingImageStandardDeviation(m_Controls.m_MovingImageStandardDeviationMutualInformation->text().toFloat()); MetricPointer->SetComputeGradient(m_Controls.m_ComputeGradient->isChecked()); m_MetricObject = MetricPointer.GetPointer(); return MetricPointer.GetPointer(); } itk::Array QmitkMutualInformationMetricView::GetMetricParameters() { itk::Array metricValues; metricValues.SetSize(4); metricValues.fill(0); metricValues[0] = m_Controls.m_ComputeGradient->isChecked(); metricValues[1] = m_Controls.m_NumberOfSpatialSamplesMutualInformation->text().toInt(); metricValues[2] = m_Controls.m_FixedImageStandardDeviationMutualInformation->text().toFloat(); metricValues[3] = m_Controls.m_MovingImageStandardDeviationMutualInformation->text().toFloat(); return metricValues; } void QmitkMutualInformationMetricView::SetMetricParameters(itk::Array metricValues) { m_Controls.m_ComputeGradient->setChecked(metricValues[0]); m_Controls.m_NumberOfSpatialSamplesMutualInformation->setText(QString::number(metricValues[1])); m_Controls.m_FixedImageStandardDeviationMutualInformation->setText(QString::number(metricValues[2])); m_Controls.m_MovingImageStandardDeviationMutualInformation->setText(QString::number(metricValues[3])); } QString QmitkMutualInformationMetricView::GetName() { return "MutualInformation"; } void QmitkMutualInformationMetricView::SetupUI(QWidget* parent) { m_Controls.setupUi(parent); QValidator* validatorLineEditInput = new QIntValidator(0, 20000000, this); m_Controls.m_NumberOfSpatialSamplesMutualInformation->setValidator(validatorLineEditInput); QValidator* validatorLineEditInputFloat = new QDoubleValidator(0, 20000000, 8, this); m_Controls.m_FixedImageStandardDeviationMutualInformation->setValidator(validatorLineEditInputFloat); m_Controls.m_MovingImageStandardDeviationMutualInformation->setValidator(validatorLineEditInputFloat); } bool QmitkMutualInformationMetricView::Maximize() { return true; -} \ No newline at end of file +} diff --git a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkNormalizedCorrelationMetricView.cpp b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkNormalizedCorrelationMetricView.cpp index e905c51f21..7d1a570969 100644 --- a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkNormalizedCorrelationMetricView.cpp +++ b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkNormalizedCorrelationMetricView.cpp @@ -1,84 +1,84 @@ /*=================================================================== 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 "QmitkNormalizedCorrelationMetricView.h" #include #include "mitkImageAccessByItk.h" #include "QValidator" QmitkNormalizedCorrelationMetricView::QmitkNormalizedCorrelationMetricView(QWidget* parent, Qt::WindowFlags f ) : QmitkRigidRegistrationMetricsGUIBase (parent, f) { } QmitkNormalizedCorrelationMetricView::~QmitkNormalizedCorrelationMetricView() { } mitk::MetricParameters::MetricType QmitkNormalizedCorrelationMetricView::GetMetricType() { return mitk::MetricParameters::NORMALIZEDCORRELATIONIMAGETOIMAGEMETRIC; } itk::Object::Pointer QmitkNormalizedCorrelationMetricView::GetMetric() { if (m_MovingImage.IsNotNull()) { AccessByItk(m_MovingImage, GetMetric2); return m_MetricObject; } return NULL; } template < class TPixelType, unsigned int VImageDimension > itk::Object::Pointer QmitkNormalizedCorrelationMetricView::GetMetric2(itk::Image* /*itkImage1*/) { typedef typename itk::Image< TPixelType, VImageDimension > FixedImageType; typedef typename itk::Image< TPixelType, VImageDimension > MovingImageType; typename itk::NormalizedCorrelationImageToImageMetric::Pointer MetricPointer = itk::NormalizedCorrelationImageToImageMetric::New(); MetricPointer->SetComputeGradient(m_Controls.m_ComputeGradient->isChecked()); m_MetricObject = MetricPointer.GetPointer(); return MetricPointer.GetPointer(); } itk::Array QmitkNormalizedCorrelationMetricView::GetMetricParameters() { itk::Array metricValues; metricValues.SetSize(1); metricValues.fill(0); metricValues[0] = m_Controls.m_ComputeGradient->isChecked(); return metricValues; } void QmitkNormalizedCorrelationMetricView::SetMetricParameters(itk::Array metricValues) { m_Controls.m_ComputeGradient->setChecked(metricValues[0]); } QString QmitkNormalizedCorrelationMetricView::GetName() { return "NormalizedCorrelation"; } void QmitkNormalizedCorrelationMetricView::SetupUI(QWidget* parent) { m_Controls.setupUi(parent); } bool QmitkNormalizedCorrelationMetricView::Maximize() { return true; -} \ No newline at end of file +} diff --git a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkNormalizedMutualInformationHistogramMetricView.cpp b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkNormalizedMutualInformationHistogramMetricView.cpp index 6450d06ab0..6dcceb3dda 100644 --- a/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkNormalizedMutualInformationHistogramMetricView.cpp +++ b/Modules/RigidRegistrationUI/RigidRegistrationMetrics/QmitkNormalizedMutualInformationHistogramMetricView.cpp @@ -1,93 +1,93 @@ /*=================================================================== 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 "QmitkNormalizedMutualInformationHistogramMetricView.h" #include #include "mitkImageAccessByItk.h" #include "QValidator" QmitkNormalizedMutualInformationHistogramMetricView::QmitkNormalizedMutualInformationHistogramMetricView(QWidget* parent, Qt::WindowFlags f ) : QmitkRigidRegistrationMetricsGUIBase (parent, f) { } QmitkNormalizedMutualInformationHistogramMetricView::~QmitkNormalizedMutualInformationHistogramMetricView() { } mitk::MetricParameters::MetricType QmitkNormalizedMutualInformationHistogramMetricView::GetMetricType() { return mitk::MetricParameters::NORMALIZEDMUTUALINFORMATIONHISTOGRAMIMAGETOIMAGEMETRIC; } itk::Object::Pointer QmitkNormalizedMutualInformationHistogramMetricView::GetMetric() { if (m_MovingImage.IsNotNull()) { AccessByItk(m_MovingImage, GetMetric2); return m_MetricObject; } return NULL; } template < class TPixelType, unsigned int VImageDimension > itk::Object::Pointer QmitkNormalizedMutualInformationHistogramMetricView::GetMetric2(itk::Image* /*itkImage1*/) { typedef typename itk::Image< TPixelType, VImageDimension > FixedImageType; typedef typename itk::Image< TPixelType, VImageDimension > MovingImageType; typename itk::NormalizedMutualInformationHistogramImageToImageMetric::Pointer MetricPointer = itk::NormalizedMutualInformationHistogramImageToImageMetric::New(); unsigned int nBins = m_Controls.m_NumberOfHistogramBinsNormalizedMutualInformationHistogram->text().toInt(); typename itk::NormalizedMutualInformationHistogramImageToImageMetric::HistogramType::SizeType histogramSize; histogramSize[0] = nBins; histogramSize[1] = nBins; MetricPointer->SetHistogramSize(histogramSize); MetricPointer->SetComputeGradient(m_Controls.m_ComputeGradient->isChecked()); m_MetricObject = MetricPointer.GetPointer(); return MetricPointer.GetPointer(); } itk::Array QmitkNormalizedMutualInformationHistogramMetricView::GetMetricParameters() { itk::Array metricValues; metricValues.SetSize(2); metricValues.fill(0); metricValues[0] = m_Controls.m_ComputeGradient->isChecked(); metricValues[1] = m_Controls.m_NumberOfHistogramBinsNormalizedMutualInformationHistogram->text().toInt(); return metricValues; } void QmitkNormalizedMutualInformationHistogramMetricView::SetMetricParameters(itk::Array metricValues) { m_Controls.m_ComputeGradient->setChecked(metricValues[0]); m_Controls.m_NumberOfHistogramBinsNormalizedMutualInformationHistogram->setText(QString::number(metricValues[1])); } QString QmitkNormalizedMutualInformationHistogramMetricView::GetName() { return "NormalizedMutualInformationHistogram"; } void QmitkNormalizedMutualInformationHistogramMetricView::SetupUI(QWidget* parent) { m_Controls.setupUi(parent); QValidator* validatorLineEditInput = new QIntValidator(0, 20000000, this); m_Controls.m_NumberOfHistogramBinsNormalizedMutualInformationHistogram->setValidator(validatorLineEditInput); } bool QmitkNormalizedMutualInformationHistogramMetricView::Maximize() { return true; -} \ No newline at end of file +} diff --git a/Modules/SceneSerializationBase/BasePropertySerializer/mitkTransferFunctionPropertySerializer.cpp b/Modules/SceneSerializationBase/BasePropertySerializer/mitkTransferFunctionPropertySerializer.cpp index 56d8e2df32..79b487907f 100644 --- a/Modules/SceneSerializationBase/BasePropertySerializer/mitkTransferFunctionPropertySerializer.cpp +++ b/Modules/SceneSerializationBase/BasePropertySerializer/mitkTransferFunctionPropertySerializer.cpp @@ -1,232 +1,232 @@ /*=================================================================== 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 "mitkTransferFunctionPropertySerializer.h" namespace mitk { mitk::TransferFunctionPropertySerializer::TransferFunctionPropertySerializer() { } mitk::TransferFunctionPropertySerializer::~TransferFunctionPropertySerializer() { } TiXmlElement* mitk::TransferFunctionPropertySerializer::Serialize() { if (const TransferFunctionProperty* prop = dynamic_cast(mitk::BasePropertySerializer::m_Property.GetPointer())) { TransferFunction* transferfunction = prop->GetValue(); if (!transferfunction) return NULL; TiXmlElement* element = new TiXmlElement("TransferFunction"); // serialize scalar opacity function TiXmlElement* scalarOpacityPointlist = new TiXmlElement( "ScalarOpacity" ); TransferFunction::ControlPoints scalarOpacityPoints = transferfunction->GetScalarOpacityPoints(); for ( TransferFunction::ControlPoints::iterator iter = scalarOpacityPoints.begin(); iter != scalarOpacityPoints.end(); ++iter ) { TiXmlElement* pointel = new TiXmlElement("point"); pointel->SetDoubleAttribute("x", iter->first); pointel->SetDoubleAttribute("y", iter->second); scalarOpacityPointlist->LinkEndChild( pointel ); } element->LinkEndChild( scalarOpacityPointlist ); // serialize gradient opacity function TiXmlElement* gradientOpacityPointlist = new TiXmlElement( "GradientOpacity" ); TransferFunction::ControlPoints gradientOpacityPoints = transferfunction->GetGradientOpacityPoints(); for ( TransferFunction::ControlPoints::iterator iter = gradientOpacityPoints.begin(); iter != gradientOpacityPoints.end(); ++iter ) { TiXmlElement* pointel = new TiXmlElement("point"); pointel->SetDoubleAttribute("x", iter->first); pointel->SetDoubleAttribute("y", iter->second); gradientOpacityPointlist->LinkEndChild( pointel ); } element->LinkEndChild( gradientOpacityPointlist ); // serialize color function vtkColorTransferFunction* ctf = transferfunction->GetColorTransferFunction(); if (ctf == NULL) return NULL; TiXmlElement* pointlist = new TiXmlElement("Color"); for (int i = 0; i < ctf->GetSize(); i++ ) { double myVal[6]; ctf->GetNodeValue(i, myVal); TiXmlElement* pointel = new TiXmlElement("point"); pointel->SetDoubleAttribute("x", myVal[0]); pointel->SetDoubleAttribute("r", myVal[1]); pointel->SetDoubleAttribute("g", myVal[2]); pointel->SetDoubleAttribute("b", myVal[3]); pointel->SetDoubleAttribute("midpoint", myVal[4]); pointel->SetDoubleAttribute("sharpness", myVal[5]); pointlist->LinkEndChild( pointel ); } element->LinkEndChild( pointlist ); return element; } else return NULL; } bool mitk::TransferFunctionPropertySerializer::SerializeTransferFunction( const char * filename, TransferFunction::Pointer tf ) { TransferFunctionPropertySerializer::Pointer tfps=TransferFunctionPropertySerializer::New(); tfps->SetProperty( TransferFunctionProperty::New( tf ) ); TiXmlElement* s=tfps->Serialize(); if(!s) { MITK_ERROR << "cant serialize transfer function"; return false; } TiXmlDocument document; TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "UTF-8", "" ); // TODO what to write here? encoding? standalone would mean that we provide a DTD somewhere... document.LinkEndChild( decl ); TiXmlElement* version = new TiXmlElement("Version"); version->SetAttribute("TransferfunctionVersion", 1 ); document.LinkEndChild(version); document.LinkEndChild(s); if ( !document.SaveFile( filename ) ) { MITK_ERROR << "Could not write scene to " << filename << "\nTinyXML reports '" << document.ErrorDesc() << "'"; return false; } return true; } BaseProperty::Pointer mitk::TransferFunctionPropertySerializer::Deserialize(TiXmlElement* element) { if (!element) return NULL; TransferFunction::Pointer tf = TransferFunction::New(); // deserialize scalar opacity function TiXmlElement* scalarOpacityPointlist = element->FirstChildElement("ScalarOpacity"); if (scalarOpacityPointlist == NULL) return NULL; tf->ClearScalarOpacityPoints(); for( TiXmlElement* pointElement = scalarOpacityPointlist->FirstChildElement("point"); pointElement != NULL; pointElement = pointElement->NextSiblingElement("point")) { double x; double y; if (pointElement->QueryDoubleAttribute("x", &x) == TIXML_WRONG_TYPE) return NULL; // TODO: can we do a better error handling? if (pointElement->QueryDoubleAttribute("y", &y) == TIXML_WRONG_TYPE) return NULL; // TODO: can we do a better error handling? tf->AddScalarOpacityPoint(x, y); } TiXmlElement* gradientOpacityPointlist = element->FirstChildElement("GradientOpacity"); if (gradientOpacityPointlist == NULL) return NULL; tf->ClearGradientOpacityPoints(); for( TiXmlElement* pointElement = gradientOpacityPointlist->FirstChildElement("point"); pointElement != NULL; pointElement = pointElement->NextSiblingElement("point")) { double x; double y; if (pointElement->QueryDoubleAttribute("x", &x) == TIXML_WRONG_TYPE) return NULL; // TODO: can we do a better error handling? if (pointElement->QueryDoubleAttribute("y", &y) == TIXML_WRONG_TYPE) return NULL; // TODO: can we do a better error handling? tf->AddGradientOpacityPoint(x, y); } TiXmlElement* rgbPointlist = element->FirstChildElement("Color"); if (rgbPointlist == NULL) return NULL; vtkColorTransferFunction* ctf = tf->GetColorTransferFunction(); if (ctf == NULL) return NULL; ctf->RemoveAllPoints(); for( TiXmlElement* pointElement = rgbPointlist->FirstChildElement("point"); pointElement != NULL; pointElement = pointElement->NextSiblingElement("point")) { double x; double r,g,b, midpoint, sharpness; if (pointElement->QueryDoubleAttribute("x", &x) == TIXML_WRONG_TYPE) return NULL; // TODO: can we do a better error handling? if (pointElement->QueryDoubleAttribute("r", &r) == TIXML_WRONG_TYPE) return NULL; // TODO: can we do a better error handling? if (pointElement->QueryDoubleAttribute("g", &g) == TIXML_WRONG_TYPE) return NULL; // TODO: can we do a better error handling? if (pointElement->QueryDoubleAttribute("b", &b) == TIXML_WRONG_TYPE) return NULL; // TODO: can we do a better error handling? if (pointElement->QueryDoubleAttribute("midpoint", &midpoint) == TIXML_WRONG_TYPE) return NULL; // TODO: can we do a better error handling? if (pointElement->QueryDoubleAttribute("sharpness", &sharpness) == TIXML_WRONG_TYPE) return NULL; // TODO: can we do a better error handling? ctf->AddRGBPoint(x, r, g, b, midpoint, sharpness); } return TransferFunctionProperty::New(tf).GetPointer(); } mitk::TransferFunction::Pointer mitk::TransferFunctionPropertySerializer::DeserializeTransferFunction( const char *filePath ) { TiXmlDocument document( filePath ); if (!document.LoadFile()) { MITK_ERROR << "Could not open/read/parse " << filePath << "\nTinyXML reports: " << document.ErrorDesc() << std::endl; return NULL; } // find version node --> note version in some variable int fileVersion = 1; TiXmlElement* versionObject = document.FirstChildElement("Version"); if (versionObject) { if ( versionObject->QueryIntAttribute( "TransferfunctionVersion", &fileVersion ) != TIXML_SUCCESS ) { MITK_WARN << "Transferfunction file " << filePath << " does not contain version information! Trying version 1 format."; } } TiXmlElement* input = document.FirstChildElement("TransferFunction"); TransferFunctionPropertySerializer::Pointer tfpd = TransferFunctionPropertySerializer::New(); BaseProperty::Pointer bp = tfpd->Deserialize(input); TransferFunctionProperty::Pointer tfp = dynamic_cast(bp.GetPointer()); if(tfp.IsNotNull()) { TransferFunction::Pointer tf = tfp->GetValue(); return tf; } MITK_WARN << "Can't deserialize transferfunction"; return NULL; } } // namespace // important to put this into the GLOBAL namespace (because it starts with 'namespace mitk') -MITK_REGISTER_SERIALIZER(TransferFunctionPropertySerializer); \ No newline at end of file +MITK_REGISTER_SERIALIZER(TransferFunctionPropertySerializer); diff --git a/Modules/ToFHardware/mitkToFCameraMESASR4000Controller.cpp b/Modules/ToFHardware/mitkToFCameraMESASR4000Controller.cpp index bc57da9d35..5c11874c1a 100644 --- a/Modules/ToFHardware/mitkToFCameraMESASR4000Controller.cpp +++ b/Modules/ToFHardware/mitkToFCameraMESASR4000Controller.cpp @@ -1,227 +1,227 @@ /*=================================================================== 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 "mitkToFCameraMESASR4000Controller.h" #include "mitkToFConfig.h" #include extern CMesaDevice* m_MESAHandle; namespace mitk { ToFCameraMESASR4000Controller::ToFCameraMESASR4000Controller() { this->m_Lambda = new float[MF_LAST]; this->m_Frequency = new float[MF_LAST]; this->m_Lambda[0] = 3.75f; this->m_Lambda[1] = 5.0f; this->m_Lambda[2] = 7.142857f; this->m_Lambda[3] = 7.5f; this->m_Lambda[4] = 7.894737f; this->m_Lambda[5] = 2.5f; this->m_Lambda[6] = 10.0f; this->m_Lambda[7] = 15.0f; this->m_Lambda[8] = 5.172414f; this->m_Lambda[9] = 4.838710f; this->m_Lambda[10] = 10.344828f; this->m_Lambda[11] = 9.677419f; this->m_Frequency[0] = 40.0f; this->m_Frequency[1] = 30.0f; this->m_Frequency[2] = 21.0f; this->m_Frequency[3] = 20.0f; this->m_Frequency[4] = 19.0f; this->m_Frequency[5] = 60.0f; this->m_Frequency[6] = 15.0f; this->m_Frequency[7] = 10.0f; this->m_Frequency[8] = 29.0f; this->m_Frequency[9] = 31.0f; this->m_Frequency[10] = 14.5f; this->m_Frequency[11] = 15.5f; } ToFCameraMESASR4000Controller::~ToFCameraMESASR4000Controller() { } bool ToFCameraMESASR4000Controller::OpenCameraConnection() { if(!m_ConnectionCheck) { - /* + /* m_PMDRes = pmdOpen (&m_PMDHandle , m_SourcePlugin , m_SourceParam , m_ProcPlugin , m_ProcParam ); m_ConnectionCheck = ErrorText(m_PMDRes); if (!m_ConnectionCheck) { return m_ConnectionCheck; } // get image properties from camera this->UpdateCamera(); m_PMDRes = pmdGetSourceDataDescription(m_PMDHandle, &m_DataDescription); ErrorText(m_PMDRes); m_CaptureWidth = m_DataDescription.img.numColumns; m_CaptureHeight = m_DataDescription.img.numRows; m_PixelNumber = m_CaptureWidth*m_CaptureHeight; m_NumberOfBytes = m_PixelNumber * sizeof(float); m_SourceDataSize = m_DataDescription.size; m_SourceDataStructSize = m_DataDescription.size + sizeof(PMDDataDescription); char serial[16]; m_PMDRes = pmdSourceCommand (m_PMDHandle, serial, 16, "GetSerialNumber"); ErrorText(m_PMDRes); MITK_INFO << "Serial-No: " << serial <m_SourceDataSize <GetIntegrationTime(); MITK_INFO << "Modulation Frequence: " << this->GetModulationFrequency(); return m_ConnectionCheck; */ //m_MESARes = SR_OpenDlg(&m_MESAHandle, 3, 0); this->m_MESARes = SR_OpenUSB(&m_MESAHandle, 0); this->m_ConnectionCheck = ErrorText(this->m_MESARes); if (m_MESARes <= 0) { this->m_ConnectionCheck = false; return this->m_ConnectionCheck; } this->m_MESARes = SR_GetRows(m_MESAHandle); this->m_CaptureHeight = this->m_MESARes; this->m_MESARes = SR_GetCols(m_MESAHandle); this->m_CaptureWidth = this->m_MESARes; this->m_PixelNumber = this->m_CaptureWidth*this->m_CaptureHeight; this->m_NumberOfBytes = this->m_PixelNumber * sizeof(float); ImgEntry* imgEntryArray; this->m_NumImg = SR_GetImageList(m_MESAHandle, &imgEntryArray); //float lambda[MF_LAST]={3.75f, 5.f, 7.142857f, 7.5f, 7.894737f, 2.5f, 10.f, 15.f, 5.172414f, 4.838710f, 10.344828f, 9.677419f};//MF_40MHz,MF_30MHz,MF_21MHz,MF_20MHz,MF_19MHz,... //float frequency[MF_LAST]={40.00f, 30.00f, 21.00f, 20.00f, 19.00f, 60.00f, 15.00f, 10.00f, 29.00f, 31.00f, 14.50f, 15.50f}; ModulationFrq frq = SR_GetModulationFrequency(m_MESAHandle); this->m_MaxRangeFactor = (this->m_Lambda[frq] * 1000.00) / (float)0xffff; unsigned char integrationTime8bit = SR_GetIntegrationTime(m_MESAHandle); float integrationTime = (0.3 + ((int)integrationTime8bit) * 0.1) * 1000; // for MESA4000 char deviceText[1024]; this->m_MESARes = SR_GetDeviceString(m_MESAHandle, deviceText, _countof(deviceText));//returns the device ID used in other calls MITK_INFO << "Device ID: " << deviceText <m_NumImg <m_CaptureWidth << " x " << this->m_CaptureHeight <m_Frequency[frq] << " MHz" <m_Lambda[frq] << " m" <m_MESARes = SR_SetIntegrationTime(m_MESAHandle, intTime); MITK_INFO << "New integration time: " << integrationTime << " microsec" <m_MESARes = SR_SetModulationFrequency (m_MESAHandle, frq); if (this->m_MESARes == 0) { this->m_MaxRangeFactor = (this->m_Lambda[frq] * 1000.00) / (float)0xffff; MITK_INFO << "New modulation frequency: " << this->m_Frequency[frq] << " MHz" <m_MESARes; } } int ToFCameraMESASR4000Controller::GetModulationFrequency() { ModulationFrq frq = SR_GetModulationFrequency(m_MESAHandle); this->m_MaxRangeFactor = (this->m_Lambda[frq] * 1000.00) / (float)0xffff; float frequency = this->m_Frequency[frq]; return (int)frequency; // TODO float!! } void ToFCameraMESASR4000Controller::SetFPN( bool fpn ) { int acquireMode; acquireMode = SR_GetMode(m_MESAHandle); acquireMode &= ~AM_COR_FIX_PTRN; if (fpn) { acquireMode |= AM_COR_FIX_PTRN; } this->m_MESARes = SR_SetMode(m_MESAHandle, acquireMode); } void ToFCameraMESASR4000Controller::SetConvGray( bool ConvGray ) { int acquireMode; acquireMode = SR_GetMode(m_MESAHandle); acquireMode &= ~AM_CONV_GRAY; if (ConvGray) { acquireMode |= AM_CONV_GRAY; } this->m_MESARes = SR_SetMode(m_MESAHandle, acquireMode); } void ToFCameraMESASR4000Controller::SetMedian( bool median ) { int acquireMode; acquireMode = SR_GetMode(m_MESAHandle); acquireMode &= ~AM_MEDIAN; if (median) { acquireMode |= AM_MEDIAN; } this->m_MESARes = SR_SetMode(m_MESAHandle, acquireMode); } void ToFCameraMESASR4000Controller::SetANF( bool anf ) { int acquireMode; acquireMode = SR_GetMode(m_MESAHandle); acquireMode &= ~AM_DENOISE_ANF; if (anf) { acquireMode |= AM_DENOISE_ANF; } this->m_MESARes = SR_SetMode(m_MESAHandle, acquireMode); } -} \ No newline at end of file +} diff --git a/Modules/ToFHardware/mitkToFCameraPMDCamBoardController.cpp b/Modules/ToFHardware/mitkToFCameraPMDCamBoardController.cpp index 9729928c63..fbbfeb5c1d 100644 --- a/Modules/ToFHardware/mitkToFCameraPMDCamBoardController.cpp +++ b/Modules/ToFHardware/mitkToFCameraPMDCamBoardController.cpp @@ -1,225 +1,225 @@ /*=================================================================== 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 "mitkToFCameraPMDCamBoardController.h" #include "mitkToFConfig.h" #include //Plugin defines for CamBoard #define SOURCE_PARAM "" #define PROC_PARAM "" extern PMDHandle m_PMDHandle; //TODO extern PMDDataDescription m_DataDescription; //TODO namespace mitk { ToFCameraPMDCamBoardController::ToFCameraPMDCamBoardController() { m_SourcePlugin = MITK_TOF_PMDCAMBOARD_SOURCE_PLUGIN; m_SourceParam = SOURCE_PARAM; m_ProcPlugin = MITK_TOF_PMDCAMBOARD_PROCESSING_PLUGIN; m_ProcParam = PROC_PARAM; } ToFCameraPMDCamBoardController::~ToFCameraPMDCamBoardController() { } bool ToFCameraPMDCamBoardController::OpenCameraConnection() { if(!m_ConnectionCheck) { m_PMDRes = pmdOpen (&m_PMDHandle , m_SourcePlugin , m_SourceParam , m_ProcPlugin , m_ProcParam ); m_ConnectionCheck = ErrorText(m_PMDRes); if (!m_ConnectionCheck) { return m_ConnectionCheck; } // get image properties from camera this->UpdateCamera(); m_PMDRes = pmdGetSourceDataDescription(m_PMDHandle, &m_DataDescription); ErrorText(m_PMDRes); m_CaptureWidth = m_DataDescription.img.numColumns; m_CaptureHeight = m_DataDescription.img.numRows; m_PixelNumber = m_CaptureWidth*m_CaptureHeight; m_NumberOfBytes = m_PixelNumber * sizeof(float); m_SourceDataSize = m_DataDescription.size; m_SourceDataStructSize = m_DataDescription.size + sizeof(PMDDataDescription); MITK_INFO << "Datasource size: " << this->m_SourceDataSize <GetIntegrationTime(); MITK_INFO << "Modulation Frequence: " << this->GetModulationFrequency(); return m_ConnectionCheck; } else return m_ConnectionCheck; } bool mitk::ToFCameraPMDCamBoardController::SetDistanceOffset( float offset ) { std::stringstream command; command<<"SetSoftOffset "<m_PMDRes = pmdSourceCommand(m_PMDHandle,0,0,command.str().c_str()); return ErrorText(this->m_PMDRes); } float mitk::ToFCameraPMDCamBoardController::GetDistanceOffset() { char offset[16]; this->m_PMDRes = pmdSourceCommand(m_PMDHandle, offset, 16, "GetSoftOffset"); ErrorText(this->m_PMDRes); return atof(offset); } bool mitk::ToFCameraPMDCamBoardController::SetRegionOfInterest( unsigned int leftUpperCornerX, unsigned int leftUpperCornerY, unsigned int width, unsigned int height ) { // check if leftUpperCornerX and width are divisible by 3 otherwise round to the next value divisible by 3 unsigned int factor = leftUpperCornerX/3; leftUpperCornerX = 3*factor; factor = width/3; width = 3*factor; std::stringstream command; command<<"SetROI "<m_PMDRes = pmdSourceCommand(m_PMDHandle,0,0,command.str().c_str()); return ErrorText(this->m_PMDRes); } bool mitk::ToFCameraPMDCamBoardController::SetRegionOfInterest( unsigned int roi[4] ) { return this->SetRegionOfInterest(roi[0],roi[1],roi[2],roi[3]); } unsigned int* mitk::ToFCameraPMDCamBoardController::GetRegionOfInterest() { /* char result[64]; this->m_PMDRes = pmdSourceCommand(m_PMDHandle, result, 64, "GetROI"); ErrorText(this->m_PMDRes); // convert char array to uint array unsigned int roi[4]; std::stringstream currentValue; int counter = 0; std::string resultString = result; char blank = ' '; for (int i=0; i<64; i++) { if (result[i]!=blank) { currentValue<m_PMDRes = pmdSourceCommand(m_PMDHandle, 0, 0, "SetExposureMode Normal"); return ErrorText(this->m_PMDRes); } else if (mode==1) // SMB mode { this->m_PMDRes = pmdSourceCommand(m_PMDHandle, 0, 0, "SetExposureMode SMB"); return ErrorText(this->m_PMDRes); } else { MITK_ERROR<<"Specified exposure mode not supported. Exposure mode must be 0 (Normal) or 1 (SMB)"; return false; } } bool mitk::ToFCameraPMDCamBoardController::SetFieldOfView( float fov ) { std::stringstream commandStream; commandStream<<"SetFOV "<m_PMDRes = pmdProcessingCommand(m_PMDHandle, 0, 0, commandStream.str().c_str()); return ErrorText(this->m_PMDRes); } bool mitk::ToFCameraPMDCamBoardController::SetFPNCalibration( bool on ) { if(on) { this->m_PMDRes=pmdSourceCommand(m_PMDHandle,0,0,"SetFPNCalibration On"); return this->ErrorText(this->m_PMDRes); } else { this->m_PMDRes=pmdSourceCommand(m_PMDHandle,0,0,"SetFPNCalibration Off"); return this->ErrorText(this->m_PMDRes); } } bool mitk::ToFCameraPMDCamBoardController::SetFPPNCalibration( bool on ) { if(on) { this->m_PMDRes=pmdProcessingCommand(m_PMDHandle,0,0,"SetFPPNCalibration On"); return this->ErrorText(this->m_PMDRes); } else { this->m_PMDRes=pmdProcessingCommand(m_PMDHandle,0,0,"SetFPPNCalibration Off"); return this->ErrorText(this->m_PMDRes); } } bool mitk::ToFCameraPMDCamBoardController::SetLinearityCalibration( bool on ) { if(on) { this->m_PMDRes=pmdProcessingCommand(m_PMDHandle,0,0,"SetLinearityCalibration On"); return this->ErrorText(this->m_PMDRes); } else { this->m_PMDRes=pmdProcessingCommand(m_PMDHandle,0,0,"SetLinearityCalibration Off"); return this->ErrorText(this->m_PMDRes); } } bool mitk::ToFCameraPMDCamBoardController::SetLensCalibration( bool on ) { if (on) { this->m_PMDRes = pmdProcessingCommand(m_PMDHandle, 0, 0, "SetLensCalibration On"); return ErrorText(this->m_PMDRes); } else { this->m_PMDRes = pmdProcessingCommand(m_PMDHandle, 0, 0, "SetLensCalibration Off"); return ErrorText(this->m_PMDRes); } } -} \ No newline at end of file +} diff --git a/Modules/ToFHardware/mitkToFCameraPMDCamBoardController.h b/Modules/ToFHardware/mitkToFCameraPMDCamBoardController.h index c91b041e80..c3ba1d6fd1 100644 --- a/Modules/ToFHardware/mitkToFCameraPMDCamBoardController.h +++ b/Modules/ToFHardware/mitkToFCameraPMDCamBoardController.h @@ -1,116 +1,116 @@ /*=================================================================== 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 __mitkToFCameraPMDCamBoardController_h #define __mitkToFCameraPMDCamBoardController_h #include "mitkToFHardwareExports.h" #include "mitkCommon.h" #include "mitkToFCameraPMDController.h" #include "itkObject.h" #include "itkObjectFactory.h" namespace mitk { /** * @brief Interface to the Time-of-Flight (ToF) camera PMD CamBoard * * * @ingroup ToFHardware */ class MITK_TOFHARDWARE_EXPORT ToFCameraPMDCamBoardController : public mitk::ToFCameraPMDController { public: mitkClassMacro( ToFCameraPMDCamBoardController , mitk::ToFCameraPMDController ); itkNewMacro( Self ); /*! \brief opens a connection to the ToF camera and initializes the hardware specific members \return returns whether the connection was successful (true) or not (false) */ virtual bool OpenCameraConnection(); /*! \brief sets an additional distance offset which will be added to all distance values. \param offset offset in m */ bool SetDistanceOffset( float offset ); /*! \brief returns the currently applied distance offset in m \param offset offset in m */ float GetDistanceOffset(); /*! \brief Setting the region of interest, the camera is configured to only output a certain area of the image. \param leftUpperCornerX x value of left upper corner of region \param leftUpperCornerX y value of left upper corner of region \param width width of region \param height height of region */ bool SetRegionOfInterest( unsigned int leftUpperCornerX, unsigned int leftUpperCornerY, unsigned int width, unsigned int height ); /*! \brief Setting the region of interest, the camera is configured to only output a certain area of the image. \param roi region of interest. roi[0]: x value of left upper corner, roi[1]: y value of left upper corner, roi[2]: width, roi[3]: height */ bool SetRegionOfInterest( unsigned int roi[4] ); /*! \brief returns the region of interest currently set \return currently set region of interest. */ unsigned int* GetRegionOfInterest(); /*! \brief sets the exposure mode of the CamCube \param mode exposure mode. 0: normal mode (one exposure), 1: Suppression of motion blur (SMB), minimizes the time needed to capture a distance image from the camera which results in a reduced amount of motion artifact but may lead to increased noise. */ bool SetExposureMode( int mode ); /*! \brief Sets the field of view of the camera lens. \param fov field of view in degrees. The default value is 40 degrees. */ bool SetFieldOfView( float fov ); /* \brief Enable/Disable PMD fixed pattern noise (FPN) calibration \param on enabled (true), disabled (false) */ bool SetFPNCalibration( bool on ); /* \brief Enable/Disable PMD fixed pattern phase noise (FPPN) calibration \param on enabled (true), disabled (false) */ bool SetFPPNCalibration( bool on ); /* \brief Enable/Disable PMD linearity calibration \param on enabled (true), disabled (false) */ bool SetLinearityCalibration( bool on ); /* \brief Enable/Disable PMD lens calibration \param on enabled (true), disabled (false) */ bool SetLensCalibration( bool on ); protected: ToFCameraPMDCamBoardController(); ~ToFCameraPMDCamBoardController(); private: }; } //END mitk namespace -#endif \ No newline at end of file +#endif diff --git a/Modules/ToFHardware/mitkToFCameraPMDO3Controller.h b/Modules/ToFHardware/mitkToFCameraPMDO3Controller.h index da6386e83b..763f28a941 100644 --- a/Modules/ToFHardware/mitkToFCameraPMDO3Controller.h +++ b/Modules/ToFHardware/mitkToFCameraPMDO3Controller.h @@ -1,58 +1,58 @@ /*=================================================================== 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 __mitkToFCameraPMDO3Controller_h #define __mitkToFCameraPMDO3Controller_h #include "mitkToFHardwareExports.h" #include "mitkCommon.h" #include "mitkToFCameraPMDController.h" #include "itkObject.h" #include "itkObjectFactory.h" namespace mitk { /** * @brief Interface to the Time-of-Flight (ToF) camera PMD O3 * Connection is established over Ethernet connection. IP address must be specified. * * @ingroup ToFHardware */ class MITK_TOFHARDWARE_EXPORT ToFCameraPMDO3Controller : public mitk::ToFCameraPMDController { public: mitkClassMacro( ToFCameraPMDO3Controller , mitk::ToFCameraPMDController ); itkNewMacro( Self ); /*! \brief opens a connection to the PMD O3 ToF camera */ virtual bool OpenCameraConnection(); protected: ToFCameraPMDO3Controller(); ~ToFCameraPMDO3Controller(); private: char *m_IPAddress; ///< holds the ip adress the O3 camera is connected to }; } //END mitk namespace -#endif \ No newline at end of file +#endif diff --git a/Modules/ToFProcessing/mitkToFImageDownsamplingFilter.cpp b/Modules/ToFProcessing/mitkToFImageDownsamplingFilter.cpp index 417a251655..3eb94d3bd3 100644 --- a/Modules/ToFProcessing/mitkToFImageDownsamplingFilter.cpp +++ b/Modules/ToFProcessing/mitkToFImageDownsamplingFilter.cpp @@ -1,130 +1,130 @@ /*=================================================================== 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 "mitkToFImageDownsamplingFilter.h" #include #include #include #include #include #include #include mitk::ToFImageDownsamplingFilter::ToFImageDownsamplingFilter(): m_ResampledX(100), m_ResampledY(100),m_ResampledZ(1) { } mitk::ToFImageDownsamplingFilter::~ToFImageDownsamplingFilter() { } void mitk::ToFImageDownsamplingFilter::GenerateData() { // set input image mitk::Image::ConstPointer inputImage = this->GetInput(0) ; if ( (inputImage->GetDimension() > 3) || (inputImage->GetDimension() < 2) ) { MITK_ERROR << "mitk::TofImageDownsamplingFilter:GenerateData works only with 2D and 3D images, sorry." << std::endl; itkExceptionMacro("mitk::TofImageDownsamplingFilter:GenerateData works only with 2D and 3D images, sorry."); return; - } + } if ( (inputImage->GetDimension(0)GetDimension(1)GetDimension(2)GetDimension()) { case 2: { AccessFixedDimensionByItk( inputImage.GetPointer(), ItkImageResampling, 2 ); break; } case 3: { AccessFixedDimensionByItk( inputImage.GetPointer(), ItkImageResampling, 3 ); break; } default: break; } } template void mitk::ToFImageDownsamplingFilter::ItkImageResampling( itk::Image* itkImage ) { // declare typdef for itk image from input mitk image typedef itk::Image< TPixel, VImageDimension > ItkImageType; //declare itk filter related typedefs (transform type, interpolater, and size type) typedef itk::ResampleImageFilter ResamplerFilterType; typedef itk::IdentityTransform TransformType; typedef itk::NearestNeighborInterpolateImageFunction InterpolatorType; typedef typename ItkImageType::SizeType::SizeValueType SizeValueType; //instantiate filter related parameters typename ResamplerFilterType::Pointer resampler = ResamplerFilterType::New(); typename TransformType::Pointer transform = TransformType::New(); typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); // establish size for downsampled image ( the result of this filter) typename ItkImageType::SizeType inputSize = itkImage->GetLargestPossibleRegion().GetSize(); typename ItkImageType::SizeType size; size[0] = static_cast< SizeValueType >( m_ResampledX ); size[1] = static_cast< SizeValueType >( m_ResampledY ); size[2] = static_cast< SizeValueType >( m_ResampledZ ); //establish spacing for new downsampled image ( resulting image) const typename ItkImageType::SpacingType& inputSpacing = itkImage->GetSpacing(); typename ItkImageType::SpacingType spacing; spacing[0] = inputSpacing[0] * ( inputSize[0]/ m_ResampledX ); spacing[1] = inputSpacing[1] * ( inputSize[1]/ m_ResampledY ); spacing[2] = inputSpacing[2] * ( inputSize[2]/ m_ResampledZ ); // set filter parameters and update transform->SetIdentity(); resampler->SetTransform(transform); resampler->SetInterpolator(interpolator); resampler->SetOutputSpacing(spacing); resampler->SetOutputOrigin(itkImage->GetOrigin()); resampler->SetSize(size); resampler->SetInput(itkImage); resampler->UpdateLargestPossibleRegion(); - // Create mitk container for resulting image + // Create mitk container for resulting image mitk::Image::Pointer resultImage = ImageToImageFilter::GetOutput(); // Cast itk image to mitk image mitk::CastToMitkImage(resampler->GetOutput(), resultImage); -} \ No newline at end of file +} diff --git a/Modules/ToFProcessing/mitkToFImageDownsamplingFilter.h b/Modules/ToFProcessing/mitkToFImageDownsamplingFilter.h index 7a2d99bb46..bd5f8506fa 100644 --- a/Modules/ToFProcessing/mitkToFImageDownsamplingFilter.h +++ b/Modules/ToFProcessing/mitkToFImageDownsamplingFilter.h @@ -1,85 +1,85 @@ /*=================================================================== 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 __mitkToFImageDownsamplingFilter_h #define __mitkToFImageDownsamplingFilter_h //MITK includes #include #include "mitkImageToImageFilter.h" #include "mitkToFProcessingExports.h" // ITK includes #include "itkImage.h" namespace mitk { /** * @brief Reduces the resolution of a ToF distance image. Although it is meant to be used for ToF distance images, it should work * for any 2D or 3D images. The dimensions (in pixels) of the desired image are taken as input parameters, and an image with these * specified dimensions is created. * * @ingroup SurfaceFilters * @ingroup ToFProcessing */ - class mitkToFProcessing_EXPORT ToFImageDownsamplingFilter : public ImageToImageFilter - { - public: - mitkClassMacro(ToFImageDownsamplingFilter, ImageToImageFilter); - itkNewMacro(Self); + class mitkToFProcessing_EXPORT ToFImageDownsamplingFilter : public ImageToImageFilter + { + public: + mitkClassMacro(ToFImageDownsamplingFilter, ImageToImageFilter); + itkNewMacro(Self); - itkSetMacro(ResampledX,double); - itkGetMacro(ResampledX,double); + itkSetMacro(ResampledX,double); + itkGetMacro(ResampledX,double); - itkSetMacro(ResampledY,double); - itkGetMacro(ResampledY,double); + itkSetMacro(ResampledY,double); + itkGetMacro(ResampledY,double); - itkSetMacro(ResampledZ,double); - itkGetMacro(ResampledZ,double); + itkSetMacro(ResampledZ,double); + itkGetMacro(ResampledZ,double); - protected: - /*! + protected: + /*! \brief Standard constructor */ - ToFImageDownsamplingFilter(); - + ToFImageDownsamplingFilter(); + /*! \brief Standard destructor */ - ~ToFImageDownsamplingFilter(); + ~ToFImageDownsamplingFilter(); /*! \brief Method generating the output of this filter. Called in the updated process of the pipeline. This method calls the AccessFixedDimensionByItk class with the ItkImageResampling function below */ - virtual void GenerateData(); + virtual void GenerateData(); /*! \brief Templated method for ITK image type which performs the resampling with an itk filter. \param itkImage is the input to the filter converted to ITK format \param TPixel is a pixel type such as float or char or double \param VImageDimension is the image dimension (2D or 3D) */ template void ItkImageResampling( itk::Image* itkImage ); - double m_ResampledX;///< length of x dimension of output image in pixels - double m_ResampledY;///< length of y dimension of output image in pixels - double m_ResampledZ;///< length of z dimension of output image in pixels (if 2D, default is set to 1) + double m_ResampledX;///< length of x dimension of output image in pixels + double m_ResampledY;///< length of y dimension of output image in pixels + double m_ResampledZ;///< length of z dimension of output image in pixels (if 2D, default is set to 1) - }; +}; }// end namespace mitk -#endif \ No newline at end of file +#endif diff --git a/Modules/US/Testing/mitkUSDeviceTest.cpp b/Modules/US/Testing/mitkUSDeviceTest.cpp index f1d2bba157..62ca54f7e4 100644 --- a/Modules/US/Testing/mitkUSDeviceTest.cpp +++ b/Modules/US/Testing/mitkUSDeviceTest.cpp @@ -1,109 +1,109 @@ /*=================================================================== 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 "mitkUSDevice.h" #include "mitkUSProbe.h" #include "mitkTestingMacros.h" #include class mitkUSDeviceTestClass { public: static void TestInstantiation() { // let's create an object of our class mitk::USDevice::Pointer device = mitk::USDevice::New("Manufacturer", "Model", true); MITK_TEST_CONDITION_REQUIRED(device.IsNotNull(), "USDevice should not be null after instantiation"); MITK_TEST_CONDITION_REQUIRED((device->GetDeviceManufacturer().compare("Manufacturer") == 0), "Manufacturer should be set correctly"); MITK_TEST_CONDITION_REQUIRED((device->GetDeviceModel().compare("Model") == 0), "Model should be set correctly"); MITK_TEST_CONDITION_REQUIRED((device->GetIsVideoOnly() == true), "Device should be VideoOnly"); } static void TestAddProbe() { mitk::USDevice::Pointer device = mitk::USDevice::New("Manufacturer", "Model", true); // create probes mitk::USProbe::Pointer usSource = mitk::USProbe::New(); mitk::USProbe::Pointer probeA = mitk::USProbe::New(); mitk::USProbe::Pointer probeB = mitk::USProbe::New(); mitk::USProbe::Pointer identicalProbe = mitk::USProbe::New(); // only this one should be identical // give my babys some names probeA->SetName("ProbeA"); probeB->SetName("ProbeB"); identicalProbe->SetName("ProbeA"); // I'm gonna be a bad father... //right now, list of devices should be empty MITK_TEST_CONDITION_REQUIRED(device->GetConnectedProbes().size() == 0, "Newly created device should have no probes connected"); // Connect Probe A device->AddProbe(probeA); MITK_TEST_CONDITION_REQUIRED(device->GetConnectedProbes().size() == 1, "Device should add one new probe"); // Connect Probe B device->AddProbe(probeB); MITK_TEST_CONDITION_REQUIRED(device->GetConnectedProbes().size() == 2, "Device should add another probe"); // Connect identical Probe device->AddProbe(identicalProbe); MITK_TEST_CONDITION_REQUIRED(device->GetConnectedProbes().size() == 2, "Device should not have added identical probe"); } static void TestActivateProbe() { mitk::USDevice::Pointer device = mitk::USDevice::New("Manufacturer", "Model", true); // create probes mitk::USProbe::Pointer usSource = mitk::USProbe::New(); mitk::USProbe::Pointer probeA = mitk::USProbe::New(); mitk::USProbe::Pointer probeB = mitk::USProbe::New(); mitk::USProbe::Pointer identicalProbe = mitk::USProbe::New(); // only this one should be identical // names probeA->SetName("ProbeA"); probeB->SetName("ProbeB"); identicalProbe->SetName("ProbeA"); device->AddProbe(probeA); device->AddProbe(probeB); // We after activation, we expect the device to activate probeA, which is the first-connected identical version. device->ActivateProbe(identicalProbe); MITK_TEST_CONDITION_REQUIRED(device->GetActiveProbe() == probeA, "probe A should be active"); // And we deactivate it again... device->DeactivateProbe(); MITK_TEST_CONDITION_REQUIRED(device->GetActiveProbe().IsNull(), "After deactivation, no probe should be active"); } }; /** * This function is testing methods of the class USDevice. */ int mitkUSDeviceTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("mitkUSDeviceTest"); mitkUSDeviceTestClass::TestInstantiation(); mitkUSDeviceTestClass::TestAddProbe(); mitkUSDeviceTestClass::TestActivateProbe(); MITK_TEST_END(); -} \ No newline at end of file +} diff --git a/Modules/US/Testing/mitkUSImageTest.cpp b/Modules/US/Testing/mitkUSImageTest.cpp index 328ed504b0..e0550e3c11 100644 --- a/Modules/US/Testing/mitkUSImageTest.cpp +++ b/Modules/US/Testing/mitkUSImageTest.cpp @@ -1,71 +1,71 @@ /*=================================================================== 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 "mitkUSImage.h" #include "mitkTestingMacros.h" #include "mitkUSImageMetadata.h" class mitkUSImageTestClass { public: static void TestInstantiation() { // let's create an object of our class mitk::USImage::Pointer usImage = mitk::USImage::New(); MITK_TEST_CONDITION_REQUIRED(usImage.IsNotNull(), "USImage should not be null after instantiation"); } static void TestMetadataInProperties(){ mitk::USImage::Pointer usImage = mitk::USImage::New(); mitk::USImageMetadata::Pointer meta1 = mitk::USImageMetadata::New(); // Create a complete metadataset and write it to the image meta1->SetDeviceComment("comment"); meta1->SetDeviceIsVideoOnly(true); meta1->SetDeviceManufacturer("manufacturer"); meta1->SetDeviceModel("model"); meta1->SetProbeFrequency("7 MHz"); meta1->SetProbeName("CA X3"); meta1->SetZoom("3x"); usImage->SetMetadata(meta1); //read metadata from image an compare for equality mitk::USImageMetadata::Pointer meta2 = usImage->GetMetadata(); MITK_TEST_CONDITION_REQUIRED(meta1->GetDeviceComment().compare(meta2->GetDeviceComment()) == 0, "Comparing Metadata after write & read: Device Comment"); MITK_TEST_CONDITION_REQUIRED(meta1->GetDeviceManufacturer().compare(meta2->GetDeviceManufacturer()) == 0, "Comparing Metadata after write & read: Device Manufacturer"); MITK_TEST_CONDITION_REQUIRED(meta1->GetDeviceModel().compare(meta2->GetDeviceModel()) == 0, "Comparing Metadata after write & read: Device Model"); MITK_TEST_CONDITION_REQUIRED(meta1->GetDeviceIsVideoOnly() == meta2->GetDeviceIsVideoOnly() , "Comparing Metadata after write & read: IsVideoOnly"); MITK_TEST_CONDITION_REQUIRED(meta1->GetProbeName().compare(meta2->GetProbeName()) == 0, "Comparing Metadata after write & read: Probe Name"); MITK_TEST_CONDITION_REQUIRED(meta1->GetProbeFrequency().compare(meta2->GetProbeFrequency()) == 0, "Comparing Metadata after write & read: Frequency"); MITK_TEST_CONDITION_REQUIRED(meta1->GetZoom().compare(meta2->GetZoom()) == 0, "Comparing Metadata after write & read: Zoom Factor"); } }; /** * This function is testing methods of the class USImage2D. */ int mitkUSImageTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("mitkUSImage2DTest"); mitkUSImageTestClass::TestInstantiation(); mitkUSImageTestClass::TestMetadataInProperties(); MITK_TEST_END(); -} \ No newline at end of file +} diff --git a/Modules/US/Testing/mitkUSImageVideoSourceTest.cpp b/Modules/US/Testing/mitkUSImageVideoSourceTest.cpp index b5a97498b8..199ebc0005 100644 --- a/Modules/US/Testing/mitkUSImageVideoSourceTest.cpp +++ b/Modules/US/Testing/mitkUSImageVideoSourceTest.cpp @@ -1,81 +1,81 @@ /*=================================================================== 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 "mitkUSImageVideoSource.h" #include "mitkTestingMacros.h" class mitkUSImageVideoSourceTestClass { public: static void TestInstantiation() { // let's create an object of our class mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New(); MITK_TEST_CONDITION_REQUIRED(usSource.IsNotNull(), "USImageVideoSource should not be null after instantiation"); } static void TestOpenVideoFile(std::string videoFilePath) { mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New(); usSource->SetVideoFileInput(videoFilePath); MITK_TEST_CONDITION_REQUIRED(usSource->GetIsVideoReady(), "USImageVideoSource should have isVideoReady flag set after opening a Video File"); mitk::USImage::Pointer frame; frame = usSource->GetNextImage(); MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "First frame should not be null."); frame = usSource->GetNextImage(); MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "Second frame should not be null."); frame = usSource->GetNextImage(); MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "Third frame should not be null."); frame = usSource->GetNextImage(); MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "Fourth frame should not be null."); frame = usSource->GetNextImage(); MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "Fifth frame should not be null."); } /** This Test will fail if no device is attached. Since it basically covers the same non-OpenCV Functionality as TestOpenVideoFile, it is ommited static void TestOpenDevice() { mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New(); usSource->SetCameraInput(-1); MITK_TEST_CONDITION_REQUIRED(usSource->GetIsVideoReady(), "USImageVideoSource should have isVideoReady flag set after opening a Camera device"); } */ }; /** * This function is testing methods of the class USImageVideoSource. */ int mitkUSImageVideoSourceTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkUSImageVideoSourceTest"); mitkUSImageVideoSourceTestClass::TestInstantiation(); #ifdef WIN32 // Video file compression is currently only supported under windows. mitkUSImageVideoSourceTestClass::TestOpenVideoFile(argv[1]); #endif // This test is commented out since no videodevcie ist steadily connected to the dart clients. // Functionality should sufficiently be tested through TestOpenVideoFile anyway //mitkUSImageVideoSourceTestClass::TestOpenDevice(); MITK_TEST_END(); -} \ No newline at end of file +} diff --git a/Modules/US/Testing/mitkUSPipelineTest.cpp b/Modules/US/Testing/mitkUSPipelineTest.cpp index a0a3e4239e..7d2613358a 100644 --- a/Modules/US/Testing/mitkUSPipelineTest.cpp +++ b/Modules/US/Testing/mitkUSPipelineTest.cpp @@ -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. ===================================================================*/ #include "mitkUSVideoDevice.h" #include "mitkTestingMacros.h" #include "mitkUSImageToUSImageFilter.h" #include "mitkPadImageFilter.h" // START TESTFILER // This is an specialization of the USImageToUSImageFIlter class TestUSFilter : public mitk::USImageToUSImageFilter { protected: TestUSFilter() : mitk::USImageToUSImageFilter(){}; virtual ~TestUSFilter(){}; public: mitkClassMacro(TestUSFilter, mitk::USImageToUSImageFilter); itkNewMacro(Self); virtual void GenerateOutputInformation() { mitk::Image::Pointer inputImage = (mitk::Image*) this->GetInput(0); mitk::Image::Pointer output = (mitk::Image*) this->GetOutput(0); if(inputImage.IsNull()) return; }; void GenerateData() { MITK_INFO << "GenerateData called in Testfilter!"; //mitk::Image::Pointer ni = const_cast(this->GetInput(0)); mitk::USImage::Pointer ni = this->GetInput(0); mitk::USImage::Pointer result = mitk::USImage::New(); result->Initialize(ni); result->SetImportVolume(ni->GetData()); mitk::USImageMetadata::Pointer meta = ni->GetMetadata(); meta->SetDeviceComment("Test"); result->SetMetadata(meta); SetNthOutput(0, result); MITK_INFO << "GenerateData completed in Testfilter!"; }; }; // END TESTFILTER class mitkUSPipelineTestClass { public: static void TestPipelineUS(std::string videoFilePath) { // Set up a pipeline mitk::USVideoDevice::Pointer videoDevice = mitk::USVideoDevice::New("C:\\Users\\maerz\\Videos\\Debut\\us.avi", "Manufacturer", "Model"); TestUSFilter::Pointer filter = TestUSFilter::New(); videoDevice->Update(); filter->SetInput(videoDevice->GetOutput()); filter->Update(); MITK_TEST_CONDITION_REQUIRED(videoDevice.IsNotNull(), "videoDevice should not be null after instantiation"); //mitk::USImage::Pointer result = dynamic_cast (filter->GetOutput(0)); mitk::USImage::Pointer result = filter->GetOutput(0); MITK_TEST_CONDITION_REQUIRED(result.IsNotNull(), "resulting images should not be null"); std::string model = result->GetMetadata()->GetDeviceModel(); MITK_TEST_CONDITION_REQUIRED(model.compare("Model") == 0 , "Resulting images should have their metadata set correctly"); } }; /** * This function is setting up a pipeline and checks the output for validity. */ int mitkUSPipelineTest(int argc , char* argv[]) { MITK_TEST_BEGIN("mitkUSPipelineTest"); #ifdef WIN32 // Video file compression is currently only supported under windows. mitkUSPipelineTestClass::TestPipelineUS(argv[1]); #endif MITK_TEST_END(); -} \ No newline at end of file +} diff --git a/Modules/US/Testing/mitkUSProbeTest.cpp b/Modules/US/Testing/mitkUSProbeTest.cpp index 715c56fd38..22aa2b263b 100644 --- a/Modules/US/Testing/mitkUSProbeTest.cpp +++ b/Modules/US/Testing/mitkUSProbeTest.cpp @@ -1,64 +1,64 @@ /*=================================================================== 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 "mitkUSProbe.h" #include "mitkTestingMacros.h" class mitkUSProbeTestClass { public: static void TestInstantiation() { // let's create an object of our class mitk::USProbe::Pointer probe = mitk::USProbe::New(); MITK_TEST_CONDITION_REQUIRED(probe.IsNotNull(), "USProbe should not be null after instantiation"); } static void TestIsEqualToProbe() { mitk::USProbe::Pointer usSource = mitk::USProbe::New(); mitk::USProbe::Pointer probeA = mitk::USProbe::New(); mitk::USProbe::Pointer probeB = mitk::USProbe::New(); mitk::USProbe::Pointer probea = mitk::USProbe::New(); mitk::USProbe::Pointer identicalProbe = mitk::USProbe::New(); probeA->SetName("ProbeA"); probeB->SetName("ProbeB"); probea->SetName("Probea"); identicalProbe->SetName("ProbeA"); MITK_TEST_CONDITION_REQUIRED(! probeA->IsEqualToProbe(probeB), "ProbeA and probeB should not be equal"); MITK_TEST_CONDITION_REQUIRED(! probeA->IsEqualToProbe(probea), "ProbeA and probea should not be equal"); MITK_TEST_CONDITION_REQUIRED(probeA->IsEqualToProbe(identicalProbe), "ProbeA and probeA should be equal"); } }; /** * This function is testing methods of the class USProbe. */ int mitkUSProbeTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("mitkUSProbeTest"); mitkUSProbeTestClass::TestInstantiation(); mitkUSProbeTestClass::TestIsEqualToProbe(); MITK_TEST_END(); -} \ No newline at end of file +} diff --git a/Modules/US/USFilters/mitkUSDevice.h b/Modules/US/USFilters/mitkUSDevice.h index 3b83efee1b..5fb28e7dc1 100644 --- a/Modules/US/USFilters/mitkUSDevice.h +++ b/Modules/US/USFilters/mitkUSDevice.h @@ -1,156 +1,156 @@ /*=================================================================== 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 MITKUSDevice_H_HEADER_INCLUDED_ #define MITKUSDevice_H_HEADER_INCLUDED_ #include #include "mitkUSProbe.h" #include "mitkUSImageMetadata.h" #include "mitkUSImage.h" #include #include #include #include namespace mitk { /**Documentation * \brief A device holds information about it's model, make and the connected probes. It is the * common super class for all devices and acts as an image source for mitkUSImages. It is the base class * for all US Devices, and every new device should extend it. * \ingroup US */ class MitkUS_EXPORT USDevice : public mitk::ImageSource { public: mitkClassMacro(USDevice, mitk::ImageSource); /** * \brief Enforces minimal Metadata to be set. The isVideoOnly flag indicates that this class * only handles a videostream and does not receive Metadata from the physical device itself. */ mitkNewMacro3Param(Self, std::string, std::string, bool); /** * \brief Add a probe to the device without connecting to it. * This should usually be done before connecting to the probe. */ virtual void AddProbe(mitk::USProbe::Pointer probe); /** * \brief Connect to a probe and activate it. The probe should be added first. * Usually, a VideoDevice will simply add a probe it wants to connect to, * but an SDK Device might require adding a probe first. */ virtual void ActivateProbe(mitk::USProbe::Pointer probe); /** * \brief Deactivates the currently active probe. */ virtual void DeactivateProbe(); /** * \brief Removes a probe from the ist of currently added probes. */ //virtual void removeProbe(mitk::USProbe::Pointer probe); /** * \brief Returns a vector containing all connected probes. */ std::vector GetConnectedProbes(); /** *\brief return the output (output with id 0) of the filter */ USImage* GetOutput(void); /** *\brief return the output with id idx of the filter */ USImage* GetOutput(unsigned int idx); /** *\brief Graft the specified DataObject onto this ProcessObject's output. * * See itk::ImageSource::GraftNthOutput for details */ virtual void GraftNthOutput(unsigned int idx, itk::DataObject *graft); /** * \brief Graft the specified DataObject onto this ProcessObject's output. * * See itk::ImageSource::Graft Output for details */ virtual void GraftOutput(itk::DataObject *graft); /** * \brief Make a DataObject of the correct type to used as the specified output. * * This method is automatically called when DataObject::DisconnectPipeline() * is called. DataObject::DisconnectPipeline, disconnects a data object * from being an output of its current source. When the data object * is disconnected, the ProcessObject needs to construct a replacement * output data object so that the ProcessObject is in a valid state. * Subclasses of USImageVideoSource that have outputs of different * data types must overwrite this method so that proper output objects * are created. */ virtual DataObjectPointer MakeOutput(unsigned int idx); //########### GETTER & SETTER ##################// /** * \brief Returns the currently active probe or null, if none is active */ itkGetMacro(ActiveProbe, mitk::USProbe::Pointer); std::string GetDeviceManufacturer(); std::string GetDeviceModel(); std::string GetDeviceComment(); bool GetIsVideoOnly(); protected: mitk::USProbe::Pointer m_ActiveProbe; std::vector m_ConnectedProbes; /** * \brief This metadata set is privately used to imprint USImages with Metadata later. * At instantiation time, it only contains Information about the Device, * At scan time, it integrates this data with the probe information and imprints it on * the produced images. This field is intentionally hidden from outside interference. */ mitk::USImageMetadata::Pointer m_Metadata; /** * \brief Enforces minimal Metadata to be set. The isVideoOnly flag indicates that this class * only handles a videostream and does not recieve Metadata from the physical device itself. */ USDevice(std::string manufacturer, std::string model, bool isVideoOnly); virtual ~USDevice(); /** * \brief Grabs the next frame from the Video input. This method is called internally, whenever Update() is invoked by an Output. */ void GenerateData(); }; } // namespace mitk -#endif \ No newline at end of file +#endif diff --git a/Modules/US/USFilters/mitkUSImage.h b/Modules/US/USFilters/mitkUSImage.h index f3d3283a55..b14f6936e0 100644 --- a/Modules/US/USFilters/mitkUSImage.h +++ b/Modules/US/USFilters/mitkUSImage.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 MITKUSIMAGE_H_HEADER_INCLUDED_ #define MITKUSIMAGE_H_HEADER_INCLUDED_ #include #include #include #include "mitkUSImageMetadata.h" namespace mitk { /**Documentation * \brief This specialization of mitk::Image only appends necessary Metadata to an MITK image. Otherwise it can safely be treated like it's mother class. * To generate an USImage from a standard mitkImage, call the appropriate constructor USImage(image::Pointer) * \ingroup US */ class MitkUS_EXPORT USImage : public mitk::Image { public: mitkClassMacro(USImage, mitk::Image); itkNewMacro(Self); /** * \brief this constructor creates an US Image identical to the recieved mitkImage. The Metadata are set to default. * The image data is shared, so don't continue to manipulate the original image. */ mitkNewMacro1Param(Self, mitk::Image::Pointer); /** * \brief Reads out this image's Metadata set from the properties and returns a corresponding USImageMetadata object. */ mitk::USImageMetadata::Pointer GetMetadata(); /** * \brief Writes the information of the metadata object into the image's properties. */ void SetMetadata(mitk::USImageMetadata::Pointer metadata); protected: /** * \brief This constructor creates an empty USImage. The Metadata are set to default. */ USImage(); /** * \brief this constructor creates an US Image identical to the recieved mitkImage. The Metadata are set to default. * The image data is shared, so don't continue to manipulate the original image. */ USImage(mitk::Image::Pointer image); virtual ~USImage(); }; } // namespace mitk -#endif \ No newline at end of file +#endif diff --git a/Modules/US/USFilters/mitkUSImageMetadata.h b/Modules/US/USFilters/mitkUSImageMetadata.h index ae42a70ad7..b95c0b45ab 100644 --- a/Modules/US/USFilters/mitkUSImageMetadata.h +++ b/Modules/US/USFilters/mitkUSImageMetadata.h @@ -1,88 +1,88 @@ /*=================================================================== 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 MITKUSIMAGEMETADATA_H_HEADER_INCLUDED_ #define MITKUSIMAGEMETADATA_H_HEADER_INCLUDED_ #include #include #include #include namespace mitk { /**Documentation * \brief This class encapsulates all necessary metadata to describe a US Image. * \ingroup US */ class MitkUS_EXPORT USImageMetadata : public itk::Object { public: mitkClassMacro(USImageMetadata, itk::Object); itkNewMacro(Self); //## getter and setter ## itkGetMacro(DeviceManufacturer, std::string); itkSetMacro(DeviceManufacturer, std::string); itkGetMacro(DeviceModel, std::string); itkSetMacro(DeviceModel, std::string); itkGetMacro(DeviceComment, std::string); itkSetMacro(DeviceComment, std::string); itkGetMacro(ProbeName, std::string); itkSetMacro(ProbeName, std::string); itkGetMacro(ProbeFrequency, std::string); itkSetMacro(ProbeFrequency, std::string); itkGetMacro(Zoom, std::string); itkSetMacro(Zoom, std::string); itkGetMacro(DeviceIsVideoOnly, bool); itkSetMacro(DeviceIsVideoOnly, bool); // The following constants define how metadata is written to and read from an mitk image // when defining new properties, add them here, define them in the cpp, and add them to // USImage's getMetadata and setMetadata methods as well static const char* PROP_DEV_MANUFACTURER; static const char* PROP_DEV_MODEL; static const char* PROP_DEV_COMMENT; static const char* PROP_DEV_ISVIDEOONLY; static const char* PROP_PROBE_NAME; static const char* PROP_PROBE_FREQUENCY; static const char* PROP_ZOOM; protected: /** * \brief Creates a new metadata object with all fields set to default values. */ USImageMetadata(); virtual ~USImageMetadata(); std::string m_DeviceManufacturer; std::string m_DeviceModel; std::string m_DeviceComment; std::string m_ProbeName; std::string m_ProbeFrequency; std::string m_Zoom; bool m_DeviceIsVideoOnly; }; } // namespace mitk -#endif \ No newline at end of file +#endif diff --git a/Modules/US/USFilters/mitkUSImageToUSImageFilter.h b/Modules/US/USFilters/mitkUSImageToUSImageFilter.h index 86ff1e89c0..6db7bf5c34 100644 --- a/Modules/US/USFilters/mitkUSImageToUSImageFilter.h +++ b/Modules/US/USFilters/mitkUSImageToUSImageFilter.h @@ -1,53 +1,53 @@ /*=================================================================== 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 MITKUSImageToUSImageFilter_H_HEADER_INCLUDED_ #define MITKUSImageToUSImageFilter_H_HEADER_INCLUDED_ #include #include #include #include "mitkUSImage.h" namespace mitk { /**Documentation * \brief Todo * \ingroup US */ class MitkUS_EXPORT USImageToUSImageFilter : public mitk::ImageToImageFilter { public: mitkClassMacro(USImageToUSImageFilter, mitk::ImageToImageFilter); itkNewMacro(Self); // ---- OVERRIDDEN INHERITED METHODS ---- // virtual void SetInput (const mitk::USImage *image); virtual void SetInput (unsigned int index, const mitk::USImage *image); virtual mitk::USImage::Pointer GetOutput(unsigned int idx); virtual mitk::USImage::Pointer GetInput (unsigned int idx); protected: USImageToUSImageFilter(); virtual ~USImageToUSImageFilter(); }; } // namespace mitk -#endif \ No newline at end of file +#endif diff --git a/Modules/US/USFilters/mitkUSImageVideoSource.h b/Modules/US/USFilters/mitkUSImageVideoSource.h index e90772ddfe..954114ca95 100644 --- a/Modules/US/USFilters/mitkUSImageVideoSource.h +++ b/Modules/US/USFilters/mitkUSImageVideoSource.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 MITKUSImageVideoSource_H_HEADER_INCLUDED_ #define MITKUSImageVideoSource_H_HEADER_INCLUDED_ #include #include "mitkUSImage.h" #include "mitkOpenCVVideoSource.h" #include "mitkOpenCVToMitkImageFilter.h" namespace mitk { /**Documentation * \brief This class can be pointed to a video file or a videodevice and delivers USImages with default metadata Sets * * \ingroup US */ class MitkUS_EXPORT USImageVideoSource : public itk::Object { public: mitkClassMacro(USImageVideoSource, itk::ProcessObject); itkNewMacro(Self); /** *\brief Opens a video file for streaming. If nothing goes wrong, the * VideoSource is ready to deliver images after calling this function. */ void SetVideoFileInput(std::string path); /** *\brief Opens a video device for streaming. Takes the Device id. Try -1 for "grab the first you can get" * which works quite well if only one device is available. If nothing goes wrong, the * VideoSource is ready to deliver images after calling this function. */ void SetCameraInput(int deviceID); /** *\brief Retrieves the next frame. This will typically be the next frame in a file * or the last cahced file in a devcie. */ mitk::USImage::Pointer GetNextImage(); // Getter & Setter itkGetMacro(OpenCVVideoSource, mitk::OpenCVVideoSource::Pointer); itkSetMacro(OpenCVVideoSource, mitk::OpenCVVideoSource::Pointer); itkGetMacro(IsVideoReady, bool); itkGetMacro(IsMetadataReady, bool); itkGetMacro(IsGeometryReady, bool); protected: USImageVideoSource(); virtual ~USImageVideoSource(); /** * \brief The source of the video */ mitk::OpenCVVideoSource::Pointer m_OpenCVVideoSource; /** * \brief The Following flags are used internally, to assure that all necessary steps are taken before capturing */ bool m_IsVideoReady; bool m_IsMetadataReady; bool m_IsGeometryReady; mitk::OpenCVToMitkImageFilter::Pointer m_OpenCVToMitkFilter; }; } // namespace mitk -#endif /* MITKUSImageVideoSource_H_HEADER_INCLUDED_ */ \ No newline at end of file +#endif /* MITKUSImageVideoSource_H_HEADER_INCLUDED_ */ diff --git a/Modules/US/USFilters/mitkUSProbe.cpp b/Modules/US/USFilters/mitkUSProbe.cpp index 22f2f51b1c..21e4889bcb 100644 --- a/Modules/US/USFilters/mitkUSProbe.cpp +++ b/Modules/US/USFilters/mitkUSProbe.cpp @@ -1,35 +1,35 @@ /*=================================================================== 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 "mitkUSProbe.h" #include mitk::USProbe::USProbe() : itk::Object() { } mitk::USProbe::~USProbe() { } bool mitk::USProbe::IsEqualToProbe(mitk::USProbe::Pointer probe) { if(m_Name.compare(probe->GetName()) == 0) return true; else return false; -} \ No newline at end of file +} diff --git a/Modules/US/USFilters/mitkUSProbe.h b/Modules/US/USFilters/mitkUSProbe.h index 5f55f4cc31..841455162f 100644 --- a/Modules/US/USFilters/mitkUSProbe.h +++ b/Modules/US/USFilters/mitkUSProbe.h @@ -1,63 +1,63 @@ /*=================================================================== 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 MITKUSProbe_H_HEADER_INCLUDED_ #define MITKUSProbe_H_HEADER_INCLUDED_ #include #include #include #include namespace mitk { /**Documentation * \brief Right now, the US Probe is only a fancy name for a string. Later, it could handle probe specific parameters * like the current frequency etc. It is able to compare itself to other probes for device managment though. * * \ingroup US */ //Be sure to check the isEqualTo() method if you expand this class to see if it needs work! class MitkUS_EXPORT USProbe : public itk::Object { public: mitkClassMacro(USProbe,itk::Object); itkNewMacro(Self); /** * \brief Compares this probe to another probe and returns true if they are equal in terms of name AND NAME ONLY * be sure to sufficiently extend this method along with further capabilities probes. */ bool IsEqualToProbe(mitk::USProbe::Pointer probe); //## getter and setter ## itkGetMacro(Name, std::string); itkSetMacro(Name, std::string); protected: USProbe(); virtual ~USProbe(); std::string m_Name; }; } // namespace mitk -#endif \ No newline at end of file +#endif diff --git a/Modules/US/USFilters/mitkUSVideoDevice.h b/Modules/US/USFilters/mitkUSVideoDevice.h index a1b6f3c42c..3de4e71894 100644 --- a/Modules/US/USFilters/mitkUSVideoDevice.h +++ b/Modules/US/USFilters/mitkUSVideoDevice.h @@ -1,64 +1,64 @@ /*=================================================================== 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 MITKUSVideoDevice_H_HEADER_INCLUDED_ #define MITKUSVideoDevice_H_HEADER_INCLUDED_ #include #include #include "mitkUSDevice.h" #include #include "mitkUSImageVideoSource.h" namespace mitk { /**Documentation * \brief A VideoDevcie is the common class for video only devcies. They capture Video Input either from * a file or from a devcie, and transform the output into an mitkUSImage with attached Metadata. * This simple implementation does only capture and display 2D Images without cropping or registration. * One can simply inherit from this class and overwrite the handle2D and handle 3Dmethods to get full access to the data * \ingroup US */ class MitkUS_EXPORT USVideoDevice : public mitk::USDevice { public: mitkClassMacro(USVideoDevice, mitk::USDevice); // To open a devcie (DeviceID, Manufacturer, Model) mitkNewMacro3Param(Self, int, std::string, std::string); // To open A VideoFile (Path, Manufacturer, Model) mitkNewMacro3Param(Self, std::string, std::string, std::string); void GenerateData(); protected: /** * \brief Creates a new device that will deliver USImages taken from a video device. * under windows, try -1 for device number, which will grab the first available one * (Open CV functionality) */ USVideoDevice(int videoDeviceNumber, std::string manufacturer, std::string model); /** * \brief Creates a new device that will deliver USImages taken from a video file. */ USVideoDevice(std::string videoFilePath, std::string manufacturer, std::string model); virtual ~USVideoDevice(); mitk::USImageVideoSource::Pointer m_Source; }; } // namespace mitk -#endif \ No newline at end of file +#endif diff --git a/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/mitkBasicImageProcessingActivator.cpp b/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/mitkBasicImageProcessingActivator.cpp index 30cf9351f8..901a8b8735 100644 --- a/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/mitkBasicImageProcessingActivator.cpp +++ b/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/mitkBasicImageProcessingActivator.cpp @@ -1,35 +1,35 @@ /*=================================================================== 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 "mitkBasicImageProcessingActivator.h" #include "QmitkBasicImageProcessingView.h" #include namespace mitk { void BasicImageProcessingActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkBasicImageProcessing, context) } void BasicImageProcessingActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } -Q_EXPORT_PLUGIN2(org_mitk_gui_qt_basicimageprocessing, mitk::BasicImageProcessingActivator) \ No newline at end of file +Q_EXPORT_PLUGIN2(org_mitk_gui_qt_basicimageprocessing, mitk::BasicImageProcessingActivator) diff --git a/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/mitkBasicImageProcessingActivator.h b/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/mitkBasicImageProcessingActivator.h index a7112f3acd..812b85edff 100644 --- a/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/mitkBasicImageProcessingActivator.h +++ b/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/mitkBasicImageProcessingActivator.h @@ -1,39 +1,39 @@ /*=================================================================== 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 MITKBASICIMAGEPROCESSINGACTIVATOR_H #define MITKBASICIMAGEPROCESSINGACTIVATOR_H #include #include namespace mitk { class MITK_LOCAL BasicImageProcessingActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // basicImageProcessingActivator } -#endif // MITKBASICIMAGEPROCESSINGACTIVATOR_H \ No newline at end of file +#endif // MITKBASICIMAGEPROCESSINGACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.h b/Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.h index 59e74c6451..e0947dfa41 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.h @@ -1,66 +1,66 @@ /*=================================================================== 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 QMITKSINGLENODESELECTION_H_ #define QMITKSINGLENODESELECTION_H_ // Own includes #include "berryISelection.h" /// Qmitk #include //# forward declarations namespace mitk { class DataNode; } namespace berry { /// /// \struct SingleNodeSelection /// \brief Represents a selection object that encapsulates the selection of a single node. /// struct MITK_QT_DATAMANAGER SingleNodeSelection: public berry::ISelection { /// /// \brief Make typdefs for pointer types. /// berryObjectMacro(SingleNodeSelection); /// /// \brief Node setter. /// void SetNode(mitk::DataNode* _SelectedNode); /// /// \brief Node getter. /// mitk::DataNode* GetNode() const; /// /// \brief Checks if node is 0. /// virtual bool IsEmpty() const; protected: /// /// \brief Holds the node that is currently selected. /// mitk::DataNode* m_Node; }; } -#endif // QMITKSINGLENODESELECTION_H_ \ No newline at end of file +#endif // QMITKSINGLENODESELECTION_H_ diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.cpp index 219bd49c94..34f924c2c6 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.cpp @@ -1,44 +1,44 @@ /*=================================================================== 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 "QmitkDelKeyFilter.h" #include #include QmitkDelKeyFilter::QmitkDelKeyFilter( QObject* _DataManagerView ) : QObject(_DataManagerView) { } bool QmitkDelKeyFilter::eventFilter( QObject *obj, QEvent *event ) { if (event->type() == QEvent::KeyPress) { QmitkDataManagerView* _DataManagerView = qobject_cast(this->parent()); QKeyEvent *keyEvent = static_cast(event); if(keyEvent->key() == Qt::Key_Delete && _DataManagerView) { // trigger deletion of selected node(s) _DataManagerView->ActionRemoveTriggered(false); // return true: this means the delete key event is not send to the table return true; } } // standard event processing return QObject::eventFilter(obj, event); -} \ No newline at end of file +} diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.h b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.h index faa9b65fd7..f3010e5389 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.h +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDelKeyFilter.h @@ -1,35 +1,35 @@ /*=================================================================== 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 QMITKDELKEYFILTER_H_ #define QMITKDELKEYFILTER_H_ #include /// /// A small class which "eats" all Del-Key-pressed events on the node table. /// When the Del Key is pressed selected nodes should be removed. /// class QmitkDelKeyFilter : public QObject { Q_OBJECT public: QmitkDelKeyFilter(QObject* _DataManagerView = 0); protected: bool eventFilter(QObject *obj, QEvent *event); }; -#endif // QMITKDELKEYFILTER_H_ \ No newline at end of file +#endif // QMITKDELKEYFILTER_H_ diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkNetworkHistogramCanvas.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkNetworkHistogramCanvas.cpp index ebc822274e..602422ce16 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkNetworkHistogramCanvas.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Connectomics/QmitkNetworkHistogramCanvas.cpp @@ -1,98 +1,98 @@ /*=================================================================== 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 "QmitkNetworkHistogramCanvas.h" #include #include #include #include #include #include #include QmitkNetworkHistogramCanvas::QmitkNetworkHistogramCanvas(QWidget * parent, Qt::WindowFlags f) : QmitkPlotWidget(parent) { setEnabled(false); setFocusPolicy(Qt::ClickFocus); } QmitkNetworkHistogramCanvas::~QmitkNetworkHistogramCanvas() { } void QmitkNetworkHistogramCanvas::DrawProfiles( ) { this->Clear(); if( !(m_Histogram) || !( m_Histogram->IsValid() )) { return; } std::vector histogramVector = m_Histogram->GetHistogramVector(); // create a data vector which contains the points to be drawn // to create nice bars, the curve takes four points for each bar std::vector< std::pair< double, double > > dataPointsVector; std::pair< double, double > leftBottom, leftTop, rightTop, rightBottom; // how wide the bar is, the gap to the next one will be 1 - barWidth double barWidth( 0.95 ); const int range = histogramVector.size(); for(int i=0; i < range ; ++i) { leftBottom.first = ((double) i) ; leftBottom.second = 0.0; leftTop.first = ((double) i) ; leftTop.second = histogramVector.at( i ); rightTop.first = ((double) i) + barWidth ; rightTop.second = histogramVector.at( i ); rightBottom.first = ((double) i) + barWidth ; rightBottom.second = 0.0; dataPointsVector.push_back( leftBottom ); dataPointsVector.push_back( leftTop ); dataPointsVector.push_back( rightTop ); dataPointsVector.push_back( rightBottom ); } this->SetPlotTitle( (m_Histogram->GetSubject()).c_str() ); QPen pen( Qt::NoPen ); QBrush brush( Qt::SolidPattern ); brush.setColor( Qt::blue ); int curveId = this->InsertCurve( (m_Histogram->GetSubject()).c_str() ); this->SetCurveData( curveId, dataPointsVector ); this->SetCurvePen( curveId, pen ); this->SetCurveBrush( curveId, brush ); // Axis 0 is the y axis, axis to the x axis this->m_Plot->setAxisTitle(0, "n"); //this->m_Plot->setAxisTitle(2, ""); this->Replot(); -} \ No newline at end of file +} diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/deprecated/QmitkDiffusionTensorEstimation.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/deprecated/QmitkDiffusionTensorEstimation.cpp index 0f15fd1fce..49f7ece123 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/deprecated/QmitkDiffusionTensorEstimation.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/deprecated/QmitkDiffusionTensorEstimation.cpp @@ -1,2499 +1,2499 @@ /*=================================================================== 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 "itkTimeProbe.h" #include "QmitkDiffusionTensorEstimation.h" #include "QmitkDiffusionTensorEstimationControls.h" #include #include "QmitkDataTreeComboBox.h" #include "QmitkDataTreeListView.h" #include "QmitkStdMultiWidget.h" #include "QmitkDiffusionTensorIcon.h" #include #include "QmitkPropertyViewFactory.h" #include #include #include #include #include #include #include // properties #include "mitkStringProperty.h" #include "mitkProperties.h" #include "mitkMaterialProperty.h" #include "mitkLevelWindowProperty.h" #include "mitkVtkRepresentationProperty.h" #include "mitkVtkInterpolationProperty.h" #include "mitkVtkScalarModeProperty.h" #include "mitkLookupTableProperty.h" #include "mitkLookupTable.h" #include "mitkTransferFunctionProperty.h" #include "mitkGridRepresentationProperty.h" #include "mitkGridVolumeMapperProperty.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkVectorImageMapper2D.h" #include "mitkOdfVtkMapper2D.h" #include "itkOrientedImage.h" #include "itkVectorImage.h" #include "itkImageSeriesReader.h" #include "itkImageFileWriter.h" #include "itkExceptionObject.h" #include "itkDiffusionTensor3DReconstructionImageFilter.h" #include "itkDiffusionTensor3D.h" #include "itkTensorFractionalAnisotropyImageFilter.h" #include "itkTensorRelativeAnisotropyImageFilter.h" #include "itkGDCMSeriesFileNames.h" #include "itkImageRegionConstIterator.h" #include "itkRescaleIntensityImageFilter.h" #include "itkDiffusionQballReconstructionImageFilter.h" #include "itkAnalyticalDiffusionQballReconstructionImageFilter.h" #include "itkPointShell.h" #include "itkRGBPixel.h" #include "itkOrientationDistributionFunction.h" #include "itkDiffusionQballPrincipleDirectionsImageFilter.h" #include "itkDiffusionQballGeneralizedFaImageFilter.h" #include "itkShiftScaleImageFilter.h" #include "itkDiffusionQballPrepareVisualizationImageFilter.h" #include "itkDiffusionTensorPrincipleDirectionImageFilter.h" #include "itkDiffusionQballSphericalDeconvolutionImageFilter.h" #include "itkVectorImagesAngularErrorImageFilter.h" #include "mitkDicomDiffusionVolumeHeaderReader.h" #include "mitkGroupDiffusionHeadersFilter.h" #include "mitkDicomDiffusionVolumesReader.h" #include "mitkNrrdDiffusionVolumesWriter.h" #include "mitkNrrdDiffusionVolumesReader.h" #include "mitkDiffusionVolumes.h" #include "mitkDataTreeFilterFunctions.h" #include "mitkProgressBar.h" #include "mitkStatusBar.h" #include "mitkTeemDiffusionTensor3DReconstructionImageFilter.h" #include "mitkSurface.h" #include "mitkDataNodeFactory.h" #include "vtkPolyData.h" #include "vtkPoints.h" #include "vtkCellArray.h" #include "vtkDelaunay2D.h" #include "vtkCleanPolyData.h" #include "vtkAppendPolyData.h" #include "mitkImageCast.h" #include #include #include #define _USE_MATH_DEFINES #include #define DIFF_EST_PI M_PI typedef float TTensorPixelType; typedef itk::DiffusionTensor3D< TTensorPixelType > TensorPixelType; typedef itk::Image< TensorPixelType, 3 > TensorImageType; typedef itk::VectorImage< DiffusionPixelType, 3 > DiffusionImageType; //CAST_N_VEC(3) //CAST_N_VEC(42) //CAST_N_VEC(92) //CAST_N_VEC(162) //CAST_N_VEC(252) //CAST_N_VEC(362) //CAST_N_VEC(492) //CAST_N_VEC(642) //CAST_N_VEC(812) //CAST_N_VEC(1002) const int QmitkDiffusionTensorEstimation::odfsize = 252; const int QmitkDiffusionTensorEstimation::nrconvkernels = 252; // Compile-time Square Root Computation: ceil(sqrt(N)) template struct Root; template struct Root { static const int root = Mid; }; template struct Root { static const int mean = (Low + High)/2; static const bool down = (mean * mean >= Size); static const int root = Root::root; }; QmitkDiffusionTensorEstimation::QmitkDiffusionTensorEstimation(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it), m_MultiWidget(mitkStdMultiWidget), m_Controls(NULL) { SetAvailability(true); m_FilterInitialized = false; } QmitkDiffusionTensorEstimation::~QmitkDiffusionTensorEstimation() {} QWidget * QmitkDiffusionTensorEstimation::CreateMainWidget(QWidget *parent) { if ( m_MultiWidget == NULL ) { m_MultiWidget = new QmitkStdMultiWidget( parent ); } return m_MultiWidget; } QWidget * QmitkDiffusionTensorEstimation::CreateControlWidget(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new QmitkDiffusionTensorEstimationControls(parent); } m_Controls->m_TensorEstimationTeemErrorImage->setChecked(false); m_Controls->m_TensorEstimationTeemSigmaEdit->setText("NaN"); m_Controls->m_TensorEstimationTeemEstimationMethodCombo->insertItem("LLS (Linear Least Squares)"); m_Controls->m_TensorEstimationTeemEstimationMethodCombo->insertItem("MLE (Maximum Likelihood)"); m_Controls->m_TensorEstimationTeemEstimationMethodCombo->insertItem("NLS (Nonlinear Least Squares)"); m_Controls->m_TensorEstimationTeemEstimationMethodCombo->insertItem("WLS (Weighted Least Squares)"); m_Controls->m_TensorEstimationTeemNumItsSpin->setValue(1); m_Controls->m_TensorEstimationTeemConfThresholdEdit->setText("NaN"); m_Controls->m_TensorEstimationTeemFuzzyEdit->setText("0.0"); m_Controls->m_TensorEstimationTeemMinValEdit->setText("1.0"); m_Controls->m_QBallReconstructionThreasholdEdit->setText("0.0"); m_Controls->m_QBallStandardAlgorithmsOrderSpinbox->setValue(0); m_Controls->m_QBallStandardAlgorithmsProbThreshEdit->setText(QString::number(1.0/double(odfsize))); m_Controls->m_QBallReconstructionNumberThreadsSpinbox->setValue(4); m_Controls->m_QBallReconstructionMaxLLevelComboBox->insertItem( QString("2") ); m_Controls->m_QBallReconstructionMaxLLevelComboBox->insertItem( QString("4") ); m_Controls->m_QBallReconstructionMaxLLevelComboBox->insertItem( QString("6") ); m_Controls->m_QBallReconstructionMaxLLevelComboBox->insertItem( QString("8") ); m_Controls->m_QBallReconstructionMaxLLevelComboBox->setCurrentItem( 3 ); m_Controls->m_QBallReconstructionNumberThreadsAnalyticalSpinbox->setValue(4); m_Controls->m_QBallReconstructionThreasholdAnalyticalEdit->setText("0.0"); m_Controls->m_QBallReconstructionLambdaLineEdit->setText("0.006"); m_Controls->m_QBallStandardAlgorithmsNumberThreadsSpinbox->setValue(4); m_Controls->m_QBallStandardAlgorithmsDeconvNumberThreadsSpinbox->setValue(4); m_Controls->m_QBallStandardAlgorithmsDeconvolutionThreshEdit->setText("0.1"); m_Controls->m_QBallStandardAlgorithmsDeconvolutionAngResThresholdEdit->setText("15"); m_Controls->m_QBallStandardAlgorithmsGFAParam1->setText("2"); m_Controls->m_QBallStandardAlgorithmsGFAParam2->setText("1"); return m_Controls; } void QmitkDiffusionTensorEstimation::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_TensorEstimationButton), SIGNAL(clicked()),(QObject*) this, SLOT(TensorEstimationButton())); connect( (QObject*)(m_Controls->m_QBallReconstructionButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallReconstructionButton())); connect( (QObject*)(m_Controls->m_QBallReconstructionAnalyticalButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallReconstructionAnalyticalButton())); connect( (QObject*)(m_Controls->m_TensorEstimationTeemEstimateButton), SIGNAL(clicked()),(QObject*) this, SLOT(TensorEstimationTeemEstimateButton())); connect( (QObject*)(m_Controls->m_TensorVolumesSaveButton), SIGNAL(clicked()),(QObject*) this, SLOT(TensorVolumesSaveButton())); connect( (QObject*)(m_Controls->m_TensorVolumesLoadButton), SIGNAL(clicked()),(QObject*) this, SLOT(TensorVolumesLoadButton())); connect( (QObject*)(m_Controls->m_TensorVolumesRemoveButton), SIGNAL(clicked()),(QObject*) this, SLOT(TensorVolumesRemoveButton())); connect( (QObject*)(m_Controls->m_StandardAlgorithmsFAButton), SIGNAL(clicked()),(QObject*) this, SLOT(StandardAlgorithmsFAButton())); connect( (QObject*)(m_Controls->m_StandardAlgorithmsRAButton), SIGNAL(clicked()),(QObject*) this, SLOT(StandardAlgorithmsRAButton())); connect( (QObject*)(m_Controls->m_StandardAlgorithmsDirectionButton), SIGNAL(clicked()),(QObject*) this, SLOT(StandardAlgorithmsDirectionButton())); connect( (QObject*)(m_Controls->m_QBallVolumesSaveButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallVolumesSaveButton())); connect( (QObject*)(m_Controls->m_QBallVolumesLoadButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallVolumesLoadButton())); connect( (QObject*)(m_Controls->m_QBallVolumesRemoveButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallVolumesRemoveButton())); connect( (QObject*)(m_Controls->m_QBallStandardAlgorithmsDirectionButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallStandardAlgorithmsDirectionButton())); connect( (QObject*)(m_Controls->m_QBallStandardAlgorithmsDeconvolutionButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallStandardAlgorithmsDeconvolutionButton())); connect( (QObject*)(m_Controls->m_QBallStandardAlgorithmsGFAButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallStandardAlgorithmsGFAButton())); connect( (QObject*)(m_Controls->m_QBallVolumesVisualizeSelectedButton), SIGNAL(clicked()),(QObject*) this, SLOT(QBallVolumesVisualizeSelectedButton())); connect( (QObject*)(m_Controls->m_DirectionVolumesSaveButton), SIGNAL(clicked()),(QObject*) this, SLOT(DirectionVolumesSaveButton())); connect( (QObject*)(m_Controls->m_DirectionVolumesLoadButton), SIGNAL(clicked()),(QObject*) this, SLOT(DirectionVolumesLoadButton())); connect( (QObject*)(m_Controls->m_DirectionVolumesRemoveButton), SIGNAL(clicked()),(QObject*) this, SLOT(DirectionVolumesRemoveButton())); connect( (QObject*)(m_Controls->m_DirectionVolumesAngularErrorButton), SIGNAL(clicked()),(QObject*) this, SLOT(DirectionVolumesAngularErrorButton())); connect( (QObject*)(m_Controls->m_DiffusionVolumesLoadButton), SIGNAL(clicked()),(QObject*) this, SLOT(DiffusionVolumesLoadButton())); connect( (QObject*)(m_Controls->m_DiffusionVolumeSaveButton), SIGNAL(clicked()),(QObject*) this, SLOT(DiffusionVolumeSaveButton())); connect( (QObject*)(m_Controls->m_DiffusionVolumesRemoveButton), SIGNAL(clicked()),(QObject*) this, SLOT(DiffusionVolumesRemoveButton())); connect( (QObject*)(m_Controls->m_TensorEstimationDiffusionVolumesSelectAllButton), SIGNAL(clicked()),(QObject*) this, SLOT(DiffusionVolumesSelectAll())); } } QAction * QmitkDiffusionTensorEstimation::CreateAction(QActionGroup *parent) { //action = new QAction( tr( "Brain Atrophy" ), pixmap, tr( "BrainAtrophy" ), 0, parent, "BrainAtrophy" ); QImage icon = qembed_findImage("QmitkDiffusionTensorEstimation"); QPixmap pixmap(icon); QAction* action; action = new QAction( tr( "Diffusion Tensor Estimation" ), pixmap, tr( "QmitkDiffusionTensorEstimation menu" ), 0, parent, "QmitkDiffusionTensorEstimation" ); return action; } void QmitkDiffusionTensorEstimation::TreeChanged() { m_Controls->m_TensorEstimationDiffusionVolumesSelector->Update(); m_Controls->m_TensorVolumesSelector->Update(); m_Controls->m_QBallVolumesSelector->Update(); m_Controls->m_DirectionVolumesSelector->Update(); if(m_DiffusionVolumesDataTreeFilter &&m_DiffusionVolumesDataTreeFilter->GetItems()->Size() > 0) { m_Controls->m_TensorEstimationButton->setEnabled(true); m_Controls->m_QBallReconstructionButton->setEnabled(true); m_Controls->m_QBallReconstructionAnalyticalButton->setEnabled(true); } else { m_Controls->m_QBallReconstructionButton->setEnabled(false); m_Controls->m_QBallReconstructionAnalyticalButton->setEnabled(false); m_Controls->m_TensorEstimationButton->setEnabled(false); } if(m_TensorVolumesDataTreeFilter && m_TensorVolumesDataTreeFilter->GetItems()->Size() > 0) { m_Controls->m_TensorVolumesSaveButton->setEnabled(true); m_Controls->m_TensorVolumesRemoveButton->setEnabled(true); } else { m_Controls->m_TensorVolumesSaveButton->setEnabled(false); m_Controls->m_TensorVolumesRemoveButton->setEnabled(false); } if(m_QballVolumesDataTreeFilter && m_QballVolumesDataTreeFilter->GetItems()->Size() > 0) { m_Controls->m_QBallVolumesSaveButton->setEnabled(true); m_Controls->m_QBallVolumesRemoveButton->setEnabled(true); m_Controls->m_QBallVolumesVisualizeSelectedButton->setEnabled(true); } else { m_Controls->m_QBallVolumesSaveButton->setEnabled(false); m_Controls->m_QBallVolumesRemoveButton->setEnabled(false); m_Controls->m_QBallVolumesVisualizeSelectedButton->setEnabled(false); } if(m_DirectionVolumesDataTreeFilter && m_DirectionVolumesDataTreeFilter->GetItems()->Size() > 0) { m_Controls->m_DirectionVolumesSaveButton->setEnabled(true); m_Controls->m_DirectionVolumesRemoveButton->setEnabled(true); } else { m_Controls->m_DirectionVolumesSaveButton->setEnabled(false); m_Controls->m_DirectionVolumesRemoveButton->setEnabled(false); } if(m_DirectionVolumesDataTreeFilter && m_DirectionVolumesDataTreeFilter->GetItems()->Size() > 1) { m_Controls->m_DirectionVolumesAngularErrorButton->setEnabled(true); } else { m_Controls->m_DirectionVolumesAngularErrorButton->setEnabled(false); } } void QmitkDiffusionTensorEstimation::Activated() { QmitkFunctionality::Activated(); if (m_FilterInitialized) return; // diffusion volumes filter m_DiffusionVolumesDataTreeFilter = mitk::DataTreeFilter::New( GetDataTreeIterator()->GetTree() ); m_DiffusionVolumesDataTreeFilter->SetSelectionMode(mitk::DataTreeFilter::MULTI_SELECT); m_DiffusionVolumesDataTreeFilter->SetHierarchyHandling(mitk::DataTreeFilter::FLATTEN_HIERARCHY); m_DiffusionVolumesDataTreeFilter->SetFilter( mitk::IsBaseDataType >() ); // show diffusion volumes mitk::DataTreeFilter::PropertyList visible_props; visible_props.push_back("name"); m_DiffusionVolumesDataTreeFilter->SetVisibleProperties(visible_props); mitk::DataTreeFilter::PropertyList property_labels; property_labels.push_back("Diffusion Volumes"); m_DiffusionVolumesDataTreeFilter->SetPropertiesLabels(property_labels); m_Controls->m_TensorEstimationDiffusionVolumesSelector->SetDataTree( GetDataTreeIterator()->GetTree() ); m_Controls->m_TensorEstimationDiffusionVolumesSelector->SetFilter( m_DiffusionVolumesDataTreeFilter ); m_Controls->m_TensorEstimationDiffusionVolumesSelector->SetAutoUpdate( false ); m_Controls->m_TensorEstimationDiffusionVolumesSelector->setStretchedColumn(1); // tensor volumes filter m_TensorVolumesDataTreeFilter = mitk::DataTreeFilter::New( GetDataTreeIterator()->GetTree() ); m_TensorVolumesDataTreeFilter->SetSelectionMode(mitk::DataTreeFilter::SINGLE_SELECT); m_TensorVolumesDataTreeFilter->SetHierarchyHandling(mitk::DataTreeFilter::FLATTEN_HIERARCHY); m_TensorVolumesDataTreeFilter->SetFilter( mitk::IsBaseDataTypeWithBoolProperty("IsTensorVolume") ); // show tensor volumes m_TensorVolumesDataTreeFilter->SetVisibleProperties(visible_props); mitk::DataTreeFilter::PropertyList tensor_property_labels; tensor_property_labels.push_back("Tensor Volumes"); m_TensorVolumesDataTreeFilter->SetPropertiesLabels(tensor_property_labels); m_Controls->m_TensorVolumesSelector->SetDataTree( GetDataTreeIterator()->GetTree() ); m_Controls->m_TensorVolumesSelector->SetFilter( m_TensorVolumesDataTreeFilter ); m_Controls->m_TensorVolumesSelector->SetAutoUpdate( false ); m_Controls->m_TensorVolumesSelector->setStretchedColumn(1); // qBall volumes filter m_QballVolumesDataTreeFilter = mitk::DataTreeFilter::New( GetDataTreeIterator()->GetTree() ); m_QballVolumesDataTreeFilter->SetSelectionMode(mitk::DataTreeFilter::MULTI_SELECT); m_QballVolumesDataTreeFilter->SetHierarchyHandling(mitk::DataTreeFilter::FLATTEN_HIERARCHY); m_QballVolumesDataTreeFilter->SetFilter( mitk::IsBaseDataTypeWithBoolProperty("IsQBallVolume") ); m_QballVolumesDataTreeFilter->SetVisibleProperties(visible_props); mitk::DataTreeFilter::PropertyList qball_property_labels; qball_property_labels.push_back("Q-Ball Volumes"); m_QballVolumesDataTreeFilter->SetPropertiesLabels(qball_property_labels); m_Controls->m_QBallVolumesSelector->SetDataTree( GetDataTreeIterator()->GetTree() ); m_Controls->m_QBallVolumesSelector->SetFilter( m_QballVolumesDataTreeFilter ); m_Controls->m_QBallVolumesSelector->SetAutoUpdate( false ); m_Controls->m_QBallVolumesSelector->setStretchedColumn(1); // direction volumes filter m_DirectionVolumesDataTreeFilter = mitk::DataTreeFilter::New( GetDataTreeIterator()->GetTree() ); m_DirectionVolumesDataTreeFilter->SetSelectionMode(mitk::DataTreeFilter::MULTI_SELECT); m_DirectionVolumesDataTreeFilter->SetHierarchyHandling(mitk::DataTreeFilter::FLATTEN_HIERARCHY); m_DirectionVolumesDataTreeFilter->SetFilter( mitk::IsBaseDataTypeWithBoolProperty("IsDirectionVolume") ); m_DirectionVolumesDataTreeFilter->SetVisibleProperties(visible_props); mitk::DataTreeFilter::PropertyList direction_property_labels; direction_property_labels.push_back("Direction Volumes"); m_DirectionVolumesDataTreeFilter->SetPropertiesLabels(direction_property_labels); m_Controls->m_DirectionVolumesSelector->SetDataTree( GetDataTreeIterator()->GetTree() ); m_Controls->m_DirectionVolumesSelector->SetFilter( m_DirectionVolumesDataTreeFilter ); m_Controls->m_DirectionVolumesSelector->SetAutoUpdate( false ); m_Controls->m_DirectionVolumesSelector->setStretchedColumn(1); m_FilterInitialized = true; TreeChanged(); } void QmitkDiffusionTensorEstimation::TensorVolumesSaveButton() { // GET SELECTED ITEM const mitk::DataTreeFilter::Item* selectedItem = m_TensorVolumesDataTreeFilter->GetSelectedItem(); if( !selectedItem ) return; mitk::Image::Pointer tensorVol = static_cast(selectedItem->GetNode()->GetData()); TensorImageType::Pointer itkTensorVol = TensorImageType::New(); mitk::CastToItkImage(tensorVol, itkTensorVol); // SELECT FILE DIALOG std::string sName = selectedItem->GetNode()->GetName(); QString qName; qName.sprintf("%s.nhdr",sName.c_str()); QString filename = QFileDialog::getSaveFileName( qName, "Nrrd Images (*.nrrd *.nhdr)", this->m_Controls, "save file dialog", "Select Nrrd Outputfile" ); if ( !filename ) return; // WRITING TENSORS TO FILE MBI_INFO << "Writing tensors "; typedef itk::ImageFileWriter TensorWriterType; TensorWriterType::Pointer tensorWriter = TensorWriterType::New(); tensorWriter->SetFileName(filename.ascii()); tensorWriter->SetInput(itkTensorVol); tensorWriter->Update(); } void QmitkDiffusionTensorEstimation::TensorVolumesLoadButton() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( this->m_Controls, "Select DWI data file", TRUE ); w->setMode( QFileDialog::ExistingFiles ); w->setFilter( "Nrrd Images (*.nrrd *.nhdr)" ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; QStringList filenames = w->selectedFiles(); QStringList::Iterator it = filenames.begin(); while( it != filenames.end() ) { std::string filename = ( *it ).ascii(); ++it; // READING TENSOR VOLUME typedef itk::ImageFileReader ReaderType; ReaderType::Pointer tensorReader = ReaderType::New(); tensorReader->SetFileName(filename); try { tensorReader->Update(); } catch (itk::ExceptionObject e) { std::cout << e << std::endl; } // Tensorvolume mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( tensorReader->GetOutput() ); image->SetVolume( tensorReader->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, itksys::SystemTools::GetFilenameName(filename)); node->SetProperty( "IsTensorVolume", mitk::BoolProperty::New( true ) ); TreeChanged(); } } void QmitkDiffusionTensorEstimation::TensorVolumesRemoveButton() { m_TensorVolumesDataTreeFilter->DeleteSelectedItems(); } void QmitkDiffusionTensorEstimation::QBallVolumesSaveButton() { // GET SELECTED ITEM const mitk::DataTreeFilter::Item* selectedItem = m_QballVolumesDataTreeFilter->GetSelectedItem(); if( !selectedItem ) return; mitk::Image::Pointer qBallVol = static_cast(selectedItem->GetNode()->GetData()); if( !qBallVol)return; typedef itk::Image,3 > IType; IType::Pointer itkQBallVol = IType::New(); mitk::CastToItkImage(qBallVol, itkQBallVol); typedef itk::VectorImage VarVecImgType; VarVecImgType::Pointer vecImg = VarVecImgType::New(); vecImg->SetSpacing( itkQBallVol->GetSpacing() ); // Set the image spacing vecImg->SetOrigin( itkQBallVol->GetOrigin() ); // Set the image origin vecImg->SetDirection( itkQBallVol->GetDirection() ); // Set the image direction vecImg->SetLargestPossibleRegion( itkQBallVol->GetLargestPossibleRegion()); vecImg->SetBufferedRegion( itkQBallVol->GetLargestPossibleRegion() ); vecImg->SetVectorLength(odfsize); vecImg->Allocate(); itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); ot = ot.Begin(); itk::ImageRegionIterator it (itkQBallVol, itkQBallVol->GetLargestPossibleRegion() ); it = it.Begin(); MBI_DEBUG << it.Get(); for (it = it.Begin(); !it.IsAtEnd(); ++it) { itk::Vector vec = it.Get(); VarVecImgType::PixelType varvec(vec.GetDataPointer(), odfsize); ot.Set(varvec); ++ot; } // SELECT FILE DIALOG std::string sName = selectedItem->GetNode()->GetName(); QString qName; qName.sprintf("%s.nhdr",sName.c_str()); QString filename = QFileDialog::getSaveFileName( qName, "Nrrd Images (*.nrrd *.nhdr)", this->m_Controls, "save file dialog", "Select Nrrd Outputfile" ); if ( !filename ) return; // WRITING TENSORS TO FILE MBI_INFO << "Writing data "; typedef itk::ImageFileWriter QBallWriterType; QBallWriterType::Pointer qballWriter = QBallWriterType::New(); qballWriter->SetFileName(filename.ascii()); qballWriter->SetInput(vecImg); qballWriter->Update(); } void QmitkDiffusionTensorEstimation::QBallVolumesLoadButton() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( this->m_Controls, "Select DWI data file", TRUE ); w->setMode( QFileDialog::ExistingFiles ); w->setFilter( "Nrrd Images (*.nrrd *.nhdr)" ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; QStringList filenames = w->selectedFiles(); QStringList::Iterator it = filenames.begin(); while( it != filenames.end() ) { std::string filename = ( *it ).ascii(); ++it; // READING TENSOR VOLUME typedef itk::Image,3 > IVType; typedef itk::ImageFileReader ReaderType; ReaderType::Pointer qballReader = ReaderType::New(); qballReader->SetFileName(filename); try { qballReader->Update(); } catch (itk::ExceptionObject e) { MBI_LOG << e; } //itk::ImageRegionConstIterator it (qballReader->GetOutput(), qballReader->GetOutput()->GetLargestPossibleRegion() ); //it = it.Begin(); //std::cout << it.Get() << std::endl; // Tensorvolume mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( qballReader->GetOutput() ); image->SetVolume( qballReader->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, itksys::SystemTools::GetFilenameName(filename)); node->SetProperty( "IsQBallVolume", mitk::BoolProperty::New( true ) ); node->SetProperty( "visible", mitk::BoolProperty::New( false ) ); TreeChanged(); } } void QmitkDiffusionTensorEstimation::QBallVolumesRemoveButton() { m_QballVolumesDataTreeFilter->DeleteSelectedItems(); } void QmitkDiffusionTensorEstimation::QBallVolumesVisualizeSelectedButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::Item* item = m_QballVolumesDataTreeFilter->GetSelectedItem(); if(!item)return; typedef itk::Vector OdfVectorType; typedef itk::Image OdfVectorImgType; mitk::Image* vol = static_cast(item->GetNode()->GetData()); OdfVectorImgType::Pointer itkvol = OdfVectorImgType::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = item->GetProperty("name"); // PREPARE FOR VISUALIZATION clock.Start(); MBI_INFO << "Preparing for Visualization "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Preparing for Visualization of %s", nodename.c_str())); typedef itk::DiffusionQballPrepareVisualizationImageFilter FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(itkvol); filter->SetNumberOfThreads(4); switch(m_Controls->m_QBallVolumesVisualizeNormalizationMethod->currentItem()) { case 0: { filter->SetNormalizationMethod(FilterType::PV_MIN_MAX); break; } case 1: { filter->SetNormalizationMethod(FilterType::PV_NONE); break; } case 2: { filter->SetNormalizationMethod(FilterType::PV_MAX); break; } case 3: { filter->SetNormalizationMethod(FilterType::PV_GLOBAL_MAX); break; } case 4: { filter->SetNormalizationMethod(FilterType::PV_MIN_MAX_INVERT); break; } default: { filter->SetNormalizationMethod(FilterType::PV_MIN_MAX); break; } } if(m_Controls->m_QBallVolumesVisualizeScaleGfaCheckbox->isChecked() ) { typedef itk::DiffusionQballGeneralizedFaImageFilter GfaFilterType; filter->SetDoScaleGfa(true); float p1 = m_Controls->m_QBallStandardAlgorithmsGFAParam1->text().toFloat(); float p2 = m_Controls->m_QBallStandardAlgorithmsGFAParam2->text().toFloat(); switch(m_Controls->m_QBallStandardAlgorithmsGFAMethod->currentItem()) { case 0: filter->SetScaleByGfaType(GfaFilterType::GFA_STANDARD); break; case 1: filter->SetScaleByGfaType(GfaFilterType::GFA_QUANTILES_HIGH_LOW); break; case 2: filter->SetScaleByGfaType(GfaFilterType::GFA_QUANTILE_HIGH); break; case 3: filter->SetScaleByGfaType(GfaFilterType::GFA_MAX_ODF_VALUE); break; case 4: filter->SetScaleByGfaType(GfaFilterType::GFA_DECONVOLUTION_COEFFS); break; case 5: filter->SetScaleByGfaType(GfaFilterType::GFA_MIN_MAX_NORMALIZED_STANDARD); break; case 6: filter->SetScaleByGfaType(GfaFilterType::GFA_NORMALIZED_ENTROPY); break; case 7: filter->SetScaleByGfaType(GfaFilterType::GFA_NEMATIC_ORDER_PARAMETER); break; case 8: filter->SetScaleByGfaType(GfaFilterType::GFA_QUANTILES_LOW_HIGH); break; case 9: filter->SetScaleByGfaType(GfaFilterType::GFA_QUANTILE_LOW); break; case 10: filter->SetScaleByGfaType(GfaFilterType::GFA_MIN_ODF_VALUE); break; case 11: filter->SetScaleByGfaType(GfaFilterType::GFA_STD_BY_MAX); break; case 12: filter->SetScaleByGfaType(GfaFilterType::GFA_PRINCIPLE_CURVATURE); filter->SetGfaParam1(p1); break; case 13: filter->SetScaleByGfaType(GfaFilterType::GFA_GENERALIZED_GFA); filter->SetGfaParam1(p1); filter->SetGfaParam2(p2); break; default: filter->SetScaleByGfaType(GfaFilterType::GFA_STANDARD); } } filter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; // VIZ TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( filter->GetOutput() ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, nodename.append(" Viz")); node->SetProperty( "IsQBallVolume", mitk::BoolProperty::New( true ) ); node->SetProperty( "ShowMaxNumber", mitk::IntProperty::New( 1500 ) ); node->SetProperty( "DoRefresh", mitk::BoolProperty::New( true ) ); node->SetProperty( "layer", mitk::IntProperty::New( 1 ) ); node->SetProperty( "global_scaling", mitk::FloatProperty::New( 1.0 ) ); mitk::OdfVtkMapper2D::Pointer odfMapper = mitk::OdfVtkMapper2D::New(); node->SetMapper(1,odfMapper); mitk::StatusBar::GetInstance()->DisplayText("Computation complete."); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::DirectionVolumesSaveButton() { // GET SELECTED ITEM const mitk::DataTreeFilter::Item* selectedItem = m_DirectionVolumesDataTreeFilter->GetSelectedItem(); if( !selectedItem ) return; mitk::Image::Pointer vol = static_cast(selectedItem->GetNode()->GetData()); if( !vol)return; typedef itk::Image,3 > IType; IType::Pointer itkVol = IType::New(); mitk::CastToItkImage(vol, itkVol); typedef itk::VectorImage VarVecImgType; VarVecImgType::Pointer vecImg = VarVecImgType::New(); vecImg->SetSpacing( itkVol->GetSpacing() ); // Set the image spacing vecImg->SetOrigin( itkVol->GetOrigin() ); // Set the image origin vecImg->SetDirection( itkVol->GetDirection() ); // Set the image direction vecImg->SetLargestPossibleRegion( itkVol->GetLargestPossibleRegion()); vecImg->SetBufferedRegion( itkVol->GetLargestPossibleRegion() ); vecImg->SetVectorLength(3); vecImg->Allocate(); itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); ot = ot.Begin(); itk::ImageRegionIterator it (itkVol, itkVol->GetLargestPossibleRegion() ); it = it.Begin(); for (it = it.Begin(); !it.IsAtEnd(); ++it) { itk::Vector vec = it.Get(); VarVecImgType::PixelType varvec(vec.GetDataPointer(), 3); ot.Set(varvec); ++ot; } // SELECT FILE DIALOG std::string sName = selectedItem->GetNode()->GetName(); QString qName; qName.sprintf("%s.nhdr",sName.c_str()); QString filename = QFileDialog::getSaveFileName( qName, "Nrrd Images (*.nrrd *.nhdr)", this->m_Controls, "save file dialog", "Select Nrrd Outputfile" ); if ( !filename ) return; // WRITING TENSORS TO FILE MBI_INFO << "Writing data "; typedef itk::ImageFileWriter WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(filename.ascii()); writer->SetInput(vecImg); writer->Update(); } void QmitkDiffusionTensorEstimation::DirectionVolumesLoadButton() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( this->m_Controls, "Select DWI data file", TRUE ); w->setMode( QFileDialog::ExistingFiles ); w->setFilter( "Nrrd Images (*.nrrd *.nhdr)" ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; QStringList filenames = w->selectedFiles(); QStringList::Iterator it = filenames.begin(); while( it != filenames.end() ) { std::string filename = ( *it ).ascii(); ++it; // READING VOLUME typedef itk::Image,3 > IType; typedef itk::ImageFileReader ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(filename); try { reader->Update(); } catch (itk::ExceptionObject e) { MBI_INFO << e << std::endl; } // Tensorvolume mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( reader->GetOutput() ); image->SetVolume( reader->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, itksys::SystemTools::GetFilenameName(filename)); node->SetProperty( "IsDirectionVolume", mitk::BoolProperty::New( true ) ); mitk::VectorImageMapper2D::Pointer mapper = mitk::VectorImageMapper2D::New(); node->SetMapper(1,mapper); TreeChanged(); } } void QmitkDiffusionTensorEstimation::DirectionVolumesRemoveButton() { m_DirectionVolumesDataTreeFilter->DeleteSelectedItems(); } void QmitkDiffusionTensorEstimation::TensorEstimationTeemEstimateButton() { try { itk::TimeProbe clock; const mitk::DataTreeFilter::ItemSet* selectedItems = m_DiffusionVolumesDataTreeFilter->GetSelectedItems(); int nrFiles = selectedItems->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataTreeFilter::ItemSet::const_iterator itemiter( selectedItems->begin() ); mitk::DataTreeFilter::ItemSet::const_iterator itemiterend( selectedItems->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { mitk::DiffusionVolumes* vols = static_cast*>( (*itemiter)->GetNode()->GetData()); std::string nodename = (*itemiter)->GetProperty("name"); itemiter++; // TENSOR RECONSTRUCTION clock.Start(); MBI_INFO << "Teem Tensor reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Teem Tensor reconstruction for %s", nodename.c_str())); typedef mitk::TeemDiffusionTensor3DReconstructionImageFilter< DiffusionPixelType, TTensorPixelType > TensorReconstructionImageFilterType; TensorReconstructionImageFilterType::Pointer tensorReconstructionFilter = TensorReconstructionImageFilterType::New(); tensorReconstructionFilter->SetInput( vols ); tensorReconstructionFilter->SetEstimateErrorImage( m_Controls->m_TensorEstimationTeemErrorImage->isChecked() ); if(!m_Controls->m_TensorEstimationTeemSigmaEdit->text().contains(QString("NaN"))) tensorReconstructionFilter->SetSigma( m_Controls->m_TensorEstimationTeemSigmaEdit->text().toFloat() ); switch(m_Controls->m_TensorEstimationTeemEstimationMethodCombo->currentItem()) { case 0: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsLLS); break; case 1: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsNLS); break; case 2: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsWLS); break; case 3: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsMLE); break; default: tensorReconstructionFilter->SetEstimationMethod(mitk::TeemTensorEstimationMethodsLLS); } tensorReconstructionFilter->SetNumIterations( m_Controls->m_TensorEstimationTeemNumItsSpin->value() ); if(!m_Controls->m_TensorEstimationTeemConfThresholdEdit->text().contains(QString("NaN"))) tensorReconstructionFilter->SetConfidenceThreshold( m_Controls->m_TensorEstimationTeemConfThresholdEdit->text().toDouble() ); tensorReconstructionFilter->SetConfidenceFuzzyness( m_Controls->m_TensorEstimationTeemFuzzyEdit->text().toFloat() ); tensorReconstructionFilter->SetMinPlausibleValue( m_Controls->m_TensorEstimationTeemMinValEdit->text().toDouble() ); tensorReconstructionFilter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; // TENSORS TO DATATREE //mitk::DataNode::Pointer node=mitk::DataNode::New(); //node->SetData( tensorReconstructionFilter->GetOutput() ); //mitk::DataStorage::GetInstance()->Add(node); //SetDefaultNodeProperties(node, nodename.append(" tensors")); //node->SetProperty( "IsConfidenceTensorVolume", mitk::BoolProperty::New( true ) ); mitk::DataNode::Pointer node2=mitk::DataNode::New(); node2->SetData( tensorReconstructionFilter->GetOutputItk() ); SetDefaultNodeProperties(node2, nodename.append(" (itk)")); node2->SetProperty( "IsTensorVolume", mitk::BoolProperty::New( true ) ); nodes.push_back(node2); mitk::ProgressBar::GetInstance()->Progress(); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) mitk::DataStorage::GetInstance()->Add(*nodeIt); mitk::ProgressBar::GetInstance()->Progress(); TreeChanged(); m_Controls->update(); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles)); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex; return ; } } void QmitkDiffusionTensorEstimation::TensorEstimationButton() { try { itk::TimeProbe clock; const mitk::DataTreeFilter::ItemSet* selectedItems = m_DiffusionVolumesDataTreeFilter->GetSelectedItems(); int nrFiles = selectedItems->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataTreeFilter::ItemSet::const_iterator itemiter( selectedItems->begin() ); mitk::DataTreeFilter::ItemSet::const_iterator itemiterend( selectedItems->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { mitk::DiffusionVolumes* vols = static_cast*>( (*itemiter)->GetNode()->GetData()); std::string nodename = (*itemiter)->GetProperty("name"); itemiter++; // TENSOR RECONSTRUCTION clock.Start(); MBI_INFO << "Tensor reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Tensor reconstruction for %s", nodename.c_str())); typedef itk::DiffusionTensor3DReconstructionImageFilter< DiffusionPixelType, DiffusionPixelType, TTensorPixelType > TensorReconstructionImageFilterType; TensorReconstructionImageFilterType::Pointer tensorReconstructionFilter = TensorReconstructionImageFilterType::New(); tensorReconstructionFilter->SetGradientImage( vols->GetDirections(), vols->GetImage() ); tensorReconstructionFilter->SetNumberOfThreads( m_Controls->m_TensorEstimationNumberThreadsSpinbox->value() ); tensorReconstructionFilter->SetBValue(vols->GetB_Value()); tensorReconstructionFilter->SetThreshold( m_Controls->m_TensorEstimationThreasholdEdit->text().toFloat() ); tensorReconstructionFilter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; // TENSORS TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( tensorReconstructionFilter->GetOutput() ); image->SetVolume( tensorReconstructionFilter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); SetDefaultNodeProperties(node, nodename.append(" tensors")); node->SetProperty( "IsTensorVolume", mitk::BoolProperty::New( true ) ); nodes.push_back(node); mitk::ProgressBar::GetInstance()->Progress(); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) mitk::DataStorage::GetInstance()->Add(*nodeIt); mitk::ProgressBar::GetInstance()->Progress(); TreeChanged(); m_Controls->update(); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles)); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex; return ; } } void QmitkDiffusionTensorEstimation::QBallReconstructionButton() { try { itk::TimeProbe clock; const mitk::DataTreeFilter::ItemSet* selectedItems = m_DiffusionVolumesDataTreeFilter->GetSelectedItems(); int nrFiles = selectedItems->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataTreeFilter::ItemSet::const_iterator itemiter( selectedItems->begin() ); mitk::DataTreeFilter::ItemSet::const_iterator itemiterend( selectedItems->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { mitk::DiffusionVolumes* vols = static_cast*>( (*itemiter)->GetNode()->GetData()); std::string nodename = (*itemiter)->GetProperty("name"); ++itemiter; // QBALL RECONSTRUCTION clock.Start(); MBI_INFO << "QBall reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "QBall reconstruction for %s", nodename.c_str())); typedef itk::DiffusionQballReconstructionImageFilter< DiffusionPixelType, DiffusionPixelType, TTensorPixelType, odfsize> //int NOdfDirections = 162, QballReconstructionImageFilterType; QballReconstructionImageFilterType::Pointer filter = QballReconstructionImageFilterType::New(); filter->SetGradientImage( vols->GetDirections(), vols->GetImage() ); filter->SetNumberOfThreads( m_Controls->m_QBallReconstructionNumberThreadsSpinbox->value() ); filter->SetBValue(vols->GetB_Value()); filter->SetThreshold( m_Controls->m_QBallReconstructionThreasholdEdit->text().toFloat() ); int normalization = m_Controls->m_QBallReconstructionPostprocessingMethod->currentItem(); switch(normalization) { case 0: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_STANDARD); break; } case 1: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_B_ZERO_B_VALUE); break; } case 2: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_B_ZERO); break; } case 3: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_NONE); break; } default: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_STANDARD); } } filter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s." << std::endl; // ODFs TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( filter->GetOutput() ); //image->SetImportVolume( filter->GetOutput()->GetBufferPointer(), 0, 0, mitk::Image::ImportMemoryManagementType::ManageMemory ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); QString newname; newname = newname.append(nodename.c_str()); newname = newname.append("_QN%1").arg(normalization); SetDefaultNodeProperties(node, newname.ascii()); node->SetProperty( "IsQBallVolume", mitk::BoolProperty::New( true ) ); nodes.push_back(node); // B-Zero TO DATATREE mitk::Image::Pointer image4 = mitk::Image::New(); image4->InitializeByItk( filter->GetBZeroImage().GetPointer() ); image4->SetVolume( filter->GetBZeroImage()->GetBufferPointer() ); mitk::DataNode::Pointer node4=mitk::DataNode::New(); node4->SetData( image4 ); SetDefaultNodeProperties(node4, nodename.append("B0")); nodes.push_back(node4); mitk::ProgressBar::GetInstance()->Progress(); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) mitk::DataStorage::GetInstance()->Add(*nodeIt); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles)); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex; return ; } } template void QmitkDiffusionTensorEstimation::ReconstructAnalytically( mitk::DiffusionVolumes* vols, float lambda, std::string nodename, std::vector* nodes) { typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetGradientImage( vols->GetDirections(), vols->GetImage() ); filter->SetNumberOfThreads( m_Controls->m_QBallReconstructionNumberThreadsAnalyticalSpinbox->value() ); filter->SetBValue(vols->GetB_Value()); filter->SetThreshold( m_Controls->m_QBallReconstructionThreasholdAnalyticalEdit->text().toFloat() ); filter->SetLambda(lambda); filter->SetAdcProfileOnly(m_Controls->m_QBallReconstructionAdcOnlyCheckbox->isChecked()); int normalization = m_Controls->m_QBallReconstructionPostprocessingMethodAnalytical->currentItem(); switch(normalization) { case 0: { filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); break; } case 1: { filter->SetNormalizationMethod(FilterType::QBAR_B_ZERO_B_VALUE); break; } case 2: { filter->SetNormalizationMethod(FilterType::QBAR_B_ZERO); break; } case 3: { filter->SetNormalizationMethod(FilterType::QBAR_NONE); break; } default: { filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); } } filter->Update(); // ODFs TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( filter->GetOutput() ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); nodes->push_back(node); QString newname; newname = newname.append(nodename.c_str()); newname = newname.append("_QA%1").arg(normalization); SetDefaultNodeProperties(node, newname.ascii()); node->SetProperty( "IsQBallVolume", mitk::BoolProperty::New( true ) ); // B-Zero TO DATATREE mitk::Image::Pointer image4 = mitk::Image::New(); image4->InitializeByItk( filter->GetBZeroImage().GetPointer() ); image4->SetVolume( filter->GetBZeroImage()->GetBufferPointer() ); mitk::DataNode::Pointer node4=mitk::DataNode::New(); node4->SetData( image4 ); nodes->push_back(node4); SetDefaultNodeProperties(node4, nodename.append("B0")); } void QmitkDiffusionTensorEstimation::QBallReconstructionAnalyticalButton() { try { itk::TimeProbe clock; const mitk::DataTreeFilter::ItemSet* selectedItems = m_DiffusionVolumesDataTreeFilter->GetSelectedItems(); int nrFiles = selectedItems->size(); if (!nrFiles) return; std::vector lambdas; float minLambda = m_Controls->m_QBallReconstructionLambdaLineEdit->text().toFloat(); if(m_Controls->m_QBallReconstructionLambdaMultiCheckbox->isChecked()) { float stepLambda = m_Controls->m_QBallReconstructionLambdaStepLineEdit->text().toFloat(); float maxLambda = m_Controls->m_QBallReconstructionLambdaMaxLineEdit->text().toFloat(); for(float l=minLambda; lAddStepsToDo(nrFiles*nLambdas); mitk::DataTreeFilter::ItemSet::const_iterator itemiter( selectedItems->begin() ); mitk::DataTreeFilter::ItemSet::const_iterator itemiterend( selectedItems->end() ); std::vector* nodes = new std::vector(); while ( itemiter != itemiterend ) // for all items { mitk::DiffusionVolumes* vols = static_cast*>( (*itemiter)->GetNode()->GetData()); std::string nodename = (*itemiter)->GetProperty("name"); itemiter++; // QBALL RECONSTRUCTION clock.Start(); MBI_INFO << "QBall reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "QBall reconstruction for %s", nodename.c_str())); for(int i=0; im_QBallReconstructionMaxLLevelComboBox->currentItem()) { case 0: { ReconstructAnalytically<2>(vols, currentLambda, nodename, nodes); break; } case 1: { ReconstructAnalytically<4>(vols, currentLambda, nodename, nodes); break; } case 2: { ReconstructAnalytically<6>(vols, currentLambda, nodename, nodes); break; } case 3: { ReconstructAnalytically<8>(vols, currentLambda, nodename, nodes); break; } } clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; mitk::ProgressBar::GetInstance()->Progress(); } } std::vector::iterator nodeIt; for(nodeIt = nodes->begin(); nodeIt != nodes->end(); ++nodeIt) mitk::DataStorage::GetInstance()->Add(*nodeIt); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles)); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex; return ; } } void QmitkDiffusionTensorEstimation::StandardAlgorithmsFAButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::Item* item = m_TensorVolumesDataTreeFilter->GetSelectedItem(); if(!item)return; mitk::Image* vol = static_cast(item->GetNode()->GetData()); itk::Image::Pointer itkvol = itk::Image::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = item->GetProperty("name"); // COMPUTE FA clock.Start(); MBI_INFO << "Computing FA "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing FA for %s", nodename.c_str())); typedef TensorPixelType::RealValueType RealValueType; typedef itk::Image< RealValueType, 3 > FAImageType; typedef itk::TensorFractionalAnisotropyImageFilter< TensorImageType, FAImageType > FAFilterType; FAFilterType::Pointer fractionalAnisotropyFilter = FAFilterType::New(); fractionalAnisotropyFilter->SetInput( itkvol ); typedef itk::ShiftScaleImageFilter ShiftScaleFilterType; ShiftScaleFilterType::Pointer multi = ShiftScaleFilterType::New(); multi->SetShift(0); multi->SetScale(200);//itk::NumericTraits::max() multi->SetInput(fractionalAnisotropyFilter->GetOutput()); multi->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; // FA TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( multi->GetOutput() ); image->SetVolume( multi->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, nodename.append(" FA")); node->SetProperty( "IsFAVolume", mitk::BoolProperty::New( true ) ); mitk::StatusBar::GetInstance()->DisplayText("Computation complete."); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::StandardAlgorithmsRAButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::Item* item = m_TensorVolumesDataTreeFilter->GetSelectedItem(); if(!item)return; mitk::Image* vol = static_cast(item->GetNode()->GetData()); itk::Image::Pointer itkvol = itk::Image::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = item->GetProperty("name"); // COMPUTE RA clock.Start(); MBI_INFO << "Computing RA "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing RA for %s", nodename.c_str())); typedef TensorPixelType::RealValueType RealValueType; typedef itk::Image< RealValueType, 3 > RAImageType; typedef itk::TensorRelativeAnisotropyImageFilter< TensorImageType, RAImageType > RAFilterType; RAFilterType::Pointer relativeAnisotropyFilter = RAFilterType::New(); relativeAnisotropyFilter->SetInput( itkvol ); relativeAnisotropyFilter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; // FA TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( relativeAnisotropyFilter->GetOutput() ); image->SetVolume( relativeAnisotropyFilter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, nodename.append(" RA")); node->SetProperty( "IsRAVolume", mitk::BoolProperty::New( true ) ); mitk::StatusBar::GetInstance()->DisplayText("Computation complete."); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::StandardAlgorithmsDirectionButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::Item* item = m_TensorVolumesDataTreeFilter->GetSelectedItem(); if(!item)return; typedef itk::DiffusionTensor3D TensorType; typedef itk::Image TensorImgType; mitk::Image* vol = static_cast(item->GetNode()->GetData()); TensorImgType::Pointer itkvol = TensorImgType::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = item->GetProperty("name"); clock.Start(); MBI_INFO << "Computing Diffusion Direction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing Diffusion Direction for %s", nodename.c_str())); typedef itk::DiffusionTensorPrincipleDirectionImageFilter FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(itkvol); filter->SetNumberOfThreads(4); filter->Update(); itk::ImageRegionIterator it (filter->GetOutput(), filter->GetOutput()->GetLargestPossibleRegion() ); it = it.Begin(); // VECTORFIELD MBI_DEBUG << "Converting to Vectorfield"; typedef itk::Image, 3> VecImgType2; VecImgType2::Pointer vecImg5 = VecImgType2::New(); vecImg5->SetSpacing( itkvol->GetSpacing() ); // Set the image spacing vecImg5->SetOrigin( itkvol->GetOrigin() ); // Set the image origin vecImg5->SetDirection( itkvol->GetDirection() ); // Set the image direction vecImg5->SetLargestPossibleRegion( itkvol->GetLargestPossibleRegion()); vecImg5->SetBufferedRegion( vecImg5->GetLargestPossibleRegion() ); vecImg5->Allocate(); itk::ImageRegionIterator ot5 (vecImg5, vecImg5->GetLargestPossibleRegion() ); ot5 = ot5.Begin(); typedef FilterType::OutputImageType::PixelType VecPixType; for (it = it.Begin(); !it.IsAtEnd(); ++it) { VecPixType vec = it.Get(); itk::Vector pix; TTensorPixelType uvec[3] = {(TTensorPixelType)(vec[0]),(TTensorPixelType)(vec[1]),(TTensorPixelType)(vec[2])}; //TTensorPixelType uvec[3] = {(TTensorPixelType)(vec[1]),(TTensorPixelType)(-vec[0]),(TTensorPixelType)(vec[2])}; pix = uvec; ot5.Set(pix); ++ot5; } // Vectors TO DATATREE mitk::Image::Pointer image5 = mitk::Image::New(); image5->InitializeByItk( vecImg5.GetPointer() ); image5->SetVolume( vecImg5->GetBufferPointer() ); mitk::DataNode::Pointer node5=mitk::DataNode::New(); node5->SetData( image5 ); node5->SetName( nodename.append(" vecs").c_str()); mitk::DataStorage::GetInstance()->Add(node5); node5->SetProperty( "IsDirectionVolume", mitk::BoolProperty::New( true ) ); node5->SetProperty( "NormalizeVecs", mitk::BoolProperty::New( true ) ); node5->SetProperty( "Scale", mitk::FloatProperty::New( 1.0 ) ); node5->SetProperty( "LineWidth", mitk::FloatProperty::New( 1 ) ); mitk::VectorImageMapper2D::Pointer vecMapper5 = mitk::VectorImageMapper2D::New(); node5->SetMapper(1,vecMapper5); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::QBallStandardAlgorithmsGFAButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::ItemSet* selectedItems = m_QballVolumesDataTreeFilter->GetSelectedItems(); int nrFiles = selectedItems->size(); if (!nrFiles) return; mitk::DataTreeFilter::ItemSet::const_iterator itemiter( selectedItems->begin() ); mitk::DataTreeFilter::ItemSet::const_iterator itemiterend( selectedItems->end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { typedef itk::Vector OdfVectorType; typedef itk::Image OdfVectorImgType; mitk::Image* vol = static_cast((*itemiter)->GetNode()->GetData()); OdfVectorImgType::Pointer itkvol = OdfVectorImgType::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = (*itemiter)->GetProperty("name"); ++itemiter; float p1 = m_Controls->m_QBallStandardAlgorithmsGFAParam1->text().toFloat(); float p2 = m_Controls->m_QBallStandardAlgorithmsGFAParam2->text().toFloat(); // COMPUTE RA clock.Start(); MBI_INFO << "Computing GFA "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing GFA for %s", nodename.c_str())); typedef OdfVectorType::ValueType RealValueType; typedef itk::Image< RealValueType, 3 > RAImageType; typedef itk::DiffusionQballGeneralizedFaImageFilter GfaFilterType; GfaFilterType::Pointer gfaFilter = GfaFilterType::New(); gfaFilter->SetInput(itkvol); gfaFilter->SetNumberOfThreads(4); double scale = 1; std::string newname; newname.append(nodename); newname.append(" GFA"); switch(m_Controls->m_QBallStandardAlgorithmsGFAMethod->currentItem()) { case 0: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_STANDARD); newname.append("00"); scale = 200.0; break; } case 1: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_QUANTILES_HIGH_LOW); newname.append("01"); scale = 200.0; break; } case 2: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_QUANTILE_HIGH); newname.append("02"); scale = 200.0; break; } case 3: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_MAX_ODF_VALUE); newname.append("03"); scale = 200.0; break; } case 4: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_DECONVOLUTION_COEFFS); newname.append("04"); scale = 200.0; break; } case 5: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_MIN_MAX_NORMALIZED_STANDARD); newname.append("05"); scale = 200.0; break; } case 6: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_NORMALIZED_ENTROPY); newname.append("06"); break; } case 7: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_NEMATIC_ORDER_PARAMETER); newname.append("07"); scale = 200.0; break; } case 8: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_QUANTILES_LOW_HIGH); newname.append("08"); scale = 200.0; break; } case 9: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_QUANTILE_LOW); newname.append("09"); scale = 200.0; break; } case 10: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_MIN_ODF_VALUE); newname.append("10"); scale = 200.0; break; } case 11: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_STD_BY_MAX); newname.append("11"); scale = 200.0; break; } case 12: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_PRINCIPLE_CURVATURE); newname.append("12"); gfaFilter->SetParam1(p1); scale = 200.0; break; } case 13: { gfaFilter->SetComputationMethod(GfaFilterType::GFA_GENERALIZED_GFA); QString paramString; paramString = paramString.append(" K%1P%2").arg(p1).arg(p2); newname.append("13").append(paramString.ascii()); gfaFilter->SetParam1(p1); gfaFilter->SetParam2(p2); scale = 200.0; break; } default: { newname.append("0"); gfaFilter->SetComputationMethod(GfaFilterType::GFA_STANDARD); scale = 200.0; } } gfaFilter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMeanTime() << "s."; typedef itk::Image ImgType; ImgType::Pointer img = ImgType::New(); img->SetSpacing( gfaFilter->GetOutput()->GetSpacing() ); // Set the image spacing img->SetOrigin( gfaFilter->GetOutput()->GetOrigin() ); // Set the image origin img->SetDirection( gfaFilter->GetOutput()->GetDirection() ); // Set the image direction img->SetLargestPossibleRegion( gfaFilter->GetOutput()->GetLargestPossibleRegion()); img->SetBufferedRegion( gfaFilter->GetOutput()->GetLargestPossibleRegion() ); img->Allocate(); itk::ImageRegionIterator ot (img, img->GetLargestPossibleRegion() ); ot = ot.Begin(); itk::ImageRegionConstIterator it (gfaFilter->GetOutput(), gfaFilter->GetOutput()->GetLargestPossibleRegion() ); it = it.Begin(); for (it = it.Begin(); !it.IsAtEnd(); ++it) { GfaFilterType::OutputImageType::PixelType val = it.Get(); ot.Set(val * scale); ++ot; } // GFA TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( img.GetPointer() ); image->SetVolume( img->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); nodes.push_back(node); SetDefaultNodeProperties(node, newname.c_str()); node->SetProperty( "IsGFAVolume", mitk::BoolProperty::New( true ) ); mitk::StatusBar::GetInstance()->DisplayText("Computation complete."); } std::vector::iterator nodeIt; for(nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) mitk::DataStorage::GetInstance()->Add(*nodeIt); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::QBallStandardAlgorithmsDirectionButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::Item* item = m_QballVolumesDataTreeFilter->GetSelectedItem(); if(!item)return; typedef itk::Vector OdfVectorType; typedef itk::Image OdfVectorImgType; mitk::Image* vol = static_cast(item->GetNode()->GetData()); OdfVectorImgType::Pointer itkvol = OdfVectorImgType::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = item->GetProperty("name"); clock.Start(); MBI_INFO << "Computing Diffusion Direction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing Diffusion Direction for %s", nodename.c_str())); typedef itk::DiffusionQballGeneralizedFaImageFilter GfaFilterType; GfaFilterType::Pointer gfaFilter = GfaFilterType::New(); gfaFilter->SetInput(itkvol); gfaFilter->SetNumberOfThreads(4); gfaFilter->Update(); itk::ImageRegionIterator itGfa (gfaFilter->GetOutput(), gfaFilter->GetOutput()->GetLargestPossibleRegion() ); itGfa = itGfa.Begin(); int numdir = m_Controls->m_QBallStandardAlgorithmsOrderSpinbox->value(); typedef itk::DiffusionQballPrincipleDirectionsImageFilter PrincipleDirectionsFilterType; PrincipleDirectionsFilterType::Pointer principleDirectionsFilter = PrincipleDirectionsFilterType::New(); principleDirectionsFilter->SetThreshold(m_Controls->m_QBallStandardAlgorithmsProbThreshEdit->text().toFloat()); principleDirectionsFilter->SetNrDirectionToExtract(numdir); principleDirectionsFilter->SetInput(itkvol); principleDirectionsFilter->SetNumberOfThreads(m_Controls->m_QBallStandardAlgorithmsNumberThreadsSpinbox->value()); principleDirectionsFilter->SetMultiplyGfa(false); principleDirectionsFilter->Update(); itk::ImageRegionIterator it (principleDirectionsFilter->GetOutput(), principleDirectionsFilter->GetOutput()->GetLargestPossibleRegion() ); if(numdir == 0) { MBI_INFO << "Converting to RGB"; typedef itk::Image, 3> VecImgType; VecImgType::Pointer vecImg = VecImgType::New(); vecImg->SetSpacing( itkvol->GetSpacing() ); // Set the image spacing vecImg->SetOrigin( itkvol->GetOrigin() ); // Set the image origin vecImg->SetDirection( itkvol->GetDirection() ); // Set the image direction vecImg->SetLargestPossibleRegion( itkvol->GetLargestPossibleRegion()); vecImg->SetBufferedRegion( vecImg->GetLargestPossibleRegion() ); vecImg->Allocate(); itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); ot = ot.Begin(); typedef PrincipleDirectionsFilterType::OutputImageType::PixelType VecPixType; for (it = it.Begin(); !it.IsAtEnd(); ++it) { VecPixType vec = it.Get(); itk::RGBPixel pix; vec*=200*itGfa.Get(); vec[0] = abs(vec[0]); vec[1] = abs(vec[1]); vec[2] = abs(vec[2]); if(vec[0] > 255 || vec[1] > 255 || vec[2] > 255) { // should never get in here double max = vec[0]; max = maxInitializeByItk( vecImg.GetPointer() ); image2->SetVolume( vecImg->GetBufferPointer() ); mitk::DataNode::Pointer node2=mitk::DataNode::New(); node2->SetData( image2 ); mitk::DataStorage::GetInstance()->Add(node2); switch(numdir) { case 0: { SetDefaultNodeProperties(node2, nodename.append(" PD0")); break; } case 1: { SetDefaultNodeProperties(node2, nodename.append(" PD1")); } case 2: { SetDefaultNodeProperties(node2, nodename.append(" PD2")); } default: { SetDefaultNodeProperties(node2, nodename.append(" PDn")); } } node2->SetProperty( "IsRGBVolume", mitk::BoolProperty::New( true ) ); } // VECTORFIELD MBI_DEBUG << "Converting to Vectorfield"; typedef itk::Image, 3> VecImgType2; VecImgType2::Pointer vecImg5 = VecImgType2::New(); vecImg5->SetSpacing( itkvol->GetSpacing() ); // Set the image spacing vecImg5->SetOrigin( itkvol->GetOrigin() ); // Set the image origin vecImg5->SetDirection( itkvol->GetDirection() ); // Set the image direction vecImg5->SetLargestPossibleRegion( itkvol->GetLargestPossibleRegion()); vecImg5->SetBufferedRegion( vecImg5->GetLargestPossibleRegion() ); vecImg5->Allocate(); itk::ImageRegionIterator ot5 (vecImg5, vecImg5->GetLargestPossibleRegion() ); ot5 = ot5.Begin(); typedef PrincipleDirectionsFilterType::OutputImageType::PixelType VecPixType; for (it = it.Begin(); !it.IsAtEnd(); ++it) { VecPixType vec = it.Get(); itk::Vector pix; TTensorPixelType uvec[3] = {(TTensorPixelType)(vec[0]),(TTensorPixelType)(vec[1]),(TTensorPixelType)(vec[2])}; pix = uvec; ot5.Set(pix); ++ot5; } // Vectors TO DATATREE mitk::Image::Pointer image5 = mitk::Image::New(); image5->InitializeByItk( vecImg5.GetPointer() ); image5->SetVolume( vecImg5->GetBufferPointer() ); mitk::DataNode::Pointer node5=mitk::DataNode::New(); node5->SetData( image5 ); mitk::DataStorage::GetInstance()->Add(node5); switch(numdir) { case 0: { SetDefaultNodeProperties(node5, nodename.append(" Vec0")); break; } case 1: { SetDefaultNodeProperties(node5, nodename.append(" Vec1")); } case 2: { SetDefaultNodeProperties(node5, nodename.append(" Vec2")); } default: { SetDefaultNodeProperties(node5, nodename.append(" Vecn")); } } node5->SetProperty( "IsDirectionVolume", mitk::BoolProperty::New( true ) ); node5->SetProperty( "NormalizeVecs", mitk::BoolProperty::New( true ) ); node5->SetProperty( "Scale", mitk::FloatProperty::New( 0.8 ) ); node5->SetProperty( "LineWidth", mitk::FloatProperty::New( 3 ) ); mitk::VectorImageMapper2D::Pointer vecMapper5 = mitk::VectorImageMapper2D::New(); node5->SetMapper(1,vecMapper5); m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::QBallStandardAlgorithmsDeconvolutionButton() { itk::TimeProbe clock; QString status; const mitk::DataTreeFilter::Item* item = m_QballVolumesDataTreeFilter->GetSelectedItem(); if(!item)return; typedef itk::Vector OdfVectorType; typedef itk::Image OdfVectorImgType; mitk::Image* vol = static_cast(item->GetNode()->GetData()); OdfVectorImgType::Pointer itkvol = OdfVectorImgType::New(); mitk::CastToItkImage(vol, itkvol); std::string nodename = item->GetProperty("name"); clock.Start(); MBI_INFO << "Computing Diffusion Direction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "Computing Diffusion Direction for %s", nodename.c_str())); typedef itk::DiffusionQballGeneralizedFaImageFilter GfaFilterType; GfaFilterType::Pointer gfaFilter = GfaFilterType::New(); gfaFilter->SetInput(itkvol); gfaFilter->SetNumberOfThreads(4); gfaFilter->Update(); itk::ImageRegionIterator itGfa (gfaFilter->GetOutput(), gfaFilter->GetOutput()->GetLargestPossibleRegion() ); itGfa = itGfa.Begin(); int numdirs = m_Controls->m_QBallStandardAlgorithmsDeconvolutionSpinbox->value(); //vnl_matrix_fixed* kernels // = new vnl_matrix_fixed(); //itk::ImageRegionIterator inIt(itkvol, itkvol->GetLargestPossibleRegion()); //inIt.GoToBegin(); //for(int i=0; i DeconvolutionFilterType; DeconvolutionFilterType::Pointer devonvolutionFilter = DeconvolutionFilterType::New(); devonvolutionFilter->SetFractionalThreshold(m_Controls->m_QBallStandardAlgorithmsDeconvolutionThreshEdit->text().toFloat()); if(!m_Controls->m_QBallStandardAlgorithmsDeconvolutionAngResThresholdEdit->text().contains(QString("NaN"))) { float angRes = m_Controls->m_QBallStandardAlgorithmsDeconvolutionAngResThresholdEdit->text().toFloat(); angRes /= 360/DIFF_EST_PI; devonvolutionFilter->SetAngularResolutionThreshold(angRes); } devonvolutionFilter->SetSamplingQuantileStart(m_Controls->m_QBallStandardAlgorithmsDeconvQuantStart->text().toFloat()); devonvolutionFilter->SetSamplingQuantileStep(m_Controls->m_QBallStandardAlgorithmsDeconvQuantStep->text().toFloat()); devonvolutionFilter->SetMinimumNumberOfSamples(m_Controls->m_QBallStandardAlgorithmsDeconvQuantMinNr->text().toInt()); devonvolutionFilter->SetIterateQuantiles(m_Controls->m_QBallStandardAlgorithmsDeconvQuantMulti->isChecked()); devonvolutionFilter->SetNrDirectionsToExtract(numdirs); devonvolutionFilter->SetInput(itkvol); devonvolutionFilter->SetNumberOfThreads(m_Controls->m_QBallStandardAlgorithmsDeconvNumberThreadsSpinbox->value()); devonvolutionFilter->SetGfaImage(gfaFilter->GetOutput()); //devonvolutionFilter->SetPresetConvolutionKernels(kernels); devonvolutionFilter->Update(); for(int i=0; i it (devonvolutionFilter->GetOutput(i), devonvolutionFilter->GetOutput()->GetLargestPossibleRegion() ); it = it.Begin(); if(i==0) { MBI_INFO << "Converting to RGB"; typedef itk::Image, 3> VecImgType; VecImgType::Pointer vecImg = VecImgType::New(); vecImg->SetSpacing( itkvol->GetSpacing() ); // Set the image spacing vecImg->SetOrigin( itkvol->GetOrigin() ); // Set the image origin vecImg->SetDirection( itkvol->GetDirection() ); // Set the image direction vecImg->SetLargestPossibleRegion( itkvol->GetLargestPossibleRegion()); vecImg->SetBufferedRegion( vecImg->GetLargestPossibleRegion() ); vecImg->Allocate(); itk::ImageRegionIterator ot (vecImg, vecImg->GetLargestPossibleRegion() ); ot = ot.Begin(); typedef DeconvolutionFilterType::OutputImageType::PixelType VecPixType; for (it = it.Begin(); !it.IsAtEnd(); ++it) { VecPixType vec = it.Get(); vnl_vector_fixed vnlvec = vec.GetVnlVector(); TTensorPixelType len = vnlvec.two_norm(); vnlvec = vnlvec.normalize(); itk::RGBPixel pix; vnlvec*=200*itGfa.Get(); vnlvec[0] = abs(vnlvec[0]); vnlvec[1] = abs(vnlvec[1]); vnlvec[2] = abs(vnlvec[2]); if(vnlvec[0] > 255 || vnlvec[1] > 255 || vnlvec[2] > 255) { //should never get in here double max = vnlvec[0]; max = maxInitializeByItk( vecImg.GetPointer() ); image2->SetVolume( vecImg->GetBufferPointer() ); mitk::DataNode::Pointer node2=mitk::DataNode::New(); node2->SetData( image2 ); mitk::DataStorage::GetInstance()->Add(node2); switch(i) { case 0: { SetDefaultNodeProperties(node2, nodename.append(" PD0")); break; } case 1: { SetDefaultNodeProperties(node2, nodename.append(" PD1")); break; } case 2: { SetDefaultNodeProperties(node2, nodename.append(" PD2")); break; } default: { SetDefaultNodeProperties(node2, nodename.append(" PDn")); break; } } node2->SetProperty( "IsRGBVolume", mitk::BoolProperty::New( true ) ); } // VECTORFIELD MBI_INFO << "Converting to Vectorfield"; typedef itk::Image, 3> VecImgType2; VecImgType2::Pointer vecImg5 = VecImgType2::New(); vecImg5->SetSpacing( itkvol->GetSpacing() ); // Set the image spacing vecImg5->SetOrigin( itkvol->GetOrigin() ); // Set the image origin vecImg5->SetDirection( itkvol->GetDirection() ); // Set the image direction vecImg5->SetLargestPossibleRegion( itkvol->GetLargestPossibleRegion()); vecImg5->SetBufferedRegion( vecImg5->GetLargestPossibleRegion() ); vecImg5->Allocate(); itk::ImageRegionIterator ot5 (vecImg5, vecImg5->GetLargestPossibleRegion() ); ot5 = ot5.Begin(); typedef DeconvolutionFilterType::OutputImageType::PixelType VecPixType; for (it = it.Begin(); !it.IsAtEnd(); ++it) { VecPixType vec = it.Get(); vnl_vector_fixed vnlvec = vec.GetVnlVector(); vnlvec = vnlvec.normalize(); itk::Vector pix; TTensorPixelType uvec[3] = {(TTensorPixelType)(vnlvec[0]),(TTensorPixelType)(vnlvec[1]),(TTensorPixelType)(vnlvec[2])}; pix = uvec; ot5.Set(pix); ++ot5; } // Vectors TO DATATREE mitk::Image::Pointer image5 = mitk::Image::New(); image5->InitializeByItk( vecImg5.GetPointer() ); image5->SetVolume( vecImg5->GetBufferPointer() ); mitk::DataNode::Pointer node5=mitk::DataNode::New(); node5->SetData( image5 ); mitk::DataStorage::GetInstance()->Add(node5); switch(i) { case 0: { SetDefaultNodeProperties(node5, nodename.append(" Vec0")); break; } case 1: { SetDefaultNodeProperties(node5, nodename.append(" Vec1")); break; } case 2: { SetDefaultNodeProperties(node5, nodename.append(" Vec2")); break; } default: { SetDefaultNodeProperties(node5, nodename.append(" Vecn")); break; } } node5->SetProperty( "IsDirectionVolume", mitk::BoolProperty::New( true ) ); node5->SetProperty( "NormalizeVecs", mitk::BoolProperty::New( true ) ); node5->SetProperty( "Scale", mitk::FloatProperty::New( 0.8 ) ); node5->SetProperty( "LineWidth", mitk::FloatProperty::New( 3 ) ); mitk::VectorImageMapper2D::Pointer vecMapper5 = mitk::VectorImageMapper2D::New(); node5->SetMapper(1,vecMapper5); } m_DataTreeIterator->GetTree()->Modified(); m_MultiWidget->RequestUpdate(); TreeChanged(); m_Controls->update(); } void QmitkDiffusionTensorEstimation::SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name) { node->SetProperty( "volumerendering", mitk::BoolProperty::New( false ) ); node->SetProperty( "use color", mitk::BoolProperty::New( true ) ); node->SetProperty( "texture interpolation", mitk::BoolProperty::New( true ) ); node->SetProperty( "reslice interpolation", mitk::VtkResliceInterpolationProperty::New() ); node->SetProperty( "layer", mitk::IntProperty::New(0)); node->SetProperty( "in plane resample extent by geometry", mitk::BoolProperty::New( false ) ); node->SetOpacity(1.0f); node->SetColor(1.0,1.0,1.0); node->SetVisibility(true); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelwindow; // levelwindow.SetAuto( image ); levWinProp->SetLevelWindow( levelwindow ); node->GetPropertyList()->SetProperty( "levelwindow", levWinProp ); // add a default rainbow lookup table for color mapping if(!node->GetProperty("LookupTable")) { mitk::LookupTable::Pointer mitkLut = mitk::LookupTable::New(); vtkLookupTable* vtkLut = mitkLut->GetVtkLookupTable(); vtkLut->SetHueRange(0.6667, 0.0); vtkLut->SetTableRange(0.0, 20.0); vtkLut->Build(); mitk::LookupTableProperty::Pointer mitkLutProp = mitk::LookupTableProperty::New(); mitkLutProp->SetLookupTable(mitkLut); node->SetProperty( "LookupTable", mitkLutProp ); } if(!node->GetProperty("binary")) node->SetProperty( "binary", mitk::BoolProperty::New( false ) ); // add a default transfer function mitk::TransferFunction::Pointer tf = mitk::TransferFunction::New(); node->SetProperty ( "TransferFunction", mitk::TransferFunctionProperty::New ( tf.GetPointer() ) ); // set foldername as string property mitk::StringProperty::Pointer nameProp = mitk::StringProperty::New( name ); node->SetProperty( "name", nameProp ); } void QmitkDiffusionTensorEstimation::DirectionVolumesAngularErrorButton() { try { const mitk::DataTreeFilter::ItemSet* selectedItems = m_DirectionVolumesDataTreeFilter->GetSelectedItems(); int nrFiles = selectedItems->size(); if (nrFiles != 2) return; mitk::DataTreeFilter::ItemSet::const_iterator itemiter( selectedItems->begin() ); mitk::Image::Pointer vol1 = static_cast((*itemiter)->GetNode()->GetData()); if( !vol1)return; std::string nodename1 = (*itemiter)->GetProperty("name"); itemiter++; mitk::Image::Pointer vol2 = static_cast((*itemiter)->GetNode()->GetData()); if( !vol2)return; std::string nodename2 = (*itemiter)->GetProperty("name"); typedef itk::Image,3 > IType; IType::Pointer itkVol1 = IType::New(); mitk::CastToItkImage(vol1, itkVol1); IType::Pointer itkVol2 = IType::New(); mitk::CastToItkImage(vol2, itkVol2); typedef itk::VectorImagesAngularErrorImageFilter FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(itkVol1); filter->SetImage2(itkVol2.GetPointer()); filter->SetNumberOfThreads(4); filter->Update(); // Angluar Error TO DATATREE mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( filter->GetOutput() ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, nodename1.append(" ").append(nodename2).append(" ERR")); node->SetProperty( "IsErrorVolume", mitk::BoolProperty::New( true ) ); TreeChanged(); m_Controls->update(); QString status; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished computing Angular Error")); } catch (itk::ExceptionObject &ex) { MBI_INFO << ex; return ; } } //void QmitkDiffusionTensorEstimation::DwiStandardAlgorithmsGFAButton() //{ // // itk::TimeProbe clock; // QString status; // const mitk::DataTreeFilter::Item* item // = m_DiffusionVolumesDataTreeFilter->GetSelectedItem(); // if(!item)return; // // typedef itk::Vector OdfVectorType; // typedef itk::Image OdfVectorImgType; // mitk::Image* vol = // static_cast(item->GetNode()->GetData()); // OdfVectorImgType::Pointer itkvol = OdfVectorImgType::New(); // mitk::CastToItkImage(vol, itkvol); // std::string nodename = item->GetProperty("name"); // // // COMPUTE RA // clock.Start(); // std::cout << "Computing GFA "; // mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( // "Computing GFA for %s", nodename.c_str())); // typedef OdfVectorType::ValueType RealValueType; // typedef itk::Image< RealValueType, 3 > RAImageType; // typedef itk::DiffusionQballGeneralizedFaImageFilter // GfaFilterType; // GfaFilterType::Pointer gfaFilter = GfaFilterType::New(); // gfaFilter->SetInput(itkvol); // gfaFilter->SetNumberOfThreads(4); // switch(m_Controls->m_QBallStandardAlgorithmsGFAMethodSpinbox->value()) // { // case 1: // { // gfaFilter->SetComputationMethod(GfaFilterType::STANDARD); // break; // } // case 2: // { // gfaFilter->SetComputationMethod(GfaFilterType::QUANTILES_HIGH_LOW); // break; // } // case 3: // { // gfaFilter->SetComputationMethod(GfaFilterType::QUANTILES_MIDDLE); // break; // } // case 4: // { // gfaFilter->SetComputationMethod(GfaFilterType::MAX_ODF_VALUE); // break; // } // case 5: // { // gfaFilter->SetComputationMethod(GfaFilterType::DECONVOLUTION_COEFFS); // break; // } // default: // { // gfaFilter->SetComputationMethod(GfaFilterType::STANDARD); // } // } // gfaFilter->Update(); // clock.Stop(); // std::cout << "took " << clock.GetMeanTime() << "s." << std::endl; // // typedef itk::Image ImgType; // ImgType::Pointer img = ImgType::New(); // img->SetSpacing( gfaFilter->GetOutput()->GetSpacing() ); // Set the image spacing // img->SetOrigin( gfaFilter->GetOutput()->GetOrigin() ); // Set the image origin // img->SetDirection( gfaFilter->GetOutput()->GetDirection() ); // Set the image direction // img->SetLargestPossibleRegion( gfaFilter->GetOutput()->GetLargestPossibleRegion()); // img->SetBufferedRegion( gfaFilter->GetOutput()->GetLargestPossibleRegion() ); // img->Allocate(); // itk::ImageRegionIterator ot (img, img->GetLargestPossibleRegion() ); // ot = ot.Begin(); // itk::ImageRegionConstIterator it // (gfaFilter->GetOutput(), gfaFilter->GetOutput()->GetLargestPossibleRegion() ); // it = it.Begin(); // // for (it = it.Begin(); !it.IsAtEnd(); ++it) // { // GfaFilterType::OutputImageType::PixelType val = it.Get(); // ot.Set(val * 200); // ++ot; // } // // // // GFA TO DATATREE // mitk::Image::Pointer image = mitk::Image::New(); // image->InitializeByItk( img.GetPointer() ); // image->SetVolume( img->GetBufferPointer() ); // mitk::DataNode::Pointer node=mitk::DataNode::New(); // node->SetData( image ); // mitk::DataStorage::GetInstance()->Add(node); // SetDefaultNodeProperties(node, nodename.append(" GFA")); // node->SetProperty( "IsGFAVolume", mitk::BoolProperty::New( true ) ); // // mitk::StatusBar::GetInstance()->DisplayText("Computation complete."); // // m_DataTreeIterator->GetTree()->Modified(); // m_MultiWidget->RequestUpdate(); // TreeChanged(); // m_Controls->update(); // //} void QmitkDiffusionTensorEstimation::DiffusionVolumeSaveButton() { // GET SELECTED ITEM const mitk::DataTreeFilter::Item* selectedItem = m_DiffusionVolumesDataTreeFilter->GetSelectedItem(); if( !selectedItem ) return; mitk::DiffusionVolumes::Pointer diffVolumes = static_cast*>(selectedItem->GetNode()->GetData()); std::string sName = selectedItem->GetNode()->GetName(); QString qName; qName.sprintf("%s.nhdr",sName.c_str()); // SELECT FILE DIALOG //QFileDialog::getSaveFileName() //QFileDialog* w = new QFileDialog( this->m_Controls, "Select Nrrd Outputfile", TRUE ); //w->setMode( QFileDialog::AnyFile ); //w->setFilter( "Nrrd Images (*.nrrd *.nhdr)" ); //w->setName(qName); //if ( w->exec() != QDialog::Accepted ) // return; //QString filename = w->selectedFile(); QString filename = QFileDialog::getSaveFileName( qName, "Nrrd Images (*.nrrd *.nhdr)", this->m_Controls, "save file dialog", "Select Nrrd Outputfile" ); if ( !filename ) return; // WRITING DWIs TO NRRD VOLUME typedef mitk::NrrdDiffusionVolumesWriter WriterType; WriterType::Pointer nrrdWriter = WriterType::New(); nrrdWriter->SetInput( diffVolumes->GetImage() ); nrrdWriter->SetDirections(diffVolumes->GetDirections()); nrrdWriter->SetB_Value(diffVolumes->GetB_Value()); nrrdWriter->SetFileName(filename.ascii()); try { nrrdWriter->Update(); } catch (itk::ExceptionObject e) { MBI_INFO << e; } } void QmitkDiffusionTensorEstimation::DiffusionVolumesLoadButton() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( this->m_Controls, "Select DWI data file", TRUE ); w->setMode( QFileDialog::ExistingFiles ); w->setFilter( "Nrrd Images (*.nrrd *.nhdr)" ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; QStringList filenames = w->selectedFiles(); QStringList::Iterator it = filenames.begin(); while( it != filenames.end() ) { std::string filename = ( *it ).ascii(); ++it; // READING NRRD DWI VOLUMES typedef mitk::NrrdDiffusionVolumesReader ReaderType; ReaderType::Pointer nrrdReader = ReaderType::New(); nrrdReader->SetFileName(filename); try { nrrdReader->Update(); // DWI TO DATATREE typedef mitk::DiffusionVolumes DiffVolumesType; DiffVolumesType::Pointer diffVolumes = DiffVolumesType::New(); diffVolumes->SetDirections(nrrdReader->GetDiffusionVectors()); diffVolumes->SetB_Value(nrrdReader->GetB_Value()); diffVolumes->SetImage(nrrdReader->GetOutput()); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( diffVolumes ); mitk::DataStorage::GetInstance()->Add(node); SetDefaultNodeProperties(node, itksys::SystemTools::GetFilenameName(filename)); TreeChanged(); } catch (itk::ExceptionObject e) { MBI_INFO << e; } } } void QmitkDiffusionTensorEstimation::DiffusionVolumesRemoveButton() { m_DiffusionVolumesDataTreeFilter->DeleteSelectedItems(); } void QmitkDiffusionTensorEstimation::DiffusionVolumesSelectAll() { const mitk::DataTreeFilter::ItemList* items = m_DiffusionVolumesDataTreeFilter->GetItems(); mitk::DataTreeFilter::ConstItemIterator itemiter( items->Begin() ); mitk::DataTreeFilter::ConstItemIterator itemiterend( items->End() ); while ( itemiter != itemiterend ) { m_DiffusionVolumesDataTreeFilter->SelectItem(*itemiter); ++itemiter; } -} \ No newline at end of file +} diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/QmitkColourImageProcessingView.cpp b/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/QmitkColourImageProcessingView.cpp index 8343670d6d..25d69aa191 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/QmitkColourImageProcessingView.cpp +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/colourimageprocessing/QmitkColourImageProcessingView.cpp @@ -1,283 +1,283 @@ /*=================================================================== 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 "QmitkColourImageProcessingView.h" #include "mitkColourImageProcessor.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include #include #include #include #include #include #include #include #include "QmitkPiecewiseFunctionCanvas.h" #include "QmitkColorTransferFunctionCanvas.h" #include #include const std::string QmitkColourImageProcessingView::VIEW_ID = "org.mitk.views.colourimageprocessing"; QmitkColourImageProcessingView::QmitkColourImageProcessingView() : QmitkFunctionality(), m_MultiWidget(NULL) { m_Controls=NULL; m_Color[0]= 255; m_Color[1]= 0; m_Color[2]= 0; } QmitkColourImageProcessingView::~QmitkColourImageProcessingView() { berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemoveSelectionListener(m_SelectionListener); } void QmitkColourImageProcessingView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Controls = new Ui::QmitkColourImageProcessingViewControls; m_Controls->setupUi(parent); connect( m_Controls->m_ConvertImageToRGBA, SIGNAL( clicked(bool) ),this, SLOT( OnConvertToRGBAImage() )); connect( m_Controls->m_ConvertImageMaskToRGBA, SIGNAL( clicked(bool) ),this, SLOT( OnConvertToRGBAImage() )); connect( m_Controls->m_ConvertImageMaskColorToRGBA, SIGNAL( clicked(bool) ),this, SLOT( OnConvertImageMaskColorToRGBAImage() )); connect( m_Controls->m_ColorButton, SIGNAL( clicked(bool) ),this, SLOT( OnChangeColor() )); connect( m_Controls->m_CombineRGBAButton, SIGNAL( clicked(bool) ),this, SLOT( OnCombineRGBA() )); m_Controls->m_ImageSelectedLabel->hide(); m_Controls->m_NoImageSelectedLabel->show(); } m_SelectionListener = berry::ISelectionListener::Pointer(new berry::SelectionChangedAdapter (this, &QmitkColourImageProcessingView::SelectionChanged)); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->AddSelectionListener(m_SelectionListener); } void QmitkColourImageProcessingView::SelectionChanged( berry::IWorkbenchPart::Pointer, berry::ISelection::ConstPointer selection ) { mitk::DataNodeSelection::ConstPointer _DataNodeSelection = selection.Cast(); if(_DataNodeSelection.IsNotNull()) { std::vector selectedNodes; mitk::DataNodeObject* _DataNodeObject = 0; for(mitk::DataNodeSelection::iterator it = _DataNodeSelection->Begin();it != _DataNodeSelection->End(); ++it) { _DataNodeObject = dynamic_cast((*it).GetPointer()); if(_DataNodeObject) { mitk::DataNode::Pointer node = _DataNodeObject->GetDataNode(); if( node.IsNotNull() && dynamic_cast(node->GetData())&&dynamic_cast(node->GetData())->GetDimension()>=3 ) selectedNodes.push_back( node ); } } mitk::DataNode::Pointer node; if(selectedNodes.size() > 0) node=selectedNodes[0]; if( node.IsNotNull() ) { m_SelectedNode = node; m_Controls->m_NoImageSelectedLabel->hide(); m_Controls->m_ImageSelectedLabel->show(); std::string infoText = std::string("Selected Image: ") + node->GetName(); if(selectedNodes.size() > 1) { mitk::DataNode::Pointer node2; node2=selectedNodes[1]; m_SelectedNode2=node2; infoText = infoText + " and " + node2->GetName(); } else { m_SelectedNode2= 0; } m_Controls->m_ImageSelectedLabel->setText( QString( infoText.c_str() ) ); } else { m_Controls->m_ImageSelectedLabel->hide(); m_Controls->m_NoImageSelectedLabel->show(); m_SelectedNode = 0; m_SelectedNode2= 0; } } } void QmitkColourImageProcessingView::OnConvertToRGBAImage() { if(m_SelectedNode.IsNull()) return; mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast(m_SelectedNode->GetProperty("TransferFunction")); if(transferFunctionProp.IsNull()) return; mitk::TransferFunction::Pointer tf = transferFunctionProp->GetValue(); if(tf.IsNull()) return; mitk::mitkColourImageProcessor CImageProcessor; mitk::Image::Pointer RGBAImageResult; if(m_SelectedNode2.IsNotNull()) { RGBAImageResult = CImageProcessor.convertWithBinaryToRGBAImage(dynamic_cast(m_SelectedNode->GetData()),dynamic_cast(m_SelectedNode2->GetData()),tf); } else { RGBAImageResult = CImageProcessor.convertToRGBAImage(dynamic_cast(m_SelectedNode->GetData()),tf); } if (!RGBAImageResult) { QMessageBox::warning(NULL, "Warning", QString("Unsupported pixeltype")); return; } mitk::DataNode::Pointer dtn = mitk::DataNode::New(); dtn->SetData( RGBAImageResult ); dtn->SetName(m_SelectedNode->GetName() + "_RGBA"); this->GetDefaultDataStorage()->Add( dtn ); // add as a child, because the segmentation "derives" from the original MITK_INFO << "convertToRGBAImage finish"; } void QmitkColourImageProcessingView::OnConvertImageMaskColorToRGBAImage( ) { if(m_SelectedNode.IsNull()) return; mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast(m_SelectedNode->GetProperty("TransferFunction")); if(transferFunctionProp.IsNull()) return; mitk::TransferFunction::Pointer tf = transferFunctionProp->GetValue(); if(tf.IsNull()) return; mitk::mitkColourImageProcessor CImageProcessor; mitk::Image::Pointer RGBAImageResult; if(m_SelectedNode2.IsNotNull()) { RGBAImageResult = CImageProcessor.convertWithBinaryAndColorToRGBAImage(dynamic_cast(m_SelectedNode->GetData()),dynamic_cast(m_SelectedNode2->GetData()),tf, m_Color); } else { RGBAImageResult = CImageProcessor.convertToRGBAImage(dynamic_cast(m_SelectedNode->GetData()),tf); } if (!RGBAImageResult) { QMessageBox::warning(NULL, "Warning", QString("Unsupported pixeltype")); return; } mitk::DataNode::Pointer dtn = mitk::DataNode::New(); dtn->SetData( RGBAImageResult ); dtn->SetName(m_SelectedNode->GetName() + "_RGBA"); this->GetDefaultDataStorage()->Add( dtn ); // add as a child, because the segmentation "derives" from the original } void QmitkColourImageProcessingView::OnChangeColor( ) { QColor color = QColorDialog::getColor(); if (color.spec() == 0) { color.setRed(255); color.setGreen(0); color.setBlue(0); } m_Color[0]= color.red(); m_Color[1]= color.green(); m_Color[2]= color.blue(); m_Controls->m_ColorButton->setStyleSheet(QString("background-color:rgb(%1,%2, %3)").arg(color.red()).arg(color.green()).arg(color.blue())); } void QmitkColourImageProcessingView::OnCombineRGBA( ) { if(m_SelectedNode.IsNull()) return; if(m_SelectedNode2.IsNull()) return; mitk::mitkColourImageProcessor CImageProcessor; mitk::Image::Pointer RGBAImageResult; RGBAImageResult = CImageProcessor.combineRGBAImage(dynamic_cast(m_SelectedNode->GetData()),dynamic_cast(m_SelectedNode2->GetData())); MITK_INFO <<"RGBAImage Result"; mitk::DataNode::Pointer dtn = mitk::DataNode::New(); dtn->SetData( RGBAImageResult ); this->GetDefaultDataStorage()->Add( dtn ); // add as a child, because the segmentation "derives" from the original -} \ No newline at end of file +} diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/isosurface/QmitkIsoSurface.cpp b/Plugins/org.mitk.gui.qt.examples/src/internal/isosurface/QmitkIsoSurface.cpp index 4298af5078..5250d317c8 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/isosurface/QmitkIsoSurface.cpp +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/isosurface/QmitkIsoSurface.cpp @@ -1,239 +1,239 @@ /*=================================================================== 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 "QmitkIsoSurface.h" //#include //GUI //#include //image //MITK headers #include #include #include #include //Qmitk headers #include #include #include //Qt-GUI headers #include #include #include #include #include #include #include QmitkIsoSurface::QmitkIsoSurface(QObject * /*parent*/, const char * /*name*/) : QmitkFunctionality() , m_Controls(NULL), m_MitkImage(NULL), m_SurfaceCounter(0) { //SetAvailability(true); } //QWidget * QmitkIsoSurface::CreateMainWidget(QWidget *) //{ // return NULL; //} //QWidget * QmitkIsoSurface::CreateControlWidget(QWidget *parent) //{ // if (m_Controls == NULL) // { // m_Controls = new QmitkIsoSurfaceControls(parent); // } // return m_Controls; //} void QmitkIsoSurface::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Controls = new Ui::QmitkIsoSurfaceControls; m_Controls->setupUi(parent); this->CreateConnections(); m_Controls->m_ImageSelector->SetDataStorage(this->GetDefaultDataStorage()); m_Controls->m_ImageSelector->SetPredicate(mitk::NodePredicateDataType::New("Image")); berry::IPreferences::Pointer prefs = this->GetPreferences(); if(prefs.IsNotNull()) m_Controls->thresholdLineEdit->setText(QString::fromStdString(prefs->Get("defaultThreshold", "0"))); } } void QmitkIsoSurface::CreateConnections() { if ( m_Controls ) { connect( m_Controls->m_ImageSelector, SIGNAL(OnSelectionChanged(const mitk::DataNode*)), this, SLOT(ImageSelected(const mitk::DataNode*)) ); connect( m_Controls->createSurfacePushButton, SIGNAL(clicked()), this, SLOT(CreateSurface()) ); } } //QAction * QmitkIsoSurface::CreateAction(QActionGroup *parent) //{ // QAction* action; // action = new QAction( tr( "IsoSurface" ), QPixmap((const char**)isoSurface_xpm), tr( "IsoSurface" ), 0, parent, "IsoSurface" ); // return action; //} void QmitkIsoSurface::DataStorageChanged() { //m_Controls->m_ImageSelector->Update(); } void QmitkIsoSurface::ImageSelected(const mitk::DataNode* item) { // nothing selected (NULL selection) if( item == 0 || item->GetData() == 0 ) return; m_MitkImage = dynamic_cast (item->GetData()); } void QmitkIsoSurface::CreateSurface() { QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); if(m_MitkImage != NULL) { //Value Gauss //float gsDev = 1.5; //Value for DecimatePro float targetReduction = 0.05; //ImageToSurface Instance mitk::DataNode::Pointer node = m_Controls->m_ImageSelector->GetSelectedNode(); /* mitk::DataTreeIteratorClone iteratorOnImageToBeSkinExtracted; iteratorOnImageToBeSkinExtracted = m_Controls->m_ImageSelector->GetFilter()->GetIteratorToSelectedItem(); if(iteratorOnImageToBeSkinExtracted.IsNull()) { iteratorOnImageToBeSkinExtracted = CommonFunctionality::GetIteratorToFirstImage(m_DataTreeIterator.GetPointer()); } */ mitk::ManualSegmentationToSurfaceFilter::Pointer filter = mitk::ManualSegmentationToSurfaceFilter::New(); if (filter.IsNull()) { std::cout<<"NULL Pointer for ManualSegmentationToSurfaceFilter"<SetInput( m_MitkImage ); filter->SetGaussianStandardDeviation( 0.5 ); filter->SetUseGaussianImageSmooth( true ); filter->SetThreshold( getThreshold()); //if( Gauss ) --> TH manipulated for vtkMarchingCube filter->SetTargetReduction( targetReduction ); int numOfPolys = filter->GetOutput()->GetVtkPolyData()->GetNumberOfPolys(); if(numOfPolys>2000000) { QApplication::restoreOverrideCursor(); if(QMessageBox::question(NULL, "CAUTION!!!", "The number of polygons is greater than 2 000 000. If you continue, the program might crash. How do you want to go on?", "Proceed anyway!", "Cancel immediately! (maybe you want to insert an other threshold)!",QString::null,0 ,1)==1) { return; } QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); } mitk::DataNode::Pointer surfaceNode = mitk::DataNode::New(); surfaceNode->SetData( filter->GetOutput() ); int layer = 0; ++m_SurfaceCounter; std::ostringstream buffer; buffer << m_SurfaceCounter; std::string surfaceNodeName = "Surface " + buffer.str(); node->GetIntProperty("layer", layer); surfaceNode->SetIntProperty("layer", layer+1); surfaceNode->SetProperty("Surface", mitk::BoolProperty::New(true)); surfaceNode->SetProperty("name", mitk::StringProperty::New(surfaceNodeName)); /* mitk::DataTreeIteratorClone iteratorClone = m_DataTreeIterator; bool isSurface = false; while(!(iteratorClone->IsAtEnd())&&(isSurface == false)) { iteratorClone->Get()->GetBoolProperty("Surface", isSurface); if(isSurface == false) { ++iteratorClone; } } iteratorClone= iteratorOnImageToBeSkinExtracted; iteratorClone->Add(surfaceNode); iteratorClone->GetTree()->Modified(); */ this->GetDefaultDataStorage()->Add(surfaceNode, node); mitk::Surface::Pointer surface = filter->GetOutput(); //to show surfaceContur surfaceNode->SetColor( m_RainbowColor.GetNextColor() ); surfaceNode->SetVisibility(true); this->GetActiveStdMultiWidget()->RequestUpdate(); }//if m_MitkImage != NULL QApplication::restoreOverrideCursor(); } float QmitkIsoSurface::getThreshold() { return m_Controls->thresholdLineEdit->text().toFloat(); } void QmitkIsoSurface::StdMultiWidgetAvailable( QmitkStdMultiWidget& /*stdMultiWidget*/ ) { m_Parent->setEnabled(true); } void QmitkIsoSurface::StdMultiWidgetNotAvailable() { m_Parent->setEnabled(false); } QmitkIsoSurface::~QmitkIsoSurface() { berry::IPreferences::Pointer prefs = this->GetPreferences(); if(prefs.IsNotNull()) prefs->Put("defaultThreshold", m_Controls->thresholdLineEdit->text().toStdString()); -} \ No newline at end of file +} diff --git a/Plugins/org.mitk.gui.qt.examples/src/internal/simplemeasurement/QmitkSimpleMeasurement.cpp b/Plugins/org.mitk.gui.qt.examples/src/internal/simplemeasurement/QmitkSimpleMeasurement.cpp index 9da2795ed5..bbc4eb717e 100644 --- a/Plugins/org.mitk.gui.qt.examples/src/internal/simplemeasurement/QmitkSimpleMeasurement.cpp +++ b/Plugins/org.mitk.gui.qt.examples/src/internal/simplemeasurement/QmitkSimpleMeasurement.cpp @@ -1,192 +1,192 @@ /*=================================================================== 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 "QmitkSimpleMeasurement.h" // #include #include #include #include #include #include #include #include #include /* QmitkSimpleMeasurement::QmitkSimpleMeasurement(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it) , m_MultiWidget(mitkStdMultiWidget), m_Controls(NULL) { SetAvailability(true); } */ QmitkSimpleMeasurement::~QmitkSimpleMeasurement() { } void QmitkSimpleMeasurement::Activated() { std::vector selection = this->GetDataManagerSelection(); this->OnSelectionChanged( selection ); } void QmitkSimpleMeasurement::Deactivated() { std::vector selection; this->OnSelectionChanged( selection ); } void QmitkSimpleMeasurement::AddDistanceSimpleMeasurement() { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); mitk::DataNode::Pointer _CurrentPointSetNode = mitk::DataNode::New(); _CurrentPointSetNode->SetData(pointSet); _CurrentPointSetNode->SetProperty("show contour", mitk::BoolProperty::New(true)); _CurrentPointSetNode->SetProperty("name", mitk::StringProperty::New("distance")); _CurrentPointSetNode->SetProperty("show distances", mitk::BoolProperty::New(true)); // add to ds and remember as created this->GetDataStorage()->Add(_CurrentPointSetNode); m_CreatedPointSetNodes.push_back( _CurrentPointSetNode ); // make new selection std::vector selection; selection.push_back( _CurrentPointSetNode ); this->FireNodesSelected( selection ); this->OnSelectionChanged( selection ); } void QmitkSimpleMeasurement::AddAngleSimpleMeasurement() { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); mitk::DataNode::Pointer _CurrentPointSetNode = mitk::DataNode::New(); _CurrentPointSetNode->SetData(pointSet); _CurrentPointSetNode->SetProperty("show contour", mitk::BoolProperty::New(true)); _CurrentPointSetNode->SetProperty("name", mitk::StringProperty::New("angle")); _CurrentPointSetNode->SetProperty("show angles", mitk::BoolProperty::New(true)); // add to ds and remember as created this->GetDataStorage()->Add(_CurrentPointSetNode); m_CreatedPointSetNodes.push_back( _CurrentPointSetNode ); // make new selection std::vector selection; selection.push_back( _CurrentPointSetNode ); this->FireNodesSelected( selection ); this->OnSelectionChanged( selection ); } void QmitkSimpleMeasurement::AddPathSimpleMeasurement() { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); mitk::DataNode::Pointer _CurrentPointSetNode = mitk::DataNode::New(); _CurrentPointSetNode->SetData(pointSet); _CurrentPointSetNode->SetProperty("show contour", mitk::BoolProperty::New(true)); _CurrentPointSetNode->SetProperty("name", mitk::StringProperty::New("path")); _CurrentPointSetNode->SetProperty("show distances", mitk::BoolProperty::New(true)); _CurrentPointSetNode->SetProperty("show angles", mitk::BoolProperty::New(true)); // add to ds and remember as created this->GetDataStorage()->Add(_CurrentPointSetNode); m_CreatedPointSetNodes.push_back( _CurrentPointSetNode ); // make new selection std::vector selection; selection.push_back( _CurrentPointSetNode ); this->FireNodesSelected( selection ); this->OnSelectionChanged( selection ); } void QmitkSimpleMeasurement::CreateQtPartControl( QWidget* parent ) { m_Controls = new Ui::QmitkSimpleMeasurementControls; m_Controls->setupUi(parent); connect( (QObject*)(m_Controls->pbDistance), SIGNAL(clicked()),(QObject*) this, SLOT(AddDistanceSimpleMeasurement()) ); connect( (QObject*)(m_Controls->pbAngle), SIGNAL(clicked()),(QObject*) this, SLOT(AddAngleSimpleMeasurement()) ); connect( (QObject*)(m_Controls->pbPath), SIGNAL(clicked()),(QObject*) this, SLOT(AddPathSimpleMeasurement()) ); } void QmitkSimpleMeasurement::OnSelectionChanged( std::vector nodes ) { mitk::DataNode* selectedNode = 0; if(nodes.size() > 0) selectedNode = nodes.front(); mitk::PointSet* pointSet = 0; if(selectedNode) pointSet = dynamic_cast ( selectedNode->GetData() ); // something else was selected. remove old interactor if (m_PointSetInteractor.IsNotNull()) { mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_PointSetInteractor); } bool pointsetCreatedByThis = false; // only go further if a pointset was selected if(pointSet) { // see if this pointset was created by us std::vector::iterator it = std::find( m_CreatedPointSetNodes.begin() , m_CreatedPointSetNodes.end(), selectedNode); if(it != m_CreatedPointSetNodes.end()) pointsetCreatedByThis = true; } // do nothing if it was not created by us or it is no pointset node or we are not activated if(pointsetCreatedByThis && this->IsActivated()) { // otherwise: set text and add interactor for the pointset m_Controls->selectedPointSet->setText( QString::fromStdString(selectedNode->GetName()) ); mitk::PointSetInteractor::Pointer newPointSetInteractor = mitk::PointSetInteractor::New("pointsetinteractor", selectedNode); mitk::GlobalInteraction::GetInstance()->AddInteractor(newPointSetInteractor); m_PointSetInteractor = newPointSetInteractor; float green[] = { 0, 255, 0 }; float red[] = { 255, 0, 0 }; selectedNode->SetColor(green); if(m_SelectedPointSetNode.IsNotNull()) m_SelectedPointSetNode->SetColor(red); m_SelectedPointSetNode = selectedNode; } else { // revert text m_Controls->selectedPointSet->setText( "None" ); } } bool QmitkSimpleMeasurement::IsExclusiveFunctionality() const { return true; } void QmitkSimpleMeasurement::NodeRemoved( const mitk::DataNode* node ) { // remove a node if it is destroyed from our created array std::vector::iterator it = std::find( m_CreatedPointSetNodes.begin() , m_CreatedPointSetNodes.end(), node); if(it != m_CreatedPointSetNodes.end()) m_CreatedPointSetNodes.erase(it); -} \ No newline at end of file +} diff --git a/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/mitkPluginActivator.cpp index 1ae9d38d2b..7381354819 100644 --- a/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/mitkPluginActivator.cpp @@ -1,36 +1,36 @@ /*=================================================================== 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 "mitkPluginActivator.h" #include "src/internal/videoplayer/QmitkVideoPlayer.h" #include namespace mitk { void PluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkVideoPlayer, context) } void PluginActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } -Q_EXPORT_PLUGIN2(org_mitk_gui_qt_examplesopencv, mitk::PluginActivator) \ No newline at end of file +Q_EXPORT_PLUGIN2(org_mitk_gui_qt_examplesopencv, mitk::PluginActivator) diff --git a/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/mitkPluginActivator.h index 179331f8af..64df836537 100644 --- a/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/mitkPluginActivator.h @@ -1,40 +1,40 @@ /*=================================================================== 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 MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include #include namespace mitk { class MITK_LOCAL PluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // PluginActivator } -#endif // MITKPLUGINACTIVATOR_H \ No newline at end of file +#endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/videoplayer/QmitkVideoPlayer.cpp b/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/videoplayer/QmitkVideoPlayer.cpp index 40e9c7f37b..97df7309af 100644 --- a/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/videoplayer/QmitkVideoPlayer.cpp +++ b/Plugins/org.mitk.gui.qt.examplesopencv/src/internal/videoplayer/QmitkVideoPlayer.cpp @@ -1,58 +1,58 @@ /*=================================================================== 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 "QmitkVideoPlayer.h" #include #include #include #include QmitkVideoPlayer::QmitkVideoPlayer() : m_VideoSource(0) , m_VideoBackground( new QmitkVideoBackground(m_VideoSource) ) { } QmitkVideoPlayer::~QmitkVideoPlayer() { // save video preferences } bool QmitkVideoPlayer::IsExclusiveFunctionality() const { return false; } void QmitkVideoPlayer::CreateQtPartControl( QWidget* parent ) { // retrieve old preferences m_VideoSource = mitk::OpenCVVideoSource::New(); m_VideoBackground = new QmitkVideoBackground(m_VideoSource); m_VideoBackground->setParent(parent); QVBoxLayout* layout = new QVBoxLayout; m_OpenCVVideoControls = new QmitkOpenCVVideoControls(m_VideoBackground, this->GetActiveStdMultiWidget()); layout->addWidget( m_OpenCVVideoControls ); parent->setLayout( layout ); } void QmitkVideoPlayer::StdMultiWidgetAvailable( QmitkStdMultiWidget& stdMultiWidget ) { m_OpenCVVideoControls->SetStdMultiWidget( &stdMultiWidget ); -} \ No newline at end of file +} diff --git a/Plugins/org.mitk.gui.qt.igtexamples/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.igtexamples/src/internal/mitkPluginActivator.h index 4a81939ee0..dc7ad4f70c 100644 --- a/Plugins/org.mitk.gui.qt.igtexamples/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.igtexamples/src/internal/mitkPluginActivator.h @@ -1,39 +1,39 @@ /*=================================================================== 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 MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include #include namespace mitk { class MITK_LOCAL PluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // PluginActivator } -#endif // MITKPLUGINACTIVATOR_H \ No newline at end of file +#endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.h b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.h index 1468052c2a..e082d4029c 100644 --- a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.h +++ b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.h @@ -1,161 +1,161 @@ /*=================================================================== 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 QmitkMITKIGTTrackingToolboxView_h #define QmitkMITKIGTTrackingToolboxView_h #include #include #include "ui_QmitkMITKIGTTrackingToolboxViewControls.h" //mitk headers #include #include #include #include //QT headers #include /*! \brief QmitkMITKIGTTrackingToolboxView This is the view of the bundle IGT Tracking Toolbox. The IGT Tracking Toolbox can be used to access tracking devices with MITK-IGT. The Tracking Toolbox can be used to log tracking data in XML or CSV format for measurement purposes. The Tracking Toolbox further allows for visualization of tools with given surfaces in combination with the NaviagtionToolManager. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkMITKIGTTrackingToolboxView : public QmitkFunctionality { // 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: static const std::string VIEW_ID; QmitkMITKIGTTrackingToolboxView(); QmitkMITKIGTTrackingToolboxView(const QmitkMITKIGTTrackingToolboxView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } virtual ~QmitkMITKIGTTrackingToolboxView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: /** @brief This slot is called if the user wants to load a new tool file. A new window opens where the user can choose a file. If the chosen file is corrupt or not valid the user gets an error message. If the file was loaded successfully the tools are show in the tool status widget. */ void OnLoadTools(); /** @brief This slot tries to start tracking with the current device. If start tracking fails the user gets an error message and tracking stays off.*/ void OnStartTracking(); /** @brief This slot stops tracking. If tracking is not strated it does nothing.*/ void OnStopTracking(); /** @brief This slot is called if the user want's to choose a file name for logging. A new windows to navigate through the file system and choose a file opens.*/ void OnChooseFileClicked(); /** @brief This slot starts logging. Logging is only possible if a device is tracking. If not the logging mechanism start when the start tracking is called.*/ void StartLogging(); /** @brief This slot stops logging. If logging is not running it does nothing.*/ void StopLogging(); /** @brief This slot enables / disables UI elements depending on the tracking device after a device is changed.*/ void OnTrackingDeviceChanged(); - /** @brief This slot selects the Tracking Volume appropriate for a given model */ - void OnTrackingVolumeChanged(QString qstr); + /** @brief This slot selects the Tracking Volume appropriate for a given model */ + void OnTrackingVolumeChanged(QString qstr); /** @brief Shows or hides the tracking volume according to the checkboxe's state */ void OnShowTrackingVolumeChanged(); /** @brief This slot auto detects tools of a NDI Aurora tracking device. If tools where found they will be stored internally as a tool storage. The user is also asked if he wants to save this tool storage to load it later. Only call it if a Aurora device was configured because other devices don't support auto detection.*/ void OnAutoDetectTools(); /** @brief Slot for tracking timer. The timer updates the IGT pipline and also the logging filter if logging is activated.*/ void UpdateTrackingTimer(); /** @brief Resets the Tracking Tools: this means all tools are removed. */ void OnResetTools(); /** @brief Opens a dialog where a new navigation tool can be created. */ void OnAddSingleTool(); /** @brief This slot is called if the user finishes the creation of a new tool. */ void OnAddSingleToolFinished(); /** @brief This slot is called if the user cancels the creation of a new tool. */ void OnAddSingleToolCanceled(); - + protected: Ui::QmitkMITKIGTTrackingToolboxViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; bool m_tracking; ///> bool which is true if tracking is running, false if not bool m_logging; ///> bool which is true if logging is running, false if not int m_loggedFrames; ///> stores the current number of logged frames if logging is on mitk::NavigationToolStorage::Pointer m_toolStorage; ///>stores the loaded tools mitk::DataNode::Pointer m_TrackingVolumeNode; ///>holds the data node of the tracking volume if volume is visualized /** @brief Shows a message box with the text given as parameter. */ void MessageBox(std::string s); /** @brief reinits the view globally. */ void GlobalReinit(); //members for the filter pipeline mitk::TrackingDeviceSource::Pointer m_TrackingDeviceSource; ///> member for the source of the IGT pipeline mitk::NavigationDataObjectVisualizationFilter::Pointer m_ToolVisualizationFilter; ///> holds the tool visualization filter (second filter of the IGT pipeline) mitk::NavigationDataRecorder::Pointer m_loggingFilter; ///> holds the logging filter if logging is on (third filter of the IGT pipeline) /** @brief This timer updates the IGT pipline and also the logging filter if logging is activated.*/ QTimer* m_TrackingTimer; //help methods for enable/disable buttons void DisableLoggingButtons(); void EnableLoggingButtons(); void DisableOptionsButtons(); void EnableOptionsButtons(); void EnableTrackingConfigurationButtons(); void DisableTrackingConfigurationButtons(); }; -#endif // _QMITKMITKIGTTRACKINGTOOLBOXVIEW_H_INCLUDED \ No newline at end of file +#endif // _QMITKMITKIGTTRACKINGTOOLBOXVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.igttracking/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.igttracking/src/internal/mitkPluginActivator.cpp index 3d1226ca47..331d6c03a3 100644 --- a/Plugins/org.mitk.gui.qt.igttracking/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.igttracking/src/internal/mitkPluginActivator.cpp @@ -1,42 +1,42 @@ /*=================================================================== 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 "mitkPluginActivator.h" #include #include "QmitkMITKIGTNavigationToolManagerView.h" #include "QmitkMITKIGTTrackingToolboxView.h" #include "QmitkNavigationDataPlayerView.h" namespace mitk { void PluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkMITKIGTNavigationToolManagerView, context) BERRY_REGISTER_EXTENSION_CLASS( QmitkMITKIGTTrackingToolboxView , context) BERRY_REGISTER_EXTENSION_CLASS( QmitkNavigationDataPlayerView , context) } void PluginActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } -Q_EXPORT_PLUGIN2(org_mitk_gui_qt_igttracking, mitk::PluginActivator) \ No newline at end of file +Q_EXPORT_PLUGIN2(org_mitk_gui_qt_igttracking, mitk::PluginActivator) diff --git a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperPluginActivator.cpp b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperPluginActivator.cpp index b17a1ed35f..534093b4e8 100644 --- a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperPluginActivator.cpp @@ -1,35 +1,35 @@ /*=================================================================== 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 "mitkImageCropperPluginActivator.h" #include "QmitkImageCropper.h" #include namespace mitk { void ImageCropperPluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS( QmitkImageCropper, context ) } void ImageCropperPluginActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } -Q_EXPORT_PLUGIN2(org_mitk_gui_qt_imagecropper, mitk::ImageCropperPluginActivator) \ No newline at end of file +Q_EXPORT_PLUGIN2(org_mitk_gui_qt_imagecropper, mitk::ImageCropperPluginActivator) diff --git a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperPluginActivator.h b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperPluginActivator.h index 615c3627da..dea2011691 100644 --- a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/mitkImageCropperPluginActivator.h @@ -1,38 +1,38 @@ /*=================================================================== 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 MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include namespace mitk { class ImageCropperPluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // PluginActivator } -#endif // MITKPLUGINACTIVATOR_H \ No newline at end of file +#endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/mitkImageNavigatorPluginActivator.cpp b/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/mitkImageNavigatorPluginActivator.cpp index 624a2b18e0..e68135c5cc 100644 --- a/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/mitkImageNavigatorPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/mitkImageNavigatorPluginActivator.cpp @@ -1,36 +1,36 @@ /*=================================================================== 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 "mitkImageNavigatorPluginActivator.h" #include "QmitkImageNavigatorView.h" #include namespace mitk { void ImageNavigatorPluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkImageNavigatorView, context) } void ImageNavigatorPluginActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } -Q_EXPORT_PLUGIN2(org_mitk_gui_qt_imagenavigator, mitk::ImageNavigatorPluginActivator) \ No newline at end of file +Q_EXPORT_PLUGIN2(org_mitk_gui_qt_imagenavigator, mitk::ImageNavigatorPluginActivator) diff --git a/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/mitkImageNavigatorPluginActivator.h b/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/mitkImageNavigatorPluginActivator.h index 9498cf4a2f..7762893d20 100644 --- a/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/mitkImageNavigatorPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.imagenavigator/src/internal/mitkImageNavigatorPluginActivator.h @@ -1,38 +1,38 @@ /*=================================================================== 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 MITKIMAGENAVIGATORPLUGINACTIVATOR_H #define MITKIMAGENAVIGATORPLUGINACTIVATOR_H #include namespace mitk { class ImageNavigatorPluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // ImageNavigatorPluginActivator } -#endif // MITKIMAGENAVIGATORPLUGINACTIVATOR_H \ No newline at end of file +#endif // MITKIMAGENAVIGATORPLUGINACTIVATOR_H 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 839aec247d..a43b5445c3 100644 --- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp +++ b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp @@ -1,319 +1,319 @@ /*=================================================================== 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 "mitkShaderRepository.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include #include #include #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() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL) { 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; mitk::ShaderRepository::GetGlobalShaderRepository(); } 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(); 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(); } /* // subscribe for property change events itk::MemberCommand::Pointer propertyModifiedCommand = itk::MemberCommand::New(); propertyModifiedCommand->SetCallbackFunction(this, &QmitkPropertiesTableModel::PropertyModified); m_PropertyModifiedObserverTags[it->first] = it->second.first->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand); itk::MemberCommand::Pointer propertyModifiedCommand = itk::MemberCommand::New(); propertyModifiedCommand->SetCallbackFunction(this, &QmitkDataStorageTableModel::PropertyModified); mitk::BaseProperty* visibilityProperty = (*it)->GetProperty("visible"); if(visibilityProperty) m_PropertyModifiedObserverTags[visibilityProperty] = visibilityProperty->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand); mitk::BaseProperty* nameProperty = (*it)->GetProperty("name"); if(nameProperty) m_PropertyModifiedObserverTags[nameProperty] = nameProperty->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand); for(mitk::PropertyList::PropertyMap::const_iterator it=m_PropertyList->GetMap()->begin() ; it!=m_PropertyList->GetMap()->end() ; it++) { // add relevant property column values m_PropertyListElements.push_back((*it)); // subscribe for property change events itk::MemberCommand::Pointer propertyModifiedCommand = itk::MemberCommand::New(); propertyModifiedCommand->SetCallbackFunction(this, &QmitkPropertiesTableModel::PropertyModified); m_PropertyModifiedObserverTags[it->first] = it->second.first->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand);*/ 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::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkMITKSurfaceMaterialEditorView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkMITKSurfaceMaterialEditorView::CreateConnections() { } void QmitkMITKSurfaceMaterialEditorView::Activated() { QmitkFunctionality::Activated(); } void QmitkMITKSurfaceMaterialEditorView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkMITKSurfaceMaterialEditorView::OnSelectionChanged(std::vector 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(); -} \ No newline at end of file +} diff --git a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.cpp b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.cpp index 4166af0e23..2e63746d3f 100644 --- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.cpp @@ -1,36 +1,36 @@ /*=================================================================== 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 "mitkMaterialEditorPluginActivator.h" #include "QmitkMITKSurfaceMaterialEditorView.h" #include namespace mitk { void MaterialEditorPluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkMITKSurfaceMaterialEditorView, context) } void MaterialEditorPluginActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } -Q_EXPORT_PLUGIN2(org_mitk_gui_qt_materialeditor, mitk::MaterialEditorPluginActivator) \ No newline at end of file +Q_EXPORT_PLUGIN2(org_mitk_gui_qt_materialeditor, mitk::MaterialEditorPluginActivator) diff --git a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.h b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.h index 0f3ebd15b0..7bd2e9448a 100644 --- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.h @@ -1,38 +1,38 @@ /*=================================================================== 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 MITKMATERIALEDITORPLUGINACTIVATOR_H #define MITKMATERIALEDITORPLUGINACTIVATOR_H #include namespace mitk { class MaterialEditorPluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // MaterialEditorPluginActivator } -#endif // MITKMATERIALEDITORPLUGINACTIVATOR_H \ No newline at end of file +#endif // MITKMATERIALEDITORPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/mitkPluginActivator.cpp index 8dbdb06016..3dcc698ee0 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/mitkPluginActivator.cpp @@ -1,37 +1,37 @@ /*=================================================================== 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 "mitkPluginActivator.h" #include "QmitkMeasurementView.h" #include "QmitkImageStatisticsView.h" #include namespace mitk { void PluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkMeasurementView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkImageStatisticsView, context) } void PluginActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } -Q_EXPORT_PLUGIN2(org.mitk.gui.qt.measurementtoolbox, mitk::PluginActivator) \ No newline at end of file +Q_EXPORT_PLUGIN2(org.mitk.gui.qt.measurementtoolbox, mitk::PluginActivator) diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/mitkPluginActivator.h index 4a81939ee0..dc7ad4f70c 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/mitkPluginActivator.h @@ -1,39 +1,39 @@ /*=================================================================== 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 MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include #include namespace mitk { class MITK_LOCAL PluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // PluginActivator } -#endif // MITKPLUGINACTIVATOR_H \ No newline at end of file +#endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/mitkMovieMakerPluginActivator.h b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/mitkMovieMakerPluginActivator.h index 503382257a..793021c1c1 100644 --- a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/mitkMovieMakerPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/mitkMovieMakerPluginActivator.h @@ -1,38 +1,38 @@ /*=================================================================== 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 MITKMOVIEMAKERPLUGINACTIVATOR_H #define MITKMOVIEMAKERPLUGINACTIVATOR_H #include namespace mitk { class MovieMakerPluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // MovieMakerPluginActivator } -#endif // MITKMOVIEMAKERPLUGINACTIVATOR_H \ No newline at end of file +#endif // MITKMOVIEMAKERPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/mitkPluginActivator.cpp index 40bfc956f4..0d0b043c28 100644 --- a/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/mitkPluginActivator.cpp @@ -1,36 +1,36 @@ /*=================================================================== 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 "mitkPluginActivator.h" #include "QmitkPointSetInteractionView.h" #include namespace mitk { void PluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkPointSetInteractionView, context) } void PluginActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } -Q_EXPORT_PLUGIN2(org_mitk_gui_qt_pointsetinteraction, mitk::PluginActivator) \ No newline at end of file +Q_EXPORT_PLUGIN2(org_mitk_gui_qt_pointsetinteraction, mitk::PluginActivator) diff --git a/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/mitkPluginActivator.h index 40b59d188b..819b89117b 100644 --- a/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.pointsetinteraction/src/internal/mitkPluginActivator.h @@ -1,39 +1,39 @@ /*=================================================================== 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 MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include #include namespace mitk { class MITK_LOCAL PluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // PluginActivator } -#endif // MITKPLUGINACTIVATOR_H \ No newline at end of file +#endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.python.console/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.python.console/src/internal/mitkPluginActivator.h index 179331f8af..64df836537 100644 --- a/Plugins/org.mitk.gui.qt.python.console/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.python.console/src/internal/mitkPluginActivator.h @@ -1,40 +1,40 @@ /*=================================================================== 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 MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include #include namespace mitk { class MITK_LOCAL PluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // PluginActivator } -#endif // MITKPLUGINACTIVATOR_H \ No newline at end of file +#endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp index 4444d4141d..a3ed165e5c 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp @@ -1,443 +1,432 @@ /*=================================================================== 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 "QmitkStdMultiWidgetEditor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include class QmitkStdMultiWidgetEditorPrivate { public: QmitkStdMultiWidgetEditorPrivate(); ~QmitkStdMultiWidgetEditorPrivate(); QmitkStdMultiWidget* m_StdMultiWidget; QmitkMouseModeSwitcher* m_MouseModeToolbar; std::string m_FirstBackgroundColor; std::string m_SecondBackgroundColor; bool m_MenuWidgetsEnabled; berry::IPartListener::Pointer m_PartListener; QHash m_RenderWindows; }; struct QmitkStdMultiWidgetPartListener : public berry::IPartListener { berryObjectMacro(QmitkStdMultiWidgetPartListener) QmitkStdMultiWidgetPartListener(QmitkStdMultiWidgetEditorPrivate* dd) : d(dd) {} Events::Types GetPartEventTypes() const { return Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartClosed (berry::IWorkbenchPartReference::Pointer partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); if (d->m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { d->m_StdMultiWidget->RemovePlanesFromDataStorage(); stdMultiWidgetEditor->RequestActivateMenuWidget(false); } } } void PartHidden (berry::IWorkbenchPartReference::Pointer partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); if (d->m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { d->m_StdMultiWidget->RemovePlanesFromDataStorage(); stdMultiWidgetEditor->RequestActivateMenuWidget(false); } } } void PartVisible (berry::IWorkbenchPartReference::Pointer partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); if (d->m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { d->m_StdMultiWidget->AddPlanesToDataStorage(); stdMultiWidgetEditor->RequestActivateMenuWidget(true); } } } private: QmitkStdMultiWidgetEditorPrivate* const d; }; QmitkStdMultiWidgetEditorPrivate::QmitkStdMultiWidgetEditorPrivate() : m_StdMultiWidget(0), m_MouseModeToolbar(0) , m_MenuWidgetsEnabled(false) , m_PartListener(new QmitkStdMultiWidgetPartListener(this)) {} QmitkStdMultiWidgetEditorPrivate::~QmitkStdMultiWidgetEditorPrivate() { } const std::string QmitkStdMultiWidgetEditor::EDITOR_ID = "org.mitk.editors.stdmultiwidget"; QmitkStdMultiWidgetEditor::QmitkStdMultiWidgetEditor() : d(new QmitkStdMultiWidgetEditorPrivate) { } QmitkStdMultiWidgetEditor::~QmitkStdMultiWidgetEditor() { this->GetSite()->GetPage()->RemovePartListener(d->m_PartListener); } QmitkStdMultiWidget* QmitkStdMultiWidgetEditor::GetStdMultiWidget() { return d->m_StdMultiWidget; } QmitkRenderWindow *QmitkStdMultiWidgetEditor::GetActiveRenderWindow() const { if (d->m_StdMultiWidget) return d->m_StdMultiWidget->GetRenderWindow1(); return 0; } QHash QmitkStdMultiWidgetEditor::GetRenderWindows() const { return d->m_RenderWindows; } QmitkRenderWindow *QmitkStdMultiWidgetEditor::GetRenderWindow(const QString &id) const { if (d->m_RenderWindows.contains(id)) return d->m_RenderWindows[id]; return 0; } mitk::Point3D QmitkStdMultiWidgetEditor::GetSelectedPosition(const QString & /*id*/) const { return d->m_StdMultiWidget->GetCrossPosition(); } void QmitkStdMultiWidgetEditor::SetSelectedPosition(const mitk::Point3D &pos, const QString &/*id*/) { d->m_StdMultiWidget->MoveCrossToPosition(pos); } void QmitkStdMultiWidgetEditor::EnableDecorations(bool enable, const QStringList &decorations) { if (decorations.isEmpty() || decorations.contains(DECORATION_BORDER)) { enable ? d->m_StdMultiWidget->EnableColoredRectangles() : d->m_StdMultiWidget->DisableColoredRectangles(); } if (decorations.isEmpty() || decorations.contains(DECORATION_LOGO)) { enable ? d->m_StdMultiWidget->EnableDepartmentLogo() : d->m_StdMultiWidget->DisableDepartmentLogo(); } if (decorations.isEmpty() || decorations.contains(DECORATION_MENU)) { d->m_StdMultiWidget->ActivateMenuWidget(enable); } if (decorations.isEmpty() || decorations.contains(DECORATION_BACKGROUND)) { enable ? d->m_StdMultiWidget->EnableGradientBackground() : d->m_StdMultiWidget->DisableGradientBackground(); } } bool QmitkStdMultiWidgetEditor::IsDecorationEnabled(const QString &decoration) const { if (decoration == DECORATION_BORDER) { return d->m_StdMultiWidget->IsColoredRectanglesEnabled(); } else if (decoration == DECORATION_LOGO) { return d->m_StdMultiWidget->IsColoredRectanglesEnabled(); } else if (decoration == DECORATION_MENU) { return d->m_StdMultiWidget->IsMenuWidgetEnabled(); } else if (decoration == DECORATION_BACKGROUND) { return d->m_StdMultiWidget->GetGradientBackgroundFlag(); } return false; } QStringList QmitkStdMultiWidgetEditor::GetDecorations() const { QStringList decorations; decorations << DECORATION_BORDER << DECORATION_LOGO << DECORATION_MENU << DECORATION_BACKGROUND; return decorations; } mitk::SlicesRotator* QmitkStdMultiWidgetEditor::GetSlicesRotator() const { return d->m_StdMultiWidget->GetSlicesRotator(); } mitk::SlicesSwiveller* QmitkStdMultiWidgetEditor::GetSlicesSwiveller() const { return d->m_StdMultiWidget->GetSlicesSwiveller(); } void QmitkStdMultiWidgetEditor::EnableSlicingPlanes(bool enable) { d->m_StdMultiWidget->SetWidgetPlanesVisibility(enable); } bool QmitkStdMultiWidgetEditor::IsSlicingPlanesEnabled() const { mitk::DataNode::Pointer node = this->d->m_StdMultiWidget->GetWidgetPlane1(); if (node.IsNotNull()) { bool visible = false; node->GetVisibility(visible, 0); return visible; } else { return false; } } void QmitkStdMultiWidgetEditor::EnableLinkedNavigation(bool enable) { enable ? d->m_StdMultiWidget->EnableNavigationControllerEventListening() : d->m_StdMultiWidget->DisableNavigationControllerEventListening(); } bool QmitkStdMultiWidgetEditor::IsLinkedNavigationEnabled() const { return d->m_StdMultiWidget->IsCrosshairNavigationEnabled(); } void QmitkStdMultiWidgetEditor::CreateQtPartControl(QWidget* parent) { if (d->m_StdMultiWidget == 0) { QHBoxLayout* layout = new QHBoxLayout(parent); layout->setContentsMargins(0,0,0,0); if (d->m_MouseModeToolbar == NULL) { d->m_MouseModeToolbar = new QmitkMouseModeSwitcher(parent); // delete by Qt via parent layout->addWidget(d->m_MouseModeToolbar); } d->m_StdMultiWidget = new QmitkStdMultiWidget(parent); d->m_RenderWindows.insert("transversal", d->m_StdMultiWidget->GetRenderWindow1()); d->m_RenderWindows.insert("sagittal", d->m_StdMultiWidget->GetRenderWindow2()); d->m_RenderWindows.insert("coronal", d->m_StdMultiWidget->GetRenderWindow3()); d->m_RenderWindows.insert("3d", d->m_StdMultiWidget->GetRenderWindow4()); d->m_MouseModeToolbar->setMouseModeSwitcher( d->m_StdMultiWidget->GetMouseModeSwitcher() ); connect( d->m_MouseModeToolbar, SIGNAL( MouseModeSelected(mitk::MouseModeSwitcher::MouseMode) ), d->m_StdMultiWidget, SLOT( MouseModeSelected(mitk::MouseModeSwitcher::MouseMode) ) ); layout->addWidget(d->m_StdMultiWidget); mitk::DataStorage::Pointer ds = this->GetDataStorage(); // Tell the multiWidget which (part of) the tree to render d->m_StdMultiWidget->SetDataStorage(ds); // Initialize views as transversal, sagittal, coronar to all data objects in DataStorage // (from top-left to bottom) mitk::TimeSlicedGeometry::Pointer geo = ds->ComputeBoundingGeometry3D(ds->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); // Initialize bottom-right view as 3D view d->m_StdMultiWidget->GetRenderWindow4()->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D ); // Enable standard handler for levelwindow-slider d->m_StdMultiWidget->EnableStandardLevelWindow(); // Add the displayed views to the tree to see their positions // in 2D and 3D d->m_StdMultiWidget->AddDisplayPlaneSubTree(); d->m_StdMultiWidget->EnableNavigationControllerEventListening(); // Store the initial visibility status of the menu widget. d->m_MenuWidgetsEnabled = d->m_StdMultiWidget->IsMenuWidgetEnabled(); this->GetSite()->GetPage()->AddPartListener(d->m_PartListener); berry::IPreferences::Pointer prefs = this->GetPreferences(); this->OnPreferencesChanged(dynamic_cast(prefs.GetPointer())); this->RequestUpdate(); } } void QmitkStdMultiWidgetEditor::OnPreferencesChanged(const berry::IBerryPreferences* prefs) { // enable change of logo std::string departmentLogoLocation = prefs->Get("DepartmentLogo",""); if (departmentLogoLocation.empty()) { d->m_StdMultiWidget->DisableDepartmentLogo(); } else { d->m_StdMultiWidget->SetDepartmentLogoPath(departmentLogoLocation.c_str()); d->m_StdMultiWidget->EnableDepartmentLogo(); } // preferences for gradient background float color = 255.0; QString firstColorName = QString::fromStdString (prefs->GetByteArray("first background color", "")); QColor firstColor(firstColorName); mitk::Color upper; if (firstColorName=="") // default values { upper[0] = 0.1; upper[1] = 0.1; upper[2] = 0.1; } else { upper[0] = firstColor.red() / color; upper[1] = firstColor.green() / color; upper[2] = firstColor.blue() / color; } QString secondColorName = QString::fromStdString (prefs->GetByteArray("second background color", "")); QColor secondColor(secondColorName); mitk::Color lower; if (secondColorName=="") // default values { lower[0] = 0.5; lower[1] = 0.5; lower[2] = 0.5; } else { lower[0] = secondColor.red() / color; lower[1] = secondColor.green() / color; lower[2] = secondColor.blue() / color; } d->m_StdMultiWidget->SetGradientBackgroundColors(upper, lower); d->m_StdMultiWidget->EnableGradientBackground(); // Set preferences respecting zooming and padding bool constrainedZooming = prefs->GetBool("Use constrained zooming and padding", false); mitk::RenderingManager::GetInstance()->SetConstrainedPaddingZooming(constrainedZooming); 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::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible"); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); // level window setting bool showLevelWindowWidget = prefs->GetBool("Show level/window widget", true); if (showLevelWindowWidget) { d->m_StdMultiWidget->EnableStandardLevelWindow(); } else { d->m_StdMultiWidget->DisableStandardLevelWindow(); } // mouse modes toolbar bool newMode = prefs->GetBool("PACS like mouse interaction", false); d->m_MouseModeToolbar->setVisible( newMode ); d->m_StdMultiWidget->GetMouseModeSwitcher()->SetInteractionScheme( newMode ? mitk::MouseModeSwitcher::PACS : mitk::MouseModeSwitcher::MITK ); } void QmitkStdMultiWidgetEditor::SetFocus() { if (d->m_StdMultiWidget != 0) d->m_StdMultiWidget->setFocus(); } void QmitkStdMultiWidgetEditor::RequestActivateMenuWidget(bool on) { if (d->m_StdMultiWidget) { if (on) { d->m_StdMultiWidget->ActivateMenuWidget(d->m_MenuWidgetsEnabled); } else { d->m_MenuWidgetsEnabled = d->m_StdMultiWidget->IsMenuWidgetEnabled(); d->m_StdMultiWidget->ActivateMenuWidget(false); } } } -bool QmitkStdMultiWidgetEditor::IsMenuWidgetEnabled() -{ - bool enabled = false; - - if (d->m_StdMultiWidget) - { - enabled = d->m_StdMultiWidget->IsMenuWidgetEnabled(); - } - - return enabled; -} diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h index 8e59ef2db8..8ef9b88c1e 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h @@ -1,121 +1,120 @@ /*=================================================================== 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 QMITKSTDMULTIWIDGETEDITOR_H_ #define QMITKSTDMULTIWIDGETEDITOR_H_ #include #include #include class QmitkStdMultiWidget; class QmitkMouseModeSwitcher; class QmitkStdMultiWidgetEditorPrivate; /** * \ingroup org_mitk_gui_qt_stdmultiwidgeteditor */ class ORG_MITK_GUI_QT_STDMULTIWIDGETEDITOR QmitkStdMultiWidgetEditor : public QmitkAbstractRenderEditor, public mitk::ILinkedRenderWindowPart { Q_OBJECT public: berryObjectMacro(QmitkStdMultiWidgetEditor) static const std::string EDITOR_ID; QmitkStdMultiWidgetEditor(); ~QmitkStdMultiWidgetEditor(); QmitkStdMultiWidget* GetStdMultiWidget(); /// \brief If on=true will request the QmitkStdMultiWidget set the Menu widget to /// whatever was the last known enabled state, and if on=false will turn the Menu widget off. void RequestActivateMenuWidget(bool on); - bool IsMenuWidgetEnabled(); // ------------------- mitk::IRenderWindowPart ---------------------- /** * \see mitk::IRenderWindowPart::GetActiveRenderWindow() */ QmitkRenderWindow* GetActiveRenderWindow() const; /** * \see mitk::IRenderWindowPart::GetRenderWindows() */ QHash GetRenderWindows() const; /** * \see mitk::IRenderWindowPart::GetRenderWindow(QString) */ QmitkRenderWindow* GetRenderWindow(const QString& id) const; /** * \see mitk::IRenderWindowPart::GetSelectionPosition() */ mitk::Point3D GetSelectedPosition(const QString& id = QString()) const; /** * \see mitk::IRenderWindowPart::SetSelectedPosition() */ void SetSelectedPosition(const mitk::Point3D& pos, const QString& id = QString()); /** * \see mitk::IRenderWindowPart::EnableDecorations() */ void EnableDecorations(bool enable, const QStringList& decorations = QStringList()); /** * \see mitk::IRenderWindowPart::IsDecorationEnabled() */ bool IsDecorationEnabled(const QString& decoration) const; /** * \see mitk::IRenderWindowPart::GetDecorations() */ QStringList GetDecorations() const; // ------------------- mitk::ILinkedRenderWindowPart ---------------------- mitk::SlicesRotator* GetSlicesRotator() const; mitk::SlicesSwiveller* GetSlicesSwiveller() const; void EnableSlicingPlanes(bool enable); bool IsSlicingPlanesEnabled() const; void EnableLinkedNavigation(bool enable); bool IsLinkedNavigationEnabled() const; protected: void SetFocus(); void OnPreferencesChanged(const berry::IBerryPreferences*); void CreateQtPartControl(QWidget* parent); private: const QScopedPointer d; }; #endif /*QMITKSTDMULTIWIDGETEDITOR_H_*/ diff --git a/Plugins/org.mitk.gui.qt.toftutorial/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.toftutorial/src/internal/mitkPluginActivator.cpp index 3a36bccdee..993d781b3c 100644 --- a/Plugins/org.mitk.gui.qt.toftutorial/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.toftutorial/src/internal/mitkPluginActivator.cpp @@ -1,35 +1,35 @@ /*=================================================================== 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 "mitkPluginActivator.h" #include #include "QmitkToFTutorialView.h" namespace mitk { void PluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkToFTutorialView, context) } void PluginActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } -Q_EXPORT_PLUGIN2(org_mitk_gui_qt_toftutorial, mitk::PluginActivator) \ No newline at end of file +Q_EXPORT_PLUGIN2(org_mitk_gui_qt_toftutorial, mitk::PluginActivator) diff --git a/Plugins/org.mitk.gui.qt.toftutorial/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.toftutorial/src/internal/mitkPluginActivator.h index f8fc02a880..ca951ddd3f 100644 --- a/Plugins/org.mitk.gui.qt.toftutorial/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.toftutorial/src/internal/mitkPluginActivator.h @@ -1,40 +1,40 @@ /*=================================================================== 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 MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include #include namespace mitk { class MITK_LOCAL PluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // PluginActivator } -#endif // MITKPLUGINACTIVATOR_H \ No newline at end of file +#endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.tofutil/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.tofutil/src/internal/mitkPluginActivator.cpp index f643e95240..ca65edbeee 100644 --- a/Plugins/org.mitk.gui.qt.tofutil/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.tofutil/src/internal/mitkPluginActivator.cpp @@ -1,35 +1,35 @@ /*=================================================================== 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 "mitkPluginActivator.h" #include #include "QmitkToFUtilView.h" namespace mitk { void PluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkToFUtilView, context) } void PluginActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } -Q_EXPORT_PLUGIN2(org_mitk_gui_qt_tofutil, mitk::PluginActivator) \ No newline at end of file +Q_EXPORT_PLUGIN2(org_mitk_gui_qt_tofutil, mitk::PluginActivator) diff --git a/Plugins/org.mitk.gui.qt.tofutil/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.tofutil/src/internal/mitkPluginActivator.h index f8fc02a880..ca951ddd3f 100644 --- a/Plugins/org.mitk.gui.qt.tofutil/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.tofutil/src/internal/mitkPluginActivator.h @@ -1,40 +1,40 @@ /*=================================================================== 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 MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include #include namespace mitk { class MITK_LOCAL PluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); }; // PluginActivator } -#endif // MITKPLUGINACTIVATOR_H \ No newline at end of file +#endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.inputdevices.wiimote/src/internal/mitkWiiMoteActivator.cpp b/Plugins/org.mitk.inputdevices.wiimote/src/internal/mitkWiiMoteActivator.cpp index 513d7fc4e6..ee5ed335ba 100644 --- a/Plugins/org.mitk.inputdevices.wiimote/src/internal/mitkWiiMoteActivator.cpp +++ b/Plugins/org.mitk.inputdevices.wiimote/src/internal/mitkWiiMoteActivator.cpp @@ -1,190 +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 "mitkWiiMoteActivator.h" #include "mitkWiiMoteAddOn.h" //mitk #include "mitkGlobalInteraction.h" #include "mitkCoreExtConstants.h" #include #include #include mitk::WiiMoteActivator::WiiMoteActivator() : m_IsRegistered(false) , m_Controller(mitk::WiiMoteVtkCameraController::New()) , m_Interactor(NULL) , m_Node(NULL) { m_PrefService = berry::Platform::GetServiceRegistry() .GetServiceById(berry::IPreferencesService::ID); } mitk::WiiMoteActivator::~WiiMoteActivator() { } bool mitk::WiiMoteActivator::RegisterInputDevice() { if(!this->m_IsRegistered) { mitk::WiiMoteAddOn::GetInstance()->ActivateWiiMotes(); mitk::EventMapper* eventMapper(mitk::GlobalInteraction::GetInstance()->GetEventMapper()); if (eventMapper != NULL) { eventMapper->AddEventMapperAddOn(mitk::WiiMoteAddOn::GetInstance()); this->m_IsRegistered = true; } else { MITK_ERROR << "Eventmapper is not initialized!"; return false; } } // get the current preferences m_WiiMotePreferencesNode = m_PrefService->GetSystemPreferences()->Node(CoreExtConstants::INPUTDEVICE_PREFERENCES); // modus change between Surface Interaction and VR Headtracking if(m_WiiMotePreferencesNode->GetBool(CoreExtConstants::WIIMOTE_SURFACEINTERACTION,false)) { if(mitk::GlobalInteraction::GetInstance()->ListenerRegistered(m_Controller)) { mitk::GlobalInteraction::GetInstance()->RemoveListener(m_Controller); } this->AddSurfaceInteractor(); } else { // Headtracking listener already registered if(!(mitk::GlobalInteraction::GetInstance()->ListenerRegistered(m_Controller))) { mitk::GlobalInteraction::GetInstance()->AddListener(m_Controller); } this->RemoveSurfaceInteractor(); } return true; } bool mitk::WiiMoteActivator::UnRegisterInputDevice() { if(this->m_IsRegistered) { mitk::WiiMoteAddOn::GetInstance()->DeactivateWiiMotes(); // remove Headtracking listener if(mitk::GlobalInteraction::GetInstance()->ListenerRegistered(m_Controller)) { mitk::GlobalInteraction::GetInstance()->RemoveListener(m_Controller); } this->RemoveSurfaceInteractor(); mitk::EventMapper* eventMapper(mitk::GlobalInteraction::GetInstance()->GetEventMapper()); if(eventMapper != NULL) { eventMapper->RemoveEventMapperAddOn(mitk::WiiMoteAddOn::GetInstance()); this->m_IsRegistered = false; } else { MITK_ERROR << "Eventmapper is not initialized!"; return false; } } return true; } mitk::DataStorage::Pointer mitk::WiiMoteActivator::GetDataStorage() { mitk::IDataStorageService::Pointer service = berry::Platform::GetServiceRegistry(). GetServiceById(mitk::IDataStorageService::ID); if (service.IsNotNull()) { return service->GetActiveDataStorage()->GetDataStorage(); } return 0; } void mitk::WiiMoteActivator::AddSurfaceInteractor() { mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New(); // model was designed by Patrick Grubb std::string fileName = MITK_ROOT; fileName += "Modules/InputDevices/WiiMote/WiiMoteModel.obj"; try { nodeReader->SetFileName(fileName.c_str()); nodeReader->Update(); m_Node = nodeReader->GetOutput(); if(m_Interactor.IsNull()) { m_Interactor = mitk::WiiMoteInteractor::New("WiiMoteSurfaceInteraction",m_Node); } m_Node->SetInteractor(m_Interactor); this->GetDataStorage()->Add(m_Node); if(!(mitk::GlobalInteraction::GetInstance()->InteractorRegistered(m_Interactor))) { mitk::GlobalInteraction::GetInstance()->AddInteractor(m_Interactor); } mitk::WiiMoteAddOn::GetInstance()->SetWiiMoteSurfaceIModus(true); } catch(...) { MITK_ERROR << "Wiimote Surface Interaction could not be initialized"; } } void mitk::WiiMoteActivator::RemoveSurfaceInteractor() { try { if(m_Node.IsNotNull()) { this->GetDataStorage()->Remove(m_Node); } if(m_Interactor.IsNotNull() && mitk::GlobalInteraction::GetInstance()->InteractorRegistered(m_Interactor)) { mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_Interactor); } mitk::WiiMoteAddOn::GetInstance()->SetWiiMoteSurfaceIModus(false); } catch(...) { MITK_ERROR << "Wiimote Surface Interactor could not be properly removed"; } -} \ No newline at end of file +} diff --git a/SuperBuild.cmake b/SuperBuild.cmake index 6e77967417..337e11469a 100644 --- a/SuperBuild.cmake +++ b/SuperBuild.cmake @@ -1,310 +1,302 @@ #----------------------------------------------------------------------------- # Convenient macro allowing to download a file #----------------------------------------------------------------------------- macro(downloadFile url dest) file(DOWNLOAD ${url} ${dest} STATUS status) list(GET status 0 error_code) list(GET status 1 error_msg) if(error_code) message(FATAL_ERROR "error: Failed to download ${url} - ${error_msg}") endif() endmacro() #----------------------------------------------------------------------------- # MITK Prerequisites #----------------------------------------------------------------------------- if(UNIX AND NOT APPLE) - #----------------------------- libxt-dev -------------------- - include(${CMAKE_ROOT}/Modules/CheckIncludeFile.cmake) - - set(CMAKE_REQUIRED_INCLUDES "/usr/include/X11/") - CHECK_INCLUDE_FILE("StringDefs.h" STRING_DEFS_H) - if(NOT STRING_DEFS_H) - message(FATAL_ERROR "error: could not find StringDefs.h provided by libxt-dev") - endif() + + include(mitkFunctionCheckPackageHeader) + + # Check for libxt-dev + mitkFunctionCheckPackageHeader(StringDefs.h libxt-dev /usr/include/X11/) - set(CMAKE_REQUIRED_INCLUDES "/usr/include/") - CHECK_INCLUDE_FILE("tiff.h" TIFF_H) - if(NOT TIFF_H) - message(FATAL_ERROR "error: could not find tiff.h - libtiff4-dev needs to be installed") - endif() + # Check for libtiff4-dev + mitkFunctionCheckPackageHeader(tiff.h libtiff4-dev) - CHECK_INCLUDE_FILE("tcpd.h" LIB_WRAP) - if(NOT LIB_WRAP) - message(STATUS "Could not find tcpd.h - if this is missing in the build libwrap0-dev needs to be installed") - endif() + # Check for libwrap0-dev + mitkFunctionCheckPackageHeader(tcpd.h libwrap0-dev) endif() #----------------------------------------------------------------------------- # ExternalProjects #----------------------------------------------------------------------------- set(external_projects VTK GDCM CableSwig ITK Boost DCMTK CTK OpenCV MITKData ) set(MITK_USE_CableSwig ${MITK_USE_Python}) set(MITK_USE_GDCM 1) set(MITK_USE_ITK 1) set(MITK_USE_VTK 1) foreach(proj VTK GDCM CableSwig ITK DCMTK CTK OpenCV) if(MITK_USE_${proj}) set(EXTERNAL_${proj}_DIR "${${proj}_DIR}" CACHE PATH "Path to ${proj} build directory") mark_as_advanced(EXTERNAL_${proj}_DIR) if(EXTERNAL_${proj}_DIR) set(${proj}_DIR ${EXTERNAL_${proj}_DIR}) endif() endif() endforeach() if(MITK_USE_Boost) set(EXTERNAL_BOOST_ROOT "${BOOST_ROOT}" CACHE PATH "Path to Boost directory") mark_as_advanced(EXTERNAL_BOOST_ROOT) if(EXTERNAL_BOOST_ROOT) set(BOOST_ROOT ${EXTERNAL_BOOST_ROOT}) endif() endif() if(BUILD_TESTING) set(EXTERNAL_MITK_DATA_DIR "${MITK_DATA_DIR}" CACHE PATH "Path to the MITK data directory") mark_as_advanced(EXTERNAL_MITK_DATA_DIR) if(EXTERNAL_MITK_DATA_DIR) set(MITK_DATA_DIR ${EXTERNAL_MITK_DATA_DIR}) endif() endif() # Look for git early on, if needed if((BUILD_TESTING AND NOT EXTERNAL_MITK_DATA_DIR) OR (MITK_USE_CTK AND NOT EXTERNAL_CTK_DIR)) find_package(Git REQUIRED) endif() #----------------------------------------------------------------------------- # External project settings #----------------------------------------------------------------------------- include(ExternalProject) set(ep_base "${CMAKE_BINARY_DIR}/CMakeExternals") set_property(DIRECTORY PROPERTY EP_BASE ${ep_base}) set(ep_install_dir ${ep_base}/Install) #set(ep_build_dir ${ep_base}/Build) set(ep_source_dir ${ep_base}/Source) #set(ep_parallelism_level) set(ep_build_shared_libs ON) set(ep_build_testing OFF) if(NOT MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL) set(MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL http://mitk.org/download/thirdparty) endif() # Compute -G arg for configuring external projects with the same CMake generator: if(CMAKE_EXTRA_GENERATOR) set(gen "${CMAKE_EXTRA_GENERATOR} - ${CMAKE_GENERATOR}") else() set(gen "${CMAKE_GENERATOR}") endif() # Use this value where semi-colons are needed in ep_add args: set(sep "^^") ## if(MSVC90 OR MSVC10) set(ep_common_C_FLAGS "${CMAKE_C_FLAGS} /bigobj /MP") set(ep_common_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj /MP") else() set(ep_common_C_FLAGS "${CMAKE_C_FLAGS} -DLINUX_EXTRA") set(ep_common_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DLINUX_EXTRA") endif() set(ep_common_args -DBUILD_TESTING:BOOL=${ep_build_testing} -DCMAKE_INSTALL_PREFIX:PATH=${ep_install_dir} -DBUILD_SHARED_LIBS:BOOL=ON -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} -DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER} -DCMAKE_CXX_COMPILER:FILEPATH=${CMAKE_CXX_COMPILER} -DCMAKE_C_FLAGS:STRING=${ep_common_C_FLAGS} -DCMAKE_CXX_FLAGS:STRING=${ep_common_CXX_FLAGS} #debug flags -DCMAKE_CXX_FLAGS_DEBUG:STRING=${CMAKE_CXX_FLAGS_DEBUG} -DCMAKE_C_FLAGS_DEBUG:STRING=${CMAKE_C_FLAGS_DEBUG} #release flags -DCMAKE_CXX_FLAGS_RELEASE:STRING=${CMAKE_CXX_FLAGS_RELEASE} -DCMAKE_C_FLAGS_RELEASE:STRING=${CMAKE_C_FLAGS_RELEASE} #relwithdebinfo -DCMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -DCMAKE_C_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_C_FLAGS_RELWITHDEBINFO} ) # Include external projects foreach(p ${external_projects}) include(CMakeExternals/${p}.cmake) endforeach() #----------------------------------------------------------------------------- # Set superbuild boolean args #----------------------------------------------------------------------------- set(mitk_cmake_boolean_args BUILD_SHARED_LIBS WITH_COVERAGE BUILD_TESTING MITK_USE_QT MITK_BUILD_ALL_PLUGINS MITK_BUILD_ALL_APPS MITK_BUILD_TUTORIAL # Deprecated. Use MITK_BUILD_EXAMPLES instead MITK_BUILD_EXAMPLES MITK_USE_Boost MITK_USE_SYSTEM_Boost MITK_USE_BLUEBERRY MITK_USE_CTK MITK_USE_DCMTK MITK_USE_OpenCV MITK_USE_Python ) #----------------------------------------------------------------------------- # Create the final variable containing superbuild boolean args #----------------------------------------------------------------------------- set(mitk_superbuild_boolean_args) foreach(mitk_cmake_arg ${mitk_cmake_boolean_args}) list(APPEND mitk_superbuild_boolean_args -D${mitk_cmake_arg}:BOOL=${${mitk_cmake_arg}}) endforeach() if(MITK_BUILD_ALL_PLUGINS) list(APPEND mitk_superbuild_boolean_args -DBLUEBERRY_BUILD_ALL_PLUGINS:BOOL=ON) endif() #----------------------------------------------------------------------------- # MITK Utilities #----------------------------------------------------------------------------- set(proj MITK-Utilities) ExternalProject_Add(${proj} DOWNLOAD_COMMAND "" CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" DEPENDS # Mandatory dependencies ${VTK_DEPENDS} ${ITK_DEPENDS} # Optionnal dependencies ${Boost_DEPENDS} ${CTK_DEPENDS} ${DCMTK_DEPENDS} ${OpenCV_DEPENDS} ${MITK-Data_DEPENDS} ) #----------------------------------------------------------------------------- # MITK Configure #----------------------------------------------------------------------------- if(MITK_INITIAL_CACHE_FILE) set(mitk_initial_cache_arg -C "${MITK_INITIAL_CACHE_FILE}") endif() set(mitk_optional_cache_args ) foreach(type RUNTIME ARCHIVE LIBRARY) if(DEFINED CTK_PLUGIN_${type}_OUTPUT_DIRECTORY) list(APPEND mitk_optional_cache_args -DCTK_PLUGIN_${type}_OUTPUT_DIRECTORY:PATH=${CTK_PLUGIN_${type}_OUTPUT_DIRECTORY}) endif() endforeach() set(proj MITK-Configure) ExternalProject_Add(${proj} LIST_SEPARATOR ^^ DOWNLOAD_COMMAND "" CMAKE_GENERATOR ${gen} CMAKE_CACHE_ARGS ${ep_common_args} ${mitk_superbuild_boolean_args} ${mitk_optional_cache_args} -DMITK_USE_SUPERBUILD:BOOL=OFF -DMITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY:PATH=${MITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY} -DMITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY:PATH=${MITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY} -DMITK_CMAKE_ARCHIVE_OUTPUT_DIRECTORY:PATH=${MITK_CMAKE_ARCHIVE_OUTPUT_DIRECTORY} -DCTEST_USE_LAUNCHERS:BOOL=${CTEST_USE_LAUNCHERS} -DMITK_CTEST_SCRIPT_MODE:STRING=${MITK_CTEST_SCRIPT_MODE} -DMITK_SUPERBUILD_BINARY_DIR:PATH=${MITK_BINARY_DIR} -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE} -DMITK_KWSTYLE_EXECUTABLE:FILEPATH=${MITK_KWSTYLE_EXECUTABLE} -DMITK_MODULES_TO_BUILD:INTERNAL=${MITK_MODULES_TO_BUILD} -DCTK_DIR:PATH=${CTK_DIR} -DDCMTK_DIR:PATH=${DCMTK_DIR} -DVTK_DIR:PATH=${VTK_DIR} # FindVTK expects VTK_DIR -DITK_DIR:PATH=${ITK_DIR} # FindITK expects ITK_DIR -DOpenCV_DIR:PATH=${OpenCV_DIR} -DGDCM_DIR:PATH=${GDCM_DIR} -DBOOST_ROOT:PATH=${BOOST_ROOT} -DMITK_USE_Boost_LIBRARIES:STRING=${MITK_USE_Boost_LIBRARIES} -DMITK_DATA_DIR:PATH=${MITK_DATA_DIR} -DMITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES} -DMITK_ACCESSBYITK_FLOATING_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES} -DMITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES} -DMITK_ACCESSBYITK_DIMENSIONS:STRING=${MITK_ACCESSBYITK_DIMENSIONS} CMAKE_ARGS ${mitk_initial_cache_arg} SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} BINARY_DIR ${CMAKE_BINARY_DIR}/MITK-build BUILD_COMMAND "" INSTALL_COMMAND "" DEPENDS MITK-Utilities ) #----------------------------------------------------------------------------- # MITK #----------------------------------------------------------------------------- if(CMAKE_GENERATOR MATCHES ".*Makefiles.*") set(mitk_build_cmd "$(MAKE)") else() set(mitk_build_cmd ${CMAKE_COMMAND} --build ${CMAKE_CURRENT_BINARY_DIR}/MITK-build --config ${CMAKE_CFG_INTDIR}) endif() if(NOT DEFINED SUPERBUILD_EXCLUDE_MITKBUILD_TARGET OR NOT SUPERBUILD_EXCLUDE_MITKBUILD_TARGET) set(MITKBUILD_TARGET_ALL_OPTION "ALL") else() set(MITKBUILD_TARGET_ALL_OPTION "") endif() add_custom_target(MITK-build ${MITKBUILD_TARGET_ALL_OPTION} COMMAND ${mitk_build_cmd} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/MITK-build DEPENDS MITK-Configure ) #----------------------------------------------------------------------------- # Custom target allowing to drive the build of the MITK project itself #----------------------------------------------------------------------------- add_custom_target(MITK COMMAND ${mitk_build_cmd} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/MITK-build ) diff --git a/Utilities/glew/mitkGlew.c b/Utilities/glew/mitkGlew.c index 56819beaa0..08d893fa5d 100644 --- a/Utilities/glew/mitkGlew.c +++ b/Utilities/glew/mitkGlew.c @@ -1,5 +1,5 @@ #ifdef glew_EXPORTS #define GLEW_BUILD #endif -#include "external/src/glew.c" \ No newline at end of file +#include "external/src/glew.c" diff --git a/Utilities/mbilog/mbilog.h b/Utilities/mbilog/mbilog.h index a926f40003..3c7206dcc6 100644 --- a/Utilities/mbilog/mbilog.h +++ b/Utilities/mbilog/mbilog.h @@ -1,225 +1,225 @@ /*=================================================================== 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 _MBILOG_H #define _MBILOG_H #include #include "mbilogExports.h" #include "mbilogBackendBase.h" #include "mbilogBackendCout.h" #include "mbilogLogMessage.h" #include "mbilogLoggingTypes.h" #include "mbilogConfig.h" namespace mbilog { /** \brief Registeres a backend to the mbi logging mechanism. If a backend is registered here, all mbilog messages * are relayed to this backend through the method ProcessMessage. If no backend is registered the default * backend is used. */ void MBILOG_DLL_API RegisterBackend(BackendBase* backend); /** \brief Unregisters a backend. */ void MBILOG_DLL_API UnregisterBackend(BackendBase* backend); /** \brief Distributes the given message to all registered backends. Should only be called by objects * of the class pseudo stream. */ void MBILOG_DLL_API DistributeToBackends(LogMessage &l); - /** Documentation - * \brief An object of this class simulates a std::cout stream. This means messages can be added by - * using the bit shift operator (<<). Should only be used by the macros defined in the file mbilog.h - * \ingroup mbilog - */ + /** + * \brief An object of this class simulates a std::cout stream. This means messages can be added by + * using the bit shift operator (<<). Should only be used by the macros defined in the file mbilog.h + * \ingroup mbilog + */ class MBILOG_DLL_API PseudoStream { protected: bool disabled; LogMessage msg; std::stringstream ss; public: inline PseudoStream( int level, const char* filePath, int lineNumber, const char* functionName) : disabled(false) , msg(LogMessage(level,filePath,lineNumber,functionName)) , ss(std::stringstream::out) { } - /** \brief The message which is stored in the member ss is written to the backend. */ + /** \brief The message which is stored in the member ss is written to the backend. */ inline ~PseudoStream() { if(!disabled) { msg.message = ss.str(); msg.moduleName = MBILOG_MODULENAME; DistributeToBackends(msg); } } - /** \brief Definition of the bit shift operator for this class.*/ + /** \brief Definition of the bit shift operator for this class.*/ template inline PseudoStream& operator<<(const T& data) { if(!disabled) { std::locale C("C"); std::locale originalLocale = ss.getloc(); ss.imbue(C); ss << data; ss.imbue( originalLocale ); } return *this; } - /** \brief Definition of the bit shift operator for this class (for non const data).*/ + /** \brief Definition of the bit shift operator for this class (for non const data).*/ template inline PseudoStream& operator<<(T& data) { if(!disabled) { std::locale C("C"); std::locale originalLocale = ss.getloc(); ss.imbue(C); ss << data; ss.imbue( originalLocale ); } return *this; } - /** \brief Definition of the bit shift operator for this class (for functions).*/ + /** \brief Definition of the bit shift operator for this class (for functions).*/ inline PseudoStream& operator<<(std::ostream& (*func)(std::ostream&)) { if(!disabled) { std::locale C("C"); std::locale originalLocale = ss.getloc(); ss.imbue(C); ss << func; ss.imbue( originalLocale ); } return *this; } - /** \brief Sets the category of this PseudoStream object. If there already is a category it is appended, seperated by a dot.*/ + /** \brief Sets the category of this PseudoStream object. If there already is a category it is appended, seperated by a dot.*/ inline PseudoStream& operator()(const char *category) { if(!disabled) { if(msg.category.length()) msg.category+="."; msg.category+=category; } return *this; } - /** \brief Enables/disables the PseudoStream. If set to false parsing and output is suppressed. */ + /** \brief Enables/disables the PseudoStream. If set to false parsing and output is suppressed. */ inline PseudoStream& operator()(bool enabled) { disabled|=!enabled; return *this; } }; - /** Documentation - * \brief An object of this class simulates a std::cout stream but does nothing. This class is for dummy objects, bit shift - * operators are availiable but doing nothing. Should only be used by the macros defined in the file mbilog.h - * \ingroup mbilog - */ + /** + * \brief An object of this class simulates a std::cout stream but does nothing. This class is for dummy objects, bit shift + * operators are availiable but doing nothing. Should only be used by the macros defined in the file mbilog.h + * \ingroup mbilog + */ class MBILOG_DLL_API NullStream { public: template inline NullStream& operator<<(const T& /*data*/) { return *this; } template inline NullStream& operator<<(T& /*data*/) { return *this; } inline NullStream& operator<<(std::ostream& (*)(std::ostream&)) { return *this; } inline NullStream& operator()(const char *) { return *this; } inline NullStream& operator()(bool) { return *this; } }; // /** \brief templated backend: one can define a class and a method to create a new backend. */ // template // struct DelegateBackend : public BackendBase // { // // typedef void(T::*Callback)(const mbilog::LogMessage&); // // DelegateBackend(T* obj, Callback callback) : m_Obj(obj), m_Callback(callback) // { // } // // void ProcessMessage(const mbilog::LogMessage& msg) // { // m_Obj->*m_Callback(msg); // } // // private: // // T* m_Obj; // Callback m_Callback; // }; } /** \brief Macros for different message levels. Creates an instance of class PseudoStream with the corresponding message level. * Other parameters are the name of the source file, line of the source code and function name which are generated * by the compiler. */ #define MBI_INFO mbilog::PseudoStream(mbilog::Info,__FILE__,__LINE__,__FUNCTION__) #define MBI_WARN mbilog::PseudoStream(mbilog::Warn,__FILE__,__LINE__,__FUNCTION__) #define MBI_ERROR mbilog::PseudoStream(mbilog::Error,__FILE__,__LINE__,__FUNCTION__) #define MBI_FATAL mbilog::PseudoStream(mbilog::Fatal,__FILE__,__LINE__,__FUNCTION__) /** \brief Macro for the debug messages. The messages are disabled if the cmake variable MBILOG_ENABLE_DEBUG is false. */ #ifdef MBILOG_ENABLE_DEBUG #define MBI_DEBUG mbilog::PseudoStream(mbilog::Debug,__FILE__,__LINE__,__FUNCTION__) #else #define MBI_DEBUG true ? mbilog::NullStream() : mbilog::NullStream() //this is magic by markus #endif -#endif \ No newline at end of file +#endif diff --git a/Utilities/mbilog/mbilogBackendBase.h b/Utilities/mbilog/mbilogBackendBase.h index cedb80efa3..abbfbdac69 100644 --- a/Utilities/mbilog/mbilogBackendBase.h +++ b/Utilities/mbilog/mbilogBackendBase.h @@ -1,49 +1,50 @@ /*=================================================================== 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 _mbilogBackendBase_H #define _mbilogBackendBase_H #include "mbilogExports.h" #include "mbilogLogMessage.h" namespace mbilog{ - /** Documentation + /** * \brief This class is an interface for logging backends that can be registered in the mbi logging mechanism. * * \ingroup mbilog */ class MBILOG_DLL_API BackendBase { public: virtual ~BackendBase(); - /** \brief This method is called by the mbi logging mechanism if the object is registered in - * the mbi logging mechanism and a logging message is emitted. - * - * \param logMessage Logging message which was emitted. - * - */ + /** + * \brief This method is called by the mbi logging mechanism if the object is registered in + * the mbi logging mechanism and a logging message is emitted. + * + * \param logMessage Logging message which was emitted. + * + */ virtual void ProcessMessage(const mbilog::LogMessage& logMessage)=0; }; } -#endif \ No newline at end of file +#endif diff --git a/Utilities/mbilog/mbilogBackendCout.h b/Utilities/mbilog/mbilogBackendCout.h index 3f0bd5e994..677061b23c 100644 --- a/Utilities/mbilog/mbilogBackendCout.h +++ b/Utilities/mbilog/mbilogBackendCout.h @@ -1,65 +1,66 @@ /*=================================================================== 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 _mbilogBackendCout_H #define _mbilogBackendCout_H #include #include "mbilogExports.h" #include "mbilogTextBackendBase.h" #include "mbilogLogMessage.h" #include "mbilogLoggingTypes.h" namespace mbilog{ - /** Documentation + /** * \brief Default backend of the mbi logging mechanism. This backend is used if no other backend is registered. * The backend formats the logging messages to a normal string and writes them to std::cout. * \ingroup mbilog */ class MBILOG_DLL_API BackendCout : public TextBackendBase { public: BackendCout(); virtual ~BackendCout(); /** \brief This method is called by the mbi logging mechanism if the object is registered in * the mbi logging mechanism and a logging message is emitted. The method formats the * logging messages to a normal string (depending on formatting mode) and writes it to std::cout. * * \param logMessage Logging message. */ virtual void ProcessMessage(const mbilog::LogMessage &l ); - /** \brief Sets the formatting mode. If true long messages will be displayed. Default is false (short/smart messages). - * Long messages provide all informations and are also capable to be postproccessed (e.g. in a web viewer). - */ + /** \brief Sets the formatting mode. If true long messages will be displayed. Default is false (short/smart messages). + * Long messages provide all informations and are also capable to be postproccessed (e.g. in a web viewer). + */ void SetFull(bool full); private: - /** \brief The formatting mode of this backend. True is full/long message formatting mode. False is short/smart - * message formatting mode */ + /** \brief The formatting mode of this backend. True is full/long message formatting mode. False is short/smart + * message formatting mode + */ bool m_useFullOutput; }; } -#endif \ No newline at end of file +#endif diff --git a/Utilities/mbilog/mbilogLogMessage.h b/Utilities/mbilog/mbilogLogMessage.h index 88bec4a5d5..e96b19804f 100644 --- a/Utilities/mbilog/mbilogLogMessage.h +++ b/Utilities/mbilog/mbilogLogMessage.h @@ -1,81 +1,81 @@ /*=================================================================== 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 _mbilogLogMessage_H #define _mbilogLogMessage_H #include #include "mbilogExports.h" namespace mbilog{ /** Documentation * \brief An object of this class represents a single logging message (logging event) of the * mbi logging mechanism. Logging message should only be generated by the macros in the class mbilog.h * * \ingroup mbilog */ //todo convert to Struct class MBILOG_DLL_API LogMessage { public: //TODO: all member names m_[...] - - /** \brief Logging level which is defined in the enum mbilogLoggingTypes.h TODO: convert to enum.*/ + + /** \brief Logging level which is defined in the enum mbilogLoggingTypes.h TODO: convert to enum.*/ const int level; - - // the data of the following section is generated by the c-compiler - - /** \brief File name of the source file where the logging message was emitted which is generated by the macros in file mbilog.h*/ - const char* filePath; + + // the data of the following section is generated by the c-compiler + + /** \brief File name of the source file where the logging message was emitted which is generated by the macros in file mbilog.h*/ + const char* filePath; /** \brief Line of the source source file where the logging message was emitted which is generated by the macros in file mbilog.h*/ const int lineNumber; - /** \brief Name of the method where the logging message was emitted which is generated by the macros in file mbilog.h*/ + /** \brief Name of the method where the logging message was emitted which is generated by the macros in file mbilog.h*/ const char* functionName; - - // the data of the following section is generated by the mitk module system - - /** \brief Name of the module where the logging message was emitted which is generated by the macros in file mbilog.h. Is empty if there module defined.*/ + + // the data of the following section is generated by the mitk module system + + /** \brief Name of the module where the logging message was emitted which is generated by the macros in file mbilog.h. Is empty if there module defined.*/ const char* moduleName; - - // user parameters - - /** \brief Category of the logging event, which was defined by the user.*/ + + // user parameters + + /** \brief Category of the logging event, which was defined by the user.*/ std::string category; - + /** \brief The actual logging message.*/ - std::string message; + std::string message; LogMessage( const int _level, const char* _filePath, const int _lineNumber, const char* _functionName ) : level(_level) , filePath(_filePath) , lineNumber(_lineNumber) , functionName(_functionName) { } }; } -#endif \ No newline at end of file +#endif diff --git a/Utilities/mbilog/mbilogLoggingTypes.h b/Utilities/mbilog/mbilogLoggingTypes.h index dcbe9be490..3197e5f408 100644 --- a/Utilities/mbilog/mbilogLoggingTypes.h +++ b/Utilities/mbilog/mbilogLoggingTypes.h @@ -1,37 +1,37 @@ /*=================================================================== 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 _MBILOG_LOGGINGTYPES_H_ #define _MBILOG_LOGGINGTYPES_H_ namespace mbilog { /** \brief This enum defines the message/event levels of the mbi logging mechanism. - * Info: TODO + * Info: TODO * Warn: TODO * Error: TODO * Fatal: TODO * Debug: TODO */ enum { Info, Warn, Error, Fatal, Debug }; } -#endif \ No newline at end of file +#endif diff --git a/Utilities/mbilog/mbilogTextBackendBase.h b/Utilities/mbilog/mbilogTextBackendBase.h index b17a1e48e4..7ac0bb2140 100644 --- a/Utilities/mbilog/mbilogTextBackendBase.h +++ b/Utilities/mbilog/mbilogTextBackendBase.h @@ -1,79 +1,79 @@ /*=================================================================== 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 _mbilogTextBackendBase_H #define _mbilogTextBackendBase_H #include "mbilogExports.h" #include "mbilogBackendBase.h" namespace mbilog{ /** Documentation * \brief This class is an abstract superclass for logging text backends. It adds string formatting methods * to the backend interface BackendBase. Accordingly backends that inherit from this class can be * registered in the mbi logging mechanism. * * \ingroup mbilog */ class MBILOG_DLL_API TextBackendBase : public BackendBase { public: virtual ~TextBackendBase(); - /** \brief This method is called by the mbi logging mechanism if the object is registered in - * the mbi logging mechanism and a logging message is emitted. - * - * \param logMessage Logging message which was emitted. - * - */ + /** \brief This method is called by the mbi logging mechanism if the object is registered in + * the mbi logging mechanism and a logging message is emitted. + * + * \param logMessage Logging message which was emitted. + * + */ virtual void ProcessMessage(const mbilog::LogMessage& logMessage)=0; protected: /** \brief Method formats the given LogMessage in the smart/short format and writes it to std::cout. - * \param threadID Can be set to the threadID where the logging message was emitted. Is 0 by default. - */ - void FormatSmart(const LogMessage &l,int threadID=0); - - /** \brief Method formats the given LogMessage in the full/long format and writes it to std::cout. - * \param threadID Can be set to the threadID where the logging message was emitted. Is 0 by default. - */ - void FormatFull(const LogMessage &l,int threadID=0); - - /** \brief Method formats the given LogMessage in the smart/short format and writes it to the given std::ostream. - * \param threadID Can be set to the threadID where the logging message was emitted. Is 0 by default. - */ + * \param threadID Can be set to the threadID where the logging message was emitted. Is 0 by default. + */ + void FormatSmart(const LogMessage &l,int threadID=0); + + /** \brief Method formats the given LogMessage in the full/long format and writes it to std::cout. + * \param threadID Can be set to the threadID where the logging message was emitted. Is 0 by default. + */ + void FormatFull(const LogMessage &l,int threadID=0); + + /** \brief Method formats the given LogMessage in the smart/short format and writes it to the given std::ostream. + * \param threadID Can be set to the threadID where the logging message was emitted. Is 0 by default. + */ void FormatSmart(std::ostream &out, const LogMessage &l,int threadID=0); - /** \brief Method formats the given LogMessage in the full/long format and writes it to the given std::ostream. - * \param threadID Can be set to the threadID where the logging message was emitted. Is 0 by default. - */ - void FormatFull(std::ostream &out, const LogMessage &l,int threadID=0); + /** \brief Method formats the given LogMessage in the full/long format and writes it to the given std::ostream. + * \param threadID Can be set to the threadID where the logging message was emitted. Is 0 by default. + */ + void FormatFull(std::ostream &out, const LogMessage &l,int threadID=0); /** \brief Writes the system time to the given stream.*/ void AppendTimeStamp(std::ostream& out); - /** \brief Special variant of method FormatSmart which uses colored messages (only for windows).*/ - //TODO: implement for linux? - void FormatSmartWindows(const mbilog::LogMessage &l,int /*threadID*/); + /** \brief Special variant of method FormatSmart which uses colored messages (only for windows).*/ + //TODO: implement for linux? + void FormatSmartWindows(const mbilog::LogMessage &l,int /*threadID*/); }; } -#endif \ No newline at end of file +#endif diff --git a/Utilities/mbilog/mbilogTextDictionary.h b/Utilities/mbilog/mbilogTextDictionary.h index c3af69d457..f832346d85 100644 --- a/Utilities/mbilog/mbilogTextDictionary.h +++ b/Utilities/mbilog/mbilogTextDictionary.h @@ -1,249 +1,249 @@ /*=================================================================== 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 _MBILOG_TEXTDICTIONARY_H_ #define _MBILOG_TEXTDICTIONARY_H_ namespace mbilog { /** \brief This is a dictionary to replace long names of classes, * modules, etc. to shorter versions in the console output. */ static char *replace[] = { ".cpp", "", ".cxx", "", ".txx", "", ".h", "", ".hpp", "", ".hxx", "", ".c", "", "org.blueberry.", "", "org.mitk.gui.qt.", "", "org.mitk.", "", "qmitk", "", "mitk", "", "berry", "", "itk", "", "vtk", "", "qt", "", "object", "obj", "factory", "fac", "classes", "cls", "plugin", "plg", "widget", "wdgt", "interface", "itf", "service", "svc", "register", "reg", "perspective", "prs", "assessor", "ase", "atrophy", "atr", "bias", "bias", "field", "fld", "multi", "mlt", "contour", "cntr", "tools", "tls", "tool", "tl", "application", "app", "calculate", "calc", "subtract", "sub", "region", "reg", "tumor", "tum", "growing", "grow", "segmentation", "seg", "statistics", "stat", "imaging", "img", "image", "img", "diffusion", "dif", "registration", "reg", "navigation", "nav", "generation", "gen", "generator", "gen", "vector", "vec", "gradient", "grad", "flow", "flow", "paint", "pnt", "brush", "brsh", "volumetry", "vol", "volume", "vol", "mapper", "map", "filter", "flt", "surface", "sfc", "point", "pnt", "organ", "org", "multiple", "mlt", "corrector", "cor", "correction", "cor", "batch", "bat", "window", "wnd", "advisor", "adv", "editor", "edt", "material", "mat", "visualization", "vis", "measurement", "mes", "scene", "scn", "serialization", "ser", "deserializer", "dser", "serializer", "ser", "sandbox", "sb", "texture", "tex", "opengl", "ogl", "vessel", "vsl", "value", "val", "analysis", "ana", "patient", "pat", "body", "body", "diagnosis", "diag", "mesh", "mesh", "radial", "rad", "simple", "smp", "algorithms", "alg", "controllers", "con", "control", "con", "interactive", "ia", "interactions", "ia", "processing", "pro", "process", "pro", "rendering", "rnd", "renderer", "rnd", "render", "rnd", "datamanagement", "data", "management", "mng", "manager", "mng", "data", "data", "anatomy", "ana", "neuro", "neo", "automatic", "auto", "optimizer", "opt", "optimize", "opt", "binary", "bin", "liver", "liv", "lymph", "lym", "node", "node", "tree", "tree", "homogeneous", "hmgn", "threshold", "tsh", // "shapebased", "shp", "based", "bsd", "shape", "shp", "model", "mdl", "extension", "ext", "activator", "act", "dicom", "dicom", "browser", "brwr", "viewer", "view", "view", "view", "finder", "fnd", "indexer", "idx", "index", "idx", "rapid", "rpd", "gui", "gui", "slices", "slc", "slice", "slc", "about", "abt", "interpolator", "inp", "switcher", "swh", "planning", "plan", "planner", "plan", "plane", "pln", "plan", "plan", "workbench", "wrkbnc", "common", "com", "resection", "rsc", "translation", "trnsl", "rotation", "rot", "deformation", "dfrm", "shader", "shd", "repository", "rep", "initializer", "init", "dialog", "dlg", "download", "down", "upload", "up", "core", "core", "manual", "man", "leaf", "leaf", "internal", "int", "external", "ext", "platform", "pltfm", "method", "mthd", "pyramidal", "prmdl", "tracking", "trck", "track", "trck", "bspline", "bspl", "spline", "spl", "create", "crt", "erase", "ers", "auto", "auto", "crop", "crop", "file", "file", "io", "io", "2d", "2d", "3d", "3d", ".", "." }; } -#endif \ No newline at end of file +#endif diff --git a/Wrapping/CSwig/Core/wrap_mitkITKImageImport.cxx b/Wrapping/CSwig/Core/wrap_mitkITKImageImport.cxx index e8898c97b2..db3be577ef 100644 --- a/Wrapping/CSwig/Core/wrap_mitkITKImageImport.cxx +++ b/Wrapping/CSwig/Core/wrap_mitkITKImageImport.cxx @@ -1,50 +1,50 @@ #include "itkImage.h" #include "mitkITKImageImport.h" #ifdef CABLE_CONFIGURATION namespace _cable_ { const char* const group="ITKImageImport"; namespace wrappers { typedef mitk::ITKImageImport::Image> ITKImageImportD2; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportD2_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportD3; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportD3_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportF2; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportF2_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportF3; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportF3_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportUS2; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportUS2_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportUS3; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportUS3_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportUC2; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportUC2_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportUC3; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportUC3_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportUI2; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportUI2_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportUI3; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportUI3_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportUL2; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportUL2_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportUL3; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportUL3_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportSC2; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportSC2_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportSC3; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportSC3_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportSI2; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportSI2_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportSI3; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportSI3_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportSS2; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportSS2_Pointer; typedef mitk::ITKImageImport::Image> ITKImageImportSS3; typedef mitk::ITKImageImport::Image>::Pointer::SmartPointer ITKImageImportSS3_Pointer; } } -#endif \ No newline at end of file +#endif diff --git a/Wrapping/CSwig/Core/wrap_mitkImageToItk.cxx b/Wrapping/CSwig/Core/wrap_mitkImageToItk.cxx index cb235b0e8a..f32932ba3c 100644 --- a/Wrapping/CSwig/Core/wrap_mitkImageToItk.cxx +++ b/Wrapping/CSwig/Core/wrap_mitkImageToItk.cxx @@ -1,50 +1,50 @@ #include "itkImage.h" #include "mitkImageToItk.h" #ifdef CABLE_CONFIGURATION namespace _cable_ { const char* const group="ImageToItk"; namespace wrappers { typedef mitk::ImageToItk::Image> ImageToItkD2; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkD2_Pointer; typedef mitk::ImageToItk::Image> ImageToItkD3; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkD3_Pointer; typedef mitk::ImageToItk::Image> ImageToItkF2; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkF2_Pointer; typedef mitk::ImageToItk::Image> ImageToItkF3; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkF3_Pointer; typedef mitk::ImageToItk::Image> ImageToItkUS2; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkUS2_Pointer; typedef mitk::ImageToItk::Image> ImageToItkUS3; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkUS3_Pointer; typedef mitk::ImageToItk::Image> ImageToItkUC2; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkUC2_Pointer; typedef mitk::ImageToItk::Image> ImageToItkUC3; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkUC3_Pointer; typedef mitk::ImageToItk::Image> ImageToItkUI2; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkUI2_Pointer; typedef mitk::ImageToItk::Image> ImageToItkUI3; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkUI3_Pointer; typedef mitk::ImageToItk::Image> ImageToItkUL2; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkUL2_Pointer; typedef mitk::ImageToItk::Image> ImageToItkUL3; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkUL3_Pointer; typedef mitk::ImageToItk::Image> ImageToItkSC2; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkSC2_Pointer; typedef mitk::ImageToItk::Image> ImageToItkSC3; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkSC3_Pointer; typedef mitk::ImageToItk::Image> ImageToItkSI2; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkSI2_Pointer; typedef mitk::ImageToItk::Image> ImageToItkSI3; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkSI3_Pointer; typedef mitk::ImageToItk::Image> ImageToItkSS2; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkSS2_Pointer; typedef mitk::ImageToItk::Image> ImageToItkSS3; typedef mitk::ImageToItk::Image>::Pointer::SmartPointer ImageToItkSS3_Pointer; } } -#endif \ No newline at end of file +#endif diff --git a/Wrapping/CSwig/mitkCSwigMacros.h b/Wrapping/CSwig/mitkCSwigMacros.h index bb54eda3e0..9ee3b15842 100644 --- a/Wrapping/CSwig/mitkCSwigMacros.h +++ b/Wrapping/CSwig/mitkCSwigMacros.h @@ -1,26 +1,26 @@ #define MITK_WRAP_OBJECT(name) \ typedef mitk::name::name name; \ typedef mitk::name::Pointer::SmartPointer name##_Pointer; #define MITK_WRAP_OBJECT_WITH_SUPERCLASS(name) \ MITK_WRAP_OBJECT(name); \ typedef mitk::name::Superclass::Self name##_Superclass; \ typedef mitk::name::Superclass::Pointer::SmartPointer name##_Superclass_Pointer; #define MITK_WRAP_OBJECT1(name, wrapname) \ typedef mitk::name::name wrapname; \ typedef mitk::name::Pointer::SmartPointer wrapname##_Pointer; #define MITK_WRAP_OBJECT_WITH_SUPERCLASS1(name, wrapname) \ MITK_WRAP_OBJECT1(name, wrapname); \ typedef mitk::name::Superclass::Self wrapname##_Superclass; \ typedef mitk::name::Superclass::Pointer::SmartPointer wrapname##_Superclass_Pointer; #define ITK_WRAP_OBJECT(name) \ typedef itk::name::name name; \ typedef itk::name::Pointer::SmartPointer name##_Pointer; #define ITK_WRAP_OBJECT1(name, arg1, wrapname) \ typedef itk::name::name wrapname; \ -typedef itk::name::Pointer::SmartPointer wrapname##_Pointer \ No newline at end of file +typedef itk::name::Pointer::SmartPointer wrapname##_Pointer