diff --git a/Core/Code/Controllers/mitkRenderingManager.cpp b/Core/Code/Controllers/mitkRenderingManager.cpp index 7999def74b..9d345b2529 100644 --- a/Core/Code/Controllers/mitkRenderingManager.cpp +++ b/Core/Code/Controllers/mitkRenderingManager.cpp @@ -1,926 +1,926 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" #include "mitkProportionalTimeGeometry.h" #include #include -#include "mitkTypes.h" +#include "mitkNumericTypes.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( SliceNavigationController::New("dummy") ), 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); 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 ); // 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); 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 ); 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); } } } void RenderingManager::InitializeViewsByBoundingObjects( const DataStorage *ds) { if (!ds) return; // get all nodes that have not set "includeInBoundingBox" to false mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" , mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = ds->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeGeometry::Pointer bounds = ds->ComputeBoundingGeometry3D(rs, "visible"); // initialize the views to the bounding geometry this->InitializeViews(bounds); } //TODO_GOETZ // Remove old function, so only this one is working. bool RenderingManager ::InitializeViews( const Geometry3D * dataGeometry, RequestType type, bool preserveRoughOrientationInWorldSpace ) { ProportionalTimeGeometry::Pointer propTimeGeometry = ProportionalTimeGeometry::New(); propTimeGeometry->Initialize(dynamic_cast(dataGeometry->Clone().GetPointer()), 1); return InitializeViews(propTimeGeometry,type, preserveRoughOrientationInWorldSpace); } bool RenderingManager ::InitializeViews( const TimeGeometry * dataGeometry, RequestType type, bool /*preserveRoughOrientationInWorldSpace*/ ) { MITK_DEBUG << "initializing views"; bool boundingBoxInitialized = false; TimeGeometry::ConstPointer timeGeometry = dataGeometry; TimeGeometry::Pointer modifiedGeometry = NULL; if (dataGeometry!=NULL) { modifiedGeometry = dataGeometry->Clone(); } // //TODO_GOETZ previously this code section has been disabled by // a later asignment to geometry (e.g. timeGeometry) // This has been fixed during Geometry-1-Plattform Project // Propably this code is not working anymore, test!! /* if (dataGeometry && preserveRoughOrientationInWorldSpace) { // clone the input geometry assert(modifiedGeometry.IsNotNull()); // construct an affine transform from it Geometry3D::TransformType::Pointer transform = Geometry3D::TransformType::New(); assert( modifiedGeometry->GetGeometryForTimeStep(0)->GetIndexToWorldTransform() ); transform->SetMatrix( modifiedGeometry->GetGeometryForTimeStep(0)->GetIndexToWorldTransform()->GetMatrix() ); transform->SetOffset( modifiedGeometry->GetGeometryForTimeStep(0)->GetIndexToWorldTransform()->GetOffset() ); // get transform matrix Geometry3D::TransformType::MatrixType::InternalMatrixType& oldMatrix = const_cast< Geometry3D::TransformType::MatrixType::InternalMatrixType& > ( transform->GetMatrix().GetVnlMatrix() ); Geometry3D::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 ScalarType 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 Geometry3D::TransformType::MatrixType newMatrixITK( newMatrix ); transform->SetMatrix( newMatrixITK ); transform->SetOffset( offset ); modifiedGeometry->SetIndexToWorldTransform( transform ); geometry = modifiedGeometry; }*/ int warningLevel = vtkObject::GetGlobalWarningDisplay(); vtkObject::GlobalWarningDisplayOff(); if ( (timeGeometry.IsNotNull() ) && (const_cast< mitk::BoundingBox * >( timeGeometry->GetBoundingBoxInWorld())->GetDiagonalLength2() > mitk::eps) ) { boundingBoxInitialized = true; } if (timeGeometry.IsNotNull() ) {// make sure bounding box has an extent bigger than zero in any direction // clone the input geometry //Old Geometry3D::Pointer modifiedGeometry = dynamic_cast( dataGeometry->Clone().GetPointer() ); assert(modifiedGeometry.IsNotNull()); for (TimeStepType step = 0; step < modifiedGeometry->CountTimeSteps(); ++step) { Geometry3D::BoundsArrayType newBounds = modifiedGeometry->GetGeometryForTimeStep(step)->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; } } modifiedGeometry->GetGeometryForTimeStep(step)->SetBounds(newBounds); } } timeGeometry = 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, timeGeometry, boundingBoxInitialized, id ); } } if ( boundingBoxInitialized ) { m_TimeNavigationController->SetInputWorldTimeGeometry( timeGeometry ); } 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 Geometry3D * geometry, bool initializeGlobalTimeSNC ) { ProportionalTimeGeometry::Pointer propTimeGeometry = ProportionalTimeGeometry::New(); propTimeGeometry->Initialize(dynamic_cast(geometry->Clone().GetPointer()), 1); return InitializeView(renderWindow, propTimeGeometry, initializeGlobalTimeSNC ); } bool RenderingManager::InitializeView( vtkRenderWindow * renderWindow, const TimeGeometry * geometry, bool initializeGlobalTimeSNC ) { bool boundingBoxInitialized = false; int warningLevel = vtkObject::GetGlobalWarningDisplay(); vtkObject::GlobalWarningDisplayOff(); if ( (geometry != NULL ) && (const_cast< mitk::BoundingBox * >( geometry->GetBoundingBoxInWorld())->GetDiagonalLength2() > mitk::eps) ) { boundingBoxInitialized = true; } mitk::BaseRenderer *baseRenderer = mitk::BaseRenderer::GetInstance( renderWindow ); int id = baseRenderer->GetMapperID(); this->InternalViewInitialization( baseRenderer, geometry, boundingBoxInitialized, id ); if ( boundingBoxInitialized && initializeGlobalTimeSNC ) { m_TimeNavigationController->SetInputWorldTimeGeometry( 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::TimeGeometry *geometry, bool boundingBoxInitialized, int mapperID ) { mitk::SliceNavigationController *nc = baseRenderer->GetSliceNavigationController(); // Re-initialize view direction nc->SetViewDirectionToDefault(); if ( boundingBoxInitialized ) { // Set geometry for NC nc->SetInputWorldTimeGeometry( 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(); } } const SliceNavigationController* RenderingManager::GetTimeNavigationController() const { return m_TimeNavigationController.GetPointer(); } SliceNavigationController* RenderingManager::GetTimeNavigationController() { return m_TimeNavigationController.GetPointer(); } 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::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/Controllers/mitkSlicesRotator.h b/Core/Code/Controllers/mitkSlicesRotator.h index 67393ea6f5..42217a54bf 100644 --- a/Core/Code/Controllers/mitkSlicesRotator.h +++ b/Core/Code/Controllers/mitkSlicesRotator.h @@ -1,165 +1,165 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 SLICESROTATOR_H_HEADER_INCLUDED_C1C55A2F #define SLICESROTATOR_H_HEADER_INCLUDED_C1C55A2F #include #pragma GCC visibility push(default) #include #pragma GCC visibility pop -#include +#include namespace mitk { /** \brief Coordinates rotation of multiple visible rendering planes (represented as lines in other render windows). \ingroup NavigationControl This class takes care of several SliceNavigationControllers and handles slice selection / slice rotation. It is added as listener to GlobalInteraction by QmitkStdMultiWidget. The SlicesRotator class adds the possibility of slice rotation to the "normal" behaviour of SliceNavigationControllers (which is picking one plane from a stack of planes). This additional class SlicesRotator is needed, because one has to be aware of multiple "visible slices" (selected Geometry2Ds of some SliceNavigationControllers) in order to choose between rotation and slice selection. Such functionality could not be implemented by a single SliceNavigationController. Rotation is achieved by modifying (rotating) the generated TimeGeometry of the corresponding SliceNavigationControllers. \section mitkSlicesRotator_StandardCase The standard case: three orthogonal views (MPR) With SlicesRotator, the rule to choose between slice rotation and selection is simple: For a mouse down event, count the number of visible planes, which are "near" the cursor. If this number is 2 (one for the window, which currently holds the cursor, one for the intersection line of another visible slice), then initiate rotation, else select slices near the cursor. If the "LinkPlanes" flag is set, the rotation is applied to the planes of all registered SNCs, not only of the one associated with the directly selected plane. In contrast to the situation without the SlicesRotator, the SliceNavigationControllers are now NOT directly registered as listeners to GlobalInteraction. SlicesRotator is registered as a listener and decides whether something should be rotated or whether another slice should be selected. In the latter case, a PositionEvent is just forwarded to the SliceNavigationController. \section mitkSlicesRotator_GeneralizedCase The generalized case: any number of views Above section as well as the original implementation of this class assumes that we have exactly three 2D vies in our scene. This used to be the standard setup of the MITK associated application for a long time. With custom applications based on MITK it is easy to create different situations. One usual use case would be to have one extra render window display the contents of any of the other ones and behave exactly like it (could e.g. be used on a second screen). In this situation the above assumption "we rotate when there are exactly 2 slices close to the cursor" will not hold: since we always have two render windows displaying the exact same slice, the number of 2 is the minimum we get. Whenever the user clicks in one of those windows and the cursor is close to one of the orthogonal planes, we will get a count of 3 or more planes that are "close to the cursor". For the class to behave correctly, we actually need to distinguish three separate cases: 1. the cursor is not close to any orthogonal planes. This should result in slice selection. 2. the cursor is close to just one orthogonal plane OR multiple which are not distinguishable visually. This should result in rotation. 3. the cursor is close to multiple orthogonal planes which are rendered as distinguishable lines on the render window. This is the case when we hit the crosshair-center of the view. In this case, we need to also just select slices. \section mitkSlicesRotator_Solution Deciding between slice selection and rotation The "counting nearby lines in the renderwindow" can also work for the general case described above. Only one details needs to be accounted for: we must not count a line when it is identical to another line. I.e. we just count how many visible lines on the screen are very close to the cursor. When this number is 1, we rotate, otherwise we let the SliceNavigationControllers do their slice selection job. \sa SlicesSwiveller */ class MITK_CORE_EXPORT SlicesRotator : public SlicesCoordinator { public: mitkClassMacro(SlicesRotator, SlicesCoordinator); static Pointer New(); /** \brief New Macro with one parameter for creating this object with static New(..) method. Needs to be the "slices-rotator" pattern of StateMachine.xml to work as expected. **/ mitkNewMacro1Param(Self, const char*); /** \brief Callback for modifications in observed SliceNavigationControllers -- forwards to UpdateRotatableSNCs(). This method is called when an observed SliceNavigationController changes its world geometry. The connection is established by calling the other SliceNavigationController's method ConnectGeometrySendEvent (or similar). */ virtual void SetGeometry(const itk::EventObject& EventObject); /** \brief NOT USED by anything open-source. Deprecated. Highly obfuscated code. Use SliceNavigationController::ReorientSlices() instead! #Deprecated */ virtual void RotateToPoint( SliceNavigationController *rotationPlaneSNC, SliceNavigationController *rotatedPlaneSNC, const Point3D &point, bool linked = false ); protected: SlicesRotator(const char* machine); virtual ~SlicesRotator(); /** \brief Called from SlicesCoordinator after a new controller is added (to internal list m_SliceNavigationControllers). */ virtual void OnSliceControllerAdded(SliceNavigationController* snc); /* \brief Called from SlicesCoordinator after a new controller is being removed (to internal list m_SliceNavigationControllers). */ virtual void OnSliceControllerRemoved(SliceNavigationController* snc); /** \brief Check all observed SliceNavigationControllers: remember those that are rotatable in m_RotatableSNCs. */ virtual void UpdateRotatableSNCs(); // following methods called from superclass ExecuteAction bool DoSelectSlice(Action*, const StateEvent*); bool DoDecideBetweenRotationAndSliceSelection(Action*, const StateEvent*); bool DoStartRotation(Action*, const StateEvent*); bool DoEndRotation(Action*, const StateEvent*); bool DoRotationStep(Action*, const StateEvent*); SNCVector m_RotatableSNCs; /// all SNCs that currently have CreatedWorldGeometries, that can be rotated. SNCVector m_SNCsToBeRotated; /// all SNCs that will be rotated (exceptions are the ones parallel to the one being clicked) Point3D m_LastCursorPosition; /// used for calculation of the rotation angle Point3D m_CenterOfRotation; /// used for calculation of the rotation angle }; } // namespace #endif diff --git a/Core/Code/Controllers/mitkSlicesSwiveller.h b/Core/Code/Controllers/mitkSlicesSwiveller.h index 59e88f7a17..87345a56b9 100644 --- a/Core/Code/Controllers/mitkSlicesSwiveller.h +++ b/Core/Code/Controllers/mitkSlicesSwiveller.h @@ -1,119 +1,119 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 SLICESSWIVELLER_H_HEADER_INCLUDED #define SLICESSWIVELLER_H_HEADER_INCLUDED #include -#include +#include #pragma GCC visibility push(default) #include #pragma GCC visibility pop namespace mitk { /** * \brief Enables arbitrary rotation of visible slices around a swivel point * (for sliced geometries). * \ingroup NavigationControl * * This class takes care of several SliceNavigationControllers and handles * slice selection / slice rotation. It is added as listener to * GlobalInteraction by QmitkStdMultiWidget. * * The SlicesSwiveller class adds the possibility of slice rotation to the * "normal" behaviour of SliceNavigationControllers. This additional class * is needed, because one has to be aware of several "visible slices" * (selected Geometry2Ds of some SliceNavigationControllers) in order to * choose between rotation and slice selection. * * Rotation is achieved by modifying (rotating) the generated * TimeGeometry of the corresponding SliceNavigationController. * * With SlicesSwiveller, slice rotation works as follows: the user clicks onto * a 2D view (2D plane) and drags the mouse; the relative direction and angle * of the dragged mouse movement directly effects the rotation axis and * angle. If "LinkPlanes" is set to true, the rotation is applied to the * planes of all registered SNCs, not only of the one associated with the * plane clicked on. * * In contrast to the situation without the SlicesRotator, the * SliceNavigationControllers are now not directly registered as listeners to * GlobalInteraction. SlicesRotator is registered as a listener and decides * whether something should be rotated or whether another slice should be * selected. In the latter case, a PositionEvent is just forwarded to the * SliceNavigationController. * * \sa SlicesRotator */ class MITK_CORE_EXPORT SlicesSwiveller : public SlicesCoordinator { public: mitkClassMacro(SlicesSwiveller, SlicesCoordinator); static Pointer New(); /** * @brief New Macro with one parameter for creating this object with static New(..) method **/ mitkNewMacro1Param(Self, const char*); virtual void SetGeometry(const itk::EventObject& EventObject); protected: SlicesSwiveller(const char* machine); // clear list of controllers virtual ~SlicesSwiveller(); // check if the slices of this SliceNavigationController can be rotated (???) Possible virtual void OnSliceControllerAdded(SliceNavigationController* snc); virtual void OnSliceControllerRemoved(SliceNavigationController* snc); virtual void UpdateRelevantSNCs(); virtual bool ExecuteAction(Action * action, StateEvent const* stateEvent); /** All SNCs that currently have CreatedWorldGeometries, that can be rotated */ SNCVector m_RelevantSNCs; /** SNCs that will be rotated (clicked plane + all relevant others, if linked) */ SNCVector m_SNCsToBeRotated; Point3D m_LastCursorPosition; Point3D m_CenterOfRotation; Point2D m_ReferenceCursor; Vector3D m_RotationPlaneNormal; Vector3D m_RotationPlaneXVector; Vector3D m_RotationPlaneYVector; Vector3D m_PreviousRotationAxis; ScalarType m_PreviousRotationAngle; }; } // namespace #endif diff --git a/Core/Code/Controllers/mitkStepper.h b/Core/Code/Controllers/mitkStepper.h index 6e2b933efd..9651a5f9af 100644 --- a/Core/Code/Controllers/mitkStepper.h +++ b/Core/Code/Controllers/mitkStepper.h @@ -1,152 +1,152 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 STEPPER_H_HEADER_INCLUDED_C1E77191 #define STEPPER_H_HEADER_INCLUDED_C1E77191 #include #include -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include #include #include namespace mitk { /** * \brief Helper class to step through a list * * A helper class to step through a list. Does not contain the list, just the * position in the list (between 0 and GetSteps()). Provides methods like * First (go to the first element), Next (go to the next one), etc. * * Besides the actual number of steps, the stepper can also hold a stepping * range, indicating the scalar values corresponding to the covered steps. * For example, steppers are generally used to slice a dataset with a plane; * Hereby, Steps indicates the total number of steps (positions) available for * the plane, Pos indicates the current step, and Range indicates the physical * minimum and maximum values for the plane, in this case a value in mm. * * The range can also be supplied with a unit name (a string) which can be * used by classes providing information about the stepping (e.g. graphical * sliders). * * \ingroup NavigationControl */ class MITK_CORE_EXPORT Stepper : public itk::Object { public: mitkClassMacro(Stepper, itk::Object); itkFactorylessNewMacro(Self) itkCloneMacro(Self) itkGetMacro(Pos, unsigned int); virtual void SetPos(unsigned int pos) { // copied from itkMacro.h, itkSetClampMacro(...) unsigned int newPos; if ( m_Steps != 0 ) { newPos = (pos > m_Steps-1 ? m_Steps-1 : pos); } else { newPos = 0; } if (this->m_Pos != newPos ) { this->m_Pos = newPos ; this->Modified(); } } itkGetMacro(Steps, unsigned int); itkSetMacro(Steps, unsigned int); itkGetMacro(AutoRepeat, bool); itkSetMacro(AutoRepeat, bool); itkBooleanMacro(AutoRepeat); /** Causes the stepper to shift direction when the boundary is reached */ itkSetMacro(PingPong, bool); itkGetMacro(PingPong, bool); itkBooleanMacro(PingPong); /** If set to true, the Next() decreases the stepper and Previous() * decreases it */ itkSetMacro(InverseDirection, bool); itkGetMacro(InverseDirection, bool); itkBooleanMacro(InverseDirection); void SetRange( ScalarType min, ScalarType max ); void InvalidateRange(); ScalarType GetRangeMin() const; ScalarType GetRangeMax() const; bool HasValidRange() const; void RemoveRange(); bool HasRange() const; void SetUnitName( const char *unitName ); const char *GetUnitName() const; void RemoveUnitName(); bool HasUnitName() const; virtual void Next(); virtual void Previous(); virtual void First(); virtual void Last(); protected: Stepper(); virtual ~Stepper(); void Increase(); void Decrease(); unsigned int m_Pos; unsigned int m_Steps; bool m_AutoRepeat; bool m_PingPong; bool m_InverseDirection; ScalarType m_RangeMin; ScalarType m_RangeMax; bool m_RangeValid; bool m_HasRange; std::string m_UnitName; bool m_HasUnitName; }; } // namespace mitk #endif /* STEPPER_H_HEADER_INCLUDED_C1E77191 */ diff --git a/Core/Code/DataManagement/itkVtkAbstractTransform.txx b/Core/Code/DataManagement/itkVtkAbstractTransform.txx index 83be3971a3..f0330aa7ba 100644 --- a/Core/Code/DataManagement/itkVtkAbstractTransform.txx +++ b/Core/Code/DataManagement/itkVtkAbstractTransform.txx @@ -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 "itkVtkAbstractTransform.h" #include -#include +#include namespace itk { template itk::VtkAbstractTransform::VtkAbstractTransform() : m_VtkAbstractTransform(NULL), m_InverseVtkAbstractTransform(NULL), m_LastVtkAbstractTransformTimeStamp(0) { } template itk::VtkAbstractTransform::~VtkAbstractTransform() { if(m_VtkAbstractTransform!=NULL) m_VtkAbstractTransform->UnRegister(NULL); } template vtkAbstractTransform* itk::VtkAbstractTransform::GetVtkAbstractTransform() const { return m_VtkAbstractTransform; } template vtkAbstractTransform* itk::VtkAbstractTransform::GetInverseVtkAbstractTransform() const { return m_InverseVtkAbstractTransform; } template void itk::VtkAbstractTransform::SetVtkAbstractTransform(vtkAbstractTransform* aVtkAbstractTransform) { if(m_VtkAbstractTransform==aVtkAbstractTransform) return; if(m_VtkAbstractTransform!=NULL) m_VtkAbstractTransform->UnRegister(NULL); m_VtkAbstractTransform=aVtkAbstractTransform; if(m_VtkAbstractTransform!=NULL) { m_VtkAbstractTransform->Register(NULL); m_InverseVtkAbstractTransform=m_VtkAbstractTransform->GetInverse(); // memory managed by m_VtkAbstractTransform } m_LastVtkAbstractTransformTimeStamp = m_VtkAbstractTransform->GetMTime(); this->Modified(); } // Transform a point template typename itk::VtkAbstractTransform::OutputPointType itk::VtkAbstractTransform:: TransformPoint(const InputPointType &point) const { assert(m_VtkAbstractTransform!=NULL); OutputPointType outputpoint; vnl_vector vnl_vec; mitk::ScalarType vtkpt[3]; mitk::itk2vtk(point, vtkpt); m_VtkAbstractTransform->TransformPoint(vtkpt, vtkpt); mitk::vtk2itk(vtkpt, outputpoint); return outputpoint; } // Transform a vector template typename itk::VtkAbstractTransform::OutputVectorType itk::VtkAbstractTransform:: TransformVector(const InputVectorType &vect) const { assert(m_VtkAbstractTransform!=NULL); OutputVectorType outputvector; vnl_vector vnl_vec; mitk::ScalarType vtkpt[3]={0,0,0}; mitk::ScalarType vtkvec[3]; mitk::vnl2vtk(vect.GetVnlVector(), vtkvec); m_VtkAbstractTransform->TransformVectorAtPoint(vtkpt, vtkvec, vtkvec); mitk::vtk2itk(vtkvec, outputvector); return outputvector; } // Transform a vnl_vector_fixed template typename itk::VtkAbstractTransform::OutputVnlVectorType itk::VtkAbstractTransform:: TransformVector(const InputVnlVectorType &vect) const { assert(m_VtkAbstractTransform!=NULL); OutputVnlVectorType outputvector; mitk::ScalarType vtkpt[3]={0,0,0}; mitk::ScalarType vtkvec[3]; mitk::vnl2vtk(vect, vtkvec); m_VtkAbstractTransform->TransformVectorAtPoint(vtkpt, vtkvec, vtkvec); mitk::vtk2itk(vtkvec, outputvector); return outputvector; } // Transform a CovariantVector template typename itk::VtkAbstractTransform::OutputCovariantVectorType itk::VtkAbstractTransform:: TransformCovariantVector(const InputCovariantVectorType &/*vec*/) const { itkExceptionMacro( << "implement before using!" ); OutputCovariantVectorType result; // Converted vector // for (unsigned int i = 0; i < NDimensions; i++) // { // result[i] = NumericTraits::Zero; // for (unsigned int j = 0; j < NDimensions; j++) // { // result[i] += m_Inverse[j][i]*vec[j]; // Inverse transposed // } // } return result; } // Back transform a point template typename VtkAbstractTransform::InputPointType itk::VtkAbstractTransform:: BackTransform(const OutputPointType &point) const { assert(m_VtkAbstractTransform!=NULL); OutputPointType outputpoint; mitk::ScalarType vtkpt[3]; mitk::itk2vtk(point, vtkpt); m_InverseVtkAbstractTransform->TransformPoint(vtkpt, vtkpt); mitk::vtk2itk(vtkpt, outputpoint); return outputpoint; } // Back transform a vector template typename VtkAbstractTransform::InputVectorType itk::VtkAbstractTransform:: BackTransform(const OutputVectorType &vect ) const { assert(m_VtkAbstractTransform!=NULL); OutputVectorType outputvector; mitk::ScalarType vtkpt[3]={0,0,0}; mitk::ScalarType vtkvec[3]; mitk::itk2vtk(vect, vtkvec); m_InverseVtkAbstractTransform->TransformVectorAtPoint(vtkpt, vtkvec, vtkvec); mitk::vtk2itk(vtkvec, outputvector); return outputvector; } // Back transform a vnl_vector template typename VtkAbstractTransform::InputVnlVectorType itk::VtkAbstractTransform:: BackTransform(const OutputVnlVectorType &vect ) const { assert(m_InverseVtkAbstractTransform!=NULL); OutputVnlVectorType outputvector; mitk::ScalarType vtkpt[3]={0,0,0}; mitk::ScalarType vtkvec[3]; mitk::itk2vtk(vect, vtkvec); m_InverseVtkAbstractTransform->TransformVectorAtPoint(vtkpt, vtkvec, vtkvec); mitk::vtk2itk(vtkvec, outputvector); return outputvector; } // Back Transform a CovariantVector template typename VtkAbstractTransform::InputCovariantVectorType itk::VtkAbstractTransform:: BackTransform(const OutputCovariantVectorType &vec) const { itkExceptionMacro( << "implement before using!" ); // for (unsigned int i = 0; i < NDimensions; i++) // { // result[i] = NumericTraits::Zero; // for (unsigned int j = 0; j < NDimensions; j++) // { // result[i] += m_Matrix[j][i]*vec[j]; // Direct matrix transposed // } // } return vec; } template unsigned long itk::VtkAbstractTransform::GetMTime() const { if((m_VtkAbstractTransform != NULL) && (m_LastVtkAbstractTransformTimeStamp < m_VtkAbstractTransform->GetMTime())) { m_LastVtkAbstractTransformTimeStamp=m_VtkAbstractTransform->GetMTime(); this->Modified(); } return Superclass::GetMTime(); } template void itk::VtkAbstractTransform::SetParameters(const ParametersType&) { // TODO } template void itk::VtkAbstractTransform::SetFixedParameters(const ParametersType&) { // TODO } template void itk::VtkAbstractTransform::ComputeJacobianWithRespectToParameters(const InputPointType&, JacobianType&) const { // TODO } template void itk::VtkAbstractTransform::ComputeJacobianWithRespectToPosition(const InputPointType&, JacobianType&) const { // TODO } } // namespace itk diff --git a/Core/Code/DataManagement/mitkQuaternion.h b/Core/Code/DataManagement/mitkAffineTransform3D.h similarity index 67% copy from Core/Code/DataManagement/mitkQuaternion.h copy to Core/Code/DataManagement/mitkAffineTransform3D.h index c1afabbb51..70dd84a0b9 100644 --- a/Core/Code/DataManagement/mitkQuaternion.h +++ b/Core/Code/DataManagement/mitkAffineTransform3D.h @@ -1,30 +1,31 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ -#ifndef MITKTYPEDEFS_H_ -#define MITKTYPEDEFS_H_ +#ifndef MITKAFFINETRANSFORM3D_H_ +#define MITKAFFINETRANSFORM3D_H_ -#include -#include "mitkConstants.h" -namespace mitk { - -typedef vnl_quaternion Quaternion; +#include +namespace mitk +{ + typedef itk::AffineGeometryFrame::TransformType AffineTransform3D; } -#endif /* MITKTYPEDEFS_H_ */ + + +#endif /* MITKAFFINETRANSFORM3D_H_ */ diff --git a/Core/Code/DataManagement/mitkAnnotationProperty.h b/Core/Code/DataManagement/mitkAnnotationProperty.h index 5a14d6d0bd..8a1d6e0275 100644 --- a/Core/Code/DataManagement/mitkAnnotationProperty.h +++ b/Core/Code/DataManagement/mitkAnnotationProperty.h @@ -1,92 +1,92 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKANNOTATIONPROPERTY_H_HEADER_INCLUDED #define MITKANNOTATIONPROPERTY_H_HEADER_INCLUDED #include #include "mitkBaseProperty.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include #include namespace mitk { /** * \brief Property for annotations * \ingroup DataManagement */ class MITK_CORE_EXPORT AnnotationProperty : public BaseProperty { public: mitkClassMacro(AnnotationProperty, BaseProperty); typedef std::string ValueType; itkFactorylessNewMacro(Self) itkCloneMacro(Self) mitkNewMacro2Param( AnnotationProperty, const char *, const Point3D & ); mitkNewMacro2Param( AnnotationProperty, const std::string &, const Point3D & ); mitkNewMacro4Param( AnnotationProperty, const char *, ScalarType, ScalarType, ScalarType ); mitkNewMacro4Param( AnnotationProperty, const std::string &, ScalarType, ScalarType, ScalarType ); itkGetStringMacro( Label ); itkSetStringMacro( Label ); const Point3D &GetPosition() const; void SetPosition( const Point3D &position ); virtual std::string GetValueAsString() const; virtual BaseProperty& operator=(const BaseProperty& other) { return Superclass::operator=(other); } \ using BaseProperty::operator =; protected: std::string m_Label; Point3D m_Position; AnnotationProperty(); AnnotationProperty( const char *label, const Point3D &position ); AnnotationProperty( const std::string &label, const Point3D &position ); AnnotationProperty( const char *label, ScalarType x, ScalarType y, ScalarType z ); AnnotationProperty( const std::string &label, ScalarType x, ScalarType y, ScalarType z ); AnnotationProperty(const AnnotationProperty& other); private: // purposely not implemented AnnotationProperty& operator=(const AnnotationProperty&); itk::LightObject::Pointer InternalClone() const; virtual bool IsEqual(const BaseProperty& property) const; virtual bool Assign(const BaseProperty & property); }; } // namespace mitk #endif /* MITKANNOTATIONPROPERTY_H_HEADER_INCLUDED */ diff --git a/Core/Code/DataManagement/mitkApplicationCursor.h b/Core/Code/DataManagement/mitkApplicationCursor.h index a0309eecaa..7145a20e01 100644 --- a/Core/Code/DataManagement/mitkApplicationCursor.h +++ b/Core/Code/DataManagement/mitkApplicationCursor.h @@ -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. ===================================================================*/ #ifndef MITK_APPLICATION_CURSOR_H_DEFINED_AND_ALL_IS_GOOD #define MITK_APPLICATION_CURSOR_H_DEFINED_AND_ALL_IS_GOOD #include -#include "mitkTypes.h" +#include "mitkNumericTypes.h" namespace mitk { /*! \brief Toolkit specific implementation of mitk::ApplicationCursor For any toolkit, this class has to be sub-classed. One instance of that sub-class has to be registered with mitk::ApplicationCursor. See the (very simple) implmentation of QmitkApplicationCursor for an example. */ class MITK_CORE_EXPORT ApplicationCursorImplementation { public: /// Change the current application cursor virtual void PushCursor(const char* XPM[], int hotspotX, int hotspotY) = 0; /// Change the current application cursor virtual void PushCursor(std::istream&, int hotspotX, int hotspotY) = 0; /// Restore the previous cursor virtual void PopCursor() = 0; /// Get absolute mouse position on screen virtual const Point2I GetCursorPosition() = 0; /// Set absolute mouse position on screen virtual void SetCursorPosition(const Point2I&) = 0; virtual ~ApplicationCursorImplementation() {} protected: private: }; /*! \brief Allows to override the application's cursor. Base class for classes that allow to override the applications cursor with context dependent cursors. Accepts cursors in the XPM format. The behaviour is stack-like. You can push your cursor on top of the stack and later pop it to reset the cursor to its former state. This is mimicking Qt's Application::setOverrideCuror() behaviour, but should be ok for most cases where you want to switch a cursor. */ class MITK_CORE_EXPORT ApplicationCursor { public: /// This class is a singleton. static ApplicationCursor* GetInstance(); /// To be called by a toolkit specific ApplicationCursorImplementation. static void RegisterImplementation(ApplicationCursorImplementation* implementation); /// Change the current application cursor void PushCursor(const char* XPM[], int hotspotX = -1, int hotspotY = -1); /// Change the current application cursor void PushCursor(std::istream&, int hotspotX = -1, int hotspotY = -1); /// Restore the previous cursor void PopCursor(); /// Get absolute mouse position on screen /// \return (-1, -1) if querying mouse position is not possible const Point2I GetCursorPosition(); /// Set absolute mouse position on screen void SetCursorPosition(const Point2I&); protected: /// Purposely hidden - singleton ApplicationCursor(); private: static ApplicationCursorImplementation* m_Implementation; }; } // namespace #endif diff --git a/Core/Code/DataManagement/mitkArray.h b/Core/Code/DataManagement/mitkArray.h index 3a022d59e0..fb9561b71e 100644 --- a/Core/Code/DataManagement/mitkArray.h +++ b/Core/Code/DataManagement/mitkArray.h @@ -1,141 +1,149 @@ -/* - * mitkArray.h - * - * Created on: Nov 11, 2013 - * Author: wirkert - */ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY 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 MITKARRAY_H_ #define MITKARRAY_H_ #include -#include "mitkConstants.h" +#include "mitkNumericConstants.h" #include "mitkEqual.h" namespace mitk { /** * Methods to copy from itk::FixedArray s (like mitk::Vector and mitk::Point) into ArrayTypes and vice versa. * ArrayTypes here are all types who implement operator[]. * The two templated methods were made free floating so you may specialize them * for your concrete type. */ /** * @brief Copies elements of an array to this Vector * @param[in] array the array whose values will be copied into the Vector. Must be of a type which overrides the [] operator * @param[out] toArray the FixedArrray (e.g., mitk::Vector or mitk::Point) which should hold the elements of array. * @attention array must be of dimension NVectorDimension! * @attention this method implicitly converts between data types. */ template - void FromArray(itk::FixedArray& toArray, const ArrayType& array) + void FillArray(itk::FixedArray& toArray, const ArrayType& array) { itk::FixedArray vectorOrPoint; - for (unsigned short int var = 0; var < NVectorDimension; ++var) { toArray[var] = array[var]; } } /** * @brief Copies elements of an array to this Vector * @param[in] array the array whose values will be copied into the Vector. Must be of a type which overrides the [] operator * @param return the FixedArrray (e.g., mitk::Vector or mitk::Point) which should hold the elements of array. * @attention array must be of dimension NVectorDimension! * @attention this method implicitly converts between data types. */ template - itk::FixedArray FromArray(const ArrayType& array) + itk::FixedArray FillArray(const ArrayType& array) { itk::FixedArray vectorOrPoint; - mitk::FromArray(vectorOrPoint, array); + mitk::FillArray(vectorOrPoint, array); return vectorOrPoint; } /** * @brief Copies the elements of this into an array * @param[in] vectorOrPoint the itk::FixedArray which shall be copied into the array. Can e.g. be of type mitk::Vector or mitk::Point * @param[out] array the array which will hold the elements. Must be of a type which overrides the [] operator. * @attention array must be of dimension NVectorDimension! * @attention this method implicitly converts between data types. */ template void ToArray(ArrayType& array, const itk::FixedArray& vectorOrPoint) { for (unsigned short int var = 0; var < NVectorDimension; ++var) { array[var] = vectorOrPoint[var]; } } /** * @brief Copies the elements of this into an array * @param[in] vectorOrPoint the itk::FixedArray which shall be copied into the array. Can e.g. be of type mitk::Vector or mitk::Point * @return the array which will hold the elements. Must be of a type which overrides the [] operator. * @attention array must be of dimension NVectorDimension! * @attention this method implicitly converts between data types. */ template ArrayType ToArray(const itk::FixedArray& vectorOrPoint) { ArrayType result; mitk::ToArray(result, vectorOrPoint); return result; } // The FillVector3D and FillVector4D methods are implemented for all common array types here template inline void FillVector3D(Tout& out, mitk::ScalarType x, mitk::ScalarType y, mitk::ScalarType z) { out[0] = x; out[1] = y; out[2] = z; } template inline void FillVector4D(Tout& out, mitk::ScalarType x, mitk::ScalarType y, mitk::ScalarType z, mitk::ScalarType t) { out[0] = x; out[1] = y; out[2] = z; out[3] = t; } /** * Compares two ArrayTypes of size size. * ArrayTypes are all Objects/Types who have a [] operator. Pay attention not to set size higher * than the actual size of the ArrayType as this will lead to unexpected results. */ template inline bool EqualArray(TArrayType1& arrayType1, TArrayType2& arrayType2, int size, ScalarType eps = mitk::eps, bool verbose = false) { bool isEqual = true; for (int var = 0; var < size; ++var) { isEqual = isEqual && Equal(arrayType1[var], arrayType2[var], eps); } ConditionalOutputOfDifference(arrayType1, arrayType2, eps, verbose, isEqual); return isEqual; } } #endif /* MITKARRAY_H_ */ diff --git a/Core/Code/DataManagement/mitkClippingProperty.h b/Core/Code/DataManagement/mitkClippingProperty.h index f371253419..9d61e0a40b 100644 --- a/Core/Code/DataManagement/mitkClippingProperty.h +++ b/Core/Code/DataManagement/mitkClippingProperty.h @@ -1,96 +1,96 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKCLIPPINGPROPERTY_H_HEADER_INCLUDED #define MITKCLIPPINGPROPERTY_H_HEADER_INCLUDED #include #include "mitkBaseProperty.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include #include namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * \brief Property for clipping datasets; currently only * clipping planes are possible * \ingroup DataManagement */ class MITK_CORE_EXPORT ClippingProperty : public BaseProperty { public: mitkClassMacro(ClippingProperty, BaseProperty); typedef std::string ValueType; itkFactorylessNewMacro(Self) itkCloneMacro(Self) mitkNewMacro2Param( ClippingProperty, const Point3D &, const Vector3D & ); bool GetClippingEnabled() const; void SetClippingEnabled( bool enabled ); const Point3D &GetOrigin() const; void SetOrigin( const Point3D &origin ); const Vector3D &GetNormal() const; void SetNormal( const Vector3D &normal ); virtual std::string GetValueAsString() const; using BaseProperty::operator =; protected: bool m_ClippingEnabled; Point3D m_Origin; Vector3D m_Normal; ClippingProperty(); ClippingProperty(const ClippingProperty& other); ClippingProperty( const Point3D &origin, const Vector3D &normal ); private: // purposely not implemented ClippingProperty& operator=(const ClippingProperty&); virtual bool IsEqual(const BaseProperty& property) const; virtual bool Assign(const BaseProperty& property); virtual itk::LightObject::Pointer InternalClone() const; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk #endif /* MITKCLIPPINGPROPERTY_H_HEADER_INCLUDED */ diff --git a/Core/Code/DataManagement/mitkEqual.h b/Core/Code/DataManagement/mitkEqual.h index 750e4ee07e..db6ebd4cc5 100644 --- a/Core/Code/DataManagement/mitkEqual.h +++ b/Core/Code/DataManagement/mitkEqual.h @@ -1,72 +1,72 @@ /* * mitkEqual.h * * Created on: Apr 14, 2014 * Author: wirkert */ #ifndef MITKEQUAL_H_ #define MITKEQUAL_H_ #include -#include "mitkConstants.h" +#include "mitkNumericConstants.h" #include "mitkLogMacros.h" namespace mitk { /** * Helper method to check if the difference is bigger or equal to a given epsilon * * @param diff the difference to be checked against the epsilon * @param the epsilon. The absolute difference needs to be smaller than this. * @return true if abs(diff) >= eps */ template inline bool DifferenceBiggerOrEqualEps(DifferenceType diff, mitk::ScalarType epsilon = mitk::eps) { return fabs(diff) >= epsilon; } /** * outputs elem1, elem2 and eps in case verbose and !isEqual. * Elem can e.g. be a mitk::Vector or an mitk::Point. * * @param elem1 first element to be output * @param elem2 second * @param eps the epsilon which their difference was bigger than * @param verbose tells the function if something shall be output * @param isEqual function will only output something if the two elements are not equal */ template inline void ConditionalOutputOfDifference(ElementToOutput1 elem1, ElementToOutput2 elem2, mitk::ScalarType eps, bool verbose, bool isEqual) { if(verbose && !isEqual) { MITK_INFO << typeid(ElementToOutput1).name() << " and " << typeid(ElementToOutput2).name() << " not equal. Lefthandside " << std::setprecision(12) << elem1 << " - Righthandside " << elem2 << " - epsilon " << eps; } } /** * @ingroup MITKTestingAPI * * @param scalar1 Scalar value to compare. * @param scalar2 Scalar value to compare. * @param eps Tolerance for floating point comparison. * @param verbose Flag indicating detailed console output. * @return True if scalars are equal. */ inline bool Equal(ScalarType scalar1, ScalarType scalar2, ScalarType eps=mitk::eps, bool verbose=false) { bool isEqual( !DifferenceBiggerOrEqualEps(scalar1-scalar2, eps)); ConditionalOutputOfDifference(scalar1, scalar2, eps, verbose, isEqual); return isEqual; } } #endif /* MITKEQUAL_H_ */ diff --git a/Core/Code/DataManagement/mitkGenericLookupTable.h b/Core/Code/DataManagement/mitkGenericLookupTable.h index e5e2b1ba62..2dfe6b8cf1 100644 --- a/Core/Code/DataManagement/mitkGenericLookupTable.h +++ b/Core/Code/DataManagement/mitkGenericLookupTable.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 MITKGENERICLOOKUPTABLE_H_HEADER_INCLUDED_C1061CEE #define MITKGENERICLOOKUPTABLE_H_HEADER_INCLUDED_C1061CEE #include #include #include #include #include -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include namespace mitk { /** * @brief Template class for generating lookup-tables * * This class template can be instantiated for all classes/internal types that fulfills * these requirements: * - an operator<< so that the properties value can be put into a std::stringstream * - an operator== so that two properties can be checked for equality * * The main purpose of this class is to be used in conjunction with * GenericLookupTableProperty. This enables passing of arbitrary lookup * tables to mappers to configure the rendering process. */ template class GenericLookupTable { public: typedef unsigned int IdentifierType; typedef T ValueType; typedef std::map< IdentifierType, ValueType > LookupTableType; typedef GenericLookupTable Self; GenericLookupTable() {} virtual ~GenericLookupTable() { } virtual const char *GetNameOfClass() const { return "GenericLookupTable"; } void SetTableValue( IdentifierType id, ValueType value ) { m_LookupTable[id] = value; } bool ValueExists(IdentifierType id) const { typename LookupTableType::const_iterator it = m_LookupTable.find(id); return (it != m_LookupTable.end()); } ValueType GetTableValue( IdentifierType id ) const { typename LookupTableType::const_iterator it = m_LookupTable.find(id); if (it != m_LookupTable.end()) return it->second; else throw std::range_error("id does not exist in the lookup table"); } const LookupTableType& GetLookupTable() const { return m_LookupTable; } bool operator==( const Self& lookupTable ) const { return (m_LookupTable == lookupTable.m_LookupTable); } bool operator!=( const Self& lookupTable ) const { return !(m_LookupTable == lookupTable.m_LookupTable); } virtual Self& operator=(const Self& other) // \TODO: this needs to be unit tested! { if ( this == &other ) { return *this; } else { m_LookupTable.clear(); m_LookupTable = other.m_LookupTable; return *this; } } protected: LookupTableType m_LookupTable; }; } // namespace mitk /** * Generates a specialized subclass of mitk::GenericLookupTable. * This way, GetNameOfClass() returns the value provided by LookupTableName. * Please see mitkProperties.h for examples. * @param LookupTableName the name of the instantiation of GenericLookupTable * @param Type the value type of the GenericLookupTable */ #define mitkSpecializeGenericLookupTable(LookupTableName,Type) \ class MITK_CORE_EXPORT LookupTableName: public GenericLookupTable< Type > \ { \ public: \ typedef LookupTableName Self; \ typedef GenericLookupTable< Type > Superclass; \ virtual const char *GetNameOfClass() const \ {return #LookupTableName;} \ LookupTableName() {} \ virtual Superclass& operator=(const Superclass& other) { return Superclass::operator=(other); } \ virtual ~LookupTableName() {} \ }; \ MITK_CORE_EXPORT std::ostream& operator<<(std::ostream& stream, const LookupTableName& /*l*/); /** * Generates the ostream << operator for the lookuptable. This definition * of a global function must be in a cpp file, therefore it is split from the * class declaration macro mitkSpecializeGenericLookupTable. */ #define mitkSpecializeGenericLookupTableOperator(LookupTableName) \ std::ostream& mitk::operator<<(std::ostream& stream, const LookupTableName& l) \ { \ typedef LookupTableName::LookupTableType::const_iterator IterType; \ IterType e = l.GetLookupTable().end(); \ IterType b = l.GetLookupTable().begin(); \ stream << "["; \ for (IterType i = b; i != e; ++i) \ { \ if (i != b) \ { \ stream << ", "; \ } \ stream << i->first << " -> " << i->second; \ } \ return stream << "]"; \ }; #endif diff --git a/Core/Code/DataManagement/mitkGenericProperty.h b/Core/Code/DataManagement/mitkGenericProperty.h index 1ca461b911..2567a6f4b2 100644 --- a/Core/Code/DataManagement/mitkGenericProperty.h +++ b/Core/Code/DataManagement/mitkGenericProperty.h @@ -1,149 +1,149 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKGENERICPROPERTY_H_HEADER_INCLUDED_C1061CEE #define MITKGENERICPROPERTY_H_HEADER_INCLUDED_C1061CEE #include #include #include -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include #include "mitkBaseProperty.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /*! @ brief Template class for generating properties for int, float, bool, etc. This class template can be instantiated for all classes/internal types that fulfills these requirements: - an operator<< so that the properties value can be put into a std::stringstream - an operator== so that two properties can be checked for equality Note: you must use the macro mitkSpecializeGenericProperty to provide specializations for concrete types (e.g. BoolProperty). Please see mitkProperties.h for examples. If you don't use the mitkSpecializeGenericProperty Macro, GetNameOfClass() returns a wrong name. */ template class MITK_EXPORT GenericProperty : public BaseProperty { public: mitkClassMacro(GenericProperty, BaseProperty); mitkNewMacro1Param(GenericProperty, T); itkCloneMacro(Self) typedef T ValueType; itkSetMacro(Value,T); itkGetConstMacro(Value,T); virtual std::string GetValueAsString() const { std::stringstream myStr; myStr << GetValue() ; return myStr.str(); } using BaseProperty::operator=; protected: GenericProperty() {} GenericProperty(T x) : m_Value(x) {} GenericProperty(const GenericProperty& other) : BaseProperty(other) , m_Value(other.m_Value) {} T m_Value; private: // purposely not implemented GenericProperty& operator=(const GenericProperty&); virtual itk::LightObject::Pointer InternalClone() const { itk::LightObject::Pointer result(new Self(*this)); result->UnRegister(); return result; } virtual bool IsEqual(const BaseProperty& other) const { return (this->m_Value == static_cast(other).m_Value); } virtual bool Assign(const BaseProperty& other) { this->m_Value = static_cast(other).m_Value; return true; } }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk /** * Generates a specialized subclass of mitk::GenericProperty. * This way, GetNameOfClass() returns the value provided by PropertyName. * Please see mitkProperties.h for examples. * @param PropertyName the name of the subclass of GenericProperty * @param Type the value type of the GenericProperty * @param Export the export macro for DLL usage */ #define mitkDeclareGenericProperty(PropertyName,Type,Export) \ class Export PropertyName: public GenericProperty< Type > \ { \ public: \ mitkClassMacro(PropertyName, GenericProperty< Type >) \ itkFactorylessNewMacro(Self) \ itkCloneMacro(Self) \ mitkNewMacro1Param(PropertyName, Type) \ using BaseProperty::operator=; \ protected: \ PropertyName(); \ PropertyName(const PropertyName&); \ PropertyName(Type x); \ private: \ itk::LightObject::Pointer InternalClone() const; \ }; #define mitkDefineGenericProperty(PropertyName,Type,DefaultValue) \ mitk::PropertyName::PropertyName() : Superclass(DefaultValue) { } \ mitk::PropertyName::PropertyName(const PropertyName& other) : GenericProperty< Type >(other) {} \ mitk::PropertyName::PropertyName(Type x) : Superclass(x) {} \ itk::LightObject::Pointer mitk::PropertyName::InternalClone() const { \ itk::LightObject::Pointer result(new Self(*this)); \ result->UnRegister(); \ return result; \ } \ #endif /* MITKGENERICPROPERTY_H_HEADER_INCLUDED_C1061CEE */ diff --git a/Core/Code/DataManagement/mitkGeometry3D.h b/Core/Code/DataManagement/mitkGeometry3D.h index 5ae7410272..45c0085947 100644 --- a/Core/Code/DataManagement/mitkGeometry3D.h +++ b/Core/Code/DataManagement/mitkGeometry3D.h @@ -1,826 +1,826 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 GEOMETRY3D_H_HEADER_INCLUDED_C1EBD0AD #define GEOMETRY3D_H_HEADER_INCLUDED_C1EBD0AD #include #include -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "mitkOperationActor.h" #include #include #include #include #include "itkScalableAffineTransform.h" #include "itkBoundingBox.h" class vtkLinearTransform; class vtkMatrixToLinearTransform; class vtkMatrix4x4; namespace mitk { //##Documentation //## @brief Standard 3D-BoundingBox typedef //## //## Standard 3D-BoundingBox typedef to get rid of template arguments (3D, type). typedef itk::BoundingBox BoundingBox; //##Documentation //## @brief Standard typedef for time-bounds typedef itk::FixedArray TimeBounds; typedef itk::FixedArray FixedArrayType; typedef itk::AffineGeometryFrame AffineGeometryFrame3D; //##Documentation //## @brief Describes the geometry of a data object //## //## At least, it can return the bounding box of the data object. //## //## The class holds //## \li a bounding box which is axes-parallel in intrinsic coordinates //## (often integer indices of pixels), to be accessed by //## GetBoundingBox() //## \li a transform to convert intrinsic coordinates into a //## world-coordinate system with coordinates in millimeters //## and milliseconds (all are floating point values), to //## be accessed by GetIndexToWorldTransform() //## \li a life span, i.e. a bounding box in time in ms (with //## start and end time), to be accessed by GetTimeBounds(). //## The default is minus infinity to plus infinity. //## //## Geometry3D and its sub-classes allow converting between //## intrinsic coordinates (called index or unit coordinates) //## and world-coordinates (called world or mm coordinates), //## e.g. WorldToIndex. //## In case you need integer index coordinates, provide an //## itk::Index<3> (or itk::Index) as target variable to //## WorldToIndex, otherwise you will get a continuous index //## (floating point values). //## //## An important sub-class is SlicedGeometry3D, which descibes //## data objects consisting of slices, e.g., objects of type Image. //## Conversions between world coordinates (in mm) and unit coordinates //## (e.g., pixels in the case of an Image) can be performed. //## //## For more information on related classes, see \ref Geometry. //## //## Geometry3D instances referring to an Image need a slightly //## different definition of corners, see SetImageGeometry. This //## is usualy automatically called by Image. //## //## Geometry3D have to be initialized in the method GenerateOutputInformation() //## of BaseProcess (or CopyInformation/ UpdateOutputInformation of BaseData, //## if possible, e.g., by analyzing pic tags in Image) subclasses. See also //## itk::ProcessObject::GenerateOutputInformation(), //## itk::DataObject::CopyInformation() and //## itk::DataObject::UpdateOutputInformation(). //## //## Rule: everything is in mm (ms) if not stated otherwise. //## @ingroup Geometry class MITK_CORE_EXPORT Geometry3D : public itk::Object, public OperationActor { public: mitkClassMacro(Geometry3D, itk::Object); typedef itk::QuaternionRigidTransform< ScalarType > QuaternionTransformType; typedef QuaternionTransformType::VnlQuaternionType VnlQuaternionType; /** Method for creation through the object factory. */ itkFactorylessNewMacro(Self) itkCloneMacro(Self) typedef itk::ScalableAffineTransform TransformType; typedef itk::BoundingBox BoundingBoxType; typedef BoundingBoxType::BoundsArrayType BoundsArrayType; typedef BoundingBoxType::Pointer BoundingBoxPointer; // a bit of a misuse, but we want only doxygen to see the following: #ifdef DOXYGEN_SKIP //##Documentation //## @brief Get the transformation used to convert from index //## to world coordinates itkGetObjectMacro(IndexToWorldTransform, AffineTransform3D); #endif //## @brief Set the transformation used to convert from index //## to world coordinates virtual void SetIndexToWorldTransform(mitk::AffineTransform3D* transform); //##Documentation //## @brief Convenience method for setting the ITK transform //## (m_IndexToWorldTransform) via an vtkMatrix4x4 //## \sa SetIndexToWorldTransform virtual void SetIndexToWorldTransformByVtkMatrix(vtkMatrix4x4* vtkmatrix); #ifdef DOXYGEN_SKIP //##Documentation //## @brief Get bounding box (in index/unit coordinates) itkGetConstObjectMacro(BoundingBox, BoundingBoxType); //##Documentation //## @brief Get bounding box (in index/unit coordinates) as a BoundsArrayType const BoundsArrayType GetBounds() const { assert(m_BoundingBox.IsNotNull()); return m_BoundingBox->GetBounds(); } #endif //##Documentation //## \brief Set the bounding box (in index/unit coordinates) //## //## Only possible via the BoundsArray to make clear that a //## copy of the bounding-box is stored, not a reference to it. virtual void SetBounds(const BoundsArrayType& bounds); //##Documentation //## @brief Set the bounding box (in index/unit coordinates) via a float array virtual void SetFloatBounds(const float bounds[6]); //##Documentation //## @brief Set the bounding box (in index/unit coordinates) via a double array virtual void SetFloatBounds(const double bounds[6]); //##Documentation //## @brief When switching from an Image Geometry to a normal Geometry (and the other way around), you have to change the origin as well (See Geometry Documentation)! This function will change the "isImageGeometry" bool flag and changes the origin respectively. virtual void ChangeImageGeometryConsideringOriginOffset( const bool isAnImageGeometry ); //##Documentation //## @brief Checks, if the given geometry can be converted to 2D without information loss //## e.g. when a 2D image is saved, the matrix is usually cropped to 2x2, and when you load it back to MITK //## it will be filled with standard values. This function checks, if information would be lost during this //## procedure virtual bool Is2DConvertable(); //##Documentation //## @brief Get the time bounds (in ms) itkGetConstReferenceMacro(TimeBounds, TimeBounds); //##Documentation //## @brief Set the time bounds (in ms) virtual void SetTimeBounds(const TimeBounds& timebounds); //##Documentation //## @brief Get the position of the corner number \a id (in world coordinates) //## //## See SetImageGeometry for how a corner is defined on images. Point3D GetCornerPoint(int id) const; //##Documentation //## @brief Get the position of a corner (in world coordinates) //## //## See SetImageGeometry for how a corner is defined on images. Point3D GetCornerPoint(bool xFront=true, bool yFront=true, bool zFront=true) const; //##Documentation //## @brief Get vector along bounding-box in the specified @a direction in mm //## //## The length of the vector is the size of the bounding-box in the //## specified @a direction in mm //## \sa GetMatrixColumn Vector3D GetAxisVector(unsigned int direction) const { Vector3D frontToBack; frontToBack.SetVnlVector(m_IndexToWorldTransform->GetMatrix().GetVnlMatrix().get_column(direction)); frontToBack *= GetExtent(direction); return frontToBack; } //##Documentation //## @brief Get the center of the bounding-box in mm //## Point3D GetCenter() const { assert(m_BoundingBox.IsNotNull()); return m_IndexToWorldTransform->TransformPoint(m_BoundingBox->GetCenter()); } //##Documentation //## @brief Get the squared length of the diagonal of the bounding-box in mm //## double GetDiagonalLength2() const { Vector3D diagonalvector = GetCornerPoint()-GetCornerPoint(false, false, false); return diagonalvector.GetSquaredNorm(); } //##Documentation //## @brief Get the length of the diagonal of the bounding-box in mm //## double GetDiagonalLength() const { return sqrt(GetDiagonalLength2()); } //##Documentation //## @brief Get a VnlVector along bounding-box in the specified //## @a direction, length is spacing //## //## \sa GetAxisVector VnlVector GetMatrixColumn(unsigned int direction) const { return m_IndexToWorldTransform->GetMatrix().GetVnlMatrix().get_column(direction); } #ifdef DOXYGEN_SKIP //##Documentation //## @brief Get the extent of the bounding box (in index/unit coordinates) //## //## To access the extent in mm use GetExtentInMM ScalarType GetExtent(unsigned int direction) const; #endif //##Documentation //## @brief Get the extent of the bounding-box in the specified @a direction in mm //## //## Equals length of GetAxisVector(direction). ScalarType GetExtentInMM(int direction) const { return m_IndexToWorldTransform->GetMatrix().GetVnlMatrix().get_column(direction).magnitude()*GetExtent(direction); } //##Documentation //## @brief Set the extent of the bounding-box in the specified @a direction in mm //## //## @note This changes the matrix in the transform, @a not the bounds, which are given in units! virtual void SetExtentInMM(int direction, ScalarType extentInMM); //##Documentation //## @brief Get the m_IndexToWorldTransform as a vtkLinearTransform vtkLinearTransform* GetVtkTransform() const { return (vtkLinearTransform*)m_VtkIndexToWorldTransform; } //##Documentation //## @brief Set the origin, i.e. the upper-left corner of the plane //## virtual void SetOrigin(const Point3D& origin); //##Documentation //## @brief Translate the origin by a vector //## virtual void Translate(const Vector3D& vector); //##Documentation //## @brief Set the transform to identity //## virtual void SetIdentity(); //##Documentation //## @brief Compose new IndexToWorldTransform with a given transform. //## //## This method composes m_IndexToWorldTransform with another transform, //## modifying self to be the composition of self and other. //## If the argument pre is true, then other is precomposed with self; //## that is, the resulting transformation consists of first applying //## other to the source, followed by self. If pre is false or omitted, //## then other is post-composed with self; that is the resulting //## transformation consists of first applying self to the source, //## followed by other. virtual void Compose( const Geometry3D::TransformType * other, bool pre = 0 ); //##Documentation //## @brief Compose new IndexToWorldTransform with a given vtkMatrix4x4. //## //## Converts the vtkMatrix4x4 into a itk-transform and calls the previous method. virtual void Compose( const vtkMatrix4x4 * vtkmatrix, bool pre = 0 ); //##Documentation //## @brief Get the origin, e.g. the upper-left corner of the plane const Point3D& GetOrigin() const { return m_Origin; } //##Documentation //## @brief Get the origin as VnlVector //## //## \sa GetOrigin VnlVector GetOriginVnl() const { return const_cast(this)->m_Origin.GetVnlVector(); } //##Documentation //## @brief Convert world coordinates (in mm) of a \em point to (continuous!) index coordinates //## \warning If you need (discrete) integer index coordinates (e.g., for iterating easily over an image), //## use WorldToIndex(const mitk::Point3D& pt_mm, itk::Index &index). //## For further information about coordinates types, please see the Geometry documentation void WorldToIndex(const mitk::Point3D& pt_mm, mitk::Point3D& pt_units) const; //##Documentation //## @brief Convert (continuous or discrete) index coordinates of a \em point to world coordinates (in mm) //## For further information about coordinates types, please see the Geometry documentation void IndexToWorld(const mitk::Point3D& pt_units, mitk::Point3D& pt_mm) const; //##Documentation //## @brief Convert (discrete) index coordinates of a \em point to world coordinates (in mm) //## For further information about coordinates types, please see the Geometry documentation template void IndexToWorld(const itk::Index &index, mitk::Point3D& pt_mm ) const { mitk::Point3D pt_units; pt_units.Fill(0); int i, dim=index.GetIndexDimension(); if(dim>3) { dim=3; } for(i=0;i void WorldToIndex(const mitk::Point3D& pt_mm, itk::Index &index) const { typedef itk::Index IndexType; mitk::Point3D pt_units; this->WorldToIndex(pt_mm, pt_units); int i, dim=index.GetIndexDimension(); if(dim>3) { index.Fill(0); dim=3; } for(i=0;i( pt_units[i] ); } } //##Documentation //## @brief Deprecated for use with ITK version 3.10 or newer. //## Convert world coordinates (in mm) of a \em point to //## ITK physical coordinates (in mm, but without a possible rotation) //## //## This method is useful if you have want to access an mitk::Image //## via an itk::Image. ITK v3.8 and older did not support rotated (tilted) //## images, i.e., ITK images are always parallel to the coordinate axes. //## When accessing a (possibly rotated) mitk::Image via an itk::Image //## the rotational part of the transformation in the Geometry3D is //## simply discarded; in other word: only the origin and spacing is //## used by ITK, not the complete matrix available in MITK. //## With WorldToItkPhysicalPoint you can convert an MITK world //## coordinate (including the rotation) into a coordinate that //## can be used with the ITK image as a ITK physical coordinate //## (excluding the rotation). template void WorldToItkPhysicalPoint(const mitk::Point3D& pt_mm, itk::Point& itkPhysicalPoint) const { mitk::vtk2itk(pt_mm, itkPhysicalPoint); } //##Documentation //## @brief Deprecated for use with ITK version 3.10 or newer. //## Convert ITK physical coordinates of a \em point (in mm, //## but without a rotation) into MITK world coordinates (in mm) //## //## For more information, see WorldToItkPhysicalPoint. template void ItkPhysicalPointToWorld(const itk::Point& itkPhysicalPoint, mitk::Point3D& pt_mm) const { mitk::vtk2itk(itkPhysicalPoint, pt_mm); } //##Documentation //## @brief Initialize the Geometry3D virtual void Initialize(); //##Documentation //## @brief Is this an ImageGeometry? //## //## For more information, see SetImageGeometry itkGetConstMacro(ImageGeometry, bool); //##Documentation //## @brief Define that this Geometry3D is refering to an Image //## //## A geometry referring to an Image needs a slightly different //## definition of the position of the corners (see GetCornerPoint). //## The position of a voxel is defined by the position of its center. //## If we would use the origin (position of the (center of) the first //## voxel) as a corner and display this point, it would seem to be //## \em not at the corner but a bit within the image. Even worse for //## the opposite corner of the image: here the corner would appear //## outside the image (by half of the voxel diameter). Thus, we have //## to correct for this and to be able to do that, we need to know //## that the Geometry3D is referring to an Image. itkSetMacro(ImageGeometry, bool); itkBooleanMacro(ImageGeometry); //##Documentation //## @brief Is this Geometry3D in a state that is valid? virtual bool IsValid() const { return m_Valid; } //##Documentation //## @brief Test whether the point \a p (world coordinates in mm) is //## inside the bounding box bool IsInside(const mitk::Point3D& p) const { mitk::Point3D index; WorldToIndex(p, index); return IsIndexInside(index); } //##Documentation //## @brief Test whether the point \a p ((continous!)index coordinates in units) is //## inside the bounding box bool IsIndexInside(const mitk::Point3D& index) const { bool inside = false; //if it is an image geometry, we need to convert the index to discrete values //this is done by applying the rounding function also used in WorldToIndex (see line 323) if (m_ImageGeometry) { mitk::Point3D discretIndex; discretIndex[0]=itk::Math::RoundHalfIntegerUp( index[0] ); discretIndex[1]=itk::Math::RoundHalfIntegerUp( index[1] ); discretIndex[2]=itk::Math::RoundHalfIntegerUp( index[2] ); inside = m_BoundingBox->IsInside(discretIndex); //we have to check if the index is at the upper border of each dimension, // because the boundingbox is not centerbased if (inside) { const BoundingBox::BoundsArrayType& bounds = m_BoundingBox->GetBounds(); if((discretIndex[0] == bounds[1]) || (discretIndex[1] == bounds[3]) || (discretIndex[2] == bounds[5])) inside = false; } } else inside = m_BoundingBox->IsInside(index); return inside; } //##Documentation //## @brief Convenience method for working with ITK indices template bool IsIndexInside(const itk::Index &index) const { int i, dim=index.GetIndexDimension(); Point3D pt_index; pt_index.Fill(0); for ( i = 0; i < dim; ++i ) { pt_index[i] = index[i]; } return IsIndexInside(pt_index); } //##Documentation //## @brief Get the spacing (size of a pixel). //## itkGetConstReferenceMacro(Spacing, mitk::Vector3D); //##Documentation //## @brief Get the spacing as a float[3] array. const float* GetFloatSpacing() const; //##Documentation //## @brief Set the spacing (m_Spacing) virtual void SetSpacing(const mitk::Vector3D& aSpacing); //##Documentation //## @brief Get the DICOM FrameOfReferenceID referring to the //## used world coordinate system itkGetConstMacro(FrameOfReferenceID, unsigned int); //##Documentation //## @brief Set the DICOM FrameOfReferenceID referring to the //## used world coordinate system itkSetMacro(FrameOfReferenceID, unsigned int); //##Documentation //## @brief Copy the ITK transform //## (m_IndexToWorldTransform) to the VTK transform //## \sa SetIndexToWorldTransform void TransferItkToVtkTransform(); //##Documentation //## @brief Copy the VTK transform //## to the ITK transform (m_IndexToWorldTransform) //## \sa SetIndexToWorldTransform void TransferVtkToItkTransform(); //##Documentation //## @brief Get the parametric bounding-box //## //## See AbstractTransformGeometry for an example usage of this. itkGetConstObjectMacro(ParametricBoundingBox, BoundingBox); //##Documentation //## @brief Get the parametric bounds //## //## See AbstractTransformGeometry for an example usage of this. const BoundingBox::BoundsArrayType& GetParametricBounds() const { assert(m_ParametricBoundingBox.IsNotNull()); return m_ParametricBoundingBox->GetBounds(); } //##Documentation //## @brief Get the parametric extent //## //## See AbstractTransformGeometry for an example usage of this. mitk::ScalarType GetParametricExtent(int direction) const { if (direction < 0 || direction>=3) mitkThrow() << "Invalid direction. Must be between either 0, 1 or 2. "; assert(m_ParametricBoundingBox.IsNotNull()); BoundingBoxType::BoundsArrayType bounds = m_ParametricBoundingBox->GetBounds(); return bounds[direction*2+1]-bounds[direction*2]; } //##Documentation //## @brief Get the parametric extent in mm //## //## See AbstractTransformGeometry for an example usage of this. virtual mitk::ScalarType GetParametricExtentInMM(int direction) const { return GetExtentInMM(direction); } //##Documentation //## @brief Get the parametric transform //## //## See AbstractTransformGeometry for an example usage of this. virtual const itk::Transform* GetParametricTransform() const { return m_IndexToWorldTransform; } //##Documentation //## @brief Calculates a bounding-box around the geometry relative //## to a coordinate system defined by a transform //## mitk::BoundingBox::Pointer CalculateBoundingBoxRelativeToTransform(const mitk::AffineTransform3D* transform) const; //##Documentation //## @brief clones the geometry //## //## Overwrite in all sub-classes. //## Normally looks like: //## \code //## Self::Pointer newGeometry = new Self(*this); //## newGeometry->UnRegister(); //## return newGeometry.GetPointer(); //## \endcode virtual itk::LightObject::Pointer InternalClone() const; //##Documentation //##@brief executes affine operations (translate, rotate, scale) virtual void ExecuteOperation(Operation* operation); /** Set/Get the IndexToWorldTransform */ itkGetConstObjectMacro(IndexToWorldTransform, AffineTransform3D); itkGetObjectMacro(IndexToWorldTransform, AffineTransform3D); /** Get the bounding box */ itkGetConstObjectMacro(BoundingBox, BoundingBoxType); const BoundsArrayType GetBounds() const { assert(m_BoundingBox.IsNotNull()); return m_BoundingBox->GetBounds(); } /** Get the extent of the bounding box */ ScalarType GetExtent(unsigned int direction) const { assert(m_BoundingBox.IsNotNull()); if (direction>=NDimensions) mitkThrow() << "Direction is too big. This geometry is for 3D Data"; BoundsArrayType bounds = m_BoundingBox->GetBounds(); return bounds[direction*2+1]-bounds[direction*2]; } protected: Geometry3D(); Geometry3D(const Geometry3D& other); virtual void InitializeGeometry(Self * newGeometry) const; static const std::string GetTransformAsString( TransformType* transformType ); static const unsigned int NDimensions = 3; virtual ~Geometry3D(); virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; virtual void BackTransform(const mitk::Point3D& in, mitk::Point3D& out) const; //##Documentation //## @brief Deprecated virtual void BackTransform(const mitk::Point3D& at, const mitk::Vector3D& in, mitk::Vector3D& out) const; //Without redundant parameter Point3D virtual void BackTransform(const mitk::Vector3D& in, mitk::Vector3D& out) const; //##Documentation //## @brief Set the parametric bounds //## //## Protected in this class, made public in some sub-classes, e.g., //## ExternAbstractTransformGeometry. virtual void SetParametricBounds(const BoundingBox::BoundsArrayType& bounds); /** Resets sub-transforms that compose m_IndexToWorldTransform, by using * the current value of m_IndexToWorldTransform and setting the rotation * component to zero. */ virtual void ResetSubTransforms(); mutable mitk::BoundingBox::Pointer m_ParametricBoundingBox; mutable mitk::TimeBounds m_TimeBounds; vtkMatrix4x4* m_VtkMatrix; bool m_ImageGeometry; AffineTransform3D::Pointer m_IndexToWorldTransform; mutable BoundingBoxPointer m_BoundingBox; //##Documentation //## @brief Spacing of the data. Only significant if the geometry describes //## an Image (m_ImageGeometry==true). mitk::Vector3D m_Spacing; bool m_Valid; unsigned int m_FrameOfReferenceID; static const std::string INDEX_TO_OBJECT_TRANSFORM; static const std::string OBJECT_TO_NODE_TRANSFORM; static const std::string INDEX_TO_NODE_TRANSFORM; static const std::string INDEX_TO_WORLD_TRANSFORM; private: mutable TransformType::Pointer m_InvertedTransform; mutable unsigned long m_IndexToWorldTransformLastModified; VnlQuaternionType m_RotationQuaternion; float m_FloatSpacing[3]; vtkMatrixToLinearTransform* m_VtkIndexToWorldTransform; //##Documentation //## @brief Origin, i.e. upper-left corner of the plane //## Point3D m_Origin; }; // // Static compare functions mainly for testing // /** * @brief Equal A function comparing two geometries for beeing identical. * @warning This method is deprecated and will not be available in the future. Use the \a bool mitk::Equal(const mitk::mitk::Geometry3D& g1, const mitk::Geometry3D& g2) instead. * * @ingroup MITKTestingAPI * * The function compares the spacing, origin, axisvectors, extents, the matrix of the * IndexToWorldTransform (elementwise), the bounding (elementwise) and the ImageGeometry flag. * * The parameter eps is a tolarence value for all methods which are internally used for comparion. * If you want to use different tolarance values for different parts of the geometry, feel free to use * the other comparison methods and write your own implementation of Equal. * @param rightHandSide Compare this against leftHandSide. * @param leftHandSide Compare this against rightHandSide. * @param eps Tolarence for comparison. You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return True, if all comparison are true. False in any other case. */ DEPRECATED( MITK_CORE_EXPORT bool Equal(const mitk::Geometry3D* leftHandSide, const mitk::Geometry3D* rightHandSide, ScalarType eps, bool verbose)); /** * @brief Equal A function comparing two geometries for beeing identical. * * @ingroup MITKTestingAPI * * The function compares the spacing, origin, axisvectors, extents, the matrix of the * IndexToWorldTransform (elementwise), the bounding (elementwise) and the ImageGeometry flag. * * The parameter eps is a tolarence value for all methods which are internally used for comparion. * If you want to use different tolarance values for different parts of the geometry, feel free to use * the other comparison methods and write your own implementation of Equal. * @param rightHandSide Compare this against leftHandSide. * @param leftHandSide Compare this against rightHandSide. * @param eps Tolarence for comparison. You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return True, if all comparison are true. False in any other case. */ MITK_CORE_EXPORT bool Equal(const mitk::Geometry3D& leftHandSide, const mitk::Geometry3D& rightHandSide, ScalarType eps, bool verbose); /** * @brief Equal A function comparing two transforms (TransformType) for beeing identical. * @warning This method is deprecated and will not be available in the future. Use the \a bool mitk::Equal(const mitk::mitk::Geometry3D::TransformType& t1, const mitk::Geometry3D::TransformType& t2) instead. * * @ingroup MITKTestingAPI * * The function compares the IndexToWorldTransform (elementwise). * * The parameter eps is a tolarence value for all methods which are internally used for comparion. * @param rightHandSide Compare this against leftHandSide. * @param leftHandSide Compare this against rightHandSide. * @param eps Tolarence for comparison. You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return True, if all comparison are true. False in any other case. */ DEPRECATED( MITK_CORE_EXPORT bool Equal(const mitk::Geometry3D::TransformType *leftHandSide, const mitk::Geometry3D::TransformType *rightHandSide, ScalarType eps, bool verbose)); /** * @brief Equal A function comparing two transforms (TransformType) for beeing identical. * * @ingroup MITKTestingAPI * * The function compares the IndexToWorldTransform (elementwise). * * The parameter eps is a tolarence value for all methods which are internally used for comparion. * @param rightHandSide Compare this against leftHandSide. * @param leftHandSide Compare this against rightHandSide. * @param eps Tolarence for comparison. You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return True, if all comparison are true. False in any other case. */ MITK_CORE_EXPORT bool Equal(const mitk::Geometry3D::TransformType& leftHandSide, const mitk::Geometry3D::TransformType& rightHandSide, ScalarType eps, bool verbose); /** * @brief Equal A function comparing two bounding boxes (BoundingBoxType) for beeing identical. * @warning This method is deprecated and will not be available in the future. Use the \a bool mitk::Equal(const mitk::mitk::Geometry3D::BoundingBoxType& b1, const mitk::Geometry3D::BoundingBoxType& b2) instead. * * @ingroup MITKTestingAPI * * The function compares the bounds (elementwise). * * The parameter eps is a tolarence value for all methods which are internally used for comparion. * @param rightHandSide Compare this against leftHandSide. * @param leftHandSide Compare this against rightHandSide. * @param eps Tolarence for comparison. You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return True, if all comparison are true. False in any other case. */ DEPRECATED( MITK_CORE_EXPORT bool Equal( const mitk::Geometry3D::BoundingBoxType *leftHandSide, const mitk::Geometry3D::BoundingBoxType *rightHandSide, ScalarType eps, bool verbose)); /** * @brief Equal A function comparing two bounding boxes (BoundingBoxType) for beeing identical. * * @ingroup MITKTestingAPI * * The function compares the bounds (elementwise). * * The parameter eps is a tolarence value for all methods which are internally used for comparion. * @param rightHandSide Compare this against leftHandSide. * @param leftHandSide Compare this against rightHandSide. * @param eps Tolarence for comparison. You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return True, if all comparison are true. False in any other case. */ MITK_CORE_EXPORT bool Equal( const mitk::Geometry3D::BoundingBoxType& leftHandSide, const mitk::Geometry3D::BoundingBoxType& rightHandSide, ScalarType eps, bool verbose); } // namespace mitk #endif /* GEOMETRY3D_H_HEADER_INCLUDED_C1EBD0AD */ diff --git a/Core/Code/DataManagement/mitkLevelWindow.h b/Core/Code/DataManagement/mitkLevelWindow.h index 41933e7fb1..5943b4c99f 100644 --- a/Core/Code/DataManagement/mitkLevelWindow.h +++ b/Core/Code/DataManagement/mitkLevelWindow.h @@ -1,241 +1,241 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C #define LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include namespace mitk { class Image; /** * @brief The LevelWindow class Class to store level/window values. * * Current min and max value are stored in m_LowerWindowBound and m_UpperWindowBound. * The maximum and minimum of valid value range is stored in m_RangeMin and m_RangeMax. * m_DefaultLevel amd m_DefaultWindow store the initial Level/Window values for the image. * m_DefaultRangeMin and m_DefaultRangeMax store the initial minrange and maxrange for the image. * * See documentation of SetAuto for information on how the level window is initialized from an image. * * @ingroup DataManagement * * @note If you want to apply the mitk::LevelWindow to an mitk::Image, make sure * to use the mitk::LevelWindowProperty and set the mitk::RenderingModeProperty * to a mode which supports level window (e.g. LEVELWINDOW_COLOR). * Make sure to check the documentation of the mitk::RenderingModeProperty. For a * code example how to use the mitk::LevelWindowProperty check the * mitkImageVtkMapper2DLevelWindowTest.cpp in Core\Code\Testing. */ class MITK_CORE_EXPORT LevelWindow { public: LevelWindow(ScalarType level=127.5, ScalarType window=255.0); LevelWindow(const mitk::LevelWindow& levWin); virtual ~LevelWindow(); /*! * \brief method that returns the level value, i.e. the center of * the current grey value interval */ ScalarType GetLevel() const; /*! * \brief returns the current window size, i.e the range size of the current grey value interval */ ScalarType GetWindow() const; /*! * \brief method returns the default level value for the image */ ScalarType GetDefaultLevel() const; /*! * \brief returns the default window size for the image */ ScalarType GetDefaultWindow() const; /*! * \brief Resets the level and the window value to the default values */ void ResetDefaultLevelWindow(); /*! * Returns the minimum Value of the window */ ScalarType GetLowerWindowBound() const; /*! * Returns the upper window bound value of the window */ ScalarType GetUpperWindowBound() const; /*! * To set the level and the window value */ void SetLevelWindow(ScalarType level, ScalarType window, bool expandRangesIfNecessary = true); /*! * Set the lower and upper bound of the window */ void SetWindowBounds(ScalarType lowerBound, ScalarType upperBound, bool expandRangesIfNecessary = true); /*! * sets the window to its maximum Size in scaleRange */ void SetToMaxWindowSize(); /*! * Set the range minimum and maximum value */ void SetRangeMinMax(ScalarType min, ScalarType max); /*! * Get the range minimum value */ ScalarType GetRangeMin() const; /*! * Get the range maximum value */ ScalarType GetRangeMax() const; /*! * Get the default range minimum value */ ScalarType GetDefaultLowerBound() const; /*! * Get the default range maximum value */ ScalarType GetDefaultUpperBound() const; /*! * \brief the default min and max range for image will be reset */ void ResetDefaultRangeMinMax(); /**! * \brief returns the size of the grey value range */ ScalarType GetRange() const; /*! * set the default level and window value */ void SetDefaultLevelWindow(ScalarType level, ScalarType window); /*! * set the default Bounderies */ void SetDefaultBoundaries(ScalarType low, ScalarType up); /**! * \brief sets level/window to the min/max greyvalues of the given Image */ void SetAuto(const mitk::Image* image, bool tryPicTags = true, bool guessByCentralSlice = true); /** * If a level window is set to fixed, the set and get methods won't accept * modifications to the level window settings anymore. This behaviour can * be turned of by setting fixed to false; */ void SetFixed( bool fixed ); /** * Returns whether the level window settings are fixed (@see SetFixed(bool)) or not */ bool GetFixed() const; /** * Returns whether the level window settings are fixed (@see SetFixed(bool)) or not */ bool IsFixed() const; /*! * \brief equality operator implementation that allows to compare two level windows */ virtual bool operator==(const LevelWindow& levWin) const; /*! * \brief non equality operator implementation that allows to compare two level windows */ virtual bool operator!=(const LevelWindow& levWin) const; /*! * \brief implementation necessary because operator made * private in itk::Object */ virtual LevelWindow& operator=(const LevelWindow& levWin); protected: /*! * lower bound of current window */ ScalarType m_LowerWindowBound; /*! * upper bound of current window */ ScalarType m_UpperWindowBound; /*! * minimum gray value of the window */ ScalarType m_RangeMin; /*! * maximum gray value of the window */ ScalarType m_RangeMax; /*! * default minimum gray value of the window */ ScalarType m_DefaultLowerBound; /*! * default maximum gray value of the window */ ScalarType m_DefaultUpperBound; /*! * Defines whether the level window settings may be changed after * initialization or not. */ bool m_Fixed; /*! * confidence tests * * if m_LowerWindowBound > m_UpperWindowBound, then the values for m_LowerWindowBound and m_UpperWindowBound will be exchanged * * if m_LowerWindowBound < m_RangeMin, m_LowerWindowBound will be set to m_RangeMin. m_UpperWindowBound will be decreased the same as m_LowerWindowBound will be increased, but minimum value for m_UpperWindowBound is also m_RangeMin. * * if m_UpperWindowBound > m_RangeMax, m_UpperWindowBound will be set to m_RangeMax. m_LowerWindowBound will be increased the same as m_UpperWindowBound will be decreased, but maximum value for m_LowerWindowBound is also m_RangeMax. * */ inline void EnsureConsistency(); }; } // namespace mitk #endif /* LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C */ diff --git a/Core/Code/DataManagement/mitkLine.h b/Core/Code/DataManagement/mitkLine.h index 1040fb568d..7a4fafd853 100644 --- a/Core/Code/DataManagement/mitkLine.h +++ b/Core/Code/DataManagement/mitkLine.h @@ -1,427 +1,427 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKLINE_H_HEADER_INCLUDED_C19C01E2 #define MITKLINE_H_HEADER_INCLUDED_C19C01E2 -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include #include #include #include namespace mitk { //##Documentation //## @brief Descibes a line //## @ingroup Geometry template class Line { public: Line() { m_Point.Fill(0); m_Direction.Fill(0); }; //##Documentation //## @brief Define line by point and direction //## //## Length of direction defines the the length of the line Line( const itk::Point& point, const itk::Vector& direction ) { this->m_Point = point; this->m_Direction = direction; } //##Documentation //## @brief Get start point of the line const itk::Point& GetPoint() const { return m_Point; } //##Documentation //## @brief Get start point of the line itk::Point& GetPoint() { return m_Point; } //##Documentation //## @brief Get point on the line with parameter @a t //## //## @return m_Point+t*m_Direction const itk::Point GetPoint(TCoordRep t) const { return m_Point+m_Direction*t; } //##Documentation //## @brief Set/change start point of the line void SetPoint( const itk::Point& point1 ) { itk::Point point2; point2 = m_Point + m_Direction; m_Point = point1; m_Direction = point2.GetVectorFromOrigin() - point1.GetVectorFromOrigin(); } //##Documentation //## @brief Get the direction vector of the line const itk::Vector& GetDirection() const { return m_Direction; } //##Documentation //## @brief Get the direction vector of the line itk::Vector& GetDirection() { return m_Direction; } //##Documentation //## @brief Set the direction vector of the line void SetDirection( const itk::Vector& direction ) { m_Direction = direction; } //##Documentation //## @brief Define line by point and direction //## //## Length of direction defines the the length of the line void Set( const itk::Point& point, const itk::Vector& direction ) { this->m_Point = point; this->m_Direction = direction; } //##Documentation //## @brief Define line by two points void SetPoints( const itk::Point& point1, const itk::Point& point2 ) { this->m_Point = point1; //this->m_Direction.sub( point2, point1 ); m_Direction = point2 - point1; } //##Documentation //## @brief Set/change start point of the line void SetPoint1( const itk::Point& point1 ) { itk::Vector point2; point2 = m_Point + m_Direction; m_Point = point1; m_Direction = point2 - point1; } //##Documentation //## @brief Get start point of the line const itk::Point& GetPoint1() const { return m_Point; } //##Documentation //## @brief Set/change end point of the line void SetPoint2( const itk::Point& point2 ) { m_Direction = point2 - m_Point; } //##Documentation //## @brief Get end point of the line itk::Point GetPoint2() const { itk::Point point2; point2 = m_Point+m_Direction; return point2; } //##Documentation //## @brief Transform the line with a Transform void Transform(itk::Transform& transform) { m_Direction = transform.TransformVector(m_Direction); m_Point = transform.TransformPoint(m_Point); } //##Documentation //## @brief Transform the line with a matrix //## //## Only the direction will be changed, not the start point. void Transform( const itk::Matrix& matrix ) { m_Direction = matrix*m_Direction; } //##Documentation //## @brief Distance between two lines double Distance( const Line& line ) const; //##Documentation //## @brief Distance of a point from the line double Distance( const itk::Point& point ) const { itk::Vector diff; diff = Project(point)-point; return diff.GetNorm(); } //##Documentation //## @brief Project a point on the line itk::Point Project( const itk::Point& point ) const { if(m_Direction.GetNorm()==0) return this->m_Point; itk::Vector diff; diff = point-this->m_Point; itk::Vector normalizedDirection = m_Direction; normalizedDirection.Normalize(); normalizedDirection *= dot_product(diff.GetVnlVector(), normalizedDirection.GetVnlVector()); return this->m_Point + normalizedDirection; } //##Documentation //## @brief Test if a point is part of the line //## //## Length of the direction vector defines the length of the line bool IsPartOfStraightLine( const itk::Point& point ) const { if( Distance( point ) > eps ) return false; itk::Vector diff; diff = point - this->m_Point; if( diff*m_Direction < 0 ) return false; if( diff.GetSquaredNorm() <= m_Direction.GetSquaredNorm() ) return true; return false; } //##Documentation //## @brief Test if a point is part of the line (line having infinite length) bool IsPartOfLine( const itk::Point& point ) const { if ( Distance( point ) < eps ) return true; return false; } //##Documentation //## @brief Test if a lines is parallel to this line bool IsParallel( const Line& line) const { vnl_vector normal; normal = vnl_cross_3d( m_Direction.GetVnlVector(), line.GetDirection().GetVnlVector() ); if ( normal.squared_magnitude() < eps ) return true; return false; } //##Documentation //## @brief Test if a line is part of the line (line having infinite length) bool IsPartOfLine( const Line& line ) const { return ( Distance( line.GetPoint() ) < 0 ) && ( IsParallel( line ) ); } //##Documentation //## @brief Test if the two lines are identical //## //## Start point and direction and length of direction vector must be //## equal for identical lines. bool operator==( const Line& line ) const { itk::Vector diff; diff = GetPoint1()-line.GetPoint1(); if(diff.GetSquaredNorm() > eps) return false; diff = GetPoint2()-line.GetPoint2(); if(diff.GetSquaredNorm() > eps) return false; return true; } //##Documentation //## @brief Set the line by another line inline const Line& operator=( const Line& line ) { m_Point = line.GetPoint(); m_Direction = line.GetDirection(); return *this; } //##Documentation //## @brief Test if two lines are not identical //## //## \sa operator== bool operator!=( const Line& line ) const { return !((*this)==line); } //##Documentation //## @brief Calculates the intersection points of a straight line in 2D //## with a rectangle //## //## @param x1,y1,x2,y2 rectangle //## @param p,d straight line: p point on it, d direction of line //## @param s1 first intersection point (valid only if s_num>0) //## @param s2 second intersection point (valid only if s_num==2) //## @return number of intersection points (0<=s_num<=2) static int RectangleLineIntersection( TCoordRep x1, TCoordRep y1, TCoordRep x2, TCoordRep y2, itk::Point< TCoordRep, 2 > p, itk::Vector< TCoordRep, 2 > d, itk::Point< TCoordRep, 2 > &s1, itk::Point< TCoordRep, 2 > &s2 ) { int s_num; TCoordRep t; s_num=0; /*test if intersecting with the horizontal axis*/ if(fabs(d[0])>eps) { t=(x1-p[0])/d[0]; itk::Point l=p+d*t; if((l[1]>=y1) && (l[1]eps) { t=(x2-p[0])/d[0]; itk::Point l=p+d*t; if((l[1]>=y1) && (l[1]eps) { t=(y1-p[1])/d[1]; itk::Point l=p+d*t; if((l[0]>=x1) && (l[0]eps) { t=(y2-p[1])/d[1]; itk::Point l=p+d*t; if((l[0]>=x1) && (l[0]0) * \param s2 second intersection point (valid only if s_num==2) * \return number of intersection points (0<=s_num<=2) */ static int BoxLineIntersection( TCoordRep x1, TCoordRep y1, TCoordRep z1, TCoordRep x2, TCoordRep y2, TCoordRep z2, itk::Point< TCoordRep, 3 > p, itk::Vector< TCoordRep, 3 > d, itk::Point< TCoordRep, 3 > &s1, itk::Point< TCoordRep, 3 > &s2 ) { int num = 0; ScalarType box[6]; box[0] = x1; box[1] = x2; box[2] = y1; box[3] = y2; box[4] = z1; box[5] = z2; itk::Point< TCoordRep, 3 > point; int i, j; for ( i = 0; i < 6; ++i ) { j = i / 2; if ( fabs( d[j] ) > eps ) { ScalarType lambda = (box[i] - p[j]) / d[j]; point = p + d * lambda; int k = (j + 1) % 3; int l = (j + 2) % 3; if ( (point[k] >= box[k*2]) && (point[k] <= box[k*2+1]) && (point[l] >= box[l*2]) && (point[l] <= box[l*2+1]) ) { if ( num == 0 ) { s1 = point; } else { s2 = point; } ++num; } } } return num; } protected: itk::Point m_Point; itk::Vector m_Direction; }; typedef Line Line3D; } // namespace mitk #endif /* MITKLINE_H_HEADER_INCLUDED_C19C01E2 */ diff --git a/Core/Code/DataManagement/mitkMatrix.h b/Core/Code/DataManagement/mitkMatrix.h index 0a8ab4a3d7..4e682b903e 100644 --- a/Core/Code/DataManagement/mitkMatrix.h +++ b/Core/Code/DataManagement/mitkMatrix.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 MITKMATRIX_H_ #define MITKMATRIX_H_ #include -#include "mitkConstants.h" +#include "mitkNumericConstants.h" #include "mitkArray.h" #include "mitkEqual.h" namespace mitk { template< class T, unsigned int NRows = 3, unsigned int NColumns = 3 > class Matrix : public itk::Matrix { public: /** Standard class typedefs. */ typedef Matrix Self; typedef typename itk::Matrix::InternalMatrixType InternalMatrixType; /** Default constructor. */ - Matrix() : + explicit Matrix() : itk::Matrix() {} /** Copy constructor. */ - Matrix(const Matrix & matrix) : + explicit Matrix(const Matrix & matrix) : itk::Matrix(matrix) {} /** Copy constructor for itk compatibility */ Matrix(const itk::Matrix & matrix) : itk::Matrix(matrix) {} /**For every operator=, there should be an equivalent copy constructor. */ inline Matrix(const vnl_matrix< T > & matrix) : itk::Matrix(matrix) {} /**For every operator=, there should be an equivalent copy constructor. */ inline explicit Matrix(InternalMatrixType & matrix) : itk::Matrix(matrix) {} /** * Necessary because otherwise operator= is default operator= from Matrix. */ using itk::Matrix::operator=; /** * Copies the elements from array array to this. * Note that this method will assign doubles to floats without complaining! * * @param array the array whose values shall be copied. Must overload [] operator. */ template - void FromArray(const ArrayType& array) + void FillMatrix(const ArrayType& array) { for (unsigned i = 0; i < NRows; i++) { for (unsigned j = 0; j < NColumns; j++) { (*this)[i][j] = array[i][j]; } } }; /** - * Warning: Array must have same dimension as Matrix + * Warning: matrix must have same dimension as Matrix */ - template - void ToArray(ArrayType array) const + template + void ToArray(MatrixType matrix) const { for (unsigned i = 0; i < NRows; i++) { for (unsigned j = 0; j < NColumns; j++) { - array[i][j] = (*this)[i][j]; + matrix[i][j] = (*this)[i][j]; } } } }; typedef Matrix Matrix2D; typedef Matrix Matrix3D; typedef Matrix Matrix4D; /*! \brief Check for matrix equality with a user defined accuracy. As an equality metric the root mean squared error (RMS) of all elements is calculated. \param matrix1 first vnl matrix \param matrix2 second vnl matrix \param epsilon user defined accuracy bounds */ template inline bool MatrixEqualRMS(const vnl_matrix_fixed& matrix1,const vnl_matrix_fixed& matrix2,mitk::ScalarType epsilon=mitk::eps) { if ( (matrix1.rows() == matrix2.rows()) && (matrix1.cols() == matrix2.cols()) ) { vnl_matrix_fixed differenceMatrix = matrix1-matrix2; if (differenceMatrix.rms() inline bool MatrixEqualRMS(const itk::Matrix& matrix1,const itk::Matrix& matrix2,mitk::ScalarType epsilon=mitk::eps) { return mitk::MatrixEqualRMS(matrix1.GetVnlMatrix(),matrix2.GetVnlMatrix(),epsilon); } /*! \brief Check for element-wise matrix equality with a user defined accuracy. \param matrix1 first vnl matrix \param matrix2 second vnl matrix \param epsilon user defined accuracy bounds */ template inline bool MatrixEqualElementWise(const vnl_matrix_fixed& matrix1,const vnl_matrix_fixed& matrix2,mitk::ScalarType epsilon=mitk::eps) { if ( (matrix1.rows() == matrix2.rows()) && (matrix1.cols() == matrix2.cols()) ) { for( unsigned int r=0; r inline bool MatrixEqualElementWise(const itk::Matrix& matrix1,const itk::Matrix& matrix2,mitk::ScalarType epsilon=mitk::eps) { return mitk::MatrixEqualElementWise(matrix1.GetVnlMatrix(),matrix2.GetVnlMatrix(),epsilon); } } #endif /* MITKMATRIX_H_ */ diff --git a/Core/Code/DataManagement/mitkConstants.cpp b/Core/Code/DataManagement/mitkNumericConstants.cpp similarity index 95% rename from Core/Code/DataManagement/mitkConstants.cpp rename to Core/Code/DataManagement/mitkNumericConstants.cpp index 913920fd6f..58a1382ec5 100644 --- a/Core/Code/DataManagement/mitkConstants.cpp +++ b/Core/Code/DataManagement/mitkNumericConstants.cpp @@ -1,23 +1,23 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkConstants.h" +#include "mitkNumericConstants.h" #include "vnl/vnl_math.h" #include const mitk::ScalarType mitk::eps = vnl_math::eps*100; const mitk::ScalarType mitk::sqrteps = vnl_math::sqrteps; extern const mitk::ScalarType mitk::large = std::numeric_limits::max(); diff --git a/Core/Code/DataManagement/mitkConstants.h b/Core/Code/DataManagement/mitkNumericConstants.h similarity index 88% rename from Core/Code/DataManagement/mitkConstants.h rename to Core/Code/DataManagement/mitkNumericConstants.h index 56582e954e..8ebbb96b6c 100644 --- a/Core/Code/DataManagement/mitkConstants.h +++ b/Core/Code/DataManagement/mitkNumericConstants.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 MITKDATATYPEBASICS_H -#define MITKDATATYPEBASICS_H +#ifndef MITKNUMERICCONSTANTS_H_ +#define MITKNUMERICCONSTANTS_H_ #include namespace mitk { typedef double ScalarType; MITK_CORE_EXPORT extern const ScalarType eps; MITK_CORE_EXPORT extern const ScalarType sqrteps; MITK_CORE_EXPORT extern const double large; } -#endif // MITKDATATYPEBASICS_H +#endif // MITKNUMERICCONSTANTS_H_ diff --git a/Core/Code/DataManagement/mitkNumericTypes.h b/Core/Code/DataManagement/mitkNumericTypes.h new file mode 100644 index 0000000000..ec9b99c320 --- /dev/null +++ b/Core/Code/DataManagement/mitkNumericTypes.h @@ -0,0 +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 MITKNUMERICTYPES_H_ +#define MITKNUMERICTYPES_H_ + + +#include "mitkNumericConstants.h" +#include "mitkQuaternion.h" +#include "mitkAffineTransform3D.h" +#include "mitkPoint.h" +#include "mitkVector.h" +#include "mitkMatrix.h" +#include "mitkEqual.h" + + +// this include hold the old deprecated ways to convert from itk 2 vtk and the likes. +// calls to these functions shall be removed in future bugsquashings so that this include can be removed. +#include "mitkVectorDeprecated.h" + + + + + + +#endif /* MITKNUMERICTYPES_H_ */ diff --git a/Core/Code/DataManagement/mitkPlaneOperation.h b/Core/Code/DataManagement/mitkPlaneOperation.h index 19f2a50d5e..34d7a5f8c4 100644 --- a/Core/Code/DataManagement/mitkPlaneOperation.h +++ b/Core/Code/DataManagement/mitkPlaneOperation.h @@ -1,60 +1,60 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKPlaneOperation_H #define MITKPlaneOperation_H #include #include "mitkPointOperation.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" namespace mitk { /** * @brief Operation for setting a plane (defined by its origin and normal) * * @ingroup Undo */ class MITK_CORE_EXPORT PlaneOperation : public PointOperation { public: PlaneOperation( OperationType operationType, Point3D point, Vector3D normal ); PlaneOperation( OperationType operationType, Point3D point, Vector3D axisVec0, Vector3D axisVec1 ); virtual ~PlaneOperation(); Vector3D GetNormal(); Vector3D GetAxisVec0(); Vector3D GetAxisVec1(); bool AreAxisDefined(); private: Vector3D m_Normal; Vector3D m_AxisVec0; Vector3D m_AxisVec1; bool m_AreAxisDefined; }; } //namespace mitk #endif /* MITKPlaneOperation_H */ diff --git a/Core/Code/DataManagement/mitkPoint.h b/Core/Code/DataManagement/mitkPoint.h index 311ac0fb16..cfbc5956cc 100644 --- a/Core/Code/DataManagement/mitkPoint.h +++ b/Core/Code/DataManagement/mitkPoint.h @@ -1,135 +1,135 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKPOINT_H -#define MITKPOINT_H +#ifndef MITKPOINT_H_ +#define MITKPOINT_H_ #include -#include "mitkConstants.h" +#include "mitkNumericConstants.h" #include "mitkArray.h" #include "mitkEqual.h" namespace mitk { //##Documentation //##@brief enumeration of the type a point can be enum PointSpecificationType { PTUNDEFINED = 0, PTSTART, PTCORNER, PTEDGE, PTEND }; template class Point : public itk::Point { public: /** Default constructor has nothing to do. */ - Point() : itk::Point() {} + explicit Point() : itk::Point() {} /** Pass-through constructors for the Array base class. */ template< typename TPointValueType > - Point(const Point< TPointValueType, NPointDimension > & r):itk::Point(r) {} + explicit Point(const Point< TPointValueType, NPointDimension > & r):itk::Point(r) {} template< typename TPointValueType > - Point(const TPointValueType r[NPointDimension]):itk::Point(r) {} + explicit Point(const TPointValueType r[NPointDimension]):itk::Point(r) {} template< typename TPointValueType > Point(const TPointValueType & v):itk::Point(v) {} Point(const mitk::Point& r) : itk::Point(r) {} Point(const TCoordRep r[NPointDimension]):itk::Point(r) {} Point(const TCoordRep & v):itk::Point(v) {} Point(const itk::Point & p) : itk::Point(p) {} /** * Copies the elements from array array to this. * Note that this method will assign doubles to floats without complaining! * * @param array the array whose values shall be copied. Must overload [] operator. */ template - void FromArray(const ArrayType& array) + void FillPoint(const ArrayType& array) { itk::FixedArray* thisP = dynamic_cast* >(this); - mitk::FromArray(*thisP, array); + mitk::FillArray(*thisP, array); } /** * Copies the values stored in this point into the array array. * * @param array the array which should store the values of this. */ template - void ToArray(ArrayType array) + void ToArray(ArrayType array) const { mitk::ToArray(array, *this); } }; typedef Point Point2D; typedef Point Point3D; typedef Point Point4D; typedef Point Point2I; typedef Point Point3I; typedef Point Point4I; /** * @ingroup MITKTestingAPI * * @param point1 Point to compare. * @param point2 Point to compare. * @param eps Tolerance for floating point comparison. * @param verbose Flag indicating detailed console output. * @return True if points are equal. */ template inline bool Equal(const itk::Point& point1, const itk::Point& point2, TCoordRep eps=mitk::eps, bool verbose=false) { bool isEqual = true; typename itk::Point::VectorType diff = point1-point2; for (unsigned int i=0; i #include "mitkOperation.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" namespace mitk { //##Documentation //## @brief Operation that handles all actions on one Point. //## //## Stores everything for Adding, Moving and Deleting a Point. //## @ingroup Undo class MITK_CORE_EXPORT PointOperation : public Operation { public: //##Documentation //##@brief Operation that handles all actions on one Point. //## //## @param operationType is the type of the operation (see mitkOperation.h; e.g. move or add; Information for StateMachine::ExecuteOperation()); //## @param point is the information of the point to add or is the information to change a point into //## @param index is e.g. the position in a list which describes the element to change PointOperation(OperationType operationType, Point3D point, int index = -1, bool selected = true, PointSpecificationType type = PTUNDEFINED); //##Documentation //##@brief Operation that handles all actions on one Point. //## //## @param operationType is the type of the operation (see mitkOperation.h; e.g. move or add; Information for StateMachine::ExecuteOperation()); //## @param point is the information of the point to add or is the information to change a point into //## @param index is e.g. the position in a list which describes the element to change PointOperation(OperationType operationType, ScalarType timeInMS, Point3D point, int index = -1, bool selected = true, PointSpecificationType type = PTUNDEFINED); virtual ~PointOperation(); Point3D GetPoint(); int GetIndex(); bool GetSelected(); PointSpecificationType GetPointType(); ScalarType GetTimeInMS() const; private: Point3D m_Point; //##Documentation //##@brief to declare an index where to store the point in data int m_Index; //to declare weather the point is selected or deselected bool m_Selected; //##Documentation //##@brief to describe the type of the point. See enum PointSpecification for different types PointSpecificationType m_Type; ScalarType m_TimeInMS; }; }//namespace mitk #endif /* MITKPOINTOPERATION_H*/ diff --git a/Core/Code/DataManagement/mitkPointSet.cpp b/Core/Code/DataManagement/mitkPointSet.cpp index a4a838a610..3802d0563d 100755 --- a/Core/Code/DataManagement/mitkPointSet.cpp +++ b/Core/Code/DataManagement/mitkPointSet.cpp @@ -1,880 +1,880 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkPointSet.h" #include "mitkPointOperation.h" #include "mitkInteractionConst.h" -#include +#include #include mitk::PointSet::PointSet() { this->InitializeEmpty(); } mitk::PointSet::PointSet(const PointSet &other) : BaseData(other) , m_PointSetSeries(other.GetPointSetSeriesSize()) , m_CalculateBoundingBox(true) { // Copy points for (std::size_t t = 0; t < m_PointSetSeries.size(); ++t) { m_PointSetSeries[t] = DataType::New(); DataType::Pointer otherPts = other.GetPointSet(t); for (PointsConstIterator i = other.Begin(t); i != other.End(t); ++i) { m_PointSetSeries[t]->SetPoint(i.Index(), i.Value()); PointDataType pointData; if (otherPts->GetPointData(i.Index(), &pointData)) { m_PointSetSeries[t]->SetPointData(i.Index(), pointData); } } } } mitk::PointSet::~PointSet() { this->ClearData(); } void mitk::PointSet::ClearData() { m_PointSetSeries.clear(); Superclass::ClearData(); } void mitk::PointSet::InitializeEmpty() { m_PointSetSeries.resize( 1 ); m_PointSetSeries[0] = DataType::New(); PointDataContainer::Pointer pointData = PointDataContainer::New(); m_PointSetSeries[0]->SetPointData( pointData ); m_CalculateBoundingBox = false; Superclass::InitializeTimeGeometry(1); m_Initialized = true; } bool mitk::PointSet::IsEmptyTimeStep(unsigned int t) const { return IsInitialized() && (GetSize(t) == 0); } void mitk::PointSet::Expand( unsigned int timeSteps ) { // Check if the vector is long enough to contain the new element // at the given position. If not, expand it with sufficient pre-initialized // elements. // // NOTE: This method will never REDUCE the vector size; it should only // be used to make sure that the vector has enough elements to include the // specified time step. unsigned int oldSize = m_PointSetSeries.size(); if ( timeSteps > oldSize ) { Superclass::Expand( timeSteps ); m_PointSetSeries.resize( timeSteps ); for ( unsigned int i = oldSize; i < timeSteps; ++i ) { m_PointSetSeries[i] = DataType::New(); PointDataContainer::Pointer pointData = PointDataContainer::New(); m_PointSetSeries[i]->SetPointData( pointData ); } //if the size changes, then compute the bounding box m_CalculateBoundingBox = true; this->InvokeEvent( PointSetExtendTimeRangeEvent() ); } } unsigned int mitk::PointSet::GetPointSetSeriesSize() const { return m_PointSetSeries.size(); } int mitk::PointSet::GetSize( unsigned int t ) const { if ( t < m_PointSetSeries.size() ) { return m_PointSetSeries[t]->GetNumberOfPoints(); } else { return 0; } } mitk::PointSet::DataType::Pointer mitk::PointSet::GetPointSet( int t ) const { if ( t < (int)m_PointSetSeries.size() ) { return m_PointSetSeries[t]; } else { return NULL; } } mitk::PointSet::PointsIterator mitk::PointSet::Begin( int t ) { if (t >= 0 && t < static_cast(m_PointSetSeries.size())) { return m_PointSetSeries[t]->GetPoints()->Begin(); } return PointsIterator(); } mitk::PointSet::PointsConstIterator mitk::PointSet::Begin(int t) const { if (t >= 0 && t < static_cast(m_PointSetSeries.size())) { return m_PointSetSeries[t]->GetPoints()->Begin(); } return PointsConstIterator(); } mitk::PointSet::PointsIterator mitk::PointSet::End( int t ) { if (t >= 0 && t < static_cast(m_PointSetSeries.size())) { return m_PointSetSeries[t]->GetPoints()->End(); } return PointsIterator(); } mitk::PointSet::PointsConstIterator mitk::PointSet::End(int t) const { if (t >= 0 && t < static_cast(m_PointSetSeries.size())) { return m_PointSetSeries[t]->GetPoints()->End(); } return PointsConstIterator(); } int mitk::PointSet::SearchPoint( Point3D point, ScalarType distance, int t ) const { if ( t >= (int)m_PointSetSeries.size() ) { return -1; } // Out is the point which is checked to be the searched point PointType out; out.Fill( 0 ); PointType indexPoint; this->GetGeometry( t )->WorldToIndex(point, indexPoint); // Searching the first point in the Set, that is +- distance far away fro // the given point unsigned int i; PointsContainer::Iterator it, end; end = m_PointSetSeries[t]->GetPoints()->End(); int bestIndex = -1; distance = distance * distance; // To correct errors from converting index to world and world to index if (distance == 0.0) { distance = 0.000001; } ScalarType bestDist = distance; ScalarType dist, tmp; for ( it = m_PointSetSeries[t]->GetPoints()->Begin(), i = 0; it != end; ++it, ++i ) { bool ok = m_PointSetSeries[t]->GetPoints() ->GetElementIfIndexExists( it->Index(), &out ); if ( !ok ) { return -1; } else if ( indexPoint == out ) //if totally equal { return it->Index(); } //distance calculation tmp = out[0] - indexPoint[0]; dist = tmp * tmp; tmp = out[1] - indexPoint[1]; dist += tmp * tmp; tmp = out[2] - indexPoint[2]; dist += tmp * tmp; if ( dist < bestDist ) { bestIndex = it->Index(); bestDist = dist; } } return bestIndex; } mitk::PointSet::PointType mitk::PointSet::GetPoint( PointIdentifier id, int t ) const { PointType out; out.Fill(0); if ( (unsigned int) t >= m_PointSetSeries.size() ) { return out; } if ( m_PointSetSeries[t]->GetPoints()->IndexExists(id) ) { m_PointSetSeries[t]->GetPoint( id, &out ); this->GetGeometry(t)->IndexToWorld( out, out ); return out; } else { return out; } } bool mitk::PointSet ::GetPointIfExists( PointIdentifier id, PointType* point, int t ) const { if ( (unsigned int) t >= m_PointSetSeries.size() ) { return false; } if ( m_PointSetSeries[t]->GetPoints()->GetElementIfIndexExists(id, point) ) { this->GetGeometry( t )->IndexToWorld( *point, *point ); return true; } else { return false; } } void mitk::PointSet::SetPoint( PointIdentifier id, PointType point, int t ) { // Adapt the size of the data vector if necessary this->Expand( t+1 ); mitk::Point3D indexPoint; this->GetGeometry( t )->WorldToIndex( point, indexPoint ); m_PointSetSeries[t]->SetPoint( id, indexPoint ); PointDataType defaultPointData; defaultPointData.id = id; defaultPointData.selected = false; defaultPointData.pointSpec = mitk::PTUNDEFINED; m_PointSetSeries[t]->SetPointData( id, defaultPointData ); //boundingbox has to be computed anyway m_CalculateBoundingBox = true; this->Modified(); } void mitk::PointSet::SetPoint( PointIdentifier id, PointType point, PointSpecificationType spec, int t ) { // Adapt the size of the data vector if necessary this->Expand( t+1 ); mitk::Point3D indexPoint; this->GetGeometry( t )->WorldToIndex( point, indexPoint ); m_PointSetSeries[t]->SetPoint( id, indexPoint ); PointDataType defaultPointData; defaultPointData.id = id; defaultPointData.selected = false; defaultPointData.pointSpec = spec; m_PointSetSeries[t]->SetPointData( id, defaultPointData ); //boundingbox has to be computed anyway m_CalculateBoundingBox = true; this->Modified(); } void mitk::PointSet::InsertPoint( PointIdentifier id, PointType point, int t ) { this->InsertPoint(id, point, mitk::PTUNDEFINED, t); } void mitk::PointSet::InsertPoint( PointIdentifier id, PointType point, PointSpecificationType spec, int t ) { if ( (unsigned int) t < m_PointSetSeries.size() ) { mitk::Point3D indexPoint; mitk::Geometry3D* tempGeometry = this->GetGeometry( t ); if (tempGeometry == NULL) { MITK_INFO<< __FILE__ << ", l." << __LINE__ << ": GetGeometry of "<< t <<" returned NULL!" << std::endl; return; } tempGeometry->WorldToIndex( point, indexPoint ); m_PointSetSeries[t]->GetPoints()->InsertElement( id, indexPoint ); PointDataType defaultPointData; defaultPointData.id = id; defaultPointData.selected = false; defaultPointData.pointSpec = spec; m_PointSetSeries[t]->GetPointData()->InsertElement(id, defaultPointData); //boundingbox has to be computed anyway m_CalculateBoundingBox = true; this->Modified(); } } bool mitk::PointSet::SwapPointPosition( PointIdentifier id, bool moveUpwards, int t ) { if(IndexExists(id, t) ) { PointType point = GetPoint(id,t); if(moveUpwards) {//up if(IndexExists(id-1,t)) { InsertPoint(id, GetPoint(id - 1, t), t); InsertPoint(id-1,point,t); this->Modified(); return true; } } else {//down if(IndexExists(id+1,t)) { InsertPoint(id, GetPoint(id + 1, t), t); InsertPoint(id+1,point,t); this->Modified(); return true; } } } return false; } bool mitk::PointSet::IndexExists( int position, int t ) const { if ( (unsigned int) t < m_PointSetSeries.size() ) { return m_PointSetSeries[t]->GetPoints()->IndexExists( position ); } else { return false; } } bool mitk::PointSet::GetSelectInfo( int position, int t ) const { if ( this->IndexExists( position, t ) ) { PointDataType pointData = { 0, false, PTUNDEFINED }; m_PointSetSeries[t]->GetPointData( position, &pointData ); return pointData.selected; } else { return false; } } void mitk::PointSet::SetSelectInfo( int position, bool selected, int t ) { if ( this->IndexExists( position, t ) ) { // timeStep to ms TimePointType timeInMS = this->GetTimeGeometry()->TimeStepToTimePoint( t ); // point Point3D point = this->GetPoint( position, t ); std::auto_ptr op; if (selected) { op.reset(new mitk::PointOperation(OpSELECTPOINT, timeInMS, point, position )); } else { op.reset(new mitk::PointOperation(OpDESELECTPOINT, timeInMS, point, position )); } this->ExecuteOperation( op.get() ); } } mitk::PointSpecificationType mitk::PointSet::GetSpecificationTypeInfo( int position, int t ) const { if ( this->IndexExists( position, t ) ) { PointDataType pointData = { 0, false, PTUNDEFINED }; m_PointSetSeries[t]->GetPointData( position, &pointData ); return pointData.pointSpec; } else { return PTUNDEFINED; } } int mitk::PointSet::GetNumberOfSelected( int t ) const { if ( (unsigned int) t >= m_PointSetSeries.size() ) { return 0; } int numberOfSelected = 0; PointDataIterator it; for ( it = m_PointSetSeries[t]->GetPointData()->Begin(); it != m_PointSetSeries[t]->GetPointData()->End(); it++ ) { if (it->Value().selected == true) { ++numberOfSelected; } } return numberOfSelected; } int mitk::PointSet::SearchSelectedPoint( int t ) const { if ( (unsigned int) t >= m_PointSetSeries.size() ) { return -1; } PointDataIterator it; for ( it = m_PointSetSeries[t]->GetPointData()->Begin(); it != m_PointSetSeries[t]->GetPointData()->End(); it++ ) { if ( it->Value().selected == true ) { return it->Index(); } } return -1; } void mitk::PointSet::ExecuteOperation( Operation* operation ) { int timeStep = -1; mitkCheckOperationTypeMacro(PointOperation, operation, pointOp); if ( pointOp ) { timeStep = this->GetTimeGeometry()->TimePointToTimeStep( pointOp->GetTimeInMS() ); } if ( timeStep < 0 ) { MITK_ERROR << "Time step (" << timeStep << ") outside of PointSet time bounds" << std::endl; return; } switch (operation->GetOperationType()) { case OpNOTHING: break; case OpINSERT://inserts the point at the given position and selects it. { int position = pointOp->GetIndex(); PointType pt; pt.CastFrom(pointOp->GetPoint()); //transfer from world to index coordinates mitk::Geometry3D* geometry = this->GetGeometry( timeStep ); if (geometry == NULL) { MITK_INFO<<"GetGeometry returned NULL!\n"; return; } geometry->WorldToIndex(pt, pt); m_PointSetSeries[timeStep]->GetPoints()->InsertElement(position, pt); PointDataType pointData = { static_cast(pointOp->GetIndex()), pointOp->GetSelected(), pointOp->GetPointType() }; m_PointSetSeries[timeStep]->GetPointData() ->InsertElement(position, pointData); this->Modified(); //boundingbox has to be computed m_CalculateBoundingBox = true; this->InvokeEvent( PointSetAddEvent() ); this->OnPointSetChange(); } break; case OpMOVE://moves the point given by index { PointType pt; pt.CastFrom(pointOp->GetPoint()); //transfer from world to index coordinates this->GetGeometry( timeStep )->WorldToIndex(pt, pt); // Copy new point into container m_PointSetSeries[timeStep]->SetPoint(pointOp->GetIndex(), pt); // Insert a default point data object to keep the containers in sync // (if no point data object exists yet) PointDataType pointData; if ( !m_PointSetSeries[timeStep]->GetPointData( pointOp->GetIndex(), &pointData ) ) { m_PointSetSeries[timeStep]->SetPointData( pointOp->GetIndex(), pointData ); } this->OnPointSetChange(); this->Modified(); //boundingbox has to be computed anyway m_CalculateBoundingBox = true; this->InvokeEvent( PointSetMoveEvent() ); } break; case OpREMOVE://removes the point at given by position { m_PointSetSeries[timeStep]->GetPoints()->DeleteIndex((unsigned)pointOp->GetIndex()); m_PointSetSeries[timeStep]->GetPointData()->DeleteIndex((unsigned)pointOp->GetIndex()); this->OnPointSetChange(); this->Modified(); //boundingbox has to be computed anyway m_CalculateBoundingBox = true; this->InvokeEvent( PointSetRemoveEvent() ); } break; case OpSELECTPOINT://select the given point { PointDataType pointData = {0, false, PTUNDEFINED}; m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData); pointData.selected = true; m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData); this->Modified(); } break; case OpDESELECTPOINT://unselect the given point { PointDataType pointData = {0, false, PTUNDEFINED}; m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData); pointData.selected = false; m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData); this->Modified(); } break; case OpSETPOINTTYPE: { PointDataType pointData = {0, false, PTUNDEFINED}; m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData); pointData.pointSpec = pointOp->GetPointType(); m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData); this->Modified(); } break; case OpMOVEPOINTUP: // swap content of point with ID pointOp->GetIndex() with the point preceding it in the container // move point position within the pointset { PointIdentifier currentID = pointOp->GetIndex(); /* search for point with this id and point that precedes this one in the data container */ PointsContainer::STLContainerType points = m_PointSetSeries[timeStep]->GetPoints()->CastToSTLContainer(); PointsContainer::STLContainerType::iterator it = points.find(currentID); if (it == points.end()) // ID not found break; if (it == points.begin()) // we are at the first element, there is no previous element break; /* get and cache current point & pointdata and previous point & pointdata */ --it; PointIdentifier prevID = it->first; if (this->SwapPointContents(prevID, currentID, timeStep) == true) this->Modified(); } break; case OpMOVEPOINTDOWN: // move point position within the pointset { PointIdentifier currentID = pointOp->GetIndex(); /* search for point with this id and point that succeeds this one in the data container */ PointsContainer::STLContainerType points = m_PointSetSeries[timeStep]->GetPoints()->CastToSTLContainer(); PointsContainer::STLContainerType::iterator it = points.find(currentID); if (it == points.end()) // ID not found break; ++it; if (it == points.end()) // ID is already the last element, there is no succeeding element break; /* get and cache current point & pointdata and previous point & pointdata */ PointIdentifier nextID = it->first; if (this->SwapPointContents(nextID, currentID, timeStep) == true) this->Modified(); } break; default: itkWarningMacro("mitkPointSet could not understrand the operation. Please check!"); break; } //to tell the mappers, that the data is modified and has to be updated //only call modified if anything is done, so call in cases //this->Modified(); mitk::OperationEndEvent endevent(operation); ((const itk::Object*)this)->InvokeEvent(endevent); //*todo has to be done here, cause of update-pipeline not working yet // As discussed lately, don't mess with the rendering from inside data structures //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::PointSet::UpdateOutputInformation() { if ( this->GetSource( ) ) { this->GetSource( )->UpdateOutputInformation( ); } // // first make sure, that the associated time sliced geometry has // the same number of geometry 3d's as PointSets are present // TimeGeometry* timeGeometry = GetTimeGeometry(); if ( timeGeometry->CountTimeSteps() != m_PointSetSeries.size() ) { itkExceptionMacro(<<"timeGeometry->CountTimeSteps() != m_PointSetSeries.size() -- use Initialize(timeSteps) with correct number of timeSteps!"); } // This is needed to detect zero objects mitk::ScalarType nullpoint[]={0,0,0,0,0,0}; BoundingBox::BoundsArrayType itkBoundsNull(nullpoint); // // Iterate over the PointSets and update the Geometry // information of each of the items. // if (m_CalculateBoundingBox) { for ( unsigned int i = 0 ; i < m_PointSetSeries.size() ; ++i ) { const DataType::BoundingBoxType *bb = m_PointSetSeries[i]->GetBoundingBox(); BoundingBox::BoundsArrayType itkBounds = bb->GetBounds(); if ( m_PointSetSeries[i].IsNull() || (m_PointSetSeries[i]->GetNumberOfPoints() == 0) || (itkBounds == itkBoundsNull) ) { itkBounds = itkBoundsNull; continue; } // Ensure minimal bounds of 1.0 in each dimension for ( unsigned int j = 0; j < 3; ++j ) { if ( itkBounds[j*2+1] - itkBounds[j*2] < 1.0 ) { BoundingBox::CoordRepType center = (itkBounds[j*2] + itkBounds[j*2+1]) / 2.0; itkBounds[j*2] = center - 0.5; itkBounds[j*2+1] = center + 0.5; } } this->GetGeometry(i)->SetBounds(itkBounds); } m_CalculateBoundingBox = false; } this->GetTimeGeometry()->Update(); } void mitk::PointSet::SetRequestedRegionToLargestPossibleRegion() { } bool mitk::PointSet::RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool mitk::PointSet::VerifyRequestedRegion() { return true; } void mitk::PointSet::SetRequestedRegion(const DataObject * ) { } void mitk::PointSet::PrintSelf( std::ostream& os, itk::Indent indent ) const { Superclass::PrintSelf(os, indent); os << indent << "Number timesteps: " << m_PointSetSeries.size() << "\n"; unsigned int i = 0; for (PointSetSeries::const_iterator it = m_PointSetSeries.begin(); it != m_PointSetSeries.end(); ++it) { os << indent << "Timestep " << i++ << ": \n"; MeshType::Pointer ps = *it; itk::Indent nextIndent = indent.GetNextIndent(); ps->Print(os, nextIndent); MeshType::PointsContainer* points = ps->GetPoints(); MeshType::PointDataContainer* datas = ps->GetPointData(); MeshType::PointDataContainer::Iterator dataIterator = datas->Begin(); for (MeshType::PointsContainer::Iterator pointIterator = points->Begin(); pointIterator != points->End(); ++pointIterator, ++dataIterator) { os << nextIndent << "Point " << pointIterator->Index() << ": ["; os << pointIterator->Value().GetElement(0); for (unsigned int i = 1; i < PointType::GetPointDimension(); ++i) { os << ", " << pointIterator->Value().GetElement(i); } os << "]"; os << ", selected: " << dataIterator->Value().selected << ", point spec: " << dataIterator->Value().pointSpec << "\n"; } } } bool mitk::PointSet::SwapPointContents(PointIdentifier id1, PointIdentifier id2, int timeStep) { /* search and cache contents */ PointType p1; if (m_PointSetSeries[timeStep]->GetPoint(id1, &p1) == false) return false; PointDataType data1; if (m_PointSetSeries[timeStep]->GetPointData(id1, &data1) == false) return false; PointType p2; if (m_PointSetSeries[timeStep]->GetPoint(id2, &p2) == false) return false; PointDataType data2; if (m_PointSetSeries[timeStep]->GetPointData(id2, &data2) == false) return false; /* now swap contents */ m_PointSetSeries[timeStep]->SetPoint(id1, p2); m_PointSetSeries[timeStep]->SetPointData(id1, data2); m_PointSetSeries[timeStep]->SetPoint(id2, p1); m_PointSetSeries[timeStep]->SetPointData(id2, data1); return true; } bool mitk::PointSet::PointDataType::operator ==(const mitk::PointSet::PointDataType &other) const { return id == other.id && selected == other.selected && pointSpec == other.pointSpec; } bool mitk::Equal( const mitk::PointSet* leftHandSide, const mitk::PointSet* rightHandSide, mitk::ScalarType eps, bool verbose ) { if((leftHandSide == NULL) || (rightHandSide == NULL)) { MITK_ERROR << "mitk::Equal( const mitk::PointSet* leftHandSide, const mitk::PointSet* rightHandSide, mitk::ScalarType eps, bool verbose ) does not work with NULL pointer input."; return false; } return Equal( *leftHandSide, *rightHandSide, eps, verbose); } bool mitk::Equal( const mitk::PointSet& leftHandSide, const mitk::PointSet& rightHandSide, mitk::ScalarType eps, bool verbose ) { bool result = true; if( !mitk::Equal( *leftHandSide.GetGeometry(), *rightHandSide.GetGeometry(), eps, verbose) ) { if(verbose) MITK_INFO << "[( PointSet )] Geometries differ."; result = false; } if ( leftHandSide.GetSize() != rightHandSide.GetSize()) { if(verbose) MITK_INFO << "[( PointSet )] Number of points differ."; result = false; } else { //if the size is equal, we compare the point values mitk::Point3D pointLeftHandSide; mitk::Point3D pointRightHandSide; int numberOfIncorrectPoints = 0; //Iterate over both pointsets in order to compare all points pair-wise mitk::PointSet::PointsConstIterator end = leftHandSide.End(); for( mitk::PointSet::PointsConstIterator pointSetIteratorLeft = leftHandSide.Begin(), pointSetIteratorRight = rightHandSide.Begin(); pointSetIteratorLeft != end; ++pointSetIteratorLeft, ++pointSetIteratorRight) //iterate simultaneously over both sets { pointLeftHandSide = pointSetIteratorLeft.Value(); pointRightHandSide = pointSetIteratorRight.Value(); if( !mitk::Equal( pointLeftHandSide, pointRightHandSide, eps, verbose ) ) { if(verbose) MITK_INFO << "[( PointSet )] Point values are different."; result = false; numberOfIncorrectPoints++; } } if((numberOfIncorrectPoints > 0) && verbose) { MITK_INFO << numberOfIncorrectPoints <<" of a total of " << leftHandSide.GetSize() << " points are different."; } } return result; } diff --git a/Core/Code/DataManagement/mitkProperties.h b/Core/Code/DataManagement/mitkProperties.h index d575d37cfd..5fc3457b49 100644 --- a/Core/Code/DataManagement/mitkProperties.h +++ b/Core/Code/DataManagement/mitkProperties.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 MITKPROPERTIES_H_HEADER_INCLUDED #define MITKPROPERTIES_H_HEADER_INCLUDED #include "mitkGenericProperty.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "mitkLookupTables.h" namespace mitk { mitkDeclareGenericProperty(BoolProperty,bool,MITK_CORE_EXPORT); mitkDeclareGenericProperty(IntProperty,int,MITK_CORE_EXPORT); mitkDeclareGenericProperty(FloatProperty,float,MITK_CORE_EXPORT); mitkDeclareGenericProperty(DoubleProperty,double,MITK_CORE_EXPORT); mitkDeclareGenericProperty(Vector3DProperty,Vector3D,MITK_CORE_EXPORT); mitkDeclareGenericProperty(Point2dProperty,Point2D,MITK_CORE_EXPORT); mitkDeclareGenericProperty(Point3dProperty,Point3D,MITK_CORE_EXPORT); mitkDeclareGenericProperty(Point4dProperty,Point4D,MITK_CORE_EXPORT); mitkDeclareGenericProperty(Point3iProperty,Point3I,MITK_CORE_EXPORT); mitkDeclareGenericProperty(FloatLookupTableProperty, FloatLookupTable,MITK_CORE_EXPORT); mitkDeclareGenericProperty(BoolLookupTableProperty, BoolLookupTable,MITK_CORE_EXPORT); mitkDeclareGenericProperty(IntLookupTableProperty, IntLookupTable,MITK_CORE_EXPORT); mitkDeclareGenericProperty(StringLookupTableProperty, StringLookupTable,MITK_CORE_EXPORT); /** * \warning If you add more specialization of GenericProperty, you must also add these to the * templated GetPropertyValue() method in mitkPropertyList.cpp! */ } // namespace mitk #endif /* MITKPROPERTIES_H_HEADER_INCLUDED */ diff --git a/Core/Code/DataManagement/mitkPropertyList.cpp b/Core/Code/DataManagement/mitkPropertyList.cpp index 1db8330c55..4aa8c37cd3 100644 --- a/Core/Code/DataManagement/mitkPropertyList.cpp +++ b/Core/Code/DataManagement/mitkPropertyList.cpp @@ -1,358 +1,358 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkPropertyList.h" #include "mitkProperties.h" #include "mitkStringProperty.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" mitk::BaseProperty* mitk::PropertyList::GetProperty(const std::string& propertyKey) const { PropertyMap::const_iterator it; it=m_Properties.find( propertyKey ); if(it!=m_Properties.end()) return it->second; else return NULL; } void mitk::PropertyList::SetProperty(const std::string& propertyKey, BaseProperty* property) { if (!property) return; //make sure that BaseProperty*, which may have just been created and never been //assigned to a SmartPointer, is registered/unregistered properly. If we do not //do that, it will a) not deleted in case it is identical to the old one or //b) possibly deleted when temporarily added to a smartpointer somewhere below. BaseProperty::Pointer tmpSmartPointerToProperty = property; PropertyMap::iterator it( m_Properties.find( propertyKey ) ); // Is a property with key @a propertyKey contained in the list? if( it != m_Properties.end() ) { // yes //is the property contained in the list identical to the new one? if( it->second->operator==(*property) ) { // yes? do nothing and return. return; } if (it->second->AssignProperty(*property)) { // The assignment was successfull this->Modified(); } else { MITK_ERROR << "In " __FILE__ ", l." << __LINE__ << ": Trying to set existing property " << it->first << " of type " << it->second->GetNameOfClass() << " to a property with different type " << property->GetNameOfClass() << "." << " Use ReplaceProperty() instead." << std::endl; } return; } //no? add it. PropertyMapElementType newProp; newProp.first = propertyKey; newProp.second = property; m_Properties.insert ( newProp ); this->Modified(); } void mitk::PropertyList::ReplaceProperty(const std::string& propertyKey, BaseProperty* property) { if (!property) return; PropertyMap::iterator it( m_Properties.find( propertyKey ) ); // Is a property with key @a propertyKey contained in the list? if( it != m_Properties.end() ) { it->second=NULL; m_Properties.erase(it); } //no? add/replace it. PropertyMapElementType newProp; newProp.first = propertyKey; newProp.second = property; m_Properties.insert ( newProp ); Modified(); } mitk::PropertyList::PropertyList() { } mitk::PropertyList::PropertyList(const mitk::PropertyList& other) : itk::Object() { for (PropertyMap::const_iterator i = other.m_Properties.begin(); i != other.m_Properties.end(); ++i) { m_Properties.insert(std::make_pair(i->first, i->second->Clone())); } } mitk::PropertyList::~PropertyList() { Clear(); } /** * Consider the list as changed when any of the properties has changed recently. */ unsigned long mitk::PropertyList::GetMTime() const { for ( PropertyMap::const_iterator it = m_Properties.begin() ; it != m_Properties.end(); ++it ) { if( it->second.IsNull() ) { itkWarningMacro(<< "Property '" << it->first <<"' contains nothing (NULL)."); continue; } if( Superclass::GetMTime() < it->second->GetMTime() ) { Modified(); break; } } return Superclass::GetMTime(); } bool mitk::PropertyList::DeleteProperty(const std::string& propertyKey) { PropertyMap::iterator it; it=m_Properties.find( propertyKey ); if(it!=m_Properties.end()) { it->second=NULL; m_Properties.erase(it); Modified(); return true; } return false; } void mitk::PropertyList::Clear() { PropertyMap::iterator it = m_Properties.begin(), end = m_Properties.end(); while(it!=end) { it->second = NULL; ++it; } m_Properties.clear(); } itk::LightObject::Pointer mitk::PropertyList::InternalClone() const { itk::LightObject::Pointer result(new Self(*this)); result->UnRegister(); return result; } void mitk::PropertyList::ConcatenatePropertyList(PropertyList *pList, bool replace) { if (pList) { const PropertyMap* propertyMap = pList->GetMap(); for ( PropertyMap::const_iterator iter = propertyMap->begin(); // m_PropertyList is created in the constructor, so we don't check it here iter != propertyMap->end(); ++iter ) { const std::string key = iter->first; BaseProperty* value = iter->second; if (replace) { ReplaceProperty( key.c_str(), value ); } else { SetProperty( key.c_str(), value ); } } } } bool mitk::PropertyList::GetBoolProperty(const char* propertyKey, bool& boolValue) const { BoolProperty *gp = dynamic_cast( GetProperty(propertyKey) ); if ( gp != NULL ) { boolValue = gp->GetValue(); return true; } return false; // Templated Method does not work on Macs //return GetPropertyValue(propertyKey, boolValue); } bool mitk::PropertyList::GetIntProperty(const char* propertyKey, int &intValue) const { IntProperty *gp = dynamic_cast( GetProperty(propertyKey) ); if ( gp != NULL ) { intValue = gp->GetValue(); return true; } return false; // Templated Method does not work on Macs //return GetPropertyValue(propertyKey, intValue); } bool mitk::PropertyList::GetFloatProperty(const char* propertyKey, float &floatValue) const { FloatProperty *gp = dynamic_cast( GetProperty(propertyKey) ); if ( gp != NULL ) { floatValue = gp->GetValue(); return true; } return false; // Templated Method does not work on Macs //return GetPropertyValue(propertyKey, floatValue); } bool mitk::PropertyList::GetStringProperty(const char* propertyKey, std::string& stringValue) const { StringProperty* sp= dynamic_cast(GetProperty(propertyKey)); if ( sp != NULL ) { stringValue = sp->GetValue(); return true; } return false; } void mitk::PropertyList::SetIntProperty(const char* propertyKey, int intValue) { SetProperty(propertyKey, mitk::IntProperty::New(intValue)); } void mitk::PropertyList::SetBoolProperty( const char* propertyKey, bool boolValue) { SetProperty(propertyKey, mitk::BoolProperty::New(boolValue)); } void mitk::PropertyList::SetFloatProperty( const char* propertyKey, float floatValue) { SetProperty(propertyKey, mitk::FloatProperty::New(floatValue)); } void mitk::PropertyList::SetStringProperty( const char* propertyKey, const char* stringValue) { SetProperty(propertyKey, mitk::StringProperty::New(stringValue)); } void mitk::PropertyList::Set( const char* propertyKey, bool boolValue ) { this->SetBoolProperty( propertyKey, boolValue ); } void mitk::PropertyList::Set( const char* propertyKey, int intValue ) { this->SetIntProperty(propertyKey, intValue); } void mitk::PropertyList::Set( const char* propertyKey, float floatValue ) { this->SetFloatProperty(propertyKey, floatValue); } void mitk::PropertyList::Set( const char* propertyKey, double doubleValue ) { this->SetDoubleProperty(propertyKey, doubleValue); } void mitk::PropertyList::Set( const char* propertyKey, const char* stringValue ) { this->SetStringProperty(propertyKey, stringValue); } void mitk::PropertyList::Set( const char* propertyKey, const std::string& stringValue ) { this->SetStringProperty(propertyKey, stringValue.c_str()); } bool mitk::PropertyList::Get( const char* propertyKey, bool& boolValue ) const { return this->GetBoolProperty( propertyKey, boolValue ); } bool mitk::PropertyList::Get( const char* propertyKey, int &intValue ) const { return this->GetIntProperty(propertyKey, intValue); } bool mitk::PropertyList::Get( const char* propertyKey, float &floatValue ) const { return this->GetFloatProperty( propertyKey, floatValue ); } bool mitk::PropertyList::Get( const char* propertyKey, double &doubleValue ) const { return this->GetDoubleProperty( propertyKey, doubleValue ); } bool mitk::PropertyList::Get( const char* propertyKey, std::string& stringValue ) const { return this->GetStringProperty( propertyKey, stringValue ); } bool mitk::PropertyList::GetDoubleProperty( const char* propertyKey, double &doubleValue ) const { DoubleProperty *gp = dynamic_cast( GetProperty(propertyKey) ); if ( gp != NULL ) { doubleValue = gp->GetValue(); return true; } return false; } void mitk::PropertyList::SetDoubleProperty( const char* propertyKey, double doubleValue ) { SetProperty(propertyKey, mitk::DoubleProperty::New(doubleValue)); } diff --git a/Core/Code/DataManagement/mitkQuaternion.h b/Core/Code/DataManagement/mitkQuaternion.h index c1afabbb51..889e2fe285 100644 --- a/Core/Code/DataManagement/mitkQuaternion.h +++ b/Core/Code/DataManagement/mitkQuaternion.h @@ -1,30 +1,30 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKTYPEDEFS_H_ -#define MITKTYPEDEFS_H_ +#ifndef MITKQUATERNION_H_ +#define MITKQUATERNION_H_ #include -#include "mitkConstants.h" +#include "mitkNumericConstants.h" namespace mitk { typedef vnl_quaternion Quaternion; } -#endif /* MITKTYPEDEFS_H_ */ +#endif /* MITKQUATERNION_H_ */ diff --git a/Core/Code/DataManagement/mitkRestorePlanePositionOperation.h b/Core/Code/DataManagement/mitkRestorePlanePositionOperation.h index a61736ed4a..6b3501637b 100644 --- a/Core/Code/DataManagement/mitkRestorePlanePositionOperation.h +++ b/Core/Code/DataManagement/mitkRestorePlanePositionOperation.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 mitkRestorePlanePositionOperation_h_Included #define mitkRestorePlanePositionOperation_h_Included #include "mitkCommon.h" #include "mitkPointOperation.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" namespace mitk { //##Documentation //## TODO class MITK_CORE_EXPORT RestorePlanePositionOperation : public Operation { public: //##Documentation //##@brief Operation that handles all actions on one Point. //## //## @param operationType is the type of the operation (see mitkOperation.h; e.g. move or add; Information for StateMachine::ExecuteOperation()); //## @param point is the information of the point to add or is the information to change a point into //## @param index is e.g. the position in a list which describes the element to change //PointOperation(OperationType operationType, Point3D point, int index = -1, bool selected = true, PointSpecificationType type = PTUNDEFINED); RestorePlanePositionOperation(OperationType operationType, ScalarType width, ScalarType height, Vector3D spacing, unsigned int pos, Vector3D direction, AffineTransform3D::Pointer transform); virtual ~RestorePlanePositionOperation(); Vector3D GetDirectionVector(); ScalarType GetWidth(); ScalarType GetHeight(); Vector3D GetSpacing(); unsigned int GetPos(); AffineTransform3D::Pointer GetTransform(); private: Vector3D m_Spacing; Vector3D m_DirectionVector; ScalarType m_Width; ScalarType m_Height; unsigned int m_Pos; AffineTransform3D::Pointer m_Transform; }; }//namespace mitk #endif diff --git a/Core/Code/DataManagement/mitkRotationOperation.h b/Core/Code/DataManagement/mitkRotationOperation.h index ae8f9cabd7..b1869a5b99 100644 --- a/Core/Code/DataManagement/mitkRotationOperation.h +++ b/Core/Code/DataManagement/mitkRotationOperation.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 MITKROTATIONOPERATION_H_HEADER_INCLUDED #define MITKROTATIONOPERATION_H_HEADER_INCLUDED #include "mitkOperation.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" namespace mitk { //##Documentation //## @brief Operation, that holds everything necessary for an rotation operation //## //## @ingroup Undo class MITK_CORE_EXPORT RotationOperation : public Operation { public: RotationOperation(OperationType operationType, Point3D pointOfRotation, Vector3D vectorOfRotation, ScalarType angleOfRotation); virtual ~RotationOperation(void); virtual ScalarType GetAngleOfRotation(); virtual const Point3D GetCenterOfRotation(); virtual const Vector3D GetVectorOfRotation(); protected: ScalarType m_AngleOfRotation; Point3D m_PointOfRotation; Vector3D m_VectorOfRotation; }; } // namespace mitk #endif /* MITKROTATIONOPERATION_H_HEADER_INCLUDED */ diff --git a/Core/Code/DataManagement/mitkTypes.h b/Core/Code/DataManagement/mitkTypes.h deleted file mode 100644 index e76b48fd54..0000000000 --- a/Core/Code/DataManagement/mitkTypes.h +++ /dev/null @@ -1,67 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - - -#ifndef MITKVECTOR_H_HEADER_INCLUDED_C1EBD0AD -#define MITKVECTOR_H_HEADER_INCLUDED_C1EBD0AD - - -#include "mitkConstants.h" -#include "mitkQuaternion.h" -#include "mitkPoint.h" -#include "mitkVector.h" -#include "mitkMatrix.h" -#include "mitkEqual.h" - - -// this include hold the old deprecated ways to convert from itk 2 vtk and the likes. -// calls to these functions shall be removed in future bugsquashings so that this include can be removed. -#include "mitkVectorDeprecated.h" - - -/* - * This part of the code has been shifted here to avoid compiler clashes - * caused by including before the declaration of - * the Equal() methods above. This problem occurs when using MSVC and is - * probably related to a compiler bug. - */ - -#include - -namespace mitk -{ - typedef itk::AffineGeometryFrame::TransformType AffineTransform3D; -} - - -#define mitkSetConstReferenceMacro(name,type) \ - virtual void Set##name (const type & _arg) \ - { \ - itkDebugMacro("setting " << #name " to " << _arg ); \ - if (this->m_##name != _arg) \ - { \ - this->m_##name = _arg; \ - this->Modified(); \ - } \ - } - -#define mitkSetVectorMacro(name,type) \ - mitkSetConstReferenceMacro(name,type) - -#define mitkGetVectorMacro(name,type) \ - itkGetConstReferenceMacro(name,type) - -#endif /* MITKVECTOR_H_HEADER_INCLUDED_C1EBD0AD */ diff --git a/Core/Code/DataManagement/mitkVector.h b/Core/Code/DataManagement/mitkVector.h index 58d365ac3d..b953dadc55 100644 --- a/Core/Code/DataManagement/mitkVector.h +++ b/Core/Code/DataManagement/mitkVector.h @@ -1,233 +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. ===================================================================*/ #ifndef MITKVECTOR_H_ #define MITKVECTOR_H_ #include #include #include -#include "mitkConstants.h" +#include "mitkNumericConstants.h" #include "mitkArray.h" #include "mitkEqual.h" #include "mitkExceptionMacro.h" namespace mitk { template class Vector : public itk::Vector { public: /** * @brief Default constructor has nothing to do. */ explicit Vector() : itk::Vector() {} /** * @brief Copy constructor. */ explicit Vector(const mitk::Vector& r) : itk::Vector(r) {} /** * @brief Constructor to convert from itk::Vector to mitk::Vector. */ Vector(const itk::Vector& r) : itk::Vector(r) {} /** * @brief Constructor to convert an array to mitk::Vector * @param r the array. * @attention must have NVectorDimension valid arguments! */ Vector(const TCoordRep r[NVectorDimension]) : itk::Vector(r) {} /** * Constructor to initialize entire vector to one value. */ Vector(const TCoordRep & v) : itk::Vector(v) {} /** * @brief Constructor for vnl_vectors. * @throws mitk::Exception if vnl_vector.size() != NVectorDimension. */ Vector(const vnl_vector& vnlVector) : itk::Vector() { if (vnlVector.size() != NVectorDimension) mitkThrow() << "when constructing mitk::Vector from vnl_vector: sizes didn't match: mitk::Vector " << NVectorDimension << "; vnl_vector " << vnlVector.size(); for (unsigned int var = 0; (var < NVectorDimension) && (var < vnlVector.size()); ++var) { this->SetElement(var, vnlVector.get(var)); } } /** * @brief Constructor for vnl_vector_fixed. */ Vector(const vnl_vector_fixed& vnlVectorFixed) : itk::Vector() { for (unsigned int var = 0; var < NVectorDimension; ++var) { this->SetElement(var, vnlVectorFixed[var]); } }; /** * Copies the elements from array array to this. * Note that this method will assign doubles to floats without complaining! * * @param array the array whose values shall be copied. Must overload [] operator. */ template - void FromArray(const ArrayType& array) + void FillVector(const ArrayType& array) { itk::FixedArray* thisP = dynamic_cast* >(this); - mitk::FromArray(*thisP, array); + mitk::FillArray(*thisP, array); } - /** * Copies the values stored in this vector into the array array.d * * @param array the array which should store the values of this. */ template - void ToArray(ArrayType array) + void ToArray(ArrayType array) const { mitk::ToArray(array, *this); } /** * @brief User defined conversion of mitk::Vector to vnl_vector. * Note: the conversion to mitk::Vector to vnl_vector_fixed has not been implemented since this * would collide with the conversion vnl_vector to vnl_vector_fixed provided by vnl. */ operator vnl_vector () const { return this->GetVnlVector(); } }; // end mitk::Vector // convenience typedefs for often used mitk::Vector representations. typedef Vector Vector2D; typedef Vector Vector3D; typedef Vector Vector4D; // other vector types used in MITK typedef vnl_vector VnlVector; // The equal methods to compare vectors for equality are below: /** * @ingroup MITKTestingAPI * * @param vector1 Vector to compare. * @param vector2 Vector to compare. * @param eps Tolerance for floating point comparison. * @param verbose Flag indicating detailed console output. * @return True if vectors are equal. */ template inline bool Equal(const itk::Vector& vector1, const itk::Vector& vector2, TCoordRep eps=mitk::eps, bool verbose=false) { bool isEqual = true; typename itk::Vector::VectorType diff = vector1-vector2; for (unsigned int i=0; i inline bool Equal(const vnl_vector_fixed & vector1, const vnl_vector_fixed& vector2, TCoordRep eps=mitk::eps, bool verbose=false) { vnl_vector_fixed diff = vector1-vector2; bool isEqual = true; for( unsigned int i=0; i #include -#include "mitkConstants.h" +#include "mitkNumericConstants.h" #include "mitkVector.h" #include "mitkPoint.h" #include "mitkMatrix.h" template class VectorTraits { public: typedef T ValueType; }; template <> class VectorTraits { public: typedef mitk::ScalarType ValueType; }; template<> class VectorTraits { public: typedef float ValueType; }; template<> class VectorTraits< itk::Index<5> > { public: typedef itk::Index<5>::IndexValueType ValueType; }; template<> class VectorTraits< itk::Index<3> > { public: typedef itk::Index<3>::IndexValueType ValueType; }; template<> class VectorTraits< long int [3]> { public: typedef long int ValueType; }; template<> class VectorTraits< float [3]> { public: typedef float ValueType; }; template<> class VectorTraits< double [3]> { public: typedef double ValueType; }; template<> class VectorTraits< vnl_vector_fixed > { public: typedef mitk::ScalarType ValueType; }; template<> class VectorTraits< long unsigned int[3]> { public: typedef long unsigned int ValueType; }; template<> class VectorTraits< unsigned int *> { public: typedef unsigned int ValueType; }; template<> class VectorTraits< double[4] > { public: typedef double ValueType; }; template<> class VectorTraits< itk::Vector > { public: typedef float ValueType; }; template<> class VectorTraits< itk::Vector > { public: typedef double ValueType; }; template<> class VectorTraits< itk::Vector > { public: typedef int ValueType; }; template<> class VectorTraits< mitk::Vector > { public: typedef double ValueType; }; template<> class VectorTraits< mitk::Point > { public: typedef float ValueType; }; template<> class VectorTraits< mitk::Point > { public: typedef float ValueType; }; template<> class VectorTraits< itk::Point > { public: typedef float ValueType; }; template<> class VectorTraits< itk::Point > { public: typedef float ValueType; }; template<> class VectorTraits< mitk::Point > { public: typedef double ValueType; }; template<> class VectorTraits< mitk::Point > { public: typedef double ValueType; }; template<> class VectorTraits< itk::Point > { public: typedef double ValueType; }; template<> class VectorTraits< itk::Point > { public: typedef double ValueType; }; template<> class VectorTraits< mitk::Point > { public: typedef int ValueType; }; namespace mitk { template inline void itk2vtk(const Tin& in, Tout& out) { out[0]=(typename VectorTraits::ValueType)(in[0]); out[1]=(typename VectorTraits::ValueType)(in[1]); out[2]=(typename VectorTraits::ValueType)(in[2]); } template inline void vtk2itk(const Tin& in, Tout& out) { out[0]=(typename VectorTraits::ValueType)(in[0]); out[1]=(typename VectorTraits::ValueType)(in[1]); out[2]=(typename VectorTraits::ValueType)(in[2]); } template inline void vnl2vtk(const vnl_vector& in, Tout *out) { unsigned int i; for(i=0; i inline void vtk2vnl(const Tin *in, vnl_vector& out) { unsigned int i; for(i=0; i inline void vnl2vtk(const vnl_vector_fixed& in, Tout *out) { unsigned int i; for(i=0; i inline void vtk2vnl(const Tin *in, vnl_vector_fixed& out) { unsigned int i; for(i=0; i inline void TransferMatrix(const itk::Matrix& in, itk::Matrix& out) { for (unsigned int i = 0; i < in.RowDimensions; ++i) for (unsigned int j = 0; j < in.ColumnDimensions; ++j) out[i][j] = in[i][j]; } +#define mitkSetConstReferenceMacro(name,type) \ + virtual void Set##name (const type & _arg) \ + { \ + itkDebugMacro("setting " << #name " to " << _arg ); \ + if (this->m_##name != _arg) \ + { \ + this->m_##name = _arg; \ + this->Modified(); \ + } \ + } + +#define mitkSetVectorMacro(name,type) \ + mitkSetConstReferenceMacro(name,type) + +#define mitkGetVectorMacro(name,type) \ + itkGetConstReferenceMacro(name,type) } // namespace mitk -#endif /* MITKOLDTYPECONVERSIONS_H_ */ +#endif /* MITKVECTORDEPRECATED_H_ */ diff --git a/Core/Code/Interactions/mitkAffineInteractor.h b/Core/Code/Interactions/mitkAffineInteractor.h index a7d7f4564c..6ddf60faf0 100755 --- a/Core/Code/Interactions/mitkAffineInteractor.h +++ b/Core/Code/Interactions/mitkAffineInteractor.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 MITKAFFINEINTERACTOR_H_HEADER_INCLUDED_C188C29F #define MITKAFFINEINTERACTOR_H_HEADER_INCLUDED_C188C29F #include #include "mitkInteractor.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" namespace mitk { class DisplayPositionEvent; //##Documentation //## @brief Interactor for Affine transformations translate, rotate and scale //## //## An object of this class can translate, rotate and scale the data objects //## by modifying its geometry. //## @ingroup Interaction //create events for interactions #pragma GCC visibility push(default) itkEventMacro(AffineInteractionEvent, itk::AnyEvent); itkEventMacro(ScaleEvent, AffineInteractionEvent); itkEventMacro(RotateEvent, AffineInteractionEvent); itkEventMacro(TranslateEvent, AffineInteractionEvent); #pragma GCC visibility pop class MITK_CORE_EXPORT AffineInteractor : public Interactor { public: mitkClassMacro(AffineInteractor,Interactor); // itkFactorylessNewMacro(Self) // itkCloneMacro(Self) mitkNewMacro2Param(Self, const char*, DataNode*); protected: // AffineInteractor(); //obsolete //##Documentation //## @brief Constructor //## //## @param dataNode is the node, this Interactor is connected to //## @param type is the type of StateMachine like declared in the XML-Configure-File AffineInteractor(const char * type, DataNode* dataNode); //##Documentation //## @brief Destructor ~AffineInteractor(){}; virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); //##Documentation //## @brief calculates how good the data this state machine handles is hit by the event. //## //## Returns a value between 0 and 1. //## (Used by GlobalInteraction to decide which DESELECTED state machine to send the event to.) //## //## \WARNING This is interactor currently does not work for interaction in 3D. Try using mitkAffineInteractor3D instead. virtual float CanHandleEvent(StateEvent const* stateEvent) const; bool CheckSelected(const mitk::Point3D& worldPoint, int timestep); bool ConvertDisplayEventToWorldPosition(mitk::DisplayPositionEvent const* displayEvent, mitk::Point3D& worldPoint); mitk::Point3D m_LastMousePosition; }; } // namespace mitk #endif /* MITKAFFINEINTERACTOR_H_HEADER_INCLUDED_C188C29F */ diff --git a/Core/Code/Interactions/mitkCoordinateSupplier.h b/Core/Code/Interactions/mitkCoordinateSupplier.h index 05f4127442..59f8f9a730 100755 --- a/Core/Code/Interactions/mitkCoordinateSupplier.h +++ b/Core/Code/Interactions/mitkCoordinateSupplier.h @@ -1,65 +1,65 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKCOORDINATESUPPLIER_H #define MITKCOORDINATESUPPLIER_H #include #include "mitkStateMachine.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" namespace mitk { class Operation; class OperationActor; //##Documentation //## @brief Interactor //## //## sends a Point, that can be processed in its own OperationActor //## @ingroup Interaction class MITK_CORE_EXPORT CoordinateSupplier : public StateMachine { public: mitkClassMacro(CoordinateSupplier, StateMachine); mitkNewMacro2Param(Self, const char*, OperationActor*); itkGetConstReferenceMacro(CurrentPoint, Point3D); protected: //##Documentation //## @brief Constructor with needed arguments //## @param type: string, that describes the StateMachine-Scheme to take from all SM (see XML-File) //## @param operationActor: the Data, operations (+ points) are send to CoordinateSupplier(const char * type, OperationActor* operationActor); ~CoordinateSupplier(); //##Documentation //## @brief executes the actions that are sent to this statemachine //## derived from StateMachine virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); private: OperationActor* m_Destination; Point3D m_OldPoint; Point3D m_CurrentPoint; }; } // namespace mitk #endif /* MITKCOORDINATESUPPLIER_H */ diff --git a/Core/Code/Interactions/mitkDisplayCoordinateOperation.h b/Core/Code/Interactions/mitkDisplayCoordinateOperation.h index a018ac4b2a..e47e245889 100644 --- a/Core/Code/Interactions/mitkDisplayCoordinateOperation.h +++ b/Core/Code/Interactions/mitkDisplayCoordinateOperation.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 MITKDISPLAYCOORDINATEOPERATION_H_HEADER_INCLUDED_C10E33D0 #define MITKDISPLAYCOORDINATEOPERATION_H_HEADER_INCLUDED_C10E33D0 #include #include "mitkBaseRenderer.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "mitkOperation.h" #include #define mitkGetMacro(name,type) \ virtual type Get##name () \ { \ return this->m_##name; \ } namespace mitk { // TODO Legacy , no longer necessary when after migrating all DisplayInteractions to new Interactions. // Coordinate supplier can probably also be removed then. //##Documentation //## @brief Operation with informations necessary for operations of DisplayVectorInteractor //## @ingroup Undo class MITK_CORE_EXPORT DisplayCoordinateOperation : public Operation { public: DisplayCoordinateOperation(mitk::OperationType operationType, mitk::BaseRenderer* renderer, const mitk::Point2D& startDisplayCoordinate, const mitk::Point2D& lastDisplayCoordinate, const mitk::Point2D& currentDisplayCoordinate ); DisplayCoordinateOperation(mitk::OperationType operationType, mitk::BaseRenderer* renderer, const mitk::Point2D& startDisplayCoordinate, const mitk::Point2D& lastDisplayCoordinate, const mitk::Point2D& currentDisplayCoordinate, const mitk::Point2D& startCoordinateInMM ); virtual ~DisplayCoordinateOperation(); mitk::BaseRenderer* GetRenderer(); mitkGetMacro(StartDisplayCoordinate, mitk::Point2D); mitkGetMacro(LastDisplayCoordinate, mitk::Point2D); mitkGetMacro(CurrentDisplayCoordinate, mitk::Point2D); mitkGetMacro(StartCoordinateInMM, mitk::Point2D); mitk::Vector2D GetLastToCurrentDisplayVector(); mitk::Vector2D GetStartToCurrentDisplayVector(); mitk::Vector2D GetStartToLastDisplayVector(); private: mitk::WeakPointer< mitk::BaseRenderer > m_Renderer; const mitk::Point2D m_StartDisplayCoordinate; const mitk::Point2D m_LastDisplayCoordinate; const mitk::Point2D m_CurrentDisplayCoordinate; const mitk::Point2D m_StartCoordinateInMM; }; } #endif /* MITKDISPLAYCOORDINATEOPERATION_H_HEADER_INCLUDED_C10E33D0 */ diff --git a/Core/Code/Interactions/mitkDisplayPositionEvent.h b/Core/Code/Interactions/mitkDisplayPositionEvent.h index ac616e79ac..b85111e0d5 100644 --- a/Core/Code/Interactions/mitkDisplayPositionEvent.h +++ b/Core/Code/Interactions/mitkDisplayPositionEvent.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 DISPLAYPOSITIONEVENT_H_HEADER_INCLUDED_C184F366 #define DISPLAYPOSITIONEVENT_H_HEADER_INCLUDED_C184F366 #include #include "mitkEvent.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "mitkDataNode.h" namespace mitk { /** * \brief Event that stores coordinates * * Stores display position of the mouse. * * If requested, the correspondent 3D world position in mm is calculated via * picking (delegated to the BaseRenderer). Additionally, the mitk::BaseData or * mitk::DataNode corresponding to the picked object in the (3D) scene can * be retrieved. * \ingroup Interaction * \deprecatedSince{2013_03} mitk::DisplayPositionEvent is deprecated. Use mitk::InteractionPositionEvent instead. * Refer to \see DataInteractionPage for general information about the concept of the new implementation. */ class MITK_CORE_EXPORT DisplayPositionEvent : public Event { public: /** \brief Constructor with all necessary arguments. * * \param sender is the renderer that caused that event * \param type, button, buttonState, key: information from the Event * \param displPosition is the 2D Position of the mouse */ DisplayPositionEvent(BaseRenderer* sender, int type, int button, int buttonState, int key, const Point2D& displPosition); const Point2D& GetDisplayPosition() const { return m_DisplayPosition; } void SetDisplayPosition(const Point2D& displayPosition) { m_DisplayPosition = displayPosition; m_WorldPositionIsSet = false; m_PickedObjectIsSet = false; } Point3D& GetWorldPosition() const; /** Returns node with object at the current position (NULL if not applicable) */ mitk::DataNode *GetPickedObjectNode() const; /** Returns object at the current position (NULL if not applicable) */ mitk::BaseData *GetPickedObject() const; protected: Point2D m_DisplayPosition; mutable Point3D m_WorldPosition; mutable bool m_WorldPositionIsSet; mutable mitk::DataNode::Pointer m_PickedObjectNode; mutable bool m_PickedObjectIsSet; }; typedef DisplayPositionEvent MouseEvent; } // namespace mitk #endif /* DISPLAYPOSITIONozsiEVENT_H_HEADER_INCLUDED_C184F366 */ diff --git a/Core/Code/Interactions/mitkKeyEvent.h b/Core/Code/Interactions/mitkKeyEvent.h index 4685e19b72..41c4f67d67 100644 --- a/Core/Code/Interactions/mitkKeyEvent.h +++ b/Core/Code/Interactions/mitkKeyEvent.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 KeyEvent_H_HEADER_INCLUDED_C184F366 #define KeyEvent_H_HEADER_INCLUDED_C184F366 #include #include "mitkEvent.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" namespace mitk { //##Documentation //## @brief Event that stores coordinates and the key which is pressed //## //## Stores display position of the mouse. If requested, the correspondent //## 3D world position in mm is calculated via picking (delegated to the //## BaseRenderer). //## @ingroup Interaction /** * \deprecatedSince{2013_03} KeyEvent is deprecated. Use mitk::InteractionKeyEvent instead. * Refer to \see DataInteractionPage for general information about the concept of the new implementation. */ class MITK_CORE_EXPORT KeyEvent : public Event { public: //##Documentation //## @brief Constructor with all necessary arguments. //## //## @param sender is the renderer that caused that event //## @param type, button, buttonState, key: information from the Event //## @param displPosition is the 2D Position of the mouse KeyEvent(BaseRenderer* sender, int type, int button, int buttonState, int key, std::string text, const Point2D& displPosition); const Point2D& GetDisplayPosition() const { return m_DisplayPosition; } void SetDisplayPosition(const Point2D& displPosition) { m_DisplayPosition = displPosition; m_WorldPositionIsSet = false; } const Point3D& GetWorldPosition() const; int GetKey() const { return m_Key; } const char* GetText() const { return m_Text.c_str(); } int GetType() const { return m_Type; } protected: Point2D m_DisplayPosition; int m_Key; std::string m_Text; mutable Point3D m_WorldPosition; mutable bool m_WorldPositionIsSet; }; } // namespace mitk #endif /* DISPLAYPOSITIONozsiEVENT_H_HEADER_INCLUDED_C184F366 */ diff --git a/Core/Code/Interactions/mitkMouseMovePointSetInteractor.h b/Core/Code/Interactions/mitkMouseMovePointSetInteractor.h index d6aa3877e5..bc22bae081 100644 --- a/Core/Code/Interactions/mitkMouseMovePointSetInteractor.h +++ b/Core/Code/Interactions/mitkMouseMovePointSetInteractor.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 MITKMOUSEMOVEPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF #define MITKMOUSEMOVEPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF #include -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include namespace mitk { class DataNode; /** * \brief Interaction with a single point by mouse movement. * * A new point is added by mouse movement, an existing point will be removed before adding a new one. * \ingroup Interaction */ class MITK_CORE_EXPORT MouseMovePointSetInteractor : public PointSetInteractor { public: mitkClassMacro(MouseMovePointSetInteractor, Interactor); mitkNewMacro3Param(Self, const char*, DataNode*, int); mitkNewMacro2Param(Self, const char*, DataNode*); /** * \brief calculates how good the data, this statemachine handles, is hit * by the event. * * overwritten, cause we don't look at the boundingbox, we look at each point * and want to accept mouse movement for setting points */ virtual float CanHandleEvent(StateEvent const* stateEvent) const; protected: /** * \brief Constructor with Param n for limited Set of Points * * if no n is set, then the number of points is unlimited* */ MouseMovePointSetInteractor(const char * type, DataNode* dataNode, int n = -1); /** * \brief Default Destructor **/ virtual ~MouseMovePointSetInteractor(); private: }; } #endif /* MITKMOUSEMOVEPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF */ diff --git a/Core/Code/Interactions/mitkNodeDepententPointSetInteractor.h b/Core/Code/Interactions/mitkNodeDepententPointSetInteractor.h index e0b69794c8..2be61e5fea 100644 --- a/Core/Code/Interactions/mitkNodeDepententPointSetInteractor.h +++ b/Core/Code/Interactions/mitkNodeDepententPointSetInteractor.h @@ -1,77 +1,77 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKNodeDepententPointSetInteractor_H_HEADER_INCLUDED #define MITKNodeDepententPointSetInteractor_H_HEADER_INCLUDED #include -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include #include #include namespace mitk { /** * \brief PointSetInteraction that is dependent on the visibility property of a data node. * * The interactor checks if the renderwindow specific property "visible" of a different node (e.g. image) * specified by @param dependentDataNode is true. The specific renderwindow is specified by the sender of the event. * If the property is true the the object behaves as described by PointSetInteractor. * If not, interaction is blocked. * * This class shows how to write an interactor, that is dependent on a special property of the associated node. * See bug #6047 for further information and a patch to test this class embedded in tutorial Step 5. * \ingroup Interaction */ class MITK_CORE_EXPORT NodeDepententPointSetInteractor : public PointSetInteractor { public: mitkClassMacro(NodeDepententPointSetInteractor, PointSetInteractor); mitkNewMacro4Param(Self, const char*, DataNode*, DataNode*, int); mitkNewMacro3Param(Self, const char*, DataNode*, DataNode*); /** * \brief Checks visibility of the specified node (e.g. image), * returns 0 if node is not visible in sending render window * If Sender within stateEvent is NULL a value of 0 is returned. */ virtual float CanHandleEvent(StateEvent const* stateEvent) const; protected: /** * \brief Constructor with Param n for limited Set of Points * * If no n is set, then the number of points is unlimited * n=0 is not supported. In this case, n is set to 1. */ NodeDepententPointSetInteractor(const char * type, DataNode* dataNode, DataNode* dependentDataNode, int n = -1); /** * \brief Default Destructor **/ virtual ~NodeDepententPointSetInteractor(); public: mitk::DataNode::Pointer m_DependentDataNode; }; } #endif /* MITKNodeDepententPointSetInteractor_H_HEADER_INCLUDED */ diff --git a/Core/Code/Interactions/mitkPointSetInteractor.h b/Core/Code/Interactions/mitkPointSetInteractor.h index 175195b2f1..eed134fdc7 100644 --- a/Core/Code/Interactions/mitkPointSetInteractor.h +++ b/Core/Code/Interactions/mitkPointSetInteractor.h @@ -1,128 +1,128 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF #define MITKPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF #include -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include namespace mitk { class DataNode; /** * \brief Interaction with a set of points. * * Points can be added, removed and moved. * In case the interaction shall be done on a * loaded set of points, the associated data * object (mitkPointSet) needs to be loaded * prior to the instanciation of this object. * The number of points are checked and the internal * statemachine set to the apropriate state. * The management of 0 points is not supported. * In this case, the amount of managed points is set to 1. * \ingroup Interaction */ class MITK_CORE_EXPORT PointSetInteractor : public Interactor { public: mitkClassMacro(PointSetInteractor, Interactor); mitkNewMacro3Param(Self, const char*, DataNode*, int); mitkNewMacro2Param(Self, const char*, DataNode*); /** * @brief Clears all the elements from the given timeStep in the list with undo-functionality and * resets the statemachine */ void Clear( unsigned int timeStep = 0, ScalarType timeInMS = 0.0 ); itkGetMacro( Precision, unsigned int ); itkSetMacro( Precision, unsigned int ); /** * \brief calculates how good the data, this statemachine handles, is hit * by the event. * * overwritten, cause we don't look at the boundingbox, we look at each point */ virtual float CanHandleEvent(StateEvent const* stateEvent) const; /** *@brief If data changed then initialize according to numbers of loaded points **/ virtual void DataChanged(); protected: /** * \brief Constructor with Param n for limited Set of Points * * If no n is set, then the number of points is unlimited * n=0 is not supported. In this case, n is set to 1. */ PointSetInteractor(const char * type, DataNode* dataNode, int n = -1); /** * \brief Default Destructor **/ virtual ~PointSetInteractor(); /** * @brief Convert the given Actions to Operations and send to data and UndoController */ virtual bool ExecuteAction( Action* action, mitk::StateEvent const* stateEvent ); /** \brief Deselects the Points in the PointSet. * supports Undo if enabled */ void UnselectAll( unsigned int timeStep = 0, ScalarType timeInMS = 0.0 ); /** * \brief Selects the point. * supports Undo if enabled. * \param position Needed for declaring operations */ void SelectPoint( int position, unsigned int timeStep = 0, ScalarType timeInMS = 0.0 ); /** \brief to calculate a direction vector from last point and actual * point */ Point3D m_LastPoint; /** \brief summ-vector for Movement */ Vector3D m_SumVec; /** \brief to store the value of precision to pick a point */ unsigned int m_Precision; private: /** * \brief the number of possible points in this object * * if -1, then no limit set */ int m_N; /** * @brief Init the StatateMachine according to the current number of points in case of a loaded pointset. **/ void InitAccordingToNumberOfPoints(); }; } #endif /* MITKPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF */ diff --git a/Core/Code/Interactions/mitkPositionEvent.cpp b/Core/Code/Interactions/mitkPositionEvent.cpp index 8c4d4bd1d5..864de0d500 100644 --- a/Core/Code/Interactions/mitkPositionEvent.cpp +++ b/Core/Code/Interactions/mitkPositionEvent.cpp @@ -1,26 +1,26 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkPositionEvent.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" mitk::PositionEvent::PositionEvent(mitk::BaseRenderer* sender, int type, int button, int buttonState, int key, const mitk::Point2D& displPosition, const mitk::Point3D& worldPosition) : DisplayPositionEvent(sender, type, button, buttonState, key, displPosition) { m_WorldPosition = worldPosition; m_WorldPositionIsSet = true; } diff --git a/Core/Code/Interactions/mitkPositionEvent.h b/Core/Code/Interactions/mitkPositionEvent.h index 11d7d4e22f..47bf0315b7 100644 --- a/Core/Code/Interactions/mitkPositionEvent.h +++ b/Core/Code/Interactions/mitkPositionEvent.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 POSITIONEVENT_H_HEADER_INCLUDED_C184F366 #define POSITIONEVENT_H_HEADER_INCLUDED_C184F366 #include #include "mitkDisplayPositionEvent.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" namespace mitk { //##Documentation //## @brief Event that stores coordinates //## //## Stores display position of the mouse and 3D world position in mm. //## @ingroup Interaction /** * \deprecatedSince{2013_03} mitk::PositionEvent is deprecated. Use mitk::InteractionPositionEvent instead. * Refer to \see DataInteractionPage for general information about the concept of the new implementation. */ class MITK_CORE_EXPORT PositionEvent : public DisplayPositionEvent { public: //##Documentation //## @brief Constructor with all necessary arguments. //## //## @param sender: the widget, that caused that event, so that it can be asked for worldCoordinates. changed later to a focus //## @param type, button, buttonState, key: information from the Event //## @param displPosition: the 2D Position e.g. from the mouse //## @param worldPosition: the 3D position e.g. from a picking PositionEvent(BaseRenderer* sender, int type, int button, int buttonState, int key, const Point2D& displPosition, const Point3D& worldPosition); }; } // namespace mitk #endif /* POSITIONEVENT_H_HEADER_INCLUDED_C184F366 */ diff --git a/Core/Code/Interactions/mitkPositionTracker.cpp b/Core/Code/Interactions/mitkPositionTracker.cpp index ba429a6dcd..725adc1a02 100755 --- a/Core/Code/Interactions/mitkPositionTracker.cpp +++ b/Core/Code/Interactions/mitkPositionTracker.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 #include #include #include #include #include #include #include #include #include #include -#include // for PointDataType +#include // for PointDataType #include mitk::PositionTracker::PositionTracker(const char * type, mitk::OperationActor* /*operationActor*/) : mitk::StateMachine(type) {} bool mitk::PositionTracker::ExecuteAction(Action* /*action*/, mitk::StateEvent const* stateEvent) { bool ok = false; const DisplayPositionEvent* displayPositionEvent = dynamic_cast(stateEvent->GetEvent()); mitk::DataNode::Pointer dtnode; mitk::DataStorage* ds = NULL; if (displayPositionEvent == NULL) return false; if (stateEvent->GetEvent()->GetSender()!=NULL) { ds = stateEvent->GetEvent()->GetSender()->GetDataStorage(); } else { itkWarningMacro(<<"StateEvent::GetSender()==NULL - setting timeInMS to 0"); return false; } if (ds == NULL) return false; // looking for desired point set dtnode = ds->GetNode(mitk::NodePredicateProperty::New("inputdevice", mitk::BoolProperty::New(true))); if (dtnode.IsNull()) return false; dtnode->SetIntProperty("BaseRendererMapperID", stateEvent->GetEvent()->GetSender()->GetMapperID()); mitk::PointSet* ps = dynamic_cast(dtnode->GetData()); if (ps == NULL) return false; int position = 0; if( ps->GetPointSet()->GetPoints()->IndexExists( position )) //first element { ps->GetPointSet()->GetPoints()->SetElement( position, displayPositionEvent->GetWorldPosition()); } else { mitk::PointSet::PointDataType pointData = {static_cast(position) , false /*selected*/, mitk::PTUNDEFINED}; ps->GetPointSet()->GetPointData()->InsertElement(position, pointData); ps->GetPointSet()->GetPoints()->InsertElement(position, displayPositionEvent->GetWorldPosition()); } ps->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return ok; } diff --git a/Core/Code/Interactions/mitkWheelEvent.cpp b/Core/Code/Interactions/mitkWheelEvent.cpp index 4ee383dc5a..f22a03e57a 100644 --- a/Core/Code/Interactions/mitkWheelEvent.cpp +++ b/Core/Code/Interactions/mitkWheelEvent.cpp @@ -1,31 +1,31 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkWheelEvent.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" mitk::WheelEvent::WheelEvent(mitk::BaseRenderer* sender, int type, int button, int buttonState, int key, const mitk::Point2D& displPosition, int delta) : DisplayPositionEvent(sender, type, button, buttonState, key, displPosition) { //m_WorldPosition = worldPosition; //m_WorldPositionIsSet = true; m_Delta = delta; } int mitk::WheelEvent::GetDelta() const { return m_Delta; } diff --git a/Core/Code/Interactions/mitkWheelEvent.h b/Core/Code/Interactions/mitkWheelEvent.h index 96ea23b62b..f40e4d0105 100644 --- a/Core/Code/Interactions/mitkWheelEvent.h +++ b/Core/Code/Interactions/mitkWheelEvent.h @@ -1,60 +1,60 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 WheelEvent_H_HEADER_INCLUDED_C184F366 #define WheelEvent_H_HEADER_INCLUDED_C184F366 #include #include "mitkDisplayPositionEvent.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" namespace mitk { //##Documentation //## @brief Event that stores coordinates and rotation on mouse wheel events //## //## Stores display position of the mouse and 3D world position in mm. //## @ingroup Interaction /** * \deprecatedSince{2013_03} mitk::WheelEvent is deprecated. Use mitk::MouseWheelEvent instead. * Refer to \see DataInteractionPage for general information about the concept of the new implementation. */ class MITK_CORE_EXPORT WheelEvent : public DisplayPositionEvent { public: //##Documentation //## @brief Constructor with all necessary arguments. //## //## @param sender: the widget, that caused that event, so that it can be asked for worldCoordinates. changed later to a focus //## @param type, button, buttonState, key: information from the Event //## @param displPosition: the 2D Position e.g. from the mouse //## @param worldPosition: the 3D position e.g. from a picking //## @param delta: the movement of the mousewheel WheelEvent(BaseRenderer* sender, int type, int button, int buttonState, int key, const Point2D& displPosition, int delta); int GetDelta() const; protected: int m_Delta; }; } // namespace mitk #endif /* WheelEvent_H_HEADER_INCLUDED_C184F366 */ diff --git a/Core/Code/Rendering/mitkPointSetVtkMapper2D.cpp b/Core/Code/Rendering/mitkPointSetVtkMapper2D.cpp index 75b05cb429..eceb59153d 100644 --- a/Core/Code/Rendering/mitkPointSetVtkMapper2D.cpp +++ b/Core/Code/Rendering/mitkPointSetVtkMapper2D.cpp @@ -1,717 +1,717 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkPointSetVtkMapper2D.h" //mitk includes #include "mitkDataNode.h" #include "mitkProperties.h" #include "mitkVtkPropRenderer.h" #include "mitkPointSet.h" #include "mitkPlaneGeometry.h" //vtk includes #include #include #include #include #include #include #include #include #include #include #include #include #include #include // constructor LocalStorage mitk::PointSetVtkMapper2D::LocalStorage::LocalStorage() { // points m_UnselectedPoints = vtkSmartPointer::New(); m_SelectedPoints = vtkSmartPointer::New(); m_ContourPoints = vtkSmartPointer::New(); // scales m_UnselectedScales = vtkSmartPointer::New(); m_SelectedScales = vtkSmartPointer::New(); // distances m_DistancesBetweenPoints = vtkSmartPointer::New(); // lines m_ContourLines = vtkSmartPointer::New(); // glyph source (provides the different shapes) m_UnselectedGlyphSource2D = vtkSmartPointer::New(); m_SelectedGlyphSource2D = vtkSmartPointer::New(); // glyphs m_UnselectedGlyph3D = vtkSmartPointer::New(); m_SelectedGlyph3D = vtkSmartPointer::New(); // polydata m_VtkUnselectedPointListPolyData = vtkSmartPointer::New(); m_VtkSelectedPointListPolyData = vtkSmartPointer ::New(); m_VtkContourPolyData = vtkSmartPointer::New(); // actors m_UnselectedActor = vtkSmartPointer ::New(); m_SelectedActor = vtkSmartPointer ::New(); m_ContourActor = vtkSmartPointer ::New(); // mappers m_VtkUnselectedPolyDataMapper = vtkSmartPointer::New(); m_VtkSelectedPolyDataMapper = vtkSmartPointer::New(); m_VtkContourPolyDataMapper = vtkSmartPointer::New(); // propassembly m_PropAssembly = vtkSmartPointer ::New(); } // destructor LocalStorage mitk::PointSetVtkMapper2D::LocalStorage::~LocalStorage() { } // input for this mapper ( = point set) const mitk::PointSet* mitk::PointSetVtkMapper2D::GetInput() const { return static_cast ( GetDataNode()->GetData() ); } // constructor PointSetVtkMapper2D mitk::PointSetVtkMapper2D::PointSetVtkMapper2D() : m_ShowContour(false), m_CloseContour(false), m_ShowPoints(true), m_ShowDistances(false), m_DistancesDecimalDigits(1), m_ShowAngles(false), m_ShowDistantLines(false), m_LineWidth(1), m_PointLineWidth(1), m_Point2DSize(6), m_IDShapeProperty(mitk::PointSetShapeProperty::CROSS), m_FillShape(false), m_DistanceToPlane(4.0f) { } // destructor mitk::PointSetVtkMapper2D::~PointSetVtkMapper2D() { } // reset mapper so that nothing is displayed e.g. toggle visiblity of the propassembly void mitk::PointSetVtkMapper2D::ResetMapper( BaseRenderer* renderer ) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); ls->m_PropAssembly->VisibilityOff(); } // returns propassembly vtkProp* mitk::PointSetVtkMapper2D::GetVtkProp(mitk::BaseRenderer * renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); return ls->m_PropAssembly; } static bool makePerpendicularVector2D(const mitk::Vector2D& in, mitk::Vector2D& out) { // The dot product of orthogonal vectors is zero. // In two dimensions the slopes of perpendicular lines are negative reciprocals. if((fabs(in[0])>0) && ( (fabs(in[0])>fabs(in[1])) || (in[1] == 0) ) ) { // negative reciprocal out[0]=-in[1]/in[0]; out[1]=1; out.Normalize(); return true; } else if(fabs(in[1])>0) { out[0]=1; // negative reciprocal out[1]=-in[0]/in[1]; out.Normalize(); return true; } else return false; } void mitk::PointSetVtkMapper2D::CreateVTKRenderObjects(mitk::BaseRenderer* renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); unsigned i = 0; // The vtk text actors need to be removed manually from the propassembly // since the same vtk text actors are not overwriten within this function, // but new actors are added to the propassembly each time this function is executed. // Thus, the actors from the last call must be removed in the beginning. for(i=0; i< ls->m_VtkTextLabelActors.size(); i++) { if(ls->m_PropAssembly->GetParts()->IsItemPresent(ls->m_VtkTextLabelActors.at(i))) ls->m_PropAssembly->RemovePart(ls->m_VtkTextLabelActors.at(i)); } for(i=0; i< ls->m_VtkTextDistanceActors.size(); i++) { if(ls->m_PropAssembly->GetParts()->IsItemPresent(ls->m_VtkTextDistanceActors.at(i))) ls->m_PropAssembly->RemovePart(ls->m_VtkTextDistanceActors.at(i)); } for(i=0; i< ls->m_VtkTextAngleActors.size(); i++) { if(ls->m_PropAssembly->GetParts()->IsItemPresent(ls->m_VtkTextAngleActors.at(i))) ls->m_PropAssembly->RemovePart(ls->m_VtkTextAngleActors.at(i)); } // initialize polydata here, otherwise we have update problems when // executing this function again ls->m_VtkUnselectedPointListPolyData = vtkSmartPointer::New(); ls->m_VtkSelectedPointListPolyData = vtkSmartPointer ::New(); ls->m_VtkContourPolyData = vtkSmartPointer::New(); // get input point set and update the PointSet mitk::PointSet::Pointer input = const_cast(this->GetInput()); // only update the input data, if the property tells us to bool update = true; this->GetDataNode()->GetBoolProperty("updateDataOnRender", update); if (update == true) input->Update(); int timestep = this->GetTimestep(); mitk::PointSet::DataType::Pointer itkPointSet = input->GetPointSet( timestep ); if ( itkPointSet.GetPointer() == NULL) { ls->m_PropAssembly->VisibilityOff(); return; } //iterator for point set mitk::PointSet::PointsContainer::Iterator pointsIter = itkPointSet->GetPoints()->Begin(); // PointDataContainer has additional information to each point, e.g. whether // it is selected or not mitk::PointSet::PointDataContainer::Iterator pointDataIter; pointDataIter = itkPointSet->GetPointData()->Begin(); //check if the list for the PointDataContainer is the same size as the PointsContainer. //If not, then the points were inserted manually and can not be visualized according to the PointData (selected/unselected) bool pointDataBroken = (itkPointSet->GetPointData()->Size() != itkPointSet->GetPoints()->Size()); if( itkPointSet->GetPointData()->size() == 0 || pointDataBroken) { ls->m_PropAssembly->VisibilityOff(); return; } ls->m_PropAssembly->VisibilityOn(); // empty point sets, cellarrays, scalars ls->m_UnselectedPoints->Reset(); ls->m_SelectedPoints->Reset(); ls->m_ContourPoints->Reset(); ls->m_ContourLines->Reset(); ls->m_UnselectedScales->Reset(); ls->m_SelectedScales->Reset(); ls->m_DistancesBetweenPoints->Reset(); ls->m_VtkTextLabelActors.clear(); ls->m_VtkTextDistanceActors.clear(); ls->m_VtkTextAngleActors.clear(); ls->m_UnselectedScales->SetNumberOfComponents(3); ls->m_SelectedScales->SetNumberOfComponents(3); int NumberContourPoints = 0; bool pointsOnSameSideOfPlane = false; const int text2dDistance = 10; // initialize points with a random start value // current point in point set itk::Point point = pointsIter->Value(); mitk::Point3D p = point; // currently visited point mitk::Point3D lastP = point; // last visited point (predecessor in point set of "point") mitk::Vector3D vec; // p - lastP mitk::Vector3D lastVec; // lastP - point before lastP - vec.Fill(0); - lastVec.Fill(0); + vec.Fill(0.0); + lastVec.Fill(0.0); mitk::Point3D projected_p = point; // p projected on viewplane mitk::Point2D pt2d; pt2d[0] = point[0]; // projected_p in display coordinates pt2d[1] = point[1]; mitk::Point2D lastPt2d = pt2d; // last projected_p in display coordinates (predecessor in point set of "pt2d") mitk::Point2D preLastPt2d = pt2d ; // projected_p in display coordinates before lastPt2 mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry(); const mitk::Geometry2D* geo2D = renderer->GetCurrentWorldGeometry2D(); vtkLinearTransform* dataNodeTransform = input->GetGeometry()->GetVtkTransform(); int count = 0; for (pointsIter=itkPointSet->GetPoints()->Begin(); pointsIter!=itkPointSet->GetPoints()->End(); pointsIter++) { lastP = p; // valid for number of points count > 0 preLastPt2d = lastPt2d; // valid only for count > 1 lastPt2d = pt2d; // valid for number of points count > 0 lastVec = vec; // valid only for counter > 1 // get current point in point set point = pointsIter->Value(); // transform point { float vtkp[3]; itk2vtk(point, vtkp); dataNodeTransform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp,point); } p[0] = point[0]; p[1] = point[1]; p[2] = point[2]; displayGeometry->Project(p, projected_p); displayGeometry->Map(projected_p, pt2d); displayGeometry->WorldToDisplay(pt2d, pt2d); vec = p-lastP; // valid only for counter > 0 // compute distance to current plane float diff = geo2D->Distance(point); diff = diff * diff; // draw markers on slices a certain distance away from the points true location according to the tolerance threshold (m_DistanceToPlane) if(diff < m_DistanceToPlane) { // is point selected or not? if (pointDataIter->Value().selected) { ls->m_SelectedPoints->InsertNextPoint(point[0],point[1],point[2]); // point is scaled according to its distance to the plane ls->m_SelectedScales->InsertNextTuple3(m_Point2DSize - (2*diff),0,0); } else { ls->m_UnselectedPoints->InsertNextPoint(point[0],point[1],point[2]); // point is scaled according to its distance to the plane ls->m_UnselectedScales->InsertNextTuple3(m_Point2DSize - (2*diff),0,0); } //---- LABEL -----// // paint label for each point if available if (dynamic_cast(this->GetDataNode()->GetProperty("label")) != NULL) { const char * pointLabel = dynamic_cast( this->GetDataNode()->GetProperty("label"))->GetValue(); std::string l = pointLabel; if (input->GetSize()>1) { std::stringstream ss; ss << pointsIter->Index(); l.append(ss.str()); } ls->m_VtkTextActor = vtkSmartPointer::New(); ls->m_VtkTextActor->SetPosition(pt2d[0] + text2dDistance, pt2d[1] + text2dDistance); ls->m_VtkTextActor->SetInput(l.c_str()); ls->m_VtkTextActor->GetTextProperty()->SetOpacity( 100 ); float unselectedColor[4]; //check if there is a color property GetDataNode()->GetColor(unselectedColor); if (unselectedColor != NULL) ls->m_VtkTextActor->GetTextProperty()->SetColor(unselectedColor[0], unselectedColor[1], unselectedColor[2]); else ls->m_VtkTextActor->GetTextProperty()->SetColor(0.0f, 1.0f, 0.0f); ls->m_VtkTextLabelActors.push_back(ls->m_VtkTextActor); } } // draw contour, distance text and angle text in render window // lines between points, which intersect the current plane, are drawn if( m_ShowContour && count > 0 ) { ScalarType distance = displayGeometry->GetWorldGeometry()->SignedDistance(point); ScalarType lastDistance = displayGeometry->GetWorldGeometry()->SignedDistance(lastP); pointsOnSameSideOfPlane = (distance * lastDistance) > 0.5; // Points must be on different side of plane in order to draw a contour. // If "show distant lines" is enabled this condition is disregarded. if ( !pointsOnSameSideOfPlane || m_ShowDistantLines) { vtkSmartPointer line = vtkSmartPointer::New(); ls->m_ContourPoints->InsertNextPoint(lastP[0],lastP[1],lastP[2]); line->GetPointIds()->SetId(0, NumberContourPoints); NumberContourPoints++; ls->m_ContourPoints->InsertNextPoint(point[0], point[1], point[2]); line->GetPointIds()->SetId(1, NumberContourPoints); NumberContourPoints++; ls->m_ContourLines->InsertNextCell(line); if(m_ShowDistances) // calculate and print distance between adjacent points { float distancePoints = point.EuclideanDistanceTo(lastP); std::stringstream buffer; buffer<m_VtkTextActor = vtkSmartPointer::New(); ls->m_VtkTextActor->SetPosition(pos2d[0],pos2d[1]); ls->m_VtkTextActor->SetInput(buffer.str().c_str()); ls->m_VtkTextActor->GetTextProperty()->SetColor(0.0, 1.0, 0.0); ls->m_VtkTextDistanceActors.push_back(ls->m_VtkTextActor); } if(m_ShowAngles && count > 1) // calculate and print angle between connected lines { std::stringstream buffer; //(char) 176 is the degree sign buffer << angle(vec.GetVnlVector(), -lastVec.GetVnlVector())*180/vnl_math::pi << (char)176; //compute desired display position of text Vector2D vec2d = pt2d-lastPt2d; // first arm enclosing the angle vec2d.Normalize(); Vector2D lastVec2d = lastPt2d-preLastPt2d; // second arm enclosing the angle lastVec2d.Normalize(); vec2d=vec2d-lastVec2d; // vector connecting both arms vec2d.Normalize(); // middle between two vectors that enclose the angle Vector2D pos2d = lastPt2d.GetVectorFromOrigin() + vec2d * text2dDistance * text2dDistance; ls->m_VtkTextActor = vtkSmartPointer::New(); ls->m_VtkTextActor->SetPosition(pos2d[0],pos2d[1]); ls->m_VtkTextActor->SetInput(buffer.str().c_str()); ls->m_VtkTextActor->GetTextProperty()->SetColor(0.0, 1.0, 0.0); ls->m_VtkTextAngleActors.push_back(ls->m_VtkTextActor); } } } if(pointDataIter != itkPointSet->GetPointData()->End()) { pointDataIter++; count++; } } // add each single text actor to the assembly for(i=0; i< ls->m_VtkTextLabelActors.size(); i++) { ls->m_PropAssembly->AddPart(ls->m_VtkTextLabelActors.at(i)); } for(i=0; i< ls->m_VtkTextDistanceActors.size(); i++) { ls->m_PropAssembly->AddPart(ls->m_VtkTextDistanceActors.at(i)); } for(i=0; i< ls->m_VtkTextAngleActors.size(); i++) { ls->m_PropAssembly->AddPart(ls->m_VtkTextAngleActors.at(i)); } //---- CONTOUR -----// //create lines between the points which intersect the plane if (m_ShowContour) { // draw line between first and last point which is rendered if(m_CloseContour && NumberContourPoints > 1){ vtkSmartPointer closingLine = vtkSmartPointer::New(); closingLine->GetPointIds()->SetId(0, 0); // index of first point closingLine->GetPointIds()->SetId(1, NumberContourPoints-1); // index of last point ls->m_ContourLines->InsertNextCell(closingLine); } ls->m_VtkContourPolyData->SetPoints(ls->m_ContourPoints); ls->m_VtkContourPolyData->SetLines(ls->m_ContourLines); ls->m_VtkContourPolyDataMapper->SetInputData(ls->m_VtkContourPolyData); ls->m_ContourActor->SetMapper(ls->m_VtkContourPolyDataMapper); ls->m_ContourActor->GetProperty()->SetLineWidth(m_LineWidth); ls->m_PropAssembly->AddPart(ls->m_ContourActor); } // the point set must be transformed in order to obtain the appropriate glyph orientation // according to the current view vtkSmartPointer transform = vtkSmartPointer::New(); vtkSmartPointer a,b = vtkSmartPointer::New(); a = geo2D->GetVtkTransform()->GetMatrix(); b->DeepCopy( a ); // delete transformation from matrix, only take orientation b->SetElement(3,3,1); b->SetElement(2,3,0); b->SetElement(1,3,0); b->SetElement(0,3,0); b->SetElement(3,2,0); b->SetElement(3,1,0); b->SetElement(3,0,0); transform->SetMatrix( b ); //---- UNSELECTED POINTS -----// // apply properties to glyph ls->m_UnselectedGlyphSource2D->SetGlyphType(m_IDShapeProperty); if(m_FillShape) ls->m_UnselectedGlyphSource2D->FilledOn(); else ls->m_UnselectedGlyphSource2D->FilledOff(); // apply transform vtkSmartPointer transformFilterU = vtkSmartPointer::New(); transformFilterU->SetInputConnection(ls->m_UnselectedGlyphSource2D->GetOutputPort()); transformFilterU->SetTransform(transform); ls->m_VtkUnselectedPointListPolyData->SetPoints(ls->m_UnselectedPoints); ls->m_VtkUnselectedPointListPolyData->GetPointData()->SetVectors(ls->m_UnselectedScales); // apply transform of current plane to glyphs ls->m_UnselectedGlyph3D->SetSourceConnection(transformFilterU->GetOutputPort()); ls->m_UnselectedGlyph3D->SetInputData(ls->m_VtkUnselectedPointListPolyData); ls->m_UnselectedGlyph3D->SetScaleModeToScaleByVector(); ls->m_UnselectedGlyph3D->SetVectorModeToUseVector(); ls->m_VtkUnselectedPolyDataMapper->SetInputConnection(ls->m_UnselectedGlyph3D->GetOutputPort()); ls->m_UnselectedActor->SetMapper(ls->m_VtkUnselectedPolyDataMapper); ls->m_UnselectedActor->GetProperty()->SetLineWidth(m_PointLineWidth); ls->m_PropAssembly->AddPart(ls->m_UnselectedActor); //---- SELECTED POINTS -----// ls->m_SelectedGlyphSource2D->SetGlyphTypeToDiamond(); ls->m_SelectedGlyphSource2D->CrossOn(); ls->m_SelectedGlyphSource2D->FilledOff(); // apply transform vtkSmartPointer transformFilterS = vtkSmartPointer::New(); transformFilterS->SetInputConnection(ls->m_SelectedGlyphSource2D->GetOutputPort()); transformFilterS->SetTransform(transform); ls->m_VtkSelectedPointListPolyData->SetPoints(ls->m_SelectedPoints); ls->m_VtkSelectedPointListPolyData->GetPointData()->SetVectors(ls->m_SelectedScales); // apply transform of current plane to glyphs ls->m_SelectedGlyph3D->SetSourceConnection(transformFilterS->GetOutputPort()); ls->m_SelectedGlyph3D->SetInputData(ls->m_VtkSelectedPointListPolyData); ls->m_SelectedGlyph3D->SetScaleModeToScaleByVector(); ls->m_SelectedGlyph3D->SetVectorModeToUseVector(); ls->m_VtkSelectedPolyDataMapper->SetInputConnection(ls->m_SelectedGlyph3D->GetOutputPort()); ls->m_SelectedActor->SetMapper(ls->m_VtkSelectedPolyDataMapper); ls->m_SelectedActor->GetProperty()->SetLineWidth(m_PointLineWidth); ls->m_PropAssembly->AddPart(ls->m_SelectedActor); } void mitk::PointSetVtkMapper2D::GenerateDataForRenderer( mitk::BaseRenderer *renderer ) { const mitk::DataNode* node = GetDataNode(); if( node == NULL ) return; LocalStorage *ls = m_LSH.GetLocalStorage(renderer); // check whether the input data has been changed bool needGenerateData = ls->IsGenerateDataRequired( renderer, this, GetDataNode() ); // toggle visibility bool visible = true; node->GetVisibility(visible, renderer, "visible"); if(!visible) { ls->m_UnselectedActor->VisibilityOff(); ls->m_SelectedActor->VisibilityOff(); ls->m_ContourActor->VisibilityOff(); ls->m_PropAssembly->VisibilityOff(); return; }else{ ls->m_PropAssembly->VisibilityOn(); } node->GetBoolProperty("show contour", m_ShowContour, renderer); node->GetBoolProperty("close contour", m_CloseContour, renderer); node->GetBoolProperty("show points", m_ShowPoints, renderer); node->GetBoolProperty("show distances", m_ShowDistances, renderer); node->GetIntProperty("distance decimal digits", m_DistancesDecimalDigits, renderer); node->GetBoolProperty("show angles", m_ShowAngles, renderer); node->GetBoolProperty("show distant lines", m_ShowDistantLines, renderer); node->GetIntProperty("line width", m_LineWidth, renderer); node->GetIntProperty("point line width", m_PointLineWidth, renderer); node->GetIntProperty("point 2D size", m_Point2DSize, renderer); node->GetBoolProperty("Pointset.2D.fill shape", m_FillShape, renderer); node->GetFloatProperty("Pointset.2D.distance to plane", m_DistanceToPlane, renderer ); mitk::PointSetShapeProperty::Pointer shape = dynamic_cast(this->GetDataNode()->GetProperty( "Pointset.2D.shape", renderer )); if(shape.IsNotNull()) { m_IDShapeProperty = shape->GetPointSetShape(); } //check for color props and use it for rendering of selected/unselected points and contour //due to different params in VTK (double/float) we have to convert float unselectedColor[4]; double selectedColor[4]={1.0f,0.0f,0.0f,1.0f}; //red double contourColor[4]={1.0f,0.0f,0.0f,1.0f}; //red float opacity = 1.0; GetDataNode()->GetOpacity(opacity, renderer); // apply color and opacity if(m_ShowPoints) { ls->m_UnselectedActor->VisibilityOn(); ls->m_SelectedActor->VisibilityOn(); //check if there is a color property GetDataNode()->GetColor(unselectedColor); //get selected color property if (dynamic_cast(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("selectedcolor")) != NULL) { mitk::Color tmpColor = dynamic_cast(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("selectedcolor"))->GetValue(); selectedColor[0] = tmpColor[0]; selectedColor[1] = tmpColor[1]; selectedColor[2] = tmpColor[2]; selectedColor[3] = 1.0f; // alpha value } else if (dynamic_cast(this->GetDataNode()->GetPropertyList(NULL)->GetProperty("selectedcolor")) != NULL) { mitk::Color tmpColor = dynamic_cast(this->GetDataNode()->GetPropertyList(NULL)->GetProperty("selectedcolor"))->GetValue(); selectedColor[0] = tmpColor[0]; selectedColor[1] = tmpColor[1]; selectedColor[2] = tmpColor[2]; selectedColor[3] = 1.0f; // alpha value } ls->m_SelectedActor->GetProperty()->SetColor(selectedColor); ls->m_SelectedActor->GetProperty()->SetOpacity(opacity); ls->m_UnselectedActor->GetProperty()->SetColor(unselectedColor[0],unselectedColor[1],unselectedColor[2]); ls->m_UnselectedActor->GetProperty()->SetOpacity(opacity); } else { ls->m_UnselectedActor->VisibilityOff(); ls-> m_SelectedActor->VisibilityOff(); } if (m_ShowContour) { ls->m_ContourActor->VisibilityOn(); //get contour color property if (dynamic_cast(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("contourcolor")) != NULL) { mitk::Color tmpColor = dynamic_cast(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("contourcolor"))->GetValue(); contourColor[0] = tmpColor[0]; contourColor[1] = tmpColor[1]; contourColor[2] = tmpColor[2]; contourColor[3] = 1.0f; } else if (dynamic_cast(this->GetDataNode()->GetPropertyList(NULL)->GetProperty("contourcolor")) != NULL) { mitk::Color tmpColor = dynamic_cast(this->GetDataNode()->GetPropertyList(NULL)->GetProperty("contourcolor"))->GetValue(); contourColor[0] = tmpColor[0]; contourColor[1] = tmpColor[1]; contourColor[2] = tmpColor[2]; contourColor[3] = 1.0f; } ls->m_ContourActor->GetProperty()->SetColor(contourColor); ls->m_ContourActor->GetProperty()->SetOpacity(opacity); } else { ls->m_ContourActor->VisibilityOff(); } if(needGenerateData) { // create new vtk render objects (e.g. a circle for a point) this->CreateVTKRenderObjects(renderer); } } void mitk::PointSetVtkMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { node->AddProperty( "line width", mitk::IntProperty::New(2), renderer, overwrite ); node->AddProperty( "point line width", mitk::IntProperty::New(1), renderer, overwrite ); node->AddProperty( "point 2D size", mitk::IntProperty::New(6), renderer, overwrite ); node->AddProperty( "show contour", mitk::BoolProperty::New(false), renderer, overwrite ); node->AddProperty( "close contour", mitk::BoolProperty::New(false), renderer, overwrite ); node->AddProperty( "show points", mitk::BoolProperty::New(true), renderer, overwrite ); node->AddProperty( "show distances", mitk::BoolProperty::New(false), renderer, overwrite ); node->AddProperty( "distance decimal digits", mitk::IntProperty::New(2), renderer, overwrite ); node->AddProperty( "show angles", mitk::BoolProperty::New(false), renderer, overwrite ); node->AddProperty( "show distant lines", mitk::BoolProperty::New(false), renderer, overwrite ); node->AddProperty( "layer", mitk::IntProperty::New(1), renderer, overwrite ); node->AddProperty( "Pointset.2D.fill shape", mitk::BoolProperty::New(false), renderer, overwrite); // fill or do not fill the glyph shape mitk::PointSetShapeProperty::Pointer pointsetShapeProperty = mitk::PointSetShapeProperty::New(); node->AddProperty( "Pointset.2D.shape", pointsetShapeProperty, renderer, overwrite); node->AddProperty( "Pointset.2D.distance to plane", mitk::FloatProperty::New(4.0f), renderer, overwrite ); //show the point at a certain distance above/below the 2D imaging plane. Superclass::SetDefaultProperties(node, renderer, overwrite); } diff --git a/Core/Code/Testing/mitkAffineTransformBaseTest.cpp b/Core/Code/Testing/mitkAffineTransformBaseTest.cpp index f7e70df745..2766b1dc67 100644 --- a/Core/Code/Testing/mitkAffineTransformBaseTest.cpp +++ b/Core/Code/Testing/mitkAffineTransformBaseTest.cpp @@ -1,185 +1,185 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkTypes.h" +#include "mitkNumericTypes.h" #include "itkScalableAffineTransform.h" #include "mitkMatrixConvert.h" #include "mitkTestingMacros.h" using namespace mitk; static Vector3D offset; static Matrix3D rotation; static Point3D originalPoint; static double originalPointDouble[4]; static vtkMatrix4x4* homogenMatrix; static vtkMatrix4x4* expectedHomogenousMatrix; static const double expectedPointAfterTransformation[] = {2, 4, 4, 1}; static void Setup() { originalPoint[0] = 1.0; originalPoint[1] = 0.0; originalPoint[2] = 0.0; for (int i = 0; i < 3; i++) originalPointDouble[i] = originalPoint[i]; // same point as the Point3D version originalPointDouble[3] = 1; // homogenous extension offset[0] = 2.0; offset[1] = 3.0; offset[2] = 4.0; // 90� rotation rotation.Fill(0); rotation[0][1] = -1; rotation[1][0] = 1; // prepare a Matrix which shall be set later to a specific // homogen matrix by TransferItkTransformToVtkMatrix // this makes sure, that the initialization to the identity does not // overshadow any bugs in TransferItkTransformToVtkMatrix // (it actually did that by "helping out" TransferItkTransformToVtkMatrix // by setting the (3,3) element to 1). homogenMatrix = vtkMatrix4x4::New(); for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) homogenMatrix->SetElement(i,j, i+j*j); // just some not trivial value // set the expected homogenous matrix result expectedHomogenousMatrix = vtkMatrix4x4::New(); expectedHomogenousMatrix->Zero(); expectedHomogenousMatrix->SetElement(0,1,-1); expectedHomogenousMatrix->SetElement(1,0,1); expectedHomogenousMatrix->SetElement(0,3,2); expectedHomogenousMatrix->SetElement(1,3,3); expectedHomogenousMatrix->SetElement(2,3,4); expectedHomogenousMatrix->SetElement(3,3,1); } /** * This first test basically assures that we understand the usage of AffineTransform3D correct. * Meaning that the rotation is set by SetMatrix and the translation is set by SetOffset */ static void testIfPointIsTransformedAsExpected(void) { Setup(); /** construct the transformation */ AffineTransform3D::Pointer transform = AffineTransform3D::New(); transform->SetOffset(offset); transform->SetMatrix(rotation); TransferItkTransformToVtkMatrix(transform.GetPointer(), homogenMatrix); /** Let a point be transformed by the AffineTransform3D */ Point3D pointTransformedByAffineTransform3D = transform->TransformPoint(originalPoint); /** assert that the transformation was successful */ bool pointCorrect = true; for (int i = 0; i < 3; i++) // only first three since no homogenous coordinates pointCorrect &= Equal(pointTransformedByAffineTransform3D[i], expectedPointAfterTransformation[i]); MITK_TEST_CONDITION(pointCorrect, "Point has been correctly transformed by AffineTranform3D") } /** * This test ensures that the function TransferItkTransformToVtkMatrix translates the AffineTransform3D * correctly to a VtkMatrix4x4 */ static void testTransferItkTransformToVtkMatrix(void) { Setup(); AffineTransform3D::Pointer transform = AffineTransform3D::New(); transform->SetOffset(offset); transform->SetMatrix(rotation); TransferItkTransformToVtkMatrix(transform.GetPointer(), homogenMatrix); bool allElementsEqual = true; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) allElementsEqual &= Equal(homogenMatrix->GetElement(i,j), expectedHomogenousMatrix->GetElement(i,j)); MITK_TEST_CONDITION(allElementsEqual, "Homogenous Matrix is set as expected") } /** * This test basically is just a sanity check and should be PASSED exactly when both * testTransferItkTransformToVtkMatrix and testIfPointIsTransformedAsExpected are PASSED. * Tests if we get the same * result by using the AffineTransform3D to transform a point or the vtkMatrix4x4 which we got by applying * the TransferItkTransformToVtkMatrix function. This test e.g. ensures we made no mistake in our * reference results. * */ static void testIfBothTransformationsProduceSameResults(void) { Setup(); /** * create both a AffineTransform3D * and let this AffineTransform describe also a homogenous 4x4 Matrix vtkMatrix * by using our transfer method */ AffineTransform3D::Pointer transform = AffineTransform3D::New(); transform->SetOffset(offset); transform->SetMatrix(rotation); TransferItkTransformToVtkMatrix(transform.GetPointer(), homogenMatrix); /** Let a point be transformed by the AffineTransform3D and by homogenMatrix */ Point3D pointTransformedByAffineTransform3D = transform->TransformPoint(originalPoint); double* pointTransformedByHomogenous= homogenMatrix->MultiplyDoublePoint(originalPointDouble); /* check if results match */ bool pointsMatch = true; for (int i = 0; i < 3; i++) // only first three since no homogenous coordinates pointsMatch &= Equal(pointTransformedByAffineTransform3D[i], pointTransformedByHomogenous[i]); bool homogenousComponentCorrect = Equal(1, pointTransformedByHomogenous[3]); MITK_TEST_CONDITION(pointsMatch && homogenousComponentCorrect, "Point transformed by AffineTransform and homogenous coordinates match") } /** * This test shall ensure and document the basic functionality of the * itk AffineTransformation functionality and test some basic transformation functionalities provided by mitk. */ int mitkAffineTransformBaseTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN("AffineTransformationBaseTest"); testIfPointIsTransformedAsExpected(); testTransferItkTransformToVtkMatrix(); testIfBothTransformationsProduceSameResults(); MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkArrayTypeConversionTest.cpp b/Core/Code/Testing/mitkArrayTypeConversionTest.cpp index 976e64750b..8955142ebc 100644 --- a/Core/Code/Testing/mitkArrayTypeConversionTest.cpp +++ b/Core/Code/Testing/mitkArrayTypeConversionTest.cpp @@ -1,91 +1,98 @@ -/* - * mitkArrayTest.cpp - * - * Created on: Apr 22, 2014 - * Author: wirkert - */ +/*=================================================================== +The Medical Imaging Interaction Toolkit (MITK) +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ #include "mitkTestingMacros.h" #include "mitkTestFixture.h" -#include "mitkConstants.h" +#include "mitkNumericConstants.h" #include "mitkArray.h" class mitkArrayTypeConversionTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkArrayTypeConversionTestSuite); MITK_TEST(EqualArray_ReturnsTrue); MITK_TEST(EqualArray_ReturnsFalse); MITK_TEST(FillVector3D_CorrectlyFilled); MITK_TEST(FillVector4D_CorrectlyFilled); CPPUNIT_TEST_SUITE_END(); private: mitk::ScalarType a[3]; mitk::ScalarType b[3]; public: void setUp(void) { b[0] = a[0] = 1.0; b[1] = a[1] = 2.12; b[2] = a[2] = 3.13; } void tearDown(void) { } void EqualArray_ReturnsTrue(void) { CPPUNIT_ASSERT_EQUAL_MESSAGE("test if EqualArray method returns true for two equal arrays.", true, mitk::EqualArray(a, b, 3)); } void EqualArray_ReturnsFalse(void) { b[2] += mitk::eps; CPPUNIT_ASSERT_EQUAL_MESSAGE("test if EqualArray method returns false for two non-equal arrays.", false, mitk::EqualArray(a, b, 3)); } void FillVector3D_CorrectlyFilled(void) { mitk::ScalarType c[3]; mitk::FillVector3D(c, a[0], a[1], a[2]); CPPUNIT_ASSERT_EQUAL_MESSAGE("test if FillVector3D correctly fills array types.", true, mitk::EqualArray(a, c, 3)); } void FillVector4D_CorrectlyFilled(void) { mitk::ScalarType e[4]; mitk::ScalarType f[4]; e[0] = 1.0; e[1] = 2.12; e[2] = 3.13; e[3] = 4.14; mitk::FillVector4D(f, e[0], e[1], e[2], e[3]); CPPUNIT_ASSERT_EQUAL_MESSAGE("test if FillVector4D correctly fills array types.", true, mitk::EqualArray(e, f, 4)); } }; MITK_TEST_SUITE_REGISTRATION(mitkArrayTypeConversion) diff --git a/Core/Code/Testing/mitkClippedSurfaceBoundsCalculatorTest.cpp b/Core/Code/Testing/mitkClippedSurfaceBoundsCalculatorTest.cpp index bd3a2a2bb2..43bfa76acd 100644 --- a/Core/Code/Testing/mitkClippedSurfaceBoundsCalculatorTest.cpp +++ b/Core/Code/Testing/mitkClippedSurfaceBoundsCalculatorTest.cpp @@ -1,484 +1,484 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include #include "mitkClippedSurfaceBoundsCalculator.h" #include "mitkGeometry3D.h" #include "mitkGeometry2D.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" static void CheckPlanesInsideBoundingBoxOnlyOnOneSlice(mitk::Geometry3D::Pointer geometry3D) { //Check planes which are inside the bounding box mitk::ClippedSurfaceBoundsCalculator* calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer image = mitk::Image::New(); image->Initialize( mitk::MakePixelType(), *(geometry3D.GetPointer()) ); //Check planes which are only on one slice: //Slice 0 mitk::Point3D origin; origin[0] = 511; origin[1] = 0; origin[2] = 0; mitk::Vector3D normal; mitk::FillVector3D(normal, 0, 0, 1); mitk::PlaneGeometry::Pointer planeOnSliceZero = mitk::PlaneGeometry::New(); planeOnSliceZero->InitializePlane(origin, normal); calculator->SetInput( planeOnSliceZero , image); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 0, "Check if plane is on slice 0"); //Slice 3 origin[2] = 3; mitk::PlaneGeometry::Pointer planeOnSliceThree = mitk::PlaneGeometry::New(); planeOnSliceThree->InitializePlane(origin, normal); planeOnSliceThree->SetImageGeometry(false); calculator->SetInput( planeOnSliceThree , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 3 && minMax.second == 3, "Check if plane is on slice 3"); //Slice 17 origin[2] = 17; mitk::PlaneGeometry::Pointer planeOnSliceSeventeen = mitk::PlaneGeometry::New(); planeOnSliceSeventeen->InitializePlane(origin, normal); calculator->SetInput( planeOnSliceSeventeen , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 17 && minMax.second == 17, "Check if plane is on slice 17"); //Slice 20 origin[2] = 19; mitk::PlaneGeometry::Pointer planeOnSliceTwenty = mitk::PlaneGeometry::New(); planeOnSliceTwenty->InitializePlane(origin, normal); calculator->SetInput( planeOnSliceTwenty , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 19 && minMax.second == 19, "Check if plane is on slice 19"); delete calculator; } static void CheckPlanesInsideBoundingBox(mitk::Geometry3D::Pointer geometry3D) { //Check planes which are inside the bounding box mitk::ClippedSurfaceBoundsCalculator* calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer image = mitk::Image::New(); image->Initialize( mitk::MakePixelType(), *(geometry3D.GetPointer()) ); //Check planes which are only on one slice: //Slice 0 mitk::Point3D origin; origin[0] = 511; // Set to 511.9 so that the intersection point is inside the bounding box origin[1] = 0; origin[2] = 0; mitk::Vector3D normal; mitk::FillVector3D(normal, 1, 0, 0); mitk::PlaneGeometry::Pointer planeSagittalOne = mitk::PlaneGeometry::New(); planeSagittalOne->InitializePlane(origin, normal); calculator->SetInput( planeSagittalOne , image); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19"); //Slice 3 origin[0] = 256; MITK_INFO << "Case1 origin: " << origin; mitk::PlaneGeometry::Pointer planeSagittalTwo = mitk::PlaneGeometry::New(); planeSagittalTwo->InitializePlane(origin, normal); MITK_INFO << "PlaneNormal: " << planeSagittalTwo->GetNormal(); MITK_INFO << "PlaneOrigin: " << planeSagittalTwo->GetOrigin(); calculator->SetInput( planeSagittalTwo , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19"); //Slice 17 origin[0] = 0; // Set to 0.1 so that the intersection point is inside the bounding box mitk::PlaneGeometry::Pointer planeOnSliceSeventeen = mitk::PlaneGeometry::New(); planeOnSliceSeventeen->InitializePlane(origin, normal); calculator->SetInput( planeOnSliceSeventeen , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19"); //Crooked planes: origin[0] = 0; origin[1] = 507; origin[2] = 0; normal[0] = 1; normal[1] = -1; normal[2] = 1; mitk::PlaneGeometry::Pointer planeCrookedOne = mitk::PlaneGeometry::New(); planeCrookedOne->InitializePlane(origin, normal); calculator->SetInput( planeCrookedOne , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 4, "Check if plane is from slice 0 to slice 4 with inclined plane"); origin[0] = 512; origin[1] = 0; origin[2] = 16; mitk::PlaneGeometry::Pointer planeCrookedTwo = mitk::PlaneGeometry::New(); planeCrookedTwo->InitializePlane(origin, normal); calculator->SetInput( planeCrookedTwo , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 17 && minMax.second == 19, "Check if plane is from slice 17 to slice 19 with inclined plane"); origin[0] = 511; origin[1] = 0; origin[2] = 0; normal[1] = 0; normal[2] = 0.04; mitk::PlaneGeometry::Pointer planeCrookedThree = mitk::PlaneGeometry::New(); planeCrookedThree->InitializePlane(origin, normal); calculator->SetInput( planeCrookedThree , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19 with inclined plane"); delete calculator; } static void CheckPlanesOutsideOfBoundingBox(mitk::Geometry3D::Pointer geometry3D) { //Check planes which are outside of the bounding box mitk::ClippedSurfaceBoundsCalculator* calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer image = mitk::Image::New(); image->Initialize( mitk::MakePixelType(), *(geometry3D.GetPointer()) ); //In front of the bounding box mitk::Point3D origin; origin[0] = 511; origin[1] = 0; origin[2] = -5; mitk::Vector3D normal; mitk::FillVector3D(normal, 0, 0, 1); mitk::PlaneGeometry::Pointer planeInFront = mitk::PlaneGeometry::New(); planeInFront->InitializePlane(origin, normal); calculator->SetInput( planeInFront , image); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); //Behind the bounding box origin[2] = 515; mitk::PlaneGeometry::Pointer planeBehind = mitk::PlaneGeometry::New(); planeBehind->InitializePlane(origin, normal); calculator->SetInput( planeBehind , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); //Above origin[1] = 515; mitk::FillVector3D(normal, 0, 1, 0); mitk::PlaneGeometry::Pointer planeAbove = mitk::PlaneGeometry::New(); planeAbove->InitializePlane(origin, normal); calculator->SetInput( planeAbove , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); //Below origin[1] = -5; mitk::PlaneGeometry::Pointer planeBelow = mitk::PlaneGeometry::New(); planeBelow->InitializePlane(origin, normal); calculator->SetInput( planeBelow , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); //Left side origin[0] = -5; mitk::FillVector3D(normal, 1, 0, 0); mitk::PlaneGeometry::Pointer planeLeftSide = mitk::PlaneGeometry::New(); planeLeftSide->InitializePlane(origin, normal); calculator->SetInput( planeLeftSide , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); //Right side origin[1] = 515; mitk::PlaneGeometry::Pointer planeRightSide = mitk::PlaneGeometry::New(); planeRightSide->InitializePlane(origin, normal); calculator->SetInput( planeRightSide , image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); delete calculator; } static void CheckIntersectionPointsOfTwoGeometry3D(mitk::Geometry3D::Pointer firstGeometry3D, mitk::Geometry3D::Pointer secondGeometry3D) { mitk::ClippedSurfaceBoundsCalculator* calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer firstImage = mitk::Image::New(); firstImage->Initialize( mitk::MakePixelType(), *(firstGeometry3D.GetPointer()) ); calculator->SetInput( secondGeometry3D, firstImage); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionZ(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19"); } static void CheckIntersectionWithPointCloud( mitk::Geometry3D::Pointer geometry3D ) { //Check planes which are inside the bounding box mitk::Image::Pointer image = mitk::Image::New(); image->Initialize( mitk::MakePixelType(), *(geometry3D.GetPointer()) ); { mitk::Point3D pnt1, pnt2; pnt1[0] = 3; pnt1[1] = 5; pnt1[2] = 3; pnt2[0] = 8; pnt2[1] = 3; pnt2[2] = 8; mitk::ClippedSurfaceBoundsCalculator::PointListType pointlist; pointlist.push_back( pnt1 ); pointlist.push_back( pnt2 ); mitk::ClippedSurfaceBoundsCalculator calculator; calculator.SetInput( pointlist, image ); calculator.Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMaxZ = calculator.GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMaxZ.first == 3 && minMaxZ.second == 8, "Check if points span from slice 3 to slice 8 in axial"); mitk::ClippedSurfaceBoundsCalculator::OutputType minMaxX = calculator.GetMinMaxSpatialDirectionX(); MITK_TEST_CONDITION(minMaxX.first == 3 && minMaxX.second == 5, "Check if points span from slice 3 to slice 5 in sagittal"); } { mitk::Point3D pnt1, pnt2; pnt1.Fill( -3 ); pnt2.Fill( 600 ); mitk::ClippedSurfaceBoundsCalculator::PointListType pointlist; pointlist.push_back( pnt1 ); pointlist.push_back( pnt2 ); mitk::ClippedSurfaceBoundsCalculator calculator; calculator.SetInput( pointlist, image ); calculator.Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMaxZ = calculator.GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMaxZ.first == 0 && minMaxZ.second == 19, "Check if points are correctly clipped to slice 0 and slice 19 in axial"); mitk::ClippedSurfaceBoundsCalculator::OutputType minMaxX = calculator.GetMinMaxSpatialDirectionX(); MITK_TEST_CONDITION(minMaxX.first == 0 && minMaxX.second == 511, "Check if points are correctly clipped to slice 0 and slice 511 in sagittal"); } } int mitkClippedSurfaceBoundsCalculatorTest(int, char* []) { // always start with this! MITK_TEST_BEGIN("ClippedSurfaceBoundsCalculator"); /** The class mitkClippedSurfaceBoundsCalculator calculates the intersection points of a PlaneGeometry and a Geometry3D. * This unittest checks if the correct min and max values for the three spatial directions (x, y, z) * are calculated. To test this we define artifical PlaneGeometries and Geometry3Ds and test different * scenarios: * * 1. planes which are inside the bounding box of a 3D geometry but only on one slice * 2. planes which are outside of the bounding box * 3. planes which are inside the bounding box but over more than one slice * * Note: Currently rotated geometries are not tested! */ /********************* Define Geometry3D ***********************/ //Define origin: mitk::Point3D origin; origin[0] = 511; origin[1] = 0; origin[2] = 0; //Define normal: mitk::Vector3D normal; mitk::FillVector3D(normal, 0, 0, 1); //Initialize PlaneGeometry: mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New(); planeGeometry->InitializePlane(origin, normal); //Set Bounds: mitk::BoundingBox::BoundsArrayType bounds = planeGeometry->GetBounds(); bounds[0] = 0; bounds[1] = 512; bounds[2] = 0; bounds[3] = 512; bounds[4] = 0; bounds[5] = 1; planeGeometry->SetBounds(bounds); //Initialize SlicedGeometry3D: mitk::SlicedGeometry3D::Pointer slicedGeometry3D = mitk::SlicedGeometry3D::New(); slicedGeometry3D->InitializeEvenlySpaced(dynamic_cast(planeGeometry.GetPointer()), 20); mitk::Geometry3D::Pointer geometry3D = dynamic_cast< mitk::Geometry3D* > ( slicedGeometry3D.GetPointer() ); geometry3D->SetImageGeometry(true); //Define origin for second Geometry3D; mitk::Point3D origin2; origin2[0] = 511; origin2[1] = 60; origin2[2] = 0; //Define normal: mitk::Vector3D normal2; mitk::FillVector3D(normal2, 0, 1, 0); //Initialize PlaneGeometry: mitk::PlaneGeometry::Pointer planeGeometry2 = mitk::PlaneGeometry::New(); planeGeometry2->InitializePlane(origin2, normal2); //Initialize SlicedGeometry3D: mitk::SlicedGeometry3D::Pointer secondSlicedGeometry3D = mitk::SlicedGeometry3D::New(); secondSlicedGeometry3D->InitializeEvenlySpaced(dynamic_cast(planeGeometry2.GetPointer()), 20); mitk::Geometry3D::Pointer secondGeometry3D = dynamic_cast< mitk::Geometry3D* > ( secondSlicedGeometry3D.GetPointer() ); secondGeometry3D->SetImageGeometry(true); /***************************************************************/ CheckPlanesInsideBoundingBoxOnlyOnOneSlice(geometry3D); CheckPlanesOutsideOfBoundingBox(geometry3D); CheckPlanesInsideBoundingBox(geometry3D); CheckIntersectionPointsOfTwoGeometry3D(geometry3D, secondGeometry3D); CheckIntersectionWithPointCloud( geometry3D ); /** ToDo: * test also rotated 3D geometry! */ MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkEqualTest.cpp b/Core/Code/Testing/mitkEqualTest.cpp index 894496a0fe..ef6cfbeb0d 100644 --- a/Core/Code/Testing/mitkEqualTest.cpp +++ b/Core/Code/Testing/mitkEqualTest.cpp @@ -1,207 +1,207 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include -#include +#include class mitkEqualTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkEqualTestSuite); MITK_TEST(Equal_SameMitkVector3D_ReturnTrue); MITK_TEST(Equal_SameMitkVector2D_ReturnTrue); MITK_TEST(Equal_DifferentMitkVector3D_ReturnFalse); MITK_TEST(Equal_DifferentMitkVector2D_ReturnFalse); MITK_TEST(Equal_SameMitkVnlVector_ReturnTrue); MITK_TEST(Equal_DifferentMitkVnlVector_ReturnFalse); MITK_TEST(Equal_SameVnlVector_ReturnTrue); MITK_TEST(Equal_DifferentVnlVector_ReturnFalse); MITK_TEST(Equal_SameItkVector_ReturnTrue); MITK_TEST(Equal_DifferentItkVector_ReturnFalse); MITK_TEST(Equal_SameScalar_ReturnTrue); MITK_TEST(Equal_DifferentScalar_ReturnFalse); MITK_TEST(Equal_SameItkPoint_ReturnTrue); MITK_TEST(Equal_DifferentItkPoint_ReturnFalse); CPPUNIT_TEST_SUITE_END(); public: void Equal_SameMitkVector3D_ReturnTrue() { mitk::Vector3D v1; v1.Fill(1); mitk::Vector3D v2; v2.Fill(1); CPPUNIT_ASSERT(mitk::Equal(v1,v2)); } void Equal_SameMitkVector2D_ReturnTrue() { mitk::Vector2D v1; v1.Fill(2); mitk::Vector2D v2; v2.Fill(2); CPPUNIT_ASSERT(mitk::Equal(v1,v2)); } void Equal_DifferentMitkVector3D_ReturnFalse() { mitk::Vector3D v1; v1.SetElement(0, 1); v1.SetElement(1, 1); v1.SetElement(2, 1); mitk::Vector3D v2; v2.SetElement(0, 2); v2.SetElement(1, 1); v2.SetElement(2, 1); CPPUNIT_ASSERT_EQUAL_MESSAGE("Coparison of 2 different 3D MITK vectors (first element). Result should be false.", mitk::Equal(v1,v2), false); mitk::Vector3D v3; v3.SetElement(0, 1); v3.SetElement(1, 2); v3.SetElement(2, 1); CPPUNIT_ASSERT_EQUAL_MESSAGE("Coparison of 2 different 3D MITK vectors (second element). Result should be false.", mitk::Equal(v1,v3), false); mitk::Vector3D v4; v4.SetElement(0, 1); v4.SetElement(1, 1); v4.SetElement(2, 2); CPPUNIT_ASSERT_EQUAL_MESSAGE("Coparison of 2 different 3D MITK vectors (third element). Result should be false.", mitk::Equal(v1,v4), false); } void Equal_DifferentMitkVector2D_ReturnFalse() { mitk::Vector2D v1; v1.SetElement(0, 1); v1.SetElement(1, 1); mitk::Vector2D v2; v2.SetElement(0, 2); v2.SetElement(1, 1); CPPUNIT_ASSERT_EQUAL_MESSAGE("Coparison of 2 different 2D MITK vectors (first element). Result should be false.", mitk::Equal(v1,v2), false); mitk::Vector2D v3; v3.SetElement(0, 1); v3.SetElement(1, 2); CPPUNIT_ASSERT_EQUAL_MESSAGE("Coparison of 2 different 2D MITK vectors (second element). Result should be false.", mitk::Equal(v1,v3), false); } void Equal_SameMitkVnlVector_ReturnTrue() { mitk::VnlVector v1(2); v1.fill(8); mitk::VnlVector v2(2); v2.fill(8); CPPUNIT_ASSERT(mitk::Equal(v1,v2)); } void Equal_DifferentMitkVnlVector_ReturnFalse() { mitk::VnlVector v1(3); v1.fill(9.2); mitk::VnlVector v2(3); v2.fill(9.2); v2[0] = 6; CPPUNIT_ASSERT_EQUAL_MESSAGE("Comparison of 2 different MITK VNL vectors. Result should be false.", mitk::Equal(v1,v2), false); } void Equal_SameVnlVector_ReturnTrue() { vnl_vector_fixed v1; v1.fill(3.0); vnl_vector_fixed v2; v2.fill(3.0); CPPUNIT_ASSERT(mitk::Equal(v1,v2)); } void Equal_DifferentVnlVector_ReturnFalse() { vnl_vector_fixed v1; v1.fill(8.231); vnl_vector_fixed v2; v2[0] = 3.1; v2[1] = 8.231; CPPUNIT_ASSERT_EQUAL_MESSAGE("Comparison of 2 different VNL vectors (first element). Result should be false.", mitk::Equal(v1,v2), false); vnl_vector_fixed v3; v3[0] = 8.231; v3[1] = 2.14; CPPUNIT_ASSERT_EQUAL_MESSAGE("Comparison of 2 different VNL vectors (first element). Result should be false.", mitk::Equal(v1,v3), false); } void Equal_SameItkVector_ReturnTrue() { itk::Vector v1; v1.Fill(1.32); itk::Vector v2; v2.Fill(1.32); mitk::Equal(v1, v2); CPPUNIT_ASSERT(mitk::Equal(v1,v2)); } void Equal_DifferentItkVector_ReturnFalse() { itk::Vector v1; v1.Fill(5.2); itk::Vector v2; v2.Fill(5.2); v2.SetElement(0, 1.4); CPPUNIT_ASSERT_EQUAL_MESSAGE("Coparison of 2 different ITK vectors (first element). Result should be false.", mitk::Equal(v1,v2), false); itk::Vector v3; v3.Fill(5.2); v3.SetElement(1, 1.4); CPPUNIT_ASSERT_EQUAL_MESSAGE("Coparison of 2 different ITK vectors (second element). Result should be false.", mitk::Equal(v1,v3), false); itk::Vector v4; v4.Fill(5.2); v4.SetElement(2, 1.4); CPPUNIT_ASSERT_EQUAL_MESSAGE("Coparison of 2 different ITK vectors (third element). Result should be false.", mitk::Equal(v1,v4), false); } void Equal_SameScalar_ReturnTrue() { mitk::ScalarType a = 6.432; mitk::ScalarType b = 6.432; CPPUNIT_ASSERT(mitk::Equal(a,b)); } void Equal_DifferentScalar_ReturnFalse() { mitk::ScalarType a = 0.6; mitk::ScalarType b = 0.6 + 1.01*mitk::eps; CPPUNIT_ASSERT_EQUAL_MESSAGE("Comparison of 2 different scalars. Result should be false", mitk::Equal(a,b), false); } void Equal_SameItkPoint_ReturnTrue() { itk::Point p1; p1.Fill(3.21); itk::Point p2; p2.Fill(3.21); CPPUNIT_ASSERT(mitk::Equal(p1,p2)); } void Equal_DifferentItkPoint_ReturnFalse() { itk::Point p1; p1.Fill(2.1); itk::Point p2; p2[0] = 1; p2[1] = 2.1; CPPUNIT_ASSERT_EQUAL_MESSAGE("Comparison of 2 different points (first element). Result should be false.", mitk::Equal(p1,p2), false); itk::Point p3; p3[0] = 2.1; p3[1] = 2.1 + 1.01*mitk::eps; CPPUNIT_ASSERT_EQUAL_MESSAGE("Comparison of 2 different points (second element). Result should be false.", mitk::Equal(p1,p3), false); } }; MITK_TEST_SUITE_REGISTRATION(mitkEqual) diff --git a/Core/Code/Testing/mitkExtractSliceFilterTest.cpp b/Core/Code/Testing/mitkExtractSliceFilterTest.cpp index 5997c821f3..7a70c208dc 100644 --- a/Core/Code/Testing/mitkExtractSliceFilterTest.cpp +++ b/Core/Code/Testing/mitkExtractSliceFilterTest.cpp @@ -1,1169 +1,1169 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include #include #include #include #include #include #include #include #include -#include +#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //use this to create the test volume on the fly #define CREATE_VOLUME //use this to save the created volume //#define SAVE_VOLUME //use this to calculate the error from the sphere mathematical model to our pixel based one //#define CALC_TESTFAILURE_DEVIATION //use this to render an oblique slice through a specified image //#define SHOW_SLICE_IN_RENDER_WINDOW //use this to have infos printed in mbilog //#define EXTRACTOR_DEBUG /*these are the deviations calculated by the function CalcTestFailureDeviation (see for details)*/ #define Testfailure_Deviation_Mean_128 0.853842 #define Testfailure_Deviation_Volume_128 0.145184 #define Testfailure_Deviation_Diameter_128 1.5625 #define Testfailure_Deviation_Mean_256 0.397693 #define Testfailure_Deviation_Volume_256 0.0141357 #define Testfailure_Deviation_Diameter_256 0.78125 #define Testfailure_Deviation_Mean_512 0.205277 #define Testfailure_Deviation_Volume_512 0.01993 #define Testfailure_Deviation_Diameter_512 0.390625 class mitkExtractSliceFilterTestClass{ public: static void TestSlice(mitk::PlaneGeometry* planeGeometry, std::string testname) { TestPlane = planeGeometry; TestName = testname; mitk::ScalarType centerCoordValue = TestvolumeSize / 2.0; mitk::ScalarType center[3] = {centerCoordValue, centerCoordValue, centerCoordValue}; mitk::Point3D centerIndex(center); double radius = TestvolumeSize / 4.0; if(TestPlane->Distance(centerIndex) >= radius ) return;//outside sphere //feed ExtractSliceFilter mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New(); slicer->SetInput(TestVolume); slicer->SetWorldGeometry(TestPlane); slicer->Update(); MITK_TEST_CONDITION_REQUIRED(slicer->GetOutput() != NULL, "Extractor returned a slice"); mitk::Image::Pointer reslicedImage = slicer->GetOutput(); AccessFixedDimensionByItk(reslicedImage, TestSphereRadiusByItk, 2); AccessFixedDimensionByItk(reslicedImage, TestSphereAreaByItk, 2); /* double devArea, devDiameter; if(TestvolumeSize == 128.0){ devArea = Testfailure_Deviation_Volume_128; devDiameter = Testfailure_Deviation_Diameter_128; } else if(TestvolumeSize == 256.0){devArea = Testfailure_Deviation_Volume_256; devDiameter = Testfailure_Deviation_Diameter_256;} else if (TestvolumeSize == 512.0){devArea = Testfailure_Deviation_Volume_512; devDiameter = Testfailure_Deviation_Diameter_512;} else{devArea = Testfailure_Deviation_Volume_128; devDiameter = Testfailure_Deviation_Diameter_128;} */ std::string areatestName = TestName.append(" area"); std::string diametertestName = TestName.append(" testing diameter"); //TODO think about the deviation, 1% makes no sense at all MITK_TEST_CONDITION(std::abs(100 - testResults.percentageAreaCalcToPixel) < 1, areatestName ); MITK_TEST_CONDITION(std::abs(100 - testResults.percentageRadiusToPixel) < 1, diametertestName ); #ifdef EXTRACTOR_DEBUG MITK_INFO << TestName << " >>> " << "planeDistanceToSphereCenter: " << testResults.planeDistanceToSphereCenter; MITK_INFO << "area in pixels: " << testResults.areaInPixel << " <-> area in mm: " << testResults.areaCalculated << " = " << testResults.percentageAreaCalcToPixel << "%"; MITK_INFO << "calculated diameter: " << testResults.diameterCalculated << " <-> diameter in mm: " << testResults.diameterInMM << " <-> diameter in pixel: " << testResults.diameterInPixel << " = " << testResults.percentageRadiusToPixel << "%"; #endif } /* * get the radius of the slice of a sphere based on pixel distance from edge to edge of the circle. */ template static void TestSphereRadiusByItk (itk::Image* inputImage) { typedef itk::Image InputImageType; //set the index to the middle of the image's edge at x and y axis typename InputImageType::IndexType currentIndexX; currentIndexX[0] = (int)(TestvolumeSize / 2.0); currentIndexX[1] = 0; typename InputImageType::IndexType currentIndexY; currentIndexY[0] = 0; currentIndexY[1] = (int)(TestvolumeSize / 2.0); //remember the last pixel value double lastValueX = inputImage->GetPixel(currentIndexX); double lastValueY = inputImage->GetPixel(currentIndexY); //storage for the index marks std::vector indicesX; std::vector indicesY; /*Get four indices on the edge of the circle*/ while(currentIndexX[1] < TestvolumeSize && currentIndexX[0] < TestvolumeSize) { //move x direction currentIndexX[1] += 1; //move y direction currentIndexY[0] += 1; if(inputImage->GetPixel(currentIndexX) > lastValueX) { //mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexX[0]; markIndex[1] = currentIndexX[1]; indicesX.push_back(markIndex); } else if( inputImage->GetPixel(currentIndexX) < lastValueX) { //mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexX[0]; markIndex[1] = currentIndexX[1] - 1;//value inside the sphere indicesX.push_back(markIndex); } if(inputImage->GetPixel(currentIndexY) > lastValueY) { //mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexY[0]; markIndex[1] = currentIndexY[1]; indicesY.push_back(markIndex); } else if( inputImage->GetPixel(currentIndexY) < lastValueY) { //mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexY[0]; markIndex[1] = currentIndexY[1] - 1;//value inside the sphere indicesY.push_back(markIndex); } //found both marks? if(indicesX.size() == 2 && indicesY.size() == 2) break; //the new 'last' values lastValueX = inputImage->GetPixel(currentIndexX); lastValueY = inputImage->GetPixel(currentIndexY); } /* *If we are here we found the four marks on the edge of the circle. *For the case our plane is rotated and shifted, we have to calculate the center of the circle, *else the center is the intersection of both straight lines between the marks. *When we have the center, the diameter of the circle will be checked to the reference value(math!). */ //each distance from the first mark of each direction to the center of the straight line between the marks double distanceToCenterX = std::abs(indicesX[0][1] - indicesX[1][1]) / 2.0; //double distanceToCenterY = std::abs(indicesY[0][0] - indicesY[1][0]) / 2.0; //the center of the straight lines typename InputImageType::IndexType centerX; //typename InputImageType::IndexType centerY; centerX[0] = indicesX[0][0]; centerX[1] = indicesX[0][1] + distanceToCenterX; //TODO think about implicit cast to int. this is not the real center of the image, which could be between two pixels //centerY[0] = indicesY[0][0] + distanceToCenterY; //centerY[1] = inidcesY[0][1]; typename InputImageType::IndexType currentIndex(centerX); lastValueX = inputImage->GetPixel(currentIndex); long sumpixels = 0; std::vector diameterIndices; //move up while(currentIndex[1] < TestvolumeSize) { currentIndex[1] += 1; if( inputImage->GetPixel(currentIndex) != lastValueX) { typename InputImageType::IndexType markIndex; markIndex[0] = currentIndex[0]; markIndex[1] = currentIndex[1] - 1; diameterIndices.push_back(markIndex); break; } sumpixels++; lastValueX = inputImage->GetPixel(currentIndex); } currentIndex[1] -= sumpixels; //move back to center to go in the other direction lastValueX = inputImage->GetPixel(currentIndex); //move down while(currentIndex[1] >= 0) { currentIndex[1] -= 1; if( inputImage->GetPixel(currentIndex) != lastValueX) { typename InputImageType::IndexType markIndex; markIndex[0] = currentIndex[0]; markIndex[1] = currentIndex[1];//outside sphere because we want to calculate the distance from edge to edge diameterIndices.push_back(markIndex); break; } sumpixels++; lastValueX = inputImage->GetPixel(currentIndex); } /* *Now sumpixels should be the apromximate diameter of the circle. This is checked with the calculated diameter from the plane transformation(math). */ mitk::Point3D volumeCenter; volumeCenter[0] = volumeCenter[1] = volumeCenter[2] = TestvolumeSize / 2.0; double planeDistanceToSphereCenter = TestPlane->Distance(volumeCenter); double sphereRadius = TestvolumeSize/4.0; //calculate the radius of the circle cut from the sphere by the plane double diameter = 2.0 * std::sqrt(std::pow(sphereRadius, 2) - std::pow( planeDistanceToSphereCenter , 2)); double percentageRadiusToPixel = 100 / diameter * sumpixels; /* *calculate the radius in mm by the both marks of the center line by using the world coordinates */ //get the points as 3D coordinates mitk::Vector3D diameterPointRight, diameterPointLeft; diameterPointRight[2] = diameterPointLeft[2] = 0.0; diameterPointLeft[0] = diameterIndices[0][0]; diameterPointLeft[1] = diameterIndices[0][1]; diameterPointRight[0] = diameterIndices[1][0]; diameterPointRight[1] = diameterIndices[1][1]; //transform to worldcoordinates TestVolume->GetGeometry()->IndexToWorld(diameterPointLeft, diameterPointLeft); TestVolume->GetGeometry()->IndexToWorld(diameterPointRight, diameterPointRight); //euklidian distance double diameterInMM = ( (diameterPointLeft * -1.0) + diameterPointRight).GetNorm(); testResults.diameterInMM = diameterInMM; testResults.diameterCalculated = diameter; testResults.diameterInPixel = sumpixels; testResults.percentageRadiusToPixel = percentageRadiusToPixel; testResults.planeDistanceToSphereCenter = planeDistanceToSphereCenter; } /*brute force the area pixel by pixel*/ template static void TestSphereAreaByItk (itk::Image* inputImage) { typedef itk::Image InputImageType; typedef itk::ImageRegionConstIterator< InputImageType > ImageIterator; ImageIterator imageIterator( inputImage, inputImage->GetLargestPossibleRegion() ); imageIterator.GoToBegin(); int sumPixelsInArea = 0; while( !imageIterator.IsAtEnd() ) { if(inputImage->GetPixel(imageIterator.GetIndex()) == pixelValueSet) sumPixelsInArea++; ++imageIterator; } mitk::Point3D volumeCenter; volumeCenter[0] = volumeCenter[1] = volumeCenter[2] = TestvolumeSize / 2.0; double planeDistanceToSphereCenter = TestPlane->Distance(volumeCenter); double sphereRadius = TestvolumeSize/4.0; //calculate the radius of the circle cut from the sphere by the plane double radius = std::sqrt(std::pow(sphereRadius, 2) - std::pow( planeDistanceToSphereCenter , 2)); double areaInMM = 3.14159265358979 * std::pow(radius, 2); testResults.areaCalculated = areaInMM; testResults.areaInPixel = sumPixelsInArea; testResults.percentageAreaCalcToPixel = 100 / areaInMM * sumPixelsInArea; } /* * random a voxel. define plane through this voxel. reslice at the plane. compare the pixel vaues of the voxel * in the volume with the pixel value in the resliced image. * there are some indice shifting problems which causes the test to fail for oblique planes. seems like the chosen * worldcoordinate is not corrresponding to the index in the 2D image. and so the pixel values are not the same as * expected. */ static void PixelvalueBasedTest() { /* setup itk image */ typedef itk::Image ImageType; typedef itk::ImageRegionConstIterator< ImageType > ImageIterator; ImageType::Pointer image = ImageType::New(); ImageType::IndexType start; start[0] = start[1] = start[2] = 0; ImageType::SizeType size; size[0] = size[1] = size[2] = 32; ImageType::RegionType imgRegion; imgRegion.SetSize(size); imgRegion.SetIndex(start); image->SetRegions(imgRegion); image->SetSpacing(1.0); image->Allocate(); ImageIterator imageIterator( image, image->GetLargestPossibleRegion() ); imageIterator.GoToBegin(); unsigned short pixelValue = 0; //fill the image with distinct values while ( !imageIterator.IsAtEnd() ) { image->SetPixel(imageIterator.GetIndex(), pixelValue); ++imageIterator; ++pixelValue; } /* end setup itk image */ mitk::Image::Pointer imageInMitk; CastToMitkImage(image, imageInMitk); /*mitk::ImageWriter::Pointer writer = mitk::ImageWriter::New(); writer->SetInput(imageInMitk); std::string file = "C:\\Users\\schroedt\\Desktop\\cube.nrrd"; writer->SetFileName(file); writer->Update();*/ PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Frontal); PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Sagittal); PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Axial); } static void PixelvalueBasedTestByPlane(mitk::Image* imageInMitk, mitk::PlaneGeometry::PlaneOrientation orientation){ typedef itk::Image ImageType; //set the seed of the rand function srand((unsigned)time(0)); /* setup a random orthogonal plane */ int sliceindex = 17;//rand() % 32; bool isFrontside = true; bool isRotated = false; if( orientation == mitk::PlaneGeometry::Axial) { /*isFrontside = false; isRotated = true;*/ } mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); plane->InitializeStandardPlane(imageInMitk->GetGeometry(), orientation, sliceindex, isFrontside, isRotated); mitk::Point3D origin = plane->GetOrigin(); mitk::Vector3D normal; normal = plane->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 plane->SetOrigin(origin); //we dont need this any more, because we are only testing orthogonal planes /*mitk::Vector3D rotationVector; rotationVector[0] = randFloat(); rotationVector[1] = randFloat(); rotationVector[2] = randFloat(); float degree = randFloat() * 180.0; mitk::RotationOperation* op = new mitk::RotationOperation(mitk::OpROTATE, plane->GetCenter(), rotationVector, degree); plane->ExecuteOperation(op); delete op;*/ /* end setup plane */ /* define a point in the 3D volume. * add the two axis vectors of the plane (each multiplied with a * random number) to the origin. now the two random numbers * become our index coordinates in the 2D image, because the * length of the axis vectors is 1. */ mitk::Point3D planeOrigin = plane->GetOrigin(); mitk::Vector3D axis0, axis1; axis0 = plane->GetAxisVector(0); axis1 = plane->GetAxisVector(1); axis0.Normalize(); axis1.Normalize(); unsigned char n1 = 7;// rand() % 32; unsigned char n2 = 13;// rand() % 32; mitk::Point3D testPoint3DInWorld; testPoint3DInWorld = planeOrigin + (axis0 * n1) + (axis1 * n2); //get the index of the point in the 3D volume ImageType::IndexType testPoint3DInIndex; imageInMitk->GetGeometry()->WorldToIndex(testPoint3DInWorld, testPoint3DInIndex); itk::Index<3> testPoint2DInIndex; /* end define a point in the 3D volume.*/ //do reslicing at the plane mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New(); slicer->SetInput(imageInMitk); slicer->SetWorldGeometry(plane); slicer->Update(); mitk::Image::Pointer slice = slicer->GetOutput(); // Get TestPoiont3D as Index in Slice slice->GetGeometry()->WorldToIndex(testPoint3DInWorld,testPoint2DInIndex); mitk::Point3D p, sliceIndexToWorld, imageIndexToWorld; p[0] = testPoint2DInIndex[0]; p[1] = testPoint2DInIndex[1]; p[2] = testPoint2DInIndex[2]; slice->GetGeometry()->IndexToWorld(p, sliceIndexToWorld); p[0] = testPoint3DInIndex[0]; p[1] = testPoint3DInIndex[1]; p[2] = testPoint3DInIndex[2]; imageInMitk->GetGeometry()->IndexToWorld(p, imageIndexToWorld); itk::Index<2> testPoint2DIn2DIndex; testPoint2DIn2DIndex[0] = testPoint2DInIndex[0]; testPoint2DIn2DIndex[1] = testPoint2DInIndex[1]; typedef mitk::ImagePixelReadAccessor< unsigned short, 3 > VolumeReadAccessorType; typedef mitk::ImagePixelReadAccessor< unsigned short, 2 > SliceReadAccessorType; VolumeReadAccessorType VolumeReadAccessor( imageInMitk ); SliceReadAccessorType SliceReadAccessor( slice ); //compare the pixelvalues of the defined point in the 3D volume with the value of the resliced image unsigned short valueAt3DVolume = VolumeReadAccessor.GetPixelByIndex( testPoint3DInIndex ); unsigned short valueAtSlice = SliceReadAccessor.GetPixelByIndex( testPoint2DIn2DIndex ); //valueAt3DVolume == valueAtSlice is not always working. because of rounding errors //indices are shifted MITK_TEST_CONDITION(valueAt3DVolume == valueAtSlice, "comparing pixelvalues for orthogonal plane"); vtkSmartPointer imageInVtk = vtkSmartPointer::New(); imageInVtk = imageInMitk->GetVtkImageData(); vtkSmartPointer sliceInVtk = vtkSmartPointer::New(); sliceInVtk = slice->GetVtkImageData(); double PixelvalueByMitkOutput = sliceInVtk->GetScalarComponentAsDouble(n1, n2, 0, 0); //double valueVTKinImage = imageInVtk->GetScalarComponentAsDouble(testPoint3DInIndex[0], testPoint3DInIndex[1], testPoint3DInIndex[2], 0); /* Test that everything is working equally if vtkoutput is used instead of the default output * from mitk ImageToImageFilter */ mitk::ExtractSliceFilter::Pointer slicerWithVtkOutput = mitk::ExtractSliceFilter::New(); slicerWithVtkOutput->SetInput(imageInMitk); slicerWithVtkOutput->SetWorldGeometry(plane); slicerWithVtkOutput->SetVtkOutputRequest(true); slicerWithVtkOutput->Update(); vtkSmartPointer vtkImageByVtkOutput = vtkSmartPointer::New(); vtkImageByVtkOutput = slicerWithVtkOutput->GetVtkOutput(); double PixelvalueByVtkOutput = vtkImageByVtkOutput->GetScalarComponentAsDouble(n1, n2, 0, 0); MITK_TEST_CONDITION(PixelvalueByMitkOutput == PixelvalueByVtkOutput, "testing convertion of image output vtk->mitk by reslicer"); /*================ mbilog outputs ===========================*/ #ifdef EXTRACTOR_DEBUG MITK_INFO << "\n" << "TESTINFO index: " << sliceindex << " orientation: " << orientation << " frontside: " << isFrontside << " rotated: " << isRotated; MITK_INFO << "\n" << "slice index to world: " << sliceIndexToWorld; MITK_INFO << "\n" << "image index to world: " << imageIndexToWorld; MITK_INFO << "\n" << "vtk: slice: " << PixelvalueByMitkOutput << ", image: "<< valueVTKinImage; MITK_INFO << "\n" << "testPoint3D InWorld" << testPoint3DInWorld << " is " << testPoint2DInIndex << " in 2D"; MITK_INFO << "\n" << "randoms: " << ((int)n1) << ", " << ((int)n2); MITK_INFO << "\n" << "point is inside plane: " << plane->IsInside(testPoint3DInWorld) << " and volume: " << imageInMitk->GetGeometry()->IsInside(testPoint3DInWorld); MITK_INFO << "\n" << "volume idx: " << testPoint3DInIndex << " = " << valueAt3DVolume ; MITK_INFO << "\n" << "volume world: " << testPoint3DInWorld << " = " << valueAt3DVolumeByWorld ; MITK_INFO << "\n" << "slice idx: " << testPoint2DInIndex << " = " << valueAtSlice ; itk::Index<3> curr; curr[0] = curr[1] = curr[2] = 0; for( int i = 0; i < 32 ; ++i){ for( int j = 0; j < 32; ++j){ ++curr[1]; if(SliceReadAccessor.GetPixelByIndex( curr ) == valueAt3DVolume){ MITK_INFO << "\n" << valueAt3DVolume << " MATCHED mitk " << curr; } } curr[1] = 0; ++curr[0]; } typedef itk::Image Image2DType; Image2DType::Pointer img = Image2DType::New(); CastToItkImage(slice, img); typedef itk::ImageRegionConstIterator< Image2DType > Iterator2D; Iterator2D iter(img, img->GetLargestPossibleRegion()); iter.GoToBegin(); while( !iter.IsAtEnd() ){ if(img->GetPixel(iter.GetIndex()) == valueAt3DVolume) MITK_INFO << "\n" << valueAt3DVolume << " MATCHED itk " << iter.GetIndex(); ++iter; } #endif //EXTRACTOR_DEBUG } /* random a float value */ static float randFloat(){ return (((float)rand()+1.0) / ((float)RAND_MAX + 1.0)) + (((float)rand()+1.0) / ((float)RAND_MAX + 1.0)) / ((float)RAND_MAX + 1.0);} /* create a sphere with the size of the given testVolumeSize*/ static void InitializeTestVolume() { #ifdef CREATE_VOLUME //do sphere creation ItkVolumeGeneration(); #ifdef SAVE_VOLUME //save in file mitk::ImageWriter::Pointer writer = mitk::ImageWriter::New(); writer->SetInput(TestVolume); std::string file; std::ostringstream filename; filename << "C:\\home\\schroedt\\MITK\\Modules\\ImageExtraction\\Testing\\Data\\sphere_"; filename << TestvolumeSize; filename << ".nrrd"; file = filename.str(); writer->SetFileName(file); writer->Update(); #endif//SAVE_VOLUME #endif #ifndef CREATE_VOLUME //read from file mitk::StandardFileLocations::Pointer locator = mitk::StandardFileLocations::GetInstance(); std::string filename = locator->FindFile("sphere_512.nrrd.mhd", "Modules/ImageExtraction/Testing/Data"); mitk::ItkImageFileReader::Pointer reader = mitk::ItkImageFileReader::New(); reader->SetFileName(filename); reader->Update(); TestVolume = reader->GetOutput(); #endif #ifdef CALC_TESTFAILURE_DEVIATION //get the TestFailureDeviation in % AccessFixedDimensionByItk(TestVolume, CalcTestFailureDeviation, 3); #endif } //the test result of the sphere reslice struct SliceProperties{ double planeDistanceToSphereCenter; double diameterInMM; double diameterInPixel; double diameterCalculated; double percentageRadiusToPixel; double areaCalculated; double areaInPixel; double percentageAreaCalcToPixel; }; static mitk::Image::Pointer TestVolume; static double TestvolumeSize; static mitk::PlaneGeometry::Pointer TestPlane; static std::string TestName; static unsigned char pixelValueSet; static SliceProperties testResults; static double TestFailureDeviation; private: /* * Generate a sphere with a radius of TestvolumeSize / 4.0 */ static void ItkVolumeGeneration () { typedef itk::Image TestVolumeType; typedef itk::ImageRegionConstIterator< TestVolumeType > ImageIterator; TestVolumeType::Pointer sphereImage = TestVolumeType::New(); TestVolumeType::IndexType start; start[0] = start[1] = start[2] = 0; TestVolumeType::SizeType size; size[0] = size[1] = size[2] = TestvolumeSize; TestVolumeType::RegionType imgRegion; imgRegion.SetSize(size); imgRegion.SetIndex(start); sphereImage->SetRegions(imgRegion); sphereImage->SetSpacing(1.0); sphereImage->Allocate(); sphereImage->FillBuffer(0); mitk::Vector3D center; center[0] = center[1] = center[2] = TestvolumeSize / 2.0; double radius = TestvolumeSize / 4.0; double pixelValue = pixelValueSet; double distanceToCenter = 0.0; ImageIterator imageIterator( sphereImage, sphereImage->GetLargestPossibleRegion() ); imageIterator.GoToBegin(); mitk::Vector3D currentVoxelInIndex; while ( !imageIterator.IsAtEnd() ) { currentVoxelInIndex[0] = imageIterator.GetIndex()[0]; currentVoxelInIndex[1] = imageIterator.GetIndex()[1]; currentVoxelInIndex[2] = imageIterator.GetIndex()[2]; distanceToCenter = (center + ( currentVoxelInIndex * -1.0 )).GetNorm(); //if distance to center is smaller then the radius of the sphere if( distanceToCenter < radius) { sphereImage->SetPixel(imageIterator.GetIndex(), pixelValue); } ++imageIterator; } CastToMitkImage(sphereImage, TestVolume); } /* calculate the devation of the voxel object to the mathematical sphere object. * this is use to make a statement about the accuracy of the resliced image, eg. the circle's diameter or area. */ template static void CalcTestFailureDeviation (itk::Image* inputImage) { typedef itk::Image InputImageType; typedef itk::ImageRegionConstIterator< InputImageType > ImageIterator; ImageIterator iterator(inputImage, inputImage->GetLargestPossibleRegion()); iterator.GoToBegin(); int volumeInPixel = 0; while( !iterator.IsAtEnd() ) { if(inputImage->GetPixel(iterator.GetIndex()) == pixelValueSet) volumeInPixel++; ++iterator; } double diameter = TestvolumeSize / 2.0; double volumeCalculated = (1.0 / 6.0) * 3.14159265358979 * std::pow(diameter, 3); double volumeDeviation = std::abs( 100 - (100 / volumeCalculated * volumeInPixel) ); typename InputImageType::IndexType index; index[0] = index[1] = TestvolumeSize / 2.0; index[2] = 0; int sumpixels = 0; while (index[2] < TestvolumeSize ) { if(inputImage->GetPixel(index) == pixelValueSet) sumpixels++; index[2] += 1; } double diameterDeviation = std::abs( 100 - (100 / diameter * sumpixels) ); #ifdef DEBUG MITK_INFO << "volume deviation: " << volumeDeviation << " diameter deviation:" << diameterDeviation; #endif mitkExtractSliceFilterTestClass::TestFailureDeviation = (volumeDeviation + diameterDeviation) / 2.0; } }; /*================ #END class ================*/ /*================#BEGIN Instanciation of members ================*/ mitk::Image::Pointer mitkExtractSliceFilterTestClass::TestVolume = mitk::Image::New(); double mitkExtractSliceFilterTestClass::TestvolumeSize = 256.0; mitk::PlaneGeometry::Pointer mitkExtractSliceFilterTestClass::TestPlane = mitk::PlaneGeometry::New(); std::string mitkExtractSliceFilterTestClass::TestName = ""; unsigned char mitkExtractSliceFilterTestClass::pixelValueSet = 255; mitkExtractSliceFilterTestClass::SliceProperties mitkExtractSliceFilterTestClass::testResults = {-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}; double mitkExtractSliceFilterTestClass::TestFailureDeviation = 0.0; /*================ #END Instanciation of members ================*/ /*================ #BEGIN test main ================*/ int mitkExtractSliceFilterTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkExtractSliceFilterTest") //pixelvalue based testing mitkExtractSliceFilterTestClass::PixelvalueBasedTest(); //initialize sphere test volume mitkExtractSliceFilterTestClass::InitializeTestVolume(); mitk::Vector3D spacing = mitkExtractSliceFilterTestClass::TestVolume->GetGeometry()->GetSpacing(); //the center of the sphere = center of image double sphereCenter = mitkExtractSliceFilterTestClass::TestvolumeSize / 2.0; double planeSize = mitkExtractSliceFilterTestClass::TestvolumeSize; /* axial plane */ mitk::PlaneGeometry::Pointer geometryAxial = mitk::PlaneGeometry::New(); geometryAxial->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Axial, sphereCenter, false, true); geometryAxial->ChangeImageGeometryConsideringOriginOffset(true); mitk::Point3D origin = geometryAxial->GetOrigin(); mitk::Vector3D normal; normal = geometryAxial->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //geometryAxial->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometryAxial, "Testing axial plane"); /* end axial plane */ /* sagittal plane */ mitk::PlaneGeometry::Pointer geometrySagital = mitk::PlaneGeometry::New(); geometrySagital->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Sagittal, sphereCenter, true, false); geometrySagital->ChangeImageGeometryConsideringOriginOffset(true); origin = geometrySagital->GetOrigin(); normal = geometrySagital->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //geometrySagital->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometrySagital, "Testing sagittal plane"); /* sagittal plane */ /* sagittal shifted plane */ mitk::PlaneGeometry::Pointer geometrySagitalShifted = mitk::PlaneGeometry::New(); geometrySagitalShifted->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Sagittal, (sphereCenter - 14), true, false); geometrySagitalShifted->ChangeImageGeometryConsideringOriginOffset(true); origin = geometrySagitalShifted->GetOrigin(); normal = geometrySagitalShifted->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //geometrySagitalShifted->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometrySagitalShifted, "Testing sagittal plane shifted"); /* end sagittal shifted plane */ /* coronal plane */ mitk::PlaneGeometry::Pointer geometryCoronal = mitk::PlaneGeometry::New(); geometryCoronal->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Frontal, sphereCenter, true, false); geometryCoronal->ChangeImageGeometryConsideringOriginOffset(true); origin = geometryCoronal->GetOrigin(); normal = geometryCoronal->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //geometryCoronal->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometryCoronal, "Testing coronal plane"); /* end coronal plane */ /* oblique plane */ mitk::PlaneGeometry::Pointer obliquePlane = mitk::PlaneGeometry::New(); obliquePlane->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Sagittal, sphereCenter, true, false); obliquePlane->ChangeImageGeometryConsideringOriginOffset(true); origin = obliquePlane->GetOrigin(); normal = obliquePlane->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //obliquePlane->SetOrigin(origin); mitk::Vector3D rotationVector; rotationVector[0] = 0.2; rotationVector[1] = 0.4; rotationVector[2] = 0.62; float degree = 37.0; mitk::RotationOperation* op = new mitk::RotationOperation(mitk::OpROTATE, obliquePlane->GetCenter(), rotationVector, degree); obliquePlane->ExecuteOperation(op); delete op; mitkExtractSliceFilterTestClass::TestSlice(obliquePlane, "Testing oblique plane"); /* end oblique plane */ #ifdef SHOW_SLICE_IN_RENDER_WINDOW /*================ #BEGIN vtk render code ================*/ //set reslicer for renderwindow mitk::ItkImageFileReader::Pointer reader = mitk::ItkImageFileReader::New(); std::string filename = "C:\\home\\Pics\\Pic3D.nrrd"; reader->SetFileName(filename); reader->Update(); mitk::Image::Pointer pic = reader->GetOutput(); vtkSmartPointer slicer = vtkSmartPointer::New(); slicer->SetInput(pic->GetVtkImageData()); mitk::PlaneGeometry::Pointer obliquePl = mitk::PlaneGeometry::New(); obliquePl->InitializeStandardPlane(pic->GetGeometry(), mitk::PlaneGeometry::Sagittal, pic->GetGeometry()->GetCenter()[0], true, false); obliquePl->ChangeImageGeometryConsideringOriginOffset(true); mitk::Point3D origin2 = obliquePl->GetOrigin(); mitk::Vector3D n; n = obliquePl->GetNormal(); n.Normalize(); origin2 += n * 0.5;//pixelspacing is 1, so half the spacing is 0.5 obliquePl->SetOrigin(origin2); mitk::Vector3D rotation; rotation[0] = 0.534307; rotation[1] = 0.000439605; rotation[2] = 0.423017; MITK_INFO << rotation; float rotateDegree = 70; mitk::RotationOperation* operation = new mitk::RotationOperation(mitk::OpROTATE, obliquePl->GetCenter(), rotationVector, degree); obliquePl->ExecuteOperation(operation); delete operation; double origin[3]; origin[0] = obliquePl->GetOrigin()[0]; origin[1] = obliquePl->GetOrigin()[1]; origin[2] = obliquePl->GetOrigin()[2]; slicer->SetResliceAxesOrigin(origin); mitk::Vector3D right, bottom, normal; right = obliquePl->GetAxisVector( 0 ); bottom = obliquePl->GetAxisVector( 1 ); normal = obliquePl->GetNormal(); right.Normalize(); bottom.Normalize(); normal.Normalize(); double cosines[9]; mitk::vnl2vtk(right.GetVnlVector(), cosines);//x mitk::vnl2vtk(bottom.GetVnlVector(), cosines + 3);//y mitk::vnl2vtk(normal.GetVnlVector(), cosines + 6);//n slicer->SetResliceAxesDirectionCosines(cosines); slicer->SetOutputDimensionality(2); slicer->Update(); //set vtk renderwindow vtkSmartPointer vtkPlane = vtkSmartPointer::New(); vtkPlane->SetOrigin(0.0, 0.0, 0.0); //These two points define the axes of the plane in combination with the origin. //Point 1 is the x-axis and point 2 the y-axis. //Each plane is transformed according to the view (axial, coronal and saggital) afterwards. vtkPlane->SetPoint1(1.0, 0.0, 0.0); //P1: (xMax, yMin, depth) vtkPlane->SetPoint2(0.0, 1.0, 0.0); //P2: (xMin, yMax, depth) //these are not the correct values for all slices, only a square plane by now vtkSmartPointer imageMapper = vtkSmartPointer::New(); imageMapper->SetInputConnection(vtkPlane->GetOutputPort()); vtkSmartPointer lookupTable = vtkSmartPointer::New(); //built a default lookuptable lookupTable->SetRampToLinear(); lookupTable->SetSaturationRange( 0.0, 0.0 ); lookupTable->SetHueRange( 0.0, 0.0 ); lookupTable->SetValueRange( 0.0, 1.0 ); lookupTable->Build(); //map all black values to transparent lookupTable->SetTableValue(0, 0.0, 0.0, 0.0, 0.0); lookupTable->SetRange(-255.0, 255.0); //lookupTable->SetRange(-1022.0, 1184.0);//pic3D range vtkSmartPointer texture = vtkSmartPointer::New(); texture->SetInput(slicer->GetOutput()); texture->SetLookupTable(lookupTable); texture->SetMapColorScalarsThroughLookupTable(true); vtkSmartPointer imageActor = vtkSmartPointer::New(); imageActor->SetMapper(imageMapper); imageActor->SetTexture(texture); // Setup renderers vtkSmartPointer renderer = vtkSmartPointer::New(); renderer->AddActor(imageActor); // 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); renderWindow->Render(); renderWindowInteractor->Start(); // always end with this! /*================ #END vtk render code ================*/ #endif //SHOW_SLICE_IN_RENDER_WINDOW MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkGenericPropertyTest.cpp b/Core/Code/Testing/mitkGenericPropertyTest.cpp index c63ae51a40..0897dd81a0 100644 --- a/Core/Code/Testing/mitkGenericPropertyTest.cpp +++ b/Core/Code/Testing/mitkGenericPropertyTest.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 "mitkTestingMacros.h" #include "mitkGenericProperty.h" #include "mitkStringProperty.h" #include "mitkProperties.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include #include // call with testValue1 != testValue2 template int TestGenericPropertyForDataType(typename T::ValueType testValue1, typename T::ValueType testValue2, std::string testValue1AsString, std::string testValue2AsString, std::string type) { std::cout << "Testing mitk::GenericProperty<" << type << ">(" << testValue1AsString << ", " << testValue2AsString << ") \n"; typename T::Pointer prop(T::New()); typename T::Pointer prop2(T::New(testValue1)); typename T::Pointer prop3(T::New(testValue2)); unsigned long tBefore = prop->GetMTime(); prop->SetValue(testValue1); unsigned long tAfter = prop->GetMTime(); prop->SetValue(testValue1); unsigned long tAfterAll = prop->GetMTime(); MITK_TEST_CONDITION_REQUIRED(prop->GetValue() == testValue1 && prop->GetValueAsString() == testValue1AsString,"Testing SetValue") MITK_TEST_CONDITION_REQUIRED((*prop == *prop2),"Testing equality operator (operator==)"); prop->SetValue(testValue2); unsigned long tAfterEverything = prop->GetMTime(); std::cout << " Testing MTime correctness when changing property value: "; if (tBefore >= tAfter || tAfterAll != tAfter || tAfterEverything <= tAfterAll) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; prop->SetValue(testValue1); std::cout << " Testing Assignment: "; prop->AssignProperty(*prop3); if ( (! (*prop == *prop3)) || (*prop == *prop2) ) { std::cout << " [FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << std::endl; return EXIT_SUCCESS; } int mitkGenericPropertyTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN(GenericPropertyTest) // testing for some different data types TestGenericPropertyForDataType(1, 2, "1", "2", "int"); TestGenericPropertyForDataType(true, false, "1", "0", "bool"); TestGenericPropertyForDataType(1.0, -1.0, "1", "-1", "float"); TestGenericPropertyForDataType(1.0, -1.0, "1", "-1", "double"); TestGenericPropertyForDataType(std::string("eins"), std::string("zwei"), std::string("eins"), std::string("zwei"), "std::string"); { mitk::Point3D p1; p1[0] = 2.0; p1[1] = 3.0; p1[2] = 4.0; mitk::Point3D p2; p2[0] =-1.0; p2[1] = 2.0; p2[2] = 3.0; TestGenericPropertyForDataType( p1, p2, "[2, 3, 4]", "[-1, 2, 3]", "mitk::Point3D"); } { mitk::Point4D p1; p1[0] = 2.0; p1[1] = 3.0; p1[2] = 4.0; p1[3] =-2.0; mitk::Point4D p2; p2[0] =-1.0; p2[1] = 2.0; p2[2] = 3.0; p2[3] = 5.0; TestGenericPropertyForDataType( p1, p2, "[2, 3, 4, -2]", "[-1, 2, 3, 5]", "mitk::Point4D"); } /* THIS won't compile because of the interface of XMLWriter... that should be reworked perhaps { mitk::Vector2D p1; p1[0] = 2.0; p1[1] = 3.0; mitk::Vector2D p2; p2[0] =-1.0; p2[1] = 2.0; TestGenericPropertyForDataType( p1, p2, "[2, 3]", "[-1, 2]", "mitk::Vector2D"); } */ { mitk::Vector3D p1; p1[0] = 2.0; p1[1] = 3.0; p1[2] = 4.0; mitk::Vector3D p2; p2[0] =-1.0; p2[1] = 2.0; p2[2] = 3.0; TestGenericPropertyForDataType( p1, p2, "[2, 3, 4]", "[-1, 2, 3]", "mitk::Vector3D"); } MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkGeometry3DTest.cpp b/Core/Code/Testing/mitkGeometry3DTest.cpp index 08c1b1ddf8..f27ca7ad8e 100644 --- a/Core/Code/Testing/mitkGeometry3DTest.cpp +++ b/Core/Code/Testing/mitkGeometry3DTest.cpp @@ -1,614 +1,614 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkGeometry3D.h" #include #include #include "mitkRotationOperation.h" #include "mitkInteractionConst.h" #include #include #include "mitkTestingMacros.h" #include -#include +#include bool testGetAxisVectorVariants(mitk::Geometry3D* geometry) { int direction; for(direction=0; direction<3; ++direction) { mitk::Vector3D frontToBack; switch(direction) { case 0: frontToBack = geometry->GetCornerPoint(false, false, false)-geometry->GetCornerPoint(true , false, false); break; //7-3 case 1: frontToBack = geometry->GetCornerPoint(false, false, false)-geometry->GetCornerPoint(false, true , false); break; //7-5 case 2: frontToBack = geometry->GetCornerPoint(false, false, false)-geometry->GetCornerPoint(false , false, true); break; //7-2 } std::cout << "Testing GetAxisVector(int) vs GetAxisVector(bool, bool, bool): "; if(mitk::Equal(geometry->GetAxisVector(direction), frontToBack) == false) { std::cout<<"[FAILED]"<GetAxisVector(direction).GetNorm(), geometry->GetExtentInMM(direction)) == false) { std::cout<<"[FAILED]"<GetOrigin(); mitk::Point3D dummy; MITK_TEST_OUTPUT( << " Testing index->world->index conversion consistency"); geometry3d->WorldToIndex(origin, dummy); geometry3d->IndexToWorld(dummy, dummy); MITK_TEST_CONDITION_REQUIRED(dummy == origin, ""); MITK_TEST_OUTPUT( << " Testing WorldToIndex(origin, mitk::Point3D)==(0,0,0)"); mitk::Point3D globalOrigin; mitk::FillVector3D(globalOrigin, 0,0,0); mitk::Point3D originContinuousIndex; geometry3d->WorldToIndex(origin, originContinuousIndex); MITK_TEST_CONDITION_REQUIRED(originContinuousIndex == globalOrigin, ""); MITK_TEST_OUTPUT( << " Testing WorldToIndex(origin, itk::Index)==(0,0,0)"); itk::Index<3> itkindex; geometry3d->WorldToIndex(origin, itkindex); itk::Index<3> globalOriginIndex; mitk::vtk2itk(globalOrigin, globalOriginIndex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT( << " Testing WorldToIndex(origin-0.5*spacing, itk::Index)==(0,0,0)"); mitk::Vector3D halfSpacingStep = geometry3d->GetSpacing()*0.5; mitk::Matrix3D rotation; mitk::Point3D originOffCenter = origin-halfSpacingStep; geometry3d->WorldToIndex(originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT( << " Testing WorldToIndex(origin+0.5*spacing-eps, itk::Index)==(0,0,0)"); originOffCenter = origin+halfSpacingStep; originOffCenter -= 0.0001; geometry3d->WorldToIndex( originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT( << " Testing WorldToIndex(origin+0.5*spacing, itk::Index)==(1,1,1)"); originOffCenter = origin+halfSpacingStep; itk::Index<3> global111; mitk::FillVector3D(global111, 1,1,1); geometry3d->WorldToIndex( originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == global111, ""); MITK_TEST_OUTPUT( << " Testing WorldToIndex(GetCenter())==BoundingBox.GetCenter: "); mitk::Point3D center = geometry3d->GetCenter(); mitk::Point3D centerContIndex; geometry3d->WorldToIndex(center, centerContIndex); mitk::BoundingBox::ConstPointer boundingBox = geometry3d->GetBoundingBox(); mitk::BoundingBox::PointType centerBounds = boundingBox->GetCenter(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(centerContIndex,centerBounds), ""); MITK_TEST_OUTPUT( << " Testing GetCenter()==IndexToWorld(BoundingBox.GetCenter): "); center = geometry3d->GetCenter(); mitk::Point3D centerBoundsInWorldCoords; geometry3d->IndexToWorld(centerBounds, centerBoundsInWorldCoords); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(center,centerBoundsInWorldCoords), ""); return EXIT_SUCCESS; } int testIndexAndWorldConsistencyForVectors(mitk::Geometry3D* geometry3d) { MITK_TEST_OUTPUT( << "Testing consistency of index and world coordinate systems for vectors: "); mitk::Vector3D xAxisMM = geometry3d->GetAxisVector(0); mitk::Vector3D xAxisContinuousIndex; mitk::Vector3D xAxisContinuousIndexDeprecated; mitk::Point3D p, pIndex, origin; origin = geometry3d->GetOrigin(); p[0] = xAxisMM[0]; p[1] = xAxisMM[1]; p[2] = xAxisMM[2]; geometry3d->WorldToIndex(p,pIndex); geometry3d->WorldToIndex(xAxisMM, xAxisContinuousIndexDeprecated); geometry3d->WorldToIndex(xAxisMM,xAxisContinuousIndex); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[0] == pIndex[0],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[1] == pIndex[1],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[2] == pIndex[2],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[0] == xAxisContinuousIndexDeprecated[0],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[1] == xAxisContinuousIndexDeprecated[1],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[2] == xAxisContinuousIndexDeprecated[2],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[0] == pIndex[0],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[1] == pIndex[1],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[2] == pIndex[2],""); geometry3d->IndexToWorld(xAxisContinuousIndex,xAxisContinuousIndex); geometry3d->IndexToWorld(xAxisContinuousIndexDeprecated,xAxisContinuousIndexDeprecated); geometry3d->IndexToWorld(pIndex,p); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex == xAxisMM,""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[0] == p[0],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[1] == p[1],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[2] == p[2],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated == xAxisMM,""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[0] == p[0],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[1] == p[1],""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[2] == p[2],""); return EXIT_SUCCESS; } int testIndexAndWorldConsistencyForIndex(mitk::Geometry3D* geometry3d) { MITK_TEST_OUTPUT( << "Testing consistency of index and world coordinate systems: "); // creating testing data itk::Index<4> itkIndex4, itkIndex4b; itk::Index<3> itkIndex3, itkIndex3b; itk::Index<2> itkIndex2, itkIndex2b; itk::Index<3> mitkIndex, mitkIndexb; itkIndex4[0] = itkIndex4[1] = itkIndex4[2] = itkIndex4[3] = 4; itkIndex3[0] = itkIndex3[1] = itkIndex3[2] = 6; itkIndex2[0] = itkIndex2[1] = 2; mitkIndex[0] = mitkIndex[1] = mitkIndex[2] = 13; // check for constistency mitk::Point3D point; geometry3d->IndexToWorld(itkIndex2,point); geometry3d->WorldToIndex(point,itkIndex2b); MITK_TEST_CONDITION_REQUIRED( ((itkIndex2b[0] == itkIndex2[0]) && (itkIndex2b[1] == itkIndex2[1])), "Testing itk::index<2> for IndexToWorld/WorldToIndex consistency"); geometry3d->IndexToWorld(itkIndex3,point); geometry3d->WorldToIndex(point,itkIndex3b); MITK_TEST_CONDITION_REQUIRED( ((itkIndex3b[0] == itkIndex3[0]) && (itkIndex3b[1] == itkIndex3[1]) && (itkIndex3b[2] == itkIndex3[2])), "Testing itk::index<3> for IndexToWorld/WorldToIndex consistency"); geometry3d->IndexToWorld(itkIndex4,point); geometry3d->WorldToIndex(point,itkIndex4b); MITK_TEST_CONDITION_REQUIRED( ((itkIndex4b[0] == itkIndex4[0]) && (itkIndex4b[1] == itkIndex4[1]) && (itkIndex4b[2] == itkIndex4[2]) && (itkIndex4b[3] == 0)), "Testing itk::index<3> for IndexToWorld/WorldToIndex consistency"); geometry3d->IndexToWorld(mitkIndex,point); geometry3d->WorldToIndex(point,mitkIndexb); MITK_TEST_CONDITION_REQUIRED( ((mitkIndexb[0] == mitkIndex[0]) && (mitkIndexb[1] == mitkIndex[1]) && (mitkIndexb[2] == mitkIndex[2])), "Testing mitk::Index for IndexToWorld/WorldToIndex consistency"); return EXIT_SUCCESS; } #include int testItkImageIsCenterBased() { MITK_TEST_OUTPUT(<< "Testing whether itk::Image coordinates are center-based."); typedef itk::Image ItkIntImage3D; ItkIntImage3D::Pointer itkintimage = ItkIntImage3D::New(); ItkIntImage3D::SizeType size; size.Fill(10); mitk::Point3D origin; mitk::FillVector3D(origin, 2,3,7); itkintimage->Initialize(); itkintimage->SetRegions(size); itkintimage->SetOrigin(origin); std::cout<<"[PASSED]"< originContinuousIndex; itkintimage->TransformPhysicalPointToContinuousIndex(origin, originContinuousIndex); MITK_TEST_CONDITION_REQUIRED(originContinuousIndex == globalOrigin, ""); MITK_TEST_OUTPUT( << " Testing itk::Image::TransformPhysicalPointToIndex(origin)==(0,0,0)"); itk::Index<3> itkindex; itkintimage->TransformPhysicalPointToIndex(origin, itkindex); itk::Index<3> globalOriginIndex; mitk::vtk2itk(globalOrigin, globalOriginIndex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT( << " Testing itk::Image::TransformPhysicalPointToIndex(origin-0.5*spacing)==(0,0,0)"); mitk::Vector3D halfSpacingStep = itkintimage->GetSpacing()*0.5; mitk::Matrix3D rotation; mitk::Point3D originOffCenter = origin-halfSpacingStep; itkintimage->TransformPhysicalPointToIndex(originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT( << " Testing itk::Image::TransformPhysicalPointToIndex(origin+0.5*spacing-eps, itk::Index)==(0,0,0)"); originOffCenter = origin+halfSpacingStep; originOffCenter -= 0.0001; itkintimage->TransformPhysicalPointToIndex( originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT( << " Testing itk::Image::TransformPhysicalPointToIndex(origin+0.5*spacing, itk::Index)==(1,1,1)"); originOffCenter = origin+halfSpacingStep; itk::Index<3> global111; mitk::FillVector3D(global111, 1,1,1); itkintimage->TransformPhysicalPointToIndex( originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == global111, ""); MITK_TEST_OUTPUT( << "=> Yes, itk::Image coordinates are center-based."); return EXIT_SUCCESS; } int testGeometry3D(bool imageGeometry) { // Build up a new image Geometry mitk::Geometry3D::Pointer geometry3d = mitk::Geometry3D::New(); float bounds[ ] = {-10.0, 17.0, -12.0, 188.0, 13.0, 211.0}; MITK_TEST_OUTPUT( << "Initializing"); geometry3d->Initialize(); MITK_TEST_OUTPUT(<< "Setting ImageGeometry to " << imageGeometry); geometry3d->SetImageGeometry(imageGeometry); MITK_TEST_OUTPUT(<< "Setting bounds by SetFloatBounds(): " << bounds); geometry3d->SetFloatBounds(bounds); MITK_TEST_OUTPUT( << "Testing AxisVectors"); if(testGetAxisVectorVariants(geometry3d) == false) return EXIT_FAILURE; if(testGetAxisVectorExtent(geometry3d) == false) return EXIT_FAILURE; MITK_TEST_OUTPUT( << "Creating an AffineTransform3D transform"); mitk::AffineTransform3D::MatrixType matrix; matrix.SetIdentity(); matrix(1,1) = 2; mitk::AffineTransform3D::Pointer transform; transform = mitk::AffineTransform3D::New(); transform->SetMatrix(matrix); MITK_TEST_OUTPUT( << "Testing a SetIndexToWorldTransform"); geometry3d->SetIndexToWorldTransform(transform); MITK_TEST_OUTPUT( << "Testing correctness of value returned by GetSpacing"); const mitk::Vector3D& spacing1 = geometry3d->GetSpacing(); mitk::Vector3D expectedSpacing; expectedSpacing.Fill(1.0); expectedSpacing[1] = 2; if( mitk::Equal(spacing1, expectedSpacing) == false ) { MITK_TEST_OUTPUT( << " [FAILED]"); return EXIT_FAILURE; } MITK_TEST_OUTPUT( << "Testing a Compose(transform)"); geometry3d->Compose(transform); MITK_TEST_OUTPUT( << "Testing correctness of value returned by GetSpacing"); const mitk::Vector3D& spacing2 = geometry3d->GetSpacing(); expectedSpacing[1] = 4; if( mitk::Equal(spacing2, expectedSpacing) == false ) { MITK_TEST_OUTPUT( << " [FAILED]"); return EXIT_FAILURE; } MITK_TEST_OUTPUT( << "Testing correctness of SetSpacing"); mitk::Vector3D newspacing; mitk::FillVector3D(newspacing, 1.5, 2.5, 3.5); geometry3d->SetSpacing(newspacing); const mitk::Vector3D& spacing3 = geometry3d->GetSpacing(); if( mitk::Equal(spacing3, newspacing) == false ) { MITK_TEST_OUTPUT( << " [FAILED]"); return EXIT_FAILURE; } // Seperate Test function for Index and World consistency testIndexAndWorldConsistency(geometry3d); testIndexAndWorldConsistencyForVectors(geometry3d); testIndexAndWorldConsistencyForIndex(geometry3d); MITK_TEST_OUTPUT( << "Testing a rotation of the geometry"); double angle = 35.0; mitk::Vector3D rotationVector; mitk::FillVector3D( rotationVector, 1, 0, 0 ); mitk::Point3D center = geometry3d->GetCenter(); mitk::RotationOperation* op = new mitk::RotationOperation( mitk::OpROTATE, center, rotationVector, angle ); geometry3d->ExecuteOperation(op); MITK_TEST_OUTPUT( << "Testing mitk::GetRotation() and success of rotation"); mitk::Matrix3D rotation; mitk::GetRotation(geometry3d, rotation); mitk::Vector3D voxelStep=rotation*newspacing; mitk::Vector3D voxelStepIndex; geometry3d->WorldToIndex(voxelStep, voxelStepIndex); mitk::Vector3D expectedVoxelStepIndex; expectedVoxelStepIndex.Fill(1); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(voxelStepIndex,expectedVoxelStepIndex), ""); delete op; std::cout<<"[PASSED]"<GetImageGeometry() == imageGeometry, ""); //Test if the translate function moves the origin correctly. mitk::Point3D oldOrigin = geometry3d->GetOrigin(); //use some random values for translation mitk::Vector3D translationVector; translationVector.SetElement(0, 17.5f); translationVector.SetElement(1, -32.3f); translationVector.SetElement(2, 4.0f); //compute ground truth mitk::Point3D tmpResult = geometry3d->GetOrigin() + translationVector; geometry3d->Translate(translationVector); MITK_TEST_CONDITION( mitk::Equal( geometry3d->GetOrigin(), tmpResult ), "Testing if origin was translated."); translationVector*=-1; //vice versa geometry3d->Translate(translationVector); MITK_TEST_CONDITION( mitk::Equal( geometry3d->GetOrigin(), oldOrigin ), "Testing if the translation could be done vice versa." ); return EXIT_SUCCESS; } int testGeometryAfterCasting() { // Epsilon. Allowed difference for rotationvalue float eps = 0.0001; // Cast ITK and MITK images and see if geometry stays typedef itk::Image Image2DType; typedef itk::Image Image3DType; // Create 3D ITK Image from Scratch, cast to 3D MITK image, compare Geometries Image3DType::Pointer image3DItk = Image3DType::New(); Image3DType::RegionType myRegion; Image3DType::SizeType mySize; Image3DType::IndexType myIndex; Image3DType::SpacingType mySpacing; Image3DType::DirectionType myDirection, rotMatrixX, rotMatrixY, rotMatrixZ; mySpacing[0] = 31; mySpacing[1] = 0.1; mySpacing[2] = 2.9; myIndex[0] = -15; myIndex[1] = 15; myIndex[2] = 12; mySize[0] = 10; mySize[1] = 2; mySize[2] = 555; myRegion.SetSize( mySize); myRegion.SetIndex( myIndex ); image3DItk->SetSpacing(mySpacing); image3DItk->SetRegions( myRegion); image3DItk->Allocate(); image3DItk->FillBuffer(0); myDirection.SetIdentity(); rotMatrixX.SetIdentity(); rotMatrixY.SetIdentity(); rotMatrixZ.SetIdentity(); mitk::Image::Pointer mitkImage; // direction [row] [coloum] MITK_TEST_OUTPUT( << "Casting a rotated 3D ITK Image to a MITK Image and check if Geometry is still same" ); for (double rotX=0; rotX < (itk::Math::pi*2); rotX+=0.4 ) { // Set Rotation X rotMatrixX[1][1] = cos( rotX ); rotMatrixX[1][2] = -sin( rotX ); rotMatrixX[2][1] = sin( rotX ); rotMatrixX[2][2] = cos( rotX ); for (double rotY=0; rotY < (itk::Math::pi*2); rotY+=0.33 ) { // Set Rotation Y rotMatrixY[0][0] = cos( rotY ); rotMatrixY[0][2] = sin( rotY ); rotMatrixY[2][0] = -sin( rotY ); rotMatrixY[2][2] = cos( rotY ); for (double rotZ=0; rotZ < (itk::Math::pi*2); rotZ+=0.5 ) { // Set Rotation Z rotMatrixZ[0][0] = cos( rotZ ); rotMatrixZ[0][1] = -sin( rotZ ); rotMatrixZ[1][0] = sin( rotZ ); rotMatrixZ[1][1] = cos( rotZ ); // Multiply matrizes myDirection = myDirection * rotMatrixX * rotMatrixY * rotMatrixZ; image3DItk->SetDirection(myDirection); mitk::CastToMitkImage(image3DItk, mitkImage); const mitk::AffineTransform3D::MatrixType& matrix = mitkImage->GetGeometry()->GetIndexToWorldTransform()->GetMatrix(); for (int row=0; row<3; row++) { for (int col=0; col<3; col++) { double mitkValue = matrix[row][col] / mitkImage->GetGeometry()->GetSpacing()[col]; double itkValue = myDirection[row][col]; double diff = mitkValue - itkValue; // if you decrease this value, you can see that there might be QUITE high inaccuracy!!! if (diff > eps) // need to check, how exact it SHOULD be .. since it is NOT EXACT! { std::cout << "Had a difference of : " << diff; std::cout << "Error: Casting altered Geometry!"; std::cout << "ITK Matrix:\n" << myDirection; std::cout << "Mitk Matrix (With Spacing):\n" << matrix; std::cout << "Mitk Spacing: " << mitkImage->GetGeometry()->GetSpacing(); MITK_TEST_CONDITION_REQUIRED(false == true, ""); return false; } } } } } } // Create 2D ITK Image from Scratch, cast to 2D MITK image, compare Geometries Image2DType::Pointer image2DItk = Image2DType::New(); Image2DType::RegionType myRegion2D; Image2DType::SizeType mySize2D; Image2DType::IndexType myIndex2D; Image2DType::SpacingType mySpacing2D; Image2DType::DirectionType myDirection2D, rotMatrix; mySpacing2D[0] = 31; mySpacing2D[1] = 0.1; myIndex2D[0] = -15; myIndex2D[1] = 15; mySize2D[0] = 10; mySize2D[1] = 2; myRegion2D.SetSize( mySize2D); myRegion2D.SetIndex( myIndex2D ); image2DItk->SetSpacing(mySpacing2D); image2DItk->SetRegions( myRegion2D); image2DItk->Allocate(); image2DItk->FillBuffer(0); myDirection2D.SetIdentity(); rotMatrix.SetIdentity(); // direction [row] [coloum] MITK_TEST_OUTPUT( << "Casting a rotated 2D ITK Image to a MITK Image and check if Geometry is still same" ); for (double rotTheta=0; rotTheta < (itk::Math::pi*2); rotTheta+=0.1 ) { // Set Rotation rotMatrix[0][0] = cos(rotTheta); rotMatrix[0][1] = -sin(rotTheta); rotMatrix[1][0] = sin(rotTheta); rotMatrix[1][1] = cos(rotTheta); // Multiply matrizes myDirection2D = myDirection2D * rotMatrix; image2DItk->SetDirection(myDirection2D); mitk::CastToMitkImage(image2DItk, mitkImage); const mitk::AffineTransform3D::MatrixType& matrix = mitkImage->GetGeometry()->GetIndexToWorldTransform()->GetMatrix(); // Compare MITK and ITK matrix for (int row=0; row<3; row++) { for (int col=0; col<3; col++) { double mitkValue = matrix[row][col] / mitkImage->GetGeometry()->GetSpacing()[col]; if ((row == 2) && (col == row)) { if (mitkValue != 1) { MITK_TEST_OUTPUT(<< "After casting a 2D ITK to 3D MITK images, MITK matrix values for 0|2, 1|2, 2|0, 2|1 MUST be 0 and value for 2|2 must be 1"); return false; } } else if ((row == 2) || (col == 2)) { if (mitkValue != 0) { MITK_TEST_OUTPUT(<< "After casting a 2D ITK to 3D MITK images, MITK matrix values for 0|2, 1|2, 2|0, 2|1 MUST be 0 and value for 2|2 must be 1"); return false; } } else { double itkValue = myDirection2D[row][col]; double diff = mitkValue - itkValue; // if you decrease this value, you can see that there might be QUITE high inaccuracy!!! if (diff > eps) // need to check, how exact it SHOULD be .. since it is NOT EXACT! { std::cout << "Had a difference of : " << diff; std::cout << "Error: Casting altered Geometry!"; std::cout << "ITK Matrix:\n" << myDirection2D; std::cout << "Mitk Matrix (With Spacing):\n" << matrix; std::cout << "Mitk Spacing: " << mitkImage->GetGeometry()->GetSpacing(); MITK_TEST_CONDITION_REQUIRED(false == true, ""); return false; } } } } } // THIS WAS TESTED: // 2D ITK -> 2D MITK, // 3D ITK -> 3D MITK, // Still need to test: 2D MITK Image with ADDITIONAL INFORMATION IN MATRIX -> 2D ITK // 1. Possibility: 3x3 MITK matrix can be converted without loss into 2x2 ITK matrix // 2. Possibility: 3x3 MITK matrix can only be converted with loss into 2x2 ITK matrix // .. before implementing this, we wait for further development in geometry classes (e.g. Geoemtry3D::SetRotation(..)) return EXIT_SUCCESS; } int mitkGeometry3DTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN(mitkGeometry3DTest); int result; MITK_TEST_CONDITION_REQUIRED( (result = testItkImageIsCenterBased()) == EXIT_SUCCESS, ""); MITK_TEST_OUTPUT(<< "Running main part of test with ImageGeometry = false"); MITK_TEST_CONDITION_REQUIRED( (result = testGeometry3D(false)) == EXIT_SUCCESS, ""); MITK_TEST_OUTPUT(<< "Running main part of test with ImageGeometry = true"); MITK_TEST_CONDITION_REQUIRED( (result = testGeometry3D(true)) == EXIT_SUCCESS, ""); MITK_TEST_OUTPUT(<< "Running test to see if Casting MITK to ITK and the other way around destroys geometry"); MITK_TEST_CONDITION_REQUIRED( (result = testGeometryAfterCasting()) == EXIT_SUCCESS, ""); MITK_TEST_END(); return EXIT_SUCCESS; } diff --git a/Core/Code/Testing/mitkLogTest.cpp b/Core/Code/Testing/mitkLogTest.cpp index 42ab30f735..cee8373457 100644 --- a/Core/Code/Testing/mitkLogTest.cpp +++ b/Core/Code/Testing/mitkLogTest.cpp @@ -1,286 +1,286 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkCommon.h" #include "mitkTestingMacros.h" #include -#include +#include #include #include #include /** Documentation * * @brief Objects of this class can start an internal thread by calling the Start() method. * The thread is then logging messages until the method Stop() is called. The class * can be used to test if logging is thread-save by using multiple objects and let * them log simuntanously. */ class mitkTestLoggingThread : public itk::Object { public: mitkClassMacro(mitkTestLoggingThread,itk::Object); mitkNewMacro1Param(mitkTestLoggingThread,itk::MultiThreader::Pointer); int NumberOfMessages; protected: mitkTestLoggingThread(itk::MultiThreader::Pointer MultiThreader) { ThreadID = -1; NumberOfMessages = 0; m_MultiThreader = MultiThreader; } bool LoggingRunning; int ThreadID; itk::MultiThreader::Pointer m_MultiThreader; void LogMessages() { while(LoggingRunning) { MITK_INFO << "Test info stream in thread" << ThreadID << "\n even with newlines"; MITK_WARN << "Test warning stream in thread " << ThreadID <<". " << "Even with a very long text, even without meaning or implied meaning or content, just a long sentence to see whether something has problems with long sentences or output in files or into windows or commandlines or whatever."; MITK_DEBUG << "Test debugging stream in thread " << ThreadID; MITK_ERROR << "Test error stream in thread " << ThreadID; MITK_FATAL << "Test fatal stream in thread " << ThreadID; NumberOfMessages += 5; } } static ITK_THREAD_RETURN_TYPE 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; } mitkTestLoggingThread *thisthread = (mitkTestLoggingThread*)pInfo->UserData; if (thisthread != NULL) thisthread->LogMessages(); return ITK_THREAD_RETURN_VALUE; } public: int Start() { LoggingRunning = true; this->ThreadID = m_MultiThreader->SpawnThread(this->ThreadStartTracking, this); return ThreadID; } void Stop() { LoggingRunning = false; } }; /** Documentation * * @brief This class holds static test methods to sturcture the test of the mitk logging mechanism. */ class mitkLogTestClass { public: static void TestSimpleLog() { bool testSucceded = true; try { MITK_INFO << "Test info stream."; MITK_WARN << "Test warning stream."; MITK_DEBUG << "Test debugging stream."; //only activated if cmake variable is on! //so no worries if you see no output for this line MITK_ERROR << "Test error stream."; MITK_FATAL << "Test fatal stream."; } catch(mitk::Exception e) { testSucceded = false; } MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging streams."); } static void TestObjectInfoLogging() { bool testSucceded = true; try { int i = 123; float f = .32234; double d = 123123; std::string testString = "testString"; std::stringstream testStringStream; testStringStream << "test" << "String" << "Stream"; mitk::Point3D testMitkPoint; testMitkPoint.Fill(2); MITK_INFO << i; MITK_INFO << f; MITK_INFO << d; MITK_INFO << testString; MITK_INFO << testStringStream.str(); MITK_INFO << testMitkPoint; } catch(mitk::Exception e) { testSucceded = false; } MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging of object information."); } static void TestThreadSaveLog(bool toFile) { bool testSucceded = true; try { if (toFile) { std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + "/testthreadlog.log"; itksys::SystemTools::RemoveFile(filename.c_str()); // remove old file, we do not want to append to large files mitk::LoggingBackend::SetLogFile(filename.c_str()); } unsigned int numberOfThreads = 20; unsigned int threadRuntimeInMilliseconds = 2000; std::vector threadIDs; std::vector threads; itk::MultiThreader::Pointer multiThreader = itk::MultiThreader::New(); for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx) { //initialize threads... mitkTestLoggingThread::Pointer newThread = mitkTestLoggingThread::New(multiThreader); threads.push_back(newThread); std::cout << "Created " << threadIdx << ". thread." << std::endl; } for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx) { //start them std::cout << "Start " << threadIdx << ". thread." << std::endl; threadIDs.push_back( threads[threadIdx]->Start() ); std::cout << threadIdx << ". thread has ID " << threadIDs[threadIdx] << std::endl; } //wait for some time (milliseconds) itksys::SystemTools::Delay( threadRuntimeInMilliseconds ); for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx) { //stop them std::cout << "Stop " << threadIdx << ". thread." << std::endl; threads[threadIdx]->Stop(); } for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx) { //Wait for all threads to end multiThreader->TerminateThread(threadIDs[threadIdx]); std::cout << "Terminated " << threadIdx << ". thread (" << threads[threadIdx]->NumberOfMessages << " messages)." << std::endl; } } catch(std::exception e) { MITK_ERROR << "exception during 'TestThreadSaveLog': "<GetOptionDirectory() + "/testlog.log"; mitk::LoggingBackend::SetLogFile(filename.c_str()); MITK_INFO << "Test logging to default filename: " << mitk::LoggingBackend::GetLogFile(); MITK_TEST_CONDITION_REQUIRED(itksys::SystemTools::FileExists(filename.c_str()),"Testing if log file exists."); //TODO delete log file? } static void TestAddAndRemoveBackends() { mbilog::BackendCout myBackend = mbilog::BackendCout(); mbilog::RegisterBackend(&myBackend); MITK_INFO << "Test logging"; mbilog::UnregisterBackend(&myBackend); //if no error occured until now, everything is ok MITK_TEST_CONDITION_REQUIRED(true,"Test add/remove logging backend."); } static void TestDefaultBackend() { //not possible now, because we cannot unregister the mitk logging backend in the moment. If such a method is added to mbilog utility one may add this test. } }; int mitkLogTest(int /* argc */, char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("Log") MITK_TEST_OUTPUT(<<"TESTING ALL LOGGING OUTPUTS, ERROR MESSAGES ARE ALSO TESTED AND NOT MEANING AN ERROR OCCURED!") mitkLogTestClass::TestSimpleLog(); mitkLogTestClass::TestObjectInfoLogging(); mitkLogTestClass::TestLoggingToFile(); mitkLogTestClass::TestAddAndRemoveBackends(); mitkLogTestClass::TestThreadSaveLog( false ); // false = to console mitkLogTestClass::TestThreadSaveLog( true ); // true = to file // TODO actually test file somehow? // always end with this! MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkLookupTableTest.cpp b/Core/Code/Testing/mitkLookupTableTest.cpp index e0b0a4f99c..bc9189ec54 100644 --- a/Core/Code/Testing/mitkLookupTableTest.cpp +++ b/Core/Code/Testing/mitkLookupTableTest.cpp @@ -1,183 +1,183 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkTestingMacros.h" -#include +#include #include #include #include class mitkLookupTableTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkLookupTableTestSuite); MITK_TEST(TestCreateLookupTable); MITK_TEST(TestSetVtkLookupTable); MITK_TEST(TestSetOpacity); MITK_TEST(TestCreateColorTransferFunction); MITK_TEST(TestCreateOpacityTransferFunction); MITK_TEST(TestCreateGradientTransferFunction); CPPUNIT_TEST_SUITE_END(); private: mitk::LookupTable::Pointer m_LookupTable; public: void TestCreateLookupTable() { // let's create an object of our class mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // first test: did this work? // it makes no sense to continue without an object. CPPUNIT_ASSERT_MESSAGE("Testing instantiation", myLookupTable.IsNotNull()); } void TestSetVtkLookupTable () { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetTableValue(0, 0.5, 0.5, 0.5, 1.0); lut->SetTableValue(1, 0.5, 0.5, 0.5, 0.5); lut->Build(); myLookupTable->SetVtkLookupTable(lut); // check if the same lookuptable is returned vtkLookupTable *lut2 = myLookupTable->GetVtkLookupTable(); CPPUNIT_ASSERT_MESSAGE("Input and output table are not equal",lut == lut2); lut->Delete(); } void TestSetOpacity() { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetRange(0, 200); lut->SetAlphaRange(0.0, 1.0); lut->Build(); myLookupTable->SetVtkLookupTable(lut); myLookupTable->ChangeOpacityForAll(0.7f); for (int i = 0; i < lut->GetNumberOfTableValues(); ++i) { CPPUNIT_ASSERT_MESSAGE("Opacity not set for all", mitk::Equal(0.7, lut->GetOpacity(i), 0.01, true)); } vtkIdType tableIndex = 10; myLookupTable->ChangeOpacity(tableIndex, 1.0); double rgba[4]; lut->GetTableValue(tableIndex, rgba); CPPUNIT_ASSERT_MESSAGE("Opacity not set for value", mitk::Equal(1.0, rgba[3], 0.01, true)); } void TestCreateColorTransferFunction () { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetRange(0, 255); lut->Build(); myLookupTable->SetVtkLookupTable(lut); vtkSmartPointer colorTransferFunction = myLookupTable->CreateColorTransferFunction(); CPPUNIT_ASSERT(colorTransferFunction != 0); vtkIdType numberOfTableEntries = lut->GetNumberOfTableValues(); double rgbaTable[4]; double rgbaFunction[4]; for (int i = 0; i < numberOfTableEntries; ++i) { lut->GetIndexedColor(i, rgbaTable); colorTransferFunction->GetIndexedColor(i, rgbaFunction); CPPUNIT_ASSERT_MESSAGE("Wrong color of transfer function", mitk::Equal(rgbaTable[0], rgbaFunction[0], 0.000001, true) && mitk::Equal(rgbaTable[1], rgbaFunction[1], 0.000001, true) && mitk::Equal(rgbaTable[2], rgbaFunction[2], 0.000001, true) ); } } void TestCreateOpacityTransferFunction () { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetAlphaRange(0, 1.0); lut->Build(); myLookupTable->SetVtkLookupTable(lut); vtkSmartPointer opacityTransferFunction = myLookupTable->CreateOpacityTransferFunction(); CPPUNIT_ASSERT(opacityTransferFunction != 0); int funcSize = opacityTransferFunction->GetSize(); double *table = new double[funcSize]; double rgba[4]; opacityTransferFunction->GetTable(0, 1, funcSize, table); for (int i = 0; i < funcSize; ++i) { lut->GetIndexedColor(i, rgba); CPPUNIT_ASSERT_MESSAGE("Wrong opacity of transfer function", mitk::Equal(table[i], rgba[3], 0.000001, true) ); } delete [] table; } void TestCreateGradientTransferFunction () { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetAlphaRange(0, 0.73); lut->Build(); myLookupTable->SetVtkLookupTable(lut); vtkSmartPointer gradientTransferFunction = myLookupTable->CreateGradientTransferFunction(); CPPUNIT_ASSERT(gradientTransferFunction != 0); int funcSize = gradientTransferFunction->GetSize(); double *table = new double[funcSize]; double rgba[4]; gradientTransferFunction->GetTable(0, 1, funcSize, table); for (int i = 0; i < funcSize; ++i) { lut->GetIndexedColor(i, rgba); CPPUNIT_ASSERT_MESSAGE("Wrong opacity of transfer function", mitk::Equal(table[i], rgba[3], 0.000001, true) ); } delete [] table; } }; MITK_TEST_SUITE_REGISTRATION(mitkLookupTable) diff --git a/Core/Code/Testing/mitkMatrixTypeConversionTest.cpp b/Core/Code/Testing/mitkMatrixTypeConversionTest.cpp index 4c4935b203..4c24a6bcf0 100644 --- a/Core/Code/Testing/mitkMatrixTypeConversionTest.cpp +++ b/Core/Code/Testing/mitkMatrixTypeConversionTest.cpp @@ -1,100 +1,100 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkTestingMacros.h" #include "mitkTestFixture.h" #include "mitkMatrix.h" class mitkMatrixTypeConversionTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkMatrixTypeConversionTestSuite); MITK_TEST(Mitk2Pod); MITK_TEST(Pod2Mitk); CPPUNIT_TEST_SUITE_END(); private: mitk::Matrix3D mitkMatrix3D; mitk::ScalarType podMatrix3D[3][3]; /** * @brief Convenience method to test if one matrix has been assigned successfully to the other. * * More specifically, tests if m1 = m2 was performed correctly. * * @param m1 The matrix m1 of the assignment m1 = m2 * @param m2 The matrix m2 of the assignment m1 = m2 */ template void TestForEquality(T1 m1, T2 m2) { for (unsigned i = 0; i < 3; i++) { for (unsigned j = 0; j < 3; j++) { std::stringstream ss; ss << "element [" << i << "][" + j << "] equal for mitkMatrix and podMatrix"; CPPUNIT_ASSERT_EQUAL_MESSAGE(ss.str(), true, (mitkMatrix3D[i][j]==podMatrix3D[i][j])); } } } public: void setUp(void) { for (unsigned i = 0; i < 3; i++) for (unsigned j = 0; j < 3; j++) { mitkMatrix3D[i][j] = i + j; podMatrix3D[i][j] = (mitk::ScalarType) (9 - (i + j)); } } void tearDown(void) { } void Mitk2Pod(void) { mitkMatrix3D.ToArray(podMatrix3D); TestForEquality(mitkMatrix3D, podMatrix3D); } void Pod2Mitk(void) { - mitkMatrix3D.FromArray(podMatrix3D); + mitkMatrix3D.FillMatrix(podMatrix3D); TestForEquality(podMatrix3D, mitkMatrix3D); } }; MITK_TEST_SUITE_REGISTRATION(mitkMatrixTypeConversion) diff --git a/Core/Code/Testing/mitkPointSetTest.cpp b/Core/Code/Testing/mitkPointSetTest.cpp index e3f9cbe45a..61a73f43b0 100644 --- a/Core/Code/Testing/mitkPointSetTest.cpp +++ b/Core/Code/Testing/mitkPointSetTest.cpp @@ -1,359 +1,359 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkTestFixture.h" #include -#include +#include #include #include #include /** * TestSuite for PointSet stuff not only operating on an empty PointSet */ class mitkPointSetTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPointSetTestSuite); MITK_TEST(TestIsNotEmpty); MITK_TEST(TestSetSelectInfo); MITK_TEST(TestGetNumberOfSelected); MITK_TEST(TestSearchSelectedPoint); MITK_TEST(TestGetPointIfExists); MITK_TEST(TestSwapPointPositionUpwards); MITK_TEST(TestSwapPointPositionUpwardsNotPossible); MITK_TEST(TestSwapPointPositionDownwards); MITK_TEST(TestSwapPointPositionDownwardsNotPossible); MITK_TEST(TestCreateHoleInThePointIDs); MITK_TEST(TestInsertPointWithPointSpecification); CPPUNIT_TEST_SUITE_END(); private: mitk::PointSet::Pointer pointSet; static const mitk::PointSet::PointIdentifier selectedPointId = 2; public: void setUp() { //Create PointSet pointSet = mitk::PointSet::New(); // add some points mitk::Point3D point2, point3, point4; point2.Fill(3); point3.Fill(4); point4.Fill(5); pointSet->InsertPoint(2,point2); pointSet->InsertPoint(3,point3); pointSet->InsertPoint(4,point4); mitk::Point3D point1; mitk::FillVector3D(point1, 1.0, 2.0, 3.0); pointSet->InsertPoint(1, point1); mitk::Point3D point0; point0.Fill(1); pointSet->InsertPoint(0, point0); // select point with id 2 pointSet->SetSelectInfo(2, true); } void tearDown() { pointSet = NULL; } void TestIsNotEmpty() { //PointSet can not be empty! CPPUNIT_ASSERT_EQUAL_MESSAGE( "check if the PointSet is not empty ", true, !pointSet->IsEmptyTimeStep(0) ); /* std::cout << "check if the PointSet is not empty "; if (pointSet->IsEmpty(0)) { std::cout<<"[FAILED]"<SetSelectInfo(4, true); CPPUNIT_ASSERT_EQUAL_MESSAGE("check SetSelectInfo", true, pointSet->GetSelectInfo(4)); /* if (!pointSet->GetSelectInfo(2)) { std::cout<<"[FAILED]"<SearchSelectedPoint() == (int) selectedPointId); /* if( pointSet->SearchSelectedPoint() != 4) { std::cout<<"[FAILED]"<GetNumberOfSelected() == 1); /* if(pointSet->GetNumberOfSelected() != 1) { std::cout<<"[FAILED]"<GetPointIfExists(4, &tmpPoint); CPPUNIT_ASSERT_EQUAL_MESSAGE("check GetPointIfExists: ", true, tmpPoint == point4); /* if (tmpPoint != point5) { std::cout<<"[FAILED]"<GetPoint(1); pointSet->SwapPointPosition(1, true); tempPoint = pointSet->GetPoint(0); CPPUNIT_ASSERT_EQUAL_MESSAGE("check SwapPointPosition upwards", true, point == tempPoint); /* if(point != tempPoint) { std::cout<<"[FAILED]"<SwapPointPosition(0, true)); /* if(pointSet->SwapPointPosition(0, true)) { std::cout<<"[FAILED]"<GetPoint(0); pointSet->SwapPointPosition(0, false); tempPoint = pointSet->GetPoint(1); CPPUNIT_ASSERT_EQUAL_MESSAGE("check SwapPointPosition down", true, point == tempPoint); /* if(point != tempPoint) { std::cout<<"[FAILED]"<SetPoint(id, point); //Check SwapPointPosition downwards not possible CPPUNIT_ASSERT_EQUAL_MESSAGE("check SwapPointPosition downwards not possible", false, pointSet2->SwapPointPosition(id, false)); /* if(pointSet->SwapPointPosition(1, false)) { std::cout<<"[FAILED]"<InsertPoint(10, p10); pointSet->InsertPoint(11, p11); pointSet->InsertPoint(12, p12); CPPUNIT_ASSERT_EQUAL_MESSAGE("add points with id 10, 11, 12: ", true, (pointSet->IndexExists(10) == true) || (pointSet->IndexExists(11) == true) || (pointSet->IndexExists(12) == true)); //check OpREMOVE ExecuteOperation int id = 11; mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpREMOVE, point, id); pointSet->ExecuteOperation(doOp); CPPUNIT_ASSERT_EQUAL_MESSAGE( "remove point id 11: ", false, pointSet->IndexExists(id)); /* if(pointSet->IndexExists(id)) { std::cout<<"[FAILED]"<ExecuteOperation(doOp); delete doOp; //check OpMOVEPOINTUP ExecuteOperation doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, p12, 12); pointSet->ExecuteOperation(doOp); delete doOp; mitk::PointSet::PointType newP10 = pointSet->GetPoint(10); mitk::PointSet::PointType newP12 = pointSet->GetPoint(12); CPPUNIT_ASSERT_EQUAL_MESSAGE("check PointOperation OpMOVEPOINTUP for point id 12:", true, ((newP10 == p12) && (newP12 == p10))); //check OpMOVEPOINTDOWN ExecuteOperation doOp = new mitk::PointOperation(mitk::OpMOVEPOINTDOWN, p10, 10); pointSet->ExecuteOperation(doOp); delete doOp; newP10 = pointSet->GetPoint(10); newP12 = pointSet->GetPoint(12); CPPUNIT_ASSERT_EQUAL_MESSAGE("check PointOperation OpMOVEPOINTDOWN for point id 10: ", true, ((newP10 == p10) && (newP12 == p12))); } void TestInsertPointWithPointSpecification() { //check InsertPoint with PointSpecification mitk::Point3D point5; mitk::Point3D tempPoint; point5.Fill(7); pointSet->SetPoint(5, point5, mitk::PTEDGE ); tempPoint = pointSet->GetPoint(5); CPPUNIT_ASSERT_EQUAL_MESSAGE("check InsertPoint with PointSpecification" , true, tempPoint == point5); /* if (tempPoint != point5) { std::cout<<"[FAILED]"< using namespace mitk; class mitkPointTypeConversionTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPointTypeConversionTestSuite); MITK_TEST(Vector2Point); MITK_TEST(Mitk2Itk_PointCompatibility); MITK_TEST(Itk2Mitk_PointCompatibility); MITK_TEST(Vtk2Mitk_PointCompatibility); MITK_TEST(Mitk2Pod_PointCompatibility); MITK_TEST(Pod2Mitk_PointCompatibility); CPPUNIT_TEST_SUITE_END(); private: vtkSmartPointer a_vtkPoints; ScalarType originalValues[3]; ScalarType valuesToCopy[3]; /** * @brief Convenience method to test if one vector has been assigned successfully to the other. * * More specifically, tests if v1 = v2 was performed correctly. * * @param v1 The vector v1 of the assignment v1 = v2 * @param v2 The vector v2 of the assignment v1 = v2 * @param v1Name The type name of v1 (e.g.: mitk::Vector3D). Necessary for the correct test output. * @param v2Name The type name of v2 (e.g.: mitk::Vector3D). Necessary for the correct test output. * @param eps defines the allowed tolerance when testing for equality. */ template void TestForEquality(T1 v1, T2 v2, std::string v1Name, std::string v2Name, ScalarType eps = mitk::eps) { CPPUNIT_ASSERT_EQUAL_MESSAGE("\nAssigning " + v2Name + " to " + v1Name + ":\n both are equal", true, EqualArray(v1, v2, 3, eps)); } public: void setUp(void) { FillVector3D(originalValues, 1.0, 2.0, 3.0); FillVector3D(valuesToCopy, 4.0, 5.0, 6.0); a_vtkPoints = vtkSmartPointer::New(); a_vtkPoints->Initialize(); } void tearDown(void) { // a_vtkPoints = NULL; } void Mitk2Itk_PointCompatibility() { itk::Point itkPoint3D = originalValues; mitk::Point3D point3D = valuesToCopy; itkPoint3D = point3D; TestForEquality(itkPoint3D, point3D, "itk::Point", "mitk:Point"); } void Itk2Mitk_PointCompatibility() { mitk::Point3D point3D = originalValues; itk::Point itkPoint3D = valuesToCopy; point3D = itkPoint3D; TestForEquality(point3D, itkPoint3D, "mitk:Point", "itk::Point"); } void Vtk2Mitk_PointCompatibility() { mitk::Point3D point3D = originalValues; a_vtkPoints->InsertNextPoint(valuesToCopy); double vtkPoint[3]; a_vtkPoints->GetPoint(0, vtkPoint); point3D = vtkPoint; TestForEquality(point3D, vtkPoint, "mitk:Point", "vtkPoint"); } void Mitk2Pod_PointCompatibility() { ScalarType podPoint[] = {1.0, 2.0, 3.0}; mitk::Point3D point3D = valuesToCopy; point3D.ToArray(podPoint); TestForEquality(podPoint, point3D, "POD point", "mitk::Point"); } void Pod2Mitk_PointCompatibility() { itk::Point point3D = originalValues; ScalarType podPoint[] = {4.0, 5.0, 6.0}; point3D = podPoint; TestForEquality(point3D, podPoint, "mitk::Point3D", "POD point"); } void Vector2Point() { itk::Point point3D = valuesToCopy; itk::Vector vector3D = originalValues; point3D = vector3D; TestForEquality(point3D, vector3D, "mitk::Point", "mitk::Vector"); } }; MITK_TEST_SUITE_REGISTRATION(mitkPointTypeConversion) diff --git a/Core/Code/Testing/mitkSurfaceTest.cpp b/Core/Code/Testing/mitkSurfaceTest.cpp index ec34335597..d3b475963d 100644 --- a/Core/Code/Testing/mitkSurfaceTest.cpp +++ b/Core/Code/Testing/mitkSurfaceTest.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 "mitkSurface.h" #include "mitkCommon.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "mitkTestingMacros.h" #include "vtkPolyData.h" #include "vtkSphereSource.h" #include int mitkSurfaceTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN("Surface"); mitk::Surface::Pointer surface = mitk::Surface::New(); MITK_TEST_CONDITION_REQUIRED( surface.GetPointer(), "Testing initialization!" ); mitk::Surface::Pointer cloneSurface = surface->Clone(); MITK_TEST_CONDITION_REQUIRED( cloneSurface.GetPointer(), "Testing clone surface initialization!" ); vtkSphereSource* sphereSource = vtkSphereSource::New(); sphereSource->SetCenter(0,0,0); sphereSource->SetRadius(5.0); sphereSource->SetThetaResolution(10); sphereSource->SetPhiResolution(10); sphereSource->Update(); vtkPolyData* polys = sphereSource->GetOutput(); MITK_TEST_CONDITION_REQUIRED(surface->GetVtkPolyData() == NULL, "Testing initial state of vtkPolyData"); surface->SetVtkPolyData( polys ); sphereSource->Delete(); MITK_TEST_CONDITION_REQUIRED(surface->GetVtkPolyData()!= NULL, "Testing set vtkPolyData"); cloneSurface= NULL; cloneSurface = surface->Clone(); MITK_TEST_CONDITION_REQUIRED(cloneSurface->GetVtkPolyData()!= NULL, "Testing set vtkPolyData of cloned surface!"); cloneSurface = NULL; double bounds[6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; polys->ComputeBounds(); polys->GetBounds( bounds ); surface->UpdateOutputInformation(); surface->SetRequestedRegionToLargestPossibleRegion(); mitk::BoundingBox* bb = const_cast(surface->GetGeometry()->GetBoundingBox()); mitk::BoundingBox::BoundsArrayType surfBounds = bb->GetBounds(); bool passed = false; if ( bounds[0] == surfBounds[0] && bounds[1] == surfBounds[1] && bounds[2] == surfBounds[2] && bounds[3] == surfBounds[3] && bounds[4] == surfBounds[4] && bounds[5] == surfBounds[5] ) { passed = true; } MITK_TEST_CONDITION_REQUIRED(passed, "Testing GetBoundingBox()!"); surface->Expand(5); surface->Update(); surface->SetRequestedRegionToLargestPossibleRegion(); mitk::Surface::RegionType requestedRegion = surface->GetRequestedRegion(); MITK_TEST_CONDITION_REQUIRED(requestedRegion.GetSize(3) == 5, "Testing mitk::Surface::Expand( timesteps ): "); double boundsMat[5][6]; for (int i=0;i<5;i++) { vtkSphereSource* sphereSource = vtkSphereSource::New(); sphereSource->SetCenter(0,0,0); sphereSource->SetRadius(1.0 * (i+1.0)); sphereSource->SetThetaResolution(10); sphereSource->SetPhiResolution(10); sphereSource->Update(); sphereSource->GetOutput()->ComputeBounds(); sphereSource->GetOutput()->GetBounds( boundsMat[i] ); surface->SetVtkPolyData( sphereSource->GetOutput(),i ); sphereSource->Delete(); } surface->UpdateOutputInformation(); surface->SetRequestedRegionToLargestPossibleRegion(); passed = true; for (int i=0;i<5;i++) { mitk::BoundingBox::BoundsArrayType surfBounds = (const_cast(surface->GetTimeGeometry()->GetGeometryForTimeStep(i)->GetBoundingBox()))->GetBounds(); if ( boundsMat[i][0] != surfBounds[0] || boundsMat[i][1] != surfBounds[1] || boundsMat[i][2] != surfBounds[2] || boundsMat[i][3] != surfBounds[3] || boundsMat[i][4] != surfBounds[4] || boundsMat[i][5] != surfBounds[5] ) { passed = false; break; } } MITK_TEST_CONDITION_REQUIRED(passed, "Testing mitk::Surface::Testing 4D surface data creation!" ); const mitk::TimeGeometry* inputTimeGeometry = surface->GetUpdatedTimeGeometry(); int time = 3; int timestep=0; timestep = inputTimeGeometry->TimePointToTimeStep( time ); MITK_TEST_CONDITION_REQUIRED(time == timestep, "Testing correctness of geometry for surface->GetUpdatedTimeGeometry()!"); sphereSource = vtkSphereSource::New(); sphereSource->SetCenter(0,0,0); sphereSource->SetRadius( 100.0 ); sphereSource->SetThetaResolution(10); sphereSource->SetPhiResolution(10); sphereSource->Update(); surface->SetVtkPolyData( sphereSource->GetOutput(), 3 ); sphereSource->Delete(); inputTimeGeometry = surface->GetUpdatedTimeGeometry(); time = 3; timestep=0; timestep = inputTimeGeometry->TimePointToTimeStep( time ); MITK_TEST_CONDITION_REQUIRED(time == timestep, "Explicitly changing the data of timestep 3 and checking for timebounds correctness of surface's geometry again!"); unsigned int numberoftimesteps = surface->GetTimeSteps(); mitk::Surface::Pointer dummy = mitk::Surface::New(); dummy->Graft(surface); MITK_TEST_CONDITION_REQUIRED( dummy->GetVtkPolyData() != NULL, "Testing copying a Surface with Graft()!"); MITK_TEST_CONDITION_REQUIRED( dummy->GetTimeSteps() == numberoftimesteps, "orig-numberofTimeSteps:" << numberoftimesteps << " copy-numberofTimeSteps:" << dummy->GetTimeSteps()); surface = NULL; MITK_TEST_CONDITION_REQUIRED( surface.IsNull(), "Testing destruction of surface!"); MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkSurfaceToSurfaceFilterTest.cpp b/Core/Code/Testing/mitkSurfaceToSurfaceFilterTest.cpp index d4e746041c..7f26be3e42 100644 --- a/Core/Code/Testing/mitkSurfaceToSurfaceFilterTest.cpp +++ b/Core/Code/Testing/mitkSurfaceToSurfaceFilterTest.cpp @@ -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. ===================================================================*/ #include "mitkSurface.h" #include "mitkSurfaceToSurfaceFilter.h" #include "mitkCommon.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "vtkPolyData.h" #include "vtkSphereSource.h" #include int mitkSurfaceToSurfaceFilterTest(int /*argc*/, char* /*argv*/[]) { mitk::Surface::Pointer surface; surface = mitk::Surface::New(); vtkSphereSource* sphereSource = vtkSphereSource::New(); sphereSource->SetCenter(0,0,0); sphereSource->SetRadius(5.0); sphereSource->SetThetaResolution(10); sphereSource->SetPhiResolution(10); sphereSource->Update(); vtkPolyData* polys = sphereSource->GetOutput(); surface->SetVtkPolyData( polys ); sphereSource->Delete(); mitk::SurfaceToSurfaceFilter::Pointer filter = mitk::SurfaceToSurfaceFilter::New(); std::cout << "Testing mitk::SurfaceToSurfaceFilter::SetInput() and ::GetNumberOfInputs() : " ; filter->SetInput( surface ); if ( filter->GetNumberOfInputs() < 1 ) { std::cout<<"[FAILED] : zero inputs set "<GetInput() != surface ) { std::cout<<"[FAILED] : GetInput does not return correct input. "<GetInput(5) != NULL ) { std::cout<<"[FAILED] : GetInput returns inputs that were not set. "< is NULL" << std::endl; std::cout << "Testing whether Output is created correctly : " << std::endl; if ( filter->GetNumberOfOutputs() != filter->GetNumberOfInputs() ) { std::cout <<"[FAILED] : number of outputs != number of inputs" << std::endl; return EXIT_FAILURE; } std::cout << "[SUCCESS] : number of inputs == number of outputs." << std::endl; mitk::Surface::Pointer outputSurface = filter->GetOutput(); if ( outputSurface->GetVtkPolyData()->GetNumberOfPolys() != surface->GetVtkPolyData()->GetNumberOfPolys() ) { std::cout << "[FAILED] : number of Polys in PolyData of output != number of Polys in PolyData of input" << std::endl; return EXIT_FAILURE; } std::cout << "[SUCCESS] : number of Polys in PolyData of input and output are identical." << std::endl; filter->Update(); outputSurface = filter->GetOutput(); if ( outputSurface->GetSizeOfPolyDataSeries() != surface->GetSizeOfPolyDataSeries() ) { std::cout << "[FAILED] : number of PolyDatas in PolyDataSeries of output != number of PolyDatas of input" << std::endl; return EXIT_FAILURE; } std::cout << "[SUCCESS] : Size of PolyDataSeries of input and output are identical." << std::endl; //std::cout << "Testing RemoveInputs() : " << std::endl; //unsigned int numOfInputs = filter->GetNumberOfInputs(); //filter->RemoveInputs( mitk::Surface::New() ); //if ( filter->GetNumberOfInputs() != numOfInputs ) //{ // std::cout << "[FAILED] : input was removed that was not set." << std::endl; // return EXIT_FAILURE; //} //std::cout << "[SUCCESS] : no input was removed that was not set." << std::endl; //filter->RemoveInputs( surface ); //if ( filter->GetNumberOfInputs() != 0 ) //{ // std::cout << "[FAILED] : existing input was not removed correctly." << std::endl; // return EXIT_FAILURE; //} //std::cout << "[SUCCESS] : existing input was removed correctly." << std::endl; std::cout<<"[TEST DONE]"< +#include #include #include #include #include #include static const std::string filename = itksys::SystemTools::GetCurrentWorkingDirectory() + "/TinyXMLTest.txt"; static const std::string elementToStoreAttributeName = "DoubleTest"; static const std::string attributeToStoreName = "CommaValue"; static double calcPrecision(const unsigned int requiredDecimalPlaces) { return pow(10.0, -1.0 * ((double) requiredDecimalPlaces)); } /** * create a simple xml document which stores the values * @param valueToWrite value which should be stored * @return true, if document was successfully created. */ static bool Setup(double valueToWrite) { // 1. create simple document TiXmlDocument document; TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" ); // TODO what to write here? encoding? etc.... document.LinkEndChild( decl ); TiXmlElement* version = new TiXmlElement("Version"); version->SetAttribute("Writer", __FILE__ ); version->SetAttribute("CVSRevision", "$Revision: 17055 $" ); version->SetAttribute("FileVersion", 1 ); document.LinkEndChild(version); // 2. store one element containing a double value with potentially many after comma digits. TiXmlElement* vElement = new TiXmlElement( elementToStoreAttributeName ); vElement->SetDoubleAttribute( attributeToStoreName, valueToWrite ); document.LinkEndChild(vElement); // 3. store in file. return document.SaveFile( filename ); } static int readValueFromSetupDocument(double& readOutValue) { TiXmlDocument document; if (!document.LoadFile(filename)) { MITK_TEST_CONDITION_REQUIRED(false, "Test Setup failed, could not open " << filename); return TIXML_NO_ATTRIBUTE; } else { TiXmlElement* doubleTest = document.FirstChildElement(elementToStoreAttributeName); return doubleTest->QueryDoubleAttribute(attributeToStoreName, &readOutValue); } } /** * * @return true if TearDown was successful. */ static bool TearDown() { return !remove(filename.c_str()); } static void Test_Setup_works() { MITK_TEST_CONDITION_REQUIRED(Setup(1.0) && TearDown(), "Test if setup and teardown correctly writes data to " << filename << " and deletes the file after the test"); } /** * this first test ensures we can correctly readout values from the * TinyXMLDocument. */ static void Test_ReadOutValue_works() { Setup(1.0); double readValue; MITK_TEST_CONDITION_REQUIRED(TIXML_SUCCESS == readValueFromSetupDocument(readValue), "checking if readout mechanism works."); } static void Test_DoubleValueWriteOut() { const double valueToWrite = -1.123456; const int validDigitsAfterComma = 6; // indicates the number of valid digits after comma of valueToWrite const double neededPrecision = calcPrecision(validDigitsAfterComma + 1); double readValue; Setup(valueToWrite); readValueFromSetupDocument(readValue); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(valueToWrite, readValue, neededPrecision), std::setprecision(validDigitsAfterComma) << "Testing if value " << valueToWrite << " equals " << readValue << " which was retrieved from TinyXML document"); TearDown(); } static void Test_DoubleValueWriteOut_manyDecimalPlaces() { const double valueToWrite = -1.12345678910111; const int validDigitsAfterComma = 14; // indicates the number of valid digits after comma of valueToWrite const double neededPrecision = calcPrecision(validDigitsAfterComma + 1); double readValue; Setup(valueToWrite); readValueFromSetupDocument(readValue); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(valueToWrite, readValue, neededPrecision), std::setprecision(validDigitsAfterComma) << "Testing if value " << valueToWrite << " equals " << readValue << " which was retrieved from TinyXML document"); TearDown(); } int mitkTinyXMLTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("TinyXMLTest"); Test_Setup_works(); Test_ReadOutValue_works(); Test_DoubleValueWriteOut(); Test_DoubleValueWriteOut_manyDecimalPlaces(); MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkVectorTest.cpp b/Core/Code/Testing/mitkVectorTest.cpp index 22cd80829c..e91de13f2c 100644 --- a/Core/Code/Testing/mitkVectorTest.cpp +++ b/Core/Code/Testing/mitkVectorTest.cpp @@ -1,141 +1,141 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 int mitkVectorTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN("mitkVector"); // test itk vector equality methods itk::Vector itkVector_1; itkVector_1[0] = 4.6; itkVector_1[1] = 9.76543; itkVector_1[2] = 746.09; itk::Vector itkVector_2; itk::Vector itkVector_3; for (int i=0; i<3; i++) { itkVector_2[i] = itkVector_1[i] - mitk::eps*1.1; itkVector_3[i] = itkVector_1[i] - mitk::eps*0.9; } MITK_TEST_CONDITION(mitk::Equal(itkVector_1,itkVector_1), "Test vector equality using the same vector with mitk::eps"); MITK_TEST_CONDITION(!mitk::Equal(itkVector_1,itkVector_2), "Test vector equality using different vectors with an element-wise difference greater than mitk::eps"); MITK_TEST_CONDITION( mitk::Equal(itkVector_1, itkVector_2, mitk::eps*1.2), "Vectors are equal for higher epsilon tolerance ( 1.2 * mitk::eps )"); MITK_TEST_CONDITION(mitk::Equal(itkVector_1,itkVector_3), "Test vector equality using different vectors with an element-wise difference less than mitk::eps"); // test itk point equality methods itk::Point itkPoint_1; itk::Point itkPoint_2; itk::Point itkPoint_3; for (int i=0; i<3; i++) { itkPoint_1[i] = itkVector_1[i]; itkPoint_2[i] = itkVector_2[i]; itkPoint_3[i] = itkVector_3[i]; } MITK_TEST_CONDITION(mitk::Equal(itkPoint_1,itkPoint_1), "Test point equality using the same point with mitk::eps"); MITK_TEST_CONDITION(!mitk::Equal(itkPoint_1,itkPoint_2), "Test point equality using different points with an element-wise difference greater than mitk::eps"); MITK_TEST_CONDITION( mitk::Equal(itkPoint_1, itkPoint_2, mitk::eps * 1.2), "Points are equal for higher epsilon tolerance ( 1.2 * mitk::eps )"); MITK_TEST_CONDITION(mitk::Equal(itkPoint_1,itkPoint_3), "Test point equality using different points with an element-wise difference less than mitk::eps"); // test mitk vnl vector equality methods mitk::VnlVector mitk_vnl_vector_1(3); mitk::VnlVector mitk_vnl_vector_2(3); mitk::VnlVector mitk_vnl_vector_3(3); for (int i=0; i<3; i++) { mitk_vnl_vector_1.put(i,itkVector_1[i]); mitk_vnl_vector_2.put(i,itkVector_2[i]); mitk_vnl_vector_3.put(i,itkVector_1[i]); } MITK_TEST_CONDITION(mitk::Equal(mitk_vnl_vector_1,mitk_vnl_vector_1), "Test mitk vnl vector equality using the same mitk vnl vector with mitk::eps"); MITK_TEST_CONDITION(!mitk::Equal(mitk_vnl_vector_1,mitk_vnl_vector_2), "Test mitk vnl vector equality using different mitk vnl vectors with an element-wise difference greater than mitk::eps"); MITK_TEST_CONDITION( mitk::Equal(mitk_vnl_vector_1, mitk_vnl_vector_2, mitk::eps*1.2), "Vnl vectors are equal for higher epsilon tolerance ( 1.2 * mitk::eps )"); MITK_TEST_CONDITION(mitk::Equal(mitk_vnl_vector_1,mitk_vnl_vector_3), "Test mitk vnl vector equality using different mitk vnl vectors with an element-wise difference less than mitk::eps"); // test vnl_vector equality method typedef mitk::ScalarType VnlValueType; vnl_vector_fixed vnlVector_1; vnlVector_1[3] = 56.98; vnlVector_1[4] = 22.32; vnlVector_1[5] = 1.00; vnlVector_1[6] = 746.09; vnl_vector_fixed vnlVector_2; vnl_vector_fixed vnlVector_3; for (int i=0; i<7; i++) { if (i<3) { vnlVector_1.put(i,itkVector_1[i]); } vnlVector_2[i] = vnlVector_1[i] - mitk::eps * 1.1f; vnlVector_3[i] = vnlVector_1[i] - mitk::eps * 0.9f; } MITK_TEST_CONDITION( (mitk::Equal(vnlVector_1,vnlVector_1)), "vnl_fixed : v_1 == v_1 "); // the v_2 is constructed so that the equality test fails for mitk::eps, the norm of the difference between the vectors is 7 * eps/6.9 MITK_TEST_CONDITION(!(mitk::Equal(vnlVector_1,vnlVector_2)), "vnl_fixed : v_1 != v_2 with mitk::eps "); // increase the epsilon value used for testing equality - should now pass ( 1.2 * mitk::eps > 7 * mitk::eps/6.9 ) MITK_TEST_CONDITION( (mitk::Equal(vnlVector_1,vnlVector_2, mitk::eps*1.2f)) , "vnl_fixed : v_1 == v_2 with eps = 1.2 * mitk::eps "); MITK_TEST_CONDITION( (mitk::Equal(vnlVector_1,vnlVector_3, mitk::eps)), "vnl_fixed : v_1 == v_3 with eps = 0.8 * mitk::eps "); MITK_TEST_CONDITION(!(mitk::Equal(vnlVector_1,vnlVector_3, mitk::eps*0.8f)), "vnl_fixed : v_1 != v_3 with eps = 0.8 * mitk::eps "); // test scalar equality method mitk::ScalarType scalar1 = 0.5689; mitk::ScalarType scalar2 = scalar1 + mitk::eps*1.01; mitk::ScalarType scalar3 = scalar1; mitk::ScalarType scalar4 = scalar1 + mitk::eps*0.95; MITK_TEST_CONDITION(mitk::Equal(scalar1,scalar1), "Test scalar equality using the same scalar with mitk::eps"); MITK_TEST_CONDITION(!mitk::Equal(scalar1,scalar2), "Test scalar equality using the different scalars with a difference greater than mitk::eps"); MITK_TEST_CONDITION(mitk::Equal(scalar1,scalar3), "Test scalar equality using the different scalars with a difference equal to mitk::eps"); MITK_TEST_CONDITION(mitk::Equal(scalar1,scalar4), "Test scalar equality using the different scalars with a difference less than mitk::eps"); // test matrix equality methods vnl_matrix_fixed vnlMatrix3x3_1; vnlMatrix3x3_1(0,0) = 1.1; vnlMatrix3x3_1(0,1) = 0.4; vnlMatrix3x3_1(0,2) = 5.3; vnlMatrix3x3_1(1,0) = 2.7; vnlMatrix3x3_1(1,1) = 3578.56418; vnlMatrix3x3_1(1,2) = 123.56; vnlMatrix3x3_1(2,0) = 546.89; vnlMatrix3x3_1(2,1) = 0.0001; vnlMatrix3x3_1(2,2) = 1.0; vnl_matrix_fixed vnlMatrix3x3_2; vnlMatrix3x3_2(0,0) = 1.1000009; vnlMatrix3x3_2(0,1) = 0.4000009; vnlMatrix3x3_2(0,2) = 5.3000009; vnlMatrix3x3_2(1,0) = 2.7000009; vnlMatrix3x3_2(1,1) = 3578.5641809; vnlMatrix3x3_2(1,2) = 123.5600009; vnlMatrix3x3_2(2,0) = 546.8900009; vnlMatrix3x3_2(2,1) = 0.0001009; vnlMatrix3x3_2(2,2) = 1.0000009; mitk::ScalarType epsilon = 0.000001; MITK_TEST_CONDITION(mitk::MatrixEqualElementWise(vnlMatrix3x3_1,vnlMatrix3x3_1,mitk::eps),"Test for matrix equality with given epsilon=mitk::eps and exactly the same matrix elements"); MITK_TEST_CONDITION(!mitk::MatrixEqualElementWise(vnlMatrix3x3_1,vnlMatrix3x3_2,0.0),"Test for matrix equality with given epsilon=0.0 and slightly different matrix elements"); MITK_TEST_CONDITION(mitk::MatrixEqualElementWise(vnlMatrix3x3_1,vnlMatrix3x3_2,epsilon),"Test for matrix equality with given epsilon and slightly different matrix elements"); MITK_TEST_CONDITION(!mitk::MatrixEqualRMS(vnlMatrix3x3_1,vnlMatrix3x3_2,0.0),"Test for matrix equality with given epsilon=0.0 and slightly different matrix elements"); MITK_TEST_CONDITION(mitk::MatrixEqualRMS(vnlMatrix3x3_1,vnlMatrix3x3_2,epsilon),"Test for matrix equality with given epsilon and slightly different matrix elements"); MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkVectorTypeConversionTest.cpp b/Core/Code/Testing/mitkVectorTypeConversionTest.cpp index a9d9f8cda2..6d02c7300a 100644 --- a/Core/Code/Testing/mitkVectorTypeConversionTest.cpp +++ b/Core/Code/Testing/mitkVectorTypeConversionTest.cpp @@ -1,264 +1,264 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "itkVector.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include #include "vnl/vnl_math.h" -#include "mitkConstants.h" +#include "mitkNumericConstants.h" #include "mitkVector.h" #include "mitkPoint.h" using namespace mitk; class mitkVectorTypeConversionTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkVectorTypeConversionTestSuite); MITK_TEST(Point2Vector); MITK_TEST(Pod2Mitk); MITK_TEST(Mitk2Pod); MITK_TEST(OneElement2Mitk); MITK_TEST(Itk2Mitk); MITK_TEST(Mitk2Itk); MITK_TEST(Vnlfixed2Mitk); MITK_TEST(Mitk2Vnlfixed); MITK_TEST(Vnl2Mitk); MITK_TEST(Mitk2Vnl); MITK_TEST(Vnl2Mitk_WrongVnlVectorSize); MITK_TEST(ToArray_DifferentType); - MITK_TEST(FromArray_DifferentType); + MITK_TEST(Fill_DifferentType); CPPUNIT_TEST_SUITE_END(); private: /** * these variables are used in the test functions * * The variable which should be copied into is set to its original value. * The value which should be copied is set to valuesToCopy. * * Then the copying takes place. The test is successful, if the variable which * should be copied into holds the valuesToCopy afterwards and is equal to the * vector which should be copied. */ ScalarType originalValues[3]; ScalarType valuesToCopy[3]; float epsDouble2Float; /** * @brief Convenience method to test if one vector has been assigned successfully to the other. * * More specifically, tests if v1 = v2 was performed correctly. * * @param v1 The vector v1 of the assignment v1 = v2 * @param v2 The vector v2 of the assignment v1 = v2 * @param v1Name The type name of v1 (e.g.: mitk::Vector3D). Necessary for the correct test output. * @param v2Name The type name of v2 (e.g.: mitk::Vector3D). Necessary for the correct test output. * @param eps defines the allowed tolerance when testing for equality. */ template - void TestForEquality(T1 v1, T2 v2, std::string v1Name, std::string v2Name, ScalarType eps = mitk::eps) + void TestForEquality(const T1& v1, const T2& v2, const std::string& v1Name, const std::string& v2Name, const ScalarType& eps = mitk::eps) const { CPPUNIT_ASSERT_EQUAL_MESSAGE("\nAssigning " + v2Name + " to " + v1Name + ":\n both are equal", true, EqualArray(v1, v2, 3, eps)); } public: void setUp(void) { FillVector3D(originalValues, 1.123456789987, 2.789456321456, 3.123654789987456); FillVector3D(valuesToCopy, 4.654789123321, 5.987456789321, 6.321654987789546); epsDouble2Float = vnl_math::float_eps * 10.0; } void tearDown(void) { } void Pod2Mitk(void) { mitk::Vector3D vector3D = valuesToCopy; TestForEquality(vector3D, valuesToCopy, "mitk::Vector3D", "double POD"); } void Mitk2Pod(void) { ScalarType podArray[3]; mitk::Vector3D vector3D = valuesToCopy; vector3D.ToArray(podArray); TestForEquality(podArray, vector3D, "double POD", "mitk::Vector3D"); } void OneElement2Mitk(void) { double twos[] = {2.0, 2.0, 2.0}; mitk::Vector vector3D(2.0); CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE( "\n one values initializes all elements to this value", EqualArray(vector3D, twos, 3)); } void Itk2Mitk(void) { Vector3D vector3D = originalValues; itk::Vector itkVector = valuesToCopy; vector3D = itkVector; TestForEquality(vector3D, itkVector, "mitk::Vector3D", "itk::Vector"); } void Mitk2Itk(void) { Vector3D vector3D = valuesToCopy; itk::Vector itkVector = originalValues; itkVector = vector3D; TestForEquality(itkVector, vector3D, "itk::Vector", "mitk::Vector3D"); } void Vnlfixed2Mitk(void) { mitk::Vector3D vector3D = originalValues; vnl_vector_fixed vnlVectorFixed(valuesToCopy); vector3D = vnlVectorFixed; TestForEquality(vector3D, vnlVectorFixed, "mitk::Vector3D", "vnl_vector_fixed"); } void Mitk2Vnlfixed(void) { vnl_vector_fixed vnlVectorFixed(originalValues); mitk::Vector3D vector3D = valuesToCopy; vnlVectorFixed = vector3D; TestForEquality(vnlVectorFixed, vector3D, "vnl_vector_fixed", "mitk::Vector3D"); } void Vnl2Mitk(void) { mitk::Vector3D vector3D = originalValues; vnl_vector vnlVector(3); vnlVector.set(valuesToCopy); vector3D = vnlVector; TestForEquality(vector3D, vnlVector, "mitk::Vector3D", "vnl_vector"); } void Mitk2Vnl(void) { vnl_vector vnlVector(3); vnlVector.set(originalValues); mitk::Vector3D vector3D = valuesToCopy; vnlVector = vector3D; TestForEquality(vnlVector, vector3D, "vnl_vector", "mitk::Vector3D"); } /** * @brief Tests if an exception is thrown when constructing an mitk::Vector form a vnl_vector of not suited size. */ void Vnl2Mitk_WrongVnlVectorSize() { ScalarType largerValuesToCopy[] = {4.12345678910, 5.10987654321, 6.123456789132456, 7.123456987789456}; mitk::Vector3D vector3D = originalValues; vnl_vector vnlVector(4); vnlVector.set(largerValuesToCopy); CPPUNIT_ASSERT_THROW(vector3D = vnlVector, mitk::Exception); } void ToArray_DifferentType(void) { float podArray[3]; for (int var = 0; var < 3; ++var) { podArray[var] = originalValues[var]; } mitk::Vector3D vector3D = valuesToCopy; vector3D.ToArray(podArray); TestForEquality(podArray, vector3D, "float POD", "mitk::Vector3D", epsDouble2Float); } - void FromArray_DifferentType(void) + void Fill_DifferentType(void) { mitk::Vector3D vector3D = originalValues; float podArray[3]; for (int var = 0; var < 3; ++var) { podArray[var] = valuesToCopy[var]; } - vector3D.FromArray(podArray); + vector3D.FillVector(podArray); TestForEquality(vector3D, podArray, "mitk::Vector3D", "float POD", epsDouble2Float); } void Point2Vector() { mitk::Point3D point3D = originalValues; mitk::Vector3D vector3D = valuesToCopy; vector3D = point3D.GetVectorFromOrigin(); TestForEquality(point3D, vector3D, "mitk::Point3D", "mitk::Vector3D"); } }; MITK_TEST_SUITE_REGISTRATION(mitkVectorTypeConversion) diff --git a/Core/Code/files.cmake b/Core/Code/files.cmake index ce55baf543..a622a8d4c5 100644 --- a/Core/Code/files.cmake +++ b/Core/Code/files.cmake @@ -1,412 +1,412 @@ set(H_FILES Algorithms/itkImportMitkImageContainer.h Algorithms/itkImportMitkImageContainer.txx Algorithms/itkMITKScalarImageToHistogramGenerator.h Algorithms/itkMITKScalarImageToHistogramGenerator.txx Algorithms/mitkInstantiateAccessFunctions.h Algorithms/mitkPixelTypeList.h 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 Algorithms/mitkConvert2Dto3DImageFilter.h Algorithms/mitkPlaneClipping.h Common/mitkCommon.h Common/mitkExceptionMacro.h DataManagement/mitkProportionalTimeGeometry.h DataManagement/mitkTimeGeometry.h DataManagement/mitkImageAccessByItk.h DataManagement/mitkImageCast.h DataManagement/mitkImagePixelAccessor.h DataManagement/mitkImagePixelReadAccessor.h DataManagement/mitkImagePixelWriteAccessor.h DataManagement/mitkImageReadAccessor.h DataManagement/mitkImageWriteAccessor.h DataManagement/mitkITKImageImport.h DataManagement/mitkITKImageImport.txx DataManagement/mitkImageToItk.h DataManagement/mitkShaderProperty.h DataManagement/mitkImageToItk.txx DataManagement/mitkTimeSlicedGeometry.h # Deprecated, empty for compatibilty reasons. DataManagement/mitkPropertyListReplacedObserver.cpp DataManagement/mitkVectorDeprecated.h DataManagement/mitkArray.h DataManagement/mitkQuaternion.h - DataManagement/mitkTypes.h + DataManagement/mitkNumericTypes.h DataManagement/mitkVector.h DataManagement/mitkPoint.h DataManagement/mitkMatrix.h Interactions/mitkEventMapperAddOn.h Interfaces/mitkIDataNodeReader.h Rendering/mitkLocalStorageHandler.h Rendering/Colortables/HotIron.h Rendering/Colortables/Jet.h Rendering/Colortables/PET20.h Rendering/Colortables/PETColor.h IO/mitkPixelTypeTraits.h ) set(CPP_FILES Algorithms/mitkBaseDataSource.cpp Algorithms/mitkCompareImageDataFilter.cpp Algorithms/mitkMultiComponentImageDataComparisonFilter.cpp Algorithms/mitkDataNodeSource.cpp Algorithms/mitkGeometry2DDataToSurfaceFilter.cpp Algorithms/mitkHistogramGenerator.cpp Algorithms/mitkImageChannelSelector.cpp Algorithms/mitkImageSliceSelector.cpp Algorithms/mitkImageSource.cpp Algorithms/mitkImageTimeSelector.cpp Algorithms/mitkImageToImageFilter.cpp Algorithms/mitkImageToSurfaceFilter.cpp Algorithms/mitkPointSetSource.cpp Algorithms/mitkPointSetToPointSetFilter.cpp Algorithms/mitkRGBToRGBACastImageFilter.cpp Algorithms/mitkSubImageSelector.cpp Algorithms/mitkSurfaceSource.cpp Algorithms/mitkSurfaceToImageFilter.cpp Algorithms/mitkSurfaceToSurfaceFilter.cpp Algorithms/mitkUIDGenerator.cpp Algorithms/mitkVolumeCalculator.cpp Algorithms/mitkClippedSurfaceBoundsCalculator.cpp Algorithms/mitkExtractSliceFilter.cpp Algorithms/mitkConvert2Dto3DImageFilter.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/mitkProportionalTimeGeometry.cpp DataManagement/mitkTimeGeometry.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/mitkImageAccessorBase.cpp DataManagement/mitkImageCaster.cpp DataManagement/mitkImageCastPart1.cpp DataManagement/mitkImageCastPart2.cpp DataManagement/mitkImageCastPart3.cpp DataManagement/mitkImageCastPart4.cpp DataManagement/mitkImageDataItem.cpp DataManagement/mitkImageDescriptor.cpp DataManagement/mitkImageVtkAccessor.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/mitkPropertyObserver.cpp DataManagement/mitkRestorePlanePositionOperation.cpp DataManagement/mitkApplyTransformMatrixOperation.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/mitkTransferFunction.cpp DataManagement/mitkTransferFunctionProperty.cpp DataManagement/mitkTransferFunctionInitializer.cpp DataManagement/mitkVector.cpp - DataManagement/mitkConstants.cpp + DataManagement/mitkNumericConstants.cpp DataManagement/mitkVtkInterpolationProperty.cpp DataManagement/mitkVtkRepresentationProperty.cpp DataManagement/mitkVtkResliceInterpolationProperty.cpp DataManagement/mitkVtkScalarModeProperty.cpp DataManagement/mitkVtkVolumeRenderingProperty.cpp DataManagement/mitkWeakPointerProperty.cpp DataManagement/mitkRenderingModeProperty.cpp DataManagement/mitkResliceMethodProperty.cpp DataManagement/mitkMaterial.cpp DataManagement/mitkPointSetShapeProperty.cpp DataManagement/mitkFloatPropertyExtension.cpp DataManagement/mitkIntPropertyExtension.cpp DataManagement/mitkPropertyExtension.cpp DataManagement/mitkPropertyFilter.cpp DataManagement/mitkPropertyAliases.cpp DataManagement/mitkPropertyDescriptions.cpp DataManagement/mitkPropertyExtensions.cpp DataManagement/mitkPropertyFilters.cpp DataManagement/mitkShaderProperty.cpp Interactions/mitkAction.cpp Interactions/mitkAffineInteractor.cpp Interactions/mitkBindDispatcherInteractor.cpp Interactions/mitkCoordinateSupplier.cpp Interactions/mitkDataInteractor.cpp Interactions/mitkDispatcher.cpp Interactions/mitkDisplayCoordinateOperation.cpp Interactions/mitkDisplayInteractor.cpp Interactions/mitkDisplayPositionEvent.cpp # Interactions/mitkDisplayVectorInteractorLevelWindow.cpp # legacy, prob even now unneeded # Interactions/mitkDisplayVectorInteractorScroll.cpp Interactions/mitkEvent.cpp Interactions/mitkEventConfig.cpp Interactions/mitkEventDescription.cpp Interactions/mitkEventFactory.cpp Interactions/mitkInteractionEventHandler.cpp Interactions/mitkEventMapper.cpp Interactions/mitkEventRecorder.cpp Interactions/mitkEventStateMachine.cpp Interactions/mitkGlobalInteraction.cpp Interactions/mitkInteractor.cpp Interactions/mitkInternalEvent.cpp Interactions/mitkInteractionEvent.cpp Interactions/mitkInteractionEventConst.cpp Interactions/mitkInteractionPositionEvent.cpp Interactions/mitkInteractionKeyEvent.cpp Interactions/mitkMousePressEvent.cpp Interactions/mitkMouseMoveEvent.cpp Interactions/mitkMouseReleaseEvent.cpp Interactions/mitkMouseWheelEvent.cpp Interactions/mitkMouseDoubleClickEvent.cpp Interactions/mitkMouseModeSwitcher.cpp Interactions/mitkMouseMovePointSetInteractor.cpp Interactions/mitkMoveBaseDataInteractor.cpp Interactions/mitkNodeDepententPointSetInteractor.cpp Interactions/mitkPointSetDataInteractor.cpp Interactions/mitkPointSetInteractor.cpp Interactions/mitkPositionEvent.cpp Interactions/mitkPositionTracker.cpp Interactions/mitkStateMachineAction.cpp Interactions/mitkStateMachineCondition.cpp Interactions/mitkStateMachineState.cpp Interactions/mitkStateMachineTransition.cpp Interactions/mitkState.cpp Interactions/mitkStateMachineContainer.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 Interactions/mitkXML2EventParser.cpp Interfaces/mitkInteractionEventObserver.cpp Interfaces/mitkIShaderRepository.cpp Interfaces/mitkIPropertyAliases.cpp Interfaces/mitkIPropertyDescriptions.cpp Interfaces/mitkIPropertyExtensions.cpp Interfaces/mitkIPropertyFilters.cpp Interfaces/mitkIPersistenceService.cpp IO/mitkBaseDataIOFactory.cpp IO/mitkCoreDataNodeReader.cpp IO/mitkDicomSeriesReader.cpp IO/mitkDicomSR_LoadDICOMScalar.cpp IO/mitkDicomSR_LoadDICOMScalar4D.cpp IO/mitkDicomSR_LoadDICOMRGBPixel.cpp IO/mitkDicomSR_LoadDICOMRGBPixel4D.cpp IO/mitkDicomSR_ImageBlockDescriptor.cpp IO/mitkDicomSR_GantryTiltInformation.cpp IO/mitkDicomSR_SliceGroupingResult.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/mitkItkLoggingAdapter.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/mitkVtkLoggingAdapter.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/mitkVtkMapper.cpp Rendering/mitkRenderWindowFrame.cpp Rendering/mitkGeometry2DDataMapper2D.cpp Rendering/mitkGeometry2DDataVtkMapper3D.cpp Rendering/mitkGLMapper.cpp Rendering/mitkGradientBackground.cpp Rendering/mitkManufacturerLogo.cpp Rendering/mitkMapper.cpp Rendering/mitkPointSetGLMapper2D.cpp Rendering/mitkPointSetVtkMapper2D.cpp Rendering/mitkPointSetVtkMapper3D.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/mitkImageVtkMapper2D.cpp Rendering/vtkMitkThickSlicesFilter.cpp Rendering/vtkMitkLevelWindowFilter.cpp Rendering/vtkNeverTranslucentTexture.cpp Rendering/mitkOverlay.cpp Rendering/mitkVtkOverlay.cpp Rendering/mitkVtkOverlay2D.cpp Rendering/mitkVtkOverlay3D.cpp Rendering/mitkOverlayManager.cpp Rendering/mitkAbstractOverlayLayouter.cpp Rendering/mitkTextOverlay2D.cpp Rendering/mitkTextOverlay3D.cpp Rendering/mitkLabelOverlay3D.cpp Rendering/mitkOverlay2DLayouter.cpp Rendering/mitkScaleLegendOverlay Common/mitkException.cpp Common/mitkCommon.h Common/mitkCoreObjectFactoryBase.cpp Common/mitkCoreObjectFactory.cpp Common/mitkCoreServices.cpp ) set(RESOURCE_FILES Interactions/globalConfig.xml Interactions/DisplayInteraction.xml Interactions/DisplayConfig.xml Interactions/DisplayConfigPACS.xml Interactions/DisplayConfigPACSPan.xml Interactions/DisplayConfigPACSScroll.xml Interactions/DisplayConfigPACSZoom.xml Interactions/DisplayConfigPACSLevelWindow.xml Interactions/DisplayConfigMITK.xml Interactions/PointSet.xml Interactions/Legacy/StateMachine.xml Interactions/Legacy/DisplayConfigMITKTools.xml Interactions/PointSetConfig.xml mitkLevelWindowPresets.xml ) diff --git a/Core/Documentation/Doxygen/Concepts/BasicDataTypes.dox b/Core/Documentation/Doxygen/Concepts/BasicDataTypes.dox index 781f6493b7..d35e6a6d97 100644 --- a/Core/Documentation/Doxygen/Concepts/BasicDataTypes.dox +++ b/Core/Documentation/Doxygen/Concepts/BasicDataTypes.dox @@ -1,59 +1,60 @@ /** -\page BasicDataTypesPage Low level MITK data types and their usage. +\page BasicDataTypesPage Numeric MITK data types and their usage. This page describes how to use very foundational data-tyes in MITK like mitk::Vector, mitk::Point and mitk::Matrix and how they can interact. \tableofcontents \section Structure Structure The previously known, monolythic structure of putting every basic type into mitkVector.h has been broken and mitkVector.h has been split up into several, more atomic files, namely: --# mitkConstants.h : contains basic constants like mitk::ScalarType or mitk::eps +-# mitkNumericConstants.h : contains basic constants like mitk::ScalarType or mitk::eps -# mitkArray.h : copy itk::FixedArrays (like itk::Point and itk::Vector) from and to types which implement the [] operator (array-types), like e.g. Plain Old Datatypes (POD) or the opencv vector --# mitkPoint.h : the mitk::Point class. This is basically the itk::Point with the added ToArray and FromArray members to conveniently copy from and to array-types. In MITK, a point is considered a fixed geometric location and thus cannot be summed or multiplied. +-# mitkPoint.h : the mitk::Point class. This is basically the itk::Point with the added ToArray and Fill members to conveniently copy from and to array-types. In MITK, a point is considered a fixed geometric location and thus cannot be summed or multiplied. -# mitkVector.h : the mitk::Vector class. This is an itk::Vector, but with the possiblity to implicitly convert to vnl_vector and vnl_vector_fixed. In MITK, vectors denote directions and can be summed or multiplied with scalars. --# mitkMatrix.h : the mitk::Matrix class. This is an itk::Matrix with the added ToArray and FromArray members to conveniently copy from and to array-types. +-# mitkMatrix.h : the mitk::Matrix class. This is an itk::Matrix with the added ToArray and Fill members to conveniently copy from and to array-types. -# mitkQuaternion.h : a typedef to vnl_quaternion. --# mitkTypes.h : this file includes all of the above as a convenience header +-# mitkAffineTransform3D.h : a typedef to itk::AffineGeometryFrame +-# mitkNumericTypes.h : this file includes all of the above as a convenience header The Equal methods to compare Points, Vectors, Matrices, ... have been moved into the respective files. E.g., if you want to compare two vectors simply use the Equal method provided by mitkVector.h. \section Conversion Conversion between the data-types If you want to convert a mitk::Vector from or to a vnl_vector or a vnl_vector_fixed, simply write \code mitkVector3D = vnlVector3D; vnlVector3D_2 = mitkVector3D; \endcode -Unfortunately this mechanism couldn't be implemented to every type of conversion. But in any case, the ToArray and FromArray member +Unfortunately this mechanism couldn't be implemented to every type of conversion. But in any case, the ToArray and FillVector/FillPoint/FillMatrix member functions can be used to convert to array-types. E.g., \code cv::Vec3d cvVec3D; mitkVector3D.ToArray(cvVec3D); - mitkVector3D_2.FromArray(cvVec3D); + mitkVector3D_2.FillVector(cvVec3D); \endcode No implicit conversion from mitk::Point to mitk::Vector was implemented as this would break with itk's concept of separating points and vectors. If you want to convert, use: \code mitkVector3D = mitkPoint3D.GetVectorFromOrigin(); mitkPoint3D_2 = mitkVector3D; \endcode more examples of how to convert between data types can be found in the tests: -# mitkArrayTypeConversionTest.cpp -# mitkPointTypeConversionTest.cpp -# mitkVectorTypeConversionTest.cpp -# mitkMatrixTypeConversionTest.cpp */ \ No newline at end of file diff --git a/Modules/CameraCalibration/mitkCameraIntrinsics.h b/Modules/CameraCalibration/mitkCameraIntrinsics.h index a6dab84e0f..bf184d257d 100644 --- a/Modules/CameraCalibration/mitkCameraIntrinsics.h +++ b/Modules/CameraCalibration/mitkCameraIntrinsics.h @@ -1,144 +1,144 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 mitkCameraIntrinsics_h #define mitkCameraIntrinsics_h #include -#include +#include #include #include #include #include #include "mitkXMLSerializable.h" #include int mitkCameraIntrinsicsTest(int argc, char* argv[]); namespace mitk { /// /// \brief class representing camera intrinsics and related functions /// class MitkCameraCalibration_EXPORT CameraIntrinsics: virtual public itk::Object, virtual public mitk::XMLSerializable { public: /// /// for testing purposes /// friend int mitkCameraIntrinsicsTest(int argc, char* argv[]); /// /// smartpointer typedefs /// mitkClassMacro(CameraIntrinsics, itk::Object); /// /// the static new function /// itkFactorylessNewMacro(Self); /// /// make a clone of this intrinsics /// itkCloneMacro(Self) /// /// copy information from other to this /// void Copy(const CameraIntrinsics* other); /// /// checks two intrinsics for equality /// bool Equals( const CameraIntrinsics* other ) const; /// /// \return the intrinsic parameter matrix as a 3x3 vnl matrix /// vnl_matrix_fixed GetVnlCameraMatrix() const; /// /// \return the intrinsic parameter matrix as a 3x4 vnl matrix /// (the last column only containing zeros) /// vnl_matrix_fixed GetVnlCameraMatrix3x4() const; /// /// \return true if the intrinsics are set (some plausibility checks /// may be done here) /// bool IsValid() const; void SetValid(bool valid); cv::Mat GetCameraMatrix() const; cv::Mat GetDistorsionCoeffs(); cv::Mat GetDistorsionCoeffs() const; void ToXML(TiXmlElement* elem) const; std::string ToString() const; std::string GetString(); double GetFocalLengthX() const; double GetFocalLengthY() const; double GetPrincipalPointX() const; double GetPrincipalPointY() const; mitk::Point4D GetDistorsionCoeffsAsPoint4D() const; mitk::Point3D GetFocalPoint() const; mitk::Point3D GetPrincipalPoint() const; vnl_vector_fixed GetFocalPointAsVnlVector() const; vnl_vector_fixed GetPrincipalPointAsVnlVector() const; /// /// set a new camera matrix utilizing a vnl matrix /// void SetCameraMatrix( const vnl_matrix_fixed& _CameraMatrix ); void SetIntrinsics( const cv::Mat& _CameraMatrix , const cv::Mat& _DistorsionCoeffs); void SetFocalLength( double x, double y ); void SetPrincipalPoint( double x, double y ); void SetDistorsionCoeffs( double k1, double k2, double p1, double p2 ); void SetIntrinsics( const mitk::Point3D& focalPoint, const mitk::Point3D& principalPoint, const mitk::Point4D& distortionCoefficients); void FromXML(TiXmlElement* elem); void FromGMLCalibrationXML(TiXmlElement* elem); std::string ToOctaveString(const std::string& varName="CameraIntrinsics"); virtual ~CameraIntrinsics(); protected: CameraIntrinsics(); CameraIntrinsics(const CameraIntrinsics& other); cv::Mat m_CameraMatrix; cv::Mat m_DistorsionCoeffs; bool m_Valid; itk::FastMutexLock::Pointer m_Mutex; private: virtual itk::LightObject::Pointer InternalClone() const; }; } // namespace mitk MitkCameraCalibration_EXPORT std::ostream& operator<< (std::ostream& os, mitk::CameraIntrinsics::Pointer p); #endif // mitkCameraIntrinsics_h diff --git a/Modules/CameraCalibration/mitkTransform.h b/Modules/CameraCalibration/mitkTransform.h index db17377407..ada8c83f0e 100644 --- a/Modules/CameraCalibration/mitkTransform.h +++ b/Modules/CameraCalibration/mitkTransform.h @@ -1,305 +1,305 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKTRANSFORM_H #define MITKTRANSFORM_H #include #include #include -#include +#include #include #include #include #include #include #include namespace mitk { /// /// \brief class representing a transfrom in 3D /// /// internally it stores a mitk navigation data. this is more /// or less a wrapper for navigation data for easy casting /// between opencv/vnl/mitk/xml representations of transform /// data /// class MitkCameraCalibration_EXPORT Transform: public itk::Object, public XMLSerializable { public: mitkClassMacro(Transform, itk::Object); itkFactorylessNewMacro(Transform); mitkNewMacro1Param(Transform, const mitk::NavigationData*); mitkNewMacro1Param(Transform, const std::string&); /// /// constants describing the type of transform /// represented here /// static const std::string UNKNOWN_TYPE; static const std::string ENDOSCOPE_SCOPE_TOOL; static const std::string ENDOSCOPE_CAM_TOOL; static const std::string CHESSBOARD_TOOL; static const std::string POINTER_TOOL; static const std::string POINTER_TO_CHESSBOARD_ORIGIN; static const std::string POINTER_TO_CHESSBOARD_X_SUPPORT_POINT; static const std::string POINTER_TO_CHESSBOARD_Y_SUPPORT_POINT; static const std::string BOARD_TO_BOARD_TOOL; static const std::string REFERENCE_CAMERA_TRANSFORM; static const std::string REFERENCE_SCOPE_TRANSFORM; static const std::string EYE_TO_HAND_TRANSFORM; static const std::string CAMERA_EXTRINSICS; itkGetConstMacro(Type, std::string); itkSetMacro(Type, std::string&); /// /// Copies the content of transform to this /// instance /// void Copy( const mitk::Transform* transform ); /// /// Copies the content of transform to this /// instance /// void Copy( const mitk::NavigationData* transform ); /// /// Inverts the rotation of this transform /// (Polaris navigation Data have inverted rotation /// so you may want to call this function when using /// polaris data) /// void TransposeRotation(); /// /// get a copy of this transform /// mitk::Transform::Pointer Clone() const; /// /// concatenate this transform with the given one, /// i.e. this transform is done first, then transform /// ( if x is this transform, y is transform, then this will be y*x) /// post multiply semantics! /// \see vtkTransform /// void Concatenate( mitk::Transform* transform ); /// /// same as above with vnl mat argument /// void Concatenate( const vnl_matrix_fixed& transform ); /// /// same as above with vtk mat argument /// void Concatenate( const vtkMatrix4x4* transform ); /// /// invert this transform /// void Invert(); /// /// resets the internal variables except type /// void Reset(); /// /// read from xml /// void FromXML(TiXmlElement* elem); /// /// read csv file /// void FromCSVFile(const std::string& file); /// /// grafts the data from naviData to this transform /// void SetNavigationData( const mitk::NavigationData* naviData ); /// /// method to set orientation quat /// void SetOrientation( const vnl_quaternion& orientation); /// /// method to set float valued orientation quat /// void SetOrientation( const vnl_quaternion& orientation); /// /// method to set translation /// void SetTranslation( const vnl_vector_fixed& transl); /// /// method to set a vector of doubles as translation /// void SetTranslation( const vnl_vector& transl); /// /// method to set a mitk::Point3D as position /// void SetPosition( const mitk::Point3D& transl); /// /// sets rotation with a rotation matrix /// void SetRotation( vnl_matrix_fixed& mat); /// /// sets rotation with a non fixed rotation matrix /// void SetRotation( vnl_matrix& mat); /// /// sets rotation and translation with a transformation matrix /// void SetMatrix( const vnl_matrix_fixed& mat); /// /// sets rotation and translation with a vtk transformation matrix /// void SetMatrix( const vtkMatrix4x4* mat); /// /// sets translation from a POD vector /// void SetTranslation( float* array ); /// /// sets translation from a POD vector. this must be a /// 3x3=9 sized vector in row major format (first row = first /// three elements) /// void SetRotation( float* array ); /// /// sets translation from a POD vector /// void SetTranslation( double array[3] ); /// /// sets translation from a POD vector /// void SetRotation( double array[3][3] ); /// /// method to set translation by cv vector /// void SetTranslation( const cv::Mat& transl); /// /// sets rotation with a rotation matrix /// void SetRotation( const cv::Mat& mat ); /// /// sets rotation with a rodrigues rotation vector /// void SetRotationVector( const cv::Mat& rotVec); /// /// \return the navigation data that stores all information /// mitk::NavigationData::Pointer GetNavigationData() const; /// /// calls navigationdata::GetPosition() /// mitk::Point3D GetPosition() const; /// /// same as GetPosition /// mitk::Point3D GetTranslation() const; /// /// calls navigationdata::IsValid() /// bool IsValid() const; /// /// calls navigationdata::SetValid() /// void SetValid(bool valid); /// /// calls navigationdata::GetOrientation() /// mitk::Quaternion GetOrientation() const; /// /// \return the homogeneous matrix representing this transform /// vnl_matrix_fixed GetMatrix() const; /// /// \return the homogeneous vtk matrix representing this transform /// void GetMatrix(vtkMatrix4x4* matrix) const; /// /// \return the homogeneous vtk matrix representing this transform /// in !OpenGL! left handed coordinate system /// void GetVtkOpenGlMatrix(vtkMatrix4x4* matrix) const; mitk::Point3D TransformPoint(mitk::Point3D point) const; /// /// create xml representation /// void ToXML(TiXmlElement* elem) const; /// /// create string representation /// std::string ToString() const; /// /// create string csv representation (only the transformation values!!!!) /// std::string ToCSVString() const; /// /// create matlab representation /// std::string ToMatlabString(const std::string& varname="transform", bool printLastRow=true) const; /// /// write csv representation to file (only the transformation values!!!!) /// void ToCSVFile(const std::string& file) const; /// /// write matlab representation to file /// void ToMatlabFile(const std::string& file , const std::string& varname="transform") const; /// /// conversion to cv types /// cv::Mat GetCvTranslation() const; cv::Mat GetCvRotationVector() const; cv::Mat GetCvRotationMatrix() const; cv::Mat GetCvMatrix() const; /// /// conversion to vnl types /// vnl_vector_fixed GetVnlTranslation() const; vnl_vector_fixed GetVnlDoubleTranslation() const; vnl_quaternion GetVnlDoubleQuaternion() const; vnl_matrix_fixed GetVnlRotationMatrix() const; vnl_matrix_fixed GetVnlDoubleMatrix() const; protected: Transform(); Transform(const mitk::NavigationData* nd); Transform(const std::string& s); // everything is stored here mitk::NavigationData::Pointer m_NavData; /// /// saves the type of the transform (Default is UNKNOWN_TYPE) /// std::string m_Type; }; } // namespace mitk MitkCameraCalibration_EXPORT std::ostream& operator<< (std::ostream& os, mitk::Transform::Pointer p); #endif // MITKTRANSFORM_H diff --git a/Modules/ContourModel/DataManagement/mitkContourElement.h b/Modules/ContourModel/DataManagement/mitkContourElement.h index 89349cf8fa..95da74d51c 100644 --- a/Modules/ContourModel/DataManagement/mitkContourElement.h +++ b/Modules/ContourModel/DataManagement/mitkContourElement.h @@ -1,269 +1,269 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 _mitkContourElement_H_ #define _mitkContourElement_H_ #include "mitkCommon.h" #include -#include +#include //#include #include namespace mitk { /** \brief Represents a contour in 3D space. A ContourElement is consisting of linked vertices implicitely defining the contour. They are stored in a double ended queue making it possible to add vertices at front and end of the contour and to iterate in both directions. To mark a vertex as a special one it can be set as a control point. \Note It is highly not recommend to use this class directly as no secure mechanism is used here. Use mitk::ContourModel instead providing some additional features. */ class MitkContourModel_EXPORT ContourElement : public itk::LightObject { public: mitkClassMacro(ContourElement, itk::LightObject); itkFactorylessNewMacro(Self) itkCloneMacro(Self) // Data container representing vertices /** \brief Represents a single vertex of contour. */ struct ContourModelVertex { ContourModelVertex(mitk::Point3D &point, bool active=false) : IsControlPoint(active), Coordinates(point) { } ContourModelVertex( const ContourModelVertex &other) : IsControlPoint(other.IsControlPoint), Coordinates(other.Coordinates) { } /** \brief Treat point special. */ bool IsControlPoint; /** \brief Coordinates in 3D space. */ mitk::Point3D Coordinates; }; // END Data container representing vertices typedef ContourModelVertex VertexType; typedef std::deque VertexListType; typedef VertexListType::iterator VertexIterator; typedef VertexListType::const_iterator ConstVertexIterator; // start of inline methods /** \brief Return a const iterator a the front. */ virtual ConstVertexIterator ConstIteratorBegin() { return this->m_Vertices->begin(); } /** \brief Return a const iterator a the end. */ virtual ConstVertexIterator ConstIteratorEnd() { return this->m_Vertices->end(); } /** \brief Return an iterator a the front. */ virtual VertexIterator IteratorBegin() { return this->m_Vertices->begin(); } /** \brief Return an iterator a the end. */ virtual VertexIterator IteratorEnd() { return this->m_Vertices->end(); } /** \brief Returns the number of contained vertices. */ virtual int GetSize() { return this->m_Vertices->size(); } // end of inline methods /** \brief Add a vertex at the end of the contour \param point - coordinates in 3D space. \param isControlPoint - is the vertex a special control point. */ virtual void AddVertex(mitk::Point3D &point, bool isControlPoint); /** \brief Add a vertex at the end of the contour \param vertex - a contour element vertex. */ virtual void AddVertex(VertexType &vertex); /** \brief Add a vertex at the front of the contour \param point - coordinates in 3D space. \param isControlPoint - is the vertex a control point. */ virtual void AddVertexAtFront(mitk::Point3D &point, bool isControlPoint); /** \brief Add a vertex at the front of the contour \param vertex - a contour element vertex. */ virtual void AddVertexAtFront(VertexType &vertex); /** \brief Add a vertex at a given index of the contour \param point - coordinates in 3D space. \param isControlPoint - is the vertex a special control point. \param index - the index to be inserted at. */ virtual void InsertVertexAtIndex(mitk::Point3D &point, bool isControlPoint, int index); /** \brief Set coordinates a given index. \param pointId Index of vertex. \param point Coordinates. */ virtual void SetVertexAt(int pointId, const mitk::Point3D &point); /** \brief Set vertex a given index. \param pointId Index of vertex. \param vertex Vertex. */ virtual void SetVertexAt(int pointId, const VertexType* vertex); /** \brief Returns the vertex a given index \param index */ virtual VertexType* GetVertexAt(int index); /** \brief Returns the approximate nearest vertex a given posoition in 3D space \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ virtual VertexType* GetVertexAt(const mitk::Point3D &point, float eps); /** \brief Returns the index of the given vertex within the contour. \param vertex - the vertex to be searched. \return index of vertex. -1 if not found. */ virtual int GetIndex(const VertexType* vertex); /** \brief Returns the container of the vertices. */ VertexListType* GetVertexList(); /** \brief Returns whether the contour element is empty. */ bool IsEmpty(); /** \brief Returns if the conour is closed or not. */ virtual bool IsClosed(); /** \brief Returns whether a given point is near a contour, according to eps. \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ virtual bool IsNearContour(const mitk::Point3D &point, float eps); /** \brief Close the contour. Connect first with last element. */ virtual void Close(); /** \brief Open the contour. Disconnect first and last element. */ virtual void Open(); /** \brief Set the contours IsClosed property. \param isClosed - true = closed; false = open; */ virtual void SetClosed(bool isClosed); /** \brief Concatenate the contuor with a another contour. All vertices of the other contour will be added after last vertex. \param other - the other contour \param check - set it true to avoid intersections */ void Concatenate(mitk::ContourElement* other, bool check); /** \brief Remove the given vertex from the container if exists. \param vertex - the vertex to be removed. */ virtual bool RemoveVertex(const VertexType* vertex); /** \brief Remove a vertex at given index within the container if exists. \param index - the index where the vertex should be removed. */ virtual bool RemoveVertexAt(int index); /** \brief Remove the approximate nearest vertex at given position in 3D space if one exists. \param point - query point in 3D space. \param eps - error bound for search algorithm. */ virtual bool RemoveVertexAt(mitk::Point3D &point, float eps); /** \brief Clear the storage container. */ virtual void Clear(); /** \brief Returns the approximate nearest vertex a given posoition in 3D space \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ VertexType* BruteForceGetVertexAt(const mitk::Point3D &point, float eps); /** \brief Returns the approximate nearest vertex a given posoition in 3D space \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ //VertexType* OptimizedGetVertexAt(const mitk::Point3D &point, float eps); VertexListType* GetControlVertices(); /** \brief Uniformly redistribute control points with a given period (in number of vertices) \param vertex - the vertex around which the redistribution is done. \param period - number of vertices between control points. */ void RedistributeControlVertices(const VertexType* vertex, int period); protected: mitkCloneMacro(Self); ContourElement(); ContourElement(const mitk::ContourElement &other); virtual ~ContourElement(); VertexListType* m_Vertices; //double ended queue with vertices bool m_IsClosed; }; } // namespace mitk #endif // _mitkContourElement_H_ diff --git a/Modules/DataTypesExt/Testing/mitkMeshTest.cpp b/Modules/DataTypesExt/Testing/mitkMeshTest.cpp index 61b84cc49a..140d0a4ca5 100644 --- a/Modules/DataTypesExt/Testing/mitkMeshTest.cpp +++ b/Modules/DataTypesExt/Testing/mitkMeshTest.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 -#include +#include #include #include #include int mitkMeshTest(int /*argc*/, char* /*argv*/[]) { //Create mesh mitk::Mesh::Pointer mesh; mesh = mitk::Mesh::New(); //try to get the itkmesh std::cout << "Create a mesh and try to get the itkMesh"; mitk::Mesh::DataType::Pointer itkdata = NULL; itkdata = mesh->GetMesh(); if (itkdata.IsNull()) { std::cout<<"[FAILED]"<GetSize() != 0) { std::cout<<"[FAILED]"<ExecuteOperation(doOp); //now check new condition! if ( (mesh->GetSize()!=1) || (!mesh->IndexExists(position))) { std::cout<<"[FAILED]"<GetPoint(position); if (tempPoint != point) { std::cout<<"[FAILED]"<SetRadius(1.0); cone->SetHeight(2.0); cone->SetDirection(0.0, -1.0, 0.0); cone->SetCenter(0.0, 0.0, 0.0); cone->SetResolution(20); cone->CappingOn(); cone->Update(); SetVtkPolyData(cone->GetOutput()); cone->Delete(); } mitk::Cone::~Cone() { } bool mitk::Cone::IsInside(const Point3D& worldPoint) const { // transform point from world to object coordinates ScalarType p[4]; p[0] = worldPoint[0]; p[1] = worldPoint[1]; p[2] = worldPoint[2]; p[3] = 1; GetGeometry()->GetVtkTransform()->GetInverse()->TransformPoint(p, p); p[1] += 1; // translate point, so that it fits to the formula below, which describes a cone that has its cone vertex at the origin return (sqrt(p[0] * p[0] + p[2] * p[2]) <= p[1] * 0.5) && (p[1] <= 2); // formula to calculate if a given point is inside a cone that has its cone vertex at the origin, is aligned on the second axis, has a radius of one an a height of two } mitk::ScalarType mitk::Cone::GetVolume() { TimeGeometry* geometry = GetTimeGeometry(); return geometry->GetExtentInWorld(0) * 0.5 * geometry->GetExtentInWorld(2) * 0.5 * vnl_math::pi / 3.0 * geometry->GetExtentInWorld(1); } diff --git a/Modules/DataTypesExt/mitkCuboid.cpp b/Modules/DataTypesExt/mitkCuboid.cpp index ecc2187485..ab25b5444a 100644 --- a/Modules/DataTypesExt/mitkCuboid.cpp +++ b/Modules/DataTypesExt/mitkCuboid.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 "mitkCuboid.h" #include "vtkLinearTransform.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "vtkCubeSource.h" #include mitk::Cuboid::Cuboid() : BoundingObject() { vtkCubeSource* cube = vtkCubeSource::New(); cube->SetXLength(2.0); cube->SetYLength(2.0); cube->SetZLength(2.0); cube->Update(); SetVtkPolyData(cube->GetOutput()); cube->Delete(); } mitk::Cuboid::~Cuboid() { } bool mitk::Cuboid::IsInside(const Point3D& worldPoint) const { // transform point from world to object coordinates ScalarType p[4]; p[0] = worldPoint[0]; p[1] = worldPoint[1]; p[2] = worldPoint[2]; p[3] = 1; GetGeometry()->GetVtkTransform()->GetInverse()->TransformPoint(p, p); return (p[0] >= -1) && (p[0] <= 1) && (p[1] >= -1) && (p[1] <= 1) && (p[2] >= -1) && (p[2] <= 1); } mitk::ScalarType mitk::Cuboid::GetVolume() { TimeGeometry* geometry = GetTimeGeometry(); return geometry->GetExtentInWorld(0) * geometry->GetExtentInWorld(1) * geometry->GetExtentInWorld(2); } diff --git a/Modules/DataTypesExt/mitkCylinder.cpp b/Modules/DataTypesExt/mitkCylinder.cpp index b28da210f1..9c131033c0 100644 --- a/Modules/DataTypesExt/mitkCylinder.cpp +++ b/Modules/DataTypesExt/mitkCylinder.cpp @@ -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. ===================================================================*/ #include "mitkCylinder.h" #include "vtkLinearTransform.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "vtkCylinderSource.h" mitk::Cylinder::Cylinder() : BoundingObject() { vtkCylinderSource* cylinder = vtkCylinderSource::New(); cylinder->SetRadius(1.0); cylinder->SetHeight(2.0); cylinder->SetCenter(0.0, 0.0, 0.0); cylinder->SetResolution(100); cylinder->CappingOn(); cylinder->Update(); SetVtkPolyData(cylinder->GetOutput()); cylinder->Delete(); } mitk::Cylinder::~Cylinder() { } bool mitk::Cylinder::IsInside(const Point3D& worldPoint) const { // transform point from world to object coordinates ScalarType p[4]; p[0] = worldPoint[0]; p[1] = worldPoint[1]; p[2] = worldPoint[2]; p[3] = 1; GetGeometry()->GetVtkTransform()->GetInverse()->TransformPoint(p, p); mitk::ScalarType v = pow(p[0], 2) + pow(p[2], 2); bool retval = (v <= 1) && (p[1] >= -1) && (p[1] <= 1); return retval; } mitk::ScalarType mitk::Cylinder::GetVolume() { TimeGeometry* geometry = GetTimeGeometry(); return geometry->GetExtentInWorld(0) * 0.5 * geometry->GetExtentInWorld(2) * 0.5 * vnl_math::pi * geometry->GetExtentInWorld(1); } diff --git a/Modules/DataTypesExt/mitkEllipsoid.cpp b/Modules/DataTypesExt/mitkEllipsoid.cpp index a1ee3b75c6..dc6d5343c2 100644 --- a/Modules/DataTypesExt/mitkEllipsoid.cpp +++ b/Modules/DataTypesExt/mitkEllipsoid.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 "mitkEllipsoid.h" #include "vtkLinearTransform.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "vtkSphereSource.h" mitk::Ellipsoid::Ellipsoid() : BoundingObject() { vtkSphereSource* sphere = vtkSphereSource::New(); sphere->SetRadius(1.0); sphere->SetThetaResolution(20); sphere->SetPhiResolution(20); sphere->Update(); SetVtkPolyData(sphere->GetOutput()); sphere->Delete(); } mitk::Ellipsoid::~Ellipsoid() { } bool mitk::Ellipsoid::IsInside(const Point3D& worldPoint) const { // transform point from world to object coordinates ScalarType p[4]; p[0] = worldPoint[0]; p[1] = worldPoint[1]; p[2] = worldPoint[2]; p[3] = 1; GetGeometry()->GetVtkTransform()->GetInverse()->TransformPoint(p, p); return (pow(p[0], 2) + pow(p[1], 2) + pow(p[2], 2) <= 1); } mitk::ScalarType mitk::Ellipsoid::GetVolume() { return GetGeometry()->GetExtentInMM(0) * 0.5 * GetGeometry()->GetExtentInMM(1) * 0.5 * GetGeometry()->GetExtentInMM(2) * 0.5 * vnl_math::pi * 4.0/3.0; } diff --git a/Modules/DataTypesExt/mitkMesh.cpp b/Modules/DataTypesExt/mitkMesh.cpp index 3f800e1d55..e532b2a178 100644 --- a/Modules/DataTypesExt/mitkMesh.cpp +++ b/Modules/DataTypesExt/mitkMesh.cpp @@ -1,840 +1,840 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkMesh.h" #include "mitkOperation.h" #include "mitkOperationActor.h" #include "mitkLineOperation.h" #include "mitkLineOperation.h" #include "mitkPointOperation.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "mitkStatusBar.h" #include "mitkInteractionConst.h" #include "mitkLine.h" #include "mitkRenderingManager.h" mitk::Mesh::Mesh() { } mitk::Mesh::~Mesh() { } const mitk::Mesh::DataType *mitk::Mesh::GetMesh( int t ) const { return m_PointSetSeries[t]; } mitk::Mesh::DataType* mitk::Mesh::GetMesh( int t ) { return m_PointSetSeries[t]; } void mitk::Mesh::SetMesh( DataType *mesh, int t ) { this->Expand( t+1 ); m_PointSetSeries[t] = mesh; } unsigned long mitk::Mesh::GetNumberOfCells( int t ) { return m_PointSetSeries[t]->GetNumberOfCells(); } //search a line that is close enough according to the given position bool mitk::Mesh::SearchLine( Point3D point, float distance, unsigned long &lineId, unsigned long &cellId, int t ) { //returns true if a line is found ScalarType bestDist = distance; //iterate through all cells. ConstCellIterator cellIt = m_PointSetSeries[t]->GetCells()->Begin(); ConstCellIterator cellEnd = m_PointSetSeries[t]->GetCells()->End(); while( cellIt != cellEnd) { if (cellIt.Value()->GetNumberOfPoints() >1) { //then iterate through all indexes of points in it->Value() PointIdIterator inAIt = cellIt.Value()->PointIdsBegin(); // first point PointIdIterator inBIt = cellIt.Value()->PointIdsBegin(); // second point PointIdIterator inEnd = cellIt.Value()->PointIdsEnd(); ++inAIt; //so it points to the point before inBIt int currentLineId = 0; while(inAIt != inEnd) { mitk::PointSet::PointType pointA, pointB; if ( m_PointSetSeries[t]->GetPoint((*inAIt), &pointA) && m_PointSetSeries[t]->GetPoint((*inBIt), &pointB)) { Line *line = new Line(); line->SetPoints(pointA, pointB); double thisDistance = line->Distance(point); if (thisDistance < bestDist) { cellId = cellIt->Index(); lineId = currentLineId; bestDist = thisDistance; } } ++inAIt; ++inBIt; ++currentLineId; } // If the cell is closed, then check the line from the last index to // the first index if inAIt points to inEnd, then inBIt points to the // last index. CellDataType cellData; bool dataOk = m_PointSetSeries[t]->GetCellData(cellIt->Index(), &cellData); if (dataOk) { if (cellData.closed) { // get the points PointIdIterator inAIt = cellIt.Value()->PointIdsBegin();//first point // inBIt points to last. mitk::PointSet::PointType pointA, pointB; if ( m_PointSetSeries[t]->GetPoint((*inAIt), &pointA) && m_PointSetSeries[t]->GetPoint((*inBIt), &pointB)) { Line *line = new Line(); line->SetPoints(pointA, pointB); double thisDistance = line->Distance(point); if (thisDistance < bestDist) { cellId = cellIt->Index(); lineId = currentLineId; bestDist = thisDistance; } } } } } ++cellIt; } return (bestDist < distance); } int mitk::Mesh::SearchFirstCell( unsigned long pointId, int t ) { //iterate through all cells and find the cell the given pointId is inside ConstCellIterator it = m_PointSetSeries[t]->GetCells()->Begin(); ConstCellIterator end = m_PointSetSeries[t]->GetCells()->End(); while( it != end) { PointIdIterator position = std::find(it->Value()->PointIdsBegin(), it->Value()->PointIdsEnd(), pointId); if ( position != it->Value()->PointIdsEnd()) { return it->Index(); } ++it; } return -1; } // Due to not implemented itk::CellInterface::EvaluatePosition and errors in // using vtkCell::EvaluatePosition (changing iterator!) we must implement // it in mitk::Mesh // make it easy and look for hit points and hit lines: needs to be done anyway! bool mitk::Mesh::EvaluatePosition( mitk::Point3D point, unsigned long &cellId, float precision, int t ) { int pointId = this->SearchPoint( point, precision, t ); if (pointId > -1) { //search the cell the point lies inside cellId = this->SearchFirstCell( pointId, t ); return true; } unsigned long lineId = 0; if ( this->SearchLine(point, precision, lineId, cellId, t) ) { return true; } return false; } unsigned long mitk::Mesh::GetNewCellId( int t ) { long nextCellId = -1; ConstCellIterator it = m_PointSetSeries[t]->GetCells()->Begin(); ConstCellIterator end = m_PointSetSeries[t]->GetCells()->End(); while (it!=end) { nextCellId = it.Index(); ++it; } ++nextCellId; return nextCellId; } int mitk::Mesh::SearchSelectedCell( int t ) { CellDataIterator cellDataIt, cellDataEnd; cellDataEnd = m_PointSetSeries[t]->GetCellData()->End(); for ( cellDataIt = m_PointSetSeries[t]->GetCellData()->Begin(); cellDataIt != cellDataEnd; cellDataIt++ ) { //then declare an operation which unselects this line; UndoOperation as well! if ( cellDataIt->Value().selected ) { return cellDataIt->Index(); } } return -1; } // get the cell; then iterate through the Ids times lineId. Then IdA ist the // one, IdB ist ne next.don't forget the last closing line if the cell is // closed bool mitk::Mesh::GetPointIds( unsigned long cellId, unsigned long lineId, int &idA, int &idB, int t ) { bool ok = false; bool found = false; CellAutoPointer cellAutoPointer; ok = m_PointSetSeries[t]->GetCell(cellId, cellAutoPointer); if (ok) { CellType * cell = cellAutoPointer.GetPointer(); //Get the cellData to also check the closing line CellDataType cellData; m_PointSetSeries[t]->GetCellData(cellId, &cellData); bool closed = cellData.closed; PointIdIterator pointIdIt = cell->PointIdsBegin(); PointIdIterator pointIdEnd = cell->PointIdsEnd(); unsigned int counter = 0; while (pointIdIt != pointIdEnd) { if(counter == lineId) { idA = (*pointIdIt); ++pointIdIt; found = true; break; } ++counter; ++pointIdIt; } if(found) { //if in the middle if (pointIdIt != pointIdEnd) { idB = (*pointIdIt); } // if found but on the end, then it is the closing connection, so the // last and the first point else if (closed) { pointIdIt = cell->PointIdsBegin(); idB = (*pointIdIt); } } else ok = false; } return ok; } void mitk::Mesh::ExecuteOperation(Operation* operation) { //adding only the operations, that aren't implemented by the pointset. switch (operation->GetOperationType()) { case OpNOTHING: break; case OpNEWCELL: { mitk::LineOperation *lineOp = dynamic_cast(operation); // if no lineoperation, then call superclass pointSet if (lineOp == NULL) { Superclass::ExecuteOperation(operation); } bool ok; int cellId = lineOp->GetCellId(); CellAutoPointer cellAutoPointer; ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); // if it doesn't already exist if (!ok) { cellAutoPointer.TakeOwnership( new PolygonType ); m_PointSetSeries[0]->SetCell(cellId, cellAutoPointer); CellDataType cellData; cellData.selected = true; cellData.selectedLines.clear(); cellData.closed = false; m_PointSetSeries[0]->SetCellData(cellId, cellData); } } break; case OpDELETECELL: { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } m_PointSetSeries[0]->GetCells()->DeleteIndex((unsigned)lineOp->GetCellId()); m_PointSetSeries[0]->GetCellData()->DeleteIndex((unsigned)lineOp->GetCellId()); } break; case OpCLOSECELL: //sets the bolean flag closed from a specified cell to true. { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { //then search the selected cell!//TODO Superclass::ExecuteOperation(operation); } bool ok; int cellId = lineOp->GetCellId(); if (cellId<0)//cellId isn't set { cellId = this->SearchSelectedCell( 0 ); if (cellId < 0 )//still not found return; } CellAutoPointer cellAutoPointer; //get directly the celldata!TODO ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); cellData.closed = true; m_PointSetSeries[0]->SetCellData(cellId, cellData); } } break; case OpOPENCELL: { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } bool ok; int cellId = lineOp->GetCellId(); CellAutoPointer cellAutoPointer; ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); cellData.closed = false;; m_PointSetSeries[0]->SetCellData(cellId, cellData); } } break; case OpADDLINE: // inserts the ID of the selected point into the indexes of lines in the // selected cell afterwars the added line is selected { mitk::LineOperation *lineOp = dynamic_cast(operation); int cellId = -1; int pId = -1; if (lineOp == NULL) { cellId = this->SearchSelectedCell( 0 ); if (cellId == -1) return; pId = this->SearchSelectedPoint( 0 ); if (pId == -1) return; } else { cellId = lineOp->GetCellId(); if (cellId == -1) return; pId = lineOp->GetPIdA(); if (pId == -1) return; } bool ok; CellAutoPointer cellAutoPointer; ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellType * cell = cellAutoPointer.GetPointer(); if( cell->GetType() == CellType::POLYGON_CELL ) { PolygonType * polygon = static_cast( cell ); // add the pointId to the Cell. filling the empty cell with // one id doesn't mean to add a line, it means, that the // initilal PointId is set. The next addition of a pointId adds // a line polygon->AddPointId(pId); // select the line, if we really added a line, so now have more than // 1 pointID in the cell CellDataType cellData; ok = m_PointSetSeries[0]->GetCellData(cellId, &cellData); if (ok) { // A line between point 0 and 1 has the Id 0. A line between // 1 and 2 has a Id = 1. So we add getnumberofpoints-2. if (polygon->GetNumberOfPoints()>1) cellData.selectedLines.push_back(polygon->GetNumberOfPoints()-2); } m_PointSetSeries[0]->SetCellData(cellId, cellData); m_PointSetSeries[0]->SetCell(cellId, cellAutoPointer); } } } break; case OpDELETELINE: { // deleted the last line through removing the index PIdA // (if set to -1, use the last point) in the given cellId mitk::LineOperation *lineOp = dynamic_cast(operation); int cellId = -1; int pId = -1; if (lineOp == NULL) { cellId = this->SearchSelectedCell( 0 ); if (cellId == -1) return; pId = this->SearchSelectedPoint( 0 ); } else { cellId = lineOp->GetCellId(); if (cellId == -1) return; pId = lineOp->GetPIdA(); } bool ok; CellAutoPointer cellAutoPointer; ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellType * cell = cellAutoPointer.GetPointer(); if( cell->GetType() == CellType::POLYGON_CELL ) { PolygonType * oldPolygon = static_cast( cell ); PolygonType * newPolygonCell = new PolygonType; CellAutoPointer newCell; newCell.TakeOwnership( newPolygonCell ); PointIdConstIterator it, oldend; oldend = oldPolygon->PointIdsEnd(); if(pId >= 0) { for(it = oldPolygon->PointIdsBegin(); it != oldend; ++it) { if((*it) != (MeshType::PointIdentifier)pId) { newPolygonCell->AddPointId(*it); } } } else { --oldend; for(it = oldPolygon->PointIdsBegin(); it != oldend; ++it) newPolygonCell->AddPointId(*it); } oldPolygon->SetPointIds(0, newPolygonCell->GetNumberOfPoints(), newPolygonCell->PointIdsBegin()); } } } break; case OpREMOVELINE: //Remove the given Index in the given cell through copying everything // into a new cell accept the one that has to be deleted. { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } bool ok; CellAutoPointer cellAutoPointer; int cellId = lineOp->GetCellId(); ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (!ok) return; CellType * cell = cellAutoPointer.GetPointer(); CellAutoPointer newCellAutoPointer; newCellAutoPointer.TakeOwnership( new PolygonType ); PolygonType * newPolygon = static_cast( cell ); PointIdIterator it = cell->PointIdsBegin(); PointIdIterator end = cell->PointIdsEnd(); int pointId = lineOp->GetPIdA(); if (pointId<0)//if not initialized!! return; while (it!=end) { if ((*it)==(unsigned int)pointId) { break; } else { newPolygon ->AddPointId(*it); } ++it; } while (it!=end) { newPolygon ->AddPointId(*it); it++; } m_PointSetSeries[0]->SetCell(cellId, newCellAutoPointer); } break; case OpINSERTLINE: // //insert line between two other points. ////before A--B after A--C--B // //the points A, B and C have to be in the pointset. // //needed: CellId, Id of C , Id A and Id B ////the cell has to exist! //{ //mitk::LineOperation *lineOp = dynamic_cast(operation); // if (lineOp == NULL)//if no lineoperation, then call superclass pointSet // { // Superclass::ExecuteOperation(operation); // } // int cellId = lineOp->GetCellId(); // int pIdC = lineOp->GetPIdC(); // int pIdA = lineOp->GetPIdA(); // int pIdB = lineOp->GetPIdB(); // //the points of the given PointIds have to exist in the PointSet // bool ok; // ok = m_PointSetSeries[0]->GetPoints()->IndexExists(pIdA); // if (!ok) // return; // ok = m_PointSetSeries[0]->GetPoints()->IndexExists(pIdB); // if (!ok) // return; // ok = m_PointSetSeries[0]->GetPoints()->IndexExists(pIdC); // if (!ok) // return; // // so the points do exist. So now check, if there is already a cell // // with the given Id // DataType::CellAutoPointer cell; // ok = m_PointSetSeries[0]->GetCell(cellId, cell); // if (!ok) // return; // //pIdA and pIdB should exist in the cell // // PointIdIterator pit = cell->PointIdsBegin(); // PointIdIterator end = cell->PointIdsEnd(); // // //now arrange the new Ids in the cell like desired; pIdC between // // pIdA and pIdB // unsigned int nuPoints = cell->GetNumberOfPoints(); // std::vector newPoints; // pit = cell->PointIdsBegin(); // end = cell->PointIdsEnd(); // int i = 0; // while( pit != end ) // { // if ((*pit) = pIdA) // { // //now we have found the place to add pIdC after // newPoints[i] = (*pit); // i++; // newPoints[i] = pIdC; // } // else // newPoints[i] = (*pit); // pit++; // } // //now we have the Ids, that existed before combined with the new ones // //so delete the old cell // //doesn't seem to be necessary! // //cell->ClearPoints(); // pit = cell->PointIdsBegin(); // cell->SetPointIds(pit); //} break; case OpMOVELINE://(moves two points) { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL) { mitk::StatusBar::GetInstance()->DisplayText( "Message from mitkMesh: Recieved wrong type of operation! See mitkMeshInteractor.cpp", 10000); return; } //create two operations out of the one operation and call superclass //through the transmitted pointIds get the koordinates of the points. //then add the transmitted vestor to them //create two operations and send them to superclass Point3D pointA, pointB; pointA.Fill(0.0); pointB.Fill(0.0); m_PointSetSeries[0]->GetPoint(lineOp->GetPIdA(), &pointA); m_PointSetSeries[0]->GetPoint(lineOp->GetPIdB(), &pointB); pointA[0] += lineOp->GetVector()[0]; pointA[1] += lineOp->GetVector()[1]; pointA[2] += lineOp->GetVector()[2]; pointB[0] += lineOp->GetVector()[0]; pointB[1] += lineOp->GetVector()[1]; pointB[2] += lineOp->GetVector()[2]; mitk::PointOperation* operationA = new mitk::PointOperation(OpMOVE, pointA, lineOp->GetPIdA()); mitk::PointOperation* operationB = new mitk::PointOperation(OpMOVE, pointB, lineOp->GetPIdB()); Superclass::ExecuteOperation(operationA); Superclass::ExecuteOperation(operationB); } break; case OpSELECTLINE://(select the given line) { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } int cellId = lineOp->GetCellId(); CellAutoPointer cellAutoPointer; bool ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); SelectedLinesType *selectedLines = &(cellData.selectedLines); SelectedLinesIter position = std::find(selectedLines->begin(), selectedLines->end(), (unsigned int) lineOp->GetId()); if (position == selectedLines->end())//if not alsready selected { cellData.selectedLines.push_back(lineOp->GetId()); } m_PointSetSeries[0]->SetCellData(lineOp->GetCellId(), cellData); } } break; case OpDESELECTLINE://(deselect the given line) { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL) { Superclass::ExecuteOperation(operation); } int cellId = lineOp->GetCellId(); CellAutoPointer cellAutoPointer; bool ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); SelectedLinesType *selectedLines = &(cellData.selectedLines); SelectedLinesIter position = std::find(selectedLines->begin(), selectedLines->end(), (unsigned int) lineOp->GetId()); if (position != selectedLines->end())//if found { selectedLines->erase(position); } m_PointSetSeries[0]->SetCellData(cellId, cellData); } } break; case OpSELECTCELL://(select the given cell) { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } int cellId = lineOp->GetCellId(); CellAutoPointer cellAutoPointer; //directly get the data!//TODO bool ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); cellData.selected = true; m_PointSetSeries[0]->SetCellData(cellId, cellData); } } break; case OpDESELECTCELL://(deselect the given cell) { mitk::LineOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no lineoperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } int cellId = lineOp->GetCellId(); CellAutoPointer cellAutoPointer; bool ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (ok) { CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); cellData.selected = false; m_PointSetSeries[0]->SetCellData(cellId, cellData); } } break; case OpMOVECELL: //moves all Points of one cell according to the given vector { mitk::CellOperation *lineOp = dynamic_cast(operation); if (lineOp == NULL)//if no celloperation, then call superclass pointSet { Superclass::ExecuteOperation(operation); } int cellId = lineOp->GetCellId(); Vector3D vector = lineOp->GetVector(); //get the cell CellAutoPointer cellAutoPointer; bool ok = m_PointSetSeries[0]->GetCell(cellId, cellAutoPointer); if (!ok) return; CellDataType cellData; m_PointSetSeries[0]->GetCellData(cellId, &cellData); // iterate through the pointIds of the CellData and move those points in // the pointset PointIdIterator it = cellAutoPointer->PointIdsBegin(); PointIdIterator end = cellAutoPointer->PointIdsEnd(); while(it != end) { unsigned int position = (*it); PointType point; point.Fill(0); m_PointSetSeries[0]->GetPoint(position, &point); point = point + vector; m_PointSetSeries[0]->SetPoint(position, point); ++it; } } break; default: //if the operation couldn't be handled here, then send it to superclass Superclass::ExecuteOperation(operation); return; } //to tell the mappers, that the data is modifierd and has to be updated this->Modified(); mitk::OperationEndEvent endevent(operation); ((const itk::Object*)this)->InvokeEvent(endevent); // As discussed lately, don't mess with rendering from inside data structures //*todo has to be done here, cause of update-pipeline not working yet //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } mitk::Mesh::DataType::BoundingBoxPointer mitk::Mesh::GetBoundingBoxFromCell( unsigned long cellId, int t ) { // itk::CellInterface has also a GetBoundingBox, but it // returns CoordRepType [PointDimension *2] DataType::BoundingBoxPointer bBoxPointer = NULL; CellAutoPointer cellAutoPointer; if ( m_PointSetSeries[t]->GetCell(cellId, cellAutoPointer)) { DataType::PointsContainerPointer pointsContainer = DataType::PointsContainer::New(); PointIdIterator bbIt = cellAutoPointer.GetPointer()->PointIdsBegin(); PointIdIterator bbEnd = cellAutoPointer.GetPointer()->PointIdsEnd(); while(bbIt != bbEnd) { mitk::PointSet::PointType point; bool pointOk = m_PointSetSeries[t]->GetPoint((*bbIt), &point); if (pointOk) pointsContainer->SetElement((*bbIt), point); ++bbIt; } bBoxPointer = DataType::BoundingBoxType::New(); bBoxPointer->SetPoints(pointsContainer); bBoxPointer->ComputeBoundingBox(); } return bBoxPointer; } diff --git a/Modules/DataTypesExt/mitkPlane.cpp b/Modules/DataTypesExt/mitkPlane.cpp index b26be9232f..01b785c9c1 100644 --- a/Modules/DataTypesExt/mitkPlane.cpp +++ b/Modules/DataTypesExt/mitkPlane.cpp @@ -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. ===================================================================*/ #include "mitkPlane.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include #include #include #include namespace mitk { Plane::Plane() : BoundingObject() { // Set up Plane Surface. m_PlaneSource = vtkPlaneSource::New(); m_PlaneSource->SetOrigin( -32.0, -32.0, 0.0 ); m_PlaneSource->SetPoint1( 32.0, -32.0, 0.0 ); m_PlaneSource->SetPoint2( -32.0, 32.0, 0.0 ); m_PlaneSource->SetResolution( 128, 128 ); m_PlaneSource->Update(); m_PlaneNormal = vtkDoubleArray::New(); m_PlaneNormal->SetNumberOfComponents( 3 ); m_PlaneNormal->SetNumberOfTuples( m_PlaneSource->GetOutput()->GetNumberOfPoints() ); m_PlaneNormal->SetTuple3( 0, 0.0, 0.0, 1.0 ); m_PlaneNormal->SetName( "planeNormal" ); m_Plane = vtkPolyData::New(); m_Plane->DeepCopy( m_PlaneSource->GetOutput() ); m_Plane->GetPointData()->SetVectors( m_PlaneNormal ); this->SetVtkPolyData( m_Plane ); } Plane::~Plane() { m_PlaneSource->Delete(); m_Plane->Delete(); m_PlaneNormal->Delete(); } void Plane::SetExtent( const double x, const double y ) { m_PlaneSource->SetOrigin( -x / 2.0, -y / 2.0, 0.0 ); m_PlaneSource->SetPoint1( x / 2.0, -y / 2.0, 0.0 ); m_PlaneSource->SetPoint2( -x / 2.0, y / 2.0, 0.0 ); m_PlaneSource->Update(); m_Plane->DeepCopy( m_PlaneSource->GetOutput() ); m_Plane->GetPointData()->SetVectors( m_PlaneNormal ); this->Modified(); } void Plane::GetExtent( double &x, double &y ) const { x = m_PlaneSource->GetPoint1()[0] - m_PlaneSource->GetOrigin()[0]; y = m_PlaneSource->GetPoint2()[1] - m_PlaneSource->GetOrigin()[1]; } void Plane::SetResolution( const int xR, const int yR ) { m_PlaneSource->SetResolution( xR, yR ); m_PlaneSource->Update(); m_Plane->DeepCopy( m_PlaneSource->GetOutput() ); m_Plane->GetPointData()->SetVectors( m_PlaneNormal ); this->Modified(); } void Plane::GetResolution( int &xR, int &yR ) const { m_PlaneSource->GetResolution( xR, yR ); } bool Plane::IsInside( const Point3D &/*worldPoint*/ ) const { // Plane does not have a volume return false; } ScalarType Plane::GetVolume() { // Plane does not have a volume return 0.0; } } diff --git a/Modules/DiffusionImaging/DiffusionCore/mitkDiffusionFunctionCollection.cpp b/Modules/DiffusionImaging/DiffusionCore/mitkDiffusionFunctionCollection.cpp index 59047d22fd..4e17e88feb 100644 --- a/Modules/DiffusionImaging/DiffusionCore/mitkDiffusionFunctionCollection.cpp +++ b/Modules/DiffusionImaging/DiffusionCore/mitkDiffusionFunctionCollection.cpp @@ -1,253 +1,253 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkDiffusionFunctionCollection.h" #include -#include "mitkTypes.h" +#include "mitkNumericTypes.h" // for Windows #ifndef M_PI #define M_PI 3.14159265358979323846 #endif // Namespace ::SH #include #include #include // Namespace ::Gradients #include "itkVectorContainer.h" #include "vnl/vnl_vector.h" //------------------------- SH-function ------------------------------------ double mitk::sh::factorial(int number) { if(number <= 1) return 1; double result = 1.0; for(int i=1; i<=number; i++) result *= i; return result; } void mitk::sh::Cart2Sph(double x, double y, double z, double *cart) { double phi, th, rad; rad = sqrt(x*x+y*y+z*z); if( rad < mitk::eps ) { th = M_PI/2; phi = M_PI/2; } else { th = acos(z/rad); phi = atan2(y, x); } cart[0] = phi; cart[1] = th; cart[2] = rad; } double mitk::sh::legendre0(int l) { if( l%2 != 0 ) { return 0; } else { double prod1 = 1.0; for(int i=1;i mitk::gradients::GetAllUniqueDirections(const BValueMap & refBValueMap, GradientDirectionContainerType *refGradientsContainer ) { IndiciesVector directioncontainer; BValueMap::const_iterator mapIterator = refBValueMap.begin(); if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1) mapIterator++; //skip bzero Values for( ; mapIterator != refBValueMap.end(); mapIterator++){ IndiciesVector currentShell = mapIterator->second; while(currentShell.size()>0) { unsigned int wntIndex = currentShell.back(); currentShell.pop_back(); IndiciesVector::iterator containerIt = directioncontainer.begin(); bool directionExist = false; while(containerIt != directioncontainer.end()) { if (fabs(dot(refGradientsContainer->ElementAt(*containerIt), refGradientsContainer->ElementAt(wntIndex))) > 0.9998) { directionExist = true; break; } containerIt++; } if(!directionExist) { directioncontainer.push_back(wntIndex); } } } return directioncontainer; } bool mitk::gradients::CheckForDifferingShellDirections(const BValueMap & refBValueMap, GradientDirectionContainerType::ConstPointer refGradientsContainer) { BValueMap::const_iterator mapIterator = refBValueMap.begin(); if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1) mapIterator++; //skip bzero Values for( ; mapIterator != refBValueMap.end(); mapIterator++){ BValueMap::const_iterator mapIterator_2 = refBValueMap.begin(); if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1) mapIterator_2++; //skip bzero Values for( ; mapIterator_2 != refBValueMap.end(); mapIterator_2++){ if(mapIterator_2 == mapIterator) continue; IndiciesVector currentShell = mapIterator->second; IndiciesVector testShell = mapIterator_2->second; for (unsigned int i = 0; i< currentShell.size(); i++) if (fabs(dot(refGradientsContainer->ElementAt(currentShell[i]), refGradientsContainer->ElementAt(testShell[i]))) <= 0.9998) { return true; } } } return false; } template double mitk::gradients::dot (vnl_vector_fixed< type ,3> const& v1, vnl_vector_fixed< type ,3 > const& v2 ) { double result = (v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]) / (v1.two_norm() * v2.two_norm()); return result ; } vnl_matrix mitk::gradients::ComputeSphericalFromCartesian(const IndiciesVector & refShell, const GradientDirectionContainerType * refGradientsContainer) { vnl_matrix Q(3, refShell.size()); Q.fill(0.0); for(unsigned int i = 0; i < refShell.size(); i++) { GradientDirectionType dir = refGradientsContainer->ElementAt(refShell[i]); double x = dir.normalize().get(0); double y = dir.normalize().get(1); double z = dir.normalize().get(2); double cart[3]; mitk::sh::Cart2Sph(x,y,z,cart); Q(0,i) = cart[0]; Q(1,i) = cart[1]; Q(2,i) = cart[2]; } return Q; } vnl_matrix mitk::gradients::ComputeSphericalHarmonicsBasis(const vnl_matrix & QBallReference, const unsigned int & LOrder) { vnl_matrix SHBasisOutput(QBallReference.cols(), (LOrder+1)*(LOrder+2)*0.5); SHBasisOutput.fill(0.0); for(int i=0; i< (int)SHBasisOutput.rows(); i++) for(int k = 0; k <= (int)LOrder; k += 2) for(int m =- k; m <= k; m++) { int j = ( k * k + k + 2 ) / 2.0 + m - 1; double phi = QBallReference(0,i); double th = QBallReference(1,i); double val = mitk::sh::Yj(m,k,th,phi); SHBasisOutput(i,j) = val; } return SHBasisOutput; } mitk::gradients::GradientDirectionContainerType::Pointer mitk::gradients::CreateNormalizedUniqueGradientDirectionContainer(const mitk::gradients::BValueMap & bValueMap, const GradientDirectionContainerType *origninalGradentcontainer) { mitk::gradients::GradientDirectionContainerType::Pointer directioncontainer = mitk::gradients::GradientDirectionContainerType::New(); BValueMap::const_iterator mapIterator = bValueMap.begin(); if(bValueMap.find(0) != bValueMap.end() && bValueMap.size() > 1){ mapIterator++; //skip bzero Values vnl_vector_fixed vec; vec.fill(0.0); directioncontainer->push_back(vec); } for( ; mapIterator != bValueMap.end(); mapIterator++){ IndiciesVector currentShell = mapIterator->second; while(currentShell.size()>0) { unsigned int wntIndex = currentShell.back(); currentShell.pop_back(); mitk::gradients::GradientDirectionContainerType::Iterator containerIt = directioncontainer->Begin(); bool directionExist = false; while(containerIt != directioncontainer->End()) { if (fabs(dot(containerIt.Value(), origninalGradentcontainer->ElementAt(wntIndex))) > 0.9998) { directionExist = true; break; } containerIt++; } if(!directionExist) { GradientDirectionType dir(origninalGradentcontainer->ElementAt(wntIndex)); directioncontainer->push_back(dir.normalize()); } } } return directioncontainer; } diff --git a/Modules/DiffusionImaging/FiberTracking/Algorithms/itkFieldmapGeneratorFilter.h b/Modules/DiffusionImaging/FiberTracking/Algorithms/itkFieldmapGeneratorFilter.h index 0398ca7e8a..74e17eb311 100644 --- a/Modules/DiffusionImaging/FiberTracking/Algorithms/itkFieldmapGeneratorFilter.h +++ b/Modules/DiffusionImaging/FiberTracking/Algorithms/itkFieldmapGeneratorFilter.h @@ -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. ===================================================================*/ #ifndef __itkFieldmapGeneratorFilter_h__ #define __itkFieldmapGeneratorFilter_h__ #include #include #include #include -#include +#include #include #include namespace itk{ /** * \brief Generate float image with artificial frequency maps used by Fiberfox. Simulates additional frequencies at (possibly multiple) positions based on 3D gaussians with the specified variance and amplitude and/or as a linear gradient in the image. * See "Fiberfox: Facilitating the creation of realistic white matter software phantoms" (DOI: 10.1002/mrm.25045) for details. */ template< class OutputImageType > class FieldmapGeneratorFilter : public ImageSource< OutputImageType > { public: typedef FieldmapGeneratorFilter Self; typedef ProcessObject Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; typedef typename OutputImageType::PixelType PixelType; typedef typename OutputImageType::IndexType IndexType; typedef itk::ImageRegion<3> OutputImageRegionType; typedef itk::Matrix MatrixType; itkFactorylessNewMacro(Self) itkCloneMacro(Self) itkTypeMacro( FieldmapGeneratorFilter, ImageSource ) /** Output image parameters. */ itkSetMacro( Spacing, itk::Vector ) itkSetMacro( Origin, mitk::Point3D ) itkSetMacro( DirectionMatrix, MatrixType ) itkSetMacro( ImageRegion, OutputImageRegionType ) /** Gradient direction and offset. */ void SetGradient( vnl_vector_fixed< double, 3 > gradient ) { m_Gradient=gradient; } void SetOffset( vnl_vector_fixed< double, 3 > offset ) { m_Offset=offset; } /** Parameters of gaussian frequency sources. */ void SetVariances( std::vector< double > variances ) { m_Variances=variances; } void SetHeights( std::vector< double > heights ) { m_Heights=heights; } void SetWorldPositions( std::vector< mitk::Point3D > worldPositions ) { m_WorldPositions=worldPositions; } protected: void BeforeThreadedGenerateData(); void ThreadedGenerateData( const OutputImageRegionType &outputRegionForThread, ThreadIdType threadId); FieldmapGeneratorFilter(); virtual ~FieldmapGeneratorFilter(); itk::Vector m_Spacing; ///< output image spacing mitk::Point3D m_Origin; ///< output image origin MatrixType m_DirectionMatrix; ///< output image rotation OutputImageRegionType m_ImageRegion; ///< output image size std::vector< double > m_Variances; std::vector< double > m_Heights; std::vector< mitk::Point3D > m_WorldPositions; vnl_vector_fixed< double, 3 > m_Gradient; vnl_vector_fixed< double, 3 > m_Offset; }; } #ifndef ITK_MANUAL_INSTANTIATION #include "itkFieldmapGeneratorFilter.cpp" #endif #endif // __itkFieldmapGeneratorFilter_h__ diff --git a/Modules/DiffusionImaging/FiberTracking/Interactions/mitkFiberBundleInteractor.h b/Modules/DiffusionImaging/FiberTracking/Interactions/mitkFiberBundleInteractor.h index d6aad362cf..f2467bc717 100644 --- a/Modules/DiffusionImaging/FiberTracking/Interactions/mitkFiberBundleInteractor.h +++ b/Modules/DiffusionImaging/FiberTracking/Interactions/mitkFiberBundleInteractor.h @@ -1,99 +1,99 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKFiberBundleINTERACTOR_H_HEADER_INCLUDED #define MITKFiberBundleINTERACTOR_H_HEADER_INCLUDED #include "mitkCommon.h" #include "MitkExtExports.h" #include -#include +#include #include #include namespace mitk { class DataNode; //##Documentation //## @brief Just select a point, that's the only way to interact with the point //## //## Interact with a point: Select the point without moving to get parameters that does not change //## All Set-operations would be done through the method "ExecuteAction", if there would be anyone. //## the identificationnumber of this point is set by this points and evalued from an empty place in the DataStructure //## @ingroup Interaction class MitkFiberTracking_EXPORT FiberBundleInteractor : public Interactor { public: mitkClassMacro(FiberBundleInteractor, Interactor); mitkNewMacro2Param(Self, const char*, DataNode*); //##Documentation //## @brief Sets the amount of precision void SetPrecision(unsigned int precision); //##Documentation //## @brief derived from mitk::Interactor; calculates Jurisdiction according to points //## //## standard method can not be used, since it doesn't calculate in points, only in BoundingBox of Points virtual float CanHandleEvent(StateEvent const* stateEvent) const; protected: //##Documentation //##@brief Constructor FiberBundleInteractor(const char * type, DataNode* dataNode); //##Documentation //##@brief Destructor virtual ~FiberBundleInteractor(); //##Documentation //## @brief select the point on the given position virtual void SelectFiber(int position); //##Documentation //## @brief unselect all points that exist in mesh virtual void DeselectAllFibers(); //##Documentation //## @brief Executes Actions virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); private: //##Documentation //## @brief to calculate a direction vector from last point and actual point Point3D m_LastPoint; //##Documentation //## @brief to store a position unsigned int m_LastPosition; // Point3D m_InitialPickedPoint; // Point2D m_InitialPickedDisplayPoint; // double m_InitialPickedPointWorld[4]; Point3D m_CurrentPickedPoint; Point2D m_CurrentPickedDisplayPoint; double m_CurrentPickedPointWorld[4]; }; } #endif /* MITKFiberBundleInteractor_H_HEADER_INCLUDED */ diff --git a/Modules/Ext/Controllers/mitkTDMouseVtkCameraController.cpp b/Modules/Ext/Controllers/mitkTDMouseVtkCameraController.cpp index fc8f759938..9cdcd2fd2f 100644 --- a/Modules/Ext/Controllers/mitkTDMouseVtkCameraController.cpp +++ b/Modules/Ext/Controllers/mitkTDMouseVtkCameraController.cpp @@ -1,241 +1,241 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkTDMouseVtkCameraController.h" #include "mitkVtkPropRenderer.h" #include "vtkCamera.h" #include "vtkRenderer.h" #include "vtkTransform.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "mitkInteractionConst.h" #include "mitkStateEvent.h" #include "mitkTDMouseEventThrower.h" #include "mitkTDMouseEvent.h" #include "mitkGlobalInteraction.h" #include "vtkMath.h" const double TRANSLATIONSENSITIVITY = 2.0; const double ROTATIONSENSIVITY = 3.5; const double ANGLESENSITIVITY = 3.5; mitk::TDMouseVtkCameraController::TDMouseVtkCameraController() : CameraController("TDMouseInteraction") { //activate and instanciate EventThrower mitk::TDMouseEventThrower* thrower = mitk::TDMouseEventThrower::GetInstance(); //add this to GlobalInteracion to listen to events mitk::GlobalInteraction::GetInstance()->AddListener(this); //connect method this->OnTDMouseEvent to StateMachineEventMechanism CONNECT_ACTION(AcONTDMOUSEINPUT, OnTDMouseEvent); CONNECT_ACTION(AcONTDMOUSEKEYDOWN, OnTDMouseKeyDown); m_ClippingRangeIsSet = false; } mitk::TDMouseVtkCameraController::~TDMouseVtkCameraController() { } bool mitk::TDMouseVtkCameraController::OnTDMouseEvent(mitk::Action* a, const mitk::StateEvent* e) { //only if 3D rendering mitk::BaseRenderer const* br = this->GetRenderer(); mitk::BaseRenderer::MapperSlotId id = ((mitk::BaseRenderer*)(br))->GetMapperID(); if (id != mitk::BaseRenderer::Standard3D) return true; //only if focused by the FocusManager if (this->GetRenderer() != mitk::GlobalInteraction::GetInstance()->GetFocus()) return true; //pre-checking for safety vtkRenderer* vtkRenderer = ((mitk::VtkPropRenderer*)this->GetRenderer())->GetVtkRenderer(); if (vtkRenderer == NULL) return false; vtkCamera* vtkCam = (vtkCamera*)vtkRenderer->GetActiveCamera(); if(!m_ClippingRangeIsSet) vtkCam->SetClippingRange(0.1, 1000000); const mitk::TDMouseEvent* tdevent = dynamic_cast(e->GetEvent()); if (tdevent == NULL) { std::cout<<"Wrong event for TDMouseCameraController!"<GetTranslation(); mitk::Vector3D rotation = tdevent->GetRotation(); mitk::ScalarType angle = tdevent->GetAngle(); //output for debug //std::cout<<"translation: "<GetDataStorage(); mitk::BoundingBox::Pointer bb = ds->ComputeBoundingBox(); mitk::BoundingBox::AccumulateType length = bb->GetDiagonalLength2(); if (length > 0.00001)//if length not zero sceneSensivity *= 100.0 / (sqrt(length)) ; //sensivity to adapt to mitk speed translation *= sceneSensivity * TRANSLATIONSENSITIVITY; rotation *= sceneSensivity * ROTATIONSENSIVITY; angle *= sceneSensivity * ANGLESENSITIVITY; //compute the global space coordinates from the relative mouse coordinate //first we need the position of the camera mitk::Vector3D camPosition; double camPositionTemp[3]; vtkCam->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]; vtkCam->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]; vtkCam->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(); //now we have the current orientation so we can adapt it according to the current information, which we got from the TDMouse //new position of the camera: //left/right = camPosition + crossVector * translation[0]; mitk::Vector3D vectorX = crossVector * -translation[0]; //changes the magnitude, not the direction double nextCamPosition[3]; nextCamPosition[0] = camPosition[0] + vectorX[0]; nextCamPosition[1] = camPosition[1] + vectorX[1]; nextCamPosition[2] = camPosition[2] + vectorX[2]; //now the up/down movement mitk::Vector3D vectorY = upCamVector * translation[1]; //changes the magnitude, not the direction nextCamPosition[0] += vectorY[0]; nextCamPosition[1] += vectorY[1]; nextCamPosition[2] += vectorY[2]; //forward/backward movement mitk::Vector3D vectorZ = focalVector * -translation[2]; //changes the magnitude, not the direction nextCamPosition[0] += vectorZ[0]; nextCamPosition[1] += vectorZ[1]; nextCamPosition[2] += vectorZ[2]; //set the next position double nextPosition[3]; nextPosition[0] = nextCamPosition[0]; nextPosition[1] = nextCamPosition[1]; nextPosition[2] = nextCamPosition[2]; vtkCam->SetPosition(nextPosition); //adapt the focal point the same way double currentFocalPoint[3], nextFocalPoint[3]; vtkCam->GetFocalPoint(currentFocalPoint); nextFocalPoint[0] = currentFocalPoint[0] + vectorX[0] + vectorY[0] + vectorZ[0]; nextFocalPoint[1] = currentFocalPoint[1] + vectorX[1] + vectorY[1] + vectorZ[1]; ; nextFocalPoint[2] = currentFocalPoint[2] + vectorX[2] + vectorY[2] + vectorZ[2]; vtkCam->SetFocalPoint(nextFocalPoint); //now adapt the rotation of the mouse and adapt the camera according to it //Pitch: //Rotate the focal point about the cross product of the view up vector and the direction of //projection, centered at the camera's position. vtkCam->Pitch(rotation[0]*angle); //Yaw: //Rotate the focal point about the view up vector centered at the camera's position. //Note that the view up vector is not necessarily perpendicular to the direction of projection. vtkCam->Yaw(rotation[1]*angle); //Roll: //Rotate the camera about the direction of projection. vtkCam->Roll(-rotation[2]*angle * 1.5);//*1.5 to speed up the rotation[2] a little bit //Recompute the ViewUp vector to force it to be perpendicular to camera->focalpoint vector. //Unless you are going to use Yaw or Azimuth on the camera, there is no need to do this. vtkCam->OrthogonalizeViewUp(); //no zooming, only translating to the front or back // dolly: Move the position of the camera along the direction // of projection. Moving towards the focal point (e.g., greater // than 1) is a dolly-in, moving away from the focal point // (e.g., less than 1) is a dolly-out. //double distance = ((tdevent->GetTranslation())[1] / 10.0);//make it less sensitive in comparison to translation and rotatipn //vtkCam->Dolly(1.0 + distance ); //Reset the camera clipping range based on the bounds of the visible actors. //This ensures that no props are cut off vtkRenderer->ResetCameraClippingRange(); mitk::RenderingManager::GetInstance()->ForceImmediateUpdate(mitk::GlobalInteraction::GetInstance()->GetFocus()->GetRenderWindow()); return true; } bool mitk::TDMouseVtkCameraController::OnTDMouseKeyDown(mitk::Action* a, const mitk::StateEvent* e) { //reset the camera, so that the objects shown in the scene can be seen. const mitk::VtkPropRenderer* glRenderer = dynamic_cast(m_Renderer); if (glRenderer) { vtkRenderer* vtkRenderer = glRenderer->GetVtkRenderer(); mitk::DataStorage* ds = m_Renderer->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; } diff --git a/Modules/Ext/DataManagement/mitkAffineTransformationOperation.h b/Modules/Ext/DataManagement/mitkAffineTransformationOperation.h index 17f753605c..95171dd660 100644 --- a/Modules/Ext/DataManagement/mitkAffineTransformationOperation.h +++ b/Modules/Ext/DataManagement/mitkAffineTransformationOperation.h @@ -1,45 +1,45 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKAFFINETRANSFORMATIONOPERATION_H_HEADER_INCLUDED #define MITKAFFINETRANSFORMATIONOPERATION_H_HEADER_INCLUDED #include "mitkPointOperation.h" #include "MitkExtExports.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" namespace mitk { //##Documentation //## @brief Operation, that holds everything necessary for an affine operation. //## //## @ingroup Undo class MitkExt_EXPORT AffineTransformationOperation : public PointOperation { public: AffineTransformationOperation(OperationType operationType, Point3D point, ScalarType angle, int index); virtual ~AffineTransformationOperation(void); ScalarType GetAngle(); protected: ScalarType m_Angle; }; } // namespace mitk #endif /* MITKAFFINETRANSFORMATIONOPERATION_H_HEADER_INCLUDED */ diff --git a/Modules/Ext/DataManagement/mitkDrawOperation.h b/Modules/Ext/DataManagement/mitkDrawOperation.h index 127fb5a573..eb7b818f9b 100755 --- a/Modules/Ext/DataManagement/mitkDrawOperation.h +++ b/Modules/Ext/DataManagement/mitkDrawOperation.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 MITKDRAWOPERATION_H #define MITKDRAWOPERATION_H #include #include "MitkExtExports.h" #include -#include +#include #include #include namespace mitk { //##Documentation //## @brief DrawOperation, that handles all actions on seeds. //## //## Stores everything for adding and deleting seeds. //## @ingroup Undo class MitkExt_EXPORT DrawOperation : public Operation { public: //##Documentation //##@brief DrawOperation, that handles all actions on seeds. //## //## @param operationType is the type of that operation (see mitkOperation.h; e.g. move or add; Information for StateMachine::ExecuteOperation()); //## @param point is the information of the seedpoint to add to the seedsimage //## @param last_point is the information of the point added before //## @param draw_state represents the seeds type e.g foreground or background seeds //## @param radius is the radius of seeds DrawOperation(OperationType operationType, Point3D point, Point3D last_point, int draw_state, int radius); virtual ~DrawOperation(); Point3D GetPoint(); Point3D GetLastPoint(); int GetDrawState(); int GetRadius(); SeedsImage::Pointer GetSeedsImage(); SeedsImage::Pointer GetLastSeedsImage(); private: Point3D m_Point; Point3D m_LastPoint; int m_DrawState; int m_Radius; SeedsImage::Pointer m_SeedsImage; SeedsImage::Pointer m_LastSeedsImage; }; }//namespace mitk #endif /* MITKDRAWOPERATION_H*/ diff --git a/Modules/Ext/DataManagement/mitkNamedPoint.h b/Modules/Ext/DataManagement/mitkNamedPoint.h index 4cb928f678..fa983c10cf 100644 --- a/Modules/Ext/DataManagement/mitkNamedPoint.h +++ b/Modules/Ext/DataManagement/mitkNamedPoint.h @@ -1,89 +1,89 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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_NAMED_POINT_H #define MITK_NAMED_POINT_H -#include +#include #include namespace mitk { class NamedPoint{ std::string m_Name; mitk::Point3D m_Point; public: /** * */ NamedPoint() { }; /** * */ NamedPoint( const NamedPoint& namedPoint ) : m_Name( namedPoint.m_Name ), m_Point( namedPoint.m_Point ) { }; /** * */ NamedPoint( const std::string name, const Point3D& point ) : m_Name( name ), m_Point( point ) { }; /** * */ const std::string& GetName() const { return m_Name; }; /** * */ void SetName( const std::string& name ) { m_Name = name; }; /** * */ const Point3D& GetPoint() const { return m_Point; }; /** * */ void SetPoint( const Point3D& point ) { m_Point = point; }; }; } // mitk #endif // MITK_NAMED_POINT_H diff --git a/Modules/Ext/Interactions/mitkConnectPointsInteractor.h b/Modules/Ext/Interactions/mitkConnectPointsInteractor.h index 0e0112b9d7..e8a2308923 100644 --- a/Modules/Ext/Interactions/mitkConnectPointsInteractor.h +++ b/Modules/Ext/Interactions/mitkConnectPointsInteractor.h @@ -1,97 +1,97 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKCONNECTPOINTSINTERACTOR_H_HEADER_INCLUDED_C11202FF #define MITKCONNECTPOINTSINTERACTOR_H_HEADER_INCLUDED_C11202FF #include "mitkCommon.h" #include "MitkExtExports.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include namespace mitk { class DataNode; //##Documentation //## @brief Interaction for mitk::Mesh: Connect existing points to lines //## @ingroup Interaction class MitkExt_EXPORT ConnectPointsInteractor : public Interactor { public: mitkClassMacro(ConnectPointsInteractor, Interactor); mitkNewMacro3Param(Self, const char*, DataNode*, int); mitkNewMacro2Param(Self, const char*, DataNode*); //##Documentation //## @brief Sets the amount of precision void SetPrecision( unsigned int precision ); //##Documentation //## @brief calculates how good the data, this statemachine handles, is hit by the event. //## //## overwritten, cause we don't look at the boundingbox, we look at each point virtual float CanHandleEvent(StateEvent const* stateEvent) const; protected: //##Documentation //##@brief Constructor with Param n for limited Set of Points //## //## if no n is set, then the number of points is unlimited* ConnectPointsInteractor(const char * type, DataNode* dataNode, int n = -1); virtual ~ConnectPointsInteractor(); virtual bool ExecuteAction( Action* action, mitk::StateEvent const* stateEvent ); //##Documentation //## @brief deselects the Points in the PointSet. //## supports Undo if enabled void UnselectAll(); //##Documentation //## @brief Selects the point. //## supports Undo if enabled. //## @param position is the index of the point that has to be selected void SelectPoint( int position ); private: //##Documentation //## @brief the number of possible points in this object //## //## if -1, then no limit set int m_N; //##Documentation //## @brief stores the current CellId this Statemachine works in unsigned int m_CurrentCellId; //##Documentation //## @brief to calculate a direction vector from last point and actual point Point3D m_LastPoint; //##Documentation //## @brief summ-vector for Movement Vector3D m_SumVec; //##Documentation //## @brief to store the value of precision to pick a point unsigned int m_Precision; }; } #endif /* MITKCONNECTPOINTSINTERACTOR_H_HEADER_INCLUDED_C11202FF */ diff --git a/Modules/Ext/Interactions/mitkDisplayPointSetInteractor.cpp b/Modules/Ext/Interactions/mitkDisplayPointSetInteractor.cpp index 24fcaccf5d..9945b641c9 100644 --- a/Modules/Ext/Interactions/mitkDisplayPointSetInteractor.cpp +++ b/Modules/Ext/Interactions/mitkDisplayPointSetInteractor.cpp @@ -1,135 +1,135 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkDisplayPointSetInteractor.h" #include "mitkInteractionConst.h" #include "mitkStateEvent.h" #include "mitkBaseRenderer.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" mitk::DisplayPointSetInteractor ::DisplayPointSetInteractor(const char * type, DataNode* dataNode, int n) :PointSetInteractor(type, dataNode, n) { } mitk::DisplayPointSetInteractor::~DisplayPointSetInteractor() { } bool mitk::DisplayPointSetInteractor ::ExecuteAction( Action* action, mitk::StateEvent const* stateEvent ) { bool ok = false;//for return type bool //get the timestep to also support 3D+T //const mitk::Event *theEvent = stateEvent->GetEvent(); /*Each case must watch the type of the event!*/ /*Each time a Point is added or removed or finished moved, the display-coordinates and the last renderer is stored.*/ switch (action->GetActionId()) { case AcADDPOINT: { mitk::DisplayPositionEvent const *posEvent = dynamic_cast < const mitk::DisplayPositionEvent * > (stateEvent->GetEvent()); if ( posEvent == NULL ) { return false; } m_LastDisplayCoordinates = posEvent->GetDisplayPosition(); m_LastRenderer = posEvent->GetSender(); ok = Superclass::ExecuteAction( action, stateEvent ); break; } case AcREMOVEPOINT://remove the given Point from the list { mitk::DisplayPositionEvent const *posEvent = dynamic_cast < const mitk::DisplayPositionEvent * > (stateEvent->GetEvent()); if ( posEvent == NULL ) { return false; } m_LastDisplayCoordinates = posEvent->GetDisplayPosition(); m_LastRenderer = posEvent->GetSender(); ok = Superclass::ExecuteAction( action, stateEvent ); break; } case AcREMOVEALL: { mitk::DisplayPositionEvent const *posEvent = dynamic_cast < const mitk::DisplayPositionEvent * > (stateEvent->GetEvent()); if ( posEvent == NULL ) { return false; } m_LastDisplayCoordinates = posEvent->GetDisplayPosition(); m_LastRenderer = posEvent->GetSender(); ok = Superclass::ExecuteAction( action, stateEvent ); break; } case AcFINISHMOVEMENT: { mitk::DisplayPositionEvent const *posEvent = dynamic_cast < const mitk::DisplayPositionEvent * > (stateEvent->GetEvent()); if ( posEvent == NULL ) { return false; } m_LastDisplayCoordinates = posEvent->GetDisplayPosition(); m_LastRenderer = posEvent->GetSender(); ok = Superclass::ExecuteAction( action, stateEvent ); break; } default: return Superclass::ExecuteAction( action, stateEvent ); } return ok; } mitk::Point2D mitk::DisplayPointSetInteractor::GetLastDisplayCoordinates() { return m_LastDisplayCoordinates; } mitk::BaseRenderer* mitk::DisplayPointSetInteractor::GetLastRenderer() { return m_LastRenderer; } diff --git a/Modules/Ext/Interactions/mitkDisplayPointSetInteractor.h b/Modules/Ext/Interactions/mitkDisplayPointSetInteractor.h index e2cc423751..25eda89b8a 100644 --- a/Modules/Ext/Interactions/mitkDisplayPointSetInteractor.h +++ b/Modules/Ext/Interactions/mitkDisplayPointSetInteractor.h @@ -1,78 +1,78 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKDISPLAYPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF #define MITKDISPLAYPOINTSETINTERACTOR_H_HEADER_INCLUDED_C11202FF #include "mitkCommon.h" #include "MitkExtExports.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include #include "mitkPointSetInteractor.h" #include namespace mitk { class DataNode; /** * \brief Interaction with a set of points. * * Points can be added, removed and moved. * \ingroup Interaction */ class MitkExt_EXPORT DisplayPointSetInteractor : public PointSetInteractor { public: mitkClassMacro(DisplayPointSetInteractor, PointSetInteractor); mitkNewMacro3Param(Self, const char*, DataNode*, int); mitkNewMacro2Param(Self, const char*, DataNode*); Point2D GetLastDisplayCoordinates(); BaseRenderer* GetLastRenderer(); protected: /** * \brief Constructor with Param n for limited Set of Points * * if no n is set, then the number of points is unlimited* */ DisplayPointSetInteractor(const char * type, DataNode* dataNode, int n = -1); /** * \brief Default Destructor **/ virtual ~DisplayPointSetInteractor(); virtual bool ExecuteAction( Action* action, mitk::StateEvent const* stateEvent ); /** \brief last display-coordinates of the point * */ Point2D m_LastDisplayCoordinates; mitk::BaseRenderer* m_LastRenderer; }; } #endif /* MITKDisplayPointSetInteractor_H_HEADER_INCLUDED_C11202FF */ diff --git a/Modules/Ext/Interactions/mitkPointInteractor.h b/Modules/Ext/Interactions/mitkPointInteractor.h index b55c47e684..2b4ae96e34 100644 --- a/Modules/Ext/Interactions/mitkPointInteractor.h +++ b/Modules/Ext/Interactions/mitkPointInteractor.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 MITKPOINTINTERACTOR_H_HEADER_INCLUDED #define MITKPOINTINTERACTOR_H_HEADER_INCLUDED #include "mitkCommon.h" #include "MitkExtExports.h" #include -#include +#include namespace mitk { class DataNode; //##Documentation //## @brief Interaction with a point //## //## Interact with a point: set point, select point, move point and remove point //## All Set-operations are done through the method "ExecuteAction". //## the identificationnumber of this point is set by this points and evalued from an empty place in the DataStructure //## @ingroup Interaction class MitkExt_EXPORT PointInteractor : public Interactor { public: mitkClassMacro(PointInteractor, Interactor); mitkNewMacro2Param(Self, const char*, DataNode*); //##Documentation //## @brief Sets the amount of precision void SetPrecision(unsigned int precision); //##Documentation //## @brief derived from mitk::Interactor; calculates Jurisdiction according to points //## //## standard method can not be used, since it doesn't calculate in points, only in BoundingBox of Points virtual float CanHandleEvent(StateEvent const* stateEvent) const; protected: //##Documentation //##@brief Constructor PointInteractor(const char * type, DataNode* dataNode); //##Documentation //##@brief Destructor virtual ~PointInteractor(); //##Documentation //## @brief select the point on the given position virtual void SelectPoint(int position); //##Documentation //## @brief unselect all points that exist in mesh virtual void DeselectAllPoints(); //##Documentation //## @brief Executes Actions virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); private: //##Documentation //## @brief to calculate a direction vector from last point and actual point Point3D m_LastPoint; //##Documentation //## @brief to store a position unsigned int m_LastPosition; }; } #endif /* MITKPOINTINTERACTOR_H_HEADER_INCLUDED */ diff --git a/Modules/Ext/Interactions/mitkPointSelectorInteractor.h b/Modules/Ext/Interactions/mitkPointSelectorInteractor.h index d4c4c0a737..05adfa433e 100644 --- a/Modules/Ext/Interactions/mitkPointSelectorInteractor.h +++ b/Modules/Ext/Interactions/mitkPointSelectorInteractor.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 MITKPOINTSELECTORINTERACTOR_H_HEADER_INCLUDED #define MITKPOINTSELECTORINTERACTOR_H_HEADER_INCLUDED #include "mitkCommon.h" #include "MitkExtExports.h" #include -#include +#include namespace mitk { class DataNode; //##Documentation //## @brief Just select a point, that's the only way to interact with the point //## //## Interact with a point: Select the point without moving to get parameters that does not change //## All Set-operations would be done through the method "ExecuteAction", if there would be anyone. //## the identificationnumber of this point is set by this points and evalued from an empty place in the DataStructure //## @ingroup Interaction class MitkExt_EXPORT PointSelectorInteractor : public Interactor { public: mitkClassMacro(PointSelectorInteractor, Interactor); mitkNewMacro2Param(Self, const char*, DataNode*); //##Documentation //## @brief Sets the amount of precision void SetPrecision(unsigned int precision); //##Documentation //## @brief derived from mitk::Interactor; calculates Jurisdiction according to points //## //## standard method can not be used, since it doesn't calculate in points, only in BoundingBox of Points virtual float CanHandleEvent(StateEvent const* stateEvent) const; protected: //##Documentation //##@brief Constructor PointSelectorInteractor(const char * type, DataNode* dataNode); //##Documentation //##@brief Destructor virtual ~PointSelectorInteractor(); //##Documentation //## @brief select the point on the given position virtual void SelectPoint(int position); //##Documentation //## @brief unselect all points that exist in mesh virtual void DeselectAllPoints(); //##Documentation //## @brief Executes Actions virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); private: //##Documentation //## @brief to calculate a direction vector from last point and actual point Point3D m_LastPoint; //##Documentation //## @brief to store a position unsigned int m_LastPosition; }; } #endif /* MITKPointSelectorInteractor_H_HEADER_INCLUDED */ diff --git a/Modules/Ext/Interactions/mitkSeedsInteractor.h b/Modules/Ext/Interactions/mitkSeedsInteractor.h index 21baf5732a..8d30dfc594 100644 --- a/Modules/Ext/Interactions/mitkSeedsInteractor.h +++ b/Modules/Ext/Interactions/mitkSeedsInteractor.h @@ -1,72 +1,72 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 __SeedsInteractor_H #define __SeedsInteractor_H #include #include "MitkExtExports.h" #include -#include +#include #include //needed by QmitkSimplexMeshes (SMDeformation.cpp and LungSegmentation.cpp) #include #include namespace mitk { //##Documentation //## @brief SeedsInteractor handles all actions on the seedsimage //## @ingroup Interaction class MitkExt_EXPORT SeedsInteractor : public Interactor { public: mitkClassMacro(SeedsInteractor, Interactor); mitkNewMacro2Param(Self, const char*, DataNode*); /// sets the radius of the seeds. void SetRadius(int val){m_Radius=val;}; void SetCurrentDrawState(int val){m_CurrentDrawState = val;}; itkSetMacro(Config, unsigned int); itkGetMacro(Config, unsigned int); protected: /** * @brief Default Constructor **/ SeedsInteractor(const char * type, DataNode* dataNode); /** * @brief Default Destructor **/ virtual ~SeedsInteractor(); virtual bool ExecuteAction(Action* action, StateEvent const* stateEvent); protected: SeedsImage::Pointer m_SeedsImage; SeedsImage::Pointer m_LastSeedsImage; Point3D event_point; Point3D last_point; int m_Radius; int m_DrawState; int m_CurrentDrawState; unsigned int m_Config; // determine whether 254,255 or smoothed float values are used. }; } #endif //__SeedsInteractor_H diff --git a/Modules/Ext/Interactions/mitkTDMouseEvent.cpp b/Modules/Ext/Interactions/mitkTDMouseEvent.cpp index a64b863683..13e62055d0 100644 --- a/Modules/Ext/Interactions/mitkTDMouseEvent.cpp +++ b/Modules/Ext/Interactions/mitkTDMouseEvent.cpp @@ -1,25 +1,25 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkTDMouseEvent.h" #include "mitkInteractionConst.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" mitk::TDMouseEvent::TDMouseEvent(int buttonState, const Vector3D& translation, const Vector3D& rotation, const ScalarType& angle) : Event(NULL, Type_TDMouseInput, BS_NoButton, buttonState, Key_none), m_Translation(translation), m_Rotation(rotation), m_Angle(angle) { } diff --git a/Modules/Ext/Interactions/mitkTDMouseEvent.h b/Modules/Ext/Interactions/mitkTDMouseEvent.h index 769b55a0e5..9e69d43eb3 100644 --- a/Modules/Ext/Interactions/mitkTDMouseEvent.h +++ b/Modules/Ext/Interactions/mitkTDMouseEvent.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 TDMOUSEEVENT_H_HEADER_INCLUDED #define TDMOUSEEVENT_H_HEADER_INCLUDED #include "mitkCommon.h" #include "mitkEvent.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" namespace mitk { //##Documentation //## @brief Event on 3D Mouse input //## //## Seven coordinates exposed by the 3D Mouse: //## 3-dimensional translation vector //## 3-dimensional rotation achsis (length allways 1.0) //## scalar rotation angle //## @ingroup Interaction class TDMouseEvent : public Event { public: //##Documentation //## @brief Constructor with all necessary arguments. //## //## buttonState: information from the Event TDMouseEvent(int buttonState, const Vector3D& translation, const Vector3D& rotation, const ScalarType& angle); const Vector3D& GetTranslation() const { return m_Translation; } void SetTranslation(const Vector3D& translation) { m_Translation = translation; } const Vector3D& GetRotation() const { return m_Rotation; } void SetRotation(const Vector3D& rotation) { m_Rotation = rotation; } const ScalarType& GetAngle() const { return m_Angle; } void SetAngle(const ScalarType& angle) { m_Angle = angle; } protected: Vector3D m_Translation; Vector3D m_Rotation; ScalarType m_Angle; }; } // namespace mitk #endif /* TDMOUSEEVENT_H_HEADER_INCLUDED */ diff --git a/Modules/Ext/Interactions/mitkTDMouseEventThrower.cpp b/Modules/Ext/Interactions/mitkTDMouseEventThrower.cpp index 90bb81bd0f..b419761930 100644 --- a/Modules/Ext/Interactions/mitkTDMouseEventThrower.cpp +++ b/Modules/Ext/Interactions/mitkTDMouseEventThrower.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 "mitkTDMouseEventThrower.h" #include "mitkTDMouseEvent.h" #include "mitkInteractionConst.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "mitkGlobalInteraction.h" #include "mitkStateEvent.h" #include "mitkSpaceNavigatorDriver.h" mitk::TDMouseEventThrower * mitk::TDMouseEventThrower::GetInstance() { //instance will not be initialize and return 0 static TDMouseEventThrower instance; return &instance; } mitk::TDMouseEventThrower::TDMouseEventThrower() { //init the driver SpaceNavigatorDriver* spaceNavigatorDriver = SpaceNavigatorDriver::GetInstance(); } mitk::TDMouseEventThrower::~TDMouseEventThrower() { } void mitk::TDMouseEventThrower::DeviceChange (long device, long keys, long programmableKeys) { } void mitk::TDMouseEventThrower::KeyDown (int keyCode) { //send the informations to GlobalInteraction mitk::Event* e = new mitk::Event(NULL, mitk::Type_TDMouseKeyDown, mitk::BS_LeftButton, keyCode, mitk::Key_none); mitk::StateEvent* se = new mitk::StateEvent(mitk::EIDTDMOUSEKEYDOWN, e); mitk::GlobalInteraction::GetInstance()->HandleEvent(se); } void mitk::TDMouseEventThrower::KeyUp (int keyCode) { } void mitk::TDMouseEventThrower::SensorInput( mitk::Vector3D translation, mitk::Vector3D rotation, mitk::ScalarType angle) { mitk::TDMouseEvent* e = new mitk::TDMouseEvent(mitk::BS_NoButton, translation, rotation, angle); mitk::StateEvent* se = new mitk::StateEvent(mitk::EIDTDMOUSEINPUT, e); mitk::GlobalInteraction::GetInstance()->HandleEvent(se); } diff --git a/Modules/Ext/Interactions/mitkTDMouseEventThrower.h b/Modules/Ext/Interactions/mitkTDMouseEventThrower.h index 6b916cbd31..9f86a61f32 100644 --- a/Modules/Ext/Interactions/mitkTDMouseEventThrower.h +++ b/Modules/Ext/Interactions/mitkTDMouseEventThrower.h @@ -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. ===================================================================*/ #ifndef TDMouseEventThrower__h__ #define TDMouseEventThrower__h__ -#include +#include #include namespace mitk { class TDMouseEventThrower { public: static TDMouseEventThrower* GetInstance(); void DeviceChange (long device, long keys, long programmableKeys); void KeyDown (int keyCode); void KeyUp (int keyCode); void SensorInput( mitk::Vector3D translation, mitk::Vector3D rotation, mitk::ScalarType angle); protected: TDMouseEventThrower(); ~TDMouseEventThrower(); }; }//namespace #endif // TDMouseEventThrower__h__ diff --git a/Modules/Ext/Testing/mitkPlaneFitTest.cpp b/Modules/Ext/Testing/mitkPlaneFitTest.cpp index eae0c6bb9e..7fbcd905c0 100644 --- a/Modules/Ext/Testing/mitkPlaneFitTest.cpp +++ b/Modules/Ext/Testing/mitkPlaneFitTest.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 #include #include -#include +#include #include #include int mitkPlaneFitTest(int, char*[] ) { //float bounds[]={0.0f,10.0f,0.0f,10.0f,0.0f,5.0f}; mitk::PlaneFit::Pointer PlaneFit = mitk::PlaneFit::New(); mitk::PointSet::Pointer PointSet = mitk::PointSet::New(); mitk::Geometry3D::Pointer Geometry3D = mitk::Geometry3D::New(); mitk::Point3D Point; //first without any point, then incrementally add points within thre points there will be a plane geometry std::cout <<"Start PlaneFitTest "<GetPointSet()->GetPoints()->InsertElement(position, Point); } //Set Input PlaneFit->SetInput(PointSet); const mitk::PointSet* testPointSet = PlaneFit->GetInput(); std::cout<<" Size test of Input Method: "; if( testPointSet->GetSize() == PointSet->GetSize() ) { std::cout<<"[PASSED]"<Update(); const mitk::Point3D ¢roid = PlaneFit->GetCentroid(); mitk::Point3D expectedCentroid; expectedCentroid[0]=2.5; expectedCentroid[1]=3.75; expectedCentroid[2]=2.5; if ( centroid == expectedCentroid ) { std::cout<<"[PASSED]"<( PlaneFit->GetOutput()->GetGeometry()); if( Geometry2D ) { std::cout<<"[PASSED]"< #include #include -#include +#include namespace mitk { /**Documentation * \brief Navigation Data * * This class represents the data object that is passed through the MITK-IGT navigation filter * pipeline. It encapsulates position and orientation of a tracked tool/sensor. Additionally, * it contains a data structure that contains error/plausibility information * * It provides methods to work with the affine transformation represented by its orientation and position. * Additionally, it provides a constructor to construct a NavigationData object from an AffineTransform3D and * a getter to create an AffineTransform3D from a NavigationData object. * * \ingroup IGT */ class MitkIGT_EXPORT NavigationData : public itk::DataObject { public: mitkClassMacro(NavigationData, itk::DataObject); itkFactorylessNewMacro(Self) itkCloneMacro(Self) mitkNewMacro2Param(Self, mitk::AffineTransform3D::Pointer, const bool); mitkNewMacro1Param(Self, mitk::AffineTransform3D::Pointer); /** * \brief Type that holds the position part of the tracking data */ typedef mitk::Point3D PositionType; /** * \brief Type that holds the orientation part of the tracking data */ typedef mitk::Quaternion OrientationType; /** * \brief type that holds the error characterization of the position and orientation measurements */ typedef itk::Matrix CovarianceMatrixType; /** * \brief type that holds the time at which the data was recorded */ typedef double TimeStampType; /** * \brief sets the position of the NavigationData object */ itkSetMacro(Position, PositionType); /** * \brief returns position of the NavigationData object */ itkGetConstMacro(Position, PositionType); /** * \brief sets the orientation of the NavigationData object */ itkSetMacro(Orientation, OrientationType); /** * \brief returns the orientation of the NavigationData object */ itkGetConstMacro(Orientation, OrientationType); /** * \brief returns true if the object contains valid data */ virtual bool IsDataValid() const; /** * \brief sets the dataValid flag of the NavigationData object indicating if the object contains valid data */ itkSetMacro(DataValid, bool); /** * \brief sets the IGT timestamp of the NavigationData object */ itkSetMacro(IGTTimeStamp, TimeStampType); /** * \brief gets the IGT timestamp of the NavigationData object */ itkGetConstMacro(IGTTimeStamp, TimeStampType); /** * \brief sets the HasPosition flag of the NavigationData object */ itkSetMacro(HasPosition, bool); /** * \brief gets the HasPosition flag of the NavigationData object */ itkGetConstMacro(HasPosition, bool); /** * \brief sets the HasOrientation flag of the NavigationData object */ itkSetMacro(HasOrientation, bool); /** * \brief gets the HasOrientation flag of the NavigationData object */ itkGetConstMacro(HasOrientation, bool); /** * \brief sets the 6x6 Error Covariance Matrix of the NavigationData object */ itkSetMacro(CovErrorMatrix, CovarianceMatrixType); /** * \brief gets the 6x6 Error Covariance Matrix of the NavigationData object */ itkGetConstMacro(CovErrorMatrix, CovarianceMatrixType); /** * \brief set the name of the NavigationData object */ itkSetStringMacro(Name); /** * \brief returns the name of the NavigationData object */ itkGetStringMacro(Name); /** * \brief Graft the data and information from one NavigationData to another. * * Copies the content of data into this object. * This is a convenience method to setup a second NavigationData object with all the meta * information of another NavigationData object. * Note that this method is different than just using two * SmartPointers to the same NavigationData object since separate DataObjects are * still maintained. */ virtual void Graft(const DataObject *data); /** * \brief copy meta data of a NavigationData object * * copies all meta data from NavigationData data to this object */ virtual void CopyInformation(const DataObject* data); /** * \brief Prints the object information to the given stream os. * \param os The stream which is used to print the output. * \param indent Defines the indentation of the output. */ void PrintSelf(std::ostream& os, itk::Indent indent) const; /** * Set the position part of m_CovErrorMatrix to I*error^2 * This means that all position variables are assumed to be independent */ void SetPositionAccuracy(mitk::ScalarType error); /** * Set the orientation part of m_CovErrorMatrix to I*error^2 * This means that all orientation variables are assumed to be independent */ void SetOrientationAccuracy(mitk::ScalarType error); /** * \brief Calculate AffineTransform3D from the transformation held by this NavigationData. * TODO: should throw an error if transformation is invalid. */ mitk::AffineTransform3D::Pointer GetAffineTransform3D() const; /** * \brief Calculate the RotationMatrix of this transformation. */ mitk::Matrix3D GetRotationMatrix() const; /** * \brief Transform by an affine transformation * * This method applies the affine transform given by self to a * given point, returning the transformed point. */ mitk::Point3D TransformPoint(const mitk::Point3D point) const; /** * Get inverse of the Transformation represented by this NavigationData. * @throws mitk::Exception in case the transformation is invalid (only case: quaternion is zero) */ mitk::NavigationData::Pointer GetInverse() const; /** Compose with another NavigationData * * This method composes self with another NavigationData of the * same dimension, modifying self to be the composition of self * and other. If the argument pre is true, then other is * precomposed with self; that is, the resulting transformation * consists of first applying other to the source, followed by * self. If pre is false or omitted, then other is post-composed * with self; that is the resulting transformation consists of * first applying self to the source, followed by other. */ void Compose(const mitk::NavigationData::Pointer n, const bool pre = false); protected: mitkCloneMacro(Self); NavigationData(); /* * Copy constructor internally used. */ NavigationData(const mitk::NavigationData& toCopy); /** * Creates a NavigationData object from an affineTransform3D. * Caution: NavigationData doesn't support spacing, only translation and rotation. If the affine * transform includes spacing it cannot be converted to a NavigationData and an exception is thrown. * @param checkForRotationMatrix if this is true, the rotation matrix coming from the affineTransform is checked * for being a rotation matrix. If it isn't, an exception is thrown. Disable this check by * setting checkForRotationMatrix to false. * * @throws mitkException if checkForRotationMatrix is true and a non rotation matrix was introduced by * AffineTransform. */ NavigationData(mitk::AffineTransform3D::Pointer affineTransform3D, const bool checkForRotationMatrix = true); virtual ~NavigationData(); /** * \brief holds the position part of the tracking data */ PositionType m_Position; /** * \brief holds the orientation part of the tracking data */ OrientationType m_Orientation; /** * \brief A 6x6 covariance matrix parameterizing the Gaussian error * distribution of the measured position and orientation. * * The hasPosition/hasOrientation fields define which entries * are valid. */ CovarianceMatrixType m_CovErrorMatrix; ///< holds the error characterization of the position and orientation /** * \brief defines if position part of m_CovErrorMatrix is valid */ bool m_HasPosition; /** * \brief defines if orientation part of m_CovErrorMatrix is valid */ bool m_HasOrientation; /** * \brief defines if the object contains valid values */ bool m_DataValid; /** * \brief contains the time at which the tracking data was recorded */ TimeStampType m_IGTTimeStamp; /** * \brief name of the navigation data */ std::string m_Name; private: void ResetCovarianceValidity(); // pre = false static mitk::NavigationData::Pointer getComposition(const mitk::NavigationData::Pointer nd1, const mitk::NavigationData::Pointer nd2); }; } // namespace mitk #endif /* MITKNAVIGATIONDATA_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/Testing/mitkNavigationDataToMessageFilterTest.cpp b/Modules/IGT/Testing/mitkNavigationDataToMessageFilterTest.cpp index 1d9af599ca..c97fdada8a 100644 --- a/Modules/IGT/Testing/mitkNavigationDataToMessageFilterTest.cpp +++ b/Modules/IGT/Testing/mitkNavigationDataToMessageFilterTest.cpp @@ -1,229 +1,229 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkNavigationDataToMessageFilter.h" #include "mitkNavigationData.h" #include "mitkTestingMacros.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include // Receiver class remembers Messages received. // Will tell about received Messages when asked. class MessageReceiverClass { public: MessageReceiverClass(unsigned int numberOfNavigationDatas) { m_ReceivedData.resize(numberOfNavigationDatas); for (unsigned int i = 0; i < numberOfNavigationDatas; ++i) m_ReceivedData[i] = mitk::NavigationData::New(); m_MessagesReceived = 0; } void OnPositionChanged(mitk::NavigationData::PositionType v, unsigned int index) { m_ReceivedData[index]->SetPosition(v); ++m_MessagesReceived; } void OnOrientationChanged(mitk::NavigationData::OrientationType v, unsigned int index) { m_ReceivedData[index]->SetOrientation(v); ++m_MessagesReceived; } void OnErrorChanged(mitk::NavigationData::CovarianceMatrixType v, unsigned int index) { m_ReceivedData[index]->SetCovErrorMatrix(v); ++m_MessagesReceived; } void OnTimeStampChanged(mitk::NavigationData::TimeStampType v, unsigned int index) { m_ReceivedData[index]->SetIGTTimeStamp(v); ++m_MessagesReceived; } void OnDataValidChanged(bool v, unsigned int index) { m_ReceivedData[index]->SetDataValid(v); ++m_MessagesReceived; } std::vector m_ReceivedData; int m_MessagesReceived; }; /**Documentation * test for the class "NavigationDataToMessageFilter". */ int mitkNavigationDataToMessageFilterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("NavigationDataToMessageFilter"); /* first tests with one input */ { // let's create an object of our class mitk::NavigationDataToMessageFilter::Pointer myFilter = mitk::NavigationDataToMessageFilter::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(myFilter.IsNotNull(),"Testing instantiation"); /* create helper objects: navigation data with position as origin, zero quaternion, zero error and data valid */ mitk::NavigationData::PositionType initialPos; mitk::FillVector3D(initialPos, 1.0, 2.0, 3.0); mitk::NavigationData::OrientationType initialOri(1.0, 2.0, 3.0, 4.0); mitk::NavigationData::Pointer nd1 = mitk::NavigationData::New(); nd1->SetPosition(initialPos); nd1->SetOrientation(initialOri); nd1->SetPositionAccuracy(11.111); nd1->SetIGTTimeStamp(64.46); nd1->SetDataValid(true); myFilter->SetInput(nd1); MITK_TEST_CONDITION(myFilter->GetInput() == nd1, "testing Set-/GetInput()"); mitk::NavigationData* output = myFilter->GetOutput(); MITK_TEST_CONDITION_REQUIRED(output != NULL, "Testing GetOutput()"); /* register message receiver */ MessageReceiverClass answers(1); myFilter->AddPositionChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnPositionChanged)); myFilter->AddOrientationChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnOrientationChanged)); myFilter->AddErrorChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnErrorChanged)); myFilter->AddTimeStampChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnTimeStampChanged)); myFilter->AddDataValidChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnDataValidChanged)); output->Update(); // execute filter MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetPosition(), nd1->GetPosition()), "Testing PositionChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetOrientation(), nd1->GetOrientation()), "Testing OrientationChanged message"); MITK_TEST_CONDITION( answers.m_ReceivedData[0]->GetCovErrorMatrix() == nd1->GetCovErrorMatrix(), "Testing ErrorChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetIGTTimeStamp(), nd1->GetIGTTimeStamp()), "Testing TimeStampChanged message"); MITK_TEST_CONDITION( answers.m_ReceivedData[0]->IsDataValid() == nd1->IsDataValid(), "Testing PositionChanged message"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 5, "Correct number of messages send?"); /* change one input parameter */ nd1->SetDataValid(false); output->Update(); // re-execute filter MITK_TEST_CONDITION( answers.m_ReceivedData[0]->IsDataValid() == nd1->IsDataValid(), "Testing PositionChanged message"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 6, "only necessary messages send?"); // only datavalid message re-send /* changing two input parameters */ mitk::FillVector3D(initialPos, 11.0, 21.0, 31.0); nd1->SetPosition(initialPos); // change only one parameter nd1->SetIGTTimeStamp(55.55); // change only one parameter output->Update(); // re-execute filter MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetPosition(), nd1->GetPosition()), "Testing PositionChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetIGTTimeStamp(), nd1->GetIGTTimeStamp()), "Testing TimeStampChanged message"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 8, "only necessary messages send?"); // only 2 new messages send /* try to add a second input */ //MITK_TEST_OUTPUT_NO_ENDL( << "Exception on adding second input? --> "); //mitk::NavigationData::Pointer nd2 = mitk::NavigationData::New(); //MITK_TEST_FOR_EXCEPTION(std::invalid_argument, myFilter->SetInput(1, nd2)); } /* now test with multiple inputs */ { MITK_TEST_OUTPUT( << "Now, perform tests with multiple inputs"); mitk::NavigationDataToMessageFilter::Pointer myFilter = mitk::NavigationDataToMessageFilter::New(); /* create helper objects: navigation data with position as origin, zero quaternion, zero error and data valid */ mitk::NavigationData::PositionType initialPos; mitk::FillVector3D(initialPos, 1.0, 1.0, 1.0); mitk::NavigationData::OrientationType initialOri(1.0, 1.0, 1.0, 1.0); mitk::NavigationData::Pointer nd0 = mitk::NavigationData::New(); nd0->SetPosition(initialPos); nd0->SetOrientation(initialOri); nd0->SetPositionAccuracy(11.111); nd0->SetIGTTimeStamp(64.46); nd0->SetDataValid(true); mitk::FillVector3D(initialPos, 2.0, 2.0, 2.0); mitk::NavigationData::OrientationType initialOri2(1.0, 1.0, 1.0, 1.0); mitk::NavigationData::Pointer nd1 = mitk::NavigationData::New(); nd1->SetPosition(initialPos); nd1->SetOrientation(initialOri2); nd1->SetPositionAccuracy(22.222); nd1->SetIGTTimeStamp(222.2); nd1->SetDataValid(true); myFilter->SetInput(0, nd0); myFilter->SetInput(1, nd1); MITK_TEST_CONDITION(myFilter->GetInput(0) == nd0, "testing Set-/GetInput(0)"); MITK_TEST_CONDITION(myFilter->GetInput(1) == nd1, "testing Set-/GetInput(1)"); mitk::NavigationData* output0 = myFilter->GetOutput(); mitk::NavigationData* output1 = myFilter->GetOutput(1); MITK_TEST_CONDITION_REQUIRED(output0 != NULL, "Testing GetOutput()"); MITK_TEST_CONDITION_REQUIRED(output1 != NULL, "Testing GetOutput(1)"); /* register message receiver */ MessageReceiverClass answers(2); myFilter->AddPositionChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnPositionChanged)); myFilter->AddOrientationChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnOrientationChanged)); myFilter->AddErrorChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnErrorChanged)); myFilter->AddTimeStampChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnTimeStampChanged)); myFilter->AddDataValidChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnDataValidChanged)); output0->Update(); // execute filter. This should send messages for both inputs MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetPosition(), nd0->GetPosition()), "Testing PositionChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetOrientation(), nd0->GetOrientation()), "Testing OrientationChanged message"); MITK_TEST_CONDITION( answers.m_ReceivedData[0]->GetCovErrorMatrix() == nd0->GetCovErrorMatrix(), "Testing ErrorChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[0]->GetIGTTimeStamp(), nd0->GetIGTTimeStamp()), "Testing TimeStampChanged message"); MITK_TEST_CONDITION( answers.m_ReceivedData[0]->IsDataValid() == nd0->IsDataValid(), "Testing PositionChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[1]->GetPosition(), nd1->GetPosition()), "Testing PositionChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[1]->GetOrientation(), nd1->GetOrientation()), "Testing OrientationChanged message"); MITK_TEST_CONDITION( answers.m_ReceivedData[1]->GetCovErrorMatrix() == nd1->GetCovErrorMatrix(), "Testing ErrorChanged message"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[1]->GetIGTTimeStamp(), nd1->GetIGTTimeStamp()), "Testing TimeStampChanged message"); MITK_TEST_CONDITION( answers.m_ReceivedData[1]->IsDataValid() == nd1->IsDataValid(), "Testing PositionChanged message"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 10, "Correct number of messages send?"); MITK_TEST_OUTPUT( << "answers.m_MessagesReceived = " << answers.m_MessagesReceived); /* change one input parameter */ nd0->SetDataValid(false); output0->Update(); // re-execute filter MITK_TEST_CONDITION( answers.m_ReceivedData[0]->IsDataValid() == nd0->IsDataValid(), "Testing PositionChanged message for input 0"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 11, "only necessary messages send?"); // only datavalid message for input 0 re-send /* remove one listener and check that message is not send */ myFilter->RemoveTimeStampChangedListener(mitk::MessageDelegate2(&answers, &MessageReceiverClass::OnTimeStampChanged)); mitk::NavigationData::TimeStampType oldValue = nd1->GetIGTTimeStamp(); nd1->SetIGTTimeStamp(999.9); myFilter->Update(); MITK_TEST_CONDITION( ! mitk::Equal(answers.m_ReceivedData[1]->GetIGTTimeStamp(), nd1->GetIGTTimeStamp()), "Testing if TimeStamp message is _not_ send after RemoveListener (!= new value)"); MITK_TEST_CONDITION( mitk::Equal(answers.m_ReceivedData[1]->GetIGTTimeStamp(), oldValue), "Testing if TimeStamp message is _not_ send after RemoveListener (== old value)"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 11, "no new messages send?"); // no new message send? /* other messages are still send? */ nd1->SetDataValid(false); myFilter->Update(); MITK_TEST_CONDITION( answers.m_ReceivedData[1]->IsDataValid() == nd1->IsDataValid(), "Other messages still send? ->Testing PositionChanged message for input 1 again"); MITK_TEST_CONDITION( answers.m_MessagesReceived == 12, "only necessary messages send?"); // only DataValid message for input 1 re-send /* check if other output still has its old value */ MITK_TEST_CONDITION( answers.m_ReceivedData[0]->IsDataValid() == nd0->IsDataValid(), "Testing PositionChanged message for input 0"); } // The end MITK_TEST_END(); } diff --git a/Modules/IGT/TrackingDevices/mitkClaronInterface.cpp b/Modules/IGT/TrackingDevices/mitkClaronInterface.cpp index 5712c815db..b5c33bbb8d 100644 --- a/Modules/IGT/TrackingDevices/mitkClaronInterface.cpp +++ b/Modules/IGT/TrackingDevices/mitkClaronInterface.cpp @@ -1,291 +1,291 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include -#include +#include mitk::ClaronInterface::ClaronInterface() { isTracking = false; sprintf(calibrationDir,"No calibration dir set yet"); sprintf(markerDir,"No marker dir set yet"); } mitk::ClaronInterface::~ClaronInterface() { } void mitk::ClaronInterface::Initialize(std::string calibrationDir, std::string toolFilesDir) { sprintf(this->calibrationDir, calibrationDir.c_str()); sprintf(this->markerDir,toolFilesDir.c_str()); this->IdentifiedMarkers = 0; this->PoseXf = 0; this->CurrCamera = 0; this->IdentifyingCamera = 0; } bool mitk::ClaronInterface::StartTracking() { isTracking = false; MTC( Cameras_AttachAvailableCameras(calibrationDir) ); //Connect to camera if (Cameras_Count() < 1) { printf("No camera found!\n"); return false; } try { //Step 1: initialize cameras MTC(Cameras_HistogramEqualizeImagesSet(true)); //set the histogram equalizing MTC( Cameras_ItemGet(0, &CurrCamera) ); //Obtain a handle to the first/only camera in the array MITK_INFO< mitk::ClaronInterface::GetAllActiveTools() { //Set returnvalue std::vector returnValue; //Here, MTC internally maintains the measurement results. //Those results can be accessed until the next call to Markers_ProcessFrame, when they //are updated to reflect the next frame's content. //First, we will obtain the collection of the markers that were identified. MTC( Markers_IdentifiedMarkersGet(NULL, IdentifiedMarkers) ); //Now we iterate on the identified markers and add them to the returnvalue for (int j=1; j<=Collection_Count(IdentifiedMarkers); j++) { // Obtain the marker's handle, and use it to obtain the pose in the current camera's space // using our Xform3D object, PoseXf. mtHandle Marker = Collection_Int(IdentifiedMarkers, j); returnValue.push_back(Marker); } return returnValue; } void mitk::ClaronInterface::GrabFrame() { MTC( Cameras_GrabFrame(NULL) ); //Grab a frame MTC( Markers_ProcessFrame(NULL) ); //Process the frame(s) } std::vector mitk::ClaronInterface::GetTipPosition(mitk::claronToolHandle c) { std::vector returnValue; double Position[3]; mtHandle t2m = Xform3D_New(); // tooltip to marker xform handle mtHandle t2c = Xform3D_New(); // tooltip to camera xform handle mtHandle m2c = Xform3D_New(); // marker to camera xform handle //Get m2c MTC( Marker_Marker2CameraXfGet (c, CurrCamera, m2c, &IdentifyingCamera) ); //Get t2m MTC( Marker_Tooltip2MarkerXfGet (c, t2m )); //Transform both to t2c MTC(Xform3D_Concatenate(t2m,m2c,t2c)); //Get position MTC( Xform3D_ShiftGet(t2c, Position) ); // Here we have to negate the X- and Y-coordinates because of a bug of the // MTC-library. returnValue.push_back(-Position[0]); returnValue.push_back(-Position[1]); returnValue.push_back(Position[2]); return returnValue; } std::vector mitk::ClaronInterface::GetPosition(claronToolHandle c) { std::vector returnValue; double Position[3]; MTC( Marker_Marker2CameraXfGet (c, CurrCamera, PoseXf, &IdentifyingCamera) ); MTC( Xform3D_ShiftGet(PoseXf, Position) ); // Here we have to negate the X- and Y-coordinates because of a bug of the // MTC-library. returnValue.push_back(-Position[0]); returnValue.push_back(-Position[1]); returnValue.push_back(Position[2]); return returnValue; } std::vector mitk::ClaronInterface::GetTipQuaternions(claronToolHandle c) { std::vector returnValue; mtHandle t2m = Xform3D_New(); // tooltip to marker xform handle mtHandle t2c = Xform3D_New(); // tooltip to camera xform handle mtHandle m2c = Xform3D_New(); // marker to camera xform handle //Get m2c MTC( Marker_Marker2CameraXfGet (c, CurrCamera, m2c, &IdentifyingCamera) ); //Get t2m MTC( Marker_Tooltip2MarkerXfGet (c, t2m )); //Transform both to t2c MTC(Xform3D_Concatenate(t2m,m2c,t2c)); //get the Claron-Quaternion double Quarternions[4]; MTC( Xform3D_RotQuaternionsGet(t2c, Quarternions) ); mitk::Quaternion claronQuaternion; //note: claron quarternion has different order than the mitk quarternion claronQuaternion[3] = Quarternions[0]; claronQuaternion[0] = Quarternions[1]; claronQuaternion[1] = Quarternions[2]; claronQuaternion[2] = Quarternions[3]; // Here we have to make a -90�-turn around the Y-axis because of a bug of the // MTC-library. mitk::Quaternion minusNinetyDegreeY; minusNinetyDegreeY[3] = sqrt(2.0)/2.0; minusNinetyDegreeY[0] = 0; minusNinetyDegreeY[1] = -1.0/(sqrt(2.0)); minusNinetyDegreeY[2] = 0; //calculate the result... mitk::Quaternion erg = (minusNinetyDegreeY*claronQuaternion); returnValue.push_back(erg[3]); returnValue.push_back(erg[0]); returnValue.push_back(erg[1]); returnValue.push_back(erg[2]); return returnValue; } std::vector mitk::ClaronInterface::GetQuaternions(claronToolHandle c) { std::vector returnValue; double Quarternions[4]; MTC( Marker_Marker2CameraXfGet (c, CurrCamera, PoseXf, &IdentifyingCamera) ); MTC( Xform3D_RotQuaternionsGet(PoseXf, Quarternions) ); //here we have to compensate a bug in the MTC-lib. (difficult to understand) mitk::Quaternion claronQuaternion; //note: claron quarternion has different order than the mitk quarternion claronQuaternion[3] = Quarternions[0]; claronQuaternion[0] = Quarternions[1]; claronQuaternion[1] = Quarternions[2]; claronQuaternion[2] = Quarternions[3]; // Here we have to make a -90�-turn around the Y-axis because of a bug of the // MTC-library. mitk::Quaternion minusNinetyDegreeY; minusNinetyDegreeY[3] = sqrt(2.0)/2.0; minusNinetyDegreeY[0] = 0; minusNinetyDegreeY[1] = -1.0/(sqrt(2.0)); minusNinetyDegreeY[2] = 0; //calculate the result... mitk::Quaternion erg = (minusNinetyDegreeY*claronQuaternion); returnValue.push_back(erg[3]); returnValue.push_back(erg[0]); returnValue.push_back(erg[1]); returnValue.push_back(erg[2]); return returnValue; } const char* mitk::ClaronInterface::GetName(claronToolHandle c) { char MarkerName[MT_MAX_STRING_LENGTH]; MTC( Marker_NameGet(c, MarkerName, MT_MAX_STRING_LENGTH, 0) ); std::string* returnValue = new std::string(MarkerName); return returnValue->c_str(); } bool mitk::ClaronInterface::IsTracking() { return this->isTracking; } bool mitk::ClaronInterface::IsMicronTrackerInstalled() { return true; } diff --git a/Modules/IGT/TrackingDevices/mitkInternalTrackingTool.h b/Modules/IGT/TrackingDevices/mitkInternalTrackingTool.h index b420ae0601..f583716123 100644 --- a/Modules/IGT/TrackingDevices/mitkInternalTrackingTool.h +++ b/Modules/IGT/TrackingDevices/mitkInternalTrackingTool.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 MITKINTERNALTRACKINGTOOL_H_HEADER_INCLUDED_ #define MITKINTERNALTRACKINGTOOL_H_HEADER_INCLUDED_ #include #include -#include +#include #include namespace mitk { /**Documentation * \brief implements TrackingTool interface * * This class is a complete TrackingTool implementation. It can either be used directly by * TrackingDevices, or be subclassed for more specific implementations. * mitk::MicroBirdTrackingDevice uses this class to manage its tools. Other tracking devices * uses specialized versions of this class (e.g. mitk::NDITrackingTool) * * \ingroup IGT */ class MitkIGT_EXPORT InternalTrackingTool : public TrackingTool { friend class MicroBirdTrackingDevice; // Add all TrackingDevice subclasses that use InternalTrackingDevice directly public: mitkClassMacro(InternalTrackingTool, TrackingTool); virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; virtual void GetPosition(Point3D& position) const; ///< returns the current position of the tool as an array of three floats (in the tracking device coordinate system) virtual void GetOrientation(Quaternion& orientation) const; ///< returns the current orientation of the tool as a quaternion (in the tracking device coordinate system) virtual bool Enable(); ///< enablea the tool, so that it will be tracked. Returns true if enabling was successfull virtual bool Disable(); ///< disables the tool, so that it will not be tracked anymore. Returns true if disabling was successfull virtual bool IsEnabled() const; ///< returns whether the tool is enabled or disabled virtual bool IsDataValid() const; ///< returns true if the current position data is valid (no error during tracking, tracking error below threshold, ...) virtual float GetTrackingError() const; ///< return one value that corresponds to the overall tracking error. The dimension of this value is specific to each tracking device virtual bool IsTooltipSet() const; ///< returns true if a tooltip is set, false if not virtual void SetToolName(const std::string _arg); ///< Sets the name of the tool virtual void SetToolName(const char* _arg); ///< Sets the name of the tool virtual void SetPosition(Point3D position); ///< sets the position virtual void SetOrientation(Quaternion orientation); ///< sets the orientation as a quaternion virtual void SetTrackingError(float error); ///< sets the tracking error virtual void SetDataValid(bool _arg); ///< sets if the tracking data (position & Orientation) is valid virtual void SetErrorMessage(const char* _arg); ///< sets the error message virtual void SetToolTip(Point3D toolTipPosition, Quaternion orientation = Quaternion(0,0,0,1), ScalarType eps=0.0); ///< defines a tool tip for this tool in tool coordinates. GetPosition() and GetOrientation() return the data of the tool tip if it is defined. By default no tooltip is defined. protected: itkFactorylessNewMacro(Self) itkCloneMacro(Self) InternalTrackingTool(); virtual ~InternalTrackingTool(); Point3D m_Position; ///< holds the position of the tool Quaternion m_Orientation; ///< holds the orientation of the tool float m_TrackingError; ///< holds the tracking error of the tool bool m_Enabled; ///< if true, tool is enabled and should receive tracking updates from the tracking device bool m_DataValid; ///< if true, data in m_Position and m_Orientation is valid, e.g. true tracking data Point3D m_ToolTip; Quaternion m_ToolTipRotation; bool m_ToolTipSet; }; } // namespace mitk #endif /* MITKINTERNALTRACKINGTOOL_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/TrackingDevices/mitkTrackingTool.h b/Modules/IGT/TrackingDevices/mitkTrackingTool.h index af13823d90..2792080c80 100644 --- a/Modules/IGT/TrackingDevices/mitkTrackingTool.h +++ b/Modules/IGT/TrackingDevices/mitkTrackingTool.h @@ -1,65 +1,65 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKTRACKINGTOOL_H_HEADER_INCLUDED_ #define MITKTRACKINGTOOL_H_HEADER_INCLUDED_ #include #include #include -#include +#include #include namespace mitk { /**Documentation * \brief Interface for all Tracking Tools * * Abstract class that defines the methods that are common for all tracking tools. * * \ingroup IGT */ class MitkIGT_EXPORT TrackingTool : public itk::Object { public: mitkClassMacro(TrackingTool, itk::Object); virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; virtual void SetToolTip(Point3D toolTipPosition, Quaternion orientation, ScalarType eps=0.0) = 0; ///< defines a tool tip for this tool in tool coordinates. GetPosition() and GetOrientation() return the data of the tool tip if it is defined. By default no tooltip is defined. virtual void GetPosition(Point3D& position) const = 0; ///< returns the current position of the tool as an array of three floats (in the tracking device coordinate system) virtual void GetOrientation(Quaternion& orientation) const = 0; ///< returns the current orientation of the tool as a quaternion in a mitk::Point4D (in the tracking device coordinate system) virtual bool Enable() = 0; ///< enables the tool, so that it will be tracked virtual bool Disable() = 0; ///< disables the tool, so that it will not be tracked anymore virtual bool IsEnabled() const = 0; ///< returns whether the tool is enabled or disabled virtual bool IsDataValid() const = 0; ///< returns true if the current position data is valid (no error during tracking, tracking error below threshold, ...) virtual float GetTrackingError() const = 0; ///< returns one value that corresponds to the overall tracking error. virtual const char* GetToolName() const; ///< every tool has a name that can be used to identify it. virtual const char* GetErrorMessage() const; ///< if the data is not valid, ErrorMessage should contain a string explaining why it is invalid (the Set-method should be implemented in subclasses, it should not be accessible by the user) itkSetMacro(IGTTimeStamp, double); ///< Sets the IGT timestamp of the tracking tool object (time in milliseconds) itkGetConstMacro(IGTTimeStamp, double); ///< Gets the IGT timestamp of the tracking tool object (time in milliseconds). Returns 0 if the timestamp was not set. protected: TrackingTool(); virtual ~TrackingTool(); std::string m_ToolName; ///< every tool has a name that can be used to identify it. std::string m_ErrorMessage; ///< if a tool is invalid, this member should contain a human readable explanation of why it is invalid double m_IGTTimeStamp; ///< contains the time at which the tracking data was recorded itk::FastMutexLock::Pointer m_MyMutex; ///< mutex to control concurrent access to the tool }; } // namespace mitk #endif /* MITKTRACKINGTOOL_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/TrackingDevices/mitkVirtualTrackingTool.h b/Modules/IGT/TrackingDevices/mitkVirtualTrackingTool.h index 7f30f1fb7a..01ff1322f4 100644 --- a/Modules/IGT/TrackingDevices/mitkVirtualTrackingTool.h +++ b/Modules/IGT/TrackingDevices/mitkVirtualTrackingTool.h @@ -1,67 +1,67 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKVirtualTrackingTool_H_HEADER_INCLUDED_ #define MITKVirtualTrackingTool_H_HEADER_INCLUDED_ #include #include -#include +#include #include #include namespace mitk { /**Documentation * \brief implements TrackingTool interface * * This class is a complete TrackingTool implementation. It can either be used directly by * TrackingDevices, or be subclassed for more specific implementations. * mitk::MicroBirdTrackingDevice uses this class to manage its tools. Other tracking devices * uses specialized versions of this class (e.g. mitk::NDITrackingTool) * * \ingroup IGT */ class MitkIGT_EXPORT VirtualTrackingTool : public InternalTrackingTool { public: mitkClassMacro(VirtualTrackingTool, InternalTrackingTool); friend class VirtualTrackingDevice; itkFactorylessNewMacro(Self) typedef itk::NonUniformBSpline<3> SplineType; ///< spline type used for tool path interpolation itkGetMacro(SplineLength, mitk::ScalarType); itkSetMacro(SplineLength, mitk::ScalarType); itkGetMacro(Velocity, mitk::ScalarType); itkSetMacro(Velocity, mitk::ScalarType); itkGetObjectMacro(Spline, SplineType); protected: itkCloneMacro(Self) VirtualTrackingTool(); virtual ~VirtualTrackingTool(); SplineType::Pointer m_Spline; mitk::ScalarType m_SplineLength; mitk::ScalarType m_Velocity; }; } // namespace mitk #endif /* MITKVirtualTrackingTool_H_HEADER_INCLUDED_ */ diff --git a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.cpp b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.cpp index 7f885f3778..ee5de8f6a3 100644 --- a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.cpp +++ b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.cpp @@ -1,61 +1,61 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 mitk::SpaceNavigatorAddOn* mitk::SpaceNavigatorAddOn::GetInstance() { // only needed for initializiation SpaceNavigatorDriver* spaceNavigatorDriver = SpaceNavigatorDriver::GetInstance(); static SpaceNavigatorAddOn instance; return &instance; } void mitk::SpaceNavigatorAddOn::DeviceChange (long device, long keys, long programmableKeys) { } void mitk::SpaceNavigatorAddOn::KeyDown (int keyCode) { mitk::Event* e = new mitk::Event(NULL, mitk::Type_SpaceNavigatorKeyDown, mitk::BS_LeftButton, keyCode, mitk::Key_none); mitk::StateEvent* se = new mitk::StateEvent(mitk::EIDSPACENAVIGATORKEYDOWN, e); this->ForwardEvent(se); } void mitk::SpaceNavigatorAddOn::KeyUp (int keyCode) { } void mitk::SpaceNavigatorAddOn::SensorInput( mitk::Vector3D translation, mitk::Vector3D rotation, mitk::ScalarType angle) { mitk::SpaceNavigatorEvent* e = new mitk::SpaceNavigatorEvent(mitk::BS_NoButton, translation, rotation, angle); mitk::StateEvent* se = new mitk::StateEvent(mitk::EIDSPACENAVIGATORINPUT, e); this->ForwardEvent(se); } diff --git a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.h b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.h index eafd7a32be..0603a6bca8 100644 --- a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.h +++ b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorAddOn.h @@ -1,78 +1,78 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKSPACENAVIGATORADDON_H_HEADER_INCLUDED #define MITKSPACENAVIGATORADDON_H_HEADER_INCLUDED -#include +#include #include #include #include namespace mitk { /** * Documentation in the interface. * * @brief EventMapper addon for a 3DConnexion Space Navigator * @ingroup Interaction */ class mitkSpaceNavigator_EXPORT SpaceNavigatorAddOn : public EventMapperAddOn { public: // Singleton static SpaceNavigatorAddOn* GetInstance(); /** * @noimplement not needed */ void DeviceChange (long device, long keys, long programmableKeys); /** * If a button is pressed down an event is fired. * * @param keyCode the id to the key, that is pressed */ void KeyDown (int keyCode); /** * @noimplement not needed */ void KeyUp (int keyCode); /** * Reacts on any movement of the mouse and fires events accordingly. * * @param translation * the translation of the mouse as an 3D vector * @param rotation * the rotation of the mouse as an 3D vector * @param angle * the angle from the mouse as an scalar unit */ void SensorInput(mitk::Vector3D translation, mitk::Vector3D rotation, mitk::ScalarType angle); protected: private: }; // end class SpaceNavigatorAddOn } // end namespace mitk #endif // MITKSPACENAVIGATORADDON_H_HEADER_INCLUDED diff --git a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorDriver.h b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorDriver.h index a2111bffc7..a5c832b944 100644 --- a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorDriver.h +++ b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorDriver.h @@ -1,96 +1,96 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 #ifndef SpaceNavigatorDriver__h__ #define SpaceNavigatorDriver__h__ #ifdef SPACE_NAVIGATOR_MAIN_SOURCE #define _ATL_ATTRIBUTES 1 #define _WIN32_DCOM #include #include #include #include #include #include // if the error C2813 occurs // just remove /MP suffix: the problem is that // the #import statement is not yet compatible [05-11-2010] // check the microsoft homepage for further information #import "progid:TDxInput.Device" embedded_idl no_namespace using namespace ATL; -#include +#include #include using std::cout; using std::endl; [module(name="mitkInputDevices")]; [ event_receiver(com) ] class SpaceNavigatorDriver { public: static SpaceNavigatorDriver* GetInstance(); private: SpaceNavigatorDriver(); ~SpaceNavigatorDriver(); //methods for workaround of .net 2003 compiler Artikel-ID : 829749 //http://support.microsoft.com/kb/829749/de inline HRESULT HookEvent1(CComPtr device); inline HRESULT HookEvent2(); inline HRESULT HookEvent3(CComPtr device); inline HRESULT HookEvent4(); inline HRESULT HookEvent5(); #if 1 CComPtr m_pISensor; CComPtr m_pIKeyboard; #else ISensorPtr m_pISensor; IKeyboardPtr m_pIKeyboard; #endif public: // COM Event handlers HRESULT InitializeCOM(); HRESULT OnDeviceChange (long reserved); HRESULT OnKeyDown (int keyCode); HRESULT OnKeyUp (int keyCode); HRESULT OnSensorInput(void); HRESULT UninitializeCOM(); }; #else // SPACE_NAVIGATOR_MAIN_SOURCE class SpaceNavigatorDriver { public: static SpaceNavigatorDriver* GetInstance(); }; #endif #endif // SpaceNavigatorDriver__h__ diff --git a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.cpp b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.cpp index 82bec99cb0..a63748aa6e 100644 --- a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.cpp +++ b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.cpp @@ -1,25 +1,25 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkSpaceNavigatorEvent.h" #include "mitkInteractionConst.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" mitk::SpaceNavigatorEvent::SpaceNavigatorEvent(int buttonState, const Vector3D& translation, const Vector3D& rotation, const ScalarType& angle) : Event(NULL, mitk::Type_SpaceNavigatorInput, BS_NoButton, buttonState, Key_none), m_Translation(translation), m_Rotation(rotation), m_Angle(angle) { } diff --git a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.h b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.h index 170a73e66e..d32f68e025 100644 --- a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.h +++ b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorEvent.h @@ -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. ===================================================================*/ #ifndef SPACENAVIGATOREVENT_H_ #define SPACENAVIGATOREVENT_H_ #include #include -#include +#include #include namespace mitk { /** * Documentation * @brief Event on 3D Mouse input * * Seven coordinates exposed by the 3D Mouse: * 3-dimensional translation vector * 3-dimensional rotation achsis (length allways 1.0) * scalar rotation angle * * @ingroup Interaction */ class mitkSpaceNavigator_EXPORT SpaceNavigatorEvent : public Event { public: /** * @brief Constructor with all necessary arguments (for further information about the parameter:
* mitk::SpaceNavigatorAddOn. * * @param buttonState information from the Event * */ SpaceNavigatorEvent(int buttonState, const Vector3D& translation, const Vector3D& rotation, const ScalarType& angle); //Getter and Setter const Vector3D& GetTranslation() const { return m_Translation; } void SetTranslation(const Vector3D& translation) { m_Translation = translation; } const Vector3D& GetRotation() const { return m_Rotation; } void SetRotation(const Vector3D& rotation) { m_Rotation = rotation; } const ScalarType& GetAngle() const { return m_Angle; } void SetAngle(const ScalarType& angle) { m_Angle = angle; } protected: Vector3D m_Translation; Vector3D m_Rotation; ScalarType m_Angle; }; // end class SpaceNavigatorEvent } // end namespace mitk #endif /* SPACENAVIGATOREVENT_H_ */ diff --git a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorVtkCameraController.cpp b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorVtkCameraController.cpp index 3de113e61b..d44eb112a0 100644 --- a/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorVtkCameraController.cpp +++ b/Modules/InputDevices/SpaceNavigator/mitkSpaceNavigatorVtkCameraController.cpp @@ -1,238 +1,238 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkSpaceNavigatorVtkCameraController.h" #include "mitkVtkPropRenderer.h" #include "vtkCamera.h" #include "vtkRenderer.h" #include "vtkTransform.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "mitkInteractionConst.h" #include "mitkStateEvent.h" #include "mitkGlobalInteraction.h" #include "vtkMath.h" #include const double TRANSLATIONSENSITIVITY = 2.0; const double ROTATIONSENSIVITY = 3.5; const double ANGLESENSITIVITY = 3.5; mitk::SpaceNavigatorVtkCameraController::SpaceNavigatorVtkCameraController() : CameraController("SpaceNavigatorInteraction") { //connect method this->OnSpaceNavigatorEvent to StateMachineEventMechanism CONNECT_ACTION(AcONSPACENAVIGATORMOUSEINPUT, OnSpaceNavigatorEvent); CONNECT_ACTION(AcONPACENAVIGATORKEYDOWN, OnSpaceNavigatorKeyDown); m_ClippingRangeIsSet = false; } mitk::SpaceNavigatorVtkCameraController::~SpaceNavigatorVtkCameraController() { } bool mitk::SpaceNavigatorVtkCameraController::OnSpaceNavigatorEvent(mitk::Action* a, const mitk::StateEvent* e) { //only if 3D rendering const mitk::BaseRenderer* br = mitk::GlobalInteraction::GetInstance()->GetFocus(); this->SetRenderer( br ); mitk::BaseRenderer::MapperSlotId id = ((mitk::BaseRenderer*)(br))->GetMapperID(); if (id != mitk::BaseRenderer::Standard3D) return true; //only if focused by the FocusManager if (this->GetRenderer() != mitk::GlobalInteraction::GetInstance()->GetFocus()) return true; //pre-checking for safety vtkRenderer* vtkRenderer = ((mitk::VtkPropRenderer*)this->GetRenderer())->GetVtkRenderer(); if (vtkRenderer == NULL) return false; vtkCamera* vtkCam = (vtkCamera*)vtkRenderer->GetActiveCamera(); if(!m_ClippingRangeIsSet) vtkCam->SetClippingRange(0.1, 1000000); const mitk::SpaceNavigatorEvent* snevent = dynamic_cast(e->GetEvent()); if (snevent == NULL) { MITK_ERROR <<"Wrong event for SpaceNavigatorVtkCameraController!"; return false; } //get the information from the mouse mitk::Vector3D translation = snevent->GetTranslation(); mitk::Vector3D rotation = snevent->GetRotation(); mitk::ScalarType angle = snevent->GetAngle(); //output for debug //std::cout<<"translation: "<GetDataStorage(); mitk::BoundingBox::Pointer bb = ds->ComputeBoundingBox(); mitk::BoundingBox::AccumulateType length = bb->GetDiagonalLength2(); if (length > 0.00001)//if length not zero sceneSensivity *= 100.0 / (sqrt(length)) ; //sensivity to adapt to mitk speed translation *= sceneSensivity * TRANSLATIONSENSITIVITY; rotation *= sceneSensivity * ROTATIONSENSIVITY; angle *= sceneSensivity * ANGLESENSITIVITY; //compute the global space coordinates from the relative mouse coordinate //first we need the position of the camera mitk::Vector3D camPosition; double camPositionTemp[3]; vtkCam->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]; vtkCam->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]; vtkCam->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(); //now we have the current orientation so we can adapt it according to the current information, which we got from the TDMouse //new position of the camera: //left/right = camPosition + crossVector * translation[0]; mitk::Vector3D vectorX = crossVector * -translation[0]; //changes the magnitude, not the direction double nextCamPosition[3]; nextCamPosition[0] = camPosition[0] + vectorX[0]; nextCamPosition[1] = camPosition[1] + vectorX[1]; nextCamPosition[2] = camPosition[2] + vectorX[2]; //now the up/down movement mitk::Vector3D vectorY = upCamVector * translation[1]; //changes the magnitude, not the direction nextCamPosition[0] += vectorY[0]; nextCamPosition[1] += vectorY[1]; nextCamPosition[2] += vectorY[2]; //forward/backward movement mitk::Vector3D vectorZ = focalVector * -translation[2]; //changes the magnitude, not the direction nextCamPosition[0] += vectorZ[0]; nextCamPosition[1] += vectorZ[1]; nextCamPosition[2] += vectorZ[2]; //set the next position double nextPosition[3]; nextPosition[0] = nextCamPosition[0]; nextPosition[1] = nextCamPosition[1]; nextPosition[2] = nextCamPosition[2]; vtkCam->SetPosition(nextPosition); //adapt the focal point the same way double currentFocalPoint[3], nextFocalPoint[3]; vtkCam->GetFocalPoint(currentFocalPoint); nextFocalPoint[0] = currentFocalPoint[0] + vectorX[0] + vectorY[0] + vectorZ[0]; nextFocalPoint[1] = currentFocalPoint[1] + vectorX[1] + vectorY[1] + vectorZ[1]; ; nextFocalPoint[2] = currentFocalPoint[2] + vectorX[2] + vectorY[2] + vectorZ[2]; vtkCam->SetFocalPoint(nextFocalPoint); //now adapt the rotation of the mouse and adapt the camera according to it //Pitch: //Rotate the focal point about the cross product of the view up vector and the direction of //projection, centered at the camera's position. vtkCam->Pitch(rotation[0]*angle); //Yaw: //Rotate the focal point about the view up vector centered at the camera's position. //Note that the view up vector is not necessarily perpendicular to the direction of projection. vtkCam->Yaw(rotation[1]*angle); //Roll: //Rotate the camera about the direction of projection. vtkCam->Roll(-rotation[2]*angle * 1.5);//*1.5 to speed up the rotation[2] a little bit //Recompute the ViewUp vector to force it to be perpendicular to camera->focalpoint vector. //Unless you are going to use Yaw or Azimuth on the camera, there is no need to do this. vtkCam->OrthogonalizeViewUp(); //no zooming, only translating to the front or back // dolly: Move the position of the camera along the direction // of projection. Moving towards the focal point (e.g., greater // than 1) is a dolly-in, moving away from the focal point // (e.g., less than 1) is a dolly-out. //double distance = ((tdevent->GetTranslation())[1] / 10.0);//make it less sensitive in comparison to translation and rotatipn //vtkCam->Dolly(1.0 + distance ); //Reset the camera clipping range based on the bounds of the visible actors. //This ensures that no props are cut off vtkRenderer->ResetCameraClippingRange(); mitk::RenderingManager::GetInstance()->ForceImmediateUpdate(mitk::GlobalInteraction::GetInstance()->GetFocus()->GetRenderWindow()); return true; } bool mitk::SpaceNavigatorVtkCameraController::OnSpaceNavigatorKeyDown(mitk::Action* a, const mitk::StateEvent* e) { //reset the camera, so that the objects shown in the scene can be seen. const mitk::VtkPropRenderer* glRenderer = dynamic_cast(m_Renderer); if (glRenderer) { vtkRenderer* vtkRenderer = glRenderer->GetVtkRenderer(); mitk::DataStorage* ds = m_Renderer->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; } diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteAddOn.h b/Modules/InputDevices/WiiMote/mitkWiiMoteAddOn.h index 7bb877e094..f2b3f4dff0 100644 --- a/Modules/InputDevices/WiiMote/mitkWiiMoteAddOn.h +++ b/Modules/InputDevices/WiiMote/mitkWiiMoteAddOn.h @@ -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. ===================================================================*/ #ifndef MITK_WIIMOTEADDON_H_ #define MITK_WIIMOTEADDON_H_ // export macro #include // mitk -#include "mitkTypes.h" // used for Point2D +#include "mitkNumericTypes.h" // used for Point2D #include namespace mitk { class WiiMoteThread; /** * Documentation in the interface. Some code snippets used here are from the demo
* application from gl.tter and therefore are under the same license as wiimote.cpp . * * @brief EventMapper addon for a Wiimote * @ingroup Interaction */ class mitkWiiMote_EXPORT WiiMoteAddOn : public EventMapperAddOn { public: WiiMoteAddOn(); ~WiiMoteAddOn(); // Singleton static WiiMoteAddOn* GetInstance(); /** * Starts all available Wiimotes. */ void ActivateWiiMotes(); /** * Disconnects all Wiimotes and stops the thread. */ void DeactivateWiiMotes(); /** * Creates suitable events, when the Wiimote sends IR data
* for movement and forwards it for further processing. */ void WiiMoteInput(const itk::EventObject& e); /** * Creates suitable events, when the Wiimote sends button events
* to trigger an action and forwards it for further processing. */ void WiiMoteButtonPressed(const itk::EventObject& e); /** * Creates suitable events, when the Wiimote sends button events
* to trigger an action and forwards it for further processing. */ void WiiMoteButtonReleased(const itk::EventObject& e); /** * Creates suitable events, when the Wiimote sends IR data
* to configure the sensitivity and forwards it for further processing. */ void WiiMoteCalibrationInput(const itk::EventObject& e); /** * @see mitk::WiiMoteThread::SetWiiMoteSurfaceIModus(bool activated) */ void SetWiiMoteSurfaceIModus(bool activated); /** * Creates suitable events, regardless what type of data the
* Wiimote sends for a surface interaction. Then forwards the
* transformed data for further processing. * */ void WiiMoteSurfaceInteractionInput(const itk::EventObject& e); protected: private: WiiMoteThread* m_WiiMoteThread; }; // end class WiiMoteAddOn } // end namespace mitk #endif // MITK_WIIMOTEADDON_H_ diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteButtonEvent.h b/Modules/InputDevices/WiiMote/mitkWiiMoteButtonEvent.h index c7a2b6b27b..6cb2c16fd5 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 "mitkTypes.h" +#include "mitkNumericTypes.h" #include "mitkInteractionConst.h" #include 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 diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.h b/Modules/InputDevices/WiiMote/mitkWiiMoteCalibrationEvent.h index 4bceea8971..4cf2b824cd 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 #include "mitkEvent.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.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 diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteIREvent.h b/Modules/InputDevices/WiiMote/mitkWiiMoteIREvent.h index cc047fa031..b375a8a6db 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 "mitkTypes.h" +#include "mitkNumericTypes.h" #include "mitkInteractionConst.h" #include 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 diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.cpp b/Modules/InputDevices/WiiMote/mitkWiiMoteInteractor.cpp index b71569eec5..c51fe833ec 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 #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->GetUpdatedTimeGeometry()->GetGeometryForTimeStep( 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; } diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.h b/Modules/InputDevices/WiiMote/mitkWiiMoteMultiIREvent.h index a1c3318665..76210072a4 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 #include "mitkEvent.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.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 diff --git a/Modules/InputDevices/WiiMote/mitkWiiMoteThread.h b/Modules/InputDevices/WiiMote/mitkWiiMoteThread.h index 78f6841929..38ab192630 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 "mitkTypes.h" +#include "mitkNumericTypes.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 diff --git a/Modules/IpPicSupport/mitkPicHelper.h b/Modules/IpPicSupport/mitkPicHelper.h index 78fbe873ac..4718aac162 100644 --- a/Modules/IpPicSupport/mitkPicHelper.h +++ b/Modules/IpPicSupport/mitkPicHelper.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 MITKPICHELPER_H_HEADER_INCLUDED_C1F4DAB4 #define MITKPICHELPER_H_HEADER_INCLUDED_C1F4DAB4 #include -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include namespace mitk { class SlicedGeometry3D; //##Documentation //## @brief Internal class for managing references on sub-images //## @ingroup Data class MitkIpPicSupport_EXPORT PicHelper { public: static const char *GetNameOfClass() { return "PicHelper"; } static bool GetSpacing(const mitkIpPicDescriptor* pic, Vector3D & spacing); static bool SetSpacing(const mitkIpPicDescriptor* pic, SlicedGeometry3D* slicedgeometry); static bool GetTimeSpacing(const mitkIpPicDescriptor* pic, float& timeSpacing); static void InitializeEvenlySpaced(const mitkIpPicDescriptor* pic, unsigned int slices, SlicedGeometry3D* slicedgeometry); static bool SetGeometry2D(const mitkIpPicDescriptor* pic, int s, SlicedGeometry3D* slicedgeometry); }; } // namespace mitk #endif /* MITKPICHELPER_H_HEADER_INCLUDED_C1F4DAB4 */ diff --git a/Modules/OpenCVVideoSupport/mitkUndistortCameraImage.h b/Modules/OpenCVVideoSupport/mitkUndistortCameraImage.h index 13d40a9c1c..ae51d11d03 100644 --- a/Modules/OpenCVVideoSupport/mitkUndistortCameraImage.h +++ b/Modules/OpenCVVideoSupport/mitkUndistortCameraImage.h @@ -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. ===================================================================*/ #ifndef __mitkUndistortCameraImage_h #define __mitkUndistortCameraImage_h #include "mitkConfig.h" #include "mitkCommon.h" #include #include "itkObject.h" #include "itkObjectFactory.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "cv.h" /*! \brief UndistortCameraImage This class is used to undistort camera images. Before any undistortion the class has to be initialized using the functions: SetFocalLength(),SetPrinzipalPoint() and SetCameraDistortion(). After this you can either use UndistortPixel() to undistort a single pixel's coordinates or UndistortImage() to undistort an OpenCV image. A faster version of UndistortImage() is UndistortImageFast(), however, it has to be initialized once with SetUndistortImageFastInfo() instead of the Set... methods before use. \sa QmitkFunctionality \ingroup Functionalities */ namespace mitk { class MITK_OPENCVVIDEOSUPPORT_EXPORT UndistortCameraImage : public itk::Object { public: mitkClassMacro(UndistortCameraImage,itk::Object); itkFactorylessNewMacro(Self) itkCloneMacro(Self) /// Initialization /// /* * Set the camera's intrinsic focal length */ void SetFocalLength(float fc_x, float fc_y) { m_fcX = fc_x; m_fcY = fc_y; } /* * Set the camera's intrinsic principal point */ void SetPrincipalPoint(float cc_x, float cc_y) { m_ccX = cc_x; m_ccY = cc_y; } /* * Set the camera's intrinsic distortion parameters */ void SetCameraDistortion(float kc1, float kc2, float kc3, float kc4) { m_distortionMatrixData[0] = kc1; m_distortionMatrixData[1] = kc2; m_distortionMatrixData[2] = kc3; m_distortionMatrixData[3] = kc4; } /* * Pre-Calculates matrices for the later use of UndistortImageFast() */ void InitRemapUndistortion(int sizeX, int sizeY); /// USAGE /// /* * Undistort a single pixel, returns undistorted pixel */ mitk::Point2D UndistortPixel(mitk::Point2D src); /* * Complete undistortion of an OpenCV image, including all calculations */ void UndistortImage(IplImage* src, IplImage* dst); /* * Complete undistortion of an OpenCV image, using pre-calculated matrices from SetUndistortImageFastInfo() * The use of only a source parameter will cause the source to be overwritten. * NOTE: Using the Fast undistortion methods does not require a initialization via the Set... methods. */ void UndistortImageFast( IplImage * src, IplImage* dst = NULL ); void SetUndistortImageFastInfo(float in_dF1, float in_dF2, float in_dPrincipalX, float in_dPrincipalY, float in_Dist[4], float ImageSizeX, float ImageSizeY); UndistortCameraImage(); virtual ~UndistortCameraImage(); protected: // principal point and focal length parameters float m_ccX, m_ccY, m_fcX, m_fcY; // undistortion parameters float m_distortionMatrixData[4]; // intrinsic camera parameters float m_intrinsicMatrixData[9]; // precalculated matrices for fast image undistortion with UndistortImageFast() CvMat * m_mapX, * m_mapY; // intrinsic and undistortion camera matrices CvMat m_intrinsicMatrix, m_distortionMatrix; // temp image IplImage * m_tempImage; CvMat *m_DistortionCoeffs; CvMat *m_CameraMatrix; }; } #endif diff --git a/Modules/PlanarFigure/Interactions/mitkPlanarFigureInteractor.h b/Modules/PlanarFigure/Interactions/mitkPlanarFigureInteractor.h index 4f606f48f3..76b994b659 100644 --- a/Modules/PlanarFigure/Interactions/mitkPlanarFigureInteractor.h +++ b/Modules/PlanarFigure/Interactions/mitkPlanarFigureInteractor.h @@ -1,205 +1,205 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKPLANARFIGUREINTERACTOR_H_HEADER_INCLUDED #define MITKPLANARFIGUREINTERACTOR_H_HEADER_INCLUDED #include #include "mitkCommon.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "mitkDataInteractor.h" #pragma GCC visibility push(default) #include #pragma GCC visibility pop namespace mitk { class DataNode; class Geometry2D; class DisplayGeometry; class PlanarFigure; class PositionEvent; class BaseRenderer; class InteractionPositionEvent; class StateMachineAction; #pragma GCC visibility push(default) // Define events for PlanarFigure interaction notifications itkEventMacro( PlanarFigureEvent, itk::AnyEvent ); itkEventMacro( StartPlacementPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( EndPlacementPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( SelectPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( StartInteractionPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( EndInteractionPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( StartHoverPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( EndHoverPlanarFigureEvent, PlanarFigureEvent ); itkEventMacro( ContextMenuPlanarFigureEvent, PlanarFigureEvent ); #pragma GCC visibility pop /** * \brief Interaction with mitk::PlanarFigure objects via control-points * * \ingroup Interaction */ class MitkPlanarFigure_EXPORT PlanarFigureInteractor : public DataInteractor { public: mitkClassMacro(PlanarFigureInteractor, DataInteractor); itkFactorylessNewMacro(Self) itkCloneMacro(Self) /** \brief Sets the amount of precision */ void SetPrecision( ScalarType precision ); /** \brief Sets the minimal distance between two control points. */ void SetMinimumPointDistance( ScalarType minimumDistance ); protected: PlanarFigureInteractor(); virtual ~PlanarFigureInteractor(); virtual void ConnectActionsAndFunctions(); //////// Conditions //////// bool CheckFigurePlaced( const InteractionEvent* interactionEvent ); bool CheckFigureHovering( const InteractionEvent* interactionEvent ); bool CheckControlPointHovering( const InteractionEvent* interactionEvent ); bool CheckSelection( const InteractionEvent* interactionEvent ); bool CheckPointValidity( const InteractionEvent* interactionEvent ); bool CheckFigureFinished( const InteractionEvent* interactionEvent ); bool CheckResetOnPointSelect( const InteractionEvent* interactionEvent ); bool CheckFigureOnRenderingGeometry( const InteractionEvent* interactionEvent ); bool CheckMinimalFigureFinished( const InteractionEvent* interactionEvent ); bool CheckFigureIsExtendable( const InteractionEvent* interactionEvent ); //////// Actions //////// bool FinalizeFigure( StateMachineAction*, InteractionEvent* interactionEvent ); bool MoveCurrentPoint(StateMachineAction*, InteractionEvent* interactionEvent); bool DeselectPoint(StateMachineAction*, InteractionEvent* interactionEvent); bool AddPoint(StateMachineAction*, InteractionEvent* interactionEvent); bool AddInitialPoint(StateMachineAction*, InteractionEvent* interactionEvent); bool StartHovering( StateMachineAction*, InteractionEvent* interactionEvent ); bool EndHovering( StateMachineAction*, InteractionEvent* interactionEvent ); bool SetPreviewPointPosition( StateMachineAction*, InteractionEvent* interactionEvent ); bool HidePreviewPoint( StateMachineAction*, InteractionEvent* interactionEvent ); bool HideControlPoints( StateMachineAction*, InteractionEvent* interactionEvent ); bool RemoveSelectedPoint(StateMachineAction*, InteractionEvent* interactionEvent); bool RequestContextMenu(StateMachineAction*, InteractionEvent* interactionEvent); bool SelectFigure( StateMachineAction*, InteractionEvent* interactionEvent ); bool SelectPoint( StateMachineAction*, InteractionEvent* interactionEvent ); bool EndInteraction( StateMachineAction*, InteractionEvent* interactionEvent ); /** \brief Used when clicking to determine if a point is too close to the previous point. */ bool IsMousePositionAcceptableAsNewControlPoint( const mitk::InteractionPositionEvent* positionEvent, const PlanarFigure* ); bool TransformPositionEventToPoint2D( const InteractionPositionEvent* positionEvent, const Geometry2D *planarFigureGeometry, Point2D &point2D ); bool TransformObjectToDisplay( const mitk::Point2D &point2D, mitk::Point2D &displayPoint, const mitk::Geometry2D *objectGeometry, const mitk::Geometry2D *rendererGeometry, const mitk::DisplayGeometry *displayGeometry ) const; /** \brief Returns true if the first specified point is in proximity of the line defined * the other two point; false otherwise. * * Proximity is defined as the rectangle around the line with pre-defined distance * from the line. */ bool IsPointNearLine( const mitk::Point2D& point, const mitk::Point2D& startPoint, const mitk::Point2D& endPoint, mitk::Point2D& projectedPoint ) const; /** \brief Returns true if the point contained in the passed event (in display coordinates) * is over the planar figure (with a pre-defined tolerance range); false otherwise. */ int IsPositionOverFigure( const InteractionPositionEvent* positionEvent, PlanarFigure *planarFigure, const Geometry2D *planarFigureGeometry, const Geometry2D *rendererGeometry, const DisplayGeometry *displayGeometry, Point2D& pointProjectedOntoLine) const; /** \brief Returns the index of the marker (control point) over which the point contained * in the passed event (in display coordinates) currently is; -1 if the point is not over * a marker. */ int IsPositionInsideMarker( const InteractionPositionEvent* positionEvent, const PlanarFigure *planarFigure, const Geometry2D *planarFigureGeometry, const Geometry2D *rendererGeometry, const DisplayGeometry *displayGeometry ) const; void LogPrintPlanarFigureQuantities( const PlanarFigure *planarFigure ); virtual void ConfigurationChanged(); private: /** \brief to store the value of precision to pick a point */ ScalarType m_Precision; /** \brief Store the minimal distance between two control points. */ ScalarType m_MinimumPointDistance; /** \brief True if the mouse is currently hovering over the image. */ bool m_IsHovering; bool m_LastPointWasValid; //mitk::PlanarFigure::Pointer m_PlanarFigure; }; } #endif // MITKPLANARFIGUREINTERACTOR_H_HEADER_INCLUDED diff --git a/Modules/SceneSerializationBase/BasePropertySerializer/mitkClippingPropertySerializer.cpp b/Modules/SceneSerializationBase/BasePropertySerializer/mitkClippingPropertySerializer.cpp index e86dded251..e767aff7d3 100644 --- a/Modules/SceneSerializationBase/BasePropertySerializer/mitkClippingPropertySerializer.cpp +++ b/Modules/SceneSerializationBase/BasePropertySerializer/mitkClippingPropertySerializer.cpp @@ -1,100 +1,100 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 mitkClippingPropertySerializer_h_included #define mitkClippingPropertySerializer_h_included #include "mitkBasePropertySerializer.h" #include "mitkClippingProperty.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include namespace mitk { class MitkSceneSerializationBase_EXPORT ClippingPropertySerializer : public BasePropertySerializer { public: mitkClassMacro( ClippingPropertySerializer, BasePropertySerializer ); itkFactorylessNewMacro(Self) itkCloneMacro(Self) virtual TiXmlElement* Serialize() { if (const ClippingProperty* prop = dynamic_cast(m_Property.GetPointer())) { TiXmlElement* element = new TiXmlElement("clipping"); if (prop->GetClippingEnabled()) element->SetAttribute("enabled", "true"); else element->SetAttribute("enabled", "false"); TiXmlElement* originElement = new TiXmlElement("origin"); const Point3D origin = prop->GetOrigin(); originElement->SetDoubleAttribute("x", origin[0]); originElement->SetDoubleAttribute("y", origin[1]); originElement->SetDoubleAttribute("z", origin[2]); element->LinkEndChild(originElement); TiXmlElement* normalElement = new TiXmlElement("normal"); const Vector3D normal = prop->GetNormal(); normalElement->SetDoubleAttribute("x", normal[0]); normalElement->SetDoubleAttribute("y", normal[1]); normalElement->SetDoubleAttribute("z", normal[2]); element->LinkEndChild(normalElement); return element; } else return NULL; } virtual BaseProperty::Pointer Deserialize(TiXmlElement* element) { if (!element) return NULL; bool enabled = std::string(element->Attribute("enabled")) == "true"; TiXmlElement* originElement = element->FirstChildElement("origin"); if (originElement == NULL) return NULL; Point3D origin; if ( originElement->QueryDoubleAttribute( "x", &origin[0] ) != TIXML_SUCCESS ) return NULL; if ( originElement->QueryDoubleAttribute( "y", &origin[1] ) != TIXML_SUCCESS ) return NULL; if ( originElement->QueryDoubleAttribute( "z", &origin[2] ) != TIXML_SUCCESS ) return NULL; TiXmlElement* normalElement = element->FirstChildElement("normal"); if (normalElement == NULL) return NULL; Vector3D normal; if ( normalElement->QueryDoubleAttribute( "x", &normal[0] ) != TIXML_SUCCESS ) return NULL; if ( normalElement->QueryDoubleAttribute( "y", &normal[1] ) != TIXML_SUCCESS ) return NULL; if ( normalElement->QueryDoubleAttribute( "z", &normal[2] ) != TIXML_SUCCESS ) return NULL; ClippingProperty::Pointer cp = ClippingProperty::New(origin, normal); cp->SetClippingEnabled(enabled); return cp.GetPointer(); } protected: ClippingPropertySerializer() {} virtual ~ClippingPropertySerializer() {} }; } // namespace // important to put this into the GLOBAL namespace (because it starts with 'namespace mitk') MITK_REGISTER_SERIALIZER(ClippingPropertySerializer); #endif diff --git a/Modules/Segmentation/DataManagement/mitkExtrudedContour.cpp b/Modules/Segmentation/DataManagement/mitkExtrudedContour.cpp index 1c41ceace4..c2ad0ea6f2 100644 --- a/Modules/Segmentation/DataManagement/mitkExtrudedContour.cpp +++ b/Modules/Segmentation/DataManagement/mitkExtrudedContour.cpp @@ -1,374 +1,374 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkExtrudedContour.h" -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include "mitkBaseProcess.h" #include "mitkProportionalTimeGeometry.h" #include #include #include #include #include #include #include #include #include #include //vtkButterflySubdivisionFilter * subdivs; #include #include #include #include #include mitk::ExtrudedContour::ExtrudedContour() : m_Contour(NULL), m_ClippingGeometry(NULL), m_AutomaticVectorGeneration(false) { ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New(); timeGeometry->Initialize(1); SetTimeGeometry(timeGeometry); FillVector3D(m_Vector, 0.0, 0.0, 1.0); m_RightVector.Fill(0.0); m_ExtrusionFilter = vtkLinearExtrusionFilter::New(); m_ExtrusionFilter->CappingOff(); m_ExtrusionFilter->SetExtrusionTypeToVectorExtrusion(); double vtkvector[3]={0,0,1}; // set extrusion vector m_ExtrusionFilter->SetVector(vtkvector); m_TriangleFilter = vtkTriangleFilter::New(); m_TriangleFilter->SetInputConnection(m_ExtrusionFilter->GetOutputPort()); m_SubdivisionFilter = vtkLinearSubdivisionFilter::New(); m_SubdivisionFilter->SetInputConnection(m_TriangleFilter->GetOutputPort()); m_SubdivisionFilter->SetNumberOfSubdivisions(4); m_ClippingBox = vtkPlanes::New(); m_ClipPolyDataFilter = vtkClipPolyData::New(); m_ClipPolyDataFilter->SetInputConnection(m_SubdivisionFilter->GetOutputPort()); m_ClipPolyDataFilter->SetClipFunction(m_ClippingBox); m_ClipPolyDataFilter->InsideOutOn(); m_Polygon = vtkPolygon::New(); m_ProjectionPlane = mitk::PlaneGeometry::New(); } mitk::ExtrudedContour::~ExtrudedContour() { m_ClipPolyDataFilter->Delete(); m_ClippingBox->Delete(); m_SubdivisionFilter->Delete(); m_TriangleFilter->Delete(); m_ExtrusionFilter->Delete(); m_Polygon->Delete(); } bool mitk::ExtrudedContour::IsInside(const Point3D& worldPoint) const { static double polygonNormal[3]={0.0,0.0,1.0}; // project point onto plane float xt[3]; itk2vtk(worldPoint, xt); xt[0] = worldPoint[0]-m_Origin[0]; xt[1] = worldPoint[1]-m_Origin[1]; xt[2] = worldPoint[2]-m_Origin[2]; float dist=xt[0]*m_Normal[0]+xt[1]*m_Normal[1]+xt[2]*m_Normal[2]; xt[0] -= dist*m_Normal[0]; xt[1] -= dist*m_Normal[1]; xt[2] -= dist*m_Normal[2]; double x[3]; x[0] = xt[0]*m_Right[0]+xt[1]*m_Right[1]+xt[2]*m_Right[2]; x[1] = xt[0]*m_Down[0] +xt[1]*m_Down[1] +xt[2]*m_Down[2]; x[2] = 0; // determine whether it's in the selection loop and then evaluate point // in polygon only if absolutely necessary. if ( x[0] >= this->m_ProjectedContourBounds[0] && x[0] <= this->m_ProjectedContourBounds[1] && x[1] >= this->m_ProjectedContourBounds[2] && x[1] <= this->m_ProjectedContourBounds[3] && this->m_Polygon->PointInPolygon(x, m_Polygon->Points->GetNumberOfPoints(), ((vtkDoubleArray *)this->m_Polygon->Points->GetData())->GetPointer(0), (double*)const_cast(this)->m_ProjectedContourBounds, polygonNormal) == 1 ) return true; else return false; } mitk::ScalarType mitk::ExtrudedContour::GetVolume() { return -1.0; } void mitk::ExtrudedContour::UpdateOutputInformation() { if ( this->GetSource() ) { this->GetSource()->UpdateOutputInformation(); } if(GetMTime() > m_LastCalculateExtrusionTime) { BuildGeometry(); BuildSurface(); } //if ( ( m_CalculateBoundingBox ) && ( m_PolyDataSeries.size() > 0 ) ) // CalculateBoundingBox(); } void mitk::ExtrudedContour::BuildSurface() { if(m_Contour.IsNull()) { SetVtkPolyData(NULL); return; } // set extrusion contour vtkPolyData *polyData = vtkPolyData::New(); vtkCellArray *polys = vtkCellArray::New(); polys->InsertNextCell(m_Polygon->GetPointIds()); polyData->SetPoints(m_Polygon->GetPoints()); //float vtkpoint[3]; //unsigned int i, numPts = m_Polygon->GetNumberOfPoints(); //for(i=0; im_Polygon->Points->GetPoint(i); // pointids[i]=loopPoints->InsertNextPoint(vtkpoint); //} //polys->InsertNextCell( i, pointids ); //delete [] pointids; //polyData->SetPoints( loopPoints ); polyData->SetPolys( polys ); polys->Delete(); m_ExtrusionFilter->SetInputData(polyData); polyData->Delete(); // set extrusion scale factor m_ExtrusionFilter->SetScaleFactor(GetGeometry()->GetExtentInMM(2)); SetVtkPolyData(m_SubdivisionFilter->GetOutput()); //if(m_ClippingGeometry.IsNull()) //{ // SetVtkPolyData(m_SubdivisionFilter->GetOutput()); //} //else //{ // m_ClipPolyDataFilter->SetInput(m_SubdivisionFilter->GetOutput()); // mitk::BoundingBox::BoundsArrayType bounds=m_ClippingGeometry->GetBounds(); // m_ClippingBox->SetBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]); // m_ClippingBox->SetTransform(GetGeometry()->GetVtkTransform()); // m_ClipPolyDataFilter->SetClipFunction(m_ClippingBox); // m_ClipPolyDataFilter->SetValue(0); // SetVtkPolyData(m_ClipPolyDataFilter->GetOutput()); //} m_LastCalculateExtrusionTime.Modified(); } void mitk::ExtrudedContour::BuildGeometry() { if(m_Contour.IsNull()) return; // Initialize(1); Vector3D nullvector; nullvector.Fill(0.0); float xProj[3]; unsigned int i; unsigned int numPts = 20; //m_Contour->GetNumberOfPoints(); mitk::Contour::PathPointer path = m_Contour->GetContourPath(); mitk::Contour::PathType::InputType cstart = path->StartOfInput(); mitk::Contour::PathType::InputType cend = path->EndOfInput(); mitk::Contour::PathType::InputType cstep = (cend-cstart)/numPts; mitk::Contour::PathType::InputType ccur; // Part I: guarantee/calculate legal vectors m_Vector.Normalize(); itk2vtk(m_Vector, m_Normal); // check m_Vector if(mitk::Equal(m_Vector, nullvector) || m_AutomaticVectorGeneration) { if ( m_AutomaticVectorGeneration == false) itkWarningMacro("Extrusion vector is 0 ("<< m_Vector << "); trying to use normal of polygon"); vtkPoints *loopPoints = vtkPoints::New(); //mitk::Contour::PointsContainerIterator pointsIt = m_Contour->GetPoints()->Begin(); double vtkpoint[3]; unsigned int i=0; for(i=0, ccur=cstart; iEvaluate(ccur), vtkpoint); loopPoints->InsertNextPoint(vtkpoint); } // Make sure points define a loop with a m_Normal vtkPolygon::ComputeNormal(loopPoints, m_Normal); loopPoints->Delete(); vtk2itk(m_Normal, m_Vector); if(mitk::Equal(m_Vector, nullvector)) { itkExceptionMacro("Cannot calculate normal of polygon"); } } // check m_RightVector if((mitk::Equal(m_RightVector, nullvector)) || (mitk::Equal(m_RightVector*m_Vector, 0.0)==false)) { if(mitk::Equal(m_RightVector, nullvector)) { itkDebugMacro("Right vector is 0. Calculating."); } else { itkWarningMacro("Right vector ("<InitializeStandardPlane(rightDV, downDV); // create vtkPolygon from contour and simultaneously determine 2D bounds of // contour projected on m_ProjectionPlane //mitk::Contour::PointsContainerIterator pointsIt = m_Contour->GetPoints()->Begin(); m_Polygon->Points->Reset(); m_Polygon->Points->SetNumberOfPoints(numPts); m_Polygon->PointIds->Reset(); m_Polygon->PointIds->SetNumberOfIds(numPts); mitk::Point2D pt2d; mitk::Point3D pt3d; mitk::Point2D min, max; min.Fill(itk::NumericTraits::max()); max.Fill(itk::NumericTraits::min()); xProj[2]=0.0; for(i=0, ccur=cstart; iEvaluate(ccur)); m_ProjectionPlane->Map(pt3d, pt2d); xProj[0]=pt2d[0]; if(pt2d[0]max[0]) max[0]=pt2d[0]; xProj[1]=pt2d[1]; if(pt2d[1]max[1]) max[1]=pt2d[1]; m_Polygon->Points->SetPoint(i, xProj); m_Polygon->PointIds->SetId(i, i); } // shift parametric origin to (0,0) for(i=0; im_Polygon->Points->GetPoint(i); pt[0]-=min[0]; pt[1]-=min[1]; itkDebugMacro( << i << ": (" << pt[0] << "," << pt[1] << "," << pt[2] << ")" ); } this->m_Polygon->GetBounds(m_ProjectedContourBounds); //m_ProjectedContourBounds[4]=-1.0; m_ProjectedContourBounds[5]=1.0; // calculate origin (except translation along the normal) and bounds // of m_ProjectionPlane: // origin is composed of the minimum x-/y-coordinates of the polygon, // bounds from the extent of the polygon, both after projecting on the plane mitk::Point3D origin; m_ProjectionPlane->Map(min, origin); ScalarType bounds[6]={0, max[0]-min[0], 0, max[1]-min[1], 0, 1}; m_ProjectionPlane->SetBounds(bounds); m_ProjectionPlane->SetOrigin(origin); // Part III: initialize geometry if(m_ClippingGeometry.IsNotNull()) { ScalarType min_dist=itk::NumericTraits::max(), max_dist=itk::NumericTraits::min(), dist; unsigned char i; for(i=0; i<8; ++i) { dist = m_ProjectionPlane->SignedDistance( m_ClippingGeometry->GetCornerPoint(i) ); if(distmax_dist) max_dist=dist; } //incorporate translation along the normal into origin origin = origin+m_Vector*min_dist; m_ProjectionPlane->SetOrigin(origin); bounds[5]=max_dist-min_dist; } else bounds[5]=20; itk2vtk(origin, m_Origin); mitk::Geometry3D::Pointer g3d = GetGeometry( 0 ); assert( g3d.IsNotNull() ); g3d->SetBounds(bounds); g3d->SetIndexToWorldTransform(m_ProjectionPlane->GetIndexToWorldTransform()); g3d->TransferItkToVtkTransform(); ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New(); timeGeometry->Initialize(g3d,1); SetTimeGeometry(timeGeometry); } unsigned long mitk::ExtrudedContour::GetMTime() const { unsigned long latestTime = Superclass::GetMTime(); if(m_Contour.IsNotNull()) { unsigned long localTime; localTime = m_Contour->GetMTime(); if(localTime > latestTime) latestTime = localTime; } return latestTime; } diff --git a/Modules/Segmentation/Interactions/mitkContourInteractor.h b/Modules/Segmentation/Interactions/mitkContourInteractor.h index f07cf3ce05..8a4a2d5006 100644 --- a/Modules/Segmentation/Interactions/mitkContourInteractor.h +++ b/Modules/Segmentation/Interactions/mitkContourInteractor.h @@ -1,65 +1,65 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 __ContourInteractor_H #define __ContourInteractor_H #include "mitkCommon.h" #include #include -#include +#include namespace mitk { //##Documentation //## @brief Interactor for the creation of an mitk::Contour //## @ingroup Interaction class MitkSegmentation_EXPORT ContourInteractor : public mitk::Interactor { public: mitkClassMacro(ContourInteractor, Interactor); mitkNewMacro2Param(Self, const char*, DataNode*); protected: ContourInteractor(const char * type, DataNode* dataNode); virtual ~ContourInteractor(); virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); /** * entry method for any interaction. Method is called if user * presses the left mouse button down. */ virtual void Press (mitk::Point3D& op); /** * this method is finally called after user release the left mouse button */ virtual void Release (mitk::Point3D& op); /** * method is called when the user moves the mouse with left mouse button down */ virtual void Move (mitk::Point3D& op); protected: bool m_Positive; bool m_Started; }; } #endif //__ContourInteractor_H diff --git a/Modules/Segmentation/Interactions/mitkExtrudedContourInteractor.h b/Modules/Segmentation/Interactions/mitkExtrudedContourInteractor.h index 4897f04206..3b370de2f6 100644 --- a/Modules/Segmentation/Interactions/mitkExtrudedContourInteractor.h +++ b/Modules/Segmentation/Interactions/mitkExtrudedContourInteractor.h @@ -1,72 +1,72 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 __ExtrudedContourInteractor_H #define __ExtrudedContourInteractor_H #include "mitkCommon.h" #include #include -#include +#include #include #include namespace mitk { //##Documentation //## @brief Interactor for the creation of an mitk::Contour //## @ingroup Interaction class MitkSegmentation_EXPORT ExtrudedContourInteractor : public mitk::Interactor { public: mitkClassMacro(ExtrudedContourInteractor, Interactor); mitkNewMacro2Param(Self, const char*, DataNode*); itkGetObjectMacro(Contour, mitk::Contour); itkGetObjectMacro(ContourNode, mitk::DataNode); protected: ExtrudedContourInteractor(const char * type, DataNode* dataNode); virtual ~ExtrudedContourInteractor(); virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent); /** * entry method for any interaction. Method is called if user * presses the left mouse button down. */ virtual void Press (mitk::Point3D& op); /** * this method is finally called after user release the left mouse button */ virtual void Release (mitk::Point3D& op); /** * method is called when the user moves the mouse with left mouse button down */ virtual void Move (mitk::Point3D& op); protected: bool m_Positive; bool m_Started; mitk::Contour::Pointer m_Contour; mitk::DataNode::Pointer m_ContourNode; }; } #endif //__ExtrudedContourInteractor_H diff --git a/Modules/ToFProcessing/Testing/mitkKinectReconstructionTest.cpp b/Modules/ToFProcessing/Testing/mitkKinectReconstructionTest.cpp index 1820fb8fbf..c166884f12 100644 --- a/Modules/ToFProcessing/Testing/mitkKinectReconstructionTest.cpp +++ b/Modules/ToFProcessing/Testing/mitkKinectReconstructionTest.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 #include #include #include #include #include -#include +#include #include #include #include #include #include /** * @brief mitkKinectReconstructionTest Testing method for the Kinect reconstruction mode. Specially meant for Kinect. * This tests loads a special data set from MITK-Data and compares it to a reference surface. * This test has no dependency to the mitkKinectModule, although it is thematically connected to it. */ int mitkKinectReconstructionTest(int argc , char* argv[]) { MITK_TEST_BEGIN("mitkKinectReconstructionTest"); MITK_TEST_CONDITION_REQUIRED(argc > 2, "Testing if enough arguments are set."); std::string calibrationFilePath(argv[1]); std::string kinectImagePath(argv[2]); mitk::ToFDistanceImageToSurfaceFilter::Pointer distToSurf = mitk::ToFDistanceImageToSurfaceFilter::New(); mitk::CameraIntrinsics::Pointer intrinsics = mitk::CameraIntrinsics::New(); //load our personal kinect calibration intrinsics->FromXMLFile(calibrationFilePath); MITK_TEST_CONDITION_REQUIRED(intrinsics.IsNotNull(), "Testing if a calibration file could be loaded."); distToSurf->SetCameraIntrinsics(intrinsics); distToSurf->SetReconstructionMode(mitk::ToFDistanceImageToSurfaceFilter::Kinect); //load a data set mitk::Image::Pointer kinectImage = mitk::IOUtil::LoadImage(kinectImagePath); MITK_TEST_CONDITION_REQUIRED(kinectImage.IsNotNull(), "Testing if a kinect image could be loaded."); distToSurf->SetInput(kinectImage); distToSurf->Update(); mitk::Surface::Pointer resultOfFilter = distToSurf->GetOutput(); MITK_TEST_CONDITION_REQUIRED(resultOfFilter.IsNotNull(), "Testing if any output was generated."); mitk::PointSet::Pointer resultPointSet = mitk::ToFTestingCommon::VtkPolyDataToMitkPointSet(resultOfFilter->GetVtkPolyData()); // generate ground truth data mitk::PointSet::Pointer groundTruthPointSet = mitk::PointSet::New(); mitk::ToFProcessingCommon::ToFPoint2D focalLength; focalLength[0] = intrinsics->GetFocalLengthX(); focalLength[1] = intrinsics->GetFocalLengthY(); mitk::ToFProcessingCommon::ToFPoint2D principalPoint; principalPoint[0] = intrinsics->GetPrincipalPointX(); principalPoint[1] = intrinsics->GetPrincipalPointY(); int xDimension = (int)kinectImage->GetDimension(0); int yDimension = (int)kinectImage->GetDimension(1); int pointCount = 0; mitk::ImagePixelReadAccessor imageAcces(kinectImage, kinectImage->GetSliceData(0)); for (int j=0; j pixel; pixel[0] = i; pixel[1] = j; mitk::ToFProcessingCommon::ToFScalarType distance = (double)imageAcces.GetPixelByIndex(pixel); mitk::Point3D currentPoint; currentPoint = mitk::ToFProcessingCommon::KinectIndexToCartesianCoordinates(i,j,distance,focalLength[0],focalLength[1],principalPoint[0],principalPoint[1]); if (distance>mitk::eps) { groundTruthPointSet->InsertPoint( pointCount, currentPoint ); pointCount++; } } } MITK_TEST_CONDITION_REQUIRED( mitk::ToFTestingCommon::PointSetsEqual(resultPointSet,groundTruthPointSet), "Testing if point sets are equal (with a small epsilon)."); MITK_TEST_END(); } diff --git a/Modules/ToFProcessing/Testing/mitkToFDistanceImageToPointSetFilterTest.cpp b/Modules/ToFProcessing/Testing/mitkToFDistanceImageToPointSetFilterTest.cpp index 89451cbc93..bcd0823a7b 100644 --- a/Modules/ToFProcessing/Testing/mitkToFDistanceImageToPointSetFilterTest.cpp +++ b/Modules/ToFProcessing/Testing/mitkToFDistanceImageToPointSetFilterTest.cpp @@ -1,346 +1,346 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include #include #include #include -#include +#include #include #include #include #include /**Documentation * test for the class "ToFDistanceImageToPointSetFilter". */ mitk::PointSet::Pointer CreateTestPointSet() { mitk::PointSet::Pointer subSet = mitk::PointSet::New(); mitk::Point3D point; point[0] = 10; point[1] = 20; point[2] = 0; subSet->InsertPoint(0,point); point[0] = 100; point[1] = 150; point[2] = 0; subSet->InsertPoint(1,point); point[0] = 110; point[1] = 30; point[2] = 0; subSet->InsertPoint(2,point); point[0] = 40; point[1] = 200; point[2] = 0; subSet->InsertPoint(3,point); return subSet; } std::vector > CreateVectorPointSet() { std::vector > subSet = std::vector >(); itk::Index<3> point; point[0] = 10; point[1] = 20; point[2] = 0; subSet.push_back(point); point[0] = 100; point[1] = 150; point[2] = 0; subSet.push_back(point); point[0] = 110; point[1] = 30; point[2] = 0; subSet.push_back(point); point[0] = 40; point[1] = 200; point[2] = 0; subSet.push_back(point); return subSet; } // Create image with pixelValue in every pixel except for the pixels in subSet, which get successively the values of distances inline static mitk::Image::Pointer CreateTestImageWithPointSet(float pixelValue, unsigned int dimX, unsigned int dimY, mitk::PointSet::Pointer subSet) { typedef itk::Image ItkImageType2D; typedef itk::ImageRegionIterator ItkImageRegionIteratorType2D; ItkImageType2D::Pointer image = ItkImageType2D::New(); ItkImageType2D::IndexType start; start[0] = 0; start[1] = 0; ItkImageType2D::SizeType size; size[0] = dimX; size[1] = dimY; ItkImageType2D::RegionType region; region.SetSize(size); region.SetIndex( start); ItkImageType2D::SpacingType spacing; spacing[0] = 1.0; spacing[1] = 1.0; image->SetRegions( region ); image->SetSpacing ( spacing ); image->Allocate(); //Obtaining image data from ToF camera// //Correlate inten values to PixelIndex// ItkImageRegionIteratorType2D imageIterator(image,image->GetLargestPossibleRegion()); imageIterator.GoToBegin(); while (!imageIterator.IsAtEnd()) { imageIterator.Set(pixelValue); ++imageIterator; } // distances varying from pixelValue std::vector distances; distances.push_back(50); distances.push_back(500); distances.push_back(2050); distances.push_back(300); // set the pixel values for the subset for(int i=0; iGetSize(); i++) { mitk::Point3D point = subSet->GetPoint(i); ItkImageType2D::IndexType index; index[0] = point[0]; index[1] = point[1]; float distance = distances.at(i); image->SetPixel(index,distance); } mitk::Image::Pointer mitkImage = mitk::Image::New(); mitk::CastToMitkImage(image,mitkImage); return mitkImage; } int mitkToFDistanceImageToPointSetFilterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("ToFDistanceImageToPointSetFilter"); mitk::ToFDistanceImageToPointSetFilter::Pointer filter = mitk::ToFDistanceImageToPointSetFilter::New(); //create test sub set MITK_INFO<<"Create test pointset"; mitk::PointSet::Pointer subSet = CreateTestPointSet(); //create test image unsigned int dimX = 204; unsigned int dimY = 204; MITK_INFO<<"Create test image"; mitk::Image::Pointer image = CreateTestImageWithPointSet(1000.0f,dimX,dimY,subSet); //initialize intrinsic parameters //initialize intrinsic parameters with some arbitrary values mitk::ToFProcessingCommon::ToFPoint2D interPixelDistance; interPixelDistance[0] = 0.04564; interPixelDistance[1] = 0.0451564; mitk::ToFProcessingCommon::ToFScalarType focalLengthX = 295.78960; mitk::ToFProcessingCommon::ToFScalarType focalLengthY = 296.348535; mitk::ToFProcessingCommon::ToFScalarType focalLength = (focalLengthX*interPixelDistance[0]+focalLengthY*interPixelDistance[1])/2.0; mitk::ToFProcessingCommon::ToFScalarType k1=-0.36,k2=-0.14,p1=0.001,p2=-0.00; mitk::ToFProcessingCommon::ToFPoint2D principalPoint; principalPoint[0] = 103.576546; principalPoint[1] = 100.1532; mitk::CameraIntrinsics::Pointer cameraIntrinsics = mitk::CameraIntrinsics::New(); cameraIntrinsics->SetFocalLength(focalLengthX,focalLengthY); cameraIntrinsics->SetPrincipalPoint(principalPoint[0],principalPoint[1]); cameraIntrinsics->SetDistorsionCoeffs(k1,k2,p1,p2); // test SetCameraIntrinsics() filter->SetCameraIntrinsics(cameraIntrinsics); MITK_TEST_CONDITION_REQUIRED((focalLengthX==filter->GetCameraIntrinsics()->GetFocalLengthX()),"Testing SetCameraIntrinsics with focalLength"); mitk::ToFProcessingCommon::ToFPoint2D pp; pp[0] = filter->GetCameraIntrinsics()->GetPrincipalPointX(); pp[1] = filter->GetCameraIntrinsics()->GetPrincipalPointY(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(principalPoint,pp),"Testing SetCameraIntrinsics with principalPoint()"); // test SetInterPixelDistance() filter->SetInterPixelDistance(interPixelDistance); mitk::ToFProcessingCommon::ToFPoint2D ipD = filter->GetInterPixelDistance(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(ipD,interPixelDistance),"Testing Set/GetInterPixelDistance()"); // test SetReconstructionMode() filter->SetReconstructionMode(false); MITK_TEST_CONDITION_REQUIRED(filter->GetReconstructionMode() == false,"Testing Set/GetReconstructionMode()"); // test Set/GetInput() filter->SetInput(image); MITK_TEST_CONDITION_REQUIRED((image==filter->GetInput()),"Testing Set/GetInput()"); // test filter without subset (without using the interpixeldistance) MITK_INFO<<"Test filter without subset without using the interpixeldistance"; filter->SetReconstructionMode(true); mitk::PointSet::Pointer expectedResult = mitk::PointSet::New(); unsigned int counter = 0; mitk::ImagePixelReadAccessor imageAcces(image, image->GetSliceData(0)); for (unsigned int j=0; j index; index[0] = i; index[1] = j; float distance = imageAcces.GetPixelByIndex(index); mitk::Point3D coordinate = mitk::ToFProcessingCommon::IndexToCartesianCoordinates(i,j,distance,focalLengthX,focalLengthY,principalPoint[0],principalPoint[1]); expectedResult->InsertPoint(counter,coordinate); counter++; } } filter->Update(); mitk::PointSet::Pointer result = filter->GetOutput(); MITK_TEST_CONDITION_REQUIRED((expectedResult->GetSize()==result->GetSize()),"Test if point set size is equal"); MITK_TEST_CONDITION_REQUIRED(mitk::ToFTestingCommon::PointSetsEqual(expectedResult,result),"Testing filter without subset"); // compare filter result with ToFDistanceImageToSurfaceFilter MITK_INFO<<"Compare filter result with ToFDistanceImageToSurfaceFilter"; mitk::ToFDistanceImageToSurfaceFilter::Pointer surfaceFilter = mitk::ToFDistanceImageToSurfaceFilter::New(); surfaceFilter->SetInput(image); surfaceFilter->SetInterPixelDistance(interPixelDistance); surfaceFilter->SetCameraIntrinsics(cameraIntrinsics); surfaceFilter->SetReconstructionMode(mitk::ToFDistanceImageToSurfaceFilter::WithOutInterPixelDistance); MITK_TEST_CONDITION_REQUIRED(filter->GetReconstructionMode() == mitk::ToFDistanceImageToSurfaceFilter::WithOutInterPixelDistance,"Testing Set/GetReconstructionMode()"); mitk::Surface::Pointer surface = surfaceFilter->GetOutput(); surface->Update(); // create point set from surface mitk::PointSet::Pointer pointSet = mitk::ToFTestingCommon::VtkPolyDataToMitkPointSet(surface->GetVtkPolyData()); //compare pointset against ground truth MITK_TEST_CONDITION_REQUIRED((pointSet->GetSize()==result->GetSize()),"Test if point set size is equal"); MITK_TEST_CONDITION_REQUIRED(mitk::ToFTestingCommon::PointSetsEqual(pointSet,result),"Compare with surface points"); // test filter without subset (with using the interpixeldistance) MITK_INFO<<"Test filter without subset with using the interpixeldistance"; filter->Modified(); filter->SetReconstructionMode(false); expectedResult = mitk::PointSet::New(); counter = 0; for (unsigned int j=0; j index; index[0] = i; index[1] = j; float distance = imageAcces.GetPixelByIndex(index); mitk::Point3D coordinate = mitk::ToFProcessingCommon::IndexToCartesianCoordinatesWithInterpixdist(i,j,distance,focalLength,interPixelDistance,principalPoint); expectedResult->InsertPoint(counter,coordinate); counter++; } } filter->Update(); result = filter->GetOutput(); MITK_TEST_CONDITION_REQUIRED((expectedResult->GetSize()==result->GetSize()),"Test if point set size is equal"); MITK_TEST_CONDITION_REQUIRED(mitk::ToFTestingCommon::PointSetsEqual(expectedResult,result),"Testing filter without subset"); // compare filter result with ToFDistanceImageToSurfaceFilter MITK_INFO<<"Compare filter result with ToFDistanceImageToSurfaceFilter"; surfaceFilter = mitk::ToFDistanceImageToSurfaceFilter::New(); surfaceFilter->SetInput(image); surfaceFilter->SetInterPixelDistance(interPixelDistance); surfaceFilter->SetCameraIntrinsics(cameraIntrinsics); surfaceFilter->SetReconstructionMode(mitk::ToFDistanceImageToSurfaceFilter::WithInterPixelDistance); MITK_TEST_CONDITION_REQUIRED(surfaceFilter->GetReconstructionMode() == mitk::ToFDistanceImageToSurfaceFilter::WithInterPixelDistance,"Testing Set/GetReconstructionMode()"); surface = surfaceFilter->GetOutput(); surface->Update(); // create point set from surface pointSet = mitk::ToFTestingCommon::VtkPolyDataToMitkPointSet(surface->GetVtkPolyData()); //compare against ground truth MITK_TEST_CONDITION_REQUIRED((pointSet->GetSize()==result->GetSize()),"Test if point set size is equal"); MITK_TEST_CONDITION_REQUIRED(mitk::ToFTestingCommon::PointSetsEqual(pointSet,result),"Compare with surface points"); // test filter with subset (without using the interpixeldistance) MITK_INFO<<"Test filter with subset without using the interpixeldistance"; filter = mitk::ToFDistanceImageToPointSetFilter::New(); filter->SetInput(image); filter->SetInterPixelDistance(interPixelDistance); filter->SetCameraIntrinsics(cameraIntrinsics); filter->SetReconstructionMode(true); expectedResult = mitk::PointSet::New(); counter = 0; for(int i=0; iGetSize(); i++) { mitk::Point3D point = subSet->GetPoint(i); itk::Index<2> index; index[0] = point[0]; index[1] = point[1]; float distance = imageAcces.GetPixelByIndex(index); mitk::Point3D coordinate = mitk::ToFProcessingCommon::IndexToCartesianCoordinates(point[0],point[1], distance,focalLengthX,focalLengthY,principalPoint[0],principalPoint[1]); expectedResult->InsertPoint(counter,coordinate); counter++; } filter->SetSubset(subSet); filter->Modified(); filter->Update(); result = filter->GetOutput(); MITK_TEST_CONDITION_REQUIRED((expectedResult->GetSize()==result->GetSize()),"Test if point set size is equal"); MITK_TEST_CONDITION_REQUIRED(mitk::ToFTestingCommon::PointSetsEqual(expectedResult,result),"Testing filter with subset"); // test filter with subset (with using the interpixeldistance) MITK_INFO<<"Test filter with subset with using the interpixeldistance"; filter = mitk::ToFDistanceImageToPointSetFilter::New(); filter->SetInput(image); filter->SetInterPixelDistance(interPixelDistance); filter->SetCameraIntrinsics(cameraIntrinsics); filter->SetReconstructionMode(false); expectedResult = mitk::PointSet::New(); counter = 0; for(int i=0; iGetSize(); i++) { mitk::Point3D point = subSet->GetPoint(i); itk::Index<2> index; index[0] = point[0]; index[1] = point[1]; float distance = imageAcces.GetPixelByIndex(index); mitk::Point3D coordinate = mitk::ToFProcessingCommon::IndexToCartesianCoordinatesWithInterpixdist(point[0],point[1], distance,focalLength,interPixelDistance,principalPoint); expectedResult->InsertPoint(counter,coordinate); counter++; } filter->SetSubset(subSet); filter->Modified(); filter->Update(); result = filter->GetOutput(); MITK_TEST_CONDITION_REQUIRED((expectedResult->GetSize()==result->GetSize()),"Test if point set size is equal"); MITK_TEST_CONDITION_REQUIRED(mitk::ToFTestingCommon::PointSetsEqual(expectedResult,result),"Testing filter with subset"); // Test case to reproduce and check fix of bug 13933. std::vector > vecSubset = CreateVectorPointSet(); filter = mitk::ToFDistanceImageToPointSetFilter::New(); try { filter->SetSubset(vecSubset); } catch (...) { MITK_TEST_CONDITION_REQUIRED(false, "Caught an exception while setting point subset!"); } MITK_TEST_END(); } diff --git a/Modules/ToFProcessing/Testing/mitkToFDistanceImageToSurfaceFilterTest.cpp b/Modules/ToFProcessing/Testing/mitkToFDistanceImageToSurfaceFilterTest.cpp index f8a5fbab41..e4c6980da7 100644 --- a/Modules/ToFProcessing/Testing/mitkToFDistanceImageToSurfaceFilterTest.cpp +++ b/Modules/ToFProcessing/Testing/mitkToFDistanceImageToSurfaceFilterTest.cpp @@ -1,392 +1,392 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include #include #include -#include +#include #include #include #include #include #include /** * @brief Test for the class "ToFDistanceImageToSurfaceFilter". */ typedef mitk::ToFProcessingCommon::ToFPoint2D ToFPoint2D; typedef mitk::ToFProcessingCommon::ToFPoint3D ToFPoint3D; typedef mitk::ToFProcessingCommon::ToFScalarType ToFScalarType; int mitkToFDistanceImageToSurfaceFilterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("ToFDistanceImageToSurfaceFilter"); mitk::ToFDistanceImageToSurfaceFilter::Pointer filter = mitk::ToFDistanceImageToSurfaceFilter::New(); // create test image unsigned int dimX =204; unsigned int dimY =204; mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(dimX,dimY); //initialize intrinsic parameters with some arbitrary values ToFScalarType focalLengthX = 295.78960; ToFScalarType focalLengthY = 296.348535; ToFPoint2D focalLengthXY; focalLengthXY[0]=focalLengthX; focalLengthXY[1]=focalLengthY; ToFScalarType k1=-0.36,k2=-0.14,p1=0.001,p2=-0.00; ToFPoint2D principalPoint; principalPoint[0] = 103.576546; principalPoint[1] = 100.1532; mitk::CameraIntrinsics::Pointer cameraIntrinsics = mitk::CameraIntrinsics::New(); cameraIntrinsics->SetFocalLength(focalLengthX,focalLengthY); cameraIntrinsics->SetPrincipalPoint(principalPoint[0],principalPoint[1]); cameraIntrinsics->SetDistorsionCoeffs(k1,k2,p1,p2); // test SetCameraIntrinsics() filter->SetCameraIntrinsics(cameraIntrinsics); MITK_TEST_CONDITION_REQUIRED((focalLengthX==filter->GetCameraIntrinsics()->GetFocalLengthX()),"Testing SetCameraIntrinsics with focalLength"); ToFPoint2D pp; pp[0] = filter->GetCameraIntrinsics()->GetPrincipalPointX(); pp[1] = filter->GetCameraIntrinsics()->GetPrincipalPointY(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(principalPoint,pp),"Testing SetCameraIntrinsics with principalPoint()"); // test SetInterPixelDistance() ToFPoint2D interPixelDistance; interPixelDistance[0] = 0.04564; interPixelDistance[1] = 0.0451564; filter->SetInterPixelDistance(interPixelDistance); ToFPoint2D ipD = filter->GetInterPixelDistance(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(ipD,interPixelDistance),"Testing Set/GetInterPixelDistance()"); // test SetReconstructionMode() filter->SetReconstructionMode(mitk::ToFDistanceImageToSurfaceFilter::WithInterPixelDistance); MITK_TEST_CONDITION_REQUIRED(filter->GetReconstructionMode() == mitk::ToFDistanceImageToSurfaceFilter::WithInterPixelDistance,"Testing Set/GetReconstructionMode()"); // test Set/GetInput() filter->SetInput(image); MITK_TEST_CONDITION_REQUIRED((image==filter->GetInput()),"Testing Set/GetInput()"); // test filter without subset (without interpixeldistance) MITK_INFO<<"Test filter with subset without interpixeldistance "; filter->SetReconstructionMode(mitk::ToFDistanceImageToSurfaceFilter::WithOutInterPixelDistance); MITK_TEST_CONDITION_REQUIRED(filter->GetReconstructionMode() == mitk::ToFDistanceImageToSurfaceFilter::WithOutInterPixelDistance,"Testing Set/GetReconstructionMode()"); vtkSmartPointer expectedResult = vtkSmartPointer::New(); expectedResult->SetDataTypeToDouble(); unsigned int counter = 0; double* point = new double[3]; // MITK_INFO<<"Test"; // MITK_INFO<<"focal: "< index = {{ i, j }}; float distance = 0.0; try { mitk::ImagePixelReadAccessor readAccess(image, image->GetSliceData()); distance = readAccess.GetPixelByIndex(index); } catch(mitk::Exception& e) { MITK_ERROR << "Image read exception!" << e.what(); } ToFPoint3D coordinate = mitk::ToFProcessingCommon::IndexToCartesianCoordinates(i,j,distance,focalLengthX,focalLengthY,principalPoint[0],principalPoint[1]); // if ((i==0)&&(j==0)) // { // MITK_INFO<<"Distance test: "<InsertPoint(pointID,point); } counter++; } } filter->Update(); mitk::Surface::Pointer resultSurface = filter->GetOutput(); vtkSmartPointer result = vtkSmartPointer::New(); result->SetDataTypeToDouble(); result = resultSurface->GetVtkPolyData()->GetPoints(); MITK_TEST_CONDITION_REQUIRED((expectedResult->GetNumberOfPoints()==result->GetNumberOfPoints()),"Test if number of points in surface is equal"); bool pointSetsEqual = true; for (unsigned int i=0; iGetNumberOfPoints(); i++) { double* expected = expectedResult->GetPoint(i); double* res = result->GetPoint(i); ToFPoint3D expectedPoint; expectedPoint[0] = expected[0]; expectedPoint[1] = expected[1]; expectedPoint[2] = expected[2]; ToFPoint3D resultPoint; resultPoint[0] = res[0]; resultPoint[1] = res[1]; resultPoint[2] = res[2]; if (!mitk::Equal(expectedPoint,resultPoint)) { // MITK_INFO << i; pointSetsEqual = false; } } MITK_TEST_CONDITION_REQUIRED(pointSetsEqual,"Testing filter without subset"); // test filter without subset (with interpixeldistance) MITK_INFO<<"Test filter with subset with interpixeldistance "; filter->SetReconstructionMode(mitk::ToFDistanceImageToSurfaceFilter::WithInterPixelDistance); MITK_TEST_CONDITION_REQUIRED(filter->GetReconstructionMode() == mitk::ToFDistanceImageToSurfaceFilter::WithInterPixelDistance,"Testing Set/GetReconstructionMode()"); // calculate focal length considering inter pixel distance ToFScalarType focalLength = (focalLengthX*interPixelDistance[0]+focalLengthY*interPixelDistance[1])/2.0; expectedResult = vtkSmartPointer::New(); expectedResult->SetDataTypeToDouble(); counter = 0; point = new double[3]; // MITK_INFO<<"Test"; // MITK_INFO<<"focal: "< index = {{ i, j }}; float distance = 0.0; try { mitk::ImagePixelReadAccessor readAccess(image, image->GetSliceData()); distance = readAccess.GetPixelByIndex(index); } catch(mitk::Exception& e) { MITK_ERROR << "Image read exception!" << e.what(); } ToFPoint3D coordinate = mitk::ToFProcessingCommon::IndexToCartesianCoordinatesWithInterpixdist(i,j,distance,focalLength,interPixelDistance,principalPoint); // if ((i==0)&&(j==0)) // { // MITK_INFO<<"Distance test: "<InsertPoint(pointID,point); } counter++; } } filter->Modified(); filter->Update(); resultSurface = filter->GetOutput(); result = vtkSmartPointer::New(); result->SetDataTypeToDouble(); result = resultSurface->GetVtkPolyData()->GetPoints(); MITK_TEST_CONDITION_REQUIRED((expectedResult->GetNumberOfPoints()==result->GetNumberOfPoints()),"Test if number of points in surface is equal"); pointSetsEqual = true; for (unsigned int i=0; iGetNumberOfPoints(); i++) { double* expected = expectedResult->GetPoint(i); double* res = result->GetPoint(i); ToFPoint3D expectedPoint; expectedPoint[0] = expected[0]; expectedPoint[1] = expected[1]; expectedPoint[2] = expected[2]; ToFPoint3D resultPoint; resultPoint[0] = res[0]; resultPoint[1] = res[1]; resultPoint[2] = res[2]; if (!mitk::Equal(expectedPoint,resultPoint)) { // MITK_INFO << i; MITK_INFO<<"expected: "<GetNumberOfPoints(); i++) { double* expected = expectedResult->GetPoint(i); double* res = result->GetPoint(i); ToFPoint3D expectedPoint; expectedPoint[0] = expected[0]; expectedPoint[1] = expected[1]; expectedPoint[2] = expected[2]; ToFPoint3D resultPoint; resultPoint[0] = res[0]; resultPoint[1] = res[1]; resultPoint[2] = res[2]; ToFPoint3D expectedPointBackward = mitk::ToFProcessingCommon::CartesianToIndexCoordinates(expectedPoint,focalLengthXY,principalPoint); ToFPoint3D resultPointBackward = mitk::ToFProcessingCommon::CartesianToIndexCoordinates(resultPoint,focalLengthXY,principalPoint); if (!mitk::Equal(expectedPointBackward,resultPointBackward)) { // MITK_INFO << i; // MITK_INFO<<"expected: "<GetNumberOfPoints(); i++) { double* expected = expectedResult->GetPoint(i); double* res = result->GetPoint(i); ToFPoint3D expectedPoint; expectedPoint[0] = expected[0]; expectedPoint[1] = expected[1]; expectedPoint[2] = expected[2]; ToFPoint3D resultPoint; resultPoint[0] = res[0]; resultPoint[1] = res[1]; resultPoint[2] = res[2]; ToFPoint3D expectedPointBackward = mitk::ToFProcessingCommon::CartesianToIndexCoordinatesWithInterpixdist(expectedPoint,focalLength,interPixelDistance,principalPoint); ToFPoint3D resultPointBackward = mitk::ToFProcessingCommon::CartesianToIndexCoordinatesWithInterpixdist(resultPoint,focalLength,interPixelDistance,principalPoint); if (!mitk::Equal(expectedPointBackward,resultPointBackward)) { // MITK_INFO << i; // MITK_INFO<<"expected: "<GetNumberOfPoints(); i++) { double* res = result->GetPoint(i); ToFPoint3D resultPoint; resultPoint[0] = res[0]; resultPoint[1] = res[1]; resultPoint[2] = res[2]; ToFPoint3D resultPointBackward = mitk::ToFProcessingCommon::CartesianToIndexCoordinates(resultPoint,focalLengthXY,principalPoint); itk::Index<2> index = {{ (int) (resultPointBackward[0]+0.5), (int) (resultPointBackward[1]+0.5) }}; float distanceBackward = 0.0; try { mitk::ImagePixelReadAccessor readAccess(image, image->GetSliceData()); distanceBackward = readAccess.GetPixelByIndex(index); } catch(mitk::Exception& e) { MITK_ERROR << "Image read exception!" << e.what(); } if (!mitk::Equal(distanceBackward,(float) resultPointBackward[2])) { MITK_INFO<<"expected: " << resultPointBackward[2]; MITK_INFO<<"result: "<< distanceBackward; compareToInput = false; } } MITK_TEST_CONDITION_REQUIRED(compareToInput,"Testing backward transformation compared to original image without interpixeldistance"); //Backwardtransformation test compare to original input with interpixeldistance compareToInput = true; for (unsigned int i=0; iGetNumberOfPoints(); i++) { double* res = result->GetPoint(i); ToFPoint3D resultPoint; resultPoint[0] = res[0]; resultPoint[1] = res[1]; resultPoint[2] = res[2]; ToFPoint3D resultPointBackward = mitk::ToFProcessingCommon::CartesianToIndexCoordinatesWithInterpixdist(resultPoint,focalLength,interPixelDistance,principalPoint); itk::Index<2> pixelIndex = {{ (int) (resultPointBackward[0]+0.5), (int) (resultPointBackward[1]+0.5) }}; float distanceBackward = 0.0; try { mitk::ImagePixelReadAccessor readAccess(image, image->GetSliceData()); distanceBackward = readAccess.GetPixelByIndex(pixelIndex); } catch(mitk::Exception& e) { MITK_ERROR << "Image read exception!" << e.what(); } if (!mitk::Equal(distanceBackward, (float) resultPointBackward[2])) { // MITK_INFO<<"expected: "<< image->GetPixelValueByIndex(pixelIndex); // MITK_INFO<<"result: "<< resultPoint; compareToInput = false; } } MITK_TEST_CONDITION_REQUIRED(compareToInput,"Testing backward transformation compared to original image with interpixeldistance"); //clean up delete point; // expectedResult->Delete(); MITK_TEST_END(); } diff --git a/Modules/ToFProcessing/mitkToFProcessingCommon.h b/Modules/ToFProcessing/mitkToFProcessingCommon.h index 1a5808d72d..ed9ba61f9a 100644 --- a/Modules/ToFProcessing/mitkToFProcessingCommon.h +++ b/Modules/ToFProcessing/mitkToFProcessingCommon.h @@ -1,345 +1,345 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 MITKTOFPROCESSINGCOMMON_H #define MITKTOFPROCESSINGCOMMON_H #include #include -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include namespace mitk { /** * @brief Helper class providing functions which are useful for multiple usage * * Currently the following methods are provided: *
    *
  • Conversion from 2D image coordinates to 3D world coordinates (IndexToCartesianCoordinates()) *
  • Conversion from 3D world coordinates to 2D image coordinates (CartesianToIndexCoordinates()) *
* The coordinate conversion follows the model of a common pinhole camera where the origin of the camera * coordinate system (world coordinates) is at the pinhole * \image html ../Modules/ToFProcessing/Documentation/PinholeCameraModel.png * The definition of the image plane and its coordinate systems (pixel and mm) is depicted in the following image * \image html ../Modules/ToFProcessing/Documentation/ImagePlane.png * @ingroup ToFProcessing */ class MitkToFProcessing_EXPORT ToFProcessingCommon { public: typedef double ToFScalarType; typedef itk::Point ToFPoint2D; typedef itk::Point ToFPoint3D; typedef itk::Vector ToFVector2D; typedef itk::Vector ToFVector3D; /*! \brief Convert index based distances to cartesian coordinates \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLengthX focal length of optical system in pixel units in x-direction (mostly obtained from camera calibration) \param focalLengthY focal length of optical system in pixel units in y-direction (mostly obtained from camera calibration) \param principalPointX x coordinate of principal point on image plane in pixel \param principalPointY y coordinate of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ static ToFPoint3D IndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY); /*! \brief Convert index based distances to cartesian coordinates \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ inline static ToFPoint3D IndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFPoint2D focalLength, ToFPoint2D principalPoint) { return IndexToCartesianCoordinates(i,j,distance,focalLength[0],focalLength[1],principalPoint[0],principalPoint[1]); } /*! \brief Convert index based distances to cartesian coordinates \param index index coordinates \param distance distance value at given index in mm \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ inline static ToFPoint3D IndexToCartesianCoordinates(itk::Index<3> index, ToFScalarType distance, ToFPoint2D focalLength, ToFPoint2D principalPoint) { return IndexToCartesianCoordinates(index[0],index[1],distance,focalLength[0],focalLength[1],principalPoint[0], principalPoint[1]); } /*! \brief Convenience method to convert index based distances to cartesian coordinates using array as input \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ inline static ToFPoint3D IndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength[2], ToFScalarType principalPoint[2]) { return IndexToCartesianCoordinates(i,j,distance,focalLength[0],focalLength[1],principalPoint[0],principalPoint[1]); } /*! \brief Convert index based distances to cartesian coordinates \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistanceX distance in x direction between adjacent pixels in mm \param interPixelDistanceY distance in y direction between adjacent pixels in mm \param principalPointX x coordinate of principal point on image plane in pixel \param principalPointY y coordinate of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ static ToFPoint3D IndexToCartesianCoordinatesWithInterpixdist(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength, ToFScalarType interPixelDistanceX, ToFScalarType interPixelDistanceY, ToFScalarType principalPointX, ToFScalarType principalPointY); /*! \brief Convert index based distances to cartesian coordinates \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ inline static ToFPoint3D IndexToCartesianCoordinatesWithInterpixdist(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength, ToFPoint2D interPixelDistance, ToFPoint2D principalPoint) { return IndexToCartesianCoordinatesWithInterpixdist(i,j,distance,focalLength,interPixelDistance[0],interPixelDistance[1],principalPoint[0],principalPoint[1]); } /*! \brief Convert index based distances to cartesian coordinates \param index index coordinates \param distance distance value at given index in mm \param focalLength focal length of optical system (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm for x and y direction \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ inline static ToFPoint3D IndexToCartesianCoordinatesWithInterpixdist(itk::Index<3> index, ToFScalarType distance, ToFScalarType focalLength, ToFPoint2D interPixelDistance, ToFPoint2D principalPoint) { return IndexToCartesianCoordinatesWithInterpixdist(index[0],index[1],distance,focalLength,interPixelDistance[0], interPixelDistance[1],principalPoint[0], principalPoint[1]); } /*! \brief Convenience method to convert index based distances to cartesian coordinates using array as input \param i index in x direction of image plane \param j index in y direction of image plane \param distance distance value at given index in mm \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm \param principalPoint coordinates of principal point on image plane in pixel \return cartesian coordinates for current index will be written here */ inline static ToFPoint3D IndexToCartesianCoordinatesWithInterpixdist(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength, ToFScalarType interPixelDistance[2], ToFScalarType principalPoint[2]) { return IndexToCartesianCoordinatesWithInterpixdist(i,j,distance,focalLength,interPixelDistance[0],interPixelDistance[1],principalPoint[0],principalPoint[1]); } /*! \brief Convert cartesian coordinates to index based distances \param cartesianPointX x coordinate of point (of a surface or point set) to convert in 3D coordinates \param cartesianPointY y coordinate of point (of a surface or point set) to convert in 3D coordinates \param cartesianPointZ z coordinate of point (of a surface or point set) to convert in 3D coordinates \param focalLengthX focal length of optical system in pixel units in x-direction (mostly obtained from camera calibration) \param focalLengthY focal length of optical system in pixel units in y-direction (mostly obtained from camera calibration) \param principalPointX x coordinate of principal point on image plane in pixel \param principalPointY y coordinate of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ static ToFPoint3D CartesianToIndexCoordinates(ToFScalarType cartesianPointX, ToFScalarType cartesianPointY,ToFScalarType cartesianPointZ, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY, bool calculateDistance=true); /*! \brief Convenience method to convert cartesian coordinates to index based distances using arrays \param cartesianPoint point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ inline static ToFPoint3D CartesianToIndexCoordinates(ToFScalarType cartesianPoint[3], ToFScalarType focalLength[2], ToFScalarType principalPoint[2], bool calculateDistance=true) { return CartesianToIndexCoordinates(cartesianPoint[0],cartesianPoint[1],cartesianPoint[2],focalLength[0], focalLength[1], principalPoint[0],principalPoint[1],calculateDistance); } /*! \brief Convert cartesian coordinates to index based distances \param cartesianPoint point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in pixel units (mostly obtained from camera calibration) \param principalPoint coordinates of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ inline static ToFPoint3D CartesianToIndexCoordinates(ToFPoint3D cartesianPoint, ToFPoint2D focalLength, ToFPoint2D principalPoint, bool calculateDistance=true) { return CartesianToIndexCoordinates(cartesianPoint[0],cartesianPoint[1],cartesianPoint[2],focalLength[0], focalLength[1], principalPoint[0],principalPoint[1],calculateDistance); } /*! \brief Convert cartesian coordinates to index based distances \param cartesianPointX x coordinate of point (of a surface or point set) to convert in 3D coordinates \param cartesianPointY y coordinate of point (of a surface or point set) to convert in 3D coordinates \param cartesianPointZ z coordinate of point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistanceX distance in x direction between adjacent pixels in mm \param interPixelDistanceY distance in y direction between adjacent pixels in mm \param principalPointX x coordinate of principal point on image plane in pixel \param principalPointY y coordinate of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ static ToFPoint3D CartesianToIndexCoordinatesWithInterpixdist(ToFScalarType cartesianPointX, ToFScalarType cartesianPointY,ToFScalarType cartesianPointZ, ToFScalarType focalLength, ToFScalarType interPixelDistanceX, ToFScalarType interPixelDistanceY, ToFScalarType principalPointX, ToFScalarType principalPointY, bool calculateDistance=true); /*! \brief Convenience method to convert cartesian coordinates to index based distances using arrays \param cartesianPoint point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm for x and y direction \param principalPoint coordinates of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ inline static ToFPoint3D CartesianToIndexCoordinatesWithInterpixdist(ToFScalarType cartesianPoint[3], ToFScalarType focalLength, ToFScalarType interPixelDistance[2], ToFScalarType principalPoint[2], bool calculateDistance=true) { return CartesianToIndexCoordinatesWithInterpixdist(cartesianPoint[0],cartesianPoint[1],cartesianPoint[2],focalLength, interPixelDistance[0],interPixelDistance[1],principalPoint[0],principalPoint[1],calculateDistance); } /*! \brief Convert cartesian coordinates to index based distances \param cartesianPoint point (of a surface or point set) to convert in 3D coordinates \param focalLength focal length of optical system in mm (mostly obtained from camera calibration) \param interPixelDistance distance between adjacent pixels in mm for x and y direction \param principalPoint coordinates of principal point on image plane in pixel \param calculateDistance if this flag is set, the distance value is stored in the z position of the output otherwise z=0 \return a ToFPoint3D. (int)ToFPoint3D[0]+0.5 and (int)ToFPoint3D[0]+0.5 will return the x and y index coordinates. ToFPoint3D[2] contains the distance value */ inline static ToFPoint3D CartesianToIndexCoordinatesWithInterpixdist(ToFPoint3D cartesianPoint, ToFScalarType focalLength, ToFPoint2D interPixelDistance, ToFPoint2D principalPoint, bool calculateDistance=true) { return CartesianToIndexCoordinatesWithInterpixdist(cartesianPoint[0],cartesianPoint[1],cartesianPoint[2],focalLength, interPixelDistance[0],interPixelDistance[1],principalPoint[0],principalPoint[1],calculateDistance); } /** \ingroup KinectReconstruction * @{ * * @brief KinectIndexToCartesianCoordinates Convert a pixel (i,j) with value d to a 3D world point. This conversion is meant for Kinect and slightly different then ToF reconstruction. See also "Hacking the Kinect" - Jeff Kramer, Matt Parker, Daniel Herrera C., Nicolas Burrus, Florian Echtler, Chapter 7, Part 1 "Moving from Depth Map to Point Cloud. * @param i Pixel index i. * @param j Pixel index j. * @param distance Distance value d in mm as obtained from OpenNI. * @param focalLengthX Focallength from calibration. * @param focalLengthY Focallength from calibration. * @param principalPointX Principal point from calibration. * @param principalPointY Principal point from calibration. * @return a ToFPoint3D. The point in world coordinates (mm). */ static ToFProcessingCommon::ToFPoint3D KinectIndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY); inline static ToFPoint3D KinectIndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFScalarType focalLength[2], ToFScalarType principalPoint[2]) { return KinectIndexToCartesianCoordinates(i,j,distance,focalLength[0],focalLength[1],principalPoint[0],principalPoint[1]); } inline static ToFPoint3D KinectIndexToCartesianCoordinates(unsigned int i, unsigned int j, ToFScalarType distance, ToFPoint2D focalLength, ToFPoint2D principalPoint) { return KinectIndexToCartesianCoordinates(i,j,distance,focalLength[0],focalLength[1],principalPoint[0],principalPoint[1]); } inline static ToFPoint3D KinectIndexToCartesianCoordinates(itk::Index<3> index, ToFScalarType distance, ToFPoint2D focalLength, ToFPoint2D principalPoint) { return KinectIndexToCartesianCoordinates(index[0],index[1],distance,focalLength[0],focalLength[1],principalPoint[0], principalPoint[1]); } /** @}*/ /** \ingroup KinectReconstructionInverse * @{ * @brief CartesianCoordinatesToKinectIndexCoordinates Transform a 3D world point back to distance image pixel coordinates. * @param cartesianPointX x value of the cartesian point. * @param cartesianPointY y value of the cartesian point. * @param cartesianPointZ z value of the cartesian point. * @param focalLengthX x value of the focal length (from calibration). * @param focalLengthY y value of the focal length (from calibration). * @param principalPointX x value of the principal point (from calibration). * @param principalPointY y value of the principal point (from calibration). * @param calculateDistance Do you want to compute also the distance of the distance image? For Kinect, this value is always the same in cartesian and index coordinates. * @return A ToFPoint3D containing the pixel indices (i,j) in [0] and [1] and (optionally) the distance value in [2] (or just 0.0). */ static ToFPoint3D CartesianToKinectIndexCoordinates(ToFScalarType cartesianPointX, ToFScalarType cartesianPointY, ToFScalarType cartesianPointZ, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY, bool calculateDistance=true); inline static ToFProcessingCommon::ToFPoint3D CartesianToKinectIndexCoordinates(ToFPoint3D cartesianPoint, ToFPoint2D focalLength, ToFPoint2D principalPoint, bool calculateDistance=true) { return CartesianToKinectIndexCoordinates( cartesianPoint[0], cartesianPoint[1], cartesianPoint[2], focalLength[0], focalLength[1], principalPoint[0], principalPoint[1], calculateDistance); } /** @}*/ /** * @brief ContinuousKinectIndexToCartesianCoordinates This method is escpially meant for reconstructing a Kinect point * with continuous index coordinates (i.e. not exactly a pixel position, but a point interpolated between two pixels). * The only difference to KinectIndexToCartesianCoordinates() is that ContinuousKinectIndexToCartesianCoordinates does not * cast to unsigned int for the index. * @param continuousIndex The continuous coordinates (e.g. 0.5; 0.5). * @param distance Distance value d in mm as obtained from OpenNI. * @param focalLengthX x value of the focal length (from calibration). * @param focalLengthY y value of the focal length (from calibration) * @param principalPointX x value of the principal point (from calibration). * @param principalPointY y value of the principal point (from calibration). * @return a ToFPoint3D. The point in world coordinates (mm). */ static ToFProcessingCommon::ToFPoint3D ContinuousKinectIndexToCartesianCoordinates(mitk::Point2D continuousIndex, ToFScalarType distance, ToFScalarType focalLengthX, ToFScalarType focalLengthY, ToFScalarType principalPointX, ToFScalarType principalPointY); /** \brief Calculates the horizontal view angle of the camera with the given intrinsics \param intrinsics intrinsic parameters of the camera \param dimX dimension of the image in horizontal direction angle = atan(principalPoint[0]/focalLength[0]) + atan((dimX-principalPoint[0]/focalLength[0])) **/ static ToFScalarType CalculateViewAngle(mitk::CameraIntrinsics::Pointer intrinsics, unsigned int dimX); }; } #endif diff --git a/Modules/ToFProcessing/mitkToFTestingCommon.h b/Modules/ToFProcessing/mitkToFTestingCommon.h index f3cfba9c30..90a7f33d1b 100644 --- a/Modules/ToFProcessing/mitkToFTestingCommon.h +++ b/Modules/ToFProcessing/mitkToFTestingCommon.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 mitkToFTestingCOMMON_H #define mitkToFTestingCOMMON_H #include -#include "mitkTypes.h" +#include "mitkNumericTypes.h" #include #include #include #include #include #include namespace mitk { class MitkToFProcessing_EXPORT ToFTestingCommon { public: /** * @brief PointSetsEqual Method two test if two point sets contain the same points. mitk::Equal is used for comparison of the points. * @param pointSet1 * @param pointSet2 * @return True if pointsets are equal. */ static bool PointSetsEqual(mitk::PointSet::Pointer pointSet1, mitk::PointSet::Pointer pointSet2) { bool pointSetsEqual = true; if (pointSet1->GetSize()==pointSet2->GetSize()) { for (int i=0; iGetSize(); i++) { mitk::Point3D expectedPoint = pointSet1->GetPoint(i); mitk::Point3D resultPoint = pointSet2->GetPoint(i); if (!mitk::Equal(expectedPoint,resultPoint)) { std::cout << std::endl; std::cout << std::setprecision(12) << "expected: " << expectedPoint; std::cout << std::endl; std::cout << std::setprecision(12) << "resultPoint: " << resultPoint; std::cout << std::endl; pointSetsEqual = false; } } } else { pointSetsEqual = false; MITK_INFO<<"Point sets have different size: "<GetSize()<<" vs. "<GetSize(); } return pointSetsEqual; } /** * @brief VtkPolyDatasEqual Convenience method for comparing the points of two vtkPolyData (using PointSetsEqual). * @param poly1 * @param poly2 * @return True if polydatas are equal. */ static bool VtkPolyDatasEqual( vtkSmartPointer poly1, vtkSmartPointer poly2 ) { return PointSetsEqual(VtkPolyDataToMitkPointSet(poly1), VtkPolyDataToMitkPointSet(poly2)); } /** * @brief VtkPolyDataToMitkPointSet Converts a vtkPolyData into an mitkPointSet * @param poly Input polydata. * @return mitk::PointSet::Pointer The resulting point set. */ static mitk::PointSet::Pointer VtkPolyDataToMitkPointSet( vtkSmartPointer poly ) { mitk::PointSet::Pointer result = mitk::PointSet::New(); int numberOfPoints = poly->GetNumberOfPoints(); for (int i=0; iGetPoint(i); mitk::Point3D point; point[0] = currentPoint[0]; point[1] = currentPoint[1]; point[2] = currentPoint[2]; result->InsertPoint(i,point); } return result; } }; } #endif diff --git a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h index 52c39e1490..7ddb753a10 100644 --- a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h +++ b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPart.h @@ -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. ===================================================================*/ #ifndef MITKIRENDERWINDOWPART_H #define MITKIRENDERWINDOWPART_H #include #include #include #include -#include +#include #include #include class QmitkRenderWindow; namespace mitk { struct IRenderingManager; class SliceNavigationController; /** * \ingroup org_mitk_gui_common * * \brief Interface for a MITK Workbench Part providing a render window. * * This interface allows generic access to Workbench parts which provide some * kind of render window. The interface is intended to be implemented by * subclasses of berry::IWorkbenchPart. Usually, the interface is implemented * by a Workbench editor. * * A IRenderWindowPart provides zero or more QmitkRenderWindow instances which can * be controlled via this interface. QmitkRenderWindow instances have an associated * \e id, which is implementation specific. However, implementations should consider * to use one of the following ids for certain QmitkRenderWindow instances to maximize * reusability (they are free to map multiple ids to one QmitkRenderWindow internally): *
    *
  • axial
  • *
  • sagittal
  • *
  • coronal
  • *
  • 3d
  • *
* * \see ILinkedRenderWindowPart * \see IRenderWindowPartListener * \see QmitkAbstractRenderEditor */ struct MITK_GUI_COMMON_PLUGIN IRenderWindowPart { static const QString DECORATION_BORDER; // = "border" static const QString DECORATION_LOGO; // = "logo" static const QString DECORATION_MENU; // = "menu" static const QString DECORATION_BACKGROUND; // = "background; virtual ~IRenderWindowPart(); /** * Get the currently active (focused) render window. * Focus handling is implementation specific. * * \return The active QmitkRenderWindow instance; NULL * if no render window is active. */ virtual QmitkRenderWindow* GetActiveQmitkRenderWindow() const = 0; /** * Get all render windows with their ids. * * \return A hash map mapping the render window id to the QmitkRenderWindow instance. */ virtual QHash GetQmitkRenderWindows() const = 0; /** * Get a render window with a specific id. * * \param id The render window id. * \return The QmitkRenderWindow instance for id */ virtual QmitkRenderWindow* GetQmitkRenderWindow(const QString& id) const = 0; /** * Get the rendering manager used by this render window part. * * \return The current IRenderingManager instance or NULL * if no rendering manager is used. */ virtual mitk::IRenderingManager* GetRenderingManager() const = 0; /** * Request an update of all render windows. * * \param requestType Specifies the type of render windows for which an update * will be requested. */ virtual void RequestUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL) = 0; /** * Force an immediate update of all render windows. * * \param requestType Specifies the type of render windows for which an immediate update * will be requested. */ virtual void ForceImmediateUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL) = 0; /** * Get the SliceNavigationController for controlling time positions. * * \return A SliceNavigationController if the render window supports this * operation; otherwise returns NULL. */ virtual mitk::SliceNavigationController* GetTimeNavigationController() const = 0; /** * Get the selected position in the render window with id id * or in the active render window if id is NULL. * * \param id The render window id. * \return The currently selected position in world coordinates. */ virtual mitk::Point3D GetSelectedPosition(const QString& id = QString()) const = 0; /** * Set the selected position in the render window with id id * or in the active render window if id is NULL. * * \param pos The position in world coordinates which should be selected. * \param id The render window id in which the selection should take place. */ virtual void SetSelectedPosition(const mitk::Point3D& pos, const QString& id = QString()) = 0; /** * Enable \e decorations like colored borders, menu widgets, logos, text annotations, etc. * * Decorations are implementation specific. A set of standardized decoration names is listed * in GetDecorations(). * * \param enable If true enable the decorations specified in decorations, * otherwise disable them. * \param decorations A list of decoration names. If empty, all supported decorations are affected. * * \see GetDecorations() */ virtual void EnableDecorations(bool enable, const QStringList& decorations = QStringList()) = 0; /** * Return if a specific decoration is enabled. * * \return true if the decoration is enabled, false if it is disabled * or unknown. * * \see GetDecorations() */ virtual bool IsDecorationEnabled(const QString& decoration) const = 0; /** * Get a list of supported decorations. * * The following decoration names are standardized and should not be used for other decoration types: *
    *
  • \e DECORATION_BORDER Any border decorations like colored rectangles, etc. *
  • \e DECORATION_MENU Menus associated with render windows *
  • \e DECORATION_BACKGROUND All kinds of backgrounds (patterns, gradients, etc.) except for solid colored backgrounds *
  • \e DECORATION_LOGO Any kind of logo overlayed on the rendered scene *
* * \return A list of supported decoration names. */ virtual QStringList GetDecorations() const = 0; }; } Q_DECLARE_INTERFACE(mitk::IRenderWindowPart, "org.mitk.ui.IRenderWindowPart") #endif // MITKIRENDERWINDOWPART_H