vtkedge-0.2.0~20110819/0000755000175000017500000000000011630435007014037 5ustar mathieumathieuvtkedge-0.2.0~20110819/ParaViewPlugins/0000755000175000017500000000000011630434663017126 5ustar mathieumathieuvtkedge-0.2.0~20110819/ParaViewPlugins/pqKWEIlluminatedLinesDisplayPanelDecorator.h0000644000175000017500000000251211363410610027607 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef __pqKWEIlluminatedLinesDisplayPanelDecorator_h #define __pqKWEIlluminatedLinesDisplayPanelDecorator_h #include class pqDisplayProxyEditor; class pqKWEIlluminatedLinesDisplayPanelDecorator : public QObject { Q_OBJECT typedef QObject Superclass; public: pqKWEIlluminatedLinesDisplayPanelDecorator(pqDisplayProxyEditor* panel); ~pqKWEIlluminatedLinesDisplayPanelDecorator(); private: pqKWEIlluminatedLinesDisplayPanelDecorator(const pqKWEIlluminatedLinesDisplayPanelDecorator&); // Not implemented. void operator=(const pqKWEIlluminatedLinesDisplayPanelDecorator&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/ParaViewPlugins/CMakeLists.txt0000644000175000017500000000421411412720617021662 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= option(VTKEdge_BUILD_PARAVIEW_PLUGINS "Build Plugins for ParaView" OFF) if(VTKEdge_BUILD_PARAVIEW_PLUGINS) find_package(ParaView REQUIRED) include(${PARAVIEW_USE_FILE}) set(MOC_SRCS) set(UI_SRCS) qt4_wrap_cpp(MOC_SRCS pqKWEIlluminatedLinesDisplayPanelDecorator.h ) include_directories(${QT_INCLUDES} ${PARAVIEW_GUI_INCLUDE_DIRS} ${PARAVIEW_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR} ) set(KWE_Interfaces ) set(KWE_Sources pqKWEIlluminatedLinesDisplayPanelDecorator.cxx ) set(SM_SOURCES vtkSMKWEIlluminatedLinesRepresentationProxy.cxx ) set(SM_XMLS vtkKWERendering.xml vtkKWEExtension.xml ) set(PLUGIN_NAME VTKEdge) set(CS_WRAP) include(${VTKEdge_BINARY_DIR}/Rendering/vtkKWERenderingKit.cmake) foreach(class ${VTK_KWERENDERING_CLASSES}) set(CS_WRAP ${CS_WRAP} ${VTKEdge_SOURCE_DIR}/Rendering/${class}.h) endforeach(class) include(${VTKEdge_BINARY_DIR}/Hybrid/vtkKWEHybridKit.cmake) foreach(class ${VTK_KWEHYBRID_CLASSES}) set(CS_WRAP ${CS_WRAP} ${VTKEdge_SOURCE_DIR}/Hybrid/${class}.h) endforeach(class) add_paraview_plugin(${PLUGIN_NAME} "1.0" SERVER_MANAGER_SOURCES "${SM_SOURCES};${CS_WRAP}" SERVER_MANAGER_XML ${SM_XMLS} GUI_INTERFACES ${KWE_Interfaces} GUI_SOURCES ${KWE_Sources} ${MOC_SRCS} ${UI_SRCS} ) target_link_libraries(${PLUGIN_NAME} vtkKWERendering vtkKWEHybrid ) endif(VTKEdge_BUILD_PARAVIEW_PLUGINS) vtkedge-0.2.0~20110819/ParaViewPlugins/pqKWEIlluminatedLinesDisplayPanelDecorator.cxx0000644000175000017500000000247011363410610030165 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "pqKWEIlluminatedLinesDisplayPanelDecorator.h" // Server Manager Includes. // Qt Includes. // ParaView Includes. #include "pqDisplayProxyEditor.h" //----------------------------------------------------------------------------- pqKWEIlluminatedLinesDisplayPanelDecorator::pqKWEIlluminatedLinesDisplayPanelDecorator( pqDisplayProxyEditor* panel) : Superclass(panel) { panel->setDisableSpecularOnScalarColoring(false); } //----------------------------------------------------------------------------- pqKWEIlluminatedLinesDisplayPanelDecorator::~pqKWEIlluminatedLinesDisplayPanelDecorator() { } vtkedge-0.2.0~20110819/ParaViewPlugins/vtkKWERendering.xml0000644000175000017500000000122611412720617022655 0ustar mathieumathieu Representation proxy illuminated lines. vtkedge-0.2.0~20110819/ParaViewPlugins/vtkSMKWEIlluminatedLinesRepresentationProxy.cxx0000644000175000017500000000551511363410610030430 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkSMKWEIlluminatedLinesRepresentationProxy.h" #include "vtkClientServerStream.h" #include "vtkObjectFactory.h" #include "vtkProcessModule.h" #include "vtkSMPropertyHelper.h" vtkStandardNewMacro(vtkSMKWEIlluminatedLinesRepresentationProxy); vtkCxxRevisionMacro(vtkSMKWEIlluminatedLinesRepresentationProxy, "$Revision: 1774 $"); //---------------------------------------------------------------------------- vtkSMKWEIlluminatedLinesRepresentationProxy::vtkSMKWEIlluminatedLinesRepresentationProxy() { } //---------------------------------------------------------------------------- vtkSMKWEIlluminatedLinesRepresentationProxy::~vtkSMKWEIlluminatedLinesRepresentationProxy() { } //---------------------------------------------------------------------------- bool vtkSMKWEIlluminatedLinesRepresentationProxy::EndCreateVTKObjects() { if (!this->Superclass::EndCreateVTKObjects()) { return false; } vtkClientServerStream stream; vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); vtkClientServerID helperID = pm->NewStreamObject("vtkKWEIlluminatedLinesPainter", stream); stream << vtkClientServerStream::Invoke << helperID << "UpdateMapper" << this->Mapper->GetID() << vtkClientServerStream::End; pm->DeleteStreamObject(helperID, stream); pm->SendStream(this->GetConnectionID(), vtkProcessModule::RENDER_SERVER | vtkProcessModule::CLIENT, stream); return true; } //---------------------------------------------------------------------------- void vtkSMKWEIlluminatedLinesRepresentationProxy::UpdateShadingParameters() { double diffuse = this->Diffuse; double specular = this->Specular; double ambient = this->Ambient; vtkSMPropertyHelper(this->Property,"Ambient").Set(ambient); vtkSMPropertyHelper(this->Property,"Diffuse").Set(diffuse); vtkSMPropertyHelper(this->Property,"Specular").Set(specular); this->Property->UpdateVTKObjects(); } //---------------------------------------------------------------------------- void vtkSMKWEIlluminatedLinesRepresentationProxy::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } vtkedge-0.2.0~20110819/ParaViewPlugins/vtkSMKWEIlluminatedLinesRepresentationProxy.h0000644000175000017500000000427011363410610030052 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkSMKWEIlluminatedLinesRepresentationProxy - representation proxy for // adding support for vtkKWEIlluminatedLinesPainter in ParaView // .SECTION Description // vtkSMKWEIlluminatedLinesRepresentationProxy is a representation proxy that // adds support for vtkKWEIlluminatedLinesPainter in ParaView. #ifndef __vtkSMKWEIlluminatedLinesRepresentationProxy_h #define __vtkSMKWEIlluminatedLinesRepresentationProxy_h #include "vtkSMSurfaceRepresentationProxy.h" class vtkSMKWEIlluminatedLinesRepresentationProxy : public vtkSMSurfaceRepresentationProxy { public: static vtkSMKWEIlluminatedLinesRepresentationProxy* New(); vtkTypeRevisionMacro(vtkSMKWEIlluminatedLinesRepresentationProxy, vtkSMSurfaceRepresentationProxy); void PrintSelf(ostream& os, vtkIndent indent); //BTX protected: vtkSMKWEIlluminatedLinesRepresentationProxy(); ~vtkSMKWEIlluminatedLinesRepresentationProxy(); // Description: // Internal method to update actual diffuse/specular/ambient coefficients used // based on the representation. virtual void UpdateShadingParameters(); // Description: // This method is called after CreateVTKObjects(). // This gives subclasses an opportunity to do some post-creation // initialization. virtual bool EndCreateVTKObjects(); private: vtkSMKWEIlluminatedLinesRepresentationProxy(const vtkSMKWEIlluminatedLinesRepresentationProxy&); // Not implemented void operator=(const vtkSMKWEIlluminatedLinesRepresentationProxy&); // Not implemented //ETX }; #endif vtkedge-0.2.0~20110819/ParaViewPlugins/vtkKWEExtension.xml0000644000175000017500000000630211354435271022720 0ustar mathieumathieu vtkedge-0.2.0~20110819/Copyright.txt0000644000175000017500000000321611364335730016560 0ustar mathieumathieu/*========================================================================= This file is part of VTKEdge. See vtkedge.org for more information. Copyright (c) 2010 Kitware, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither name of Kitware nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ vtkedge-0.2.0~20110819/IO/0000755000175000017500000000000011630434665014357 5ustar mathieumathieuvtkedge-0.2.0~20110819/IO/vtkKWEXMLElement.cxx0000644000175000017500000005760011363410610020144 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEXMLElement.h" #include "vtkCollection.h" #include "vtkObjectFactory.h" #include "vtkSmartPointer.h" vtkCxxRevisionMacro(vtkKWEXMLElement, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEXMLElement); #include #include #include #if defined(_WIN32) && !defined(__CYGWIN__) # define SNPRINTF _snprintf #else # define SNPRINTF snprintf #endif struct vtkKWEXMLElementInternals { vtkstd::vector AttributeNames; vtkstd::vector AttributeValues; typedef vtkstd::vector > VectorOfElements; VectorOfElements NestedElements; vtkstd::string CharacterData; }; //---------------------------------------------------------------------------- vtkKWEXMLElement::vtkKWEXMLElement() { this->Name = 0; this->Id = 0; this->Parent = 0; this->Internal = new vtkKWEXMLElementInternals; } //---------------------------------------------------------------------------- vtkKWEXMLElement::~vtkKWEXMLElement() { this->SetName(0); this->SetId(0); delete this->Internal; } //---------------------------------------------------------------------------- void vtkKWEXMLElement::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Id: " << (this->Id?this->Id:"") << endl; os << indent << "Name: " << (this->Name?this->Name:"") << endl; unsigned int numNested = this->GetNumberOfNestedElements(); for (unsigned int i=0; i< numNested; i++) { if (this->GetNestedElement(i)) { this->GetNestedElement(i)->PrintSelf(os, indent.GetNextIndent()); } } } //---------------------------------------------------------------------------- void vtkKWEXMLElement::AddAttribute(const char* attrName, unsigned int attrValue) { vtksys_ios::ostringstream valueStr; valueStr << attrValue << ends; this->AddAttribute(attrName, valueStr.str().c_str()); } //---------------------------------------------------------------------------- void vtkKWEXMLElement::AddAttribute(const char* attrName, int attrValue) { vtksys_ios::ostringstream valueStr; valueStr << attrValue << ends; this->AddAttribute(attrName, valueStr.str().c_str()); } //---------------------------------------------------------------------------- void vtkKWEXMLElement::AddAttribute(const char* attrName, unsigned long attrValue) { vtksys_ios::ostringstream valueStr; valueStr << attrValue << ends; this->AddAttribute(attrName, valueStr.str().c_str()); } #if defined(VTK_USE_64BIT_IDS) //---------------------------------------------------------------------------- void vtkKWEXMLElement::AddAttribute(const char* attrName, vtkIdType attrValue) { vtksys_ios::ostringstream valueStr; valueStr << attrValue << ends; this->AddAttribute(attrName, valueStr.str().c_str()); } #endif //---------------------------------------------------------------------------- void vtkKWEXMLElement::AddAttribute(const char* attrName, double attrValue) { vtksys_ios::ostringstream valueStr; valueStr << attrValue << ends; this->AddAttribute(attrName, valueStr.str().c_str()); } //---------------------------------------------------------------------------- void vtkKWEXMLElement::AddAttribute(const char* attrName, const char* attrValue) { if (!attrName || !attrValue) { return; } this->Internal->AttributeNames.push_back(attrName); this->Internal->AttributeValues.push_back(attrValue); } //---------------------------------------------------------------------------- void vtkKWEXMLElement::AddAttribute(const char* attrName, double* vals, unsigned int length) { if (!attrName || !vals || length == 0) { return; } vtksys_ios::ostringstream valueStr; for(unsigned int i=0; iAddAttribute(attrName, valueStr.str().c_str()); } //---------------------------------------------------------------------------- void vtkKWEXMLElement::AddAttribute(const char *attrName, int *vals, unsigned int length) { if (!attrName || !vals || length == 0) { return; } vtksys_ios::ostringstream valueStr; for(unsigned int i=0; iAddAttribute(attrName, valueStr.str().c_str()); } //---------------------------------------------------------------------------- void vtkKWEXMLElement::AddAttribute(const char* attrName, unsigned long* vals, unsigned int length) { if (!attrName || !vals || length == 0) { return; } vtksys_ios::ostringstream valueStr; for(unsigned int i=0; iAddAttribute(attrName, valueStr.str().c_str()); } #if defined(VTK_USE_64BIT_IDS) //---------------------------------------------------------------------------- void vtkKWEXMLElement::AddAttribute(const char* attrName, vtkIdType* vals, unsigned int length) { if (!attrName || !vals || length == 0) { return; } vtksys_ios::ostringstream valueStr; for(unsigned int i=0; iAddAttribute(attrName, valueStr.str().c_str()); } #endif //---------------------------------------------------------------------------- void vtkKWEXMLElement::SetAttribute(const char *attrName, const char *attrValue) { if (!attrName || !attrValue) { return; } // iterate over the names, and find if the attribute name exists. size_t numAttributes = this->Internal->AttributeNames.size(); size_t i; for(i=0; i < numAttributes; ++i) { if(strcmp(this->Internal->AttributeNames[i].c_str(), attrName) == 0) { this->Internal->AttributeValues[i] = attrValue; return; } } // add the attribute. this->AddAttribute(attrName, attrValue); } //---------------------------------------------------------------------------- void vtkKWEXMLElement::ReadXMLAttributes(const char** atts) { this->Internal->AttributeNames.clear(); this->Internal->AttributeValues.clear(); if(atts) { const char** attsIter = atts; unsigned int count=0; while(*attsIter++) { ++count; } unsigned int numberOfAttributes = count/2; unsigned int i; for(i=0;i < numberOfAttributes; ++i) { this->AddAttribute(atts[i*2], atts[i*2+1]); } } } //---------------------------------------------------------------------------- void vtkKWEXMLElement::RemoveAllNestedElements() { this->Internal->NestedElements.clear(); } //---------------------------------------------------------------------------- void vtkKWEXMLElement::RemoveNestedElement(vtkKWEXMLElement* element) { vtkstd::vector >::iterator iter = this->Internal->NestedElements.begin(); for ( ; iter != this->Internal->NestedElements.end(); ++iter) { if (iter->GetPointer() == element) { this->Internal->NestedElements.erase(iter); break; } } } //---------------------------------------------------------------------------- void vtkKWEXMLElement::AddNestedElement(vtkKWEXMLElement* element) { this->AddNestedElement(element, 1); } //---------------------------------------------------------------------------- void vtkKWEXMLElement::AddNestedElement(vtkKWEXMLElement* element, int setParent) { if (setParent) { element->SetParent(this); } this->Internal->NestedElements.push_back(element); } //---------------------------------------------------------------------------- void vtkKWEXMLElement::AddCharacterData(const char* data, int length) { this->Internal->CharacterData.append(data, length); } //---------------------------------------------------------------------------- const char *vtkKWEXMLElement::GetAttribute(const char *name) { size_t numAttributes = this->Internal->AttributeNames.size(); size_t i; for(i=0; i < numAttributes; ++i) { if(strcmp(this->Internal->AttributeNames[i].c_str(), name) == 0) { return this->Internal->AttributeValues[i].c_str(); } } return 0; } //---------------------------------------------------------------------------- const char* vtkKWEXMLElement::GetCharacterData() { return this->Internal->CharacterData.c_str(); } //---------------------------------------------------------------------------- void vtkKWEXMLElement::PrintXML() { this->PrintXML(cout, vtkIndent()); } //---------------------------------------------------------------------------- void vtkKWEXMLElement::PrintXML(ostream& os, vtkIndent indent) { os << indent << "<" << (this->Name?this->Name:"NoName"); size_t numAttributes = this->Internal->AttributeNames.size(); size_t i; for(i=0;i < numAttributes; ++i) { const char* aName = this->Internal->AttributeNames[i].c_str(); const char* aValue = this->Internal->AttributeValues[i].c_str(); // we always print the encoded value. The expat parser processes encoded // values when reading them, hence we don't need any decoding when reading // the values back. const vtkStdString& sanitizedValue = vtkKWEXMLElement::Encode(aValue); os << " " << (aName?aName:"NoName") << "=\"" << (aValue?sanitizedValue.c_str():"NoValue") << "\""; } size_t numberOfNestedElements = this->Internal->NestedElements.size(); if(numberOfNestedElements > 0) { os << ">\n"; for(i=0;i < numberOfNestedElements;++i) { vtkIndent nextIndent = indent.GetNextIndent(); this->Internal->NestedElements[i]->PrintXML(os, nextIndent); } os << indent << "Name?this->Name:"NoName") << ">\n"; } else { os << "/>\n"; } } //---------------------------------------------------------------------------- void vtkKWEXMLElement::SetParent(vtkKWEXMLElement* parent) { this->Parent = parent; } //---------------------------------------------------------------------------- vtkKWEXMLElement* vtkKWEXMLElement::GetParent() { return this->Parent; } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetNumberOfNestedElements() { return static_cast(this->Internal->NestedElements.size()); } //---------------------------------------------------------------------------- vtkKWEXMLElement* vtkKWEXMLElement::GetNestedElement(unsigned int index) { if(static_cast(index) < this->Internal->NestedElements.size()) { return this->Internal->NestedElements[index]; } return 0; } //---------------------------------------------------------------------------- vtkKWEXMLElement* vtkKWEXMLElement::LookupElement(const char* id) { return this->LookupElementUpScope(id); } //---------------------------------------------------------------------------- vtkKWEXMLElement* vtkKWEXMLElement::FindNestedElement(const char* id) { size_t numberOfNestedElements = this->Internal->NestedElements.size(); size_t i; for(i=0;i < numberOfNestedElements;++i) { const char* nid = this->Internal->NestedElements[i]->GetId(); if(nid && strcmp(nid, id) == 0) { return this->Internal->NestedElements[i]; } } return 0; } //---------------------------------------------------------------------------- vtkKWEXMLElement* vtkKWEXMLElement::FindNestedElementByName(const char* name) { vtkKWEXMLElementInternals::VectorOfElements::iterator iter = this->Internal->NestedElements.begin(); for(; iter != this->Internal->NestedElements.end(); ++iter) { const char* cur_name = (*iter)->GetName(); if(name && cur_name && strcmp(cur_name, name) == 0) { return (*iter); } } return 0; } //---------------------------------------------------------------------------- vtkKWEXMLElement* vtkKWEXMLElement::LookupElementInScope(const char* id) { // Pull off the first qualifier. const char* end = id; while(*end && (*end != '.')) ++end; size_t len = end - id; char* name = new char[len+1]; strncpy(name, id, len); name[len] = '\0'; // Find the qualifier in this scope. vtkKWEXMLElement* next = this->FindNestedElement(name); if(next && (*end == '.')) { // Lookup rest of qualifiers in nested scope. next = next->LookupElementInScope(end+1); } delete [] name; return next; } //---------------------------------------------------------------------------- vtkKWEXMLElement* vtkKWEXMLElement::LookupElementUpScope(const char* id) { // Pull off the first qualifier. const char* end = id; while(*end && (*end != '.')) ++end; size_t len = end - id; char* name = new char[len+1]; strncpy(name, id, len); name[len] = '\0'; // Find most closely nested occurrence of first qualifier. vtkKWEXMLElement* curScope = this; vtkKWEXMLElement* start = 0; while(curScope && !start) { start = curScope->FindNestedElement(name); curScope = curScope->GetParent(); } if(start && (*end == '.')) { start = start->LookupElementInScope(end+1); } delete [] name; return start; } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetScalarAttribute(const char* name, int* value) { return this->GetVectorAttribute(name, 1, value); } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetScalarAttribute(const char* name, unsigned int* value) { return this->GetVectorAttribute(name, 1, value); } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetScalarAttribute(const char* name, unsigned long* value) { return this->GetVectorAttribute(name, 1, value); } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetScalarAttribute(const char* name, float* value) { return this->GetVectorAttribute(name, 1, value); } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetScalarAttribute(const char* name, double* value) { return this->GetVectorAttribute(name, 1, value); } #if defined(VTK_USE_64BIT_IDS) //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetScalarAttribute(const char* name, vtkIdType* value) { return this->GetVectorAttribute(name, 1, value); } #endif //---------------------------------------------------------------------------- template unsigned int vtkKWEXMLVectorAttributeParse(const char* str, unsigned int length, T* data) { if(!str || !length) { return 0; } vtksys_ios::stringstream vstr; vstr << str << ends; for(unsigned int i=0; i < length; ++i) { vstr >> data[i]; if(!vstr) { return i; } } return length; } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetVectorAttribute(const char* name, unsigned int length, int* data) { return vtkKWEXMLVectorAttributeParse(this->GetAttribute(name), length, data); } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetVectorAttribute(const char* name, unsigned int length, unsigned int* data) { return vtkKWEXMLVectorAttributeParse(this->GetAttribute(name), length, data); } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetVectorAttribute(const char* name, unsigned int length, unsigned long* data) { return vtkKWEXMLVectorAttributeParse(this->GetAttribute(name), length, data); } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetVectorAttribute(const char* name, unsigned int length, float* data) { return vtkKWEXMLVectorAttributeParse(this->GetAttribute(name), length, data); } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetVectorAttribute(const char* name, unsigned int length, double* data) { return vtkKWEXMLVectorAttributeParse(this->GetAttribute(name), length, data); } #if defined(VTK_USE_64BIT_IDS) //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetVectorAttribute(const char* name, unsigned int length, vtkIdType* data) { return vtkKWEXMLVectorAttributeParse(this->GetAttribute(name), length, data); } #endif //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetCharacterDataAsVector(unsigned int length, int* data) { return vtkKWEXMLVectorAttributeParse(this->GetCharacterData(), length, data); } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetCharacterDataAsVector(unsigned int length, float* data) { return vtkKWEXMLVectorAttributeParse(this->GetCharacterData(), length, data); } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetCharacterDataAsVector(unsigned int length, double* data) { return vtkKWEXMLVectorAttributeParse(this->GetCharacterData(), length, data); } //---------------------------------------------------------------------------- void vtkKWEXMLElement::GetElementsByName(const char* name, vtkCollection* elements) { if (!elements) { vtkErrorMacro("elements cannot be NULL."); return; } if (!name) { vtkErrorMacro("name cannot be NULL."); return; } unsigned int numChildren = this->GetNumberOfNestedElements(); unsigned int cc; for (cc=0; cc < numChildren; cc++) { vtkKWEXMLElement* child = this->GetNestedElement(cc); if (child && child->GetName() && strcmp(child->GetName(), name) == 0) { elements->AddItem(child); } } for (cc=0; cc < numChildren; cc++) { vtkKWEXMLElement* child = this->GetNestedElement(cc); if (child) { child->GetElementsByName(name, elements); } } } //---------------------------------------------------------------------------- vtkStdString vtkKWEXMLElement::Encode(const char* plaintext) { //escape any characters that are not allowed in XML vtkStdString sanitized = ""; if (!plaintext) { return sanitized; } const char toescape[] = { '&', '\'', '<', '>', '\"', '\r', '\n', '\t', 0}; size_t pt_length = strlen(plaintext); for (size_t cc = 0; cc < pt_length; cc++) { const char* escape_char = toescape; for ( ; *escape_char != 0; escape_char++) { if (plaintext[cc] == *escape_char) { break; } } if (*escape_char) { char temp[20]; SNPRINTF(temp, 20, "&#x%x;", static_cast(*escape_char)); sanitized += temp; } else { sanitized += plaintext[cc]; } } return sanitized; } #if defined(VTK_USE_64BIT_IDS) //---------------------------------------------------------------------------- unsigned int vtkKWEXMLElement::GetCharacterDataAsVector(unsigned int length, vtkIdType* data) { return vtkKWEXMLVectorAttributeParse(this->GetCharacterData(), length, data); } #endif void vtkKWEXMLElement::Merge(vtkKWEXMLElement* element, const char* attributeName) { if(!element || 0 != strcmp(this->GetName(), element->GetName())) { return; } if(attributeName) { const char* attr1 = this->GetAttribute(attributeName); const char* attr2 = element->GetAttribute(attributeName); if(attr1 && attr2 && 0 != strcmp(attr1, attr2)) { return; } } // override character data if there is some if(!element->Internal->CharacterData.empty()) { this->Internal->CharacterData = element->Internal->CharacterData; } // add attributes from element to this, or override attribute values on this size_t numAttributes = element->Internal->AttributeNames.size(); size_t numAttributes2 = this->Internal->AttributeNames.size(); for(size_t i=0; i < numAttributes; ++i) { bool found = false; for(size_t j=0; !found && j < numAttributes2; ++j) { if(element->Internal->AttributeNames[i] == this->Internal->AttributeNames[j]) { this->Internal->AttributeValues[j] = element->Internal->AttributeValues[i]; found = true; } } // if not found, add it if(!found) { this->AddAttribute(element->Internal->AttributeNames[i].c_str(), element->Internal->AttributeValues[i].c_str()); } } // now recursively merge the children with the same names vtkKWEXMLElementInternals::VectorOfElements::iterator iter; vtkKWEXMLElementInternals::VectorOfElements::iterator iter2; for(iter = element->Internal->NestedElements.begin(); iter != element->Internal->NestedElements.end(); ++iter) { bool found = false; for(iter2 = this->Internal->NestedElements.begin(); iter2 != this->Internal->NestedElements.end(); ++iter2) { const char* attr1 = attributeName ? this->GetAttribute(attributeName) : NULL; const char* attr2 = attributeName ? element->GetAttribute(attributeName) : NULL; if(0 == strcmp((*iter)->Name, (*iter2)->Name) && (!attributeName || (!attr1 || !attr2 || 0 == strcmp(attr1, attr2)))) { (*iter2)->Merge(*iter, attributeName); found = true; } } // if not found, add it if(!found) { vtkSmartPointer newElement = vtkSmartPointer::New(); newElement->SetName((*iter)->GetName()); newElement->SetId((*iter)->GetId()); newElement->Internal->AttributeNames = (*iter)->Internal->AttributeNames; newElement->Internal->AttributeValues = (*iter)->Internal->AttributeValues; this->AddNestedElement(newElement); newElement->Merge(*iter, attributeName); } } } vtkedge-0.2.0~20110819/IO/vtkKWESerializableObject.h0000644000175000017500000001056511363410610021353 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWESerializableObject - Superclass for serializable objects // .SECTION Description // vtkKWESerializableObject works with vtkKWESerializer and its subclasses // to provide a serialization framework. The user asks a vtkKWESerializer to // write or read an archive consisting of a collection of vtkKWESerializableObjects. // The serializer then reads/writes the archive in collaboration with the // serializable objects. // When reading an archive, the serializer creates the appropriate objects // (usually using the instantiator) and then calls Serialize() on them. // It is then the responsability of these objects to restore their state // by calling functions provided by the serializer. For example, this may // look like: // \code // void vtkKWEObjectTreeNodeBase::Serialize(vtkKWESerializer* ser) // { // ser->Serialize("Attributes", this->Attributes); // ser->Serialize("Properties", this->Properties); // vtkKWESerializableObject *parent = this->Parent; // ser->Serialize("Parent", parent, true); // true indicates it is a weak ptr // if (ser->IsWriting()) // { // vtkstd::vector< vtkSmartPointer > myVector = // vtkKWESerializer::ToBase > >( // *this->Children ); // ser->Serialize("Children", myVector); // } // else // { // this->Parent = vtkKWEObjectTreeNodeBase::SafeDownCast(parent); // vtkstd::vector< vtkSmartPointer > myVector; // ser->Serialize("Children", myVector); // vtkKWESerializer::FromBase(myVector, *this->Children); // } // \endcode // When writing the archive, the serializer calls Serialize() on the "root" // objects (the ones passed by the user) which then use the serializer methods // to write themselves in the archive. // // Note that there is only one Serialize() method that does reading and writing. // This works because the methods in vtkKWESerializer take references to data // member and can read or write them as appropriate. In cases where the class // needs to do something different during reading or writing, you can separate // the implementation using if (ser->IsWriting()) {..} else {..} as shown // in the example above. // // You can also implement more sophisticated serialization code by using // temporaries during reading and writing and copying them to the actual data // members yourself. Something like: // \code // void vtkSomeSerializableObject::Serialize(vtkKWESerializer* ser) // { // int foo; // if (ser->IsWriting) // { // // ... // } // else // { // int foo; // ser->Serialize(foo); // // Based on the value of foo, do something to data members // } // \endcode // // The serializer also supports versioning. You can get the version of the // archive being written or read using vtkKWESerializer::GetArchiveVersion() #ifndef __vtkKWESerializableObject_h #define __vtkKWESerializableObject_h #include "vtkObject.h" #include "VTKEdgeConfigure.h" // include configuration header class vtkKWESerializer; class VTKEdge_IO_EXPORT vtkKWESerializableObject : public vtkObject { public: static vtkKWESerializableObject *New(); vtkTypeRevisionMacro(vtkKWESerializableObject,vtkObject); // Description: // Reads the state of an instance from an archive OR // writes the state of an instance to an archive. See // the documentation for this class for details. virtual void Serialize(vtkKWESerializer*) {} protected: vtkKWESerializableObject(); ~vtkKWESerializableObject(); private: vtkKWESerializableObject(const vtkKWESerializableObject&); // Not implemented. void operator=(const vtkKWESerializableObject&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/IO/vtkKWEXMLParser.h0000644000175000017500000000505511363410610017431 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEXMLParser parses XML files. // .SECTION Description // This is a subclass of vtkXMLParser that constructs a DOM representation // of parsed XML using vtkKWEXMLElement. #ifndef __vtkKWEXMLParser_h #define __vtkKWEXMLParser_h #include "vtkXMLParser.h" #include "VTKEdgeConfigure.h" // include configuration header class vtkKWEXMLElement; class VTKEdge_IO_EXPORT vtkKWEXMLParser : public vtkXMLParser { public: vtkTypeRevisionMacro(vtkKWEXMLParser,vtkXMLParser); void PrintSelf(ostream& os, vtkIndent indent); static vtkKWEXMLParser* New(); // Description: // Write the parsed XML into the output stream. void PrintXML(ostream& os); // Description: // Get the root element from the XML document. vtkKWEXMLElement* GetRootElement(); // Description: // Get/Set the file from which to read the configuration. vtkSetStringMacro(FileName); vtkGetStringMacro(FileName); protected: vtkKWEXMLParser(); ~vtkKWEXMLParser(); void StartElement(const char* name, const char** atts); void EndElement(const char* name); void CharacterDataHandler(const char* data, int length); void AddElement(vtkKWEXMLElement* element); void PushOpenElement(vtkKWEXMLElement* element); vtkKWEXMLElement* PopOpenElement(); // The root XML element. vtkKWEXMLElement* RootElement; // The stack of elements currently being parsed. vtkKWEXMLElement** OpenElements; unsigned int NumberOfOpenElements; unsigned int OpenElementsSize; // Counter to assign unique element ids to those that don't have any. unsigned int ElementIdIndex; // Called by Parse() to read the stream and call ParseBuffer. Can // be replaced by subclasses to change how input is read. virtual int ParseXML(); private: vtkKWEXMLParser(const vtkKWEXMLParser&); // Not implemented. void operator=(const vtkKWEXMLParser&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/IO/vtkKWEXMLArchiveWriter.h0000644000175000017500000002003711363410610020750 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEXMLArchiveWriter - Writes an XML archive to output stream // .SECTION Description // Given a vector of vtkObject, vtkKWEXMLArchiveWriter writes // the object graph in an XML format. Note, to be written an object // must either be a subclass of vtkSerializableObject or have a helper // registered with vtkKWESerializationHelperMap which knows how to // serialize the object type. All objects are written in a flat collection // under the root element. All references to these objects are stored using // elements of type Pointer. All objects in the input vector are stored under // a RootObjects element. For example: // \code // // // // // // // // // // // // // // // // // // // // // // // // // // \endcode // .SECTION See Also // vtkKWESerializer #ifndef __vtkKWEXMLArchiveWriter_h #define __vtkKWEXMLArchiveWriter_h #include "vtkKWESerializer.h" #include "VTKEdgeConfigure.h" // include configuration header #include // Vector of smart pointers #include "vtkSmartPointer.h" // Vector of smart pointers //BTX struct vtkKWEXMLArchiveWriterInternals; class vtkKWEXMLElement; //ETX class VTKEdge_IO_EXPORT vtkKWEXMLArchiveWriter : public vtkKWESerializer { public: static vtkKWEXMLArchiveWriter *New(); vtkTypeRevisionMacro(vtkKWEXMLArchiveWriter,vtkKWESerializer); void PrintSelf(ostream& os, vtkIndent indent); // Description: // This method returns true if the serializer is an output // serializer (writer). Returns true. virtual bool IsWriting() {return true;} // Description: // This is the main entry point used to write a vector of // objects to the XML archive. The rootName is the name // of the root XML element in the archive. This name is // not used when restoring the archive so it is for information // only. For example: // \code // vtkKWEObjectTreeTransformableNode *root = // vtkKWEObjectTreeTransformableNode::New(); // root->SetName("RootNode"); // // vtkKWEObjectTreeTransformableNode *child = // vtkKWEObjectTreeTransformableNode::New(); // root->SetName("Child Node"); // root->AddChild( child ); // // vtkSmartPointer writer = // vtkSmartPointer::New(); // vtksys_ios::ostringstream ostr; // writer->SetArchiveVersion(1); // vtkstd::vector > objs; // objs.push_back(root); // writer->Serialize(ostr, "ObjectTree", objs); // \endcode virtual void Serialize(ostream& ostr, const char* rootName, vtkstd::vector >& objs); // Description: // Additional entry point, used to write a vector of // objects to the XML archive, in the form of a vtkKWEXMLElement which // is assumed to have been allocated by the caller. virtual void Serialize(vtkKWEXMLElement* elem, const char* rootName, vtkstd::vector >& objs); // Description: // Additional entry point, used to write a single (root) object // to the XML archive, in the form of a vtkKWEXMLElement which // is assumed to have been allocated by the caller. virtual void Serialize(vtkKWEXMLElement* elem, const char* rootName, vtkObject *objs); // Description: // Serializes a single integer. virtual void Serialize(const char* name, int& val); // Description: // Serializes an array. virtual void Serialize(const char* name, int*& val, unsigned int& length); // Description: // Serializes a single unsigned long. virtual void Serialize(const char* name, unsigned long& val) ; // Description: // Serializes an array. virtual void Serialize(const char* name, unsigned long*& val, unsigned int& length); // Description: // Reads a single vtkIdType. #if defined(VTK_USE_64BIT_IDS) virtual void Serialize(const char* name, vtkIdType& val); #endif // Description: // Reads an array. #if defined(VTK_USE_64BIT_IDS) virtual void Serialize(const char* name, vtkIdType*& val, unsigned int& length); #endif // Description: // Serializes a single double. virtual void Serialize(const char* name, double& val); // Description: // Serializes an array. virtual void Serialize(const char* name, double*& val, unsigned int& length); // Description: // Serializes a string. virtual void Serialize(const char* name, char*& str); // Description: // Serializes a string. virtual void Serialize(const char* name, vtkstd::string& str); // Description: // Serializes a vtkObject. Note, the object must either be subclass of // vtkKWESerializableObject or have a helper registered with // vtkKWESerializableObjectManager which knows how to serialize the object // type. The weakPtr parameter is actually ignored (we don't write an // attribute indicating it is weak, if it is) because the reading code will // have the same parameter specifying the pointer is weak. Here for symmetry. virtual void Serialize(const char* name, vtkObject*& object, bool weakPtr = false); // Description: // Serializes a vtkInformationObject. virtual void Serialize(const char* name, vtkInformation* info); // Description: // Serializes a vector of vtkObjects. The weakPtr parameter // is actually ignored (we don't write an attribute indicating it is weak, // if it is) because the reading code will have the same paremter specifying // the pointer is weak. Here for symmetry. virtual void Serialize(const char* name, vtkstd::vector >& objs, bool weakPtr = false); // Description: // Serializes a map from int to vector of vtkObjects. virtual void Serialize(const char* name, vtkstd::map > >& objs); protected: vtkKWEXMLArchiveWriter(); ~vtkKWEXMLArchiveWriter(); // Description: // Try to serialize the given vtkObject if it has not been serialized already. // If the object could not be serialized then return 0, else return the // id for serialized object's xml tag. The id is always greater than or // equal to 1. If the object has already been serialized then this will just // lookup and return the id. virtual unsigned int Serialize(vtkObject*& obj); private: vtkKWEXMLArchiveWriter(const vtkKWEXMLArchiveWriter&); // Not implemented. void operator=(const vtkKWEXMLArchiveWriter&); // Not implemented. virtual void CreateDOM(const char* rootName, vtkstd::vector >& objs); void SetRootElement(vtkKWEXMLElement*); // Description: // Serializes a vtkInformationObject. virtual void Serialize(vtkKWEXMLElement* elem, vtkInformation* info); vtkKWEXMLArchiveWriterInternals* Internal; vtkKWEXMLElement* RootElement; }; #endif vtkedge-0.2.0~20110819/IO/vtkKWECommonSerializationHelper.cxx0000644000175000017500000002074711363410610023322 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWECommonSerializationHelper.h" #include "vtkDoubleArray.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkIntArray.h" #include "vtkKWESerializationHelperMap.h" #include "vtkKWESerializer.h" #include "vtkKWEXMLElement.h" #include "vtkObjectFactory.h" #include "vtkTransform.h" vtkCxxRevisionMacro(vtkKWECommonSerializationHelper, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWECommonSerializationHelper); //----------------------------------------------------------------------------- vtkKWECommonSerializationHelper::vtkKWECommonSerializationHelper() { } //----------------------------------------------------------------------------- int vtkKWECommonSerializationHelper::Serialize(vtkObject *object, vtkKWESerializer *serializer) { if (vtkTransform::SafeDownCast(object)) { this->SerializeTransform(vtkTransform::SafeDownCast(object), serializer); return 1; } // make sure object is a type of vtkDataArray that is supported else if (vtkDataArray::SafeDownCast(object) && this->GetSerializationType(object)) { this->SerializeDataArray(vtkDataArray::SafeDownCast(object), serializer); return 1; } return 0; } //----------------------------------------------------------------------------- void vtkKWECommonSerializationHelper::RegisterWithHelperMap() { vtkKWESerializationHelperMap::RegisterHelperForClass("vtkTransform", this); vtkKWESerializationHelperMap::RegisterHelperForClass("vtkIdTypeArray", this); vtkKWESerializationHelperMap::RegisterHelperForClass("vtkDoubleArray", this); vtkKWESerializationHelperMap::RegisterHelperForClass("vtkIntArray", this); } //----------------------------------------------------------------------------- void vtkKWECommonSerializationHelper::UnRegisterWithHelperMap() { vtkKWESerializationHelperMap::UnRegisterHelperForClass("vtkTransform", this); vtkKWESerializationHelperMap::UnRegisterHelperForClass("vtkIdTypeArray", this); vtkKWESerializationHelperMap::UnRegisterHelperForClass("vtkDoubleArray", this); vtkKWESerializationHelperMap::UnRegisterHelperForClass("vtkIntArray", this); } //----------------------------------------------------------------------------- void vtkKWECommonSerializationHelper::SerializeTransform(vtkTransform *transform, vtkKWESerializer *serializer) { if (serializer->IsWriting()) { unsigned int length = 16; double *elementsPtr = *transform->GetMatrix()->Element; // just the matrix for now... plan to add better support for serializing transforms serializer->Serialize("Matrix", elementsPtr, length); } else { unsigned int length = 0; double *elements = 0; serializer->Serialize("Matrix", elements, length); if (length > 0) { transform->Concatenate(elements); delete [] elements; } } } //----------------------------------------------------------------------------- void vtkKWECommonSerializationHelper::SerializeDataArray(vtkDataArray *dataArray, vtkKWESerializer *serializer) { if (serializer->IsWriting()) { if (dataArray->HasInformation()) { serializer->Serialize("ArrayInformation", dataArray->GetInformation()); } int numberOfComponents = dataArray->GetNumberOfComponents(); serializer->Serialize("NumberOfComponents", numberOfComponents); // Upon reading we are going to be limited to array of length vtkIdType, // which if not using 64-bit ID's means at most ~2^31 (~2 billion) values... // which is a LOT when considering this will be written as ASCII (this // serialization is NOT intended for storing LARGE data). Therefore, for the // time being, we write out at most what can be represented by an int. unsigned long numberOfValuesLong = dataArray->GetDataSize(); unsigned int numberOfValues = static_cast( static_cast(numberOfValuesLong) ); if (numberOfValues < numberOfValuesLong) { vtkErrorMacro("Unable to Serialize the entire array; too large!"); } // now handle the type specfic if (vtkIdTypeArray::SafeDownCast(dataArray)) { vtkIdType *arrayPtr = vtkIdTypeArray::SafeDownCast(dataArray)->GetPointer(0); serializer->Serialize("Array", arrayPtr, numberOfValues); } else if (vtkDoubleArray::SafeDownCast(dataArray)) { double *arrayPtr = vtkDoubleArray::SafeDownCast(dataArray)->GetPointer(0); serializer->Serialize("Array", arrayPtr, numberOfValues); } else if (vtkIntArray::SafeDownCast(dataArray)) { int *arrayPtr = vtkIntArray::SafeDownCast(dataArray)->GetPointer(0); serializer->Serialize("Array", arrayPtr, numberOfValues); } } else { // handle vtkInformation, if present vtkSmartPointer infoObject = vtkSmartPointer::New(); serializer->Serialize("ArrayInformation", infoObject); if (infoObject->GetNumberOfKeys() > 0) { dataArray->GetInformation()->Copy(infoObject, 1); } // how many components int numberOfComponents; serializer->Serialize("NumberOfComponents", numberOfComponents); dataArray->SetNumberOfComponents(numberOfComponents); // now unsigned int numberOfValues = 0; if (vtkIdTypeArray::SafeDownCast(dataArray)) { vtkIdType *arrayPtr = 0; serializer->Serialize("Array", arrayPtr, numberOfValues); if (numberOfValues > 0) { // the dataArray assumes reposibility for the array allocated // in Serialize(), indicated by the final arguement of "0" vtkIdTypeArray::SafeDownCast(dataArray)->SetArray( arrayPtr, static_cast(numberOfValues), 0, vtkIdTypeArray::VTK_DATA_ARRAY_DELETE); } } else if (vtkDoubleArray::SafeDownCast(dataArray)) { double *arrayPtr = 0; serializer->Serialize("Array", arrayPtr, numberOfValues); if (numberOfValues > 0) { // the dataArray assumes reposibility for the array allocated // in Serialize(), indicated by the final arguement of "0" vtkDoubleArray::SafeDownCast(dataArray)->SetArray( arrayPtr, static_cast(numberOfValues), 0, vtkDoubleArray::VTK_DATA_ARRAY_DELETE); } } else if (vtkIntArray::SafeDownCast(dataArray)) { int *arrayPtr = 0; serializer->Serialize("Array", arrayPtr, numberOfValues); if (numberOfValues > 0) { // the dataArray assumes reposibility for the array allocated // in Serialize(), indicated by the final arguement of "0" vtkIntArray::SafeDownCast(dataArray)->SetArray( arrayPtr, static_cast(numberOfValues), 0, vtkIntArray::VTK_DATA_ARRAY_DELETE); } } } } //----------------------------------------------------------------------------- const char *vtkKWECommonSerializationHelper::GetSerializationType(vtkObject *object) { if (vtkTransform::SafeDownCast(object)) { return "vtkTransform"; } if (vtkIdTypeArray::SafeDownCast(object)) { return "vtkIdTypeArray"; } if (vtkDoubleArray::SafeDownCast(object)) { return "vtkDoubleArray"; } if (vtkIntArray::SafeDownCast(object)) { return "vtkIntArray"; } return 0; } //----------------------------------------------------------------------------- void vtkKWECommonSerializationHelper::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Supported ClassTypes:\n"; os << indent.GetNextIndent() << "vtkTransform\n"; os << indent.GetNextIndent() << "vtkDoubleArray\n"; os << indent.GetNextIndent() << "vtkIntArray\n"; os << indent.GetNextIndent() << "vtkIdTypeArray\n"; } vtkedge-0.2.0~20110819/IO/vtkKWESerializationHelperMap.cxx0000644000175000017500000001262411363410610022602 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWESerializationHelperMap.h" #include "vtkKWECommonSerializationHelper.h" #include "vtkKWESerializationHelper.h" #include "vtkObjectFactory.h" #include "vtkSmartPointer.h" #include "vtkToolkits.h" #include #include #ifdef VTK_USE_RENDERING #include "vtkKWERenderingSerializationHelper.h" #endif vtkCxxRevisionMacro(vtkKWESerializationHelperMap, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWESerializationHelperMap); bool vtkKWESerializationHelperMap::DefaultHelpersInstantiated = false; namespace { typedef vtkstd::map > ClassHelperMapType; struct vtkKWESerializationHelperMapInternals { ClassHelperMapType ClassMap; }; vtkKWESerializationHelperMapInternals vtkKWESerializationHelperMapClassMap; } //----------------------------------------------------------------------------- vtkKWESerializationHelperMap::vtkKWESerializationHelperMap() { } //----------------------------------------------------------------------------- vtkKWESerializationHelperMap::~vtkKWESerializationHelperMap() { } void vtkKWESerializationHelperMap::InstantiateDefaultHelpers() { if (!DefaultHelpersInstantiated) { DefaultHelpersInstantiated = true; vtkSmartPointer commonHelper = vtkSmartPointer::New(); commonHelper->RegisterWithHelperMap(); #ifdef VTK_USE_RENDERING vtkSmartPointer renderingHelper = vtkSmartPointer::New(); renderingHelper->RegisterWithHelperMap(); #endif } } //----------------------------------------------------------------------------- void vtkKWESerializationHelperMap::RegisterHelperForClass(const char *classType, vtkKWESerializationHelper* helper) { vtkKWESerializationHelperMapClassMap.ClassMap[classType] = helper; } //----------------------------------------------------------------------------- void vtkKWESerializationHelperMap::UnRegisterHelperForClass(const char *classType, vtkKWESerializationHelper* helper) { ClassHelperMapType::iterator iter = vtkKWESerializationHelperMapClassMap.ClassMap.find(classType); if (iter != vtkKWESerializationHelperMapClassMap.ClassMap.end() && iter->second == helper) { vtkKWESerializationHelperMapClassMap.ClassMap.erase(iter); } } //----------------------------------------------------------------------------- void vtkKWESerializationHelperMap::RemoveAllHelpers() { vtkKWESerializationHelperMapClassMap.ClassMap.clear(); } //----------------------------------------------------------------------------- bool vtkKWESerializationHelperMap::IsSerializable(vtkObject *obj) { ClassHelperMapType::iterator iter = vtkKWESerializationHelperMapClassMap.ClassMap.find(obj->GetClassName()); if (iter != vtkKWESerializationHelperMapClassMap.ClassMap.end()) { return true; } return false; } //----------------------------------------------------------------------------- int vtkKWESerializationHelperMap::Serialize(vtkObject *object, vtkKWESerializer *serializer) { ClassHelperMapType::iterator iter = vtkKWESerializationHelperMapClassMap.ClassMap.find(object->GetClassName()); if (iter == vtkKWESerializationHelperMapClassMap.ClassMap.end()) { vtkGenericWarningMacro("Unable to serialize object: " << object->GetClassName()); return 0; } iter->second->Serialize(object, serializer); return 1; } //----------------------------------------------------------------------------- const char *vtkKWESerializationHelperMap::GetSerializationType(vtkObject *object) { ClassHelperMapType::iterator iter = vtkKWESerializationHelperMapClassMap.ClassMap.find(object->GetClassName()); if (iter == vtkKWESerializationHelperMapClassMap.ClassMap.end()) { vtkGenericWarningMacro("Unable to get serialization type: " << object->GetClassName()); return 0; } return iter->second->GetSerializationType(object); } //----------------------------------------------------------------------------- vtkKWESerializationHelper* vtkKWESerializationHelperMap::GetHelper(const char *classType) { ClassHelperMapType::iterator iter = vtkKWESerializationHelperMapClassMap.ClassMap.find(classType); if (iter == vtkKWESerializationHelperMapClassMap.ClassMap.end()) { return 0; } return iter->second; } //----------------------------------------------------------------------------- void vtkKWESerializationHelperMap::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/IO/vtkKWESerializationHelper.cxx0000644000175000017500000000205211363410610022136 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWESerializationHelper.h" #include vtkCxxRevisionMacro(vtkKWESerializationHelper, "$Revision: 1774 $"); //----------------------------------------------------------------------------- void vtkKWESerializationHelper::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/IO/vtkKWESerializer.h0000644000175000017500000002026311363410610017723 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWESerializer - Abstract superclass of input and output archivers // .SECTION Description // vtkKWESerializer and its sub-classes are used to serialize and de-serialize // a collection of objects to/from an io stream. The serializers can work // with vtkKWESerializableObject and its subclasses, or vtkObjects in general // that have a subclass of vtkKWESerializationHelper registered with // vtkKWESerializationHelperMap. It can walk a object graph and // serialize/deserialize all objects contained in it. Circular references are // supported. // In order to (most easily) add serialization support to your class, subclass // from vtkKWESerializableObject and re-implement its Serialize() method using // methods available in the serializer. Otherwise create a subclass // vtkKWESerializationHelper and register it with the serialization manager // See vtkKWESerializableObject for details. // .SECTION See Also // vtkKWESerializableObject vtkKWESerializationHelper vtkKWESerializationHelperMap #ifndef __vtkKWESerializer_h #define __vtkKWESerializer_h #include "vtkObject.h" #include "VTKEdgeConfigure.h" // include configuration header #include "vtkSmartPointer.h" // For collections #include // For vectors #include // For maps class vtkInformation; class VTKEdge_IO_EXPORT vtkKWESerializer : public vtkObject { public: vtkTypeRevisionMacro(vtkKWESerializer,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // This method returns true if the serializer is an output // serializer (writer) virtual bool IsWriting() = 0; // Description: // Serializes a single integer. virtual void Serialize(const char* name, int& val) = 0; // Description: // Serializes an array. virtual void Serialize(const char* name, int*& val, unsigned int& length) = 0; // Description: // Serializes a single unsigned long. virtual void Serialize(const char* name, unsigned long& val) = 0; // Description: // Serializes an array. virtual void Serialize(const char* name, unsigned long*& val, unsigned int& length) = 0; // Description: // Serializes a single vtkIdType. #if defined(VTK_USE_64BIT_IDS) virtual void Serialize(const char* name, vtkIdType& val) = 0; #endif // Description: // Serializes an array. #if defined(VTK_USE_64BIT_IDS) virtual void Serialize(const char* name, vtkIdType*& val, unsigned int& length) = 0; #endif // Description: // Serializes a single double. virtual void Serialize(const char* name, double& val) = 0; // Description: // Serializes an array. virtual void Serialize(const char* name, double*& val, unsigned int& length) = 0; // Description: // Serializes a string. virtual void Serialize(const char* name, char*& str) = 0; // Description: // Serializes a string. virtual void Serialize(const char* name, vtkstd::string& str) = 0; // Description: // Serializes a vtkObject. virtual void Serialize(const char* name, vtkObject*& obj, bool weakPtr = false) = 0; // Description: // Serializes a vtkInformationObject. Note that only keys registered // with the vtkKWEInformationKeyMap are restored. virtual void Serialize(const char* name, vtkInformation* info) = 0; // Description: // Serializes a vector of vtkObjects. virtual void Serialize(const char* name, vtkstd::vector >& objs, bool weakPtr = false) = 0; // Description: // Serializes a map from int to vector of vtkObjects. virtual void Serialize(const char* name, vtkstd::map > >& objs) = 0; // Description: // Set/Get the archive version. Make sure to set the version before // writing to an archive. When reading an archive, the version is read // from the input stream. vtkSetMacro(ArchiveVersion, unsigned int); vtkGetMacro(ArchiveVersion, unsigned int); // Description: // Helper function to make is easier to write containers of sub-classes // of vtkObject. For example: // \code // vtkstd::Container > sub; // vtkstd::vector > vec = // vtkKWESerializer::ToBase(sub); // ser->Serialize("Vector", vec); // \endcode // The container must support forward iteration, begin(), end(), and // push_back. template static vtkstd::vector > ToBase(Container& from) { vtkstd::vector > retVal; typename Container::iterator iter = from.begin(); for(; iter != from.end(); iter++) { retVal.push_back(*iter); } return retVal; } // Description: // Helper function to make it easier to read into containers of sub-classes // of vtkObject. For example: // \code // vtkstd::Container > sub; // vtkstd::vector > vec; // ser->Serialize("Vector", vec); // vtkKWESerializer::FromBase(vec, sub); // \endcode // The container must support forward iteration, begin(), end(), and // push_back. template static void FromBase( vtkstd::vector >& from, Container& to) { vtkstd::vector >::iterator iter = from.begin(); for(; iter != from.end(); iter++) { // to.push_back(static_cast(iter->GetPointer())); to.insert(to.end(), static_cast(iter->GetPointer())); } } // Description: // Helper function to make it easier to write maps of containers of sub-classes // of vtkObject. For example: // \code // vtkstd::map > > map = // vtkKWESerializer::ToBase(this->Internal->Associations); // ser->Serialize("Associations", map); // \endcode // The container must support forward iteration, begin(), end(), and // push_back. template static vtkstd::map > > ToBase(vtkstd::map& from) { vtkstd::map > > retVal; typename vtkstd::map::iterator iter = from.begin(); for(; iter != from.end(); iter++) { retVal[iter->first] = (ToBase(iter->second)); } return retVal; } // Description: // Helper function to make it easier to read maps of containers of sub-classes // of vtkObject. For example: // \code // vtkstd::map > > map; // ser->Serialize("Associations", map); // vtkKWESerializer::FromBase(map, this->Internal->Associations); // \endcode // The container must support forward iteration, begin(), end(), and // push_back. template static void FromBase( vtkstd::map > >& from, vtkstd::map& to) { vtkstd::map > >::iterator iter = from.begin(); for(; iter != from.end(); iter++) { vtkstd::vector >& f = iter->second; Container& t = to[iter->first]; FromBase(f, t); } } protected: vtkKWESerializer(); ~vtkKWESerializer() {} private: vtkKWESerializer(const vtkKWESerializer&); // Not implemented. void operator=(const vtkKWESerializer&); // Not implemented. unsigned int ArchiveVersion; }; #endif vtkedge-0.2.0~20110819/IO/CMakeLists.txt0000644000175000017500000000702611363410610017107 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Set of basic source files # ----------------------------------------------------------------------------- set(KIT_SRCS vtkKWECommonSerializationHelper.cxx vtkKWESerializableObject.cxx vtkKWESerializationHelper.cxx vtkKWESerializationHelperMap.cxx vtkKWESerializer.cxx vtkKWEXMLArchiveReader.cxx vtkKWEXMLArchiveWriter.cxx vtkKWEXMLElement.cxx vtkKWEXMLParser.cxx ) set_source_files_properties( vtkKWESerializationHelper.cxx vtkKWESerializer.cxx ABSTRACT ) # ----------------------------------------------------------------------------- # List the source files that should not be wrapped. # ----------------------------------------------------------------------------- #SET_SOURCE_FILES_PROPERTIES( # # WRAP_EXCLUDE) # ----------------------------------------------------------------------------- # List the kits from VTK that are needed by this project # ----------------------------------------------------------------------------- set(KIT_LIBS vtkKWECommon vtkIO ) # ----------------------------------------------------------------------------- # If building Rendering, add help for serialization # ----------------------------------------------------------------------------- if(VTK_USE_RENDERING) set(KIT_EXTRA_SRCS ${KIT_EXTRA_SRCS} vtkKWERenderingSerializationHelper.cxx ) set(KIT_LIBS ${KIT_LIBS} vtkRendering) endif(VTK_USE_RENDERING) # ----------------------------------------------------------------------------- # Create the library # ----------------------------------------------------------------------------- add_library(vtkKWEIO ${KIT_SRCS} ${KIT_EXTRA_SRCS}) target_link_libraries(vtkKWEIO ${KIT_LIBS}) # ----------------------------------------------------------------------------- # Testing # ----------------------------------------------------------------------------- if(BUILD_TESTING) add_subdirectory(Testing) endif(BUILD_TESTING) # ----------------------------------------------------------------------------- # Installation # ----------------------------------------------------------------------------- if(NOT VTKEdge_INSTALL_NO_LIBRARIES) install_targets( ${VTKEdge_INSTALL_LIB_DIR} RUNTIME_DIRECTORY ${VTKEdge_INSTALL_BIN_DIR} vtkKWEIO ) endif(NOT VTKEdge_INSTALL_NO_LIBRARIES) if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_INCLUDE_DIR} .h ${KIT_SRCS}) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) # ----------------------------------------------------------------------------- # This make it easy for other projects to get the list of files etc. in this # kit. # ----------------------------------------------------------------------------- include(${VTK_CMAKE_DIR}/vtkExportKit.cmake) vtk_export_kit2("KWEIO" "KWEIO" ${CMAKE_CURRENT_BINARY_DIR} "${KIT_SRCS}") vtkedge-0.2.0~20110819/IO/vtkKWERenderingSerializationHelper.h0000644000175000017500000000567311363410610023435 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWERenderingSerializationHelper - Concrete serialization helper for // Rendering package. // .SECTION Description // Concrete class for serialization of vtkObjects in the Rendering package using // vtkKWEXMLArchiveWriter and vtkKWEXMLArchiveReader. Only serialization of // vtkCamera (and its subclasses) is currently implemented. // .SECTION See Also // vtkKWESerializationHelperMap vtkKWESerializationHelper #ifndef __vtkKWERenderingSerializationHelper_h #define __vtkKWERenderingSerializationHelper_h #include "vtkKWESerializationHelper.h" #include "VTKEdgeConfigure.h" // include configuration header class vtkCamera; class vtkKWESerializer; class VTKEdge_IO_EXPORT vtkKWERenderingSerializationHelper : public vtkKWESerializationHelper { public: static vtkKWERenderingSerializationHelper *New(); vtkTypeRevisionMacro(vtkKWERenderingSerializationHelper, vtkKWESerializationHelper); void PrintSelf(ostream& os, vtkIndent indent); // Description: // This member registers ALL the classes supported by this helper with the // vtkKWESerializationHelperMap, which manages all the helpers. Should be // called after construction unless you only want to enable support for // a subset (in which case it must be done "manually" by calling // vtkKWESerializationHelperMap::RegisterHelperForClass() virtual void RegisterWithHelperMap(); // Description: // Unregister this helper (remove each class type/helper pair) with the // vtkKWESerializationHelperMap virtual void UnRegisterWithHelperMap(); // Description: // Get the value for the "type" attribute of the specfied object type virtual const char *GetSerializationType(vtkObject *object); // Description: // Serialize the input object. Returns 1 if successful. virtual int Serialize(vtkObject *object, vtkKWESerializer *serializer); //BTX protected: vtkKWERenderingSerializationHelper(); ~vtkKWERenderingSerializationHelper() {} // Description: // Serialize a vtkCamera void SerializeCamera(vtkCamera *camera, vtkKWESerializer *serializer); private: vtkKWERenderingSerializationHelper(const vtkKWERenderingSerializationHelper&); // Not implemented. void operator=(const vtkKWERenderingSerializationHelper&); // Not implemented. //ETX }; #endif vtkedge-0.2.0~20110819/IO/vtkKWEXMLArchiveWriter.cxx0000644000175000017500000004771211363410610021334 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEXMLArchiveWriter.h" #include "vtkInformation.h" #include "vtkInformationIdTypeKey.h" #include "vtkInformationIntegerKey.h" #include "vtkInformationIntegerVectorKey.h" #include "vtkInformationDoubleKey.h" #include "vtkInformationStringKey.h" #include "vtkInformationDoubleVectorKey.h" #include "vtkInformationIterator.h" #include "vtkInformationObjectBaseKey.h" #include "vtkInformationObjectBaseVectorKey.h" #include "vtkInformationKeyVectorKey.h" #include "vtkInformationStringVectorKey.h" #include "vtkKWEInformationKeyMap.h" #include "vtkKWESerializableObject.h" #include "vtkKWESerializationHelperMap.h" #include "vtkKWEXMLElement.h" #include "vtkObjectFactory.h" #include "vtkSmartPointer.h" #include #include #include #include "vtksys/ios/sstream" vtkCxxRevisionMacro(vtkKWEXMLArchiveWriter, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEXMLArchiveWriter); vtkCxxSetObjectMacro(vtkKWEXMLArchiveWriter, RootElement, vtkKWEXMLElement); struct vtkKWEXMLArchiveWriterInternals { vtkKWEXMLArchiveWriterInternals() : CurrentID(1) {} void Push(vtkKWEXMLElement* elem) { this->Stack.push_front(elem); } void Pop() { this->Stack.pop_front(); } vtkstd::list Stack; vtkstd::map IDs; unsigned int CurrentID; }; //---------------------------------------------------------------------------- vtkKWEXMLArchiveWriter::vtkKWEXMLArchiveWriter() { this->Internal = new vtkKWEXMLArchiveWriterInternals; vtkKWESerializationHelperMap::InstantiateDefaultHelpers(); this->RootElement = 0; } //---------------------------------------------------------------------------- vtkKWEXMLArchiveWriter::~vtkKWEXMLArchiveWriter() { delete this->Internal; this->SetRootElement(0); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } namespace { vtkSmartPointer BaseSerialize(const char* name, vtkKWEXMLArchiveWriterInternals* internal) { vtkKWEXMLElement* root = internal->Stack.front(); if (!root) { vtkGenericWarningMacro("Serialize cannot be called before setting the RootElement"); return 0; } vtkSmartPointer elem = vtkSmartPointer::New(); elem->SetName(name); root->AddNestedElement(elem); return elem; } } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(const char* name, vtkObject*& object, bool vtkNotUsed(weakPtr)) { vtkSmartPointer elem = BaseSerialize(name, this->Internal); if (!elem.GetPointer()) { return; } elem->AddAttribute("type", "Pointer"); if (object) { unsigned int id = this->Serialize(object); if (id > 0) { elem->AddAttribute("to_id", id); } } } //---------------------------------------------------------------------------- unsigned int vtkKWEXMLArchiveWriter::Serialize(vtkObject*& object) { if (!object) { return 0; } vtkstd::map::iterator iter = this->Internal->IDs.find(object); if (iter != this->Internal->IDs.end()) { return iter->second; } if (!this->RootElement) { vtkGenericWarningMacro("Serialize cannot be called before setting the RootElement"); return 0; } vtkKWESerializableObject *serializableObject = vtkKWESerializableObject::SafeDownCast(object); if (!serializableObject && !vtkInformation::SafeDownCast(object) && !vtkKWESerializationHelperMap::IsSerializable(object)) { return 0; } vtkSmartPointer newElem = vtkSmartPointer::New(); newElem->SetName("Object"); this->RootElement->AddNestedElement(newElem); // set the "type" attribute... may have to get from SerializationHelper if (serializableObject) { newElem->AddAttribute("type", serializableObject->GetClassName()); } else if (!vtkInformation::SafeDownCast(object)) { newElem->AddAttribute("type", vtkKWESerializationHelperMap::GetSerializationType(object)); } // type for vtkInformation added inside Serialize unsigned int id = this->Internal->CurrentID++; newElem->AddAttribute("id", id); this->Internal->IDs[object] = id; this->Internal->Push(newElem); if (serializableObject) { serializableObject->Serialize(this); } else if (vtkInformation::SafeDownCast(object)) { this->Serialize(newElem, vtkInformation::SafeDownCast(object)); } else { vtkKWESerializationHelperMap::Serialize(object, this); } this->Internal->Pop(); return id; } namespace { template void SerializeScalarKey(vtkInformation* info, KeyType* key, const char* keyName, vtkKWEXMLElement* parent) { vtkSmartPointer keyElem = vtkSmartPointer::New(); keyElem->SetName(keyName); parent->AddNestedElement(keyElem); ValueType val = info->Get(key); keyElem->AddAttribute("value", val); } template void SerializeVectorKey(vtkInformation* info, KeyType* key, const char* keyName, vtkKWEXMLElement* parent) { vtkSmartPointer keyElem = vtkSmartPointer::New(); keyElem->SetName(keyName); parent->AddNestedElement(keyElem); ValueType* vals = info->Get(key); unsigned int length = static_cast(info->Length(key)); keyElem->AddAttribute("values", vals, length); keyElem->AddAttribute("length", length); } void SerializeStringVectorKey(vtkInformation* info, vtkInformationStringVectorKey* key, const char* keyName, vtkKWEXMLElement* parent) { vtkSmartPointer keyElem = vtkSmartPointer::New(); keyElem->SetName(keyName); parent->AddNestedElement(keyElem); vtksys_ios::ostringstream valueStr; unsigned int length = static_cast(info->Length(key)); int* lengths = new int[length]; for (unsigned int i = 0; i < length; ++i) { if (i != 0) { valueStr << ","; } const char* tmpStr = info->Get(key, i); lengths[i] = static_cast(strlen(tmpStr)); valueStr << tmpStr; } keyElem->AddAttribute("values", valueStr.str().c_str()); keyElem->AddAttribute("lengths", lengths, length); keyElem->AddAttribute("length", length); delete[] lengths; } void SerializeKeyVectorKey(vtkInformation* info, vtkInformationKeyVectorKey* key, const char* keyName, vtkKWEXMLElement* parent) { vtkSmartPointer keyElem = vtkSmartPointer::New(); keyElem->SetName(keyName); parent->AddNestedElement(keyElem); vtksys_ios::ostringstream valueStr; unsigned int length = static_cast(info->Length(key)); for (unsigned int i = 0; i < length; ++i) { vtkInformationKey* tmpKey = info->Get(key, i); valueStr << vtkKWEInformationKeyMap::GetFullName(tmpKey) << " "; } keyElem->AddAttribute("values", valueStr.str().c_str()); keyElem->AddAttribute("length", length); } } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(const char* name, vtkInformation* info) { this->Serialize(BaseSerialize(name, this->Internal), info); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(vtkKWEXMLElement* elem, vtkInformation* info) { if (!elem) { return; } elem->AddAttribute("type", info->GetClassName()); vtkInformationIterator* iter = vtkInformationIterator::New(); iter->SetInformation(info); for (iter->GoToFirstItem(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { vtkInformationKey* key = iter->GetCurrentKey(); vtkstd::string keystr = vtkKWEInformationKeyMap::GetFullName(key); if (key->IsA("vtkInformationIntegerKey")) { SerializeScalarKey(info, static_cast(key), keystr.c_str(), elem); } else if (key->IsA("vtkInformationDoubleKey")) { SerializeScalarKey(info, static_cast(key), keystr.c_str(), elem); } else if (key->IsA("vtkInformationIdTypeKey")) { SerializeScalarKey(info, static_cast(key), keystr.c_str(), elem); } else if (key->IsA("vtkInformationStringKey")) { SerializeScalarKey(info, static_cast(key), keystr.c_str(), elem); } else if (key->IsA("vtkInformationDoubleVectorKey")) { SerializeVectorKey(info, static_cast(key), keystr.c_str(), elem); } else if (key->IsA("vtkInformationIntegerVectorKey")) { SerializeVectorKey(info, static_cast(key), keystr.c_str(), elem); } else if (key->IsA("vtkInformationStringVectorKey")) { SerializeStringVectorKey(info, static_cast(key), keystr.c_str(), elem); } else if (key->IsA("vtkInformationKeyVectorKey")) { SerializeKeyVectorKey(info, static_cast(key), keystr.c_str(), elem); } else if (key->IsA("vtkInformationObjectBaseKey")) { vtkObject *ptr =vtkObject::SafeDownCast( info->Get(static_cast(key))); // Returns 0 if ptr is null or isn't serializable unsigned int serializedId = this->Serialize(ptr); vtkSmartPointer keyElem = vtkSmartPointer::New(); keyElem->SetName(keystr.c_str()); elem->AddNestedElement(keyElem); keyElem->AddAttribute("to_id", serializedId); } else if (key->IsA("vtkInformationObjectBaseVectorKey")) { vtkSmartPointer keyElem = vtkSmartPointer::New(); keyElem->SetName(keystr.c_str()); elem->AddNestedElement(keyElem); vtkstd::vector ids; vtkInformationObjectBaseVectorKey* vecKey = static_cast(key); int size = vecKey->Size(info); for (int i = 0; i < size; ++i) { vtkObject *ptr = vtkObject::SafeDownCast(vecKey->Get(info, i)); // Returns 0 if ptr is null or isn't serializable unsigned int serializedId = this->Serialize(ptr); ids.push_back(serializedId); } unsigned int length = static_cast(ids.size()); unsigned long* idVec = new unsigned long[length]; vtkstd::copy(ids.begin(), ids.end(), idVec); keyElem->AddAttribute("ids", idVec, length); keyElem->AddAttribute("length", length); delete[] idVec; } } iter->Delete(); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(const char* name, vtkstd::vector >& objs, bool weakPtr/*=false*/) { vtkSmartPointer elem = BaseSerialize(name, this->Internal); if (!elem.GetPointer()) { return; } elem->AddAttribute("type", "vtkObjectVector"); this->Internal->Push(elem); vtkstd::vector >::iterator iter = objs.begin(); for(; iter != objs.end(); iter++) { vtkObject* obj = iter->GetPointer(); this->Serialize("Item", obj, weakPtr); } this->Internal->Pop(); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(const char* name, vtkstd::map > >& map) { vtkSmartPointer elem = BaseSerialize(name, this->Internal); if (!elem.GetPointer()) { return; } elem->AddAttribute("type", "vtkObjectVectorMap"); this->Internal->Push(elem); vtkstd::map > >::iterator iter = map.begin(); for(; iter != map.end(); iter++) { vtkstd::vector >& objs = iter->second; vtksys_ios::ostringstream str; str << "Key_" << iter->first; this->Serialize(str.str().c_str(), objs); } this->Internal->Pop(); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::CreateDOM(const char* rootName, vtkstd::vector >& objs) { // Initialize this->RootElement->SetName(rootName); this->RootElement->AddAttribute("version", this->GetArchiveVersion()); vtkSmartPointer elem = vtkSmartPointer::New(); elem->SetName("RootObjects"); this->RootElement->AddNestedElement(elem); this->Internal->Push(elem); vtkstd::vector >::iterator iter = objs.begin(); for( ; iter != objs.end(); iter++) { vtkObject* obj = iter->GetPointer(); this->Serialize("Item", obj); } this->Internal->Pop(); //return this->RootElement; } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(vtkKWEXMLElement* elem, const char* rootName, vtkObject *obj) { vtkstd::vector > objs; objs.push_back(obj); this->Serialize(elem, rootName, objs); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(vtkKWEXMLElement* elem, const char* rootName, vtkstd::vector >& objs) { if (!elem) { vtkErrorMacro("vtkKWEXMLElement must be instantiated before calling Serialize!"); return; } delete this->Internal; this->Internal = new vtkKWEXMLArchiveWriterInternals; this->SetRootElement(elem); this->CreateDOM(rootName, objs); this->SetRootElement(0); delete this->Internal; this->Internal = 0; } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(ostream& ostr, const char* rootName, vtkstd::vector >& objs) { delete this->Internal; this->Internal = new vtkKWEXMLArchiveWriterInternals; vtkKWEXMLElement *rootElement = vtkKWEXMLElement::New(); this->SetRootElement(rootElement); rootElement->Delete(); this->CreateDOM(rootName, objs); this->RootElement->PrintXML(ostr, vtkIndent()); this->SetRootElement(0); delete this->Internal; this->Internal = 0; } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(const char* name, int& val) { vtkSmartPointer elem = BaseSerialize(name, this->Internal); if (!elem.GetPointer()) { return; } elem->AddAttribute("value", val); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(const char* name, int*& val, unsigned int& length) { vtkSmartPointer elem = BaseSerialize(name, this->Internal); if (!elem.GetPointer()) { return; } if (!val) { elem->AddAttribute("length", static_cast(0)); return; } elem->AddAttribute("length", length); elem->AddAttribute("values", val, length); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(const char* name, unsigned long& val) { vtkSmartPointer elem = BaseSerialize(name, this->Internal); if (!elem.GetPointer()) { return; } elem->AddAttribute("value", val); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(const char* name, unsigned long*& val, unsigned int& length) { vtkSmartPointer elem=BaseSerialize(name, this->Internal); if (!elem.GetPointer()) { return; } if (!val) { elem->AddAttribute("length", static_cast(0)); return; } elem->AddAttribute("length", length); elem->AddAttribute("values", val, length); } //---------------------------------------------------------------------------- #if defined(VTK_USE_64BIT_IDS) void vtkKWEXMLArchiveWriter::Serialize(const char* name, vtkIdType& val) { vtkSmartPointer elem=BaseSerialize(name, this->Internal); if (!elem.GetPointer()) { return; } elem->AddAttribute("value", val); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(const char* name, vtkIdType*& val, unsigned int& length) { vtkSmartPointer elem=BaseSerialize(name, this->Internal); if (!elem.GetPointer()) { return; } if (!val) { elem->AddAttribute("length", static_cast(0)); return; } elem->AddAttribute("length", length); elem->AddAttribute("values", val, length); } #endif // if defined(VTK_USE_64BIT_IDS) //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(const char* name, double& val) { vtkSmartPointer elem = BaseSerialize(name, this->Internal); if (!elem.GetPointer()) { return; } elem->AddAttribute("value", val); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(const char* name, double*& val, unsigned int& length) { vtkSmartPointer elem = BaseSerialize(name, this->Internal); if (!elem.GetPointer()) { return; } if (!val) { elem->AddAttribute("length", static_cast(0)); return; } elem->AddAttribute("length", length); elem->AddAttribute("values", val, length); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(const char* name, char*& str) { vtkSmartPointer elem = BaseSerialize(name, this->Internal); if (!elem.GetPointer()) { return; } if (str) { elem->AddAttribute("value", str); } } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveWriter::Serialize(const char* name, vtkstd::string& str) { vtkSmartPointer elem = BaseSerialize(name, this->Internal); if (!elem.GetPointer()) { return; } if (str.c_str()) { elem->AddAttribute("value", str.c_str()); } } vtkedge-0.2.0~20110819/IO/vtkKWEXMLArchiveReader.cxx0000644000175000017500000005145011363410610021254 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEXMLArchiveReader.h" #include "vtkInformation.h" #include "vtkInformationDoubleKey.h" #include "vtkInformationIdTypeKey.h" #include "vtkInformationIntegerKey.h" #include "vtkInformationIntegerVectorKey.h" #include "vtkInformationStringKey.h" #include "vtkInformationDoubleVectorKey.h" #include "vtkInformationObjectBaseKey.h" #include "vtkInformationObjectBaseVectorKey.h" #include "vtkInformationKeyVectorKey.h" #include "vtkInformationStringVectorKey.h" #include "vtkInstantiator.h" #include "vtkKWEInformationKeyMap.h" #include "vtkKWESerializableObject.h" #include "vtkKWESerializationHelperMap.h" #include "vtkKWEXMLElement.h" #include "vtkKWEXMLParser.h" #include "vtkObjectFactory.h" #include "vtkSmartPointer.h" #include #include #include #include vtkCxxRevisionMacro(vtkKWEXMLArchiveReader, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEXMLArchiveReader); vtkCxxSetObjectMacro(vtkKWEXMLArchiveReader, RootElement, vtkKWEXMLElement); struct vtkKWEXMLArchiveReaderInternals { vtkstd::map IdToElement; vtkKWEXMLElement* FindElement(int id) { vtkstd::map::iterator iter = this->IdToElement.find(id); if (iter != this->IdToElement.end()) { return iter->second; } return 0; } vtkstd::map IdToObject; vtkObject* FindObject(int id) { vtkstd::map::iterator iter = this->IdToObject.find(id); if (iter != this->IdToObject.end()) { return iter->second; } return 0; } vtkKWEXMLElement* Top() { return this->Stack.front(); } void Push(vtkKWEXMLElement* elem) { this->Stack.push_front(elem); } void Pop() { this->Stack.pop_front(); } vtkstd::list Stack; // Stack to hold all the serializable objects; to support a weakPtr // to an object that is read before the object being referred to is created. // The ObjectStack holds an extra reference to all objects to prevent leaks // while supoorting this situtation (see comment in ReadObject). vtkstd::list > ObjectStack; }; //---------------------------------------------------------------------------- vtkKWEXMLArchiveReader::vtkKWEXMLArchiveReader() { this->Internal = new vtkKWEXMLArchiveReaderInternals; vtkKWESerializationHelperMap::InstantiateDefaultHelpers(); this->RootElement = 0; } //---------------------------------------------------------------------------- vtkKWEXMLArchiveReader::~vtkKWEXMLArchiveReader() { this->SetRootElement(0); delete this->Internal; } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(istream& str, const char*, vtkstd::vector >& objs) { delete this->Internal; this->Internal = new vtkKWEXMLArchiveReaderInternals; objs.clear(); if (this->ParseStream(str)) { this->Serialize(objs); } } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(vtkKWEXMLElement *rootElement, const char*, vtkstd::vector >& objs) { delete this->Internal; this->Internal = new vtkKWEXMLArchiveReaderInternals; objs.clear(); this->SetRootElement(rootElement); this->Serialize(objs); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(vtkstd::vector >& objs) { unsigned int nnested = this->RootElement->GetNumberOfNestedElements(); for (unsigned int i=0; iRootElement->GetNestedElement(i); int id; if (elem->GetScalarAttribute("id", &id)) { this->Internal->IdToElement[id] = elem; } } unsigned int version; if (this->RootElement->GetScalarAttribute("version", &version)) { this->SetArchiveVersion(version); } this->Internal->Push(this->RootElement); this->Internal->ObjectStack.clear(); // just to be sure this->Serialize("RootObjects", objs); this->Internal->Pop(); delete this->Internal; this->Internal = 0; } //---------------------------------------------------------------------------- vtkObject* vtkKWEXMLArchiveReader::ReadObject(int id, bool weakPtr) { // There will never be an object with id 0 if (id == 0) { return 0; } vtkObject* obj = this->Internal->FindObject(id); if (obj) { if (!weakPtr) { obj->Register(0); } return obj; } vtkKWEXMLElement* elem = this->Internal->FindElement(id); if (!elem) { vtkErrorMacro("Could not find of id " << id) return 0; } const char* className = elem->GetAttribute("type"); obj = vtkObject::SafeDownCast(vtkInstantiator::CreateInstance(className)); if (!obj) { vtkErrorMacro("Could not create object of type " << className) return 0; } this->Internal->ObjectStack.push_back( obj ); if (weakPtr) { // pointer to this object was weak, but the object hadn't been created // yet; The ObjectStack will hold the only reference until non-weak // references are made to the object (and registered at the top of this // fn). The extra reference held by the ObjectStack gets removed when // we are done reading (delete the this->Internal structure). obj->UnRegister(0); } this->Internal->IdToObject[id] = obj; this->Internal->Push(elem); vtkKWESerializableObject *serializableObject = vtkKWESerializableObject::SafeDownCast(obj); if (serializableObject) { serializableObject->Serialize(this); } else if (vtkInformation::SafeDownCast(obj)) { this->Serialize(elem, vtkInformation::SafeDownCast(obj)); } else { vtkKWESerializationHelperMap::Serialize(obj, this); } this->Internal->Pop(); return obj; } //---------------------------------------------------------------------------- int vtkKWEXMLArchiveReader::ParseStream(istream& str) { vtkSmartPointer parser = vtkSmartPointer::New(); parser->SetStream(&str); int result = parser->Parse(); this->SetRootElement(parser->GetRootElement()); return result; } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } namespace { vtkKWEXMLElement* BaseSerialize(vtkKWEXMLArchiveReaderInternals* internal, const char* name) { vtkKWEXMLElement* root = internal->Top(); if (!root) { vtkGenericWarningMacro("Serialize cannot be called outside serialization"); return 0; } return root->FindNestedElementByName(name); } } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(const char* name, vtkstd::vector >& objs, bool vtkNotUsed(weakPtr)/*=false*/) { objs.clear(); vtkKWEXMLElement* elem = BaseSerialize(this->Internal, name); if (!elem) { return; } unsigned int nnested = elem->GetNumberOfNestedElements(); for(unsigned int i=0; iGetNestedElement(i); int id; if (objElem->GetScalarAttribute("to_id", &id)) { vtkObject* obj = this->ReadObject(id, false); if (obj) { objs.push_back(obj); // ReadObject incremented the ReferenceCount (weakPtr = false), or // created the object (ReferenceCount = 1); we then stuff it in the // vector , which is where we were trying to get it but has the // side effect of further incrementing the ReferenceCount. To prevent // a leak we need to decerment the ReferenceCount. obj->UnRegister(0); } } } } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(const char* name, vtkstd::map > >& map) { map.clear(); vtkKWEXMLElement* elem = BaseSerialize(this->Internal, name); if (!elem) { return; } this->Internal->Push(elem); unsigned int nnested = elem->GetNumberOfNestedElements(); for(unsigned int i=0; iGetNestedElement(i); // Take out Key_ and convert to int int key = atoi(vecElem->GetName() + 4); this->Serialize(vecElem->GetName(), map[key]); } this->Internal->Pop(); } namespace { template void SerializeScalarKey(vtkInformation* info, KeyType* key, vtkKWEXMLElement* elem) { ValueType val; if (elem->GetScalarAttribute("value", &val)) { info->Set(key, val); } } //---------------------------------------------------------------------------- template void SerializeVectorKey(vtkInformation* info, KeyType* key, vtkKWEXMLElement* elem) { int length; if (!elem->GetScalarAttribute("length", &length)) { return; } if (length > 0) { ValueType* vals = new ValueType[length]; if (elem->GetVectorAttribute("values", length, vals)) { info->Set(key, vals, length); } delete[] vals; } } //---------------------------------------------------------------------------- void SerializeStringVectorKey(vtkInformation* info, vtkInformationStringVectorKey* key, vtkKWEXMLElement* elem) { int length = 0; if (!elem->GetScalarAttribute("length", &length) || length <= 0) { return; } const char* values = elem->GetAttribute("values"); if (!values) { return; } int* lengths = new int[length]; if (!elem->GetVectorAttribute("lengths", length, lengths)) { delete[] lengths; return; } vtkstd::string valuesStr(values); size_t currentPos = 0; for (int i = 0; i < length; ++i) { size_t strLength = static_cast(lengths[i]); vtkstd::string tmpStr = valuesStr.substr(currentPos, strLength); currentPos += strLength + 1; // skip over the semi-colon separator key->Set(info, tmpStr.c_str(), i); } delete[] lengths; } //---------------------------------------------------------------------------- void SerializeKeyVectorKey(vtkInformation* info, vtkInformationKeyVectorKey* key, vtkKWEXMLElement* elem) { int length; if (!elem->GetScalarAttribute("length", &length)) { return; } if (length <= 0) { return; } const char* values = elem->GetAttribute("values"); if (!values) { return; } vtksys_ios::istringstream valueStr(values); for (int i = 0; i < length; ++i) { vtkstd::string keyName; valueStr >> keyName; vtkInformationKey* tmpKey = vtkKWEInformationKeyMap::FindKey(keyName.c_str()); if (tmpKey) { info->Append(key, tmpKey); } else { vtkGenericWarningMacro("Lookup failed for vtkInformationKey: " << keyName.c_str()); } } } } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(const char* name, vtkInformation* info) { this->Serialize(BaseSerialize(this->Internal, name), info); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(vtkKWEXMLElement* elem, vtkInformation* info) { if (!elem) { return; } info->Clear(); unsigned int nnested = elem->GetNumberOfNestedElements(); for(unsigned int i=0; iGetNestedElement(i); vtkInformationKey* key = vtkKWEInformationKeyMap::FindKey(keyElem->GetName()); if (!key) { vtkErrorMacro("Lookup failed for vtkInformationKey: " << keyElem->GetName()); continue; } if (key->IsA("vtkInformationIntegerKey")) { SerializeScalarKey(info, static_cast(key), keyElem); } else if (key->IsA("vtkInformationDoubleKey")) { SerializeScalarKey(info, static_cast(key), keyElem); } else if (key->IsA("vtkInformationIdTypeKey")) { SerializeScalarKey(info, static_cast(key), keyElem); } else if (key->IsA("vtkInformationStringKey")) { const char* val = keyElem->GetAttribute("value"); if (val) { info->Set(static_cast(key), val); } } else if (key->IsA("vtkInformationDoubleVectorKey")) { SerializeVectorKey(info, static_cast(key), keyElem); } else if (key->IsA("vtkInformationIntegerVectorKey")) { SerializeVectorKey(info, static_cast(key), keyElem); } else if (key->IsA("vtkInformationStringVectorKey")) { SerializeStringVectorKey(info, static_cast(key), keyElem); } else if (key->IsA("vtkInformationKeyVectorKey")) { SerializeKeyVectorKey(info, static_cast(key), keyElem); } else if (key->IsA("vtkInformationObjectBaseKey")) { int id; if (keyElem->GetScalarAttribute("to_id", &id)) { vtkObject *obj = this->ReadObject(id, false); info->Set(static_cast(key), obj); if(obj) { // ReadObject incremented the ReferenceCount (weakPtr = false), or // created the object (ReferenceCount = 1); we then stuff it in the // information object, which is where we were trying to get it but // has the side effect of further incrementing the ReferenceCount. // To prevent a leak we need to decrment the ReferenceCount. obj->UnRegister(0); } } } else if (key->IsA("vtkInformationObjectBaseVectorKey")) { vtkInformationObjectBaseVectorKey* vecKey = static_cast(key); unsigned int length; if (keyElem->GetScalarAttribute("length", &length)) { unsigned long* ids = new unsigned long[length]; if (keyElem->GetVectorAttribute("ids", length, ids)) { vecKey->Resize(info, length); for (unsigned int k = 0; k < length; ++k) { vtkObject *obj = this->ReadObject(ids[k], false); vecKey->Set(info, obj, k); if(obj) { // ReadObject incremented the ReferenceCount (weakPtr = false), or // created the object (ReferenceCount = 1); we then stuff it in the // information object, which is where we were trying to get it but // has the side effect of further incrementing the ReferenceCount. // To prevent a leak we need to decrment the ReferenceCount. obj->UnRegister(0); } } } delete[] ids; } } } } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(const char* name, vtkObject*& obj, bool weakPtr/*=false*/) { vtkKWEXMLElement* elem = BaseSerialize(this->Internal, name); if (!elem) { return; } obj = 0; int id; if (elem->GetScalarAttribute("to_id", &id)) { obj = this->ReadObject(id, weakPtr); } } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(const char* name, int& val) { vtkKWEXMLElement* elem = BaseSerialize(this->Internal, name); if (!elem) { return; } elem->GetScalarAttribute("value", &val); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(const char* name, int*& val, unsigned int& length) { vtkKWEXMLElement* elem = BaseSerialize(this->Internal, name); if (!elem) { return; } if (val) { delete[] val; val = 0; } length = 0; elem->GetScalarAttribute("length", &length); if (length > 0) { val = new int[length]; elem->GetVectorAttribute("values", length, val); } } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(const char* name, unsigned long& val) { vtkKWEXMLElement* elem = BaseSerialize(this->Internal, name); if (!elem) { return; } elem->GetScalarAttribute("value", &val); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(const char* name, unsigned long*& val, unsigned int& length) { vtkKWEXMLElement* elem = BaseSerialize(this->Internal, name); if (!elem) { return; } if (val) { delete[] val; val = 0; } length = 0; elem->GetScalarAttribute("length", &length); if (length > 0) { val = new unsigned long[length]; elem->GetVectorAttribute("values", length, val); } } //---------------------------------------------------------------------------- #if defined(VTK_USE_64BIT_IDS) void vtkKWEXMLArchiveReader::Serialize(const char* name, vtkIdType& val) { vtkKWEXMLElement* elem = BaseSerialize(this->Internal, name); if (!elem) { return; } elem->GetScalarAttribute("value", &val); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(const char* name, vtkIdType*& val, unsigned int& length) { vtkKWEXMLElement* elem = BaseSerialize(this->Internal, name); if (!elem) { return; } if (val) { delete[] val; val = 0; } length = 0; elem->GetScalarAttribute("length", &length); if (length > 0) { val = new vtkIdType[length]; elem->GetVectorAttribute("values", length, val); } } #endif // if defined(VTK_USE_64BIT_IDS) //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(const char* name, double& val) { vtkKWEXMLElement* elem = BaseSerialize(this->Internal, name); if (!elem) { return; } elem->GetScalarAttribute("value", &val); } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(const char* name, double*& val, unsigned int& length) { vtkKWEXMLElement* elem = BaseSerialize(this->Internal, name); if (!elem) { return; } if (val) { delete[] val; val = 0; } length = 0; elem->GetScalarAttribute("length", &length); if (length > 0) { val = new double[length]; elem->GetVectorAttribute("values", length, val); } } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(const char* name, char*& str) { vtkKWEXMLElement* elem = BaseSerialize(this->Internal, name); if (!elem) { return; } str = 0; const char* val = elem->GetAttribute("value"); if (val) { str = vtksys::SystemTools::DuplicateString(val); } } //---------------------------------------------------------------------------- void vtkKWEXMLArchiveReader::Serialize(const char* name, vtkstd::string& str) { vtkKWEXMLElement* elem = BaseSerialize(this->Internal, name); if (!elem) { return; } const char* val = elem->GetAttribute("value"); if (val) { str = val; } else { str = vtkstd::string(); } } vtkedge-0.2.0~20110819/IO/vtkKWEXMLArchiveReader.h0000644000175000017500000001265311363410610020703 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEXMLArchiveReader - Reads an XML archive from input stream // .SECTION Description // This concrete subclass of vtkKWESerializer reads an XML archive from // an input stream and create a collection of sub-classes of vtkObject. // For example: // \code // vtkstd::vector > objs; // ifstream ifs(filename); // // vtkSmartPointer reader = // vtkSmartPointer::New(); // reader->Serialize(istr, "ObjectTree", objs); // .. Do something with objs // \endcode // See vtkKWEXMLArchiveWriter for details about the XML format. // .SECTION See Also // vtkKWESerializer vtkKWEXMLArchiveWriter #ifndef __vtkKWEXMLArchiveReader_h #define __vtkKWEXMLArchiveReader_h #include "vtkKWESerializer.h" #include "VTKEdgeConfigure.h" // include configuration header //BTX class vtkKWEXMLElement; struct vtkKWEXMLArchiveReaderInternals; //ETX class VTKEdge_IO_EXPORT vtkKWEXMLArchiveReader : public vtkKWESerializer { public: static vtkKWEXMLArchiveReader *New(); vtkTypeRevisionMacro(vtkKWEXMLArchiveReader,vtkKWESerializer); void PrintSelf(ostream& os, vtkIndent indent); // Description: // This method returns true if the serializer is an output // serializer (writer). Returns false. virtual bool IsWriting() {return false;} // Description: // Main entry point called to read an XML archive. // It populates the obj vector with the root objects in the // archive (under the RootObjects element). virtual void Serialize(istream& istr, const char* rootName, vtkstd::vector >& objs); // Description: // Additional entry point called to read an XML archive from a // vtkKWEXMLElement (as opposed to "from a stream"). It // populates the obj vector with the root objects in the // archive (under the RootObjects element). virtual void Serialize(vtkKWEXMLElement *rootElement, const char* rootName, vtkstd::vector >& objs); // Description: // Reads a single integer. virtual void Serialize(const char* name, int& val); // Description: // Reads an array. virtual void Serialize(const char* name, int*& val, unsigned int& length); // Description: // Serializes a single unsigned long. virtual void Serialize(const char* name, unsigned long& val) ; // Description: // Serializes an array. virtual void Serialize(const char* name, unsigned long*& val, unsigned int& length); // Description: // Reads a single vtkIdType. #if defined(VTK_USE_64BIT_IDS) virtual void Serialize(const char* name, vtkIdType& val); #endif // Description: // Reads an array. #if defined(VTK_USE_64BIT_IDS) virtual void Serialize(const char* name, vtkIdType*& val, unsigned int& length); #endif // Description: // Reads a single double. virtual void Serialize(const char* name, double& val); // Description: // Reads an array. virtual void Serialize(const char* name, double*& val, unsigned int& length); // Description: // Serializes a string. virtual void Serialize(const char* name, char*& str); // Description: // Serializes a string. virtual void Serialize(const char* name, vtkstd::string& str); // Description: // Reads a vtkObject. weakPtr should be set to true if this reference to the // object should NOT be reference counted. virtual void Serialize(const char* name, vtkObject*& obj, bool weakPtr = false); // Description: // Reads a vtkInformationObject. Note that only keys registered // with the vtkKWEInformationKeyMap are restored. virtual void Serialize(const char* name, vtkInformation* info); // Description: // Reads a vector of vtkObjects. virtual void Serialize(const char* name, vtkstd::vector >& objs, bool weakPtr = false); // Description: // Reads a map from int to vector of vtkObject. virtual void Serialize(const char* name, vtkstd::map > >& objs); protected: vtkKWEXMLArchiveReader(); ~vtkKWEXMLArchiveReader(); private: vtkKWEXMLArchiveReader(const vtkKWEXMLArchiveReader&); // Not implemented. void operator=(const vtkKWEXMLArchiveReader&); // Not implemented. void Serialize(vtkstd::vector >& objs); int ParseStream(istream& str); vtkKWEXMLElement* RootElement; // Description: // weakPtr is true if the object is NOT to be reference counted. vtkObject* ReadObject(int id, bool weakPtr); // Description: // Reads a vtkInformationObject. Note that only keys registered // with the vtkKWEInformationKeyMap are restored. virtual void Serialize(vtkKWEXMLElement* elem, vtkInformation* info); void SetRootElement(vtkKWEXMLElement* re); vtkKWEXMLArchiveReaderInternals* Internal; }; #endif vtkedge-0.2.0~20110819/IO/Testing/0000755000175000017500000000000011630434665015774 5ustar mathieumathieuvtkedge-0.2.0~20110819/IO/Testing/Cxx/0000755000175000017500000000000011630434665016536 5ustar mathieumathieuvtkedge-0.2.0~20110819/IO/Testing/Cxx/TestSerializeInformation.cxx0000644000175000017500000001624511363410610024252 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEXMLArchiveWriter.h" #include "vtkKWEXMLArchiveReader.h" #include "vtkKWEInformationKeyMap.h" #include "vtkCamera.h" #include "vtkInformation.h" #include "vtkInformationIntegerKey.h" #include "vtkInformationIntegerVectorKey.h" #include "vtkInformationDoubleKey.h" #include "vtkInformationDoubleVectorKey.h" #include "vtkInformationStringKey.h" #include "vtkInformationStringVectorKey.h" #include "vtkInformationObjectBaseKey.h" #include "vtkInformationObjectBaseVectorKey.h" #include "vtkSmartPointer.h" #include "vtkCommonInstantiator.h" #include #define VTK_CREATE(type, var) \ vtkSmartPointer var = vtkSmartPointer::New() #define fail(msg) \ std::cerr << msg << std::endl; \ return EXIT_FAILURE; namespace { class TestClass { public: // Method to register the keys static void RegisterKeys(); // The keys static vtkInformationIntegerKey* TestInt(); static vtkInformationIntegerVectorKey* TestIntVector(); static vtkInformationDoubleKey* TestDouble(); static vtkInformationDoubleVectorKey* TestDoubleVector(); static vtkInformationStringKey* TestString(); static vtkInformationStringVectorKey* TestStringVector(); static vtkInformationObjectBaseKey* TestObject(); static vtkInformationObjectBaseVectorKey* TestObjectVector(); }; vtkInformationKeyMacro(TestClass, TestInt, Integer); vtkInformationKeyMacro(TestClass, TestIntVector, IntegerVector); vtkInformationKeyMacro(TestClass, TestDouble, Double); vtkInformationKeyMacro(TestClass, TestDoubleVector, DoubleVector); vtkInformationKeyMacro(TestClass, TestString, String); vtkInformationKeyMacro(TestClass, TestStringVector, StringVector); vtkInformationKeyMacro(TestClass, TestObject, ObjectBase); vtkInformationKeyMacro(TestClass, TestObjectVector, ObjectBaseVector); void TestClass::RegisterKeys() { vtkKWEInformationKeyMap::RegisterKey(TestInt()); vtkKWEInformationKeyMap::RegisterKey(TestIntVector()); vtkKWEInformationKeyMap::RegisterKey(TestDouble()); vtkKWEInformationKeyMap::RegisterKey(TestDoubleVector()); vtkKWEInformationKeyMap::RegisterKey(TestString()); vtkKWEInformationKeyMap::RegisterKey(TestStringVector()); vtkKWEInformationKeyMap::RegisterKey(TestObject()); vtkKWEInformationKeyMap::RegisterKey(TestObjectVector()); } } int TestSerializeInformation(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) { TestClass::RegisterKeys(); // Create info object and serializers VTK_CREATE(vtkInformation, info); VTK_CREATE(vtkKWEXMLArchiveReader, reader); VTK_CREATE(vtkKWEXMLArchiveWriter, writer); vtksys_ios::stringstream xmlStream; // Create cameras VTK_CREATE(vtkCamera, cam1); VTK_CREATE(vtkCamera, cam2); cam1->SetPosition(1.0, 2.0, 3.0); cam2->SetPosition(4.0, 5.0, 6.0); // Set values in the information object info->Set(TestClass::TestInt(), 1); info->Set(TestClass::TestIntVector(), 1, 2, 3); info->Set(TestClass::TestDouble(), 1.0); info->Set(TestClass::TestDoubleVector(), 1.0, 2.0, 3.0); info->Set(TestClass::TestString(), "foo"); info->Set(TestClass::TestStringVector(), "foo", 0); info->Set(TestClass::TestStringVector(), "ba\"r", 1); info->Set(TestClass::TestObject(), cam1); TestClass::TestObjectVector()->Set(info, cam1, 0); TestClass::TestObjectVector()->Set(info, NULL, 1); TestClass::TestObjectVector()->Set(info, cam2, 2); // The writer expects a vector of objects vtkstd::vector > objs; objs.push_back(info); // Serialize the object vector writer->Serialize(xmlStream, "info", objs); // Print out the XML std::cerr << xmlStream.str().c_str() << std::endl; // Read the XML to deserialize the objects objs.clear(); reader->Serialize(xmlStream, "info", objs); if (objs.size() != 1) { fail("Serialization reader didn't produce correct number of objects."); } // Get the new vtkInformation object created for the reader vtkSmartPointer newInfo = vtkInformation::SafeDownCast(objs[0]); objs.clear(); if (!newInfo) { fail("Did not get new information object."); } // Get the values stored in the new information object int testInt = info->Get(TestClass::TestInt()); int* testIntVector = info->Get(TestClass::TestIntVector()); double testDouble = info->Get(TestClass::TestDouble()); double* testDoubleVector = info->Get(TestClass::TestDoubleVector()); const char* testString = info->Get(TestClass::TestString()); const char* testStringVector[2]; testStringVector[0] = info->Get(TestClass::TestStringVector(), 0); testStringVector[1] = info->Get(TestClass::TestStringVector(), 1); vtkCamera* newCam1 = vtkCamera::SafeDownCast(info->Get(TestClass::TestObject())); vtkCamera* newCam2 = vtkCamera::SafeDownCast(TestClass::TestObjectVector()->Get(info, 0)); vtkObjectBase* nullPtr = TestClass::TestObjectVector()->Get(info, 1); vtkCamera* newCam3 = vtkCamera::SafeDownCast(TestClass::TestObjectVector()->Get(info, 2)); // Test all the values if (testInt != 1) { fail("Integer has incorrect value."); } if ( testIntVector[0] != 1 || testIntVector[1] != 2 || testIntVector[2] != 3) { fail("Integer vector has incorrect value."); } if (testDouble != 1.0) { fail("Double has incorrect value."); } if ( testDoubleVector[0] != 1.0 || testDoubleVector[1] != 2.0 || testDoubleVector[2] != 3.0) { fail("Double vector has incorrect value."); } if (strcmp(testString, "foo")) { fail("String has incorrect value."); } if ( strcmp(testStringVector[0], "foo") || strcmp(testStringVector[1], "ba\"r")) { fail("String vector has incorrect value."); } if (!newCam1) { fail ("Failed to get camera object."); } if (nullPtr) { fail ("Second object should have been null."); } // These pointers should be the same since they were the same when we inserted // them into the original infomation object if (newCam1 != newCam2) { fail ("Camera objects were not the same pointer."); } double* newCam2Pos = newCam2->GetPosition(); double* newCam3Pos = newCam3->GetPosition(); if ( newCam2Pos[0] != 1.0 || newCam2Pos[1] != 2.0 || newCam2Pos[2] != 3.0) { fail("First camera has incorrect position."); } if ( newCam3Pos[0] != 4.0 || newCam3Pos[1] != 5.0 || newCam3Pos[2] != 6.0) { fail("Second camera has incorrect position."); } return EXIT_SUCCESS; } vtkedge-0.2.0~20110819/IO/Testing/Cxx/CMakeLists.txt0000644000175000017500000000427411363410610021270 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Name this kit - this will be used to form test executable names later # Then we'll add in tests with various data or kit dependencies to the # test executables # ----------------------------------------------------------------------------- set(KIT IO) set(TESTBASE ${PROJECT_NAME}${KIT}) #include_directories("${VTKEdge_SOURCE_DIR}/IO") # ----------------------------------------------------------------------------- # First, list all the tests that either use no data, or only data from the # VTKEdge data directory (which always exists since it is part of the # VTKEdge repository). These will go into one test executable. # ----------------------------------------------------------------------------- set(MyTests TestSerializeInformation ) create_test_sourcelist(Tests ${TESTBASE}CxxTests.cxx ${MyTests} EXTRA_INCLUDE vtkTestDriver.h ) add_executable(${TESTBASE}CxxTests ${Tests}) #install_targets(${VTKEdge_INSTALL_BIN_DIR} ${TESTBASE}CxxTests) target_link_libraries(${TESTBASE}CxxTests vtkKWEIO) set(TestsToRun ${Tests}) remove(TestsToRun ${TESTBASE}CxxTests.cxx) # Add all the executables foreach(test ${TestsToRun}) get_filename_component(TName ${test} NAME_WE) add_test(${TName} ${CXX_TEST_PATH}/${TESTBASE}CxxTests ${TName} -D ${PROJECT_SOURCE_DIR}/Data -T ${PROJECT_BINARY_DIR}/Testing/Temporary -V ${PROJECT_SOURCE_DIR}/Data/Baseline/${KIT}/${TName}.png ) endforeach(test) vtkedge-0.2.0~20110819/IO/Testing/CMakeLists.txt0000644000175000017500000000166011363410610020522 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Add the Cxx testing directory # ----------------------------------------------------------------------------- add_subdirectory(Cxx) vtkedge-0.2.0~20110819/IO/vtkKWESerializationHelperMap.h0000644000175000017500000000751411363410610022231 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWESerializationHelperMap - Map from class name to helper object. // .SECTION Description // This class is used to map from class name to a helper class that has been // registered to serialize the class. // // Note, helper classes must be manually instantiated, at which time // the class types supported by the helper should be registered with the // vtkKWESerializationHelperMap (by calling RegisterWithHelperMap on the // helper). The "known" helper classes (those for the VTK/VTKEdge kits) // should be added to InstantiateDefaultHelpers(), which is called by both // the vtkKWEXMLArchiveReader and vtkKWEXMLArchiveWriter during their // construction. This class then manages destruction of the helper since the // map holds a vtkSmartPointer to the helper for each supported class type. // // .SECTION See Also // vtkKWESerializationHelper #ifndef __vtkKWESerializationHelperMap_h #define __vtkKWESerializationHelperMap_h #include "vtkObject.h" #include "VTKEdgeConfigure.h" // include configuration header class vtkKWESerializationHelper; class vtkKWESerializer; class vtkKWEXMLElement; class VTKEdge_IO_EXPORT vtkKWESerializationHelperMap : public vtkObject { public: static vtkKWESerializationHelperMap *New(); vtkTypeRevisionMacro(vtkKWESerializationHelperMap,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Instantiate all "known" (supporting core VTK and VTKEdge) helpers // and then register them with the helper map. static void InstantiateDefaultHelpers(); // Description: // Register (add) a class type / helper with the map. static void RegisterHelperForClass(const char *classType, vtkKWESerializationHelper* helper); // Description: // UnRegister (remove) a class type / helper in the map, if the registered // helper matches. static void UnRegisterHelperForClass(const char *classType, vtkKWESerializationHelper* helper); // Description: // Serialize the input object using a registered helper. If successful (map // entry exists), returns 1 (0 if not). static int Serialize(vtkObject *obj, vtkKWESerializer *serializer); // Description: // Get the value for the "type" attribute (generally the ClassName but may be // name of Superclass) of the specfied object type from a registerd helper // for the object Clas static const char *GetSerializationType(vtkObject *object); // Description: // Returns true if the object class type is registered with the map, and thus // can be serialized. static bool IsSerializable(vtkObject *obj); // Description: // Return the serialization helper registered for the indicated class (if one // has been registerd); otherwise return NULL static vtkKWESerializationHelper* GetHelper(const char *classType); // Description: // Removes all helpers from the map. static void RemoveAllHelpers(); protected: vtkKWESerializationHelperMap(); ~vtkKWESerializationHelperMap(); private: vtkKWESerializationHelperMap(const vtkKWESerializationHelperMap&); // Not implemented. void operator=(const vtkKWESerializationHelperMap&); // Not implemented. static bool DefaultHelpersInstantiated; }; #endif vtkedge-0.2.0~20110819/IO/vtkKWESerializableObject.cxx0000644000175000017500000000200311363410610021712 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWESerializableObject.h" #include vtkCxxRevisionMacro(vtkKWESerializableObject, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWESerializableObject); vtkKWESerializableObject::vtkKWESerializableObject() { } vtkKWESerializableObject::~vtkKWESerializableObject() { } vtkedge-0.2.0~20110819/IO/vtkKWERenderingSerializationHelper.cxx0000644000175000017500000001417511363410610024005 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWERenderingSerializationHelper.h" #include "vtkCamera.h" #include "vtkKWESerializationHelperMap.h" #include "vtkKWESerializer.h" #include "vtkKWEXMLElement.h" #include vtkCxxRevisionMacro(vtkKWERenderingSerializationHelper, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWERenderingSerializationHelper); //----------------------------------------------------------------------------- vtkKWERenderingSerializationHelper::vtkKWERenderingSerializationHelper() { } //----------------------------------------------------------------------------- int vtkKWERenderingSerializationHelper::Serialize(vtkObject *object, vtkKWESerializer *serializer) { if (vtkCamera::SafeDownCast(object)) { this->SerializeCamera(vtkCamera::SafeDownCast(object), serializer); return 1; } return 0; } //----------------------------------------------------------------------------- void vtkKWERenderingSerializationHelper::RegisterWithHelperMap() { vtkKWESerializationHelperMap::RegisterHelperForClass("vtkCamera", this); vtkKWESerializationHelperMap::RegisterHelperForClass("vtkOpenGLCamera", this); vtkKWESerializationHelperMap::RegisterHelperForClass("vtkMesaCamera", this); } //----------------------------------------------------------------------------- void vtkKWERenderingSerializationHelper::UnRegisterWithHelperMap() { vtkKWESerializationHelperMap::UnRegisterHelperForClass("vtkCamera", this); vtkKWESerializationHelperMap::UnRegisterHelperForClass("vtkOpenGLCamera", this); vtkKWESerializationHelperMap::UnRegisterHelperForClass("vtkMesaCamera", this); } //----------------------------------------------------------------------------- void vtkKWERenderingSerializationHelper::SerializeCamera(vtkCamera *camera, vtkKWESerializer *serializer) { if (serializer->IsWriting()) { // vectors of length 3 unsigned int length = 3; double *position = camera->GetPosition(); serializer->Serialize("Position", position, length); double *focalPt = camera->GetFocalPoint(); serializer->Serialize("FocalPoint", focalPt, length); double *viewUp = camera->GetViewUp(); serializer->Serialize("ViewUp", viewUp, length); // vectors of length 2 length = 2; double *clippingRange = camera->GetClippingRange(); serializer->Serialize("ClippingRange", clippingRange, length); double *windowCenter = camera->GetWindowCenter(); serializer->Serialize("WindowCenter", windowCenter, length); // scalars double viewAngle = camera->GetViewAngle(); serializer->Serialize("ViewAngle", viewAngle); int parallelProjection = camera->GetParallelProjection(); serializer->Serialize("ParallelProjection", parallelProjection); double parallelScale = camera->GetParallelScale(); serializer->Serialize("ParallelScale", parallelScale); int useHorizontalViewAngle = camera->GetUseHorizontalViewAngle(); serializer->Serialize("UseHorizontalViewAngle", useHorizontalViewAngle); } else { unsigned int length = 0; // vectors of length 3 double *position = 0, *focalPt = 0, *viewUp = 0; serializer->Serialize("Position", position, length); if (length > 0) { camera->SetPosition(position); delete [] position; } serializer->Serialize("FocalPoint", focalPt, length); if (length > 0) { camera->SetFocalPoint(focalPt); delete [] focalPt; } serializer->Serialize("ViewUp", viewUp, length); if (length > 0) { camera->SetViewUp(viewUp); delete [] viewUp; } // vectors of length 2 double *clippingRange = 0, *windowCenter = 0; serializer->Serialize("ClippingRange", clippingRange, length); if (length > 0) { camera->SetClippingRange(clippingRange); delete [] clippingRange; } serializer->Serialize("WindowCenter", windowCenter, length); if (length > 0) { camera->SetWindowCenter(windowCenter[0], windowCenter[1]); delete [] windowCenter; } // scalars double viewAngle = camera->GetViewAngle(); // default value serializer->Serialize("ViewAngle", viewAngle); camera->SetViewAngle(viewAngle); int parallelProjection = camera->GetParallelProjection(); serializer->Serialize("ParallelProjection", parallelProjection); camera->SetParallelProjection(parallelProjection); double parallelScale = camera->GetParallelScale(); serializer->Serialize("ParallelScale", parallelScale); camera->SetParallelScale(parallelScale); int useHorizontalViewAngle = camera->GetUseHorizontalViewAngle(); serializer->Serialize("UseHorizontalViewAngle", useHorizontalViewAngle); camera->SetUseHorizontalViewAngle(useHorizontalViewAngle); } } //----------------------------------------------------------------------------- const char *vtkKWERenderingSerializationHelper::GetSerializationType(vtkObject *object) { if (vtkCamera::SafeDownCast(object)) { return "vtkCamera"; } return 0; } //----------------------------------------------------------------------------- void vtkKWERenderingSerializationHelper::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Supported ClassTypes:\n"; os << indent.GetNextIndent() << "vtkCamera\n"; os << indent.GetNextIndent() << "vtkOpenGLCamera\n"; os << indent.GetNextIndent() << "vtkMesaCamera\n"; } vtkedge-0.2.0~20110819/IO/vtkKWESerializer.cxx0000644000175000017500000000220311363410610020270 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWESerializer.h" vtkCxxRevisionMacro(vtkKWESerializer, "$Revision: 1774 $"); //---------------------------------------------------------------------------- vtkKWESerializer::vtkKWESerializer() { this->ArchiveVersion = 0; } //---------------------------------------------------------------------------- void vtkKWESerializer::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/IO/vtkKWEXMLParser.cxx0000644000175000017500000001125011363410610017776 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEXMLParser.h" #include "vtkObjectFactory.h" #include "vtkKWEXMLElement.h" #include "vtksys/ios/sstream" vtkCxxRevisionMacro(vtkKWEXMLParser, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEXMLParser); //---------------------------------------------------------------------------- vtkKWEXMLParser::vtkKWEXMLParser() { this->FileName = 0; this->InputString = 0; this->NumberOfOpenElements = 0; this->OpenElementsSize = 10; this->OpenElements = new vtkKWEXMLElement*[this->OpenElementsSize]; this->ElementIdIndex = 0; this->RootElement = 0; } //---------------------------------------------------------------------------- vtkKWEXMLParser::~vtkKWEXMLParser() { unsigned int i; for(i=0;i < this->NumberOfOpenElements;++i) { this->OpenElements[i]->Delete(); } delete [] this->OpenElements; if(this->RootElement) { this->RootElement->Delete(); } this->SetFileName(0); } //---------------------------------------------------------------------------- void vtkKWEXMLParser::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "FileName: " << (this->FileName? this->FileName : "(none)") << "\n"; } //---------------------------------------------------------------------------- void vtkKWEXMLParser::StartElement(const char* name, const char** atts) { vtkKWEXMLElement* element = vtkKWEXMLElement::New(); element->SetName(name); element->ReadXMLAttributes(atts); const char* id = element->GetAttribute("id"); if(id) { element->SetId(id); } else { vtksys_ios::ostringstream idstr; idstr << this->ElementIdIndex++ << ends; element->SetId(idstr.str().c_str()); } this->PushOpenElement(element); } //---------------------------------------------------------------------------- void vtkKWEXMLParser::EndElement(const char* vtkNotUsed(name)) { vtkKWEXMLElement* finished = this->PopOpenElement(); unsigned int numOpen = this->NumberOfOpenElements; if(numOpen > 0) { this->OpenElements[numOpen-1]->AddNestedElement(finished); finished->Delete(); } else { this->RootElement = finished; } } //---------------------------------------------------------------------------- void vtkKWEXMLParser::CharacterDataHandler(const char* data, int length) { unsigned int numOpen = this->NumberOfOpenElements; if(numOpen > 0) { this->OpenElements[numOpen-1]->AddCharacterData(data, length); } } //---------------------------------------------------------------------------- void vtkKWEXMLParser::PushOpenElement(vtkKWEXMLElement* element) { if(this->NumberOfOpenElements == this->OpenElementsSize) { unsigned int newSize = this->OpenElementsSize*2; vtkKWEXMLElement** newOpenElements = new vtkKWEXMLElement*[newSize]; unsigned int i; for(i=0; i < this->NumberOfOpenElements;++i) { newOpenElements[i] = this->OpenElements[i]; } delete [] this->OpenElements; this->OpenElements = newOpenElements; this->OpenElementsSize = newSize; } unsigned int pos = this->NumberOfOpenElements++; this->OpenElements[pos] = element; } //---------------------------------------------------------------------------- vtkKWEXMLElement* vtkKWEXMLParser::PopOpenElement() { if(this->NumberOfOpenElements > 0) { --this->NumberOfOpenElements; return this->OpenElements[this->NumberOfOpenElements]; } return 0; } //---------------------------------------------------------------------------- void vtkKWEXMLParser::PrintXML(ostream& os) { this->RootElement->PrintXML(os, vtkIndent()); } //---------------------------------------------------------------------------- int vtkKWEXMLParser::ParseXML() { if (this->RootElement) { this->RootElement->Delete(); this->RootElement = 0; } return this->Superclass::ParseXML(); } //---------------------------------------------------------------------------- vtkKWEXMLElement* vtkKWEXMLParser::GetRootElement() { return this->RootElement; } vtkedge-0.2.0~20110819/IO/vtkKWECommonSerializationHelper.h0000644000175000017500000000621011363410610022734 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWECommonSerializationHelper - Concrete serialization helper for // Common package vtkObjects. // .SECTION Description // Concrete class for serialization of vtkObjects in the Common package using // vtkKWEXMLArchiveWriter and vtkKWEXMLArchiveReader. Only serialization of // vtkTransform, vtkIdTypeArray, vtkIntArray, and vtkDoubleArray is currently // implemented. // .SECTION See Also // vtkKWESerializationHelperMap vtkKWESerializationHelper #ifndef __vtkKWECommonSerializationHelper_h #define __vtkKWECommonSerializationHelper_h #include "vtkKWESerializationHelper.h" #include "VTKEdgeConfigure.h" // include configuration header class vtkDataArray; class vtkKWESerializer; class vtkTransform; class VTKEdge_IO_EXPORT vtkKWECommonSerializationHelper : public vtkKWESerializationHelper { public: static vtkKWECommonSerializationHelper *New(); vtkTypeRevisionMacro(vtkKWECommonSerializationHelper, vtkKWESerializationHelper); void PrintSelf(ostream& os, vtkIndent indent); // Description: // This member registers ALL the classes supported by this helper with the // vtkKWESerializationHelperMap, which manages all the helpers. Should be // called after construction unless you only want to enable support for // a subset (in which case it must be done "manually" by calling // vtkKWESerializationHelperMap::RegisterHelperForClass() virtual void RegisterWithHelperMap(); // Description: // Unregister this helper (remove each class type/helper pair) with the // vtkKWESerializationHelperMap virtual void UnRegisterWithHelperMap(); // Description: // Get the value for the "type" attribute of the specfied object type virtual const char *GetSerializationType(vtkObject *object); // Description: // Serialize the input object. Returns 1 if successful. virtual int Serialize(vtkObject *object, vtkKWESerializer *serializer); //BTX protected: vtkKWECommonSerializationHelper(); ~vtkKWECommonSerializationHelper() {} // Description: // Serialize a vtkTransform void SerializeTransform(vtkTransform *transform, vtkKWESerializer *serializer); // Description: // Serialize vtkIdTypeArray, vtkIntArray, or vtkDoubleArray void SerializeDataArray(vtkDataArray *dataArray, vtkKWESerializer *serializer); private: vtkKWECommonSerializationHelper(const vtkKWECommonSerializationHelper&); // Not implemented. void operator=(const vtkKWECommonSerializationHelper&); // Not implemented. //ETX }; #endif vtkedge-0.2.0~20110819/IO/vtkKWEXMLElement.h0000644000175000017500000001771611363410610017575 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEXMLElement represents an XML element and those nested inside. // .SECTION Description // This is used by vtkKWEXMLParser to represent an XML document starting // at the root element. #ifndef __vtkKWEXMLElement_h #define __vtkKWEXMLElement_h #include "vtkObject.h" #include "VTKEdgeConfigure.h" // include configuration header #include "vtkStdString.h" // needed for vtkStdString. class vtkCollection; class vtkKWEXMLParser; //BTX struct vtkKWEXMLElementInternals; //ETX class VTKEdge_IO_EXPORT vtkKWEXMLElement : public vtkObject { public: vtkTypeRevisionMacro(vtkKWEXMLElement,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); static vtkKWEXMLElement* New(); // Description: // Set/Get the name of the element. This is its XML tag. // (). vtkSetStringMacro(Name); vtkGetStringMacro(Name); // Description: // Get the id of the element. This is assigned by the XML parser // and can be used as an identifier to an element. vtkGetStringMacro(Id); // Description: // Get the attribute with the given name. If it doesn't exist, // returns 0. const char* GetAttribute(const char* name); // Description: // Get the character data for the element. const char* GetCharacterData(); // Description: // Get the attribute with the given name converted to a scalar // value. Returns whether value was extracted. unsigned int GetScalarAttribute(const char* name, int* value); unsigned int GetScalarAttribute(const char* name, unsigned int* value); unsigned int GetScalarAttribute(const char* name, unsigned long* value); unsigned int GetScalarAttribute(const char* name, float* value); unsigned int GetScalarAttribute(const char* name, double* value); #if defined(VTK_USE_64BIT_IDS) unsigned int GetScalarAttribute(const char* name, vtkIdType* value); #endif // Description: // Get the attribute with the given name converted to a scalar // value. Returns length of vector read. unsigned int GetVectorAttribute(const char* name, unsigned int length, int* value); unsigned int GetVectorAttribute(const char* name, unsigned int length, unsigned int* value); unsigned int GetVectorAttribute(const char* name, unsigned int length, unsigned long* value); unsigned int GetVectorAttribute(const char* name, unsigned int length, float* value); unsigned int GetVectorAttribute(const char* name, unsigned int length, double* value); #if defined(VTK_USE_64BIT_IDS) unsigned int GetVectorAttribute(const char* name, unsigned int length, vtkIdType* value); #endif // Description: // Get the character data converted to a scalar // value. Returns length of vector read. unsigned int GetCharacterDataAsVector(unsigned int length, int* value); unsigned int GetCharacterDataAsVector(unsigned int length, unsigned long* value); unsigned int GetCharacterDataAsVector(unsigned int length, float* value); unsigned int GetCharacterDataAsVector(unsigned int length, double* value); #if defined(VTK_USE_64BIT_IDS) unsigned int GetCharacterDataAsVector(unsigned int length, vtkIdType* value); #endif // Description: // Get the parent of this element. vtkKWEXMLElement* GetParent(); // Description: // Get the number of elements nested in this one. unsigned int GetNumberOfNestedElements(); // Description: // Get the element nested in this one at the given index. vtkKWEXMLElement* GetNestedElement(unsigned int index); // Description: // Find a nested element with the given id. // Note that this searches only the immediate children of this // vtkKWEXMLElement. vtkKWEXMLElement* FindNestedElement(const char* id); // Description: // Locate a nested element with the given tag name. vtkKWEXMLElement* FindNestedElementByName(const char* name); // Description: // Removes all nested elements. void RemoveAllNestedElements(); // Description: // Remove a particular element. void RemoveNestedElement(vtkKWEXMLElement*); // Description: // Lookup the element with the given id, starting at this scope. vtkKWEXMLElement* LookupElement(const char* id); // Description: // Given it's name and value, add an attribute. void AddAttribute(const char* attrName, const char* attrValue); void AddAttribute(const char* attrName, unsigned int attrValue); void AddAttribute(const char* attrName, double attrValue); void AddAttribute(const char* attrName, int attrValue); void AddAttribute(const char* attrName, unsigned long attrValue); void AddAttribute(const char* attrName, double* vals, unsigned int length); void AddAttribute(const char* attrName, int* vals, unsigned int length); void AddAttribute(const char* attrName, unsigned long* vals, unsigned int length); #if defined(VTK_USE_64BIT_IDS) void AddAttribute(const char* attrName, vtkIdType attrValue); void AddAttribute(const char* attrName, vtkIdType* vals, unsigned int length); #endif // Description: // Given it's name and value, set an attribute. // If an attribute with the given name already exists, // it replaces the old attribute. // chars that need to be XML escaped will be done so internally // for example " will be converted to " void SetAttribute(const char* attrName, const char* attrValue); // Description: // Add a sub-element. The parent element keeps a reference to // sub-element. If setParent is true, the nested element's parent // is set as this. void AddNestedElement(vtkKWEXMLElement* element, int setPrent); void AddNestedElement(vtkKWEXMLElement* element); // Description: // Serialize (as XML) in the given stream. void PrintXML(ostream& os, vtkIndent indent); void PrintXML(); // Description: // Merges another element with this one, both having the same name. // If any attribute, character data or nested element exists in both, // the passed in one will override this one's. If they don't exist, // they'll be added. If nested elements have the same names, the // optional attributeName maybe passed in as another criteria to determine // what to merge in case of same names. void Merge(vtkKWEXMLElement* element, const char* attributeName); // Description: // Similar to DOM sepecific getElementsByTagName(). // Returns a list of vtkKWEXMLElements with the given name in the order // in which they will be encountered in a preorder traversal // of the sub-tree under this node. The elements are populated // in the vtkCollection passed as an argument. void GetElementsByName(const char* name, vtkCollection* elements); // Description: // Encode a string. static vtkStdString Encode(const char* plaintext); protected: vtkKWEXMLElement(); ~vtkKWEXMLElement(); vtkKWEXMLElementInternals* Internal; char* Name; char* Id; // The parent of this element. vtkKWEXMLElement* Parent; // Method used by vtkKWEXMLParser to setup the element. vtkSetStringMacro(Id); void ReadXMLAttributes(const char** atts); void AddCharacterData(const char* data, int length); // Internal utility methods. vtkKWEXMLElement* LookupElementInScope(const char* id); vtkKWEXMLElement* LookupElementUpScope(const char* id); void SetParent(vtkKWEXMLElement* parent); //BTX friend class vtkKWEXMLParser; //ETX private: vtkKWEXMLElement(const vtkKWEXMLElement&); // Not implemented. void operator=(const vtkKWEXMLElement&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/IO/vtkKWESerializationHelper.h0000644000175000017500000000544411363410610021573 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWESerializationHelper - Superclass for serialization helpers // .SECTION Description // Abstract class for serialization of vtkObjects with the // vtkKWEXMLArchiveWriter and vtkKWEXMLArchiveReader. Subclasses must // implement RegisterWithHelperMap (which registers each class type supported // by the helper with the vtkKWESerializationHelperMap), GetSerializationType // (returns the "type" to set as the attribute for the element), and Serialize // (which does the actual serialization) and UnRegisterWithHelperMap(). // .SECTION See Also // vtkKWESerializationHelperMap #ifndef __vtkKWESerializationHelper_h #define __vtkKWESerializationHelper_h #include "vtkObject.h" #include "VTKEdgeConfigure.h" // include configuration header class vtkKWESerializer; class VTKEdge_IO_EXPORT vtkKWESerializationHelper : public vtkObject { public: vtkTypeRevisionMacro(vtkKWESerializationHelper,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // This member registers ALL the classes supported by this helper with the // vtkKWESerializationHelperMap, which manages all the helpers. Should be // called after construction unless you only want to enable support for // a subset (in which case it must be done "manually" by calling // vtkKWESerializationHelperMap::RegisterHelperForClass() virtual void RegisterWithHelperMap() = 0; // Description: // Unregister the helper (remove each class type/helper pair) with the // vtkKWESerializationHelperMap virtual void UnRegisterWithHelperMap() = 0; // Description: // Get the value for the "type" attribute of the specfied object type virtual const char *GetSerializationType(vtkObject *object) = 0; // Description: // Serialize the input object. Returns 1 if successful. virtual int Serialize(vtkObject *object, vtkKWESerializer *serializer) = 0; protected: vtkKWESerializationHelper() {} ~vtkKWESerializationHelper() {} private: vtkKWESerializationHelper(const vtkKWESerializationHelper&); // Not implemented. void operator=(const vtkKWESerializationHelper&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/ExportConfiguration.cmake0000644000175000017500000001635011363410610021053 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # Generate the VTKEdgeConfig.cmake file in the build tree. Also configure # one for installation. The file tells external projects how to use # VTKEdge. # Help store a literal dollar in a string. CMake 2.2 allows escaped # dollars but we have to support CMake 2.0. set(DOLLAR "$") #----------------------------------------------------------------------------- # Settings shared between the build tree and install tree. export_library_dependencies( ${VTKEdge_BINARY_DIR}/VTKEdgeLibraryDepends.cmake) include(${CMAKE_ROOT}/Modules/CMakeExportBuildSettings.cmake) cmake_export_build_settings( ${VTKEdge_BINARY_DIR}/VTKEdgeBuildSettings.cmake) if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_PACKAGE_DIR} FILES ${CMAKE_CURRENT_SOURCE_DIR}/UseVTKEdge.cmake ${VTKEdge_BINARY_DIR}/VTKEdgeLibraryDepends.cmake ${VTKEdge_BINARY_DIR}/VTKEdgeBuildSettings.cmake ) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) #----------------------------------------------------------------------------- # Settings specific to the build tree. # The install-only section is empty for the build tree. set(VTKEdge_CONFIG_INSTALL_ONLY) # The "use" file. set(VTKEdge_USE_FILE_CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/UseVTKEdge.cmake) # The build settings file. set(VTKEdge_BUILD_SETTINGS_FILE_CONFIG ${VTKEdge_BINARY_DIR}/VTKEdgeBuildSettings.cmake) # The library directories. set(VTKEdge_LIBRARY_DIRS_CONFIG ${VTKEdge_LIBRARY_DIRS}) # The runtime directories. set(VTKEdge_RUNTIME_DIRS_CONFIG ${VTKEdge_RUNTIME_DIRS}) # The include directories. set(VTKEdge_INCLUDE_DIRS_CONFIG ${VTKEdge_INCLUDE_PATH}) # The library dependencies file. set(VTKEdge_LIBRARY_DEPENDS_FILE ${VTKEdge_BINARY_DIR}/VTKEdgeLibraryDepends.cmake) # The CMake macros dir. set(VTKEdge_CMAKE_DIR_CONFIG ${VTKEdge_CMAKE_DIR}) # The VTK options. set(VTKEdge_VTK_DIR_CONFIG ${VTK_DIR}) # The build configuration information. set(VTKEdge_CONFIGURATION_TYPES_CONFIG ${VTKEdge_CONFIGURATION_TYPES}) set(VTKEdge_BUILD_TYPE_CONFIG ${CMAKE_BUILD_TYPE}) # Configure VTKEdgeConfig.cmake for the build tree. configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/VTKEdgeConfig.cmake.in ${VTKEdge_BINARY_DIR}/VTKEdgeConfig.cmake @ONLY IMMEDIATE) #----------------------------------------------------------------------------- # Settings specific to the install tree. # The "use" file. set(VTKEdge_USE_FILE_CONFIG ${DOLLAR}{VTKEdge_INSTALL_PREFIX}${VTKEdge_INSTALL_PACKAGE_DIR}/UseVTKEdge.cmake) # The build settings file. set(VTKEdge_BUILD_SETTINGS_FILE_CONFIG ${DOLLAR}{VTKEdge_INSTALL_PREFIX}${VTKEdge_INSTALL_PACKAGE_DIR}/VTKEdgeBuildSettings.cmake) # The library directories. if(CYGWIN AND VTKEdge_BUILD_SHARED_LIBS) # In Cygwin programs directly link to the .dll files. set(VTKEdge_LIBRARY_DIRS_CONFIG ${DOLLAR}{VTKEdge_INSTALL_PREFIX}${VTKEdge_INSTALL_BIN_DIR}) else(CYGWIN AND VTKEdge_BUILD_SHARED_LIBS) set(VTKEdge_LIBRARY_DIRS_CONFIG ${DOLLAR}{VTKEdge_INSTALL_PREFIX}${VTKEdge_INSTALL_LIB_DIR}) endif(CYGWIN AND VTKEdge_BUILD_SHARED_LIBS) # The runtime directories. if(WIN32) set(VTKEdge_RUNTIME_DIRS_CONFIG ${DOLLAR}{VTKEdge_INSTALL_PREFIX}${VTKEdge_INSTALL_BIN_DIR}) else(WIN32) set(VTKEdge_RUNTIME_DIRS_CONFIG ${DOLLAR}{VTKEdge_INSTALL_PREFIX}${VTKEdge_INSTALL_LIB_DIR}) endif(WIN32) # The include directories. set(VTKEdge_INCLUDE_DIRS_CONFIG ${DOLLAR}{VTKEdge_INSTALL_PREFIX}${VTKEdge_INSTALL_INCLUDE_DIR}) # The library dependencies file. set(VTKEdge_LIBRARY_DEPENDS_FILE ${DOLLAR}{VTKEdge_INSTALL_PREFIX}${VTKEdge_INSTALL_PACKAGE_DIR}/VTKEdgeLibraryDepends.cmake) # The CMake macros dir. set(VTKEdge_CMAKE_DIR_CONFIG ${DOLLAR}{VTKEdge_INSTALL_PREFIX}${VTKEdge_INSTALL_PACKAGE_DIR}/CMake) # The VTK options. # If VTK_BINARY_DIR is set, then VTKEdge is part of a larger parent project # that also builds VTK. In that case, VTKEdge_VTK_INSTALL_PACKAGE_DIR # should be set to the value of VTK_INSTALL_PACKAGE_DIR. Otherwise, if not set, # then we are using an outside VTK whose location will not change when we # install. if(VTK_BINARY_DIR) if(NOT VTKEdge_VTK_INSTALL_PACKAGE_DIR) message( "VTKEdge_VTK_INSTALL_PACKAGE_DIR must be set by the parent project to the value of VTK_INSTALL_PACKAGE_DIR it uses to configure VTK.") endif(NOT VTKEdge_VTK_INSTALL_PACKAGE_DIR) set(VTKEdge_VTK_DIR_CONFIG ${VTKEdge_VTK_INSTALL_PACKAGE_DIR}) else(VTK_BINARY_DIR) set(VTKEdge_VTK_DIR_CONFIG ${VTK_DIR}) endif(VTK_BINARY_DIR) # The build configuration information. # The install tree only has one configuration. set(VTKEdge_CONFIGURATION_TYPES_CONFIG) # Configure VTKEdgeConfig.cmake for the install tree. # Construct the proper number of GET_FILENAME_COMPONENT(... PATH) # calls to compute the installation prefix from VTKEdge_DIR. string(REGEX REPLACE "/" ";" VTKEdge_INSTALL_PACKAGE_DIR_COUNT "${VTKEdge_INSTALL_PACKAGE_DIR}") set(VTKEdge_CONFIG_INSTALL_ONLY " # Compute the installation prefix from VTKEdge_DIR. set(VTKEdge_INSTALL_PREFIX \"${DOLLAR}{VTKEdge_DIR}\") ") foreach(p ${VTKEdge_INSTALL_PACKAGE_DIR_COUNT}) set(VTKEdge_CONFIG_INSTALL_ONLY "${VTKEdge_CONFIG_INSTALL_ONLY}GET_FILENAME_COMPONENT(VTKEdge_INSTALL_PREFIX \"${DOLLAR}{VTKEdge_INSTALL_PREFIX}\" PATH)\n" ) endforeach(p) if(CMAKE_CONFIGURATION_TYPES) # There are multiple build configurations. Configure one # VTKEdgeConfig.cmake for each configuration. foreach(config ${CMAKE_CONFIGURATION_TYPES}) set(VTKEdge_BUILD_TYPE_CONFIG ${config}) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/VTKEdgeConfig.cmake.in ${VTKEdge_BINARY_DIR}/Install/${config}/VTKEdgeConfig.cmake @ONLY IMMEDIATE) endforeach(config) # Install the config file corresponding to the build configuration # specified when building the install target. The BUILD_TYPE variable # will be set while CMake is processing the install files. if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_PACKAGE_DIR} FILES ${VTKEdge_BINARY_DIR}/Install/${DOLLAR}{BUILD_TYPE}/VTKEdgeConfig.cmake) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) else(CMAKE_CONFIGURATION_TYPES) # There is only one build configuration. Configure one VTKEdgeConfig.cmake. set(VTKEdge_BUILD_TYPE_CONFIG ${CMAKE_BUILD_TYPE}) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/VTKEdgeConfig.cmake.in ${VTKEdge_BINARY_DIR}/Install/VTKEdgeConfig.cmake @ONLY IMMEDIATE) # Setup an install rule for the config file. if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_PACKAGE_DIR} FILES ${VTKEdge_BINARY_DIR}/Install/VTKEdgeConfig.cmake) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) endif(CMAKE_CONFIGURATION_TYPES) vtkedge-0.2.0~20110819/Rendering/0000755000175000017500000000000011630435007015754 5ustar mathieumathieuvtkedge-0.2.0~20110819/Rendering/vtkKWEIlluminatedLinesPainter_fs.glsl0000644000175000017500000000213311363410610025203 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // Filename: vtkIlluminatedLinesPainter_fp.glsl // Filename is useful when using gldb-gui // Fragement shader. Must only be used when InterpolateScalarsBeforeMapping is // ON. #version 110 uniform sampler2D tex; varying vec4 varColor; varying vec4 varSpecular; void main () { vec4 texColor = texture2D(tex, gl_TexCoord[0].st); gl_FragColor = texColor * varColor + varSpecular; } vtkedge-0.2.0~20110819/Rendering/vtkKWEWireframePainter_vs.glsl0000644000175000017500000000247211363410610023710 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // Id: $Id: vtkKWEWireframePainter_vs.glsl 1774 2010-04-20 20:41:44Z avila $ #version 110 varying vec4 vColor; // from vtkKWEColorMaterialHelper gl_MaterialParameters getMaterialParameters(); // from vtkKWELightingHelper vec4 singleColor(gl_MaterialParameters m, vec3 surfacePosEyeCoords, vec3 n); vec4 colorFrontFace() { vec4 heyeCoords = gl_ModelViewMatrix*gl_Vertex; vec3 eyeCoords = heyeCoords.xyz/heyeCoords.w; vec3 n = normalize(gl_NormalMatrix*gl_Normal); return singleColor(getMaterialParameters(),eyeCoords,n); } void main (void) { gl_Position = ftransform(); vColor = colorFrontFace(); } vtkedge-0.2.0~20110819/Rendering/vtkKWEVertexBufferObject.h0000644000175000017500000000571011363410610022756 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEVertexBufferObject // .SECTION Description #ifndef __vtkKWEVertexBufferObject_h #define __vtkKWEVertexBufferObject_h #include "vtkObject.h" #include "VTKEdgeConfigure.h" // include configuration header #include "vtkWeakPointer.h" // needed for vtkWeakPointer. class vtkRenderWindow; class vtkOpenGLExtensionManager; class vtkDataArray; class vtkCellArray; class vtkPainterDeviceAdapter; class VTKEdge_RENDERING_EXPORT vtkKWEVertexBufferObject : public vtkObject { public: static vtkKWEVertexBufferObject* New(); vtkTypeRevisionMacro(vtkKWEVertexBufferObject, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Get/Set the context. Context must be a vtkOpenGLRenderWindow. // This does not increase the reference count of the // context to avoid reference loops. // SetContext() may raise an error is the OpenGL context does not support the // required OpenGL extensions. void SetContext(vtkRenderWindow* context); vtkRenderWindow* GetContext(); //BTX enum BufferType{ ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER }; // Description: // Make the buffer active. void Bind(BufferType buffer); //ETX // Description: // Inactivate the buffer. void UnBind(); // Description: // Upload the data array. bool Upload(vtkDataArray* array, BufferType type=ARRAY_BUFFER); bool UploadIndices(vtkCellArray* ca, bool build_draw_multielements_arrays=false); bool RenderIndices(int vtkprimtype); vtkGetMacro(Initialized, bool); //BTX protected: vtkKWEVertexBufferObject(); ~vtkKWEVertexBufferObject(); // Description: // Loads all required OpenGL extensions. Must be called every time a new // context is set. bool LoadRequiredExtensions(vtkOpenGLExtensionManager* mgr); // Description: // Create the pixel buffer object. void CreateBuffer(); // Description: // Destroys the pixel buffer object. void DestroyBuffer(); vtkWeakPointer Context; unsigned int BufferTarget; // actually GLenum unsigned int Handle; bool Initialized; private: vtkKWEVertexBufferObject(const vtkKWEVertexBufferObject&); // Not implemented. void operator=(const vtkKWEVertexBufferObject&); // Not implemented. class vtkInternals; vtkInternals* Internals; //ETX }; #endif vtkedge-0.2.0~20110819/Rendering/vtkKWEWireframePainter_fs.glsl0000644000175000017500000000245311363410610023667 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // Id: $Id: vtkKWEWireframePainter_fs.glsl 1774 2010-04-20 20:41:44Z avila $ #version 110 uniform sampler2D texDepth; uniform vec2 uViewSize; varying vec4 vColor; const vec2 threshold = vec2(0.00001, 0.005); void main (void) { float surfaceDepth = texture2D(texDepth, gl_FragCoord.xy/uViewSize).x; // tolerance increases as depth increases, this ensures that the lines appear // smooth and continuous. float tolerance = threshold.x + (1.0 - gl_FragCoord.z) * (threshold.y - threshold.x); if (surfaceDepth+tolerance < gl_FragCoord.z) { discard; } gl_FragColor = vColor; } vtkedge-0.2.0~20110819/Rendering/CMakeLists.txt0000644000175000017500000000725111412720617020523 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Set of basic source files (not the OpenGL or GLSL ones) # ----------------------------------------------------------------------------- set(KIT_SRCS vtkKWEIlluminatedLinesPainter.cxx vtkKWERenderingFactory.cxx vtkKWEVBOTStripsPainter.cxx vtkKWEVertexBufferObject.cxx vtkKWEWireframePainter.cxx ) # ----------------------------------------------------------------------------- # Set of GLSL source files # ----------------------------------------------------------------------------- set(KIT_GLSL_SRCS vtkKWEIlluminatedLinesPainter_fs vtkKWEIlluminatedLinesPainter_vs vtkKWEWireframePainter_fs vtkKWEWireframePainter_vs ) # ----------------------------------------------------------------------------- # Create custom commands to encode each glsl file into a C string literal # in a header file # ----------------------------------------------------------------------------- foreach(file ${KIT_GLSL_SRCS}) set(src ${CMAKE_CURRENT_SOURCE_DIR}/${file}.glsl) set(res ${CMAKE_CURRENT_BINARY_DIR}/${file}.cxx) add_custom_command( OUTPUT ${res} DEPENDS ${src} COMMAND ${VTK_ENCODESTRING_EXE} ARGS ${res} ${src} ${file} ) set(KIT_EXTRA_SRCS ${KIT_EXTRA_SRCS} ${res}) #set(KIT_EXTRA_SRCS ${res}) endforeach(file) # ----------------------------------------------------------------------------- # List the kits from VTK that are needed by this project # ----------------------------------------------------------------------------- set(KIT_LIBS vtkRendering ) # ----------------------------------------------------------------------------- # Create the library # ----------------------------------------------------------------------------- add_library(vtkKWERendering ${KIT_SRCS} ${KIT_EXTRA_SRCS}) target_link_libraries(vtkKWERendering ${KIT_LIBS}) # ----------------------------------------------------------------------------- # Testing # ----------------------------------------------------------------------------- if(BUILD_TESTING) add_subdirectory(Testing) endif(BUILD_TESTING) # ----------------------------------------------------------------------------- # Installation # ----------------------------------------------------------------------------- if(NOT VTKEdge_INSTALL_NO_LIBRARIES) install_targets( ${VTKEdge_INSTALL_LIB_DIR} RUNTIME_DIRECTORY ${VTKEdge_INSTALL_BIN_DIR} vtkKWERendering ) endif(NOT VTKEdge_INSTALL_NO_LIBRARIES) if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_INCLUDE_DIR} .h ${KIT_SRCS}) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) # ----------------------------------------------------------------------------- # This make it easy for other projects to get the list of files etc. in this # kit. # ----------------------------------------------------------------------------- include(${VTK_CMAKE_DIR}/vtkExportKit.cmake) vtk_export_kit2("KWERendering" "KWERENDERING" ${CMAKE_CURRENT_BINARY_DIR} "${KIT_SRCS}") vtkedge-0.2.0~20110819/Rendering/vtkKWEVBOTStripsPainter.cxx0000644000175000017500000002234511363410610023100 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEVBOTStripsPainter.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkObjectFactory.h" #include "vtkPainterDeviceAdapter.h" #include "vtkPoints.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkRenderer.h" #include "vtkOpenGLRenderWindow.h" #include "vtkUnsignedCharArray.h" #include "vtkTriangle.h" #include "vtkOpenGLExtensionManager.h" #include "vtkKWEVertexBufferObject.h" #define BUFFER_OFFSET(i) ((char*)NULL + (i)) vtkStandardNewMacro(vtkKWEVBOTStripsPainter); vtkCxxRevisionMacro(vtkKWEVBOTStripsPainter, "$Revision: 1774 $"); //----------------------------------------------------------------------------- vtkKWEVBOTStripsPainter::vtkKWEVBOTStripsPainter() { this->PointIDs = vtkKWEVertexBufferObject::New(); this->PointCoordinates = vtkKWEVertexBufferObject::New(); this->PointColors = vtkKWEVertexBufferObject::New(); this->PointNormals = vtkKWEVertexBufferObject::New(); this->PointTCords = vtkKWEVertexBufferObject::New(); } //----------------------------------------------------------------------------- vtkKWEVBOTStripsPainter::~vtkKWEVBOTStripsPainter() { if (this->LastContext) { this->ReleaseGraphicsResources(this->LastContext); this->LastContext = 0; } this->PointIDs->Delete(); this->PointCoordinates->Delete(); this->PointColors->Delete(); this->PointNormals->Delete(); this->PointTCords->Delete(); } //----------------------------------------------------------------------------- void vtkKWEVBOTStripsPainter::ReleaseGraphicsResources(vtkWindow* w) { if (this->LastContext && this->LastContext.GetPointer() == w) { this->PointIDs->SetContext(0); this->PointCoordinates->SetContext(0); this->PointColors->SetContext(0); this->PointNormals->SetContext(0); this->PointTCords->SetContext(0); this->LastContext = 0; } this->Superclass::ReleaseGraphicsResources(w); } //----------------------------------------------------------------------------- bool vtkKWEVBOTStripsPainter::UpdateGraphicsResources(unsigned long idx, vtkDataArray* n, vtkUnsignedCharArray* c, vtkDataArray* t, vtkRenderer* renderer) { bool forceUpdate = false; vtkRenderWindow* renWin = renderer->GetRenderWindow(); if (this->LastContext && this->LastContext != renWin) { this->ReleaseGraphicsResources(this->LastContext); forceUpdate = true; } this->LastContext = renWin; this->PointIDs->SetContext(renWin); this->PointCoordinates->SetContext(renWin); this->PointColors->SetContext(renWin); this->PointNormals->SetContext(renWin); this->PointTCords->SetContext(renWin); vtkPolyData* pd = this->GetInputAsPolyData(); vtkPoints* points = pd->GetPoints(); vtkCellArray* ca = pd->GetStrips(); if (forceUpdate || !this->PointIDs->GetInitialized() || this->PointIDs->GetMTime() < pd->GetMTime() || this->PointIDs->GetMTime() < ca->GetMTime()) { if (!this->PointIDs->UploadIndices(ca, true)) { return false; } } if (forceUpdate || !this->PointCoordinates->GetInitialized() || this->PointCoordinates->GetMTime() < pd->GetMTime() || this->PointCoordinates->GetMTime() < points->GetMTime()) { if (!this->PointCoordinates->Upload(points->GetData())) { return false; } } if ((idx & VTK_PDM_NORMALS) && n) { if (forceUpdate || !this->PointNormals->GetInitialized() || this->PointNormals->GetMTime() < pd->GetMTime() || this->PointNormals->GetMTime() < n->GetMTime()) { if (!this->PointNormals->Upload(n)) { return false; } } } else { // ensures that any allocated buffer are cleared. this->PointNormals->SetContext(0); } if ((idx & VTK_PDM_COLORS) && c && !(idx & VTK_PDM_CELL_COLORS)) { if (forceUpdate || !this->PointColors->GetInitialized() || this->PointColors->GetMTime() < pd->GetMTime() || this->PointColors->GetMTime() < c->GetMTime()) { if (!this->PointColors->Upload(c)) { return false; } } } else { this->PointColors->SetContext(0); } // transfer texture coords to buffer object if (idx & VTK_PDM_TCOORDS && t) { if (forceUpdate || !this->PointTCords->GetInitialized() || this->PointTCords->GetMTime() < pd->GetMTime() || this->PointTCords->GetMTime() < t->GetMTime()) { if (!this->PointTCords->Upload(t)) { return false; } } } else { this->PointTCords->SetContext(0); } // everything was transfered O.K. return true; } //----------------------------------------------------------------------------- int vtkKWEVBOTStripsPainter::RenderPrimitive(unsigned long idx, vtkDataArray* n, vtkUnsignedCharArray* c, vtkDataArray* t, vtkRenderer* ren) { vtkOpenGLRenderWindow* renWin = vtkOpenGLRenderWindow::SafeDownCast( ren->GetRenderWindow()); // anything to draw? vtkPolyData* pd = this->GetInputAsPolyData(); vtkCellArray* ca = pd->GetStrips(); vtkPoints* points = pd->GetPoints(); vtkIdType numCells = ca->GetNumberOfCells(); if (numCells <= 0) { return 1; } bool case_handled = true; // We don't handle cell attributes or generic attributes. Eventually, we'll // support generic attributes. if ((idx & VTK_PDM_CELL_NORMALS) || (idx & VTK_PDM_CELL_COLORS) || (idx & VTK_PDM_GENERIC_VERTEX_ATTRIBUTES)) { case_handled = false; } // build normals is slower using VBOs, pass to delegate if (!(idx & (VTK_PDM_NORMALS | VTK_PDM_CELL_NORMALS)) && this->BuildNormals) { case_handled = false; } // check for extension support vtkOpenGLExtensionManager* mgr = renWin->GetExtensionManager(); if (!mgr->ExtensionSupported("GL_VERSION_2_0") && !mgr->ExtensionSupported("GL_ARB_vertex_buffer_object")) { case_handled = false; } // generate the VBOs and copy data to the card if (case_handled == false || this->UpdateGraphicsResources(idx, n, c, t, ren) == false) { if (this->LastContext) { this->ReleaseGraphicsResources(this->LastContext); this->LastContext = 0; } return this->Superclass::RenderPrimitive(idx, n, c, t, ren); } // enable arrays and client state vtkPainterDeviceAdapter* device = ren->GetRenderWindow()-> GetPainterDeviceAdapter(); if (this->PointCoordinates->GetInitialized()) { this->PointCoordinates->Bind(vtkKWEVertexBufferObject::ARRAY_BUFFER); device->SetAttributePointer(vtkDataSetAttributes::NUM_ATTRIBUTES, 3, points->GetDataType(), 0, NULL); this->PointCoordinates->UnBind(); device->EnableAttributeArray(vtkDataSetAttributes::NUM_ATTRIBUTES); } if (this->PointNormals->GetInitialized()) { this->PointNormals->Bind(vtkKWEVertexBufferObject::ARRAY_BUFFER); device->SetAttributePointer(vtkDataSetAttributes::NORMALS, 3, n->GetDataType(), 0, NULL); this->PointNormals->UnBind(); device->EnableAttributeArray(vtkDataSetAttributes::NORMALS); } if (this->PointColors->GetInitialized()) { int numComponents = idx & VTK_PDM_OPAQUE_COLORS ? 3 : 4; int dataNumComponents = c->GetNumberOfComponents(); int stride = (dataNumComponents == 4 && numComponents == 3) ? 4 * c->GetDataTypeSize() : 0; this->PointColors->Bind(vtkKWEVertexBufferObject::ARRAY_BUFFER); device->SetAttributePointer(vtkDataSetAttributes::SCALARS, numComponents, c->GetDataType(), stride, NULL); this->PointColors->UnBind(); device->EnableAttributeArray(vtkDataSetAttributes::SCALARS); } // tcoords if (this->PointTCords->GetInitialized()) { int numComponents = t->GetNumberOfComponents(); this->PointTCords->Bind(vtkKWEVertexBufferObject::ARRAY_BUFFER); device->SetAttributePointer(vtkDataSetAttributes::TCOORDS, numComponents, t->GetDataType(), 0, 0); this->PointTCords->UnBind(); device->EnableAttributeArray(vtkDataSetAttributes::TCOORDS); } this->PointIDs->RenderIndices(VTK_TRIANGLE_STRIP); // disable client state device->DisableAttributeArray(vtkDataSetAttributes::NUM_ATTRIBUTES); device->DisableAttributeArray(vtkDataSetAttributes::NORMALS); device->DisableAttributeArray(vtkDataSetAttributes::SCALARS); device->DisableAttributeArray(vtkDataSetAttributes::TCOORDS); return 1; } //----------------------------------------------------------------------------- void vtkKWEVBOTStripsPainter::PrintSelf(ostream& os ,vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } vtkedge-0.2.0~20110819/Rendering/vtkKWERenderingFactory.cxx0000644000175000017500000000536611363410610023047 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWERenderingFactory.h" #include "vtkObjectFactory.h" #include "vtkToolkits.h" #include "vtkVersion.h" #include "vtkKWEIlluminatedLinesPainter.h" #include "vtkKWEWireframePainter.h" #include "vtkKWEVBOTStripsPainter.h" vtkStandardNewMacro(vtkKWERenderingFactory); vtkCxxRevisionMacro(vtkKWERenderingFactory, "$Revision: 1774 $"); //---------------------------------------------------------------------------- VTK_FACTORY_INTERFACE_IMPLEMENT(vtkKWERenderingFactory); VTK_CREATE_CREATE_FUNCTION(vtkKWEIlluminatedLinesPainter); VTK_CREATE_CREATE_FUNCTION(vtkKWEWireframePainter); VTK_CREATE_CREATE_FUNCTION(vtkKWEVBOTStripsPainter); //---------------------------------------------------------------------------- vtkKWERenderingFactory::vtkKWERenderingFactory() { this->RegisterOverride("vtkLinesPainter", "vtkKWEIlluminatedLinesPainter", "KWERendering", 1, vtkObjectFactoryCreatevtkKWEIlluminatedLinesPainter); this->RegisterOverride("vtkRepresentationPainter", "vtkKWEWireframePainter", "KWERendering", 1, vtkObjectFactoryCreatevtkKWEWireframePainter); this->RegisterOverride("vtkTStripsPainter", "vtkKWEVBOTStripsPainter", "KWERendering", 1, vtkObjectFactoryCreatevtkKWEVBOTStripsPainter); } //---------------------------------------------------------------------------- void vtkKWERenderingFactory::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //---------------------------------------------------------------------------- const char* vtkKWERenderingFactory::GetVTKSourceVersion() { return VTK_SOURCE_VERSION; } //---------------------------------------------------------------------------- const char* vtkKWERenderingFactory::GetDescription() { return "VTKEdge Rendering Support Factory"; } //---------------------------------------------------------------------------- void vtkKWERenderingFactory::RegisterFactory() { vtkKWERenderingFactory* factory = vtkKWERenderingFactory::New(); vtkObjectFactory::RegisterFactory(factory); factory->Delete(); } vtkedge-0.2.0~20110819/Rendering/Testing/0000755000175000017500000000000011630435007017371 5ustar mathieumathieuvtkedge-0.2.0~20110819/Rendering/Testing/Cxx/0000755000175000017500000000000011630435007020133 5ustar mathieumathieuvtkedge-0.2.0~20110819/Rendering/Testing/Cxx/TestGlyph3DMapperOrientationArray.cxx0000644000175000017500000001043211363410610027345 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkActor.h" #include "vtkCamera.h" #include "vtkPlaneSource.h" #include "vtkElevationFilter.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkSuperquadricSource.h" #include "vtkSphereSource.h" #include "vtkPolyDataReader.h" #include "vtkInteractorStyleSwitch.h" #include "vtkArrayCalculator.h" #include "vtkPointData.h" #include "vtkConeSource.h" // If USE_FILTER is defined, glyph3D->PolyDataMapper is used instead of // Glyph3DMapper. //#define USE_FILTER #ifdef USE_FILTER # include "vtkGlyph3D.h" #else # include "vtkKWEGlyph3DMapper.h" #endif int TestGlyph3DMapperOrientationArray(int argc, char *argv[]) { int res=30; vtkPlaneSource *plane=vtkPlaneSource::New(); plane->SetResolution(res,res); vtkElevationFilter *colors=vtkElevationFilter::New(); colors->SetInputConnection(plane->GetOutputPort()); colors->SetLowPoint(-0.25,-0.25,-0.25); colors->SetHighPoint(0.25,0.25,0.25); vtkPolyDataMapper *planeMapper=vtkPolyDataMapper::New(); planeMapper->SetInputConnection(colors->GetOutputPort()); colors->Delete(); vtkArrayCalculator *calc=vtkArrayCalculator::New(); calc->SetInputConnection(colors->GetOutputPort()); calc->AddScalarVariable("x","Elevation"); // calc->AddCoordinateVectorVariable("p"); calc->SetResultArrayName("orientation"); calc->SetResultArrayType(VTK_DOUBLE); calc->SetFunction("100*x*jHat"); calc->Update(); calc->GetOutput()->GetPointData()->SetActiveScalars("Elevation"); vtkActor *planeActor=vtkActor::New(); planeActor->SetMapper(planeMapper); planeMapper->Delete(); planeActor->GetProperty()->SetRepresentationToWireframe(); vtkConeSource *squad=vtkConeSource::New(); squad->SetHeight(10.0); squad->SetRadius(1.0); squad->SetResolution(50); squad->SetDirection(0.0,0.0,1.0); #ifdef USE_FILTER vtkGlyph3D *glypher=vtkGlyph3D::New(); glypher->SetInputConnection(colors->GetOutputPort()); #else vtkKWEGlyph3DMapper *glypher=vtkKWEGlyph3DMapper::New(); glypher->SetInputConnection(calc->GetOutputPort()); glypher->SetOrientationArray("orientation"); glypher->SetOrientationModeToRotation(); #endif glypher->SetScaleFactor(0.01); glypher->SetSourceConnection(squad->GetOutputPort()); squad->Delete(); plane->Delete(); calc->Delete(); #ifdef USE_FILTER vtkPolyDataMapper *glyphMapper=vtkPolyDataMapper::New(); glyphMapper->SetInputConnection(glypher->GetOutputPort()); #endif vtkActor *glyphActor=vtkActor::New(); #ifdef USE_FILTER glyphActor->SetMapper(glyphMapper); glyphMapper->Delete(); #else glyphActor->SetMapper(glypher); #endif glypher->Delete(); //Create the rendering stuff vtkRenderer *ren=vtkRenderer::New(); vtkRenderWindow *win=vtkRenderWindow::New(); win->SetMultiSamples(0); // make sure regression images are the same on all platforms win->AddRenderer(ren); ren->Delete(); vtkRenderWindowInteractor *iren=vtkRenderWindowInteractor::New(); vtkInteractorStyleSwitch::SafeDownCast(iren->GetInteractorStyle())->SetCurrentStyleToTrackballCamera(); iren->SetRenderWindow(win); win->Delete(); ren->AddActor(planeActor); planeActor->Delete(); ren->AddActor(glyphActor); glyphActor->Delete(); ren->SetBackground(0.5,0.5,0.5); win->SetSize(450,450); win->Render(); ren->GetActiveCamera()->Zoom(1.5); win->Render(); int retVal = vtkRegressionTestImage(win); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } iren->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Rendering/Testing/Cxx/TestIlluminatedLines.cxx0000644000175000017500000000663011363410610024762 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkActor.h" #include "vtkCamera.h" #include "vtkGenericDataObjectReader.h" #include "vtkKWEIlluminatedLinesPainter.h" #include "vtkKWERenderingFactory.h" #include "vtkPainterPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkTestUtilities.h" int TestIlluminatedLines(int argc, char *argv[]) { // Register factory. vtkKWERenderingFactory::RegisterFactory(); vtkRenderer *renderer = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *interactor = vtkRenderWindowInteractor::New(); interactor->SetRenderWindow(renWin); renWin->SetSize(300,300); renderer->SetBackground(0.3, 0.3, 0.3); renWin->Render(); if (!vtkKWEIlluminatedLinesPainter::IsSupported(renWin)) { cout << "WARNING: The rendering context does not support required " "extensions." << endl; return 0; } char* filename = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/disk_out_ref_streamlines.vtk"); vtkGenericDataObjectReader *pl3d = vtkGenericDataObjectReader::New(); pl3d->SetFileName(filename); delete[] filename; pl3d->Update(); vtkPainterPolyDataMapper * mapper = vtkPainterPolyDataMapper::New(); mapper->SetInputConnection(pl3d->GetOutputPort()); pl3d->Delete(); mapper->SelectColorArray("Pres"); mapper->SetScalarModeToUsePointFieldData(); mapper->ScalarVisibilityOff(); mapper->CreateDefaultLookupTable(); mapper->InterpolateScalarsBeforeMappingOn(); mapper->ImmediateModeRenderingOff(); mapper->SetScalarRange(0.006, 0.022); vtkActor *actor = vtkActor::New(); actor->SetMapper(mapper); mapper->Delete(); actor->GetProperty()->SetSpecularPower(50.0); //actor->GetProperty()->SetColor(1,1,1); actor->GetProperty()->SetColor(0.8,0.4,0.1); // actor->GetProperty()->SetSpecularColor(0.5,0.5,0.1); actor->GetProperty()->SetDiffuse(0.8); actor->GetProperty()->SetSpecular(0.5); // actor->GetProperty()->SetSpecularColor(0.9, 0.7, 0.7); // actor->GetProperty()->SetDiffuseColor(0.5, 0.5, 0.5); renderer->AddActor(actor); actor->Delete(); renderer->GetActiveCamera()->Azimuth(280); renderer->ResetCamera(); renderer->GetActiveCamera()->Zoom(1.5); renWin->Render(); int retVal = vtkTesting::Test(argc, argv, renWin, 75); if (retVal == vtkRegressionTester::DO_INTERACTOR) { interactor->Start(); } interactor->Delete(); renderer->RemoveAllViewProps(); renderer->Delete(); renWin->Delete(); if ((retVal == vtkTesting::PASSED) || (retVal == vtkTesting::DO_INTERACTOR)) { return 0; } // failed. return 1; } vtkedge-0.2.0~20110819/Rendering/Testing/Cxx/TestHiddenLinesRemoval.cxx0000644000175000017500000000574211363410610025237 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkCamera.h" #include "vtkObjectFactory.h" #include "vtkPainterPolyDataMapper.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" #include "vtkXMLPolyDataReader.h" #include "vtkKWERenderingFactory.h" #include "vtkProperty.h" #define VTK_CREATE_NEW(var, class) vtkSmartPointer var = vtkSmartPointer::New(); int TestHiddenLinesRemoval(int argc, char* argv[]) { vtkKWERenderingFactory::RegisterFactory(); char* filename = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/disk_out_ref_surface.vtp"); VTK_CREATE_NEW(reader, vtkXMLPolyDataReader); if (!reader->CanReadFile(filename)) { cerr << "Cannot read file: " << filename << endl; return 1; } reader->SetFileName(filename); delete [] filename; reader->Update(); VTK_CREATE_NEW(renWin, vtkRenderWindow); VTK_CREATE_NEW(renderer, vtkRenderer); VTK_CREATE_NEW(iren, vtkRenderWindowInteractor); renWin->SetReportGraphicErrors(1); renWin->AddRenderer(renderer); renWin->SetSize(300,300); iren->SetRenderWindow(renWin); VTK_CREATE_NEW(clone, vtkPolyData); clone->ShallowCopy(reader->GetOutput()); clone->GetPointData()->SetActiveVectors("V"); VTK_CREATE_NEW(mapper, vtkPainterPolyDataMapper); mapper->SetInput(clone); mapper->ImmediateModeRenderingOn(); VTK_CREATE_NEW(actor, vtkActor); actor->SetMapper(mapper); actor->GetProperty()->SetRepresentation(VTK_WIREFRAME); renderer->AddActor(actor); renderer->GetActiveCamera()->SetFocalPoint(-1.88, -0.98, -1.04); renderer->GetActiveCamera()->SetPosition(13.64, 4.27, -31.59); renderer->GetActiveCamera()->SetViewAngle(30); renderer->GetActiveCamera()->SetViewUp(0.41, 0.83, 0.35); renderer->SetBackground(0.3, 0.3, 0.3); //renderer->SetViewport(.2, 0.2, 1, 1); renderer->ResetCamera(); //actor->SetPosition(10, 0, 0); renWin->Render(); int retVal = vtkTesting::Test(argc, argv, renWin, 75); if (retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } if ((retVal == vtkTesting::PASSED) || (retVal == vtkTesting::DO_INTERACTOR)) { return 0; } // failed. return 1; } vtkedge-0.2.0~20110819/Rendering/Testing/Cxx/TestGlyph3DMapperPicking.cxx0000644000175000017500000001740611363410610025447 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This tests vtkVisibleCellSelector, vtkExtractSelectedFrustum, // vtkRenderedAreaPicker, and vtkInteractorStyleRubberBandPick. // // The command line arguments are: // -I => run in interactive mode; unless this is used, the program will // not allow interaction and exit #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSphereSource.h" #include "vtkActor.h" #include "vtkInteractorStyleRubberBandPick.h" #include "vtkCommand.h" #include "vtkHardwareSelector.h" #include "vtkSelection.h" #include "vtkIdTypeArray.h" #include "vtkRenderedAreaPicker.h" #include "vtkCamera.h" #include "vtkImageActor.h" #include "vtkPointData.h" #include "vtkPlaneSource.h" #include "vtkElevationFilter.h" #include "vtkBitArray.h" #include "vtkKWEGlyph3DMapper.h" #include "vtkSelection.h" #include "vtkSelectionNode.h" #include vtkRenderer *renderer = NULL; class MyEndPickCommand : public vtkCommand { public: MyEndPickCommand() { this->Renderer=0; // no reference counting this->Mask=0; // no reference counting this->DataSet=0; } virtual ~MyEndPickCommand() { // empty } virtual void Execute(vtkObject *vtkNotUsed(caller), unsigned long vtkNotUsed(eventId), void *vtkNotUsed(callData)) { assert("pre: renderer_exists" && this->Renderer!=0); vtkHardwareSelector *sel = vtkHardwareSelector::New(); sel->SetFieldAssociation(vtkDataObject::FIELD_ASSOCIATION_POINTS); sel->SetRenderer(renderer); double x0 = renderer->GetPickX1(); double y0 = renderer->GetPickY1(); double x1 = renderer->GetPickX2(); double y1 = renderer->GetPickY2(); sel->SetArea(static_cast(x0), static_cast(y0), static_cast(x1), static_cast(y1)); vtkSelection *res = sel->Select(); #if 0 cerr << "x0 " << x0 << " y0 " << y0 << "\t"; cerr << "x1 " << x1 << " y1 " << y1 << endl; res->Print(cout); #endif // Reset the mask to false. vtkIdType numPoints = this->Mask->GetNumberOfTuples(); for (vtkIdType i=0; i < numPoints; i++) { this->Mask->SetValue(i,false); } vtkSelectionNode *glyphids = res->GetNode(0); if (glyphids!=0) { vtkAbstractArray *abs=glyphids->GetSelectionList(); if(abs==0) { cout<<"abs is null"<GetNumberOfTuples(); for (vtkIdType i =0; i < numSelPoints; i++) { vtkIdType value = ids->GetValue(i); if (value >=0 && value < numPoints) { cout << "Turn On: " << value << endl; this->Mask->SetValue(value,true); } else { cout << "Ignoring: " << value << endl; } } } } this->DataSet->Modified(); sel->Delete(); res->Delete(); } void SetRenderer(vtkRenderer *r) { this->Renderer=r; } vtkRenderer *GetRenderer() const { return this->Renderer; } void SetMask(vtkBitArray *m) { this->Mask=m; } void SetDataSet(vtkDataSet* ds) { this->DataSet = ds; } protected: vtkRenderer *Renderer; vtkBitArray *Mask; vtkDataSet *DataSet; }; int TestGlyph3DMapperPicking(int argc, char* argv[]) { int res=6; vtkPlaneSource *plane=vtkPlaneSource::New(); plane->SetResolution(res,res); vtkElevationFilter *colors=vtkElevationFilter::New(); colors->SetInputConnection(plane->GetOutputPort()); plane->Delete(); colors->SetLowPoint(-0.25,-0.25,-0.25); colors->SetHighPoint(0.25,0.25,0.25); vtkSphereSource *squad=vtkSphereSource::New(); squad->SetPhiResolution(25); squad->SetThetaResolution(25); vtkKWEGlyph3DMapper *glypher=vtkKWEGlyph3DMapper::New(); // glypher->SetNestedDisplayLists(0); glypher->SetInputConnection(colors->GetOutputPort()); colors->Delete(); glypher->SetScaleFactor(0.1); glypher->SetSourceConnection(squad->GetOutputPort()); squad->Delete(); // selection is performed on actor1 vtkActor *glyphActor1=vtkActor::New(); glyphActor1->SetMapper(glypher); glypher->Delete(); glyphActor1->PickableOn(); // result of selection is on actor2 vtkActor *glyphActor2=vtkActor::New(); glyphActor2->PickableOff(); colors->Update(); // make sure output is valid. vtkDataSet *selection=colors->GetOutput()->NewInstance(); selection->ShallowCopy(colors->GetOutput()); vtkBitArray *selectionMask=vtkBitArray::New(); selectionMask->SetName("mask"); selectionMask->SetNumberOfComponents(1); selectionMask->SetNumberOfTuples(selection->GetNumberOfPoints()); // Initially, everything is selected vtkIdType i=0; vtkIdType c=selectionMask->GetNumberOfTuples(); while(iSetValue(i,true); ++i; } selection->GetPointData()->AddArray(selectionMask); selectionMask->Delete(); vtkKWEGlyph3DMapper *glypher2=vtkKWEGlyph3DMapper::New(); // glypher->SetNestedDisplayLists(0); glypher2->SetMasking(1); glypher2->SetMaskArray("mask"); glypher2->SetInputConnection(0, selection->GetProducerPort()); glypher2->SetScaleFactor(0.1); glypher2->SetSourceConnection(squad->GetOutputPort()); glyphActor2->SetMapper(glypher2); glypher2->Delete(); // Standard rendering classes renderer = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); //set up the view renderer->SetBackground(0.2,0.2,0.2); renWin->SetSize(300,300); //use the rubber band pick interactor style vtkRenderWindowInteractor* rwi = renWin->GetInteractor(); vtkInteractorStyleRubberBandPick *rbp = vtkInteractorStyleRubberBandPick::New(); rwi->SetInteractorStyle(rbp); vtkRenderedAreaPicker *areaPicker = vtkRenderedAreaPicker::New(); rwi->SetPicker(areaPicker); renderer->AddActor(glyphActor1); renderer->AddActor(glyphActor2); glyphActor2->SetPosition(2,0,0); glyphActor1->Delete(); glyphActor2->Delete(); //pass pick events to the VisibleGlyphSelector MyEndPickCommand *cbc=new MyEndPickCommand; cbc->SetRenderer(renderer); cbc->SetMask(selectionMask); cbc->SetDataSet(selection); rwi->AddObserver(vtkCommand::EndPickEvent,cbc); cbc->Delete(); //////////////////////////////////////////////////////////// //run the test renderer->ResetCamera(); renWin->Render(); areaPicker->AreaPick(51,78,82,273,renderer); cbc->Execute(NULL, 0, NULL); renWin->Render(); int retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } // Cleanup renderer->Delete(); renWin->Delete(); iren->Delete(); rbp->Delete(); areaPicker->Delete(); selection->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Rendering/Testing/Cxx/TestVBO.cxx0000644000175000017500000000464011363410610022145 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkActor.h" #include "vtkCamera.h" #include "vtkGenericDataObjectReader.h" #include "vtkKWERenderingFactory.h" #include "vtkPainterPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkTestUtilities.h" #include "vtkSphereSource.h" #include "vtkStripper.h" #include "vtkTimerLog.h" int TestVBO(int argc, char* argv[]) { vtkRenderWindow *renWin = vtkRenderWindow::New(); vtkRenderer *renderer = vtkRenderer::New(); renWin->AddRenderer(renderer); renderer->SetBackground(1, 1, 0); renderer->Delete(); vtkRenderWindowInteractor *interactor = vtkRenderWindowInteractor::New(); interactor->SetRenderWindow(renWin); vtkKWERenderingFactory::RegisterFactory(); vtkSphereSource* sphere = vtkSphereSource::New(); sphere->SetThetaResolution(1024); sphere->SetPhiResolution(1024); vtkStripper* stipper = vtkStripper::New(); stipper->SetInputConnection(sphere->GetOutputPort()); vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); mapper->SetInputConnection(stipper->GetOutputPort()); mapper->ImmediateModeRenderingOn(); vtkActor* actor = vtkActor::New(); actor->SetMapper(mapper); renderer->AddActor(actor); renWin->Render(); vtkTimerLog* log = vtkTimerLog::New(); double sum = 0.0; for (int cc=0; cc < 50; cc++) { log->StartTimer(); renWin->Render(); log->StopTimer(); sum += log->GetElapsedTime(); } log->Delete(); cout << "Avg Time: " << sum/50.0 << endl; //interactor->Start(); renWin->Delete(); interactor->Delete(); sphere->Delete(); stipper->Delete(); mapper->Delete(); actor->Delete(); return 0; } vtkedge-0.2.0~20110819/Rendering/Testing/Cxx/CMakeLists.txt0000644000175000017500000000535511412720617022705 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Name this kit - this will be used to form test executable names later # Then we'll add in tests with various data or kit dependencies to the # test executables # ----------------------------------------------------------------------------- set(KIT Rendering) set(TESTBASE ${PROJECT_NAME}${KIT}) # ----------------------------------------------------------------------------- # First, list all the tests that either use no data, or only data from the # VTKEdge data directory (which always exists since it is part of the # VTKEdge repository). These will go into one test executable. # ----------------------------------------------------------------------------- set(MyTests TestIlluminatedLines.cxx TestHiddenLinesRemoval.cxx # TestTransferRates.cxx # TestVBO.cxx ) # add tests that require data from VTKData/Data include_directories("${VTKEdge_SOURCE_DIR}/Examples/Rendering/Cxx") create_test_sourcelist(Tests ${TESTBASE}CxxTests.cxx ${MyTests} ${MyTestsWithVTKData} EXTRA_INCLUDE vtkTestDriver.h ) add_executable(${TESTBASE}CxxTests ${Tests}) #install_targets(${VTKEdge_INSTALL_BIN_DIR} ${TESTBASE}CxxTests) target_link_libraries(${TESTBASE}CxxTests vtkKWERendering) set(TestsToRun ${Tests}) remove(TestsToRun ${TESTBASE}CxxTests.cxx ${MyTestsWithVTKData}) # Add all the executables foreach(test ${TestsToRun}) get_filename_component(TName ${test} NAME_WE) add_test(${TName} ${CXX_TEST_PATH}/${TESTBASE}CxxTests ${TName} -D ${PROJECT_SOURCE_DIR}/Data -T ${PROJECT_BINARY_DIR}/Testing/Temporary -V ${PROJECT_SOURCE_DIR}/Data/Baseline/${KIT}/${TName}.png ) endforeach(test) if(VTK_DATA_ROOT) foreach(test ${MyTestsWithVTKData}) get_filename_component(TName ${test} NAME_WE) add_test(${TName} ${CXX_TEST_PATH}/${TESTBASE}CxxTests ${TName} -D ${VTK_DATA_ROOT} -T ${PROJECT_BINARY_DIR}/Testing/Temporary -V ${PROJECT_SOURCE_DIR}/Data/Baseline/${KIT}/${TName}.png ) endforeach(test) endif(VTK_DATA_ROOT) vtkedge-0.2.0~20110819/Rendering/Testing/Cxx/TestGlyph3DMapperMasking.cxx0000644000175000017500000001076111363410610025451 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkActor.h" #include "vtkCamera.h" #include "vtkPlaneSource.h" #include "vtkElevationFilter.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkSuperquadricSource.h" #include "vtkSphereSource.h" #include "vtkPolyDataReader.h" #include "vtkInteractorStyleSwitch.h" #include "vtkArrayCalculator.h" #include "vtkPointData.h" // If USE_FILTER is defined, glyph3D->PolyDataMapper is used instead of // Glyph3DMapper. //#define USE_FILTER #ifdef USE_FILTER # include "vtkGlyph3D.h" #else # include "vtkKWEGlyph3DMapper.h" #endif int TestGlyph3DMapperMasking(int argc, char *argv[]) { int res=30; vtkPlaneSource *plane=vtkPlaneSource::New(); plane->SetResolution(res,res); vtkElevationFilter *colors=vtkElevationFilter::New(); colors->SetInputConnection(plane->GetOutputPort()); colors->SetLowPoint(-0.25,-0.25,-0.25); colors->SetHighPoint(0.25,0.25,0.25); vtkPolyDataMapper *planeMapper=vtkPolyDataMapper::New(); planeMapper->SetInputConnection(colors->GetOutputPort()); colors->Delete(); vtkArrayCalculator *calc=vtkArrayCalculator::New(); calc->SetInputConnection(colors->GetOutputPort()); calc->SetResultArrayName("mask"); calc->SetResultArrayType(VTK_BIT); calc->AddScalarArrayName("Elevation"); calc->SetFunction("Elevation>0.2 & Elevation<0.4"); calc->Update(); calc->GetOutput()->GetPointData()->GetArray("mask"); calc->GetOutput()->GetPointData()->SetActiveScalars("Elevation"); vtkActor *planeActor=vtkActor::New(); planeActor->SetMapper(planeMapper); planeMapper->Delete(); planeActor->GetProperty()->SetRepresentationToWireframe(); // create simple poly data so we can apply glyph // vtkSuperquadricSource *squad=vtkSuperquadricSource::New(); vtkSphereSource *squad=vtkSphereSource::New(); squad->SetPhiResolution(45); squad->SetThetaResolution(45); #ifdef USE_FILTER vtkGlyph3D *glypher=vtkGlyph3D::New(); glypher->SetInputConnection(colors->GetOutputPort()); #else vtkKWEGlyph3DMapper *glypher=vtkKWEGlyph3DMapper::New(); glypher->SetNestedDisplayLists(0); glypher->SetMasking(1); glypher->SetMaskArray("mask"); glypher->SetInputConnection(calc->GetOutputPort()); //glypher->SetInputConnection(colors->GetOutputPort()); calc->Delete(); #endif // glypher->SetScaleModeToDataScalingOn(); glypher->SetScaleFactor(0.1); //glypher->SetInputConnection(plane->GetOutputPort()); glypher->SetSourceConnection(squad->GetOutputPort()); squad->Delete(); plane->Delete(); #ifdef USE_FILTER vtkPolyDataMapper *glyphMapper=vtkPolyDataMapper::New(); glyphMapper->SetInputConnection(glypher->GetOutputPort()); #endif vtkActor *glyphActor=vtkActor::New(); #ifdef USE_FILTER glyphActor->SetMapper(glyphMapper); glyphMapper->Delete(); #else glyphActor->SetMapper(glypher); #endif glypher->Delete(); //Create the rendering stuff vtkRenderer *ren=vtkRenderer::New(); vtkRenderWindow *win=vtkRenderWindow::New(); win->SetMultiSamples(0); // make sure regression images are the same on all platforms win->AddRenderer(ren); ren->Delete(); vtkRenderWindowInteractor *iren=vtkRenderWindowInteractor::New(); vtkInteractorStyleSwitch::SafeDownCast(iren->GetInteractorStyle())->SetCurrentStyleToTrackballCamera(); iren->SetRenderWindow(win); win->Delete(); ren->AddActor(planeActor); planeActor->Delete(); ren->AddActor(glyphActor); glyphActor->Delete(); ren->SetBackground(0.5,0.5,0.5); win->SetSize(450,450); win->Render(); ren->GetActiveCamera()->Zoom(1.5); win->Render(); int retVal = vtkRegressionTestImage(win); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } iren->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Rendering/Testing/Cxx/TestGlyph3DMapper.cxx0000644000175000017500000000640711363410610024141 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkActor.h" #include "vtkCamera.h" #include "vtkPlaneSource.h" #include "vtkElevationFilter.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkSuperquadricSource.h" // If USE_FILTER is defined, glyph3D->PolyDataMapper is used instead of // Glyph3DMapper. //#define USE_FILTER #ifdef USE_FILTER # include "vtkGlyph3D.h" #else # include "vtkKWEGlyph3DMapper.h" #endif int TestGlyph3DMapper(int argc, char *argv[]) { int res=6; vtkPlaneSource *plane=vtkPlaneSource::New(); plane->SetResolution(res,res); vtkElevationFilter *colors=vtkElevationFilter::New(); colors->SetInputConnection(plane->GetOutputPort()); plane->Delete(); colors->SetLowPoint(-0.25,-0.25,-0.25); colors->SetHighPoint(0.25,0.25,0.25); vtkPolyDataMapper *planeMapper=vtkPolyDataMapper::New(); planeMapper->SetInputConnection(colors->GetOutputPort()); colors->Delete(); vtkActor *planeActor=vtkActor::New(); planeActor->SetMapper(planeMapper); planeMapper->Delete(); planeActor->GetProperty()->SetRepresentationToWireframe(); // create simple poly data so we can apply glyph vtkSuperquadricSource *squad=vtkSuperquadricSource::New(); #ifdef USE_FILTER vtkGlyph3D *glypher=vtkGlyph3D::New(); #else vtkKWEGlyph3DMapper *glypher=vtkKWEGlyph3DMapper::New(); #endif glypher->SetInputConnection(colors->GetOutputPort()); glypher->SetSourceConnection(squad->GetOutputPort()); squad->Delete(); #ifdef USE_FILTER vtkPolyDataMapper *glyphMapper=vtkPolyDataMapper::New(); glyphMapper->SetInputConnection(glypher->GetOutputPort()); #endif vtkActor *glyphActor=vtkActor::New(); #ifdef USE_FILTER glyphActor->SetMapper(glyphMapper); glyphMapper->Delete(); #else glyphActor->SetMapper(glypher); #endif glypher->Delete(); //Create the rendering stuff vtkRenderer *ren=vtkRenderer::New(); vtkRenderWindow *win=vtkRenderWindow::New(); win->AddRenderer(ren); ren->Delete(); vtkRenderWindowInteractor *iren=vtkRenderWindowInteractor::New(); iren->SetRenderWindow(win); win->Delete(); ren->AddActor(planeActor); planeActor->Delete(); ren->AddActor(glyphActor); glyphActor->Delete(); ren->SetBackground(0.5,0.5,0.5); win->SetSize(450,450); win->Render(); ren->GetActiveCamera()->Zoom(1.5); win->Render(); int retVal = vtkRegressionTestImage(win); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } iren->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Rendering/Testing/Cxx/TestGlyph3DMapperArrow.cxx0000644000175000017500000001030011363410610025137 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkActor.h" #include "vtkCamera.h" #include "vtkPLOT3DReader.h" #include "vtkExtractGrid.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkArrowSource.h" #include "vtkExecutive.h" #include "vtkInformationVector.h" #include "vtkTimerLog.h" // If USE_FILTER is defined, glyph3D->PolyDataMapper is used instead of // Glyph3DMapper. //#define USE_FILTER #ifdef USE_FILTER # include "vtkGlyph3D.h" #else # include "vtkKWEGlyph3DMapper.h" #endif // from Graphics/Testing/Python/glyphComb.py int TestGlyph3DMapperArrow(int argc, char *argv[]) { vtkPLOT3DReader *reader=vtkPLOT3DReader::New(); char *fname= vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/combxyz.bin"); reader->SetXYZFileName(fname); delete[] fname; fname=vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/combq.bin"); reader->SetQFileName(fname); delete[] fname; reader->SetScalarFunctionNumber(100); reader->SetVectorFunctionNumber(202); reader->Update(); vtkExtractGrid *eg=vtkExtractGrid::New(); eg->SetInputConnection(reader->GetOutputPort()); reader->Delete(); eg->SetSampleRate(4,4,4); eg->Update(); cout<< "eg pts="<GetOutput()->GetNumberOfPoints()<GetElapsedTime()<<" seconds" <GetActiveCamera()->Zoom(1.5); timer->StartTimer(); win->Render(); timer->StopTimer(); cout<<"second frame: "<< timer->GetElapsedTime()<<" seconds" <Delete(); int retVal = vtkRegressionTestImage(win); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } iren->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Rendering/Testing/CMakeLists.txt0000644000175000017500000000166011363410610022130 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Add the Cxx testing directory # ----------------------------------------------------------------------------- add_subdirectory(Cxx) vtkedge-0.2.0~20110819/Rendering/vtkKWERenderingFactory.h0000644000175000017500000000313511363410610022464 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWERenderingFactory - // .SECTION Description #ifndef __vtkKWERenderingFactory_h #define __vtkKWERenderingFactory_h #include "vtkObjectFactory.h" #include "VTKEdgeConfigure.h" // include configuration header class VTKEdge_RENDERING_EXPORT vtkKWERenderingFactory : public vtkObjectFactory { public: static vtkKWERenderingFactory *New(); vtkTypeRevisionMacro(vtkKWERenderingFactory,vtkObjectFactory); virtual void PrintSelf(ostream& os, vtkIndent indent); virtual const char* GetVTKSourceVersion(); virtual const char* GetDescription(); // Description: // Can be called to register this factory with the vtkObjectFactory singleton. static void RegisterFactory(); protected: vtkKWERenderingFactory(); private: vtkKWERenderingFactory(const vtkKWERenderingFactory&); // Not implemented. void operator=(const vtkKWERenderingFactory&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Rendering/vtkKWEIlluminatedLinesPainter.h0000644000175000017500000000746011363410610024011 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEIlluminatedLinesPainter - painter that paints lines. // .SECTION Description // This painter tries to paint lines efficiently. Request to Render // any other primitive are ignored and not passed to the delegate painter, // if any. This painter cannot handle cell colors/normals. If they are // present the request is passed on to the Delegate painter. If this // class is able to render the primitive, the render request is not // propagated to the delegate painter. // #ifndef __vtkKWEIlluminatedLinesPainter_h #define __vtkKWEIlluminatedLinesPainter_h #include "vtkLinesPainter.h" #include "VTKEdgeConfigure.h" // include configuration header #include "vtkWeakPointer.h" // needed for vtkWeakPointer. class vtkInformationIntegerKey; class vtkShaderProgram2; class vtkShader2; class vtkPainterPolyDataMapper; class vtkRenderWindow; class vtkWindow; class VTKEdge_RENDERING_EXPORT vtkKWEIlluminatedLinesPainter : public vtkLinesPainter { public: static vtkKWEIlluminatedLinesPainter* New(); vtkTypeRevisionMacro(vtkKWEIlluminatedLinesPainter, vtkLinesPainter); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Release any graphics resources that are being consumed by this painter. // The parameter window could be used to determine which graphic // resources to release. // The call is propagated to the delegate painter, if any. virtual void ReleaseGraphicsResources(vtkWindow *); // Description: // Key used to enable/disable this painter. static vtkInformationIntegerKey* ENABLE(); // Description: // Initializes the mapper with a new instance of vtkKWEIlluminatedLinesPainter // inserted at the correct location. static void UpdateMapper(vtkPainterPolyDataMapper* mapper); // Description: // Returns if the context supports the required extensions. static bool IsSupported(vtkRenderWindow* renWin); //BTX protected: vtkKWEIlluminatedLinesPainter(); ~vtkKWEIlluminatedLinesPainter(); // Description: // Called before RenderInternal() if the Information has been changed // since the last time this method was called. virtual void ProcessInformation(vtkInformation*); // Description: // Some subclasses may need to do some preprocessing // before the actual rendering can be done eg. build effecient // representation for the data etc. This should be done here. // This method get called after the ProcessInformation() // but before RenderInternal(). virtual void PrepareForRendering(vtkRenderer*, vtkActor*); // Description: // The actual rendering happens here. This method is called only when // SupportedPrimitive is present in typeflags when Render() is invoked. virtual int RenderPrimitive(unsigned long flags, vtkDataArray* n, vtkUnsignedCharArray* c, vtkDataArray* t, vtkRenderer* ren); vtkSetMacro(Enable, int); int Enable; vtkWeakPointer LastRenderWindow; vtkShaderProgram2* Program; vtkShader2* FragmentShader; private: vtkKWEIlluminatedLinesPainter(const vtkKWEIlluminatedLinesPainter&); // Not implemented. void operator=(const vtkKWEIlluminatedLinesPainter&); // Not implemented. //ETX }; #endif vtkedge-0.2.0~20110819/Rendering/vtkKWEWireframePainter.h0000644000175000017500000000470211363410610022464 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEWireframePainter // .SECTION Description #ifndef __vtkKWEWireframePainter_h #define __vtkKWEWireframePainter_h #include "vtkOpenGLRepresentationPainter.h" #include "VTKEdgeConfigure.h" // include configuration header class VTKEdge_RENDERING_EXPORT vtkKWEWireframePainter : public vtkOpenGLRepresentationPainter { public: static vtkKWEWireframePainter* New(); vtkTypeRevisionMacro(vtkKWEWireframePainter, vtkOpenGLRepresentationPainter); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Release any graphics resources that are being consumed by this mapper. // The parameter window could be used to determine which graphic // resources to release. In this case, releases the display lists. virtual void ReleaseGraphicsResources(vtkWindow *); //BTX protected: vtkKWEWireframePainter(); ~vtkKWEWireframePainter(); // Description: // Some subclasses may need to do some preprocessing // before the actual rendering can be done eg. build effecient // representation for the data etc. This should be done here. // This method get called after the ProcessInformation() // but before RenderInternal(). virtual void PrepareForRendering(vtkRenderer*, vtkActor*); // Description: // Changes the polygon mode according to the representation. void RenderInternal(vtkRenderer* renderer, vtkActor* actor, unsigned long typeflags, bool forceCompileOnly); // Description: // Returns true when rendering is possible. bool CanRender(vtkRenderer*, vtkActor*); private: vtkKWEWireframePainter(const vtkKWEWireframePainter&); // Not implemented. void operator=(const vtkKWEWireframePainter&); // Not implemented. class vtkInternals; vtkInternals* Internals; //ETX }; #endif vtkedge-0.2.0~20110819/Rendering/vtkKWEVertexBufferObject.cxx0000644000175000017500000002204011363410610023324 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEVertexBufferObject.h" #include "vtkObjectFactory.h" #include "vtkOpenGLRenderWindow.h" #include "vtkOpenGLExtensionManager.h" #include "vtkDataArray.h" #include "vtkCellArray.h" #include "vtkPainterDeviceAdapter.h" #include //--------------------------------------------------------------------------- class vtkKWEVertexBufferObject::vtkInternals { public: const GLvoid **MDEIndexOffsets; GLsizei *MDECounts; GLsizei MDEPrimCount; void Init() { this->MDEPrimCount = 0; this->MDECounts = 0; this->MDEIndexOffsets = 0; } void Clear() { delete [] this->MDECounts; delete [] this->MDEIndexOffsets; this->Init(); } vtkInternals() { this->Init(); } ~vtkInternals() { this->Clear(); } }; vtkStandardNewMacro(vtkKWEVertexBufferObject); vtkCxxRevisionMacro(vtkKWEVertexBufferObject, "$Revision: 1774 $"); //---------------------------------------------------------------------------- vtkKWEVertexBufferObject::vtkKWEVertexBufferObject() { this->Internals = new vtkKWEVertexBufferObject::vtkInternals(); this->Handle = 0; this->Context = 0; this->BufferTarget = 0; this->Initialized = false; } //---------------------------------------------------------------------------- vtkKWEVertexBufferObject::~vtkKWEVertexBufferObject() { this->SetContext(0); delete this->Internals; } //---------------------------------------------------------------------------- bool vtkKWEVertexBufferObject::LoadRequiredExtensions(vtkOpenGLExtensionManager* mgr) { return (mgr->LoadSupportedExtension("GL_VERSION_2_0") && mgr->LoadSupportedExtension("GL_VERSION_1_5") && mgr->LoadSupportedExtension("GL_ARB_vertex_buffer_object")); } //---------------------------------------------------------------------------- vtkRenderWindow* vtkKWEVertexBufferObject::GetContext() { return this->Context; } //---------------------------------------------------------------------------- void vtkKWEVertexBufferObject::SetContext(vtkRenderWindow* renWin) { if (this->Context == renWin) { return; } this->DestroyBuffer(); vtkOpenGLRenderWindow* openGLRenWin = vtkOpenGLRenderWindow::SafeDownCast(renWin); this->Context = openGLRenWin; if (openGLRenWin) { if (!this->LoadRequiredExtensions(openGLRenWin->GetExtensionManager())) { this->Context = 0; vtkErrorMacro("Required OpenGL extensions not supported by the context."); } } this->Modified(); } //---------------------------------------------------------------------------- void vtkKWEVertexBufferObject::CreateBuffer() { this->Context->MakeCurrent(); if (!this->Handle) { GLuint ioBuf; vtkgl::GenBuffers(1, &ioBuf); vtkGraphicErrorMacro(this->Context, "Generate vertex buffer"); this->Handle = static_cast(ioBuf); this->Initialized = false; } } //---------------------------------------------------------------------------- void vtkKWEVertexBufferObject::DestroyBuffer() { if (this->Context && this->Handle) { GLuint ioBuf = static_cast(this->Handle); vtkgl::DeleteBuffers(1, &ioBuf); this->Initialized = false; } this->Handle = 0; this->Internals->Clear(); } //---------------------------------------------------------------------------- void vtkKWEVertexBufferObject::Bind(BufferType type) { if (!this->Context) { vtkErrorMacro("No context specified. Cannot bind."); return; } if (!this->Handle) { vtkErrorMacro("A vertex buffer can be bound only after it has been created." " Are you sure you uploaded some data?"); return; } GLenum target = this->BufferTarget; switch (type) { case ARRAY_BUFFER: target = vtkgl::ARRAY_BUFFER; break; case ELEMENT_ARRAY_BUFFER: target = vtkgl::ELEMENT_ARRAY_BUFFER; break; } if (this->BufferTarget && this->BufferTarget != target) { this->UnBind(); } this->BufferTarget = target; vtkgl::BindBuffer(this->BufferTarget, this->Handle); vtkGraphicErrorMacro(this->Context,"Post Bind"); } //---------------------------------------------------------------------------- void vtkKWEVertexBufferObject::UnBind() { if (this->Context && this->Handle && this->BufferTarget) { vtkgl::BindBuffer(this->BufferTarget, 0); vtkGraphicErrorMacro(this->Context,"Post UnBind"); this->BufferTarget = 0; } } //---------------------------------------------------------------------------- bool vtkKWEVertexBufferObject::Upload(vtkDataArray* data, BufferType type) { this->Internals->Clear(); if (!this->Context) { vtkErrorMacro("No context specified. Cannot upload data."); return false; } // TODO: Handle double data. this->CreateBuffer(); this->Bind(type); vtkgl::BufferData(this->BufferTarget, data->GetDataTypeSize() * data->GetNumberOfTuples() * data->GetNumberOfComponents(), data->GetVoidPointer(0), vtkgl::STATIC_DRAW); // TODO: Try stream draw vtkGraphicErrorMacro(this->Context,"Post Upload"); this->UnBind(); this->Initialized = true; this->Modified(); return true; } //---------------------------------------------------------------------------- bool vtkKWEVertexBufferObject::UploadIndices(vtkCellArray* ca, bool build_draw_multielements_arrays/*=false*/) { this->Internals->Clear(); if (!this->Context) { vtkErrorMacro("No context specified. Cannot upload data."); return false; } this->CreateBuffer(); this->Bind(ELEMENT_ARRAY_BUFFER); vtkIdType numCells = ca->GetNumberOfCells(); vtkIdType numIndices = (ca->GetNumberOfConnectivityEntries() - numCells); // TODO: try to use minimum data size. vtkgl::BufferData(this->BufferTarget, static_cast( static_cast(numIndices)*sizeof(GLuint)), NULL, vtkgl::STATIC_DRAW); // TODO: Try stream draw GLuint *vboPtr = reinterpret_cast( vtkgl::MapBuffer(vtkgl::ELEMENT_ARRAY_BUFFER, vtkgl::WRITE_ONLY)); if (build_draw_multielements_arrays) { this->Internals->MDECounts = new GLsizei[numCells]; this->Internals->MDEIndexOffsets = new const GLvoid*[numCells]; this->Internals->MDEPrimCount = static_cast(numCells); } size_t currentBufferOffset = 0; vtkIdType* caData = ca->GetPointer(); for (vtkIdType kk=0; kk < numCells; ++kk) { vtkIdType numPoints = *(caData); caData++; for (vtkIdType cc=0; cc < numPoints; ++cc) { *vboPtr = static_cast(*caData); caData++; vboPtr++; } if (build_draw_multielements_arrays) { this->Internals->MDECounts[kk] = static_cast(numPoints); this->Internals->MDEIndexOffsets[kk] = reinterpret_cast(currentBufferOffset); } currentBufferOffset += (static_cast(numPoints) * sizeof(GLuint)); } vtkgl::UnmapBuffer(vtkgl::ELEMENT_ARRAY_BUFFER); this->UnBind(); this->Initialized = true; this->Modified(); return true; } static const GLenum VTK2OpenGLPrimitive[] = { static_cast(0xFFFF), // 0 - VTK_EMPTY_CELL GL_POINTS, // 1 - VTK_VERTEX GL_POINTS, // 2 - VTK_POLY_VERTEX GL_LINES, // 3 - VTK_LINE GL_LINE_STRIP, // 4 - VTK_POLY_LINE GL_TRIANGLES, // 5 - VTK_TRIANGLE GL_TRIANGLE_STRIP, // 6 - VTK_TRIANGLE_STRIP GL_POLYGON, // 7 - VTK_POLYGON static_cast(0xFFFF), // 8 - VTK_PIXEL GL_QUADS, // 9 - VTK_QUAD GL_LINE_LOOP // 10 - VTK_TETRA }; //---------------------------------------------------------------------------- bool vtkKWEVertexBufferObject::RenderIndices(int vtkprimtype) { if (vtkprimtype <= 0 || vtkprimtype >= VTK_TETRA) { vtkErrorMacro("Unsupported primitive: " << vtkprimtype); return false; } if (this->Initialized && this->Internals->MDEPrimCount > 0) { this->Bind(ELEMENT_ARRAY_BUFFER); vtkgl::MultiDrawElements(VTK2OpenGLPrimitive[vtkprimtype], this->Internals->MDECounts, GL_UNSIGNED_INT, this->Internals->MDEIndexOffsets, this->Internals->MDEPrimCount); this->UnBind(); return true; } return false; } //---------------------------------------------------------------------------- void vtkKWEVertexBufferObject::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } vtkedge-0.2.0~20110819/Rendering/vtkKWEVBOTStripsPainter.h0000644000175000017500000000662611363410610022531 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkVBOLinesPainter - this painter paints triangle strips using vertex // buffer objects to increase data transfer speeds. // .SECTION Description // This painter tries to paint triangle strips efficiently. Data are // transfered in bulk to vertex buffer objects and then rendered from // these buffers. If vertex buffer objects are not supported, or if // they cannot be allocated, then this renderer cannot render the // primitive and will propagate the request to the delegate painter. // Requests to Render any other primitive are ignored and not passed // to the delegate painter, if any. If this class is able to render // the primitive, the render request is not propagated to the delegate // painter. Cell attributes are not supported. #ifndef __vtkKWEVBOTStripsPainter_h #define __vtkKWEVBOTStripsPainter_h #include "VTKEdgeConfigure.h" // include configuration header #include "vtkTStripsPainter.h" class vtkKWEVertexBufferObject; class vtkRenderWindow; class VTKEdge_RENDERING_EXPORT vtkKWEVBOTStripsPainter : public vtkTStripsPainter { public: static vtkKWEVBOTStripsPainter* New(); vtkTypeRevisionMacro(vtkKWEVBOTStripsPainter, vtkTStripsPainter); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Delete VBOs virtual void ReleaseGraphicsResources(vtkWindow* w); //BTX protected: vtkKWEVBOTStripsPainter(); ~vtkKWEVBOTStripsPainter(); // Description: // The actual rendering happens here. VBOs are generated if // necessary, data is copied to the VBOs, and the primitive is drawn. virtual int RenderPrimitive(unsigned long flags, vtkDataArray* n, vtkUnsignedCharArray* c, vtkDataArray* t, vtkRenderer* ren); // Description: // Copy data (points, normals, colors, tcoords, indices) to the // VBOs. Calls GenerateVBOs to make sure that the VBOs have not // been generated. Returns nonzero if all data was updated // successfully. It is probably a good idea to call // ReleaseGraphicsResources if this call is not successful. virtual bool UpdateGraphicsResources(unsigned long idx, vtkDataArray* n, vtkUnsignedCharArray* c, vtkDataArray* t, vtkRenderer* ren); vtkKWEVertexBufferObject* PointIDs; vtkKWEVertexBufferObject* PointCoordinates; vtkKWEVertexBufferObject* PointColors; vtkKWEVertexBufferObject* PointNormals; vtkKWEVertexBufferObject* PointTCords; vtkWeakPointer LastContext; private: vtkKWEVBOTStripsPainter(const vtkKWEVBOTStripsPainter&); // Not implemented. void operator=(const vtkKWEVBOTStripsPainter&); // Not implemented. //ETX }; #endif vtkedge-0.2.0~20110819/Rendering/vtkKWEIlluminatedLinesPainter_vs.glsl0000644000175000017500000000725411363410610025234 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // Filename: vtkIlluminatedLinesPainter_vp.glsl // Filename is useful when using gldb-gui /* * Vertex program for illuminated lines using maxumum reflection principle. * IN: tangent(3) as gl_TexCoord[0].stp */ #version 110 varying vec4 varColor; varying vec4 varSpecular; vec3 getViewVector() { // Camera position is obtained by doing: // gl_ModelViewMatrixInverse * vec4(0.0, 0.0, 0.0, 1.0); // However that's same as simply taking the 4th column, hence we can avoid the // matrix multiplication -- yea!!! vec4 cameraPosition = gl_ModelViewMatrixInverse[3];//* vec4(0.0, 0.0, 0.0, 1.0); return cameraPosition.xyz - gl_Vertex.xyz; } #define GL_AMBIENT 1 #define GL_DIFFUSE 2 #define GL_SPECULAR 3 #define GL_AMBIENT_AND_DIFFUSE 4 #define GL_EMISSION 5 uniform int uMode; gl_MaterialParameters getMaterialParameters() { if (uMode == 0) { return gl_FrontMaterial; } gl_MaterialParameters materialParams = gl_FrontMaterial; if (uMode == GL_AMBIENT) { materialParams.ambient = gl_Color; } else if (uMode == GL_DIFFUSE) { materialParams.diffuse = gl_Color; } else if (uMode == GL_SPECULAR) { materialParams.specular = gl_Color; } else if (uMode == GL_AMBIENT_AND_DIFFUSE) { materialParams.ambient = gl_Color; materialParams.diffuse = gl_Color; } else if (uMode == GL_EMISSION) { materialParams.emission = gl_Color; } return materialParams; } #define VTK_MAX_LIGHTS 8 void lighting() { vec3 V = normalize(getViewVector()); vec3 T = normalize(gl_Vertex.xyz - gl_MultiTexCoord1.stp); // tangent float Vt = min(0.9999999, abs(dot(V, T))); vec4 vAmbient = vec4(0.0); vec4 vDiffuse = vec4(0.0); vec4 vSpecular = vec4(0.0); gl_MaterialParameters material = getMaterialParameters(); for (int cc=0; cc < VTK_MAX_LIGHTS; cc++) { // we are using the light.diffuse.w to convey the enabled state. if (gl_LightSource[cc].diffuse.w > 0.0) { // gl_LightSource gives position in ModelView space, we need to transform it // back to world space. vec4 worldLightPosition = gl_ModelViewMatrixInverse * gl_LightSource[cc].position; vec3 L = normalize(worldLightPosition.xyz - gl_Vertex.xyz); float Lt = min(0.9999999, abs(dot(L, T))); float Fd = sqrt(1.0 - Lt * Lt); float term = sqrt(1.0 - Vt*Vt) * Fd - Vt*Lt; float Fs = 0.0; if (term > 0.0) { Fs = pow(term, material.shininess); } vAmbient += (gl_LightSource[cc].ambient); vDiffuse += abs(gl_LightSource[cc].diffuse * Fd); vSpecular += abs(gl_LightSource[cc].specular * Fs); } } varColor = (vAmbient* material.ambient + vDiffuse * material.diffuse); varSpecular = material.specular * vSpecular; vec4 color = varColor + varSpecular; gl_FrontColor = color; // This is essential, for scalar coloring done using textures to work. gl_TexCoord[0] = gl_MultiTexCoord0; } void main() { lighting(); gl_Position = ftransform(); } vtkedge-0.2.0~20110819/Rendering/vtkKWEWireframePainter.cxx0000644000175000017500000002240111370314341023035 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEWireframePainter.h" #include "vtkActor.h" #include "vtkBoundingBox.h" #include "vtkColorMaterialHelper.h" #include "vtkFrameBufferObject.h" #include "vtkLightingHelper.h" #include "vtkShaderProgram2.h" #include "vtkShader2.h" #include "vtkShader2Collection.h" #include "vtkUniformVariables.h" #include "vtkTextureObject.h" #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkOpenGLRenderWindow.h" #include #include #include "vtkgl.h" extern const char* vtkKWEWireframePainter_vs; extern const char* vtkKWEWireframePainter_fs; vtkStandardNewMacro(vtkKWEWireframePainter); vtkCxxRevisionMacro(vtkKWEWireframePainter, "$Revision: 1973 $"); #define vtkGetIndex(r,c) (c*4+r) inline double vtkClamp(double val, const double& min, const double& max) { val = (val < min)? min : val; val = (val > max)? max : val; return val; } class vtkKWEWireframePainter::vtkInternals { public: vtkWeakPointer LastContext; int LastViewportSize[2]; int ViewportExtent[4]; vtkSmartPointer FBO; vtkSmartPointer DepthImage; vtkSmartPointer Shader; vtkSmartPointer LightingHelper; vtkSmartPointer ColorMaterialHelper; vtkInternals() { this->LastViewportSize[0] = this->LastViewportSize[1] = 0; this->LightingHelper = vtkSmartPointer::New(); this->ColorMaterialHelper = vtkSmartPointer::New(); } void ClearTextures() { this->DepthImage = 0; if (this->FBO) { this->FBO->RemoveAllColorBuffers(); this->FBO->RemoveDepthBuffer(); } } void ClearGraphicsResources() { this->ClearTextures(); this->FBO = 0; this->DepthImage = 0; this->LightingHelper->Initialize(0,VTK_SHADER_TYPE_VERTEX); this->ColorMaterialHelper->Initialize(0); if(this->Shader!=0) { this->Shader->ReleaseGraphicsResources(); this->Shader = 0; } } }; //---------------------------------------------------------------------------- vtkKWEWireframePainter::vtkKWEWireframePainter() { this->Internals = new vtkInternals(); } //---------------------------------------------------------------------------- vtkKWEWireframePainter::~vtkKWEWireframePainter() { this->ReleaseGraphicsResources(this->Internals->LastContext); delete this->Internals; } //---------------------------------------------------------------------------- void vtkKWEWireframePainter::ReleaseGraphicsResources(vtkWindow* win) { this->Internals->ClearGraphicsResources(); this->Internals->LastContext = 0; this->Superclass::ReleaseGraphicsResources(win); } //---------------------------------------------------------------------------- bool vtkKWEWireframePainter::CanRender(vtkRenderer* vtkNotUsed(renderer), vtkActor* actor) { return (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME); } //---------------------------------------------------------------------------- void vtkKWEWireframePainter::PrepareForRendering(vtkRenderer* renderer, vtkActor* actor) { if (!this->CanRender(renderer, actor)) { this->Internals->ClearGraphicsResources(); this->Internals->LastContext = 0; this->Superclass::PrepareForRendering(renderer, actor); return; } vtkRenderWindow* renWin = renderer->GetRenderWindow(); if (this->Internals->LastContext != renWin) { this->Internals->ClearGraphicsResources(); } this->Internals->LastContext = renWin; int viewsize[2], vieworigin[2]; renderer->GetTiledSizeAndOrigin(&viewsize[0], &viewsize[1], &vieworigin[0], &vieworigin[1]); if (this->Internals->LastViewportSize[0] != viewsize[0] || this->Internals->LastViewportSize[1] != viewsize[1]) { // View size has changed, we need to re-generate the textures. this->Internals->ClearTextures(); } this->Internals->LastViewportSize[0] = viewsize[0]; this->Internals->LastViewportSize[1] = viewsize[1]; if (!this->Internals->FBO) { vtkFrameBufferObject* fbo = vtkFrameBufferObject::New(); fbo->SetContext(renWin); this->Internals->FBO = fbo; fbo->Delete(); } if (!this->Internals->DepthImage) { vtkTextureObject* depthImage = vtkTextureObject::New(); depthImage->SetContext(renWin); depthImage->Create2D(viewsize[0], viewsize[1], 1, VTK_VOID, false); this->Internals->FBO->SetDepthBuffer(depthImage); this->Internals->DepthImage = depthImage; depthImage->Delete(); } if (!this->Internals->Shader) { vtkShaderProgram2* pgm = vtkShaderProgram2::New(); pgm->SetContext(static_cast(renWin)); vtkShader2 *s1=vtkShader2::New(); s1->SetType(VTK_SHADER_TYPE_VERTEX); s1->SetSourceCode(vtkKWEWireframePainter_vs); s1->SetContext(pgm->GetContext()); vtkShader2 *s2=vtkShader2::New(); s2->SetType(VTK_SHADER_TYPE_FRAGMENT); s2->SetSourceCode(vtkKWEWireframePainter_fs); s2->SetContext(pgm->GetContext()); pgm->GetShaders()->AddItem(s1); pgm->GetShaders()->AddItem(s2); s1->Delete(); s2->Delete(); this->Internals->LightingHelper->Initialize(pgm,VTK_SHADER_TYPE_VERTEX); this->Internals->ColorMaterialHelper->Initialize(pgm); this->Internals->Shader = pgm; pgm->Delete(); } // Now compute the bounds of the pixels that this dataset is going to occupy // on the screen. this->Internals->ViewportExtent[0] = vieworigin[0]; this->Internals->ViewportExtent[1] = vieworigin[0] + viewsize[0]; this->Internals->ViewportExtent[2] = vieworigin[1]; this->Internals->ViewportExtent[3] = vieworigin[1] + viewsize[1]; this->Superclass::PrepareForRendering(renderer, actor); } //---------------------------------------------------------------------------- void vtkKWEWireframePainter::RenderInternal(vtkRenderer *renderer, vtkActor *actor, unsigned long typeflags, bool forceCompileOnly) { if (!this->CanRender(renderer, actor)) { this->Superclass::RenderInternal(renderer, actor, typeflags, forceCompileOnly); return; } vtkRenderWindow* renWin = renderer->GetRenderWindow(); // Save context state to be able to restore. glPushAttrib(GL_ALL_ATTRIB_BITS); glDisable(GL_POLYGON_OFFSET_FILL); glDisable(GL_POLYGON_OFFSET_LINE); glDisable(GL_POLYGON_OFFSET_POINT); // we get the view port size (not the renderwindow size). int viewsize[2], vieworigin[2]; renderer->GetTiledSizeAndOrigin(&viewsize[0], &viewsize[1], &vieworigin[0], &vieworigin[1]); // Pass One: Render surface, we are only interested in the depth buffer, hence // we don't clear the color buffer. However, color buffer attachment is needed // for FBO completeness (verify). this->Internals->FBO->StartNonOrtho(viewsize[0], viewsize[1], false); glClear(GL_DEPTH_BUFFER_BIT); this->Superclass::Superclass::RenderInternal(renderer, actor, typeflags, forceCompileOnly); glFlush(); this->Internals->FBO->UnBind(); // Now paste back the rendered image into the default framebuffer. renWin->MakeCurrent(); this->Internals->LightingHelper->PrepareForRendering(); this->Internals->ColorMaterialHelper->PrepareForRendering(); this->Internals->Shader->Build(); if(this->Internals->Shader->GetLastBuildStatus() !=VTK_SHADER_PROGRAM2_LINK_SUCCEEDED) { vtkErrorMacro("Pass Two failed."); } else { this->Internals->ColorMaterialHelper->Render(); vtkgl::ActiveTexture(vtkgl::TEXTURE0); this->Internals->DepthImage->Bind(); int value=0; this->Internals->Shader->GetUniformVariables()->SetUniformi("texDepth",1,&value); float fvalues[2]; fvalues[0]=static_cast(viewsize[0]); fvalues[1]=static_cast(viewsize[1]); this->Internals->Shader->GetUniformVariables()->SetUniformf("uViewSize",2,fvalues); this->Internals->Shader->Use(); if(!this->Internals->Shader->IsValid()) { vtkErrorMacro(<<" validation of the program failed: "<Internals->Shader->GetLastValidateLog()); } this->Superclass::RenderInternal(renderer, actor, typeflags, forceCompileOnly); this->Internals->Shader->Restore(); } // Pop the attributes. glPopAttrib(); } //---------------------------------------------------------------------------- void vtkKWEWireframePainter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } vtkedge-0.2.0~20110819/Rendering/vtkKWEIlluminatedLinesPainter.cxx0000644000175000017500000003341011370314341024360 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEIlluminatedLinesPainter.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkChooserPainter.h" #include "vtkInformation.h" #include "vtkInformationIntegerKey.h" #include "vtkLightingHelper.h" #include "vtkShaderProgram2.h" #include "vtkShader2Collection.h" #include "vtkUniformVariables.h" #include "vtkObjectFactory.h" #include "vtkOpenGLExtensionManager.h" #include "vtkOpenGLRenderWindow.h" #include "vtkPainterDeviceAdapter.h" #include "vtkPainterPolyDataMapper.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkSmartPointer.h" #include "vtkUnsignedCharArray.h" #include "vtkgl.h" extern const char* vtkKWEIlluminatedLinesPainter_vs; extern const char* vtkKWEIlluminatedLinesPainter_fs; vtkStandardNewMacro(vtkKWEIlluminatedLinesPainter); vtkCxxRevisionMacro(vtkKWEIlluminatedLinesPainter, "$Revision: 1973 $"); vtkInformationKeyMacro(vtkKWEIlluminatedLinesPainter, ENABLE, Integer); //----------------------------------------------------------------------------- vtkKWEIlluminatedLinesPainter::vtkKWEIlluminatedLinesPainter() { this->Enable = 1; this->Program = 0; this->FragmentShader=0; this->SetSupportedPrimitive(vtkPainter::LINES | vtkPainter::POLYS); } //----------------------------------------------------------------------------- vtkKWEIlluminatedLinesPainter::~vtkKWEIlluminatedLinesPainter() { if (this->LastRenderWindow) { vtkSmartPointer lastWindow = this->LastRenderWindow.GetPointer(); this->ReleaseGraphicsResources(this->LastRenderWindow); } if(this->FragmentShader!=0) { this->FragmentShader->Delete(); this->FragmentShader=0; } if (this->Program) { this->Program->Delete(); this->Program = 0; } } //----------------------------------------------------------------------------- void vtkKWEIlluminatedLinesPainter::ReleaseGraphicsResources(vtkWindow* win) { if (this->LastRenderWindow == win) { if(this->FragmentShader!=0) { this->FragmentShader->ReleaseGraphicsResources(); this->FragmentShader->Delete(); this->FragmentShader=0; } if (this->Program) { this->Program->ReleaseGraphicsResources(); this->Program->Delete(); this->Program = 0; } this->LastRenderWindow = 0; } this->Superclass::ReleaseGraphicsResources(win); } //----------------------------------------------------------------------------- void vtkKWEIlluminatedLinesPainter::ProcessInformation(vtkInformation* info) { if (info->Has(vtkKWEIlluminatedLinesPainter::ENABLE())) { this->SetEnable(info->Get(vtkKWEIlluminatedLinesPainter::ENABLE())); } else { this->SetEnable(1); } this->Superclass::ProcessInformation(info); } //----------------------------------------------------------------------------- bool vtkKWEIlluminatedLinesPainter::IsSupported(vtkRenderWindow* renWin) { return vtkShaderProgram2::IsSupported( static_cast(renWin)); } //----------------------------------------------------------------------------- void vtkKWEIlluminatedLinesPainter::PrepareForRendering(vtkRenderer* renderer, vtkActor* actor) { if (this->LastRenderWindow.GetPointer() != renderer->GetRenderWindow()) { vtkSmartPointer lastWindow = this->LastRenderWindow.GetPointer(); this->ReleaseGraphicsResources(lastWindow); } if (!this->LastRenderWindow) { vtkOpenGLRenderWindow* renWin = vtkOpenGLRenderWindow::SafeDownCast( renderer->GetRenderWindow()); this->LastRenderWindow = renWin; vtkOpenGLExtensionManager* mgr = renWin->GetExtensionManager(); if (mgr->LoadSupportedExtension("GL_VERSION_1_3")) { this->Program = vtkShaderProgram2::New(); this->Program->SetContext(static_cast(renderer->GetRenderWindow())); vtkShader2 *s1=vtkShader2::New(); s1->SetType(VTK_SHADER_TYPE_VERTEX); s1->SetSourceCode(vtkKWEIlluminatedLinesPainter_vs); s1->SetContext(this->Program->GetContext()); this->Program->GetShaders()->AddItem(s1); s1->Delete(); vtkShader2 *s2=vtkShader2::New(); s2->SetType(VTK_SHADER_TYPE_FRAGMENT); s2->SetSourceCode(vtkKWEIlluminatedLinesPainter_fs); s2->SetContext(this->Program->GetContext()); this->Program->GetShaders()->AddItem(s2); this->FragmentShader=s2; #if 0 this->Program->Build(); if(this->Program->GetLastBuildStatus()!=VTK_SHADER_PROGRAM2_LINK_SUCCEEDED) { vtkErrorMacro("Program bind failed."); // return 0; } int value=0; this->Program->GetUniformVariables()->SetUniformi("tex",1,&value); value=1; this->Program->GetUniformVariables()->SetUniformi("uMode",1,&value); this->Program->Use(); if(!this->Program->IsValid()) { vtkErrorMacro(<<" validation of the program failed: "<Program->GetLastValidateLog()); } this->Program->Restore(); cout << "done" << endl; #endif } else { vtkErrorMacro("OpenGL 1.3 support is required."); } } this->Superclass::PrepareForRendering(renderer, actor); } template inline void DirectionVector(const T p1[3], const T p2[3], T vector[3]) { vector[0] = static_cast(p2[0] - p1[0]); vector[1] = static_cast(p2[1] - p1[1]); vector[2] = static_cast(p2[2] - p1[2]); } inline void sendTCoords(int type, const void* ptr, unsigned long offset) { switch (type) { case VTK_SHORT: vtkgl::MultiTexCoord3sv(vtkgl::TEXTURE1, static_cast(ptr)+offset); break; case VTK_INT: vtkgl::MultiTexCoord3iv(vtkgl::TEXTURE1, static_cast(ptr)+offset); break; case VTK_FLOAT: vtkgl::MultiTexCoord3fv(vtkgl::TEXTURE1, static_cast(ptr)+offset); break; case VTK_DOUBLE: vtkgl::MultiTexCoord3dv(vtkgl::TEXTURE1, static_cast(ptr)+offset); break; } } template void sendPrevTCoords(int ptype, T* points, vtkIdType *ptId) { const T* cur = static_cast(points) + (3**ptId); const T* next = static_cast(points) +(3**(ptId+1)); T prev[3]; ::DirectionVector(next, cur, prev); prev[0] = static_cast(cur[0] + prev[0]); prev[1] = static_cast(cur[1] + prev[1]); prev[2] = static_cast(cur[2] + prev[2]); sendTCoords(ptype, prev, 0); } inline void sendPrevTCoords(int ptype, void* points, vtkIdType *ptIds) { switch (ptype) { case VTK_SHORT: sendPrevTCoords(ptype, static_cast(points), ptIds); break; case VTK_INT: sendPrevTCoords(ptype, static_cast(points), ptIds); break; case VTK_FLOAT: sendPrevTCoords(ptype, static_cast(points), ptIds); break; case VTK_DOUBLE: sendPrevTCoords(ptype, static_cast(points), ptIds); break; } } //----------------------------------------------------------------------------- // We need to put in the previous(or next) point as the tcoord, so that the // shader program can compute tangents. #define vtkDrawPrimsMacro(prim,glVertFuncs,glInitFuncs) \ { \ vtkIdType nPts; unsigned short count = 0; \ glInitFuncs \ while (ptIds < endPtIds) \ { \ nPts = *ptIds; \ ++ptIds; \ if (nPts == 0) \ { \ continue; \ } \ device->BeginPrimitive(prim);\ if (nPts < 2)\ { \ sendTCoords(ptype, points, 3**ptIds); \ abort(); \ } \ else \ { \ sendPrevTCoords(ptype, points, ptIds);\ } \ glVertFuncs \ ++ptIds; \ --nPts; \ while (nPts > 0) \ { \ sendTCoords(ptype, points, 3*(*ptIds-1));\ glVertFuncs \ ++ptIds; \ --nPts; \ } \ device->EndPrimitive();\ if (++count == 10000) \ { \ cellNum += 10000; \ count = 0; \ this->UpdateProgress(static_cast(cellNum-cellNumStart)/static_cast(totalCells)); \ if (ren->GetRenderWindow()->CheckAbortStatus()) \ { \ break; \ } \ } \ } \ cellNum += count; \ } //----------------------------------------------------------------------------- int vtkKWEIlluminatedLinesPainter::RenderPrimitive(unsigned long idx, vtkDataArray* n, vtkUnsignedCharArray* c, vtkDataArray* t, vtkRenderer* ren) { if (!this->Enable || !this->Program) { return this->Superclass::RenderPrimitive(idx, n, c, t, ren); } vtkPolyData* pd = this->GetInputAsPolyData(); vtkPoints* p = pd->GetPoints(); vtkCellArray* ca = (this->RenderPolys)? pd->GetPolys() : pd->GetLines(); vtkIdType cellNum = pd->GetVerts()->GetNumberOfCells(); vtkIdType cellNumStart = cellNum; vtkIdType totalCells = ca->GetNumberOfCells(); vtkPainterDeviceAdapter* device = ren->GetRenderWindow()-> GetPainterDeviceAdapter(); void *points = p->GetVoidPointer(0); void *tcoords = 0; unsigned char *colors = 0; if (ca->GetNumberOfCells() == 0) { return 1; } if (t) { tcoords = t->GetVoidPointer(0); } if (c) { colors = c->GetPointer(0); } vtkIdType *ptIds = ca->GetPointer(); vtkIdType *endPtIds = ptIds + ca->GetNumberOfConnectivityEntries(); int ptype = p->GetDataType(); int ttype = (t)? t->GetDataType() : 0; int tcomps = (t)? t->GetNumberOfComponents() : 0; int primitive = (this->RenderPolys)? VTK_TETRA : VTK_POLY_LINE; // since this painter does not deal with field colors specially, // we just ignore the flag. idx &= (~static_cast(VTK_PDM_FIELD_COLORS)); idx &= (~static_cast(VTK_PDM_NORMALS)); //::vtkUpdateLights(); vtkLightingHelper* lhelper = vtkLightingHelper::New(); lhelper->PrepareForRendering(); lhelper->Delete(); int mode = 0; if (glIsEnabled(GL_COLOR_MATERIAL)) { GLint colorMaterialParameter; glGetIntegerv(GL_COLOR_MATERIAL_PARAMETER, &colorMaterialParameter); switch (colorMaterialParameter) { case GL_AMBIENT: mode = 1; break; case GL_DIFFUSE: mode = 2; break; case GL_SPECULAR: mode = 3; break; case GL_AMBIENT_AND_DIFFUSE: mode = 4; break; case GL_EMISSION: mode = 5; break; } } int handled = 1; // draw all the elements, use fast path if available #if 1 if (t) { if(this->Program->GetShaders()->IsItemPresent(this->FragmentShader)==0) { this->Program->GetShaders()->AddItem(this->FragmentShader); } } else { int location= this->Program->GetShaders()->IsItemPresent(this->FragmentShader); if(location>0) { this->Program->GetShaders()->RemoveItem(location-1); } } #endif this->Program->Build(); if(this->Program->GetLastBuildStatus()!=VTK_SHADER_PROGRAM2_LINK_SUCCEEDED) { vtkErrorMacro("Program bind failed."); return 0; } int value=0; this->Program->GetUniformVariables()->SetUniformi("tex",1,&value); value=mode; this->Program->GetUniformVariables()->SetUniformi("uMode",1,&value); this->Program->Use(); if(!this->Program->IsValid()) { vtkErrorMacro(<<" validation of the program failed: "<Program->GetLastValidateLog()); } switch (idx) { case 0: vtkDrawPrimsMacro(primitive, device->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3, ptype, points, 3**ptIds);,;); break; case VTK_PDM_COLORS: vtkDrawPrimsMacro(primitive, device->SendAttribute(vtkPointData::SCALARS, 4, VTK_UNSIGNED_CHAR, colors + 4**ptIds); device->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3, ptype, points, 3**ptIds);,;); break; case VTK_PDM_COLORS | VTK_PDM_OPAQUE_COLORS: vtkDrawPrimsMacro(primitive, device->SendAttribute(vtkPointData::SCALARS, 3, VTK_UNSIGNED_CHAR, colors + 4**ptIds); device->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3, ptype, points, 3**ptIds);,;); break; case VTK_PDM_TCOORDS: vtkDrawPrimsMacro(primitive, device->SendAttribute(vtkPointData::TCOORDS, tcomps, ttype, tcoords, tcomps**ptIds); device->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3, ptype, points, 3**ptIds);,;); break; default: handled = 0; // let the delegate painter handle this call. vtkErrorMacro("Case not handled. Illumination disabled."); } this->Program->Restore(); return handled; } //----------------------------------------------------------------------------- void vtkKWEIlluminatedLinesPainter::UpdateMapper(vtkPainterPolyDataMapper* mapper) { vtkPainter* painter = mapper->GetPainter(); vtkChooserPainter* chooser = vtkChooserPainter::SafeDownCast(painter); while (painter && !chooser) { painter = painter->GetDelegatePainter(); chooser = vtkChooserPainter::SafeDownCast(painter); } if (chooser) { vtkKWEIlluminatedLinesPainter* lines = vtkKWEIlluminatedLinesPainter::New(); chooser->SetLinePainter(lines); chooser->UseLinesPainterForWireframesOn(); lines->Delete(); } } //----------------------------------------------------------------------------- void vtkKWEIlluminatedLinesPainter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } vtkedge-0.2.0~20110819/Common/0000755000175000017500000000000011630434664015277 5ustar mathieumathieuvtkedge-0.2.0~20110819/Common/vtkKWEDataArrayStreamer.h0000644000175000017500000000777011363410610022116 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEDataArrayStreamer // .SECTION Description // Compute 2D texture image extent to transfer any data array as 2D image // chunks to GPU memory. It is also used to transfer back 2D texture chunk // as part of a data array. // .SECTION See Also // Used by the vtkKWEGPUArrayCalculator. #ifndef __vtkKWEDataArrayStreamer_h #define __vtkKWEDataArrayStreamer_h #include "vtkObject.h" #include "VTKEdgeConfigure.h" // include configuration header class VTKEdge_COMMON_EXPORT vtkKWEDataArrayStreamer : public vtkObject { public: static vtkKWEDataArrayStreamer *New(); vtkTypeRevisionMacro(vtkKWEDataArrayStreamer,vtkObject); void PrintSelf(ostream &os,vtkIndent indent); // Description: // Data array to split. Initial value is 0. vtkSetMacro(NumberOfTuples, vtkIdType); vtkGetMacro(NumberOfTuples, vtkIdType); // Description: // Maximum size of any dimension of a 3D texture. Initial value is 16, // the minimal value of the OpenGL specifications. vtkSetMacro(Max3DTextureSize,int); vtkGetMacro(Max3DTextureSize,int); // Description: // Maximum size of any dimension of a 1D or 2D texture. Initial value is 64, // the minimal value of the OpenGL specifications. vtkSetMacro(MaxTextureSize,int); vtkGetMacro(MaxTextureSize,int); // Description: // User-defined maximum size in bytes of a texture in GPU memory. // Initial value is 134217728 bytes (128*2^20=128Mb). // In a 32-bit build, this ivar can encode up to 4GB. // A null value means no limit. vtkSetMacro(MaxTextureMemorySizeInBytes,vtkIdType); vtkGetMacro(MaxTextureMemorySizeInBytes,vtkIdType); // Description: // Size of a tuple in bytes (number of components*size of type). // If the streamer is used by several dataarray at the same time, // the user should set its value to the maximum tuple size. // Initial value is 1. vtkSetMacro(TupleSize,int); vtkGetMacro(TupleSize,int); // Description: // User-defined maximum number of tuples per block. If 0, this value is // ignored. Initial value is 0. vtkSetMacro(MaxNumberOfTuplesPerBlock,vtkIdType); vtkGetMacro(MaxNumberOfTuplesPerBlock,vtkIdType); // Description: // Place the cursor on the first chunk, if any. void Begin(); // Description: // Is the iteration over? bool IsDone(); // Description: // Go the next chunk, if any. // \pre not_done: !IsDone() void Next(); // Description: // Number of colums and number of rows of the current image chunk. // \pre not_done: !IsDone() vtkGetVector2Macro(ChunkDimensions,vtkIdType); // Description: // Current starting tuple position in the data array. // \pre not_done: !IsDone() vtkGetMacro(Cursor,vtkIdType); //BTX protected: vtkKWEDataArrayStreamer(); ~vtkKWEDataArrayStreamer(); void UpdateChunkDimensions(); vtkIdType NumberOfTuples; int Max3DTextureSize; int MaxTextureSize; vtkIdType MaxTextureMemorySizeInBytes; int TupleSize; vtkIdType MaxNumberOfTuplesPerBlock; vtkIdType ChunkDimensions[2]; vtkIdType Cursor; vtkIdType Step; vtkIdType Stage2Cursor; vtkIdType Stage2Step; vtkIdType Stage3Cursor; vtkIdType Stage3Step; vtkIdType Stage2NumberOfRows; private: vtkKWEDataArrayStreamer(const vtkKWEDataArrayStreamer&); // Not implemented. void operator=(const vtkKWEDataArrayStreamer&); // Not implemented. //ETX }; #endif vtkedge-0.2.0~20110819/Common/vtkKWEFunctionToGLSL.h0000644000175000017500000001315611363410610021310 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEFunctionToGLSL - Parse a mathematical expression and generate a // GLSL source code string. // .SECTION Description // vtkKWEFunctionToGLSL parses a mathematical expression conformed to the // syntax parsed by vtkFunctionParser. However, instead of evaluating a value by // executing the bytecode, it uses the bytecode to generate a GLSL source code // used by vtkKWEGPUArrayCalculator. // // The functions that this array calculator understands is: //
// standard operations: + - * / ^ .
// access vector components: iHat, jHat, kHat
// abs
// acos
// asin
// atan
// ceil
// cos
// cosh
// exp
// floor
// log
// mag
// min
// max
// norm
// sign
// sin
// sinh
// sqrt
// tan
// tanh
// 
// Note that some of these operations work on scalars, some on vectors, and some on // both (e.g., you can multiply a scalar times a vector). The operations are performed // tuple-wise (i.e., tuple-by-tuple). The user must specify which arrays to use as // vectors and/or scalars, and the name of the output data array. // // .SECTION See Also // vtkFunctionParser vtkKWEGPUArrayCalculator. #ifndef __vtkKWEFunctionToGLSL_h #define __vtkKWEFunctionToGLSL_h #include "vtkFunctionParser.h" #include "VTKEdgeConfigure.h" // include configuration header class vtkStdString; class vtkOStrStreamWrapper; class VTKEdge_COMMON_EXPORT vtkKWEFunctionToGLSL : public vtkFunctionParser { public: vtkTypeRevisionMacro(vtkKWEFunctionToGLSL,vtkFunctionParser); void PrintSelf(ostream& os, vtkIndent indent); static vtkKWEFunctionToGLSL *New(); // Description: // Value modified by GenerateGLSL(). virtual bool GetParseStatus(); // Description: // Generate GLSL source code in GLSLCode. // Update ParseStatus. virtual void GenerateGLSL(); // Description: // Return the dimension of the result of the expression. // \pre valid_expression: GetParseStatus() // \post valid_result: result==1 || result==3 virtual int GetResultDimension(); // Description: // Return the GLSLCode generated by GenerateGLSL() in a string. // \pre valid_expression: GetParseStatus() virtual vtkStdString *GetGLSLCode(); // Description: // Return if a given scalar data array is used in the function expression. // \pre valid_expression: GetParseStatus() // \pre valid_index:index>=0 && indexNumberOfScalarVariables virtual bool GetScalarIsUsed(int index); // Description: // Return if a given vector data array is used in the function expression. // \pre valid_expression: GetParseStatus() // \pre valid_index:index>=0 && indexNumberOfVectorVariables virtual bool GetVectorIsUsed(int index); // Description: // Return the GLSL name attached to the a given scalar data array. // \pre valid_expression: GetParseStatus() // \pre valid_index:index>=0 && indexNumberOfScalarVariables // \pre used_scalar: this->GetScalarIsUsed(index) vtkStdString *GetGLSLScalarName(int index); // Description: // Return the GLSL name attached to the a given vector data array. // \pre valid_expression: GetParseStatus() // \pre valid_index:index>=0 && indexNumberOfVectorVariables // \pre used_vector: this->GetVectorIsUsed(index) vtkStdString *GetGLSLVectorName(int index); // Description: // Return the number of scalar variables used in the expression. // \pre valid_expression: GetParseStatus() // \post valid_result: result>=0 && result<=GetNumberOfScalarVariables() virtual int GetNumberOfUsedScalarVariables(); // Description: // Return the number of vector variables used in the expression. // \pre valid_expression: GetParseStatus() // \post valid_result: result>=0 && result<=GetNumberOfVectorVariables() virtual int GetNumberOfUsedVectorVariables(); protected: // Description: // Default constructor. The function expression is a null pointer. // The GLSLCode is a null pointer. ParseStatus is false. vtkKWEFunctionToGLSL(); // Description: // Destructor. ~vtkKWEFunctionToGLSL(); // Description: // Allocate string stack. // \pre void: this->StringStack==0 // \pre positive_size: this->StackSize>0 // \post allocated: this->StringStack!=0 void AllocateStringStack(); // Description: // Delete string stack. void DeleteStringStack(); // Description: // Build the name of the variable for GLSL. Only load the variables used // in the function expression. // \pre parsed: bytcode exists and is valid void BuildGLSLVariableNames(); bool ParseStatus; vtkStdString *GLSLCode; vtkStdString *StringStack; int *PrecedenceStack; bool *ScalarIsUsed; int ScalarIsUsedSize; vtkStdString *GLSLScalarNames; int NumberOfUsedScalarVariables; bool *VectorIsUsed; int VectorIsUsedSize; vtkStdString *GLSLVectorNames; int NumberOfUsedVectorVariables; int ResultDimension; // 1 or 3 private: vtkKWEFunctionToGLSL(const vtkKWEFunctionToGLSL&); // Not implemented. void operator=(const vtkKWEFunctionToGLSL&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Common/vtkKWEInformationKeyMap.h0000644000175000017500000000500111363410610022120 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEInformationKeyMap - Map from string to information key instances // .SECTION Description // This class is used to access information keys given a string in the // form KeyLocation.KeyName. For example: vtkDataObject.DATA_OBJECT // (note the lack of () at the end). // You have to manually register the keys in the map before they can // be accessed. // Note that all of the key instances are stored using smart pointers. // Make sure to call RemoveAllKeys() before exit to avoid leak warnings // from vtkDebugLeaks. #ifndef __vtkKWEInformationKeyMap_h #define __vtkKWEInformationKeyMap_h #include "vtkObject.h" #include "VTKEdgeConfigure.h" // include configuration header #include //BTX class vtkInformationKey; //ETX class VTKEdge_COMMON_EXPORT vtkKWEInformationKeyMap : public vtkObject { public: static vtkKWEInformationKeyMap *New(); vtkTypeRevisionMacro(vtkKWEInformationKeyMap,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Register a key with the map. The key will be KeyLocation::KeyName. static void RegisterKey(vtkInformationKey* key); // Description: // Lookup a key instance registered with the map using its location // and name. static vtkInformationKey* FindKey(const char* name); // Description: // Given a key instance, returns its name used to store it in the // map. Implemented as: // key->GetLocation() + "." + key->GetName() static vtkstd::string GetFullName(vtkInformationKey* key); // Description: // Removes all keys from the map. static void RemoveAllKeys(); protected: vtkKWEInformationKeyMap(); ~vtkKWEInformationKeyMap(); private: vtkKWEInformationKeyMap(const vtkKWEInformationKeyMap&); // Not implemented. void operator=(const vtkKWEInformationKeyMap&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Common/vtkKWEUUID.cxx0000644000175000017500000003731511363410610017662 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // // Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de // l'Image). All rights reserved. See Doc/License.txt or // http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notices for more information. // //============================================================================= #include "vtkKWEUUID.h" #include "VTKEdgeUUIDConfigure.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include #if defined(_WIN32) || defined(__CYGWIN__) # define HAVE_UUIDCREATE # include #elif defined(SYSTEM_UUID_FOUND) # define HAVE_UUID_GENERATE # include "uuid/uuid.h" #endif // For GetMACAddress #ifdef _WIN32 # include # include #else # include # include # include # include #endif #ifdef CMAKE_HAVE_SYS_IOCTL_H # include // For SIOCGIFCONF on Linux #endif #ifdef CMAKE_HAVE_SYS_SOCKET_H # include #endif #ifdef CMAKE_HAVE_SYS_SOCKIO_H # include // For SIOCGIFCONF on SunOS #endif #ifdef CMAKE_HAVE_NET_IF_H # include #endif #ifdef CMAKE_HAVE_NETINET_IN_H # include //For IPPROTO_IP #endif #ifdef CMAKE_HAVE_NET_IF_DL_H # include #endif #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun) // This is absolutely necessary on SunOS # include #endif vtkCxxRevisionMacro(vtkKWEUUID, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEUUID); //----------------------------------------------------------------------------- void vtkKWEUUID::ConstructUUID(unsigned char uuid[16]) { // set the random seed the 1st time static bool firstTime = true; if (firstTime) { vtkMath::RandomSeed( static_cast(vtksys::SystemTools::GetTime()) ); firstTime = false; } size_t offset = 0; unsigned char macAddress[6]; // if successful, set 1st 3 bytes of the uuid to be the last 3 bytes of the // MAC address. Not using the 1st 3 bytes because I've read concern about // having uuid that identifies the machine it was created on. At least by // eliminating the 1st 3 bytes, the device manufacturer is now hidden if (vtkKWEUUID::GetMACAddress(macAddress) != -1) { uuid[0] = macAddress[3]; uuid[1] = macAddress[4]; uuid[2] = macAddress[5]; offset = 3; } // up to 3 bytes from the hostname (would like something other than just to // rely on the random number generator)... for grins, let's take it from the // end of the hostname where, if there are several machines of similar name // at a site, there is likely (?) to be a number at the end char hostName[256]; if (gethostname(hostName, sizeof(hostName)) != -1) { hostName[sizeof(hostName) - 1] = '\0'; // just to be sure int bytesAdded = 0, strOffset = static_cast(strlen(hostName)) - 1; int msb, lsb; while(bytesAdded++ < 3 && strOffset > 0) { // not perfect (not all equally likely), but at least all possible msb = hostName[strOffset--] % 16; lsb = hostName[strOffset--] % 16; uuid[offset++] = static_cast((msb << 4) + lsb); } } // generate remaining bytes for the uuid from random # generator while(offset < 16) { double randomVal = vtkMath::Random(); size_t bytesToCopy = sizeof(double) >> 1; // only use have the random # if (bytesToCopy > 16 - offset) { bytesToCopy = 16 - offset; } memcpy(uuid + offset, &randomVal, bytesToCopy); offset += bytesToCopy; } } //----------------------------------------------------------------------------- void vtkKWEUUID::ConvertBinaryUUIDToString(unsigned char *uuid, vtkstd::string &uuidString) { char buffer[8]; // why more than 3? uuidString.clear(); for (int i = 0; i < 16; i++) { sprintf(buffer, "%.2x", uuid[i]); uuidString += buffer; if (i == 3 || i == 5 || i == 7 || i == 9) { uuidString += "-"; } } } //----------------------------------------------------------------------------- int vtkKWEUUID::GenerateUUID(unsigned char uuid[16]) { #ifdef HAVE_UUIDCREATE if (FAILED(UuidCreate((GUID *)uuid))) { return -1; } #elif defined(HAVE_UUID_GENERATE) uuid_t g; uuid_generate(g); memcpy(uuid, g, sizeof(uuid_t)); #else uuid[0] = 0; // so won't complain about being unused return -1; #endif return 0; } //----------------------------------------------------------------------------- void vtkKWEUUID::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //----------------------------------------------------------------------------- int vtkKWEUUID::GetMACAddress(unsigned char addr[6]) { // This code is the result of a long internet search to find something // as compact as possible (not OS independant). We only have to separate // 3 OS: Win32, SunOS and 'real' POSIX // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be // http://bdn.borland.com/article/0,1410,26040,00.html int stat = vtkKWEUUID::GetMacAddrSys(addr); if (stat != 0) { vtkGenericWarningMacro("Problem in finding the MAC Address"); return -1; } return 0; } #ifdef __sgi static int SGIGetMacAddress(unsigned char *addr) { FILE *f = popen("/etc/nvram eaddr","r"); if(f == 0) { return -1; } unsigned int x[6]; if(fscanf(f,"%02x:%02x:%02x:%02x:%02x:%02x", x,x+1,x+2,x+3,x+4,x+5) != 6) { pclose(f); return -1; } for(unsigned int i = 0; i < 6; i++) { addr[i] = static_cast(x[i]); } return 0; } #endif #ifdef _WIN32 typedef BOOL(WINAPI * pSnmpExtensionInit) ( IN DWORD dwTimeZeroReference, OUT HANDLE * hPollForTrapEvent, OUT AsnObjectIdentifier * supportedView); typedef BOOL(WINAPI * pSnmpExtensionTrap) ( OUT AsnObjectIdentifier * enterprise, OUT AsnInteger * genericTrap, OUT AsnInteger * specificTrap, OUT AsnTimeticks * timeStamp, OUT RFC1157VarBindList * variableBindings); typedef BOOL(WINAPI * pSnmpExtensionQuery) ( IN BYTE requestType, IN OUT RFC1157VarBindList * variableBindings, OUT AsnInteger * errorStatus, OUT AsnInteger * errorIndex); typedef BOOL(WINAPI * pSnmpExtensionInitEx) ( OUT AsnObjectIdentifier * supportedView); #endif //----------------------------------------------------------------------------- int vtkKWEUUID::GetMacAddrSys(unsigned char *addr) { #ifdef _WIN32 WSADATA WinsockData; if ( (WSAStartup(MAKEWORD(2, 0), &WinsockData)) != 0 ) { std::cerr << "in Get MAC Adress (internal) : This program requires Winsock 2.x!" << std::endl; return -1; } HANDLE PollForTrapEvent; AsnObjectIdentifier SupportedView; UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 }; UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 }; UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 }; AsnObjectIdentifier MIB_ifMACEntAddr = { sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr }; AsnObjectIdentifier MIB_ifEntryType = { sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType }; AsnObjectIdentifier MIB_ifEntryNum = { sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum }; RFC1157VarBindList varBindList; RFC1157VarBind varBind[2]; AsnInteger errorStatus; AsnInteger errorIndex; AsnObjectIdentifier MIB_NULL = { 0, 0 }; int ret; int dtmp; int j = 0; // Load the SNMP dll and get the addresses of the functions necessary HINSTANCE m_hInst = LoadLibrary("inetmib1.dll"); if (m_hInst < (HINSTANCE) HINSTANCE_ERROR) { return -1; } pSnmpExtensionInit m_Init = (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit"); pSnmpExtensionQuery m_Query = (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery"); m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView); /* Initialize the variable list to be retrieved by m_Query */ varBindList.list = varBind; varBind[0].name = MIB_NULL; varBind[1].name = MIB_NULL; // Copy in the OID to find the number of entries in the // Inteface table varBindList.len = 1; // Only retrieving one item SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum); m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus, &errorIndex); // printf("# of adapters in this system : %i\n", // varBind[0].value.asnValue.number); varBindList.len = 2; // Copy in the OID of ifType, the type of interface SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType); // Copy in the OID of ifPhysAddress, the address SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr); do { // Submit the query. Responses will be loaded into varBindList. // We can expect this call to succeed a # of times corresponding // to the # of adapters reported to be in the system ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus, &errorIndex); if (!ret) { ret = 1; } else { // Confirm that the proper type has been returned ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType, MIB_ifEntryType.idLength); } if (!ret) { j++; dtmp = varBind[0].value.asnValue.number; // Type 6 describes ethernet interfaces if (dtmp == 6) { // Confirm that we have an address here ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr, MIB_ifMACEntAddr.idLength); if ( !ret && varBind[1].value.asnValue.address.stream != NULL ) { if ( (varBind[1].value.asnValue.address.stream[0] == 0x44) && (varBind[1].value.asnValue.address.stream[1] == 0x45) && (varBind[1].value.asnValue.address.stream[2] == 0x53) && (varBind[1].value.asnValue.address.stream[3] == 0x54) && (varBind[1].value.asnValue.address.stream[4] == 0x00) ) { // Ignore all dial-up networking adapters std::cerr << "in Get MAC Adress (internal) : Interface #" << j << " is a DUN adapter\n"; continue; } if ( (varBind[1].value.asnValue.address.stream[0] == 0x00) && (varBind[1].value.asnValue.address.stream[1] == 0x00) && (varBind[1].value.asnValue.address.stream[2] == 0x00) && (varBind[1].value.asnValue.address.stream[3] == 0x00) && (varBind[1].value.asnValue.address.stream[4] == 0x00) && (varBind[1].value.asnValue.address.stream[5] == 0x00) ) { // Ignore NULL addresses returned by other network // interfaces std::cerr << "in Get MAC Adress (internal) : Interface #" << j << " is a NULL address\n"; continue; } memcpy( addr, varBind[1].value.asnValue.address.stream, 6); } } } } while (!ret); // Free the bindings SNMP_FreeVarBind(&varBind[0]); SNMP_FreeVarBind(&varBind[1]); return 0; #endif //Win32 version #ifdef __sgi return SGIGetMacAddress(addr); #endif // __sgi // implementation for POSIX system #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun) //The POSIX version is broken anyway on Solaris, plus would require full //root power struct arpreq parpreq; struct sockaddr_in *psa; struct hostent *phost; char hostname[MAXHOSTNAMELEN]; char **paddrs; int sock, status=0; if (gethostname(hostname, MAXHOSTNAMELEN) != 0 ) { perror("in Get MAC Adress (internal) : gethostname"); return -1; } phost = gethostbyname(hostname); paddrs = phost->h_addr_list; sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock == -1 ) { perror("in Get MAC Adress (internal) : sock"); return -1; } memset(&parpreq, 0, sizeof(struct arpreq)); psa = static_cast(&parpreq.arp_pa); memset(psa, 0, sizeof(struct sockaddr_in)); psa->sin_family = AF_INET; memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr)); status = ioctl(sock, SIOCGARP, &parpreq); if (status == -1 ) { perror("in Get MAC Adress (internal) : SIOCGARP"); return -1; } memcpy(addr, parpreq.arp_ha.sa_data, 6); return 0; #elif !defined(_WIN32) # ifdef CMAKE_HAVE_NET_IF_H int sd; struct ifreq ifr, *ifrp; struct ifconf ifc; char buf[1024]; int n, i; unsigned char *a; # if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR)) struct sockaddr_dl *sdlp; # endif // // BSD 4.4 defines the size of an ifreq to be // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len // However, under earlier systems, sa_len isn't present, so the size is // just sizeof(struct ifreq) // We should investigate the use of SIZEOF_ADDR_IFREQ // # ifdef HAVE_SA_LEN # ifndef max # define max(a,b) ((a) > (b) ? (a) : (b)) # endif # define ifreq_size(i) max(sizeof(struct ifreq),\ sizeof((i).ifr_name)+(i).ifr_addr.sa_len) # else # define ifreq_size(i) sizeof(struct ifreq) # endif // HAVE_SA_LEN if ( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 ) { return -1; } memset(buf, 0, sizeof(buf)); ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; if (ioctl (sd, SIOCGIFCONF, reinterpret_cast(&ifc)) < 0) { close(sd); return -1; } n = ifc.ifc_len; for (i = 0; i < n; i+= ifreq_size(*ifrp) ) { ifrp = reinterpret_cast(static_cast(ifc.ifc_buf)+i); strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ); # ifdef SIOCGIFHWADDR if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0) { continue; } a = reinterpret_cast(&ifr.ifr_hwaddr.sa_data); # else # ifdef SIOCGENADDR // In theory this call should also work on Sun Solaris, but apparently // SIOCGENADDR is not implemented properly thus the call // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2 // (No such file or directory) // Furthermore the DLAPI seems to require full root access if (ioctl(sd, SIOCGENADDR, &ifr) < 0) { continue; } a = static_cast<(unsigned char *>(ifr.ifr_enaddr); # else # ifdef AF_LINK sdlp = reinterpret_cast(&ifrp->ifr_addr); if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6)) continue; a = reinterpret_cast(&sdlp->sdl_data[sdlp->sdl_nlen]); # else perror("in Get MAC Adress (internal) : No way to access hardware"); close(sd); return -1; # endif // AF_LINK # endif // SIOCGENADDR # endif // SIOCGIFHWADDR if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue; if (addr) { memcpy(addr, a, 6); close(sd); return 0; } } close(sd); # endif // Not implemented platforms (or no cable !) perror("in Get MAC Adress (internal) : There was a configuration problem (or no cable !) on your platform"); memset(addr,0,6); return -1; #endif //__sun } vtkedge-0.2.0~20110819/Common/CMakeLists.txt0000644000175000017500000001400211374311375020032 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Set of basic source files # ----------------------------------------------------------------------------- set(KIT_SRCS vtkKWEDataArrayStreamer.cxx vtkKWEFunctionToGLSL.cxx vtkKWEUUID.cxx vtkKWEInformationKeyMap.cxx ) # ----------------------------------------------------------------------------- # List the kits from VTK that are needed by this project # Need filtering for now because older VTK has vtkInformationKey in # vtkFiltering, not vtkCommon. Specifically trying to support # VolView build which still uses an older version of VTK # ----------------------------------------------------------------------------- set(KIT_LIBS vtkCommon vtkFiltering ) # ----------------------------------------------------------------------------- # UUID support # ----------------------------------------------------------------------------- find_package(UUID) if(UUID_FOUND) set(SYSTEM_UUID_FOUND 1) set(KIT_LIBS ${KIT_LIBS} ${UUID_LIBRARIES}) endif(UUID_FOUND) if(WIN32) if (NOT BORLAND) # rpcrt4 -> UuidCreate #snmpapi -> getting MAC address set(KIT_LIBS ${KIT_LIBS} rpcrt4 snmpapi) endif(NOT BORLAND) endif(WIN32) # Check if header file exists and add it to the list. include (${CMAKE_ROOT}/Modules/CheckIncludeFiles.cmake) MACRO(CHECK_INCLUDE_FILE_CONCAT FILE VARIABLE) CHECK_INCLUDE_FILES("${KWECommon_INCLUDES};${FILE}" ${VARIABLE}) if(${VARIABLE}) set(KWECommon_INCLUDES ${KWECommon_INCLUDES} ${FILE}) endif(${VARIABLE}) ENDMACRO(CHECK_INCLUDE_FILE_CONCAT) # Need these headers for GetMacAddress in vtkKWEUUID # Tricky as you need to figure out the proper order to test the inclusion of files CHECK_INCLUDE_FILE_CONCAT("unistd.h" CMAKE_HAVE_UNISTD_H) CHECK_INCLUDE_FILE_CONCAT("stdlib.h" CMAKE_HAVE_STDLIB_H) if(UNIX) #Avoid polluting Win32 cmakecache CHECK_INCLUDE_FILE_CONCAT("sys/ioctl.h" CMAKE_HAVE_SYS_IOCTL_H) CHECK_INCLUDE_FILE_CONCAT("sys/socket.h" CMAKE_HAVE_SYS_SOCKET_H) CHECK_INCLUDE_FILE_CONCAT("sys/sockio.h" CMAKE_HAVE_SYS_SOCKIO_H) CHECK_INCLUDE_FILE_CONCAT("net/if.h" CMAKE_HAVE_NET_IF_H) CHECK_INCLUDE_FILE_CONCAT("netinet/in.h" CMAKE_HAVE_NETINET_IN_H) CHECK_INCLUDE_FILE_CONCAT("net/if_dl.h" CMAKE_HAVE_NET_IF_DL_H) CHECK_INCLUDE_FILE_CONCAT("net/if_arp.h" CMAKE_HAVE_NET_IF_ARP_H) endif(UNIX) # Test if os defines a length for sockaddr # only doing the test when we have sys/socket if( ${CMAKE_HAVE_SYS_SOCKET_H} ) if("HAVE_SA_LEN" MATCHES "^HAVE_SA_LEN$") STRING(ASCII 35 POUND) FILE(WRITE ${PROJECT_BINARY_DIR}/CMakeTmp/kweCommonTestHAVESALEN.c "${POUND}include \n" "${POUND}include \n" "int main() { struct sockaddr sa; sa.sa_len = 0; }\n") message(STATUS "Checking if ifreq has a sa_len") TRY_COMPILE(HAVE_SA_LEN ${PROJECT_BINARY_DIR} ${PROJECT_BINARY_DIR}/CMakeTmp/kweCommonTestHAVESALEN.c OUTPUT_VARIABLE OUTPUT) if(HAVE_SA_LEN) message(STATUS "Checking if ifreq has a sa_len -- yes") set(HAVE_SA_LEN 1 CACHE INTERNAL "Support if ifreq has a sa_len") write_file(${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log "Determining if ifreq has a sa_len" "passed with the following output:\n" "${OUTPUT}\n" APPEND) else(HAVE_SA_LEN) message(STATUS "Checking if ifreq has a sa_len -- no") set(HAVE_SA_LEN 0 CACHE INTERNAL "Support if ifreq has a sa_len") write_file(${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "Determining if ifreq has a sa_len" "failed with the following output:\n" "${OUTPUT}\n" APPEND) endif(HAVE_SA_LEN) endif("HAVE_SA_LEN" MATCHES "^HAVE_SA_LEN$") endif( ${CMAKE_HAVE_SYS_SOCKET_H} ) # The configured header file used to pass CMake settings to the source code. configure_file( "${PROJECT_SOURCE_DIR}/Common/VTKEdgeUUIDConfigure.h.in" "${PROJECT_BINARY_DIR}/VTKEdgeUUIDConfigure.h" ) # ----------------------------------------------------------------------------- # Create the library # ----------------------------------------------------------------------------- add_library(vtkKWECommon ${KIT_SRCS}) target_link_libraries(vtkKWECommon ${KIT_LIBS}) # ----------------------------------------------------------------------------- # Testing # ----------------------------------------------------------------------------- #if(BUILD_TESTING) # add_subdirectory(Testing) #endif(BUILD_TESTING) # ----------------------------------------------------------------------------- # Installation # ----------------------------------------------------------------------------- if(NOT VTKEdge_INSTALL_NO_LIBRARIES) install_targets( ${VTKEdge_INSTALL_LIB_DIR} RUNTIME_DIRECTORY ${VTKEdge_INSTALL_BIN_DIR} vtkKWECommon ) endif(NOT VTKEdge_INSTALL_NO_LIBRARIES) if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_INCLUDE_DIR} .h ${KIT_SRCS}) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) # ----------------------------------------------------------------------------- # This make it easy for other projects to get the list of files etc. in this # kit. # ----------------------------------------------------------------------------- include(${VTK_CMAKE_DIR}/vtkExportKit.cmake) vtk_export_kit2("KWECommon" "KWECOMMON" ${CMAKE_CURRENT_BINARY_DIR} "${KIT_SRCS}") vtkedge-0.2.0~20110819/Common/vtkKWEUUID.h0000644000175000017500000000640211363410610017300 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // // Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de // l'Image). All rights reserved. See Doc/License.txt or // http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notices for more information. // //============================================================================= // .NAME vtkKWEUUID - (Static) Class for generating/constructing UUIDs // .SECTION Description // This class provides ability to "generate" (using system/platform calls) a // UUID, as well as to "construct" a UUID from MAC address, hostname, and // random number generation. The main Generate/Construct methods returns the // uuid as binary, which can be converted to the 26 character string by calling // ConvertBinaryUUIDToString. // Note: The MAC address code comes from gdcm (see the copyright above). #ifndef __vtkKWEUUID_h #define __vtkKWEUUID_h #include "vtkObject.h" #include "VTKEdgeConfigure.h" // include configuration header class VTKEdge_COMMON_EXPORT vtkKWEUUID : public vtkObject { public: static vtkKWEUUID* New(); vtkTypeRevisionMacro(vtkKWEUUID, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Generate a (binary) UUID using system/platform method call. Note, it may // fail (return value -1), in which case you can call ConstructUUID. static int GenerateUUID(unsigned char uuid[16]); // Description: // Construct a (binary) UUID from MAC address (if can successfully acquire), // hostname, and random # generation. This fn is guaranteed to create an // "uuid" (a semi-unique number) based on random # generation, regardless of // whether the MAC address and/or hostname is obtained. static void ConstructUUID(unsigned char uuid[16]); // Description: // Convert a (16-byte) binary UUID to its string form (in hexadecimal): // XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX static void ConvertBinaryUUIDToString(unsigned char uuid[16], vtkstd::string &uuidString); // Description: // Get the 6-byte binary MAC address. Returns -1 on failure. static int GetMACAddress(unsigned char addr[6]); protected: vtkKWEUUID() {}; ~vtkKWEUUID() {}; private: vtkKWEUUID(const vtkKWEUUID&); // Not implemented. void operator=(const vtkKWEUUID&); // Not implemented. // the main (system specific) code for determining the MAC address static int GetMacAddrSys(unsigned char *addr); }; #endif vtkedge-0.2.0~20110819/Common/Testing/0000755000175000017500000000000011630434664016714 5ustar mathieumathieuvtkedge-0.2.0~20110819/Common/Testing/Cxx/0000755000175000017500000000000011630434664017456 5ustar mathieumathieuvtkedge-0.2.0~20110819/Common/Testing/Cxx/CMakeLists.txt0000755000175000017500000000416711363411147022223 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Name this kit - this will be used to form test executable names later # Then we'll add in tests with various data or kit dependencies to the # test executables # ----------------------------------------------------------------------------- set(KIT Common) set(TESTBASE ${PROJECT_NAME}${KIT}) # ----------------------------------------------------------------------------- # First, list all the tests that either use no data, or only data from the # VTKEdge data directory (which always exists since it is part of the # VTKEdge repository). These will go into one test executable. # ----------------------------------------------------------------------------- set(MyTests ) create_test_sourcelist(Tests ${TESTBASE}CxxTests.cxx ${MyTests} EXTRA_INCLUDE vtkTestDriver.h ) add_executable(${TESTBASE}CxxTests ${Tests}) #install_targets(${VTKEdge_INSTALL_BIN_DIR} ${TESTBASE}CxxTests) target_link_libraries(${TESTBASE}CxxTests vtkKWECommon) set(TestsToRun ${Tests}) remove(TestsToRun ${TESTBASE}CxxTests.cxx) # Add all the executables foreach(test ${TestsToRun}) get_filename_component(TName ${test} NAME_WE) add_test(${TName} ${CXX_TEST_PATH}/${TESTBASE}CxxTests ${TName} -D ${PROJECT_SOURCE_DIR}/Data -T ${PROJECT_BINARY_DIR}/Testing/Temporary -V ${PROJECT_SOURCE_DIR}/Data/Baseline/${KIT}/${TName}.png ) endforeach(test) vtkedge-0.2.0~20110819/Common/Testing/Cxx/TestHeaderStyle.cxx0000644000175000017500000002107511363410610023244 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkTestUtilities.h" #include "VTKEdgeConfigure.h" #include "vtkDirectory.h" void CleanLine( char *line ) { while ( line[strlen(line)-1] == ' ' || line[strlen(line)-1] == '\n' ) { line[strlen(line)-1] = 0; } } int ProcessFile( const char *fileName, const char *newFileName ) { // cout << " Processing file " << fileName << endl; int status = 0; FILE *fp = fopen(fileName, "r"); FILE *newfp = fopen(newFileName, "w"); if ( !fp ) { cout << "Error opening file " << fileName << endl; return 1; } if ( !newfp ) { cout << "Error opening file " << fileName << endl; return 1; } char line[256]; const char *slashText[20] = {"//=============================================================================", "// This file is part of VTKEdge. See vtkedge.org for more information.", "//", "// Copyright (c) 2008 Kitware, Inc.", "//", "// VTKEdge may be used under the terms of the GNU General Public License", "// version 3 as published by the Free Software Foundation and appearing in", "// the file LICENSE.txt included in the top level directory of this source", "// code distribution. Alternatively you may (at your option) use any later", "// version of the GNU General Public License if such license has been", "// publicly approved by Kitware, Inc. (or its successors, if any).", "//", "// VTKEdge is distributed \"AS IS\" with NO WARRANTY OF ANY KIND, INCLUDING", "// THE WARRANTIES OF DESIGN, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR", "// PURPOSE. See LICENSE.txt for additional details.", "//", "// VTKEdge is available under alternative license terms. Please visit", "// vtkedge.org or contact us at kitware@kitware.com for further information.", "//", "//============================================================================="}; const char *slashTextNew[20] = {"//=============================================================================", "// This file is part of VTKEdge. See vtkedge.org for more information.", "//", "// Copyright (c) 2010 Kitware, Inc.", "//", "// VTKEdge may be used under the terms of the BSD License", "// Please see the file Copyright.txt in the root directory of", "// VTKEdge for further information.", "//", "// Alternatively, you may see: ", "//", "// http://www.vtkedge.org/vtkedge/project/license.html", "//", "//", "// For custom extensions, consulting services, or training for", "// this or any other Kitware supported open source project, please", "// contact Kitware at sales@kitware.com.", "//", "//", "//============================================================================="}; const char *hashText[20] = {"##=============================================================================", "## This file is part of VTKEdge. See vtkedge.org for more information.", "##", "## Copyright (c) 2008 Kitware, Inc.", "##", "## VTKEdge may be used under the terms of the GNU General Public License", "## version 3 as published by the Free Software Foundation and appearing in", "## the file LICENSE.txt included in the top level directory of this source", "## code distribution. Alternatively you may (at your option) use any later", "## version of the GNU General Public License if such license has been", "## publicly approved by Kitware, Inc. (or its successors, if any).", "##", "## VTKEdge is distributed \"AS IS\" with NO WARRANTY OF ANY KIND, INCLUDING", "## THE WARRANTIES OF DESIGN, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR", "## PURPOSE. See LICENSE.txt for additional details.", "##", "## VTKEdge is available under alternative license terms. Please visit", "## vtkedge.org or contact us at kitware@kitware.com for further information.", "##", "##============================================================================="}; const char *hashTextNew[20] = {"##=============================================================================", "## This file is part of VTKEdge. See vtkedge.org for more information.", "##", "## Copyright (c) 2010 Kitware, Inc.", "##", "## VTKEdge may be used under the terms of the BSD License", "## Please see the file Copyright.txt in the root directory of", "## VTKEdge for further information.", "##", "## Alternatively, you may see: ", "##", "## http://www.vtkedge.org/vtkedge/project/license.html", "##", "##", "## For custom extensions, consulting services, or training, please", "## this or any other Kitware supported open source project, please", "## contact Kitware at sales@kitware.com.", "##", "##", "##============================================================================="}; char *result=0; int i = 0; while ( result=fgets( line, 255, fp ) ) { CleanLine(line); if ( status==0 && i < 20 && line[0] == '/' ) { fputs( slashTextNew[i], newfp ); if ( strcmp(slashText[i], line) ) { cout << "Error at line " << i << " in file " << fileName << endl; cout << " correct: " << strlen(slashText[i]) << " " << slashText[i] << endl; cout << " found: " << strlen(line) << " " << line << endl; status = 1; break; } } else if ( status == 0 && i < 20 && line[0] == '#') { fputs( hashTextNew[i], newfp ); if ( strcmp(hashText[i], line) ) { cout << "Error at line " << i << " in file " << fileName << endl; cout << " correct: " << strlen(hashText[i]) << " " << hashText[i] << endl; cout << " found: " << strlen(line) << " " << line << endl; status = 1; break; } } else if ( i < 20 ) { status = 1; break; } else { fputs( line, newfp ); } fputs( "\n", newfp ); i++; } fclose(fp); fclose(newfp); return status; } int ProcessDirectory(const char *dirName) { cout << "Processing directory " << dirName << endl; int numFailures = 0; vtkDirectory *dir = vtkDirectory::New(); int opened = dir->Open(dirName); if (!opened) { cout << "Could not open directory: " << dirName << endl; dir->Delete(); return 1; } vtkIdType numFiles = dir->GetNumberOfFiles(); vtkIdType i; for ( i = 0; i < numFiles; i++ ) { if (strcmp(dir->GetFile(i), ".") == 0 || strcmp(dir->GetFile(i), "..") == 0 || strcmp(dir->GetFile(i), ".svn") == 0) { continue; } if (dir->GetFile(i)[strlen(dir->GetFile(i))-1] == '~' ) { continue; } char *fullName; size_t size = strlen(dir->GetFile(i)) + strlen(dirName) + 2; fullName = new char[size]; sprintf( fullName, "%s/%s", dirName, dir->GetFile(i) ); if (dir->FileIsDirectory(dir->GetFile(i))) { numFailures += ProcessDirectory(fullName); } else { char newFileName[512]; sprintf(newFileName, "%s.new", fullName ); int numFailuresBefore = numFailures; numFailures += ProcessFile(fullName, newFileName); if ( numFailuresBefore == numFailures ) { cout << "Attempting the rename" << newFileName << " " << fullName << endl; remove(fullName); dir->Rename(newFileName, fullName); } } delete [] fullName; } dir->Delete(); return numFailures; } int TestHeaderStyle(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) { int numFailures = 0; numFailures = ProcessDirectory(VTKEdge_SOURCE_DIR); if ( numFailures > 0 ) { cout << numFailures << " files failed header check." << endl; return 1; } return 0; } vtkedge-0.2.0~20110819/Common/Testing/CMakeLists.txt0000755000175000017500000000166011363410610021446 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Add the Cxx testing directory # ----------------------------------------------------------------------------- add_subdirectory(Cxx) vtkedge-0.2.0~20110819/Common/vtkKWEFunctionToGLSL.cxx0000644000175000017500000012316311363410610021663 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEFunctionToGLSL.h" #include "vtkStdString.h" #include "vtkObjectFactory.h" #include #include vtkCxxRevisionMacro(vtkKWEFunctionToGLSL, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEFunctionToGLSL); // GLSL Operator Precedence (from the GLSL spec). 1 is the highest, // 17 the lowest. // 1. parenthentical grouping // 2. array subscript, function/constructor call, field selector // 4. multiplicative // 5. additive // ---------------------------------------------------------------------------- // Description: // Value modified by GenerateGLSL(). bool vtkKWEFunctionToGLSL::GetParseStatus() { return this->ParseStatus; } // ---------------------------------------------------------------------------- // Description: // Allocate string stack. // \pre void: this->StringStack==0 // \pre positive_size: this->StackSize>0 // \post allocated: this->StringStack!=0 void vtkKWEFunctionToGLSL::AllocateStringStack() { assert("pre: void" && this->StringStack==0); assert("pre: positive_size" && this->StackSize>0); this->StringStack=new vtkStdString[this->StackSize]; #if 0 int i=0; while(iStackSize) { this->StringStack[i]=0; ++i; } #endif assert("post: allocated" && this->StringStack!=0); } // ---------------------------------------------------------------------------- // Description: // Delete string stack. void vtkKWEFunctionToGLSL::DeleteStringStack() { if(this->StringStack!=0) { #if 0 int i=0; while(iStackSize) { if(this->StringStack[i]!=0) { delete this->StringStack[i]; this->StringStack[i]=0; } ++i; } #endif delete[] this->StringStack; this->StringStack=0; } } // ---------------------------------------------------------------------------- // Description: // Return the dimension of the result of the expression. // \pre valid_expression: GetParseStatus() // \post valid_result: result==1 || result==3 int vtkKWEFunctionToGLSL::GetResultDimension() { assert("pre: valid_expression" && this->GetParseStatus()); assert("post: valid_result" && (this->ResultDimension==1 || this->ResultDimension==3)); return this->ResultDimension; } // ---------------------------------------------------------------------------- // Description: // Generate GLSL source code in GLSLCode. // Update ParseStatus. void vtkKWEFunctionToGLSL::GenerateGLSL() { // Almost like vtkFunctionParser::Evaluate() int numBytesProcessed; int numImmediatesProcessed = 0; int stackPosition = -1; this->ResultDimension=0; // 1 or 3. if (this->FunctionMTime.GetMTime() > this->ParseMTime.GetMTime()) { this->ParseStatus=this->Parse()==1; if(this->StringStack!=0) { this->DeleteStringStack(); } if(this->PrecedenceStack!=0) { delete[] this->PrecedenceStack; this->PrecedenceStack=0; } if (!this->ParseStatus) { return; } if (this->StackSize>0) { this->AllocateStringStack(); this->PrecedenceStack = new int[this->StackSize]; if(this->PrecedenceStack==0) { vtkErrorMacro("Parse: Out of memory"); this->ParseStatus=false; return; } } this->BuildGLSLVariableNames(); } int dim=0; // dimension of the result of the last operation (1 or 3). for (numBytesProcessed = 0; numBytesProcessed < this->ByteCodeSize; numBytesProcessed++) { vtksys_ios::ostringstream ost; switch (this->ByteCode[numBytesProcessed]) { case VTK_PARSER_IMMEDIATE: ++stackPosition; // we use ost.setf/unsetf(ios::showpoint) instead of // ost<Immediates[numImmediatesProcessed++]; ost.unsetf(ios::showpoint); this->StringStack[stackPosition]=ost.str(); this->PrecedenceStack[stackPosition]=1; // highest GLSL priority. dim=1; break; case VTK_PARSER_UNARY_MINUS: ost<<"-"; if(this->PrecedenceStack[stackPosition]>3) // unary is 3 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>3) // unary is 3 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=3; dim=1; break; case VTK_PARSER_ADD: if(this->PrecedenceStack[stackPosition-1]>5) // additive is 5 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>5) // additive is 5 { // need to be protected by parenthesis ost<<")"; } ost<<"+"; if(this->PrecedenceStack[stackPosition]>5) // additive is 5 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>5) // additive is 5 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=5; --stackPosition; dim=1; break; case VTK_PARSER_SUBTRACT: if(this->PrecedenceStack[stackPosition-1]>5) // additive is 5 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>5) // additive is 5 { // need to be protected by parenthesis ost<<")"; } ost<<"-"; if(this->PrecedenceStack[stackPosition]>5) // additive is 5 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>5) // additive is 5 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=5; --stackPosition; dim=1; break; case VTK_PARSER_MULTIPLY: if(this->PrecedenceStack[stackPosition-1]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<")"; } ost<<"*"; if(this->PrecedenceStack[stackPosition]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=4; --stackPosition; dim=1; break; case VTK_PARSER_DIVIDE: if(this->PrecedenceStack[stackPosition-1]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<")"; } ost<<"/"; if(this->PrecedenceStack[stackPosition]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=4; --stackPosition; dim=1; break; case VTK_PARSER_POWER: ost<<"pow("; ost<StringStack[stackPosition-1]; ost<<","; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=2; // function is 2 --stackPosition; dim=1; break; case VTK_PARSER_ABSOLUTE_VALUE: ost<<"fabs("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_EXPONENT: ost<<"exp("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_CEILING: ost<<"ceil("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_FLOOR: ost<<"floor("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_LOGARITHM: case VTK_PARSER_LOGARITHME: ost<<"log("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_LOGARITHM10: ost<<"log("; ost<StringStack[stackPosition]; ost<<")/log(10.0)"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=4; // multiplicative is 4 dim=1; break; case VTK_PARSER_SQUARE_ROOT: ost<<"sqrt("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_SINE: ost<<"sin("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_COSINE: ost<<"cos("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_TANGENT: ost<<"tan("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_ARCSINE: ost<<"asin("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_ARCCOSINE: ost<<"acos("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_ARCTANGENT: ost<<"atan("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_HYPERBOLIC_SINE: // sinh(x)=0.5*(exp(x)-exp(-x)) ost<<"0.5*(exp("; ost<StringStack[stackPosition]; ost<<")-exp(-"; if(this->PrecedenceStack[stackPosition]>3) // unary is 3 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>3) // unary is 3 { // need to be protected by parenthesis ost<<")"; } ost<<"))"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=4; // multiplicative is 4 dim=1; break; case VTK_PARSER_HYPERBOLIC_COSINE: // cosh(x)=0.5*(exp(x)+exp(-x)) ost<<"0.5*(exp("; ost<StringStack[stackPosition]; ost<<")+exp(-"; if(this->PrecedenceStack[stackPosition]>3) // unary is 3 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>3) // unary is 3 { // need to be protected by parenthesis ost<<")"; } ost<<"))"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=4; // multiplicative is 4 dim=1; break; case VTK_PARSER_HYPERBOLIC_TANGENT: // tanh(x)=(exp(2.0*x)-1.0)/(exp(2.0*x)+1.0) ost<<"(exp(2.0*"; if(this->PrecedenceStack[stackPosition]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<")"; } ost<<")-1.0)/(exp(2.0*"; if(this->PrecedenceStack[stackPosition]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<")"; } ost<<")+1.0)"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=4; // multiplicative is 4 dim=1; break; case VTK_PARSER_MIN: ost<<"min("; ost<StringStack[stackPosition-1]; ost<<","; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=2; // function is 2 --stackPosition; dim=1; break; case VTK_PARSER_MAX: ost<<"max("; ost<StringStack[stackPosition-1]; ost<<","; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=2; // function is 2 --stackPosition; dim=1; break; case VTK_PARSER_CROSS: // vector ost<<"cross("; #if 0 // with field selector if(this->PrecedenceStack[stackPosition-1]>2) // field selector is 2 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>2) // field selector is 2 { // need to be protected by parenthesis ost<<")"; } ost<<".xyz,"; if(this->PrecedenceStack[stackPosition]>2) // field selector is 2 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>2) // field selector is 2 { // need to be protected by parenthesis ost<<")"; } ost<<".xyz)"; #else // without field selector ost<StringStack[stackPosition-1]; ost<<","; ost<StringStack[stackPosition]; ost<<")"; #endif // Update the precedence. this->PrecedenceStack[stackPosition-1]=2; // function is 2 --stackPosition; dim=3; break; case VTK_PARSER_SIGN: ost<<"sign("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_VECTOR_UNARY_MINUS: ost<<"-"; if(this->PrecedenceStack[stackPosition]>3) // unary is 3 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>3) // unary is 3 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=3; dim=3; break; case VTK_PARSER_DOT_PRODUCT: ost<<"dot("; ost<StringStack[stackPosition-1]; ost<<","; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=2; // function is 2 --stackPosition; dim=1; break; case VTK_PARSER_VECTOR_ADD: if(this->PrecedenceStack[stackPosition-1]>5) // additive is 5 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>5) // additive is 5 { // need to be protected by parenthesis ost<<")"; } ost<<"+"; if(this->PrecedenceStack[stackPosition]>5) // additive is 5 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>5) // additive is 5 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=5; --stackPosition; dim=3; break; case VTK_PARSER_VECTOR_SUBTRACT: if(this->PrecedenceStack[stackPosition-1]>5) // additive is 5 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>5) // additive is 5 { // need to be protected by parenthesis ost<<")"; } ost<<"-"; if(this->PrecedenceStack[stackPosition]>5) // additive is 5 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>5) // additive is 5 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=5; --stackPosition; dim=3; break; case VTK_PARSER_SCALAR_TIMES_VECTOR: if(this->PrecedenceStack[stackPosition-1]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<"("; } // scalar ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<")"; } ost<<"*"; if(this->PrecedenceStack[stackPosition]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<"("; } // vector ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=4; --stackPosition; dim=3; break; case VTK_PARSER_VECTOR_TIMES_SCALAR: if(this->PrecedenceStack[stackPosition-1]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<"("; } // vector ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<")"; } ost<<"*"; if(this->PrecedenceStack[stackPosition]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<"("; } // scalar ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>4) // multiplicative is 4 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=4; --stackPosition; dim=3; break; case VTK_PARSER_MAGNITUDE: ost<<"length("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=1; break; case VTK_PARSER_NORMALIZE: ost<<"normalize("; ost<StringStack[stackPosition]; ost<<")"; this->StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=2; // function is 2 dim=3; break; case VTK_PARSER_IHAT: ++stackPosition; this->StringStack[stackPosition]="vec3(1.0,0.0,0.0)"; this->PrecedenceStack[stackPosition]=2; // constructor dim=3; break; case VTK_PARSER_JHAT: ++stackPosition; this->StringStack[stackPosition]="vec3(0.0,1.0,0.0)"; this->PrecedenceStack[stackPosition]=2; // constructor dim=3; break; case VTK_PARSER_KHAT: ++stackPosition; this->StringStack[stackPosition]="vec3(0.0,0.0,1.0)"; this->PrecedenceStack[stackPosition]=2; // constructor dim=3; break; case VTK_PARSER_LESS_THAN: if(this->PrecedenceStack[stackPosition-1]>7) // relational is 7 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>7) // relational is 7 { // need to be protected by parenthesis ost<<")"; } ost<<"<"; if(this->PrecedenceStack[stackPosition]>7) // relational is 7 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>7) // relational is 7 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=7; --stackPosition; dim=1; break; case VTK_PARSER_GREATER_THAN: if(this->PrecedenceStack[stackPosition-1]>7) // relational is 7 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>7) // relational is 7 { // need to be protected by parenthesis ost<<")"; } ost<<">"; if(this->PrecedenceStack[stackPosition]>7) // relational is 7 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>7) // relational is 7 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=7; --stackPosition; dim=1; break; case VTK_PARSER_EQUAL_TO: if(this->PrecedenceStack[stackPosition-1]>8) // equality is 8 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>8) // equality is 8 { // need to be protected by parenthesis ost<<")"; } ost<<"=="; if(this->PrecedenceStack[stackPosition]>8) // equality is 8 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>8) // equality is 8 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=8; --stackPosition; dim=1; break; case VTK_PARSER_AND: if(this->PrecedenceStack[stackPosition-1]>12) // logical and is 12 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>12) // logical and is 12 { // need to be protected by parenthesis ost<<")"; } ost<<"&&"; if(this->PrecedenceStack[stackPosition]>12) // logical and is 12 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>12) // logical and is 12 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=12; --stackPosition; dim=1; break; case VTK_PARSER_OR: if(this->PrecedenceStack[stackPosition-1]>14) // logical inclusive or is 14 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>14) // logical inclusive or is 14 { // need to be protected by parenthesis ost<<")"; } ost<<"&&"; if(this->PrecedenceStack[stackPosition]>14) // logical inclusive or is 14 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>14) // logical inclusive or is 14 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-1]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-1]=14; --stackPosition; dim=1; break; case VTK_PARSER_IF: { // Stack[stackPosition]=Stack[2] refers to the bool // argument of if(bool,valtrue,valfalse). Stack[1] is valtrue, and // Stack[0] is valfalse. if(this->PrecedenceStack[stackPosition]>15) // selection is 15 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>15) // selection is 15 { // need to be protected by parenthesis ost<<")"; } ost<<"?"; if(this->PrecedenceStack[stackPosition-1]>15) // selection is 15 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>15) // selection is 15 { // need to be protected by parenthesis ost<<")"; } ost<<":"; if(this->PrecedenceStack[stackPosition-2]>15) // selection is 15 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-2]; if(this->PrecedenceStack[stackPosition-2]>15) // selection is 15 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-2]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-2]=15; stackPosition-=2; dim=1; break; } case VTK_PARSER_VECTOR_IF: { // Stack[stackPosition]=Stack[2] refers to the bool (scalar) // argument of if(bool,valtrue,valfalse). Stack[1] is valtrue // (vector), and Stack[0] is valfalse (vector). if(this->PrecedenceStack[stackPosition]>15) // selection is 15 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition]; if(this->PrecedenceStack[stackPosition]>15) // selection is 15 { // need to be protected by parenthesis ost<<")"; } ost<<"?"; if(this->PrecedenceStack[stackPosition-1]>15) // selection is 15 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-1]; if(this->PrecedenceStack[stackPosition-1]>15) // selection is 15 { // need to be protected by parenthesis ost<<")"; } ost<<":"; if(this->PrecedenceStack[stackPosition-2]>15) // selection is 15 { // need to be protected by parenthesis ost<<"("; } ost<StringStack[stackPosition-2]; if(this->PrecedenceStack[stackPosition-2]>15) // selection is 15 { // need to be protected by parenthesis ost<<")"; } this->StringStack[stackPosition-2]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition-2]=15; stackPosition-=2; dim=1; break; } default: ++stackPosition; int variableId= this->ByteCode[numBytesProcessed]-VTK_PARSER_BEGIN_VARIABLES; if(variableId< this->NumberOfScalarVariables) // scalar { ost<<"scalarValue"; dim=1; } else // vector { variableId-=this->NumberOfScalarVariables; ost<<"vectorValue"; dim=3; } ost<StringStack[stackPosition]=ost.str(); // Update the precedence. this->PrecedenceStack[stackPosition]=1; // highest GLSL one } } vtksys_ios::ostringstream ost2; // It has to be the first line of code. ost2 << "#version 110" << endl; int c=this->NumberOfScalarVariables; int i=0; while(iScalarIsUsed[i]) { ost2<<"uniform sampler2D scalar"<NumberOfVectorVariables; i=0; while(iVectorIsUsed[i]) { ost2<<"uniform sampler2D vector"<NumberOfScalarVariables; i=0; while(iScalarIsUsed[i]) { ost2<<" float scalarValue"<NumberOfVectorVariables; i=0; while(iVectorIsUsed[i]) { ost2<<" vec3 vectorValue"<StringStack[stackPosition]; if(dim==1) { ost2<<")"; } else { assert("check: vector" && dim==3); ost2<<",0.0)"; } ost2<<";"<ResultDimension=dim; (*this->GLSLCode)=ost2.str(); this->EvaluateMTime.Modified(); } // ---------------------------------------------------------------------------- // Description: // Return if a given scalar is used in the function expression. // \pre valid_index:index>=0 && indexNumberOfScalarVariables bool vtkKWEFunctionToGLSL::GetScalarIsUsed(int index) { assert("pre: valid_index" && index>=0 && indexNumberOfScalarVariables); return this->ScalarIsUsed[index]; } // ---------------------------------------------------------------------------- // Description: // Return if a given vector is used in the function expression. // \pre valid_index:index>=0 && indexNumberOfVectorVariables bool vtkKWEFunctionToGLSL::GetVectorIsUsed(int index) { assert("pre: valid_index" && index>=0 && indexNumberOfVectorVariables); return this->VectorIsUsed[index]; } // ---------------------------------------------------------------------------- // Description: // Return the GLSL name attached to the a given scalar data array. // \pre valid_index:index>=0 && indexNumberOfScalarVariables // \pre used_scalar: this->GetScalarIsUsed(index) vtkStdString *vtkKWEFunctionToGLSL::GetGLSLScalarName(int index) { assert("pre: valid_index" && index>=0 && indexNumberOfScalarVariables); assert("pre: used_scalar" && this->GetScalarIsUsed(index)); return &this->GLSLScalarNames[index]; } // ---------------------------------------------------------------------------- // Description: // Return the GLSL name attached to the a given vector data array. // \pre valid_index:index>=0 && indexNumberOfVectorVariables // \pre used_vector: this->GetVectorIsUsed(index) vtkStdString *vtkKWEFunctionToGLSL::GetGLSLVectorName(int index) { assert("pre: valid_index" && index>=0 && indexNumberOfVectorVariables); assert("pre: used_vector" && this->GetVectorIsUsed(index)); return &this->GLSLVectorNames[index]; } // ---------------------------------------------------------------------------- // Description: // Return the number of scalar variables used in the expression. // \post valid_result: result>=0 && result<=GetNumberOfScalarVariables() int vtkKWEFunctionToGLSL::GetNumberOfUsedScalarVariables() { assert("post: valid_result" && this->NumberOfUsedScalarVariables>=0 && this->NumberOfUsedScalarVariables<=this->GetNumberOfScalarVariables()); return this->NumberOfUsedScalarVariables; } // ---------------------------------------------------------------------------- // Description: // Return the number of vector variables used in the expression. // \post valid_result: result>=0 && result<=GetNumberOfVectorVariables() int vtkKWEFunctionToGLSL::GetNumberOfUsedVectorVariables() { assert("post: valid_result" && this->NumberOfUsedVectorVariables>=0 && this->NumberOfUsedVectorVariables<=this->GetNumberOfVectorVariables()); return this->NumberOfUsedVectorVariables; } // ---------------------------------------------------------------------------- // Description: // Build the name of the variable for GLSL. Only load the variables used // in the function expression. // \pre parsed: bytcode exists and is valid void vtkKWEFunctionToGLSL::BuildGLSLVariableNames() { if(this->ScalarIsUsed!=0 && this->ScalarIsUsedSize!=this->NumberOfScalarVariables) { #if 0 int c=this->ScalarIsUsedSize; int i=0; while(iGLSLScalarNames[i]!=0) { delete this->GLSLScalarNames[i]; } ++i; } #endif delete[] this->GLSLScalarNames; this->GLSLScalarNames=0; delete[] this->ScalarIsUsed; this->ScalarIsUsed=0; this->ScalarIsUsedSize=0; } if(this->VectorIsUsed!=0 && this->VectorIsUsedSize!=this->NumberOfVectorVariables) { #if 0 int c=this->VectorIsUsedSize; int i=0; while(iGLSLVectorNames[i]!=0) { delete this->GLSLVectorNames[i]; } ++i; } #endif delete[] this->GLSLVectorNames; this->GLSLVectorNames=0; delete[] this->VectorIsUsed; this->VectorIsUsed=0; this->VectorIsUsedSize=0; } int i; int c; c=this->NumberOfScalarVariables; if(c>0) { if(this->ScalarIsUsed==0) { this->ScalarIsUsed=new bool[c]; this->ScalarIsUsedSize=c; this->GLSLScalarNames=new vtkStdString[c]; } i=0; while(iScalarIsUsed[i]=false; vtksys_ios::ostringstream ost; ost<<"scalar"; ost<GLSLScalarNames[i]=ost.str(); ++i; } } c=this->NumberOfVectorVariables; if(c>0) { if(this->VectorIsUsed==0) { this->VectorIsUsed=new bool[c]; this->VectorIsUsedSize=c; this->GLSLVectorNames=new vtkStdString[c]; } i=0; while(iVectorIsUsed[i]=false; vtksys_ios::ostringstream ost; ost<<"vector"; ost<GLSLVectorNames[i]=ost.str(); ++i; } } this->NumberOfUsedScalarVariables=0; this->NumberOfUsedVectorVariables=0; i=0; c=this->ByteCodeSize; while(iByteCode[i]-VTK_PARSER_BEGIN_VARIABLES; if(j>=0) { if(jNumberOfScalarVariables) { // scalar variable if(!this->ScalarIsUsed[j]) { this->ScalarIsUsed[j]=true; ++this->NumberOfUsedScalarVariables; } } else { // vector variable j-=this->NumberOfScalarVariables; if(!this->VectorIsUsed[j]) { this->VectorIsUsed[j]=true; ++this->NumberOfUsedVectorVariables; } } } ++i; } #if 0 if(usedScalars!=0) { delete[] usedScalars; } if(usedVectors!=0) { delete[] usedVectors; } #endif } // ---------------------------------------------------------------------------- // Description: // Return the GLSLCode generated by GenerateGLSL() in a string. // \pre valid_expression: GetParseStatus() vtkStdString *vtkKWEFunctionToGLSL::GetGLSLCode() { assert("pre: valid_expression" && this->GetParseStatus()); return this->GLSLCode; } // ---------------------------------------------------------------------------- // Description: // Default constructor. The function expression is a null pointer. // The GLSLCode is a null pointer. ParseStatus is false. vtkKWEFunctionToGLSL::vtkKWEFunctionToGLSL() { this->ParseStatus=false; this->GLSLCode=new vtkStdString; this->StringStack=0; this->PrecedenceStack=0; this->ScalarIsUsed=0; this->ScalarIsUsedSize=0; this->VectorIsUsed=0; this->VectorIsUsedSize=0; this->NumberOfUsedScalarVariables=0; this->NumberOfUsedVectorVariables=0; } // ---------------------------------------------------------------------------- // Description: // Destructor. vtkKWEFunctionToGLSL::~vtkKWEFunctionToGLSL() { if(this->GLSLCode!=0) { delete this->GLSLCode; this->GLSLCode=0; } if(this->StringStack!=0) { this->DeleteStringStack(); } if(this->PrecedenceStack!=0) { delete [] this->PrecedenceStack; this->PrecedenceStack=0; } if(this->ScalarIsUsed!=0) { delete[] this->GLSLScalarNames; this->GLSLScalarNames=0; delete[] this->ScalarIsUsed; this->ScalarIsUsed=0; this->ScalarIsUsedSize=0; } if(this->VectorIsUsed!=0) { delete[] this->GLSLVectorNames; this->GLSLVectorNames=0; delete[] this->VectorIsUsed; this->VectorIsUsed=0; this->VectorIsUsedSize=0; } } // ---------------------------------------------------------------------------- void vtkKWEFunctionToGLSL::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Common/vtkKWEDataArrayStreamer.cxx0000644000175000017500000001565711363410610022474 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEDataArrayStreamer.h" #include "vtkObjectFactory.h" #include "assert.h" vtkStandardNewMacro(vtkKWEDataArrayStreamer); vtkCxxRevisionMacro(vtkKWEDataArrayStreamer, "$Revision: 1774 $"); // ---------------------------------------------------------------------------- vtkKWEDataArrayStreamer::vtkKWEDataArrayStreamer() { this->NumberOfTuples=0; this->Max3DTextureSize=16; // 16 is the minimum value of the OpenGL spec. this->MaxTextureSize=64; // 64 is the minimum value of the OpenGL spec. this->MaxTextureMemorySizeInBytes=128*1024*1024; this->TupleSize=1; this->MaxNumberOfTuplesPerBlock=0; this->Cursor=0; this->Step=0; this->ChunkDimensions[0]=0; this->ChunkDimensions[1]=0; this->Stage2Cursor=0; this->Stage2Step=0; this->Stage2NumberOfRows=0; this->Stage3Cursor=0; this->Stage3Step=0; } // ---------------------------------------------------------------------------- vtkKWEDataArrayStreamer::~vtkKWEDataArrayStreamer() { } //---------------------------------------------------------------------------- // Description: // Place the cursor on the first chunk, if any. void vtkKWEDataArrayStreamer::Begin() { // There are three stages, all of them are optional // Stage 1: a bunch of images with the maximum possible size on the GPU // Stage 2: an image with the largest width but with the remaining number of // rows // Stage 3: an image of one row, with the remaining number of colums. // Hardware index limits: int maxSize=this->MaxTextureSize; vtkIdType maxStep=maxSize*maxSize; // User limits and datatype: if(this->MaxTextureMemorySizeInBytes>0) { int maxTupleSize=this->TupleSize; vtkIdType currentSize=maxStep*maxTupleSize; vtkIdType ratio= currentSize/this->MaxTextureMemorySizeInBytes; // can be 0. if(ratio>1) { if(maxStep>1) { if(ratio>maxStep) { maxStep=1; } else { maxStep/=ratio; } } } } if(this->MaxNumberOfTuplesPerBlock>0) { if(maxStep>this->MaxNumberOfTuplesPerBlock) { maxStep=this->MaxNumberOfTuplesPerBlock; } } // maxStep is the maximum possible step in the dataArray with all // included conditions above. // Can we do a full row? bool fullRow=maxStep>=maxSize; vtkIdType size=this->NumberOfTuples; vtkIdType stage1Step; if(!fullRow) { // we can not load a full row, // There are first `numberOfStage1Images' 1D texture (maxStep*1)... vtkIdType numberOfStage1Images=size/maxStep; // it can be 0 stage1Step=maxStep; // ... followed by a last (stage3Step*1) image. this->Stage3Cursor=numberOfStage1Images*stage1Step; this->Stage3Step=size%maxStep; // can be 0 this->ChunkDimensions[0]=maxStep; this->ChunkDimensions[1]=1; // just to have the variables initialized this->Stage2Cursor=this->Stage3Cursor; this->Stage2Step=0; this->Stage2NumberOfRows=0; } else { this->ChunkDimensions[0]=maxSize; // Stage 3. // last row will have stage3Step elements, one (stage3Step*1) image this->Stage3Step=size%maxSize; // can be 0. vtkIdType numberOfFullRows=size/maxSize; // can be 0. if(numberOfFullRows>0) { // if maxStep=maxSize*maxSize, maxHeight=maxSize. // here we take maxStep into account vtkIdType maxHeight=maxStep/maxSize; // Stage 1: // number of images (maxSize*maxHeight), can be 0 vtkIdType numberOfFullImages=numberOfFullRows/maxHeight; // Stage 2: // number of remaining full rows, can be 0. // image is (maxSize*Stage2NumberOfRows) this->Stage2NumberOfRows=numberOfFullRows%maxHeight; stage1Step=maxSize*maxHeight; this->Stage2Cursor=numberOfFullImages*(maxSize*maxHeight); this->Stage2Step=maxSize*this->Stage2NumberOfRows; this->ChunkDimensions[1]=maxHeight; } else { stage1Step=0; this->Stage2Cursor=0; this->Stage2Step=0; this->Stage2NumberOfRows=0; this->ChunkDimensions[1]=1; } this->Stage3Cursor=this->Stage2Cursor+this->Stage2Step; } // start iteration this->Cursor=0; this->Step=stage1Step; if(!IsDone()) { this->UpdateChunkDimensions(); } // naive way: // size: size of dataArray in number of tuples // maxsize: hw index limit // a=size/maxsize=number of complete rows (can be 0) // b=size%maxsize=last row will have b elements (can be 0) -> stage 3 // if(a>0) // c=a/maxsize=number of complete images (can be 0) -> stage1 // d=a%maxsize=number of rows in stage 2 (can be 0) -> stage2 } // ---------------------------------------------------------------------------- // Description: // Is the iteration over? bool vtkKWEDataArrayStreamer::IsDone() { // Check for the most outer loop return this->Cursor>=this->NumberOfTuples; } // ---------------------------------------------------------------------------- // Description: // Go the next chunk, if any. // \pre not_done: !IsDone() void vtkKWEDataArrayStreamer::Next() { assert("pre: not_done" && !this->IsDone()); this->Cursor+=this->Step; if(!this->IsDone()) { this->UpdateChunkDimensions(); } } // ---------------------------------------------------------------------------- // Description: void vtkKWEDataArrayStreamer::UpdateChunkDimensions() { if(this->Cursor==this->Stage3Cursor) { this->ChunkDimensions[0]=this->Stage3Step; this->ChunkDimensions[1]=1; this->Step=this->Stage3Step; } else { if(this->Cursor==this->Stage2Cursor) { this->ChunkDimensions[0]=this->MaxTextureSize; this->ChunkDimensions[1]=this->Stage2NumberOfRows; this->Step=this->Stage2Step; } } assert("post: dims_match_step" && (this->Step==this->ChunkDimensions[0]*this->ChunkDimensions[1])); } // ---------------------------------------------------------------------------- void vtkKWEDataArrayStreamer::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } vtkedge-0.2.0~20110819/Common/VTKEdgeUUIDConfigure.h.in0000644000175000017500000000324111363410610021623 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // // Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de // l'Image). All rights reserved. See Doc/License.txt or // http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notices for more information. // //============================================================================= /* GetMacAddress require a lot of include files to access low level API */ #cmakedefine CMAKE_HAVE_UNISTD_H #cmakedefine CMAKE_HAVE_STDLIB_H #cmakedefine CMAKE_HAVE_SYS_IOCTL_H #cmakedefine CMAKE_HAVE_SYS_SOCKET_H #cmakedefine CMAKE_HAVE_SYS_SOCKIO_H #cmakedefine CMAKE_HAVE_NET_IF_H #cmakedefine CMAKE_HAVE_NETINET_IN_H #cmakedefine CMAKE_HAVE_NET_IF_DL_H #cmakedefine CMAKE_HAVE_NET_IF_ARP_H #cmakedefine HAVE_SA_LEN #cmakedefine SYSTEM_UUID_FOUND vtkedge-0.2.0~20110819/Common/vtkKWEInformationKeyMap.cxx0000644000175000017500000000524511363410610022505 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEInformationKeyMap.h" #include #include #include #include #include vtkCxxRevisionMacro(vtkKWEInformationKeyMap, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEInformationKeyMap); namespace { typedef vtkstd::map >KeyMapType; struct vtkKWEInformationKeyMapInternals { KeyMapType Keys; }; vtkKWEInformationKeyMapInternals vtkKWEInformationKeyMapKeys; } //---------------------------------------------------------------------------- vtkKWEInformationKeyMap::vtkKWEInformationKeyMap() { } //---------------------------------------------------------------------------- vtkKWEInformationKeyMap::~vtkKWEInformationKeyMap() { } //---------------------------------------------------------------------------- void vtkKWEInformationKeyMap::RegisterKey(vtkInformationKey* key) { vtkstd::string name = vtkstd::string(key->GetLocation()) + "." + key->GetName(); vtkKWEInformationKeyMapKeys.Keys[name] = key; } //---------------------------------------------------------------------------- vtkInformationKey* vtkKWEInformationKeyMap::FindKey(const char* name) { KeyMapType::iterator iter = vtkKWEInformationKeyMapKeys.Keys.find(name); if (iter != vtkKWEInformationKeyMapKeys.Keys.end()) { return iter->second; } return 0; } //---------------------------------------------------------------------------- vtkstd::string vtkKWEInformationKeyMap::GetFullName(vtkInformationKey* key) { return vtkstd::string(key->GetLocation()) + "." + key->GetName(); } //---------------------------------------------------------------------------- void vtkKWEInformationKeyMap::RemoveAllKeys() { vtkKWEInformationKeyMapKeys.Keys.clear(); } //---------------------------------------------------------------------------- void vtkKWEInformationKeyMap::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/VolumeRendering/0000755000175000017500000000000011630434664017154 5ustar mathieumathieuvtkedge-0.2.0~20110819/VolumeRendering/vtkKWERepresentativeVolumeImageCreator.cxx0000644000175000017500000012561611363410610027446 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWERepresentativeVolumeImageCreator.h" #include "vtkObjectFactory.h" #include "vtkColorTransferFunction.h" #include "vtkCommand.h" #include "vtkDataArray.h" #include "vtkImageData.h" #include "vtkMath.h" #include "vtkMultiThreader.h" #include "vtkMutexLock.h" #include "vtkPiecewiseFunction.h" #include "vtkPointData.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkVolumeProperty.h" #include vtkStandardNewMacro( vtkKWERepresentativeVolumeImageCreator ); vtkCxxRevisionMacro( vtkKWERepresentativeVolumeImageCreator, "$Revision: 1774 $"); vtkCxxSetObjectMacro(vtkKWERepresentativeVolumeImageCreator, Input, vtkImageData); vtkCxxSetObjectMacro(vtkKWERepresentativeVolumeImageCreator, Property, vtkVolumeProperty); #define vtkKWERVIC_Interpolate( VAL, PTR, VOXEL, C, DIM, COMPONENTS ) \ {float _weight[3]; \ _weight[0] = static_cast(VOXEL[0] - static_cast(static_cast(VOXEL[0]))); \ _weight[1] = static_cast(VOXEL[1] - static_cast(static_cast(VOXEL[1]))); \ _weight[2] = static_cast(VOXEL[2] - static_cast(static_cast(VOXEL[2]))); \ float _A = static_cast(*(PTR + C)); \ float _B = static_cast(*(PTR + C + COMPONENTS)); \ float _C = static_cast(*(PTR + C + COMPONENTS*DIM[0])); \ float _D = static_cast(*(PTR + C + COMPONENTS*(1 + DIM[0]))); \ float _E = static_cast(*(PTR + C + COMPONENTS*DIM[0]*DIM[1])); \ float _F = static_cast(*(PTR + C + COMPONENTS*(1 +DIM[0]*DIM[1]))); \ float _G = static_cast(*(PTR + C + COMPONENTS*(DIM[0] + DIM[0]*DIM[1]))); \ float _H = static_cast(*(PTR + C + \ COMPONENTS*(1 + \ DIM[0] + \ DIM[0]*DIM[1]))); \ VAL = \ (1.0f -_weight[0])*(1.0f -_weight[1])*(1.0f-_weight[2])*_A + \ ( _weight[0])*(1.0f -_weight[1])*(1.0f-_weight[2])*_B + \ (1.0f -_weight[0])*( _weight[1])*(1.0f-_weight[2])*_C + \ ( _weight[0])*( _weight[1])*(1.0f-_weight[2])*_D + \ (1.0f -_weight[0])*(1.0f -_weight[1])*( _weight[2])*_E + \ ( _weight[0])*(1.0f -_weight[1])*( _weight[2])*_F + \ (1.0f -_weight[0])*( _weight[1])*( _weight[2])*_G + \ ( _weight[0])*( _weight[1])*( _weight[2])*_H;} #define vtkKWERVIC_ComputeGradient( N, PTR, VOXEL, C, DIM, COMPONENTS, ASPECT ) \ float _val1, _val2; \ float _voxel1[3]; \ _voxel1[0] = VOXEL[0] - 1.0f; \ _voxel1[1] = VOXEL[1]; \ _voxel1[2] = VOXEL[2]; \ vtkKWERVIC_Interpolate( _val1, \ PTR-COMPONENTS, \ _voxel1, C, DIM, COMPONENTS ); \ \ _voxel1[0] = VOXEL[0] + 1.0f; \ vtkKWERVIC_Interpolate( _val2, \ ptr+COMPONENTS, \ _voxel1, C, DIM, COMPONENTS ); \ \ N[0] = _val2 - _val1; \ \ _voxel1[0] = VOXEL[0]; \ _voxel1[1] = VOXEL[1]-1.0f; \ vtkKWERVIC_Interpolate( _val1, \ ptr-COMPONENTS*DIM[0], \ _voxel1, C, DIM, COMPONENTS ); \ \ _voxel1[1] = VOXEL[1] + 1.0f; \ vtkKWERVIC_Interpolate( _val2, \ ptr+COMPONENTS*DIM[0], \ _voxel1, C, DIM, COMPONENTS ); \ \ N[1] = _val2 - _val1; \ \ _voxel1[1] = VOXEL[1]; \ _voxel1[2] = VOXEL[2] - 1.0f; \ vtkKWERVIC_Interpolate( _val1, \ ptr-COMPONENTS*DIM[0]*DIM[1], \ _voxel1, C, DIM, COMPONENTS ); \ \ _voxel1[2] = VOXEL[2] + 1.0f; \ vtkKWERVIC_Interpolate( _val2, \ ptr+COMPONENTS*DIM[0]*DIM[1], \ _voxel1, C, DIM, COMPONENTS ); \ \ N[2] = _val2 - _val1; \ N[0] /= aspect[0]; \ N[1] /= aspect[1]; \ N[2] /= aspect[2]; #define vtkKWERVIC_ShadeSample(RAY, N, A, D, S, P, R, G, B, C) \ float _viewDir[3]; \ _viewDir[0] = RAY[0]; \ _viewDir[1] = RAY[1]; \ _viewDir[2] = RAY[2]; \ vtkMath::Normalize(_viewDir); \ \ float _n_dot_l = vtkMath::Dot(N,_viewDir); \ \ float _tmp1 = A; \ float _tmp2 = 0.0f; \ \ if ( _n_dot_l > 0.0f ) \ { \ _tmp1 += D*_n_dot_l; \ _tmp2 = S * powf( _n_dot_l,P ); \ } \ \ C[0] = _tmp1*R + _tmp2; \ C[1] = _tmp1*G + _tmp2; \ C[2] = _tmp1*B + _tmp2; // ---------------------------------------------------------------------------- // The only purpose of this class is to be a friend to // vtkKWERepresentativeVolumeImageCreator so that we can access the interal // variables without having to expose them as part of the public API // ---------------------------------------------------------------------------- class vtkKWERVICFriend { public: vtkKWERepresentativeVolumeImageCreator *Creator; vtkImageData *GetInput() {return Creator->InternalInput;}; vtkVolumeProperty *GetProperty() {return Creator->InternalProperty;}; float *GetColorTable(int i) {return Creator->ColorTable[i];} float *GetOpacityTable(int i) {return Creator->OpacityTable[i];} float GetTableOffset(int i) {return Creator->TableOffset[i];} float GetTableScale(int i) {return Creator->TableScale[i];} }; // ---------------------------------------------------------------------------- // This is the templated class for computing a max intensity image // ---------------------------------------------------------------------------- template void vtkKWERVIC_MIP( T *dataPtr, float voxel[3], float rayIncrement[3], unsigned char color[3], vtkKWERVICFriend *myFriend ) { // We need the input image data and the property vtkImageData *input = myFriend->GetInput(); vtkVolumeProperty *property = myFriend->GetProperty(); // Find out how many components we have int components = input->GetNumberOfScalarComponents(); // Are the components independent? int independent = property->GetIndependentComponents(); // What is our volume dimensions? We need this to keep our // ray inside the volume int dim[3]; input->GetDimensions(dim); // Some variables we'll need to compute the final pixel color float maxValue[4]; int c; float *colorTable[4]; float *opacityTable[4]; float tableOffset[4]; float tableScale[4]; float weight[4]; // ptr is a pointer to the voxel location T *ptr = dataPtr + components * ( static_cast(voxel[0]) + static_cast(voxel[1]) * dim[0] + static_cast(voxel[2]) * dim[0] * dim[1] ); // For each component: // - initialize the max value to the first value found // - get the color and opacity tables // - get the offset / scale values to transform scalar // value into index // - get the weight for ( c = 0; c < components; c++ ) { maxValue[c] = static_cast(ptr[c]); colorTable[c] = myFriend->GetColorTable(c); opacityTable[c] = myFriend->GetOpacityTable(c); tableOffset[c] = myFriend->GetTableOffset(c); tableScale[c] = myFriend->GetTableScale(c); weight[c] = static_cast(property->GetComponentWeight(c)); } // Keep stepping until we exit the volume. We'll be conservative and // considering exiting the volume to be passing into or beyong the last // voxel in each direction - that avoids boundary conditions in any // blending modes that require gradients while ( voxel[0] > 1.0 && voxel[1] > 1.0 && voxel[2] > 1.0 && voxel[0] < (dim[0]-2) && voxel[1] < (dim[1]-2) && voxel[2] < (dim[2]-2) ) { if ( independent ) { // Check each component if we have a new max value for ( c = 0; c < components; c++ ) { float val; vtkKWERVIC_Interpolate( val, ptr, voxel, c, dim, components ); if ( val > maxValue[c] ) { maxValue[c] = val; } } } else { float val; vtkKWERVIC_Interpolate( val, ptr, voxel, components-1, dim, components ); if ( val > maxValue[components-1] ) { maxValue[components-1] = val; for ( c = 0; c < components-1; c++ ) { vtkKWERVIC_Interpolate( val, ptr, voxel, c, dim, components ); maxValue[c] = val; } } } // Increment to the next voxel voxel[0] += rayIncrement[0]; voxel[1] += rayIncrement[1]; voxel[2] += rayIncrement[2]; // Move the pointer to this location ptr = dataPtr + components * ( static_cast(voxel[0]) + static_cast(voxel[1]) * dim[0] + static_cast(voxel[2]) * dim[0] * dim[1] ); } // Now compute the color. Exact computation will depend on whether // the component are independent or dependend (and if dependent, on // whether there are Need to consider each components contribution float tmpColor[4] = {0,0,0,0}; int index; if ( independent ) { for ( c = 0; c < components; c++ ) { // Find the index into the table and look up RGBA index = static_cast((maxValue[c] + tableOffset[c]) * tableScale[c] + 0.5); index = (index < 0 )?(0):((index>1023)?(1023):(index)); float r = *(colorTable[c] + 3*index); float g = *(colorTable[c] + 3*index+1); float b = *(colorTable[c] + 3*index+2); float a = *(opacityTable[c] + index); // Add it in (multiplied by weight) tmpColor[0] += weight[c] * r * a; tmpColor[1] += weight[c] * g * a; tmpColor[2] += weight[c] * b * a; tmpColor[3] += weight[c] * a; } } else if ( components == 2 ) { // Find the index into the table and look up A index = static_cast((maxValue[1] + tableOffset[1]) * tableScale[1] + 0.5); tmpColor[3] = *(opacityTable[0] + index); // Find the index into the table and look up RGB index = static_cast((maxValue[0] + tableOffset[0]) * tableScale[0] + 0.5); tmpColor[0] = *(colorTable[0] + 3*index ) * tmpColor[3]; tmpColor[1] = *(colorTable[0] + 3*index+1) * tmpColor[3]; tmpColor[2] = *(colorTable[0] + 3*index+2) * tmpColor[3]; } else if ( components == 4 ) { // Find the index into the table and look up A index = static_cast((maxValue[3] + tableOffset[3]) * tableScale[3] + 0.5); tmpColor[3] = *(opacityTable[0] + index); // Use first three components directly as RGB. We know this must be // unsigned char (only type allowed in this case) so we'll use that // knowledge to convert to a [0,1] range. tmpColor[0] = maxValue[0]/255.0f * tmpColor[3]; tmpColor[1] = maxValue[1]/255.0f * tmpColor[3]; tmpColor[2] = maxValue[2]/255.0f * tmpColor[3]; } // Check bounds to make sure everything is between [0,1] tmpColor[0] = (tmpColor[0] < 0)?(0):((tmpColor[0]>1)?(1):(tmpColor[0])); tmpColor[1] = (tmpColor[1] < 0)?(0):((tmpColor[1]>1)?(1):(tmpColor[1])); tmpColor[2] = (tmpColor[2] < 0)?(0):((tmpColor[2]>1)?(1):(tmpColor[2])); tmpColor[3] = (tmpColor[3] < 0)?(0):((tmpColor[3]>1)?(1):(tmpColor[3])); // Now convert to unsigned char color[0] = static_cast(tmpColor[0]*255.0 + 0.5); color[1] = static_cast(tmpColor[1]*255.0 + 0.5); color[2] = static_cast(tmpColor[2]*255.0 + 0.5); } // ---------------------------------------------------------------------------- // This is the templated class for computing a composite image // ---------------------------------------------------------------------------- template void vtkKWERVIC_Composite( T *dataPtr, float voxel[3], float rayIncrement[3], unsigned char color[3], vtkKWERVICFriend *myFriend ) { // We need the input image data and the property vtkImageData *input = myFriend->GetInput(); vtkVolumeProperty *property = myFriend->GetProperty(); double spacing[3]; input->GetSpacing(spacing); double avgSpacing = (spacing[0]+spacing[1]+spacing[2])/3.0; // adjust the aspect float aspect[3]; aspect[0] = static_cast(spacing[0] * 2.0 / avgSpacing); aspect[1] = static_cast(spacing[1] * 2.0 / avgSpacing); aspect[2] = static_cast(spacing[2] * 2.0 / avgSpacing); // Find out how many components we have int components = input->GetNumberOfScalarComponents(); // Are the components independent? int independent = property->GetIndependentComponents(); // What is our volume dimensions? We need this to keep our // ray inside the volume int dim[3]; input->GetDimensions(dim); // Some variables we'll need to compute the final pixel color int c; float *colorTable[4]; float *opacityTable[4]; float tableOffset[4]; float tableScale[4]; float weight[4]; float ambient[4]; float diffuse[4]; float specular[4]; float specularPower[4]; float accumColor[3] = {0,0,0}; float remainingOpacity = 1.0; // ptr is a pointer to the voxel location T *ptr = dataPtr + components * ( static_cast(voxel[0]) + static_cast(voxel[1]) * dim[0] + static_cast(voxel[2]) * dim[0] * dim[1] ); // For each component: // - get the color and opacity tables // - get the offset / scale values to transform scalar // value into index // - get the weight for ( c = 0; c < components; c++ ) { colorTable[c] = myFriend->GetColorTable(c); opacityTable[c] = myFriend->GetOpacityTable(c); tableOffset[c] = myFriend->GetTableOffset(c); tableScale[c] = myFriend->GetTableScale(c); weight[c] = static_cast(property->GetComponentWeight(c)); ambient[c] = static_cast(property->GetAmbient(c)); diffuse[c] = static_cast(property->GetDiffuse(c)); specular[c] = static_cast(property->GetSpecular(c)); specularPower[c] = static_cast(property->GetSpecularPower(c)); } // Keep stepping until we exit the volume. We'll be conservative and // considering exiting the volume to be passing into or beyong the last // voxel in each direction - that avoids boundary conditions in any // blending modes that require gradients while ( voxel[0] > 1 && voxel[1] > 1 && voxel[2] > 1 && voxel[0] < (dim[0]-2) && voxel[1] < (dim[1]-2) && voxel[2] < (dim[2]-2) && remainingOpacity > 0.02 ) { float tmpColor[4] = {0,0,0,0}; int index; if ( independent ) { for ( c = 0; c < components; c++ ) { float val; vtkKWERVIC_Interpolate( val, ptr, voxel, c, dim, components ); index = static_cast((val + tableOffset[c]) * tableScale[c] + 0.5); index = (index<0)?(0):((index>1023)?(1023):(index)); float r = *(colorTable[c] + 3*index); float g = *(colorTable[c] + 3*index+1); float b = *(colorTable[c] + 3*index+2); float a = *(opacityTable[c] + index); if ( a > 0.0 && property->GetShade() ) { float n[3]; vtkKWERVIC_ComputeGradient( n, ptr, voxel, c, dim, components, aspect ); float length = vtkMath::Normalize(n); if ( length < 1.0 / tableScale[c] ) { tmpColor[0] += weight[c]*a*((ambient[c])*r); tmpColor[1] += weight[c]*a*((ambient[c])*g); tmpColor[2] += weight[c]*a*((ambient[c])*b); tmpColor[3] += weight[c]*a; } else { float shadedColor[3]; vtkKWERVIC_ShadeSample(rayIncrement, n, ambient[c], diffuse[c], specular[c],specularPower[c], r, g, b, shadedColor ); tmpColor[0] += weight[c]*a*shadedColor[0]; tmpColor[1] += weight[c]*a*shadedColor[1]; tmpColor[2] += weight[c]*a*shadedColor[2]; tmpColor[3] += weight[c]*a; } } else { // Add it in (multiplied by weight) tmpColor[0] += weight[c] * r * a; tmpColor[1] += weight[c] * g * a; tmpColor[2] += weight[c] * b * a; tmpColor[3] += weight[c] * a; } } } else { // start by getting the opacity from the last component // passed through the lookup table float val; c = components-1; vtkKWERVIC_Interpolate( val, ptr, voxel, c, dim, components ); index = static_cast((val + tableOffset[c]) * tableScale[c] + 0.5); index = (index<0)?(0):((index>1023)?(1023):(index)); float r, g, b, a; // avoid compiler warning r = g = b = 0.0; // initialize alpha a = *(opacityTable[0] + index); if ( a ) { if ( components == 4 ) { vtkKWERVIC_Interpolate( val, ptr, voxel, 0, dim, components ); r = val/255.0f; vtkKWERVIC_Interpolate( val, ptr, voxel, 1, dim, components ); g = val/255.0f; vtkKWERVIC_Interpolate( val, ptr, voxel, 2, dim, components ); b = val/255.0f; } else if ( components == 2 ) { vtkKWERVIC_Interpolate( val, ptr, voxel, 0, dim, components ); index = static_cast((val + tableOffset[0]) * tableScale[0] + 0.5); index = (index<0)?(0):((index>1023)?(1023):(index)); r = *(colorTable[0] + 3*index); g = *(colorTable[0] + 3*index+1); b = *(colorTable[0] + 3*index+2); } else { // This case should not happen, it is just here to // avoid VS warning C4701: "potentially uninitialized local variable // 'r'/'g'/'b' used" r=0.0f; g=0.0f; b=0.0f; assert("check: impossible case. components is neither 2 nor 4" && 0); } // unshaded color tmpColor[0] = a*r; tmpColor[1] = a*g; tmpColor[2] = a*b; tmpColor[3] = a; if ( property->GetShade() ) { float n[3]; vtkKWERVIC_ComputeGradient( n, ptr, voxel, components-1, dim, components, aspect ); float length = vtkMath::Normalize(n); if ( length < 1.0 / tableScale[0] ) { tmpColor[0] = r*ambient[0]; tmpColor[1] = g*ambient[0]; tmpColor[2] = b*ambient[0]; } else { float shadedColor[3]; vtkKWERVIC_ShadeSample(rayIncrement, n, ambient[0], diffuse[0], specular[0],specularPower[0], r, g, b, shadedColor ); tmpColor[0] = a*shadedColor[0]; tmpColor[1] = a*shadedColor[1]; tmpColor[2] = a*shadedColor[2]; tmpColor[3] = a; } } } } accumColor[0] += tmpColor[0]*remainingOpacity; accumColor[1] += tmpColor[1]*remainingOpacity; accumColor[2] += tmpColor[2]*remainingOpacity; remainingOpacity *= (1.0f - tmpColor[3]); // Increment to the next voxel voxel[0] += rayIncrement[0]; voxel[1] += rayIncrement[1]; voxel[2] += rayIncrement[2]; // Move the pointer to this location ptr = dataPtr + components * ( static_cast(voxel[0]) + static_cast(voxel[1]) * dim[0] + static_cast(voxel[2]) * dim[0] * dim[1] ); } // Check bounds to make sure everything is between [0,1] accumColor[0] = (accumColor[0] < 0)?(0):((accumColor[0]>1)?(1):(accumColor[0])); accumColor[1] = (accumColor[1] < 0)?(0):((accumColor[1]>1)?(1):(accumColor[1])); accumColor[2] = (accumColor[2] < 0)?(0):((accumColor[2]>1)?(1):(accumColor[2])); // Now do the alpha multiplication and convert to unsigned char color[0] = static_cast(accumColor[0]*255.0 + 0.5); color[1] = static_cast(accumColor[1]*255.0 + 0.5); color[2] = static_cast(accumColor[2]*255.0 + 0.5); } // ---------------------------------------------------------------------------- // This is the threaded function // ---------------------------------------------------------------------------- VTK_THREAD_RETURN_TYPE vtkKWERVICGenerateImage( void *arg ) { vtkKWERepresentativeVolumeImageCreator *creator; vtkMutexLock *activeFlagLock; int *activeFlag; vtkMultiThreader::ThreadInfo *castedArg; castedArg = static_cast(arg); activeFlagLock = castedArg->ActiveFlagLock; activeFlag = castedArg->ActiveFlag; creator = static_cast (static_cast(arg)->UserData); creator->GenerateImage( activeFlag, activeFlagLock ); return VTK_THREAD_RETURN_VALUE; } // ---------------------------------------------------------------------------- // Constructor // ---------------------------------------------------------------------------- vtkKWERepresentativeVolumeImageCreator::vtkKWERepresentativeVolumeImageCreator() { this->Property = NULL; this->BlendMode = -1; this->Input = NULL; this->InternalProperty = vtkVolumeProperty::New(); this->InternalBlendMode = -1; this->InternalInput = NULL; this->VisibleSide = vtkKWERepresentativeVolumeImageCreator::MinusYSideView; this->Threader = vtkMultiThreader::New(); this->SpawnedThreadID = -1; this->RepresentativeImage = NULL; this->RepresentativeImageIsValidLock = vtkMutexLock::New(); this->RepresentativeImageIsValid = 0; this->RepresentativeImageSize[0] = 0; this->RepresentativeImageSize[1] = 0; } // ---------------------------------------------------------------------------- // Destructor // ---------------------------------------------------------------------------- vtkKWERepresentativeVolumeImageCreator::~vtkKWERepresentativeVolumeImageCreator() { this->Stop(); this->ClearInternalParameters(); this->InternalProperty->Delete(); this->SetProperty(NULL); this->SetInput(NULL); this->RepresentativeImageIsValidLock->Delete(); this->Threader->Delete(); if ( this->RepresentativeImage ) { this->RepresentativeImage->Delete(); } } // ---------------------------------------------------------------------------- // Internal method to clear out copies of parameters kept for processing in the // spawned thread // ---------------------------------------------------------------------------- void vtkKWERepresentativeVolumeImageCreator::ClearInternalParameters() { if ( this->InternalInput ) { this->InternalInput->UnRegister(this); } this->InternalBlendMode = -1; this->InternalInput = NULL; } // ---------------------------------------------------------------------------- // The Start method will start a process to create the representative image. // ---------------------------------------------------------------------------- void vtkKWERepresentativeVolumeImageCreator::Start() { // First check if we are already processing - it is an error to try to // process more than one image at a time. if ( this->IsProcessing() ) { vtkErrorMacro("Cannot start since an image is currently being processed."); return; } // Clear out the old internal parameters this->ClearInternalParameters(); // Invalidate the last representative image this->RepresentativeImageIsValidLock->Lock(); this->RepresentativeImageIsValid = 0; this->RepresentativeImageIsValidLock->Unlock(); // If the image size is not set, it is an error if ( this->RepresentativeImageSize[0] == 0 || this->RepresentativeImageSize[1] == 0 ) { vtkErrorMacro("You must set the size of the representative image before starting."); return; } // If we already have a representative image, release it if ( this->RepresentativeImage ) { this->RepresentativeImage->Delete(); } // Now create one of the right size and type this->RepresentativeImage = vtkImageData::New(); this->RepresentativeImage->SetDimensions( this->RepresentativeImageSize[0], this->RepresentativeImageSize[1], 1 ); this->RepresentativeImage->SetScalarTypeToUnsignedChar(); this->RepresentativeImage->SetNumberOfScalarComponents(3); this->RepresentativeImage->AllocateScalars(); // Keep a separate pointer to the input. We are still sharing the // input with the main thread - we'll only be reading it, but the main // thread can also only read it while we are processing. The main thread // can change our input (but cannot make changes to the vtkImageData that // was the input at the time we were last started...) this->InternalInput = this->Input; this->InternalInput->Register(this); // For the property, let's make a copy of it. This way we don't // have to worry about what the main thread might be doing with // it. this->InternalProperty->DeepCopy(this->Property); this->InternalBlendMode = this->BlendMode; // Now spawn the thread this->SpawnedThreadID = this->Threader->SpawnThread( vtkKWERVICGenerateImage, this ); } // ---------------------------------------------------------------------------- // The GenerateImage method is called from the threaded function // ---------------------------------------------------------------------------- void vtkKWERepresentativeVolumeImageCreator::GenerateImage(int *flag, vtkMutexLock *lock) { float rayIncrement[3]; this->ComputeRayIncrement(rayIncrement); double sampleDistance = this->ComputeSampleDistance(rayIncrement); this->UpdateTransferFunctions(sampleDistance); unsigned char *ptr = static_cast(this->RepresentativeImage->GetScalarPointer()); int i, j; for ( j = 0; j < this->RepresentativeImageSize[1]; j++ ) { for ( i = 0; i < this->RepresentativeImageSize[0]; i++ ) { float voxel[3]; this->ComputeFirstVoxel(i, j, voxel); if ( voxel[0] == -1 ) { ptr[0] = 0; ptr[1] = 0; ptr[2] = 0; } else { unsigned char color[3]; this->CastRay(voxel, rayIncrement, color); ptr[0] = color[0]; ptr[1] = color[1]; ptr[2] = color[2]; } ptr+=3; } } // The image is done now this->RepresentativeImageIsValidLock->Lock(); this->RepresentativeImageIsValid = 1; this->RepresentativeImageIsValidLock->Unlock(); lock->Lock(); *flag = 0; lock->Unlock(); } // ---------------------------------------------------------------------------- // The Stop method will stop the background thread that is processing the image. // ---------------------------------------------------------------------------- void vtkKWERepresentativeVolumeImageCreator::Stop() { if ( this->IsProcessing() ) { this->Threader->TerminateThread(this->SpawnedThreadID); } } // ---------------------------------------------------------------------------- // IsProcessing will return 1 if the background thread is processing an image // ---------------------------------------------------------------------------- int vtkKWERepresentativeVolumeImageCreator::IsProcessing() { // Can't be processing, we don't have a spawned thread ID if ( this->SpawnedThreadID < 0 ) { return 0; } // Check with the threader return this->Threader->IsThreadActive(this->SpawnedThreadID); } // ---------------------------------------------------------------------------- // IsValid will return 1 is the last attempt at processing an image was // successful // ---------------------------------------------------------------------------- int vtkKWERepresentativeVolumeImageCreator::IsValid() { this->RepresentativeImageIsValidLock->Lock(); int val = this->RepresentativeImageIsValid; this->RepresentativeImageIsValidLock->Unlock(); return val; } // ---------------------------------------------------------------------------- // GetRepresentativeImage will return the representative image as long as // this class is not currently processing and that image is valid // ---------------------------------------------------------------------------- vtkImageData *vtkKWERepresentativeVolumeImageCreator::GetRepresentativeImage() { if ( this->IsProcessing() ) { vtkErrorMacro("Can't get image while processing"); return NULL; } if ( !this->IsValid() ) { vtkErrorMacro("Image is not valid"); return NULL; } return this->RepresentativeImage; } // ---------------------------------------------------------------------------- // SetRepresentativeImageSize will set the width / height of the representative // image. These values must be at least 1 and at most 1024. // ---------------------------------------------------------------------------- void vtkKWERepresentativeVolumeImageCreator::SetRepresentativeImageSize(int width, int height) { if ( width < 1 || height < 1 || width > 1024 || height > 1024 ) { vtkErrorMacro("Width and height must be between 1 and 1024!"); return; } if ( width != this->RepresentativeImageSize[0] || height != this->RepresentativeImageSize[1] ) { this->RepresentativeImageSize[0] = width; this->RepresentativeImageSize[1] = height; this->Modified(); } } // ---------------------------------------------------------------------------- void vtkKWERepresentativeVolumeImageCreator::ComputeRayIncrement(float rayIncrement[3]) { float inc = 0.5; switch ( this->VisibleSide ) { case vtkKWERepresentativeVolumeImageCreator::XSideView: rayIncrement[0] = -inc; rayIncrement[1] = 0.0; rayIncrement[2] = 0.0; break; case vtkKWERepresentativeVolumeImageCreator::MinusXSideView: rayIncrement[0] = inc; rayIncrement[1] = 0.0; rayIncrement[2] = 0.0; break; case vtkKWERepresentativeVolumeImageCreator::YSideView: rayIncrement[0] = 0.0; rayIncrement[1] = -inc; rayIncrement[2] = 0.0; break; case vtkKWERepresentativeVolumeImageCreator::MinusYSideView: rayIncrement[0] = 0.0; rayIncrement[1] = inc; rayIncrement[2] = 0.0; break; case vtkKWERepresentativeVolumeImageCreator::ZSideView: rayIncrement[0] = 0.0; rayIncrement[1] = 0.0; rayIncrement[2] = -inc; break; case vtkKWERepresentativeVolumeImageCreator::MinusZSideView: rayIncrement[0] = 0.0; rayIncrement[1] = 0.0; rayIncrement[2] = inc; break; default: vtkErrorMacro("Invalid VisibleSide"); break; } } // ---------------------------------------------------------------------------- void vtkKWERepresentativeVolumeImageCreator::ComputeFirstVoxel(int i, int j, float voxel[3]) { int idim[3]; this->RepresentativeImage->GetDimensions(idim); int vdim[3]; this->InternalInput->GetDimensions(vdim); double spacing[3]; this->InternalInput->GetSpacing(spacing); double size[3]; size[0] = static_cast(vdim[0]-1)*spacing[0]; size[1] = static_cast(vdim[1]-1)*spacing[1]; size[2] = static_cast(vdim[2]-1)*spacing[2]; int imageXAxis = 0; int imageYAxis = 1; double xAxisSign = 1.0; switch ( this->VisibleSide ) { case vtkKWERepresentativeVolumeImageCreator::XSideView: imageXAxis = 1; imageYAxis = 2; voxel[0] = static_cast(vdim[0] - 2.0001 - vtkMath::Random()); xAxisSign = 1.0; break; case vtkKWERepresentativeVolumeImageCreator::MinusXSideView: imageXAxis = 1; imageYAxis = 2; voxel[0] = static_cast(1.0001 + vtkMath::Random()); xAxisSign = -1.0; break; case vtkKWERepresentativeVolumeImageCreator::YSideView: imageXAxis = 0; imageYAxis = 2; voxel[1] = static_cast(vdim[1] - 2.0001 - vtkMath::Random()); xAxisSign = -1.0; break; case vtkKWERepresentativeVolumeImageCreator::MinusYSideView: imageXAxis = 0; imageYAxis = 2; voxel[1] = static_cast(1.0001 + vtkMath::Random()); xAxisSign = 1.0; break; case vtkKWERepresentativeVolumeImageCreator::ZSideView: imageXAxis = 0; imageYAxis = 1; voxel[2] = static_cast(vdim[2] - 2.0001 - vtkMath::Random()); xAxisSign = 1.0; break; case vtkKWERepresentativeVolumeImageCreator::MinusZSideView: imageXAxis = 0; imageYAxis = 1; voxel[2] = static_cast(1.0001 + vtkMath::Random()); xAxisSign = -1.0; break; default: vtkErrorMacro("Invalid VisibleSide"); break; } double imageScaleX = static_cast(idim[0]-1)/(size[imageXAxis]); double imageScaleY = static_cast(idim[1]-1)/(size[imageYAxis]); double scaleFactor; double length; if ( imageScaleX < imageScaleY ) { scaleFactor = imageScaleX; length = idim[0]-1; } else { scaleFactor = imageScaleY; length = idim[1]-1; } // convert position into normalized location centered on image center double p1 = (imageScaleX/scaleFactor)* (static_cast(i) - static_cast(idim[0]-1)/2.0)/length; // flip p1 because X axis runs from right to left p1 *= xAxisSign; double p2 = (imageScaleY/scaleFactor)*(static_cast(j) - static_cast(idim[1]-1)/2.0)/length; // convert to voxel location voxel[imageXAxis] = static_cast(p1 * static_cast(vdim[imageXAxis]-5.0) + static_cast(vdim[imageXAxis]-1)/2.0); voxel[imageYAxis] = static_cast(p2 * static_cast(vdim[imageYAxis]-5.0) + static_cast(vdim[imageYAxis]-1)/2.0); if ( ! (voxel[0] > 1.0 && voxel[1] > 1.0 && voxel[2] > 1.0 && voxel[0] < (vdim[0]-2) && voxel[1] < (vdim[1]-2) && voxel[2] < (vdim[2]-2)) ) { // Ray does not intersect volume - happens due to aspect ratio because // we make the whole volume fit in all directions. voxel[0] = -1; } } // ---------------------------------------------------------------------------- void vtkKWERepresentativeVolumeImageCreator::UpdateTransferFunctions(double sampleDistance) { int numComponents = this->InternalInput->GetNumberOfScalarComponents(); int independent = this->InternalProperty->GetIndependentComponents(); int i; for (i = 0; i < numComponents; i++ ) { double range[2]; this->InternalInput->GetPointData()->GetScalars()->GetRange(range, i); this->TableOffset[i] = static_cast(-range[0]); this->TableScale[i] = static_cast(1023.0 / (range[1]-range[0])); // If we have independent components, we'll get a color and opacity table for each // component and store it in that component's index (i). Otherwise, we have // "dependent" components (LA, or RGBA) and we have at most one color table and // exactly one opacity table, and we'll store those in the 0th entry in our // ColorTable / OpacityTable. int tableIdx = (independent==0)?(0):(i); if ( independent || ( i == 0 && numComponents == 2) ) { if ( this->InternalProperty->GetColorChannels(tableIdx) == 1 ) { vtkPiecewiseFunction *gf = this->InternalProperty->GetGrayTransferFunction(tableIdx); float tmp[1024]; gf->GetTable( range[0], range[1], 1024, tmp ); for ( int index = 0; index < 1024; index++ ) { this->ColorTable[tableIdx][index*3 ] = tmp[index]; this->ColorTable[tableIdx][index*3+1] = tmp[index]; this->ColorTable[tableIdx][index*3+2] = tmp[index]; } } else { vtkColorTransferFunction *cf = this->InternalProperty->GetRGBTransferFunction(tableIdx); cf->GetTable( range[0], range[1], 1024, this->ColorTable[tableIdx] ); } } if ( independent || ( i == numComponents-1) ) { this->InternalProperty->GetScalarOpacity(tableIdx)->GetTable( range[0], range[1], 1024, this->OpacityTable[tableIdx] ); // If the blend mode is composite, then we'll need to adjust the opacity // function for the sample distance if ( this->InternalBlendMode == vtkVolumeMapper::COMPOSITE_BLEND ) { int idx; for ( idx = 0; idx < 1023; idx++ ) { if ( this->OpacityTable[tableIdx][idx] > 0.0001 ) { this->OpacityTable[tableIdx][idx] = static_cast( 1.0-pow(static_cast((1.0 - this->OpacityTable[tableIdx][idx])), sampleDistance)); } } } } } } // ---------------------------------------------------------------------------- double vtkKWERepresentativeVolumeImageCreator::ComputeSampleDistance(float rayIncrement[3]) { double spacing[3]; this->InternalInput->GetSpacing(spacing); switch ( this->VisibleSide ) { case vtkKWERepresentativeVolumeImageCreator::XSideView: case vtkKWERepresentativeVolumeImageCreator::MinusXSideView: return spacing[0]*fabs(rayIncrement[0]); break; case vtkKWERepresentativeVolumeImageCreator::YSideView: case vtkKWERepresentativeVolumeImageCreator::MinusYSideView: return spacing[1]*fabs(rayIncrement[1]); break; case vtkKWERepresentativeVolumeImageCreator::ZSideView: case vtkKWERepresentativeVolumeImageCreator::MinusZSideView: return spacing[2]*fabs(rayIncrement[2]); break; default: vtkErrorMacro("Invalid VisibleSide"); break; } return 0.0; } // ---------------------------------------------------------------------------- void vtkKWERepresentativeVolumeImageCreator::CastRay(float voxel[3], float rayIncrement[3], unsigned char color[3]) { int scalarType = this->InternalInput->GetScalarType(); void *dataPtr = this->InternalInput->GetScalarPointer(); vtkKWERVICFriend *myFriend = new vtkKWERVICFriend; myFriend->Creator = this; switch ( this->InternalBlendMode ) { case vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND: switch ( scalarType ) { vtkTemplateMacro( vtkKWERVIC_MIP(static_cast(dataPtr), voxel, rayIncrement, color, myFriend ) ); } break; case vtkVolumeMapper::COMPOSITE_BLEND: switch ( scalarType ) { vtkTemplateMacro( vtkKWERVIC_Composite(static_cast(dataPtr), voxel, rayIncrement, color, myFriend ) ); } break; default: color[0] = 255; color[1] = 0; color[2] = 0; break; } delete myFriend; } // ---------------------------------------------------------------------------- void vtkKWERepresentativeVolumeImageCreator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/VolumeRendering/CMakeLists.txt0000644000175000017500000000731711374311375021722 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Set of basic source files (not the OpenGL or GLSL ones) # ----------------------------------------------------------------------------- set(KIT_SRCS vtkKWERepresentativeVolumeImageCreator.cxx ) # ----------------------------------------------------------------------------- # Set of OpenGL source files # ----------------------------------------------------------------------------- set(KIT_OpenGL_SRCS ) # ----------------------------------------------------------------------------- # Set of GLSL source files # ----------------------------------------------------------------------------- set(KIT_GLSL_SRCS ) # ----------------------------------------------------------------------------- # Create custom commands to encode each glsl file into a C string literal # in a header file # ----------------------------------------------------------------------------- foreach(file ${KIT_GLSL_SRCS}) set(src ${VTKEdge_SOURCE_DIR}/VolumeRendering/${file}.glsl) set(res ${VTKEdge_BINARY_DIR}/VolumeRendering/${file}.cxx) add_custom_command( OUTPUT ${res} DEPENDS ${src} COMMAND ${VTK_ENCODESTRING_EXE} ARGS ${res} ${src} ${file} ) set(KIT_EXTRA_SRCS ${KIT_EXTRA_SRCS} ${res}) endforeach(file) # ----------------------------------------------------------------------------- # List the kits from VTK that are needed by this project # ----------------------------------------------------------------------------- set(KIT_LIBS vtkVolumeRendering vtkKWECommon ) # ----------------------------------------------------------------------------- # Create the library # ----------------------------------------------------------------------------- add_library(vtkKWEVolumeRendering ${KIT_SRCS} ${KIT_OpenGL_SRCS} ${KIT_EXTRA_SRCS}) target_link_libraries(vtkKWEVolumeRendering ${KIT_LIBS}) # ----------------------------------------------------------------------------- # Testing # ----------------------------------------------------------------------------- if(BUILD_TESTING) add_subdirectory(Testing) endif(BUILD_TESTING) # ----------------------------------------------------------------------------- # Installation # ----------------------------------------------------------------------------- if(NOT VTKEdge_INSTALL_NO_LIBRARIES) install_targets( ${VTKEdge_INSTALL_LIB_DIR} RUNTIME_DIRECTORY ${VTKEdge_INSTALL_BIN_DIR} vtkKWEVolumeRendering ) endif(NOT VTKEdge_INSTALL_NO_LIBRARIES) if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_INCLUDE_DIR} .h ${KIT_SRCS}) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) # ----------------------------------------------------------------------------- # This make it easy for other projects to get the list of files etc. in this # kit. # ----------------------------------------------------------------------------- include(${VTK_CMAKE_DIR}/vtkExportKit.cmake) vtk_export_kit2("KWEVolumeRendering" "KWEVOLUMERENDERING" ${CMAKE_CURRENT_BINARY_DIR} "${KIT_SRCS}") vtkedge-0.2.0~20110819/VolumeRendering/Testing/0000755000175000017500000000000011630434664020571 5ustar mathieumathieuvtkedge-0.2.0~20110819/VolumeRendering/Testing/Cxx/0000755000175000017500000000000011630434664021333 5ustar mathieumathieuvtkedge-0.2.0~20110819/VolumeRendering/Testing/Cxx/CMakeLists.txt0000644000175000017500000000665211363410610024070 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Name this kit - this will be used to form test executable names later # Then we'll add in tests with various data or kit dependencies to the # test executables # ----------------------------------------------------------------------------- set(KIT VolumeRendering) set(TESTBASE ${PROJECT_NAME}${KIT}) # ----------------------------------------------------------------------------- # First, list all the tests that either use no data, or only data from the # VTKEdge data directory (which always exists since it is part of the # VTKEdge repository). These will go into one test executable. # ----------------------------------------------------------------------------- set(MyTests TestCompositeMask.cxx TestCompositeMaskBlend.cxx TestCompositeShadeMask.cxx TestGPURayCastCompositeToMIP.cxx TestGPURayCastDataTypesMIP.cxx TestGPURayCastDataTypesMinIP.cxx TestGPURayCastFourComponentsMIP.cxx TestGPURayCastFourComponentsMinIP.cxx TestGPURayCastFourComponentsComposite.cxx TestGPURayCastFourComponentsCompositeStreaming.cxx TestGPURayCastNearestDataTypesMIP.cxx TestGPURayCastMIPToComposite.cxx ) # add tests that require data from VTKData/Data if(VTK_DATA_ROOT) set(MyTestsWithVTKData TestGPURayCastCropping.cxx ) endif(VTK_DATA_ROOT) # Force to not enable floating point exception as we hit some exception # inside the OpenGL driver at vtkgl::LinkProgram() (nVidia 185.18.36). set(CMAKE_TESTDRIVER_BEFORE_TESTMAIN) set(CMAKE_TESTDRIVER_BEFORE_TESTMAIN "${CMAKE_TESTDRIVER_BEFORE_TESTMAIN} try {") create_test_sourcelist(Tests ${TESTBASE}CxxTests.cxx ${MyTests} ${MyTestsWithVTKData} EXTRA_INCLUDE vtkTestDriver.h ) add_executable(${TESTBASE}CxxTests ${Tests}) #install_targets(${VTKEdge_INSTALL_BIN_DIR} ${TESTBASE}CxxTests) target_link_libraries(${TESTBASE}CxxTests vtkRendering vtkIO vtkVolumeRendering vtkKWEGraphics vtkKWEVolumeRendering) set(TestsToRun ${Tests}) remove(TestsToRun ${TESTBASE}CxxTests.cxx ${MyTestsWithVTKData}) # Add all the executables foreach(test ${TestsToRun}) get_filename_component(TName ${test} NAME_WE) add_test(${TName} ${CXX_TEST_PATH}/${TESTBASE}CxxTests ${TName} -D ${PROJECT_SOURCE_DIR}/Data -T ${PROJECT_BINARY_DIR}/Testing/Temporary -V ${PROJECT_SOURCE_DIR}/Data/Baseline/${KIT}/${TName}.png ) endforeach(test) if(VTK_DATA_ROOT) foreach(test ${MyTestsWithVTKData}) get_filename_component(TName ${test} NAME_WE) add_test(${TName} ${CXX_TEST_PATH}/${TESTBASE}CxxTests ${TName} -D ${VTK_DATA_ROOT} -T ${PROJECT_BINARY_DIR}/Testing/Temporary -V ${PROJECT_SOURCE_DIR}/Data/Baseline/${KIT}/${TName}.png ) endforeach(test) endif(VTK_DATA_ROOT) vtkedge-0.2.0~20110819/VolumeRendering/Testing/CMakeLists.txt0000644000175000017500000000172311363410610023320 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Add the Cxx testing directory # ----------------------------------------------------------------------------- # There are no tests right now... #add_subdirectory(Cxx) vtkedge-0.2.0~20110819/VolumeRendering/vtkKWERepresentativeVolumeImageCreator.h0000644000175000017500000001734711363410610027074 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= //----------------------------------------------------------------------------- // .NAME vtkKWERepresentativeVolumeImageCreator - Create a representative // image given a volume and properties // .SECTION Description // vtkKWEResprentativeVolumeImageCreator is a class that will generate // reprentative images of a volume given some properties such as the // color and opacity transfer functions (contained in a vtkVolumeProperty), the // blending mode, and the input volume. It will create a representative image // of the requested size in a background thread. It is assumed that the Stop() // method will be called by the calling process before any of the input // parameters are modified. The IsComplete() method will return 0 if the // image is still being generated or if an error occurred, and 1 if the image // generation process is complete. The IsValid() method will return 1 if the // genterated image is valid, or 0 if an error occurred during the computation // (e.g. due to missing input parameters). // // .SECTION Limitations // - Works only on the scalars in the point data of the input // - Does not do gradient opacity //----------------------------------------------------------------------------- #ifndef __vtkKWERepresentativeVolumeImageCreator_h #define __vtkKWERepresentativeVolumeImageCreator_h #include "vtkObject.h" #include "VTKEdgeConfigure.h" // include configuration header #include "vtkVolumeMapper.h" // for definition of blend modes class vtkImageData; class vtkMultiThreader; class vtkMutexLock; class vtkRenderWindow; class vtkRenderWindowInteractor; class vtkVolumeProperty; // Forward declaration for friend //BTX VTK_THREAD_RETURN_TYPE vtkKWERVICGenerateImage(void *arg); class vtkKWERVICFriend; //ETX class VTKEdge_VOLUMERENDERING_EXPORT vtkKWERepresentativeVolumeImageCreator : public vtkObject { public: static vtkKWERepresentativeVolumeImageCreator *New(); vtkTypeRevisionMacro(vtkKWERepresentativeVolumeImageCreator,vtkObject); void PrintSelf( ostream& os, vtkIndent indent ); // Description: // Set the vtkVolumeProperty. This will be used for the various transfer // function, and the component information. void SetProperty(vtkVolumeProperty *p); // Description: // Get the current property vtkGetObjectMacro( Property, vtkVolumeProperty ); // Description: // Set/Get the blend mode. vtkSetMacro( BlendMode, int ); void SetBlendModeToComposite() { this->SetBlendMode( vtkVolumeMapper::COMPOSITE_BLEND ); } void SetBlendModeToMaximumIntensity() { this->SetBlendMode( vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND ); } void SetBlendModeToMinimumIntensity() { this->SetBlendMode( vtkVolumeMapper::MINIMUM_INTENSITY_BLEND ); } vtkGetMacro( BlendMode, int ); // Description: // Set the input volume void SetInput(vtkImageData *volume); // Description: // Get the input volume vtkGetObjectMacro( Input, vtkImageData ); // Description: // Start generating the image. This is a non-blocking operation - // the image will be generated in a background thread. Use // IsProcessing() to poll whether it is done, or register for // the End event. void Start(); // Description: // Stop generating the image. void Stop(); // Description: // Is this class still working on generating the image? A return value // of 1 means that the class is still actively processing the image. // Otherwise the return value will be 0. int IsProcessing(); // Description: // Is the generated image valid? This will return 0 if IsProcessing() // returns 1. It will also return 0 if an error occurred during // the last image creation attempt, or if no image has been created. // Otherwise it will return 1. int IsValid(); // Description: // Set the size of the representative image. The default value is // (0,0) which is invalid, so this must be set before calling Start(). // The width / height must be at least 1 and at most 1024. void SetRepresentativeImageSize( int w, int h ); void SetRepresentativeImageSize( int size[2] ) {this->SetRepresentativeImageSize(size[0], size[1]);} // Description: // Get the size of the representative image. A value of (0,0) means // the size was never set. vtkGetVectorMacro( RepresentativeImageSize, int, 3 ); // Description: // Get the representative image. Should only be called after // Start() has been called, and IsProcessing() is 0, and // IsValid() is 1. This will create a new vtkImageData that // the caller should immediately register since this class // will release its hold on it when Start() is called again. vtkImageData *GetRepresentativeImage(); // Description: // Select the side to view. An XSideView implied that the +X size // of the data is visible - the viewing direction is (-1, 0, 0). // The two sets of enumerated types are equivalent views using // different terminology (scientific X,Y,Z right handed coordinate // system vs. medical R, A, S left-handed coordinate system) vtkSetClampMacro( VisibleSide, int, vtkKWERepresentativeVolumeImageCreator::XSideView, vtkKWERepresentativeVolumeImageCreator::MinusZSideView ); // Description: // Get the visible side of the volume. See SetVisibleSide for further // clarification. vtkGetMacro( VisibleSide, int ); //BTX enum { XSideView=0, MinusXSideView, YSideView, MinusYSideView, ZSideView, MinusZSideView }; enum { LeftSideView=0, RightSideView, PosteriorSideView, AnteriorSideView, SuperiorSideView, InferiorSideView }; //ETX protected: vtkKWERepresentativeVolumeImageCreator(); ~vtkKWERepresentativeVolumeImageCreator(); friend VTK_THREAD_RETURN_TYPE vtkKWERVICGenerateImage(void *arg); friend class vtkKWERVICFriend; void GenerateImage( int *flag, vtkMutexLock *lock ); void ClearInternalParameters(); vtkVolumeProperty *Property; int BlendMode; vtkImageData *Input; vtkVolumeProperty *InternalProperty; int InternalBlendMode; vtkImageData *InternalInput; vtkImageData *RepresentativeImage; vtkMutexLock *RepresentativeImageIsValidLock; int RepresentativeImageIsValid; int RepresentativeImageSize[2]; int VisibleSide; vtkMultiThreader *Threader; int SpawnedThreadID; void ComputeFirstVoxel( int i, int j, float voxel[3] ); void ComputeRayIncrement( float increment[3] ); void CastRay( float voxel[3], float increment[3], unsigned char color[3] ); void UpdateTransferFunctions(double sampleDistance); double ComputeSampleDistance(float rayIncrement[3]); float TableOffset[4]; float TableScale[4]; float ColorTable[4][1024*3]; float OpacityTable[4][1024]; int TableComponents; int TableIndependentComponents; private: vtkKWERepresentativeVolumeImageCreator(const vtkKWERepresentativeVolumeImageCreator&); // Not implemented. void operator=(const vtkKWERepresentativeVolumeImageCreator&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/VTKEdgeConfig.cmake.in0000644000175000017500000001170311363410610020023 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= #----------------------------------------------------------------------------- # # VTKEdgeConfig.cmake - CMake configuration file for external projects. # # This file is configured by VTKEdge and used by the UseVTKEdge.cmake # module to load VTKEdge's settings for an external project. @VTKEdge_CONFIG_INSTALL_ONLY@ # The VTKEdge version number. set(VTKEdge_VERSION_MAJOR "@VTKEdge_VERSION_MAJOR@") set(VTKEdge_VERSION_MINOR "@VTKEdge_VERSION_MINOR@") set(VTKEdge_VERSION_BUILD "@VTKEdge_VERSION_BUILD@") set(VTKEdge_VERSION "@VTKEdge_VERSION@") # The libraries. set(VTKEdge_LIBRARIES "@VTKEdge_LIBRARIES@") # The CMake macros dir. set(VTKEdge_CMAKE_DIR "@VTKEdge_CMAKE_DIR_CONFIG@") # The configuration options. set(VTKEdge_BUILD_SHARED_LIBS "@VTKEdge_BUILD_SHARED_LIBS@") set(VTKEdge_BUILD_EXAMPLES "@VTKEdge_BUILD_EXAMPLES@") set(VTKEdge_BUILD_PARAVIEW_PLUGINS "@VTKEdge_BUILD_PARAVIEW_PLUGINS@") set(VTKEdge_USE_CUDA "@VTKEdge_USE_CUDA@") set(VTKEdge_USE_DIRECTX "@VTKEdge_USE_DIRECTX@") set(VTKEdge_USE_CORE_GRAPHICS "@VTKEdge_USE_CORE_GRAPHICS@") set(VTKEdge_USE_NVCONTROL "@VTKEdge_USE_NVCONTROL@") set(VTKEdge_USE_ITK "@VTKEdge_USE_ITK@") set(VTKEdge_AVAILABLE_KITS "@VTKEdge_AVAILABLE_KITS@") set(VTKEdge_ENABLED_KITS "@VTKEdge_ENABLED_KITS@") set(VTKEdge_BUILD_Common_KIT "@VTKEdge_BUILD_Common_KIT@") set(VTKEdge_BUILD_Filtering_KIT "@VTKEdge_BUILD_Filtering_KIT@") set(VTKEdge_BUILD_Graphics_KIT "@VTKEdge_BUILD_Graphics_KIT@") set(VTKEdge_BUILD_Hybrid_KIT "@VTKEdge_BUILD_Hybrid_KIT@") set(VTKEdge_BUILD_Imaging_KIT "@VTKEdge_BUILD_Imaging_KIT@") set(VTKEdge_BUILD_IO_KIT "@VTKEdge_BUILD_IO_KIT@") set(VTKEdge_BUILD_Rendering_KIT "@VTKEdge_BUILD_Rendering_KIT@") set(VTKEdge_BUILD_VolumeRendering_KIT "@VTKEdge_BUILD_VolumeRendering_KIT@") set(VTKEdge_BUILD_Widgets_KIT "@VTKEdge_BUILD_Widgets_KIT@") set(VTKEdge_PAINTBRUSH_LABEL_TYPE "@VTKEdge_PAINTBRUSH_LABEL_TYPE@") # The C and C++ flags added to the cmake-configured flags. set(VTKEdge_REQUIRED_C_FLAGS "@VTKEdge_REQUIRED_C_FLAGS@") set(VTKEdge_REQUIRED_CXX_FLAGS "@VTKEdge_REQUIRED_CXX_FLAGS@") set(VTKEdge_REQUIRED_EXE_LINKER_FLAGS "@VTKEdge_REQUIRED_EXE_LINKER_FLAGS@") set(VTKEdge_REQUIRED_SHARED_LINKER_FLAGS "@VTKEdge_REQUIRED_SHARED_LINKER_FLAGS@") set(VTKEdge_REQUIRED_MODULE_LINKER_FLAGS "@VTKEdge_REQUIRED_MODULE_LINKER_FLAGS@") # The "use" file. set(VTKEdge_USE_FILE "@VTKEdge_USE_FILE_CONFIG@") # The build settings file. set(VTKEdge_BUILD_SETTINGS_FILE "@VTKEdge_BUILD_SETTINGS_FILE_CONFIG@") # The library directories. set(VTKEdge_LIBRARY_DIRS "@VTKEdge_LIBRARY_DIRS_CONFIG@") # The runtime directories. # Note that if VTKEdge_CONFIGURATION_TYPES is set (see below) then # these directories will be the parent directories under which there will # be a directory of runtime binaries for each configuration type. set(VTKEdge_RUNTIME_DIRS "@VTKEdge_RUNTIME_DIRS_CONFIG@") # The include directories. set(VTKEdge_INCLUDE_DIRS "@VTKEdge_INCLUDE_DIRS_CONFIG@") # The library dependencies file. if(NOT VTKEdge_NO_LIBRARY_DEPENDS AND EXISTS "@VTKEdge_LIBRARY_DEPENDS_FILE@") include("@VTKEdge_LIBRARY_DEPENDS_FILE@") endif(NOT VTKEdge_NO_LIBRARY_DEPENDS AND EXISTS "@VTKEdge_LIBRARY_DEPENDS_FILE@") # The VTK options. set(VTKEdge_VTK_DIR "@VTKEdge_VTK_DIR_CONFIG@") # An install tree always provides one build configuration. # A build tree may provide either one or multiple build # configurations depending on the CMake generator used. Since # this project can be used either from a build tree or an install tree it # is useful for outside projects to know the configurations available. # If this VTKEdgeConfig.cmake is in an install tree # VTKEdge_CONFIGURATION_TYPES will be empty and VTKEdge_BUILD_TYPE # will be set to the value of CMAKE_BUILD_TYPE used to build # VTKEdge. If VTKEdgeConfig.cmake is in a build tree # then VTKEdge_CONFIGURATION_TYPES and VTKEdge_BUILD_TYPE will # have values matching CMAKE_CONFIGURATION_TYPES and CMAKE_BUILD_TYPE # for that build tree (only one will ever be set). set(VTKEdge_CONFIGURATION_TYPES @VTKEdge_CONFIGURATION_TYPES_CONFIG@) set(VTKEdge_BUILD_TYPE @VTKEdge_BUILD_TYPE_CONFIG@) vtkedge-0.2.0~20110819/UseVTKEdge.cmake0000644000175000017500000000457511363410610016756 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # # This module is provided as VTKEdge_USE_FILE by VTKEdgeConfig.cmake. # It can be INCLUDEd in a project to load the needed compiler and linker # settings to use VTKEdge: # find_package(VTKEdge REQUIRED) # include(${VTKEdge_USE_FILE}) # if(NOT VTKEdge_USE_FILE_INCLUDED) set(VTKEdge_USE_FILE_INCLUDED 1) # Load the compiler settings used for VTKEdge. if(VTKEdge_BUILD_SETTINGS_FILE) include(${CMAKE_ROOT}/Modules/CMakeImportBuildSettings.cmake) cmake_import_build_settings(${VTKEdge_BUILD_SETTINGS_FILE}) endif(VTKEdge_BUILD_SETTINGS_FILE) # Add compiler flags needed to use VTKEdge. set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${VTKEdge_REQUIRED_C_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${VTKEdge_REQUIRED_CXX_FLAGS}") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${VTKEdge_REQUIRED_EXE_LINKER_FLAGS}") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${VTKEdge_REQUIRED_SHARED_LINKER_FLAGS}") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${VTKEdge_REQUIRED_MODULE_LINKER_FLAGS}") # Add include directories needed to use VTKEdge. include_directories(${VTKEdge_INCLUDE_DIRS}) # Add link directories needed to use VTKEdge. link_directories(${VTKEdge_LIBRARY_DIRS}) # Add cmake module path. set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${VTKEdge_CMAKE_DIR}") # Use VTK. if(NOT VTKEdge_NO_USE_VTK) set(VTK_DIR ${VTKEdge_VTK_DIR}) find_package(VTK) if(VTK_FOUND) include(${VTK_USE_FILE}) else(VTK_FOUND) message("VTK not found in VTKEdge_VTK_DIR=\"${VTKEdge_VTK_DIR}\".") endif(VTK_FOUND) endif(NOT VTKEdge_NO_USE_VTK) endif(NOT VTKEdge_USE_FILE_INCLUDED) vtkedge-0.2.0~20110819/CTestConfig.cmake0000644000175000017500000000171011363410610017204 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= set(CTEST_PROJECT_NAME "VTKEdge") set(CTEST_NIGHTLY_START_TIME "01:00:00 UTC") set(CTEST_DROP_METHOD "http") set(CTEST_DROP_SITE "kitware.com") set(CTEST_DROP_LOCATION "/CDash/submit.php?project=VTKEdge") set(CTEST_DROP_SITE_CDASH TRUE) vtkedge-0.2.0~20110819/CMakeLists.txt0000644000175000017500000003521011363410610016574 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Set the minimum required cmake version. Setting here to 2.4, but really # 2.7 is required for testing with bullseye coverage. Will change to 2.8 once # it is officially released # ----------------------------------------------------------------------------- cmake_minimum_required(VERSION 2.4) project(VTKEdge) # ----------------------------------------------------------------------------- # Set cmake policy CMP0003 to NEW. This means cmake will not break up linked # libraries into separate linker search paths and library names. # ----------------------------------------------------------------------------- if(COMMAND CMAKE_POLICY) cmake_policy(SET CMP0003 NEW) endif(COMMAND CMAKE_POLICY) # ----------------------------------------------------------------------------- # VTKEdge version number. An even minor number corresponds to a release # ----------------------------------------------------------------------------- set(VTKEdge_VERSION_MAJOR 0) set(VTKEdge_VERSION_MINOR 1) set(VTKEdge_VERSION_BUILD 0) set(VTKEdge_VERSION "${VTKEdge_VERSION_MAJOR}.${VTKEdge_VERSION_MINOR}.${VTKEdge_VERSION_BUILD}") # ----------------------------------------------------------------------------- # Setup the output paths # Remark: # Make sure this section appears before FIND_PACKAGE(VTK) statement. # In case FIND_PACKAGE(VTK) statement is used before the following lines and # fails for any reason, EXECUTABLE_OUTPUT_PATH is set to empty, as it is a # cached variable there would be no change it takes ${PROJECT_BINARY_DIR}/bin # as its default value. # Reminder: # EXECUTABLE_OUTPUT_PATH is no longer used in Cmake 2.6. The day the minimum # requirement moves from 2.4 to 2.6, it should be replaced by the use of # RUNTIME_OUTPUT_DIRECTORY target property. # ----------------------------------------------------------------------------- set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin CACHE PATH "Single output directory for building all libraries.") set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin CACHE PATH "Single output directory for building all executables.") mark_as_advanced(LIBRARY_OUTPUT_PATH EXECUTABLE_OUTPUT_PATH) set(VTKEdge_LIBRARY_DIRS ${LIBRARY_OUTPUT_PATH}) set(VTKEdge_RUNTIME_DIRS ${LIBRARY_OUTPUT_PATH}) # Set CXX_TEST_PATH, bullet-proof to empty EXECUTABLE_OUTPUT_PATH. if(EXECUTABLE_OUTPUT_PATH) set(CXX_TEST_PATH "${EXECUTABLE_OUTPUT_PATH}") else(EXECUTABLE_OUTPUT_PATH) set(CXX_TEST_PATH ".") endif(EXECUTABLE_OUTPUT_PATH) # ----------------------------------------------------------------------------- # Disable deprecation warnings for standard C and STL functions in VS2005 and # later (no, we don't need IF(CMAKE_COMPILER_2005) ... ) # ----------------------------------------------------------------------------- add_definitions(-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE) add_definitions(-D_SCL_SECURE_NO_DEPRECATE) # ----------------------------------------------------------------------------- # Bring our CMake modules to the CMake path # ----------------------------------------------------------------------------- set(VTKEdge_CMAKE_DIR "${VTKEdge_SOURCE_DIR}/CMake" CACHE INTERNAL "") set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${VTKEdge_CMAKE_DIR}") add_subdirectory(CMake) # ----------------------------------------------------------------------------- # Setup the installation settings # ----------------------------------------------------------------------------- set(VTKEdge_CONFIGURATION_TYPES ${CMAKE_CONFIGURATION_TYPES}) set(VTK_INSTALL_NO_DEVELOPMENT ON) # why? if(NOT VTKEdge_INSTALL_BIN_DIR) set(VTKEdge_INSTALL_BIN_DIR "/bin") endif(NOT VTKEdge_INSTALL_BIN_DIR) if(NOT VTKEdge_INSTALL_LIB_DIR) set(VTKEdge_INSTALL_LIB_DIR "/lib/${PROJECT_NAME}") endif(NOT VTKEdge_INSTALL_LIB_DIR) if(NOT VTKEdge_INSTALL_DATA_DIR) set(VTKEdge_INSTALL_DATA_DIR "/share/${PROJECT_NAME}" CACHE INTERNAL "") endif(NOT VTKEdge_INSTALL_DATA_DIR) if(NOT VTKEdge_INSTALL_INCLUDE_DIR) set(VTKEdge_INSTALL_INCLUDE_DIR "/include/${PROJECT_NAME}") endif(NOT VTKEdge_INSTALL_INCLUDE_DIR) if(NOT VTKEdge_INSTALL_PACKAGE_DIR) set(VTKEdge_INSTALL_PACKAGE_DIR ${VTKEdge_INSTALL_LIB_DIR} CACHE INTERNAL "") endif(NOT VTKEdge_INSTALL_PACKAGE_DIR) if(NOT VTKEdge_VTK_INSTALL_PACKAGE_DIR) set(VTKEdge_VTK_INSTALL_PACKAGE_DIR ${VTK_INSTALL_PACKAGE_DIR}) endif(NOT VTKEdge_VTK_INSTALL_PACKAGE_DIR) if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) set(VTKEdge_INSTALL_NO_DEVELOPMENT 0) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) if(NOT VTKEdge_INSTALL_NO_RUNTIME) set(VTKEdge_INSTALL_NO_RUNTIME 0) endif(NOT VTKEdge_INSTALL_NO_RUNTIME) if(NOT VTKEdge_INSTALL_NO_DOCUMENTATION) set(VTKEdge_INSTALL_NO_DOCUMENTATION 0) endif(NOT VTKEdge_INSTALL_NO_DOCUMENTATION) set(VTKEdge_INSTALL_NO_LIBRARIES) if(VTKEdge_BUILD_SHARED_LIBS) if(VTKEdge_INSTALL_NO_RUNTIME AND VTKEdge_INSTALL_NO_DEVELOPMENT) set(VTKEdge_INSTALL_NO_LIBRARIES 1) endif(VTKEdge_INSTALL_NO_RUNTIME AND VTKEdge_INSTALL_NO_DEVELOPMENT) else(VTKEdge_BUILD_SHARED_LIBS) if(VTKEdge_INSTALL_NO_DEVELOPMENT) set(VTKEdge_INSTALL_NO_LIBRARIES 1) endif(VTKEdge_INSTALL_NO_DEVELOPMENT) endif(VTKEdge_BUILD_SHARED_LIBS) # ----------------------------------------------------------------------------- # Include CTest for testing # ----------------------------------------------------------------------------- include(CTest) # ----------------------------------------------------------------------------- # Add in the option for building examples, default to ON # If BUILD_EXAMPLES was set by a larger project, use it. # ----------------------------------------------------------------------------- option(VTKEdge_BUILD_EXAMPLES "Build VTKEdge examples." ${BUILD_EXAMPLES}) # ----------------------------------------------------------------------------- # Find VTK - it is a required package # ----------------------------------------------------------------------------- find_package(VTK REQUIRED) include(${VTK_USE_FILE}) # ----------------------------------------------------------------------------- # Find ITK - it is an optional package that if present allows the usage of # complex paintbrush operations in Widgets/ such as flood fill # paintbrushes etc. # If you are using VTKEdge as a subproject within your project, and you want # to enable/disable the use of ITK, just set VTKEdge_USE_ITK_DEFAULT from your # top level directory # ----------------------------------------------------------------------------- SET(default_val 0) IF(DEFINED VTKEdge_USE_ITK_DEFAULT) SET(default_val ${VTKEdge_USE_ITK_DEFAULT}) ENDIF(DEFINED VTKEdge_USE_ITK_DEFAULT) OPTION(VTKEdge_USE_ITK "Build filtered brush widgets that require ITK" ${default_val}) MARK_AS_ADVANCED(VTKEdge_USE_ITK) IF(VTKEdge_USE_ITK) IF(NOT ITK_SOURCE_DIR) FIND_PACKAGE(ITK REQUIRED) IF(ITK_FOUND) INCLUDE(${ITK_USE_FILE}) ENDIF(ITK_FOUND) ENDIF(NOT ITK_SOURCE_DIR) ENDIF(VTKEdge_USE_ITK) # ----------------------------------------------------------------------------- # Find CUDA # ----------------------------------------------------------------------------- option(VTKEdge_USE_CUDA "Use NVIDIAs CUDA library." OFF) if(VTKEdge_USE_CUDA) find_package(Cuda) endif(VTKEdge_USE_CUDA) # ----------------------------------------------------------------------------- # Add an option for building shared - default to the same choice made for VTK # BUILD_SHARED_LIBS is a builtin cmake variable. # ----------------------------------------------------------------------------- option(BUILD_SHARED_LIBS "Build with shared libraries." ${VTK_BUILD_SHARED_LIBS}) # Set VTKEdge_BUILD_SHARED_LIBS to 1 or 0 for use in creating the # configuration header. if(BUILD_SHARED_LIBS) set(VTKEdge_BUILD_SHARED_LIBS 1) else(BUILD_SHARED_LIBS) set(VTKEdge_BUILD_SHARED_LIBS 0) endif(BUILD_SHARED_LIBS) # ----------------------------------------------------------------------------- # Configure VTK_DATA_ROOT for the location of VTKData. VTKData is required for # some examples and tests. Check this directory, up one, and up two. # ----------------------------------------------------------------------------- find_path(VTK_DATA_ROOT VTKData.readme ${VTKEdge_SOURCE_DIR}/VTKData ${VTKEdge_SOURCE_DIR}/../VTKData ${VTKEdge_SOURCE_DIR}/../../VTKData ${VTKEdge_SOURCE_DIR}/../VTK/VTKData ${VTKEdge_SOURCE_DIR}/../../VTK/VTKData $ENV{VTK_DATA_ROOT} ) # ----------------------------------------------------------------------------- # Enable kits # ----------------------------------------------------------------------------- set(VTKEdge_AVAILABLE_KITS Common Filtering Hybrid Imaging IO Rendering VolumeRendering Widgets ) set(VTKEdge_ENABLED_KITS) set(VTKEdge_RELATIVE_INCLUDE_DIRS) set(libraries) set(include_paths) foreach(kit ${VTKEdge_AVAILABLE_KITS}) if(DEFINED VTKEdge_BUILD_${kit}_KIT_DEFAULT) set(default_val ${VTKEdge_BUILD_${kit}_KIT_DEFAULT}) else(DEFINED VTKEdge_BUILD_${kit}_KIT_DEFAULT) set(default_val 1) endif(DEFINED VTKEdge_BUILD_${kit}_KIT_DEFAULT) option(VTKEdge_BUILD_${kit}_KIT "Build VTKEdge ${kit} kit." ${default_val}) mark_as_advanced(VTKEdge_BUILD_${kit}_KIT) if(VTKEdge_BUILD_${kit}_KIT) set(VTKEdge_ENABLED_KITS ${VTKEdge_ENABLED_KITS} ${kit}) set(libraries ${libraries} vtkKWE${kit}) set(VTKEdge_RELATIVE_INCLUDE_DIRS ${VTKEdge_RELATIVE_INCLUDE_DIRS} ${kit}) set(include_paths ${include_paths} ${VTKEdge_SOURCE_DIR}/${kit}) endif(VTKEdge_BUILD_${kit}_KIT) endforeach(kit) set(include_paths ${include_paths} ${PROJECT_BINARY_DIR}) set(VTKEdge_INCLUDE_PATH ${include_paths} CACHE INTERNAL "Include paths for VTKEdge") set(VTKEdge_LIBRARIES ${libraries} CACHE INTERNAL "Libraries for VTKEdge") include_directories(${VTKEdge_INCLUDE_PATH}) # Find the VTK_VERSION_DATE. The widgets have code so as to deal with changes # in VTK both before and after the Depth peeling compatibility changes. FIND_FILE(VTK_VERSION_FILENAME "vtkVersion.h" ${VTK_INCLUDE_DIRS}) MARK_AS_ADVANCED(VTK_VERSION_FILENAME) FILE(READ ${VTK_VERSION_FILENAME} VTK_VERSION_FILE) FIND_FILE(VTK_DATE_STAMP_FILENAME "vtksys/DateStamp.h" ${VTK_INCLUDE_DIRS}) IF(EXISTS ${VTK_DATE_STAMP_FILENAME}) FILE(READ ${VTK_DATE_STAMP_FILENAME} VTK_DATE_STAMP_FILE) SET( VTK_VERSION_FILE ${VTK_VERSION_FILE} ${VTK_DATE_STAMP_FILE}) ENDIF(EXISTS ${VTK_DATE_STAMP_FILENAME}) STRING(REGEX MATCH "[0-9][0-9][0-9][0-9][/|-][0-9][0-9][/|-][0-9][0-9]" VTKEdge_VTK_VERSION_DATE ${VTK_VERSION_FILE}) STRING(REGEX REPLACE "[/|-]" "" VTKEdge_VTK_VERSION_DATE ${VTKEdge_VTK_VERSION_DATE}) # ----------------------------------------------------------------------------- # The configured header file used to pass CMake settings to the source code. # DO NOT DEFINE ANY OPTION AFTER THIS SECTION # Here we configure the .in file to form the .h, that is then stored in the # binary directory - so we'll need to add that in the include path # As the config file depends on VTKEdge_BUILD_SHARED_LIBS and VTKedge version # number, make sure to place this statement after them. # ----------------------------------------------------------------------------- configure_file( "${PROJECT_SOURCE_DIR}/VTKEdgeConfigure.h.in" "${PROJECT_BINARY_DIR}/VTKEdgeConfigure.h" ) if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_INCLUDE_DIR} FILES ${VTKEdge_BINARY_DIR}/VTKEdgeConfigure.h) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) # ----------------------------------------------------------------------------- # Dashboard options. # ----------------------------------------------------------------------------- configure_file(${VTKEdge_CMAKE_DIR}/CTestCustom.cmake.in ${PROJECT_BINARY_DIR}/CTestCustom.cmake @ONLY) # ----------------------------------------------------------------------------- # Testing # ----------------------------------------------------------------------------- if(BUILD_TESTING) make_directory(${PROJECT_BINARY_DIR}/Testing/Temporary) endif(BUILD_TESTING) # Leave this option ON by default. It helps to catch floating point math # exceptions early on nightly dashboard runs. option(VTKEdge_TESTING_USE_FPE "VTKEdge tests call vtkFloatingPointExceptions::Enable()" ON) mark_as_advanced(VTKEdge_TESTING_USE_FPE) set(CMAKE_TESTDRIVER_BEFORE_TESTMAIN) if(VTKEdge_TESTING_USE_FPE) set(CMAKE_TESTDRIVER_BEFORE_TESTMAIN "${CMAKE_TESTDRIVER_BEFORE_TESTMAIN} vtkFloatingPointExceptions::Enable();\n") endif() set(CMAKE_TESTDRIVER_BEFORE_TESTMAIN "${CMAKE_TESTDRIVER_BEFORE_TESTMAIN} try {") SET(CMAKE_TESTDRIVER_AFTER_TESTMAIN " } catch(vtkstd::exception& e) { fprintf(stderr, \"Test driver caught exception: [%s]\\n\", e.what()); result = -1; }") # ----------------------------------------------------------------------------- # Add each kit's directory # DO NOT DEFINE ANY OPTION AFTER THIS SECTION THAT COULD BE USED # BY A KIT (add_subdirectory is executed *now*) # ----------------------------------------------------------------------------- foreach(kit ${VTKEdge_ENABLED_KITS}) add_subdirectory(${kit}) endforeach(kit) # ----------------------------------------------------------------------------- # Build the examples if they are turned on # ----------------------------------------------------------------------------- if(VTKEdge_BUILD_EXAMPLES) set(VTKEdge_EXAMPLE_EXECUTABLE_PREFIX ${PROJECT_NAME}) add_subdirectory(Examples) endif(VTKEdge_BUILD_EXAMPLES) # ----------------------------------------------------------------------------- # Build the documentation # ----------------------------------------------------------------------------- add_subdirectory(Utilities/Doxygen) # ----------------------------------------------------------------------------- # Build the Paraview plugins # ----------------------------------------------------------------------------- add_subdirectory(ParaViewPlugins) # -------------------------------------------------------------------------- # Configure the export configuration files # -------------------------------------------------------------------------- include(${CMAKE_CURRENT_SOURCE_DIR}/ExportConfiguration.cmake) vtkedge-0.2.0~20110819/Examples/0000755000175000017500000000000011630435007015615 5ustar mathieumathieuvtkedge-0.2.0~20110819/Examples/Rendering/0000755000175000017500000000000011630435007017532 5ustar mathieumathieuvtkedge-0.2.0~20110819/Examples/Rendering/Cxx/0000755000175000017500000000000011630435007020274 5ustar mathieumathieuvtkedge-0.2.0~20110819/Examples/Rendering/Cxx/CMakeLists.txt0000644000175000017500000000133111363410610023026 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= vtkedge-0.2.0~20110819/Examples/Rendering/CMakeLists.txt0000644000175000017500000000166211363410610022273 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Just add all the subdirectories # ----------------------------------------------------------------------------- add_subdirectory(Cxx) vtkedge-0.2.0~20110819/Examples/GUI/0000755000175000017500000000000011630435007016241 5ustar mathieumathieuvtkedge-0.2.0~20110819/Examples/GUI/CMakeLists.txt0000644000175000017500000000233111363410610020774 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= option(VTKEdge_BUILD_KWWidgets_EXAMPLES "Build examples that use the KWWidgets libraries." OFF) if (VTKEdge_BUILD_KWWidgets_EXAMPLES) IF(NOT KWWidgets_SOURCE_DIR) FIND_PACKAGE(KWWidgets REQUIRED) IF(NOT KWWidgets_FOUND) MESSAGE(FATAL_ERROR "KWWidgets is required to build the these examples. Plase specify KWWidgets_DIR") ENDIF(NOT KWWidgets_FOUND) INCLUDE(${KWWidgets_USE_FILE}) ENDIF(NOT KWWidgets_SOURCE_DIR) SUBDIRS( KWWidgets ) endif (VTKEdge_BUILD_KWWidgets_EXAMPLES) vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/0000755000175000017500000000000011630435007020111 5ustar mathieumathieuvtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/PaintbrushExample4.cxx0000644000175000017500000001543411363410610024357 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This example differs from PaintbrushExample3 in that it renders the brush in // as contours. Note while drawing the increased resolution obtained as a // result. Note also the differences in the way in which the paintbrush data // is set as the initial segmentation below. // // The abstract class vtkKWEPaintbrushData has two concrete subclasses : // vtkKWEPaintbrushStencilData and vtkPaintrushGrayscaleData. This example uses // the latter. // // Aside from the aforementioned difference, follow the documentation of the // previous example. #include "vtkKWMyWindow.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentationGrayscale2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include KWLIBS_CREATE_EXAMPLE // Macro fires up a basic app with some data void MySelectEditCallbackMethod( vtkKWEPaintbrushWidget *w, int editMode ) { w->SetPaintbrushMode( editMode ? vtkKWEPaintbrushWidget::Edit : vtkKWEPaintbrushWidget::Select ); } int my_example( int argc, char *argv[], vtkKWApplication * , vtkKWMyWindow * example ) { example->Initialize(); vtkImageData * imageData = example->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( example->GetNthRenderWidget(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentationGrayscale2D * rep = vtkKWEPaintbrushRepresentationGrayscale2D::New(); w->SetRepresentation(rep); if (rep) { vtkImageActor * imageActor = example->GetNthImageActor(i); rep->SetImageActor(imageActor); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } // This will simply cause the method // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Edit ) or // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Select ) // to be invoked based on which radio button is depressed. example->SetSelectEditCallbackMethod( MySelectEditCallbackMethod ); example->AddSelectEditCallback(w); set->AddWidget(w); rep->Delete(); w->Delete(); } vtkKWEPaintbrushRepresentation2D * repx = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawingx = repx->GetPaintbrushDrawing(); for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawingx ); } // Now read in an initial segmentation. typedef vtksys::CommandLineArguments argT; argT arg; arg.Initialize(argc, argv); std::string * filename = NULL, fn; arg.AddArgument("--initial_segmentation", argT::SPACE_ARGUMENT, filename, "Initial segmentation"); arg.Parse(); if (!filename) { vtkstd::vector< vtksys_stl::string > stringArray; stringArray.push_back(vtkKWMyWindow::GetExampleDataPath()); stringArray.push_back("Ventricles.mha"); fn = vtksys::SystemTools::JoinPath(stringArray); vtksys::SystemTools::ConvertToUnixSlashes(fn); filename = &fn; } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); drawing->InitializeData(); vtkKWEPaintbrushGrayscaleData *data = vtkKWEPaintbrushGrayscaleData::New(); if (filename && vtksys::SystemTools::FileExists( filename->c_str())) { // Read the file vtkMetaImageReader * reader = vtkMetaImageReader::New(); reader->SetFileName( filename->c_str() ); reader->Update(); data->SetImageData(reader->GetOutput()); reader->Delete(); // Set the first stroke as the initial segmentation. drawing->AddNewStroke(0, vtkKWEPaintbrushEnums::Draw, data); // Instead of the above line, you can set this directly as the new stencil, // saves some memory, as the overhead data of an extra stroke need not be // managed. // drawing->SetPaintbrushData(data); for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation * repr = vtkKWEPaintbrushRepresentation::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } } set->SetEnabled(1); int res = example->Run(); // Save out the resulting segmentation. // vtkImageData * output = vtkImageData::New(); drawing->GetPaintbrushData()-> GetPaintbrushDataAsImageData( output ); vtkMetaImageWriter * outputWriter = vtkMetaImageWriter::New(); outputWriter->SetFileName("Drawing.mha"); outputWriter->SetInput( output ); outputWriter->Write(); // Save out each of the resulting segmentations. // for (int i = 0; i < drawing->GetNumberOfItems(); i++) { vtkImageData * outputN = vtkImageData::New(); drawing->GetItem(i)->GetPaintbrushData()-> GetPaintbrushDataAsImageData( outputN ); vtkMetaImageWriter * outputWriterN = vtkMetaImageWriter::New(); std::ostringstream filenameN; filenameN << "Drawing" << i << ".mha" << std::ends; outputWriterN->SetFileName(filenameN.str().c_str()); outputWriterN->SetInput( outputN ); outputWriterN->Write(); outputWriterN->Delete(); outputN->Delete(); } data->Delete(); outputWriter->Delete(); output->Delete(); set->Delete(); return res; } vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/PaintbrushExample5.cxx0000644000175000017500000000661011363410610024354 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // PaintbrushData drawn can be filtered through "operations". These are // represented by abstract base classes: vtkKWEPaintbrushOperation. The base // class acts as a pass through filter. Concrete subclasses can do fancy // filtering operations such as flood-fill etc. These operations permit an // inplace filtering of a paintbrush data during a sketch. // // As an example, a flood-fill operation is implemented in // vtkKWEITKConfidenceConnectedPaintbrushOperation. This uses a combination of ITK // region growing and hole-filling filters. This example illustrates how to // plug an operation into the paintbrush widget. #include "vtkKWMyWindow.h" #include "VTKEdgeConfigure.h" // export #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEITKConfidenceConnectedPaintbrushOperation.h" #include "vtkKWEWidgetGroup.h" KWLIBS_CREATE_EXAMPLE // Macro fires up a basic app with some data int my_example( int , char *[], vtkKWApplication * , vtkKWMyWindow * example ) { example->Initialize(); vtkImageData * imageData = example->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); vtkKWEITKConfidenceConnectedPaintbrushOperation * operation = vtkKWEITKConfidenceConnectedPaintbrushOperation::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( example->GetNthRenderWidget(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); rep->SetImageActor( example->GetNthImageActor(i) ); // Note that an operation if set, must be set before the image data. rep->SetPaintbrushOperation(operation); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); set->AddWidget(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } set->SetEnabled(1); int res = example->Run(); operation->Delete(); set->Delete(); return res; } vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/PaintbrushExample3.cxx0000644000175000017500000001624111363410610024353 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This example shows how you can initialize the paintbrush with several initial // segmentation. It also demonstrates how you can save the final segmentation. // A user-defined segmentation can be added to the existing segmentation, at // any time, (not just to initialize the paintbrush data). // // The initial segmentation file used here is "Ventricles.mhd" should, of course // have the same metadata as the input image. In this example, the segmentation is // added as a new stroke, so it is possible to undo-redo it. Note that this allows // you to actually compose multiple segmentations as : // // drawing->AddItem( sketch1 ); // sketch1->AddNewStroke( vtkKWEPaintbrushEnums::Draw, stencilData1 ); // drawing->AddItem( sketch2 ); // sketch2->AddNewStroke( vtkKWEPaintbrushEnums::Draw, stencilData2 ); // // It also allows you to add to an existing segmentation as : // sketch2->AddNewStroke( vtkKWEPaintbrushEnums::Draw, stencilData3 ); // // The example demonstrates writing out the final segmentations as // DrawingN.mha #include "vtkKWMyWindow.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include KWLIBS_CREATE_EXAMPLE // Macro fires up a basic app with some data void MySelectEditCallbackMethod( vtkKWEPaintbrushWidget *w, int editMode ) { w->SetPaintbrushMode( editMode ? vtkKWEPaintbrushWidget::Edit : vtkKWEPaintbrushWidget::Select ); } int my_example( int , char *[], vtkKWApplication * , vtkKWMyWindow * example ) { vtkMetaImageReader * reader; example->SetFilename( vtkKWMyWindow::ExpandFilename("brainweb1e1a10f20.mha").c_str()); example->Initialize(); vtkImageData * imageData = example->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( example->GetNthRenderWidget(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); if (rep) { vtkImageActor * imageActor = example->GetNthImageActor(i); rep->SetImageActor(imageActor); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } // This will simply cause the method // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Edit ) or // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Select ) // to be invoked based on which radio button is depressed. example->SetSelectEditCallbackMethod( MySelectEditCallbackMethod ); example->AddSelectEditCallback(w); set->AddWidget(w); w->Delete(); } // Now read in an initial segmentation. vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); drawing->InitializeData(); // Clear the drawing and start on a clean slate. The drawing would have // automatically created an empty sketch for us, so we can start drawing // right away. We will wipe it all off. drawing->RemoveAllItems(); // ----- Segmentation 1 ------- // Read segmentation and create binary data out of it. vtkKWEPaintbrushStencilData *stencilData1 = vtkKWEPaintbrushStencilData::New(); reader = vtkMetaImageReader::New(); reader->SetFileName( vtkKWMyWindow::ExpandFilename("LRVentricles.mha").c_str() ); reader->Update(); vtkKWEPaintbrushUtilities::GetStencilFromImage< vtkKWEPaintbrushUtilities::vtkFunctorGreaterThanEqualTo >( reader->GetOutput(), stencilData1->GetImageStencilData(), 128.0); reader->Delete(); // Now create a sketch. // Add the segmentation to the sketch, as a stroke. // Add the sketch to drawing. vtkKWEPaintbrushSketch * sketch1 = vtkKWEPaintbrushSketch::New(); drawing->AddItem( sketch1 ); sketch1->AddNewStroke( vtkKWEPaintbrushEnums::Draw, stencilData1 ); sketch1->Delete(); // ----- Segmentation 2 ------- // Read segmentation and create binary data out of it. vtkKWEPaintbrushStencilData *stencilData2 = vtkKWEPaintbrushStencilData::New(); reader = vtkMetaImageReader::New(); reader->SetFileName( vtkKWMyWindow::ExpandFilename("WhiteMatter.mha").c_str() ); reader->Update(); vtkKWEPaintbrushUtilities::GetStencilFromImage< vtkKWEPaintbrushUtilities::vtkFunctorGreaterThanEqualTo >( reader->GetOutput(), stencilData2->GetImageStencilData(), 128.0); reader->Delete(); // Now create a sketch. // Add the segmentation to the sketch, as a stroke. // Add the sketch to drawing. vtkKWEPaintbrushSketch * sketch2 = vtkKWEPaintbrushSketch::New(); drawing->AddItem( sketch2 ); sketch2->AddNewStroke( vtkKWEPaintbrushEnums::Draw, stencilData2 ); sketch2->Delete(); // Now set the drawing on all representations. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } // Enable the widget and we are done. set->SetEnabled(1); int res = example->Run(); // Save out each of the resulting segmentations. We will write out each // sketch in the drawing as a seperate file. for (int i = 0; i < drawing->GetNumberOfItems(); i++) { vtkImageData * outputN = vtkImageData::New(); drawing->GetItem(i)->GetPaintbrushData()-> GetPaintbrushDataAsImageData( outputN ); vtkMetaImageWriter * outputWriterN = vtkMetaImageWriter::New(); std::ostringstream filenameN; filenameN << "Drawing" << i << ".mha" << std::ends; outputWriterN->SetFileName(filenameN.str().c_str()); outputWriterN->SetInput( outputN ); outputWriterN->Write(); outputWriterN->Delete(); outputN->Delete(); } stencilData1->Delete(); stencilData2->Delete(); set->Delete(); return res; } vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/vtkKWMyWindow.cxx0000644000175000017500000004655611363410610023415 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWMyWindow.h" #include "vtkBMPReader.h" #include "vtkCommand.h" #include "vtkImageReader2.h" #include "vtkImageReader2Factory.h" #include "vtkImageViewer2.h" #include "vtkMetaImageReader.h" #include "vtkObjectFactory.h" #include "vtkPNGReader.h" #include "vtkPNMReader.h" #include "vtkToolkits.h" #include "vtkXMLImageDataReader.h" #include "vtkCollection.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWDialog.h" #include "vtkKWFrame.h" #include "vtkKWFrameWithLabel.h" #include "vtkKWListBox.h" #include "vtkKWMenu.h" #include "vtkKWMenuButton.h" #include "vtkKWMenuButtonWithSpinButtons.h" #include "vtkKWMenuButtonWithSpinButtonsWithLabel.h" #include "vtkKWNotebook.h" #include "vtkKWScaleWithEntry.h" #include "vtkKWSelectionFrame.h" #include "vtkKWSelectionFrameLayoutManager.h" #include "vtkKWText.h" #include "vtkKWTextWithScrollbars.h" #include "vtkKWTextWithScrollbarsWithLabel.h" #include "vtkKWWindow.h" #include "vtkKWRadioButton.h" #include "vtkKWRadioButtonSet.h" #include "vtksys/ios/sstream" static const char *vtkKWMyWindowWidgetStrings[] = { "Axial", "Coronal", "Sagittal", "Blank", NULL }; //---------------------------------------------------------------------------- vtkStandardNewMacro( vtkKWMyWindow ); vtkCxxRevisionMacro(vtkKWMyWindow, "$Revision: 1774 $"); vtkCxxSetObjectMacro( vtkKWMyWindow, Input, vtkImageData ); //---------------------------------------------------------------------------- vtkKWMyWindow::vtkKWMyWindow() { this->SelectionFrameLayoutManager = vtkKWSelectionFrameLayoutManager::New(); this->SelectionFrame = vtkKWSelectionFrame::New(); this->SelectionFrame->SetTitle( vtkKWMyWindowWidgetStrings[0] ); this->SelectionFrame->AllowChangeTitleOff(); for (int i = 0; i < 3; i++) { this->ImageViewer[i] = vtkImageViewer2::New(); this->SliceScale[i] = vtkKWScaleWithEntry::New(); } this->Filename = NULL; this->FourPaneView = 1; this->Window = NULL; this->Input = NULL; this->InfoDialog = vtkKWDialog::New(); this->InfoDialog->ModalOff(); this->CxxSourceText = vtkKWTextWithScrollbarsWithLabel::New(); this->SelectEditRadioButtons = NULL; this->Widgets = vtkCollection::New(); } //---------------------------------------------------------------------------- vtkKWMyWindow::~vtkKWMyWindow() { for (int i = 0; i < 3; i++) { this->ImageViewer[i]->Delete(); this->SliceScale[i]->Delete(); } // TODO I don't know why the following 6 lines are necessary, but their absence // causes a warning "A TkRenderWidget is being destroyed before it associated // vtkRenderWindow is destroyed.". this->GetNthRenderWidget(0)->SetParent(NULL); if (this->FourPaneView) { this->GetNthRenderWidget(1)->SetParent(NULL); this->GetNthRenderWidget(2)->SetParent(NULL); } this->SelectionFrame->Delete(); this->SelectionFrameLayoutManager->Delete(); if (this->Filename) { delete [] this->Filename; } if (this->SelectEditRadioButtons) { this->SelectEditRadioButtons->Delete(); } if (this->Window) { this->Window->Delete(); } this->SetInput(NULL); this->InfoDialog->Delete(); this->CxxSourceText->Delete(); this->Widgets->Delete(); } //---------------------------------------------------------------------------- void vtkKWMyWindow::SetApplication( vtkKWApplication * app ) { this->Application = app; } //---------------------------------------------------------------------------- void vtkKWMyWindow::Initialize() { vtkKWApplication *app = this->GetApplication(); app->SetName("Paintbrush Example"); app->RestoreApplicationSettingsFromRegistry(); this->Window = vtkKWWindow::New(); app->AddWindow(this->Window); this->Window->Create(); this->Window->SecondaryPanelVisibilityOff(); this->Window->MainPanelVisibilityOff(); if (this->FourPaneView) { this->SelectionFrameLayoutManager->SetParent(this->Window->GetViewFrame()); this->SelectionFrameLayoutManager->SetResolution(2, 2); this->SelectionFrameLayoutManager->Create(); for (int i = 0; i < 3; i++) { vtkKWSelectionFrame * sel_frame = vtkKWSelectionFrame::New(); sel_frame->SetTitle(vtkKWMyWindowWidgetStrings[i]); this->SelectionFrameLayoutManager->AddWidget(sel_frame); sel_frame->AllowCloseOff(); sel_frame->AllowChangeTitleOff(); sel_frame->Delete(); } app->Script("pack %s -expand y -fill both -anchor c -expand y", this->SelectionFrameLayoutManager->GetWidgetName()); // Add a render widget, attach it to the view frame, and pack for (int i = 0; i < 3; i++) { vtkKWRenderWidget * renwidget = vtkKWRenderWidget::New(); renwidget->SetParent(this->SelectionFrameLayoutManager-> GetWidgetWithTitle(vtkKWMyWindowWidgetStrings[i])->GetBodyFrame()); renwidget->Create(); renwidget->CornerAnnotationVisibilityOn(); app->Script("pack %s -expand y -fill both -anchor c -expand y", renwidget->GetWidgetName()); renwidget->Delete(); } } else { this->SelectionFrame->SetParent(this->Window->GetViewFrame()); this->SelectionFrame->SetAllowChangeTitle(0); this->SelectionFrame->AllowCloseOff(); this->SelectionFrame->Create(); this->SelectionFrame->SetSelectionList(3, vtkKWMyWindowWidgetStrings); app->Script("pack %s -expand y -fill both -anchor c -expand y", this->SelectionFrame->GetWidgetName()); vtkKWRenderWidget * renwidget = vtkKWRenderWidget::New(); renwidget->SetParent(this->SelectionFrame->GetBodyFrame()); renwidget->Create(); renwidget->CornerAnnotationVisibilityOn(); app->Script("pack %s -expand y -fill both -anchor c -expand y", renwidget->GetWidgetName()); renwidget->Delete(); } // Read the data, if an input hasn't already been specified if (!this->Input) { vtkImageReader2 *reader; this->GetValidReader( reader, this->Filename ); if (!reader) { std::cerr << "Cannot read input image file ! " << std::endl; return; } reader->Update(); this->SetInput(reader->GetOutput()); reader->Delete(); } // Create an image viewer // Use the render window and renderer of the renderwidget if (this->FourPaneView == 0) { vtkKWRenderWidget * rw = this->GetAxialRenderWidget(); this->ImageViewer[0]->SetRenderWindow(rw->GetRenderWindow()); this->ImageViewer[0]->SetRenderer(rw->GetRenderer()); this->ImageViewer[0]->SetInput(this->Input); this->ImageViewer[0]->SetupInteractor( rw->GetRenderWindow()->GetInteractor()); // Reset the window/level and the camera double *range = this->Input->GetScalarRange(); this->ImageViewer[0]->SetColorWindow(range[1] - range[0]); this->ImageViewer[0]->SetColorLevel(0.5 * (range[1] + range[0])+ 0.0000001); rw->ResetCamera(); this->SliceScale[0]->SetParent(this->Window->GetViewPanelFrame()); this->SliceScale[0]->SetEntryPositionToLeft(); this->SliceScale[0]->Create(); this->SliceScale[0]->SetCommand(this, "SetSliceFromScaleCallback"); app->Script("pack %s -side top -expand n -fill x -padx 2 -pady 2", this->SliceScale[0]->GetWidgetName()); this->SelectionFrame->SetSelectionListCommand( this, "RenderWidgetSelectionChangedCallback" ); } else { for (int i = 0; i < 3; i++) { vtkKWSelectionFrame * sel_frame = this->SelectionFrameLayoutManager-> GetWidgetWithTitle(vtkKWMyWindowWidgetStrings[i]); vtkKWRenderWidget * rw = this->GetRenderWidget(sel_frame); this->ImageViewer[i]->SetRenderWindow(rw->GetRenderWindow()); this->ImageViewer[i]->SetRenderer(rw->GetRenderer()); this->ImageViewer[i]->SetInput(this->Input); this->ImageViewer[i]->SetupInteractor( rw->GetRenderWindow()->GetInteractor()); // Reset the window/level and the camera double *range = this->Input->GetScalarRange(); this->ImageViewer[i]->SetColorWindow(range[1] - range[0]); this->ImageViewer[i]->SetColorLevel(0.5 * (range[1] + range[0])+ 0.0000001); this->ImageViewer[i]->SetSliceOrientation(2-i); rw->ResetCamera(); sel_frame->LeftUserFrameVisibilityOn(); this->SliceScale[i]->SetParent(sel_frame->GetLeftUserFrame()); this->SliceScale[i]->SetOrientationToVertical(); this->SliceScale[i]->EntryVisibilityOff(); this->SliceScale[i]->Create(); vtksys_ios::ostringstream s; s << "SetSliceFromScaleCallback" << i << std::ends; this->SliceScale[i]->SetCommand(this, s.str().c_str()); app->Script("pack %s -side top -anchor nw -expand yes -fill y -padx 0 -pady 0", this->SliceScale[i]->GetWidgetName()); } } this->UpdateSliceRanges(); this->Window->Display(); // Repeatedly set the layout manager resolution here. When win->Display // is invoked the layout manager is automatically re-adjusted. if (this->FourPaneView) { this->SelectionFrameLayoutManager->SetResolution(2,2); } } //---------------------------------------------------------------------------- int vtkKWMyWindow::Run() { vtkKWApplication *app = this->GetApplication(); app->Start(); int ret = app->GetExitStatus(); this->Window->Close(); return ret; } //---------------------------------------------------------------------------- vtkKWRenderWidget * vtkKWMyWindow::GetNthRenderWidget( int i ) { return this->GetRenderWidget( this->FourPaneView ? this->SelectionFrameLayoutManager-> GetWidgetWithTitle(vtkKWMyWindowWidgetStrings[i]) : this->SelectionFrame); } //---------------------------------------------------------------------------- vtkImageActor * vtkKWMyWindow::GetNthImageActor( int i ) { vtkKWRenderWidget * rw = this->GetNthRenderWidget(i); for (int j = 0; j < 3; j++) { if (this->ImageViewer[j]->GetRenderWindow() == rw->GetRenderWindow()) { return this->ImageViewer[j]->GetImageActor(); } } return NULL; } //---------------------------------------------------------------------------- vtkKWRenderWidget * vtkKWMyWindow ::GetRenderWidget( vtkKWSelectionFrame *widget ) { vtkKWRenderWidget *rw = NULL; if (widget) { vtkKWFrame *frame = widget->GetBodyFrame(); if (frame) { int nb_children = frame->GetNumberOfChildren(); for (int i = 0; i < nb_children; i++) { vtkKWWidget *child = frame->GetNthChild(i); if (child) { rw = vtkKWRenderWidget::SafeDownCast(child); if (rw) { return rw; } int nb_grand_children = child->GetNumberOfChildren(); for (int j = 0; j < nb_grand_children; j++) { vtkKWWidget *grand_child = child->GetNthChild(j); if (grand_child) { rw = vtkKWRenderWidget::SafeDownCast(grand_child); if (rw) { return rw; } } } } } } } return rw; } //---------------------------------------------------------------------------- void vtkKWMyWindow::SetSliceFromScaleCallback( double value ) { if (this->FourPaneView == 0) { this->ImageViewer[0]->SetSlice((int)value); } } //---------------------------------------------------------------------------- void vtkKWMyWindow::SetSliceFromScaleCallback0( double value ) { this->ImageViewer[0]->SetSlice((int)value); } //---------------------------------------------------------------------------- void vtkKWMyWindow::SetSliceFromScaleCallback1( double value ) { this->ImageViewer[1]->SetSlice((int)value); } //---------------------------------------------------------------------------- void vtkKWMyWindow::SetSliceFromScaleCallback2( double value ) { this->ImageViewer[2]->SetSlice((int)value); } //---------------------------------------------------------------------------- void vtkKWMyWindow::UpdateSliceRanges() { if (this->FourPaneView) { for (int i = 0; i < 3; i++) { this->SliceScale[i]->SetRange( this->ImageViewer[i]->GetSliceMin(), this->ImageViewer[i]->GetSliceMax()); this->SliceScale[i]->SetValue( this->ImageViewer[i]->GetSlice() ); } } else { this->SliceScale[0]->SetRange( this->ImageViewer[0]->GetSliceMin(), this->ImageViewer[0]->GetSliceMax()); this->SliceScale[0]->SetValue( this->ImageViewer[0]->GetSlice()); } } //---------------------------------------------------------------------------- void vtkKWMyWindow::RenderWidgetSelectionChangedCallback( const char * title, vtkKWSelectionFrame * ) { for (int i = 0; i < 3; i++) { if (strcmp(title, vtkKWMyWindowWidgetStrings[i]) == 0) { if (this->ImageViewer[0]->GetSliceOrientation() != (2-i)) { this->SelectionFrame->SetTitle(title); this->ImageViewer[0]->SetSliceOrientation(2-i); this->UpdateSliceRanges(); } } } } //---------------------------------------------------------------------------- void vtkKWMyWindow::GetValidReader( vtkImageReader2* & reader, const char *filename) { if (filename == NULL) { return; } reader = vtkMetaImageReader::New(); reader->SetFileName(filename); if (reader->CanReadFile(filename) == 3) { return; } /* * Damn ! I can't read .vtk files. they don't subclass from vtkImageReader2 * TODO : put a work around for VTK files later * * reader = vtkXMLImageDataReader::New(); int valid = reader->CanReadFile(filename); if (reader->CanReadFile(filename) == 3) { return; } */ reader = vtkPNGReader::New(); if (reader->CanReadFile(filename) == 3) { return; } reader = vtkBMPReader::New(); if (reader->CanReadFile(filename) == 3) { return; } reader = vtkPNMReader::New(); if (reader->CanReadFile(filename) == 3) { return; } reader->Delete(); reader = NULL; } //---------------------------------------------------------------------------- void vtkKWMyWindow::CreateInfo( vtksys_stl::string name, vtkKWApplication * app ) { this->InfoDialog->SetApplication(app); this->InfoDialog->Create(); this->InfoDialog->SetDisplayPositionToMasterWindowCenter(); this->InfoDialog->SetDeleteWindowProtocolCommand(this->InfoDialog, "Withdraw"); this->InfoDialog->Display(); this->InfoDialog->SetSize(700, 400); vtksys_stl::string source, line; char buffer[1024]; // Add text widget to display the C++ example source this->CxxSourceText->SetParent(this->InfoDialog); this->CxxSourceText->Create(); this->CxxSourceText->SetLabelPositionToTop(); this->CxxSourceText->SetLabelText("C++ Source"); vtkKWTextWithScrollbars *text_widget = this->CxxSourceText->GetWidget(); text_widget->VerticalScrollbarVisibilityOn(); vtkKWText *text = text_widget->GetWidget(); text->ReadOnlyOn(); text->SetWrapToNone(); text->SetHeight(3000); text->AddTagMatcher("^//[^\n]*", "_bold_tag_"); text->AddTagMatcher("\n//[^\n]*", "_bold_tag_"); text->AddTagMatcher("#[a-z]+", "_fg_red_tag_"); text->AddTagMatcher(" //[^\n]*", "_fg_navy_tag_"); text->AddTagMatcher("\"[^\"]*\"", "_fg_blue_tag_"); text->AddTagMatcher("<[^>]*>", "_fg_blue_tag_"); text->AddTagMatcher("vtk[A-Z][a-zA-Z0-9_]+", "_fg_dark_green_tag_"); app->Script("pack %s -side top -expand y -fill both -padx 2 -pady 2", this->CxxSourceText->GetWidgetName()); vtksys_stl::string fname_path = vtksys::SystemTools::GetFilenamePath(__FILE__); sprintf(buffer, "%s/%s", fname_path.c_str(), vtksys::SystemTools::GetFilenameName(name).c_str()); if (!vtksys::SystemTools::FileExists(buffer)) { sprintf(buffer, "%s/%s.cxx", app->GetInstallationDirectory(), name.c_str()); } source = ""; if (vtksys::SystemTools::FileExists(buffer)) { ifstream ifs(buffer); while (vtksys::SystemTools::GetLineFromStream(ifs, line)) { source += line; source += "\n"; } ifs.close(); } this->CxxSourceText->GetWidget()->GetWidget()->SetText(source.c_str()); } //---------------------------------------------------------------------------- vtksys_stl::string vtkKWMyWindow::ExpandFilename( const char * s ) { vtkstd::vector< vtksys_stl::string > stringArray; stringArray.push_back(vtkKWMyWindow::GetExampleDataPath()); stringArray.push_back(s); std::string fn = vtksys::SystemTools::JoinPath(stringArray); vtksys::SystemTools::ConvertToUnixSlashes(fn); return fn; } //---------------------------------------------------------------------------- void vtkKWMyWindow::AddSelectEditCallback( vtkKWEPaintbrushWidget * w ) { if (!this->Widgets->IsItemPresent(w)) { this->Widgets->AddItem(w); } if (this->SelectEditRadioButtons == NULL) { this->Window->MainPanelVisibilityOn(); this->SelectEditRadioButtons = vtkKWRadioButtonSet::New(); this->SelectEditRadioButtons->SetParent( this->Window->GetMainPanelFrame() ); this->SelectEditRadioButtons->Create(); this->SelectEditRadioButtons->SetBorderWidth(2); this->SelectEditRadioButtons->SetReliefToGroove(); vtkKWRadioButton *editButton = this->SelectEditRadioButtons->AddWidget(0); editButton->SetText("Edit"); editButton->SetBalloonHelpString( "The Paintbrush widget can operate either in an \"edit\" mode or in a " "\"select\" mode. In \"edit\" mode, you can draw, erase, create and edit " "segmentations."); editButton->SetCommand( this, "SelectEditCallback" ); vtkKWRadioButton *selectButton = this->SelectEditRadioButtons->AddWidget(1); selectButton->SetText("Select"); selectButton->SetBalloonHelpString( "The Paintbrush widget can operate either in an \"edit\" mode or in a " "\"select\" mode. The \"select\" mode facilitates one/multi-click selection " "of sketches and allows you merge and remove segmentations."); selectButton->SetCommand( this, "SelectEditCallback" ); // Default to edit mode. this->SelectEditRadioButtons->GetWidget(0)->SetSelectedState(1); this->Application->Script("pack %s -side top -anchor nw -expand n -padx 2 -pady 2", this->SelectEditRadioButtons->GetWidgetName() ); } } //---------------------------------------------------------------------------- void vtkKWMyWindow::SetSelectEditCallbackMethod( SelectEditCallbackMethodType f ) { this->SelectEditCallbackMethod = f; } //---------------------------------------------------------------------------- void vtkKWMyWindow::SelectEditCallback() { vtkKWEPaintbrushWidget *w; for ( this->Widgets->InitTraversal(); (w=static_cast< vtkKWEPaintbrushWidget*>(this->Widgets->GetNextItemAsObject())); ) this->SelectEditCallbackMethod(w, this->SelectEditRadioButtons->GetWidget(0)->GetSelectedState()); } vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/PaintbrushExample6.cxx0000644000175000017500000002331711363410610024360 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // PaintbrushData drawn can be filtered through "operations". These are // represented by abstract base classes: vtkKWEPaintbrushOperation. The base // class acts as a pass through filter. Concrete subclasses can do fancy // filtering operations such as flood-fill etc. These operations permit an // inplace filtering of a paintbrush data during a sketch. // // As an example, a flood-fill operation is implemented in // vtkKWEITKConfidenceConnectedPaintbrushOperation. This uses a combination of ITK // region growing and hole-filling filters. This example illustrates how to // plug an operation into the paintbrush widget. #include "vtkKWMyWindow.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEITKImageToStencilFilter.h" #include "vtkKWEITKPaintbrushOperation.h" #include "itkBinaryThresholdImageFilter.h" #include "vtkImageStencilData.h" #include "vtkKWEPaintbrushStroke.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkObjectFactory.h" #include "vtkImageExtractComponents.h" #include "vtkExtractVOI.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEWidgetGroup.h" #include "itkNumericTraits.h" #include "vtkKWEITKFilterModuleStencilOutput.h" KWLIBS_CREATE_EXAMPLE // Macro fires up a basic app with some data namespace vtkitk { template class vtkKWEITKBinaryThresholdImageFilter : public vtkKWEITKImageToStencilFilter { public: typedef vtkKWEITKBinaryThresholdImageFilter Self; typedef vtkKWEITKImageToStencilFilter Superclass; typedef itk::SmartPointer< Self > Pointer; typedef itk::SmartPointer< const Self > ConstPointer; itkTypeMacro(vtkKWEITKBinaryThresholdImageFilter, vtkKWEITKImageToStencilFilter); itkNewMacro(Self); typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::BinaryThresholdImageFilter< InputImageType, OutputImageType > FilterType; // No MTime checks etc.. will update every time.. virtual void Update() { this->Superclass::Update(); FilterModuleStencilOutput< FilterType > * f = (dynamic_cast< FilterModuleStencilOutput< FilterType > * >(this->m_Filter)); // Update the filter.. If any timing analysis needs to be done.. // This method needs to be interactive enough. f->Update(); } protected: vtkKWEITKBinaryThresholdImageFilter() { FilterModuleStencilOutput< FilterType > * filter = new FilterModuleStencilOutput< FilterType >(); this->m_Filter = filter; filter->GetFilter()->SetLowerThreshold( 200 ); filter->GetFilter()->SetUpperThreshold( 255 ); } ~vtkKWEITKBinaryThresholdImageFilter() { delete this->m_Filter; } }; } // end namespace vtkitk class vtkKWEITKBinaryThresholdPaintbrushOperation : public vtkKWEITKPaintbrushOperation { public: static vtkKWEITKBinaryThresholdPaintbrushOperation *New(); vtkTypeRevisionMacro(vtkKWEITKBinaryThresholdPaintbrushOperation, vtkKWEITKPaintbrushOperation); protected: vtkKWEITKBinaryThresholdPaintbrushOperation() {}; ~vtkKWEITKBinaryThresholdPaintbrushOperation() {}; // See superclass documentation for details on these methods. virtual void DoOperationOnStencil(vtkImageStencilData *, double p[3]); virtual void DoOperation( vtkKWEPaintbrushData *data, double p[3] ) { // The paintbrush data can be binary or grayscale. Invoke the appropriate // filtering operation in each case. if (vtkKWEPaintbrushStencilData *sdata = vtkKWEPaintbrushStencilData::SafeDownCast(data)) { // Convert from world coords to pixel index. double spacing[3], origin[3]; this->ImageData->GetSpacing(spacing); this->ImageData->GetOrigin(origin); this->DoOperationOnStencil( sdata->GetImageStencilData(), p ); } } private: vtkKWEITKBinaryThresholdPaintbrushOperation( const vtkKWEITKBinaryThresholdPaintbrushOperation&); //Not implemented void operator=(const vtkKWEITKBinaryThresholdPaintbrushOperation&); //Not implemented }; template< class T > int MyPaintbrushRunner( vtkKWEITKBinaryThresholdPaintbrushOperation * self, double center[3], vtkImageStencilData *stencil, T ) { self->InternalFilter = NULL; typedef vtkitk::vtkKWEITKBinaryThresholdImageFilter< T > PaintbrushFilterType; typename PaintbrushFilterType::Pointer filter = PaintbrushFilterType::New(); self->InternalFilter = filter; // Set the update region to a certain region on either side of the center int extent[6], imageExtent[6]; double spacing[3], origin[3]; self->GetImageData()->GetSpacing(spacing); self->GetImageData()->GetExtent(imageExtent); double *width = self->GetPaintbrushShape()->GetWidth(); // Set the center and radius to mask out a spherical stencil, instead of // one with rectangular jagged edges. self->GetImageData()->GetOrigin(origin); extent[0] = (int)((center[0] - width[0])/spacing[0] + 0.5); extent[1] = (int)((center[0] + width[0])/spacing[0] + 0.5); extent[2] = (int)((center[1] - width[1])/spacing[1] + 0.5); extent[3] = (int)((center[1] + width[1])/spacing[1] + 0.5); extent[4] = (int)((center[2] - width[2])/spacing[2] + 0.5); extent[5] = (int)((center[2] + width[2])/spacing[2] + 0.5); vtkKWEPaintbrushUtilities::GetIntersectingExtents(extent, imageExtent, extent); // Despite the fact that the FilterModule framework supports updates on // requested extents, a lot of filters in ITK (such as the // ConfidenceConnectedImageFilter don't really support updating a subextent. // So in most cases, you will have to extract a VOI). vtkExtractVOI *extractVOI = vtkExtractVOI::New(); extractVOI->SetInput( self->GetImageData()); extractVOI->SetVOI(extent); // Extract the first component vtkImageExtractComponents * extractComponent = vtkImageExtractComponents::New(); extractComponent->SetInput( extractVOI->GetOutput() ); extractComponent->GetOutput()->SetUpdateExtent( extent ); extractComponent->SetComponents(0); extractComponent->Update(); filter->SetRequestedExtent(extent); filter->SetInput( extractComponent->GetOutput() ); filter->SetRequestedExtent(extent); filter->Update(); filter->BoundWithRadiusOn(); filter->GetOutputAsStencil(stencil); extractComponent->Delete(); extractVOI->Delete(); return 1; } vtkStandardNewMacro(vtkKWEITKBinaryThresholdPaintbrushOperation) vtkCxxRevisionMacro(vtkKWEITKBinaryThresholdPaintbrushOperation, "$Revision: 1774 $"); void vtkKWEITKBinaryThresholdPaintbrushOperation:: DoOperationOnStencil(vtkImageStencilData *stencilData, double p[3]) { this->PaintbrushShape->GetStencil( stencilData, p); vtkImageStencilData * stencil = vtkImageStencilData::New(); switch (this->ImageData->GetScalarType()) { vtkitkTemplateMacro( MyPaintbrushRunner( this, p, stencil, static_cast< VTK_TT >(0))); default: { vtkErrorMacro(<< "vtkKWEITKBinaryThresholdPaintbrushOperation: Unknown ScalarType"); break; } } // Remove everything in the stencil. stencilData->AllocateExtents(); // This will be the stuff that's filtered through the operation. In this // case the stuff in stencilData, thresholded. stencilData->Add(stencil); stencil->Delete(); } int my_example( int , char *[], vtkKWApplication * , vtkKWMyWindow * example ) { example->Initialize(); vtkImageData * imageData = example->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); vtkKWEITKBinaryThresholdPaintbrushOperation * operation = vtkKWEITKBinaryThresholdPaintbrushOperation::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( example->GetNthRenderWidget(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); rep->SetImageActor( example->GetNthImageActor(i) ); // Note that an operation if set, must be set before the image data. rep->SetPaintbrushOperation(operation); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); set->AddWidget(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } set->SetEnabled(1); int res = example->Run(); operation->Delete(); set->Delete(); return res; } vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/CMakeLists.txt0000644000175000017500000000756011363410610022655 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= if(NOT VTKEdge_SOURCE_DIR) find_package(VTKEdge REQUIRED) include(${VTKEdge_USE_FILE}) endif(NOT VTKEdge_SOURCE_DIR) if(NOT KWWidgets_SOURCE_DIR) find_package(KWWidgets REQUIRED) if(NOT KWWidgets_FOUND) message(FATAL_ERROR "KWWidgets is required to build the Paintbrush examples. Plase specify KWWidgets_DIR") endif(NOT KWWidgets_FOUND) include(${KWWidgets_USE_FILE}) endif(NOT KWWidgets_SOURCE_DIR) if (VTKEdge_USE_ITK) if(NOT ITK_SOURCE_DIR) find_package(ITK REQUIRED) if(NOT ITK_FOUND) message(FATAL_ERROR "ITK is required to build the Paintbrush examples. Plase specify ITK_DIR") endif(NOT ITK_FOUND) include(${ITK_USE_FILE}) endif(NOT ITK_SOURCE_DIR) endif (VTKEdge_USE_ITK) include_regular_expression("^.*$") include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ) include("${KWWidgets_CMAKE_DIR}/KWWidgetsWrappingMacros.cmake") kwwidgets_wrap_tcl("KWMyWindowLib" LIB_TCL_SRCS "vtkKWMyWindow.cxx" "") add_library(KWMyWindowLib STATIC ${LIB_TCL_SRCS} "vtkKWMyWindow.cxx") target_link_libraries(KWMyWindowLib ${VTKEdge_LIBRARIES}) set(cxx_names PaintbrushExample1 PaintbrushExample2 PaintbrushExample3 PaintbrushExample4 PaintbrushLabelMapSimpleExample PaintbrushLabelMapChangeNoLabelValue PaintbrushExample8 PaintbrushExample9 ) set(itk_cxx_names) if(ITK_FOUND OR ITK_SOURCE_DIR) set(itk_cxx_names PaintbrushExample5 PaintbrushExample6 PaintbrushExample7 ) set(cxx_names ${cxx_names} ${itk_cxx_names}) endif(ITK_FOUND OR ITK_SOURCE_DIR) foreach(cxx_name ${cxx_names}) set(exe ${VTKEdge_EXAMPLE_EXECUTABLE_PREFIX}${cxx_name}) # On Win32 platforms, let's create a .rc resource file to setup a decent # application icon as well as some additional information in the "Version" # tab of the properties panel. This is also required for static Tk set(RC_FILENAME) if(WIN32 AND NOT BORLAND AND NOT CYGWIN) include("${KWWidgets_CMAKE_DIR}/KWWidgetsResourceMacros.cmake") set(RC_FILENAME "${CMAKE_CURRENT_BINARY_DIR}/${exe}.rc") kwwidgets_create_rc_file( RC_FILENAME "${RC_FILENAME}" RC_APPLICATION_NAME "${exe}" RC_COMPANY_NAME "Kitware, Inc.") endif(WIN32 AND NOT BORLAND AND NOT CYGWIN) add_executable(${exe} WIN32 ${cxx_name}.cxx ${RC_FILENAME}) target_link_libraries(${exe} KWMyWindowLib ${KWWidgets_LIBRARIES} ${VTKEdge_LIBRARIES}) install_targets(${VTKEdge_INSTALL_BIN_DIR} ${exe}) endforeach(cxx_name) # NOT BUILD_SHARED_LIBS: until I figure out why the damn: # 'itk::ImageToVTKImageFilter::...' definition of dllimport function not allowed if(ITK_FOUND OR ITK_SOURCE_DIR) foreach(cxx_name ${itk_cxx_names}) set(exe ${VTKEdge_EXAMPLE_EXECUTABLE_PREFIX}${cxx_name}) target_link_libraries(${exe} ${ITK_LIBRARIES}) endforeach(cxx_name) endif(ITK_FOUND OR ITK_SOURCE_DIR) # If needed, copy the Tcl/Tk support files required at run-time # to initialize Tcl/Tk. This is only triggered if VTK was built # against a Tcl/Tk static library. include("${KWWidgets_CMAKE_DIR}/KWWidgetsTclTkMacros.cmake") kwwidgets_copy_tcl_tk_support_files("${PROJECT_BINARY_DIR}/lib") kwwidgets_install_tcl_tk_support_files("/lib") vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/PaintbrushLabelMapChangeNoLabelValue.cxx0000644000175000017500000002123311363410610027707 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // Before you run this example, be sure to check out PaintbrushLabelMapSimpleExample // // This example shows you how you can change the default NoLabelValue of 0, if // you wish to use a different value to represent the absense of a label. // Here we use a value of 255. // // The only line required to do is // vtkKWEPaintbrushLabelData::SetNoLabelValue( 255 ); // // If you choose to set this, take care to set this to only one value and // as early as possible in your application. // ---------------------------------------------------------------------------- #include "vtkKWMyWindow.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include "vtkMultiThreader.h" #include #include #include class PaintbrushExample8Labels { public: class Annotation { public: Annotation() {}; Annotation(const std::string &l, unsigned char r, unsigned char g, unsigned char b ) { label = l; R = r; G = g; B = b; } bool operator!=(const Annotation &a) const { return a.label != this->label; } std::string label; unsigned char R, G, B; }; std::map< unsigned short, Annotation > LabelMap; }; void MySelectEditCallbackMethod( vtkKWEPaintbrushWidget *w, int editMode ) { w->SetPaintbrushMode( editMode ? vtkKWEPaintbrushWidget::Edit : vtkKWEPaintbrushWidget::Select ); } KWLIBS_CREATE_EXAMPLE // Macro fires up a basic app with some data int my_example( int , char *[], vtkKWApplication * , vtkKWMyWindow * example ) { vtkKWEPaintbrushLabelData::SetNoLabelValue( 255 ); typedef PaintbrushExample8Labels::Annotation AnnotationType; PaintbrushExample8Labels MyLabels; MyLabels.LabelMap[42]=AnnotationType("Right-Cerebral-Cortex", 205 , 62, 78 ); MyLabels.LabelMap[43]=AnnotationType("Right-Lateral-Ventricle", 120 , 18, 134 ); example->SetFilename( vtkKWMyWindow::ExpandFilename("IBSRData.mha").c_str()); example->Initialize(); vtkImageData * imageData = example->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( example->GetNthRenderWidget(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); if (rep) { vtkImageActor * imageActor = example->GetNthImageActor(i); rep->SetImageActor(imageActor); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } // This will simply cause the method // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Edit ) or // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Select ) // to be invoked based on which radio button is depressed. example->SetSelectEditCallbackMethod( MySelectEditCallbackMethod ); example->AddSelectEditCallback(w); set->AddWidget(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); // Our internal representation will be to manage a label map. drawing->SetRepresentationToLabel(); // This will allocate our canvas based on the size of the overlay image // that was set on the WidgetRepresentation. drawing->InitializeData(); // Clear the drawing and start on a clean slate. The drawing would have // automatically created 1 empty sketch for us, so we can start drawing // right away. Let's remove it, since we'd like to initialize the drawing // with our IBSR label map. drawing->RemoveAllItems(); // Read the IBSR label map vtkMetaImageReader * reader = vtkMetaImageReader::New(); reader->SetFileName( vtkKWMyWindow::ExpandFilename("IBSRLabelMap-USHORT-2Labels-NoLabelValue255.mha").c_str() ); reader->Update(); // Create a PaintbrushLabelData to represent the label map. vtkKWEPaintbrushLabelData *paintbrushLabelMap = vtkKWEPaintbrushLabelData::New(); paintbrushLabelMap->SetLabelMap( reader->GetOutput() ); // Set the label map as the initial canvas data of the drawing. drawing->SetPaintbrushData( paintbrushLabelMap ); // Create a sketch for each label in the label map, we'd like to edit. // NOTE: We can skip labels in the label map that we do not care about simply // by not adding a sketch corresponding to that label into the drawing. In // this case, we will take into account all the labels (1-62). // NOTE: As a reminder, bear in mind that 0 is a reserved value and must not // be used as a label. for (std::map< unsigned short, AnnotationType >::const_iterator cit = MyLabels.LabelMap.begin(); cit != MyLabels.LabelMap.end(); ++cit) { // For each label. // Initialize the sketch with the label map. Note that you must add the // sketch to the drawing and set the label you wish the sketch to represent // before you initialize it from the label map. // Also note that when the representation is a "Label-map", all sketches // share the same label map to avoid memory duplication. The corollary to // this is that if you initialize sketches in your drawing using a labelmap, // you must use the same "vtkKWEPaintbrushLabelData" that is used by the // drawing. vtkKWEPaintbrushSketch * sketch = vtkKWEPaintbrushSketch::New(); drawing->AddItem( sketch ); sketch->SetLabel( cit->first ); sketch->Initialize( paintbrushLabelMap ); // Optionally, the identifier can be used to display text annotations as // you navigate through your maze of sketches. 62 segmentations can sure // get you lost pretty quickly. sketch->GetPaintbrushProperty()->SetIdentifier(cit->second.label.c_str()); // Assign a nice color to the sketch. double sketchColor[3] = { (double)(cit->second.R)/255.0, (double)(cit->second.G)/255.0, (double)(cit->second.B)/255.0 }; sketch->GetPaintbrushProperty()->SetColor( sketchColor ); sketch->Delete(); } reader->Delete(); // Now set the drawing on all representations (axial, coronal and sagittal) // in the WidgetSet. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } // Enable the widget and we are done. set->SetEnabled(1); int res = example->Run(); // Save out each of the resulting segmentations. We will write out each // sketch in the drawing as a seperate file. This will take a while. You // might have noticed that when you quit this application it takes a while, // This is because we are writing out our edited segmentation for validation. const bool writeOutResults = false; if (writeOutResults) { vtkKWEPaintbrushLabelData * finalLabelMap = vtkKWEPaintbrushLabelData::SafeDownCast(drawing->GetPaintbrushData()); vtkMetaImageWriter * outputWriter = vtkMetaImageWriter::New(); outputWriter->SetFileName("EditedLabelMap.mha"); outputWriter->SetInput( finalLabelMap->GetLabelMap() ); outputWriter->Write(); outputWriter->Delete(); } paintbrushLabelMap->Delete(); set->Delete(); return res; } vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/PaintbrushExample8.cxx0000644000175000017500000003103211363410610024353 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This example loads a file IBSRData.mha and a label map IBSRLabelMap.mha. // The label map, (courtesy of IBSR) is a label map with 62 segmentations. This // example creates a sketch from each label and initializes the drawing with // these sketches. It also assigns user specified colors to the sketches. #include "vtkKWMyWindow.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include #include #include class PaintbrushExample8Labels { public: class Annotation { public: Annotation() {}; Annotation(const std::string &l, unsigned char r, unsigned char g, unsigned char b ) { label = l; R = r; G = g; B = b; } bool operator!=(const Annotation &a) const { return a.label != this->label; } std::string label; unsigned char R, G, B; }; std::map< unsigned short, Annotation > LabelMap; }; void MySelectEditCallbackMethod( vtkKWEPaintbrushWidget *w, int editMode ) { w->SetPaintbrushMode( editMode ? vtkKWEPaintbrushWidget::Edit : vtkKWEPaintbrushWidget::Select ); } KWLIBS_CREATE_EXAMPLE // Macro fires up a basic app with some data int my_example( int , char *[], vtkKWApplication * , vtkKWMyWindow * example ) { typedef PaintbrushExample8Labels::Annotation AnnotationType; PaintbrushExample8Labels MyLabels; MyLabels.LabelMap[1]=AnnotationType("Left-Cerebral-Exterior", 205 , 62, 78 ); MyLabels.LabelMap[2]=AnnotationType("Left-Cerebral-White-Matter", 225 , 225, 225 ); MyLabels.LabelMap[3]=AnnotationType("Left-Cerebral-Cortex", 205 , 62, 78 ); MyLabels.LabelMap[4]=AnnotationType("Left-Lateral-Ventricle", 120 , 18, 134 ); MyLabels.LabelMap[5]=AnnotationType("Left-Inf-Lat-Vent", 196 , 58, 250 ); MyLabels.LabelMap[6]=AnnotationType("Left-Cerebellum-Exterior", 0 , 148, 0 ); MyLabels.LabelMap[7]=AnnotationType("Left-Cerebellum-White-Matter", 220 , 248, 164 ); MyLabels.LabelMap[8]=AnnotationType("Left-Cerebellum-Cortex", 230 , 148, 34 ); MyLabels.LabelMap[9]=AnnotationType("Left-Thalamus", 0 , 118, 14 ); MyLabels.LabelMap[10]=AnnotationType("Left-Thalamus-Proper", 0 , 118, 14 ); MyLabels.LabelMap[11]=AnnotationType("Left-Caudate", 122 , 186, 220 ); MyLabels.LabelMap[12]=AnnotationType("Left-Putamen", 236 , 13, 176 ); MyLabels.LabelMap[13]=AnnotationType("Left-Pallidum", 12 , 48, 255 ); MyLabels.LabelMap[14]=AnnotationType("3rd-Ventricle", 204 , 182, 142 ); MyLabels.LabelMap[15]=AnnotationType("4th-Ventricle", 42 , 204, 164 ); MyLabels.LabelMap[16]=AnnotationType("Brain-Stem", 119 , 159, 176 ); MyLabels.LabelMap[17]=AnnotationType("Left-Hippocampus", 220 , 216, 20 ); MyLabels.LabelMap[18]=AnnotationType("Left-Amygdala", 103 , 255, 255 ); MyLabels.LabelMap[19]=AnnotationType("Left-Insula", 80 , 196, 98 ); MyLabels.LabelMap[20]=AnnotationType("Left-Operculum", 60 , 58, 210 ); MyLabels.LabelMap[21]=AnnotationType("Line-1", 60 , 58, 210 ); MyLabels.LabelMap[22]=AnnotationType("Line-2", 60 , 58, 210 ); MyLabels.LabelMap[23]=AnnotationType("Line-3", 60 , 58, 210 ); MyLabels.LabelMap[24]=AnnotationType("CSF", 60 , 60, 60 ); MyLabels.LabelMap[25]=AnnotationType("Left-Lesion", 255 , 165, 0 ); MyLabels.LabelMap[26]=AnnotationType("Left-Accumbens-area", 255 , 165, 0 ); MyLabels.LabelMap[27]=AnnotationType("Left-Substancia-Nigra", 0 , 255, 127 ); MyLabels.LabelMap[28]=AnnotationType("Left-VentralDC", 165 , 42, 42 ); MyLabels.LabelMap[29]=AnnotationType("Left-undetermined", 135 , 206, 235 ); MyLabels.LabelMap[30]=AnnotationType("Left-vessel", 160 , 32, 240 ); MyLabels.LabelMap[31]=AnnotationType("Left-choroid-plexus", 0 , 255, 255 ); MyLabels.LabelMap[32]=AnnotationType("Left-F3orb", 100 , 50, 100 ); MyLabels.LabelMap[33]=AnnotationType("Left-lOg", 135 , 50, 74 ); MyLabels.LabelMap[34]=AnnotationType("Left-aOg", 122 , 135, 50 ); MyLabels.LabelMap[35]=AnnotationType("Left-mOg", 51 , 50, 135 ); MyLabels.LabelMap[36]=AnnotationType("Left-pOg", 74 , 155, 60 ); MyLabels.LabelMap[37]=AnnotationType("Left-Stellate", 120 , 62, 43 ); MyLabels.LabelMap[38]=AnnotationType("Left-Porg", 74 , 155, 60 ); MyLabels.LabelMap[39]=AnnotationType("Left-Aorg", 122 , 135, 50 ); MyLabels.LabelMap[40]=AnnotationType("Right-Cerebral-Exterior", 205 , 62, 78 ); MyLabels.LabelMap[41]=AnnotationType("Right-Cerebral-White-Matter", 0 , 225, 0 ); MyLabels.LabelMap[42]=AnnotationType("Right-Cerebral-Cortex", 205 , 62, 78 ); MyLabels.LabelMap[43]=AnnotationType("Right-Lateral-Ventricle", 120 , 18, 134 ); MyLabels.LabelMap[44]=AnnotationType("Right-Inf-Lat-Vent", 196 , 58, 250 ); MyLabels.LabelMap[45]=AnnotationType("Right-Cerebellum-Exterior", 0 , 148, 0 ); MyLabels.LabelMap[46]=AnnotationType("Right-Cerebellum-White-Matter", 220 , 248, 164 ); MyLabels.LabelMap[47]=AnnotationType("Right-Cerebellum-Cortex", 230 , 148, 34 ); MyLabels.LabelMap[48]=AnnotationType("Right-Thalamus", 0 , 118, 14 ); MyLabels.LabelMap[49]=AnnotationType("Right-Thalamus-Proper", 0 , 118, 14 ); MyLabels.LabelMap[50]=AnnotationType("Right-Caudate", 122 , 186, 220 ); MyLabels.LabelMap[51]=AnnotationType("Right-Putamen", 236 , 13, 176 ); MyLabels.LabelMap[52]=AnnotationType("Right-Pallidum", 255 , 48, 255 ); MyLabels.LabelMap[53]=AnnotationType("Right-Hippocampus", 220 , 216, 20 ); MyLabels.LabelMap[54]=AnnotationType("Right-Amygdala", 103 , 255, 255 ); MyLabels.LabelMap[55]=AnnotationType("Right-Insula", 80 , 196, 98 ); MyLabels.LabelMap[56]=AnnotationType("Right-Operculum", 60 , 58, 210 ); MyLabels.LabelMap[57]=AnnotationType("Right-Lesion", 255 , 165, 0 ); MyLabels.LabelMap[58]=AnnotationType("Right-Accumbens-area", 255 , 165, 0 ); MyLabels.LabelMap[59]=AnnotationType("Right-Substancia-Nigra", 0 , 255, 127 ); MyLabels.LabelMap[60]=AnnotationType("Right-VentralDC", 165 , 42, 42 ); MyLabels.LabelMap[61]=AnnotationType("Right-undetermined", 135 , 206, 235 ); MyLabels.LabelMap[62]=AnnotationType("Right-vessel", 160 , 32, 240 ); example->SetFilename( vtkKWMyWindow::ExpandFilename("IBSRData.mha").c_str()); example->Initialize(); vtkImageData * imageData = example->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( example->GetNthRenderWidget(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); if (rep) { vtkImageActor * imageActor = example->GetNthImageActor(i); rep->SetImageActor(imageActor); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } // This will simply cause the method // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Edit ) or // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Select ) // to be invoked based on which radio button is depressed. example->SetSelectEditCallbackMethod( MySelectEditCallbackMethod ); example->AddSelectEditCallback(w); set->AddWidget(w); w->Delete(); } // Now read in an initial segmentation. vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); drawing->InitializeData(); // Clear the drawing and start on a clean slate. The drawing would have // automatically created an empty sketch for us, so we can start drawing // right away. We will wipe it all off. drawing->RemoveAllItems(); // Read the label map vtkMetaImageReader * reader = vtkMetaImageReader::New(); reader->SetFileName( vtkKWMyWindow::ExpandFilename("IBSRLabelMap.mha").c_str() ); reader->Update(); // Create a binary sketch for each label in the label map. for (std::map< unsigned short, AnnotationType >::const_iterator cit = MyLabels.LabelMap.begin(); cit != MyLabels.LabelMap.end(); ++cit) { // Note the use of the functor to check the label in the label map. vtkKWEPaintbrushStencilData *stencilData = vtkKWEPaintbrushStencilData::New(); vtkKWEPaintbrushUtilities::GetStencilFromImage< vtkKWEPaintbrushUtilities::vtkFunctorEqualTo >( reader->GetOutput(), stencilData->GetImageStencilData(), cit->first); vtkKWEPaintbrushSketch * sketch = vtkKWEPaintbrushSketch::New(); drawing->AddItem( sketch ); sketch->AddNewStroke( vtkKWEPaintbrushEnums::Draw, stencilData ); // Optionally, the identifier can be used to display text annotations as // you navigate through your maze of sketches. 62 segmentations can sure // get you lost pretty easily. sketch->GetPaintbrushProperty()->SetIdentifier(cit->second.label.c_str()); // Assign a nice color to the sketch. double sketchColor[3] = { (double)(cit->second.R)/255.0, (double)(cit->second.G)/255.0, (double)(cit->second.B)/255.0 }; sketch->GetPaintbrushProperty()->SetColor( sketchColor ); sketch->Delete(); } reader->Delete(); // Now set the drawing on all representations. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } // Enable the widget and we are done. set->SetEnabled(1); int res = example->Run(); // Save out each of the resulting segmentations. We will write out each // sketch in the drawing as a seperate file. /* for (int i = 0; i < drawing->GetNumberOfItems(); i++) { vtkImageData * outputN = vtkImageData::New(); drawing->GetItem(i)->GetPaintbrushData()-> GetPaintbrushDataAsImageData( outputN ); vtkMetaImageWriter * outputWriterN = vtkMetaImageWriter::New(); std::ostringstream filenameN; filenameN << "Drawing" << i << ".mha" << std::ends; outputWriterN->SetFileName(filenameN.str().c_str()); outputWriterN->SetInput( outputN ); outputWriterN->Write(); outputWriterN->Delete(); outputN->Delete(); } */ drawing->Delete(); set->Delete(); return res; } vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/PaintbrushExample1.cxx0000644000175000017500000003662211363410610024356 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This example loads a file IBSRData.mha and a label map IBSRLabelMap-UCHAR.mha. // The label map, (courtesy of IBSR) is a label map with 62 segmentations. This // example creates a sketch from each label and initializes the drawing with // these sketches. It also assigns user specified colors to the sketches. // ---------------------------------------------------------------------------- // // User interactions: // // The follwing interactions are supported by the brush in Edit mode. // Left click and drag - Draws a stroke // Ctrl-Left click and drag - Erases the stroke // Backspace or Left key - Undo the sketch (deletes the previously drawn stroke in a sketch) // Right key - Redo on the given sketch // Shift "+" - Start a new sketch. // Shift Right - Traverse to the next sketch. // Shift Left - Traverse to the previous sketch. // Shift Backspace - Delete a sketch. // Right click and drag - Resize the shape isotropically // Ctrl-Right click and drag - Resize the shape anisotropically // Shift "<" - Decrease the opacity of the overlaid drawing // Shift ">" - Increase the opacity of the overlaid drawing // "l" key - Render the current sketch immutable/mutable. // (Supported only when editing labelmaps) // Escape - Enable/Disable interactions // // The follwing interactions are supported by the brush in Select Mode // Left click - Select/Unselect a sketch // Left click and drag - Drag and drop merge of sketches. // Backspace key - Delete selected sketches. // "m" key - Merge selected sketches. // Escape - Enable/Disable interactions #include "vtkKWMyWindow.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include "vtkMultiThreader.h" #include #include #include class PaintbrushExample1Labels { public: class Annotation { public: Annotation() {}; Annotation(const std::string &l, unsigned char r, unsigned char g, unsigned char b ) { label = l; R = r; G = g; B = b; } bool operator!=(const Annotation &a) const { return a.label != this->label; } std::string label; unsigned char R, G, B; }; std::map< unsigned short, Annotation > LabelMap; }; void MySelectEditCallbackMethod( vtkKWEPaintbrushWidget *w, int editMode ) { w->SetPaintbrushMode( editMode ? vtkKWEPaintbrushWidget::Edit : vtkKWEPaintbrushWidget::Select ); } KWLIBS_CREATE_EXAMPLE // Macro fires up a basic app with some data int my_example( int , char *[], vtkKWApplication * , vtkKWMyWindow * example ) { vtkMultiThreader::SetGlobalMaximumNumberOfThreads(1); typedef PaintbrushExample1Labels::Annotation AnnotationType; PaintbrushExample1Labels MyLabels; MyLabels.LabelMap[1]=AnnotationType("Left-Cerebral-Exterior", 205 , 62, 78 ); MyLabels.LabelMap[2]=AnnotationType("Left-Cerebral-White-Matter", 225 , 225, 225 ); MyLabels.LabelMap[3]=AnnotationType("Left-Cerebral-Cortex", 205 , 62, 78 ); MyLabels.LabelMap[4]=AnnotationType("Left-Lateral-Ventricle", 120 , 18, 134 ); MyLabels.LabelMap[5]=AnnotationType("Left-Inf-Lat-Vent", 196 , 58, 250 ); MyLabels.LabelMap[6]=AnnotationType("Left-Cerebellum-Exterior", 0 , 148, 0 ); MyLabels.LabelMap[7]=AnnotationType("Left-Cerebellum-White-Matter", 220 , 248, 164 ); MyLabels.LabelMap[8]=AnnotationType("Left-Cerebellum-Cortex", 230 , 148, 34 ); MyLabels.LabelMap[9]=AnnotationType("Left-Thalamus", 0 , 118, 14 ); MyLabels.LabelMap[10]=AnnotationType("Left-Thalamus-Proper", 0 , 118, 14 ); MyLabels.LabelMap[11]=AnnotationType("Left-Caudate", 122 , 186, 220 ); MyLabels.LabelMap[12]=AnnotationType("Left-Putamen", 236 , 13, 176 ); MyLabels.LabelMap[13]=AnnotationType("Left-Pallidum", 12 , 48, 255 ); MyLabels.LabelMap[14]=AnnotationType("3rd-Ventricle", 204 , 182, 142 ); MyLabels.LabelMap[15]=AnnotationType("4th-Ventricle", 42 , 204, 164 ); MyLabels.LabelMap[16]=AnnotationType("Brain-Stem", 119 , 159, 176 ); MyLabels.LabelMap[17]=AnnotationType("Left-Hippocampus", 220 , 216, 20 ); MyLabels.LabelMap[18]=AnnotationType("Left-Amygdala", 103 , 255, 255 ); MyLabels.LabelMap[19]=AnnotationType("Left-Insula", 80 , 196, 98 ); MyLabels.LabelMap[20]=AnnotationType("Left-Operculum", 60 , 58, 210 ); MyLabels.LabelMap[21]=AnnotationType("Line-1", 60 , 58, 210 ); MyLabels.LabelMap[22]=AnnotationType("Line-2", 60 , 58, 210 ); MyLabels.LabelMap[23]=AnnotationType("Line-3", 60 , 58, 210 ); MyLabels.LabelMap[24]=AnnotationType("CSF", 60 , 60, 60 ); MyLabels.LabelMap[25]=AnnotationType("Left-Lesion", 255 , 165, 0 ); MyLabels.LabelMap[26]=AnnotationType("Left-Accumbens-area", 255 , 165, 0 ); MyLabels.LabelMap[27]=AnnotationType("Left-Substancia-Nigra", 0 , 255, 127 ); MyLabels.LabelMap[28]=AnnotationType("Left-VentralDC", 165 , 42, 42 ); MyLabels.LabelMap[29]=AnnotationType("Left-undetermined", 135 , 206, 235 ); MyLabels.LabelMap[30]=AnnotationType("Left-vessel", 160 , 32, 240 ); MyLabels.LabelMap[31]=AnnotationType("Left-choroid-plexus", 0 , 255, 255 ); MyLabels.LabelMap[32]=AnnotationType("Left-F3orb", 100 , 50, 100 ); MyLabels.LabelMap[33]=AnnotationType("Left-lOg", 135 , 50, 74 ); MyLabels.LabelMap[34]=AnnotationType("Left-aOg", 122 , 135, 50 ); MyLabels.LabelMap[35]=AnnotationType("Left-mOg", 51 , 50, 135 ); MyLabels.LabelMap[36]=AnnotationType("Left-pOg", 74 , 155, 60 ); MyLabels.LabelMap[37]=AnnotationType("Left-Stellate", 120 , 62, 43 ); MyLabels.LabelMap[38]=AnnotationType("Left-Porg", 74 , 155, 60 ); MyLabels.LabelMap[39]=AnnotationType("Left-Aorg", 122 , 135, 50 ); MyLabels.LabelMap[40]=AnnotationType("Right-Cerebral-Exterior", 205 , 62, 78 ); MyLabels.LabelMap[41]=AnnotationType("Right-Cerebral-White-Matter", 0 , 225, 0 ); MyLabels.LabelMap[42]=AnnotationType("Right-Cerebral-Cortex", 205 , 62, 78 ); MyLabels.LabelMap[43]=AnnotationType("Right-Lateral-Ventricle", 120 , 18, 134 ); MyLabels.LabelMap[44]=AnnotationType("Right-Inf-Lat-Vent", 196 , 58, 250 ); MyLabels.LabelMap[45]=AnnotationType("Right-Cerebellum-Exterior", 0 , 148, 0 ); MyLabels.LabelMap[46]=AnnotationType("Right-Cerebellum-White-Matter", 220 , 248, 164 ); MyLabels.LabelMap[47]=AnnotationType("Right-Cerebellum-Cortex", 230 , 148, 34 ); MyLabels.LabelMap[48]=AnnotationType("Right-Thalamus", 0 , 118, 14 ); MyLabels.LabelMap[49]=AnnotationType("Right-Thalamus-Proper", 0 , 118, 14 ); MyLabels.LabelMap[50]=AnnotationType("Right-Caudate", 122 , 186, 220 ); MyLabels.LabelMap[51]=AnnotationType("Right-Putamen", 236 , 13, 176 ); MyLabels.LabelMap[52]=AnnotationType("Right-Pallidum", 255 , 48, 255 ); MyLabels.LabelMap[53]=AnnotationType("Right-Hippocampus", 220 , 216, 20 ); MyLabels.LabelMap[54]=AnnotationType("Right-Amygdala", 103 , 255, 255 ); MyLabels.LabelMap[55]=AnnotationType("Right-Insula", 80 , 196, 98 ); MyLabels.LabelMap[56]=AnnotationType("Right-Operculum", 60 , 58, 210 ); MyLabels.LabelMap[57]=AnnotationType("Right-Lesion", 255 , 165, 0 ); MyLabels.LabelMap[58]=AnnotationType("Right-Accumbens-area", 255 , 165, 0 ); MyLabels.LabelMap[59]=AnnotationType("Right-Substancia-Nigra", 0 , 255, 127 ); MyLabels.LabelMap[60]=AnnotationType("Right-VentralDC", 165 , 42, 42 ); MyLabels.LabelMap[61]=AnnotationType("Right-undetermined", 135 , 206, 235 ); MyLabels.LabelMap[62]=AnnotationType("Right-vessel", 160 , 32, 240 ); example->SetFilename( vtkKWMyWindow::ExpandFilename("IBSRData.mha").c_str()); example->Initialize(); vtkImageData * imageData = example->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( example->GetNthRenderWidget(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); if (rep) { vtkImageActor * imageActor = example->GetNthImageActor(i); rep->SetImageActor(imageActor); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } // This will simply cause the method // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Edit ) or // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Select ) // to be invoked based on which radio button is depressed. example->SetSelectEditCallbackMethod( MySelectEditCallbackMethod ); example->AddSelectEditCallback(w); set->AddWidget(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); // Our internal representation will be to manage a label map. drawing->SetRepresentationToLabel(); // This will allocate our canvas based on the size of the overlay image // that was set on the WidgetRepresentation. drawing->InitializeData(); // Clear the drawing and start on a clean slate. The drawing would have // automatically created 1 empty sketch for us, so we can start drawing // right away. Let's remove it, since we'd like to initialize the drawing // with our IBSR label map. drawing->RemoveAllItems(); // Read the IBSR label map vtkMetaImageReader * reader = vtkMetaImageReader::New(); reader->SetFileName( vtkKWMyWindow::ExpandFilename("IBSRLabelMap-USHORT.mha").c_str() ); reader->Update(); // Create a PaintbrushLabelData to represent the label map. vtkKWEPaintbrushLabelData *paintbrushLabelMap = vtkKWEPaintbrushLabelData::New(); paintbrushLabelMap->SetLabelMap( reader->GetOutput() ); // Set the label map as the initial canvas data of the drawing. drawing->SetPaintbrushData( paintbrushLabelMap ); // Create a sketch for each label in the label map, we'd like to edit. // NOTE: We can skip labels in the label map that we do not care about simply // by not adding a sketch corresponding to that label into the drawing. In // this case, we will take into account all the labels (1-62). // NOTE: As a reminder, bear in mind that 0 is a reserved value and must not // be used as a label. for (std::map< unsigned short, AnnotationType >::const_iterator cit = MyLabels.LabelMap.begin(); cit != MyLabels.LabelMap.end(); ++cit) { // For each label. // Initialize the sketch with the label map. Note that you must add the // sketch to the drawing and set the label you wish the sketch to represent // before you initialize it from the label map. // Also note that when the representation is a "Label-map", all sketches // share the same label map to avoid memory duplication. The corollary to // this is that if you initialize sketches in your drawing using a labelmap, // you must use the same "vtkKWEPaintbrushLabelData" that is used by the // drawing. vtkKWEPaintbrushSketch * sketch = vtkKWEPaintbrushSketch::New(); drawing->AddItem( sketch ); sketch->SetLabel( cit->first ); sketch->Initialize( paintbrushLabelMap ); // Optionally, the identifier can be used to display text annotations as // you navigate through your maze of sketches. 62 segmentations can sure // get you lost pretty quickly. sketch->GetPaintbrushProperty()->SetIdentifier(cit->second.label.c_str()); // Assign a nice color to the sketch. double sketchColor[3] = { (double)(cit->second.R)/255.0, (double)(cit->second.G)/255.0, (double)(cit->second.B)/255.0 }; sketch->GetPaintbrushProperty()->SetColor( sketchColor ); sketch->Delete(); } reader->Delete(); // Now set the drawing on all representations (axial, coronal and sagittal) // in the WidgetSet. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } // Enable the widget and we are done. set->SetEnabled(1); int res = example->Run(); // Save out each of the resulting segmentations. We will write out each // sketch in the drawing as a seperate file. This will take a while. You // might have noticed that when you quit this application it takes a while, // This is because we are writing out our edited segmentation for validation. const bool writeOutResults = false; if (writeOutResults) { vtkKWEPaintbrushLabelData * finalLabelMap = vtkKWEPaintbrushLabelData::SafeDownCast(drawing->GetPaintbrushData()); vtkMetaImageWriter * outputWriter = vtkMetaImageWriter::New(); outputWriter->SetFileName("EditedLabelMap.mha"); outputWriter->SetInput( finalLabelMap->GetLabelMap() ); outputWriter->Write(); outputWriter->Delete(); } paintbrushLabelMap->Delete(); set->Delete(); return res; } vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/PaintbrushExample7.cxx0000644000175000017500000002355611363410610024366 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // PaintbrushData drawn can be filtered through "operations". These are // represented by abstract base classes: vtkKWEPaintbrushOperation. The base // class acts as a pass through filter. Concrete subclasses can do fancy // filtering operations such as flood-fill etc. These operations permit an // inplace filtering of a paintbrush data during a sketch. // // As an example, a flood-fill operation is implemented in // vtkKWEITKConfidenceConnectedPaintbrushOperation. This uses a combination of ITK // region growing and hole-filling filters. This example illustrates how to // plug an operation into the paintbrush widget. #include "vtkKWMyWindow.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShapeBox.h" #include "vtkKWEITKImageToStencilFilter.h" #include "vtkKWEITKPaintbrushOperation.h" #include "itkBinaryThresholdImageFilter.h" #include "vtkImageStencilData.h" #include "vtkKWEPaintbrushStroke.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkObjectFactory.h" #include "vtkImageExtractComponents.h" #include "vtkExtractVOI.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEWidgetGroup.h" #include "itkNumericTraits.h" #include "vtkKWEITKFilterModuleStencilOutput.h" KWLIBS_CREATE_EXAMPLE // Macro fires up a basic app with some data namespace vtkitk { template class vtkKWEITKBinaryThresholdImageFilter : public vtkKWEITKImageToStencilFilter { public: typedef vtkKWEITKBinaryThresholdImageFilter Self; typedef vtkKWEITKImageToStencilFilter Superclass; typedef itk::SmartPointer< Self > Pointer; typedef itk::SmartPointer< const Self > ConstPointer; itkTypeMacro(vtkKWEITKBinaryThresholdImageFilter, vtkKWEITKImageToStencilFilter); itkNewMacro(Self); typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::BinaryThresholdImageFilter< InputImageType, OutputImageType > FilterType; // No MTime checks etc.. will update every time.. virtual void Update() { this->Superclass::Update(); FilterModuleStencilOutput< FilterType > * f = (dynamic_cast< FilterModuleStencilOutput< FilterType > * >(this->m_Filter)); // Update the filter.. If any timing analysis needs to be done.. // This method needs to be interactive enough. f->Update(); } protected: vtkKWEITKBinaryThresholdImageFilter() { FilterModuleStencilOutput< FilterType > * filter = new FilterModuleStencilOutput< FilterType >(); this->m_Filter = filter; filter->GetFilter()->SetLowerThreshold( 200 ); filter->GetFilter()->SetUpperThreshold( 255 ); } ~vtkKWEITKBinaryThresholdImageFilter() { delete this->m_Filter; } }; } // end namespace vtkitk class vtkKWEITKBinaryThresholdPaintbrushOperation : public vtkKWEITKPaintbrushOperation { public: static vtkKWEITKBinaryThresholdPaintbrushOperation *New(); vtkTypeRevisionMacro(vtkKWEITKBinaryThresholdPaintbrushOperation, vtkKWEITKPaintbrushOperation); protected: vtkKWEITKBinaryThresholdPaintbrushOperation() {}; ~vtkKWEITKBinaryThresholdPaintbrushOperation() {}; // See superclass documentation for details on these methods. virtual void DoOperationOnStencil(vtkImageStencilData *, double p[3]); virtual void DoOperation( vtkKWEPaintbrushData *data, double p[3] ) { // The paintbrush data can be binary or grayscale. Invoke the appropriate // filtering operation in each case. if (vtkKWEPaintbrushStencilData *sdata = vtkKWEPaintbrushStencilData::SafeDownCast(data)) { // Convert from world coords to pixel index. double spacing[3], origin[3]; this->ImageData->GetSpacing(spacing); this->ImageData->GetOrigin(origin); this->DoOperationOnStencil( sdata->GetImageStencilData(), p ); } } private: vtkKWEITKBinaryThresholdPaintbrushOperation( const vtkKWEITKBinaryThresholdPaintbrushOperation&); //Not implemented void operator=(const vtkKWEITKBinaryThresholdPaintbrushOperation&); //Not implemented }; template< class T > int MyPaintbrushRunner( vtkKWEITKBinaryThresholdPaintbrushOperation * self, double center[3], vtkImageStencilData *stencil, T ) { self->InternalFilter = NULL; typedef vtkitk::vtkKWEITKBinaryThresholdImageFilter< T > PaintbrushFilterType; typename PaintbrushFilterType::Pointer filter = PaintbrushFilterType::New(); self->InternalFilter = filter; // Set the update region to a certain region on either side of the center int extent[6], imageExtent[6]; double spacing[3], origin[3]; self->GetImageData()->GetSpacing(spacing); self->GetImageData()->GetExtent(imageExtent); double *width = self->GetPaintbrushShape()->GetWidth(); // Set the center and radius to mask out a spherical stencil, instead of // one with rectangular jagged edges. self->GetImageData()->GetOrigin(origin); extent[0] = (int)((center[0] - width[0])/spacing[0] + 0.5); extent[1] = (int)((center[0] + width[0])/spacing[0] + 0.5); extent[2] = (int)((center[1] - width[1])/spacing[1] + 0.5); extent[3] = (int)((center[1] + width[1])/spacing[1] + 0.5); extent[4] = (int)((center[2] - width[2])/spacing[2] + 0.5); extent[5] = (int)((center[2] + width[2])/spacing[2] + 0.5); vtkKWEPaintbrushUtilities::GetIntersectingExtents(extent, imageExtent, extent); // Despite the fact that the FilterModule framework supports updates on // requested extents, a lot of filters in ITK (such as the // ConfidenceConnectedImageFilter don't really support updating a subextent. // So in most cases, you will have to extract a VOI). vtkExtractVOI *extractVOI = vtkExtractVOI::New(); extractVOI->SetInput( self->GetImageData()); extractVOI->SetVOI(extent); // Extract the first component vtkImageExtractComponents * extractComponent = vtkImageExtractComponents::New(); extractComponent->SetInput( extractVOI->GetOutput() ); extractComponent->GetOutput()->SetUpdateExtent( extent ); extractComponent->SetComponents(0); extractComponent->Update(); filter->SetRequestedExtent(extent); filter->SetInput( extractComponent->GetOutput() ); filter->SetRequestedExtent(extent); filter->Update(); filter->BoundWithRadiusOn(); filter->GetOutputAsStencil(stencil); extractComponent->Delete(); extractVOI->Delete(); return 1; } vtkStandardNewMacro(vtkKWEITKBinaryThresholdPaintbrushOperation) vtkCxxRevisionMacro(vtkKWEITKBinaryThresholdPaintbrushOperation, "$Revision: 1774 $"); void vtkKWEITKBinaryThresholdPaintbrushOperation:: DoOperationOnStencil(vtkImageStencilData *stencilData, double p[3]) { this->PaintbrushShape->GetStencil( stencilData, p); vtkImageStencilData * stencil = vtkImageStencilData::New(); switch (this->ImageData->GetScalarType()) { vtkitkTemplateMacro( MyPaintbrushRunner( this, p, stencil, static_cast< VTK_TT >(0))); default: { vtkErrorMacro(<< "vtkKWEITKBinaryThresholdPaintbrushOperation: Unknown ScalarType"); break; } } // Remove everything in the stencil. stencilData->AllocateExtents(); // This will be the stuff that's filtered through the operation. In this // case the stuff in stencilData, thresholded. stencilData->Add(stencil); stencil->Delete(); } int my_example( int , char *[], vtkKWApplication * , vtkKWMyWindow * example ) { example->Initialize(); vtkImageData * imageData = example->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); vtkKWEITKBinaryThresholdPaintbrushOperation * operation = vtkKWEITKBinaryThresholdPaintbrushOperation::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( example->GetNthRenderWidget(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); vtkKWEPaintbrushShapeBox * shape = vtkKWEPaintbrushShapeBox::New(); rep->SetImageActor( example->GetNthImageActor(i) ); // Note that an operation if set, must be set before the image data. rep->SetPaintbrushOperation(operation); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->SetPaintbrushShape(shape); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); set->AddWidget(w); shape->Delete(); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } set->SetEnabled(1); int res = example->Run(); operation->Delete(); set->Delete(); return res; } vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/vtkKWMyWindow.h0000644000175000017500000003033111500717532023030 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef __vtkKWMyWindow_h #define __vtkKWMyWindow_h #include "vtkKWObject.h" #include "vtkKWApplication.h" #include "vtkKWRenderWidget.h" #include "vtkImageActor.h" #include "vtkImageData.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include #include #include #include #include #include "VTKEdgeConfigure.h" // export //BTX // Convenience macro for the examples "KWLIBS_CREATE_EXAMPLE" #define KWLIBS_CREATE_EXAMPLE_MACRO \ \ int my_main(int argc, char *argv[]) \ { \ Tcl_Interp *interp = vtkKWApplication::InitializeTcl(argc, argv, &cerr); \ if (!interp) \ { \ cerr << "Error: InitializeTcl failed" << endl ; \ return 1; \ } \ \ Kwmywindowlib_Init(interp); \ \ vtkKWApplication *app = vtkKWApplication::New(); \ vtkKWMyWindow *example = vtkKWMyWindow::New(); \ example->SetApplication(app); \ \ vtksys::CommandLineArguments arg; \ arg.Initialize(argc, argv); \ typedef vtksys::CommandLineArguments argT; \ char * data_filename = NULL; \ arg.AddArgument("--data", argT::SPACE_ARGUMENT, &data_filename, \ "Input data to paint on"); \ arg.Parse(); \ \ if (data_filename && vtksys::SystemTools::FileExists( \ data_filename)) \ { \ example->SetFilename(data_filename); \ } \ else \ { \ vtkstd::vector< vtksys_stl::string > stringArray; \ stringArray.push_back(vtkKWMyWindow::GetExampleDataPath()); \ stringArray.push_back("HeadMR.mha"); \ vtksys_stl::string fn = vtksys::SystemTools::JoinPath(stringArray); \ vtksys::SystemTools::ConvertToUnixSlashes(fn); \ example->SetFilename(fn.c_str()); \ } \ example->CreateInfo( __FILE__, app ); \ \ int res = my_example( argc, argv, app, example ); \ example->Delete(); \ app->Delete(); \ return res; \ } #define KWLIBS_CREATE_WINDOWS_EXAMPLE \ extern "C" int Kwmywindowlib_Init(Tcl_Interp *interp); \ int my_main(int argc, char *argv[]); \ int my_example( int argc, char *argv[], \ vtkKWApplication * app, \ vtkKWMyWindow * example_window ); \ int __stdcall WinMain(HINSTANCE, HINSTANCE, LPSTR lpCmdLine, int) \ { \ int argc; \ char **argv; \ vtksys::SystemTools::ConvertWindowsCommandLineToUnixArguments(lpCmdLine, &argc, &argv); \ int ret = my_main(argc, argv); \ for (int i = 0; i < argc; i++) { delete [] argv[i]; } \ delete [] argv; \ return ret; \ } \ KWLIBS_CREATE_EXAMPLE_MACRO #define KWLIBS_CREATE_UNIX_EXAMPLE \ extern "C" int Kwmywindowlib_Init(Tcl_Interp *interp); \ int my_main(int argc, char *argv[]); \ int my_example( int argc, char *argv[], \ vtkKWApplication * app, \ vtkKWMyWindow * example_window ); \ int main(int argc, char *argv[]) { return my_main(argc, argv); } \ KWLIBS_CREATE_EXAMPLE_MACRO #if defined(_WIN32) && !defined(__CYGWIN__) #include #define KWLIBS_CREATE_EXAMPLE KWLIBS_CREATE_WINDOWS_EXAMPLE #else #define KWLIBS_CREATE_EXAMPLE KWLIBS_CREATE_UNIX_EXAMPLE #endif //ETX class vtkImageViewer2; class vtkImageReader2; class vtkKWEPaintbrushWidget; class vtkKWSelectionFrame; class vtkKWSelectionFrameLayoutManager; class vtkCollection; class vtkKWScaleWithEntry; class vtkKWWindow; class vtkKWDialog; class vtkKWTextWithScrollbarsWithLabel; class vtkKWRadioButtonSet; // ------- The window class used by all examples ------------ class vtkKWMyWindow : public vtkObject { public: static vtkKWMyWindow* New(); vtkTypeRevisionMacro(vtkKWMyWindow,vtkObject); // Description: // Initialize() must be called before Run() void Initialize(); int Run(); // Description: // Callbacks virtual void SetSliceFromScaleCallback (double value); virtual void SetSliceFromScaleCallback0(double value); virtual void SetSliceFromScaleCallback1(double value); virtual void SetSliceFromScaleCallback2(double value); void RenderWidgetSelectionChangedCallback( const char * title, vtkKWSelectionFrame * ); // Description: // Filename of the data to be loaded. vtkSetStringMacro( Filename ); vtkGetStringMacro( Filename ); // Description: // Get the Window class vtkGetObjectMacro( Window, vtkKWWindow ); // Description: // Default is a single render window. However you can display // Axial, Sagittal, Coronal, Blank render windows simultaneously vtkSetMacro( FourPaneView, int ); vtkGetMacro( FourPaneView, int ); vtkBooleanMacro( FourPaneView, int ); // Description: // Get the render widgets. vtkKWRenderWidget * GetAxialRenderWidget() { return this->GetNthRenderWidget(0); } vtkKWRenderWidget * GetCoronalRenderWidget() { return this->GetNthRenderWidget(1); } vtkKWRenderWidget * GetSagittalRenderWidget() { return this->GetNthRenderWidget(2); } vtkKWRenderWidget * GetNthRenderWidget( int i ); // Description: // Get the image actors vtkImageActor * GetAxialImageActor() { return this->GetNthImageActor(0); } vtkImageActor * GetCoronalImageActor() { return this->GetNthImageActor(1); } vtkImageActor * GetSagittalImageActor() { return this->GetNthImageActor(2); } vtkImageActor * GetNthImageActor( int i ); // Description: // Set/Get the input image data that the actors are showing. This may be // set explicitly as below, or may be supplied via a user-argument to the // example application as "--data somefile.mha" . If no input is specified, // a default head MRI image is loaded up. vtkGetObjectMacro( Input, vtkImageData ); virtual void SetInput( vtkImageData * ); // Description: // Internally used to display a top level dialog with code //BTX void CreateInfo( vtksys_stl::string name, vtkKWApplication * app ); // Description: // Get the path where testing data is stored. static vtksys_stl::string GetExampleDataPath() { vtksys_stl::string fname_base = vtksys::SystemTools::GetFilenamePath(__FILE__); vtkstd::vector< vtksys_stl::string > stringArray; stringArray.push_back(fname_base); stringArray.push_back("/../../../Data/"); stringArray.push_back("Data"); vtksys_stl::string fn = vtksys::SystemTools::JoinPath(stringArray); vtksys::SystemTools::ConvertToUnixSlashes(fn); fn += "/"; return fn; } // Description: // Given a filename, looks in the example path and returns the fullfilename // with path. static vtksys_stl::string ExpandFilename( const char * s ); //ETX void SetApplication( vtkKWApplication * a ); vtkKWApplication *GetApplication() { return this->Application; } // Description: // Easy way to tie the Select and edit mode callbacks to the paintbrush // widget whenever the radio button is depressed. Basically this will simply // cause the method // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Edit ) or // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Select ) // to be invoked based on which radio button is depressed. void AddSelectEditCallback( vtkKWEPaintbrushWidget * w ); //BTX typedef void (*SelectEditCallbackMethodType)( vtkKWEPaintbrushWidget *, int editMode ); void SetSelectEditCallbackMethod( SelectEditCallbackMethodType ); //ETX // Description // INTERNAL - do not use. void SelectEditCallback(); // Description: // Callbacks for the examples to plug things into void AddSketchCallback() { this->AddSketchCallbackMethod(this->CallData); }; //BTX // User specified callbacks void (*AddSketchCallbackMethod)(void*); void *CallData; //ETX protected: vtkKWMyWindow(); ~vtkKWMyWindow(); vtkKWApplication *Application; vtkImageViewer2 *ImageViewer[3]; vtkKWScaleWithEntry *SliceScale[3]; vtkKWSelectionFrameLayoutManager *SelectionFrameLayoutManager; vtkKWSelectionFrame *SelectionFrame; vtkKWWindow *Window; vtkImageData *Input; vtkKWDialog *InfoDialog; vtkKWTextWithScrollbarsWithLabel *CxxSourceText; char * Filename; int FourPaneView; vtkKWRadioButtonSet *SelectEditRadioButtons; vtkCollection *Widgets; SelectEditCallbackMethodType SelectEditCallbackMethod; // Get the renderwidget packed into a selection frame static vtkKWRenderWidget * GetRenderWidget( vtkKWSelectionFrame * ); virtual void UpdateSliceRanges(); void GetValidReader( vtkImageReader2 * & reader, const char * filename); private: vtkKWMyWindow(const vtkKWMyWindow&); // Not implemented. void operator=(const vtkKWMyWindow&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/PaintbrushExample9.cxx0000644000175000017500000000642111363410610024360 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This example demonstrates how you can use a vtkKWEPaintbrushWidget to create // and edit segmentations on a render window. Basic editing capabilities, // drawing, erasing, resizing the brush, undo-redo etc are demonstrated in // this example. // // User interactions: // Left click and drag - Draws a stroke // Ctrl-Left click and - Erases the stroke // Backspace or Left keypress - Undo the sketch (deletes the previously // drawn stroke in a sketch) // Right keypress - Redo on the given sketch // Shift "+" - Start a new sketch. // Shift Right - Traverse to the next sketch. // Shift Left - Traverse to the previous sketch. // Shift Backspace - Delete a sketch. // Escape - Toggle Enable/Disable a brush. #include "vtkKWMyWindow.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" KWLIBS_CREATE_EXAMPLE // Macro fires up a basic app with some data void MySelectEditCallbackMethod( vtkKWEPaintbrushWidget *w, int editMode ) { w->SetPaintbrushMode( editMode ? vtkKWEPaintbrushWidget::Edit : vtkKWEPaintbrushWidget::Select ); } int my_example( int, char *[], vtkKWApplication * , vtkKWMyWindow * example ) { example->FourPaneViewOff(); example->Initialize(); vtkImageData * imageData = example->GetInput(); vtkKWEPaintbrushWidget *widget = vtkKWEPaintbrushWidget::New(); widget->SetInteractor( example->GetAxialRenderWidget()-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(widget->GetRepresentation()); rep->SetImageActor( example->GetAxialImageActor() ); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); widget->SetEnabled(1); // This will simply cause the method // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Edit ) or // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Select ) // to be invoked based on which radio button is depressed. example->SetSelectEditCallbackMethod( MySelectEditCallbackMethod ); example->AddSelectEditCallback(widget); int res = example->Run(); widget->Delete(); return res; } vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/PaintbrushExample2.cxx0000644000175000017500000000631611363410610024354 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // Unlike PaintbrushExample1, this example shows how the user can use a // vtkKWEWidgetGroup to tie multiple paintbrushes to paint on several // render windows. Here a paintbrush can be used on a 3 pane view. #include "vtkKWMyWindow.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEWidgetGroup.h" KWLIBS_CREATE_EXAMPLE // Macro fires up a basic app with some data void MySelectEditCallbackMethod( vtkKWEPaintbrushWidget *w, int editMode ) { w->SetPaintbrushMode( editMode ? vtkKWEPaintbrushWidget::Edit : vtkKWEPaintbrushWidget::Select ); } int my_example( int , char *[], vtkKWApplication * , vtkKWMyWindow * example ) { example->Initialize(); vtkImageData * imageData = example->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( example->GetNthRenderWidget(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); rep->SetImageActor( example->GetNthImageActor(i) ); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); set->AddWidget(w); // This will simply cause the method // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Edit ) or // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Select ) // to be invoked based on which radio button is depressed. example->SetSelectEditCallbackMethod( MySelectEditCallbackMethod ); example->AddSelectEditCallback(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } set->SetEnabled(1); int res = example->Run(); set->Delete(); return res; } vtkedge-0.2.0~20110819/Examples/GUI/KWWidgets/PaintbrushLabelMapSimpleExample.cxx0000644000175000017500000002362211363410610027041 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This example loads a file IBSRData.mha and a label map IBSRLabelMap-UCHAR.mha. // The label map, (courtesy of IBSR) is a label map with 62 segmentations. This // example creates a sketch from each label and initializes the drawing with // these sketches. It also assigns user specified colors to the sketches. // ---------------------------------------------------------------------------- // // User interactions: // // The follwing interactions are supported by the brush in Edit mode. // Left click and drag - Draws a stroke // Ctrl-Left click and drag - Erases the stroke // Backspace or Left key - Undo the sketch (deletes the previously drawn stroke in a sketch) // Right key - Redo on the given sketch // Shift "+" - Start a new sketch. // Shift Right - Traverse to the next sketch. // Shift Left - Traverse to the previous sketch. // Shift Backspace - Delete a sketch. // Right click and drag - Resize the shape isotropically // Ctrl-Right click and drag - Resize the shape anisotropically // Shift "<" - Decrease the opacity of the overlaid drawing // Shift ">" - Increase the opacity of the overlaid drawing // "l" key - Render the current sketch immutable/mutable. // (Supported only when editing labelmaps) // Escape - Enable/Disable interactions // // The follwing interactions are supported by the brush in Select Mode // Left click - Select/Unselect a sketch // Left click and drag - Drag and drop merge of sketches. // Backspace key - Delete selected sketches. // "m" key - Merge selected sketches. // Escape - Enable/Disable interactions #include "vtkKWMyWindow.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include "vtkMultiThreader.h" #include #include #include class PaintbrushExample8Labels { public: class Annotation { public: Annotation() {}; Annotation(const std::string &l, unsigned char r, unsigned char g, unsigned char b ) { label = l; R = r; G = g; B = b; } bool operator!=(const Annotation &a) const { return a.label != this->label; } std::string label; unsigned char R, G, B; }; std::map< unsigned short, Annotation > LabelMap; }; void MySelectEditCallbackMethod( vtkKWEPaintbrushWidget *w, int editMode ) { w->SetPaintbrushMode( editMode ? vtkKWEPaintbrushWidget::Edit : vtkKWEPaintbrushWidget::Select ); } KWLIBS_CREATE_EXAMPLE // Macro fires up a basic app with some data int my_example( int , char *[], vtkKWApplication * , vtkKWMyWindow * example ) { vtkMultiThreader::SetGlobalMaximumNumberOfThreads(1); typedef PaintbrushExample8Labels::Annotation AnnotationType; PaintbrushExample8Labels MyLabels; MyLabels.LabelMap[42]=AnnotationType("Right-Cerebral-Cortex", 205 , 62, 78 ); MyLabels.LabelMap[43]=AnnotationType("Right-Lateral-Ventricle", 120 , 18, 134 ); example->SetFilename( vtkKWMyWindow::ExpandFilename("IBSRData.mha").c_str()); example->Initialize(); vtkImageData * imageData = example->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( example->GetNthRenderWidget(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); if (rep) { vtkImageActor * imageActor = example->GetNthImageActor(i); rep->SetImageActor(imageActor); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } // This will simply cause the method // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Edit ) or // w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Select ) // to be invoked based on which radio button is depressed. example->SetSelectEditCallbackMethod( MySelectEditCallbackMethod ); example->AddSelectEditCallback(w); set->AddWidget(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); // Our internal representation will be to manage a label map. drawing->SetRepresentationToLabel(); // This will allocate our canvas based on the size of the overlay image // that was set on the WidgetRepresentation. drawing->InitializeData(); // Clear the drawing and start on a clean slate. The drawing would have // automatically created 1 empty sketch for us, so we can start drawing // right away. Let's remove it, since we'd like to initialize the drawing // with our IBSR label map. drawing->RemoveAllItems(); // Read the IBSR label map vtkMetaImageReader * reader = vtkMetaImageReader::New(); reader->SetFileName( vtkKWMyWindow::ExpandFilename("IBSRLabelMap-USHORT-2Labels.mha").c_str() ); reader->Update(); // Create a PaintbrushLabelData to represent the label map. vtkKWEPaintbrushLabelData *paintbrushLabelMap = vtkKWEPaintbrushLabelData::New(); paintbrushLabelMap->SetLabelMap( reader->GetOutput() ); // Set the label map as the initial canvas data of the drawing. drawing->SetPaintbrushData( paintbrushLabelMap ); // Create a sketch for each label in the label map, we'd like to edit. // NOTE: We can skip labels in the label map that we do not care about simply // by not adding a sketch corresponding to that label into the drawing. In // this case, we will take into account all the labels (1-62). // NOTE: As a reminder, bear in mind that 0 is a reserved value and must not // be used as a label. for (std::map< unsigned short, AnnotationType >::const_iterator cit = MyLabels.LabelMap.begin(); cit != MyLabels.LabelMap.end(); ++cit) { // For each label. // Initialize the sketch with the label map. Note that you must add the // sketch to the drawing and set the label you wish the sketch to represent // before you initialize it from the label map. // Also note that when the representation is a "Label-map", all sketches // share the same label map to avoid memory duplication. The corollary to // this is that if you initialize sketches in your drawing using a labelmap, // you must use the same "vtkKWEPaintbrushLabelData" that is used by the // drawing. vtkKWEPaintbrushSketch * sketch = vtkKWEPaintbrushSketch::New(); drawing->AddItem( sketch ); sketch->SetLabel( cit->first ); sketch->Initialize( paintbrushLabelMap ); // Optionally, the identifier can be used to display text annotations as // you navigate through your maze of sketches. 62 segmentations can sure // get you lost pretty quickly. sketch->GetPaintbrushProperty()->SetIdentifier(cit->second.label.c_str()); // Assign a nice color to the sketch. double sketchColor[3] = { (double)(cit->second.R)/255.0, (double)(cit->second.G)/255.0, (double)(cit->second.B)/255.0 }; sketch->GetPaintbrushProperty()->SetColor( sketchColor ); sketch->Delete(); } reader->Delete(); // Now set the drawing on all representations (axial, coronal and sagittal) // in the WidgetSet. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } // Enable the widget and we are done. set->SetEnabled(1); int res = example->Run(); // Save out each of the resulting segmentations. We will write out each // sketch in the drawing as a seperate file. This will take a while. You // might have noticed that when you quit this application it takes a while, // This is because we are writing out our edited segmentation for validation. const bool writeOutResults = false; if (writeOutResults) { vtkKWEPaintbrushLabelData * finalLabelMap = vtkKWEPaintbrushLabelData::SafeDownCast(drawing->GetPaintbrushData()); vtkMetaImageWriter * outputWriter = vtkMetaImageWriter::New(); outputWriter->SetFileName("EditedLabelMap.mha"); outputWriter->SetInput( finalLabelMap->GetLabelMap() ); outputWriter->Write(); outputWriter->Delete(); } paintbrushLabelMap->Delete(); set->Delete(); return res; } vtkedge-0.2.0~20110819/Examples/CMakeLists.txt0000644000175000017500000000224011363410610020347 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Just add all the subdirectories # ----------------------------------------------------------------------------- set(kits Filtering Hybrid Rendering ) foreach(kit ${kits}) if(VTKEdge_BUILD_${kit}_KIT) add_subdirectory(${kit}) endif(VTKEdge_BUILD_${kit}_KIT) endforeach(kit) if (VTKEdge_BUILD_Widgets_KIT) subdirs( GUI ) endif(VTKEdge_BUILD_Widgets_KIT) vtkedge-0.2.0~20110819/Examples/Hybrid/0000755000175000017500000000000011630435007017036 5ustar mathieumathieuvtkedge-0.2.0~20110819/Examples/Hybrid/Cxx/0000755000175000017500000000000011630435007017600 5ustar mathieumathieuvtkedge-0.2.0~20110819/Examples/Hybrid/Cxx/CMakeLists.txt0000644000175000017500000000165611363410610022344 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= set(exe ${VTKEdge_EXAMPLE_EXECUTABLE_PREFIX}GPUArrayCalculatorDemo) add_executable(${exe} GPUArrayCalculatorDemo.cxx) target_link_libraries(${exe} vtkKWEHybrid) install_targets(${VTKEdge_INSTALL_BIN_DIR} ${exe}) vtkedge-0.2.0~20110819/Examples/Hybrid/Cxx/GPUArrayCalculatorDemo.cxx0000644000175000017500000000600011363410610024565 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // Example demonstrating use of vtkKWEGPUArrayCalculator filter. #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkKWEGPUArrayCalculator.h" #include "vtkRenderWindow.h" #include "vtkImageImport.h" #include // On a nVidia Quadro FX 3600M (~GeForce8), // GL_MAX_TEXTURE_SIZE = 8192, GL_MAX_3D_TEXTURE_SIZE = 2048 // GL_MAX_VIEWPORT_DIMS = 8192, 8192 // The following size matches two complete full 2D textures, one 2D texture // with one complete row and one 2D texture with just one pixel. //const vtkIdType TestNumberOfPoints=2*(8192*8192)+8192+1; const vtkIdType TestNumberOfPoints=(2*(8192*8192)+8192+1); vtkImageImport *CreateSource(vtkIdType numberOfPoints) { assert("pre: valid_number_of_points" && numberOfPoints>0); vtkImageImport *im=vtkImageImport::New(); float *ptr=new float[numberOfPoints]; vtkIdType i=0; while(i(i); ++i; } im->SetDataScalarTypeToFloat(); im->SetImportVoidPointer(ptr,0); // let the importer delete it. im->SetNumberOfScalarComponents(1); im->SetDataExtent(0,static_cast(numberOfPoints-1),0,0,0,0); im->SetWholeExtent(0,static_cast(numberOfPoints-1),0,0,0,0); im->SetScalarArrayName("values"); return im; } // Example demonstrating use of vtkKWEGPUArrayCalculator filter. int GPUArrayCalculatorDemo(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) { vtkRenderWindow *win=vtkRenderWindow::New(); // Create an dataset with an array of values to work with. vtkImageImport *im=CreateSource(TestNumberOfPoints); // Create the calculator vtkKWEGPUArrayCalculator *calc=vtkKWEGPUArrayCalculator::New(); // Need an OpenGL context calc->SetContext(win); calc->SetInputConnection(0,im->GetOutputPort(0)); // reader or source // We just state that Result:=exp(sqrt(sin(values)*cos(values)+10.0)) calc->AddScalarArrayName("values"); calc->SetResultArrayName("Result"); calc->SetFunction("exp(sqrt(sin(values)*cos(values)+10.0))"); // Perform the computation calc->Update(); // The result in in calc2->GetOutput(). calc->Delete(); win->Delete(); im->Delete(); return 0; // !retVal; 0: passed, 1: failed } #ifndef KWE_TESTING int main(int argc, char* argv[]) { return GPUArrayCalculatorDemo(argc, argv); } #endif vtkedge-0.2.0~20110819/Examples/Hybrid/CMakeLists.txt0000644000175000017500000000166211363410610021577 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Just add all the subdirectories # ----------------------------------------------------------------------------- add_subdirectory(Cxx) vtkedge-0.2.0~20110819/Examples/Filtering/0000755000175000017500000000000011630435007017540 5ustar mathieumathieuvtkedge-0.2.0~20110819/Examples/Filtering/Cxx/0000755000175000017500000000000011630435007020302 5ustar mathieumathieuvtkedge-0.2.0~20110819/Examples/Filtering/Cxx/CMakeLists.txt0000644000175000017500000000174611363410610023046 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= set(exe ${VTKEdge_EXAMPLE_EXECUTABLE_PREFIX}ObjectTreeDemo) include_directories(${VTKEdge_BINARY_DIR}/Filtering) add_executable(${exe} ObjectTreeDemo.cxx) target_link_libraries(${exe} vtkKWEFiltering vtkKWERendering) install_targets(${VTKEdge_INSTALL_BIN_DIR} ${exe}) vtkedge-0.2.0~20110819/Examples/Filtering/Cxx/ObjectTreeDemo.cxx0000644000175000017500000007610511363410610023666 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkCamera.h" #include "vtkDoubleArray.h" #include "vtkIntArray.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationDoubleKey.h" #include "vtkInformationDoubleVectorKey.h" #include "vtkInformationIdTypeKey.h" #include "vtkInformationIntegerKey.h" #include "vtkInformationIntegerVectorKey.h" #include "vtkInformationIterator.h" #include "vtkInformationObjectBaseKey.h" #include "vtkInformationStringKey.h" #include "vtkKWEUUID.h" #include "vtkKWEInformationKeyMap.h" #include "vtkKWEObjectTreeColorProperty.h" #include "vtkKWEObjectTreeTransformableNode.h" #include "vtkKWEObjectTreeNodeIterator.h" #include "vtkKWEObjectTreeUserProperty.h" #include "vtkKWESerializationHelperMap.h" #include "vtkKWEXMLArchiveWriter.h" #include "vtkKWEXMLArchiveReader.h" #include "vtkKWEXMLElement.h" #include "vtkKWEFilteringInstantiator.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" #include "vtkTransform.h" #include "vtkCommonInstantiator.h" #include "vtkRenderingInstantiator.h" #include #include vtkInformationDoubleKey *testUserDoubleKey; vtkInformationIdTypeKey *testUserIdTypeKey; vtkInformationIntegerKey *testUserIntKey; vtkInformationStringKey *testUserStringKey; vtkInformationIntegerVectorKey *testUserIntVectorKey; vtkInformationDoubleVectorKey *testUserDoubleVectorKey; // global so we can easily add it to the objects we write out vtkSmartPointer camera; #define PASS 0 #define FAIL 1 int BuildOriginalTree(vtkKWEObjectTreeNodeBase *root) { int buildResult = PASS; root->SetName("RootNode"); vtkKWEObjectTreeTransformableNode *(child[10]); char name[20]; // add a vtkIntArray as the node's NodeObject vtkSmartPointer intArray = vtkSmartPointer::New(); intArray->SetNumberOfComponents(1); intArray->SetNumberOfTuples(1); intArray->SetTuple1(0, 10); vtkInformation *arrayInfo = intArray->GetInformation(); // using a key we're already registering... arrayInfo->Set( vtkKWEObjectTreeNodeBase::NAME(), "My Int Array"); root->SetNodeObject( intArray ); // 5 children of the root node for (int i = 0; i < 5; i++) { child[i] = vtkKWEObjectTreeTransformableNode::New(); sprintf(name, "Node %d (child)", i); child[i]->SetName(name); root->AddChild(child[i]); child[i]->Delete(); } // add a vtkDoubleArray as one of the children's NodeObject vtkKWEObjectTreeNodeBase *tmpPtr = root->GetChild(1); vtkSmartPointer doubleArray = vtkSmartPointer::New(); doubleArray->SetNumberOfComponents(3); doubleArray->SetNumberOfTuples(1); doubleArray->SetTuple3(0, 5.5, 4.4, 3.3); tmpPtr->SetNodeObject( doubleArray ); // add a vtkIdTypeArray as one of the children's NodeObject tmpPtr = root->GetChild(2); vtkSmartPointer idTypeArray = vtkSmartPointer::New(); idTypeArray->SetNumberOfComponents(3); idTypeArray->SetNumberOfTuples(2); idTypeArray->SetTuple3(0, 5, 4, 3); idTypeArray->SetTuple3(1, 2, 1, 0); tmpPtr->SetNodeObject( idTypeArray ); // add "grandchildren" to one of the nodes child[5] = vtkKWEObjectTreeTransformableNode::New(); child[5]->SetName("Node 5 (grandchild)"); vtkSmartPointer tmpTransform2 = vtkSmartPointer::New(); tmpTransform2->Translate(5.0, 0, 0); child[5]->SetTransform(tmpTransform2); tmpPtr->AddChild(child[5]); child[5]->Delete(); // actually add a transform child[6] = vtkKWEObjectTreeTransformableNode::New(); child[6]->SetName("Node 6 (grandchild)"); vtkSmartPointer tmpTransform = vtkSmartPointer::New(); child[6]->SetTransform(tmpTransform); camera = vtkSmartPointer::New(); camera->Print(cout); child[6]->SetNodeObject( camera ); tmpPtr->InsertChild(0, child[6]); child[6]->Delete(); // add a node of the base node type, for iteration example in TestIteration vtkKWEObjectTreeNodeBase *baseChild = vtkKWEObjectTreeNodeBase::New(); baseChild->SetName("Node 7 (grandchild)"); tmpPtr->InsertChild(1, baseChild); baseChild->Delete(); // and finally, one great grandchild (that doesn't inherit proeprties) child[8] = vtkKWEObjectTreeTransformableNode::New(); child[8]->SetName("Node 8 (great-grandchild)"); child[8]->InheritPropertiesOff(); baseChild->AddChild(child[8]); child[8]->Delete(); // now remove some children root->RemoveChild(child[0]); root->RemoveChild(3); // and finally, start adding some properties vtkSmartPointer colorProp = vtkSmartPointer::New(); double tmpColor[3] = {0.1, 0.5, 0.1}; colorProp->SetColor(tmpColor); vtkSmartPointer childIterator = vtkSmartPointer::New(); childIterator->SetBaseNode( tmpPtr ); childIterator->SetTraversalToChildrenOnly(); vtkKWEObjectTreeNodeBase *currentChild; cout << "Iterating through children of Node 2:\n"; for (childIterator->InitTraversal(); (currentChild = childIterator->GetCurrentNode()); childIterator->GoToNextNode()) { cout << " " << currentChild->GetName() << "\n"; // want to add to "Node 6" if (!strcmp(currentChild->GetName(), "Node 6 (grandchild)")) { if (currentChild->AddProperty(colorProp) == 0) { cout << "Unable to add property (already exists)!!!!\n\n"; buildResult = FAIL; } } } // actually set the Object on one of the nodes; We want it to be serialized, // so that we get something more than ; thus set // as the Property we just created. baseChild->SetNodeObject( colorProp ); vtkSmartPointer colorProp2 = vtkSmartPointer::New(); // the correct result is that we shouldn't be able to add the same // property to the node again if (!child[6]->AddProperty(colorProp2) == 0) { cout << "Property added!!!\n\n"; buildResult = FAIL; } // but now remove the original and try adding again, which should succeed if (!child[6]->RemoveProperty( colorProp )) { cout << "Prop NOT removed!!!!\n\n"; buildResult = FAIL; } if (child[6]->AddProperty(colorProp2) == 0) { cout << "Unable to add property (already exists)!!!!\n\n"; buildResult = FAIL; } // modify the color property bool inheritedPropertyFlag; vtkKWEObjectTreeColorProperty *getColorProp = vtkKWEObjectTreeColorProperty::SafeDownCast( child[6]->GetProperty(vtkKWEObjectTreeColorProperty::KEY(), inheritedPropertyFlag) ); double newColor[3] = {1, 1, 1}; if (getColorProp) { getColorProp->SetColor(newColor); } // now add a "user" property vtkSmartPointer userProp = vtkSmartPointer::New(); // make up some keys for the user property testUserIntKey = new vtkInformationIntegerKey("UserIntValue", "testTree"); userProp->GetAttributesPointer()->Set(testUserIntKey, 5); testUserDoubleKey = new vtkInformationDoubleKey("UserDoubleValue", "testTree"); userProp->GetAttributesPointer()->Set(testUserDoubleKey, 37.2); testUserIdTypeKey = new vtkInformationIdTypeKey("UserIdTypeValue", "testTree"); userProp->GetAttributesPointer()->Set(testUserIdTypeKey, 9); testUserStringKey = new vtkInformationStringKey("UserStringValue", "testTree"); userProp->GetAttributesPointer()->Set(testUserStringKey, "Test String"); testUserIntVectorKey = new vtkInformationIntegerVectorKey("UserIntVectorValue", "testTree",3); int white[3] = {255, 255, 255}; userProp->GetAttributesPointer()->Set(testUserIntVectorKey, white, 3); testUserDoubleVectorKey = new vtkInformationDoubleVectorKey("UserDoubleVectorValue","testTree",2); double tmpDouble[2] = {3.14, 10.0}; userProp->GetAttributesPointer()->Set(testUserDoubleVectorKey, tmpDouble, 2); // and now registor the keys so they will be serialized (specifically, read in) vtkKWEInformationKeyMap::RegisterKey(testUserDoubleKey); vtkKWEInformationKeyMap::RegisterKey(testUserIdTypeKey); vtkKWEInformationKeyMap::RegisterKey(testUserIntKey); vtkKWEInformationKeyMap::RegisterKey(testUserStringKey); vtkKWEInformationKeyMap::RegisterKey(testUserIntVectorKey); vtkKWEInformationKeyMap::RegisterKey(testUserDoubleVectorKey); // and, of course, add the property to a node if (child[2]->AddProperty(userProp) == 0) { cout << "Unable to add property (already exists)!!!!\n\n"; buildResult = FAIL; } // and, add it to another node child[6]->AddProperty(userProp); // the internal state... primarily to get coverage for the PrintSelf methods root->Print(cout); return buildResult; } int CompareIterationResult(vtkKWEObjectTreeNodeIterator *iterator, vtkstd::string *(expectedResult), int expectedCount) { int testResult = PASS; vtkKWEObjectTreeNodeBase *currentNode; int iterationIndex = 0; for (iterator->InitTraversal(); (currentNode = iterator->GetCurrentNode()); iterator->GoToNextNode(), iterationIndex++) { vtkstd::string testString; for (int i = 0; i < iterator->GetCurrentDepth(); i++) { testString += " "; } testString += currentNode->GetName(); cout << testString; if (iterationIndex >= expectedCount || expectedResult[iterationIndex] != testString) { cout << " (WRONG!)\n"; testResult = FAIL; } else { cout << "\n"; } } if (iterationIndex != expectedCount) { cout << "Iteration error: expected " << expectedCount << " nodes, but iterated over " << iterationIndex << "\n"; testResult = FAIL; } return testResult; } int TestIteration( vtkKWEObjectTreeNodeBase *root ) { int testResult = PASS; // Iteration Test/Example 0 // "test" the iterator vtkSmartPointer iterator = vtkSmartPointer::New(); iterator->SetBaseNode( root ); iterator->SetTraversalToChildrenOnly(); cout << "EXAMPLE 0: Iterating over the children of the BaseNode:\n"; vtkstd::string expectedResult0[3] = {" Node 1 (child)", " Node 2 (child)"," Node 3 (child)"}; testResult = CompareIterationResult(iterator, expectedResult0, 3) == FAIL ? FAIL : testResult; // Iteration Test/Example 1 // now the whole tree, depth-first iterator->SetTraversalToEntireSubtree(); iterator->SetTraversalModeToDepthFirst(); cout << "\nEXAMPLE 1: Iterating through root (depth-first):\n"; vtkstd::string expectedResult1[8] = {"RootNode"," Node 1 (child)", " Node 2 (child)"," Node 6 (grandchild)"," Node 7 (grandchild)", " Node 8 (great-grandchild)"," Node 5 (grandchild)", " Node 3 (child)"}; testResult = CompareIterationResult(iterator, expectedResult1, 8) == FAIL ? FAIL : testResult; // Iteration Test/Example 2 // now the whole tree, but breadth-first iterator->SetTraversalModeToBreadthFirst(); cout << "\nEXAMPLE 2: Iterating through root (breadth-first):\n"; vtkstd::string expectedResult2[8] = {"RootNode"," Node 1 (child)", " Node 2 (child)"," Node 3 (child)"," Node 6 (grandchild)", " Node 7 (grandchild)"," Node 5 (grandchild)", " Node 8 (great-grandchild)",}; testResult = CompareIterationResult(iterator, expectedResult2, 8) == FAIL ? FAIL : testResult; // Iteration Test/Example 3 // now only nodes that have a UserProperty vtkSmartPointer patternNode = vtkSmartPointer::New(); vtkSmartPointer userProp = vtkSmartPointer::New(); patternNode->AddProperty(userProp); iterator->SetPatternNode( patternNode ); cout << "\nEXAMPLE 3: Iterating through root (breadth-first), with matching node:\n"; vtkstd::string expectedResult3[2] = {" Node 2 (child)"," Node 6 (grandchild)"}; testResult = CompareIterationResult(iterator, expectedResult3, 2) == FAIL ? FAIL : testResult; // Iteration Test/Example 4 // now only nodes that have a UserProperty... which can be inherited; // Note, "Node 7" will inherit a UserProperty but is of the wrong type // (the PatternNode is more specific... vtkKWEObjectTreeTransformableNode) // We repeat the same test in Test/Example 5, but make the PatternNode a // vtkKWEObjectTReeNodeBase, which will then include "Node 7" iterator->ConsiderInheritedPropertiesOn(); cout << "\nEXAMPLE 4: Iterating through root (breadth-first), with matching node \n(can inherit property):\n"; vtkstd::string expectedResult4[3] = {" Node 2 (child)", " Node 6 (grandchild)"," Node 5 (grandchild)"}; testResult = CompareIterationResult(iterator, expectedResult4, 3) == FAIL ? FAIL : testResult; // Iteration Test/Example 5 // Same as #4, add an identity transform vtkSmartPointer transform = vtkSmartPointer::New(); patternNode->SetTransform(transform); cout << "\nEXAMPLE 5: Iterating through root (breadth-first), with matching node \n(can inherit property) and identity transform:\n"; vtkstd::string expectedResult5[1] = {" Node 6 (grandchild)"}; testResult = CompareIterationResult(iterator, expectedResult5, 1) == FAIL ? FAIL : testResult; // Iteration Test/Example 6 // Save as #4, but now the PatternNode is a vtkKWEObjectTreeNodeBase, so that // all vtkKWEObjectTreeNodeBase(s) and subclasses are potential matches vtkSmartPointer basePatternNode = vtkSmartPointer::New(); basePatternNode->AddProperty(userProp); iterator->SetPatternNode( basePatternNode ); cout << "\nEXAMPLE 6: Iterating through root (breadth-first), with (more basic) \nPatternNode (+ can inherit property):\n"; vtkstd::string expectedResult6[4] = {" Node 2 (child)", " Node 6 (grandchild)"," Node 7 (grandchild)"," Node 5 (grandchild)"}; testResult = CompareIterationResult(iterator, expectedResult6, 4) == FAIL ? FAIL : testResult; // Iteration Test/Example 6 // Find the Camera.... basePatternNode->RemoveAllProperties(); vtkSmartPointer tmpCamera = vtkSmartPointer::New(); basePatternNode->SetNodeObject( tmpCamera ); cout << "\nEXAMPLE 7: Iterating through root to find the (any) camera\n"; vtkstd::string expectedResult7[1] = {" Node 6 (grandchild)"}; testResult = CompareIterationResult(iterator, expectedResult7, 1) == FAIL ? FAIL : testResult; cout << endl; return testResult; } //----------------------------------------------------------------------------- template bool AreScalarKeysEqual(vtkInformation* thisInfo, vtkInformation* testInfo, KeyType* key) { // if thisInfo doesn't have the key or the key values don't match, return false if (!thisInfo->Has(key) || testInfo->Get(key) != thisInfo->Get(key)) { return false; } return true; } //----------------------------------------------------------------------------- template bool AreVectorKeysEqual(vtkInformation* thisInfo, vtkInformation* testInfo, KeyType* key) { if (!thisInfo->Has(key) || thisInfo->Length(key) != testInfo->Length(key)) { return false; } ValueType *thisValues = thisInfo->Get(key); ValueType *testValues = testInfo->Get(key); int length = testInfo->Length(key); for (int i = 0; i < length; i++) { if (thisValues[i] != testValues[i]) { return false; } } return true; } bool AreInfoObjectsEqual(vtkInformation *info0, vtkInformation *info1) { if (info0->GetNumberOfKeys() != info1->GetNumberOfKeys()) { return false; } vtkSmartPointer infoIterator = vtkSmartPointer::New(); infoIterator->SetInformation( info0 ); for (infoIterator->InitTraversal(); !infoIterator->IsDoneWithTraversal(); infoIterator->GoToNextItem()) { vtkInformationKey *key = infoIterator->GetCurrentKey(); if (key->IsA("vtkInformationIntegerKey")) { if (!AreScalarKeysEqual( info1, info0, static_cast(key))) { return false; } } else if (key->IsA("vtkInformationDoubleKey")) { if (!AreScalarKeysEqual( info1, info0, static_cast(key))) { return false; } } else if (key->IsA("vtkInformationIdTypeKey")) { if (!AreScalarKeysEqual( info1, info0, static_cast(key))) { return false; } } else if (key->IsA("vtkInformationStringKey")) { vtkInformationStringKey *stringKey = static_cast(key); if (!info1->Has(stringKey) || strcmp(info1->Get(stringKey), info0->Get(stringKey))) { return false; } } else if (key->IsA("vtkInformationIntegerVectorKey")) { if (!AreVectorKeysEqual( info1, info0, static_cast(key))) { return false; } } else if (key->IsA("vtkInformationDoubleVectorKey")) { if (!AreVectorKeysEqual( info1, info0, static_cast(key))) { return false; } } } return true; } //----------------------------------------------------------------------------- template bool AreTreeObjectDataArraysEqual(vtkKWEObjectTreeNodeBase *tree1, vtkKWEObjectTreeNodeBase *tree2) { vtkSmartPointer iterator = vtkSmartPointer::New(); iterator->SetTraversalToEntireSubtree(); vtkSmartPointer patternNode = vtkSmartPointer::New(); patternNode->SetNodeObject( vtkSmartPointer::New() ); iterator->SetPatternNode( patternNode ); vtkKWEObjectTreeNodeBase *node; ArrayType *array1 = 0, *array2 = 0; // get array from the 1st tree iterator->SetBaseNode( tree1 ); iterator->InitTraversal(); node = iterator->GetCurrentNode(); if (node) { array1 = ArrayType::SafeDownCast( node->GetNodeObject() ); } // get array from the 1st tree iterator->SetBaseNode( tree2 ); iterator->InitTraversal(); node = iterator->GetCurrentNode(); if (node) { array2 = ArrayType::SafeDownCast( node->GetNodeObject() ); } // we very much expect there to be an array in each tree, but just in case if (!array1 || !array2) { cout << "Error: Iterator failed to find vtkDataArrays of expected type\n"; return false; } if (array1->GetDataSize() != array2->GetDataSize() || array1->GetNumberOfComponents() != array2->GetNumberOfComponents()) { cout << "Error: Comparing vtkDataArrays... sizes don't match\n"; return false; } for (vtkIdType i = 0; i < array1->GetDataSize(); i++) { if (array1->GetValue(i) != array2->GetValue(i)) { cout << "Error: vtkDataArrays don't match\n"; return false; } } if (array1->HasInformation() && array2->HasInformation()) { if (!AreInfoObjectsEqual(array1->GetInformation(), array2->GetInformation())) { cout << "Error: vtkDataArray vtkInformation doesn't match!\n"; return false; } } else if (array1->HasInformation() || array2->HasInformation()) { cout << "Error: Missing vtkInformation on vtkDataArray\n"; return false; } return true; } static int ObjectTreeDemo(int argc, char* argv[]) { vtkstd::string filename; vtksys::CommandLineArguments arg; arg.StoreUnusedArguments(1); arg.Initialize(argc, argv); typedef vtksys::CommandLineArguments argT; arg.AddArgument("--input", argT::EQUAL_ARGUMENT, &filename, "(optional) Enter xml file to load for comparison to tree created in memory"); if (!arg.Parse()) { cerr << "Problem parsing arguments." << endl; cerr << arg.GetHelp() << endl; return 1; } int testResult = PASS; // Register keys with the map. This makes it possible for the // archiver to access this key when reading an archive vtkKWEInformationKeyMap::RegisterKey(vtkKWEObjectTreeNodeBase::NAME()); vtkKWEInformationKeyMap::RegisterKey(vtkKWEObjectTreeNodeBase::UUID()); vtkKWEInformationKeyMap::RegisterKey(vtkKWEObjectTreeNodeBase::STATE()); vtkKWEInformationKeyMap::RegisterKey(vtkKWEObjectTreeNodeBase::INHERIT_PROPERTIES()); vtkKWEInformationKeyMap::RegisterKey(vtkKWEObjectTreeUserProperty::KEY()); vtkKWEInformationKeyMap::RegisterKey(vtkKWEObjectTreeColorProperty::KEY()); vtkKWEInformationKeyMap::RegisterKey(vtkKWEObjectTreeColorProperty::COLOR()); vtkKWEInformationKeyMap::RegisterKey(vtkKWEObjectTreePropertyBase::IS_INHERITABLE()); // ObjectTree we build vtkSmartPointer root = vtkSmartPointer::New(); testResult = BuildOriginalTree(root); // Output the tree to an archive (a string stream) vtkSmartPointer strWriter = vtkSmartPointer::New(); vtksys_ios::ostringstream ostr; // Set to version to 1 (default is 0) strWriter->SetArchiveVersion(1); // The archiver expects a vector of objects vtkstd::vector > objs; objs.push_back(root); // just for grins, and because I just changed the input to Serialize to take // a vector of vtkObjects instead of vtkSerializableObjects, add the camera // that is the "Object" of "Node 6" to the root objects objs.push_back(camera); // The root node with be called ObjectTree. This is for // reference only. strWriter->Serialize(ostr, "ObjectTree", objs); // Print out the XML cout << ostr.str().c_str() << endl; // ObjectTree read from disk (saved previously... baseline for what we expect) if (filename != "") { // Create an input stream to read the XML back vtksys_ios::ifstream ifstr( filename.c_str() ); // Read using a vtkKWEXMLArchiveReader vtkSmartPointer reader = vtkSmartPointer::New(); vtkstd::vector > inObjs; reader->Serialize(ifstr, "ObjectTree", inObjs); ifstr.close(); // compare tree we read in to the one we built vtkKWEObjectTreeNodeBase *treeFromDisk = vtkKWEObjectTreeNodeBase::SafeDownCast( inObjs[0] ); if (!root->IsEqualTo(treeFromDisk, true)) { cout << "Error: Tree we built doesn't match baseline tree read from disk.\n\n"; testResult = FAIL; } } // Test IO via vtkKWEXMLElement instead of a stream vtkKWEXMLElement *rootElement = vtkKWEXMLElement::New(); vtkSmartPointer elemWriter = vtkSmartPointer::New(); elemWriter->Serialize(rootElement, "My Name", root); vtkSmartPointer elemReader = vtkSmartPointer::New(); vtkstd::vector > inFromElementObjs; elemReader->Serialize(rootElement, 0, inFromElementObjs); vtkKWEObjectTreeNodeBase *treeFromElement = vtkKWEObjectTreeNodeBase::SafeDownCast( inFromElementObjs[0] ); if (!root->IsEqualTo(treeFromElement, true)) { cout << "Error: Tree we built doesn't match baseline tree read from XML element.\n\n"; testResult = FAIL; } rootElement->Delete(); // Test iterating over the tree if (TestIteration(root) == FAIL) { testResult = FAIL; } ///////////////////////////////////////////////////////////////////////////// // write out the tree we built, then read it back and compare to the original // to test write/read... ///////////////////////////////////////////////////////////////////////////// char *tmpFileName = vtkTestUtilities::GetArgOrEnvOrDefault("-T", argc, argv, "VTK_TEMP_DIR", "."); vtkstd::string testOutputInputFilename = tmpFileName; delete [] tmpFileName; testOutputInputFilename += "/testObjectTree.xml"; // Create an output stream to write the XML vtksys_ios::ofstream ofstr( testOutputInputFilename.c_str() ); vtkSmartPointer writer = vtkSmartPointer::New(); // Set to version to 1 (default is 0) writer->SetArchiveVersion(1); vtkstd::vector > outObjs; outObjs.push_back(root); outObjs.push_back(root); vtkSmartPointer tmpInfo = vtkSmartPointer::New(); double tmpDouble[2] = {3.14, 10.0}; tmpInfo->Set(testUserDoubleVectorKey, tmpDouble, 2); outObjs.push_back(tmpInfo); // The root node with be called ObjectTree. This is for reference only. writer->Serialize(ofstr, "ObjectTree", outObjs); ofstr.close(); // now read it back in vtksys_ios::ifstream ifstr( testOutputInputFilename.c_str() ); // Read using a vtkKWEXMLArchiveReader vtkSmartPointer reader = vtkSmartPointer::New(); vtkstd::vector > inObjs; reader->Serialize(ifstr, "ObjectTree", inObjs); ifstr.close(); // compare tree we read in to the one we built vtkKWEObjectTreeNodeBase *treeFromDisk = 0; if (inObjs.size() > 0) { treeFromDisk = vtkKWEObjectTreeNodeBase::SafeDownCast( inObjs[0] ); if (!root->IsEqualTo(treeFromDisk, true)) { cout << "Error: Tree we built doesn't match tree written then read from disk.\n\n"; testResult = FAIL; } else // compare the data arrays { if (!AreTreeObjectDataArraysEqual(root, treeFromDisk)) { cout << "Error: vtkIntArray in tree we built doesn't match the one written then read from disk.\n\n"; testResult = FAIL; } if (!AreTreeObjectDataArraysEqual(root, treeFromDisk)) { cout << "Error: vtkIdTypeArray in tree we built doesn't match the one written then read from disk.\n\n"; testResult = FAIL; } if (!AreTreeObjectDataArraysEqual(root, treeFromDisk)) { cout << "Error: vtkDoubleArray in tree we built doesn't match the one written then read from disk.\n\n"; testResult = FAIL; } } } else { cout << "No tree(s) read.\n\n"; return FAIL; } // compare info we read in to the one we built if (inObjs.size() > 2) { vtkInformation *infoFromDisk = vtkInformation::SafeDownCast( inObjs[2] ); if (!infoFromDisk || !AreInfoObjectsEqual(infoFromDisk, tmpInfo)) { cout << "Error: vtkInfomration we built doesn't match info written then read from disk.\n\n"; testResult = FAIL; } } else { cout << "No information object read.\n\n"; testResult = FAIL; } ///////////////////////////////////////////////////////////////////////////// // Finally, let's start mucking around with the tree, trying doing various // comparisons along the way ///////////////////////////////////////////////////////////////////////////// bool inheritedPropertyFlag; vtkKWEObjectTreeUserProperty *userProperty = vtkKWEObjectTreeUserProperty::SafeDownCast( treeFromDisk->GetChild(1)->GetProperty( vtkKWEObjectTreeUserProperty::KEY(), inheritedPropertyFlag ) ); if (userProperty) { int originalValue = userProperty->GetAttributesPointer()->Get(testUserIntKey); userProperty->GetAttributesPointer()->Set(testUserIntKey, originalValue + 2); if (root->IsEqualTo( treeFromDisk, true )) { cout << "changed a property; should be different!!!\n\n"; testResult = FAIL; } userProperty->GetAttributesPointer()->Set(testUserIntKey, originalValue); if (!root->IsEqualTo( treeFromDisk, true )) { cout << "changed property back; should be equal!!!\n\n"; testResult = FAIL; } userProperty->GetAttributesPointer()->Remove(testUserIntKey); if (root->IsEqualTo( treeFromDisk, true )) { cout << "removed a property; should be different!!!\n\n"; testResult = FAIL; } userProperty->GetAttributesPointer()->Set(testUserIntKey, originalValue); if (!root->IsEqualTo( treeFromDisk, true )) { cout << "added property again; should be equal!!!\n\n"; testResult = FAIL; } int *vectorValue = userProperty->GetAttributesPointer()->Get(testUserIntVectorKey); int original[3] = {vectorValue[0], vectorValue[1], vectorValue[2]}; int purple[3] = {255, 0, 255}; userProperty->GetAttributesPointer()->Set(testUserIntVectorKey, purple, 3); if (root->IsEqualTo( treeFromDisk, true )) { cout << "changed a property (vector); should be different!!!\n\n"; testResult = FAIL; } userProperty->GetAttributesPointer()->Set(testUserIntVectorKey, original, 3); if (!root->IsEqualTo( treeFromDisk, true )) { cout << "changed property back; should be equal!!!\n\n"; testResult = FAIL; } } else { cout << "Didn't get UserProperty as expected!!\n\n"; testResult = FAIL; } int uuidResult = root->CreateUUID(); if (uuidResult == 1) { cout << "UUID Generated for Node: " << root->GetUUID() << "\n"; unsigned char uuid[16]; vtkKWEUUID::ConstructUUID(uuid); vtkstd::string uuidString; vtkKWEUUID::ConvertBinaryUUIDToString(uuid, uuidString); cout << "Constructed UUID (just testing): " << uuidString << "\n\n"; } else //uuidResult == 2 { cout << "UUID Constructed for Node (Generate failed): " << root->GetUUID() << "\n\n"; } if (root->IsEqualTo( treeFromDisk, false)) { cout << "added UUID; should be different!!!\n\n"; testResult = FAIL; } if (!root->IsEqualTo( treeFromDisk, false, true)) { cout << "added UUID; but is superset, so should be \"equal\"!!!\n\n"; testResult = FAIL; } root->ClearUUID(); //clear UUID so createPseudoUUID will do something // change the tree we read in, and now expect a difference treeFromDisk->GetChild(1)->RemoveChild(2); if (root->IsEqualTo( treeFromDisk, true )) { cout << "removed a child; should be different!!!\n\n"; testResult = FAIL; } if (testResult == PASS) { cout << "\nAll tests passed!\n\n"; } return testResult; } #ifndef KWE_TESTING int main(int argc, char* argv[]) { return ObjectTreeDemo(argc, argv); } #endif vtkedge-0.2.0~20110819/Examples/Filtering/CMakeLists.txt0000644000175000017500000000166211363410610022301 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Just add all the subdirectories # ----------------------------------------------------------------------------- add_subdirectory(Cxx) vtkedge-0.2.0~20110819/Hybrid/0000755000175000017500000000000011630434664015270 5ustar mathieumathieuvtkedge-0.2.0~20110819/Hybrid/vtkKWEGPUImageAlgorithmDriver.cxx0000644000175000017500000004235711370314341023532 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEGPUImageAlgorithmDriver.h" #include "vtkDataArray.h" #include "vtkDebugLeaks.h" #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkDataTransferHelper.h" #include "vtkKWEExtentCalculator.h" #include "vtkStructuredExtent.h" #include "vtkTextureObject.h" #include "vtkObjectFactory.h" #include "vtkOpenGLRenderWindow.h" #include "vtkPointData.h" #include "vtkSmartPointer.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkTimerLog.h" #include "vtkToolkits.h" vtkSmartPointer mylog = vtkSmartPointer::New(); #define START_LOG()\ mylog->StartTimer(); #define STOP_LOG(msg)\ glFinish();\ mylog->StopTimer();\ cout << msg << " " << mylog->GetElapsedTime() << endl; #define PRINTEXT(__arg) \ __arg[0] << ", " << __arg[1] << ", " << __arg[2] << ", " << __arg[3] << ", " << __arg[4] << ", " << __arg[5] #include //---------------------------------------------------------------------------- class vtkKWEGPUImageAlgorithmDriver::vtkPipe { private: vtkKWEGPUImageAlgorithmDriver* Driver; bool AbortFlag; struct vtkPipeItem { vtkSmartPointer UpBuses; vtkSmartPointer Downbus; }; vtkstd::list InPipe; vtkstd::list ExecutePipe; vtkstd::list DownloadPipe; vtkstd::list DownloadPipe2; vtkstd::list > AvailableUpBuses; bool Chug() { bool result = (!this->AbortFlag); if (this->DownloadPipe2.size() > 0) { START_LOG(); vtkPipeItem item = this->DownloadPipe2.front(); this->DownloadPipe2.pop_front(); // Note that Download() is not going to be called unless result == true // i.e. this->AbortFlag == false. result = result && item.Downbus->DownloadAsync2(); STOP_LOG("Download2"); } if (this->DownloadPipe.size() > 0) { vtkPipeItem item = this->DownloadPipe.front(); this->DownloadPipe.pop_front(); // Push it in the available buses. this->AvailableUpBuses.push_back(item.UpBuses); // release the bus. item.UpBuses = NULL; START_LOG(); // Note that Download() is not going to be called unless result == true // i.e. this->AbortFlag == false. result = result && item.Downbus->DownloadAsync1(); this->DownloadPipe2.push_back(item); STOP_LOG("Download1"); } if (this->ExecutePipe.size() > 0) { START_LOG(); vtkPipeItem item = this->ExecutePipe.front(); this->ExecutePipe.pop_front(); // Note that Execute() is not going to be called unless result == true // i.e. this->AbortFlag == false. result = result && this->Driver->Execute(item.UpBuses, item.Downbus); this->DownloadPipe.push_back(item); STOP_LOG("Execute:"); } if (this->InPipe.size() > 0) { vtkPipeItem item = this->InPipe.front(); this->InPipe.pop_front(); this->ExecutePipe.push_back(item); } return result; } public: vtkPipe(vtkKWEGPUImageAlgorithmDriver* driver) { this->AbortFlag = false; this->Driver = driver; } ~vtkPipe() { this->Driver = 0; this->AbortFlag = true; this->Flush(); } vtkKWEGPUImageAlgorithmDriver::vtkBuses* NewBus() { if (this->AvailableUpBuses.size() > 0) { vtkKWEGPUImageAlgorithmDriver::vtkBuses* front = this->AvailableUpBuses.front(); front->Register(0); this->AvailableUpBuses.erase(this->AvailableUpBuses.begin()); return front; } return vtkKWEGPUImageAlgorithmDriver::vtkBuses::New(); } bool Push( vtkKWEGPUImageAlgorithmDriver::vtkBuses* up_buses, vtkDataTransferHelper* down_bus) { vtkPipeItem item; item.UpBuses= up_buses; item.Downbus = down_bus; this->InPipe.push_back(item); return this->Chug(); } void Flush() { while (this->InPipe.size() > 0 || this->ExecutePipe.size() > 0 || this->DownloadPipe.size() > 0 || this->DownloadPipe2.size() > 0) { this->Chug(); } this->AvailableUpBuses.clear(); } void Abort() { this->AbortFlag = true; } }; //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkKWEGPUImageAlgorithmDriver::vtkBuses, "$Revision: 1.1$"); vtkKWEGPUImageAlgorithmDriver::vtkBuses* vtkKWEGPUImageAlgorithmDriver::vtkBuses::New() { #ifdef VTK_DEBUG_LEAKS vtkDebugLeaks::ConstructClass("vtkBuses"); #endif return new vtkBuses(); } //---------------------------------------------------------------------------- void vtkKWEGPUImageAlgorithmDriver::vtkBuses::SetNumberOfPorts(unsigned int num) { this->Buses.resize(num); } //---------------------------------------------------------------------------- void vtkKWEGPUImageAlgorithmDriver::vtkBuses::SetNumberOfConnections( unsigned int port, unsigned int num) { if (port < this->Buses.size()) { this->Buses[port].resize(num); } } //---------------------------------------------------------------------------- vtkDataTransferHelper* vtkKWEGPUImageAlgorithmDriver::vtkBuses::GetBus( unsigned int port, unsigned int conn) { if (port < this->Buses.size()) { if (conn < this->Buses[port].size()) { return this->Buses[port][conn]; } } return 0; } //---------------------------------------------------------------------------- void vtkKWEGPUImageAlgorithmDriver::vtkBuses::SetBus( unsigned int port, unsigned int conn, vtkDataTransferHelper* bus) { if (port < this->Buses.size()) { if (conn < this->Buses[port].size()) { this->Buses[port][conn] = bus; } } } //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkKWEGPUImageAlgorithmDriver, "$Revision: 1973 $"); //---------------------------------------------------------------------------- vtkKWEGPUImageAlgorithmDriver::vtkKWEGPUImageAlgorithmDriver() { this->Context = 0; this->OwnContext = false; } //---------------------------------------------------------------------------- vtkKWEGPUImageAlgorithmDriver::~vtkKWEGPUImageAlgorithmDriver() { this->SetContext(0); } //---------------------------------------------------------------------------- void vtkKWEGPUImageAlgorithmDriver::SetContext(vtkRenderWindow* context) { if (this->Context == context) { return; } if (this->Context && this->OwnContext) { this->Context->Delete(); } this->Context = context; this->OwnContext = false; // Don't call Modified() since this may get called in RequestData(). // this->Modified(); } //---------------------------------------------------------------------------- vtkRenderWindow* vtkKWEGPUImageAlgorithmDriver::GetContext() { return this->Context; } //---------------------------------------------------------------------------- int vtkKWEGPUImageAlgorithmDriver::RequestUpdateExtent ( vtkInformation * vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { int update_ext[6]; outputVector->GetInformationObject(0)->Get( vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), update_ext); int numInputPorts = this->GetNumberOfInputPorts(); for (int port=0; port < numInputPorts; port++) { int numConns = inputVector[port]->GetNumberOfInformationObjects(); for (int conn = 0; conn < numConns; conn++) { vtkInformation* inInfo = inputVector[port]->GetInformationObject(conn); int input_update_extent[6]; if (!this->MapOutputExtentToInput(input_update_extent, port, conn, inputVector[port]->GetInformationObject(conn), update_ext)) { // don't know why the subclass said we cannot handle this case. So abort. return 0; } int whole_extent[6]; inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), whole_extent); // clamp extent_to_upload to the input extents. vtkStructuredExtent::Clamp(input_update_extent, whole_extent); inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), input_update_extent, 6); } } return 1; } //---------------------------------------------------------------------------- bool vtkKWEGPUImageAlgorithmDriver::SetupOutputTexture( ExtentTypes chunkType, vtkDataTransferHelper* down_bus) { vtkDataArray* outputArray = down_bus->GetArray(); vtkTextureObject* texture = vtkTextureObject::New(); texture->SetContext(this->Context); int extent[6]; down_bus->GetGPUExtent(extent); int dims[3]; vtkStructuredExtent::GetDimensions(extent, dims); switch (chunkType) { case XY_PLANE: texture->Create2D(dims[0], dims[1], outputArray->GetNumberOfComponents(), outputArray->GetDataType(), false); break; case YZ_PLANE: texture->Create2D(dims[1], dims[2], outputArray->GetNumberOfComponents(), outputArray->GetDataType(), false); break; case XZ_PLANE: texture->Create2D(dims[0], dims[2], outputArray->GetNumberOfComponents(), outputArray->GetDataType(), false); break; case XYZ_GRID: texture->Create3D(dims[0], dims[1], dims[2], outputArray->GetNumberOfComponents(), outputArray->GetDataType(), false); break; default: vtkErrorMacro("Unhandled chunk description: " << static_cast(chunkType)); texture->Delete(); return false; } down_bus->SetTexture(texture); texture->Delete(); return true; } //---------------------------------------------------------------------------- vtkKWEGPUImageAlgorithmDriver::vtkBuses* vtkKWEGPUImageAlgorithmDriver::Upload( vtkKWEExtentCalculator* extentCalculator, vtkInformationVector** inputVector, vtkKWEGPUImageAlgorithmDriver::vtkPipe& pipe) { START_LOG(); int numInputPorts = this->GetNumberOfInputPorts(); vtkBuses* upBuses = pipe.NewBus(); upBuses->SetNumberOfPorts(numInputPorts); for (int port =0; port < numInputPorts; port++) { int numConns = inputVector[port]->GetNumberOfInformationObjects(); upBuses->SetNumberOfConnections(port, numConns); } try { for (int port = 0; port < numInputPorts; port++) { int numConnections = inputVector[port]->GetNumberOfInformationObjects(); for (int conn = 0; conn < numConnections; conn++) { vtkImageData* input = vtkImageData::GetData(inputVector[port], conn); // Give subclass an opportunity to map output extent to input for this port. int extent_to_upload[6]; int min_tex_dims = this->MapOutputExtentToInput(extent_to_upload, port, conn, inputVector[port]->GetInformationObject(conn), extentCalculator->GetOutChunkExtent()); if (min_tex_dims <= 0) { throw 0; } if (min_tex_dims < 1 || min_tex_dims > 3) { vtkWarningMacro("Forcing minimum texture dimensionality () to 2 (instead of " << min_tex_dims << " )"); min_tex_dims = 2; } // clamp extent_to_upload to the input extents. vtkStructuredExtent::Clamp(extent_to_upload, input->GetExtent()); // up_bus is used to upload the result from the GPU. vtkSmartPointer up_bus = vtkSmartPointer::New(); up_bus->SetContext(this->Context); up_bus->SetCPUExtent(input->GetExtent()); up_bus->SetGPUExtent(extent_to_upload); //cout << "Upload CPUExtent: " << // PRINTEXT(up_bus->GetCPUExtent()) << endl; cout << "Upload GPUExtent: " << PRINTEXT(up_bus->GetGPUExtent()) << endl; //up_bus->SetMinTextureDimension(min_tex_dims); up_bus->SetArray(input->GetPointData()->GetScalars()); if (!up_bus->Upload(0, 0)) { throw 0; } upBuses->SetBus(port, conn, up_bus); //inputVector2[port]->GetInformationObject(conn)->Set(UPLOAD_BUS(), up_bus); // UPLOAD_BUS() will provide the subclass all the information it needs to // know about the input including extents. } } } catch (int) { upBuses->Delete(); upBuses = 0; } STOP_LOG("Upload"); return upBuses; } #include "vtkTimerLog.h" //---------------------------------------------------------------------------- int vtkKWEGPUImageAlgorithmDriver::RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkTimerLog* timer = vtkTimerLog::New(); timer->StartTimer(); if (!this->Context) { this->SetContext(vtkRenderWindow::New()); this->OwnContext = true; this->Context->Render(); } this->Context->SetReportGraphicErrors(1); this->Context->MakeCurrent(); // Ask the subclass the order of processing the output pieces. ExtentTypes chunkType = this->GetSplitMode(request, inputVector, outputVector); if (chunkType == vtkKWEGPUImageAlgorithmDriver::INVALID) { return 0; } vtkImageData* output = vtkImageData::GetData(outputVector, 0); this->AllocateOutputData(output); // Now, our subclass has told us how it needs the slices. vtkSmartPointer extentCalculator = vtkSmartPointer::New(); extentCalculator->SetChunkDescription(static_cast(chunkType)); extentCalculator->SetWholeExtent(output->GetExtent()); extentCalculator->LoadLimits(this->Context); // TODO: Take in to consideration if any input has padding. vtkKWEGPUImageAlgorithmDriver::vtkPipe pipe(this); if (!this->InitializeExecution(request, inputVector, outputVector)) { vtkErrorMacro("Failed initialization."); return 0; } int count = 0; for (extentCalculator->Begin(); !extentCalculator->IsDone(); extentCalculator->Next(), count++) { vtkSmartPointer up_buses; up_buses.TakeReference(this->Upload(extentCalculator, inputVector, pipe)); if (!up_buses.GetPointer()) { vtkErrorMacro("Upload failed."); pipe.Abort(); break; } // down_bus is used to download the result from the GPU. vtkSmartPointer down_bus = vtkSmartPointer::New(); down_bus->SetContext(this->Context); down_bus->SetCPUExtent(output->GetExtent()); int down_ext[6]; extentCalculator->GetOutChunkExtent(down_ext); vtkStructuredExtent::Clamp(down_ext, output->GetExtent()); down_bus->SetGPUExtent(down_ext); down_bus->SetArray(output->GetPointData()->GetScalars()); //cout << "Download CPUExtent: " << // PRINTEXT(down_bus->GetCPUExtent()) << endl; //cout << "Download GPUExtent: " << // PRINTEXT(down_bus->GetGPUExtent()) << endl; if (!this->SetupOutputTexture(chunkType, down_bus)) { vtkErrorMacro("Failed to create download texture."); pipe.Abort(); break; } if (!pipe.Push(up_buses, down_bus)) { // failed. vtkErrorMacro("GPU processing pipe failed"); pipe.Abort(); break; } } pipe.Flush(); if (!this->FinalizeExecution(request, inputVector, outputVector)) { vtkErrorMacro("Failed cleanup."); return 0; } timer->StopTimer(); cout << "vtkKWEGPUImageAlgorithmDriver ("<GetElapsedTime() << endl; timer->Delete(); return 1; } //---------------------------------------------------------------------------- bool vtkKWEGPUImageAlgorithmDriver::ComputeTCoordsRange( double tcoords[6], const int inputExt[6], const int outputExt[6]) { if (!vtkStructuredExtent::Smaller(outputExt, inputExt)) { vtkErrorMacro("Cannot handle cases where output extent is larger than input."); return false; } tcoords[0] = tcoords[2] = tcoords[4] = 0.0; tcoords[1] = tcoords[3] = tcoords[5] = 1.0; int indims[3]; vtkStructuredExtent::GetDimensions(inputExt, indims); int outdims[3]; vtkStructuredExtent::GetDimensions(outputExt, outdims); tcoords[0] = (outputExt[0] - inputExt[0])/static_cast(indims[0]); tcoords[1] = tcoords[0] + outdims[0]/static_cast(indims[0]); tcoords[2] = (outputExt[2] - inputExt[2])/static_cast(indims[1]); tcoords[3] = tcoords[2] + outdims[1]/static_cast(indims[1]); tcoords[4] = (outputExt[4] - inputExt[4])/static_cast(indims[2]); tcoords[5] = tcoords[4] + outdims[2]/static_cast(indims[2]); return true; } //---------------------------------------------------------------------------- void vtkKWEGPUImageAlgorithmDriver::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } vtkedge-0.2.0~20110819/Hybrid/vtkKWEImageGradientMagnitude.cxx0000644000175000017500000002157511370314341023446 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEImageGradientMagnitude.h" #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkDataTransferHelper.h" #include "vtkFrameBufferObject.h" #include "vtkShaderProgram2.h" #include "vtkShader2.h" #include "vtkShader2Collection.h" #include "vtkUniformVariables.h" #include "vtkStructuredExtent.h" #include "vtkTextureObject.h" #include "vtkObjectFactory.h" #include "vtkOpenGLRenderWindow.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkgl.h" extern const char* vtkKWEImageGradientMagnitude_2D_fs; extern const char* vtkKWEImageGradientMagnitude_3D_fs; vtkStandardNewMacro(vtkKWEImageGradientMagnitude); vtkCxxRevisionMacro(vtkKWEImageGradientMagnitude, "$Revision: 1973 $"); //---------------------------------------------------------------------------- vtkKWEImageGradientMagnitude::vtkKWEImageGradientMagnitude() { this->Dimensionality = 2; this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(1); } //---------------------------------------------------------------------------- vtkKWEImageGradientMagnitude::~vtkKWEImageGradientMagnitude() { } //---------------------------------------------------------------------------- vtkKWEGPUImageAlgorithmDriver::ExtentTypes vtkKWEImageGradientMagnitude::GetSplitMode( vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* vtkNotUsed(outputVector)) { return vtkKWEGPUImageAlgorithmDriver::XY_PLANE; } //---------------------------------------------------------------------------- int vtkKWEImageGradientMagnitude::MapOutputExtentToInput(int input_extent[6], int vtkNotUsed(port), int vtkNotUsed(connection), vtkInformation* inInfo, const int output_extent[6]) { int dimensionality = 2; if (this->Dimensionality == 3) { int whole_extent[6]; if (!inInfo->Has(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT())) { vtkErrorMacro("Missing WHOLE_EXTENT()."); return 0; } inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), whole_extent); int whole_dims[3]; vtkStructuredExtent::GetDimensions(whole_extent, whole_dims); dimensionality = vtkStructuredData::GetDataDimension( vtkStructuredData::GetDataDescription(whole_dims)); dimensionality = (this->Dimensionality == 3 && dimensionality == 3)? 3 : 2; } memcpy(input_extent, output_extent, 6*sizeof(int)); vtkStructuredExtent::Grow(input_extent, 1); if (dimensionality != 3) { // We don't need ghost levels along Z axis, unless going 3D gradients. input_extent[4] = output_extent[4]; input_extent[5] = output_extent[5]; } return (dimensionality !=3)? 2 : 3; } //---------------------------------------------------------------------------- bool vtkKWEImageGradientMagnitude::InitializeExecution( vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* vtkNotUsed(outputVector)) { int dimensionality = 2; if (this->Dimensionality == 3) { vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); int whole_extent[6]; if (!inInfo->Has(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT())) { vtkErrorMacro("Missing WHOLE_EXTENT()."); return 0; } inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), whole_extent); int whole_dims[3]; vtkStructuredExtent::GetDimensions(whole_extent, whole_dims); dimensionality = vtkStructuredData::GetDataDimension( vtkStructuredData::GetDataDescription(whole_dims)); } dimensionality = dimensionality == 3? 3: 2; vtkShaderProgram2* pgm = vtkShaderProgram2::New(); pgm->SetContext(vtkOpenGLRenderWindow::SafeDownCast(this->GetContext())); vtkShader2 *shader=vtkShader2::New(); shader->SetType(VTK_SHADER_TYPE_FRAGMENT); shader->SetSourceCode(dimensionality == 3? vtkKWEImageGradientMagnitude_3D_fs: vtkKWEImageGradientMagnitude_2D_fs); pgm->GetShaders()->AddItem(shader); shader->Delete(); this->GLSLProgram = pgm; pgm->Delete(); vtkImageData* input = vtkImageData::GetData(inputVector[0], 0); input->GetSpacing(this->SpacingReciprocal); this->SpacingReciprocal[0] = 0.5/this->SpacingReciprocal[0]; this->SpacingReciprocal[1] = 0.5/this->SpacingReciprocal[1]; this->SpacingReciprocal[2] = 0.5/this->SpacingReciprocal[2]; return true; } //---------------------------------------------------------------------------- bool vtkKWEImageGradientMagnitude::Execute( vtkKWEGPUImageAlgorithmDriver::vtkBuses* upBuses, vtkDataTransferHelper* downBus) { vtkDataTransferHelper* upBus = upBuses->GetBus(0, 0); int dims[3]; dims[0] = downBus->GetTexture()->GetWidth(); dims[1] = downBus->GetTexture()->GetHeight(); dims[2] = 0; double tcoords[6]; if (!this->ComputeTCoordsRange(tcoords, upBus->GetGPUExtent(), downBus->GetGPUExtent())) { return false; } // Create fbo to render. vtkFrameBufferObject* fbo = vtkFrameBufferObject::New(); fbo->SetContext(vtkOpenGLRenderWindow::SafeDownCast(this->Context)); fbo->SetColorBuffer(0, downBus->GetTexture()); fbo->Start(dims[0], dims[1], true); this->GLSLProgram->Build(); if(this->GLSLProgram->GetLastBuildStatus()!= VTK_SHADER_PROGRAM2_LINK_SUCCEEDED) { vtkErrorMacro("GLSLProgram bind failed."); return false; } int value; value=0; this->GLSLProgram->GetUniformVariables()->SetUniformi("uInputImage",1, &value); float fvalues[3]; fvalues[0]=static_cast(upBus->GetTexture()->GetWidth()); fvalues[1]=static_cast(upBus->GetTexture()->GetHeight()); fvalues[2]=static_cast(upBus->GetTexture()->GetDepth()); this->GLSLProgram->GetUniformVariables()->SetUniformf("uInputImageDims",3, fvalues); fvalues[0]=static_cast(this->SpacingReciprocal[0]); fvalues[1]=static_cast(this->SpacingReciprocal[1]); fvalues[2]=static_cast(this->SpacingReciprocal[2]); this->GLSLProgram->GetUniformVariables()->SetUniformf("uSpacingReciprocal",3, fvalues); this->GLSLProgram->Use(); double zTexCoord = (downBus->GetGPUExtent()[4] == upBus->GetGPUExtent()[4])? 0.0 : 0.5; // render viewport-sized quad to perform actual computation upBus->GetTexture()->Bind(); glTexParameteri(upBus->GetTexture()->GetTarget(), GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(upBus->GetTexture()->GetTarget(), GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(upBus->GetTexture()->GetTarget(), vtkgl::TEXTURE_WRAP_R, GL_CLAMP); if(!this->GLSLProgram->IsValid()) { vtkErrorMacro(<<" validation of the program failed: "<GLSLProgram->GetLastValidateLog()); } glBegin(GL_QUADS); glTexCoord3f(static_cast(tcoords[0]), static_cast(tcoords[2]), static_cast(zTexCoord)); glVertex2f(0.0, 0.0); glTexCoord3f(static_cast(tcoords[1]), static_cast(tcoords[2]), static_cast(zTexCoord)); glVertex2f(static_cast(dims[0]), 0.0); glTexCoord3f(static_cast(tcoords[1]), static_cast(tcoords[3]), static_cast(zTexCoord)); glVertex2f(static_cast(dims[0]), static_cast(dims[1])); glTexCoord3f(static_cast(tcoords[0]), static_cast(tcoords[3]), static_cast(zTexCoord)); glVertex2f(0.0, static_cast(dims[1])); glEnd(); fbo->Delete(); return true; } //---------------------------------------------------------------------------- bool vtkKWEImageGradientMagnitude::FinalizeExecution( vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* vtkNotUsed(outputVector)) { this->GLSLProgram = 0; return true; } //---------------------------------------------------------------------------- void vtkKWEImageGradientMagnitude::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Dimensionality: " << this->Dimensionality << endl; } vtkedge-0.2.0~20110819/Hybrid/vtkKWEGPUArrayCalculator.cxx0000644000175000017500000010610111370314341022541 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEGPUArrayCalculator.h" #include "vtkCellData.h" #include "vtkDataSet.h" #include "vtkDoubleArray.h" #include "vtkFieldData.h" #include "vtkKWEFunctionToGLSL.h" #include "vtkGraph.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPointSet.h" #include "vtkPolyData.h" #include "vtkUnstructuredGrid.h" #include "vtkOpenGLRenderWindow.h" #include "vtkOpenGLExtensionManager.h" #include "vtkShaderProgram2.h" #include "vtkShader2.h" #include "vtkShader2Collection.h" #include "vtkUniformVariables.h" #include "vtkgl.h" #include "vtkKWEDataArrayStreamer.h" #include #include "vtkDataTransferHelper.h" #include "vtkFrameBufferObject.h" #include "vtkTextureObject.h" #include #include "vtkTimerLog.h" #include "vtkFloatArray.h" //#define VTKKWE_GPU_ARRAY_CALCULATOR_DEBUG // display debug info vtkCxxRevisionMacro(vtkKWEGPUArrayCalculator, "$Revision: 1973 $"); vtkStandardNewMacro(vtkKWEGPUArrayCalculator); // ---------------------------------------------------------------------------- vtkKWEGPUArrayCalculator::vtkKWEGPUArrayCalculator() { // initialized by superclass assert("this->FunctionParser exists" && this->FunctionParser!=0); // this->FunctionParser->Delete(); // this->FunctionParser = vtkKWEFunctionToGLSL::New(); this->FunctionParserToGLSL=vtkKWEFunctionToGLSL::New(); this->Context = 0; this->SupportedByHardware=false; this->MaxGPUMemorySizeInBytes=128*1024*1024; this->SizeThreshold=0; this->UseCalibration=0; this->CalibratedSizeThreshold=0; this->CalibrationDone=false; } // ---------------------------------------------------------------------------- vtkKWEGPUArrayCalculator::~vtkKWEGPUArrayCalculator() { this->FunctionParserToGLSL->Delete(); this->FunctionParserToGLSL = NULL; this->SetContext(0); } // ---------------------------------------------------------------------------- void vtkKWEGPUArrayCalculator::SetContext(vtkRenderWindow* context) { vtkSetObjectBodyMacro(Context, vtkRenderWindow, context); if (this->Context) { vtkOpenGLExtensionManager *mgr=vtkOpenGLExtensionManager::New(); mgr->SetRenderWindow(this->Context); // We need shader support, PBO, FBO, multitexturing, draw buffers, // NPOT textures, float textures // GL_ARB_draw_buffers requires at least OpenGL>=1.3 // (multitexturing is part of OpenGL 1.3) bool gl13=mgr->ExtensionSupported("GL_VERSION_1_3")==1; if(!gl13) { // give up this->SupportedByHardware=false; } else { bool gl15=mgr->ExtensionSupported("GL_VERSION_1_5")==1; bool gl20=mgr->ExtensionSupported("GL_VERSION_2_0")==1; bool gl21=mgr->ExtensionSupported("GL_VERSION_2_1")==1; bool vbo=gl15 || mgr->ExtensionSupported("GL_ARB_vertex_buffer_object")==1; bool pbo=vbo && (gl21 || mgr->ExtensionSupported("GL_ARB_pixel_buffer_object")==1); bool drawbuffers=gl20 || mgr->ExtensionSupported("GL_ARB_draw_buffers")==1; bool npot=gl20 || mgr->ExtensionSupported("GL_ARB_texture_non_power_of_two")==1; bool shading_language_100=gl20 || mgr->ExtensionSupported("GL_ARB_shading_language_100"); bool shader_objects=gl20 || mgr->ExtensionSupported("GL_ARB_shader_objects"); bool fragment_shader=gl20 || mgr->ExtensionSupported("GL_ARB_fragment_shader"); bool fbo=mgr->ExtensionSupported("GL_EXT_framebuffer_object" )==1; bool texture_float=mgr->ExtensionSupported("GL_ARB_texture_float")==1; this->SupportedByHardware=pbo && drawbuffers && npot && shading_language_100 && shader_objects && fragment_shader && fbo && texture_float; if(this->SupportedByHardware) { mgr->LoadSupportedExtension("GL_VERSION_1_3"); if(gl15) { mgr->LoadSupportedExtension("GL_VERSION_1_5"); } else { mgr->LoadCorePromotedExtension("GL_ARB_vertex_buffer_object"); } if(gl20) { mgr->LoadSupportedExtension("GL_VERSION_2_0"); } else { mgr->LoadCorePromotedExtension("GL_ARB_draw_buffers"); // npot does not provide new functions. mgr->LoadCorePromotedExtension("GL_ARB_shading_language_100"); mgr->LoadCorePromotedExtension("GL_ARB_shader_objects"); mgr->LoadCorePromotedExtension("GL_ARB_fragment_shader"); } if(gl21) { mgr->LoadSupportedExtension("GL_VERSION_2_1"); } else { mgr->LoadCorePromotedExtension("GL_ARB_pixel_buffer_object"); } mgr->LoadExtension("GL_EXT_framebuffer_object"); mgr->LoadExtension( "GL_ARB_texture_float" ); } } mgr->Delete(); } else { this->SupportedByHardware=false; } } // ---------------------------------------------------------------------------- // Description: // Tells if the GPU implementation is supported by the graphics card in use. bool vtkKWEGPUArrayCalculator::GetSupportedByHardware() { return this->SupportedByHardware; } // ---------------------------------------------------------------------------- // Description: // Compute range of values for a scalar array for a subset of tuples. void vtkKWEGPUArrayCalculator::ComputeSubRange(vtkDataArray *array, vtkIdType first, vtkIdType last, double subRange[2]) { assert("pre: array_exists" && array!=0); assert("pre: scalar" && array->GetNumberOfComponents()==1); assert("pre: array_not_empty" && array->GetNumberOfTuples()>=1); assert("pre: positive_first" && first>=0); assert("pre: last_in_range" && lastGetNumberOfTuples()); assert("pre: increasing order" && first<=last); subRange[0]=VTK_DOUBLE_MAX; subRange[1]=VTK_DOUBLE_MIN; vtkIdType i=first; while(i<=last) { double value=array->GetComponent(i,0); if(valuesubRange[1]) { subRange[1]=value; } ++i; } } // ---------------------------------------------------------------------------- // Description: // Tell the filter to calibrate itself. Starting for the current value of // SizeThreshold, try to find the actual threshold size at which the GPU // implementation is faster than the CPU one. This call is expensive. // This method is usually called automatically once when UseCalibration is // on. But you can call it directly to control at what time the calibration // happens or to force a new calibration. void vtkKWEGPUArrayCalculator::Calibrate() { if(!this->SupportedByHardware) { // cannot calibrate. this->CalibratedSizeThreshold=0; // reset to initial value. this->CalibrationDone=false; } vtkTimerLog *timer=vtkTimerLog::New(); // Starting value. Start from last estimate if not null. if(this->CalibratedSizeThreshold==0) { if(this->SizeThreshold>0) { this->CalibratedSizeThreshold=this->SizeThreshold; } else { this->CalibratedSizeThreshold=15000; // estimate from experience. } } double cpuTime=0.0; double gpuTime=0.0; vtkFloatArray *values=0; const int maxIterations=6; // limit the calibration to 6 passes. int iteration=0; vtkIdType minSize=0; vtkIdType maxSize=100000; // resonable upper limit. while(!this->CalibrationDone) { // cpu computation: fill an array with values. timer->StartTimer(); values=vtkFloatArray::New(); values->SetNumberOfComponents(1); values->SetNumberOfTuples(this->CalibratedSizeThreshold); vtkIdType i=0; while(iCalibratedSizeThreshold) { double x=static_cast(i); values->SetValue(i,static_cast(x)); x=values->GetValue(i); double y; if(i>0) { y=values->GetValue(i-1); } else { y=0.0; } x=exp(sqrt(sin(x)*cos(exp(y))+10.0)); values->SetValue(i,static_cast(x)); ++i; } timer->StopTimer(); cpuTime=timer->GetElapsedTime(); cpuTime=cpuTime*10.0; // simulate overhead of bytecode execution. timer->StartTimer(); this->SimulateGPUComputation(values); timer->StopTimer(); gpuTime=timer->GetElapsedTime(); values->Delete(); double speedFactor=cpuTime/gpuTime; cout<<"iteration="<UseCalibration) { if(!this->CalibrationDone) { this->Calibrate(); } } if((!this->UseCalibration && numTuplesUseCalibration && numTuplesCalibratedSizeThreshold)) { // CPU flavor. return this->Superclass::RequestData(request,inputVector,outputVector); } for (i = 0; i < this->NumberOfScalarArrays; i++) { currentArray = inFD->GetArray(this->ScalarArrayNames[i]); if (currentArray) { if (currentArray->GetNumberOfComponents() > this->SelectedScalarComponents[i]) { this->FunctionParserToGLSL-> SetScalarVariableValue( this->ScalarVariableNames[i], currentArray->GetComponent(0, this->SelectedScalarComponents[i])); } else { vtkErrorMacro("Array " << this->ScalarArrayNames[i] << " does not contain the selected component."); return 1; } } else { vtkErrorMacro("Invalid array name: " << this->ScalarArrayNames[i]); return 1; } } for (i = 0; i < this->NumberOfVectorArrays; i++) { currentArray = inFD->GetArray(this->VectorArrayNames[i]); if (currentArray) { if ((currentArray->GetNumberOfComponents() > this->SelectedVectorComponents[i][0]) && (currentArray->GetNumberOfComponents() > this->SelectedVectorComponents[i][1]) && (currentArray->GetNumberOfComponents() > this->SelectedVectorComponents[i][2])) { this->FunctionParserToGLSL-> SetVectorVariableValue( this->VectorVariableNames[i], currentArray->GetComponent(0, this->SelectedVectorComponents[i][0]), currentArray->GetComponent(0, this->SelectedVectorComponents[i][1]), currentArray->GetComponent(0, this->SelectedVectorComponents[i][2])); } else { vtkErrorMacro("Array " << this->VectorArrayNames[i] << " does not contain one of the selected components."); return 1; } } else { vtkErrorMacro("Invalid array name: " << this->VectorArrayNames[i]); return 1; } } // we can add points if(attributeDataType == 0) { for (i = 0; i < this->NumberOfCoordinateScalarArrays; i++) { double* pt = 0; if (dsInput) { pt = dsInput->GetPoint(0); } else { pt = graphInput->GetPoint(0); } this->FunctionParserToGLSL-> SetScalarVariableValue( this->CoordinateScalarVariableNames[i], pt[this->SelectedCoordinateScalarComponents[i]]); } for (i = 0; i < this->NumberOfCoordinateVectorArrays; i++) { double* pt = 0; if (dsInput) { pt = dsInput->GetPoint(0); } else { pt = graphInput->GetPoint(0); } this->FunctionParserToGLSL-> SetVectorVariableValue( this->CoordinateVectorVariableNames[i], pt[this->SelectedCoordinateVectorComponents[i][0]], pt[this->SelectedCoordinateVectorComponents[i][1]], pt[this->SelectedCoordinateVectorComponents[i][2]]); } } this->FunctionParserToGLSL->GenerateGLSL(); if(!this->FunctionParserToGLSL->GetParseStatus()) { return 0; } // output allocation. if(this->FunctionParserToGLSL->GetResultDimension()==3) { resultType=1; } else { resultType=0; } // The number of arrays in input is limited by the maximum number of // texture units GLint ivalue[4]; glGetIntegerv(vtkgl::MAX_TEXTURE_IMAGE_UNITS,ivalue); // Count the number of arrays used in the expression. int usedVariables=this->FunctionParserToGLSL->GetNumberOfUsedScalarVariables() +this->FunctionParserToGLSL->GetNumberOfUsedVectorVariables(); if(usedVariables>ivalue[0]) { vtkErrorMacro(<<" the expression uses " << usedVariables << " but the GPU can process only" << ivalue[0] <<" variables."); return 0; } // iterate first over all used variables (scalar or vector) to // find the maximum size for a tuple in bytes. // also accumulate size of a tuple when combining all used inputs and the // output. int maxTupleSize=1; // 1 component of type signed/unsigned char. int accumulatedTupleSize=0; int c=this->FunctionParserToGLSL->GetNumberOfScalarVariables(); j=0; while(jFunctionParserToGLSL->GetScalarIsUsed(j)) { currentArray=inFD->GetArray(this->ScalarArrayNames[j]); if (currentArray) { int tupleSize=currentArray->GetDataTypeSize(); if(currentArray->GetDataType()==VTK_DOUBLE) { // pbo will convert double into float tupleSize/=2; } if(tupleSize>maxTupleSize) { maxTupleSize=tupleSize; } accumulatedTupleSize+=tupleSize; } else { vtkErrorMacro("Invalid array name: " << this->ScalarArrayNames[j]); return 0; } } ++j; } c=this->FunctionParserToGLSL->GetNumberOfVectorVariables(); j=0; while(jFunctionParserToGLSL->GetVectorIsUsed(j)) { currentArray=inFD->GetArray(this->VectorArrayNames[j]); if (currentArray) { int tupleSize=currentArray->GetDataTypeSize(); if(currentArray->GetDataType()==VTK_DOUBLE) { // pbo will convert double into float tupleSize/=2; } tupleSize*=3; // vector if(tupleSize>maxTupleSize) { maxTupleSize=tupleSize; } accumulatedTupleSize+=tupleSize; } else { vtkErrorMacro("Invalid array name: " << this->VectorArrayNames[j]); return 0; } } ++j; } // add the size of the output (component is always float): if(resultType==1) { accumulatedTupleSize+=12; // (3*4) } else { accumulatedTupleSize+=4; } if(resultType == 1 && CoordinateResults != 0 && (psOutput || graphOutput)) { resultPoints = vtkPoints::New(); resultPoints->SetNumberOfPoints(numTuples); resultArray = resultPoints->GetData(); } else if(CoordinateResults != 0) { if(resultType != 1) { vtkErrorMacro("Coordinate output specified, " "but there are no vector results"); } else if(!psOutput) { vtkErrorMacro("Coordinate output specified, " "but output is not polydata or unstructured grid"); } return 1; } else { resultArray= vtkDataArray::SafeDownCast(vtkAbstractArray::CreateArray(this->ResultArrayType)); } if (resultType == 0) { resultArray->SetNumberOfComponents(1); resultArray->SetNumberOfTuples(numTuples); } else { resultArray->Allocate(numTuples * 3); resultArray->SetNumberOfComponents(3); } vtkShaderProgram2 *prog=vtkShaderProgram2::New(); prog->SetContext(static_cast(this->Context)); vtkShader2 *shader=vtkShader2::New(); shader->SetType(VTK_SHADER_TYPE_FRAGMENT); shader->SetSourceCode(this->FunctionParserToGLSL->GetGLSLCode()->c_str()); shader->SetContext(prog->GetContext()); prog->GetShaders()->AddItem(shader); shader->Delete(); prog->Build(); if(prog->GetLastBuildStatus()!=VTK_SHADER_PROGRAM2_LINK_SUCCEEDED) { vtkErrorMacro("shader build error."); return 0; } vtkKWEDataArrayStreamer *streamer=vtkKWEDataArrayStreamer::New(); GLint value; glGetIntegerv(vtkgl::MAX_3D_TEXTURE_SIZE,&value); vtkGraphicErrorMacro(this->Context,"__FILE__ __LINE__"); streamer->SetMax3DTextureSize(value); glGetIntegerv(GL_MAX_TEXTURE_SIZE,&value); vtkGraphicErrorMacro(this->Context,"__FILE__ __LINE__"); streamer->SetMaxTextureSize(value); streamer->SetMaxTextureMemorySizeInBytes(0); streamer->SetMaxNumberOfTuplesPerBlock(this->MaxGPUMemorySizeInBytes /accumulatedTupleSize); streamer->SetNumberOfTuples(numTuples); vtkstd::vector *buses= new vtkstd::vector(this->FunctionParserToGLSL->GetNumberOfUsedScalarVariables()+this->FunctionParserToGLSL->GetNumberOfUsedVectorVariables()); size_t busIndex=0; size_t numberOfBuses=buses->size(); while(busIndexSetContext(this->Context); (*buses)[busIndex]->SetMinTextureDimension(2); ++busIndex; } vtkDataTransferHelper *resultBus=vtkDataTransferHelper::New(); resultBus->SetContext(this->Context); resultBus->SetArray(resultArray); resultBus->SetShaderSupportsTextureInt(false); resultBus->SetMinTextureDimension(2); streamer->SetTupleSize(maxTupleSize); streamer->Begin(); vtkIdType dims[2]; bool firstIteration=true; vtkFrameBufferObject *fbo=0; int fboDims[2]; fboDims[0]=0; // to remove warning fboDims[1]=0; // to remove warning while(!streamer->IsDone()) { streamer->GetChunkDimensions(dims); vtkIdType cursor=streamer->GetCursor(); #ifdef VTKKWE_GPU_ARRAY_CALCULATOR_DEBUG cout<<"stream block start at cursor="<ScalarArrayNames[j]); return 0; } } ++j; } c=this->FunctionParserToGLSL->GetNumberOfVectorVariables(); j=0; while(jFunctionParserToGLSL->GetVectorIsUsed(j)) { ++textureUnit; vtkgl::ActiveTexture(vtkgl::TEXTURE0+textureUnit); currentArray=inFD->GetArray(this->VectorArrayNames[j]); if (currentArray) { if(firstIteration) { prog->GetUniformVariables()->SetUniformi(this->FunctionParserToGLSL->GetGLSLVectorName(j)->c_str(),1,&textureUnit); } // code to upload texture here. vtkDataTransferHelper *d=(*buses)[textureUnit]; d->SetArray(currentArray); d->SetCPUExtent(0,static_cast(numTuples-1),0,0,0,0); d->SetGPUExtent(static_cast(cursor), static_cast(cursor+dims[0]*dims[1]-1), 0,0,0,0); d->SetTextureExtent(0,static_cast(dims[0]-1),0, static_cast(dims[1]-1),0,0); int *components=this->SelectedVectorComponents[j]; d->Upload(3,components); d->GetTexture()->Bind(); } else { vtkErrorMacro("Invalid array name: " << this->VectorArrayNames[j]); return 0; } } ++j; } // Run GPU computation by drawing a quad prog->Use(); if(!prog->IsValid()) { vtkErrorMacro(<<" validation of the program failed: "<GetLastValidateLog()); } fbo->Start(fboDims[0],fboDims[1],false); fbo->RenderQuad(0,static_cast(dims[0]-1),0, static_cast(dims[1]-1)); prog->Restore(); // Get the result of the GPU, by downloading the texture. resultBus->SetCPUExtent(0,static_cast(numTuples-1),0,0,0,0); resultBus->SetGPUExtent(static_cast(cursor), static_cast(cursor+dims[0]*dims[1]-1), 0,0,0,0); resultBus->SetTextureExtent(0,static_cast(dims[0]-1),0, static_cast(dims[1]-1),0,0); resultBus->Download(); firstIteration=false; streamer->Next(); } if(fbo!=0) { fbo->Delete(); // do unbind and restore GL resources. } if(prog!=0) { prog->ReleaseGraphicsResources(); prog->Delete(); // do unbind and restore GL resources. } streamer->Delete(); busIndex=0; while(busIndexDelete(); ++busIndex; } delete buses; resultBus->Delete(); if(resultPoints) { if(psInput) { if(attributeDataType == 0) { psOutput->CopyStructure(psInput); } else { vtkPolyData* pd = vtkPolyData::SafeDownCast(psOutput); vtkUnstructuredGrid* ug = vtkUnstructuredGrid::SafeDownCast(psOutput); if(pd) { pd->Reset(); pd->Allocate(numTuples); for (i = 1; i < numTuples; i++) { pd->InsertNextCell(VTK_VERTEX, 1, &i); } } else if(ug) { ug->Reset(); ug->Allocate(numTuples); for (i = 1; i < numTuples; i++) { ug->InsertNextCell(VTK_VERTEX, 1, &i); } } } psOutput->SetPoints(resultPoints); } else { graphOutput->CopyStructure(graphInput); } outFD->PassData(inFD); resultPoints->Delete(); } else { dsOutput->CopyStructure(dsInput); dsOutput->CopyAttributes(dsInput); resultArray->SetName(this->ResultArrayName); outFD->AddArray(resultArray); if (resultType == 0) { outFD->SetActiveScalars(this->ResultArrayName); } else { outFD->SetActiveVectors(this->ResultArrayName); } resultArray->Delete(); } return 1; } // ---------------------------------------------------------------------------- void vtkKWEGPUArrayCalculator::SetFunction(const char* function) { if (this->Function && function && strcmp(this->Function, function) == 0) { return; } this->Modified(); if (this->Function) { delete [] this->Function; this->Function = NULL; } if (function) { this->Function = new char[strlen(function)+1]; strcpy(this->Function, function); this->FunctionParser->SetFunction(this->Function); this->FunctionParserToGLSL->SetFunction(this->Function); } } // ---------------------------------------------------------------------------- void vtkKWEGPUArrayCalculator::RemoveScalarVariables() { this->Superclass::RemoveScalarVariables(); this->FunctionParserToGLSL->RemoveScalarVariables(); } // ---------------------------------------------------------------------------- void vtkKWEGPUArrayCalculator::RemoveVectorVariables() { this->Superclass::RemoveVectorVariables(); this->FunctionParserToGLSL->RemoveVectorVariables(); } // ---------------------------------------------------------------------------- void vtkKWEGPUArrayCalculator::RemoveCoordinateScalarVariables() { this->Superclass::RemoveCoordinateScalarVariables(); this->FunctionParserToGLSL->RemoveScalarVariables(); } // ---------------------------------------------------------------------------- void vtkKWEGPUArrayCalculator::RemoveCoordinateVectorVariables() { this->Superclass::RemoveCoordinateVectorVariables(); this->FunctionParserToGLSL->RemoveVectorVariables(); } // ---------------------------------------------------------------------------- void vtkKWEGPUArrayCalculator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Max GPU Memory Size In Bytes: " << this->MaxGPUMemorySizeInBytes << endl; } vtkedge-0.2.0~20110819/Hybrid/CMakeLists.txt0000644000175000017500000000751511370314341020026 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Set of basic source files (not the OpenGL or GLSL ones) # ----------------------------------------------------------------------------- set(KIT_SRCS vtkKWEExtentCalculator.cxx vtkKWEGPUArrayCalculator.cxx vtkKWEGPUImageAlgorithmDriver.cxx vtkKWEImageGradientMagnitude.cxx ) # ----------------------------------------------------------------------------- # List the source files that should not be wrapped. # ----------------------------------------------------------------------------- #SET_SOURCE_FILES_PROPERTIES( # # WRAP_EXCLUDE) # ----------------------------------------------------------------------------- # Set of GLSL source files # ----------------------------------------------------------------------------- set(KIT_GLSL_SRCS vtkKWEImageGradientMagnitude_2D_fs vtkKWEImageGradientMagnitude_3D_fs ) # ----------------------------------------------------------------------------- # Create custom commands to encode each glsl file into a C string literal # in a header file # ----------------------------------------------------------------------------- foreach(file ${KIT_GLSL_SRCS}) set(src ${CMAKE_CURRENT_SOURCE_DIR}/${file}.glsl) set(res ${CMAKE_CURRENT_BINARY_DIR}/${file}.cxx) add_custom_command( OUTPUT ${res} DEPENDS ${src} COMMAND ${VTK_ENCODESTRING_EXE} ARGS ${res} ${src} ${file} ) set(KIT_EXTRA_SRCS ${KIT_EXTRA_SRCS} ${res}) endforeach(file) # ----------------------------------------------------------------------------- # List the kits that are needed by this project # ----------------------------------------------------------------------------- set(KIT_LIBS vtkHybrid vtkKWECommon vtkKWERendering ) # ----------------------------------------------------------------------------- # Create the library # ----------------------------------------------------------------------------- add_library(vtkKWEHybrid ${KIT_SRCS} ${KIT_EXTRA_SRCS}) target_link_libraries(vtkKWEHybrid ${KIT_LIBS}) # ----------------------------------------------------------------------------- # Testing # ----------------------------------------------------------------------------- if(BUILD_TESTING) add_subdirectory(Testing) endif(BUILD_TESTING) # ----------------------------------------------------------------------------- # Installation # ----------------------------------------------------------------------------- if(NOT VTKEdge_INSTALL_NO_LIBRARIES) install_targets( ${VTKEdge_INSTALL_LIB_DIR} RUNTIME_DIRECTORY ${VTKEdge_INSTALL_BIN_DIR} vtkKWEHybrid ) endif(NOT VTKEdge_INSTALL_NO_LIBRARIES) if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_INCLUDE_DIR} .h ${KIT_SRCS}) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) # ----------------------------------------------------------------------------- # This make it easy for other projects to get the list of files etc. in this # kit. # ----------------------------------------------------------------------------- include(${VTK_CMAKE_DIR}/vtkExportKit.cmake) vtk_export_kit2("KWEHybrid" "KWEHYBRID" ${CMAKE_CURRENT_BINARY_DIR} "${KIT_SRCS}") vtkedge-0.2.0~20110819/Hybrid/vtkKWEImageGradientMagnitude.h0000644000175000017500000000630411370314341023064 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEImageGradientMagnitude // .SECTION Description #ifndef __vtkKWEImageGradientMagnitude_h #define __vtkKWEImageGradientMagnitude_h #include "vtkKWEGPUImageAlgorithmDriver.h" class vtkShaderProgram2; class VTKEdge_HYBRID_EXPORT vtkKWEImageGradientMagnitude : public vtkKWEGPUImageAlgorithmDriver { public: static vtkKWEImageGradientMagnitude* New(); vtkTypeRevisionMacro(vtkKWEImageGradientMagnitude, vtkKWEGPUImageAlgorithmDriver); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Determines how the input is interpreted (set of 2d slices ...) vtkSetClampMacro(Dimensionality,int,2,3); vtkGetMacro(Dimensionality,int); //BTX protected: vtkKWEImageGradientMagnitude(); ~vtkKWEImageGradientMagnitude(); // Description: // The method should return how the streamer should break up extents. // This is not much different from the split mode specified on // vtkExtentTranslator. virtual ExtentTypes GetSplitMode(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); // Description: // Given the output_extent that we need to // produce, what extents does the subclass need from the input on the // indicated (port, connection). Return value is a an int indicating the // minimum dimensionality of the texture created for the corresponding input. // Returns value 0 (or less) indicates error. virtual int MapOutputExtentToInput(int input_extent[6], int port, int connection, vtkInformation* inInfo, const int output_extent[6]); // Description: // Actual execution method. virtual bool Execute(vtkBuses* upBuses, vtkDataTransferHelper* downBus); virtual void Execute() { this->Superclass::Execute(); } // Description: // Gives the subclasses an opportunity to do some initialization before the // looping begins. bool InitializeExecution( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); // Description: // Gives the subclasses an opportunity to do some cleanup after the // looping ends. bool FinalizeExecution( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); int Dimensionality; vtkSmartPointer GLSLProgram; double SpacingReciprocal[3]; private: vtkKWEImageGradientMagnitude(const vtkKWEImageGradientMagnitude&); // Not implemented. void operator=(const vtkKWEImageGradientMagnitude&); // Not implemented. //ETX }; #endif vtkedge-0.2.0~20110819/Hybrid/Testing/0000755000175000017500000000000011630434664016705 5ustar mathieumathieuvtkedge-0.2.0~20110819/Hybrid/Testing/Cxx/0000755000175000017500000000000011630434664017447 5ustar mathieumathieuvtkedge-0.2.0~20110819/Hybrid/Testing/Cxx/TestKWEGPUArrayCalculator.cxx0000644000175000017500000002116511363410610025037 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This test covers vtkKWEGPUArrayCalulator, compare to vtkArrayCalculator. // The command line arguments are: // -I => run in interactive mode; unless this is used, the program will // not allow interaction and exit // An image data is first created with a raw array. // Some computation on the data array is performed // IF THIS TEST TIMEOUT, IT IS PROBABLY ON VISTA WITH A NOT-FAST-ENOUGH // GRAPHICS CARD: // Depending on how fast/slow is the graphics card, the computation on the GPU // can take more than 2 seconds. On Vista, after a 2 seconds timeout, the // Windows Vista's Timeout Detection and Recovery (TDR) kills all the graphics // contexts, resets the graphics chip and recovers the graphics driver, in // order to keep the operating system responsive. // ref: http://www.opengl.org/pipeline/article/vol003_7/ // This reset actually freezes the test. And it really times out this time... // Example of pathological case: dash1vista32.kitware/Win32Vista-vs80 #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkArrayCalculator.h" #include "vtkKWEGPUArrayCalculator.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderWindow.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkRenderer.h" #include "vtkOutlineFilter.h" #include "vtkImageData.h" #include "vtkPointData.h" #include "vtkImageImport.h" #include #include "vtkTimerLog.h" #include "vtkDoubleArray.h" #include "vtkXYPlotWidget.h" #include "vtkXYPlotActor.h" // On a nVidia Quadro FX 3600M (~GeForce8), // GL_MAX_TEXTURE_SIZE = 8192, GL_MAX_3D_TEXTURE_SIZE = 2048 // GL_MAX_VIEWPORT_DIMS = 8192, 8192 // The following size matches two complete full 2D textures, one 2D texture // with one complete row and one 2D texture with just one pixel. //const vtkIdType TestNumberOfPoints=2*(8192*8192)+8192+1; const vtkIdType TestNumberOfPoints=(2*(8192*8192)+8192+1)/10; // 2*(8192*8192)+8192+1; //4096*4096; const int TestNumberOfComponents=1; // 1 or 3 void ComputeAndDisplayMeanErrorAndStandardDeviation(vtkDoubleArray *c, vtkDoubleArray *g) { assert("pre: c_exists" && c!=0); assert("pre: g_exists" && g!=0); assert("pre: same_size" && c->GetNumberOfTuples()==g->GetNumberOfTuples()); assert("pre: same_components" && c->GetNumberOfComponents()==g->GetNumberOfComponents()); assert("pre: not_empty" && c->GetNumberOfTuples()>0); vtkIdType n=c->GetNumberOfTuples()*c->GetNumberOfComponents(); double *a=static_cast(c->GetVoidPointer(0)); double *b=static_cast(g->GetVoidPointer(0)); vtkIdType i; // mean error double meanError=0.0; double maxError=0.0; i=0; while(imaxError) { maxError=delta; } meanError+=delta; ++i; } meanError/=static_cast(n); // std deviation double stdDeviation=0.0; i=0; while(i(n)); cout<<" number of values="<0); vtkImageImport *im=vtkImageImport::New(); float *ptr=new float[numberOfPoints*numberOfComponents]; vtkIdType i=0; while(i(i); // 2.0 ++i; } im->SetDataScalarTypeToFloat(); im->SetImportVoidPointer(ptr,0); // let the importer delete it. im->SetNumberOfScalarComponents(numberOfComponents); im->SetDataExtent(0,static_cast(numberOfPoints-1),0,0,0,0); im->SetWholeExtent(0,static_cast(numberOfPoints-1),0,0,0,0); im->SetScalarArrayName("values"); return im; } int TestKWEGPUArrayCalculator(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) { vtkRenderWindowInteractor *iren=vtkRenderWindowInteractor::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->SetSize(101,99); renWin->SetAlphaBitPlanes(1); renWin->SetReportGraphicErrors(1); iren->SetRenderWindow(renWin); renWin->Delete(); // Useful when looking at the test output in CDash: cout << "IF THIS TEST TIMEOUT, IT IS PROBABLY ON VISTA WITH" << " A NOT-FAST-ENOUGH GRAPHICS CARD."<SetInputConnection(0,im->GetOutputPort(0)); // reader or source calc->AddScalarArrayName("values"); calc->SetResultArrayName("Result"); calc->SetFunction("values+10.0"); // calc->SetFunction("sin(norm(values))+cos(norm(values))+10.0"); // calc->SetFunction("sin(values)*cos(values)+10.0"); // calc->SetFunction("exp(sqrt(sin(values)*cos(values)+10.0))"); vtkTimerLog *timer=vtkTimerLog::New(); timer->StartTimer(); calc->Update(); timer->StopTimer(); cout<<"Elapsed time with CPU version:"<GetElapsedTime()<<" seconds."<GetOutputDataObject(0)); image->GetPointData()->GetScalars()->GetRange(range); cout<<"range2[2]="<SetContext(renWin); calc2->SetInputConnection(0,im->GetOutputPort(0)); // reader or source calc2->AddScalarArrayName("values"); calc2->SetResultArrayName("Result"); calc2->SetFunction("values+10"); // calc2->SetFunction("sin(norm(values))+cos(norm(values))+10.0"); // calc2->SetFunction("sin(values)*cos(values)+10.0"); // calc2->SetFunction("exp(sqrt(sin(values)*cos(values)+10.0))"); // my nVidia Quadro FX 3600M has 512MB // esimatation of 28MB already taken for screen+current context // at 1600*1200: 512-28=484 // calc2->SetMaxGPUMemorySizeInBytes(512*1024*1024); calc2->SetMaxGPUMemorySizeInBytes(128*1024*1024); timer->StartTimer(); calc2->Update(); timer->StopTimer(); cout<<"Elapsed time with GPU version:"<GetElapsedTime()<<" seconds."<GetOutputDataObject(0)); image2->GetPointData()->GetScalars()->GetRange(range); cout<<"range3[2]="<GetPointData()->GetScalars()), vtkDoubleArray::SafeDownCast(image2->GetPointData()->GetScalars())); timer->Delete(); calc2->Calibrate(); cout<<"Calibrated size threshold="<GetCalibratedSizeThreshold()<SetBackground(0.0,0.0,0.3); renWin->AddRenderer(renderer); renderer->Delete(); vtkXYPlotActor *actor=vtkXYPlotActor::New(); renderer->AddViewProp(actor); actor->Delete(); actor->AddInput(image,"Result",0); actor->SetPlotColor(0,1.0,0.0,0.0); actor->AddInput(image2,"Result",0); actor->SetPlotColor(1,0.0,1.0,0.0); renWin->Render(); vtkXYPlotWidget *w=vtkXYPlotWidget::New(); w->SetInteractor(iren); w->SetXYPlotActor(actor); w->SetEnabled(1); int retVal = vtkRegressionTestImage(renWin); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } w->Delete(); #endif calc2->Delete(); // need context iren->Delete(); im->Delete(); calc->Delete(); return 0; // !retVal; 0: passed, 1: failed } vtkedge-0.2.0~20110819/Hybrid/Testing/Cxx/CMakeLists.txt0000644000175000017500000000434011363410610022174 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Name this kit - this will be used to form test executable names later # Then we'll add in tests with various data or kit dependencies to the # test executables # ----------------------------------------------------------------------------- set(KIT Hybrid) set(TESTBASE ${PROJECT_NAME}${KIT}) include_directories("${VTKEdge_SOURCE_DIR}/Examples/Hybrid/Cxx") # ----------------------------------------------------------------------------- # First, list all the tests that either use no data, or only data from the # VTKEdge data directory (which always exists since it is part of the # VTKEdge repository). These will go into one test executable. # ----------------------------------------------------------------------------- set(MyTests TestKWEGPUArrayCalculator ) create_test_sourcelist(Tests ${TESTBASE}CxxTests.cxx ${MyTests} EXTRA_INCLUDE vtkTestDriver.h ) add_executable(${TESTBASE}CxxTests ${Tests}) #install_targets(${VTKEdge_INSTALL_BIN_DIR} ${TESTBASE}CxxTests) target_link_libraries(${TESTBASE}CxxTests vtkKWEHybrid vtkWidgets) set(TestsToRun ${Tests}) remove(TestsToRun ${TESTBASE}CxxTests.cxx) # Add all the executables foreach(test ${TestsToRun}) get_filename_component(TName ${test} NAME_WE) add_test(${TName} ${CXX_TEST_PATH}/${TESTBASE}CxxTests ${TName} -D ${PROJECT_SOURCE_DIR}/Data -T ${PROJECT_BINARY_DIR}/Testing/Temporary -V ${PROJECT_SOURCE_DIR}/Data/Baseline/${KIT}/${TName}.png ) endforeach(test) vtkedge-0.2.0~20110819/Hybrid/Testing/CMakeLists.txt0000644000175000017500000000166011363410610021434 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Add the Cxx testing directory # ----------------------------------------------------------------------------- add_subdirectory(Cxx) vtkedge-0.2.0~20110819/Hybrid/vtkKWEImageGradientMagnitude_2D_fs.glsl0000644000175000017500000000271711363410610024615 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // FileID: $Id: vtkKWEImageGradientMagnitude_2D_fs.glsl 1774 2010-04-20 20:41:44Z avila $ #version 110 // Expected uniforms. uniform sampler2D uInputImage; uniform vec3 uSpacingReciprocal; uniform vec3 uInputImageDims; // Computed constants. const float step_w = 1.0/uInputImageDims.x; const float step_h = 1.0/uInputImageDims.y; vec2 offset[2] = vec2[](vec2(step_w, 0), vec2(0, step_h)); void main(void) { vec4 dX = texture2D(uInputImage, gl_TexCoord[0].st-offset[0]); dX -= texture2D(uInputImage, gl_TexCoord[0].st+offset[0]); dX *= uSpacingReciprocal.x; vec4 dY = texture2D(uInputImage, gl_TexCoord[0].st-offset[1]); dY -= texture2D(uInputImage, gl_TexCoord[0].st+offset[1]); dY *= uSpacingReciprocal.y; gl_FragColor = sqrt(dX*dX+dY*dY); } vtkedge-0.2.0~20110819/Hybrid/vtkKWEExtentCalculator.cxx0000644000175000017500000001611711363410610022363 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEExtentCalculator.h" #include "vtkObjectFactory.h" #include "vtkRenderWindow.h" #include "assert.h" #include "vtkgl.h" static void vtkInvalidateExtent(int ext[6]) { ext[0] = ext[2] = ext[4] = 0; ext[1] = ext[3] = ext[5] = -1; } static bool vtkIsValid(int ext[6]) { return (ext[1] >= ext[0] && ext[3] >= ext[2] && ext[5] >= ext[4]); } vtkStandardNewMacro(vtkKWEExtentCalculator); vtkCxxRevisionMacro(vtkKWEExtentCalculator, "$Revision: 1774 $"); //---------------------------------------------------------------------------- vtkKWEExtentCalculator::vtkKWEExtentCalculator() { vtkInvalidateExtent(this->WholeExtent); vtkInvalidateExtent(this->InChunkExtent); vtkInvalidateExtent(this->OutChunkExtent); this->GhostLevels[0] = this->GhostLevels[1] = this->GhostLevels[2] = 0; this->ChunkDescription = XYZ_GRID; this->Max3DTextureSize=16; // 16 is the minimum value of the OpenGL spec. this->MaxTextureSize=64; // 64 is the minimum value of the OpenGL spec. this->MaxTextureMemorySizeInBytes=128*1024*1024; this->InTupleSize=1; this->OutTupleSize=1; } //---------------------------------------------------------------------------- vtkKWEExtentCalculator::~vtkKWEExtentCalculator() { } //---------------------------------------------------------------------------- void vtkKWEExtentCalculator::LoadLimits(vtkRenderWindow* renWin) { renWin->MakeCurrent(); GLint value; glGetIntegerv(vtkgl::MAX_3D_TEXTURE_SIZE,&value); this->SetMax3DTextureSize(value); glGetIntegerv(GL_MAX_TEXTURE_SIZE,&value); this->SetMaxTextureSize(value); } //---------------------------------------------------------------------------- void vtkKWEExtentCalculator::Begin() { if (!::vtkIsValid(this->WholeExtent)) { return; } this->Order[0]=0; this->Order[1]=1; this->Order[2]=2; this->Max[0]=this->WholeExtent[1]-this->WholeExtent[0]+1; this->Max[1]=this->WholeExtent[3]-this->WholeExtent[2]+1; this->Max[2]=this->WholeExtent[5]-this->WholeExtent[4]+1; this->Cursor[0]=0; this->Cursor[1]=0; this->Cursor[2]=0; this->Step[0]=this->WholeExtent[1]-this->WholeExtent[0]+1; this->Step[1]=this->WholeExtent[3]-this->WholeExtent[2]+1; this->Step[2]=this->WholeExtent[5]-this->WholeExtent[4]+1; // The challenging work is here. switch (this->ChunkDescription) { case XY_PLANE: this->Order[0]=2; this->Order[1]=1; this->Order[2]=0; this->Step[2]=1; break; case YZ_PLANE: this->Order[0]=0; this->Order[1]=2; this->Order[2]=1; this->Step[0]=1; break; case XZ_PLANE: this->Order[0]=1; this->Order[1]=2; this->Order[2]=0; this->Step[1]=1; break; case XYZ_GRID: this->Order[0]=2; this->Order[1]=1; this->Order[2]=0; break; } // Hardware index limits: int maxSize=this->Max3DTextureSize; if(this->ChunkDescription!=XYZ_GRID && this->GhostLevels[this->Order[0]]==0) { maxSize=this->MaxTextureSize; } int comp=0; while(comp<3) { if(this->Step[comp]>maxSize) { this->Step[comp]=maxSize-2*this->GhostLevels[comp]; } ++comp; } // User limits and datatype: if(this->MaxTextureMemorySizeInBytes>0) { int maxTupleSize; if(this->InTupleSize>this->OutTupleSize) { maxTupleSize=this->InTupleSize; } else { maxTupleSize=this->OutTupleSize; } int currentSize=this->Step[0]*this->Step[1]*this->Step[2]*maxTupleSize; int ratio=currentSize/this->MaxTextureMemorySizeInBytes; // can be 0. int remainder=currentSize-ratio*this->MaxTextureMemorySizeInBytes; int compToShrink=0; while(compToShrink<3 && (ratio>=1 && remainder>0)) { if(this->Step[Order[compToShrink]]>1) { if(ratio>this->Step[Order[compToShrink]]) { this->Step[Order[compToShrink]]=1; } else { this->Step[Order[compToShrink]]/=ratio; } } currentSize=this->Step[0]*this->Step[1]*this->Step[2]*maxTupleSize; ratio=currentSize/this->MaxTextureMemorySizeInBytes; remainder=currentSize-ratio*this->MaxTextureMemorySizeInBytes; ++compToShrink; } } this->ComputeChunkExtents(); } //---------------------------------------------------------------------------- bool vtkKWEExtentCalculator::IsDone() { // Check for the most outer loop return this->Cursor[this->Order[0]]>=this->Max[this->Order[0]]; } //---------------------------------------------------------------------------- void vtkKWEExtentCalculator::Next() { assert("pre: not_done" && !this->IsDone()); // Most inner loop first this->Cursor[this->Order[2]]+=this->Step[this->Order[2]]; if(this->Cursor[this->Order[2]]>=this->Max[this->Order[2]]) { this->Cursor[this->Order[2]]=0; this->Cursor[this->Order[1]]+=this->Step[this->Order[1]]; if(this->Cursor[this->Order[1]]>=this->Max[this->Order[1]]) { this->Cursor[this->Order[1]]=0; this->Cursor[this->Order[0]]+=this->Step[this->Order[0]]; } } this->ComputeChunkExtents(); } //---------------------------------------------------------------------------- void vtkKWEExtentCalculator::ComputeChunkExtents() { vtkInvalidateExtent(this->InChunkExtent); vtkInvalidateExtent(this->OutChunkExtent); if (this->IsDone()) { return; } int coord=0; while(coord<3) { this->InChunkExtent[2*coord]=this->Cursor[coord]-this->GhostLevels[coord]; if(this->InChunkExtent[2*coord]WholeExtent[2*coord]) { this->InChunkExtent[2*coord]=this->WholeExtent[2*coord]; } this->InChunkExtent[2*coord+1]=this->Cursor[coord]+this->Step[coord]-1 +this->GhostLevels[coord]; if(this->InChunkExtent[2*coord+1]>this->WholeExtent[2*coord+1]) { this->InChunkExtent[2*coord+1]=this->WholeExtent[2*coord+1]; } // Should not need to clamp the output. It should be in the right range // by construction. this->OutChunkExtent[2*coord]=this->Cursor[coord]; this->OutChunkExtent[2*coord+1]=this->Cursor[coord]+this->Step[coord]-1; ++coord; } assert("post: validate InChunkExtent" && vtkIsValid(this->InChunkExtent)); assert("post: validate OutChunkExtent" && vtkIsValid(this->OutChunkExtent)); } //---------------------------------------------------------------------------- void vtkKWEExtentCalculator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } vtkedge-0.2.0~20110819/Hybrid/vtkKWEGPUImageAlgorithmDriver.h0000644000175000017500000001256211370314341023152 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEGPUImageAlgorithmDriver // .SECTION Description // vtkKWEGPUImageAlgorithmDriver is a the driver for all image processing // algorithms that use the GPU to do the work. #ifndef __vtkKWEGPUImageAlgorithmDriver_h #define __vtkKWEGPUImageAlgorithmDriver_h #include "vtkImageAlgorithm.h" #include "VTKEdgeConfigure.h" // include configuration header #include "vtkStructuredData.h" // for VTK_XY_PLANE, ... #include "vtkWeakPointer.h" // needed for vtkWeakPointer #include "vtkSmartPointer.h" // needed for vtkWeakPointer //BTX #include //ETX class vtkRenderWindow; class vtkDataTransferHelper; class vtkKWEExtentCalculator; class VTKEdge_HYBRID_EXPORT vtkKWEGPUImageAlgorithmDriver : public vtkImageAlgorithm { public: vtkTypeRevisionMacro(vtkKWEGPUImageAlgorithmDriver, vtkImageAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Get/Set the context. Note that the context is not reference counted. vtkRenderWindow* GetContext(); virtual void SetContext(vtkRenderWindow*); //BTX enum ExtentTypes { INVALID=0, XY_PLANE = VTK_XY_PLANE, YZ_PLANE = VTK_YZ_PLANE, XZ_PLANE = VTK_XZ_PLANE, XYZ_GRID = VTK_XYZ_GRID }; protected: class vtkBuses; vtkKWEGPUImageAlgorithmDriver(); ~vtkKWEGPUImageAlgorithmDriver(); // Description: // The method should return how the streamer should break up extents. // This is not much different from the split mode specified on // vtkExtentTranslator. virtual ExtentTypes GetSplitMode(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) = 0; // Description: // Given the output_extent that we need to // produce, what extents does the subclass need from the input on the // indicated (port, connection). Return value is a an int indicating the // minimum dimensionality of the texture created for the corresponding input. // Returns value 0 (or less) indicates error. virtual int MapOutputExtentToInput(int input_extent[6], int port, int connection, vtkInformation* inInfo, const int output_extent[6]) = 0; // Description: // Gives the subclasses an opportunity to do some initialization before the // looping begins. virtual bool InitializeExecution( vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* vtkNotUsed(outputVector)) {return true;} // Description: // Actual execution method. virtual bool Execute(vtkBuses* upBuses, vtkDataTransferHelper* downBus) = 0; virtual void Execute() { this->Superclass::Execute(); } // Description: // Gives the subclasses an opportunity to do some cleanup after the // looping ends. virtual bool FinalizeExecution( vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* vtkNotUsed(outputVector)) {return true;} // Description: // Actual execution. Subclasses should not override this method. They should // override Execute() instead. virtual int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); // Description: // RequestUpdateExtent. int RequestUpdateExtent ( vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector); bool ComputeTCoordsRange(double tcoords[6], const int inputExt[6], const int outputExt[6]); vtkWeakPointer Context; bool OwnContext; private: vtkKWEGPUImageAlgorithmDriver(const vtkKWEGPUImageAlgorithmDriver&); // Not implemented. void operator=(const vtkKWEGPUImageAlgorithmDriver&); // Not implemented. class vtkPipe; friend class vtkPipe; // Description: // Internal method that uploads the current chunk for all inputs to the GPU. vtkBuses* Upload(vtkKWEExtentCalculator* extentCalculator, vtkInformationVector** inputVector, vtkPipe& pipe); bool SetupOutputTexture(ExtentTypes chunkType, vtkDataTransferHelper* down_bus); //ETX }; //BTX class vtkKWEGPUImageAlgorithmDriver::vtkBuses : public vtkObjectBase { public: vtkTypeRevisionMacro(vtkBuses, vtkObjectBase); static vtkBuses* New(); void SetNumberOfPorts(unsigned int num); void SetNumberOfConnections(unsigned int port, unsigned int num); vtkDataTransferHelper* GetBus(unsigned int port, unsigned int conn); void SetBus(unsigned int port, unsigned int conn, vtkDataTransferHelper* bus); private: vtkBuses() { } virtual ~vtkBuses() { } typedef vtkstd::vector > XferHelperVector; typedef vtkstd::vector VectorOfXferHelperVector; VectorOfXferHelperVector Buses; }; //ETX #endif vtkedge-0.2.0~20110819/Hybrid/vtkKWEExtentCalculator.h0000644000175000017500000001126311363410610022005 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEExtentCalculator - facilitates iterating over structured data. // .SECTION Description // vtkKWEExtentCalculator facilitates iterating over structured data. // Used to compute input/output image extents. #ifndef __vtkKWEExtentCalculator_h #define __vtkKWEExtentCalculator_h #include "VTKEdgeConfigure.h" // include configuration header #include "vtkObject.h" #include "vtkStructuredData.h" // for VTK_XY_PLANE, ... class vtkRenderWindow; class VTKEdge_HYBRID_EXPORT vtkKWEExtentCalculator : public vtkObject { public: static vtkKWEExtentCalculator* New(); vtkTypeRevisionMacro(vtkKWEExtentCalculator, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Input extent to split. vtkSetVector6Macro(WholeExtent, int); vtkGetVector6Macro(WholeExtent, int); // Description: // Rule governing how to split the data into chunks. vtkSetMacro(ChunkDescription, int); vtkGetMacro(ChunkDescription, int); //BTX enum ChunkDescriptions { XY_PLANE = VTK_XY_PLANE, YZ_PLANE = VTK_YZ_PLANE, XZ_PLANE = VTK_XZ_PLANE, XYZ_GRID = VTK_XYZ_GRID, DEFAULT = XYZ_GRID }; //ETX // Description: // Set ghost levels for each pass. vtkSetVector3Macro(GhostLevels, int); vtkGetVector3Macro(GhostLevels, int); // Description: // Maximum size of any dimension of a 3D texture. Initial value is 16, // the minimal value of the OpenGL specifications. vtkSetMacro(Max3DTextureSize, int); vtkGetMacro(Max3DTextureSize, int); // Description: // Maximum size of any dimension of a 1D or 2D texture. Initial value is 64, // the minimal value of the OpenGL specifications. vtkSetMacro(MaxTextureSize, int); vtkGetMacro(MaxTextureSize, int); // Description: // User-defined maximum size in bytes of a texture in GPU memory. // Initial value is 134217728 bytes (128*2^20=128Mb). // As this ivar is a signed int, it cannot encode more than 2GB. // A negative value means no limit. vtkSetMacro(MaxTextureMemorySizeInBytes,int); vtkGetMacro(MaxTextureMemorySizeInBytes,int); // Description: // Size of a tuple of the incoming data in bytes. // Initial value is 1. vtkSetMacro(InTupleSize,int); vtkGetMacro(InTupleSize,int); // Description: // Size of a tuple of the output data in bytes. // Initial value is 1. vtkSetMacro(OutTupleSize,int); vtkGetMacro(OutTupleSize,int); // Description: // Place the cursor on the first chunk, if any. void Begin(); // Description: // Is the iteration over? bool IsDone(); // Description: // Go the next chunk, if any. // \pre not_done: !IsDone() void Next(); // Description: // Returns the extent for the input for the current piece. This will be the // output extent plus the ghost levels, if any. // \pre not_done: !IsDone() vtkGetVector6Macro(InChunkExtent, int); // Description: // Returns the extent for the output for the current piece. // \pre not_done: !IsDone() vtkGetVector6Macro(OutChunkExtent, int); // Description: // Load texture limits using the context. void LoadLimits(vtkRenderWindow* context); //BTX protected: vtkKWEExtentCalculator(); ~vtkKWEExtentCalculator(); int WholeExtent[6]; int ChunkDescription; int GhostLevels[3]; int InChunkExtent[6]; int OutChunkExtent[6]; int Max3DTextureSize; int MaxTextureSize; int MaxTextureMemorySizeInBytes; int InTupleSize; int OutTupleSize; // int Piece; // int NumberOfPieces; int Cursor[3]; // current position in i,j,k int Max[3]; // i goes from 0 to Max[0]-1, j goes from 0 Max[1]-1, ... int Order[3]; // Tells if we iterate over i then j then k (0,1,2), // over i,k,j (0,2,1), over j,k,i (1,2,0), j,i,k (1,0,2), k,i,j (2,0,1) // or k,j,i (2,1,0) Order[0]!=Order[1]!=Order[2] int Step[3]; // step for i, j and k at each iteration step void ComputeChunkExtents(); private: vtkKWEExtentCalculator(const vtkKWEExtentCalculator&); // Not implemented. void operator=(const vtkKWEExtentCalculator&); // Not implemented. //ETX }; #endif vtkedge-0.2.0~20110819/Hybrid/vtkKWEImageGradientMagnitude_3D_fs.glsl0000644000175000017500000000327511363410610024616 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // FileID: $Id: vtkKWEImageGradientMagnitude_3D_fs.glsl 1774 2010-04-20 20:41:44Z avila $ #version 110 // Expected uniforms. uniform sampler3D uInputImage; uniform vec3 uSpacingReciprocal; uniform vec3 uInputImageDims; // Computed constants. const float step_w = 1.0/uInputImageDims.x; const float step_h = 1.0/uInputImageDims.y; const float step_d = 1.0/uInputImageDims.z; vec3 offset[3] = vec3[](vec3(step_w, 0, 0), vec3(0, step_h,0), vec3(0, 0, step_d)); void main(void) { vec4 dX = texture3D(uInputImage, gl_TexCoord[0].stp-offset[0]); dX -= texture3D(uInputImage, gl_TexCoord[0].stp+offset[0]); dX *= uSpacingReciprocal.x; vec4 dY = texture3D(uInputImage, gl_TexCoord[0].stp-offset[1]); dY -= texture3D(uInputImage, gl_TexCoord[0].stp+offset[1]); dY *= uSpacingReciprocal.y; vec4 dZ = texture3D(uInputImage, gl_TexCoord[0].stp-offset[2]); dZ -= texture3D(uInputImage, gl_TexCoord[0].stp+offset[2]); dZ *= uSpacingReciprocal.z; gl_FragColor = sqrt(dX*dX+dY*dY+dZ*dZ); } vtkedge-0.2.0~20110819/Hybrid/vtkKWEGPUArrayCalculator.h0000644000175000017500000001422111363410610022165 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEGPUArrayCalculator - perform mathematical operations on data in field data arrays on the GPU // .SECTION Description // vtkGPUArrayCalculator performs operations on vectors or scalars in field // data arrays on the GPU. It uses vtkFunctionParser to do the parsing and to // evaluate the function for each entry in the input arrays. The arrays // used in a given function must be all in point data or all in cell data. // The resulting array will be stored as a field data array. The result // array can either be stored in a new array or it can overwrite an existing // array. // // The functions that this array calculator understands is: //
// standard operations: + - * / ^ .
// access vector components: iHat, jHat, kHat
// abs
// acos
// asin
// atan
// ceil
// cos
// cosh
// exp
// floor
// log
// mag
// min
// max
// norm
// sign
// sin
// sinh
// sqrt
// tan
// tanh
// 
// Note that some of these operations work on scalars, some on vectors, and some on // both (e.g., you can multiply a scalar times a vector). The operations are performed // tuple-wise (i.e., tuple-by-tuple). The user must specify which arrays to use as // vectors and/or scalars, and the name of the output data array. // // .SECTION See Also // vtkFunctionParser #ifndef __vtkKWEGPUArrayCalculator_h #define __vtkKWEGPUArrayCalculator_h #include "vtkArrayCalculator.h" #include "VTKEdgeConfigure.h" // include configuration header class vtkKWEFunctionToGLSL; class vtkRenderWindow; class vtkFloatArray; class VTKEdge_HYBRID_EXPORT vtkKWEGPUArrayCalculator : public vtkArrayCalculator { public: vtkTypeRevisionMacro(vtkKWEGPUArrayCalculator,vtkArrayCalculator); void PrintSelf(ostream& os, vtkIndent indent); static vtkKWEGPUArrayCalculator *New(); // Description: // Get/Set the rendering context. vtkGetObjectMacro(Context, vtkRenderWindow); void SetContext(vtkRenderWindow *); // Description: // Tells if the GPU implementation is supported by the graphics card in use. bool GetSupportedByHardware(); // Description: // Set/Get the function to be evaluated. virtual void SetFunction(const char* function); // Description: // Set/Get the dataset size threshold. Under this size, // the CPU implementation is used (see vtkArrayCalculator). // Above or equal to this size, the GPU is used if it supports the required // OpenGL extensions. Initial value is 0, trying to use the GPU in any case. // The GPU implementation is faster than the CPU implementation if the data // array is large enough. This threshold depends on the both the speed of // the CPU and the GPU, the RAM and VRAM. An experiment on an Intel Core 2 // Duo T9500, 4GB with a nVidia Quadro FX 3600M, 512MB shows that 15000 is // a good threshold. vtkSetMacro(SizeThreshold,vtkIdType); vtkGetMacro(SizeThreshold,vtkIdType); // Description: // Tell the filter to use CalibratedSizeThreshold instead of SizeThreshold. // If CalibratedSizeThreshold has not been computed yet, a calibration is // performed (expensive call to Calibrate() that happens once). vtkGetMacro(UseCalibration,int); vtkSetMacro(UseCalibration,int); vtkBooleanMacro(UseCalibration,int); // Description: // Tell the filter to calibrate itself. Starting for the current value of // SizeThreshold, try to find the actual threshold size at which the GPU // implementation is faster than the CPU one. This call is expensive. // This method is usually called automatically once when UseCalibration is // on. But you can call it directly to control at what time the calibration // happens or to force a new calibration. void Calibrate(); // Description: // Return the size threshold computed by the last calibration. Initial value // is 0. vtkGetMacro(CalibratedSizeThreshold,vtkIdType); // Description: // Remove all the scalar variable names and their associated array names. virtual void RemoveScalarVariables(); // Description: // Remove all the scalar variable names and their associated array names. virtual void RemoveVectorVariables(); // Description: // Remove all the coordinate variables. virtual void RemoveCoordinateScalarVariables(); // Description: // Remove all the coordinate variables. virtual void RemoveCoordinateVectorVariables(); // Description: // User-defined maximum size in bytes of GPU memory that can be // assigned to the array calculator. // Initial value is 134217728 bytes (128*2^20=128Mb). // In a 32-bit build, this ivar can encode up to 4GB. // A null value means no limit. vtkSetMacro(MaxGPUMemorySizeInBytes,vtkIdType); vtkGetMacro(MaxGPUMemorySizeInBytes,vtkIdType); protected: vtkKWEGPUArrayCalculator(); virtual ~vtkKWEGPUArrayCalculator(); void SimulateGPUComputation(vtkFloatArray *values); virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); virtual void ComputeSubRange(vtkDataArray *array, vtkIdType first, vtkIdType last, double subRange[2]); vtkRenderWindow *Context; vtkKWEFunctionToGLSL *FunctionParserToGLSL; vtkIdType MaxGPUMemorySizeInBytes; vtkIdType SizeThreshold; int UseCalibration; // boolean vtkIdType CalibratedSizeThreshold; bool CalibrationDone; bool SupportedByHardware; private: vtkKWEGPUArrayCalculator(const vtkKWEGPUArrayCalculator&); // Not implemented. void operator=(const vtkKWEGPUArrayCalculator&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/VTKEdgeConfigure.h.in0000644000175000017500000001736511363410610017720 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= //----------------------------------------------------------------------------- // The version information //----------------------------------------------------------------------------- #define VTKEdge_VERSION_MAJOR @VTKEdge_VERSION_MAJOR@ #define VTKEdge_VERSION_MINOR @VTKEdge_VERSION_MINOR@ #define VTKEdge_VERSION_BUILD @VTKEdge_VERSION_BUILD@ #define VTKEdge_VERSION @VTKEdge_VERSION@ #define VTKEdge_VERSION_STRING "@VTKEdge_VERSION@" //----------------------------------------------------------------------------- // Expose the source directory to allow for style testing //----------------------------------------------------------------------------- #define VTKEdge_SOURCE_DIR "@VTKEdge_SOURCE_DIR@" //----------------------------------------------------------------------------- // Config options //----------------------------------------------------------------------------- #cmakedefine VTKEdge_BUILD_SHARED_LIBS #cmakedefine VTKEdge_BUILD_EXAMPLES #cmakedefine VTKEdge_BUILD_PARAVIEW_PLUGINS #cmakedefine VTKEdge_BUILD_Common_KIT #cmakedefine VTKEdge_BUILD_Filtering_KIT #cmakedefine VTKEdge_BUILD_Graphics_KIT #cmakedefine VTKEdge_BUILD_Hybrid_KIT #cmakedefine VTKEdge_BUILD_Imaging_KIT #cmakedefine VTKEdge_BUILD_IO_KIT #cmakedefine VTKEdge_BUILD_Rendering_KIT #cmakedefine VTKEdge_BUILD_VolumeRendering_KIT #cmakedefine VTKEdge_BUILD_Widgets_KIT #cmakedefine VTKEdge_USE_CUDA #cmakedefine VTKEdge_USE_DIRECTX #cmakedefine VTKEdge_USE_CORE_GRAPHICS #cmakedefine VTKEdge_USE_NVCONTROL // The VTK_VERSION_DATE. The widgets have code so as to deal with changes // in VTK both before and after the Depth peeling compatibility changes. #cmakedefine VTKEdge_VTK_VERSION_DATE ${VTKEdge_VTK_VERSION_DATE} // Define @PROJECT_NAME@_SHARED if the library was built shared. // Why are we doing that?? #if @VTKEdge_BUILD_SHARED_LIBS@ # define @PROJECT_NAME@_SHARED #endif //----------------------------------------------------------------------------- // export stuff //----------------------------------------------------------------------------- #if defined(WIN32) && defined(@PROJECT_NAME@_SHARED) #define VTKEdge_EXPORT __declspec( dllexport ) #else #define VTKEdge_EXPORT #endif //----------------------------------------------------------------------------- // export stuff for Common //----------------------------------------------------------------------------- // vtkKWECommon_EXPORTS is defined by cmake when building the shared // library vtkKWECommon. #if defined(WIN32) && defined(@PROJECT_NAME@_SHARED) #if defined(vtkKWECommon_EXPORTS) #define VTKEdge_COMMON_EXPORT __declspec( dllexport ) #else #define VTKEdge_COMMON_EXPORT __declspec( dllimport ) #endif #else #define VTKEdge_COMMON_EXPORT #endif //----------------------------------------------------------------------------- // export stuff for Filtering //----------------------------------------------------------------------------- // vtkKWEFiltering_EXPORTS is defined by cmake when building the shared // library vtkKWEFiltering. #if defined(WIN32) && defined(@PROJECT_NAME@_SHARED) #if defined(vtkKWEFiltering_EXPORTS) #define VTKEdge_FILTERING_EXPORT __declspec( dllexport ) #else #define VTKEdge_FILTERING_EXPORT __declspec( dllimport ) #endif #else #define VTKEdge_FILTERING_EXPORT #endif //----------------------------------------------------------------------------- // export stuff for Graphics //----------------------------------------------------------------------------- // vtkKWEGraphics_EXPORTS is defined by cmake when building the shared // library vtkKWEGraphics. #if defined(WIN32) && defined(@PROJECT_NAME@_SHARED) #if defined(vtkKWEGraphics_EXPORTS) #define VTKEdge_GRAPHICS_EXPORT __declspec( dllexport ) #else #define VTKEdge_GRAPHICS_EXPORT __declspec( dllimport ) #endif #else #define VTKEdge_GRAPHICS_EXPORT #endif //----------------------------------------------------------------------------- // export stuff for Hybrid //----------------------------------------------------------------------------- // vtkKWEHybrid_EXPORTS is defined by cmake when building the shared // library vtkKWEHybrid. #if defined(WIN32) && defined(@PROJECT_NAME@_SHARED) #if defined(vtkKWEHybrid_EXPORTS) #define VTKEdge_HYBRID_EXPORT __declspec( dllexport ) #else #define VTKEdge_HYBRID_EXPORT __declspec( dllimport ) #endif #else #define VTKEdge_HYBRID_EXPORT #endif //----------------------------------------------------------------------------- // export stuff for Imaging //----------------------------------------------------------------------------- // vtkKWEImaging_EXPORTS is defined by cmake when building the shared // library vtkKWEImaging. #if defined(WIN32) && defined(@PROJECT_NAME@_SHARED) #if defined(vtkKWEImaging_EXPORTS) #define VTKEdge_IMAGING_EXPORT __declspec( dllexport ) #else #define VTKEdge_IMAGING_EXPORT __declspec( dllimport ) #endif #else #define VTKEdge_IMAGING_EXPORT #endif //----------------------------------------------------------------------------- // export stuff for IO //----------------------------------------------------------------------------- // vtkKWEIO_EXPORTS is defined by cmake when building the shared // library vtkKWEIO. #if defined(WIN32) && defined(@PROJECT_NAME@_SHARED) #if defined(vtkKWEIO_EXPORTS) #define VTKEdge_IO_EXPORT __declspec( dllexport ) #else #define VTKEdge_IO_EXPORT __declspec( dllimport ) #endif #else #define VTKEdge_IO_EXPORT #endif //----------------------------------------------------------------------------- // export stuff for Rendering //----------------------------------------------------------------------------- // vtkKWERendering_EXPORTS is defined by cmake when building the shared // library vtkKWERendering. #if defined(WIN32) && defined(@PROJECT_NAME@_SHARED) #if defined(vtkKWERendering_EXPORTS) #define VTKEdge_RENDERING_EXPORT __declspec( dllexport ) #else #define VTKEdge_RENDERING_EXPORT __declspec( dllimport ) #endif #else #define VTKEdge_RENDERING_EXPORT #endif //----------------------------------------------------------------------------- // export stuff for VolumeRendering //----------------------------------------------------------------------------- // vtkKWEVolumeRendering_EXPORTS is defined by cmake when building the shared // library vtkKWEVolumeRendering. #if defined(WIN32) && defined(@PROJECT_NAME@_SHARED) #if defined(vtkKWEVolumeRendering_EXPORTS) #define VTKEdge_VOLUMERENDERING_EXPORT __declspec( dllexport ) #else #define VTKEdge_VOLUMERENDERING_EXPORT __declspec( dllimport ) #endif #else #define VTKEdge_VOLUMERENDERING_EXPORT #endif //----------------------------------------------------------------------------- // export stuff for Widgets //----------------------------------------------------------------------------- // vtkKWEWidgets_EXPORTS is defined by cmake when building the shared // library vtkKWEWidgets. #if defined(WIN32) && defined(@PROJECT_NAME@_SHARED) #if defined(vtkKWEWidgets_EXPORTS) #define VTKEdge_WIDGETS_EXPORT __declspec( dllexport ) #else #define VTKEdge_WIDGETS_EXPORT __declspec( dllimport ) #endif #else #define VTKEdge_WIDGETS_EXPORT #endif vtkedge-0.2.0~20110819/Imaging/0000755000175000017500000000000011630435006015411 5ustar mathieumathieuvtkedge-0.2.0~20110819/Imaging/vtkKWEImageFFT.cu0000644000175000017500000000231311050621736020422 0ustar mathieumathieu #include #include // Defined in vtkImageFourierFilter.h // We re-difine it here so nvcc can compile it. typedef struct{ float Real; float Imag; } vtkImageComplexf; extern "C" void ExecuteFft(vtkImageComplexf *in, vtkImageComplexf *out, int N) { if(N == 1) { *out++ = *in++; return; } //CUT_DEVICE_INIT(); int mem_size = sizeof(vtkImageComplexf) * N; // Allocate device memory for signal float2 * d_signal; CUDA_SAFE_CALL(cudaMalloc((void**)&d_signal, mem_size)); // Copy host memory to device CUDA_SAFE_CALL(cudaMemcpy(d_signal, in, mem_size, cudaMemcpyHostToDevice)); // CUFFT plan cufftHandle plan; CUFFT_SAFE_CALL(cufftPlan1d(&plan, N, CUFFT_C2C, 1)); // Transform signal CUFFT_SAFE_CALL(cufftExecC2C(plan, (cufftComplex *)d_signal, (cufftComplex *)d_signal, CUFFT_FORWARD)); // Check if kernel execution generated and error CUT_CHECK_ERROR("Kernel execution failed [ ComplexPointwiseMulAndScale ]"); // Copy device memory to host CUDA_SAFE_CALL(cudaMemcpy(out, d_signal, mem_size, cudaMemcpyDeviceToHost)); //Destroy CUFFT context CUFFT_SAFE_CALL(cufftDestroy(plan)); // cleanup memory CUDA_SAFE_CALL(cudaFree(d_signal)); }vtkedge-0.2.0~20110819/Imaging/vtkKWEImageFFT.cxx0000644000175000017500000002311211363410610020607 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEImageFFT.h" #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include vtkCxxRevisionMacro(vtkKWEImageFFT, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEImageFFT); // Description: // Complex number struct using floats as CUDA only supports // 32-bit floating point percision as of 08/12/2008. typedef struct{ float Real; float Imag; } vtkImageComplexf; // execution method found in vtkKWEImageFFT.cu extern "C" void ExecuteFft(vtkImageComplexf *in, vtkImageComplexf *out, int N); //---------------------------------------------------------------------------- // This extent of the components changes to real and imaginary values. int vtkKWEImageFFT::IterativeRequestInformation( vtkInformation* vtkNotUsed(input), vtkInformation* output) { vtkDataObject::SetPointDataActiveScalarInfo(output, VTK_DOUBLE, 2); return 1; } //---------------------------------------------------------------------------- void vtkKWEImageFFTInternalRequestUpdateExtent(int *inExt, int *outExt, int *wExt, int iteration) { memcpy(inExt, outExt, 6 * sizeof(int)); inExt[iteration*2] = wExt[iteration*2]; inExt[iteration*2 + 1] = wExt[iteration*2 + 1]; } //---------------------------------------------------------------------------- // This method tells the superclass that the whole input array is needed // to compute any output region. int vtkKWEImageFFT::IterativeRequestUpdateExtent( vtkInformation* input, vtkInformation* output) { int *outExt = output->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT()); int *wExt = input->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()); int inExt[6]; vtkKWEImageFFTInternalRequestUpdateExtent(inExt,outExt,wExt,this->Iteration); input->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),inExt,6); return 1; } //---------------------------------------------------------------------------- // This templated execute method handles any type input, but the output // is always doubles. template void vtkKWEImageFFTExecute(vtkKWEImageFFT *self, vtkImageData *inData, int inExt[6], T *inPtr, vtkImageData *outData, int outExt[6], double *outPtr, int id) { vtkImageComplexf *inComplex; vtkImageComplexf *outComplex; vtkImageComplexf *pComplex; // int inMin0, inMax0; vtkIdType inInc0, inInc1, inInc2; T *inPtr0, *inPtr1, *inPtr2; // int outMin0, outMax0, outMin1, outMax1, outMin2, outMax2; vtkIdType outInc0, outInc1, outInc2; double *outPtr0, *outPtr1, *outPtr2; // int idx0, idx1, idx2, inSize0, numberOfComponents; unsigned long count = 0; unsigned long target; double startProgress; startProgress = self->GetIteration()/static_cast(self->GetNumberOfIterations()); // Reorder axes (The outs here are just placeholdes self->PermuteExtent(inExt, inMin0, inMax0, outMin1,outMax1,outMin2,outMax2); self->PermuteExtent(outExt, outMin0,outMax0,outMin1,outMax1,outMin2,outMax2); self->PermuteIncrements(inData->GetIncrements(), inInc0, inInc1, inInc2); self->PermuteIncrements(outData->GetIncrements(), outInc0, outInc1, outInc2); inSize0 = inMax0 - inMin0 + 1; // Input has to have real components at least. numberOfComponents = inData->GetNumberOfScalarComponents(); if (numberOfComponents < 1) { vtkGenericWarningMacro("No real components"); return; } // Allocate the arrays of complex numbers inComplex = new vtkImageComplexf[inSize0]; outComplex = new vtkImageComplexf[inSize0]; target = static_cast((outMax2-outMin2+1)*(outMax1-outMin1+1) * self->GetNumberOfIterations() / 50.0); target++; // loop over other axes inPtr2 = inPtr; outPtr2 = outPtr; for (idx2 = outMin2; idx2 <= outMax2; ++idx2) { inPtr1 = inPtr2; outPtr1 = outPtr2; for (idx1 = outMin1; !self->AbortExecute && idx1 <= outMax1; ++idx1) { if (!id) { if (!(count%target)) { self->UpdateProgress(count/(50.0*target) + startProgress); } count++; } // copy into complex numbers inPtr0 = inPtr1; pComplex = inComplex; for (idx0 = inMin0; idx0 <= inMax0; ++idx0) { pComplex->Real = static_cast(*inPtr0); pComplex->Imag = 0.0; if (numberOfComponents > 1) { // yes we have an imaginary input pComplex->Imag = static_cast(inPtr0[1]);; } inPtr0 += inInc0; ++pComplex; } // Call the method that performs the fft ::ExecuteFft(inComplex, outComplex, inSize0); // copy into output outPtr0 = outPtr1; pComplex = outComplex + (outMin0 - inMin0); for (idx0 = outMin0; idx0 <= outMax0; ++idx0) { *outPtr0 = static_cast(pComplex->Real); outPtr0[1] = static_cast(pComplex->Imag); outPtr0 += outInc0; ++pComplex; } inPtr1 += inInc1; outPtr1 += outInc1; } inPtr2 += inInc2; outPtr2 += outInc2; } delete [] inComplex; delete [] outComplex; } //---------------------------------------------------------------------------- // This method is passed input and output Datas, and executes the fft // algorithm to fill the output from the input. // Not threaded yet. void vtkKWEImageFFT::ThreadedExecute(vtkImageData *inData, vtkImageData *outData, int outExt[6], int threadId) { void *inPtr, *outPtr; int inExt[6]; int *wExt = inData->GetWholeExtent(); vtkKWEImageFFTInternalRequestUpdateExtent(inExt,outExt,wExt,this->Iteration); inPtr = inData->GetScalarPointerForExtent(inExt); outPtr = outData->GetScalarPointerForExtent(outExt); // this filter expects that the output be doubles. if (outData->GetScalarType() != VTK_DOUBLE) { vtkErrorMacro(<< "Execute: Output must be be type double."); return; } // this filter expects input to have 1 or two components if (outData->GetNumberOfScalarComponents() != 1 && outData->GetNumberOfScalarComponents() != 2) { vtkErrorMacro(<< "Execute: Cannot handle more than 2 components"); return; } // choose which templated function to call. switch (inData->GetScalarType()) { vtkTemplateMacro(vtkKWEImageFFTExecute(this, inData, inExt, static_cast(inPtr), outData, outExt, static_cast(outPtr), threadId)); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } //---------------------------------------------------------------------------- // For streaming and threads. Splits output update extent into num pieces. // This method needs to be called num times. Results must not overlap for // consistent starting extent. Subclass can override this method. // This method returns the number of peices resulting from a successful split. // This can be from 1 to "total". // If 1 is returned, the extent cannot be split. int vtkKWEImageFFT::SplitExtent(int splitExt[6], int startExt[6], int num, int total) { int splitAxis; int min, max; vtkDebugMacro("SplitExtent: ( " << startExt[0] << ", " << startExt[1] << ", " << startExt[2] << ", " << startExt[3] << ", " << startExt[4] << ", " << startExt[5] << "), " << num << " of " << total); // start with same extent memcpy(splitExt, startExt, 6 * sizeof(int)); splitAxis = 2; min = startExt[4]; max = startExt[5]; while ((splitAxis == this->Iteration) || (min == max)) { splitAxis--; if (splitAxis < 0) { // cannot split vtkDebugMacro(" Cannot Split"); return 1; } min = startExt[splitAxis*2]; max = startExt[splitAxis*2+1]; } // determine the actual number of pieces that will be generated if ((max - min + 1) < total) { total = max - min + 1; } if (num >= total) { vtkDebugMacro(" SplitRequest (" << num << ") larger than total: " << total); return total; } // determine the extent of the piece splitExt[splitAxis*2] = min + (max - min + 1)*num/total; if (num == total - 1) { splitExt[splitAxis*2+1] = max; } else { splitExt[splitAxis*2+1] = (min-1) + (max - min + 1)*(num+1)/total; } vtkDebugMacro(" Split Piece: ( " <NumberOfThreads = 1; } ~vtkKWEImageFFT() {}; virtual int IterativeRequestInformation(vtkInformation* in, vtkInformation* out); virtual int IterativeRequestUpdateExtent(vtkInformation* in, vtkInformation* out); void ThreadedExecute(vtkImageData *inData, vtkImageData *outData, int outExt[6], int threadId); // Description: // CUDA is only threadsafe accross multiple devices. // This method raises a vtkError if called. virtual void SetNumberOfThreads(int _arg); private: vtkKWEImageFFT(const vtkKWEImageFFT&); // Not implemented. void operator=(const vtkKWEImageFFT&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Imaging/CMakeLists.txt0000644000175000017500000000663211363410610020155 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Set of basic source files (not the OpenGL, GLSL or CUDA ones) # ----------------------------------------------------------------------------- set(KIT_SRCS vtkKWEImageFDKFilter.cxx ) # ----------------------------------------------------------------------------- # Set of source files that call Cuda # ----------------------------------------------------------------------------- if(CUDA_FOUND AND CUDA_CUTIL_FOUND) set(KIT_CUDA_DEPENDANT_SRCS vtkKWEImageFFT.cxx vtkKWEImageRFFT.cxx ) set(KIT_CUDA_SOURCES vtkKWEImageFFT.cu vtkKWEImageRFFT.cu ) include_directories( ${CUDA_INCLUDE_DIR} ${CUDA_CUTIL_INCLUDE_DIR} ) cuda_compile(KIT_CUDA_C_SOURCES ${KIT_CUDA_SOURCES}) endif(CUDA_FOUND AND CUDA_CUTIL_FOUND) # ----------------------------------------------------------------------------- # List the kits from VTK that are needed by this project # ----------------------------------------------------------------------------- set(KIT_LIBS vtkIO vtkImaging vtkRendering vtkVolumeRendering ) # ----------------------------------------------------------------------------- # Create the library # ----------------------------------------------------------------------------- if(KIT_CUDA_C_SOURCES OR KIT_SRCS OR KIT_CUDA_DEPENDANT_SRCS) add_library(vtkKWEImaging ${KIT_CUDA_C_SOURCES} ${KIT_SRCS} ${KIT_CUDA_DEPENDANT_SRCS}) target_link_libraries(vtkKWEImaging ${KIT_LIBS} ${CUDA_LIBRARIES} ${CUDA_CUTIL_LIBRARY}) endif(KIT_CUDA_C_SOURCES OR KIT_SRCS OR KIT_CUDA_DEPENDANT_SRCS) # ----------------------------------------------------------------------------- # Testing # ----------------------------------------------------------------------------- if(BUILD_TESTING) add_subdirectory(Testing) endif(BUILD_TESTING) # ----------------------------------------------------------------------------- # Installation # ----------------------------------------------------------------------------- if(NOT VTKEdge_INSTALL_NO_LIBRARIES) install_targets( ${VTKEdge_INSTALL_LIB_DIR} RUNTIME_DIRECTORY ${VTKEdge_INSTALL_BIN_DIR} vtkKWEImaging ) endif(NOT VTKEdge_INSTALL_NO_LIBRARIES) if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_INCLUDE_DIR} .h ${KIT_SRCS}) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) # ----------------------------------------------------------------------------- # This make it easy for other projects to get the list of files etc. in this # kit. # ----------------------------------------------------------------------------- include(${VTK_CMAKE_DIR}/vtkExportKit.cmake) vtk_export_kit2("KWEImaging" "KWEImaging" ${CMAKE_CURRENT_BINARY_DIR} "${KIT_SRCS}") vtkedge-0.2.0~20110819/Imaging/vtkKWEImageFDKFilter.cxx0000644000175000017500000003421711363410610021752 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEImageFDKFilter.h" #include "vtkDoubleArray.h" #include "vtkExecutive.h" #include "vtkFastNumericConversion.h" #include "vtkImageData.h" #include "vtkImageExtractComponents.h" #include "vtkImageFFT.h" #include "vtkImageFourierFilter.h" #include "vtkImageMathematics.h" #include "vtkImageRFFT.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMath.h" #include "vtkMultiThreader.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkTimerLog.h" #include #include #include vtkCxxRevisionMacro(vtkKWEImageFDKFilter, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEImageFDKFilter); //---------------------------------------------------------------------------- vtkKWEImageFDKFilter::vtkKWEImageFDKFilter() { this->WeightFunction = vtkImageData::New(); this->Radius = 1.0; this->Angles = vtkDoubleArray::New(); this->Angles->SetNumberOfComponents(1); } //---------------------------------------------------------------------------- vtkKWEImageFDKFilter::~vtkKWEImageFDKFilter() { this->WeightFunction->Delete(); this->Angles->Delete(); } //---------------------------------------------------------------------------- void vtkKWEImageFDKFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } int vtkKWEImageFDKFilter::RequestData(vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // Get the information object. vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // Get the data objects. vtkImageData * inData = vtkImageData::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkImageData * outData = vtkImageData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); //void *inPtr1; //void *inPtr2; float *outPtr; //int *tExt; int inExt[6], outExt[6] = {0, 128, 0, 128, 0 , 128}; inData->GetExtent(inExt); outData->GetExtent(outExt); vtkImageData * inImage = inData; //inPtr1 = inData->GetScalarPointerForExtent(outExt); // this filter expects that input is the same type as output. if (inData->GetScalarType() != outData->GetScalarType()) { vtkErrorMacro("Execute: input ScalarType, " << inData->GetScalarType() << ", must match out ScalarType " << outData->GetScalarType()); return 0; } // make the temporary regions to iterate over. /* vtkImageData *in = vtkImageData::New(); in->SetExtent(inExt); in->SetNumberOfScalarComponents(inData[0][0]->GetNumberOfScalarComponents()); in->SetScalarType(VTK_DOUBLE); in->CopyAndCastFrom(inData[0][0],inExt);*/ vtkFastNumericConversion * numeric = vtkFastNumericConversion::New(); // N = 2*floor( nc_p /(2*sqrt(2)) ); % take the default value int N = static_cast(2 * floor( (187)/ (2*sqrt(2.0)))); int N2 = static_cast(ceil(N/2.0)); int volExt[6] = { 0, N, 0, N, 0, N }; vtkImageData *out = vtkImageData::New(); out->SetExtent(volExt); out->SetNumberOfScalarComponents( inData->GetNumberOfScalarComponents()); out->SetScalarType(VTK_FLOAT); out->AllocateScalars(); outData->SetExtent(volExt); outData->SetNumberOfScalarComponents( inData->GetNumberOfScalarComponents()); outData->SetScalarType(VTK_FLOAT); outData->AllocateScalars(); outPtr = static_cast(outData->GetScalarPointer()); for(int i = 0; i < N * N * N; i++) { *outPtr++ = 0.0; } float theta, x, y, z, s, t, ctrX, ctrY; int dimX, dimY, dimZ, u, u1, v, v1, outX, outY, outZ; dimX = inExt[1]-inExt[0] + 1; dimY = inExt[3]-inExt[2] + 1; dimZ = inExt[5]-inExt[4] + 1; outX = volExt[1]-volExt[0] + 1; outY = volExt[3]-volExt[2] + 1; outZ = volExt[5]-volExt[4] + 1; ctrX = static_cast(ceil(dimX/2.0)); ctrY = static_cast(ceil(dimY/2.0)); // Generate Weighting Function for the projections this->GenerateWeightingFunction(inExt); // Generate a vector filter int order = 1; while(order < dimX) { order <<= 1; } if(order < 64) { order = 64; } /*float ** H = NULL; H = new float*[6]; for(int i = 0; i < 6; i++) { H[i] = new float[order]; }*/ float * H = new float[order]; this->GenerateFilter(H,order); vtkImageMathematics * math = vtkImageMathematics::New(); math->SetOperationToMultiply(); vtkImageData * tempSlice = vtkImageData::New(); tempSlice->SetNumberOfScalarComponents(1); tempSlice->SetScalarTypeToFloat(); tempSlice->SetDimensions(order, 6, 1); tempSlice->Update(); vtkImageFFT * fft = vtkImageFFT::New(); vtkImageRFFT * ifft = vtkImageRFFT::New(); //vtkStreamingDemandDrivenPipeline * fftPipe = // vtkStreamingDemandDrivenPipeline::SafeDownCast(fft->GetExecutive()); //vtkStreamingDemandDrivenPipeline * ifftPipe = // vtkStreamingDemandDrivenPipeline::SafeDownCast(ifft->GetExecutive()); vtkImageData * fftOutput = NULL; int fftExt[6] = {0, order, 0, dimY - 1, 0, dimZ - 1}; //int ifftExt[6] = {0, order, 0, dimY - 1, 0, dimZ - 1}; int projIdx = 0; float projValue = 0.0; float cosTheta = 0.0; float sinTheta = 0.0; float Radius2 = 0.0; float * fftPtr = NULL; float * ifftPtr = NULL; //float * volPtr = NULL; vtkTimerLog * timer = vtkTimerLog::New(); timer->StartTimer(); // Main execution loop for(int i = 0; i < 360; i++) { // for each row of tempRowS // Mutiply Projection by Weight this->ApplyWeightingFunction(64, i, inImage, tempSlice); fft->SetInput(tempSlice); fft->Update(); fftOutput = fft->GetOutput(); fftPtr = static_cast(fft->GetOutput()->GetScalarPointer()); fftOutput->GetExtent(fftExt); // Filter each Projection row with H for(int j = 0; j < 6; j++) { // Multiply by Filter H. for(int k = 0; k < order; k++) { // We must multiply both real and imaginary parts. //*fftPtr++ *= H[k]; //*fftPtr++ *= H[k]; //fftPtr++; //fftPtr++; } } ifft->SetInput(fftOutput); // Inverse transform back to spatial domain. ifft->Update(); theta = static_cast(this->Angles->GetTuple1(i)); ifftPtr = static_cast(ifft->GetOutput()->GetScalarPointer()); vtkImageExtractComponents * real = vtkImageExtractComponents::New(); real->SetInput(ifft->GetOutput()); real->SetComponents(0); real->Update(); // reset pointer outPtr = static_cast(outData->GetScalarPointer()); cosTheta = cosf(theta); sinTheta = sinf(theta); for(x = static_cast(-N2 + 1); x < N2; x++) { for(y = static_cast(-N2 + 1); y < N2; y++) { s = x * cosTheta + y * sinTheta; t = -x * sinTheta + y * cosTheta; Radius2 = this->Radius - s; //u is the 1st projection pixel coordinate u = numeric->Round(this->Radius * t/Radius2 + ctrX); //fileOut << u << endl; if(u <= 0 ||u >= (dimX+1)) { // this u is outside the projection, skip //cout << "u: " << u << endl; //outPtr++; continue; } for(z = static_cast(-N2); z < 1; z++) { //v = int(this->Radius/Radius2 * z) + ctrY; v = numeric->Round(this->Radius/Radius2 * z + 3); /* v1=round( v0+nr_p/2 ) ; % coord. correction idx = id_1_term + v1 ; % idx = sub2ind(szproj,u1, v1); tmp = proj(idx); % just in case tmp = tmp(:).*inv_R_s_quad; % back-projection ... from pixels to voxels ...! tmp1(good_u)=tmp; tmp1(lengoodu)=0;% tmp2(maskV)=tmp1; % prepare for image reconst. within the mask iposz=iposz_v(iz); % position of the current slice iz in the volume at iposz vol_tmp(:,iposz)=vol_tmp(:,iposz)+tmp2; % sum up back-projections without reshaping */ projIdx = (u - 1) * 6 + v; u1 = projIdx / order; v1 = projIdx - (u1 * order); u1 = 0; v1 = 0; //if(v > 0 && v < dimY) //if(y + N2 - 1 < dimY) { //cout << "x: " << x << "y: " << y << "v: " << v << endl; //projValue = *static_cast(ifft->GetOutput()->GetScalarPointer(u, v, 0)); //projValue = *static_cast(tempSlice->GetScalarPointer(u, v + ctrY, 0)); projValue = *static_cast(tempSlice->GetScalarPointer(u1,v1,0)); //projValue = *static_cast(inImage->GetScalarPointer(x + N2 - 1, y + N2 - 1, 0)); //if(projValue > std::numeric_limits::min() && projValue < std::numeric_limits::max()) { *outPtr++ += projValue /(Radius2 * Radius2); //cout << projValue << " "; } } } } } //fileOut.close(); cout << "Projection " << i << " complete." << endl; } timer->StopTimer(); cout << "Execution took " << timer->GetElapsedTime() << " seconds." << endl; numeric->Delete(); out->Delete(); math->Delete(); ifft->Delete(); fft->Delete(); tempSlice->Delete(); timer->Delete(); delete [] H; return 1; } //---------------------------------------------------------------------------- // The output extent is the intersection. int vtkKWEImageFDKFilter::RequestInformation ( vtkInformation * vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); int extent[6]; inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent); //this->ComputeOutputWholeExtent(extent, this->HandleBoundaries); outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent, 6); return 1; } void vtkKWEImageFDKFilter::GenerateWeightingFunction(int projExt[6]) { int dimX, dimY; dimX = projExt[1]-projExt[0] + 1; dimY = projExt[3]-projExt[2] + 1; this->WeightFunction->SetNumberOfScalarComponents(1); this->WeightFunction->SetScalarTypeToDouble(); this->WeightFunction->SetDimensions(dimX, dimY, 1); this->WeightFunction->Update(); /*vtkImageData *in = vtkImageData::New(); in->SetExtent(inExt); in->SetNumberOfScalarComponents(inData[0][0]->GetNumberOfScalarComponents()); in->SetScalarType(VTK_DOUBLE); in->CopyAndCastFrom(inData[0][0],inExt);*/ float * weightPtr = static_cast(this->WeightFunction->GetScalarPointer()); // Generate a Weighting function. // The projection weights the pixels about the origin of the projection // which is the center of the projection. //[X,Y]=meshgrid([[floor(8/2):-1:0],[1:(8-floor(8/2)-1)]],... //[[floor(8/2):-1:0],[1:(8-floor(8/2)-1)]]); //W=R.* ( (X.^2 + Y.^2 + R^2).^-0.5 ); int dim2X, dim2Y, p, zeta; dim2X = static_cast(floor(dimX/2.0)); dim2Y = static_cast(floor(dimY/2.0)); double d = this->Radius; double d2 = d * d; double numerator = 0.0; for(zeta = -dim2Y; zeta < dim2Y; zeta++) { for(p = -dim2X; p < dim2X; p++) { numerator = d2 + pow(static_cast(zeta), 2.0) + pow(static_cast(p), 2.0); *weightPtr = static_cast(d * pow(numerator,-0.5)); weightPtr++; } } } void vtkKWEImageFDKFilter::ApplyWeightingFunction( int row, int slice, vtkImageData * projection, vtkImageData * output) { int inExt[6], outExt[6]; projection->GetExtent(inExt); output->GetExtent(outExt); int dimY, x , y, padX0, padX1; dimY = outExt[3] + 1; padX0 = static_cast(floor((outExt[1] - (inExt[1] + 1))/2.0)); padX1 = outExt[1] - padX0; float * weightPtr = NULL; float * projPtr = NULL; //const char * type = projection->GetScalarTypeAsString(); float * outPtr = static_cast(output->GetScalarPointer()); // Apply weight and also insert padding for FFT for(y = 0; y < dimY; y++) { weightPtr = static_cast(this->WeightFunction->GetScalarPointer(0, row, 0)); projPtr = static_cast(projection->GetScalarPointer(0, row, slice)); for(x = 0; x < padX0; x++) { *outPtr++ = 0.0; } for(x = padX0; x < padX1; x++) { //*outPtr++ = *weightPtr++ * *projPtr++; *outPtr++ = *projPtr++; } for(x = padX1; x < outExt[1] + 1; x++) { *outPtr++ = 0.0; } } } void vtkKWEImageFDKFilter::GenerateFilter(float * filter, int order) { //filt = 2*( 0:(order/2) )./order; //w = 2*pi*(0:size(filt,2)-1)/order; % frequency axis up to Nyquist //filt(w>pi*d) = 0; % Crop the frequency response //filt = [filt , filt(end-1:-1:2)]; % Symmetry of the filter int i = 0, ii = 0; int halfOrder = order/2; for(i = 0; i < halfOrder; i++) { filter[i] = static_cast(2 * i/order); } float * w = new float[halfOrder]; float PI = vtkMath::Pi(); // ramp up the frequency to Nyquist for(i = 0; i < halfOrder; i++) { w[i] = 2 * PI * static_cast(i/order); } // crop the frequency response for(i = 0; i < halfOrder; i++) { /*if(w[i] > PI * d) { filter[i] = 0; }*/ } // Filter is symetric, mirror it to fill the rest of the array for(i = halfOrder, ii = halfOrder - 1; i < order; i++, ii--) { filter[i] = filter[ii]; } delete [] w; } vtkedge-0.2.0~20110819/Imaging/Testing/0000755000175000017500000000000011630435006017026 5ustar mathieumathieuvtkedge-0.2.0~20110819/Imaging/Testing/Cxx/0000755000175000017500000000000011630435006017570 5ustar mathieumathieuvtkedge-0.2.0~20110819/Imaging/Testing/Cxx/TestKWEImageFFT.cxx0000644000175000017500000000533011363410610023103 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkActor.h" #include "vtkCamera.h" #include "vtkImageExtractComponents.h" #include "vtkImageIdealHighPass.h" #include "vtkImageReader2.h" #include "vtkImageReader2Factory.h" #include "vtkImageViewer2.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkTimerLog.h" #include "vtkKWEImageFFT.h" #include "vtkKWEImageRFFT.h" int TestKWEImageFFT(int argc, char *argv[]) { vtkImageReader2Factory * createReader = vtkImageReader2Factory::New(); char *fname= vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/fullhead15.png"); vtkImageReader2 * reader = createReader->CreateImageReader2(fname); reader->SetFileName(fname); delete[] fname; vtkKWEImageFFT * fft = vtkKWEImageFFT::New(); fft->SetInputConnection(reader->GetOutputPort()); vtkImageIdealHighPass * highPass = vtkImageIdealHighPass::New(); highPass->SetInputConnection(fft->GetOutputPort()); highPass->SetXCutOff(0.1); highPass->SetYCutOff(0.1); highPass->ReleaseDataFlagOff(); vtkKWEImageRFFT * rfft = vtkKWEImageRFFT::New(); rfft->SetInputConnection(highPass->GetOutputPort()); vtkImageExtractComponents * real = vtkImageExtractComponents::New(); real->SetInputConnection(rfft->GetOutputPort()); real->SetComponents(0); vtkImageViewer2 * viewer = vtkImageViewer2::New(); viewer->SetInputConnection(real->GetOutputPort()); viewer->SetColorWindow(500); viewer->SetColorLevel(0); vtkRenderWindowInteractor * iren = vtkRenderWindowInteractor::New(); viewer->SetupInteractor(iren); viewer->Render(); int retVal = vtkRegressionTestImage( viewer->GetRenderWindow() ); if (retVal == vtkRegressionTester::DO_INTERACTOR) { viewer->Render(); iren->Start(); retVal = vtkRegressionTester::PASSED; } createReader->Delete(); reader->Delete(); fft->Delete(); highPass->Delete(); rfft->Delete(); real->Delete(); iren->Delete(); viewer->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Imaging/Testing/Cxx/CMakeLists.txt0000644000175000017500000000575411363410610022340 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Name this kit - this will be used to form test executable names later # Then we'll add in tests with various data or kit dependencies to the # test executables # ----------------------------------------------------------------------------- set(KIT Imaging) set(TESTBASE ${PROJECT_NAME}${KIT}) # ----------------------------------------------------------------------------- # First, list all the tests that either use no data, or only data from the # VTKEdge data directory (which always exists since it is part of the # VTKEdge repository). These will go into one test executable. # ----------------------------------------------------------------------------- set(ImagingTests TestKWEImageFDK.cxx ) if(CUDA_FOUND AND CUDA_CUTIL_FOUND) set(CUDAImagingTests TestKWEImageFFT.cxx ) endif(CUDA_FOUND AND CUDA_CUTIL_FOUND) # add tests that require data from VTKData/Data if(VTK_DATA_ROOT) set(ImagingTestsWithVTKData ) if(CUDA_FOUND AND CUDA_CUTIL_FOUND) set(CUDAImagingTestsWithVTKData ) endif(CUDA_FOUND AND CUDA_CUTIL_FOUND) endif(VTK_DATA_ROOT) create_test_sourcelist(Tests ${TESTBASE}CxxTests.cxx ${ImagingTests} ${CUDAImagingTests} ${ImagingTestsWithVTKData} ${CUDAImagingTestsWithVTKData} EXTRA_INCLUDE vtkTestDriver.h ) add_executable(${TESTBASE}CxxTests ${Tests}) #install_targets(${VTKEdge_INSTALL_BIN_DIR} ${TESTBASE}CxxTests) target_link_libraries(${TESTBASE}CxxTests vtkKWEImaging) set(TestsToRun ${Tests}) remove(TestsToRun ${TESTBASE}CxxTests.cxx ${ImagingTestsWithVTKData}) # Add all the executables foreach(test ${TestsToRun}) get_filename_component(TName ${test} NAME_WE) add_test(${TName} ${CXX_TEST_PATH}/${TESTBASE}CxxTests ${TName} -D ${PROJECT_SOURCE_DIR}/Data -T ${PROJECT_BINARY_DIR}/Testing/Temporary -V ${PROJECT_SOURCE_DIR}/Data/Baseline/${KIT}/${TName}.png ) endforeach(test) if(VTK_DATA_ROOT) foreach(test ${MyTestsWithVTKData}) get_filename_component(TName ${test} NAME_WE) add_test(${TName} ${CXX_TEST_PATH}/${TESTBASE}CxxTests ${TName} -D ${VTK_DATA_ROOT} -T ${PROJECT_BINARY_DIR}/Testing/Temporary -V ${PROJECT_SOURCE_DIR}/Data/Baseline/${KIT}/${TName}.png ) endforeach(test) endif(VTK_DATA_ROOT) vtkedge-0.2.0~20110819/Imaging/Testing/Cxx/TestKWEImageFDK.cxx0000644000175000017500000001052011363410610023065 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkColorTransferFunction.h" #include "vtkDataSetSurfaceFilter.h" #include "vtkDoubleArray.h" #include "vtkImageData.h" #include "vtkImageShiftScale.h" #include "vtkImageViewer2.h" #include "vtkKWEImageFDKFilter.h" #include "vtkMath.h" #include "vtkMetaImageReader.h" #include "vtkPiecewiseFunction.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" #include "vtkVolume.h" #include "vtkVolumeProperty.h" #include "vtkVolumeRayCastMapper.h" #include "vtkVolumeRayCastCompositeFunction.h" #define VTK_CREATE(type, name) \ vtkSmartPointer name = vtkSmartPointer::New() #include int TestKWEImageFDK(int argc, char *argv[]) { int numImages = 360; vtkRenderWindowInteractor *iren=vtkRenderWindowInteractor::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); iren->SetRenderWindow(renWin); renWin->Delete(); vtkRenderer *renderer = vtkRenderer::New(); renWin->AddRenderer(renderer); char *fname= vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/SheppLoganProjections.mhd"); vtkMetaImageReader *reader = vtkMetaImageReader::New(); reader->SetFileName(fname); reader->Update(); delete[] fname; vtkKWEImageFDKFilter * FDKFilter = vtkKWEImageFDKFilter::New(); FDKFilter->SetInput(reader->GetOutput()); FDKFilter->SetRadius(150); vtkDoubleArray * angles = FDKFilter->GetAngles(); angles->SetNumberOfTuples(numImages); double PI = vtkMath::DoublePi(); angles->SetTuple1(0, 0.0); for(int i = 1; i < numImages; i++) { angles->SetTuple1(i, i*(2.0*PI)/numImages); } //FDKFilter->Update(); vtkImageShiftScale * scale = vtkImageShiftScale::New(); scale->SetInputConnection(reader->GetOutputPort()); scale->SetOutputScalarTypeToUnsignedChar(); vtkPiecewiseFunction * opacityTransferFunction = vtkPiecewiseFunction::New(); opacityTransferFunction->AddPoint(20, 0.0); opacityTransferFunction->AddPoint(255, 0.2); vtkColorTransferFunction * colorTransferFunction = vtkColorTransferFunction::New(); colorTransferFunction->AddRGBPoint(0.0, 0.0, 0.0, 0.0); colorTransferFunction->AddRGBPoint(10.0, 1.0, 0.0, 0.0); colorTransferFunction->AddRGBPoint(20.0, 0.0, 0.0, 1.0); colorTransferFunction->AddRGBPoint(30.0, 0.0, 1.0, 0.0); colorTransferFunction->AddRGBPoint(255.0, 0.0, 0.2, 0.0); vtkVolumeRayCastCompositeFunction * compositeFunction1 = vtkVolumeRayCastCompositeFunction::New(); vtkVolumeRayCastMapper * volumeMapper = vtkVolumeRayCastMapper::New(); vtkVolumeProperty * volumeProperty = vtkVolumeProperty::New(); volumeProperty->SetColor(colorTransferFunction); volumeProperty->SetScalarOpacity(opacityTransferFunction); volumeProperty->SetInterpolationTypeToLinear(); volumeProperty->ShadeOff(); volumeMapper->SetVolumeRayCastFunction(compositeFunction1); volumeMapper->SetInputConnection(scale->GetOutputPort()); vtkVolume * volume = vtkVolume::New(); volume->SetMapper(volumeMapper); volume->SetProperty(volumeProperty); renderer->AddVolume(volume); renderer->SetBackground(0.0,0.0,0.0); int retVal = vtkRegressionTestImage(renWin); if (retVal == vtkRegressionTester::DO_INTERACTOR) { renWin->Render(); iren->Start(); retVal = vtkRegressionTester::PASSED; } volumeProperty->Delete(); FDKFilter->Delete(); reader->Delete(); scale->Delete(); iren->Delete(); renderer->Delete(); volume->Delete(); compositeFunction1->Delete(); colorTransferFunction->Delete(); opacityTransferFunction->Delete(); volumeMapper->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Imaging/Testing/CMakeLists.txt0000644000175000017500000000166011363410610021566 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Add the Cxx testing directory # ----------------------------------------------------------------------------- add_subdirectory(Cxx) vtkedge-0.2.0~20110819/Imaging/vtkKWEImageRFFT.cu0000644000175000017500000000331611050621736020550 0ustar mathieumathieu #include #include // Defined in vtkImageFourierFilter.h // We re-difine it here so nvcc can compile it. typedef struct{ float Real; float Imag; } vtkImageComplexf; __global__ void Scale(float2 * in, int N, float scale) { const int numThreads = blockDim.x * gridDim.x; const int threadID = blockIdx.x * blockDim.x + threadIdx.x; for (int i = threadID; i < N; i += numThreads) { in[i].x *= scale; in[i].y *= scale; } } extern "C" void ExecuteRFft(vtkImageComplexf *in, vtkImageComplexf *out, int N) { // If a given dimenion is 1 we just copy input to output. (e.q. when // processing a 256 x 256 x 1 data set, we dont need to do a 3rd FFT // in the Z dimension) if(N == 1) { *out++ = *in++; return; } //CUT_DEVICE_INIT(); int mem_size = sizeof(vtkImageComplexf) * N; // Allocate device memory for signal float2 * d_signal; CUDA_SAFE_CALL(cudaMalloc((void**)&d_signal, mem_size)); // Copy host memory to device CUDA_SAFE_CALL(cudaMemcpy(d_signal, in, mem_size, cudaMemcpyHostToDevice)); // CUFFT plan cufftHandle plan; CUFFT_SAFE_CALL(cufftPlan1d(&plan, N, CUFFT_C2C, 1)); // Transform signal CUFFT_SAFE_CALL(cufftExecC2C(plan, (cufftComplex *)d_signal, (cufftComplex *)d_signal, CUFFT_INVERSE)); // Normalize the result Scale<<<32, N>>>(d_signal, N, 1.0f/N); // Check if kernel execution generated and error CUT_CHECK_ERROR("Kernel execution failed [ ComplexPointwiseMulAndScale ]"); // Copy device memory to host CUDA_SAFE_CALL(cudaMemcpy(out, d_signal, mem_size, cudaMemcpyDeviceToHost)); //Destroy CUFFT context CUFFT_SAFE_CALL(cufftDestroy(plan)); // cleanup memory CUDA_SAFE_CALL(cudaFree(d_signal)); }vtkedge-0.2.0~20110819/Imaging/vtkKWEImageFDKFilter.h0000644000175000017500000000521211363410610021370 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEImageFDKFilter - Generic filter that has N inputs. // .SECTION Description // vtkKWEImageFDKFilter is a super class for filters that // have any number of inputs. Streaming is not available in this class yet. // .SECTION See Also // vtkImageToImageFilter vtkImageInPlaceFilter vtkImageTwoInputFilter #ifndef __vtkKWEImageFDKFilter_h #define __vtkKWEImageFDKFilter_h #include "vtkImageAlgorithm.h" #include "VTKEdgeConfigure.h" // include configuration header class vtkDoubleArray; class VTKEdge_IMAGING_EXPORT vtkKWEImageFDKFilter : public vtkImageAlgorithm { public: static vtkKWEImageFDKFilter *New(); vtkTypeRevisionMacro(vtkKWEImageFDKFilter,vtkImageAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Distance from the detector to the center of // rotation of the source object. vtkSetMacro(Radius,float); vtkGetMacro(Radius,float); // Description: // Collection of the angles of each projection vtkGetObjectMacro(Angles, vtkDoubleArray); protected: vtkKWEImageFDKFilter(); ~vtkKWEImageFDKFilter(); float Radius; // Distance from the detector to the center of rotation of the source object vtkDoubleArray * Angles; virtual int RequestInformation (vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector); virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); void GenerateWeightingFunction(int projExt[6]); void ApplyWeightingFunction(int row, int slice, vtkImageData * projection, vtkImageData * output); void GenerateFilter(float * filter, int order); private: vtkKWEImageFDKFilter(const vtkKWEImageFDKFilter&); // Not implemented. void operator=(const vtkKWEImageFDKFilter&); // Not implemented. vtkImageData * WeightFunction; }; #endif vtkedge-0.2.0~20110819/Imaging/vtkKWEImageRFFT.cxx0000644000175000017500000002273511363410610020743 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEImageRFFT.h" #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include vtkCxxRevisionMacro(vtkKWEImageRFFT, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEImageRFFT); // Description: // Complex number struct using floats as CUDA only supports // 32-bit floating point percision as of 08/12/2008. typedef struct{ float Real; float Imag; } vtkImageComplexf; // execution method found in vtkKWEImageFFT.cu extern "C" void ExecuteRFft(vtkImageComplexf *in, vtkImageComplexf *out, int N); //---------------------------------------------------------------------------- // This extent of the components changes to real and imaginary values. int vtkKWEImageRFFT::IterativeRequestInformation( vtkInformation* vtkNotUsed(input), vtkInformation* output) { vtkDataObject::SetPointDataActiveScalarInfo(output, VTK_DOUBLE, 2); return 1; } void vtkKWEImageRFFTInternalRequestUpdateExtent(int *inExt, int *outExt, int *wExt, int iteration) { memcpy(inExt, outExt, 6 * sizeof(int)); inExt[iteration*2] = wExt[iteration*2]; inExt[iteration*2 + 1] = wExt[iteration*2 + 1]; } //---------------------------------------------------------------------------- // This method tells the superclass that the whole input array is needed // to compute any output region. int vtkKWEImageRFFT::IterativeRequestUpdateExtent( vtkInformation* input, vtkInformation* output) { int *outExt = output->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT()); int *wExt = input->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()); int inExt[6]; vtkKWEImageRFFTInternalRequestUpdateExtent(inExt,outExt,wExt,this->Iteration); input->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),inExt,6); return 1; } //---------------------------------------------------------------------------- // This templated execute method handles any type input, but the output // is always doubles. template void vtkKWEImageRFFTExecute(vtkKWEImageRFFT *self, vtkImageData *inData, int inExt[6], T *inPtr, vtkImageData *outData, int outExt[6], double *outPtr, int id) { vtkImageComplexf *inComplex; vtkImageComplexf *outComplex; vtkImageComplexf *pComplex; // int inMin0, inMax0; vtkIdType inInc0, inInc1, inInc2; T *inPtr0, *inPtr1, *inPtr2; // int outMin0, outMax0, outMin1, outMax1, outMin2, outMax2; vtkIdType outInc0, outInc1, outInc2; double *outPtr0, *outPtr1, *outPtr2; // int idx0, idx1, idx2, inSize0, numberOfComponents; unsigned long count = 0; unsigned long target; double startProgress; startProgress = self->GetIteration()/ static_cast(self->GetNumberOfIterations()); // Reorder axes (The outs here are just placeholdes self->PermuteExtent(inExt, inMin0, inMax0, outMin1,outMax1,outMin2,outMax2); self->PermuteExtent(outExt, outMin0,outMax0,outMin1,outMax1,outMin2,outMax2); self->PermuteIncrements(inData->GetIncrements(), inInc0, inInc1, inInc2); self->PermuteIncrements(outData->GetIncrements(), outInc0, outInc1, outInc2); inSize0 = inMax0 - inMin0 + 1; // Input has to have real components at least. numberOfComponents = inData->GetNumberOfScalarComponents(); if (numberOfComponents < 1) { vtkGenericWarningMacro("No real components"); return; } // Allocate the arrays of complex numbers inComplex = new vtkImageComplexf[inSize0]; outComplex = new vtkImageComplexf[inSize0]; target = static_cast((outMax2-outMin2+1)*(outMax1-outMin1+1) * self->GetNumberOfIterations() / 50.0); target++; // loop over other axes inPtr2 = inPtr; outPtr2 = outPtr; for (idx2 = outMin2; idx2 <= outMax2; ++idx2) { inPtr1 = inPtr2; outPtr1 = outPtr2; for (idx1 = outMin1; !self->AbortExecute && idx1 <= outMax1; ++idx1) { if (!id) { if (!(count%target)) { self->UpdateProgress(count/(50.0*target) + startProgress); } count++; } // copy into complex numbers inPtr0 = inPtr1; pComplex = inComplex; for (idx0 = inMin0; idx0 <= inMax0; ++idx0) { pComplex->Real = static_cast(*inPtr0); pComplex->Imag = 0.0; if (numberOfComponents > 1) { // yes we have an imaginary input pComplex->Imag = static_cast(inPtr0[1]);; } inPtr0 += inInc0; ++pComplex; } // Call the method that performs the RFFT ::ExecuteRFft(inComplex, outComplex, inSize0); // copy into output outPtr0 = outPtr1; pComplex = outComplex + (outMin0 - inMin0); for (idx0 = outMin0; idx0 <= outMax0; ++idx0) { *outPtr0 = static_cast(pComplex->Real); outPtr0[1] = static_cast(pComplex->Imag); outPtr0 += outInc0; ++pComplex; } inPtr1 += inInc1; outPtr1 += outInc1; } inPtr2 += inInc2; outPtr2 += outInc2; } delete [] inComplex; delete [] outComplex; } //---------------------------------------------------------------------------- // This method is passed input and output Datas, and executes the RFFT // algorithm to fill the output from the input. // Not threaded yet. void vtkKWEImageRFFT::ThreadedExecute(vtkImageData *inData, vtkImageData *outData, int outExt[6], int threadId) { void *inPtr, *outPtr; int inExt[6]; int *wExt = inData->GetWholeExtent(); vtkKWEImageRFFTInternalRequestUpdateExtent(inExt,outExt,wExt,this->Iteration); inPtr = inData->GetScalarPointerForExtent(inExt); outPtr = outData->GetScalarPointerForExtent(outExt); // this filter expects that the output be doubles. if (outData->GetScalarType() != VTK_DOUBLE) { vtkErrorMacro(<< "Execute: Output must be be type double."); return; } // this filter expects input to have 1 or two components if (outData->GetNumberOfScalarComponents() != 1 && outData->GetNumberOfScalarComponents() != 2) { vtkErrorMacro(<< "Execute: Cannot handle more than 2 components"); return; } // choose which templated function to call. switch (inData->GetScalarType()) { vtkTemplateMacro( vtkKWEImageRFFTExecute(this, inData, inExt, static_cast(inPtr), outData, outExt, static_cast(outPtr), threadId)); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } //---------------------------------------------------------------------------- // For streaming and threads. Splits output update extent into num pieces. // This method needs to be called num times. Results must not overlap for // consistent starting extent. Subclass can override this method. // This method returns the number of peices resulting from a successful split. // This can be from 1 to "total". // If 1 is returned, the extent cannot be split. int vtkKWEImageRFFT::SplitExtent(int splitExt[6], int startExt[6], int num, int total) { int splitAxis; int min, max; vtkDebugMacro("SplitExtent: ( " << startExt[0] << ", " << startExt[1] << ", " << startExt[2] << ", " << startExt[3] << ", " << startExt[4] << ", " << startExt[5] << "), " << num << " of " << total); // start with same extent memcpy(splitExt, startExt, 6 * sizeof(int)); splitAxis = 2; min = startExt[4]; max = startExt[5]; while ((splitAxis == this->Iteration) || (min == max)) { splitAxis--; if (splitAxis < 0) { // cannot split vtkDebugMacro(" Cannot Split"); return 1; } min = startExt[splitAxis*2]; max = startExt[splitAxis*2+1]; } // determine the actual number of pieces that will be generated if ((max - min + 1) < total) { total = max - min + 1; } if (num >= total) { vtkDebugMacro(" SplitRequest (" << num << ") larger than total: " << total); return total; } // determine the extent of the piece splitExt[splitAxis*2] = min + (max - min + 1)*num/total; if (num == total - 1) { splitExt[splitAxis*2+1] = max; } else { splitExt[splitAxis*2+1] = (min-1) + (max - min + 1)*(num+1)/total; } vtkDebugMacro(" Split Piece: ( " <NumberOfThreads = 1; } ~vtkKWEImageRFFT() {}; virtual int IterativeRequestInformation(vtkInformation* in, vtkInformation* out); virtual int IterativeRequestUpdateExtent(vtkInformation* in, vtkInformation* out); void ThreadedExecute(vtkImageData *inData, vtkImageData *outData, int outExt[6], int threadId); private: vtkKWEImageRFFT(const vtkKWEImageRFFT&); // Not implemented. void operator=(const vtkKWEImageRFFT&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/CMake/0000755000175000017500000000000011630434663015026 5ustar mathieumathieuvtkedge-0.2.0~20110819/CMake/FindUUID.cmake0000644000175000017500000000357011363410610017371 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # - Find UUID # Find the native UUID includes and library # This module defines # UUID_INCLUDE_DIR, where to find jpeglib.h, etc. # UUID_LIBRARIES, the libraries needed to use UUID. # UUID_FOUND, If false, do not try to use UUID. # also defined, but not for general use are # UUID_LIBRARY, where to find the UUID library. FIND_PATH(UUID_INCLUDE_DIR uuid/uuid.h /usr/local/include /usr/include ) FIND_LIBRARY(UUID_LIBRARY NAMES uuid PATHS /lib /usr/lib /usr/local/lib ) IF (UUID_LIBRARY AND UUID_INCLUDE_DIR) SET(UUID_LIBRARIES ${UUID_LIBRARY}) SET(UUID_FOUND "YES") ELSE (UUID_LIBRARY AND UUID_INCLUDE_DIR) SET(UUID_FOUND "NO") ENDIF (UUID_LIBRARY AND UUID_INCLUDE_DIR) IF (UUID_FOUND) IF (NOT UUID_FIND_QUIETLY) MESSAGE(STATUS "Found UUID: ${UUID_LIBRARIES}") ENDIF (NOT UUID_FIND_QUIETLY) ELSE (UUID_FOUND) IF (UUID_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find UUID library") ENDIF (UUID_FIND_REQUIRED) ENDIF (UUID_FOUND) # Deprecated declarations. #SET (NATIVE_UUID_INCLUDE_PATH ${UUID_INCLUDE_DIR} ) #GET_FILENAME_COMPONENT (NATIVE_UUID_LIB_PATH ${UUID_LIBRARY} PATH) MARK_AS_ADVANCED( UUID_LIBRARY UUID_INCLUDE_DIR ) vtkedge-0.2.0~20110819/CMake/FindCuda.cmake0000644000175000017500000001105611363410610017475 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= #========================================================================= # Module to locate NVIDIA's CUDA Toolkit and SDK. # # Basic variables # CUDA_FOUND - True if Cuda runtime library/compiler were found. # CUDA_CUTIL_FOUND - True if Cuda SDK was found. # CUDA_LIBRARIES - Libraries to link against to use Cuda. # CUDA_CUTIL_LIBRARIES - Libraries to link agains to use cutil. # CUDA_INCLUDE_DIR - Include dir for Cuda run time. # CUDA_CUTIL_INCLUDE_DIR - Include dir for cutil. # Additional variables # CUDA_COMPILER - the cuda nvcc compiler. # CUDA_DEVICE_EMULATION - Set this to True to use emulation. # Macro to convert a *.cu file to *.c file that can be compiled by the C # compiler. # CUDA_COMPILE(outfiles inputfiles ... ) FIND_PACKAGE(OpenGL) SET(CUDA_FOUND FALSE) SET(CUDA_CUTIL_FOUND FALSE) ## Find Cuda toolkit. FIND_PROGRAM(CUDA_COMPILER NAMES "nvcc" PATHS "/usr/local/cuda/bin" "C:/CUDA/bin" DOC "Path to the Cuda compiler (nvcc)" ) FIND_LIBRARY(CUDA_RT_LIBRARY cudart "/usr/local/cuda/lib" "C:/CUDA/lib" DOC "Path to Cuda runtime library (cudart)") FIND_LIBRARY(CUDA_FFT_LIBRARY cufft "/usr/local/cuda/lib" "C:/CUDA/lib" DOC "Path to Cuda FFT library (cufft)") FIND_PATH(CUDA_INCLUDE_DIR cuda.h "/usr/local/cuda/include" "C:/CUDA/include" DOC "Path to Cuda headers (cuda.h)") IF (CUDA_COMPILER AND CUDA_RT_LIBRARY AND CUDA_INCLUDE_DIR) SET (CUDA_FOUND TRUE) ELSE (CUDA_COMPILER AND CUDA_RT_LIBRARY AND CUDA_INCLUDE_DIR) SET (CUDA_FOUND FALSE) ENDIF (CUDA_COMPILER AND CUDA_RT_LIBRARY AND CUDA_INCLUDE_DIR) SET (CUDA_LIBRARIES CACHE INTERNAL "Libraries to link against Cuda.") IF (CUDA_FOUND) SET (CUDA_LIBRARIES ${CUDA_RT_LIBRARY} ${CUDA_FFT_LIBRARY}) ENDIF (CUDA_FOUND) SET (CUDA_DEVICE_EMULATION OFF CACHE BOOL "Use device enumlation for Cuda") MARK_AS_ADVANCED(CUDA_COMPILER CUDA_RT_LIBRARY CUDA_FFT_LIBRARY CUDA_INCLUDE_DIR CUDA_DEVICE_EMULATION) ## Find Cuda SDK. FIND_LIBRARY(CUDA_CUTIL_LIBRARY NAMES cutil64.lib cutil32.lib cutil PATHS "C:/Program Files (x86)/NVIDIA Corporation/NVIDIA CUDA SDK/common/lib/" "C:/Program Files/NVIDIA Corporation/NVIDIA CUDA SDK/common/lib" DOC "Path to Cuda SDK libraries (cutil)") FIND_PATH(CUDA_CUTIL_INCLUDE_DIR cutil.h "C:/Program Files (x86)/NVIDIA Corporation/NVIDIA CUDA SDK/common/inc" "C:/Program Files/NVIDIA Corporation/NVIDIA CUDA SDK/common/inc" DOC "Path to Cuda SDK include directory (cutil.h)") IF (CUDA_CUTIL_LIBRARY AND CUDA_CUTIL_INCLUDE_DIR) SET (CUDA_CUTIL_FOUND TRUE) ELSE (CUDA_CUTIL_LIBRARY AND CUDA_CUTIL_INCLUDE_DIR) SET (CUDA_CUTIL_FOUND FALSE) ENDIF (CUDA_CUTIL_LIBRARY AND CUDA_CUTIL_INCLUDE_DIR) MARK_AS_ADVANCED(CUDA_CUTIL_LIBRARY CUDA_CUTIL_INCLUDE_DIR) SET (CUDA_CUTIL_LIBRARIES CACHE INTERNAL "Libraries to link agains Cuda cutil.") IF (CUDA_CUTIL_FOUND) SET (CUDA_CUTIL_LIBRARIES ${CUDA_LIBRARIES} ${CUDA_CUTIL_LIBRARY}) ENDIF (CUDA_CUTIL_FOUND) MACRO (CUDA_COMPILE outfiles) IF (WIN32) SET (extra_args "-ccbin \"$(VCInstallDir)bin\" ") ENDIF (WIN32) IF (CUDA_DEVICE_EMULATION) SET (extra_args "${extra_args} --device-emulation") ENDIF (CUDA_DEVICE_EMULATION) # Get the directories to pass as include directories. GET_DIRECTORY_PROPERTY(include_dirs INCLUDE_DIRECTORIES) FOREACH (iter ${include_dirs}) SET (extra_args ${extra_args} -I ${iter}) ENDFOREACH (iter) FOREACH (iter ${ARGN}) GET_FILENAME_COMPONENT(filename ${iter} NAME) SET (outfile ${CMAKE_CURRENT_BINARY_DIR}/${filename}.cxx) GET_FILENAME_COMPONENT(infile ${iter} ABSOLUTE) ADD_CUSTOM_COMMAND( OUTPUT ${outfile} COMMAND ${CUDA_COMPILER} ${extra_args} -o ${outfile} -cuda ${infile} DEPENDS ${iter} COMMENT "Processing CUDA file") SET (${outfiles} ${${outfiles}} ${outfile}) ENDFOREACH (iter) ENDMACRO (CUDA_COMPILE outfiles) vtkedge-0.2.0~20110819/CMake/CMakeLists.txt0000644000175000017500000000155511363410610017561 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_PACKAGE_DIR}/CMake "\\.cmake$") endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) vtkedge-0.2.0~20110819/CMake/CTestCustom.cmake.in0000644000175000017500000000241311363410610020637 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # see: http://www.cmake.org/Wiki/CMake_Testing_With_CTest#Customizing_CTest # Does not make sense to cover files like /Testing/Cxx/VTKEdgeCxxTests.cxx SET(CTEST_CUSTOM_COVERAGE_EXCLUDE "VTKEdge.*CxxTests.cxx") # Report up to 222 warnings to the dashboard. set(CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS 222) # Don't perform memcheck on tests that timeout or crash on GeForce6 (LIC) SET(CTEST_CUSTOM_MEMCHECK_IGNORE TestImageDataLIC2D TestStructuredGridLIC2DXSlice TestStructuredGridLIC2DYSlice TestStructuredGridLIC2DZSlice TestSurfaceLIC ) vtkedge-0.2.0~20110819/Utilities/0000755000175000017500000000000011630435006016011 5ustar mathieumathieuvtkedge-0.2.0~20110819/Utilities/Doxygen/0000755000175000017500000000000011630435006017426 5ustar mathieumathieuvtkedge-0.2.0~20110819/Utilities/Doxygen/paper-clip.gif0000644000175000017500000000012511052363605022152 0ustar mathieumathieuGIF89a ‘âââ]]]ÿÿÿ!ù, &”›ƒ’æ[iÀNÛ‡mè¢q’(¨ Ûc®÷.ÔÝ R;vtkedge-0.2.0~20110819/Utilities/Doxygen/doc_makeall.sh.in0000644000175000017500000003136611363410610022630 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ------------------------------------------------------------------------- # Doxygen documentation batch # modified by S. Barre (Time-stamp: <2005-06-17 15:12:59 barre> # ------------------------------------------------------------------------- # Path to several tools (_PROG to avoid the typical GZIP env var pb) # Example: # DOXYGEN_PROG=@DOXYGEN@ (INCLUDE(FindDoxygen.cmake)) # GZIP_PROG=@GZIP@ (INCLUDE(FindCygwin.cmake)) # HHC_PROG=@HTML_HELP_COMPILER@ (INCLUDE(FindHTMLHelp.cmake)) # MV_PROG=@MV@ (INCLUDE(FindCygwin.cmake)) # PERL_PROG=@PERL@ (INCLUDE(FindPerl.cmake)) # RM_PROG=@RM@ (INCLUDE(FindCygwin.cmake)) # TAR_PROG=@TAR@ (INCLUDE(FindCygwin.cmake)) # WGET_PROG=@WGET@ (INCLUDE(FindWget.cmake)) # export DOXYGEN_PROG="@DOXYGEN@" # Doxygen export GZIP_PROG="@GZIP@" # gzip (Unix-like 'gzip compressor') export GNUPLOT_PROG="@GNUPLOT@" # gnuplot (data plotting program) export HHC_PROG="@HTML_HELP_COMPILER@" # HTML Help Compiler export MV_PROG="@MV@" # mv (Unix-like 'move/rename files') export PERL_PROG="@PERL@" # Perl export RM_PROG="@RM@" # rm (Unix-like 'remove files') export TAR_PROG="@TAR@" # tar (Unix-like 'archiver') export WGET_PROG="@WGET@" # wget (remote file retrieval) # PROJECT_NAME: # Documentation/project name. Used in some of the resulting file names and # xrefs to uniquify two or more projects linked together through their # Doxygen's tag files. Mandatory for each documentation set. # Note: might be the same as the doxyfile's PROJECT_NAME # Example: # PROJECT_NAME=VTK # export PROJECT_NAME=@DOXYGEN_PROJECT_NAME@ # PATH_TO_VTK_DOX_SCRIPTS: # Path to the directory holding the Perl scripts used to produce the VTK doc # in Doxygen format. You need the VTK source files or a local copy of # these scripts. # Example: # PATH_TO_VTK_DOX_SCRIPTS=@CMAKE_CURRENT_SOURCE_DIR@ # export PATH_TO_VTK_DOX_SCRIPTS="@DOXYGEN_SOURCE_DIR@" # SOURCE_DIR: # Source directory. The top directory of the source files. # Example: # SOURCE_DIR=@DOXYGEN_PROJECT_SOURCE_DIR@ # export SOURCE_DIR="@DOXYGEN_PROJECT_SOURCE_DIR@" # REL_PATH_TO_TOP: # Relative path from the top directory of the source files to the directory # (or top directory) holding the files to document. Useful if several parts # of the same source directory should be documented separately. # Example: # REL_PATH_TO_TOP=. # REL_PATH_TO_TOP=framework/src # export REL_PATH_TO_TOP=. # INTERMEDIATE_DOX_DIR: # Directory where the intermediate Doxygen files should be stored (mainly # these headers files converted from the VTK format to the Doxygen format). # This directory is erased at the end of this script, unless you comment # the corresponding line. # DOXTEMP might be used to simplify the syntax. # Example: # DOXTEMP=DOXTEMP=@CMAKE_CURRENT_BINARY_DIR@ # INTERMEDIATE_DOX_DIR=$DOXTEMP/dox # export DOXTEMP="@CMAKE_CURRENT_BINARY_DIR@" export INTERMEDIATE_DOX_DIR="$DOXTEMP/dox" # CVSWEB_CHECKOUT, CVSWEB_CHECKOUT_SUFFIX: # URL to the CVSWeb of the project, in checkout mode (i.e. appending a file # name to this URL will retrieve the contents of the file). In the same way # CVSWEB_CHECKOUT_SUFFIX is appended to the result. # Example: # CVSWEB_CHECKOUT=http://public.kitware.com/cgi-bin/cvsweb.cgi/~checkout~/VTK # CVSWEB_CHECKOUT_SUFFIX=?cvsroot=CMake # export CVSWEB_CHECKOUT="@DOXYGEN_CVSWEB_CHECKOUT@" export CVSWEB_CHECKOUT_SUFFIX="@DOXYGEN_CVSWEB_CHECKOUT_SUFFIX@" # DOXYFILE: # Path to the Doxygen configuration file (i.e. doxyfile). # Example: # DOXYFILE=$DOXTEMP/doxyfile # export DOXYFILE="$DOXTEMP/doxyfile" # OUTPUT_DIRECTORY ALLOW_ERASE_OUTPUT_DIRECTORY: # Path to the Doxygen output directory (where the resulting doc is stored). # Note: should be the same as your doxyfile's OUTPUT_DIRECTORY # If ON, allows the output directory to be erased when some advanced output # file have been produced (HTML Help, or TAR archive for example). # Example: # OUTPUT_DIRECTORY=$DOXTEMP/doc # ALLOW_ERASE_OUTPUT_DIRECTORY=ON # export OUTPUT_DIRECTORY="$DOXTEMP/doc" export ALLOW_ERASE_OUTPUT_DIRECTORY=ON # COMPILE_HTML_HELP RESULTING_HTML_HELP_FILE: # Compile the CHM (Compressed HTML) HTML Help file, name of the resulting # file. If set to ON and name is non-empty these options will actually # trigger the HTML-Help compiler to create the CHM. The resulting # file (usually index.chm) will be renamed to this name. # Note: if ON, the whole $OUTPUT_DIRECTORY will be erased at the end of # this script, since this file is considered to be one of the # advanced final output, unless ALLOW_ERASE_OUTPUT_DIRECTORY is OFF # Note: your doxyfile should be configured to enable HTML Help creation # (using GENERATE_HTML = YES, GENERATE_HTMLHELP = YES) # Example: # COMPILE_HTML_HELP=ON # COMPILE_HTML_HELP=@DOCUMENTATION_HTML_HELP@ # RESULTING_HTML_HELP_FILE=$DOXTEMP/vtk4.chm # export COMPILE_HTML_HELP=@DOCUMENTATION_HTML_HELP@ export RESULTING_HTML_HELP_FILE="$DOXTEMP/$PROJECT_NAME.chm" # CREATE_HTML_TARZ_ARCHIVE RESULTING_HTML_TARZ_ARCHIVE_FILE: # Create a compressed (gzip) tar archive of the html directory (located # under the OUTPUT_DIRECTORY), and name of the resulting archive file. # Note: your doxyfile should be configured to enable HTML creation # (using GENERATE_HTML = YES) # Example: # CREATE_HTML_TARZ_ARCHIVE=ON # CREATE_HTML_TARZ_ARCHIVE=@DOCUMENTATION_HTML_TARZ@ # RESULTING_HTML_TARZ_ARCHIVE_FILE=$DOXTEMP/vtk4-html.tar.gz # export CREATE_HTML_TARZ_ARCHIVE=@DOCUMENTATION_HTML_TARZ@ export RESULTING_HTML_TARZ_ARCHIVE_FILE="$DOXTEMP/$PROJECT_NAME-html.tar.gz" # DOWNLOAD_VTK_TAGFILE VTK_TAGFILE VTK_TAGFILE_REMOTE_DIR VTK_TAGFILE_DEST_DIR: # Download the VTK tag file, name, remote location and destination dir of this # tag file. If set to ON, the tag file is retrieved from its remote location # using wget and stored in the destination dir. # The tag file is expected to be compressed using gzip, but DO NOT include # the .gz extension in VTK_TAGFILE. # Note: your doxyfile must be tailored to make use-of or create this tag file. # (using TAGFILES = vtk4-nightly.tag=http://www.vtk.org/doc/nightly/html # or GENERATE_TAGFILE = "@FOO_BINARY_DIR@/Utilities/Doxygen/vtk4.tag") # Example: # DOWNLOAD_VTK_TAGFILE=OFF # VTK_TAGFILE=vtk4-nightly.tag # VTK_TAGFILE_REMOTE_DIR=http://www.vtk.org/doc/nightly/html # VTK_TAGFILE_DEST_DIR=$DOXTEMP # export DOWNLOAD_VTK_TAGFILE=@DOCUMENTATION_DOWNLOAD_VTK_TAGFILE@ export VTK_TAGFILE=vtkNightlyDoc.tag export VTK_TAGFILE_REMOTE_DIR="http://www.vtk.org/files/nightly" export VTK_TAGFILE_DEST_DIR="$DOXTEMP" echoexit() { echo "$1" exit 1 } cd "${DOXTEMP}" || echoexit "Cannot find Doxygen output directory: ${DOXTEMP}" # ---------------------------------------------------------------------------- # Convert the VTK headers to the Doxygen format. echo "Convert the VTK headers to the Doxygen format." if test "x$PERL_PROG" != "xNOTFOUND" ; then $PERL_PROG "$PATH_TO_VTK_DOX_SCRIPTS/doc_header2doxygen.pl" \ --to "$INTERMEDIATE_DOX_DIR" \ --relativeto "@DOXYGEN_SOURCE_LOCATIONS_DIR@" \ @DOXYGEN_SOURCE_LOCATIONS@ || echoexit "Problem converting VTK headers" if test "x@DOXYGEN_BINARY_LOCATIONS_DIR@" != "x"; then $PERL_PROG "$PATH_TO_VTK_DOX_SCRIPTS/doc_header2doxygen.pl" \ --to "$INTERMEDIATE_DOX_DIR" \ --relativeto "@DOXYGEN_BINARY_LOCATIONS_DIR@" \ @DOXYGEN_BINARY_LOCATIONS@ || echoexit "Problem converting VTK headers" fi fi echo "Convert the VTK headers to the Doxygen format - done" # ---------------------------------------------------------------------------- # Build the full-text index. echo "Build the full-text index." if test "x$PERL_PROG" != "xNOTFOUND" ; then $PERL_PROG "$PATH_TO_VTK_DOX_SCRIPTS/doc_index.pl" \ --project "$PROJECT_NAME" \ --stop "$PATH_TO_VTK_DOX_SCRIPTS/doc_index.stop" \ --store "doc_""$PROJECT_NAME""_index.dox" \ --to "$INTERMEDIATE_DOX_DIR" \ @DOXYGEN_SOURCE_LOCATIONS@ \ @DOXYGEN_BINARY_LOCATIONS@ || echoexit "Problem building full-text index" fi echo "Build the full-text index - done" # # ---------------------------------------------------------------------------- # # Generate the 'Class to Demos' page cross-linking each class to these # # demos that use that class. # if test "x$PERL_PROG" != "xNOTFOUND" ; then # $PERL_PROG $PATH_TO_VTK_DOX_SCRIPTS/doc_class2example.pl \ # --datamatch "\W((VTK|ParaView)_DATA_ROOT|(VTK|MedVIP)Data|(vtk)?GetDataRoot|ExpandDataFileName)\W" \ # --dataicon "paper-clip.gif" \ # --dirmatch "^demos$" \ # --label "Demos" \ # --project "$PROJECT_NAME" \ # --store "doc_""$PROJECT_NAME""_class2demos.dox" \ # --title "Class To Demos" \ # --to "$INTERMEDIATE_DOX_DIR" \ # --unique "d" \ # "$SOURCE_DIR/framework/demos" # fi # ---------------------------------------------------------------------------- # Retrieve the (gziped) VTK 4 tag file and decompress it if test "x$DOWNLOAD_VTK_TAGFILE" == "xON" ; then if test "x$VTK_TAGFILE" != "x" ; then if test "x$WGET_PROG" != "xNOTFOUND" ; then $WGET_PROG -nd -nH \ "$VTK_TAGFILE_REMOTE_DIR/$VTK_TAGFILE.gz" \ -O "$VTK_TAGFILE_DEST_DIR/$VTK_TAGFILE.gz" if test "x$GZIP_PROG" != "xNOTFOUND" ; then $GZIP_PROG -f -d "$VTK_TAGFILE_DEST_DIR/$VTK_TAGFILE.gz" fi fi fi fi # ---------------------------------------------------------------------------- # Create the Doxygen doc. if test "x$DOXYGEN_PROG" != "xNOTFOUND" ; then if test "x$RM_PROG" != "xNOTFOUND" ; then $RM_PROG -fr "$OUTPUT_DIRECTORY" fi $DOXYGEN_PROG "$DOXYFILE" || echoexit "Problem running doxygen" fi # ---------------------------------------------------------------------------- # Clean the HTML pages to remove the path to the intermediate Doxygen dir. if test "x$PERL_PROG" != "xNOTFOUND" ; then $PERL_PROG "$PATH_TO_VTK_DOX_SCRIPTS/doc_rmpath.pl" \ --to "$INTERMEDIATE_DOX_DIR" \ --html "$OUTPUT_DIRECTORY/html" || echoexit "Problem cleaning HTML pages" fi # ---------------------------------------------------------------------------- # Create the CHM HTML HELP doc. if test "x$COMPILE_HTML_HELP" == "xON" ; then if test "x$RESULTING_HTML_HELP_FILE" != "x" ; then cd "$OUTPUT_DIRECTORY/html" if test "x$HHC_PROG" != "xNOTFOUND" ; then $HHC_PROG index.hhp || echoexit "Problem generating CHM" if test "x$MV_PROG" != "xNOTFOUND" ; then $MV_PROG -f index.chm "$RESULTING_HTML_HELP_FILE" fi fi fi fi # ---------------------------------------------------------------------------- # Create the compressed tar archive. if test "x$CREATE_HTML_TARZ_ARCHIVE" == "xON" ; then if test "x$RESULTING_HTML_TARZ_ARCHIVE_FILE" != "x" ; then cd "$OUTPUT_DIRECTORY" if test "x$TAR_PROG" != "xNOTFOUND" ; then if test "x$RM_PROG" != "xNOTFOUND" ; then $RM_PROG -f html.tar fi $TAR_PROG -cf html.tar html if test "x$GZIP_PROG" != "xNOTFOUND" ; then if test "x$RM_PROG" != "xNOTFOUND" ; then $RM_PROG -f html.tar.gz fi $GZIP_PROG html.tar $MV_PROG -f html.tar.gz "$RESULTING_HTML_TARZ_ARCHIVE_FILE" fi fi fi fi # ---------------------------------------------------------------------------- # Clean-up. if test "x$RM_PROG" != "xNOTFOUND" ; then $RM_PROG -fr "$INTERMEDIATE_DOX_DIR" if test "x$DOWNLOAD_VTK_TAGFILE" == "xON" ; then if test "x$VTK_TAGFILE" != "x" ; then $RM_PROG -f "$VTK_TAGFILE_DEST_DIR/$VTK_TAGFILE" fi fi if test "x$COMPILE_HTML_HELP" == "xON" ; then if test "x$RESULTING_HTML_HELP_FILE" != "x" ; then if test "x$ALLOW_ERASE_OUTPUT_DIRECTORY" == "xON" ; then $RM_PROG -fr "$OUTPUT_DIRECTORY" fi fi fi fi vtkedge-0.2.0~20110819/Utilities/Doxygen/CMakeLists.txt0000644000175000017500000000651011363410610022165 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # # Build the documentation # #INCLUDE (Documentation) INCLUDE (${CMAKE_ROOT}/Modules/Documentation.cmake) IF (BUILD_DOCUMENTATION) SET(BUILD_DOXYGEN ON) SET(DOCUMENTATION_DOWNLOAD_VTK_TAGFILE ON) SET(DOCUMENTATION_HTML_TARZ ON) SET(DOXYGEN_PROJECT_NAME "VTKEdge") # path to Perl scripts used to produce the VTK doc in Doxygen format. FIND_PATH(VTK_SOURCE_DIR vtkConfigure.h.in ${VTKEdge_SOURCE_DIR}/.. DOC "root of the VTK source directory") MESSAGE("VTK_SOURCE_DIR=${VTK_SOURCE_DIR}") SET(DOXYGEN_SOURCE_DIR "${VTK_SOURCE_DIR}/Utilities/Doxygen") SET(DOXYGEN_PROJECT_SOURCE_DIR "${VTKEdge_SOURCE_DIR}") SET(VTK_DOXYGEN_HOME "${VTK_SOURCE_DIR}/Utilities/Doxygen") # SET(DOXYGEN_CVSWEB_CHECKOUT "http://public.kitware.com/cgi-bin/cvsweb.cgi/~checkout~/ParaView3/") # SET(DOXYGEN_CVSWEB_CHECKOUT_SUFFIX "?cvsroot=ParaView3") SET(DOXYGEN_SOURCE_LOCATIONS_DIR "${VTKEdge_SOURCE_DIR}") SET(DOXYGEN_SOURCE_LOCATIONS "\"${VTKEdge_SOURCE_DIR}/Common\" \\ \"${VTKEdge_SOURCE_DIR}/Filtering\" \\ \"${VTKEdge_SOURCE_DIR}/Graphics\" \\ \"${VTKEdge_SOURCE_DIR}/Hybrid\" \\ \"${VTKEdge_SOURCE_DIR}/Imaging\" \\ \"${VTKEdge_SOURCE_DIR}/IO\" \\ \"${VTKEdge_SOURCE_DIR}/Rendering\" \\ \"${VTKEdge_SOURCE_DIR}/Widgets\" \\ \"${VTKEdge_SOURCE_DIR}/VolumeRendering\"") SET(DOXYGEN_BINARY_LOCATIONS_DIR "${VTKEdge_BINARY_DIR}") SET(DOXYGEN_BINARY_LOCATIONS "") SET(DOXYGEN_PARSED_INPUT_DIRS "\"${CMAKE_CURRENT_BINARY_DIR}/dox/Common\" \\ \"${CMAKE_CURRENT_BINARY_DIR}/dox/Filtering\" \\ \"${CMAKE_CURRENT_BINARY_DIR}/dox/Graphics\" \\ \"${CMAKE_CURRENT_BINARY_DIR}/dox/Hybrid\" \\ \"${CMAKE_CURRENT_BINARY_DIR}/dox/Imaging\" \\ \"${CMAKE_CURRENT_BINARY_DIR}/dox/IO\" \\ \"${CMAKE_CURRENT_BINARY_DIR}/dox/Rendering\" \\ \"${CMAKE_CURRENT_BINARY_DIR}/dox/Widgets\" \\ \"${CMAKE_CURRENT_BINARY_DIR}/dox/VolumeRendering\"") SET(DOXYGEN_IGNORE_PREFIX "vtkKWE vtk") # # Configure the script and the doxyfile, then add target # IF(NOT DOT_PATH) GET_FILENAME_COMPONENT(DOT_PATH ${DOT} PATH) ENDIF(NOT DOT_PATH) SET(TAGFILES "\"${CMAKE_CURRENT_BINARY_DIR}/vtkNightlyDoc.tag=http://www.vtk.org/doc/nightly/html\"") CONFIGURE_FILE( ${CMAKE_CURRENT_SOURCE_DIR}/doxyfile.in ${CMAKE_CURRENT_BINARY_DIR}/doxyfile @ONLY IMMEDIATE) CONFIGURE_FILE( ${CMAKE_CURRENT_SOURCE_DIR}/doc_makeall.sh.in ${CMAKE_CURRENT_BINARY_DIR}/doc_makeall.sh @ONLY IMMEDIATE) ADD_CUSTOM_TARGET(${DOXYGEN_PROJECT_NAME}DoxygenDoc ${BASH} ${CMAKE_CURRENT_BINARY_DIR}/doc_makeall.sh) ENDIF (BUILD_DOCUMENTATION) vtkedge-0.2.0~20110819/Utilities/Doxygen/doxyfile.in0000644000175000017500000001452711363410610021607 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ------------------------------------------------------------------------- # doxyfile for generic project # modified by S. Barre (Time-stamp: <2005-11-07 11:45:05 barre> # ------------------------------------------------------------------------- PROJECT_NAME = @DOXYGEN_PROJECT_NAME@ FULL_PATH_NAMES = YES WARN_IF_UNDOCUMENTED = NO GENERATE_TREEVIEW = NO GENERATE_TODOLIST = YES GENERATE_BUGLIST = YES GENERATE_HTML = YES GENERATE_HTMLHELP = YES GENERATE_LATEX = NO GENERATE_MAN = NO GENERATE_RTF = NO GENERATE_TAGFILE = "@CMAKE_CURRENT_BINARY_DIR@/@DOXYGEN_PROJECT_NAME@.tag" HAVE_DOT = YES #HAVE_DOT = NO DOT_PATH = "@DOT_PATH@" CLASS_GRAPH = YES COLLABORATION_GRAPH = YES TEMPLATE_RELATIONS = YES INCLUDE_GRAPH = YES INCLUDED_BY_GRAPH = YES CLASS_DIAGRAMS = YES GENERATE_LEGEND = YES GRAPHICAL_HIERARCHY = YES ALLEXTERNALS = NO IMAGE_PATH = "@CMAKE_CURRENT_SOURCE_DIR@" OUTPUT_DIRECTORY = "@CMAKE_CURRENT_BINARY_DIR@/doc" INPUT = \ "@CMAKE_CURRENT_BINARY_DIR@/dox/doc_@DOXYGEN_PROJECT_NAME@_index.dox" \ @DOXYGEN_PARSED_INPUT_DIRS@ #TAGFILES = "@CMAKE_CURRENT_BINARY_DIR@/vtkNightlyDoc.tag=http://www.vtk.org/doc/nightly/html" TAGFILES = @TAGFILES@ EXTRACT_ALL = YES EXTRACT_PRIVATE = NO EXTRACT_STATIC = YES HIDE_UNDOC_MEMBERS = NO HIDE_UNDOC_CLASSES = YES ALWAYS_DETAILED_SEC = NO SOURCE_BROWSER = YES INLINE_SOURCES = NO CASE_SENSE_NAMES = YES VERBATIM_HEADERS = NO SHOW_INCLUDE_FILES = YES JAVADOC_AUTOBRIEF = YES SORT_MEMBER_DOCS = NO DISTRIBUTE_GROUP_DOC = YES TAB_SIZE = 3 FILE_PATTERNS = *.h RECURSIVE = NO EXCLUDE = Common/vtkSetGet.h EXCLUDE_PATTERNS = HTML_ALIGN_MEMBERS = YES ALPHABETICAL_INDEX = YES COLS_IN_ALPHA_INDEX = 3 IGNORE_PREFIX = @DOXYGEN_IGNORE_PREFIX@ ENABLE_PREPROCESSING = YES MACRO_EXPANSION = YES SEARCH_INCLUDES = YES INCLUDE_PATH = EXPAND_ONLY_PREDEF = YES PREDEFINED = "vtkSetMacro(name,type)= \ virtual void Set##name (type);" \ "vtkGetMacro(name,type)= \ virtual type Get##name ();" \ "vtkSetStringMacro(name)= \ virtual void Set##name (const char*);" \ "vtkGetStringMacro(name)= \ virtual char* Get##name ();" \ "vtkSetClampMacro(name,type,min,max)= \ virtual void Set##name (type);" \ "vtkSetObjectMacro(name,type)= \ virtual void Set##name (type*);" \ "vtkGetObjectMacro(name,type)= \ virtual type *Get##name ();" \ "vtkBooleanMacro(name,type)= \ virtual void name##On (); \ virtual void name##Off ();" \ "vtkSetVector2Macro(name,type)= \ virtual void Set##name (type, type); \ void Set##name (type [2]);" \ "vtkGetVector2Macro(name,type)= \ virtual type *Get##name (); \ virtual void Get##name (type &, type &); \ virtual void Get##name (type [2]);" \ "vtkSetVector3Macro(name,type)= \ virtual void Set##name (type, type, type); \ virtual void Set##name (type [3]);" \ "vtkGetVector3Macro(name,type)= \ virtual type *Get##name (); \ virtual void Get##name (type &, type &, type &); \ virtual void Get##name (type [3]);" \ "vtkSetVector4Macro(name,type)= \ virtual void Set##name (type, type, type, type); \ virtual void Set##name (type [4]);" \ "vtkGetVector4Macro(name,type)= \ virtual type *Get##name (); \ virtual void Get##name (type &, type &, type &, type &); \ virtual void Get##name (type [4]);" \ "vtkSetVector6Macro(name,type)= \ virtual void Set##name (type, type, type, type, \ type, type); \ virtual void Set##name (type [6]);" \ "vtkGetVector6Macro(name,type)= \ virtual type *Get##name (); \ virtual void Get##name (type &, type &, type &, \ type &, type &, type &); \ virtual void Get##name (type [6]);" \ "vtkSetVectorMacro(name,type,count)= \ virtual void Set##name(type data[]);" \ "vtkGetVectorMacro(name,type,count)= \ virtual type *Get##name (); \ virtual void Get##name(type data[##count]);" \ "vtkWorldCoordinateMacro(name)= \ virtual vtkCoordinate *Get##name##Coordinate (); \ virtual void Set##name(float x[3]); \ virtual void Set##name(float x, float y, float z); \ virtual float *Get##name();" \ "vtkViewportCoordinateMacro(name)= \ virtual vtkCoordinate *Get##name##Coordinate (); \ virtual void Set##name(float x[2]); \ virtual void Set##name(float x, float y); \ virtual float *Get##name();" \ "vtkTypeMacro(thisClass,superclass)= \ virtual const char *GetClassName(); \ static int IsTypeOf(const char *type); \ virtual int IsA(const char *type); \ static thisClass* SafeDownCast(vtkObject *o);" vtkedge-0.2.0~20110819/Filtering/0000755000175000017500000000000011630434664015772 5ustar mathieumathieuvtkedge-0.2.0~20110819/Filtering/vtkKWEObjectTreeNodeBase.h0000644000175000017500000002675211363410610022666 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEObjectTreeNodeBase - Base class for ObjectTree nodes // .SECTION Description // The base class for ObjectTree nodes, vtkKWEObjectTreeNodeBase provides the // ability add and remove children of a node while guaranteeing that a cycle // isn't created. Also, to change the characteristics of a "basic" node type, // subclasses of vtkKWEObjectTreePropertyBase can be added to a node, though // a node can only have one instance of each property type (such as // vtkKWEObjectTreeUserProperty). Though not implemented yet, descendants of // a node could (or would?) inherit these properties, if they don't have an // instance of the propeoerty type themselves. Similar to Properties, but // not to be inherited by a descendant are Attributes of a node. These // are more basic charateristics of the node, including the "Name" of the node // as well as its "State" (if "inactive", the node is "off", and children are // not traversed). If requested, a node will also generate a UUID for the // purpose of uniquely identifying a node. // // As a subclass of vtkKWESerializableObject, this object can easily be // serialized via its Serialize method. // // .SECTION See Also // vtkKWEObjectTreeTransformableNode vtkKWEObjectTreePropertyBase #ifndef __vtkKWEObjectTreeNodeBase_h #define __vtkKWEObjectTreeNodeBase_h #include "vtkKWESerializableObject.h" #include "vtkSmartPointer.h" #include "VTKEdgeConfigure.h" // include configuration header class vtkInformation; class vtkInformationIntegerKey; class vtkInformationObjectBaseKey; class vtkInformationStringKey; class vtkKWEObjectTreePropertyBase; class vtkKWEObjectTreeNodeBaseChildren; class vtkKWEObjectTreeNodeIterator; class vtkKWESerializer; class VTKEdge_FILTERING_EXPORT vtkKWEObjectTreeNodeBase : public vtkKWESerializableObject { public: static vtkKWEObjectTreeNodeBase* New(); vtkTypeRevisionMacro(vtkKWEObjectTreeNodeBase, vtkKWESerializableObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set/Get the vtkObject for this node. virtual void SetNodeObject(vtkObject *object); vtkGetObjectMacro(NodeObject, vtkObject); // Description: // Returns number of children this node has. virtual unsigned int GetNumberOfChildren(); // Description: // Add the child to this node and set this node as its parent. The node // is added only if unique (not already a child), if the node doesn't have // a parent (which actually handles its uniqueness as a child), and if a // cycle won't be created by adding the child. // Returns index of the child (-1 if not added). virtual int AddChild(vtkKWEObjectTreeNodeBase *childNode); // Description: // Inserts this child at the specified index (0 based)in the child "list" // and sets this node as its parent. The node is added only if unique (not // already a child), if the index is valid (will not insert at index 3 if // only 2 children in the list), if the node doesn't have a parent (which // actually handles its uniqueness as a child), and if a cycle won't be // created by adding the child. // Return 1 if the node is added (0 otherwise); virtual int InsertChild(unsigned int index, vtkKWEObjectTreeNodeBase *childNode); // Description: // Remove indicated child node. Return index of the child that was removed or // -1 if it wasn't a child. int RemoveChild(vtkKWEObjectTreeNodeBase *childNode); // Description: // Remove child at indicated index. Return 1 if successful (0 otherwise). int RemoveChild(unsigned int index); // Description: // Get child at indicated index. vtkKWEObjectTreeNodeBase *GetChild(unsigned int index); // Description: // Get the parent of this node (a value of NULL indicates this node is the // root of the tree vtkGetObjectMacro(Parent, vtkKWEObjectTreeNodeBase); // Description: // Tests whether a node exists in the tree (returns true if it does). virtual bool IsDescendant(vtkKWEObjectTreeNodeBase *testNode); // Description: // Add the property to the node; returns 0 if the property was already present // (does NOT replace the existing property) int AddProperty(vtkKWEObjectTreePropertyBase *nodeProperty); // Description: // Fill the passed vtkInformation object with ALL the properties of this node, // including those that this node inherits, IF CanInheritProperties()==true void GetAllProperties(vtkInformation *allProperties); // Description: // Retrieves the requested property, if it exists (otherwise returns NULL). If // includeInheritance == true (and INHERIT_PROPERTIES is ON), will search // ancestors for inheritable property of specified type. The // inheritedProperty flag it set to true if the property is inherited from // an ancestor. vtkKWEObjectTreePropertyBase* GetProperty(vtkInformationObjectBaseKey *propertyKey, bool &inheritedProperty, bool includeInheritance = false); // Description: // Removes the property with the given Key, if it exists. // Returns 1 if the property existed and was removed, 0 otherwise. int RemoveProperty(vtkInformationObjectBaseKey *propertyKey); // Description: // Removes the property if it exists. // Returns 1 if the property existed and was removed, 0 otherwise. int RemoveProperty(vtkKWEObjectTreePropertyBase *nodeProperty); // Description: // Removes all the node's properties. void RemoveAllProperties(); // Description: // Return the number of properties set on this node. int GetNumberOfProperties(); // Description: // Update modifed time for this object and also update the TreeModifiedTime // (for this object, and pushes up to parent as well) virtual void Modified(); // Description: // Return this object's modified time, considering the properties of this // node. This value is not affected by a child changing (but is by adding // or removing a child) virtual unsigned long GetMTime(); // Description: // Return the modified time for this (sub)tree. vtkGetMacro(TreeModifiedTime, unsigned long); // Description: // Check to see if the specified node is the same (Attributes and Properties) // as this node. If checkDescendants == true, then the children (and their // children) are compared as well (and must be in the same order). If // canBeSuperset == true, then it is considered "equal" if all attrbiutes // and Properties that are set in the testNode match in "this" node (this // node can be a superset of testNode); the final flag // "considerInheritedProperties" will compare an inherited property as if // it were a property specifed on the node. virtual bool IsEqualTo(vtkKWEObjectTreeNodeBase *testNode, bool checkDescendants, bool canBeSuperset = false, bool considerInheritedProperties = false); // Description: // Reads the state of an instance from an archive OR // writes the state of an instance to an archive. virtual void Serialize(vtkKWESerializer*); // Description: // Set/Get the name of this node. const char *GetName(); void SetName(const char *name); // Description: // Get the UUID for this node. const char *GetUUID(); // Description: // Set the UUID for this node. void SetUUID(const char *uuid); // Description: // Creates a UUID for this node (if one doesn't already exist). Return 0 // if already exists, 1 if able to "generate" an uuid, and 2 if it was // necessary to "construct" (less unique) an uuid. int CreateUUID(); // Description: // Clear/remove the UUID for this node. Calling CreateUUID after ClearUUID // will create a new/different UUID. void ClearUUID(); //BTX // might expand to have a third state, where node is inactive, but the // subtree is not. enum NodeStates { ACTIVE_STATE, INACTIVE_STATE }; //ETX void SetStateToActive() { this->SetState(ACTIVE_STATE); } void SetStateToInactive() { this->SetState(INACTIVE_STATE); } void SetState(int nodeState); int GetState(); const char *GetStateAsString(); // Description: // Set/Get whether or not this node can inherit properties from its ancestors void InheritPropertiesOn() { this->SetInheritProperties(true); } void InheritPropertiesOff() { this->SetInheritProperties(false); } bool CanInheritProperties() { return this->GetInheritProperties(); } bool GetInheritProperties(); void SetInheritProperties(bool inheritState); static vtkInformationStringKey* NAME(); static vtkInformationStringKey* UUID(); static vtkInformationIntegerKey* STATE(); static vtkInformationIntegerKey* INHERIT_PROPERTIES(); protected: vtkKWEObjectTreeNodeBase(); virtual ~vtkKWEObjectTreeNodeBase(); // Description: // The parent of this node. void SetParent(vtkKWEObjectTreeNodeBase *parent); // Description: // Adds the children of this node to the iterator according to how the // iterator is defined/setup. friend class vtkKWEObjectTreeNodeIterator; void AddChildren(vtkKWEObjectTreeNodeIterator *iterator); // Description: // Update the TreeModifiedTime for this node (and pushes the time up // to its parent as well) friend class vtkKWEObjectTreePropertyBase; virtual void UpdateTreeModifiedTime(unsigned long treeTime); // Description: // Add inheritable properties that don't already exist in allProperties. // Should only be called by a child of "this" object and the resulting list // is only accurate for the original caller of GetAllProperties() void AddInheritedProperties(vtkInformation *allProperties); // Description: // Returns the number of entries in the vtkInformation object. This really // should go in with the vtkInformation code in VTK, but here for now int GetNumberOfInformationEntries(vtkInformation *infoObject); // Description: // The children of this node. PIMPL vtkKWEObjectTreeNodeBaseChildren *Children; // Description: // Parent of the node. If NULL, then this node is the root of the tree. vtkKWEObjectTreeNodeBase *Parent; // Description: // Properties that make this node "special". They could be properties // controlling visualization or maybe an application specific property. vtkInformation *Properties; // Description: // "Attributes" of this node that are not inherited by the children vtkInformation *Attributes; // Description: // Cached value for the tree with this node as root unsigned long TreeModifiedTime; // Description: // The vtkObject contained within this node vtkObject *NodeObject; // Description: // Serialize the Object member. I've separated this out (from Serialize) and // made it virtual since subclasses may want to serialize this differently based // on the type of the Object that the Node will hold. virtual void SerializeObject(vtkKWESerializer*); private: vtkKWEObjectTreeNodeBase(const vtkKWEObjectTreeNodeBase&); // Not implemented. void operator=(const vtkKWEObjectTreeNodeBase&); // Not implemented. bool RemoveAllPropertiesInternal(); }; #endif vtkedge-0.2.0~20110819/Filtering/vtkKWEObjectTreeTransformableNode.h0000644000175000017500000000662211363410610024605 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEObjectTreeTransformableNode - Transformable nodes that can be referenced // .SECTION Description // vtkKWEObjectTreeTransformableNode adds a vtkTransform object to // vtkKWEObjectTreeNodeBase and also is the base class of nodes that can be // "referenced" by other nodes. // .SECTION See Also #ifndef __vtkKWEObjectTreeTransformableNode_h #define __vtkKWEObjectTreeTransformableNode_h #include "vtkKWEObjectTreeNodeBase.h" #include "vtkSmartPointer.h" #include "VTKEdgeConfigure.h" // include configuration header class vtkInformation; class vtkTransform; class vtkKWEObjectTreeTransformableNodeReferencingNodes; class VTKEdge_FILTERING_EXPORT vtkKWEObjectTreeTransformableNode : public vtkKWEObjectTreeNodeBase { public: static vtkKWEObjectTreeTransformableNode* New(); vtkTypeRevisionMacro(vtkKWEObjectTreeTransformableNode, vtkKWEObjectTreeNodeBase); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set/Get this objects transform void SetTransform(vtkTransform *transform); vtkGetObjectMacro(Transform, vtkTransform); // Description: // Update the TreeModifiedTime for this node (and pushes the time up // to any nodes referencing it as well) virtual void UpdateTreeModifiedTime(unsigned long treeTime); // Description: // Return this object's modified time, considering the transforms MTime virtual unsigned long GetMTime(); // Description: // Adds test of the this node's transform to the equality test performed // by the base class. virtual bool IsEqualTo(vtkKWEObjectTreeNodeBase *testNode, bool checkDescendants, bool canBeSuperset = false, bool considerInheritedProperties = false); // Description: // Reads the state of an instance from an archive OR // writes the state of an instance to an archive. virtual void Serialize(vtkKWESerializer*); // Description: // Keep track of referencing nodes (vtkKWEObjectTreeReferenceNode) so we can // notify them when we have changed // void AddReferencingNode( vtkKWEObjectTreeTransformableNode *referencingNode ) {}; //void RemoveReferencingNode( vtkKWEObjectTreeTransformableNode *referencingNode ) {}; protected: vtkKWEObjectTreeTransformableNode(); virtual ~vtkKWEObjectTreeTransformableNode(); // Description: // This node's transform. vtkTransform *Transform; // Description: // Keep track of referencing nodes (vtkKWEObjectTreeReferenceNode) so we can // notify them when we have changed. PIMPL vtkKWEObjectTreeTransformableNodeReferencingNodes *ReferencingNodes; private: vtkKWEObjectTreeTransformableNode(const vtkKWEObjectTreeTransformableNode&); // Not implemented. void operator=(const vtkKWEObjectTreeTransformableNode&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Filtering/vtkKWEObjectTreeUserProperty.cxx0000644000175000017500000000264611363410610024240 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEObjectTreeUserProperty.h" #include "vtkInformation.h" #include "vtkInformationObjectBaseKey.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkKWEObjectTreeUserProperty, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEObjectTreeUserProperty); vtkInformationKeyMacro(vtkKWEObjectTreeUserProperty, KEY, ObjectBase); //----------------------------------------------------------------------------- vtkInformation *vtkKWEObjectTreeUserProperty::GetAttributesPointer() { return this->Attributes; } // --------------------------------------------------------------------------- void vtkKWEObjectTreeUserProperty::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Filtering/vtkKWEObjectTreeUserProperty.h0000644000175000017500000000533311363410610023661 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEObjectTreeUserProperty - A user editable Property for ObjectTree nodes // .SECTION Description // Whereas other ObjectTreeProperties can only be edited via the provided // Set/Get methods, the vtkKWEObjectTreeUserProperty allows an application // developer to define specific attributes/keys within the app (without // subclassing vtkKWEObjectTreePropertyBase) which can then be serialized // as other vtkKWEObjectTreePropertyBase) are serialized. Note that it // is the responsibility of the user of this class to call Modified() // when/if changes are made (values added/removed/changed) if the "TreeTime" // of the nodes referring to the property is to be preoperly updated. // See TestObjectTree.cxx for example usage. // .SECTION See Also // vtkKWEObjectTreePropertyBase #ifndef __vtkKWEObjectTreeUserProperty_h #define __vtkKWEObjectTreeUserProperty_h #include "vtkKWEObjectTreePropertyBase.h" class vtkInformationDoubleVectorKey; class vtkInformationObjectBaseKey; class VTKEdge_FILTERING_EXPORT vtkKWEObjectTreeUserProperty : public vtkKWEObjectTreePropertyBase { public: static vtkKWEObjectTreeUserProperty* New(); vtkTypeRevisionMacro(vtkKWEObjectTreeUserProperty, vtkKWEObjectTreePropertyBase); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Give access to the internal vtkInformation object so information can be // added as user wants. NOTE: If changes are made, Modified() should/must // be called so we can update the TreeModifiedTime of all our // referencing nodes. vtkInformation *GetAttributesPointer(); // Description: // Get the key used for keeping track of this property. static vtkInformationObjectBaseKey* KEY(); virtual vtkInformationObjectBaseKey* GetKey() { return KEY(); } protected: vtkKWEObjectTreeUserProperty() {}; ~vtkKWEObjectTreeUserProperty() {}; private: vtkKWEObjectTreeUserProperty(const vtkKWEObjectTreeUserProperty&); // Not implemented. void operator=(const vtkKWEObjectTreeUserProperty&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Filtering/vtkKWEObjectTreePropertyBase.cxx0000644000175000017500000002365311363410610024175 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEObjectTreePropertyBase.h" #include "vtkKWEObjectTreeNodeBase.h" #include "vtkInformation.h" #include "vtkInformationDoubleKey.h" #include "vtkInformationDoubleVectorKey.h" #include "vtkInformationIdTypeKey.h" #include "vtkInformationIntegerKey.h" #include "vtkInformationIntegerVectorKey.h" #include "vtkInformationIterator.h" #include "vtkInformationStringKey.h" #include "vtkObjectFactory.h" #include "vtkKWESerializer.h" #include #include vtkCxxRevisionMacro(vtkKWEObjectTreePropertyBase, "$Revision: 1774 $"); vtkInformationKeyMacro(vtkKWEObjectTreePropertyBase, IS_INHERITABLE, Integer); class vtkKWEObjectTreePropertyBaseReferencingNodes : public vtkstd::set< vtkKWEObjectTreeNodeBase* > { }; //----------------------------------------------------------------------------- vtkKWEObjectTreePropertyBase::vtkKWEObjectTreePropertyBase() { this->Attributes = vtkInformation::New(); this->ReferencingNodes = new vtkKWEObjectTreePropertyBaseReferencingNodes; this->SetIsInheritable(true); // by default properties are inheritable } //----------------------------------------------------------------------------- vtkKWEObjectTreePropertyBase::~vtkKWEObjectTreePropertyBase() { this->Attributes->Delete(); if (this->ReferencingNodes->size() > 0) { vtkErrorMacro("We seem to think that someone still is refercing us.... so should be destructing!"); } delete this->ReferencingNodes; } //----------------------------------------------------------------------------- void vtkKWEObjectTreePropertyBase::Modified() { this->Superclass::Modified(); vtkKWEObjectTreePropertyBaseReferencingNodes::const_iterator iterator; for (iterator = this->ReferencingNodes->begin(); iterator != this->ReferencingNodes->end(); iterator++) { (*iterator)->UpdateTreeModifiedTime( this->GetMTime() ); } } //----------------------------------------------------------------------------- bool vtkKWEObjectTreePropertyBase::GetIsInheritable() { if (this->Attributes->Has(IS_INHERITABLE())) { return this->Attributes->Get( IS_INHERITABLE() ) ? true : false; } return true; // if not set, return true } //----------------------------------------------------------------------------- void vtkKWEObjectTreePropertyBase::SetIsInheritable(bool isInheritable) { // if already set AND same as "new" value, do nothing if (this->Attributes->Has(IS_INHERITABLE()) && this->GetIsInheritable() == isInheritable) { return; } // otherwise need to set and indicate that we've been modified this->Attributes->Set(IS_INHERITABLE(), isInheritable ? 1 : 0); this->Modified(); } //----------------------------------------------------------------------------- void vtkKWEObjectTreePropertyBase::UnsetIsInheritable() { this->Attributes->Remove(IS_INHERITABLE()); this->Modified(); } //----------------------------------------------------------------------------- void vtkKWEObjectTreePropertyBase::AddReferencingNode(vtkKWEObjectTreeNodeBase *node) { this->ReferencingNodes->insert(node); } //----------------------------------------------------------------------------- void vtkKWEObjectTreePropertyBase::RemoveReferencingNode(vtkKWEObjectTreeNodeBase *node) { this->ReferencingNodes->erase(node); } //----------------------------------------------------------------------------- void vtkKWEObjectTreePropertyBase::Serialize(vtkKWESerializer* ser) { ser->Serialize("Attributes", this->Attributes); if (ser->IsWriting()) { vtkstd::vector< vtkSmartPointer > myVector = vtkKWESerializer::ToBase( *this->ReferencingNodes ); ser->Serialize("ReferencingNodes", myVector, true); } else { // The ReferencingNodes are "weak" pointers; still upon deserializaing the method // expects a vector of SmartPointers. When we call FromBase we fill our // non-referencing counted container, giving the desired "weak" pointers (and no leak) vtkstd::vector< vtkSmartPointer > myVector; ser->Serialize("ReferencingNodes", myVector, true); vtkKWESerializer::FromBase(myVector, *this->ReferencingNodes); } } //----------------------------------------------------------------------------- int vtkKWEObjectTreePropertyBase::GetNumberOfAttributes() { vtkSmartPointer attributeIterator = vtkSmartPointer::New(); attributeIterator->SetInformation( this->Attributes ); int numberOfAttributes = 0; for (attributeIterator->InitTraversal(); !attributeIterator->IsDoneWithTraversal(); attributeIterator->GoToNextItem()) { numberOfAttributes++; } return numberOfAttributes; } //----------------------------------------------------------------------------- template bool AreScalarKeysEqual(vtkInformation* thisInfo, vtkInformation* testInfo, KeyType* key) { // if thisInfo doesn't have the key or the key values don't match, return false if (!thisInfo->Has(key) || testInfo->Get(key) != thisInfo->Get(key)) { return false; } return true; } //----------------------------------------------------------------------------- template bool AreVectorKeysEqual(vtkInformation* thisInfo, vtkInformation* testInfo, KeyType* key) { if (!thisInfo->Has(key) || thisInfo->Length(key) != testInfo->Length(key)) { return false; } ValueType *thisValues = thisInfo->Get(key); ValueType *testValues = testInfo->Get(key); int length = testInfo->Length(key); for (int i = 0; i < length; i++) { if (thisValues[i] != testValues[i]) { return false; } } return true; } // --------------------------------------------------------------------------- bool vtkKWEObjectTreePropertyBase::IsEqualTo(vtkKWEObjectTreePropertyBase *testProperty, bool canBeSuperset/*=false*/) { if (!testProperty) { return false; // can't be EqualTo if it doesn't exist! } if (strcmp(this->GetClassName(), testProperty->GetClassName())) { return false; // must be the same type of Property to be equal! } int myNumAttributes = this->GetNumberOfAttributes(); int testNumAttributes = testProperty->GetNumberOfAttributes(); if (myNumAttributes < testNumAttributes || (myNumAttributes > testNumAttributes && !canBeSuperset)) { // if the number of attributes doesn't match, then we can't be equal... // unless "this" Property has more and it can be a superset of the property // we are comparing ourselves to return false; } // test to see if the attributes match; at this point we know we either have // the same number of attributes or "this" has more but ok if it is a // superset. Thus just test every attribute in the testProperty to see if // there is a matching attribute in "this" Property... if so, then they match vtkSmartPointer attributeIterator = vtkSmartPointer::New(); attributeIterator->SetInformation( testProperty->Attributes ); for (attributeIterator->InitTraversal(); !attributeIterator->IsDoneWithTraversal(); attributeIterator->GoToNextItem()) { vtkInformationKey *key = attributeIterator->GetCurrentKey(); if (key->IsA("vtkInformationIntegerKey")) { if (!AreScalarKeysEqual( this->Attributes, testProperty->Attributes, static_cast(key))) { return false; } } else if (key->IsA("vtkInformationDoubleKey")) { if (!AreScalarKeysEqual( this->Attributes, testProperty->Attributes, static_cast(key))) { return false; } } else if (key->IsA("vtkInformationIdTypeKey")) { if (!AreScalarKeysEqual( this->Attributes, testProperty->Attributes, static_cast(key))) { return false; } } else if (key->IsA("vtkInformationStringKey")) { vtkInformationStringKey *stringKey = static_cast(key); if (!this->Attributes->Has(stringKey) || strcmp(this->Attributes->Get(stringKey), testProperty->Attributes->Get(stringKey))) { return false; } } else if (key->IsA("vtkInformationIntegerVectorKey")) { if (!AreVectorKeysEqual( this->Attributes, testProperty->Attributes, static_cast(key))) { return false; } } else if (key->IsA("vtkInformationDoubleVectorKey")) { if (!AreVectorKeysEqual( this->Attributes, testProperty->Attributes, static_cast(key))) { return false; } } } return true; } // --------------------------------------------------------------------------- void vtkKWEObjectTreePropertyBase::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Attributes:\n"; this->Attributes->PrintSelf(os, indent.GetNextIndent()); } vtkedge-0.2.0~20110819/Filtering/vtkKWEObjectTreeColorProperty.h0000644000175000017500000000440211363410610024015 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEObjectTreeColorProperty - simple (temporary) Property example // .SECTION Description // vtkKWEObjectTreeColorProperty is a simple concreate example of a ObjectTree // Property. containg one value to be saved in the Attribute list (COLOR()). // Here for example only, with plans to remove it as soon as a better/"real" // class is created and added to VTKEdge. // // .SECTION See Also // vtkKWEObjectTreePropertyBase vtkKWEObjectTreeUserProperty #ifndef __vtkKWEObjectTreeColorProperty_h #define __vtkKWEObjectTreeColorProperty_h #include "vtkKWEObjectTreePropertyBase.h" class vtkInformationDoubleVectorKey; class VTKEdge_FILTERING_EXPORT vtkKWEObjectTreeColorProperty : public vtkKWEObjectTreePropertyBase { public: static vtkKWEObjectTreeColorProperty* New(); vtkTypeRevisionMacro(vtkKWEObjectTreeColorProperty, vtkKWEObjectTreePropertyBase); void PrintSelf(ostream& os, vtkIndent indent); static vtkInformationDoubleVectorKey* COLOR(); // Description: // Set/Get the color of this node. double *GetColor(); void SetColor(double *color); // Description: // Get the key used for keeping track of this property. // referencing nodes. static vtkInformationObjectBaseKey* KEY(); virtual vtkInformationObjectBaseKey* GetKey() { return KEY(); } protected: vtkKWEObjectTreeColorProperty() {}; ~vtkKWEObjectTreeColorProperty() {}; private: vtkKWEObjectTreeColorProperty(const vtkKWEObjectTreeColorProperty&); // Not implemented. void operator=(const vtkKWEObjectTreeColorProperty&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Filtering/vtkKWEObjectTreeNodeIterator.cxx0000644000175000017500000002270511363410610024152 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEObjectTreeNodeIterator.h" #include "vtkKWEObjectTreeNodeBase.h" #include "vtkObjectFactory.h" #include "vtkWeakPointer.h" #include #include vtkCxxRevisionMacro(vtkKWEObjectTreeNodeIterator, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEObjectTreeNodeIterator); vtkCxxSetObjectMacro(vtkKWEObjectTreeNodeIterator, BaseNode, vtkKWEObjectTreeNodeBase); vtkCxxSetObjectMacro(vtkKWEObjectTreeNodeIterator, PatternNode, vtkKWEObjectTreeNodeBase); //----------------------------------------------------------------------------- class vtkKWEObjectTreeNodeIteratorInternals { public: vtkKWEObjectTreeNodeIteratorInternals() { this->TraversalMode = vtkKWEObjectTreeNodeIterator::DEPTH_FIRST; } // Move to next node and remove it from the appropriate container void NextNode(vtkKWEObjectTreeNodeBase*& node, int& depth); // Add a node (and its depth) to the appropriate container void AddNode(vtkKWEObjectTreeNodeBase* node, int depth); // Add a vector of node to the appropriate container void AddNodes(vtkstd::vector &nodes, int depth); // Depth-first (use Stack) versus breadth-first (use Queue) void SetMode(int mode) { this->TraversalMode = mode; } // Is the relevant container empty? bool IsEmpty(); // Empty both containers void Clear(); private: int TraversalMode; typedef struct { vtkWeakPointer Node; int Depth; // 0 = base, 1 = children, 2 = grandchildren, etc. } NodeInfo; vtkstd::stack< NodeInfo > Stack; vtkstd::queue< NodeInfo > Queue; }; //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeIteratorInternals::NextNode(vtkKWEObjectTreeNodeBase*& node, int& depth) { if (this->TraversalMode == vtkKWEObjectTreeNodeIterator::DEPTH_FIRST) { if (this->Stack.empty()) { node = 0; depth = -1; return; } node = this->Stack.top().Node; depth = this->Stack.top().Depth; this->Stack.pop(); } else // breadth-first { if (this->Queue.empty()) { node = 0; depth = -1; return; } node = this->Queue.front().Node; depth = this->Queue.front().Depth; this->Queue.pop(); } } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeIteratorInternals::AddNodes( vtkstd::vector &nodes, int depth) { if (this->TraversalMode == vtkKWEObjectTreeNodeIterator::DEPTH_FIRST) { // (reverse) iterate because we're adding these to a Stack, and want to pull // the 1st node from the iterator 1st (before the other nodes) vtkstd::vector::reverse_iterator nodeIter; for (nodeIter = nodes.rbegin(); nodeIter != nodes.rend(); nodeIter++) { this->AddNode(*nodeIter, depth); } } else // breadth first, so we can add them in the order they are in the list { vtkstd::vector::const_iterator nodeIter; for (nodeIter = nodes.begin(); nodeIter != nodes.end(); nodeIter++) { this->AddNode(*nodeIter, depth); } } } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeIteratorInternals::AddNode(vtkKWEObjectTreeNodeBase* node, int depth) { NodeInfo tmpNodeInfo; tmpNodeInfo.Node = node; tmpNodeInfo.Depth = depth; if (this->TraversalMode == vtkKWEObjectTreeNodeIterator::DEPTH_FIRST) { this->Stack.push( tmpNodeInfo ); } else { this->Queue.push( tmpNodeInfo ); } } //----------------------------------------------------------------------------- bool vtkKWEObjectTreeNodeIteratorInternals::IsEmpty() { if (this->TraversalMode == vtkKWEObjectTreeNodeIterator::DEPTH_FIRST) { return this->Stack.empty(); } // if not depth-first, assume breadth-first return this->Queue.empty(); } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeIteratorInternals::Clear() { while (!this->Stack.empty()) { this->Stack.pop(); } while (!this->Queue.empty()) { this->Queue.pop(); } } //----------------------------------------------------------------------------- vtkKWEObjectTreeNodeIterator::vtkKWEObjectTreeNodeIterator() { this->Internals = new vtkKWEObjectTreeNodeIteratorInternals; this->BaseNode = 0; this->PatternNode = 0; this->CurrentNode = 0; this->CurrentDepth = 0; this->InitTraversalTime = 0; this->TraversalMode = DEPTH_FIRST; this->ConsiderInheritedProperties = false; // default to adding only the children of the BaseNode this->IncludeBaseNode = false; this->MaximumTraversalDepth = 1; } //----------------------------------------------------------------------------- vtkKWEObjectTreeNodeIterator::~vtkKWEObjectTreeNodeIterator() { this->SetBaseNode(0); this->SetPatternNode(0); this->CurrentNode = 0; delete this->Internals; } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeIterator::GoToFirstNode() { // reset before starting traversal this->Internals->Clear(); this->Internals->SetMode( this->TraversalMode ); this->CurrentNode = 0; if (!this->BaseNode) { vtkErrorMacro("Unable to init traversal; BaseNode must be set!"); return; } this->InitTraversalTime = this->GetMTime(); if (this->IncludeBaseNode) { this->Internals->AddNode(this->BaseNode, 0); } else if (this->MaximumTraversalDepth > 0) { this->CurrentDepth = 0; this->BaseNode->AddChildren( this ); } this->GoToNextNode(); } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeIterator::GoToNextNode() { this->CurrentNode = 0; // if the iterator has changed since starting traversal, clear the CurrentNode // I'm allowing the Pattern to change during traversal, thus NOT checking // (this->PatternNode && this->InitTraversalTime < this->PatternNode->GetMTime())) if (this->InitTraversalTime < this->GetMTime()) { this->Internals->Clear(); return; } vtkKWEObjectTreeNodeBase *candidateNode; while (!this->CurrentNode) { // If Container is empty... we're done (and CurrentNode will equal 0) if (this->Internals->IsEmpty()) { return; } // grab the node at the front of the container and pop it off the container this->Internals->NextNode(candidateNode, this->CurrentDepth); // If the candidate node exists and we are traversing beyond its depth, // add its children if (candidateNode && this->CurrentDepth < this->MaximumTraversalDepth) { candidateNode->AddChildren( this ); } // node has to exist (non-NULL) and match the PatternNode (if set) to be // the CurrentNode; othersie, "throw it away" and keep looking if (candidateNode && (!this->PatternNode || candidateNode->IsEqualTo(this->PatternNode, false, true, this->ConsiderInheritedProperties))) { this->CurrentNode = candidateNode; } } } //----------------------------------------------------------------------------- bool vtkKWEObjectTreeNodeIterator::IsDoneWithTraversal() { return this->CurrentNode ? false : true; } // --------------------------------------------------------------------------- vtkKWEObjectTreeNodeBase *vtkKWEObjectTreeNodeIterator::GetCurrentNode() { return this->CurrentNode; } // --------------------------------------------------------------------------- // Description: // Return the traversal mode as a descriptive character string. const char *vtkKWEObjectTreeNodeIterator::GetTraversalModeAsString() { switch (this->TraversalMode) { case DEPTH_FIRST: return "Depth-first"; case BREADTH_FIRST: return "Breadth-first"; } return "Unrecognized"; } // --------------------------------------------------------------------------- void vtkKWEObjectTreeNodeIterator::AddChildren(vtkstd::vector &children) { this->Internals->AddNodes(children, this->CurrentDepth + 1); } // --------------------------------------------------------------------------- void vtkKWEObjectTreeNodeIterator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "TraversalMode: " << this->GetTraversalModeAsString() << "\n"; os << indent << "IncludeBaseNode: " << (this->IncludeBaseNode ? "On\n" : "Off\n"); os << indent << "ConsiderInheritedProperties: " << (this->ConsiderInheritedProperties ? "On\n" : "Off\n"); os << indent << "MaximumTraversalDepth: " << this->MaximumTraversalDepth << "\n"; } vtkedge-0.2.0~20110819/Filtering/CMakeLists.txt0000644000175000017500000000763111363410610020525 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # IO is required! # ----------------------------------------------------------------------------- if(NOT VTKEdge_BUILD_IO_KIT) message(FATAL_ERROR "VTKEdge_BUILD_Filtering_KIT requires VTKEdge_BUILD_IO_KIT.") endif(NOT VTKEdge_BUILD_IO_KIT) # ----------------------------------------------------------------------------- # Set of basic source files # ----------------------------------------------------------------------------- set(KIT_SRCS vtkKWEObjectTreePropertyBase.cxx vtkKWEObjectTreeTransformableNode.cxx vtkKWEObjectTreeUserProperty.cxx vtkKWEObjectTreeNodeBase.cxx vtkKWEObjectTreeNodeIterator.cxx vtkKWEObjectTreeColorProperty.cxx ) set_source_files_properties( vtkKWEObjectTreePropertyBase ABSTRACT ) # ----------------------------------------------------------------------------- # List the source files that should not be wrapped. # ----------------------------------------------------------------------------- #SET_SOURCE_FILES_PROPERTIES( # # WRAP_EXCLUDE) # ----------------------------------------------------------------------------- # List the kits from VTK that are needed by this project # ----------------------------------------------------------------------------- set(KIT_LIBS vtkKWEIO ) # ----------------------------------------------------------------------------- # Setup vtkInstantiator registration for this library's classes. # THIS IS REQUIRED FOR THE SERIALIZATION TO WORK # ----------------------------------------------------------------------------- INCLUDE(${VTK_CMAKE_DIR}/vtkMakeInstantiator.cmake) VTK_MAKE_INSTANTIATOR3(vtkKWEFilteringInstantiator FilteringInstantiatorFiles "${KIT_SRCS}" VTK_EXPORT "${CMAKE_CURRENT_BINARY_DIR}" "") # ----------------------------------------------------------------------------- # Create the library # ----------------------------------------------------------------------------- add_library(vtkKWEFiltering ${KIT_SRCS} ${KIT_EXTRA_SRCS} ${FilteringInstantiatorFiles}) target_link_libraries(vtkKWEFiltering ${KIT_LIBS}) # ----------------------------------------------------------------------------- # Testing # ----------------------------------------------------------------------------- if(BUILD_TESTING) add_subdirectory(Testing) endif(BUILD_TESTING) # ----------------------------------------------------------------------------- # Installation # ----------------------------------------------------------------------------- if(NOT VTKEdge_INSTALL_NO_LIBRARIES) install_targets( ${VTKEdge_INSTALL_LIB_DIR} RUNTIME_DIRECTORY ${VTKEdge_INSTALL_BIN_DIR} vtkKWEFiltering ) endif(NOT VTKEdge_INSTALL_NO_LIBRARIES) if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_INCLUDE_DIR} .h ${KIT_SRCS}) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) # ----------------------------------------------------------------------------- # This make it easy for other projects to get the list of files etc. in this # kit. # ----------------------------------------------------------------------------- include(${VTK_CMAKE_DIR}/vtkExportKit.cmake) vtk_export_kit2("KWEFiltering" "KWEFILTERING" ${CMAKE_CURRENT_BINARY_DIR} "${KIT_SRCS}") vtkedge-0.2.0~20110819/Filtering/vtkKWEObjectTreeTransformableNode.cxx0000644000175000017500000001313511363410610025155 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEObjectTreeTransformableNode.h" #include "vtkKWESerializer.h" #include "vtkObjectFactory.h" #include "vtkTransform.h" #include vtkCxxRevisionMacro(vtkKWEObjectTreeTransformableNode, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEObjectTreeTransformableNode); vtkCxxSetObjectMacro(vtkKWEObjectTreeTransformableNode, Transform, vtkTransform); class vtkKWEObjectTreeTransformableNodeReferencingNodes : public vtkstd::set< vtkKWEObjectTreeTransformableNode* > { }; //----------------------------------------------------------------------------- vtkKWEObjectTreeTransformableNode::vtkKWEObjectTreeTransformableNode() { this->Transform = 0; this->ReferencingNodes = new vtkKWEObjectTreeTransformableNodeReferencingNodes; } //----------------------------------------------------------------------------- vtkKWEObjectTreeTransformableNode::~vtkKWEObjectTreeTransformableNode() { this->SetTransform(0); delete this->ReferencingNodes; } //----------------------------------------------------------------------------- unsigned long vtkKWEObjectTreeTransformableNode::GetMTime() { unsigned long mTime = this->Superclass::GetMTime(); if (this->Transform && this->Transform->GetMTime() > mTime) { mTime = this->Transform->GetMTime(); } return mTime; } //----------------------------------------------------------------------------- void vtkKWEObjectTreeTransformableNode::UpdateTreeModifiedTime(unsigned long treeTime) { if (this->TreeModifiedTime == treeTime) { return; } this->Superclass::UpdateTreeModifiedTime(treeTime); // iterate through referencing nodes, pushing the treeTime up their tree vtkKWEObjectTreeTransformableNodeReferencingNodes::const_iterator refIterator; for (refIterator = this->ReferencingNodes->begin(); refIterator != this->ReferencingNodes->end(); refIterator++) { (*refIterator)->UpdateTreeModifiedTime(treeTime); } } // --------------------------------------------------------------------------- bool vtkKWEObjectTreeTransformableNode::IsEqualTo(vtkKWEObjectTreeNodeBase *testNode, bool checkDescendants, bool canBeSuperset/*=false*/, bool considerInheritedProperties/*=false*/) { if (!this->Superclass::IsEqualTo(testNode, checkDescendants, canBeSuperset, considerInheritedProperties)) { return false; } vtkKWEObjectTreeTransformableNode *transformableTestNode = vtkKWEObjectTreeTransformableNode::SafeDownCast(testNode); // if the testNode is NOT a vtkKWEObjectTreeTransformableNode, then only should // have gotten here if canBeSuperset == true. if (!transformableTestNode) { if (!canBeSuperset) { vtkErrorMacro("Unexpected node type - must be logic error in base class IsEqualTo!"); return false; } // so, canBeSuperset==true as expected... and it is just that, a superset return true; } // if canBeSuperset==true and there is no transform on the testNode, then // regardless of whether we have a transform or not we pass this equality test; // Also test possiblity that transforms share same ptr (including NULL) if ((canBeSuperset && !transformableTestNode->Transform) || transformableTestNode->Transform == this->Transform) { return true; } if (this->Transform && transformableTestNode->Transform) { // compare the transforms value by value for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (this->Transform->GetMatrix()->GetElement(i,j) != transformableTestNode->Transform->GetMatrix()->GetElement(i,j)) { return false; } } } } else // one is Null, other is not and we're not in "canBeSuperset" situation { return false; } return true; } //----------------------------------------------------------------------------- void vtkKWEObjectTreeTransformableNode::Serialize(vtkKWESerializer* ser) { this->Superclass::Serialize(ser); if (ser->IsWriting()) { if (this->Transform) { vtkObject *transform = this->Transform; ser->Serialize("Transform", transform); } } if (!ser->IsWriting()) { if (this->Transform) { this->Transform->UnRegister( this ); this->Transform = 0; } // the object is registered during serialization vtkObject *transform = 0; ser->Serialize("Transform", transform); this->Transform = vtkTransform::SafeDownCast(transform); } } // --------------------------------------------------------------------------- void vtkKWEObjectTreeTransformableNode::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Transform: "; if (this->Transform) { os << this->Transform << "\n"; } else { os << "(none)\n"; } } vtkedge-0.2.0~20110819/Filtering/Testing/0000755000175000017500000000000011630434664017407 5ustar mathieumathieuvtkedge-0.2.0~20110819/Filtering/Testing/Cxx/0000755000175000017500000000000011630434664020151 5ustar mathieumathieuvtkedge-0.2.0~20110819/Filtering/Testing/Cxx/CMakeLists.txt0000644000175000017500000000443011363410610022676 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Name this kit - this will be used to form test executable names later # Then we'll add in tests with various data or kit dependencies to the # test executables # ----------------------------------------------------------------------------- set(KIT Filtering) set(TESTBASE ${PROJECT_NAME}${KIT}) include_directories("${VTKEdge_SOURCE_DIR}/Examples/Filtering/Cxx") include_directories(${VTKEdge_BINARY_DIR}/Filtering) # ----------------------------------------------------------------------------- # First, list all the tests that either use no data, or only data from the # VTKEdge data directory (which always exists since it is part of the # VTKEdge repository). These will go into one test executable. # ----------------------------------------------------------------------------- set(MyTests TestObjectTree ) create_test_sourcelist(Tests ${TESTBASE}CxxTests.cxx ${MyTests} EXTRA_INCLUDE vtkTestDriver.h ) add_executable(${TESTBASE}CxxTests ${Tests}) #install_targets(${VTKEdge_INSTALL_BIN_DIR} ${TESTBASE}CxxTests) target_link_libraries(${TESTBASE}CxxTests vtkKWEFiltering vtkKWERendering) set(TestsToRun ${Tests}) remove(TestsToRun ${TESTBASE}CxxTests.cxx) # Add all the executables foreach(test ${TestsToRun}) get_filename_component(TName ${test} NAME_WE) add_test(${TName} ${CXX_TEST_PATH}/${TESTBASE}CxxTests ${TName} -D ${PROJECT_SOURCE_DIR}/Data -T ${PROJECT_BINARY_DIR}/Testing/Temporary -V ${PROJECT_SOURCE_DIR}/Data/Baseline/${KIT}/${TName}.png ) endforeach(test) vtkedge-0.2.0~20110819/Filtering/Testing/Cxx/TestObjectTree.cxx0000644000175000017500000000271011363410610023547 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #define KWE_TESTING #include "ObjectTreeDemo.cxx" #undef KWE_TESTING #include int TestObjectTree(int argc, char *argv[]) { char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/ObjectTree.xml"); vtkstd::string filename = fname; if (fname) { delete [] fname; } filename = "--input=" + filename; char** new_argv = new char*[argc+1]; for (int cc=0; cc < argc; cc++) { new_argv[cc] = vtksys::SystemTools::DuplicateString(argv[cc]); } new_argv[argc++] = vtksys::SystemTools::DuplicateString(filename.c_str()); int status = ::ObjectTreeDemo(argc, new_argv); for (int kk=0; kk < argc; kk++) { delete [] new_argv[kk]; } delete [] new_argv; return status; } vtkedge-0.2.0~20110819/Filtering/Testing/CMakeLists.txt0000644000175000017500000000166011363410610022136 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Add the Cxx testing directory # ----------------------------------------------------------------------------- add_subdirectory(Cxx) vtkedge-0.2.0~20110819/Filtering/vtkKWEObjectTreePropertyBase.h0000644000175000017500000001216311363410610023614 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEObjectTreePropertyBase - Base class for ObjectTree Properties // .SECTION Description // vtkKWEObjectTreePropertyBase is the base class for Properties to be added // to ObjectTree nodes, providing a container for the Properties "Attributes", // a container for nodes that reference this object (so the nodes can be // nodified when the property changes) and a general GetKey() method to // retrieve a concrete subclass's KEY(). The Modified() method updates the // TreeMTime of all referencing nodes and thus should be called by subclasses // whenever changes are made to values. // // As a subclass of vtkKWESerializableObject, the Attributes are // easily serialized. Furthermore, the subclass does not need to worry // about serialization. // // Properties of a node can be inherited by decendants unless the Property // is set to NOT be inheritable (IsInheritableOff()). // // .SECTION See Also #ifndef __vtkKWEObjectTreePropertyBase_h #define __vtkKWEObjectTreePropertyBase_h #include "vtkKWESerializableObject.h" #include "VTKEdgeConfigure.h" // include configuration header class vtkInformation; class vtkInformationIntegerKey; class vtkInformationObjectBaseKey; class vtkKWEObjectTreeNodeBase; class vtkKWEObjectTreePropertyBaseReferencingNodes; class vtkKWESerializer; class VTKEdge_FILTERING_EXPORT vtkKWEObjectTreePropertyBase : public vtkKWESerializableObject { public: vtkTypeRevisionMacro(vtkKWEObjectTreePropertyBase, vtkKWESerializableObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Reads the state of an instance from an archive OR // writes the state of an instance to an archive. virtual void Serialize(vtkKWESerializer* ser); // Description: // When we get modified, update the TreeModifiedTime of nodes that // reference us. Note, subclasses needed to call this after // making changes to the Attributes object. virtual void Modified(); // Description: // Retrieve the KEY from a concrete subclass virtual vtkInformationObjectBaseKey *GetKey() = 0; // Description: // Is "this" the same as testProperty (same Attributes)? If canBeSuperset // == true, then can be considered equal if the only difference is that // "this" has additional attributes. virtual bool IsEqualTo(vtkKWEObjectTreePropertyBase *testProperty, bool canBeSuperset = false); // Description: // Return the number of attributes that have been set for this Property. int GetNumberOfAttributes(); // Description: // Set/Get whether this Property is inherited by it's descendants. // By default it is set to be "true". Also, if unset, it will return // true. However, if two properties are otherwise equal, they will // NOT be considered to be equal if one Property (A) has the value set // to true while the other Property (B) doesn't have the value set... unless, // A->IsEqualTo(B, true)... A can be a superset of B. This is actually why // unsetting of the value is allowed, so that the value can be unset in a // PatternNode given to the iterator: the iteration result will then not // depend on this value. static vtkInformationIntegerKey* IS_INHERITABLE(); void IsInheritableOn() { this->SetIsInheritable(true); } void IsInheritableOff() { this->SetIsInheritable(false); } bool IsInheritable() { return this->GetIsInheritable(); } bool GetIsInheritable(); void SetIsInheritable(bool isInheritable); // Description: // Unset the IS_INHERITABLE() key. Note, GetIsInheritable() will return true // if it is Unset. If the key is Unset, a PatternNode of an iterator can be // used to iterate over nodes comparing/filtering based on a property without // the result depending on whether the Property IsHeritable or not. void UnsetIsInheritable(); protected: vtkKWEObjectTreePropertyBase(); virtual ~vtkKWEObjectTreePropertyBase(); // Description: // The main object that object attributes("properties") are stored in vtkInformation *Attributes; // Description: // Add/Remove from our set of nodes that use the Property object. friend class vtkKWEObjectTreeNodeBase; void AddReferencingNode(vtkKWEObjectTreeNodeBase *node); void RemoveReferencingNode(vtkKWEObjectTreeNodeBase *node); vtkKWEObjectTreePropertyBaseReferencingNodes *ReferencingNodes; private: vtkKWEObjectTreePropertyBase(const vtkKWEObjectTreePropertyBase&); // Not implemented. void operator=(const vtkKWEObjectTreePropertyBase&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Filtering/vtkKWEObjectTreeColorProperty.cxx0000644000175000017500000000433611363410610024376 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEObjectTreeColorProperty.h" #include "vtkInformation.h" #include "vtkInformationDoubleVectorKey.h" #include "vtkInformationObjectBaseKey.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkKWEObjectTreeColorProperty, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEObjectTreeColorProperty); vtkInformationKeyRestrictedMacro(vtkKWEObjectTreeColorProperty, COLOR, DoubleVector, 3); vtkInformationKeyMacro(vtkKWEObjectTreeColorProperty, KEY, ObjectBase); //----------------------------------------------------------------------------- double *vtkKWEObjectTreeColorProperty::GetColor() { return this->Attributes->Get(COLOR()); } //----------------------------------------------------------------------------- void vtkKWEObjectTreeColorProperty::SetColor(double *color) { double *currentColor = this->GetColor(); if (!currentColor || currentColor[0] != color[0] || currentColor[1] != color[1] || currentColor[2] != color[2]) { this->Attributes->Set(COLOR(), color, 3); this->Modified(); } } // --------------------------------------------------------------------------- void vtkKWEObjectTreeColorProperty::PrintSelf(ostream& os, vtkIndent indent) { os << indent << this->GetClassName() << "\n"; this->Superclass::PrintSelf(os,indent); if (this->Attributes->Has(COLOR())) { double *color = this->GetColor(); os << indent << "Color: (" << color[0] << ", " << color[1] << ", " << color[2] << ")\n"; } else { os << indent << "Color: (not set)\n"; } } vtkedge-0.2.0~20110819/Filtering/vtkKWEObjectTreeNodeIterator.h0000644000175000017500000002257111363410610023600 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEObjectTreeNodeIterator - Iterator for nodes in an ObjectTree // .SECTION Description // vtkKWEObjectTreeNodeIterator is an iterator for nodes in an ObjectTree. The // iterator can be set to depth-first or breadth-first, to include the BaseNode // or not, and to only consider nodes up to a maximum dpeth from the BaseNode. // Additionally, a PatternNode can be sepcified which will act as a filter // controlling which nodes in the tree will be iterated over. Matching nodes // can be a superset of the PatternNode, but whatever Attributes and Properties // (as well as node type and the type of the node in the object) are specified // on the PatternNode must exist and have matching values in the nodes be // considered for iteration. // // To use this iterator, SetBaseNode() and then either InitTraversal() or // GoToFirstNode(). GetCurrentNode() can then be called to retrieve the // top/current node in the iterator. Repeated calls to GoToNextNode followed by // GetCurrentNode can be made to move through the values being iterated over // (and GetCurrentDepth can be called to get the depth of the current node // realtive to the BaseNode; 0 - BaseNode, 1 - children of BaseNode, etc) // When the value of GetCurrentNode is NULL, iteration is complete. Note that // values pushed onto the internal stack of the iterator are vtkWeakPointers, // and thus COULD become NULL during iteration. However, GoToNextNode() will // skip over NULL values. CurrentNode is a vtkSmartPointer, and thus will not // become invalid unless done so by the iterator (setting it to NULL). // // A simple example: // \code // vtkSmartPointer iterator = // vtkSmartPointer::New(); // iterator->SetBaseNode( root ); // iterator->SetTraversalToEntireSubtree(); // iterator->SetTraversalModeToDepthFirst(); // // // only interested in nodes that have a "user" property, though we don't // // care about the contents of the user property. // vtkSmartPointer patternNode = // vtkSmartPointer::New(); // vtkSmartPointer userProp = // vtkSmartPointer::New(); // patternNode->AddProperty(userProp); // iterator->SetPatternNode( patternNode ); // for (iterator->InitTraversal(); // (currentNode = iterator->GetCurrentNode()); iterator->GoToNextNode()) // { // // do something // } // \endcode // // NOTE: A 2nd call to InitTraversal() or GoToFirstNode() clears the // existing contents and starts iteration again based on the current tree // structure. Thus, the 2nd (or subsequent) iterations may not give the same // results (if the ObjectTree has changed). // // Also, changes made to the iterater (changing the value of a member variable) // result in clearing the iteration. InitiTraversal or GoToFirstNode must be // called to start the iteration over. Note, however, that the PatternNode // CAN be changed without requireing restarting the iteration (though nodes // already passed-over in the tree because they didn't match the PatternNode // but which might now match, will not be reconsidered) // // .SECTION See Also #ifndef __vtkKWEObjectTreeNodeIterator_h #define __vtkKWEObjectTreeNodeIterator_h #include "vtkObject.h" #include "vtkSmartPointer.h" #include "VTKEdgeConfigure.h" // include configuration header #include class vtkKWEObjectTreeNodeBase; class vtkKWEObjectTreeNodeIteratorInternals; class VTKEdge_FILTERING_EXPORT vtkKWEObjectTreeNodeIterator : public vtkObject { public: static vtkKWEObjectTreeNodeIterator* New(); vtkTypeRevisionMacro(vtkKWEObjectTreeNodeIterator, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set/Get the BaseNode from which to fill the iterator void SetBaseNode(vtkKWEObjectTreeNodeBase* baseNode); vtkGetObjectMacro(BaseNode, vtkKWEObjectTreeNodeBase); // Description: // Set/Get the PatternNode; if set, only nodes matching the PatternNode // will be iterated over. Note: nodes can be a superset of this node but must // match Atttributes, Properties, and Object type (actual object not compared) // set on the Pattern node void SetPatternNode(vtkKWEObjectTreeNodeBase* patternNode); vtkGetObjectMacro(PatternNode, vtkKWEObjectTreeNodeBase); // Description: // Clear stack/iterator and then initialize the stack with the children of // the BaseNode, setting CurrentNode to be the 1st of these children. // Same as GoToFirstNode. void InitTraversal() { this->GoToFirstNode(); }; // Description: // Clear stack/iterator and then initialize the stack with the children of // the BaseNode, setting CurrentNode to be the 1st of these children. // Same as InitTraversal. void GoToFirstNode(); // Description: // Sets the value of CurrentNode to be the next non-zero value in the // iterator. If empty or only NULL values, the CurrentNode is set to NULL. void GoToNextNode(); // Description: // Returns pointer to the current node in the iteration. To iterate // through the nodes: InitTraversal(), GetCurrentNode(), GoToNextNode(), // GetCurrentNode(), GoToNextNode(), etc. until GetCurrentNode returns a NULL // pointer. CurrentNode is a SmartPointer and thus is protected from // destruction elsewhere in the application. vtkKWEObjectTreeNodeBase *GetCurrentNode(); // Description: // Get the depth (relative to the BaseNode) of the current node . 0 is the // BaseNode level, 1 would be children of the base node, etc. The value is // only valid if CurrentNode is non-NULL; vtkGetMacro(CurrentDepth, int); // Description: // Test whether the iterator is currently positioned at a valid item. bool IsDoneWithTraversal(); // Description: // Set/Get whether the BaseNode is included (considered) during traversal. vtkBooleanMacro(IncludeBaseNode, bool); vtkSetMacro(IncludeBaseNode, bool); vtkGetMacro(IncludeBaseNode, bool); // Description: // Set/Get the maximum depth for traversal vtkSetClampMacro(MaximumTraversalDepth, int, 0, VTK_LARGE_INTEGER); vtkGetMacro(MaximumTraversalDepth, int); // Description: // Convenience method for setting iterator to only consider the children // of the BaseNode (BaseNode NOT traversed). void SetTraversalToChildrenOnly() { this->SetMaximumTraversalDepth(1); this->IncludeBaseNodeOff(); } // Description: // Convenience method for setting iterator to consider the entier subtree // of the BaseNode (BaseNode is included) void SetTraversalToEntireSubtree() { this->SetMaximumTraversalDepth(VTK_LARGE_INTEGER); this->IncludeBaseNodeOn(); } enum TraversalModes { DEPTH_FIRST = 0, BREADTH_FIRST }; // Description: // Set/Get whether the tree is iterated over depth-first or breadth-first. void SetTraversalModeToDepthFirst() { this->SetTraversalMode( DEPTH_FIRST ); } void SetTraversalModeToBreadthFirst() { this->SetTraversalMode( BREADTH_FIRST ); } vtkSetClampMacro(TraversalMode, int, DEPTH_FIRST, BREADTH_FIRST); vtkGetMacro(TraversalMode, int); const char *GetTraversalModeAsString(); // Description: // Set/Get whether inherited properties are considered when // comparing to a PatternNode. By default this is off (only properties // actually set on the node are compared) vtkBooleanMacro(ConsiderInheritedProperties, bool); vtkSetMacro(ConsiderInheritedProperties, bool); vtkGetMacro(ConsiderInheritedProperties, bool); protected: vtkKWEObjectTreeNodeIterator(); virtual ~vtkKWEObjectTreeNodeIterator(); vtkKWEObjectTreeNodeBase *BaseNode; vtkKWEObjectTreeNodeBase *PatternNode; vtkSmartPointer CurrentNode; vtkKWEObjectTreeNodeIteratorInternals *Internals; // Description: // Is the BaseNode included in the traversal? bool IncludeBaseNode; // Description: // Time at which we started traversal unsigned long InitTraversalTime; friend class vtkKWEObjectTreeNodeBase; void AddChildren(vtkstd::vector &children); // Description: // Depth (relative to BaseNode) of the CurrentNode int CurrentDepth; // Description: // The maximum depth (relative to BaseNode) of traversal int MaximumTraversalDepth; // Description: // Depth-first versus breadth-first int TraversalMode; // Description: // During comparison the a PatternNode can the node inherit the property // to achieve a match bool ConsiderInheritedProperties; // internal method for clearing the stack void Clear(); private: vtkKWEObjectTreeNodeIterator(const vtkKWEObjectTreeNodeIterator&); // Not implemented. void operator=(const vtkKWEObjectTreeNodeIterator&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Filtering/vtkKWEObjectTreeNodeBase.cxx0000644000175000017500000006360311363410610023235 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEObjectTreeNodeBase.h" #include "vtkInformation.h" #include "vtkInformationIntegerKey.h" #include "vtkInformationIterator.h" #include "vtkInformationObjectBaseKey.h" #include "vtkInformationStringKey.h" #include "vtkKWEUUID.h" #include "vtkKWEObjectTreePropertyBase.h" #include "vtkKWESerializer.h" #include "vtkKWEObjectTreeNodeIterator.h" #include "vtkObjectFactory.h" #include vtkCxxRevisionMacro(vtkKWEObjectTreeNodeBase, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEObjectTreeNodeBase); vtkInformationKeyMacro(vtkKWEObjectTreeNodeBase, NAME, String); vtkInformationKeyMacro(vtkKWEObjectTreeNodeBase, UUID, String); vtkInformationKeyMacro(vtkKWEObjectTreeNodeBase, STATE, Integer); vtkInformationKeyMacro(vtkKWEObjectTreeNodeBase, INHERIT_PROPERTIES, Integer); // PIMPL class vtkKWEObjectTreeNodeBaseChildren : public vtkstd::vector< vtkSmartPointer > { }; //----------------------------------------------------------------------------- vtkKWEObjectTreeNodeBase::vtkKWEObjectTreeNodeBase() { this->Parent = 0; this->NodeObject = 0; this->Attributes = vtkInformation::New(); this->Properties = vtkInformation::New(); this->TreeModifiedTime = 0; this->Children = new vtkKWEObjectTreeNodeBaseChildren; this->SetStateToActive(); this->InheritPropertiesOn(); } //----------------------------------------------------------------------------- vtkKWEObjectTreeNodeBase::~vtkKWEObjectTreeNodeBase() { // visit children and tell them they no longer have a parent ("someone" else, // may be holding on to the child as a tree on it's own, but we need to tell // it it no longer has a parent) vtkKWEObjectTreeNodeBaseChildren::const_iterator childIterator; for (childIterator = this->Children->begin(); childIterator != this->Children->end(); childIterator++) { (*childIterator)->SetParent(0); } delete this->Children; this->SetParent(0); this->SetNodeObject(0); this->Attributes->Delete(); this->RemoveAllPropertiesInternal(); this->Properties->Delete(); } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::SetNodeObject(vtkObject *object) { if (this->NodeObject == object) { return; } if ( vtkKWEObjectTreeNodeBase::SafeDownCast(object) ) { vtkErrorMacro("Setting the object to be an ObjectTreeNode is NOT allowed. Use a vtkKWEObjectTreeReferenceNode to achieve a similar result!"); return; } if (this->NodeObject) { this->NodeObject->UnRegister( this ); } this->NodeObject = object; if (this->NodeObject) { this->NodeObject->Register( this ); } this->Modified(); } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::SetParent(vtkKWEObjectTreeNodeBase *parent) { if (this->Parent == parent) { return; } // we shouldn't be calling this if we already have a parent, but just in case if (this->Parent && parent) { vtkErrorMacro("Can't set parent; already has parent"); return; } this->Parent = parent; this->Modified(); } //----------------------------------------------------------------------------- unsigned int vtkKWEObjectTreeNodeBase::GetNumberOfChildren() { return static_cast(this->Children->size()); } //----------------------------------------------------------------------------- vtkKWEObjectTreeNodeBase *vtkKWEObjectTreeNodeBase::GetChild(unsigned int index) { if (index >= this->Children->size()) { vtkErrorMacro("Invalid child index!"); return 0; } return this->Children->at(index); } //----------------------------------------------------------------------------- int vtkKWEObjectTreeNodeBase::AddChild(vtkKWEObjectTreeNodeBase *childNode) { // test for parent usefule in preventing cycles as well as guaranteeing the // child is unique (if childNode is already a child of "this", then it // will have a parent, and we don't add childNode if it alrady has a parent) if (childNode->GetParent()) { vtkErrorMacro("Unable to add child because it already has a parent!"); return -1; } if (childNode->IsDescendant(this)) { vtkErrorMacro("Unable to add child because a cycle would be created!"); return -1; } this->Children->push_back(childNode); childNode->SetParent(this); this->Modified(); return static_cast(this->Children->size() - 1); } //----------------------------------------------------------------------------- int vtkKWEObjectTreeNodeBase::InsertChild(unsigned int index, vtkKWEObjectTreeNodeBase *childNode) { // test for parent usefule in preventing cycles as well as guaranteeing the // child is unique (if childNode is already a child of "this", then it // will have a parent, and we don't add childNode if it alrady has a parent) if (childNode->GetParent()) { vtkErrorMacro("Unable to add child because it already has a parent!"); return 0; } if (childNode->IsDescendant(this)) { vtkErrorMacro("Unable to add child because a cycle would be created!"); return 0; } if (static_cast(index) > this->Children->size()) { vtkErrorMacro( "Unable to add child because the index is out of range: " << index ); return 0; } this->Children->insert( this->Children->begin() + index, childNode); childNode->SetParent(this); this->Modified(); return 1; } //----------------------------------------------------------------------------- int vtkKWEObjectTreeNodeBase::RemoveChild(vtkKWEObjectTreeNodeBase *childNode) { int index = 0; vtkKWEObjectTreeNodeBaseChildren::iterator childIterator; for (childIterator = this->Children->begin(); childIterator != this->Children->end(); childIterator++, index++) { if (*childIterator == childNode) { childNode->SetParent(0); this->Children->erase(childIterator); this->Modified(); return index; } } return -1; } //----------------------------------------------------------------------------- int vtkKWEObjectTreeNodeBase::RemoveChild(unsigned int index) { if (static_cast(index) >= this->Children->size()) { vtkErrorMacro( "Unable to remove child because the index is out of range: " << index ); return 0; } this->Children->erase( this->Children->begin() + index ); this->Modified(); return 1; } //----------------------------------------------------------------------------- int vtkKWEObjectTreeNodeBase::GetNumberOfProperties() { return this->GetNumberOfInformationEntries( this->Properties ); } //----------------------------------------------------------------------------- int vtkKWEObjectTreeNodeBase::GetNumberOfInformationEntries(vtkInformation *infoObject) { vtkSmartPointer infoIterator = vtkSmartPointer::New(); infoIterator->SetInformation( infoObject ); int numberOfInfoValues = 0; for (infoIterator->InitTraversal(); !infoIterator->IsDoneWithTraversal(); infoIterator->GoToNextItem()) { numberOfInfoValues++; } return numberOfInfoValues; } //----------------------------------------------------------------------------- int vtkKWEObjectTreeNodeBase::AddProperty(vtkKWEObjectTreePropertyBase *nodeProperty) { if ( this->Properties->Has(nodeProperty->GetKey()) ) { return 0; } this->Properties->Set(nodeProperty->GetKey(), nodeProperty); nodeProperty->AddReferencingNode(this); this->Modified(); return 1; } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::GetAllProperties(vtkInformation *allProperties) { if (!allProperties) { vtkErrorMacro("Must pass in valid vtkInformation object"); return; } // make sure empty to start allProperties->Clear(); // copy the "local" (non-inherited) Properties allProperties->Copy(this->Properties); if (this->CanInheritProperties() && this->Parent) { this->Parent->AddInheritedProperties( allProperties ); } } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::AddInheritedProperties(vtkInformation *allProperties) { vtkInformationObjectBaseKey *key; vtkKWEObjectTreePropertyBase *tmpProperty; // iterate through all our "local" properties; add to allProperties if not // already in allProperties AND inheritable vtkSmartPointer propertyIterator = vtkSmartPointer::New(); propertyIterator->SetInformation( this->Properties ); for (propertyIterator->InitTraversal(); !propertyIterator->IsDoneWithTraversal(); propertyIterator->GoToNextItem()) { key = vtkInformationObjectBaseKey::SafeDownCast( propertyIterator->GetCurrentKey() ); if (allProperties->Has(key)) { // already has the Property, so won't inherit it continue; } tmpProperty = vtkKWEObjectTreePropertyBase::SafeDownCast( this->Properties->Get(key) ); if (tmpProperty->IsInheritable()) { allProperties->Set(key, tmpProperty); } } // if we can inherit properties, see what else is out tere if (this->CanInheritProperties() && this->Parent) { this->Parent->AddInheritedProperties( allProperties ); } } //----------------------------------------------------------------------------- vtkKWEObjectTreePropertyBase* vtkKWEObjectTreeNodeBase::GetProperty( vtkInformationObjectBaseKey *propertyKey, bool &inheritedProperty, bool includeInheritance/*=false*/) { vtkKWEObjectTreePropertyBase *requestedProperty = vtkKWEObjectTreePropertyBase::SafeDownCast( this->Properties->Get(propertyKey) ); if (requestedProperty) { inheritedProperty = false; return requestedProperty; } else if (includeInheritance && this->CanInheritProperties() && this->Parent) { requestedProperty = this->Parent->GetProperty(propertyKey, inheritedProperty, true); inheritedProperty = true; // some ancestor did have the property, but is it an inheritable property if (requestedProperty && !requestedProperty->IsInheritable()) { requestedProperty = 0; } } return requestedProperty; } //----------------------------------------------------------------------------- int vtkKWEObjectTreeNodeBase::RemoveProperty(vtkKWEObjectTreePropertyBase *nodeProperty) { return this->RemoveProperty( nodeProperty->GetKey() ); } //----------------------------------------------------------------------------- int vtkKWEObjectTreeNodeBase::RemoveProperty(vtkInformationObjectBaseKey *propertyKey) { if (this->Properties->Has(propertyKey)) { vtkKWEObjectTreePropertyBase::SafeDownCast( this->Properties->Get(propertyKey) )-> RemoveReferencingNode(this); this->Properties->Remove(propertyKey); this->Modified(); return 1; } return 0; } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::RemoveAllProperties() { if (this->RemoveAllPropertiesInternal()) { this->Modified(); } } //----------------------------------------------------------------------------- bool vtkKWEObjectTreeNodeBase::RemoveAllPropertiesInternal() { vtkSmartPointer propertyIterator = vtkSmartPointer::New(); propertyIterator->SetInformation( this->Properties ); bool hadProperties = false; vtkInformationObjectBaseKey *key; for (propertyIterator->InitTraversal(); !propertyIterator->IsDoneWithTraversal(); propertyIterator->GoToNextItem()) { hadProperties = true; key = vtkInformationObjectBaseKey::SafeDownCast( propertyIterator->GetCurrentKey() ); vtkKWEObjectTreePropertyBase::SafeDownCast( this->Properties->Get(key) )-> RemoveReferencingNode(this); } if (hadProperties) { this->Properties->Clear(); } return hadProperties; } //----------------------------------------------------------------------------- bool vtkKWEObjectTreeNodeBase::IsDescendant(vtkKWEObjectTreeNodeBase *testNode) { if (this == testNode) { return true; } vtkKWEObjectTreeNodeBaseChildren::const_iterator childIterator; for (childIterator = this->Children->begin(); childIterator != this->Children->end(); childIterator++) { if ((*childIterator)->IsDescendant(testNode)) { return true; } } return false; } //----------------------------------------------------------------------------- // Create a UUID for this node (if it doesn't already exist). Returns 1 // on success (or already exists) int vtkKWEObjectTreeNodeBase::CreateUUID() { if (this->Attributes->Has(UUID())) { return 0; } int retValue = 1; unsigned char uuid[16]; if (vtkKWEUUID::GenerateUUID(uuid) == -1) { vtkKWEUUID::ConstructUUID(uuid); retValue = 2; } vtkstd::string uuidString; vtkKWEUUID::ConvertBinaryUUIDToString(uuid, uuidString); this->SetUUID(uuidString.c_str()); return retValue; } //----------------------------------------------------------------------------- // Returns the UUID for this node. The UUID is not created until requested. const char *vtkKWEObjectTreeNodeBase::GetUUID() { return this->Attributes->Get(UUID()); } //----------------------------------------------------------------------------- // Sets the UUID for this node. void vtkKWEObjectTreeNodeBase::SetUUID(const char *uuid) { this->Attributes->Set(UUID(), uuid); } //----------------------------------------------------------------------------- // Returns the UUID for this node. The UUID is not created until requested. void vtkKWEObjectTreeNodeBase::ClearUUID() { return this->Attributes->Remove(UUID()); } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::SetName(const char *name) { this->Attributes->Set(NAME(), name); } //----------------------------------------------------------------------------- const char *vtkKWEObjectTreeNodeBase::GetName() { return this->Attributes->Get(NAME()); } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::SetState(int nodeState) { this->Attributes->Set(STATE(), nodeState); } //----------------------------------------------------------------------------- int vtkKWEObjectTreeNodeBase::GetState() { return this->Attributes->Get(STATE()); } // --------------------------------------------------------------------------- // Description: // Return the state as a descriptive character string. const char *vtkKWEObjectTreeNodeBase::GetStateAsString(void) { switch (this->GetState()) { case ACTIVE_STATE: return "Active"; case INACTIVE_STATE: return "Inactive"; } return "Unrecognized"; } //----------------------------------------------------------------------------- bool vtkKWEObjectTreeNodeBase::GetInheritProperties() { return this->Attributes->Get(INHERIT_PROPERTIES()) ? true : false; } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::SetInheritProperties(bool inheritState) { this->Attributes->Set(INHERIT_PROPERTIES(), inheritState ? 1 : 0); } //----------------------------------------------------------------------------- unsigned long vtkKWEObjectTreeNodeBase::GetMTime() { unsigned long propMTime; unsigned long mTime = this->Superclass::GetMTime(); if (this->Attributes->GetMTime() > mTime) { mTime = this->Attributes->GetMTime(); } // consider the MTime of our Properties as well; vtkSmartPointer propertyIterator = vtkSmartPointer::New(); propertyIterator->SetInformation( this->Properties ); vtkInformationObjectBaseKey *key; for (propertyIterator->InitTraversal(); !propertyIterator->IsDoneWithTraversal(); propertyIterator->GoToNextItem()) { key = vtkInformationObjectBaseKey::SafeDownCast( propertyIterator->GetCurrentKey() ); propMTime = vtkKWEObjectTreePropertyBase::SafeDownCast( this->Properties->Get(key) )->GetMTime(); if ( propMTime > mTime ) { mTime = propMTime; } } return mTime; } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::Modified() { this->Superclass::Modified(); this->UpdateTreeModifiedTime( this->GetMTime() ); } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::UpdateTreeModifiedTime(unsigned long treeTime) { if (this->TreeModifiedTime == treeTime) { return; } this->TreeModifiedTime = treeTime; if (this->Parent) { this->Parent->UpdateTreeModifiedTime(treeTime); } } //----------------------------------------------------------------------------- bool vtkKWEObjectTreeNodeBase::IsEqualTo(vtkKWEObjectTreeNodeBase *testNode, bool checkDescendants, bool canBeSuperset/*=false*/, bool considerInheritedProperties/*=false*/) { if (!testNode) { return false; // can't be EqualTo if it doesn't exist! } // If canBeSuperset == false, must be the EXACT same type of Node to be equal; // otherwise we can be a subclass of the testNode type if ((!canBeSuperset && strcmp(this->GetClassName(), testNode->GetClassName())) || (canBeSuperset && !this->IsA(testNode->GetClassName()))) { return false; } // Do our Attributes match? if (testNode->GetState() != this->GetState()) // we always have a state! { return false; } // can be a match if the testNode does NOT have a name be we do... IF canBeSuperset == true if ((testNode->GetName() && this->GetName() && strcmp(testNode->GetName(), this->GetName())) || (!testNode->GetName() && this->GetName() && !canBeSuperset) || (testNode->GetName() && !this->GetName()) ) { return false; } // can be a match if the testNode does NOT have a UUID be we do... IF canBeSuperset == true if ((testNode->GetUUID() && this->GetUUID() && strcmp(testNode->GetUUID(), this->GetUUID())) || (!testNode->GetUUID() && this->GetUUID() && !canBeSuperset) || (testNode->GetUUID() && !this->GetUUID()) ) { return false; } // compare Objects... is only one or the other set (if so, return false, // unless canBeSuperset). if ((!testNode->NodeObject && this->NodeObject && !canBeSuperset) || (testNode->NodeObject && !this->NodeObject) || // if both objects exist, then type must match exactly if can't be superset OR // this->NodeObject only has to be an IsA (subclass of) if it can be a superset ((testNode->NodeObject && this->NodeObject) && ((!canBeSuperset && strcmp(testNode->NodeObject->GetClassName(), this->NodeObject->GetClassName())) || ((canBeSuperset && !this->NodeObject->IsA(testNode->NodeObject->GetClassName())))))) { return false; } int myNumProperties, testNumProperties; vtkSmartPointer myProperties, testNodeProperties; if (considerInheritedProperties) { // if we inherited properties are considered for the purpose of this // comparison then build a complete set of properties for this node // (include inherited properties) myProperties = vtkSmartPointer::New(); this->GetAllProperties(myProperties); myNumProperties = this->GetNumberOfInformationEntries(myProperties); testNodeProperties = vtkSmartPointer::New(); testNode->GetAllProperties(testNodeProperties); testNumProperties = testNode->GetNumberOfInformationEntries(myProperties); } else { myNumProperties = this->GetNumberOfProperties(); myProperties = this->Properties; testNumProperties = testNode->GetNumberOfProperties(); testNodeProperties = testNode->Properties; } if (myNumProperties < testNumProperties || (myNumProperties > testNumProperties && !canBeSuperset)) { // if the number of properties doesn't match, then we can't be equal... // unless "this" has more and it can be a superset of the testNode we are // comparing ourselves to return false; } // To be "equal", we must have that same set of Properties as the testNode... // and the Properties need to be equal vtkSmartPointer propertyIterator = vtkSmartPointer::New(); propertyIterator->SetInformation( testNodeProperties ); vtkInformationObjectBaseKey *key; for (propertyIterator->InitTraversal(); !propertyIterator->IsDoneWithTraversal(); propertyIterator->GoToNextItem()) { key = vtkInformationObjectBaseKey::SafeDownCast( propertyIterator->GetCurrentKey() ); vtkKWEObjectTreePropertyBase *thisProperty = vtkKWEObjectTreePropertyBase::SafeDownCast(myProperties->Get(key)); // if the Property doesn't exist in "this" then return false (not equal)... // (we know it exists in testNode since that is what we're iterating over) if (!thisProperty) { return false; } vtkKWEObjectTreePropertyBase *testProperty = vtkKWEObjectTreePropertyBase::SafeDownCast(testNodeProperties->Get(key)); // if IsEqualTo returns false, then "obviously" not equal if (!thisProperty->IsEqualTo( testProperty, canBeSuperset )) { return false; } } // finally, if we're checking descendants... do so if (checkDescendants) { // must have the same number of children if (this->GetNumberOfChildren() != testNode->GetNumberOfChildren()) { return false; } // and they must be in the same order for (unsigned int i = 0; i < this->GetNumberOfChildren(); i++) { if (!this->GetChild(i)->IsEqualTo( testNode->GetChild(i), true, canBeSuperset )) { return false; } } } return true; } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::SerializeObject(vtkKWESerializer* ser) { if (ser->IsWriting()) { if (this->NodeObject) { ser->Serialize("NodeObject", this->NodeObject); } } if (!ser->IsWriting()) { if (this->NodeObject) { this->NodeObject->UnRegister( this ); this->NodeObject = 0; } // the object is registered during serialization ser->Serialize("NodeObject", this->NodeObject); } } //----------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::Serialize(vtkKWESerializer* ser) { this->SerializeObject( ser ); ser->Serialize("Attributes", this->Attributes); ser->Serialize("Properties", this->Properties); vtkObject *parent = this->Parent; ser->Serialize("Parent", parent, true); // true indicates it is a weak ptr if (ser->IsWriting()) { vtkstd::vector< vtkSmartPointer > myVector = vtkKWESerializer::ToBase > >( *this->Children ); ser->Serialize("Children", myVector); } else { this->Parent = vtkKWEObjectTreeNodeBase::SafeDownCast(parent); vtkstd::vector< vtkSmartPointer > myVector; ser->Serialize("Children", myVector); vtkKWESerializer::FromBase(myVector, *this->Children); } } // --------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::AddChildren(vtkKWEObjectTreeNodeIterator *iterator) { vtkstd::vector children; children.insert(children.begin(), this->Children->begin(), this->Children->end()); iterator->AddChildren(children); } // --------------------------------------------------------------------------- void vtkKWEObjectTreeNodeBase::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if (this->NodeObject) { os << indent << "NodeObject: \n"; this->NodeObject->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "NodeObject: (none)\n"; } if (this->GetName()) { os << indent << "Name: " << this->GetName() << "\n"; } else { os << indent << "Name: (none)\n"; } os << indent << "STATE: " << this->GetStateAsString() << "\n"; if (this->GetUUID()) { os << indent << "UUID: " << this->GetUUID() << "\n"; } else { os << indent << "UUID: (none)\n"; } os << indent << "PROPERTIES:\n"; vtkSmartPointer propertyIterator = vtkSmartPointer::New(); propertyIterator->SetInformation( this->Properties ); vtkInformationObjectBaseKey *key; for (propertyIterator->InitTraversal(); !propertyIterator->IsDoneWithTraversal(); propertyIterator->GoToNextItem()) { key = vtkInformationObjectBaseKey::SafeDownCast( propertyIterator->GetCurrentKey() ); vtkKWEObjectTreePropertyBase::SafeDownCast( this->Properties->Get(key) )-> PrintSelf(os, indent.GetNextIndent()); } os << indent << "END PROPERTIES:\n"; // Print the children... os << indent << "CHILDREN:\n"; vtkKWEObjectTreeNodeBaseChildren::const_iterator childIterator; for (childIterator = this->Children->begin(); childIterator != this->Children->end(); childIterator++) { (*childIterator)->PrintSelf(os, indent.GetNextIndent()); } os << indent << "END CHILDREN:\n"; } vtkedge-0.2.0~20110819/Graphics/0000755000175000017500000000000011630434664015607 5ustar mathieumathieuvtkedge-0.2.0~20110819/Graphics/CMakeLists.txt0000644000175000017500000000510011363410610020327 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Set of basic source files (not the OpenGL or GLSL ones) # ----------------------------------------------------------------------------- set(KIT_SRCS ) # ----------------------------------------------------------------------------- # List the kits from VTK that are needed by this project # ----------------------------------------------------------------------------- set(KIT_LIBS vtkGraphics ) # ----------------------------------------------------------------------------- # Create the library # ----------------------------------------------------------------------------- add_library(vtkKWEGraphics ${KIT_SRCS}) target_link_libraries(vtkKWEGraphics ${KIT_LIBS}) # ----------------------------------------------------------------------------- # Testing # ----------------------------------------------------------------------------- if(BUILD_TESTING) add_subdirectory(Testing) endif(BUILD_TESTING) # ----------------------------------------------------------------------------- # Installation # ----------------------------------------------------------------------------- if(NOT VTKEdge_INSTALL_NO_LIBRARIES) install_targets( ${VTKEdge_INSTALL_LIB_DIR} RUNTIME_DIRECTORY ${VTKEdge_INSTALL_BIN_DIR} vtkKWEGraphics ) endif(NOT VTKEdge_INSTALL_NO_LIBRARIES) if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_INCLUDE_DIR} .h ${KIT_SRCS}) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) # ----------------------------------------------------------------------------- # This make it easy for other projects to get the list of files etc. in this # kit. # ----------------------------------------------------------------------------- include(${VTK_CMAKE_DIR}/vtkExportKit.cmake) vtk_export_kit2("KWEGraphics" "KWEGRAPHICS" ${CMAKE_CURRENT_BINARY_DIR} "${KIT_SRCS}") vtkedge-0.2.0~20110819/Graphics/Testing/0000755000175000017500000000000011630434664017224 5ustar mathieumathieuvtkedge-0.2.0~20110819/Graphics/Testing/Cxx/0000755000175000017500000000000011630434664017766 5ustar mathieumathieuvtkedge-0.2.0~20110819/Graphics/Testing/Cxx/CMakeLists.txt0000644000175000017500000000436611363410610022523 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Name this kit - this will be used to form test executable name later # Then we'll add in tests with various data or kit dependencies later. # ----------------------------------------------------------------------------- set(KIT Graphics) set(TESTBASE ${PROJECT_NAME}${KIT}) # ----------------------------------------------------------------------------- # First, list all the tests that have no dependencies and can always be run. # Then we'll add in tests with various data or kit dependencies later. # ----------------------------------------------------------------------------- set(MyTests TestDensifyPolyData.cxx TestTessellatedBoxSource.cxx ) create_test_sourcelist(Tests ${TESTBASE}CxxTests.cxx ${MyTests} EXTRA_INCLUDE vtkTestDriver.h ) add_executable(${TESTBASE}CxxTests ${Tests}) #install_targets(${VTKEdge_INSTALL_BIN_DIR} ${TESTBASE}CxxTests) target_link_libraries(${TESTBASE}CxxTests vtkRendering vtkIO vtkKWEGraphics) set(TestsToRun ${Tests}) remove(TestsToRun ${TESTBASE}CxxTests.cxx) # Add all the executables foreach(test ${TestsToRun}) get_filename_component(TName ${test} NAME_WE) if(VTK_DATA_ROOT) add_test(${TName} ${CXX_TEST_PATH}/${TESTBASE}CxxTests ${TName} -D ${VTK_DATA_ROOT} -T ${PROJECT_BINARY_DIR}/Testing/Temporary -V ${PROJECT_SOURCE_DIR}/Data/Baseline/${KIT}/${TName}.png) else(VTK_DATA_ROOT) add_test(${TName} ${CXX_TEST_PATH}/${TESTBASE}CxxTests ${TName}) endif(VTK_DATA_ROOT) endforeach(test) vtkedge-0.2.0~20110819/Graphics/Testing/CMakeLists.txt0000644000175000017500000000166011363410610021753 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Add the Cxx testing directory # ----------------------------------------------------------------------------- add_subdirectory(Cxx) vtkedge-0.2.0~20110819/Widgets/0000755000175000017500000000000011630434665015456 5ustar mathieumathieuvtkedge-0.2.0~20110819/Widgets/itkImageToVTKImageFilter.h0000644000175000017500000000644411363410610022355 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef __itkImageToVTKImageFilter_h #define __itkImageToVTKImageFilter_h #include "VTKEdgeConfigure.h" // Needed for export symbol def #include "itkVTKImageExport.h" #include "vtkImageImport.h" #include "vtkImageData.h" namespace itk { /** \class ImageToVTKImageFilter * \brief Converts an ITK image into a VTK image and plugs a * itk data pipeline to a VTK datapipeline. * * This class puts together an itkVTKImageExporter and a vtkImageImporter. * It takes care of the details related to the connection of ITK and VTK * pipelines. The User will perceive this filter as an adaptor to which * an itk::Image can be plugged as input and a vtkImage is produced as * output. * * \ingroup ImageFilters */ template class ITK_EXPORT ImageToVTKImageFilter : public ProcessObject { public: /** Standard class typedefs. */ typedef ImageToVTKImageFilter Self; typedef ProcessObject Superclass; typedef SmartPointer Pointer; typedef SmartPointer ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(ImageToVTKImageFilter, ProcessObject); /** Some typedefs. */ typedef TInputImage InputImageType; typedef typename InputImageType::ConstPointer InputImagePointer; typedef VTKImageExport< InputImageType> ExporterFilterType; typedef typename ExporterFilterType::Pointer ExporterFilterPointer; /** Get the output in the form of a vtkImage. This call is delegated to the internal vtkImageImporter filter */ vtkImageData * GetOutput() const; /** Set the input in the form of an itk::Image */ void SetInput( const InputImageType * ); /** Return the internal VTK image importer filter. This is intended to facilitate users the access to methods in the importer */ vtkImageImport * GetImporter() const; /** Return the internal ITK image exporter filter. This is intended to facilitate users the access to methods in the exporter */ ExporterFilterType * GetExporter() const; /** This call delegate the update to the importer */ void Update(); protected: ImageToVTKImageFilter(); virtual ~ImageToVTKImageFilter(); private: ImageToVTKImageFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented ExporterFilterPointer m_Exporter; vtkImageImport * m_Importer; }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkImageToVTKImageFilter.txx" #endif #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEITKConnectedThresholdPaintbrushOperation.cxx0000644000175000017500000001374111363410610027337 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEITKConnectedThresholdPaintbrushOperation.h" #include "vtkKWEITKConnectedThresholdImageFilter.h" #include "vtkKWEPaintbrushStroke.h" #include "vtkKWEPaintbrushShape.h" #include "vtkImageStencilData.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkObjectFactory.h" #include "vtkImageExtractComponents.h" #include "vtkExtractVOI.h" #include "vtkKWEPaintbrushUtilities.h" vtkCxxRevisionMacro(vtkKWEITKConnectedThresholdPaintbrushOperation, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEITKConnectedThresholdPaintbrushOperation); //---------------------------------------------------------------------- vtkKWEITKConnectedThresholdPaintbrushOperation::vtkKWEITKConnectedThresholdPaintbrushOperation() { } //---------------------------------------------------------------------- vtkKWEITKConnectedThresholdPaintbrushOperation::~vtkKWEITKConnectedThresholdPaintbrushOperation() { } template< class T > int PaintbrushRunner( vtkKWEITKConnectedThresholdPaintbrushOperation * self, double center[3], vtkImageStencilData *stencil, T ) { self->InternalFilter = NULL; typedef vtkitk::vtkKWEITKConnectedThresholdImageFilter< T > PaintbrushFilterType; typename PaintbrushFilterType::Pointer filter = PaintbrushFilterType::New(); self->InternalFilter = filter; // Set the update region to a certain region on either side of the center double spacing[3]; double origin[3]; int imageExtent[6]; self->GetImageData()->GetOrigin(origin); self->GetImageData()->GetSpacing(spacing); self->GetImageData()->GetExtent(imageExtent); int xyz[3] = { (int)(center[0]/spacing[0] + 0.5), (int)(center[1]/spacing[1] + 0.5), (int)(center[2]/spacing[2] + 0.5) }; int extent[6]; if( self->GetFilterHalfWidth()[0] >= 0 && self->GetFilterHalfWidth()[1] >= 0 && self->GetFilterHalfWidth()[2] >= 0 ) { extent[0] = (int)(xyz[0]-self->GetFilterHalfWidth()[0]); extent[1] = (int)(xyz[0]+self->GetFilterHalfWidth()[0]); extent[2] = (int)(xyz[1]-self->GetFilterHalfWidth()[1]); extent[3] = (int)(xyz[1]+self->GetFilterHalfWidth()[1]); extent[4] = (int)(xyz[2]-self->GetFilterHalfWidth()[2]); extent[5] = (int)(xyz[2]+self->GetFilterHalfWidth()[2]); vtkKWEPaintbrushUtilities::GetIntersectingExtents(extent, imageExtent, extent); vtkKWEPaintbrushUtilities::GetIntersectingExtents(extent, self->GetExtent(), extent); } else { vtkKWEPaintbrushUtilities::GetIntersectingExtents(self->GetExtent(), imageExtent, extent); } // Despite the fact that the FilterModule framework supports updates on // requested extents, a lot of filters in ITK (such as the // ConnectedThresholdImageFilter don't really support updating a subextent. // So in most cases, you will have to extract a VOI). vtkExtractVOI *extractVOI = vtkExtractVOI::New(); extractVOI->SetInput( self->GetImageData()); extractVOI->SetVOI(extent); // Extract the first component vtkImageExtractComponents * extractComponent = vtkImageExtractComponents::New(); extractComponent->SetInput( extractVOI->GetOutput() ); //extractComponent->GetOutput()->SetUpdateExtent( extent ); extractComponent->SetComponents(0); extractComponent->Update(); //filter->SetRequestedExtent(extent); // This is the filter that does most of the work. This is where most of the // time for this operation is spent filter->SetInput( extractComponent->GetOutput() ); // Should add a seed for every point in the stencil filter->AddSeed( xyz ); filter->SetRequestedExtent(extent); //filter->BoundWithRadiusOn(); filter->SetCenter( xyz ); filter->SetRadius( self->GetFilterHalfWidth() ); filter->Update(); filter->GetOutputAsStencil(stencil); extractComponent->Delete(); extractVOI->Delete(); return 1; } //---------------------------------------------------------------------- void vtkKWEITKConnectedThresholdPaintbrushOperation:: DoOperationOnStencil(vtkImageStencilData *stencilData, double p[3] ) { this->PaintbrushShape->GetStencil( stencilData, p ); vtkImageStencilData * stencil = vtkImageStencilData::New(); switch( this->ImageData->GetScalarType() ) { vtkitkTemplateMacro( PaintbrushRunner( this, p, stencil, static_cast< VTK_TT >(0)) ); default: { vtkErrorMacro(<< "vtkKWEITKConnectedThresholdPaintbrushOperation: Unknown ScalarType"); break; } } stencilData->Add(stencil); stencil->Delete(); } //---------------------------------------------------------------------- void vtkKWEITKConnectedThresholdPaintbrushOperation:: DoOperation( vtkKWEPaintbrushData *data, double p[3], vtkKWEPaintbrushEnums::OperationType & op ) { op = vtkKWEPaintbrushEnums::Add; // The paintbrush data can be binary or grayscale. Invoke the appropriate // filtering operation in each case. vtkKWEPaintbrushStencilData *sdata = vtkKWEPaintbrushStencilData::SafeDownCast(data); if ( sdata ) { this->DoOperationOnStencil( sdata->GetImageStencilData(), p ); } } //---------------------------------------------------------------------- void vtkKWEITKConnectedThresholdPaintbrushOperation::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEITKPaintbrushOperation.h0000644000175000017500000000412111363410610023254 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEITKPaintbrushOperation - // .SECTION Description // This is an abstract base class. // .SECTION See Also #ifndef __vtkKWEITKPaintbrushOperation_h #define __vtkKWEITKPaintbrushOperation_h #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEITKImageToStencilFilter.h" typedef double RealType; class vtkImageStencilData; class VTKEdge_WIDGETS_EXPORT vtkKWEITKPaintbrushOperation : public vtkKWEPaintbrushOperation { public: // Description: // Standard methods for instances of this class. vtkTypeRevisionMacro(vtkKWEITKPaintbrushOperation, vtkKWEPaintbrushOperation); void PrintSelf(ostream& os, vtkIndent indent); //BTX typedef vtkitk::vtkKWEITKImageToStencilFilter InternalFilterType; InternalFilterType::Pointer InternalFilter; //ETX vtkSetVector3Macro( FilterHalfWidth, double ); vtkGetVector3Macro( FilterHalfWidth, double ); protected: vtkKWEITKPaintbrushOperation(); ~vtkKWEITKPaintbrushOperation(); double FilterHalfWidth[3]; // Description: // Filter the incoming data (first arg) through this operation. The // operation is centered at point 'p'. virtual void DoOperationOnStencil(vtkImageStencilData *, double p[3]) = 0; private: vtkKWEITKPaintbrushOperation(const vtkKWEITKPaintbrushOperation&); //Not implemented void operator=(const vtkKWEITKPaintbrushOperation&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushWidgetCallbackMapper.h0000644000175000017500000001032511521051333024753 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushWidgetCallbackMapper - map widget events into callbacks // .SECTION Description // vtkKWEPaintbrushWidgetCallbackMapper maps widget events into static callback // methods on the paintbrush widget. This class may be overridden to customize // the paintbrush widget interactions. // // .SECTION Interactions //

// The follwing interactions are defined by this class when the brush is // in Edit mode. // Left click and drag - Draws a stroke // Ctrl-Left click and drag - Erase stroke // Shift Left click drag - Draws a stroke on this sketch alone. All other sketches are deemed uneditable while the shift key is depressed. // Shft Ctrl Left click drag - Erase stroke on this sketch alone. All other sketches are deemed uneditable while the shift key is depressed. // Backspace or Left key - Undo the sketch (deletes the previously drawn stroke in a sketch) // Right key - Redo on the given sketch // Shift "+" - Start a new sketch. // Shift Right - Traverse to the next sketch. // Shift Left - Traverse to the previous sketch. // Shift Backspace - Delete a sketch. // Right click and drag - Resize the shape isotropically // Ctrl-Right click and drag - Resize the shape anisotropically // Shift "<" - Decrease the opacity of the overlaid drawing // Shift ">" - Increase the opacity of the overlaid drawing // "l" key - Render the current sketch immutable/mutable. (Supported only when editing labelmaps) // Escape - Enable/Disable interactions //

// The follwing interactions are defined by this class when the brush is in Select Mode // Left click - Select/Unselect a sketch // Left click and drag - Drag and drop merge of sketches. // Backspace key - Delete selected sketches. // "m" key - Merge selected sketches. // Escape - Enable/Disable interactions // // // .SECTION See Also // vtkWidgetEvent vtkWidgetEventTranslator #ifndef __vtkKWEPaintbrushWidgetCallbackMapper_h #define __vtkKWEPaintbrushWidgetCallbackMapper_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkWidgetCallbackMapper.h" class vtkKWEAbstractPaintbrushWidget; class vtkKWEPaintbrushWidget; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushWidgetCallbackMapper : public vtkWidgetCallbackMapper { public: // Description: // Instantiate the class. static vtkKWEPaintbrushWidgetCallbackMapper *New(); // Description: // Standard macros. vtkTypeMacro(vtkKWEPaintbrushWidgetCallbackMapper,vtkWidgetCallbackMapper); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set the paintbrush widget. No reference counting to avoid loops. void SetPaintbrushWidget( vtkKWEAbstractPaintbrushWidget * w ); // Description: // Set the default bindings. If you want to set your own bindings, you // would create your own subclass of vtkKWEPaintbrushWidgetCallbackMapper // and override the Bindings() method. virtual void Bindings(); protected: vtkKWEPaintbrushWidgetCallbackMapper(); ~vtkKWEPaintbrushWidgetCallbackMapper(); vtkKWEAbstractPaintbrushWidget * PaintbrushWidget; private: vtkKWEPaintbrushWidgetCallbackMapper(const vtkKWEPaintbrushWidgetCallbackMapper&); //Not implemented void operator=(const vtkKWEPaintbrushWidgetCallbackMapper&); //Not implemented }; #endif /* __vtkKWEPaintbrushWidgetCallbackMapper_h */ vtkedge-0.2.0~20110819/Widgets/vtkKWEITKFilterModuleStencilOutput.h0000644000175000017500000000525611363410610024424 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef _vtkKWEITKFilterModuleStencilOutput_h #define _vtkKWEITKFilterModuleStencilOutput_h #include "vtkKWEITKFilterModule.h" #include "vtkImageStencilData.h" #include "vtkImageData.h" #include "vtkImageIterator.h" namespace vtkitk { template class FilterModuleStencilOutput : public FilterModule< TFilterType > { public: // Instantiate the image types typedef TFilterType FilterType; typedef typename FilterType::InputImageType InputImageType; typedef typename FilterType::OutputImageType OutputImageType; typedef typename InputImageType::PixelType InputPixelType; typedef typename OutputImageType::PixelType OutputPixelType; itkStaticConstMacro( Dimension, unsigned int, itk::GetImageDimension< InputImageType >::ImageDimension ); typedef itk::VTKImageToImageFilter< InputImageType > ImportFilterType; typedef itk::ImageToVTKImageFilter< OutputImageType > ExportFilterType; typedef typename InputImageType::SizeType SizeType; typedef typename InputImageType::IndexType IndexType; typedef typename InputImageType::RegionType RegionType; /** Constructor */ FilterModuleStencilOutput(); virtual ~FilterModuleStencilOutput(); /** Will return 0 if the output is not of type UNSIGNED_CHAR */ int GetOutputAsStencil( vtkImageStencilData *stencilData ); /** Filters inherently run on image regions. These are cuboids, defined by * bounded by a set of extents. Often, when a local region growing is * performed with a seed or a paintbrush, you would expect the regions to * be spherical, and not have rectangular artefacts. */ int GetSphereBoundedOutputAsStencil( vtkImageStencilData *stencilData, int center[3], double radius[3] ); }; } // end namespace vtkitk #include "vtkKWEITKFilterModuleStencilOutput.txx" #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushDataStatistics.cxx0000644000175000017500000002152711363410610024254 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushDataStatistics.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkObjectFactory.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkExecutive.h" #include "vtkAlgorithmOutput.h" #include "vtkImageData.h" #include "vtkImageStencilData.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkContourFilter.h" #include "vtkImageConstantPad.h" #include "vtkTriangleFilter.h" #include "vtkMassProperties.h" vtkCxxRevisionMacro(vtkKWEPaintbrushDataStatistics, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEPaintbrushDataStatistics); //---------------------------------------------------------------------------- vtkKWEPaintbrushDataStatistics::vtkKWEPaintbrushDataStatistics() { this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(0); this->ContourFilter = NULL; this->TriangleFilter = NULL; this->PadFilter = NULL; this->MassProperties = NULL; this->Volume = 0; } //---------------------------------------------------------------------------- vtkKWEPaintbrushDataStatistics::~vtkKWEPaintbrushDataStatistics() { if (this->ContourFilter) { this->ContourFilter->Delete(); } if (this->PadFilter) { this->PadFilter->Delete(); } if (this->TriangleFilter) { this->TriangleFilter->Delete(); } if (this->MassProperties) { this->MassProperties->Delete(); } } //---------------------------------------------------------------------------- int vtkKWEPaintbrushDataStatistics ::RequestData( vtkInformation *, vtkInformationVector** inputVector, vtkInformationVector* vtkNotUsed( outputVector )) { vtkInformation *info = inputVector[0]->GetInformationObject(0); vtkKWEPaintbrushData *data = vtkKWEPaintbrushData::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); this->Volume = 0; if (vtkKWEPaintbrushStencilData *sdata = vtkKWEPaintbrushStencilData::SafeDownCast(data)) { vtkImageStencilData *stencilData = sdata->GetImageStencilData(); // For binary data, we will compute the volume simply by counting the // number of voxels. // Find the number of voxels that are ON in the stencil. unsigned long nVoxels = 0; int moreSubExtents; int iter, r1, r2, extent[6]; stencilData->GetExtent(extent); for (int z=extent[4]; z <= extent[5]; z++) { for (int y=extent[2] ; y <= extent[3]; y++) { iter = 0; moreSubExtents = 1; while( moreSubExtents ) { moreSubExtents = stencilData->GetNextExtent( r1, r2, extent[0], extent[1], y, z, iter); // sanity check if (r1 <= r2) { nVoxels += (r2 - r1 + 1); } } // end for each extent tuple } // end for each scan line } // end of each slice // Volume = number of voxels * volume of a voxel. double spacing[3]; stencilData->GetSpacing(spacing); this->Volume = static_cast(nVoxels) * spacing[0] * spacing[1] * spacing[2]; } else if (vtkKWEPaintbrushGrayscaleData *gdata = vtkKWEPaintbrushGrayscaleData::SafeDownCast(data)) { // The pipeline to compute volume for grayscale data is // image --> PadFilter --> ContourFilter --> TriangleFilter // --> vtkMassProperties --> Volume // // The pad filter is necessary to add a border around the image, otherwise // the contour filter might generate non-closed surfaces and // vtkMassProperties will end up giving us bogus values. vtkImageData *image = gdata->GetImageData(); if (!this->PadFilter) { this->PadFilter = vtkImageConstantPad::New(); } this->PadFilter->SetInput(image); int extent[6]; image->GetExtent(extent); extent[0] -= 1; extent[1] += 1; extent[2] -= 1; extent[3] += 1; extent[4] -= 1; extent[5] += 1; this->PadFilter->SetOutputWholeExtent(extent); if (!this->ContourFilter) { this->ContourFilter = vtkContourFilter::New(); this->ContourFilter->SetValue( 0, 127.5 ); } this->ContourFilter->SetInput( this->PadFilter->GetOutput() ); this->ContourFilter->Update(); // Make sure we have something to compute the volume of. if (this->ContourFilter->GetOutput()->GetNumberOfPoints()) { if (!this->TriangleFilter) { this->TriangleFilter = vtkTriangleFilter::New(); } this->TriangleFilter->SetInput( this->ContourFilter->GetOutput()); if (!this->MassProperties) { this->MassProperties = vtkMassProperties::New(); } this->MassProperties->SetInput( this->TriangleFilter->GetOutput() ); this->Volume = this->MassProperties->GetVolume(); } } return 1; } //---------------------------------------------------------------------------- double vtkKWEPaintbrushDataStatistics::GetVolume() { this->Update(); return this->Volume; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushDataStatistics:: FillInputPortInformation(int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkKWEPaintbrushData"); return 1; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushDataStatistics:: ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // generate the data if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) { return this->RequestData(request, inputVector, outputVector); } return this->Superclass::ProcessRequest(request, inputVector, outputVector); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDataStatistics::SetInput(vtkKWEPaintbrushData* input) { this->SetInputConnection(0,input->GetProducerPort()); } //---------------------------------------------------------------------------- double vtkKWEPaintbrushDataStatistics::GetOverlapVolume( vtkKWEPaintbrushStencilData * s1, vtkKWEPaintbrushStencilData * s2 ) { unsigned long nVoxels = 0; int s1Extent[6], s2Extent[6], commonExtent[6]; s1->GetExtent( s1Extent ); s2->GetExtent( s2Extent ); vtkImageStencilData *s1data = s1->GetImageStencilData(); vtkImageStencilData *s2data = s2->GetImageStencilData(); if (vtkKWEPaintbrushUtilities::GetIntersectingExtents( s1Extent, s2Extent, commonExtent) ) { // Find the number of voxels that are ON in both int moreSubExtents1, moreSubExtents2; int iter_1, iter_2, r1_1, r2_1, r1_2, r2_2; for (int z=commonExtent[4]; z <= commonExtent[5]; z++) { for (int y=commonExtent[2] ; y <= commonExtent[3]; y++) { iter_1 = 0; moreSubExtents1 = 1; while( moreSubExtents1 ) { moreSubExtents1 = s1data->GetNextExtent( r1_1, r2_1, commonExtent[0], commonExtent[1], y, z, iter_1); if (r1_1 <= r2_1) { moreSubExtents2 = 1; iter_2 = 0; while( moreSubExtents2 ) { moreSubExtents2 = s2data->GetNextExtent( r1_2, r2_2, r1_1, r2_1, y, z, iter_2); if (r1_2 <= r2_2) { // There is an intersection nVoxels += (r2_2 - r1_2 + 1); } // end if there is a finite intersectingextent in data1 } // end foreach extent tuple of data2 // within the extent extracted from data1 } // end if there is a finite extent in data1 } // end for each extent tuple in data1 } // end for each scan line } // end of each slice } double spacing[3]; s1data->GetSpacing(spacing); return static_cast(nVoxels) * spacing[0] * spacing[1] * spacing[2]; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDataStatistics::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushSketch.cxx0000644000175000017500000005724711567202500022564 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStroke.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkObjectFactory.h" #include "vtkMath.h" #include "vtkImageData.h" #include "vtkProperty.h" #define max(x,y) ((x>y) ? (x) : (y)) vtkCxxRevisionMacro(vtkKWEPaintbrushSketch, "$Revision: 3551 $"); vtkStandardNewMacro(vtkKWEPaintbrushSketch); vtkCxxSetObjectMacro(vtkKWEPaintbrushSketch,PaintbrushOperation, vtkKWEPaintbrushOperation); //---------------------------------------------------------------------- vtkKWEPaintbrushSketch::vtkKWEPaintbrushSketch() { this->PaintbrushData = NULL; this->PaintbrushOperation = NULL; this->ImageData = NULL; this->PaintbrushProperty = vtkKWEPaintbrushProperty::New(this); this->CurrentStroke = -1; this->Representation = vtkKWEPaintbrushEnums::Binary; this->HistoryLength = 4; this->Label = vtkKWEPaintbrushLabelData::NoLabelValue; this->PaintbrushDrawing = NULL; } //---------------------------------------------------------------------- vtkKWEPaintbrushSketch::~vtkKWEPaintbrushSketch() { if (this->PaintbrushData) { this->PaintbrushData->Delete(); } this->SetPaintbrushOperation(NULL); this->SetImageData(NULL); // Delete the internals. for (unsigned int i=0; iStrokes.size(); i++) { this->Strokes[i]->UnRegister(this); } this->Strokes.clear(); this->PaintbrushProperty->Delete(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushSketch::Initialize() { if (!this->ImageData) { vtkErrorMacro( << "No image data"); return; } if (this->PaintbrushData) { this->PaintbrushData->Delete(); this->PaintbrushData = NULL; } if (this->Representation == vtkKWEPaintbrushEnums::Binary) { this->PaintbrushData = vtkKWEPaintbrushStencilData::New(); } else if (this->Representation == vtkKWEPaintbrushEnums::Grayscale) { this->PaintbrushData = vtkKWEPaintbrushGrayscaleData::New(); } if (this->PaintbrushData) { this->AllocatePaintbrushData(); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushSketch::Initialize( vtkKWEPaintbrushLabelData *labelMap ) { if (!this->PaintbrushData) { vtkErrorMacro( << "PaintbrushData is NULL. Did you add this sketch to the " << "drawing and Initialize the drawing prior to initializing the sketch ?"); return; } if (this->Representation != vtkKWEPaintbrushEnums::Label) { vtkErrorMacro( << "Representation of the sketch isnt a label map!" << " You probably want to call SetRepresentation( " << "vtkKWEPaintbrushEnums::Label) on the sketch first."); return; } if (this->Label == vtkKWEPaintbrushLabelData::NoLabelValue) { vtkErrorMacro( << "Set the Label on this sketch first. " << "Note that " << vtkKWEPaintbrushLabelData::NoLabelValue << " is a reserved value."); return; } // Add the label data for this label as a stroke, so it can be undone or // redone. Note also that strokes are still managed as stencils, since // they are guarenteed to be binary. Stencils, inherently stored in run- // length encoded form still are the most efficient representations // for strokes. vtkKWEPaintbrushStencilData *strokeData = vtkKWEPaintbrushStencilData::New(); // Extract all voxels in the label map with this->Label and store // it in strokeData. vtkKWEPaintbrushUtilities::GetStencilFromImage< vtkKWEPaintbrushUtilities::vtkFunctorEqualTo >( labelMap->GetLabelMap(), strokeData->GetImageStencilData(), this->Label ); // Add the initial segmentation as a stroke to this sketch. this->AddNewStroke( vtkKWEPaintbrushEnums::Draw, strokeData, NULL, true ); strokeData->Delete(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushSketch::SetImageData( vtkImageData * imageData ) { if (this->ImageData != imageData) { vtkImageData * var = this->ImageData; this->ImageData = imageData; if (this->ImageData != NULL) { this->ImageData->Register(this); } if (var != NULL) { var->UnRegister(this); } this->Modified(); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushSketch::AllocatePaintbrushData() { if (!this->ImageData) { vtkErrorMacro( << "No image data"); } if (!this->PaintbrushData) { vtkErrorMacro( << "Must call Initialize() before using this class !"); } int extent[6]; double spacing[3], origin[3]; this->ImageData->GetWholeExtent(extent); this->ImageData->GetSpacing(spacing); this->ImageData->GetOrigin(origin); this->PaintbrushData->SetExtent(extent); this->PaintbrushData->SetSpacing(spacing); this->PaintbrushData->SetOrigin(origin); this->PaintbrushData->Allocate(); } //---------------------------------------------------------------------- int vtkKWEPaintbrushSketch::AddNewStroke( int polarity, // Draw or erase vtkKWEPaintbrushData *initialization, int *extents, bool forceMutable ) { this->CurrentStroke++; // If we've exceeded the maximum allowed queue length, keep the queue length // at the limit by merging the last two strokes in the queue. This will // ensure that the queue size is always "HistoryLength" or less. if (this->CurrentStroke > this->HistoryLength) { if (this->HistoryLength > 0) { vtkKWEPaintbrushStroke * stroke0 = this->Strokes[0]; vtkKWEPaintbrushStroke * stroke1 = this->Strokes[1]; stroke0->GetPaintbrushData()->SetLabel(this->Label); stroke1->GetPaintbrushData()->SetLabel(this->Label); // Merge, keeping the polarity in mind. Stroke 0 has to be of positive // polarity. if (stroke1->GetState() == vtkKWEPaintbrushEnums::Erase) { stroke0->GetPaintbrushData()->Subtract(stroke1->GetPaintbrushData(), forceMutable); } else { stroke0->GetPaintbrushData()->Add(stroke1->GetPaintbrushData(), forceMutable); } // Update stroke0's draw time to the most recent of stroke0 and stroke1. // Of course the more recent one is stroke1. stroke0->SetDrawTime( stroke1->GetDrawTime() ); // Now that we've merged, remove the stroke. So if we have 5 strokes: // 0, 1, 2, 3, 4. // 1 is merged into 0. Then 1 is removed. We will end up with 4 strokes:7 // (0 U 1), 2, 3, 4 this->Strokes.erase(this->Strokes.begin()+1); stroke1->UnRegister(this); } // We are at the end of the queue. this->CurrentStroke = this->HistoryLength; } // Only if we are worried about Undo/Redo if (this->HistoryLength) { // Erase all future sequences.. (the moment you start drawing a new // sequence, you forget about the last undo), exactly like MSWord this->EraseStrokes( this->CurrentStroke, static_cast(this->Strokes.size()-1)); } // 'stroke' will represent the stroke on which we will now etch. vtkSmartPointer< vtkKWEPaintbrushStroke > stroke = NULL; if ((this->HistoryLength == 0) && this->Strokes.size()) { // If we aren't maintaining history, we will keep reusing the same stroke. // We will not create a new one or add it to the history queue. stroke = this->Strokes[this->CurrentStroke]; } else { // Create a new stroke stroke = vtkSmartPointer< vtkKWEPaintbrushStroke >::New(); stroke->SetPaintbrushOperation(this->PaintbrushOperation); stroke->SetRepresentation(this->Representation); stroke->SetState(polarity); // The polarity, draw / erase. stroke->SetLabel(this->Label); // Check if extents have been specified, the stroke size may be a lot // smaller than that of the canvas and we can save memory :) if (extents && extents[1] >= extents[0]) { stroke->SetExtent(extents); } stroke->SetImageData(this->ImageData); // Push it onto our history queue. stroke->Register(this); this->Strokes.push_back(stroke); } if (initialization) { initialization->SetLabel( this->Label ); // Initialize stroke with user specified data, if provided. This allows // user provided initializations to be undone/redone as well. stroke->SetPaintbrushData(initialization); this->PaintbrushData->Add(initialization, forceMutable); } return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushSketch::Add( vtkKWEPaintbrushSketch * sketch ) { // Merges another sketch into this sketch. if (!this->PaintbrushData) { vtkErrorMacro( << "PaintbrushData is NULL. Did you add this sketch to the " << "drawing and Initialize the drawing prior to initializing the sketch ?"); return; } if (this->Representation != sketch->GetRepresentation()) { vtkErrorMacro( << "Both sketches should have the same representation."); return; } if (this->Representation == vtkKWEPaintbrushEnums::Label && sketch->GetRepresentation() == vtkKWEPaintbrushEnums::Label) { if (this->Label == vtkKWEPaintbrushLabelData::NoLabelValue || sketch->GetLabel() == vtkKWEPaintbrushLabelData::NoLabelValue) { vtkErrorMacro( << "Set the Label on this sketch first. " << "Note that " << vtkKWEPaintbrushLabelData::NoLabelValue << " is a reserved value."); return; } // Add the label data for this label as a stroke, so it can be undone or // redone. Note also that strokes are still managed as stencils, since // they are guarenteed to be binary. Stencils, inherently stored in run- // length encoded form still are the most efficient representations // for strokes. vtkKWEPaintbrushLabelData * labelMap = vtkKWEPaintbrushLabelData::SafeDownCast(sketch->GetPaintbrushData()); vtkKWEPaintbrushStencilData *strokeData = vtkKWEPaintbrushStencilData::New(); // Extract all voxels in the label map with this->Label and store // it in strokeData. vtkKWEPaintbrushUtilities::GetStencilFromImage< vtkKWEPaintbrushUtilities::vtkFunctorEqualTo >( labelMap->GetLabelMap(), strokeData->GetImageStencilData(), sketch->GetLabel() ); // Add the initial segmentation as a stroke to this sketch. this->AddNewStroke( vtkKWEPaintbrushEnums::Draw, strokeData, NULL, true ); strokeData->Delete(); } else { // For other representations, no need to extract the label. The generic // method takes care of it. this->AddNewStroke( vtkKWEPaintbrushEnums::Draw, sketch->GetPaintbrushData(), NULL, true ); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushSketch::EraseStrokes(int start, int end) { if (end < start || start < 0 || end >= static_cast(this->Strokes.size())) { return; } for (int i=start; i <= end; i++) { this->Strokes[i]->UnRegister(this); } this->Strokes.erase(this->Strokes.begin()+start, this->Strokes.begin()+end+1); } //---------------------------------------------------------------------- int vtkKWEPaintbrushSketch::PopStroke() { if (this->Strokes.size() <= 1 || this->CurrentStroke < 1) { return 0; } this->CurrentStroke--; this->ComposeStrokes(); return 1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushSketch::PushStroke() { if (!this->Strokes.size() || this->CurrentStroke >= (static_cast(this->Strokes.size())-1) ) { return 0; } this->CurrentStroke++; if (this->Representation == vtkKWEPaintbrushEnums::Label) { // Need to compose all strokes for multi-label undo/redo. this->ComposeStrokes(); } else { // Shortcut for non-label drawings. Just add the current stroke back. vtkKWEPaintbrushStroke *stroke = this->Strokes[this->CurrentStroke]; stroke->GetPaintbrushData()->SetLabel(this->Label); // Subtract this stroke if it was an erase stroke, add it if it was a // draw stroke. if (stroke->GetState() == vtkKWEPaintbrushEnums::Erase) { this->PaintbrushData->Subtract(stroke->GetPaintbrushData()); } else { this->PaintbrushData->Add(stroke->GetPaintbrushData()); } } return 1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushSketch::DeleteLastStroke() { if (!this->Strokes.size()) { return 0; } vtkKWEPaintbrushStroke *stroke = this->Strokes[this->Strokes.size()-1]; stroke->UnRegister(this); this->Strokes.pop_back(); this->ComposeStrokes(); if (this->CurrentStroke >= 0) { this->CurrentStroke--; return 1; } return 0; } //---------------------------------------------------------------------- void vtkKWEPaintbrushSketch::ComposeStrokes() { // Clear before composing // FIXME check if allocate erases the buffer for ImageData too this->PaintbrushData->Clear( this->Label ); if (this->CurrentStroke >= static_cast(this->Strokes.size())) { vtkErrorMacro( << "Trying to access " << this->CurrentStroke << " but number of strokes " << "available in sketch " << this << " is " << this->Strokes.size()); return; } // Multilabel undo/redo. if (this->Representation == vtkKWEPaintbrushEnums::Label) { if (this->CurrentStroke >= 0 && this->PaintbrushDrawing) { this->PaintbrushDrawing->ComposeStrokes(); } } else { if (this->CurrentStroke >= 0) { for (int i=0; i<= this->CurrentStroke; i++) { vtkKWEPaintbrushStroke *stroke = this->Strokes[i]; stroke->GetPaintbrushData()->SetLabel(this->Label); // Subtract this stroke if it was an erase stroke, add it if it was a // draw stroke. if (stroke->GetState() == vtkKWEPaintbrushEnums::Erase) { this->PaintbrushData->Subtract(stroke->GetPaintbrushData()); } else { this->PaintbrushData->Add(stroke->GetPaintbrushData()); } } } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushSketch::AddShapeToCurrentStroke(double p[3], vtkKWEPaintbrushData *auxData) { if (!this->Strokes.size() || this->CurrentStroke < 0 || this->CurrentStroke >= static_cast(this->Strokes.size()) || !this->PaintbrushData) { return; } vtkKWEPaintbrushStroke *stroke = this->Strokes[this->CurrentStroke]; // Add the shape at the current position to the stroke. We will also // pass in the paintbrush data from this sketch (this->PaintbrushData) and // the one from the drawing (auxData) and add/subtract the shape (passed // through the operation) to that data. This is done for efficiency, so that // we don't query the shape twice to compute the paintbrushData at thex // current location. // Hey, you need some hacks for speed right :) ! if (!stroke->AddShapeAtPosition(p, this->PaintbrushData, auxData)) { return; } } //---------------------------------------------------------------------- void vtkKWEPaintbrushSketch::SetPaintbrushData(vtkKWEPaintbrushData * data ) { // If you set an external data as the stroke manager's data, you // lose all the undo-redo history.. this->EraseStrokes(0,static_cast(this->Strokes.size()-1)); if (this->PaintbrushData != data) { vtkKWEPaintbrushData * var = this->PaintbrushData; this->PaintbrushData = data; if (this->PaintbrushData != NULL) { this->PaintbrushData->Register(this); } if (var != NULL) { var->UnRegister(this); } this->Modified(); } this->CurrentStroke = -1; } //---------------------------------------------------------------------- unsigned long vtkKWEPaintbrushSketch::GetMTime() { // TODO: Check this. Do we need to check the property MTime. I // don't want uncessary re-rendering... for instance changing the // highlight property when I am not using Highlight etc.... unsigned long t = 0; if (this->PaintbrushData) { t = this->PaintbrushData->GetMTime(); } unsigned long mtime = vtkObject::GetMTime(); unsigned long propertyMtime = this->PaintbrushProperty->GetMTime(); return max( max(mtime, t), propertyMtime ); } //---------------------------------------------------------------------- void vtkKWEPaintbrushSketch:: GetStrokes(vtkstd::vector< vtkKWEPaintbrushStroke * > &strokes) { // Push all the strokes until the current stroke into strokes. if (this->Strokes.size()) { strokes.insert( strokes.end(), this->Strokes.begin(), this->Strokes.begin() + this->CurrentStroke + 1 ); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushSketch::SetMutable( int m ) { // Sanity checks. if (!this->PaintbrushData) { vtkErrorMacro( << "Initialize PaintbrushSketch prior to affecting its mutability." ); return; } vtkKWEPaintbrushLabelData *labelData = vtkKWEPaintbrushLabelData::SafeDownCast(this->PaintbrushData); if (!labelData) { vtkErrorMacro( << "Mutability makes sense only when editing label maps." ); return; } if (this->Label == vtkKWEPaintbrushLabelData::NoLabelValue) { vtkErrorMacro( << "You cannot affect mutability before setting the label value." ); return; } if (labelData && labelData->IsMutable(this->Label) != m) { // Let's collapse the history. Consider a scenario where we make a // sketch immutable, then draw, (it doesn't actually change the sketch). // then undo, then make the sketch mutable, then redo. This time the // stroke will change the sketch, because the stroke has no idea that // the sketch it was affecting when created was immutable at that time. // So to be on the same side, we will clear this history every time we // change the mutability flag. for (int i = 0; i < this->PaintbrushDrawing->GetNumberOfItems(); i++) { //this->PaintbrushDrawing->GetItem(i)->CollapseHistory(); } labelData->SetMutable( m, this->Label ); } } // ---------------------------------------------------------------------------- void vtkKWEPaintbrushSketch::CollapseHistory() { if (this->HistoryLength) { // Remove all future strokes. this->EraseStrokes(this->CurrentStroke+1, static_cast(this->Strokes.size()-1)); // Recursively collapse the bottom two strokes, until we have just // one stroke left. while (this->Strokes.size() > 1) { vtkKWEPaintbrushStroke * stroke0 = this->Strokes[0]; vtkKWEPaintbrushStroke * stroke1 = this->Strokes[1]; stroke0->GetPaintbrushData()->SetLabel(this->Label); stroke1->GetPaintbrushData()->SetLabel(this->Label); // Merge, keeping the polarity in mind. Stroke 0 has to be of positive // polarity. if (stroke1->GetState() == vtkKWEPaintbrushEnums::Erase) { stroke0->GetPaintbrushData()->Subtract(stroke1->GetPaintbrushData()); } else { stroke0->GetPaintbrushData()->Add(stroke1->GetPaintbrushData()); } // Update stroke0's draw time to the most recent of stroke0 and stroke1. // Of course the more recent one is stroke1. stroke0->SetDrawTime( stroke1->GetDrawTime() ); // Now that we've merged, remove the stroke. So if we have 5 strokes: // 0, 1, 2, 3, 4. // 1 is merged into 0. Then 1 is removed. We will end up with 4 strokes:7 // (0 U 1), 2, 3, 4 this->Strokes.erase(this->Strokes.begin()+1); stroke1->UnRegister(this); } this->CurrentStroke = 0; // Re-create the initial stroke to match what's there. if (this->Strokes.size()) { if (vtkKWEPaintbrushLabelData *labelMap = vtkKWEPaintbrushLabelData::SafeDownCast(this->PaintbrushData)) { if (vtkKWEPaintbrushStencilData *stencilData = vtkKWEPaintbrushStencilData::SafeDownCast( this->Strokes[0]->GetPaintbrushData())) { vtkKWEPaintbrushUtilities::GetStencilFromImage< vtkKWEPaintbrushUtilities::vtkFunctorEqualTo >( labelMap->GetLabelMap(), stencilData->GetImageStencilData(), this->Label ); } } } } } // ---------------------------------------------------------------------------- void vtkKWEPaintbrushSketch::CopySketchFromExtentToExtent( int sourceExtent[6], int targetExtent[6] ) { // This method is useful for copying a sketch from one slice to another. // The source and target extents should be of the same dimension. // Its currently implemented only if the sketch is of a label map type. if (this->Representation != vtkKWEPaintbrushEnums::Label) { vtkErrorMacro( << "Currently the copy functionality is implemented only for label maps."); return; } vtkKWEPaintbrushLabelData *labelData = vtkKWEPaintbrushLabelData::SafeDownCast(this->PaintbrushData); vtkImageData *labelImage = labelData->GetLabelMap(); typedef vtkKWEPaintbrushEnums::LabelType LabelType; typedef vtkImageIterator< LabelType > IteratorType; // Copy over.. We won't do any extent checking.. int labelImageExtent[6]; labelImage->GetExtent(labelImageExtent); if (!vtkMath::ExtentIsWithinOtherExtent(sourceExtent, labelImageExtent) || !vtkMath::ExtentIsWithinOtherExtent(targetExtent, labelImageExtent)) { vtkErrorMacro( << "Copy extents are not within the labelmap's extent"); return; } IteratorType it1(labelImage, sourceExtent); IteratorType it2(labelImage, targetExtent); while( !it1.IsAtEnd() ) { LabelType *inSI1 = it1.BeginSpan(); LabelType *inSIEnd1 = it1.EndSpan(); LabelType *inSI2 = it2.BeginSpan(); while (inSI1 != inSIEnd1) { LabelType l = *inSI1; if (l == this->Label) { *inSI2 = l; } ++inSI1; ++inSI2; } it1.NextSpan(); it2.NextSpan(); } this->Modified(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushSketch::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h os << indent << "PaintbrushOperation: " << this->PaintbrushOperation << endl; if (this->PaintbrushOperation) { this->PaintbrushOperation->PrintSelf( os, indent.GetNextIndent() ); } this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushAnnotationRepresentation.h0000644000175000017500000001004511363410610026003 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushAnnotationRepresentation - An abstract base class for 2D/3D paintbrush widget representations // .SECTION Description // See vtkKWEPaintbrushAnnotationRepresentation2D for more details. // The ShapePlacer must be set prior to use. // // Before using the class, you must set the ImageActor on which the brush is // being drawn. #ifndef __vtkKWEPaintbrushAnnotationRepresentation_h #define __vtkKWEPaintbrushAnnotationRepresentation_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkWidgetRepresentation.h" #include class vtkTimeStamp; class vtkKWEPaintbrushRepresentation; class vtkActor2D; class vtkTextMapper; class vtkTextProperty; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushAnnotationRepresentation : public vtkWidgetRepresentation { //BTX friend class vtkKWEPaintbrushRepresentation; //ETX public: // Description: // Instantiate this class. static vtkKWEPaintbrushAnnotationRepresentation *New(); // Description: // Standard VTK methods. vtkTypeRevisionMacro(vtkKWEPaintbrushAnnotationRepresentation,vtkWidgetRepresentation); void PrintSelf(ostream& os, vtkIndent indent); // Description: // These are methods that satisfy vtkWidgetRepresentation's API. virtual void BuildRepresentation(); // Description: // Methods required by vtkProp superclass. virtual void ReleaseGraphicsResources(vtkWindow *w); virtual int RenderOverlay(vtkViewport *viewport); virtual int RenderOpaqueGeometry(vtkViewport *viewport); #if VTKEdge_VTK_VERSION_DATE > 20070305 virtual int RenderTranslucentPolygonalGeometry(vtkViewport *viewport); virtual int HasTranslucentPolygonalGeometry(); #else // Legacy method to support VTK source versions prior to 2007/03/05 virtual int RenderTranslucentGeometry(vtkViewport *viewport); #endif // Description: // Override superclass method and propagate to all sub-props. virtual void SetVisibility(int); // Description: // Annotations will by default be placed whereever the brush currently is. // If you would like to have annotations appearing at a certain spot, you // can override this. The position is in Normalized display coords vtkSetVector2Macro( AnnotationPosition, double ); vtkGetVector2Macro( AnnotationPosition, double ); // Description: // Set/Get the string to render. This is automatically set from // vtkKWEPaintbrushAnnotationWidget. vtkSetStringMacro( Annotation ); vtkGetStringMacro( Annotation ); // Description: // Get the text property used to render the annotation. vtkGetObjectMacro( TextProperty, vtkTextProperty ); protected: vtkKWEPaintbrushAnnotationRepresentation(); ~vtkKWEPaintbrushAnnotationRepresentation(); vtkTimeStamp *BuildTime; vtkActor2D *TextActor; vtkTextProperty *TextProperty; vtkTextMapper *TextMapper; char *Annotation; vtkKWEPaintbrushRepresentation *PaintbrushRepresentation; vtksys_stl::string LastDisplayedAnnotation; int LastDisplayPosition[2]; double AnnotationPosition[2]; private: vtkKWEPaintbrushAnnotationRepresentation(const vtkKWEPaintbrushAnnotationRepresentation&); //Not implemented void operator=(const vtkKWEPaintbrushAnnotationRepresentation&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEITKConnectedThresholdImageFilter.txx0000644000175000017500000000565511363410610025555 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEITKConnectedThresholdImageFilter.h" #include "itkNumericTraits.h" #include "vtkKWEITKFilterModuleStencilOutput.h" #include "itkImageFileWriter.h" namespace vtkitk { template< class InputPixelType > vtkKWEITKConnectedThresholdImageFilter< InputPixelType > ::vtkKWEITKConnectedThresholdImageFilter() { this->m_Filter = new FilterModuleStencilOutput< FilterType >(); } template< class InputPixelType > vtkKWEITKConnectedThresholdImageFilter< InputPixelType > ::~vtkKWEITKConnectedThresholdImageFilter() { delete this->m_Filter; } template< class InputPixelType > void vtkKWEITKConnectedThresholdImageFilter< InputPixelType > ::AddSeed( int seed[3] ) { IndexType index; index[0] = seed[0]; index[1] = seed[1]; index[2] = seed[2]; FilterModuleStencilOutput< FilterType > * f = (dynamic_cast< FilterModuleStencilOutput< FilterType > * >(this->m_Filter)); if (!f) { itkExceptionMacro( << "dynamic cast returned false.. impossible!"); } FilterType *filter = f->GetFilter(); filter->SetSeed(index); InputPixelType val = static_cast< InputPixelType >( this->m_Filter->GetInput() ->GetScalarComponentAsDouble( index[0], index[1], index[2], 0) ); filter->SetUpper( val ); filter->SetLower( val ); filter->SetReplaceValue( itk::NumericTraits< typename OutputImageType::PixelType >::max() ); } template< class InputPixelType > void vtkKWEITKConnectedThresholdImageFilter< InputPixelType > ::Update() { this->Superclass::Update(); FilterModuleStencilOutput< FilterType > * f = (dynamic_cast< FilterModuleStencilOutput< FilterType > * >(this->m_Filter)); if (!f) { itkExceptionMacro( << "dynamic cast returned false.. impossible!"); } // Update the filter.. If any timing analysis needs to be done.. // This method needs to be interactive enough. f->Update(); //typedef itk::ImageFileWriter< OutputImageType > ImageWriterType; //typename ImageWriterType::Pointer writer = ImageWriterType::New(); //writer->SetInput( f->GetFilter()->GetOutput() ); //writer->SetFileName( "filterConnThresh.mha" ); //writer->Update(); } } // end namespace vtkitk vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushShapeBox.h0000644000175000017500000000621711363410610022465 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushShapeBox - A box shaped paintbrush template // .SECTION Usage // // .SECTION Description // // .SECTION See Also #ifndef __vtkKWEPaintbrushShapeBox_h #define __vtkKWEPaintbrushShapeBox_h #include "vtkKWEPaintbrushShape.h" class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushShapeBox : public vtkKWEPaintbrushShape { public: // Description: // Instantiate this class. static vtkKWEPaintbrushShapeBox *New(); // Description: // Standard methods for instances of this class. vtkTypeRevisionMacro(vtkKWEPaintbrushShapeBox, vtkKWEPaintbrushShape); void PrintSelf(ostream& os, vtkIndent indent); // Description: // It allows the paintbrush representation to query the template for a // paintbrush outline centered at the specified point and intersecting // with the specified plane. If the plane is NULL, a polydata representation // of the template in 3D is returned. (a cube in this case). // Returns NULL if the plane does not intersect with the cube. //BTX virtual vtkSmartPointer< vtkPolyData > GetShapePolyData( double *center, vtkPlane *plane = NULL); //ETX // Description: // Get the template as a stencil virtual void GetStencil(vtkImageStencilData *, double p[3]); virtual void GetGrayscaleData(vtkImageData *, double p[3]); //Description: //Set new shape width virtual void SetWidth( double newWidthX, double newWidthY, double newWidthZ ); virtual void SetWidth( double newWidth[3]); vtkGetVector3Macro( Width, double ); // Description: // See superclass documentation virtual int Resize(double d[3], int ResizeType); // Description: // Deep copy.. Synchronizes states etc. virtual void DeepCopy(vtkKWEPaintbrushShape *); // Description: // Provide some kind of contextual annotation about the shape that // indicates its size etc.. virtual void GetAnnotation(char *); // Description: // Check if point is inside the shape virtual int IsInside(double currentPos[3], double wolrdPos[3]); // Description: // INTERNAL - Do not use. // Get the extents of a shape drawn at the current location. virtual void GetExtent( int extent[6], double p[3] ); protected: vtkKWEPaintbrushShapeBox(); ~vtkKWEPaintbrushShapeBox(); double Width[3]; private: vtkKWEPaintbrushShapeBox(const vtkKWEPaintbrushShapeBox&); //Not implemented void operator=(const vtkKWEPaintbrushShapeBox&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushStencilData.cxx0000644000175000017500000002446511363410610023527 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushStencilData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkMath.h" #include "vtkImageIterator.h" #include "vtkImageStencilData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkImageData.h" #include vtkCxxRevisionMacro(vtkKWEPaintbrushStencilData, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEPaintbrushStencilData); //---------------------------------------------------------------------------- vtkKWEPaintbrushStencilData::vtkKWEPaintbrushStencilData() { this->ImageStencilData = vtkImageStencilData::New(); this->Information->Set(vtkDataObject::DATA_EXTENT_TYPE(), VTK_3D_EXTENT); this->Information->Set(vtkDataObject::DATA_EXTENT(), this->ImageStencilData->GetExtent(), 6); } //---------------------------------------------------------------------------- vtkKWEPaintbrushStencilData::~vtkKWEPaintbrushStencilData() { this->SetImageStencilData(NULL); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushStencilData::SetImageStencilData(vtkImageStencilData *s) { vtkSetObjectBodyMacro( ImageStencilData, vtkImageStencilData, s ); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushStencilData::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushStencilData::ShallowCopy(vtkDataObject *o) { vtkKWEPaintbrushStencilData *s=vtkKWEPaintbrushStencilData::SafeDownCast(o); if (s) { this->ImageStencilData->ShallowCopy(s->GetImageStencilData()); } vtkDataObject::ShallowCopy(o); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushStencilData::DeepCopy(vtkDataObject *o) { vtkKWEPaintbrushStencilData *s=vtkKWEPaintbrushStencilData::SafeDownCast(o); if(s) { this->ImageStencilData->DeepCopy(s->GetImageStencilData()); } vtkDataObject::DeepCopy(o); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushStencilData::Add(vtkImageStencilData *s, bool vtkNotUsed(forceMutable)) { // FIXME Must actually be vtkImageStencilData::InternalAdd here // Make the protected method public later and give it a sensible name this->ImageStencilData->Add(s); return 1; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushStencilData::Subtract(vtkImageStencilData *s, bool vtkNotUsed(forceMutable)) { this->ImageStencilData->Subtract(s); return 1; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushStencilData::Replace(vtkImageStencilData *s, bool vtkNotUsed(forceMutable)) { this->ImageStencilData->Replace(s); return 1; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushStencilData::Add(vtkKWEPaintbrushData *d, bool forceMutable) { vtkKWEPaintbrushStencilData *s= vtkKWEPaintbrushStencilData::SafeDownCast(d); if(s) { return this->Add(s->GetImageStencilData(), forceMutable); } return 0; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushStencilData::Subtract(vtkKWEPaintbrushData *d, bool forceMutable) { vtkKWEPaintbrushStencilData *s=vtkKWEPaintbrushStencilData::SafeDownCast(d); if(s) { return this->Subtract(s->GetImageStencilData(), forceMutable); } return 0; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushStencilData::Replace(vtkKWEPaintbrushData *d, bool forceMutable) { vtkKWEPaintbrushStencilData *s=vtkKWEPaintbrushStencilData::SafeDownCast(d); if(s) { return this->Replace(s->GetImageStencilData(), forceMutable); } return 0; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushStencilData::Allocate(double value) { int extent[6]; this->GetExtent(extent); /*cout << "Allocating : " << this->ImageStencilData << " with extents (" << extent[0] << "," << extent[1] << "," << extent[2] << "," << extent[3] << "," << extent[4] << "," << extent[5] << "," <<")" << endl;*/ this->ImageStencilData->AllocateExtents(); if( value != 0.0 ) { this->ImageStencilData->Fill(); } this->ImageStencilData->Modified(); this->Modified(); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushStencilData::Resize(int extent[6], double f) { int oldExtent[6]; this->ImageStencilData->GetExtent(oldExtent); if (oldExtent[1] < oldExtent[0]) { // We haven't been allocated yet. Just allocate and return. this->SetExtent(extent); this->Allocate(f); return; } if (oldExtent[0] != extent[0] || oldExtent[1] != extent[1] || oldExtent[2] != extent[2] || oldExtent[3] != extent[3] || oldExtent[4] != extent[4] || oldExtent[5] != extent[5]) { vtkImageStencilData * oldData = vtkImageStencilData::New(); oldData->DeepCopy(this->ImageStencilData); this->SetExtent(extent); this->Allocate(f); int r1, r2, moreSubExtents, iter; for (int z=extent[4]; z <= extent[5]; z++) { for (int y=extent[2]; y <= extent[3]; y++) { iter = 0; moreSubExtents = 1; while( moreSubExtents ) { moreSubExtents = oldData->GetNextExtent( r1, r2, extent[0], extent[1], y, z, iter); if (r1 <= r2) { this->ImageStencilData->InsertNextExtent(r1, r2, y, z); } } // end for each extent tuple } // end for each scan line } // end of each slice oldData->Delete(); } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushStencilData::SetSpacing( double s[3] ) { this->ImageStencilData->SetSpacing(s); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushStencilData::SetOrigin( double s[3] ) { this->ImageStencilData->SetOrigin(s); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushStencilData::SetExtent( int extent[6] ) { this->ImageStencilData->SetExtent(extent); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushStencilData::GetExtent( int extent[6] ) { this->ImageStencilData->GetExtent(extent); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushStencilData::Clip( int extent[6] ) { int currentExtent[6], idy, idz, newExtent[6], r1, r2, iter; this->Update(); this->GetExtent( currentExtent ); if (vtkMath::ExtentIsWithinOtherExtent( currentExtent, extent )) { // Nothing to do, we are already within the clipping extents. return 0; } if (vtkKWEPaintbrushUtilities::GetIntersectingExtents( currentExtent, extent, newExtent )) { // Copy into a temporary vtkImageStencilData *tmp = vtkImageStencilData::New(); tmp->DeepCopy(this->ImageStencilData); // Clear and re-allocate ourself. this->SetExtent(newExtent); this->ImageStencilData->AllocateExtents(); // Reallocate extents. for (idz=newExtent[4]; idz<=newExtent[5]; idz++) { for (idy = newExtent[2]; idy <= newExtent[3]; idy++) { iter = 0; int moreSubExtents = 1; while( moreSubExtents ) { moreSubExtents = tmp->GetNextExtent( r1, r2, newExtent[0], newExtent[1], idy, idz, iter); if (r1 <= r2 ) // sanity check { this->ImageStencilData->InsertNextExtent( r1, r2, idy, idz ); } } } } return 1; } return 0; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushStencilData::GetPaintbrushDataAsImageData( vtkImageData *image) { vtkKWEPaintbrushUtilities::GetImageFromStencil( image, this->ImageStencilData, 255, 0); image->SetSpacing(this->ImageStencilData->GetSpacing()); image->SetOrigin(this->ImageStencilData->GetOrigin()); } //---------------------------------------------------------------------------- unsigned long vtkKWEPaintbrushStencilData::GetMTime() { unsigned long t = this->ImageStencilData->GetMTime(); unsigned long mtime = vtkObject::GetMTime(); return (mtime > t ? mtime : t); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushStencilData::IsInside( double p[3] ) { int pixelPos[3], extent[6]; double origin[3], spacing[3]; this->ImageStencilData->GetSpacing(spacing); this->ImageStencilData->GetOrigin(origin); this->GetExtent(extent); for (int i = 0; i < 3; i++) { pixelPos[i] = static_cast(((p[i] - origin[i])/spacing[i])+0.5); if (pixelPos[i] < extent[2*i] || pixelPos[i] > extent[2*i+1]) { return 0; } } int moreSubExtents = 1, iter = 0, r1, r2; while( moreSubExtents ) { moreSubExtents = this->ImageStencilData->GetNextExtent( r1, r2, extent[0], extent[1], pixelPos[1], pixelPos[2], iter); if (r1 <= pixelPos[0] && r2 >= pixelPos[0] ) { return 1; } } return 0; } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushOperation.h0000644000175000017500000000737211363410610022717 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushOperation - Perform inplace operations on paintbrush stencils // .SECTION Description // This is a base class for Paintbrush operations that perform smart inplace // operations on paintbrush stencils. This class acts as a pass through // filter that does not modify the incoming stencils. Subclasses must // override the protected method \c DoOperationOnStencil to modify the // stencil possibly based on the underlying image data. // // .SECTION See Also #ifndef __vtkKWEPaintbrushOperation_h #define __vtkKWEPaintbrushOperation_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkKWEPaintbrushEnums.h" // needed for export symbols directives #include "vtkObject.h" class vtkImageStencilData; class vtkKWEPaintbrushData; class vtkKWEPaintbrushShape; class vtkImageData; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushOperation : public vtkObject { public: // Description: // Instantiate this class. static vtkKWEPaintbrushOperation *New(); // Description: // Standard methods for instances of this class. vtkTypeRevisionMacro(vtkKWEPaintbrushOperation, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set the paintbrush shape. This must be set. virtual void SetPaintbrushShape( vtkKWEPaintbrushShape* ); vtkGetObjectMacro( PaintbrushShape, vtkKWEPaintbrushShape); // Description: // Set the image data on which the paintbrush is drawn. This must be set. virtual void SetImageData( vtkImageData * ); vtkGetObjectMacro( ImageData, vtkImageData ); // Description: // Get the Paintbrush data for the shape at point 'p' filtered through // this operation. This class will simply return shape->GetPaintbrushData(). // Subclasses would generally override this, so as to filter the // paintbrushData from the shape. virtual void GetPaintbrushData(vtkKWEPaintbrushData *, double p[3], vtkKWEPaintbrushEnums::OperationType & op ); // Description: // The default behaviour is "You are allowed to paint everywhere." // Optionally, you may retrict this via extents. ie. the operation will // filter data through only if it lies within the specified extents. vtkSetVector6Macro( Extent, int ); vtkGetVector6Macro( Extent, int ); // Description: // INTERNAL: Do not use. // Deep copy.. Synchronizes states etc. virtual void DeepCopy(vtkKWEPaintbrushOperation *); protected: vtkKWEPaintbrushOperation(); ~vtkKWEPaintbrushOperation(); // Description: // Filter the incoming data (first arg) through this operation. The operation // is centered at the point 'p'. virtual void DoOperation( vtkKWEPaintbrushData *, double p[3], vtkKWEPaintbrushEnums::OperationType & op ); vtkImageData *ImageData; vtkKWEPaintbrushShape *PaintbrushShape; int Extent[6]; private: vtkKWEPaintbrushOperation(const vtkKWEPaintbrushOperation&); //Not implemented void operator=(const vtkKWEPaintbrushOperation&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEITKPaintbrushExtractConnectedComponents.cxx0000644000175000017500000004370011363410610027200 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEITKPaintbrushExtractConnectedComponents.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkObjectFactory.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkExecutive.h" #include "vtkAlgorithmOutput.h" #include "vtkImageData.h" #include "vtkImageIterator.h" #include "vtkImageThreshold.h" #include "vtkSmartPointer.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushPropertyManager.h" #include "itkConnectedComponentImageFilter.h" #include "itkVTKImageToImageFilter.h" #include "itkImageToVTKImageFilter.h" #include "itkBinaryDilateImageFilter.h" #include "itkBinaryBallStructuringElement.h" #include "itkImage.h" #include "itkImageRegionIterator.h" vtkCxxRevisionMacro(vtkKWEITKPaintbrushExtractConnectedComponents, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEITKPaintbrushExtractConnectedComponents); //---------------------------------------------------------------------------- vtkKWEITKPaintbrushExtractConnectedComponents:: vtkKWEITKPaintbrushExtractConnectedComponents() { this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(1); this->SketchIndex = 0; } //---------------------------------------------------------------------------- vtkKWEITKPaintbrushExtractConnectedComponents:: ~vtkKWEITKPaintbrushExtractConnectedComponents() { } //---------------------------------------------------------------------------- void vtkKWEITKPaintbrushExtractConnectedComponents:: PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //---------------------------------------------------------------------------- int vtkKWEITKPaintbrushExtractConnectedComponents ::RequestData( vtkInformation *, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkInformation *info = inputVector[0]->GetInformationObject(0); vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkKWEPaintbrushDrawing *inputDrawing = vtkKWEPaintbrushDrawing::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); vtkKWEPaintbrushDrawing *outputDrawing = vtkKWEPaintbrushDrawing::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); // Sanity check. if (this->SketchIndex >= inputDrawing->GetNumberOfItems()) { vtkErrorMacro( << "sketch" << this->SketchIndex << " isnt present in the drawing."); return 0; } outputDrawing->SetRepresentation( inputDrawing->GetRepresentation() ); outputDrawing->SetImageData( inputDrawing->GetImageData() ); outputDrawing->SetPaintbrushOperation( inputDrawing->GetPaintbrushOperation() ); outputDrawing->GetPaintbrushPropertyManager()->SetHighlightType( inputDrawing->GetPaintbrushPropertyManager()->GetHighlightType() ); // This is the image on which we will run the connected components algorithm vtkSmartPointer< vtkImageData > inputImage = vtkSmartPointer< vtkImageData >::New(); inputDrawing->GetItem(this->SketchIndex)->GetPaintbrushData()-> GetPaintbrushDataAsImageData( inputImage ); vtkSmartPointer< vtkImageData > inputBinaryImage = vtkSmartPointer< vtkImageData >::New(); if (inputDrawing->GetRepresentation() == vtkKWEPaintbrushEnums::Grayscale) { // Threshold the image at 127.5 if it came from a grayscale representation. // We want to make sure that the connected components algorithm runs on a // binary image. vtkSmartPointer< vtkImageThreshold > threshold = vtkSmartPointer< vtkImageThreshold >::New(); threshold->SetInput( inputImage ); threshold->SetInValue(255.0); threshold->SetOutValue(0.0); threshold->ThresholdByUpper( 127.5 ); threshold->Update(); inputBinaryImage->ShallowCopy( threshold->GetOutput() ); } else { inputBinaryImage->ShallowCopy( inputImage ); } typedef itk::Image< unsigned char, 3 > ImageType; typedef itk::ConnectedComponentImageFilter< ImageType, ImageType > FilterType; FilterType::Pointer connectedComponentsFilter = FilterType::New(); // Use face and edge connectivity. (26 connectivity in 3D). connectedComponentsFilter->FullyConnectedOn(); // Connect the pipeline. typedef itk::VTKImageToImageFilter< ImageType > VTK2ITKConverter; typedef itk::ImageToVTKImageFilter< ImageType > ITK2VTKConverter; VTK2ITKConverter::Pointer inputConverter = VTK2ITKConverter::New(); ITK2VTKConverter::Pointer outputConverter = ITK2VTKConverter::New(); inputConverter->SetInput( inputBinaryImage ); connectedComponentsFilter->SetInput( inputConverter->GetOutput() ); // Run the connected components algorithm. try { inputConverter->Update(); connectedComponentsFilter->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; return 0; } // Covert the segmented object label map to VTK land. outputConverter->SetInput( connectedComponentsFilter->GetOutput() ); outputConverter->Update(); int nSegments = static_cast< int >(connectedComponentsFilter->GetObjectCount()); // Find the bounding box of each of the segments. We will do that so as to // save some memory allocating N sketches of the whole extent. int *sketchExtents = new int[6*nSegments]; this->ComputeSegmentExtents( nSegments, sketchExtents, outputConverter->GetOutput() ); // Now extract each connected component out into a vtkKWEPaintbrushSketch. for (int n = 1; n <= nSegments; n++) { int extent[6]; inputDrawing->GetImageData()->GetExtent(extent); // Extract segmentN into an imageData. vtkSmartPointer< vtkImageData > segmentN = vtkSmartPointer< vtkImageData >::New(); segmentN->SetExtent( sketchExtents + 6*(n-1) ); segmentN->SetScalarTypeToUnsignedChar(); segmentN->SetOrigin( inputDrawing->GetImageData()->GetOrigin() ); segmentN->SetSpacing( inputDrawing->GetImageData()->GetSpacing() ); segmentN->AllocateScalars(); if (inputDrawing->GetRepresentation() == vtkKWEPaintbrushEnums::Grayscale) { // Extract object N from the output of the connected components algo ImageType::Pointer image = ImageType::New(); image->SetRegions(connectedComponentsFilter->GetOutput() ->GetLargestPossibleRegion()); image->Allocate(); typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType; typedef itk::ImageRegionIterator< ImageType > IteratorType; ConstIteratorType cit( connectedComponentsFilter->GetOutput(), connectedComponentsFilter->GetOutput()->GetBufferedRegion()); IteratorType it( image, image->GetBufferedRegion()); while (!it.IsAtEnd()) { it.Set( (cit.Get() == n) ? 255 : 0 ); ++cit; ++it; } // Dilate the object, so we can copy over the transition region as well. // We will dilate with a 5x5x5 structuring element. typedef itk::BinaryBallStructuringElement< unsigned char, 3 > StructuringElementType; typedef itk::BinaryDilateImageFilter< ImageType, ImageType, StructuringElementType > DilateFilterType; DilateFilterType::Pointer dilate = DilateFilterType::New(); dilate->SetInput( image ); StructuringElementType structuringElement; structuringElement.SetRadius( 2 ); // 5x5 structuring element structuringElement.CreateStructuringElement(); dilate->SetKernel( structuringElement ); dilate->SetDilateValue(255); dilate->Update(); // Covert the dilated ITK image to VTK ITK2VTKConverter::Pointer dilatedConverter = ITK2VTKConverter::New(); dilatedConverter->SetInput( dilate->GetOutput() ); cout << "Start dilating object " << n << " of " << nSegments << endl; dilatedConverter->Update(); cout << "Finished dilating" << endl; // Now do the copy of both the object and the transition region. // For the object, we need to look in the extracted segment, for the // transition region, we need to look in the dilation. Within these // regions we will copy the grayscale values from the original image. // Outside these we will set the values to 0. // // So we need 4 iterators, to iterate over // * Extracted object // * Dilation of above // * Input drawing // * Output drawing. // vtkImageIterator< unsigned char > it1( outputConverter->GetOutput(), segmentN->GetExtent()); vtkImageIterator< unsigned char > it2( segmentN, segmentN->GetExtent() ); vtkImageIterator< unsigned char > it3( inputImage, segmentN->GetExtent() ); vtkImageIterator< unsigned char > it4( dilatedConverter->GetOutput(), segmentN->GetExtent() ); while( !it2.IsAtEnd() ) { unsigned char *inSI = it1.BeginSpan(); unsigned char *inSIEnd = it1.EndSpan(); unsigned char *inSI2 = it2.BeginSpan(); unsigned char *inSI3 = it3.BeginSpan(); unsigned char *inSI4 = it3.BeginSpan(); while (inSI != inSIEnd) { unsigned char inputDrawingVal = *inSI3; if (*inSI == (unsigned char)n) { *inSI2 = inputDrawingVal; // Within the object } else if (*inSI4 && inputDrawingVal <= 127.5) { *inSI2 = inputDrawingVal; // Within the transition region } else { *inSI2 = 0; // Outside. } ++inSI; ++inSI2; ++inSI3; ++inSI4; } it1.NextSpan(); it2.NextSpan(); it3.NextSpan(); it4.NextSpan(); } } else // Binary case { vtkImageIterator< unsigned char > it1( outputConverter->GetOutput(), segmentN->GetExtent()); vtkImageIterator< unsigned char > it2( segmentN, segmentN->GetExtent() ); while( !it2.IsAtEnd() ) { unsigned char *inSI = it1.BeginSpan(); unsigned char *inSIEnd = it1.EndSpan(); unsigned char *inSI2 = it2.BeginSpan(); while (inSI != inSIEnd) { *inSI2 = ((*inSI == (unsigned char)n) ? 255 : 0); ++inSI; ++inSI2; } it1.NextSpan(); it2.NextSpan(); } } // Populate a sketch that encapsulates this segment and add it to the // drawing. vtkKWEPaintbrushSketch *sketchN = outputDrawing->AddItem(); vtkKWEPaintbrushData * data; // Convert this vtkImageData that represents the segment into // a vtkKWEPaintbrushData. if (inputDrawing->GetRepresentation() == vtkKWEPaintbrushEnums::Binary) { vtkKWEPaintbrushStencilData *sdata = vtkKWEPaintbrushStencilData::New(); vtkKWEPaintbrushUtilities::GetStencilFromImage< vtkKWEPaintbrushUtilities::vtkFunctorGreaterThan >( segmentN, sdata->GetImageStencilData(), 127.5 ); data = sdata; } else if (inputDrawing->GetRepresentation() == vtkKWEPaintbrushEnums::Grayscale) { vtkKWEPaintbrushGrayscaleData *sdata = vtkKWEPaintbrushGrayscaleData::New(); sdata->SetImageData( segmentN ); data = sdata; } else { std::cerr << "ERROR: Unsupported paintbrush representation" << std::endl; return 0; } // Copy over some default properties from the input drawing. vtkKWEPaintbrushProperty *inputProperty = inputDrawing->GetItem(this->SketchIndex)->GetPaintbrushProperty(); vtkKWEPaintbrushProperty *sketchNProperty = sketchN->GetPaintbrushProperty(); sketchNProperty->SetHighlightColor( inputProperty->GetHighlightColor() ); sketchNProperty->SetHighlightType( inputProperty->GetHighlightType() ); sketchNProperty->SetOpacity( inputProperty->GetOpacity() ); sketchN->SetPaintbrushData( data ); data->Delete(); } delete [] sketchExtents; return 1; } //---------------------------------------------------------------------------- int vtkKWEITKPaintbrushExtractConnectedComponents:: FillInputPortInformation(int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkKWEPaintbrushDrawing"); return 1; } //---------------------------------------------------------------------------- int vtkKWEITKPaintbrushExtractConnectedComponents::FillOutputPortInformation( int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkKWEPaintbrushDrawing"); return 1; } //---------------------------------------------------------------------------- // This method returns the largest region that can be generated. void vtkKWEITKPaintbrushExtractConnectedComponents::RequestInformation ( vtkInformation * vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector *outputVector) { vtkInformation *info = inputVector[0]->GetInformationObject(0); vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkKWEPaintbrushDrawing *inputDrawing = vtkKWEPaintbrushDrawing::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); // set the extent int wExtent[6]; inputDrawing->GetImageData()->GetExtent( wExtent ); outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wExtent, 6); } //---------------------------------------------------------------------------- int vtkKWEITKPaintbrushExtractConnectedComponents:: ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // create the output if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA_OBJECT())) { return this->RequestDataObject(request, inputVector, outputVector); } // generate the data if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) { this->RequestData(request, inputVector, outputVector); return 1; } // execute information if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION())) { this->RequestInformation(request, inputVector, outputVector); return 1; } return this->Superclass::ProcessRequest(request, inputVector, outputVector); } //---------------------------------------------------------------------------- int vtkKWEITKPaintbrushExtractConnectedComponents::RequestDataObject( vtkInformation*, vtkInformationVector** inputVector , vtkInformationVector* outputVector) { vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); if (!inInfo) { return 0; } vtkDataObject *input = inInfo->Get(vtkDataObject::DATA_OBJECT()); if (input) { // for each output for(int i=0; i < this->GetNumberOfOutputPorts(); ++i) { vtkInformation* info = outputVector->GetInformationObject(i); vtkDataObject *output = info->Get(vtkDataObject::DATA_OBJECT()); if (!output || !output->IsA(input->GetClassName())) { vtkDataObject* newOutput = input->NewInstance(); newOutput->SetPipelineInformation(info); newOutput->Delete(); this->GetOutputPortInformation(0)->Set( vtkDataObject::DATA_EXTENT_TYPE(), newOutput->GetExtentType()); } } return 1; } return 0; } //---------------------------------------------------------------------------- void vtkKWEITKPaintbrushExtractConnectedComponents:: SetInput(vtkKWEPaintbrushDrawing* input) { this->SetInputConnection(0,input->GetProducerPort()); } //---------------------------------------------------------------------------- vtkKWEPaintbrushDrawing* vtkKWEITKPaintbrushExtractConnectedComponents::GetOutput() { return vtkKWEPaintbrushDrawing::SafeDownCast(this->GetOutputDataObject(0)); } //---------------------------------------------------------------------------- void vtkKWEITKPaintbrushExtractConnectedComponents ::ComputeSegmentExtents( int nSegments, int *e, vtkImageData *image ) { vtkImageIterator< unsigned char > it(image, image->GetExtent()); for (int i = 0; i < nSegments; i++) { const int offset = i*6; e[offset] = e[offset + 2] = e[offset + 4] = VTK_INT_MAX; e[offset+1] = e[offset + 3] = e[offset + 5] = VTK_INT_MIN; } int extent[6]; image->GetExtent(extent); int ijk[3] = { extent[0], extent[2], extent[4] }; while( !it.IsAtEnd() ) { unsigned char *inSI = it.BeginSpan(); unsigned char *inSIEnd = it.EndSpan(); while (inSI != inSIEnd) { for (int i = 1; i <= nSegments; i++) { if (*inSI == i) { const int offset = (i-1)*6; for (int j = 0; j < 3; j++) { if (e[offset + 2*j] > ijk[j]) { e[offset + 2*j] = ijk[j]; } if (e[offset + 2*j +1] < ijk[j]) { e[offset + 2*j+1] = ijk[j]; } } } } ++inSI; ++ijk[0]; // Find out our structured coordinate in the image. } it.NextSpan(); if (ijk[0] > extent[1]) { ijk[0] = extent[0]; ++ijk[1]; if (ijk[1] > extent[3]) { ijk[1] = extent[2]; ++ijk[2]; } } } for (int i = 0; i < nSegments; i++) { const int offset = i*6; cout << e[offset] <<" " << e[offset + 1] << " " << e[offset + 2] << " " << e[offset + 3] << " " << e[offset + 4] << " " << e[offset + 5] << endl; } } vtkedge-0.2.0~20110819/Widgets/vtkKWEBoundingBoxRepresentation2D.cxx0000644000175000017500000013254111363410610024616 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEBoundingBoxRepresentation2D.h" #include "vtkSmartPointer.h" #include "vtkActor2D.h" #include "vtkActor.h" #include "vtkCamera.h" #include "vtkCellArray.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkInteractorObserver.h" #include "vtkEvent.h" #include "vtkSphereHandleRepresentation.h" #include "vtkImageActorPointPlacer.h" #include "vtkImageActor.h" #include "vtkImageData.h" #include "vtkSmartPointer.h" #include "vtkActor2DCollection.h" #include "vtkCollection.h" #include "vtkTextMapper.h" #include "vtkTextProperty.h" #include "vtkLine.h" #define min(x,y) ((xy) ? (x) : (y)) #define VTK_BBOXREP_TOLERANCE 0 // used to be 1e-4. I don't think this is needed. //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkKWEBoundingBoxRepresentation2D, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEBoundingBoxRepresentation2D); vtkCxxSetObjectMacro(vtkKWEBoundingBoxRepresentation2D, HandleProperty, vtkProperty); vtkCxxSetObjectMacro(vtkKWEBoundingBoxRepresentation2D, SelectedHandleProperty, vtkProperty); vtkCxxSetObjectMacro(vtkKWEBoundingBoxRepresentation2D, HoveredHandleProperty, vtkProperty); vtkCxxSetObjectMacro(vtkKWEBoundingBoxRepresentation2D, ImageData, vtkImageData); //---------------------------------------------------------------------------- vtkKWEBoundingBoxRepresentation2D::vtkKWEBoundingBoxRepresentation2D() { this->ImageData = NULL; this->ShowSliceScaleBar = 1; // Create a vtkPolydata for the bounding box. this->PolyData = vtkPolyData::New(); vtkPoints * points = vtkPoints::New(); points->SetNumberOfPoints(8); this->PolyData->SetPoints(points); for (int i = 0; i < 8 ; i++) { points->SetPoint( i, 0.0, 0.0, 0.0 ); } vtkCellArray *cellArray = vtkCellArray::New(); vtkIdType pts[6][4] = { { 1, 0, 2, 3 }, { 5, 4, 0, 1 }, { 5, 1, 3, 7 }, { 0, 4, 6, 2 }, { 3, 2, 6, 7 }, { 4, 5, 7, 6 } }; for (int i = 0; i < 6; i++) { cellArray->InsertNextCell( 4, pts[i] ); } this->PolyData->SetPolys(cellArray); cellArray->Delete(); points->Delete(); this->LastEventPosition[0] = this->LastEventPosition[1] = 0.0; // Construct the poly data representing the box this->BoxPolyData = vtkPolyData::New(); this->BoxMapper = vtkPolyDataMapper::New(); this->BoxActor = vtkActor::New(); this->BoxMapper->SetInput(this->BoxPolyData); this->BoxMapper->SetResolveCoincidentTopologyToPolygonOffset(); this->BoxActor->SetMapper(this->BoxMapper); this->BoxPoints = vtkPoints::New(VTK_DOUBLE); this->BoxPoints->SetNumberOfPoints(4); this->BoxPolyData->SetPoints(this->BoxPoints); // Topology of the box // 0 ------ 1 // | | // 3 ------ 2 // cellArray = vtkCellArray::New(); cellArray->InsertNextCell(5); cellArray->InsertCellPoint(0); cellArray->InsertCellPoint(1); cellArray->InsertCellPoint(3); cellArray->InsertCellPoint(2); cellArray->InsertCellPoint(0); this->BoxPolyData->SetLines(cellArray); cellArray->Delete(); // Set some default properties. // Handle properties this->HandleProperty = vtkProperty::New(); this->SelectedHandleProperty = vtkProperty::New(); this->HoveredHandleProperty = vtkProperty::New(); this->HandleProperty ->SetColor(1.0,1.0,0.7); this->SelectedHandleProperty->SetColor(0.9,1.0,0.5); this->HoveredHandleProperty ->SetColor(1.0,0.7,0.5); // Outline properties (for the hex and the chair) this->LineProperty = vtkProperty::New(); this->LineProperty->SetColor(1.0,0.3,0.1); this->LineProperty->SetLineWidth(2.0); this->SelectedLineProperty = vtkProperty::New(); this->SelectedLineProperty->SetColor(0.0,0.0,1.0); this->SelectedLineProperty->SetLineWidth(2.0); this->BoxActor->SetProperty(this->LineProperty); this->CurrentHandleIdx = -1; this->MinimumThickness[0] = 3.0; this->MinimumThickness[1] = 3.0; this->MinimumThickness[2] = 0.0; this->PlaceFactor = 1.0; this->PointPlacer = vtkImageActorPointPlacer::New(); // Handle looks like spheres. this->HandleRepresentation = NULL; this->HandleRepresentations = NULL; vtkSphereHandleRepresentation * hRep = vtkSphereHandleRepresentation::New(); hRep->SetProperty(this->HandleProperty); hRep->SetHandleSize(10.0); hRep->SetSelectedProperty(this->SelectedHandleProperty); hRep->SetPointPlacer( this->PointPlacer ); this->SetHandleRepresentation(hRep); hRep->Delete(); // Text annotation for the width and height this->TextActors = vtkActor2DCollection::New(); this->TextMappers = vtkCollection::New(); for (int i = 0; i < 2; i++) { vtkSmartPointer< vtkActor2D > actor = vtkSmartPointer< vtkActor2D >::New(); vtkSmartPointer< vtkTextMapper >mapper = vtkSmartPointer< vtkTextMapper >::New(); this->TextActors->AddItem( actor ); this->TextMappers->AddItem( mapper ); mapper->SetInput("0"); actor->SetMapper( mapper ); vtkTextProperty * textProperty = mapper->GetTextProperty(); textProperty->SetColor(1.0,0.7,0.5); textProperty->SetItalic(1); } this->LabelFormat = new char[6]; sprintf(this->LabelFormat,"%s","%0.1f"); // ---------------------------------------- // A scale bar on the right this->ScaleBar = vtkPolyData::New(); this->ScaleBar2 = vtkPolyData::New(); this->ScaleBarActor = vtkActor::New(); this->ScaleBarActor2 = vtkActor::New(); // --- // | // | // |- // | // | // | // --- // vtkPoints * scaleBarPoints = vtkPoints::New(); scaleBarPoints->SetNumberOfPoints(8); for (int i = 0; i < 8; i++) { scaleBarPoints->SetPoint(i, 0.0, 0.0, 0.0); } this->ScaleBar->SetPoints(scaleBarPoints); vtkCellArray *scaleBarCellArray = vtkCellArray::New(); this->ScaleBar->SetLines( scaleBarCellArray ); for (int i = 0; i < 4; i++) { scaleBarCellArray->InsertNextCell(2); scaleBarCellArray->InsertCellPoint(2*i); scaleBarCellArray->InsertCellPoint(2*i+1); } scaleBarCellArray->Delete(); this->ScaleBar2->SetPoints(scaleBarPoints); scaleBarCellArray = vtkCellArray::New(); this->ScaleBar2->SetLines( scaleBarCellArray ); scaleBarCellArray->InsertNextCell(2); scaleBarCellArray->InsertCellPoint(3); scaleBarCellArray->InsertCellPoint(4); scaleBarCellArray->Delete(); scaleBarPoints->Delete(); vtkPolyDataMapper *pdm = vtkPolyDataMapper::New(); pdm->SetInput(this->ScaleBar); pdm->SetResolveCoincidentTopologyToPolygonOffset(); this->ScaleBarActor->SetMapper( pdm ); pdm->Delete(); pdm = vtkPolyDataMapper::New(); pdm->SetInput(this->ScaleBar2); pdm->SetResolveCoincidentTopologyToPolygonOffset(); this->ScaleBarActor2->SetMapper( pdm ); pdm->Delete(); this->ScaleBarActor->GetProperty()->SetColor( 0.7, 1.0, 0.5 ); this->ScaleBarActor2->GetProperty()->SetColor( 0.7, 1.0, 0.5 ); this->ScaleBarActor2->GetProperty()->SetLineWidth(2.0); for (int i = 4; i < 6; i++) { vtkSphereHandleRepresentation *rep = vtkSphereHandleRepresentation::New(); this->HandleRepresentations[i] = rep; rep->SetHandleSize(7.0); } // The slice text actors and mappers. for (int i = 0; i < 2; i++) { vtkSmartPointer< vtkActor2D > actor = vtkSmartPointer< vtkActor2D >::New(); vtkSmartPointer< vtkTextMapper >mapper = vtkSmartPointer< vtkTextMapper >::New(); this->TextActors->AddItem( actor ); this->TextMappers->AddItem( mapper ); mapper->SetInput("0"); actor->SetMapper( mapper ); vtkTextProperty * textProperty = mapper->GetTextProperty(); textProperty->SetColor(0.8, 1.0, 0.5); } this->Unplaced = 1; this->Fade = 0; this->ID = -1; this->InteractionState = Outside; this->Point1DisplayPosition[0] = this->Point1DisplayPosition[1] = VTK_INT_MIN; // Add an ID Text actor. vtkSmartPointer< vtkActor2D > actor = vtkSmartPointer< vtkActor2D >::New(); vtkSmartPointer< vtkTextMapper >mapper = vtkSmartPointer< vtkTextMapper >::New(); this->TextActors->AddItem( actor ); this->TextMappers->AddItem( mapper ); actor->SetMapper(mapper); actor->VisibilityOff(); vtkTextProperty * textProperty = mapper->GetTextProperty(); textProperty->SetColor(1.0,0.7,0.5); textProperty->SetItalic(1); } //---------------------------------------------------------------------------- vtkKWEBoundingBoxRepresentation2D::~vtkKWEBoundingBoxRepresentation2D() { this->PolyData ->Delete(); this->BoxActor ->Delete(); this->BoxMapper ->Delete(); this->BoxPolyData ->Delete(); this->BoxPoints ->Delete(); this->LineProperty ->Delete(); this->PointPlacer ->Delete(); this->SelectedLineProperty ->Delete(); this->TextActors ->Delete(); this->TextMappers ->Delete(); this->ScaleBar ->Delete(); this->ScaleBarActor ->Delete(); this->ScaleBar2 ->Delete(); this->ScaleBarActor2 ->Delete(); this->SetHandleRepresentation ( NULL ); this->SetHandleProperty ( NULL ); this->SetSelectedHandleProperty ( NULL ); this->SetHoveredHandleProperty ( NULL ); this->SetLabelFormat ( NULL ); this->SetImageData ( NULL ); } //---------------------------------------------------------------------------- vtkHandleRepresentation* vtkKWEBoundingBoxRepresentation2D ::GetHandleRepresentation( int handleIndex ) { return (handleIndex > 5) ? NULL : this->HandleRepresentations[handleIndex]; } //---------------------------------------------------------------------- // You can swap the handle representation to one that you like. void vtkKWEBoundingBoxRepresentation2D ::SetHandleRepresentation(vtkHandleRepresentation *handle) { if ( handle == this->HandleRepresentation ) { return; } vtkSetObjectBodyMacro( HandleRepresentation, vtkHandleRepresentation, handle ); if (this->HandleRepresentation) { // Allocate the 4 handles if they haven't been allocated. if (!this->HandleRepresentations) { this->HandleRepresentations = new vtkHandleRepresentation* [6]; for (int i=0; i<6; i++) { this->HandleRepresentations[i] = NULL; } } } else { // Free the 4 handles if they haven't been freed. if (this->HandleRepresentations) { for (int i=0; i<6; i++) { this->HandleRepresentations[i]->Delete(); } delete [] this->HandleRepresentations; this->HandleRepresentations = NULL; } } for (int i=0; i<4; i++) { // We will remove the old handle, in anticipation of the new user- // provided handle type that we are going to set a few lines later. if (this->HandleRepresentations && this->HandleRepresentations[i]) { this->HandleRepresentations[i]->Delete(); this->HandleRepresentations[i] = NULL; } // Copy the new user-provided handle. if (this->HandleRepresentation) { this->HandleRepresentations[i] = this->HandleRepresentation->NewInstance(); this->HandleRepresentations[i]->ShallowCopy(this->HandleRepresentation); this->HandleRepresentations[i]->Highlight(0); } } } //---------------------------------------------------------------------------- void vtkKWEBoundingBoxRepresentation2D::SetImageActor( vtkImageActor *a ) { if (a != this->PointPlacer->GetImageActor()) { this->PointPlacer->SetImageActor(a); // Default placement. if (a && this->ImageData) { this->Unplaced = 1; } } } //---------------------------------------------------------------------------- void vtkKWEBoundingBoxRepresentation2D::PlaceWidget() { vtkImageActor * a = this->GetImageActor(); if (!a || !this->ImageData) { vtkErrorMacro( << "ImageActor and ImageData must be set prior to placing the widget."); } this->PointPlacer->SetImageActor(a); double bounds[6]; this->ImageData->GetBounds(bounds); for (int i = 0; i < 3; i ++) { const double c = bounds[2*i+1] - bounds[2*i]; bounds[2*i] += c/10.0; bounds[2*i+1] -= c/10.0; } this->PlaceWidget( bounds ); } //---------------------------------------------------------------------------- vtkImageActor * vtkKWEBoundingBoxRepresentation2D::GetImageActor() { return this->PointPlacer->GetImageActor(); } //---------------------------------------------------------------------- // This is where the bulk of the work is done. int vtkKWEBoundingBoxRepresentation2D ::ComputeInteractionState(int X, int Y, int vtkNotUsed(modify)) { // ----------------------------------------------------------- double worldOrient[9]; if ( this->InteractionState == BeginDefining ) { this->Point1DisplayPosition[0] = X; this->Point1DisplayPosition[1] = Y; this->Point2DisplayPosition[0] = X; this->Point2DisplayPosition[1] = Y; this->InteractionState = Defining; } else if ( this->InteractionState == Defining ) { this->Point2DisplayPosition[0] = X; this->Point2DisplayPosition[1] = Y; } if (this->InteractionState == BeginDefining || this->InteractionState == Defining || this->InteractionState == EndDefining ) { double point1WorldPos[3], point2WorldPos[3], bounds[6]; if (this->ComputeOrientation() && this->PointPlacer->ComputeWorldPosition( this->Renderer, this->Point1DisplayPosition, point1WorldPos, worldOrient ) && this->PointPlacer->ComputeWorldPosition( this->Renderer, this->Point2DisplayPosition, point2WorldPos, worldOrient ) ) { this->ImageData->GetBounds(bounds); bounds[2*XAxis] = min(point1WorldPos[XAxis], point2WorldPos[XAxis]); bounds[2*XAxis+1] = max(point1WorldPos[XAxis], point2WorldPos[XAxis]); bounds[2*YAxis] = min(point1WorldPos[YAxis], point2WorldPos[YAxis]); bounds[2*YAxis+1] = max(point1WorldPos[YAxis], point2WorldPos[YAxis]); int success = this->PlaceWidgetInternal(bounds); if (this->InteractionState == EndDefining) { // If we did not successfully placed the widget, go back and start // defining it all over again this->InteractionState = (success ? Outside : BeginDefining); // If we successfully placed the widget, update the Unplaced ivar to // reflect that. this->Unplaced = (success ? 0 : 1); } } } // ----------------------------------------------------------- else if ( this->InteractionState == RequestResizeBox ) { this->CurrentHandleIdx = -1; // We are trying to perform user interaction that might potentially // select a handle. Check if we are really near a handle, so it // can be selected. // Loop over all the handles and check if one of them is selected for(int i = 0; i< (this->ShowSliceScaleBar ? 6 : 4); i++) { this->HandleRepresentations[i]->ComputeInteractionState(X, Y, 0); if (this->HandleRepresentations[i]->GetInteractionState() == vtkHandleRepresentation::Selecting) { // The selected handle. this->CurrentHandleIdx = i; // Highlight the selected handle and unhighlight all others. this->SetHandleHighlight(-1, this->HandleProperty); this->SetHandleHighlight( this->CurrentHandleIdx, this->SelectedHandleProperty); this->InteractionState = vtkKWEBoundingBoxRepresentation2D::Resizing; break; } } if (this->InteractionState == RequestResizeBox) { // We aren't near any of the handles, otherwise our state would have // changed to Resizing. We are definitely outside. this->InteractionState = Outside; } } // (B) ----------------------------------------------------------- // Handle the resizing operations. else if (this->InteractionState == vtkKWEBoundingBoxRepresentation2D::Resizing) { // Ensure that a handle has been picked. if (this->CurrentHandleIdx != -1) { // Compute world positions corresponding to the current event position // (X,Y) and the last event positions such that they lie at the same // depth that the handle lies on. double handleWorldPos[4], handleTranslation[3], handleDisplayPos[4], newHandleWorldPos[3]; this->HandleRepresentations[this->CurrentHandleIdx] ->GetWorldPosition(handleWorldPos); this->HandleRepresentations[this->CurrentHandleIdx] ->GetDisplayPosition(handleDisplayPos); // The motion vector in display coords const double motionVector[3] = { X - this->LastEventPosition[0], Y - this->LastEventPosition[1], 0.0 }; handleDisplayPos[0] += motionVector[0]; handleDisplayPos[1] += motionVector[1]; if (this->CurrentHandleIdx < 4) { if (this->PointPlacer->ComputeWorldPosition( this->Renderer, handleDisplayPos, newHandleWorldPos, worldOrient ) ) { handleTranslation[0] = newHandleWorldPos[0] - handleWorldPos[0]; handleTranslation[1] = newHandleWorldPos[1] - handleWorldPos[1]; handleTranslation[2] = newHandleWorldPos[2] - handleWorldPos[2]; // Translate handle and its neighbors. this->Translate( handleTranslation, motionVector ); } } else { this->Translate( handleTranslation, motionVector ); } } else { // In theory, we should never get there. this->InteractionState = vtkKWEBoundingBoxRepresentation2D::Outside; } } else { this->InteractionState = vtkKWEBoundingBoxRepresentation2D::Outside; // Loop over all the handles and check if we are near one of them. for(int i = 0; i< 6; i++) { this->HandleRepresentations[i]->ComputeInteractionState(X, Y, 0); if (this->HandleRepresentations[i]->GetInteractionState() == vtkHandleRepresentation::Selecting) { this->SetHandleHighlight( i, this->HoveredHandleProperty ); this->InteractionState = vtkKWEBoundingBoxRepresentation2D::Inside; break; } } if (this->InteractionState == vtkKWEBoundingBoxRepresentation2D::Outside) { // Unhighlight all handles and faces. this->SetHandleHighlight( -1, this->HandleProperty ); } } // Cache the last event position. this->LastEventPosition[0] = X; this->LastEventPosition[1] = Y; return this->InteractionState; } //---------------------------------------------------------------------------- void vtkKWEBoundingBoxRepresentation2D ::Translate( const double translation[3], const double cursorMotionVector[3] ) { if (!this->ComputeOrientation()) { return; } if (this->CurrentHandleIdx < 4) { double handleWorldPos[3], bounds[6]; const double tolerance = 1e-1; this->PolyData->GetBounds( bounds ); this->HandleRepresentations[ this->CurrentHandleIdx]->GetWorldPosition(handleWorldPos); for (unsigned int k = 0; k < 3; k++) { if (fabs(handleWorldPos[k] - bounds[2*k]) < tolerance) { bounds[2*k] += translation[k]; } else if (fabs(handleWorldPos[k] - bounds[2*k+1]) < tolerance) { bounds[2*k+1] += translation[k]; } } this->PlaceWidget(bounds); this->Cut(); this->PositionHandles(); } else { if (cursorMotionVector[1] == 0.0) { return; } double imageSliceBoundsW[2][3], bboxBoundsW[2][3], t; this->ScaleBar->GetPoints()->GetPoint(2, imageSliceBoundsW[0]); this->ScaleBar->GetPoints()->GetPoint(5, imageSliceBoundsW[1]); this->ScaleBar->GetPoints()->GetPoint(3, bboxBoundsW[0]); this->ScaleBar->GetPoints()->GetPoint(4, bboxBoundsW[1]); double handleDisplayPos[3], worldOrient[9], newHandleWorldPos[3]; this->HandleRepresentations[this->CurrentHandleIdx]-> GetDisplayPosition(handleDisplayPos); handleDisplayPos[1] += cursorMotionVector[1]; this->PointPlacer->ComputeWorldPosition( this->Renderer, handleDisplayPos, newHandleWorldPos, worldOrient ); if (this->CurrentHandleIdx == 4) { vtkLine::DistanceToLine( newHandleWorldPos, imageSliceBoundsW[0], bboxBoundsW[1], t, newHandleWorldPos ); } else { vtkLine::DistanceToLine( newHandleWorldPos, imageSliceBoundsW[1], bboxBoundsW[0], t, newHandleWorldPos ); } // Now find the slice extents. t = fabs(imageSliceBoundsW[1][YAxis] - newHandleWorldPos[YAxis]) / fabs(imageSliceBoundsW[1][YAxis] - imageSliceBoundsW[0][YAxis]); double bounds[6], bbbounds[6]; this->PolyData->GetBounds( bbbounds ); this->ImageData->GetBounds(bounds); bbbounds[2*ZAxis + this->CurrentHandleIdx-4] = t * bounds[2*ZAxis] + (1-t) * bounds[2*ZAxis+1]; // Ensure that teh current slice is within the bounds, if not clamp it. // int extent[6]; this->GetImageActor()->GetDisplayExtent(extent); double displayBounds[2], spacing[3], origin[3]; this->ImageData->GetSpacing(spacing); this->ImageData->GetOrigin(origin); displayBounds[0] = extent[2*ZAxis] * spacing[ZAxis] + origin[ZAxis] - VTK_BBOXREP_TOLERANCE; displayBounds[1] = extent[2*ZAxis+1] * spacing[ZAxis] + origin[ZAxis] + VTK_BBOXREP_TOLERANCE; bbbounds[2*ZAxis] = (bbbounds[2*ZAxis] > displayBounds[0]) ? displayBounds[0] : bbbounds[2*ZAxis]; bbbounds[2*ZAxis+1] = (bbbounds[2*ZAxis+1] < displayBounds[1]) ? displayBounds[1] : bbbounds[2*ZAxis+1]; // Now place the widget.. our slice may have changed. this->PlaceWidget(bbbounds); } } //---------------------------------------------------------------------- void vtkKWEBoundingBoxRepresentation2D::GetActors2D(vtkPropCollection *pc) { vtkActor2D* actor; vtkCollectionSimpleIterator adit; for ( this->TextActors->InitTraversal(adit); (actor = this->TextActors->GetNextActor2D(adit));) { actor->GetActors(pc); } } //---------------------------------------------------------------------- void vtkKWEBoundingBoxRepresentation2D::GetActors(vtkPropCollection *pc) { for (int i=0; i < (this->ShowSliceScaleBar ? 6 : 4); i++) { this->HandleRepresentations[i]->GetActors(pc); } this->BoxActor->GetActors(pc); this->ScaleBarActor->GetActors(pc); } //---------------------------------------------------------------------- void vtkKWEBoundingBoxRepresentation2D::ReleaseGraphicsResources(vtkWindow *w) { this->BoxActor->ReleaseGraphicsResources(w); for (int i=0; i< 6; i++) { this->HandleRepresentations[i]->ReleaseGraphicsResources(w); } this->ScaleBarActor->ReleaseGraphicsResources(w); this->ScaleBarActor2->ReleaseGraphicsResources(w); } //---------------------------------------------------------------------- int vtkKWEBoundingBoxRepresentation2D::RenderOverlay(vtkViewport *v) { int count = 0; // Render if we have been placed or if we are in the process of placing if (this->Unplaced == 0 || this->InteractionState == Defining) { if (this->BoxActor->GetVisibility()) { count += this->BoxActor->RenderOverlay(v); } for (int i=0; i< (this->ShowSliceScaleBar ? 6 : 4); i++) { if (this->HandleRepresentations[i]->GetVisibility()) { count+=this->HandleRepresentations[i]->RenderOverlay(v); } } vtkActor2D* actor; vtkCollectionSimpleIterator adit; for ( this->TextActors->InitTraversal(adit); (actor = this->TextActors->GetNextActor2D(adit));) { // Make sure that the actor is visible before rendering if (actor->GetVisibility()) { count += actor->RenderOverlay(v); } } if (this->ShowSliceScaleBar) { if (this->ScaleBarActor->GetVisibility()) { count+=this->ScaleBarActor->RenderOverlay(v); } if (this->ScaleBarActor2->GetVisibility()) { count+=this->ScaleBarActor2->RenderOverlay(v); } } } return count; } //---------------------------------------------------------------------------- int vtkKWEBoundingBoxRepresentation2D::RenderOpaqueGeometry(vtkViewport *viewport) { int count = 0; this->BuildRepresentation(); // Render if we have been placed or if we are in the process of placing if (this->Unplaced == 0 || this->InteractionState == Defining) { if (this->BoxActor->GetVisibility()) { count+=this->BoxActor->RenderOpaqueGeometry(viewport); } for (int i=0; i< (this->ShowSliceScaleBar ? 6 : 4); i++) { if (this->HandleRepresentations[i]->GetVisibility()) { count += this->HandleRepresentations[i]->RenderOpaqueGeometry(viewport); } } vtkActor2D* actor; vtkCollectionSimpleIterator adit; for ( this->TextActors->InitTraversal(adit); (actor = this->TextActors->GetNextActor2D(adit));) { // Make sure that the actor is visible before rendering if (actor->GetVisibility()) { count += actor->RenderOpaqueGeometry(viewport); } } if (this->ShowSliceScaleBar) { if (this->ScaleBarActor->GetVisibility()) { count+=this->ScaleBarActor->RenderOpaqueGeometry(viewport); } if (this->ScaleBarActor2->GetVisibility()) { count+=this->ScaleBarActor2->RenderOpaqueGeometry(viewport); } } } return count; } //---------------------------------------------------------------------------- void vtkKWEBoundingBoxRepresentation2D::PositionHandles() { bool modified = false; double newPos[3], oldPos[3]; for (int i = 0; i < 4; ++i) { this->HandleRepresentations[i]->GetWorldPosition(oldPos); this->BoxPoints->GetPoint(i, newPos); if (oldPos[0] != newPos[0] || oldPos[1] != newPos[1] || oldPos[2] != newPos[2]) { this->HandleRepresentations[i]->SetWorldPosition(newPos); modified = true; } } // The position has changed. Force the actor to update the next time. if (modified) { this->BoxPolyData->Modified(); } } //---------------------------------------------------------------------------- void vtkKWEBoundingBoxRepresentation2D::SetHandleHighlight( int handleIdx, vtkProperty *property ) { if ( handleIdx == -1) { // Do for all handles for (int i = 0; i < (this->ShowSliceScaleBar ? 6 : 4); i++) { static_cast< vtkSphereHandleRepresentation * >( this->HandleRepresentations[i])->SetProperty(property); static_cast< vtkSphereHandleRepresentation * >( this->HandleRepresentations[i])->SetSelectedProperty(property); } } else { static_cast< vtkSphereHandleRepresentation * >( this->HandleRepresentations[handleIdx])->SetProperty(property); static_cast< vtkSphereHandleRepresentation * >( this->HandleRepresentations[handleIdx])->SetSelectedProperty(property); } } //---------------------------------------------------------------------------- void vtkKWEBoundingBoxRepresentation2D::PlaceWidget(double bounds[6]) { if (this->PlaceWidgetInternal(bounds)) { // we are no longer defining. We've been placed. this->Unplaced = 0; } } //---------------------------------------------------------------------------- int vtkKWEBoundingBoxRepresentation2D::PlaceWidgetInternal(double bounds[6]) { double corners[8][3] = { { bounds[0], bounds[2], bounds[4] }, { bounds[1], bounds[2], bounds[4] }, { bounds[0], bounds[3], bounds[4] }, { bounds[1], bounds[3], bounds[4] }, { bounds[0], bounds[2], bounds[5] }, { bounds[1], bounds[2], bounds[5] }, { bounds[0], bounds[3], bounds[5] }, { bounds[1], bounds[3], bounds[5] } }; vtkImageActor *imageActor = this->GetImageActor(); if (!imageActor || !this->ImageData) { vtkErrorMacro( << "ImageActor and ImageData must be set prior to placing the widget."); return 0; } // Scale the corners of parallelopiped according to the place factor. double center[3] = {0.0, 0.0, 0.0}, newCorners[8][3]; for (int j = 0; j < 3; j++) { for (int i = 0; i < 8; i++) { center[j] += corners[i][j]; } center[j] /= 8.0; for (int i = 0; i < 8; i++) { newCorners[i][j] = center[j] + this->PlaceFactor*(corners[i][j]-center[j]); } } // Make sure that the thickness is greater than minimum thickness. double spacing[3]; this->ImageData->GetSpacing(spacing); if (this->InteractionState == Defining || this->InteractionState == BeginDefining || ((sqrt(vtkMath::Distance2BetweenPoints(newCorners[0], newCorners[1])) >= this->MinimumThickness[0]*spacing[0]) && (sqrt(vtkMath::Distance2BetweenPoints(newCorners[0], newCorners[2])) >= this->MinimumThickness[1]*spacing[1]) && (sqrt(vtkMath::Distance2BetweenPoints(newCorners[0], newCorners[4])) >= this->MinimumThickness[2]*spacing[2])) ) { vtkPoints * points = this->PolyData->GetPoints(); for (int i = 0; i < 8; i++) { points->SetPoint(i, newCorners[i] ); } this->PolyData->Modified(); if (this->Cut()) { this->PositionHandles(); this->AnnotateScaleBar(); return 1; } } return 0; } //---------------------------------------------------------------------------- vtkPolyData * vtkKWEBoundingBoxRepresentation2D::GetPolyData() { return this->PolyData; } //---------------------------------------------------------------------------- void vtkKWEBoundingBoxRepresentation2D::BuildRepresentation() { // If we are placed or are in the process of placing, render. if (this->Unplaced == 0 || this->InteractionState == Defining) { this->Cut(); this->Annotate(); } } //---------------------------------------------------------------------------- int vtkKWEBoundingBoxRepresentation2D::Cut() { if (!this->ComputeOrientation()) { this->SetVisibilityInternal(0); return 0; } vtkImageActor *imageActor = this->GetImageActor(); double bounds[6], origin[3], spacing[3]; int displayExtent[6]; this->PolyData->GetBounds(bounds); this->ImageData->GetOrigin(origin); this->ImageData->GetSpacing(spacing); imageActor->GetDisplayExtent(displayExtent); const double depth = origin[ZAxis] + displayExtent[ZAxis*2]*spacing[ZAxis]; // cout << "SliceDepth: " << depth << " " // << bounds[2*ZAxis] << " " << bounds[2*ZAxis+1] << endl; int sliceExtent[2] = { vtkMath::Round((bounds[2*ZAxis]-origin[ZAxis])/spacing[ZAxis]), vtkMath::Round((bounds[2*ZAxis+1]-origin[ZAxis])/spacing[ZAxis]) }; double sliceBounds[2] = { sliceExtent[0] * spacing[ZAxis] + origin[ZAxis], sliceExtent[1] * spacing[ZAxis] + origin[ZAxis] }; // Check if we should display the box at all. Are we within the bounds ? if (depth < sliceBounds[0] || depth > sliceBounds[1]) { this->SetVisibilityInternal(0); return 0; } this->SetVisibilityInternal(1); // BoxPoints... // 0 ----- 1 // | | // 3 ----- 2 // this->BoxPoints->SetPoint(0, bounds[2*XAxis], bounds[2*YAxis], depth); this->BoxPoints->SetPoint(1, bounds[2*XAxis+1], bounds[2*YAxis], depth); this->BoxPoints->SetPoint(2, bounds[2*XAxis], bounds[2*YAxis+1], depth); this->BoxPoints->SetPoint(3, bounds[2*XAxis+1], bounds[2*YAxis+1], depth); this->PositionHandles(); return 1; } //---------------------------------------------------------------------------- int vtkKWEBoundingBoxRepresentation2D::ComputeOrientation() { vtkImageActor *imageActor = this->PointPlacer->GetImageActor(); if (!this->Renderer || !imageActor || !this->ImageData) { return 0; } double viewUp[3]; int displayExtent[6]; imageActor->GetDisplayExtent(displayExtent); if ( displayExtent[0] == displayExtent[1] ) { ZAxis = 0; } else if ( displayExtent[2] == displayExtent[3] ) { ZAxis = 1; } else if ( displayExtent[4] == displayExtent[5] ) { ZAxis = 2; } else { vtkErrorMacro("Incorrect display extent in Image Actor"); return 0; } vtkCamera * cam = this->Renderer->GetActiveCamera(); cam->GetViewUp(viewUp); for (int i = 0; i < 3; i++) { if (fabs(viewUp[i]) > 0.95) { YAxis = i; continue; } if (i == ZAxis) { continue; } XAxis = i; } return 1; } //---------------------------------------------------------------------------- int vtkKWEBoundingBoxRepresentation2D::Annotate() { double p[3][3], dispPos[3][3]; this->TextActors->InitTraversal(); for (int i = 0; i < 3; i++) { this->HandleRepresentations[i]->GetDisplayPosition(dispPos[i]); this->BoxPoints->GetPoint(i, p[i]); } double lengths[2] = { sqrt(vtkMath::Distance2BetweenPoints( p[0], p[1] )), sqrt(vtkMath::Distance2BetweenPoints( p[0], p[2] )) }; int textSize[2], stringSize[2], *winSize = this->Renderer->GetSize(); for (int i = 0; i < 2; i++) { vtkTextMapper * mapper = static_cast< vtkTextMapper * >( this->TextMappers->GetItemAsObject(i)); char distStr[256]; sprintf(distStr, this->LabelFormat, lengths[i]); mapper->SetInput( distStr ); vtkTextMapper::SetRelativeFontSize( mapper, this->Renderer, winSize, stringSize, 0.012f); mapper->GetSize(this->Renderer, textSize); if (i == 0) { this->TextActors->GetNextActor2D()->SetPosition( (dispPos[0][0] + dispPos[1][0])/2.0 - textSize[0]/1.8, (dispPos[0][1] + dispPos[1][1])/2.0 + textSize[1] * 0.5 ); } else { this->TextActors->GetNextActor2D()->SetPosition( (dispPos[0][0] + dispPos[2][0])/2.0 - textSize[0] * 1.1, (dispPos[0][1] + dispPos[2][1])/2.0 - textSize[1]/1.8 ); } } // Annotate the scale bar as well. this->AnnotateScaleBar(); // Annotate the ID field. vtkActor2D * tac = static_cast< vtkActor2D * >( this->TextActors->GetItemAsObject(4)); if (this->ID == -1) { tac->SetVisibility(0); } else { tac->SetVisibility(this->BoxActor->GetVisibility()); vtkTextMapper * mapper = static_cast< vtkTextMapper * >( this->TextMappers->GetItemAsObject(4)); char distStr[10]; sprintf(distStr, "%d:", this->ID); mapper->SetInput( distStr ); vtkTextMapper::SetRelativeFontSize( mapper, this->Renderer, winSize, stringSize, 0.012f); mapper->GetSize(this->Renderer, textSize); tac->SetPosition( dispPos[0][0] - textSize[0] * 1.5, dispPos[0][1] - textSize[1]/1.8 ); } return 1; } //---------------------------------------------------------------------------- int vtkKWEBoundingBoxRepresentation2D::AnnotateScaleBar() { vtkImageActor *imageActor = this->PointPlacer->GetImageActor(); if (!this->Renderer || !imageActor || !this->ShowSliceScaleBar || !this->ImageData) { return 0; } double bounds[6], handleWorldPos[4][3]; for (int i = 0; i < 4; i++) { this->BoxPoints->GetPoint(i, handleWorldPos[i]); } // Width of actor is a tenth of the width of the bbox. const double width = sqrt( vtkMath::Distance2BetweenPoints(handleWorldPos[0], handleWorldPos[1]))/10.0; vtkPoints *scaleBarPoints = this->ScaleBar->GetPoints(); double offsetVector[3] = { handleWorldPos[1][0] - handleWorldPos[0][0], handleWorldPos[1][1] - handleWorldPos[0][1], handleWorldPos[1][2] - handleWorldPos[0][2] }; vtkMath::Normalize( offsetVector ); scaleBarPoints->SetPoint( 0, handleWorldPos[3][0] + 2 * width * offsetVector[0], handleWorldPos[3][1] + 2 * width * offsetVector[1], handleWorldPos[3][2] + 2 * width * offsetVector[2] ); scaleBarPoints->SetPoint( 1, handleWorldPos[3][0] + 3 * width * offsetVector[0], handleWorldPos[3][1] + 3 * width * offsetVector[1], handleWorldPos[3][2] + 3 * width * offsetVector[2] ); scaleBarPoints->SetPoint( 2, handleWorldPos[3][0] + 2.5 * width * offsetVector[0], handleWorldPos[3][1] + 2.5 * width * offsetVector[1], handleWorldPos[3][2] + 2.5 * width * offsetVector[2]); scaleBarPoints->SetPoint( 5, handleWorldPos[1][0] + 2.5 * width * offsetVector[0], handleWorldPos[1][1] + 2.5 * width * offsetVector[1], handleWorldPos[1][2] + 2.5 * width * offsetVector[2]); scaleBarPoints->SetPoint( 6, handleWorldPos[1][0] + 2 * width * offsetVector[0], handleWorldPos[1][1] + 2 * width * offsetVector[1], handleWorldPos[1][2] + 2 * width * offsetVector[2] ); scaleBarPoints->SetPoint( 7, handleWorldPos[1][0] + 3 * width * offsetVector[0], handleWorldPos[1][1] + 3 * width * offsetVector[1], handleWorldPos[1][2] + 3 * width * offsetVector[2]); double bbbounds[6], endPoints[2][3], pp[2][3]; this->PolyData->GetBounds(bbbounds); this->ImageData->GetBounds(bounds); scaleBarPoints->GetPoint(2, endPoints[0]); scaleBarPoints->GetPoint(5, endPoints[1]); for (int i = 0; i < 2; i++) { const double fraction = fabs(bbbounds[2*ZAxis+i] - bounds[2*ZAxis]) / (bounds[2*ZAxis+1] - bounds[2*ZAxis]); for (int j = 0; j < 3; j++) { pp[i][j] = fraction * endPoints[1][j] + (1.0-fraction) * endPoints[0][j]; } } scaleBarPoints->SetPoint( 3, pp[0] ); scaleBarPoints->SetPoint( 4, pp[1] ); this->HandleRepresentations[4]->SetWorldPosition(pp[0]); this->HandleRepresentations[5]->SetWorldPosition(pp[1]); scaleBarPoints->Modified(); // Annotate slice-scale text. int extent[6]; this->GetExtent(extent); for (int i = 2; i < 4; i++) { vtkTextMapper * mapper = static_cast< vtkTextMapper * >( this->TextMappers->GetItemAsObject(i)); char distStr[100]; sprintf(distStr, "%d", extent[2*ZAxis+(i-2)]+1); mapper->SetInput( distStr ); int textSize[2], stringSize[2], *winSize = this->Renderer->GetSize(); vtkTextMapper::SetRelativeFontSize( mapper, this->Renderer, winSize, stringSize, 0.012f); mapper->GetSize(this->Renderer, textSize); double dispPos[3]; this->HandleRepresentations[i+2]->GetDisplayPosition(dispPos); static_cast< vtkActor2D * >(this->TextActors->GetItemAsObject(i)) ->SetPosition( dispPos[0] + textSize[0]/1.8, dispPos[1] ); } return 1; } //---------------------------------------------------------------------------- void vtkKWEBoundingBoxRepresentation2D::SetExtent( int extents[6] ) { if (!this->ComputeOrientation()) { vtkErrorMacro( << "Check if the renderer, imageActor have been set and " << "that the image actor has an input.") return; } double bounds[6], origin[3], spacing[3]; this->PolyData->GetBounds(bounds); this->ImageData->GetOrigin(origin); this->ImageData->GetSpacing(spacing); for (int i = 0; i < 3; i++) { bounds[2*i] = extents[2*i] * spacing[i] + origin[i]; bounds[2*i+1] = extents[2*i+1] * spacing[i] + origin[i]; } this->PlaceWidget(bounds); } //---------------------------------------------------------------------------- int vtkKWEBoundingBoxRepresentation2D::GetExtent( int extents[6] ) { extents[0] = extents[2] = extents[4] = 0; extents[1] = extents[3] = extents[5] = -1; // Sanity check first, before we proceed to compute the extents. if (!this->Renderer || !this->ImageData || this->InteractionState == BeginDefining || (this->InteractionState == EndDefining && this->Unplaced == 1)) { return 0; } // The extents are easily computed from the bounds of the cuboid that // we use to represent out Bounding box, the iVar "PolyData" double bounds[6], origin[3], spacing[3]; this->PolyData->GetBounds(bounds); this->ImageData->GetOrigin(origin); this->ImageData->GetSpacing(spacing); for (int i = 0; i < 3; i++) { extents[2*i] = vtkMath::Round((bounds[2*i]-origin[i])/spacing[i]); extents[2*i+1] = vtkMath::Round((bounds[2*i+1]-origin[i])/spacing[i]); if (extents[2*i] > extents[2*i+1]) { extents[0] = extents[2] = extents[4] = 0; extents[1] = extents[3] = extents[5] = -1; return 0; } } // Sanity check. if (extents[0] == extents[1] && extents[2] == extents[3] && extents[4] == extents[5]) { return 0; } return 1; } //---------------------------------------------------------------------------- void vtkKWEBoundingBoxRepresentation2D::SetVisibilityInternal( int vis ) { // for everything but the bbox. int v = ((vis == 1 && this->Fade == 0) ? 1 : 0); for (int i=0; i< 4; i++) { this->HandleRepresentations[i]->SetVisibility( this->InteractionState != Defining ? v : 0); } for (int i=4; i< 6; i++) { this->HandleRepresentations[i]->SetVisibility( (this->ShowSliceScaleBar && this->InteractionState != Defining) ? v : 0); } this->BoxActor->SetVisibility(vis); this->ScaleBarActor->SetVisibility( (this->ShowSliceScaleBar && this->InteractionState != Defining) ? v : 0); this->ScaleBarActor2->SetVisibility( (this->ShowSliceScaleBar && this->InteractionState != Defining) ? v : 0); this->TextActors->InitTraversal(); // size annotation this->TextActors->GetNextActor2D()->SetVisibility( this->InteractionState != Defining ? vis : 0); this->TextActors->GetNextActor2D()->SetVisibility( this->InteractionState != Defining ? vis : 0); // Slice annotation. this->TextActors->GetNextActor2D()->SetVisibility( (this->ShowSliceScaleBar && this->InteractionState != Defining) ? v : 0); this->TextActors->GetNextActor2D()->SetVisibility( (this->ShowSliceScaleBar && this->InteractionState != Defining) ? v : 0); } //---------------------------------------------------------------------------- vtkProperty * vtkKWEBoundingBoxRepresentation2D::GetOutlineProperty() { return this->BoxActor->GetProperty(); } //---------------------------------------------------------------------------- vtkTextProperty * vtkKWEBoundingBoxRepresentation2D::GetWidthTextProperty() { vtkTextMapper * mapper = static_cast< vtkTextMapper * >( this->TextMappers->GetItemAsObject(0)); return mapper->GetTextProperty(); } //---------------------------------------------------------------------------- vtkTextProperty * vtkKWEBoundingBoxRepresentation2D::GetHeightTextProperty() { vtkTextMapper * mapper = static_cast< vtkTextMapper * >( this->TextMappers->GetItemAsObject(1)); return mapper->GetTextProperty(); } //---------------------------------------------------------------------------- vtkTextProperty * vtkKWEBoundingBoxRepresentation2D::GetIDTextProperty() { vtkTextMapper * mapper = static_cast< vtkTextMapper * >( this->TextMappers->GetItemAsObject(4)); return mapper->GetTextProperty(); } //---------------------------------------------------------------------------- void vtkKWEBoundingBoxRepresentation2D::PrintSelf(ostream& os, vtkIndent indent) { double p[3]; os << indent << "BoundingBox points: " << this->PolyData->GetPoints() << endl; for (int i = 0; i < 8; i++) { this->PolyData->GetPoints()->GetPoint(i,p); os << indent.GetNextIndent() << "Point " << i << " : (" << p[0] << ", " << p[1] << ", " << p[2] << ")" << endl; } os << indent << "BoxPoints (cut of the bounding box):" << this->BoxPoints << endl; for (int i = 0; i < 4; i++) { this->BoxPoints->GetPoint(i,p); os << indent.GetNextIndent() << "Point " << i << " : (" << p[0] << ", " << p[1] << ", " << p[2] << ")" << endl; } os << indent << "HandlePositions (coincides with BoxPoints):" << endl; for (int i = 0; i < 4; i++) { this->HandleRepresentations[i]->GetWorldPosition(p); os << indent.GetNextIndent() << "Point " << i << " : (" << p[0] << ", " << p[1] << ", " << p[2] << ")" << endl; } os << indent << "ScaleBar points (where the scale bar is displayed): " << this->ScaleBar->GetPoints() << endl; for (int i = 0; i < 8; i++) { this->ScaleBar->GetPoints()->GetPoint(i,p); os << indent.GetNextIndent() << "Point " << i << " : (" << p[0] << ", " << p[1] << ", " << p[2] << ")" << endl; } this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/itkVTKImageToImageFilter.txx0000644000175000017500000000652711363410610022753 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef _itkVTKImageToImageFilter_txx #define _itkVTKImageToImageFilter_txx #include "itkVTKImageToImageFilter.h" namespace itk { /** * Constructor */ template VTKImageToImageFilter ::VTKImageToImageFilter() { m_Exporter = vtkImageExport::New(); m_Importer = ImporterFilterType::New(); m_Importer->SetUpdateInformationCallback( m_Exporter->GetUpdateInformationCallback()); m_Importer->SetPipelineModifiedCallback( m_Exporter->GetPipelineModifiedCallback()); m_Importer->SetWholeExtentCallback( m_Exporter->GetWholeExtentCallback()); m_Importer->SetSpacingCallback( m_Exporter->GetSpacingCallback()); m_Importer->SetOriginCallback( m_Exporter->GetOriginCallback()); m_Importer->SetScalarTypeCallback( m_Exporter->GetScalarTypeCallback()); m_Importer->SetNumberOfComponentsCallback( m_Exporter->GetNumberOfComponentsCallback()); m_Importer->SetPropagateUpdateExtentCallback( m_Exporter->GetPropagateUpdateExtentCallback()); m_Importer->SetUpdateDataCallback( m_Exporter->GetUpdateDataCallback()); m_Importer->SetDataExtentCallback( m_Exporter->GetDataExtentCallback()); m_Importer->SetBufferPointerCallback( m_Exporter->GetBufferPointerCallback()); m_Importer->SetCallbackUserData( m_Exporter->GetCallbackUserData()); } /** * Destructor */ template VTKImageToImageFilter ::~VTKImageToImageFilter() { if( m_Exporter ) { m_Exporter->Delete(); m_Exporter = 0; } } /** * Set a vtkImageData as input */ template void VTKImageToImageFilter ::SetInput( vtkImageData * inputImage ) { m_Exporter->SetInput( inputImage ); } /** * Get the vtkImageData set as input */ template vtkImageData * VTKImageToImageFilter ::GetInput() { return this->m_Exporter->GetInput(); } /** * Get an itk::Image as output */ template const typename VTKImageToImageFilter::OutputImageType * VTKImageToImageFilter ::GetOutput() const { return m_Importer->GetOutput(); } /** * Get the exporter filter */ template vtkImageExport * VTKImageToImageFilter ::GetExporter() const { return m_Exporter; } /** * Get the importer filter */ template typename VTKImageToImageFilter::ImporterFilterType * VTKImageToImageFilter ::GetImporter() const { return m_Importer; } /** * Delegate the Update to the importer */ template void VTKImageToImageFilter ::Update() { m_Importer->Update(); } } // end namespace itk #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEStencilContourFilter.cxx0000644000175000017500000002144611363410610023411 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEStencilContourFilter.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkContourFilter.h" #include "vtkImageStencilData.h" #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" vtkCxxRevisionMacro(vtkKWEStencilContourFilter, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEStencilContourFilter); //---------------------------------------------------------------------------- vtkKWEStencilContourFilter::vtkKWEStencilContourFilter() { this->ContourFilter = vtkContourFilter::New(); this->ImageData = vtkImageData::New(); this->ImageData->SetScalarTypeToUnsignedChar(); this->ImageData->SetNumberOfScalarComponents(1); this->ContourFilter->SetInput( this->ImageData ); this->ContourFilter->SetValue(0, 127.5); this->Extent[0] = this->Extent[2] = this->Extent[4] = 0; this->Extent[1] = this->Extent[3] = this->Extent[5] = -1; } //---------------------------------------------------------------------------- vtkKWEStencilContourFilter::~vtkKWEStencilContourFilter() { this->ContourFilter->Delete(); this->ImageData->Delete(); } //---------------------------------------------------------------------------- // Overload standard modified time function. If contour filter is modified, // then this object is modified as well. unsigned long vtkKWEStencilContourFilter::GetMTime() { unsigned long mTime=this->Superclass::GetMTime(), time; if (this->ContourFilter) { time = this->ContourFilter->GetMTime(); mTime = ( time > mTime ? time : mTime ); } return mTime; } //---------------------------------------------------------------------------- // This method computes the Region of input necessary to generate outRegion. // We will take the intersection of the stencil and the supplied clipping // extents, (if they have been specified), otherwise we will use the whole // extent of the stencil. // int vtkKWEStencilContourFilter::RequestUpdateExtent(vtkInformation* , vtkInformationVector** inputVector, vtkInformationVector* ) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkImageStencilData *input = vtkImageStencilData::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); int extent[6], uExt[6]; input->GetExtent(extent); // Now clip this with the bounding extents, if supplied. if (this->Extent[0] <= this->Extent[1]) { if (!vtkKWEPaintbrushUtilities::GetIntersectingExtents( this->Extent, extent, uExt )) { // They don't intersect.. inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), this->Extent, 6); } else { inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), uExt, 6); } return 1; } inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), extent, 6); return 1; } //---------------------------------------------------------------------------- int vtkKWEStencilContourFilter::RequestData( vtkInformation* , vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // get the input and output vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkImageStencilData *input = vtkImageStencilData::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); if (!input || !output) { return 0; } int uExt[6], currentExtent[6], inputExtent[6], intersectingExtents[6]; inInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), uExt); this->ImageData->GetExtent(currentExtent); // Check if the input is outside the update extent. If so, output = NULL. input->GetExtent(inputExtent); if (vtkKWEPaintbrushUtilities::GetIntersectingExtents( uExt, inputExtent, intersectingExtents)) { if (intersectingExtents[0] != currentExtent[0] || intersectingExtents[1] != currentExtent[1] || intersectingExtents[2] != currentExtent[2] || intersectingExtents[3] != currentExtent[3] || intersectingExtents[4] != currentExtent[4] || intersectingExtents[5] != currentExtent[5] ) { this->ImageData->SetExtent(intersectingExtents); this->ImageData->AllocateScalars(); } // Popualate image from the stencil this->ImageData->SetSpacing(input->GetSpacing()); this->ImageData->SetOrigin(input->GetOrigin()); vtkKWEPaintbrushUtilities::GetImageFromStencil( this->ImageData, input, 255, 0, true); this->ContourFilter->Update(); output->ShallowCopy(this->ContourFilter->GetOutput()); return 1; } // Nothing is there here. output->SetPoints(NULL); output->SetLines(NULL); output->SetPolys(NULL); return 0; } //---------------------------------------------------------------------------- int vtkKWEStencilContourFilter::FillInputPortInformation(int, vtkInformation *info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkImageStencilData"); return 1; } //---------------------------------------------------------------------------- void vtkKWEStencilContourFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //---------------------------------------------------------------------------- void vtkKWEStencilContourFilter::SetValue(int i, double value) { this->ContourFilter->SetValue(i,value); } //---------------------------------------------------------------------------- double vtkKWEStencilContourFilter::GetValue(int i) { return this->ContourFilter->GetValue(i); } //---------------------------------------------------------------------------- double *vtkKWEStencilContourFilter::GetValues() { return this->ContourFilter->GetValues(); } //---------------------------------------------------------------------------- void vtkKWEStencilContourFilter::GetValues(double *contourValues) { this->ContourFilter->GetValues(contourValues); } //---------------------------------------------------------------------------- void vtkKWEStencilContourFilter::SetNumberOfContours(int number) { this->ContourFilter->SetNumberOfContours(number); } //---------------------------------------------------------------------------- int vtkKWEStencilContourFilter::GetNumberOfContours() { return this->ContourFilter->GetNumberOfContours(); } //---------------------------------------------------------------------------- void vtkKWEStencilContourFilter::GenerateValues(int numContours, double range[2]) { this->ContourFilter->GenerateValues(numContours, range); } //---------------------------------------------------------------------------- void vtkKWEStencilContourFilter::GenerateValues(int numContours, double rangeStart, double rangeEnd) { this->ContourFilter->GenerateValues(numContours, rangeStart, rangeEnd); } //---------------------------------------------------------------------------- void vtkKWEStencilContourFilter::SetComputeGradients(int s) { this->ContourFilter->SetComputeGradients(s); } //---------------------------------------------------------------------------- void vtkKWEStencilContourFilter::SetComputeNormals(int s) { this->ContourFilter->SetComputeNormals(s); } //---------------------------------------------------------------------------- void vtkKWEStencilContourFilter::SetComputeScalars(int s) { this->ContourFilter->SetComputeScalars(s); } //---------------------------------------------------------------------------- int vtkKWEStencilContourFilter::GetComputeGradients() { return this->ContourFilter->GetComputeGradients(); } //---------------------------------------------------------------------------- int vtkKWEStencilContourFilter::GetComputeNormals() { return this->ContourFilter->GetComputeNormals(); } //---------------------------------------------------------------------------- int vtkKWEStencilContourFilter::GetComputeScalars() { return this->ContourFilter->GetComputeScalars(); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushDrawing.cxx0000644000175000017500000005250011521221413022713 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkObjectFactory.h" #include "vtkImageStencilData.h" #include "vtkProperty.h" #include "vtkImageData.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkKWEPaintbrushPropertyManager.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushStroke.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include #include vtkCxxRevisionMacro(vtkKWEPaintbrushDrawing, "$Revision: 3417 $"); vtkStandardNewMacro(vtkKWEPaintbrushDrawing); //---------------------------------------------------------------------- vtkKWEPaintbrushDrawing::vtkKWEPaintbrushDrawing() { this->PaintbrushData = NULL; this->PaintbrushOperation = NULL; this->ImageData = NULL; this->PaintbrushPropertyManager = vtkKWEPaintbrushPropertyManager::New(this); this->Collection = vtkCollection::New(); this->Representation = vtkKWEPaintbrushEnums::Binary; this->MaximumNumberOfSketches = 0; this->LabelMap = 0; } //---------------------------------------------------------------------- vtkKWEPaintbrushDrawing::~vtkKWEPaintbrushDrawing() { if (this->PaintbrushData) { this->PaintbrushData->Delete(); } this->Collection->Delete(); if (this->PaintbrushOperation) { this->PaintbrushOperation->Delete(); } if (this->ImageData) { this->ImageData->Delete(); } this->PaintbrushPropertyManager->Delete(); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::SetImageData( vtkImageData * i) { vtkKWEPaintbrushSketch *a; vtkCollectionSimpleIterator ait; for ( this->Collection->InitTraversal(ait); (a=static_cast< vtkKWEPaintbrushSketch * >(this->Collection->GetNextItemAsObject(ait))); ) { a->SetImageData(i); } vtkSetObjectBodyMacro( ImageData, vtkImageData, i) } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::InitializeData() { if (this->PaintbrushData) { this->PaintbrushData->Delete(); } if (this->Representation == vtkKWEPaintbrushEnums::Binary) { this->PaintbrushData = vtkKWEPaintbrushStencilData::New(); } else if (this->Representation == vtkKWEPaintbrushEnums::Grayscale) { this->PaintbrushData = vtkKWEPaintbrushGrayscaleData::New(); } else { this->PaintbrushData = vtkKWEPaintbrushLabelData::New(); } this->AllocatePaintbrushData(); if (this->GetNumberOfItems() == 0) { // If there are no items, create one by default. The user, when he creates // this widget, expects there to be at least a sketch alive, so he can // sketch something. vtkKWEPaintbrushSketch *m = vtkKWEPaintbrushSketch::New(); m->SetRepresentation(this->Representation); this->AddItem(m); m->Delete(); this->AssignUniqueLabelToSketch(m); // Assign a unique label to the sketch. } else { vtkKWEPaintbrushSketch *a; vtkCollectionSimpleIterator ait; // Initialize all the sketches in the drawing. Be prepared to lose your // sketches. for ( this->Collection->InitTraversal(ait); (a=static_cast< vtkKWEPaintbrushSketch * >(this->Collection->GetNextItemAsObject(ait))); ) { a->Initialize(); } if (this->Representation == vtkKWEPaintbrushEnums::Label) { // For Label maps, all sketches point to the same label map, since they // will be editing different labels within the same label map. this->SetPaintbrushData( static_cast< vtkKWEPaintbrushLabelData * >(this->PaintbrushData) ); } } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawing:: SetPaintbrushOperation( vtkKWEPaintbrushOperation * i) { vtkKWEPaintbrushSketch *a; vtkCollectionSimpleIterator ait; for ( this->Collection->InitTraversal(ait); (a=static_cast< vtkKWEPaintbrushSketch * >(this->Collection->GetNextItemAsObject(ait))); ) { a->SetPaintbrushOperation(i); } vtkSetObjectBodyMacro( PaintbrushOperation, vtkKWEPaintbrushOperation, i) } //---------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::AllocatePaintbrushData() { vtkImageData *i = this->GetImageData(); if (!i) { vtkErrorMacro( << "No image data"); } if (!this->PaintbrushData) { vtkErrorMacro( << "Must call Initialize() before using this class !"); } int extent[6]; double spacing[3], origin[3]; i->GetWholeExtent(extent); i->GetSpacing(spacing); i->GetOrigin(origin); // If a label map has been supplied (and our representation is a label map), // used the supplied one, otherwise allocate fresh paintbrush data with the // same size as the canvas. this->PaintbrushData->SetExtent(extent); this->PaintbrushData->SetSpacing(spacing); this->PaintbrushData->SetOrigin(origin); if (this->Representation == vtkKWEPaintbrushEnums::Label && this->LabelMap ) { // Sanity check : Ensure that the label map supplied by the user has the // same extents as the canvas, or we will have cryptic errors later on // during the overlay-blend render phase. if (!vtkKWEPaintbrushUtilities::ExtentIsEqualToExtent( extent, this->LabelMap->GetExtent())) { vtkErrorMacro( << "The extents of the canvas and that of the label map " << "must be equal !" ); } static_cast< vtkKWEPaintbrushLabelData * >( this->PaintbrushData)->SetLabelMap( this->LabelMap ); } else { this->PaintbrushData->Allocate(); } } //---------------------------------------------------------------------- int vtkKWEPaintbrushDrawing::AddNewStroke( int n, // Stroke is added to the n'th sketch int type, // Draw or Erase ? vtkKWEPaintbrushData *userSpecifiedStrokeData // User provided initialization ) { if (userSpecifiedStrokeData) { this->PaintbrushData->Add(userSpecifiedStrokeData); } return this->GetItem(n)->AddNewStroke( type, userSpecifiedStrokeData ); } //---------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::AddShapeToCurrentStroke( int n, double p[3] ) { if (n < this->GetNumberOfItems() && n >= 0) { // Add (or subtract) a shape centered at 'p' to the current stroke. // Also add (or subtract) the same to this->PaintbrushData, as a service. this->GetItem(n)->AddShapeToCurrentStroke(p, this->PaintbrushData); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::SetPaintbrushData( vtkKWEPaintbrushLabelData * data ) { vtkSetObjectBodyMacro( PaintbrushData, vtkKWEPaintbrushData, data ); // For label maps, all sketches share the same data, this label map. // Set it on all of them. vtkKWEPaintbrushSketch *a; vtkCollectionSimpleIterator ait; for ( this->Collection->InitTraversal(ait); (a=static_cast< vtkKWEPaintbrushSketch * >( this->Collection->GetNextItemAsObject(ait))); ) { a->SetPaintbrushData( data ); } // Sanity check. Make sure the scalar type of the data is correct. if (data && data->GetLabelMap()) { if (data->GetLabelMap()->GetScalarType() != vtkKWEPaintbrushEnums::GetLabelType()) { vtkErrorMacro( << "DataType of the label map must match the enumeration in " << "vtkKWEPaintbrushEnums. Either change the datatype of the label map or change " << "the enumeration to suit your needs" ); } } } //---------------------------------------------------------------------------- vtkKWEPaintbrushDrawing* vtkKWEPaintbrushDrawing::GetData(vtkInformation* info) { return info? vtkKWEPaintbrushDrawing::SafeDownCast(info->Get(DATA_OBJECT())) : 0; } //---------------------------------------------------------------------------- vtkKWEPaintbrushDrawing* vtkKWEPaintbrushDrawing::GetData(vtkInformationVector* v, int i) { return vtkKWEPaintbrushDrawing::GetData(v->GetInformationObject(i)); } //---------------------------------------------------------------------------- // Determine the modified time of this object unsigned long vtkKWEPaintbrushDrawing::GetMTime() { unsigned long result = 0; vtkKWEPaintbrushSketch *a; vtkCollectionSimpleIterator ait; for ( this->Collection->InitTraversal(ait); (a=static_cast< vtkKWEPaintbrushSketch * >( this->Collection->GetNextItemAsObject(ait))); ) { unsigned long t = a->GetMTime(); if (t > result) { result = t; } } unsigned long mtime = vtkObject::GetMTime(); result = ( mtime > result ? mtime : result); return result; } //---------------------------------------------------------------------------- vtkKWEPaintbrushSketch * vtkKWEPaintbrushDrawing::AddItem() { if (this->MaximumNumberOfSketches && this->GetNumberOfItems() == this->MaximumNumberOfSketches) { return NULL; // We hit the limit. } vtkKWEPaintbrushSketch * a = vtkKWEPaintbrushSketch::New(); this->Collection->AddItem(a); a->SetRepresentation(this->Representation); a->SetImageData(this->ImageData); a->SetPaintbrushOperation(this->PaintbrushOperation); a->PaintbrushDrawing = this; a->Initialize(); // For Label maps, all sketches point to the same label map, since they // will be editing different labels within the same label map. if (this->Representation == vtkKWEPaintbrushEnums::Label) { a->SetPaintbrushData( this->PaintbrushData ); } a->Delete(); return a; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::AddItem(vtkKWEPaintbrushSketch *a) { if (this->MaximumNumberOfSketches && this->GetNumberOfItems() == this->MaximumNumberOfSketches) { return; // We hit the limit. } this->Collection->AddItem(a); a->SetRepresentation(this->Representation); a->SetImageData(this->ImageData); a->SetPaintbrushOperation(this->PaintbrushOperation); a->PaintbrushDrawing = this; a->Initialize(); // For Label maps, all sketches point to the same label map, since they // will be editing different labels within the same label map. if (this->Representation == vtkKWEPaintbrushEnums::Label) { a->SetPaintbrushData( this->PaintbrushData ); } } //---------------------------------------------------------------------------- vtkKWEPaintbrushSketch *vtkKWEPaintbrushDrawing::GetItem(int i) { return static_cast< vtkKWEPaintbrushSketch * >( this->Collection->GetItemAsObject(i)); } //---------------------------------------------------------------------------- vtkKWEPaintbrushSketch * vtkKWEPaintbrushDrawing:: GetItemWithLabel( vtkKWEPaintbrushEnums::LabelType l ) { vtkKWEPaintbrushSketch *a; vtkCollectionSimpleIterator ait; for ( this->Collection->InitTraversal(ait); (a=static_cast< vtkKWEPaintbrushSketch * >( this->Collection->GetNextItemAsObject(ait))); ) { if (a->GetLabel() == l) { return a; } } return NULL; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushDrawing::IsItemPresent( vtkKWEPaintbrushSketch * s ) { return this->Collection->IsItemPresent(s); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushDrawing::GetIndexOfItem( vtkKWEPaintbrushSketch * s ) { int result = 0; vtkKWEPaintbrushSketch *a; vtkCollectionSimpleIterator ait; for ( this->Collection->InitTraversal(ait); (a=static_cast< vtkKWEPaintbrushSketch * >( this->Collection->GetNextItemAsObject(ait))); result++ ) { if (s == a) { return result; } } return -1; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::RemoveAllItems() { return this->Collection->RemoveAllItems(); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushDrawing::RemoveItem( vtkKWEPaintbrushSketch *s ) { if (this->Collection->IsItemPresent(s)) { this->Collection->RemoveItem(s); return 1; } return 0; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::ShallowCopy( vtkDataObject * src ) { if (src == this) { return; } vtkKWEPaintbrushDrawing *srcDrawing = vtkKWEPaintbrushDrawing::SafeDownCast(src); if (!srcDrawing) { vtkErrorMacro( << "Safedowncast to vtkKWEPaintbrushDrawing failed." ) return; } this->SetRepresentation( srcDrawing->GetRepresentation() ); this->SetImageData( srcDrawing->GetImageData()); this->SetPaintbrushOperation( srcDrawing->GetPaintbrushOperation() ); this->MaximumNumberOfSketches = srcDrawing->MaximumNumberOfSketches; this->Initialize(); // Copy some property defaults. this->PaintbrushPropertyManager->SetHighlightType( srcDrawing-> GetPaintbrushPropertyManager()->GetHighlightType() ); // Shallow copy the collection of sketches. this->Collection->UnRegister(this); this->Collection = srcDrawing->Collection; this->Collection->Register(this); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::ComposeStrokes() { // FIXME // Is clearing the whole PaintbrushData necessary ? // vector containing all the strokes in the drawing. (upto the undoable one) vtkstd::vector< vtkKWEPaintbrushStroke * > strokes; vtkKWEPaintbrushSketch *sketch; vtkCollectionSimpleIterator it; for ( this->Collection->InitTraversal(it); (sketch=static_cast< vtkKWEPaintbrushSketch * >( this->Collection->GetNextItemAsObject(it))); ) { sketch->GetStrokes( strokes ); } // Sort the strokes, oldest to latest. vtkstd::sort( strokes.begin(), strokes.end(), vtkKWEPaintbrushStroke::IsRecent ); // FIXME // We could be smarter by composing just the strokes with extents that // intersect with the one just undone/redone. vtkstd::vector< vtkKWEPaintbrushStroke * >::iterator sit = strokes.begin(); for ( ; sit != strokes.end(); ++sit ) { vtkKWEPaintbrushStroke * stroke = *sit; if (stroke->GetState() == vtkKWEPaintbrushEnums::Erase) { this->PaintbrushData->Subtract(stroke->GetPaintbrushData()); } else { this->PaintbrushData->Add(stroke->GetPaintbrushData()); } } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::AssignUniqueLabelToSketch( vtkKWEPaintbrushSketch *s ) { int nSketches = this->GetNumberOfItems(); vtkstd::vector< vtkKWEPaintbrushEnums::LabelType > labels( nSketches ); for (int i = 0; i < nSketches; i++) { labels[i] = this->GetItem(i)->GetLabel(); } vtkKWEPaintbrushEnums::LabelType minLabel = 1; vtkKWEPaintbrushEnums::LabelType maxLabel = vtkstd::numeric_limits< vtkKWEPaintbrushEnums::LabelType >::max(); for (vtkKWEPaintbrushEnums::LabelType i = minLabel; i < maxLabel; i++) { if (std::find(labels.begin(), labels.end(), i) != labels.end()) { s->SetLabel(i); return; } } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::InitializeSketches() { // For representations that are not label maps, this should already have // been done. if (!this->PaintbrushData) { vtkErrorMacro( << "PaintbrushData is NULL. Did you add this sketch to the " << "drawing and call InitializeData on the drawing prior to " << "initializing the sketch ?"); return; } if (this->GetNumberOfItems() == 0) { vtkErrorMacro( << "No sketches to initialize. " << "Did you call AddSketch and add sketches to the drawing first ?"); return; } if (this->Representation != vtkKWEPaintbrushEnums::Label) { vtkErrorMacro( << "This method is only intended to be used when editing LabelMaps." << " Did you set the representation first ?" ); return; } vtkstd::vector< vtkKWEPaintbrushEnums::LabelType > labels(this->Collection->GetNumberOfItems()); unsigned int i = 0; vtkCollectionSimpleIterator ait; vtkKWEPaintbrushSketch *a; for ( this->Collection->InitTraversal(ait); (a=static_cast< vtkKWEPaintbrushSketch * >(this->Collection->GetNextItemAsObject(ait))); ) { labels[i++] = a->GetLabel(); } vtkImageData *image = vtkKWEPaintbrushLabelData::SafeDownCast( this->PaintbrushData )->GetLabelMap(); // Populate all the strokes at one shot vtkstd::map< vtkKWEPaintbrushEnums::LabelType, vtkSmartPointer< vtkKWEPaintbrushStencilData > > initialStrokes = vtkKWEPaintbrushUtilities::GetStencilsFromImage( image, labels ); // Initialize all the sketches with their user-specified strokes. for ( this->Collection->InitTraversal(ait); (a=static_cast< vtkKWEPaintbrushSketch * >(this->Collection->GetNextItemAsObject(ait))); ) { a->AddNewStroke( vtkKWEPaintbrushEnums::Draw, initialStrokes[a->GetLabel()], NULL, true ); } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::CreateSketches() { // For representations that are not label maps, this should already have // been done. if (!this->PaintbrushData) { vtkErrorMacro( << "PaintbrushData is NULL. Did you add this sketch to the " << "drawing and call InitializeData on the drawing prior to " << "initializing the sketch ?"); return; } if (this->Representation != vtkKWEPaintbrushEnums::Label) { vtkErrorMacro( << "This method is only intended to be used when editing LabelMaps." << " Did you set the representation first ?" ); return; } vtkKWEPaintbrushLabelData *paintbrushLabelData = vtkKWEPaintbrushLabelData::SafeDownCast(this->PaintbrushData); typedef vtkKWEPaintbrushLabelData::LabelSetType LabelSetType; LabelSetType labelSet = paintbrushLabelData->GetLabels(); // fast path if this is the first time we are initilizing. This enables us to // initialize all sketches at one shot. bool firstTime = this->GetNumberOfItems() == 0 ? true : false; // Create new sketches for each of the labels in the label map, taking care // check if we don't have a sketch with that label already. for ( LabelSetType::const_iterator it = labelSet.begin(); it != labelSet.end(); ++it ) { vtkKWEPaintbrushEnums::LabelType label = *it; if (!this->GetItemWithLabel(label)) { vtkKWEPaintbrushSketch * sketch = this->AddItem(); sketch->SetLabel(label); } } // Remove any sketches that aren't in this label map if (!firstTime) { std::vector< vtkKWEPaintbrushSketch * > toRemove; const int nSketches = this->GetNumberOfItems(); for (int i = 0; i < nSketches; i++) { vtkKWEPaintbrushSketch *s = this->GetItem(i); if (labelSet.find(s->GetLabel()) == labelSet.end()) { toRemove.push_back(s); } } const int nToRemove = toRemove.size(); for (int i = 0; i < nToRemove; i++) { this->RemoveItem(toRemove[i]); } } // Now that we've created these sketches, let's initialize all the sketches // based on the label map. this->InitializeSketches(); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::CollapseHistory() { const int nSketches = this->GetNumberOfItems(); for (int i = 0; i < nSketches; i++) { this->GetItem(i)->CollapseHistory(); } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawing::PrintSelf(ostream& os, vtkIndent indent) { if (this->Representation == vtkKWEPaintbrushEnums::Binary) { os << indent << "Representation: Binary" << endl; } else { os << indent << "Representation: Grayscale" << endl; } os << indent << "PaintbrushOperation: " << this->PaintbrushOperation << endl; if (this->PaintbrushOperation) { this->PaintbrushOperation->PrintSelf( os, indent.GetNextIndent() ); } os << indent << "Number of sketches: " << this->GetNumberOfItems() << endl; for (int i = 0; i < this->GetNumberOfItems(); i++) { os << indent << "Sketch: " << i << " (" << this->GetItem(i) << ")" << endl; this->GetItem(i)->PrintSelf(os, indent.GetNextIndent()); } if (this->MaximumNumberOfSketches) { os << indent << "MaximumNumberOfSketches: " << this->MaximumNumberOfSketches << endl; } this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushTesting.cxx0000644000175000017500000002155211363410610022743 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushTesting.h" #include "vtkBMPReader.h" #include "vtkCommand.h" #include "vtkImageReader2.h" #include "vtkImageReader2Factory.h" #include "vtkImageViewer2.h" #include "vtkMetaImageReader.h" #include "vtkObjectFactory.h" #include "vtkPNGReader.h" #include "vtkPNMReader.h" #include "vtkToolkits.h" #include "vtkXMLImageDataReader.h" #include "vtkCollection.h" #include "vtkSliderRepresentation.h" #include "vtkSliderRepresentation2D.h" #include "vtkSliderWidget.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkProperty2D.h" #include "vtksys/ios/sstream" class vtkKWEPaintbrushTestingSliderCallback : public vtkCommand { public: static vtkKWEPaintbrushTestingSliderCallback *New() { return new vtkKWEPaintbrushTestingSliderCallback; } void SetImageViewer(vtkImageViewer2 *viewer) { m_Viewer = viewer; } virtual void Execute(vtkObject *caller, unsigned long , void* ) { vtkSliderWidget *slider = static_cast(caller); vtkSliderRepresentation *sliderRepres = static_cast(slider->GetRepresentation()); int pos = static_cast(sliderRepres->GetValue()); m_Viewer->SetSlice(pos); } protected: vtkImageViewer2 *m_Viewer; }; static const char *vtkKWEPaintbrushTestingWindowStrings[] = { "Paintbrush - Axial", "Paintbrush - Coronal", "Paintbrush - Sagittal", NULL }; //---------------------------------------------------------------------------- vtkStandardNewMacro( vtkKWEPaintbrushTesting ); vtkCxxRevisionMacro(vtkKWEPaintbrushTesting, "$Revision: 1774 $"); vtkCxxSetObjectMacro( vtkKWEPaintbrushTesting, Input, vtkImageData ); //---------------------------------------------------------------------------- vtkKWEPaintbrushTesting::vtkKWEPaintbrushTesting() { for (int i = 0; i < 3; i++) { this->ImageViewer[i] = vtkImageViewer2::New(); vtkRenderer *renderer = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); this->ImageViewer[i]->SetRenderWindow(renWin); this->ImageViewer[i]->SetRenderer(renderer); this->ImageViewer[i]->SetupInteractor(iren); renWin->SetWindowName( vtkKWEPaintbrushTestingWindowStrings[i] ); this->SliderCallbacks[i] = vtkKWEPaintbrushTestingSliderCallback::New(); this->SliderCallbacks[i]->SetImageViewer( this->ImageViewer[i] ); vtkSliderRepresentation2D *SliderRepres = vtkSliderRepresentation2D::New(); SliderRepres->SetTitleText("Slice"); SliderRepres->GetPoint1Coordinate()->SetCoordinateSystemToNormalizedDisplay(); SliderRepres->GetPoint1Coordinate()->SetValue(0.15, 0.05); SliderRepres->GetPoint2Coordinate()->SetCoordinateSystemToNormalizedDisplay(); SliderRepres->GetPoint2Coordinate()->SetValue(0.85, 0.05); SliderRepres->SetSliderLength(0.02); SliderRepres->SetSliderWidth(0.03); SliderRepres->SetEndCapLength(0.01); SliderRepres->SetEndCapWidth(0.03); SliderRepres->SetTubeWidth(0.005); SliderRepres->SetLabelFormat("%3.0lf"); SliderRepres->SetTitleHeight(0.02); SliderRepres->SetLabelHeight(0.03); SliderRepres->GetTubeProperty()->SetColor( 0, 1, 0 ); SliderRepres->GetCapProperty()->SetColor( 0, 0.5, 1 ); SliderRepres->GetSelectedProperty()->SetColor( 0, 1, 1 ); this->SliderWidget[i] = vtkSliderWidget::New(); this->SliderWidget[i]->SetInteractor(iren); this->SliderWidget[i]->SetRepresentation(SliderRepres); this->SliderWidget[i]->KeyPressActivationOff(); this->SliderWidget[i]->SetAnimationModeToAnimate(); SliderRepres->Delete(); this->SliderWidget[i]->AddObserver(vtkCommand::InteractionEvent, this->SliderCallbacks[i]); renderer->Delete(); renWin->Delete(); iren->Delete(); } this->Filename = NULL; this->FourPaneView = 1; this->Input = NULL; } //---------------------------------------------------------------------------- vtkKWEPaintbrushTesting::~vtkKWEPaintbrushTesting() { for (int i = 0; i < 3; i++) { this->ImageViewer[i]->Delete(); this->SliderCallbacks[i]->Delete(); this->SliderWidget[i]->Delete(); } if (this->Filename) { delete [] this->Filename; } this->SetInput(NULL); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushTesting::Initialize() { // Read the data, if an input hasn't already been specified if (!this->Input) { vtkImageReader2 *reader; this->GetValidReader( reader, this->Filename ); if (!reader) { std::cerr << "Cannot read input image file ! " << std::endl; return; } reader->Update(); this->SetInput(reader->GetOutput()); reader->Delete(); } // Create an image viewer // set the render window and renderer of the renderwidget // const int size = 350; if (this->FourPaneView == 0) { this->ImageViewer[0]->SetInput(this->Input); // Reset the window/level and the camera double *range = this->Input->GetScalarRange(); this->ImageViewer[0]->SetColorWindow(range[1] - range[0]); this->ImageViewer[0]->SetColorLevel(0.5 * (range[1] + range[0])+ 0.0000001); int min = ImageViewer[0]->GetSliceMin(); int max = ImageViewer[0]->GetSliceMax(); vtkSliderRepresentation2D *sliderRepres = vtkSliderRepresentation2D::SafeDownCast( this->SliderWidget[0]->GetRepresentation()); sliderRepres->SetMinimumValue(min); sliderRepres->SetMaximumValue(max); sliderRepres->SetValue(static_cast((min + max) / 2)); ImageViewer[0]->SetSlice(static_cast(sliderRepres->GetValue())); this->SliderWidget[0]->EnabledOn(); this->ImageViewer[0]->SetSize( size, size ); this->ImageViewer[0]->SetPosition( 0, 0 ); } else { for (int i = 0; i < 3; i++) { this->ImageViewer[i]->SetInput(this->Input); // Reset the window/level and the camera double *range = this->Input->GetScalarRange(); this->ImageViewer[i]->SetColorWindow(range[1] - range[0]); this->ImageViewer[i]->SetColorLevel(0.5 * (range[1] + range[0])+ 0.0000001); this->ImageViewer[i]->SetSliceOrientation(2-i); int min = ImageViewer[i]->GetSliceMin(); int max = ImageViewer[i]->GetSliceMax(); vtkSliderRepresentation2D *sliderRepres = vtkSliderRepresentation2D::SafeDownCast( this->SliderWidget[i]->GetRepresentation()); sliderRepres->SetMinimumValue(min); sliderRepres->SetMaximumValue(max); sliderRepres->SetValue(static_cast((min + max) / 2)); ImageViewer[i]->SetSlice(static_cast(sliderRepres->GetValue())); this->SliderWidget[i]->EnabledOn(); this->ImageViewer[i]->SetSize( size, size ); this->ImageViewer[i]->SetPosition( static_cast(1.2 * size * (i%2)), static_cast(1.2 * size * (i/2)) ); } } } //---------------------------------------------------------------------------- int vtkKWEPaintbrushTesting::Run() { if (this->FourPaneView) { for (int i = 0; i < 3; i++) { this->ImageViewer[i]->GetRenderWindow()->GetInteractor()->Start(); } } else { this->ImageViewer[0]->GetRenderWindow()->GetInteractor()->Start(); } return 1; } //---------------------------------------------------------------------------- vtkImageActor * vtkKWEPaintbrushTesting::GetNthImageActor( int i ) { return this->ImageViewer[i]->GetImageActor(); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushTesting::GetValidReader( vtkImageReader2* & reader, const char *filename) { if (filename == NULL) { return; } reader = vtkMetaImageReader::New(); reader->SetFileName(filename); if (reader->CanReadFile(filename) == 3) { return; } /* * Damn ! I can't read .vtk files. they don't subclass from vtkImageReader2 * TODO : put a work around for VTK files later * * reader = vtkXMLImageDataReader::New(); int valid = reader->CanReadFile(filename); if (reader->CanReadFile(filename) == 3) { return; } */ reader->Delete(); reader = NULL; } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushRepresentation.cxx0000644000175000017500000002357111504122432024332 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushRepresentation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushAnnotationRepresentation.h" #include "vtkKWEPaintbrushSelectionRepresentation.h" #include "vtkKWEPaintbrushData.h" #include "vtkCoordinate.h" #include "vtkRenderer.h" #include "vtkObjectFactory.h" #include "vtkInteractorObserver.h" #include "vtkMath.h" #include "vtkLine.h" #include "vtkCamera.h" #include "vtkPolyData.h" #include "vtkPointPlacer.h" vtkCxxRevisionMacro(vtkKWEPaintbrushRepresentation, "$Revision: 3282 $"); vtkCxxSetObjectMacro(vtkKWEPaintbrushRepresentation, ShapePlacer, vtkPointPlacer); //---------------------------------------------------------------------- vtkKWEPaintbrushRepresentation::vtkKWEPaintbrushRepresentation() { this->PaintbrushDrawing = vtkKWEPaintbrushDrawing::New(); this->PaintbrushOperation = vtkKWEPaintbrushOperation::New(); this->PaintbrushDrawing->SetPaintbrushOperation(this->PaintbrushOperation); this->InteractionState = PaintbrushDisabled; this->ShapePlacer = NULL; this->SketchIndex = 0; this->Annotation = vtkKWEPaintbrushAnnotationRepresentation::New(); this->PipelineInstalled = 0; this->SelectionRepresentation = NULL; this->Annotation->PaintbrushRepresentation = this; this->LastDisplayPosition[0] = this->LastDisplayPosition[1] = 0; } //---------------------------------------------------------------------- vtkKWEPaintbrushRepresentation::~vtkKWEPaintbrushRepresentation() { this->PaintbrushDrawing->Delete(); this->SetPaintbrushOperation(NULL); this->SetShapePlacer(NULL); this->Annotation->Delete(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation::SetPaintbrushOperation( vtkKWEPaintbrushOperation * filter ) { if (this->PaintbrushOperation != filter) { vtkKWEPaintbrushOperation * var = this->PaintbrushOperation; this->PaintbrushOperation = filter; if (this->PaintbrushOperation) { this->PaintbrushOperation->Register(this); } if (var != NULL) { var->UnRegister(this); } this->Modified(); } if (this->PaintbrushOperation) { this->PaintbrushDrawing->SetPaintbrushOperation( this->PaintbrushOperation ); } } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation::BeginNewSketch() { if (this->GetSketchIndex() >= 0) { this->PaintbrushDrawing->AddItem(); } this->SketchIndex = this->PaintbrushDrawing->GetNumberOfItems()-1; return 1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation::IncrementSketch() { return this->GoToSketch(this->GetSketchIndex() + 1); } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation::DecrementSketch() { return this->GoToSketch(this->GetSketchIndex() - 1); } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation::GoToSketch( int n ) { if (n < this->PaintbrushDrawing->GetNumberOfItems() && n >= 0) { this->SketchIndex = n; return 1; } return 0; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation::BeginNewStroke() { if (vtkKWEPaintbrushSketch * paintbrushSketch = this->PaintbrushDrawing->GetItem(this->GetSketchIndex())) { // Give the representation a chance to save some memory. Check if the // stroke cannot go beyond these extents. int extents[6]; this->GetEtchExtents( extents ); if (this->InteractionState == PaintbrushDraw) { return paintbrushSketch->AddNewStroke( vtkKWEPaintbrushEnums::Draw, NULL, extents); } if (this->InteractionState == PaintbrushErase) { return paintbrushSketch->AddNewStroke( vtkKWEPaintbrushEnums::Erase, NULL, extents); } } return 0; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation::UndoStroke() { if (vtkKWEPaintbrushSketch * paintbrushSketch = this->PaintbrushDrawing->GetItem(this->GetSketchIndex())) { return paintbrushSketch->PopStroke(); } return 0; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation::RedoStroke() { if (vtkKWEPaintbrushSketch * paintbrushSketch = this->PaintbrushDrawing->GetItem(this->GetSketchIndex())) { return paintbrushSketch->PushStroke(); } return 0; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation::RemoveLastStroke() { if (vtkKWEPaintbrushSketch * paintbrushSketch = this->PaintbrushDrawing->GetItem(this->GetSketchIndex())) { return paintbrushSketch->DeleteLastStroke(); } return 0; } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation::DeepCopy(vtkWidgetRepresentation *rep) { vtkKWEPaintbrushRepresentation *r = vtkKWEPaintbrushRepresentation::SafeDownCast(rep); if (this == r || !r) { return; } //if (this->ShapePlacer && r->ShapePlacer) // { // this->ShapePlacer->DeepCopy(r->ShapePlacer); // } this->CurrentShapePosition[0] = r->CurrentShapePosition[0]; this->CurrentShapePosition[1] = r->CurrentShapePosition[1]; this->CurrentShapePosition[2] = r->CurrentShapePosition[2]; this->InteractionState = r->InteractionState; this->SketchIndex = r->GetSketchIndex(); this->SetPaintbrushDrawing( r->GetPaintbrushDrawing() ); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation::SetPaintbrushDrawing( vtkKWEPaintbrushDrawing * drawing ) { if (this->PaintbrushDrawing != drawing) { vtkKWEPaintbrushDrawing * var = this->PaintbrushDrawing; this->PaintbrushDrawing = drawing; if (this->PaintbrushDrawing != NULL) { this->PaintbrushDrawing->Register(this); } if (var != NULL) { var->UnRegister(this); } if (this->SelectionRepresentation) { this->SelectionRepresentation->SetPaintbrushDrawing( drawing ); } this->Modified(); } } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation::GetSketchIndex() { int upperBound = this->PaintbrushDrawing->GetNumberOfItems()-1; if (upperBound < 0) { upperBound = 0; } this->SketchIndex = (this->SketchIndex < 0 ? 0 : (this->SketchIndex > upperBound ? upperBound : this->SketchIndex)); return this->SketchIndex; } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation::InstallPipeline() { this->PipelineInstalled = 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation::UnInstallPipeline() { this->PipelineInstalled = 0; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation::IsInsideCanvas(int displaypos[2]) { double displayPos[2], worldPos[3], worldOrient[9]; displayPos[0] = displaypos[0]; displayPos[1] = displaypos[1]; if ( !this->ShapePlacer->ComputeWorldPosition( this->Renderer, displayPos, worldPos, worldOrient) ) { return 0; // not a valid display location to paint on. } return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation::GetEtchExtents( int extents[6] ) { extents[0] = extents[2] = extents[4] = 0; extents[1] = extents[3] = extents[5] = -1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation ::RemoveSketch( vtkKWEPaintbrushSketch * sketch ) { int n = this->PaintbrushDrawing->GetIndexOfItem(sketch); if (n == -1) // the sketch is not present { return 0; } int label = sketch->GetLabel(); this->PaintbrushDrawing->RemoveItem(sketch); // Now clear the label (KK: Is this really necessary. The next time we render, // aren't we cumulating all the sketches anyway ?) if (this->PaintbrushDrawing->GetRepresentation() == vtkKWEPaintbrushEnums::Label) { this->PaintbrushDrawing->GetPaintbrushData()->Clear(label); } // if the index of the currently active sketch is higher than the one // being deleted, we'll need to decrement the sketch index. if (this->SketchIndex >= n && this->SketchIndex != 0) { --this->SketchIndex; } return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation::AddShapeToCurrentStroke( double p[3] ) { this->PaintbrushDrawing->AddShapeToCurrentStroke( this->SketchIndex, p ); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushStroke.h0000644000175000017500000001345111363410610022221 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushStroke - A stroke is an atomic unit of a paintbrush draw // .SECTION Description // The stroke is intended to represent a basic unit of a paintbrush draw. A // stroke (can be a positive (draw) or a negative (erase) stroke) is one // continuous sketch with the brush. // // .SECTION See Also #ifndef __vtkKWEPaintbrushStroke_h #define __vtkKWEPaintbrushStroke_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkKWEPaintbrushEnums.h" #include "vtkObject.h" #include class vtkKWEPaintbrushOperation; class vtkKWEPaintbrushData; class vtkImageData; //BTX class vtkKWEPaintbrushStrokeNode { public: double WorldPosition[3]; }; class vtkKWEPaintbrushStrokeInternals { public: vtkKWEPaintbrushStrokeInternals() : State( vtkKWEPaintbrushEnums::Draw ) {} vtkstd::vector Node; vtkKWEPaintbrushEnums::BrushType State; // Erase or Draw ? }; //ETX class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushStroke : public vtkObject { //BTX friend class vtkKWEPaintbrushSketch; friend class vtkKWEPaintbrushDrawing; //ETX public: // Description: // Instantiate this class. static vtkKWEPaintbrushStroke *New(); // Description: // Standard methods for instances of this class. vtkTypeRevisionMacro(vtkKWEPaintbrushStroke, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set the template virtual void SetPaintbrushOperation( vtkKWEPaintbrushOperation * ); vtkGetObjectMacro( PaintbrushOperation, vtkKWEPaintbrushOperation ); // Description: // Get the stencil. // The stroke is represented by a binary stencil. This is updated every // time a template is added to the stroke. virtual void SetPaintbrushData(vtkKWEPaintbrushData *); vtkGetObjectMacro( PaintbrushData, vtkKWEPaintbrushData ); // Description: // Set/Get the image data on which the sequence is drawn. This must // be set by the user or bad things will happen. virtual void SetImageData( vtkImageData * ); vtkGetObjectMacro( ImageData, vtkImageData ); // Description: // Stroke can be a draw or erase stroke // vtkKWEPaintbrushEnums::Draw // vtkKWEPaintbrushEnums::Erase virtual void SetStateToDraw(); virtual void SetStateToErase(); virtual void SetState( int ); virtual int GetState(); // Description: // Set the representation of the stroke. // See vtkKWEPaintbrushEnums::LabelType. virtual void SetRepresentation( int representation ); vtkGetMacro(Representation, int); virtual void SetRepresentationToGrayscale() { this->SetRepresentation(vtkKWEPaintbrushEnums::Grayscale); } virtual void SetRepresentationToBinary() { this->SetRepresentation(vtkKWEPaintbrushEnums::Binary); } // This is optional - USE WITH CARE // By default, each stroke has extents that match that of the canvas image. // Although there are efficient datastructures to more compactly represent // a stroke, it can induce some memory drag. If you are dead sure that your // stroke is going to have certain bounding extents, you can set this. // The widgets internally use this under certain conditions to speed things // up. Note that, if you set this method, you must do so before you set the // canvas image via SetImageData(..), since calling this method, by default // will allocate extents that are as large as the canvas image. virtual void SetExtent( int extent[6] ); vtkGetVector6Macro( Extent, int ); protected: vtkKWEPaintbrushStroke(); ~vtkKWEPaintbrushStroke(); vtkKWEPaintbrushOperation *PaintbrushOperation; vtkKWEPaintbrushStrokeInternals *Internals; vtkKWEPaintbrushData *PaintbrushData; vtkImageData *ImageData; int Extent[6]; int Representation; double Tolerance; vtkKWEPaintbrushEnums::LabelType Label; // Description: // Allocate the internal stencil. This must be called prior to use and after // the SetExtent or the SetImageData method has been called. virtual void Allocate(); // Description: // Add template at position. If auxData is specified, the shape is added // not only to the stroke's PaintbrushData but also the auxillary data // specified. virtual int AddShapeAtPosition(double p[3], vtkKWEPaintbrushData *auxData1 = NULL, vtkKWEPaintbrushData *auxData2 = NULL ); // Description: // Set the label of the stroke. Makes sense only when editing label maps. void SetLabel( vtkKWEPaintbrushEnums::LabelType l ) { this->Label = l; } vtkGetMacro( Label, vtkKWEPaintbrushEnums::LabelType ); // Description: // The time the stroke was drawn. vtkSetMacro( DrawTime, unsigned long ); vtkGetMacro( DrawTime, unsigned long ); unsigned long DrawTime; // Is 'a' more recent than 'b' ? static bool IsRecent( const vtkKWEPaintbrushStroke *a, const vtkKWEPaintbrushStroke *b ); private: vtkKWEPaintbrushStroke(const vtkKWEPaintbrushStroke&); //Not implemented void operator=(const vtkKWEPaintbrushStroke&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEStencilContourFilter.h0000644000175000017500000000753211363410610023036 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEStencilContourFilter - generate isosurface/isoline from a vtkImageStencilData // .SECTION Description #ifndef __vtkKWEStencilContourFilter_h #define __vtkKWEStencilContourFilter_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkPolyDataAlgorithm.h" class vtkContourFilter; class vtkImageStencilData; class vtkImageData; class VTKEdge_WIDGETS_EXPORT vtkKWEStencilContourFilter : public vtkPolyDataAlgorithm { public: static vtkKWEStencilContourFilter *New(); vtkTypeRevisionMacro(vtkKWEStencilContourFilter,vtkPolyDataAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set/Get extents. The contour filter will update only within the specified // extents. If the extents aren't set, the extents of the input will be used. vtkSetVector6Macro( Extent, int ); vtkGetVector6Macro( Extent, int ); // Description: // Methods to set / get contour values. void SetValue(int i, double value); double GetValue(int i); double *GetValues(); void GetValues(double *contourValues); void SetNumberOfContours(int number); int GetNumberOfContours(); void GenerateValues(int numContours, double range[2]); void GenerateValues(int numContours, double rangeStart, double rangeEnd); // Description: // Modified GetMTime Because we delegate to vtkContourValues unsigned long GetMTime(); // Description: // Set/Get the computation of normals. Normal computation is fairly // expensive in both time and storage. If the output data will be // processed by filters that modify topology or geometry, it may be // wise to turn Normals and Gradients off. void SetComputeNormals( int ); int GetComputeNormals(); vtkBooleanMacro(ComputeNormals,int); // Description: // Set/Get the computation of gradients. Gradient computation is // fairly expensive in both time and storage. Note that if // ComputeNormals is on, gradients will have to be calculated, but // will not be stored in the output dataset. If the output data // will be processed by filters that modify topology or geometry, it // may be wise to turn Normals and Gradients off. void SetComputeGradients( int ); int GetComputeGradients(); vtkBooleanMacro(ComputeGradients,int); // Description: // Set/Get the computation of scalars. void SetComputeScalars( int ); int GetComputeScalars(); vtkBooleanMacro(ComputeScalars,int); protected: vtkKWEStencilContourFilter(); ~vtkKWEStencilContourFilter(); virtual int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); virtual int RequestUpdateExtent(vtkInformation*, vtkInformationVector**, vtkInformationVector*); virtual int FillInputPortInformation(int port, vtkInformation *info); vtkContourFilter *ContourFilter; vtkImageData *ImageData; int Extent[6]; private: vtkKWEStencilContourFilter(const vtkKWEStencilContourFilter&); // Not implemented. void operator=(const vtkKWEStencilContourFilter&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushMergeSketches.h0000644000175000017500000000600311363410610023476 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushMergeSketches - Merge all sketches in a drawing into a single sketch // .SECTION Description // Takes a drawing as input. Generates a drawing as output. The input drawing // will have one or more sketches. The output drawing will have a single // sketch. All sketches from the input will be merged into a single sketch. #ifndef __vtkKWEPaintbrushMergeSketches_h #define __vtkKWEPaintbrushMergeSketches_h #include "vtkAlgorithm.h" #include "VTKEdgeConfigure.h" class vtkKWEPaintbrushDrawing; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushMergeSketches : public vtkAlgorithm { public: // Description: // Standard VTK methods. static vtkKWEPaintbrushMergeSketches *New(); vtkTypeRevisionMacro(vtkKWEPaintbrushMergeSketches, vtkAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set a paintbrush drawing as input virtual void SetInput( vtkKWEPaintbrushDrawing * ); // Description: // see vtkAlgorithm for details virtual int ProcessRequest(vtkInformation*, vtkInformationVector**, vtkInformationVector*); // Description: // Get the output data object of this algorithm. vtkKWEPaintbrushDrawing* GetOutput(); protected: vtkKWEPaintbrushMergeSketches(); ~vtkKWEPaintbrushMergeSketches(); // Description: // see vtkAlgorithm for docs. virtual int FillInputPortInformation(int, vtkInformation*); virtual int FillOutputPortInformation(int, vtkInformation*); virtual int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); virtual void RequestInformation (vtkInformation*, vtkInformationVector**, vtkInformationVector*); // Description: // Creates the same output type as the input type. virtual int RequestDataObject(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); private: vtkKWEPaintbrushMergeSketches( const vtkKWEPaintbrushMergeSketches&); //Not implemented void operator=(const vtkKWEPaintbrushMergeSketches&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushAnnotationRepresentation.cxx0000644000175000017500000001372211363410610026363 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushAnnotationRepresentation.h" #include "vtkRenderer.h" #include "vtkObjectFactory.h" #include "vtkInteractorObserver.h" #include "vtkCamera.h" #include "vtkKWEPaintbrushRepresentation.h" #include "vtkTextProperty.h" #include "vtkActor2D.h" #include "vtkTextMapper.h" vtkCxxRevisionMacro(vtkKWEPaintbrushAnnotationRepresentation, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEPaintbrushAnnotationRepresentation); //---------------------------------------------------------------------- vtkKWEPaintbrushAnnotationRepresentation::vtkKWEPaintbrushAnnotationRepresentation() { this->LastDisplayedAnnotation = ""; this->Annotation = NULL; this->LastDisplayPosition[0] = this->LastDisplayPosition[1] = 0; this->AnnotationPosition[0] = this->AnnotationPosition[1] = -1; this->BuildTime = vtkTimeStamp::New(); // Annotation stuff this->TextProperty = vtkTextProperty::New(); this->TextProperty->SetBold(0); this->TextProperty->SetItalic(1); this->TextProperty->SetShadow(0); this->TextProperty->SetFontFamilyToArial(); this->TextProperty->SetFontSize(5); this->TextMapper = vtkTextMapper::New(); this->TextMapper->SetTextProperty(this->TextProperty); this->TextMapper->SetInput("0.0"); this->TextActor = vtkActor2D::New(); this->TextActor->SetMapper(this->TextMapper); this->TextActor->VisibilityOn(); } //---------------------------------------------------------------------- vtkKWEPaintbrushAnnotationRepresentation::~vtkKWEPaintbrushAnnotationRepresentation() { this->SetAnnotation(NULL); this->TextProperty->Delete(); this->TextMapper->Delete(); this->TextActor->Delete(); this->BuildTime->Delete(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationRepresentation::BuildRepresentation() { if (!this->Annotation || !this->PaintbrushRepresentation || !this->Renderer) { this->TextActor->VisibilityOff(); return; } int stringSize[2], *winSize = this->Renderer->GetSize(); vtksys_stl::string annotation(this->Annotation); this->TextActor->VisibilityOn(); double disp[3] = {this->AnnotationPosition[0] * winSize[0], this->AnnotationPosition[1] * winSize[1], 0.0 }; this->TextMapper->SetInput(this->Annotation); if (disp[0] < 0) { // User did not provide a default position. Just place it where the // brush is. vtkInteractorObserver::ComputeWorldToDisplay(this->Renderer, this->PaintbrushRepresentation->CurrentShapePosition[0], this->PaintbrushRepresentation->CurrentShapePosition[1], this->PaintbrushRepresentation->CurrentShapePosition[2], disp); } this->TextActor->SetPosition(disp[0], disp[1]); // Adjust the font size vtkTextMapper::SetRelativeFontSize(this->TextMapper, this->Renderer, winSize, stringSize, 0.01f); } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationRepresentation::SetVisibility(int i) { this->TextActor->SetVisibility(i); this->Superclass::SetVisibility(i); } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationRepresentation::ReleaseGraphicsResources(vtkWindow *w) { this->TextActor->ReleaseGraphicsResources(w); } //---------------------------------------------------------------------- int vtkKWEPaintbrushAnnotationRepresentation::RenderOverlay(vtkViewport *viewport) { int count = 0; if ( this->TextActor->GetVisibility()) { count += this->TextActor->RenderOverlay(viewport); } return count; } //---------------------------------------------------------------------- int vtkKWEPaintbrushAnnotationRepresentation::RenderOpaqueGeometry(vtkViewport *viewport) { int count = 0; if ( this->TextActor->GetVisibility() ) { count += this->TextActor->RenderOpaqueGeometry(viewport); } return count; } #if VTKEdge_VTK_VERSION_DATE > 20070305 //---------------------------------------------------------------------- int vtkKWEPaintbrushAnnotationRepresentation::RenderTranslucentPolygonalGeometry(vtkViewport *viewport) { int count=0; if ( this->TextActor->GetVisibility() ) { count += this->TextActor->RenderTranslucentPolygonalGeometry(viewport); } return count; } //---------------------------------------------------------------------- int vtkKWEPaintbrushAnnotationRepresentation::HasTranslucentPolygonalGeometry() { int result=0; if ( this->TextActor->GetVisibility() ) { result |= this->TextActor->HasTranslucentPolygonalGeometry(); } return result; } #else //---------------------------------------------------------------------- // Legacy method to support VTK source versions prior to 2007/03/05 int vtkKWEPaintbrushAnnotationRepresentation::RenderTranslucentGeometry(vtkViewport *viewport) { int count=0; if ( this->TextActor->GetVisibility() ) { count += this->TextActor->RenderTranslucentGeometry(viewport); } return count; } #endif //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationRepresentation::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushWidget.h0000644000175000017500000003562411521051333022202 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushWidget - Paintbrush widget. // // .SECTION Description // The vtkKWEPaintbrushWidget is intended to edit and create segmentations. The // widget operates in two modes. An "edit" mode and a "select" mode. In the // "edit" mode, the widget can be used to edit and create segmentations. In // the "select" mode, the widget allows you to select one or more seperate // segmentations and then merge them into a single segmentation, do one click // deletion of selected segmentations etc. // // .SECTION Framework // The key to understanding brushes is to understand the datastructures, the // model and role of the following classes. // (1) vtkKWEPaintbrushDrawing (2) vtkKWEPaintbrushSketch (3) vtkKWEPaintbrushStroke // (4) vtkKWEPaintbrushData (5) vtkKWEPaintbrushShape (6) vtkKWEPaintbrushProperty // (7) vtkKWEPaintbrushOperation (8) Binary and Grayscale representations // (9) vtkPointPlacer (10) Widget Groups // // .SECTION Drawing // A PaintbrushWidget is used to edit a "Drawing" (vtkKWEPaintbrushDrawing). // The drawing contains several "sketches" (vtkKWEPaintbrushSketch). // // .SECTION Sketch // The drawing contains several "sketches" (vtkKWEPaintbrushSketch). Think of a // each sketch as a segmentation. Each "sketch" is composed of one or more // "strokes". Keeping the strokes around allows for undo-redo operations. // // .SECTION Stroke // Each stroke (vtkKWEPaintbrushStroke) represents a swish of the brush. It is // created interactively by dragging a "shape" (vtkKWEPaintbrushShape) around. // It can also be created manually (to load predefined segmentations/edits). // A stroke can be a positive stroke (draw) or a negative stroke (erase). // // .SECTION Shape // Shapes (vtkKWEPaintbrushShape) modes a brush. It allows you to have your // brush take a variety of forms. The output of the shape is filtered through // an "operation" (vtkKWEPaintbrushOperation) before being composed into its // stroke. Concrete shapes can be created by deriving from vtkKWEPaintbrushShape. // Two examples, an ellipsoid and a box are provided. A shape maintains a // polarity (correspoding to a draw and an erase brush). // // .SECTION Operation // Operations (vtkKWEPaintbrushOperation) allow you to plug in filters that take // effect as you draw. For instance, you can have a region growing operation // that does a flood fill on the image as you draw. A few operations are // provided as examples. Bridges between ITK and VTK can also be built. Its // customary to use ITK's powerful imaging filters to construct operations. // An example is vtkKWEITKConfidenceConnectedPaintbrushOperation. // // .SECTION PointPlacers // The widget uses "point placers" (vtkPointPlacer) to dictate the placement // of shapes. Point placers allow you to place constraints on the placement of // shapes. For instance a vtkKWEVoxelAlignedImageActorPointPlacer constrains // placement of shapes to pixel-grid boundaries. A vtkBoundedPlanePointPlacer // can be used to constrain placement to an arbitrary region, bounded by a set // of planes. A varirty of point placers exist in VTK and they lend themselves // to easy subclassing. // // .SECTION vtkKWEPaintbrushData // This is an abstract class that is used to store edits made using the // paintbrush. Each sketch maintains its own paintbrush data. Each stroke also // maintaints its own paintbrush data. The sketch's data is merely a composition // of the data from all its storkes. Two concrete implementations of // vtkKWEPaintbrushData exist. One for storing binary 1/0 strokes and another for // storing grayscale strokes. //

// vtkKWEPaintbrushData provides minkowski operators. You can add, subtract, // merge, intersect data. // // .SECTION Representations // Two representations are supported, a binary and a grayscale representation. // The Binary representation is rendered via an overlay. (see // vtkKWEPaintbrushRepresentation2D) Its datastructures are modeled by // vtkKWEPaintbrushStencilData and are memory efficient (They maintain a run // length encoded structure internally). //

// The grayscale representation is rendered as contours. See // vtkKWEPaintbrushRepresentationGrayscale2D. It stores the data internally using // vtkKWEPaintbrushGrayscaleData, which maintains a vtkImageData under the hood. // // .SECTION Property // A drawing can contain many sketches. Each sketch is rendered on the screen. // A sketch's properties are encapsulated in vtkKWEPaintbrushProperty. A property // manager automatically manages colors to ensure that each new sketch created // by the user has unique colors. However you may set your own colors. Apart // from managing colors, the property manages highlight styles. These take // effect when a sketch is highlighted (interactively during select mode) or // programatically. The Property also has methods to change the mutability of // sketches, a functionality supported only when editing label maps. // // .SECTION Widget Groups // It is customary for the user working on his segmentation(s) to have an // axial, coronal and sagittal view side by side while editing. vtkKWEWidgetGroup // enables this. It links widgets that exist on multiple render windows // together, so that they behave in unison. It relieves the user of the burden // of managing these disparate widgets and their underlying datastructures. // // .SECTION Supporting classes // Several supporting classes exist in the library. Note that // vtkKWEPaintbrushDrawing is a data-object. Algorithms can run on it that take // each of the segmentations and perform operations. See for instance // vtkKWEPaintbrushMergeSketches and vtkKWEITKPaintbrushExtractConnectedComponents. // The former merges all sketches in a drawing. The latter extracts out each // connected component in a sketch and populates them into seperate sketches. // // .SECTION Interactions // Please see vtkKWEPaintbrushWidgetCallbackMapper for the interactions supported // by the brush in its Edit and Select modes. One may override the class // vtkKWEPaintbrushWidgetCallbackMapper to customize the interactions. One such // override is vtkKWELightPaintbrushWidgetCallbackMapper. // // .SECTION See Also // #ifndef __vtkKWEPaintbrushWidget_h #define __vtkKWEPaintbrushWidget_h #include "VTKEdgeConfigure.h" // needed for export symbol directives #include "vtkKWEAbstractPaintbrushWidget.h" class vtkKWEPaintbrushRepresentation; class vtkKWEPaintbrushAnnotationWidget; class vtkKWEPaintbrushSelectionWidget; class vtkKWEWidgetGroup; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushWidget : public vtkKWEAbstractPaintbrushWidget { public: // Description: // Instantiate this class. static vtkKWEPaintbrushWidget *New(); // Description: // Standard methods for a VTK class. vtkTypeRevisionMacro(vtkKWEPaintbrushWidget,vtkKWEAbstractPaintbrushWidget); void PrintSelf(ostream& os, vtkIndent indent); // Description: // The method for activiating and deactiviating this widget. virtual void SetEnabled(int); // Description: // Specify an instance of vtkWidgetRepresentation used to represent this // widget in the scene. void SetRepresentation(vtkKWEPaintbrushRepresentation *r); // Description: // Create the default vtkKWEPaintbrushRepresentation if one is not set. virtual void CreateDefaultRepresentation(); // Description: // Set the mode that the widget should operate in. The Paintbrush widget can // operate either in an "edit" mode or in a "select" mode. In the "edit" // mode, you can draw, erase, create and edit segmentations. The "select" // mode facilitates one/multi-click selection of sketches and allows you // merge and remove segmentations. Default mode is edit. virtual void SetPaintbrushMode( int ); vtkGetMacro( PaintbrushMode, int ); // Description: // Get the selection widget. This is relevant only if the PaintbrushMode // is set to "Select". vtkGetObjectMacro(PaintbrushSelectionWidget, vtkKWEPaintbrushSelectionWidget); // Description: // Get the annotation manager. This is used to display hover annotations vtkGetObjectMacro(PaintbrushAnnotationWidget, vtkKWEPaintbrushAnnotationWidget); // Description: // Events and states. //BTX enum { BeginDrawStrokeEvent = 10000, BeginDrawStrokeForThisSketchEvent, BeginEraseStrokeEvent, BeginEraseStrokeForThisSketchEvent, EndStrokeEvent, UndoStrokeEvent, RedoStrokeEvent, DeleteStrokeEvent, BeginResizeEvent, BeginIsotropicResizeEvent, BeginNewSketchEvent, ResizeEvent, EndResizeEvent, ToggleSelectStateEvent, DrawEvent, EraseEvent, IncrementSketchEvent, DecrementSketchEvent, IncreaseOpacityEvent, DecreaseOpacityEvent, SelectSketchEvent, SelectAllSketchesEvent, UnselectSketchEvent, UnSelectAllSketchesEvent, ToggleSelectAllSketchesEvent, ToggleSketchMutabilityEvent, DeleteSelectionEvent, MergeSelectionEvent, GoToSketchEvent, EnterEvent, LeaveEvent }; enum { PaintbrushInteract, PaintbrushDraw, PaintbrushErase, PaintbrushResize, PaintbrushIsotropicResize, PaintbrushDisabled }; enum PaintbrushMode { Edit, Select }; //ETX // Description: // Deep copy from another widget. Synchronizes states, representations, etc virtual void DeepCopy(vtkAbstractWidget *w); // Description: // Override method to propagate to the child vtkKWEPaintbrushSelection widget virtual void SetProcessEvents(int); // Description: // Programmatically perform the actions that correspond to the callbacks above void IncrementSketch(); void GoToSketch( int n ); void SetWidgetStateToEnabled(); void SetWidgetStateToDisabled(); vtkGetMacro( WidgetState, int ); // Description: // INTERNAL - Do not use. // Callback interface to tie ends with the CallbackMapper for the events // invoked by this widget. Note the seperation of "Callbacks" and "Actions". // The callbacks are invoked in response to events from the // RenderWindowInteractor. They are then dispatched to the WidgetGroup, who // inturn calls the corresponding "Actions" on each of the widgets in the // group. // // As a rule of thumb, the mapping of "Callbacks" is to "Events" from the // Callbackmapper. The mapping of "Actions" is meant to be one pertinent // to the geometry changes on the widget's representation. // For instance a MouseMoveEvent should map to a "MoveCallback". This // can, depending on the state of the widget, trigger any of three Actions: // HoverAction, DrawAction, ResizeAction. // This is done, so that you can have multiple widgets, say a seed // widget drawn on 3 render windows and have them all synchronized, if they // belong to the same group. // static void BeginDrawCallback ( vtkAbstractWidget* ); static void BeginDrawThisSketchCallback ( vtkAbstractWidget* ); static void BeginEraseCallback ( vtkAbstractWidget* ); static void BeginEraseThisSketchCallback ( vtkAbstractWidget* ); static void MoveCallback ( vtkAbstractWidget* ); static void EndStrokeCallback ( vtkAbstractWidget* ); static void UndoCallback ( vtkAbstractWidget* ); static void RedoCallback ( vtkAbstractWidget* ); static void DeleteCallback ( vtkAbstractWidget* ); static void BeginResizeShapeCallback ( vtkAbstractWidget* ); static void BeginIsotropicResizeShapeCallback( vtkAbstractWidget* ); static void EndResizeShapeCallback ( vtkAbstractWidget* ); static void ToggleSelectStateCallback ( vtkAbstractWidget* ); static void BeginNewSketchCallback ( vtkAbstractWidget* ); static void IncrementSketchCallback ( vtkAbstractWidget* ); static void DecrementSketchCallback ( vtkAbstractWidget* ); static void IncreaseOpacityCallback ( vtkAbstractWidget* ); static void DecreaseOpacityCallback ( vtkAbstractWidget* ); static void MergeSelectionCallback ( vtkAbstractWidget* ); static void ToggleSelectAllSketchesCallback ( vtkAbstractWidget* ); static void ToggleSketchMutabilityCallback ( vtkAbstractWidget* ); static void EnterWidgetCallback ( vtkAbstractWidget* ); static void LeaveWidgetCallback ( vtkAbstractWidget* ); protected: vtkKWEPaintbrushWidget(); ~vtkKWEPaintbrushWidget(); // Description: // Geometric actions / states on that the representation responds to. int BeginDrawAction ( vtkKWEPaintbrushWidget *dispatcher); int EndStrokeAction ( vtkKWEPaintbrushWidget *dispatcher); int BeginEraseAction ( vtkKWEPaintbrushWidget *dispatcher); int HoverAction ( vtkKWEPaintbrushWidget *dispatcher); int UndoAction ( vtkKWEPaintbrushWidget *dispatcher); int RedoAction ( vtkKWEPaintbrushWidget *dispatcher); int DeleteAction ( vtkKWEPaintbrushWidget *dispatcher); int BeginResizeAction ( vtkKWEPaintbrushWidget *dispatcher); int BeginIsotropicResizeAction ( vtkKWEPaintbrushWidget *dispatcher); int ResizeAction ( vtkKWEPaintbrushWidget *dispatcher); int EndResizeAction ( vtkKWEPaintbrushWidget *dispatcher); int ToggleSelectStateAction ( vtkKWEPaintbrushWidget *dispatcher); int BeginNewSketchAction ( vtkKWEPaintbrushWidget *dispatcher); int IncrementSketchAction ( vtkKWEPaintbrushWidget *dispatcher); int DecrementSketchAction ( vtkKWEPaintbrushWidget *dispatcher); int EnterWidgetAction ( vtkKWEPaintbrushWidget *dispatcher); int LeaveWidgetAction ( vtkKWEPaintbrushWidget *dispatcher); int GoToSketchAction ( vtkKWEPaintbrushWidget *dispatcher); // Description: // Cursor management virtual void SetCursor( int interactionState ); private: vtkKWEPaintbrushWidget(const vtkKWEPaintbrushWidget&); //Not implemented void operator=(const vtkKWEPaintbrushWidget&); //Not implemented int ResizeStartPosition[2]; double ResizeFactor[3]; int WidgetState; int PaintbrushMode; vtkKWEPaintbrushAnnotationWidget * PaintbrushAnnotationWidget; vtkKWEPaintbrushSelectionWidget * PaintbrushSelectionWidget; }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushSelectionRepresentation2D.cxx0000644000175000017500000001455111363410610026365 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushSelectionRepresentation2D.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkProperty.h" #include "vtkObjectFactory.h" #include "vtkImageActorPointPlacer.h" #include "vtkActor.h" #include "vtkPolyDataMapper.h" #include "vtkPolyData.h" #include "vtkPoints.h" #include "vtkCellArray.h" vtkCxxRevisionMacro(vtkKWEPaintbrushSelectionRepresentation2D, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEPaintbrushSelectionRepresentation2D); //---------------------------------------------------------------------- vtkKWEPaintbrushSelectionRepresentation2D::vtkKWEPaintbrushSelectionRepresentation2D() { this->PointPlacer = vtkImageActorPointPlacer::New(); this->DragPolyData = vtkPolyData::New(); this->DragActor = vtkActor::New(); vtkPolyDataMapper *dragMapper = vtkPolyDataMapper::New(); this->DragActor->SetMapper( dragMapper ); dragMapper->SetInput( this->DragPolyData ); dragMapper->SetResolveCoincidentTopologyToPolygonOffset(); vtkCellArray * cells = vtkCellArray::New(); vtkPoints *points = vtkPoints::New(); cells->InsertNextCell(2); cells->InsertCellPoint(0); cells->InsertCellPoint(1); points->SetNumberOfPoints(2); this->DragPolyData->SetLines(cells); this->DragPolyData->SetPoints(points); cells->Delete(); points->Delete(); dragMapper->Delete(); this->DragActor->GetProperty()->SetLineStipplePattern( 0x00ff ); } //---------------------------------------------------------------------- vtkKWEPaintbrushSelectionRepresentation2D::~vtkKWEPaintbrushSelectionRepresentation2D() { this->DragPolyData->Delete(); this->DragActor->Delete(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionRepresentation2D::SetImageActor( vtkImageActor * a) { if (vtkImageActorPointPlacer * p = vtkImageActorPointPlacer::SafeDownCast(this->PointPlacer)) { p->SetImageActor(a); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionRepresentation2D::BuildRepresentation() { if ( this->DragBeginPoint[0] == VTK_DOUBLE_MIN || this->DragEndPoint[0] == VTK_DOUBLE_MIN ) { this->DragActor->VisibilityOff(); return; } // Set the color of the leader to the color of the sketch that we are // about to drop the dragged sketch. this->DragActor->VisibilityOn(); this->DragActor->GetProperty()->SetColor( this->DragAndDropDestination ? this->DragAndDropDestination->GetPaintbrushProperty()->GetColor() : this->SelectedSketch->GetPaintbrushProperty()->GetColor() ); vtkPoints * p = this->DragPolyData->GetPoints(); p->SetPoint( 0, this->DragBeginPoint ); p->SetPoint( 1, this->DragEndPoint ); this->DragPolyData->Modified(); } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionRepresentation2D::RenderOverlay(vtkViewport *viewport) { return this->DragActor->GetVisibility() ? this->DragActor->RenderOverlay(viewport) : 0; } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionRepresentation2D ::RenderOpaqueGeometry(vtkViewport *viewport) { this->BuildRepresentation(); return this->DragActor->GetVisibility() ? this->DragActor->RenderOpaqueGeometry(viewport) : 0; } #if VTKEdge_VTK_VERSION_DATE > 20070305 //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionRepresentation2D ::RenderTranslucentPolygonalGeometry(vtkViewport *viewport) { return this->DragActor->GetVisibility() ? this->DragActor->RenderTranslucentPolygonalGeometry(viewport) : 0; } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionRepresentation2D::HasTranslucentPolygonalGeometry() { return this->DragActor->GetVisibility() ? this->DragActor->HasTranslucentPolygonalGeometry() : 0; } #else //---------------------------------------------------------------------- // Legacy method to support VTK source versions prior to 2007/03/05 int vtkKWEPaintbrushSelectionRepresentation2D:: RenderTranslucentGeometry(vtkViewport *viewport) { return this->DragActor->GetVisibility() ? this->DragActor->RenderTranslucentGeometry(viewport) : 0; } #endif //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionRepresentation2D::GetActors( vtkPropCollection * pc ) { this->DragActor->GetActors(pc); } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionRepresentation2D ::DeepCopy(vtkWidgetRepresentation *rep) { vtkKWEPaintbrushSelectionRepresentation2D *r = vtkKWEPaintbrushSelectionRepresentation2D::SafeDownCast(rep); if (this == r || !r) { return; } if (vtkImageActorPointPlacer * pthis = vtkImageActorPointPlacer::SafeDownCast(this->PointPlacer)) { if (vtkImageActorPointPlacer * pthat = vtkImageActorPointPlacer::SafeDownCast(r->PointPlacer)) { pthis->SetImageActor(pthat->GetImageActor()); } } this->Superclass::DeepCopy(rep); } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionRepresentation2D::DragAndDropMerge() { int ret = this->Superclass::DragAndDropMerge(); this->DragBeginPoint[0] = this->DragEndPoint[0] = VTK_DOUBLE_MIN; this->DragActor->VisibilityOff(); return ret; } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionRepresentation2D ::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushBlend.h0000644000175000017500000000647711363410610022010 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushBlend - blend images together using alpha or opacity // .SECTION Description #ifndef __vtkKWEPaintbrushBlend_h #define __vtkKWEPaintbrushBlend_h #include "VTKEdgeConfigure.h" #include "vtkThreadedImageAlgorithm.h" #include class vtkImageStencilData; class vtkKWEPaintbrushDrawing; class vtkKWEPaintbrushBlendColors; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushBlend : public vtkThreadedImageAlgorithm { public: static vtkKWEPaintbrushBlend *New(); vtkTypeRevisionMacro(vtkKWEPaintbrushBlend,vtkThreadedImageAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set the opacity of an stencil. // Defaults to 0.5 vtkSetClampMacro(Opacity,double,0.0,1.0); vtkGetMacro(Opacity,double); // Description: // Restrict the blending to be performed on a set of extents.. does not // care about stuff outside the extents.. this will work only if the input and // the output are of the same // Description: // Set stencils to apply when blending the data. virtual void SetPaintbrushDrawing(vtkKWEPaintbrushDrawing *); vtkKWEPaintbrushDrawing * GetPaintbrushDrawing(); // Description: // Use an overlay ? Defaults to ON. // If ON, this class will produce an output image that represents a blending // of the input and the drawing, passed through a color lookup table. // If OFF, this class will produce an output image that is the drawing passed // through a color lookup table. vtkSetMacro( UseOverlay, int ); vtkGetMacro( UseOverlay, int ); vtkBooleanMacro( UseOverlay, int ); protected: vtkKWEPaintbrushBlend(); ~vtkKWEPaintbrushBlend(); virtual int RequestUpdateExtent(vtkInformation *, vtkInformationVector **, vtkInformationVector *); void ThreadedRequestData (vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector, vtkImageData ***inData, vtkImageData **outData, int ext[6], int id); // see vtkAlgorithm for docs. virtual int FillInputPortInformation(int, vtkInformation*); // see vtkAlgorithm for docs. virtual int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); double Opacity; int UseOverlay; private: vtkKWEPaintbrushBlend(const vtkKWEPaintbrushBlend&); // Not implemented. void operator=(const vtkKWEPaintbrushBlend&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushRepresentationGrayscale2D.h0000644000175000017500000000661411363410610026000 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef __vtkKWEPaintbrushRepresentationGrayscale2D_h #define __vtkKWEPaintbrushRepresentationGrayscale2D_h #include "vtkKWEPaintbrushRepresentation2D.h" class vtkActorCollection; class vtkMapperCollection; class vtkContourFilter; class vtkCollection; class vtkKWEPaintbrushSketch; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushRepresentationGrayscale2D : public vtkKWEPaintbrushRepresentation2D { public: // Description: // Instantiate this class. static vtkKWEPaintbrushRepresentationGrayscale2D *New(); // Description: // Standard VTK methods. vtkTypeRevisionMacro(vtkKWEPaintbrushRepresentationGrayscale2D, vtkKWEPaintbrushRepresentation2D); void PrintSelf(ostream& os, vtkIndent indent); // Description: // These are methods that satisfy vtkWidgetRepresentation's API. virtual void BuildRepresentation(); // Description: // Methods required by vtkProp superclass. virtual int RenderOverlay(vtkViewport *viewport); virtual int RenderOpaqueGeometry(vtkViewport *viewport); #if VTKEdge_VTK_VERSION_DATE > 20070305 virtual int RenderTranslucentPolygonalGeometry(vtkViewport *viewport); virtual int HasTranslucentPolygonalGeometry(); #else // Legacy method to support VTK source versions prior to 2007/03/05 virtual int RenderTranslucentGeometry(vtkViewport *viewport); #endif // Description: // Get the actors maintained by the representation, that need to be rendered. virtual void GetActors(vtkPropCollection *); // Description: // Set/Get the isovalue for contours on the grayscale brush data vtkSetMacro( IsoValue, double ); vtkGetMacro( IsoValue, double ); // Description: // See superclass documentation virtual void SetPaintbrushDrawing( vtkKWEPaintbrushDrawing * ); // Descirption: // Deep copy.. synchronizes states etc.. virtual void DeepCopy(vtkWidgetRepresentation *r); // Description: // INTERNAL - Do not use virtual void InstallPipeline() {} virtual void UnInstallPipeline() {} protected: vtkKWEPaintbrushRepresentationGrayscale2D(); ~vtkKWEPaintbrushRepresentationGrayscale2D(); double IsoValue; vtkCollection * ContourFilters; vtkMapperCollection * ContourPolyDataMappers; vtkActorCollection * ContourPolyDataActors; vtkCollection * ExtractComponents; vtkCollection * ImageClips; private: vtkKWEPaintbrushRepresentationGrayscale2D( const vtkKWEPaintbrushRepresentationGrayscale2D&); //Not implemented void operator=(const vtkKWEPaintbrushRepresentationGrayscale2D&); //Not implemented // Given an actor, it finds the sketch that its a rendition of. vtkKWEPaintbrushSketch * GetSketch( vtkActor * ); }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWELightPaintbrushWidgetCallbackMapper.cxx0000644000175000017500000000713211524700572026331 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWELightPaintbrushWidgetCallbackMapper.h" #include "vtkWidgetEventTranslator.h" #include "vtkAbstractWidget.h" #include "vtkCommand.h" #include "vtkObjectFactory.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkEvent.h" #include "vtkWidgetEvent.h" vtkStandardNewMacro(vtkKWELightPaintbrushWidgetCallbackMapper); //---------------------------------------------------------------------------- void vtkKWELightPaintbrushWidgetCallbackMapper::Bindings() { // Remove any events from the existing callback mapper. this->EventTranslator->ClearEvents(); // These are the event callbacks supported by this widget this->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkEvent::NoModifier, 0, 0, NULL, vtkKWEPaintbrushWidget::BeginDrawStrokeForThisSketchEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::BeginDrawThisSketchCallback); this->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkEvent::ControlModifier, 0, 0, NULL, vtkKWEPaintbrushWidget::BeginEraseStrokeForThisSketchEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::BeginEraseThisSketchCallback); this->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkEvent::ShiftModifier, 0, 0, NULL, vtkKWEPaintbrushWidget::BeginDrawStrokeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::BeginDrawCallback); this->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkEvent::ControlModifier | vtkEvent::ShiftModifier, 0, 0, NULL, vtkKWEPaintbrushWidget::BeginEraseStrokeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::BeginEraseCallback); this->SetCallbackMethod(vtkCommand::MouseMoveEvent, vtkWidgetEvent::Move, this->PaintbrushWidget, vtkKWEPaintbrushWidget::MoveCallback); this->SetCallbackMethod(vtkCommand::LeftButtonReleaseEvent, vtkKWEPaintbrushWidget::EndStrokeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::EndStrokeCallback); this->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkEvent::ShiftModifier, 0, 0, NULL, vtkKWEPaintbrushWidget::BeginIsotropicResizeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::BeginIsotropicResizeShapeCallback); this->SetCallbackMethod(vtkCommand::EnterEvent, vtkKWEPaintbrushWidget::EnterEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::EnterWidgetCallback); this->SetCallbackMethod(vtkCommand::LeaveEvent, vtkKWEPaintbrushWidget::LeaveEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::LeaveWidgetCallback); } //---------------------------------------------------------------------------- void vtkKWELightPaintbrushWidgetCallbackMapper::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEITKImageToStencilFilter.cxx0000644000175000017500000000620411363410610023650 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEITKImageToStencilFilter.h" #include "vtkImageStencilData.h" #include "vtkImageData.h" namespace vtkitk { vtkKWEITKImageToStencilFilter::vtkKWEITKImageToStencilFilter() { for (int i=0; i < 6; i++) { this->m_Extent[i] = -1; } this->m_BoundWithRadius = true; this->m_Radius[0] = 0; this->m_Radius[1] = 0; this->m_Radius[2] = 0; this->m_Center[0] = 0; this->m_Center[1] = 0; this->m_Center[2] = 0; } vtkKWEITKImageToStencilFilter::~vtkKWEITKImageToStencilFilter() { } void vtkKWEITKImageToStencilFilter::SetInput( vtkImageData * image ) { this->m_Filter->SetInput(image); } void vtkKWEITKImageToStencilFilter::SetCenter( int center[3] ) { m_Center[0] = center[0]; m_Center[1] = center[1]; m_Center[2] = center[2]; } void vtkKWEITKImageToStencilFilter::SetRadius( double radius[3] ) { m_Radius[0] = radius[0]; m_Radius[1] = radius[1]; m_Radius[2] = radius[2]; } int vtkKWEITKImageToStencilFilter::GetOutputAsStencil( vtkImageStencilData *stencilData ) { if (this->m_BoundWithRadius) { return this->m_Filter->GetSphereBoundedOutputAsStencil(stencilData, m_Center, m_Radius); } else { return this->m_Filter->GetOutputAsStencil(stencilData); } } void vtkKWEITKImageToStencilFilter::SetRequestedExtent( int extent[6] ) { if (this->m_Extent[0] == extent[0] && this->m_Extent[1] == extent[1] && this->m_Extent[2] == extent[2] && this->m_Extent[3] == extent[3] && this->m_Extent[4] == extent[4] && this->m_Extent[5] == extent[5]) { return; } for (int i=0; i < 6; i++) { this->m_Extent[i] = extent[i]; } this->Modified(); } void vtkKWEITKImageToStencilFilter::Update() { if ((this->m_Extent[0]) != (-1)) { int extent[6]; this->m_Filter->GetInput()->GetExtent(extent); m_Extent[0] = (m_Extent[0] < extent[0]) ? extent[0] : m_Extent[0]; m_Extent[1] = (m_Extent[1] > extent[1]) ? extent[1] : m_Extent[1]; m_Extent[2] = (m_Extent[2] < extent[2]) ? extent[2] : m_Extent[2]; m_Extent[3] = (m_Extent[3] > extent[3]) ? extent[3] : m_Extent[3]; m_Extent[4] = (m_Extent[4] < extent[4]) ? extent[4] : m_Extent[4]; m_Extent[5] = (m_Extent[5] > extent[5]) ? extent[5] : m_Extent[5]; } this->m_Filter->SetRequestedExtent(this->m_Extent); } } // end namespace vtkitk vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushRepresentation2D.h0000644000175000017500000002365011507576154024164 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushRepresentation2D - A widget representation that represents 2D paintbrushes // .SECTION Description // This is a concrete implementation of the abstract vtkKWEPaintbrushRepresentation // class for paintbrush effects on a 2D scene. // // A typical use will be as follows: // // \code // vtkKWEPaintbrushWidget * widget = vtkKWEPaintbrushWidget::New(); // widget->SetInteractor( RenderWindowInteractor ); // vtkKWEPaintbrushRepresentation2D * rep2D = vtkKWEPaintbrushRepresentation2D:: // SafeDownCast( widget->GetRepresentation() ); // \endcode // // .SECTION Behaviour // The paintbrush should behave like GIMP paintbrushes do. When you select a // paintbrush, you will have the template outline along with an alpha // transparency of the template moving with the cursor. You can click-drag-release // to draw/erase // // The vtkKWEPaintbrushWidget will set this representation into one of three // states: Draw, Erase or Interact. During the Interact state the brush // outline just hovers around with the template. During the Draw / Erase // state, the representation uses the stroke manager to add a stroke / // erase a stroke. // // .SECTION ShapePlacer // The default template uses a shape placer to validate the "validity" of the // shape at a given point. The default shape placer is a // \c vtkKWEVoxelAlignedImageActorPointPlacer. This placer snaps the tempate to // a position on the image grid. See the vtkPointPlacer architecture for // details. You can use this to restrict the shape to a given set of bounding // planes. // // .SECTION See Also #ifndef __vtkKWEPaintbrushRepresentation2D_h #define __vtkKWEPaintbrushRepresentation2D_h #include "vtkKWEPaintbrushRepresentation.h" class vtkActor; class vtkProperty; class vtkPolyDataMapper; class vtkPolyData; class vtkPoints; class vtkCellArray; class vtkKWEPaintbrushBlend; class vtkImageActor; class vtkImageData; class vtkActor2D; class vtkTextMapper; class vtkTextProperty; class vtkKWEPaintbrushHighlightActors; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushRepresentation2D : public vtkKWEPaintbrushRepresentation { public: // Description: // Instantiate this class. static vtkKWEPaintbrushRepresentation2D *New(); // Description: // Standard VTK methods. vtkTypeRevisionMacro(vtkKWEPaintbrushRepresentation2D,vtkKWEPaintbrushRepresentation); void PrintSelf(ostream& os, vtkIndent indent); // Description: // These are methods that satisfy vtkWidgetRepresentation's API. virtual void BuildRepresentation(); virtual int ComputeInteractionState(int X, int Y, int modified=0); virtual void StartWidgetInteraction(double e[2]); // Description: // Must be present to satisfy the vtkWidgetRepresentation's API. // This method will check the state of the representation. If the state is // "Draw" (states are set by the vtkKWEPaintbrushWidget); the representation // will enter this state during click-drags, the DrawFromLastEventPositionTo // method is invoked. virtual void WidgetInteraction(double eventPos[2]); // Description: // Methods required by vtkProp superclass. virtual void ReleaseGraphicsResources(vtkWindow *w); virtual int RenderOverlay(vtkViewport *viewport); virtual int RenderOpaqueGeometry(vtkViewport *viewport); #if VTKEdge_VTK_VERSION_DATE > 20070305 virtual int RenderTranslucentPolygonalGeometry(vtkViewport *viewport); virtual int HasTranslucentPolygonalGeometry(); #else // Legacy method to support VTK source versions prior to 2007/03/05 virtual int RenderTranslucentGeometry(vtkViewport *viewport); #endif // Description: // Set/Get the properties of the template outline. This should behave like // the GIMP paintbrushes do. When you select a paintbrush, you will have // the template outline along with an alpha transparency at the cursor // location. You can move around, place it somewhere, or drag with the // mouse button to create a stroke. void SetShapeOutlinePropertyInteract(vtkProperty*); vtkGetObjectMacro(ShapeOutlinePropertyInteract,vtkProperty); void SetShapeOutlinePropertyDraw(vtkProperty*); vtkGetObjectMacro(ShapeOutlinePropertyDraw,vtkProperty); void SetShapeOutlinePropertyErase(vtkProperty*); vtkGetObjectMacro(ShapeOutlinePropertyErase,vtkProperty); // Description: virtual int ActivateShapeOutline( int x, int y ); // Description: // Create the template outline at location pos[3] (world coords) virtual void CreateShapeOutline( double * pos ); // Description: // Get the actors maintained by the representation, that need to be rendered. virtual void GetActors(vtkPropCollection *); virtual void GetActors2D(vtkPropCollection *); // Description: // Set the Paintbrush representation state virtual void SetStateToDraw(); virtual void SetStateToErase(); virtual void SetStateToInteract(); virtual void SetStateToDisabled(); // Description: // Set the paintbrush operation. Here we override the superclass methodm so // that we can set some defaults of the operation based on the imageactor's // input. virtual void SetPaintbrushOperation( vtkKWEPaintbrushOperation * ); // Description: // Set the image actor on which the paintbrush is drawn. We will need to // update the actor with the stencil's output etc.. virtual void SetImageActor( vtkImageActor * ); vtkGetObjectMacro ( ImageActor, vtkImageActor ); // Description: // Set the underlying image data. While this is not always necessary, it // is required by some variants of the paintbrush widget such as region // growing widgets, etc that use features from the underlying image data. // At best, just specify the underlying image data always.. (In most // cases, its just the ImageActor->GetInput()) // // NOTE: The canvas (PaintbrushDrawing) gets allocated when you invoke this // method. You would do well to set the representation on the drawing // prior to calling this method, so as to avoid unnecessary // re-allocation later on. virtual void SetImageData( vtkImageData * ); vtkGetObjectMacro( ImageData, vtkImageData ); // Descirption: // Deep copy.. synchronizes states etc.. virtual void DeepCopy(vtkWidgetRepresentation *r); // Description: // See superclass documentation virtual int ResizeShape( double d[3], int resizeType ); virtual void SetPaintbrushDrawing( vtkKWEPaintbrushDrawing * ); virtual void SetShapeOutlineVisibility( int ); virtual int GetShapeOutlineVisibility( ); // Description: // INTERNAL - Do not use. // Invoked by the widget in response to user interaction // Increase / Decrease the opacity of the drawing. virtual int IncreaseOpacity(); virtual int DecreaseOpacity(); // Description: // INTERNAL - Do not use // Sticks the stencil into the pipeline. (between the ImageActor and its // original input). virtual void InstallPipeline(); virtual void UnInstallPipeline(); // Description: // See docuementation of vtkKWEPaintbrushBlend::SetUseOverlay vtkSetMacro( UseOverlay, int ); vtkGetMacro( UseOverlay, int ); vtkBooleanMacro( UseOverlay, int ); // Description: // Do a slice by slice painting, or paint in 3D using a 3D shape. If we do a // Single slice painting, the dimension of the shape orthogonal to the // currently displayed slice will be flattened implicitly. Default is 3D // painting. vtkSetMacro( SingleSliceThickBrush, int ); vtkGetMacro( SingleSliceThickBrush, int ); vtkBooleanMacro( SingleSliceThickBrush, int ); // Description: // Copy a sketch from the currently displayed slice to the next/previous // slice. Returns 1 on success / 0 on failure. virtual int CopySketchToNextSlice( vtkKWEPaintbrushSketch *s ); virtual int CopySketchToPreviousSlice( vtkKWEPaintbrushSketch *s ); // Description: // INTERNAL - Do not use // This method is called from vtkKWEPaintbrushWidget whenever we draw using // a shape centered at the location "p". Here we override the superclass // method. virtual void AddShapeToCurrentStroke( double p[3] ); protected: vtkKWEPaintbrushRepresentation2D(); ~vtkKWEPaintbrushRepresentation2D(); // Description: // Create default representation. The default representation instantiates // a new sequencer, if one hasn't been set. It also sets default properties // for the ShapeOutline etc. virtual void CreateDefaultRepresentation(); vtkPolyData *ShapeOutline; vtkPolyDataMapper *ShapeOutlineMapper; vtkActor *ShapeOutlineActor; vtkProperty *ShapeOutlinePropertyInteract; vtkProperty *ShapeOutlinePropertyDraw; vtkProperty *ShapeOutlinePropertyErase; vtkImageActor *ImageActor; vtkImageData *ImageData; vtkKWEPaintbrushHighlightActors *HighlightActors; double LastEventPosition[2]; int SingleSliceThickBrush; // Description: // Get the extents of the current etch. virtual void GetEtchExtents( int extent[6] ); private: vtkKWEPaintbrushRepresentation2D(const vtkKWEPaintbrushRepresentation2D&); //Not implemented void operator=(const vtkKWEPaintbrushRepresentation2D&); //Not implemented vtkKWEPaintbrushBlend *PaintbrushBlend; int UseOverlay; }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushBlend.cxx0000644000175000017500000013441711363410610022357 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushBlend.h" #include "vtkAlgorithmOutput.h" #include "vtkImageData.h" #include "vtkImageStencilData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkPointData.h" #include "vtkCollection.h" #include "vtkProperty.h" #include "vtkImageIterator.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushPropertyManager.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushEnums.h" typedef unsigned char VTKColorType [3]; //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkKWEPaintbrushBlend, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEPaintbrushBlend); //---------------------------------------------------------------------------- vtkKWEPaintbrushBlend::vtkKWEPaintbrushBlend() { this->SetNumberOfInputPorts(2); this->Opacity = 0.5; this->UseOverlay=1; } //---------------------------------------------------------------------------- vtkKWEPaintbrushBlend::~vtkKWEPaintbrushBlend() { } //---------------------------------------------------------------------------- vtkKWEPaintbrushDrawing *vtkKWEPaintbrushBlend::GetPaintbrushDrawing() { if (this->GetNumberOfInputConnections(1) < 1) { return NULL; } return vtkKWEPaintbrushDrawing::SafeDownCast( this->GetExecutive()->GetInputData(1,0)); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushBlend::SetPaintbrushDrawing( vtkKWEPaintbrushDrawing *c) { // if stencil is null, then set the input port to null this->SetInput(1, c); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushBlend::RequestUpdateExtent( vtkInformation * vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo0 = inputVector[0]->GetInformationObject(0); vtkInformation *inInfo1 = inputVector[1]->GetInformationObject(0); vtkInformation* outInfo = outputVector->GetInformationObject(0); // default input extents will be that of output extent int inExt[6]; outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),inExt); inInfo0->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),inExt,6); inInfo1->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),inExt,6); return 1; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushBlend::RequestData( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkImageData *input = vtkImageData::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); if (!input || ! this->GetPaintbrushDrawing()) { return 1; } vtkInformation *info = inputVector[1]->GetInformationObject(0); vtkKWEPaintbrushDrawing *drawing = vtkKWEPaintbrushDrawing::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); // Attempt to assign a (possibly unique) color for each sketch in the drawing drawing->GetPaintbrushPropertyManager()->Update(); if (drawing->GetRepresentation() == vtkKWEPaintbrushEnums::Label) { // Preprocess and store all the labels. } return this->Superclass::RequestData(request,inputVector,outputVector); } //---------------------------------------------------------------------------- // This templated function blends a stencil that represents a sketch from a // drawing into the overlaid image. This method is specific to the case when // the overlaid image has data type of CHAR template void vtkKWEPaintbrushBlendExecuteChar( vtkImageStencilData * stencil, vtkKWEPaintbrushBlend *vtkNotUsed(self), int extent[6], vtkImageData *inData, T *, vtkImageData *outData, T *, double opacity, unsigned char color[3]) { int inC, outC; unsigned short r, f, o; int v0, v1, v2; int stencilExtent[6]; // round opacity to a value in the range [0,256], because division // by 256 can be efficiently achieved by bit-shifting by 8 bits o = static_cast(256*opacity + 0.5); r = o; f = static_cast(256 - o); inC = inData->GetNumberOfScalarComponents(); outC = outData->GetNumberOfScalarComponents(); // Check the stencil extents stencil->GetExtent(stencilExtent); stencilExtent[0] = (stencilExtent[0] < extent[0]) ? extent[0] : stencilExtent[0]; stencilExtent[1] = (stencilExtent[1] > extent[1]) ? extent[1] : stencilExtent[1]; stencilExtent[2] = (stencilExtent[2] < extent[2]) ? extent[2] : stencilExtent[2]; stencilExtent[3] = (stencilExtent[3] > extent[3]) ? extent[3] : stencilExtent[3]; stencilExtent[4] = (stencilExtent[4] < extent[4]) ? extent[4] : stencilExtent[4]; stencilExtent[5] = (stencilExtent[5] > extent[5]) ? extent[5] : stencilExtent[5]; // Loop through ouput pixels for (int idxZ = stencilExtent[4]; idxZ <= stencilExtent[5]; idxZ++) { for (int idxY = stencilExtent[2]; idxY <= stencilExtent[3]; idxY++) { int iter = 0, moreSubExtents = 1, r1, r2; while (moreSubExtents) { moreSubExtents = stencil->GetNextExtent( r1, r2, stencilExtent[0], stencilExtent[1], idxY, idxZ, iter ); r1 = (r1 < stencilExtent[0]) ? stencilExtent[0] : r1; r2 = (r2 > stencilExtent[1]) ? stencilExtent[1] : r2; if (r1 <= r2 ) // sanity check { T *beginInPtr = static_cast(inData->GetScalarPointer(r1, idxY, idxZ)); T *beginOutPtr = static_cast(outData->GetScalarPointer(r1, idxY, idxZ)); T *endOutPtr = static_cast(outData->GetScalarPointer(r2, idxY, idxZ)); while (beginOutPtr <= endOutPtr) { if (outC >= 3 && inC >= 4) { // RGB(A) blended with RGBA // multiply to get a number in the range [0,65280] // where 65280 = 255*256 = range of beginInPtr[3] * range of o r = static_cast(beginInPtr[3]*o); f = static_cast(65280 - r); v0 = beginInPtr[0]*f + color[0]*r; v1 = beginInPtr[1]*f + color[1]*r; v2 = beginInPtr[2]*f + color[2]*r; // do some math tricks to achieve division by 65280: // this is not an approximation, it gives exactly the // same result as an integer division by 65280 beginOutPtr[0] = static_cast((v0 + (v0 >> 8) + (v0 >> 16) + 1) >> 16); beginOutPtr[1] = static_cast((v1 + (v1 >> 8) + (v1 >> 16) + 1) >> 16); beginOutPtr[2] = static_cast((v2 + (v2 >> 8) + (v2 >> 16) + 1) >> 16); } else if (outC >= 3 && inC == 3) { // RGB(A) blended with RGB // the bit-shift achieves a division by 256 beginOutPtr[0] = static_cast((beginInPtr[0]*f + color[0]*r) >> 8); beginOutPtr[1] = static_cast((beginInPtr[1]*f + color[1]*r) >> 8); beginOutPtr[2] = static_cast((beginInPtr[2]*f + color[2]*r) >> 8); } else if (inC == 2) { // luminance(+alpha) blended with luminance+alpha // multiply to get a number in the range [0,65280] // where 65280 = 255*256 = range of beginInPtr[1] * range of o r = static_cast(beginInPtr[1]*o); f = static_cast(65280 - r); v0 = beginOutPtr[0]*f + beginInPtr[0]*r; // do some math tricks to achieve division by 65280: // this is not an approximation, it gives exactly the // same result as an integer division by 65280 beginOutPtr[0] = static_cast((v0 + (v0 >> 8) + (v0 >> 16) + 1) >> 16); } else { // luminance(+alpha) blended with luminance // the bit-shift achieves a division by 256 beginOutPtr[0] = static_cast((beginInPtr[0]*f) >> 8); } beginInPtr += inC; beginOutPtr += outC; } } } } } } //---------------------------------------------------------------------------- // This templated function blends an image that represents a label map into // the overlay image. This function is specific to the case when the overlay // image has data type of CHAR template void vtkKWEPaintbrushBlendExecuteChar( vtkKWEPaintbrushLabelData *labelMap, vtkKWEPaintbrushBlend *self, int extent[6], vtkImageData *inData, T *, vtkImageData *outData, T *, vtkKWEPaintbrushPropertyManager::LabelToColorMapType &labelToColorMap) { // Is an overlay present ? If absent, the label map, passed through the // color lookup table is displayed as is. If not, it is blended with // the overlay and displayed. bool useOverlay = self->GetUseOverlay() ? true : false; int inC, outC; unsigned short r = 0, f = 0, o = 0; int v0, v1, v2; int labelMapExtent[6]; inC = inData->GetNumberOfScalarComponents(); outC = outData->GetNumberOfScalarComponents(); // Check the label map's extents labelMap->GetExtent(labelMapExtent); // Find the intersection of the labelmap's extents and the overlaid image's // extents. This is the region we need to be blending. labelMapExtent[0] = (labelMapExtent[0] < extent[0]) ? extent[0] : labelMapExtent[0]; labelMapExtent[1] = (labelMapExtent[1] > extent[1]) ? extent[1] : labelMapExtent[1]; labelMapExtent[2] = (labelMapExtent[2] < extent[2]) ? extent[2] : labelMapExtent[2]; labelMapExtent[3] = (labelMapExtent[3] > extent[3]) ? extent[3] : labelMapExtent[3]; labelMapExtent[4] = (labelMapExtent[4] < extent[4]) ? extent[4] : labelMapExtent[4]; labelMapExtent[5] = (labelMapExtent[5] > extent[5]) ? extent[5] : labelMapExtent[5]; vtkImageData *labelMapData = labelMap->GetLabelMap(); // Lookup table of label to color map. unsigned char color[3]; // To avoid gcc 4.4 warning "color[x] may be used uninitialized in this // function [-Wuninitialized]" color[0]=0; color[1]=0; color[2]=0; vtkKWEPaintbrushPropertyManager::vtkKWEPaintbrushLabelMapColor colorClass; // Loop through pixels T *beginInPtr = NULL, *beginOutPtr; vtkKWEPaintbrushEnums::LabelType * labelPtr; // Type of compositing.. int compositeType = 3; // luminance(+alpha) blended with luminance if (outC >= 3 && inC >= 4) { // RGB(A) blended with RGBA compositeType = 0; } else if (outC >= 3 && inC == 3) { // RGB(A) blended with RGB compositeType = 1; } else if (inC == 2) { // luminance(+alpha) blended with luminance+alpha compositeType = 2; } vtkKWEPaintbrushEnums::LabelType lastLabel = vtkKWEPaintbrushLabelData::NoLabelValue; // Loop through ouput pixels for (int idxZ = labelMapExtent[4]; idxZ <= labelMapExtent[5]; idxZ++) { for (int idxY = labelMapExtent[2]; idxY <= labelMapExtent[3]; idxY++) { if (useOverlay) { beginInPtr = static_cast(inData->GetScalarPointer(labelMapExtent[0], idxY, idxZ)); } beginOutPtr = static_cast(outData->GetScalarPointer(labelMapExtent[0], idxY, idxZ)); labelPtr = static_cast( labelMapData->GetScalarPointer(labelMapExtent[0], idxY, idxZ)); for (int idxX = labelMapExtent[0]; idxX <= labelMapExtent[1]; idxX++) { const vtkKWEPaintbrushEnums::LabelType label = *labelPtr; if (useOverlay) { if (label != vtkKWEPaintbrushLabelData::NoLabelValue) { if( label != lastLabel ) { colorClass = labelToColorMap[label]; lastLabel = label; color[0] = colorClass.Color[0]; color[1] = colorClass.Color[1]; color[2] = colorClass.Color[2]; // round opacity to a value in the range [0,256], because division // by 256 can be efficiently achieved by bit-shifting by 8 bits o = static_cast(256*colorClass.Opacity + 0.5); r = o; f = static_cast(256 - o); } if (compositeType == 0) { // RGB(A) blended with RGBA // multiply to get a number in the range [0,65280] // where 65280 = 255*256 = range of inSI[3] * range of o r = static_cast(beginInPtr[3]*o); f = static_cast(65280 - r); v0 = beginInPtr[0]*f + color[0]*r; v1 = beginInPtr[1]*f + color[1]*r; v2 = beginInPtr[2]*f + color[2]*r; // do some math tricks to achieve division by 65280: // this is not an approximation, it gives exactly the // same result as an integer division by 65280 beginOutPtr[0] = static_cast((v0 + (v0 >> 8) + (v0 >> 16) + 1) >> 16); beginOutPtr[1] = static_cast((v1 + (v1 >> 8) + (v1 >> 16) + 1) >> 16); beginOutPtr[2] = static_cast((v2 + (v2 >> 8) + (v2 >> 16) + 1) >> 16); } else if (compositeType == 1) { // the bit-shift achieves a division by 256 beginOutPtr[0] = static_cast((beginInPtr[0]*f + color[0]*r) >> 8); beginOutPtr[1] = static_cast((beginInPtr[1]*f + color[1]*r) >> 8); beginOutPtr[2] = static_cast((beginInPtr[2]*f + color[2]*r) >> 8); } else if (compositeType == 2) { // luminance(+alpha) blended with luminance+alpha // multiply to get a number in the range [0,65280] // where 65280 = 255*256 = range of beginInPtr[1] * range of o r = static_cast(beginInPtr[1]*o); f = static_cast(65280 - r); v0 = beginOutPtr[0]*f + beginInPtr[0]*r; // do some math tricks to achieve division by 65280: // this is not an approximation, it gives exactly the // same result as an integer division by 65280 beginOutPtr[0] = static_cast((v0 + (v0 >> 8) + (v0 >> 16) + 1) >> 16); } else { // luminance(+alpha) blended with luminance // the bit-shift achieves a division by 256 beginOutPtr[0] = static_cast((beginInPtr[0]*f) >> 8); } } beginInPtr += inC; beginOutPtr += outC; ++labelPtr; } else // No overlays. { if( label != lastLabel ) { colorClass = labelToColorMap[label]; lastLabel = label; } if (compositeType == 0) { beginOutPtr[0] = colorClass.Color[0]; beginOutPtr[1] = colorClass.Color[1]; beginOutPtr[2] = colorClass.Color[2]; if (outC > 3) { beginOutPtr[3] = 255; } } else if (compositeType == 1) { beginOutPtr[0] = colorClass.Color[0]; beginOutPtr[1] = colorClass.Color[1]; beginOutPtr[2] = colorClass.Color[2]; } else if (compositeType == 2) { beginOutPtr[0] = colorClass.Color[0]; } else { // luminance(+alpha) blended with luminance // the bit-shift achieves a division by 256 beginOutPtr[0] = colorClass.Color[0]; } beginOutPtr += outC; ++labelPtr; } } } } } //---------------------------------------------------------------------------- // This templated function blends an image that represents a label map into // the overlay image. This function is specific to the case when the overlay // (canvas) image as well as the label map have data type of CHAR template void vtkKWEPaintbrushBlendExecuteCharLabelMapTypeUC( vtkKWEPaintbrushLabelData * labelMap, vtkKWEPaintbrushBlend *self, int extent[6], vtkImageData *inData, T *, vtkImageData *outData, T *, VTKColorType *labelToColorMapUC, double *labelToOpacityMapUC) { // Is an overlay present ? If absent, the label map, passed through the // color lookup table is displayed as is. If not, it is blended with // the overlay and displayed. bool useOverlay = self->GetUseOverlay() ? true : false; int inC, outC; unsigned short r, f, o; int v0, v1, v2; int labelMapExtent[6]; double opacity = 1.0; inC = inData->GetNumberOfScalarComponents(); outC = outData->GetNumberOfScalarComponents(); // Check the label map's extents labelMap->GetExtent(labelMapExtent); // Find the intersection of the labelmap's extents and the overlaid image's // extents. This is the region we need to be blending. labelMapExtent[0] = (labelMapExtent[0] < extent[0]) ? extent[0] : labelMapExtent[0]; labelMapExtent[1] = (labelMapExtent[1] > extent[1]) ? extent[1] : labelMapExtent[1]; labelMapExtent[2] = (labelMapExtent[2] < extent[2]) ? extent[2] : labelMapExtent[2]; labelMapExtent[3] = (labelMapExtent[3] > extent[3]) ? extent[3] : labelMapExtent[3]; labelMapExtent[4] = (labelMapExtent[4] < extent[4]) ? extent[4] : labelMapExtent[4]; labelMapExtent[5] = (labelMapExtent[5] > extent[5]) ? extent[5] : labelMapExtent[5]; vtkImageData *labelMapData = labelMap->GetLabelMap(); vtkImageIterator< T > inIt( inData, labelMapExtent ); vtkImageIterator< T > outIt( outData, labelMapExtent ); vtkImageIterator< vtkKWEPaintbrushEnums::LabelType > labelMapIt( labelMapData, labelMapExtent ); unsigned char *color; int compositeType = 3; if (outC >= 3 && inC >= 4) { compositeType = 0; } else if (outC >= 3 && inC == 3) { compositeType = 1; } else if (inC == 2) { compositeType = 2; } T *beginInPtr = 0, *beginOutPtr; vtkKWEPaintbrushEnums::LabelType * labelPtr; // Loop through ouput pixels for (int idxZ = labelMapExtent[4]; idxZ <= labelMapExtent[5]; idxZ++) { for (int idxY = labelMapExtent[2]; idxY <= labelMapExtent[3]; idxY++) { if (useOverlay) { beginInPtr = static_cast(inData->GetScalarPointer(labelMapExtent[0], idxY, idxZ)); } beginOutPtr = static_cast(outData->GetScalarPointer(labelMapExtent[0], idxY, idxZ)); labelPtr = static_cast( labelMapData->GetScalarPointer(labelMapExtent[0], idxY, idxZ)); for (int idxX = labelMapExtent[0]; idxX <= labelMapExtent[1]; idxX++) { const vtkKWEPaintbrushEnums::LabelType label = *labelPtr; if (useOverlay) { if (label != vtkKWEPaintbrushLabelData::NoLabelValue) { // Get the color for this label in the label map. color = labelToColorMapUC[label]; opacity = labelToOpacityMapUC[label]; // round opacity to a value in the range [0,256], because division // by 256 can be efficiently achieved by bit-shifting by 8 bits o = static_cast(256*opacity + 0.5); r = o; f = static_cast(256 - o); if (compositeType == 0) { if (useOverlay) { // RGB(A) blended with RGBA // multiply to get a number in the range [0,65280] // where 65280 = 255*256 = range of beginInPtr[3] * range of o r = static_cast(beginInPtr[3]*o); f = static_cast(65280 - r); v0 = beginInPtr[0]*f + color[0]*r; v1 = beginInPtr[1]*f + color[1]*r; v2 = beginInPtr[2]*f + color[2]*r; // do some math tricks to achieve division by 65280: // this is not an approximation, it gives exactly the // same result as an integer division by 65280 beginOutPtr[0] = static_cast((v0 + (v0 >> 8) + (v0 >> 16) + 1) >> 16); beginOutPtr[1] = static_cast((v1 + (v1 >> 8) + (v1 >> 16) + 1) >> 16); beginOutPtr[2] = static_cast((v2 + (v2 >> 8) + (v2 >> 16) + 1) >> 16); } else { beginOutPtr[0] = color[0]; beginOutPtr[1] = color[1]; beginOutPtr[2] = color[2]; } } else if (compositeType == 1) { if (useOverlay) { // RGB(A) blended with RGB // the bit-shift achieves a division by 256 beginOutPtr[0] = static_cast((beginInPtr[0]*f + color[0]*r) >> 8); beginOutPtr[1] = static_cast((beginInPtr[1]*f + color[1]*r) >> 8); beginOutPtr[2] = static_cast((beginInPtr[2]*f + color[2]*r) >> 8); } else { beginOutPtr[0] = color[0]; beginOutPtr[1] = color[1]; beginOutPtr[2] = color[2]; } } else if (compositeType == 2) { // luminance(+alpha) blended with luminance+alpha // multiply to get a number in the range [0,65280] // where 65280 = 255*256 = range of beginInPtr[1] * range of o r = static_cast(beginInPtr[1]*o); f = static_cast(65280 - r); v0 = beginOutPtr[0]*f + beginInPtr[0]*r; // do some math tricks to achieve division by 65280: // this is not an approximation, it gives exactly the // same result as an integer division by 65280 beginOutPtr[0] = static_cast((v0 + (v0 >> 8) + (v0 >> 16) + 1) >> 16); } else { // luminance(+alpha) blended with luminance // the bit-shift achieves a division by 256 beginOutPtr[0] = static_cast((beginInPtr[0]*f) >> 8); } } beginInPtr += inC; beginOutPtr += outC; ++labelPtr; } else // no overlay { // Get the color for this label in the label map. color = labelToColorMapUC[label]; if (compositeType == 0) { beginOutPtr[0] = color[0]; beginOutPtr[1] = color[1]; beginOutPtr[2] = color[2]; if (outC > 3) { beginOutPtr[3] = 255; } } else if (compositeType == 1) { beginOutPtr[0] = color[0]; beginOutPtr[1] = color[1]; beginOutPtr[2] = color[2]; } else if (compositeType == 2) { beginOutPtr[0] = color[0]; } else { beginOutPtr[0] = color[0]; } beginOutPtr += outC; ++labelPtr; } } } } } //---------------------------------------------------------------------------- template void vtkKWEPaintbrushBlendExecute( vtkImageStencilData *stencil, vtkKWEPaintbrushBlend *vtkNotUsed(self), int extent[6], vtkImageData *inData, T *, vtkImageData *outData, T *, double opacity ) { int inC, outC; double r, f; double minA, maxA; int stencilExtent[6]; if (inData->GetScalarType() == VTK_DOUBLE || inData->GetScalarType() == VTK_FLOAT) { minA = 0.0; maxA = 1.0; } else { minA = inData->GetScalarTypeMin(); maxA = inData->GetScalarTypeMax(); } r = opacity; f = 1.0 - r; opacity = opacity/(maxA-minA); inC = inData->GetNumberOfScalarComponents(); outC = outData->GetNumberOfScalarComponents(); // Check the stencil extents stencil->GetExtent(stencilExtent); stencilExtent[0] = (stencilExtent[0] < extent[0]) ? extent[0] : stencilExtent[0]; stencilExtent[1] = (stencilExtent[1] > extent[1]) ? extent[1] : stencilExtent[1]; stencilExtent[2] = (stencilExtent[2] < extent[2]) ? extent[2] : stencilExtent[2]; stencilExtent[3] = (stencilExtent[3] > extent[3]) ? extent[3] : stencilExtent[3]; stencilExtent[4] = (stencilExtent[4] < extent[4]) ? extent[4] : stencilExtent[4]; stencilExtent[5] = (stencilExtent[5] > extent[5]) ? extent[5] : stencilExtent[5]; // Loop through ouput pixels for (int idxZ = stencilExtent[4]; idxZ <= stencilExtent[5]; idxZ++) { for (int idxY = stencilExtent[2]; idxY <= stencilExtent[3]; idxY++) { int iter = 0, moreSubExtents = 1, r1, r2; while (moreSubExtents) { moreSubExtents = stencil->GetNextExtent( r1, r2, stencilExtent[0], stencilExtent[1], idxY, idxZ, iter ); if (r1 <= r2 ) // sanity check { T *beginOutPtr= static_cast(outData->GetScalarPointer(r1, idxY, idxZ)); T *endOutPtr= static_cast(outData->GetScalarPointer(r2, idxY, idxZ)); T *beginInPtr= static_cast(inData->GetScalarPointer(r1, idxY, idxZ)); while (beginOutPtr <= endOutPtr) { if (outC >= 3 && inC >= 4) { // RGB(A) blended with RGBA // multiply to get a number in the range [0,65280] // where 65280 = 255*256 = range of beginInPtr[3] * range of o r = opacity*(static_cast(beginInPtr[3])-minA); f = 1.0-r; beginOutPtr[0] = T(static_cast(beginOutPtr[0])*f + static_cast(beginInPtr[0])*r); beginOutPtr[1] = T(static_cast(beginOutPtr[1])*f + static_cast(beginInPtr[1])*r); beginOutPtr[2] = T(static_cast(beginOutPtr[2])*f + static_cast(beginInPtr[2])*r); beginOutPtr += outC; beginInPtr += inC; } else if (outC >= 3 && inC == 3) { // RGB(A) blended with RGB // the bit-shift achieves a division by 256 beginOutPtr[0] = T(static_cast(beginOutPtr[0])*f + static_cast(beginInPtr[0])*r); beginOutPtr[1] = T(static_cast(beginOutPtr[1])*f + static_cast(beginInPtr[1])*r); beginOutPtr[2] = T(static_cast(beginOutPtr[2])*f + static_cast(beginInPtr[2])*r); beginOutPtr += outC; beginInPtr += inC; } else if (inC == 2) { r = opacity*(static_cast(beginInPtr[1])-minA); f = 1.0-r; *beginOutPtr = T(static_cast(*beginOutPtr)*f + static_cast(*beginInPtr)*r); beginOutPtr += outC; beginInPtr += 2; } else { // luminance(+alpha) blended with luminance // the bit-shift achieves a division by 256 *beginOutPtr = T(static_cast(*beginOutPtr)*f + static_cast(*beginInPtr)*r); beginOutPtr += outC; beginInPtr++; } } } } } } } //---------------------------------------------------------------------------- // Label map blend method for general overlay data (not unsigned char overlays) template void vtkKWEPaintbrushBlendExecute( vtkKWEPaintbrushLabelData *labelMap, vtkKWEPaintbrushBlend *vtkNotUsed(self), int extent[6], vtkImageData *inData, T *, vtkImageData *outData, T *, vtkKWEPaintbrushPropertyManager::LabelToColorMapType &labelToColorMap ) { int inC, outC; double r, f, opacity; double minA, maxA; int labelMapExtent[6]; if (inData->GetScalarType() == VTK_DOUBLE || inData->GetScalarType() == VTK_FLOAT) { minA = 0.0; maxA = 1.0; } else { minA = inData->GetScalarTypeMin(); maxA = inData->GetScalarTypeMax(); } inC = inData->GetNumberOfScalarComponents(); outC = outData->GetNumberOfScalarComponents(); // Check the label map's extents labelMap->GetExtent(labelMapExtent); // Find the intersection of the labelmap's extents and the overlaid image's // extents. This is the region we need to be blending. labelMapExtent[0] = (labelMapExtent[0] < extent[0]) ? extent[0] : labelMapExtent[0]; labelMapExtent[1] = (labelMapExtent[1] > extent[1]) ? extent[1] : labelMapExtent[1]; labelMapExtent[2] = (labelMapExtent[2] < extent[2]) ? extent[2] : labelMapExtent[2]; labelMapExtent[3] = (labelMapExtent[3] > extent[3]) ? extent[3] : labelMapExtent[3]; labelMapExtent[4] = (labelMapExtent[4] < extent[4]) ? extent[4] : labelMapExtent[4]; labelMapExtent[5] = (labelMapExtent[5] > extent[5]) ? extent[5] : labelMapExtent[5]; vtkImageIterator< T > inIt( inData, labelMapExtent ); vtkImageIterator< T > outIt( outData, labelMapExtent ); vtkImageIterator< vtkKWEPaintbrushEnums::LabelType > labelMapIt( labelMap->GetLabelMap(), labelMapExtent ); // Lookup table of label to color map. unsigned char color[3]; vtkKWEPaintbrushPropertyManager::vtkKWEPaintbrushLabelMapColor colorClass; // Loop through pixels while (!labelMapIt.IsAtEnd()) { vtkKWEPaintbrushEnums::LabelType *labelMapSI = labelMapIt.BeginSpan(); vtkKWEPaintbrushEnums::LabelType *labelMapSIEnd = labelMapIt.EndSpan(); T *inSI = inIt.BeginSpan(); T *outSI = outIt.BeginSpan(); while (labelMapSI != labelMapSIEnd) { const vtkKWEPaintbrushEnums::LabelType label = *labelMapSI; colorClass = labelToColorMap[label]; color[0] = colorClass.Color[0]; color[1] = colorClass.Color[1]; color[2] = colorClass.Color[2]; opacity = colorClass.Opacity; r = opacity; f = 1.0 - r; opacity = opacity/(maxA-minA); if (outC >= 3 && inC >= 4) { // RGB(A) blended with RGBA // multiply to get a number in the range [0,65280] // where 65280 = 255*256 = range of inSI[3] * range of o r = opacity*(static_cast(inSI[3])-minA); f = 1.0-r; outSI[0] = T(static_cast(outSI[0])*f + static_cast(inSI[0])*r); outSI[1] = T(static_cast(outSI[1])*f + static_cast(inSI[1])*r); outSI[2] = T(static_cast(outSI[2])*f + static_cast(inSI[2])*r); outSI += outC; inSI += inC; } else if (outC >= 3 && inC == 3) { // RGB(A) blended with RGB // the bit-shift achieves a division by 256 outSI[0] = T(static_cast(outSI[0])*f + static_cast(inSI[0])*r); outSI[1] = T(static_cast(outSI[1])*f + static_cast(inSI[1])*r); outSI[2] = T(static_cast(outSI[2])*f + static_cast(inSI[2])*r); outSI += outC; inSI += inC; } else if (inC == 2) { r = opacity*(static_cast(inSI[1])-minA); f = 1.0-r; *outSI = T(static_cast(*outSI)*f + static_cast(*inSI)*r); outSI += outC; inSI += 2; } else { // luminance(+alpha) blended with luminance // the bit-shift achieves a division by 256 *outSI = T(static_cast(*outSI)*f + static_cast(*inSI)*r); outSI += outC; inSI++; } ++labelMapSI; inSI += inC; outSI += outC; } labelMapIt.NextSpan(); inIt.NextSpan(); outIt.NextSpan(); } } //---------------------------------------------------------------------------- // This templated function blends an image that represents a label map into // the overlay image. This function is specific to the case when the overlay // image has data type of CHAR template void vtkKWEPaintbrushBlendExecuteLabelMapTypeUC( vtkKWEPaintbrushLabelData *labelMap, vtkKWEPaintbrushBlend *vtkNotUsed(self), int extent[6], vtkImageData *inData, T *, vtkImageData *outData, T *, VTKColorType *labelToColorMapUC, double *labelToOpacityMapUC) { int inC, outC; double r, f, opacity; double minA, maxA; int labelMapExtent[6]; unsigned char *color; if (inData->GetScalarType() == VTK_DOUBLE || inData->GetScalarType() == VTK_FLOAT) { minA = 0.0; maxA = 1.0; } else { minA = inData->GetScalarTypeMin(); maxA = inData->GetScalarTypeMax(); } inC = inData->GetNumberOfScalarComponents(); outC = outData->GetNumberOfScalarComponents(); // Check the label map's extents labelMap->GetExtent(labelMapExtent); // Find the intersection of the labelmap's extents and the overlaid image's // extents. This is the region we need to be blending. labelMapExtent[0] = (labelMapExtent[0] < extent[0]) ? extent[0] : labelMapExtent[0]; labelMapExtent[1] = (labelMapExtent[1] > extent[1]) ? extent[1] : labelMapExtent[1]; labelMapExtent[2] = (labelMapExtent[2] < extent[2]) ? extent[2] : labelMapExtent[2]; labelMapExtent[3] = (labelMapExtent[3] > extent[3]) ? extent[3] : labelMapExtent[3]; labelMapExtent[4] = (labelMapExtent[4] < extent[4]) ? extent[4] : labelMapExtent[4]; labelMapExtent[5] = (labelMapExtent[5] > extent[5]) ? extent[5] : labelMapExtent[5]; vtkImageIterator< T > inIt( inData, labelMapExtent ); vtkImageIterator< T > outIt( outData, labelMapExtent ); vtkImageIterator< vtkKWEPaintbrushEnums::LabelType > labelMapIt( labelMap->GetLabelMap(), labelMapExtent ); // Loop through pixels while (!labelMapIt.IsAtEnd()) { vtkKWEPaintbrushEnums::LabelType *labelMapSI = labelMapIt.BeginSpan(); vtkKWEPaintbrushEnums::LabelType *labelMapSIEnd = labelMapIt.EndSpan(); T *inSI = inIt.BeginSpan(); T *outSI = outIt.BeginSpan(); while (labelMapSI != labelMapSIEnd) { // Fast retrieve from the lookup table to fetch the color for this label. color = labelToColorMapUC[*labelMapSI]; // Blend based on opacity opacity = labelToOpacityMapUC[*labelMapSI]; r = opacity; f = 1.0 - r; opacity = opacity/(maxA-minA); if (outC >= 3 && inC >= 4) { // RGB(A) blended with RGBA // multiply to get a number in the range [0,65280] // where 65280 = 255*256 = range of inSI[3] * range of o r = opacity*(static_cast(inSI[3])-minA); f = 1.0-r; outSI[0] = T(static_cast(outSI[0])*f + static_cast(inSI[0])*r); outSI[1] = T(static_cast(outSI[1])*f + static_cast(inSI[1])*r); outSI[2] = T(static_cast(outSI[2])*f + static_cast(inSI[2])*r); outSI += outC; inSI += inC; } else if (outC >= 3 && inC == 3) { // RGB(A) blended with RGB // the bit-shift achieves a division by 256 outSI[0] = T(static_cast(outSI[0])*f + static_cast(inSI[0])*r); outSI[1] = T(static_cast(outSI[1])*f + static_cast(inSI[1])*r); outSI[2] = T(static_cast(outSI[2])*f + static_cast(inSI[2])*r); outSI += outC; inSI += inC; } else if (inC == 2) { r = opacity*(static_cast(inSI[1])-minA); f = 1.0-r; *outSI = T(static_cast(*outSI)*f + static_cast(*inSI)*r); outSI += outC; inSI += 2; } else { // luminance(+alpha) blended with luminance // the bit-shift achieves a division by 256 *outSI = T(static_cast(*outSI)*f + static_cast(*inSI)*r); outSI += outC; inSI++; } ++labelMapSI; inSI += inC; outSI += outC; } labelMapIt.NextSpan(); inIt.NextSpan(); outIt.NextSpan(); } } //---------------------------------------------------------------------------- // This function simply does a copy (for the first input) //---------------------------------------------------------------------------- void vtkKWEPaintbrushBlendCopyData(vtkImageData *inData, vtkImageData *outData, int *ext) { int idxY, idxZ, maxY, maxZ; vtkIdType inIncX, inIncY, inIncZ; vtkIdType rowLength; unsigned char *inPtr, *inPtr1, *outPtr; inPtr = static_cast(inData->GetScalarPointerForExtent(ext)); // Get increments to march through inData inData->GetIncrements(inIncX, inIncY, inIncZ); // find the region to loop over rowLength = (ext[1] - ext[0]+1)*inIncX*inData->GetScalarSize(); maxY = ext[3] - ext[2]; maxZ = ext[5] - ext[4]; outPtr=static_cast(outData->GetScalarPointerForExtent(ext)); inData->GetIncrements(inIncX, inIncY, inIncZ); inIncY *= inData->GetScalarSize(); inIncZ *= inData->GetScalarSize(); // Loop through outData pixels for (idxZ = 0; idxZ <= maxZ; idxZ++) { inPtr1 = inPtr + idxZ*inIncZ; for (idxY = 0; idxY <= maxY; idxY++) { memcpy(outPtr,inPtr1,rowLength); inPtr1 += inIncY; outPtr += rowLength; } } } //---------------------------------------------------------------------------- // This method is passed a input and output regions, and executes the filter // algorithm to fill the output from the inputs. // It just executes a switch statement to call the correct function for // the regions data types. void vtkKWEPaintbrushBlend::ThreadedRequestData ( vtkInformation * vtkNotUsed( request ), vtkInformationVector** inputVector, vtkInformationVector * vtkNotUsed( outputVector ), vtkImageData ***inData, vtkImageData **outData, int outExt[6], int vtkNotUsed(id)) { void *inPtr; void *outPtr; // check if (inData[0][0]->GetNumberOfScalarComponents() > 4) { vtkErrorMacro("The first input can have a maximum of four components"); return; } vtkInformation *info = inputVector[1]->GetInformationObject(0); vtkKWEPaintbrushDrawing *drawing = vtkKWEPaintbrushDrawing::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); if (this->GetUseOverlay()) { // copy the first image directly to the output vtkKWEPaintbrushBlendCopyData(inData[0][0], outData[0], outExt); } // this filter expects that input is the same type as output. if (inData[0][0]->GetScalarType() != outData[0]->GetScalarType()) { vtkErrorMacro( << "Execute: input ScalarType (" << inData[0][0]->GetScalarType() << "), must match output ScalarType (" << outData[0]->GetScalarType() << ")" ); return; } inPtr = inData[0][0]->GetScalarPointerForExtent(outExt); outPtr = outData[0]->GetScalarPointerForExtent(outExt); if (drawing->GetRepresentation() == vtkKWEPaintbrushEnums::Binary) { // Loop over each stencil and blend it. for (int n = 0; n < drawing->GetNumberOfItems(); n++) { vtkKWEPaintbrushSketch *sketch = drawing->GetItem(n); vtkImageStencilData *stencil = (vtkKWEPaintbrushStencilData:: SafeDownCast(sketch->GetPaintbrushData()))->GetImageStencilData(); // The color of the blend. unsigned char color[3]; double colorD[3]; sketch->GetPaintbrushProperty()->GetColor(colorD); color[0] = static_cast< unsigned char >(colorD[0] * 255.0); color[1] = static_cast< unsigned char >(colorD[1] * 255.0); color[2] = static_cast< unsigned char >(colorD[2] * 255.0); double opacity = sketch->GetPaintbrushProperty()->GetOpacity(); // for performance reasons, use a special method for unsigned char if (inData[0][0]->GetScalarType() == VTK_UNSIGNED_CHAR) { vtkKWEPaintbrushBlendExecuteChar( stencil, this, outExt, inData[0][0], static_cast(inPtr), outData[0], static_cast(outPtr), opacity, color ); } else { switch (inData[0][0]->GetScalarType()) { vtkTemplateMacro( vtkKWEPaintbrushBlendExecute(stencil, this, outExt, inData[0][0], static_cast(inPtr), outData[0], static_cast(outPtr), opacity )); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } } } else if (drawing->GetRepresentation() == vtkKWEPaintbrushEnums::Label) { // the label map we need to blend onto our overlay image. vtkKWEPaintbrushLabelData *labelData = vtkKWEPaintbrushLabelData::SafeDownCast( drawing->GetPaintbrushData() ); vtkKWEPaintbrushPropertyManager *propertyManager = drawing->GetPaintbrushPropertyManager(); // for performance reasons, use a special method for unsigned char if (inData[0][0]->GetScalarType() == VTK_UNSIGNED_CHAR) { if (vtkKWEPaintbrushEnums::GetLabelType() == VTK_UNSIGNED_CHAR) { // Fast Lookup table of label to color map. VTKColorType *labelToColorMapUC = propertyManager->LabelToColorMapUC; double *labelToOpacityMapUC = propertyManager->LabelToOpacityMapUC; vtkKWEPaintbrushBlendExecuteCharLabelMapTypeUC( labelData, this, outExt, inData[0][0], static_cast(inPtr), outData[0], static_cast(outPtr), labelToColorMapUC, labelToOpacityMapUC ); } else { vtkKWEPaintbrushBlendExecuteChar( labelData, this, outExt, inData[0][0], static_cast(inPtr), outData[0], static_cast(outPtr), propertyManager->LabelToColorMap ); } } else { if (vtkKWEPaintbrushEnums::GetLabelType() == VTK_UNSIGNED_CHAR) { // Fast Lookup table of label to color map. VTKColorType *labelToColorMapUC = propertyManager->LabelToColorMapUC; double *labelToOpacityMapUC = propertyManager->LabelToOpacityMapUC; switch (inData[0][0]->GetScalarType()) { vtkTemplateMacro( vtkKWEPaintbrushBlendExecuteLabelMapTypeUC( labelData, this, outExt, inData[0][0], static_cast(inPtr), outData[0], static_cast(outPtr), labelToColorMapUC, labelToOpacityMapUC )); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } else { switch (inData[0][0]->GetScalarType()) { vtkTemplateMacro( vtkKWEPaintbrushBlendExecute( labelData, this, outExt, inData[0][0], static_cast(inPtr), outData[0], static_cast(outPtr), propertyManager->LabelToColorMap )); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } } // Endif LabelType is UCHAR or everything else } // Endif Drawing type (LabelMap or Stencil) } //---------------------------------------------------------------------------- int vtkKWEPaintbrushBlend::FillInputPortInformation(int port, vtkInformation* info) { if (port == 0) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkImageData"); return 1; } else if (port == 1) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkKWEPaintbrushDrawing"); return 1; } return 0; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushBlend::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Opacity: " << this->Opacity << endl; os << indent << "UseOverlay: " << this->UseOverlay << endl; } vtkedge-0.2.0~20110819/Widgets/vtkKWEBoundingBoxRepresentation2D.h0000644000175000017500000001762111363410610024244 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEBoundingBoxRepresentation2D // .SECTION Description #ifndef __vtkKWEBoundingBoxRepresentation2D_h #define __vtkKWEBoundingBoxRepresentation2D_h #include "VTKEdgeConfigure.h" // Needed for export symbols #include "vtkWidgetRepresentation.h" class vtkHandleRepresentation; class vtkCellArray; class vtkPoints; class vtkPolyData; class vtkPolyDataMapper; class vtkTextMapper; class vtkTextProperty; class vtkProperty; class vtkActor2D; class vtkActor; class vtkProperty2D; class vtkProperty; class vtkImageActorPointPlacer; class vtkImageActor; class vtkActor2DCollection; class vtkCollection; class vtkImageData; class VTKEdge_WIDGETS_EXPORT vtkKWEBoundingBoxRepresentation2D : public vtkWidgetRepresentation { public: // Description: // Instantiate the class. static vtkKWEBoundingBoxRepresentation2D *New(); // Description: // Standard VTK methods. vtkTypeRevisionMacro(vtkKWEBoundingBoxRepresentation2D,vtkWidgetRepresentation); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set the image actor on which this widget is placed. virtual void SetImageActor( vtkImageActor * ); vtkImageActor *GetImageActor(); // Description: // This method is used to specify the type of handle representation to use // for the four internal vtkHandleRepresentations within // vtkKWEBoundingBoxRepresentation2D. To use this method, create a dummy // vtkHandleRepresentation (or subclass), and then invoke this method with // this dummy. Then the vtkKWEBoundingBoxRepresentation2D uses this dummy to // clone four vtkHandleRepresentations of the same type. void SetHandleRepresentation(vtkHandleRepresentation *handle); vtkHandleRepresentation* GetHandleRepresentation( int handleIndex ); // Description: // Retrieve the property used to control the appearance of the two // orthogonal lines. vtkGetObjectMacro(LineProperty,vtkProperty); vtkGetObjectMacro(SelectedLineProperty,vtkProperty); virtual void SetSelectedHandleProperty( vtkProperty * ); virtual void SetHoveredHandleProperty( vtkProperty * ); virtual void SetHandleProperty( vtkProperty * ); // Description: // Get the 3D bounding-box as a polydata. vtkPolyData * GetPolyData(); // Description: // Set/Get the extents of the bbox. Returns 0 on failure. int GetExtent( int extents[6] ); void SetExtent( int extents[6] ); // Description: // These are methods that satisfy vtkWidgetRepresentation's API. virtual void BuildRepresentation(); virtual int ComputeInteractionState(int X, int Y, int modify=0); virtual void GetActors2D(vtkPropCollection *pc); virtual void GetActors(vtkPropCollection *pc); virtual void PlaceWidget(double bounds[6]); // Description: // Methods required by vtkProp superclass. virtual void ReleaseGraphicsResources(vtkWindow *w); virtual int RenderOverlay(vtkViewport *viewport); virtual int RenderOpaqueGeometry(vtkViewport *viewport); // Description: // INTERNAL. Do not use. // This is set from vtkKWEBoundingBoxWidget. vtkSetMacro(InteractionState,int); //BTX - manage the state of the widget enum _InteractionState { Outside = 0, Inside, RequestResizeBox, Resizing, BeginDefining, Defining, EndDefining }; //ETX // Description: // Specify the format to use for labelling the distance. Note that an empty // string results in no label, or a format string without a "%" character // will not print the distance value. vtkSetStringMacro(LabelFormat); vtkGetStringMacro(LabelFormat); // Description: // Set the image data on which the widget is placed. virtual void SetImageData( vtkImageData * ); vtkGetObjectMacro( ImageData, vtkImageData ); // Description: // Optionally an ID field may be displayed next to the box vtkSetMacro( ID, int ); vtkGetMacro( ID, int ); // Description: // Get the outline property. vtkProperty * GetOutlineProperty(); // Description: // Get the property of the text annotations vtkTextProperty * GetWidthTextProperty(); vtkTextProperty * GetHeightTextProperty(); vtkTextProperty * GetIDTextProperty(); // Description: // INTERNAL: Do not use.. Must be set by the widget alone. // This serves to fade the representation into the background. When on, // the representation will but also show up only with the rectangular // bounding box. The handles and the slice actors don't show up anymore. vtkSetMacro( Fade, int ); vtkGetMacro( Fade, int ); // Description: // INTERNAL: Do not use.. Must be set by the widget alone. vtkSetMacro( ShowSliceScaleBar, int ); // Description: // INTERNAL: Do not use vtkGetMacro( Unplaced, int ); protected: vtkKWEBoundingBoxRepresentation2D(); ~vtkKWEBoundingBoxRepresentation2D(); // Description: // On/Off the visibility of the widget. void SetVisibilityInternal( int ); void Translate( const double translation[3], const double cursorMotionVector[3] ); void PositionHandles(); // Highlight the nth handle. Called with an argument of "-1" will set the // property to all 4 handles. void SetHandleHighlight( int handleIdx, vtkProperty *property ); // Default place the widget according to the bounds of the image actor void PlaceWidget(); // User specified bounds to place the widget. int PlaceWidgetInternal(double bounds[6]); // Cut "PolyData" to produce "BoxPolyData". The cut will be done by using the // camera parameters. (using the focal point and the normal). // Returns 1 if "BoxPoints" is different from what it used to be. int Cut(); // Compute annotations, if needed.. such as text width, height etc.. int Annotate(); int AnnotateScaleBar(); vtkImageActorPointPlacer * PointPlacer; vtkPolyData * PolyData; // 8 Points vtkCollection * TextMappers; vtkActor2DCollection * TextActors; vtkPolyData * BoxPolyData; vtkPolyDataMapper * BoxMapper; vtkActor * BoxActor; vtkPoints * BoxPoints; // 4 Points, a "cut" of PolyData vtkProperty * HandleProperty; vtkProperty * SelectedHandleProperty; vtkProperty * HoveredHandleProperty; vtkProperty * LineProperty; vtkProperty * SelectedLineProperty; vtkHandleRepresentation * HandleRepresentation; vtkHandleRepresentation **HandleRepresentations; int CurrentHandleIdx; double MinimumThickness[3]; double PlaceFactor; double LastEventPosition[2]; char * LabelFormat; vtkActor * ScaleBarActor; vtkActor * ScaleBarActor2; vtkPolyData * ScaleBar; vtkPolyData * ScaleBar2; int ShowSliceScaleBar; int Unplaced; vtkImageData * ImageData; int Fade; int ID; private: vtkKWEBoundingBoxRepresentation2D(const vtkKWEBoundingBoxRepresentation2D&); //Not implemented void operator=(const vtkKWEBoundingBoxRepresentation2D&); //Not implemented int ComputeOrientation(); int XAxis, YAxis, ZAxis; double Point1DisplayPosition[2], Point2DisplayPosition[2]; }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushOperationFloodFill.cxx0000644000175000017500000000356211363410610025062 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushOperationFloodFill.h" #include "vtkKWEPaintbrushShape.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkKWEPaintbrushOperationFloodFill, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEPaintbrushOperationFloodFill); //---------------------------------------------------------------------- vtkKWEPaintbrushOperationFloodFill::vtkKWEPaintbrushOperationFloodFill() { } //---------------------------------------------------------------------- vtkKWEPaintbrushOperationFloodFill::~vtkKWEPaintbrushOperationFloodFill() { } //---------------------------------------------------------------------- void vtkKWEPaintbrushOperationFloodFill:: DoOperationOnStencil(vtkImageStencilData *stencilData, int x, int y, int z) { this->Superclass::DoOperationOnStencil( stencilData, x, y, z ); if (!this->ImageData) { return; } // Now do the floodfill on the image data } //---------------------------------------------------------------------- void vtkKWEPaintbrushOperationFloodFill::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushGrayscaleData.cxx0000644000175000017500000004632711363410610024041 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkMath.h" #include "vtkImageIterator.h" #include "vtkImageData.h" #include "vtkKWEPaintbrushUtilities.h" #include #ifndef max #define max(x,y) ((x>y) ? (x) : (y)) #endif #ifndef min #define min(x,y) ((xImageData = vtkImageData::New(); this->ImageData->SetScalarTypeToUnsignedChar(); this->Information->Set(vtkDataObject::DATA_EXTENT_TYPE(), VTK_3D_EXTENT); this->Information->Set(vtkDataObject::DATA_EXTENT(), this->ImageData->GetExtent(), 6); this->OutsideValue = 0.0; this->OutsideValueTolerance = 0.01; } //---------------------------------------------------------------------------- vtkKWEPaintbrushGrayscaleData::~vtkKWEPaintbrushGrayscaleData() { this->SetImageData(NULL); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushGrayscaleData::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "ImageData: " << this->ImageData << "\n"; if (this->ImageData) { this->ImageData->PrintSelf(os,indent.GetNextIndent()); } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushGrayscaleData::ShallowCopy(vtkDataObject *o) { vtkKWEPaintbrushGrayscaleData *s= vtkKWEPaintbrushGrayscaleData::SafeDownCast(o); if (s) { this->ImageData->ShallowCopy(s->GetImageData()); } vtkDataObject::ShallowCopy(o); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushGrayscaleData::DeepCopy(vtkDataObject *o) { vtkKWEPaintbrushGrayscaleData *s= vtkKWEPaintbrushGrayscaleData::SafeDownCast(o); if (s) { this->ImageData->DeepCopy(s->GetImageData()); } vtkDataObject::DeepCopy(o); } //---------------------------------------------------------------------------- // Returns 0 if nothing was added // Implements minkowski add and subtract operators (max and min) template< class T1, class T2 > int vtkKWEPaintbrushGrayscaleDataAdd( vtkKWEPaintbrushGrayscaleData * self, vtkImageData *s, T1, T2 ) { const double outsideValue = self->GetOutsideValue(); const double outsideValueTolerance = self->GetOutsideValueTolerance(); // Not using vtkImageMathematics there cause we want to use self as the // output and do a quick inplace add. int extent[6]; if (!vtkKWEPaintbrushUtilities::GetIntersectingExtents( self->GetImageData()->GetExtent(), s->GetExtent(), extent)) { return 0; } vtkImageIterator< T1 > it1(self->GetImageData(), extent); vtkImageIterator< T2 > it2(s, extent); while( !it2.IsAtEnd() ) { T1 *inSI = it1.BeginSpan(); T1 *inSIEnd = it1.EndSpan(); T2 *inSI2 = it2.BeginSpan(); while (inSI != inSIEnd) { if ((static_cast< double >(*inSI2) - outsideValue) > outsideValueTolerance) { *inSI = max(static_cast< T1 >(*inSI2), static_cast< T1 >(*inSI)); } ++inSI; ++inSI2; } it1.NextSpan(); it2.NextSpan(); } self->GetImageData()->Modified(); self->Modified(); return 1; } //---------------------------------------------------------------------------- // Returns 0 if nothing was added template< class T1, class T2 > int vtkKWEPaintbrushGrayscaleDataSubtract(vtkKWEPaintbrushGrayscaleData *self, vtkImageData *s, T1, T2 ) { const double outsideValue = self->GetOutsideValue(); const double outsideValueTolerance = self->GetOutsideValueTolerance(); // Not using vtkImageMathematics there cause we want to use self as the // output and do a quick inplace add. int extent[6]; if (!vtkKWEPaintbrushUtilities::GetIntersectingExtents( self->GetImageData()->GetExtent(), s->GetExtent(), extent)) { return 0; } vtkImageIterator< T1 > it1(self->GetImageData(), extent); vtkImageIterator< T2 > it2(s, extent); while( !it1.IsAtEnd() ) { T1 *inSI = it1.BeginSpan(); T1 *inSIEnd = it1.EndSpan(); T2 *inSI2 = it2.BeginSpan(); while (inSI != inSIEnd) { if ((static_cast< double >(*inSI2) - outsideValue) > outsideValueTolerance) { *inSI = min(static_cast< T1 >(*inSI2), static_cast< T1 >(*inSI)); } ++inSI; ++inSI2; } it1.NextSpan(); it2.NextSpan(); } self->GetImageData()->Modified(); self->Modified(); return 1; } //---------------------------------------------------------------------------- // Returns 0 if nothing was added template< class T1, class T2 > int vtkKWEPaintbrushGrayscaleDataReplace(vtkKWEPaintbrushGrayscaleData *self, vtkImageData *s, T1, T2 ) { const double outsideValue = self->GetOutsideValue(); const double outsideValueTolerance = self->GetOutsideValueTolerance(); // Not using vtkImageMathematics there cause we want to use self as the // output and do a quick inplace add. int extent[6]; if (!vtkKWEPaintbrushUtilities::GetIntersectingExtents( self->GetImageData()->GetExtent(), s->GetExtent(), extent)) { return 0; } vtkImageIterator< T1 > it1(self->GetImageData(), extent); vtkImageIterator< T2 > it2(s, extent); while( !it1.IsAtEnd() ) { T1 *inSI = it1.BeginSpan(); T1 *inSIEnd = it1.EndSpan(); T2 *inSI2 = it2.BeginSpan(); while (inSI != inSIEnd) { if ((static_cast< double >(*inSI2) - outsideValue) > outsideValueTolerance) { *inSI = static_cast< T1 >(*inSI2); } ++inSI; ++inSI2; } it1.NextSpan(); it2.NextSpan(); } self->GetImageData()->Modified(); self->Modified(); return 1; } //---------------------------------------------------------------------------- template< class T1 > int vtkKWEPaintbrushGrayscaleDataOper(vtkKWEPaintbrushGrayscaleData *self, vtkImageData *s, T1, int oper) { int ret = 0; if (oper == 0) // add { switch (s->GetScalarType()) { vtkTemplateMacro( ret=vtkKWEPaintbrushGrayscaleDataAdd(self,s, static_cast(0), static_cast< VTK_TT >(0) )); } } else if (oper == 1) // subtract { switch (s->GetScalarType()) { vtkTemplateMacro( ret=vtkKWEPaintbrushGrayscaleDataSubtract(self,s, static_cast(0), static_cast< VTK_TT >(0) )); } } else if (oper == 2) // replace { switch (s->GetScalarType()) { vtkTemplateMacro( ret=vtkKWEPaintbrushGrayscaleDataReplace(self,s, static_cast(0), static_cast< VTK_TT >(0) )); } } return ret; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushGrayscaleData::Add(vtkImageData *s, bool vtkNotUsed(forceMutable)) { int ret = 0; switch(this->ImageData->GetScalarType()) { vtkTemplateMacro( ret = vtkKWEPaintbrushGrayscaleDataOper(this,s, static_cast(0), 0 )); default: { vtkErrorMacro(<< "vtkKWEPaintbrushGrayscaleData: Unknown ScalarType"); return 0; } } return ret; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushGrayscaleData::Subtract(vtkImageData *s, bool vtkNotUsed(forceMutable)) { int ret = 0; switch(this->ImageData->GetScalarType()) { vtkTemplateMacro( ret = vtkKWEPaintbrushGrayscaleDataOper( this, s, static_cast< VTK_TT >(0), 1 )); default: { vtkErrorMacro(<< "vtkKWEPaintbrushGrayscaleData: Unknown ScalarType"); return 0; } } return ret; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushGrayscaleData::Replace(vtkImageData *s, bool vtkNotUsed(forceMutable)) { int ret = 0; switch(this->ImageData->GetScalarType()) { vtkTemplateMacro( ret = vtkKWEPaintbrushGrayscaleDataOper( this, s, static_cast< VTK_TT >(0), 2 )); default: { vtkErrorMacro(<< "vtkKWEPaintbrushGrayscaleData: Unknown ScalarType"); return 0; } } return ret; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushGrayscaleData::Add(vtkKWEPaintbrushData *d, bool forceMutable) { vtkKWEPaintbrushGrayscaleData *s= vtkKWEPaintbrushGrayscaleData::SafeDownCast(d); if (s) { return this->Add(s->GetImageData(), forceMutable); } return 0; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushGrayscaleData::Subtract(vtkKWEPaintbrushData *d, bool forceMutable) { vtkKWEPaintbrushGrayscaleData *s= vtkKWEPaintbrushGrayscaleData::SafeDownCast(d); if (s) { return this->Subtract(s->GetImageData(), forceMutable); } return 0; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushGrayscaleData::Replace(vtkKWEPaintbrushData *d, bool forceMutable) { vtkKWEPaintbrushGrayscaleData *s= vtkKWEPaintbrushGrayscaleData::SafeDownCast(d); if (s) { return this->Replace(s->GetImageData(), forceMutable); } return 0; } //---------------------------------------------------------------------------- template< class T > void vtkKWEPaintbrushGrayscaleDataFillBufferInside( vtkImageData *image, T fillValue ) { vtkImageIterator< T > it(image, image->GetExtent()); while( !it.IsAtEnd() ) { T *inSI = it.BeginSpan(); T *inSIEnd = it.EndSpan(); while (inSI != inSIEnd) { *inSI = static_cast< T >(fillValue); ++inSI; } it.NextSpan(); } } //---------------------------------------------------------------------------- template< class T > void vtkKWEPaintbrushGrayscaleDataFillBufferOutside( vtkImageData *image, int extent[6], T fillValue ) { int imageExtent[6]; image->GetExtent(imageExtent); int y = imageExtent[2], z = imageExtent[4], e[6]; e[0] = (extent[0] < imageExtent[0] ? imageExtent[0] : extent[0]); e[1] = (extent[1] > imageExtent[1] ? imageExtent[1] : extent[1]); e[2] = (extent[2] < imageExtent[2] ? imageExtent[2] : extent[2]); e[3] = (extent[3] > imageExtent[3] ? imageExtent[3] : extent[3]); e[4] = (extent[4] < imageExtent[4] ? imageExtent[4] : extent[4]); e[5] = (extent[5] > imageExtent[5] ? imageExtent[5] : extent[5]); // Handle 4 cases with extent clippers // // Image ------------------- // ClipExtent Case 0 ------- // ClipExtent Case 1 ------------ // ClipExtent Case 2 -------------- // ClipExtent Case 3 --------------------------- int type = (extent[0] <= imageExtent[0]) ? 0x01 : 0x00; type |= (extent[1] >= imageExtent[1]) ? 0x10 : 0x00; int incr0 = 0; int incr1 = 0; switch (type) { case 0: incr0 = extent[0] - imageExtent[0] + 1; incr1 = imageExtent[1] - extent[0]; break; case 1: incr0 = extent[1] - imageExtent[0] + 1; break; case 2: incr0 = extent[0] - imageExtent[0]; break; } vtkImageIterator< T > it(image, e); while( !it.IsAtEnd() ) { T *inSI = it.BeginSpan(); T *inSIEnd = it.EndSpan(); if (z < extent[4] || z > extent[5] || y < extent[2] || y > extent[3]) { while (inSI != inSIEnd) { *inSI = static_cast< T >(fillValue); ++inSI; } } else if (type == 0) { T* inSIEnd0 = inSI + incr0; T* inSIBegin1 = inSI + incr1; while (inSI != inSIEnd0) { *inSI = static_cast< T >(fillValue); ++inSI; } while (inSIBegin1 != inSIEnd) { *inSIBegin1 = static_cast< T >(fillValue); ++inSIBegin1; } } else if (type == 1) { inSI += incr0; while (inSI != inSIEnd) { *inSI = static_cast< T >(fillValue); ++inSI; } } else if (type == 2) { inSIEnd = inSI + incr0; while (inSI != inSIEnd) { *inSI = static_cast< T >(fillValue); ++inSI; } } it.NextSpan(); if (y == extent[3]) { ++z; y = extent[2]; } else { ++y; } } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushGrayscaleData::Allocate(double fillValue) { this->ImageData->AllocateScalars(); switch(this->ImageData->GetScalarType()) { vtkTemplateMacro( vtkKWEPaintbrushGrayscaleDataFillBufferInside(this->ImageData, static_cast< VTK_TT >(fillValue) )); } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushGrayscaleData::SetSpacing( double s[3] ) { this->ImageData->SetSpacing(s); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushGrayscaleData::SetOrigin( double s[3] ) { this->ImageData->SetOrigin(s); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushGrayscaleData::SetExtent( int extent[6] ) { this->ImageData->SetExtent(extent); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushGrayscaleData::GetExtent( int extent[6] ) { this->ImageData->GetExtent(extent); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushGrayscaleData::Clip( int extent[6] ) { // This will not re-allocate extents. In other words, this is not a means // of saving memory. It will simply set to 0, any values in the image // outside the extents. int intersectingExtent[6], currentExtent[6]; this->ImageData->GetExtent( currentExtent ); if (vtkMath::ExtentIsWithinOtherExtent( currentExtent, extent )) { return 0; } if (!vtkKWEPaintbrushUtilities::GetIntersectingExtents( currentExtent, extent, intersectingExtent )) { // Nothing is inside.. blank image.. switch (this->ImageData->GetScalarType()) { vtkTemplateMacro( vtkKWEPaintbrushGrayscaleDataFillBufferInside( this->ImageData, static_cast< VTK_TT >(this->OutsideValue) )); } } else { // Nothing is inside.. blank image.. switch (this->ImageData->GetScalarType()) { vtkTemplateMacro( vtkKWEPaintbrushGrayscaleDataFillBufferOutside( this->ImageData, extent, static_cast< VTK_TT >(this->OutsideValue))); } } return 1; } //---------------------------------------------------------------------------- template < class T > void vtkKWEPaintbrushGrayscaleDataGetValue( int coords[3], double &value, vtkImageData *image, T ) { value = static_cast( *(static_cast(image->GetScalarPointer(coords)))); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushGrayscaleData::IsInside( double p[3] ) { // Check if point "p" (p is in world coordinates) is inside the painting. double pcoords[3]; double value = 0; int ijk[3]; if (this->ImageData->ComputeStructuredCoordinates( p, ijk, pcoords )) { switch (this->ImageData->GetScalarType()) { vtkTemplateMacro( vtkKWEPaintbrushGrayscaleDataGetValue( ijk, value, this->ImageData, static_cast(0) )); } return (fabs(value - this->OutsideValue) < this->OutsideValueTolerance ? 0 : 1); } return 0; } //---------------------------------------------------------------------------- unsigned long vtkKWEPaintbrushGrayscaleData::GetMTime() { unsigned long t = this->ImageData->GetMTime(); unsigned long mtime = vtkObject::GetMTime(); return (mtime > t ? mtime : t); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushGrayscaleData::GetPaintbrushDataAsImageData( vtkImageData *image) { image->ShallowCopy(this->ImageData); } //---------------------------------------------------------------------------- template< class T > void vtkKWEPaintbrushGrayscaleDataResize( vtkImageData *imageResized, vtkImageData *imageOld, int oldExtent[6], T ) { vtkImageIterator< T > it1(imageResized, oldExtent); vtkImageIterator< T > it2(imageOld, oldExtent); while( !it2.IsAtEnd() ) { T *inSI = it1.BeginSpan(); T *inSIEnd = it1.EndSpan(); T *inSI2 = it2.BeginSpan(); while (inSI != inSIEnd) { *inSI = *inSI2; ++inSI; ++inSI2; } it1.NextSpan(); it2.NextSpan(); } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushGrayscaleData::Resize(int extent[6], double f) { int oldExtent[6]; this->ImageData->GetExtent(oldExtent); if (oldExtent[1] < oldExtent[0]) { // We haven't been allocated yet. Just allocate and return. this->SetExtent(extent); this->Allocate(f); return; } if (oldExtent[0] != extent[0] || oldExtent[1] != extent[1] || oldExtent[2] != extent[2] || oldExtent[3] != extent[3] || oldExtent[4] != extent[4] || oldExtent[5] != extent[5]) { vtkImageData * oldData = vtkImageData::New(); oldData->DeepCopy(this->ImageData); this->SetExtent(extent); this->Allocate(f); switch (this->ImageData->GetScalarType()) { vtkTemplateMacro( vtkKWEPaintbrushGrayscaleDataResize( this->ImageData, oldData, extent, static_cast(0) )); } oldData->Delete(); } this->ImageData->Modified(); this->Modified(); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushHighlightActors.cxx0000644000175000017500000002305611363410610024412 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushHighlightActors.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEStencilContourFilter.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkObjectFactory.h" #include "vtkProperty.h" #include "vtkActorCollection.h" #include "vtkMapperCollection.h" #include "vtkImageStencilData.h" vtkCxxRevisionMacro(vtkKWEPaintbrushHighlightActors, "$Revision: 1774 $"); vtkCxxSetObjectMacro(vtkKWEPaintbrushHighlightActors, PaintbrushDrawing, vtkKWEPaintbrushDrawing); //---------------------------------------------------------------------------- // We've hidden the New() method from users by making it protected. So we've // got to provide the implementation ourself instead of using // vtkStandardNewMacro. vtkKWEPaintbrushHighlightActors* vtkKWEPaintbrushHighlightActors::New() { if (vtkObject* ret = vtkObjectFactory::CreateInstance("vtkKWEPaintbrushHighlightActors")) { return static_cast(ret); } return new vtkKWEPaintbrushHighlightActors; } //---------------------------------------------------------------------- vtkKWEPaintbrushHighlightActors::vtkKWEPaintbrushHighlightActors() { this->ContourFilters = vtkCollection::New(); this->ContourPolyDataMappers = vtkMapperCollection::New(); this->ContourPolyDataActors = vtkActorCollection::New(); this->PaintbrushDrawing = NULL; this->Extent[0] = this->Extent[2] = this->Extent[4] = 0; this->Extent[1] = this->Extent[3] = this->Extent[5] = -1; } //---------------------------------------------------------------------- vtkKWEPaintbrushHighlightActors::~vtkKWEPaintbrushHighlightActors() { this->ContourFilters->Delete(); this->ContourPolyDataMappers->Delete(); this->ContourPolyDataActors->Delete(); this->SetPaintbrushDrawing(NULL); } //---------------------------------------------------------------------- void vtkKWEPaintbrushHighlightActors::BuildRepresentation() { // The pipeline is as follows : // // SketchImage_0 --> StencilContourFilter_0 --> PolyDataMapper_0 --> Actor_0 // // SketchImage_1 --> StencilContourFilter_1 --> PolyDataMapper_1 --> Actor_1 // .... // .... vtkKWEStencilContourFilter * cf; vtkCollectionSimpleIterator ait; const int nSketches = this->PaintbrushDrawing->GetNumberOfItems(); // Create new actors for newly highlighted sketches. for (int i = 0; i < nSketches; i++) { vtkKWEPaintbrushSketch * sketch = this->PaintbrushDrawing->GetItem(i); // If the sketch isn't highlighted, don't even bother. if (sketch->GetPaintbrushProperty()->GetHighlight() == 0) { continue; } if (vtkKWEPaintbrushStencilData *mask = vtkKWEPaintbrushStencilData:: SafeDownCast(sketch->GetPaintbrushData())) { vtkImageStencilData * stencil = mask->GetImageStencilData(); bool found = false; for ( this->ContourFilters->InitTraversal(ait); (cf=static_cast< vtkKWEStencilContourFilter * >( this->ContourFilters->GetNextItemAsObject(ait))); ) { if (static_cast< vtkImageStencilData * >(cf->GetInput()) == stencil) { found = true; break; } } if (!found) { vtkKWEStencilContourFilter * contourFilter = vtkKWEStencilContourFilter::New(); vtkPolyDataMapper * mapper = vtkPolyDataMapper::New(); vtkActor * actor = vtkActor::New(); contourFilter->SetInput(stencil); contourFilter->SetExtent(this->Extent); contourFilter->Update(); mapper->SetInput(contourFilter->GetOutput()); mapper->SetResolveCoincidentTopologyToPolygonOffset(); mapper->ScalarVisibilityOff(); actor->SetMapper(mapper); actor->SetProperty( sketch->GetPaintbrushProperty()->GetProperty() ); this->ContourPolyDataActors->AddItem(actor); this->ContourPolyDataMappers->AddItem(mapper); this->ContourFilters->AddItem(contourFilter); contourFilter->Delete(); mapper->Delete(); actor->Delete(); } } } // Now remove actors that correspond to sketches that have been removed or // unhighlighted. std::vector< int > indicesToRemove; int j = 0; for ( this->ContourFilters->InitTraversal(ait); (cf=static_cast< vtkKWEStencilContourFilter * >( this->ContourFilters->GetNextItemAsObject(ait))); j++) { bool found = false; for (int i = 0; i < nSketches; i++) { vtkKWEPaintbrushSketch * sketch = this->PaintbrushDrawing->GetItem(i); if (sketch->GetPaintbrushProperty()->GetHighlight()) { if (vtkKWEPaintbrushStencilData *mask = vtkKWEPaintbrushStencilData:: SafeDownCast(sketch->GetPaintbrushData())) { if (static_cast< vtkImageStencilData * >(cf->GetInput()) == mask->GetImageStencilData()) { found = true; break; } } } } if (!found) { indicesToRemove.push_back(j); } } for (std::vector< int >::const_iterator it = indicesToRemove.begin(); it != indicesToRemove.end(); ++it) { int indexToRemove = *it; // We need to get rid of this actor and its associated pipeline this->ContourPolyDataActors->RemoveItem( indexToRemove ); this->ContourPolyDataMappers->RemoveItem( indexToRemove ); this->ContourFilters->RemoveItem( indexToRemove ); } for ( this->ContourFilters->InitTraversal(ait); (cf=static_cast< vtkKWEStencilContourFilter * >( this->ContourFilters->GetNextItemAsObject(ait))); ) { cf->SetExtent( this->Extent ); cf->Update(); } } //---------------------------------------------------------------------- int vtkKWEPaintbrushHighlightActors::RenderOpaqueGeometry(vtkViewport *viewport) { this->BuildRepresentation(); int count = 0; vtkActor *ac; vtkCollectionSimpleIterator ait; for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { count += ac->RenderOpaqueGeometry(viewport); } return count; } #if VTKEdge_VTK_VERSION_DATE > 20070305 //---------------------------------------------------------------------- int vtkKWEPaintbrushHighlightActors ::RenderTranslucentPolygonalGeometry(vtkViewport *viewport) { int count = 0; vtkActor *ac; vtkCollectionSimpleIterator ait; for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { count += ac->RenderTranslucentPolygonalGeometry(viewport); } return count; } //---------------------------------------------------------------------- int vtkKWEPaintbrushHighlightActors::HasTranslucentPolygonalGeometry() { int result = 0; vtkActor *ac; vtkCollectionSimpleIterator ait; for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { result |= ac->HasTranslucentPolygonalGeometry(); } return result; } #else //---------------------------------------------------------------------- // Legacy method to support VTK source versions prior to 2007/03/05 int vtkKWEPaintbrushHighlightActors:: RenderTranslucentGeometry(vtkViewport *viewport) { int count = 0; vtkActor *ac; vtkCollectionSimpleIterator ait; for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { count += ac->RenderTranslucentGeometry(viewport); } return count; } #endif //---------------------------------------------------------------------- void vtkKWEPaintbrushHighlightActors::GetActors( vtkPropCollection * pc ) { vtkActor *ac; vtkCollectionSimpleIterator ait; for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { ac->GetActors(pc); } } //---------------------------------------------------------------------- double* vtkKWEPaintbrushHighlightActors::GetBounds() { double bounds[6]; vtkActor *ac; vtkCollectionSimpleIterator ait; for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { ac->GetBounds(bounds); for (int i=0; i<3; i++) { this->Bounds[2*i+1] = (bounds[2*i+1]>this->Bounds[2*i+1]) ? (bounds[2*i+1]):(this->Bounds[2*i+1]); this->Bounds[2*i] = (bounds[2*i]Bounds[2*i]) ? (bounds[2*i]):(this->Bounds[2*i]); } } return this->Bounds; } //---------------------------------------------------------------------- void vtkKWEPaintbrushHighlightActors::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEITKConfidenceConnectedPaintbrushOperation.h0000644000175000017500000000433311363410610027062 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEITKConfidenceConnectedPaintbrushOperation - // .SECTION Description // This is an abstract base class. // .SECTION See Also #ifndef __vtkKWEITKConfidenceConnectedPaintbrushOperation_h #define __vtkKWEITKConfidenceConnectedPaintbrushOperation_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkKWEITKPaintbrushOperation.h" class vtkImageStencilData; class VTKEdge_WIDGETS_EXPORT vtkKWEITKConfidenceConnectedPaintbrushOperation : public vtkKWEITKPaintbrushOperation { public: // Description: // Instantiate this class. static vtkKWEITKConfidenceConnectedPaintbrushOperation *New(); // Description: // Standard methods for instances of this class. vtkTypeRevisionMacro(vtkKWEITKConfidenceConnectedPaintbrushOperation, vtkKWEITKPaintbrushOperation); void PrintSelf(ostream& os, vtkIndent indent); protected: vtkKWEITKConfidenceConnectedPaintbrushOperation(); ~vtkKWEITKConfidenceConnectedPaintbrushOperation(); // Description: // See superclass Doc virtual void DoOperationOnStencil(vtkImageStencilData *, double p[3]); virtual void DoOperation( vtkKWEPaintbrushData *, double p[3], vtkKWEPaintbrushEnums::OperationType & op ); private: vtkKWEITKConfidenceConnectedPaintbrushOperation( const vtkKWEITKConfidenceConnectedPaintbrushOperation&); //Not implemented void operator=(const vtkKWEITKConfidenceConnectedPaintbrushOperation&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEITKConnectedThresholdImageFilter.h0000644000175000017500000000401511363410610025146 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef _vtkKWEITKConnectedThresholdFilterModule_h #define _vtkKWEITKConnectedThresholdFilterModule_h #include "itkConnectedThresholdImageFilter.h" #include "vtkKWEITKImageToStencilFilter.h" #include namespace vtkitk { template class vtkKWEITKConnectedThresholdImageFilter : public vtkKWEITKImageToStencilFilter { public: typedef vtkKWEITKConnectedThresholdImageFilter Self; typedef vtkKWEITKImageToStencilFilter Superclass; typedef itk::SmartPointer< Self > Pointer; typedef itk::SmartPointer< const Self > ConstPointer; itkTypeMacro(vtkKWEITKConnectedThresholdImageFilter, vtkKWEITKImageToStencilFilter); itkNewMacro(Self); typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef typename InputImageType::IndexType IndexType; typedef itk::ConnectedThresholdImageFilter< InputImageType, OutputImageType > FilterType; virtual void AddSeed( int seed[3] ); // No MTime checks etc.. will update every time.. virtual void Update(); protected: vtkKWEITKConnectedThresholdImageFilter(); ~vtkKWEITKConnectedThresholdImageFilter(); }; } // end namespace vtkitk #ifndef ITK_MANUAL_INSTANTIATION #include "vtkKWEITKConnectedThresholdImageFilter.txx" #endif #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushPropertyManager.cxx0000644000175000017500000002401211521051333024436 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushPropertyManager.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushData.h" #include "vtkProperty.h" #include "vtkObjectFactory.h" //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkKWEPaintbrushPropertyManager, "$Revision: 3416 $"); //---------------------------------------------------------------------------- vtkKWEPaintbrushPropertyManager* vtkKWEPaintbrushPropertyManager::New() { return vtkKWEPaintbrushPropertyManager::New(NULL); } //---------------------------------------------------------------------------- // Implement the standard form of the New() method. vtkKWEPaintbrushPropertyManager* vtkKWEPaintbrushPropertyManager::New(vtkKWEPaintbrushDrawing * s) { vtkObject* ret = vtkObjectFactory::CreateInstance("vtkKWEPaintbrushPropertyManager"); if(ret) { static_cast(ret)->PaintbrushDrawing = s; return static_cast(ret); } vtkKWEPaintbrushPropertyManager * p = new vtkKWEPaintbrushPropertyManager; p->PaintbrushDrawing = s; return p; } //---------------------------------------------------------------------------- vtkKWEPaintbrushPropertyManager::vtkKWEPaintbrushPropertyManager() { this->PaintbrushDrawing = NULL; this->HighlightType = vtkKWEPaintbrushProperty::ColorHighlight; this->Colors[ ColorType( 1.0, 0.4, 0.4, 0 )] = 0; this->Colors[ ColorType( 0.4, 1.0, 0.4, 1 )] = 0; this->Colors[ ColorType( 0.4, 0.4, 1.0, 2 )] = 0; this->Colors[ ColorType( 1.0, 0.0, 0.4, 3 )] = 0; this->Colors[ ColorType( 1.0, 0.4, 1.0, 4 )] = 0; this->Colors[ ColorType( 0.4, 1.0, 1.0, 5 )] = 0; this->Colors[ ColorType( 1.0, 0.2, 0.5, 6 )] = 0; this->Colors[ ColorType( 0.3, 0.7, 0.0, 7 )] = 0; this->Colors[ ColorType( 0.5, 0.2, 1.0, 8 )] = 0; this->Colors[ ColorType( 1.0, 0.5, 0.0, 9 )] = 0; this->Colors[ ColorType( 0.0, 1.0, 0.0, 10 )] = 0; this->Colors[ ColorType( 0.0, 0.0, 1.0, 11 )] = 0; this->Colors[ ColorType( 1.0, 0.2, 0.8, 12 )] = 0; this->Colors[ ColorType( 0.2, 1.0, 0.8, 13 )] = 0; this->Colors[ ColorType( 0.2, 0.4, 0.8, 14 )] = 0; this->Colors[ ColorType( 0.9, 0.5, 0.2, 15 )] = 0; this->Colors[ ColorType( 0.4, 0.9, 0.2, 16 )] = 0; this->Colors[ ColorType( 0.5, 0.2, 0.9, 17 )] = 0; this->Colors[ ColorType( 0.7, 0.3, 0.9, 18 )] = 0; this->Colors[ ColorType( 0.9, 0.3, 0.5, 19 )] = 0; this->Colors[ ColorType( 0.3, 0.9, 1.0, 20 )] = 0; // Clear our fast lookup label map to color table. Clearly we need to do this // only if we are using a UCHAR label map, since that's the only case when // fast lookup is exercised. if (vtkKWEPaintbrushEnums::GetLabelType() == VTK_UNSIGNED_CHAR) { for (int i = 0; i < 256; i++) { for (int j = 0; j < 3; j++) { this->LabelToColorMapUC[i][j] = 0; } this->LabelToOpacityMapUC[i] = 1.0; } } } //---------------------------------------------------------------------------- vtkKWEPaintbrushPropertyManager::~vtkKWEPaintbrushPropertyManager() { } //---------------------------------------------------------------------------- void vtkKWEPaintbrushPropertyManager::Initialize() { for( ColorsMapType::iterator iter = Colors.begin(); iter != Colors.end(); ++iter ) iter->second = 0; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushPropertyManager::AddUsedColor( vtkProperty * p ) { double rgb[3]; p->GetColor( rgb ); ColorType c( rgb[0], rgb[1], rgb[2] ); AddUsedColor(c); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushPropertyManager::AddUsedColor( const ColorType &c ) { if (c.R > 0.0 || c.G > 0.0 || c.B > 0.0) { for( ColorsMapType::iterator iter = Colors.begin(); iter != Colors.end(); ++iter ) { if (iter->first == c) ++iter->second; } } } //---------------------------------------------------------------------------- vtkKWEPaintbrushPropertyManager::ColorType vtkKWEPaintbrushPropertyManager::RequestColor() { unsigned int minVal = VTK_INT_MAX; ColorType c(0.0,0.0,0.0,0); for( ColorsMapType::iterator iter = Colors.begin(); iter != Colors.end(); ++iter ) { if (iter->second < minVal) { c = iter->first; minVal = iter->second; } } ++Colors[c]; return c; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushPropertyManager:: RetrieveSketchColor( vtkKWEPaintbrushSketch *s, unsigned char c[3] ) { ColorType color = SketchToColorMap[s]; c[0] = static_cast< unsigned char >(color.R * 255.0); c[1] = static_cast< unsigned char >(color.G * 255.0); c[2] = static_cast< unsigned char >(color.B * 255.0); } //---------------------------------------------------------------------------- vtkKWEPaintbrushProperty * vtkKWEPaintbrushPropertyManager:: RequestColorForSketch( vtkKWEPaintbrushSketch *s ) { // If the user overrode with his own fancy color, let's not displease // him by assigning our own. if (!s->GetPaintbrushProperty()->HasUserSpecifiedColorOverride()) { // Give this sketch a nice color and put it in our table. this->SketchToColorMap[s] = ColorType( 1.0, 0.4, 0.4, 0 ); this->SketchToColorMap[s] = RequestColor(); double rgb[3] = { this->SketchToColorMap[s].R, this->SketchToColorMap[s].G, this->SketchToColorMap[s].B }; s->GetPaintbrushProperty()->SetColorInternal( rgb ); } return s->GetPaintbrushProperty(); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushPropertyManager::Update() { // Remove unused sketches from our map. for( SketchToColorMapType::iterator iter = this->SketchToColorMap.begin(); iter != this->SketchToColorMap.end(); ) { SketchToColorMapType::iterator iter2 = iter; ++iter; if (this->PaintbrushDrawing->IsItemPresent(iter2->first) == 0) { // Remove this sketch from our color map. It no-longer exists. // Maybe someone deleted it. --(this->Colors[iter2->second]); this->SketchToColorMap.erase(iter2); } } // Now create new colors for the sketches that aren't in the map. These // are most likely new sketches. Try to assign unique colors. If unique // isn't possible, at least assign the least used colors. for (int n = 0; n < this->PaintbrushDrawing->GetNumberOfItems(); n++) { vtkKWEPaintbrushSketch * s = this->PaintbrushDrawing->GetItem(n); if (this->SketchToColorMap.find(s) == this->SketchToColorMap.end()) { // This sketch isn't in our table. Put it in the table and give it a // nice color. this->RequestColorForSketch(s); } // Propagate our Highlight type to all properties in the drawing. s->GetPaintbrushProperty()->SetHighlightType(this->HighlightType); } this->UpdateLabelToColorMap(); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushPropertyManager::UpdateLabelToColorMap() { if (this->PaintbrushDrawing->GetRepresentation() == vtkKWEPaintbrushEnums::Label) { if (vtkKWEPaintbrushEnums::GetLabelType() == VTK_UNSIGNED_CHAR) { for (int n = 0; n < this->PaintbrushDrawing->GetNumberOfItems(); n++) { vtkKWEPaintbrushSketch * s = this->PaintbrushDrawing->GetItem(n); s->GetPaintbrushProperty()->GetColor( this->LabelToColorMapUC[s->GetLabel()]); this->LabelToOpacityMapUC[s->GetLabel()] = s->GetPaintbrushProperty()->GetVisibility() ? s->GetPaintbrushProperty()->GetOpacity() : 0.0; } } else { unsigned char rgb[3]; this->LabelToColorMap.clear(); for (int n = 0; n < this->PaintbrushDrawing->GetNumberOfItems(); n++) { vtkKWEPaintbrushSketch * s = this->PaintbrushDrawing->GetItem(n); s->GetPaintbrushProperty()->GetColor(rgb); double opacity = s->GetPaintbrushProperty()->GetVisibility() ? s->GetPaintbrushProperty()->GetOpacity() : 0.0; this->LabelToColorMap[s->GetLabel()] = vtkKWEPaintbrushLabelMapColor(rgb, opacity); } } } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushPropertyManager ::GrabFocus( vtkKWEPaintbrushSketch *sketch ) { const int nSketches = this->PaintbrushDrawing->GetNumberOfItems(); for (int n = 0; n < nSketches; n++) { vtkKWEPaintbrushSketch * s = this->PaintbrushDrawing->GetItem(n); s->GetPaintbrushProperty()->SetInteractionEnabled(s == sketch); } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushPropertyManager::ReleaseFocus() { const int nSketches = this->PaintbrushDrawing->GetNumberOfItems(); for (int n = 0; n < nSketches; n++) { vtkKWEPaintbrushSketch * s = this->PaintbrushDrawing->GetItem(n); s->GetPaintbrushProperty()->SetInteractionEnabled(1); } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushPropertyManager::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushLabelData.cxx0000644000175000017500000011150711567177014023155 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushEnums.h" #include "vtkImageStencilData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkDemandDrivenPipeline.h" #include "vtkPointData.h" #include "vtkDataArray.h" #include "vtkObjectFactory.h" #include "vtkMath.h" #include "vtkImageShiftScale.h" #include "vtkImageCast.h" #include #include vtkCxxRevisionMacro(vtkKWEPaintbrushLabelData, "$Revision: 3550 $"); vtkStandardNewMacro(vtkKWEPaintbrushLabelData); //---------------------------------------------------------------------------- vtkKWEPaintbrushEnums::LabelType vtkKWEPaintbrushLabelData::NoLabelValue = 0; //---------------------------------------------------------------------------- vtkKWEPaintbrushLabelData::vtkKWEPaintbrushLabelData() { this->LabelMap = vtkImageData::New(); this->LabelMap->SetScalarType( vtkKWEPaintbrushEnums::GetLabelType() ); this->Information->Set( vtkDataObject::DATA_EXTENT_TYPE(), VTK_3D_EXTENT ); this->Information->Set( vtkDataObject::DATA_EXTENT(), this->LabelMap->GetExtent(), 6); } //---------------------------------------------------------------------------- vtkKWEPaintbrushLabelData::~vtkKWEPaintbrushLabelData() { if (this->LabelMap) { this->LabelMap->Delete(); this->LabelMap = NULL; } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::Initialize() { this->LabelMap->Initialize(); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::CopyInformationToPipeline(vtkInformation* request, vtkInformation* input, vtkInformation* output, int forceCopy) { this->LabelMap->CopyInformationToPipeline( request, input, output, forceCopy ); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::CopyInformationFromPipeline(vtkInformation* request) { this->LabelMap->CopyInformationFromPipeline(request); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::CopyOriginAndSpacingFromPipeline() { // Copy origin and spacing from pipeline information to the internal copies vtkInformation* info = this->PipelineInformation; if(info->Has(SPACING())) { this->SetSpacing(info->Get(SPACING())); } if(info->Has(ORIGIN())) { this->SetOrigin(info->Get(ORIGIN())); } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::SetExtent(int* extent) { this->LabelMap->SetExtent(extent); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::SetExtent(int x1, int x2, int y1, int y2, int z1, int z2) { int ext[6]; ext[0] = x1; ext[1] = x2; ext[2] = y1; ext[3] = y2; ext[4] = z1; ext[5] = z2; this->LabelMap->SetExtent(ext); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::GetExtent(int e[6]) { this->LabelMap->GetExtent(e); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::ShallowCopy(vtkDataObject *o) { vtkKWEPaintbrushLabelData *s = vtkKWEPaintbrushLabelData::SafeDownCast(o); if (s) { this->LabelMap->ShallowCopy(s->GetLabelMap()); } vtkDataObject::ShallowCopy(o); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::DeepCopy(vtkDataObject *o) { vtkKWEPaintbrushLabelData *s = vtkKWEPaintbrushLabelData::SafeDownCast(o); if (s) { this->LabelMap->DeepCopy(s->GetLabelMap()); } vtkDataObject::DeepCopy(o); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::Allocate( double value ) { // Allocate this->LabelMap->AllocateScalars(); // Fill with the unused label value. vtkDataArray * array = this->LabelMap->GetPointData()->GetScalars(); vtkKWEPaintbrushEnums::LabelType *arrayPointer = static_cast(array->GetVoidPointer(0)); unsigned long size = array->GetDataSize(); for (unsigned long i = 0; i < size; i++) { *arrayPointer = static_cast(value); ++arrayPointer; } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::Clear( vtkKWEPaintbrushEnums::LabelType label ) { if (this->LabelMap->GetPointData()->GetScalars() == NULL) { // Data hasn't been allocated yet. Allocate and be done this->Allocate(0.0); } else { // Clear label vtkDataArray * array = this->LabelMap->GetPointData()->GetScalars(); vtkKWEPaintbrushEnums::LabelType *arrayPointer = static_cast(array->GetVoidPointer(0)); unsigned long size = array->GetDataSize(); for (unsigned long i = 0; i < size; i++) { if (*arrayPointer == label) { *arrayPointer = vtkKWEPaintbrushLabelData::NoLabelValue; } ++arrayPointer; } this->LabelMap->Modified(); } } //---------------------------------------------------------------------------- vtkKWEPaintbrushLabelData* vtkKWEPaintbrushLabelData::GetData(vtkInformation* info) { return info? vtkKWEPaintbrushLabelData::SafeDownCast(info->Get(DATA_OBJECT())) : 0; } //---------------------------------------------------------------------------- vtkKWEPaintbrushLabelData* vtkKWEPaintbrushLabelData::GetData(vtkInformationVector* v, int i) { return vtkKWEPaintbrushLabelData::GetData(v->GetInformationObject(i)); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushLabelData::Add( vtkKWEPaintbrushData * data, bool forceMutable ) { int extentToBeAdded[6], currentExtent[6], extent[6]; data->GetExtent(extentToBeAdded); this->GetExtent(currentExtent); if (!vtkKWEPaintbrushUtilities::GetIntersectingExtents( currentExtent, extentToBeAdded, extent )) { // The stuff we are adding is entirely outside our bounds. // Nothing to add. return 0; } // Handle Immubtability of sketches. // For details, see vtkKWEPaintbrushProperty::SetMubtale const bool mutableLabelsPresent = (this->ImmutableLabels.size() > 0); vtkstd::set< vtkKWEPaintbrushEnums::LabelType >::const_iterator iterEnd = this->ImmutableLabels.end(); if (vtkKWEPaintbrushLabelData *labelData = vtkKWEPaintbrushLabelData::SafeDownCast(data)) { // PaintbrushLabelData + PaintbrushLabelData vtkImageIterator< vtkKWEPaintbrushEnums::LabelType > it2( labelData->GetLabelMap(), extent ); vtkImageIterator< vtkKWEPaintbrushEnums::LabelType > it1( this->LabelMap, extent ); bool immutableLabel = false; vtkKWEPaintbrushEnums::LabelType lastLabel = vtkKWEPaintbrushLabelData::NoLabelValue; while( !it1.IsAtEnd() ) { vtkKWEPaintbrushEnums::LabelType *inSI = it1.BeginSpan(); vtkKWEPaintbrushEnums::LabelType *inSI2 = it2.BeginSpan(); vtkKWEPaintbrushEnums::LabelType *inSIEnd = it1.EndSpan(); if( mutableLabelsPresent && !forceMutable ) { while (inSI != inSIEnd) { vtkKWEPaintbrushEnums::LabelType l = *inSI2; if (l != vtkKWEPaintbrushLabelData::NoLabelValue) { if( lastLabel != *inSI ) { lastLabel = *inSI; if( this->ImmutableLabels.find(*inSI) == iterEnd ) { immutableLabel = false; } else { immutableLabel = true; } } if( !immutableLabel ) { *inSI = l; } } ++inSI; ++inSI2; } } else { while (inSI != inSIEnd) { vtkKWEPaintbrushEnums::LabelType l = *inSI2; if (l != vtkKWEPaintbrushLabelData::NoLabelValue) { *inSI = l; } ++inSI; ++inSI2; } } it1.NextSpan(); it2.NextSpan(); } } else if (vtkKWEPaintbrushStencilData *binaryPaintbrushData = vtkKWEPaintbrushStencilData::SafeDownCast(data)) { this->AddStencil( binaryPaintbrushData, forceMutable ); } this->LabelMap->Modified(); this->Modified(); return 1; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushLabelData:: AddStencil( vtkKWEPaintbrushStencilData * data, bool forceMutable ) { int extentToBeAdded[6], currentExtent[6], extent[6]; data->GetExtent(extentToBeAdded); this->GetExtent(currentExtent); if (!vtkKWEPaintbrushUtilities::GetIntersectingExtents( currentExtent, extentToBeAdded, extent )) { // The stuff we are adding is entirely outside our bounds. // Nothing to add. return 0; } // Handle Immubtability of sketches. // For details, see vtkKWEPaintbrushProperty::SetMubtale const bool mutableLabelsPresent = (this->ImmutableLabels.size() > 0); vtkstd::set< vtkKWEPaintbrushEnums::LabelType >::const_iterator iterEnd = this->ImmutableLabels.end(); // PaintbrushLabelData + PaintbrushStencilData vtkImageStencilData *stencilData = data->GetImageStencilData(); // Compute incremental deltas for Undo-Redo, if requested. vtkSmartPointer< vtkImageStencilData > tempData = stencilData; if (this->ComputeDelta) { tempData = vtkSmartPointer< vtkImageStencilData >::New(); tempData->DeepCopy(stencilData); } vtkKWEPaintbrushEnums::LabelType l = data->GetLabel(); int r1, r2, moreSubExtents, iter; bool immutableLabel = false; vtkKWEPaintbrushEnums::LabelType lastLabel = vtkKWEPaintbrushLabelData::NoLabelValue; for (int z=extent[4]; z <= extent[5]; z++) { for (int y=extent[2]; y <= extent[3]; y++) { iter = 0; moreSubExtents = 1; while( moreSubExtents ) { moreSubExtents = tempData->GetNextExtent( r1, r2, extent[0], extent[1], y, z, iter); int removeStart = -1, removeEnd = -1; // sanity check if (r1 <= r2) { vtkKWEPaintbrushEnums::LabelType *beginExtent = static_cast(this->LabelMap->GetScalarPointer(r1, y, z)); vtkKWEPaintbrushEnums::LabelType *endExtent = static_cast(this->LabelMap->GetScalarPointer(r2, y, z)); if( mutableLabelsPresent && !forceMutable ) { while (beginExtent <= endExtent) { // If this voxel is mutable.. if( lastLabel != *beginExtent ) { lastLabel = *beginExtent; if( this->ImmutableLabels.find(*beginExtent) == iterEnd ) { immutableLabel = false; } else { immutableLabel = true; } } if( !immutableLabel ) { if (*beginExtent != l) { *beginExtent = l; // This scan line already exists on the data. Remove it from // the stroke if (this->ComputeDelta && removeStart != -1 && removeEnd == -1 && removeStart < r1) { stencilData->RemoveExtent( removeStart, r1-1, y, z ); removeStart = removeEnd = -1; // reset them. } } else { if (removeStart == -1) { removeStart = r1; } } } else // this pixel is locked to any changes { if (removeStart == -1) { removeStart = r1; } } ++beginExtent; ++r1; } // This scan line already exists on the data. Remove it from the // stroke if (this->ComputeDelta && removeStart != -1 && removeEnd == -1) { stencilData->RemoveExtent( removeStart, r1 - 1, y, z ); } } else { while (beginExtent <= endExtent) { if (*beginExtent != l) { *beginExtent = l; // This scan line already exists on the data. Remove it from // the stroke if (this->ComputeDelta && removeStart != -1 && removeEnd == -1 && removeStart < r1) { stencilData->RemoveExtent( removeStart, r1-1, y, z ); removeStart = removeEnd = -1; // reset them. } } else { if (removeStart == -1) { removeStart = r1; } } ++beginExtent; ++r1; } // This scan line already exists on the data. Remove it from the // stroke if (this->ComputeDelta && removeStart != -1 && removeEnd == -1) { stencilData->RemoveExtent( removeStart, r1 - 1, y, z ); } } } } // end for each extent tuple } // end for each scan line } // end of each slice } //---------------------------------------------------------------------------- int vtkKWEPaintbrushLabelData::Subtract( vtkKWEPaintbrushData * data, bool forceMutable ) { int extentToBeSubtracted[6], currentExtent[6], extent[6]; data->GetExtent(extentToBeSubtracted); this->GetExtent(currentExtent); if (!vtkKWEPaintbrushUtilities::GetIntersectingExtents( currentExtent, extentToBeSubtracted, extent )) { // The stuff we are removing is entirely outside our bounds. // Nothing to add. return 0; } // Handle Immubtability of sketches. // For details, see vtkKWEPaintbrushProperty::SetMubtale const bool mutableLabelsPresent = (this->ImmutableLabels.size() > 0); vtkstd::set< vtkKWEPaintbrushEnums::LabelType >::const_iterator iterEnd = this->ImmutableLabels.end(); if (vtkKWEPaintbrushLabelData *labelData = vtkKWEPaintbrushLabelData::SafeDownCast(data)) { vtkImageIterator< vtkKWEPaintbrushEnums::LabelType > it2( labelData->GetLabelMap(), extent ); vtkImageIterator< vtkKWEPaintbrushEnums::LabelType > it1( this->LabelMap, extent ); bool immutableLabel = false; vtkKWEPaintbrushEnums::LabelType lastLabel = vtkKWEPaintbrushLabelData::NoLabelValue; while( !it1.IsAtEnd() ) { vtkKWEPaintbrushEnums::LabelType *inSI = it1.BeginSpan(); vtkKWEPaintbrushEnums::LabelType *inSI2 = it2.BeginSpan(); vtkKWEPaintbrushEnums::LabelType *inSIEnd = it1.EndSpan(); if( mutableLabelsPresent && !forceMutable ) { while (inSI != inSIEnd) { if (*inSI2 != vtkKWEPaintbrushLabelData::NoLabelValue) { // If this voxel is mutable.. if( lastLabel != *inSI ) { lastLabel = *inSI; if( this->ImmutableLabels.find(*inSI) == iterEnd ) { immutableLabel = false; } else { immutableLabel = true; } } if( !immutableLabel ) { *inSI = vtkKWEPaintbrushLabelData::NoLabelValue; } } ++inSI; ++inSI2; } } else { while (inSI != inSIEnd) { if (*inSI2 != vtkKWEPaintbrushLabelData::NoLabelValue) { // If this voxel is mutable.. *inSI = vtkKWEPaintbrushLabelData::NoLabelValue; } ++inSI; ++inSI2; } } it1.NextSpan(); it2.NextSpan(); } } else if (vtkKWEPaintbrushStencilData *binaryPaintbrushData = vtkKWEPaintbrushStencilData::SafeDownCast(data)) { vtkImageStencilData *stencilData = binaryPaintbrushData->GetImageStencilData(); // Compute incremental deltas for Undo-Redo, if requested. vtkSmartPointer< vtkImageStencilData > tempData = stencilData; if (this->ComputeDelta) { tempData = vtkSmartPointer< vtkImageStencilData >::New(); tempData->DeepCopy(stencilData); } int r1, r2, moreSubExtents, iter; bool immutableLabel = false; vtkKWEPaintbrushEnums::LabelType lastLabel = vtkKWEPaintbrushLabelData::NoLabelValue; for (int z=extent[4]; z <= extent[5]; z++) { for (int y=extent[2]; y <= extent[3]; y++) { iter = 0; moreSubExtents = 1; while( moreSubExtents ) { moreSubExtents = tempData->GetNextExtent( r1, r2, extent[0], extent[1], y, z, iter); // sanity check if (r1 <= r2) { int removeStart = -1, removeEnd = -1; vtkKWEPaintbrushEnums::LabelType *beginExtent = static_cast(this->LabelMap->GetScalarPointer(r1, y, z)); vtkKWEPaintbrushEnums::LabelType *endExtent = static_cast(this->LabelMap->GetScalarPointer(r2, y, z)); if( mutableLabelsPresent && !forceMutable ) { while (beginExtent <= endExtent) { if( lastLabel != *beginExtent ) { lastLabel = *beginExtent; if( this->ImmutableLabels.find(*beginExtent) == iterEnd ) { immutableLabel = false; } else { immutableLabel = true; } } if( !immutableLabel ) { if (*beginExtent != vtkKWEPaintbrushLabelData::NoLabelValue) { *beginExtent = vtkKWEPaintbrushLabelData::NoLabelValue; // This scan line already exists on the data. Remove it from // the stroke if (this->ComputeDelta && removeStart != -1 && removeEnd == -1 && removeStart < r1) { stencilData->RemoveExtent( removeStart, r1-1, y, z ); removeStart = removeEnd = -1; // reset them. } } else { if (removeStart == -1) { removeStart = r1; } } } else // this pixel is locked to any changes { if (removeStart == -1) { removeStart = r1; } } ++beginExtent; ++r1; } } else { while (beginExtent <= endExtent) { if (*beginExtent != vtkKWEPaintbrushLabelData::NoLabelValue) { *beginExtent = vtkKWEPaintbrushLabelData::NoLabelValue; // This scan line already exists on the data. Remove it from // the stroke if (this->ComputeDelta && removeStart != -1 && removeEnd == -1 && removeStart < r1) { stencilData->RemoveExtent( removeStart, r1-1, y, z ); removeStart = removeEnd = -1; // reset them. } } else { if (removeStart == -1) { removeStart = r1; } } ++beginExtent; ++r1; } } // This scan line already exists on the data. Remove it from the // stroke if (this->ComputeDelta && removeStart != -1 && removeEnd == -1) { stencilData->RemoveExtent( removeStart, r1 - 1, y, z ); } } } // end for each extent tuple } // end for each scan line } // end of each slice } this->LabelMap->Modified(); this->Modified(); return 1; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushLabelData::Replace( vtkKWEPaintbrushData * data, bool forceMutable ) { int extentToBeReplaced[6], currentExtent[6], extent[6]; data->GetExtent(extentToBeReplaced); this->GetExtent(currentExtent); if( !vtkKWEPaintbrushUtilities::GetIntersectingExtents( currentExtent, extentToBeReplaced, extent ) ) { // The stuff we are removing is entirely outside our bounds. // Nothing to add. return 0; } // Handle Immubtability of sketches. // For details, see vtkKWEPaintbrushProperty::SetMubtale const bool mutableLabelsPresent = (this->ImmutableLabels.size() > 0); vtkstd::set< vtkKWEPaintbrushEnums::LabelType >::const_iterator iterEnd = this->ImmutableLabels.end(); if (vtkKWEPaintbrushLabelData *labelData = vtkKWEPaintbrushLabelData::SafeDownCast(data)) { vtkImageIterator< vtkKWEPaintbrushEnums::LabelType > it2( labelData->GetLabelMap(), extent ); vtkImageIterator< vtkKWEPaintbrushEnums::LabelType > it1( this->LabelMap, extent ); bool immutableLabel = false; vtkKWEPaintbrushEnums::LabelType lastLabel = vtkKWEPaintbrushLabelData::NoLabelValue; while( !it1.IsAtEnd() ) { vtkKWEPaintbrushEnums::LabelType *inSI = it1.BeginSpan(); vtkKWEPaintbrushEnums::LabelType *inSI2 = it2.BeginSpan(); vtkKWEPaintbrushEnums::LabelType *inSIEnd = it1.EndSpan(); if( mutableLabelsPresent && !forceMutable ) { while (inSI != inSIEnd) { // If this voxel is mutable.. if( lastLabel != *inSI ) { lastLabel = *inSI; if( this->ImmutableLabels.find(*inSI) == iterEnd ) { immutableLabel = false; } else { immutableLabel = true; } } if( !immutableLabel ) { if( *inSI2 == this->GetLabel() ) { *inSI = this->GetLabel(); } else { if( *inSI == this->GetLabel() ) { *inSI = vtkKWEPaintbrushLabelData::NoLabelValue; } } } ++inSI; ++inSI2; } } else { while (inSI != inSIEnd) { if( *inSI2 == this->GetLabel() ) { *inSI = this->GetLabel(); } else { if( *inSI == this->GetLabel() ) { *inSI = vtkKWEPaintbrushLabelData::NoLabelValue; } } ++inSI; ++inSI2; } } it1.NextSpan(); it2.NextSpan(); } } else if (vtkKWEPaintbrushStencilData *binaryPaintbrushData = vtkKWEPaintbrushStencilData::SafeDownCast(data)) { vtkImageStencilData *stencilData = binaryPaintbrushData->GetImageStencilData(); int r1, r2, moreSubExtents, iter; bool immutableLabel = false; vtkKWEPaintbrushEnums::LabelType lastLabel = vtkKWEPaintbrushLabelData::NoLabelValue; for (int z=extent[4]; z <= extent[5]; z++) { for (int y=extent[2]; y <= extent[3]; y++) { vtkKWEPaintbrushEnums::LabelType *beginExtent = static_cast( this->LabelMap->GetScalarPointer(extent[0], y, z) ); vtkKWEPaintbrushEnums::LabelType *endExtent = static_cast( this->LabelMap->GetScalarPointer(extent[1], y, z) ); while( beginExtent < endExtent ) { if( *beginExtent == this->GetLabel() ) { *beginExtent = vtkKWEPaintbrushLabelData::NoLabelValue; } ++beginExtent; } iter = 0; moreSubExtents = 1; while( moreSubExtents ) { moreSubExtents = stencilData->GetNextExtent( r1, r2, extent[0], extent[1], y, z, iter); // sanity check if (r1 <= r2) { beginExtent = static_cast( this->LabelMap->GetScalarPointer(r1, y, z)); endExtent = static_cast( this->LabelMap->GetScalarPointer(r2, y, z)); if( mutableLabelsPresent && !forceMutable ) { while (beginExtent <= endExtent) { if( lastLabel != *beginExtent ) { lastLabel = *beginExtent; if( this->ImmutableLabels.find(*beginExtent) == iterEnd ) { immutableLabel = false; } else { immutableLabel = true; } } if( !immutableLabel ) { *beginExtent = this->GetLabel(); } ++beginExtent; } } else { while (beginExtent <= endExtent) { *beginExtent = this->GetLabel(); ++beginExtent; } } } } // end for each extent tuple } // end for each scan line } // end of each slice } this->LabelMap->Modified(); this->Modified(); return 1; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushLabelData::Clip( int extent[6] ) { int currentExtent[6], idy, idz, idx; this->Update(); this->GetExtent( currentExtent ); if (vtkMath::ExtentIsWithinOtherExtent( currentExtent, extent )) { // Nothing to do, we are already within the clipping extents. return 0; } // Does not resize the current allocation if the clipped region is smaller. // It simply blanks out data outside the extents specified. // TODO: Check if this has an impact on memory or performance. bool remove = false, removed = false; vtkKWEPaintbrushEnums::LabelType *ptr = static_cast(this->LabelMap->GetScalarPointer()); for (idz=currentExtent[4]; idz<=currentExtent[5]; idz++) { remove = (idz < extent[4] || idz > extent[5]); for (idy = currentExtent[2]; idy <= currentExtent[3]; idy++) { remove |= (idy < extent[2] || idy > extent[3]); for (idx = currentExtent[4]; idx <= currentExtent[5]; idx++) { remove |= (idx < extent[4] || idx > extent[5]); if (remove) { *ptr = vtkKWEPaintbrushLabelData::NoLabelValue; } removed |= remove; ++ptr; } } } if (removed) { this->LabelMap->Modified(); this->Modified(); } return (removed ? 1 : 0); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushLabelData::IsInside(double p[3]) { int pixelPos[3], extent[6]; double origin[3], spacing[3]; this->LabelMap->GetSpacing(spacing); this->LabelMap->GetOrigin(origin); this->LabelMap->GetExtent(extent); for (int i = 0; i < 3; i++) { pixelPos[i] = static_cast(((p[i] - origin[i])/spacing[i])+0.5); if (pixelPos[i] < extent[2*i] || pixelPos[i] > extent[2*i+1]) { return 0; } } return static_cast(*(static_cast (this->LabelMap->GetScalarPointer(pixelPos)))); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::SetSpacing( double s[3] ) { this->LabelMap->SetSpacing(s); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::GetSpacing( double s[3] ) { this->LabelMap->GetSpacing(s); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::SetOrigin( double s[3] ) { this->LabelMap->SetOrigin(s); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::GetOrigin( double s[3] ) { this->LabelMap->GetOrigin(s); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::GetPaintbrushDataAsImageData(vtkImageData *image) { image->ShallowCopy(this->LabelMap); } //---------------------------------------------------------------------------- unsigned long vtkKWEPaintbrushLabelData::GetMTime() { unsigned long t = this->LabelMap->GetMTime(); unsigned long mtime = vtkObject::GetMTime(); return (mtime > t ? mtime : t); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::SetNoLabelValue( vtkKWEPaintbrushEnums::LabelType label ) { vtkKWEPaintbrushLabelData::NoLabelValue = label; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::SetMutable( int isMutable, vtkKWEPaintbrushEnums::LabelType label ) { if (isMutable) { this->ImmutableLabels.insert(label); } else { this->ImmutableLabels.erase(label); } } //---------------------------------------------------------------------------- int vtkKWEPaintbrushLabelData::IsMutable( vtkKWEPaintbrushEnums::LabelType label ) { return (this->ImmutableLabels.find(label) == this->ImmutableLabels.end()) ? 0 : 1; } //---------------------------------------------------------------------------- vtkKWEPaintbrushLabelData::LabelSetType vtkKWEPaintbrushLabelData::GetLabels() { LabelSetType labels; vtkDataArray * array = this->LabelMap->GetPointData()->GetScalars(); vtkKWEPaintbrushEnums::LabelType *arrayPointer = static_cast(array->GetVoidPointer(0)); const unsigned long size = array->GetDataSize(); for (unsigned long i = 0; i < size; ++i, ++arrayPointer) { vtkKWEPaintbrushEnums::LabelType l = *arrayPointer; if (l != NoLabelValue) { labels.insert(l); } } return labels; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::RelabelDataToContiguousLabels() { // Convenience method to collapse the labels in a label map. Consider a label // map with labels of 32, 64, 125, 255 and a NoLabelValue of 0. This will // collapse this data into labels of 1, 2, 3, 4. // Build a map of the old (uncontiguous) labels to contiguous labels. const LabelSetType oldLabels = this->GetLabels(); typedef vtkKWEPaintbrushEnums::LabelType LabelType; typedef std::map< LabelType, LabelType > RelabelMapType; RelabelMapType relabelMap; LabelType i = 0; for ( LabelSetType::const_iterator it = oldLabels.begin(); it != oldLabels.end(); ++it, ++i ) { if (i == NoLabelValue) { ++i; } relabelMap.insert(std::pair< LabelType, LabelType >(*it, i)); } // Check that the labels are really "uncontiguous". If they aren't, we have // nothing to do. int isContiguous = true; for (RelabelMapType::const_iterator rit = relabelMap.begin(); (rit != relabelMap.end() && isContiguous); ++rit) { isContiguous &= (rit->first == rit->second); } // Now visit every label in the image and re-map it to its contiguous value. if (!isContiguous) { vtkDataArray * array = this->LabelMap->GetPointData()->GetScalars(); vtkKWEPaintbrushEnums::LabelType *arrayPointer = static_cast(array->GetVoidPointer(0)); const unsigned long size = array->GetDataSize(); for (unsigned long i = 0; i < size; ++i, ++arrayPointer) { vtkKWEPaintbrushEnums::LabelType l = *arrayPointer; if (l != NoLabelValue) { *arrayPointer = relabelMap[l]; } } this->LabelMap->Modified(); this->Modified(); } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::SetLabelMap( vtkImageData * labelMap ) { // If the datatype of the label map is different from what is defined as // vtkKWEPaintbrushEnums::GetLabelType(), we have to do a casting to that // type. if (this->LabelMap == NULL || this->LabelMap->GetScalarType() == vtkKWEPaintbrushEnums::GetLabelType()) { vtkSetObjectBodyMacro( LabelMap, vtkImageData, labelMap ); } // The scalar type is different.... // Check if labelMap's scalar range will fit in the our scalar type. typedef std::numeric_limits< vtkKWEPaintbrushEnums::LabelType > LimitsType; double range[2]; labelMap->GetScalarRange(range); if ((range[0] >= LimitsType::min() && range[1] <= LimitsType::max()) || (range[1]-range[0]) > (LimitsType::max() - LimitsType::max())) { // Yes we fit.. just do regular casting.. vtkImageCast *cast = vtkImageCast::New(); cast->SetInput(labelMap); cast->SetOutputScalarType(vtkKWEPaintbrushEnums::GetLabelType()); cast->Update(); vtkImageData *castedLabelMap = vtkImageData::New(); castedLabelMap->ShallowCopy(cast->GetOutput()); vtkSetObjectBodyMacro( LabelMap, vtkImageData, castedLabelMap ); cast->Delete(); castedLabelMap->Delete(); } // We can't just cast simply. At least check if our scalar range fits // within the precision we support. else { // Shift to our range vtkImageShiftScale *shiftScale = vtkImageShiftScale::New(); shiftScale->SetInput(labelMap); shiftScale->SetOutputScalarType(vtkKWEPaintbrushEnums::GetLabelType()); // 1 offset assumes that NoLabelValue is 0. shiftScale->SetShift(range[0]+1); shiftScale->Update(); vtkImageData *shiftScaledLabelMap = vtkImageData::New(); shiftScaledLabelMap->ShallowCopy(shiftScale->GetOutput()); vtkSetObjectBodyMacro( LabelMap, vtkImageData, shiftScaledLabelMap ); shiftScale->Delete(); shiftScaledLabelMap->Delete(); } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushLabelData::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "LabelMap:\n"; if (this->LabelMap) { this->LabelMap->PrintSelf(os,indent.GetNextIndent()); int extent[6]; this->GetExtent(extent); os << indent << "Extent: (" << extent[0] << ", " << extent[1] << ", " << extent[2] << ", " << extent[3] << ", " << extent[4] << ", " << extent[5] << ")\n"; double spacing[3], origin[3]; this->GetSpacing(spacing); this->GetOrigin(origin); os << indent << "Spacing: (" << spacing[0] << ", " << spacing[1] << ", " << spacing[2] << ")\n"; os << indent << "Origin: (" << origin[0] << ", " << origin[1] << ", " << origin[2] << ")\n"; } } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushRepresentationGrayscale2D.cxx0000644000175000017500000003640111363410610026350 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushRepresentationGrayscale2D.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushPropertyManager.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkKWEPaintbrushPropertyManager.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushShape.h" #include "vtkContourFilter.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkObjectFactory.h" #include "vtkProperty.h" #include "vtkImageData.h" #include "vtkImageExtractComponents.h" #include "vtkImageClip.h" #include "vtkImageActor.h" #include "vtkImageActorPointPlacer.h" #include "vtkSmartPointer.h" #include "vtkActorCollection.h" #include "vtkMapperCollection.h" vtkCxxRevisionMacro(vtkKWEPaintbrushRepresentationGrayscale2D, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEPaintbrushRepresentationGrayscale2D); //---------------------------------------------------------------------- vtkKWEPaintbrushRepresentationGrayscale2D::vtkKWEPaintbrushRepresentationGrayscale2D() { this->ContourFilters = vtkCollection::New(); this->ExtractComponents = vtkCollection::New(); this->ImageClips = vtkCollection::New(); this->ContourPolyDataMappers = vtkMapperCollection::New(); this->ContourPolyDataActors = vtkActorCollection::New(); this->IsoValue = 127.5; this->PaintbrushDrawing->SetRepresentationToGrayscale(); // The paintbrushes don't snap to the grid vtkImageActorPointPlacer * v = vtkImageActorPointPlacer::New(); this->SetShapePlacer(v); v->Delete(); // Thick highlight looks better when we have contours this->PaintbrushDrawing->GetPaintbrushPropertyManager()->SetHighlightType( vtkKWEPaintbrushProperty::ThickHighlight); this->PaintbrushOperation->GetPaintbrushShape()-> SetRepresentation( vtkKWEPaintbrushEnums::Grayscale ); } //---------------------------------------------------------------------- vtkKWEPaintbrushRepresentationGrayscale2D::~vtkKWEPaintbrushRepresentationGrayscale2D() { this->ExtractComponents->Delete(); this->ImageClips->Delete(); this->ContourFilters->Delete(); this->ContourPolyDataMappers->Delete(); this->ContourPolyDataActors->Delete(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentationGrayscale2D::BuildRepresentation() { // The pipeline is as follows : // // SketchImage_0 --> ExtractFirstComponent_0 --> ImageClip_0 --> // ContourFilter_0 --> PolyDataMapper_0 --> Actor_0 // // SketchImage_1 --> ExtractFirstComponent_1 --> ImageClip_1 --> // ContourFilter_1 --> PolyDataMapper_1 --> Actor_1 // .... // .... vtkImageClip *ic; vtkActor *ac; vtkImageExtractComponents *a; vtkContourFilter * cf; vtkCollectionSimpleIterator ait; const int nSketches = this->PaintbrushDrawing->GetNumberOfItems(); for (int i = 0; i < nSketches; i++) { vtkKWEPaintbrushSketch * sketch = this->PaintbrushDrawing->GetItem(i); vtkKWEPaintbrushGrayscaleData *mask = vtkKWEPaintbrushGrayscaleData:: SafeDownCast(sketch->GetPaintbrushData()); if (mask) { vtkImageData * image = mask->GetImageData(); bool found = false; for ( this->ExtractComponents->InitTraversal(ait); (a=static_cast< vtkImageExtractComponents * >( this->ExtractComponents->GetNextItemAsObject(ait))); ) { if (a->GetInput() == image) { found = true; break; } } if (!found) { vtkImageExtractComponents * extractComponents = vtkImageExtractComponents::New(); vtkImageClip * imageClip = vtkImageClip::New(); vtkContourFilter * contourFilter = vtkContourFilter::New(); vtkPolyDataMapper * mapper = vtkPolyDataMapper::New(); vtkActor * actor = vtkActor::New(); extractComponents->SetInput( image ); extractComponents->SetComponents(0); imageClip->SetClipData(1); imageClip->SetInput(extractComponents->GetOutput()); contourFilter->SetInput(imageClip->GetOutput()); contourFilter->SetValue(0, this->IsoValue); imageClip->Update(); contourFilter->Update(); mapper->SetInput(contourFilter->GetOutput()); mapper->SetResolveCoincidentTopologyToPolygonOffset(); mapper->ScalarVisibilityOff(); actor->SetMapper(mapper); vtkProperty * property = vtkProperty::New(); property->SetColor( 0.0, 0.0, 0.0 ); actor->SetProperty( property ); property->Delete(); this->ContourPolyDataActors->AddItem(actor); this->ContourPolyDataMappers->AddItem(mapper); this->ExtractComponents->AddItem(extractComponents); this->ImageClips->AddItem(imageClip); this->ContourFilters->AddItem(contourFilter); imageClip->Delete(); extractComponents->Delete(); contourFilter->Delete(); mapper->Delete(); actor->Delete(); } } } // Now remove old unused ones, if any std::vector< int > indicesToRemove; int j = 0; for ( this->ExtractComponents->InitTraversal(ait); (a=static_cast< vtkImageExtractComponents * >( this->ExtractComponents->GetNextItemAsObject(ait))); j++) { bool found = false; for (int i = 0; i < nSketches; i++) { if (vtkKWEPaintbrushGrayscaleData *mask = vtkKWEPaintbrushGrayscaleData:: SafeDownCast(this->PaintbrushDrawing->GetItem(i)->GetPaintbrushData())) { if (a->GetInput() == mask->GetImageData()) { found = true; break; } } } if (!found) { indicesToRemove.push_back(j); } } for (std::vector< int >::const_iterator it = indicesToRemove.begin(); it != indicesToRemove.end(); ++it) { int indexToRemove = *it; // We need to get rid of this actor and its associated pipeline this->ContourPolyDataActors->RemoveItem(indexToRemove); this->ContourPolyDataMappers->RemoveItem(indexToRemove); this->ExtractComponents->RemoveItem(indexToRemove); this->ImageClips->RemoveItem(indexToRemove); this->ContourFilters->RemoveItem(indexToRemove); } // Now, for the new actors we created, we need to set reasonable colors, // preferably not the same colors as the ones the other actors use. So // let's go about working some magic to get new colors. // Clear our table. this->PaintbrushDrawing->GetPaintbrushPropertyManager()->Initialize(); // These are all the actors that were created long ago. for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait)); ) { this->PaintbrushDrawing->GetPaintbrushPropertyManager()->AddUsedColor( ac->GetProperty()); } // Visit all the newly created actors and assign properties. for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { double rgb[3]; ac->GetProperty()->GetColor(rgb); if (rgb[0] == 0.0 && rgb[1] == 0.0 && rgb[2] == 0.0) { // This is a newly created actor, with no color set yet. Request a // possibly unique color for the sketch that this actor is rendering // and assign it to the actor's property. ac->SetProperty( this->PaintbrushDrawing->GetPaintbrushPropertyManager()-> RequestColorForSketch( this->GetSketch(ac) )->GetProperty()); } } // Set the update extent to the extent of the image actor. That's all we // can see anyway. If the image actor's extents are outside the canvas // turn the visibility off. int imageActorExtents[6], imageDataExtents[6], intersectingExtents[6]; this->ImageActor->GetDisplayExtent( imageActorExtents ); this->ImageData->GetExtent( imageDataExtents ); int visible = vtkKWEPaintbrushUtilities::GetIntersectingExtents( imageActorExtents, imageDataExtents, intersectingExtents) && this->Visibility; if (visible) { for ( this->ImageClips->InitTraversal(ait); (ic=static_cast< vtkImageClip * >( this->ImageClips->GetNextItemAsObject(ait))); ) { ic->SetOutputWholeExtent( intersectingExtents ); } // Set the isovalue of the contour filters to the isovalue and update the // contour filter. for ( this->ContourFilters->InitTraversal(ait); (cf=static_cast< vtkContourFilter * >( this->ContourFilters->GetNextItemAsObject(ait))); ) { cf->SetValue(0, this->IsoValue); cf->Update(); } } for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { ac->SetVisibility( visible ); } } //---------------------------------------------------------------------- vtkKWEPaintbrushSketch * vtkKWEPaintbrushRepresentationGrayscale2D:: GetSketch( vtkActor * a ) { vtkActor *ac; vtkCollectionSimpleIterator ait; int i = 0; vtkImageData * image = NULL; const int nSketches = this->PaintbrushDrawing->GetNumberOfItems(); for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait)); ++i) { if (ac == a) { image = static_cast< vtkImageData *>(( static_cast< vtkImageExtractComponents * >( this->ExtractComponents->GetItemAsObject(i)))->GetInput()); } } for (i = 0; i < nSketches; i++) { vtkKWEPaintbrushSketch * sketch = this->PaintbrushDrawing->GetItem(i); if (vtkKWEPaintbrushGrayscaleData *mask = vtkKWEPaintbrushGrayscaleData:: SafeDownCast(sketch->GetPaintbrushData())) { if (image == mask->GetImageData()) { return sketch; } } } return NULL; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentationGrayscale2D::RenderOverlay(vtkViewport *viewport) { int count = 0; if (this->ShapeOutlineActor->GetVisibility()) { count += this->ShapeOutlineActor->RenderOverlay(viewport); } vtkActor *ac; vtkCollectionSimpleIterator ait; for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { if (ac->GetVisibility()) { count += ac->RenderOverlay(viewport); } } return count; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentationGrayscale2D ::RenderOpaqueGeometry(vtkViewport *viewport) { this->BuildRepresentation(); int count = 0; if (this->ShapeOutlineActor->GetVisibility()) { count += this->ShapeOutlineActor->RenderOpaqueGeometry(viewport); } vtkActor *ac; vtkCollectionSimpleIterator ait; for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { if (ac->GetVisibility()) { double rgb[3]; ac->GetProperty()->GetColor(rgb); count += ac->RenderOpaqueGeometry(viewport); } } return count; } #if VTKEdge_VTK_VERSION_DATE > 20070305 //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentationGrayscale2D ::RenderTranslucentPolygonalGeometry(vtkViewport *viewport) { int count = 0; if (this->ShapeOutlineActor->GetVisibility()) { count += this->ShapeOutlineActor->RenderTranslucentPolygonalGeometry(viewport); } vtkActor *ac; vtkCollectionSimpleIterator ait; for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { if (ac->GetVisibility()) { count += ac->RenderTranslucentPolygonalGeometry(viewport); } } return count; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentationGrayscale2D::HasTranslucentPolygonalGeometry() { int result = 0; if (this->ShapeOutlineActor->GetVisibility()) { result |= this->ShapeOutlineActor->HasTranslucentPolygonalGeometry(); } vtkActor *ac; vtkCollectionSimpleIterator ait; for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { result |= ac->HasTranslucentPolygonalGeometry(); } return result; } #else //---------------------------------------------------------------------- // Legacy method to support VTK source versions prior to 2007/03/05 int vtkKWEPaintbrushRepresentationGrayscale2D:: RenderTranslucentGeometry(vtkViewport *viewport) { int count = 0; if (this->ShapeOutlineActor->GetVisibility()) { count += this->ShapeOutlineActor->RenderTranslucentGeometry(viewport); } vtkActor *ac; vtkCollectionSimpleIterator ait; for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { if (ac->GetVisibility()) { count += ac->RenderTranslucentGeometry(viewport); } } return count; } #endif //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentationGrayscale2D::GetActors( vtkPropCollection * pc ) { this->ShapeOutlineActor->GetActors(pc); vtkActor *ac; vtkCollectionSimpleIterator ait; for ( this->ContourPolyDataActors->InitTraversal(ait); (ac=this->ContourPolyDataActors->GetNextActor(ait));) { ac->GetActors(pc); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentationGrayscale2D::DeepCopy(vtkWidgetRepresentation *rep) { if (this == rep) { return; } vtkKWEPaintbrushRepresentationGrayscale2D *r = vtkKWEPaintbrushRepresentationGrayscale2D::SafeDownCast(rep); if (r) { this->IsoValue = r->IsoValue; } this->Superclass::DeepCopy(rep); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentationGrayscale2D::SetPaintbrushDrawing( vtkKWEPaintbrushDrawing * drawing ) { vtkKWEPaintbrushRepresentation::SetPaintbrushDrawing(drawing); // Thick highlight looks better when we have contours this->PaintbrushDrawing->GetPaintbrushPropertyManager()->SetHighlightType( vtkKWEPaintbrushProperty::ThickHighlight); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentationGrayscale2D::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWELightPaintbrushWidgetCallbackMapper.h0000644000175000017500000000560111521051333025744 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWELightPaintbrushWidgetCallbackMapper - map widget events into callbacks // .SECTION Description // vtkKWELightPaintbrushWidgetCallbackMapper is a subclass of vtkKWEPaintbrushWidgetCallbackMapper. // It is an example of how one may override the default bindings to set their own // bindings on the paintbrush widget. To use this class, one sets the callback mapper // on the widget. // // .SECTION Interactions //

// The follwing interactions are defined by this class when the brush is // in Edit mode. // Left click and drag - Draws a stroke // Ctrl-Left click and drag - Erase stroke // Shift Left click drag - Draws a stroke on this sketch alone. All other sketches are deemed uneditable while the shift key is depressed. // Shft Ctrl Left click drag - Erase stroke on this sketch alone. All other sketches are deemed uneditable while the shift key is depressed. // Right click and drag - Resize the shape isotropically // // The Select mode is not supported/defined by this class. // // .SECTION See Also // vtkWidgetEvent vtkWidgetEventTranslator #ifndef __vtkKWELightPaintbrushWidgetCallbackMapper_h #define __vtkKWELightPaintbrushWidgetCallbackMapper_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkKWEPaintbrushWidgetCallbackMapper.h" class VTKEdge_WIDGETS_EXPORT vtkKWELightPaintbrushWidgetCallbackMapper : public vtkKWEPaintbrushWidgetCallbackMapper { public: // Description: // Instantiate the class. static vtkKWELightPaintbrushWidgetCallbackMapper *New(); // Description: // Standard macros. vtkTypeMacro(vtkKWELightPaintbrushWidgetCallbackMapper,vtkKWEPaintbrushWidgetCallbackMapper); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Overriding the superclass method virtual void Bindings(); protected: vtkKWELightPaintbrushWidgetCallbackMapper() {}; ~vtkKWELightPaintbrushWidgetCallbackMapper() {}; private: vtkKWELightPaintbrushWidgetCallbackMapper(const vtkKWELightPaintbrushWidgetCallbackMapper&); //Not implemented void operator=(const vtkKWELightPaintbrushWidgetCallbackMapper&); //Not implemented }; #endif /* __vtkKWELightPaintbrushWidgetCallbackMapper_h */ vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushDataStatistics.h0000644000175000017500000000640311363410610023675 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushDataStatistics - Compute volume of a vtkKWEPaintbrushData // .SECTION Description // Computes the volume of a grayscale or binary brush data. Simply use the // class as // // vtkKWEPaintbrushDataStatistics *algo = vtkKWEPaintbrushDataStatistics::New(); // algo->SetInput( paintbrushData ); // double volume = algo->GetVolume(); // // .SECTION See Also #ifndef __vtkKWEPaintbrushDataStatistics_h #define __vtkKWEPaintbrushDataStatistics_h #include "vtkAlgorithm.h" #include "VTKEdgeConfigure.h" class vtkKWEPaintbrushData; class vtkContourFilter; class vtkImageConstantPad; class vtkTriangleFilter; class vtkMassProperties; class vtkKWEPaintbrushStencilData; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushDataStatistics : public vtkAlgorithm { public: // Description: // Standard VTK methods. static vtkKWEPaintbrushDataStatistics *New(); vtkTypeRevisionMacro(vtkKWEPaintbrushDataStatistics, vtkAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set a paintbrush data as input virtual void SetInput( vtkKWEPaintbrushData * ); // Description: // see vtkAlgorithm for details virtual int ProcessRequest(vtkInformation*, vtkInformationVector**, vtkInformationVector*); // Description: // Get the volume double GetVolume(); // Description: // Get the overlapped volume between two binary paintbrush data's. I would // have added the implementation for grayscale ones too, but its too // complicated to do that. // It is assumed that both the stencils have the same specing and origin, // although they need not have the same extent. static double GetOverlapVolume( vtkKWEPaintbrushStencilData *, vtkKWEPaintbrushStencilData * ); protected: vtkKWEPaintbrushDataStatistics(); ~vtkKWEPaintbrushDataStatistics(); // Description: // see vtkAlgorithm for docs. virtual int FillInputPortInformation(int, vtkInformation*); virtual int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); vtkContourFilter * ContourFilter; vtkImageConstantPad * PadFilter; vtkTriangleFilter * TriangleFilter; vtkMassProperties * MassProperties; double Volume; private: vtkKWEPaintbrushDataStatistics( const vtkKWEPaintbrushDataStatistics& ); void operator=(const vtkKWEPaintbrushDataStatistics&); }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushDrawing.h0000644000175000017500000002214511521221413022342 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushDrawing - a list of Sketches // .SECTION Description // vtkKWEPaintbrushDrawing represents and provides methods to manipulate a list of // Sketches. The list is unsorted and duplicate entries are not prevented. // // .SECTION see also // vtkKWEPaintbrushSketch #ifndef __vtkKWEPaintbrushDrawing_h #define __vtkKWEPaintbrushDrawing_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkCollection.h" #include "vtkDataObject.h" #include "vtkKWEPaintbrushSketch.h" // For inline methods #include "vtkImageData.h" class vtkKWEPaintbrushOperation; class vtkKWEPaintbrushPropertyManager; class vtkKWEPaintbrushLabelData; class vtkKWEPaintbrushWidget; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushDrawing : public vtkDataObject { //BTX friend class vtkKWEPaintbrushSketch; friend class vtkKWEPaintbrushRepresentation; //ETX public: static vtkKWEPaintbrushDrawing *New(); vtkTypeRevisionMacro(vtkKWEPaintbrushDrawing,vtkDataObject); virtual void PrintSelf(ostream& os, vtkIndent indent); // Description: // Add an Sketch to the list. void AddItem(vtkKWEPaintbrushSketch *a); // Description: // Add a new sketch to the list. Also initialize it with the usual parameters. // Returns the newly added sketch. vtkKWEPaintbrushSketch * AddItem(); // Description: // Remove all sketches in the drawing. void RemoveAllItems(); // Description: // Remove the specified sketch. Returns 1 if the item was removed. int RemoveItem( vtkKWEPaintbrushSketch * ); // Description: // Get the Nth sketch from the drawing. vtkKWEPaintbrushSketch *GetItem(int i); // Description: // Get the sketch with the specified label. Note that is method is relevant, // only if our representation is a LabelMap. // Returns NULL if there is no sketch with that label. vtkKWEPaintbrushSketch *GetItemWithLabel( vtkKWEPaintbrushEnums::LabelType ); // Is a sketch present ? Returns 1 if yes. int IsItemPresent( vtkKWEPaintbrushSketch * s ); // Description: // Set the image we are painting on. void SetImageData( vtkImageData * ); vtkGetObjectMacro( ImageData, vtkImageData ); // Description: // Set the LabelMap we are painting on to an existing labelmap. Set // before calling InitializeData. Only used if the representation type // is set to labelmap. vtkSetObjectMacro( LabelMap, vtkImageData ); vtkGetObjectMacro( LabelMap, vtkImageData ); // Description: // Set the PaintbrushData for the drawing. You must use this method only // if your data is a label map. If not, the data of each sketch is managed // independently and you should set the PaintbrushData on each sketch // seperately using the method above. void SetPaintbrushData( vtkKWEPaintbrushLabelData * ); // Description: // Set/Get the paintbrush data that we've sketched out. This is the cumlated // paintbrush data of all sketches. vtkGetObjectMacro( PaintbrushData, vtkKWEPaintbrushData ); // Description: // Initialize the drawing data based on the image metadata. void InitializeData(); // Description: // There are two ways to initialize sketches in a drawing. They may be // initialized individually using vtkKWEPaintbrushSketch::Initialize(..) // or // they may be initliazed more efficiently by the following method. This // method is more efficient if you have several sketches in your drawing // since, the drawing data is parsed for seperation into sketches only // once. Note that you must have a collection of sketches in this drawing. // Then we parse the paintbrush label data for labels that correspond to // each of those sketches and initialize those sketches with the initial // label map data as a stroke. void InitializeSketches(); // Description: // Unlike the above method, this method creates sketches for each label // prsent in the label map. The subtle difference is that InitializeSketches // initializes existing sketches in the drawing from the labels that // these sketches represent that may be present in the label map. CreateSketches // will read in a label map and create a set of sketches for you based on // any label that is present in the label map. void CreateSketches(); // Description: // Set the PaintbrushOperation void SetPaintbrushOperation( vtkKWEPaintbrushOperation * ); vtkGetObjectMacro( PaintbrushOperation, vtkKWEPaintbrushOperation ); // Description: // Add and delete a stroke. A stroke can hold multiple points. // If type is 1, the stroke is a positive (draw) stroke. If type // is 0, its a negative (erase) stroke. // You can also add a new stroke with your own paintbrush data as input, // let's say you wanted to compose an external segmentation to the // existing ones. virtual int AddNewStroke( int n, int type = vtkKWEPaintbrushEnums::Draw, vtkKWEPaintbrushData *initialization = NULL); //BTX // Description: // Retrieve an instance of this class from an information object. static vtkKWEPaintbrushDrawing* GetData(vtkInformation* info); static vtkKWEPaintbrushDrawing* GetData(vtkInformationVector* v, int i=0); //ETX // Description: // Data objects are composite objects and need to check each part for MTime. // The information object also needs to be considered. virtual unsigned long GetMTime(); // Description: // Return the number of sketches in the drawing. int GetNumberOfItems() { return this->Collection->GetNumberOfItems(); } // Description: // Get the index of the item in the list. Returns -1 if the item // isn't present. int GetIndexOfItem( vtkKWEPaintbrushSketch * s ); // Description: // The user must set this using the class. For details, see documentation of // vtkKWEPaintbrushEnums::BrushType. vtkSetMacro(Representation, int); vtkGetMacro(Representation, int); virtual void SetRepresentationToGrayscale() { this->SetRepresentation(vtkKWEPaintbrushEnums::Grayscale); } virtual void SetRepresentationToBinary() { this->SetRepresentation(vtkKWEPaintbrushEnums::Binary); } virtual void SetRepresentationToLabel() { this->SetRepresentation(vtkKWEPaintbrushEnums::Label); } // Description: // You can set an upper limit on the number of sketches that can be added // to the drawing. By default there is no limit. // As a caveat, note that if you already have more sketches than the limit, // setting this ivar will not remove any existing sketches. vtkSetMacro( MaximumNumberOfSketches, int ); vtkGetMacro( MaximumNumberOfSketches, int ); // Description: // Collapse the history of all sketches in the drawing. This simply calls // the CollapseHistory() method for each sketch in this drawing. virtual void CollapseHistory(); // Description: // Shallow copy. This copies the data, but not any of the pipeline // connections. virtual void ShallowCopy(vtkDataObject *src); // Description: // INTERNAL - Do not use. // Get the property manager, used to assign unique colors etc. vtkGetObjectMacro( PaintbrushPropertyManager, vtkKWEPaintbrushPropertyManager ); // Description: // Compose strokes from all sketches together. This will visit each stroke // on the stack from each sketch. Sort them by MTime. Then compose them all // together. void ComposeStrokes(); protected: vtkKWEPaintbrushDrawing(); ~vtkKWEPaintbrushDrawing(); vtkKWEPaintbrushData *PaintbrushData; vtkImageData *ImageData; vtkImageData *LabelMap; vtkKWEPaintbrushOperation *PaintbrushOperation; vtkKWEPaintbrushPropertyManager *PaintbrushPropertyManager; vtkCollection *Collection; int Representation; int MaximumNumberOfSketches; // After setting the ImageData on which to draw the strokes, allocate // paintbrush data of the appropriate size. virtual void AllocatePaintbrushData(); // Description: // Helper function to assign a unique label to a newly created sketch. This // makes sense only if the representation is "Label" void AssignUniqueLabelToSketch( vtkKWEPaintbrushSketch *s ); // Description: // This method will be invoked from the widget during user interaction virtual void AddShapeToCurrentStroke( int n, double p[3] ); private: vtkKWEPaintbrushDrawing(const vtkKWEPaintbrushDrawing&); // Not implemented. void operator=(const vtkKWEPaintbrushDrawing&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Widgets/CMakeLists.txt0000644000175000017500000001553011501735401020207 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # -------------------------------------------------------------------------- # Sources # SET(KIT_SRCS vtkKWEAbstractPaintbrushWidget.cxx vtkKWEBoundingBoxRepresentation2D.cxx vtkKWEBoundingBoxWidget2D.cxx vtkKWEPaintbrushAnnotationRepresentation.cxx vtkKWEPaintbrushAnnotationWidget.cxx vtkKWEPaintbrushBlend.cxx vtkKWEPaintbrushData.cxx vtkKWEPaintbrushDataStatistics.cxx vtkKWEPaintbrushDrawing.cxx vtkKWEPaintbrushDrawingStatistics.cxx vtkKWEPaintbrushGrayscaleData.cxx vtkKWEPaintbrushHighlightActors.cxx vtkKWEPaintbrushLabelData.cxx vtkKWEPaintbrushMergeSketches.cxx vtkKWEPaintbrushOperation.cxx vtkKWEPaintbrushProperty.cxx vtkKWEPaintbrushPropertyManager.cxx vtkKWEPaintbrushRepresentation.cxx vtkKWEPaintbrushRepresentation2D.cxx vtkKWEPaintbrushRepresentationGrayscale2D.cxx vtkKWEPaintbrushSelectionWidget.cxx vtkKWEPaintbrushSelectionRepresentation.cxx vtkKWEPaintbrushSelectionRepresentation2D.cxx vtkKWEPaintbrushShape.cxx vtkKWEPaintbrushShapeBox.cxx vtkKWEPaintbrushShapeEllipsoid.cxx vtkKWEPaintbrushSketch.cxx vtkKWEPaintbrushStencilData.cxx vtkKWEPaintbrushStroke.cxx vtkKWEPaintbrushUtilities.cxx vtkKWEPaintbrushWidget.cxx vtkKWEPaintbrushWidgetCallbackMapper.cxx vtkKWELightPaintbrushWidgetCallbackMapper.cxx vtkKWEPaintbrushTesting.cxx vtkKWEStencilContourFilter.cxx vtkKWEVoxelAlignedImageActorPointPlacer.cxx vtkKWEWidgetGroup.cxx ) SET_SOURCE_FILES_PROPERTIES( vtkKWEAbstractPaintbrushWidget.cxx vtkKWEPaintbrushData.cxx vtkKWEPaintbrushRepresentation.cxx vtkKWEPaintbrushShape.cxx ABSTRACT ) IF(VTKEdge_USE_ITK) SET(KIT_SRCS ${KIT_SRCS} vtkKWEITKConnectedThresholdPaintbrushOperation.cxx vtkKWEITKConfidenceConnectedPaintbrushOperation.cxx vtkKWEITKImage.cxx vtkKWEITKImageToStencilFilter.cxx vtkKWEITKPaintbrushOperation.cxx vtkKWEITKPaintbrushExtractConnectedComponents.cxx ) SET_SOURCE_FILES_PROPERTIES( vtkKWEITKImageToStencilFilter.cxx vtkKWEITKPaintbrushOperation.cxx ABSTRACT ) ENDIF(VTKEdge_USE_ITK) # -------------------------------------------------------------------------- # Include dirs # # If we are in a tree that includes the ITK source dir already, then # we need to explicitly set the ITK include paths. We could let the # super-project takes care of it (since it is the one that bundles us # with ITK), but including ITK paths can bring many extra-paths that could # push the limit of the compiler. Let's do it only when needed. IF(VTKEdge_USE_ITK AND ITK_SOURCE_DIR) INCLUDE(${ITK_SOURCE_DIR}/Utilities/itkThirdParty.cmake) INCLUDE(${ITK_SOURCE_DIR}/itkIncludeDirectories.cmake) INCLUDE_DIRECTORIES( ${ITK_INCLUDE_DIRS_BUILD_TREE} ${ITK_INCLUDE_DIRS_BUILD_TREE_CXX} ${ITK_INCLUDE_DIRS_SYSTEM} ) ENDIF(VTKEdge_USE_ITK AND ITK_SOURCE_DIR) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) # ----------------------------------------------------------------------------- # Configure the vtkKWEPaintbrushEnums header. # ----------------------------------------------------------------------------- set(VTKEdge_PAINTBRUSH_LABEL_TYPE VTK_UNSIGNED_SHORT CACHE STRING "The scalar type used for paintbrush label data. This impacts memory requirements for the label map image. Valid values are VTK_CHAR, VTK_UNSIGNED_CHAR, VTK_SHORT, VTK_UNSIGNED_SHORT.") mark_as_advanced(VTKEdge_PAINTBRUSH_LABEL_TYPE) set(VTKEdge_PAINTBRUSH_LABEL_TYPEDEF) set(typedef_VTK_CHAR "char") set(typedef_VTK_UNSIGNED_CHAR "unsigned char") set(typedef_VTK_SHORT "short") set(typedef_VTK_UNSIGNED_SHORT "unsigned short") set(VTKEdge_PAINTBRUSH_LABEL_TYPEDEF ${typedef_${VTKEdge_PAINTBRUSH_LABEL_TYPE}}) if(NOT VTKEdge_PAINTBRUSH_LABEL_TYPEDEF) message(SEND_ERROR "VTKEdge_PAINTBRUSH_LABEL_TYPE has been set to an invalid value. Please choose from VTK_CHAR, VTK_UNSIGNED_CHAR, VTK_SHORT, VTK_UNSIGNED_SHORT") endif(NOT VTKEdge_PAINTBRUSH_LABEL_TYPEDEF) configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/vtkKWEPaintbrushEnums.h.in" "${PROJECT_BINARY_DIR}/vtkKWEPaintbrushEnums.h") set(KIT_SRCS ${KIT_SRCS} "${PROJECT_BINARY_DIR}/vtkKWEPaintbrushEnums.h") # -------------------------------------------------------------------------- # Build the library # set(KIT_LIBS vtkWidgets vtkRendering vtkFiltering vtkCommon vtkImaging ) IF(VTKEdge_USE_ITK) set (KIT_LIBS ${KIT_LIBS} ITKCommon ITKBasicFilters ) ENDIF(VTKEdge_USE_ITK) add_library(vtkKWEWidgets ${KIT_SRCS}) target_link_libraries(vtkKWEWidgets ${KIT_LIBS}) # -------------------------------------------------------------------------- # Testing if(BUILD_TESTING) add_subdirectory(Testing) endif(BUILD_TESTING) # ----------------------------------------------------------------------------- # Installation # ----------------------------------------------------------------------------- if(NOT VTKEdge_INSTALL_NO_LIBRARIES) install_targets( ${VTKEdge_INSTALL_LIB_DIR} RUNTIME_DIRECTORY ${VTKEdge_INSTALL_BIN_DIR} vtkKWEWidgets ) endif(NOT VTKEdge_INSTALL_NO_LIBRARIES) IF(VTKEdge_USE_ITK) SET(KIT_HEADERS itkConfidenceConnectedMiniPipelineFilter.h itkConfidenceConnectedMiniPipelineFilter.txx itkImageToVTKImageFilter.h itkImageToVTKImageFilter.txx itkVTKImageToImageFilter.h itkVTKImageToImageFilter.txx vtkKWEITKFilterModuleBase.h vtkKWEITKFilterModule.h vtkKWEITKFilterModuleStencilOutput.h vtkKWEITKFilterModuleStencilOutput.txx vtkKWEITKPaintbrushFilterModule.h) ENDIF(VTKEdge_USE_ITK) if(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) install_files(${VTKEdge_INSTALL_INCLUDE_DIR} .h ${KIT_SRCS}) # Need to install header and .txx files without corresponding .cxx install(FILES ${KIT_HEADERS} DESTINATION include/${PROJECT_NAME}) endif(NOT VTKEdge_INSTALL_NO_DEVELOPMENT) # ----------------------------------------------------------------------------- # This make it easy for other projects to get the list of files etc. in this # kit. # ----------------------------------------------------------------------------- include(${VTK_CMAKE_DIR}/vtkExportKit.cmake) vtk_export_kit2("KWEWidgets" "KWEWIDGETS" ${CMAKE_CURRENT_BINARY_DIR} "${KIT_SRCS}") vtkedge-0.2.0~20110819/Widgets/Examples/0000755000175000017500000000000011630434665017234 5ustar mathieumathieuvtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushSelectionWidget.h0000644000175000017500000001402511363410610024041 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushSelectionWidget #ifndef __vtkKWEPaintbrushSelectionWidget_h #define __vtkKWEPaintbrushSelectionWidget_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkKWEAbstractPaintbrushWidget.h" #include class vtkKWEPaintbrushSelectionRepresentation; class vtkKWEPaintbrushSketch; class vtkKWEWidgetGroup; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushSelectionWidget : public vtkKWEAbstractPaintbrushWidget { public: // Description: // Instantiate this class. static vtkKWEPaintbrushSelectionWidget *New(); // Description: // Standard methods for a VTK class. vtkTypeRevisionMacro(vtkKWEPaintbrushSelectionWidget,vtkKWEAbstractPaintbrushWidget); void PrintSelf(ostream& os, vtkIndent indent); // Description: // The method for activiating and deactiviating this widget. This method // must be overridden because it is a composite widget and does more than // its superclass' vtkAbstractWidget::SetEnabled() method. virtual void SetEnabled(int); // Description: // Specify an instance of vtkWidgetRepresentation used to represent this // widget in the scene. Note that the representation is a subclass of vtkProp // so it can be added to the renderer independent of the widget. void SetRepresentation(vtkKWEPaintbrushSelectionRepresentation *r); // Description: // Method to satisfy the superclass API. // Create the default vtkKWEPaintbrushRepresentation if one is not set. virtual void CreateDefaultRepresentation(); // Description: // The widget by default supports drag and drop merge of sketches. You // may enable/disable this vtkSetMacro( EnableDragAndDrop, int ); vtkGetMacro( EnableDragAndDrop, int ); vtkBooleanMacro( EnableDragAndDrop, int ); // Description: // Delete selected sketches. virtual void DeleteSelectedSketches(); // Description: // Merge sketches into supplied sketch. Old sketches //virtual void MergeSelectedSketches( vtkKWEPaintbrushSketch * s ); //BTX //virtual void RemoveSketches( std::vector< vtkKWEPaintbrushSketch * > ); //virtual void MergeSketchesInto( std::vector< vtkKWEPaintbrushSketch * >, // vtkKWEPaintbrushSketch *newSketch ); //ETX // Description: // Synchronize states etc. virtual void DeepCopy( vtkAbstractWidget * ); // Description: // INTERNAL - Do not use // To be used by the vtkKWEPaintbrushWidget to propagate Abort events from // the callback command, since this widget is meant to be used as a child // of vtkKWEPaintbrushWidget vtkGetObjectMacro( EventCallbackCommand, vtkCallbackCommand ); protected: vtkKWEPaintbrushSelectionWidget(); ~vtkKWEPaintbrushSelectionWidget(); // Description: // States //BTX enum { Disabled = 10000, BeginSelecting, EndSelecting, None }; //ETX // Description: // Callback interface to tie ends with the CallbackMapper for the events // invoked by this widget. Note the seperation of "Callbacks" and "Actions". // The callbacks are invoked in response to events from the // RenderWindowInteractor. They are then dispatched to the WidgetGroup, who // inturn calls the corresponding "Actions" on each of the widgets in the // group. // // As a rule of thumb, the mapping of "Callbacks" is to "Events" from the // Callbackmapper. The mapping of "Actions" is meant to be one pertinent // to the geometry changes on the widget's representation. // For instance a MouseMoveEvent should map to a "MoveCallback". This // can, depending on the state of the widget, trigger any of three Actions: // HoverAction, DrawAction, ResizeAction. // This is done, so that you can have multiple widgets, say a seed // widget drawn on 3 render windows and have them all synchronized, if they // belong to the same group. // static void BeginToggleSelectSketchCallback( vtkAbstractWidget* ); static void EndToggleSelectSketchCallback ( vtkAbstractWidget* ); static void DeleteSelectionCallback ( vtkAbstractWidget* ); static void MergeSelectionCallback ( vtkAbstractWidget* ); static void SelectAllSketchesCallback ( vtkAbstractWidget* ); static void UnSelectAllSketchesCallback ( vtkAbstractWidget* ); static void ToggleSelectAllSketchesCallback( vtkAbstractWidget* ); static void MoveCallback ( vtkAbstractWidget* ); // Description: // Geometric actions / states on that the representation responds to. int SelectSketchAction ( vtkKWEPaintbrushSelectionWidget *dispatcher); int UnselectSketchAction ( vtkKWEPaintbrushSelectionWidget *dispatcher); int SelectAllSketchesAction ( vtkKWEPaintbrushSelectionWidget *dispatcher); int UnSelectAllSketchesAction( vtkKWEPaintbrushSelectionWidget *dispatcher); int ReleaseSelectAction ( vtkKWEPaintbrushSelectionWidget *dispatcher); int DeleteSelectionAction ( vtkKWEPaintbrushSelectionWidget *dispatcher); int MergeSelectionAction ( vtkKWEPaintbrushSelectionWidget *dispatcher); int WidgetState; vtkKWEPaintbrushSketch * MergedSketch; int RemoveSketchesDuringMerge; int EnableDragAndDrop; private: vtkKWEPaintbrushSelectionWidget(const vtkKWEPaintbrushSelectionWidget&); //Not implemented void operator=(const vtkKWEPaintbrushSelectionWidget&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushSketch.h0000644000175000017500000002014611507576154022212 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushSketch // .SECTION Description // .SECTION See Also #ifndef __vtkKWEPaintbrushSketch_h #define __vtkKWEPaintbrushSketch_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkKWEPaintbrushEnums.h" #include "vtkObject.h" #include class vtkKWEPaintbrushOperation; class vtkKWEPaintbrushStroke; class vtkImageData; class vtkKWEPaintbrushData; class vtkKWEPaintbrushLabelData; class vtkKWEPaintbrushProperty; class vtkKWEPaintbrushDrawing; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushSketch : public vtkObject { //BTX friend class vtkKWEPaintbrushDrawing; friend class vtkKWEPaintbrushProperty; //ETX public: // Description: // Standard VTK methods static vtkKWEPaintbrushSketch *New(); vtkTypeRevisionMacro(vtkKWEPaintbrushSketch, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set/Get the operation. Must be set. virtual void SetPaintbrushOperation( vtkKWEPaintbrushOperation * ); vtkGetObjectMacro( PaintbrushOperation, vtkKWEPaintbrushOperation ); // Description: // Set/Get the image data over which the strokes are overlayed. This is the // background image. virtual void SetImageData( vtkImageData * ); vtkGetObjectMacro( ImageData, vtkImageData ); // Description: // Set/Get the paintbrush data that we've already sketched out. If one is // not set, the canvas will be created automatically for you. vtkGetObjectMacro( PaintbrushData, vtkKWEPaintbrushData ); virtual void SetPaintbrushData( vtkKWEPaintbrushData * ); // Description: // Initializes the datastructures, creates a canvas (vtkKWEPaintbrushData) if // one hasn't been set already. If called, it must be called only after the // operation and the ImageData have been set. virtual void Initialize(); // Description: // Alternate function signature for initializing the sketch. Must be called // only after the operation and ImageData and the label value have been set. // The former two will be automatically set if you have added this to the // drawing already. virtual void Initialize( vtkKWEPaintbrushLabelData * labelMap ); // Description: // See documentation of vtkKWEPaintbrushEnums::BrushType. vtkSetMacro(Representation, int); vtkGetMacro(Representation, int); virtual void SetRepresentationToGrayscale() { this->SetRepresentation(vtkKWEPaintbrushEnums::Grayscale); } virtual void SetRepresentationToBinary() { this->SetRepresentation(vtkKWEPaintbrushEnums::Binary); } virtual void SetRepresentationToLabel() { this->SetRepresentation(vtkKWEPaintbrushEnums::Label); } // Description: // This must be set if you are setting the representation to 'Label'. This // indicates the value in the label map that this sketch represents. vtkSetMacro( Label, vtkKWEPaintbrushEnums::LabelType ); vtkGetMacro( Label, vtkKWEPaintbrushEnums::LabelType ); // Description: // The sketch maintains a history of strokes made, to facilitate undo/redo // of edits. A larger history length implies more memory. A length of 0 // implies that no undo-redo functionality is possible. // Defaults to 4. // If you choose to set this, do so once before using the sketch. DO NOT // change it midway. vtkSetClampMacro( HistoryLength, int, 0, 10 ); vtkGetMacro( HistoryLength, int ); // Description: // Get the property of the sketch. You may use this to change colors etc. vtkGetObjectMacro( PaintbrushProperty, vtkKWEPaintbrushProperty ); // Description: // Add a new stroke. // // The first argument specifies if it is a draw or an erase stroke. // // The second argument is optional. You can initialize this new stroke // data, let's say you wanted to compose an external segmentation to the // existing ones. Your initialization will automatically be added to the // sketch's history. // // The third argument is optional. By default, each stroke has extents that // match that of the canvas image. Although there are efficient // datastructures to more compactly represent this, it can induce some // memory drag. If you are dead sure that your stroke is going to have // certain bounding extents, you can set this. The widgets internally use // this under certain conditions to speed things up. virtual int AddNewStroke( int polarity = vtkKWEPaintbrushEnums::Draw, vtkKWEPaintbrushData * initialization = NULL, int *extents = NULL, bool forceMutable = false ); // Description: // Add another sketch's data to this sketch void Add( vtkKWEPaintbrushSketch * sketch ); // Description: // Delete the last added stroke virtual int DeleteLastStroke(); // Description: // Used to maintain the undo/redo functionality.. Pop sequence pops a // sequence out of the list during undo. Push pushes the last undone // sequence back into the list. (essentially does a redo). virtual int PopStroke(); virtual int PushStroke(); // Description: // Strokes between start and end, both inclusive, are erased. virtual void EraseStrokes( int start, int end ); // Description: // This method can be used to copy a sketch from a source extent to a // target extent. Only voxels that belong to this sketch will be copied // over. Use cases for this method are slice by slice propagation of a // sketch. void CopySketchFromExtentToExtent(int sourceExtent[6], int targetExtent[6]); // Description: // See vtkObject for doc virtual unsigned long GetMTime(); // Description: // INTERNAL - Do not use. // This method merges strokes from start to end. virtual void ComposeStrokes(); protected: vtkKWEPaintbrushSketch(); ~vtkKWEPaintbrushSketch(); vtkKWEPaintbrushOperation *PaintbrushOperation; vtkKWEPaintbrushData *PaintbrushData; vtkKWEPaintbrushProperty *PaintbrushProperty; vtkImageData *ImageData; int CurrentStroke; int Representation; int HistoryLength; vtkKWEPaintbrushDrawing *PaintbrushDrawing; // This is used only if our sketch's representation is of type: Label vtkKWEPaintbrushEnums::LabelType Label; // Description: // INTERNAL - Do not use. // Invoked by a user draw/erase interaction. // Adds a shape to the current stroke at position "p" virtual void AddShapeToCurrentStroke( double p[3], vtkKWEPaintbrushData * auxData = NULL); // Description: // By default, the sketch's extents will be same as that of the canvas, // ImageData that's set as input. You should never need to explicitly // call this method, but if called, must be called after Initialize(). virtual void AllocatePaintbrushData(); // Description: // Collapses the history of the sketch. This does not affect the history // length. This simply collapses all existing history. void CollapseHistory(); private: vtkKWEPaintbrushSketch(const vtkKWEPaintbrushSketch&); //Not implemented void operator=(const vtkKWEPaintbrushSketch&); //Not implemented // Mutability of the sketch. This is set by the PaintbrushProperty. void SetMutable( int m ); //BTX // Set of strokes contained by this sketch (ordered by time) vtkstd::vector Strokes; // Description: // Get all the strokes upto the current stroke. void GetStrokes(vtkstd::vector< vtkKWEPaintbrushStroke * > &strokes); //ETX }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushProperty.h0000644000175000017500000001503611521051333022576 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushProperty // .SECTION Description #ifndef __vtkKWEPaintbrushProperty_h #define __vtkKWEPaintbrushProperty_h #include "VTKEdgeConfigure.h" #include "vtkObject.h" class vtkKWEPaintbrushSketch; class vtkKWEPaintbrushDrawing; class vtkProperty; class vtkKWEPaintbrushPropertyManager; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushProperty : public vtkObject { //BTX friend class vtkKWEPaintbrushSketch; friend class vtkKWEPaintbrushBlend; friend class vtkKWEPaintbrushRepresentationGrayscale2D; friend class vtkKWEPaintbrushPropertyManager; friend class vtkKWEPaintbrushSelectionRepresentation; friend class vtkKWEPaintbrushHighlightActors; //ETX public: vtkTypeRevisionMacro(vtkKWEPaintbrushProperty,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // A drawing is always associated with a paintbrush sketch. A // vtkKWEPaintbrushSketch upon creation will automatically be assigned a // default property internally. You can, using this method, query the sketch // to which this property is assigned. vtkGetObjectMacro( PaintbrushSketch, vtkKWEPaintbrushSketch ); // Description: // Set a unique identifier string. This may be rendered as annotations etc. vtkSetStringMacro( Identifier ); vtkGetStringMacro( Identifier ); // Description: // Set/Get the object's opacity. 1.0 is totally opaque and 0.0 is completely // transparent. void SetOpacity( double o ); double GetOpacity(); // Description: // Set the visibility of the sketch vtkSetMacro( Visibility, int ); vtkGetMacro( Visibility, int ); vtkBooleanMacro( Visibility, int ); // Description: // Set/Get the width of a Line. The width is expressed in screen units. // This is only implemented for OpenGL. The default is 1.0. void SetLineWidth( float ); vtkGetMacro( LineWidth, float ); // Description: // Get the color of the property. Colors are for now, auto assigned to give // the most pleasing appearance, and as far as possible ensure that colors // for each segmentation are unique. Note that the values are normalized to // [0-1] when the arguments passed in are double. void GetColor(double rgb[3]); void GetColor(unsigned char rgb[3]); double *GetColor(); // Description: // Set the color of the property. Colors are for now, auto assigned to give // the most pleasing appearance, and as far as possible ensure that colors // for each segmentation are unique. The moment you start assign a color to // any property in a drawing the property manager will stop autoassigning // "quasi-unique" colors. Note that the values are normalized to [0-1]. void SetColor(double rgb[3]); // Description: // Return this object's modified time. virtual unsigned long GetMTime(); //BTX enum HighlightTypeEnum { StippledInvertedHighlight, ThickHighlight, ColorHighlight }; //ETX // Description: // Three highlight modes are allowed. // 1. Stippled inverted highlight looks better when you have an overlay, as // with vtkKWEPaintbrushRepresentation2D. // 2. ThickHighlight looks better when you render the brushdata as contour // as is done in vtkKWEPaintbrushRepresentationGrayscale2D // 3. Color Highlighting of the edges looks nice on both. Just make sure // that you don't assign the same color as the highlight assigned color // to the sketches you draw or you'll have trouble making out that its // highlighted. Yellow is the default color Highlight. // ColorHighlight is the default HighlightType. vtkSetMacro( HighlightType, int ); vtkGetMacro( HighlightType, int ); // Description: // Factor by which the highlighted lines should thicken when a sketch is // highlighted. Default is 2.0 (ie. the lines will appear twice as thick // if highlighted). Note that this applies only if our highlight mode is // ThickHighlight. vtkSetClampMacro( HighlightThickness, double, 1.0, 10.0 ); vtkGetMacro( HighlightThickness, double ); // Description: // HighlightColor. // The default HighlightColor is yellow. // This makes sense only if HighlightType is ColorHighlight vtkSetVector3Macro( HighlightColor, double ); vtkGetVector3Macro( HighlightColor, double ); // Description: // Are we Highlighted ? vtkGetMacro( Highlight, int ); // Description: // Sketches can be deemed immutable or mutable. An immutable sketch cannot // be modified by *user* edits. By default all sketches are mutable. void SetMutable( int ); virtual int GetMutable(); protected: static vtkKWEPaintbrushProperty *New( vtkKWEPaintbrushSketch * ); static vtkKWEPaintbrushProperty *New(); vtkKWEPaintbrushProperty(); ~vtkKWEPaintbrushProperty(); // Description: // Highlight ? void SetHighlight( int ); vtkBooleanMacro ( Highlight, int ); // Get the internal property. vtkGetObjectMacro( Property, vtkProperty ); vtkProperty * Property; // Description: // Has the user specified a color. If this is true, the property manager will // stop autoassigning "quasi-unique" colors. bool HasUserSpecifiedColorOverride(); // Description: void SetColorInternal( double rgb[3] ); // Description: void SetInteractionEnabled(int i); private: vtkKWEPaintbrushProperty(const vtkKWEPaintbrushProperty&); // Not implemented. void operator=(const vtkKWEPaintbrushProperty&); // Not implemented. vtkKWEPaintbrushSketch * PaintbrushSketch; int Mutable; char * Identifier; bool UserSpecifiedColorOverride; int Highlight; float LineWidth; int HighlightType; double HighlightThickness; double Color[3]; int Visibility; int InteractionEnabled; // Used when HighlightType is ColorHighlight double HighlightColor[3]; }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushStroke.cxx0000644000175000017500000003326111567177014022613 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2008 Kitware, Inc. // // VTKEdge may be used under the terms of the GNU General Public License // version 3 as published by the Free Software Foundation and appearing in // the file LICENSE.txt included in the top level directory of this source // code distribution. Alternatively you may (at your option) use any later // version of the GNU General Public License if such license has been // publicly approved by Kitware, Inc. (or its successors, if any). // // VTKEdge is distributed "AS IS" with NO WARRANTY OF ANY KIND, INCLUDING // THE WARRANTIES OF DESIGN, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR // PURPOSE. See LICENSE.txt for additional details. // // VTKEdge is available under alternative license terms. Please visit // vtkedge.org or contact us at kitware@kitware.com for further information. // //============================================================================= #include "vtkKWEPaintbrushStroke.h" #include "vtkObjectFactory.h" #include "vtkImageStencilData.h" #include "vtkKWEPaintbrushData.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkImageData.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushShape.h" vtkCxxRevisionMacro(vtkKWEPaintbrushStroke, "$Revision: 3550 $"); vtkStandardNewMacro(vtkKWEPaintbrushStroke); vtkCxxSetObjectMacro(vtkKWEPaintbrushStroke,PaintbrushOperation, vtkKWEPaintbrushOperation); vtkCxxSetObjectMacro(vtkKWEPaintbrushStroke,PaintbrushData,vtkKWEPaintbrushData); //---------------------------------------------------------------------- vtkKWEPaintbrushStroke::vtkKWEPaintbrushStroke() { this->PaintbrushOperation = NULL; this->PaintbrushData = NULL; this->ImageData = NULL; this->Internals = new vtkKWEPaintbrushStrokeInternals; this->Extent[0] = -1; this->Extent[1] = 0; this->Extent[2] = -1; this->Extent[3] = 0; this->Extent[4] = -1; this->Extent[5] = 0; this->Representation = vtkKWEPaintbrushEnums::Binary; this->Tolerance = 1e-4; this->Label = 1; this->DrawTime = this->GetMTime(); } //---------------------------------------------------------------------- vtkKWEPaintbrushStroke::~vtkKWEPaintbrushStroke() { this->SetPaintbrushData(NULL); // Delete the internals. for (unsigned int i=0; iInternals->Node.size(); i++) { delete this->Internals->Node[i]; } this->Internals->Node.clear(); delete this->Internals; this->SetPaintbrushOperation(NULL); this->SetImageData(NULL); } //---------------------------------------------------------------------- void vtkKWEPaintbrushStroke::SetImageData( vtkImageData * imageData ) { if (this->ImageData != imageData) { vtkImageData * var = this->ImageData; this->ImageData = imageData; if (this->ImageData != NULL) { this->ImageData->Register(this); } if (var != NULL) { var->UnRegister(this); } this->Modified(); } if (this->ImageData) { this->Allocate(); } } //---------------------------------------------------------------------- int vtkKWEPaintbrushStroke::AddShapeAtPosition( double p[3], vtkKWEPaintbrushData * auxiliaryData1, vtkKWEPaintbrushData * auxiliaryData2) { if (!this->PaintbrushOperation) { vtkErrorMacro(<< "PaintbrushOperation must be set prior to use"); return 0; } if (!this->PaintbrushData) { vtkErrorMacro(<< "PaintbrushData must be allocated before use"); return 0; } if (!(this->Internals->State == vtkKWEPaintbrushEnums::Draw || this->Internals->State == vtkKWEPaintbrushEnums::Erase)) { return 0; } // Check if the point is already in the sequence for (unsigned int i=0; iInternals->Node.size(); i++) { if ( fabs(this->Internals->Node[i]->WorldPosition[0] - p[0]) < this->Tolerance && fabs(this->Internals->Node[i]->WorldPosition[1] - p[1]) < this->Tolerance && fabs(this->Internals->Node[i]->WorldPosition[2] - p[2]) < this->Tolerance) { return 0; } } // Make sure that auxiliaryData1 and auxiliaryData2 aren't the same, so that // we may avoid adding twice needlessly. This could happen if the sketch // and the drawing share the same data (as is the case with label maps). vtkKWEPaintbrushData *auxData1 = auxiliaryData1; vtkKWEPaintbrushData *auxData2 = (auxiliaryData2 != auxiliaryData1) ? auxiliaryData2 : NULL; this->PaintbrushData->SetLabel(this->Label); if (auxData1) { auxData1->SetLabel(this->Label); } if (auxData2) { auxData2->SetLabel(this->Label); } // Add the a template stencil at the given point to the current stencil vtkKWEPaintbrushData * data; if (this->Representation == vtkKWEPaintbrushEnums::Binary) { data = vtkKWEPaintbrushStencilData::New(); } else if (this->Representation == vtkKWEPaintbrushEnums::Grayscale) { data = vtkKWEPaintbrushGrayscaleData::New(); } else { cerr << "ERROR: Unsupported paintbrush representation type." << std::endl; return 0; } data->SetLabel( this->Label ); // Get the paintbrush data filtered through the operation. This allows us // to support in-place smart filters etc.. vtkKWEPaintbrushEnums::OperationType op; // This operation may change the value of op. this->PaintbrushOperation->GetPaintbrushData(data, p, op); if( op == vtkKWEPaintbrushEnums::Replace ) { this->PaintbrushData->Replace(data); if (auxData1) { auxData1->Replace(data); } if (auxData2) { auxData2->Replace(data); } } else if( (this->Internals->State == vtkKWEPaintbrushEnums::Draw && op == vtkKWEPaintbrushEnums::Add) || (this->Internals->State == vtkKWEPaintbrushEnums::Erase && op == vtkKWEPaintbrushEnums::Subtract) ) { if (auxData1) { // Enable delta computation for the first time to compute detlas w.r.t // what's already there for the Undo/Redo stuff auxData1->SetComputeDelta(1); auxData1->Add(data); auxData1->SetComputeDelta(0); } if (auxData2) { auxData2->Add(data); } this->PaintbrushData->Add(data); // TODO Was InternalAdd before.. check } else if( (this->Internals->State == vtkKWEPaintbrushEnums::Erase && op == vtkKWEPaintbrushEnums::Add) || (this->Internals->State == vtkKWEPaintbrushEnums::Draw && op == vtkKWEPaintbrushEnums::Subtract) ) { // This is bound to bite me later.. We need to have the stencilData // maintain a notion of a label map (at least a binary one). The deal is // that if you are using a StencilData, you need to add within a stroke // and subtract a negative stroke from your stroke manager... The point // being that for stencils, the stroke maintains the polarity. For the // grayscale data, the polarity is ingrained in the grayscale values // emitted by the shape, so the shape (who generates the image data for a // shape at a given position) maintains the polarity. TODO I know, this // is confusing.. I will rework this later // Stephen's comment: Seems like the following should be conditional on // grayscaleData not stencilData if (vtkKWEPaintbrushStencilData::SafeDownCast(this->PaintbrushData)) { if (auxData1) { // Enable delta computation for the first time to compute detlas w.r.t // what's already there for the Undo/Redo stuff auxData1->SetComputeDelta(1); auxData1->Subtract(data); auxData1->SetComputeDelta(0); } if (auxData2) { auxData2->Subtract(data); } this->PaintbrushData->Add(data); } else { this->PaintbrushData->Subtract(data); if (auxData1) { auxData1->Subtract(data); } if (auxData2) { auxData2->Subtract(data); } } } // Push the node position on the list. We use the node position to compare // and see if the shape moved since the last draw. This is done to avoid // multiple brush compositions at the same point, therby buying minor // speedups. vtkKWEPaintbrushStrokeNode *node = new vtkKWEPaintbrushStrokeNode; node->WorldPosition[0] = p[0]; node->WorldPosition[1] = p[1]; node->WorldPosition[2] = p[2]; this->Internals->Node.push_back(node); this->DrawTime = data->GetMTime(); // Update the draw time. data->Delete(); return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushStroke::Allocate() { if (this->PaintbrushData) { vtkErrorMacro( << "Error: vtkKWEPaintbrushStroke::Allocate called twice"); } if (!this->ImageData) { vtkErrorMacro( << "Set the image data on which the stencil is drawn" ); } if (this->Extent[1] < this->Extent[0]) { this->ImageData->GetExtent(this->Extent); } double spacing[3],origin[3]; this->ImageData->GetSpacing(spacing); this->ImageData->GetOrigin( origin ); if (this->Representation == vtkKWEPaintbrushEnums::Binary) { this->PaintbrushData = vtkKWEPaintbrushStencilData::New(); } else if (this->Representation == vtkKWEPaintbrushEnums::Grayscale) { this->PaintbrushData = vtkKWEPaintbrushGrayscaleData::New(); } this->PaintbrushData->SetExtent(this->Extent); this->PaintbrushData->SetSpacing(spacing); this->PaintbrushData->SetOrigin(origin); if (this->GetState() == vtkKWEPaintbrushEnums::Erase) { // Start with an inverted buffer for a Minkowski "min" if we are // using grayscale data. this->PaintbrushData->Allocate( this->Representation == vtkKWEPaintbrushEnums::Grayscale ? 255.0 : 0.0); } else { this->PaintbrushData->Allocate(); } this->PaintbrushData->SetLabel(this->Label); } //---------------------------------------------------------------------- void vtkKWEPaintbrushStroke::SetState( int state ) { this->Internals->State = static_cast(state); if (!this->PaintbrushOperation) { vtkErrorMacro( << "Set the paintbrush operation first "); return; } vtkKWEPaintbrushShape *s = this->PaintbrushOperation->GetPaintbrushShape(); if (!s) { vtkErrorMacro( << "Set the shape on the operation, prior to setting its " << "polarity !"); return; } s->SetPolarity(state); } //---------------------------------------------------------------------- void vtkKWEPaintbrushStroke::SetStateToDraw() { this->SetState( vtkKWEPaintbrushEnums::Draw ); } //---------------------------------------------------------------------- void vtkKWEPaintbrushStroke::SetStateToErase() { this->SetState( vtkKWEPaintbrushEnums::Erase ); } //---------------------------------------------------------------------- int vtkKWEPaintbrushStroke::GetState() { return this->Internals->State; } //---------------------------------------------------------------------- void vtkKWEPaintbrushStroke::SetExtent( int e[6] ) { if (this->Extent[0] != e[0] || this->Extent[1] != e[1] || this->Extent[2] != e[2] || this->Extent[3] != e[3] || this->Extent[4] != e[4] || this->Extent[5] != e[5]) { this->Extent[0] = e[0]; this->Extent[1] = e[1]; this->Extent[2] = e[2]; this->Extent[3] = e[3]; this->Extent[4] = e[4]; this->Extent[5] = e[5]; if (this->PaintbrushData) { this->PaintbrushData->SetExtent(this->Extent); } this->Modified(); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushStroke::SetRepresentation( int r ) { if (r == vtkKWEPaintbrushEnums::Label) { // Strokes can never be label maps. One stroke can represent only one // unique label. ie You can never edit two labels in one swoosh. this->SetRepresentation( vtkKWEPaintbrushEnums::Binary ); } if ( this->Representation != r && r != vtkKWEPaintbrushEnums::Label ) { this->Representation = r; this->Modified(); } } //---------------------------------------------------------------------- bool vtkKWEPaintbrushStroke::IsRecent( const vtkKWEPaintbrushStroke *a, const vtkKWEPaintbrushStroke *b ) { return (const_cast(a)->GetDrawTime() < const_cast(b)->GetDrawTime()); } //---------------------------------------------------------------------- void vtkKWEPaintbrushStroke::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Extent: (" << this->Extent[0] << "," << this->Extent[1] << "," << this->Extent[2] << "," << this->Extent[3] << "," << this->Extent[4] << "," << this->Extent[5] << ")" << endl; os << indent << "ImageData: "; if (this->ImageData) { os << indent << this->ImageData << endl; this->ImageData->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "None" << endl; } if (this->PaintbrushData) { os << indent << this->PaintbrushData << endl; this->PaintbrushData->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "None" << endl; } } vtkedge-0.2.0~20110819/Widgets/vtkKWEITKImage.cxx0000644000175000017500000003736211363410610020666 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEITKImage.h" #include "vtkObjectFactory.h" #include "vtkImageData.h" #include "vtkImageStencilData.h" #include "vtkImageIterator.h" #include "itkVTKImageToImageFilter.h" #include "itkImageToVTKImageFilter.h" #define ItkToVtkPipelineGetOutputMacro(type) \ { \ typedef itk::Image< type, 3 > InputImageType; \ typedef itk::ImageToVTKImageFilter< InputImageType > TType; \ if (TType * t = dynamic_cast< TType * >(exporter.GetPointer())) \ { \ return t->GetOutput(); \ } \ } #define VtkToItkPipelineGetOutputMacro(type) \ { \ typedef itk::Image< type, 3 > OutputImageType; \ typedef itk::VTKImageToImageFilter< OutputImageType > TType; \ if (TType * t = dynamic_cast< TType * >(exporter.GetPointer())) \ { \ return const_cast< OutputImageType * >(t->GetOutput()); \ } \ } /** \class ItkToVtkPipeline * This helper class will take care of instantiating the appropriate * ITK Export class corresponding to the actual pixel type of the * input image. */ template class ItkToVtkPipeline { public: typedef itk::Image< TPixel, 3 > ImageType; static void CreateExporter( itk::ImageBase<3>::Pointer & imageBase, itk::ProcessObject::Pointer & exporter ) { if (ImageType * image = dynamic_cast< ImageType * >( imageBase.GetPointer() )) { typedef itk::ImageToVTKImageFilter< ImageType > ExportFilterType; typedef typename ExportFilterType::Pointer ExportFilterPointer; ExportFilterPointer itkExporter = ExportFilterType::New(); itkExporter->SetInput( image ); exporter = itkExporter; } } static vtkImageData * GetOutput( itk::ProcessObject::Pointer & exporter ) { ItkToVtkPipelineGetOutputMacro( unsigned char ); ItkToVtkPipelineGetOutputMacro( char ); ItkToVtkPipelineGetOutputMacro( unsigned short ); ItkToVtkPipelineGetOutputMacro( short ); ItkToVtkPipelineGetOutputMacro( unsigned int ); ItkToVtkPipelineGetOutputMacro( int ); ItkToVtkPipelineGetOutputMacro( unsigned long ); ItkToVtkPipelineGetOutputMacro( long ); ItkToVtkPipelineGetOutputMacro( float ); ItkToVtkPipelineGetOutputMacro( double ); return NULL; } }; /** \class ItkToVtkPipeline * This helper class will take care of instantiating the appropriate * ITK Export class corresponding to the actual pixel type of the * input image. */ template class VtkToItkPipeline { public: typedef itk::Image< TPixel, 3 > ImageType; static void CreateExporter( vtkImageData * image, itk::ProcessObject::Pointer & exporter ) { typedef itk::VTKImageToImageFilter< ImageType > ExportFilterType; typedef typename ExportFilterType::Pointer ExportFilterPointer; ExportFilterPointer itkExporter = ExportFilterType::New(); itkExporter->SetInput( image ); exporter = itkExporter; } static itk::ImageBase<3> * GetOutput( itk::ProcessObject::Pointer & exporter ) { VtkToItkPipelineGetOutputMacro( unsigned char ); VtkToItkPipelineGetOutputMacro( char ); VtkToItkPipelineGetOutputMacro( unsigned short ); VtkToItkPipelineGetOutputMacro( short ); VtkToItkPipelineGetOutputMacro( unsigned int ); VtkToItkPipelineGetOutputMacro( int ); VtkToItkPipelineGetOutputMacro( unsigned long ); VtkToItkPipelineGetOutputMacro( long ); VtkToItkPipelineGetOutputMacro( float ); VtkToItkPipelineGetOutputMacro( double ); return NULL; } }; /** This helper macro will instantiate the pipeline creator for a particular * pixel type */ #define CreateItkToVtkPipelineMacro( PixelType ) \ ItkToVtkPipeline< PixelType >::CreateExporter( \ this->ItkImage, this->ItkToVtkExporter ); //---------------------------------------------------------------------------- vtkStandardNewMacro( vtkKWEITKImage ); vtkCxxRevisionMacro(vtkKWEITKImage, "$Revision: 1774 $"); //---------------------------------------------------------------------------- vtkKWEITKImage::vtkKWEITKImage() { this->InputMode = vtkKWEITKImage::NO_INPUT_SET; } //---------------------------------------------------------------------------- vtkKWEITKImage::~vtkKWEITKImage() { } //---------------------------------------------------------------------------- void vtkKWEITKImage::SetImage( itk::ImageBase< 3 > * image ) { if( this->InputMode == vtkKWEITKImage::ITK_IMAGE_INPUT && this->ItkImage == image) { return; } this->InputMode = vtkKWEITKImage::ITK_IMAGE_INPUT; this->ItkImage = image; this->Modified(); this->ItkImageTime.Modified(); } //---------------------------------------------------------------------------- void vtkKWEITKImage::SetImage( vtkImageData * image ) { if( this->InputMode == vtkKWEITKImage::VTK_IMAGE_INPUT && this->VtkImage == image) { return; } this->InputMode = vtkKWEITKImage::VTK_IMAGE_INPUT; this->VtkImage = image; this->Modified(); this->VtkImageTime.Modified(); } //---------------------------------------------------------------------------- void vtkKWEITKImage::SetImage( vtkImageStencilData * image ) { if( this->InputMode == vtkKWEITKImage::VTK_IMAGE_STENCIL_INPUT && this->VtkImageStencil == image) { return; } this->VtkImageStencil = image; this->InputMode = vtkKWEITKImage::VTK_IMAGE_STENCIL_INPUT; this->Modified(); this->VtkImageStencilTime.Modified(); } //---------------------------------------------------------------------------- vtkImageData * vtkKWEITKImage::GetVTKImage() { if (this->InputMode == ITK_IMAGE_INPUT && this->ItkImage) { if (this->VtkImageTime < this->ItkImageTime) { CreateItkToVtkPipelineMacro( unsigned char ); CreateItkToVtkPipelineMacro( char ); CreateItkToVtkPipelineMacro( unsigned short ); CreateItkToVtkPipelineMacro( short ); CreateItkToVtkPipelineMacro( unsigned int ); CreateItkToVtkPipelineMacro( int ); CreateItkToVtkPipelineMacro( unsigned long ); CreateItkToVtkPipelineMacro( long ); CreateItkToVtkPipelineMacro( float ); CreateItkToVtkPipelineMacro( double ); this->ItkToVtkExporter->Update(); this->VtkImage = ItkToVtkPipeline::GetOutput(this->ItkToVtkExporter); this->VtkImageTime.Modified(); } } else if (this->InputMode == VTK_IMAGE_STENCIL_INPUT && this->VtkImageStencil) { if (this->VtkImageTime < this->VtkImageStencilTime) { if (!this->VtkImage) { this->VtkImage = vtkImageData::New(); } vtkKWEITKImage::GetImageFromStencil( this->VtkImage, this->VtkImageStencil, 255, 0); this->VtkImageTime.Modified(); } } else if (this->InputMode == VTK_IMAGE_INPUT && this->VtkImage) { // No conversion to do :) } else { this->VtkImage = NULL; } return this->VtkImage; } //---------------------------------------------------------------------------- vtkKWEITKImage::ImageBaseType * vtkKWEITKImage::GetITKImage() { if (this->InputMode == ITK_IMAGE_INPUT && this->ItkImage) { // No conversion to do :) } else if (this->InputMode == VTK_IMAGE_STENCIL_INPUT && this->VtkImageStencil) { if (this->ItkImageTime < this->VtkImageStencilTime) { if (vtkImageData *image = this->GetVTKImage()) { switch (image->GetScalarType()) { vtkitkTemplateMacro( VtkToItkPipeline< VTK_TT >::CreateExporter( image, this->VtkToItkExporter) ); default: { vtkErrorMacro(<< "vtkitkTemplateMacro: Unknown ScalarType"); return NULL; } } this->ItkImage = VtkToItkPipeline::GetOutput(this->VtkToItkExporter); this->ItkImageTime.Modified(); } } } else if (this->InputMode == VTK_IMAGE_INPUT && this->VtkImage) { switch (this->VtkImage->GetScalarType()) { vtkitkTemplateMacro( VtkToItkPipeline::CreateExporter( this->VtkImage, this->VtkToItkExporter) ); default: { vtkErrorMacro(<< "vtkitkTemplateMacro: Unknown ScalarType"); return NULL; } } this->ItkImage = VtkToItkPipeline::GetOutput(this->VtkToItkExporter); this->ItkImageTime.Modified(); } else { this->ItkImage = NULL; } return this->ItkImage; } //---------------------------------------------------------------------------- vtkImageStencilData * vtkKWEITKImage::GetVTKImageStencilData() { if (this->InputMode == ITK_IMAGE_INPUT && this->ItkImage) { if (this->VtkImageStencilTime < this->ItkImageTime) { if (!this->VtkImageStencil) { this->VtkImageStencil = vtkImageStencilData::New(); } vtkKWEITKImage::GetStencilFromImage(this->GetVTKImage(), this->VtkImageStencil, 128); this->VtkImageStencilTime.Modified(); } } else if (this->InputMode == VTK_IMAGE_INPUT && this->VtkImage) { if (this->VtkImageStencilTime < this->VtkImageTime) { if (!this->VtkImageStencil) { this->VtkImageStencil = vtkImageStencilData::New(); } vtkKWEITKImage::GetStencilFromImage(this->GetVTKImage(), this->VtkImageStencil, 128); this->VtkImageStencilTime.Modified(); } } else if (this->InputMode == VTK_IMAGE_STENCIL_INPUT && this->VtkImageStencil) { // No conversion to do :) } else { this->VtkImageStencil = NULL; } return this->VtkImageStencil; } //---------------------------------------------------------------------------- vtkKWEITKImage::ITKScalarPixelType vtkKWEITKImage::GetITKScalarPixelType() { this->GetITKImage(); ITKScalarPixelType pixelType = itk::ImageIOBase::UCHAR; ImageBaseType * itkImageBase = this->ItkImage.GetPointer(); if( dynamic_cast< itk::Image< unsigned char, 3> * >( itkImageBase ) ) { pixelType = itk::ImageIOBase::UCHAR; } else if( dynamic_cast< itk::Image< char, 3> * >( itkImageBase ) ) { pixelType = itk::ImageIOBase::CHAR; } else if( dynamic_cast< itk::Image< short, 3> * >( itkImageBase ) ) { pixelType = itk::ImageIOBase::SHORT; } else if( dynamic_cast< itk::Image< unsigned short, 3> * >( itkImageBase ) ) { pixelType = itk::ImageIOBase::USHORT; } else if( dynamic_cast< itk::Image< int, 3> * >( itkImageBase ) ) { pixelType = itk::ImageIOBase::INT; } else if( dynamic_cast< itk::Image< unsigned int, 3> * >( itkImageBase ) ) { pixelType = itk::ImageIOBase::UINT; } else if( dynamic_cast< itk::Image< long, 3> * >( itkImageBase ) ) { pixelType = itk::ImageIOBase::LONG; } else if( dynamic_cast< itk::Image< unsigned long, 3> * >( itkImageBase ) ) { pixelType = itk::ImageIOBase::ULONG; } else if( dynamic_cast< itk::Image< float, 3> * >( itkImageBase ) ) { pixelType = itk::ImageIOBase::FLOAT; } else if( dynamic_cast< itk::Image< double, 3> * >( itkImageBase ) ) { pixelType = itk::ImageIOBase::DOUBLE; } return pixelType; } //---------------------------------------------------------------------------- int vtkKWEITKImage::GetVTKScalarPixelType() { return this->GetVTKImage()->GetScalarType(); } //---------------------------------------------------------------------------- void vtkKWEITKImage::GetImageFromStencil( vtkImageData *image, vtkImageStencilData *stencilData, unsigned char inVal, unsigned char outVal) { int extent[6]; stencilData->GetExtent( extent ); image->SetExtent( extent ); image->SetScalarTypeToUnsignedChar(); image->SetNumberOfScalarComponents(1); image->AllocateScalars(); // Fill image with zeroes vtkImageIterator< unsigned char > it(image, image->GetExtent()); while( !it.IsAtEnd() ) { unsigned char *inSI = it.BeginSpan(); unsigned char *inSIEnd = it.EndSpan(); while (inSI != inSIEnd) { *inSI = outVal; ++inSI; } it.NextSpan(); } vtkIdType increments[3]; image->GetIncrements( increments ); int iter = 0; for (int z=extent[4]; z <= extent[5]; z++) { for (int y=extent[2]; y <= extent[3]; y++, iter = 0) { int r1,r2; int moreSubExtents = 1; while( moreSubExtents ) { moreSubExtents = stencilData->GetNextExtent( r1, r2, extent[0], extent[1], y, z, iter); // sanity check if (r1 <= r2 ) { unsigned char *beginExtent = (unsigned char *)(image->GetScalarPointer(r1, y, z)); unsigned char *endExtent = (unsigned char *)(image->GetScalarPointer(r2, y, z)); while (beginExtent <= endExtent) { *beginExtent = inVal; beginExtent += increments[0]; } } } // end for each extent tuple } // end for each scan line } // end of each slice } //---------------------------------------------------------------------------- template < class T > void vtkKWEITKImageGetStencilFromImage( vtkImageData *image, vtkImageStencilData *stencilData, T threshold) { int extent[6]; double spacing[3], origin[3]; image->GetExtent(extent); image->GetSpacing(spacing); image->GetOrigin(origin); stencilData->SetExtent(extent); stencilData->SetSpacing(spacing); stencilData->SetOrigin(origin); stencilData->AllocateExtents(); vtkImageIterator< T > it(image, extent); int ends[2], index[3]; index[1] = extent[2]; index[2] = extent[4]; while( !it.IsAtEnd() ) { T *inSI = it.BeginSpan(); T *inSIEnd = it.EndSpan(); index[0] = extent[0]; ends[0] = -1; ends[1] = -1; if (*inSI >= threshold) { ends[0] = extent[0]; } // for each row while (inSI != inSIEnd) { if (ends[0] == -1 && *inSI >= threshold) { // look for start ends[0] = index[0]; ++index[0]; ++inSI; continue; } if (ends[0] != -1 && ends[1] == -1 && *inSI < threshold) { ends[1] = index[0]; stencilData->InsertNextExtent(ends[0], ends[1], index[1], index[2]); ends[0] = ends[1] = -1; } ++index[0]; ++inSI; } if (*(inSI-1) >= threshold) // ends[0] has to be not -1, ends[1] has to be -1; { stencilData->InsertNextExtent(ends[0], extent[1], index[1], index[2]); } it.NextSpan(); if (index[1] == extent[3]) { ++index[2]; index[1] = extent[2]; } else { ++index[1]; } } } //---------------------------------------------------------------------------- void vtkKWEITKImage::GetStencilFromImage( vtkImageData *image, vtkImageStencilData *stencilData, double threshold) { if (image == NULL) { stencilData = NULL; return; } switch (image->GetScalarType()) { vtkTemplateMacro( vtkKWEITKImageGetStencilFromImage( image, stencilData, static_cast(threshold))); } } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushShapeEllipsoid.h0000644000175000017500000000717611363410610023666 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushShapeEllipsoid - A box shaped paintbrush template // .SECTION Usage // // .SECTION Description // // .SECTION See Also #ifndef __vtkKWEPaintbrushShapeEllipsoid_h #define __vtkKWEPaintbrushShapeEllipsoid_h #include "vtkKWEPaintbrushShape.h" class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushShapeEllipsoid : public vtkKWEPaintbrushShape { public: // Description: // Instantiate this class. static vtkKWEPaintbrushShapeEllipsoid *New(); // Description: // Standard methods for instances of this class. vtkTypeRevisionMacro(vtkKWEPaintbrushShapeEllipsoid, vtkKWEPaintbrushShape); void PrintSelf(ostream& os, vtkIndent indent); // Description: // It allows the paintbrush representation to query the template for a // paintbrush outline centered at the specified point and intersecting // with the specified plane. If the plane is NULL, a polydata representation // of the template in 3D is returned. (a cube in this case). // Returns NULL if the plane does not intersect with the cube. //BTX virtual vtkSmartPointer< vtkPolyData > GetShapePolyData( double *center, vtkPlane *plane = NULL); //ETX // Description: // Get the shape as a binary stencil virtual void GetStencil(vtkImageStencilData *, double p[3]); // Description: // Get the shape as a grayscale image data virtual void GetGrayscaleData(vtkImageData *, double p[3]); //Description: //Set new shape width virtual void SetWidth( double newWidthX, double newWidthY, double newWidthZ ); virtual void SetWidth( double newWidth[3]); vtkGetVector3Macro( Width, double ); // Description: // Set/Get the resolution of the ellipse. The resolution is the number of // points on the polydata used to represent the ellipse. vtkSetMacro( Resolution, int ); vtkGetMacro( Resolution, int ); // Description: // See superclass documentation virtual int Resize(double d[3], int ResizeType); // Description: // Deep copy.. Synchronizes states etc. virtual void DeepCopy(vtkKWEPaintbrushShape *); // Description: // Retrieve text annotation. This returns the size of the box virtual void GetAnnotation(char *s); // Description: // Transition region for the grayscale brush. Default 20% of the brush // radius on either side of the brush. vtkSetClampMacro( TransitionRegion, double, 0.0, 1.0 ); vtkGetMacro( TransitionRegion, double ); // Description: // INTERNAL - Do not use. // Get the extents of a shape drawn at the current location. virtual void GetExtent( int extent[6], double p[3] ); protected: vtkKWEPaintbrushShapeEllipsoid(); ~vtkKWEPaintbrushShapeEllipsoid(); double Width[3]; int Resolution; double TransitionRegion; private: vtkKWEPaintbrushShapeEllipsoid(const vtkKWEPaintbrushShapeEllipsoid&); //Not implemented void operator=(const vtkKWEPaintbrushShapeEllipsoid&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEITKFilterModuleBase.h0000644000175000017500000001314711363410610022452 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef _vtkKWEITKFilterModuleBase_h #define _vtkKWEITKFilterModuleBase_h #include "VTKEdgeConfigure.h" // Needed for export symbols #include "itkCommand.h" #include "itkProcessObject.h" #include "itkImageRegion.h" #include "itkSize.h" #include "itkIndex.h" #include "vtkSetGet.h" #include #include #include #include class vtkImageData; class vtkImageStencilData; #if defined(VTK_TYPE_USE___INT64) #define vtkitkTemplateMacro___INT64 \ vtkTemplateMacroCase_si64(VTK___INT64, __int64, call); #else #define vtkitkTemplateMacro___INT64 #endif #if defined(VTK_TYPE_USE___INT64) && defined(VTK_TYPE_CONVERT_UI64_TO_DOUBLE) #define vtkitkTemplateMacro___UINT64 \ vtkTemplateMacroCase_ui64(VTK_UNSIGNED___INT64, unsigned __int64, call); #else #define vtkitkTemplateMacro___UINT64 #endif // ITK's support for 64 bit types, long long etc is poor, not as exhaustive // as VTK. Define an alternate macro here that ignores those types. Nobody // will use them anyway. #define vtkitkTemplateMacro(call) \ vtkTemplateMacroCase(VTK_DOUBLE, double, call); \ vtkTemplateMacroCase(VTK_FLOAT, float, call); \ vtkitkTemplateMacro___INT64 \ vtkitkTemplateMacro___UINT64 \ vtkTemplateMacroCase(VTK_LONG, long, call); \ vtkTemplateMacroCase(VTK_UNSIGNED_LONG, unsigned long, call); \ vtkTemplateMacroCase(VTK_INT, int, call); \ vtkTemplateMacroCase(VTK_UNSIGNED_INT, unsigned int, call); \ vtkTemplateMacroCase(VTK_SHORT, short, call); \ vtkTemplateMacroCase(VTK_UNSIGNED_SHORT, unsigned short, call); \ vtkTemplateMacroCase(VTK_CHAR, char, call); \ vtkTemplateMacroCase(VTK_SIGNED_CHAR, signed char, call); \ vtkTemplateMacroCase(VTK_UNSIGNED_CHAR, unsigned char, call) namespace vtkitk { class FilterModuleBase { public: // Command/Observer intended to update the progress typedef itk::MemberCommand< FilterModuleBase > CommandType; // Type used by most algorithms. These types depend only on dimension. typedef itk::ImageRegion<3> RegionType; typedef itk::Index<3> IndexType; typedef itk::Size<3> SizeType; /** Constructor */ FilterModuleBase() { this->m_CommandObserver = CommandType::New(); this->m_UpdateMessage = "Processing the filter..."; this->m_CommandObserver->SetCallbackFunction( this, &FilterModuleBase::ProgressUpdate ); this->m_CumulatedProgress = 0.0; this->m_CurrentFilterProgressWeight = 1.0; this->m_ProcessComponentsIndependetly = true; this->m_InternalIterationCounter = 0; } /** Destructor */ virtual ~FilterModuleBase() { } void SetUpdateMessage( const char * message ) { m_UpdateMessage = message; } void InitializeProgressValue() { this->m_CumulatedProgress = 0.0; } void SetCumulatedProgress( float progress ) { this->m_CumulatedProgress = progress; } void SetCurrentFilterProgressWeight( float weight ) { this->m_CurrentFilterProgressWeight = weight; } float GetCurrentFilterProgressWeight() const { return this->m_CurrentFilterProgressWeight; } void SetProcessComponentsIndependetly( bool independentProcessing ) { this->m_ProcessComponentsIndependetly = independentProcessing; } CommandType * GetCommandObserver() { return this->m_CommandObserver; } void ProgressUpdate( itk::Object * itkNotUsed(caller), const itk::EventObject & itkNotUsed(event) ) { // TODO Invoke a vtk event for the corresponding itk event here.... } virtual void SetInput( vtkImageData * itkNotUsed(data) ) = 0; virtual vtkImageData * GetInput() = 0; // Optional method for subclasses that output a stencil virtual int GetOutputAsStencil( vtkImageStencilData * itkNotUsed(data) ) { return 0; }; virtual int GetSphereBoundedOutputAsStencil( vtkImageStencilData * itkNotUsed(data), int itkNotUsed(center)[3], double itkNotUsed(radius)[3] ) { return 0; }; // Set the requested region virtual void SetRequestedExtent( int itkNotUsed(extent)[6] ) {}; private: CommandType::Pointer m_CommandObserver; std::string m_UpdateMessage; float m_CumulatedProgress; float m_CurrentFilterProgressWeight; bool m_ProcessComponentsIndependetly; unsigned int m_InternalIterationCounter; }; } // end namespace vtkitk #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushPropertyManager.h0000644000175000017500000001516011521051333024067 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushPropertyManager - Manages a default set of properties corresponding to the collection of sketches // .SECTION Description // This class is not meant to be used by the user and hence is not exposed // to the user. It is used internally by the paintbrush infrastructure to // assign a default set of properties as new sketches are added, so that // you get unique colors for each segmentation etc. It is also used by // the blender for optmizations in blending a label map containing // many sketches into a final overlay. #ifndef __vtkKWEPaintbrushPropertyManager_h #define __vtkKWEPaintbrushPropertyManager_h #include "VTKEdgeConfigure.h" #include "vtkKWEPaintbrushEnums.h" #include "vtkObject.h" #include class vtkKWEPaintbrushSketch; class vtkKWEPaintbrushDrawing; class vtkKWEPaintbrushProperty; class vtkKWEPaintbrushBlend; class vtkProperty; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushPropertyManager : public vtkObject { //BTX friend class vtkKWEPaintbrushDrawing; friend class vtkKWEPaintbrushBlend; friend class vtkKWEPaintbrushWidget; //ETX public: vtkTypeRevisionMacro(vtkKWEPaintbrushPropertyManager,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // A drawing is always associated with a paintbrush sketch. A // vtkKWEPaintbrushSketch upon creation will automatically be assigned a // default property internally. You can, using this method, query the sketch // to which this property is assigned. vtkGetObjectMacro( PaintbrushDrawing, vtkKWEPaintbrushDrawing ); // Description: // Two highlight modes are allowed. // Please see vtkKWEPaintbrushProperty::HighlightTypeEnum // Stippled inverted highlight looks better when you have an overlay, as with // vtkKWEPaintbrushRepresentation2D. ThickHighlight looks better when you render // brushdata as contours as in vtkKWEPaintbrushRepresentationGrayscale2D. vtkSetMacro( HighlightType, int ); vtkGetMacro( HighlightType, int ); // Description: // Assign colors to sketches in the drawing, using some strategy to ensure, // as far as possible some sort of uniqueness void Update(); // Description: // INTERNAL - Do not Use. // Used to figure out used colors and assign "pleasing" defaultcolors to new // sketches. The representations typically Initialize the manager, // AddUsedColors for all the sketches that have colors already and then // request a color for the new sketch. void Initialize(); void AddUsedColor( vtkProperty * p ); void RetrieveSketchColor( vtkKWEPaintbrushSketch *s, unsigned char c[3] ); vtkKWEPaintbrushProperty * RequestColorForSketch( vtkKWEPaintbrushSketch *s ); // Description: // INTERNAL - Do not use class vtkKWEPaintbrushLabelMapColor { public: unsigned char Color[3]; double Opacity; vtkKWEPaintbrushLabelMapColor() { Color[0] = Color[1] = Color[2] = 0; } vtkKWEPaintbrushLabelMapColor( unsigned char r, unsigned char g, unsigned char b, double opacity ) { Color[0] = r; Color[1] = g; Color[2] = b; Opacity = opacity; } vtkKWEPaintbrushLabelMapColor( unsigned char rgba[3], double o ) { Color[0] = rgba[0]; Color[1] = rgba[1]; Color[2] = rgba[2]; Opacity=o; } bool operator==(const vtkKWEPaintbrushLabelMapColor &a) const { return ( this->Color[0] == a.Color[0] && this->Color[1] == a.Color[1] && this->Color[2] == a.Color[2] ); } }; typedef vtkstd::map< vtkKWEPaintbrushEnums::LabelType, vtkKWEPaintbrushLabelMapColor > LabelToColorMapType; protected: static vtkKWEPaintbrushPropertyManager *New( vtkKWEPaintbrushDrawing * ); static vtkKWEPaintbrushPropertyManager *New(); vtkKWEPaintbrushPropertyManager(); ~vtkKWEPaintbrushPropertyManager(); // Description: // Called from Update(). This is done only if the Drawing type is LabelMap void UpdateLabelToColorMap(); // To provide default colors class vtkKWEPaintbrushColors { public: double R, G, B, Opacity; unsigned int Idx; vtkKWEPaintbrushColors() { Opacity = 1.0; Idx = 0; } vtkKWEPaintbrushColors( double r, double g, double b, int idx = 0 ) { R=r; G=g; B=b; Idx=idx; Opacity=0.0; } bool operator==(const vtkKWEPaintbrushColors &a) const { return (fabs(this->R - a.R) < 0.01 && fabs(this->G - a.G) < 0.01 && fabs(this->B - a.B) < 0.01); } }; typedef vtkKWEPaintbrushColors ColorType; void AddUsedColor( const ColorType & ); ColorType RequestColor(); // Description: // Grab focus makes only a certain sketch editable. This is called in respose // to interaction automatically by vtkKWEPaintbrushWidget. void GrabFocus( vtkKWEPaintbrushSketch * ); void ReleaseFocus(); private: vtkKWEPaintbrushPropertyManager(const vtkKWEPaintbrushPropertyManager&); void operator=(const vtkKWEPaintbrushPropertyManager&); vtkKWEPaintbrushDrawing * PaintbrushDrawing; struct vtkKWEPaintbrushColorsCompare { bool operator()(const ColorType& s1, const ColorType& s2) const { return s1.Idx < s2.Idx; } }; typedef vtkstd::map< vtkKWEPaintbrushSketch *, ColorType > SketchToColorMapType; typedef vtkstd::map< ColorType, unsigned int, vtkKWEPaintbrushColorsCompare > ColorsMapType; SketchToColorMapType SketchToColorMap; ColorsMapType Colors; int HighlightType; // Everything below this is used only if we our representation is a label map. // // When the LabelType isn't unsigned char, we are forced to use an std::map // to store the label to color lookup table. This will introduce some lag, // but what can we do ? unsigned char LabelToColorMapUC[256][3]; double LabelToOpacityMapUC[256]; LabelToColorMapType LabelToColorMap; }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushEnums.h.in0000644000175000017500000000526311363410610022450 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef __vtkKWEPaintbrushEnums_h #define __vtkKWEPaintbrushEnums_h #include "VTKEdgeConfigure.h" #include "vtkSetGet.h" // .NAME vtkKWEPaintbrushEnums - Defines enums used throughout these classes. // .SECTION Description // This file is included by all the paintbrush classes and defines a few // enumerations. class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushEnums { public: // Description: // - A binary brush creates black and white drawings // - A Grayscale brush creates a gaussian profile (actually a ramp) like drawing. // - A label brush creates a label map, each stroke can represent any one label. // // The brush you choose depends on what your intent is. // - If your drawing has just one segmentation (one label), you are better // off using a binary brush. You will be editing with voxel precision. // - If you wish to render your segmentation as contours and be able to edit // with sub-voxel precision, use the grayscale brush. // - If your drawing has several segmentations, you would be better off using // a Label brush. You will be editing with voxel precision. Note that you // can still edit multiple segmentations with several binary brushes, but // its in the interest of memory not to do so. // typedef enum { Binary = 0, Grayscale, Label } DataType; // Description: // Are we drawing in erase or draw mode ? typedef enum { Erase = 0, Draw } BrushType; // Description: // Paintbrush standard operation add, subtract, replace ? typedef enum { Add = 0, Subtract, Replace } OperationType; // Description: // Datatype used to represent labels. This will affect memory consumption. // It will also determine the maximum number of labels in your label-map. // Users can change the precision of labels used in this library by // changing the two lines below. // typedef @VTKEdge_PAINTBRUSH_LABEL_TYPEDEF@ LabelType; static int GetLabelType() { return @VTKEdge_PAINTBRUSH_LABEL_TYPE@; } }; #endif vtkedge-0.2.0~20110819/Widgets/itkImageToVTKImageFilter.txx0000644000175000017500000000614011363410610022742 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef _itkImageToVTKImageFilter_txx #define _itkImageToVTKImageFilter_txx #include "itkImageToVTKImageFilter.h" namespace itk { /** * Constructor */ template ImageToVTKImageFilter ::ImageToVTKImageFilter() { m_Importer = vtkImageImport::New(); m_Exporter = ExporterFilterType::New(); m_Importer->SetUpdateInformationCallback(m_Exporter->GetUpdateInformationCallback()); m_Importer->SetPipelineModifiedCallback(m_Exporter->GetPipelineModifiedCallback()); m_Importer->SetWholeExtentCallback(m_Exporter->GetWholeExtentCallback()); m_Importer->SetSpacingCallback(m_Exporter->GetSpacingCallback()); m_Importer->SetOriginCallback(m_Exporter->GetOriginCallback()); m_Importer->SetScalarTypeCallback(m_Exporter->GetScalarTypeCallback()); m_Importer->SetNumberOfComponentsCallback(m_Exporter->GetNumberOfComponentsCallback()); m_Importer->SetPropagateUpdateExtentCallback(m_Exporter->GetPropagateUpdateExtentCallback()); m_Importer->SetUpdateDataCallback(m_Exporter->GetUpdateDataCallback()); m_Importer->SetDataExtentCallback(m_Exporter->GetDataExtentCallback()); m_Importer->SetBufferPointerCallback(m_Exporter->GetBufferPointerCallback()); m_Importer->SetCallbackUserData(m_Exporter->GetCallbackUserData()); } /** * Destructor */ template ImageToVTKImageFilter ::~ImageToVTKImageFilter() { if( m_Importer ) { m_Importer->Delete(); m_Importer = 0; } } /** * Set an itk::Image as input */ template void ImageToVTKImageFilter ::SetInput( const InputImageType * inputImage ) { m_Exporter->SetInput( inputImage ); } /** * Get a vtkImage as output */ template vtkImageData * ImageToVTKImageFilter ::GetOutput() const { return m_Importer->GetOutput(); } /** * Get the importer filter */ template vtkImageImport * ImageToVTKImageFilter ::GetImporter() const { return m_Importer; } /** * Get the exporter filter */ template typename ImageToVTKImageFilter::ExporterFilterType * ImageToVTKImageFilter ::GetExporter() const { return m_Exporter.GetPointer(); } /** * Delegate the Update to the importer */ template void ImageToVTKImageFilter ::Update() { m_Importer->Update(); } } // end namespace itk #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushShape.cxx0000644000175000017500000001062511504122432022364 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushData.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkKWEPaintbrushShape, "$Revision: 3282 $"); //---------------------------------------------------------------------- vtkKWEPaintbrushShape::vtkKWEPaintbrushShape() { this->Spacing[0] = this->Spacing[1] = this->Spacing[2] = 1.0; this->Origin[0] = this->Origin[1] = this->Origin[2] = 0.0; this->ScalarType = VTK_UNSIGNED_CHAR; this->Polarity = vtkKWEPaintbrushEnums::Draw; this->ResizeConstraint = vtkKWEPaintbrushShape::PaintbrushResizeUnConstrained; this->Representation = vtkKWEPaintbrushEnums::Binary; this->MaxWidth[0] = this->MaxWidth[1] = this->MaxWidth[2] = -1.0; this->ClipExtent[0] = VTK_INT_MIN; this->ClipExtent[2] = VTK_INT_MIN; this->ClipExtent[4] = VTK_INT_MIN; this->ClipExtent[1] = VTK_INT_MAX; this->ClipExtent[3] = VTK_INT_MAX; this->ClipExtent[5] = VTK_INT_MAX; } //---------------------------------------------------------------------- vtkKWEPaintbrushShape::~vtkKWEPaintbrushShape() { } //---------------------------------------------------------------------- void vtkKWEPaintbrushShape::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //---------------------------------------------------------------------- void vtkKWEPaintbrushShape::GetPaintbrushData(vtkKWEPaintbrushData *d, int x, int y, int z) { double worldPos[3]; worldPos[0] = x * this->Spacing[0] + this->Origin[0]; worldPos[1] = y * this->Spacing[1] + this->Origin[1]; worldPos[2] = z * this->Spacing[2] + this->Origin[2]; this->GetPaintbrushData(d, worldPos); } //---------------------------------------------------------------------- void vtkKWEPaintbrushShape::GetPaintbrushData(vtkKWEPaintbrushData *d, double p[3]) { if (vtkKWEPaintbrushStencilData *s = vtkKWEPaintbrushStencilData::SafeDownCast(d)) { this->GetStencil( s->GetImageStencilData(), p); } else if (vtkKWEPaintbrushGrayscaleData *t = vtkKWEPaintbrushGrayscaleData::SafeDownCast(d)) { this->GetGrayscaleData( t->GetImageData(), p); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShape::DeepCopy(vtkKWEPaintbrushShape *s) { if (s == this || !s) { return; } for (unsigned int i=0; i<3; i++) { this->Spacing[i] = s->Spacing[i]; this->Origin[i] = s->Origin[i]; this->ScalarType = s->ScalarType; this->Polarity = s->Polarity; } this->Modified(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushShape::SetClipExtent(int e[6]) { for (int i = 0; i < 6; i++) { this->ClipExtent[i] = e[i]; } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShape::GetClipExtent(int e[6]) { for (int i = 0; i < 6; i++) { e[i] = this->ClipExtent[i]; } } //---------------------------------------------------------------------- int *vtkKWEPaintbrushShape::GetClipExtent() { return this->ClipExtent; } //---------------------------------------------------------------------- void vtkKWEPaintbrushShape::SetPolarityToDraw() { this->SetPolarity(vtkKWEPaintbrushEnums::Draw); } //---------------------------------------------------------------------- void vtkKWEPaintbrushShape::SetPolarityToErase() { this->SetPolarity(vtkKWEPaintbrushEnums::Erase); } vtkedge-0.2.0~20110819/Widgets/vtkKWEVoxelAlignedImageActorPointPlacer.cxx0000644000175000017500000001152711363410610025745 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEVoxelAlignedImageActorPointPlacer.h" #include "vtkObjectFactory.h" #include "vtkRenderer.h" #include "vtkImageActor.h" #include "vtkImageData.h" vtkCxxRevisionMacro(vtkKWEVoxelAlignedImageActorPointPlacer, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEVoxelAlignedImageActorPointPlacer); //---------------------------------------------------------------------- vtkKWEVoxelAlignedImageActorPointPlacer::vtkKWEVoxelAlignedImageActorPointPlacer() { } //---------------------------------------------------------------------- vtkKWEVoxelAlignedImageActorPointPlacer::~vtkKWEVoxelAlignedImageActorPointPlacer() { } //---------------------------------------------------------------------- int vtkKWEVoxelAlignedImageActorPointPlacer::ComputeWorldPosition( vtkRenderer *ren, double displayPos[2], double *refWorldPos, double worldPos[3], double worldOrient[9] ) { return (this->Superclass::ComputeWorldPosition( ren, displayPos, refWorldPos, worldPos, worldOrient ) && this->InternalValidateWorldPosition(worldPos)); } //---------------------------------------------------------------------- int vtkKWEVoxelAlignedImageActorPointPlacer::InternalValidateWorldPosition( double worldPos[3]) { double spacing[3], origin[3]; int extent[6], imagePosition[3]; this->ImageActor->GetInput()->GetExtent(extent); this->ImageActor->GetInput()->GetSpacing(spacing); this->ImageActor->GetInput()->GetOrigin(origin); imagePosition[0] = static_cast((worldPos[0]-origin[0])/spacing[0] + 0.5); imagePosition[1] = static_cast((worldPos[1]-origin[1])/spacing[1] + 0.5); imagePosition[2] = static_cast((worldPos[2]-origin[2])/spacing[2] + 0.5); if (imagePosition[0] < extent[0] || imagePosition[0] > extent[1] || imagePosition[1] < extent[2] || imagePosition[1] > extent[3] || imagePosition[2] < extent[4] || imagePosition[2] > extent[5]) { return 0; } worldPos[0] = imagePosition[0] * spacing[0] + origin[0]; worldPos[1] = imagePosition[1] * spacing[1] + origin[1]; worldPos[2] = imagePosition[2] * spacing[2] + origin[2]; return 1; } //---------------------------------------------------------------------- int vtkKWEVoxelAlignedImageActorPointPlacer::ComputeWorldPosition( vtkRenderer *ren, double displayPos[2], double worldPos[3], double worldOrient[9] ) { return (this->Superclass::ComputeWorldPosition( ren, displayPos, worldPos, worldOrient ) && this->InternalValidateWorldPosition(worldPos)); } //---------------------------------------------------------------------- int vtkKWEVoxelAlignedImageActorPointPlacer::ValidateWorldPosition( double worldPos[3], double *worldOrient) { return this->Superclass::ValidateWorldPosition( worldPos, worldOrient ) && this->InternalValidateWorldPosition(worldPos); } //---------------------------------------------------------------------- int vtkKWEVoxelAlignedImageActorPointPlacer::ValidateWorldPosition( double worldPos[3] ) { return this->Superclass::ValidateWorldPosition( worldPos ) && this->InternalValidateWorldPosition(worldPos); } //---------------------------------------------------------------------- int vtkKWEVoxelAlignedImageActorPointPlacer::UpdateWorldPosition( vtkRenderer *ren, double worldPos[3], double worldOrient[9] ) { return this->Superclass::UpdateWorldPosition( ren, worldPos, worldOrient ) && this->InternalValidateWorldPosition(worldPos); } //---------------------------------------------------------------------- void vtkKWEVoxelAlignedImageActorPointPlacer::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushOperation.cxx0000644000175000017500000001101111363410610023253 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushShapeEllipsoid.h" #include "vtkKWEPaintbrushData.h" #include "vtkImageData.h" #include "vtkMath.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkKWEPaintbrushOperation, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEPaintbrushOperation); vtkCxxSetObjectMacro(vtkKWEPaintbrushOperation,PaintbrushShape,vtkKWEPaintbrushShape); vtkCxxSetObjectMacro(vtkKWEPaintbrushOperation,ImageData,vtkImageData); //---------------------------------------------------------------------- vtkKWEPaintbrushOperation::vtkKWEPaintbrushOperation() { this->ImageData = NULL; this->PaintbrushShape = NULL; this->Extent[0] = this->Extent[2] = this->Extent[4] = 0; this->Extent[1] = this->Extent[3] = this->Extent[5] = -1; // Set a default shape vtkKWEPaintbrushShapeEllipsoid * paintbrushShape = vtkKWEPaintbrushShapeEllipsoid::New(); this->SetPaintbrushShape( paintbrushShape ); paintbrushShape->SetWidth(5.0,5.0,5.0); paintbrushShape->Delete(); } //---------------------------------------------------------------------- vtkKWEPaintbrushOperation::~vtkKWEPaintbrushOperation() { this->SetPaintbrushShape(NULL); this->SetImageData(NULL); } //---------------------------------------------------------------------- void vtkKWEPaintbrushOperation:: GetPaintbrushData(vtkKWEPaintbrushData *paintbrushData, double p[3], vtkKWEPaintbrushEnums::OperationType & op ) { if (!this->PaintbrushShape) { vtkErrorMacro( << "Set the shape prior to use" ); } // Do the operation only if the paintbrush shape (whose center is denoted // by "p" is within the bounding extents) or of no bounding extents have // been specified. bool isWithinBounds = false; bool uninitializedExtent = (this->Extent[0] > this->Extent[1]); if (!uninitializedExtent) { double spacing[3], origin[3]; this->PaintbrushShape->GetSpacing(spacing); this->PaintbrushShape->GetOrigin(origin); double bounds[6] = { this->Extent[0] * spacing[0] + origin[0], this->Extent[1] * spacing[0] + origin[0], this->Extent[2] * spacing[1] + origin[1], this->Extent[3] * spacing[1] + origin[1], this->Extent[4] * spacing[2] + origin[2], this->Extent[5] * spacing[2] + origin[2] }; double tolerance[3] = {1e-10, 1e-10, 1e-10}; if (vtkMath::PointIsWithinBounds( p, bounds, tolerance )) { isWithinBounds = true; } } if (isWithinBounds || uninitializedExtent) { // Perform the operation. this->DoOperation(paintbrushData, p, op); // Clip the resulting paintbrushdata, if bounding extents have been // specified. if (!uninitializedExtent ) { paintbrushData->Clip( this->Extent ); } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushOperation:: DoOperation( vtkKWEPaintbrushData *data, double p[3], vtkKWEPaintbrushEnums::OperationType & op ) { op = vtkKWEPaintbrushEnums::Add; // The default, pass through operation, simply pulls data from the shape. this->PaintbrushShape->GetPaintbrushData( data, p ); } //---------------------------------------------------------------------- void vtkKWEPaintbrushOperation::DeepCopy(vtkKWEPaintbrushOperation *op) { if (op == this || !op) { return; } if (this->ImageData != op->ImageData) // operations on different image data // may be different. { return; } if (this->PaintbrushShape && op->PaintbrushShape) { this->PaintbrushShape->DeepCopy(op->PaintbrushShape); } this->Modified(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushOperation::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/itkConfidenceConnectedMiniPipelineFilter.h0000644000175000017500000001022411363410610025652 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef __itkConfidenceConnectedMiniPipelineFilter_h #define __itkConfidenceConnectedMiniPipelineFilter_h #include "VTKEdgeConfigure.h" // Needed for export symbol def #include "itkConfidenceConnectedImageFilter.h" #include "itkVotingBinaryHoleFillingImageFilter.h" #include "itkMedianImageFilter.h" namespace itk{ /** \class ConfidenceConnectedMiniPipelineFilter * \brief Confidence connected mini pipeline filter * * This class is a wrapper around a set of filters that perform region * growing on an image. The filter internally uses a three step process * for region growing. * * Nonlinear Smoothing -> Region growing -> Hole filling * * The smoothing process employed here is Median filter with a 3x3 kernel, * cause its fast. The region growing process is * ConfidenceConnectedRegionGrowing. Hole filling is accomplised by a * binary voting filter. * * The class gives you access to the three filters. It is up to you to * set the parameters to those filters. You can turn off hole filling if * you like. */ template class ITK_EXPORT ConfidenceConnectedMiniPipelineFilter: public ImageToImageFilter { public: /** Standard class typedefs. */ typedef ConfidenceConnectedMiniPipelineFilter Self; typedef ImageToImageFilter Superclass; typedef SmartPointer Pointer; typedef SmartPointer ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(ConfidenceConnectedMiniPipelineFilter, ImageToImageFilter); typedef TInputImage InputImageType; typedef TOutputImage OutputImageType; /** Pipeline filters */ typedef MedianImageFilter< InputImageType, InputImageType > SmoothingFilterType; typedef ConfidenceConnectedImageFilter< InputImageType, OutputImageType > RegionGrowingFilterType; typedef VotingBinaryHoleFillingImageFilter< OutputImageType, OutputImageType > HoleFillingFilterType; typedef typename RegionGrowingFilterType::SeedsContainerType SeedsContainerType; void PrintSelf ( std::ostream& os, Indent indent ) const; /** Get the pipeline filters */ virtual SmoothingFilterType * GetSmoothingFilter(); virtual RegionGrowingFilterType * GetRegionGrowingFilter(); virtual HoleFillingFilterType * GetHoleFillingFilter(); /** Do hole filling.. turn this off if needed. On by default */ itkSetMacro( UseHoleFilling, bool ); itkGetConstReferenceMacro( UseHoleFilling, bool ); itkBooleanMacro( UseHoleFilling ); protected: ConfidenceConnectedMiniPipelineFilter(); ~ConfidenceConnectedMiniPipelineFilter(){}; // Override since the filter needs all the data for the algorithm void GenerateInputRequestedRegion(); virtual void GenerateOutputInformation(); void GenerateData(); private: ConfidenceConnectedMiniPipelineFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented typename SmoothingFilterType::Pointer m_SmoothingFilter; typename RegionGrowingFilterType::Pointer m_RegionGrowingFilter; typename HoleFillingFilterType::Pointer m_HoleFillingFilter; bool m_UseHoleFilling; }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkConfidenceConnectedMiniPipelineFilter.txx" #endif #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushSelectionRepresentation2D.h0000644000175000017500000000572311363410610026013 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushSelectionRepresentation2D - // .SECTION Description // // .SECTION See Also #ifndef __vtkKWEPaintbrushSelectionRepresentation2D_h #define __vtkKWEPaintbrushSelectionRepresentation2D_h #include "vtkKWEPaintbrushSelectionRepresentation.h" class vtkImageActor; class vtkActor; class vtkPolyData; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushSelectionRepresentation2D : public vtkKWEPaintbrushSelectionRepresentation { public: // Description: // Instantiate this class. static vtkKWEPaintbrushSelectionRepresentation2D *New(); // Description: // Standard VTK methods. vtkTypeRevisionMacro(vtkKWEPaintbrushSelectionRepresentation2D, vtkKWEPaintbrushSelectionRepresentation); void PrintSelf(ostream& os, vtkIndent indent); // Description: // These are methods that satisfy vtkWidgetRepresentation's API. virtual void BuildRepresentation(); // Description: // Set the image actor on which the paintbrush is drawn. virtual void SetImageActor( vtkImageActor * ); // Descirption: // Deep copy.. synchronizes states etc.. virtual void DeepCopy(vtkWidgetRepresentation *r); // Description: // Methods required by vtkProp superclass. virtual int RenderOverlay(vtkViewport *viewport); virtual int RenderOpaqueGeometry(vtkViewport *viewport); #if VTKEdge_VTK_VERSION_DATE > 20070305 virtual int RenderTranslucentPolygonalGeometry(vtkViewport *viewport); virtual int HasTranslucentPolygonalGeometry(); #else // Legacy method to support VTK source versions prior to 2007/03/05 virtual int RenderTranslucentGeometry(vtkViewport *viewport); #endif // Description: // Get the actors maintained by the representation, that need to be rendered. virtual void GetActors(vtkPropCollection *); protected: vtkKWEPaintbrushSelectionRepresentation2D(); ~vtkKWEPaintbrushSelectionRepresentation2D(); vtkActor * DragActor; vtkPolyData * DragPolyData; // Description: // Drag and drop merge support. virtual int DragAndDropMerge(); private: vtkKWEPaintbrushSelectionRepresentation2D(const vtkKWEPaintbrushSelectionRepresentation2D&); //Not implemented void operator=(const vtkKWEPaintbrushSelectionRepresentation2D&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushHighlightActors.h0000644000175000017500000000614711363410610024041 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushHighlightActors - // .SECTION Description // Can be instantiated only by a vtkObject. #ifndef __vtkKWEPaintbrushHighlightActors_h #define __vtkKWEPaintbrushHighlightActors_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkProp3D.h" class vtkActorCollection; class vtkMapperCollection; class vtkKWEStencilContourFilter; class vtkCollection; class vtkKWEPaintbrushDrawing; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushHighlightActors : public vtkProp3D { //BTX friend class vtkKWEPaintbrushRepresentation2D; //ETX public: // Description: // Standard VTK methods. vtkTypeRevisionMacro(vtkKWEPaintbrushHighlightActors, vtkProp3D); void PrintSelf(ostream& os, vtkIndent indent); // Description: // The drawing must be set. Our actors need to highlight something right ? virtual void SetPaintbrushDrawing( vtkKWEPaintbrushDrawing* ); vtkGetObjectMacro( PaintbrushDrawing, vtkKWEPaintbrushDrawing ); // Description: // Set / get extents vtkSetVector6Macro( Extent, int ); vtkGetVector6Macro( Extent, int ); // Description: // Methods required by vtkProp superclass. virtual int RenderOpaqueGeometry(vtkViewport *viewport); #if VTKEdge_VTK_VERSION_DATE > 20070305 virtual int RenderTranslucentPolygonalGeometry(vtkViewport *viewport); virtual int HasTranslucentPolygonalGeometry(); #else // Legacy method to support VTK source versions prior to 2007/03/05 virtual int RenderTranslucentGeometry(vtkViewport *viewport); #endif // Description: // See vtkProp3D. virtual void GetActors(vtkPropCollection *); virtual double *GetBounds(); protected: vtkKWEPaintbrushHighlightActors(); ~vtkKWEPaintbrushHighlightActors(); // Description: // Can be instantiated only by a vtkObject. static vtkKWEPaintbrushHighlightActors *New(); vtkCollection * ContourFilters; vtkMapperCollection * ContourPolyDataMappers; vtkActorCollection * ContourPolyDataActors; vtkKWEPaintbrushDrawing * PaintbrushDrawing; int Extent[6]; // Description: // Update and build all the actors according to the drawing. virtual void BuildRepresentation(); private: vtkKWEPaintbrushHighlightActors( const vtkKWEPaintbrushHighlightActors&); //Not implemented void operator=(const vtkKWEPaintbrushHighlightActors&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/Testing/0000755000175000017500000000000011630434665017073 5ustar mathieumathieuvtkedge-0.2.0~20110819/Widgets/Testing/Cxx/0000755000175000017500000000000011630434665017635 5ustar mathieumathieuvtkedge-0.2.0~20110819/Widgets/Testing/Cxx/PaintbrushTest3.cxx0000644000175000017500000002673411363410610023422 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This test loads a file IBSRData.mha and a label map IBSRLabelMap-UCHAR.mha. // The label map, (courtesy of IBSR) is a label map with 62 segmentations. This // test creates a sketch from each label and initializes the drawing with // these sketches. It also assigns user specified colors to the sketches. // ---------------------------------------------------------------------------- // // User interactions: // // The follwing interactions are supported by the brush in Edit mode. // Left click and drag - Draws a stroke // Ctrl-Left click and drag - Erases the stroke // Backspace or Left key - Undo the sketch (deletes the previously drawn stroke in a sketch) // Right key - Redo on the given sketch // Shift "+" - Start a new sketch. // Shift Right - Traverse to the next sketch. // Shift Left - Traverse to the previous sketch. // Shift Backspace - Delete a sketch. // Right click and drag - Resize the shape isotropically // Ctrl-Right click and drag - Resize the shape anisotropically // Shift "<" - Decrease the opacity of the overlaid drawing // Shift ">" - Increase the opacity of the overlaid drawing // "l" key - Render the current sketch immutable/mutable. // (Supported only when editing labelmaps) // Escape - Enable/Disable interactions // // The follwing interactions are supported by the brush in Select Mode // Left click - Select/Unselect a sketch // Left click and drag - Drag and drop merge of sketches. // Backspace key - Delete selected sketches. // "m" key - Merge selected sketches. // Escape - Enable/Disable interactions #include "vtkInteractorEventRecorder.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkImageViewer2.h" #include "vtkRenderer.h" #include "vtkRenderer.h" #include "vtkRegressionTestImage.h" #include "vtkDebugLeaks.h" #include "vtkRegressionTestImage.h" #include "vtkDebugLeaks.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkMetaImageReader.h" #include "vtkImageActor.h" #include "vtkImageData.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageWriter.h" #include #include #include class PaintbrushTest3Labels { public: class Annotation { public: Annotation() {}; Annotation(const std::string &l, unsigned char r, unsigned char g, unsigned char b ) { label = l; R = r; G = g; B = b; } bool operator!=(const Annotation &a) const { return a.label != this->label; } std::string label; unsigned char R, G, B; }; std::map< unsigned short, Annotation > LabelMap; }; int PaintbrushTest3( int argc , char *argv[]) { if( argc < 6 ) { std::cerr << "Usage error: \t " << argv[0] << "\t" << "Input_Image_Data InitialLabelMap EventsLogFile Mode(0:replay 1:record)" << "[OutputLabelMap]" << std::endl; return EXIT_FAILURE; } vtkMetaImageReader * reader = vtkMetaImageReader::New(); reader->SetFileName( argv[1] ); if( reader->CanReadFile( argv[1] ) != 3 ) { std::cerr << "Meta image reader couldn't read the input data\t" << std::endl; return EXIT_FAILURE; } reader->Update(); vtkImageData * imageData = reader->GetOutput(); vtkRenderer *renderer = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); vtkImageViewer2 *viewer = vtkImageViewer2::New(); viewer->SetRenderWindow(renWin); viewer->SetRenderer(renderer); viewer->SetInput(imageData); viewer->SetupInteractor(iren); double *range = imageData->GetScalarRange(); viewer->SetColorWindow(range[1] - range[0]); viewer->SetColorLevel(0.5 * (range[1] + range[0])+ 0.0000001); viewer->SetSlice( 15 ); typedef PaintbrushTest3Labels::Annotation AnnotationType; PaintbrushTest3Labels MyLabels; MyLabels.LabelMap[40]=AnnotationType("Right-Cerebral-Exterior", 205 , 62, 78 ); MyLabels.LabelMap[41]=AnnotationType("Right-Cerebral-White-Matter", 0 , 225, 0 ); MyLabels.LabelMap[42]=AnnotationType("Right-Cerebral-Cortex", 205 , 62, 78 ); MyLabels.LabelMap[43]=AnnotationType("Right-Lateral-Ventricle", 120 , 18, 134 ); MyLabels.LabelMap[44]=AnnotationType("Right-Inf-Lat-Vent", 196 , 58, 250 ); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 1; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( iren ); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); if (rep) { rep->SetImageActor( viewer->GetImageActor() ); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } set->AddWidget(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); // Our internal representation will be to manage a label map. drawing->SetRepresentationToLabel(); // This will allocate our canvas based on the size of the overlay image // that was set on the WidgetRepresentation. drawing->InitializeData(); // Clear the drawing and start on a clean slate. The drawing would have // automatically created 1 empty sketch for us, so we can start drawing // right away. Let's remove it, since we'd like to initialize the drawing // with our IBSR label map. drawing->RemoveAllItems(); // Read the IBSR label map vtkMetaImageReader * reader2 = vtkMetaImageReader::New(); reader2->SetFileName( argv[2] ); reader2->Update(); // Create a PaintbrushLabelData to represent the label map. vtkKWEPaintbrushLabelData *paintbrushLabelMap = vtkKWEPaintbrushLabelData::New(); paintbrushLabelMap->SetLabelMap( reader2->GetOutput() ); // Set the label map as the initial canvas data of the drawing. drawing->SetPaintbrushData( paintbrushLabelMap ); // Create a sketch for each label in the label map, we'd like to edit. // NOTE: We can skip labels in the label map that we do not care about simply // by not adding a sketch corresponding to that label into the drawing. In // this case, we will take into account all the labels (1-62). // NOTE: As a reminder, bear in mind that 0 is a reserved value and must not // be used as a label. for (std::map< unsigned short, AnnotationType >::const_iterator cit = MyLabels.LabelMap.begin(); cit != MyLabels.LabelMap.end(); ++cit) { // For each label. // Initialize the sketch with the label map. Note that you must add the // sketch to the drawing and set the label you wish the sketch to represent // before you initialize it from the label map. // Also note that when the representation is a "Label-map", all sketches // share the same label map to avoid memory duplication. The corollary to // this is that if you initialize sketches in your drawing using a labelmap, // you must use the same "vtkKWEPaintbrushLabelData" that is used by the // drawing. vtkKWEPaintbrushSketch * sketch = vtkKWEPaintbrushSketch::New(); drawing->AddItem( sketch ); sketch->SetLabel( cit->first ); sketch->Initialize( paintbrushLabelMap ); // Optionally, the identifier can be used to display text annotations as // you navigate through your maze of sketches. 62 segmentations can sure // get you lost pretty quickly. sketch->GetPaintbrushProperty()->SetIdentifier(cit->second.label.c_str()); // Assign a nice color to the sketch. double sketchColor[3] = { cit->second.R/255.0, cit->second.G/255.0, cit->second.B/255.0 }; sketch->GetPaintbrushProperty()->SetColor( sketchColor ); sketch->Delete(); } // Now set the drawing on all representations (axial, coronal and sagittal) // in the WidgetSet. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } // Enable the widget and we are done. set->SetEnabled(1); renWin->SetSize( 500, 500 ); renderer->ResetCamera(); renWin->Render(); // record/replay events vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New(); recorder->SetInteractor(iren); //Set event log recording file std::string eventLogFileName = argv[3]; recorder->SetFileName(eventLogFileName.c_str()); recorder->On(); //Set recorder mode depending on the user's choice int retVal = 1; unsigned int mode= atoi( argv[4] ); if( mode ) { std::cout << "Interaction recording....." << std::endl; recorder->Record(); iren->Start(); } else { std::cout << "Interaction replaying....." << std::endl; recorder->Play(); //recorder must be turned off before regression testing recorder->Off(); retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { recorder->GetInteractor()->Start(); } } if (argc >= 6) { vtkKWEPaintbrushLabelData * finalLabelMap = vtkKWEPaintbrushLabelData::SafeDownCast(drawing->GetPaintbrushData()); vtkMetaImageWriter * outputWriter = vtkMetaImageWriter::New(); outputWriter->SetFileName(argv[5]); outputWriter->SetInput( finalLabelMap->GetLabelMap() ); outputWriter->Write(); outputWriter->Delete(); } // clean up recorder->Off(); recorder->Delete(); viewer->Delete(); reader2->Delete(); paintbrushLabelMap->Delete(); set->Delete(); renderer->Delete(); renWin->Delete(); iren->Delete(); reader->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Widgets/Testing/Cxx/PaintbrushTest2.cxx0000644000175000017500000001035011363410610023404 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkCommand.h" #include "vtkInteractorEventRecorder.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkImageViewer2.h" #include "vtkRenderer.h" #include "vtkRenderer.h" #include "vtkRegressionTestImage.h" #include "vtkDebugLeaks.h" #include "vtkRegressionTestImage.h" #include "vtkDebugLeaks.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkMetaImageReader.h" #include "vtkImageActor.h" #include "vtkImageData.h" #include "vtkImageMapToColors.h" #include "vtkLookupTable.h" int PaintbrushTest2( int argc, char *argv[] ) { if( argc < 4 ) { std::cerr << "Usage error: \t " << argv[0] << "\t" << "Input_Image_Data \tEventsLogFile\t Mode(0:replay 1:record)" << std::endl; return EXIT_FAILURE; } vtkImageReader2 * reader = vtkMetaImageReader::New(); reader->SetFileName( argv[1] ); if( reader->CanReadFile( argv[1] ) != 3 ) { std::cerr << "Meta image reader couldn't read the input data\t" << std::endl; return EXIT_FAILURE; } reader->Update(); vtkImageData * imageData = reader->GetOutput(); vtkRenderer *renderer = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); vtkImageViewer2 *viewer = vtkImageViewer2::New(); viewer->SetRenderWindow(renWin); viewer->SetRenderer(renderer); viewer->SetInput(imageData); viewer->SetupInteractor(iren); double *range = imageData->GetScalarRange(); viewer->SetColorWindow(range[1] - range[0]); viewer->SetColorLevel(0.5 * (range[1] + range[0])+ 0.0000001); viewer->SetSlice( 15 ); vtkKWEPaintbrushWidget *widget = vtkKWEPaintbrushWidget::New(); widget->SetInteractor( iren ); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(widget->GetRepresentation()); rep->SetImageActor( viewer->GetImageActor() ); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); iren->Initialize(); renWin->SetSize( 500, 500 ); renWin->Render(); widget->SetEnabled(1); // record/replay events vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New(); recorder->SetInteractor(iren); //Set event log recording file std::string eventLogFileName = argv[2]; recorder->SetFileName(eventLogFileName.c_str()); recorder->On(); //Set recorder mode depending on the user's choice int retVal = 1; unsigned int mode= atoi( argv[3] ); if( mode ) { std::cout << "Interaction recording....." << std::endl; recorder->Record(); iren->Start(); } else { std::cout << "Interaction replaying....." << std::endl; recorder->Play(); //recorder must be turned off before regression testing recorder->Off(); retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { recorder->GetInteractor()->Start(); } } // Clean up recorder->Off(); recorder->Delete(); viewer->Delete(); widget->Delete(); renderer->Delete(); renWin->Delete(); iren->Delete(); reader->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Widgets/Testing/Cxx/PaintbrushTest1c.cxx0000644000175000017500000003660411502655425023572 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This test loads a file IBSRData.mha and a label map IBSRLabelMap-UCHAR.mha. // The label map, (courtesy of IBSR) is a label map with 62 segmentations. This // test creates a sketch from each label and initializes the drawing with // these sketches. It also assigns user specified colors to the sketches. // ---------------------------------------------------------------------------- // // User interactions: // // The follwing interactions are supported by the brush in Edit mode. // Left click and drag - Draws a stroke // Ctrl-Left click and drag - Erases the stroke // Backspace or Left key - Undo the sketch (deletes the previously drawn stroke in a sketch) // Right key - Redo on the given sketch // Shift "+" - Start a new sketch. // Shift Right - Traverse to the next sketch. // Shift Left - Traverse to the previous sketch. // Shift Backspace - Delete a sketch. // Right click and drag - Resize the shape isotropically // Ctrl-Right click and drag - Resize the shape anisotropically // Shift "<" - Decrease the opacity of the overlaid drawing // Shift ">" - Increase the opacity of the overlaid drawing // "l" key - Render the current sketch immutable/mutable. // (Supported only when editing labelmaps) // Escape - Enable/Disable interactions // // The follwing interactions are supported by the brush in Select Mode // Left click - Select/Unselect a sketch // Left click and drag - Drag and drop merge of sketches. // Backspace key - Delete selected sketches. // "m" key - Merge selected sketches. // Escape - Enable/Disable interactions #include "vtkInteractorEventRecorder.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkImageViewer2.h" #include "vtkRenderer.h" #include "vtkRenderer.h" #include "vtkCommand.h" #include "vtkCamera.h" #include "vtkRegressionTestImage.h" #include "vtkDebugLeaks.h" #include "vtkRegressionTestImage.h" #include "vtkDebugLeaks.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkSliderRepresentation.h" #include "vtkSliderRepresentation2D.h" #include "vtkSliderWidget.h" #include "vtkMetaImageReader.h" #include "vtkImageActor.h" #include "vtkImageData.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushDrawingStatistics.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include #include #include //------------------------------------------------------------------------- class PaintbrushTest1cLabels { public: class Annotation { public: Annotation() {}; Annotation(const std::string &l, unsigned char r, unsigned char g, unsigned char b ) { label = l; R = r; G = g; B = b; } bool operator!=(const Annotation &a) const { return a.label != this->label; } std::string label; unsigned char R, G, B; }; std::map< unsigned short, Annotation > LabelMap; }; //------------------------------------------------------------------------- class vtkSliderCallback100c : public vtkCommand { public: static vtkSliderCallback100c *New() { return new vtkSliderCallback100c; } void SetImageViewer(vtkImageViewer2 *viewer) { m_Viewer = viewer; } virtual void Execute(vtkObject *caller, unsigned long , void* ) { vtkSliderWidget *slider = static_cast(caller); vtkSliderRepresentation *sliderRepres = static_cast(slider->GetRepresentation()); int pos = static_cast(sliderRepres->GetValue()); m_Viewer->SetSlice(pos); } protected: vtkImageViewer2 *m_Viewer; }; //------------------------------------------------------------------------- class vtkKWEPaintbrushDrawingStatisticsCallback : public vtkCommand { public: static vtkKWEPaintbrushDrawingStatisticsCallback *New() { return new vtkKWEPaintbrushDrawingStatisticsCallback; } void SetPaintbrushDrawingStatistics(vtkKWEPaintbrushDrawingStatistics *s) { m_PaintbrushDrawingStatistics = s; } virtual void Execute(vtkObject *caller, unsigned long , void* ) { vtkKWEPaintbrushDrawing *drawing = m_PaintbrushDrawingStatistics->GetDrawing(); std::cout << "---------" << std::endl; m_PaintbrushDrawingStatistics->Update(); for (unsigned int i = 0; i < drawing->GetNumberOfItems(); i++) { vtkKWEPaintbrushSketch * sketch = drawing->GetItem(i); std::cout << "Volume of " << sketch->GetPaintbrushProperty()->GetIdentifier() << " is " << m_PaintbrushDrawingStatistics->GetVolume(sketch) << "mm^3" << std::endl; } std::cout << "Total volume of all sketches is " << m_PaintbrushDrawingStatistics->GetVolume() << "mm^3" << std::endl; } protected: vtkKWEPaintbrushDrawingStatistics *m_PaintbrushDrawingStatistics; }; int PaintbrushTest1c( int argc , char *argv[]) { if( argc < 6 ) { std::cerr << "Usage error: \t " << argv[0] << "\t" << "Input_Image_Data InitialLabelMap EventsLogFile Mode(0:replay 1:record)" << "[OutputLabelMap]" << std::endl; return EXIT_FAILURE; } vtkImageReader2 * reader = vtkMetaImageReader::New(); reader->SetFileName( argv[1] ); if( reader->CanReadFile( argv[1] ) != 3 ) { std::cerr << "Meta image reader couldn't read the input data\t" << std::endl; return EXIT_FAILURE; } reader->Update(); vtkImageData * imageData = reader->GetOutput(); vtkRenderer *renderer = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); vtkImageViewer2 *viewer = vtkImageViewer2::New(); viewer->SetRenderWindow(renWin); viewer->SetRenderer(renderer); viewer->SetInput(imageData); viewer->SetupInteractor(iren); double *range = imageData->GetScalarRange(); viewer->SetColorWindow(range[1] - range[0]); viewer->SetColorLevel(0.5 * (range[1] + range[0])+ 0.0000001); // Tie a slider widget to manipulate the slices of the image viewer // vtkSliderRepresentation2D *SliderRepres = vtkSliderRepresentation2D::New(); int min = viewer->GetSliceMin(); int max = viewer->GetSliceMax(); SliderRepres->SetMinimumValue(min); SliderRepres->SetMaximumValue(max); SliderRepres->SetValue(static_cast((min + max) / 2)); SliderRepres->SetTitleText("Slice"); SliderRepres->GetPoint1Coordinate()->SetCoordinateSystemToNormalizedDisplay(); SliderRepres->GetPoint1Coordinate()->SetValue(0.3, 0.05); SliderRepres->GetPoint2Coordinate()->SetCoordinateSystemToNormalizedDisplay(); SliderRepres->GetPoint2Coordinate()->SetValue(0.7, 0.05); SliderRepres->SetSliderLength(0.02); SliderRepres->SetSliderWidth(0.03); SliderRepres->SetEndCapLength(0.01); SliderRepres->SetEndCapWidth(0.03); SliderRepres->SetTubeWidth(0.005); SliderRepres->SetLabelFormat("%3.0lf"); SliderRepres->SetTitleHeight(0.02); SliderRepres->SetLabelHeight(0.02); vtkSliderWidget *SliderWidget = vtkSliderWidget::New(); SliderWidget->SetInteractor(iren); SliderWidget->SetRepresentation(SliderRepres); SliderWidget->KeyPressActivationOff(); SliderWidget->SetAnimationModeToAnimate(); SliderWidget->SetEnabled(true); vtkSliderCallback100c *SliderCb = vtkSliderCallback100c::New(); SliderCb->SetImageViewer(viewer); SliderWidget->AddObserver(vtkCommand::InteractionEvent, SliderCb); viewer->SetSlice(static_cast(SliderRepres->GetValue())); typedef PaintbrushTest1cLabels::Annotation AnnotationType; PaintbrushTest1cLabels MyLabels; MyLabels.LabelMap[40]=AnnotationType("Right-Cerebral-Exterior", 205 , 62, 78 ); MyLabels.LabelMap[41]=AnnotationType("Right-Cerebral-White-Matter", 0 , 225, 0 ); MyLabels.LabelMap[42]=AnnotationType("Right-Cerebral-Cortex", 205 , 62, 78 ); MyLabels.LabelMap[43]=AnnotationType("Right-Lateral-Ventricle", 120 , 18, 134 ); MyLabels.LabelMap[44]=AnnotationType("Right-Inf-Lat-Vent", 196 , 58, 250 ); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 1; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( iren ); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); if (rep) { rep->SetImageActor( viewer->GetImageActor() ); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } set->AddWidget(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); // Our internal representation will be to manage a label map. drawing->SetRepresentationToLabel(); // This will allocate our canvas based on the size of the overlay image // that was set on the WidgetRepresentation. drawing->InitializeData(); // Clear the drawing and start on a clean slate. The drawing would have // automatically created 1 empty sketch for us, so we can start drawing // right away. Let's remove it, since we'd like to initialize the drawing // with our IBSR label map. drawing->RemoveAllItems(); // Read the IBSR label map vtkMetaImageReader * reader2 = vtkMetaImageReader::New(); reader2->SetFileName( argv[2] ); reader2->Update(); // Create a PaintbrushLabelData to represent the label map. vtkKWEPaintbrushLabelData *paintbrushLabelMap = vtkKWEPaintbrushLabelData::New(); paintbrushLabelMap->SetLabelMap( reader2->GetOutput() ); // Set the label map as the initial canvas data of the drawing. drawing->SetPaintbrushData( paintbrushLabelMap ); // Create a sketch for each label in the label map, we'd like to edit. // NOTE: We can skip labels in the label map that we do not care about simply // by not adding a sketch corresponding to that label into the drawing. In // this case, we will take into account all the labels (1-62). // NOTE: As a reminder, bear in mind that 0 is a reserved value and must not // be used as a label. for (std::map< unsigned short, AnnotationType >::const_iterator cit = MyLabels.LabelMap.begin(); cit != MyLabels.LabelMap.end(); ++cit) { // For each label. // Initialize the sketch with the label map. Note that you must add the // sketch to the drawing and set the label you wish the sketch to represent // before you initialize it from the label map. // Also note that when the representation is a "Label-map", all sketches // share the same label map to avoid memory duplication. The corollary to // this is that if you initialize sketches in your drawing using a labelmap, // you must use the same "vtkKWEPaintbrushLabelData" that is used by the // drawing. vtkKWEPaintbrushSketch * sketch = vtkKWEPaintbrushSketch::New(); drawing->AddItem( sketch ); sketch->SetLabel( cit->first ); sketch->Initialize( paintbrushLabelMap ); // Optionally, the identifier can be used to display text annotations as // you navigate through your maze of sketches. 62 segmentations can sure // get you lost pretty quickly. sketch->GetPaintbrushProperty()->SetIdentifier(cit->second.label.c_str()); // Assign a nice color to the sketch. double sketchColor[3] = { cit->second.R/255.0, cit->second.G/255.0, cit->second.B/255.0 }; sketch->GetPaintbrushProperty()->SetColor( sketchColor ); sketch->Delete(); } vtkKWEPaintbrushDrawingStatistics * statistics = vtkKWEPaintbrushDrawingStatistics::New(); statistics->SetInput(drawing); vtkKWEPaintbrushDrawingStatisticsCallback *statsCallback = vtkKWEPaintbrushDrawingStatisticsCallback::New(); statsCallback->SetPaintbrushDrawingStatistics(statistics); // Now set the drawing on all representations (axial, coronal and sagittal) // in the WidgetSet. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { set->GetNthWidget(i)->AddObserver(vtkKWEPaintbrushWidget::EndStrokeEvent, statsCallback); set->GetNthWidget(i)->AddObserver(vtkKWEPaintbrushWidget::UndoStrokeEvent, statsCallback); set->GetNthWidget(i)->AddObserver(vtkKWEPaintbrushWidget::RedoStrokeEvent, statsCallback); vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } // Enable the widget and we are done. set->SetEnabled(1); renWin->SetSize( 500, 500 ); renderer->ResetCamera(); renWin->Render(); // record/replay events vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New(); recorder->SetInteractor(iren); //Set event log recording file std::string eventLogFileName = argv[3]; recorder->SetFileName(eventLogFileName.c_str()); //Set recorder mode depending on the user's choice int retVal = 1; unsigned int mode= atoi( argv[4] ); if( mode ) { std::cout << "Interaction recording....." << std::endl; recorder->Record(); iren->Start(); } else { recorder->On(); std::cout << "Interaction replaying....." << std::endl; recorder->Play(); //recorder must be turned off before regression testing recorder->Off(); retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { recorder->GetInteractor()->Start(); } } // Clean up recorder->Off(); recorder->Delete(); viewer->Delete(); reader2->Delete(); paintbrushLabelMap->Delete(); set->Delete(); renderer->Delete(); renWin->Delete(); iren->Delete(); reader->Delete(); SliderRepres->Delete(); SliderCb->Delete(); SliderWidget->Delete(); statsCallback->Delete(); statistics->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Widgets/Testing/Cxx/PaintbrushTest6.cxx0000644000175000017500000001567411363410610023426 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // // The example differs from the previous ones in that it renders the brush in // as contours. The brush data is grayscale in nature and is represented with // vtkKWEPaintbrushGrayscaleData. The paintbrush representation is also a grayscale // representation (vtkKWEPaintbrushRepresentationGrayscale2D). #include "vtkKWEPaintbrushTesting.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentationGrayscale2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include "vtkMultiThreader.h" #include "vtkImageViewer2.h" #include #include #include #include "vtkInteractorEventRecorder.h" #include "vtkRegressionTestImage.h" int PaintbrushTest6( int argc, char *argv[] ) { if( argc < 5 ) { std::cerr << "Usage error: \t " << argv[0] << "\t" << "Input_Image_Data InitialLabelMap EventsLogFile Mode(0:replay 1:record)" << "[OutputLabelMap]" << std::endl; return EXIT_FAILURE; } vtkKWEPaintbrushTesting *paintbrushTesting = vtkKWEPaintbrushTesting::New(); paintbrushTesting->SetFilename( argv[1] ); paintbrushTesting->Initialize(); vtkImageData * imageData = paintbrushTesting->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( paintbrushTesting->GetNthImageViewer(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentationGrayscale2D * rep = vtkKWEPaintbrushRepresentationGrayscale2D::New(); w->SetRepresentation(rep); if (rep) { vtkImageActor * imageActor = paintbrushTesting->GetNthImageActor(i); rep->SetImageActor(imageActor); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } set->AddWidget(w); rep->Delete(); w->Delete(); } vtkKWEPaintbrushRepresentation2D * repx = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawingx = repx->GetPaintbrushDrawing(); for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawingx ); } // Now read in an initial segmentation. vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); drawing->InitializeData(); vtkKWEPaintbrushGrayscaleData *data = vtkKWEPaintbrushGrayscaleData::New(); // Read the file (initial segmentation) vtkMetaImageReader * reader = vtkMetaImageReader::New(); reader->SetFileName( argv[2] ); reader->Update(); data->SetImageData(reader->GetOutput()); reader->Delete(); // Set the first stroke as the initial segmentation. drawing->AddNewStroke(0, vtkKWEPaintbrushEnums::Draw, data); // Instead of the above line, you can set this directly as the new stencil, // saves some memory, as the overhead data of an extra stroke need not be // managed. // drawing->SetPaintbrushData(data); for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation * repr = vtkKWEPaintbrushRepresentation::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } set->SetEnabled(1); // record/replay events vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New(); //Interaction only in the first Image Viewer recorder->SetInteractor( paintbrushTesting->GetNthImageViewer(0)-> GetRenderWindow()->GetInteractor()); //Set event log recording file std::string eventLogFileName = argv[3]; recorder->SetFileName(eventLogFileName.c_str()); recorder->On(); //Set recorder mode depending on the user's choice unsigned int mode = atoi( argv[4] ); int retVal = 1; if( mode ) { std::cout << "Interaction recording....." << std::endl; recorder->Record(); paintbrushTesting->Run(); } else { std::cout << "Interaction replaying....." << std::endl; recorder->Play(); //recorder must be turned off before regression testing recorder->Off(); retVal = vtkRegressionTestImage( paintbrushTesting->GetNthImageViewer(0)->GetRenderWindow() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { recorder->GetInteractor()->Start(); } } // Save out the resulting segmentation. // vtkImageData * output = vtkImageData::New(); drawing->GetPaintbrushData()-> GetPaintbrushDataAsImageData( output ); vtkMetaImageWriter * outputWriter = vtkMetaImageWriter::New(); outputWriter->SetFileName("Drawing.mha"); outputWriter->SetInput( output ); outputWriter->Write(); // Save out each of the resulting segmentations. // for (int i = 0; i < drawing->GetNumberOfItems(); i++) { vtkImageData * outputN = vtkImageData::New(); drawing->GetItem(i)->GetPaintbrushData()-> GetPaintbrushDataAsImageData( outputN ); vtkMetaImageWriter * outputWriterN = vtkMetaImageWriter::New(); std::ostringstream filenameN; filenameN << "Drawing" << i << ".mha" << std::ends; outputWriterN->SetFileName(filenameN.str().c_str()); outputWriterN->SetInput( outputN ); outputWriterN->Write(); outputWriterN->Delete(); outputN->Delete(); } recorder->Delete(); data->Delete(); outputWriter->Delete(); output->Delete(); set->Delete(); paintbrushTesting->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Widgets/Testing/Cxx/vtkITKImageTest.cxx0000644000175000017500000000557711363410610023341 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkITKImage.h" #include "vtkVolume16Reader.h" #include "vtkTestUtilities.h" #include "itkImageFileWriter.h" #include "vtkXMLImageDataWriter.h" int main( int argc, char *argv[] ) { char* fname2 = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/headsq/quarter"); vtkVolume16Reader *v16 = vtkVolume16Reader::New(); v16->SetDataDimensions (64,64); v16->SetImageRange (1,93); v16->SetDataByteOrderToLittleEndian(); v16->SetFilePrefix (fname2); v16->SetDataSpacing (3.2, 3.2, 1.5); v16->Update(); vtkITKImage * image = vtkITKImage::New(); image->SetImage( v16->GetOutput() ); // vtkImageData -> vtkImageData // vtkXMLImageDataWriter *w = vtkXMLImageDataWriter::New(); w->SetInput( image->GetVTKImage() ); image->GetVTKImage()->Print(std::cout); w->SetFileName( "VTKImageToVTKImage.vtp" ); w->Update(); // vtkImageData -> itk::Image // typedef itk::Image< unsigned short, 3 > UShortImageType; itk::ImageFileWriter< UShortImageType >::Pointer w2 = itk::ImageFileWriter< UShortImageType >::New(); w2->SetInput( image->GetITKImage( static_cast< unsigned short >(0) ) ); w2->UseCompressionOn(); w2->SetFileName( "VTKImageToITKImage.mhd" ); w2->Update(); // vtkImageData -> vtkImageStencilData -> itk::Image< T > // typedef itk::Image< unsigned char, 3 > UCharImageType; itk::ImageFileWriter< UCharImageType >::Pointer w3 = itk::ImageFileWriter< UCharImageType >::New(); vtkITKImage *image2 = vtkITKImage::New(); image2->SetImage(image->GetVTKImageStencilData()); w3->SetInput( image2->GetITKImage( static_cast< unsigned char >(0) ) ); w3->SetFileName( "VTKImageToVTKImageStencilDataToITKImage.mhd" ); w3->UseCompressionOn(); w3->Update(); // itk::Image< T > --> vtkImageData // vtkXMLImageDataWriter *w4 = vtkXMLImageDataWriter::New(); vtkITKImage *image3 = vtkITKImage::New(); image3->SetImage(image2->GetITKImage( static_cast< unsigned char >(0))); w4->SetInput( image3->GetVTKImage() ); w4->SetFileName( "ITKImageToVTKImage.vtp" ); w4->Update(); w->Delete(); w4->Delete(); v16->Delete(); image->Delete(); image2->Delete(); image3->Delete(); delete [] fname2; return EXIT_SUCCESS; } vtkedge-0.2.0~20110819/Widgets/Testing/Cxx/PaintbrushTest8.cxx0000644000175000017500000002526211363410610023422 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This paintbrushTesting loads a file IBSRData.mha and a label map IBSRLabelMap-UCHAR.mha. // The label map, (courtesy of IBSR) is a label map with 62 segmentations. This // paintbrushTesting creates a sketch from each label and initializes the drawing with // these sketches. It also assigns user specified colors to the sketches. // ---------------------------------------------------------------------------- // // User interactions: // // The follwing interactions are supported by the brush in Edit mode. // Left click and drag - Draws a stroke // Ctrl-Left click and drag - Erases the stroke // Backspace or Left key - Undo the sketch (deletes the previously drawn stroke in a sketch) // Right key - Redo on the given sketch // Shift "+" - Start a new sketch. // Shift Right - Traverse to the next sketch. // Shift Left - Traverse to the previous sketch. // Shift Backspace - Delete a sketch. // Right click and drag - Resize the shape isotropically // Ctrl-Right click and drag - Resize the shape anisotropically // Shift "<" - Decrease the opacity of the overlaid drawing // Shift ">" - Increase the opacity of the overlaid drawing // "l" key - Render the current sketch immutable/mutable. // (Supported only when editing labelmaps) // Escape - Enable/Disable interactions // // The follwing interactions are supported by the brush in Select Mode // Left click - Select/Unselect a sketch // Left click and drag - Drag and drop merge of sketches. // Backspace key - Delete selected sketches. // "m" key - Merge selected sketches. // Escape - Enable/Disable interactions #include "vtkKWEPaintbrushTesting.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include "vtkMultiThreader.h" #include "vtkImageViewer2.h" #include #include #include #include "vtkInteractorEventRecorder.h" #include "vtkRegressionTestImage.h" class PaintbrushTesting8Labels { public: class Annotation { public: Annotation() {}; Annotation(const std::string &l, unsigned char r, unsigned char g, unsigned char b ) { label = l; R = r; G = g; B = b; } bool operator!=(const Annotation &a) const { return a.label != this->label; } std::string label; unsigned char R, G, B; }; std::map< unsigned short, Annotation > LabelMap; }; int PaintbrushTest8( int argc, char *argv[] ) { if( argc < 5 ) { std::cerr << "Usage error: \t " << argv[0] << "\t" << "Input_Image_Data InitialLabelMap EventsLogFile Mode(0:replay 1:record)" << "[OutputLabelMap]" << std::endl; return EXIT_FAILURE; } typedef PaintbrushTesting8Labels::Annotation AnnotationType; PaintbrushTesting8Labels MyLabels; MyLabels.LabelMap[40]=AnnotationType("Right-Cerebral-Exterior", 205 , 62, 78 ); MyLabels.LabelMap[41]=AnnotationType("Right-Cerebral-White-Matter", 0 , 225, 0 ); MyLabels.LabelMap[42]=AnnotationType("Right-Cerebral-Cortex", 205 , 62, 78 ); MyLabels.LabelMap[43]=AnnotationType("Right-Lateral-Ventricle", 120 , 18, 134 ); MyLabels.LabelMap[44]=AnnotationType("Right-Inf-Lat-Vent", 196 , 58, 250 ); vtkKWEPaintbrushTesting *paintbrushTesting = vtkKWEPaintbrushTesting::New(); paintbrushTesting->SetFilename( argv[1] ); paintbrushTesting->Initialize(); vtkImageData * imageData = paintbrushTesting->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( paintbrushTesting->GetNthImageViewer(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); if (rep) { vtkImageActor * imageActor = paintbrushTesting->GetNthImageActor(i); rep->SetImageActor(imageActor); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } set->AddWidget(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); // This will allocate our canvas based on the size of the overlay image // that was set on the WidgetRepresentation. drawing->InitializeData(); // Clear the drawing and start on a clean slate. The drawing would have // automatically created 1 empty sketch for us, so we can start drawing // right away. Let's remove it, since we'd like to initialize the drawing // with our IBSR label map. drawing->RemoveAllItems(); // Read the IBSR label map vtkMetaImageReader * reader = vtkMetaImageReader::New(); reader->SetFileName( argv[2] ); reader->Update(); // Create a PaintbrushLabelData to represent the label map. vtkKWEPaintbrushLabelData *paintbrushLabelMap = vtkKWEPaintbrushLabelData::New(); paintbrushLabelMap->SetLabelMap( reader->GetOutput() ); // Set the label map as the initial canvas data of the drawing. drawing->SetPaintbrushData( paintbrushLabelMap ); // Create a sketch for each label in the label map, we'd like to edit. // NOTE: We can skip labels in the label map that we do not care about simply // by not adding a sketch corresponding to that label into the drawing. In // this case, we will take into account all the labels (1-62). // NOTE: As a reminder, bear in mind that 0 is a reserved value and must not // be used as a label. for (std::map< unsigned short, AnnotationType >::const_iterator cit = MyLabels.LabelMap.begin(); cit != MyLabels.LabelMap.end(); ++cit) { // For each label. // Initialize the sketch with the label map. Note that you must add the // sketch to the drawing and set the label you wish the sketch to represent // before you initialize it from the label map. // Also note that when the representation is a "Label-map", all sketches // share the same label map to avoid memory duplication. The corollary to // this is that if you initialize sketches in your drawing using a labelmap, // you must use the same "vtkKWEPaintbrushLabelData" that is used by the // drawing. // Note the use of the functor to check the label in the label map. vtkKWEPaintbrushStencilData *stencilData = vtkKWEPaintbrushStencilData::New(); vtkKWEPaintbrushUtilities::GetStencilFromImage< vtkKWEPaintbrushUtilities::vtkFunctorEqualTo >( reader->GetOutput(), stencilData->GetImageStencilData(), cit->first); vtkKWEPaintbrushSketch * sketch = vtkKWEPaintbrushSketch::New(); drawing->AddItem( sketch ); sketch->AddNewStroke( vtkKWEPaintbrushEnums::Draw, stencilData ); // Optionally, the identifier can be used to display text annotations as // you navigate through your maze of sketches. 62 segmentations can sure // get you lost pretty quickly. sketch->GetPaintbrushProperty()->SetIdentifier(cit->second.label.c_str()); // Assign a nice color to the sketch. double sketchColor[3] = { cit->second.R/255.0, cit->second.G/255.0, cit->second.B/255.0 }; sketch->GetPaintbrushProperty()->SetColor( sketchColor ); sketch->Delete(); stencilData->Delete(); } reader->Delete(); // Now set the drawing on all representations (axial, coronal and sagittal) // in the WidgetSet. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } // Enable the widget and we are done. set->SetEnabled(1); // We are in selection mode, not draw mode. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::SafeDownCast( set->GetNthWidget(i)); w->SetPaintbrushMode( vtkKWEPaintbrushWidget::Select ); } // record/replay events vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New(); //Interaction only in the first Image Viewer recorder->SetInteractor( paintbrushTesting->GetNthImageViewer(0)-> GetRenderWindow()->GetInteractor()); //Set event log recording file std::string eventLogFileName = argv[3]; recorder->SetFileName(eventLogFileName.c_str()); recorder->On(); //Set recorder mode depending on the user's choice int retVal = 1; unsigned int mode= atoi( argv[4] ); if( mode ) { std::cout << "Interaction recording....." << std::endl; recorder->Record(); paintbrushTesting->Run(); } else { std::cout << "Interaction replaying....." << std::endl; recorder->Play(); //recorder must be turned off before regression testing recorder->Off(); retVal = vtkRegressionTestImage( paintbrushTesting->GetNthImageViewer(0)->GetRenderWindow() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { recorder->GetInteractor()->Start(); } } // clean up recorder->Off(); recorder->Delete(); paintbrushLabelMap->Delete(); set->Delete(); paintbrushTesting->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Widgets/Testing/Cxx/PaintbrushTest4.cxx0000644000175000017500000002507711363410610023422 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This paintbrushTesting loads a file IBSRData.mha and a label map IBSRLabelMap-UCHAR.mha. // The label map, (courtesy of IBSR) is a label map with 62 segmentations. This // paintbrushTesting creates a sketch from each label and initializes the drawing with // these sketches. It also assigns user specified colors to the sketches. // ---------------------------------------------------------------------------- // // User interactions: // // The follwing interactions are supported by the brush in Edit mode. // Left click and drag - Draws a stroke // Ctrl-Left click and drag - Erases the stroke // Backspace or Left key - Undo the sketch (deletes the previously drawn stroke in a sketch) // Right key - Redo on the given sketch // Shift "+" - Start a new sketch. // Shift Right - Traverse to the next sketch. // Shift Left - Traverse to the previous sketch. // Shift Backspace - Delete a sketch. // Right click and drag - Resize the shape isotropically // Ctrl-Right click and drag - Resize the shape anisotropically // Shift "<" - Decrease the opacity of the overlaid drawing // Shift ">" - Increase the opacity of the overlaid drawing // "l" key - Render the current sketch immutable/mutable. // (Supported only when editing labelmaps) // Escape - Enable/Disable interactions // // The follwing interactions are supported by the brush in Select Mode // Left click - Select/Unselect a sketch // Left click and drag - Drag and drop merge of sketches. // Backspace key - Delete selected sketches. // "m" key - Merge selected sketches. // Escape - Enable/Disable interactions #include "vtkKWEPaintbrushTesting.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include "vtkMultiThreader.h" #include "vtkImageViewer2.h" #include #include #include #include "vtkInteractorEventRecorder.h" #include "vtkRegressionTestImage.h" class PaintbrushTesting4Labels { public: class Annotation { public: Annotation() {}; Annotation(const std::string &l, unsigned char r, unsigned char g, unsigned char b ) { label = l; R = r; G = g; B = b; } bool operator!=(const Annotation &a) const { return a.label != this->label; } std::string label; unsigned char R, G, B; }; std::map< unsigned short, Annotation > LabelMap; }; int PaintbrushTest4( int argc, char *argv[] ) { if( argc < 6 ) { std::cerr << "Usage error: \t " << argv[0] << "\t" << "Input_Image_Data InitialLabelMap EventsLogFile Mode(0:replay 1:record)" << "[OutputLabelMap]" << std::endl; return EXIT_FAILURE; } typedef PaintbrushTesting4Labels::Annotation AnnotationType; PaintbrushTesting4Labels MyLabels; MyLabels.LabelMap[40]=AnnotationType("Right-Cerebral-Exterior", 205 , 62, 78 ); MyLabels.LabelMap[41]=AnnotationType("Right-Cerebral-White-Matter", 0 , 225, 0 ); MyLabels.LabelMap[42]=AnnotationType("Right-Cerebral-Cortex", 205 , 62, 78 ); MyLabels.LabelMap[43]=AnnotationType("Right-Lateral-Ventricle", 120 , 18, 134 ); MyLabels.LabelMap[44]=AnnotationType("Right-Inf-Lat-Vent", 196 , 58, 250 ); vtkKWEPaintbrushTesting *paintbrushTesting = vtkKWEPaintbrushTesting::New(); paintbrushTesting->SetFilename( argv[1] ); paintbrushTesting->Initialize(); vtkImageData * imageData = paintbrushTesting->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( paintbrushTesting->GetNthImageViewer(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); if (rep) { vtkImageActor * imageActor = paintbrushTesting->GetNthImageActor(i); rep->SetImageActor(imageActor); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } set->AddWidget(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); // Our internal representation will be to manage a label map. drawing->SetRepresentationToLabel(); // This will allocate our canvas based on the size of the overlay image // that was set on the WidgetRepresentation. drawing->InitializeData(); // Clear the drawing and start on a clean slate. The drawing would have // automatically created 1 empty sketch for us, so we can start drawing // right away. Let's remove it, since we'd like to initialize the drawing // with our IBSR label map. drawing->RemoveAllItems(); // Read the IBSR label map vtkMetaImageReader * reader = vtkMetaImageReader::New(); reader->SetFileName( argv[2] ); reader->Update(); // Create a PaintbrushLabelData to represent the label map. vtkKWEPaintbrushLabelData *paintbrushLabelMap = vtkKWEPaintbrushLabelData::New(); paintbrushLabelMap->SetLabelMap( reader->GetOutput() ); // Set the label map as the initial canvas data of the drawing. drawing->SetPaintbrushData( paintbrushLabelMap ); // Create a sketch for each label in the label map, we'd like to edit. // NOTE: We can skip labels in the label map that we do not care about simply // by not adding a sketch corresponding to that label into the drawing. In // this case, we will take into account all the labels (1-62). // NOTE: As a reminder, bear in mind that 0 is a reserved value and must not // be used as a label. for (std::map< unsigned short, AnnotationType >::const_iterator cit = MyLabels.LabelMap.begin(); cit != MyLabels.LabelMap.end(); ++cit) { // For each label. // Initialize the sketch with the label map. Note that you must add the // sketch to the drawing and set the label you wish the sketch to represent // before you initialize it from the label map. // Also note that when the representation is a "Label-map", all sketches // share the same label map to avoid memory duplication. The corollary to // this is that if you initialize sketches in your drawing using a labelmap, // you must use the same "vtkKWEPaintbrushLabelData" that is used by the // drawing. vtkKWEPaintbrushSketch * sketch = vtkKWEPaintbrushSketch::New(); drawing->AddItem( sketch ); sketch->SetLabel( cit->first ); sketch->Initialize( paintbrushLabelMap ); // Optionally, the identifier can be used to display text annotations as // you navigate through your maze of sketches. 62 segmentations can sure // get you lost pretty quickly. sketch->GetPaintbrushProperty()->SetIdentifier(cit->second.label.c_str()); // Assign a nice color to the sketch. double sketchColor[3] = { cit->second.R/255.0, cit->second.G/255.0, cit->second.B/255.0 }; sketch->GetPaintbrushProperty()->SetColor( sketchColor ); sketch->Delete(); } reader->Delete(); // Now set the drawing on all representations (axial, coronal and sagittal) // in the WidgetSet. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } // Enable the widget and we are done. set->SetEnabled(1); // record/replay events vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New(); //Interaction only in the first Image Viewer recorder->SetInteractor( paintbrushTesting->GetNthImageViewer(0)-> GetRenderWindow()->GetInteractor()); //Set event log recording file std::string eventLogFileName = argv[3]; recorder->SetFileName(eventLogFileName.c_str()); recorder->On(); //Set recorder mode depending on the user's choice int retVal = 1; unsigned int mode= atoi( argv[4] ); if( mode ) { std::cout << "Interaction recording....." << std::endl; recorder->Record(); paintbrushTesting->Run(); } else { std::cout << "Interaction replaying....." << std::endl; recorder->Play(); //recorder must be turned off before regression testing recorder->Off(); retVal = vtkRegressionTestImage( paintbrushTesting->GetNthImageViewer(0)->GetRenderWindow() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { recorder->GetInteractor()->Start(); } } if (argc >= 6) { vtkKWEPaintbrushLabelData * finalLabelMap = vtkKWEPaintbrushLabelData::SafeDownCast(drawing->GetPaintbrushData()); vtkMetaImageWriter * outputWriter = vtkMetaImageWriter::New(); outputWriter->SetFileName(argv[5]); outputWriter->SetInput( finalLabelMap->GetLabelMap() ); outputWriter->Write(); outputWriter->Delete(); } // clean up recorder->Off(); recorder->Delete(); paintbrushLabelMap->Delete(); set->Delete(); paintbrushTesting->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Widgets/Testing/Cxx/CMakeLists.txt0000644000175000017500000001212711502655425022375 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Name this kit - this will be used to form test executable names later # Then we'll add in tests with various data or kit dependencies to the # test executables # ----------------------------------------------------------------------------- set(KIT Widgets) set(TESTBASE ${PROJECT_NAME}${KIT}) set(WIDGETS_DATA_ROOT ${VTKEdge_SOURCE_DIR}/Data) set(CXX_TEST_PATH ${EXECUTABLE_OUTPUT_PATH}) set(MyTests PaintbrushTest1.cxx PaintbrushTest1b.cxx PaintbrushTest1c.cxx PaintbrushTest2.cxx PaintbrushTest3.cxx PaintbrushTest4.cxx PaintbrushTest5.cxx PaintbrushTest6.cxx PaintbrushTest7.cxx PaintbrushTest8.cxx PaintbrushInstantiatonMemLeaksTest.cxx ) create_test_sourcelist(Tests ${TESTBASE}CxxTests.cxx ${MyTests} EXTRA_INCLUDE vtkTestDriver.h ) add_executable(${TESTBASE}CxxTests ${Tests}) #install_targets(${VTKEdge_INSTALL_BIN_DIR} ${TESTBASE}CxxTests) target_link_libraries(${TESTBASE}CxxTests vtkRendering vtkIO vtkKWEWidgets vtkFiltering vtkImaging ) #ADD regression testing set(labelmap_type "USHORT") if (VTKEdge_PAINTBRUSH_LABEL_TYPE STREQUAL "VTK_UNSIGNED_CHAR") set(labelmap_type "UCHAR") endif (VTKEdge_PAINTBRUSH_LABEL_TYPE STREQUAL "VTK_UNSIGNED_CHAR") add_test(PaintbrushTest1 ${CXX_TEST_PATH}/${TESTBASE}CxxTests PaintbrushTest1 ${WIDGETS_DATA_ROOT}/Data/IBSRDataCropped.mha ${WIDGETS_DATA_ROOT}/Data/IBSRLabelMap-4Labels-${labelmap_type}-Cropped.mha ${WIDGETS_DATA_ROOT}/Data/PaintbrushTest1InputEventLog.txt 0 ${CMAKE_CURRENT_BINARY_DIR}/EditedLabelMap.mha ) add_test(PaintbrushTest1b ${CXX_TEST_PATH}/${TESTBASE}CxxTests PaintbrushTest1b ${WIDGETS_DATA_ROOT}/Data/IBSRDataCropped.mha ${WIDGETS_DATA_ROOT}/Data/IBSRLabelMap-4Labels-${labelmap_type}-Cropped.mha ${WIDGETS_DATA_ROOT}/Data/PaintbrushTest1bInputEventLog.txt 0 ${CMAKE_CURRENT_BINARY_DIR}/EditedLabelMap.mha ) add_test(PaintbrushTest1c ${CXX_TEST_PATH}/${TESTBASE}CxxTests PaintbrushTest1c ${WIDGETS_DATA_ROOT}/Data/IBSRDataCropped.mha ${WIDGETS_DATA_ROOT}/Data/IBSRLabelMap-4Labels-${labelmap_type}-Cropped.mha ${WIDGETS_DATA_ROOT}/Data/PaintbrushTest1cInputEventLog.txt 0 ${CMAKE_CURRENT_BINARY_DIR}/EditedLabelMap.mha ) add_test(PaintbrushTest2 ${CXX_TEST_PATH}/${TESTBASE}CxxTests PaintbrushTest2 ${WIDGETS_DATA_ROOT}/Data/HeadMR.mha ${WIDGETS_DATA_ROOT}/Data/PaintbrushTest2InputEventLog.txt 0 ) add_test(PaintbrushTest3 ${CXX_TEST_PATH}/${TESTBASE}CxxTests PaintbrushTest3 ${WIDGETS_DATA_ROOT}/Data/IBSRDataCropped.mha ${WIDGETS_DATA_ROOT}/Data/IBSRLabelMap-4Labels-${labelmap_type}-Cropped.mha ${WIDGETS_DATA_ROOT}/Data/PaintbrushTest3InputEventLog.txt 0 ${CMAKE_CURRENT_BINARY_DIR}/Temporary/EditedLabelMap.mha ) add_test(PaintbrushTest4 ${CXX_TEST_PATH}/${TESTBASE}CxxTests PaintbrushTest4 ${WIDGETS_DATA_ROOT}/Data/IBSRDataCropped.mha ${WIDGETS_DATA_ROOT}/Data/IBSRLabelMap-4Labels-${labelmap_type}-Cropped.mha ${WIDGETS_DATA_ROOT}/Data/PaintbrushTest4InputEventLog.txt 0 ${CMAKE_CURRENT_BINARY_DIR}/Temporary/EditedLabelMap.mha ) add_test(PaintbrushTest5 ${CXX_TEST_PATH}/${TESTBASE}CxxTests PaintbrushTest5 ${WIDGETS_DATA_ROOT}/Data/IBSRData.mha ${WIDGETS_DATA_ROOT}/Data/IBSRLabelMap-4Labels-${labelmap_type}.mha ${WIDGETS_DATA_ROOT}/Data/PaintbrushTest4InputEventLog.txt 0 ${CMAKE_CURRENT_BINARY_DIR}/Temporary/EditedLabelMap.mha ) add_test(PaintbrushTest6 ${CXX_TEST_PATH}/${TESTBASE}CxxTests PaintbrushTest6 ${WIDGETS_DATA_ROOT}/Data/IBSRDataCropped.mha ${WIDGETS_DATA_ROOT}/Data/IBSRLabelMap-WhiteMatter-${labelmap_type}-Cropped.mha ${WIDGETS_DATA_ROOT}/Data/PaintbrushTest6InputEventLog.txt 0 ) add_test(PaintbrushTest7 ${CXX_TEST_PATH}/${TESTBASE}CxxTests PaintbrushTest7 ${WIDGETS_DATA_ROOT}/Data/IBSRDataCropped.mha ${WIDGETS_DATA_ROOT}/Data/IBSRLabelMap-4Labels-${labelmap_type}-Cropped.mha ${WIDGETS_DATA_ROOT}/Data/PaintbrushTest7InputEventLog.txt 0 ${CMAKE_CURRENT_BINARY_DIR}/Temporary/EditedLabelMap.mha ) add_test(PaintbrushTest8 ${CXX_TEST_PATH}/${TESTBASE}CxxTests PaintbrushTest8 ${WIDGETS_DATA_ROOT}/Data/IBSRDataCropped.mha ${WIDGETS_DATA_ROOT}/Data/IBSRLabelMap-4Labels-${labelmap_type}-Cropped.mha ${WIDGETS_DATA_ROOT}/Data/PaintbrushTest8InputEventLog.txt 0 ) add_test( PaintbrushInstantiationMemLeaksTest ${CXX_TEST_PATH}/${TESTBASE}CxxTests PaintbrushInstantiatonMemLeaksTest ) vtkedge-0.2.0~20110819/Widgets/Testing/Cxx/PaintbrushTest5.cxx0000644000175000017500000002305111363410610023411 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // // Same as PaintbrushTest4 except that it shows you how you can ignore the // overlay image. To do this, you simply have to set the mode on the // PaintbrushBlend class. See documentation of PaintbrushBlend::SetUseOverlay // // Use an overlay ? Defaults to ON. // If ON, this class will produce an output image that represents a blending // of the input and the drawing, passed through a color lookup table. // If OFF, this class will produce an output image that is the drawing passed // through a color lookup table. // // In this example, we will set it to OFF> // ---------------------------------------------------------------------------- #include "vtkKWEPaintbrushTesting.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include "vtkMultiThreader.h" #include "vtkImageViewer2.h" #include #include #include #include "vtkInteractorEventRecorder.h" #include "vtkRegressionTestImage.h" class PaintbrushTesting4Labels { public: class Annotation { public: Annotation() {}; Annotation(const std::string &l, unsigned char r, unsigned char g, unsigned char b ) { label = l; R = r; G = g; B = b; } bool operator!=(const Annotation &a) const { return a.label != this->label; } std::string label; unsigned char R, G, B; }; std::map< unsigned short, Annotation > LabelMap; }; int PaintbrushTest5( int argc, char *argv[] ) { if( argc < 6 ) { std::cerr << "Usage error: \t " << argv[0] << "\t" << "Input_Image_Data InitialLabelMap EventsLogFile Mode(0:replay 1:record)" << "[OutputLabelMap]" << std::endl; return EXIT_FAILURE; } typedef PaintbrushTesting4Labels::Annotation AnnotationType; PaintbrushTesting4Labels MyLabels; MyLabels.LabelMap[40]=AnnotationType("Right-Cerebral-Exterior", 205 , 62, 78 ); MyLabels.LabelMap[41]=AnnotationType("Right-Cerebral-White-Matter", 0 , 225, 0 ); MyLabels.LabelMap[42]=AnnotationType("Right-Cerebral-Cortex", 205 , 62, 78 ); MyLabels.LabelMap[43]=AnnotationType("Right-Lateral-Ventricle", 120 , 18, 134 ); MyLabels.LabelMap[44]=AnnotationType("Right-Inf-Lat-Vent", 196 , 58, 250 ); vtkKWEPaintbrushTesting *paintbrushTesting = vtkKWEPaintbrushTesting::New(); paintbrushTesting->SetFilename( argv[1] ); paintbrushTesting->Initialize(); vtkImageData * imageData = paintbrushTesting->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( paintbrushTesting->GetNthImageViewer(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); if (rep) { vtkImageActor * imageActor = paintbrushTesting->GetNthImageActor(i); rep->SetImageActor(imageActor); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } set->AddWidget(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); // Our internal representation will be to manage a label map. drawing->SetRepresentationToLabel(); // This will allocate our canvas based on the size of the overlay image // that was set on the WidgetRepresentation. drawing->InitializeData(); // Clear the drawing and start on a clean slate. The drawing would have // automatically created 1 empty sketch for us, so we can start drawing // right away. Let's remove it, since we'd like to initialize the drawing // with our IBSR label map. drawing->RemoveAllItems(); // Read the IBSR label map vtkMetaImageReader * reader = vtkMetaImageReader::New(); reader->SetFileName( argv[2] ); reader->Update(); // Create a PaintbrushLabelData to represent the label map. vtkKWEPaintbrushLabelData *paintbrushLabelMap = vtkKWEPaintbrushLabelData::New(); paintbrushLabelMap->SetLabelMap( reader->GetOutput() ); // Set the label map as the initial canvas data of the drawing. drawing->SetPaintbrushData( paintbrushLabelMap ); // Create a sketch for each label in the label map, we'd like to edit. // NOTE: We can skip labels in the label map that we do not care about simply // by not adding a sketch corresponding to that label into the drawing. In // this case, we will take into account all the labels (1-62). // NOTE: As a reminder, bear in mind that 0 is a reserved value and must not // be used as a label. for (std::map< unsigned short, AnnotationType >::const_iterator cit = MyLabels.LabelMap.begin(); cit != MyLabels.LabelMap.end(); ++cit) { // For each label. // Initialize the sketch with the label map. Note that you must add the // sketch to the drawing and set the label you wish the sketch to represent // before you initialize it from the label map. // Also note that when the representation is a "Label-map", all sketches // share the same label map to avoid memory duplication. The corollary to // this is that if you initialize sketches in your drawing using a labelmap, // you must use the same "vtkKWEPaintbrushLabelData" that is used by the // drawing. vtkKWEPaintbrushSketch * sketch = vtkKWEPaintbrushSketch::New(); drawing->AddItem( sketch ); sketch->SetLabel( cit->first ); sketch->Initialize( paintbrushLabelMap ); // Optionally, the identifier can be used to display text annotations as // you navigate through your maze of sketches. 62 segmentations can sure // get you lost pretty quickly. sketch->GetPaintbrushProperty()->SetIdentifier(cit->second.label.c_str()); // Assign a nice color to the sketch. double sketchColor[3] = { cit->second.R/255.0, cit->second.G/255.0, cit->second.B/255.0 }; sketch->GetPaintbrushProperty()->SetColor( sketchColor ); sketch->Delete(); } reader->Delete(); // Now set the drawing on all representations (axial, coronal and sagittal) // in the WidgetSet. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); repr->UseOverlayOff(); // Disable the use of the overlay. } // Enable the widget and we are done. set->SetEnabled(1); // record/replay events vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New(); //Interaction only in the first Image Viewer recorder->SetInteractor( paintbrushTesting->GetNthImageViewer(0)-> GetRenderWindow()->GetInteractor()); //Set event log recording file std::string eventLogFileName = argv[3]; recorder->SetFileName(eventLogFileName.c_str()); recorder->On(); //Set recorder mode depending on the user's choice int retVal = 1; unsigned int mode= atoi( argv[4] ); if( mode ) { std::cout << "Interaction recording....." << std::endl; recorder->Record(); paintbrushTesting->Run(); } else { std::cout << "Interaction replaying....." << std::endl; recorder->Play(); //recorder must be turned off before regression testing recorder->Off(); retVal = vtkRegressionTestImage( paintbrushTesting->GetNthImageViewer(0)->GetRenderWindow() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { recorder->GetInteractor()->Start(); } } if (argc >= 6) { vtkKWEPaintbrushLabelData * finalLabelMap = vtkKWEPaintbrushLabelData::SafeDownCast(drawing->GetPaintbrushData()); vtkMetaImageWriter * outputWriter = vtkMetaImageWriter::New(); outputWriter->SetFileName(argv[5]); outputWriter->SetInput( finalLabelMap->GetLabelMap() ); outputWriter->Write(); outputWriter->Delete(); } // clean up recorder->Off(); recorder->Delete(); paintbrushLabelMap->Delete(); set->Delete(); // Delete the widgets before the interactor. Need valid iren. paintbrushTesting->Delete(); // Delete the Render window interactor last. return !retVal; } vtkedge-0.2.0~20110819/Widgets/Testing/Cxx/PaintbrushInstantiatonMemLeaksTest.cxx0000644000175000017500000001150311363410610027336 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushRepresentationGrayscale2D.h" #include "vtkKWEPaintbrushMergeSketches.h" //#include "vtkITKPaintbrushExtractConnectedComponents.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushStroke.h" #include "vtkKWEPaintbrushShapeEllipsoid.h" #include "vtkKWEPaintbrushShapeBox.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushBlend.h" #include "vtkKWEPaintbrushAnnotationRepresentation.h" #include "vtkKWEPaintbrushAnnotationWidget.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushPropertyManager.h" #include "vtkKWEWidgetGroup.h" #include "vtkGarbageCollector.h" int PaintbrushInstantiatonMemLeaksTest( int , char *[] ) { { vtkKWEPaintbrushWidget *o = vtkKWEPaintbrushWidget::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushAnnotationWidget *o = vtkKWEPaintbrushAnnotationWidget::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushRepresentationGrayscale2D *o = vtkKWEPaintbrushRepresentationGrayscale2D::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushRepresentation2D *o = vtkKWEPaintbrushRepresentation2D::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushAnnotationRepresentation *o = vtkKWEPaintbrushAnnotationRepresentation::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushStencilData *o = vtkKWEPaintbrushStencilData::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushGrayscaleData *o = vtkKWEPaintbrushGrayscaleData::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushLabelData *o = vtkKWEPaintbrushLabelData::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushDrawing *o = vtkKWEPaintbrushDrawing::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushSketch *o = vtkKWEPaintbrushSketch::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushStroke *o = vtkKWEPaintbrushStroke::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushShapeEllipsoid *o = vtkKWEPaintbrushShapeEllipsoid::New(); double w[3]; o->GetWidth(w); (void)w; o->SetResolution(10); int res = o->GetResolution(); if (res != 10) { return EXIT_FAILURE; } vtkKWEPaintbrushShapeEllipsoid *o2 = vtkKWEPaintbrushShapeEllipsoid::New(); o2->DeepCopy(o); o2->Print(std::cout); o2->Delete(); o->Delete(); } { vtkKWEPaintbrushShapeBox *o = vtkKWEPaintbrushShapeBox::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushOperation *o = vtkKWEPaintbrushOperation::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushBlend *o = vtkKWEPaintbrushBlend::New(); o->Print(std::cout); o->Delete(); } { vtkKWEWidgetGroup *o = vtkKWEWidgetGroup::New(); o->Print(std::cout); o->Delete(); } { vtkKWEPaintbrushMergeSketches *o = vtkKWEPaintbrushMergeSketches::New(); o->Print(std::cout); o->Delete(); } { //vtkITKPaintbrushExtractConnectedComponents *o = vtkITKPaintbrushExtractConnectedComponents::New(); //o->Print(std::cout); //o->Delete(); } { vtkKWEWidgetGroup *os = vtkKWEWidgetGroup::New(); vtkKWEPaintbrushWidget *o = vtkKWEPaintbrushWidget::New(); os->AddWidget(o); o->Delete(); vtkKWEPaintbrushWidget *o1 = vtkKWEPaintbrushWidget::New(); os->AddWidget(o1); os->Print(std::cout); o1->Delete(); os->Delete(); } { vtkKWEWidgetGroup *os = vtkKWEWidgetGroup::New(); vtkKWEPaintbrushWidget *o = vtkKWEPaintbrushWidget::New(); os->AddWidget(o); o->Delete(); os->RemoveWidget(o); vtkKWEPaintbrushWidget *o1 = vtkKWEPaintbrushWidget::New(); os->AddWidget(o1); o1->Delete(); os->Delete(); } return EXIT_SUCCESS; } vtkedge-0.2.0~20110819/Widgets/Testing/Cxx/PaintbrushTest7.cxx0000644000175000017500000002234711363410610023422 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // // Uses a box as the paintbrush shape. #include "vtkKWEPaintbrushTesting.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShapeBox.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include "vtkMultiThreader.h" #include "vtkImageViewer2.h" #include #include #include #include "vtkInteractorEventRecorder.h" #include "vtkRegressionTestImage.h" class PaintbrushTesting4Labels { public: class Annotation { public: Annotation() {}; Annotation(const std::string &l, unsigned char r, unsigned char g, unsigned char b ) { label = l; R = r; G = g; B = b; } bool operator!=(const Annotation &a) const { return a.label != this->label; } std::string label; unsigned char R, G, B; }; std::map< unsigned short, Annotation > LabelMap; }; int PaintbrushTest7( int argc, char *argv[] ) { if( argc < 6 ) { std::cerr << "Usage error: \t " << argv[0] << "\t" << "Input_Image_Data InitialLabelMap EventsLogFile Mode(0:replay 1:record)" << "[OutputLabelMap]" << std::endl; return EXIT_FAILURE; } typedef PaintbrushTesting4Labels::Annotation AnnotationType; PaintbrushTesting4Labels MyLabels; MyLabels.LabelMap[40]=AnnotationType("Right-Cerebral-Exterior", 205 , 62, 78 ); MyLabels.LabelMap[41]=AnnotationType("Right-Cerebral-White-Matter", 0 , 225, 0 ); MyLabels.LabelMap[42]=AnnotationType("Right-Cerebral-Cortex", 205 , 62, 78 ); MyLabels.LabelMap[43]=AnnotationType("Right-Lateral-Ventricle", 120 , 18, 134 ); MyLabels.LabelMap[44]=AnnotationType("Right-Inf-Lat-Vent", 196 , 58, 250 ); vtkKWEPaintbrushTesting *paintbrushTesting = vtkKWEPaintbrushTesting::New(); paintbrushTesting->SetFilename( argv[1] ); cout << "Reading : " << paintbrushTesting->GetFilename() << endl; paintbrushTesting->FourPaneViewOff(); cout << "Does paintbrush testing have four pane view ? " << paintbrushTesting->GetFourPaneView() << endl; paintbrushTesting->Initialize(); vtkImageData * imageData = paintbrushTesting->GetInput(); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 3; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( paintbrushTesting->GetNthImageViewer(i)-> GetRenderWindow()->GetInteractor()); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); if (rep) { vtkImageActor * imageActor = paintbrushTesting->GetNthImageActor(i); rep->SetImageActor(imageActor); rep->SetImageData(imageData); // Set a cuboid as the paintbrush shape instead of the default ellipsoid vtkKWEPaintbrushShapeBox * shape = vtkKWEPaintbrushShapeBox::New(); rep->GetPaintbrushOperation()->SetPaintbrushShape(shape); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); shape->Delete(); } set->AddWidget(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); // Our internal representation will be to manage a label map. drawing->SetRepresentationToLabel(); // This will allocate our canvas based on the size of the overlay image // that was set on the WidgetRepresentation. drawing->InitializeData(); // Clear the drawing and start on a clean slate. The drawing would have // automatically created 1 empty sketch for us, so we can start drawing // right away. Let's remove it, since we'd like to initialize the drawing // with our IBSR label map. drawing->RemoveAllItems(); // Read the IBSR label map vtkMetaImageReader * reader = vtkMetaImageReader::New(); reader->SetFileName( argv[2] ); reader->Update(); // Create a PaintbrushLabelData to represent the label map. vtkKWEPaintbrushLabelData *paintbrushLabelMap = vtkKWEPaintbrushLabelData::New(); paintbrushLabelMap->SetLabelMap( reader->GetOutput() ); // Set the label map as the initial canvas data of the drawing. drawing->SetPaintbrushData( paintbrushLabelMap ); // Create a sketch for each label in the label map, we'd like to edit. // NOTE: We can skip labels in the label map that we do not care about simply // by not adding a sketch corresponding to that label into the drawing. In // this case, we will take into account all the labels (1-62). // NOTE: As a reminder, bear in mind that 0 is a reserved value and must not // be used as a label. for (std::map< unsigned short, AnnotationType >::const_iterator cit = MyLabels.LabelMap.begin(); cit != MyLabels.LabelMap.end(); ++cit) { // For each label. // Initialize the sketch with the label map. Note that you must add the // sketch to the drawing and set the label you wish the sketch to represent // before you initialize it from the label map. // Also note that when the representation is a "Label-map", all sketches // share the same label map to avoid memory duplication. The corollary to // this is that if you initialize sketches in your drawing using a labelmap, // you must use the same "vtkKWEPaintbrushLabelData" that is used by the // drawing. vtkKWEPaintbrushSketch * sketch = vtkKWEPaintbrushSketch::New(); drawing->AddItem( sketch ); sketch->SetLabel( cit->first ); sketch->Initialize( paintbrushLabelMap ); // Optionally, the identifier can be used to display text annotations as // you navigate through your maze of sketches. 62 segmentations can sure // get you lost pretty quickly. sketch->GetPaintbrushProperty()->SetIdentifier(cit->second.label.c_str()); // Assign a nice color to the sketch. double sketchColor[3] = { cit->second.R/255.0, cit->second.G/255.0, cit->second.B/255.0 }; sketch->GetPaintbrushProperty()->SetColor( sketchColor ); sketch->Delete(); } reader->Delete(); // Now set the drawing on all representations (axial, coronal and sagittal) // in the WidgetSet. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } // Enable the widget and we are done. set->SetEnabled(1); // record/replay events vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New(); //Interaction only in the first Image Viewer recorder->SetInteractor( paintbrushTesting->GetNthImageViewer(0)-> GetRenderWindow()->GetInteractor()); //Set event log recording file std::string eventLogFileName = argv[3]; recorder->SetFileName(eventLogFileName.c_str()); recorder->On(); //Set recorder mode depending on the user's choice int retVal = 1; unsigned int mode= atoi( argv[4] ); if( mode ) { std::cout << "Interaction recording....." << std::endl; recorder->Record(); paintbrushTesting->Run(); } else { std::cout << "Interaction replaying....." << std::endl; recorder->Play(); //recorder must be turned off before regression testing recorder->Off(); retVal = vtkRegressionTestImage( paintbrushTesting->GetNthImageViewer(0)->GetRenderWindow() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { recorder->GetInteractor()->Start(); } } if (argc >= 6) { vtkKWEPaintbrushLabelData * finalLabelMap = vtkKWEPaintbrushLabelData::SafeDownCast(drawing->GetPaintbrushData()); vtkMetaImageWriter * outputWriter = vtkMetaImageWriter::New(); outputWriter->SetFileName(argv[5]); outputWriter->SetInput( finalLabelMap->GetLabelMap() ); outputWriter->Write(); outputWriter->Delete(); } // clean up recorder->Off(); recorder->Delete(); paintbrushLabelMap->Delete(); set->Delete(); paintbrushTesting->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Widgets/Testing/Cxx/PaintbrushTest1.cxx0000644000175000017500000003336711502612435023424 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This test loads a file IBSRData.mha and a label map IBSRLabelMap-UCHAR.mha. // The label map, (courtesy of IBSR) is a label map with 62 segmentations. This // test creates a sketch from each label and initializes the drawing with // these sketches. It also assigns user specified colors to the sketches. // ---------------------------------------------------------------------------- // // User interactions: // // The follwing interactions are supported by the brush in Edit mode. // Left click and drag - Draws a stroke // Ctrl-Left click and drag - Erases the stroke // Backspace or Left key - Undo the sketch (deletes the previously drawn stroke in a sketch) // Right key - Redo on the given sketch // Shift "+" - Start a new sketch. // Shift Right - Traverse to the next sketch. // Shift Left - Traverse to the previous sketch. // Shift Backspace - Delete a sketch. // Right click and drag - Resize the shape isotropically // Ctrl-Right click and drag - Resize the shape anisotropically // Shift "<" - Decrease the opacity of the overlaid drawing // Shift ">" - Increase the opacity of the overlaid drawing // "l" key - Render the current sketch immutable/mutable. // (Supported only when editing labelmaps) // Escape - Enable/Disable interactions // // The follwing interactions are supported by the brush in Select Mode // Left click - Select/Unselect a sketch // Left click and drag - Drag and drop merge of sketches. // Backspace key - Delete selected sketches. // "m" key - Merge selected sketches. // Escape - Enable/Disable interactions #include "vtkInteractorEventRecorder.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkImageViewer2.h" #include "vtkRenderer.h" #include "vtkRenderer.h" #include "vtkCommand.h" #include "vtkCamera.h" #include "vtkRegressionTestImage.h" #include "vtkDebugLeaks.h" #include "vtkRegressionTestImage.h" #include "vtkDebugLeaks.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkSliderRepresentation.h" #include "vtkSliderRepresentation2D.h" #include "vtkSliderWidget.h" #include "vtkMetaImageReader.h" #include "vtkImageActor.h" #include "vtkImageData.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include #include #include class PaintbrushTest1Labels { public: class Annotation { public: Annotation() {}; Annotation(const std::string &l, unsigned char r, unsigned char g, unsigned char b ) { label = l; R = r; G = g; B = b; } bool operator!=(const Annotation &a) const { return a.label != this->label; } std::string label; unsigned char R, G, B; }; std::map< unsigned short, Annotation > LabelMap; }; class vtkSliderCallback100 : public vtkCommand { public: static vtkSliderCallback100 *New() { return new vtkSliderCallback100; } void SetImageViewer(vtkImageViewer2 *viewer) { m_Viewer = viewer; } virtual void Execute(vtkObject *caller, unsigned long , void* ) { vtkSliderWidget *slider = static_cast(caller); vtkSliderRepresentation *sliderRepres = static_cast(slider->GetRepresentation()); int pos = static_cast(sliderRepres->GetValue()); m_Viewer->SetSlice(pos); } protected: vtkImageViewer2 *m_Viewer; }; int PaintbrushTest1( int argc , char *argv[]) { if( argc < 6 ) { std::cerr << "Usage error: \t " << argv[0] << "\t" << "Input_Image_Data InitialLabelMap EventsLogFile Mode(0:replay 1:record)" << "[OutputLabelMap]" << std::endl; return EXIT_FAILURE; } vtkImageReader2 * reader = vtkMetaImageReader::New(); reader->SetFileName( argv[1] ); if( reader->CanReadFile( argv[1] ) != 3 ) { std::cerr << "Meta image reader couldn't read the input data\t" << std::endl; return EXIT_FAILURE; } reader->Update(); vtkImageData * imageData = reader->GetOutput(); vtkRenderer *renderer = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); vtkImageViewer2 *viewer = vtkImageViewer2::New(); viewer->SetRenderWindow(renWin); viewer->SetRenderer(renderer); viewer->SetInput(imageData); viewer->SetupInteractor(iren); double *range = imageData->GetScalarRange(); viewer->SetColorWindow(range[1] - range[0]); viewer->SetColorLevel(0.5 * (range[1] + range[0])+ 0.0000001); // Tie a slider widget to manipulate the slices of the image viewer // vtkSliderRepresentation2D *SliderRepres = vtkSliderRepresentation2D::New(); int min = viewer->GetSliceMin(); int max = viewer->GetSliceMax(); SliderRepres->SetMinimumValue(min); SliderRepres->SetMaximumValue(max); SliderRepres->SetValue(static_cast((min + max) / 2)); SliderRepres->SetTitleText("Slice"); SliderRepres->GetPoint1Coordinate()->SetCoordinateSystemToNormalizedDisplay(); SliderRepres->GetPoint1Coordinate()->SetValue(0.3, 0.05); SliderRepres->GetPoint2Coordinate()->SetCoordinateSystemToNormalizedDisplay(); SliderRepres->GetPoint2Coordinate()->SetValue(0.7, 0.05); SliderRepres->SetSliderLength(0.02); SliderRepres->SetSliderWidth(0.03); SliderRepres->SetEndCapLength(0.01); SliderRepres->SetEndCapWidth(0.03); SliderRepres->SetTubeWidth(0.005); SliderRepres->SetLabelFormat("%3.0lf"); SliderRepres->SetTitleHeight(0.02); SliderRepres->SetLabelHeight(0.02); vtkSliderWidget *SliderWidget = vtkSliderWidget::New(); SliderWidget->SetInteractor(iren); SliderWidget->SetRepresentation(SliderRepres); SliderWidget->KeyPressActivationOff(); SliderWidget->SetAnimationModeToAnimate(); SliderWidget->SetEnabled(true); vtkSliderCallback100 *SliderCb = vtkSliderCallback100::New(); SliderCb->SetImageViewer(viewer); SliderWidget->AddObserver(vtkCommand::InteractionEvent, SliderCb); viewer->SetSlice(static_cast(SliderRepres->GetValue())); typedef PaintbrushTest1Labels::Annotation AnnotationType; PaintbrushTest1Labels MyLabels; MyLabels.LabelMap[40]=AnnotationType("Right-Cerebral-Exterior", 205 , 62, 78 ); MyLabels.LabelMap[41]=AnnotationType("Right-Cerebral-White-Matter", 0 , 225, 0 ); MyLabels.LabelMap[42]=AnnotationType("Right-Cerebral-Cortex", 205 , 62, 78 ); MyLabels.LabelMap[43]=AnnotationType("Right-Lateral-Ventricle", 120 , 18, 134 ); MyLabels.LabelMap[44]=AnnotationType("Right-Inf-Lat-Vent", 196 , 58, 250 ); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 1; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( iren ); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); if (rep) { rep->SetImageActor( viewer->GetImageActor() ); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } set->AddWidget(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); // Our internal representation will be to manage a label map. drawing->SetRepresentationToLabel(); // This will allocate our canvas based on the size of the overlay image // that was set on the WidgetRepresentation. drawing->InitializeData(); // Clear the drawing and start on a clean slate. The drawing would have // automatically created 1 empty sketch for us, so we can start drawing // right away. Let's remove it, since we'd like to initialize the drawing // with our IBSR label map. drawing->RemoveAllItems(); // Read the IBSR label map vtkMetaImageReader * reader2 = vtkMetaImageReader::New(); reader2->SetFileName( argv[2] ); reader2->Update(); // Create a PaintbrushLabelData to represent the label map. vtkKWEPaintbrushLabelData *paintbrushLabelMap = vtkKWEPaintbrushLabelData::New(); paintbrushLabelMap->SetLabelMap( reader2->GetOutput() ); // Set the label map as the initial canvas data of the drawing. drawing->SetPaintbrushData( paintbrushLabelMap ); // Create a sketch for each label in the label map, we'd like to edit. // NOTE: We can skip labels in the label map that we do not care about simply // by not adding a sketch corresponding to that label into the drawing. In // this case, we will take into account all the labels (1-62). // NOTE: As a reminder, bear in mind that 0 is a reserved value and must not // be used as a label. for (std::map< unsigned short, AnnotationType >::const_iterator cit = MyLabels.LabelMap.begin(); cit != MyLabels.LabelMap.end(); ++cit) { // For each label. // Initialize the sketch with the label map. Note that you must add the // sketch to the drawing and set the label you wish the sketch to represent // before you initialize it from the label map. // Also note that when the representation is a "Label-map", all sketches // share the same label map to avoid memory duplication. The corollary to // this is that if you initialize sketches in your drawing using a labelmap, // you must use the same "vtkKWEPaintbrushLabelData" that is used by the // drawing. vtkKWEPaintbrushSketch * sketch = vtkKWEPaintbrushSketch::New(); drawing->AddItem( sketch ); sketch->SetLabel( cit->first ); sketch->Initialize( paintbrushLabelMap ); // Optionally, the identifier can be used to display text annotations as // you navigate through your maze of sketches. 62 segmentations can sure // get you lost pretty quickly. sketch->GetPaintbrushProperty()->SetIdentifier(cit->second.label.c_str()); // Assign a nice color to the sketch. double sketchColor[3] = { cit->second.R/255.0, cit->second.G/255.0, cit->second.B/255.0 }; sketch->GetPaintbrushProperty()->SetColor( sketchColor ); sketch->Delete(); } // Now set the drawing on all representations (axial, coronal and sagittal) // in the WidgetSet. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } // Enable the widget and we are done. set->SetEnabled(1); renWin->SetSize( 500, 500 ); renderer->ResetCamera(); renWin->Render(); // record/replay events vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New(); recorder->SetInteractor(iren); //Set event log recording file std::string eventLogFileName = argv[3]; recorder->SetFileName(eventLogFileName.c_str()); //Set recorder mode depending on the user's choice int retVal = 1; unsigned int mode= atoi( argv[4] ); if( mode ) { std::cout << "Interaction recording....." << std::endl; recorder->Record(); iren->Start(); } else { recorder->On(); std::cout << "Interaction replaying....." << std::endl; recorder->Play(); //recorder must be turned off before regression testing recorder->Off(); retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { recorder->GetInteractor()->Start(); } } if (argc >= 6) { vtkKWEPaintbrushLabelData * finalLabelMap = vtkKWEPaintbrushLabelData::SafeDownCast(drawing->GetPaintbrushData()); vtkMetaImageWriter * outputWriter = vtkMetaImageWriter::New(); outputWriter->SetFileName(argv[5]); outputWriter->SetInput( finalLabelMap->GetLabelMap() ); outputWriter->Write(); outputWriter->Delete(); } // Clean up recorder->Off(); recorder->Delete(); viewer->Delete(); reader2->Delete(); paintbrushLabelMap->Delete(); set->Delete(); renderer->Delete(); renWin->Delete(); iren->Delete(); reader->Delete(); SliderRepres->Delete(); SliderCb->Delete(); SliderWidget->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Widgets/Testing/Cxx/PaintbrushTest1b.cxx0000644000175000017500000002630711502612435023562 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // This test loads a file IBSRData.mha and a label map IBSRLabelMap-UCHAR.mha. // The label map, (courtesy of IBSR) is a label map with 62 segmentations. This // test creates a sketch from each label and initializes the drawing with // these sketches. It also assigns user specified colors to the sketches. // ---------------------------------------------------------------------------- // // User interactions: // // The follwing interactions are supported by the brush in Edit mode. // Left click and drag - Draws a stroke // Ctrl-Left click and drag - Erases the stroke // Backspace or Left key - Undo the sketch (deletes the previously drawn stroke in a sketch) // Right key - Redo on the given sketch // Shift "+" - Start a new sketch. // Shift Right - Traverse to the next sketch. // Shift Left - Traverse to the previous sketch. // Shift Backspace - Delete a sketch. // Right click and drag - Resize the shape isotropically // Ctrl-Right click and drag - Resize the shape anisotropically // Shift "<" - Decrease the opacity of the overlaid drawing // Shift ">" - Increase the opacity of the overlaid drawing // "l" key - Render the current sketch immutable/mutable. // (Supported only when editing labelmaps) // Escape - Enable/Disable interactions // // The follwing interactions are supported by the brush in Select Mode // Left click - Select/Unselect a sketch // Left click and drag - Drag and drop merge of sketches. // Backspace key - Delete selected sketches. // "m" key - Merge selected sketches. // Escape - Enable/Disable interactions #include "vtkInteractorEventRecorder.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkImageViewer2.h" #include "vtkRenderer.h" #include "vtkRenderer.h" #include "vtkCommand.h" #include "vtkCamera.h" #include "vtkRegressionTestImage.h" #include "vtkDebugLeaks.h" #include "vtkRegressionTestImage.h" #include "vtkDebugLeaks.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkSliderRepresentation.h" #include "vtkSliderRepresentation2D.h" #include "vtkSliderWidget.h" #include "vtkMetaImageReader.h" #include "vtkImageActor.h" #include "vtkImageData.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEWidgetGroup.h" #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include #include #include class vtkSliderCallback100b : public vtkCommand { public: static vtkSliderCallback100b *New() { return new vtkSliderCallback100b; } void SetImageViewer(vtkImageViewer2 *viewer) { m_Viewer = viewer; } virtual void Execute(vtkObject *caller, unsigned long , void* ) { vtkSliderWidget *slider = static_cast(caller); vtkSliderRepresentation *sliderRepres = static_cast(slider->GetRepresentation()); int pos = static_cast(sliderRepres->GetValue()); m_Viewer->SetSlice(pos); } protected: vtkImageViewer2 *m_Viewer; }; int PaintbrushTest1b( int argc , char *argv[]) { if( argc < 6 ) { std::cerr << "Usage error: \t " << argv[0] << "\t" << "Input_Image_Data InitialLabelMap EventsLogFile Mode(0:replay 1:record)" << "[OutputLabelMap]" << std::endl; return EXIT_FAILURE; } vtkImageReader2 * reader = vtkMetaImageReader::New(); reader->SetFileName( argv[1] ); if( reader->CanReadFile( argv[1] ) != 3 ) { std::cerr << "Meta image reader couldn't read the input data\t" << std::endl; return EXIT_FAILURE; } reader->Update(); vtkImageData * imageData = reader->GetOutput(); vtkRenderer *renderer = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); vtkImageViewer2 *viewer = vtkImageViewer2::New(); viewer->SetRenderWindow(renWin); viewer->SetRenderer(renderer); viewer->SetInput(imageData); viewer->SetupInteractor(iren); double *range = imageData->GetScalarRange(); viewer->SetColorWindow(range[1] - range[0]); viewer->SetColorLevel(0.5 * (range[1] + range[0])+ 0.0000001); // Tie a slider widget to manipulate the slices of the image viewer // vtkSliderRepresentation2D *SliderRepres = vtkSliderRepresentation2D::New(); int min = viewer->GetSliceMin(); int max = viewer->GetSliceMax(); SliderRepres->SetMinimumValue(min); SliderRepres->SetMaximumValue(max); SliderRepres->SetValue(static_cast((min + max) / 2)); SliderRepres->SetTitleText("Slice"); SliderRepres->GetPoint1Coordinate()->SetCoordinateSystemToNormalizedDisplay(); SliderRepres->GetPoint1Coordinate()->SetValue(0.3, 0.05); SliderRepres->GetPoint2Coordinate()->SetCoordinateSystemToNormalizedDisplay(); SliderRepres->GetPoint2Coordinate()->SetValue(0.7, 0.05); SliderRepres->SetSliderLength(0.02); SliderRepres->SetSliderWidth(0.03); SliderRepres->SetEndCapLength(0.01); SliderRepres->SetEndCapWidth(0.03); SliderRepres->SetTubeWidth(0.005); SliderRepres->SetLabelFormat("%3.0lf"); SliderRepres->SetTitleHeight(0.02); SliderRepres->SetLabelHeight(0.02); vtkSliderWidget *SliderWidget = vtkSliderWidget::New(); SliderWidget->SetInteractor(iren); SliderWidget->SetRepresentation(SliderRepres); SliderWidget->KeyPressActivationOff(); SliderWidget->SetAnimationModeToAnimate(); SliderWidget->SetEnabled(true); vtkSliderCallback100b *SliderCb = vtkSliderCallback100b::New(); SliderCb->SetImageViewer(viewer); SliderWidget->AddObserver(vtkCommand::InteractionEvent, SliderCb); viewer->SetSlice(static_cast(SliderRepres->GetValue())); vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); for (int i = 0; i < 1; i++) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::New(); w->SetInteractor( iren ); vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast(w->GetRepresentation()); if (rep) { rep->SetImageActor( viewer->GetImageActor() ); rep->SetImageData(imageData); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetSpacing( imageData->GetSpacing() ); rep->GetPaintbrushOperation()->GetPaintbrushShape()->SetOrigin( imageData->GetOrigin() ); } set->AddWidget(w); w->Delete(); } vtkKWEPaintbrushRepresentation2D * rep = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(0)->GetRepresentation()); vtkKWEPaintbrushDrawing * drawing = rep->GetPaintbrushDrawing(); // Our internal representation will be to manage a label map. drawing->SetRepresentationToLabel(); // This will allocate our canvas based on the size of the overlay image // that was set on the WidgetRepresentation. drawing->InitializeData(); // Clear the drawing and start on a clean slate. The drawing would have // automatically created 1 empty sketch for us, so we can start drawing // right away. Let's remove it, since we'd like to initialize the drawing // with our IBSR label map. drawing->RemoveAllItems(); // Read the IBSR label map vtkMetaImageReader * reader2 = vtkMetaImageReader::New(); reader2->SetFileName( argv[2] ); reader2->Update(); // Create a PaintbrushLabelData to represent the label map. vtkKWEPaintbrushLabelData *paintbrushLabelMap = vtkKWEPaintbrushLabelData::New(); paintbrushLabelMap->SetLabelMap( reader2->GetOutput() ); // Set the label map as the initial canvas data of the drawing. drawing->SetPaintbrushData( paintbrushLabelMap ); // Note the difference here w.r.t PaintbrushTest1. In this case, we create // sketches defined by all the labels in the label map at one shot, instead // of creating a selective subset of them. drawing->CreateSketches(); // Now set the drawing on all representations (axial, coronal and sagittal) // in the WidgetSet. for (unsigned int i = 0; i < set->GetNumberOfWidgets(); i++) { vtkKWEPaintbrushRepresentation2D * repr = vtkKWEPaintbrushRepresentation2D::SafeDownCast( set->GetNthWidget(i)->GetRepresentation()); repr->SetPaintbrushDrawing( drawing ); } // Enable the widget and we are done. set->SetEnabled(1); renWin->SetSize( 500, 500 ); renderer->ResetCamera(); renWin->Render(); // record/replay events vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New(); recorder->SetInteractor(iren); //Set event log recording file std::string eventLogFileName = argv[3]; recorder->SetFileName(eventLogFileName.c_str()); //Set recorder mode depending on the user's choice int retVal = 1; unsigned int mode= atoi( argv[4] ); if( mode ) { std::cout << "Interaction recording....." << std::endl; recorder->Record(); iren->Start(); } else { std::cout << "Interaction replaying....." << std::endl; recorder->On(); recorder->Play(); //recorder must be turned off before regression testing recorder->Off(); retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { recorder->GetInteractor()->Start(); } } if (argc >= 6) { vtkKWEPaintbrushLabelData * finalLabelMap = vtkKWEPaintbrushLabelData::SafeDownCast(drawing->GetPaintbrushData()); vtkMetaImageWriter * outputWriter = vtkMetaImageWriter::New(); outputWriter->SetFileName(argv[5]); outputWriter->SetInput( finalLabelMap->GetLabelMap() ); outputWriter->Write(); outputWriter->Delete(); } // Clean up recorder->Off(); recorder->Delete(); viewer->Delete(); reader2->Delete(); paintbrushLabelMap->Delete(); set->Delete(); renderer->Delete(); renWin->Delete(); iren->Delete(); reader->Delete(); SliderRepres->Delete(); SliderCb->Delete(); SliderWidget->Delete(); return !retVal; } vtkedge-0.2.0~20110819/Widgets/Testing/CMakeLists.txt0000644000175000017500000000166111363410610021622 0ustar mathieumathieu##============================================================================= ## This file is part of VTKEdge. See vtkedge.org for more information. ## ## Copyright (c) 2010 Kitware, Inc. ## ## VTKEdge may be used under the terms of the BSD License ## Please see the file Copyright.txt in the root directory of ## VTKEdge for further information. ## ## Alternatively, you may see: ## ## http://www.vtkedge.org/vtkedge/project/license.html ## ## ## For custom extensions, consulting services, or training, please ## this or any other Kitware supported open source project, please ## contact Kitware at sales@kitware.com. ## ## ##============================================================================= # ----------------------------------------------------------------------------- # Add the Cxx testing directory # ----------------------------------------------------------------------------- add_subdirectory(Cxx) vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushSelectionRepresentation.cxx0000644000175000017500000003167111363410610026201 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushSelectionRepresentation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushData.h" #include "vtkCoordinate.h" #include "vtkRenderer.h" #include "vtkObjectFactory.h" #include "vtkInteractorObserver.h" #include "vtkPointPlacer.h" #include "vtkProperty.h" #include vtkCxxRevisionMacro(vtkKWEPaintbrushSelectionRepresentation, "$Revision: 1774 $"); vtkCxxSetObjectMacro(vtkKWEPaintbrushSelectionRepresentation, PointPlacer, vtkPointPlacer); vtkCxxSetObjectMacro(vtkKWEPaintbrushSelectionRepresentation, PaintbrushDrawing, vtkKWEPaintbrushDrawing); //---------------------------------------------------------------------- vtkKWEPaintbrushSelectionRepresentation::vtkKWEPaintbrushSelectionRepresentation() { this->PaintbrushDrawing = NULL; this->PointPlacer = NULL; this->SelectedSketch = NULL; this->InteractionState = None; this->DragBeginPoint[0] = this->DragBeginPoint[1] = this->DragBeginPoint[2] = VTK_DOUBLE_MIN; } //---------------------------------------------------------------------- vtkKWEPaintbrushSelectionRepresentation::~vtkKWEPaintbrushSelectionRepresentation() { this->SetPaintbrushDrawing(NULL); this->SetPointPlacer(NULL); } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionRepresentation ::ComputeInteractionState( int X, int Y, int vtkNotUsed(modifier) ) { const int nSketches = this->PaintbrushDrawing->GetNumberOfItems(); if (this->InteractionState == PaintbrushRequestSketchSelect) { // First check if the point placer validates us. double displayPos[2] = {X, Y}, worldPos[3], worldOrient[9] = {1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0}; if ( this->PointPlacer->ComputeWorldPosition( this->Renderer, displayPos, worldPos, worldOrient ) ) { // Traverse the list of selected sketches and see if we are trying // to unselect any of them. for (SelectedSketchesType::reverse_iterator rit = this->SelectedSketches.rbegin(); rit != this->SelectedSketches.rend(); ++rit) { if (this->WorldPositionIsInside( *rit, worldPos )) { // We clicked on a selected sketch. We should toggle its selection; // Unselect it. this->InteractionState = this->PrevInteractionState = PaintbrushSketchUnselect; this->SelectedSketch = *rit; // Its really an unselected sketch. this->RemoveSketchFromSelection(*rit); return this->InteractionState; } } // Now traverse the list of un-selected sketches in the drawing and see // if we are trying to select any of them. for (int i = 0; i < nSketches; i++) { vtkKWEPaintbrushSketch *s = this->PaintbrushDrawing->GetItem(i); // Skip any sketches that are already selected for efficiency. We // know that we aren't over an already selected sketch; if we were, // we'd have unselected it in above. if (vtkstd::find(this->SelectedSketches.begin(), this->SelectedSketches.end(), s) != this->SelectedSketches.end()) { continue; } if (this->WorldPositionIsInside( s, worldPos )) { // Select this sketch. this->InteractionState = this->PrevInteractionState = PaintbrushSketchSelect; this->SelectedSketch = s; this->AddSketchToSelection(s); return this->InteractionState; } } } } // Drag and drop merge support... else if (this->InteractionState == PaintbrushRequestSketchMerge && nSketches > 1) { double displayPos[2]={X, Y}, worldOrient[9] = {1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0}; if (this->PrevInteractionState == PaintbrushSketchSelect && this->SelectedSketch ) { this->DragEndPoint[0] = this->DragEndPoint[1] = this->DragEndPoint[2] = VTK_DOUBLE_MIN; if ( !this->PointPlacer->ComputeWorldPosition( this->Renderer, displayPos, this->DragBeginPoint, worldOrient ) ) { this->DragBeginPoint[0] = this->DragBeginPoint[1] = this->DragBeginPoint[2] = VTK_DOUBLE_MIN; } this->PrevInteractionState = PaintbrushRequestSketchMerge; } if ( !this->PointPlacer->ComputeWorldPosition( this->Renderer, displayPos, this->DragEndPoint, worldOrient ) ) { this->DragEndPoint[0] = this->DragEndPoint[1] = this->DragEndPoint[2] = VTK_DOUBLE_MIN; } else { this->DragAndDropDestination = NULL; for (int i = nSketches-1; i >= 0 ; --i) { vtkKWEPaintbrushSketch *s = this->PaintbrushDrawing->GetItem(i); if (this->WorldPositionIsInside( s, this->DragEndPoint)) { this->DragAndDropDestination = s; this->InteractionState = PaintbrushSketchMerge; break; } } } return this->InteractionState; } // Clearly, if we got here, we haven't managed to toggle the selected // state of any sketch. this->InteractionState = None; this->SelectedSketch = NULL; return this->InteractionState; } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionRepresentation ::AddSketchToSelection( vtkKWEPaintbrushSketch * s ) { if (vtkstd::find(this->SelectedSketches.begin(), this->SelectedSketches.end(), s) == this->SelectedSketches.end()) { this->SelectedSketches.push_back(s); s->GetPaintbrushProperty()->HighlightOn(); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionRepresentation::SelectAllSketches() { this->SelectedSketches.clear(); const int nSketches = this->PaintbrushDrawing->GetNumberOfItems(); for (int n = 0; n < nSketches; n++) { vtkKWEPaintbrushSketch * s = this->PaintbrushDrawing->GetItem(n); this->SelectedSketches.push_back(s); s->GetPaintbrushProperty()->HighlightOn(); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionRepresentation::UnSelectAllSketches() { // Iterate over all the sketches and un-highlight them. for (SelectedSketchesType::iterator it = this->SelectedSketches.begin(); it != this->SelectedSketches.end(); ++it) { if (this->PaintbrushDrawing->IsItemPresent(*it)) { (*it)->GetPaintbrushProperty()->HighlightOff(); } } this->SelectedSketches.clear(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionRepresentation ::RemoveSketchFromSelection( vtkKWEPaintbrushSketch * s ) { SelectedSketchesType::iterator it = vtkstd::find( this->SelectedSketches.begin(), this->SelectedSketches.end(), s); if (it != this->SelectedSketches.end()) { s->GetPaintbrushProperty()->HighlightOff(); this->SelectedSketches.erase(it); } } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionRepresentation ::WorldPositionIsInside( vtkKWEPaintbrushSketch *s, double worldPos[3] ) { return s->GetPaintbrushData()->IsInside(worldPos); } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionRepresentation ::DisplayPositionIsInside( vtkKWEPaintbrushSketch *s, double dispPos[2] ) { // First check if the point placer validates us. double worldPos[3], worldOrient[9] = {1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0}; if ( this->PointPlacer->ComputeWorldPosition( this->Renderer, dispPos, worldPos, worldOrient ) ) { return this->WorldPositionIsInside( s, worldPos ); } return 0; } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionRepresentation::DeleteSelectedSketches() { int nSketchesRemoved = 0; for (SelectedSketchesType::iterator it = this->SelectedSketches.begin(); it != this->SelectedSketches.end(); ++it) { nSketchesRemoved += this->PaintbrushDrawing->RemoveItem( *it ); } this->SelectedSketch = NULL; this->SelectedSketches.clear(); // Don't let the drawing lie without any sketches at all. Keep one there, // so that we can draw something. return nSketchesRemoved; } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionRepresentation ::MergeSelectedSketches( vtkKWEPaintbrushSketch *mergedSketch, int removeSketches ) { if (this->SelectedSketches.size() < 2) { return 0; // We need at least two to merge. } // Assert that mergedSketch, if supplied, is a sketch from the drawing. if (mergedSketch && this->PaintbrushDrawing->IsItemPresent(mergedSketch) == 0) { vtkErrorMacro( "The sketch youre trying to merge into must be a sketch" << " from the drawing" ); return 0; } SelectedSketchesType::iterator it = this->SelectedSketches.begin(); vtkKWEPaintbrushSketch *sketchToMergeInto = mergedSketch ? mergedSketch : (*it); // Now merge all the selected sketches into sketchToMergeInto for (; it != this->SelectedSketches.end(); ++it) { // We don't want to merge the sketchToMergeInto with sketchToMergeInto if (*it != sketchToMergeInto) { // Sanity check to make sure that the sketch is present in the drawing if (this->PaintbrushDrawing->IsItemPresent(*it)) { sketchToMergeInto->GetPaintbrushData()->Add( (*it)->GetPaintbrushData() ); if (removeSketches) { (*it)->GetPaintbrushProperty()->HighlightOff(); this->PaintbrushDrawing->RemoveItem( *it ); } } } } if (removeSketches) { // If the sketch being merged into was a part of the selection, leave it as // selected and remove the rest. if (vtkstd::find(this->SelectedSketches.begin(), this->SelectedSketches.end(), sketchToMergeInto) != this->SelectedSketches.end()) { this->SelectedSketch = sketchToMergeInto; this->SelectedSketches.clear(); this->SelectedSketches.push_back( sketchToMergeInto ); } else { this->SelectedSketch = NULL; this->SelectedSketches.clear(); } } // Don't let the drawing lie without any sketches at all. Keep one there, // so that we can draw something. return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionRepresentation::DeepCopy(vtkWidgetRepresentation *rep) { vtkKWEPaintbrushSelectionRepresentation *r = vtkKWEPaintbrushSelectionRepresentation::SafeDownCast(rep); if (this == r || !r) { return; } //if (this->PointPlacer && r->PointPlacer) // { // this->PointPlacer->DeepCopy(r->PointPlacer); // } this->InteractionState = r->InteractionState; this->SelectedSketch = r->SelectedSketch; this->SelectedSketches = r->SelectedSketches; this->SetPaintbrushDrawing( r->GetPaintbrushDrawing() ); } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionRepresentation::DragAndDropMerge() { // If both the drag and the drop sketches aren't null.. if (this->SelectedSketch && this->DragAndDropDestination && this->PaintbrushDrawing->IsItemPresent(this->SelectedSketch) && this->PaintbrushDrawing->IsItemPresent(this->DragAndDropDestination)) { this->DragAndDropDestination->GetPaintbrushData()->Add( this->SelectedSketch->GetPaintbrushData() ); this->RemoveSketchFromSelection(this->SelectedSketch); this->PaintbrushDrawing->RemoveItem(this->SelectedSketch); this->SelectedSketch = NULL; return 1; } return 0; } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionRepresentation ::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEBoundingBoxWidget2D.h0000644000175000017500000000772011363410610022464 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEBoundingBoxWidget2D - Manages a 3D bounding box on a 2D image actor // .SECTION Description // The widget can be placed on one of the orthogonal (axial/sagittal/coronal) // image actors and be used to specify bounds (or extents). The widget // includes a slice scale (with 2 handles) to manipulate the extents along Z // and 4 handles to manipulate the bounding box. // // If bounds are changed, the widget invokes a BoundsChangedEvent along with // a pointer to 6 tuple double containing the new bounds. // // If extents are changed, the widget invokes a ExtentsChangedEvent along with // a pointer to 6 tuple integer containing the new extent. // // Needless to say, a BoundsChangedEvent will be invoked every time an // ExtentsChangedEvent is invoked. The converse is not always true. #ifndef __vtkKWEBoundingBoxWidget2D_h #define __vtkKWEBoundingBoxWidget2D_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkAbstractWidget.h" class vtkKWEBoundingBoxRepresentation2D; class vtkHandleWidget; class VTKEdge_WIDGETS_EXPORT vtkKWEBoundingBoxWidget2D : public vtkAbstractWidget { public: // Description: // Instantiate this class. static vtkKWEBoundingBoxWidget2D *New(); // Description: // Standard methods for a VTK class. vtkTypeRevisionMacro(vtkKWEBoundingBoxWidget2D,vtkAbstractWidget); void PrintSelf(ostream& os, vtkIndent indent); // Description: // The method for activiating and deactiviating this widget. This method // must be overridden because it is a composite widget and does more than // its superclass' vtkAbstractWidget::SetEnabled() method. virtual void SetEnabled(int); // Description: // See superclass doc virtual void SetProcessEvents( int ); // Description:i // This serves to fade the representation into the background. If faded, // ProcessEvents is automatically turned off, ie the widget will not // respond to events. virtual void SetFade( int ); virtual int GetFade(); vtkBooleanMacro(Fade, int); // Description: // Events emitted by the widget //BTX enum { BeginResizeEvent = 1000, ResizingEvent, EndResizeEvent, BoundsChangedEvent, ExtentsChangedEvent }; //ETX // Description: // Set the representation virtual void SetRepresentation( vtkKWEBoundingBoxRepresentation2D * ); // Description: // See superclass for documentation virtual void CreateDefaultRepresentation(); // Description: // If set, it must be set prior to enabling the widget. Default is ON. virtual void SetShowSliceScaleBar(int); vtkGetMacro( ShowSliceScaleBar, int ); vtkBooleanMacro( ShowSliceScaleBar, int ); protected: vtkKWEBoundingBoxWidget2D(); ~vtkKWEBoundingBoxWidget2D(); // Description: static void OnMouseMoveCallback ( vtkAbstractWidget* ); static void OnLeftButtonDownCallback ( vtkAbstractWidget* ); static void OnLeftButtonUpCallback ( vtkAbstractWidget* ); void SetCursor( int ); int ShowSliceScaleBar; void SetEnabledStateOfSliceScaleBar(); double LastComputedBounds[6]; int LastComputedExtent[6]; private: vtkKWEBoundingBoxWidget2D(const vtkKWEBoundingBoxWidget2D&); //Not implemented void operator=(const vtkKWEBoundingBoxWidget2D&); //Not implemented vtkHandleWidget ** HandleWidgets; }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushWidgetCallbackMapper.cxx0000644000175000017500000002046311521051333025332 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushWidgetCallbackMapper.h" #include "vtkWidgetEventTranslator.h" #include "vtkAbstractWidget.h" #include "vtkCommand.h" #include "vtkObjectFactory.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkEvent.h" #include "vtkWidgetEvent.h" vtkStandardNewMacro(vtkKWEPaintbrushWidgetCallbackMapper); //---------------------------------------------------------------------------- vtkKWEPaintbrushWidgetCallbackMapper::vtkKWEPaintbrushWidgetCallbackMapper() { } //---------------------------------------------------------------------------- vtkKWEPaintbrushWidgetCallbackMapper::~vtkKWEPaintbrushWidgetCallbackMapper() { } //---------------------------------------------------------------------------- void vtkKWEPaintbrushWidgetCallbackMapper::Bindings() { // These are the event callbacks supported by this widget this->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkEvent::NoModifier, 0, 0, NULL, vtkKWEPaintbrushWidget::BeginDrawStrokeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::BeginDrawCallback); this->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkEvent::ControlModifier, 0, 0, NULL, vtkKWEPaintbrushWidget::BeginEraseStrokeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::BeginEraseCallback); this->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkEvent::ShiftModifier, 0, 0, NULL, vtkKWEPaintbrushWidget::BeginDrawStrokeForThisSketchEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::BeginDrawThisSketchCallback); this->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkEvent::ControlModifier | vtkEvent::ShiftModifier, 0, 0, NULL, vtkKWEPaintbrushWidget::BeginEraseStrokeForThisSketchEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::BeginEraseThisSketchCallback); this->SetCallbackMethod(vtkCommand::MouseMoveEvent, vtkWidgetEvent::Move, this->PaintbrushWidget, vtkKWEPaintbrushWidget::MoveCallback); this->SetCallbackMethod(vtkCommand::LeftButtonReleaseEvent, vtkKWEPaintbrushWidget::EndStrokeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::EndStrokeCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::NoModifier, 8, 1,"BackSpace", vtkKWEPaintbrushWidget::UndoStrokeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::UndoCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, // Ctrl+z vtkEvent::ControlModifier, 26, 0,"z", vtkKWEPaintbrushWidget::UndoStrokeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::UndoCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::NoModifier, 40, 1, "Right", vtkKWEPaintbrushWidget::RedoStrokeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::RedoCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, // Ctrl+y vtkEvent::ControlModifier, 25, 0,"y", vtkKWEPaintbrushWidget::RedoStrokeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::RedoCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::ControlModifier, 8, 1,"BackSpace", vtkKWEPaintbrushWidget::RedoStrokeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::RedoCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::NoModifier, 47, 1, "Delete", vtkWidgetEvent::Delete, this->PaintbrushWidget, vtkKWEPaintbrushWidget::DeleteCallback); this->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkEvent::ShiftModifier, 0, 0, NULL, vtkKWEPaintbrushWidget::BeginIsotropicResizeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::BeginIsotropicResizeShapeCallback); this->SetCallbackMethod(vtkCommand::RightButtonPressEvent, vtkEvent::NoModifier, 0, 0, NULL, vtkKWEPaintbrushWidget::BeginIsotropicResizeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::BeginIsotropicResizeShapeCallback); this->SetCallbackMethod(vtkCommand::RightButtonPressEvent, vtkEvent::ControlModifier, 0, 0, NULL, vtkKWEPaintbrushWidget::BeginResizeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::BeginResizeShapeCallback); this->SetCallbackMethod(vtkCommand::RightButtonReleaseEvent, vtkKWEPaintbrushWidget::EndResizeEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::EndResizeShapeCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::NoModifier, 27, 1,"Escape", vtkKWEPaintbrushWidget::ToggleSelectStateEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::ToggleSelectStateCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, // Shift+ vtkEvent::ShiftModifier, 43, 1,"plus", vtkKWEPaintbrushWidget::BeginNewSketchEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::BeginNewSketchCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::ShiftModifier, 40, 1, "Right", vtkKWEPaintbrushWidget::IncrementSketchEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::IncrementSketchCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::ShiftModifier, 38, 1, "Left", vtkKWEPaintbrushWidget::DecrementSketchEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::DecrementSketchCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::NoModifier, 109, 0, "m", vtkKWEPaintbrushWidget::MergeSelectionEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::MergeSelectionCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, // Ctrl+a vtkEvent::ControlModifier, 1, 0,"a", vtkKWEPaintbrushWidget::ToggleSelectAllSketchesEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::ToggleSelectAllSketchesCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, // "<" vtkEvent::ShiftModifier, 60, 0,"less", vtkKWEPaintbrushWidget::DecreaseOpacityEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::DecreaseOpacityCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, // ">" vtkEvent::ShiftModifier, 62, 0,"greater", vtkKWEPaintbrushWidget::IncreaseOpacityEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::IncreaseOpacityCallback); this->SetCallbackMethod(vtkCommand::EnterEvent, vtkKWEPaintbrushWidget::EnterEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::EnterWidgetCallback); this->SetCallbackMethod(vtkCommand::LeaveEvent, vtkKWEPaintbrushWidget::LeaveEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::LeaveWidgetCallback); this->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::NoModifier, 108, 0, "l", vtkKWEPaintbrushWidget::ToggleSketchMutabilityEvent, this->PaintbrushWidget, vtkKWEPaintbrushWidget::ToggleSketchMutabilityCallback); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushWidgetCallbackMapper::SetPaintbrushWidget( vtkKWEAbstractPaintbrushWidget * w ) { this->PaintbrushWidget = w; this->SetEventTranslator(w->GetEventTranslator()); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushWidgetCallbackMapper::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEITKPaintbrushExtractConnectedComponents.h0000644000175000017500000000743711363410610026634 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEITKPaintbrushExtractConnectedComponents - Extract connected components in a drawing. // .SECTION Description // Takes a drawing as input. Generates a drawing as output. The input drawing // will have one or more sketches. The user set the sketch for which connected // components must be extracted via 'SetSketchIndex' (default is the first // sketch). The algorithm will produce as output a drawing with 'n' sketches // where 'n' is the number of connected components. Each connected component // is a seperate sketch. // .SECTION See Also #ifndef __vtkKWEITKPaintbrushExtractConnectedComponents_h #define __vtkKWEITKPaintbrushExtractConnectedComponents_h #include "vtkAlgorithm.h" #include "VTKEdgeConfigure.h" class vtkKWEPaintbrushDrawing; class vtkImageData; class VTKEdge_WIDGETS_EXPORT vtkKWEITKPaintbrushExtractConnectedComponents : public vtkAlgorithm { public: // Description: // Standard VTK methods. static vtkKWEITKPaintbrushExtractConnectedComponents *New(); vtkTypeRevisionMacro(vtkKWEITKPaintbrushExtractConnectedComponents, vtkAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set the sketch from the input drawing of which we wish to extract // connected components. Defaults to 0. vtkSetMacro( SketchIndex, int ); vtkGetMacro( SketchIndex, int ); // Description: // Set a paintbrush drawing as input virtual void SetInput( vtkKWEPaintbrushDrawing * ); // Description: // see vtkAlgorithm for details virtual int ProcessRequest(vtkInformation*, vtkInformationVector**, vtkInformationVector*); // Description: // Get the output data object of this algorithm. vtkKWEPaintbrushDrawing* GetOutput(); protected: vtkKWEITKPaintbrushExtractConnectedComponents(); ~vtkKWEITKPaintbrushExtractConnectedComponents(); // Description: // see vtkAlgorithm for docs. virtual int FillInputPortInformation(int, vtkInformation*); virtual int FillOutputPortInformation(int, vtkInformation*); virtual int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); virtual void RequestInformation (vtkInformation*, vtkInformationVector**, vtkInformationVector*); // Description: // Creates the same output type as the input type. virtual int RequestDataObject(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); // Description: // Compute the tightest bounding box that covers each of the connected // components. void ComputeSegmentExtents( int nSegments, int *e, vtkImageData *image ); int SketchIndex; private: vtkKWEITKPaintbrushExtractConnectedComponents( const vtkKWEITKPaintbrushExtractConnectedComponents&); //Not implemented void operator=(const vtkKWEITKPaintbrushExtractConnectedComponents&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEWidgetGroup.h0000644000175000017500000001715111502037234021155 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEWidgetGroup - Synchronize a collection on vtkWidgets drawn on different renderwindows using the Callback - Dispatch Action mechanism. // // .SECTION Description // The class synchronizes a set of vtkAbstractWidget(s). Widgets typically // invoke "Actions" that drive the geometry/behaviour of their representations // in response to interactor events. Interactor interactions on a render window // are mapped into "Callbacks" by the widget, from which "Actions" are // dispatched to the entire set. This architecture allows us to tie widgets // existing in different render windows together. For instance a HandleWidget // might exist on the sagittal view. Moving it around should update the // representations of the corresponding handle widget that lies on the axial // and coronal and volume views as well. // // .SECTION User API // A user would use this class as follows. // \code // vtkKWEWidgetGroup *set = vtkKWEWidgetGroup::New(); // vtkKWEPaintbrushWidget *w1 = vtkKWEPaintbrushWidget::New(); // set->AddWidget(w1); // w1->SetInteractor(axialRenderWindow->GetInteractor()); // vtkKWEPaintbrushWidget *w2 = vtkKWEPaintbrushWidget::New(); // set->AddWidget(w2); // w2->SetInteractor(coronalRenderWindow->GetInteractor()); // vtkKWEPaintbrushWidget *w3 = vtkKWEPaintbrushWidget::New(); // set->AddWidget(w3); // w3->SetInteractor(sagittalRenderWindow->GetInteractor()); // set->SetEnabled(1); // \endcode // // .SECTION Motivation // The motivation for this class is really to provide a usable API to tie // widgets drawn on multiple render windows. To enable this, subclasses // of vtkAbstractWidget, must be written as follows: // They will generally have callback methods mapped to some user // interaction such as: // \code // this->CallbackMapper->SetCallbackMethod(vtkCommand::RightButtonPressEvent, // vtkEvent::NoModifier, 0, 0, NULL, // vtkKWEPaintbrushWidget::ResizeEvent, // this, vtkKWEPaintbrushWidget::ResizeCallback); // \endcode // The callback invoked when the right button is pressed looks like: // \code // void vtkKWEPaintbrushWidget::ResizeCallback(vtkAbstractWidget *w) // { // vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); // self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::ResizeAction); // } // \endcode // The actual code for resizing is written in the ResizeAction method. // \code // void vtkKWEPaintbrushWidget::ResizeAction( vtkKWEPaintbrushWidget *dispatcher) // { // // Here dispatcher is the widget that was interacted with, the one that // // dispatched an action to all the other widgets in its group. You may, if // // necessary find it helpful to get parameters from it. // if (this == dispatcher) // { // this->WidgetRep->Resize( eventPos, lastEventPos ); // // // The active widget can use the return value to signify an abort. // // The other widgets in the set won't have the action dispatched to // // them at all. // if (newSize == oldSize) return 0; // } // else // { // double *newsize = dispatcher->GetRepresentation()->GetSize(); // this->WidgetRep->SetSize(newsize); // } // } // \endcode // // .SECTION Caveats // Actions are always dispatched first to the activeWidget, the one calling // the set, and then to the other widgets in the set. // #ifndef __vtkKWEWidgetGroup_h #define __vtkKWEWidgetGroup_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkObject.h" #include class vtkAbstractWidget; class VTKEdge_WIDGETS_EXPORT vtkKWEWidgetGroup : public vtkObject { public: // Description: // Instantiate this class. static vtkKWEWidgetGroup *New(); // Description: // Standard methods for a VTK class. vtkTypeRevisionMacro(vtkKWEWidgetGroup,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Method for activiating and deactiviating all widgets in the group. virtual void SetEnabled(int); vtkBooleanMacro(Enabled, int); // Description: // Add a widget to the set. void AddWidget(vtkAbstractWidget *); // Description: // Remove a widget from the set void RemoveWidget(vtkAbstractWidget *); // Description: // Get number of widgets in the set. unsigned int GetNumberOfWidgets(); // Description: // Get the Nth widget in the set. vtkAbstractWidget *GetNthWidget( unsigned int ); //BTX // TODO: Move this to the protected section. The class vtkAbstractWidget // should be a friend of this class. typedef vtkstd::vector< vtkAbstractWidget * > WidgetContainerType; typedef WidgetContainerType::iterator WidgetIteratorType; typedef WidgetContainerType::const_iterator WidgetConstIteratorType; WidgetContainerType Widget; // Description: // Pointer to a member function that takes a vtkAbstractWidget (the active // child) and another vtkAbstractWidget (the widget to dispatch an action) // to. All "Action" funtions in a widget must conform to this signature. // A return value of 0 from the active widget indicates that there is no // need to for the widget set to dispatch the action to other widgets in // the set. template< class TWidget > struct ActionFunction { typedef int (TWidget::*TActionFunctionPointer)(TWidget *dispatcher); }; // Description: // Dispatch an "Action" to every widget in this set. This is meant be be // invoked from a "Callback" in a widget. template < class TWidget > void DispatchAction(TWidget *caller, typename ActionFunction< TWidget >::TActionFunctionPointer action) { // Dispatch action to the caller first. for (WidgetIteratorType it = this->Widget.begin(); it != this->Widget.end() ; ++it) { TWidget *w = static_cast(*it); if (caller == w) { if (((*w).*(action))(caller) == 0) return; break; } } // Dispatch action to all other widgets for (WidgetIteratorType it = this->Widget.begin(); it != this->Widget.end() ; ++it) { TWidget *w = static_cast(*it); if (caller != w) ((*w).*(action))(caller); } } //ETX // Description: // Enable garbage collection due to ref counting cycles with vtkAbstractWidget virtual void Register(vtkObjectBase* o); virtual void UnRegister(vtkObjectBase* o); // Description: // Is this widget present in the group int HasWidget( vtkAbstractWidget * ); // Description: // Render all the widgets in the group. void Render(); protected: vtkKWEWidgetGroup(); ~vtkKWEWidgetGroup(); // We need to break reference count loops. The widgets held by us refcount us // too virtual void ReportReferences(vtkGarbageCollector* collector); private: vtkKWEWidgetGroup(const vtkKWEWidgetGroup&); //Not implemented void operator=(const vtkKWEWidgetGroup&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushShapeBox.cxx0000644000175000017500000003753611504122432023047 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushShapeBox.h" #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkImageStencilData.h" #include "vtkImageData.h" #include "vtkCubeSource.h" #include "vtkPlane.h" #include "vtkMath.h" #define sign(x) ((x<0) ? (-1) : (1)) vtkCxxRevisionMacro(vtkKWEPaintbrushShapeBox, "$Revision: 3282 $"); vtkStandardNewMacro(vtkKWEPaintbrushShapeBox); //---------------------------------------------------------------------- vtkKWEPaintbrushShapeBox::vtkKWEPaintbrushShapeBox() { this->Width[0] = 2.0; this->Width[1] = 2.0; this->Width[2] = 2.0; } //---------------------------------------------------------------------- vtkKWEPaintbrushShapeBox::~vtkKWEPaintbrushShapeBox() { } //---------------------------------------------------------------------- vtkSmartPointer< vtkPolyData > vtkKWEPaintbrushShapeBox::GetShapePolyData( double *center, vtkPlane *plane) { if (plane == NULL) { // No Orientation specified. Return the whole Polydata. This is what will // be rendered on the volume widget vtkCubeSource * templateOutline = vtkCubeSource::New(); templateOutline->SetCenter( center ); templateOutline->SetXLength(this->Width[0]); templateOutline->SetYLength(this->Width[1]); templateOutline->SetZLength(this->Width[2]); templateOutline->Update(); vtkSmartPointer< vtkPolyData > pd = templateOutline->GetOutput(); templateOutline->Delete(); return pd; } else { double normal[3], origin[3]; plane->GetNormal(normal); plane->GetOrigin(origin); // Fast handlers for axis aligned planes. const double tolerance = 0.01; if ((fabs(normal[0])-1.0) < tolerance && fabs(normal[1]) < tolerance && fabs(normal[2]) < tolerance) { if (fabs(origin[0] - center[0]) > this->Width[0]/2.0) { return NULL; } vtkSmartPointer< vtkPolyData > templateOutline = vtkSmartPointer< vtkPolyData >::New(); templateOutline->Allocate(1, 1); vtkPoints * points = vtkPoints::New(); points->InsertNextPoint( center[0], center[1] - this->Width[1]/2.0, center[2] - this->Width[2]/2.0); points->InsertNextPoint( center[0], center[1] - this->Width[1]/2.0, center[2] + this->Width[2]/2.0); points->InsertNextPoint( center[0], center[1] + this->Width[1]/2.0, center[2] + this->Width[2]/2.0); points->InsertNextPoint( center[0], center[1] + this->Width[1]/2.0, center[2] - this->Width[2]/2.0); templateOutline->SetPoints(points); vtkIdType ptIds[4]; ptIds[0] = 0; ptIds[1] = 1; ptIds[2] = 2; ptIds[3] = 3; templateOutline->InsertNextCell(VTK_QUAD, 4, ptIds); points->Delete(); return templateOutline; } else if (fabs(normal[0]) < tolerance && (fabs(normal[1])-1.0) < tolerance && fabs(normal[2]) < tolerance) { if (fabs(origin[1] - center[1]) > this->Width[1]/2.0) { return NULL; } vtkSmartPointer< vtkPolyData > templateOutline = vtkSmartPointer< vtkPolyData >::New(); templateOutline->Allocate(1, 1); vtkPoints * points = vtkPoints::New(); points->InsertNextPoint( center[0] - this->Width[0]/2.0, center[1], center[2] - this->Width[2]/2.0); points->InsertNextPoint( center[0] - this->Width[0]/2.0, center[1], center[2] + this->Width[2]/2.0); points->InsertNextPoint( center[0] + this->Width[0]/2.0, center[1], center[2] + this->Width[2]/2.0); points->InsertNextPoint( center[0] + this->Width[0]/2.0, center[1], center[2] - this->Width[2]/2.0); templateOutline->SetPoints(points); vtkIdType ptIds[4]; ptIds[0] = 0; ptIds[1] = 1; ptIds[2] = 2; ptIds[3] = 3; templateOutline->InsertNextCell(VTK_QUAD, 4, ptIds); points->Delete(); return templateOutline; } else if (fabs(normal[0]) < tolerance && fabs(normal[1]) < tolerance && (fabs(normal[2])-1.0) < tolerance) { if (fabs(origin[2] - center[2]) > this->Width[2]/2.0) { return NULL; } vtkSmartPointer< vtkPolyData > templateOutline = vtkSmartPointer< vtkPolyData >::New(); templateOutline->Allocate(1, 1); vtkPoints * points = vtkPoints::New(); points->InsertNextPoint( center[0] - this->Width[0]/2.0, center[1] - this->Width[1]/2.0, center[2]); points->InsertNextPoint( center[0] - this->Width[0]/2.0, center[1] + this->Width[1]/2.0, center[2]); points->InsertNextPoint( center[0] + this->Width[0]/2.0, center[1] + this->Width[1]/2.0, center[2]); points->InsertNextPoint( center[0] + this->Width[0]/2.0, center[1] - this->Width[1]/2.0, center[2]); templateOutline->SetPoints(points); vtkIdType ptIds[4]; ptIds[0] = 0; ptIds[1] = 1; ptIds[2] = 2; ptIds[3] = 3; templateOutline->InsertNextCell(VTK_QUAD, 4, ptIds); points->Delete(); return templateOutline; } else { // TODO intersect cube with arbitrarily oriented plane and return polydata vtkErrorMacro( << "Not yet supported" ); return NULL; } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::GetStencil( vtkImageStencilData *stencilData, double p[3]) { int extent[6]; this->GetExtent( extent, p ); stencilData->SetExtent(extent); stencilData->SetSpacing(this->Spacing); stencilData->SetOrigin(this->Origin); stencilData->AllocateExtents(); for (int idz=extent[4]; idz<=extent[5]; idz++) { for (int idy = extent[2]; idy <= extent[3]; idy++) { stencilData->InsertNextExtent( extent[0], extent[1], idy, idz ); } } } //---------------------------------------------------------------------- // This really returns the distance map from an ellipsoid of similar size // as the cuboid.. Who the hell will use a box shaped rectangular image // data anyway.. Its got singularities.. noone doing image processing // for sure.. !! template < class T > int vtkKWEPaintbrushShapeBoxFillBuffer( vtkKWEPaintbrushShapeBox * self, vtkImageData *imageData, T, int extent[6], double p[3] ) { // Polarity of the shape bool state = false; if (self->GetPolarity() == vtkKWEPaintbrushEnums::Draw) { state = true; } const double r1square = 0.25 * self->GetWidth()[0]*self->GetWidth()[0]; const double r2square = 0.25 * self->GetWidth()[1]*self->GetWidth()[1]; const double r3square = 0.25 * self->GetWidth()[2]*self->GetWidth()[2]; double value; for (int k= extent[4]; k<=extent[5]; k++) { for (int j= extent[2]; j<=extent[3]; j++) { for (int i= extent[0]; i<=extent[1]; i++) { T * np = static_cast< T* >(imageData->GetScalarPointer(i,j,k)); double px = (i * self->GetSpacing()[0] + self->GetOrigin()[0]) - p[0]; double py = (j * self->GetSpacing()[1] + self->GetOrigin()[1]) - p[1]; double pz = (k * self->GetSpacing()[2] + self->GetOrigin()[2]) - p[2]; if ( (px*px/r1square + py*py/r2square + pz*pz/r3square) > 2.0 ) { // Outside the ellipse *np = static_cast< T >(0.0); continue; } // Normalized distance of the point from the surface of the ellipse. // This is 1.0 at the surface, 0.0 at the center, 2.0 at twice the // distance from the surface... double distance = sqrt(px*px/r1square + py*py/r2square + pz*pz/r3square); if (state) { value = 255.0 - 127.5 * distance; } else { value = 127.5 * distance; } // clamp value if( value < 1.0 ) { value = 1.0; } else if( value > 254.0 ) { value = 254.0; } *np = static_cast< T >(value); } } } return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::GetGrayscaleData( vtkImageData *imageData, double p[3]) { // Compute the extents of the an image centered about p. int extent[6]; this->GetExtent( extent, p ); imageData->SetSpacing(this->Spacing); imageData->SetOrigin(this->Origin); imageData->SetExtent(extent); imageData->SetScalarType(this->GetScalarType()); imageData->AllocateScalars(); switch (imageData->GetScalarType()) { vtkTemplateMacro( vtkKWEPaintbrushShapeBoxFillBuffer( this, imageData, static_cast< VTK_TT >(0), extent, p )); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::SetWidth( double newWidthX, double newWidthY, double newWidthZ ) { vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting Width to (" << newWidthX << "," << newWidthY << "," << newWidthZ << ")"); if ((this->Width[0] != newWidthX)||(this->Width[1] != newWidthY)||(this->Width[2] != newWidthZ)) { this->Width[0] = (this->MaxWidth[0] < 0. || this->MaxWidth[0] > newWidthX)? newWidthX :this->MaxWidth[0]; this->Width[1] = (this->MaxWidth[1] < 0. || this->MaxWidth[1] > newWidthY)? newWidthY :this->MaxWidth[1]; this->Width[2] = (this->MaxWidth[2] < 0. || this->MaxWidth[2] > newWidthZ)? newWidthZ :this->MaxWidth[2]; this->Modified(); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::SetWidth( double newWidth[3] ) { this->SetWidth( newWidth[0], newWidth[1], newWidth[2] ); } //---------------------------------------------------------------------- int vtkKWEPaintbrushShapeBox::Resize(double d[3], int ResizeType) { // If the user specified a constraint on the resize type, use that, // otherwise default to whatever the widget told us in the functions' // argument. const int resizeType = (this->ResizeConstraint == PaintbrushResizeUnConstrained) ? ResizeType : this->ResizeConstraint; // Define a minimum size that the shape will take. The shape will not // get smaller than this. const double minSize = 0.5; double newWidth[3] = { this->Width[0], this->Width[1], this->Width[2] }; if (resizeType == vtkKWEPaintbrushShape::PaintbrushResizeAnisotropic) { // non-isotropic resize. This will resize each axis according to the // factor specified along each axis. for (unsigned int i=0; i<3; i++) { if (d[i] > 0.0 || this->Width[i] > 0.5) { newWidth[i] *= (1+d[i]/10.0); } } } else { // Not an AnIsotropic resize.. This will resize each axis by the same // factor. This factor will be the norm of the factor vector specified // as the functions' argument // Calculate the sign.. (grow or shrink) unsigned int idx = 0; double max = fabs(d[0]); int signVal; for (unsigned int i=1; i<3; i++) { if (fabs(d[i]) > max) { idx = i; max = fabs(d[i]); } } signVal = sign(d[idx]); // The new size is .... const double norm = vtkMath::Norm(d); for (unsigned int i=0; i<3; i++) { newWidth[i] *= (1+(norm * signVal)/10.0); } } // Handle special cases. switch (resizeType) { case PaintbrushResize_XY: newWidth[2] = this->Width[2]; break; case PaintbrushResize_YZ: newWidth[0] = this->Width[0]; break; case PaintbrushResize_XZ: newWidth[1] = this->Width[1]; break; } // Make sure we aren't smaller than the minimum if (newWidth[0] < minSize || newWidth[1] < minSize || newWidth[2] < minSize) { return 0; } // Now change our size to the new size. this->SetWidth( newWidth ); return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::DeepCopy(vtkKWEPaintbrushShape *s) { if (s == this) { return; } vtkKWEPaintbrushShapeBox *sb = vtkKWEPaintbrushShapeBox::SafeDownCast(s); if (sb) { for (unsigned int i=0; i<3; i++) { this->Width[i] = sb->Width[i]; } } this->Superclass::DeepCopy(s); this->Modified(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::GetAnnotation(char *s) { sprintf(s, "(%0.3g,%0.3g,%0.3g)", this->Width[0], this->Width[1], this->Width[2]); } //---------------------------------------------------------------------- int vtkKWEPaintbrushShapeBox::IsInside(double currPos[3], double worldPos[3]) { for (unsigned int i=0; i<3; i++) { if (fabs(worldPos[i] - currPos[i]) > this->Width[i]/2.0) { return 0; } } return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::GetExtent( int extent[6], double p[3] ) { if (this->Representation == vtkKWEPaintbrushEnums::Grayscale) { for (int i=0; i< 3; i++) { // transition region based extension of width. extent[2*i] = static_cast((p[i] - this->Width[i]* (0.5+1.0/2.0) - this->Origin[i])/ this->Spacing[i] + 0.5); extent[2*i+1] = static_cast((p[i] + this->Width[i]* (0.5+1.0/2.0) - this->Origin[i])/ this->Spacing[i] - 0.4999999); extent[2*i] = extent[2*i] < 0 ? 0 : extent[2*i]; if (extent[2*i] > extent[2*i+1]) { extent[2*i+1] = extent[2*i]; } } } else { for (int i=0; i< 3; i++) { extent[2*i] = static_cast((p[i] - this->Width[i]/2.0 - this->Origin[i]) /this->Spacing[i] + 0.5); extent[2*i+1] = static_cast((p[i] + this->Width[i]/2.0 - this->Origin[i]) /this->Spacing[i] - 0.49999999); extent[2*i] = extent[2*i] < 0 ? 0 : extent[2*i]; if (extent[2*i] > extent[2*i+1]) { extent[2*i+1] = extent[2*i]; } } } // Clip the extents with the ClipExtent for (int i=0; i< 3; i++) { if (extent[2*i] < this->ClipExtent[2*i]) { extent[2*i] = this->ClipExtent[2*i]; } if (extent[2*i+1] > this->ClipExtent[2*i+1]) { extent[2*i+1] = this->ClipExtent[2*i+1]; } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Width: (" << this->Width[0] << ", " << this->Width[1] << ", " << this->Width[2] << ")\n"; } vtkedge-0.2.0~20110819/Widgets/vtkKWEITKImage.h0000644000175000017500000002041711363410610020304 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef __vtkKWEITKImage_h #define __vtkKWEITKImage_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "itkVTKImageToImageFilter.h" #include "itkImageToVTKImageFilter.h" #include "itkCastImageFilter.h" #include "vtkKWEITKFilterModuleBase.h" #include "itkImage.h" #include "vtkImageData.h" #include "itkImageIOBase.h" #include "vtkObject.h" #include "vtkSmartPointer.h" class vtkImageData; class vtkImageImport; class vtkImageStencilData; #if defined(VTK_TYPE_USE___INT64) #define vtkitkTemplateMacro___INT64 \ vtkTemplateMacroCase_si64(VTK___INT64, __int64, call); #else #define vtkitkTemplateMacro___INT64 #endif #if defined(VTK_TYPE_USE___INT64) && defined(VTK_TYPE_CONVERT_UI64_TO_DOUBLE) #define vtkitkTemplateMacro___UINT64 \ vtkTemplateMacroCase_ui64(VTK_UNSIGNED___INT64, unsigned __int64, call); #else #define vtkitkTemplateMacro___UINT64 #endif // ITK's support for 64 bit types, long long etc is poor, not as exhaustive // as VTK. Define an alternate macro here that ignores those types. Nobody // will use them anyway. #define vtkitkTemplateMacro(call) \ vtkTemplateMacroCase(VTK_DOUBLE, double, call); \ vtkTemplateMacroCase(VTK_FLOAT, float, call); \ vtkitkTemplateMacro___INT64 \ vtkitkTemplateMacro___UINT64 \ vtkTemplateMacroCase(VTK_LONG, long, call); \ vtkTemplateMacroCase(VTK_UNSIGNED_LONG, unsigned long, call); \ vtkTemplateMacroCase(VTK_INT, int, call); \ vtkTemplateMacroCase(VTK_UNSIGNED_INT, unsigned int, call); \ vtkTemplateMacroCase(VTK_SHORT, short, call); \ vtkTemplateMacroCase(VTK_UNSIGNED_SHORT, unsigned short, call); \ vtkTemplateMacroCase(VTK_CHAR, char, call); \ vtkTemplateMacroCase(VTK_SIGNED_CHAR, signed char, call); \ vtkTemplateMacroCase(VTK_UNSIGNED_CHAR, unsigned char, call) // .NAME vtkKWEITKImage // .SECTION Description // This class provides seamless conversion from VTK to ITK images and vice // versa. Specifically, you can set an ITK image (itk::Image< T >) and get // the corresponding VTK image (vtkImageData), or a binarized stencil image // (vtkImageStencilData). You can also go the other way around. // .SECTION See Also class VTKEdge_WIDGETS_EXPORT vtkKWEITKImage : public vtkObject { public: static vtkKWEITKImage* New(); vtkTypeRevisionMacro(vtkKWEITKImage,vtkObject); typedef itk::ImageIOBase::IOComponentType ITKScalarPixelType; // Description: // Set methods. You should use only one of them. Using another // invalidates the previous "Set..." void SetImage( itk::ImageBase< 3 > * ); void SetImage( vtkImageData * ); void SetImage( vtkImageStencilData * ); // Description: // Get an image as a ITK (untemplated or templated and implicitly casted) / // VTK / VTK binarized image. vtkImageData * GetVTKImage(); vtkImageStencilData * GetVTKImageStencilData(); itk::ImageBase< 3 > * GetITKImage(); template< class T > itk::Image * GetITKImage( T ) { return this->InternalGetITKImage(static_cast(0)); } // Return the pixel type using ITK enums. ITKScalarPixelType GetITKScalarPixelType(); // Return the pixel type using VTK enums. int GetVTKScalarPixelType(); protected: vtkKWEITKImage(); ~vtkKWEITKImage(); // Description: // Get a binary stencil from an image. All pixels >= threshold are // considered within the stencil. static void GetStencilFromImage( vtkImageData *, vtkImageStencilData *, double thresold=127.5 ); // Description: // Construct an unsigned char vtkImageData from a stencil. static void GetImageFromStencil( vtkImageData *, vtkImageStencilData *, unsigned char inVal=255, unsigned char outVal=0); enum InputType { VTK_IMAGE_INPUT = 0, VTK_IMAGE_STENCIL_INPUT, ITK_IMAGE_INPUT, NO_INPUT_SET }; typedef itk::ImageBase< 3 > ImageBaseType; typedef ImageBaseType::Pointer ImagePointer; typedef ImageBaseType::ConstPointer ImageConstPointer; private: vtkKWEITKImage(const vtkKWEITKImage&); // Not implemented. void operator=(const vtkKWEITKImage&); // Not implemented. InputType InputMode; itk::ProcessObject::Pointer ItkToVtkExporter; itk::ProcessObject::Pointer VtkToItkExporter; itk::ProcessObject::Pointer ItkToItkCastor; vtkSmartPointer< vtkImageStencilData > VtkImageStencil; vtkSmartPointer< vtkImageData > VtkImage; itk::ImageBase<3>::Pointer ItkImage; vtkTimeStamp VtkImageStencilTime; vtkTimeStamp VtkImageTime; vtkTimeStamp ItkImageTime; /** \class ItkToItkCastor * This helper class will take care of casting an ITK image to one of type * TPixel. */ template class ItkToItkCast { public: typedef itk::Image< TPixel, 3 > InputImageType; typedef itk::Image< TOutputPixel, 3 > OutputImageType; typedef itk::CastImageFilter< InputImageType, OutputImageType > CastFilterType; static itk::Image * Cast( itk::ImageBase<3> * imageBase, itk::ProcessObject::Pointer & castor ) { if (InputImageType * image = dynamic_cast< InputImageType * >( imageBase )) { typedef typename CastFilterType::Pointer CastFilterPointer; CastFilterPointer caster = dynamic_cast< CastFilterType * >(castor.GetPointer()); if (!caster) { caster = CastFilterType::New(); } caster->SetInput( image ); castor = caster; caster->Update(); return caster->GetOutput(); } return NULL; } }; template itk::Image * InternalGetITKImage( T ) { if (itk::Image * i = ItkToItkCast< unsigned char, T >::Cast( this->GetITKImage(), this->ItkToItkCastor )) return i; if (itk::Image * i = ItkToItkCast< char, T >::Cast( this->GetITKImage(), this->ItkToItkCastor )) return i; if (itk::Image * i = ItkToItkCast< unsigned short, T >::Cast( this->GetITKImage(), this->ItkToItkCastor )) return i; if (itk::Image * i = ItkToItkCast< short, T >::Cast( this->GetITKImage(), this->ItkToItkCastor )) return i; if (itk::Image * i = ItkToItkCast< unsigned int, T >::Cast( this->GetITKImage(), this->ItkToItkCastor )) return i; if (itk::Image * i = ItkToItkCast< int, T >::Cast( this->GetITKImage(), this->ItkToItkCastor )) return i; if (itk::Image * i = ItkToItkCast< unsigned long, T >::Cast( this->GetITKImage(), this->ItkToItkCastor )) return i; if (itk::Image * i = ItkToItkCast< long, T >::Cast( this->GetITKImage(), this->ItkToItkCastor )) return i; if (itk::Image * i = ItkToItkCast< float, T >::Cast( this->GetITKImage(), this->ItkToItkCastor )) return i; if (itk::Image * i = ItkToItkCast< double, T >::Cast( this->GetITKImage(), this->ItkToItkCastor )) return i; return NULL; } }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushWidget.cxx0000644000175000017500000013361611521051333022555 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEWidgetGroup.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushAnnotationWidget.h" #include "vtkKWEPaintbrushSelectionWidget.h" #include "vtkKWEPaintbrushWidgetCallbackMapper.h" #include "vtkCommand.h" #include "vtkCallbackCommand.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderWindow.h" #include "vtkObjectFactory.h" #include "vtkRenderer.h" #include "vtkWidgetCallbackMapper.h" #include "vtkProperty2D.h" #include "vtkEvent.h" #include "vtkWidgetEvent.h" #include "vtkCoordinate.h" #include "vtkMath.h" #include "vtkImageActor.h" #include "vtkImageData.h" #include "vtkKWEPaintbrushPropertyManager.h" #define sign(x) ((static_cast(x) < 0.0) ? (-1) : (1)) vtkCxxRevisionMacro(vtkKWEPaintbrushWidget, "$Revision: 3416 $"); vtkStandardNewMacro(vtkKWEPaintbrushWidget); //---------------------------------------------------------------------- vtkKWEPaintbrushWidget::vtkKWEPaintbrushWidget() { this->WidgetState = vtkKWEPaintbrushWidget::PaintbrushInteract; this->ResizeStartPosition[0] = this->ResizeStartPosition[1] = -1; // Set the bindings. vtkKWEPaintbrushWidgetCallbackMapper *bindings = vtkKWEPaintbrushWidgetCallbackMapper::New(); this->SetCallbackMapper(bindings); bindings->Delete(); this->PaintbrushMode = vtkKWEPaintbrushWidget::Edit; // The selection widget will be used if we enter a "select" mode. this->PaintbrushSelectionWidget = vtkKWEPaintbrushSelectionWidget::New(); this->PaintbrushSelectionWidget->SetParent(this); this->PaintbrushAnnotationWidget = vtkKWEPaintbrushAnnotationWidget::New(); this->PaintbrushAnnotationWidget->PaintbrushWidget = this; this->CreateDefaultRepresentation(); } //---------------------------------------------------------------------- vtkKWEPaintbrushWidget::~vtkKWEPaintbrushWidget() { this->PaintbrushAnnotationWidget->Delete(); this->PaintbrushSelectionWidget->Delete(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::CreateDefaultRepresentation() { // Creates only the 2D rep by default for now // We will accomodate the 3D rep later. if ( ! this->WidgetRep ) { vtkKWEPaintbrushRepresentation2D *rep = vtkKWEPaintbrushRepresentation2D::New(); this->SetRepresentation(rep); rep->Delete(); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::SetEnabled(int enabling) { vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); // The handle widgets are not actually enabled until they are placed. // The handle widgets take their representation from the vtkKWEPaintbrushRepresentation. if ( enabling ) { rep->VisibilityOn(); rep->SetStateToInteract(); } else { rep->VisibilityOff(); } this->Superclass::SetEnabled(enabling); this->PaintbrushAnnotationWidget->SetInteractor(this->Interactor); this->PaintbrushAnnotationWidget->SetEnabled(enabling); // The selection widget is enabled only if we are in selection mode and if // the parent widget (ourself) is enabled. this->PaintbrushSelectionWidget->SetInteractor(this->Interactor); this->PaintbrushSelectionWidget->SetEnabled( (this->PaintbrushMode == vtkKWEPaintbrushWidget::Select && enabling == 1) ? 1 : 0 ); if (enabling) { rep->InstallPipeline(); } else { rep->UnInstallPipeline(); } } // The following methods are the callbacks that the widget responds to. //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::BeginDrawCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if ( self->WidgetState == PaintbrushDisabled || !self->WidgetGroup) { return; } // If we are in "Select" mode, let the PaintbrushSelectionWidget handle it. if (self->PaintbrushMode == vtkKWEPaintbrushWidget::Select) { // Invoke an event for the PaintbrushSelectionWidget. The // PaintbrushSelectionWidget's parent is ourself and the widget will // respond to our invocation of the the event. self->InvokeEvent( vtkCommand::LeftButtonPressEvent); // Propagate abort events from the selection widget. self->EventCallbackCommand->SetAbortFlag( self-> PaintbrushSelectionWidget->GetEventCallbackCommand()->GetAbortFlag()); return; } // We are in "Edit" mode. // Check if we are inside the canvas. If we aren't just return. vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); if (!rep->IsInsideCanvas( self->Interactor->GetEventPosition() )) { return; } self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::BeginDrawAction); self->InvokeEvent( vtkKWEPaintbrushWidget::BeginDrawStrokeEvent ); self->EventCallbackCommand->SetAbortFlag(1); } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::BeginDrawThisSketchCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if ( self->WidgetState == PaintbrushDisabled || !self->WidgetGroup) { return; } // If we are in "Select" mode, let the PaintbrushSelectionWidget handle it. if (self->PaintbrushMode == vtkKWEPaintbrushWidget::Select) { // Invoke an event for the PaintbrushSelectionWidget. The // PaintbrushSelectionWidget's parent is ourself and the widget will // respond to our invocation of the the event. self->InvokeEvent( vtkCommand::LeftButtonPressEvent); // Propagate abort events from the selection widget. self->EventCallbackCommand->SetAbortFlag( self-> PaintbrushSelectionWidget->GetEventCallbackCommand()->GetAbortFlag()); return; } // We are in "Edit" mode. // Check if we are inside the canvas. If we aren't just return. vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); if (!rep->IsInsideCanvas( self->Interactor->GetEventPosition() )) { return; } // Make all other sketches except the active one immutable, so that we will // erase only this particular sketch. if (vtkKWEPaintbrushDrawing *drawing = rep->GetPaintbrushDrawing()) { if (vtkKWEPaintbrushSketch *sketch = drawing->GetItem(rep->GetSketchIndex())) { drawing->GetPaintbrushPropertyManager()->GrabFocus(sketch); } } self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::BeginDrawAction); self->InvokeEvent( vtkKWEPaintbrushWidget::BeginDrawStrokeForThisSketchEvent ); self->EventCallbackCommand->SetAbortFlag(1); } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::BeginEraseCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if ( self->WidgetState == PaintbrushDisabled || !self->WidgetGroup || self->PaintbrushMode == vtkKWEPaintbrushWidget::Select ) { return; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); if (!rep->IsInsideCanvas( self->Interactor->GetEventPosition() )) { return; } self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::BeginEraseAction); self->InvokeEvent( vtkKWEPaintbrushWidget::BeginEraseStrokeEvent ); self->EventCallbackCommand->SetAbortFlag(1); } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::BeginEraseThisSketchCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if ( self->WidgetState == PaintbrushDisabled || !self->WidgetGroup || self->PaintbrushMode == vtkKWEPaintbrushWidget::Select ) { return; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); if (!rep->IsInsideCanvas( self->Interactor->GetEventPosition() )) { return; } // Make all other sketches except the active one immutable, so that we will // erase only this particular sketch. if (vtkKWEPaintbrushDrawing *drawing = rep->GetPaintbrushDrawing()) { if (vtkKWEPaintbrushSketch *sketch = drawing->GetItem(rep->GetSketchIndex())) { drawing->GetPaintbrushPropertyManager()->GrabFocus(sketch); } } self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::BeginEraseAction); self->InvokeEvent( vtkKWEPaintbrushWidget::BeginEraseStrokeForThisSketchEvent ); self->EventCallbackCommand->SetAbortFlag(1); } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::MoveCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (self->WidgetState == PaintbrushDisabled) { return; } if (self->PaintbrushMode == vtkKWEPaintbrushWidget::Select) { // Invoke an event for the PaintbrushSelectionWidget. The // PaintbrushSelectionWidget's parent is ourself and the widget will // respond to our invocation of the the event. self->InvokeEvent( vtkCommand::MouseMoveEvent); return; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); double eventPos[2] = { self->Interactor->GetEventPosition()[0], self->Interactor->GetEventPosition()[1] }; if (self->WidgetState == vtkKWEPaintbrushWidget::PaintbrushInteract || self->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDraw || self->WidgetState == vtkKWEPaintbrushWidget::PaintbrushErase) { // We are in Interact mode.. The template should just // hover around along with the cursor. int activate = rep->ActivateShapeOutline(static_cast(eventPos[0]), static_cast(eventPos[1])); if ( activate == 1) { self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::HoverAction); } else if ( activate == -1 ) { self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::LeaveWidgetAction); } } if (self->WidgetState == vtkKWEPaintbrushWidget::PaintbrushResize || self->WidgetState == vtkKWEPaintbrushWidget::PaintbrushIsotropicResize) { // Compute the distance in world co-ordinates from the previous point // This will determine how much we resize.. If we moved up, we will // grow. If we moved down, we will shrink vtkCoordinate *c = vtkCoordinate::New(); c->SetCoordinateSystemToDisplay(); c->SetValue(eventPos[0],eventPos[1],0.0); double * p = c->GetComputedWorldValue(self->GetCurrentRenderer()); double p1[3] = { p[0], p[1], p[2] }; c->SetValue( self->ResizeStartPosition[0], self->ResizeStartPosition[1], 0.0); p = c->GetComputedWorldValue(self->GetCurrentRenderer()); double p2[3] = { p[0], p[1], p[2] }; c->Delete(); // Compute the resize sign.. (grow or shrink) int signVal; if (self->WidgetState == vtkKWEPaintbrushWidget::PaintbrushResize) { unsigned int idx = 0; double max = fabs(p1[0] - p2[0]); for (unsigned int i=1; i<3; i++) { if (fabs(p1[i] - p2[i]) > max) { idx = i; max = fabs(p1[i] - p2[i]); } } signVal = sign(p1[idx]-p2[idx]); } else { const int dx = static_cast(eventPos[0] - self->ResizeStartPosition[0]); const int dy = static_cast(eventPos[1] - self->ResizeStartPosition[1]); signVal = sign(fabs(static_cast(dy)) > fabs(static_cast(dx)) ? dy : dx); double a = fabs(static_cast(dy)); double b = fabs(static_cast(dx)); if (a > b) { signVal = sign(dy); } else { signVal = sign(dx); } } double distance[3] = { fabs(p2[0] - p1[0]) * signVal, fabs(p2[1] - p1[1]) * signVal, fabs(p2[2] - p1[2]) * signVal }; // Let the representation do the actual resize if (rep->ResizeShape( distance, (self->WidgetState == PaintbrushIsotropicResize) ? vtkKWEPaintbrushShape::PaintbrushResizeIsotropic : vtkKWEPaintbrushShape::PaintbrushResizeAnisotropic )) { self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::ResizeAction); self->InvokeEvent( vtkKWEPaintbrushWidget::ResizeEvent ); } self->ResizeStartPosition[0] = static_cast(eventPos[0]); self->ResizeStartPosition[1] = static_cast(eventPos[1]); } } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::EndStrokeCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (self) { if (self->PaintbrushMode == vtkKWEPaintbrushWidget::Select && self->WidgetState != PaintbrushDisabled) { self->ResizeStartPosition[0] = self->ResizeStartPosition[1] = -1; // Invoke an event for the PaintbrushSelectionWidget. The // PaintbrushSelectionWidget's parent is ourself and the widget will // respond to our invocation of the the event. self->InvokeEvent( vtkCommand::LeftButtonReleaseEvent ); return; } else if (self->WidgetState == PaintbrushDisabled || !self->WidgetGroup || self->WidgetState == PaintbrushInteract ) { return; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); // Make all other sketches except the active one immutable, so that we will // erase only this particular sketch. if (vtkKWEPaintbrushDrawing *drawing = rep->GetPaintbrushDrawing()) { if (vtkKWEPaintbrushSketch *sketch = drawing->GetItem(rep->GetSketchIndex())) { drawing->GetPaintbrushPropertyManager()->ReleaseFocus(); } } self->WidgetGroup->DispatchAction( self, &vtkKWEPaintbrushWidget::EndStrokeAction); self->InvokeEvent( vtkKWEPaintbrushWidget::EndStrokeEvent ); } } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::UndoCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (self) { if (self->PaintbrushMode == vtkKWEPaintbrushWidget::Select && self->WidgetState != PaintbrushDisabled) { // Invoke an event for the PaintbrushSelectionWidget. The // PaintbrushSelectionWidget's parent is ourself and the widget will // respond to our invocation of the the event. self->InvokeEvent( vtkCommand::KeyPressEvent); return; } else if (self->WidgetState != PaintbrushInteract || !self->WidgetGroup) { return; } } self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::UndoAction); } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::DeleteCallback(vtkAbstractWidget *w) { // Similar to undo.. stuff is removed from the list forever.. vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (self) { if (self->PaintbrushMode == vtkKWEPaintbrushWidget::Select && self->WidgetState != PaintbrushDisabled) { // Invoke an event for the PaintbrushSelectionWidget. The // PaintbrushSelectionWidget's parent is ourself and the widget will // respond to our invocation of the the event. self->InvokeEvent( vtkCommand::KeyPressEvent); return; } else if (self->WidgetState != PaintbrushInteract || !self->WidgetGroup) { return; } } self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::DeleteAction); } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::RedoCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (!self || self->WidgetState == PaintbrushDisabled || !self->WidgetGroup || self->WidgetState != vtkKWEPaintbrushWidget::PaintbrushInteract || self->PaintbrushMode == vtkKWEPaintbrushWidget::Select) { return; } self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::RedoAction); } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::BeginNewSketchCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (self->WidgetState != vtkKWEPaintbrushWidget::PaintbrushInteract || self->PaintbrushMode == vtkKWEPaintbrushWidget::Select) { return; } // If the user has set a limit on the number of sketches in the drawing, // obey the limit. vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); int maxSketchesAllowed = rep->GetPaintbrushDrawing()->GetMaximumNumberOfSketches(); if (maxSketchesAllowed && rep->GetPaintbrushDrawing()->GetNumberOfItems() == maxSketchesAllowed) { return; // We hit the limit. } self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::BeginNewSketchAction); self->PaintbrushAnnotationWidget->AnnotateNewSketch(); self->InvokeEvent( vtkKWEPaintbrushWidget::BeginNewSketchEvent ); } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::IncrementSketch() { this->IncrementSketchCallback(this); } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::IncrementSketchCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (self->WidgetState != vtkKWEPaintbrushWidget::PaintbrushInteract || self->PaintbrushMode == vtkKWEPaintbrushWidget::Select) { return; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); if (rep->GetPaintbrushDrawing()->GetMaximumNumberOfSketches() == 1) { return; // We just got one sketch. Why annotate it ? } const int oldSketchIndex = rep->GetSketchIndex(); self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::IncrementSketchAction); int newSketchIndex = rep->GetSketchIndex(); self->PaintbrushAnnotationWidget->AnnotateIncrementSketch(); if (newSketchIndex != oldSketchIndex) { self->InvokeEvent( vtkKWEPaintbrushWidget::IncrementSketchEvent, &newSketchIndex ); } } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::DecrementSketchCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (self->WidgetState != vtkKWEPaintbrushWidget::PaintbrushInteract || self->PaintbrushMode == vtkKWEPaintbrushWidget::Select) { return; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); if (rep->GetPaintbrushDrawing()->GetMaximumNumberOfSketches() == 1) { return; // We just got one sketch. Why annotate it ? } const int oldSketchIndex = rep->GetSketchIndex(); self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::DecrementSketchAction); int newSketchIndex = rep->GetSketchIndex(); self->PaintbrushAnnotationWidget->AnnotateDecrementSketch(); if (newSketchIndex != oldSketchIndex) { self->InvokeEvent( vtkKWEPaintbrushWidget::DecrementSketchEvent, &newSketchIndex ); } } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::GoToSketch(int n) { if (this->WidgetState != vtkKWEPaintbrushWidget::PaintbrushInteract || this->PaintbrushMode == vtkKWEPaintbrushWidget::Select) { return; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); this->Payload = &n; this->WidgetGroup->DispatchAction(this, &vtkKWEPaintbrushWidget::GoToSketchAction); int idx = rep->GetSketchIndex(); this->InvokeEvent( vtkKWEPaintbrushWidget::GoToSketchEvent, &idx ); } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::BeginResizeShapeCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (!self || self->WidgetState != PaintbrushInteract || !self->WidgetGroup || self->PaintbrushMode == vtkKWEPaintbrushWidget::Select) { return; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); if (!rep->IsInsideCanvas( self->Interactor->GetEventPosition() )) { return; } self->WidgetGroup->DispatchAction( self, &vtkKWEPaintbrushWidget::BeginResizeAction); self->InvokeEvent( vtkKWEPaintbrushWidget::BeginResizeEvent ); } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::BeginIsotropicResizeShapeCallback(vtkAbstractWidget *w) { // TODO : Write the corresponding actions for it vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (self->WidgetState != PaintbrushInteract || self->PaintbrushMode == vtkKWEPaintbrushWidget::Select) { return; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); if (!rep->IsInsideCanvas( self->Interactor->GetEventPosition() )) { return; } self->WidgetGroup->DispatchAction( self, &vtkKWEPaintbrushWidget::BeginIsotropicResizeAction); self->InvokeEvent( vtkKWEPaintbrushWidget::BeginIsotropicResizeEvent ); } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::EndResizeShapeCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (!self || self->WidgetState == PaintbrushDisabled || self->PaintbrushMode == vtkKWEPaintbrushWidget::Select) { return; } self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::EndResizeAction); self->InvokeEvent( vtkKWEPaintbrushWidget::EndResizeEvent ); } //---------------------------------------------------------------------- // The motivation for this method is strange.. Let me explain.. The widget // by default grabs focus during draws and erases, resize, anisotropic // resize etc.. Sometimes, you may be drawing on an image actor where you // have other callbacks mapped onto similar events.. (for instance window // /level, zoom, translate etc). This method toggles the select state // of the widget void vtkKWEPaintbrushWidget::ToggleSelectStateCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::ToggleSelectStateAction); } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::MergeSelectionCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (self && self->WidgetState != PaintbrushDisabled && self->PaintbrushMode == vtkKWEPaintbrushWidget::Select) { // Invoke an event for the PaintbrushSelectionWidget. The // PaintbrushSelectionWidget's parent is ourself and the widget will // respond to our invocation of the the event. self->InvokeEvent( vtkCommand::KeyPressEvent); } } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::ToggleSelectAllSketchesCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (self && self->WidgetState != PaintbrushDisabled && self->PaintbrushMode == vtkKWEPaintbrushWidget::Select) { // Invoke an event for the PaintbrushSelectionWidget. The // PaintbrushSelectionWidget's parent is ourself and the widget will // respond to our invocation of the the event. self->InvokeEvent( vtkCommand::KeyPressEvent ); } } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::ToggleSketchMutabilityCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (self && self->WidgetState != PaintbrushDisabled && self->PaintbrushMode == vtkKWEPaintbrushWidget::Edit) { vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); vtkKWEPaintbrushSketch * sketch = rep->GetPaintbrushDrawing()->GetItem(rep->GetSketchIndex()); vtkKWEPaintbrushProperty *property = sketch->GetPaintbrushProperty(); property->SetMutable( 1- property->GetMutable() ); self->InvokeEvent( vtkKWEPaintbrushWidget::ToggleSketchMutabilityEvent ); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::DecreaseOpacityCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (self->WidgetState != PaintbrushDisabled) { vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); if (rep->DecreaseOpacity()) { self->Render(); self->InvokeEvent(vtkKWEPaintbrushWidget::DecreaseOpacityEvent); } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::IncreaseOpacityCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (self->WidgetState != PaintbrushDisabled) { vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(self->WidgetRep); if (rep->IncreaseOpacity()) { self->Render(); self->InvokeEvent(vtkKWEPaintbrushWidget::IncreaseOpacityEvent); } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::EnterWidgetCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (!self || self->WidgetState != PaintbrushDisabled) { return; } self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::EnterWidgetAction); self->InvokeEvent( vtkKWEPaintbrushWidget::EnterEvent ); } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::LeaveWidgetCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushWidget *self = vtkKWEPaintbrushWidget::SafeDownCast(w); if (!self || self->WidgetState == PaintbrushDisabled) { return; } self->WidgetGroup->DispatchAction(self, &vtkKWEPaintbrushWidget::LeaveWidgetAction); self->InvokeEvent( vtkKWEPaintbrushWidget::LeaveEvent ); } //---------------------------------------------------------------------- // Geometric Actions / states that the representation can conform to. int vtkKWEPaintbrushWidget::BeginDrawAction(vtkKWEPaintbrushWidget *dispatcher) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); this->WidgetState = vtkKWEPaintbrushWidget::PaintbrushDraw; rep->SetStateToDraw(); if (dispatcher == this) { // Make sure that the current shape position is updated. rep->ActivateShapeOutline( this->Interactor->GetEventPosition()[0], this->Interactor->GetEventPosition()[1] ); rep->BeginNewStroke(); // Get the current position from the active widget. double d[3]; vtkKWEPaintbrushRepresentation *dispatcher_rep = vtkKWEPaintbrushRepresentation::SafeDownCast(dispatcher->WidgetRep); dispatcher_rep->GetCurrentShapePosition(d[0], d[1], d[2]); rep->CreateShapeOutline(d); // If the draw action results in a draw or an erase, do it on the active widget if ((rep->GetInteractionState() == PaintbrushDraw || rep->GetInteractionState() == PaintbrushErase)) { rep->AddShapeToCurrentStroke( d ); } } else { rep->DeepCopy(dispatcher->WidgetRep); } this->SetCursor( rep->GetInteractionState() ); this->Render(); this->EventCallbackCommand->SetAbortFlag(1); return 1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushWidget:: EndStrokeAction( vtkKWEPaintbrushWidget *vtkNotUsed(dispatcher) ) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); this->WidgetState = vtkKWEPaintbrushWidget::PaintbrushInteract; rep->SetStateToInteract(); // Remove focus this->SetCursor( rep->GetInteractionState() ); this->EventCallbackCommand->SetAbortFlag(0); return 1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushWidget::BeginEraseAction(vtkKWEPaintbrushWidget *dispatcher) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); this->WidgetState = vtkKWEPaintbrushWidget::PaintbrushErase; rep->SetStateToErase(); if (dispatcher == this) { // Make sure that the current shape position is updated. rep->ActivateShapeOutline( this->Interactor->GetEventPosition()[0], this->Interactor->GetEventPosition()[1] ); rep->BeginNewStroke(); double d[3]; vtkKWEPaintbrushRepresentation *dispatcher_rep = vtkKWEPaintbrushRepresentation::SafeDownCast(dispatcher->WidgetRep); dispatcher_rep->GetCurrentShapePosition(d[0], d[1], d[2]); rep->CreateShapeOutline(d); // If the draw action results in a draw or an erase, do it on the active widget if ((rep->GetInteractionState() == PaintbrushDraw || rep->GetInteractionState() == PaintbrushErase)) { rep->AddShapeToCurrentStroke( d ); } } else { rep->DeepCopy(dispatcher->WidgetRep); } this->SetCursor( rep->GetInteractionState() ); this->Render(); this->EventCallbackCommand->SetAbortFlag(1); return 1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushWidget::HoverAction(vtkKWEPaintbrushWidget *dispatcher) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } // Get the current position from the active widget. double d[3]; vtkKWEPaintbrushRepresentation *dispatcher_rep = vtkKWEPaintbrushRepresentation::SafeDownCast(dispatcher->WidgetRep); vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); dispatcher_rep->GetCurrentShapePosition(d[0], d[1], d[2]); rep->SetShapeOutlineVisibility(1); rep->CreateShapeOutline(d); // If the hover results in a draw or an erase, do it on the active widget if (this == dispatcher && (rep->GetInteractionState() == PaintbrushDraw || rep->GetInteractionState() == PaintbrushErase)) { rep->AddShapeToCurrentStroke( d ); } this->SetCursor( PaintbrushDraw ); this->Render(); return 1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushWidget::UndoAction(vtkKWEPaintbrushWidget *dispatcher) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); if (dispatcher == this) { if (rep->UndoStroke() == 0) { return 0; } } this->EventCallbackCommand->SetAbortFlag(1); // We are definitely selected this->Render(); this->InvokeEvent( vtkKWEPaintbrushWidget::UndoStrokeEvent ); return 1; } //------------------------------------------------------------------------- int vtkKWEPaintbrushWidget::RedoAction(vtkKWEPaintbrushWidget *dispatcher) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); if (dispatcher == this) { if (rep->RedoStroke() == 0) { return 0; } } this->EventCallbackCommand->SetAbortFlag(1); // We are definitely selected this->Render(); this->InvokeEvent( vtkKWEPaintbrushWidget::RedoStrokeEvent ); return 1; } //------------------------------------------------------------------------- int vtkKWEPaintbrushWidget::BeginNewSketchAction(vtkKWEPaintbrushWidget *dispatcher) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); if (dispatcher == this) { rep->BeginNewSketch(); } else { rep->DeepCopy(dispatcher->WidgetRep); } return 1; } //------------------------------------------------------------------------- int vtkKWEPaintbrushWidget ::IncrementSketchAction(vtkKWEPaintbrushWidget *vtkNotUsed(dispatcher)) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); return rep->IncrementSketch(); } //------------------------------------------------------------------------- int vtkKWEPaintbrushWidget ::ToggleSelectStateAction(vtkKWEPaintbrushWidget *dispatcher) { vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { this->PaintbrushAnnotationWidget->AnnotateString("Brush enabled"); this->WidgetState = vtkKWEPaintbrushWidget::PaintbrushInteract; this->PaintbrushSelectionWidget->ProcessEventsOn(); rep->SetStateToInteract(); rep->SetShapeOutlineVisibility( this->PaintbrushMode == vtkKWEPaintbrushWidget::Select ? 0 : 1 ); } else { this->PaintbrushAnnotationWidget->AnnotateString("Brush disabled"); this->WidgetState = vtkKWEPaintbrushWidget::PaintbrushDisabled; this->ResizeStartPosition[0] = this->ResizeStartPosition[1] = -1; this->PaintbrushSelectionWidget->ProcessEventsOff(); rep->SetStateToDisabled(); } this->SetCursor( rep->GetInteractionState() ); this->EventCallbackCommand->SetAbortFlag(1); this->Render(); this->InvokeEvent( vtkKWEPaintbrushWidget::ToggleSelectStateEvent ); return 1; } //------------------------------------------------------------------------- int vtkKWEPaintbrushWidget ::DecrementSketchAction(vtkKWEPaintbrushWidget *vtkNotUsed(dispatcher)) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); return rep->DecrementSketch(); } //------------------------------------------------------------------------- int vtkKWEPaintbrushWidget ::GoToSketchAction(vtkKWEPaintbrushWidget *dispatcher) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } int *n = static_cast< int * >( dispatcher->Payload ); vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); return rep->GoToSketch(*n); } //---------------------------------------------------------------------- int vtkKWEPaintbrushWidget::DeleteAction(vtkKWEPaintbrushWidget *dispatcher) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); if (dispatcher == this) { if (rep->RemoveLastStroke() == 0) { return 0; } } this->Render(); this->InvokeEvent( vtkKWEPaintbrushWidget::DeleteStrokeEvent ); return 1; } //------------------------------------------------------------------------- int vtkKWEPaintbrushWidget::BeginResizeAction(vtkKWEPaintbrushWidget *dispatcher) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); rep->SetStateToResize(); this->WidgetState = vtkKWEPaintbrushWidget::PaintbrushResize; if (dispatcher == this) { this->ResizeStartPosition[0] = this->Interactor->GetEventPosition()[0]; this->ResizeStartPosition[1] = this->Interactor->GetEventPosition()[1]; this->PaintbrushAnnotationWidget->AnnotateSize(); } this->SetCursor( rep->GetInteractionState() ); this->EventCallbackCommand->SetAbortFlag(1); // We are definitely selected return 1; } //------------------------------------------------------------------------- int vtkKWEPaintbrushWidget::BeginIsotropicResizeAction( vtkKWEPaintbrushWidget *dispatcher) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); this->WidgetState = vtkKWEPaintbrushWidget::PaintbrushIsotropicResize; rep->SetStateToIsotropicResize(); if (dispatcher == this) { this->ResizeStartPosition[0] = this->Interactor->GetEventPosition()[0]; this->ResizeStartPosition[1] = this->Interactor->GetEventPosition()[1]; this->PaintbrushAnnotationWidget->AnnotateSize(); } this->SetCursor( rep->GetInteractionState() ); // We are definitely selected this->EventCallbackCommand->SetAbortFlag(1); return 1; } //------------------------------------------------------------------------- int vtkKWEPaintbrushWidget::ResizeAction(vtkKWEPaintbrushWidget *dispatcher) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } if (this == dispatcher) { // Compute the distance in world co-ordinates from the previous point // This will determine how much we resize.. If we moved up, we will // grow. If we moved down, we will shrink double eventPos[2] = { this->Interactor->GetEventPosition()[0], this->Interactor->GetEventPosition()[1] }; vtkCoordinate *c = vtkCoordinate::New(); c->SetCoordinateSystemToDisplay(); c->SetValue(eventPos[0],eventPos[1],0.0); double * p = c->GetComputedWorldValue(this->GetCurrentRenderer()); double p1[3] = { p[0], p[1], p[2] }; c->SetValue( this->ResizeStartPosition[0], this->ResizeStartPosition[1], 0.0); p = c->GetComputedWorldValue(this->GetCurrentRenderer()); double p2[3] = { p[0], p[1], p[2] }; c->Delete(); // Compute the resize sign.. (grow or shrink) int signVal; if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushResize) { unsigned int idx = 0; double max = fabs(p1[0] - p2[0]); for (unsigned int i=1; i<3; i++) { if (fabs(p1[i] - p2[i]) > max) { idx = i; max = fabs(p1[i] - p2[i]); } } signVal = sign(p1[idx]-p2[idx]); } else { signVal = sign(eventPos[1] - this->ResizeStartPosition[1]); } this->ResizeFactor[0] = fabs(p2[0] - p1[0]) * signVal; this->ResizeFactor[1] = fabs(p2[1] - p1[1]) * signVal; this->ResizeFactor[2] = fabs(p2[2] - p1[2]) * signVal; // Throw some annotation up on the screen. this->PaintbrushAnnotationWidget->AnnotateSize(); } else { this->DeepCopy(dispatcher); // synchronize states with the dispatcher } this->Render(); return 1; } //------------------------------------------------------------------------- int vtkKWEPaintbrushWidget ::EndResizeAction(vtkKWEPaintbrushWidget *vtkNotUsed(dispatcher)) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); this->WidgetState = vtkKWEPaintbrushWidget::PaintbrushInteract; this->ResizeStartPosition[0] = this->ResizeStartPosition[1] = -1; rep->SetStateToInteract(); this->EventCallbackCommand->SetAbortFlag(0); // remove focus this->SetCursor( rep->GetInteractionState() ); return 1; } //------------------------------------------------------------------------- int vtkKWEPaintbrushWidget:: EnterWidgetAction(vtkKWEPaintbrushWidget *vtkNotUsed(dispatcher)) { // TODO if you want to implement anything special return 1; } //------------------------------------------------------------------------- int vtkKWEPaintbrushWidget:: LeaveWidgetAction(vtkKWEPaintbrushWidget *vtkNotUsed(dispatcher)) { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { return 0; } vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep); if ( rep->GetShapeOutlineVisibility() ) { //clear string this->PaintbrushAnnotationWidget->AnnotateString(""); rep->SetShapeOutlineVisibility(0); this->Render(); } return 1; } //------------------------------------------------------------------------- void vtkKWEPaintbrushWidget::DeepCopy(vtkAbstractWidget *widget) { vtkKWEPaintbrushWidget *w = vtkKWEPaintbrushWidget::SafeDownCast(widget); if (this == w || !w) { return; } this->WidgetState = w->WidgetState; if (w->WidgetGroup) { w->WidgetGroup->AddWidget(this); } if (w->WidgetRep && this->WidgetRep) { (static_cast(this->WidgetRep))->DeepCopy(w->WidgetRep); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::SetRepresentation( vtkKWEPaintbrushRepresentation * r ) { this->PaintbrushAnnotationWidget->SetRepresentation( r ? r->GetAnnotation() : NULL); this->PaintbrushSelectionWidget->SetRepresentation( r ? r->GetSelectionRepresentation() : NULL); this->Superclass::SetWidgetRepresentation(r); } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::SetPaintbrushMode( int m ) { if (m == this->PaintbrushMode) { return; } // Enable the selection widget in select mode. this->PaintbrushSelectionWidget->SetEnabled( (m == vtkKWEPaintbrushWidget::Select && this->Enabled == 1) ? 1 : 0 ); // turn off the hovering brush if we are in selection mode. vtkKWEPaintbrushRepresentation * rep = static_cast< vtkKWEPaintbrushRepresentation * >(this->WidgetRep); rep->SetShapeOutlineVisibility( m == vtkKWEPaintbrushWidget::Select ? 0 : 1 ); // Cursor is a hand cursor in selection mode, crosshair in edit mode //this->RequestCursorShape( m == vtkKWEPaintbrushWidget::Select ? // VTK_CURSOR_HAND : VTK_CURSOR_CROSSHAIR); this->PaintbrushMode = m; } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::SetProcessEvents(int pe) { this->Superclass::SetProcessEvents(pe); if (vtkKWEPaintbrushRepresentation *rep = vtkKWEPaintbrushRepresentation::SafeDownCast(this->WidgetRep)) { // If we aren't receiving any events, don't show the annoying shape outline. rep->SetShapeOutlineVisibility( pe && this->WidgetState != PaintbrushDisabled && this->PaintbrushMode != Select ); } this->PaintbrushSelectionWidget->SetProcessEvents(pe); } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::SetCursor(int vtkNotUsed(nteractionstate)) { /* if (this->GetPaintbrushMode() == Select) { // Hand cursor in selection mode this->RequestCursorShape( VTK_CURSOR_HAND ); } // Cursor is a hand cursor in selection mode, crosshair in edit mode else if (interactionstate == vtkKWEPaintbrushRepresentation::PaintbrushResize || interactionstate == vtkKWEPaintbrushRepresentation::PaintbrushIsotropicResize) { // Resize cursor this->RequestCursorShape( VTK_CURSOR_SIZEALL ); } else { // the default is a crosshair cursor. this->RequestCursorShape( VTK_CURSOR_CROSSHAIR); } */ } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::SetWidgetStateToEnabled() { if (this->WidgetState == vtkKWEPaintbrushWidget::PaintbrushDisabled) { this->ToggleSelectStateCallback(this); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::SetWidgetStateToDisabled() { if (this->WidgetState != vtkKWEPaintbrushWidget::PaintbrushDisabled) { this->ToggleSelectStateCallback(this); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushWidget::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushStencilData.h0000644000175000017500000000675711363410610023160 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushStencilData - An abstract class used to support segmentations // .SECTION Description // // .SECTION see also // vtkImageStencilSource vtkImageStencil #ifndef __vtkKWEPaintbrushStencilData_h #define __vtkKWEPaintbrushStencilData_h #include "vtkKWEPaintbrushData.h" class vtkImageStencilData; class vtkImageData; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushStencilData : public vtkKWEPaintbrushData { public: static vtkKWEPaintbrushStencilData *New(); vtkTypeRevisionMacro(vtkKWEPaintbrushStencilData, vtkKWEPaintbrushData); void PrintSelf(ostream& os, vtkIndent indent); void DeepCopy(vtkDataObject *o); void ShallowCopy(vtkDataObject *f); // Description: virtual void SetImageStencilData( vtkImageStencilData * ); vtkGetObjectMacro( ImageStencilData, vtkImageStencilData ); // Description: // Minkowski operations virtual int Add( vtkKWEPaintbrushData *, bool forceMutable=false ); virtual int Subtract( vtkKWEPaintbrushData *, bool forceMutable=false ); virtual int Replace( vtkKWEPaintbrushData *, bool forceMutable=false ); virtual int Add( vtkImageStencilData *, bool forceMutable=false ); virtual int Subtract( vtkImageStencilData *, bool forceMutable=false ); virtual int Replace( vtkImageStencilData *, bool forceMutable=false ); // Description: // Clip self with supplied extents. Return 1 if something changed virtual int Clip( int extent[6] ); // Description: // Allocate and fill. This will wipe out any existing data. virtual void Allocate(double fillValue = 0.0 ); // Description: // Resize. Unlike allocate, this will allocate to conform to the new // extents, while preserving existing data. If you are calling // Resize with the extents for the first time, this is the same as // calling // SetExtent(..) followed by Allocate(..). virtual void Resize( int extent[6], double fillValue = 0.0 ); // Description: // Set the metadata. virtual void SetSpacing(double spacing[3]); virtual void SetOrigin( double origin[3] ); // Description: // Set/Get extents. virtual void SetExtent( int extent[6] ); virtual void GetExtent( int extent[6] ); // Description: // Is the point "p" inside ? virtual int IsInside( double p[3] ); // Description: // Get the binary brush stencil data as an image data virtual void GetPaintbrushDataAsImageData( vtkImageData * ); // Description: // See vtkObject for doc virtual unsigned long GetMTime(); protected: vtkKWEPaintbrushStencilData(); ~vtkKWEPaintbrushStencilData(); vtkImageStencilData * ImageStencilData; private: vtkKWEPaintbrushStencilData(const vtkKWEPaintbrushStencilData&); // Not implemented. void operator=(const vtkKWEPaintbrushStencilData&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushAnnotationWidget.cxx0000644000175000017500000003021111363410610024574 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushAnnotationWidget.h" #include "vtkKWEPaintbrushAnnotationRepresentation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushRepresentation.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushShape.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkTextProperty.h" #include "vtkCommand.h" #include "vtkCallbackCommand.h" #include "vtkRenderWindowInteractor.h" #include "vtkObjectFactory.h" #include "vtkRenderer.h" #include "vtkWidgetCallbackMapper.h" #include "vtkEvent.h" #include "vtkWidgetEvent.h" #include "vtkCoordinate.h" #include "vtkMath.h" #include #define sign(x) ((((double)x) < 0.0) ? (-1) : (1)) vtkCxxRevisionMacro(vtkKWEPaintbrushAnnotationWidget, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEPaintbrushAnnotationWidget); //---------------------------------------------------------------------- vtkKWEPaintbrushAnnotationWidget::vtkKWEPaintbrushAnnotationWidget() { this->WidgetState = vtkKWEPaintbrushAnnotationWidget::Start; // These are the event callbacks supported by this widget this->CallbackMapper->SetCallbackMethod(vtkCommand::MouseMoveEvent, vtkWidgetEvent::Move, this, vtkKWEPaintbrushAnnotationWidget::MoveCallback); this->CallbackMapper->SetCallbackMethod(vtkCommand::TimerEvent, vtkWidgetEvent::TimedOut, this, vtkKWEPaintbrushAnnotationWidget::HoverCallback); this->Movement = 0; this->TimerDuration = 5000; this->TimerId = -1; this->PaintbrushWidget = NULL; this->CreateDefaultRepresentation(); } //---------------------------------------------------------------------- vtkKWEPaintbrushAnnotationWidget::~vtkKWEPaintbrushAnnotationWidget() { if ( this->WidgetState == vtkKWEPaintbrushAnnotationWidget::Timing && this->TimerId != -1 && this->Interactor) { this->Interactor->DestroyTimer(this->TimerId); this->TimerId = -1; } } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationWidget::CreateDefaultRepresentation() { // Creates only the 2D rep by default for now // We will accomodate the 3D rep later. if ( ! this->WidgetRep ) { vtkKWEPaintbrushAnnotationRepresentation *rep = vtkKWEPaintbrushAnnotationRepresentation::New(); this->WidgetRep = rep; } } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationWidget::SetEnabled(int enabling) { // The handle widgets are not actually enabled until they are placed. // The handle widgets take their representation from the vtkKWEPaintbrushAnnotationRepresentation. if ( enabling ) { vtkKWEPaintbrushAnnotationRepresentation *rep = vtkKWEPaintbrushAnnotationRepresentation::SafeDownCast(this->WidgetRep); rep->VisibilityOn(); } else { (vtkKWEPaintbrushAnnotationRepresentation::SafeDownCast( this->WidgetRep))->VisibilityOff(); } this->Superclass::SetEnabled(enabling); } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationWidget::AnnotateString( const char *s ) { if (vtkKWEPaintbrushAnnotationRepresentation *rep = static_cast< vtkKWEPaintbrushAnnotationRepresentation *>(this->WidgetRep)) { rep->SetAnnotation(s); this->SetWidgetState( vtkKWEPaintbrushAnnotationWidget::BeginTimer ); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationWidget::AnnotateIncrementSketch() { if (vtkKWEPaintbrushRepresentation *rep = static_cast< vtkKWEPaintbrushRepresentation*>(this->PaintbrushWidget->GetRepresentation())) { if (vtkKWEPaintbrushSketch *sketch = rep->GetPaintbrushDrawing()-> GetItem(rep->GetSketchIndex())) { vtkKWEPaintbrushProperty * sketchProperty = sketch->GetPaintbrushProperty(); vtksys_ios::ostringstream o; o << "Sketch " << rep->GetSketchIndex(); if (sketchProperty->GetIdentifier()) { o << ": " << sketchProperty->GetIdentifier(); } o << ends; // Annotation color to match the sketch color. static_cast< vtkKWEPaintbrushAnnotationRepresentation *>(this->WidgetRep)-> GetTextProperty()->SetColor( sketchProperty->GetColor() ); this->AnnotateString(o.str().c_str()); } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationWidget::AnnotateDecrementSketch() { if (vtkKWEPaintbrushRepresentation *rep = static_cast< vtkKWEPaintbrushRepresentation*>(this->PaintbrushWidget->GetRepresentation())) { if (vtkKWEPaintbrushSketch *sketch = rep->GetPaintbrushDrawing()-> GetItem(rep->GetSketchIndex())) { vtkKWEPaintbrushProperty * sketchProperty = sketch->GetPaintbrushProperty(); vtksys_ios::ostringstream o; o << "Sketch " << rep->GetSketchIndex(); if (sketchProperty->GetIdentifier()) { o << ": " << sketchProperty->GetIdentifier(); } o << ends; // Annotation color to match the sketch color. static_cast< vtkKWEPaintbrushAnnotationRepresentation *>(this->WidgetRep)-> GetTextProperty()->SetColor( sketchProperty->GetColor() ); this->AnnotateString(o.str().c_str()); } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationWidget::AnnotateNewSketch() { if (vtkKWEPaintbrushRepresentation *rep = static_cast< vtkKWEPaintbrushRepresentation*>(this->PaintbrushWidget->GetRepresentation())) { if (vtkKWEPaintbrushSketch *sketch = rep->GetPaintbrushDrawing()-> GetItem(rep->GetSketchIndex())) { vtkKWEPaintbrushProperty * sketchProperty = sketch->GetPaintbrushProperty(); vtksys_ios::ostringstream o; o << "New sketch " << rep->GetSketchIndex(); if (sketchProperty->GetIdentifier()) { o << ": " << sketchProperty->GetIdentifier(); } o << ends; // Annotation color to match the sketch color. static_cast< vtkKWEPaintbrushAnnotationRepresentation *>(this->WidgetRep)-> GetTextProperty()->SetColor( sketchProperty->GetColor() ); this->AnnotateString(o.str().c_str()); } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationWidget::AnnotateSize() { if (vtkKWEPaintbrushRepresentation *rep = static_cast< vtkKWEPaintbrushRepresentation*>(this->PaintbrushWidget->GetRepresentation())) { char str[256]; rep->GetPaintbrushOperation()->GetPaintbrushShape()->GetAnnotation(str); if (vtkKWEPaintbrushSketch *sketch = rep->GetPaintbrushDrawing()-> GetItem(rep->GetSketchIndex())) { vtkKWEPaintbrushProperty * sketchProperty = sketch->GetPaintbrushProperty(); // Annotation color to match the sketch color. static_cast< vtkKWEPaintbrushAnnotationRepresentation *>(this->WidgetRep)-> GetTextProperty()->SetColor( sketchProperty->GetColor() ); } this->AnnotateString(str); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationWidget::AnnotatePaintbrushMode() { vtksys_stl::string annotationString = (this->PaintbrushWidget->GetPaintbrushMode() == vtkKWEPaintbrushWidget::Edit) ? "EditMode" : "Select Mode"; if (vtkKWEPaintbrushRepresentation *rep = static_cast< vtkKWEPaintbrushRepresentation*>(this->PaintbrushWidget->GetRepresentation())) { if (vtkKWEPaintbrushSketch *sketch = rep->GetPaintbrushDrawing()-> GetItem(rep->GetSketchIndex())) { vtkKWEPaintbrushProperty * sketchProperty = sketch->GetPaintbrushProperty(); // Annotation color to match the sketch color. static_cast< vtkKWEPaintbrushAnnotationRepresentation *>(this->WidgetRep)-> GetTextProperty()->SetColor( sketchProperty->GetColor() ); } this->AnnotateString(annotationString.c_str()); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationWidget::SetWidgetState( int w ) { if (this->WidgetState != w) { bool needRender = false; vtkKWEPaintbrushAnnotationRepresentation *rep = static_cast< vtkKWEPaintbrushAnnotationRepresentation *>(this->WidgetRep); // Create a new timer. if (w == vtkKWEPaintbrushAnnotationWidget::BeginTimer) { if ( this->WidgetState == vtkKWEPaintbrushAnnotationWidget::Timing ) { this->Interactor->DestroyTimer(this->TimerId); this->TimerId = -1; } this->TimerId = this->Interactor->CreateOneShotTimer(this->TimerDuration); this->WidgetState = vtkKWEPaintbrushAnnotationWidget::Timing; this->Movement = 0; if (rep) { rep->VisibilityOn(); rep->BuildRepresentation(); needRender = true; } } // Remove any timers if (w == vtkKWEPaintbrushAnnotationWidget::EndTimer) { if ( this->WidgetState == vtkKWEPaintbrushAnnotationWidget::Timing) { this->Interactor->DestroyTimer(this->TimerId); this->TimerId = -1; this->WidgetState = vtkKWEPaintbrushAnnotationWidget::Start; if (rep) { rep->VisibilityOff(); needRender = true; } } } if (needRender) { this->Render(); } } } // The following methods are the callbacks that the widget responds to. //------------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationWidget::MoveCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushAnnotationWidget *self = reinterpret_cast(w); if (self->Movement++ > 20) { // Remove annotation. User is trying to shirk it off self->SetWidgetState(vtkKWEPaintbrushAnnotationWidget::EndTimer); } } //------------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationWidget::HoverCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushAnnotationWidget *self = reinterpret_cast(w); if (self->CallData) { int timerId = *(reinterpret_cast(self->CallData)); // If this is the timer event we are waiting for... if ( timerId == self->TimerId && self->WidgetState == vtkKWEPaintbrushAnnotationWidget::Timing ) { // Remove annotation. Its been there for too long (TimerDuration time). //self->SetWidgetState(vtkKWEPaintbrushAnnotationWidget::EndTimer); self->EventCallbackCommand->SetAbortFlag(1); //no one else gets this timer } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationWidget::SetRepresentation( vtkKWEPaintbrushAnnotationRepresentation * r ) { this->Superclass::SetWidgetRepresentation(r); } //---------------------------------------------------------------------- void vtkKWEPaintbrushAnnotationWidget::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEAbstractPaintbrushWidget.cxx0000644000175000017500000000564311501735401024242 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEAbstractPaintbrushWidget.h" #include "vtkKWEWidgetGroup.h" #include "vtkKWEPaintbrushWidgetCallbackMapper.h" #include "vtkWidgetEventTranslator.h" #include "vtkObjectFactory.h" #include "vtkGarbageCollector.h" vtkCxxRevisionMacro(vtkKWEAbstractPaintbrushWidget, "$Revision: 3231 $"); //---------------------------------------------------------------------- vtkKWEAbstractPaintbrushWidget::vtkKWEAbstractPaintbrushWidget() { this->WidgetGroup = NULL; vtkKWEWidgetGroup * w = vtkKWEWidgetGroup::New(); w->AddWidget(this); w->Delete(); this->Payload = NULL; } //---------------------------------------------------------------------- void vtkKWEAbstractPaintbrushWidget::Register( vtkObjectBase *o ) { // Enable garbage collection. There are ref counting cycles with vtkKWEWidgetGroup this->RegisterInternal(o, 1); } //---------------------------------------------------------------------- void vtkKWEAbstractPaintbrushWidget::UnRegister( vtkObjectBase *o ) { // Enable garbage collection. There are ref counting cycles with vtkKWEWidgetGroup this->UnRegisterInternal(o, 1); } //---------------------------------------------------------------------- void vtkKWEAbstractPaintbrushWidget:: SetCallbackMapper( vtkKWEPaintbrushWidgetCallbackMapper *o ) { if (o == this->CallbackMapper) { return; } // Enable garbage collection. There are ref counting cycles with vtkKWEWidgetGroup if (this->CallbackMapper) { this->CallbackMapper->SetEventTranslator(NULL); this->CallbackMapper->Delete(); this->CallbackMapper = NULL; } this->CallbackMapper = o; if (o) { this->CallbackMapper->Register(this); o->SetPaintbrushWidget(this); // no ref couting here. o->Bindings(); } } //---------------------------------------------------------------------------- void vtkKWEAbstractPaintbrushWidget::ReportReferences(vtkGarbageCollector* collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->WidgetGroup, "WidgetGroup"); } //---------------------------------------------------------------------- void vtkKWEAbstractPaintbrushWidget::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEBoundingBoxWidget2D.cxx0000644000175000017500000003472611363410610023045 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEBoundingBoxWidget2D.h" #include "vtkKWEBoundingBoxRepresentation2D.h" #include "vtkActor.h" #include "vtkCallbackCommand.h" #include "vtkObjectFactory.h" #include "vtkProperty.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkRendererCollection.h" #include "vtkRenderWindow.h" #include "vtkCommand.h" #include "vtkWidgetEventTranslator.h" #include "vtkWidgetCallbackMapper.h" #include "vtkEvent.h" #include "vtkWidgetEvent.h" #include "vtkInteractorObserver.h" #include "vtkHandleWidget.h" #include "vtkPolyData.h" vtkCxxRevisionMacro(vtkKWEBoundingBoxWidget2D, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEBoundingBoxWidget2D); //---------------------------------------------------------------------- vtkKWEBoundingBoxWidget2D::vtkKWEBoundingBoxWidget2D() { this->ShowSliceScaleBar = 1; // 4 handles for the 4 corners of the box. this->HandleWidgets = new vtkHandleWidget* [6]; for (int i=0; i<6; i++) { this->HandleWidgets[i] = vtkHandleWidget::New(); this->HandleWidgets[i]->SetParent(this); // We will decide what cursor to show. this->HandleWidgets[i]->ManagesCursorOff(); } // Define widget events this->CallbackMapper->SetCallbackMethod( vtkCommand::LeftButtonPressEvent, vtkEvent::NoModifier, 0, 0, NULL, 101001, this, vtkKWEBoundingBoxWidget2D::OnLeftButtonDownCallback); this->CallbackMapper->SetCallbackMethod( vtkCommand::LeftButtonReleaseEvent, vtkEvent::NoModifier, 0, 0, NULL, 101002, this, vtkKWEBoundingBoxWidget2D::OnLeftButtonUpCallback); this->CallbackMapper->SetCallbackMethod( vtkCommand::MouseMoveEvent, vtkEvent::NoModifier, 0, 1, NULL, vtkWidgetEvent::Move, this, vtkKWEBoundingBoxWidget2D::OnMouseMoveCallback); for (int i = 0; i < 6; i++) { this->LastComputedBounds[i] = 0.0; this->LastComputedExtent[i] = 0; } this->SetPriority( 0.5 ); // default } //---------------------------------------------------------------------- vtkKWEBoundingBoxWidget2D::~vtkKWEBoundingBoxWidget2D() { for (int i=0; i<6; i++) { this->HandleWidgets[i]->Delete(); } delete [] this->HandleWidgets; } //---------------------------------------------------------------------- void vtkKWEBoundingBoxWidget2D::CreateDefaultRepresentation() { if ( !this->WidgetRep ) { this->WidgetRep = vtkKWEBoundingBoxRepresentation2D::New(); this->WidgetRep->SetRenderer(this->CurrentRenderer); } } //---------------------------------------------------------------------- void vtkKWEBoundingBoxWidget2D ::SetRepresentation( vtkKWEBoundingBoxRepresentation2D * rep ) { this->Superclass::SetWidgetRepresentation( rep ); } //---------------------------------------------------------------------- void vtkKWEBoundingBoxWidget2D::SetEnabled(int enabling) { if ( enabling ) //---------------- { vtkDebugMacro(<<"Enabling widget"); if ( this->Enabled ) //already enabled, just return { return; } if ( ! this->Interactor ) { vtkErrorMacro(<<"The interactor must be set prior to enabling the widget"); return; } int X=this->Interactor->GetEventPosition()[0]; int Y=this->Interactor->GetEventPosition()[1]; if ( ! this->CurrentRenderer ) { this->SetCurrentRenderer(this->Interactor->FindPokedRenderer(X,Y)); if (this->CurrentRenderer == NULL) { return; } } // We're ready to enable this->Enabled = 1; this->CreateDefaultRepresentation(); this->WidgetRep->SetRenderer(this->CurrentRenderer); // listen for the events found in the EventTranslator if ( ! this->Parent ) { this->EventTranslator->AddEventsToInteractor(this->Interactor, this->EventCallbackCommand,this->Priority); } else { this->EventTranslator->AddEventsToParent(this->Parent, this->EventCallbackCommand,this->Priority); } // Enable each of the handle widgets. for(int i=0; i< 4; i++) { if(this->HandleWidgets[i]) { this->HandleWidgets[i]->SetRepresentation( vtkKWEBoundingBoxRepresentation2D::SafeDownCast (this->WidgetRep)->GetHandleRepresentation(i)); this->HandleWidgets[i]->SetInteractor(this->Interactor); this->HandleWidgets[i]->GetRepresentation()->SetRenderer( this->CurrentRenderer); this->HandleWidgets[i]->SetEnabled(enabling); } } // Enable the slice handle widgets this->SetEnabledStateOfSliceScaleBar(); if ( this->ManagesCursor ) { this->WidgetRep->ComputeInteractionState(X, Y); this->SetCursor(this->WidgetRep->GetInteractionState()); } this->WidgetRep->BuildRepresentation(); this->CurrentRenderer->AddViewProp(this->WidgetRep); this->WidgetRep->VisibilityOn(); this->InvokeEvent(vtkCommand::EnableEvent,NULL); } else //disabling------------------ { vtkDebugMacro(<<"Disabling widget"); if ( ! this->Enabled ) //already disabled, just return { return; } this->Enabled = 0; // don't listen for events any more if ( ! this->Parent ) { this->Interactor->RemoveObserver(this->EventCallbackCommand); } else { this->Parent->RemoveObserver(this->EventCallbackCommand); } // Disable each of the handle widgets. for(int i=0; i<4; i++) { if(this->HandleWidgets[i]) { this->HandleWidgets[i]->SetEnabled(enabling); } } // Disable the slice handle widgets this->SetEnabledStateOfSliceScaleBar(); this->CurrentRenderer->RemoveViewProp(this->WidgetRep); this->WidgetRep->VisibilityOff(); this->InvokeEvent(vtkCommand::DisableEvent,NULL); this->SetCurrentRenderer(NULL); } // Should only render if there is no parent if ( this->Interactor && !this->Parent ) { this->Interactor->Render(); } } //---------------------------------------------------------------------- void vtkKWEBoundingBoxWidget2D::SetEnabledStateOfSliceScaleBar() { if (this->ShowSliceScaleBar && this->Enabled) { // Enable each of the handle widgets. for(int i=4; i< 6; i++) { if(this->HandleWidgets[i]) { this->HandleWidgets[i]->SetRepresentation( vtkKWEBoundingBoxRepresentation2D::SafeDownCast (this->WidgetRep)->GetHandleRepresentation(i)); this->HandleWidgets[i]->SetInteractor(this->Interactor); this->HandleWidgets[i]->GetRepresentation()->SetRenderer( this->CurrentRenderer); this->HandleWidgets[i]->SetEnabled(1); } } } else if (!this->ShowSliceScaleBar && !this->Enabled) { // Disable each of the handle widgets. for(int i=4; i<6; i++) { if(this->HandleWidgets[i]) { this->HandleWidgets[i]->SetEnabled(0); } } } else { return; } if (vtkKWEBoundingBoxRepresentation2D *rep = static_cast< vtkKWEBoundingBoxRepresentation2D *>(this->WidgetRep)) { rep->SetShowSliceScaleBar(this->ShowSliceScaleBar); } } //---------------------------------------------------------------------- void vtkKWEBoundingBoxWidget2D::SetShowSliceScaleBar(int i) { if (i == this->ShowSliceScaleBar) { return; } this->ShowSliceScaleBar = i; this->Modified(); this->SetEnabledStateOfSliceScaleBar(); } //---------------------------------------------------------------------- void vtkKWEBoundingBoxWidget2D::OnLeftButtonDownCallback(vtkAbstractWidget *w) { vtkKWEBoundingBoxWidget2D *self = reinterpret_cast(w); vtkKWEBoundingBoxRepresentation2D*rep = reinterpret_cast(self->WidgetRep); if (rep->GetUnplaced()) { // Not yet been placed. We should try to define the widget. rep->SetInteractionState( vtkKWEBoundingBoxRepresentation2D::BeginDefining ); } else { // The widget has been placed. We are probably trying to select a handle. // Lets make a request on the representation and see if we are close to one. rep->SetInteractionState( vtkKWEBoundingBoxRepresentation2D::RequestResizeBox ); } // Let the representation compute itself. int interactionState = rep->ComputeInteractionState( self->Interactor->GetEventPosition()[0], self->Interactor->GetEventPosition()[1] ); self->SetCursor(interactionState); if (interactionState != vtkKWEBoundingBoxRepresentation2D::Outside) { // Render ourself. self->EventCallbackCommand->SetAbortFlag(1); self->StartInteraction(); self->InvokeEvent(vtkCommand::StartInteractionEvent, NULL); self->Interactor->Render(); } } //---------------------------------------------------------------------- void vtkKWEBoundingBoxWidget2D::OnLeftButtonUpCallback(vtkAbstractWidget *w) { vtkKWEBoundingBoxWidget2D *self = reinterpret_cast(w); vtkKWEBoundingBoxRepresentation2D *rep = reinterpret_cast(self->WidgetRep); int interactionState = rep->GetInteractionState(); // If we are defining, end that. if (interactionState == vtkKWEBoundingBoxRepresentation2D::Defining) { rep->SetInteractionState(vtkKWEBoundingBoxRepresentation2D::EndDefining); if (rep->ComputeInteractionState( self->Interactor->GetEventPosition()[0], self->Interactor->GetEventPosition()[1] ) == vtkKWEBoundingBoxRepresentation2D::EndDefining ) { // Still in EndDefining state. Something surely went wrong, such as the // user trying to place handles out of the bounds etc... // Go back to BeginDefining state. self->Interactor->Render(); return; } } int extent[6]; double bounds[6]; rep->GetExtent(extent); rep->GetPolyData()->GetBounds(bounds); // Reset and render ourself. if (interactionState != vtkKWEBoundingBoxRepresentation2D::Outside && interactionState != vtkKWEBoundingBoxRepresentation2D::BeginDefining) { rep->SetInteractionState( vtkKWEBoundingBoxRepresentation2D::Outside ); self->Interactor->Render(); self->SetCursor(vtkKWEBoundingBoxRepresentation2D::Outside); self->InvokeEvent(vtkCommand::EndInteractionEvent, NULL); } if (bounds[0] != self->LastComputedBounds[0] || bounds[1] != self->LastComputedBounds[1] || bounds[2] != self->LastComputedBounds[2] || bounds[3] != self->LastComputedBounds[3] || bounds[4] != self->LastComputedBounds[4] || bounds[5] != self->LastComputedBounds[5] ) { self->InvokeEvent( vtkKWEBoundingBoxWidget2D::BoundsChangedEvent, bounds ); if (extent[0] != self->LastComputedExtent[0] || extent[1] != self->LastComputedExtent[1] || extent[2] != self->LastComputedExtent[2] || extent[3] != self->LastComputedExtent[3] || extent[4] != self->LastComputedExtent[4] || extent[5] != self->LastComputedExtent[5] ) { self->InvokeEvent( vtkKWEBoundingBoxWidget2D::ExtentsChangedEvent, extent ); } for (int i = 0; i < 6; i++) { self->LastComputedBounds[i] = bounds[i]; self->LastComputedExtent[i] = extent[i]; } self->EventCallbackCommand->SetAbortFlag(1); self->Interactor->Render(); } } //---------------------------------------------------------------------- void vtkKWEBoundingBoxWidget2D::OnMouseMoveCallback(vtkAbstractWidget *w) { vtkKWEBoundingBoxWidget2D *self = reinterpret_cast(w); vtkKWEBoundingBoxRepresentation2D*rep = reinterpret_cast(self->WidgetRep); int interactionState = rep->GetInteractionState(); // Let the representation re-compute what the appropriate state is. int newInteractionState = rep->ComputeInteractionState( self->Interactor->GetEventPosition()[0], self->Interactor->GetEventPosition()[1] ); // If we computed a different interaction state than the one we were in, // render in response to any changes. Also take care of trivial cases that // require no rendering. if (newInteractionState != interactionState || (newInteractionState != vtkKWEBoundingBoxRepresentation2D::Inside && newInteractionState != vtkKWEBoundingBoxRepresentation2D::Outside )) { self->Interactor->Render(); self->SetCursor(newInteractionState); self->InvokeEvent(vtkCommand::InteractionEvent, NULL); } } //------------------------------------------------------------------------- void vtkKWEBoundingBoxWidget2D::SetCursor(int state) { switch (state) { case vtkKWEBoundingBoxRepresentation2D::Resizing: this->RequestCursorShape(VTK_CURSOR_HAND); break; default: this->RequestCursorShape(VTK_CURSOR_ARROW); } } //---------------------------------------------------------------------------- void vtkKWEBoundingBoxWidget2D::SetProcessEvents(int pe) { this->Superclass::SetProcessEvents(pe); for (int i=0; i<6; i++) { this->HandleWidgets[i]->SetProcessEvents(pe); } } //---------------------------------------------------------------------------- void vtkKWEBoundingBoxWidget2D::SetFade( int f ) { if (f == 1) { this->SetProcessEvents(0); } vtkKWEBoundingBoxRepresentation2D *rep = static_cast(this->WidgetRep); rep->SetFade(f); } //---------------------------------------------------------------------------- int vtkKWEBoundingBoxWidget2D::GetFade() { vtkKWEBoundingBoxRepresentation2D *rep = static_cast(this->WidgetRep); return rep->GetFade(); } //---------------------------------------------------------------------- void vtkKWEBoundingBoxWidget2D::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushMergeSketches.cxx0000644000175000017500000002041611363410610024055 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushMergeSketches.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkObjectFactory.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkExecutive.h" #include "vtkAlgorithmOutput.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushUtilities.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushPropertyManager.h" vtkCxxRevisionMacro(vtkKWEPaintbrushMergeSketches, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEPaintbrushMergeSketches); //---------------------------------------------------------------------------- vtkKWEPaintbrushMergeSketches::vtkKWEPaintbrushMergeSketches() { this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(1); } //---------------------------------------------------------------------------- vtkKWEPaintbrushMergeSketches::~vtkKWEPaintbrushMergeSketches() { } //---------------------------------------------------------------------------- void vtkKWEPaintbrushMergeSketches:: PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushMergeSketches ::RequestData( vtkInformation *, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkInformation *info = inputVector[0]->GetInformationObject(0); vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkKWEPaintbrushDrawing *inputDrawing = vtkKWEPaintbrushDrawing::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); vtkKWEPaintbrushDrawing *outputDrawing = vtkKWEPaintbrushDrawing::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); outputDrawing->SetRepresentation( inputDrawing->GetRepresentation() ); outputDrawing->SetImageData( inputDrawing->GetImageData() ); outputDrawing->SetPaintbrushOperation( inputDrawing->GetPaintbrushOperation() ); outputDrawing->InitializeData(); outputDrawing->RemoveAllItems(); outputDrawing->GetPaintbrushPropertyManager()->SetHighlightType( inputDrawing->GetPaintbrushPropertyManager()->GetHighlightType() ); // Sanity check. if (inputDrawing->GetNumberOfItems() == 0) { // No sketches.. just return. return 1; } if (inputDrawing->GetNumberOfItems() == 1) { // Just 1 sketch. Nothing to merge with. outputDrawing->AddItem( inputDrawing->GetItem(0) ); return 1; } // The output data vtkKWEPaintbrushData * data = NULL; if (inputDrawing->GetRepresentation() == vtkKWEPaintbrushEnums::Binary) { vtkKWEPaintbrushStencilData *sdata = vtkKWEPaintbrushStencilData::New(); data = sdata; } else if (inputDrawing->GetRepresentation() == vtkKWEPaintbrushEnums::Grayscale) { vtkKWEPaintbrushGrayscaleData *sdata = vtkKWEPaintbrushGrayscaleData::New(); data = sdata; } data->SetExtent( inputDrawing->GetImageData()->GetExtent() ); data->SetSpacing( inputDrawing->GetImageData()->GetSpacing() ); data->SetOrigin( inputDrawing->GetImageData()->GetOrigin() ); data->Allocate(); for (int n = 0; n < inputDrawing->GetNumberOfItems(); n++) { data->Add( inputDrawing->GetItem(n)->GetPaintbrushData() ); } vtkKWEPaintbrushSketch *sketch = outputDrawing->AddItem(); sketch->AddNewStroke( vtkKWEPaintbrushEnums::Draw, data ); data->Delete(); // Copy over some default properties from the input drawing. vtkKWEPaintbrushProperty *inputProperty = inputDrawing->GetItem(0)->GetPaintbrushProperty(); vtkKWEPaintbrushProperty *outputProperty = sketch->GetPaintbrushProperty(); outputProperty->SetHighlightColor( inputProperty->GetHighlightColor() ); outputProperty->SetHighlightType( inputProperty->GetHighlightType() ); outputProperty->SetOpacity( inputProperty->GetOpacity() ); return 1; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushMergeSketches:: FillInputPortInformation(int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkKWEPaintbrushDrawing"); return 1; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushMergeSketches::FillOutputPortInformation( int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkKWEPaintbrushDrawing"); return 1; } //---------------------------------------------------------------------------- // This method returns the largest region that can be generated. void vtkKWEPaintbrushMergeSketches::RequestInformation ( vtkInformation * vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector *outputVector) { vtkInformation *info = inputVector[0]->GetInformationObject(0); vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkKWEPaintbrushDrawing *inputDrawing = vtkKWEPaintbrushDrawing::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); // set the extent int wExtent[6]; inputDrawing->GetImageData()->GetExtent( wExtent ); outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wExtent, 6); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushMergeSketches:: ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // create the output if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA_OBJECT())) { return this->RequestDataObject(request, inputVector, outputVector); } // generate the data if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) { this->RequestData(request, inputVector, outputVector); return 1; } // execute information if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION())) { this->RequestInformation(request, inputVector, outputVector); return 1; } return this->Superclass::ProcessRequest(request, inputVector, outputVector); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushMergeSketches::RequestDataObject( vtkInformation*, vtkInformationVector** inputVector , vtkInformationVector* outputVector) { vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); if (!inInfo) { return 0; } vtkDataObject *input = inInfo->Get(vtkDataObject::DATA_OBJECT()); if (input) { // for each output for(int i=0; i < this->GetNumberOfOutputPorts(); ++i) { vtkInformation* info = outputVector->GetInformationObject(i); vtkDataObject *output = info->Get(vtkDataObject::DATA_OBJECT()); if (!output || !output->IsA(input->GetClassName())) { vtkDataObject* newOutput = input->NewInstance(); newOutput->SetPipelineInformation(info); newOutput->Delete(); this->GetOutputPortInformation(0)->Set( vtkDataObject::DATA_EXTENT_TYPE(), newOutput->GetExtentType()); } } return 1; } return 0; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushMergeSketches:: SetInput(vtkKWEPaintbrushDrawing* input) { this->SetInputConnection(0,input->GetProducerPort()); } //---------------------------------------------------------------------------- vtkKWEPaintbrushDrawing* vtkKWEPaintbrushMergeSketches::GetOutput() { return vtkKWEPaintbrushDrawing::SafeDownCast(this->GetOutputDataObject(0)); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushRepresentation.h0000644000175000017500000002210611504122432023750 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushRepresentation - An abstract base class for 2D/3D paintbrush widget representations // .SECTION Description // See vtkKWEPaintbrushRepresentation2D for more details. // The ShapePlacer must be set prior to use. #ifndef __vtkKWEPaintbrushRepresentation_h #define __vtkKWEPaintbrushRepresentation_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkWidgetRepresentation.h" class vtkImageStencil; class vtkImageStencilData; class vtkTimeStamp; class vtkKWEPaintbrushDrawing; class vtkKWEPaintbrushOperation; class vtkKWEPaintbrushAnnotationRepresentation; class vtkKWEPaintbrushSelectionRepresentation; class vtkKWEPaintbrushSketch; class vtkPointPlacer; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushRepresentation : public vtkWidgetRepresentation { //BTX friend class vtkKWEPaintbrushAnnotationRepresentation; //ETX public: // Description: // Standard VTK methods. vtkTypeRevisionMacro(vtkKWEPaintbrushRepresentation,vtkWidgetRepresentation); void PrintSelf(ostream& os, vtkIndent indent); //BTX -- The representation can be set in two states by the widget. Draw/Erase enum { PaintbrushInteract, PaintbrushDraw, PaintbrushErase, PaintbrushResize, PaintbrushIsotropicResize, PaintbrushDisabled }; //ETX // Description: // These are methods that satisfy vtkWidgetRepresentation's API. virtual void BuildRepresentation()=0; virtual int ComputeInteractionState(int X, int Y, int modified=0)=0; virtual void StartWidgetInteraction(double e[2])=0; virtual void WidgetInteraction(double e[2])=0; // Description: // Set the Paintbrush sequencer virtual void SetPaintbrushDrawing( vtkKWEPaintbrushDrawing * ); vtkGetObjectMacro( PaintbrushDrawing, vtkKWEPaintbrushDrawing ); // Description: // Set the paintbrush operation. virtual void SetPaintbrushOperation( vtkKWEPaintbrushOperation * ); vtkGetObjectMacro( PaintbrushOperation, vtkKWEPaintbrushOperation ); // Description: // Set the Paintbrush representation state virtual void SetStateToDraw() { this->InteractionState = PaintbrushDraw; } virtual void SetStateToErase() { this->InteractionState = PaintbrushErase; } virtual void SetStateToInteract() { this->InteractionState = PaintbrushInteract; } virtual void SetStateToResize() { this->InteractionState = PaintbrushResize; } virtual void SetStateToDisabled() { this->InteractionState = PaintbrushDisabled; } virtual void SetStateToIsotropicResize() { this->InteractionState = PaintbrushIsotropicResize; } // Description: // Start a new sketch. virtual int BeginNewSketch(); // Description: // Methods to jump to a certain sketch. // Returns 0 if the jump was unsuccessful, (if you try to jump outside the // available sketches etc). virtual int GoToSketch( int n ); virtual int IncrementSketch(); virtual int DecrementSketch(); // Description: // Get the sketch being currently edited. int GetSketchIndex(); // Description: // Start a new stroke. virtual int BeginNewStroke(); // Description: // Remove the last stroke. Will work only if there is a stroke in the list virtual int UndoStroke(); virtual int RemoveLastStroke(); virtual int RedoStroke(); // Description: // Remove an entire sketch from the drawing. Returns 1 if successful. Note // that this may cause the SketchIndex to decrement, if the index of the // currently active sketch is higher than the one being deleted. You can // query this value by calling GetSketchIndex(). virtual int RemoveSketch( vtkKWEPaintbrushSketch * s ); // Descirption: // Set / get the Point Placer. The point placer is responsible for // converting display coordinates into world coordinates according // to some constraints, and for validating world positions. // By writing an appopriate point placer, you can toggle the visibiliy // of the templates based on display position, have it snap to the // image grid etc.. void SetShapePlacer( vtkPointPlacer * ); vtkGetObjectMacro( ShapePlacer, vtkPointPlacer ); // Descirption: // This method is meant to be invoked from vtkKWEPaintbrushWidget during user // interaction. // Resize the shape. The value passed is a factor that determines how much // to resize. Its up to the shape to use this factor appropriately. // See vtkKWEPaintbrushShape::PaintbrushResizeEnum for possible resizeTypes. // Returns 1 if a resize happened (you need to re-render), 0 otherwise.. virtual int ResizeShape( double d[3], int resizeType ) = 0; // Descirption: // Get the current position of the center of the shape. vtkGetVector3Macro(CurrentShapePosition, double); // Descirption: // Deep copy.. synchronizes states etc.. virtual void DeepCopy(vtkWidgetRepresentation *); // Description: // Check if display point (x,y) is inside the paintable region of the canvas. // The ShapePlacer can be used to dictate which location in the canvas the // shape can etch on. You can very easily restrict drawing to certain // region simply by writing an appropriate point placer. (See vtkPointPlacer) virtual int IsInsideCanvas( int displayPos[2] ); // Description: // Get the annotation representation. This displays timer based informative // annotations vtkGetObjectMacro( Annotation, vtkKWEPaintbrushAnnotationRepresentation ); // Description: // Get the selection widget's representation. This is used if the paintbrush // is in selection mode. vtkGetObjectMacro( SelectionRepresentation, vtkKWEPaintbrushSelectionRepresentation ); // Description: // INTERNAL - Do not use. // Add a shape centered at "p" to the currently active sketch's current // stroke. This method is called by the widget whenever we interactively // trace. virtual void AddShapeToCurrentStroke( double p[3] ); // Description: // INTERNAL - Do not use // Invoked by the widget in response to user interaction // Activate the template outline and the supplied coordinate // according to the constraints of the placer ? virtual int ActivateShapeOutline( int X, int Y ) = 0; // Description: // INTERNAL - Do not use // Invoked by the widget in response to user interaction // Create a shape outline at the current shape position. Does not check the // placer for constraints. virtual void CreateShapeOutline(double *pos) = 0; // Description: // INTERNAL - Do not use. // Invoked by the widget in response to user interaction // Turn on/off the hovering shape outline visibility virtual void SetShapeOutlineVisibility( int ) = 0; virtual int GetShapeOutlineVisibility( ) = 0; // Description: // INTERNAL - Do not use. // Invoked by the widget in response to user interaction // Increase / Decrease the opacity of the drawing. virtual int IncreaseOpacity() { return 0; } virtual int DecreaseOpacity() { return 0; } // Description: // INTERNAL - Do not use. virtual void InstallPipeline(); virtual void UnInstallPipeline(); protected: vtkKWEPaintbrushRepresentation(); ~vtkKWEPaintbrushRepresentation(); vtkKWEPaintbrushOperation *PaintbrushOperation; vtkKWEPaintbrushDrawing *PaintbrushDrawing; // Description: // The point placer determines the world coordinate based on screen // coordinate and allows you to set constraints too.. It can also // be used to toggle the template visibility depending on the position // if you write an appropriate subclass of the point placer. One // such subclass snaps the contour to regular positions on the image // grid. vtkPointPlacer * ShapePlacer; // Description: // Displays timer based informative annotations vtkKWEPaintbrushAnnotationRepresentation * Annotation; // Description: // The selection widget's representation. This is used if the paintbrush // is in selection mode. vtkKWEPaintbrushSelectionRepresentation * SelectionRepresentation; // Description: // Bookkeeping of the last display position. int LastDisplayPosition[2]; double CurrentShapePosition[3]; int SketchIndex; // We can manage multiple sketches. int ShapeOutlineVisibility; int PipelineInstalled; // Description: // Get the extents of the current etch. virtual void GetEtchExtents( int extent[6] ); private: vtkKWEPaintbrushRepresentation(const vtkKWEPaintbrushRepresentation&); //Not implemented void operator=(const vtkKWEPaintbrushRepresentation&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEITKConfidenceConnectedImageFilter.txx0000644000175000017500000000646111363410610025652 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEITKConfidenceConnectedImageFilter.h" #include "itkNumericTraits.h" #include "vtkKWEITKFilterModuleStencilOutput.h" namespace vtkitk { template< class InputPixelType > vtkKWEITKConfidenceConnectedImageFilter< InputPixelType > ::vtkKWEITKConfidenceConnectedImageFilter() { this->m_Filter = new FilterModuleStencilOutput< FilterType >(); } template< class InputPixelType > vtkKWEITKConfidenceConnectedImageFilter< InputPixelType > ::~vtkKWEITKConfidenceConnectedImageFilter() { delete this->m_Filter; } template< class InputPixelType > void vtkKWEITKConfidenceConnectedImageFilter< InputPixelType > ::AddSeed( int seed[3] ) { IndexType index; index[0] = seed[0]; index[1] = seed[1]; index[2] = seed[2]; FilterModuleStencilOutput< FilterType > * f = (dynamic_cast< FilterModuleStencilOutput< FilterType > * >(this->m_Filter)); if (!f) { itkExceptionMacro( << "dynamic cast returned false.. impossible!"); } FilterType *filter = f->GetFilter(); filter->GetRegionGrowingFilter()->AddSeed(index); } template< class InputPixelType > void vtkKWEITKConfidenceConnectedImageFilter< InputPixelType > ::Update() { this->Superclass::Update(); FilterModuleStencilOutput< FilterType > * f = (dynamic_cast< FilterModuleStencilOutput< FilterType > * >(this->m_Filter)); if (!f) { itkExceptionMacro( << "dynamic cast returned false.. impossible!"); } FilterType *filter = f->GetFilter(); // Override the propagation of extents.. the voting filters require that // the input be 1/2 the structuring element size larger on each side. // So we will shrink the output extents appropriately. if (filter->GetUseHoleFilling()) { typename InputImageType::SizeType radius = filter->GetHoleFillingFilter()->GetRadius(); int extent[6]; memcpy(extent, this->m_Extent, 6*sizeof(int)); extent[0] += radius[0]; extent[2] += radius[1]; extent[4] += radius[2]; extent[1] -= radius[0]; extent[3] -= radius[1]; extent[5] -= radius[2]; if (extent[0] > extent[1] || extent[2] > extent[3] || extent[4] > extent[5]) { // The extracted region on which region growing is being done is // too small to be shrunk any further.. turn holefilling off. filter->UseHoleFillingOff(); } else { memcpy(this->m_Extent, extent, 6*sizeof(int)); this->m_Filter->SetRequestedExtent(this->m_Extent); } } // Update the filter.. If any timing analysis needs to be done.. // This method needs to be interactive enough. f->Update(); } } // end namespace vtkitk vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushSelectionRepresentation.h0000644000175000017500000001355411363410610025626 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushSelectionRepresentation - // .SECTION Description #ifndef __vtkKWEPaintbrushSelectionRepresentation_h #define __vtkKWEPaintbrushSelectionRepresentation_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkWidgetRepresentation.h" #include class vtkKWEPaintbrushDrawing; class vtkPointPlacer; class vtkKWEPaintbrushSketch; class vtkKWEPaintbrushSelectionWidget; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushSelectionRepresentation : public vtkWidgetRepresentation { //BTX friend class vtkKWEPaintbrushSelectionWidget; //ETX public: // Description: // Standard VTK methods. vtkTypeRevisionMacro( vtkKWEPaintbrushSelectionRepresentation, vtkWidgetRepresentation); void PrintSelf(ostream& os, vtkIndent indent); //BTX -- States the representation can set itself into enum { PaintbrushRequestSketchSelect, PaintbrushSketchSelect, PaintbrushSketchUnselect, PaintbrushRequestSketchMerge, PaintbrushSketchMerge, PaintbrushDisabled, None }; //ETX // Description: // These are methods that satisfy vtkWidgetRepresentation's API. virtual int ComputeInteractionState(int X, int Y, int modifier=0); // Description: // Set the Paintbrush drawing virtual void SetPaintbrushDrawing( vtkKWEPaintbrushDrawing * ); vtkGetObjectMacro( PaintbrushDrawing, vtkKWEPaintbrushDrawing ); // Descirption: // Set / get the Point Placer. The point placer is responsible for // converting display coordinates into world coordinates according // to some constraints, and for validating world positions. // By writing an appopriate point placer, you can disable/enable selection // on regions in world space. void SetPointPlacer( vtkPointPlacer * ); vtkGetObjectMacro( PointPlacer, vtkPointPlacer ); // Descirption: // Deep copy.. synchronizes states etc.. virtual void DeepCopy(vtkWidgetRepresentation *); // Description: // Check if display point is inside the sketch "s". virtual int DisplayPositionIsInside( vtkKWEPaintbrushSketch *s, double displayPos[2]); // Description: // Check if world point is inside the sketch "s". virtual int WorldPositionIsInside( vtkKWEPaintbrushSketch *s, double worldPos[3]); // Description: // Check if display position is inside the drawing and return the first // drawing that falls within the display position. Returns NULL if the // position doesn't lie on any sketch in the drawing. //virtual vtkKWEPaintbrushSketch* DisplayPositionIsInside( double displayPos[2] ); // Description: // Get the selected sketch. vtkGetObjectMacro( SelectedSketch, vtkKWEPaintbrushSketch ); // Description: // Add sketch to the list of selected sketches. virtual void AddSketchToSelection( vtkKWEPaintbrushSketch * ); // Description: // Remove sketch from the list of selected sketches. virtual void RemoveSketchFromSelection( vtkKWEPaintbrushSketch * ); // Description: // Deletes selected sketches. Returns the number of sketches removed. virtual int DeleteSelectedSketches(); // Description: // Select/UnSelect all the sketches in the drawing virtual void SelectAllSketches(); virtual void UnSelectAllSketches(); //BTX // Description: // Get the selected sketches. const vtkstd::vector< vtkKWEPaintbrushSketch * > & GetSelectedSketches() { return this->SelectedSketches; } //ETX // Description: // Merge the selected sketches. // You may specify a sketch, from the drawing, to merge into. If NULL, the // first selected sketch will contain the merge. // By default sketches merged are removed. The removeSketches ivar can be // used to control this. virtual int MergeSelectedSketches( vtkKWEPaintbrushSketch *mergedSketch = NULL, int removeSketches = 1 ); protected: vtkKWEPaintbrushSelectionRepresentation(); ~vtkKWEPaintbrushSelectionRepresentation(); // Description: // Set the interaction state. vtkSetMacro( InteractionState, int ); // Description: // Drag and drop merge support. Returns 1 if successful. virtual int DragAndDropMerge(); vtkKWEPaintbrushDrawing *PaintbrushDrawing; // Description: // The point placer determines the world coordinate based on screen // coordinate and allows you to set constraints too. vtkPointPlacer * PointPlacer; // Description: // Bookkeeping of the last display position. int LastDisplayPosition[2]; // Description: // The sketch just selected. vtkKWEPaintbrushSketch * SelectedSketch; // Description: // List of selected sketches. typedef vtkstd::vector< vtkKWEPaintbrushSketch * > SelectedSketchesType; SelectedSketchesType SelectedSketches; int PrevInteractionState; double DragBeginPoint[3], DragEndPoint[3]; vtkKWEPaintbrushSketch * DragAndDropDestination; private: vtkKWEPaintbrushSelectionRepresentation(const vtkKWEPaintbrushSelectionRepresentation&); //Not implemented void operator=(const vtkKWEPaintbrushSelectionRepresentation&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushOperationFloodFill.h0000644000175000017500000000342111363410610024501 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushOperationFloodFill - // .SECTION Description // .SECTION See Also #ifndef __vtkKWEPaintbrushOperationFloodFill_h #define __vtkKWEPaintbrushOperationFloodFill_h #include "vtkKWEPaintbrushOperation.h" class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushOperationFloodFill : public vtkKWEPaintbrushOperation { public: // Description: // Instantiate this class. static vtkKWEPaintbrushOperationFloodFill *New(); // Description: // Standard methods for instances of this class. vtkTypeRevisionMacro(vtkKWEPaintbrushOperationFloodFill, vtkKWEPaintbrushOperation); void PrintSelf(ostream& os, vtkIndent indent); protected: vtkKWEPaintbrushOperationFloodFill(); ~vtkKWEPaintbrushOperationFloodFill(); virtual void DoOperationOnStencil( vtkImageStencilData *, int x, int y, int z); private: vtkKWEPaintbrushOperationFloodFill(const vtkKWEPaintbrushOperationFloodFill&); //Not implemented void operator=(const vtkKWEPaintbrushOperationFloodFill&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/itkVTKImageToImageFilter.h0000644000175000017500000000661311363410610022353 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef __itkVTKImageToImageFilter_h #define __itkVTKImageToImageFilter_h #include "VTKEdgeConfigure.h" // Needed for export symbol def #include "itkVTKImageImport.h" #include "vtkImageExport.h" #include "vtkImageData.h" #ifndef vtkFloatingPointType #define vtkFloatingPointType float #endif namespace itk { /** \class VTKImageToImageFilter * \brief Converts a VTK image into an ITK image and plugs a * vtk data pipeline to an ITK datapipeline. * * This class puts together an itkVTKImageImporter and a vtkImageExporter. * It takes care of the details related to the connection of ITK and VTK * pipelines. The User will perceive this filter as an adaptor to which * a vtkImage can be plugged as input and an itk::Image is produced as * output. * * \ingroup ImageFilters */ template class ITK_EXPORT VTKImageToImageFilter : public ProcessObject { public: /** Standard class typedefs. */ typedef VTKImageToImageFilter Self; typedef ProcessObject Superclass; typedef SmartPointer Pointer; typedef SmartPointer ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(VTKImageToImageFilter, ProcessObject); /** Some typedefs. */ typedef TOutputImage OutputImageType; typedef typename OutputImageType::ConstPointer OutputImagePointer; typedef VTKImageImport< OutputImageType > ImporterFilterType; typedef typename ImporterFilterType::Pointer ImporterFilterPointer; /** Get the output in the form of a vtkImage. This call is delegated to the internal vtkImageImporter filter */ const OutputImageType * GetOutput() const; /** Set the input in the form of a vtkImageData */ void SetInput( vtkImageData * ); vtkImageData * GetInput(); /** Return the internal VTK image exporter filter. This is intended to facilitate users the access to methods in the exporter */ vtkImageExport * GetExporter() const; /** Return the internal ITK image importer filter. This is intended to facilitate users the access to methods in the importer */ ImporterFilterType * GetImporter() const; /** This call delegate the update to the importer */ void Update(); protected: VTKImageToImageFilter(); virtual ~VTKImageToImageFilter(); private: VTKImageToImageFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented ImporterFilterPointer m_Importer; vtkImageExport * m_Exporter; }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkVTKImageToImageFilter.txx" #endif #endif vtkedge-0.2.0~20110819/Widgets/itkConfidenceConnectedMiniPipelineFilter.txx0000644000175000017500000001631411363410610026254 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef __itkConfidenceConnectedMiniPipelineFilter_txx_ #define __itkConfidenceConnectedMiniPipelineFilter_txx_ #include "itkConfidenceConnectedMiniPipelineFilter.h" #include "itkProgressAccumulator.h" #include "itkNumericTraits.h" namespace itk { /** * Constructor */ template ConfidenceConnectedMiniPipelineFilter ::ConfidenceConnectedMiniPipelineFilter() { this->m_SmoothingFilter = SmoothingFilterType::New(); this->m_RegionGrowingFilter = RegionGrowingFilterType::New(); this->m_HoleFillingFilter = HoleFillingFilterType::New(); // Set up the pipeline this->m_SmoothingFilter->SetInput(this->GetInput()); this->m_RegionGrowingFilter->SetInput(this->m_SmoothingFilter->GetOutput()); this->m_HoleFillingFilter->SetInput(this->m_RegionGrowingFilter->GetOutput()); // Set up some default parameters of the pipeline filters // Smoothing filter params typename InputImageType::SizeType medianFilterRadius; medianFilterRadius.Fill(1); this->m_SmoothingFilter->SetRadius(medianFilterRadius); // 3 x 3 kernel // Region growing filter params this->m_RegionGrowingFilter->SetNumberOfIterations(2); this->m_RegionGrowingFilter->SetMultiplier(1.5); this->m_RegionGrowingFilter->SetInitialNeighborhoodRadius(1); this->m_RegionGrowingFilter->SetReplaceValue( itk::NumericTraits< typename OutputImageType::PixelType >::max() ); // Hole filling filter params typename InputImageType::SizeType holeFillingFilterRadius; holeFillingFilterRadius.Fill(2); this->m_HoleFillingFilter->SetRadius(holeFillingFilterRadius); this->m_HoleFillingFilter->SetBackgroundValue( itk::NumericTraits< typename OutputImageType::PixelType >::Zero ); this->m_HoleFillingFilter->SetForegroundValue( itk::NumericTraits< typename OutputImageType::PixelType >::max() ); this->m_HoleFillingFilter->SetMajorityThreshold(20); this->m_UseHoleFilling = true; } /** * Standard PrintSelf method. */ template void ConfidenceConnectedMiniPipelineFilter ::PrintSelf(std::ostream& os, Indent indent) const { this->Superclass::PrintSelf(os, indent); os << indent << "SmoothingFilter: " << std::endl; this->m_SmoothingFilter->Print(os,indent.GetNextIndent()); os << indent << "RegionGrowingFilter: " << std::endl; this->m_RegionGrowingFilter->Print(os,indent.GetNextIndent()); os << indent << "HoleFillingFilter: " << std::endl; this->m_HoleFillingFilter->Print(os,indent.GetNextIndent()); if (this->m_UseHoleFilling) { os << indent << "UseHoleFilling: On" << std::endl; } else { os << indent << "UseHoleFilling: Off" << std::endl; } } template void ConfidenceConnectedMiniPipelineFilter ::GenerateInputRequestedRegion() { Superclass::GenerateInputRequestedRegion(); // Why am I setting the region to largest possible region ? // Because the region growing filters in ITK do that. // Why do the region growing filters in ITK do that ? // I don't know. if ( this->GetInput() ) { typename InputImageType::Pointer image = const_cast< TInputImage * >( this->GetInput() ); image->SetRequestedRegionToLargestPossibleRegion(); } } template void ConfidenceConnectedMiniPipelineFilter ::GenerateOutputInformation() { Superclass::GenerateOutputInformation(); if (!this->m_UseHoleFilling) { return; } const TInputImage * inputPtr = this->GetInput(); if( !inputPtr ) { return; } // If we use holefilling, the voting filters require that // the input be 1/2 the structuring element size larger on each side. // So we will shrink the output typename OutputImageType::RegionType outputRegion; typename OutputImageType::SizeType sz; typename OutputImageType::IndexType idx; typename InputImageType::SizeType input_sz = inputPtr->GetLargestPossibleRegion().GetSize(); typename InputImageType::IndexType input_idx = inputPtr->GetLargestPossibleRegion().GetIndex(); idx = input_idx + this->m_HoleFillingFilter->GetRadius(); sz = input_sz - this->m_HoleFillingFilter->GetRadius(); sz = sz - this->m_HoleFillingFilter->GetRadius(); outputRegion.SetSize(sz); outputRegion.SetIndex(idx); this->GetOutput()->SetLargestPossibleRegion(outputRegion); } template void ConfidenceConnectedMiniPipelineFilter ::GenerateData() { // Allocate the output this->AllocateOutputs(); this->m_SmoothingFilter->SetInput(this->GetInput()); // Create a process accumulator for tracking the progress of this // minipipeline ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); progress = ProgressAccumulator::New(); progress->SetMiniPipelineFilter(this); progress->RegisterInternalFilter( this->m_SmoothingFilter, 1.0/3.0); progress->RegisterInternalFilter( this->m_RegionGrowingFilter, 1.0/3.0); progress->RegisterInternalFilter( this->m_HoleFillingFilter, 1.0/3.0); progress->ResetProgress(); // Graft this filter's output to the mini-pipeline. this sets up // the mini-pipeline to write to this filter's output and copies // region ivars and meta-data if (this->m_UseHoleFilling) { this->m_HoleFillingFilter->GraftOutput(this->GetOutput()); this->m_HoleFillingFilter->Update(); } else { this->m_RegionGrowingFilter->GraftOutput(this->GetOutput()); this->m_RegionGrowingFilter->Update(); } } template typename ConfidenceConnectedMiniPipelineFilter< TInputImage,TOutputImage>::SmoothingFilterType * ConfidenceConnectedMiniPipelineFilter ::GetSmoothingFilter() { return this->m_SmoothingFilter.GetPointer(); } template typename ConfidenceConnectedMiniPipelineFilter< TInputImage,TOutputImage>::RegionGrowingFilterType * ConfidenceConnectedMiniPipelineFilter ::GetRegionGrowingFilter() { return this->m_RegionGrowingFilter.GetPointer(); } template typename ConfidenceConnectedMiniPipelineFilter< TInputImage,TOutputImage>::HoleFillingFilterType * ConfidenceConnectedMiniPipelineFilter ::GetHoleFillingFilter() { return this->m_HoleFillingFilter.GetPointer(); } } // end namespace itk #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushDrawingStatistics.h0000644000175000017500000000605711502655425024436 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushDrawingStatistics - Compute volume of sketches in a drawing // .SECTION Description // Takes a drawing as input. // .SECTION See Also #ifndef __vtkKWEPaintbrushDrawingStatistics_h #define __vtkKWEPaintbrushDrawingStatistics_h #include "vtkAlgorithm.h" #include "VTKEdgeConfigure.h" #include "vtkKWEPaintbrushEnums.h" #include class vtkKWEPaintbrushDrawing; class vtkKWEPaintbrushSketch; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushDrawingStatistics : public vtkAlgorithm { public: // Description: // Standard VTK methods. static vtkKWEPaintbrushDrawingStatistics *New(); vtkTypeRevisionMacro(vtkKWEPaintbrushDrawingStatistics, vtkAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set a paintbrush drawing as input virtual void SetInput( vtkKWEPaintbrushDrawing * ); // Description: // see vtkAlgorithm for details virtual int ProcessRequest(vtkInformation*, vtkInformationVector**, vtkInformationVector*); // Description: // Get the volume of the drawing. This will the sum of the volumes of all // the sketches in the drawing double GetVolume(); // Description: // Get the volume of the n'th sketch in the drawing. double GetVolume( int n ); // Description: // Get the volume of this sketch in the drawing double GetVolume( vtkKWEPaintbrushSketch * ); // Description: // Get the volume of the sketch with this label double GetLabelVolume( vtkKWEPaintbrushEnums::LabelType ); // Description: // Get the input to this filter vtkKWEPaintbrushDrawing * GetDrawing(); protected: vtkKWEPaintbrushDrawingStatistics(); ~vtkKWEPaintbrushDrawingStatistics(); // Description: // see vtkAlgorithm for docs. virtual int FillInputPortInformation(int, vtkInformation*); virtual int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); vtkstd::vector< double > Volumes; double Volume; unsigned long * VolumesArray; unsigned long MaximumLabelValue; private: vtkKWEPaintbrushDrawingStatistics( const vtkKWEPaintbrushDrawingStatistics& ); void operator=(const vtkKWEPaintbrushDrawingStatistics&); }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEITKPaintbrushOperation.cxx0000644000175000017500000000270411363410610023634 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEITKPaintbrushOperation.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkKWEITKPaintbrushOperation, "$Revision: 1774 $"); //---------------------------------------------------------------------- vtkKWEITKPaintbrushOperation::vtkKWEITKPaintbrushOperation() { this->InternalFilter = NULL; this->FilterHalfWidth[0] = 10; this->FilterHalfWidth[1] = 10; this->FilterHalfWidth[2] = 10; } //---------------------------------------------------------------------- vtkKWEITKPaintbrushOperation::~vtkKWEITKPaintbrushOperation() { } //---------------------------------------------------------------------- void vtkKWEITKPaintbrushOperation::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEITKPaintbrushFilterModule.h0000644000175000017500000001107311363410610023713 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef _vtkKWEITKPaintbrushFilterModule_h #define _vtkKWEITKPaintbrushFilterModule_h #include "vtkKWEITKFilterModule.h" namespace vtkitk { template class PaintbrushFilterModule : public FilterModule< TFilterType > { public: // Instantiate the image types typedef typename Superclass::FilterType FilterType; typedef typename Superclass::InputImageType InputImageType; typedef typename Superclass::OutputImageType OutputImageType; typedef typename Superclass::PixelType InputPixelType; typedef typename Superclass::PixelType OutputPixelType; typedef typename Superclass::SizeType SizeType; typedef typename Superclass::IndexType IndexType; typedef typename Superclass::RegionType RegionType; /** Constructor */ FilterModule() { this->m_ImportFilter = ImportFilterType::New(); this->m_ExportFilter = ExportFilterType::New(); this->m_Filter = FilterType::New(); this->m_Filter->ReleaseDataFlagOn(); this->m_Filter->SetInput( this->m_ImportFilter->GetOutput() ); this->m_ExportFilter->SetInput( this->m_Filter->GetOutput() ); // Set the Observer for updating progress in the GUI this->m_Filter->AddObserver( itk::ProgressEvent(), this->GetCommandObserver() ); this->m_Filter->AddObserver( itk::StartEvent(), this->GetCommandObserver() ); this->m_Filter->AddObserver( itk::EndEvent(), this->GetCommandObserver() ); this->m_LetITKAllocateOutputMemory = false; } /** Destructor */ virtual ~FilterModule() { } /** Give access to the input image */ void SetInput(vtkImageData * image) { this->m_ImportFilter->SetInput(image); } /** Give access to the input image */ const InputImageType * GetInput() { this->m_ImportFilter->Update(); return this->m_ImportFilter->GetOutput(); } /** Return a pointer to the internal filter */ FilterType * GetFilter() { return this->m_Filter.GetPointer(); } void SetLetITKAllocateOutputMemory(bool s) { this->m_LetITKAllocateOutputMemory = s; } // FIXME: We are so busted when doing this for multi-component data. // It won't even frickin compile. void SetOutputBuffer( void * buffer ) { this->m_LetITKAllocateOutputMemory = false; RegionType region = this->m_Filter->GetOutput()->GetLargestPossibleRegion(); const unsigned long nPixels = region.GetNumberOfPixels(); this->m_Filter->GetOutput()->SetImportPointer( static_cast< OutputPixelType * >(buffer), nPixels ); this->m_Filter->GetOutput()->Allocate( ); // TODO Check if necessary } void SetOutputRegion( RegionType region ) { this->m_Filter->GetOutput()->SetRegions( region ); } /** Update performs the actual filtering on the data */ virtual void Update( const vtkVVProcessDataStruct * pds ) { // Progress reporting this->InitializeProgressValue(); this->SetCurrentFilterProgressWeight( 1.0 ); // Execute the importer try { this->m_ImportFilter->Update(); } catch( itk::ProcessAborted & e ) { } // Update the filter try { this->m_Filter->Update(); } catch( itk::ProcessAborted & e) { std::cerr << "ITK error " << e.what() << std::endl; } // Update the exporter try { this->m_ExportFilter->Update(); } catch( itk::ProcessAborted & e) { std::cerr << "ITK error " << e.what() << std::endl; } } vtkImageData * GetOutput() { return this->m_ExportFilter->GetOutput(); } private: typename ImportFilterType::Pointer m_ImportFilter; typename FilterType::Pointer m_Filter; bool m_LetITKAllocateOutputMemory; typename ExportFilterType::Pointer m_ExportFilter; }; } // end namespace vtkitk #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEVoxelAlignedImageActorPointPlacer.h0000644000175000017500000001007411363410610025366 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEVoxelAlignedImageActorPointPlacer - point placer that forces the placement of points to the nearest voxel center // .SECTION Description // vtkKWEVoxelAlignedImageActorPointPlacer is a point placer that works on // image actors and automatically forces the placement of the point to // the nearest voxel center. This is useful when using voxelized editing // widgets and you'd like to see the shape be placed exactly over a voxel // rather than in between two voxels. #ifndef __vtkKWEVoxelAlignedImageActorPointPlacer_h #define __vtkKWEVoxelAlignedImageActorPointPlacer_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkImageActorPointPlacer.h" class VTKEdge_WIDGETS_EXPORT vtkKWEVoxelAlignedImageActorPointPlacer : public vtkImageActorPointPlacer { public: // Description: // Instantiate this class. static vtkKWEVoxelAlignedImageActorPointPlacer *New(); // Description: // Standard methods for instances of this class. vtkTypeRevisionMacro(vtkKWEVoxelAlignedImageActorPointPlacer, vtkImageActorPointPlacer); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Given and renderer and a display position in pixels, // find a world position and orientation. In this class // an internal vtkBoundedPlanePointPlacer is used to compute // the world position and orientation. The internal placer // is set to use the plane of the image actor and the bounds // of the image actor as the constraints for placing points. int ComputeWorldPosition( vtkRenderer *ren, double displayPos[2], double worldPos[3], double worldOrient[9] ); // Description: // This method is identical to the one above since the // reference position is ignored by the bounded plane // point placer. int ComputeWorldPosition( vtkRenderer *ren, double displayPos[2], double refWorldPos[2], double worldPos[3], double worldOrient[9] ); // Description: // This method validates a world position by checking to see // if the world position is valid according to the constraints // of the internal placer (essentially - is this world position // on the image?) int ValidateWorldPosition( double worldPos[3] ); // Description: // This method is identical to the one above since the bounded // plane point placer ignores orientation int ValidateWorldPosition( double worldPos[3], double worldOrient[9]); // Description: // Update the world position and orientation according the // the current constraints of the placer. Will be called // by the representation when it notices that this placer // has been modified. int UpdateWorldPosition( vtkRenderer *ren, double worldPos[3], double worldOrient[9]); protected: vtkKWEVoxelAlignedImageActorPointPlacer(); ~vtkKWEVoxelAlignedImageActorPointPlacer(); int InternalValidateWorldPosition(double worldPos[3]); private: vtkKWEVoxelAlignedImageActorPointPlacer( const vtkKWEVoxelAlignedImageActorPointPlacer&); //Not implemented void operator=(const vtkKWEVoxelAlignedImageActorPointPlacer&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushUtilities.cxx0000644000175000017500000001221311363410610023273 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushUtilities.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkKWEPaintbrushUtilities, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEPaintbrushUtilities); vtkKWEPaintbrushUtilities::vtkKWEPaintbrushUtilities() { } vtkKWEPaintbrushUtilities::~vtkKWEPaintbrushUtilities() { } //---------------------------------------------------------------------------- void vtkKWEPaintbrushUtilities::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushUtilities::GetIntersectingExtents( int extent1[6], int extent2[6], int extent[6]) { if ((extent1[0] > extent2[1]) || (extent1[1] < extent2[0]) || (extent1[2] > extent2[3]) || (extent1[3] < extent2[2]) || (extent1[4] > extent2[5]) || (extent1[5] < extent2[4])) { // The extents don't intersect extent[0] = extent[1] = extent[2] = extent[3] = extent[4] = extent[5] = -1; return 0; } extent[0] = (extent1[0] < extent2[0]) ? extent2[0] : extent1[0]; extent[1] = (extent1[1] > extent2[1]) ? extent2[1] : extent1[1]; extent[2] = (extent1[2] < extent2[2]) ? extent2[2] : extent1[2]; extent[3] = (extent1[3] > extent2[3]) ? extent2[3] : extent1[3]; extent[4] = (extent1[4] < extent2[4]) ? extent2[4] : extent1[4]; extent[5] = (extent1[5] > extent2[5]) ? extent2[5] : extent1[5]; return 1; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushUtilities::GetImageFromStencil( vtkImageData *image, vtkImageStencilData *stencilData, unsigned char inVal, unsigned char outVal, bool useImageExtent ) { int extent[6]; stencilData->GetExtent( extent ); if (!useImageExtent) { // We will take care of initializing the image. image->SetExtent( extent ); image->SetScalarTypeToUnsignedChar(); image->SetNumberOfScalarComponents(1); image->AllocateScalars(); } else { // extent = intersection of ImageExtent and StencilExtent. int imageExtent[6]; image->GetExtent(imageExtent); extent[0] = (extent[0] < imageExtent[0] ? imageExtent[0] : extent[0]); extent[1] = (extent[1] > imageExtent[1] ? imageExtent[1] : extent[1]); extent[2] = (extent[2] < imageExtent[2] ? imageExtent[2] : extent[2]); extent[3] = (extent[3] > imageExtent[3] ? imageExtent[3] : extent[3]); extent[4] = (extent[4] < imageExtent[4] ? imageExtent[4] : extent[4]); extent[5] = (extent[5] > imageExtent[5] ? imageExtent[5] : extent[5]); } // Fill image with zeroes vtkImageIterator< unsigned char > it(image, image->GetExtent()); while( !it.IsAtEnd() ) { unsigned char *inSI = it.BeginSpan(); unsigned char *inSIEnd = it.EndSpan(); while (inSI != inSIEnd) { *inSI = outVal; ++inSI; } it.NextSpan(); } // Now populate image with inVal wherever the stencil exists. int r1, r2, moreSubExtents, iter; for (int z=extent[4]; z <= extent[5]; z++) { for (int y=extent[2]; y <= extent[3]; y++) { iter = 0; moreSubExtents = 1; while( moreSubExtents ) { moreSubExtents = stencilData->GetNextExtent( r1, r2, extent[0], extent[1], y, z, iter); // sanity check if (r1 <= r2) { unsigned char *beginExtent = static_cast(image->GetScalarPointer(r1, y, z)); unsigned char *endExtent = static_cast(image->GetScalarPointer(r2, y, z)); while (beginExtent <= endExtent) { *beginExtent = inVal; ++beginExtent; } } } // end for each extent tuple } // end for each scan line } // end of each slice image->Modified(); } //---------------------------------------------------------------------------- int vtkKWEPaintbrushUtilities ::ExtentIsEqualToExtent( int extent1[6], int extent2[6] ) { if (!extent1 || !extent2) { return 0; } return (extent1[0] == extent2[0] && extent1[1] == extent2[1] && extent1[2] == extent2[2] && extent1[3] == extent2[3] && extent1[4] == extent2[4] && extent1[5] == extent2[5]) ? 1 : 0; } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushShape.h0000644000175000017500000001460011504122432022006 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushShape - An abstract class to represent a paintbrush shape // .SECTION Description // The class represents a paintbrush shape. It defines two pure virtual // methods: \c GetStencil and \c GetShapePolyData. The first returns the shape // stencil centered at a given point. The second returns the shape polydata // in world coordinates intersecting with the specified plane. If the plane // is NULL, it should return the shape polydata in 3D. // // .SECTION See Also #ifndef __vtkKWEPaintbrushShape_h #define __vtkKWEPaintbrushShape_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkKWEPaintbrushEnums.h" #include "vtkSmartPointer.h" // #include "vtkPolyData.h" #include "vtkObject.h" class vtkImageStencilData; class vtkImageData; class vtkKWEPaintbrushData; class vtkPlane; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushShape : public vtkObject { public: // Description: // Standard methods for instances of this class. vtkTypeRevisionMacro(vtkKWEPaintbrushShape, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // It allows the paintbrush representation to query the template for a // paintbrush outline centered at the specified point and intersecting // with the specified plane. If the plane is NULL, a polydata representation // of the template in 3D is returned. // Returns NULL if the plane does not intersect with the template. //BTX virtual vtkSmartPointer< vtkPolyData > GetShapePolyData( double *center, vtkPlane *plane = NULL) = 0; //ETX // Description: // Get the template as a stencil or as a grayscale data. virtual void GetStencil(vtkImageStencilData *, double p[3]) = 0; virtual void GetGrayscaleData(vtkImageData *, double p[3]) = 0; void GetPaintbrushData(vtkKWEPaintbrushData *, int x, int y, int z); void GetPaintbrushData(vtkKWEPaintbrushData *, double p[3]); // Description: // Set/Get methods to set the metadata of the image on which the template is // drawn. These must be set or bad things will happen. vtkSetVector3Macro( Spacing, double ); vtkGetVector3Macro( Spacing, double ); vtkSetVector3Macro( Origin, double ); vtkGetVector3Macro( Origin, double ); // Description: // Set the datatype of the grayscale data returned. (ie VTK_UNSIGNED_CHAR // etc) vtkSetMacro(ScalarType,int); vtkGetMacro(ScalarType,int); // Description: // Set the polarity of the shape. Positive by default. Positive shapes // are intended to draw. Negative shapes are intended to be used for // erasing. vtkSetMacro(Polarity, int); vtkGetMacro(Polarity, int); virtual void SetPolarityToDraw(); virtual void SetPolarityToErase(); //BTX // Enums that constrain resizing of the brush enum PaintbrushResizeEnum { PaintbrushResizeUnConstrained = 0, PaintbrushResizeIsotropic, PaintbrushResizeAnisotropic, PaintbrushResize_XY, PaintbrushResize_YZ, PaintbrushResize_XZ }; //ETX // Description: // Optionally, you may set a constraint on the resizing of the brush. This // constraint is imposed during interactive resizing of the brush. See the // enum: PaintbrushResizeEnum. // Default is UnConstrained. vtkSetMacro( ResizeConstraint, int ); vtkGetMacro( ResizeConstraint, int ); // Description: // INTERNAL - Do not use. // Resize the shape. This method is only intended to be called from // the vtkKWEPaintbrushWidget class via user-interaction. If you wish to specify // an initial size for the brush, use the method SetWidth/SetRadius etc // that each concrete subclass provides. // 'ResizeType' must be one fo the PaintbrushResizeEnum's specified below. // Returns 1 if resize is successful. 0 otherwise. virtual int Resize(double factor[3], int ResizeType) = 0; // Description: // Deep copy.. Synchronizes states etc. virtual void DeepCopy(vtkKWEPaintbrushShape *); // Description: // Provide some kind of contextual annotation about the shape that // indicates its size etc.. virtual void GetAnnotation(char *) = 0; // Description: // Check if point is inside the shape. Subclasses must implement this. virtual int IsInside(double vtkNotUsed(currPos)[3], double vtkNotUsed(testPos)[3]) { return 1; } // Description: // Abstract method to get the width of the shape. virtual double *GetWidth() = 0; virtual void GetWidth (double &, double &, double &) = 0; // Description: // Set the shape representation. Either: // vtkKWEPaintbrushEnums::Binary or // vtkKWEPaintbrushEnums::Grayscale vtkSetMacro( Representation, int ); vtkGetMacro( Representation, int ); // Description: // Set the maximum width of the shape for each axe. vtkSetVector3Macro( MaxWidth, double ); vtkGetVector3Macro( MaxWidth, double ); // Description: // The etch produced by the shape can be sent through these clip extents, so // as to confine it to a certain axis aligned region. The default clip // extents are infinite. void SetClipExtent( int e[6] ); void GetClipExtent( int e[6] ); int * GetClipExtent(); // Description: // INTERNAL - Do not use. // Get the extents of a shape drawn at the current location. virtual void GetExtent( int extent[6], double p[3] ) = 0; protected: vtkKWEPaintbrushShape(); ~vtkKWEPaintbrushShape(); double Spacing[3]; double Origin[3]; int ScalarType; int Polarity; int ResizeConstraint; int Representation; double MaxWidth[3]; int ClipExtent[6]; private: vtkKWEPaintbrushShape(const vtkKWEPaintbrushShape&); //Not implemented void operator=(const vtkKWEPaintbrushShape&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushShapeEllipsoid.cxx0000644000175000017500000004766311504122432024245 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushShapeEllipsoid.h" #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkImageStencilData.h" #include "vtkImageData.h" #include "vtkMath.h" #include "vtkParametricFunctionSource.h" #include "vtkParametricEllipsoid.h" #include "vtkImageEllipsoidSource.h" #include "vtkPlane.h" #include "vtkCellArray.h" #include "vtkKWEPaintbrushUtilities.h" #ifndef min #define min(x,y) ((xWidth[0] = 0.0; this->Width[1] = 0.0; this->Width[2] = 0.0; this->Resolution = 64; this->TransitionRegion = 0.2; } //---------------------------------------------------------------------- vtkKWEPaintbrushShapeEllipsoid::~vtkKWEPaintbrushShapeEllipsoid() { } //---------------------------------------------------------------------- vtkSmartPointer< vtkPolyData > vtkKWEPaintbrushShapeEllipsoid::GetShapePolyData( double *center, vtkPlane *plane) { if (plane == NULL) { // No Orientation specified. Return the whole Polydata. This is what will // be rendered on the volume widget vtkParametricFunctionSource * parametricFunctionSource = vtkParametricFunctionSource::New(); vtkParametricEllipsoid * ellipsoidFunction = vtkParametricEllipsoid::New(); parametricFunctionSource->SetParametricFunction(ellipsoidFunction); parametricFunctionSource->SetScalarModeToNone(); parametricFunctionSource->GenerateTextureCoordinatesOff(); parametricFunctionSource->SetUResolution( this->Resolution ); parametricFunctionSource->Update(); vtkSmartPointer< vtkPolyData > pd = parametricFunctionSource->GetOutput(); ellipsoidFunction->Delete(); parametricFunctionSource->Delete(); return pd; } else { double normal[3], origin[3], r[3]; r[0] = this->Width[0]/2.0; r[1] = this->Width[1]/2.0; r[2] = this->Width[2]/2.0; plane->GetNormal(normal); plane->GetOrigin(origin); // Fast handlers for axis aligned planes. const double tolerance = 0.01; if ((fabs(normal[0])-1.0) < tolerance && fabs(normal[1]) < tolerance && fabs(normal[2]) < tolerance) { if (fabs(origin[0] - center[0]) > this->Width[0]/2.0) { return NULL; } vtkSmartPointer< vtkPolyData > templateOutline = vtkSmartPointer< vtkPolyData >::New(); vtkPoints *points = vtkPoints::New(); vtkCellArray *lines = vtkCellArray::New(); vtkIdType *lineIndices = new vtkIdType[this->Resolution + 1]; r[1] = r[1] * sqrt(1- (origin[0]-center[0])*(origin[0]-center[0])/(r[0]*r[0])); r[2] = r[2] * sqrt(1- (origin[0]-center[0])*(origin[0]-center[0])/(r[0]*r[0])); for (int i = 0; i< this->Resolution; i++) { const double angle = 2.0*vtkMath::Pi()* static_cast(i)/static_cast(this->Resolution); points->InsertPoint(static_cast(i), origin[0], center[1] + r[1] * cos(angle), center[2] + r[2] * sin(angle)); lineIndices[i] = static_cast(i); } lineIndices[this->Resolution] = 0; lines->InsertNextCell(this->Resolution+1,lineIndices); delete [] lineIndices; templateOutline->SetPoints(points); templateOutline->SetLines(lines); points->Delete(); lines->Delete(); return templateOutline; } else if (fabs(normal[0]) < tolerance && (fabs(normal[1])-1.0) < tolerance && fabs(normal[2]) < tolerance) { if (fabs(origin[1] - center[1]) > this->Width[1]/2.0) { return NULL; } vtkSmartPointer< vtkPolyData > templateOutline = vtkSmartPointer< vtkPolyData >::New(); vtkPoints *points = vtkPoints::New(); vtkCellArray *lines = vtkCellArray::New(); vtkIdType *lineIndices = new vtkIdType[this->Resolution + 1]; r[0] = r[0] * sqrt(1- (origin[1]-center[1])*(origin[1]-center[1])/(r[1]*r[1])); r[2] = r[2] * sqrt(1- (origin[1]-center[1])*(origin[1]-center[1])/(r[1]*r[1])); for (int i = 0; i< this->Resolution; i++) { const double angle = 2.0*vtkMath::Pi() *i/static_cast(this->Resolution); points->InsertPoint(static_cast(i), center[0] + r[0] * cos(angle), origin[1], center[2] + r[2] * sin(angle)); lineIndices[i] = static_cast(i); } lineIndices[this->Resolution] = 0; lines->InsertNextCell(this->Resolution+1,lineIndices); delete [] lineIndices; templateOutline->SetPoints(points); templateOutline->SetLines(lines); points->Delete(); lines->Delete(); return templateOutline; } else if (fabs(normal[0]) < tolerance && fabs(normal[1]) < tolerance && (fabs(normal[2])-1.0) < tolerance) { if (fabs(origin[2] - center[2]) > this->Width[2]/2.0) { return NULL; } vtkSmartPointer< vtkPolyData > templateOutline = vtkSmartPointer< vtkPolyData >::New(); vtkPoints *points = vtkPoints::New(); vtkCellArray *lines = vtkCellArray::New(); vtkIdType *lineIndices = new vtkIdType[this->Resolution + 1]; r[0] = r[0] * sqrt(1- (origin[1]-center[1])*(origin[1]-center[1])/(r[1]*r[1])); r[2] = r[2] * sqrt(1- (origin[1]-center[1])*(origin[1]-center[1])/(r[1]*r[1])); for (int i = 0; i< this->Resolution; i++) { const double angle = 2.0*vtkMath::Pi()* i/static_cast(this->Resolution); points->InsertPoint(static_cast(i), center[0] + r[0] * cos(angle), center[1] + r[1] * sin(angle), origin[2]); lineIndices[i] = static_cast(i); } lineIndices[this->Resolution] = 0; lines->InsertNextCell(this->Resolution+1,lineIndices); delete [] lineIndices; templateOutline->SetPoints(points); templateOutline->SetLines(lines); points->Delete(); lines->Delete(); return templateOutline; } else { // TODO intersect cube with arbitrarily oriented plane and return polydata vtkErrorMacro( << "Not yet supported" ); return NULL; } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeEllipsoid::GetStencil( vtkImageStencilData *stencilData, double p[3]) { //int extent[6]; //this->GetExtent( extent, p ); // A. Get an elliptical stencil // A.1. Compute extents that the stencil will have double ellipsoidBounds[6]; int ellipsoidExtent[6]; for (int i = 0; i < 3; i++) { ellipsoidBounds[2*i] = p[i] - this->Width[i]/2.0; ellipsoidBounds[2*i+1] = p[i] + this->Width[i]/2.0; ellipsoidExtent[2*i] = static_cast< int >((ellipsoidBounds[2*i]- this->Origin[i])/this->Spacing[i]); ellipsoidExtent[2*i+1] = static_cast< int >((ellipsoidBounds[2*i+1]- this->Origin[i])/this->Spacing[i] + 0.5); // Clip the extents with the clip extent. if (ellipsoidExtent[2*i] < this->ClipExtent[2*i]) { ellipsoidExtent[2*i] = this->ClipExtent[2*i]; } if (ellipsoidExtent[2*i+1] > this->ClipExtent[2*i+1]) { ellipsoidExtent[2*i+1] = this->ClipExtent[2*i+1]; } } // A.2 Allocate the stencil stencilData->SetExtent(ellipsoidExtent); stencilData->SetSpacing(this->Spacing); stencilData->SetOrigin(this->Origin); stencilData->AllocateExtents(); // A.3 Fill the stencil with an ellipsoid int xIdx, yIdx, zIdx, ends[2]; double startPt[3], inc[3]; for (int i = 0; i < 3; i++) { startPt[i] = 2.0 * (((double)ellipsoidExtent[2*i])*this->Spacing[i] + this->Origin[i] - p[i])/this->Width[i]; inc[i] = 2.0 * this->Spacing[i] / this->Width[i]; } double yInc = inc[1], xInc = inc[0], zInc = inc[2], zDist = startPt[2], xDist, yDist; double zDistSq, zyDistSq, distSq; // A.4 Rasterize for (zIdx = ellipsoidExtent[4]; zIdx <= ellipsoidExtent[5]; zIdx++, zDist += zInc) { zDistSq = zDist * zDist; yDist = startPt[1]; for (yIdx = ellipsoidExtent[2]; yIdx <= ellipsoidExtent[3]; yIdx++, yDist += yInc) { zyDistSq = zDistSq + (yDist * yDist); xDist = startPt[0]; ends[0] = ends[1] = -1; for (xIdx = ellipsoidExtent[0]; xIdx <= ellipsoidExtent[1]; xIdx++, xDist += xInc) { distSq = zyDistSq + (xDist * xDist); if (ends[0] == -1 && distSq <= 1.0) { // found the start ends[0] = xIdx; continue; } if (ends[0] != -1 && distSq > 1.0) { // found the end, jump to to the next scan line. There can be only one // segment per scan line in an ellipse. ends[1] = xIdx; stencilData->InsertNextExtent(ends[0], ends[1]-1, yIdx, zIdx); break; } } if (ends[1] == -1 && ends[0] != -1) { // scan line never completed. stencilData->InsertNextExtent(ends[0], ellipsoidExtent[1], yIdx, zIdx); } } } } //---------------------------------------------------------------------- template < class T > int vtkKWEPaintbrushShapeEllipsoidFillBuffer( vtkKWEPaintbrushShapeEllipsoid * self, vtkImageData *imageData, T, int extent[6], double p[3] ) { // Polarity of the shape const bool state = (self->GetPolarity() == vtkKWEPaintbrushEnums::Draw); // Get the radius along each axis = halfwidth ^ 2 const double r1square = 0.25 * self->GetWidth()[0]*self->GetWidth()[0]; const double r2square = 0.25 * self->GetWidth()[1]*self->GetWidth()[1]; const double r3square = 0.25 * self->GetWidth()[2]*self->GetWidth()[2]; // get metadata double spacing[3], origin[3], value; self->GetSpacing(spacing); self->GetOrigin(origin); // The grayscale values in the brush will extend to maxRadiusFactor times // the brush width along any direction. const double transitionRegion = self->GetTransitionRegion(); const double maxRadiusFactor = 1.0 + transitionRegion; const double maxRadiusFactorSq = maxRadiusFactor * maxRadiusFactor; const double polarity = (state ? 1.0 : -1.0); for (int k= extent[4]; k<=extent[5]; k++) { for (int j= extent[2]; j<=extent[3]; j++) { T * np = static_cast< T* >(imageData->GetScalarPointer(extent[0],j,k)); for (int i= extent[0]; i<=extent[1]; ++i, ++np) { double px = i * spacing[0] + origin[0] - p[0]; double py = j * spacing[1] + origin[1] - p[1]; double pz = k * spacing[2] + origin[2] - p[2]; const double distanceSq = px*px/r1square + py*py/r2square + pz*pz/r3square; if ( distanceSq > maxRadiusFactorSq ) { // Outside the ellipse *np = static_cast< T >(0.0); continue; } // Normalized distance of the point from the surface of the ellipse. // This is 1.0 at the surface, 0.0 at the center, 2.0 at twice the // distance from the surface... const double distance = sqrt(distanceSq); if (distance <= (1.0 - transitionRegion)) { value = state ? 255.0 : 0.0; } else { value = 127.5 * (1.0 + polarity * (1-distance)/transitionRegion); } // Positive brush profile Negarive brush profile // // // 255 - /\ ---- ---- // / \ \ / // 127.5 - / \ \ / // / \ \ / // 0 _ ____/ \____ \/ // // | | | | | | // -2r 0 2r -2r 0 2r // // value = state ? (255.0 - 127.5 * distance) : 127.5 * distance; // Don't use 0. So we shrink the range within the shape by 1 on // each end. 1 - 254. The reason is 0 is used to indicate an // outside value (outside the brush). See vtkKWEPaintbrushGrayscaleData // // clamp value [1 - 254] if( value < 1.0 ) { value = 1.0; } else if( value > 254.0 ) { value = 254.0; } *np = static_cast< T >(value); } } } return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeEllipsoid::GetGrayscaleData( vtkImageData *imageData, double p[3]) { // Compute the extents of the an image centered about p. int extent[6]; this->GetExtent( extent, p ); imageData->SetSpacing(this->Spacing); imageData->SetOrigin(this->Origin); imageData->SetExtent(extent); imageData->SetScalarType(this->GetScalarType()); imageData->AllocateScalars(); switch (imageData->GetScalarType()) { vtkTemplateMacro( vtkKWEPaintbrushShapeEllipsoidFillBuffer( this, imageData, static_cast< VTK_TT >(0), extent, p )); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeEllipsoid::SetWidth( double newWidthX, double newWidthY, double newWidthZ ) { vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting Width to (" << newWidthX << "," << newWidthY << "," << newWidthZ << ")"); if ((this->Width[0] != newWidthX)||(this->Width[1] != newWidthY)||(this->Width[2] != newWidthZ)) { this->Width[0] = (this->MaxWidth[0] < 0. || this->MaxWidth[0] > newWidthX)? newWidthX :this->MaxWidth[0]; this->Width[1] = (this->MaxWidth[1] < 0. || this->MaxWidth[1] > newWidthY)? newWidthY :this->MaxWidth[1]; this->Width[2] = (this->MaxWidth[2] < 0. || this->MaxWidth[2] > newWidthZ)? newWidthZ :this->MaxWidth[2]; this->Modified(); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeEllipsoid::SetWidth( double newWidth[3] ) { this->SetWidth( newWidth[0], newWidth[1], newWidth[2] ); } //---------------------------------------------------------------------- int vtkKWEPaintbrushShapeEllipsoid::Resize(double d[3], int ResizeType) { // If the user specified a constraint on the resize type, use that, // otherwise default to whatever the widget told us in the functions' // argument. const int resizeType = (this->ResizeConstraint == PaintbrushResizeUnConstrained) ? ResizeType : this->ResizeConstraint; // Define a minimum size that the shape will take. The shape will not // get smaller than this. const double minSize = 0.5; double newWidth[3] = { this->Width[0], this->Width[1], this->Width[2] }; if (resizeType == vtkKWEPaintbrushShape::PaintbrushResizeAnisotropic) { // non-isotropic resize. This will resize each axis according to the // factor specified along each axis. for (unsigned int i=0; i<3; i++) { if (d[i] > 0.0 || this->Width[i] > minSize) { newWidth[i] *= (1+d[i]/10.0); } } } else { // Not an AnIsotropic resize.. This will resize each axis by the same // factor. This factor will be the norm of the factor vector specified // as the functions' argument // Calculate the sign.. (grow or shrink) unsigned int idx = 0; double max = fabs(d[0]); int signVal; for (unsigned int i=1; i<3; i++) { if (fabs(d[i]) > max) { idx = i; max = fabs(d[i]); } } signVal = sign(d[idx]); // The new size is .... const double norm = vtkMath::Norm(d); for (unsigned int i=0; i<3; i++) { newWidth[i] *= (1+(norm * signVal)/10.0); } } // Handle special cases. switch (resizeType) { case PaintbrushResize_XY: newWidth[2] = this->Width[2]; break; case PaintbrushResize_YZ: newWidth[0] = this->Width[0]; break; case PaintbrushResize_XZ: newWidth[1] = this->Width[1]; break; } // Make sure we aren't smaller than the minimum if (newWidth[0] < minSize || newWidth[1] < minSize || newWidth[2] < minSize) { return 0; } // Now change our size to the new size. this->SetWidth( newWidth ); return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeEllipsoid::DeepCopy(vtkKWEPaintbrushShape *s) { if (s == this) { return; } vtkKWEPaintbrushShapeEllipsoid *sb = vtkKWEPaintbrushShapeEllipsoid::SafeDownCast(s); if (sb) { for (unsigned int i=0; i<3; i++) { this->Width[i] = sb->Width[i]; } this->Resolution = sb->Resolution; } this->Superclass::DeepCopy(s); this->Modified(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeEllipsoid::GetAnnotation(char *s) { sprintf(s, "Diameter: (%0.3g,%0.3g,%0.3g)", this->Width[0], this->Width[1], this->Width[2]); } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeEllipsoid::GetExtent(int extent[6], double p[3]) { if (this->Representation == vtkKWEPaintbrushEnums::Grayscale) { for (int i=0; i< 3; i++) { // transition region based extension of width. extent[2*i] = static_cast((p[i] - this->Width[i]* (0.5+this->TransitionRegion/2.0) - this->Origin[i])/ this->Spacing[i] + 0.5); extent[2*i+1] = static_cast((p[i] + this->Width[i]* (0.5+this->TransitionRegion/2.0) - this->Origin[i])/ this->Spacing[i] - 0.4999999); extent[2*i] = extent[2*i] < 0 ? 0 : extent[2*i]; if (extent[2*i] > extent[2*i+1]) { extent[2*i+1] = extent[2*i]; } } } else { for (int i=0; i< 3; i++) { extent[2*i] = static_cast((p[i] - this->Width[i]/2.0 - this->Origin[i]) /this->Spacing[i] + 0.5); extent[2*i+1] = static_cast((p[i] + this->Width[i]/2.0 - this->Origin[i]) /this->Spacing[i] - 0.49999999); extent[2*i] = extent[2*i] < 0 ? 0 : extent[2*i]; if (extent[2*i] > extent[2*i+1]) { extent[2*i+1] = extent[2*i]; } } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeEllipsoid::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Width: (" << this->Width[0] << ", " << this->Width[1] << ", " << this->Width[2] << ")\n"; os << indent << "Resolution: " << this->Resolution << std::endl; } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushDrawingStatistics.cxx0000644000175000017500000001636611502655425025015 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushDrawingStatistics.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkObjectFactory.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkExecutive.h" #include "vtkAlgorithmOutput.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkKWEPaintbrushDataStatistics.h" #include "vtkImageData.h" #include "vtkDataArray.h" #include "vtkPointData.h" vtkCxxRevisionMacro(vtkKWEPaintbrushDrawingStatistics, "$Revision: 3258 $"); vtkStandardNewMacro(vtkKWEPaintbrushDrawingStatistics); //---------------------------------------------------------------------------- vtkKWEPaintbrushDrawingStatistics::vtkKWEPaintbrushDrawingStatistics() { this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(0); this->Volume = 0; this->Volumes.clear(); this->MaximumLabelValue = 1; for (int i = 0; i < sizeof( vtkKWEPaintbrushEnums::LabelType ); i++) { this->MaximumLabelValue *= 256; } this->VolumesArray = new unsigned long[this->MaximumLabelValue]; } //---------------------------------------------------------------------------- vtkKWEPaintbrushDrawingStatistics::~vtkKWEPaintbrushDrawingStatistics() { delete this->VolumesArray; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushDrawingStatistics ::RequestData( vtkInformation *, vtkInformationVector** inputVector, vtkInformationVector* vtkNotUsed( outputVector )) { vtkInformation *info = inputVector[0]->GetInformationObject(0); vtkKWEPaintbrushDrawing *inputDrawing = vtkKWEPaintbrushDrawing::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); this->Volume = 0; if (inputDrawing->GetRepresentation() != vtkKWEPaintbrushEnums::Label) { this->Volumes.clear(); const int nSketches = inputDrawing->GetNumberOfItems(); for (int n = 0; n < nSketches; n++) { vtkKWEPaintbrushSketch * sketch = inputDrawing->GetItem(n); vtkKWEPaintbrushData * data = sketch->GetPaintbrushData(); vtkKWEPaintbrushDataStatistics * stats = vtkKWEPaintbrushDataStatistics::New(); stats->SetInput(data); stats->Update(); const double sketchVolume = stats->GetVolume(); this->Volumes.push_back(sketchVolume); this->Volume += sketchVolume; stats->Delete(); } } else { for (unsigned long i = 0; i < this->MaximumLabelValue; i++) { this->VolumesArray[i] = 0; } vtkKWEPaintbrushLabelData *ldata = vtkKWEPaintbrushLabelData::SafeDownCast( inputDrawing->GetPaintbrushData()); vtkImageData *labelImage = ldata->GetLabelMap(); vtkDataArray * array = labelImage->GetPointData()->GetScalars(); vtkKWEPaintbrushEnums::LabelType *arrayPointer = static_cast(array->GetVoidPointer(0)); const unsigned long size = array->GetDataSize(); for (unsigned long i = 0; i < size; ++i, ++arrayPointer) { vtkKWEPaintbrushEnums::LabelType l = *arrayPointer; if (l != vtkKWEPaintbrushLabelData::NoLabelValue) { ++(this->VolumesArray[l]); } } double spacing[3]; ldata->GetSpacing(spacing); const double voxelVolume = spacing[0] * spacing[1] * spacing[2]; for (unsigned long i = 0; i < this->MaximumLabelValue; i++) { this->Volume += ((double)(this->VolumesArray[i]) * voxelVolume); } } return 1; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushDrawingStatistics:: FillInputPortInformation(int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkKWEPaintbrushDrawing"); return 1; } //---------------------------------------------------------------------------- int vtkKWEPaintbrushDrawingStatistics:: ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // generate the data if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) { this->RequestData(request, inputVector, outputVector); return 1; } return this->Superclass::ProcessRequest(request, inputVector, outputVector); } //---------------------------------------------------------------------------- double vtkKWEPaintbrushDrawingStatistics::GetVolume() { this->Update(); return this->Volume; } //---------------------------------------------------------------------------- vtkKWEPaintbrushDrawing * vtkKWEPaintbrushDrawingStatistics::GetDrawing() { return vtkKWEPaintbrushDrawing::SafeDownCast( this->GetExecutive()->GetInputData(0, 0)); } //---------------------------------------------------------------------------- double vtkKWEPaintbrushDrawingStatistics::GetVolume(int n) { this->Update(); if (this->GetDrawing()->GetRepresentation() != vtkKWEPaintbrushEnums::Label) { return static_cast(n) < this->Volumes.size() ? this->Volumes[n] : 0.0; } else { double spacing[3]; vtkKWEPaintbrushLabelData *ldata = vtkKWEPaintbrushLabelData::SafeDownCast( this->GetDrawing()->GetPaintbrushData()); ldata->GetSpacing(spacing); const double voxelVolume = spacing[0] * spacing[1] * spacing[2]; return voxelVolume * (double)(this->VolumesArray[ this->GetDrawing()->GetItem(n)->GetLabel()]); } } //---------------------------------------------------------------------------- double vtkKWEPaintbrushDrawingStatistics::GetVolume( vtkKWEPaintbrushSketch *s ) { return this->GetVolume(this->GetDrawing()->GetIndexOfItem(s)); } //---------------------------------------------------------------------------- double vtkKWEPaintbrushDrawingStatistics ::GetLabelVolume( vtkKWEPaintbrushEnums::LabelType l ) { this->Update(); double spacing[3]; vtkKWEPaintbrushLabelData *ldata = vtkKWEPaintbrushLabelData::SafeDownCast( this->GetDrawing()->GetPaintbrushData()); ldata->GetSpacing(spacing); const double voxelVolume = spacing[0] * spacing[1] * spacing[2]; return voxelVolume * (double)(this->VolumesArray[l]); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawingStatistics::SetInput(vtkKWEPaintbrushDrawing* input) { this->SetInputConnection(0,input->GetProducerPort()); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushDrawingStatistics::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEITKConfidenceConnectedImageFilter.h0000644000175000017500000000404511363410610025252 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef _vtkKWEITKConfidenceConnectedFilterModule_h #define _vtkKWEITKConfidenceConnectedFilterModule_h #include "itkConfidenceConnectedMiniPipelineFilter.h" #include "vtkKWEITKImageToStencilFilter.h" #include namespace vtkitk { template class vtkKWEITKConfidenceConnectedImageFilter : public vtkKWEITKImageToStencilFilter { public: typedef vtkKWEITKConfidenceConnectedImageFilter Self; typedef vtkKWEITKImageToStencilFilter Superclass; typedef itk::SmartPointer< Self > Pointer; typedef itk::SmartPointer< const Self > ConstPointer; itkTypeMacro(vtkKWEITKConfidenceConnectedImageFilter, vtkKWEITKImageToStencilFilter); itkNewMacro(Self); typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef typename InputImageType::IndexType IndexType; typedef itk::ConfidenceConnectedMiniPipelineFilter< InputImageType, OutputImageType > FilterType; virtual void AddSeed( int seed[3] ); // No MTime checks etc.. will update every time.. virtual void Update(); protected: vtkKWEITKConfidenceConnectedImageFilter(); ~vtkKWEITKConfidenceConnectedImageFilter(); }; } // end namespace vtkitk #ifndef ITK_MANUAL_INSTANTIATION #include "vtkKWEITKConfidenceConnectedImageFilter.txx" #endif #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEWidgetGroup.cxx0000644000175000017500000001171511502037234021530 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEWidgetGroup.h" #include "vtkObjectFactory.h" #include "vtkGarbageCollector.h" #include #include "vtkKWEAbstractPaintbrushWidget.h" // REMOVE vtkCxxRevisionMacro(vtkKWEWidgetGroup, "$Revision: 3236 $"); vtkStandardNewMacro(vtkKWEWidgetGroup); //---------------------------------------------------------------------- vtkKWEWidgetGroup::vtkKWEWidgetGroup() { } //---------------------------------------------------------------------- vtkKWEWidgetGroup::~vtkKWEWidgetGroup() { for (WidgetIteratorType it = this->Widget.begin(); it != this->Widget.end() ; ++it) { if (*it) { this->RemoveWidget( *it ); (*it)->Delete(); } } } //---------------------------------------------------------------------- void vtkKWEWidgetGroup::Register( vtkObjectBase *o ) { // Enable garbage collection due to ref counting cycles with vtkAbstractWidget this->RegisterInternal(o, 1); } //---------------------------------------------------------------------- void vtkKWEWidgetGroup::UnRegister( vtkObjectBase *o ) { // Enable garbage collection due to ref counting cycles with vtkAbstractWidget this->UnRegisterInternal(o, 1); } //---------------------------------------------------------------------- void vtkKWEWidgetGroup::SetEnabled(int enabling) { for (WidgetIteratorType it = this->Widget.begin(); it != this->Widget.end() ; ++it) { (*it)->SetEnabled(enabling); } } //---------------------------------------------------------------------- void vtkKWEWidgetGroup::AddWidget( vtkAbstractWidget *w ) { for ( unsigned int i = 0; i < this->Widget.size(); i++) { if (this->Widget[i] == w) { return; } } // TODO : Won't be necessary if we move this to the AbstractWidget.. superclass vtkKWEAbstractPaintbrushWidget *obj= static_cast(w); // If the widget was attached to someother widget set, remove it from that. if (vtkKWEWidgetGroup * otherWidgetGroup = obj->WidgetGroup) { otherWidgetGroup->RemoveWidget(w); } // Here is where we introduce the ref-counting cycle. w->Register(this); this->Register(w); this->Widget.push_back(w); obj->WidgetGroup = this; } //---------------------------------------------------------------------- void vtkKWEWidgetGroup::RemoveWidget( vtkAbstractWidget * w) { for (WidgetIteratorType it = this->Widget.begin(); it != this->Widget.end() ; ++it) { if (*it == w) { this->Widget.erase(it); static_cast(w)->WidgetGroup = NULL; w->UnRegister(this); this->UnRegister(w); break; } } } //---------------------------------------------------------------------- void vtkKWEWidgetGroup::Render() { for (WidgetIteratorType it = this->Widget.begin(); it != this->Widget.end() ; ++it) { (*it)->Render(); } } //---------------------------------------------------------------------- int vtkKWEWidgetGroup::HasWidget( vtkAbstractWidget * w ) { return (std::find(this->Widget.begin(), this->Widget.end(), w) == this->Widget.end() ? 0 : 1); } //---------------------------------------------------------------------- vtkAbstractWidget * vtkKWEWidgetGroup::GetNthWidget( unsigned int i ) { return this->Widget[i]; } //---------------------------------------------------------------------- unsigned int vtkKWEWidgetGroup::GetNumberOfWidgets() { return static_cast< unsigned int >(this->Widget.size()); } //---------------------------------------------------------------------- void vtkKWEWidgetGroup::ReportReferences(vtkGarbageCollector* collector) { const unsigned int n = this->GetNumberOfWidgets(); if (n) { this->Superclass::ReportReferences(collector); for (unsigned int i = 0; i < n; i++) { vtkGarbageCollectorReport(collector, this->Widget[i], "A widget from the WidgetGroup"); } } } //---------------------------------------------------------------------- void vtkKWEWidgetGroup::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushAnnotationWidget.h0000644000175000017500000000664011363410610024232 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushAnnotationWidget // .SECTION Description // .SECTION See Also // vtkKWEPaintbrushRepresentation, vtkKWEPaintbrushRepresentation2D, vtkKWEPaintbrushSketch, // vtkKWEPaintbrushShape. // #ifndef __vtkKWEPaintbrushAnnotationWidget_h #define __vtkKWEPaintbrushAnnotationWidget_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkAbstractWidget.h" class vtkKWEPaintbrushAnnotationRepresentation; class vtkKWEPaintbrushWidget; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushAnnotationWidget : public vtkAbstractWidget { //BTX friend class vtkKWEPaintbrushWidget; //ETX public: // Description: // Standard VTK methods. static vtkKWEPaintbrushAnnotationWidget *New(); vtkTypeRevisionMacro(vtkKWEPaintbrushAnnotationWidget,vtkAbstractWidget); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Annotation methods. void AnnotatePaintbrushMode(); void AnnotateNewSketch(); void AnnotateIncrementSketch(); void AnnotateDecrementSketch(); void AnnotateSize(); void AnnotateString( const char * ); protected: vtkKWEPaintbrushAnnotationWidget(); ~vtkKWEPaintbrushAnnotationWidget(); // The widget can be in any of the following states. //BTX enum { Start = 0, BeginTimer, EndTimer, Timing, TimedOut }; //ETX // Description: // Set the widget state. You must set it to either // BeginTimer or EndTimer only. virtual void SetWidgetState(int); vtkGetMacro( WidgetState, int ); // Description: // The method for activiating and deactiviating this widget. virtual void SetEnabled(int); // Description: // Callback interface to tie ends with the CallbackMapper for the events // invoked by this widget. static void MoveCallback ( vtkAbstractWidget* ); static void HoverCallback ( vtkAbstractWidget* ); // Description: // Method to satisfy the superclass API. // Create the default vtkKWEPaintbrushRepresentation if one is not set. virtual void CreateDefaultRepresentation(); // Description: // Specify an instance of vtkWidgetRepresentation used to represent this // widget in the scene. Note that the representation is a subclass of vtkProp // so it can be added to the renderer independent of the widget. void SetRepresentation(vtkKWEPaintbrushAnnotationRepresentation *r); private: vtkKWEPaintbrushAnnotationWidget(const vtkKWEPaintbrushAnnotationWidget&); //Not implemented void operator=(const vtkKWEPaintbrushAnnotationWidget&); //Not implemented // Description: int Movement; int WidgetState; int TimerId; int TimerDuration; vtkKWEPaintbrushWidget * PaintbrushWidget; }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEITKImageToStencilFilter.h0000644000175000017500000000464411363410610023303 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef _vtkKWEITKImageToStencilFilter_h #define _vtkKWEITKImageToStencilFilter_h #include "VTKEdgeConfigure.h" // Needed for export symbols #include "vtkKWEITKFilterModule.h" class vtkImageData; class vtkImageStencilData; namespace vtkitk { class VTKEdge_WIDGETS_EXPORT vtkKWEITKImageToStencilFilter : public itk::Object { public: typedef vtkKWEITKImageToStencilFilter Self; typedef itk::Object Superclass; typedef itk::SmartPointer< Self > Pointer; typedef itk::SmartPointer< const Self > ConstPointer; itkTypeMacro(ConfidenceConnectedRunner, itk::Object); itkStaticConstMacro( Dimension, unsigned int, 3); typedef unsigned char OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef FilterModuleBase InternalFilterType; // No MTime checks etc.. will update every time.. virtual void Update(); virtual void SetInput( vtkImageData * ); virtual int GetOutputAsStencil( vtkImageStencilData * ); virtual void SetRequestedExtent( int extent[6] ); itkSetMacro( BoundWithRadius, bool ); itkGetConstReferenceMacro( BoundWithRadius, bool ); itkBooleanMacro( BoundWithRadius ); void SetCenter( int center[3] ); void SetRadius( double radius[3] ); protected: vtkKWEITKImageToStencilFilter(); ~vtkKWEITKImageToStencilFilter(); InternalFilterType * m_Filter; int m_Extent[6]; bool m_BoundWithRadius; int m_Center[3]; double m_Radius[3]; }; } // end namespace vtkitk #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEAbstractPaintbrushWidget.h0000644000175000017500000000602011502037623023657 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEAbstractPaintbrushWidget - Abstract base class that enables the use of WidgetGroups. // .SECTION Description // The vtkKWEAbstractPaintbrushWidget is used to enable the use of a vtkKWEWidgetGroup // by adding the appropriate friend declarations. Its role is trivial and is // scheduled to be moved into vtkAbstractWidget. Until then we will keep this // class around to avoid modifications to vtkAbstractWidget. #ifndef __vtkKWEAbstractPaintbrushWidget_h #define __vtkKWEAbstractPaintbrushWidget_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkAbstractWidget.h" class vtkKWEPaintbrushRepresentation; class vtkKWEPaintbrushAnnotationWidget; class vtkKWEWidgetGroup; class vtkKWEPaintbrushWidgetCallbackMapper; class VTKEdge_WIDGETS_EXPORT vtkKWEAbstractPaintbrushWidget : public vtkAbstractWidget { //BTX // TODO: Move this to the superclass. friend class vtkKWEWidgetGroup; //ETX public: // Description: // Standard methods for a VTK class. vtkTypeRevisionMacro(vtkKWEAbstractPaintbrushWidget,vtkAbstractWidget); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Enable garbage collection. There are ref counting cycles with vtkKWEWidgetGroup virtual void Register(vtkObjectBase* o); virtual void UnRegister(vtkObjectBase* o); // Description: // Set the mouse and keyboard bindings through a callback mapper. If you want to // set your own bindings, you would create your own subclass of // vtkKWEPaintbrushWidgetCallbackMapper and override the Bindings() method. virtual void SetCallbackMapper( vtkKWEPaintbrushWidgetCallbackMapper * ); vtkGetObjectMacro( CallbackMapper, vtkWidgetCallbackMapper ); // Description: // Get the widget group that contains this paintbrush widget vtkGetObjectMacro( WidgetGroup, vtkKWEWidgetGroup ); protected: vtkKWEAbstractPaintbrushWidget(); ~vtkKWEAbstractPaintbrushWidget() {}; vtkKWEWidgetGroup* WidgetGroup; // We need to break reference count loops. The WidgetGroup ref counts us // and we ref-count the WidgetGroup. virtual void ReportReferences(vtkGarbageCollector* collector); void * Payload; private: vtkKWEAbstractPaintbrushWidget(const vtkKWEAbstractPaintbrushWidget&); //Not implemented void operator=(const vtkKWEAbstractPaintbrushWidget&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushLabelData.h0000644000175000017500000001420711567177014022601 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushLabelData - An abstract class used to support segmentations // .SECTION Description // // .SECTION see also // vtkImageLabelSource vtkImageLabel #ifndef __vtkKWEPaintbrushLabelData_h #define __vtkKWEPaintbrushLabelData_h #include "vtkKWEPaintbrushData.h" #include class vtkImageData; class vtkKWEPaintbrushSketch; class vtkKWEPaintbrushStencilData; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushLabelData : public vtkKWEPaintbrushData { //BTX friend class vtkKWEPaintbrushSketch; //ETX public: static vtkKWEPaintbrushLabelData *New(); vtkTypeRevisionMacro(vtkKWEPaintbrushLabelData, vtkKWEPaintbrushData); void PrintSelf(ostream& os, vtkIndent indent); void DeepCopy(vtkDataObject *o); void ShallowCopy(vtkDataObject *f); // Description: // Set/Get the label map. // This method should be used if you wish to initialize the class from an // existing label map. virtual void SetLabelMap( vtkImageData * ); vtkGetObjectMacro( LabelMap, vtkImageData ); // Description: // Minkowski operations. // The arguments can be both vtkKWEPaintbrushStencilData or // vtkKWEPaintbrushLabelData virtual int Add( vtkKWEPaintbrushData *, bool forceMutable=false ); virtual int Subtract( vtkKWEPaintbrushData *, bool forceMutable=false ); virtual int Replace( vtkKWEPaintbrushData *, bool forceMutable=false ); // Description: // Clip self with supplied extents. Return 1 if something changed virtual int Clip( int extent[6] ); // Description: // Allocate and fill. This will wipe out any existing data. It is assumed // that the extents have been set. virtual void Allocate(double fillValue = vtkKWEPaintbrushLabelData::NoLabelValue); // Description: // Set the spacing. virtual void SetSpacing( double spacing[3] ); virtual void GetSpacing( double spacing[3] ); // Description: // Set the origin. virtual void SetOrigin( double origin[3] ); virtual void GetOrigin( double origin[3] ); // Description: // Set the extent of the data. virtual void SetExtent(int extent[6]); virtual void SetExtent(int x1, int x2, int y1, int y2, int z1, int z2); virtual void GetExtent(int extent[6]); // Description: // Is the point "p" inside ? // The value returned is the label value. A value of 0 indicates that there // is nothing at the current location. virtual int IsInside( double p[3] ); // Description: // Get the label data as an image data. This is present merely to satisfy the // superclass requirement. It is preferred that you use the method above // instead. virtual void GetPaintbrushDataAsImageData( vtkImageData * ); // Description: // See vtkObject/vtkDataObject for doc virtual unsigned long GetMTime(); // Description: // Override these to handle origin, spacing, scalar type, and scalar // number of components. See vtkDataObject for details. virtual void CopyInformationToPipeline(vtkInformation* request, vtkInformation* input, vtkInformation* output, int forceCopy); virtual void CopyInformationFromPipeline(vtkInformation* request); //BTX // Description: // Retrieve an instance of this class from an information object. // See vtkObject/vtkDataObject for doc static vtkKWEPaintbrushLabelData* GetData(vtkInformation* info); static vtkKWEPaintbrushLabelData* GetData(vtkInformationVector* v, int i=0); //ETX // Description: // Restore data object to initial state. See vtkDataObject for details virtual void Initialize(); // Description: // Clear data corresponding to a label. // This sets all the voxels with the supplied label value to 0. virtual void Clear( vtkKWEPaintbrushEnums::LabelType label ); // Description: // The value 'NoLabelValue' is used to represent the absence of any label. // Default value is 0. static void SetNoLabelValue( vtkKWEPaintbrushEnums::LabelType label ); static vtkKWEPaintbrushEnums::LabelType NoLabelValue; //BTX // Description: // Get the labels that are present in this image. This will visit every single // voxel in the LabelMap and add it to the resulting set. typedef vtkstd::set< vtkKWEPaintbrushEnums::LabelType > LabelSetType; LabelSetType GetLabels(); //ETX // Description: // Convenience method to collapse the labels in a label map. Consider a label // map with labels of 32, 64, 125, 255 and a NoLabelValue of 0. This will // collapse this data into labels of 1, 2, 3, 4. virtual void RelabelDataToContiguousLabels(); protected: vtkKWEPaintbrushLabelData(); ~vtkKWEPaintbrushLabelData(); // Description: // Get important info from pipeline. void CopyOriginAndSpacingFromPipeline(); // Description: // The actual 'data' is stored here. vtkImageData *LabelMap; int AddStencil( vtkKWEPaintbrushStencilData * s, bool forceMutable ); private: vtkKWEPaintbrushLabelData(const vtkKWEPaintbrushLabelData&); // Not implemented. void operator=(const vtkKWEPaintbrushLabelData&); // Not implemented. // Description: // Called only from vtkKWEPaintbrushSketch. // Is the supplied label mutable ? void SetMutable( int isMutable, vtkKWEPaintbrushEnums::LabelType label ); int IsMutable( vtkKWEPaintbrushEnums::LabelType label ); //BTX // Is a label immutable ? If not present in the map, it is assumed to be // mutable. LabelSetType ImmutableLabels; //ETX }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushData.cxx0000644000175000017500000000352111567177014022211 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2008 Kitware, Inc. // // VTKEdge may be used under the terms of the GNU General Public License // version 3 as published by the Free Software Foundation and appearing in // the file LICENSE.txt included in the top level directory of this source // code distribution. Alternatively you may (at your option) use any later // version of the GNU General Public License if such license has been // publicly approved by Kitware, Inc. (or its successors, if any). // // VTKEdge is distributed "AS IS" with NO WARRANTY OF ANY KIND, INCLUDING // THE WARRANTIES OF DESIGN, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR // PURPOSE. See LICENSE.txt for additional details. // // VTKEdge is available under alternative license terms. Please visit // vtkedge.org or contact us at kitware@kitware.com for further information. // //============================================================================= #include "vtkKWEPaintbrushData.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkKWEPaintbrushData, "$Revision: 3550 $"); //---------------------------------------------------------------------- vtkKWEPaintbrushData::vtkKWEPaintbrushData() { this->Label = 1; this->ComputeDelta = 0; } //---------------------------------------------------------------------- vtkKWEPaintbrushData::~vtkKWEPaintbrushData() { } //---------------------------------------------------------------------- void vtkKWEPaintbrushData::Clear( vtkKWEPaintbrushEnums::LabelType ) { this->Allocate( ); } //---------------------------------------------------------------------- void vtkKWEPaintbrushData::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushProperty.cxx0000644000175000017500000001710711521051333023152 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushProperty.h" #include "vtkProperty.h" #include "vtkObjectFactory.h" #include "vtkKWEPaintbrushSketch.h" //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkKWEPaintbrushProperty, "$Revision: 3416 $"); //---------------------------------------------------------------------------- vtkKWEPaintbrushProperty* vtkKWEPaintbrushProperty::New() { return vtkKWEPaintbrushProperty::New(NULL); } //---------------------------------------------------------------------------- // Implement the standard form of the New() method. vtkKWEPaintbrushProperty* vtkKWEPaintbrushProperty::New(vtkKWEPaintbrushSketch * s) { vtkObject* ret = vtkObjectFactory::CreateInstance("vtkKWEPaintbrushProperty"); if(ret) { static_cast(ret)->PaintbrushSketch = s; return static_cast(ret); } vtkKWEPaintbrushProperty * p = new vtkKWEPaintbrushProperty; p->PaintbrushSketch = s; return p; } //---------------------------------------------------------------------------- vtkKWEPaintbrushProperty::vtkKWEPaintbrushProperty() { this->Mutable = 0; this->PaintbrushSketch = NULL; this->Identifier = NULL; this->Property = vtkProperty::New(); this->UserSpecifiedColorOverride = false; this->LineWidth = 1.0; this->HighlightType = ColorHighlight; this->Highlight = 0; this->Visibility = 1; this->InteractionEnabled = 1; // When highlighted, the lines are thrice as thick. // Only used if HighlightType is ThickHighlight this->HighlightThickness = 3.0; // The default HighlightColor is yellow. // Only used if HighlightType is ColorHighlight this->HighlightColor[0] = this->HighlightColor[1] = 1.0; this->HighlightColor[2] = 0.0; } //---------------------------------------------------------------------------- vtkKWEPaintbrushProperty::~vtkKWEPaintbrushProperty() { this->SetIdentifier(NULL); this->Property->Delete(); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushProperty::SetOpacity( double o ) { this->Property->SetOpacity( o < 0.0 ? 0.0 : (o > 1.0 ? 1.0 : o) ); } //---------------------------------------------------------------------------- double vtkKWEPaintbrushProperty::GetOpacity() { return this->Property->GetOpacity(); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushProperty::SetLineWidth( float o ) { // The factor accounts for highlighting. If its 2.0, its highlighted, if // its 1.0, its not. const double factor = this->Property->GetLineWidth()/this->LineWidth; this->Property->SetLineWidth( static_cast(factor * static_cast(o)) ); this->LineWidth = o; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushProperty::GetColor( unsigned char rgb[3] ) { double rgbd[3]; this->Property->GetColor(rgbd); rgb[0] = static_cast< unsigned char >(rgbd[0] * 255.0); rgb[1] = static_cast< unsigned char >(rgbd[1] * 255.0); rgb[2] = static_cast< unsigned char >(rgbd[2] * 255.0); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushProperty::GetColor( double rgb[3] ) { this->Property->GetColor(rgb); } //---------------------------------------------------------------------------- double * vtkKWEPaintbrushProperty::GetColor() { return this->Property->GetColor(); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushProperty::SetColor( double rgb[3] ) { this->SetColorInternal( rgb ); this->UserSpecifiedColorOverride = true; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushProperty::SetColorInternal( double rgb[3] ) { this->Property->SetColor(rgb); // The edge color is the inverse of the face color. We will use the edge // color for highlighting. Using the same color, espcially when in overlay // mode makes it hard for us to see the highlighting. this->Property->SetEdgeColor(1.0-rgb[0], 1.0-rgb[1], 1.0-rgb[2]); this->Color[0] = rgb[0]; this->Color[1] = rgb[1]; this->Color[2] = rgb[2]; } //---------------------------------------------------------------------------- // Return the modification for this object. unsigned long int vtkKWEPaintbrushProperty::GetMTime() { unsigned long int mtime = this->Superclass::GetMTime(); unsigned long int mtime2 = this->Property->GetMTime(); return (mtime > mtime2 ? mtime : mtime2); } //---------------------------------------------------------------------------- // Return the modification for this object. bool vtkKWEPaintbrushProperty::HasUserSpecifiedColorOverride() { return this->UserSpecifiedColorOverride; } //---------------------------------------------------------------------------- void vtkKWEPaintbrushProperty::SetHighlight( int h ) { this->Highlight = h; // Based on one of the three HighlightTypes, set the vtkProperty // appropriately. // 1. Stippled Inverted highlight .. this->Property->SetEdgeVisibility( (this->HighlightType == StippledInvertedHighlight && h == 1) ? 1 : 0 ); this->Property->SetLineStipplePattern( (this->HighlightType == StippledInvertedHighlight && h == 1) ? 0x000f : 0xffff ); // 2. Thick highlight .. this->Property->SetLineWidth(static_cast( (this->HighlightType == ThickHighlight && h == 1) ? this->HighlightThickness*this->LineWidth : this->LineWidth )); // 3. Color highlight .. this->Property->SetColor( (this->HighlightType == ColorHighlight && h == 1) ? this->HighlightColor : this->Color ); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushProperty::SetMutable( int m ) { int a = m ? 1 : 0; // Clamp to Range: [0-1] if (this->Mutable != a) { this->Mutable = a; this->PaintbrushSketch->SetMutable(a || (!this->InteractionEnabled)); this->Modified(); } } //---------------------------------------------------------------------------- int vtkKWEPaintbrushProperty::GetMutable() { return this->Mutable && (!this->InteractionEnabled); } //---------------------------------------------------------------------------- void vtkKWEPaintbrushProperty::SetInteractionEnabled( int e ) { // Do not change the modified flags here. This is called by the paintbrush // widget during interaction. if (e != this->InteractionEnabled) { this->InteractionEnabled = e; this->PaintbrushSketch->SetMutable(this->Mutable || (!this->InteractionEnabled)); } } //---------------------------------------------------------------------------- void vtkKWEPaintbrushProperty::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushGrayscaleData.h0000644000175000017500000001025611363410610023456 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef __vtkKWEPaintbrushGrayscaleData_h #define __vtkKWEPaintbrushGrayscaleData_h #include "vtkKWEPaintbrushData.h" #include "VTKEdgeConfigure.h" // Needed for export symbols directives class vtkImageData; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushGrayscaleData : public vtkKWEPaintbrushData { public: static vtkKWEPaintbrushGrayscaleData *New(); vtkTypeRevisionMacro(vtkKWEPaintbrushGrayscaleData, vtkKWEPaintbrushData); void PrintSelf(ostream& os, vtkIndent indent); void DeepCopy(vtkDataObject *o); void ShallowCopy(vtkDataObject *f); // Description: // Set/Get the image data externally.. usually the image data is created // internally during every stroke.. This method allows you to load an // external segmentation and initialize the PaintbrushData with that // segmentation. virtual void SetImageData( vtkImageData * ); vtkGetObjectMacro( ImageData, vtkImageData ); // Description: // These operators are minkowski Add/Subtract operators. The Add operator // implements a pixelwise max function. The subtract operator is a // pixelwise min function. virtual int Add( vtkKWEPaintbrushData *, bool forceMutable=false ); virtual int Subtract( vtkKWEPaintbrushData *, bool forceMutable=false ); virtual int Replace( vtkKWEPaintbrushData *, bool forceMutable=false ); virtual int Add( vtkImageData *, bool forceMutable=false ); virtual int Subtract( vtkImageData *, bool forceMutable=false ); virtual int Replace( vtkImageData *, bool forceMutable=false ); // Description: // Clip self with supplied extents. Return 1 if something changed virtual int Clip( int extent[6] ); // Description: // Allocate the grayscale image. Destroys existing data, if any virtual void Allocate( double fillValue = 0.0 ); // Description: // Resize. Unlike allocate, this will allocate to conform to the new // extents, while preserving existing data. If you are calling // Resize with the extents for the first time, this is the same as // calling // SetExtent(..) followed by Allocate(..). virtual void Resize( int extent[6], double fillValue = 0.0 ); virtual void SetSpacing(double spacing[3]); virtual void SetOrigin( double origin[3] ); // Description: // Set/Get extents. This will be the same virtual void SetExtent( int extent[6] ); virtual void GetExtent( int extent[6] ); // Description: // You can set a certain value in the grayscale data as the outside value. // Pixels with a value equal (within the specified tolerance) to the // OutsideValue will not affect the image when adding or subtract. vtkSetMacro(OutsideValue, double); vtkGetMacro(OutsideValue, double); vtkSetMacro(OutsideValueTolerance, double); vtkGetMacro(OutsideValueTolerance, double); // Description: // Is the point "p" inside ? virtual int IsInside( double p[3] ); // Description: // Get the paintbrush data as an image data.. Note.. shallow copy here of // the existing image data. virtual void GetPaintbrushDataAsImageData( vtkImageData * ); // Description: // See vtkObject for doc virtual unsigned long GetMTime(); protected: vtkKWEPaintbrushGrayscaleData(); ~vtkKWEPaintbrushGrayscaleData(); // Description: // Stores the bulk data vtkImageData *ImageData; double OutsideValue; double OutsideValueTolerance; private: vtkKWEPaintbrushGrayscaleData(const vtkKWEPaintbrushGrayscaleData&); // Not implemented. void operator=(const vtkKWEPaintbrushGrayscaleData&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushSelectionWidget.cxx0000644000175000017500000003761111363410610024422 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushSelectionWidget.h" #include "vtkKWEPaintbrushWidget.h" #include "vtkKWEPaintbrushSelectionRepresentation2D.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSketch.h" #include "vtkKWEWidgetGroup.h" #include "vtkRenderWindowInteractor.h" #include "vtkCallbackCommand.h" #include "vtkObjectFactory.h" #include "vtkRenderer.h" #include "vtkWidgetCallbackMapper.h" #include "vtkEvent.h" #include "vtkWidgetEvent.h" vtkCxxRevisionMacro(vtkKWEPaintbrushSelectionWidget, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEPaintbrushSelectionWidget); //---------------------------------------------------------------------- vtkKWEPaintbrushSelectionWidget::vtkKWEPaintbrushSelectionWidget() { this->ManagesCursor = 1; this->EnableDragAndDrop = 1; // Enable drag and drop merge by default // These are the event callbacks supported by this widget this->CallbackMapper->SetCallbackMethod( vtkCommand::LeftButtonPressEvent, vtkEvent::NoModifier, 0, 0, NULL, vtkKWEPaintbrushWidget::SelectSketchEvent, this, vtkKWEPaintbrushSelectionWidget::BeginToggleSelectSketchCallback); this->CallbackMapper->SetCallbackMethod( vtkCommand::LeftButtonReleaseEvent, vtkEvent::NoModifier, 0, 0, NULL, vtkCommand::LeftButtonReleaseEvent, this, vtkKWEPaintbrushSelectionWidget::EndToggleSelectSketchCallback); this->CallbackMapper->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::NoModifier, 47, 1, "Delete", vtkWidgetEvent::Delete, this, vtkKWEPaintbrushSelectionWidget::DeleteSelectionCallback); this->CallbackMapper->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::NoModifier, 8, 1,"BackSpace", vtkWidgetEvent::Delete, this, vtkKWEPaintbrushSelectionWidget::DeleteSelectionCallback); this->CallbackMapper->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::NoModifier, 109, 0, "m", vtkKWEPaintbrushWidget::MergeSelectionEvent, this, vtkKWEPaintbrushSelectionWidget::MergeSelectionCallback); this->CallbackMapper->SetCallbackMethod(vtkCommand::KeyPressEvent, // Ctrl+a vtkEvent::ControlModifier, 1, 0,"a", vtkKWEPaintbrushWidget::ToggleSelectAllSketchesEvent, this, vtkKWEPaintbrushSelectionWidget::ToggleSelectAllSketchesCallback); this->CallbackMapper->SetCallbackMethod(vtkCommand::MouseMoveEvent, vtkWidgetEvent::Move, this, vtkKWEPaintbrushSelectionWidget::MoveCallback); this->CreateDefaultRepresentation(); // Sketches merged are removed by default this->RemoveSketchesDuringMerge = 1; this->MergedSketch = NULL; this->WidgetState = vtkKWEPaintbrushSelectionWidget::None; } //---------------------------------------------------------------------- vtkKWEPaintbrushSelectionWidget::~vtkKWEPaintbrushSelectionWidget() { } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget::CreateDefaultRepresentation() { // Creates only the 2D rep by default for now // We will accomodate the 3D rep later. if ( ! this->WidgetRep ) { vtkKWEPaintbrushSelectionRepresentation2D *rep = vtkKWEPaintbrushSelectionRepresentation2D::New(); this->SetRepresentation(rep); rep->Delete(); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget::SetEnabled(int enabling) { if (this->Enabled == enabling) { return; // Nothing to do } vtkKWEPaintbrushSelectionRepresentation *rep = static_cast< vtkKWEPaintbrushSelectionRepresentation *>(this->WidgetRep); // Start off on a clean slate. rep->UnSelectAllSketches(); rep->SetVisibility( enabling ); this->Superclass::SetEnabled(enabling); } // The following methods are the callbacks that the widget responds to. //------------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget ::BeginToggleSelectSketchCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushSelectionWidget *self = static_cast< vtkKWEPaintbrushSelectionWidget *>(w); if (!self || self->WidgetState == Disabled) { return; } self->WidgetState = None; vtkKWEPaintbrushSelectionRepresentation *rep = static_cast< vtkKWEPaintbrushSelectionRepresentation *>(self->WidgetRep); // Request a selection. The representation is free to deny it based on // constraints of the placer etc. rep->SetInteractionState( vtkKWEPaintbrushSelectionRepresentation::PaintbrushRequestSketchSelect); int interactionState = rep->ComputeInteractionState( self->Interactor->GetEventPosition()[0], self->Interactor->GetEventPosition()[1]); if (interactionState == vtkKWEPaintbrushSelectionRepresentation:: PaintbrushSketchSelect) { // We selected some sketch. self->WidgetState = vtkKWEPaintbrushSelectionWidget::BeginSelecting; self->WidgetGroup->DispatchAction( self, &vtkKWEPaintbrushSelectionWidget::SelectSketchAction); self->EventCallbackCommand->SetAbortFlag(1); } else if (interactionState == vtkKWEPaintbrushSelectionRepresentation:: PaintbrushSketchUnselect) { // We de-selected some sketch. self->WidgetGroup->DispatchAction( self, &vtkKWEPaintbrushSelectionWidget::UnselectSketchAction); self->EventCallbackCommand->SetAbortFlag(1); } } //------------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget ::EndToggleSelectSketchCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushSelectionWidget *self = static_cast< vtkKWEPaintbrushSelectionWidget *>(w); if (!self || self->WidgetState == Disabled) { return; } self->WidgetGroup->DispatchAction( self, &vtkKWEPaintbrushSelectionWidget::ReleaseSelectAction); } //------------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget ::DeleteSelectionCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushSelectionWidget *self = static_cast< vtkKWEPaintbrushSelectionWidget *>(w); if (!self || self->WidgetState == Disabled) { return; } self->WidgetGroup->DispatchAction( self, &vtkKWEPaintbrushSelectionWidget::DeleteSelectionAction); } //------------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget ::ToggleSelectAllSketchesCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushSelectionWidget *self = static_cast< vtkKWEPaintbrushSelectionWidget *>(w); if (!self || self->WidgetState == Disabled) { return; } vtkKWEPaintbrushSelectionRepresentation *rep = static_cast< vtkKWEPaintbrushSelectionRepresentation *>(self->WidgetRep); const int nSketches = rep->GetPaintbrushDrawing()->GetNumberOfItems(); if (nSketches) { const int nSelectedSketches = static_cast(rep->GetSelectedSketches().size()); // If more than half the sketches are selected, unselect all of them. // If less than half the sketches are selected, select all of them. if (nSelectedSketches > nSketches/2) { self->UnSelectAllSketchesCallback(self); } else { self->SelectAllSketchesCallback(self); } } } //------------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget ::SelectAllSketchesCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushSelectionWidget *self = static_cast< vtkKWEPaintbrushSelectionWidget *>(w); if (!self || self->WidgetState == Disabled) { return; } self->WidgetGroup->DispatchAction( self, &vtkKWEPaintbrushSelectionWidget::SelectAllSketchesAction); } //------------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget ::UnSelectAllSketchesCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushSelectionWidget *self = static_cast< vtkKWEPaintbrushSelectionWidget *>(w); if (!self || self->WidgetState == Disabled) { return; } self->WidgetGroup->DispatchAction( self, &vtkKWEPaintbrushSelectionWidget::UnSelectAllSketchesAction); } //------------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget ::MergeSelectionCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushSelectionWidget *self = static_cast< vtkKWEPaintbrushSelectionWidget *>(w); if (!self || self->WidgetState == Disabled || !self->WidgetGroup) { return; } self->WidgetGroup->DispatchAction( self, &vtkKWEPaintbrushSelectionWidget::MergeSelectionAction); } //------------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget ::MoveCallback(vtkAbstractWidget *w) { vtkKWEPaintbrushSelectionWidget *self = static_cast< vtkKWEPaintbrushSelectionWidget *>(w); if (self->WidgetState != BeginSelecting) { return; } if (!self->EnableDragAndDrop) { return; // Ignore drag. } vtkKWEPaintbrushSelectionRepresentation *rep = static_cast< vtkKWEPaintbrushSelectionRepresentation *>(self->WidgetRep); rep->SetInteractionState( vtkKWEPaintbrushSelectionRepresentation:: PaintbrushRequestSketchMerge ); if ( rep->ComputeInteractionState( self->Interactor->GetEventPosition()[0], self->Interactor->GetEventPosition()[1]) != vtkKWEPaintbrushSelectionRepresentation::None ) { self->Render(); self->EventCallbackCommand->SetAbortFlag(1); } } //---------------------------------------------------------------------- // Actions that are dispatched from the WidgetGroup. int vtkKWEPaintbrushSelectionWidget ::SelectSketchAction(vtkKWEPaintbrushSelectionWidget *dispatcher) { vtkKWEPaintbrushSelectionRepresentation *rep = static_cast< vtkKWEPaintbrushSelectionRepresentation *>(this->WidgetRep); this->DeepCopy(dispatcher); this->Render(); this->EventCallbackCommand->SetAbortFlag(1); this->InvokeEvent(vtkKWEPaintbrushWidget::SelectSketchEvent, static_cast(rep->GetSelectedSketch()) ); return 1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionWidget ::UnselectSketchAction(vtkKWEPaintbrushSelectionWidget *dispatcher) { vtkKWEPaintbrushSelectionRepresentation *rep = static_cast< vtkKWEPaintbrushSelectionRepresentation *>(this->WidgetRep); this->DeepCopy(dispatcher); this->Render(); this->EventCallbackCommand->SetAbortFlag(1); this->InvokeEvent(vtkKWEPaintbrushWidget::UnselectSketchEvent, static_cast(rep->GetSelectedSketch()) ); return 1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionWidget ::SelectAllSketchesAction(vtkKWEPaintbrushSelectionWidget *dispatcher) { if (this == dispatcher) { vtkKWEPaintbrushSelectionRepresentation *rep = static_cast< vtkKWEPaintbrushSelectionRepresentation *>(this->WidgetRep); rep->SelectAllSketches(); } else { this->DeepCopy(dispatcher); } this->Render(); this->EventCallbackCommand->SetAbortFlag(1); this->InvokeEvent( vtkKWEPaintbrushWidget::SelectAllSketchesEvent ); return 1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionWidget ::UnSelectAllSketchesAction(vtkKWEPaintbrushSelectionWidget *dispatcher) { if (this == dispatcher) { vtkKWEPaintbrushSelectionRepresentation *rep = static_cast< vtkKWEPaintbrushSelectionRepresentation *>(this->WidgetRep); rep->UnSelectAllSketches(); } else { this->DeepCopy(dispatcher); } this->Render(); this->EventCallbackCommand->SetAbortFlag(1); this->InvokeEvent( vtkKWEPaintbrushWidget::UnSelectAllSketchesEvent ); return 1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionWidget ::ReleaseSelectAction(vtkKWEPaintbrushSelectionWidget *vtkNotUsed(dispatcher)) { if (this->WidgetState == BeginSelecting) { this->WidgetState = EndSelecting; this->EventCallbackCommand->SetAbortFlag(1); if (!this->EnableDragAndDrop) { return 0; // Ignore potential drop. } // Drag and drop merge support. vtkKWEPaintbrushSelectionRepresentation *rep = static_cast< vtkKWEPaintbrushSelectionRepresentation *>(this->WidgetRep); if (rep->GetInteractionState() == vtkKWEPaintbrushSelectionRepresentation::PaintbrushSketchMerge) { rep->DragAndDropMerge(); this->Render(); this->EventCallbackCommand->SetAbortFlag(1); } return 1; } return 0; } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionWidget ::DeleteSelectionAction(vtkKWEPaintbrushSelectionWidget *dispatcher) { vtkKWEPaintbrushSelectionRepresentation *rep = static_cast< vtkKWEPaintbrushSelectionRepresentation *>(this->WidgetRep); if (this == dispatcher) { if (rep->DeleteSelectedSketches() == 0) { return 0; // Nothing was removed.. just return. } } else { this->DeepCopy(dispatcher); } // Render only if needed. this->Render(); this->EventCallbackCommand->SetAbortFlag(1); this->InvokeEvent( vtkKWEPaintbrushWidget::DeleteSelectionEvent ); return 1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushSelectionWidget ::MergeSelectionAction(vtkKWEPaintbrushSelectionWidget *dispatcher) { vtkKWEPaintbrushSelectionRepresentation *rep = static_cast< vtkKWEPaintbrushSelectionRepresentation *>(this->WidgetRep); if (this == dispatcher) { if (rep->MergeSelectedSketches( this->MergedSketch, this->RemoveSketchesDuringMerge) == 0) { return 0; // Nothing was merged.. just return. } } else { this->DeepCopy(dispatcher); } // Render only if needed. this->Render(); this->EventCallbackCommand->SetAbortFlag(1); this->InvokeEvent( vtkKWEPaintbrushWidget::DeleteSelectionEvent ); return 1; } //------------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget::DeepCopy(vtkAbstractWidget *widget) { vtkKWEPaintbrushSelectionWidget *w = static_cast< vtkKWEPaintbrushSelectionWidget *>(widget); if (this == w || !w) { return; } this->WidgetState = w->WidgetState; if (w->WidgetGroup) { w->WidgetGroup->AddWidget(this); } if (w->WidgetRep && this->WidgetRep) { (static_cast(this->WidgetRep))-> DeepCopy(w->WidgetRep); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget::DeleteSelectedSketches() { this->WidgetGroup->DispatchAction( this, &vtkKWEPaintbrushSelectionWidget::DeleteSelectionAction); } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget ::SetRepresentation(vtkKWEPaintbrushSelectionRepresentation *r) { this->Superclass::SetWidgetRepresentation(r); } //---------------------------------------------------------------------- void vtkKWEPaintbrushSelectionWidget::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushRepresentation2D.cxx0000644000175000017500000006464211507576154024545 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushRepresentation2D.h" #include "vtkKWEPaintbrushShapeBox.h" #include "vtkKWEPaintbrushShapeEllipsoid.h" #include "vtkKWEPaintbrushOperation.h" #include "vtkKWEPaintbrushDrawing.h" #include "vtkKWEPaintbrushSelectionRepresentation2D.h" #include "vtkKWEPaintbrushBlend.h" #include "vtkKWEPaintbrushData.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushHighlightActors.h" #include "vtkKWEPaintbrushPropertyManager.h" #include "vtkKWEPaintbrushProperty.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkActor.h" #include "vtkCoordinate.h" #include "vtkRenderer.h" #include "vtkObjectFactory.h" #include "vtkInteractorObserver.h" #include "vtkMath.h" #include "vtkImageActor.h" #include "vtkImageStencilData.h" #include "vtkImageData.h" #include "vtkPolyData.h" #include "vtkCamera.h" #include "vtkPlane.h" #include "vtkKWEVoxelAlignedImageActorPointPlacer.h" #include "vtkInformationExecutivePortVectorKey.h" #include "vtkAlgorithmOutput.h" #include "vtkExecutive.h" vtkCxxRevisionMacro(vtkKWEPaintbrushRepresentation2D, "$Revision: 3301 $"); vtkStandardNewMacro(vtkKWEPaintbrushRepresentation2D); vtkCxxSetObjectMacro(vtkKWEPaintbrushRepresentation2D,ShapeOutlinePropertyDraw,vtkProperty); vtkCxxSetObjectMacro(vtkKWEPaintbrushRepresentation2D,ShapeOutlinePropertyErase,vtkProperty); vtkCxxSetObjectMacro(vtkKWEPaintbrushRepresentation2D,ShapeOutlinePropertyInteract,vtkProperty); //---------------------------------------------------------------------- vtkKWEPaintbrushRepresentation2D::vtkKWEPaintbrushRepresentation2D() { this->UseOverlay = 1; this->ImageActor = NULL; this->ImageData = NULL; this->SingleSliceThickBrush = 0; this->ShapeOutline = vtkPolyData::New(); // Create the mapper this->ShapeOutlineMapper = vtkPolyDataMapper::New(); vtkCoordinate *tcoord = vtkCoordinate::New(); tcoord->SetCoordinateSystemToWorld(); this->ShapeOutlineMapper->SetInput(this->ShapeOutline); tcoord->Delete(); // Create the actor this->ShapeOutlineActor = vtkActor::New(); this->ShapeOutlineActor->SetMapper( this->ShapeOutlineMapper ); // property->SetRepresentationToSurface(); // Create the template outline properties in draw/erase/interact modes. this->ShapeOutlinePropertyDraw = vtkProperty::New(); this->ShapeOutlinePropertyDraw->SetColor(0.7,1.0,0.0); this->ShapeOutlinePropertyDraw->SetOpacity(0.5); this->ShapeOutlinePropertyDraw->SetLineWidth( 2.0 ); this->ShapeOutlinePropertyErase = vtkProperty::New(); this->ShapeOutlinePropertyErase->SetColor(1.0,0.0,1.0); this->ShapeOutlinePropertyErase->SetOpacity(0.5); this->ShapeOutlinePropertyErase->SetLineWidth( 2.0 ); this->ShapeOutlinePropertyInteract = vtkProperty::New(); this->ShapeOutlinePropertyInteract->SetColor(1.0,1.0,0.0); this->ShapeOutlinePropertyInteract->SetOpacity(0.5); this->ShapeOutlinePropertyInteract->SetLineWidth( 2.0 ); this->ShapeOutlineActor->SetProperty(this->ShapeOutlinePropertyDraw); /* TODELETE: The ellipsoid PaintbrushShape is already defined in the * vtkKWEPaintbrushRepresentation constructor. vtkKWEPaintbrushShapeEllipsoid *paintbrushShape = vtkKWEPaintbrushShapeEllipsoid::New(); this->PaintbrushOperation->SetPaintbrushShape( paintbrushShape ); paintbrushShape->SetWidth(5.0,5.0,5.0); paintbrushShape->Delete(); */ this->PaintbrushBlend = NULL; this->CurrentShapePosition[0] = VTK_FLOAT_MIN; this->CurrentShapePosition[1] = VTK_FLOAT_MIN; this->CurrentShapePosition[2] = VTK_FLOAT_MIN; // The paintbrushes snap to the grid vtkKWEVoxelAlignedImageActorPointPlacer * v = vtkKWEVoxelAlignedImageActorPointPlacer::New(); this->SetShapePlacer(v); v->Delete(); // Used if the paintbrush goes into "select" mode. this->SelectionRepresentation = vtkKWEPaintbrushSelectionRepresentation2D::New(); this->SelectionRepresentation->SetPaintbrushDrawing(this->PaintbrushDrawing); // Highlighting stuff. Selected sketches will be highlighted. this->HighlightActors = vtkKWEPaintbrushHighlightActors::New(); this->HighlightActors->SetPaintbrushDrawing(this->PaintbrushDrawing); } //---------------------------------------------------------------------- vtkKWEPaintbrushRepresentation2D::~vtkKWEPaintbrushRepresentation2D() { this->ShapeOutline->Delete(); this->ShapeOutlineMapper->Delete(); this->ShapeOutlineActor->Delete(); this->ShapeOutlinePropertyDraw->Delete(); this->ShapeOutlinePropertyErase->Delete(); this->ShapeOutlinePropertyInteract->Delete(); if (this->PaintbrushBlend) { this->PaintbrushBlend->Delete(); } this->SetImageActor(NULL); this->SetImageData(NULL); this->SetShapePlacer(NULL); this->SelectionRepresentation->Delete(); this->HighlightActors->Delete(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::SetImageActor( vtkImageActor * imageActor ) { if (this->ImageActor != imageActor) { vtkImageActor * var = this->ImageActor; this->ImageActor = imageActor; if (this->ImageActor != NULL) { this->ImageActor->Register(this); } if (var != NULL) { var->UnRegister(this); } this->Modified(); if (this->ImageActor) { // Set the actor as the placer's actor, if it is an ImageActorPointPlacer. vtkImageActorPointPlacer * imageActorPointPlacer = vtkImageActorPointPlacer::SafeDownCast(this->ShapePlacer); if (imageActorPointPlacer) { imageActorPointPlacer->SetImageActor(this->ImageActor); } } if (vtkKWEPaintbrushSelectionRepresentation2D * selectionRep = vtkKWEPaintbrushSelectionRepresentation2D::SafeDownCast( this->SelectionRepresentation)) { selectionRep->SetImageActor(imageActor); } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::SetImageData( vtkImageData * imageData ) { if (this->ImageData != imageData) { vtkImageData * var = this->ImageData; this->ImageData = imageData; if (this->ImageData != NULL) { this->ImageData->Register(this); } if (var != NULL) { var->UnRegister(this); } this->Modified(); } if (this->ImageData) { this->PaintbrushDrawing->SetImageData( this->ImageData ); this->PaintbrushDrawing->InitializeData(); if (this->PaintbrushOperation) { this->PaintbrushOperation->SetImageData(this->ImageData); } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::SetPaintbrushOperation( vtkKWEPaintbrushOperation * filter ) { if (this->PaintbrushOperation != filter) { this->Superclass::SetPaintbrushOperation(filter); if ( this->PaintbrushOperation && this->ImageActor && !this->PaintbrushOperation->GetImageData()) { this->PaintbrushOperation->SetImageData(this->ImageActor->GetInput()); } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::CreateShapeOutline( double *pos ) { // TODO: Create a polydata that outlines the actual template.. if (!this->ImageActor) { vtkErrorMacro( << "The image actor must be set prior to overlaying the paintbrush template"); } if (this->ShapeOutline) { this->ShapeOutline->Delete(); this->ShapeOutline = NULL; } vtkImageData *image = this->ImageActor->GetInput(); if (!image) { vtkErrorMacro( << "The image actor must be set prior to overlaying the paintbrush template"); return; } this->ShapeOutline = vtkPolyData::New(); this->ShapeOutlineMapper->SetInput(this->ShapeOutline); // Rebuild the template outline. double viewPlaneNormal[3]; this->Renderer->GetActiveCamera()->GetViewPlaneNormal(viewPlaneNormal); vtkPlane *plane = vtkPlane::New(); plane->SetNormal(viewPlaneNormal); plane->SetOrigin(pos); vtkSmartPointer< vtkPolyData > pd = this->PaintbrushOperation->GetPaintbrushShape()->GetShapePolyData(pos, plane); plane->Delete(); if (pd) { this->ShapeOutline->DeepCopy(pd.GetPointer()); } this->CurrentShapePosition[0] = pos[0]; this->CurrentShapePosition[1] = pos[1]; this->CurrentShapePosition[2] = pos[2]; } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::BuildRepresentation() { this->HighlightActors->SetExtent(this->ImageActor->GetDisplayExtent()); this->HighlightActors->BuildRepresentation(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::ReleaseGraphicsResources(vtkWindow *w) { this->ShapeOutlineActor->ReleaseGraphicsResources(w); } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation2D::RenderOverlay(vtkViewport *viewport) { int count = 0; if (this->ShapeOutlineActor->GetVisibility()) { count += this->ShapeOutlineActor->RenderOverlay(viewport); } if ( this->ImageActor->GetVisibility() ) { count += this->ImageActor->RenderOverlay(viewport); } return count; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation2D::RenderOpaqueGeometry(vtkViewport *viewport) { int count = 0; this->BuildRepresentation(); if (this->ShapeOutlineActor->GetVisibility()) { count += this->ShapeOutlineActor->RenderOpaqueGeometry(viewport); } if ( this->ImageActor->GetVisibility() ) { count += this->ImageActor->RenderOpaqueGeometry(viewport); } if ( this->HighlightActors->GetVisibility() ) { count += this->HighlightActors->RenderOpaqueGeometry(viewport); } return count; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation2D::ComputeInteractionState( int vtkNotUsed(X), int vtkNotUsed(Y), int vtkNotUsed(modified)) { return this->InteractionState; } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::StartWidgetInteraction(double [2]) { } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::WidgetInteraction(double [2]) { } #if VTKEdge_VTK_VERSION_DATE > 20070305 //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation2D::RenderTranslucentPolygonalGeometry(vtkViewport *viewport) { int count=0; if ( this->ImageActor->GetVisibility() ) { count += this->ImageActor->RenderTranslucentPolygonalGeometry(viewport); } if (this->ShapeOutlineActor->GetVisibility()) { count += this->ShapeOutlineActor->RenderTranslucentPolygonalGeometry(viewport); } if ( this->HighlightActors->GetVisibility() ) { count += this->HighlightActors->RenderTranslucentPolygonalGeometry(viewport); } return count; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation2D::HasTranslucentPolygonalGeometry() { int result=0; if ( this->ShapeOutlineActor->GetVisibility() ) { result |= this->ShapeOutlineActor->HasTranslucentPolygonalGeometry(); } if ( this->ImageActor->GetVisibility() ) { result |= this->ImageActor->HasTranslucentPolygonalGeometry(); } if ( this->HighlightActors->GetVisibility() ) { result += this->HighlightActors->HasTranslucentPolygonalGeometry(); } return result; } #else //---------------------------------------------------------------------- // Legacy method to support VTK source versions prior to 2007/03/05 int vtkKWEPaintbrushRepresentation2D::RenderTranslucentGeometry(vtkViewport *viewport) { int count=0; if ( this->ImageActor->GetVisibility() ) { count += this->ImageActor->RenderTranslucentGeometry(viewport); } if (this->ShapeOutlineActor->GetVisibility()) { count += this->ShapeOutlineActor->RenderTranslucentGeometry(viewport); } if ( this->HighlightActors->GetVisibility() ) { count += this->HighlightActors->RenderTranslucentGeometry(viewport); } return count; } #endif //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation2D::ActivateShapeOutline( int x, int y ) { double displayPos[2], worldPos[3], worldOrient[9]; displayPos[0] = x; displayPos[1] = y; // Compute world pos from the display pos. if ( !this->ShapePlacer->ComputeWorldPosition( this->Renderer, displayPos, worldPos, worldOrient) ) { return -1; // Do not draw the template here. The placer told us that this // is not a valid display location. } this->LastDisplayPosition[0] = x; // bookkeeping this->LastDisplayPosition[1] = y; // If the paintbrush template has moved, draw it again at the new spot. if ( this->InteractionState == PaintbrushResize || this->InteractionState == PaintbrushIsotropicResize || vtkMath::Distance2BetweenPoints( this->CurrentShapePosition, worldPos) > 1e-5) { this->CreateShapeOutline(worldPos); return 1; } return 0; } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::AddShapeToCurrentStroke( double p[3] ) { // If we are doing a slice by slice segmentation, do a clip with the // current slice. int extent[6]; if (this->SingleSliceThickBrush) { this->ImageActor->GetDisplayExtent(extent); } else { this->ImageData->GetExtent(extent); } this->PaintbrushDrawing->GetPaintbrushOperation()-> GetPaintbrushShape()->SetClipExtent(extent); this->Superclass::AddShapeToCurrentStroke(p); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::CreateDefaultRepresentation() { } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::GetActors( vtkPropCollection * pc ) { this->ShapeOutlineActor->GetActors(pc); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::GetActors2D( vtkPropCollection * ) { // this->ShapeOutlineActor->GetActors(pc); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::SetStateToDraw() { this->ShapeOutlineActor->SetProperty(this->ShapeOutlinePropertyDraw); this->SetShapeOutlineVisibility(1); this->Superclass::SetStateToDraw(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::SetStateToErase() { this->ShapeOutlineActor->SetProperty(this->ShapeOutlinePropertyErase); this->SetShapeOutlineVisibility(1); this->Superclass::SetStateToErase(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::SetStateToInteract() { this->ShapeOutlineActor->SetProperty(this->ShapeOutlinePropertyInteract); this->SetShapeOutlineVisibility(1); this->Superclass::SetStateToInteract(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::SetStateToDisabled() { this->SetShapeOutlineVisibility(0); this->Superclass::SetStateToDisabled(); } //---------------------------------------------------------------------- // Will be called when the widget is enabled void vtkKWEPaintbrushRepresentation2D::InstallPipeline() { if (!this->ImageActor) { vtkErrorMacro( << "Cannot install pipeline before the image actor is set"); return; } if (!this->PaintbrushBlend) { this->PaintbrushBlend = vtkKWEPaintbrushBlend::New(); } // What we do here is to stick a "Blender" before the ImageActor. The blender // will blend the background image with the sketch to give us an overlay. if (!this->PipelineInstalled && this->ImageActor->GetInput() != this->PaintbrushBlend->GetOutput()) { // The "If" ensures that the pipeline has not already been installed. this->PaintbrushBlend->SetInput(this->ImageActor->GetInput()); this->ImageActor->SetInput(this->PaintbrushBlend->GetOutput()); } // Sanity check if (this->PaintbrushDrawing->GetRepresentation() != vtkKWEPaintbrushEnums::Binary && this->PaintbrushDrawing->GetRepresentation() != vtkKWEPaintbrushEnums::Label) { vtkErrorMacro( << "This class is intended to be a representation for " << "overlaying vtkKWEPaintbrushStencilData or vtkKWEPaintbrushLabelData on an " << "image, not vtkKWEPaintbrushGrayscaleData !") } // Set the overlay paintbrush stencil as input to the blender. this->PaintbrushBlend->SetPaintbrushDrawing( this->PaintbrushDrawing ); this->PaintbrushBlend->SetUseOverlay(this->UseOverlay); this->PipelineInstalled = 1; } //---------------------------------------------------------------------- // Will be called when the widget is disabled void vtkKWEPaintbrushRepresentation2D::UnInstallPipeline() { // Return if we aren't installed yet. if (!this->ImageActor || !this->PipelineInstalled || !this->PaintbrushBlend) { this->PipelineInstalled = 0; return; } this->PipelineInstalled = 0; // What we do here is undo what was done in InstallPipeline(). if (this->PaintbrushBlend->GetOutput() == this->ImageActor->GetInput()) { this->ImageActor->SetInput(static_cast (this->PaintbrushBlend->GetInput()) ); } else { // Get the consumer process object. Have the consumer's input be the // PaintbrushBlend's input. In otherwords, remove PaintbrushBlend // from the chain. vtkInformation *info = this->PaintbrushBlend->GetExecutive()-> GetOutputInformation(0); vtkExecutive ** consumers = vtkExecutive::CONSUMERS()->GetExecutives(info); int consumerCount = vtkExecutive::CONSUMERS()->Length(info); for (int consumerIdx = 0; consumerIdx < consumerCount; consumerIdx++) { if (vtkAlgorithm * consumerProcessObject = consumers[consumerIdx]->GetAlgorithm()) { // The assumption is made that PaintbrushBlend's output is always on // the first port of the consumer's. In general the consumer is another // PaintbrushBlend, or an ImageActor, the latter which is handled on // the other "if" block. consumerProcessObject->SetInputConnection( 0, this->PaintbrushBlend->GetInputConnection(0,0) ); } } } this->PaintbrushBlend->Delete(); this->PaintbrushBlend = NULL; } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D ::SetPaintbrushDrawing(vtkKWEPaintbrushDrawing *drawing) { this->Superclass::SetPaintbrushDrawing(drawing); this->HighlightActors->SetPaintbrushDrawing(drawing); } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation2D::ResizeShape(double d[3], int resizeType) { if (this->PaintbrushOperation->GetPaintbrushShape()->Resize(d, resizeType)) { this->CreateShapeOutline(this->CurrentShapePosition); return 1; } return 0; } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::DeepCopy(vtkWidgetRepresentation *rep) { if (this == rep) { return; } vtkKWEPaintbrushRepresentation2D *r = vtkKWEPaintbrushRepresentation2D::SafeDownCast(rep); if (r) { if (this->PaintbrushOperation && r->PaintbrushOperation) { this->PaintbrushOperation->DeepCopy(r->PaintbrushOperation); } } this->Superclass::DeepCopy(rep); } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::SetShapeOutlineVisibility(int v) { this->ShapeOutlineActor->SetVisibility(v); this->HighlightActors->SetVisibility(v); } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation2D::GetShapeOutlineVisibility() { return this->ShapeOutlineActor->GetVisibility(); } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation2D::IncreaseOpacity() { if (!this->PaintbrushDrawing) { return 0; } const int nSketches = this->PaintbrushDrawing->GetNumberOfItems(); int changed = 0; for (int i = 0; i < nSketches; i++) { vtkKWEPaintbrushSketch * sketch = this->PaintbrushDrawing->GetItem(i); vtkKWEPaintbrushProperty * property = sketch->GetPaintbrushProperty(); double o = property->GetOpacity(); if (o == 1.0) { continue; } property->SetOpacity(o + 0.1); changed = 1; } // "chnaged" is 1 if at least 1 shetch's property changed. return changed; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation2D::DecreaseOpacity() { if (!this->PaintbrushDrawing) { return 0; } const int nSketches = this->PaintbrushDrawing->GetNumberOfItems(); int changed = 0; for (int i = 0; i < nSketches; i++) { vtkKWEPaintbrushSketch * sketch = this->PaintbrushDrawing->GetItem(i); vtkKWEPaintbrushProperty * property = sketch->GetPaintbrushProperty(); double o = property->GetOpacity(); if (o == 0.0) { continue; } property->SetOpacity(o - 0.1); changed = 1; } // "chnaged" is 1 if at least 1 shetch's property changed. return changed; } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::GetEtchExtents( int extent[6] ) { extent[0] = extent[2] = extent[4] = 0; extent[1] = extent[3] = extent[5] = -1; // We know that the stroke can be no larger than the current shape's // etch on the image data. if (this->ImageData) { this->ImageData->GetExtent(extent); int extentShape[6]; this->PaintbrushOperation->GetPaintbrushShape()-> GetExtent(extentShape, this->CurrentShapePosition); double viewPlaneNormal[3]; this->Renderer->GetActiveCamera()->GetViewPlaneNormal(viewPlaneNormal); for (int i = 0; i < 3; i++) { if (fabs(fabs(viewPlaneNormal[i]) - 1.0) < 1e-8) { extent[2*i] = extentShape[2*i]; extent[2*i+1] = extentShape[2*i+1]; return; } } } } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation2D ::CopySketchToPreviousSlice( vtkKWEPaintbrushSketch *sketch ) { // Figure out the extents of the current slice and the next slice. if (!this->PaintbrushDrawing) { vtkErrorMacro( << "Drawing does not exist!"); return 0; } if (this->PaintbrushDrawing->GetRepresentation() != vtkKWEPaintbrushEnums::Label) { vtkErrorMacro( << "This functionality exists only for label maps now"); return 0; } // Figure out the extents of the current slice and the next slice. int currSliceExt[6], targetSliceExt[6], labelImageExtent[6]; this->ImageActor->GetDisplayExtent(currSliceExt); for (int i = 0; i < 3; i++) { targetSliceExt[2*i] = currSliceExt[2*i]; targetSliceExt[2*i+1] = currSliceExt[2*i+1]; if (currSliceExt[2*i] == currSliceExt[2*i+1]) { targetSliceExt[2*i] = currSliceExt[2*i] - 1; targetSliceExt[2*i+1] = currSliceExt[2*i+1] - 1; } } // Do a sanity check to make sure that the target extents are within the // whole extent. This may not be true if we are on the last slice. vtkKWEPaintbrushLabelData *lData = vtkKWEPaintbrushLabelData::SafeDownCast( this->PaintbrushDrawing->GetPaintbrushData()); vtkImageData *labelImage = lData->GetLabelMap(); labelImage->GetExtent(labelImageExtent); if (!vtkMath::ExtentIsWithinOtherExtent(targetSliceExt, labelImageExtent)) { return 0; } sketch->CopySketchFromExtentToExtent(currSliceExt, targetSliceExt); return 1; } //---------------------------------------------------------------------- int vtkKWEPaintbrushRepresentation2D ::CopySketchToNextSlice( vtkKWEPaintbrushSketch *sketch ) { // Figure out the extents of the current slice and the next slice. if (!this->PaintbrushDrawing) { vtkErrorMacro( << "Drawing does not exist!"); return 0; } if (this->PaintbrushDrawing->GetRepresentation() != vtkKWEPaintbrushEnums::Label) { vtkErrorMacro( << "This functionality exists only for label maps now"); return 0; } // Figure out the extents of the current slice and the next slice. int currSliceExt[6], targetSliceExt[6], labelImageExtent[6]; this->ImageActor->GetDisplayExtent(currSliceExt); for (int i = 0; i < 3; i++) { targetSliceExt[2*i] = currSliceExt[2*i]; targetSliceExt[2*i+1] = currSliceExt[2*i+1]; if (currSliceExt[2*i] == currSliceExt[2*i+1]) { targetSliceExt[2*i] = currSliceExt[2*i] + 1; targetSliceExt[2*i+1] = currSliceExt[2*i+1] + 1; } } // Do a sanity check to make sure that the target extents are within the // whole extent. This may not be true if we are on the last slice. vtkKWEPaintbrushLabelData *lData = vtkKWEPaintbrushLabelData::SafeDownCast( this->PaintbrushDrawing->GetPaintbrushData()); vtkImageData *labelImage = lData->GetLabelMap(); labelImage->GetExtent(labelImageExtent); if (!vtkMath::ExtentIsWithinOtherExtent(targetSliceExt, labelImageExtent)) { return 0; } sketch->CopySketchFromExtentToExtent(currSliceExt, targetSliceExt); return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushRepresentation2D::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushTesting.h0000644000175000017500000000714511363410610022372 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushTesting - class providing framework for Paintbrush testing // .SECTION Description // vtkKWEPaintbrushTesting provides convenience utilities for paintbrush testing // such as a 3 viewer slice viewer etc.. #ifndef __vtkKWEPaintbrushTesting_h #define __vtkKWEPaintbrushTesting_h #include "vtkImageActor.h" #include "vtkImageData.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include #include #include #include #include #include "VTKEdgeConfigure.h" // export class vtkImageViewer2; class vtkImageReader2; class vtkKWEPaintbrushWidget; class vtkSliderWidget; class vtkKWEPaintbrushTestingSliderCallback; // ------- The window class used by all examples ------------ class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushTesting : public vtkObject { public: static vtkKWEPaintbrushTesting* New(); vtkTypeRevisionMacro(vtkKWEPaintbrushTesting,vtkObject); // Description: // Initialize() must be called before Run() void Initialize(); int Run(); // Description: // Filename of the data to be loaded. vtkSetStringMacro( Filename ); vtkGetStringMacro( Filename ); // Description: // Default is a single render window. However you can display // Axial, Sagittal, Coronal, Blank render windows simultaneously vtkSetMacro( FourPaneView, int ); vtkGetMacro( FourPaneView, int ); vtkBooleanMacro( FourPaneView, int ); // Description: // Get the image actors vtkImageActor * GetAxialImageActor() { return this->GetNthImageActor(0); } vtkImageActor * GetCoronalImageActor() { return this->GetNthImageActor(1); } vtkImageActor * GetSagittalImageActor() { return this->GetNthImageActor(2); } vtkImageActor * GetNthImageActor( int i ); vtkImageViewer2 * GetNthImageViewer( int i ) { return this->ImageViewer[i]; } // Description: // Set/Get the input image data that the actors are showing. This may be // set explicitly as below, or may be supplied via a user-argument to the // example application as "--data somefile.mha" . If no input is specified, // a default head MRI image is loaded up. vtkGetObjectMacro( Input, vtkImageData ); virtual void SetInput( vtkImageData * ); protected: vtkKWEPaintbrushTesting(); ~vtkKWEPaintbrushTesting(); vtkImageViewer2 *ImageViewer[3]; vtkKWEPaintbrushTestingSliderCallback *SliderCallbacks[3]; vtkSliderWidget *SliderWidget[3]; vtkImageData *Input; char * Filename; int FourPaneView; void GetValidReader( vtkImageReader2 * & reader, const char * filename); private: vtkKWEPaintbrushTesting(const vtkKWEPaintbrushTesting&); // Not implemented. void operator=(const vtkKWEPaintbrushTesting&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEITKFilterModule.h0000644000175000017500000001266311363410610021661 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #ifndef _vtkKWEITKFilterModule_h #define _vtkKWEITKFilterModule_h #include "VTKEdgeConfigure.h" // Needed for export symbols #include "itkVTKImageToImageFilter.h" #include "itkImageToVTKImageFilter.h" #include "vtkKWEITKFilterModuleBase.h" #include "itkImage.h" #include "vtkImageData.h" #include #include namespace vtkitk { template class FilterModule : public FilterModuleBase { public: // Instantiate the image types typedef TFilterType FilterType; typedef typename FilterType::InputImageType InputImageType; typedef typename FilterType::OutputImageType OutputImageType; typedef typename InputImageType::PixelType InputPixelType; typedef typename OutputImageType::PixelType OutputPixelType; itkStaticConstMacro( Dimension, unsigned int, itk::GetImageDimension< InputImageType >::ImageDimension ); typedef itk::VTKImageToImageFilter< InputImageType > ImportFilterType; typedef itk::ImageToVTKImageFilter< OutputImageType > ExportFilterType; typedef typename InputImageType::SizeType SizeType; typedef typename InputImageType::IndexType IndexType; typedef typename InputImageType::RegionType RegionType; /** Constructor */ FilterModule() { this->m_ImportFilter = ImportFilterType::New(); this->m_ExportFilter = ExportFilterType::New(); this->m_Filter = FilterType::New(); //this->m_Filter->ReleaseDataFlagOn(); // Set the Observer for updating progress in the GUI this->m_Filter->AddObserver( itk::ProgressEvent(), this->GetCommandObserver() ); this->m_Filter->AddObserver( itk::StartEvent(), this->GetCommandObserver() ); this->m_Filter->AddObserver( itk::EndEvent(), this->GetCommandObserver() ); this->m_LetITKAllocateOutputMemory = false; } /** Destructor */ virtual ~FilterModule() { } /** Give access to the input image */ void SetInput(vtkImageData * image) { this->m_ImportFilter->SetInput(image); } /** Give access to the input image */ virtual vtkImageData* GetInput() { return this->m_ImportFilter->GetInput(); } /** Return a pointer to the internal filter */ FilterType * GetFilter() { return this->m_Filter.GetPointer(); } void SetLetITKAllocateOutputMemory(bool s) { this->m_LetITKAllocateOutputMemory = s; } // FIXME: We are so busted when doing this for multi-component data. // It won't even frickin compile. void SetOutputBuffer( void * buffer ) { this->m_LetITKAllocateOutputMemory = false; RegionType region = this->m_Filter->GetOutput()->GetLargestPossibleRegion(); const unsigned long nPixels = region.GetNumberOfPixels(); this->m_Filter->GetOutput()->SetImportPointer( static_cast< OutputPixelType * >(buffer), nPixels ); this->m_Filter->GetOutput()->Allocate( ); // TODO Check if necessary } /** Update performs the actual filtering on the data */ virtual void Update() { // Progress reporting this->InitializeProgressValue(); this->SetCurrentFilterProgressWeight( 1.0 ); // Update the filter try { this->m_ImportFilter->Update(); } catch( itk::ProcessAborted & e) { std::cerr << "ITK error " << e.what() << std::endl; } // Update the filter try { this->m_Filter->SetInput( this->m_ImportFilter->GetOutput() ); this->m_Filter->Update(); } catch( itk::ProcessAborted & e) { std::cerr << "ITK error " << e.what() << std::endl; } // Update the exporter try { this->m_ExportFilter->SetInput( this->m_Filter->GetOutput() ); this->m_ExportFilter->Update(); } catch( itk::ProcessAborted & e) { std::cerr << "ITK error " << e.what() << std::endl; } } vtkImageData * GetOutput() { return this->m_ExportFilter->GetOutput(); } virtual void SetRequestedExtent( int extent[6] ) { SizeType size; size[0] = extent[1] - extent[0] + 1; size[1] = extent[3] - extent[2] + 1; size[2] = extent[5] - extent[4] + 1; IndexType index; index[0] = extent[0]; index[1] = extent[2]; index[2] = extent[4]; RegionType region(index,size); this->m_Filter->GetOutput()->SetRegions( region ); this->m_ExportFilter->GetOutput()->SetUpdateExtent(extent); } protected: typename ImportFilterType::Pointer m_ImportFilter; typename FilterType::Pointer m_Filter; bool m_LetITKAllocateOutputMemory; typename ExportFilterType::Pointer m_ExportFilter; }; } // end namespace vtkitk #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushUtilities.h0000644000175000017500000002477311363410610022736 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEPaintbrushUtilities - helper class to cram unrelated functions. // .SECTION Description // Helper class to cram unclassifiable functions.. // // All methods here are of course static #ifndef __vtkKWEPaintbrushUtilities_h #define __vtkKWEPaintbrushUtilities_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkObject.h" #include "vtkImageData.h" #include "vtkImageStencilData.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushLabelData.h" #include "vtkImageIterator.h" #include "vtkSmartPointer.h" #include #include class vtkImageData; class vtkImageStencilData; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushUtilities: public vtkObject { public: static vtkKWEPaintbrushUtilities * New(); vtkTypeRevisionMacro(vtkKWEPaintbrushUtilities, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Returns 0 if the extents don't intersect, 1 if they do interesect // extent contains the intersection of extent1 and extent2. static int GetIntersectingExtents( int extent1[6], int extent2[6], int extent[6]); //BTX // Description: // These functors provide the ability to do boolean operations on input data // so as to convert imagedata to segmentations. They can be used to create // multiple stencils from a label-map, by saying // vtkImageStencilData *s1 = vtkImageStencilData::New(); // vtkImageStencilData *s2 = vtkImageStencilData::New(); // vtkImageStencilData *s3 = vtkImageStencilData::New(); // GetStencilFromImage< vtkFunctorEqualTo >( labelMapImage, s1, 64.0 ); // GetStencilFromImage< vtkFunctorEqualTo >( labelMapImage, s2, 128.0 ); // GetStencilFromImage< vtkFunctorEqualTo >( labelMapImage, s3, 192.0 ); class vtkFunctorEqualTo { public: inline bool operator()( const double &a, const double &b ) { return (a == b); } }; class vtkFunctorGreaterThanEqualTo { public: inline bool operator()( const double &a, const double &b ) { return (a >= b); } }; class vtkFunctorGreaterThan { public: inline bool operator()( const double &a, const double &b ) { return (a > b); } }; class vtkFunctorLessThan { public: inline bool operator()( const double &a, const double &b ) { return (a < b); } }; class vtkFunctorLessThanEqualTo { public: inline bool operator()( const double &a, const double &b ) { return (a < b); } }; template < class TFunctor, class T > static void vtkKWEPaintbrushUtilitiesGetStencilFromImage( vtkImageData *image, vtkImageStencilData *stencilData, T threshold) { TFunctor f; int extent[6]; double spacing[3], origin[3]; image->GetExtent(extent); image->GetSpacing(spacing); image->GetOrigin(origin); stencilData->SetExtent(extent); stencilData->SetSpacing(spacing); stencilData->SetOrigin(origin); stencilData->AllocateExtents(); vtkImageIterator< T > it(image, extent); int ends[2], index[3]; index[1] = extent[2]; index[2] = extent[4]; while( !it.IsAtEnd() ) { T *inSI = it.BeginSpan(); T *inSIEnd = it.EndSpan(); index[0] = extent[0]; ends[0] = -1; ends[1] = -1; if (f(static_cast(*inSI), static_cast(threshold))) { ends[0] = extent[0]; } // for each row while (inSI != inSIEnd) { if (ends[0] == -1 && f(static_cast(*inSI), static_cast(threshold))) { // look for start ends[0] = index[0]; ++index[0]; ++inSI; continue; } if (ends[0] != -1 && ends[1] == -1 && !f(static_cast(*inSI), static_cast(threshold))) { ends[1] = index[0]; stencilData->InsertNextExtent(ends[0], ends[1]-1, index[1], index[2]); ends[0] = ends[1] = -1; } ++index[0]; ++inSI; } if (f(static_cast(*(inSI-1)), static_cast(threshold))) // ends[0] can't be -1, ends[1] has to be -1 { stencilData->InsertNextExtent(ends[0], extent[1], index[1], index[2]); } it.NextSpan(); if (index[1] == extent[3]) { ++index[2]; index[1] = extent[2]; } else { ++index[1]; } } } template< class T > static vtkstd::map< vtkKWEPaintbrushEnums::LabelType, vtkSmartPointer< vtkKWEPaintbrushStencilData > > vtkKWEPaintbrushUtilitiesGetStencilsFromImage( vtkImageData *image, vtkstd::vector< vtkKWEPaintbrushEnums::LabelType > labels, T ) { int extent[6]; double spacing[3], origin[3]; image->GetExtent(extent); image->GetSpacing(spacing); image->GetOrigin(origin); vtkstd::map< vtkKWEPaintbrushEnums::LabelType, vtkSmartPointer< vtkKWEPaintbrushStencilData > > pstrokeDatas; vtkstd::map< vtkKWEPaintbrushEnums::LabelType, vtkSmartPointer< vtkImageStencilData > > strokeDatas; for (vtkstd::vector< vtkKWEPaintbrushEnums::LabelType >::const_iterator lit = labels.begin(); lit != labels.end(); ++lit) { vtkKWEPaintbrushEnums::LabelType l = *lit; pstrokeDatas[l] = vtkSmartPointer< vtkKWEPaintbrushStencilData >::New(); pstrokeDatas[l]->SetLabel(*lit); pstrokeDatas[l]->SetExtent(extent); pstrokeDatas[l]->SetSpacing(spacing); pstrokeDatas[l]->SetOrigin(origin); pstrokeDatas[l]->Allocate(); strokeDatas[l] = pstrokeDatas[l]->GetImageStencilData(); } vtkImageIterator< T > it(image, extent); int ends[2], index[3]; index[1] = extent[2]; index[2] = extent[4]; vtkKWEPaintbrushEnums::LabelType label = vtkKWEPaintbrushLabelData::NoLabelValue; while( !it.IsAtEnd() ) { T *inSI = it.BeginSpan(); T *inSIEnd = it.EndSpan(); index[0] = extent[0]; ends[0] = -1; ends[1] = -1; // for each row while (inSI != inSIEnd) { if (ends[0] == -1 && *inSI != vtkKWEPaintbrushLabelData::NoLabelValue) { // look for start ends[0] = index[0]; ++index[0]; label = static_cast< vtkKWEPaintbrushEnums::LabelType >(*inSI); ++inSI; continue; } if (ends[0] != -1 && ends[1] == -1 && *inSI != label) { ends[1] = index[0]; strokeDatas[label]->InsertNextExtent(ends[0], ends[1]-1, index[1], index[2]); ends[0] = ends[1] = -1; if (*inSI != vtkKWEPaintbrushLabelData::NoLabelValue) { ends[0] = index[0]; label = static_cast< vtkKWEPaintbrushEnums::LabelType >(*inSI); } } ++index[0]; ++inSI; } if (ends[0] != -1 && ends[1] == -1) // ends[0] can't be -1, ends[1] has to be -1 { strokeDatas[label]->InsertNextExtent(ends[0], extent[1], index[1], index[2]); } it.NextSpan(); if (index[1] == extent[3]) { ++index[2]; index[1] = extent[2]; } else { ++index[1]; } } return pstrokeDatas; } // Description: // Get a binary stencil from an image. All pixels threshold are // considered within the stencil. // // TFunctor may be any of the above defined class templates or your own. // It may be any one of <= == >= > < operators. // It should be a templated class that will provide a mechanism of // comparing with the threshold and return a boolean. Common templates // for greater-than / less-than etc are already provided. template < class TFunctor > static void GetStencilFromImage( vtkImageData * image, vtkImageStencilData * stencilData, double threshold ) { switch (image->GetScalarType()) { vtkTemplateMacro( vtkKWEPaintbrushUtilitiesGetStencilFromImage< TFunctor >( image, stencilData, static_cast(threshold))); } } static vtkstd::map< vtkKWEPaintbrushEnums::LabelType, vtkSmartPointer< vtkKWEPaintbrushStencilData > > GetStencilsFromImage( vtkImageData * image, vtkstd::vector< vtkKWEPaintbrushEnums::LabelType > labels) { typedef vtkstd::map< vtkKWEPaintbrushEnums::LabelType, vtkSmartPointer< vtkKWEPaintbrushStencilData > > StrokeToLabelMapType; StrokeToLabelMapType r; switch (image->GetScalarType()) { vtkTemplateMacro( (r = vtkKWEPaintbrushUtilitiesGetStencilsFromImage( image, labels, static_cast(0)))); } return r; } // Description: // Populate a vtkImageData from a binary stencil. // "inVal" and "outVal" define the values assigned to the image inside and // outside the object. If "UseImageExtent" is true, the image extents are // preserved. If not, the image acquires its metadata from the stencil. static void GetImageFromStencil( vtkImageData *, vtkImageStencilData *, unsigned char inVal, unsigned char outVal, bool UseImageExtent = false ); //ETX // Description: // Check if one extent is equal to the other extent. Returns 1 if true. static int ExtentIsEqualToExtent( int e1[6], int e2[6] ); protected: vtkKWEPaintbrushUtilities(); ~vtkKWEPaintbrushUtilities(); private: vtkKWEPaintbrushUtilities(const vtkKWEPaintbrushUtilities &); // Not implemented void operator=(const vtkKWEPaintbrushUtilities &); // Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEITKConnectedThresholdPaintbrushOperation.h0000644000175000017500000000431711363410610026763 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= // .NAME vtkKWEITKConnectedThresholdPaintbrushOperation - // .SECTION Description // This is an abstract base class. // .SECTION See Also #ifndef __vtkKWEITKConnectedThresholdPaintbrushOperation_h #define __vtkKWEITKConnectedThresholdPaintbrushOperation_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkKWEITKPaintbrushOperation.h" class vtkImageStencilData; class VTKEdge_WIDGETS_EXPORT vtkKWEITKConnectedThresholdPaintbrushOperation : public vtkKWEITKPaintbrushOperation { public: // Description: // Instantiate this class. static vtkKWEITKConnectedThresholdPaintbrushOperation *New(); // Description: // Standard methods for instances of this class. vtkTypeRevisionMacro(vtkKWEITKConnectedThresholdPaintbrushOperation, vtkKWEITKPaintbrushOperation); void PrintSelf(ostream& os, vtkIndent indent); protected: vtkKWEITKConnectedThresholdPaintbrushOperation(); ~vtkKWEITKConnectedThresholdPaintbrushOperation(); // Description: // See superclass Doc virtual void DoOperationOnStencil(vtkImageStencilData *, double p[3]); virtual void DoOperation( vtkKWEPaintbrushData *, double p[3], vtkKWEPaintbrushEnums::OperationType & op ); private: vtkKWEITKConnectedThresholdPaintbrushOperation( const vtkKWEITKConnectedThresholdPaintbrushOperation&); //Not implemented void operator=(const vtkKWEITKConnectedThresholdPaintbrushOperation&); //Not implemented }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEITKFilterModuleStencilOutput.txx0000644000175000017500000001562211363410610025016 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEITKFilterModuleStencilOutput.h" namespace vtkitk { template < class TFilterType > FilterModuleStencilOutput< TFilterType >::FilterModuleStencilOutput() { } template < class TFilterType > FilterModuleStencilOutput< TFilterType >::~FilterModuleStencilOutput() { } template < class TFilterType > int FilterModuleStencilOutput< TFilterType > ::GetOutputAsStencil( vtkImageStencilData * stencilData ) { if ( this->m_ExportFilter->GetOutput()->GetNumberOfScalarComponents() != 1 || this->m_ExportFilter->GetOutput()->GetScalarType() != VTK_UNSIGNED_CHAR ) { return 0; } // Convert the output to a stencil. vtkImageData * image = this->m_ExportFilter->GetOutput(); int extent[6]; double spacing[3], origin[3]; image->GetExtent(extent); image->GetSpacing(spacing); image->GetOrigin(origin); // Allocate stencil extents stencilData->SetExtent(extent); stencilData->SetSpacing(spacing); stencilData->SetOrigin(origin); stencilData->AllocateExtents(); vtkImageIterator< unsigned char > it(image, extent); int ends[2], index[3]; index[1] = extent[2]; index[2] = extent[4]; while( !it.IsAtEnd() ) { unsigned char *inSI = it.BeginSpan(); unsigned char *inSIEnd = it.EndSpan(); index[0] = extent[0]; // for each row while ( inSI < inSIEnd ) { // Skip until find a valid pixel while( inSI < inSIEnd && *inSI == 0) { ++index[0]; ++inSI; } if( inSI < inSIEnd ) { ends[0] = index[0]; // first valid pixel ++index[0]; ++inSI; // Skip until find an invalid pixel while( inSI < inSIEnd && *inSI != 0) { ++index[0]; ++inSI; } // Only use valid pixels ends[1] = index[0]-1; stencilData->InsertNextExtent(ends[0], ends[1], index[1], index[2]); if( inSI < inSIEnd ) { ++index[0]; ++inSI; } } } it.NextSpan(); if (index[1] == extent[3]) { ++index[2]; index[1] = extent[2]; } else { ++index[1]; } } return 1; } template < class TFilterType > int FilterModuleStencilOutput< TFilterType > ::GetSphereBoundedOutputAsStencil( vtkImageStencilData * stencilData, int center[3], double radius[3] ) { if ( this->m_ExportFilter->GetOutput()->GetNumberOfScalarComponents() != 1 || this->m_ExportFilter->GetOutput()->GetScalarType() != VTK_UNSIGNED_CHAR ) { return 0; } // Convert the output to a stencil. vtkImageData * image = this->m_ExportFilter->GetOutput(); int extent[6]; double spacing[3], origin[3]; image->GetExtent(extent); image->GetSpacing(spacing); image->GetOrigin(origin); // Allocate stencil extents stencilData->SetExtent(extent); stencilData->SetSpacing(spacing); stencilData->SetOrigin(origin); stencilData->AllocateExtents(); vtkImageIterator< unsigned char > it(image, extent); int ends[2], index[3]; index[1] = extent[2]; index[2] = extent[4]; double lengthSq[3]; // BUG: Center of extent is not necessarily the brush center. // At edges, extent is clipped. lengthSq[1] = (double)((index[1]-center[1]) * (index[1]-center[1])) /(radius[1] * radius[1]); lengthSq[2] = (double)((index[2]-center[2]) * (index[2]-center[2])) /(radius[2] * radius[2]); while( !it.IsAtEnd() ) { unsigned char *inSI = it.BeginSpan(); unsigned char *inSIEnd = it.EndSpan(); index[0] = extent[0]; // for each row double len2; while ( inSI < inSIEnd ) { lengthSq[0] = (double)((index[0]-center[0]) * (index[0]-center[0])) /(radius[0] * radius[0]); len2 = (lengthSq[0]+lengthSq[1]+lengthSq[2]); // Skip until inside the circle while( inSI < inSIEnd && len2 > 1.0 ) { ++index[0]; ++inSI; lengthSq[0] = (double)((index[0]-center[0]) * (index[0]-center[0])) /(radius[0] * radius[0]); len2 = (lengthSq[0]+lengthSq[1]+lengthSq[2]); } // Skip until find a valid pixel while( inSI < inSIEnd && *inSI == 0 && len2 <= 1.0 ) { ++index[0]; ++inSI; lengthSq[0] = (double)((index[0]-center[0]) * (index[0]-center[0])) /(radius[0] * radius[0]); len2 = (lengthSq[0]+lengthSq[1]+lengthSq[2]); } if( inSI < inSIEnd && len2 <= 1.0 ) { ends[0] = index[0]; // first valid pixel ++index[0]; ++inSI; lengthSq[0] = (double)((index[0]-center[0]) * (index[0]-center[0])) /(radius[0] * radius[0]); len2 = (lengthSq[0]+lengthSq[1]+lengthSq[2]); // Skip until find an invalid pixel while( inSI < inSIEnd && *inSI != 0 && len2 <= 1.0 ) { ++index[0]; ++inSI; lengthSq[0] = (double)((index[0]-center[0]) * (index[0]-center[0])) /(radius[0] * radius[0]); len2 = (lengthSq[0]+lengthSq[1]+lengthSq[2]); } // Only use valid pixels ends[1] = index[0]-1; stencilData->InsertNextExtent(ends[0], ends[1], index[1], index[2]); if( inSI < inSIEnd && len2 <= 1.0 ) { ++index[0]; ++inSI; lengthSq[0] = (double)((index[0]-center[0]) * (index[0]-center[0])) /(radius[0] * radius[0]); len2 = (lengthSq[0]+lengthSq[1]+lengthSq[2]); } } } it.NextSpan(); if (index[1] == extent[3]) { ++index[2]; lengthSq[2] = (double)((index[2]-center[2]) * (index[2]-center[2])) /(radius[2]*radius[2]); index[1] = extent[2]; lengthSq[1] = (double)((index[1]-center[1]) * (index[1]-center[1])) /(radius[1]*radius[1]); } else { ++index[1]; lengthSq[1] = (double)((index[1]-center[1]) * (index[1]-center[1])) /(radius[1]*radius[1]); } } return 1; } } // end namespace vtkitk vtkedge-0.2.0~20110819/Widgets/vtkKWEPaintbrushData.h0000644000175000017500000001035711567177014021643 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2008 Kitware, Inc. // // VTKEdge may be used under the terms of the GNU General Public License // version 3 as published by the Free Software Foundation and appearing in // the file LICENSE.txt included in the top level directory of this source // code distribution. Alternatively you may (at your option) use any later // version of the GNU General Public License if such license has been // publicly approved by Kitware, Inc. (or its successors, if any). // // VTKEdge is distributed "AS IS" with NO WARRANTY OF ANY KIND, INCLUDING // THE WARRANTIES OF DESIGN, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR // PURPOSE. See LICENSE.txt for additional details. // // VTKEdge is available under alternative license terms. Please visit // vtkedge.org or contact us at kitware@kitware.com for further information. // //============================================================================= #ifndef __vtkKWEPaintbrushData_h #define __vtkKWEPaintbrushData_h #include "VTKEdgeConfigure.h" // needed for export symbols directives #include "vtkKWEPaintbrushEnums.h" #include "vtkDataObject.h" class vtkImageData; class VTKEdge_WIDGETS_EXPORT vtkKWEPaintbrushData : public vtkDataObject { public: vtkTypeRevisionMacro(vtkKWEPaintbrushData, vtkDataObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Minkowski operators. Return 1 if something changed. virtual int Add( vtkKWEPaintbrushData *, bool forceMutable=false ) = 0; virtual int Subtract( vtkKWEPaintbrushData *, bool forceMutable=false ) = 0; virtual int Replace( vtkKWEPaintbrushData *, bool forceMutable=false ) = 0; // Description: // Clip self with supplied extents. Return 1 if something changed virtual int Clip( int extent[6] ) = 0; // Description: // Set/Get extents. virtual void SetExtent( int extent[6] ) = 0; virtual void GetExtent( int extent[6] ) = 0; // Description: // Allocate the bulk data (once you've set the extents). virtual void Allocate( double fillValue = 0.0 ) = 0; // Description: // Metadata. virtual void SetSpacing(double spacing[3]) = 0; virtual void SetOrigin( double origin[3] ) = 0; // Description: // Is the point "p" inside ? virtual int IsInside( double p[3] ) = 0; // Description: // Get the brush data as an image data. Note that for grayscale brushes, // this is just a shallow copy of the data. For binary brushes, this // converts from the internal representation to an image data. virtual void GetPaintbrushDataAsImageData( vtkImageData * ) = 0; // Description: // Get the data type as an integer (this will return VTK_DATA_OBJECT // for now, maybe a proper type constant will be reserved later). int GetDataObjectType() { return VTK_DATA_OBJECT; } // Description: // The extent type is 3D, just like vtkImageData. int GetExtentType() { return VTK_3D_EXTENT; }; // Description: // INTERNAL - Do not use. void SetLabel(vtkKWEPaintbrushEnums::LabelType l) { this->Label = l; } vtkGetMacro( Label, vtkKWEPaintbrushEnums::LabelType ); // Description: // Clear data corresponding to a label. // - For vtkKWEPaintbrushStencilData, labels make no sense, since the data is // binary. So Clear(.) <==> Allocate() // - For vtkKWEPaintbrushGrayscaleData, labels make no sense. So // Clear(.) <==> Allocate(0.0) // - For vtkKWEPaintbrushLabelData, this sets all the voxels with the supplied // label value to 0. virtual void Clear( vtkKWEPaintbrushEnums::LabelType label ); // Description: // INTERAL - Do not use. // This is internally called to compute deltas for the Undo-Redo guys void SetComputeDelta( int i ) { this->ComputeDelta = i; } int GetComputeDelta() { return this->ComputeDelta; } protected: vtkKWEPaintbrushData(); ~vtkKWEPaintbrushData(); // Relevant only for vtkKWEPaintbrushStencilData when editing into label maps. vtkKWEPaintbrushEnums::LabelType Label; int ComputeDelta; private: vtkKWEPaintbrushData(const vtkKWEPaintbrushData&); // Not implemented. void operator=(const vtkKWEPaintbrushData&); // Not implemented. }; #endif vtkedge-0.2.0~20110819/Widgets/vtkKWEITKConfidenceConnectedPaintbrushOperation.cxx0000644000175000017500000001354411363410610027441 0ustar mathieumathieu//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEITKConfidenceConnectedPaintbrushOperation.h" #include "vtkKWEITKConfidenceConnectedImageFilter.h" #include "vtkKWEPaintbrushStroke.h" #include "vtkKWEPaintbrushShape.h" #include "vtkImageStencilData.h" #include "vtkKWEPaintbrushStencilData.h" #include "vtkKWEPaintbrushGrayscaleData.h" #include "vtkObjectFactory.h" #include "vtkImageExtractComponents.h" #include "vtkExtractVOI.h" #include "vtkKWEPaintbrushUtilities.h" vtkCxxRevisionMacro(vtkKWEITKConfidenceConnectedPaintbrushOperation, "$Revision: 1774 $"); vtkStandardNewMacro(vtkKWEITKConfidenceConnectedPaintbrushOperation); //---------------------------------------------------------------------- vtkKWEITKConfidenceConnectedPaintbrushOperation::vtkKWEITKConfidenceConnectedPaintbrushOperation() { } //---------------------------------------------------------------------- vtkKWEITKConfidenceConnectedPaintbrushOperation::~vtkKWEITKConfidenceConnectedPaintbrushOperation() { } template< class T > int PaintbrushRunner( vtkKWEITKConfidenceConnectedPaintbrushOperation * self, double center[3], vtkImageStencilData *stencil, T ) { self->InternalFilter = NULL; typedef vtkitk::vtkKWEITKConfidenceConnectedImageFilter< T > PaintbrushFilterType; typename PaintbrushFilterType::Pointer filter = PaintbrushFilterType::New(); self->InternalFilter = filter; // Set the update region to a certain region on either side of the center int extent[6], imageExtent[6]; double spacing[3], origin[3]; self->GetImageData()->GetSpacing(spacing); self->GetImageData()->GetExtent(imageExtent); // Set the center and radius to mask out a spherical stencil, instead of // one with rectangular jagged edges. self->GetImageData()->GetOrigin(origin); double radiusFactor = 10.0 * spacing[0]; int xyz[3] = { (int)(center[0]/spacing[0] + 0.5), (int)(center[1]/spacing[1] + 0.5), (int)(center[2]/spacing[2] + 0.5) }; double radius[3] = { radiusFactor/spacing[0], radiusFactor/spacing[1], radiusFactor/spacing[2] }; extent[0] = (int)((center[0] - radiusFactor)/spacing[0] + 0.5); extent[1] = (int)((center[0] + radiusFactor)/spacing[0] + 0.5); extent[2] = (int)((center[1] - radiusFactor)/spacing[1] + 0.5); extent[3] = (int)((center[1] + radiusFactor)/spacing[1] + 0.5); extent[4] = (int)((center[2] - radiusFactor)/spacing[2] + 0.5); extent[5] = (int)((center[2] + radiusFactor)/spacing[2] + 0.5); vtkKWEPaintbrushUtilities::GetIntersectingExtents(extent, imageExtent, extent); // Despite the fact that the FilterModule framework supports updates on // requested extents, a lot of filters in ITK (such as the // ConfidenceConnectedImageFilter don't really support updating a subextent. // So in most cases, you will have to extract a VOI). vtkExtractVOI *extractVOI = vtkExtractVOI::New(); extractVOI->SetInput( self->GetImageData()); extractVOI->SetVOI(extent); // Extract the first component vtkImageExtractComponents * extractComponent = vtkImageExtractComponents::New(); extractComponent->SetInput( extractVOI->GetOutput() ); extractComponent->GetOutput()->SetUpdateExtent( extent ); extractComponent->SetComponents(0); extractComponent->Update(); filter->SetRequestedExtent(extent); // This is the filter that does most of the work. This is where most of the // time for this operation is spent filter->SetInput( extractComponent->GetOutput() ); filter->AddSeed( xyz ); filter->SetRequestedExtent(extent); filter->Update(); filter->BoundWithRadiusOn(); filter->SetCenter( xyz ); filter->SetRadius( radius ); filter->GetOutputAsStencil(stencil); extractComponent->Delete(); extractVOI->Delete(); return 1; } //---------------------------------------------------------------------- void vtkKWEITKConfidenceConnectedPaintbrushOperation:: DoOperationOnStencil(vtkImageStencilData *stencilData, double p[3]) { this->PaintbrushShape->GetStencil( stencilData, p); vtkImageStencilData * stencil = vtkImageStencilData::New(); switch (this->ImageData->GetScalarType()) { vtkitkTemplateMacro( PaintbrushRunner( this, p, stencil, static_cast< VTK_TT >(0))); default: { vtkErrorMacro(<< "vtkKWEITKConfidenceConnectedPaintbrushOperation: Unknown ScalarType"); break; } } stencilData->Add(stencil); stencil->Delete(); } //---------------------------------------------------------------------- void vtkKWEITKConfidenceConnectedPaintbrushOperation:: DoOperation( vtkKWEPaintbrushData *data, double p[3], vtkKWEPaintbrushEnums::OperationType & op ) { op = vtkKWEPaintbrushEnums::Add; // The paintbrush data can be binary or grayscale. Invoke the appropriate // filtering operation in each case. if (vtkKWEPaintbrushStencilData *sdata = vtkKWEPaintbrushStencilData::SafeDownCast(data)) { this->DoOperationOnStencil( sdata->GetImageStencilData(), p ); } } //---------------------------------------------------------------------- void vtkKWEITKConfidenceConnectedPaintbrushOperation::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); }