diff --git a/Modules/Core/include/mitkAbstractFileReader.h b/Modules/Core/include/mitkAbstractFileReader.h index 7b61ca5b32..310ad06fda 100644 --- a/Modules/Core/include/mitkAbstractFileReader.h +++ b/Modules/Core/include/mitkAbstractFileReader.h @@ -1,243 +1,243 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef AbstractFileReader_H_HEADER_INCLUDED_C1E7E521 #define AbstractFileReader_H_HEADER_INCLUDED_C1E7E521 // Macro #include // MITK #include #include #include // Microservices #include #include #include namespace us { struct PrototypeServiceFactory; } namespace mitk { class CustomMimeType; /** * @brief Base class for creating mitk::BaseData objects from files or streams. * @ingroup IO */ class MITKCORE_EXPORT AbstractFileReader : public mitk::IFileReader { public: void SetInput(const std::string &location) override; void SetInput(const std::string &location, std::istream *is) override; std::string GetInputLocation() const override; std::istream *GetInputStream() const override; MimeType GetRegisteredMimeType() const; /** * @brief Reads a path or stream and creates a list of BaseData objects. * * The default implementation of this method (1) calls DoRead() - * (Implement the specific reader operation there) and (2) it addes general + * (Implement the specific reader operation there) and (2) it adds general * meta information about the loading process. */ std::vector> Read() override; DataStorage::SetOfObjects::Pointer Read(mitk::DataStorage &ds) override; ConfidenceLevel GetConfidenceLevel() const override; Options GetOptions() const override; us::Any GetOption(const std::string &name) const override; void SetOptions(const Options &options) override; void SetOption(const std::string &name, const us::Any &value) override; void AddProgressCallback(const ProgressCallback &callback) override; void RemoveProgressCallback(const ProgressCallback &callback) override; /** * Associate this reader with the MIME type returned by the current IMimeTypeProvider * service for the provided extension if the MIME type exists, otherwise registers * a new MIME type when RegisterService() is called. * * If no MIME type for \c extension is already registered, a call to RegisterService() * will register a new MIME type and associate this reader instance with it. The MIME * type id can be set via SetMimeType() or it will be auto-generated using \c extension, * having the form "application/vnd.mitk.". * * @param context */ us::ServiceRegistration RegisterService(us::ModuleContext *context = us::GetModuleContext()); void UnregisterService(); /** * @return A list of files that were loaded during the last call of Read. Has to be filled by the actual reader class. */ std::vector< std::string > GetReadFiles() override; void SetProperties(const PropertyList* properties) override; protected: /** * @brief An input stream wrapper. * * If a reader can only work with input streams, use an instance * of this class to either wrap the specified input stream or * create a new input stream based on the input location in the * file system. */ class MITKCORE_EXPORT InputStream : public std::istream { public: InputStream(IFileReader *writer, std::ios_base::openmode mode = std::ios_base::in); ~InputStream() override; private: std::istream *m_Stream; }; AbstractFileReader(); ~AbstractFileReader() override; AbstractFileReader(const AbstractFileReader &other); /** * Associate this reader instance with the given MIME type. * * If \c mimeType does not provide an extension list, an already * registered mime-type object is used. Otherwise, the first entry in * the extensions list is used to construct a mime-type name and * register it as a new CustomMimeType service object in the default * implementation of RegisterMimeType(). * * @param mimeType The mime type this reader can read. * @param description A human readable description of this reader. * * @throws std::invalid_argument if \c mimeType is empty. * * @see RegisterService */ explicit AbstractFileReader(const CustomMimeType &mimeType, const std::string &description); /** Method that should be implemented by derived classes and does the real loading. * This method is called by Read(). * This method must be implemented for each specific reader. Call * GetInputStream() first and check for a non-null stream to read from. * If the input stream is \c nullptr, use GetInputLocation() to read from a local * file-system path. * * If the reader cannot use streams directly, use GetLocalFileName() instead. * * @return The created BaseData objects. * @throws mitk::Exception * * @see GetLocalFileName() * @see IFileReader::Read() */ virtual std::vector> DoRead() = 0; virtual us::ServiceProperties GetServiceProperties() const; /** * Registers a new CustomMimeType service object. * * This method is called from RegisterService and the default implementation * registers a new mime-type service object if all of the following conditions * are true: * * - TODO * * @param context * @return * @throws std::invalid_argument if \c context is nullptr. */ virtual us::ServiceRegistration RegisterMimeType(us::ModuleContext *context); void SetMimeType(const CustomMimeType &mimeType); /** * @return The mime-type this reader can handle. */ const CustomMimeType *GetMimeType() const; void SetMimeTypePrefix(const std::string &prefix); std::string GetMimeTypePrefix() const; void SetDescription(const std::string &description); std::string GetDescription() const; void SetDefaultOptions(const Options &defaultOptions); Options GetDefaultOptions() const; /** * \brief Set the service ranking for this file reader. * * Default is zero and should only be chosen differently for a reason. * The ranking is used to determine which reader to use if several * equivalent readers have been found. * It may be used to replace a default reader from MITK in your own project. * E.g. if you want to use your own reader for nrrd files instead of the default, * implement it and give it a higher ranking than zero. */ void SetRanking(int ranking); int GetRanking() const; /** * @brief Get a local file name for reading. * * This is a convenience method for readers which cannot work natively * with input streams. If no input stream has been been set, * this method just returns the result of GetLocation(). However, if * SetLocation(std::string, std::istream*) has been called with a non-null * input stream, this method writes the contents of the stream to a temporary * file and returns the name of the temporary file. * * The temporary file is deleted when either SetLocation(std::string, std::istream*) * is called again with a different input stream or the destructor of this * class is called. * * This method does not validate file names set via SetInput(std::string). * * @return A file path in the local file-system for reading. */ std::string GetLocalFileName() const; virtual void SetDefaultDataNodeProperties(DataNode *node, const std::string &filePath); const PropertyList* GetProperties() const override; std::vector< std::string > m_ReadFiles; private: AbstractFileReader &operator=(const AbstractFileReader &other); virtual mitk::IFileReader *Clone() const = 0; class Impl; std::unique_ptr d; }; } // namespace mitk #endif /* AbstractFileReader_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Modules/Core/include/mitkAbstractFileWriter.h b/Modules/Core/include/mitkAbstractFileWriter.h index e8a64a2572..4bd26b552a 100644 --- a/Modules/Core/include/mitkAbstractFileWriter.h +++ b/Modules/Core/include/mitkAbstractFileWriter.h @@ -1,226 +1,226 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef AbstractFileWriter_H_HEADER_INCLUDED_C1E7E521 #define AbstractFileWriter_H_HEADER_INCLUDED_C1E7E521 // Macro #include // MITK #include #include // Microservices #include #include #include #include namespace us { struct PrototypeServiceFactory; } namespace mitk { class CustomMimeType; /** * @brief Base class for writing mitk::BaseData objects to files or streams. * * In general, all file writers should derive from this class, this way it is - * made sure that the new implementation is - * exposed to the Microservice-Framework and that is automatically available troughout MITK. + * made sure that the new implementation is exposed to the + * Microservice-Framework and that is automatically available throughout MITK. * The default implementation only requires one Write() * method and the Clone() method to be implemented. * * @ingroup IO */ class MITKCORE_EXPORT AbstractFileWriter : public mitk::IFileWriter { public: void SetInput(const BaseData *data) override; const BaseData *GetInput() const override; void SetOutputLocation(const std::string &location) override; std::string GetOutputLocation() const override; void SetOutputStream(const std::string &location, std::ostream *os) override; std::ostream *GetOutputStream() const override; /** * \brief Write the base data to the specified location or output stream. * * This method must be implemented for each specific writer. Call * GetOutputStream() first and check for a non-null stream to write to. * If the output stream is \c nullptr, use GetOutputLocation() to write * to a local file-system path. * * If the reader cannot use streams directly, use GetLocalFile() to retrieve * a temporary local file name instead. * * \throws mitk::Exception * * \see GetLocalFile() * \see IFileWriter::Write() */ void Write() override = 0; ConfidenceLevel GetConfidenceLevel() const override; MimeType GetRegisteredMimeType() const; Options GetOptions() const override; us::Any GetOption(const std::string &name) const override; void SetOptions(const Options &options) override; void SetOption(const std::string &name, const us::Any &value) override; void AddProgressCallback(const ProgressCallback &callback) override; void RemoveProgressCallback(const ProgressCallback &callback) override; us::ServiceRegistration RegisterService(us::ModuleContext *context = us::GetModuleContext()); void UnregisterService(); protected: /** * @brief A local file representation for streams. * * If a writer can only work with local files, use an instance * of this class to get either a temporary file name for writing * to the specified output stream or the original output location * if no output stream was set. */ class MITKCORE_EXPORT LocalFile { public: LocalFile(IFileWriter *writer); // Writes to the ostream and removes the temporary file ~LocalFile(); // Creates a temporary file for output operations. std::string GetFileName(); private: // disabled LocalFile(); LocalFile(const LocalFile &); LocalFile &operator=(const LocalFile &other); struct Impl; std::unique_ptr d; }; /** * @brief An output stream wrapper. * * If a writer can only work with output streams, use an instance * of this class to either wrap the specified output stream or * create a new output stream based on the output location in the * file system. */ class MITKCORE_EXPORT OutputStream : public std::ostream { public: OutputStream(IFileWriter *writer, std::ios_base::openmode mode = std::ios_base::trunc | std::ios_base::out); ~OutputStream() override; private: std::ostream *m_Stream; }; ~AbstractFileWriter() override; AbstractFileWriter(const AbstractFileWriter &other); AbstractFileWriter(const std::string &baseDataType); AbstractFileWriter(const std::string &baseDataType, const CustomMimeType &mimeType, const std::string &description); virtual us::ServiceProperties GetServiceProperties() const; /** * Registers a new CustomMimeType service object. * * This method is called from RegisterService and the default implementation * registers a new mime-type service object if all of the following conditions * are true: * * - TODO * * @param context * @return * @throws std::invalid_argument if \c context is nullptr. */ virtual us::ServiceRegistration RegisterMimeType(us::ModuleContext *context); void SetMimeType(const CustomMimeType &mimeType); /** * @return Get the mime-type this writer can handle. */ const CustomMimeType *GetMimeType() const; void SetMimeTypePrefix(const std::string &prefix); std::string GetMimeTypePrefix() const; /** * \brief Sets a human readable description of this writer. * * This will be used in file dialogs for example. */ void SetDescription(const std::string &description); std::string GetDescription() const; void SetDefaultOptions(const Options &defaultOptions); Options GetDefaultOptions() const; /** * \brief Set the service ranking for this file writer. * * Default is zero and should only be chosen differently for a reason. * The ranking is used to determine which writer to use if several * equivalent writers have been found. * It may be used to replace a default writer from MITK in your own project. * E.g. if you want to use your own writer for nrrd files instead of the default, * implement it and give it a higher ranking than zero. */ void SetRanking(int ranking); int GetRanking() const; /** * \brief Sets the name of the mitk::Basedata that this writer is able to handle. * * The correct value is the one given as the first parameter in the mitkNewMacro of that BaseData derivate. * You can also retrieve it by calling GetNameOfClass() on an instance of said data. */ void SetBaseDataType(const std::string &baseDataType); virtual std::string GetBaseDataType() const; void ValidateOutputLocation() const; private: AbstractFileWriter &operator=(const AbstractFileWriter &other); virtual mitk::IFileWriter *Clone() const = 0; class Impl; std::unique_ptr d; }; } // namespace mitk #endif /* AbstractFileWriter_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Modules/Core/include/mitkAnnotation.h b/Modules/Core/include/mitkAnnotation.h index 91b86cf65f..5b74b463da 100644 --- a/Modules/Core/include/mitkAnnotation.h +++ b/Modules/Core/include/mitkAnnotation.h @@ -1,458 +1,458 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef Annotation_H #define Annotation_H #include "mitkServiceInterface.h" #include "usServiceRegistration.h" #include #include #include namespace mitk { /** \brief Base class for all Annotation * This class is to be implemented in order to create Annotation which are managed by a AbstractAnnotationRenderer. * This class contains an internal Propertylist for configuring the appearance of the implemented Overlay. */ class MITKCORE_EXPORT Annotation : public itk::Object { public: /** \brief Container for position and size on the display.*/ struct Bounds { itk::Point Position; itk::Point Size; }; - /** \brief Base class for mapper specific rendering ressources. + /** \brief Base class for mapper specific rendering resources. */ class MITKCORE_EXPORT BaseLocalStorage { public: bool IsGenerateDataRequired(mitk::BaseRenderer *renderer, mitk::Annotation *Annotation); inline void UpdateGenerateDataTime() { m_LastGenerateDataTime.Modified(); } inline itk::TimeStamp &GetLastGenerateDataTime() { return m_LastGenerateDataTime; } protected: /** \brief timestamp of last update of stored data */ itk::TimeStamp m_LastGenerateDataTime; }; /** * @brief Set the property (instance of BaseProperty) with key @a propertyKey in the PropertyList * of the @a renderer (if nullptr, use BaseRenderer-independent PropertyList). This is set-by-value. * * @warning Change in semantics since Aug 25th 2006. Check your usage of this method if you do * more with properties than just call SetProperty( "key", new SomeProperty("value") ). * * @sa GetProperty * @sa m_PropertyList * @sa m_MapOfPropertyLists */ void SetProperty(const std::string &propertyKey, const BaseProperty::Pointer &property); /** * @brief Replace the property (instance of BaseProperty) with key @a propertyKey in the PropertyList * of the @a renderer (if nullptr, use BaseRenderer-independent PropertyList). This is set-by-reference. * * If @a renderer is @a nullptr the property is set in the BaseRenderer-independent * PropertyList of this Annotation. * @sa GetProperty * @sa m_PropertyList * @sa m_MapOfPropertyLists */ void ReplaceProperty(const std::string &propertyKey, const BaseProperty::Pointer &property); /** * @brief Add the property (instance of BaseProperty) if it does * not exist (or always if \a overwrite is \a true) * with key @a propertyKey in the PropertyList * of the @a renderer (if nullptr, use BaseRenderer-independent * PropertyList). This is set-by-value. * * For \a overwrite == \a false the property is \em not changed * if it already exists. For \a overwrite == \a true the method * is identical to SetProperty. * * @sa SetProperty * @sa GetProperty * @sa m_PropertyList * @sa m_MapOfPropertyLists */ void AddProperty(const std::string &propertyKey, const BaseProperty::Pointer &property, bool overwrite = false); /** * @brief Add values from another PropertyList. * * Overwrites values in m_PropertyList only when possible (i.e. when types are compatible). * If you want to allow for object type changes (replacing a "visible":BoolProperty with "visible":IntProperty, * set \c replace. * * @param pList * @param replace true: if \c pList contains a property "visible" of type ColorProperty and our m_PropertyList * also has a "visible" property of a different type (e.g. BoolProperty), change the type, i.e. replace the objects * behind the pointer. * * @sa SetProperty * @sa ReplaceProperty * @sa m_PropertyList */ void ConcatenatePropertyList(PropertyList *pList, bool replace = false); /** * @brief Get the property (instance of BaseProperty) with key @a propertyKey from the PropertyList * of the @a renderer, if available there, otherwise use the BaseRenderer-independent PropertyList. * * If @a renderer is @a nullptr or the @a propertyKey cannot be found * in the PropertyList specific to @a renderer or is disabled there, the BaseRenderer-independent * PropertyList of this Annotation is queried. * @sa GetPropertyList * @sa m_PropertyList * @sa m_MapOfPropertyLists */ mitk::BaseProperty *GetProperty(const std::string &propertyKey) const; /** * @brief Get the property of type T with key @a propertyKey from the PropertyList * of the @a renderer, if available there, otherwise use the BaseRenderer-independent PropertyList. * * If @a renderer is @a nullptr or the @a propertyKey cannot be found * in the PropertyList specific to @a renderer or is disabled there, the BaseRenderer-independent * PropertyList of this Annotation is queried. * @sa GetPropertyList * @sa m_PropertyList * @sa m_MapOfPropertyLists */ template bool GetProperty(itk::SmartPointer &property, const std::string &propertyKey) const { property = dynamic_cast(GetProperty(propertyKey)); return property.IsNotNull(); } /** * @brief Get the property of type T with key @a propertyKey from the PropertyList * of the @a renderer, if available there, otherwise use the BaseRenderer-independent PropertyList. * * If @a renderer is @a nullptr or the @a propertyKey cannot be found * in the PropertyList specific to @a renderer or is disabled there, the BaseRenderer-independent * PropertyList of this Annotation is queried. * @sa GetPropertyList * @sa m_PropertyList * @sa m_MapOfPropertyLists */ template bool GetProperty(T *&property, const std::string &propertyKey) const { property = dynamic_cast(GetProperty(propertyKey)); return property != nullptr; } /** * @brief Convenience access method for GenericProperty properties * (T being the type of the second parameter) * @return @a true property was found */ template bool GetPropertyValue(const std::string &propertyKey, T &value) const { GenericProperty *gp = dynamic_cast *>(GetProperty(propertyKey)); if (gp != nullptr) { value = gp->GetValue(); return true; } return false; } /** * @brief Convenience access method for bool properties (instances of * BoolProperty) * @return @a true property was found */ bool GetBoolProperty(const std::string &propertyKey, bool &boolValue) const; /** * @brief Convenience access method for int properties (instances of * IntProperty) * @return @a true property was found */ bool GetIntProperty(const std::string &propertyKey, int &intValue) const; /** * @brief Convenience access method for float properties (instances of * FloatProperty) * @return @a true property was found */ bool GetFloatProperty(const std::string &propertyKey, float &floatValue) const; /** * @brief Convenience access method for double properties (instances of * DoubleProperty) * @return @a true property was found */ bool GetDoubleProperty(const std::string &propertyKey, double &doubleValue) const; /** * @brief Convenience access method for string properties (instances of * StringProperty) * @return @a true property was found */ bool GetStringProperty(const std::string &propertyKey, std::string &string) const; /** * @brief Convenience method for setting int properties (instances of * IntProperty) */ void SetIntProperty(const std::string &propertyKey, int intValue); /** * @brief Convenience method for setting int properties (instances of * IntProperty) */ void SetBoolProperty(const std::string &propertyKey, bool boolValue); /** * @brief Convenience method for setting int properties (instances of * IntProperty) */ void SetFloatProperty(const std::string &propertyKey, float floatValue); /** * @brief Convenience method for setting int properties (instances of * IntProperty) */ void SetDoubleProperty(const std::string &propertyKey, double doubleValue); /** * @brief Convenience method for setting int properties (instances of * IntProperty) */ void SetStringProperty(const std::string &propertyKey, const std::string &string); /** * @brief Convenience access method for boolean properties (instances * of BoolProperty). Return value is the value of the property. If the property is * not found, the value of @a defaultIsOn is returned. * * Thus, the return value has a different meaning than in the * GetBoolProperty method! * @sa GetBoolProperty */ bool IsOn(const std::string &propertyKey, bool defaultIsOn = true) const { GetBoolProperty(propertyKey, defaultIsOn); return defaultIsOn; } /** * @brief Convenience access method for accessing the name of an object (instance of * StringProperty with property-key "name") * @return @a true property was found */ bool GetName(std::string &nodeName, const std::string &propertyKey = "name") const; /** * @brief Extra convenience access method for accessing the name of an object (instance of * StringProperty with property-key "name"). * * This method does not take the renderer specific * propertylists into account, because the name of an object should never be renderer specific. * @returns a std::string with the name of the object (content of "name" Property). * If there is no "name" Property, an empty string will be returned. */ virtual std::string GetName() const; /** * @brief Extra convenience access method to set the name of an object. * * The name will be stored in the non-renderer-specific PropertyList in a StringProperty named "name". */ virtual void SetName(const std::string &name); /** * @brief Convenience access method for color properties (instances of * ColorProperty) * @return @a true property was found */ bool GetColor(float rgb[], const std::string &propertyKey = "color") const; /** * @brief Convenience method for setting color properties (instances of * ColorProperty) */ void SetColor(const mitk::Color &color, const std::string &propertyKey = "color"); /** * @brief Convenience method for setting color properties (instances of * ColorProperty) */ void SetColor(float red, float green, float blue, const std::string &propertyKey = "color"); /** * @brief Convenience method for setting color properties (instances of * ColorProperty) */ void SetColor(const float rgb[], const std::string &propertyKey = "color"); /** * @brief Convenience access method for opacity properties (instances of * FloatProperty) * @return @a true property was found */ bool GetOpacity(float &opacity, const std::string &propertyKey = "opacity") const; /** * @brief Convenience method for setting opacity properties (instances of * FloatProperty) */ void SetOpacity(float opacity, const std::string &propertyKey = "opacity"); void SetText(std::string text); std::string GetText() const; void SetFontSize(int fontSize); int GetFontSize() const; /** * @brief Convenience access method for visibility properties (instances * of BoolProperty with property-key "visible") * @return @a true property was found * @sa IsVisible */ bool GetVisibility(bool &visible, const std::string &propertyKey = "visible") const; /** * @brief Convenience access method for visibility properties (instances * of BoolProperty). Return value is the visibility. Default is * visible==true, i.e., true is returned even if the property (@a * propertyKey) is not found. * * Thus, the return value has a different meaning than in the * GetVisibility method! * @sa GetVisibility * @sa IsOn */ bool IsVisible(const std::string &propertyKey = "visible", bool defaultIsOn = true) const; /** * @brief Convenience method for setting visibility properties (instances * of BoolProperty) * @param visible If set to true, the data will be rendered. If false, the render will skip this data. - * @param propertyKey Can be used to specify a user defined name of the visibility propery. + * @param propertyKey Can be used to specify a user defined name of the visibility property. */ void SetVisibility(bool visible, const std::string &propertyKey = "visible"); /** \brief Adds the Annotation to the specified renderer. Update Annotation should be called soon in order to apply * all * properties*/ virtual void AddToBaseRenderer(BaseRenderer *renderer) = 0; /** \brief Adds the Annotation to the specified renderer. Update Annotation should be called soon in order to apply * all * properties*/ virtual void AddToRenderer(BaseRenderer *renderer, vtkRenderer *vtkrenderer) = 0; /** \brief Removes the Annotation from the specified renderer. It is not visible anymore then.*/ virtual void RemoveFromBaseRenderer(BaseRenderer *renderer) = 0; /** \brief Removes the Annotation from the specified renderer. It is not visible anymore then.*/ virtual void RemoveFromRenderer(BaseRenderer *renderer, vtkRenderer *vtkrenderer) = 0; /** \brief Applies all properties and should be called before the rendering procedure.*/ virtual void Update(BaseRenderer *renderer) = 0; /** \brief Returns position and size of the Annotation on the display.*/ virtual Bounds GetBoundsOnDisplay(BaseRenderer *renderer) const; /** \brief Sets position and size of the Annotation on the display.*/ virtual void SetBoundsOnDisplay(BaseRenderer *renderer, const Bounds &); void SetForceInForeground(bool forceForeground); bool IsForceInForeground() const; PropertyList *GetPropertyList() const; /** *\brief Returns the id that this device is registered with. The id will only be valid, if the * Annotation has been registered using RegisterAsMicroservice(). */ std::string GetMicroserviceID(); /** *\brief These Constants are used in conjunction with Microservices */ static const std::string US_INTERFACE_NAME; static const std::string US_PROPKEY_AnnotationNAME; static const std::string US_PROPKEY_ID; static const std::string US_PROPKEY_MODIFIED; static const std::string US_PROPKEY_RENDERER_ID; static const std::string US_PROPKEY_AR_ID; /** *\brief Registers this object as a Microservice, making it available to every module and/or plugin. * To unregister, call UnregisterMicroservice(). */ virtual void RegisterAsMicroservice(us::ServiceProperties props); /** *\brief Registers this object as a Microservice, making it available to every module and/or plugin. */ virtual void UnRegisterMicroservice(); void AnnotationModified(); mitkClassMacroItkParent(Annotation, itk::Object); protected: /** \brief explicit constructor which disallows implicit conversions */ Annotation(); /** \brief virtual destructor in order to derive from this class */ ~Annotation() override; /** * @brief BaseRenderer-independent PropertyList * * Properties herein can be overwritten specifically for each BaseRenderer * by the BaseRenderer-specific properties defined in m_MapOfPropertyLists. */ PropertyList::Pointer m_PropertyList; /** * @brief Timestamp of the last change of m_Data */ itk::TimeStamp m_DataReferenceChangedTime; void SetUSProperty(const std::string &propertyKey, us::Any value); private: /** \brief render this Annotation on a foreground renderer */ bool m_ForceInForeground; /** \brief copy constructor */ Annotation(const Annotation &); /** \brief assignment operator */ Annotation &operator=(const Annotation &); private: us::ServiceRegistration m_ServiceRegistration; unsigned long m_PropertyListModifiedObserverTag; void PropertyListModified(const itk::Object *, const itk::EventObject &); }; } // namespace mitk MITK_DECLARE_SERVICE_INTERFACE(mitk::Annotation, "org.mitk.services.Annotation") #endif // Annotation_H diff --git a/Modules/Core/include/mitkApplicationCursor.h b/Modules/Core/include/mitkApplicationCursor.h index 349c24cce2..da717dde90 100644 --- a/Modules/Core/include/mitkApplicationCursor.h +++ b/Modules/Core/include/mitkApplicationCursor.h @@ -1,96 +1,96 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITK_APPLICATION_CURSOR_H_DEFINED_AND_ALL_IS_GOOD #define MITK_APPLICATION_CURSOR_H_DEFINED_AND_ALL_IS_GOOD #include "mitkNumericTypes.h" #include 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 + be registered with mitk::ApplicationCursor. See the (very simple) implementation of QmitkApplicationCursor for an example. */ class MITKCORE_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 MITKCORE_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/Modules/Core/include/mitkArbitraryTimeGeometry.h b/Modules/Core/include/mitkArbitraryTimeGeometry.h index 9b82658e8a..0ad9797125 100644 --- a/Modules/Core/include/mitkArbitraryTimeGeometry.h +++ b/Modules/Core/include/mitkArbitraryTimeGeometry.h @@ -1,252 +1,252 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef ArbitraryTimeGeometry_h #define ArbitraryTimeGeometry_h //MITK #include #include #include namespace mitk { /** * \brief Organizes geometries over arbitrary defined time steps * * For this TimeGeometry implementation it is assumed that * the durations of the time steps are arbitrary and may differ. * The geometries of the time steps are independent, * and not linked to each other. Since the timeBounds of the * geometries are different for each time step it is not possible * to set the same geometry to different time steps. Instead * copies should be used. * @remark The lower time bound of a succeeding time step may not be smaller * than the upper time bound of its predecessor. Thus the list of time points is * always sorted by its lower time bounds. * @remark For the conversion between time step and time point the following assumption * is used.:\n * time step -> time point: time point is the lower time bound of the geometry indicated by step.\n * time point -> time step: associated time step is last step which lower time bound is smaller or equal then the time * point. * * \addtogroup geometry */ class MITKCORE_EXPORT ArbitraryTimeGeometry : public TimeGeometry { public: mitkClassMacro(ArbitraryTimeGeometry, TimeGeometry); ArbitraryTimeGeometry(); typedef ArbitraryTimeGeometry self; itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * \brief Returns the number of time steps. * * Returns the number of time steps for which * geometries are saved. The number of time steps * is also the upper bound of the time steps. The * minimum time steps is always 0. */ TimeStepType CountTimeSteps() const override; /** * \brief Returns the first time point for which the time geometry instance is valid. * * Returns the first valid time point for this geometry. It is the lower time bound of * the first step. The time point is given in ms. */ TimePointType GetMinimumTimePoint() const override; /** * \brief Returns the last time point for which the time geometry instance is valid * * Gives the last time point for which a valid geometry is saved in * this time geometry. It is the upper time bound of the last step. * The time point is given in ms. */ TimePointType GetMaximumTimePoint() const override; /** * \brief Returns the first time point for which the time geometry instance is valid. * * Returns the first valid time point for the given TimeStep. The time point * is given in ms. */ TimePointType GetMinimumTimePoint(TimeStepType step) const override; /** * \brief Returns the last time point for which the time geometry instance is valid * * Gives the last time point for the Geometry specified by the given TimeStep. The time point is given in ms. */ TimePointType GetMaximumTimePoint(TimeStepType step) const override; /** * \brief Get the time bounds (in ms) * it returns GetMinimumTimePoint() and GetMaximumTimePoint() results as bounds. */ TimeBounds GetTimeBounds() const override; /** * \brief Get the time bounds for the given TimeStep (in ms) */ TimeBounds GetTimeBounds(TimeStepType step) const override; /** * \brief Tests if a given time point is covered by this time geometry instance * * Returns true if a geometry can be returned for the given time * point (so it is within GetTimeBounds() and fails if not. * The time point must be given in ms. */ bool IsValidTimePoint(TimePointType timePoint) const override; /** - * \brief Test for the given time step if a geometry is availible + * \brief Test for the given time step if a geometry is available * * Returns true if a geometry is defined for the given time step. * Otherwise false is returned. - * The time step is defined as positiv number. + * The time step is defined as positive number. */ bool IsValidTimeStep(TimeStepType timeStep) const override; /** * \brief Converts a time step to a time point * * Converts a time step to a time point by using the time steps lower * time bound. * If the original time steps does not point to a valid geometry, * a time point is calculated that also does not point to a valid * geometry, but no exception is raised. */ TimePointType TimeStepToTimePoint(TimeStepType timeStep) const override; /** * \brief Converts a time point to the corresponding time step * * Converts a time point to a time step in a way that * the new time step indicates the same geometry as the time point. * The associated time step is the last step which lower time bound * is smaller or equal then the time point. * If a negative invalid time point is given always time step 0 is * returned. If a positive invalid time point is given the last time * step will be returned. This is also true for time points that are * exactly on the upper time bound (the only exception is the final * time step in case that HasCollapsedFinalTimeStep() is true). */ TimeStepType TimePointToTimeStep(TimePointType timePoint) const override; /** * \brief Returns the geometry which corresponds to the given time step * * Returns a clone of the geometry which defines the given time step. If * the given time step is invalid an null-pointer is returned. */ BaseGeometry::Pointer GetGeometryCloneForTimeStep(TimeStepType timeStep) const override; /** * \brief Returns the geometry which corresponds to the given time point * * Returns the geometry which defines the given time point. If * the given time point is invalid an null-pointer is returned. * * If the returned geometry is changed this will affect the saved * geometry. */ BaseGeometry::Pointer GetGeometryForTimePoint(TimePointType timePoint) const override; /** * \brief Returns the geometry which corresponds to the given time step * * Returns the geometry which defines the given time step. If * the given time step is invalid an null-pointer is returned. * * If the returned geometry is changed this will affect the saved * geometry. */ BaseGeometry::Pointer GetGeometryForTimeStep(TimeStepType timeStep) const override; /** - * \brief Tests if all necessary informations are set and the object is valid + * \brief Tests if all necessary information are set and the object is valid */ bool IsValid() const override; /** * \brief Initializes a new object with one time steps which contains an empty geometry. */ void Initialize() override; /** * \brief Expands the time geometry to the given number of time steps. * * Initializes the new time steps with empty geometries. This default geometries will behave like * ProportionalTimeGeometry. * Shrinking is not supported. The new steps will have the same duration like the last step before extension. */ void Expand(TimeStepType size) override; /** * \brief Replaces the geometry instances with clones of the passed geometry. * * Replaces the geometries of all time steps with clones of the passed * geometry. Replacement strategy depends on the implementation of TimeGeometry * sub class. * @remark The time points itself stays untouched. Use this method if you want * to change the spatial properties of a TimeGeometry and preserve the time * "grid". */ void ReplaceTimeStepGeometries(const BaseGeometry *geometry) override; /** * \brief Sets the geometry for the given time step * * If passed time step is not valid. Nothing will be changed. * @pre geometry must point to a valid instance. */ void SetTimeStepGeometry(BaseGeometry *geometry, TimeStepType timeStep) override; /** * \brief Makes a deep copy of the current object */ itk::LightObject::Pointer InternalClone() const override; void ClearAllGeometries(); /** Append the passed geometry to the time geometry. * @pre The passed geometry pointer must be valid. * @pre The minimumTimePoint must not be smaller than the maximum time point of the currently last time step. * Therefore time steps must not be overlapping in time. * @pre minimumTimePoint must not be larger then maximumTimePoint.*/ void AppendNewTimeStep(BaseGeometry *geometry, TimePointType minimumTimePoint, TimePointType maximumTimePoint); /** Same than AppendNewTimeStep. But clones geometry before adding it.*/ void AppendNewTimeStepClone(const BaseGeometry* geometry, TimePointType minimumTimePoint, TimePointType maximumTimePoint ); void ReserveSpaceForGeometries( TimeStepType numberOfGeometries ); void PrintSelf(std::ostream &os, itk::Indent indent) const override; - /** This is a helper that indicates problematic corner cases that often occure e.g. when loading + /** This is a helper that indicates problematic corner cases that often occur e.g. when loading dynamic DICOM data. There the final time step is collapsed as min time bound and max time bound have the same value. For a more detailed explanation why it happens please see: https://phabricator.mitk.org/T24766#131411 and https://phabricator.mitk.org/T27259#203524 */ bool HasCollapsedFinalTimeStep() const; protected: ~ArbitraryTimeGeometry() override; std::vector m_GeometryVector; std::vector m_MinimumTimePoints; std::vector m_MaximumTimePoints; }; // end class ArbitraryTimeGeometry } // end namespace MITK #endif // ArbitraryTimeGeometry_h diff --git a/Modules/Core/include/mitkBaseGeometry.h b/Modules/Core/include/mitkBaseGeometry.h index 040e5e8134..687c184515 100644 --- a/Modules/Core/include/mitkBaseGeometry.h +++ b/Modules/Core/include/mitkBaseGeometry.h @@ -1,752 +1,752 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BaseGeometry_H_HEADER_INCLUDED #define BaseGeometry_H_HEADER_INCLUDED #include "mitkOperationActor.h" #include #include #include "itkScalableAffineTransform.h" #include "mitkNumericTypes.h" #include #include #include #include #include #include class vtkMatrix4x4; class vtkMatrixToLinearTransform; class vtkLinearTransform; 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; //##Documentation //## @brief BaseGeometry Describes the geometry of a 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 an origin and spacing to define the geometry //## //## BaseGeometry 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 //## mitk::Index3D (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 + //## An important sub-class is SlicedGeometry3D, which describes //## 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. //## //## BaseGeometry instances referring to an Image need a slightly //## different definition of corners, see SetImageGeometry. This - //## is usualy automatically called by Image. + //## is usually automatically called by Image. //## //## BaseGeometry 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(). //## //## At least, it can return the bounding box of the data object. //## //## The BaseGeometry class is an abstract class. The most simple implementation - //## is the sublass Geometry3D. + //## is the subclass Geometry3D. //## //## Rule: everything is in mm (ms) if not stated otherwise. //## @ingroup Geometry class MITKCORE_EXPORT BaseGeometry : public itk::Object, public OperationActor { public: mitkClassMacroItkParent(BaseGeometry, itk::Object); itkCloneMacro(Self); // ********************************** TypeDef ********************************** typedef GeometryTransformHolder::TransformType TransformType; typedef itk::BoundingBox BoundingBoxType; typedef BoundingBoxType::BoundsArrayType BoundsArrayType; typedef BoundingBoxType::Pointer BoundingBoxPointer; // ********************************** Origin, Spacing ********************************** //##Documentation //## @brief Get the origin, e.g. the upper-left corner of the plane const Point3D GetOrigin() const; //##Documentation //## @brief Set the origin, i.e. the upper-left corner of the plane //## void SetOrigin(const Point3D &origin); //##Documentation //## @brief Get the spacing (size of a pixel). //## const mitk::Vector3D GetSpacing() const; //##Documentation //## @brief Set the spacing (m_Spacing). //## //##The spacing is also changed in the IndexToWorldTransform. void SetSpacing(const mitk::Vector3D &aSpacing, bool enforceSetSpacing = false); //##Documentation //## @brief Get the origin as VnlVector //## //## \sa GetOrigin VnlVector GetOriginVnl() const; // ********************************** other functions ********************************** //##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); itkGetConstMacro(IndexToWorldTransformLastModified, unsigned long); //##Documentation //## @brief Overload of function Modified() to prohibit several calls of Modified() using the ModifiedLock class. //## //## For the use of Modified(), see class ModifiedLock. void Modified() const override; friend class ModifiedLock; //##Documentation //## @brief Is this BaseGeometry in a state that is valid? //## //## This function returns always true in the BaseGeometry class. Other implementations are possible in subclasses. virtual bool IsValid() const; // ********************************** Initialize ********************************** //##Documentation //## @brief Initialize the BaseGeometry void Initialize(); void InitializeGeometry(Self *newGeometry) const; // ********************************** Transformations Set/Get ********************************** //##Documentation //## @brief Get the transformation used to convert from index //## to world coordinates mitk::AffineTransform3D *GetIndexToWorldTransform(); //##Documentation //## @brief Get the transformation used to convert from index //## to world coordinates const mitk::AffineTransform3D *GetIndexToWorldTransform() const; //## @brief Set the transformation used to convert from index //## to world coordinates. The spacing of the new transform is //## copied to m_spacing. void SetIndexToWorldTransform(mitk::AffineTransform3D *transform); //##Documentation //## @brief Convenience method for setting the ITK transform //## (m_IndexToWorldTransform) via an vtkMatrix4x4.The spacing of //## the new transform is copied to m_spacing. //## \sa SetIndexToWorldTransform void SetIndexToWorldTransformByVtkMatrix(vtkMatrix4x4 *vtkmatrix); //## @brief Set the transformation used to convert from index //## to world coordinates.This function keeps the original spacing. void SetIndexToWorldTransformWithoutChangingSpacing(mitk::AffineTransform3D *transform); //##Documentation //## @brief Convenience method for setting the ITK transform //## (m_IndexToWorldTransform) via an vtkMatrix4x4. This function keeps the original spacing. //## \sa SetIndexToWorldTransform void SetIndexToWorldTransformByVtkMatrixWithoutChangingSpacing(vtkMatrix4x4 *vtkmatrix); //## Get the Vtk Matrix which describes the transform. vtkMatrix4x4 *GetVtkMatrix(); //##Documentation //## @brief Get the m_IndexToWorldTransform as a vtkLinearTransform vtkLinearTransform *GetVtkTransform() const; //##Documentation //## @brief Set the transform to identity, the spacing to 1 and origin to 0 //## void SetIdentity(); // ********************************** Transformations ********************************** //##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. //## This method also changes m_spacing. void Compose(const TransformType *other, bool pre = false); //##Documentation //## @brief Compose new IndexToWorldTransform with a given vtkMatrix4x4. //## //## Converts the vtkMatrix4x4 into a itk-transform and calls the previous method. void Compose(const vtkMatrix4x4 *vtkmatrix, bool pre = false); //##Documentation //## @brief Translate the origin by a vector //## void Translate(const Vector3D &vector); //##Documentation //##@brief executes affine operations (translate, rotate, scale) void ExecuteOperation(Operation *operation) override; //##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 world coordinates (in mm) of a \em vector //## \a vec_mm to (continuous!) index coordinates. //## For further information about coordinates types, please see the Geometry documentation void WorldToIndex(const mitk::Vector3D &vec_mm, mitk::Vector3D &vec_units) const; //##Documentation //## @brief Convert world coordinates (in mm) of a \em point to (discrete!) index coordinates. //## This method rounds to integer indices! //## For further information about coordinates types, please see the Geometry documentation template 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 < dim; ++i) { index[i] = itk::Math::RoundHalfIntegerUp(pt_units[i]); } } //##Documentation //## @brief Convert (continuous or discrete) index coordinates of a \em vector //## \a vec_units to world coordinates (in mm) //## For further information about coordinates types, please see the Geometry documentation void IndexToWorld(const mitk::Vector3D &vec_units, mitk::Vector3D &vec_mm) 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 < dim; ++i) { pt_units[i] = index[i]; } IndexToWorld(pt_units, pt_mm); } //##Documentation //## @brief Convert (continuous or discrete) index coordinates of a \em vector //## \a vec_units to world coordinates (in mm) //## @deprecated First parameter (Point3D) is not used. If possible, please use void IndexToWorld(const // mitk::Vector3D& vec_units, mitk::Vector3D& vec_mm) const. //## For further information about coordinates types, please see the Geometry documentation void IndexToWorld(const mitk::Point3D &atPt3d_units, const mitk::Vector3D &vec_units, mitk::Vector3D &vec_mm) const; //##Documentation //## @brief Convert world coordinates (in mm) of a \em vector //## \a vec_mm to (continuous!) index coordinates. //## @deprecated First parameter (Point3D) is not used. If possible, please use void WorldToIndex(const // mitk::Vector3D& vec_mm, mitk::Vector3D& vec_units) const. //## For further information about coordinates types, please see the Geometry documentation void WorldToIndex(const mitk::Point3D &atPt3d_mm, const mitk::Vector3D &vec_mm, mitk::Vector3D &vec_units) const; //##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 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 BaseGeometry 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); } // ********************************** BoundingBox ********************************** /** Get the bounding box */ itkGetConstObjectMacro(BoundingBox, BoundingBoxType); // a bit of a misuse, but we want only doxygen to see the following: #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; #endif const BoundsArrayType GetBounds() const; //##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. void SetBounds(const BoundsArrayType &bounds); //##Documentation //## @brief Set the bounding box (in index/unit coordinates) via a float array void SetFloatBounds(const float bounds[6]); //##Documentation //## @brief Set the bounding box (in index/unit coordinates) via a double array void SetFloatBounds(const double bounds[6]); //##Documentation //## @brief Get a VnlVector along bounding-box in the specified //## @a direction, length is spacing //## //## \sa GetAxisVector VnlVector GetMatrixColumn(unsigned int direction) const; //##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 Set the time bounds (in ms) // void SetTimeBounds(const TimeBounds& timebounds); // ********************************** Geometry ********************************** #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 /** Get the extent of the bounding box */ ScalarType GetExtent(unsigned int direction) const; //##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; //##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; //##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 center of the bounding-box in mm //## Point3D GetCenter() const; //##Documentation //## @brief Get the squared length of the diagonal of the bounding-box in mm //## double GetDiagonalLength2() const; //##Documentation //## @brief Get the length of the diagonal of the bounding-box in mm //## double GetDiagonalLength() const; //##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 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! void SetExtentInMM(int direction, ScalarType extentInMM); //##Documentation //## @brief Test whether the point \a p (world coordinates in mm) is //## inside the bounding box bool IsInside(const mitk::Point3D &p) const; //##Documentation - //## @brief Test whether the point \a p ((continous!)index coordinates in units) is + //## @brief Test whether the point \a p ((continuous!)index coordinates in units) is //## inside the bounding box bool IsIndexInside(const mitk::Point3D &index) const; //##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); } // ********************************* Image Geometry ******************************** //##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 Is this an ImageGeometry? //## //## For more information, see SetImageGeometry itkGetConstMacro(ImageGeometry, bool) //##Documentation - //## @brief Define that this BaseGeometry is refering to an Image + //## @brief Define that this BaseGeometry is referring 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 BaseGeometry is referring to an Image. itkSetMacro(ImageGeometry, bool); itkBooleanMacro(ImageGeometry); const GeometryTransformHolder *GetGeometryTransformHolder() const; protected: // ********************************** Constructor ********************************** BaseGeometry(); BaseGeometry(const BaseGeometry &other); ~BaseGeometry() override; itk::LightObject::Pointer InternalClone() const override = 0; void PrintSelf(std::ostream &os, itk::Indent indent) const override; static const std::string GetTransformAsString(TransformType *transformType); itkGetConstMacro(NDimensions, unsigned int); bool IsBoundingBoxNull() const; bool IsIndexToWorldTransformNull() const; void SetVtkMatrixDeepCopy(vtkTransform *vtktransform); void _SetSpacing(const mitk::Vector3D &aSpacing, bool enforceSetSpacing = false); //##Documentation //## @brief PreSetSpacing //## //## These virtual function allows a different beahiour in subclasses. //## Do implement them in every subclass of BaseGeometry. If not needed, use //## {Superclass::PreSetSpacing();}; virtual void PreSetSpacing(const mitk::Vector3D & /*aSpacing*/){}; //##Documentation //## @brief CheckBounds //## //## This function is called in SetBounds. Assertions can be implemented in this function (see PlaneGeometry.cpp). //## If you implement this function in a subclass, make sure, that all classes were your class inherits from //## have an implementation of CheckBounds //## (e.g. inheritance BaseGeometry <- A <- B. Implementation of CheckBounds in class B needs implementation in A as // well!) virtual void CheckBounds(const BoundsArrayType & /*bounds*/){}; //##Documentation //## @brief CheckIndexToWorldTransform //## //## This function is called in SetIndexToWorldTransform. Assertions can be implemented in this function (see // PlaneGeometry.cpp). //## In Subclasses of BaseGeometry, implement own conditions or call Superclass::CheckBounds(bounds);. virtual void CheckIndexToWorldTransform(mitk::AffineTransform3D * /*transform*/){}; private: GeometryTransformHolder *m_GeometryTransform; void InitializeGeometryTransformHolder(const BaseGeometry *otherGeometry); //##Documentation //## @brief Bounding Box, which is axes-parallel in intrinsic coordinates //## (often integer indices of pixels) BoundingBoxPointer m_BoundingBox; unsigned int m_FrameOfReferenceID; // mitk::TimeBounds m_TimeBounds; static const unsigned int m_NDimensions = 3; mutable TransformType::Pointer m_InvertedTransform; mutable unsigned long m_IndexToWorldTransformLastModified; bool m_ImageGeometry; //##Documentation //## @brief ModifiedLockFlag is used to prohibit the call of Modified() //## //## For the use of this Flag, see class ModifiedLock. This flag should only be set //## by the ModifiedLock class! bool m_ModifiedLockFlag; //##Documentation //## @brief ModifiedcalledFlag is used to collect calls of Modified(). //## //## For the use of this Flag, see class ModifiedLock. This flag should only be set //## by the Modified() function! mutable bool m_ModifiedCalledFlag; }; // ********************************** Equal Functions ********************************** // // Static compare functions mainly for testing // /** - * @brief Equal A function comparing two geometries for beeing identical. + * @brief Equal A function comparing two geometries for being 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. + * The parameter eps is a tolarence value for all methods which are internally used for comparison. * If you want to use different tolerance 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 coordinateEps Tolerance for comparison of all spatial aspects (spacing, origin and grid alignment). * You can use mitk::eps in most cases. * @param directionEps Tolerance for comparison of all directional aspects (axis). 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. */ MITKCORE_EXPORT bool Equal(const mitk::BaseGeometry& leftHandSide, const mitk::BaseGeometry& rightHandSide, ScalarType coordinateEps, ScalarType directionEps, bool verbose = false); /** - * @brief Equal A function comparing two geometries for beeing identical. + * @brief Equal A function comparing two geometries for being identical. * * @ingroup MITKTestingAPI * * This is an overloaded version that uses a single tolerance for spatial and directional aspects. For more details, * see the other overloaded version. * * @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. */ MITKCORE_EXPORT bool Equal(const mitk::BaseGeometry &leftHandSide, const mitk::BaseGeometry &rightHandSide, ScalarType eps = mitk::eps, bool verbose = false); /** - * @brief Equal A function comparing two transforms (TransformType) for beeing identical. + * @brief Equal A function comparing two transforms (TransformType) for being 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. + * The parameter eps is a tolarence value for all methods which are internally used for comparison. * @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. */ MITKCORE_EXPORT bool Equal(const mitk::BaseGeometry::TransformType &leftHandSide, const mitk::BaseGeometry::TransformType &rightHandSide, ScalarType eps, bool verbose); /** - * @brief Equal A function comparing two bounding boxes (BoundingBoxType) for beeing identical. + * @brief Equal A function comparing two bounding boxes (BoundingBoxType) for being 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. + * The parameter eps is a tolarence value for all methods which are internally used for comparison. * @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. */ MITKCORE_EXPORT bool Equal(const mitk::BaseGeometry::BoundingBoxType &leftHandSide, const mitk::BaseGeometry::BoundingBoxType &rightHandSide, ScalarType eps, bool verbose); /** * @brief A function checks if a test geometry is a sub geometry of * a given reference geometry. * * Sub geometry means that both geometries have the same voxel grid (same spacing, same axes, - * orgin is on voxel grid), but the bounding box of the checked geometry is contained or equal + * origin is on voxel grid), but the bounding box of the checked geometry is contained or equal * to the bounding box of the reference geometry.\n * By this definition equal geometries are always sub geometries of each other. * * The function checks the spacing, origin, axis vectors, extents, the matrix of the * IndexToWorldTransform (elementwise), the bounding (elementwise) and the ImageGeometry flag. * * The parameter eps is a tolerance value for all methods which are internally used for comparison. * @param testGeo Geometry that should be checked if it is a sub geometry of referenceGeo. * @param referenceGeo Geometry that should contain testedGeometry as sub geometry. * @param coordinateEps Tolerance for comparison of all spatial aspects (spacing, origin and grid alignment). * You can use mitk::eps in most cases. * @param directionEps Tolerance for comparison of all directional aspects (axis). 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 comparisons are true. False otherwise. */ MITKCORE_EXPORT bool IsSubGeometry(const mitk::BaseGeometry& testGeo, const mitk::BaseGeometry& referenceGeo, ScalarType coordinateEps, ScalarType directionEps, bool verbose = false); /** * @brief A function checks if a test geometry is a sub geometry of * a given reference geometry. * * This is a overloaded version that uses a single tolerance for spatial and directional aspects. For more details, * see the other overloaded version. * * @param testGeo Geometry that should be checked if it is a sub geometry of referenceGeo. * @param referenceGeo Geometry that should contain testedGeometry as sub geometry. * @param eps Tolarence for comparison (both spatial and directional). 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 otherwise. */ MITKCORE_EXPORT bool IsSubGeometry(const mitk::BaseGeometry& testGeo, const mitk::BaseGeometry& referenceGeo, ScalarType eps = mitk::eps, bool verbose = false); } // namespace mitk #endif /* BaseGeometry_H_HEADER_INCLUDED */ diff --git a/Modules/Core/include/mitkBaseProperty.h b/Modules/Core/include/mitkBaseProperty.h index fcad73663b..5bd652197f 100644 --- a/Modules/Core/include/mitkBaseProperty.h +++ b/Modules/Core/include/mitkBaseProperty.h @@ -1,98 +1,98 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BASEPROPERTY_H_HEADER_INCLUDED_C1F4DF54 #define BASEPROPERTY_H_HEADER_INCLUDED_C1F4DF54 #include #include #include #include namespace mitk { /*! \brief Abstract base class for properties \ingroup DataManagement Base class for properties. Properties are arbitrary additional information (to define a new type of information you have to define a subclass of BaseProperty) that can be added to a PropertyList. Concrete subclasses of BaseProperty should define Set-/Get-methods to assess the property value, which should be stored by value (not by reference). Subclasses must implement an operator==(const BaseProperty& property), which is used by PropertyList to check whether a property has been changed. */ class MITKCORE_EXPORT BaseProperty : public itk::Object { public: mitkClassMacroItkParent(BaseProperty, itk::Object); itkCloneMacro(Self); /*! @brief Subclasses must implement IsEqual(const BaseProperty&) to support comparison. operator== which is used by PropertyList to check whether a property has been changed. */ bool operator==(const BaseProperty &property) const; /*! @brief Assigns property to this BaseProperty instance. Subclasses must implement Assign(const BaseProperty&) and call the superclass Assign method for proper handling of polymorphic assignments. The assignment operator of the subclass should be disabled and the baseclass operator should be made visible using "using" statements. */ BaseProperty &operator=(const BaseProperty &property); /*! @brief Assigns property to this BaseProperty instance. This method is identical to the assignment operator, except for the return type. - It allows to directly check if the assignemnt was successfull. + It allows to directly check if the assignment was successful. */ bool AssignProperty(const BaseProperty &property); virtual std::string GetValueAsString() const; /** * @brief Default return value if a property which can not be returned as string */ static const std::string VALUE_CANNOT_BE_CONVERTED_TO_STRING; protected: BaseProperty(); BaseProperty(const BaseProperty &other); ~BaseProperty() override; private: /*! Override this method in subclasses to implement a meaningful comparison. The property argument is guaranteed to be castable to the type of the implementing subclass. */ virtual bool IsEqual(const BaseProperty &property) const = 0; /*! Override this method in subclasses to implement a meaningful assignment. The property argument is guaranteed to be castable to the type of the implementing subclass. @warning This is not yet exception aware/safe and if this method returns false, this property's state might be undefined. @return True if the argument could be assigned to this property. */ virtual bool Assign(const BaseProperty &) = 0; }; } // namespace mitk #endif /* BASEPROPERTY_H_HEADER_INCLUDED_C1F4DF54 */ diff --git a/Modules/Core/include/mitkBaseRenderer.h b/Modules/Core/include/mitkBaseRenderer.h index 8d2a45ef67..430721aee6 100644 --- a/Modules/Core/include/mitkBaseRenderer.h +++ b/Modules/Core/include/mitkBaseRenderer.h @@ -1,523 +1,523 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BASERENDERER_H_HEADER_INCLUDED_C1CCA0F4 #define BASERENDERER_H_HEADER_INCLUDED_C1CCA0F4 #include "mitkCameraRotationController.h" #include "mitkDataStorage.h" #include "mitkPlaneGeometry.h" #include "mitkPlaneGeometryData.h" #include "mitkSliceNavigationController.h" #include "mitkTimeGeometry.h" #include "mitkBindDispatcherInteractor.h" #include "mitkDispatcher.h" #include #include #include #include namespace mitk { class NavigationController; class SliceNavigationController; class CameraRotationController; class CameraController; class DataStorage; class Mapper; class BaseLocalStorageHandler; class KeyEvent; #pragma GCC visibility push(default) itkEventMacroDeclaration(RendererResetEvent, itk::AnyEvent); #pragma GCC visibility pop //##Documentation //## @brief Organizes the rendering process //## //## Organizes the rendering process. A Renderer contains a reference to a //## DataStorage and asks the mappers of the data objects to render //## the data into the renderwindow it is associated to. //## //## \#Render() checks if rendering is currently allowed by calling //## RenderWindow::PrepareRendering(). Initialization of a rendering context //## can also be performed in this method. //## //## The actual rendering code has been moved to \#Repaint() //## Both \#Repaint() and \#Update() are declared protected now. //## //## Note: Separation of the Repaint and Update processes (rendering vs //## creating a vtk prop tree) still needs to be worked on. The whole //## rendering process also should be reworked to use VTK based classes for //## both 2D and 3D rendering. //## @ingroup Renderer class MITKCORE_EXPORT BaseRenderer : public itk::Object { public: typedef std::map BaseRendererMapType; static BaseRendererMapType baseRendererMap; static BaseRenderer *GetInstance(vtkRenderWindow *renWin); static void AddInstance(vtkRenderWindow *renWin, BaseRenderer *baseRenderer); static void RemoveInstance(vtkRenderWindow *renWin); static BaseRenderer *GetByName(const std::string &name); static vtkRenderWindow *GetRenderWindowByName(const std::string &name); /** Standard class typedefs. */ mitkClassMacroItkParent(BaseRenderer, itk::Object); BaseRenderer(const char *name = nullptr, vtkRenderWindow *renWin = nullptr); //##Documentation //## @brief MapperSlotId defines which kind of mapper (e.g. 2D or 3D) should be used. typedef int MapperSlotId; enum StandardMapperSlot { Standard2D = 1, Standard3D = 2 }; //##Documentation //## @brief Possible view directions for render windows. enum class ViewDirection { AXIAL = 0, SAGITTAL, CORONAL, THREE_D }; virtual void SetDataStorage(DataStorage *storage); ///< set the datastorage that will be used for rendering //##Documentation //## return the DataStorage that is used for rendering virtual DataStorage::Pointer GetDataStorage() const { return m_DataStorage.GetPointer(); } //##Documentation //## @brief Access the RenderWindow into which this renderer renders. vtkRenderWindow *GetRenderWindow() const { return m_RenderWindow; } vtkRenderer *GetVtkRenderer() const { return m_VtkRenderer; } //##Documentation //## @brief Returns the Dispatcher which handles Events for this BaseRenderer Dispatcher::Pointer GetDispatcher() const; //##Documentation //## @brief Default mapper id to use. static const MapperSlotId defaultMapper; //##Documentation //## @brief Do the rendering and flush the result. virtual void Paint(); //##Documentation //## @brief Initialize the RenderWindow. Should only be called from RenderWindow. virtual void Initialize(); //##Documentation //## @brief Called to inform the renderer that the RenderWindow has been resized. virtual void Resize(int w, int h); //##Documentation //## @brief Initialize the renderer with a RenderWindow (@a renderwindow). virtual void InitRenderer(vtkRenderWindow *renderwindow); //##Documentation //## @brief Set the initial size. Called by RenderWindow after it has become //## visible for the first time. virtual void InitSize(int w, int h); //##Documentation //## @brief Draws a point on the widget. //## Should be used during conferences to show the position of the remote mouse virtual void DrawOverlayMouse(Point2D &p2d); //##Documentation //## @brief Set/Get the WorldGeometry (m_WorldGeometry) for 3D and 2D rendering, that describing the //## (maximal) area to be rendered. //## //## Depending of the type of the passed BaseGeometry more or less information can be extracted: //## \li if it is a PlaneGeometry (which is a sub-class of BaseGeometry), m_CurrentWorldPlaneGeometry is //## also set to point to it. m_WorldTimeGeometry is set to nullptr. //## \li if it is a TimeGeometry, m_WorldTimeGeometry is also set to point to it. //## If m_WorldTimeGeometry contains instances of SlicedGeometry3D, m_CurrentWorldPlaneGeometry is set to //## one of geometries stored in the SlicedGeometry3D according to the value of m_Slice; otherwise //## a PlaneGeometry describing the top of the bounding-box of the BaseGeometry is set as the //## m_CurrentWorldPlaneGeometry. //## \li otherwise a PlaneGeometry describing the top of the bounding-box of the BaseGeometry //## is set as the m_CurrentWorldPlaneGeometry. m_WorldTimeGeometry is set to nullptr. //## @todo add calculation of PlaneGeometry describing the top of the bounding-box of the BaseGeometry //## when the passed BaseGeometry is not sliced. //## \sa m_WorldGeometry //## \sa m_WorldTimeGeometry //## \sa m_CurrentWorldPlaneGeometry virtual void SetWorldGeometry3D(const BaseGeometry *geometry); virtual void SetWorldTimeGeometry(const mitk::TimeGeometry *geometry); itkGetConstObjectMacro(WorldTimeGeometry, TimeGeometry); //##Documentation //## @brief Get the current 3D-worldgeometry (m_CurrentWorldGeometry) used for 3D-rendering itkGetConstObjectMacro(CurrentWorldGeometry, BaseGeometry); //##Documentation //## @brief Get the current 2D-worldgeometry (m_CurrentWorldPlaneGeometry) used for 2D-rendering itkGetConstObjectMacro(CurrentWorldPlaneGeometry, PlaneGeometry) /** * \deprecatedSince{2014_10} Please use GetCurrentWorldPlaneGeometry */ DEPRECATED(const PlaneGeometry *GetCurrentWorldGeometry2D()) { return GetCurrentWorldPlaneGeometry(); }; //##Documentation //## Calculates the bounds of the DataStorage (if it contains any valid data), //## creates a geometry from these bounds and sets it as world geometry of the renderer. //## //## Call this method to re-initialize the renderer to the current DataStorage //## (e.g. after loading an additional dataset), to ensure that the view is //## aligned correctly. //## \warning This is not implemented yet. virtual bool SetWorldGeometryToDataStorageBounds() { return false; } //##Documentation //## @brief Set/Get m_Slice which defines together with m_TimeStep the 2D geometry //## stored in m_WorldTimeGeometry used as m_CurrentWorldPlaneGeometry //## //## \sa m_Slice virtual void SetSlice(unsigned int slice); itkGetConstMacro(Slice, unsigned int); //##Documentation //## @brief Set/Get m_TimeStep which defines together with m_Slice the 2D geometry //## stored in m_WorldTimeGeometry used as m_CurrentWorldPlaneGeometry //## //## \sa m_TimeStep virtual void SetTimeStep(unsigned int timeStep); itkGetConstMacro(TimeStep, unsigned int); //##Documentation //## @brief Get the time-step of a BaseData object which //## exists at the time of the currently displayed content //## //## Returns -1 or mitk::BaseData::m_TimeSteps if there //## is no data at the current time. //## \sa GetTimeStep, m_TimeStep TimeStepType GetTimeStep(const BaseData *data) const; //##Documentation //## @brief Get the time in ms of the currently displayed content //## //## \sa GetTimeStep, m_TimeStep ScalarType GetTime() const; //##Documentation //## @brief SetWorldGeometry is called according to the geometrySliceEvent, //## which is supposed to be a SliceNavigationController::GeometrySendEvent virtual void SetGeometry(const itk::EventObject &geometrySliceEvent); //##Documentation //## @brief UpdateWorldGeometry is called to re-read the 2D geometry from the //## slice navigation controller virtual void UpdateGeometry(const itk::EventObject &geometrySliceEvent); //##Documentation //## @brief SetSlice is called according to the geometrySliceEvent, //## which is supposed to be a SliceNavigationController::GeometrySliceEvent virtual void SetGeometrySlice(const itk::EventObject &geometrySliceEvent); //##Documentation //## @brief SetTimeStep is called according to the geometrySliceEvent, //## which is supposed to be a SliceNavigationController::GeometryTimeEvent virtual void SetGeometryTime(const itk::EventObject &geometryTimeEvent); //##Documentation //## @brief Get a DataNode pointing to a data object containing the current 2D-worldgeometry // m_CurrentWorldPlaneGeometry (for 2D rendering) itkGetObjectMacro(CurrentWorldPlaneGeometryNode, DataNode) /** * \deprecatedSince{2014_10} Please use GetCurrentWorldPlaneGeometryNode */ DEPRECATED(DataNode *GetCurrentWorldGeometry2DNode()) { return GetCurrentWorldPlaneGeometryNode(); }; //##Documentation //## @brief Sets timestamp of CurrentWorldPlaneGeometry and forces so reslicing in that renderwindow void SendUpdateSlice(); //##Documentation //## @brief Get timestamp of last call of SetCurrentWorldPlaneGeometry unsigned long GetCurrentWorldPlaneGeometryUpdateTime() { return m_CurrentWorldPlaneGeometryUpdateTime; } /** * \deprecatedSince{2014_10} Please use GetCurrentWorldPlaneGeometryUpdateTime */ DEPRECATED(unsigned long GetCurrentWorldGeometry2DUpdateTime()) { return GetCurrentWorldPlaneGeometryUpdateTime(); }; //##Documentation //## @brief Get timestamp of last change of current TimeStep unsigned long GetTimeStepUpdateTime() { return m_TimeStepUpdateTime; } //##Documentation //## @brief Perform a picking: find the x,y,z world coordinate of a //## display x,y coordinate. //## @warning Has to be overwritten in subclasses for the 3D-case. //## //## Implemented here only for 2D-rendering virtual void PickWorldPoint(const Point2D &diplayPosition, Point3D &worldPosition) const = 0; /** \brief Determines the object (mitk::DataNode) closest to the current * position by means of picking * * \warning Implementation currently empty for 2D rendering; intended to be * implemented for 3D renderers */ virtual DataNode *PickObject(const Point2D & /*displayPosition*/, Point3D & /*worldPosition*/) const { return nullptr; } //##Documentation //## @brief Get the MapperSlotId to use. itkGetMacro(MapperID, MapperSlotId); itkGetConstMacro(MapperID, MapperSlotId); //##Documentation //## @brief Set the MapperSlotId to use. virtual void SetMapperID(MapperSlotId id); virtual int *GetSize() const; virtual int *GetViewportSize() const; void SetSliceNavigationController(SliceNavigationController *SlicenavigationController); itkGetObjectMacro(CameraController, CameraController); itkGetObjectMacro(SliceNavigationController, SliceNavigationController); itkGetObjectMacro(CameraRotationController, CameraRotationController); itkGetMacro(EmptyWorldGeometry, bool); //##Documentation //## @brief Tells if the displayed region is shifted and rescaled if the render window is resized. itkGetMacro(KeepDisplayedRegion, bool) //##Documentation //## @brief Tells if the displayed region should be shifted and rescaled if the render window is resized. itkSetMacro(KeepDisplayedRegion, bool); //##Documentation //## @brief get the name of the Renderer //## @note const char *GetName() const { return m_Name.c_str(); } //##Documentation //## @brief get the x_size of the RendererWindow //## @note int GetSizeX() const { return GetSize()[0]; } //##Documentation //## @brief get the y_size of the RendererWindow //## @note int GetSizeY() const { return GetSize()[1]; } const double *GetBounds() const; void RequestUpdate(); void ForceImmediateUpdate(); /** Returns number of mappers which are visible and have level-of-detail * rendering enabled */ unsigned int GetNumberOfVisibleLODEnabledMappers() const; //##Documentation //## @brief This method converts a display point to the 3D world index //## using the geometry of the renderWindow. void DisplayToWorld(const Point2D &displayPoint, Point3D &worldIndex) const; //##Documentation //## @brief This method converts a display point to the 2D world index, mapped onto the display plane //## using the geometry of the renderWindow. void DisplayToPlane(const Point2D &displayPoint, Point2D &planePointInMM) const; //##Documentation //## @brief This method converts a 3D world index to the display point //## using the geometry of the renderWindow. void WorldToDisplay(const Point3D &worldIndex, Point2D &displayPoint) const; //##Documentation //## @brief This method converts a 3D world index to the point on the viewport //## using the geometry of the renderWindow. void WorldToView(const Point3D &worldIndex, Point2D &viewPoint) const; //##Documentation //## @brief This method converts a 2D plane coordinate to the display point //## using the geometry of the renderWindow. void PlaneToDisplay(const Point2D &planePointInMM, Point2D &displayPoint) const; //##Documentation //## @brief This method converts a 2D plane coordinate to the point on the viewport //## using the geometry of the renderWindow. void PlaneToView(const Point2D &planePointInMM, Point2D &viewPoint) const; double GetScaleFactorMMPerDisplayUnit() const; Point2D GetDisplaySizeInMM() const; Point2D GetViewportSizeInMM() const; Point2D GetOriginInMM() const; itkGetConstMacro(ConstrainZoomingAndPanning, bool) virtual void SetConstrainZoomingAndPanning(bool constrain); /** * \brief Provides (1) world coordinates for a given mouse position and (2) * translates mousePosition to Display coordinates * \deprecated Map2DRendererPositionTo3DWorldPosition is deprecated. Please use DisplayToWorld instead. */ DEPRECATED(virtual Point3D Map2DRendererPositionTo3DWorldPosition(const Point2D &mousePosition) const); protected: ~BaseRenderer() override; //##Documentation //## @brief Call update of all mappers. To be implemented in subclasses. virtual void Update() = 0; vtkRenderWindow *m_RenderWindow; vtkRenderer *m_VtkRenderer; //##Documentation - //## @brief MapperSlotId to use. Defines which kind of mapper (e.g., 2D or 3D) shoud be used. + //## @brief MapperSlotId to use. Defines which kind of mapper (e.g., 2D or 3D) should be used. MapperSlotId m_MapperID; //##Documentation //## @brief The DataStorage that is used for rendering. DataStorage::Pointer m_DataStorage; //##Documentation //## @brief Timestamp of last call of Update(). unsigned long m_LastUpdateTime; //##Documentation //## @brief CameraController for 3D rendering //## @note preliminary. itk::SmartPointer m_CameraController; SliceNavigationController::Pointer m_SliceNavigationController; CameraRotationController::Pointer m_CameraRotationController; //##Documentation //## @brief Sets m_CurrentWorldPlaneGeometry virtual void SetCurrentWorldPlaneGeometry(const PlaneGeometry *geometry2d); /** * \deprecatedSince{2014_10} Please use SetCurrentWorldPlaneGeometry */ DEPRECATED(void SetCurrentWorldGeometry2D(PlaneGeometry *geometry2d)) { SetCurrentWorldPlaneGeometry(geometry2d); }; //##Documentation //## @brief Sets m_CurrentWorldGeometry virtual void SetCurrentWorldGeometry(const BaseGeometry *geometry); private: //##Documentation //## m_WorldTimeGeometry is set by SetWorldGeometry if the passed BaseGeometry is a //## TimeGeometry (or a sub-class of it). If it contains instances of SlicedGeometry3D, //## m_Slice and m_TimeStep (set via SetSlice and SetTimeStep, respectively) define //## which 2D geometry stored in m_WorldTimeGeometry (if available) //## is used as m_CurrentWorldPlaneGeometry. //## \sa m_CurrentWorldPlaneGeometry TimeGeometry::ConstPointer m_WorldTimeGeometry; //##Documentation //## Pointer to the current 3D-worldgeometry. BaseGeometry::ConstPointer m_CurrentWorldGeometry; //##Documentation //## Pointer to the current 2D-worldgeometry. The 2D-worldgeometry //## describes the maximal area (2D manifold) to be rendered in case we //## are doing 2D-rendering. //## It is const, since we are not allowed to change it (it may be taken //## directly from the geometry of an image-slice and thus it would be //## very strange when suddenly the image-slice changes its geometry). PlaneGeometry::Pointer m_CurrentWorldPlaneGeometry; //##Documentation //## Defines together with m_Slice which 2D geometry stored in m_WorldTimeGeometry //## is used as m_CurrentWorldPlaneGeometry: m_WorldTimeGeometry->GetPlaneGeometry(m_Slice, m_TimeStep). //## \sa m_WorldTimeGeometry unsigned int m_Slice; //##Documentation //## Defines together with m_TimeStep which 2D geometry stored in m_WorldTimeGeometry //## is used as m_CurrentWorldPlaneGeometry: m_WorldTimeGeometry->GetPlaneGeometry(m_Slice, m_TimeStep). //## \sa m_WorldTimeGeometry unsigned int m_TimeStep; //##Documentation //## @brief timestamp of last call of SetWorldGeometry itk::TimeStamp m_CurrentWorldPlaneGeometryUpdateTime; //##Documentation //## @brief timestamp of last change of the current time step itk::TimeStamp m_TimeStepUpdateTime; //##Documentation //## @brief Helper class which establishes connection between Interactors and Dispatcher via a common DataStorage. BindDispatcherInteractor *m_BindDispatcherInteractor; //##Documentation //## @brief Tells if the displayed region should be shifted or rescaled if the render window is resized. bool m_KeepDisplayedRegion; protected: void PrintSelf(std::ostream &os, itk::Indent indent) const override; //##Documentation //## Data object containing the m_CurrentWorldPlaneGeometry defined above. PlaneGeometryData::Pointer m_CurrentWorldPlaneGeometryData; //##Documentation //## DataNode objects containing the m_CurrentWorldPlaneGeometryData defined above. DataNode::Pointer m_CurrentWorldPlaneGeometryNode; //##Documentation //## @brief test only unsigned long m_CurrentWorldPlaneGeometryTransformTime; std::string m_Name; double m_Bounds[6]; bool m_EmptyWorldGeometry; typedef std::set LODEnabledMappersType; /** Number of mappers which are visible and have level-of-detail * rendering enabled */ unsigned int m_NumberOfVisibleLODEnabledMappers; // Local Storage Handling for mappers protected: std::list m_RegisteredLocalStorageHandlers; bool m_ConstrainZoomingAndPanning; public: void RemoveAllLocalStorages(); void RegisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh); void UnregisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh); }; } // namespace mitk #endif /* BASERENDERER_H_HEADER_INCLUDED_C1CCA0F4 */ diff --git a/Modules/Core/include/mitkCallbackFromGUIThread.h b/Modules/Core/include/mitkCallbackFromGUIThread.h index fe0d5c6d0b..de52351c9a 100644 --- a/Modules/Core/include/mitkCallbackFromGUIThread.h +++ b/Modules/Core/include/mitkCallbackFromGUIThread.h @@ -1,176 +1,176 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITK_CALLBACK_WITHIN_GUI_TREAD_H_INCLUDGEWQ #define MITK_CALLBACK_WITHIN_GUI_TREAD_H_INCLUDGEWQ #include #include #include namespace mitk { /*! \brief Used by CallbackFromGUIThread to pass parameters. */ template class CallbackEventOneParameter : public itk::AnyEvent { public: typedef CallbackEventOneParameter Self; typedef itk::AnyEvent Superclass; CallbackEventOneParameter(const T t) : m_Data(t) {} ~CallbackEventOneParameter() override {} const char *GetEventName() const override { return "CallbackEventOneParameter"; } bool CheckEvent(const ::itk::EventObject *e) const override { return dynamic_cast(e); } ::itk::EventObject *MakeObject() const override { return new Self(m_Data); } const T GetData() const { return m_Data; } CallbackEventOneParameter(const Self &s) : itk::AnyEvent(s), m_Data(s.m_Data){}; protected: const T m_Data; private: void operator=(const Self &); }; /*! \brief Toolkit specific implementation of mitk::CallbackFromGUIThread For any toolkit, this class has to be sub-classed. One instance of that sub-class has to - be registered with mitk::CallbackFromGUIThread. See the (very simple) implmentation of + be registered with mitk::CallbackFromGUIThread. See the (very simple) implementation of QmitkCallbackFromGUIThread for an example. */ class MITKCORE_EXPORT CallbackFromGUIThreadImplementation { public: /// Change the current application cursor virtual void CallThisFromGUIThread(itk::Command *, itk::EventObject *) = 0; virtual ~CallbackFromGUIThreadImplementation(){}; protected: private: }; /*! \brief Allows threads to call some method from within the GUI thread. This class is useful for use with GUI toolkits that are not thread-safe, e.g. Qt. Any thread that needs to work with the GUI at some time during its execution (e.g. at the end, to display some results) can use this class to ask for a call to a member function from the GUI thread. Usage example We assume that you have a class ThreadedClass, that basically lives in a thread that is different from the GUI thread. Now this class has to change some element of the GUI to indicate its status. This could be dangerous (with Qt it is for sure). The solution is, that ThreadedClass asks mitk::CallbackFromGUIThread to call a method from the GUI thread (main thread). Here is part of the header of ThreadedClass: \code class ThreadedClass : public ParentClass { public: ... // All you need // This function runs in its own thread ! void ThreadedFunction(); // This should be called from the GUI thread void ChangeGUIElementsToIndicateProgress(const itk::EventObject&); ... }; \endcode \code #include "mitkCallbackFromGUIThread.h" #include // This method runs in a thread of its own! So it can't manipulate GUI elements directly without causing trouble void ThreadedClass::ThreadedFunction() { ... // Create a command object (passing parameters comes later) itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction(this, &ThreadedClass::ChangeGUIElementsToIndicateProgress); // Ask to execute that command from the GUI thread mitk::CallbackFromGUIThread::GetInstance()->CallThisFromGUIThread(command); ... } // Do dangerous GUI changing stuff here void ThreadedClass::ChangeGUIElementsToIndicateProgress(const itk::EventObject& e) { Application::GetButtonGrid()->AddButton("Stop"); // this is pseudo code } \endcode This obviously won't allow you to pass parameters to ChangeGUIElementsToIndicateProgress. If you need to do that, you have to create a kind of itk::EventObject that can be asked for a parameter (this solution is not nice, if you see a better solution, please mail to mitk-users@lists.sourceforge.net). The itk::EventObject has to be created with "new" (which can also be done by calling MakeObject on an existing EventObject). \code const mitk::OneParameterEvent* event = new mitk::OneParameterEvent(1); // this class is not yet defined but will be itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction(this, &ThreadedClass::ChangeGUIElementsToIndicateProgress); mitk::CallbackFromGUIThread::GetInstance()->CallThisFromGUIThread(command, event); // DO NOT delete event now. This will be done by CallThisFromGUIThread after the command will executed. \endcode \todo Create a set of "normal" parameter-event-objects that people might want to use. */ class MITKCORE_EXPORT CallbackFromGUIThread { public: /// This class is a singleton. static CallbackFromGUIThread *GetInstance(); /// To be called by a toolkit specific CallbackFromGUIThreadImplementation. static void RegisterImplementation(CallbackFromGUIThreadImplementation *implementation); /// Change the current application cursor void CallThisFromGUIThread(itk::Command *, itk::EventObject *e = nullptr); protected: /// Purposely hidden - singleton CallbackFromGUIThread(); private: static CallbackFromGUIThreadImplementation *m_Implementation; static CallbackFromGUIThread *m_Instance; }; } // namespace #endif diff --git a/Modules/Core/include/mitkCommon.h b/Modules/Core/include/mitkCommon.h index 1fd400dfaf..d483493f69 100644 --- a/Modules/Core/include/mitkCommon.h +++ b/Modules/Core/include/mitkCommon.h @@ -1,196 +1,196 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITK_COMMON_H_DEFINED #define MITK_COMMON_H_DEFINED #ifdef _MSC_VER // This warns about truncation to 255 characters in debug/browse info #pragma warning(disable : 4786) #pragma warning(disable : 4068) /* disable unknown pragma warnings */ #endif // add only those headers here that are really necessary for all classes! #include "itkObject.h" #include "mitkConfig.h" #include "mitkExceptionMacro.h" #include "mitkGetClassHierarchy.h" #include "mitkLogMacros.h" typedef unsigned int MapperSlotId; /** From ITK 4.7 version, the TypeMacro overrides (by using the explicit attribute) the GetNameOfClass * hence the SuperClass must provide one. * * If not, use the mitkClassMacroNoParent version */ #define mitkClassMacro(className, SuperClassName) \ typedef className Self; \ typedef SuperClassName Superclass; \ typedef itk::SmartPointer Pointer; \ typedef itk::SmartPointer ConstPointer; \ static const char *GetStaticNameOfClass() { return #className; } \ virtual std::vector GetClassHierarchy() const override { return mitk::GetClassHierarchy(); } \ itkTypeMacro(className, SuperClassName); #define mitkClassMacroItkParent(className, SuperClassName) \ typedef className Self; \ typedef SuperClassName Superclass; \ typedef itk::SmartPointer Pointer; \ typedef itk::SmartPointer ConstPointer; \ static const char *GetStaticNameOfClass() { return #className; } \ virtual std::vector GetClassHierarchy() const { return mitk::GetClassHierarchy(); } \ itkTypeMacro(className, SuperClassName); /** At version 4.7 provides two type macros, the normal one expects the Superclass to provide the - * GetNameOfClass explicitely, the NoParent deos not expect anything. + * GetNameOfClass explicitly, the NoParent deos not expect anything. */ #define mitkClassMacroNoParent(className) \ typedef className Self; \ typedef itk::SmartPointer Pointer; \ typedef itk::SmartPointer ConstPointer; \ static const char *GetStaticNameOfClass() { return #className; } \ virtual std::vector GetClassHierarchy() const { return mitk::GetClassHierarchy(); } \ itkTypeMacroNoParent(className) /** * Macro for Constructors with one parameter for classes derived from itk::Lightobject **/ #define mitkNewMacro1Param(classname, type) \ \ static Pointer New(type _arg) \ \ { \ Pointer smartPtr = new classname(_arg); \ smartPtr->UnRegister(); \ return smartPtr; \ } /** * Macro for Constructors with two parameters for classes derived from itk::Lightobject **/ #define mitkNewMacro2Param(classname, typea, typeb) \ \ static Pointer New(typea _arga, typeb _argb) \ \ { \ Pointer smartPtr = new classname(_arga, _argb); \ smartPtr->UnRegister(); \ return smartPtr; \ } /** * Macro for Constructors with three parameters for classes derived from itk::Lightobject **/ #define mitkNewMacro3Param(classname, typea, typeb, typec) \ \ static Pointer New(typea _arga, typeb _argb, typec _argc) \ \ { \ Pointer smartPtr = new classname(_arga, _argb, _argc); \ smartPtr->UnRegister(); \ return smartPtr; \ } /** * Macro for Constructors with four parameters for classes derived from itk::Lightobject **/ #define mitkNewMacro4Param(classname, typea, typeb, typec, typed) \ \ static Pointer New(typea _arga, typeb _argb, typec _argc, typed _argd) \ \ { \ Pointer smartPtr = new classname(_arga, _argb, _argc, _argd); \ smartPtr->UnRegister(); \ return smartPtr; \ } /** * Macro for Constructors with five parameters for classes derived from itk::Lightobject **/ #define mitkNewMacro5Param(classname, typea, typeb, typec, typed, typee) \ \ static Pointer New(typea _arga, typeb _argb, typec _argc, typed _argd, typee _arge) \ \ { \ Pointer smartPtr = new classname(_arga, _argb, _argc, _argd, _arge); \ smartPtr->UnRegister(); \ return smartPtr; \ } /** * Macro for Constructors with six parameters for classes derived from itk::Lightobject **/ #define mitkNewMacro6Param(classname, typea, typeb, typec, typed, typee, typef) \ \ static Pointer New(typea _arga, typeb _argb, typec _argc, typed _argd, typee _arge, typef _argf) \ \ { \ Pointer smartPtr = new classname(_arga, _argb, _argc, _argd, _arge, _argf); \ smartPtr->UnRegister(); \ return smartPtr; \ } /** Get a smart const pointer to an object. Creates the member * Get"name"() (e.g., GetPoints()). */ #define mitkGetObjectMacroConst(name, type) \ virtual type *Get##name() const \ { \ itkDebugMacro("returning " #name " address " << this->m_##name); \ return this->m_##name.GetPointer(); \ } /** Creates a Clone() method for "Classname". Returns a smartPtr of a clone of the calling object*/ #define mitkCloneMacro(classname) \ virtual itk::LightObject::Pointer InternalClone() const override \ \ { \ Pointer smartPtr = new classname(*this); \ smartPtr->UnRegister(); \ return smartPtr.GetPointer(); \ } /** cross-platform deprecation macro \todo maybe there is something in external toolkits (ITK, VTK,...) that we could reulse -- would be much preferable */ #ifdef MITK_NO_DEPRECATED_WARNINGS #define DEPRECATED(func) func #elif defined(__GNUC__) #define DEPRECATED(...) __VA_ARGS__ __attribute__((deprecated)) #elif defined(_MSC_VER) #define DEPRECATED(...) __declspec(deprecated)##__VA_ARGS__ #else #pragma message("WARNING: You need to implement DEPRECATED for your compiler!") #define DEPRECATED(func) func #endif /** * Mark templates as exported to generate public RTTI symbols which are * needed for GCC and Clang to support e.g. dynamic_cast between DSOs. */ #if defined(__clang__) || defined(__GNUC__) #define MITK_EXPORT __attribute__((visibility("default"))) #define MITK_IMPORT __attribute__((visibility("default"))) #define MITK_LOCAL __attribute__((visibility("hidden"))) #elif defined(WIN32) #define MITK_EXPORT __declspec(dllexport) #define MITK_IMPORT __declspec(dllimport) #define MITK_LOCAL #else #define MITK_EXPORT #define MITK_IMPORT #define MITK_LOCAL #endif #endif // MITK_COMMON_H_DEFINED diff --git a/Modules/Core/include/mitkCompareImageDataFilter.h b/Modules/Core/include/mitkCompareImageDataFilter.h index ba19b64e8a..4acbb3fc5e 100644 --- a/Modules/Core/include/mitkCompareImageDataFilter.h +++ b/Modules/Core/include/mitkCompareImageDataFilter.h @@ -1,108 +1,108 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKCOMPAREIMAGEDATAFILTER_H #define MITKCOMPAREIMAGEDATAFILTER_H // MITK #include "mitkImage.h" #include "mitkImageToImageFilter.h" // ITK #include namespace mitk { /** * @brief A simple struct to hold the result of the comparison filter. */ struct CompareFilterResults { void PrintSelf() { if (!m_FilterCompleted) { MITK_INFO << "Comparison filter terminated due to an exception: \n " << m_ExceptionMessage; return; } MITK_INFO << "Min. difference: " << m_MinimumDifference << "\n" << "Max. difference: " << m_MaximumDifference << "\n" << "Total difference: " << m_TotalDifference << "\n" << "Mean difference: " << m_MeanDifference << "\n" << "Number of pixels with differences: " << m_PixelsWithDifference; } double m_MinimumDifference; double m_MaximumDifference; double m_TotalDifference; double m_MeanDifference; size_t m_PixelsWithDifference; bool m_FilterCompleted; std::string m_ExceptionMessage; }; /** * @brief Filter for comparing two mitk::Image objects by pixel values * * The comparison is pixel-wise, the filter uses the itk::Testing::ComparisonImageFilter * to find differences. The filter expects two images as input, provide them by using the SetInput( int, mitk::Image) * method. */ class MITKCORE_EXPORT CompareImageDataFilter : public ImageToImageFilter { public: mitkClassMacro(CompareImageDataFilter, ImageToImageFilter); itkSimpleNewMacro(Self); /** * @brief Get the result of the comparison * * The method compares only the number of pixels with differences. It returns true if the amount * is under the specified threshold. To get the complete results, use the GetCompareResults method. * - * Returns false also if the itk ComparisionImageFilter raises an exception during update. + * Returns false also if the itk ComparisonImageFilter raises an exception during update. * * @param threshold Allowed amount of pixels with differences */ bool GetResult(size_t threshold = 0); /** - * @brief Get the detailed results of the comparision run + * @brief Get the detailed results of the comparison run * * @sa CompareFilterResults */ CompareFilterResults GetCompareResults() { return m_CompareDetails; } void SetTolerance(double eps) { m_Tolerance = eps; } protected: CompareImageDataFilter(); ~CompareImageDataFilter() override {} void GenerateData() override; - /*! \brief Method resets the compare detail memeber struct to its initial state */ + /*! \brief Method resets the compare detail member struct to its initial state */ void ResetCompareResultsToInitial(); - /** ITK-like method which calls the ComparisionFilter on the two inputs of the filter */ + /** ITK-like method which calls the ComparisonFilter on the two inputs of the filter */ template void EstimateValueDifference(const itk::Image *itkImage1, const mitk::Image *referenceImage); bool m_CompareResult; CompareFilterResults m_CompareDetails; double m_Tolerance; }; } // end namespace mitk #endif // MITKCompareImageDataFilter_H diff --git a/Modules/Core/include/mitkCoreObjectFactory.h b/Modules/Core/include/mitkCoreObjectFactory.h index f1bdca80dd..6bcc7442ad 100644 --- a/Modules/Core/include/mitkCoreObjectFactory.h +++ b/Modules/Core/include/mitkCoreObjectFactory.h @@ -1,140 +1,140 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef COREOBJECTFACTORY_H_INCLUDED #define COREOBJECTFACTORY_H_INCLUDED #include #include "mitkCoreObjectFactoryBase.h" #include "mitkFileWriterWithInformation.h" #include namespace mitk { class Event; class LegacyFileReaderService; class LegacyFileWriterService; class LegacyImageWriterService; class MITKCORE_EXPORT CoreObjectFactory : public CoreObjectFactoryBase { public: mitkClassMacro(CoreObjectFactory, CoreObjectFactoryBase); itkFactorylessNewMacro(CoreObjectFactory); Mapper::Pointer CreateMapper(mitk::DataNode *node, MapperSlotId slotId) override; void SetDefaultProperties(mitk::DataNode *node) override; virtual void MapEvent(const mitk::Event *event, const int eventID); virtual void RegisterExtraFactory(CoreObjectFactoryBase *factory); virtual void UnRegisterExtraFactory(CoreObjectFactoryBase *factory); static Pointer GetInstance(); ~CoreObjectFactory() override; /** * @brief This method gets the supported (open) file extensions as string. * * This string can then used by the Qt QFileDialog widget. * * @return The c-string that contains the file extensions * @deprecatedSince{2014_10} See mitk::FileReaderRegistry and QmitkIOUtil */ DEPRECATED(virtual std::string GetFileExtensions() override); /** * @brief get the defined (open) file extension map * * @return the defined (open) file extension map * @deprecatedSince{2014_10} See mitk::FileReaderRegistry and QmitkIOUtil */ DEPRECATED(virtual MultimapType GetFileExtensionsMap() override); /** * @brief This method gets the supported (save) file extensions as string. * * This string can then used by the Qt QFileDialog widget. * * @return The c-string that contains the (save) file extensions * @deprecatedSince{2014_10} See mitk::FileWriterRegistry and QmitkIOUtil */ DEPRECATED(virtual std::string GetSaveFileExtensions() override); /** * @brief get the defined (save) file extension map * * @return the defined (save) file extension map * @deprecatedSince{2014_10} See mitk::FileWriterRegistry and QmitkIOUtil */ MultimapType GetSaveFileExtensionsMap() override; /** * @deprecatedSince{2014_10} See mitk::FileWriterRegistry */ DEPRECATED(virtual FileWriterList GetFileWriters()); /** * @deprecatedSince{2014_10} See mitk::FileWriterRegistry and QmitkIOUtil */ DEPRECATED(std::string GetDescriptionForExtension(const std::string &extension)); protected: CoreObjectFactory(); /** * @brief Merge the input map into the fileExtensionsMap. Duplicate entries are removed * * @param fileExtensionsMap the existing map, it contains value pairs like * ("*.dcm", "DICOM files"),("*.dc3", "DICOM files"). - * This map is extented/merged with the values from the input map. + * This map is extended/merged with the values from the input map. * @param inputMap the input map, it contains value pairs like ("*.dcm", * "DICOM files"),("*.dc3", "DICOM files") returned by the extra factories. * @deprecatedSince{2014_10} */ void MergeFileExtensions(MultimapType &fileExtensionsMap, MultimapType inputMap); /** * @brief initialize the file extension entries for open and save * @deprecatedSince{2014_10} */ void CreateFileExtensionsMap(); /** * @deprecatedSince{2014_10} */ DEPRECATED(void CreateSaveFileExtensions()); typedef std::set ExtraFactoriesContainer; ExtraFactoriesContainer m_ExtraFactories; FileWriterList m_FileWriters; std::string m_FileExtensions; MultimapType m_FileExtensionsMap; std::string m_SaveFileExtensions; MultimapType m_SaveFileExtensionsMap; private: void RegisterLegacyReaders(mitk::CoreObjectFactoryBase *factory); void RegisterLegacyWriters(mitk::CoreObjectFactoryBase *factory); void UnRegisterLegacyReaders(mitk::CoreObjectFactoryBase *factory); void UnRegisterLegacyWriters(mitk::CoreObjectFactoryBase *factory); std::map> m_LegacyReaders; std::map> m_LegacyWriters; }; } // namespace mitk #endif diff --git a/Modules/Core/include/mitkCustomMimeType.h b/Modules/Core/include/mitkCustomMimeType.h index 5e609a81aa..1a550cff2f 100644 --- a/Modules/Core/include/mitkCustomMimeType.h +++ b/Modules/Core/include/mitkCustomMimeType.h @@ -1,131 +1,131 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKCUSTOMMIMETYPE_H #define MITKCUSTOMMIMETYPE_H #include #include #include #include namespace mitk { class MimeType; /** * @ingroup IO * @ingroup MicroServices_Interfaces * * @brief The CustomMimeType class represents a custom mime-type which * may be registered as a service object. It should only be used for mime-type registration, * see also mitk::MimeType. * * Instances of this class are usually created and registered as a service. * They act as meta data information to allow the linking of files to reader and writer. * They write files to specific IFileReader instances and provide data format * meta-data for selecting compatible IFileWriter instances. - * mirk::CustomMimetype should only be used to register mime-types. All other interaction should happen trough + * mirk::CustomMimetype should only be used to register mime-types. All other interaction should happen through * mitk::MimeTypeProvider, from which registered mimetypes can be pulled. mitk::MimeType provides a safe and * memory-managed * way of interacting with Mimetypes. */ class MITKCORE_EXPORT CustomMimeType { public: CustomMimeType(); CustomMimeType(const std::string &name); CustomMimeType(const CustomMimeType &other); explicit CustomMimeType(const MimeType &other); virtual ~CustomMimeType(); CustomMimeType &operator=(const CustomMimeType &other); CustomMimeType &operator=(const MimeType &other); /** * \brief Returns the unique name for the MimeType. */ std::string GetName() const; /** * \brief Returns the human-readable Category of the mime-type. Allows grouping of similar mime-types (like Surfaces) */ std::string GetCategory() const; /** * \brief Returns all extensions that this MimeType can handle. */ std::vector GetExtensions() const; /** * \brief Returns the Human readable comment of the MimeType, a string that describes its unique role. */ std::string GetComment() const; /** * \brief Checks if the MimeType can handle file at the given location. * * In its base implementation, this function exclusively looks a the given string. * However, child classes can override this behaviour and peek into the file. */ virtual bool AppliesTo(const std::string &path) const; /** - * \brief Checks if the MimeType can handle the etension of the given path + * \brief Checks if the MimeType can handle the extension of the given path * * This function exclusively looks a the given string */ bool MatchesExtension(const std::string &path) const; /** * \brief Provides the first matching extension * * Checks whether any of its extensions are present at the end of the provided path. * Returns the first found one. */ std::string GetExtension(const std::string &path) const; /** * \brief Provides the filename minus the extension * * Checks whether any of its extensions are present at the end of the provided path. * Returns the filename without that extension and without the directory. */ std::string GetFilenameWithoutExtension(const std::string &path) const; void SetName(const std::string &name); void SetCategory(const std::string &category); void SetExtension(const std::string &extension); void AddExtension(const std::string &extension); void SetComment(const std::string &comment); void Swap(CustomMimeType &r); virtual CustomMimeType *Clone() const; private: // returns true if an extension was found bool ParsePathForExtension(const std::string &path, std::string &extension, std::string &filename) const; struct Impl; Impl *d; }; void swap(CustomMimeType &l, CustomMimeType &r); } MITK_DECLARE_SERVICE_INTERFACE(mitk::CustomMimeType, "org.mitk.CustomMimeType") #endif // MITKCUSTOMMIMETYPE_H diff --git a/Modules/Core/include/mitkDataNode.h b/Modules/Core/include/mitkDataNode.h index b90c2e03e8..64a1da0297 100644 --- a/Modules/Core/include/mitkDataNode.h +++ b/Modules/Core/include/mitkDataNode.h @@ -1,618 +1,618 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef DATATREENODE_H_HEADER_INCLUDED_C1E14338 #define DATATREENODE_H_HEADER_INCLUDED_C1E14338 #include "mitkBaseData.h" //#include "mitkMapper.h" #include "mitkDataInteractor.h" #include "mitkIdentifiable.h" #include "mitkIPropertyOwner.h" #include #include #include "mitkColorProperty.h" #include "mitkPropertyList.h" #include "mitkStringProperty.h" //#include "mitkMapper.h" #include "mitkGeometry3D.h" #include "mitkLevelWindow.h" #include #include class vtkLinearTransform; namespace mitk { class BaseRenderer; class Mapper; /** * \brief Definition of an itk::Event that is invoked when * a DataInteractor is set on this DataNode. */ itkEventMacroDeclaration(InteractorChangedEvent, itk::AnyEvent); /** * \brief Class for nodes of the DataTree * * Contains the data (instance of BaseData), a list of mappers, which can * draw the data, a transform (vtkTransform) and a list of properties * (PropertyList). * \ingroup DataManagement * * \todo clean up all the GetProperty methods. There are too many different flavours... Can most probably be reduced * to * bool GetProperty(type&) * * \warning Change in semantics of SetProperty() since Aug 25th 2006. Check your usage of this method if you do * more with properties than just call SetProperty( "key", new SomeProperty("value") ). */ class MITKCORE_EXPORT DataNode : public itk::DataObject, public IPropertyOwner { public: typedef mitk::Geometry3D::Pointer Geometry3DPointer; typedef std::vector> MapperVector; typedef std::map MapOfPropertyLists; typedef std::vector PropertyListKeyNames; typedef std::set GroupTagList; mitkClassMacroItkParent(DataNode, itk::DataObject); itkFactorylessNewMacro(Self); // IPropertyProvider BaseProperty::ConstPointer GetConstProperty(const std::string &propertyKey, const std::string &contextName = "", bool fallBackOnDefaultContext = true) const override; std::vector GetPropertyKeys(const std::string &contextName = "", bool includeDefaultContext = false) const override; std::vector GetPropertyContextNames() const override; // IPropertyOwner BaseProperty * GetNonConstProperty(const std::string &propertyKey, const std::string &contextName = "", bool fallBackOnDefaultContext = true) override; void SetProperty(const std::string &propertyKey, BaseProperty *property, const std::string &contextName = "", bool fallBackOnDefaultContext = false) override; void RemoveProperty(const std::string &propertyKey, const std::string &contextName = "", bool fallBackOnDefaultContext = false) override; mitk::Mapper *GetMapper(MapperSlotId id) const; /** * \brief Get the data object (instance of BaseData, e.g., an Image) * managed by this DataNode */ BaseData *GetData() const; /** * \brief Get the transformation applied prior to displaying the data as * a vtkTransform * \deprecated use GetData()->GetGeometry()->GetVtkTransform() instead */ vtkLinearTransform *GetVtkTransform(int t = 0) const; /** * \brief Set the data object (instance of BaseData, e.g., an Image) * managed by this DataNode * * Prior set properties are kept if previous data of the node already exists and has the same * type as the new data to be set. Otherwise, the default properties are used. * In case that previous data already exists, the property list of the data node is cleared * before setting new default properties. * * \warning the actor-mode of the vtkInteractor does not work any more, if the transform of the * data-tree-node is connected to the transform of the basedata via vtkTransform->SetInput. */ virtual void SetData(mitk::BaseData *baseData); /** * \brief Set the Interactor. */ virtual void SetDataInteractor(const DataInteractor::Pointer interactor); virtual DataInteractor::Pointer GetDataInteractor() const; mitk::DataNode &operator=(const DataNode &right); mitk::DataNode &operator=(BaseData *right); virtual void SetMapper(MapperSlotId id, mitk::Mapper *mapper); void UpdateOutputInformation() override; void SetRequestedRegionToLargestPossibleRegion() override; bool RequestedRegionIsOutsideOfTheBufferedRegion() override; bool VerifyRequestedRegion() override; void SetRequestedRegion(const itk::DataObject *data) override; void CopyInformation(const itk::DataObject *data) override; /** * \brief The "names" used for (renderer-specific) PropertyLists in GetPropertyList(string). * * All possible values for the "renderer" parameters of * the diverse GetProperty/List() methods. */ PropertyListKeyNames GetPropertyListNames() const; /** * \brief Set the property (instance of BaseProperty) with key \a propertyKey in the PropertyList * of the \a renderer (if nullptr, use BaseRenderer-independent PropertyList). This is set-by-value. * * \warning Change in semantics since Aug 25th 2006. Check your usage of this method if you do * more with properties than just call SetProperty( "key", new SomeProperty("value") ). * * \sa GetProperty * \sa m_PropertyList * \sa m_MapOfPropertyLists */ void SetProperty(const char *propertyKey, BaseProperty *property, const mitk::BaseRenderer *renderer = nullptr); /** * \brief Replace the property (instance of BaseProperty) with key \a propertyKey in the PropertyList * of the \a renderer (if nullptr, use BaseRenderer-independent PropertyList). This is set-by-reference. * * If \a renderer is \a nullptr the property is set in the BaseRenderer-independent * PropertyList of this DataNode. * \sa GetProperty * \sa m_PropertyList * \sa m_MapOfPropertyLists */ void ReplaceProperty(const char *propertyKey, BaseProperty *property, const mitk::BaseRenderer *renderer = nullptr); /** * \brief Add the property (instance of BaseProperty) if it does * not exist (or always if\a overwrite is\a true) * with key \a propertyKey in the PropertyList * of the \a renderer (if nullptr, use BaseRenderer-independent * PropertyList). This is set-by-value. * * For\a overwrite ==\a false the property is\em not changed * if it already exists. For\a overwrite ==\a true the method * is identical to SetProperty. * * \sa SetProperty * \sa GetProperty * \sa m_PropertyList * \sa m_MapOfPropertyLists */ void AddProperty(const char *propertyKey, BaseProperty *property, const mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); /** * \brief Get the PropertyList of the \a renderer. If \a renderer is \a * nullptr, the BaseRenderer-independent PropertyList of this DataNode * is returned. * \sa GetProperty * \sa m_PropertyList * \sa m_MapOfPropertyLists */ mitk::PropertyList *GetPropertyList(const mitk::BaseRenderer *renderer = nullptr) const; mitk::PropertyList *GetPropertyList(const std::string &rendererName) const; /** * \brief Add values from another PropertyList. * * Overwrites values in m_PropertyList only when possible (i.e. when types are compatible). * If you want to allow for object type changes (replacing a "visible":BoolProperty with "visible":IntProperty, * set \c replace . * * \param replace true: if \param pList contains a property "visible" of type ColorProperty and our m_PropertyList * also has a "visible" property of a different type (e.g. BoolProperty), change the type, i.e. replace the objects * behind the pointer. * * \sa SetProperty * \sa ReplaceProperty * \sa m_PropertyList */ void ConcatenatePropertyList(PropertyList *pList, bool replace = false); /** * \brief Get the property (instance of BaseProperty) with key \a propertyKey from the PropertyList * of the \a renderer, if available there, otherwise use the BaseRenderer-independent PropertyList. * * If \a renderer is \a nullptr or the \a propertyKey cannot be found * in the PropertyList specific to \a renderer or is disabled there, the BaseRenderer-independent * PropertyList of this DataNode is queried. * * If \a fallBackOnDataProperties is true, the data property list is queried as a last resort. * * \sa GetPropertyList * \sa m_PropertyList * \sa m_MapOfPropertyLists */ mitk::BaseProperty *GetProperty(const char *propertyKey, const mitk::BaseRenderer *renderer = nullptr, bool fallBackOnDataProperties = true) const; /** * \brief Get the property of type T with key \a propertyKey from the PropertyList * of the \a renderer, if available there, otherwise use the BaseRenderer-independent PropertyList. * * If \a renderer is \a nullptr or the \a propertyKey cannot be found * in the PropertyList specific to \a renderer or is disabled there, the BaseRenderer-independent * PropertyList of this DataNode is queried. * \sa GetPropertyList * \sa m_PropertyList * \sa m_MapOfPropertyLists */ template bool GetProperty(itk::SmartPointer &property, const char *propertyKey, const mitk::BaseRenderer *renderer = nullptr) const { property = dynamic_cast(GetProperty(propertyKey, renderer)); return property.IsNotNull(); } /** * \brief Get the property of type T with key \a propertyKey from the PropertyList * of the \a renderer, if available there, otherwise use the BaseRenderer-independent PropertyList. * * If \a renderer is \a nullptr or the \a propertyKey cannot be found * in the PropertyList specific to \a renderer or is disabled there, the BaseRenderer-independent * PropertyList of this DataNode is queried. * \sa GetPropertyList * \sa m_PropertyList * \sa m_MapOfPropertyLists */ template bool GetProperty(T *&property, const char *propertyKey, const mitk::BaseRenderer *renderer = nullptr) const { property = dynamic_cast(GetProperty(propertyKey, renderer)); return property != nullptr; } /** * \brief Convenience access method for GenericProperty properties * (T being the type of the second parameter) * \return \a true property was found */ template bool GetPropertyValue(const char *propertyKey, T &value, const mitk::BaseRenderer *renderer = nullptr) const { GenericProperty *gp = dynamic_cast *>(GetProperty(propertyKey, renderer)); if (gp != nullptr) { value = gp->GetValue(); return true; } return false; } /// \brief Get a set of all group tags from this node's property list GroupTagList GetGroupTags() const; /** * \brief Convenience access method for bool properties (instances of * BoolProperty) * \return \a true property was found */ bool GetBoolProperty(const char *propertyKey, bool &boolValue, const mitk::BaseRenderer *renderer = nullptr) const; /** * \brief Convenience access method for int properties (instances of * IntProperty) * \return \a true property was found */ bool GetIntProperty(const char *propertyKey, int &intValue, const mitk::BaseRenderer *renderer = nullptr) const; /** * \brief Convenience access method for float properties (instances of * FloatProperty) * \return \a true property was found */ bool GetFloatProperty(const char *propertyKey, float &floatValue, const mitk::BaseRenderer *renderer = nullptr) const; /** * \brief Convenience access method for double properties (instances of * DoubleProperty) * * If there is no DoubleProperty for the given\c propertyKey argument, the method * looks for a corresponding FloatProperty instance. * * \return \a true property was found */ bool GetDoubleProperty(const char *propertyKey, double &doubleValue, const mitk::BaseRenderer *renderer = nullptr) const; /** * \brief Convenience access method for string properties (instances of * StringProperty) * \return \a true property was found */ bool GetStringProperty(const char *propertyKey, std::string &string, const mitk::BaseRenderer *renderer = nullptr) const; /** * \brief Convenience access method for color properties (instances of * ColorProperty) * \return \a true property was found */ bool GetColor(float rgb[3], const mitk::BaseRenderer *renderer = nullptr, const char *propertyKey = "color") const; /** * \brief Convenience access method for level-window properties (instances of * LevelWindowProperty) * \return \a true property was found */ bool GetLevelWindow(mitk::LevelWindow &levelWindow, const mitk::BaseRenderer *renderer = nullptr, const char *propertyKey = "levelwindow") const; /** * \brief set the node as selected */ void SetSelected(bool selected, const mitk::BaseRenderer *renderer = nullptr); /** * \brief set the node as selected * \return \a true node is selected */ bool IsSelected(const mitk::BaseRenderer *renderer = nullptr); /** * \brief Convenience access method for accessing the name of an object (instance of * StringProperty with property-key "name") * \return \a true property was found */ bool GetName(std::string &nodeName, const mitk::BaseRenderer *renderer = nullptr, const char *propertyKey = "name") const { return GetStringProperty(propertyKey, nodeName, renderer); } /** * \brief Extra convenience access method for accessing the name of an object (instance of * StringProperty with property-key "name"). * * This method does not take the renderer specific * propertylists into account, because the name of an object should never be renderer specific. * \returns a std::string with the name of the object (content of "name" Property). * If there is no "name" Property, an empty string will be returned. */ virtual std::string GetName() const { mitk::StringProperty *sp = dynamic_cast(this->GetProperty("name")); if (sp == nullptr) return ""; return sp->GetValue(); } /** Value constant that is used indicate that node names are not set so far.*/ static std::string NO_NAME_VALUE() { return "No Name!"; } /** * \brief Extra convenience access method to set the name of an object. * * If the data has already a "name" property, the name will be stored in it. Otherwise, the name will be stored in * the non-renderer-specific PropertyList in a StringProperty named "name". */ virtual void SetName(const char *name) { if (name == nullptr) return; auto* data = this->GetData(); if (nullptr != data) { auto property = data->GetProperty("name"); if (property.IsNotNull()) { auto* stringProperty = dynamic_cast(property.GetPointer()); if (nullptr != stringProperty) { stringProperty->SetValue(name); return; } } } this->SetStringProperty("name", name); } /** * \brief Extra convenience access method to set the name of an object. * * \sa SetName(const char*) */ virtual void SetName(const std::string& name) { this->SetName(name.c_str()); } /** * \brief Convenience access method for visibility properties (instances * of BoolProperty with property-key "visible") * \return \a true property was found * \sa IsVisible */ bool GetVisibility(bool &visible, const mitk::BaseRenderer *renderer, const char *propertyKey = "visible") const { return GetBoolProperty(propertyKey, visible, renderer); } /** * \brief Convenience access method for opacity properties (instances of * FloatProperty) * \return \a true property was found */ bool GetOpacity(float &opacity, const mitk::BaseRenderer *renderer, const char *propertyKey = "opacity") const; /** * \brief Convenience access method for boolean properties (instances * of BoolProperty). Return value is the value of the property. If the property is * not found, the value of \a defaultIsOn is returned. * * Thus, the return value has a different meaning than in the * GetBoolProperty method! * \sa GetBoolProperty */ bool IsOn(const char *propertyKey, const mitk::BaseRenderer *renderer, bool defaultIsOn = true) const { if (propertyKey == nullptr) return defaultIsOn; GetBoolProperty(propertyKey, defaultIsOn, renderer); return defaultIsOn; } /** * \brief Convenience access method for visibility properties (instances * of BoolProperty). Return value is the visibility. Default is * visible==true, i.e., true is returned even if the property (\a * propertyKey) is not found. * * Thus, the return value has a different meaning than in the * GetVisibility method! * \sa GetVisibility * \sa IsOn */ bool IsVisible(const mitk::BaseRenderer *renderer, const char *propertyKey = "visible", bool defaultIsOn = true) const { return IsOn(propertyKey, renderer, defaultIsOn); } /** * \brief Convenience method for setting color properties (instances of * ColorProperty) */ void SetColor(const mitk::Color &color, const mitk::BaseRenderer *renderer = nullptr, const char *propertyKey = "color"); /** * \brief Convenience method for setting color properties (instances of * ColorProperty) */ void SetColor(float red, float green, float blue, const mitk::BaseRenderer *renderer = nullptr, const char *propertyKey = "color"); /** * \brief Convenience method for setting color properties (instances of * ColorProperty) */ void SetColor(const float rgb[3], const mitk::BaseRenderer *renderer = nullptr, const char *propertyKey = "color"); /** * \brief Convenience method for setting visibility properties (instances * of BoolProperty) * \param visible If set to true, the data will be rendered. If false, the render will skip this data. * \param renderer Specify a renderer if the visibility shall be specific to a renderer - * \param propertyKey Can be used to specify a user defined name of the visibility propery. + * \param propertyKey Can be used to specify a user defined name of the visibility property. */ void SetVisibility(bool visible, const mitk::BaseRenderer *renderer = nullptr, const char *propertyKey = "visible"); /** * \brief Convenience method for setting opacity properties (instances of * FloatProperty) */ void SetOpacity(float opacity, const mitk::BaseRenderer *renderer = nullptr, const char *propertyKey = "opacity"); /** * \brief Convenience method for setting level-window properties * (instances of LevelWindowProperty) */ void SetLevelWindow(mitk::LevelWindow levelWindow, const mitk::BaseRenderer *renderer = nullptr, const char *propertyKey = "levelwindow"); /** * \brief Convenience method for setting int properties (instances of * IntProperty) */ void SetIntProperty(const char *propertyKey, int intValue, const mitk::BaseRenderer *renderer = nullptr); /** * \brief Convenience method for setting boolean properties (instances of * BoolProperty) */ void SetBoolProperty(const char *propertyKey, bool boolValue, const mitk::BaseRenderer *renderer = nullptr); /** * \brief Convenience method for setting float properties (instances of * FloatProperty) */ void SetFloatProperty(const char *propertyKey, float floatValue, const mitk::BaseRenderer *renderer = nullptr); /** * \brief Convenience method for setting double properties (instances of * DoubleProperty) */ void SetDoubleProperty(const char *propertyKey, double doubleValue, const mitk::BaseRenderer *renderer = nullptr); /** * \brief Convenience method for setting string properties (instances of * StringProperty) */ void SetStringProperty(const char *propertyKey, const char *string, const mitk::BaseRenderer *renderer = nullptr); /** * \brief Get the timestamp of the last change of the contents of this node or * the referenced BaseData. */ itk::ModifiedTimeType GetMTime() const override; /** * \brief Get the timestamp of the last change of the reference to the * BaseData. */ unsigned long GetDataReferenceChangedTime() const { return m_DataReferenceChangedTime.GetMTime(); } protected: DataNode(); ~DataNode() override; /// Invoked when the property list was modified. Calls Modified() of the DataNode virtual void PropertyListModified(const itk::Object *caller, const itk::EventObject &event); /// \brief Mapper-slots mutable MapperVector m_Mappers; /** * \brief The data object (instance of BaseData, e.g., an Image) managed * by this DataNode */ BaseData::Pointer m_Data; /** * \brief BaseRenderer-independent PropertyList * * Properties herein can be overwritten specifically for each BaseRenderer * by the BaseRenderer-specific properties defined in m_MapOfPropertyLists. */ PropertyList::Pointer m_PropertyList; /// \brief Map associating each BaseRenderer with its own PropertyList mutable MapOfPropertyLists m_MapOfPropertyLists; DataInteractor::Pointer m_DataInteractor; /// \brief Timestamp of the last change of m_Data itk::TimeStamp m_DataReferenceChangedTime; unsigned long m_PropertyListModifiedObserverTag; }; MITKCORE_EXPORT std::istream &operator>>(std::istream &i, DataNode::Pointer &dtn); MITKCORE_EXPORT std::ostream &operator<<(std::ostream &o, DataNode::Pointer &dtn); } // namespace mitk #endif /* DATATREENODE_H_HEADER_INCLUDED_C1E14338 */ diff --git a/Modules/Core/include/mitkDataNodeSource.h b/Modules/Core/include/mitkDataNodeSource.h index 5f55e1be01..0823971f56 100644 --- a/Modules/Core/include/mitkDataNodeSource.h +++ b/Modules/Core/include/mitkDataNodeSource.h @@ -1,72 +1,72 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_DATA_TREE_NODE_SOURCE_H #define _MITK_DATA_TREE_NODE_SOURCE_H #include "itkProcessObject.h" #include "mitkDataNode.h" namespace mitk { /** * @brief Superclass of all classes generating data tree nodes (instances of class * mitk::DataNode) as output. * * In itk and vtk the generated result of a ProcessObject is only guaranteed * to be up-to-date, when Update() of the ProcessObject or the generated * DataObject is called immediately before access of the data stored in the * DataObject. This is also true for subclasses of mitk::BaseProcess and thus * for mitk::DataNodeSource. * @ingroup Process */ class MITKCORE_EXPORT DataNodeSource : public itk::ProcessObject { public: mitkClassMacroItkParent(DataNodeSource, itk::ProcessObject); itkFactorylessNewMacro(Self); itkCloneMacro(Self); typedef mitk::DataNode OutputType; typedef OutputType::Pointer OutputTypePointer; /** * Allocates a new output object and returns it. Currently the * index idx is not evaluated. * @param idx the index of the output for which an object should be created * @returns the new object */ DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) override; /** * This is a default implementation to make sure we have something. - * Once all the subclasses of ProcessObject provide an appopriate + * Once all the subclasses of ProcessObject provide an appropriate * MakeOutput(), then ProcessObject::MakeOutput() can be made pure * virtual. */ DataObjectPointer MakeOutput(const DataObjectIdentifierType &name) override; OutputType *GetOutput(); const OutputType *GetOutput() const; OutputType *GetOutput(DataObjectPointerArraySizeType idx); const OutputType *GetOutput(DataObjectPointerArraySizeType idx) const; protected: DataNodeSource(); ~DataNodeSource() override; }; } #endif // #define _MITK_BASE_DATA_SOURCE_H diff --git a/Modules/Core/include/mitkDataStorage.h b/Modules/Core/include/mitkDataStorage.h index b884a7b12d..a0d1c42fc9 100644 --- a/Modules/Core/include/mitkDataStorage.h +++ b/Modules/Core/include/mitkDataStorage.h @@ -1,442 +1,442 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKDATASTORAGE_H #define MITKDATASTORAGE_H #include "itkObject.h" #include "itkVectorContainer.h" #include "mitkDataNode.h" #include "mitkGeometry3D.h" #include "mitkMessage.h" #include #include #include namespace mitk { class NodePredicateBase; class DataNode; class BaseRenderer; //##Documentation //## @brief Data management class that handles 'was created by' relations //## //## The DataStorage provides data storage and management functionality. //## It handles a 'was created by' relation by associating each data object with a //## set of source objects, that this object was created from. //## Thus, nodes are stored in a noncyclical directed graph data structure. //## If a new node is added to the DataStorage, AddNodeEvent is emitted. //## If a node is removed, RemoveNodeEvent is emitted. //## //## //## \ingroup DataStorage class MITKCORE_EXPORT DataStorage : public itk::Object { public: mitkClassMacroItkParent(DataStorage, itk::Object); //##Documentation //## @brief A Container of objects that is used as a result set of GetSubset() query operations (Set of //SmartPointers // to DataNodes). typedef itk::VectorContainer SetOfObjects; //##Documentation //## @brief Adds a DataNode containing a data object to its internal storage //## //## This Method adds a new data object to the DataStorage. The new object is //## passed in the first parameter. The second parameter is a set //## of source objects, that were used to create this object. The new object will have //## a 'was created from' relation to its source objects. //## the addition of a new object will fire the notification mechanism. //## If the node parameter is nullptr or if the DataNode has already been added, //## an exception will be thrown. virtual void Add(DataNode *node, const DataStorage::SetOfObjects *parents = nullptr) = 0; //##Documentation //## @brief Convenience method to add a node that has one parent //## void Add(DataNode *node, DataNode *parent); //##Documentation //## @brief Removes node from the DataStorage //## virtual void Remove(const DataNode *node) = 0; //##Documentation //## @brief Checks if a node exists in the DataStorage //## virtual bool Exists(const DataNode *node) const = 0; //##Documentation //## @brief Removes a set of nodes from the DataStorage //## void Remove(const DataStorage::SetOfObjects *nodes); //##Documentation //## @brief returns a set of data objects that meet the given condition(s) //## //## GetSubset returns a set of objects with a specific data type that meet the condition(s) //## specified in the condition parameter. Conditions can be //## - data type of the data object //## - is source object of specific object (e.g. all source objects of node x) //## - has property with specific value (e.g. OrganType is Liver) //## - negation of any condition //## - conjunction of a set of conditions //## - disjunction of a set of conditions //## Conditions are implemented as predicates using the Composite Design Pattern //## (see definition of NodePredicateBase for details). //## The method returns a set of SmartPointers to the DataNodes that fulfill the //## conditions. A set of all objects can be retrieved with the GetAll() method; SetOfObjects::ConstPointer GetSubset(const NodePredicateBase *condition) const; //##Documentation //## @brief returns a set of source objects for a given node that meet the given condition(s). //## virtual SetOfObjects::ConstPointer GetSources(const DataNode *node, const NodePredicateBase *condition = nullptr, bool onlyDirectSources = true) const = 0; //##Documentation //## @brief returns a set of derived objects for a given node. //## //## GetDerivations() returns a set of objects that are derived from the DataNode node. //## This means, that node was used to create the returned objects. If the parameter //## onlyDirectDerivations is set to true (default value), only objects that directly have //## node as one of their source objects will be returned. Otherwise, objects that are //## derived from derivations of node are returned too. //## The derived objects can be filtered with a predicate object as described in the GetSubset() //## method by providing a predicate as the condition parameter. virtual SetOfObjects::ConstPointer GetDerivations(const DataNode *node, const NodePredicateBase *condition = nullptr, bool onlyDirectDerivations = true) const = 0; //##Documentation //## @brief returns a set of all data objects that are stored in the data storage //## virtual SetOfObjects::ConstPointer GetAll() const = 0; //##Documentation //## @brief Convenience method to get the first node that matches the predicate condition //## DataNode *GetNode(const NodePredicateBase *condition = nullptr) const; //##Documentation //## @brief Convenience method to get the first node with a given name //## DataNode *GetNamedNode(const char *name) const; //##Documentation //## @brief Convenience method to get the first node with a given name //## DataNode *GetNamedNode(const std::string name) const { return this->GetNamedNode(name.c_str()); } //##Documentation //## @brief Convenience method to get the first node with a given name that is derived from sourceNode //## DataNode *GetNamedDerivedNode(const char *name, const DataNode *sourceNode, bool onlyDirectDerivations = true) const; //##Documentation //## @brief Convenience method to get the first data object of a given data type with a given name //## template DataType *GetNamedObject(const char *name) const { if (name == nullptr) return nullptr; DataNode *n = this->GetNamedNode(name); if (n == nullptr) return nullptr; else return dynamic_cast(n->GetData()); } //##Documentation //## @brief Convenience method to get the first data object of a given data type with a given name //## template DataType *GetNamedObject(const std::string name) const { return this->GetNamedObject(name.c_str()); } //##Documentation //## @brief Convenience method to get the first data object of a given data type with a given name that is derived // from a specific node //## template DataType *GetNamedDerivedObject(const char *name, const DataNode *sourceNode, bool onlyDirectDerivations = true) const { if (name == nullptr) return nullptr; DataNode *n = this->GetNamedDerivedNode(name, sourceNode, onlyDirectDerivations); if (n == nullptr) return nullptr; else return dynamic_cast(n->GetData()); } //##Documentation //## @brief Returns a list of used grouptags //## const DataNode::GroupTagList GetGroupTags() const; /*ITK Mutex */ mutable std::mutex m_MutexOne; /* Public Events */ typedef Message1 DataStorageEvent; //##Documentation //## @brief AddEvent is emitted whenever a new node has been added to the DataStorage. //## //## Observers should register to this event by calling myDataStorage->AddNodeEvent.AddListener(myObject, // MyObject::MyMethod). //## After registering, myObject->MyMethod() will be called every time a new node has been added to the DataStorage. //## Observers should unregister by calling myDataStorage->AddNodeEvent.RemoveListener(myObject, //MyObject::MyMethod). //## Note: AddEvents are _not_ emitted if a node is added to DataStorage by adding it to the the underlying //DataTree! // member variable is not needed to be locked in multi threaded scenarios since the DataStorageEvent is a typedef // for // a Message1 object which is thread safe DataStorageEvent AddNodeEvent; //##Documentation //## @brief RemoveEvent is emitted directly before a node is removed from the DataStorage. //## //## Observers should register to this event by calling myDataStorage->RemoveNodeEvent.AddListener(myObject, // MyObject::MyMethod). //## After registering, myObject->MyMethod() will be called every time a new node has been added to the DataStorage. //## Observers should unregister by calling myDataStorage->RemoveNodeEvent.RemoveListener(myObject, // MyObject::MyMethod). //## Note: RemoveEvents are also emitted if a node was removed from the DataStorage by deleting it from the //underlying // DataTree // member variable is not needed to be locked in multi threaded scenarios since the DataStorageEvent is a typedef // for // a Message1 object which is thread safe DataStorageEvent RemoveNodeEvent; //##Documentation //## @brief ChangedEvent is emitted directly after a node was changed. //## //## Observers should register to this event by calling myDataStorage->ChangedNodeEvent.AddListener(myObject, // MyObject::MyMethod). //## After registering, myObject->MyMethod() will be called every time a new node has been changed. //## Observers should unregister by calling myDataStorage->ChangedNodeEvent.RemoveListener(myObject, // MyObject::MyMethod). //## Internally the DataStorage listens to itk::ModifiedEvents on the nodes and forwards them //## to the listeners of this event. // member variable is not needed to be locked in multi threaded scenarios since the DataStorageEvent is a typedef // for // a Message1 object which is thread safe DataStorageEvent ChangedNodeEvent; //##Documentation //## @brief DeleteNodeEvent is emitted directly before a node is deleted. //## //## Observers should register to this event by calling myDataStorage->DeleteNodeEvent.AddListener(myObject, // MyObject::MyMethod). //## After registering, myObject->MyMethod() will be called when a node is deleted. //## Observers should unregister by calling myDataStorage->DeleteNodeEvent.RemoveListener(myObject, // MyObject::MyMethod). //## Internally the DataStorage listens to itk::DeleteEvents on the nodes and forwards them //## to the listeners of this event. // member variable is not needed to be locked in multi threaded scenarios since the DataStorageEvent is a typedef // for // a Message1 object which is thread safe DataStorageEvent DeleteNodeEvent; DataStorageEvent InteractorChangedNodeEvent; //##Documentation //## @brief Compute the axis-parallel bounding geometry of the input objects //## //## Throws std::invalid_argument exception if input is nullptr //## @param input set of objects of the DataStorage to be included in the bounding geometry //## @param boolPropertyKey if a BoolProperty with this boolPropertyKey exists for a node (for @a renderer) //## and is set to @a false, the node is ignored for the bounding-box calculation. //## @param renderer see @a boolPropertyKey //## @param boolPropertyKey2 a second condition that is applied additionally to @a boolPropertyKey TimeGeometry::ConstPointer ComputeBoundingGeometry3D(const SetOfObjects *input, const char *boolPropertyKey = nullptr, const BaseRenderer *renderer = nullptr, const char *boolPropertyKey2 = nullptr) const; //##Documentation //## @brief Compute the axis-parallel bounding geometry of the data tree //## (bounding box, minimal spacing of the considered nodes, live-span) //## //## it -> an iterator to a data tree structure //## @param boolPropertyKey if a BoolProperty with this boolPropertyKey exists for a node (for @a renderer) //## and is set to @a false, the node is ignored for the bounding-box calculation. //## @param renderer see @a boolPropertyKey //## @param boolPropertyKey2 a second condition that is applied additionally to @a boolPropertyKey TimeGeometry::ConstPointer ComputeBoundingGeometry3D(const char *boolPropertyKey = nullptr, const BaseRenderer *renderer = nullptr, const char *boolPropertyKey2 = nullptr) const; //##Documentation //## @brief Compute the axis-parallel bounding geometry of all visible parts of the //## data tree bounding box, minimal spacing of the considered nodes, live-span) //## //## Simply calls ComputeBoundingGeometry3D(it, "visible", renderer, boolPropertyKey). //## it -> an iterator of a data tree structure //## @param renderer the reference to the renderer //## @param boolPropertyKey if a BoolProperty with this boolPropertyKey exists for a node (for @a renderer) //## and is set to @a false, the node is ignored for the bounding-box calculation. TimeGeometry::ConstPointer ComputeVisibleBoundingGeometry3D(const BaseRenderer *renderer = nullptr, const char *boolPropertyKey = nullptr); //##Documentation //## @brief Compute the bounding box of data tree structure //## it -> an iterator to a data tree structure //## @param boolPropertyKey if a BoolProperty with this boolPropertyKey exists for a node (for @a renderer) //## and is set to @a false, the node is ignored for the bounding-box calculation. //## @param renderer see @a boolPropertyKey //## @param boolPropertyKey2 a second condition that is applied additionally to @a boolPropertyKey BoundingBox::Pointer ComputeBoundingBox(const char *boolPropertyKey = nullptr, const BaseRenderer *renderer = nullptr, const char *boolPropertyKey2 = nullptr); //##Documentation //## \brief Compute the bounding box of all visible parts of the data tree structure, for general //## rendering or renderer specific visibility property checking //## //## Simply calls ComputeBoundingBox(it, "visible", renderer, boolPropertyKey). //## it -> an iterator of a data tree structure //## @param renderer the reference to the renderer //## @param boolPropertyKey if a BoolProperty with this boolPropertyKey exists for a node (for @a renderer) //## and is set to @a false, the node is ignored for the bounding-box calculation. BoundingBox::Pointer ComputeVisibleBoundingBox(const BaseRenderer *renderer = nullptr, const char *boolPropertyKey = nullptr) { return ComputeBoundingBox("visible", renderer, boolPropertyKey); } //##Documentation //## @brief Compute the time-bounds of the contents of a data tree structure //## //## The methods returns only [-infinity, +infinity], if all data-objects have an infinite live-span. Otherwise, //## all data-objects with infinite live-span are ignored. //## it -> an iterator to a data tree structure //## @param boolPropertyKey if a BoolProperty with this boolPropertyKey exists for a node (for @a renderer) //## and is set to @a false, the node is ignored for the time-bounds calculation. //## @param renderer see @a boolPropertyKey //## @param boolPropertyKey2 a second condition that is applied additionally to @a boolPropertyKey TimeBounds ComputeTimeBounds(const char *boolPropertyKey, const BaseRenderer *renderer, const char *boolPropertyKey2); //##Documentation //## @brief Compute the time-bounds of all visible parts of the data tree structure, for general //## rendering or renderer specific visibility property checking //## //## The methods returns only [-infinity, +infinity], if all data-objects have an infinite live-span. Otherwise, //## all data-objects with infinite live-span are ignored. //## Simply calls ComputeTimeBounds(it, "visible", renderer, boolPropertyKey). //## @param boolPropertyKey if a BoolProperty with this boolPropertyKey exists for a node (for @a renderer) //## and is set to @a false, the node is ignored for the time-bounds calculation. //## @param renderer see @a boolPropertyKey TimeBounds ComputeTimeBounds(const BaseRenderer *renderer, const char *boolPropertyKey) { return ComputeTimeBounds("visible", renderer, boolPropertyKey); } //##Documentation //## @brief Defines whether or not NodeChangedEvent is invoked . //## //## This method can be used to set m_BlockNodeModifiedEvents. //## //## If this flag is true, NodeChangedEvent is not invoked when a //## DataNode is modified. This might be undesired when setting //## many properties on a datanode and you do not want anyone to //## react. void BlockNodeModifiedEvents(bool block); protected: //##Documentation //## @brief EmitAddNodeEvent emits the AddNodeEvent //## //## This method should be called by subclasses to emit the AddNodeEvent void EmitAddNodeEvent(const DataNode *node); //##Documentation //## @brief EmitRemoveNodeEvent emits the RemoveNodeEvent //## //## This method should be called by subclasses to emit the RemoveNodeEvent void EmitRemoveNodeEvent(const DataNode *node); void OnNodeInteractorChanged(itk::Object *caller, const itk::EventObject &event); //##Documentation //## @brief OnNodeModified listens to modified events of DataNodes. //## //## The node is hidden behind the caller parameter, which has to be casted first. //## If the cast succeeds the ChangedNodeEvent is emitted with this node. void OnNodeModifiedOrDeleted(const itk::Object *caller, const itk::EventObject &event); //##Documentation //## @brief Adds a Modified-Listener to the given Node. void AddListeners(const DataNode *_Node); //##Documentation //## @brief Removes a Modified-Listener from the given Node. void RemoveListeners(const DataNode *_Node); //##Documentation //## @brief Saves Modified-Observer Tags for each node in order to remove the event listeners again. std::map m_NodeModifiedObserverTags; std::map m_NodeInteractorChangedObserverTags; //##Documentation //## @brief Saves Delete-Observer Tags for each node in order to remove the event listeners again. std::map m_NodeDeleteObserverTags; //##Documentation //## @brief If this class changes nodes itself, set this to TRUE in order //## to suppress NodeChangedEvent to be emitted. bool m_BlockNodeModifiedEvents; DataStorage(); ~DataStorage() override; //##Documentation //## @brief Filters a SetOfObjects by the condition. If no condition is provided, the original set is returned SetOfObjects::ConstPointer FilterSetOfObjects(const SetOfObjects *set, const NodePredicateBase *condition) const; //##Documentation //## @brief Prints the contents of the DataStorage to os. Do not call directly, call ->Print() instead void PrintSelf(std::ostream &os, itk::Indent indent) const override; }; //##Documentation //## @brief returns the topmost visible node of a given list of nodes. //## The function returns a node that is visible and has the highest layer of a set of given nodes. - //## The property list, which is used to find the visibility- and layer-property is is specified by the + //## The property list, which is used to find the visibility- and layer-property is specified by the //## given base renderer. //## MITKCORE_EXPORT DataNode::Pointer FindTopmostVisibleNode(const DataStorage::SetOfObjects::ConstPointer nodes, const Point3D worldPosition, const TimePointType timePoint, const BaseRenderer* baseRender); } // namespace mitk #endif // MITKDATASTORAGE_H diff --git a/Modules/Core/include/mitkDisplayCoordinateOperation.h b/Modules/Core/include/mitkDisplayCoordinateOperation.h index b37a864f4a..7e97e38f99 100644 --- a/Modules/Core/include/mitkDisplayCoordinateOperation.h +++ b/Modules/Core/include/mitkDisplayCoordinateOperation.h @@ -1,71 +1,71 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKDISPLAYCOORDINATEOPERATION_H_HEADER_INCLUDED_C10E33D0 #define MITKDISPLAYCOORDINATEOPERATION_H_HEADER_INCLUDED_C10E33D0 #include "mitkBaseRenderer.h" #include "mitkNumericTypes.h" #include "mitkOperation.h" #include #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 + //## @brief Operation with information necessary for operations of DisplayVectorInteractor //## @ingroup Undo class MITKCORE_EXPORT DisplayCoordinateOperation : public Operation { public: DisplayCoordinateOperation(mitk::OperationType operationType, mitk::BaseRenderer *renderer, const mitk::Point2D &startDisplayCoordinate, const mitk::Point2D &lastDisplayCoordinate, const mitk::Point2D ¤tDisplayCoordinate); DisplayCoordinateOperation(mitk::OperationType operationType, mitk::BaseRenderer *renderer, const mitk::Point2D &startDisplayCoordinate, const mitk::Point2D &lastDisplayCoordinate, const mitk::Point2D ¤tDisplayCoordinate, const mitk::Point2D &startCoordinateInMM); ~DisplayCoordinateOperation() override; 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 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/Modules/Core/include/mitkEventConfig.h b/Modules/Core/include/mitkEventConfig.h index afcbe5524c..1c4c35d8c2 100755 --- a/Modules/Core/include/mitkEventConfig.h +++ b/Modules/Core/include/mitkEventConfig.h @@ -1,189 +1,189 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkStateMachineConfig_h #define mitkStateMachineConfig_h #include #include "mitkPropertyList.h" #include "usSharedData.h" #include "itkSmartPointer.h" namespace us { class Module; } namespace mitk { class InteractionEvent; struct EventConfigPrivate; /** * \class EventConfig * \brief Configuration Object for Statemachines. * * Reads given config file, which translates specific user inputs (InteractionEvents) into EventVariants that can be *processed * by the StateMachine. * Refer to \ref ConfigFileDescriptionSection . * * @ingroup Interaction **/ class MITKCORE_EXPORT EventConfig { public: typedef itk::SmartPointer EventType; /** * @brief Constructs an invalid EventConfig object. * * Call LoadConfig to create a valid configuration object. */ EventConfig(); EventConfig(const EventConfig &other); /** * @brief Construct an EventConfig object based on a XML configuration file. * * Uses the specified resource file containing an XML event configuration to * construct an EventConfig object. If the resource is invalid, the created * EventConfig object will also be invalid. * * @param filename The resource name relative to the Interactions resource folder. * @param module */ EventConfig(const std::string &filename, const us::Module *module = nullptr); /** * @brief Construct an EventConfig object based on a XML configuration file. * - * Uses the specified istream refering to a file containing an XML event configuration to + * Uses the specified istream referring to a file containing an XML event configuration to * construct an EventConfig object. If the resource is invalid, the created * EventConfig object will also be invalid. * * @param inputStream std::ifstream to XML configuration file */ EventConfig(std::istream &inputStream); /** * @brief Construct an EventConfig object based on a vector of mitk::PropertyLists * * Constructs the EventObject based on a description provided by vector of property values, where each mitk::PropertyList describes * one Event. * Example \code #include "mitkEventConfig.h" #include "mitkInteractionEventConst.h" #include "mitkPropertyList.h" // First event mitk::PropertyList::Pointer propertyList1 = mitk::PropertyList::New(); // Setting the EventClass property to 'MousePressEvent' propertyList1->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventClass.c_str(), "MousePressEvent"); // Setting the Event variant value to 'MousePressEventVariantÄ propertyList1->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventVariant.c_str(), "MousePressEventVariant"); // set control and alt buttons as modifiers propertyList1->SetStringProperty("Modifiers","CTRL,ALT"); // Second event mitk::PropertyList::Pointer propertyList2 = mitk::PropertyList::New(); propertyList2->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventClass.c_str(), "MouseReleaseEvent"); propertyList2->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventVariant.c_str(), "MouseReleaseEventVariant"); propertyList2->SetStringProperty("Modifiers","SHIFT"); // putting both descriptions in a vector std::vector* configDescription = new std::vector(); configDescription->push_back(propertyList1); configDescription->push_back(propertyList2); // create the config object mitk::EventConfig newConfig(configDescription); \endcode */ EventConfig(const std::vector &configDescription); EventConfig &operator=(const EventConfig &other); ~EventConfig(); /** - * @brief Checks wether this EventConfig object is valid. + * @brief Checks whether this EventConfig object is valid. * @return Returns \c true if a configuration was successfully loaded, \c false otherwise. */ bool IsValid() const; /** * @brief This method \e extends this configuration. * * The configuration from the resource provided is loaded and only the ones conflicting are replaced by the new one. * This way several configuration files can be combined. * * @see AddConfig(const EventConfig&) * @see InteractionEventHandler::AddEventConfig(const std::string&, const Module*) * * @param filename The resource name relative to the Interactions resource folder. * @param module The module containing the resource. Defaults to the Mitk module. * @return \c true if the configuration was successfully added, \c false otherwise. */ bool AddConfig(const std::string &filename, const us::Module *module = nullptr); /** * @brief This method \e extends this configuration. * The configuration from the EventConfig object is loaded and only the ones conflicting are replaced by the new * one. * This way several configurations can be combined. * * @see AddConfig(const std::string&, const Module*) * @see InteractionEventHandler::AddEventConfig(const EventConfig&) * * @param config The EventConfig object whose configuration should be added. * @return \c true if the configuration was successfully added, \c false otherwise. */ bool AddConfig(const EventConfig &config); /** * @brief Reset this EventConfig object, rendering it invalid. */ void ClearConfig(); /** * Returns a PropertyList that contains the properties set in the configuration file. * All properties are stored as strings. */ PropertyList::Pointer GetAttributes() const; /** * Checks if the config object has a definition for the given event. If it has, the corresponding variant name is * returned, else * an empty string is returned. * \note mitk::InternalEvent is handled differently. Their signal name is returned as event variant. So there is no * need * to configure them in a config file. * \note mitk::InteractionKeyEvent may have a defined event variant, if this is the case, this function returns it. * If * no * such definition is found key events are mapped to Std + Key , so an 'A' will be return as 'StdA' . */ std::string GetMappedEvent(const EventType &interactionEvent) const; private: us::SharedDataPointer d; }; } // namespace mitk #endif /* mitkStateMachineConfig_h */ diff --git a/Modules/Core/include/mitkEventRecorder.h b/Modules/Core/include/mitkEventRecorder.h index a99f54fb56..4cc12578a3 100644 --- a/Modules/Core/include/mitkEventRecorder.h +++ b/Modules/Core/include/mitkEventRecorder.h @@ -1,85 +1,85 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkEventRecorder_h #define mitkEventRecorder_h #include "iostream" #include "mitkInteractionEventObserver.h" #include namespace mitk { /** *\class EventRecorder *@brief Observer that enables recoding of all user interaction with the render windows and storing it in an XML *file. * * @ingroup Interaction * * XML file will look like: * * \code{.unparsed} * * * * * * * * * * * * * * * * \endcode **/ class MITKCORE_EXPORT EventRecorder : public InteractionEventObserver { public: EventRecorder(); ~EventRecorder() override; /** * By this function the Observer gets notified about new events. */ void Notify(InteractionEvent *interactionEvent, bool) override; /** * @brief SetEventIgnoreList Optional. Provide a list of strings that describe which events are to be ignored */ void SetEventIgnoreList(std::vector list); void StartRecording(); void StopRecording(); bool IsActive() { return m_Active; } void SetOutputFile(std::string filename) { m_FileName = filename; } private: /** * @brief m_IgnoreList lists the names of events that are dropped */ std::vector m_IgnoreList; /** - * @brief m_Active determindes if events are caught and written to file + * @brief m_Active determines if events are caught and written to file */ bool m_Active; std::string m_FileName; std::ofstream m_FileStream; }; } #endif diff --git a/Modules/Core/include/mitkException.h b/Modules/Core/include/mitkException.h index c632970caf..f0d84497b8 100644 --- a/Modules/Core/include/mitkException.h +++ b/Modules/Core/include/mitkException.h @@ -1,115 +1,115 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKEXCEPTION_H_INCLUDED #define MITKEXCEPTION_H_INCLUDED #include #include #include namespace mitk { /**Documentation * \brief An object of this class represents an exception of MITK. * Please don't instantiate exceptions manually, but use the * exception macros (file mitkExceptionMacro.h) instead. * Simple use in your code is: * * mitkThrow() << "optional exception message"; * * You can also define specialized exceptions which must inherit * from this class. Please always use the mitkExceptionClassMacro * when implementing specialized exceptions. A simple implementation * can look like: * * class MyException : public mitk::Exception * { * public: * mitkExceptionClassMacro(MyException,mitk::Exception); * }; * * You can then throw your specialized exceptions by using the macro * * mitkThrowException(MyException) << "optional exception message"; */ class MITKCORE_EXPORT Exception : public itk::ExceptionObject { public: Exception(const char *file, unsigned int lineNumber = 0, const char *desc = "None", const char *loc = "Unknown") : itk::ExceptionObject(file, lineNumber, desc, loc) { } ~Exception() throw() override {} itkTypeMacro(ClassName, SuperClassName); /** \brief Adds rethrow data to this exception. */ void AddRethrowData(const char *file, unsigned int lineNumber, const char *message); /** \return Returns how often the exception was rethrown. */ int GetNumberOfRethrows(); /** @return Returns the rethrow data of the specified rethrow number. Returns empty data, if the rethrowNumber * doesn't * exist. * @param rethrowNumber The internal number of the rethrow. - * @param file (returnvalue) This varaiable will be filled with the file of the specified rethrow. - * @param line (returnvalue) This varaiable will be filled with the line of the specified rethrow. - * @param message (returnvalue) This varaiable will be filled with the message of the specified rethrow. + * @param file (returnvalue) This variable will be filled with the file of the specified rethrow. + * @param line (returnvalue) This variable will be filled with the line of the specified rethrow. + * @param message (returnvalue) This variable will be filled with the message of the specified rethrow. */ void GetRethrowData(int rethrowNumber, std::string &file, int &line, std::string &message); /** \brief Definition of the bit shift operator for this class.*/ template inline Exception &operator<<(const T &data) { std::stringstream ss; ss << this->GetDescription() << data; this->SetDescription(ss.str()); return *this; } /** \brief Definition of the bit shift operator for this class (for non const data).*/ template inline Exception &operator<<(T &data) { std::stringstream ss; ss << this->GetDescription() << data; this->SetDescription(ss.str()); return *this; } /** \brief Definition of the bit shift operator for this class (for functions).*/ inline Exception &operator<<(std::ostream &(*func)(std::ostream &)) { std::stringstream ss; ss << this->GetDescription() << func; this->SetDescription(ss.str()); return *this; } protected: struct ReThrowData { std::string RethrowClassname; unsigned int RethrowLine; std::string RethrowMessage; }; std::vector m_RethrowData; }; MITKCORE_EXPORT std::ostream &operator<<(std::ostream &os, const mitk::Exception &e); } // namespace mitk #endif diff --git a/Modules/Core/include/mitkExtractSliceFilter.h b/Modules/Core/include/mitkExtractSliceFilter.h index e4b1ae2e3d..c7e2182e3e 100644 --- a/Modules/Core/include/mitkExtractSliceFilter.h +++ b/Modules/Core/include/mitkExtractSliceFilter.h @@ -1,208 +1,208 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkExtractSliceFilter_h_Included #define mitkExtractSliceFilter_h_Included #include "MitkCoreExports.h" #include "mitkImageToImageFilter.h" #include #include #include #include #include #include #include namespace mitk { /** - \brief ExtractSliceFilter extracts a 2D abitrary oriented slice from a 3D volume. + \brief ExtractSliceFilter extracts a 2D arbitrary oriented slice from a 3D volume. The filter can reslice in all orthogonal planes such as sagittal, coronal and axial, and is also able to reslice an arbitrary oriented oblique plane. Curved planes are specified via an AbstractTransformGeometry as the input worldgeometry. Additionally the filter extracts the specified component of a multi-component input image. This is done only if the caller requests an mitk::Image output ('m_VtkOutputRequested' set to false). The default component to be extracted is '0'. The convenient workflow is: 1. Set an image as input. 2. Set the worldPlaneGeometry. This defines a grid where the slice is being extracted 3. And then start the pipeline. There are a few more properties that can be set to modify the behavior of the slicing. The properties are: - interpolation mode either Nearestneighbor, Linear or Cubic. - a transform this is a convenient way to adapt the reslice axis for the case that the image is transformed e.g. rotated. - time step the time step in a times volume. - the component to extract from a multi-component input image - vtkoutputrequested, to define whether an mitk::image should be initialized - resample by geometry whether the resampling grid corresponds to the specs of the worldgeometry or is directly derived from the input image By default the properties are set to: - interpolation mode Nearestneighbor. - a transform nullptr (No transform is set). - time step 0. - component 0. - resample by geometry false (Corresponds to input image). */ class MITKCORE_EXPORT ExtractSliceFilter : public ImageToImageFilter { public: mitkClassMacro(ExtractSliceFilter, ImageToImageFilter); itkFactorylessNewMacro(Self); itkCloneMacro(Self); mitkNewMacro1Param(Self, vtkImageReslice *); /** \brief Set the axis where to reslice at.*/ void SetWorldGeometry(const PlaneGeometry *geometry) { if (geometry != m_WorldGeometry) { this->m_WorldGeometry = geometry; this->Modified(); } } /** \brief Set the time step in the 4D volume */ void SetTimeStep(unsigned int timestep) { m_TimeStep = timestep; } unsigned int GetTimeStep() { return m_TimeStep; } /** \brief Set the component of an image to be extracted */ void SetComponent(unsigned int component) { m_Component = component; } /** \brief Set a transform for the reslice axes. * This transform is needed if the image volume itself is transformed. (Effects the reslice axis) */ void SetResliceTransformByGeometry(const BaseGeometry *transform) { this->m_ResliceTransform = transform; } /** \brief Resampling grid corresponds to: false->image true->worldgeometry*/ void SetInPlaneResampleExtentByGeometry(bool inPlaneResampleExtentByGeometry) { this->m_InPlaneResampleExtentByGeometry = inPlaneResampleExtentByGeometry; } /** \brief Sets the output dimension of the slice*/ void SetOutputDimensionality(unsigned int dimension) { this->m_OutputDimension = dimension; } /** \brief Set the spacing in z direction manually. * Required if the outputDimension is > 2. */ void SetOutputSpacingZDirection(double zSpacing) { this->m_ZSpacing = zSpacing; } - /** \brief Set the extent in pixel for direction z manualy. + /** \brief Set the extent in pixel for direction z manually. Required if the output dimension is > 2. */ void SetOutputExtentZDirection(int zMin, int zMax) { this->m_ZMin = zMin; this->m_ZMax = zMax; } /** \brief Get the bounding box of the slice [xMin, xMax, yMin, yMax, zMin, zMax] * The method uses the input of the filter to calculate the bounds. * It is recommended to use * GetClippedPlaneBounds(const BaseGeometry*, const PlaneGeometry*, double*) * if you are not sure about the input. */ bool GetClippedPlaneBounds(double bounds[6]); /** \brief Get the bounding box of the slice [xMin, xMax, yMin, yMax, zMin, zMax]*/ bool GetClippedPlaneBounds(const BaseGeometry *boundingGeometry, const PlaneGeometry *planeGeometry, double *bounds); /** \brief Get the spacing of the slice. returns mitk::ScalarType[2] */ mitk::ScalarType *GetOutputSpacing(); /** \brief Get Output as vtkImageData. * Note: * SetVtkOutputRequest(true) has to be called at least once before * GetVtkOutput(). Otherwise the output is empty for the first update step. */ vtkImageData *GetVtkOutput() { m_VtkOutputRequested = true; return m_Reslicer->GetOutput(); } - /** Set VtkOutPutRequest to suppress the convertion of the image. + /** Set VtkOutPutRequest to suppress the conversion of the image. * It is suggested to use this with GetVtkOutput(). * Note: * SetVtkOutputRequest(true) has to be called at least once before * GetVtkOutput(). Otherwise the output is empty for the first update step. */ void SetVtkOutputRequest(bool isRequested) { m_VtkOutputRequested = isRequested; } /** \brief Get the reslices axis matrix. * Note: the axis are recalculated when calling SetResliceTransformByGeometry. */ vtkMatrix4x4 *GetResliceAxes() { return this->m_Reslicer->GetResliceAxes(); } void SetBackgroundLevel(double backgroundLevel) { m_BackgroundLevel = backgroundLevel; } enum ResliceInterpolation { RESLICE_NEAREST = 0, RESLICE_LINEAR = 1, RESLICE_CUBIC = 3 }; void SetInterpolationMode(ExtractSliceFilter::ResliceInterpolation interpolation) { this->m_InterpolationMode = interpolation; } protected: ExtractSliceFilter(vtkImageReslice *reslicer = nullptr); ~ExtractSliceFilter() override; void GenerateData() override; void GenerateOutputInformation() override; void GenerateInputRequestedRegion() override; PlaneGeometry::ConstPointer m_WorldGeometry; vtkSmartPointer m_Reslicer; unsigned int m_TimeStep; unsigned int m_OutputDimension; double m_ZSpacing; int m_ZMin; int m_ZMax; ResliceInterpolation m_InterpolationMode; bool m_InPlaneResampleExtentByGeometry; // Resampling grid corresponds to: false->image true->worldgeometry mitk::ScalarType *m_OutPutSpacing; bool m_VtkOutputRequested; double m_BackgroundLevel; unsigned int m_Component; private: BaseGeometry::ConstPointer m_ResliceTransform; /* Axis vectors of the relevant geometry. Set in GenerateOutputInformation() and also used in GenerateData().*/ Vector3D m_Right, m_Bottom; /* Bounds of the relevant plane. Set in GenerateOutputInformation() and also used in GenerateData().*/ int m_XMin, m_XMax, m_YMin, m_YMax; }; } #endif // mitkExtractSliceFilter_h_Included diff --git a/Modules/Core/include/mitkGenericIDRelationRule.h b/Modules/Core/include/mitkGenericIDRelationRule.h index f6e2c8fd96..de22d3649d 100644 --- a/Modules/Core/include/mitkGenericIDRelationRule.h +++ b/Modules/Core/include/mitkGenericIDRelationRule.h @@ -1,98 +1,98 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkGenericIDRelationRule_h #define mitkGenericIDRelationRule_h #include "mitkPropertyRelationRuleBase.h" namespace mitk { /**This rule class can be used for relations that are only defined on the ID-layer and where no connection on the Data-layer can be defined or deduced. So it can be used for all ID based relations between PropertyProviders that also implement the interface identifiable. In order to be able to use this class for different relation types based on ID, the ruleIDTag is used. It must be specified when creating a rule instance. The ruleIDTag will be used as suffix for the rule ID of the instance and therefore allows to create specific and distinguishable rules instances based on this class. - One may also specify the display name and the role names of the instance. If not speficied the default values + One may also specify the display name and the role names of the instance. If not specified, the default values are used (display name: " relation", source role name: "source of relation", destination role name: "destination of relation") */ class MITKCORE_EXPORT GenericIDRelationRule : public mitk::PropertyRelationRuleBase { public: mitkClassMacro(GenericIDRelationRule, PropertyRelationRuleBase); itkCloneMacro(Self); mitkNewMacro1Param(Self, const RuleIDType &); mitkNewMacro2Param(Self, const RuleIDType &, const std::string &); mitkNewMacro4Param(Self, const RuleIDType &, const std::string &, const std::string &, const std::string &); using RuleIDType = PropertyRelationRuleBase::RuleIDType; using RelationUIDType = PropertyRelationRuleBase::RelationUIDType; using RelationUIDVectorType = PropertyRelationRuleBase::RelationUIDVectorType; /** Returns an ID string that identifies the rule class */ RuleIDType GetRuleID() const override; bool IsAbstract() const override; /** Returns a human readable string that can be used to describe the rule. Does not need to be unique.*/ std::string GetDisplayName() const override; /** Returns a human readable string that can be used to describe the role of a source in context of the rule * instance.*/ std::string GetSourceRoleName() const override; /** Returns a human readable string that can be used to describe the role of a destination in context of the rule * instance.*/ std::string GetDestinationRoleName() const override; /** Pass through to base implementation of PropertyRelationRuleBase. See PropertyRelationRuleBase::connect documentation for more information. */ RelationUIDType Connect(IPropertyOwner *source, const IPropertyProvider *destination) const; protected: GenericIDRelationRule(const RuleIDType &ruleIDTag); GenericIDRelationRule(const RuleIDType &ruleIDTag, const std::string &displayName); GenericIDRelationRule(const RuleIDType &ruleIDTag, const std::string &displayName, const std::string &sourceRole, const std::string &destinationRole); ~GenericIDRelationRule() override = default; using InstanceIDType = PropertyRelationRuleBase::InstanceIDType; using InstanceIDVectorType = PropertyRelationRuleBase::InstanceIDVectorType; using DataRelationUIDVectorType = PropertyRelationRuleBase::DataRelationUIDVectorType; DataRelationUIDVectorType GetRelationUIDs_DataLayer(const IPropertyProvider* source, const IPropertyProvider* destination, const InstanceIDVectorType& instances_IDLayer) const override; void Connect_datalayer(IPropertyOwner *source, const IPropertyProvider *destination, const InstanceIDType &instanceID) const override; void Disconnect_datalayer(IPropertyOwner *source, const RelationUIDType& relationUID) const override; bool IsSupportedRuleID(const RuleIDType& ruleID) const override; itk::LightObject::Pointer InternalClone() const override; private: RuleIDType m_RuleIDTag; std::string m_DisplayName; std::string m_SourceRole; std::string m_DestinationRole; }; } // namespace mitk #endif diff --git a/Modules/Core/include/mitkGeometryDataReaderService.h b/Modules/Core/include/mitkGeometryDataReaderService.h index aa95947ed4..a06f33e20b 100644 --- a/Modules/Core/include/mitkGeometryDataReaderService.h +++ b/Modules/Core/include/mitkGeometryDataReaderService.h @@ -1,59 +1,59 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkGeometryDataReaderService_h #define mitkGeometryDataReaderService_h // MITK #include #include namespace mitk { /** * @internal * * @brief reads XML representations of mitk::GeometryData from a file/stream. * * To be used via IOUtil. * - * Reader for XML files containing one or multiple XML represenations of + * Reader for XML files containing one or multiple XML representations of * mitk::GeometryData. If multiple mitk::GeometryData objects are stored in one file, * these are assigned to multiple BaseData objects. * * @sa Geometry3DToXML * * @ingroup IO */ class GeometryDataReaderService : public AbstractFileReader { public: GeometryDataReaderService(); ~GeometryDataReaderService() override; using AbstractFileReader::Read; /** * @brief Provides the MIME type for reader and writer. */ static CustomMimeType GEOMETRY_DATA_MIMETYPE(); protected: std::vector> DoRead() override; private: GeometryDataReaderService(const GeometryDataReaderService &other); GeometryDataReaderService *Clone() const override; }; } #endif diff --git a/Modules/Core/include/mitkGradientBackground.h b/Modules/Core/include/mitkGradientBackground.h index 6ec83c793b..a98a7c0816 100644 --- a/Modules/Core/include/mitkGradientBackground.h +++ b/Modules/Core/include/mitkGradientBackground.h @@ -1,103 +1,103 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkGradientBackground_h #define mitkGradientBackground_h #include #include #include #include class vtkRenderer; class vtkRenderWindow; namespace mitk { class RenderWindow; /** * Displays a color gradient in the background * of a vtkRenderWindow. - * The gradient ist faked by displaying a non-interactable + * The gradient is faked by displaying a non-interactable * smoothly shaded plane in a separate layer behind the * scene. After setting the renderwindow, the gradient may be * activated by calling Enable() * @deprecatedSince{2015_05} not used in renderwindows */ class MITKCORE_EXPORT GradientBackground : public itk::Object { public: mitkClassMacroItkParent(GradientBackground, itk::Object); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * Sets the renderwindow, in which the gradient background * will be shown. Make sure, you have called this function * before calling Enable() */ virtual void SetRenderWindow(vtkSmartPointer renderWindow); /** * Returns the vtkRenderWindow, which is used * for displaying the gradient background */ virtual vtkSmartPointer GetRenderWindow(); /** * Returns the renderer responsible for * rendering the color gradient into the * vtkRenderWindow */ virtual vtkSmartPointer GetVtkRenderer(); /** * Sets the gradient colors. The gradient * will smoothly fade from color1 to color2 */ virtual void SetGradientColors(double r1, double g1, double b1, double r2, double g2, double b2); virtual void SetGradientColors(Color upper, Color lower); virtual void SetUpperColor(double r, double g, double b); virtual void SetLowerColor(double r, double g, double b); virtual void SetUpperColor(Color upper); virtual void SetLowerColor(Color lower); /** * Enables drawing of the color gradient background. * If you want to disable it, call the Disable() function. */ virtual void Enable(); /** * Disables drawing of the color gradient background. * If you want to enable it, call the Enable() function. */ virtual void Disable(); /** * Checks, if the gradient background is currently * enabled (visible) */ virtual bool IsEnabled(); protected: GradientBackground(); ~GradientBackground() override; vtkSmartPointer m_RenderWindow; vtkSmartPointer m_Renderer; }; } // end of namespace mitk #endif // mitkGradientBackground_h diff --git a/Modules/Core/include/mitkIFileReader.h b/Modules/Core/include/mitkIFileReader.h index 615cb27f80..04b7062762 100644 --- a/Modules/Core/include/mitkIFileReader.h +++ b/Modules/Core/include/mitkIFileReader.h @@ -1,156 +1,156 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef IFileReader_H_HEADER_INCLUDED_C1E7E521 #define IFileReader_H_HEADER_INCLUDED_C1E7E521 #include #include #include namespace mitk { class BaseData; class PropertyList; } namespace itk { template class SmartPointer; } namespace mitk { /** * \ingroup IO * \ingroup MicroServices_Interfaces * * \brief The common interface for all MITK file readers. * * Implementations of this interface must be registered as a service - * to make themselve available via the service registry. If the + * to make themselves available via the service registry. If the * implementation is state-full, the service should be registered using * a PrototypeServiceFactory. * * The file reader implementation is associated with a mime-type, specified * in the service property PROP_MIMETYPE(). The specified mime-type should * have a corresponding CustomMimeType service object, registered by the reader * or some other party. * * It is recommended to derive new implementations from AbstractFileReader or * from AbstractFileIO (if both reader and writer is implemented), * which provide correct service registration semantics. * * \sa AbstractFileReader * \sa AbstractFileIO * \sa CustomMimeType * \sa FileReaderRegistry * \sa IFileWriter */ struct MITKCORE_EXPORT IFileReader : public IFileIO { ~IFileReader() override; /** * \brief Set the input location. * \param location The file name to read from. */ virtual void SetInput(const std::string &location) = 0; /** * @brief Set an input stream to read from. * @param location A custom label for the input stream. * @param is The input stream. * * If \c is is \c nullptr, this clears the current input stream and \c location * is interpreted as a file-system path. Otherwise, \c location is a custom * label describing the input stream \c is. */ virtual void SetInput(const std::string &location, std::istream *is) = 0; /** * @brief Get the current input location. * @return The input location. */ virtual std::string GetInputLocation() const = 0; /** * @brief Get the input stream. * @return The currently set input stream. */ virtual std::istream *GetInputStream() const = 0; /** * \brief Reads the specified file or input stream and returns its contents. * * \return A list of created BaseData objects. * * If GetInputStream() returns a non-null value, this method must use * the returned stream object to read the data from. If no input stream * was set, the data must be read from the path returned by GetInputLocation(). * * \throws mitk::Exception */ virtual std::vector> Read() = 0; /** * \brief Reads the specified file or input stream, loading its * contents into the provided DataStorage. * * \param ds The DataStorage to which the data is added. * \return The set of added DataNodes to \c ds. * * This method may be overridden by implementations to create or * reconstructed a hierarchy of mitk::DataNode instances in the * provided mitk::DataStorage. * * \throws mitk::Exception */ virtual DataStorage::SetOfObjects::Pointer Read(mitk::DataStorage &ds) = 0; /** * @return A list of files that were loaded during the last call of Read. */ virtual std::vector< std::string > GetReadFiles() = 0; /** * \brief Optionally provide base data properties as a source of meta data. * * The purpose of this method is not to preset the base data property list * of the read data but to provide access to meta data of previous read * operations that may be beneficial for the new read operation. * * A typical usecase may occur when reading files from an MITK scene file * in which case base data properties are already provided in addition to * the actual data file. If such a data file references other files * relative to its original location on the filesystem, the original * location can be retrieved from the base data properties. In this * scenario, GetInputLocation() would return a path within a temporary * directory in which the scene file has been extracted. This is not the * intended base path for searching referenced external data files. */ virtual void SetProperties(const PropertyList* properties) = 0; protected: /** \sa SetProperties(). */ virtual const PropertyList* GetProperties() const = 0; }; } // namespace mitk MITK_DECLARE_SERVICE_INTERFACE(mitk::IFileReader, "org.mitk.IFileReader") #endif /* IFileReader_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Modules/Core/include/mitkIFileWriter.h b/Modules/Core/include/mitkIFileWriter.h index 20cd64970b..53cebeb1ea 100644 --- a/Modules/Core/include/mitkIFileWriter.h +++ b/Modules/Core/include/mitkIFileWriter.h @@ -1,134 +1,134 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef IFileWriter_H_HEADER_INCLUDED_C1E7E521 #define IFileWriter_H_HEADER_INCLUDED_C1E7E521 #include #include namespace mitk { class BaseData; } namespace mitk { /** * \ingroup IO * \ingroup MicroServices_Interfaces * * \brief The common interface of all MITK file writers. * * Implementations of this interface must be registered as a service - * to make themselve available via the service registry. If the + * to make themselves available via the service registry. If the * implementation is stateful, the service should be registered using * a PrototypeServiceFactory. * * The file writer implementation is associated with a mime-type, specified * in the service property PROP_MIMETYPE() and a mitk::BaseData sub-class * as specified in the PROP_BASEDATA_TYPE() service property. * The specified mime-type should have a corresponding CustomMimeType service * object, registered by the reader or some other party. * * It is recommended to derive new implementations from AbstractFileWriter or * AbstractFileIO (if both reader and writer is implemented), * which provide correct service registration semantics. * * A more in-depth explanation is available on the concepts pages in the developer manual. * * \sa AbstractFileWriter * \sa AbstractFileIO * \sa CustomMimeType * \sa FileWriterRegistry * \sa IFileReader */ struct MITKCORE_EXPORT IFileWriter : public IFileIO { ~IFileWriter() override; /** * @brief Set the input data for writing. * @param data The input data. */ virtual void SetInput(const BaseData *data) = 0; /** * @brief Get the input data set via SetInput(). * @return The input data. */ virtual const BaseData *GetInput() const = 0; /** * @brief Set the output location. * @param location A file-system path. * * The location argument specifies a file-system path where the input * data must be written. This method must remove any previously set * output stream. */ virtual void SetOutputLocation(const std::string &location) = 0; /** * @brief Get the current output location. * @return The output location. * * If no stream is set (i.e. GetOutputStream returns \c nullptr), the * returned location string is required to represent a file-system path. */ virtual std::string GetOutputLocation() const = 0; /** * @brief Set an output stream for writing. * @param location A custom label for the output stream. * @param os The output stream. * * If \c os is \c nullptr, this clears the current output stream and \c location * is interpreted as a file-system path. Otherwise, \c location is a custom * label describing the output stream \c os. */ virtual void SetOutputStream(const std::string &location, std::ostream *os) = 0; /** * @brief Get the output stream. * @return The currently set output stream. */ virtual std::ostream *GetOutputStream() const = 0; /** * @brief Write the input data. * * If GetOutputStream() returns a non-null value, this method must use * the returned stream object to write the data set via SetInput(). If no * output stream was set, the data must be written to the path returned * by GetOutputLocation(). * * @throws mitk::Exception */ virtual void Write() = 0; /** * @brief Service property name for the supported mitk::BaseData sub-class. * * The property value must be of type \c std::string. * * @return The property name. */ static std::string PROP_BASEDATA_TYPE(); }; } // namespace mitk MITK_DECLARE_SERVICE_INTERFACE(mitk::IFileWriter, "org.mitk.IFileWriter") #endif /* IFileWriter_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Modules/Core/include/mitkIMimeTypeProvider.h b/Modules/Core/include/mitkIMimeTypeProvider.h index a891013803..ccaa88b827 100644 --- a/Modules/Core/include/mitkIMimeTypeProvider.h +++ b/Modules/Core/include/mitkIMimeTypeProvider.h @@ -1,68 +1,68 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKIMIMETYPEPROVIDER_H #define MITKIMIMETYPEPROVIDER_H #include #include #include #include #include namespace mitk { /** * @ingroup IO * @ingroup MicroServices_Interfaces * * @brief The IMimeTypeProvider service interface allows to query all registered * mime types. * * Mime types are added to the system by registering a service object of type * CustomMimeType and the registered mime types can be queried bei either using direct * look-ups in the service registry or calling the methods of this service interface. * * This service interface also allows to infer the mime type of a file on the file - * system. The heuristics for infering the actual mime type is implementation specific. + * system. The heuristics for inferring the actual mime type is implementation specific. * * @note This is a core service * * @sa CustomMimeType * @sa CoreServices::GetMimeTypeProvider() */ struct MITKCORE_EXPORT IMimeTypeProvider { virtual ~IMimeTypeProvider(); virtual std::vector GetMimeTypes() const = 0; virtual std::vector GetMimeTypesForFile(const std::string &filePath) const = 0; virtual std::vector GetMimeTypesForCategory(const std::string &category) const = 0; virtual MimeType GetMimeTypeForName(const std::string &name) const = 0; /** * @brief Get a sorted and unique list of mime-type categories. * @return A sorted, unique list of mime-type categories. */ virtual std::vector GetCategories() const = 0; }; } MITK_DECLARE_SERVICE_INTERFACE(mitk::IMimeTypeProvider, "org.mitk.IMimeTypeProvider") #endif // MITKIMIMETYPEPROVIDER_H diff --git a/Modules/Core/include/mitkIOUtil.h b/Modules/Core/include/mitkIOUtil.h index 036258e4f6..9f395d13f3 100644 --- a/Modules/Core/include/mitkIOUtil.h +++ b/Modules/Core/include/mitkIOUtil.h @@ -1,440 +1,440 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKIOUTIL_H #define MITKIOUTIL_H #include #include #include #include #include #include #include #include #include #include namespace us { class ModuleResource; } namespace mitk { class PropertyList; /** * \ingroup IO * * \brief A utility class to load and save data from/to the local file system. * * \see QmitkIOUtil */ class MITKCORE_EXPORT IOUtil { public: - /**Struct that containes information regarding the current loading process. (e.g. Path that should be loaded, + /**Struct that contains information regarding the current loading process. (e.g. Path that should be loaded, all found readers for the load path,...). It is set be IOUtil and used to pass information via the option callback in load operations. */ struct MITKCORE_EXPORT LoadInfo { LoadInfo(const std::string &path); std::string m_Path; std::vector m_Output; FileReaderSelector m_ReaderSelector; bool m_Cancel; const PropertyList* m_Properties; }; /**Struct that is the base class for option callbacks used in load operations. The callback is used by IOUtil, if - more than one suitable reader was found or the a reader containes options that can be set. The callback allows to + more than one suitable reader was found or the a reader contains options that can be set. The callback allows to change option settings and select the reader that should be used (via loadInfo). */ struct MITKCORE_EXPORT ReaderOptionsFunctorBase { virtual bool operator()(LoadInfo &loadInfo) const = 0; }; struct MITKCORE_EXPORT SaveInfo { SaveInfo(const BaseData *baseData, const MimeType &mimeType, const std::string &path); bool operator<(const SaveInfo &other) const; /// The BaseData object to save. const BaseData *m_BaseData; /// Contains a set of IFileWriter objects. FileWriterSelector m_WriterSelector; /// The selected mime-type, used to restrict results from FileWriterSelector. MimeType m_MimeType; /// The path to write the BaseData object to. std::string m_Path; /// Flag indicating if sub-sequent save operations are to be canceled. bool m_Cancel; }; /**Struct that is the base class for option callbacks used in save operations. The callback is used by IOUtil, if - more than one suitable writer was found or the a writer containes options that can be set. The callback allows to + more than one suitable writer was found or the a writer contains options that can be set. The callback allows to change option settings and select the writer that should be used (via saveInfo). */ struct MITKCORE_EXPORT WriterOptionsFunctorBase { virtual bool operator()(SaveInfo &saveInfo) const = 0; }; /** * Get the file system path where the running executable is located. * * @return The location of the currently running executable, without the filename. */ static std::string GetProgramPath(); /** * Get the default temporary path. * * @return The default path for temporary data. */ static std::string GetTempPath(); /** * Returns the Directory Seperator for the current OS. * * @return the Directory Seperator for the current OS, i.e. "\\" for Windows and "/" otherwise. */ static char GetDirectorySeparator(); /** * Create and open a temporary file. * * This method generates a unique temporary filename from \c templateName, creates * and opens the file using the output stream \c tmpStream and returns the name of * the newly create file. * - * The \c templateName argument must contain six consective 'X' characters ("XXXXXX") + * The \c templateName argument must contain six consecutive 'X' characters ("XXXXXX") * and these are replaced with a string that makes the filename unique. * * The file is created with read and write permissions for owner only. * * @param tmpStream The output stream for writing to the temporary file. * @param templateName An optional template for the filename. * @param path An optional path where the temporary file should be created. Defaults * to the default temp path as returned by GetTempPath(). * @return The filename of the created temporary file. * * @throw mitk::Exception if the temporary file could not be created. */ static std::string CreateTemporaryFile(std::ofstream &tmpStream, const std::string &templateName = "XXXXXX", std::string path = std::string()); /** * Create and open a temporary file. * * This method generates a unique temporary filename from \c templateName, creates * and opens the file using the output stream \c tmpStream and the specified open * mode \c mode and returns the name of the newly create file. The open mode is always * OR'd with std::ios_base::out | std::ios_base::trunc. * - * The \c templateName argument must contain six consective 'X' characters ("XXXXXX") + * The \c templateName argument must contain six consecutive 'X' characters ("XXXXXX") * and these are replaced with a string that makes the filename unique. * * The file is created with read and write permissions for owner only. * * @param tmpStream The output stream for writing to the temporary file. * @param mode The open mode for the temporary file stream. * @param templateName An optional template for the filename. * @param path An optional path where the temporary file should be created. Defaults * to the default temp path as returned by GetTempPath(). * @return The filename of the created temporary file. * * @throw mitk::Exception if the temporary file could not be created. */ static std::string CreateTemporaryFile(std::ofstream &tmpStream, std::ios_base::openmode mode, const std::string &templateName = "XXXXXX", std::string path = std::string()); /** * Creates an empty temporary file. * * This method generates a unique temporary filename from \c templateName and creates * this file. * * The file is created with read and write permissions for owner only. * * --- * This version is potentially unsafe because the created temporary file is not kept open * and could be used by another process between calling this method and opening the returned * file path for reading or writing. * --- * * @return The filename of the created temporary file. * @param templateName An optional template for the filename. * @param path An optional path where the temporary file should be created. Defaults * to the default temp path as returned by GetTempPath(). * @throw mitk::Exception if the temporary file could not be created. */ static std::string CreateTemporaryFile(const std::string &templateName = "XXXXXX", std::string path = std::string()); /** * Create a temporary directory. * * This method generates a uniquely named temporary directory from \c templateName. * The last set of six consecutive 'X' characters in \c templateName is replaced * with a string that makes the directory name unique. * * The directory is created with read, write and executable permissions for owner only. * * @param templateName An optional template for the directory name. * @param path An optional path where the temporary directory should be created. Defaults * to the default temp path as returned by GetTempPath(). * @return The filename of the created temporary file. * * @throw mitk::Exception if the temporary directory could not be created. */ static std::string CreateTemporaryDirectory(const std::string &templateName = "XXXXXX", std::string path = std::string()); /** * @brief Load a file into the given DataStorage. * * This method calls Load(const std::vector&, DataStorage&) with a * one-element vector. * * @param path The absolute file name including the file extension. * @param storage A DataStorage object to which the loaded data will be added. * @param optionsCallback Pointer to a callback instance. The callback is used by * the load operation if more the suitable reader was found or the reader has options * that can be set. * @return The set of added DataNode objects. * @throws mitk::Exception if \c path could not be loaded. * * @sa Load(const std::vector&, DataStorage&) */ static DataStorage::SetOfObjects::Pointer Load(const std::string &path, DataStorage &storage, const ReaderOptionsFunctorBase *optionsCallback = nullptr); /** * @brief Load a file into the given DataStorage given user defined IFileReader::Options. * * This method calls Load(const std::vector&, DataStorage&) with a * one-element vector. * * @param path The absolute file name including the file extension. * @param options IFileReader option instance that should be used if selected reader * has options. * @param storage A DataStorage object to which the loaded data will be added. * @return The set of added DataNode objects. * @throws mitk::Exception if \c path could not be loaded. * * @sa Load(const std::vector&, DataStorage&) */ static DataStorage::SetOfObjects::Pointer Load(const std::string &path, const IFileReader::Options &options, DataStorage &storage); /** * @brief Load a file and return the loaded data. * * This method calls Load(const std::vector&) with a * one-element vector. * * @param path The absolute file name including the file extension. * @param optionsCallback Pointer to a callback instance. The callback is used by * the load operation if more the suitable reader was found or the reader has options * that can be set. * @return The set of added DataNode objects. * @throws mitk::Exception if \c path could not be loaded. * * @sa Load(const std::vector&, DataStorage&) */ static std::vector Load(const std::string &path, const ReaderOptionsFunctorBase *optionsCallback = nullptr); template static typename T::Pointer Load(const std::string& path, const ReaderOptionsFunctorBase *optionsCallback = nullptr) { return dynamic_cast(Load(path, optionsCallback).at(0).GetPointer()); } /** * @brief Load a file and return the loaded data. * * This method calls Load(const std::vector&) with a * one-element vector. * * @param path The absolute file name including the file extension. * @param options IFileReader option instance that should be used if selected reader * has options. * @return The set of added DataNode objects. * @throws mitk::Exception if \c path could not be loaded. * * @sa Load(const std::vector&, DataStorage&) */ static std::vector Load(const std::string &path, const IFileReader::Options &options); template static typename T::Pointer Load(const std::string& path, const IFileReader::Options &options) { return dynamic_cast(Load(path, options).at(0).GetPointer()); } /** * @brief Loads a list of file paths into the given DataStorage. * * If an entry in \c paths cannot be loaded, this method will continue to load * the remaining entries into \c storage and throw an exception afterwards. * * @param paths A list of absolute file names including the file extension. * @param storage A DataStorage object to which the loaded data will be added. * @param optionsCallback Pointer to a callback instance. The callback is used by * the load operation if more the suitable reader was found or the reader has options * that can be set. * @return The set of added DataNode objects. * @throws mitk::Exception if an entry in \c paths could not be loaded. */ static DataStorage::SetOfObjects::Pointer Load(const std::vector &paths, DataStorage &storage, const ReaderOptionsFunctorBase *optionsCallback = nullptr); static std::vector Load(const std::vector &paths, const ReaderOptionsFunctorBase *optionsCallback = nullptr); /** * @brief Loads the contents of a us::ModuleResource and returns the corresponding mitk::BaseData * @param usResource a ModuleResource, representing a BaseData object * @param mode Optional parameter to set the openmode of the stream * @return The set of loaded BaseData objects. \c Should contain either one or zero elements, since a resource * stream * respresents one object. * @throws mitk::Exception if no reader was found for the stream. */ static std::vector Load(const us::ModuleResource &usResource, std::ios_base::openmode mode = std::ios_base::in); template static typename T::Pointer Load(const us::ModuleResource &usResource, std::ios_base::openmode mode = std::ios_base::in) { return dynamic_cast(Load(usResource, mode).at(0).GetPointer()); } static BaseData::Pointer Load(const std::string& path, const PropertyList* properties); /** * @brief Save a mitk::BaseData instance. * @param data The data to save. * @param path The path to the image including file name and and optional file extension. * If no extension is set, the default extension and mime-type for the * BaseData type of \c data is used. * @param setPathProperty * @throws mitk::Exception if no writer for \c data is available or the writer * is not able to write the image. */ static void Save(const mitk::BaseData *data, const std::string &path, bool setPathProperty = false); /** * @brief Save a mitk::BaseData instance. * @param data The data to save. * @param path The path to the image including file name and an optional file extension. * If no extension is set, the default extension and mime-type for the * BaseData type of \c data is used. * @param options The IFileWriter options to use for the selected writer. * @param setPathProperty * @throws mitk::Exception if no writer for \c data is available or the writer * is not able to write the image. */ static void Save(const mitk::BaseData *data, const std::string &path, const IFileWriter::Options &options, bool setPathProperty = false); /** * @brief Save a mitk::BaseData instance. * @param data The data to save. * @param mimeType The mime-type to use for writing \c data. * @param path The path to the image including file name and an optional file extension. * @param addExtension If \c true, an extension according to the given \c mimeType * is added to \c path if it does not contain one. If \c path already contains * a file name extension, it is not checked for compatibility with \c mimeType. * @param setPathProperty * * @throws mitk::Exception if no writer for the combination of \c data and \c mimeType is * available or the writer is not able to write the image. */ static void Save(const mitk::BaseData *data, const std::string &mimeType, const std::string &path, bool addExtension = true, bool setPathProperty = false); /** * @brief Save a mitk::BaseData instance. * @param data The data to save. * @param mimeType The mime-type to use for writing \c data. * @param path The path to the image including file name and an optional file extension. * @param options Configuration data for the used IFileWriter instance. * @param addExtension If \c true, an extension according to the given \c mimeType * is added to \c path if it does not contain one. If \c path already contains * a file name extension, it is not checked for compatibility with \c mimeType. * @param setPathProperty * * @throws mitk::Exception if no writer for the combination of \c data and \c mimeType is * available or the writer is not able to write the image. */ static void Save(const mitk::BaseData *data, const std::string &mimeType, const std::string &path, const mitk::IFileWriter::Options &options, bool addExtension = true, bool setPathProperty = false); /** * @brief Use SaveInfo objects to save BaseData instances. * * This is a low-level method for directly working with SaveInfo objects. Usually, * the Save() methods taking a BaseData object as an argument are more appropriate. * * @param saveInfos A list of SaveInfo objects for saving contained BaseData objects. * @param setPathProperty * * @see Save(const mitk::BaseData*, const std::string&) */ static void Save(std::vector &saveInfos, bool setPathProperty = false); protected: static std::string Load(std::vector &loadInfos, DataStorage::SetOfObjects *nodeResult, DataStorage *ds, const ReaderOptionsFunctorBase *optionsCallback); static std::string Save(const BaseData *data, const std::string &mimeType, const std::string &path, WriterOptionsFunctorBase *optionsCallback, bool addExtension, bool setPathProperty); static std::string Save(std::vector &saveInfos, WriterOptionsFunctorBase *optionsCallback, bool setPathProperty); private: struct Impl; }; } #endif // MITKIOUTIL_H diff --git a/Modules/Core/include/mitkIPersistenceService.h b/Modules/Core/include/mitkIPersistenceService.h index 175777be24..22a390446e 100644 --- a/Modules/Core/include/mitkIPersistenceService.h +++ b/Modules/Core/include/mitkIPersistenceService.h @@ -1,370 +1,370 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkIPersistenceService_h #define mitkIPersistenceService_h // mitk #include "mitkPropertyListReplacedObserver.h" #include "usGetModuleContext.h" #include "usModuleContext.h" #include "usServiceReference.h" // for microservices #include "mitkDataStorage.h" #include namespace mitk { /** * \ingroup MicroServices_Interfaces * * The central service for the persistence module * Basic idea is to create PropertyLists with a unique id using AddPropertyList(). A consumer * of this interface can write arbitrary information into this propertylist * Calling Save() and Load() will cause the Service to save and load the current set of propertlists from * a file in the user directory. * Using SetAutoLoadAndSave(true) will cause the service to load/save the property lists at application * start/stop. * Moreover, depending on the backend type, the service is connected to the SceneSerialization module, i.e. * the user will be asked whether to save/load the propertlists in/from the current ".mitk" file that is selected * by the user. */ class MITKCORE_EXPORT IPersistenceService { public: /** * If PropertyList with the given id exists, returns it. Otherwise creates a new one and returns it. * If id is empty a UUID will be created and set on the variable * If existed was passed, it is true if the PropertyList with that id existed, false otherwise * \return a valid PropertyList with a StringProperty "Id" containing the passed id */ virtual mitk::PropertyList::Pointer GetPropertyList(std::string &id, bool *existed = nullptr) = 0; /** * removes the PropertyList with the given id * \return true if PropertyList existed and could be removed, false otherwise */ virtual bool RemovePropertyList(std::string &id) = 0; /** * Get the default name of the PersistenceFile (the one that is loaded at startup) */ virtual std::string GetDefaultPersistenceFile() = 0; /** * \return The name of the Bool Property that specifies whether a DataNode is a Node carrying Persistence * PropertyLists */ virtual std::string GetPersistenceNodePropertyName() = 0; /** * Creates a vector of DataNodes that contain all PropertyLists. Additionally, the DataNodes * will have the property name set to the PropertyList's id and a BoolProperty equal to * GetPersistenceNodePropertyName() set to true. If ds is set the returned DataNodes will also be added to that DS. * \return vector of DataNodes with the described attributes */ virtual DataStorage::SetOfObjects::Pointer GetDataNodes(DataStorage *ds = nullptr) = 0; /** * Searches storage for persistent DataNodes, extracts and inserts the appended property lists to this service * \return true if at least one node was found from which a PropertyList could be restored */ virtual bool RestorePropertyListsFromPersistentDataNodes(const DataStorage *storage) = 0; /** * Save the current PropertyLists to fileName. If fileName is empty, a special file in the users home directory will * be * used. * if appendchanges is true, the file will not replaced but first loaded, then overwritten and then replaced - * \return false if an error occured (cannot write to file), true otherwise + * \return false if an error occurred (cannot write to file), true otherwise */ virtual bool Save(const std::string &fileName = "", bool appendChanges = false) = 0; /** * Load PropertyLists from fileName. If fileName is empty, a special file in the users home directory will be used. * If enforeReload is false, the service will take care of modified time flags, i.e. it will not load a file * that was loaded before and did not change in the meantime or that was modified by the service itself * *ATTENTION*: If there are PropertyLists with the same id contained in the file, existing PropertyLists will be * overwritten! * \see AddPropertyListReplacedObserver() - * \return false if an error occured (cannot load from file), true otherwise + * \return false if an error occurred (cannot load from file), true otherwise */ virtual bool Load(const std::string &fileName = "", bool enforeReload = true) = 0; /** * Using SetAutoLoadAndSave(true) will cause the service to load/save the property lists at application * start/stop. */ virtual void SetAutoLoadAndSave(bool autoLoadAndSave) = 0; /** * \return whether AutoLoading is activated or not */ virtual bool GetAutoLoadAndSave() = 0; /** * adds a observer which is informed if a propertyList gets replaced during a Load() procedure */ virtual void AddPropertyListReplacedObserver(PropertyListReplacedObserver *observer) = 0; /** * removes a specific observer */ virtual void RemovePropertyListReplacedObserver(PropertyListReplacedObserver *observer) = 0; /** * nothing to do here */ virtual ~IPersistenceService(); }; } // MACROS FOR AUTOMATIC SAVE FUNCTION #define PERSISTENCE_GET_MODULE_CONTEXT_FUNCTION us::GetModuleContext() #define PERSISTENCE_GET_SERVICE_MACRO \ mitk::IPersistenceService *persistenceService = 0; \ us::ModuleContext *context = PERSISTENCE_GET_MODULE_CONTEXT_FUNCTION; \ if (context) \ { \ us::ServiceReference persistenceServiceRef = \ context->GetServiceReference(); \ if (persistenceServiceRef) \ { \ persistenceService = dynamic_cast( \ context->GetService(persistenceServiceRef)); \ } \ } #define PERSISTENCE_GET_SERVICE_METHOD_MACRO \ mitk::IPersistenceService *GetPersistenceService() const \ { \ PERSISTENCE_GET_SERVICE_MACRO \ return persistenceService; \ } #define PERSISTENCE_MACRO_START_PART(ID_MEMBER_NAME) \ \ public: \ bool Save(const std::string &fileName = "", bool appendChanges = false) \ { \ mitk::IPersistenceService *persistenceService = this->GetPersistenceService(); \ bool noError = persistenceService != 0; \ if (noError) \ this->ToPropertyList(); \ if (noError) \ noError = persistenceService->Save(fileName, appendChanges); \ return noError; \ } \ bool Load(const std::string &fileName = "", bool enforeReload = true) \ { \ mitk::IPersistenceService *persistenceService = this->GetPersistenceService(); \ bool noError = persistenceService != 0 && persistenceService->Load(fileName, enforeReload); \ if (noError) \ { \ this->FromPropertyList(); \ } \ return noError; \ } \ void ToPropertyList() \ { \ mitk::IPersistenceService *persistenceService = this->GetPersistenceService(); \ this->InitializePropertyListReplacedObserver(persistenceService); \ if (!persistenceService) \ return; \ mitk::PropertyList::Pointer propList = persistenceService->GetPropertyList(ID_MEMBER_NAME); #define PERSISTENCE_MACRO_MIDDLE_PART(ID_MEMBER_NAME) \ } \ void FromPropertyList() \ { \ mitk::IPersistenceService *persistenceService = this->GetPersistenceService(); \ this->InitializePropertyListReplacedObserver(persistenceService); \ if (!persistenceService) \ return; \ mitk::PropertyList::Pointer propList = persistenceService->GetPropertyList(ID_MEMBER_NAME); #define PERSISTENCE_MACRO_END_PART(THE_CLASS_NAME, ID_MEMBER_NAME) \ } \ \ std::string GetId() const { return ID_MEMBER_NAME; } \ private: \ PERSISTENCE_GET_SERVICE_METHOD_MACRO \ struct MyPropertyListReplacedObserver : public mitk::PropertyListReplacedObserver \ { \ MyPropertyListReplacedObserver() : m_##THE_CLASS_NAME(0), m_PersistenceService(0) {} \ ~MyPropertyListReplacedObserver() \ { \ if (m_PersistenceService) \ m_PersistenceService->RemovePropertyListReplacedObserver(this); \ } \ void AfterPropertyListReplaced(const std::string &id, mitk::PropertyList *) \ { \ if (m_##THE_CLASS_NAME && m_##THE_CLASS_NAME->GetId() == id) \ m_##THE_CLASS_NAME->FromPropertyList(); \ } \ void Initialize(THE_CLASS_NAME *_##THE_CLASS_NAME, mitk::IPersistenceService *persistenceService) \ { \ m_##THE_CLASS_NAME = _##THE_CLASS_NAME; \ m_PersistenceService = persistenceService; \ if (m_PersistenceService) \ m_PersistenceService->AddPropertyListReplacedObserver(this); \ } \ \ private: \ THE_CLASS_NAME *m_##THE_CLASS_NAME; \ mitk::IPersistenceService *m_PersistenceService; \ }; \ MyPropertyListReplacedObserver m_MyPropertyListReplacedObserver; \ void InitializePropertyListReplacedObserver(mitk::IPersistenceService *persistenceService) \ { \ static bool observerInitialized = false; \ if (observerInitialized == false && persistenceService) \ { \ m_MyPropertyListReplacedObserver.Initialize(this, persistenceService); \ observerInitialized = true; \ } \ } #define PERSISTENCE_CREATE(THE_CLASS_NAME, ID_MEMBER_NAME, PARAM_MEMBER_NAME) \ PERSISTENCE_MACRO_START_PART(ID_MEMBER_NAME) \ propList->Set(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ PERSISTENCE_MACRO_MIDDLE_PART(ID_MEMBER_NAME) \ propList->Get(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ PERSISTENCE_MACRO_END_PART(THE_CLASS_NAME, ID_MEMBER_NAME) #define PERSISTENCE_CREATE2(THE_CLASS_NAME, ID_MEMBER_NAME, PARAM_MEMBER_NAME, PARAM2_MEMBER_NAME) \ PERSISTENCE_MACRO_START_PART(ID_MEMBER_NAME) \ propList->Set(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Set(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ PERSISTENCE_MACRO_MIDDLE_PART(ID_MEMBER_NAME) \ propList->Get(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Get(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ PERSISTENCE_MACRO_END_PART(THE_CLASS_NAME, ID_MEMBER_NAME) #define PERSISTENCE_CREATE3(THE_CLASS_NAME, ID_MEMBER_NAME, PARAM_MEMBER_NAME, PARAM2_MEMBER_NAME, PARAM3_MEMBER_NAME) \ PERSISTENCE_MACRO_START_PART(ID_MEMBER_NAME) \ propList->Set(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Set(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ propList->Set(#PARAM3_MEMBER_NAME, PARAM3_MEMBER_NAME); \ PERSISTENCE_MACRO_MIDDLE_PART(ID_MEMBER_NAME) \ propList->Get(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Get(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ propList->Get(#PARAM3_MEMBER_NAME, PARAM3_MEMBER_NAME); \ PERSISTENCE_MACRO_END_PART(THE_CLASS_NAME, ID_MEMBER_NAME) #define PERSISTENCE_CREATE4( \ THE_CLASS_NAME, ID_MEMBER_NAME, PARAM_MEMBER_NAME, PARAM2_MEMBER_NAME, PARAM3_MEMBER_NAME, PARAM4_MEMBER_NAME) \ PERSISTENCE_MACRO_START_PART(ID_MEMBER_NAME) \ propList->Set(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Set(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ propList->Set(#PARAM3_MEMBER_NAME, PARAM3_MEMBER_NAME); \ propList->Set(#PARAM4_MEMBER_NAME, PARAM4_MEMBER_NAME); \ PERSISTENCE_MACRO_MIDDLE_PART(ID_MEMBER_NAME) \ propList->Get(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Get(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ propList->Get(#PARAM3_MEMBER_NAME, PARAM3_MEMBER_NAME); \ propList->Get(#PARAM4_MEMBER_NAME, PARAM4_MEMBER_NAME); \ PERSISTENCE_MACRO_END_PART(THE_CLASS_NAME, ID_MEMBER_NAME) #define PERSISTENCE_CREATE5(THE_CLASS_NAME, \ ID_MEMBER_NAME, \ PARAM_MEMBER_NAME, \ PARAM2_MEMBER_NAME, \ PARAM3_MEMBER_NAME, \ PARAM4_MEMBER_NAME, \ PARAM5_MEMBER_NAME) \ PERSISTENCE_MACRO_START_PART(ID_MEMBER_NAME) \ propList->Set(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Set(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ propList->Set(#PARAM3_MEMBER_NAME, PARAM3_MEMBER_NAME); \ propList->Set(#PARAM4_MEMBER_NAME, PARAM4_MEMBER_NAME); \ propList->Set(#PARAM5_MEMBER_NAME, PARAM5_MEMBER_NAME); \ PERSISTENCE_MACRO_MIDDLE_PART(ID_MEMBER_NAME) \ propList->Get(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Get(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ propList->Get(#PARAM3_MEMBER_NAME, PARAM3_MEMBER_NAME); \ propList->Get(#PARAM4_MEMBER_NAME, PARAM4_MEMBER_NAME); \ propList->Get(#PARAM5_MEMBER_NAME, PARAM5_MEMBER_NAME); \ PERSISTENCE_MACRO_END_PART(THE_CLASS_NAME, ID_MEMBER_NAME) #define PERSISTENCE_CREATE6(THE_CLASS_NAME, \ ID_MEMBER_NAME, \ PARAM_MEMBER_NAME, \ PARAM2_MEMBER_NAME, \ PARAM3_MEMBER_NAME, \ PARAM4_MEMBER_NAME, \ PARAM5_MEMBER_NAME, \ PARAM6_MEMBER_NAME) \ PERSISTENCE_MACRO_START_PART(ID_MEMBER_NAME) \ propList->Set(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Set(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ propList->Set(#PARAM3_MEMBER_NAME, PARAM3_MEMBER_NAME); \ propList->Set(#PARAM4_MEMBER_NAME, PARAM4_MEMBER_NAME); \ propList->Set(#PARAM5_MEMBER_NAME, PARAM5_MEMBER_NAME); \ propList->Set(#PARAM6_MEMBER_NAME, PARAM6_MEMBER_NAME); \ PERSISTENCE_MACRO_MIDDLE_PART(ID_MEMBER_NAME) \ propList->Get(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Get(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ propList->Get(#PARAM3_MEMBER_NAME, PARAM3_MEMBER_NAME); \ propList->Get(#PARAM4_MEMBER_NAME, PARAM4_MEMBER_NAME); \ propList->Get(#PARAM5_MEMBER_NAME, PARAM5_MEMBER_NAME); \ propList->Get(#PARAM6_MEMBER_NAME, PARAM6_MEMBER_NAME); \ PERSISTENCE_MACRO_END_PART(THE_CLASS_NAME, ID_MEMBER_NAME) #define PERSISTENCE_CREATE7(THE_CLASS_NAME, \ ID_MEMBER_NAME, \ PARAM_MEMBER_NAME, \ PARAM2_MEMBER_NAME, \ PARAM3_MEMBER_NAME, \ PARAM4_MEMBER_NAME, \ PARAM5_MEMBER_NAME, \ PARAM6_MEMBER_NAME, \ PARAM7_MEMBER_NAME) \ PERSISTENCE_MACRO_START_PART(ID_MEMBER_NAME) \ propList->Set(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Set(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ propList->Set(#PARAM3_MEMBER_NAME, PARAM3_MEMBER_NAME); \ propList->Set(#PARAM4_MEMBER_NAME, PARAM4_MEMBER_NAME); \ propList->Set(#PARAM5_MEMBER_NAME, PARAM5_MEMBER_NAME); \ propList->Set(#PARAM6_MEMBER_NAME, PARAM6_MEMBER_NAME); \ propList->Set(#PARAM7_MEMBER_NAME, PARAM7_MEMBER_NAME); \ PERSISTENCE_MACRO_MIDDLE_PART(ID_MEMBER_NAME) \ propList->Get(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Get(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ propList->Get(#PARAM3_MEMBER_NAME, PARAM3_MEMBER_NAME); \ propList->Get(#PARAM4_MEMBER_NAME, PARAM4_MEMBER_NAME); \ propList->Get(#PARAM5_MEMBER_NAME, PARAM5_MEMBER_NAME); \ propList->Get(#PARAM6_MEMBER_NAME, PARAM6_MEMBER_NAME); \ propList->Get(#PARAM7_MEMBER_NAME, PARAM7_MEMBER_NAME); \ PERSISTENCE_MACRO_END_PART(THE_CLASS_NAME, ID_MEMBER_NAME) #define PERSISTENCE_CREATE8(THE_CLASS_NAME, \ ID_MEMBER_NAME, \ PARAM_MEMBER_NAME, \ PARAM2_MEMBER_NAME, \ PARAM3_MEMBER_NAME, \ PARAM4_MEMBER_NAME, \ PARAM5_MEMBER_NAME, \ PARAM6_MEMBER_NAME, \ PARAM7_MEMBER_NAME, \ PARAM8_MEMBER_NAME) \ PERSISTENCE_MACRO_START_PART(ID_MEMBER_NAME) \ propList->Set(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Set(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ propList->Set(#PARAM3_MEMBER_NAME, PARAM3_MEMBER_NAME); \ propList->Set(#PARAM4_MEMBER_NAME, PARAM4_MEMBER_NAME); \ propList->Set(#PARAM5_MEMBER_NAME, PARAM5_MEMBER_NAME); \ propList->Set(#PARAM6_MEMBER_NAME, PARAM6_MEMBER_NAME); \ propList->Set(#PARAM7_MEMBER_NAME, PARAM7_MEMBER_NAME); \ propList->Set(#PARAM8_MEMBER_NAME, PARAM8_MEMBER_NAME); \ PERSISTENCE_MACRO_MIDDLE_PART(ID_MEMBER_NAME) \ propList->Get(#PARAM_MEMBER_NAME, PARAM_MEMBER_NAME); \ propList->Get(#PARAM2_MEMBER_NAME, PARAM2_MEMBER_NAME); \ propList->Get(#PARAM3_MEMBER_NAME, PARAM3_MEMBER_NAME); \ propList->Get(#PARAM4_MEMBER_NAME, PARAM4_MEMBER_NAME); \ propList->Get(#PARAM5_MEMBER_NAME, PARAM5_MEMBER_NAME); \ propList->Get(#PARAM6_MEMBER_NAME, PARAM6_MEMBER_NAME); \ propList->Get(#PARAM7_MEMBER_NAME, PARAM7_MEMBER_NAME); \ propList->Get(#PARAM8_MEMBER_NAME, PARAM8_MEMBER_NAME); \ PERSISTENCE_MACRO_END_PART(THE_CLASS_NAME, ID_MEMBER_NAME) MITK_DECLARE_SERVICE_INTERFACE(mitk::IPersistenceService, "org.mitk.services.IPersistenceService") #endif diff --git a/Modules/Core/include/mitkIPropertyDescriptions.h b/Modules/Core/include/mitkIPropertyDescriptions.h index b9c8659ec7..9c31c66e58 100644 --- a/Modules/Core/include/mitkIPropertyDescriptions.h +++ b/Modules/Core/include/mitkIPropertyDescriptions.h @@ -1,99 +1,99 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkIPropertyDescriptions_h #define mitkIPropertyDescriptions_h #include #include #include namespace mitk { /** * \ingroup MicroServices_Interfaces * \brief Interface of property descriptions service. * * This service allows you to manage descriptions for properties. * The property view displays descriptions of selected properties (in rich text format) at its bottom. */ class MITKCORE_EXPORT IPropertyDescriptions { public: virtual ~IPropertyDescriptions(); /** \brief Add a description for a specific property. * * \param[in] propertyName Name of the property. * \param[in] description Description of the property. * \param[in] className Optional data node class name to which this description is restricted. * \param[in] overwrite Overwrite already existing description. * \return True if description was added successfully. */ virtual bool AddDescription(const std::string &propertyName, const std::string &description, const std::string &className = "", bool overwrite = false) = 0; - /** \brief Add a description for all properties matching the property regulary expression. + /** \brief Add a description for all properties matching the property regular expression. * - * \param[in] propertyRegEx String of the regular expression specifing all relevant property names. + * \param[in] propertyRegEx String of the regular expression specifying all relevant property names. * \param[in] description Description of the property. * \param[in] className Optional data node class name to which this description is restricted. * \param[in] overwrite Overwrite already existing description. * \return True if description was added successfully. */ virtual bool AddDescriptionRegEx(const std::string &propertyRegEx, const std::string &description, const std::string &className = "", bool overwrite = false) = 0; /** \brief Get the description for a specific property. * * \param[in] propertyName Name of the property. * \param[in] className Optional data node class name to which the returned description is restricted. * \param[in] allowNameRegEx Indicates of also regular expressions should be regarded. * \return Property description or empty string if no description is available. */ virtual std::string GetDescription(const std::string &propertyName, const std::string &className = "", bool allowNameRegEx = true) const = 0; /** \brief Check if a specific property has a description. * * \param[in] propertyName Name of the property. * \param[in] className Optional data node class name to which this description is restricted. * \param[in] allowNameRegEx Indicates of also regular expressions should be regarded. * \return True if the property has a description, false otherwise. */ virtual bool HasDescription(const std::string &propertyName, const std::string &className = "", bool allowNameRegEx = true) const = 0; /** \brief Remove all descriptions. * * \param[in] className Optional data node class name to which this description is restricted. */ virtual void RemoveAllDescriptions(const std::string &className = "") = 0; /** \brief Remove description of specific property. * * \param[in] propertyName Name of the property. * \param[in] className Optional data node class name to which this description is restricted. */ virtual void RemoveDescription(const std::string &propertyName, const std::string &className = "") = 0; }; } MITK_DECLARE_SERVICE_INTERFACE(mitk::IPropertyDescriptions, "org.mitk.IPropertyDescriptions") #endif diff --git a/Modules/Core/include/mitkIPropertyPersistence.h b/Modules/Core/include/mitkIPropertyPersistence.h index 50b17a941b..e0ff774a1e 100644 --- a/Modules/Core/include/mitkIPropertyPersistence.h +++ b/Modules/Core/include/mitkIPropertyPersistence.h @@ -1,115 +1,115 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkIPropertyPersistence_h #define mitkIPropertyPersistence_h #include #include namespace mitk { /** \ingroup MicroServices_Interfaces * \brief Interface of property persistence service * * This service allows you to manage persistence info for base data properties. * Persistent properties will be saved if the file format supports custom key value pairs like the .nrrd file * format.\n * \remark The service supports the use of regular expressions (regex; ECMAscript syntax) - * for property names and persistance keys to specifiy persistence rules in a generic way. The getter of the + * for property names and persistance keys to specify persistence rules in a generic way. The getter of the * interface - * (GetInfo and GetInfoByKey) will always ensure that the return containes no regex, thus name and key in the results + * (GetInfo and GetInfoByKey) will always ensure that the return contains no regex, thus name and key in the results * can directly be used. */ class MITKCORE_EXPORT IPropertyPersistence { public: virtual ~IPropertyPersistence(); using InfoResultType = std::list; using MimeTypeNameType = PropertyPersistenceInfo::MimeTypeNameType; /** \brief Add persistence info for a specific base data property. * If there is already a property info instance for the passed * property name and the same info, it won't be added. Info instances * are regarded equal, if the mime types are equal. * You may enforce to overwrite the old equal info for a property name * by the overwrite parameter. * * \param[in] info Persistence info of the property. * \param[in] overwrite Overwrite already existing persistence info. * \return True if persistence info was added successfully. */ virtual bool AddInfo(const PropertyPersistenceInfo *info, bool overwrite = false) = 0; /** \brief Get the persistence info for a specific base data property. * \param[in] propertyName Name of the property. * \param[in] allowNameRegEx Indicates if also added info instances with regexs are being checked. * \return Property persistence info or null pointer if no persistence info is available. */ virtual InfoResultType GetInfo(const std::string &propertyName, bool allowNameRegEx = true) const = 0; /** \brief Get the persistence info for a specific base data property and mime type. * * \param[in] propertyName Name of the property. * \param[in] mime Name of the mime type the info is specified for. * \param[in] allowMimeWildCard Indicates if wildcard is allowed. If it is allowed, the method will first try to find * the specified info. * If no info was found but an info exists with the mime type name PropertyPersistenceInfo::ANY_MIMETYPE_NAME(), the * later info will be * returned as fall back option. * \param[in] allowNameRegEx Indicates if also added info instances with regexs are being checked. * \return Property persistence info or null pointer if no persistence info is available. */ virtual InfoResultType GetInfo(const std::string &propertyName, const MimeTypeNameType &mime, bool allowMimeWildCard = false, bool allowNameRegEx = true) const = 0; /** \brief Get the persistence info that will use the specified key. * * \param[in] persistenceKey Name of the property. * \param[in] allowKeyRegEx Indicates if also added info instances with regexs for the key are being checked. * \return Property persistence info or null pointer if no persistence info is available. */ virtual InfoResultType GetInfoByKey(const std::string &persistenceKey, bool allowKeyRegEx = true) const = 0; /** \brief Check if a specific base data property has persistence info. * * \param[in] propertyName Name of the property. * \param[in] allowNameRegEx Indicates if also added info instances with regexs are being checked. * \return True if the property has persistence info, false otherwise. */ virtual bool HasInfo(const std::string &propertyName, bool allowNameRegEx = true) const = 0; /** \brief Remove all persistence info. */ virtual void RemoveAllInfo() = 0; /** \brief Remove persistence info instances of a specific property name/regex. * * \param[in] propertyName Registered name or regex that should be removed. */ virtual void RemoveInfo(const std::string &propertyName) = 0; /** \brief Remove persistence info instances of a specific property name/regex and mime type. * * \param[in] propertyName Registered name or regex that should be removed. * \param[in] mime Name of the mime type. */ virtual void RemoveInfo(const std::string &propertyName, const MimeTypeNameType &mime) = 0; }; } MITK_DECLARE_SERVICE_INTERFACE(mitk::IPropertyPersistence, "org.mitk.IPropertyPersistence") #endif diff --git a/Modules/Core/include/mitkIPropertyRelations.h b/Modules/Core/include/mitkIPropertyRelations.h index 45476b48d0..c35bd8640d 100644 --- a/Modules/Core/include/mitkIPropertyRelations.h +++ b/Modules/Core/include/mitkIPropertyRelations.h @@ -1,95 +1,95 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkIPropertyRelations_h #define mitkIPropertyRelations_h #include #include namespace mitk { /** \ingroup MicroServices_Interfaces * \brief Interface of property relations service * * This service allows you to manage relations between property provider based on properties. * Property relations are managed by rule classes derived from PropertyRelationRuleBase. * */ class MITKCORE_EXPORT IPropertyRelations { public: virtual ~IPropertyRelations(); using RuleResultVectorType = std::list; using RuleIDType = PropertyRelationRuleBase::RuleIDType; using RuleIDVectorType = std::vector; /** \brief Add rule for a specific relation. * If there is already a property rule instance it won't be added. * Rule instances are regarded equal, if the rule ID is equal. * You may enforce to overwrite the old equal rule * by the overwrite parameter. * * \param[in] rule Relation rule of the property. * \param[in] overwrite Overwrite already existing relation rule. * \return True if relation rule was added successfully. */ virtual bool AddRule(const PropertyRelationRuleBase *rule, bool overwrite = false) = 0; /** \brief Get all relation rules the passed source is really a source of. (PropertyRelationRuleBase::IsSource() would return true) * \param[in] source Pointer to the instance that should be checked as source for the searched rules. * \return Property relation rules or empty list if no relation rules are available. */ virtual RuleResultVectorType GetRulesForSource(const IPropertyProvider* source) const = 0; /** \brief Get all relation rules that would accept the passed IPropertOwner as source. * \param[in] sourceCandidate Pointer to the instance that should be checked to be a suitable source. * \return Property relation rules or empty list if no relation rules are available. */ virtual RuleResultVectorType GetRulesForSourceCandidate(const IPropertyProvider* sourceCandidate) const = 0; /** \brief Get all relation rules that would accept the passed IPropertOwner as destination. * \param[in] destCandidate Pointer to the instance that should be checked to be a suitable destination. * \return Property relation rules or empty list if no relation rules are available. */ virtual RuleResultVectorType GetRulesForDestinationCandidate(const IPropertyProvider* destCandidate) const = 0; - /** \brief Get the relation rule that has the specfied ruleID. + /** \brief Get the relation rule that has the specified ruleID. * * \return Property relation rule or null pointer, if no relation rule is available. */ virtual PropertyRelationRuleBase::ConstPointer GetRule(const RuleIDType &ruleID) const = 0; /** \brief Get all IDs of registered rules */ virtual RuleIDVectorType GetRuleIDs() const = 0; /** \brief Check if a passed instance has defined relation covered by the registered rules. * * \param[in] source Pointer to the instance that should be checked as source for the searched rules. * \return True if the property has relations of registered rules, false otherwise. */ virtual bool HasRuleForSource(const IPropertyProvider* source) const = 0; /** \brief Remove all relation rules. */ virtual void RemoveAllRules() = 0; /** \brief Remove relation rule instance with the passed ID. If rule does not exist nothing happens. */ virtual void RemoveRule(const RuleIDType &ruleID) = 0; }; } MITK_DECLARE_SERVICE_INTERFACE(mitk::IPropertyRelations, "org.mitk.IPropertyRelations") #endif diff --git a/Modules/Core/include/mitkITKImageImport.txx b/Modules/Core/include/mitkITKImageImport.txx index 5e15366fdb..046082da2a 100644 --- a/Modules/Core/include/mitkITKImageImport.txx +++ b/Modules/Core/include/mitkITKImageImport.txx @@ -1,187 +1,187 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkITKImageImport_txx #define __mitkITKImageImport_txx #include "mitkITKImageImport.h" #include "mitkImageReadAccessor.h" template mitk::ITKImageImport::ITKImageImport() { } template mitk::ITKImageImport::~ITKImageImport() { } template typename mitk::ITKImageImport::InputImageType *mitk::ITKImageImport::GetInput(void) { return static_cast(this->ProcessObject::GetInput(0)); } template void mitk::ITKImageImport::SetInput(const InputImageType *input) { this->ProcessObject::SetNthInput(0, const_cast(input)); } template void mitk::ITKImageImport::SetGeometry(const BaseGeometry *geometry) { if (geometry != nullptr) { m_Geometry = static_cast(geometry->Clone().GetPointer()); } else { m_Geometry = nullptr; } Modified(); } template void mitk::ITKImageImport::GenerateOutputInformation() { InputImageConstPointer input = this->GetInput(); mitk::Image::Pointer output = this->GetOutput(); itkDebugMacro(<< "GenerateOutputInformation()"); output->InitializeByItk(input.GetPointer()); if (m_Geometry.IsNotNull()) { output->SetGeometry(m_Geometry); } } template void mitk::ITKImageImport::GenerateData() { InputImageConstPointer input = this->GetInput(); mitk::Image::Pointer output = this->GetOutput(); output->SetImportChannel((void *)input->GetBufferPointer(), 0, mitk::Image::ReferenceMemory); } template void mitk::ITKImageImport::GenerateInputRequestedRegion() { Superclass::GenerateInputRequestedRegion(); // Input is an image, cast away the constness so we can set // the requested region. InputImagePointer input = const_cast(this->GetInput()); // Use the function object RegionCopier to copy the output region // to the input. The default region copier has default implementations // to handle the cases where the input and output are the same // dimension, the input a higher dimension than the output, and the // input a lower dimension than the output. InputImageRegionType inputRegion; OutputToInputRegionCopierType regionCopier; regionCopier(inputRegion, this->GetOutput()->GetRequestedRegion()); input->SetRequestedRegion(inputRegion); } template void mitk::ITKImageImport::SetNthOutput(DataObjectPointerArraySizeType idx, itk::DataObject *output) { if ((output == nullptr) && (idx == 0)) { // we are disconnected from our output: // copy buffer of input to output, because we // cannot guarantee that the input (to which our - // output is refering) will stay alive. + // output is referring) will stay alive. InputImageConstPointer input = this->GetInput(); mitk::Image::Pointer currentOutput = this->GetOutput(); if (input.IsNotNull() && currentOutput.IsNotNull()) currentOutput->SetChannel(input->GetBufferPointer()); } Superclass::SetNthOutput(idx, output); } template mitk::Image::Pointer mitk::ImportItkImage(const itk::SmartPointer &itkimage, const BaseGeometry *geometry, bool update) { typename mitk::ITKImageImport::Pointer importer = mitk::ITKImageImport::New(); importer->SetInput(itkimage); importer->SetGeometry(geometry); if (update) importer->Update(); return importer->GetOutput(); } template mitk::Image::Pointer mitk::ImportItkImage(const ItkOutputImageType *itkimage, const BaseGeometry *geometry, bool update) { typename mitk::ITKImageImport::Pointer importer = mitk::ITKImageImport::New(); importer->SetInput(itkimage); importer->SetGeometry(geometry); if (update) importer->Update(); return importer->GetOutput(); } template mitk::Image::Pointer mitk::GrabItkImageMemory(itk::SmartPointer &itkimage, mitk::Image *mitkImage, const BaseGeometry *geometry, bool update) { return GrabItkImageMemory(itkimage.GetPointer(), mitkImage, geometry, update); } template mitk::Image::Pointer mitk::GrabItkImageMemory(ItkOutputImageType *itkimage, mitk::Image *mitkImage, const BaseGeometry *geometry, bool update) { if (update) itkimage->Update(); mitk::Image::Pointer resultImage; if (mitkImage != nullptr) { resultImage = mitkImage; - // test the pointer equality with read accessor only if mitk Image is intialized, otherwise an Exception is thrown + // test the pointer equality with read accessor only if mitk Image is initialized, otherwise an Exception is thrown // by the ReadAccessor if (mitkImage->IsInitialized()) { // check the data pointer, for that, we need to ignore the lock of the mitkImage mitk::ImageReadAccessor read_probe(mitk::Image::Pointer(mitkImage), nullptr, mitk::ImageAccessorBase::IgnoreLock); if (itkimage->GetBufferPointer() == read_probe.GetData()) return resultImage; } } else { resultImage = mitk::Image::New(); } resultImage->InitializeByItk(itkimage); resultImage->SetImportVolume(itkimage->GetBufferPointer(), 0, 0, Image::ManageMemory); itkimage->GetPixelContainer()->ContainerManageMemoryOff(); if (geometry != nullptr) resultImage->SetGeometry(static_cast(geometry->Clone().GetPointer())); return resultImage; } #endif //__mitkITKImageImport_txx diff --git a/Modules/Core/include/mitkIdentifiable.h b/Modules/Core/include/mitkIdentifiable.h index 9c2cef821f..f499053cf1 100644 --- a/Modules/Core/include/mitkIdentifiable.h +++ b/Modules/Core/include/mitkIdentifiable.h @@ -1,77 +1,77 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkIdentifiable_h #define mitkIdentifiable_h #include #include namespace mitk { /** * \brief Base class of identifiable objects. * * Offers an interface to query a UID for the instance. Can be inherited * by other classes to provide this capability.\n\n * What does the UID stand for/what is its scope?\n - * - It is unique in its creation, but it is not a content specific unique ID. Therfore: + * - It is unique in its creation, but it is not a content specific unique ID. Therefore: * - A class instance, associated with a UID, may change its values over its lifetime, but still have the same UID. - If a class instance gets persisted and loaded multiple times, then their could be several instances with the same UID. - UIDs are therefore more simelar to git paths than to git hashes. They identify something, but the state of something can change (stream of commits). The difference of the UID compared to using e.g. plain instance pointers to identify an object is that UIDs allow the feature of serialization as they abstract from the memory location of the current runtime environment. - It is up to the application that builds upon that feature to ensure appropriate usage within the application scope. * @remark It is not a feature of mitk::Identifiable per se to be persistable. It depends on classes that derive * from mitk::Identifiable, if and how they implement a persistence mechanism for their MITK UID. * @remark If you want to change the unique ID after creation time, you can use * the mitk::UIDManipulator class. The reationale behind this pattern is * to ensure that you think twice before doing this. It is intended to be * used by data readers if necessary at all. */ class MITKCORE_EXPORT Identifiable { public: using UIDType = std::string; Identifiable(); explicit Identifiable(const UIDType &uid); Identifiable(const Identifiable &) = delete; Identifiable(Identifiable &&) noexcept; virtual ~Identifiable(); Identifiable & operator =(const Identifiable &) = delete; Identifiable & operator =(Identifiable &&other) noexcept; /** * \brief Get unique ID of an object. * * \return Empty string if an object has no unique ID. */ virtual UIDType GetUID() const; protected: virtual void SetUID(const UIDType& uid); private: friend class UIDManipulator; struct Impl; Impl *m_Impl; }; } #endif diff --git a/Modules/Core/include/mitkImage.h b/Modules/Core/include/mitkImage.h index a568fb65b8..5ed23f8a55 100644 --- a/Modules/Core/include/mitkImage.h +++ b/Modules/Core/include/mitkImage.h @@ -1,643 +1,643 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKIMAGE_H_HEADER_INCLUDED_C1C2FCD2 #define MITKIMAGE_H_HEADER_INCLUDED_C1C2FCD2 #include "mitkBaseData.h" #include "mitkImageAccessorBase.h" #include "mitkImageDataItem.h" #include "mitkImageDescriptor.h" #include "mitkImageVtkAccessor.h" #include "mitkLevelWindow.h" #include "mitkPlaneGeometry.h" #include "mitkSlicedData.h" #include #include #ifndef __itkHistogram_h #include #endif class vtkImageData; namespace itk { template class MutexLockHolder; } namespace mitk { class SubImageSelector; class ImageTimeSelector; class ImageStatisticsHolder; /** * @brief Image class for storing images * * Can be asked for header information, the data vector, or vtkImageData objects. * If not the complete data is required, the appropriate SubImageSelector class * should be used for access. * Image organizes sets of slices (s x 2D), volumes (t x 3D) and channels (n * x ND). Channels are for different kind of data, e.g., morphology in * channel 0, velocities in channel 1. All channels must have the same Geometry! In * particular, the dimensions of all channels are the same, only the pixel-type * may differ between channels. * * For importing ITK images use of mitk::ITKImageImport is recommended, see * \ref Adaptor. * * For ITK v3.8 and older: Converting coordinates from the ITK physical * coordinate system (which does not support rotated images) to the MITK world * coordinate system should be performed via the BaseGeometry of the Image, see * BaseGeometry::WorldToItkPhysicalPoint. * * For more information, see \ref MitkImagePage . * @ingroup Data */ class MITKCORE_EXPORT Image : public SlicedData { friend class SubImageSelector; friend class ImageAccessorBase; friend class ImageVtkAccessor; friend class ImageVtkReadAccessor; friend class ImageVtkWriteAccessor; friend class ImageReadAccessor; friend class ImageWriteAccessor; public: mitkClassMacro(Image, SlicedData); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** Smart Pointer type to a ImageDataItem. */ typedef itk::SmartPointer ImageDataItemPointer; typedef itk::Statistics::Histogram HistogramType; typedef mitk::ImageStatisticsHolder *StatisticsHolderPointer; /** This enum is evaluated when setting new data to an image. */ enum ImportMemoryManagementType { CopyMemory, /**< Data to be set is copied and assigned to a new memory block. Data memory block will be freed on deletion of mitk::Image. */ ManageMemory, /**< Data to be set will be referenced, and Data memory block will be freed on deletion of mitk::Image. */ ReferenceMemory, /**< Data to be set will be referenced, but Data memory block will not be freed on deletion of mitk::Image. */ DontManageMemory = ReferenceMemory }; /** * @brief Vector container of SmartPointers to ImageDataItems; * Class is only for internal usage to allow convenient access to all slices over iterators; * See documentation of ImageDataItem for details. */ typedef std::vector ImageDataItemPointerArray; public: /** * @brief Returns the PixelType of channel @a n. */ const mitk::PixelType GetPixelType(int n = 0) const; /** * @brief Get dimension of the image */ unsigned int GetDimension() const; /** * @brief Get the size of dimension @a i (e.g., i=0 results in the number of pixels in x-direction). * * @sa GetDimensions() */ unsigned int GetDimension(int i) const; public: /** * @brief Get a volume at a specific time @a t of channel @a n as a vtkImageData. */ virtual vtkImageData *GetVtkImageData(int t = 0, int n = 0); virtual const vtkImageData *GetVtkImageData(int t = 0, int n = 0) const; /** * @brief Check whether slice @a s at time @a t in channel @a n is set */ bool IsSliceSet(int s = 0, int t = 0, int n = 0) const override; /** * @brief Check whether volume at time @a t in channel @a n is set */ bool IsVolumeSet(int t = 0, int n = 0) const override; /** * @brief Check whether the channel @a n is set */ bool IsChannelSet(int n = 0) const override; /** * @brief Set @a data as slice @a s at time @a t in channel @a n. It is in * the responsibility of the caller to ensure that the data vector @a data * is really a slice (at least is not smaller than a slice), since there is * no chance to check this. * * The data is copied to an array managed by the image. If the image shall * reference the data, use SetImportSlice with ImportMemoryManagementType * set to ReferenceMemory. For importing ITK images use of mitk:: * ITKImageImport is recommended. * @sa SetPicSlice, SetImportSlice, SetImportVolume */ virtual bool SetSlice(const void *data, int s = 0, int t = 0, int n = 0); /** * @brief Set @a data as volume at time @a t in channel @a n. It is in * the responsibility of the caller to ensure that the data vector @a data * is really a volume (at least is not smaller than a volume), since there is * no chance to check this. * * The data is copied to an array managed by the image. If the image shall * reference the data, use SetImportVolume with ImportMemoryManagementType * set to ReferenceMemory. For importing ITK images use of mitk:: * ITKImageImport is recommended. * @sa SetPicVolume, SetImportVolume */ virtual bool SetVolume(const void *data, int t = 0, int n = 0); /** * @brief Set @a data in channel @a n. It is in * the responsibility of the caller to ensure that the data vector @a data * is really a channel (at least is not smaller than a channel), since there is * no chance to check this. * * The data is copied to an array managed by the image. If the image shall * reference the data, use SetImportChannel with ImportMemoryManagementType * set to ReferenceMemory. For importing ITK images use of mitk:: * ITKImageImport is recommended. * @sa SetPicChannel, SetImportChannel */ virtual bool SetChannel(const void *data, int n = 0); /** * @brief Set @a data as slice @a s at time @a t in channel @a n. It is in * the responsibility of the caller to ensure that the data vector @a data * is really a slice (at least is not smaller than a slice), since there is * no chance to check this. * * The data is managed according to the parameter \a importMemoryManagement. * @sa SetPicSlice */ virtual bool SetImportSlice( void *data, int s = 0, int t = 0, int n = 0, ImportMemoryManagementType importMemoryManagement = CopyMemory); /** * @brief Set @a data as volume at time @a t in channel @a n. It is in * the responsibility of the caller to ensure that the data vector @a data * is really a volume (at least is not smaller than a volume), since there is * no chance to check this. * * The data is managed according to the parameter \a importMemoryManagement. * @sa SetPicVolume */ virtual bool SetImportVolume(void *data, int t = 0, int n = 0, ImportMemoryManagementType importMemoryManagement = CopyMemory); virtual bool SetImportVolume(const void *const_data, int t = 0, int n = 0); /** * @brief Set @a data in channel @a n. It is in * the responsibility of the caller to ensure that the data vector @a data * is really a channel (at least is not smaller than a channel), since there is * no chance to check this. * * The data is managed according to the parameter \a importMemoryManagement. * @sa SetPicChannel */ virtual bool SetImportChannel(void *data, int n = 0, ImportMemoryManagementType importMemoryManagement = CopyMemory); /** * initialize new (or re-initialize) image information * @warning Initialize() by pic assumes a plane, evenly spaced geometry starting at (0,0,0). */ virtual void Initialize(const mitk::PixelType &type, unsigned int dimension, const unsigned int *dimensions, unsigned int channels = 1); /** * initialize new (or re-initialize) image information by a BaseGeometry * * \param type * \param geometry * \param channels * @param tDim defines the number of time steps for which the Image should be initialized */ virtual void Initialize(const mitk::PixelType &type, const mitk::BaseGeometry &geometry, unsigned int channels = 1, int tDim = 1); /** * \brief Initialize new (or re-initialize) image information by a TimeGeometry * * \param type * \param geometry * \param channels * \param tDim override time dimension if the value is bigger than 0 (Default -1) */ virtual void Initialize(const mitk::PixelType &type, const mitk::TimeGeometry &geometry, unsigned int channels = 1, int tDim = -1); /** * initialize new (or re-initialize) image information by a PlaneGeometry and number of slices * * Initializes the bounding box according to the width/height of the * PlaneGeometry and @a sDim via SlicedGeometry3D::InitializeEvenlySpaced. * The spacing is calculated from the PlaneGeometry. * \sa SlicedGeometry3D::InitializeEvenlySpaced */ virtual void Initialize(const mitk::PixelType &type, int sDim, const mitk::PlaneGeometry &geometry2d, unsigned int channels = 1, int tDim = 1); /** * initialize new (or re-initialize) image information by another * mitk-image. * Only the header is used, not the data vector! */ virtual void Initialize(const mitk::Image *image); virtual void Initialize(const mitk::ImageDescriptor::Pointer inDesc); /** * initialize new (or re-initialize) image information by @a vtkimagedata, * a vtk-image. * Only the header is used, not the data vector! Use * SetVolume(vtkimage->GetScalarPointer()) to set the data vector. * * @param vtkimagedata * @param channels * @param tDim override time dimension in @a vtkimagedata (if >0 and <) * @param sDim override z-space dimension in @a vtkimagedata (if >0 and <) * @param pDim override y-space dimension in @a vtkimagedata (if >0 and <) */ virtual void Initialize(vtkImageData *vtkimagedata, int channels = 1, int tDim = -1, int sDim = -1, int pDim = -1); /** * initialize new (or re-initialize) image information by @a itkimage, * a templated itk-image. * Only the header is used, not the data vector! Use * SetVolume(itkimage->GetBufferPointer()) to set the data vector. * * @param itkimage * @param channels * @param tDim override time dimension in @a itkimage (if >0 and <) * @param sDim override z-space dimension in @a itkimage (if >0 and <) */ template void InitializeByItk(const itkImageType *itkimage, int channels = 1, int tDim = -1, int sDim = -1) { if (itkimage == nullptr) return; MITK_DEBUG << "Initializing MITK image from ITK image."; // build array with dimensions in each direction with at least 4 entries m_Dimension = itkimage->GetImageDimension(); unsigned int i, *tmpDimensions = new unsigned int[m_Dimension > 4 ? m_Dimension : 4]; for (i = 0; i < m_Dimension; ++i) tmpDimensions[i] = itkimage->GetLargestPossibleRegion().GetSize().GetSize()[i]; if (m_Dimension < 4) { unsigned int *p; for (i = 0, p = tmpDimensions + m_Dimension; i < 4 - m_Dimension; ++i, ++p) *p = 1; } // overwrite number of slices if sDim is set if ((m_Dimension > 2) && (sDim >= 0)) tmpDimensions[2] = sDim; // overwrite number of time points if tDim is set if ((m_Dimension > 3) && (tDim >= 0)) tmpDimensions[3] = tDim; // rough initialization of Image // mitk::PixelType importType = ImportItkPixelType( itkimage::PixelType ); Initialize( MakePixelType(itkimage->GetNumberOfComponentsPerPixel()), m_Dimension, tmpDimensions, channels); const typename itkImageType::SpacingType &itkspacing = itkimage->GetSpacing(); MITK_DEBUG << "ITK spacing " << itkspacing; // access spacing of itk::Image Vector3D spacing; FillVector3D(spacing, itkspacing[0], 1.0, 1.0); if (m_Dimension >= 2) spacing[1] = itkspacing[1]; if (m_Dimension >= 3) spacing[2] = itkspacing[2]; // access origin of itk::Image Point3D origin; const typename itkImageType::PointType &itkorigin = itkimage->GetOrigin(); MITK_DEBUG << "ITK origin " << itkorigin; FillVector3D(origin, itkorigin[0], 0.0, 0.0); if (m_Dimension >= 2) origin[1] = itkorigin[1]; if (m_Dimension >= 3) origin[2] = itkorigin[2]; // access direction of itk::Imagm_PixelType = new mitk::PixelType(type);e and include spacing const typename itkImageType::DirectionType &itkdirection = itkimage->GetDirection(); MITK_DEBUG << "ITK direction " << itkdirection; mitk::Matrix3D matrix; matrix.SetIdentity(); unsigned int j, itkDimMax3 = (m_Dimension >= 3 ? 3 : m_Dimension); // check if spacing has no zero entry and itkdirection has no zero columns bool itkdirectionOk = true; mitk::ScalarType columnSum; for (j = 0; j < itkDimMax3; ++j) { columnSum = 0.0; for (i = 0; i < itkDimMax3; ++i) { columnSum += fabs(itkdirection[i][j]); } if (columnSum < mitk::eps) { itkdirectionOk = false; } if ((spacing[j] < -mitk::eps) // (normally sized) negative value && (j == 2) && (m_Dimensions[2] == 1)) { // Negative spacings can occur when reading single DICOM slices with ITK via GDCMIO - // In these cases spacing is not determind by ITK correctly (because it distinguishes correctly + // In these cases spacing is not determined by ITK correctly (because it distinguishes correctly // between slice thickness and inter slice distance -- slice distance is meaningless for // single slices). - // I experienced that ITK produced something meaningful nonetheless because is is + // I experienced that ITK produced something meaningful nonetheless because it is // evaluating the tag "(0018,0088) Spacing between slices" as a fallback. This tag is not // reliable (http://www.itk.org/pipermail/insight-users/2005-September/014711.html) // but gives at least a hint. // In real world cases I experienced that this tag contained the correct inter slice distance // with a negative sign, so we just invert such negative spacings. MITK_WARN << "Illegal value of itk::Image::GetSpacing()[" << j << "]=" << spacing[j] << ". Using inverted value " << -spacing[j]; spacing[j] = -spacing[j]; } else if (spacing[j] < mitk::eps) // value near zero { MITK_ERROR << "Illegal value of itk::Image::GetSpacing()[" << j << "]=" << spacing[j] << ". Using 1.0 instead."; spacing[j] = 1.0; } } if (itkdirectionOk == false) { MITK_ERROR << "Illegal matrix returned by itk::Image::GetDirection():" << itkdirection << " Using identity instead."; for (i = 0; i < itkDimMax3; ++i) for (j = 0; j < itkDimMax3; ++j) if (i == j) matrix[i][j] = spacing[j]; else matrix[i][j] = 0.0; } else { for (i = 0; i < itkDimMax3; ++i) for (j = 0; j < itkDimMax3; ++j) matrix[i][j] = itkdirection[i][j] * spacing[j]; } // re-initialize PlaneGeometry with origin and direction PlaneGeometry *planeGeometry = static_cast(GetSlicedGeometry(0)->GetPlaneGeometry(0)); planeGeometry->SetOrigin(origin); planeGeometry->GetIndexToWorldTransform()->SetMatrix(matrix); // re-initialize SlicedGeometry3D SlicedGeometry3D *slicedGeometry = GetSlicedGeometry(0); slicedGeometry->InitializeEvenlySpaced(planeGeometry, m_Dimensions[2]); slicedGeometry->SetSpacing(spacing); // re-initialize TimeGeometry ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New(); timeGeometry->Initialize(slicedGeometry, m_Dimensions[3]); SetTimeGeometry(timeGeometry); // clean-up delete[] tmpDimensions; this->Initialize(); } /** * @brief Check whether slice @a s at time @a t in channel @a n is valid, i.e., * is (or can be) inside of the image */ virtual bool IsValidSlice(int s = 0, int t = 0, int n = 0) const; /** * @brief Check whether volume at time @a t in channel @a n is valid, i.e., * is (or can be) inside of the image */ virtual bool IsValidVolume(int t = 0, int n = 0) const; /** * @brief Check whether the channel @a n is valid, i.e., * is (or can be) inside of the image */ virtual bool IsValidChannel(int n = 0) const; /** * @brief Returns true if an image is rotated, i.e. its geometry's * transformation matrix has nonzero elements besides the diagonal. * Non-diagonal elements are checked if larger then 1/1000 of the matrix' trace. */ bool IsRotated() const; /** * @brief Get the sizes of all dimensions as an integer-array. * * @sa GetDimension(int i); */ unsigned int *GetDimensions() const; ImageDescriptor::Pointer GetImageDescriptor() const { return m_ImageDescriptor; } ChannelDescriptor GetChannelDescriptor(int id = 0) const { return m_ImageDescriptor->GetChannelDescriptor(id); } /** \brief Sets a geometry to an image. */ void SetGeometry(BaseGeometry *aGeometry3D) override; /** * @warning for internal use only */ virtual ImageDataItemPointer GetSliceData(int s = 0, int t = 0, int n = 0, void *data = nullptr, ImportMemoryManagementType importMemoryManagement = CopyMemory) const; /** * @warning for internal use only */ virtual ImageDataItemPointer GetVolumeData(int t = 0, int n = 0, void *data = nullptr, ImportMemoryManagementType importMemoryManagement = CopyMemory) const; /** * @warning for internal use only */ virtual ImageDataItemPointer GetChannelData(int n = 0, void *data = nullptr, ImportMemoryManagementType importMemoryManagement = CopyMemory) const; /** \brief Returns a pointer to the ImageStatisticsHolder object that holds all statistics information for the image. All Get-methods for statistics properties formerly accessible directly from an Image object are now moved to the new \a ImageStatisticsHolder object. */ StatisticsHolderPointer GetStatistics() const { return m_ImageStatistics; } protected: mitkCloneMacro(Self); typedef std::lock_guard MutexHolder; int GetSliceIndex(int s = 0, int t = 0, int n = 0) const; int GetVolumeIndex(int t = 0, int n = 0) const; void ComputeOffsetTable(); virtual bool IsValidTimeStep(int t) const; void Expand(unsigned int timeSteps) override; virtual ImageDataItemPointer AllocateSliceData( int s = 0, int t = 0, int n = 0, void *data = nullptr, ImportMemoryManagementType importMemoryManagement = CopyMemory) const; virtual ImageDataItemPointer AllocateVolumeData( int t = 0, int n = 0, void *data = nullptr, ImportMemoryManagementType importMemoryManagement = CopyMemory) const; virtual ImageDataItemPointer AllocateChannelData( int n = 0, void *data = nullptr, ImportMemoryManagementType importMemoryManagement = CopyMemory) const; Image(); Image(const Image &other); ~Image() override; void Clear() override; /** @warning Has to be called by every Initialize method! */ void Initialize() override; void PrintSelf(std::ostream &os, itk::Indent indent) const override; mutable ImageDataItemPointerArray m_Channels; mutable ImageDataItemPointerArray m_Volumes; mutable ImageDataItemPointerArray m_Slices; mutable std::mutex m_ImageDataArraysLock; unsigned int m_Dimension; unsigned int *m_Dimensions; ImageDescriptor::Pointer m_ImageDescriptor; size_t *m_OffsetTable; ImageDataItemPointer m_CompleteData; // Image statistics Holder replaces the former implementation directly inside this class friend class ImageStatisticsHolder; StatisticsHolderPointer m_ImageStatistics; private: ImageDataItemPointer GetSliceData_unlocked( int s, int t, int n, void *data, ImportMemoryManagementType importMemoryManagement) const; ImageDataItemPointer GetVolumeData_unlocked(int t, int n, void *data, ImportMemoryManagementType importMemoryManagement) const; ImageDataItemPointer GetChannelData_unlocked(int n, void *data, ImportMemoryManagementType importMemoryManagement) const; ImageDataItemPointer AllocateSliceData_unlocked( int s, int t, int n, void *data, ImportMemoryManagementType importMemoryManagement) const; ImageDataItemPointer AllocateVolumeData_unlocked(int t, int n, void *data, ImportMemoryManagementType importMemoryManagement) const; ImageDataItemPointer AllocateChannelData_unlocked(int n, void *data, ImportMemoryManagementType importMemoryManagement) const; bool IsSliceSet_unlocked(int s, int t, int n) const; bool IsVolumeSet_unlocked(int t, int n) const; bool IsChannelSet_unlocked(int n) const; /** Stores all existing ImageReadAccessors */ mutable std::vector m_Readers; /** Stores all existing ImageWriteAccessors */ mutable std::vector m_Writers; /** Stores all existing ImageVtkAccessors */ mutable std::vector m_VtkReaders; /** A mutex, which needs to be locked to manage m_Readers and m_Writers */ mutable std::mutex m_ReadWriteLock; /** A mutex, which needs to be locked to manage m_VtkReaders */ mutable std::mutex m_VtkReadersLock; }; /** - * @brief Equal A function comparing two images for beeing equal in meta- and imagedata + * @brief Equal A function comparing two images for being equal in meta- and imagedata * * @ingroup MITKTestingAPI * * Following aspects are tested for equality: * - dimension of the images * - size of the images * - pixel type * - pixel values : pixel values are expected to be identical at each position ( for other options see * mitk::CompareImageFilter ) * * @param rightHandSide An image to be compared * @param leftHandSide An image to be compared * @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 subsequent comparisons are true, false otherwise */ MITKCORE_EXPORT bool Equal(const mitk::Image &leftHandSide, const mitk::Image &rightHandSide, ScalarType eps, bool verbose); } // namespace mitk #endif /* MITKIMAGE_H_HEADER_INCLUDED_C1C2FCD2 */ diff --git a/Modules/Core/include/mitkImageAccessByItk.h b/Modules/Core/include/mitkImageAccessByItk.h index 388e92c867..80a497bf82 100644 --- a/Modules/Core/include/mitkImageAccessByItk.h +++ b/Modules/Core/include/mitkImageAccessByItk.h @@ -1,706 +1,706 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKIMAGEACCESSBYITK_H_HEADER_INCLUDED #define MITKIMAGEACCESSBYITK_H_HEADER_INCLUDED #include #include #include #include #include #include #include #include #include #include namespace mitk { /** * \brief Exception class thrown in #AccessByItk macros. * * This exception can be thrown by the invocation of the #AccessByItk macros, * if the MITK image is of non-expected dimension or pixel type. * * \ingroup Adaptor */ class AccessByItkException : public virtual std::runtime_error { public: AccessByItkException(const std::string &msg) : std::runtime_error(msg) {} ~AccessByItkException() throw() override {} }; } #ifndef DOXYGEN_SKIP #define _accessByItkPixelTypeException(pixelType, pixelTypeSeq) \ { \ std::string msg("Pixel type "); \ msg.append(pixelType.GetPixelTypeAsString()); \ msg.append(" is not in " BOOST_PP_STRINGIZE(pixelTypeSeq)); \ throw mitk::AccessByItkException(msg); \ } #define _accessByItkDimensionException(dim, validDims) \ { \ std::stringstream msg; \ msg << "Dimension " << (dim) << " is not in " << validDims; \ throw mitk::AccessByItkException(msg.str()); \ } #define _checkSpecificDimensionIter(r, mitkImage, dim) \ if (mitkImage->GetDimension() == dim) \ ; \ else #define _checkSpecificDimension(mitkImage, dimSeq) \ BOOST_PP_SEQ_FOR_EACH(_checkSpecificDimensionIter, mitkImage, dimSeq) \ _accessByItkDimensionException(mitkImage->GetDimension(), BOOST_PP_STRINGIZE(dimSeq)) #define _msvc_expand_bug(macro, arg) BOOST_PP_EXPAND(macro arg) //-------------------------------- 0-Arg Versions -------------------------------------- #define _accessByItk(itkImageTypeFunctionAndImageSeq, pixeltype, dimension) \ if (pixelType == mitk::MakePixelType(pixelType.GetNumberOfComponents()) && \ BOOST_PP_SEQ_TAIL(itkImageTypeFunctionAndImageSeq)->GetDimension() == dimension) \ { \ BOOST_PP_SEQ_HEAD(itkImageTypeFunctionAndImageSeq) \ (mitk::ImageToItkImage(BOOST_PP_SEQ_TAIL(itkImageTypeFunctionAndImageSeq)).GetPointer()); \ } \ else #define _accessByItkArgs(itkImageTypeFunction, type) (itkImageTypeFunction, BOOST_PP_TUPLE_REM(2) type) // product will be of the form ((itkImageTypeFunction)(mitkImage))(short)(2) for pixel type short and dimension 2 #ifdef _MSC_VER #define _accessByItkProductIter(r, product) \ _msvc_expand_bug( \ _accessByItk, \ _msvc_expand_bug(_accessByItkArgs, (BOOST_PP_SEQ_HEAD(product), BOOST_PP_SEQ_TO_TUPLE(BOOST_PP_SEQ_TAIL(product))))) #else #define _accessByItkProductIter(r, product) \ BOOST_PP_EXPAND( \ _accessByItk _accessByItkArgs(BOOST_PP_SEQ_HEAD(product), BOOST_PP_SEQ_TO_TUPLE(BOOST_PP_SEQ_TAIL(product)))) #endif #define _accessFixedTypeByItk(itkImageTypeFunction, mitkImage, pixelTypeSeq, dimSeq) \ BOOST_PP_SEQ_FOR_EACH_PRODUCT(_accessByItkProductIter, (((itkImageTypeFunction)(mitkImage)))(pixelTypeSeq)(dimSeq)) //-------------------------------- n-Arg Versions -------------------------------------- #define _accessByItk_n(itkImageTypeFunctionAndImageSeq, pixeltype, dimension, args) \ if (pixelType == mitk::MakePixelType(pixelType.GetNumberOfComponents()) && \ BOOST_PP_SEQ_TAIL(itkImageTypeFunctionAndImageSeq)->GetDimension() == dimension) \ { \ BOOST_PP_SEQ_HEAD(itkImageTypeFunctionAndImageSeq) \ (mitk::ImageToItkImage(BOOST_PP_SEQ_TAIL(itkImageTypeFunctionAndImageSeq)).GetPointer(), \ BOOST_PP_TUPLE_REM(BOOST_PP_SEQ_HEAD(args)) BOOST_PP_SEQ_TAIL(args)); \ } \ else #define _accessByItkArgs_n(itkImageTypeFunction, type, args) (itkImageTypeFunction, BOOST_PP_TUPLE_REM(2) type, args) // product will be of the form (((itkImageTypeFunction)(mitkImage))(3)(a,b,c))(short)(2) // for the variable argument list a,b,c and for pixel type short and dimension 2 #ifdef _MSC_VER #define _accessByItkProductIter_n(r, product) \ _msvc_expand_bug(_accessByItk_n, \ _msvc_expand_bug(_accessByItkArgs_n, \ (BOOST_PP_SEQ_HEAD(BOOST_PP_SEQ_HEAD(product)), \ BOOST_PP_SEQ_TO_TUPLE(BOOST_PP_SEQ_TAIL(product)), \ BOOST_PP_SEQ_TAIL(BOOST_PP_SEQ_HEAD(product))))) #else #define _accessByItkProductIter_n(r, product) \ BOOST_PP_EXPAND(_accessByItk_n _accessByItkArgs_n(BOOST_PP_SEQ_HEAD(BOOST_PP_SEQ_HEAD(product)), \ BOOST_PP_SEQ_TO_TUPLE(BOOST_PP_SEQ_TAIL(product)), \ BOOST_PP_SEQ_TAIL(BOOST_PP_SEQ_HEAD(product)))) #endif #define _accessFixedTypeByItk_n(itkImageTypeFunction, mitkImage, pixelTypeSeq, dimSeq, va_tuple) \ BOOST_PP_SEQ_FOR_EACH_PRODUCT( \ _accessByItkProductIter_n, \ ((((itkImageTypeFunction)(mitkImage))(MITK_PP_ARG_COUNT va_tuple)va_tuple))(pixelTypeSeq)(dimSeq)) #endif // DOXYGEN_SKIP /** * \brief Access a MITK image by an ITK image * * Define a templated function or method (\a itkImageTypeFunction) * within which the mitk-image (\a mitkImage) is accessed: * \code * template < typename TPixel, unsigned int VImageDimension > * void ExampleFunction( itk::Image* itkImage ); * \endcode * * The itk::Image passed to the function/method has the same * data-pointer as the mitk-image. Depending on the const-ness of the * \c mitkImage, your templated access function needs to take a const or * non-const itk::Image pointer and you will get read-only or full read/write * access to the data vector of the mitk-image using the itk-image. * * Example code using the access function above: * \code * mitk::Image* inputMitkImage = ... * try * { * AccessByItk(inputMitkImage, ExampleFunction); * } * catch (const mitk::AccessByItkException& e) * { * // mitk::Image is of wrong pixel type or dimension, * // insert error handling here * } * \endcode * * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * \note If your inputMitkImage is an mitk::Image::Pointer, use * inputMitkImage.GetPointer() * \note If you need to pass additional parameters to your * access-function (\a itkImageTypeFunction), use #AccessByItk_n. * \note If you know the dimension of your input mitk-image, * it is better to use AccessFixedDimensionByItk (less code * is generated). * \sa AccessFixedDimensionByItk * \sa AccessFixedTypeByItk * \sa AccessFixedPixelTypeByItk * \sa AccessByItk_n * * \ingroup Adaptor */ #define AccessByItk(mitkImage, itkImageTypeFunction) \ AccessFixedTypeByItk( \ mitkImage, itkImageTypeFunction, MITK_ACCESSBYITK_PIXEL_TYPES_SEQ, MITK_ACCESSBYITK_DIMENSIONS_SEQ) /** * \brief Access a mitk-image with known pixeltype (but unknown dimension) by an itk-image. * * For usage, see #AccessByItk. * * \param pixelTypeSeq A sequence of pixel types, like (short)(char)(int) * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * If the image has a different pixel type, a mitk::AccessByItkException exception is * thrown. If you do not know the pixel type for sure, use #AccessByItk. * * \sa AccessByItk * \sa AccessFixedDimensionByItk * \sa AccessFixedTypeByItk * \sa AccessFixedPixelTypeByItk_n * * \ingroup Adaptor */ #define AccessFixedPixelTypeByItk(mitkImage, itkImageTypeFunction, pixelTypeSeq) \ AccessFixedTypeByItk(mitkImage, itkImageTypeFunction, pixelTypeSeq, MITK_ACCESSBYITK_DIMENSIONS_SEQ) /** * \brief Access a mitk-image with an integral pixel type by an itk-image * * See #AccessByItk for details. * * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * \sa AccessFixedPixelTypeByItk * \sa AccessByItk * \sa AccessIntegralPixelTypeByItk_n */ #define AccessIntegralPixelTypeByItk(mitkImage, itkImageTypeFunction) \ AccessFixedTypeByItk( \ mitkImage, itkImageTypeFunction, MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES_SEQ, MITK_ACCESSBYITK_DIMENSIONS_SEQ) /** * \brief Access a mitk-image with a floating point pixel type by an ITK image * * See #AccessByItk for details. * * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * \sa AccessFixedPixelTypeByItk * \sa AccessByItk * \sa AccessFloatingPixelTypeByItk_n */ #define AccessFloatingPixelTypeByItk(mitkImage, itkImageTypeFunction) \ AccessFixedTypeByItk( \ mitkImage, itkImageTypeFunction, MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES_SEQ, MITK_ACCESSBYITK_DIMENSIONS_SEQ) #define AccessVectorPixelTypeByItk(mitkImage, itkImageTypeFunction) \ AccessFixedTypeByItk( \ mitkImage, itkImageTypeFunction, MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES_SEQ, MITK_ACCESSBYITK_DIMENSIONS_SEQ) /** * \brief Access a mitk-image with known dimension by an itk-image * * For usage, see #AccessByItk. * * \param dimension Dimension of the mitk-image. If the image has a different dimension, * a mitk::AccessByItkException exception is thrown. * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * \note If you do not know the dimension for sure, use #AccessByItk. * * \sa AccessByItk * \sa AccessFixedDimensionByItk_n * \sa AccessFixedTypeByItk * \sa AccessFixedPixelTypeByItk * * \ingroup Adaptor */ #define AccessFixedDimensionByItk(mitkImage, itkImageTypeFunction, dimension) \ AccessFixedTypeByItk(mitkImage, itkImageTypeFunction, MITK_ACCESSBYITK_PIXEL_TYPES_SEQ, (dimension)) #define AccessVectorFixedDimensionByItk(mitkImage, itkImageTypeFunction, dimension) \ AccessFixedTypeByItk(mitkImage, itkImageTypeFunction, MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES_SEQ, (dimension)) /** * \brief Access a mitk-image with known type (pixel type and dimension) by an itk-image. * * The provided mitk-image must be in the set of types created by taking the * cartesian product of the pixel type sequence and the dimension sequence. * For example, a call to * \code * AccessFixedTypeByItk(myMitkImage, MyAccessFunction, (short)(int), (2)(3)) * \endcode * asserts that the type of myMitkImage (pixeltype,dim) is in the set {(short,2),(short,3),(int,2),(int,3)}. * For more information, see #AccessByItk. * * \param pixelTypeSeq A sequence of pixel types, like (short)(char)(int). * \param dimSeq A sequence of dimensions, like (2)(3). * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * If the image has a different dimension or pixel type, * a mitk::AccessByItkException exception is thrown. * * \note If you do not know the dimension for sure, use #AccessByItk. * * \sa AccessByItk * \sa AccessFixedDimensionByItk * \sa AccessFixedTypeByItk_n * \sa AccessFixedPixelTypeByItk * * \ingroup Adaptor */ #define AccessFixedTypeByItk(mitkImage, itkImageTypeFunction, pixelTypeSeq, dimSeq) \ \ { \ const mitk::PixelType &pixelType = mitkImage->GetPixelType(); \ _checkSpecificDimension(mitkImage, dimSeq); \ _accessFixedTypeByItk(itkImageTypeFunction, mitkImage, pixelTypeSeq, dimSeq) \ _accessByItkPixelTypeException(mitkImage->GetPixelType(), pixelTypeSeq) \ } //------------------------------ n-Arg Access Macros ----------------------------------- /** * \brief Access a MITK image by an ITK image with one or more parameters. * - * Define a templated function or method (\a itkImageTypeFunction) with one ore more + * Define a templated function or method (\a itkImageTypeFunction) with one or more * additional parameters, within which the mitk-image (\a mitkImage) is accessed: * \code * template < typename TPixel, unsigned int VImageDimension > * void ExampleFunction( itk::Image* itkImage, SomeType param); * \endcode * * The itk::Image passed to the function/method has the same * data-pointer as the mitk-image. So you have full read- and write- * access to the data vector of the mitk-image using the itk-image. * Call by: * \code * SomeType param = ... * mitk::Image* inputMitkImage = ... * try * { * AccessByItk_n(inputMitkImage, ExampleFunction, (param)); * } * catch (const mitk::AccessByItkException& e) * { * // mitk::Image is of wrong pixel type or dimension, * // insert error handling here * } * \endcode * * \param va_tuple A variable length tuple containing the arguments to be passed * to the access function itkImageTypeFunction, e.g. ("first", 2, THIRD). * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * \note If your inputMitkImage is an mitk::Image::Pointer, use * inputMitkImage.GetPointer() * \note If you know the dimension of your input mitk-image, * it is better to use AccessFixedDimensionByItk_n (less code * is generated). * \sa AccessFixedDimensionByItk_n * \sa AccessFixedTypeByItk_n * \sa AccessFixedPixelTypeByItk_n * \sa AccessByItk * * \ingroup Adaptor */ #define AccessByItk_n(mitkImage, itkImageTypeFunction, va_tuple) \ AccessFixedTypeByItk_n( \ mitkImage, itkImageTypeFunction, MITK_ACCESSBYITK_PIXEL_TYPES_SEQ, MITK_ACCESSBYITK_DIMENSIONS_SEQ, va_tuple) /** * \brief Access a mitk-image with known pixeltype (but unknown dimension) by an itk-image * with one or more parameters. * * For usage, see #AccessByItk_n. * * \param va_tuple A variable length tuple containing the arguments to be passed * to the access function itkImageTypeFunction, e.g. ("first", 2, THIRD). * \param pixelTypeSeq A sequence of pixel types, like (short)(char)(int). * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * If the image has a different pixel type, a mitk::AccessByItkException exception is * thrown. If you do not know the pixel type for sure, use #AccessByItk_n. * * \sa AccessByItk_n * \sa AccessFixedDimensionByItk_n * \sa AccessFixedTypeByItk_n * \sa AccessFixedPixelTypeByItk * * \ingroup Adaptor */ #define AccessFixedPixelTypeByItk_n(mitkImage, itkImageTypeFunction, pixelTypeSeq, va_tuple) \ AccessFixedTypeByItk_n(mitkImage, itkImageTypeFunction, pixelTypeSeq, MITK_ACCESSBYITK_DIMENSIONS_SEQ, va_tuple) /** * \brief Access an mitk::Image with an integral pixel type by an ITK image with * one or more parameters. * * See #AccessByItk_n for details. * * \param va_tuple A variable length tuple containing the arguments to be passed * to the access function itkImageTypeFunction, e.g. ("first", 2, THIRD). * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * \sa AccessFixedPixelTypeByItk_n * \sa AccessByItk_n * \sa AccessIntegralPixelTypeByItk */ #define AccessIntegralPixelTypeByItk_n(mitkImage, itkImageTypeFunction, va_tuple) \ AccessFixedTypeByItk_n(mitkImage, \ itkImageTypeFunction, \ MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES_SEQ, \ MITK_ACCESSBYITK_DIMENSIONS_SEQ, \ va_tuple) /** * \brief Access an mitk::Image with a floating point pixel type by an ITK image * with one or more parameters. * * See #AccessByItk_n for details. * * \param va_tuple A variable length tuple containing the arguments to be passed * to the access function itkImageTypeFunction, e.g. ("first", 2, THIRD). * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * \sa AccessFixedPixelTypeByItk_n * \sa AccessByItk_n * \sa AccessFloatingPixelTypeByItk */ #define AccessFloatingPixelTypeByItk_n(mitkImage, itkImageTypeFunction, va_tuple) \ AccessFixedTypeByItk_n(mitkImage, \ itkImageTypeFunction, \ MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES_SEQ, \ MITK_ACCESSBYITK_DIMENSIONS_SEQ, \ va_tuple) /** * \brief Access a vector mitk::Image by an ITK vector image with one or more parameters. * * See #AccessByItk_n for details. * * \param va_tuple A variable length tuple containing the arguments to be passed * to the access function itkImageTypeFunction, e.g. ("first", 2, THIRD). * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * \sa AccessFixedPixelTypeByItk_n * \sa AccessByItk_n */ #define AccessVectorPixelTypeByItk_n(mitkImage, itkImageTypeFunction, va_tuple) \ AccessFixedTypeByItk_n(mitkImage, \ itkImageTypeFunction, \ MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES_SEQ, \ MITK_ACCESSBYITK_DIMENSIONS_SEQ, \ va_tuple) /** * \brief Access a mitk-image with known dimension by an itk-image with * one or more parameters. * * For usage, see #AccessByItk_n. * * \param dimension Dimension of the mitk-image. If the image has a different dimension, * a mitk::AccessByItkException exception is thrown. * \param va_tuple A variable length tuple containing the arguments to be passed * to the access function itkImageTypeFunction, e.g. ("first", 2, THIRD). * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * \note If you do not know the dimension for sure, use #AccessByItk_n. * * \sa AccessByItk_n * \sa AccessFixedDimensionByItk * \sa AccessFixedTypeByItk_n * \sa AccessFixedPixelTypeByItk_n * * \ingroup Adaptor */ #define AccessFixedDimensionByItk_n(mitkImage, itkImageTypeFunction, dimension, va_tuple) \ AccessFixedTypeByItk_n(mitkImage, itkImageTypeFunction, MITK_ACCESSBYITK_PIXEL_TYPES_SEQ, (dimension), va_tuple) /** * \brief Access a vector mitk-image with known dimension by a ITK vector image with * one or more parameters. * * For usage, see #AccessByItk_n. * * \param dimension Dimension of the mitk-image. If the image has a different dimension, * a mitk::AccessByItkException exception is thrown. * \param va_tuple A variable length tuple containing the arguments to be passed * to the access function itkImageTypeFunction, e.g. ("first", 2, THIRD). * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * \note If you do not know the dimension for sure, use #AccessVectorPixelTypeByItk_n. * * \sa AccessByItk_n * \sa AccessVectorPixelTypeByItk_n * \sa AccessFixedTypeByItk_n * * \ingroup Adaptor */ #define AccessVectorFixedDimensionByItk_n(mitkImage, itkImageTypeFunction, dimension, va_tuple) \ AccessFixedTypeByItk_n( \ mitkImage, itkImageTypeFunction, MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES_SEQ, (dimension), va_tuple) /** * \brief Access a mitk-image with known type (pixel type and dimension) by an itk-image * with one or more parameters. * * For usage, see AccessFixedTypeByItk. * * \param pixelTypeSeq A sequence of pixel types, like (short)(char)(int). * \param dimSeq A sequence of dimensions, like (2)(3). * \param va_tuple A variable length tuple containing the arguments to be passed * to the access function itkImageTypeFunction, e.g. ("first", 2, THIRD). * \param mitkImage The MITK input image. * \param itkImageTypeFunction The templated access-function to be called. * * \throws mitk::AccessByItkException If mitkImage is of unsupported pixel type or dimension. * * If the image has a different dimension or pixel type, * a mitk::AccessByItkException exception is thrown. * * \note If you do not know the dimension for sure, use #AccessByItk_n. * * \sa AccessByItk_n * \sa AccessFixedDimensionByItk_n * \sa AccessFixedTypeByItk * \sa AccessFixedPixelTypeByItk_n * * \ingroup Adaptor */ #define AccessFixedTypeByItk_n(mitkImage, itkImageTypeFunction, pixelTypeSeq, dimSeq, va_tuple) \ \ { \ const mitk::PixelType &pixelType = mitkImage->GetPixelType(); \ _checkSpecificDimension(mitkImage, dimSeq); \ _accessFixedTypeByItk_n(itkImageTypeFunction, mitkImage, pixelTypeSeq, dimSeq, va_tuple) \ _accessByItkPixelTypeException(mitkImage->GetPixelType(), pixelTypeSeq) \ } //------------------------- For back-wards compatibility ------------------------------- #define AccessByItk_1(mitkImage, itkImageTypeFunction, arg1) AccessByItk_n(mitkImage, itkImageTypeFunction, (arg1)) #define AccessFixedPixelTypeByItk_1(mitkImage, itkImageTypeFunction, pixelTypeSeq, arg1) \ AccessFixedPixelTypeByItk_n(mitkImage, itkImageTypeFunction, pixelTypeSeq, (arg1)) #define AccessFixedDimensionByItk_1(mitkImage, itkImageTypeFunction, dimension, arg1) \ AccessFixedDimensionByItk_n(mitkImage, itkImageTypeFunction, dimension, (arg1)) #define AccessFixedTypeByItk_1(mitkImage, itkImageTypeFunction, pixelTypeSeq, dimSeq, arg1) \ AccessFixedTypeByItk_n(mitkImage, itkImageTypeFunction, pixelTypeSeq, dimSeq, (arg1)) #define AccessByItk_2(mitkImage, itkImageTypeFunction, arg1, arg2) \ AccessByItk_n(mitkImage, itkImageTypeFunction, (arg1, arg2)) #define AccessFixedPixelTypeByItk_2(mitkImage, itkImageTypeFunction, pixelTypeSeq, arg1, arg2) \ AccessFixedPixelTypeByItk_n(mitkImage, itkImageTypeFunction, pixelTypeSeq, (arg1, arg2)) #define AccessFixedDimensionByItk_2(mitkImage, itkImageTypeFunction, dimension, arg1, arg2) \ AccessFixedDimensionByItk_n(mitkImage, itkImageTypeFunction, dimension, (arg1, arg2)) #define AccessFixedTypeByItk_2(mitkImage, itkImageTypeFunction, pixelTypeSeq, dimSeq, arg1, arg2) \ AccessFixedTypeByItk_n(mitkImage, itkImageTypeFunction, pixelTypeSeq, dimSeq, (arg1, arg2)) #define AccessByItk_3(mitkImage, itkImageTypeFunction, arg1, arg2, arg3) \ AccessByItk_n(mitkImage, itkImageTypeFunction, (arg1, arg2, arg3)) #define AccessFixedPixelTypeByItk_3(mitkImage, itkImageTypeFunction, pixelTypeSeq, arg1, arg2, arg3) \ AccessFixedPixelTypeByItk_n(mitkImage, itkImageTypeFunction, pixelTypeSeq, (arg1, arg2, arg3)) #define AccessFixedDimensionByItk_3(mitkImage, itkImageTypeFunction, dimension, arg1, arg2, arg3) \ AccessFixedDimensionByItk_n(mitkImage, itkImageTypeFunction, dimension, (arg1, arg2, arg3)) #define AccessFixedTypeByItk_3(mitkImage, itkImageTypeFunction, pixelTypeSeq, dimSeq, arg1, arg2, arg3) \ AccessFixedTypeByItk_n(mitkImage, itkImageTypeFunction, pixelTypeSeq, dimSeq, (arg1, arg2, arg3)) //----------------------------- Access two MITK Images --------------------------------- #ifndef DOXYGEN_SKIP #define _accessTwoImagesByItk(itkImageTypeFunction, pixeltype1, dim1, pixeltype2, dim2) \ if (pixelType1 == mitk::MakePixelType>() && \ pixelType2 == mitk::MakePixelType>() && constImage1->GetDimension() == dim1 && \ constImage2->GetDimension() == dim2) \ { \ typedef itk::Image ImageType1; \ typedef itk::Image ImageType2; \ typedef mitk::ImageToItk ImageToItkType1; \ typedef mitk::ImageToItk ImageToItkType2; \ itk::SmartPointer imagetoitk1 = ImageToItkType1::New(); \ imagetoitk1->SetInput(nonConstImage1); \ imagetoitk1->Update(); \ itk::SmartPointer imagetoitk2 = ImageToItkType2::New(); \ imagetoitk2->SetInput(nonConstImage2); \ imagetoitk2->Update(); \ itkImageTypeFunction(imagetoitk1->GetOutput(), imagetoitk2->GetOutput()); \ } \ else #define _accessTwoImagesByItkArgs2(itkImageTypeFunction, type1, type2) \ (itkImageTypeFunction, BOOST_PP_TUPLE_REM(2) type1, BOOST_PP_TUPLE_REM(2) type2) #define _accessTwoImagesByItkArgs(product) \ BOOST_PP_EXPAND(_accessTwoImagesByItkArgs2 BOOST_PP_EXPAND( \ (BOOST_PP_SEQ_HEAD(product), BOOST_PP_TUPLE_REM(2) BOOST_PP_SEQ_TO_TUPLE(BOOST_PP_SEQ_TAIL(product))))) // product is of the form (itkImageTypeFunction)((short,2))((char,2)) #ifdef _MSC_VER #define _accessTwoImagesByItkIter(r, product) \ BOOST_PP_EXPAND(_accessTwoImagesByItk _msvc_expand_bug( \ _accessTwoImagesByItkArgs2, \ (BOOST_PP_SEQ_HEAD(product), \ _msvc_expand_bug(BOOST_PP_TUPLE_REM(2), BOOST_PP_EXPAND(BOOST_PP_SEQ_TO_TUPLE(BOOST_PP_SEQ_TAIL(product))))))) #else #define _accessTwoImagesByItkIter(r, product) BOOST_PP_EXPAND(_accessTwoImagesByItk _accessTwoImagesByItkArgs(product)) #endif #define _accessTwoImagesByItkForEach(itkImageTypeFunction, tseq1, tseq2) \ BOOST_PP_SEQ_FOR_EACH_PRODUCT(_accessTwoImagesByItkIter, ((itkImageTypeFunction))(tseq1)(tseq2)) #endif // DOXYGEN_SKIP /** * \brief Access two mitk-images with known dimension by itk-images * * Define a templated function or method (\a itkImageTypeFunction) * within which the mitk-images (\a mitkImage1 and \a mitkImage2) are accessed: * \code * template * void ExampleFunctionTwoImages(itk::Image* itkImage1, itk::Image* itkImage2); * \endcode * * The itk::Image passed to the function/method has the same * data-pointer as the mitk-image. So you have full read- and write- * access to the data vector of the mitk-image using the itk-image. * Call by: * \code * mitk::Image* inputMitkImage1 = ... * mitk::Image* inputMitkImage2 = ... * try * { * AccessTwoImagesFixedDimensionByItk(inputMitkImage1, inputMitkImage2, ExampleFunctionTwoImages, 3); * } * catch (const mitk::AccessByItkException& e) * { * // mitk::Image arguments are of wrong pixel type or dimension, * // insert error handling here * } * \endcode * * \note If your inputMitkImage1 or inputMitkImage2 is a mitk::Image::Pointer, use * inputMitkImage1.GetPointer(). * * \param mitkImage1 The first MITK input image. * \param mitkImage2 The second MITK input image. * \param itkImageTypeFunction The name of the template access-function to be called. * \param dimension Dimension of the two mitk-images. * * \throws mitk::AccessByItkException If mitkImage1 and mitkImage2 have different dimensions or * one of the images is of unsupported pixel type or dimension. * * \sa #AccessByItk * * \ingroup Adaptor */ #define AccessTwoImagesFixedDimensionByItk(mitkImage1, mitkImage2, itkImageTypeFunction, dimension) \ \ { \ const mitk::PixelType &pixelType1 = mitkImage1->GetPixelType(); \ const mitk::PixelType &pixelType2 = mitkImage2->GetPixelType(); \ const mitk::Image *constImage1 = mitkImage1; \ const mitk::Image *constImage2 = mitkImage2; \ mitk::Image *nonConstImage1 = const_cast(constImage1); \ mitk::Image *nonConstImage2 = const_cast(constImage2); \ nonConstImage1->Update(); \ nonConstImage2->Update(); \ _checkSpecificDimension(mitkImage1, (dimension)); \ _checkSpecificDimension(mitkImage2, (dimension)); \ _accessTwoImagesByItkForEach( \ itkImageTypeFunction, MITK_ACCESSBYITK_TYPES_DIMN_SEQ(dimension), MITK_ACCESSBYITK_TYPES_DIMN_SEQ(dimension)) \ { \ std::string msg("Pixel type "); \ msg.append(pixelType1.GetComponentTypeAsString()); \ msg.append(" or pixel type "); \ msg.append(pixelType2.GetComponentTypeAsString()); \ msg.append(" is not in " BOOST_PP_STRINGIZE(MITK_ACCESSBYITK_TYPES_DIMN_SEQ(dimension))); \ throw mitk::AccessByItkException(msg); \ } \ } #endif // of MITKIMAGEACCESSBYITK_H_HEADER_INCLUDED diff --git a/Modules/Core/include/mitkImageCaster.h b/Modules/Core/include/mitkImageCaster.h index 46aeb9fdaf..e855aac3fd 100644 --- a/Modules/Core/include/mitkImageCaster.h +++ b/Modules/Core/include/mitkImageCaster.h @@ -1,62 +1,62 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKIMAGECASTER_H #define MITKIMAGECASTER_H #include #include #include #include #include #include #include #define DeclareMitkImageCasterMethods(r, data, type) \ static void CastToItkImage(const mitk::Image *, itk::SmartPointer> &); \ static void CastToMitkImage(const itk::Image *, itk::SmartPointer &); namespace mitk { /// /// \brief This class is just a proxy for global functions which are needed by the - /// python wrapping process since global functions cannnot be wrapped. Static method + /// python wrapping process since global functions cannot be wrapped. Static method /// can be wrapped though. /// class MITKCORE_EXPORT ImageCaster { public: BOOST_PP_SEQ_FOR_EACH(DeclareMitkImageCasterMethods, _, MITK_ACCESSBYITK_TYPES_DIMN_SEQ(2)) BOOST_PP_SEQ_FOR_EACH(DeclareMitkImageCasterMethods, _, MITK_ACCESSBYITK_TYPES_DIMN_SEQ(3)) static void CastBaseData(mitk::BaseData *const, itk::SmartPointer &); }; class MITKCORE_EXPORT Caster { public: static void Cast(BaseData *dat, Surface *surface); }; class MITKCORE_EXPORT RendererAccess { public: static void Set3DRenderer(vtkRenderer *renderer); static vtkRenderer *Get3DRenderer(); protected: static vtkRenderer *m_3DRenderer; }; } // namespace mitk #endif // MITKIMAGECASTER_H diff --git a/Modules/Core/include/mitkImageDescriptor.h b/Modules/Core/include/mitkImageDescriptor.h index e9e082a3d7..57fde4f2b3 100644 --- a/Modules/Core/include/mitkImageDescriptor.h +++ b/Modules/Core/include/mitkImageDescriptor.h @@ -1,122 +1,122 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKIMAGEDESCRIPTOR_H #define MITKIMAGEDESCRIPTOR_H #include #include #include #include "mitkChannelDescriptor.h" #include "mitkCommon.h" /// Defines the maximum of 8 dimensions per image channel #define MAX_IMAGE_DIMENSIONS 8 namespace mitk { /** \brief An object to hold all essential information about an Image object The ImageDescriptor holds an std::vector of pointers to ChannelDescriptor together with the - information about the image's dimensions. The general assumption ist, that each channel of an image + information about the image's dimensions. The general assumption is that each channel of an image has to have the same geometry. \sa Image, ChannelDescriptor */ class MITKCORE_EXPORT ImageDescriptor : public itk::Object { public: mitkClassMacroItkParent(ImageDescriptor, itk::Object); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** Insert new channel @param ptype Pixel Type @param name channel's name */ void AddNewChannel(mitk::PixelType ptype, const char *name = nullptr); /** \brief Initialize the image descriptor by the dimensions */ void Initialize(const unsigned int *dims, const unsigned int dim); /** \brief Initialize the descriptor by an referenced Descriptor */ void Initialize(const ImageDescriptor::Pointer refDescriptor, unsigned int channel = 0); /** \brief Get the C-array of unsigned int holding the size for each dimension of the image - The C-array has allways lenght of MAX_IMAGE_DIMENSIONS + The C-array has always length of MAX_IMAGE_DIMENSIONS */ const unsigned int *GetDimensions() const { return m_Dimensions; } /** \brief Get the number dimensions used (e.g. non-zero size) The return value does not exceed MAX_IMAGE_DIMENSIONS */ unsigned int GetNumberOfDimensions() const { return m_NumberOfDimensions; } /** \brief Get the name of selected channel If the name of the channel wasn't initialized, the string returned is set to "Unnamed [ ]" \sa PixelType, ChannelDescriptor */ const std::string GetChannelName(unsigned int id) const; /** \brief Get the pixel type of a channel specified by its name Returns an uninitialized PixelType object if no channel with given name was found */ PixelType GetChannelTypeByName(const char *name) const; /** \brief Get the pixel type of a channel specified by its id Returns an uninitialized PixelType object if no channel with given id was found */ PixelType GetChannelTypeById(unsigned int id) const; /** \brief Get the ChannelDescriptor for a channel specified by its id */ ChannelDescriptor GetChannelDescriptor(unsigned int id = 0) const; /** \brief Get the count of channels used */ unsigned int GetNumberOfChannels() const { return m_NumberOfChannels; } protected: /** Protected constructor */ ImageDescriptor(); - /** Protected desctructor */ + /** Protected destructor */ ~ImageDescriptor() override{}; private: /** A std::vector holding a pointer to a ChannelDescriptor for each active channel of the image */ std::vector m_ChannelDesc; /** A vector holding the names of corresponding channels */ std::vector m_ChannelNames; /** Constant iterator for traversing the vector of channel's names */ typedef std::vector::const_iterator ConstChannelNamesIter; /** Constant iterator for traversing the vector of ChannelDescriptors */ typedef std::vector::const_iterator ConstChannelsIter; unsigned int m_NumberOfChannels; unsigned int m_NumberOfDimensions; unsigned int m_Dimensions[MAX_IMAGE_DIMENSIONS]; }; } // end namespace #endif // MITKIMAGEDESCRIPTOR_H diff --git a/Modules/Core/include/mitkImageGenerator.h b/Modules/Core/include/mitkImageGenerator.h index fee6d12c9d..b6700090f8 100644 --- a/Modules/Core/include/mitkImageGenerator.h +++ b/Modules/Core/include/mitkImageGenerator.h @@ -1,236 +1,236 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef ImageGenerator_H_HEADER_INCLUDED #define ImageGenerator_H_HEADER_INCLUDED #include "mitkImageWriteAccessor.h" #include #include #include #include namespace mitk { /** * @brief generator for synthetic MITK images * This is a helper class to generate synthetic MITK images (random or gradient). * * @ingroup IO */ class MITKCORE_EXPORT ImageGenerator { public: /** * \brief Generates gradient image with the defined size and spacing */ template static mitk::Image::Pointer GenerateGradientImage(unsigned int dimX, unsigned int dimY, unsigned int dimZ, float spacingX = 1, float spacingY = 1, float spacingZ = 1) { typedef itk::Image ImageType; typename ImageType::RegionType imageRegion; imageRegion.SetSize(0, dimX); imageRegion.SetSize(1, dimY); imageRegion.SetSize(2, dimZ); typename ImageType::SpacingType spacing; spacing[0] = spacingX; spacing[1] = spacingY; spacing[2] = spacingZ; mitk::Point3D origin; origin.Fill(0.0); itk::Matrix directionMatrix; directionMatrix.SetIdentity(); typename ImageType::Pointer image = ImageType::New(); image->SetSpacing(spacing); image->SetOrigin(origin); image->SetDirection(directionMatrix); image->SetLargestPossibleRegion(imageRegion); image->SetBufferedRegion(imageRegion); image->SetRequestedRegion(imageRegion); image->Allocate(); image->FillBuffer(0.0); typedef itk::ImageRegionIterator IteratorOutputType; IteratorOutputType it(image, imageRegion); it.GoToBegin(); TPixelType val = 0; while (!it.IsAtEnd()) { it.Set(val); val++; ++it; } mitk::Image::Pointer mitkImage = mitk::Image::New(); mitkImage->InitializeByItk(image.GetPointer()); mitkImage->SetVolume(image->GetBufferPointer()); return mitkImage; } /** * \brief Generates an image of a same geometry as the one given as reference The image buffer is filled to the fill_value given as parameter */ template static mitk::Image::Pointer GenerateImageFromReference(mitk::Image::Pointer reference, TPixelType fill_value) { mitk::Image::Pointer output = mitk::Image::New(); mitk::PixelType output_type = MakeScalarPixelType(); // all metadata (except type) come from reference image output->SetGeometry(reference->GetGeometry()); output->Initialize(output_type, reference->GetDimension(), reference->GetDimensions()); // get a pointer to the image buffer to write into TPixelType *imageBuffer = nullptr; try { mitk::ImageWriteAccessor writeAccess(output); imageBuffer = static_cast(writeAccess.GetData()); } catch (...) { MITK_ERROR << "Write access not granted on mitk::Image."; } - // fill the buffer with the specifed value + // fill the buffer with the specified value for (unsigned int i = 0; i < output->GetVolumeData(0)->GetSize(); i++) { imageBuffer[i] = fill_value; } return output; } /*! \brief Generates random image with the defined size and spacing */ template static mitk::Image::Pointer GenerateRandomImage(unsigned int dimX, unsigned int dimY, unsigned int dimZ = 1, unsigned int dimT = 1, mitk::ScalarType spacingX = 1, mitk::ScalarType spacingY = 1, mitk::ScalarType spacingZ = 1, const double randomMax = 1000.0f, const double randMin = 0.0f) { // set the data type according to the template mitk::PixelType type = MakeScalarPixelType(); // type.Initialize(typeid(TPixelType)); - // initialize the MITK image with given dimenion and data type + // initialize the MITK image with given dimension and data type mitk::Image::Pointer output = mitk::Image::New(); auto dimensions = new unsigned int[4]; unsigned int numberOfDimensions = 0; unsigned int bufferSize = 0; // check which dimension is needed if (dimT <= 1) { if (dimZ <= 1) { // 2D numberOfDimensions = 2; dimensions[0] = dimX; dimensions[1] = dimY; bufferSize = dimX * dimY; } else { // 3D numberOfDimensions = 3; dimensions[0] = dimX; dimensions[1] = dimY; dimensions[2] = dimZ; bufferSize = dimX * dimY * dimZ; } } else { // 4D numberOfDimensions = 4; dimensions[0] = dimX; dimensions[1] = dimY; dimensions[2] = dimZ; dimensions[3] = dimT; bufferSize = dimX * dimY * dimZ * dimT; } output->Initialize(type, numberOfDimensions, dimensions); mitk::Vector3D spacing; spacing[0] = spacingX; spacing[1] = spacingY; spacing[2] = spacingZ; output->SetSpacing(spacing); // get a pointer to the image buffer to write into TPixelType *imageBuffer = nullptr; try { mitk::ImageWriteAccessor writeAccess(output); imageBuffer = static_cast(writeAccess.GetData()); } catch (...) { MITK_ERROR << "Write access not granted on mitk::Image."; } // initialize the random generator itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer randomGenerator = itk::Statistics::MersenneTwisterRandomVariateGenerator::New(); randomGenerator->Initialize(); // fill the buffer for each pixel/voxel for (unsigned int i = 0; i < bufferSize; i++) { // the comparison of the component type is sufficient enough since the mitk::PixelType type object is // created as SCALAR and hence does not need the comparison against type.GetPixelTypeId() == // itk::IOPixelEnum::SCALAR if (type.GetComponentType() == itk::IOComponentEnum::INT) // call integer function { imageBuffer[i] = (TPixelType)randomGenerator->GetIntegerVariate((int)randomMax); // TODO random generator does not support integer values in a given range (e.g. from 5-10) // range is always [0, (int)randomMax] } else if ((type.GetComponentType() == itk::IOComponentEnum::DOUBLE) || (type.GetComponentType() == itk::IOComponentEnum::FLOAT)) // call floating point function { imageBuffer[i] = (TPixelType)randomGenerator->GetUniformVariate(randMin, randomMax); } else if (type.GetComponentType() == itk::IOComponentEnum::UCHAR) { // use the integer randomGenerator with mod 256 to generate unsigned char values imageBuffer[i] = (unsigned char)((int)randomGenerator->GetIntegerVariate((int)randomMax)) % 256; } else if (type.GetComponentType() == itk::IOComponentEnum::USHORT) { imageBuffer[i] = (unsigned short)((int)randomGenerator->GetIntegerVariate((int)randomMax)) % 65536; } else { MITK_ERROR << "Datatype not supported yet."; // TODO call different methods for other datatypes } } return output; } }; } // namespace mitk #endif /* ImageGenerator_H_HEADER_INCLUDED */ diff --git a/Modules/Core/include/mitkImagePixelWriteAccessor.h b/Modules/Core/include/mitkImagePixelWriteAccessor.h index 25b3b20943..a4dbea561b 100644 --- a/Modules/Core/include/mitkImagePixelWriteAccessor.h +++ b/Modules/Core/include/mitkImagePixelWriteAccessor.h @@ -1,138 +1,138 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKIMAGEPIXELWRITEACCESSOR_H #define MITKIMAGEPIXELWRITEACCESSOR_H #include "mitkImagePixelAccessor.h" #include "mitkImageWriteAccessor.h" namespace mitk { /** * @brief Gives locked and index-based write access for a particular image part. * The class provides several set- and get-methods, which allow an easy pixel access. * It needs to know about pixel type and dimension of its image at compile time. * @tparam TPixel defines the PixelType * @tparam VDimension defines the dimension for accessing data * @ingroup Data */ template class ImagePixelWriteAccessor : public ImagePixelAccessor { friend class Image; public: typedef ImagePixelAccessor ImagePixelAccessorType; typedef itk::SmartPointer ImagePointer; /** \brief Instantiates a mitk::ImageWriteAccessor (see its doxygen page for more details) * \param iP specifies the associated Image * \param iDI specifies the allocated image part * \param OptionFlags properties from mitk::ImageAccessorBase::Options can be chosen and assembled with bitwise * unification. * \throws mitk::Exception if the Constructor was created inappropriately * \throws mitk::MemoryIsLockedException if requested image area is exclusively locked and * mitk::ImageAccessorBase::ExceptionIfLocked is set in OptionFlags * * Includes a check if typeid of PixelType coincides with templated TPixel * and a check if VDimension equals to the Dimension of the Image. * * \note - * To avoid intermittent Update() calls to a predecessing filter pipeline, a call to Modifed() method after the + * To avoid intermittent Update() calls to a predecessing filter pipeline, a call to Modified() method after the * access is finished is left to the developer. */ ImagePixelWriteAccessor(ImagePointer iP, const ImageDataItem *iDI = nullptr, int OptionFlags = ImageAccessorBase::DefaultBehavior) : ImagePixelAccessor(iP.GetPointer(), iDI), m_WriteAccessor(iP, iDI, OptionFlags) { } /** \brief Gives full data access. */ virtual inline TPixel *GetData() const { return static_cast(m_WriteAccessor.m_AddressBegin); } /// Sets a pixel value at given index. void SetPixelByIndex(const itk::Index &idx, const TPixel &value) { unsigned int offset = ImagePixelAccessor::GetOffset(idx); *(((TPixel *)m_WriteAccessor.m_AddressBegin) + offset) = value; } /** Extends SetPixel by integrating index validation to prevent overflow. */ void SetPixelByIndexSafe(const itk::Index &idx, const TPixel &value) { unsigned int offset = ImagePixelAccessorType::GetOffset(idx); TPixel *targetAddress = ((TPixel *)m_WriteAccessor.m_AddressBegin) + offset; if (targetAddress >= m_WriteAccessor.m_AddressBegin && targetAddress < m_WriteAccessor.m_AddressEnd) { *targetAddress = value; } else { // printf("image dimensions = %d, %d, %d\n", imageDims[0], imageDims[1], imageDims[2]); // printf("m_AddressBegin: %p, m_AddressEnd: %p, offset: %u\n", m_WriteAccessor.m_AddressBegin, // m_WriteAccessor.m_AddressEnd, offset); mitkThrow() << "ImageAccessor Overflow: image access exceeds the requested image area at " << idx << "."; } } /** Returns a const reference to the pixel at given index. */ const TPixel &GetPixelByIndex(const itk::Index &idx) const { unsigned int offset = ImagePixelAccessorType::GetOffset(idx); return *(((TPixel *)m_WriteAccessor.m_AddressBegin) + offset); } /** Extends GetPixel by integrating index validation to prevent overflow. * \throws mitk::Exception in case of overflow */ const TPixel &GetPixelByIndexSafe(const itk::Index &idx) const { unsigned int offset = ImagePixelAccessorType::GetOffset(idx); TPixel *targetAddress = ((TPixel *)m_WriteAccessor.m_AddressBegin) + offset; if (!(targetAddress >= m_WriteAccessor.m_AddressBegin && targetAddress < m_WriteAccessor.m_AddressEnd)) { mitkThrow() << "ImageAccessor Overflow: image access exceeds the requested image area at " << idx << "."; } return *targetAddress; } /** Returns a const reference to the pixel at given world coordinate - works only with three-dimensional * ImageAccessor */ const TPixel &GetPixelByWorldCoordinates(mitk::Point3D position) { itk::Index<3> itkIndex; m_WriteAccessor.GetImage()->GetGeometry()->WorldToIndex(position, itkIndex); return GetPixelByIndex(itkIndex); } /** Returns a reference to the pixel at given world coordinate */ void SetPixelByWorldCoordinates(const mitk::Point3D &, const TPixel &value, unsigned int timestep = 0); ~ImagePixelWriteAccessor() override {} private: ImageWriteAccessor m_WriteAccessor; ImagePixelWriteAccessor &operator=(const ImagePixelWriteAccessor &); // Not implemented on purpose. ImagePixelWriteAccessor(const ImagePixelWriteAccessor &); }; } #endif // MITKIMAGEWRITEACCESSOR_H diff --git a/Modules/Core/include/mitkImageSource.h b/Modules/Core/include/mitkImageSource.h index 52461c8159..1d886ec7b8 100644 --- a/Modules/Core/include/mitkImageSource.h +++ b/Modules/Core/include/mitkImageSource.h @@ -1,251 +1,251 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef IMAGESOURCE_H_HEADER_INCLUDED_C1E7D6EC #define IMAGESOURCE_H_HEADER_INCLUDED_C1E7D6EC #include "mitkBaseDataSource.h" #include "mitkImage.h" #include namespace mitk { /** * @brief Superclass of all classes generating Images (instances of class * Image) as output. * * In itk and vtk the generated result of a ProcessObject is only guaranteed * to be up-to-date, when Update() of the ProcessObject or the generated * DataObject is called immediately before access of the data stored in the * DataObject. This is also true for subclasses of mitk::BaseProcess and thus * for mitk::ImageSource. But there are also three access methods provided * that guarantee an up-to-date result (by first calling Update and then * returning the result of GetOutput()): GetData(), GetPic() and * GetVtkImageData(). * @ingroup Process */ class MITKCORE_EXPORT ImageSource : public BaseDataSource { public: mitkClassMacro(ImageSource, BaseDataSource); /** @brief Method for creation through the object factory. */ itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** @brief Some convenient typedefs. */ typedef mitk::Image OutputImageType; typedef OutputImageType OutputType; typedef OutputImageType::Pointer OutputImagePointer; typedef SlicedData::RegionType OutputImageRegionType; /** * @brief Get the output data of this image source object. * * The output of this * function is not valid until an appropriate Update() method has * been called, either explicitly or implicitly. Both the filter * itself and the data object have Update() methods, and both * methods update the data. Here are three ways to use * GetOutput() and make sure the data is valid. In these * examples, \a image is a pointer to some Image object, and the * particular ProcessObjects involved are filters. The same * examples apply to non-image (e.g. Mesh) data as well. * * \code * anotherFilter->SetInput( someFilter->GetOutput() ); * anotherFilter->Update(); * \endcode * * In this situation, \a someFilter and \a anotherFilter are said * to constitute a \b pipeline. * * \code * image = someFilter->GetOutput(); * image->Update(); * \endcode * * \code * someFilter->Update(); * image = someFilter->GetOutput(); * \endcode * (In the above example, the two lines of code can be in * either order.) * * Note that Update() is not called automatically except within a * pipeline as in the first example. When \b streaming (using a * StreamingImageFilter) is activated, it may be more efficient to * use a pipeline than to call Update() once for each filter in * turn. * * For an image, the data generated is for the requested * Region, which can be set using ImageBase::SetRequestedRegion(). * By default, the largest possible region is requested. * * For Filters which have multiple outputs of different types, the * GetOutput() method assumes the output is of OutputImageType. For * the GetOutput(DataObjectPointerArraySizeType) method, a dynamic_cast is performed * incase the filter has outputs of different types or image * types. Derived classes should have named get methods for these * outputs. */ mitkBaseDataSourceGetOutputDeclarations /** @brief Make a DataObject of the correct type to used as the specified * output. * * Every ProcessObject subclass must be able to create a * DataObject that can be used as a specified output. This method * is automatically called when DataObject::DisconnectPipeline() is * called. DataObject::DisconnectPipeline, disconnects a data object * from being an output of its current source. When the data object * is disconnected, the ProcessObject needs to construct a replacement * output data object so that the ProcessObject is in a valid state. * So DataObject::DisconnectPipeline eventually calls * ProcessObject::MakeOutput. Note that MakeOutput always returns a * SmartPointer to a DataObject. If a subclass of ImageSource has * multiple outputs of different types, then that class must provide * an implementation of MakeOutput(). */ itk::DataObject::Pointer MakeOutput(DataObjectPointerArraySizeType idx) override; /** * This is a default implementation to make sure we have something. - * Once all the subclasses of ProcessObject provide an appopriate + * Once all the subclasses of ProcessObject provide an appropriate * MakeOutput(), then ProcessObject::MakeOutput() can be made pure * virtual. */ itk::DataObject::Pointer MakeOutput(const DataObjectIdentifierType &name) override; virtual vtkImageData *GetVtkImageData(); virtual const vtkImageData *GetVtkImageData() const; protected: ImageSource(); ~ImageSource() override {} /** @brief A version of GenerateData() specific for image processing * filters. * * This implementation will split the processing across * multiple threads. The buffer is allocated by this method. Then * the BeforeThreadedGenerateData() method is called (if * provided). Then, a series of threads are spawned each calling * ThreadedGenerateData(). After all the threads have completed * processing, the AfterThreadedGenerateData() method is called (if * provided). If an image processing filter cannot be threaded, the * filter should provide an implementation of GenerateData(). That * implementation is responsible for allocating the output buffer. * If a filter an be threaded, it should NOT provide a * GenerateData() method but should provide a ThreadedGenerateData() * instead. * * \sa ThreadedGenerateData() */ void GenerateData() override; /** @brief If an imaging filter can be implemented as a multithreaded * algorithm, the filter will provide an implementation of * ThreadedGenerateData(). * * This superclass will automatically split * the output image into a number of pieces, spawn multiple threads, * and call ThreadedGenerateData() in each thread. Prior to spawning * threads, the BeforeThreadedGenerateData() method is called. After * all the threads have completed, the AfterThreadedGenerateData() * method is called. If an image processing filter cannot support * threading, that filter should provide an implementation of the * GenerateData() method instead of providing an implementation of * ThreadedGenerateData(). If a filter provides a GenerateData() * method as its implementation, then the filter is responsible for * allocating the output data. If a filter provides a * ThreadedGenerateData() method as its implementation, then the * output memory will allocated automatically by this superclass. * The ThreadedGenerateData() method should only produce the output * specified by "outputThreadRegion" * parameter. ThreadedGenerateData() cannot write to any other * portion of the output image (as this is responsibility of a * different thread). * * \sa GenerateData(), SplitRequestedRegion() */ virtual void ThreadedGenerateData(const OutputImageRegionType &outputRegionForThread, itk::ThreadIdType threadId); /** @brief This method is intentionally left blank. * * ImageSource's need not * Initialize their containers. The Image::Allocate() method (called * from GenerateData()) will resize the container if more memory is * needed. Otherwise, the memory can be reused. */ void PrepareOutputs() override; /** @brief The GenerateData method normally allocates the buffers for all of the * outputs of a filter. * * Some filters may want to override this default * behavior. For example, a filter may have multiple outputs with * varying resolution. Or a filter may want to process data in place by * grafting its input to its output.*/ virtual void AllocateOutputs(); /** @brief If an imaging filter needs to perform processing after the buffer * has been allocated but before threads are spawned, the filter can * can provide an implementation for BeforeThreadedGenerateData(). * * The execution flow in the default GenerateData() method will be: * 1) Allocate the output buffer * 2) Call BeforeThreadedGenerateData() * 3) Spawn threads, calling ThreadedGenerateData() in each thread. * 4) Call AfterThreadedGenerateData() * Note that this flow of control is only available if a filter provides * a ThreadedGenerateData() method and NOT a GenerateData() method. */ virtual void BeforeThreadedGenerateData() {} /** @brief If an imaging filter needs to perform processing after all * processing threads have completed, the filter can can provide an * implementation for AfterThreadedGenerateData(). * * The execution * flow in the default GenerateData() method will be: * 1) Allocate the output buffer * 2) Call BeforeThreadedGenerateData() * 3) Spawn threads, calling ThreadedGenerateData() in each thread. * 4) Call AfterThreadedGenerateData() * Note that this flow of control is only available if a filter provides * a ThreadedGenerateData() method and NOT a GenerateData() method. */ virtual void AfterThreadedGenerateData() {} /** @brief Split the output's RequestedRegion into "num" pieces, returning * region "i" as "splitRegion". * * This method is called "num" times. The * regions must not overlap. The method returns the number of pieces that * the routine is capable of splitting the output RequestedRegion, * i.e. return value is less than or equal to "num". */ virtual unsigned int SplitRequestedRegion(unsigned int i, unsigned int num, OutputImageRegionType &splitRegion); /** @brief Static function used as a "callback" by the MultiThreader. * * The threading library will call this routine for each thread, which will delegate the * control to ThreadedGenerateData(). */ static itk::ITK_THREAD_RETURN_TYPE ThreaderCallback(void *arg); /** @brief Internal structure used for passing image data into the threading library */ struct ThreadStruct { Pointer Filter; }; private: ImageSource(const Self &); // purposely not implemented void operator=(const Self &); // purposely not implemented }; } // namespace mitk #endif /* IMAGESOURCE_H_HEADER_INCLUDED_C1E7D6EC */ diff --git a/Modules/Core/include/mitkImageStatisticsHolder.h b/Modules/Core/include/mitkImageStatisticsHolder.h index c6b2a5387d..e7c5e66b8d 100644 --- a/Modules/Core/include/mitkImageStatisticsHolder.h +++ b/Modules/Core/include/mitkImageStatisticsHolder.h @@ -1,176 +1,176 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKIMAGESTATISTICSHOLDER_H #define MITKIMAGESTATISTICSHOLDER_H #include "mitkImage.h" #include "mitkImageTimeSelector.h" #include #ifndef __itkHistogram_h #include #endif namespace mitk { /** - @brief Class holding the statistics informations about a single mitk::Image + @brief Class holding the statistics information about a single mitk::Image This computation was previously directly included in the definition and implementation of the mitk::Image class but for having a clear interface, all statistics computation is moved to the ImageStatisticsHolder class. Each mitk::Image holds a normal pointer to its StatisticsHolder object. To get access to the methods, use the GetStatistics() method in mitk::Image class. Minimum or maximum might by infinite values. 2nd minimum and maximum are guaranteed to be finite values. */ class MITKCORE_EXPORT ImageStatisticsHolder { public: /** Constructor */ ImageStatisticsHolder(mitk::Image *image); - /** Desctructor */ + /** Destructor */ virtual ~ImageStatisticsHolder(); typedef itk::Statistics::Histogram HistogramType; virtual const HistogramType *GetScalarHistogram(int t = 0, unsigned int = 0); //##Documentation //## \brief Get the minimum for scalar images. Recomputation performed only when necessary. virtual ScalarType GetScalarValueMin(int t = 0, unsigned int component = 0); //##Documentation //## \brief Get the maximum for scalar images. Recomputation performed only when necessary. virtual ScalarType GetScalarValueMax(int t = 0, unsigned int component = 0); //##Documentation //## \brief Get the second smallest value for scalar images. //## Recomputation performed only when necessary. //## \post The returned value is always a finite value. virtual ScalarType GetScalarValue2ndMin(int t = 0, unsigned int component = 0); //##Documentation //## \brief Get the smallest value for scalar images, but do not recompute it first virtual mitk::ScalarType GetScalarValueMinNoRecompute(unsigned int t = 0) const { if (t < m_ScalarMin.size()) return m_ScalarMin[t]; else return itk::NumericTraits::max(); } //##Documentation //## \brief Get the second smallest value for scalar images, but do not recompute it first //## \post The returned value is always a finite value. virtual mitk::ScalarType GetScalarValue2ndMinNoRecompute(unsigned int t = 0) const { if (t < m_Scalar2ndMin.size()) return m_Scalar2ndMin[t]; else return itk::NumericTraits::max(); } //##Documentation //## \brief Get the second largest value for scalar images //## \post The returned value is always a finite value. virtual ScalarType GetScalarValue2ndMax(int t = 0, unsigned int component = 0); //##Documentation //## \brief Get the largest value for scalar images, but do not recompute it first //## \post The returned value is always a finite value. virtual mitk::ScalarType GetScalarValueMaxNoRecompute(unsigned int t = 0) { if (t < m_ScalarMax.size()) return m_ScalarMax[t]; else return itk::NumericTraits::NonpositiveMin(); } //##Documentation //## \brief Get the second largest value for scalar images, but do not recompute it first virtual mitk::ScalarType GetScalarValue2ndMaxNoRecompute(unsigned int t = 0) { if (t < m_Scalar2ndMax.size()) return m_Scalar2ndMax[t]; else return itk::NumericTraits::NonpositiveMin(); } //##Documentation //## \brief Get the count of voxels with the smallest scalar value in the dataset mitk::ScalarType GetCountOfMinValuedVoxels(int t = 0, unsigned int component = 0); //##Documentation //## \brief Get the count of voxels with the largest scalar value in the dataset mitk::ScalarType GetCountOfMaxValuedVoxels(int t = 0, unsigned int component = 0); //##Documentation //## \brief Get the count of voxels with the largest scalar value in the dataset virtual unsigned int GetCountOfMaxValuedVoxelsNoRecompute(unsigned int t = 0) { if (t < m_CountOfMaxValuedVoxels.size()) return m_CountOfMaxValuedVoxels[t]; else return 0; } //##Documentation //## \brief Get the count of voxels with the smallest scalar value in the dataset virtual unsigned int GetCountOfMinValuedVoxelsNoRecompute(unsigned int t = 0) const { if (t < m_CountOfMinValuedVoxels.size()) return m_CountOfMinValuedVoxels[t]; else return 0; } bool IsValidTimeStep(int t) const; template friend void _ComputeExtremaInItkImage(const ItkImageType *itkImage, mitk::ImageStatisticsHolder *statisticsHolder, int t); template friend void _ComputeExtremaInItkVectorImage(const ItkImageType *itkImage, mitk::ImageStatisticsHolder *statisticsHolder, int t, unsigned int component); protected: virtual void ResetImageStatistics(); virtual void ComputeImageStatistics(int t = 0, unsigned int component = 0); virtual void Expand(unsigned int timeSteps); ImageTimeSelector::Pointer GetTimeSelector(); mitk::Image *m_Image; mutable itk::Object::Pointer m_HistogramGeneratorObject; mutable itk::Object::Pointer m_TimeSelectorForExtremaObject; mutable std::vector m_CountOfMinValuedVoxels; mutable std::vector m_CountOfMaxValuedVoxels; mutable std::vector m_ScalarMin; mutable std::vector m_ScalarMax; mutable std::vector m_Scalar2ndMin; mutable std::vector m_Scalar2ndMax; itk::TimeStamp m_LastRecomputeTimeStamp; }; } // end namespace #endif // MITKIMAGESTATISTICSHOLDER_H diff --git a/Modules/Core/include/mitkImageToImageFilter.h b/Modules/Core/include/mitkImageToImageFilter.h index 199d7c2bdf..a0dc60c25f 100644 --- a/Modules/Core/include/mitkImageToImageFilter.h +++ b/Modules/Core/include/mitkImageToImageFilter.h @@ -1,80 +1,80 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef IMAGETOIMAGEFILTER_H_HEADER_INCLUDED_C1E5E869 #define IMAGETOIMAGEFILTER_H_HEADER_INCLUDED_C1E5E869 #include "mitkImageSource.h" #include namespace mitk { //##Documentation //## @brief Superclass of all classes having one or more Images as input and //## generating Images as output //## @ingroup Process class MITKCORE_EXPORT ImageToImageFilter : public ImageSource { public: mitkClassMacro(ImageToImageFilter, ImageSource); /** Method for creation through the object factory. */ itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** Superclass typedefs. */ typedef Superclass::OutputImageRegionType OutputImageRegionType; /** Some convenient typedefs. */ typedef mitk::Image InputImageType; typedef InputImageType::Pointer InputImagePointer; typedef InputImageType::ConstPointer InputImageConstPointer; typedef SlicedData::RegionType InputImageRegionType; using itk::ProcessObject::SetInput; /** Set/Get the image input of this process object. */ virtual void SetInput(const InputImageType *image); virtual void SetInput(unsigned int, const InputImageType *image); InputImageType *GetInput(void); InputImageType *GetInput(unsigned int idx); const InputImageType *GetInput(void) const; const InputImageType *GetInput(unsigned int idx) const; protected: ImageToImageFilter(); ~ImageToImageFilter() override; void PrintSelf(std::ostream &os, itk::Indent indent) const override; /** What is the input requested region that is required to produce the * output requested region? The base assumption for image processing * filters is that the input requested region can be set to match the * output requested region. If a filter requires more input (for instance * a filter that uses neighborhoods needs more input than output to avoid * introducing artificial boundary conditions) or less input (for instance * a magnify filter) will have to override this method. In doing so, it * should call its superclass' implementation as its first step. Note that * this imaging filters operate differently than the classes to this - * point in the class hierachy. Up till now, the base assumption has been + * point in the class hierarchy. Up till now, the base assumption has been * that the largest possible region will be requested of the input. * * \sa ProcessObject::GenerateInputRequestedRegion(), * ImageSource::GenerateInputRequestedRegion() */ void GenerateInputRequestedRegion() override; private: void operator=(const Self &); // purposely not implemented }; } // namespace mitk #endif /* IMAGETOIMAGEFILTER_H_HEADER_INCLUDED_C1E5E869 */ diff --git a/Modules/Core/include/mitkImageToItk.txx b/Modules/Core/include/mitkImageToItk.txx index 29abe89a77..b765b5a2de 100644 --- a/Modules/Core/include/mitkImageToItk.txx +++ b/Modules/Core/include/mitkImageToItk.txx @@ -1,290 +1,290 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef IMAGETOITK_TXX_INCLUDED_C1C2FCD2 #define IMAGETOITK_TXX_INCLUDED_C1C2FCD2 #include "itkImportMitkImageContainer.h" #include "mitkBaseProcess.h" #include "mitkException.h" #include "mitkImageReadAccessor.h" #include "mitkImageToItk.h" #include "mitkImageWriteAccessor.h" #include template struct SetLengthHelper { SetLengthHelper(TImageType *in) { m_Image = in; } private: TImageType *m_Image; }; template struct SetLengthHelper> { typedef itk::Image TImageType; SetLengthHelper(TImageType *in) { m_Image = in; } void SetVectorLength(size_t) {} private: TImageType *m_Image; }; template struct SetLengthHelper> { typedef itk::VectorImage TImageType; SetLengthHelper(TImageType *in) { m_Image = in; } void SetVectorLength(size_t len) { m_Image->SetVectorLength(len); } private: TImageType *m_Image; }; template void mitk::ImageToItk::SetInput(mitk::Image *input) { this->SetInput(static_cast(input)); m_ConstInput = false; } template void mitk::ImageToItk::SetInput(const mitk::Image *input) { this->CheckInput(input); // Process object is not const-correct so the const_cast is required here itk::ProcessObject::PushFrontInput(input); m_ConstInput = true; } template mitk::Image *mitk::ImageToItk::GetInput(void) { if (this->GetNumberOfInputs() < 1) { return nullptr; } return static_cast(itk::ProcessObject::GetInput(0)); } template const mitk::Image *mitk::ImageToItk::GetInput() const { if (this->GetNumberOfInputs() < 1) { return nullptr; } return static_cast(itk::ProcessObject::GetInput(0)); } template void mitk::ImageToItk::GenerateData() { // Allocate output mitk::Image::Pointer input = this->GetInput(); typename Superclass::OutputImageType::Pointer output = this->GetOutput(); unsigned long noBytes = input->GetDimension(0); for (unsigned int i = 1; i < TOutputImage::GetImageDimension(); ++i) { noBytes = noBytes * input->GetDimension(i); } const mitk::PixelType pixelType = input->GetPixelType(); if (pixelType.GetPixelType() == itk::IOPixelEnum::VECTOR) { noBytes *= pixelType.GetNumberOfComponents(); SetLengthHelper helper(output.GetPointer()); helper.SetVectorLength(pixelType.GetNumberOfComponents()); } std::unique_ptr imageAccess; if (m_ConstInput) { imageAccess.reset(new mitk::ImageReadAccessor(input, nullptr, m_Options)); } else { imageAccess.reset(new mitk::ImageWriteAccessor(input, nullptr, m_Options)); } // hier wird momentan wohl nur der erste Channel verwendet??!! if (imageAccess->GetData() == nullptr) { itkWarningMacro(<< "no image data to import in ITK image"); RegionType bufferedRegion; output->SetBufferedRegion(bufferedRegion); return; } if (m_CopyMemFlag) { itkDebugMacro("copyMem ..."); output->Allocate(); memcpy(output->GetBufferPointer(), imageAccess->GetData(), sizeof(InternalPixelType) * noBytes); } else { itkDebugMacro("do not copyMem ..."); typedef itk::ImportMitkImageContainer ImportContainerType; typename ImportContainerType::Pointer import; import = ImportContainerType::New(); import->Initialize(); itkDebugMacro(<< "size of container = " << import->Size()); // import->SetImageDataItem(m_ImageDataItem); import->SetImageAccessor(imageAccess.release(), sizeof(InternalPixelType) * noBytes); output->SetPixelContainer(import); itkDebugMacro(<< "size of container = " << import->Size()); } } template void mitk::ImageToItk::UpdateOutputInformation() { mitk::Image::Pointer input = this->GetInput(); if (input.IsNotNull() && (input->GetSource().IsNotNull()) && input->GetSource()->Updating()) { typename Superclass::OutputImageType::Pointer output = this->GetOutput(); unsigned long t1 = input->GetUpdateMTime() + 1; if (t1 > this->m_OutputInformationMTime.GetMTime()) { output->SetPipelineMTime(t1); this->GenerateOutputInformation(); this->m_OutputInformationMTime.Modified(); } return; } Superclass::UpdateOutputInformation(); } template void mitk::ImageToItk::GenerateOutputInformation() { mitk::Image::ConstPointer input = this->GetInput(); typename Superclass::OutputImageType::Pointer output = this->GetOutput(); // allocate size, origin, spacing, direction in types of output image SizeType size; const unsigned int itkDimMin3 = (TOutputImage::ImageDimension > 3 ? TOutputImage::ImageDimension : 3); const unsigned int itkDimMax3 = (TOutputImage::ImageDimension < 3 ? TOutputImage::ImageDimension : 3); typename Superclass::OutputImageType::PointType::ValueType origin[itkDimMin3]; typename Superclass::OutputImageType::SpacingType::ComponentType spacing[itkDimMin3]; typename Superclass::OutputImageType::DirectionType direction; // copy as much information as possible into size and spacing unsigned int i; for (i = 0; i < itkDimMax3; ++i) { size[i] = input->GetDimension(i); spacing[i] = input->GetGeometry()->GetSpacing()[i]; } for (; i < TOutputImage::ImageDimension; ++i) { origin[i] = 0.0; size[i] = input->GetDimension(i); spacing[i] = 1.0; } // build region from size IndexType start; start.Fill(0); RegionType region; region.SetIndex(start); region.SetSize(size); // copy as much information as possible into origin const mitk::Point3D &mitkorigin = input->GetGeometry()->GetOrigin(); itk2vtk(mitkorigin, origin); // copy as much information as possible into direction direction.SetIdentity(); unsigned int j; const AffineTransform3D::MatrixType &matrix = input->GetGeometry()->GetIndexToWorldTransform()->GetMatrix(); /// \warning 2D MITK images could have a 3D rotation, since they have a 3x3 geometry matrix. /// If it is only a rotation around the axial plane normal, it can be express with a 2x2 matrix. /// In this case, the ITK image conservs this information and is identical to the MITK image! /// If the MITK image contains any other rotation, the ITK image will have no rotation at all. /// Spacing is of course conserved in both cases. - // the following loop devides by spacing now to normalize columns. + // the following loop divides by spacing now to normalize columns. // counterpart of InitializeByItk in mitkImage.h line 372 of revision 15092. // Check if information is lost if (TOutputImage::ImageDimension <= 2) { if ((TOutputImage::ImageDimension == 2) && ((matrix[0][2] != 0) || (matrix[1][2] != 0) || (matrix[2][0] != 0) || (matrix[2][1] != 0) || ((matrix[2][2] != 1) && (matrix[2][2] != -1)))) { // The 2D MITK image contains 3D rotation information. // This cannot be expressed in a 2D ITK image, so the ITK image will have no rotation } else { // The 2D MITK image can be converted to an 2D ITK image without information loss! for (i = 0; i < itkDimMax3; ++i) for (j = 0; j < itkDimMax3; ++j) direction[i][j] = matrix[i][j] / spacing[j]; } } else { // Normal 3D image. Conversion possible without problem! for (i = 0; i < itkDimMax3; ++i) for (j = 0; j < itkDimMax3; ++j) direction[i][j] = matrix[i][j] / spacing[j]; } // set information into output image output->SetRegions(region); output->SetOrigin(origin); output->SetSpacing(spacing); output->SetDirection(direction); } template void mitk::ImageToItk::CheckInput(const mitk::Image *input) const { if (input == nullptr) { itkExceptionMacro(<< "image is null"); } if (input->GetDimension() != TOutputImage::GetImageDimension()) { itkExceptionMacro(<< "image has dimension " << input->GetDimension() << " instead of " << TOutputImage::GetImageDimension()); } if (!(input->GetPixelType() == mitk::MakePixelType(input->GetPixelType().GetNumberOfComponents()))) { itkExceptionMacro(<< "image has wrong pixel type "); } } template void mitk::ImageToItk::PrintSelf(std::ostream &os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); } #endif // IMAGETOITK_TXX_INCLUDED_C1C2FCD2 diff --git a/Modules/Core/include/mitkImageToSurfaceFilter.h b/Modules/Core/include/mitkImageToSurfaceFilter.h index 01c0d93c22..937c76a07b 100644 --- a/Modules/Core/include/mitkImageToSurfaceFilter.h +++ b/Modules/Core/include/mitkImageToSurfaceFilter.h @@ -1,247 +1,247 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITKIMAGETOSURFACEFILTER_h__ #define _MITKIMAGETOSURFACEFILTER_h__ #include "MitkCoreExports.h" #include #include #include #include #include #include #include #include namespace mitk { /** * @brief Converts pixel data to surface data by using a threshold * The mitkImageToSurfaceFilter is used to create a new surface out of an mitk image. The filter * uses a threshold to define the surface. It is based on the vtkMarchingCube algorithm. By default * a vtkPolyData surface based on an input threshold for the input image will be created. Optional * it is possible to reduce the number of triangles/polygones [SetDecimate(mitk::ImageToSurfaceFilter::DecimatePro) and * SetTargetReduction (float _arg)] * or smooth the surface-data [SetSmooth(true), SetSmoothIteration(int smoothIteration) and SetSmoothRelaxation(float * smoothRelaxation)]. * * The resulting vtk-surface has the same size as the input image. The surface * can be generally smoothed by vtkDecimatePro reduce complexity of triangles * and vtkSmoothPolyDataFilter to relax the mesh. Both are enabled by default * and connected in the common way of pipelining in ITK. It's also possible * to create time sliced surfaces. * * @ingroup ImageFilters * @ingroup Process */ class MITKCORE_EXPORT ImageToSurfaceFilter : public SurfaceSource { public: /* * To decide whether a reduction of polygons in the created surface shall be * done or not by using the vtkDecimatePro Filter. Till vtk 4.x an vtkDecimateFilter existed, - * but was patented. So since vtk 5.x it was replaced by the (worser?) vtkDecimateProFilter + * but was patented. So since vtk 5.x it was replaced by the (much worse?) vtkDecimateProFilter * Maybe another Filter will come soon. */ enum DecimationType { NoDecimation, DecimatePro, QuadricDecimation }; mitkClassMacro(ImageToSurfaceFilter, SurfaceSource); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * For each image time slice a surface will be created. This method is * called by Update(). */ void GenerateData() override; /** * Initializes the output information ( i.e. the geometry information ) of * the output of the filter */ void GenerateOutputInformation() override; /** - * Returns a const reference to the input image (e.g. the original input image that ist used to create the surface) + * Returns a const reference to the input image (e.g. the original input image that is used to create the surface) */ const mitk::Image *GetInput(void); /** * Set the source image to create a surface for this filter class. As input every mitk * 3D or 3D+t image can be used. */ using itk::ProcessObject::SetInput; virtual void SetInput(const mitk::Image *image); /** * Set the number of iterations that is used to smooth the surface. Used is the vtkSmoothPolydataFilter that uses * the * laplacian filter. The higher the number of iterations that stronger the smooth-result * - * @param smoothIteration As smoothIteration default in that case 50 was choosen. The VTK documentation recommends + * @param smoothIteration As smoothIteration default in that case 50 was chosen. The VTK documentation recommends * small relaxation factors and large numbers of iterations. */ void SetSmoothIteration(int smoothIteration); /** * Set number of relaxation. Specify the relaxation factor for Laplacian * smoothing. The VTK documentation recommends small relaxation factors * and large numbers of iterations. * - * @param smoothRelaxation As smoothRelaxation default in that case 0.1 was choosen. The VTK documentation + * @param smoothRelaxation As smoothRelaxation default in that case 0.1 was chosen. The VTK documentation * recommends * small relaxation factors and large numbers of iterations. */ void SetSmoothRelaxation(float smoothRelaxation); /** * Threshold that is used to create the surface. All pixel in the input image that are higher than that * value will be considered in the surface. The threshold referees to * vtkMarchingCube. Default value is 1. See also SetThreshold (ScalarType _arg) */ itkSetMacro(Threshold, ScalarType); /** * Get Threshold from vtkMarchingCube. Threshold can be manipulated by * inherited classes. */ itkGetConstMacro(Threshold, ScalarType); /** * Enables vtkSmoothPolyDataFilter. With Laplacian smoothing this filter * will relax the surface. You can control the Filter by manipulating the * number of iterations and the relaxing factor. * */ itkSetMacro(Smooth, bool); /* * Enable/Disable surface smoothing. */ itkBooleanMacro(Smooth); /* * Returns if surface smoothing is enabled */ itkGetConstMacro(Smooth, bool); /** * Get the state of decimation mode to reduce triangle in the - * surface represantation. Modes can only be NoDecimation or DecimatePro + * surface representation. Modes can only be NoDecimation or DecimatePro * (till vtk 4.x also Decimate) * */ itkGetConstMacro(Decimate, DecimationType); /** * Enable the decimation filter to reduce the number of triangles in the * mesh and produce a good approximation to the original image. The filter * has support for vtk-5 and earlier versions. More detailed information * check the vtkDecimatePro and vtkDecimate. * */ itkSetMacro(Decimate, DecimationType); /** * Set desired TargetReduction of triangles in the range from 0.0 to 1.0. * The destroyed triangles are in relation with the size of data. For example 0.9 * will reduce the data set to 10%. */ itkSetMacro(TargetReduction, float); /** * Returns the reduction factor for the VtkDecimatePro Decimation Filter as a float value */ itkGetConstMacro(TargetReduction, float); /** * Transforms a point by a 4x4 matrix */ template inline void mitkVtkLinearTransformPoint(T1 matrix[4][4], T2 in[3], T3 out[3]) { T3 x = matrix[0][0] * in[0] + matrix[0][1] * in[1] + matrix[0][2] * in[2] + matrix[0][3]; T3 y = matrix[1][0] * in[0] + matrix[1][1] * in[1] + matrix[1][2] * in[2] + matrix[1][3]; T3 z = matrix[2][0] * in[0] + matrix[2][1] * in[1] + matrix[2][2] * in[2] + matrix[2][3]; out[0] = x; out[1] = y; out[2] = z; } protected: ImageToSurfaceFilter(); /** * Destructor * */ ~ImageToSurfaceFilter() override; /** * With the given threshold vtkMarchingCube creates the surface. By default nothing a * vtkPolyData surface based on a threshold of the input image will be created. Optional * it is possible to reduce the number of triangles/polygones [SetDecimate(mitk::ImageToSurfaceFilter::DecimatePro) * and * SetTargetReduction (float _arg)] * or smooth the data [SetSmooth(true), SetSmoothIteration(int smoothIteration) and SetSmoothRelaxation(float * smoothRelaxation)]. * * @param time selected slice or "0" for single * @param *vtkimage input image * @param *surface output * @param threshold can be different from SetThreshold() */ void CreateSurface(int time, vtkImageData *vtkimage, mitk::Surface *surface, const ScalarType threshold); /** * Flag whether the created surface shall be smoothed or not (default is "false"). SetSmooth (bool _arg) * */ bool m_Smooth; /** * Decimation mode, default mode is "NoDecimation". See also SetDecimate (DecimationType _arg) * */ DecimationType m_Decimate; /** * Threshold that is used to create the surface. All pixel in the input image that are higher than that * value will be considered in the surface. Default value is 1. See also SetThreshold (ScalarType _arg) * */ ScalarType m_Threshold; /** * The Reduction factor of the Decimation Filter for the created surface. See also SetTargetReduction (float _arg) * */ float m_TargetReduction; /** * The Iteration value for the Smooth Filter of the created surface. See also SetSmoothIteration (int * smoothIteration) * */ int m_SmoothIteration; /** * The Relaxation value for the Smooth Filter of the created surface. See also SetSmoothRelaxation (float * smoothRelaxation) * */ float m_SmoothRelaxation; }; } // namespace mitk #endif //_MITKIMAGETOSURFACEFILTER_h__ diff --git a/Modules/Core/include/mitkImageVtkMapper2D.h b/Modules/Core/include/mitkImageVtkMapper2D.h index 52d3efc792..d1ee542a8f 100644 --- a/Modules/Core/include/mitkImageVtkMapper2D.h +++ b/Modules/Core/include/mitkImageVtkMapper2D.h @@ -1,321 +1,321 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKIMAGEVTKMAPPER2D_H_HEADER_INCLUDED_C10E906E #define MITKIMAGEVTKMAPPER2D_H_HEADER_INCLUDED_C10E906E // MITK #include // MITK Rendering #include "mitkBaseRenderer.h" #include "mitkExtractSliceFilter.h" #include "mitkVtkMapper.h" // VTK #include #include class vtkActor; class vtkPolyDataMapper; class vtkPlaneSource; class vtkImageData; class vtkLookupTable; class vtkImageExtractComponents; class vtkImageReslice; class vtkImageChangeInformation; class vtkPoints; class vtkMitkThickSlicesFilter; class vtkPolyData; class vtkMitkApplyLevelWindowToRGBFilter; class vtkMitkLevelWindowFilter; namespace mitk { /** \brief Mapper to resample and display 2D slices of a 3D image. * * The following image gives a brief overview of the mapping and the involved parts. * * \image html imageVtkMapper2Darchitecture.png * * First, the image is resliced by means of vtkImageReslice. The volume image * serves as input to the mapper in addition to spatial placement of the slice and a few other * properties such as thick slices. This code was already present in the old version * (mitkImageMapperGL2D). * * Next, the obtained slice (m_ReslicedImage) is put into a vtkMitkLevelWindowFilter * and the scalar levelwindow, opacity levelwindow and optional clipping to * local image bounds are applied * * Next, the output of the vtkMitkLevelWindowFilter is used to create a texture * (m_Texture) and a plane onto which the texture is rendered (m_Plane). For * mapping purposes, a vtkPolyDataMapper (m_Mapper) is utilized. Orthographic * projection is applied to create the effect of a 2D image. The mapper and the * texture are assigned to the actor (m_Actor) which is passed to the VTK rendering * pipeline via the method GetVtkProp(). * * In order to transform the textured plane to the correct position in space, the * same transformation as used for reslicing is applied to both the camera and the * vtkActor. All important steps are explained in more detail below. The resulting * 2D image (by reslicing the underlying 3D input image appropriately) can either * be directly rendered in a 2D view or just be calculated to be used later by another * rendering entity, e.g. in texture mapping in a 3D view. * * Properties that can be set for images and influence the imageMapper2D are: * * - \b "opacity": (FloatProperty) Opacity of the image * - \b "color": (ColorProperty) Color of the image * - \b "LookupTable": (mitkLookupTableProperty) If this property is set, * the default lookuptable will be ignored and the "LookupTable" value * will be used instead. * - \b "Image Rendering.Mode": This property decides which mode is used to render images. (E.g. if a lookup table or a transferfunction is applied). Detailed documentation about the modes can be found here: \link mitk::RenderingModeProperty \endlink * - \b "Image Rendering.Transfer Function": (mitkTransferFunctionProperty) If this * property is set, a color transferfunction will be used to color the image. * - \b "binary": (BoolProperty) is the image a binary image or not * - \b "outline binary": (BoolProperty) show outline of the image or not * - \b "texture interpolation": (BoolProperty) texture interpolation of the image * - \b "reslice interpolation": (VtkResliceInterpolationProperty) reslice interpolation of the image * - \b "in plane resample extent by geometry": (BoolProperty) Do it or not * - \b "bounding box": (BoolProperty) Is the Bounding Box of the image shown or not * - \b "layer": (IntProperty) Layer of the image * - \b "volume annotation color": (ColorProperty) color of the volume annotation, TODO has to be reimplemented * - \b "volume annotation unit": (StringProperty) annotation unit as string (does not implicit convert the unit!) unit is ml or cm3, TODO has to be reimplemented * The default properties are: * - \b "opacity", mitk::FloatProperty::New(0.3f), renderer, overwrite ) * - \b "color", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ) * - \b "binary", mitk::BoolProperty::New( true ), renderer, overwrite ) * - \b "outline binary", mitk::BoolProperty::New( false ), renderer, overwrite ) * - \b "texture interpolation", mitk::BoolProperty::New( false ) ) * - \b "reslice interpolation", mitk::VtkResliceInterpolationProperty::New() ) * - \b "in plane resample extent by geometry", mitk::BoolProperty::New( false ) ) * - \b "bounding box", mitk::BoolProperty::New( false ) ) * - \b "layer", mitk::IntProperty::New(10), renderer, overwrite) * - \b "Image Rendering.Transfer Function": Default color transfer function for CTs * - \b "LookupTable": Rainbow color. * If the modality-property is set for an image, the mapper uses modality-specific default properties, * e.g. color maps, if they are defined. * \ingroup Mapper */ class MITKCORE_EXPORT ImageVtkMapper2D : public VtkMapper { public: /** Standard class typedefs. */ mitkClassMacro(ImageVtkMapper2D, VtkMapper); /** Method for creation through the object factory. */ itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** \brief Get the Image to map */ const mitk::Image *GetInput(void); /** \brief Checks whether this mapper needs to update itself and generate * data. */ void Update(mitk::BaseRenderer *renderer) override; //### methods of MITK-VTK rendering pipeline vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) override; //### end of methods of MITK-VTK rendering pipeline /** \brief Internal class holding the mapper, actor, etc. for each of the 3 2D render windows */ /** * To render axial, coronal, and sagittal, the mapper is called three times. * For performance reasons, the corresponding data for each view is saved in the * internal helper class LocalStorage. This allows rendering n views with just * 1 mitkMapper using n vtkMapper. * */ class MITKCORE_EXPORT LocalStorage : public mitk::Mapper::BaseLocalStorage { public: /** \brief Actor of the image in a 2D render window. */ vtkSmartPointer m_ImageActor; /** \brief Actor of the shadowimage in a 2D render window. */ vtkSmartPointer m_ShadowOutlineActor; - /** Prop assembly containting everything for a regular display of the image.*/ + /** Prop assembly containing everything for a regular display of the image.*/ vtkSmartPointer m_Actors; /** Prop assembly used if workspace is in an invalid state (e.g. invalid time point or * invalid world coordinate position is selected) and mapper has to "early out" * in Update() or GenerateDataForRenderer()*/ vtkSmartPointer m_EmptyActors; /** Prop assembly exposed publicly via ImagVtkMapper2D::GetVTKProp()*/ vtkProp* m_PublicActors = nullptr; /** \brief Mapper of a 2D render window. */ vtkSmartPointer m_Mapper; vtkSmartPointer m_VectorComponentExtractor; /** \brief Current slice of a 2D render window.*/ vtkSmartPointer m_ReslicedImage; /** \brief Empty vtkPolyData that is set when rendering geometry does not * intersect the image geometry. * \warning This member variable is set to nullptr, * if no image geometry is inside the plane geometry * of the respective render window. Any user of this * slice has to check whether it is set to nullptr! */ vtkSmartPointer m_EmptyPolyData; /** \brief Plane on which the slice is rendered as texture. */ vtkSmartPointer m_Plane; /** \brief The texture which is used to render the current slice. */ vtkSmartPointer m_Texture; /** \brief The lookuptables for colors and level window */ vtkSmartPointer m_DefaultLookupTable; vtkSmartPointer m_BinaryLookupTable; vtkSmartPointer m_ColorLookupTable; /** \brief The actual reslicer (one per renderer) */ mitk::ExtractSliceFilter::Pointer m_Reslicer; /** \brief Filter for thick slices */ vtkSmartPointer m_TSFilter; - /** \brief PolyData object containg all lines/points needed for outlining the contour. + /** \brief PolyData object containing all lines/points needed for outlining the contour. This container is used to save a computed contour for the next rendering execution. For instance, if you zoom or pann, there is no need to recompute the contour. */ vtkSmartPointer m_OutlinePolyData; /** \brief Timestamp of last update of stored data. */ itk::TimeStamp m_LastUpdateTime; /** \brief mmPerPixel relation between pixel and mm. (World spacing).*/ mitk::ScalarType *m_mmPerPixel; /** \brief This filter is used to apply the level window to Grayvalue and RBG(A) images. */ vtkSmartPointer m_LevelWindowFilter; /** \brief Default constructor of the local storage. */ LocalStorage(); /** \brief Default deconstructor of the local storage. */ ~LocalStorage() override; }; /** \brief Get the LocalStorage corresponding to the current renderer. */ const LocalStorage *GetConstLocalStorage(mitk::BaseRenderer *renderer); /** \brief Set the default properties for general image rendering. */ static void SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); /** \brief This method switches between different rendering modes (e.g. use a lookup table or a transfer function). * Detailed documentation about the modes can be found here: \link mitk::RenderingModeProperty \endlink */ void ApplyRenderingMode(mitk::BaseRenderer *renderer); protected: /** \brief The LocalStorageHandler holds all (three) LocalStorages for the three 2D render windows. */ mitk::LocalStorageHandler m_LSH; /** \brief Get the LocalStorage corresponding to the current renderer. */ LocalStorage* GetLocalStorage(mitk::BaseRenderer* renderer); /** \brief Transforms the actor to the actual position in 3D. * \param renderer The current renderer corresponding to the render window. */ void TransformActor(mitk::BaseRenderer *renderer); - /** \brief Generates a plane according to the size of the resliced image in milimeters. + /** \brief Generates a plane according to the size of the resliced image in millimeters. * * In VTK a vtkPlaneSource is defined through three points. The origin and two * points defining the axes of the plane (see VTK documentation). The origin is * set to (xMin; yMin; Z), where xMin and yMin are the minimal bounds of the * resliced image in space. Z is relevant for blending and the layer property. * The center of the plane (C) is also the center of the view plane (cf. the image above). * * \note For the standard MITK view with three 2D render windows showing three * different slices, three such planes are generated. All these planes are generated * in the XY-plane (even if they depict a YZ-slice of the volume). * */ void GeneratePlane(mitk::BaseRenderer *renderer, double planeBounds[6]); /** \brief Generates a vtkPolyData object containing the outline of a given binary slice. \param renderer: Pointer to the renderer containing the needed information \note This code is based on code from the iil library. */ template vtkSmartPointer CreateOutlinePolyData(mitk::BaseRenderer *renderer); /** Default constructor */ ImageVtkMapper2D(); /** Default deconstructor */ ~ImageVtkMapper2D() override; /** \brief Does the actual resampling, without rendering the image yet. * All the data is generated inside this method. The vtkProp (or Actor) * is filled with content (i.e. the resliced image). * * After generation, a 4x4 transformation matrix(t) of the current slice is obtained * from the vtkResliceImage object via GetReslicesAxis(). This matrix is * applied to each textured plane (actor->SetUserTransform(t)) to transform everything * to the actual 3D position (cf. the following image). * * \image html cameraPositioning3D.png * */ void GenerateDataForRenderer(mitk::BaseRenderer *renderer) override; /** \brief This method uses the vtkCamera clipping range and the layer property - * to calcualte the depth of the object (e.g. image or contour). The depth is used + * to calculate the depth of the object (e.g. image or contour). The depth is used * to keep the correct order for the final VTK rendering.*/ float CalculateLayerDepth(mitk::BaseRenderer *renderer); /** \brief This method applies (or modifies) the lookuptable for all types of images. * \warning To use the lookup table, the property 'Lookup Table' must be set and a 'Image Rendering.Mode' * which uses the lookup table must be set. */ void ApplyLookuptable(mitk::BaseRenderer *renderer); /** \brief This method applies a color transfer function. - * Internally, a vtkColorTransferFunction is used. This is usefull for coloring continous + * Internally, a vtkColorTransferFunction is used. This is useful for coloring continuous * images (e.g. float) * \warning To use the color transfer function, the property 'Image Rendering.Transfer Function' must be set and a * 'Image Rendering.Mode' which uses the color transfer function must be set. */ void ApplyColorTransferFunction(mitk::BaseRenderer *renderer); /** * @brief ApplyLevelWindow Apply the level window for the given renderer. * \warning To use the level window, the property 'LevelWindow' must be set and a 'Image Rendering.Mode' which uses * the level window must be set. * @param renderer Level window for which renderer? */ void ApplyLevelWindow(mitk::BaseRenderer *renderer); /** \brief Set the color of the image/polydata */ void ApplyColor(mitk::BaseRenderer *renderer); /** \brief Set the opacity of the actor. */ void ApplyOpacity(mitk::BaseRenderer *renderer); /** * \brief Calculates whether the given rendering geometry intersects the * given SlicedGeometry3D. * * This method checks if the given PlaneGeometry intersects the given * SlicedGeometry3D. It calculates the distance of the PlaneGeometry to all * 8 cornerpoints of the SlicedGeometry3D. If all distances have the same * sign (all positive or all negative) there is no intersection. * If the distances have different sign, there is an intersection. **/ bool RenderingGeometryIntersectsImage(const PlaneGeometry *renderingGeometry, SlicedGeometry3D *imageGeometry); /** Helper function to reset the local storage in order to indicate an invalid state.*/ void SetToInvalidState(mitk::ImageVtkMapper2D::LocalStorage* localStorage); }; } // namespace mitk #endif /* MITKIMAGEVTKMAPPER2D_H_HEADER_INCLUDED_C10E906E */ diff --git a/Modules/Core/include/mitkInteractionConst.h b/Modules/Core/include/mitkInteractionConst.h index c74f992edc..def5e21ed5 100644 --- a/Modules/Core/include/mitkInteractionConst.h +++ b/Modules/Core/include/mitkInteractionConst.h @@ -1,776 +1,776 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKINTERACTCONST_H #define MITKINTERACTCONST_H //##Documentation //## @file mitkInteractionConst.h //## @brief Constants for most interaction classes, due to the generic StateMachines. //## //## Changes in Type, ButtonState or Key has to be don in mitkEventMapper.cpp, too. //## @ingroup Interaction /*Prefixes for Constants: E = Enumeration EID = EventId's Op = Operations Ac = Action Type_ = Type of Event BS_ = ButtonStates and Buttons Key_ = Keys like in QT */ namespace mitk { // Constants for EventIds; use the according constant to through an event in the code enum EEventIds { EIDNULLEVENT = 0, EIDLEFTMOUSEBTN = 1, EIDRIGHTMOUSEBTN = 2, EIDLEFTMOUSEBTNANDSHIFT = 3, EIDMIDDLEMOUSEBTN = 4, EIDLEFTMOUSEBTNANDCTRL = 5, EIDMIDDLEMOUSEBTNANDCTRL = 6, EIDRIGHTMOUSEBTNANDCTRL = 7, EIDLEFTMOUSEBTNDOUBLECLICK = 8, EIDMOUSEWHEEL = 9, EIDLEFTMOUSERELEASE = 505, EIDMIDDLEMOUSERELEASE = 506, EIDRIGHTMOUSERELEASE = 507, EIDLEFTMOUSERELEASEANDSHIFT = 508, EIDMOUSEMOVE = 520, EIDLEFTMOUSEBTNANDMOUSEWHEEL = 521, EIDRIGHTMOUSEBTNANDMOUSEWHEEL = 522, EIDMIDDLEMOUSEBTNANDMOUSEWHEEL = 523, EIDLEFTMOUSEBTNANDMOUSEMOVE = 530, EIDRIGHTMOUSEBTNANDMOUSEMOVE = 531, EIDMIDDLEMOUSEBTNANDMOUSEMOVE = 533, EIDCTRLANDLEFTMOUSEBTNANDMOUSEMOVE = 534, EIDCTRLANDRIGHTMOUSEBTNANDMOUSEMOVE = 535, EIDCTRLANDMIDDLEMOUSEBTNANDMOUSEMOVE = 536, EIDCTRLANDLEFTMOUSEBTNRELEASE = 537, EIDCTRLANDRIGHTMOUSEBTNRELEASE = 538, EIDCTRLANDMIDDLEMOUSEBTNRELEASE = 539, EIDSHIFTANDCTRLANDMIDDLEMOUSEBTN = 540, EIDSHIFTANDLEFTMOUSEBTNANDMOUSEMOVE = 541, EIDSHIFTANDCTRLANDMOUSEMOVE = 542, EIDSHIFTANDCTRLANDMOUSERELEASE = 543, EIDALTANDLEFTMOUSEBTN = 600, EIDALTANDLEFTMOUSEBTNANDMOUSEMOVE = 610, EIDALTANDLEFTMOUSERELEASE = 620, EIDCTRLANDLEFTMOUSEWHEEL = 630, EIDALTANDMOUSEWHEEL = 640, EIDALTANDMIDDLEMOUSEBTN = 641, EIDALTANDMIDDLEMOUSEBTNANDMOVE = 642, EIDALTANDMIDDLEMOUSEBTNRELEASE = 643, EIDALTANDSHIFTANDRIGHTMOUSEBTN = 644, EIDALTANDSHIFTANDRIGHTMOUSEBTNANDMOUSEMOVE = 645, EIDALTANDSHIFTANDRIGHTMOUSEBTNRELEASE = 646, EIDSHIFTANDRIGHTMOUSEPRESS = 2000, EIDSHIFTANDRIGHTMOUSEMOVE = 2001, EIDSHIFTANDRIGHTMOUSERELEASE = 2002, EIDSHIFTANDMIDDLEMOUSEPRESS = 2003, EIDSHIFTANDMIDDLEMOUSEMOVE = 2004, EIDSHIFTANDMIDDLEMOUSERELEASE = 2005, EIDSPACENAVIGATORINPUT = 4001, // 3d Mouse, SpaceNavigator input EIDSPACENAVIGATORKEYDOWN = 4002, // 3d Mouse, KeyDown EIDWIIMOTEINPUT = 4003, // WiiMote input EIDWIIMOTEBUTTON = 4004, // WiiMote home button EIDWIIMOTEBUTTONB = 4005, // WiiMote b button EIDSTRGANDN = 10, EIDSTRGANDE = 11, EIDDELETE = 12, EIDN = 13, EIDESCAPE = 14, EIDP = 15, EIDR = 16, EIDT = 17, EIDS = 18, EIDE = 19, EIDSTRGANDALTANDA = 20, EIDSTRGANDALTANDB = 21, EIDH = 22, EIDRETURN = 23, EIDENTER = 24, EIDSPACE = 25, EIDPLUS = 26, EIDMINUS = 27, EIDSTRGANDALTANDH = 30, EIDSTRGANDALTANDI = 31, EIDSTRGANDALTANDS = 40, EIDALT = 90, EIDSTRGANDB = 91, EIDNEW = 1000, EIDOLD = 1001, EIDFINISHED = 1002, EIDNO = 1003, EIDYES = 1004, EIDSAME = 1005, EIDNOANDLASTOBJECT = 1006, EIDNOANDNOTLASTOBJECT = 1007, EIDLAST = 1008, EIDNOTLAST = 1009, EIDSTSMALERNMINUS1 = 1010, EIDSTLARGERNMINUS1 = 1011, EIDPOSITIONEVENT = 1012, EIDEDIT = 1013, EIDSMALLERN = 1014, EIDEQUALSN = 1015, EIDLARGERN = 1016, EIDEMPTY = 1017, EIDSUBDESELECT = 1020, EIDSMTOSELECTED = 1030, EIDSMTODESELECTED = 1031, EIDTIP = 1050, EIDHEAD = 1051, EIDBODY = 1052, EIDCLEAR = 1100, EIDACTIVATETOOL = 1300, EIDPRINT = 3001, EV_INIT = 5551001, EV_PREVIOUS = 5551002, EV_PATH_COLLECTION_SELECTED = 5551003, EV_NAVIGATION_SELECTED = 5551004, EV_LESS_THEN_MIN_COUNT = 5551005, EV_READY = 5551006, EV_NEXT = 5551007, EV_DONE = 5551008, EV_NEW_LANDMARK = 5551009, EV_REMOVE_LANDMARK = 5551010, EIDINSIDE = 2500, EIDA = 4001, EIDB = 4002, EIDC = 4003, EIDD = 4004, EIDF = 4005, EIDG = 4006, EIDI = 4007, EIDJ = 4008, EIDK = 4009, EIDL = 4010, EIDM = 4011, EIDO = 4012, EIDQ = 4013, EIDU = 4014, EIDV = 4015, EIDW = 4016, EIDX = 4017, EIDY = 4018, EIDZ = 4019, EID1 = 4020, EID2 = 4021, EID3 = 4022, EID4 = 4023, EID5 = 4024, EID6 = 4025, EID7 = 4026, EID8 = 4027, EID9 = 4028, EID0 = 4029, EIDFIGUREHOVER = 12340, EIDNOFIGUREHOVER = 12341 }; //##Constants for Operations //## xomments are always examples of the usage enum EOperations { OpNOTHING = 0, OpTEST = 1, OpNEWCELL = 10, // add a new cell OpADD = 100, // add a point or a vessel OpUNDOADD = 101, OpADDLINE = 1001, // add a line OpINSERT = 200, // insert a point at position OpINSERTLINE = 201, // insert a line at position OpINSERTPOINT = 202, OpCLOSECELL = 250, // close a cell (to a polygon) OpOPENCELL = 251, // close a cell (to a polygon) OpMOVE = 300, // move a point OpMOVELINE = 301, // move a line OpMOVECELL = 302, // move a line OpUNDOMOVE = 303, OpMOVEPOINTUP = 304, OpMOVEPOINTDOWN = 305, OpREMOVE = 400, // remove a point at position OpREMOVELINE = 401, // remove a line at position OpREMOVECELL = 402, // remove a cell OpREMOVEPOINT = 403, OpDELETE = 500, // delete OpDELETELINE = 501, // delete the last line in a cell OpUNDELETE = 502, OpDELETECELL = 505, OpSTATECHANGE = 600, // change a state OpTIMECHANGE = 601, // change a state OpTERMINATE = 666, // change a state OpSELECTPOINT = 700, OpSELECTLINE = 701, OpSELECTCELL = 702, OpSELECTSUBOBJECT = 703, // for VesselGraphInteractor // OpSELECTNEWSUBOBJECT = 704, //for VesselGraphInteractor OpSELECT = 705, OpDESELECTPOINT = 800, OpDESELECTLINE = 801, OpDESELECTCELL = 802, OpDESELECTSUBOBJECT = 803, // for VesselGraphInteractor OpDESELECTALL = 804, // for VesselGraphInteractor OpDESELECT = 805, OpNAVIGATE = 900, OpZOOM = 1000, OpSCALE = 1100, OpROTATE = 1200, OpORIENT = 1201, OpRESTOREPLANEPOSITION = 1202, OpAPPLYTRANSFORMMATRIX = 1203, OpSETPOINTTYPE = 1210, OpMODECHANGE = 1500, OpSENDCOORDINATES = 1600, OpPERIPHERYSEARCH = 2000, // used in VesselGraphInteractor OpROOTSEARCH = 2001, // used in VesselGraphInteractor OpTHICKSTVESSELSEARCH = 2002, // used in VesselGraphInteractor OpSHORTESTPATHSEARCH = 2003, // used in VesselGraphInteractor OpATTRIBUTATION = 2004, // used in VesselGraphInteractor OpDEFAULT = 2006, // used in VesselGraphInteractor OpSURFACECHANGED = 3000, // used for changing polydata in surfaces }; //##Constants for EventMapping... //##connects the statemachine.xml-File with the implemented conditions. //##within one statemachine the choice of the actionconstants is freely //## //## ActionId enum EActions { AcDONOTHING = 0, AcINITNEWOBJECT = 5, AcINITEDITOBJECT = 6, AcINITEDITGROUP = 7, AcINITMOVEMENT = 8, AcINITMOVE = 9, AcINITFOREGROUND = 45, // used in SeedsInteractor for setting the foreground seeds AcINITBACKGROUND = 46, // used in SeedsInteractor for setting the background seeds AcINITNEUTRAL = 47, // used in SeedsInteractor for setting the neutral seeds (rubber) AcINITUPDATE = 1235, // For shape model deformation AcADDPOINT = 10, AcADDPOINTRMB = 6000, // in mitralPointSetInteractor used to set a different type of point AcADD = 11, AcADDLINE = 12, AcADDANDFINISH = 13, AcADDSELECTEDTOGROUP = 64, AcCHECKPOINT = 21, AcCHECKLINE = 22, AcCHECKCELL = 23, AcCHECKELEMENT = 30, // check if there is a element close enough (picking) AcCHECKOBJECT = 31, // check if an object is hit AcCHECKNMINUS1 = 32, // check if the number of elements is equal to N-1 AcCHECKEQUALS1 = 33, // check if the number of elements in the data is equal to 1 AcCHECKNUMBEROFPOINTS = 330, // check the number of elements in the data AcCHECKSELECTED = 34, // check if the given element is selected or not AcCHECKONESELECTED = 340, // check if there is an element that is selected AcCHECKHOVERING = 341, // check if there is an element that is selected AcCHECKGREATERZERO = 35, // check if the current number of elements is greater than 0 AcCHECKGREATERTWO = 36, // check if the current number of elements is greater than two AcCHECKOPERATION = 37, // check if the operation is of one spectial type AcCHECKONESUBINTERACTOR = 38, AcCHECKSUBINTERACTORS = 39, AcFINISHOBJECT = 40, AcFINISHGROUP = 41, AcFINISHMOVEMENT = 42, AcFINISHMOVE = 43, AcFINISH = 44, AcSEARCHOBJECT = 50, AcSEARCHGROUP = 51, AcSEARCHANOTHEROBJECT = 52, // one object is selected and another object is to be added to selection AcSELECTPICKEDOBJECT = 60, // select the picked object and deselect others AcSELECTANOTHEROBJECT = 61, AcSELECTGROUP = 62, AcSELECTALL = 63, AcSELECT = 65, AcSELECTPOINT = 66, AcSELECTLINE = 68, AcSELECTCELL = 67, AcSELECTSUBOBJECT = 69, // used in VesselGraphInteractor AcDESELECTOBJECT = 70, // deselect picked from group AcDESELECTALL = 72, AcDESELECT = 75, AcDESELECTPOINT = 76, AcDESELECTLINE = 78, AcDESELECTCELL = 77, AcNEWPOINT = 80, AcNEWSUBOBJECT = 81, AcMOVEPOINT = 90, AcMOVESELECTED = 91, AcMOVE = 92, AcMOVEPOINTUP = 93, AcMOVEPOINTDOWN = 94, AcREMOVEPOINT = 100, AcREMOVE = 101, AcREMOVELINE = 102, AcREMOVEALL = 103, AcREMOVESELECTEDSUBOBJECT = 104, // used in VesselGraphInteractor AcWHEEL = 105, AcPLUS = 106, AcMINUS = 107, AcDELETEPOINT = 120, AcCLEAR = 130, // clear all elements from a list AcINSERTPOINT = 110, AcINSERTLINE = 111, AC_SET_NEXT_BUTTON_VISIBLE = 5550001, AC_SET_NEXT_BUTTON_INVISIBLE = 5550002, AC_SET_PREVIOUS_BUTTON_VISIBLE = 5550003, AC_SET_PREVIOUS_BUTTON_INVISIBLE = 5550004, AC_SET_ASSISTAND_WIDGET_STECK = 5550005, AC_SETMAX_COUNT_REF_POINTS = 5550006, AC_SET_NEXT_BUTTON_TEXT = 5550007, AC_CHECK_LANDMARK_COUNT = 5550008, AC_SET_DONE_FALSE = 5550009, AC_INIT = 55500010, AC_SET_APPLICATION_SELECTED_FALSE = 55500011, AC_SENSOR_ATTACHED = 55500012, AC_CLOSE_ASSISTENT = 55500013, AC_START_APPLICATION_TEXT = 55500014, AC_START_NAVIGATION = 55500015, AC_START_PATHCOLLECTION = 55500016, AC_LOAD_LANDMARKS = 55500017, AC_CALCULATE_LANDMARK_TRANSFORM = 55500018, AcTERMINATE_INTERACTION = 666, AcTRANSLATESTART = 1000, AcTRANSLATE = 1001, AcSCALESTART = 1002, AcSCALE = 1003, AcROTATESTART = 1004, AcROTATE = 1005, AcINITAFFINEINTERACTIONS = 1006, AcFINISHAFFINEINTERACTIONS = 1007, AcTRANSLATEEND = 1008, AcSCALEEND = 1009, AcROTATEEND = 1010, AcINITZOOM = 1011, AcZOOM = 1012, AcSCROLL = 1013, AcLEVELWINDOW = 1014, AcSCROLLMOUSEWHEEL = 1015, AcSETSTARTPOINT = 1050, AcMODEDESELECT = 1100, // set interactor in not selected mode AcMODESELECT = 1101, // set interactor in selected mode AcMODESUBSELECT = 1102, // set interacor in sub selected mode AcINFORMLISTENERS = 1200, AcASKINTERACTORS = 1201, AcCHECKGREATERONE = 1500, AcCHECKBOUNDINGBOX = 1510, AcFORCESUBINTERACTORS = 1550, AcSENDCOORDINATES = 1600, AcTRANSMITEVENT = 2000, // to transmit an event to a lower Interactor/Statemachine AcPERIPHERYSEARCH = 3000, // used in VesselGraphInteractor AcROOTSEARCH = 3001, // used in VesselGraphInteractor AcTHICKSTVESSELSEARCH = 3002, // used in VesselGraphInteractor AcSHORTESTPATHSEARCH = 3003, // used in VesselGraphInteractor AcSINGLE = 3004, // used in VesselGraphInteractor AcATTRIBUTATION = 3005, // used in VesselGraphInteractor AcDEFAULT = 3007, // used in VesselGraphInteractor AcSETVESSELELEMENT = 3008, // used in VesselGraphInteractor AcCHECKBARRIERSTATUS = 3010, // used in VesselGraphInteractor AcUPDATEMESH = 1234, // For Shape Model Interaction AcINCREASE = 49012, AcDECREASE = 49013, AcMODIFY = 49014, AcUNDOUPDATE = 1236, // For restoring a mesh after an update AcENTEROBJECT = 48000, AcLEAVEOBJECT = 48001, AcSWITCHOBJECT = 48002, AcUPDATELINE = 48003, AcINITLINE = 48004, AcTERMINATELINE = 48005, AcCREATEBOX = 48006, AcCREATEOBJECTFROMLINE = 48007, AcCANCEL = 48008, AcACTIVATETOOL = 48009, AcROTATEAROUNDPOINT1 = 49002, AcROTATEAROUNDPOINT2 = 49003, AcMOVEPOINT1 = 49004, AcMOVEPOINT2 = 49005, AcUPDATEPOINT = 49006, AcUPDATERADIUSMOUSEWHEEL = 49007, AcDISPLAYOPTIONS = 49009, AcCYCLE = 49010, AcACCEPT = 49011, AcONSPACENAVIGATORMOUSEINPUT = 4001, // On input of 3D Mouse AcONPACENAVIGATORKEYDOWN = 4002, // On input of 3D Mouse AcONWIIMOTEINPUT = 4003, // used for wiimote to signal IR input AcRESETVIEW = 4004, // used for wiimote to reset view AcONWIIMOTEBUTTONRELEASED = 4005, // stops the surface interaction AcCHECKPOSITION = 5000, AcINITIALIZECONTOUR = 5001, AcCALCULATENEWSEGMENTATION_SP = 5002, AcINTERACTOR = 5003, AcCALCULATENEWSEGMENTATION_BB = 5004 }; /* //!!!!!!!!!!!!!!!!!!!!!!!! //!!!!!!!!!!!!!!!!!!!!!!!! //EventMechanism: //If you change anything from here on, then change in mitkEventMapper.cpp (Array of constants) as well. //!!!!!!!!!!!!!!!!!!!!!!!! //!!!!!!!!!!!!!!!!!!!!!!!! */ // Type of an Event; enum EEventType { Type_None = 0, // invalid event Type_Timer = 1, // timer event Type_MouseButtonPress = 2, // mouse button pressed Type_MouseButtonRelease = 3, // mouse button released Type_MouseButtonDblClick = 4, // mouse button double click Type_MouseMove = 5, // mouse move Type_KeyPress = 6, // key pressed Type_KeyRelease = 7, // key released Type_FocusIn = 8, // keyboard focus received Type_FocusOut = 9, // keyboard focus lost Type_Enter = 10, // mouse enters widget Type_Leave = 11, // mouse leaves widget Type_Paint = 12, // paint widget Type_Move = 13, // move widget Type_Resize = 14, // resize widget Type_Create = 15, // after object creation Type_Destroy = 16, // during object destruction Type_Show = 17, // widget is shown Type_Hide = 18, // widget is hidden Type_Close = 19, // request to close widget Type_Quit = 20, // request to quit application Type_Reparent = 21, // widget has been reparented Type_ShowMinimized = 22, // widget is shown minimized Type_ShowNormal = 23, // widget is shown normal Type_WindowActivate = 24, // window was activated Type_WindowDeactivate = 25, // window was deactivated Type_ShowToParent = 26, // widget is shown to parent Type_HideToParent = 27, // widget is hidden to parent Type_ShowMaximized = 28, // widget is shown maximized Type_ShowFullScreen = 29, // widget is shown full-screen Type_Accel = 30, // accelerator event Type_Wheel = 31, // wheel event Type_AccelAvailable = 32, // accelerator available event Type_CaptionChange = 33, // caption changed Type_IconChange = 34, // icon changed Type_ParentFontChange = 35, // parent font changed Type_ApplicationFontChange = 36, // application font changed Type_ParentPaletteChange = 37, // parent palette changed Type_ApplicationPaletteChange = 38, // application palette changed Type_PaletteChange = 39, // widget palette changed Type_Clipboard = 40, // internal clipboard event Type_Speech = 42, // reserved for speech input Type_SockAct = 50, // socket activation Type_AccelOverride = 51, // accelerator override event Type_DeferredDelete = 52, // deferred delete event Type_DragEnter = 60, // drag moves into widget Type_DragMove = 61, // drag moves in widget Type_DragLeave = 62, // drag leaves or is cancelled Type_Drop = 63, // actual drop Type_DragResponse = 64, // drag accepted/rejected Type_ChildInserted = 70, // new child widget Type_ChildRemoved = 71, // deleted child widget Type_LayoutHint = 72, // child min/max size changed Type_ShowWindowRequest = 73, // widget's window should be mapped Type_ActivateControl = 80, // ActiveX activation Type_DeactivateControl = 81, // ActiveX deactivation Type_ContextMenu = 82, // context popup menu Type_IMStart = 83, // input method composition start Type_IMCompose = 84, // input method composition Type_IMEnd = 85, // input method composition end Type_Accessibility = 86, // accessibility information is requested Type_TabletMove = 87, // Wacom tablet event Type_LocaleChange = 88, // the system locale changed Type_LanguageChange = 89, // the application language changed Type_LayoutDirectionChange = 90, // the layout direction changed Type_Style = 91, // internal style event Type_TabletPress = 92, // tablet press Type_TabletRelease = 93, // tablet release Type_User = 1000, // first user event id - Type_SpaceNavigatorInput = 1094, // 3D mouse input occured - Type_SpaceNavigatorKeyDown = 1095, // 3D mouse input occured - Type_WiiMoteInput = 1096, // WiiMote input occured + Type_SpaceNavigatorInput = 1094, // 3D mouse input occurred + Type_SpaceNavigatorKeyDown = 1095, // 3D mouse input occurred + Type_WiiMoteInput = 1096, // WiiMote input occurred Type_WiiMoteButton = 1097, // WiiMote button pressed Type_MaxUser = 65535 }; //##ButtonState // mouse/keyboard state values // QT combinations if MOUSEBUTTONRelease: left MouseButton + ControlButton: 0x201 enum EButtonStates { BS_NoButton = 0x0000, BS_LeftButton = 0x0001, BS_RightButton = 0x0002, BS_MidButton = 0x0004, BS_MouseButtonMask = 0x0007, BS_ShiftButton = 0x0100, BS_ControlButton = 0x0200, BS_AltButton = 0x0400, BS_MetaButton = 0x0800, BS_KeyButtonMask = 0x0f00, BS_Keypad = 0x4000 }; //##Key enum EKeys { Key_Escape = 0x1000, // misc keys Key_Tab = 0x1001, Key_Backtab = 0x1002, Key_BackTab = 0x1002, //= Key_Backtab Key_Backspace = 0x1003, Key_BackSpace = 0x1003, //= Key_Backspace Key_Return = 0x1004, Key_Enter = 0x1005, Key_Insert = 0x1006, Key_Delete = 0x1007, Key_Pause = 0x1008, Key_Print = 0x1009, Key_SysReq = 0x100a, Key_Home = 0x1010, // cursor movement Key_End = 0x1011, Key_Left = 0x1012, Key_Up = 0x1013, Key_Right = 0x1014, Key_Down = 0x1015, Key_Prior = 0x1016, Key_PageUp = 0x1016, //=Key_Prior Key_Next = 0x1017, Key_PageDown = 0x1017, //=Key_Next Key_Shift = 0x1020, // modifiers Key_Control = 0x1021, Key_Meta = 0x1022, Key_Alt = 0x1023, Key_CapsLock = 0x1024, Key_NumLock = 0x1025, Key_ScrollLock = 0x1026, Key_F1 = 0x1030, // function keys Key_F2 = 0x1031, Key_F3 = 0x1032, Key_F4 = 0x1033, Key_F5 = 0x1034, Key_F6 = 0x1035, Key_F7 = 0x1036, Key_F8 = 0x1037, Key_F9 = 0x1038, Key_F10 = 0x1039, Key_F11 = 0x103a, Key_F12 = 0x103b, Key_F13 = 0x103c, Key_F14 = 0x103d, Key_F15 = 0x103e, Key_F16 = 0x103f, Key_F17 = 0x1040, Key_F18 = 0x1041, Key_F19 = 0x1042, Key_F20 = 0x1043, Key_F21 = 0x1044, Key_F22 = 0x1045, Key_F23 = 0x1046, Key_F24 = 0x1047, Key_F25 = 0x1048, // F25 .. F35 only on X11 Key_F26 = 0x1049, Key_F27 = 0x104a, Key_F28 = 0x104b, Key_F29 = 0x104c, Key_F30 = 0x104d, Key_F31 = 0x104e, Key_F32 = 0x104f, Key_F33 = 0x1050, Key_F34 = 0x1051, Key_F35 = 0x1052, Key_Super_L = 0x1053, // extra keys Key_Super_R = 0x1054, Key_Menu = 0x1055, Key_Hyper_L = 0x1056, Key_Hyper_R = 0x1057, Key_Help = 0x1058, // International input method support (X keycode - = 0xEE00) // Only interesting if you are writing your own input method Key_Muhenkan = 0x1122, // Cancel Conversion Key_Henkan = 0x1123, // Start/Stop Conversion Key_Hiragana_Katakana = 0x1127, // Hiragana/Katakana toggle Key_Zenkaku_Hankaku = 0x112A, // Zenkaku/Hankaku toggle Key_Space = 0x20, // 7 bit printable ASCII Key_Any = 0x20, //= Key_Space Key_Exclam = 0x21, Key_QuoteDbl = 0x22, Key_NumberSign = 0x23, Key_Dollar = 0x24, Key_Percent = 0x25, Key_Ampersand = 0x26, Key_Apostrophe = 0x27, Key_ParenLeft = 0x28, Key_ParenRight = 0x29, Key_Asterisk = 0x2a, Key_Plus = 0x2b, Key_Comma = 0x2c, Key_Minus = 0x2d, Key_Period = 0x2e, Key_Slash = 0x2f, Key_0 = 0x30, Key_1 = 0x31, Key_2 = 0x32, Key_3 = 0x33, Key_4 = 0x34, Key_5 = 0x35, Key_6 = 0x36, Key_7 = 0x37, Key_8 = 0x38, Key_9 = 0x39, Key_Colon = 0x3a, Key_Semicolon = 0x3b, Key_Less = 0x3c, Key_Equal = 0x3d, Key_Greater = 0x3e, Key_Question = 0x3f, Key_At = 0x40, Key_A = 0x41, Key_B = 0x42, Key_C = 0x43, Key_D = 0x44, Key_E = 0x45, Key_F = 0x46, Key_G = 0x47, Key_H = 0x48, Key_I = 0x49, Key_J = 0x4a, Key_K = 0x4b, Key_L = 0x4c, Key_M = 0x4d, Key_N = 0x4e, Key_O = 0x4f, Key_P = 0x50, Key_Q = 0x51, Key_R = 0x52, Key_S = 0x53, Key_T = 0x54, Key_U = 0x55, Key_V = 0x56, Key_W = 0x57, Key_X = 0x58, Key_Y = 0x59, Key_Z = 0x5a, Key_BracketLeft = 0x5b, Key_Backslash = 0x5c, Key_BracketRight = 0x5d, Key_AsciiCircum = 0x5e, Key_Underscore = 0x5f, Key_QuoteLeft = 0x60, Key_BraceLeft = 0x7b, Key_Bar = 0x7c, Key_BraceRight = 0x7d, Key_AsciiTilde = 0x7e, Key_nobreakspace = 0x0a0, Key_exclamdown = 0x0a1, Key_cent = 0x0a2, Key_sterling = 0x0a3, Key_currency = 0x0a4, Key_yen = 0x0a5, Key_brokenbar = 0x0a6, Key_section = 0x0a7, Key_diaeresis = 0x0a8, Key_copyright = 0x0a9, Key_ordfeminine = 0x0aa, Key_guillemotleft = 0x0ab, // left angle quotation mark Key_notsign = 0x0ac, Key_hyphen = 0x0ad, Key_registered = 0x0ae, Key_macron = 0x0af, Key_degree = 0x0b0, Key_plusminus = 0x0b1, Key_twosuperior = 0x0b2, Key_threesuperior = 0x0b3, Key_acute = 0x0b4, Key_mu = 0x0b5, Key_paragraph = 0x0b6, Key_periodcentered = 0x0b7, Key_cedilla = 0x0b8, Key_onesuperior = 0x0b9, Key_masculine = 0x0ba, Key_guillemotright = 0x0bb, // right angle quotation mark Key_onequarter = 0x0bc, Key_onehalf = 0x0bd, Key_threequarters = 0x0be, Key_questiondown = 0x0bf, Key_Agrave = 0x0c0, Key_Aacute = 0x0c1, Key_Acircumflex = 0x0c2, Key_Atilde = 0x0c3, Key_Adiaeresis = 0x0c4, Key_Aring = 0x0c5, Key_AE = 0x0c6, Key_Ccedilla = 0x0c7, Key_Egrave = 0x0c8, Key_Eacute = 0x0c9, Key_Ecircumflex = 0x0ca, Key_Ediaeresis = 0x0cb, Key_Igrave = 0x0cc, Key_Iacute = 0x0cd, Key_Icircumflex = 0x0ce, Key_Idiaeresis = 0x0cf, Key_ETH = 0x0d0, Key_Ntilde = 0x0d1, Key_Ograve = 0x0d2, Key_Oacute = 0x0d3, Key_Ocircumflex = 0x0d4, Key_Otilde = 0x0d5, Key_Odiaeresis = 0x0d6, Key_multiply = 0x0d7, Key_Ooblique = 0x0d8, Key_Ugrave = 0x0d9, Key_Uacute = 0x0da, Key_Ucircumflex = 0x0db, Key_Udiaeresis = 0x0dc, Key_Yacute = 0x0dd, Key_THORN = 0x0de, Key_ssharp = 0x0df, Key_agrave = 0x0e0, Key_aacute = 0x0e1, Key_acircumflex = 0x0e2, Key_atilde = 0x0e3, Key_adiaeresis = 0x0e4, Key_aring = 0x0e5, Key_ae = 0x0e6, Key_ccedilla = 0x0e7, Key_egrave = 0x0e8, Key_eacute = 0x0e9, Key_ecircumflex = 0x0ea, Key_ediaeresis = 0x0eb, Key_igrave = 0x0ec, Key_iacute = 0x0ed, Key_icircumflex = 0x0ee, Key_idiaeresis = 0x0ef, Key_eth = 0x0f0, Key_ntilde = 0x0f1, Key_ograve = 0x0f2, Key_oacute = 0x0f3, Key_ocircumflex = 0x0f4, Key_otilde = 0x0f5, Key_odiaeresis = 0x0f6, Key_division = 0x0f7, Key_oslash = 0x0f8, Key_ugrave = 0x0f9, Key_uacute = 0x0fa, Key_ucircumflex = 0x0fb, Key_udiaeresis = 0x0fc, Key_yacute = 0x0fd, Key_thorn = 0x0fe, Key_ydiaeresis = 0x0ff, Key_unknown = 0xffff, Key_none = 0xffff //= Key_unknown }; } // namespace mitk #endif // ifndef MITKINTERACTCONST_H diff --git a/Modules/Core/include/mitkInteractionEventHandler.h b/Modules/Core/include/mitkInteractionEventHandler.h index 53fb42c44c..7d95e471a9 100644 --- a/Modules/Core/include/mitkInteractionEventHandler.h +++ b/Modules/Core/include/mitkInteractionEventHandler.h @@ -1,129 +1,129 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKEVENTHANDLER_H_ #define MITKEVENTHANDLER_H_ #include "itkLightObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include "mitkEventConfig.h" #include "mitkPropertyList.h" #include #include namespace us { class Module; } namespace mitk { /** * \class EventHandler * Serves as a base class for all objects and classes that handle mitk::InteractionEvents. * * It provides an interface to load configuration objects map of events to variant names. */ class InteractionEvent; class MITKCORE_EXPORT InteractionEventHandler : public itk::Object { public: mitkClassMacroItkParent(InteractionEventHandler, itk::Object); /** * @brief Loads a configuration from an XML resource. * * Loads an event configuration from an XML resource file contained in the given module. * Default is the Mitk module (core). * The files have to be placed in the Resources/Interactions folder of their respective module. * This method will remove all existing configuration and replaces it with the new one. * * @see SetEventConfig(const EventConfig&) * * @param filename The resource name relative to the Interactions resource folder. * @param module The module containing the resource. Defaults to the Mitk module. * @return \c true if the resource was successfully loaded, \c false otherwise. */ bool SetEventConfig(const std::string &filename, const us::Module *module = nullptr); /** * @brief Loads a configuration from an EventConfig object. * * Loads an event configuration from the given EventConfig object. This method will remove * all existing configuration and replaces it with the new one. * * @see SetEventConfig(const std::string&, const Module*) * * @param config The EventConfig object containing the new configuration. * @return \c true if the configuration was successfully loaded, \c false otherwise. */ bool SetEventConfig(const EventConfig &config); /** * @brief Returns the current configuration. * @return A EventConfig object representing the current event configuration. */ EventConfig GetEventConfig() const; /** * @brief This method \e extends the configuration. * * The configuration from the resource provided is loaded and only the ones conflicting are replaced by the new one. * This way several configuration files can be combined. * * @see AddEventConfig(const EventConfig&) * * @param filename The resource name relative to the Interactions resource folder. * @param module The module containing the resource. Defaults to the Mitk module. * @return \c true if the configuration was successfully added, \c false otherwise. */ bool AddEventConfig(const std::string &filename, const us::Module *module = nullptr); /** * @brief This method \e extends the configuration. * The configuration from the EventConfig object is loaded and only the ones conflicting are replaced by the new * one. * This way several configurations can be combined. * * @see AddEventConfig(const std::string&, const Module*) * * @param config The EventConfig object whose configuration should be added. * @return \c true if the configuration was successfully added, \c false otherwise. */ bool AddEventConfig(const EventConfig &config); protected: InteractionEventHandler(); ~InteractionEventHandler() override; /** * Returns a PropertyList in which the parameters defined in the config file are listed. */ PropertyList::Pointer GetAttributes() const; std::string MapToEventVariant(InteractionEvent *interactionEvent); /** - * Is called whenever a new config object ist set. + * Is called whenever a new config object is set. * Overwrite this method e.g. to initialize EventHandler with parameters in configuration file. */ virtual void ConfigurationChanged(); private: EventConfig m_EventConfig; }; } /* namespace mitk */ #endif /* MITKEVENTHANDLER_H_ */ diff --git a/Modules/Core/include/mitkLevelWindow.h b/Modules/Core/include/mitkLevelWindow.h index 538fe6e56c..6855dc4ce4 100644 --- a/Modules/Core/include/mitkLevelWindow.h +++ b/Modules/Core/include/mitkLevelWindow.h @@ -1,263 +1,263 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C #define LEVELWINDOW_H_HEADER_INCLUDED_C1F4F02C #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. * 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. * * The finite maximum and minimum of valid value range is stored in m_RangeMin and m_RangeMax. * If deduced from an image by default the minimum or maximum of it statistics is used. If one * of these values are infinite the 2nd extrimum (which is guaranteed to be finite), will be used. * * 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 MITKCORE_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 + * set the default Boundaries */ void SetDefaultBoundaries(ScalarType low, ScalarType up); /**! * \brief sets level/window to optimize the contrast of the given Image */ void SetAuto(const Image *image, bool tryPicTags = true, bool guessByCentralSlice = true, unsigned selectedComponent = 0); /**! * \brief sets level/window to the min/max greyvalues of the given Image */ void SetToImageRange(const Image *image); /** * 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); /*! * \brief Shows if floating values are accepted */ bool IsFloatingValues() const; /*! * \brief Sets the floating image value */ void SetFloatingValues(bool value); 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; /*! * Image with floating values */ bool m_IsFloatingImage; /*! * 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/Modules/Core/include/mitkLimitedLinearUndo.h b/Modules/Core/include/mitkLimitedLinearUndo.h index 3d724b1db7..01a20f8a53 100644 --- a/Modules/Core/include/mitkLimitedLinearUndo.h +++ b/Modules/Core/include/mitkLimitedLinearUndo.h @@ -1,159 +1,159 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef LIMITEDLINEARUNDO_H_HEADER_INCLUDED_C16E9C96 #define LIMITEDLINEARUNDO_H_HEADER_INCLUDED_C16E9C96 // MITK header #include "mitkOperationEvent.h" #include "mitkUndoModel.h" #include // STL header #include // ITK header #pragma GCC visibility push(default) #include #pragma GCC visibility pop #include namespace mitk { //##Documentation //## @brief A linear undo model with one undo and one redo stack. //## //## Derived from UndoModel AND itk::Object. Invokes ITK-events to signal listening //## GUI elements, whether each of the stacks is empty or not (to enable/disable button, ...) class MITKCORE_EXPORT LimitedLinearUndo : public UndoModel { public: typedef std::deque UndoContainer; typedef std::deque::reverse_iterator UndoContainerRevIter; mitkClassMacro(LimitedLinearUndo, UndoModel); itkFactorylessNewMacro(Self); itkCloneMacro(Self); bool SetOperationEvent(UndoStackItem *stackItem) override; //##Documentation //## @brief Undoes the last changes //## //## Reads the top element of the Undo-Stack, //## executes the operation, //## swaps the OperationEvent-Undo with the Operation //## and sets it to Redo-Stack bool Undo() override; bool Undo(bool) override; //##Documentation //## @brief Undoes all changes until ObjectEventID oeid virtual bool Undo(int oeid); //##Documentation //## @brief Undoes the last changes //## //## Reads the top element of the Redo-Stack, //## executes the operation, //## swaps the OperationEvent-Operation with the Undo-Operation //## and sets it to Undo-Stack bool Redo() override; bool Redo(bool) override; //##Documentation //## @brief Redoes all changes until ObjectEventID oeid virtual bool Redo(int oeid); //##Documentation //## @brief Clears UndoList and RedoList void Clear() override; //##Documentation //## @brief Clears the RedoList void ClearRedoList() override; //##Documentation //## @brief True, if RedoList is empty bool RedoListEmpty() override; //##Documentation //## @brief Gets the limit on the size of the undo history. //## The undo limit determines how many items can be stored //## in the undo stack. If the value is 0 that means that //## there is no limit. std::size_t GetUndoLimit() const override; //##Documentation //## @brief Sets a limit on the size of the undo history. //## If the limit is reached, the oldest undo items will //## be dropped from the bottom of the undo stack. //## The 0 value means that there is no limit. //## @param limit the maximum number of items on the stack void SetUndoLimit(std::size_t limit) override; //##Documentation //## @brief Returns the ObjectEventId of the //## top element in the OperationHistory int GetLastObjectEventIdInList() override; //##Documentation //## @brief Returns the GroupEventId of the //## top element in the OperationHistory int GetLastGroupEventIdInList() override; //##Documentation //## @brief Returns the last specified OperationEvent in Undo-list //## corresponding to the given values; if nothing found, then returns nullptr OperationEvent *GetLastOfType(OperationActor *destination, OperationType opType) override; protected: //##Documentation //## Constructor LimitedLinearUndo(); //##Documentation //## Destructor ~LimitedLinearUndo() override; //## @brief Convenience method to free the memory of //## elements in the list and to clear the list void ClearList(UndoContainer *list); UndoContainer m_UndoList; UndoContainer m_RedoList; private: int FirstObjectEventIdOfCurrentGroup(UndoContainer &stack); std::size_t m_UndoLimit; }; #pragma GCC visibility push(default) - /// Some itk events to notify listening GUI elements, when the undo or redo stack is empty (diable undo button) + /// Some itk events to notify listening GUI elements, when the undo or redo stack is empty (disable undo button) /// or when there are items in the stack (enable button) itkEventMacroDeclaration(UndoStackEvent, itk::ModifiedEvent); itkEventMacroDeclaration(UndoEmptyEvent, UndoStackEvent); itkEventMacroDeclaration(RedoEmptyEvent, UndoStackEvent); itkEventMacroDeclaration(UndoNotEmptyEvent, UndoStackEvent); itkEventMacroDeclaration(RedoNotEmptyEvent, UndoStackEvent); /// Additional unused events, if anybody wants to put an artificial limit to the possible number of items in the stack itkEventMacroDeclaration(UndoFullEvent, UndoStackEvent); itkEventMacroDeclaration(RedoFullEvent, UndoStackEvent); #pragma GCC visibility pop } // namespace mitk #endif /* LIMITEDLINEARUNDO_H_HEADER_INCLUDED_C16E9C96 */ diff --git a/Modules/Core/include/mitkLine.h b/Modules/Core/include/mitkLine.h index 936060e4f5..1c11c873c6 100644 --- a/Modules/Core/include/mitkLine.h +++ b/Modules/Core/include/mitkLine.h @@ -1,413 +1,413 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKLINE_H_HEADER_INCLUDED_C19C01E2 #define MITKLINE_H_HEADER_INCLUDED_C19C01E2 #include "mitkNumericTypes.h" #include #include #include #include namespace mitk { //##Documentation - //## @brief Descibes a line + //## @brief Describes 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.GetVectorFromOrigin() + m_Direction; m_Point = point1; m_Direction = point2 - point1.GetVectorFromOrigin(); } //##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 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 p, itk::Vector d, itk::Point &s1, itk::Point &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] < y2)) { // yes, intersection point within the bounds of the border-line if (s_num) s2 = l; else s1 = l; ++s_num; } } if (fabs(d[0]) > eps) { t = (x2 - p[0]) / d[0]; itk::Point l = p + d * t; if ((l[1] >= y1) && (l[1] < y2)) { // yes, intersection point within the bounds of the border-line if (s_num) s2 = l; else s1 = l; ++s_num; } } /*test if intersecting with the vertical axis*/ if (fabs(d[1]) > eps) { t = (y1 - p[1]) / d[1]; itk::Point l = p + d * t; if ((l[0] >= x1) && (l[0] < x2)) { // yes, intersection point within the bounds of the border-line if (s_num) s2 = l; else s1 = l; ++s_num; } } if (fabs(d[1]) > eps) { t = (y2 - p[1]) / d[1]; itk::Point l = p + d * t; if ((l[0] >= x1) && (l[0] < x2)) { // yes, intersection point within the bounds of the border-line if (s_num) s2 = l; else s1 = l; ++s_num; } } return s_num; } /** * \brief Calculates the intersection points of a straight line in 3D with * a box. * * \param x1,y1,z1 first corner of the box * \param x2,y2,z2 second corner of the box * \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 BoxLineIntersection(TCoordRep x1, TCoordRep y1, TCoordRep z1, TCoordRep x2, TCoordRep y2, TCoordRep z2, itk::Point p, itk::Vector d, itk::Point &s1, itk::Point &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 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[k] <= box[k * 2]) && (point[k] >= box[k * 2 + 1]))) && (((point[l] >= box[l * 2]) && (point[l] <= box[l * 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/Modules/Core/include/mitkLocalStorageHandler.h b/Modules/Core/include/mitkLocalStorageHandler.h index 86349b4138..b20eb19b3d 100644 --- a/Modules/Core/include/mitkLocalStorageHandler.h +++ b/Modules/Core/include/mitkLocalStorageHandler.h @@ -1,112 +1,112 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef LOCALSTORAGEHANDLER_H_HEADER_INCLUDED_C1E6EA08 #define LOCALSTORAGEHANDLER_H_HEADER_INCLUDED_C1E6EA08 #include "mitkBaseRenderer.h" #include "mitkCommon.h" #include "mitkLevelWindow.h" #include "mitkVtkPropRenderer.h" #include #include #include class vtkWindow; class vtkProp; namespace mitk { /** \brief Interface for accessing (templated) LocalStorageHandler instances. */ class BaseLocalStorageHandler { public: virtual ~BaseLocalStorageHandler() {} virtual void ClearLocalStorage(mitk::BaseRenderer *renderer, bool unregisterFromBaseRenderer = true) = 0; }; /** \brief Templated class for management of LocalStorage implementations in Mappers. * * The LocalStorageHandler is responsible for providing a LocalStorage to a * concrete mitk::Mapper subclass. Each RenderWindow / mitk::BaseRenderer is - * assigned its own LocalStorage instance so that all contained ressources + * assigned its own LocalStorage instance so that all contained resources * (actors, shaders, textures, ...) are provided individually per window. * */ template class LocalStorageHandler : public mitk::BaseLocalStorageHandler { protected: std::map m_BaseRenderer2LS; public: - /** \brief deallocates a local storage for a specifc BaseRenderer (if the + /** \brief deallocates a local storage for a specific BaseRenderer (if the * BaseRenderer is itself deallocating it in its destructor, it has to set * unregisterFromBaseRenderer=false) */ void ClearLocalStorage(mitk::BaseRenderer *renderer, bool unregisterFromBaseRenderer = true) override { // MITK_INFO << "deleting a localstorage on a mapper request"; if (unregisterFromBaseRenderer) renderer->UnregisterLocalStorageHandler(this); L *l = m_BaseRenderer2LS[renderer]; m_BaseRenderer2LS.erase(renderer); delete l; } std::vector GetRegisteredBaseRenderer() { std::vector baserenderers; typename std::map::iterator it; for (it = m_BaseRenderer2LS.begin(); it != m_BaseRenderer2LS.end(); ++it) { baserenderers.push_back(it->first); } return baserenderers; } /** \brief Retrieves a LocalStorage for a specific BaseRenderer. * * Should be used by mappers in GenerateDataForRenderer() */ L *GetLocalStorage(mitk::BaseRenderer *forRenderer) { L *l = m_BaseRenderer2LS[forRenderer]; if (!l) { // MITK_INFO << "creating new localstorage"; l = new L; m_BaseRenderer2LS[forRenderer] = l; forRenderer->RegisterLocalStorageHandler(this); } return l; } ~LocalStorageHandler() override { typename std::map::iterator it; for (it = m_BaseRenderer2LS.begin(); it != m_BaseRenderer2LS.end(); it++) { (*it).first->UnregisterLocalStorageHandler(this); delete (*it).second; } m_BaseRenderer2LS.clear(); } }; } // namespace mitk #endif /* LOCALSTORAGEHANDLER_H_HEADER_INCLUDED_C1E6EA08 */ diff --git a/Modules/Core/include/mitkLocaleSwitch.h b/Modules/Core/include/mitkLocaleSwitch.h index 601ac02d63..0d02161310 100644 --- a/Modules/Core/include/mitkLocaleSwitch.h +++ b/Modules/Core/include/mitkLocaleSwitch.h @@ -1,72 +1,72 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkLocaleSwitch_h #define __mitkLocaleSwitch_h #include "MitkCoreExports.h" namespace mitk { /** \brief Convenience class to temporarily change the current locale. This helper class can be used to switch to a specific locale for a couple of operations. Once the class is destroyed, the previous locale will be restored. This avoids calling or forgetting to call setlocale() in multiple return locations. Typically this is used to switch to a "C" locale when parsing or printing numbers, in order to consistently get "." and not "," as a decimal separator. WARNING: Please be aware that using setlocale and there for is not thread - safe. So use this class with care (see tast T24295 for more information. + safe. So use this class with care (see task T24295 for more information. This switch is especially use full if you have to deal with third party code - where you have to controll the locale via set locale + where you have to control the locale via set locale \code { mitk::LocaleSwitch localeSwitch("C");// installs C locale until the end of the function ExternalLibraryCall(); //that might throw or what ever. } \endcode If you just want to control you own stringstream operations use imbue instead, as it is threadsafe. E.G.: \code std::string toString(int number) { std::ostringstream parser; parser.imbue(std::locale("C")); parser << number; return parser.str(); } \endcode */ struct MITKCORE_EXPORT LocaleSwitch { explicit LocaleSwitch(const char *newLocale); ~LocaleSwitch(); LocaleSwitch(LocaleSwitch &) = delete; LocaleSwitch operator=(LocaleSwitch &) = delete; private: struct Impl; Impl *m_LocaleSwitchImpl; }; } #endif // __mitkLocaleSwitch_h diff --git a/Modules/Core/include/mitkLog.h b/Modules/Core/include/mitkLog.h index 1d74b0d687..95c6a7086c 100644 --- a/Modules/Core/include/mitkLog.h +++ b/Modules/Core/include/mitkLog.h @@ -1,104 +1,104 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_LOG_H #define _MITK_LOG_H #include #include namespace mitk { /*! \brief mbilog backend implementation for mitk */ class MITKCORE_EXPORT LoggingBackend : public mbilog::TextBackendBase { public: /** \brief overloaded method for receiving log message from mbilog */ void ProcessMessage(const mbilog::LogMessage &) override; /** \brief registers MITK logging backend at mbilog */ static void Register(); /** \brief Unregisters MITK logging backend at mbilog */ static void Unregister(); /** \brief Sets extra log file path (additionally to the console log) */ static void SetLogFile(const char *file); /** @brief Activates and handles a rolling log file with the given prefix and path. * This method handles 10 log files with a given prefix, e.g. "myLogFile". * The 10 log files will then look like this: * myLogFile-0.log (current file) * myLogFile-1.log (last file) * myLogFile-2.log * [...] * myLogFile-9.log * * Everytime this method this called, normally when MITK is started, then * all log files are copied one file below (0 to 1, 1 to 2, and so on). - * The oldes logfile (number 9) is always deleted. So users have access to + * The oldest logfile (number 9) is always deleted. So users have access to * the log files of the last 10 runs. * @throws mitk::Exception Throws an exception if there is a problem with renaming the logfiles, e.g., because of * file access problems. * @param prefixPath Should hold the prefix of the logfile together with its path. E.g., * "C:/programs/mitk/myLogFile". */ static void RotateLogFiles(const std::string &prefixPath); /** @brief Increments the names of logfiles with the given prefixPath. * This means, if the prefixPath is "myLogFile" myLogFile-0.log * is renamed to myLogFile-1.log, myLogFile-1.log to myLogFile-2.log, * and so on. The oldest logfile is deleted. The number of log files is * defined by the parameter "numLogFiles". The first logfile name is - * "free" (e.g., [prefix]-0.log) again. This name is retured. + * "free" (e.g., [prefix]-0.log) again. This name is returned. * @param prefixPath Should hold the prefix of the logfile together with its path. E.g., * "C:/programs/mitk/myLogFile". * @param numLogFiles Sets the number of logfiles. Default value is 10. This means logfiles from [prefix]-0.log * to [prefix]-1.log are stored. * @return Returns a new logfile name which is free again because the old first log file was renamed. * @throws mitk::Exception Throws an exception if there is a problem with renaming the logfiles, e.g., because of * file access problems. */ static std::string IncrementLogFileNames(const std::string &prefixPath, int numLogFiles = 10); /** @return Returns the log file if there is one. Returns an empty string * if no log file is active. */ static std::string GetLogFile(); /** \brief Enables an additional logging output window by means of itk::outputwindow * This might be relevant for showing log output in applications with no default output console */ static void EnableAdditionalConsoleWindow(bool enable); /** \brief Automatically extracts and removes the "--logfile " parameters from the standard C main(argc,argv) * parameter list and calls SetLogFile if needed */ static void CatchLogFileCommandLineParameter(int &argc, char **argv); mbilog::OutputType GetOutputType() const override; protected: /** Checks if a file exists. * @return Returns true if the file exists, false if not. */ static bool CheckIfFileExists(const std::string &filename); }; } #endif diff --git a/Modules/Core/include/mitkMapper.h b/Modules/Core/include/mitkMapper.h index c30e6411e0..b4200f76b4 100644 --- a/Modules/Core/include/mitkMapper.h +++ b/Modules/Core/include/mitkMapper.h @@ -1,211 +1,211 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MAPPER_H_HEADER_INCLUDED_C1E6EA08 #define MAPPER_H_HEADER_INCLUDED_C1E6EA08 #include "mitkBaseRenderer.h" #include "mitkCommon.h" #include "mitkLevelWindow.h" #include "mitkLocalStorageHandler.h" #include "mitkVtkPropRenderer.h" #include #include #include class vtkWindow; class vtkProp; namespace mitk { class BaseRenderer; class BaseData; class DataNode; /** \brief Base class of all mappers, Vtk as well as OpenGL mappers * * By the help of mappers, the input data is transformed to tangible primitives, * such as surfaces, points, lines, etc. * This is the base class of all mappers, Vtk as well as OpenGL mappers. * Subclasses of mitk::Mapper control the creation of rendering primitives * that interface to the graphics library (e.g., OpenGL, vtk). * * \todo Should Mapper be a subclass of ImageSource? * \ingroup Mapper */ class MITKCORE_EXPORT Mapper : public itk::Object { public: mitkClassMacroItkParent(Mapper, itk::Object); /** \brief Set the DataNode containing the data to map */ itkSetObjectMacro(DataNode, DataNode); /** \brief Get the DataNode containing the data to map. * Method only returns valid DataNode Pointer if the mapper belongs to a data node. * Otherwise, the returned DataNode Pointer might be invalid. */ virtual DataNode *GetDataNode() const; /**\brief Get the data to map * * Returns the mitk::BaseData object associated with this mapper. * \return the mitk::BaseData associated with this mapper. * \deprecatedSince{2013_03} Use GetDataNode()->GetData() instead to access the data */ DEPRECATED(BaseData *GetData() const); /** \brief Convenience access method for color properties (instances of * ColorProperty) * \return \a true property was found * \deprecatedSince{2013_03} Use GetDataNode()->GetColor(...) instead to get the color */ DEPRECATED(virtual bool GetColor(float rgb[3], BaseRenderer *renderer, const char *name = "color") const); /** \brief Convenience access method for visibility properties (instances * of BoolProperty) * \return \a true property was found * \sa IsVisible * \deprecatedSince{2013_03} Use GetDataNode()->GetVisibility(...) instead to get the visibility */ DEPRECATED(virtual bool GetVisibility(bool &visible, BaseRenderer *renderer, const char *name = "visible") const); /** \brief Convenience access method for opacity properties (instances of * FloatProperty) * \return \a true property was found * \deprecatedSince{2013_03} Use GetDataNode()->GetOpacity(...) instead to get the opacity */ DEPRECATED(virtual bool GetOpacity(float &opacity, BaseRenderer *renderer, const char *name = "opacity") const); /** \brief Convenience access method for color properties (instances of * LevelWindoProperty) * \return \a true property was found * \deprecatedSince{2013_03} Use GetDataNode->GetLevelWindow(...) instead to get the levelwindow */ DEPRECATED(virtual bool GetLevelWindow(LevelWindow &levelWindow, BaseRenderer *renderer, const char *name = "levelwindow") const); /** \brief Convenience access method for visibility properties (instances * of BoolProperty). Return value is the visibility. Default is * visible==true, i.e., true is returned even if the property (\a * propertyKey) is not found. * * Thus, the return value has a different meaning than in the * GetVisibility method! * \sa GetVisibility * \deprecatedSince{2013_03} Use GetDataNode()->GetVisibility(...) instead */ DEPRECATED(virtual bool IsVisible(BaseRenderer *renderer, const char *name = "visible") const); /** \brief Returns whether this is an vtk-based mapper * \deprecatedSince{2013_03} All mappers of superclass VTKMapper are vtk based, use a dynamic_cast instead */ virtual bool IsVtkBased() const { return true; } /** \brief Calls the time step of the input data for the specified renderer and checks * whether the time step is valid and calls method GenerateDataForRenderer() */ virtual void Update(BaseRenderer *renderer); /** \brief Responsible for calling the appropriate render functions. * To be implemented in sub-classes. */ virtual void MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType type) = 0; /** * \brief Apply specific color and opacity properties read from the PropertyList. * Reimplemented in GLmapper (does not use the actor) and the VtkMapper class. * The function is called by the individual mapper (mostly in the ApplyProperties() or ApplyAllProperties() * method). */ virtual void ApplyColorAndOpacityProperties(mitk::BaseRenderer *renderer, vtkActor *actor = nullptr) = 0; /** \brief Set default values of properties used by this mapper * to \a node * * \param node The node for which the properties are set * \param overwrite overwrite existing properties (default: \a false) * \param renderer defines which property list of node is used * (default: \a nullptr, i.e. default property list) */ static void SetDefaultProperties(DataNode *node, BaseRenderer *renderer = nullptr, bool overwrite = false); /** \brief Returns the current time step as calculated from the renderer */ int GetTimestep() const { return m_TimeStep; } /** Returns true if this Mapper currently allows for Level-of-Detail rendering. * This reflects whether this Mapper currently invokes StartEvent, EndEvent, and * ProgressEvent on BaseRenderer. */ virtual bool IsLODEnabled(BaseRenderer * /*renderer*/) const { return false; } protected: /** \brief explicit constructor which disallows implicit conversions */ explicit Mapper(); /** \brief virtual destructor in order to derive from this class */ ~Mapper() override; /** \brief Generate the data needed for rendering (independent of a specific renderer) * \deprecatedSince{2013_03} Use GenerateDataForRenderer(BaseRenderer* renderer) instead. */ DEPRECATED(virtual void GenerateData()) {} /** \brief Generate the data needed for rendering into \a renderer */ virtual void GenerateDataForRenderer(BaseRenderer * /* renderer */) {} /** \brief Updates the time step, which is sometimes needed in subclasses */ virtual void CalculateTimeStep(BaseRenderer *renderer); /** \brief Reset the mapper (i.e., make sure that nothing is displayed) if no * valid data is present. In most cases the reimplemented function * disables the according actors (toggling visibility off) * * To be implemented in sub-classes. */ virtual void ResetMapper(BaseRenderer * /*renderer*/) {} mitk::DataNode *m_DataNode; private: /** \brief The current time step of the dataset to be rendered, * for use in subclasses. * The current timestep can be accessed via the GetTimestep() method. */ int m_TimeStep; /** \brief copy constructor */ Mapper(const Mapper &); /** \brief assignment operator */ Mapper &operator=(const Mapper &); public: - /** \brief Base class for mapper specific rendering ressources. + /** \brief Base class for mapper specific rendering resources. */ class MITKCORE_EXPORT BaseLocalStorage { public: BaseLocalStorage() = default; virtual ~BaseLocalStorage() = default; BaseLocalStorage(const BaseLocalStorage &) = delete; BaseLocalStorage & operator=(const BaseLocalStorage &) = delete; bool IsGenerateDataRequired(mitk::BaseRenderer *renderer, mitk::Mapper *mapper, mitk::DataNode *dataNode) const; inline void UpdateGenerateDataTime() { m_LastGenerateDataTime.Modified(); } inline itk::TimeStamp &GetLastGenerateDataTime() { return m_LastGenerateDataTime; } protected: /** \brief timestamp of last update of stored data */ itk::TimeStamp m_LastGenerateDataTime; }; }; } // namespace mitk #endif /* MAPPER_H_HEADER_INCLUDED_C1E6EA08 */ diff --git a/Modules/Core/include/mitkMaterial.h b/Modules/Core/include/mitkMaterial.h index 271a6bb2dc..bf42e9e30f 100644 --- a/Modules/Core/include/mitkMaterial.h +++ b/Modules/Core/include/mitkMaterial.h @@ -1,453 +1,453 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_MATERIAL_H_ #define _MITK_MATERIAL_H_ #include #include #include #include #include #include #include namespace mitk { /** * Encapsulates 3D visualization properties which are forwarded to vtk for * color mapping. This includes color, specular coefficient and power, opacity * interpolation type (flat, gouraud, phong) and representation (points, * wireframe or surface). * * @see vtkProperty */ class MITKCORE_EXPORT Material : public itk::Object { public: mitkClassMacroItkParent(Material, itk::Object); typedef itk::RGBPixel Color; enum InterpolationType { Flat, Gouraud, Phong }; enum RepresentationType { Points, Wireframe, Surface }; /** * Constructor. Materials are set to the following default values: * Color (0.5, 0.5, 0.5) color coefficient 1.0, specular color (1.0, 1.0, 1.0), * specular coefficient 1.0, specular power 10, opacity 1.0, interpolation * Gouraud, representation Surface. */ static Pointer New() { Pointer smartPtr = new Material(); smartPtr->UnRegister(); return smartPtr; } /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param color the material color in RGB. Each RGB value should be in the * range [0..1] * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ static Pointer New(Color color, double opacity = 1.0f) { Pointer smartPtr = new Material(color, opacity); smartPtr->UnRegister(); return smartPtr; } /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ static Pointer New(double red, double green, double blue, double opacity = 1.0f) { Pointer smartPtr = new Material(red, green, blue, opacity); smartPtr->UnRegister(); return smartPtr; } /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) * @param colorCoefficient a scaling factor for the color coefficient which * will be multiplied with each color component (range [0..1]). * @param specularCoefficient controls in combination with the specular power * how shiny the material will appear (range [0..1]). * @param specularPower controls in combination with the specular coefficient * how shiny the material will appear (range [0..inf]). * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ static Pointer New(double red, double green, double blue, double colorCoefficient, double specularCoefficient, double specularPower, double opacity) { Pointer smartPtr = new Material(red, green, blue, colorCoefficient, specularCoefficient, specularPower, opacity); smartPtr->UnRegister(); return smartPtr; } /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * * @param color the material color in RGB. Each RGB value should be in the * range [0..1] * @param colorCoefficient a scaling factor for the color coefficient which * will be multiplied with each color component (range [0..1]). * @param specularCoefficient controls in combination with the specular power * how shiny the material will appear (range [0..1]). * @param specularPower controls in combination with the specular coefficient * how shiny the material will appear (range [0..inf]). * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ static Pointer New( Color color, double colorCoefficient, double specularCoefficient, double specularPower, double opacity) { Pointer smartPtr = new Material(color, colorCoefficient, specularCoefficient, specularPower, opacity); smartPtr->UnRegister(); return smartPtr; } /** * Copy constructor */ mitkNewMacro1Param(Material, const Material &); /** - * Copy constructor, provided for convinience. The values are copied from property + * Copy constructor, provided for convenience. The values are copied from property * and afterwards the values provided for red green blue and opacity are written into the object. */ static Pointer New( const Material &property, double red, double green, double blue, double opacity = 1.0, std::string name = "") { Pointer smartPtr = new Material(property, red, green, blue, opacity, name); smartPtr->UnRegister(); return smartPtr; } virtual bool Assignable(const Material &other) const; virtual Material &operator=(const Material &other); /* Sets the materials color in RGB space. The rgb components have to be * in the range [0..1] * @param color the new color of the material */ virtual void SetColor(Color color); /** * Sets the materials color in RGB space. The rgb components have to be * in the range [0..1] * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) */ virtual void SetColor(double red, double green, double blue); /** * Sets a attenuation coefficient for the color. A value of 0 results in * a black object. VAlid range is [0..1] * @param coefficient the color attenuation coefficient */ virtual void SetColorCoefficient(double coefficient); /** * Sets the specular color * @param color the specular color in RGB. Each RGB value should be in the * range [0..1] */ virtual void SetSpecularColor(Color color); /** * Sets the specular color * @param red the red component of the specular color (range [0..1]) * @param green the green component of the specular color (range [0..1]) * @param blue the blue component of the specular color (range [0..1]) */ virtual void SetSpecularColor(double red, double green, double blue); /** * Sets the specular coefficient which controls the shininess of the object * together with the specular power * @param specularCoefficient the new specular coefficient. Valid range * is [0..1] */ virtual void SetSpecularCoefficient(double specularCoefficient); /** * Sets the specular power which controls the shininess of the object * together with the specular coefficient * @param specularPower the new specular coefficient. Valid range * is [0..inf] */ virtual void SetSpecularPower(double specularPower); /** * Sets the opacity of the material, which controls how transparent the * object appears. Valid range is [0..1], where 0 means fully transparent * and 1 means a solid surface. * @param opacity the new opacity of the material */ virtual void SetOpacity(double opacity); /** * Sets the surface interpolation method of the object rendered using the * given materials. Valid Interopation types are Flat, Gouraud and Phong. * See any computer graphics book for their meaning * @param interpolation the interpolation method used for rendering of * surfaces. */ virtual void SetInterpolation(InterpolationType interpolation); /** * Sets the surface representation method of the object rendered using the * given materials. Valid Interopation types are Points, Wireframe and * Surface. * @param representation the representation method used for rendering of * surfaces. */ virtual void SetRepresentation(RepresentationType representation); /** * Set/Get the width of a Line. The width is expressed in screen units. The default is 1.0. */ virtual void SetLineWidth(float lineWidth); /** * @returns the color of the material */ virtual Color GetColor() const; /** * @returns the color coefficient of the material. Range is [0..1] */ virtual double GetColorCoefficient() const; /** * @returns the specular color of the material in rgb values, which * range from 0 .. 1 */ virtual Color GetSpecularColor() const; /** * @returns the specular coefficient used for rendering. Range is [0..1] */ virtual double GetSpecularCoefficient() const; /** * @returns the specular power. Ranges from 0 to infinity */ virtual double GetSpecularPower() const; /** * @returns the opacity of the material. Ranges from 0 to 1 */ virtual double GetOpacity() const; /** * @returns the interpolation method used for rendering. */ virtual InterpolationType GetInterpolation() const; /** * @returns the representation type used for rendering. */ virtual RepresentationType GetRepresentation() const; /** * @returns the interpolation method used for rendering using the predefined * vtk constants. */ virtual int GetVtkInterpolation() const; /** * @returns the representation type used for rendering using the predefined * vtk constants. */ virtual int GetVtkRepresentation() const; /** * @returns the line width used for wireframe rendering as a fraction of screen units */ virtual float GetLineWidth() const; /** * Fills the current materials with the properties of the * given material. * @param property the materials which should be copied in the * current materials */ virtual void Initialize(const Material &property); /** * comparison operator which uses the member variables for * comparison */ virtual bool operator==(const Material &property) const; /** * Dumps the properties to the out stream out */ void PrintSelf(std::ostream &os, itk::Indent) const override; /** * Sets an optional name which may be associated with the material property * Please note, that this name is NOT forwarded to the data tree node * as the node name */ itkSetMacro(Name, std::string); /** * returns the name associated with the material property */ itkGetConstMacro(Name, std::string); protected: /** * Constructor. Materials are set to the following default values: * Color (0.5, 0.5, 0.5) color coefficient 1.0, specular color (1.0, 1.0, 1.0), * specular coefficient 1.0, specular power 10, opacity 1.0, interpolation * Gouraud, representation Surface. */ Material(); /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param color the material color in RGB. Each RGB value should be in the * range [0..1] * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ Material(Color color, double opacity = 1.0f); /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ Material(double red, double green, double blue, double opacity = 1.0f); /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) * @param colorCoefficient a scaling factor for the color coefficient which * will be multiplied with each color component (range [0..1]). * @param specularCoefficient controls in combination with the specular power * how shiny the material will appear (range [0..1]). * @param specularPower controls in combination with the specular coefficient * how shiny the material will appear (range [0..inf]). * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ Material(double red, double green, double blue, double colorCoefficient, double specularCoefficient, double specularPower, double opacity); /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * * @param color the material color in RGB. Each RGB value should be in the * range [0..1] * @param colorCoefficient a scaling factor for the color coefficient which * will be multiplied with each color component (range [0..1]). * @param specularCoefficient controls in combination with the specular power * how shiny the material will appear (range [0..1]). * @param specularPower controls in combination with the specular coefficient * how shiny the material will appear (range [0..inf]). * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ Material(Color color, double colorCoefficient, double specularCoefficient, double specularPower, double opacity); /** * Copy constructor */ Material(const Material &property); /** - * Copy constructor, provided for convinience. The values are copied from property + * Copy constructor, provided for convenience. The values are copied from property * and afterwards the values provided for red green blue and opacity are written into the object. */ Material( const Material &property, double red, double green, double blue, double opacity = 1.0, std::string name = ""); virtual void InitializeStandardValues(); virtual void Update(); std::string m_Name; Color m_Color; Color m_SpecularColor; double m_ColorCoefficient; double m_SpecularCoefficient; double m_SpecularPower; double m_Opacity; float m_LineWidth; InterpolationType m_Interpolation; RepresentationType m_Representation; }; typedef itk::VectorContainer MaterialVectorContainer; } #endif diff --git a/Modules/Core/include/mitkMemoryUtilities.h b/Modules/Core/include/mitkMemoryUtilities.h index 502faf095c..33e94a49bc 100644 --- a/Modules/Core/include/mitkMemoryUtilities.h +++ b/Modules/Core/include/mitkMemoryUtilities.h @@ -1,91 +1,91 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_MEMORY_UTILITIES_H_ #define _MITK_MEMORY_UTILITIES_H_ #include #include namespace mitk { class MITKCORE_EXPORT MemoryUtilities { public: /** * Returns the memory usage of the current process in bytes. * On linux, this refers to the virtual memory allocated by * the process (the VIRT column in top). * On windows, this refery to the size in bytes of the working * set pages (the "Speicherauslastung" column in the task manager). */ static size_t GetProcessMemoryUsage(); /** - * Returns the total size of phyiscal memory in bytes + * Returns the total size of physical memory in bytes */ static size_t GetTotalSizeOfPhysicalRam(); /** * Allocates an array of a given number of elements. Each element * has a size of sizeof(ElementType). The function returns nullptr, if the array * could not be allocated. * @param numberOfElements the number of elements of the array * @param noThrow if set to false, an exception is thrown if memory allocation * fails. If set to true, a itk::MemoryAllocationError is thrown * @returns a pointer to the allocated array. If noThrow == true, nullptr is returned * if memory allocation failed. */ template static ElementType *AllocateElements(size_t numberOfElements, bool noThrow = false) { // Encapsulate all image memory allocation here to throw an // exception when memory allocation fails even when the compiler // does not do this by default. ElementType *data = nullptr; try { data = new ElementType[numberOfElements]; } catch (...) { data = nullptr; } if ((data == nullptr) && (noThrow == false)) { throw itk::MemoryAllocationError(__FILE__, __LINE__, "Failed to allocate memory.", ITK_LOCATION); } return data; } /** * Deletes an array of elements previously allocated by AllocateElements. * @param elements the array to delete. Not that nullptr is an accepted value. */ template static void DeleteElements(ElementType *elements) { if (elements != nullptr) { delete[] elements; } } protected: #ifndef _MSC_VER static int ReadStatmFromProcFS( int *size, int *res, int *shared, int *text, int *sharedLibs, int *stack, int *dirtyPages); #endif }; } // end of namespace mitk #endif diff --git a/Modules/Core/include/mitkMessage.h b/Modules/Core/include/mitkMessage.h index 564472316c..3b8723a8a2 100644 --- a/Modules/Core/include/mitkMessage.h +++ b/Modules/Core/include/mitkMessage.h @@ -1,697 +1,697 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkMessageHIncluded #define mitkMessageHIncluded #include #include #include /** * Adds a Message<> variable and methods to add/remove message delegates to/from * this variable. */ #define mitkNewMessageMacro(msgHandleObject) \ private: \ ::mitk::Message<> m_##msgHandleObject##Message; \ \ public: \ inline void Add##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate<> &delegate) \ { \ m_##msgHandleObject##Message += delegate; \ } \ inline void Remove##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate<> &delegate) \ { \ m_##msgHandleObject##Message -= delegate; \ } #define mitkNewMessageWithReturnMacro(msgHandleObject, returnType) \ private: \ ::mitk::Message m_##msgHandleObject##Message; \ \ public: \ inline void Add##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate &delegate) \ { \ m_##msgHandleObject##Message += delegate; \ } \ inline void Remove##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate &delegate) \ { \ m_##msgHandleObject##Message -= delegate; \ } #define mitkNewMessage1Macro(msgHandleObject, type1) \ private: \ ::mitk::Message1 m_##msgHandleObject##Message; \ \ public: \ void Add##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate1 &delegate) \ { \ m_##msgHandleObject##Message += delegate; \ } \ void Remove##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate1 &delegate) \ { \ m_##msgHandleObject##Message -= delegate; \ } #define mitkNewMessage2Macro(msgHandleObject, type1, type2) \ private: \ ::mitk::Message2 m_##msgHandleObject##Message; \ \ public: \ void Add##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate2 &delegate) \ { \ m_##msgHandleObject##Message += delegate; \ } \ void Remove##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate2 &delegate) \ { \ m_##msgHandleObject##Message -= delegate; \ } namespace mitk { template class MessageAbstractDelegate { public: virtual ~MessageAbstractDelegate() {} virtual A Execute() const = 0; virtual bool operator==(const MessageAbstractDelegate *cmd) const = 0; virtual MessageAbstractDelegate *Clone() const = 0; }; template class MessageAbstractDelegate1 { public: virtual ~MessageAbstractDelegate1() {} virtual A Execute(T t) const = 0; virtual bool operator==(const MessageAbstractDelegate1 *cmd) const = 0; virtual MessageAbstractDelegate1 *Clone() const = 0; }; template class MessageAbstractDelegate2 { public: virtual ~MessageAbstractDelegate2() {} virtual A Execute(T t, U u) const = 0; virtual bool operator==(const MessageAbstractDelegate2 *cmd) const = 0; virtual MessageAbstractDelegate2 *Clone() const = 0; }; template class MessageAbstractDelegate3 { public: virtual ~MessageAbstractDelegate3() {} virtual A Execute(T t, U u, V v) const = 0; virtual bool operator==(const MessageAbstractDelegate3 *cmd) const = 0; virtual MessageAbstractDelegate3 *Clone() const = 0; }; template class MessageAbstractDelegate4 { public: virtual ~MessageAbstractDelegate4() {} virtual A Execute(T t, U u, V v, W w) const = 0; virtual bool operator==(const MessageAbstractDelegate4 *cmd) const = 0; virtual MessageAbstractDelegate4 *Clone() const = 0; }; /** * This class essentially wraps a function pointer with signature * A(R::*function)(). A is the return type of your callback function * and R the type of the class implementing the function. * * Use this class to add a callback function to * messages without parameters. */ template class MessageDelegate : public MessageAbstractDelegate { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate(R *object, A (R::*memberFunctionPointer)()) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } ~MessageDelegate() override {} // override function "Call" A Execute() const override { return (m_Object->*m_MemberFunctionPointer)(); // execute member function } bool operator==(const MessageAbstractDelegate *c) const override { const MessageDelegate *cmd = dynamic_cast *>(c); if (!cmd) return false; if ((void *)this->m_Object != (void *)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate *Clone() const override { return new MessageDelegate(m_Object, m_MemberFunctionPointer); } private: R *m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(); // pointer to member function }; /** * This class essentially wraps a function pointer with signature * A(R::*function)(T). A is the return type of your callback function, * R the type of the class implementing the function and T the type * of the argument. * * Use this class to add a callback function to * messages with one parameter. * * If you need more parameters, use MessageDelegate2 etc. */ template class MessageDelegate1 : public MessageAbstractDelegate1 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate1(R *object, A (R::*memberFunctionPointer)(T)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } ~MessageDelegate1() override {} // override function "Call" A Execute(T t) const override { return (m_Object->*m_MemberFunctionPointer)(t); // execute member function } bool operator==(const MessageAbstractDelegate1 *c) const override { const MessageDelegate1 *cmd = dynamic_cast *>(c); if (!cmd) return false; if ((void *)this->m_Object != (void *)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate1 *Clone() const override { return new MessageDelegate1(m_Object, m_MemberFunctionPointer); } private: R *m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T); // pointer to member function }; template class MessageDelegate2 : public MessageAbstractDelegate2 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate2(R *object, A (R::*memberFunctionPointer)(T, U)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } ~MessageDelegate2() override {} // override function "Call" A Execute(T t, U u) const override { return (m_Object->*m_MemberFunctionPointer)(t, u); // execute member function } bool operator==(const MessageAbstractDelegate2 *c) const override { const MessageDelegate2 *cmd = dynamic_cast *>(c); if (!cmd) return false; if ((void *)this->m_Object != (void *)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate2 *Clone() const override { return new MessageDelegate2(m_Object, m_MemberFunctionPointer); } private: R *m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T, U); // pointer to member function }; template class MessageDelegate3 : public MessageAbstractDelegate3 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate3(R *object, A (R::*memberFunctionPointer)(T, U, V)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } ~MessageDelegate3() override {} // override function "Call" A Execute(T t, U u, V v) const override { return (m_Object->*m_MemberFunctionPointer)(t, u, v); // execute member function } bool operator==(const MessageAbstractDelegate3 *c) const override { const MessageDelegate3 *cmd = dynamic_cast *>(c); if (!cmd) return false; if ((void *)this->m_Object != (void *)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate3 *Clone() const override { return new MessageDelegate3(m_Object, m_MemberFunctionPointer); } private: R *m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T, U, V); // pointer to member function }; template class MessageDelegate4 : public MessageAbstractDelegate4 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate4(R *object, A (R::*memberFunctionPointer)(T, U, V, W)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~MessageDelegate4() {} // override function "Call" virtual A Execute(T t, U u, V v, W w) const { return (m_Object->*m_MemberFunctionPointer)(t, u, v, w); // execute member function } bool operator==(const MessageAbstractDelegate4 *c) const { const MessageDelegate4 *cmd = dynamic_cast *>(c); if (!cmd) return false; if ((void *)this->m_Object != (void *)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate4 *Clone() const { return new MessageDelegate4(m_Object, m_MemberFunctionPointer); } private: R *m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T, U, V, W); // pointer to member function }; template class MessageBase { public: typedef std::vector ListenerList; virtual ~MessageBase() { for (auto iter = m_Listeners.begin(); iter != m_Listeners.end(); ++iter) { delete *iter; } } MessageBase() {} MessageBase(const MessageBase &o) { for (typename ListenerList::iterator iter = o.m_Listeners.begin(); iter != o.m_Listeners.end(); ++iter) { m_Listeners.push_back((*iter)->Clone()); } } MessageBase &operator=(const MessageBase &o) { MessageBase tmp(o); std::swap(tmp.m_Listeners, this->m_Listeners); return *this; } void AddListener(const AbstractDelegate &delegate) const { AbstractDelegate *msgCmd = delegate.Clone(); m_Mutex.lock(); for (auto iter = m_Listeners.begin(); iter != m_Listeners.end(); ++iter) { if ((*iter)->operator==(msgCmd)) { delete msgCmd; m_Mutex.unlock(); return; } } m_Listeners.push_back(msgCmd); m_Mutex.unlock(); } void operator+=(const AbstractDelegate &delegate) const { this->AddListener(delegate); } void RemoveListener(const AbstractDelegate &delegate) const { m_Mutex.lock(); for (auto iter = m_Listeners.begin(); iter != m_Listeners.end(); ++iter) { if ((*iter)->operator==(&delegate)) { delete *iter; m_Listeners.erase(iter); m_Mutex.unlock(); return; } } m_Mutex.unlock(); } void operator-=(const AbstractDelegate &delegate) const { this->RemoveListener(delegate); } const ListenerList &GetListeners() const { return m_Listeners; } bool HasListeners() const { return !m_Listeners.empty(); } bool IsEmpty() const { return m_Listeners.empty(); } protected: /** * \brief List of listeners. * * This is declared mutable for a reason: Imagine an object that sends out notifications and * someone gets a const Database object, because he/she should not write to the * database. He/she should anyway be able to register for notifications about changes in the database * -- this is why AddListener and RemoveListener are declared const. m_Listeners must be * mutable so that AddListener and RemoveListener can modify it regardless of the object's constness. */ mutable ListenerList m_Listeners; mutable std::mutex m_Mutex; }; /** * \brief Event/message/notification class. * * \sa mitk::BinaryThresholdTool * \sa QmitkBinaryThresholdToolGUI * * This totally ITK, Qt, VTK, whatever toolkit independent class * allows one class to send out messages and another class to * receive these message. This class is templated over the * return type (A) of the callback functions. * There are variations of this class * (Message1, Message2, etc.) for sending * one, two or more parameters along with the messages. * * This is an implementation of the Observer pattern. * * \li There is no guarantee about the order of which observer is notified first. At the moment the observers which * register first will be notified first. * \li Notifications are synchronous, by direct method calls. There is no support for asynchronous messages. * * To conveniently add methods for registering/unregistering observers * to Message variables of your class, you can use the mitkNewMessageMacro * macros. */ template class Message : public MessageBase> { public: typedef MessageBase> Super; typedef typename Super::ListenerList ListenerList; void Send() const { ListenerList listeners; { this->m_Mutex.lock(); listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); this->m_Mutex.unlock(); } for (auto iter = listeners.begin(); iter != listeners.end(); ++iter) { // notify each listener (*iter)->Execute(); } } void operator()() const { this->Send(); } }; // message with 1 parameter and return type template class Message1 : public MessageBase> { public: typedef MessageBase> Super; typedef typename Super::ListenerList ListenerList; void Send(T t) const { ListenerList listeners; { this->m_Mutex.lock(); listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); this->m_Mutex.unlock(); } for (auto iter = listeners.begin(); iter != listeners.end(); ++iter) { // notify each listener (*iter)->Execute(t); } } void operator() (T t) const { this->Send(t); } }; // message with 2 parameters and return type template class Message2 : public MessageBase> { public: typedef MessageBase> Super; typedef typename Super::ListenerList ListenerList; void Send(T t, U u) const { ListenerList listeners; { this->m_Mutex.lock(); listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); this->m_Mutex.unlock(); } for (auto iter = listeners.begin(); iter != listeners.end(); ++iter) { // notify each listener (*iter)->Execute(t, u); } } void operator()(T t, U u) const { this->Send(t, u); } }; // message with 3 parameters and return type template class Message3 : public MessageBase> { public: typedef MessageBase> Super; typedef typename Super::ListenerList ListenerList; void Send(T t, U u, V v) const { ListenerList listeners; { this->m_Mutex.lock(); listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); this->m_Mutex.unlock(); } for (typename ListenerList::iterator iter = listeners.begin(); iter != listeners.end(); ++iter) { // notify each listener (*iter)->Execute(t, u, v); } } void operator()(T t, U u, V v) const { this->Send(t, u, v); } }; // message with 4 parameters and return type template class Message4 : public MessageBase> { public: typedef MessageBase> Super; typedef typename Super::ListenerList ListenerList; void Send(T t, U u, V v, W w) const { ListenerList listeners; { this->m_Mutex.lock(); listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); this->m_Mutex.unlock(); } for (typename ListenerList::iterator iter = listeners.begin(); iter != listeners.end(); ++iter) { // notify each listener (*iter)->Execute(t, u, v, w); } } void operator()(T t, U u, V v, W w) const { this->Send(t, u, v, w); } }; /* Here is an example how to use the macros and templates: * * // An object to be send around * class Law * { * private: * std::string m_Description; * * public: * * Law(const std::string law) : m_Description(law) * { } * * std::string GetDescription() const * { * return m_Description; * } * }; * * // The NewtonMachine will issue specific events * class NewtonMachine * { * mitkNewMessageMacro(AnalysisStarted); * mitkNewMessage1Macro(AnalysisStopped, bool); * mitkNewMessage1Macro(LawDiscovered, const Law&); * * public: * * void StartAnalysis() * { * // send the "started" signal * m_AnalysisStartedMessage(); * * // we found a new law of nature by creating one :-) * Law massLaw("F=ma"); * m_LawDiscoveredMessage(massLaw); * } * * void StopAnalysis() * { * // send the "stop" message with false, indicating -* // that no error occured +* // that no error occurred * m_AnalysisStoppedMessage(false); * } * }; * * class Observer * { * private: * * NewtonMachine* m_Machine; * * public: * * Observer(NewtonMachine* machine) : m_Machine(machine) * { * // Add "observers", i.e. function pointers to the machine * m_Machine->AddAnalysisStartedListener( * ::mitk::MessageDelegate(this, &Observer::MachineStarted)); * m_Machine->AddAnalysisStoppedListener( * ::mitk::MessageDelegate1(this, &Observer::MachineStopped)); * m_Machine->AddLawDiscoveredListener( * ::mitk::MessageDelegate1(this, &Observer::LawDiscovered)); * } * * ~Observer() * { * // Always remove your observers when finished * m_Machine->RemoveAnalysisStartedListener( * ::mitk::MessagDelegate(this, &Observer::MachineStarted)); * m_Machine->RemoveAnalysisStoppedListener( * ::mitk::MessageDelegate1(this, &Observer::MachineStopped)); * m_Machine->RemoveLawDiscoveredListener( * ::mitk::MessageDelegate1(this, &Observer::LawDiscovered)); * } * * void MachineStarted() * { * std::cout << "Observed machine has started" << std::endl; * } * * void MachineStopped(bool error) * { * std::cout << "Observed machine stopped " << (error ? "with an error" : "") << std::endl; * } * * void LawDiscovered(const Law& law) * { * std::cout << "New law of nature discovered: " << law.GetDescription() << std::endl; * } * }; * * NewtonMachine newtonMachine; * Observer observer(&newtonMachine); * * // This will send two events to registered observers * newtonMachine.StartAnalysis(); * // This will send one event to registered observers * newtonMachine.StopAnalysis(); * * Another example of how to use these message classes can be * found in the directory Testing, file mitkMessageTest.cpp * */ } // namespace #endif diff --git a/Modules/Core/include/mitkMultiComponentImageDataComparisonFilter.h b/Modules/Core/include/mitkMultiComponentImageDataComparisonFilter.h index 169a6436f2..da5b55c6fa 100644 --- a/Modules/Core/include/mitkMultiComponentImageDataComparisonFilter.h +++ b/Modules/Core/include/mitkMultiComponentImageDataComparisonFilter.h @@ -1,85 +1,85 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKMULTICOMPONENTIMAGEDATACOMPARISONFILTER_H #define MITKMULTICOMPONENTIMAGEDATACOMPARISONFILTER_H // mitk includes #include "mitkCompareImageDataFilter.h" #include "mitkImageToImageFilter.h" // struct CompareFilterResults; namespace mitk { /*! Documentation: * \brief Filter for comparing two multi channel mitk::Image objects by channel wise by pixel values * * The comparison is channel- / pixel-wise. */ class MITKCORE_EXPORT MultiComponentImageDataComparisonFilter : public ImageToImageFilter { public: mitkClassMacro(MultiComponentImageDataComparisonFilter, ImageToImageFilter); itkSimpleNewMacro(Self); /*! /brief */ void SetTestImage(const Image *_arg); const Image *GetTestImage(); /*! /brief */ void SetValidImage(const Image *_arg); const Image *GetValidImage(); /*! /brief Specify the tolerance of the image data comparison /param Tolerance Default is 0.0f. */ itkSetMacro(Tolerance, double); itkGetMacro(Tolerance, double); /*! /brief */ void SetCompareFilterResult(CompareFilterResults *results); /*! /brief Get the detailed results of the comparison run * /sa CompareFilterResults */ CompareFilterResults *GetCompareFilterResult(); /*! /brief Get the result of the comparison * The method compares only the number of pixels with differences. It returns true if the amount * is under the specified threshold. To get the complete results, use the GetCompareResults method. - * Returns false also if the itk ComparisionImageFilter raises an exception during update. + * Returns false also if the itk ComparisonImageFilter raises an exception during update. * /param threshold Allowed percentage of pixels with differences (between 0.0...1.0) */ bool GetResult(double threshold = 0.0f); protected: MultiComponentImageDataComparisonFilter(); ~MultiComponentImageDataComparisonFilter() override; void GenerateData() override; template void CompareMultiComponentImage(const Image *testImage, const Image *validImage); double m_Tolerance; bool m_CompareResult; CompareFilterResults *m_CompareDetails; }; } // end namespace mitk #endif // MITKMULTICOMPONENTIMAGEDATACOMPARISONFILTER_H diff --git a/Modules/Core/include/mitkNodePredicateGeometry.h b/Modules/Core/include/mitkNodePredicateGeometry.h index fc33950b04..23c9c0e089 100644 --- a/Modules/Core/include/mitkNodePredicateGeometry.h +++ b/Modules/Core/include/mitkNodePredicateGeometry.h @@ -1,107 +1,107 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKNODEPREDICATEGEOMETRY_H_HEADER_INCLUDED_ #define MITKNODEPREDICATEGEOMETRY_H_HEADER_INCLUDED_ #include "mitkNodePredicateBase.h" #include "mitkBaseGeometry.h" #include "mitkTimeGeometry.h" namespace mitk { class BaseData; /**Documentation @brief Predicate that evaluates if the given DataNode's data object has the same geometry (in terms of spacing, origin, orientation) like the reference geometry. One can either check the whole time geometry of - the date node by defining a referenc time geometry or check against one given + the date node by defining a reference time geometry or check against one given reference base geometry. If the predicate should check against a base geometry, you can specify the timepoint of the data's time geometry that should be checked. If no timepoint is defined the predicate will evaluate the data geometry in the first timestep. Evaluates to "false" for unsupported or undefined data objects/geometries. One can specify the tolerance/precision of the check via SetCheckPrecision(), SetCheckCoordinatePrecision() or SetCheckDirectionPrecision(). @remark The default tolerance for coordinate checks is defined by NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION. The default tolerance for direction checks is defined by NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_DIRECTION_PRECISION. Both are not as strict as mitk::eps. The reason is, that, for the typical use of the node predicate, mitk::eps would be to pedantic, as we encounter often rounding differences/errors in real world data sets. For more details, see the documentation of the aforementioned constants. We have introduced two different precision values because differences are less impactful for coordinates than for direction values. Therefore we can relax coordinate checks more then direction checks. @ingroup DataStorage */ class MITKCORE_EXPORT NodePredicateGeometry : public NodePredicateBase { public: mitkClassMacro(NodePredicateGeometry, NodePredicateBase); mitkNewMacro1Param(NodePredicateGeometry, const TimeGeometry*); mitkNewMacro1Param(NodePredicateGeometry, const BaseGeometry*); mitkNewMacro2Param(NodePredicateGeometry, const BaseGeometry*, TimePointType); /** Sets CheckCoordinatePrecision and CheckDirectionPrecision to the passed value.*/ void SetCheckPrecision(mitk::ScalarType precision); itkSetMacro(CheckCoordinatePrecision, mitk::ScalarType); itkGetMacro(CheckCoordinatePrecision, mitk::ScalarType); itkSetMacro(CheckDirectionPrecision, mitk::ScalarType); itkGetMacro(CheckDirectionPrecision, mitk::ScalarType); ~NodePredicateGeometry() override; bool CheckNode(const mitk::DataNode *node) const override; protected: /**Constructor that is used configures the predicate to check the reference geometry against the first data timepoint.*/ NodePredicateGeometry(const BaseGeometry* refGeometry); /**Constructor allows to define the timepoint that should be evaluated against the reference.*/ NodePredicateGeometry(const BaseGeometry* refGeometry, TimePointType relevantTimePoint); /**Constructor that is used configures the predicate to check against the whole time geometry.*/ NodePredicateGeometry(const TimeGeometry* refGeometry); BaseGeometry::ConstPointer m_RefGeometry; TimeGeometry::ConstPointer m_RefTimeGeometry; TimePointType m_TimePoint; /**Indicates if m_TimePoint should be regarded or always the first timestep should be used.*/ bool m_UseTimePoint; /**Precision that should be used for the equal coordinate checks.*/ mitk::ScalarType m_CheckCoordinatePrecision; /**Precision that should be used for the equal direction checks.*/ mitk::ScalarType m_CheckDirectionPrecision; }; /** The default tolerance for the comparison of spatial/world coordinate equality. This tolerance is as strict as mitk::eps. The reason is, that, for the typical use of the node predicate, mitk::eps would be to pedantic. We often encounter floating point differences and practically it makes no difference e.g. if two images differ something like 0.0001 mm in size or spacing or origin.*/ constexpr double NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION = 1e-4; /** The default tolerance for the comparison of direction matrix equality. This tolerance is as strict as mitk::eps. The reason is, that, for the typical use of the node predicate, mitk::eps would be to pedantic. We often encounter floating point differences and practically it makes no difference e.g. if the elements of the direction/orientation matrix differ something like 0.000001.*/ constexpr double NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_DIRECTION_PRECISION = 1e-6; } // namespace mitk #endif /* MITKNodePredicateGeometry_H_HEADER_INCLUDED_ */ diff --git a/Modules/Core/include/mitkNodePredicateSubGeometry.h b/Modules/Core/include/mitkNodePredicateSubGeometry.h index 755d058dbf..eb7cb6f175 100644 --- a/Modules/Core/include/mitkNodePredicateSubGeometry.h +++ b/Modules/Core/include/mitkNodePredicateSubGeometry.h @@ -1,90 +1,90 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKNODEPREDICATESUBGEOMETRY_H_HEADER_INCLUDED_ #define MITKNODEPREDICATESUBGEOMETRY_H_HEADER_INCLUDED_ #include "mitkNodePredicateBase.h" #include "mitkBaseGeometry.h" #include "mitkTimeGeometry.h" namespace mitk { class BaseData; /**Documentation @brief Predicate that evaluates if the given DataNode's data object - has a geometry that is a sub geomety of the reference geometry. + has a geometry that is a sub geometry of the reference geometry. Sub geometry means that both geometries have the same voxel grid (same spacing, same axes, - orgin is on voxel grid), but the bounding box of the checked geometry is contained or equal + origin is on voxel grid), but the bounding box of the checked geometry is contained or equal to the bounding box of the reference geometry.\n One can either check the whole time geometry of - the data node by defining a referenc time geometry or check against one given2 + the data node by defining a reference time geometry or check against one given2 reference base geometry. If the predicate should check against a base geometry, you can specify the timepoint of the data's time geometry that should be checked. If no timepoint is defined the predicate will evaluate the data geometry in the first timestep. Evaluates to "false" for unsupported or undefined data objects/geometries. One can specify the tolerance/precision of the check via SetCheckPrecision(), SetCheckCoordinatePrecision() or SetCheckDirectionPrecision(). @remark The default tolerance for coordinate checks is defined by NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION. The default tolerance for direction checks is defined by NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_DIRECTION_PRECISION. Both are not as strict as mitk::eps. The reason is, that, for the typical use of the node predicate, mitk::eps would be to pedantic, as we encounter often rounding differences/errors in real world data sets. For more details, see the documentation of the aforementioned constants. We have introduced two different precision values because differences are less impactful for coordinates than for direction values. Therefore we can relax coordinate checks more then direction checks. @ingroup DataStorage */ class MITKCORE_EXPORT NodePredicateSubGeometry : public NodePredicateBase { public: mitkClassMacro(NodePredicateSubGeometry, NodePredicateBase); mitkNewMacro1Param(NodePredicateSubGeometry, const BaseGeometry*); mitkNewMacro2Param(NodePredicateSubGeometry, const BaseGeometry*, TimePointType); /** Sets CheckCoordinatePrecision and CheckDirectionPrecision to the passed value.*/ void SetCheckPrecision(mitk::ScalarType precision); itkSetMacro(CheckCoordinatePrecision, mitk::ScalarType); itkGetMacro(CheckCoordinatePrecision, mitk::ScalarType); itkSetMacro(CheckDirectionPrecision, mitk::ScalarType); itkGetMacro(CheckDirectionPrecision, mitk::ScalarType); ~NodePredicateSubGeometry() override; bool CheckNode(const mitk::DataNode *node) const override; protected: /**Constructor that is used configures the predicate to check the reference geometry against the first data timepoint.*/ NodePredicateSubGeometry(const BaseGeometry* refGeometry); /**Constructor allows to define the timepoint that should be evaluated against the reference.*/ NodePredicateSubGeometry(const BaseGeometry* refGeometry, TimePointType relevantTimePoint); BaseGeometry::ConstPointer m_RefGeometry; TimePointType m_TimePoint; /**Indicates if m_TimePoint should be regarded or always the first timestep should be used.*/ bool m_UseTimePoint; /**Precision that should be used for the equal coordinate checks.*/ mitk::ScalarType m_CheckCoordinatePrecision; /**Precision that should be used for the equal direction checks.*/ mitk::ScalarType m_CheckDirectionPrecision; }; } // namespace mitk #endif diff --git a/Modules/Core/include/mitkOperationActor.h b/Modules/Core/include/mitkOperationActor.h index 4dd66b28db..b3b5ee92d5 100644 --- a/Modules/Core/include/mitkOperationActor.h +++ b/Modules/Core/include/mitkOperationActor.h @@ -1,53 +1,53 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef OPERATIONACTOR_H_HEADER_INCLUDED_C16E28BD #define OPERATIONACTOR_H_HEADER_INCLUDED_C16E28BD #include #include /** Macro for checking the type of an operation */ #define mitkCheckOperationTypeMacro(OperationType, operation, newOperationName) \ \ OperationType *newOperationName = dynamic_cast(operation); \ \ if (newOperationName == nullptr) \ \ { \ - itkWarningMacro("Recieved wrong type of operation!"); \ + itkWarningMacro("Received wrong type of operation!"); \ return; \ } namespace mitk { class Operation; class OperationEvent; /** * \brief abstract class, that can be used by Undo to undo an operation. * * \ingroup Undo */ class MITKCORE_EXPORT OperationActor { public: itkTypeMacroNoParent(OperationActor) virtual ~OperationActor() { } virtual void ExecuteOperation(Operation *operation) = 0; }; } #endif /* OPERATIONACTOR_H_HEADER_INCLUDED_C16E28BD */ diff --git a/Modules/Core/include/mitkOperationEvent.h b/Modules/Core/include/mitkOperationEvent.h index 2d170eff24..97aaacbeae 100644 --- a/Modules/Core/include/mitkOperationEvent.h +++ b/Modules/Core/include/mitkOperationEvent.h @@ -1,201 +1,201 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef OPERATIONEVENT_H_HEADER_INCLUDED_C16E83FC #define OPERATIONEVENT_H_HEADER_INCLUDED_C16E83FC #include "mitkOperation.h" #include "mitkOperationActor.h" #include "mitkUndoModel.h" #include #include #include namespace mitk { //##Documentation //## @brief Represents an entry of the undo or redo stack. //## //## This basic entry includes a textual description of the item and a pair of IDs. Static //## member functions handle creation and incrementing of these IDs. //## //## The GroupEventID is intended for logical grouping of several related Operations. //## Currently this is used only by PointSetDataInteractor. How this is done and when to use //## GroupEventIDs is still undocumented. //## @ingroup Undo class MITKCORE_EXPORT UndoStackItem { public: UndoStackItem(std::string description = ""); virtual ~UndoStackItem(); //##Documentation //## @brief For combining operations in groups //## //## This ID is used in the undo mechanism. - //## For separation of the seperate operations + //## For separation of the separate operations //## If the GroupEventId of two OperationEvents is equal, //## then they share one group and will be undone in case of Undo(fine==false) static int GetCurrGroupEventId(); //##Documentation //## @brief For combining operations in Objects //## //## This ID is used in the Undo-Mechanism. - //## For separation of the seperate operations + //## For separation of the separate operations //## If the ObjectEventId of two OperationEvents is equal, //## then they share one Object and will be undone in all cases of Undo(true and false). - //## they shal not be seperated, because they were produced to realize one object-change. + //## they shal not be separated, because they were produced to realize one object-change. //## for example: OE_statechange and OE_addlastpoint static int GetCurrObjectEventId(); //##Documentation //## @brief Returns the GroupEventId for this object int GetGroupEventId(); //##Documentation //## @brief Returns the ObjectEventId for this object int GetObjectEventId(); //##Documentation //## @brief Returns the textual description of this object std::string GetDescription(); virtual void ReverseOperations(); virtual void ReverseAndExecute(); //##Documentation //## @brief Increases the current ObjectEventId //## For example if a button click generates operations the ObjectEventId has to be incremented to be able to undo //the // operations. //## Difference between ObjectEventId and GroupEventId: The ObjectEventId capsulates all operations caused by one // event. //## A GroupEventId capsulates several ObjectEventIds so that several operations caused by several events can be // undone with one Undo call. static void IncCurrObjectEventId(); //##Documentation //## @brief Increases the current GroupEventId //## For example if a button click generates operations the GroupEventId has to be incremented to be able to undo //the // operations. //## Difference between ObjectEventId and GroupEventId: The ObjectEventId capsulates all operations caused by one // event. //## A GroupEventId capsulates several ObjectEventIds so that several operations caused by several events can be // undone with one Undo call. static void IncCurrGroupEventId(); protected: //##Documentation - //## @brief true, if operation and undooperation have been swaped/changed + //## @brief true, if operation and undooperation have been swapped/changed bool m_Reversed; private: static int m_CurrObjectEventId; static int m_CurrGroupEventId; int m_ObjectEventId; int m_GroupEventId; std::string m_Description; UndoStackItem(UndoStackItem &); // hide copy constructor void operator=(const UndoStackItem &); // hide operator= }; //##Documentation //## @brief Represents a pair of operations: undo and the according redo. //## //## Additionally to the base class UndoStackItem, which only provides a description of an //## item, OperationEvent does the actual accounting of the undo/redo stack. This class //## holds two Operation objects (operation and its inverse operation) and the corresponding //## OperationActor. The operations may be swapped by the //## undo models, when an OperationEvent is moved from their undo to their redo //## stack or vice versa. //## //## Note, that memory management of operation and undooperation is done by this class. //## Memory of both objects is freed in the destructor. For this, the method IsValid() is needed which holds //## information of the state of m_Destination. In case the object referenced by m_Destination is already deleted, //## isValid() returns false. //## In more detail if the destination happens to be an itk::Object (often the case), OperationEvent is informed as //soon //## as the object is deleted - from this moment on the OperationEvent gets invalid. You should //## check this flag before you call anything on destination //## //## @ingroup Undo class MITKCORE_EXPORT OperationEvent : public UndoStackItem { public: //## @brief default constructor OperationEvent(OperationActor *destination, Operation *operation, Operation *undoOperation, std::string description = ""); //## @brief default destructor //## //## removes observers if destination is valid //## and frees memory referenced by m_Operation and m_UndoOperation ~OperationEvent() override; //## @brief Returns the operation Operation *GetOperation(); //## @brief Returns the destination of the operations OperationActor *GetDestination(); friend class UndoModel; //## @brief Swaps the two operations and sets a flag, //## that it has been swapped and doOp is undoOp and undoOp is doOp void ReverseOperations() override; //##reverses and executes both operations (used, when moved from undo to redo stack) void ReverseAndExecute() override; //## @brief returns true if the destination still is present //## and false if it already has been deleted virtual bool IsValid(); protected: void OnObjectDeleted(); private: // Has to be observed for itk::DeleteEvents. // When destination is deleted, this stack item is invalid! OperationActor *m_Destination; //## reference to the operation Operation *m_Operation; //## reference to the undo operation Operation *m_UndoOperation; //## hide copy constructor OperationEvent(OperationEvent &); //## hide operator= void operator=(const OperationEvent &); // observertag used to listen to m_Destination unsigned long m_DeleteTag; //## stores if destination is valid or already has been freed bool m_Invalid; }; } // namespace mitk #endif /* OPERATIONEVENT_H_HEADER_INCLUDED_C16E83FC */ diff --git a/Modules/Core/include/mitkPixelTypeList.h b/Modules/Core/include/mitkPixelTypeList.h index 1ecbad2720..f7d0982a17 100644 --- a/Modules/Core/include/mitkPixelTypeList.h +++ b/Modules/Core/include/mitkPixelTypeList.h @@ -1,182 +1,182 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include namespace mitk { struct EmptyType { }; template struct PixelTypeList; template struct PixelTypeList { typedef T0 head; typedef PixelTypeList tail; enum { length = tail::length + 1 }; }; template <> struct PixelTypeList { enum { length = 0 }; }; template struct PixelTypeLength { enum { value = TypeList::length }; }; template ::value == 0 // out of range flag > struct GetPixelType { typedef typename GetPixelType::type type; }; //"out of range" specialization template struct GetPixelType { // if OutOfRange is 'true' the 'type' is undefined // so we'll get a compile-time error }; //"element found" specialization template struct GetPixelType { // the index is equal to the recursion step // so the result type is the head of the Typlist and stop! typedef typename TypeList::head type; }; //////////////////////////////////////////////////////////// // run-time type switch template ::value)> struct PixelTypeSwitch; template struct PixelTypeSwitch { template bool operator()(int i, F &f) { if (i == Index) { return f.operator()::type>(); } else { PixelTypeSwitch next; return next(i, f); } } }; template struct PixelTypeSwitch { template bool operator()(int, F &) { throw std::out_of_range("Index out of range"); } }; template struct AccessItkImageFunctor { typedef void (*CallBack)(T1, T2, T3); AccessItkImageFunctor( X *cl, CallBack callBack, const mitk::Image *mitkImage, T1 t1 = T1(), T2 t2 = T2(), T3 t3 = T3()) : cl(cl), callBack(callBack), mitkImage(mitkImage), pixelType(mitkImage->GetPixelType()), t1(t1), t2(t2), t3(t3) { } template bool operator()() { if (pixelType != typeid(PixelType)) return false; if (mitkImage->GetDimension() != VDimension) return false; const_cast(mitkImage)->Update(); typedef itk::Image ImageType; typedef mitk::ImageToItk ImageToItkType; itk::SmartPointer imagetoitk = ImageToItkType::New(); imagetoitk->SetInput(mitkImage); imagetoitk->Update(); cl->*callBack(imagetoitk->GetOutput(), t1, t2, t3); return true; } private: X *cl; CallBack callBack; const mitk::Image *mitkImage; const mitk::PixelType &pixelType; T1 t1; T2 t2; T3 t3; }; } // namespace mitk diff --git a/Modules/Core/include/mitkPixelTypeTraits.h b/Modules/Core/include/mitkPixelTypeTraits.h index a5f190d33a..bf91d49adc 100644 --- a/Modules/Core/include/mitkPixelTypeTraits.h +++ b/Modules/Core/include/mitkPixelTypeTraits.h @@ -1,272 +1,272 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef PIXELTYPETRAITS_H #define PIXELTYPETRAITS_H #include #include #include #include #include #include /** \file mitkPixelTypeTraits.h * * The pixel type traits are in general used for compile time resolution of the component type and * the number of components for compound types like the ones in ItkImageType. * The default values are used to define the corresponding variable also for scalar types */ namespace itk { /** Forward declaration of the Variable Length Vector class from ITK */ template class VariableLengthVector; } #define MITK_PIXEL_COMPONENT_TYPE(type, ctype, name) \ template <> \ struct mitk::MapPixelComponentType \ { \ static const int value = ctype; \ } template <> \ std::string mitk::PixelComponentTypeToString() \ { \ return name; \ } namespace mitk { static const int PixelUserType = static_cast(itk::IOPixelEnum::MATRIX) + 1; static const int PixelComponentUserType = static_cast(itk::IOComponentEnum::DOUBLE) + 1; /** * Maps pixel component types (primitive types like int, short, double, etc. and custom * types) to and integer constant. Specialize this template for custom types by using the * #MITK_PIXEL_COMPONENT_TYPE macro. */ template struct MapPixelComponentType { static const itk::IOComponentEnum value = itk::ImageIOBase::MapPixelType::CType; }; /** \brief This is an implementation of a type trait to provide a compile-time check for PixelType used in the instantiation of an itk::Image */ template struct isPrimitiveType { static const bool value = false; }; /** \brief Provides a partial specialization for the \sa isPrimitiveType object */ #define DEFINE_TYPE_PRIMITIVE(_TYPEIN) \ template <> \ struct isPrimitiveType<_TYPEIN> \ { \ static const bool value = true; \ } /** \brief Partial specialization (unsigned char) for the isPrimitiveType object */ DEFINE_TYPE_PRIMITIVE(unsigned char); /** \brief Partial specialization (char) for the isPrimitiveType object */ DEFINE_TYPE_PRIMITIVE(char); /** \brief Partial specialization (signed char) for the isPrimitiveType object */ DEFINE_TYPE_PRIMITIVE(signed char); /** \brief Partial specialization (unsigned short) for the isPrimitiveType object */ DEFINE_TYPE_PRIMITIVE(unsigned short); /** \brief Partial specialization (short) for the isPrimitiveType object */ DEFINE_TYPE_PRIMITIVE(short); /** \brief Partial specialization (unsigned int) for the isPrimitiveType object */ DEFINE_TYPE_PRIMITIVE(unsigned int); /** \brief Partial specialization (int) for the isPrimitiveType object */ DEFINE_TYPE_PRIMITIVE(int); /** \brief Partial specialization (long int) for the isPrimitiveType object */ DEFINE_TYPE_PRIMITIVE(long int); /** \brief Partial specialization (long unsigned int) for the isPrimitiveType object */ DEFINE_TYPE_PRIMITIVE(long unsigned int); /** \brief Partial specialization (float) for the isPrimitiveType object */ DEFINE_TYPE_PRIMITIVE(float); /** \brief Partial specialization (double) for the isPrimitiveType object */ DEFINE_TYPE_PRIMITIVE(double); template struct ImageTypeTrait { typedef itk::Image ImageType; static const bool IsVectorImage = false; }; template struct ImageTypeTrait, VDimension> { typedef itk::VectorImage ImageType; static const bool IsVectorImage = true; }; template struct ImageTypeTrait { typedef T ImageType; static const bool IsVectorImage = false; }; template struct ImageTypeTrait, 0> { typedef itk::VectorImage ImageType; static const bool IsVectorImage = true; }; /** \brief Compile-time trait for resolving the ValueType from an ItkImageType */ template struct PixelTypeTrait { typedef T ValueType; }; /** \brief Partial specialization for the PixelTypeTrait * * Specialization for the false value. Used to define the value type for non-primitive pixel types */ template struct PixelTypeTrait { typedef typename T::ValueType ValueType; }; /** \brief Compile time resolving of the type of a component */ template struct GetComponentType { typedef typename PixelTypeTrait::value, T>::ValueType ComponentType; }; /** \brief Object for compile-time resolving of the number of components for given type. * * Default value for the component number is 1 */ template struct ComponentsTrait { static const size_t Size = 1; }; /** \brief Partial specialization for the ComponentsTraits in case of compound types */ template struct ComponentsTrait { static const size_t Size = T::ValueType::Length; }; typedef itk::IOPixelEnum itkIOPixelType; typedef itk::IOComponentEnum itkIOComponentType; /** \brief Object for compile-time translation of a composite pixel type into an itk::ImageIOBase::IOPixelType * information * * The default value of the IOCompositeType is the UNKNOWNPIXELTYPE, the default value will be used for all but the * types below with own partial specialization. The values of the IOCompositeType member in the specializations * correspond * to the values of the itk::ImageIOBase::IOPixelType enum values. */ template struct MapCompositePixelType { static const itkIOPixelType IOCompositeType = itkIOPixelType::UNKNOWNPIXELTYPE; }; //------------------------ // Partial template specialization for fixed-length types //------------------------ template struct MapCompositePixelType> { static const itkIOPixelType IOCompositeType = itkIOPixelType::RGB; }; template struct MapCompositePixelType> { static const itkIOPixelType IOCompositeType = itkIOPixelType::RGBA; }; template struct MapCompositePixelType> { static const itkIOPixelType IOCompositeType = itkIOPixelType::DIFFUSIONTENSOR3D; }; template struct MapCompositePixelType> { static const itkIOPixelType IOCompositeType = itkIOPixelType::VECTOR; }; //------------------------ // Partial template specialization for variable-length types //------------------------ template struct MapCompositePixelType> { static const itkIOPixelType IOCompositeType = itkIOPixelType::VECTOR; }; template struct MapCompositePixelType> { static const itkIOPixelType IOCompositeType = itkIOPixelType::COVARIANTVECTOR; }; template struct MapCompositePixelType> { static const itkIOPixelType IOCompositeType = itkIOPixelType::COVARIANTVECTOR; }; template struct MapCompositePixelType> { static const itkIOPixelType IOCompositeType = itkIOPixelType::MATRIX; }; /** \brief Object for compile-time translation of a pixel type into an itk::ImageIOBase::IOPixelType information * * The first template parameter is the pixel type to be translated, the second parameter determines the processing * way. For non-primitive types the first template parameter is passed to the MapCompositePixelType object to be * resolved there * for primitive types the value is set to SCALAR. * - * To initalize the flag correctly in compile-time use the \sa isPrimitiveType trait. + * To initialize the flag correctly in compile-time use the \sa isPrimitiveType trait. */ template struct MapPixelType { static const itkIOPixelType IOPixelType = MapCompositePixelType::IOCompositeType; static const itkIOComponentType IOComponentType = MapPixelComponentType::ComponentType>::value; }; /** \brief Partial specialization for setting the IOPixelType for primitive types to SCALAR */ template struct MapPixelType { static const itkIOPixelType IOPixelType = itkIOPixelType::SCALAR; static const itkIOComponentType IOComponentType = MapPixelComponentType::value; }; } // end namespace mitk #endif // PIXELTYPETRAITS_H diff --git a/Modules/Core/include/mitkPlaneGeometryDataVtkMapper3D.h b/Modules/Core/include/mitkPlaneGeometryDataVtkMapper3D.h index fa7ee89fcd..1e4d578a9e 100644 --- a/Modules/Core/include/mitkPlaneGeometryDataVtkMapper3D.h +++ b/Modules/Core/include/mitkPlaneGeometryDataVtkMapper3D.h @@ -1,215 +1,215 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKGEOMETRY2DDATAVTKMAPPER3D_H_HEADER_INCLUDED_C196C71F #define MITKGEOMETRY2DDATAVTKMAPPER3D_H_HEADER_INCLUDED_C196C71F #include "mitkDataStorage.h" #include "mitkPlaneGeometryDataToSurfaceFilter.h" #include "mitkVtkMapper.h" #include "mitkWeakPointer.h" #include #include #include class vtkActor; class vtkPolyDataMapper; class vtkAssembly; class vtkFeatureEdges; class vtkTubeFilter; class vtkTransformPolyDataFilter; class vtkHedgeHog; namespace mitk { class PlaneGeometryData; class BaseRenderer; class ImageVtkMapper2D; class DataStorage; class PlaneGeometryDataVtkMapper3D; /** \deprecatedSince{2014_10} This class is deprecated. Please use PlaneGeometryDataVTKMapper3D instead. */ DEPRECATED(typedef PlaneGeometryDataVtkMapper3D Geometry2DDataVtkMapper3D); /** * \brief Vtk-based mapper to display a PlaneGeometry in a 3D window * \ingroup Mapper * * Uses a PlaneGeometryDataToSurfaceFilter object to create a vtkPolyData representation of a given PlaneGeometry * instance. * PlaneGeometry may either contain a common flat plane or a curved plane (ThinPlateSplineCurvedGeometry). * * The vtkPolyData object is then decorated by a colored tube on the edges and by image textures if possible * (currently this requires that there is a 2D render window rendering the same geometry as this mapper). * * Properties that influence rendering are: * * - \b "draw edges": (Bool) Toggle display of the tubed frame * - \b "color": (ColorProperty) Color of the tubed frame. * - \b "xresolution": (FloatProperty) Resolution (=number of tiles) in x direction. Only relevant for * ThinPlateSplineCurvedGeometry * - \b "yresolution": (FloatProperty) Resolution (=number of tiles) in y direction. Only relevant for * ThinPlateSplineCurvedGeometry * - \b "draw normals 3D": (BoolProperty) If true, a vtkHedgeHog is used to display normals for the generated surface * object. Useful to distinguish front and back of a plane. Hedgehogs are colored according to "front color" and "back * color" * - \b "color two sides": (BoolProperty) If true, front and back side of the plane are colored differently ("front * color" and "back color") * - \b "invert normals": (BoolProperty) Inverts front/back for display. * - \b "front color": (ColorProperty) Color for front side of the plane * - \b "back color": (ColorProperty) Color for back side of the plane * - \b "material.representation": (BoolProperty) Choose the representation to draw the mesh in (Surface, Wireframe, * Point Cloud) * - \b "surfacegeometry": TODO: Add documentation * - \b "LookupTable": (LookupTableProperty) Set the lookuptable to render with. * * Note: The following properties are set for each image individually, and thus, also influence the rendering of this * mapper: * * - \b "texture interpolation": (BoolProperty) Turn on/off the texture interpolation of each image * - \b "use color": (BoolProperty) Decide whether we want to use the color property or a lookuptable. * - \b "binary": (BoolProperty) Binary image handling: Color the value=1.0 with the color property and make the * background (value=0.0) of the image translucent. * - \b "layer": (IntProperty) Controls what image is considered "on top" of another. In the case that two should * inhabit the same space, higher layer occludes lower layer. * - \b "opacity": (FloatProperty) Set the opacity for each rendered image. * - \b "color": (FloatProperty) Set the color for each rendered image. */ class MITKCORE_EXPORT PlaneGeometryDataVtkMapper3D : public VtkMapper { public: mitkClassMacro(PlaneGeometryDataVtkMapper3D, VtkMapper); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * Overloaded since the displayed color-frame of the image mustn't be * transformed after generation of poly data, but before (vertex coordinates * only) */ vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) override; void UpdateVtkTransform(mitk::BaseRenderer *renderer) override; /** * \brief Get the PlaneGeometryData to map */ virtual const PlaneGeometryData *GetInput(); /** * \brief All images found when traversing the (sub-) tree starting at * \a iterator which are resliced by an ImageVtkMapper2D will be mapped. * This method is used to set the data storage to traverse. This offers * the possibility to use this mapper for other data storages (not only * the default data storage). */ virtual void SetDataStorageForTexture(mitk::DataStorage *storage); protected: typedef std::multimap LayerSortedActorList; PlaneGeometryDataVtkMapper3D(); ~PlaneGeometryDataVtkMapper3D() override; void GenerateDataForRenderer(BaseRenderer *renderer) override; void ProcessNode(DataNode *node, BaseRenderer *renderer, Surface *surface, LayerSortedActorList &layerSortedActors); void ImageMapperDeletedCallback(itk::Object *caller, const itk::EventObject &event); /** \brief general PropAssembly to hold the entire scene */ vtkAssembly *m_Prop3DAssembly; /** \brief PropAssembly to hold the planes */ vtkAssembly *m_ImageAssembly; PlaneGeometryDataToSurfaceFilter::Pointer m_SurfaceCreator; BoundingBox::Pointer m_SurfaceCreatorBoundingBox; BoundingBox::PointsContainer::Pointer m_SurfaceCreatorPointsContainer; /** \brief Edge extractor for tube-shaped frame */ vtkFeatureEdges *m_Edges; /** \brief Filter to apply object transform to the extracted edges */ vtkTransformPolyDataFilter *m_EdgeTransformer; /** \brief Source to create the tube-shaped frame */ vtkTubeFilter *m_EdgeTuber; /** \brief Mapper for the tube-shaped frame */ vtkPolyDataMapper *m_EdgeMapper; /** \brief Actor for the tube-shaped frame */ vtkActor *m_EdgeActor; /** \brief Mapper for black plane background */ vtkPolyDataMapper *m_BackgroundMapper; /** \brief Actor for black plane background */ vtkActor *m_BackgroundActor; - /** \brief Transforms the suface before applying the glyph filter */ + /** \brief Transforms the surface before applying the glyph filter */ vtkTransformPolyDataFilter *m_NormalsTransformer; /** \brief Mapper for normals representation (thin lines) */ vtkPolyDataMapper *m_FrontNormalsMapper; vtkPolyDataMapper *m_BackNormalsMapper; /** \brief Generates lines for surface normals */ vtkHedgeHog *m_FrontHedgeHog; vtkHedgeHog *m_BackHedgeHog; /** \brief Actor to hold the normals arrows */ vtkActor *m_FrontNormalsActor; vtkActor *m_BackNormalsActor; /** Cleans the polyline in order to avoid phantom boundaries */ vtkCleanPolyData *m_Cleaner; /** Internal flag, if actors for normals are already added to m_Prop3DAssembly*/ bool m_NormalsActorAdded; - /** \brief The DataStorage defines which part of the data tree is traversed for renderering. */ + /** \brief The DataStorage defines which part of the data tree is traversed for rendering. */ mitk::WeakPointer m_DataStorage; class MITKCORE_EXPORT ActorInfo { public: vtkActor *m_Actor; // we do not need a smart-pointer, because we delete our // connection, when the referenced mapper is destroyed itk::Object *m_Sender; unsigned long m_ObserverID; void Initialize(vtkActor *actor, itk::Object *sender, itk::Command *command); ActorInfo(); ~ActorInfo(); }; /** \brief List holding the vtkActor to map the image into 3D for each * ImageMapper */ typedef std::map ActorList; ActorList m_ImageActors; - // responsiblity to remove the observer upon its destruction + // responsibility to remove the observer upon its destruction typedef itk::MemberCommand MemberCommandType; MemberCommandType::Pointer m_ImageMapperDeletedCommand; }; } // namespace mitk #endif /* MITKGEOMETRY2DDATAVTKMAPPER3D_H_HEADER_INCLUDED_C196C71F */ diff --git a/Modules/Core/include/mitkPointSet.h b/Modules/Core/include/mitkPointSet.h index d58c5bfe77..77b0b744de 100755 --- a/Modules/Core/include/mitkPointSet.h +++ b/Modules/Core/include/mitkPointSet.h @@ -1,348 +1,348 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKPointSet_H_HEADER_INCLUDED #define MITKPointSet_H_HEADER_INCLUDED #include "mitkBaseData.h" #include #include namespace mitk { /** * \brief Data structure which stores a set of points. * * 3D points are grouped within a point set; for time resolved usage, one point * set is created and maintained per time step. A point entry consists of the * point coordinates and point data. * * The point data includes a point ID (unique identifier to address this point * within the point set), the selection state of the point and the type of * the point. * * For further information about different point types see * mitk::PointSpecificationType in mitkVector.h. * * Inserting a point is accompanied by an event, containing an index. The new * point is inserted into the list at the specified position. At the same time * an internal ID is generated and stored for the point. Points at specific time * steps are accessed by specifying the time step number (which defaults to 0). * * The points of itk::PointSet stores the points in a pointContainer * (MapContainer). The points are best accessed by using a ConstIterator (as * defined in MapContainer); avoid access via index. * * The class internally uses an itk::Mesh for each time step. * * \section mitkPointSetDisplayOptions * * The default mappers for this data structure are mitk::PointSetGLMapper2D and * mitk::PointSetVtkMapper3D. See these classes for display options which can * can be set via properties. * * \section Events * * PointSet issues the following events, for which observers can register * (the below events are grouped into a class hierarchy as indicated by - * identation level; e.g. PointSetSizeChangeEvent comprises PointSetAddEvent + * indentation level; e.g. PointSetSizeChangeEvent comprises PointSetAddEvent * and PointSetRemoveEvent): * * * PointSetEvent subsumes all PointSet events * PointSetMoveEvent issued when a point of the PointSet is moved * PointSetSizeChangeEvent subsumes add and remove events * PointSetAddEvent issued when a point is added to the PointSet * PointSetRemoveEvent issued when a point is removed from the PointSet * * \ingroup PSIO * \ingroup Data */ class MITKCORE_EXPORT PointSet : public BaseData { public: mitkClassMacro(PointSet, BaseData); itkFactorylessNewMacro(Self); itkCloneMacro(Self); typedef mitk::ScalarType CoordinateType; typedef mitk::ScalarType InterpolationWeightType; static const unsigned int PointDimension = 3; static const unsigned int MaxTopologicalDimension = 3; /** * \brief struct for data of a point */ struct MITKCORE_EXPORT PointDataType { unsigned int id; // to give the point a special ID bool selected; // information about if the point is selected mitk::PointSpecificationType pointSpec; // specifies the type of the point bool operator==(const PointDataType &other) const; }; /** * \brief cellDataType, that stores all indexes of the lines, that are * selected e.g.: points A,B and C.Between A and B there is a line with * index 0. If vector of cellData contains 1 and 2, then the lines between * B and C and C and A is selected. */ typedef std::vector SelectedLinesType; typedef SelectedLinesType::iterator SelectedLinesIter; struct CellDataType { // used to set the whole cell on selected bool selected; // indexes of selected lines. 0 is between pointId 0 and 1 SelectedLinesType selectedLines; // is the polygon already finished and closed bool closed; }; typedef itk::DefaultDynamicMeshTraits MeshTraits; typedef itk::Mesh MeshType; typedef MeshType DataType; typedef Point3D PointType; typedef DataType::PointIdentifier PointIdentifier; typedef DataType::PointsContainer PointsContainer; typedef DataType::PointsContainerIterator PointsIterator; typedef DataType::PointsContainer::ConstIterator PointsConstIterator; typedef DataType::PointDataContainer PointDataContainer; typedef DataType::PointDataContainerIterator PointDataIterator; typedef DataType::PointDataContainerIterator PointDataConstIterator; void Expand(unsigned int timeSteps) override; /** \brief executes the given Operation */ void ExecuteOperation(Operation *operation) override; /** \brief returns the current size of the point-list */ virtual int GetSize(unsigned int t = 0) const; virtual unsigned int GetPointSetSeriesSize() const; /** \brief returns the pointset */ virtual DataType::Pointer GetPointSet(int t = 0) const; PointsIterator Begin(int t = 0); PointsConstIterator Begin(int t = 0) const; PointsIterator End(int t = 0); PointsConstIterator End(int t = 0) const; /** * \brief Get an iterator to the max ID element if existent. Return End() otherwise. */ PointsIterator GetMaxId(int t = 0); /** * \brief Get the point with ID id in world coordinates * * check if the ID exists. If it doesn't exist, then return 0,0,0 */ PointType GetPoint(PointIdentifier id, int t = 0) const; /** * \brief Get the point with ID id in world coordinates * * If a point exists for the ID id, the point is returned in the parameter point * and the method returns true. If the ID does not exist, the method returns false */ bool GetPointIfExists(PointIdentifier id, PointType *point, int t = 0) const; /** * \brief Set the given point in world coordinate system into the itkPointSet. */ void SetPoint(PointIdentifier id, PointType point, int t = 0); /** * \brief Set the given point in world coordinate system with the given PointSpecificationType */ void SetPoint(PointIdentifier id, PointType point, PointSpecificationType spec, int t = 0); /** * \brief Set the given point in world coordinate system into the itkPointSet. */ void InsertPoint(PointIdentifier id, PointType point, int t = 0); /** * \brief Set the given point in world coordinate system with given PointSpecificationType */ void InsertPoint(PointIdentifier id, PointType point, PointSpecificationType spec, int t); /** * \brief Insert the given point in world coordinate system with incremented max id at time step t. */ PointIdentifier InsertPoint(PointType point, int t = 0); /** * \brief Remove point with given id at timestep t, if existent */ bool RemovePointIfExists(PointIdentifier id, int t = 0); /** * \brief Remove max id point at timestep t and return iterator to precedent point */ PointsIterator RemovePointAtEnd(int t = 0); /** * \brief Swap a point at the given position (id) with the upper point (moveUpwards=true) or with the lower point * (moveUpwards=false). * If upper or lower index does not exist false is returned, if swap was successful true. */ bool SwapPointPosition(PointIdentifier id, bool moveUpwards, int t = 0); /** * \brief searches a selected point and returns the id of that point. * If no point is found, then -1 is returned */ virtual int SearchSelectedPoint(int t = 0) const; /** \brief returns true if a point exists at this position */ virtual bool IndexExists(int position, int t = 0) const; /** \brief to get the state selected/unselected of the point on the * position */ virtual bool GetSelectInfo(int position, int t = 0) const; virtual void SetSelectInfo(int position, bool selected, int t = 0); /** \brief to get the type of the point at the position and the moment */ virtual PointSpecificationType GetSpecificationTypeInfo(int position, int t) const; /** \brief returns the number of selected points */ virtual int GetNumberOfSelected(int t = 0) const; /** * \brief searches a point in the list == point +/- distance * * \param point is in world coordinates. * \param distance is in mm. * \param t * returns -1 if no point is found * or the position in the list of the first match */ int SearchPoint(Point3D point, ScalarType distance, int t = 0) const; bool IsEmptyTimeStep(unsigned int t) const override; // virtual methods, that need to be implemented void UpdateOutputInformation() override; void SetRequestedRegionToLargestPossibleRegion() override; bool RequestedRegionIsOutsideOfTheBufferedRegion() override; bool VerifyRequestedRegion() override; void SetRequestedRegion(const itk::DataObject *data) override; // Method for subclasses virtual void OnPointSetChange(){}; protected: mitkCloneMacro(Self); PointSet(); PointSet(const PointSet &other); ~PointSet() override; void PrintSelf(std::ostream &os, itk::Indent indent) const override; ///< print content of the object to os void ClearData() override; void InitializeEmpty() override; /** \brief swaps point coordinates and point data of the points with identifiers id1 and id2 */ bool SwapPointContents(PointIdentifier id1, PointIdentifier id2, int t = 0); typedef std::vector PointSetSeries; PointSetSeries m_PointSetSeries; DataType::PointsContainer::Pointer m_EmptyPointsContainer; /** * @brief flag to indicate the right time to call SetBounds **/ bool m_CalculateBoundingBox; }; /** - * @brief Equal A function comparing two pointsets for beeing identical. + * @brief Equal A function comparing two pointsets for being identical. * @warning This method is deprecated and will not be available in the future. Use the \a bool mitk::Equal(const * mitk::PointSet& p1, const mitk::PointSet& p2) instead. * * @ingroup MITKTestingAPI * * The function compares the Geometry, the size and all points element-wise. - * The parameter eps is a tolarence value for all methods which are internally used for comparion. + * The parameter eps is a tolarence value for all methods which are internally used for comparison. * * @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. * @param checkGeometry if comparing point sets loaded from a file, the geometries might be different and must not be * compared. In all other cases, you should compare the geometries. * @return True, if all subsequent comparisons are true, false otherwise */ DEPRECATED(MITKCORE_EXPORT bool Equal(const mitk::PointSet *leftHandSide, const mitk::PointSet *rightHandSide, mitk::ScalarType eps, bool verbose, bool checkGeometry = true)); /** - * @brief Equal A function comparing two pointsets for beeing identical. + * @brief Equal A function comparing two pointsets for being identical. * * @ingroup MITKTestingAPI * * The function compares the Geometry, the size and all points element-wise. - * The parameter eps is a tolarence value for all methods which are internally used for comparion. + * The parameter eps is a tolarence value for all methods which are internally used for comparison. * * @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. * @param checkGeometry if comparing point sets loaded from a file, the geometries might be different and must not be * compared. In all other cases, you should compare the geometries. * @return True, if all subsequent comparisons are true, false otherwise */ MITKCORE_EXPORT bool Equal(const mitk::PointSet &leftHandSide, const mitk::PointSet &rightHandSide, mitk::ScalarType eps, bool verbose, bool checkGeometry = true); itkEventMacroDeclaration(PointSetEvent, itk::AnyEvent); itkEventMacroDeclaration(PointSetMoveEvent, PointSetEvent); itkEventMacroDeclaration(PointSetSizeChangeEvent, PointSetEvent); itkEventMacroDeclaration(PointSetAddEvent, PointSetSizeChangeEvent); itkEventMacroDeclaration(PointSetRemoveEvent, PointSetSizeChangeEvent); itkEventMacroDeclaration(PointSetExtendTimeRangeEvent, PointSetEvent); } // namespace mitk #endif /* MITKPointSet_H_HEADER_INCLUDED */ diff --git a/Modules/Core/include/mitkPointSetDataInteractor.h b/Modules/Core/include/mitkPointSetDataInteractor.h index 98e156d2b2..9726e47a32 100644 --- a/Modules/Core/include/mitkPointSetDataInteractor.h +++ b/Modules/Core/include/mitkPointSetDataInteractor.h @@ -1,186 +1,186 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkPointSetDataInteractor_h_ #define mitkPointSetDataInteractor_h_ #include "itkObject.h" #include "itkObjectFactory.h" #include "itkSmartPointer.h" #include "mitkCommon.h" #include "mitkDataInteractor.h" #include #include namespace mitk { /** * Class PointSetDataInteractor * \brief Implementation of the PointSetInteractor * * Interactor operates on a point set and supports to: * - add points * - remove points * - move single points * - move complete pointset * - select/unselect a point * * in 2d and 3d render windows. * * \warning If this Interactor is assigned (SetDataNode) an empty mitk::DataNode it creates a point set, * changing the point set of the assigned mitk::DataNode after this assignment will cause the mitk::PointSetDataInteractor * to not work properly. So the usage has follow this general scheme: * * \code // Set up interactor m_CurrentInteractor = mitk::PointSetDataInteractor::New(); m_CurrentInteractor->LoadStateMachine("PointSet.xml"); m_CurrentInteractor->SetEventConfig("PointSetConfig.xml"); //Create new PointSet which will receive the interaction input m_TestPointSet = mitk::PointSet::New(); // Add the point set to the mitk::DataNode *before* the DataNode is added to the mitk::PointSetDataInteractor m_TestPointSetNode->SetData(m_TestPointSet); // finally add the mitk::DataNode (which already is added to the mitk::DataStorage) to the mitk::PointSetDataInteractor m_CurrentInteractor->SetDataNode(m_TestPointSetNode); \endcode * * */ // Inherit from DataInteratcor, this provides functionality of a state machine and configurable inputs. class MITKCORE_EXPORT PointSetDataInteractor : public DataInteractor { public: mitkClassMacro(PointSetDataInteractor, DataInteractor); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * Sets the maximum distance that is accepted when looking for a point at a certain position using the * GetPointIndexByPosition function. */ void SetAccuracy(float accuracy); /** * @brief SetMaxPoints Sets the maximal number of points for the pointset - * Default ist zero, which result in infinite number of allowed points + * Default is zero, which result in infinite number of allowed points * @param maxNumber */ void SetMaxPoints(unsigned int maxNumber = 0); protected: PointSetDataInteractor(); ~PointSetDataInteractor() override; /** * Here actions strings from the loaded state machine pattern are mapped to functions of * the DataInteractor. These functions are called when an action from the state machine pattern is executed. */ void ConnectActionsAndFunctions() override; /** * This function is called when a DataNode has been set/changed. * It is used to initialize the DataNode, e.g. if no PointSet exists yet it is created * and added to the DataNode. */ void DataNodeChanged() override; /** * \brief Return index in PointSet of the point that is within given accuracy to the provided position. * * Assumes that the DataNode contains a PointSet, if so it iterates over all points * in the DataNode to check if it contains a point near the pointer position. * If a point is found its index-position is returned, else -1 is returned. */ virtual int GetPointIndexByPosition(Point3D position, unsigned int time = 0, float accuracy = -1); virtual bool CheckSelection(const InteractionEvent *interactionEvent); /** Adds a point at the given coordinates. * Every time a point is added it is also checked if the maximal number of points is reached, * and if so an InternalEvent with the signal name "MaxNumberOfPoints" is triggered. */ virtual void AddPoint(StateMachineAction *, InteractionEvent *event); /** Removes point that is selected */ virtual void RemovePoint(StateMachineAction *, InteractionEvent *interactionEvent); /** * Checks if new point is close enough to an old one, * if so, trigger the ClosedContour signal which can be caught by the state machine. */ virtual void IsClosedContour(StateMachineAction *, InteractionEvent *); /** - * Moves the currently selected point to the new coodinates. + * Moves the currently selected point to the new coordinates. */ virtual void MovePoint(StateMachineAction *, InteractionEvent *); /** * Initializes the movement, stores starting position. */ virtual void InitMove(StateMachineAction *, InteractionEvent *interactionEvent); /** * Is called when a movement is finished, changes back to regular color. */ virtual void FinishMove(StateMachineAction *, InteractionEvent *); /** * Selects a point from the PointSet as currently active. */ virtual void SelectPoint(StateMachineAction *, InteractionEvent *); /** * Unselects a point at the given coordinate. */ virtual void UnSelectPointAtPosition(StateMachineAction *, InteractionEvent *); /** * Unselects all points out of reach. */ virtual void UnSelectAll(StateMachineAction *, InteractionEvent *); /** * @brief UpdatePointSet Updates the member variable that holds the point set, evaluating the time step of the * sender. */ virtual void UpdatePointSet(StateMachineAction *stateMachineAction, InteractionEvent *); /** * Calls for inactivation of the DataInteractor */ virtual void Abort(StateMachineAction *, InteractionEvent *); /** \brief to calculate a direction vector from last point and actual * point */ Point3D m_LastPoint; /** \brief summ-vector for Movement */ Vector3D m_SumVec; // DATA PointSet::Pointer m_PointSet; int m_MaxNumberOfPoints; // maximum of allowed number of points float m_SelectionAccuracy; // accuracy that's needed to select a point // FUNCTIONS void UnselectAll(unsigned int timeStep, ScalarType timeInMs); void SelectPoint(int position, unsigned int timeStep, ScalarType timeInMS); }; } #endif diff --git a/Modules/Core/include/mitkPointSetSource.h b/Modules/Core/include/mitkPointSetSource.h index a393f8e6db..7068e54079 100644 --- a/Modules/Core/include/mitkPointSetSource.h +++ b/Modules/Core/include/mitkPointSetSource.h @@ -1,67 +1,67 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_POINT_SET_SOURCE_H #define _MITK_POINT_SET_SOURCE_H #include "mitkBaseDataSource.h" #include "mitkPointSet.h" namespace mitk { /** * @brief Superclass of all classes generating point sets (instances of class * mitk::PointSet) as output. * * In itk and vtk the generated result of a ProcessObject is only guaranteed * to be up-to-date, when Update() of the ProcessObject or the generated * DataObject is called immediately before access of the data stored in the * DataObject. * @ingroup Process */ class MITKCORE_EXPORT PointSetSource : public BaseDataSource { public: mitkClassMacro(PointSetSource, BaseDataSource); itkFactorylessNewMacro(Self); itkCloneMacro(Self); typedef PointSet OutputType; typedef OutputType::Pointer OutputTypePointer; mitkBaseDataSourceGetOutputDeclarations /** * Allocates a new output object and returns it. Currently the * index idx is not evaluated. * @param idx the index of the output for which an object should be created * @returns the new object */ itk::DataObject::Pointer MakeOutput(DataObjectPointerArraySizeType idx) override; /** * This is a default implementation to make sure we have something. - * Once all the subclasses of ProcessObject provide an appopriate + * Once all the subclasses of ProcessObject provide an appropriate * MakeOutput(), then ProcessObject::MakeOutput() can be made pure * virtual. */ itk::DataObject::Pointer MakeOutput(const DataObjectIdentifierType &name) override; protected: PointSetSource(); ~PointSetSource() override; }; } #endif // #define _MITK_POINT_SET_SOURCE_H diff --git a/Modules/Core/include/mitkPointSetVtkMapper2D.h b/Modules/Core/include/mitkPointSetVtkMapper2D.h index def499c1c9..267cf0b204 100644 --- a/Modules/Core/include/mitkPointSetVtkMapper2D.h +++ b/Modules/Core/include/mitkPointSetVtkMapper2D.h @@ -1,239 +1,239 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkPointSetVtkMapper2D_h #define mitkPointSetVtkMapper2D_h #include "mitkBaseRenderer.h" #include "mitkLocalStorageHandler.h" #include "mitkVtkMapper.h" #include #include // VTK #include class vtkActor; class vtkPropAssembly; class vtkPolyData; class vtkPolyDataMapper; class vtkGlyphSource2D; class vtkGlyph3D; class vtkFloatArray; class vtkCellArray; namespace mitk { class PointSet; /** * @brief Vtk-based 2D mapper for PointSet * * Due to the need of different colors for selected * and unselected points and the facts, that we also have a contour and * labels for the points, the vtk structure is build up the following way: * * We have three PolyData, one selected, and one unselected and one * for a contour between the points. Each one is connected to an own * PolyDataMapper and an Actor. The different color for the unselected and * selected state and for the contour is read from properties. * * This mapper has several additional functionalities, such as rendering * a contour between points, calculating and displaying distances or angles * between points. * * @section mitkPointSetVtkMapper2D_point_rep Point Representation * * The points are displayed as small glyphs of configurable shape * (see property "PointSet.2D.shape"). The size of these glyphs * is given in world units. That means, the size or shape of those * glyphs is independent of the BaseGeometry object that you assign * to the PointSet. As for all other objects, _positions_ of points * will be transformed into the world via the Geometry's index-to-world * transform. * * Then the three Actors are combined inside a vtkPropAssembly and this * object is returned in GetProp() and so hooked up into the rendering * pipeline. * * @section mitkPointSetVtkMapper2D_propertires Applicable Properties * * Properties that can be set for point sets and influence the PointSetVTKMapper2D are: * * - \b "line width": (IntProperty 2) // line width of the line from one point to another * - \b "point line width": (IntProperty 1) // line width of the cross marking a point * - \b "point 2D size": (FloatProperty 6) // size of the glyph marking a point (diameter, in world * units!) * - \b "show contour": (BoolProperty false) // enable contour rendering between points (lines) * - \b "close contour": (BoolProperty false) // if enabled, the open strip is closed (first point * connected with last point) * - \b "show points": (BoolProperty true) // show or hide points * - \b "show distances": (BoolProperty false) // show or hide distance measure * - \b "distance decimal digits": (IntProperty 2) // set the number of decimal digits to be shown when * rendering the distance information * - \b "show angles": (BoolProperty false) // show or hide angle measurement * - \b "show distant lines": (BoolProperty false) // show the line between to points from a distant view * (equals "always on top" option) * - \b "layer": (IntProperty 1) // default is drawing pointset above images (they have a * default layer of 0) * - \b "PointSet.2D.shape" (EnumerationProperty Cross) // provides different shapes marking a point * 0 = "None", 1 = "Vertex", 2 = "Dash", 3 = "Cross", 4 = "ThickCross", 5 = "Triangle", 6 = "Square", 7 = * "Circle", * 8 = "Diamond", 9 = "Arrow", 10 = "ThickArrow", 11 = "HookedArrow", 12 = "Cross" * - \b "PointSet.2D.fill shape": (BoolProperty false) // fill or do not fill the glyph shape * - \b "Pointset.2D.distance to plane": (FloatProperty 4.0) //In the 2D render window, points are rendered which lie * within a certain distance * to the current plane. They are projected on the current * plane and scaled according to their distance. * Point markers appear smaller as the plane moves away * from * their true location. * The distance threshold can be adjusted by this float * property, which ables the user to delineate the points * that lie exactly on the plane. (+/- rounding error) * * Other Properties used here but not defined in this class: * * - \b "selectedcolor": (ColorProperty (1.0f, 0.0f, 0.0f)) // default color of the selected pointset e.g. the * current * point is red * - \b "contourcolor" : (ColorProperty (1.0f, 0.0f, 0.0f)) // default color for the contour is red * - \b "color": (ColorProperty (1.0f, 1.0f, 0.0f)) // default color of the (unselected) pointset is yellow * - \b "opacity": (FloatProperty 1.0) // opacity of point set, contours * - \b "label": (StringProperty nullptr) // a label can be defined for each point, which is rendered in proximity * to * the point * * @ingroup Mapper */ class MITKCORE_EXPORT PointSetVtkMapper2D : public VtkMapper { public: mitkClassMacro(PointSetVtkMapper2D, VtkMapper); itkFactorylessNewMacro(Self); itkCloneMacro(Self); virtual const mitk::PointSet *GetInput() const; /** \brief returns the a prop assembly */ vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) override; /** \brief set the default properties for this mapper */ static void SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); /** \brief Internal class holding the mapper, actor, etc. for each of the 3 2D render windows */ class LocalStorage : public mitk::Mapper::BaseLocalStorage { public: /* constructor */ LocalStorage(); /* destructor */ ~LocalStorage() override; // points vtkSmartPointer m_UnselectedPoints; vtkSmartPointer m_SelectedPoints; vtkSmartPointer m_ContourPoints; // scales vtkSmartPointer m_UnselectedScales; vtkSmartPointer m_SelectedScales; // distances vtkSmartPointer m_DistancesBetweenPoints; // lines vtkSmartPointer m_ContourLines; // glyph source (provides different shapes for the points) vtkSmartPointer m_UnselectedGlyphSource2D; vtkSmartPointer m_SelectedGlyphSource2D; // glyph vtkSmartPointer m_UnselectedGlyph3D; vtkSmartPointer m_SelectedGlyph3D; // polydata vtkSmartPointer m_VtkUnselectedPointListPolyData; vtkSmartPointer m_VtkSelectedPointListPolyData; vtkSmartPointer m_VtkContourPolyData; // actor vtkSmartPointer m_UnselectedActor; vtkSmartPointer m_SelectedActor; vtkSmartPointer m_ContourActor; vtkSmartPointer m_VtkTextActor; std::vector> m_VtkTextLabelActors; std::vector> m_VtkTextDistanceActors; std::vector> m_VtkTextAngleActors; // mappers vtkSmartPointer m_VtkUnselectedPolyDataMapper; vtkSmartPointer m_VtkSelectedPolyDataMapper; vtkSmartPointer m_VtkContourPolyDataMapper; // propassembly vtkSmartPointer m_PropAssembly; }; /** \brief The LocalStorageHandler holds all (three) LocalStorages for the three 2D render windows. */ mitk::LocalStorageHandler m_LSH; protected: /* constructor */ PointSetVtkMapper2D(); /* destructor */ ~PointSetVtkMapper2D() override; /* \brief Applies the color and opacity properties and calls CreateVTKRenderObjects */ void GenerateDataForRenderer(mitk::BaseRenderer *renderer) override; /* \brief Called in mitk::Mapper::Update * If TimeGeometry or time step is not valid of point set: reset mapper so that nothing is - * displayed e.g. toggle visiblity of the propassembly */ + * displayed e.g. toggle visibility of the propassembly */ void ResetMapper(BaseRenderer *renderer) override; /* \brief Fills the vtk objects, thus it is only called when the point set has been changed. * This function iterates over the input point set and determines the glyphs which lie in a specific * range around the current slice. Those glyphs are rendered using a specific shape defined in vtk glyph source * to mark each point. The shape can be changed in MITK using the property "PointSet.2D.shape". * * There were issues when rendering vtk glyphs in the 2D-render windows. By default, the glyphs are * rendered within the x-y plane in each 2D-render window, so you would only see them from the * side in the sagittal and coronal 2D-render window. The solution to this is to rotate the glyphs in order * to be ortogonal to the current view vector. To achieve this, the rotation (vtktransform) of the current - * PlaneGeometry is applied to the orienation of the glyphs. */ + * PlaneGeometry is applied to the orientation of the glyphs. */ virtual void CreateVTKRenderObjects(mitk::BaseRenderer *renderer); // member variables holding the current value of the properties used in this mapper bool m_ShowContour; // "show contour" property bool m_CloseContour; // "close contour" property bool m_ShowPoints; // "show points" property bool m_ShowDistances; // "show distances" property int m_DistancesDecimalDigits; // "distance decimal digits" property bool m_ShowAngles; // "show angles" property bool m_ShowDistantLines; // "show distant lines" property int m_LineWidth; // "line width" property int m_PointLineWidth; // "point line width" property float m_Point2DSize; // "point 2D size" property int m_IDShapeProperty; // ID for mitkPointSetShape Enumeration Property "Pointset.2D.shape" bool m_FillShape; // "Pointset.2D.fill shape" property float m_DistanceToPlane; // "Pointset.2D.distance to plane" property bool m_FixedSizeOnScreen; // "Pointset.2D.fixed size on screen" property }; } // namespace mitk #endif /* mitkPointSetVtkMapper2D_h */ diff --git a/Modules/Core/include/mitkProgressBarImplementation.h b/Modules/Core/include/mitkProgressBarImplementation.h index 8d7cb4f570..44ad914e72 100644 --- a/Modules/Core/include/mitkProgressBarImplementation.h +++ b/Modules/Core/include/mitkProgressBarImplementation.h @@ -1,52 +1,52 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKPROGRESSBARIMPLEMENTATION_H #define MITKPROGRESSBARIMPLEMENTATION_H #include namespace mitk { //##Documentation - //## @brief GUI indepentent Interface for all Gui depentent implementations of a ProgressBar. + //## @brief GUI independent Interface for all Gui depentent implementations of a ProgressBar. class MITKCORE_EXPORT ProgressBarImplementation { public: //##Documentation //## @brief Constructor ProgressBarImplementation(){}; //##Documentation //## @brief Destructor virtual ~ProgressBarImplementation(){}; //##Documentation //## @brief Sets whether the current progress value is displayed. virtual void SetPercentageVisible(bool visible) = 0; //##Documentation //## @brief Explicitly reset progress bar. virtual void Reset() = 0; //##Documentation //## @brief Adds steps to totalSteps. virtual void AddStepsToDo(unsigned int steps) = 0; //##Documentation //## @brief Sets the current amount of progress to current progress + steps. //## @param steps the number of steps done since last Progress(int steps) call. virtual void Progress(unsigned int steps) = 0; }; } // end namespace mitk #endif /* define MITKPROGRESSBARIMPLEMENTATION_H */ diff --git a/Modules/Core/include/mitkPropertyKeyPath.h b/Modules/Core/include/mitkPropertyKeyPath.h index 134bb8e9ff..bf0c37101e 100644 --- a/Modules/Core/include/mitkPropertyKeyPath.h +++ b/Modules/Core/include/mitkPropertyKeyPath.h @@ -1,216 +1,216 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkPropertyKeyPath_h #define mitkPropertyKeyPath_h #include #include #include #include namespace mitk { /** @brief Class that can be used to specify nested or wild carded property keys. E.g. * for the use in context of the property persistence service or the property relation service.\n * Following assumptions are made /preconditions are defined: * - A property key is partitioned by "." into nodes (c.f. visualization of property keys in the PropertyView). * - A node can either be an element or a selection. * - An element has a name (alphanumric, - and space; "A-Za-z0-9- ") or is wildcarded ("*") * - A selection is either an index (e.g. "[1]") or a wildcard ("[*]"). * - * Selections are used to indicate that the preceding element has multiple occurences and which occurence is meant. + * Selections are used to indicate that the preceding element has multiple occurrences and which occurence is meant. * Example property keys would be: * - prop : A simple property key - * - prop.subprop1 : A property key consting of two nodes + * - prop.subprop1 : A property key consisting of two nodes * - prop.* : Any property key that starts with a node "prop" * - prop.sub.[2] : A property key that starts with a node "prop" and a has a second node that is selection and has * the index 2. * - prop.sub.[*] : Any property key that starts with a node "prop" and a has a second node that is selection (with * any index). * * To build a path one may use the Add* method to build up the PropertyKeyPath element by element.\n * "first.*.third.[3]" would be equivalent to * propKeyPath.AddElement("first"); * propKeyPath.AddAnyElement(); * propKeyPath.AddSelection("third",3);\n * or the inline version * propKeyPath.AddElement("first").AddAnyElement().AddSelection("third",3); */ class MITKCORE_EXPORT PropertyKeyPath final { public: using ItemSelectionIndex = std::size_t; using ElementNameType = std::string; struct MITKCORE_EXPORT NodeInfo { enum class NodeType { Invalid = 0, //*< Node does not exist or is invalid. Element, //*< Selects an specific element given the node name. ElementSelection, //*< Selects an specific item in a sequence of items and has a item selector ("[n]"). AnySelection, //*< Selects all items of a specific element ("[*]"). AnyElement //*< Selects any element/item. Node name is wildcarded ("*"); item selection as well implictily. }; NodeType type; ElementNameType name; ItemSelectionIndex selection; NodeInfo(); NodeInfo(const ElementNameType &name, NodeType type = NodeType::Element, ItemSelectionIndex index = 0); bool Matches(const NodeInfo &right) const; bool operator==(const NodeInfo &right) const; }; using NodeInfoVectorType = std::vector; using PathIndexType = NodeInfoVectorType::size_type; /** Returns if the PropertyKeyPath is empty.*/ bool IsEmpty() const; /** Returns if the path is explicit (has no wildcards).*/ bool IsExplicit() const; /** Returns if the path has any nodes with item selection wild cards ([*]).*/ bool HasItemSelectionWildcardsOnly() const; /** Number of path nodes the PropertyKeyPath contains.*/ PathIndexType GetSize() const; /** Adds a new node to the end of the path. \param [in] newNode Reference to the node that should be added. \return Returns the index of the newly added node.*/ PathIndexType AddNode(const NodeInfo &newNode); /** Function returns the node info of a path node specified by the index * within the PropertyKeyPath. * \pre Passed index must not be out of bounds. * \param [in] index Index of the node whose info should be retrieved. * \return Info of the specified path node. If the index is out of bound an InvalidPathNode exception will be * thrown.*/ const NodeInfo &GetNode(const PathIndexType &index) const; /** Function returns the node info of a path node specified by the index * within the PropertyKeyPath. * \pre Passed index must not be out of bounds. * \param [in] index Index of the node whose info should be retrieved. * \return Info of the specified path node. If the index is out of bound an InvalidPathNode exception will be * thrown.*/ NodeInfo &GetNode(const PathIndexType &index); /** Function returns the node info of the first path node within the PropertyKeyPath. * \pre PropertyKeyPath must not be empty. * \return Info of the first path node. If the path is empty, an InvalidPathNode exception will be thrown.*/ NodeInfo &GetFirstNode(); /** Function returns the node info of the first path node within the PropertyKeyPath. * \pre PropertyKeyPath must not be empty. * \return Info of the first path node. If the path is empty, an InvalidPathNode exception will be thrown.*/ const NodeInfo &GetFirstNode() const; /** Function returns the node info of the last path node within the PropertyKeyPath. * \pre PropertyKeyPath must not be empty. * \return Info of the first path node. If the path is empty, an InvalidPathNode exception will be thrown.*/ NodeInfo &GetLastNode(); /** Function returns the node info of the last path node within the PropertyKeyPath. * \pre PropertyKeyPath must not be empty. * \return Info of the first path node. If the path is empty, an InvalidPathNode exception will be thrown.*/ const NodeInfo &GetLastNode() const; const NodeInfoVectorType &GetNodes() const; /**Compares two PropertyKeyPaths for real equality. So it is a string comparison of their string conversion.*/ bool operator==(const PropertyKeyPath &path) const; /**Operation equals like comparing the ToStr() results with operator <.*/ bool operator<(const PropertyKeyPath &right) const; /**Operation equals like comparing the ToStr() results with operator <=.*/ bool operator<=(const PropertyKeyPath &right) const; /**Operation equals like comparing the ToStr() results with operator >=.*/ bool operator>=(const PropertyKeyPath &right) const; /**Operation equals like comparing the ToStr() results with operator >.*/ bool operator>(const PropertyKeyPath &right) const; /**Checks if two PropertyKeyPaths specify the same node. Hence all wildcards will be processed.\n * E.G.: "item1.child1.grandChild2" == "item1.*.grandChild2" is true. * \remark If you want to check if two paths are "truly" equal and not only equal in terms of * pointing to the same node, use the member function operator ==().*/ bool Equals(const PropertyKeyPath &path) const; PropertyKeyPath &operator=(const PropertyKeyPath &path); /** Appends an "any element" to the path instance.*/ PropertyKeyPath &AddAnyElement(); /** Appends an element with the passed name to the path instance.*/ PropertyKeyPath &AddElement(const ElementNameType &name); /** Appends an element with the passed name and any selection to the path instance.*/ PropertyKeyPath &AddAnySelection(const ElementNameType &name); /** Appends an element with the passed name and selection index to the path instance.*/ PropertyKeyPath &AddSelection(const ElementNameType &name, ItemSelectionIndex index); PropertyKeyPath(); PropertyKeyPath(const PropertyKeyPath &path); - /** overload constructor that supports simple key pathes consisting only of elements.*/ + /** overload constructor that supports simple key paths consisting only of elements.*/ PropertyKeyPath(const std::initializer_list< ElementNameType >& list); ~PropertyKeyPath(); void Reset(); protected: NodeInfoVectorType m_NodeInfos; static bool PropertyKeyPathsMatch(const PropertyKeyPath &left, const PropertyKeyPath &right); }; class MITKCORE_EXPORT InvalidPathNodeException : public mitk::Exception { public: mitkExceptionClassMacro(InvalidPathNodeException, mitk::Exception); }; MITKCORE_EXPORT std::ostream &operator<<(std::ostream &os, const PropertyKeyPath &path); /**Helper function that converts a path PropertyKeyPath into a regex string that can be used to search for property keys (using std::regex) that are matched by the PropertyKeyPath. This function is used in context of the property persistence service.*/ MITKCORE_EXPORT std::string PropertyKeyPathToPropertyRegEx(const PropertyKeyPath &tagPath); /**Helper function that converts a path PropertyKeyPath into a regex string that can be used to search for property persistence keys (using std::regex) that are matched by the PropertyKeyPath. This function is used in context of the property persistence service.*/ MITKCORE_EXPORT std::string PropertyKeyPathToPersistenceKeyRegEx(const PropertyKeyPath &tagPath); /**Helper function that converts a path PropertyKeyPath into a regex that can be used as key template in a PropertyPersistanceInfo. This function is used in context of the property persistence service.*/ MITKCORE_EXPORT std::string PropertyKeyPathToPersistenceKeyTemplate(const PropertyKeyPath &tagPath); /**Helper function that converts a path PropertyKeyPath into a regex that can be used as name template in a PropertyPersistanceInfo. This function is used in context of the property persistence service.*/ MITKCORE_EXPORT std::string PropertyKeyPathToPersistenceNameTemplate(const PropertyKeyPath &tagPath); /** Converts the passed property name into a tag path. If the property name cannot be converted into a valid path, the returned path is empty.*/ MITKCORE_EXPORT PropertyKeyPath PropertyNameToPropertyKeyPath(const std::string &propertyName); /** returns the correct property name for a given PropertyKeyPath instance. */ MITKCORE_EXPORT std::string PropertyKeyPathToPropertyName(const PropertyKeyPath &tagPath); } // namespace mitk #endif diff --git a/Modules/Core/include/mitkPropertyList.h b/Modules/Core/include/mitkPropertyList.h index c5832a5888..35e29262a5 100644 --- a/Modules/Core/include/mitkPropertyList.h +++ b/Modules/Core/include/mitkPropertyList.h @@ -1,254 +1,254 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef PROPERTYLIST_H_HEADER_INCLUDED_C1C77D8D #define PROPERTYLIST_H_HEADER_INCLUDED_C1C77D8D #include "mitkBaseProperty.h" #include "mitkGenericProperty.h" #include "mitkUIDGenerator.h" #include "mitkIPropertyOwner.h" #include #include #include #include namespace mitk { class XMLWriter; /** * @brief Key-value list holding instances of BaseProperty * * This list is meant to hold an arbitrary list of "properties", * which should describe the object associated with this list. * * Usually you will use PropertyList as part of a DataNode * object - in this context the properties describe the data object * held by the DataNode (e.g. whether the object is rendered at * all, which color is used for rendering, what name should be * displayed for the object, etc.) * * The values in the list are not fixed, you may introduce any kind * of property that seems useful - all you have to do is inherit * from BaseProperty. * * The list is organized as a key-value pairs, i.e. * * \li "name" : pointer to a StringProperty * \li "visible" : pointer to a BoolProperty * \li "color" : pointer to a ColorProperty * \li "volume" : pointer to a FloatProperty * * Please see the documentation of SetProperty and ReplaceProperty for two * quite different semantics. Normally SetProperty is what you want - this * method will try to change the value of an existing property and will * not allow you to replace e.g. a ColorProperty with an IntProperty. * * Please also regard, that the key of a property must be a none empty string. * This is a precondition. Setting properties with empty keys will raise an exception. * * @ingroup DataManagement */ class MITKCORE_EXPORT PropertyList : public itk::Object, public IPropertyOwner { public: mitkClassMacroItkParent(PropertyList, itk::Object); /** * Method for creation through the object factory. */ itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * Map structure to hold the properties: the map key is a string, * the value consists of the actual property object (BaseProperty). */ typedef std::map PropertyMap; typedef std::pair PropertyMapElementType; // IPropertyProvider BaseProperty::ConstPointer GetConstProperty(const std::string &propertyKey, const std::string &contextName = "", bool fallBackOnDefaultContext = true) const override; std::vector GetPropertyKeys(const std::string &contextName = "", bool includeDefaultContext = false) const override; std::vector GetPropertyContextNames() const override; // IPropertyOwner BaseProperty * GetNonConstProperty(const std::string &propertyKey, const std::string &contextName = "", bool fallBackOnDefaultContext = true) override; void SetProperty(const std::string &propertyKey, BaseProperty *property, const std::string &contextName = "", bool fallBackOnDefaultContext = false) override; void RemoveProperty(const std::string &propertyKey, const std::string &contextName = "", bool fallBackOnDefaultContext = false) override; /** * @brief Get a property by its name. */ mitk::BaseProperty *GetProperty(const std::string &propertyKey) const; /** * @brief Set a property object in the list/map by reference. * * The actual OBJECT holding the value of the property is replaced by this function. * This is useful if you want to change the type of the property, like from BoolProperty to StringProperty. - * Another use is to share one and the same property object among several ProperyList/DataNode objects, which + * Another use is to share one and the same property object among several PropertyList/DataNode objects, which * makes them appear synchronized. */ void ReplaceProperty(const std::string &propertyKey, BaseProperty *property); /** * @brief Set a property object in the list/map by reference. */ void ConcatenatePropertyList(PropertyList *pList, bool replace = false); //##Documentation //## @brief Convenience access method for GenericProperty properties //## (T being the type of the second parameter) //## @return @a true property was found template bool GetPropertyValue(const char *propertyKey, T &value) const { GenericProperty *gp = dynamic_cast *>(GetProperty(propertyKey)); if (gp != nullptr) { value = gp->GetValue(); return true; } return false; } /** * @brief Convenience method to access the value of a BoolProperty */ bool GetBoolProperty(const char *propertyKey, bool &boolValue) const; /** * @brief ShortCut for the above method */ bool Get(const char *propertyKey, bool &boolValue) const; /** * @brief Convenience method to set the value of a BoolProperty */ void SetBoolProperty(const char *propertyKey, bool boolValue); /** * @brief ShortCut for the above method */ void Set(const char *propertyKey, bool boolValue); /** * @brief Convenience method to access the value of an IntProperty */ bool GetIntProperty(const char *propertyKey, int &intValue) const; /** * @brief ShortCut for the above method */ bool Get(const char *propertyKey, int &intValue) const; /** * @brief Convenience method to set the value of an IntProperty */ void SetIntProperty(const char *propertyKey, int intValue); /** * @brief ShortCut for the above method */ void Set(const char *propertyKey, int intValue); /** * @brief Convenience method to access the value of a FloatProperty */ bool GetFloatProperty(const char *propertyKey, float &floatValue) const; /** * @brief ShortCut for the above method */ bool Get(const char *propertyKey, float &floatValue) const; /** * @brief Convenience method to set the value of a FloatProperty */ void SetFloatProperty(const char *propertyKey, float floatValue); /** * @brief ShortCut for the above method */ void Set(const char *propertyKey, float floatValue); /** * @brief Convenience method to access the value of a DoubleProperty */ bool GetDoubleProperty(const char *propertyKey, double &doubleValue) const; /** * @brief ShortCut for the above method */ bool Get(const char *propertyKey, double &doubleValue) const; /** * @brief Convenience method to set the value of a DoubleProperty */ void SetDoubleProperty(const char *propertyKey, double doubleValue); /** * @brief ShortCut for the above method */ void Set(const char *propertyKey, double doubleValue); /** * @brief Convenience method to access the value of a StringProperty */ bool GetStringProperty(const char *propertyKey, std::string &stringValue) const; /** * @brief ShortCut for the above method */ bool Get(const char *propertyKey, std::string &stringValue) const; /** * @brief Convenience method to set the value of a StringProperty */ void SetStringProperty(const char *propertyKey, const char *stringValue); /** * @brief ShortCut for the above method */ void Set(const char *propertyKey, const char *stringValue); /** * @brief ShortCut for the above method */ void Set(const char *propertyKey, const std::string &stringValue); /** * @brief Get the timestamp of the last change of the map or the last change of one of * the properties store in the list (whichever is later). */ itk::ModifiedTimeType GetMTime() const override; /** * @brief Remove a property from the list/map. */ bool DeleteProperty(const std::string &propertyKey); const PropertyMap *GetMap() const { return &m_Properties; } bool IsEmpty() const { return m_Properties.empty(); } virtual void Clear(); protected: PropertyList(); PropertyList(const PropertyList &other); ~PropertyList() override; /** * @brief Map of properties. */ PropertyMap m_Properties; private: itk::LightObject::Pointer InternalClone() const override; }; } // namespace mitk #endif /* PROPERTYLIST_H_HEADER_INCLUDED_C1C77D8D */ diff --git a/Modules/Core/include/mitkPropertyObserver.h b/Modules/Core/include/mitkPropertyObserver.h index 62f1ae6ab6..04903c7e71 100644 --- a/Modules/Core/include/mitkPropertyObserver.h +++ b/Modules/Core/include/mitkPropertyObserver.h @@ -1,81 +1,81 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITK_BASEPROPERTYOBSERVER_H_INCLUDED #define MITK_BASEPROPERTYOBSERVER_H_INCLUDED #include "MitkCoreExports.h" #include "mitkCommon.h" #include namespace mitk { /** \brief Convenience class to observe changes of a mitk::BaseProperty. This class registers itself as an ITK observer to a BaseProperty and gets - informed of changes to the property. Whenever such a change occurrs, the virtual + informed of changes to the property. Whenever such a change occurs, the virtual method PropertyChanged() or PropertyRemoved() is called. This way, derived classes can implement behaviour for more specific properties (e.g. ColorProperty) without the need to reimplement the Subject-Observer handling. */ class BaseProperty; class MITKCORE_EXPORT PropertyObserver { public: PropertyObserver(); virtual ~PropertyObserver(); virtual void PropertyChanged() = 0; virtual void PropertyRemoved() = 0; protected: void BeginModifyProperty(); void EndModifyProperty(); unsigned long m_ModifiedTag; unsigned long m_DeleteTag; bool m_SelfCall; }; class MITKCORE_EXPORT PropertyView : public PropertyObserver { public: PropertyView(const mitk::BaseProperty *); ~PropertyView() override; void OnModified(const itk::EventObject &e); void OnDelete(const itk::EventObject &e); protected: const mitk::BaseProperty *m_Property; }; class MITKCORE_EXPORT PropertyEditor : public PropertyObserver { public: PropertyEditor(mitk::BaseProperty *); ~PropertyEditor() override; void OnModified(const itk::EventObject &e); void OnDelete(const itk::EventObject &e); protected: mitk::BaseProperty *m_Property; }; } #endif diff --git a/Modules/Core/include/mitkPropertyPersistenceInfo.h b/Modules/Core/include/mitkPropertyPersistenceInfo.h index 3f3a429149..1325f3953a 100644 --- a/Modules/Core/include/mitkPropertyPersistenceInfo.h +++ b/Modules/Core/include/mitkPropertyPersistenceInfo.h @@ -1,124 +1,124 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkPropertyPersistenceInfo_h #define mitkPropertyPersistenceInfo_h #include #include #include #include #include namespace mitk { /** \brief Property persistence info. This class is used to specify the way the persistance of a property of BaseData derived instances is handled. The info specifies the key for property, as well as the mime type the info is defined for and should be used. Additionally the functions for deserialization and serialization of the property can be defined. As default */ class MITKCORE_EXPORT PropertyPersistenceInfo : public itk::LightObject { public: /** Signature specification for functions that can be provided for deserialization of the property. @post The function returns a valid instance derived from mitk::BaseProperty.*/ using DeserializationFunctionType = std::function; using SerializationFunctionType = std::function; using MimeTypeNameType = std::string; mitkClassMacroItkParent(PropertyPersistenceInfo, itk::LightObject); itkFactorylessNewMacro(Self); itkCloneMacro(Self) mitkNewMacro1Param(Self, const std::string &); mitkNewMacro2Param(Self, const std::string &, const std::string &); std::string GetName() const; std::string GetKey() const; void SetName(const std::string &name); void SetNameAndKey(const std::string &name, const std::string &key); bool IsRegEx() const; /** Sets the name and the key identifier as a regular expression that describes valid names and keys. - * @pre nameRegEx must be a valid regular expression, otherweis a regex_error esception + * @pre nameRegEx must be a valid regular expression, otherwise a regex_error esception * is thrown and the info object is not changed. - * @pre keyRegEx must be a valid regular expression, otherweis a regex_error esception + * @pre keyRegEx must be a valid regular expression, otherwise a regex_error esception * is thrown and the info object is not changed.*/ void UseRegEx(const std::string &nameRegEx, const std::string &nameTemplate); void UseRegEx(const std::string &nameRegEx, const std::string &nameTemplate, const std::string &keyRegEx, const std::string keyTemplate); const std::string &GetKeyTemplate() const; const std::string &GetNameTemplate() const; const MimeTypeNameType &GetMimeTypeName() const; void SetMimeTypeName(const MimeTypeNameType &mimeTypeName); const DeserializationFunctionType GetDeserializationFunction() const; void SetDeserializationFunction(const DeserializationFunctionType &fnc); const SerializationFunctionType GetSerializationFunction() const; void SetSerializationFunction(const SerializationFunctionType &fnc); PropertyPersistenceInfo::Pointer UnRegExByName(const std::string &propertyName) const; PropertyPersistenceInfo::Pointer UnRegExByKey(const std::string &key) const; /** This mime type name indicates that a info can be used for any mime type as long as another info with a more specific mime type is not available.*/ static MimeTypeNameType ANY_MIMETYPE_NAME(); protected: /** \brief Constructor. * * \param[in] name Name is the name of the property that described by the info. Key will be the same. */ PropertyPersistenceInfo(const std::string &name = ""); /** \brief Constructor. * * \param[in] name Name is the name of the property that described by the info. Key will be the same. * \param[in] mimeTypeName mime type the info is defined for. */ PropertyPersistenceInfo(const std::string &name, const std::string &mimeTypeName); ~PropertyPersistenceInfo() override; void PrintSelf(std::ostream &os, itk::Indent indent) const override; private: PropertyPersistenceInfo(const Self &other); Self &operator=(const Self &other); struct Impl; Impl *m_Impl; }; MITKCORE_EXPORT std::ostream &operator<<(std::ostream &os, const PropertyPersistenceInfo &info); namespace PropertyPersistenceSerialization { /** Simple default serialization that uses prop->GetValueAsString for the serialization.*/ MITKCORE_EXPORT::std::string serializeByGetValueAsString(const mitk::BaseProperty *prop); } namespace PropertyPersistenceDeserialization { /** Simple default functions that puts the passed string into a string property.*/ MITKCORE_EXPORT mitk::BaseProperty::Pointer deserializeToStringProperty(const std::string &value); } } #endif diff --git a/Modules/Core/include/mitkPropertyRelationRuleBase.h b/Modules/Core/include/mitkPropertyRelationRuleBase.h index 2ea5eadefa..1a77b47f64 100644 --- a/Modules/Core/include/mitkPropertyRelationRuleBase.h +++ b/Modules/Core/include/mitkPropertyRelationRuleBase.h @@ -1,403 +1,403 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkPropertyRelationRuleBase_h #define mitkPropertyRelationRuleBase_h #include "mitkIPropertyOwner.h" #include "mitkIdentifiable.h" #include "mitkException.h" #include "mitkNodePredicateBase.h" #include "mitkPropertyKeyPath.h" #include #include namespace mitk { /**Base class to standardize/abstract/encapsulate rules and business logic to detect and define (property/data based) relations in MITK. - Following important definitions must be regarded when using/implementing/specifing rule classes: - - Releations represented by rules are directed relations that point from a source IPropertyOwner (Source) + Following important definitions must be regarded when using/implementing/specifying rule classes: + - Relations represented by rules are directed relations that point from a source IPropertyOwner (Source) to a destination IPropertyOwner (Destination). - Rule can be abstract (indicated by IsAbstract()) or concrete. Abstract rules cannot be used to connect relations. Abstract rules can only be used to detect/indicate or disconnect relations. Therefore, in contrast to concrete rules, abstract rules can be used to indicate several relations that are established be "derived" rules. See e.g. GenericIDRelationRule: in its abstract state it cannot connect but be used to detect any type of generic ID relation. - A concrete rule ID (rule ID of a concrete rule) always "implements" a concrete relation type. E.g. In DICOM the way to express the source image relation to an input image and to a mask would be nearly the same and only differs by the encoded purpose. One may implement an interim or joined class that manages the mutual stuff, but the registered instances must be one concrete rule for "DICOM source input image" and one concrete rule for "DICOM source mask" and both rules must have distinct rule IDs. - Source may have several relations of a rule to different Destinations. Destination may have several relations of a rule from different Sources. But a specific source destination pair may have only one relation of a specific rule id (concrete rule). A specific source destination pair may however have multiple relations for an abstract rule. - The deletion of a Destination in the storage does not remove the relation implicitly. It becomes a "zombie" relation but it should still be documented, even if the destination is unknown. One has to explicitly disconnect a zombie relation to get rid of it. - Each relation has its own UID (relationUID) that can be used to address it. The basic concept of the rule design is that we have two layers of relation identification: Layer 1 is the ID-layer which uses the IIdentifiable interface and UIDs if available to encode "hard" relations. Layer 2 is the Data-layer which uses the properties of Source and Destination to deduce if there is a relation of the rule type. The ID-layer is completely implemented by this base class. The base class falls back to the Data-layer (implemented by the concrete rule class) if the ID-layer is not sufficient or it is explicitly stated to (only) look at the data layer. Reasons for the introduction of the ID-layer are: 1st, data-defined relations may be weak (several Destinations are possible; e.g. DICOM source images may point to several loaded mitk images). But if explicitly a relation was connected it should be deduceable. 2nd, checks on a UID are faster then unnecessary data deduction. - Rules use relation instance identifing (RII) properties in order to manage their relations that are stored in the + Rules use relation instance identifying (RII) properties in order to manage their relations that are stored in the Source. The RII-properties follow the following naming schema: "MITK.Relations.\.[relationUID|destinationUID|ruleID|\]" - \: The unique index of the relation for the Source. Used to assign/group the properties to their relation. In the default implementation of this class the instance id is an positive integer (i>0). - relationUID: The UID of the relation. Set by the ID-layer (so by this class) - destinationUID: The UID of the Destination. Set by the ID-layer (so by this class) if Destination implements IIdentifiable. - ruleID: The identifier of the concrete rule that sets the property. Is specified by the derived class and set - automaticaly be this base class. + automatically be this base class. - : Information needed by the Data-layer (so derived classes) to find the relationUID */ class MITKCORE_EXPORT PropertyRelationRuleBase : public itk::Object { public: mitkClassMacroItkParent(PropertyRelationRuleBase, itk::Object); itkCloneMacro(Self); itkCreateAnotherMacro(Self); using RuleIDType = std::string; using RelationUIDType = Identifiable::UIDType; using RelationUIDVectorType = std::vector; /** Enum class for different types of relations. */ enum class RelationType { None = 0, /**< Two IPropertyOwner have no relation under the rule.*/ Data = 1, /**< Two IPropertyOwner have a relation, but it is "only" deduced from the Data-layer (so a bit "weaker" as ID). Reasons for the missing ID connection could be that Destintination has not IIdentifiable implemented.*/ - ID = 2, /**< Two IPropertyOwner have a relation and are explictly connected via the ID of IIdentifiable of the Destination.*/ - Complete = 3 /**< Two IPropertyOwner have a relation and are fully explictly connected (via data layer and ID layer).*/ + ID = 2, /**< Two IPropertyOwner have a relation and are explicitly connected via the ID of IIdentifiable of the Destination.*/ + Complete = 3 /**< Two IPropertyOwner have a relation and are fully explicitly connected (via data layer and ID layer).*/ }; using RelationVectorType = std::vector; /** Returns the generic root path for relation rules ("MITK.Relations").*/ static PropertyKeyPath GetRootKeyPath(); using InstanceIDType = std::string; /** Returns the property key path for a RII property. * @param propName If not empty a PropertyPath element will added (with the passed value) after the \ element. * @param instanceID If not empty, the PropertyKeyPath is only for a specific instance. If empty, * it is wildcarded and will match RIIs property of any instance.*/ static PropertyKeyPath GetRIIPropertyKeyPath(const std::string propName, const InstanceIDType& instanceID); /** Returns the property key path for RII RelationUID properties. * @param instanceID If not empty, the PropertyKeyPath is only for a specific instance. If empty, * it is wildcarded and will match RII RelationUIDs property of any instance.*/ static PropertyKeyPath GetRIIRelationUIDPropertyKeyPath(const InstanceIDType& instanceID = ""); /** Returns the property key path for RII RuleID properties. * @param instanceID If not empty, the PropertyKeyPath is only for a specific instance. If empty, * it is wildcarded and will match RII RuleIDs property of any instance.*/ static PropertyKeyPath GetRIIRuleIDPropertyKeyPath(const InstanceIDType& instanceID = ""); /** Returns the property key path for RII DestinationUID properties. * @param instanceID If not empty, the PropertyKeyPath is only for a specific instance. If empty, * it is wildcarded and will match RII DestinationUIDs property of any instance.*/ static PropertyKeyPath GetRIIDestinationUIDPropertyKeyPath(const InstanceIDType& instanceID = ""); /** Returns an ID string that identifies the rule class. @post The returned rule ID must met the preconditions of a PropertyKeyPath element name (see mitk::PropertyKeyPath*/ virtual RuleIDType GetRuleID() const = 0; /** Returns a human readable string that can be used to describe the rule. Does not need to be unique.*/ virtual std::string GetDisplayName() const = 0; /** Returns a human readable string that can be used to describe the role of a source in context of the rule * instance.*/ virtual std::string GetSourceRoleName() const = 0; - /** Returns a human readable string that can be used to describe the role of a destionation in context of the rule + /** Returns a human readable string that can be used to describe the role of a destination in context of the rule * instance.*/ virtual std::string GetDestinationRoleName() const = 0; /** Returns if the instance is a abstract rule (true). Default implementation is true. Overwrite and reimplement if another behavior is needed.*/ virtual bool IsAbstract() const; /** This method checks if owner is eligible to be a Source for the rule. The default implementation returns a True for every valid IPropertyProvider (so only a null_ptr results into false). May be reimplement by derived rules if they have requirements on potential Sources).*/ virtual bool IsSourceCandidate(const IPropertyProvider *owner) const; /** This method checks if owner is eligible to be a Destination for the rule. The default implementation returns a True for every valid IPropertyProvider (so only a null_ptr results into false). May be reimplement by derived rules if they have requirements on potential Sources).*/ virtual bool IsDestinationCandidate(const IPropertyProvider *owner) const; /** Returns true if the passed owner is a Source of a relation defined by the rule. @pre owner must be a pointer to a valid IPropertyProvider instance.*/ bool IsSource(const IPropertyProvider *owner) const; /** Returns all relation types of the passed IPropertyOwner instances. @remark Abstract rules may have several relationtypes between the instances (from different supported concrete rules), that cover both ID and Data relations; thus it returns a vector of RelationTypes. @result Vector of all relation types that exist between the given instances. Empty vector equals none relation at all. @pre source must be a pointer to a valid IPropertyProvider instance. @pre destination must be a pointer to a valid IPropertyProvider instance. */ RelationVectorType GetRelationTypes(const IPropertyProvider* source, const IPropertyProvider* destination) const; /** Indicates if passed IPropertyOwner instances have a relation of a certain type. @remark Abstract rules may also indicate RelationType::Complete if there are multiple relations (from different supported concrete rules), that cover both ID and Data relations. @param source @param destination @param requiredRelation Defines the type of relation that should be present. None: does not matter which one, as long as at least one is present. Data: Only data layer exclusive connections, ID: Only ID layer exclusive connections. Complete: Only relations that are connected on both layers. @pre source must be a pointer to a valid IPropertyProvider instance. @pre destination must be a pointer to a valid IPropertyProvider instance. */ bool HasRelation(const IPropertyProvider *source, const IPropertyProvider *destination, RelationType requiredRelation = RelationType::None) const; /** Returns a vector of relation UIDs for all relations of this rule instance that are defined for the passed source. @pre source must be a pointer to a valid IPropertyOwner instance. @param source @param layer Defines the layer the relations must be reflected. None: does not matter which one, as long as at least one is present. Data: Only data layer exclusive connections, ID: Only ID layer exclusive connections. Complete: Only relations that are connected on both layers.*/ RelationUIDVectorType GetExistingRelations(const IPropertyProvider *source, RelationType layer = RelationType::None) const; /** Returns the relation UID(s) for the passed source and destination of this rule instance. If the rule is abstract multiple relation UIDs might be returned. In case of concrete rule only one relation UID. @pre source must be a pointer to a valid IPropertyOwner instance. @pre destination must be a pointer to a valid IPropertyOwner instance.*/ RelationUIDVectorType GetRelationUIDs(const IPropertyProvider *source, const IPropertyProvider *destination) const; /** Returns the relation UID for the passed source and destination of this rule instance. If the passed instances have no relation, no ID can be deduced and an exception will be thrown. If more than one relation is found, also an exception will be thrown. Thus only use this convenience method, if you are sure that one(!) relation UID can exist. @pre source must be a pointer to a valid IPropertyOwner instance. @pre destination must be a pointer to a valid IPropertyOwner instance. @pre Source and destination have one relation; otherwise if no relation exists a NoPropertyRelationException is thrown; if more than one relation exists - a default MITK expception is thrown.*/ + a default MITK exception is thrown.*/ RelationUIDType GetRelationUID(const IPropertyProvider *source, const IPropertyProvider *destination) const; /**Predicate that can be used to find nodes that qualify as source for that rule (but must not be a source yet). Thus all nodes where IsSourceCandidate() returns true. */ NodePredicateBase::ConstPointer GetSourceCandidateIndicator() const; /**Predicate that can be used to find nodes that qualify as destination for that rule (but must not be a destination yet). Thus all nodes where IsDestinationCandidate() returns true. */ NodePredicateBase::ConstPointer GetDestinationCandidateIndicator() const; /**Predicate that can be used to find nodes that are Sources of that rule and connected. Thus all nodes where IsSource() returns true.*/ NodePredicateBase::ConstPointer GetConnectedSourcesDetector() const; /**Predicate that can be used to find nodes that are as source related to the passed Destination under the rule @param destination Pointer to the Destination instance that should be used for detection. @param exclusiveRelation Defines if only special types of relations should detected. None: All relations (default); Data: must be a data relation (so Data or Complete); ID: must be an ID relation (so ID or Complete); Complete: only complete relations. @pre Destination must be a valid instance.*/ NodePredicateBase::ConstPointer GetSourcesDetector( const IPropertyProvider *destination, RelationType exclusiveRelation = RelationType::None) const; /**Predicate that can be used to find nodes that are as Destination related to the passed Source under the rule @param source Pointer to the Source instance that should be used for detection. @param exclusiveRelation Defines if only special types of relations should detected. None: All relations (default); Data: must be a data relation (so Data or Complete); ID: must be an ID relation (so ID or Complete); Complete: only complete relations. @pre Source must be a valid instance.*/ NodePredicateBase::ConstPointer GetDestinationsDetector( const IPropertyProvider *source, RelationType exclusiveRelation = RelationType::None) const; /**Returns a predicate that can be used to find the Destination of the passed Source for a given relationUID. @param source Pointer to the Source instance that should be used for detection. @param relationUID @pre source must be a valid instance. @pre relationUID must identify a relation of the passed source and rule. (This must be in the return of this->GetExistingRelations(source). */ NodePredicateBase::ConstPointer GetDestinationDetector(const IPropertyProvider *source, RelationUIDType relationUID) const; - /**Disconnect the passed instances by modifing source. One can specify which layer should be disconnected + /**Disconnect the passed instances by modifying source. One can specify which layer should be disconnected via the argument "layer". Default is the complete disconnection. All RII-properties or properties that define the connection on the data layer in the source for the passed destination will be removed. @pre source must be a valid instance. @pre destination must be a valid instance. @param source @param destination @param layer Defines the way of disconnection. Data: Only the remove the connection on the data layer. ID: Only remove the connection on the ID layer. Complete: Remove the connection on all layers. If a connection does not exist on a selected layer, it is silently ignored.*/ void Disconnect(IPropertyOwner *source, const IPropertyProvider *destination, RelationType layer = RelationType::Complete) const; - /**Disconnect the source from the passed relationUID (usefull for "zombie relations"). + /**Disconnect the source from the passed relationUID (useful for "zombie relations"). One can specify which layer should be disconnected via the argument "layer". Default is the complete disconnection. All RII-properties or properties that define the connection on the data layer in the source for the passed destination will be removed. If the relationUID is not part of the source. Nothing will be changed. @pre source must be a valid instance. @param source @param relationUID @param layer Defines the way of disconnection. Data: Only the remove the connection on the data layer. ID: Only remove the connection on the ID layer. Complete: Remove the connection on all layers. If a connection does not exist on a selected layer, it is silently ignored.*/ void Disconnect(IPropertyOwner *source, RelationUIDType relationUID, RelationType layer = RelationType::Complete) const; /**Returns the list of PropertyKeyPaths of all properties that are relevant for a given relation. - @param source Pointer to the Source instance that containes the potential properties. + @param source Pointer to the Source instance that contains the potential properties. @param relationUID UID of the relation that is relevant for the requested properties. @param layer Indicates which layer is requested. ID: returns all RII properties that belong to the relation. Data: returns all properties that are relevant/belong to the data layer of the relation. Complete: returns all properties (ID+Data) @pre source must be a valid instance. @pre relationUID must identify a relation of the passed source and rule. (This must be in the return of this->GetExistingRelations(source). */ - std::vector GetReleationPropertyPaths(const IPropertyProvider* source, + std::vector GetRelationPropertyPaths(const IPropertyProvider* source, RelationUIDType relationUID, RelationType layer = RelationType::Data) const; protected: PropertyRelationRuleBase() = default; ~PropertyRelationRuleBase() override = default; using InstanceIDVectorType = std::vector; static InstanceIDType NULL_INSTANCE_ID(); /** Returns the instance IDs for the passed source and destination for this rule instance. If the passed source and destination instances has no explicit relation on the ID layer (Connected_ID), an empty vector will be returned. @remark Per definition of property relation rules only 0 or 1 instance should be found for one provider pair and concrete rule. But there might be more then one instanceID because either 1) the rule is abstract and supports multiple rule IDs or 2) the data layer may be ambiguous and therefore multiple relation instances of the rule instance could match. The implementation of this function should report all relation instances. The calling function will take care. @pre source must be a pointer to a valid IPropertyProvider instance. @pre destination must be a pointer to a valid IPropertyProvider instance.*/ InstanceIDVectorType GetInstanceID_IDLayer(const IPropertyProvider *source, const IPropertyProvider *destination) const; using DataRelationUIDVectorType = std::vector< std::pair >; - /** Returns the ReleationUIDs of all relations that are defined by the data layer of source for + /** Returns the RelationUIDs of all relations that are defined by the data layer of source for this rule instance and, if defined, destination. If the passed source (and destination) instance has no relation on the data layer, an empty vector will be returned. @remark Per definition for property relation rules only 0 or 1 instance should be found for one provider pair and concrete rule. But there might be more then one instance because either 1) the rule is abstract and supports multiple rule IDs or 2) the data layer may be ambiguous (e.g. because the destination was not specified) and therefore multiple relation instances of the rule instance could match. The implementation of this function should report all relation instances. The calling function will take care. @param source @param destination Destination the find relations should point to. If destination is NULL any relation on the data layer for this rule and source are wanted. - @param instances_IDLayer List of releation instances that are already defined by the ID layer. The implementation of this - function should only cover releations that are not already resembled in the passed relarions_IDLayer. + @param instances_IDLayer List of relation instances that are already defined by the ID layer. The implementation of this + function should only cover relations that are not already resembled in the passed relarions_IDLayer. @pre source must be a pointer to a valid IPropertyProvider instance.*/ virtual DataRelationUIDVectorType GetRelationUIDs_DataLayer(const IPropertyProvider * source, const IPropertyProvider * destination, const InstanceIDVectorType& instances_IDLayer) const = 0; /**Helper function that deduces the relation UID of the given relation instance. If it cannot be deduced an NoPropertyRelationException is thrown.*/ RelationUIDType GetRelationUIDByInstanceID(const IPropertyProvider *source, const InstanceIDType &instanceID) const; /**Helper function that deduces the relation instance ID given the relation UID. If it cannot be deduced an NoPropertyRelationException is thrown.*/ InstanceIDType GetInstanceIDByRelationUID(const IPropertyProvider *source, const RelationUIDType &relationUID) const; /**Explicitly connects the passed instances. Afterwards they have a relation of Data (if data layer is supported), ID (if a destination implements IIdentifiable) or Complete (if Data and ID could be connected). If the passed instance are already connected the old connection will be overwritten (and raised to the highest possible connection level). @remark This method has protected visibility in the base implementation, because it is a design decision of derived rule classes which interface they want to offer for connecting. It may just be made public (e.g. GenericIDRelationRule) or used by own implementations. @pre source must be a valid instance. @pre destination must be a valid instance. @pre the rule instance must not be abstract. @return Return the relation uid of the relation connected by this method call*/ RelationUIDType Connect(IPropertyOwner *source, const IPropertyProvider *destination) const; /**Is called by Connect() to ensure that source has correctly set properties to resemble the relation on the data layer. This means that the method should set the properties that describe and encode the relation on the data layer (data-layer-specific relation properties). If the passed instance are already connected, the old settings should be overwritten. Connect() will ensure that source and destination are valid pointers. @param source @param destination - @param instanceID is the ID for the relation instance that should be connected. Existance of the relation instance + @param instanceID is the ID for the relation instance that should be connected. Existence of the relation instance is ensured. @pre source must be a valid instance. @pre destination must be a valid instance.*/ virtual void Connect_datalayer(IPropertyOwner *source, const IPropertyProvider *destination, const InstanceIDType &instanceID) const = 0; /**This method is called by Disconnect() to remove all properties of the relation from the source that are set by Connect_datalayer(). @remark This method should remove all properties that are set for a specific relation by Connect_datalayer(...). If the relationUID is not part of the source, nothing will be changed. Disconnect() ensures that source is a valid pointer if called. @remark Disconnect() ensures that sourece is valid and only invokes if instance exists.*/ virtual void Disconnect_datalayer(IPropertyOwner *source, const RelationUIDType & relationUID) const = 0; /** Returns if the passed rule ID is supported/relevant for the rule. Either because it is the very ID of the rule (default implementation) or because it is an abstract rule which also supports the rule ID. @return true: If the rule ID can handle the rule ID. false: the rule does not support the rule ID.*/ virtual bool IsSupportedRuleID(const RuleIDType& ruleID) const; /** Helper function that generates a reg ex that can be used to find a specific RII property for the rule instance. * @param propName If not empty a PropertyPath element will be added (with the passed value) after the \ element. * @param instanceID If not empty only for the reg ex will only valid for the passed instanceID. Otherwise for all.*/ std::string GetRIIPropertyRegEx(const std::string propName = "", const InstanceIDType &instanceID = "") const; /**Helper function that deduces the instance ID out of a property name. If it cannot be deduced an MITK exception is thrown.*/ static InstanceIDType GetInstanceIDByPropertyName(const std::string propName); - /**Helper function that retrives the rule ID of a relation instance of a passed source. + /**Helper function that retrieves the rule ID of a relation instance of a passed source. @pre source must be valid. @pre source must have a relation instance with this ID*/ RuleIDType GetRuleIDByInstanceID(const IPropertyProvider *source, const InstanceIDType &instanceID) const; - /**Helper function that retrives the destination UID of a relation instance of a passed + /**Helper function that retrieves the destination UID of a relation instance of a passed source. If the relation has no destination UID, an empty string will be returned. @pre source must be valid.*/ std::string GetDestinationUIDByInstanceID(const IPropertyProvider * source, const InstanceIDType & instanceID) const; itk::LightObject::Pointer InternalClone() const override; /** helper method that serves as a workaround until T24729 is done. Please remove if T24728 is done then could directly use owner->GetPropertyKeys() again.*/ static std::vector GetPropertyKeys(const IPropertyProvider *owner); /** Helper method that tries to cast the provider to the Identifiable interface.*/ const Identifiable* CastProviderAsIdentifiable(const mitk::IPropertyProvider* provider) const; private: - /** Creats a relation UID*/ + /** Creates a relation UID*/ static RelationUIDType CreateRelationUID(); - /**Prepares a new relation instance. Therefore an unused and valid instance ID for the passed source will be genarated + /**Prepares a new relation instance. Therefore an unused and valid instance ID for the passed source will be generated and a relationUID property with the relationUID will be set to block the instance ID. The instance ID will be returned. @remark The method is guarded by a class wide mutex to avoid racing conditions in a scenario where rules are used concurrently.*/ InstanceIDType CreateNewRelationInstance(IPropertyOwner *source, const RelationUIDType &relationUID) const; }; /**Exception that is used by PropertyRelationRuleBase based classes to indicate that two objects have no relation.*/ class NoPropertyRelationException : public Exception { public: mitkExceptionClassMacro(NoPropertyRelationException, Exception) }; } // namespace mitk #endif diff --git a/Modules/Core/include/mitkProportionalTimeGeometry.h b/Modules/Core/include/mitkProportionalTimeGeometry.h index 699ed702a9..48ff6563d0 100644 --- a/Modules/Core/include/mitkProportionalTimeGeometry.h +++ b/Modules/Core/include/mitkProportionalTimeGeometry.h @@ -1,260 +1,260 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef ProportionalTimeGeometry_h #define ProportionalTimeGeometry_h // MITK #include #include #include #include namespace mitk { /** * \brief Organizes geometries over proportional time steps * * For this TimeGeometry implementation it is assumed that * the durations of the time steps are equidistant, e.g. * the durations of the time steps in one ProportionalTimeGeometry * are the same. The geometries of the time steps are independent, * and not linked to each other. Since the timeBounds of the * geometries are different for each time step it is not possible * to set the same geometry to different time steps. Instead * copies should be used. * * \addtogroup geometry */ class MITKCORE_EXPORT ProportionalTimeGeometry : public TimeGeometry { public: mitkClassMacro(ProportionalTimeGeometry, TimeGeometry); ProportionalTimeGeometry(); typedef ProportionalTimeGeometry self; itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * \brief Returns the number of time steps. * * Returns the number of time steps for which * geometries are saved. The number of time steps * is also the upper bound of the time steps. The * minimum time steps is always 0. */ TimeStepType CountTimeSteps() const override; /** * \brief Returns the first time point for which the object is valid. * * Returns the first valid time point for this geometry. If only one * time steps available it usually goes from -max to +max. The time point * is given in ms. */ TimePointType GetMinimumTimePoint() const override; /** * \brief Returns the last time point for which the object is valid * - * Gives the last time point for which a valid geometrie is saved in + * Gives the last time point for which a valid geometry is saved in * this time geometry. The time point is given in ms. */ TimePointType GetMaximumTimePoint() const override; /** * \brief Returns the first time point for which the object is valid. * * Returns the first valid time point for the given TimeStep. The time point * is given in ms. */ TimePointType GetMinimumTimePoint(TimeStepType step) const override; /** * \brief Returns the last time point for which the object is valid * * Gives the last time point for the Geometry specified by the given TimeStep. The time point is given in ms. */ TimePointType GetMaximumTimePoint(TimeStepType step) const override; /** * \brief Get the time bounds (in ms) */ TimeBounds GetTimeBounds() const override; /** * \brief Get the time bounds for the given TimeStep (in ms) */ TimeBounds GetTimeBounds(TimeStepType step) const override; /** * \brief Tests if a given time point is covered by this object * * Returns true if a geometry can be returned for the given time * point and falls if not. The time point must be given in ms. */ bool IsValidTimePoint(TimePointType timePoint) const override; /** - * \brief Test for the given time step if a geometry is availible + * \brief Test for the given time step if a geometry is available * * Returns true if a geometry is defined for the given time step. * Otherwise false is returned. - * The time step is defined as positiv number. + * The time step is defined as positive number. */ bool IsValidTimeStep(TimeStepType timeStep) const override; /** * \brief Converts a time step to a time point * * Converts a time step to a time point in a way that * the new time point indicates the same geometry as the time step. * If the original time steps does not point to a valid geometry, * a time point is calculated that also does not point to a valid * geometry, but no exception is raised. */ TimePointType TimeStepToTimePoint(TimeStepType timeStep) const override; /** * \brief Converts a time point to the corresponding time step * * Converts a time point to a time step in a way that * the new time step indicates the same geometry as the time point. - * If a negativ invalid time point is given always time step 0 is - * returned. If an positiv invalid time step is given an invalid + * If a negative invalid time point is given always time step 0 is + * returned. If an positive invalid time step is given an invalid * time step will be returned. */ TimeStepType TimePointToTimeStep(TimePointType timePoint) const override; /** * \brief Returns the geometry which corresponds to the given time step * * Returns a clone of the geometry which defines the given time step. If * the given time step is invalid an null-pointer is returned. */ BaseGeometry::Pointer GetGeometryCloneForTimeStep(TimeStepType timeStep) const override; /** * \brief Returns the geometry which corresponds to the given time point * * Returns the geometry which defines the given time point. If * the given time point is invalid an null-pointer is returned. * * If the returned geometry is changed this will affect the saved * geometry. */ BaseGeometry::Pointer GetGeometryForTimePoint(TimePointType timePoint) const override; /** * \brief Returns the geometry which corresponds to the given time step * * Returns the geometry which defines the given time step. If * the given time step is invalid an null-pointer is returned. * * If the returned geometry is changed this will affect the saved * geometry. */ BaseGeometry::Pointer GetGeometryForTimeStep(TimeStepType timeStep) const override; /** - * \brief Tests if all necessary informations are set and the object is valid + * \brief Tests if all necessary information are set and the object is valid */ bool IsValid() const override; /** - * \brief Initilizes a new object with one time steps which contains an empty geometry. + * \brief Initializes a new object with one time steps which contains an empty geometry. */ void Initialize() override; /** * \brief Expands the time geometry to the given number of time steps. * * Initializes the new time steps with empty geometries if no timesteps * in the geometry so far. Otherwise fills the new times steps with * clones of the first time step. * Shrinking is not supported. */ void Expand(TimeStepType size) override; /** * \brief Sets the geometry for the given time step * * This method does not afflict other time steps, since the geometry for * each time step is saved individually. */ void SetTimeStepGeometry(BaseGeometry *geometry, TimeStepType timeStep) override; /** * \brief Replaces the geometry instances with clones of the passed geometry. * * Replaces the geometries of all time steps with clones of the passed * geometry. Replacement strategy depends on the implementation of TimeGeometry * sub class. * @remark The time points itself stays untouched. Use this method if you want * to change the spatial properties of a TimeGeometry and preserve the time * "grid". */ void ReplaceTimeStepGeometries(const BaseGeometry *geometry) override; /** * \brief Makes a deep copy of the current object */ itk::LightObject::Pointer InternalClone() const override; itkGetConstMacro(FirstTimePoint, TimePointType); itkSetMacro(FirstTimePoint, TimePointType); itkGetConstMacro(StepDuration, TimePointType); itkSetMacro(StepDuration, TimePointType); // void SetGeometryForTimeStep(TimeStepType timeStep, BaseGeometry& geometry); void ClearAllGeometries(); // void AddGeometry(BaseGeometry geometry); void ReserveSpaceForGeometries(TimeStepType numberOfGeometries); /** * \brief Initializes the TimeGeometry with equally time Step geometries * * Saves a copy for each time step. */ void Initialize(const BaseGeometry *geometry, TimeStepType timeSteps); /** * \brief Initialize the TimeGeometry with empty BaseGeometry */ void Initialize(TimeStepType timeSteps); void PrintSelf(std::ostream &os, itk::Indent indent) const override; protected: ~ProportionalTimeGeometry() override; std::vector m_GeometryVector; TimePointType m_FirstTimePoint; TimePointType m_StepDuration; }; // end class ProportialTimeGeometry /** * @brief Equal A function comparing two ProportionalTimeGeometries for being identical. * * @ingroup MITKTestingAPI * * The function compares two instances of ProportionalTimeGeometries in all their aspects. * * The parameter eps is a tolerance value for all methods which are internally used for comparison. * If you want to use different tolerance 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 Tolerance 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. */ MITKCORE_EXPORT bool Equal(const mitk::ProportionalTimeGeometry &leftHandSide, const mitk::ProportionalTimeGeometry &rightHandSide, ScalarType eps, bool verbose); } // end namespace MITK #endif // ProportionalTimeGeometry_h diff --git a/Modules/Core/include/mitkRenderingManager.h b/Modules/Core/include/mitkRenderingManager.h index 6518d232d8..2691261279 100644 --- a/Modules/Core/include/mitkRenderingManager.h +++ b/Modules/Core/include/mitkRenderingManager.h @@ -1,487 +1,487 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKRENDERINGMANAGER_H #define MITKRENDERINGMANAGER_H #include #include #include #include #include #include #include #include class vtkRenderWindow; class vtkObject; namespace mitk { class RenderingManagerFactory; class BaseGeometry; class SliceNavigationController; class BaseRenderer; class DataStorage; /** * \brief Manager for coordinating the rendering process. * * RenderingManager is a central instance retrieving and executing * RenderWindow update requests. Its main purpose is to coordinate * distributed requests which cannot be aware of each other - lacking the * knowledge of whether they are really necessary or not. For example, two * objects might determine that a specific RenderWindow needs to be updated. * This would result in one unnecessary update, if both executed the update * on their own. * * The RenderingManager addresses this by letting each such object * request an update, and waiting for other objects to possibly * issue the same request. The actual update will then only be executed at a * well-defined point in the main event loop (this may be each time after * event processing is done). * - * Convinience methods for updating all RenderWindows which have been - * registered with the RenderingManager exist. If theses methods are not + * Convenience methods for updating all RenderWindows which have been + * registered with the RenderingManager exist. If these methods are not * used, it is not required to register (add) RenderWindows prior to using * the RenderingManager. * * The methods #ForceImmediateUpdate() and #ForceImmediateUpdateAll() can * be used to force the RenderWindow update execution without any delay, * bypassing the request functionality. * * The interface of RenderingManager is platform independent. Platform * specific subclasses have to be implemented, though, to supply an - * appropriate event issueing for controlling the update execution process. + * appropriate event issuing for controlling the update execution process. * See method documentation for a description of how this can be done. * * \sa TestingRenderingManager An "empty" RenderingManager implementation which * can be used in tests etc. * */ class MITKCORE_EXPORT RenderingManager : public itk::Object { public: mitkClassMacroItkParent(RenderingManager, itk::Object); typedef std::vector RenderWindowVector; typedef std::vector FloatVector; typedef std::vector BoolVector; typedef itk::SmartPointer DataStoragePointer; enum RequestType { REQUEST_UPDATE_ALL = 0, REQUEST_UPDATE_2DWINDOWS, REQUEST_UPDATE_3DWINDOWS }; static Pointer New(); /** Set the object factory which produces the desired platform specific * RenderingManager singleton instance. */ static void SetFactory(RenderingManagerFactory *factory); /** Get the object factory which produces the platform specific * RenderingManager instances. */ static const RenderingManagerFactory *GetFactory(); /** Returns true if a factory has already been set. */ static bool HasFactory(); /** Get the RenderingManager singleton instance. */ static RenderingManager *GetInstance(); /** Returns true if the singleton instance does already exist. */ static bool IsInstantiated(); /** Adds a RenderWindow. This is required if the methods #RequestUpdateAll * or #ForceImmediateUpdate are to be used. */ void AddRenderWindow(vtkRenderWindow *renderWindow); /** Removes a RenderWindow. */ void RemoveRenderWindow(vtkRenderWindow *renderWindow); /** Get a list of all registered RenderWindows */ const RenderWindowVector &GetAllRegisteredRenderWindows(); /** Requests an update for the specified RenderWindow, to be executed as * soon as the main loop is ready for rendering. */ void RequestUpdate(vtkRenderWindow *renderWindow); /** Immediately executes an update of the specified RenderWindow. */ void ForceImmediateUpdate(vtkRenderWindow *renderWindow); /** Requests all currently registered RenderWindows to be updated. * If only 2D or 3D windows should be updated, this can be specified * via the parameter requestType. */ void RequestUpdateAll(RequestType type = REQUEST_UPDATE_ALL); /** Immediately executes an update of all registered RenderWindows. * If only 2D or 3D windows should be updated, this can be specified * via the parameter requestType. */ void ForceImmediateUpdateAll(RequestType type = REQUEST_UPDATE_ALL); /** * @brief Initialize the render windows by the aggregated geometry of all objects that are held in * the data storage. * * @param dataStorage The data storage from which the bounding object can be retrieved */ virtual void InitializeViewsByBoundingObjects(const DataStorage* dataStorage); /** * @brief Initialize the render windows specified by "type" to the given geometry. * * Throws an exception if bounding box has 0 extent due to exceeding double precision range. * * @param geometry The geometry to be used to initialize / update a * render window's time and slice navigation controller * @param type The type of update request: * - REQUEST_UPDATE_ALL will initialize / update the * time and slice navigation controller of all retrieved render windows * - REQUEST_UPDATE_2DWINDOWS will only initialize / update the * time and slice navigation controller of 2D render windows * - REQUEST_UPDATE_3DWINDOWS will only initialize / update the * time and slice navigation controller of 3D render windows * @param resetCamera If this parameter is set to true, the camera controller will be * set / fit to the center of the rendered image. If set to false, only the * the slice navigation controller is reset to the geometry without changing * the camera view / position. */ virtual bool InitializeViews(const BaseGeometry *geometry, RequestType type = REQUEST_UPDATE_ALL, bool resetCamera = true); /** * @brief Initialize the render windows specified by "type" to the given geometry. * * Throws an exception if bounding box has 0 extent due to exceeding double precision range. * * @param geometry The geometry to be used to initialize / update a * render window's time- and slice navigation controller * @param type The type of update request: * - REQUEST_UPDATE_ALL will initialize / update the * time- and slice navigation controller of all retrieved render windows * - REQUEST_UPDATE_2DWINDOWS will only initialize / update the * time- and slice navigation controller of 2D render windows * - REQUEST_UPDATE_3DWINDOWS will only initialize / update the * time- and slice navigation controller of 3D render windows * @param resetCamera If this parameter is set to true, the camera controller will be * set / fit to the center of the rendered image. If set to false, only the * the slice navigation controller is reset to the geometry without changing * the camera view / position. */ virtual bool InitializeViews(const TimeGeometry *geometry, RequestType type = REQUEST_UPDATE_ALL, bool resetCamera = true); /** * @brief Initialize the render windows specified by "type" to the default viewing direction * without updating the geometry information. * * @param type The type of update request: * - REQUEST_UPDATE_ALL will initialize the * slice navigation controller of all retrieved render windows * - REQUEST_UPDATE_2DWINDOWS will only initialize the * slice navigation controller of 2D render windows * - REQUEST_UPDATE_3DWINDOWS will only initialize the * slice navigation controller of 3D render windows */ virtual bool InitializeViews(RequestType type = REQUEST_UPDATE_ALL); /** * @brief Initialize the specified render window to the given geometry. * * Throws an exception if bounding box has 0 extent due to exceeding double precision range. * - * @param renderWindow The specifid render window to update + * @param renderWindow The specific render window to update * @param geometry The geometry to be used to initialize / update the * render window's time- and slice navigation controller * @param resetCamera If this parameter is set to true, the camera controller will be * set / fit to the center of the rendered image. If set to false, only the * the slice navigation controller is reset to the geometry without changing * the camera view / position. */ virtual bool InitializeView(vtkRenderWindow *renderWindow, const BaseGeometry *geometry, bool resetCamera = true); /** * @brief Initialize the specified render window to the given geometry. * * Throws an exception if bounding box has 0 extent due to exceeding double precision range. * - * @param renderWindow The specifid render window to update + * @param renderWindow The specific render window to update * @param geometry The geometry to be used to initialize / update the * render window's time- and slice navigation controller * @param resetCamera If this parameter is set to true, the camera controller will be * set / fit to the center of the rendered image. If set to false, only the * the slice navigation controller is reset to the geometry without changing * the camera view / position. */ virtual bool InitializeView(vtkRenderWindow *renderWindow, const TimeGeometry *geometry, bool resetCamera = true); /** * @brief Initialize the specified render window to the default viewing direction * without updating the geometry information. * - * @param renderWindow The specifid render window to update + * @param renderWindow The specific render window to update */ virtual bool InitializeView(vtkRenderWindow *renderWindow); /** Gets the (global) SliceNavigationController responsible for * time-slicing. */ const SliceNavigationController *GetTimeNavigationController() const; /** Gets the (global) SliceNavigationController responsible for * time-slicing. */ SliceNavigationController *GetTimeNavigationController(); ~RenderingManager() override; /** Executes all pending requests. This method has to be called by the * system whenever a RenderingManager induced request event occurs in * the system pipeline (see concrete RenderingManager implementations). */ virtual void ExecutePendingRequests(); bool IsRendering() const; void AbortRendering(); /** En-/Disable LOD increase globally. */ itkSetMacro(LODIncreaseBlocked, bool); /** En-/Disable LOD increase globally. */ itkGetMacro(LODIncreaseBlocked, bool); /** En-/Disable LOD increase globally. */ itkBooleanMacro(LODIncreaseBlocked); /** En-/Disable LOD abort mechanism. */ itkSetMacro(LODAbortMechanismEnabled, bool); /** En-/Disable LOD abort mechanism. */ itkGetMacro(LODAbortMechanismEnabled, bool); /** En-/Disable LOD abort mechanism. */ itkBooleanMacro(LODAbortMechanismEnabled); /** Force a sub-class to start a timer for a pending hires-rendering request */ virtual void StartOrResetTimer(){}; /** To be called by a sub-class from a timer callback */ void ExecutePendingHighResRenderingRequest(); virtual void DoStartRendering(){}; virtual void DoMonitorRendering(){}; virtual void DoFinishAbortRendering(){}; int GetNextLOD(BaseRenderer *renderer); /** Set current LOD (nullptr means all renderers)*/ void SetMaximumLOD(unsigned int max); void SetShading(bool state, unsigned int lod); bool GetShading(unsigned int lod); void SetClippingPlaneStatus(bool status); bool GetClippingPlaneStatus(); void SetShadingValues(float ambient, float diffuse, float specular, float specpower); FloatVector &GetShadingValues(); /** Returns a property list */ PropertyList::Pointer GetPropertyList() const; /** Returns a property from m_PropertyList */ BaseProperty *GetProperty(const char *propertyKey) const; /** Sets or adds (if not present) a property in m_PropertyList */ void SetProperty(const char *propertyKey, BaseProperty *propertyValue); /** * \brief Setter for internal DataStorage * * Sets the DataStorage that is used internally. This instance holds all DataNodes that are * rendered by the registered BaseRenderers. * * If this DataStorage is changed at runtime by calling SetDataStorage(), * all currently registered BaseRenderers are automatically given the correct instance. * When a new BaseRenderer is added, it is automatically initialized with the currently active DataStorage. */ void SetDataStorage(DataStorage *storage); /** * \brief Getter for internal DataStorage * * Returns the DataStorage that is used internally. This instance holds all DataNodes that are * rendered by the registered BaseRenderers. */ itkGetMacro(DataStorage, DataStorage*); itkGetConstMacro(DataStorage, DataStorage*); /** * @brief Sets a flag to the given renderwindow to indicated that it has the focus e.g. has been clicked recently. * @param focusWindow */ void SetRenderWindowFocus(vtkRenderWindow *focusWindow); itkGetMacro(FocusedRenderWindow, vtkRenderWindow *); itkSetMacro(ConstrainedPanningZooming, bool); itkGetConstMacro(ConstrainedPanningZooming, bool); void SetAntiAliasing(AntiAliasing antiAliasing); itkGetConstMacro(AntiAliasing, AntiAliasing); protected: enum { RENDERING_INACTIVE = 0, RENDERING_REQUESTED, RENDERING_INPROGRESS }; RenderingManager(); /** Abstract method for generating a system specific event for rendering * request. This method is called whenever an update is requested */ virtual void GenerateRenderingRequestEvent() = 0; virtual void InitializePropertyList(); bool m_UpdatePending; typedef std::map RendererIntMap; typedef std::map RendererBoolMap; RendererBoolMap m_RenderingAbortedMap; RendererIntMap m_NextLODMap; unsigned int m_MaxLOD; bool m_LODIncreaseBlocked; bool m_LODAbortMechanismEnabled; BoolVector m_ShadingEnabled; bool m_ClippingPlaneEnabled; FloatVector m_ShadingValues; static void RenderingStartCallback(vtkObject *caller, unsigned long eid, void *clientdata, void *calldata); static void RenderingProgressCallback(vtkObject *caller, unsigned long eid, void *clientdata, void *calldata); static void RenderingEndCallback(vtkObject *caller, unsigned long eid, void *clientdata, void *calldata); typedef std::map RenderWindowList; RenderWindowList m_RenderWindowList; RenderWindowVector m_AllRenderWindows; struct RenderWindowCallbacks { vtkCallbackCommand *commands[3u]; }; typedef std::map RenderWindowCallbacksList; RenderWindowCallbacksList m_RenderWindowCallbacksList; itk::SmartPointer m_TimeNavigationController; static RenderingManager::Pointer s_Instance; static RenderingManagerFactory *s_RenderingManagerFactory; PropertyList::Pointer m_PropertyList; DataStoragePointer m_DataStorage; bool m_ConstrainedPanningZooming; private: /** * @brief Initialize the specified renderer to the given geometry. * - * @param baseRenderer The specifid renderer to update + * @param baseRenderer The specific renderer to update * @param geometry The geometry to be used to initialize / update the * render window's slice navigation controller * @param boundingBoxInitialized If this parameter is set to true, the slice navigation controller will be * initialized / updated with the given geometry. If set to false, the geometry * of the slice navigation controller is not updated. * @param mapperID The mapper ID is used to define if the given renderer is a 2D or a 3D renderer. * In case of a 2D renderer and if "boundingBoxInitialized" is set to true (slice * navigation controller will be updated with a new geometry), the position of the * slice navigation controller is set to the center slice. * @param resetCamera If this parameter is set to true, the camera controller will be * set / fit to the center of the rendered image. If set to false, only the * the slice navigation controller is reset to the geometry without changing * the camera view / position. */ void InternalViewInitialization(BaseRenderer *baseRenderer, const TimeGeometry *geometry, bool boundingBoxInitialized, int mapperID, bool resetCamera); /** * @brief Extend the bounding box of the given geometry to make sure the bounding box has an extent bigger than * zero in any direction. * * @param originalGeometry The original geometry to be extended * @param modifiedGeometry The modified geometry where the new bounds (extended bounding box) are used / set */ bool ExtendGeometryForBoundingBox(const TimeGeometry* originalGeometry, TimeGeometry::Pointer& modifiedGeometry); vtkRenderWindow *m_FocusedRenderWindow; AntiAliasing m_AntiAliasing; }; #pragma GCC visibility push(default) itkEventMacroDeclaration(RenderingManagerEvent, itk::AnyEvent); itkEventMacroDeclaration(RenderingManagerViewsInitializedEvent, RenderingManagerEvent); #pragma GCC visibility pop itkEventMacroDeclaration(FocusChangedEvent, itk::AnyEvent); /** - * Generic RenderingManager implementation for "non-rendering-plattform", + * Generic RenderingManager implementation for "non-rendering-platform", * e.g. for tests. Its factory (TestingRenderingManagerFactory) is * automatically on start-up and is used by default if not other * RenderingManagerFactory is instantiated explicitly thereafter. * (see mitkRenderingManager.cpp) */ class MITKCORE_EXPORT TestingRenderingManager : public RenderingManager { public: mitkClassMacro(TestingRenderingManager, RenderingManager); itkFactorylessNewMacro(Self); itkCloneMacro(Self); protected: void GenerateRenderingRequestEvent() override {}; }; } // namespace mitk #endif // MITKRENDERINGMANAGER_H diff --git a/Modules/Core/include/mitkSliceNavigationController.h b/Modules/Core/include/mitkSliceNavigationController.h index 9b262c68e0..dd2548c92e 100644 --- a/Modules/Core/include/mitkSliceNavigationController.h +++ b/Modules/Core/include/mitkSliceNavigationController.h @@ -1,472 +1,472 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef SLICENAVIGATIONCONTROLLER_H_HEADER_INCLUDED_C1C55A2F #define SLICENAVIGATIONCONTROLLER_H_HEADER_INCLUDED_C1C55A2F #include "mitkBaseController.h" #include "mitkMessage.h" #include "mitkRenderingManager.h" #include "mitkTimeGeometry.h" #include #pragma GCC visibility push(default) #include #pragma GCC visibility pop #include "mitkDataStorage.h" #include "mitkRestorePlanePositionOperation.h" #include #include namespace mitk { #define mitkTimeGeometryEventMacro(classname, super) \ class MITKCORE_EXPORT classname : public super \ { \ public: \ typedef classname Self; \ typedef super Superclass; \ classname(TimeGeometry *aTimeGeometry, unsigned int aPos) : Superclass(aTimeGeometry, aPos) {} \ virtual ~classname() {} \ virtual const char *GetEventName() const { return #classname; } \ virtual bool CheckEvent(const ::itk::EventObject *e) const { return dynamic_cast(e); } \ virtual ::itk::EventObject *MakeObject() const { return new Self(GetTimeGeometry(), GetPos()); } \ private: \ void operator=(const Self &); \ } class PlaneGeometry; class BaseGeometry; class BaseRenderer; /** * \brief Controls the selection of the slice the associated BaseRenderer * will display * * A SliceNavigationController takes a BaseGeometry or a TimeGeometry as input world geometry * (TODO what are the exact requirements?) and generates a TimeGeometry * as output. The TimeGeometry holds a number of SlicedGeometry3Ds and * these in turn hold a series of PlaneGeometries. One of these PlaneGeometries is * selected as world geometry for the BaseRenderers associated to 2D views. * * The SliceNavigationController holds has Steppers (one for the slice, a * second for the time step), which control the selection of a single * PlaneGeometry from the TimeGeometry. SliceNavigationController generates * ITK events to tell observers, like a BaseRenderer, when the selected slice * or timestep changes. * * Example: * \code * // Initialization * sliceCtrl = mitk::SliceNavigationController::New(); * * // Tell the navigator the geometry to be sliced (with geometry a * // BaseGeometry::ConstPointer) * sliceCtrl->SetInputWorldGeometry3D(geometry.GetPointer()); * * // Tell the navigator in which direction it shall slice the data * sliceCtrl->SetViewDirection(mitk::SliceNavigationController::Axial); * * // Connect one or more BaseRenderer to this navigator, i.e.: events sent * // by the navigator when stepping through the slices (e.g. by * // sliceCtrl->GetSlice()->Next()) will be received by the BaseRenderer * // (in this example only slice-changes, see also ConnectGeometryTimeEvent * // and ConnectGeometryEvents.) * sliceCtrl->ConnectGeometrySliceEvent(renderer.GetPointer()); * * //create a world geometry and send the information to the connected renderer(s) * sliceCtrl->Update(); * \endcode * * * You can connect visible navigators to a SliceNavigationController, e.g., a * QmitkSliderNavigator (for Qt): * * \code * // Create the visible navigator (a slider with a spin-box) * QmitkSliderNavigator* navigator = * new QmitkSliderNavigator(parent, "slidernavigator"); * * // Connect the navigator to the slice-stepper of the - * // SliceNavigationController. For initialization (position, mininal and + * // SliceNavigationController. For initialization (position, minimal and * // maximal values) the values of the SliceNavigationController are used. * // Thus, accessing methods of a navigator is normally not necessary, since * // everything can be set via the (Qt-independent) SliceNavigationController. * // The QmitkStepperAdapter converts the Qt-signals to Qt-independent * // itk-events. * new QmitkStepperAdapter(navigator, sliceCtrl->GetSlice(), "navigatoradaptor"); * \endcode * * If you do not want that all renderwindows are updated when a new slice is * selected, you can use a specific RenderingManager, which updates only those * renderwindows that should be updated. This is sometimes useful when a 3D view * does not need to be updated when the slices in some 2D views are changed. * QmitkSliderNavigator (for Qt): * * \code * // create a specific RenderingManager * mitk::RenderingManager::Pointer myManager = mitk::RenderingManager::New(); * * // tell the RenderingManager to update only renderwindow1 and renderwindow2 * myManager->AddRenderWindow(renderwindow1); * myManager->AddRenderWindow(renderwindow2); * * // tell the SliceNavigationController of renderwindow1 and renderwindow2 * // to use the specific RenderingManager instead of the global one * renderwindow1->GetSliceNavigationController()->SetRenderingManager(myManager); * renderwindow2->GetSliceNavigationController()->SetRenderingManager(myManager); * \endcode * * \todo implement for non-evenly-timed geometry! * \ingroup NavigationControl */ class MITKCORE_EXPORT SliceNavigationController : public BaseController { public: mitkClassMacro(SliceNavigationController, BaseController); // itkFactorylessNewMacro(Self) // mitkNewMacro1Param(Self, const char *); itkNewMacro(Self); // itkCloneMacro(Self) /** * \brief Possible view directions, \a Original will uses * the PlaneGeometry instances in a SlicedGeometry3D provided * as input world geometry (by SetInputWorldGeometry3D). */ enum ViewDirection { Axial, Sagittal, Coronal, Original }; /** * \brief Set the input world geometry3D out of which the * geometries for slicing will be created. * * Any previous previous set input geometry (3D or Time) will * be ignored in future. */ void SetInputWorldGeometry3D(const mitk::BaseGeometry *geometry); itkGetConstObjectMacro(InputWorldGeometry3D, mitk::BaseGeometry); void SetInputWorldTimeGeometry(const mitk::TimeGeometry *geometry); itkGetConstObjectMacro(InputWorldTimeGeometry, mitk::TimeGeometry); /** * \brief Access the created geometry */ itkGetConstObjectMacro(CreatedWorldGeometry, mitk::TimeGeometry); /** * \brief Set the desired view directions * * \sa ViewDirection * \sa Update(ViewDirection viewDirection, bool top = true, * bool frontside = true, bool rotated = false) */ itkSetEnumMacro(ViewDirection, ViewDirection); itkGetEnumMacro(ViewDirection, ViewDirection); /** * \brief Set the default view direction * * This is used to re-initialize the view direction of the SNC to the * default value with SetViewDirectionToDefault() * * \sa ViewDirection * \sa Update(ViewDirection viewDirection, bool top = true, * bool frontside = true, bool rotated = false) */ itkSetEnumMacro(DefaultViewDirection, ViewDirection); itkGetEnumMacro(DefaultViewDirection, ViewDirection); const char *GetViewDirectionAsString() const; virtual void SetViewDirectionToDefault(); /** * \brief Do the actual creation and send it to the connected * observers (renderers) * */ virtual void Update(); /** * \brief Extended version of Update, additionally allowing to * specify the direction/orientation of the created geometry. * */ virtual void Update(ViewDirection viewDirection, bool top = true, bool frontside = true, bool rotated = false); /** * \brief Send the created geometry to the connected * observers (renderers) * * Called by Update(). */ virtual void SendCreatedWorldGeometry(); /** * \brief Tell observers to re-read the currently selected 2D geometry * */ virtual void SendCreatedWorldGeometryUpdate(); /** * \brief Send the currently selected slice to the connected * observers (renderers) * * Called by Update(). */ virtual void SendSlice(); /** * \brief Send the currently selected time to the connected * observers (renderers) * * Called by Update(). */ virtual void SendTime(); class MITKCORE_EXPORT TimeGeometryEvent : public itk::AnyEvent { public: typedef TimeGeometryEvent Self; typedef itk::AnyEvent Superclass; TimeGeometryEvent(TimeGeometry *aTimeGeometry, unsigned int aPos) : m_TimeGeometry(aTimeGeometry), m_Pos(aPos) {} ~TimeGeometryEvent() override {} const char *GetEventName() const override { return "TimeGeometryEvent"; } bool CheckEvent(const ::itk::EventObject *e) const override { return dynamic_cast(e); } ::itk::EventObject *MakeObject() const override { return new Self(m_TimeGeometry, m_Pos); } TimeGeometry *GetTimeGeometry() const { return m_TimeGeometry; } unsigned int GetPos() const { return m_Pos; } private: TimeGeometry::Pointer m_TimeGeometry; unsigned int m_Pos; // TimeGeometryEvent(const Self&); void operator=(const Self &); // just hide }; mitkTimeGeometryEventMacro(GeometrySendEvent, TimeGeometryEvent); mitkTimeGeometryEventMacro(GeometryUpdateEvent, TimeGeometryEvent); mitkTimeGeometryEventMacro(GeometryTimeEvent, TimeGeometryEvent); mitkTimeGeometryEventMacro(GeometrySliceEvent, TimeGeometryEvent); template void ConnectGeometrySendEvent(T *receiver) { typedef typename itk::ReceptorMemberCommand::Pointer ReceptorMemberCommandPointer; ReceptorMemberCommandPointer eventReceptorCommand = itk::ReceptorMemberCommand::New(); eventReceptorCommand->SetCallbackFunction(receiver, &T::SetGeometry); unsigned long tag = AddObserver(GeometrySendEvent(nullptr, 0), eventReceptorCommand); m_ReceiverToObserverTagsMap[static_cast(receiver)].push_back(tag); } template void ConnectGeometryUpdateEvent(T *receiver) { typedef typename itk::ReceptorMemberCommand::Pointer ReceptorMemberCommandPointer; ReceptorMemberCommandPointer eventReceptorCommand = itk::ReceptorMemberCommand::New(); eventReceptorCommand->SetCallbackFunction(receiver, &T::UpdateGeometry); unsigned long tag = AddObserver(GeometryUpdateEvent(nullptr, 0), eventReceptorCommand); m_ReceiverToObserverTagsMap[static_cast(receiver)].push_back(tag); } template void ConnectGeometrySliceEvent(T *receiver, bool connectSendEvent = true) { typedef typename itk::ReceptorMemberCommand::Pointer ReceptorMemberCommandPointer; ReceptorMemberCommandPointer eventReceptorCommand = itk::ReceptorMemberCommand::New(); eventReceptorCommand->SetCallbackFunction(receiver, &T::SetGeometrySlice); unsigned long tag = AddObserver(GeometrySliceEvent(nullptr, 0), eventReceptorCommand); m_ReceiverToObserverTagsMap[static_cast(receiver)].push_back(tag); if (connectSendEvent) ConnectGeometrySendEvent(receiver); } template void ConnectGeometryTimeEvent(T *receiver, bool connectSendEvent = true) { typedef typename itk::ReceptorMemberCommand::Pointer ReceptorMemberCommandPointer; ReceptorMemberCommandPointer eventReceptorCommand = itk::ReceptorMemberCommand::New(); eventReceptorCommand->SetCallbackFunction(receiver, &T::SetGeometryTime); unsigned long tag = AddObserver(GeometryTimeEvent(nullptr, 0), eventReceptorCommand); m_ReceiverToObserverTagsMap[static_cast(receiver)].push_back(tag); if (connectSendEvent) ConnectGeometrySendEvent(receiver); } template void ConnectGeometryEvents(T *receiver) { // connect sendEvent only once ConnectGeometrySliceEvent(receiver, false); ConnectGeometryTimeEvent(receiver); } // use a templated method to get the right offset when casting to void* template void Disconnect(T *receiver) { auto i = m_ReceiverToObserverTagsMap.find(static_cast(receiver)); if (i == m_ReceiverToObserverTagsMap.end()) return; const std::list &tags = i->second; for (auto tagIter = tags.begin(); tagIter != tags.end(); ++tagIter) { RemoveObserver(*tagIter); } m_ReceiverToObserverTagsMap.erase(i); } Message1 SetCrosshairEvent; /** * \brief To connect multiple SliceNavigationController, we can * act as an observer ourselves: implemented interface * \warning not implemented */ virtual void SetGeometry(const itk::EventObject &geometrySliceEvent); /** * \brief To connect multiple SliceNavigationController, we can * act as an observer ourselves: implemented interface */ virtual void SetGeometrySlice(const itk::EventObject &geometrySliceEvent); /** * \brief To connect multiple SliceNavigationController, we can * act as an observer ourselves: implemented interface */ virtual void SetGeometryTime(const itk::EventObject &geometryTimeEvent); /** \brief Positions the SNC according to the specified point */ void SelectSliceByPoint(const mitk::Point3D &point); /** \brief Returns the TimeGeometry created by the SNC. */ mitk::TimeGeometry *GetCreatedWorldGeometry(); /** \brief Returns the BaseGeometry of the currently selected time step. */ const mitk::BaseGeometry *GetCurrentGeometry3D(); /** \brief Returns the currently selected Plane in the current * BaseGeometry (if existent). */ const mitk::PlaneGeometry *GetCurrentPlaneGeometry(); /** \brief Sets the BaseRenderer associated with this SNC (if any). While * the BaseRenderer is not directly used by SNC, this is a convenience * method to enable BaseRenderer access via the SNC. */ void SetRenderer(BaseRenderer *renderer); /** \brief Gets the BaseRenderer associated with this SNC (if any). While * the BaseRenderer is not directly used by SNC, this is a convenience * method to enable BaseRenderer access via the SNC. Returns nullptr if no * BaseRenderer has been specified*/ BaseRenderer *GetRenderer() const; /** \brief Re-orients the slice stack. All slices will be oriented to the given normal vector. The given point (world coordinates) defines the selected slice. Careful: The resulting axis vectors are not clearly defined this way. If you want to define them clearly, use ReorientSlices (const mitk::Point3D &point, const mitk::Vector3D &axisVec0, const mitk::Vector3D &axisVec1). */ void ReorientSlices(const mitk::Point3D &point, const mitk::Vector3D &normal); /** \brief Re-orients the slice stack so that all planes are oriented according to the * given axis vectors. The given Point eventually defines selected slice. */ void ReorientSlices(const mitk::Point3D &point, const mitk::Vector3D &axisVec0, const mitk::Vector3D &axisVec1); void ExecuteOperation(Operation *operation) override; /** * \brief Feature option to lock planes during mouse interaction. * This option flag disables the mouse event which causes the center * cross to move near by. */ itkSetMacro(SliceLocked, bool); itkGetMacro(SliceLocked, bool); itkBooleanMacro(SliceLocked); /** * \brief Feature option to lock slice rotation. * * This option flag disables separately the rotation of a slice which is * implemented in mitkSliceRotator. */ itkSetMacro(SliceRotationLocked, bool); itkGetMacro(SliceRotationLocked, bool); itkBooleanMacro(SliceRotationLocked); /** * \brief Adjusts the numerical range of the slice stepper according to * the current geometry orientation of this SNC's SlicedGeometry. */ void AdjustSliceStepperRange(); /** \brief Convenience method that returns the time step currently selected by the controller.*/ TimeStepType GetSelectedTimeStep() const; /** \brief Convenience method that returns the time point that corresponds to the selected * time step. The conversion is done using the time geometry of the SliceNavigationController. * If the time geometry is not yet set, this function will always return 0.0.*/ TimePointType GetSelectedTimePoint() const; protected: SliceNavigationController(); ~SliceNavigationController() override; mitk::BaseGeometry::ConstPointer m_InputWorldGeometry3D; mitk::TimeGeometry::ConstPointer m_InputWorldTimeGeometry; mitk::TimeGeometry::Pointer m_CreatedWorldGeometry; ViewDirection m_ViewDirection; ViewDirection m_DefaultViewDirection; mitk::RenderingManager::Pointer m_RenderingManager; mitk::BaseRenderer *m_Renderer; itkSetMacro(Top, bool); itkGetMacro(Top, bool); itkBooleanMacro(Top); itkSetMacro(FrontSide, bool); itkGetMacro(FrontSide, bool); itkBooleanMacro(FrontSide); itkSetMacro(Rotated, bool); itkGetMacro(Rotated, bool); itkBooleanMacro(Rotated); bool m_Top; bool m_FrontSide; bool m_Rotated; bool m_BlockUpdate; bool m_SliceLocked; bool m_SliceRotationLocked; unsigned int m_OldPos; typedef std::map> ObserverTagsMapType; ObserverTagsMapType m_ReceiverToObserverTagsMap; }; } // namespace mitk #endif /* SLICENAVIGATIONCONTROLLER_H_HEADER_INCLUDED_C1C55A2F */ diff --git a/Modules/Core/include/mitkSlicedGeometry3D.h b/Modules/Core/include/mitkSlicedGeometry3D.h index 573541b549..da2c611722 100644 --- a/Modules/Core/include/mitkSlicedGeometry3D.h +++ b/Modules/Core/include/mitkSlicedGeometry3D.h @@ -1,328 +1,328 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKSLICEDGEOMETRY3D_H_HEADER_INCLUDED_C1EBD0AD #define MITKSLICEDGEOMETRY3D_H_HEADER_INCLUDED_C1EBD0AD #include "mitkBaseGeometry.h" #include "mitkPlaneGeometry.h" namespace mitk { class SliceNavigationController; class NavigationController; /** \brief Describes the geometry of a data object consisting of slices. * * A PlaneGeometry can be requested for each slice. In the case of * \em evenly-spaced, \em plane geometries (m_EvenlySpaced==true), * only the 2D-geometry of the first slice has to be set (to an instance of * PlaneGeometry). The 2D geometries of the other slices are calculated * by shifting the first slice in the direction m_DirectionVector by * m_Spacing.z * sliceNumber. The m_Spacing member (which is only - * relevant in the case m_EvenlySpaced==true) descibes the size of a voxel + * relevant in the case m_EvenlySpaced==true) describes the size of a voxel * (in mm), i.e., m_Spacing.x is the voxel width in the x-direction of the * plane. It is derived from the reference geometry of this SlicedGeometry3D, * which usually would be the global geometry describing how datasets are to * be resliced. * * By default, slices are oriented in the direction of one of the main axes * (x, y, z). However, by means of rotation, it is possible to realign the * slices in any possible direction. In case of an inclined plane, the spacing * is derived as a product of the (regular) geometry spacing and the direction * vector of the plane. * * SlicedGeometry3D and the associated PlaneGeometries 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 * * \sa itk::ProcessObject::GenerateOutputInformation(), * \sa itk::DataObject::CopyInformation() and * \a itk::DataObject::UpdateOutputInformation(). * * Rule: everything is in mm (or ms for temporal information) if not * stated otherwise. * * \warning The hull (i.e., transform, bounding-box and * time-bounds) is only guaranteed to be up-to-date after calling * UpdateInformation(). * * \ingroup Geometry */ class MITKCORE_EXPORT SlicedGeometry3D : public mitk::BaseGeometry { public: mitkClassMacro(SlicedGeometry3D, BaseGeometry); /** Method for creation through the object factory. */ itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * \brief Returns the PlaneGeometry of the slice (\a s). * * If (a) m_EvenlySpaced==true, (b) we don't have a PlaneGeometry stored * for the requested slice, and (c) the first slice (s=0) * is a PlaneGeometry instance, then we calculate the geometry of the * requested as the plane of the first slice shifted by m_Spacing[3]*s * in the direction of m_DirectionVector. * * \warning The PlaneGeometries are not necessarily up-to-date and not even * initialized. * * The PlaneGeometries 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 * * \sa itk::ProcessObject::GenerateOutputInformation(), * \sa itk::DataObject::CopyInformation() and * \sa itk::DataObject::UpdateOutputInformation(). */ virtual mitk::PlaneGeometry *GetPlaneGeometry(int s) const; /** * \deprecatedSince{2014_10} Please use GetPlaneGeometry */ DEPRECATED(const PlaneGeometry *GetGeometry2D(int s)) { return GetPlaneGeometry(s); } /** * \deprecatedSince{2014_10} Please use SetPlaneGeometry */ DEPRECATED(void SetGeometry2D(PlaneGeometry *geo, int s)) { SetPlaneGeometry(geo, s); } //##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. void ChangeImageGeometryConsideringOriginOffset(const bool isAnImageGeometry) override; // virtual void SetTimeBounds( const mitk::TimeBounds& timebounds ); const mitk::BoundingBox *GetBoundingBox() const override; /** * \brief Get the number of slices */ itkGetConstMacro(Slices, unsigned int); /** * \brief Set PlaneGeometry of slice \a s. */ virtual bool SetPlaneGeometry(mitk::PlaneGeometry *geometry2D, int s); /** * \brief Check whether a slice exists */ virtual bool IsValidSlice(int s = 0) const; virtual const BaseGeometry* GetReferenceGeometry() const; virtual void SetReferenceGeometry(const BaseGeometry *referenceGeometry); bool HasReferenceGeometry() const; /** * \brief Set the SliceNavigationController corresponding to this sliced * geometry. * * The SNC needs to be informed when the number of slices in the geometry * changes, which can occur whenthe slices are re-oriented by rotation. */ virtual void SetSliceNavigationController(mitk::SliceNavigationController *snc); mitk::SliceNavigationController *GetSliceNavigationController(); /** * \brief Set/Get whether the SlicedGeometry3D is evenly-spaced * (m_EvenlySpaced) * * If (a) m_EvenlySpaced==true, (b) we don't have a PlaneGeometry stored for * the requested slice, and (c) the first slice (s=0) is a PlaneGeometry * instance, then we calculate the geometry of the requested as the plane * of the first slice shifted by m_Spacing.z * s in the direction of * m_DirectionVector. * * \sa GetPlaneGeometry */ itkGetConstMacro(EvenlySpaced, bool); virtual void SetEvenlySpaced(bool on = true); /** * \brief Set/Get the vector between slices for the evenly-spaced case * (m_EvenlySpaced==true). * * If the direction-vector is (0,0,0) (the default) and the first * 2D geometry is a PlaneGeometry, then the direction-vector will be * calculated from the plane normal. * * \sa m_DirectionVector */ virtual void SetDirectionVector(const mitk::Vector3D &directionVector); itkGetConstMacro(DirectionVector, const mitk::Vector3D &); itk::LightObject::Pointer InternalClone() const override; #ifndef SWIG static const std::string SLICES; const static std::string DIRECTION_VECTOR; const static std::string EVENLY_SPACED; #endif // !SWIG /** * \brief Tell this instance how many PlaneGeometries it shall manage. Bounding * box and the PlaneGeometries must be set additionally by calling the respective * methods! * * \warning Bounding box and the 2D-geometries must be set additionally: use * SetBounds(), SetGeometry(). */ virtual void InitializeSlicedGeometry(unsigned int slices); /** * \brief Completely initialize this instance as evenly-spaced with slices * parallel to the provided PlaneGeometry that is used as the first slice and * for spacing calculation. * * Initializes the bounding box according to the width/height of the * PlaneGeometry and \a slices. The spacing is calculated from the PlaneGeometry. */ virtual void InitializeEvenlySpaced(mitk::PlaneGeometry *geometry2D, unsigned int slices); /** * \brief Completely initialize this instance as evenly-spaced with slices * parallel to the provided PlaneGeometry that is used as the first slice and * for spacing calculation (except z-spacing). * * Initializes the bounding box according to the width/height of the * PlaneGeometry and \a slices. The x-/y-spacing is calculated from the * PlaneGeometry. */ virtual void InitializeEvenlySpaced(mitk::PlaneGeometry *geometry2D, mitk::ScalarType zSpacing, unsigned int slices); /** * \brief Completely initialize this instance as evenly-spaced plane slices * parallel to a side of the provided BaseGeometry and using its spacing * information. * * Initializes the bounding box according to the width/height of the * BaseGeometry and the number of slices according to * BaseGeometry::GetExtent(2). * * \param geometry3D * \param planeorientation side parallel to which the slices will be oriented * \param top if \a true, create plane at top, otherwise at bottom * (for PlaneOrientation Axial, for other plane locations respectively) * \param frontside defines the side of the plane (the definition of * front/back is somewhat arbitrary) * * \param rotated rotates the plane by 180 degree around its normal (the * definition of rotated vs not rotated is somewhat arbitrary) */ virtual void InitializePlanes(const mitk::BaseGeometry *geometry3D, mitk::PlaneGeometry::PlaneOrientation planeorientation, bool top = true, bool frontside = true, bool rotated = false); void SetImageGeometry(const bool isAnImageGeometry) override; void ExecuteOperation(Operation *operation) override; static double CalculateSpacing(const mitk::Vector3D &spacing, const mitk::Vector3D &d); protected: SlicedGeometry3D(); SlicedGeometry3D(const SlicedGeometry3D &other); ~SlicedGeometry3D() override; /** * Reinitialize plane stack after rotation. More precisely, the first plane * of the stack needs to spatially aligned, in two respects: * * 1. Re-alignment with respect to the dataset center; this is necessary * since the distance from the first plane to the center could otherwise * continuously decrease or increase. * 2. Re-alignment with respect to a given reference point; the reference * point is a location which the user wants to be exactly touched by one * plane of the plane stack. The first plane is minimally shifted to * ensure this touching. Usually, the reference point would be the * point around which the geometry is rotated. */ virtual void ReinitializePlanes(const Point3D ¢er, const Point3D &referencePoint); ScalarType GetLargestExtent(const BaseGeometry *geometry); void PrintSelf(std::ostream &os, itk::Indent indent) const override; /** Calculate "directed spacing", i.e. the spacing in directions * non-orthogonal to the coordinate axes. This is done via the * ellipsoid equation. */ double CalculateSpacing(const mitk::Vector3D &direction) const; /** The extent of the slice stack, i.e. the number of slices, depends on the * plane normal. For rotated geometries, the geometry's transform needs to * be accounted in this calculation. */ mitk::Vector3D AdjustNormal(const mitk::Vector3D &normal) const; /** * Container for the 2D-geometries contained within this SliceGeometry3D. */ mutable std::vector m_PlaneGeometries; /** * If (a) m_EvenlySpaced==true, (b) we don't have a PlaneGeometry stored * for the requested slice, and (c) the first slice (s=0) * is a PlaneGeometry instance, then we calculate the geometry of the * requested as the plane of the first slice shifted by m_Spacing.z*s * in the direction of m_DirectionVector. * * \sa GetPlaneGeometry */ bool m_EvenlySpaced; /** * Vector between slices for the evenly-spaced case (m_EvenlySpaced==true). * If the direction-vector is (0,0,0) (the default) and the first * 2D geometry is a PlaneGeometry, then the direction-vector will be * calculated from the plane normal. */ mutable mitk::Vector3D m_DirectionVector; - /** Number of slices this SliceGeometry3D is descibing. */ + /** Number of slices this SliceGeometry3D is describing. */ unsigned int m_Slices; /** Underlying BaseGeometry for this SlicedGeometry */ const mitk::BaseGeometry *m_ReferenceGeometry; /** SNC correcsponding to this geometry; used to reflect changes in the * number of slices due to rotation. */ // mitk::NavigationController *m_NavigationController; mitk::SliceNavigationController *m_SliceNavigationController; //##Documentation //## @brief PreSetSpacing //## //## These virtual function allows a different beahiour in subclasses. //## Do implement them in every subclass of BaseGeometry. If not needed, use //## {Superclass::PreSetSpacing();}; void PreSetSpacing(const mitk::Vector3D &aSpacing) override; }; } // namespace mitk #endif /* MITKSLICEDGEOMETRY3D_H_HEADER_INCLUDED_C1EBD0AD */ diff --git a/Modules/Core/include/mitkSourceImageRelationRule.h b/Modules/Core/include/mitkSourceImageRelationRule.h index b6647a871f..bdb0cd6dc2 100644 --- a/Modules/Core/include/mitkSourceImageRelationRule.h +++ b/Modules/Core/include/mitkSourceImageRelationRule.h @@ -1,129 +1,129 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITK_SOURCE_IMAGE_RELATION_RULE_H #define MITK_SOURCE_IMAGE_RELATION_RULE_H #include "mitkPropertyRelationRuleBase.h" #include "mitkImage.h" namespace mitk { /**This rule class can be used for relations that reference an image as source for a destination entity. (e.g. an image that is used to generate the relation source). - The ID-layer is supported like for GenericIDReleations. + The ID-layer is supported like for GenericIDRelations. So it can be used for all ID based relations between PropertyProviders that also implement the interface identifiable. In addition the rule uses the data-layer to deduce/define relations. For this layer it uses properties compliant to DICOM. Thus (1) the information is stored in a DICOM Source Image Sequence item (0x0008,0x2112) and (2) the destination must have properties DICOM SOP Instance UIDs (0x0008, 0x0018) and DICOM SOP Class UID (0x0008, 0x0016). If the destination does not have this properties, no connection can be made on the data-layer. @remark Please note that PropertyRelationRules and DICOM use the term "source" differently. The DICOM source (image) equals the PropertyRelationRule destination. This is due to an inverted relation direction. So in the context of the SourceImageRelationRule interface a derived data is the source and points to the original image, it derives from. In the context of DICOM this referenced original image would be called source image (as the name of this class). In order to be able to use this class for different relation types (DICOM would call it purposes), the purposeTag is used. It must be specified when creating a rule instance. The purposeTag will be used as suffix for the rule ID of the instance and therefore allows to create specific and distinguishable rules instances based on this class. One may also specify the display name and the role names of the instance. If not specified the default values are used (display name: " relation", source role name: "derived data", destination role name: "source image") */ class MITKCORE_EXPORT SourceImageRelationRule : public mitk::PropertyRelationRuleBase { public: mitkClassMacro(SourceImageRelationRule, PropertyRelationRuleBase); itkNewMacro(Self); mitkNewMacro1Param(Self, const RuleIDType &); mitkNewMacro2Param(Self, const RuleIDType &, const std::string &); mitkNewMacro4Param(Self, const RuleIDType &, const std::string &, const std::string &, const std::string &); using RuleIDType = PropertyRelationRuleBase::RuleIDType; using RelationUIDType = PropertyRelationRuleBase::RelationUIDType; using RelationUIDVectorType = PropertyRelationRuleBase::RelationUIDVectorType; /** Returns an ID string that identifies the rule class */ RuleIDType GetRuleID() const override; bool IsAbstract() const override; /** Returns a human readable string that can be used to describe the rule. Does not need to be unique.*/ std::string GetDisplayName() const override; /** Returns a human readable string that can be used to describe the role of a source in context of the rule * instance.*/ std::string GetSourceRoleName() const override; /** Returns a human readable string that can be used to describe the role of a destination in context of the rule * instance.*/ std::string GetDestinationRoleName() const override; bool IsDestinationCandidate(const IPropertyProvider *owner) const override; /** Connects to passed images. - @remark destination must specifiy DICOM SOP Instance UIDs (0x0008, 0x0018) and DICOM SOP Class UID (0x0008, 0x0016) + @remark destination must specify DICOM SOP Instance UIDs (0x0008, 0x0018) and DICOM SOP Class UID (0x0008, 0x0016) in order to establish a connection on the data layer.*/ RelationUIDType Connect(Image *source, const Image *destination) const; protected: SourceImageRelationRule(); SourceImageRelationRule(const RuleIDType &purposeTag); SourceImageRelationRule(const RuleIDType &purposeTag, const std::string &displayName); SourceImageRelationRule(const RuleIDType &purposeTag, const std::string &displayName, const std::string &sourceRole, const std::string &destinationRole); ~SourceImageRelationRule() override = default; using InstanceIDType = PropertyRelationRuleBase::InstanceIDType; using InstanceIDVectorType = PropertyRelationRuleBase::InstanceIDVectorType; /** Helper function that returns a vector of all selections of the property DICOM.0008.2112 (and its associated ruleID) that refer to destination or all (if no destination is passed) with a supported RuleID and which are not already covered by the ignoreInstances.*/ std::vector > GetReferenceSequenceIndices(const IPropertyProvider * source, const IPropertyProvider* destination = nullptr, InstanceIDVectorType ignoreInstances = {}) const; using DataRelationUIDVectorType = PropertyRelationRuleBase::DataRelationUIDVectorType; virtual DataRelationUIDVectorType GetRelationUIDs_DataLayer(const IPropertyProvider* source, const IPropertyProvider* destination, const InstanceIDVectorType& instances_IDLayer) const override; void Connect_datalayer(IPropertyOwner *source, const IPropertyProvider *destination, const InstanceIDType &instanceID) const override; void Disconnect_datalayer(IPropertyOwner *source, const RelationUIDType& relationUID) const override; bool IsSupportedRuleID(const RuleIDType& ruleID) const override; itk::LightObject::Pointer InternalClone() const override; /**Prepares a new reference to an image on the data layer. Therefore an unused and valid sequence item index - for the passed source will be genarated and a relationUID property with the relationUID will be set to block the instance ID. The + for the passed source will be generated and a relationUID property with the relationUID will be set to block the instance ID. The instance ID will be returned. @remark The method is guarded by a class wide mutex to avoid racing conditions in a scenario where rules are used concurrently.*/ PropertyKeyPath::ItemSelectionIndex CreateNewSourceImageSequenceItem(IPropertyOwner *source) const; std::string GenerateRuleID(const std::string& purpose) const; private: RuleIDType m_PurposeTag; std::string m_DisplayName; std::string m_SourceRole; std::string m_DestinationRole; }; } // namespace mitk #endif diff --git a/Modules/Core/include/mitkStandardFileLocations.h b/Modules/Core/include/mitkStandardFileLocations.h index d49dc2405e..1bc4bb5f0d 100644 --- a/Modules/Core/include/mitkStandardFileLocations.h +++ b/Modules/Core/include/mitkStandardFileLocations.h @@ -1,112 +1,112 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITK_STANDARD_FILE_LOCATIONS_H_INCLUDED_SWDG #define MITK_STANDARD_FILE_LOCATIONS_H_INCLUDED_SWDG #include #include #include #include namespace mitk { /*! \brief Provides a method to look for configuration and option files etc. Call mitk::StandardFileLocations::FindFile(filename) to look for configuration files. Call mitk::StandardFileLocations::GetOptionDirectory() to look for/save option files. */ class MITKCORE_EXPORT StandardFileLocations : public itk::Object { public: typedef StandardFileLocations Self; typedef itk::Command Superclass; typedef itk::SmartPointer Pointer; /*! \brief Adds a directory into the search queue: \ Use this function in combination with FindFile(), after adding some \ directories, they will also be searched for the requested file \param dir directory you want to be searched in - \param insertInFrontOfSearchList wheather this search request shall be processed first + \param insertInFrontOfSearchList whether this search request shall be processed first */ void AddDirectoryForSearch(const char *dir, bool insertInFrontOfSearchList = true); /*! \brief Remove a directory from the search queue: \ Use this function in combination with FindFile(). \param dir directory you want to be searched in */ void RemoveDirectoryForSearch(const char *dir); /*! \brief looks for a file in several standard locations \param filename The file you want to fine, without any path \param pathInSourceDir Where in the source tree hierarchy would that file be? \return The absolute path to the file including the filename This method appends several standard locations to the end of the searchqueue (if they not already exist) and then searches for the file within all directories contained in the search queue:
  1. Add the directory specified in the environment variable MITKCONF
  2. Add the .mitk directory in the home folder of the user
  3. Add the current working directory
  4. Add the (current working directory)/bin directory
  5. Add the directory specified in pathInSourceDir, that is relative to the source code directory root (which is determined at compile time)
Already added directories in the searchqueue by using AddDirectoryForSearch before calling FindFile are still searched first, because above mentioned standard locations are always appended at the end of the list. */ std::string FindFile(const char *filename, const char *pathInSourceDir = nullptr); /*! \brief Return directory of/for option files \return The absolute path to the directory for option files. This method looks for the directory of/for option files in two ways. The logic is as follows 1. If there is an environment variable MITKOPTIONS, then use that directory. 2. Use .mitk-subdirectory in home directory of the user The directory will be created if it does not exist. */ std::string GetOptionDirectory(); static StandardFileLocations *GetInstance(); protected: itkFactorylessNewMacro(Self); itkCloneMacro(Self); typedef std::vector FileSearchVectorType; FileSearchVectorType m_SearchDirectories; StandardFileLocations(); ~StandardFileLocations() override; std::string SearchDirectoriesForFile(const char *filename); private: // Private Copy Constructor StandardFileLocations(const StandardFileLocations &); }; } // namespace #endif diff --git a/Modules/Core/include/mitkStatusBarImplementation.h b/Modules/Core/include/mitkStatusBarImplementation.h index 17cf30fb96..f8121f2ff6 100644 --- a/Modules/Core/include/mitkStatusBarImplementation.h +++ b/Modules/Core/include/mitkStatusBarImplementation.h @@ -1,60 +1,60 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKSTATUSBARIMPLEMENTATION_H #define MITKSTATUSBARIMPLEMENTATION_H #include #include namespace mitk { //##Documentation - //## @brief GUI indepentent Interface for all Gui depentent implementations of a StatusBar. + //## @brief GUI independent Interface for all Gui depentent implementations of a StatusBar. class MITKCORE_EXPORT StatusBarImplementation { public: mitkClassMacroNoParent(StatusBarImplementation) //##Documentation //## @brief Constructor StatusBarImplementation(){}; //##Documentation //## @brief Destructor virtual ~StatusBarImplementation(){}; //##Documentation //## @brief Send a string to the applications StatusBar virtual void DisplayText(const char *t) = 0; //##Documentation //## @brief Send a string with a time delay to the applications StatusBar virtual void DisplayText(const char *t, int ms) = 0; virtual void DisplayErrorText(const char *t) = 0; virtual void DisplayWarningText(const char *t) = 0; virtual void DisplayWarningText(const char *t, int ms) = 0; virtual void DisplayGenericOutputText(const char *t) = 0; virtual void DisplayDebugText(const char *t) = 0; virtual void DisplayGreyValueText(const char *t) = 0; //##Documentation //## @brief removes any temporary message being shown. virtual void Clear() = 0; //##Documentation //## @brief Set the SizeGrip of the window //## (the triangle in the lower right Windowcorner for changing the size) //## to enabled or disabled virtual void SetSizeGripEnabled(bool enable) = 0; }; } // end namespace mitk #endif /* define MITKSTATUSBARIMPLEMENTATION_H */ diff --git a/Modules/Core/include/mitkSurfaceSource.h b/Modules/Core/include/mitkSurfaceSource.h index 6c43c1ba09..c903d6cbcc 100644 --- a/Modules/Core/include/mitkSurfaceSource.h +++ b/Modules/Core/include/mitkSurfaceSource.h @@ -1,69 +1,69 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKSURFACEDATASOURCE_H_HEADER_INCLUDED_C10B4740 #define MITKSURFACEDATASOURCE_H_HEADER_INCLUDED_C10B4740 #include "mitkBaseDataSource.h" namespace mitk { class Surface; /** * @brief Superclass of all classes generating surfaces (instances of class * Surface) as output. * * In itk and vtk the generated result of a ProcessObject is only guaranteed * to be up-to-date, when Update() of the ProcessObject or the generated * DataObject is called immediately before access of the data stored in the * DataObject. This is also true for subclasses of mitk::BaseProcess and thus * for mitk::SurfaceSource. * @ingroup Process */ class MITKCORE_EXPORT SurfaceSource : public BaseDataSource { public: mitkClassMacro(SurfaceSource, BaseDataSource); itkFactorylessNewMacro(Self); itkCloneMacro(Self); typedef Surface OutputType; mitkBaseDataSourceGetOutputDeclarations /** * Allocates a new output object and returns it. Currently the * index idx is not evaluated. * @param idx the index of the output for which an object should be created * @returns the new object */ itk::DataObject::Pointer MakeOutput(DataObjectPointerArraySizeType idx) override; /** * This is a default implementation to make sure we have something. - * Once all the subclasses of ProcessObject provide an appopriate + * Once all the subclasses of ProcessObject provide an appropriate * MakeOutput(), then ProcessObject::MakeOutput() can be made pure * virtual. */ itk::DataObject::Pointer MakeOutput(const DataObjectIdentifierType &name) override; protected: SurfaceSource(); ~SurfaceSource() override; }; } // namespace mitk #endif /* MITKSURFACEDATASOURCE_H_HEADER_INCLUDED_C10B4740 */ diff --git a/Modules/Core/include/mitkSurfaceVtkMapper2D.h b/Modules/Core/include/mitkSurfaceVtkMapper2D.h index 9e52cbc226..eda0c82186 100644 --- a/Modules/Core/include/mitkSurfaceVtkMapper2D.h +++ b/Modules/Core/include/mitkSurfaceVtkMapper2D.h @@ -1,215 +1,215 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkSurfaceVtkMapper2D_h #define mitkSurfaceVtkMapper2D_h #include "mitkBaseRenderer.h" #include "mitkLocalStorageHandler.h" #include "mitkVtkMapper.h" #include // VTK #include class vtkAssembly; class vtkCutter; class vtkPlane; class vtkLookupTable; class vtkGlyph3D; class vtkArrowSource; class vtkReverseSense; namespace mitk { class Surface; /** * @brief Vtk-based mapper for cutting 2D slices out of Surfaces. * * The mapper uses a vtkCutter filter to cut out slices (contours) of the 3D * volume and render these slices as vtkPolyData. The data is transformed * according to its geometry before cutting, to support the geometry concept * of MITK. * * Properties: * \b Surface.2D.Line Width: Thickness of the rendered lines in 2D. * \b Surface.2D.Normals.Draw Normals: enables drawing of normals as 3D arrows * in the 2D render window. The normals are created with a vtkGlyph3D from * the vtkPolyData. * \b Surface.2D.Normals.Draw Inverse Normals: same as normals, but in the * other direction. The inverse normals are computed with a vtkReverseSense * filter. * \b Surface.2D.Normals.(Inverse) Normals Color: Color of the (inverse) normals. * \b Surface.2D.Normals.(Inverse) Normals Scale Factor: Regulates the size of the normals. * * @ingroup Mapper */ class MITKCORE_EXPORT SurfaceVtkMapper2D : public VtkMapper { public: mitkClassMacro(SurfaceVtkMapper2D, VtkMapper); itkFactorylessNewMacro(Self); itkCloneMacro(Self); virtual const mitk::Surface *GetInput() const; /** \brief returns the prop assembly */ vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) override; /** \brief set the default properties for this mapper */ static void SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); /** \brief Internal class holding the mapper, actor, etc. for each of the 3 2D render windows */ class LocalStorage : public mitk::Mapper::BaseLocalStorage { public: /** \brief Timestamp of last update of stored data. */ itk::TimeStamp m_LastUpdateTime; /** * @brief m_PropAssembly Contains all vtkProps for the final rendering. * * Consists of 3 actors: * The surface cut (the slice from the 3D surface). * The normals and the inverse normals. */ vtkSmartPointer m_PropAssembly; /** * @brief m_Actor actor for the surface cut. */ vtkSmartPointer m_Actor; /** * @brief m_NormalActor actor for the normals. */ vtkSmartPointer m_NormalActor; /** * @brief m_InverseNormalActor actor for the inverse normals. */ vtkSmartPointer m_InverseNormalActor; /** * @brief m_Mapper VTK mapper for all types of 2D polydata e.g. werewolves. */ vtkSmartPointer m_Mapper; /** * @brief m_Cutter Filter to cut out the 2D slice. */ vtkSmartPointer m_Cutter; /** * @brief m_CuttingPlane The plane where to cut off the 2D slice. */ vtkSmartPointer m_CuttingPlane; /** * @brief m_NormalMapper Mapper for the normals. */ vtkSmartPointer m_NormalMapper; /** * @brief m_InverseNormalMapper Mapper for the inverse normals. */ vtkSmartPointer m_InverseNormalMapper; /** * @brief m_NormalGlyph Glyph for creating normals. */ vtkSmartPointer m_NormalGlyph; /** * @brief m_InverseNormalGlyph Glyph for creating inverse normals. */ vtkSmartPointer m_InverseNormalGlyph; /** * @brief m_ArrowSource Arrow representation of the normals. */ vtkSmartPointer m_ArrowSource; /** * @brief m_ReverseSense Filter to invert the normals. */ vtkSmartPointer m_ReverseSense; /** \brief Default constructor of the local storage. */ LocalStorage(); /** \brief Default deconstructor of the local storage. */ ~LocalStorage() override; }; /** \brief The LocalStorageHandler holds all (three) LocalStorages for the three 2D render windows. */ mitk::LocalStorageHandler m_LSH; /** * @brief UpdateVtkTransform Overwrite the method of the base class. * * The base class transforms the actor according to the respective * geometry which is correct for most cases. This mapper, however, * uses a vtkCutter to cut out a contour. To cut out the correct * contour, the data has to be transformed beforehand. Else the * current plane geometry will point the cutter to en empty location * (if the surface does have a geometry, which is a rather rare case). */ void UpdateVtkTransform(mitk::BaseRenderer * /*renderer*/) override {} protected: /** * @brief SurfaceVtkMapper2D default constructor. */ SurfaceVtkMapper2D(); /** * @brief ~SurfaceVtkMapper2D default destructor. */ ~SurfaceVtkMapper2D() override; /** * @brief GenerateDataForRenderer produces all the data. * @param renderer The respective renderer of the mitkRenderWindow. */ void GenerateDataForRenderer(mitk::BaseRenderer *renderer) override; /** * @brief ResetMapper Called in mitk::Mapper::Update to hide objects. * If TimeGeometry or time step is not valid, reset the mapper. - * so that nothing is displayed e.g. toggle visiblity of the propassembly. + * so that nothing is displayed e.g. toggle visibility of the propassembly. * * @param renderer The respective renderer of the mitkRenderWindow. */ void ResetMapper(BaseRenderer *renderer) override; /** * @brief Updates legacy properties to current behavior/interpretation. * @param properties The property list which should be adapted to new behaviour. * * Whenever a mapper decides to change its property types or its * interpretation of certain values, it should add something to this * method and call it before methods like ApplyProperties(); * * This is particularly helpful when dealing with data from * archive/scene files that were created before changes. */ virtual void FixupLegacyProperties(PropertyList *properties); /** * @brief ApplyAllProperties Pass all the properties to VTK. * @param renderer The respective renderer of the mitkRenderWindow. */ void ApplyAllProperties(BaseRenderer *renderer); /** * @brief Update Check if data should be generated. * @param renderer The respective renderer of the mitkRenderWindow. */ void Update(BaseRenderer *renderer) override; }; } // namespace mitk #endif /* mitkSurfaceVtkMapper2D_h */ diff --git a/Modules/Core/include/mitkTemporoSpatialStringProperty.h b/Modules/Core/include/mitkTemporoSpatialStringProperty.h index 99a145cc8d..510958cd02 100644 --- a/Modules/Core/include/mitkTemporoSpatialStringProperty.h +++ b/Modules/Core/include/mitkTemporoSpatialStringProperty.h @@ -1,136 +1,136 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKTEMPOROSPATIALSTRINGPROPERTY_H_HEADER #define MITKTEMPOROSPATIALSTRINGPROPERTY_H_HEADER #include #include "mitkBaseProperty.h" #include #include "mitkTimeGeometry.h" #include namespace mitk { #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4522) #endif /** * @brief Property for time and space resolved string values * @ingroup DataManagement */ class MITKCORE_EXPORT TemporoSpatialStringProperty : public BaseProperty { public: typedef ::itk::IndexValueType IndexValueType; typedef std::string ValueType; mitkClassMacro(TemporoSpatialStringProperty, BaseProperty); itkFactorylessNewMacro(Self); itkCloneMacro(Self); mitkNewMacro1Param(TemporoSpatialStringProperty, const char*); mitkNewMacro1Param(TemporoSpatialStringProperty, const std::string &); /**Returns the value of the first time point in the first slice. * If now value is set it returns an empty string.*/ ValueType GetValue() const; /**Returns the value of the passed time step and slice. If it does not exist and allowedClosed is true * it will look for the closest value. If nothing could be found an empty string will be returned.*/ ValueType GetValue(const TimeStepType &timeStep, const IndexValueType &zSlice, bool allowCloseTime = false, bool allowCloseSlice = false) const; ValueType GetValueBySlice(const IndexValueType &zSlice, bool allowClose = false) const; ValueType GetValueByTimeStep(const TimeStepType &timeStep, bool allowClose = false) const; bool HasValue() const; bool HasValue(const TimeStepType &timeStep, const IndexValueType &zSlice, bool allowCloseTime = false, bool allowCloseSlice = false) const; bool HasValueBySlice(const IndexValueType &zSlice, bool allowClose = false) const; bool HasValueByTimeStep(const TimeStepType &timeStep, bool allowClose = false) const; /** return all slices stored for the specified timestep.*/ std::vector GetAvailableSlices(const TimeStepType& timeStep) const; /** return all time steps stored for the specified slice.*/ std::vector GetAvailableTimeSteps(const IndexValueType& slice) const; /** return all time steps stored in the property.*/ std::vector GetAvailableTimeSteps() const; /** return all slices stored in the property. @remark not all time steps may contain all slices.*/ std::vector GetAvailableSlices() const; void SetValue(const TimeStepType &timeStep, const IndexValueType &zSlice, const ValueType &value); void SetValue(const ValueType &value); std::string GetValueAsString() const override; - /** Inidicates of all values (all time steps, all slices) are the same, or if at least one value stored + /** Indicates of all values (all time steps, all slices) are the same, or if at least one value stored in the property is different. If IsUniform==true one can i.a. use GetValueAsString() without the loss of information to retrieve the stored value.*/ bool IsUniform() const; using BaseProperty::operator=; protected: typedef std::map SliceMapType; typedef std::map TimeMapType; TimeMapType m_Values; TemporoSpatialStringProperty(const char *string = nullptr); TemporoSpatialStringProperty(const std::string &s); TemporoSpatialStringProperty(const TemporoSpatialStringProperty &); std::pair CheckValue(const TimeStepType &timeStep, const IndexValueType &zSlice, bool allowCloseTime = false, bool allowCloseSlice = false) const; private: // purposely not implemented TemporoSpatialStringProperty &operator=(const TemporoSpatialStringProperty &); itk::LightObject::Pointer InternalClone() const override; bool IsEqual(const BaseProperty &property) const override; bool Assign(const BaseProperty &property) override; }; namespace PropertyPersistenceSerialization { /** Serialization of a TemporoSpatialStringProperty into a JSON string.*/ MITKCORE_EXPORT::std::string serializeTemporoSpatialStringPropertyToJSON(const mitk::BaseProperty *prop); } namespace PropertyPersistenceDeserialization { /**Deserialize a passed JSON string into a TemporoSpatialStringProperty.*/ MITKCORE_EXPORT mitk::BaseProperty::Pointer deserializeJSONToTemporoSpatialStringProperty(const std::string &value); } #ifdef _MSC_VER #pragma warning(pop) #endif } // namespace mitk #endif diff --git a/Modules/Core/include/mitkTimeGeometry.h b/Modules/Core/include/mitkTimeGeometry.h index 48f6414e22..b1c0070ed1 100644 --- a/Modules/Core/include/mitkTimeGeometry.h +++ b/Modules/Core/include/mitkTimeGeometry.h @@ -1,349 +1,349 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef TimeGeometry_h #define TimeGeometry_h // ITK #include // MITK #include "mitkOperationActor.h" #include #include #include namespace mitk { typedef mitk::ScalarType TimePointType; typedef std::size_t TimeStepType; /** * \brief Manages the geometries of a data object for each time step * * This class is an abstract class. The concrete implementation * depends on the way the different time steps are managed. * * The time is defined either by a time step or a time point. Time steps - * are non-negativ integers starting from 0. A time point is is a ScalarType value + * are non-negative integers starting from 0. A time point is a ScalarType value * which gives the passed time since start in ms. Be aware that the starting * point is not fixed so it is possible that the same time point defines two * different time depending on the start time of the used time geometry. * * \addtogroup geometry */ class MITKCORE_EXPORT TimeGeometry : public itk::Object, public OperationActor { protected: TimeGeometry(); ~TimeGeometry() override; /** * \brief Contains a bounding box which includes all time steps */ BoundingBox::Pointer m_BoundingBox; /** * \brief Makes a deep copy of the current object */ LightObject::Pointer InternalClone() const override; public: mitkClassMacroItkParent(TimeGeometry, itk::Object); itkCloneMacro(Self); itkCreateAnotherMacro(Self); /** * \brief Returns the number of time steps. * * Returns the number of time steps for which * geometries are saved. The number of time steps * is also the upper bound of the time steps. The * minimum time steps is always 0. */ virtual TimeStepType CountTimeSteps() const = 0; /** * \brief Returns the first time point for which the object is valid. * * Returns the first valid time point for this geometry. If only one * time steps available it usually goes from -max to +max. The time point * is given in ms. */ virtual TimePointType GetMinimumTimePoint() const = 0; /** * \brief Returns the last time point for which the object is valid * - * Gives the last time point for which a valid geometrie is saved in + * Gives the last time point for which a valid geometry is saved in * this time geometry. The time point is given in ms. */ virtual TimePointType GetMaximumTimePoint() const = 0; /** * \brief Returns the first time point for which the object is valid. * * Returns the first valid time point for the given TimeStep. The time point * is given in ms. */ virtual TimePointType GetMinimumTimePoint(TimeStepType step) const = 0; /** * \brief Returns the last time point for which the object is valid * * Gives the last time point for the Geometry specified by the given TimeStep. The time point is given in ms. */ virtual TimePointType GetMaximumTimePoint(TimeStepType step) const = 0; /** * \brief Get the time bounds (in ms) */ virtual TimeBounds GetTimeBounds() const = 0; /** * \brief Get the time bounds for the given TimeStep (in ms) */ virtual TimeBounds GetTimeBounds(TimeStepType step) const = 0; /** * \brief Tests if a given time point is covered by this object * * Returns true if a geometry can be returned for the given time * point and falls if not. The time point must be given in ms. */ virtual bool IsValidTimePoint(TimePointType timePoint) const = 0; /** - * \brief Test for the given time step if a geometry is availible + * \brief Test for the given time step if a geometry is available * * Returns true if a geometry is defined for the given time step. * Otherwise false is returned. - * The time step is defined as positiv number. + * The time step is defined as positive number. */ virtual bool IsValidTimeStep(TimeStepType timeStep) const = 0; /** * \brief Converts a time step to a time point * * Converts a time step to a time point in a way that * the new time point indicates the same geometry as the time step. * If the original time steps does not point to a valid geometry, * a time point is calculated that also does not point to a valid * geometry, but no exception is raised. */ virtual TimePointType TimeStepToTimePoint(TimeStepType timeStep) const = 0; /** * \brief Converts a time point to the corresponding time step * * Converts a time point to a time step in a way that * the new time step indicates the same geometry as the time point. - * If a negativ invalid time point is given always time step 0 is - * returned. If an positiv invalid time step is given an invalid + * If a negative invalid time point is given always time step 0 is + * returned. If an positive invalid time step is given an invalid * time step will be returned. */ virtual TimeStepType TimePointToTimeStep(TimePointType timePoint) const = 0; /** * \brief Returns the geometry of a specific time point * * Returns the geometry which defines the given time point. If * the given time point is invalid an null-pointer is returned. * * The pointer to the returned geometry may point to the saved * geometry but this is not necessarily the case. So a change to * the returned geometry may or may not afflict the geometry for the * time point or all time points depending on the used implementation * of TimeGeometry. */ virtual BaseGeometry::Pointer GetGeometryForTimePoint(TimePointType timePoint) const = 0; /** * \brief Returns the geometry which corresponds to the given time step * * Returns the geometry which defines the given time step. If * the given time step is invalid an null-pointer is returned. * * The pointer to the returned geometry may point to the saved * geometry but this is not necessarily the case. So a change to * the returned geometry may or may not afflict the geometry for the * time step or all time steps depending on the used implementation * of TimeGeometry. */ virtual BaseGeometry::Pointer GetGeometryForTimeStep(TimeStepType timeStep) const = 0; /** * \brief Returns a clone of the geometry of a specific time point * * If an invalid time step is given (e.g. no geometry is defined for this time step) * a null-pointer will be returned. */ virtual BaseGeometry::Pointer GetGeometryCloneForTimeStep(TimeStepType timeStep) const = 0; /** * \brief Sets the geometry for a given time step * * Sets the geometry for the given time steps. This may also afflects other * time steps, depending on the implementation of TimeGeometry. */ virtual void SetTimeStepGeometry(BaseGeometry *geometry, TimeStepType timeStep) = 0; /** * \brief Expands to the given number of time steps * * Expands to the given number of time steps. Each new created time * step is filled with an empty geometry. * Shrinking is not supported! */ virtual void Expand(TimeStepType size) = 0; /** * \brief Replaces the geometry instances with clones ot the passed geometry. * * Replaces the geometries of all time steps with clones of the passed - * geometry. Replacment strategy depends on the implementation of TimeGeometry + * geometry. Replacement strategy depends on the implementation of TimeGeometry * sub class. * @remark The time points itself stays untouched. Use this method if you want * to change the spatial properties of a TimeGeometry and preserve the time * "grid". */ virtual void ReplaceTimeStepGeometries(const BaseGeometry *geometry) = 0; /** - * \brief Tests if all necessary informations are set and the object is valid + * \brief Tests if all necessary information are set and the object is valid */ virtual bool IsValid() const = 0; /** * \brief Get the position of the corner number \a id (in world coordinates) * * See SetImageGeometry for how a corner is defined on images. */ Point3D GetCornerPointInWorld(int id) const; /** * \brief Get the position of a corner (in world coordinates) * * See SetImageGeometry for how a corner is defined on images. */ Point3D GetCornerPointInWorld(bool xFront = true, bool yFront = true, bool zFront = true) const; /** * \brief Get the center of the bounding-box in mm */ Point3D GetCenterInWorld() const; /** * \brief Get the squared length of the diagonal of the bounding-box in mm */ double GetDiagonalLength2InWorld() const; /** * \brief Get the length of the diagonal of the bounding-box in mm */ double GetDiagonalLengthInWorld() const; /** * \brief Test whether the point \a p (world coordinates in mm) is inside the bounding box */ bool IsWorldPointInside(const mitk::Point3D &p) const; /** * \brief Updates the bounding box to cover the area used in all time steps * * The bounding box is updated by this method. The new bounding box * covers an area which includes all bounding boxes during * all times steps. */ void UpdateBoundingBox(); /** * \brief Returns a bounding box that covers all time steps */ BoundingBox *GetBoundingBoxInWorld() const { return m_BoundingBox; } /** * \brief Returns the world bounds of the object that cover all time steps */ BoundingBox::BoundsArrayType GetBoundsInWorld() const { return m_BoundingBox->GetBounds(); } /** * \brief Returns the Extend of the bounding in the given direction */ ScalarType GetExtentInWorld(unsigned int direction) const; /** * \brief Initializes the TimeGeometry */ virtual void Initialize(); /** * \brief Updates the geometry */ void Update(); /** * \brief Updates everything except the Bounding box * * This class should be overwritten by child classes. * The method is called when Update() is required. */ virtual void UpdateWithoutBoundingBox(){}; /** * \brief Executes the given operation on all time steps */ void ExecuteOperation(Operation *op) override; void PrintSelf(std::ostream &os, itk::Indent indent) const override; }; // end class TimeGeometry /** * @brief Equal A function comparing two instances of TimeGeometry for being identical. * * @ingroup MITKTestingAPI * * The function compares two instances of TimeGeometries in all their aspects. * * The parameter eps is a tolerance value for all methods which are internally used for comparison. * If you want to use different tolerance 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 Tolerance 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. */ MITKCORE_EXPORT bool Equal(const mitk::TimeGeometry &leftHandSide, const mitk::TimeGeometry &rightHandSide, ScalarType eps, bool verbose); /** * @brief Compare two instances of TimeGeometry * * @ingroup MITKTestingAPI * * The function compares two instances of TimeGeometries in all their aspects. * * The parameter eps is a tolerance value for all methods which are internally used for comparison. * If you want to use different tolerance values for different parts of the geometry, feel free to use * the other comparison methods and write your own implementation of Equal. * * @param leftHandSide Compare this against rightHandSide. * @param rightHandSide Compare this against leftHandSide. * @param coordinateEps Tolerance for comparison of all spatial and temporal aspects (spacing, origin and grid alignment, time points). * You can use mitk::eps in most cases. * @param directionEps Tolerance for comparison of all directional aspects (axis). 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 comparisons are true. False in any other case. */ MITKCORE_EXPORT bool Equal(const mitk::TimeGeometry& leftHandSide, const mitk::TimeGeometry& rightHandSide, ScalarType coordinateEps, ScalarType directionEps, bool verbose); } // end namespace MITK #endif // TimeGeometry_h diff --git a/Modules/Core/include/mitkUIDGenerator.h b/Modules/Core/include/mitkUIDGenerator.h index 0b7931f039..ac261e108c 100644 --- a/Modules/Core/include/mitkUIDGenerator.h +++ b/Modules/Core/include/mitkUIDGenerator.h @@ -1,44 +1,44 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITK_UID_GENERATOR_INDCLUDED_FASAWE #define MITK_UID_GENERATOR_INDCLUDED_FASAWE #include #include namespace mitk { /*! \brief Generated unique IDs Creates unique IDs. The current implementation uses the UUID specification (https://www.ietf.org/rfc/rfc4122.txt) and random generator. - One may define a prefix for the UID string. But it is not needed to guarantee uniquness. It is + One may define a prefix for the UID string. But it is not needed to guarantee uniqueness. It is just a human readable addition, e.g. to see for which purpose the UID was generated. */ class MITKCORE_EXPORT UIDGenerator { public: explicit UIDGenerator(const char * prefix = ""); /** @return Returns a unique ID as string. You will get another unique ID each time you call GetUID. */ std::string GetUID(); private: std::string m_Prefix; }; } // namespace mitk #endif diff --git a/Modules/Core/include/mitkVtkInteractorStyle.h b/Modules/Core/include/mitkVtkInteractorStyle.h index e9f5a494cb..4ebd6a8bde 100644 --- a/Modules/Core/include/mitkVtkInteractorStyle.h +++ b/Modules/Core/include/mitkVtkInteractorStyle.h @@ -1,57 +1,57 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ /** * \brief Implements the handling of events that are missing for MITK interaction. * * This class inherits from vtkInteractorStyleUser, a class that handles * VTK-Events and invokes callbacks by means of an observer pattern. * * Most event-types needed for typical MITK interaction have already * been implemented in vtkInteractorStyleUser (Mouse-Buttons + Keyboard). -* However, wheel-events and widgetModifed-events (whatever these are) +* However, wheel-events and widgetModified-events (whatever these are) * have not been handled so far. This is the purpose of this class. */ #ifndef __mitkVtkInteractorStyle_h #define __mitkVtkInteractorStyle_h #include "MitkCoreExports.h" #include class MITKCORE_EXPORT mitkVtkInteractorStyle : public vtkInteractorStyleUser { public: // default VTK c'tor static mitkVtkInteractorStyle *New(); vtkTypeMacro(mitkVtkInteractorStyle, vtkInteractorStyleUser); /** * \brief Called when scrolling forwards with the mouse-wheel. */ void OnMouseWheelForward() override; /** * \brief Called when scrolling backwards with the mouse-wheel. */ void OnMouseWheelBackward() override; protected: mitkVtkInteractorStyle(); ~mitkVtkInteractorStyle() override; private: mitkVtkInteractorStyle(const mitkVtkInteractorStyle &); // Not implemented. void operator=(const mitkVtkInteractorStyle &); // Not implemented. }; #endif diff --git a/Modules/Core/include/mitkVtkLayerController.h b/Modules/Core/include/mitkVtkLayerController.h index 089491086c..b6825c8fa2 100644 --- a/Modules/Core/include/mitkVtkLayerController.h +++ b/Modules/Core/include/mitkVtkLayerController.h @@ -1,114 +1,114 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkVtkLayerController_h #define mitkVtkLayerController_h #include #include #include #include class vtkRenderWindow; class vtkRenderer; namespace mitk { /** * Manages the VTK layer hierarchy * of a vtkRenderWindow. * For simple access the layers are divided into three * main groups: background, scene and foreground layers. * Renderers can be registered via the insert... functions and * removed via the RemoveRenderer function. */ class MITKCORE_EXPORT VtkLayerController { public: static VtkLayerController *GetInstance(vtkSmartPointer renWin); static void AddInstance(vtkSmartPointer renWin, vtkSmartPointer mitkSceneRenderer); static void RemoveInstance(vtkSmartPointer renWin); VtkLayerController(vtkSmartPointer renderWindow); virtual ~VtkLayerController(); /** * Returns the current vtkRenderer of the Scene */ vtkSmartPointer GetSceneRenderer(); /** * Connects a VTK renderer with a vtk renderwindow. The renderer will be rendered in the background. * With forceAbsoluteBackground set true a renderer can be placed at the absolute background of the scene. * Multiple calls with forceAbsoluteBackground set true will set the latest registered renderer as background. */ void InsertBackgroundRenderer(vtkSmartPointer renderer, bool forceAbsoluteBackground); /** * Connects a VTK renderer with a vtk renderwindow. The renderer will be rendered in the foreground. * With forceAbsoluteBackground set true a renderer can be placed at the absolute foreground of the scene. * Multiple calls with forceAbsoluteForeground set true will set the latest registered renderer as foreground. */ void InsertForegroundRenderer(vtkSmartPointer renderer, bool forceAbsoluteForeground); /** * Connects a VTK renderer with a vtk renderwindow. The renderer will be rendered between background renderers and * foreground renderers. */ void InsertSceneRenderer(vtkSmartPointer renderer); /** * Connects a VtkRenderWindow with the layer controller. */ void SetRenderWindow(vtkSmartPointer renwin); /** * A renderer which has been inserted via a insert... function can be removed from the vtkRenderWindow with * RemoveRenderer. */ void RemoveRenderer(vtkSmartPointer renderer); /** * Returns true if a renderer has been inserted */ bool IsRendererInserted(vtkSmartPointer renderer); /** * Returns the number of renderers in the renderwindow. */ unsigned int GetNumberOfRenderers(); void SetEraseForAllRenderers(int i); protected: vtkSmartPointer m_RenderWindow; private: /** * Internally used to sort all registered renderers and to connect the with the vtkRenderWindow. * Mention that VTK Version 5 and above is rendering higher numbers in the background and VTK - * Verison < 5 in the foreground. + * Version < 5 in the foreground. */ void UpdateLayers(); // Layer Management typedef std::vector> RendererVectorType; RendererVectorType m_BackgroundRenderers; RendererVectorType m_SceneRenderers; RendererVectorType m_ForegroundRenderers; typedef std::map, mitk::VtkLayerController *> vtkLayerControllerMapType; static vtkLayerControllerMapType s_LayerControllerMap; }; } // Namespace MITK #endif /* mitkVtkLayerController_h */ diff --git a/Modules/Core/include/mitkVtkMapper.h b/Modules/Core/include/mitkVtkMapper.h index e42a8df801..e6c6dbd967 100644 --- a/Modules/Core/include/mitkVtkMapper.h +++ b/Modules/Core/include/mitkVtkMapper.h @@ -1,151 +1,151 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // change number #ifndef VTKMAPPER_H_HEADER_INCLUDED_C1C5453B #define VTKMAPPER_H_HEADER_INCLUDED_C1C5453B #include "mitkBaseRenderer.h" #include "mitkDataNode.h" #include "mitkLocalStorageHandler.h" #include "mitkMapper.h" #include "mitkVtkPropRenderer.h" #include #include #include #include #include #include #include #include #include #include class vtkProp; class vtkProp3D; class vtkActor; namespace mitk { /** \brief Base class of all Vtk Mappers in order to display primitives * by exploiting Vtk functionality. * * Rendering of opaque, translucent or volumetric geometry and overlays * is done in consecutive render passes. * * \ingroup Mapper */ class MITKCORE_EXPORT VtkMapper : public Mapper { public: mitkClassMacro(VtkMapper, Mapper); virtual vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) = 0; /** * \brief Returns whether this is an vtk-based mapper * \deprecatedSince{2013_03} All mappers of superclass VTKMapper are vtk based, use a dynamic_cast instead */ DEPRECATED(virtual bool IsVtkBased() const override); /** \brief Determines which geometry should be rendered * (opaque, translucent, volumetric, overlay) * and calls the appropriate function. * * Called by mitk::VtkPropRenderer::Render */ void MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType type) override; /** \brief Checks visibility and renders the overlay */ virtual void MitkRenderOverlay(BaseRenderer *renderer); /** \brief Checks visibility and renders untransparent geometry */ virtual void MitkRenderOpaqueGeometry(BaseRenderer *renderer); - /** \brief Checks visiblity and renders transparent geometry */ + /** \brief Checks visibility and renders transparent geometry */ virtual void MitkRenderTranslucentGeometry(BaseRenderer *renderer); /** \brief Checks visibility and renders volumes */ virtual void MitkRenderVolumetricGeometry(BaseRenderer *renderer); /** \brief Returns true if this mapper owns the specified vtkProp for * the given BaseRenderer. * * Note: returns false by default; should be implemented for VTK-based * Mapper subclasses. */ virtual bool HasVtkProp(const vtkProp *prop, BaseRenderer *renderer); /** \brief Set the vtkTransform of the m_Prop3D for * the current time step of \a renderer * * Called by mitk::VtkPropRenderer::Update before rendering. This * method will transform all actors (e.g. of an vtkAssembly) according * the geometry. * * \warning This method transforms only props which derive * from vtkProp3D. Make sure to use vtkAssembly, if you have * multiple props. vtkPropAssembly does not work, since it derives * from vtkProp. */ virtual void UpdateVtkTransform(mitk::BaseRenderer *renderer); /** * \brief Apply color and opacity properties read from the PropertyList * \deprecatedSince{2013_03} Use ApplyColorAndOpacityProperties(mitk::BaseRenderer* renderer, vtkActor * actor) * instead */ DEPRECATED(inline virtual void ApplyProperties(vtkActor *actor, mitk::BaseRenderer *renderer)) { ApplyColorAndOpacityProperties(renderer, actor); } /** * \deprecatedSince{2018_04} */ DEPRECATED(void ApplyShaderProperties(mitk::BaseRenderer *)){} /** * \brief Apply color and opacity properties read from the PropertyList. * Called by mapper subclasses. */ void ApplyColorAndOpacityProperties(mitk::BaseRenderer *renderer, vtkActor *actor) override; /** * \brief Release vtk-based graphics resources that are being consumed by this mapper. * * Method called by mitk::VtkPropRenderer. The parameter renderer could be used to * determine which graphic resources to release. The local storage is accessible * by the parameter renderer. Should be overwritten in subclasses. */ virtual void ReleaseGraphicsResources(mitk::BaseRenderer * /*renderer*/) {} class LocalStorage : public mitk::Mapper::BaseLocalStorage { }; protected: /** constructor */ VtkMapper(); /** virtual destructor in order to derive from this class */ ~VtkMapper() override; private: /** copy constructor */ VtkMapper(const VtkMapper &); /** assignment operator */ VtkMapper &operator=(const VtkMapper &); }; } // namespace mitk #endif /* VTKMAPPER_H_HEADER_INCLUDED_C1C5453B */ diff --git a/Modules/Core/include/mitkXML2EventParser.h b/Modules/Core/include/mitkXML2EventParser.h index c86dec4fa4..c95356fc66 100755 --- a/Modules/Core/include/mitkXML2EventParser.h +++ b/Modules/Core/include/mitkXML2EventParser.h @@ -1,91 +1,91 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkXML2EventParser_h #define mitkXML2EventParser_h #include #include "mitkPropertyList.h" #include #include "mitkInteractionEvent.h" namespace us { class Module; } namespace mitk { /** * \class InteractionEventList * \brief Generates a list of InteractionEvents based on an XML file- * * @sa EventRecorder * @ingroup Interaction **/ class MITKCORE_EXPORT XML2EventParser : public vtkXMLParser { public: /** * @brief Construct an InteractionEventList object based on a XML configuration file. * * Uses the specified resource file containing an XML event configuration to * construct an EventConfig object. If the resource is invalid, the created * EventConfig object will also be invalid. * * @param filename The resource name relative to the Interactions resource folder. * @param module */ XML2EventParser(const std::string &filename, const us::Module *module = nullptr); /** * @brief Construct an InteractionEventList object based on a XML configuration file. * - * Uses the specified istream refering to a file containing an XML event configuration to + * Uses the specified istream referring to a file containing an XML event configuration to * construct an EventConfig object. If the resource is invalid, the created * EventConfig object will also be invalid. * * @param inputStream std::ifstream to XML configuration file */ XML2EventParser(std::istream &inputStream); typedef std::vector EventContainerType; EventContainerType GetInteractions() { return m_InteractionList; } ~XML2EventParser() override{}; protected: /** * @brief Derived from XMLReader **/ void StartElement(const char *elementName, const char **atts) override; /** * @brief Derived from XMLReader **/ void EndElement(const char *elementName) override; std::string ReadXMLStringAttribute(const std::string &name, const char **atts); bool ReadXMLBooleanAttribute(const std::string &name, const char **atts); private: PropertyList::Pointer m_EventPropertyList; EventContainerType m_InteractionList; }; } // namespace mitk #endif /* mitkStateMachineConfig_h */