diff --git a/CMake/SuperBuild/External_VTK.cmake b/CMake/SuperBuild/External_VTK.cmake index f5f7b37b3afc58d3244f672cd2c2104374a3ff46..395eb7deda86a78ece3bdb17687eb5291b07dcdc 100644 --- a/CMake/SuperBuild/External_VTK.cmake +++ b/CMake/SuperBuild/External_VTK.cmake @@ -2,8 +2,9 @@ # Copyright 2015 by Kitware and RPI. See toplevel LICENSE.txt for details. ########################################################################### -set(VTK_VERSION_NUM 6.2) -set(VTK_TAG v${VTK_VERSION_NUM}.0) +set(VTK_VERSION_NUM 6.3) +# set(VTK_TAG v${VTK_VERSION_NUM}.0) +set(VTK_TAG 47425ee694df750be696b0f6ade9a8dc4fe0b652) set(VTK_REPOSITORY https://gitlab.kitware.com/vtk/vtk.git) # Make sure this file is included only once @@ -83,5 +84,5 @@ else() SimMedTKEmptyExternalProject(${proj} "${${proj}_DEPENDENCIES}") endif() -set(SimMedTK_CMAKE_INCLUDE_PATH ${CMAKE_BINARY_DIR}/SuperBuild/${proj}/include/${sep}${SimMedTK_CMAKE_INCLUDE_PATH}) +set(SimMedTK_CMAKE_INCLUDE_PATH ${CMAKE_BINARY_DIR}/SimMedTK-build/include/vtk-${VTK_VERSION_NUM}/${sep}${SimMedTK_CMAKE_INCLUDE_PATH}) list(APPEND SimMedTK_SUPERBUILD_EP_ARGS -DVTK_DIR:PATH=${${proj}_DIR}) diff --git a/CMakeLists.txt b/CMakeLists.txt index 11da74f454940b82b207107afd740602efa3230d..53faad69a6136655d41c0ede99e818f86bdaee39 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -281,7 +281,6 @@ set(SimMedTK_exports Geometry IO Mesh - RenderDelegates Rendering Simulators VirtualTools @@ -300,7 +299,6 @@ add_subdirectory(External) add_subdirectory(Geometry) add_subdirectory(IO) add_subdirectory(Mesh) -add_subdirectory(RenderDelegates) add_subdirectory(Rendering) add_subdirectory(VTKRendering) add_subdirectory(Simulators) diff --git a/Collision/SurfaceTree.hpp b/Collision/SurfaceTree.hpp index b7de6081a54578efad6fb9e765fd711a1ee524fe..ed9c04abec92eea670d81b2366080fac2d81598b 100644 --- a/Collision/SurfaceTree.hpp +++ b/Collision/SurfaceTree.hpp @@ -28,7 +28,6 @@ #include <numeric> // for iota // SimMedTK includes -#include "Rendering/OpenGLViewer.h" #include "Collision/SurfaceTreeIterator.h" #include "Event/KeyboardEvent.h" #include "Core/Factory.h" diff --git a/Core/BaseMesh.cpp b/Core/BaseMesh.cpp index 577787df12b0f335864e960dca61152c42054deb..98925daccf9ec89de5fc993e39e6d277ae5d9083 100644 --- a/Core/BaseMesh.cpp +++ b/Core/BaseMesh.cpp @@ -157,6 +157,13 @@ std::array<core::Vec3d,3> BaseMesh::getTriangleVertices(size_t i) const }; return std::move(triangleVertices); } - +int BaseMesh::getMeshType() +{ + return this->meshType; +} +void BaseMesh::setMeshType(int meshType) +{ + this->meshType = meshType; +} } diff --git a/Core/BaseMesh.h b/Core/BaseMesh.h index d012fd0ad27839aea2a138007c342d2a0187d42c..aef9fa0257dcc1ba1b8d6cc68b2b06b5c55ace22 100644 --- a/Core/BaseMesh.h +++ b/Core/BaseMesh.h @@ -162,6 +162,9 @@ public: /// std::array<core::Vec3d,3> getTriangleVertices(size_t i) const; + int getMeshType(); + void setMeshType(int); + protected: // Data arrays - Vertices only // vertices co-ordinate data at time t @@ -181,6 +184,9 @@ protected: // Render identification, only used in \StylusRenderDelegate. // TODO: Remove this size_t renderingID; + + ///mesh type set by the loader + int meshType; }; }// namespace Core diff --git a/Core/CMakeLists.txt b/Core/CMakeLists.txt index 1bcc0371503e228277c96fa8e112cf5622fcdaa9..c96e0a5f659f7d2a6781da341793613c18066cc4 100644 --- a/Core/CMakeLists.txt +++ b/Core/CMakeLists.txt @@ -1,4 +1,5 @@ include(${VTK_USE_FILE}) + simmedtk_add_library(Core SOURCES BaseMesh.cpp @@ -31,6 +32,7 @@ simmedtk_add_library(Core BaseMesh.h CollisionConfig.h CollisionDetection.h + CollisionManager.h CollisionModelIterator.h CollisionPair.h Color.h @@ -41,7 +43,9 @@ simmedtk_add_library(Core DataStructures.h DataStructures.hpp Dispatcher.h + DisplayText.h ErrorLog.h + EventData.h Event.h EventHandler.h Factory.h @@ -51,6 +55,7 @@ simmedtk_add_library(Core Light.h MakeUnique.h Matrix.h + MemoryBlock.h Model.h Module.h ObjectSimulator.h @@ -74,7 +79,6 @@ simmedtk_add_library(Core ) target_link_libraries(Core - PUBLIC ${OPENGL_LIBRARY} sfml::graphics diff --git a/Core/Geometry.h b/Core/Geometry.h index 2672c2a8f3e997ed199d8c81ab65768f49032143..0cb7ec966c6c518875d478ec561ff8aab85ef51b 100644 --- a/Core/Geometry.h +++ b/Core/Geometry.h @@ -30,7 +30,6 @@ #include "Core/Matrix.h" #include "Core/Factory.h" -#include "Rendering/OpenGLRenderer.h" #include "RenderDelegate.h" //forward declaration diff --git a/Core/ObjectSimulator.cpp b/Core/ObjectSimulator.cpp index b06d9c19fcadc8aea7b289dc6f8e4b90a9667057..2a4c6b48deeb5e765c81877792fe1df4424da32f 100644 --- a/Core/ObjectSimulator.cpp +++ b/Core/ObjectSimulator.cpp @@ -23,7 +23,6 @@ #include "Core/ObjectSimulator.h" #include "Core/SDK.h" -#include "Rendering/OpenGLViewer.h" ObjectSimulator::ObjectSimulator(std::shared_ptr<ErrorLog> p_log) { diff --git a/Core/RenderDetail.cpp b/Core/RenderDetail.cpp index cb0eb39cbf6b850854526a37636a225ee22a5677..4597b89b421a1f8ff689b94ce585a38ffb2b9ec4 100644 --- a/Core/RenderDetail.cpp +++ b/Core/RenderDetail.cpp @@ -13,219 +13,582 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +// +//--------------------------------------------------------------------------- +// +// Authors: +// +// Contact: +//--------------------------------------------------------------------------- #include "Core/RenderDetail.h" +#include <fstream> +#include <sstream> +#include <iostream> -void RenderDetail::addShader(std::shared_ptr<UnifiedId> p_shaderID) +//--------------------------------------------------------------------------- +// Shaders +//--------------------------------------------------------------------------- +std::map<std::string, ShaderDetail> Shaders::shaderPrograms; + +//--------------------------------------------------------------------------- +bool Shaders::shaderExists(std::string shaderProgramName) +{ + std::map<std::string, ShaderDetail>::iterator it= shaderPrograms.find(shaderProgramName); + if (it == shaderPrograms.end()) + { + return false; + } + else + { + return true; + } +} + +//--------------------------------------------------------------------------- +bool Shaders::getShaderProgram(std::string shaderProgramName, ShaderDetail &shaderDetail) +{ + std::map<std::string, ShaderDetail>::iterator it; + it = shaderPrograms.find(shaderProgramName); + if (it == shaderPrograms.end()) + { + return false; + } + else + { + shaderDetail = shaderPrograms[shaderProgramName]; + return true; + } +} + +//--------------------------------------------------------------------------- +bool Shaders::createShader(std::string shaderProgramName, std::string vertexShaderFileName, + std::string fragmentShaderFileName, std::string geometryShaderFileName) { - shaderEnable.push_back(true); - shaders.push_back(p_shaderID); + ShaderDetail shaderDetail; + std::map<std::string, ShaderDetail> &shaderPrograms = Shaders::getShaderPrograms(); + + std::ifstream shaderFileStream(vertexShaderFileName.c_str(), std::ifstream::in); + if (!shaderFileStream.is_open()) + { + std::cerr << "Error opening the shader program: " << vertexShaderFileName << std::endl; + return false; + } + std::stringstream buffer; + buffer << shaderFileStream.rdbuf(); + + shaderDetail.vertexShaderFileName = vertexShaderFileName; + shaderDetail.vertexShaderSource = buffer.str(); + //std::cout << shaderDetail.vertexShaderSource << std::endl; + + //loading the fragment shader source code + shaderFileStream.close(); + shaderFileStream.clear(); + buffer.str(std::string()); + buffer.clear(); + + shaderFileStream.open(fragmentShaderFileName.c_str(), std::ifstream::in); + if (!shaderFileStream.is_open()) + { + std::cerr << "Error opening the shader program: " << fragmentShaderFileName << std::endl; + return false; + } + + buffer << shaderFileStream.rdbuf(); + shaderDetail.fragmentShaderFileName = fragmentShaderFileName; + shaderDetail.fragmentShaderSource = buffer.str(); + //std::cout << shaderDetail.fragmentShaderSource << std::endl; + + shaderFileStream.close(); + shaderFileStream.clear(); + buffer.str(std::string()); + buffer.clear(); + + if (!geometryShaderFileName.empty()) + { + shaderFileStream.open(geometryShaderFileName.c_str(), std::ifstream::in); + if (!shaderFileStream.is_open()) + { + std::cerr << "Error opening the shader program: " << geometryShaderFileName << std::endl; + return false; + } + buffer << shaderFileStream.rdbuf(); + shaderDetail.geometryShaderFileName = geometryShaderFileName; + shaderDetail.geometryShaderSource = buffer.str(); + shaderDetail.geometryShaderExists = true; + shaderFileStream.close(); + shaderFileStream.clear(); + buffer.str(std::string()); + buffer.clear(); + } + shaderDetail.shaderProgramName = shaderProgramName; + shaderPrograms.emplace(shaderProgramName, shaderDetail); + + return true; } -void RenderDetail::addVAO(std::shared_ptr<UnifiedId> p_shaderID) + +//--------------------------------------------------------------------------- +std::map<std::string, ShaderDetail> &Shaders::getShaderPrograms() { - VAOs.push_back(p_shaderID); - VAOEnable.push_back(true); + return Shaders::shaderPrograms; } +//--------------------------------------------------------------------------- +// RenderDetail +//--------------------------------------------------------------------------- RenderDetail::RenderDetail() { this->reset(); } +//--------------------------------------------------------------------------- RenderDetail::RenderDetail(unsigned int type) { this->reset(); - normalLength = 1.0; + this->normalLength = 1.0; this->renderType = type; + this->hasShader = false; } -void RenderDetail::reset() +//--------------------------------------------------------------------------- +RenderDetail::~RenderDetail() {} + +//--------------------------------------------------------------------------- +const Color& RenderDetail::getAmbientColor() const { - renderType = 0; - highLightColor.rgba[0] = 1.0; - highLightColor.rgba[1] = 0.0; - highLightColor.rgba[2] = 0.0; - pointSize = 1; - lineSize = 1; - shadowColor.rgba[0] = 0.0; - shadowColor.rgba[1] = 0.0; - shadowColor.rgba[2] = 0.0; - shadowColor.rgba[3] = 0.5; - colorDiffuse = Color::colorGray; - colorAmbient = Color::colorGray; - colorSpecular = Color::colorWhite; - normalColor = Color::colorGreen; - wireFrameColor = Color::colorBlue; - shininess = 50.0; - debugDraw = false; - castShadow = true; - canGetShadow = true; - opacity = 1.0; - textureFilename = ""; + return this->ambientColor; +} - background.rgba[0] = 0.5; - background.rgba[1] = 0.5; - background.rgba[2] = 0.7; +//--------------------------------------------------------------------------- +const Color& RenderDetail::getDiffuseColor() const +{ + return this->diffuseColor; +} - faceBackgroundBottom.setValue(0.8, 0.8, 0.8, 1.0); - faceBackgroundTop.setValue(0.45, 0.45, 0.8, 1.0); +//--------------------------------------------------------------------------- +const Color& RenderDetail::getSpecularColor() const +{ + return this->specularColor; +} - background.rgba[3] = 1.0; +//--------------------------------------------------------------------------- +const Color& RenderDetail::getHighLightColor() const +{ + return this->highLightColor; } -void RenderDetail::setNormalLength(const float len) +//--------------------------------------------------------------------------- +const Color& RenderDetail::getNormalColor() const { - this->normalLength = len; + return this->normalColor; } -void RenderDetail::setLineSize(const float size) + +//--------------------------------------------------------------------------- +const Color& RenderDetail::getShadowColor() const { - this->lineSize = size; + return this->shadowColor; } -void RenderDetail::setPointSize(const float size) + +//--------------------------------------------------------------------------- +const Color& RenderDetail::getVertexColor() const { - this->pointSize = size; + return this->vertexRenderColor; } -void RenderDetail::setVertexColor(const Color vertColor) + +//--------------------------------------------------------------------------- +const Color& RenderDetail::getWireFrameColor() const { - this->vertexRenderColor = vertColor; + return this->wireFrameColor; } -void RenderDetail::setNormalColor(const Color normColor) + +//--------------------------------------------------------------------------- +void RenderDetail::setAmbientColor(const Color &color) { - this->normalColor = normColor; + this->ambientColor = color; } -void RenderDetail::setDiffuseColor(const Color diffColor) + +//--------------------------------------------------------------------------- +void RenderDetail::setDiffuseColor(const Color &color) { - this->colorDiffuse = diffColor; + this->diffuseColor = color; } -void RenderDetail::setAmbientColor(const Color ambColor) + +//--------------------------------------------------------------------------- +void RenderDetail::setHighlightColor(const Color &color) { - this->colorAmbient = ambColor; + this->highLightColor = color; } -void RenderDetail::setSpecularColor(const Color specColor) + +//--------------------------------------------------------------------------- +void RenderDetail::setNormalColor(const Color &color) { - this->colorSpecular = specColor; + this->normalColor = color; } -void RenderDetail::setShadowColor(const Color shadColor) + +//--------------------------------------------------------------------------- +void RenderDetail::setShadowColor(const Color &color) { - this->shadowColor = shadColor; + this->shadowColor = color; } -void RenderDetail::setWireframeColor(const Color wireColor) + +//--------------------------------------------------------------------------- +void RenderDetail::setSpecularColor(const Color &color) { - this->wireFrameColor = wireColor; + this->specularColor = color; } -void RenderDetail::setShininess(const float s) + +//--------------------------------------------------------------------------- +void RenderDetail::setVertexColor(const Color &color) { - this->shininess = s; + this->vertexRenderColor = color; } -void RenderDetail::setHighlightColor(const Color highlightColor) + +//--------------------------------------------------------------------------- +void RenderDetail::setWireframeColor(const Color &color) { - this->highLightColor = highlightColor; + this->wireFrameColor = color; } -const Color& RenderDetail::getColorDiffuse() const + +//--------------------------------------------------------------------------- +const Color& RenderDetail::getBackground() const { - return colorDiffuse; + return this->background; } -const Color& RenderDetail::getColorAmbient() const + +//--------------------------------------------------------------------------- +void RenderDetail::setBackground(const Color &color) { - return colorAmbient; + this->background = color; } -const Color& RenderDetail::getColorSpecular() const + +//--------------------------------------------------------------------------- +const float &RenderDetail::getOpacity() const { - return colorSpecular; + return this->opacity; } -const float& RenderDetail::getShininess() const + +//--------------------------------------------------------------------------- +void RenderDetail::setOpacity(const float &opacityValue) { - return shininess; + this->opacity = opacityValue; } -const unsigned int& RenderDetail::getRenderType() const + +//--------------------------------------------------------------------------- +const float& RenderDetail::getShininess() const { - return renderType; + return this->shininess; } -const float& RenderDetail::getPointSize() const + +//--------------------------------------------------------------------------- +void RenderDetail::setShininess(const float &value) { - return pointSize; + this->shininess = value; } -const float& RenderDetail::getLineSize() const + +//--------------------------------------------------------------------------- +const float& RenderDetail::getNormalLength() const { - return lineSize; + return this->normalLength; } -const Color& RenderDetail::getNormalColor() const + +//--------------------------------------------------------------------------- +void RenderDetail::setNormalLength(const float &value) { - return this->normalColor; + this->normalLength = value; } -const Color& RenderDetail::getHighLightColor() const + +//--------------------------------------------------------------------------- +const float& RenderDetail::getPointSize() const { - return this->highLightColor; + return this->pointSize; } -const Color& RenderDetail::getVertexColor() const + +//--------------------------------------------------------------------------- +void RenderDetail::setPointSize(const float &value) { - return this->vertexRenderColor; + this->pointSize = value; } -const Color& RenderDetail::getShadowColor() const + +//--------------------------------------------------------------------------- +const float& RenderDetail::getLineSize() const { - return this->shadowColor; + return this->lineSize; } -const bool& RenderDetail::getCastShadow() const + +//--------------------------------------------------------------------------- +void RenderDetail::setLineSize(const float &value) { - return this->castShadow; + this->lineSize = value; } + +//--------------------------------------------------------------------------- const bool& RenderDetail::getCanGetShadow() const { return this->canGetShadow; } -const Color& RenderDetail::getWireFrameColor() const + +//--------------------------------------------------------------------------- +const bool& RenderDetail::getCastShadow() const { - return this->wireFrameColor; + return this->castShadow; } + +//--------------------------------------------------------------------------- const bool& RenderDetail::getDebugDraw() const { return this->debugDraw; } -const std::vector< std::shared_ptr<UnifiedId> >& RenderDetail::getShaders() const + +//--------------------------------------------------------------------------- +const unsigned int& RenderDetail::getRenderType() const { - return this->shaders; + return this->renderType; } + +//--------------------------------------------------------------------------- const std::vector< bool >& RenderDetail::getShaderEnable() const { return this->shaderEnable; } + +//--------------------------------------------------------------------------- const std::vector< std::shared_ptr<UnifiedId> >& RenderDetail::getVAOs() const { return this->VAOs; } + +//--------------------------------------------------------------------------- const std::vector< bool >& RenderDetail::getVAOEnable() const { return this->VAOEnable; } -void RenderDetail::setTextureFilename(const std::string& filename) -{ - this->textureFilename = filename; -} -const std::string &RenderDetail::getTextureFilename() const -{ - return this->textureFilename; + +//--------------------------------------------------------------------------- +void RenderDetail::setRenderTexture(bool value) +{ + if(value) + { + this->renderType |= SIMMEDTK_RENDER_TEXTURE; + } + else + { + this->renderType |= ~SIMMEDTK_RENDER_TEXTURE; + } } + +//--------------------------------------------------------------------------- bool RenderDetail::renderTexture() const { - return !this->textureFilename.empty() && this->renderType & SIMMEDTK_RENDER_TEXTURE; + return !this->textureFilename.empty() && (this->renderType & SIMMEDTK_RENDER_TEXTURE); +} + +//--------------------------------------------------------------------------- +void RenderDetail::setRenderNormals(bool value) +{ + if(value) + { + this->renderType |= SIMMEDTK_RENDER_NORMALS; + } + else + { + this->renderType |= ~SIMMEDTK_RENDER_NORMALS; + } } + +//--------------------------------------------------------------------------- bool RenderDetail::renderNormals() const { return this->renderType & SIMMEDTK_RENDER_NORMALS; } -const float &RenderDetail::getOpacity() const -{ - return this->opacity; -} -void RenderDetail::setOpacity(const float &opacityValue) -{ - this->opacity = opacityValue; + +//--------------------------------------------------------------------------- +void RenderDetail::setRenderWireframe(bool value) +{ + if(value) + { + this->renderType |= SIMMEDTK_RENDER_WIREFRAME; + } + else + { + this->renderType |= ~SIMMEDTK_RENDER_WIREFRAME; + } } + +//--------------------------------------------------------------------------- bool RenderDetail::renderWireframe() const { return this->renderType & SIMMEDTK_RENDER_WIREFRAME; } + +//--------------------------------------------------------------------------- +void RenderDetail::setRenderFaces(bool value) +{ + if(value) + { + this->renderType |= SIMMEDTK_RENDER_FACES; + } + else + { + this->renderType |= ~SIMMEDTK_RENDER_FACES; + } +} + +//--------------------------------------------------------------------------- bool RenderDetail::renderFaces() const { return this->renderType & SIMMEDTK_RENDER_FACES; } + +//--------------------------------------------------------------------------- +void RenderDetail::addShaderProgram(const std::string &shaderProgramName) +{ + if (Shaders::shaderExists(shaderProgramName)) + { + this->hasShader = true; + this->shaderProgramName.assign(shaderProgramName); + } +} +//This will deprecate +void RenderDetail::addShaderProgram(int shaderType, const std::string& programFilename, const std::string &shaderProgramName) +{ + ShaderDetail shaderDetail; + + std::ifstream shaderFileStream(programFilename.c_str(), std::ifstream::in); + if(!shaderFileStream.is_open()) + { + std::cerr << "Error opening the shader program: " << programFilename << std::endl; + return; + } + std::stringstream buffer; + buffer << shaderFileStream.rdbuf(); + std::map<std::string, ShaderDetail> &shaderPrograms = Shaders::getShaderPrograms(); + if (!(shaderPrograms.find(shaderProgramName) == shaderPrograms.end())){ + shaderDetail = shaderPrograms[shaderProgramName]; + } + if (shaderType == 0/*vtkShader::Vertex*/){//the numeric value will be changed with vtkShader::Vertex + shaderDetail.vertexShaderFileName=programFilename; + shaderDetail.vertexShaderSource=buffer.str(); + } + if (shaderType == 1/*vtkShader::Fragment*/){//the numeric value will be changed with vtkShader::Fragment + //auto &shaderDetail = shaderPrograms[shaderProgramName]; + shaderDetail.fragmentShaderFileName=programFilename; + shaderDetail.fragmentShaderSource=buffer.str(); + } + shaderPrograms.emplace(shaderProgramName, shaderDetail); +} + +//--------------------------------------------------------------------------- +std::string RenderDetail::getShaderProgram() +{ + return shaderProgramName; +} + +//--------------------------------------------------------------------------- +void RenderDetail::addShaderProgramReplacement(int type, const std::string& from, const std::string& to) +{ + std::array<std::string, 2> replacement = {from, to}; + this->shaderProgramReplacements[type].push_back(replacement); +} + +//--------------------------------------------------------------------------- +std::map< int, std::vector< std::array< std::string, int(2) > > >& RenderDetail::getShaderProgramReplacements() +{ + return this->shaderProgramReplacements; +} + +//--------------------------------------------------------------------------- +bool RenderDetail::hasShaders() +{ + return hasShader; +} + +//--------------------------------------------------------------------------- +void RenderDetail::addShader(std::shared_ptr<UnifiedId> p_shaderID) +{ + this->shaderEnable.push_back(true); + this->shaders.push_back(p_shaderID); +} + +//--------------------------------------------------------------------------- +const std::vector< std::shared_ptr<UnifiedId> >& RenderDetail::getShaders() const +{ + return this->shaders; +} + +//--------------------------------------------------------------------------- +void RenderDetail::addVAO(std::shared_ptr<UnifiedId> p_shaderID) +{ + this->VAOs.push_back(p_shaderID); + this->VAOEnable.push_back(true); +} + +//--------------------------------------------------------------------------- +void RenderDetail::reset() +{ + this->background.rgba[0] = 81.0/255.0; + this->background.rgba[1] = 87.0/255.0; + this->background.rgba[2] = 110.0/255.0; + this->background.rgba[3] = 1.0; + this->canGetShadow = true; + this->castShadow = true; + this->ambientColor = Color::colorGray; + this->diffuseColor = Color::colorGray; + this->specularColor = Color::colorWhite; + this->debugDraw = false; + this->highLightColor.rgba[0] = 1.0; + this->highLightColor.rgba[1] = 0.0; + this->highLightColor.rgba[2] = 0.0; + this->lineSize = 1; + this->normalColor = Color::colorGreen; + this->opacity = 1.0; + this->pointSize = 1; + this->renderType = 0; + this->shadowColor.rgba[0] = 0.0; + this->shadowColor.rgba[1] = 0.0; + this->shadowColor.rgba[2] = 0.0; + this->shadowColor.rgba[3] = 0.5; + this->shininess = 50.0; + this->textureFilename = ""; + this->wireFrameColor = Color::colorBlue; + this->faceBackgroundBottom.setValue(0.8, 0.8, 0.8, 1.0); + this->faceBackgroundTop.setValue(0.45, 0.45, 0.8, 1.0); +} + +//--------------------------------------------------------------------------- +void RenderDetail::setRenderType(unsigned int p_renderType) +{ + renderType = p_renderType; +} + +//--------------------------------------------------------------------------- +void RenderDetail::addShaderAttribute(int shaderType, const std::string &attributeName) +{ + // TODO (Tansel) + std::cerr<<"Error: RenderDetail::addShaderAttribute not yet implemented."<<std::endl; +} + +//--------------------------------------------------------------------------- +void RenderDetail::addTexture(const std::string &textureName, const std::string &filename, + const std::string &shaderBinding, const std::string &shaderProgramName) +{ + this->textures[textureName].textureName = textureName; + this->textures[textureName].fileName = filename; + this->textures[textureName].shaderBinding = shaderBinding; + this->textures[textureName].shaderProgramName = shaderProgramName; + this->textures[textureName].shaderUniformGL = -1; //not defined intially +} + +//--------------------------------------------------------------------------- +std::map<std::string, TextureDetail> &RenderDetail::getTextures() +{ + return this->textures; +} + +//--------------------------------------------------------------------------- +int RenderDetail::getNumberOfTextures() +{ + return this->textures.size(); +} + +// static +std::map<std::string, vtkOpenGLTexture*> TextureDetail::textures; diff --git a/Core/RenderDetail.h b/Core/RenderDetail.h index 7a0743f26b1b9b94a75354fbe5eb2dd646c1a24b..27db420c691938b51f256fe3181a1d1948e1e698 100644 --- a/Core/RenderDetail.h +++ b/Core/RenderDetail.h @@ -14,67 +14,130 @@ // See the License for the specific language governing permissions and // limitations under the License. // +//--------------------------------------------------------------------------- +// +// Authors: +// +// Contact: +//--------------------------------------------------------------------------- #ifndef SMRENDERDETAIL_H #define SMRENDERDETAIL_H #include "Core/Config.h" #include "Core/Color.h" #include "Core/ConfigRendering.h" +#include <GL/glew.h> #include <memory> #include <vector> #include <string> +#include <map> +#include <array> class VisualArtifact; class CoreClass; class Model; struct UnifiedId; -///\brief Hold a pointer to a source of geometry that render details can use for drawing. -struct GeometrySource { - CoreClass* sceneObject; - VisualArtifact* analyticObject; - Model *model; +class vtkOpenGLTexture; + +/// +/// \brief Hold a pointer to a source of geometry that render details can use for drawing. +/// +struct GeometrySource +{ + CoreClass* sceneObject; + VisualArtifact* analyticObject; + Model *model; - GeometrySource() - : sceneObject(nullptr), analyticObject(nullptr) + GeometrySource() + : sceneObject(nullptr), analyticObject(nullptr) { } - void setSource(CoreClass* src) + void setSource(CoreClass* src) { - this->sceneObject = src; - this->analyticObject = nullptr; - this->model = nullptr; + this->sceneObject = src; + this->analyticObject = nullptr; + this->model = nullptr; } - void setSource(VisualArtifact* src) + void setSource(VisualArtifact* src) { - this->sceneObject = nullptr; - this->model = nullptr; - this->analyticObject = src; + this->sceneObject = nullptr; + this->model = nullptr; + this->analyticObject = src; } - void setSource(Model* src) + void setSource(Model* src) { - this->sceneObject = nullptr; - this->model = src; - this->analyticObject = nullptr; + this->sceneObject = nullptr; + this->model = src; + this->analyticObject = nullptr; } - template<typename T> - T* sourceAs() const + template<typename T> + T* sourceAs() const { - T* result; - if ((result = dynamic_cast<T*>(sceneObject))) - { - return result; - } - if ((result = dynamic_cast<T*>(analyticObject))) - { - return result; + T* result; + if((result = dynamic_cast<T*>(sceneObject))) + { + return result; + } + if((result = dynamic_cast<T*>(analyticObject))) + { + return result; + } + if((result = dynamic_cast<T*>(model))) + { + return result; + } + return nullptr; } - if ((result = dynamic_cast<T*>(model))) +}; + +struct TextureDetail +{ + std::string textureName; + std::string fileName; + std::string shaderBinding; + std::string shaderProgramName; + GLint shaderUniformGL; + vtkOpenGLTexture* vtexture; + static std::map<std::string, vtkOpenGLTexture*> textures; +}; + +struct ShaderDetail +{ + ShaderDetail() { - return result; - } - return nullptr; + initialized = false; + geometryShaderExists = false; } + std::string vertexShaderFileName; + std::string vertexShaderSource; + + std::string fragmentShaderFileName; + std::string fragmentShaderSource; + + bool geometryShaderExists; + std::string geometryShaderFileName; + std::string geometryShaderSource; + std::string shaderProgramName; + bool initialized; + + //std::string tessellationShaderFileName; + //std::string tessellationShaderSource; + //std::string computeShaderFileName; + //std::string computeShaderSource; +}; + +class Shaders +{ +public: + Shaders(); + static bool createShader(std::string shaderProgramName, std::string vertexShaderFileName, std::string fragmentShaderFileName, std::string geometryShaderFileName); + static std::map<std::string, ShaderDetail> &getShaderPrograms(); + static bool getShaderProgram(std::string shaderProgramName, ShaderDetail &shaderDetail); + static bool shaderExists(std::string shaderProgramName); + +protected: + static std::map<std::string, ShaderDetail> shaderPrograms; }; /// \brief RenderDetail has rendering options and features. @@ -84,137 +147,245 @@ struct RenderDetail public: typedef std::shared_ptr<RenderDetail> Ptr; + /// + /// \brief Constructors/Destructor + /// RenderDetail(); + ~RenderDetail(); RenderDetail(unsigned int type); - void reset(); - - /// \brief attachment of shader - void addShader(std::shared_ptr<UnifiedId> p_shaderID); - - /// \brief attachment of VAO - void addVAO(std::shared_ptr<UnifiedId> p_shaderID); + /// + /// @brief Color setters + /// + const Color &getAmbientColor() const; + const Color &getDiffuseColor() const; + const Color &getSpecularColor() const; + const Color &getHighLightColor() const; + const Color &getNormalColor() const; + const Color &getShadowColor() const; + const Color &getVertexColor() const; + const Color &getWireFrameColor() const; - const Color &getColorDiffuse() const; + /// + /// @brief Color getters + /// + void setAmbientColor(const Color &color); + void setDiffuseColor(const Color &color); + void setHighlightColor(const Color &color); + void setNormalColor(const Color &color); + void setShadowColor(const Color &color); + void setSpecularColor(const Color &color); + void setVertexColor(const Color &color); + void setWireframeColor(const Color &color); + + /// + /// \brief Get/Set background color + /// + const Color &getBackground() const; + void setBackground(const Color &value); + const Color &getBackgroundTop() const + { + return this->faceBackgroundTop; + } - const Color &getColorAmbient() const; + const Color &getBackgroundBottom() const + { + return this->faceBackgroundBottom; + } - const Color &getColorSpecular() const; + /// + /// \brief Get/Set opacity value + /// + const float &getOpacity() const; + void setOpacity(const float &value); + /// + /// \brief Get/Set specular power + /// const float &getShininess() const; + void setShininess(const float &value); - const unsigned int &getRenderType() const; + /// + /// \brief Get/Set the length of the normal vector to draw + /// + const float &getNormalLength() const; + void setNormalLength(const float &value); + /// + /// \brief Get/Set size of point to draw + /// const float &getPointSize() const; + void setPointSize(const float &value); + /// + /// \brief Get/Set size of line to draw + /// const float &getLineSize() const; + void setLineSize(const float &value); - const Color &getNormalColor() const; - - const Color &getHighLightColor() const; - - const Color &getVertexColor() const; - - const Color &getShadowColor() const; - - const bool &getCastShadow() const; - + /// + /// \brief Can the object get the shadow + /// const bool &getCanGetShadow() const; - const Color &getWireFrameColor() const; + /// + /// \brief Can the object cast a shadow + /// + const bool &getCastShadow() const; + /// + /// \brief Debug mode + /// const bool &getDebugDraw() const; - const std::vector<std::shared_ptr<UnifiedId>> &getShaders() const; + /// + /// \brief Render type + /// + const unsigned int &getRenderType() const; + /// + /// \brief Get enabled/disabled shaders array + /// const std::vector<bool> &getShaderEnable() const; + /// + /// \brief Get VAO's array + /// const std::vector<std::shared_ptr<UnifiedId>> &getVAOs() const; + /// + /// \brief Get enabled/disabled VAO array + /// const std::vector<bool> &getVAOEnable() const; - void setPointSize(const float size); - - void setLineSize(const float size); - - void setVertexColor(const Color vertColor); - - void setHighlightColor(const Color highlightColor); - - void setNormalColor(const Color highlightColor); - - void setShininess(const float s); - - void setNormalLength(const float len); - - void setDiffuseColor(const Color diffColor); - - void setAmbientColor(const Color ambColor); - - void setSpecularColor(const Color specColor); - - void setShadowColor(const Color shadColor); - - void setWireframeColor(const Color wireColor); - - void setTextureFilename(const std::string &filename); - const std::string &getTextureFilename() const; + /// + /// \brief Set/Get the binding texture filename for a shader. shaderBinding is for texture name in the shader name + /// + void addTexture(const std::string &textureName, const std::string &filename, + const std::string &shaderBinding, const std::string &shaderProgramName); + std::map<std::string, TextureDetail>& getTextures(); + int getNumberOfTextures(); + + /// + /// \brief Returns true if you want to draw texture map + /// + void setRenderTexture(bool value); bool renderTexture() const; + /// + /// \brief Returns true if you want to draw normalsmap + /// + void setRenderNormals(bool value); bool renderNormals() const; + + /// + /// \brief Returns true if you want to draw wireframe + /// + void setRenderWireframe(bool value); bool renderWireframe() const; + + /// + /// \brief Returns true if you want to draw faces + /// + void setRenderFaces(bool value); bool renderFaces() const; - const float &getOpacity() const; - void setOpacity(const float &value); + /// + /// @brief Add a shader program to the the list (vtk) + /// + void addShaderProgram(int shaderType, const std::string &programFilename, const std::string & programName); + void addShaderProgram(const std::string &shaderProgramName); + std::string getShaderProgram(); + + /// + /// \brief Return list of shader programs + /// + std::map<std::string, bool> &getShaderPrograms(); + + /// + /// @brief Add a shader program for partial replacement of vtk default shaders. + /// @param type 0 = vertex, 1 = Fragment, 2 = Geometry + /// @param program String containing the actual program + /// + void addShaderProgramReplacement(int type, const std::string &from, + const std::string &to); + + + /// + /// \brief Return list of shader program replacements + /// + std::map<int, std::vector<std::array<std::string, 2>>> + &getShaderProgramReplacements(); + + /// + /// \brief Retrurns true if there is vtk shader in the list + /// + bool hasShaders(); + + /// + /// \brief attachment of shader + /// + void addShader(std::shared_ptr<UnifiedId> p_shaderID); - const Color &getBackground() const - { - return this->background; - } + /// + /// \brief Get shaders array + /// + const std::vector<std::shared_ptr<UnifiedId>> &getShaders() const; - const Color &getBackgroundTop() const - { - return this->faceBackgroundTop; - } + /// + /// \brief attachment of VAO + /// + void addVAO(std::shared_ptr<UnifiedId> p_shaderID); - const Color &getBackgroundBottom() const - { - return this->faceBackgroundBottom; - } + /// + /// \brief Reset variables and containers + /// + void reset(); - void setBackground(const Color &value) - { - this->background = value; - } -public: - unsigned int renderType; // render type - Color colorDiffuse; // diffuse color - Color colorAmbient; // ambient color - Color colorSpecular; // specular color - Color highLightColor; // highlight color - Color vertexRenderColor; // vertex color - Color shadowColor; // shadow color - bool castShadow; // object can generate a shadow or not + /// + /// \brief Set render type + /// + void setRenderType(unsigned int p_renderType); + + /// + /// @brief Add an attribute to a program to the the list (vtk) + /// + void addShaderAttribute(int shaderType, const std::string &attributeName); + +private: bool canGetShadow; // object can get the shadow or not + bool castShadow; // object can generate a shadow or not + bool debugDraw; // debug draw enabled or not + Color background; // backgroung color + Color faceBackgroundBottom; + Color faceBackgroundTop; + Color ambientColor; // ambient color + Color diffuseColor; // diffuse color + Color specularColor; // specular color + Color highLightColor; // highlight color Color normalColor; // normal color + Color shadowColor; // shadow color + Color vertexRenderColor; // vertex color Color wireFrameColor; // wire frame color - float pointSize; // point size if rendering of vertices are enabled float lineSize; // line width size - float shininess; // specular shinness - bool debugDraw; // debug draw enabled or not float normalLength; // length of rendered normals float opacity; // opacity + float pointSize; // point size if rendering of vertices are enabled + float shininess; // specular shinness std::string textureFilename; // file name for the texture attached] - Color background; + unsigned int renderType; // render type - Color faceBackgroundBottom; - Color faceBackgroundTop; + std::string shaderProgramName; + bool hasShader; - std::vector<std::shared_ptr<UnifiedId>> shaders; // attached shaders + std::map<std::string,bool> shaderPrograms; + std::map<int, std::vector<std::array<std::string, 2>>> shaderProgramReplacements; std::vector<bool> shaderEnable; // enable/disable any attached shader - std::vector<std::shared_ptr<UnifiedId>> VAOs; // stores VAO IDs std::vector<bool> VAOEnable; // enable/disable any attached VAO + std::vector<std::shared_ptr<UnifiedId>> shaders; // attached shaders + std::vector<std::shared_ptr<UnifiedId>> VAOs; // stores VAO IDs + std::map<std::string,int> shaderAttributes; + std::map<std::string, TextureDetail> textures; }; #endif // SMRENDERDETAIL_H diff --git a/Core/SDK.h b/Core/SDK.h index ea06c7eb3a7fc221857d972ddd597bd0fe14c2b0..3e50a99a34e52db35c31b84fbf383a914d6522d6 100644 --- a/Core/SDK.h +++ b/Core/SDK.h @@ -35,7 +35,7 @@ #include "Core/Module.h" #include "Core/DataStructures.h" #include "Core/MakeUnique.h" -#include "Rendering/OpenGLViewer.h" +#include "Core/ViewerBase.h" /// \brief maximum entities in the framework #define SIMMEDTK_SDK_MAXMESHES 100 diff --git a/Examples/AVMNidus/CMakeLists.txt b/Examples/AVMNidus/CMakeLists.txt index f08931b16566fb36df8ecf5e6924228c073d3e64..fb8b9be875522aadc7c881bd1b5a130e24064ef2 100644 --- a/Examples/AVMNidus/CMakeLists.txt +++ b/Examples/AVMNidus/CMakeLists.txt @@ -1,11 +1,13 @@ set(APP AVMNidus) +include(${VTK_USE_FILE}) + add_executable(${APP} main.cpp) target_link_libraries(${APP} Core + Geometry VTKRendering Rendering - RenderDelegates Simulators Mesh Collision @@ -38,8 +40,6 @@ set(DATA ${${APP}_DATA}/nidus1764.mass ${${APP}_DATA}/nidusS7415.vtk ${${APP}_DATA}/nidusV1764.vtk - ${${APP}_DATA}/wet_frag.glsl - ${${APP}_DATA}/wet_vert.glsl ) add_custom_command( diff --git a/Examples/AVMNidus/main.cpp b/Examples/AVMNidus/main.cpp index 2e71db4b2cd053e22ce1e6a88ba1bf80b28ae9a9..c57b69ebfde4ddbdeb7e2aab9b33631036491f19 100644 --- a/Examples/AVMNidus/main.cpp +++ b/Examples/AVMNidus/main.cpp @@ -43,7 +43,6 @@ #include "ContactHandling/PenaltyContactFemToStatic.h" #include "IO/InitIO.h" -#include "RenderDelegates/InitRenderDelegates.h" #include "VTKRendering/InitVTKRendering.h" #include "IO/IOMesh.h" @@ -55,46 +54,28 @@ int main(int ac, char **av) configFile = av[1]; } - InitRenderDelegates(); InitVTKRendering(); InitIODelegates(); - Matrix33d mat; - //------------------------------------------------------- // 1. Create an instance of the SimMedTK framework/SDK // 2. Create viewer // 3. Create default scene (scene 0) //------------------------------------------------------- auto sdk = SDK::createStandardSDK(); + auto sdkSimulator = sdk->getSimulator(); //------------------------------------------------------- // Create scene actor 1: fem scene object + fem simulator //------------------------------------------------------- - // create a FEM simulator auto femSimulator = std::make_shared<VegaFemSimulator>(sdk->getErrorLog()); // create a Vega based FEM object and attach it to the fem simulator auto femObject = std::make_shared<VegaFemSceneObject>(sdk->getErrorLog(),configFile); - auto meshRenderDetail = std::make_shared<RenderDetail>(SIMMEDTK_RENDER_WIREFRAME | - //| SIMMEDTK_RENDER_VERTICES - SIMMEDTK_RENDER_FACES | SIMMEDTK_RENDER_NORMALS - ); - meshRenderDetail->setNormalLength(0.02); - meshRenderDetail->setAmbientColor(Color(0.2,0.2,0.2,1.0)); - meshRenderDetail->setDiffuseColor(Color::colorGray); - meshRenderDetail->setSpecularColor(Color(1.0, 1.0, 1.0,0.5)); - meshRenderDetail->setShininess(20.0); - - auto renderingMesh = femObject->getVolumetricMesh()->getRenderingMesh(); - if(renderingMesh) - { - renderingMesh->setRenderDetail(meshRenderDetail); - } - sdk->addSceneActor(femObject, femSimulator); + sdkSimulator->registerObjectSimulator(femSimulator); //------------------------------------------------------- // Create scene actor 2: plane + dummy simulator @@ -102,7 +83,7 @@ int main(int ac, char **av) // Create dummy simulator auto staticSimulator = std::make_shared<DefaultSimulator>(sdk->getErrorLog()); - // create a static plane scene object of given normal and position + // Create a static plane scene object of given normal and position auto staticObject = std::make_shared<StaticSceneObject>(); auto plane = std::make_shared<PlaneCollisionModel>(core::Vec3d(0.0, 0.0, -35.0), @@ -111,21 +92,13 @@ int main(int ac, char **av) staticObject->setModel(plane); sdk->addSceneActor(staticObject, staticSimulator); - //------------------------------------------------------- - // Register both object simulators - //------------------------------------------------------- - auto sdkSimulator = sdk->getSimulator(); - sdkSimulator->registerObjectSimulator(femSimulator); - //------------------------------------------------------- // Enable collision between scene actors 1 and 2 //------------------------------------------------------- auto meshModel = std::make_shared<MeshCollisionModel>(); - meshModel->setMesh(femObject->getVolumetricMesh()->getAttachedMesh(0)); auto planeMeshCollisionPairs = std::make_shared<CollisionPair>(); - planeMeshCollisionPairs->setModels(meshModel, plane); sdkSimulator->addCollisionPair(planeMeshCollisionPairs); @@ -138,9 +111,7 @@ int main(int ac, char **av) // Enable contact handling between scene actors 1 and 2 //------------------------------------------------------- auto planeToMeshContact = std::make_shared<PenaltyContactFemToStatic>(false); - planeToMeshContact->setCollisionPairs(planeMeshCollisionPairs); - planeToMeshContact->setSceneObjects(staticObject, femObject); sdkSimulator->registerContactHandling(planeToMeshContact); @@ -156,6 +127,9 @@ int main(int ac, char **av) viewer->setGlobalAxisLength(0.8); + //------------------------------------------------------- + // Customize the scene + //------------------------------------------------------- // Get Scene auto scene = sdk->getScene(0); viewer->registerScene(scene); diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index 3bf051f978b0694317db2330b893b4bdfbed2b3b..69d1c319fc9d812f8a4ee69cb7b5e388471c4b3d 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -23,6 +23,7 @@ function(MIDAS_DOWNLOAD MIDAS_URL FILE_SHA1 LOCAL_FILE) endif() endfunction() -add_subdirectory(vegaFem) +add_subdirectory(FEMSimulator) add_subdirectory(LaparoscopicCamera) add_subdirectory(AVMNidus) +add_subdirectory(Shaders) diff --git a/Examples/vegaFem/CMakeLists.txt b/Examples/FEMSimulator/CMakeLists.txt similarity index 99% rename from Examples/vegaFem/CMakeLists.txt rename to Examples/FEMSimulator/CMakeLists.txt index ca228fa57979020c9eefbf4ebba985f1f4f16028..0aaafbfb5a8f5a2c3ce03244e403f8a5f844f4a6 100644 --- a/Examples/vegaFem/CMakeLists.txt +++ b/Examples/FEMSimulator/CMakeLists.txt @@ -1,4 +1,4 @@ -set(APP vegaFemExample) +set(APP FEMSimulator) add_executable(${APP} main.cpp) target_link_libraries(${APP} diff --git a/Examples/vegaFem/main.cpp b/Examples/FEMSimulator/main.cpp similarity index 99% rename from Examples/vegaFem/main.cpp rename to Examples/FEMSimulator/main.cpp index fcd35d721b779e7c4b7c5c20a2ee7badf1e138db..1d91e82b74cb5c28b9c2f00df799e2219e88ecc0 100644 --- a/Examples/vegaFem/main.cpp +++ b/Examples/FEMSimulator/main.cpp @@ -166,6 +166,7 @@ int main(int ac, char** av) sdkSimulator->registerObjectSimulator(femSimulator); //sdkSimulator->registerObjectSimulator(staticSimulator); + //------------------------------------------------------- // Enable collision between scene actors 1 and 2 //------------------------------------------------------- @@ -179,6 +180,7 @@ int main(int ac, char** av) femObject->setModel(meshModel); auto planeMeshCollisionPairs = std::make_shared<CollisionPair>(); + planeMeshCollisionPairs->setModels(meshModel, plane); sdkSimulator->addCollisionPair(planeMeshCollisionPairs); @@ -191,7 +193,9 @@ int main(int ac, char** av) // Enable contact handling between scene actors 1 and 2 //------------------------------------------------------- auto planeToMeshContact = std::make_shared<PenaltyContactFemToStatic>(false); + planeToMeshContact->setCollisionPairs(planeMeshCollisionPairs); + planeToMeshContact->setSceneObjects(staticObject, femObject); sdkSimulator->registerContactHandling(planeToMeshContact); diff --git a/Examples/LaparoscopicCamera/CMakeLists.txt b/Examples/LaparoscopicCamera/CMakeLists.txt index 1cd11d9b06947667f68a2d604493fe77d23ce844..aa22dc0bbd20a27a1c58dea3a3233edb5b501294 100644 --- a/Examples/LaparoscopicCamera/CMakeLists.txt +++ b/Examples/LaparoscopicCamera/CMakeLists.txt @@ -1,4 +1,4 @@ -set(APP LapCameraNavigationApp) +set(APP LaparoscopicCamera) add_executable(${APP} main.cpp) target_link_libraries(${APP} diff --git a/Examples/LaparoscopicCamera/main.cpp b/Examples/LaparoscopicCamera/main.cpp index e71e6d663e1695e3e0be1feca43eebffcf9e8701..2a70a71f53a573c49d5dd92bff95bb4c3aec0ae6 100644 --- a/Examples/LaparoscopicCamera/main.cpp +++ b/Examples/LaparoscopicCamera/main.cpp @@ -187,6 +187,8 @@ bool createCameraNavigationScene( Color meshColor(0.32, 0.32, 0.32, 1.0); std::shared_ptr<RenderDetail> targetRenderDetail = std::make_shared<RenderDetail>(SIMMEDTK_RENDER_TEXTURE); + targetRenderDetail->addTexture("target", targetFileName, "", ""); + std::shared_ptr<RenderDetail> blockRenderDetail = std::make_shared<RenderDetail>(SIMMEDTK_RENDER_NORMALS); blockRenderDetail->setAmbientColor(meshColor); blockRenderDetail->setDiffuseColor(meshColor); @@ -248,15 +250,6 @@ bool createCameraNavigationScene( surfaceMesh->setVertices(points); surfaceMesh->setTriangles(triArray); - // model - std::shared_ptr<MeshCollisionModel> targetModel = std::make_shared<MeshCollisionModel>(); - targetModel->setMesh(surfaceMesh); - targetModel->setRenderDetail(targetRenderDetail); - targetModel->getMesh()->scale(s); - targetModel->getMesh()->translate(t2); - targetModel->getMesh()->rotate(q); - targetModel->addTexture(targetFileName, "target"); - // Texture Coordinates double height = (bottomLeftEdge - topLeftEdge).norm(); double width = (bottomLeftEdge - bottomRightEdge).norm(); @@ -279,6 +272,14 @@ bool createCameraNavigationScene( surfaceMesh->addTextureCoordinate(1.0+dx,1.0+dy); surfaceMesh->addTextureCoordinate(-dx,1.0+dy); + // model + std::shared_ptr<MeshCollisionModel> targetModel = std::make_shared<MeshCollisionModel>(); + targetModel->setMesh(surfaceMesh); + targetModel->setRenderDetail(targetRenderDetail); + targetModel->getMesh()->scale(s); + targetModel->getMesh()->translate(t2); + targetModel->getMesh()->rotate(q); + // object std::shared_ptr<StaticSceneObject> targetObject = std::make_shared<StaticSceneObject>(); targetObject->setModel(targetModel); diff --git a/Examples/Shaders/CMakeLists.txt b/Examples/Shaders/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..493c99c43081f0081dc7531e2a354ce968f95bef --- /dev/null +++ b/Examples/Shaders/CMakeLists.txt @@ -0,0 +1,38 @@ +set(APP Shaders) + +include(${VTK_USE_FILE}) + +add_executable(${APP} main.cpp) +target_link_libraries(${APP} + Core + Geometry + VTKRendering + Rendering + Mesh + Event + IO + ) + +set_target_properties(${APP} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" +) + +set(${APP}_DATA "${CMAKE_CURRENT_BINARY_DIR}") +if(NOT EXISTS ${${APP}_DATA}) + file(MAKE_DIRECTORY ${${APP}_DATA}) +endif() + +set(FILE_URL http://midas3.kitware.com/midas/download/item/318851/ShadersData.tar) +set(FILE_SHA1 df719673804075b4505ea267b39e5cd68568f72c) +set(LOCAL_FILE ${EXAMPLES_DATA}/ShadersData.tar) + +midas_download(${FILE_URL} ${FILE_SHA1} ${LOCAL_FILE}) + +add_custom_command( + TARGET ${APP} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E tar xf ${LOCAL_FILE} + WORKING_DIRECTORY ${${APP}_DATA} + COMMENT "-- Unpacking ${LOCAL_FILE}" +) diff --git a/Examples/Shaders/main.cpp b/Examples/Shaders/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..29600b57be6ee4d965e6a23d0a3814569e553905 --- /dev/null +++ b/Examples/Shaders/main.cpp @@ -0,0 +1,134 @@ +// This file is part of the SimMedTK project. +// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, +// Rensselaer Polytechnic Institute +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//--------------------------------------------------------------------------- +// +// Authors: +// +// Contact: +//--------------------------------------------------------------------------- + +#include <memory> + +// Core SimMedTK includes +#include "Core/SDK.h" +#include "Geometry/MeshModel.h" + +#include "IO/InitIO.h" +#include "VTKRendering/InitVTKRendering.h" +#include "IO/IOMesh.h" + +int main() +{ + InitVTKRendering(); + InitIODelegates(); + + //------------------------------------------------------- + // 1. Create an instance of the SimMedTK framework/SDK + // 2. Create viewer + // 3. Create default scene (scene 0) + //------------------------------------------------------- + auto sdk = SDK::createStandardSDK(); + + //------------------------------------------------------- + // Customize the viewer + //------------------------------------------------------- + auto viewer = sdk->getViewerInstance(); + + viewer->viewerRenderDetail = viewer->viewerRenderDetail | + SIMMEDTK_VIEWERRENDER_FADEBACKGROUND | + SIMMEDTK_VIEWERRENDER_GLOBAL_AXIS; + + viewer->setGlobalAxisLength(0.8); + + //------------------------------------------------------- + // Setup Shaders and textures + //------------------------------------------------------- + Shaders::createShader("wetshader", "ShadersData/shaders/wet_vert.glsl", "ShadersData/shaders/wet_frag.glsl", ""); + + // Mesh render detail + auto meshRenderDetail = std::make_shared<RenderDetail>(SIMMEDTK_RENDER_FACES | SIMMEDTK_RENDER_NORMALS ); + meshRenderDetail->setAmbientColor(Color(0.2,0.2,0.2,1.0)); + meshRenderDetail->setDiffuseColor(Color::colorGray); + meshRenderDetail->setSpecularColor(Color(1.0, 1.0, 1.0,0.5)); + meshRenderDetail->setShininess(20.0); + + meshRenderDetail->addShaderProgram("wetshader"); + meshRenderDetail->addTexture("decal", "ShadersData/textures/brainx.bmp", "textureDecal", "wetshader"); + meshRenderDetail->addTexture("bump", "ShadersData/textures/metalbump.jpg", "textureBump", "wetshader"); + + // Plane render detail + auto planeMeshRenderDetail = std::make_shared<RenderDetail>(SIMMEDTK_RENDER_FACES | SIMMEDTK_RENDER_NORMALS); + planeMeshRenderDetail->setAmbientColor(Color(0.2, 0.2, 0.2, 1.0)); + planeMeshRenderDetail->setDiffuseColor(Color::colorGray); + planeMeshRenderDetail->setSpecularColor(Color(1.0, 1.0, 1.0, 0.5)); + planeMeshRenderDetail->setShininess(20.0); + + planeMeshRenderDetail->addShaderProgram("wetshader"); + planeMeshRenderDetail->addTexture("decal", "ShadersData/textures/brain_outside.jpg", "textureDecal", "wetshader"); + planeMeshRenderDetail->addTexture("bump", "ShadersData/textures/metalbump.jpg", "textureBump", "wetshader"); + + //------------------------------------------------------- + // Customize the scene + //------------------------------------------------------- + // Get Scene + auto scene = sdk->getScene(0); + viewer->registerScene(scene); + + // Setup Cube + auto cubeModel = std::make_shared<MeshModel>(); + cubeModel->load("ShadersData/models/brain.obj"); + //cubeModel->load("ShadersData/models/brain.3ds"); + cubeModel->setRenderDetail(meshRenderDetail); + + auto cube = std::make_shared<StaticSceneObject>(); + cube->setModel(cubeModel); + scene->addSceneObject(cube); + + // Setup Plane + auto planeModel = std::make_shared<MeshModel>(); + planeModel->load("ShadersData/models/plane.obj"); + planeModel->setRenderDetail(planeMeshRenderDetail); + + auto planeObject = std::make_shared<StaticSceneObject>(); + planeObject->setModel(planeModel); + scene->addSceneObject(planeObject); + + // Setup Scene lighting + auto light1 = Light::getDefaultLighting(); + light1->lightPos.setPosition(core::Vec3d(-25.0, 10.0, 10.0)); + scene->addLight(light1); + + auto light2 = Light::getDefaultLighting(); + light2->lightPos.setPosition(core::Vec3d(25.0, 10.0, 10.0)); + scene->addLight(light2); + + // Camera setup + auto sceneCamera = Camera::getDefaultCamera(); + sceneCamera->setPos(-200,0,0); + sceneCamera->setZoom(.5); + scene->addCamera(sceneCamera); + + //------------------------------------------------------- + // Run the SDK + //------------------------------------------------------- + sdk->run(); + + //cleanup + sdk->releaseScene(scene); + + return 0; +} diff --git a/Geometry/MeshModel.cpp b/Geometry/MeshModel.cpp index 38b2dd9bbdcfad2424f307da22246c7c7ec8ec7c..df7b4cf06932ca1f45ee5a0a070cfce454c38426 100644 --- a/Geometry/MeshModel.cpp +++ b/Geometry/MeshModel.cpp @@ -40,6 +40,7 @@ void MeshModel::load(const std::string& meshName) reader->read(meshName); this->mesh = reader->getMesh(); + this->mesh->setMeshType ((int)reader->getFileType()); } const std::vector<core::Vec3d>& MeshModel::getVertices() const @@ -69,25 +70,3 @@ void MeshModel::setRenderDetail(std::shared_ptr< RenderDetail > renderDetail) { this->mesh->setRenderDetail(renderDetail); } -void MeshModel::addTexture(const std::string& textureFileName, const std::string& textureName) -{ - std::shared_ptr<SurfaceMesh> surfaceMesh = std::dynamic_pointer_cast<SurfaceMesh>(this->mesh); - if(!surfaceMesh) - { - std::cerr << "Cant assign texture to non-surface mesh." << std::endl; - return; - } - - if(surfaceMesh->getRenderDetail()) - { - surfaceMesh->getRenderDetail()->setTextureFilename(textureFileName); - } - else - { - auto renderDetail = std::make_shared<RenderDetail>(); - renderDetail->setTextureFilename(textureFileName); - surfaceMesh->setRenderDetail(renderDetail); - } - - surfaceMesh->assignTexture(textureName); -} diff --git a/Geometry/MeshModel.h b/Geometry/MeshModel.h index 4b3f0d0c41f1bba77832a45a22cf7405ea8c9522..8055d6751c3dac574a7ef9073c68bc1f056a409c 100644 --- a/Geometry/MeshModel.h +++ b/Geometry/MeshModel.h @@ -32,6 +32,7 @@ #include "Core/Model.h" #include "Mesh/SurfaceMesh.h" + /// /// @brief Mesh representation of a model. /// Base class used by all models that can be represented by a mesh @@ -86,13 +87,9 @@ public: /// std::shared_ptr<Core::BaseMesh> getMesh() override; - /// - /// \brief Assign texture to the surface mesh - /// - void addTexture(const std::string& textureFileName, const std::string& textureName); - protected: std::shared_ptr<Core::BaseMesh> mesh; // Underlying mesh + }; #endif // SMMESHMODEL_H diff --git a/IO/IOMesh.h b/IO/IOMesh.h index 7609c7d071324a2eb6e50de155548540e68778ff..be050024e38294edc3dc175353d2c01748e5ede3 100644 --- a/IO/IOMesh.h +++ b/IO/IOMesh.h @@ -69,7 +69,7 @@ public: /// \brief Enum class for the type of files this mesh io expect, /// add more types here to extend the mesh io. /// - enum class MeshFileType + enum class MeshFileType:int { VTK, VTU, diff --git a/Mesh/SurfaceMesh.cpp b/Mesh/SurfaceMesh.cpp index 13ad80e9d084df837c5eaecc0bc1cb00161d256c..c426ead21e6a3a4f63f6ab0ed0a00f6b33464ef0 100644 --- a/Mesh/SurfaceMesh.cpp +++ b/Mesh/SurfaceMesh.cpp @@ -119,52 +119,87 @@ void SurfaceMesh::computeTriangleTangents() return; } - this->triangleTangents.resize(this->triangleArray.size()); - - // First, calculate the triangle tangents - for(size_t t = 0, end = this->triangleArray.size(); t < end; ++t) + if (this->useThreeDSTexureCoordinates) { - const auto &triangle = this->triangleArray[t]; + this->triangleTangents.resize(this->triangleArray.size()); - // Get triangle vertices - const auto &v0 = this->vertices[triangle[0]]; - const auto &v1 = this->vertices[triangle[1]]; - const auto &v2 = this->vertices[triangle[2]]; + // First, calculate the triangle tangents + for (size_t t = 0, end = this->triangleArray.size(); t < end; ++t) + { + const auto &triangle = this->triangleArray[t]; - // Get texture coordinates for triangle - const auto &t0 = this->textureCoord[triangle[0]]; - const auto &t1 = this->textureCoord[triangle[1]]; - const auto &t2 = this->textureCoord[triangle[2]]; + // Get triangle vertices + const auto &v0 = this->vertices[triangle[0]]; + const auto &v1 = this->vertices[triangle[1]]; + const auto &v2 = this->vertices[triangle[2]]; - // COMMENT: I am not sure why two different types of tangent calculations are used here. - this->triangleTangents[t] = ((t1[1] - t0[1])*(v1 - v0) - (t2[1] - t0[1])*(v2 - v0)); + // Get texture coordinates for triangle + const auto &t0 = this->textureCoord[triangle[0]]; + const auto &t1 = this->textureCoord[triangle[1]]; + const auto &t2 = this->textureCoord[triangle[2]]; - if(this->useThreeDSTexureCoordinates) - { - float r = 1.0/((t1[0]-t0[0])*(t2[1]-t0[1]) - (t1[1]-t0[1])*(t2[0]-t0[0])); - this->triangleTangents[t] *= r; - } + double tt1 = t1[0] - t0[0]; + double tt2 = t2[0] - t0[0]; - this->triangleTangents[t].normalize(); - } + double bb1 = t1[1] - t0[1]; + double bb2 = t2[1] - t0[1]; + auto V1 = v1 - v0; + auto V2 = v2 - v0; + double r = 1.0F / (tt1 * bb2 - tt2 * bb1); + this->triangleTangents[t][0] = (bb2*V1[0] - bb1*V2[0])*r; + this->triangleTangents[t][1] = (bb2*V1[1] - bb1*V2[1])*r; + this->triangleTangents[t][2] = (bb2*V1[2] - bb1*V2[2])*r; - // Calculate the vertex tangents - if(this->useThreeDSTexureCoordinates || this->useOBJDSTexureCoordinates) + this->triangleTangents[t].normalize(); + } + } + else if (this->useOBJDSTexureCoordinates) { - for(size_t v = 0, end = this->vertices.size(); v < end; ++v) + this->triangleTangents.resize(this->triangleArray.size()); + // First, calculate the triangle tangents + for (size_t t = 0, end = this->vertices.size()/3; t < end; ++t) { - this->vertexTangents[v][0] = this->vertexTangents[v][1] = this->vertexTangents[v][2] = 0; + // Get triangle vertices + const auto &v0 = this->vertices[t*3]; + const auto &v1 = this->vertices[t*3+1]; + const auto &v2 = this->vertices[t*3+2]; + + // Get texture coordinates for triangle + const auto &t0 = this->textureCoord[t * 3]; + const auto &t1 = this->textureCoord[t * 3 + 1]; + const auto &t2 = this->textureCoord[t * 3 + 2]; + + double tt1 = t1[0] - t0[0]; + double tt2 = t2[0] - t0[0]; - for(size_t i = 0; i < this->vertexTriangleNeighbors[v].size(); i++) - { - this->vertexTangents[v] += this->triangleTangents[this->vertexTriangleNeighbors[v][i]]; - } - this->vertexTangents[v].normalize(); - this->vertexTangents[v] -= this->vertexNormals[v]*this->vertexNormals[v].dot(this->vertexTangents[v]); - this->vertexTangents[v].normalize(); + double bb1 = t1[1] - t0[1]; + double bb2 = t2[1] - t0[1]; + auto V1 = v1 - v0; + auto V2 = v2 - v0; + double r = 1.0F / (tt1 * bb2 - tt2 * bb1); + this->triangleTangents[t][0] = (bb2*V1[0] - bb1*V2[0])*r; + this->triangleTangents[t][1] = (bb2*V1[1] - bb1*V2[1])*r; + this->triangleTangents[t][2] = (bb2*V1[2] - bb1*V2[2])*r; + + this->triangleTangents[t].normalize(); } } + + this->vertexTangents.resize(this->vertices.size(), core::Vec3d::Zero()); + for (size_t v = 0, end = this->vertices.size(); v < end; ++v) + { + this->vertexTangents[v][0] = this->vertexTangents[v][1] = this->vertexTangents[v][2] = 0; + + for (size_t i = 0; i < this->vertexTriangleNeighbors[v].size(); i++) + { + this->vertexTangents[v] += this->triangleTangents[this->vertexTriangleNeighbors[v][i]]; + } + + this->vertexTangents[v].normalize(); + this->vertexTangents[v] -= this->vertexNormals[v] * this->vertexNormals[v].dot(this->vertexTangents[v]); + this->vertexTangents[v].normalize(); + } } void SurfaceMesh::checkTriangleOrientation() { @@ -201,14 +236,6 @@ std::vector< Eigen::Matrix< float, int(2), int(1) >, Eigen::aligned_allocator< E { return this->textureCoord; } -const std::vector< std::shared_ptr< SurfaceMesh::TextureAttachment > >& SurfaceMesh::getTextures() const -{ - return this->textures; -} -const int& SurfaceMesh::getTextureId(size_t i) const -{ - return this->textures[i]->textureId; -} void SurfaceMesh::addTextureCoordinate(const core::Vec2f& coord) { this->textureCoord.push_back(coord); @@ -221,24 +248,6 @@ void SurfaceMesh::addTextureCoordinate(const float& x, const float& y) { this->textureCoord.emplace_back(x,y); } -void SurfaceMesh::assignTexture(const std::string& referenceName) -{ - // TODO: This test has to be done at the rendrer level! -// int id; -// TextureManager::findTextureId(referenceName,id); -// -// if(id < 0) -// { -// std::cerr << "The texture " << referenceName -// << " cant be attached because it has not been processed by the manager." << std::endl; -// return; -// } -// - auto attachment = std::make_shared<TextureAttachment>(); - attachment->textureId = this->textures.size(); - attachment->textureName = referenceName; - this->textures.push_back(attachment); -} bool SurfaceMesh::isMeshTextured() const { if(!this->renderDetail) @@ -246,15 +255,17 @@ bool SurfaceMesh::isMeshTextured() const return false; } - return !this->renderDetail->getTextureFilename().empty(); + return this->renderDetail->getNumberOfTextures(); } void SurfaceMesh::setUseOBJTexture(bool use) { this->useOBJDSTexureCoordinates = use; + this->useThreeDSTexureCoordinates = !use; } void SurfaceMesh::setUseThreDSTexture(bool use) { this->useThreeDSTexureCoordinates = use; + this->useOBJDSTexureCoordinates = !use; } void SurfaceMesh::print() const { diff --git a/Mesh/SurfaceMesh.h b/Mesh/SurfaceMesh.h index 18b09edb7a602f495772b29295eeda999fbf33a1..4a107701e3ee336118a570c0e6d30864042df3a4 100644 --- a/Mesh/SurfaceMesh.h +++ b/Mesh/SurfaceMesh.h @@ -77,9 +77,6 @@ public: /// void checkTriangleOrientation(); - /// Texture handling - - struct TextureAttachment; /// /// \brief Returns the texture coordinates array. /// @@ -88,16 +85,6 @@ public: std::vector<core::Vec2f, Eigen::aligned_allocator<core::Vec2f>> &getTextureCoordinates(); - /// - /// \brief Returns the bounding box for this mesh. - /// - const std::vector<std::shared_ptr<TextureAttachment>> &getTextures() const; - - /// - /// \brief Returns the bounding box for this mesh. - /// - const int &getTextureId(size_t i) const; - /// /// \brief Return true if it contains texture coordinates /// @@ -109,11 +96,6 @@ public: void addTextureCoordinate(const core::Vec2f &coord); void addTextureCoordinate(const float &x, const float &y); - /// - /// \brief Assign the texture - /// - void assignTexture(const std::string& referenceName); - /// /// \brief Query if the mesh has textures available for rendering /// @@ -183,15 +165,15 @@ private: // List of vertex tangents std::vector<core::Vec3d> vertexTangents; + // List of vertex tangents + std::vector<core::Vec3d> vertexTangentsDelete; + // List of vertex neighbors std::vector<std::vector<size_t>> vertexNeighbors; // List of vertex neighbors std::vector<std::vector<size_t>> vertexTriangleNeighbors; - // Textures attached to this mesh. - std::vector<std::shared_ptr<TextureAttachment>> textures; - // Texture coordinates std::vector<core::Vec2f, Eigen::aligned_allocator<core::Vec2f>> textureCoord; @@ -200,24 +182,6 @@ private: bool useOBJDSTexureCoordinates; }; -/// -/// \brief Texture management structure -/// -struct SurfaceMesh::TextureAttachment -{ - TextureAttachment() : - textureId(-1), - textureName("") - { - } - - // Texture id - int textureId; - - // Texture internal name - std::string textureName; -}; - #endif diff --git a/Mesh/VegaVolumetricMesh.cpp b/Mesh/VegaVolumetricMesh.cpp index 13722682edfffd5523531d7a20b29844b1f8c3aa..1b0a4104224199b3b1a839634bb680f8d73c0707 100644 --- a/Mesh/VegaVolumetricMesh.cpp +++ b/Mesh/VegaVolumetricMesh.cpp @@ -115,7 +115,7 @@ void VegaVolumetricMesh::updateAttachedMeshes(double *q) { vertices[i] = restPositions[i] + displacements[i]; } -// renderingMesh->computeTriangleNormals(); + renderingMesh->computeTriangleNormals(); renderingMesh->getRenderDelegate()->modified(); } diff --git a/RenderDelegates/AABBRenderDelegate.cpp b/RenderDelegates/AABBRenderDelegate.cpp deleted file mode 100644 index ca5774c19402c39ed176108c4e181804d07a26af..0000000000000000000000000000000000000000 --- a/RenderDelegates/AABBRenderDelegate.cpp +++ /dev/null @@ -1,84 +0,0 @@ -// This file is part of the SimMedTK project. -// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, -// Rensselaer Polytechnic Institute -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//--------------------------------------------------------------------------- -// -// Authors: -// -// Contact: -//--------------------------------------------------------------------------- - -#include "Core/Model.h" -#include "Core/Geometry.h" -#include "Core/RenderDelegate.h" -#include "Core/Factory.h" - -// VTK glew library -#include <vtk_glew.h> - -#ifndef __APPLE__ -# include <GL/gl.h> // for GLfloat, etc. -#else -# include <OpenGL/gl.h> // for GLfloat, etc. -#endif - -class AABBRenderDelegate : public RenderDelegate -{ -public: - virtual void draw() const override; -}; - -void AABBRenderDelegate::draw() const -{ - AABB* geom = this->getSourceGeometryAs<AABB>(); - if (!geom) - return; - - glBegin(GL_LINES); - { - glVertex3d(geom->aabbMin[0], geom->aabbMin[1], geom->aabbMin[2]); - glVertex3d(geom->aabbMin[0], geom->aabbMin[1], geom->aabbMax[2]); - glVertex3d(geom->aabbMin[0], geom->aabbMax[1], geom->aabbMin[2]); - glVertex3d(geom->aabbMin[0], geom->aabbMax[1], geom->aabbMax[2]); - glVertex3d(geom->aabbMax[0], geom->aabbMin[1], geom->aabbMin[2]); - glVertex3d(geom->aabbMax[0], geom->aabbMin[1], geom->aabbMax[2]); - glVertex3d(geom->aabbMax[0], geom->aabbMax[1], geom->aabbMin[2]); - glVertex3d(geom->aabbMax[0], geom->aabbMax[1], geom->aabbMax[2]); - - glVertex3d(geom->aabbMin[0], geom->aabbMin[1], geom->aabbMin[2]); - glVertex3d(geom->aabbMin[0], geom->aabbMax[1], geom->aabbMin[2]); - glVertex3d(geom->aabbMin[0], geom->aabbMin[1], geom->aabbMax[2]); - glVertex3d(geom->aabbMin[0], geom->aabbMax[1], geom->aabbMax[2]); - glVertex3d(geom->aabbMax[0], geom->aabbMin[1], geom->aabbMin[2]); - glVertex3d(geom->aabbMax[0], geom->aabbMax[1], geom->aabbMin[2]); - glVertex3d(geom->aabbMax[0], geom->aabbMin[1], geom->aabbMax[2]); - glVertex3d(geom->aabbMax[0], geom->aabbMax[1], geom->aabbMax[2]); - - glVertex3d(geom->aabbMin[0], geom->aabbMin[1], geom->aabbMin[2]); - glVertex3d(geom->aabbMax[0], geom->aabbMin[1], geom->aabbMin[2]); - glVertex3d(geom->aabbMin[0], geom->aabbMax[1], geom->aabbMin[2]); - glVertex3d(geom->aabbMax[0], geom->aabbMax[1], geom->aabbMin[2]); - glVertex3d(geom->aabbMin[0], geom->aabbMin[1], geom->aabbMax[2]); - glVertex3d(geom->aabbMax[0], geom->aabbMin[1], geom->aabbMax[2]); - glVertex3d(geom->aabbMin[0], geom->aabbMax[1], geom->aabbMax[2]); - glVertex3d(geom->aabbMax[0], geom->aabbMax[1], geom->aabbMax[2]); - } - glEnd(); -} - -RegisterFactoryClass(RenderDelegate, - AABBRenderDelegate, - RenderDelegate::RendererType::Other) diff --git a/RenderDelegates/CMakeLists.txt b/RenderDelegates/CMakeLists.txt deleted file mode 100644 index 2ccc7801dfddaa59d2004dbbdb47ec5413ba3cdd..0000000000000000000000000000000000000000 --- a/RenderDelegates/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -include(${VTK_USE_FILE}) -simmedtk_add_library(RenderDelegates - SOURCES - AABBRenderDelegate.cpp - MeshRenderDelegate.cpp - PlaneRenderDelegate.cpp - SceneObjectDeformableRenderDelegate.cpp - StaticSceneObjectRenderDelegate.cpp - SurfaceTreeRenderDelegate.cpp - InitRenderDelegates.cpp - PUBLIC_HEADERS - InitRenderDelegates.h -) - -target_link_libraries(RenderDelegates - PRIVATE - Core - Rendering - Mesh - Simulators -) diff --git a/RenderDelegates/FemSceneRenderDelegate.cpp b/RenderDelegates/FemSceneRenderDelegate.cpp deleted file mode 100644 index 806d21821082e990769cf61b1f9716dffcdb1cf1..0000000000000000000000000000000000000000 --- a/RenderDelegates/FemSceneRenderDelegate.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// This file is part of the SimMedTK project. -// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, -// Rensselaer Polytechnic Institute -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//--------------------------------------------------------------------------- -// -// Authors: -// -// Contact: -//--------------------------------------------------------------------------- - -#include "Core/Model.h" -#include "Simulators/FemSceneObject.h" -#include "Core/RenderDelegate.h" -#include "Core/Factory.h" -#include "Mesh/VolumeMesh.h" - -class FemSceneRenderDelegate : public RenderDelegate -{ -public: - virtual void draw() const override; -}; - -void FemSceneRenderDelegate::draw() const -{ - auto v_mesh = this->getSourceGeometryAs<FemSceneObject>()->v_mesh; - RenderDelegate::Ptr delegate = v_mesh->getRenderDelegate(); - if (delegate) - delegate->draw(); -} - -RegisterFactoryClass(RenderDelegate, - FemSceneRenderDelegate, - RenderDelegate::RendererType::Other) diff --git a/RenderDelegates/InitRenderDelegates.cpp b/RenderDelegates/InitRenderDelegates.cpp deleted file mode 100644 index 7c0dc33d3c8d0e26d7db2759432c31d8234d99a3..0000000000000000000000000000000000000000 --- a/RenderDelegates/InitRenderDelegates.cpp +++ /dev/null @@ -1,28 +0,0 @@ -// This file is part of the SimMedTK project. -// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, -// Rensselaer Polytechnic Institute -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//--------------------------------------------------------------------------- -// -// Authors: -// -// Contact: -//--------------------------------------------------------------------------- -#include "RenderDelegates/InitRenderDelegates.h" - -void InitRenderDelegates() -{ - SIMMEDTK_REGISTER_RENDER_DELEGATES(); -} diff --git a/RenderDelegates/InitRenderDelegates.h b/RenderDelegates/InitRenderDelegates.h deleted file mode 100644 index dbb76786fd995a457e684fb43b2cacce965d6377..0000000000000000000000000000000000000000 --- a/RenderDelegates/InitRenderDelegates.h +++ /dev/null @@ -1,41 +0,0 @@ -// This file is part of the SimMedTK project. -// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, -// Rensselaer Polytechnic Institute -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//--------------------------------------------------------------------------- -// -// Authors: -// -// Contact: -//--------------------------------------------------------------------------- -#ifndef SMRENDERDELEGATES_CONFIG_H -#define SMRENDERDELEGATES_CONFIG_H - -/// NOTE: This file should be only included once by the application. - -#include "Core/Config.h" - -#define SIMMEDTK_REGISTER_RENDER_DELEGATES() \ - SIMMEDTK_RUN_LOADER(register_OpenGLViewer); \ - SIMMEDTK_RUN_LOADER(register_AABBRenderDelegate); \ - SIMMEDTK_RUN_LOADER(register_MeshRenderDelegate); \ - SIMMEDTK_RUN_LOADER(register_PlaneRenderDelegate); \ - SIMMEDTK_RUN_LOADER(register_SceneObjectDeformableRenderDelegate); \ - SIMMEDTK_RUN_LOADER(register_StaticSceneObjectRenderDelegate); \ - SIMMEDTK_RUN_LOADER(register_SurfaceTreeRenderDelegate); - -void InitRenderDelegates(); - -#endif // SMRENDERDELEGATES_CONFIG_H diff --git a/RenderDelegates/MeshRenderDelegate.cpp b/RenderDelegates/MeshRenderDelegate.cpp deleted file mode 100644 index c2a887b68650a111d332d9d926a0f3bd23eab30a..0000000000000000000000000000000000000000 --- a/RenderDelegates/MeshRenderDelegate.cpp +++ /dev/null @@ -1,68 +0,0 @@ -// This file is part of the SimMedTK project. -// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, -// Rensselaer Polytechnic Institute -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//--------------------------------------------------------------------------- -// -// Authors: -// -// Contact: -//--------------------------------------------------------------------------- - -#include "Core/Model.h" -#include "Core/Geometry.h" -#include "Core/RenderDelegate.h" -#include "Core/Factory.h" -#include "Mesh/SurfaceMesh.h" - -class MeshRenderDelegate : public RenderDelegate -{ -public: - virtual void draw() const override; - virtual bool isTargetTextured() const override; -}; - -void MeshRenderDelegate::draw() const -{ - auto geom = this->getSourceGeometryAs<SurfaceMesh>(); - if(!geom) - { - return; - } - - auto mesh = std::static_pointer_cast<SurfaceMesh>(geom->shared_from_this()); - OpenGLRenderer::drawSurfaceMeshTriangles(mesh, geom->getRenderDetail()); - - if(geom->getRenderDetail()->renderType & SIMMEDTK_RENDER_NORMALS) - { - OpenGLRenderer::drawNormals(mesh, - geom->getRenderDetail()->normalColor, - geom->getRenderDetail()->normalLength); - } -} - -bool MeshRenderDelegate::isTargetTextured() const -{ - auto geom = this->getSourceGeometryAs<SurfaceMesh>(); - if(!geom) - { - return false; - } - return geom->isMeshTextured(); -} - -RegisterFactoryClass(RenderDelegate, - MeshRenderDelegate, - RenderDelegate::RendererType::Other) diff --git a/RenderDelegates/PlaneRenderDelegate.cpp b/RenderDelegates/PlaneRenderDelegate.cpp deleted file mode 100644 index 3320f3db34b738e901a20380ac05cdaf5e1d9bbb..0000000000000000000000000000000000000000 --- a/RenderDelegates/PlaneRenderDelegate.cpp +++ /dev/null @@ -1,68 +0,0 @@ -// This file is part of the SimMedTK project. -// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, -// Rensselaer Polytechnic Institute -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//--------------------------------------------------------------------------- -// -// Authors: -// -// Contact: -//--------------------------------------------------------------------------- - -#include "Core/Model.h" -#include "Core/Geometry.h" -#include "Core/RenderDelegate.h" -#include "Core/Factory.h" - -class PlaneRenderDelegate : public RenderDelegate -{ -public: - virtual void draw() const override; -}; - -void PlaneRenderDelegate::draw() const -{ - OpenGLRenderer::draw(*this->getSourceGeometryAs<Plane>()); -// if (this->movedOrRotated) -// { -// updateDrawPoints(); -// } -// glEnable(GL_LIGHTING); -// -// glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, Color::colorGray.toGLColor<GLfloat>()); -// glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Color::colorWhite.toGLColor<GLfloat>()); -// glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, Color::colorGray.toGLColor<GLfloat>()); -// -// glEnable(GL_BLEND); -// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); -// -// glPushMatrix(); -// glBegin(GL_QUADS); -// glVertex3f(this->drawPoints[0][0], this->drawPoints[0][1], this->drawPoints[0][2]); -// glVertex3f(this->drawPoints[1][0], this->drawPoints[1][1], this->drawPoints[1][2]); -// glVertex3f(this->drawPoints[2][0], this->drawPoints[2][1], this->drawPoints[2][2]); -// glVertex3f(this->drawPoints[3][0], this->drawPoints[3][1], this->drawPoints[3][2]); -// glEnd(); -// glPopMatrix(); -// -// glDisable(GL_BLEND); -// -// glEnable(GL_LIGHTING); - -} - -RegisterFactoryClass(RenderDelegate, - PlaneRenderDelegate, - RenderDelegate::RendererType::Other) diff --git a/RenderDelegates/SceneObjectDeformableRenderDelegate.cpp b/RenderDelegates/SceneObjectDeformableRenderDelegate.cpp deleted file mode 100644 index 75a29f679512fc7e458452ce0181c107d9d5a70d..0000000000000000000000000000000000000000 --- a/RenderDelegates/SceneObjectDeformableRenderDelegate.cpp +++ /dev/null @@ -1,69 +0,0 @@ -// This file is part of the SimMedTK project. -// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, -// Rensselaer Polytechnic Institute -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//--------------------------------------------------------------------------- -// -// Authors: -// -// Contact: -//--------------------------------------------------------------------------- - -#include "Core/Model.h" -#include "Core/Geometry.h" -#include "Core/RenderDelegate.h" -#include "Core/Factory.h" -#include "Simulators/SceneObjectDeformable.h" -#include "Simulators/VegaFemSceneObject.h" -#include "Mesh/VegaVolumetricMesh.h" -#include "Mesh/SurfaceMesh.h" - -/// \brief Displays the fem object with primary or secondary mesh, fixed vertices, -/// vertices interacted with, ground plane etc. -class SceneObjectDeformableRenderDelegate : public RenderDelegate -{ -public: - virtual void draw() const override; -}; - -void SceneObjectDeformableRenderDelegate::draw() const -{ - auto geom = this->getSourceGeometryAs<VegaFemSceneObject>(); - - if(!geom) - { - return; - } - auto mesh = geom->getVolumetricMesh(); - if(!mesh) - { - return; - } - auto surfaceMesh = mesh->getAttachedMesh(0); - if(!surfaceMesh) - { - return; - } - auto delegate = surfaceMesh->getRenderDelegate(); - if(!delegate) - { - return; - } - delegate->draw(); -} - -RegisterFactoryClass(RenderDelegate, - SceneObjectDeformableRenderDelegate, - RenderDelegate::RendererType::Other) diff --git a/RenderDelegates/StaticSceneObjectRenderDelegate.cpp b/RenderDelegates/StaticSceneObjectRenderDelegate.cpp deleted file mode 100644 index e46391f3e7878beb3e81c1d008382bc93d6af7b5..0000000000000000000000000000000000000000 --- a/RenderDelegates/StaticSceneObjectRenderDelegate.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// This file is part of the SimMedTK project. -// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, -// Rensselaer Polytechnic Institute -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//--------------------------------------------------------------------------- -// -// Authors: -// -// Contact: -//--------------------------------------------------------------------------- - -#include "Core/Model.h" -#include "Core/Geometry.h" -#include "Core/StaticSceneObject.h" -#include "Core/RenderDelegate.h" -#include "Core/Factory.h" - -class StaticSceneObjectRenderDelegate : public RenderDelegate -{ -public: - virtual void draw() const override; -}; - -void StaticSceneObjectRenderDelegate::draw() const -{ - StaticSceneObject* geom = this->getSourceGeometryAs<StaticSceneObject>(); - if (!geom) - return; - - geom->getModel()->draw(); -} - -RegisterFactoryClass(RenderDelegate, - StaticSceneObjectRenderDelegate, - RenderDelegate::RendererType::Other) diff --git a/RenderDelegates/SurfaceTreeRenderDelegate.cpp b/RenderDelegates/SurfaceTreeRenderDelegate.cpp deleted file mode 100644 index 78fa4cc50e25d28d94f89dd7645ed2c30ca525f8..0000000000000000000000000000000000000000 --- a/RenderDelegates/SurfaceTreeRenderDelegate.cpp +++ /dev/null @@ -1,86 +0,0 @@ -// This file is part of the SimMedTK project. -// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, -// Rensselaer Polytechnic Institute -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//--------------------------------------------------------------------------- -// -// Authors: -// -// Contact: -//--------------------------------------------------------------------------- - -#include "Core/Model.h" -#include "Core/RenderDelegate.h" -#include "Core/Factory.h" -#include "Collision/MeshCollisionModel.h" -#include "Collision/SurfaceTree.h" - -#include <vtk_glew.h> - -#ifndef __APPLE__ -# include <GL/gl.h> // for GLfloat, etc. -#else -# include <OpenGL/gl.h> // for GLfloat, etc. -#endif - -class SurfaceTreeRenderDelegate : public RenderDelegate -{ -public: - virtual void draw() const override; - - template<typename T> - bool drawTree() const; -}; - -/// \brief Draw the surface tree. -void SurfaceTreeRenderDelegate::draw() const -{ - if (this->drawTree<SurfaceTree<MeshCollisionModel::AABBNodeType>>()) - return; - if (this->drawTree<SurfaceTree<OctreeCell>>()) - return; -} - -template<typename T> -bool SurfaceTreeRenderDelegate::drawTree() const -{ - T* geom = this->getSourceGeometryAs<T>(); - if (!geom) - return false; - - core::Vec3d center; - glColor3fv(Color::colorGreen.toGLColor<GLfloat>()); - - glEnable(GL_LIGHTING); - glPushAttrib(GL_LIGHTING_BIT); - glColor3fv(Color::colorGreen.toGLColor<GLfloat>()); - glColor3fv(Color::colorBlue.toGLColor<GLfloat>()); - - glPushMatrix(); - glColor3fv(Color::colorPink.toGLColor<GLfloat>()); - - geom->getRoot()->draw(); - - glPopMatrix(); - - - glPopAttrib(); - glEnable(GL_LIGHTING); - return true; -} - -RegisterFactoryClass(RenderDelegate, - SurfaceTreeRenderDelegate, - RenderDelegate::RendererType::Other) diff --git a/Rendering/CMakeLists.txt b/Rendering/CMakeLists.txt index bff323323c0703ffded6c7cf560beeb69585adf6..5503b2a131ca17b9abf08d504d0c02951c31ac2b 100644 --- a/Rendering/CMakeLists.txt +++ b/Rendering/CMakeLists.txt @@ -7,8 +7,6 @@ simmedtk_add_library(Rendering FrameBuffer.cpp GLUtils.cpp MetalShader.cpp - OpenGLRenderer.cpp - OpenGLViewer.cpp SceneTextureShader.cpp Shader.cpp TextureManager.cpp @@ -19,8 +17,6 @@ simmedtk_add_library(Rendering FrameBuffer.h GLUtils.h MetalShader.h - OpenGLRenderer.h - OpenGLViewer.h SceneTextureShader.h Shader.h TextureManager.h @@ -40,7 +36,6 @@ target_link_libraries(Rendering sfml::graphics sfml::window sfml::system - vtkglew ) diff --git a/Rendering/FrameBuffer.cpp b/Rendering/FrameBuffer.cpp index 32d749fa0c8628602183bd8c856e25d5f36419b9..71a289d624dde9e85c54eeebafed0dc7a47bd53f 100644 --- a/Rendering/FrameBuffer.cpp +++ b/Rendering/FrameBuffer.cpp @@ -26,7 +26,6 @@ #include <string.h> #include "Core/Config.h" #include "Rendering/TextureManager.h" -#include "Rendering/OpenGLRenderer.h" bool FrameBuffer::checkStatus() { diff --git a/Rendering/MetalShader.cpp b/Rendering/MetalShader.cpp index 7ef56f1846dab3e3fd8d1948d6a3b06b83924c4f..5f796d0957eb6e11e705e3cbae94a009a2b70bd1 100644 --- a/Rendering/MetalShader.cpp +++ b/Rendering/MetalShader.cpp @@ -98,11 +98,11 @@ void MetalShader::initDraw() void MetalShader::predraw(std::shared_ptr<Core::BaseMesh> mesh ) { - specularPowerValue = mesh->getRenderDetail()->shininess; + specularPowerValue = mesh->getRenderDetail()->getShininess(); glUniform1fARB( specularPower, specularPowerValue ); glUniform1fARB( alphaMapGain, alphaMapGainValue ); - if ( mesh->getRenderDetail()->canGetShadow ) + if ( mesh->getRenderDetail()->getCanGetShadow() ) { glUniform1fARB( canGetShadowUniform, 1 ); } @@ -168,7 +168,7 @@ void MetalShaderShadow::predraw( std::shared_ptr<Core::BaseMesh> p_mesh ) { MetalShader::predraw( p_mesh ); - if ( p_mesh->getRenderDetail()->canGetShadow ) + if ( p_mesh->getRenderDetail()->getCanGetShadow() ) { glUniform1fARB( canGetShadowUniform, 1 ); } diff --git a/Rendering/OpenGLRenderer.cpp b/Rendering/OpenGLRenderer.cpp deleted file mode 100644 index a7be4f507dc6e2dcd1af68a9dc758a32da78431f..0000000000000000000000000000000000000000 --- a/Rendering/OpenGLRenderer.cpp +++ /dev/null @@ -1,655 +0,0 @@ -// This file is part of the SimMedTK project. -// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, -// Rensselaer Polytechnic Institute -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//--------------------------------------------------------------------------- -// -// Authors: -// -// Contact: -//--------------------------------------------------------------------------- - -#include "Core/DataStructures.h" -#include "Core/Quaternion.h" -#include "Core/RenderDelegate.h" -#include "Core/Geometry.h" -#include "Mesh/SurfaceMesh.h" -#include "Rendering/OpenGLRenderer.h" -#include "Rendering/OpenGLViewer.h" -#include "Rendering/TextureManager.h" -#include "Rendering/VAO.h" -#include "Rendering/GLUtils.h" - -#ifndef _MSC_VER -# pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#endif - - - -OpenGLRenderer::OpenGLRenderer() -{ - -} - -#if 0 -void OpenGLRenderer::drawLineMesh(std::shared_ptr<LineMesh> p_lineMesh, std::shared_ptr<RenderDetail> renderDetail) -{ - static core::Vec3d origin(0, 0, 0); - static core::Vec3d xAxis(1, 0, 0); - static core::Vec3d yAxis(0, 1, 0); - static core::Vec3d zAxis(0, 0, 1); - - const int renderType = renderDetail->getRenderType(); - - if (renderType & SIMMEDTK_RENDER_NONE) - { - return; - } - - glDisable(GL_TEXTURE_2D); - - glPointSize(renderDetail->getPointSize()); - glLineWidth(renderDetail->getLineSize()); - - if (renderType & SIMMEDTK_RENDER_TRANSPARENT) - { - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } - - if (renderType & SIMMEDTK_RENDER_MATERIALCOLOR) - { - glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, renderDetail->getColorDiffuse().toGLColor<GLfloat>()); - glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, renderDetail->getColorSpecular().toGLColor<GLfloat>()); - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, renderDetail->getColorAmbient().toGLColor<GLfloat>()); - glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, renderDetail->getShininess()); - } - - glEnableClientState(GL_VERTEX_ARRAY); - - if (renderType & SIMMEDTK_RENDER_TEXTURE) - { - if (p_lineMesh->isMeshTextured()) - { - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - - for (size_t t = 0; t < p_lineMesh->textureIds.size(); t++) - { - glActiveTexture(GL_TEXTURE0 + t); - TextureManager::activateTexture(p_lineMesh->textureIds[t].textureId); - } - } - } - - if (renderType & SIMMEDTK_RENDER_COLORMAP) - { - glEnableClientState(GL_COLOR_ARRAY); - } - - glVertexPointer(3, GL_FLOAT, 0, p_lineMesh->vertices.data()); - - if (renderType & SIMMEDTK_RENDER_TEXTURE) - { - if (p_lineMesh->isMeshTextured()) - { - glTexCoordPointer(2, GL_FLOAT, 0, p_lineMesh->texCoord); - } - } - - if (renderType & SIMMEDTK_RENDER_FACES) - { - glDrawElements(GL_LINES, p_lineMesh->nbrEdges * 2, GL_UNSIGNED_INT, p_lineMesh->edges); - } - - if ((renderType & (SIMMEDTK_RENDER_VERTICES))) - { - glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); - glDisable(GL_LIGHTING); - glDrawElements(GL_LINES, p_lineMesh->nbrEdges * 2, GL_UNSIGNED_INT, p_lineMesh->edges); - glEnable(GL_LIGHTING); - //default rendering - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - } - - if (renderType & SIMMEDTK_RENDER_WIREFRAME) - { - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - glPolygonOffset(3.0, 2.0); - glDisable(GL_LIGHTING); - glDrawElements(GL_LINES, p_lineMesh->nbrEdges * 2, GL_UNSIGNED_INT, p_lineMesh->edges); - glEnable(GL_LIGHTING); - //default rendering - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - } - - if (renderType & SIMMEDTK_RENDER_LOCALAXIS) - { - glEnable(GL_LIGHTING); - } - - if (renderType & SIMMEDTK_RENDER_HIGHLIGHTVERTICES) - { - glDisable(GL_LIGHTING); - glColor3fv(renderDetail->getHighLightColor().toGLColor<GLfloat>()); - glDrawArrays(GL_POINTS, 0, p_lineMesh->nbrVertices); - glEnable(GL_LIGHTING); - } - - if (renderType & SIMMEDTK_RENDER_TRANSPARENT) - { - glDisable(GL_BLEND); - } - - glDisableClientState(GL_VERTEX_ARRAY); - - if (renderType & SIMMEDTK_RENDER_TEXTURE) - { - if (p_lineMesh->isMeshTextured()) - { - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - - for (size_t t = 0; t < p_lineMesh->textureIds.size(); t++) - { - glActiveTexture(GL_TEXTURE0 + t); - TextureManager::disableTexture(p_lineMesh->textureIds[t].textureId); - } - } - } - - if (renderType & SIMMEDTK_RENDER_COLORMAP) - { - glDisableClientState(GL_COLOR_ARRAY); - } - - glEnable(GL_LIGHTING); - glPointSize(1.0); - glLineWidth(1.0); -} -#endif // 0 - -void OpenGLRenderer::drawSurfaceMeshTriangles( - std::shared_ptr<SurfaceMesh> p_surfaceMesh, - std::shared_ptr<RenderDetail> renderDetail) -{ - if (p_surfaceMesh->getRenderDetail()->getRenderType() & SIMMEDTK_RENDER_NONE) - { - return; - } - - glDisable(GL_TEXTURE_2D); - glPointSize(renderDetail->getPointSize()); - glLineWidth(renderDetail->getLineSize()); - - if (p_surfaceMesh->getRenderDetail()->getRenderType() & SIMMEDTK_RENDER_TRANSPARENT) - { - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } - - if (p_surfaceMesh->getRenderDetail()->getRenderType() & SIMMEDTK_RENDER_MATERIALCOLOR) - { - const GLfloat * color = renderDetail->getColorDiffuse().toGLColor<GLfloat>(); - glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color); - glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, renderDetail->getColorSpecular().toGLColor<GLfloat>()); - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, renderDetail->getColorAmbient().toGLColor<GLfloat>()); - glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, renderDetail->getShininess()); - } - - glEnableClientState(GL_VERTEX_ARRAY); - glVertexPointer(3, GL_DOUBLE, 0, p_surfaceMesh->getVertices().data()->data()); - glEnableClientState(GL_NORMAL_ARRAY); - glNormalPointer(GL_DOUBLE, 0, p_surfaceMesh->getVertexNormals().data()->data()); - - auto &meshTextures = p_surfaceMesh->getTextures(); - if (p_surfaceMesh->getRenderDetail()->getRenderType() & SIMMEDTK_RENDER_TEXTURE) - { - if (p_surfaceMesh->getRenderDelegate()->isTargetTextured()) - { - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glTexCoordPointer(2, GL_FLOAT, 0, p_surfaceMesh->getTextureCoordinates().data()->data()); - - for (size_t t = 0, end = meshTextures.size(); t < end; ++t) - { - glActiveTexture(GL_TEXTURE0 + t); - TextureManager::activateTexture(meshTextures[t]->textureName); - } - } - } - - if (p_surfaceMesh->getRenderDetail()->getRenderType() & SIMMEDTK_RENDER_COLORMAP) - { - glEnableClientState(GL_COLOR_ARRAY); - } - - if (p_surfaceMesh->getRenderDetail()->getRenderType() & SIMMEDTK_RENDER_FACES) - { - // TODO: Investigate why this expensive copy needs to be performed. - // Sean: I can only think because the data MUST be unsigned int or - // GLuint would really be the most appropriate, as per - // GL_UNSIGNED_INT. Also the vector could be a std::array. - std::vector<unsigned int> data; - for(auto t : p_surfaceMesh->getTriangles()) - { - data.emplace_back((unsigned int) t[0]); - data.emplace_back((unsigned int) t[1]); - data.emplace_back((unsigned int) t[2]); - } - glDrawElements(GL_TRIANGLES, data.size(), GL_UNSIGNED_INT, data.data()); - } - - if ((p_surfaceMesh->getRenderDetail()->getRenderType() & (SIMMEDTK_RENDER_VERTICES))) - { - glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); - glDisable(GL_LIGHTING); - glColor3fv(renderDetail->getVertexColor().toGLColor<GLfloat>()); - glDrawElements(GL_TRIANGLES, p_surfaceMesh->getTriangles().size() * 3, GL_UNSIGNED_INT, p_surfaceMesh->getTriangles().data()->data()); - - glEnable(GL_LIGHTING); - //default rendering - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - } - - if (p_surfaceMesh->getRenderDetail()->getRenderType() & SIMMEDTK_RENDER_WIREFRAME) - { - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - glLineWidth(renderDetail->getLineSize() + 0.5); - glPolygonOffset(1.0, 1.0); - glDisable(GL_LIGHTING); - glDisable(GL_TEXTURE_2D); - glColor4fv(renderDetail->getWireFrameColor().toGLColor<GLfloat>()); - - glDrawElements(GL_TRIANGLES, p_surfaceMesh->getTriangles().size() * 3, GL_UNSIGNED_INT, p_surfaceMesh->getTriangles().data()->data()); - - glEnable(GL_LIGHTING); - glEnable(GL_TEXTURE_2D); - glLineWidth(renderDetail->getLineSize()); - //default rendering - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - } - - if (p_surfaceMesh->getRenderDetail()->getRenderType() & SIMMEDTK_RENDER_HIGHLIGHTVERTICES) - { - glDisable(GL_LIGHTING); - glColor3fv(renderDetail->getHighLightColor().toGLColor<GLfloat>()); - glDrawArrays(GL_POINTS, 0, p_surfaceMesh->getNumberOfVertices()); - glEnable(GL_LIGHTING); - } - - if (p_surfaceMesh->getRenderDetail()->getRenderType() & SIMMEDTK_RENDER_TRANSPARENT) - { - glDisable(GL_BLEND); - } - - glDisableClientState(GL_VERTEX_ARRAY); - glDisableClientState(GL_NORMAL_ARRAY); - - if (p_surfaceMesh->getRenderDetail()->getRenderType() & SIMMEDTK_RENDER_TEXTURE) - { - if (p_surfaceMesh->getRenderDelegate()->isTargetTextured()) - { - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - - for (size_t t = 0, end = meshTextures.size(); t < end; ++t) - { - glActiveTexture(GL_TEXTURE0 + t); - TextureManager::disableTexture(p_surfaceMesh->getTextureId(t)); - } - } - } - - if (p_surfaceMesh->getRenderDetail()->getRenderType() & SIMMEDTK_RENDER_COLORMAP) - { - glDisableClientState(GL_COLOR_ARRAY); - } - - glEnable(GL_LIGHTING); - glPointSize(1.0); - glLineWidth(1.0); -} - -void OpenGLRenderer::drawNormals(std::shared_ptr<SurfaceMesh> p_mesh, Color p_color, float length) -{ - glDisable(GL_LIGHTING); - glColor3fv(reinterpret_cast<GLfloat*>(&p_color)); - core::Vec3d baryCenter; - core::Vec3d tmp; - - glBegin(GL_LINES); - - auto &vertices = p_mesh->getVertices(); - for (size_t i = 0, end = vertices.size(); i < end; i++) - { - glVertex3dv(vertices[i].data()); - tmp = vertices[i] + p_mesh->getVertexNormal(i) * length; - glVertex3dv(tmp.data()); - } - - auto const &triangles = p_mesh->getTriangles(); - for (size_t i = 0, end = p_mesh->getTriangles().size(); i < end; i++) - { - baryCenter = vertices[triangles[i][0]] + vertices[triangles[i][1]] + vertices[triangles[i][2]]; - baryCenter = baryCenter / 3.0; - glVertex3dv(baryCenter.data()); - tmp = baryCenter + p_mesh->getTriangleNormal(i) * length; - glVertex3dv(tmp.data()); - } - - glEnd(); - - glEnable(GL_LIGHTING); -} - -void OpenGLRenderer::beginTriangles() -{ - glBegin(GL_TRIANGLES); -} - -void OpenGLRenderer::drawTriangle(core::Vec3d &p_1, core::Vec3d &p_2, core::Vec3d &p_3) -{ - glVertex3dv(p_1.data()); - glVertex3dv(p_2.data()); - glVertex3dv(p_3.data()); -} - -void OpenGLRenderer::endTriangles() -{ - glEnd(); -} - -void OpenGLRenderer::draw(const Eigen::AlignedBox3d &aabb, Color p_color) -{ - glPushAttrib(GL_LIGHTING_BIT); - - glDisable(GL_LIGHTING); - glDisable(GL_TEXTURE_2D); - - glLineWidth(1.0); - glColor3fv(p_color.toGLColor<GLfloat>()); - glBegin(GL_LINES); - - auto const &min = aabb.min(); - auto const &max = aabb.max(); - - glVertex3d(min(0), min(0), min(2)); - glVertex3d(max(0), min(0), min(2)); - - glVertex3d(min(0), min(0), min(2)); - glVertex3d(min(0), max(0), min(2)); - - glVertex3d(min(0), min(0), min(2)); - glVertex3d(min(0), min(0), max(2)); - - glVertex3d(max(0), max(0), max(2)); - glVertex3d(min(0), max(0), max(2)); - - glVertex3d(max(0), max(0), max(2)); - glVertex3d(max(0), min(0), max(2)); - - glVertex3d(max(0), max(0), max(2)); - glVertex3d(max(0), max(0), min(2)); - - glVertex3d(min(0), max(0), max(2)); - glVertex3d(min(0), min(0), max(2)); - - glVertex3d(min(0), max(0), max(2)); - glVertex3d(min(0), max(0), min(2)); - - glVertex3d(max(0), min(0), max(2)); - glVertex3d(min(0), min(0), max(2)); - - glVertex3d(max(0), min(0), max(2)); - glVertex3d(max(0), min(0), min(2)); - - glVertex3d(max(0), max(0), min(2)); - glVertex3d(max(0), min(0), min(2)); - - glVertex3d(max(0), max(0), min(2)); - glVertex3d(min(0), max(0), min(2)); - glEnd(); - glLineWidth(1.0); - glEnable(GL_LIGHTING); - glPopAttrib(); -} - -void OpenGLRenderer::drawArrow(const core::Vec3f &start, const core::Vec3f &end, const float D) -{ - float x = end[0] - start[0]; - float y = end[1] - start[1]; - float z = end[2] - start[2]; - float L = sqrt(x*x + y*y + z*z); - - GLUquadricObj *quadObj; - - glPushMatrix(); - - glTranslated(start[0], start[1], start[2]); - - if ((x != 0.) || (y != 0.)) { - glRotated(atan2(y, x) / 0.0174533, 0., 0., 1.); - glRotated(atan2(sqrt(x*x + y*y), z) / 0.0174533, 0., 1., 0.); - } - else if (z<0){ - glRotated(180, 1., 0., 0.); - } - - glTranslatef(0, 0, L - 4 * D); - - quadObj = gluNewQuadric(); - gluQuadricDrawStyle(quadObj, GLU_FILL); - gluQuadricNormals(quadObj, GLU_SMOOTH); - gluCylinder(quadObj, 2 * D, 0.0, 4 * D, 32, 1); - gluDeleteQuadric(quadObj); - - quadObj = gluNewQuadric(); - gluQuadricDrawStyle(quadObj, GLU_FILL); - gluQuadricNormals(quadObj, GLU_SMOOTH); - gluDisk(quadObj, 0.0, 2 * D, 32, 1); - gluDeleteQuadric(quadObj); - - glTranslatef(0, 0, -L + 4 * D); - - quadObj = gluNewQuadric(); - gluQuadricDrawStyle(quadObj, GLU_FILL); - gluQuadricNormals(quadObj, GLU_SMOOTH); - gluCylinder(quadObj, D, D, L - 4 * D, 32, 1); - gluDeleteQuadric(quadObj); - - quadObj = gluNewQuadric(); - gluQuadricDrawStyle(quadObj, GLU_FILL); - gluQuadricNormals(quadObj, GLU_SMOOTH); - gluDisk(quadObj, 0.0, D, 32, 1); - gluDeleteQuadric(quadObj); - - glPopMatrix(); - -} - -void OpenGLRenderer::drawAxes(const float length) -{ - glDisable(GL_LIGHTING); - - float headWidth = length / 12; - - Eigen::Vector3f origin(0, 0, 0); - - glColor3fv(Color::colorRed.toGLColor<GLfloat>()); - glPushMatrix(); - drawArrow(origin, Eigen::Vector3f(length, 0, 0), headWidth); - glPopMatrix(); - - glColor3fv(Color::colorGreen.toGLColor<GLfloat>()); - glPushMatrix(); - drawArrow(origin, Eigen::Vector3f(0, length, 0), headWidth); - glPopMatrix(); - - glColor3fv(Color::colorBlue.toGLColor<GLfloat>()); - glPushMatrix(); - drawArrow(origin, Eigen::Vector3f(0, 0, length), headWidth); - glPopMatrix(); - - glEnable(GL_LIGHTING); -} - -void OpenGLRenderer::drawAxes(const Matrix33f &rotMat, const core::Vec3f &pos, const float length) -{ - glDisable(GL_LIGHTING); - - GLfloat headWidth = length / 12; - - glColor3fv(Color::colorRed.toGLColor<GLfloat>()); - glPushMatrix(); - Eigen::Vector3f xVec(length, 0, 0); - xVec = rotMat*xVec + pos; - drawArrow(pos, xVec, headWidth); - glPopMatrix(); - - glColor3fv(Color::colorGreen.toGLColor<GLfloat>()); - glPushMatrix(); - Eigen::Vector3f yVec(0, length, 0); - yVec = rotMat*yVec + pos; - drawArrow(pos, yVec, headWidth); - glPopMatrix(); - - glColor3fv(Color::colorBlue.toGLColor<GLfloat>()); - glPushMatrix(); - Eigen::Vector3f zVec(0, 0, length); - zVec = rotMat*zVec + pos; - drawArrow(pos, zVec, headWidth); - glPopMatrix(); - - glEnable(GL_LIGHTING); -} - -void OpenGLRenderer::draw(Plane &p_plane, float p_scale, Color p_color) -{ - - double angle; - core::Vec3d axisOfRot; - core::Vec3d defaultDir(0, 0, 1); - core::Vec3d planePoints[4] = {core::Vec3d(-p_scale, p_scale, 0), - core::Vec3d(-p_scale, -p_scale, 0), - core::Vec3d(p_scale, -p_scale, 0), - core::Vec3d(p_scale, p_scale, 0) - }; - core::Vec3d tmp; - - core::Vec3d normal = p_plane.getUnitNormal(); - core::Vec3d point = p_plane.getPoint(); - angle = std::acos(defaultDir.dot(normal)); - axisOfRot = normal.cross(defaultDir); - axisOfRot.normalize(); - - core::Quaterniond rot = getRotationQuaternion(-angle,axisOfRot); - - glDisable(GL_LIGHTING); - glBegin(GL_QUADS); - glColor3fv(p_color.toGLColor<GLfloat>()); - tmp = rot*planePoints[0] + point; - glVertex3dv(tmp.data()); - tmp = rot*planePoints[1] + point; - glVertex3dv(tmp.data()); - tmp = rot*planePoints[2] + point; - glVertex3dv(tmp.data()); - tmp = rot*planePoints[3] + point; - glVertex3dv(tmp.data()); - glEnd(); - glEnable(GL_LIGHTING); -} - -void OpenGLRenderer::renderScene(std::shared_ptr<Scene> p_scene) -{ - assert(p_scene); - - Matrix44f proj = p_scene->getCamera()->getProjMat(); - Matrix44f view = p_scene->getCamera()->getViewMat(); - - renderScene(p_scene, proj, view); -} - -void OpenGLRenderer::renderScene(std::shared_ptr<Scene> p_scene, - const Matrix44f &p_proj, - const Matrix44f &p_view) -{ - SceneLocal sceneLocal; - - assert(p_scene); - - //Load View and Projection Matrices - // -- with new rendering techniques, these would be passed to a shader - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glLoadMatrixf(p_proj.data()); - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glLoadMatrixf(p_view.data()); - - p_scene->copySceneToLocal(sceneLocal); - - //Enable lights - p_scene->activateLights(); - p_scene->placeLights(); - - for (auto x: sceneLocal.sceneObjects) - { - renderSceneObject(x); - } - - p_scene->deactivateLights(); - - glMatrixMode(GL_MODELVIEW); - glPopMatrix(); - glMatrixMode(GL_PROJECTION); - glPopMatrix(); -} - -void OpenGLRenderer::renderSceneObject(std::shared_ptr<SceneObject> p_sceneObject) -{ - RenderDetail::Ptr detail = p_sceneObject->getRenderDetail(); - if (!detail || detail->getRenderType() & SIMMEDTK_RENDER_NONE) - { - return; - } - - //if the custom rendering enable only render this - RenderDelegate::Ptr delegate = p_sceneObject->getRenderDelegate(); - std::shared_ptr<CustomRenderer> renderer = p_sceneObject->getRenderer(); - if (detail->getRenderType() & SIMMEDTK_RENDER_CUSTOMRENDERONLY) - { - if (renderer != nullptr) - { - renderer->preDrawObject(*p_sceneObject); - renderer->drawObject(*p_sceneObject); - renderer->postDrawObject(*p_sceneObject); - } - } - else if (delegate) - { - //If there is custom renderer first render the preDraw function. which is responsible for - //rendering before the default renderer takes place - if (renderer != nullptr) - { - renderer->preDrawObject(*p_sceneObject); - } - - delegate->draw(); - - //If there is custom renderer, render the postDraw function. which is responsible for - //rendering after the default renderer takes place - if (renderer != nullptr) - { - renderer->postDrawObject(*p_sceneObject); - } - } -} diff --git a/Rendering/OpenGLRenderer.h b/Rendering/OpenGLRenderer.h deleted file mode 100644 index 6df572451d5b2ce2786f587c7d80cc924c67d26e..0000000000000000000000000000000000000000 --- a/Rendering/OpenGLRenderer.h +++ /dev/null @@ -1,114 +0,0 @@ -// This file is part of the SimMedTK project. -// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, -// Rensselaer Polytechnic Institute -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//--------------------------------------------------------------------------- -// -// Authors: -// -// Contact: -//--------------------------------------------------------------------------- - -#ifndef SMGLRENDERER_H -#define SMGLRENDERER_H - -// STL includes -#include <memory> - -// SimMedTK includes -#include "Core/Config.h" -#include "Core/CoreClass.h" -#include "Core/SceneObject.h" -#include "Core/Matrix.h" - -class SurfaceMesh; -class AABB; -class LineMesh; -class OpenGLViewer; -class Plane; -class Scene; - -struct RenderDetail; -/// \brief gl rendering utilities -class OpenGLRenderer: public CoreClass -{ -public: - /// \brief constructor - OpenGLRenderer(); - - /// \brief draws surface mesh with given rendertdail and draw paramters - static void drawSurfaceMeshTriangles(std::shared_ptr<SurfaceMesh> p_surfaceMesh, std::shared_ptr<RenderDetail> renderDetail); - - /// \brief draw normals - static void drawNormals(std::shared_ptr<SurfaceMesh> p_mesh, Color p_color = Color::colorBlue, float length=1.0); - - /// \brief draw coordinate system - static void drawCoordSystem(std::shared_ptr<OpenGLViewer> viewer, std::string p_name, core::Vec3d p_pos, core::Vec3d dirX, core::Vec3d dirY, core::Vec3d dirZ); - - /// \brief begin rendering triangle - static void beginTriangles(); - - /// \brief draw triangle - static void drawTriangle(core::Vec3d &p_1, core::Vec3d &p_2, core::Vec3d &p_3); - - /// \brief end triangle rendering - static void endTriangles(); - - /// \brief draw AABB - static void draw(const Eigen::AlignedBox3d &aabb, Color p_color = Color(1.0, 1.0, 1.0)); - - /// \brief draw plane - static void draw(Plane &p_plane, float p_scale = 10.0, Color p_color = Color::colorYellow); - - /// \brief draw axes given rotation matrix, position and length to draw - static void drawAxes(const Matrix33f &rotMat, const core::Vec3f &pos, const float length); - - /// \brief draw global axes length to draw - static void drawAxes(const float length); - - /// \brief draw arrow given starting position, ending poistion and width of the arrow head - static void drawArrow(const core::Vec3f &start, const core::Vec3f &end, const float D); - - /// \brief draw function is called for visualization the object - virtual void draw() const {} - - /// \brief switch to default rendering - static void enableDefaultGLRendering(); - - /// \brief Renders an Scene's objects - /// - /// \detail Requires the caller to have called registerForScene() on p_scene - /// \param p_scene The scene to render - /// \param p_param The drawing parameters - static void renderScene(std::shared_ptr<Scene> p_scene); - /// \brief Renders a Scene's objects - /// - /// \detail Requires the caller to have called registerForScene() on p_scene - /// \param p_scene The scene to render - /// \param p_param The drawing parameters - /// \param p_proj A custom projection matrix to use instead of that provided with the scene - /// \param p_view A custom view matrix to use instead of that provided with the scene - static void renderScene(std::shared_ptr<Scene> p_scene, - const Matrix44f &p_proj, - const Matrix44f &p_view); - - /// \brief Renders a single SceneObject - /// - /// \param p_sceneObject The scene object to render - /// \param p_param The drawing parameters - static void renderSceneObject(std::shared_ptr<SceneObject> p_sceneObject); -}; - -#endif diff --git a/Rendering/OpenGLViewer.cpp b/Rendering/OpenGLViewer.cpp deleted file mode 100644 index dfccd721687d140728b8d75f1ab7263ebe1cf650..0000000000000000000000000000000000000000 --- a/Rendering/OpenGLViewer.cpp +++ /dev/null @@ -1,434 +0,0 @@ -// This file is part of the SimMedTK project. -// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, -// Rensselaer Polytechnic Institute -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//--------------------------------------------------------------------------- -// -// Authors: -// -// Contact: -//--------------------------------------------------------------------------- - -#include "Rendering/OpenGLViewer.h" - -#include "Core/EventHandler.h" -#include "Core/IOStream.h" -#include "Core/Factory.h" -#include "Core/ViewerBase.h" -#include "Event/KeyboardEvent.h" -#include "Event/KeySFMLInterface.h" -#include "Event/MouseButtonEvent.h" -#include "Event/MouseMoveEvent.h" -#include "Rendering/OpenGLRenderer.h" -#include "Rendering/Shader.h" -#include "Rendering/VAO.h" -#include "Rendering/VBO.h" -#include "Rendering/TextureManager.h" -#include "Rendering/FrameBuffer.h" - -// VTK glew library -#include <vtk_glew.h> - -#ifndef __APPLE__ -# include <GL/gl.h> // for GLfloat, etc. -#else -# include <OpenGL/gl.h> // for GLfloat, etc. -#endif - -#ifdef __linux__ -# include <X11/Xlib.h> -# include <X11/Xutil.h> -// # include <GL/glxew.h> -// # include <GL/glxext.h> -# include <GL/glx.h> -#endif - -#ifdef _WIN32 -typedef bool (APIENTRY *PFNWGLSWAPINTERVALFARPROC)(int); -#endif - -void OpenGLViewer::setVSync(bool sync) -{ - this->sfmlWindow->setVerticalSyncEnabled(sync); -} - -OpenGLViewer::OpenGLViewer() -{ - this->windowOutput = std::make_shared<OpenGLWindowStream>(); -} - -OpenGLViewer::~OpenGLViewer() {} -void OpenGLViewer::exitViewer() -{ -} - -/// \brief Initializes OpenGL capabilities and flags -void OpenGLViewer::initRenderingCapabilities() -{ - //use multiple fragment samples in computing the final color of a pixel - glEnable(GL_MULTISAMPLE); - //do depth comparisons and update the depth buffer - glEnable(GL_DEPTH_TEST); - //cull polygons based on their winding in window coordinates - glEnable(GL_CULL_FACE); - //DEPRECIATED AS OF v3.3 have one or more material parameters - // track the current color - glDisable(GL_COLOR_MATERIAL); - //DEPRECIATED AS OF v3.3 If enabled and no vertex shader is active, - // use the current lighting parameters to compute the vertex color or index - glEnable(GL_LIGHTING); - //DEPRECIATED AS OF v3.3 If enabled and no vertex shader is active, - // normal vectors are normalized to unit length after transformation and - // before lighting - glEnable(GL_NORMALIZE); - - //Fill the face of the polygon for all front and back facing polygons - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - - glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); - glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); - glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); - glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST); - glFrontFace(GL_CCW); - //DEPRECIATED AS OF v3.3 Smooth shading - glShadeModel(GL_SMOOTH); - //DEPRECIATED AS OF v3.3 Specifies the specular component of a material - glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, 50); -} - -/// \brief Initializes FBOs, textures, shaders and VAOs -void OpenGLViewer::initResources() -{ - TextureManager::initGLTextures(); - Shader::initGLShaders(); - VAO::initVAOs(); - - initFboListItems(); -} - -/// \brief Initializes the OpenGL context, and window containing it -void OpenGLViewer::initRenderingContext() -{ - - // Init OpenGL context - sfmlContext = std::unique_ptr<sf::Context>(new sf::Context); - sfmlWindow = std::unique_ptr<sf::Window>(new sf::Window); - // Init the rest of window system - if (viewerRenderDetail & SIMMEDTK_VIEWERRENDER_FULLSCREEN) - { - this->sfmlWindow->create(sf::VideoMode(this->width(), this->height()), - windowTitle, sf::Style::Fullscreen); - } - else - { - this->sfmlWindow->create(sf::VideoMode(this->width(), this->height()), - windowTitle, sf::Style::Default); - } - - // Init GLEW - GLenum err = glewInit(); - - if (GLEW_OK != err) - { - /* Problem: glewInit failed, something is seriously wrong. - * Most likely an OpenGL context is not created yet */ - std::cout << "Error:" << glewGetErrorString(err) << "\n"; - assert(false); - } -} - -/// \brief Cleans up after initGLContext() -void OpenGLViewer::destroyRenderingContext() -{ - //nothing to do -} - -/// \brief render depth texture for debugging -void OpenGLViewer::renderTextureOnView() -{ - - glPushAttrib(GL_TEXTURE_BIT | GL_VIEWPORT_BIT | GL_LIGHTING_BIT); - glUseProgramObjectARB(0); - glDisable(GL_LIGHTING); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(-1, 1, -1, 1, 1, 20); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glColor4f(1, 1, 1, 1); - glActiveTextureARB(GL_TEXTURE0); - TextureManager::activateTexture("depth"); - glEnable(GL_TEXTURE_2D); - glTranslated(0, 0, -1); - glBegin(GL_QUADS); - glTexCoord2d(0, 0); - glVertex3d(0, 0, 0); - glTexCoord2d(1, 0); - glVertex3d(1, 0, 0); - glTexCoord2d(1, 1); - glVertex3d(1, 1.0, 0); - glTexCoord2d(0, 1); - glVertex3d(0, 1.0, 0); - glEnd(); - glDisable(GL_TEXTURE_2D); - glPopAttrib(); -} - -/// \brief Initializes the FBOs in the FBO list -void OpenGLViewer::initFboListItems() -{ - for (size_t i = 0; i < this->fboListItems.size(); i++) - { - FboListItem *item = &fboListItems[i]; - item->fbo = new FrameBuffer(); - item->fbo->setDim(item->width, item->height); - if (item->colorTex) - { - item->fbo->attachColorTexture(item->colorTex, 0); - } - if (item->depthTex) - { - item->fbo->attachDepthTexture(item->depthTex); - } - for (size_t j = 0; j < renderOperations.size(); j++) - { - if (renderOperations[j].fboName == item->fboName) - { - renderOperations[j].fbo = item->fbo; - } - } - item->fbo->disable(); - } -} - -/// \brief Destroys all the FBOs in the FBO list -void OpenGLViewer::destroyFboListItems() -{ - for (size_t i = 0; i < this->fboListItems.size(); i++) - { - if (fboListItems[i].fbo) - { - delete (fboListItems[i].fbo); - fboListItems[i].fbo = nullptr; - } - } -} - -/// \brief Processes viewerRenderDetail options -void OpenGLViewer::processViewerOptions() -{ - if (viewerRenderDetail & SIMMEDTK_VIEWERRENDER_FADEBACKGROUND) - { - GLUtils::fadeBackgroundDraw(); - } -} - -///\brief Render and then process window events until the event queue is empty. -void OpenGLViewer::processWindowEvents() -{ - sf::Event event; - this->render(); - while (this->sfmlWindow->pollEvent(event)) - this->processSFMLEvents(event); -} - -/// \brief Renders the render operation to an FBO -void OpenGLViewer::renderToFBO(const RenderOperation &p_rop) -{ - assert(p_rop.fbo); - //Enable FBO for rendering - p_rop.fbo->enable(); - //Setup Viewport & Clear buffers - glViewport(0, 0, p_rop.fbo->getWidth(), p_rop.fbo->getHeight()); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); - - processViewerOptions(); - //Render Scene - OpenGLRenderer::renderScene(p_rop.scene); - //Disable FBO - p_rop.fbo->disable(); -} - -/// \brief Renders the render operation to screen -void OpenGLViewer::renderToScreen(const RenderOperation &p_rop) -{ - //Setup Viewport & Clear buffers - glViewport(0, 0, this->width(), this->height()); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); - - processViewerOptions(); - //Render Scene - OpenGLRenderer::renderScene(p_rop.scene); - - //Render axis - if (viewerRenderDetail & SIMMEDTK_VIEWERRENDER_GLOBAL_AXIS) - { - Matrix44f proj = p_rop.scene->getCamera()->getProjMat(); - Matrix44f view = p_rop.scene->getCamera()->getViewMat(); - - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glLoadMatrixf(proj.data()); - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glLoadMatrixf(view.data()); - - //Enable lights - p_rop.scene->activateLights(); - p_rop.scene->placeLights(); - - OpenGLRenderer::drawAxes(this->globalAxisLength); - - p_rop.scene->deactivateLights(); - - glMatrixMode(GL_MODELVIEW); - glPopMatrix(); - glMatrixMode(GL_PROJECTION); - glPopMatrix(); - - } -} - -/// \brief Set the color and other viewer defaults -void OpenGLViewer::setToDefaults() -{ - glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, defaultDiffuseColor.toGLColor<GLfloat>()); - glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, defaultSpecularColor.toGLColor<GLfloat>()); - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, defaultAmbientColor.toGLColor<GLfloat>()); - glColor4fv(defaultDiffuseColor.toGLColor<GLfloat>()); -} - -/// \brief Called at the beginning of each frame by the module -void OpenGLViewer::beginFrame() -{ - if (terminateExecution == true) - { - terminationCompleted = true; - } - - this->sfmlWindow->setActive(true); //activates opengl context -} - -///\brief Called at the end of each frame by the module -void OpenGLViewer::endFrame() -{ - this->sfmlWindow->display(); //swaps buffers -} - -void OpenGLViewer::processSFMLEvents(const sf::Event& p_event) -{ - switch(p_event.type) - { - case sf::Event::Closed: - //TODO: some type of terminate event - break; - case sf::Event::KeyPressed: - case sf::Event::KeyReleased: - { - auto keyboardEvent = - std::make_shared<event::KeyboardEvent>(event::SFMLKeyToSmKey(p_event.key.code)); - keyboardEvent->setPressed(sf::Event::KeyPressed == p_event.type); - - keyboardEvent->setModifierKey(event::ModKey::none); - if (p_event.key.shift) - keyboardEvent->setModifierKey(keyboardEvent->getModifierKey() | event::ModKey::shift); - if (p_event.key.control) - keyboardEvent->setModifierKey(keyboardEvent->getModifierKey() | event::ModKey::control); - if (p_event.key.alt) - keyboardEvent->setModifierKey(keyboardEvent->getModifierKey() | event::ModKey::alt); - if (p_event.key.system) - keyboardEvent->setModifierKey(keyboardEvent->getModifierKey() | event::ModKey::super); - - eventHandler->triggerEvent(keyboardEvent); - break; - } - case sf::Event::MouseButtonPressed: - case sf::Event::MouseButtonReleased: - { - event::MouseButton mouseButton; - if (sf::Mouse::Left == p_event.mouseButton.button) - mouseButton = event::MouseButton::Left; - else if (sf::Mouse::Right == p_event.mouseButton.button) - mouseButton = event::MouseButton::Right; - else if (sf::Mouse::Middle == p_event.mouseButton.button) - mouseButton = event::MouseButton::Middle; - else - mouseButton = event::MouseButton::Unknown; - - auto mouseEvent = std::make_shared<event::MouseButtonEvent>(mouseButton); - mouseEvent->setPresed(sf::Event::MouseButtonPressed == p_event.type); - mouseEvent->setWindowCoord(core::Vec2d(p_event.mouseButton.x,p_event.mouseButton.y)); - eventHandler->triggerEvent(mouseEvent); - break; - } - case sf::Event::MouseMoved: - { - auto mouseEvent = std::make_shared<event::MouseMoveEvent>(); - mouseEvent->setSender(core::EventSender::Module); - mouseEvent->setWindowCoord(core::Vec2d(p_event.mouseMove.x, p_event.mouseMove.y)); - eventHandler->triggerEvent(mouseEvent); - break; - } - default: - break; - } -} - -void OpenGLViewer::addObject(std::shared_ptr<CoreClass> object) -{ - - SDK::getInstance()->addRef(object); - objectList.push_back(object); -} - -void OpenGLViewer::handleEvent(std::shared_ptr<core::Event> /*p_event*/ ) -{ - -} - -void OpenGLViewer::addText(std::string p_tag) -{ - - windowOutput->addText(p_tag, std::string("")); -} - -void OpenGLViewer::updateText(std::string p_tag, std::string p_string) -{ - - windowOutput->updateText(p_tag, p_string); -} -void OpenGLViewer::updateText(int p_handle, std::string p_string) -{ - - windowOutput->updateText(p_handle, p_string); -} - -void OpenGLViewer::setWindowTitle(const std::string &str) -{ - windowTitle = str; -} - -void OpenGLViewer::cleanUp() -{ - destroyFboListItems(); - destroyRenderingContext(); - - //Must be set when all cleanup is done - terminationCompleted = true; -} - -RegisterFactoryClass(ViewerBase, - OpenGLViewer, - RenderDelegate::RendererType::Other) diff --git a/Rendering/OpenGLViewer.h b/Rendering/OpenGLViewer.h deleted file mode 100644 index 04a37ddbc22d52f3d5ab0b29589a524029ee54cf..0000000000000000000000000000000000000000 --- a/Rendering/OpenGLViewer.h +++ /dev/null @@ -1,98 +0,0 @@ -// This file is part of the SimMedTK project. -// Copyright (c) Center for Modeling, Simulation, and Imaging in Medicine, -// Rensselaer Polytechnic Institute -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//--------------------------------------------------------------------------- -// -// Authors: -// -// Contact: -//--------------------------------------------------------------------------- - -#ifndef SMVIEWER_H -#define SMVIEWER_H - -// 3rd Party iIncludes -#include <SFML/Window.hpp> - -// SimMedTK includes -#include "Core/ViewerBase.h" - -//forward declaration -class OpenGLWindowStream; -class SceneTextureShader; - -/// \brief Handles all rendering routines. -class OpenGLViewer : public ViewerBase -{ -public: - /// \brief default constructor - OpenGLViewer(); - ~OpenGLViewer(); - - /// \brief for exit viewer - virtual void exitViewer() override; - /// \brief add object for rendering - void addObject(std::shared_ptr<CoreClass> object) override; - /// \brief add text for display - virtual void addText(std::string p_tag) override; - /// \brief update text - virtual void updateText(std::string p_tag, std::string p_string) override; - virtual void updateText(int p_handle, std::string p_string) override; - /// \brief set scene as texture - void setSceneAsTextureShader(std::shared_ptr<SceneTextureShader> p_shader); - /// \brief set the window title - void setWindowTitle(const std::string &str) override; - /// \brief enable/disable VSync - virtual void setVSync(bool sync) override; - -protected: - virtual void initRenderingCapabilities() override; - virtual void initResources() override; - virtual void initRenderingContext() override; - virtual void destroyRenderingContext() override; - /// \brief Cleanup function called on exit to ensure resources are cleaned up - virtual void cleanUp() override; - /// \brief Renders the internal sceneList - void renderSceneList(); - - virtual void processViewerOptions() override; - virtual void processWindowEvents() override; - virtual void renderToScreen(const RenderOperation &p_rop) override; - virtual void renderToFBO(const RenderOperation &p_rop) override; - virtual void setToDefaults() override; - virtual void beginFrame() override; - virtual void endFrame() override; - virtual void renderTextureOnView() override; - /// \brief event handler - virtual void handleEvent(std::shared_ptr<core::Event> p_event) override; - /// \brief processes an SFML event - virtual void initFboListItems(); - virtual void destroyFboListItems(); - void processSFMLEvents(const sf::Event& p_event); - -protected: - std::unique_ptr<sf::Window> sfmlWindow; - -private: - std::unique_ptr<sf::Context> sfmlContext; - std::shared_ptr<OpenGLWindowStream> windowOutput; - std::string windowTitle; - Color defaultDiffuseColor; - Color defaultAmbientColor; - Color defaultSpecularColor; -}; - -#endif diff --git a/Rendering/Shader.h b/Rendering/Shader.h index 778ee72270d2f47572ffb97712a3fc5115a8fbfe..46288e8f9ae673b5b4f7f13a666c80f9e2a3136d 100644 --- a/Rendering/Shader.h +++ b/Rendering/Shader.h @@ -38,6 +38,7 @@ #include "Rendering/GLUtils.h" #include "Core/Timer.h" #include "Core/BaseMesh.h" +#include "Mesh/SurfaceMesh.h" namespace Core { class BaseMesh; diff --git a/Rendering/VAO.cpp b/Rendering/VAO.cpp index 727d4317cdc9587cf0c95e5d646f5ab95263e09b..0232ce133c88bf34a680e544dd4bfc6b02f35e3b 100644 --- a/Rendering/VAO.cpp +++ b/Rendering/VAO.cpp @@ -23,7 +23,7 @@ #include "Rendering/VAO.h" #include "Rendering/Shader.h" -#include "Rendering/OpenGLViewer.h" +#include "Mesh/SurfaceMesh.h" std::unordered_map<int, std::shared_ptr<VAO>> VAO::VAOs; @@ -233,7 +233,7 @@ bool VAO::setBufferDataFromMesh( SurfaceMesh *p_mesh, std::shared_ptr<Shader> p_ { if ( p_shader == nullptr ) { - shader = Shader::getShader( p_mesh->getRenderDetail()->shaders[0] ); + shader = Shader::getShader( p_mesh->getRenderDetail()->getShaders()[0] ); } else { diff --git a/VTKRendering/MeshNodalCoordinates.h b/VTKRendering/MeshNodalCoordinates.h index 7d02c29e7959bd79a1194d865bd58f201bcfa7b0..d49acc7c9050844409f07467222702c716bb9a15 100644 --- a/VTKRendering/MeshNodalCoordinates.h +++ b/VTKRendering/MeshNodalCoordinates.h @@ -103,6 +103,7 @@ public: void SetValue(vtkIdType idx, Scalar value); vtkIdType InsertNextValue(Scalar v); void InsertValue(vtkIdType idx, Scalar v); + void InsertVariantValue(vtkIdType idx, vtkVariant value); protected: MeshNodalCoordinates(); diff --git a/VTKRendering/MeshNodalCoordinates.txx b/VTKRendering/MeshNodalCoordinates.txx index 2edd786496f4cf276c2d379ce1ef0311ae9c428b..43fc3f048fdd47142d2e64944d178abffc0563cb 100644 --- a/VTKRendering/MeshNodalCoordinates.txx +++ b/VTKRendering/MeshNodalCoordinates.txx @@ -462,6 +462,14 @@ template <class Scalar> void MeshNodalCoordinates<Scalar> return; } +//------------------------------------------------------------------------------ +template <class Scalar> void MeshNodalCoordinates<Scalar> +::InsertVariantValue(vtkIdType, vtkVariant) +{ + vtkErrorMacro("Read only container.") + return; +} + //------------------------------------------------------------------------------ template <class Scalar> MeshNodalCoordinates<Scalar> ::MeshNodalCoordinates() diff --git a/VTKRendering/VTKMeshRenderDelegate.cpp b/VTKRendering/VTKMeshRenderDelegate.cpp index 4c1911f111c890ea032a0c60a9f5c12b0d7fb70b..128ef7e5d5c13e78d5397748e621ea6edd103b29 100644 --- a/VTKRendering/VTKMeshRenderDelegate.cpp +++ b/VTKRendering/VTKMeshRenderDelegate.cpp @@ -28,6 +28,7 @@ #include "Core/RenderDelegate.h" #include "Mesh/SurfaceMesh.h" #include "Mesh/VegaVolumetricMesh.h" +#include "IO/IOMesh.h" #include "VTKRendering/MeshNodalCoordinates.h" #include "VTKRendering/VTKRenderDelegate.h" @@ -44,11 +45,24 @@ #include <vtkCellArray.h> #include <vtkGeometryFilter.h> #include <vtkPolyDataNormals.h> -#include <vtkPNGReader.h> -#include <vtkJPEGReader.h> + #include <vtkFloatArray.h> #include <vtkTexture.h> +#include <vtkOpenGLPolyDataMapper.h> #include <vtkProperty.h> +#include "vtkShaderProgram.h" +#include "vtkOpenGLVertexArrayObject.h" +#include "vtkOpenGLVertexBufferObject.h" +#include <vtkXMLImageDataReader.h> +#include <vtkImageReader.h> +#include <vtkImageReader2Factory.h> +#include "RenderDetail.h" +#include "vtkTextureObject.h" +#include "vtkOpenGLTexture.h" +#include "vtkOpenGLRenderWindow.h" +#include "vtkIndent.h" + +vtkStandardNewMacro(CustomGLPolyDataMapper) class MeshRenderDelegate : public VTKRenderDelegate @@ -69,6 +83,19 @@ private: vtkSmartPointer<vtkDataSet> dataSet; }; + +class vtkOpenGLTexture_Impl :public vtkOpenGLTexture +{ +public: + static vtkOpenGLTexture_Impl* New(); + void Load(vtkRenderer*p_renderer) + { + vtkOpenGLTexture::Load(p_renderer); + this->GetTextureObject()->SetLinearMagnification(true); + this->GetTextureObject()->SetMinificationFilter(true); + } +}; +vtkStandardNewMacro(vtkOpenGLTexture_Impl) void MeshRenderDelegate::initDraw() { @@ -94,6 +121,7 @@ void MeshRenderDelegate::initDraw() auto mesh = std::static_pointer_cast<SurfaceMesh>(geom->shared_from_this()); mappedData->SetVertexArray(mesh->getVertices()); + vtkNew<vtkCellArray> triangles; auto surfaceTriangles = mesh->getTriangles(); for(const auto &t : surfaceTriangles) @@ -112,13 +140,14 @@ void MeshRenderDelegate::initDraw() vtkNew<vtkUnstructuredGrid> unstructuredMesh; unstructuredMesh->SetPoints(vertices.GetPointer()); unstructuredMesh->SetCells(VTK_TRIANGLE,triangles.GetPointer()); + //unstructuredMesh->SetCells(VTK_POLYGON, triangles.GetPointer()); auto renderDetail = mesh->getRenderDetail(); if(renderDetail) { - auto ambientColor = renderDetail->getColorAmbient().getValue(); - auto diffuseColor = renderDetail->getColorDiffuse().getValue(); - auto specularColor = renderDetail->getColorSpecular().getValue(); + auto ambientColor = renderDetail->getAmbientColor().getValue(); + auto diffuseColor = renderDetail->getDiffuseColor().getValue(); + auto specularColor = renderDetail->getSpecularColor().getValue(); auto specularPower = renderDetail->getShininess(); auto opacity = renderDetail->getOpacity(); actor->GetProperty()->SetAmbient(ambientColor[3]); @@ -131,74 +160,130 @@ void MeshRenderDelegate::initDraw() actor->GetProperty()->SetOpacity(opacity); } + // Render Wireframe if(renderDetail && renderDetail->renderWireframe()) { actor->GetProperty()->SetRepresentationToWireframe(); } + // Render Faces if (renderDetail && renderDetail->renderFaces()) { actor->GetProperty()->SetRepresentationToSurface(); actor->GetProperty()->SetInterpolationToPhong(); } - vtkSmartPointer<vtkTexture> texture; - if(renderDetail && renderDetail->renderTexture()) + // Render Textures + int nbrTextures = renderDetail->getNumberOfTextures(); + if ((renderDetail && renderDetail->renderTexture()) || nbrTextures>0) { - texture = vtkTexture::New(); - texture->RepeatOff(); - - std::string filename = mesh->getRenderDetail()->getTextureFilename(); - std::string ext = filename.substr(filename.find_last_of(".") + 1); - if (ext == "png" || ext == "PNG") + vtkOpenGLTexture_Impl* textureImpl; + vtkOpenGLTexture *texture; + vtkSmartPointer<vtkImageReader2Factory> readerFactory = + vtkSmartPointer<vtkImageReader2Factory>::New(); + std::map<std::string, TextureDetail>& textures = renderDetail->getTextures(); + + // Go through all TextureDetails + for (auto &t : textures) { - vtkNew<vtkPNGReader> PNGreader; - PNGreader->SetFileName(filename.c_str()); - texture->SetInputConnection(PNGreader->GetOutputPort()); + TextureDetail &textureDetail = t.second; + + // Case Texture already loaded + if (TextureDetail::textures.find(textureDetail.fileName) != TextureDetail::textures.end()) + { + textureDetail.vtexture = TextureDetail::textures[textureDetail.fileName]; + texture = textureDetail.vtexture; + + cout << "Image file " << textureDetail.fileName << " is already loaded." << endl; + continue; + } + + // Read Image + vtkSmartPointer<vtkImageReader2> imageReader = + readerFactory->CreateImageReader2(textureDetail.fileName.c_str()); + if (imageReader == NULL) + { + cout << "Error in opening the file" << endl; + continue; + } + imageReader->SetFileName(textureDetail.fileName.c_str()); + imageReader->Update(); + + // Create Texture + textureImpl = vtkOpenGLTexture_Impl::New(); + textureImpl->SetInputConnection(imageReader->GetOutputPort()); + + // Update TextureDetail + textureDetail.vtexture = textureImpl; + texture = textureImpl; + TextureDetail::textures.emplace(textureDetail.fileName, texture); + + cout << "Image file "<<textureDetail.fileName << " loaded." << endl; } - else if (ext == "jpg" || ext == "JPG" || ext == "jpeg" || ext == "JPEG") + + if(texture) { - vtkNew<vtkJPEGReader> JPEGreader; - JPEGreader->SetFileName(filename.c_str()); - texture->SetInputConnection(JPEGreader->GetOutputPort()); - } + // With VTK, required to assign one of the textures + // to the actor in order to display all the textures + actor->SetTexture(texture); - vtkNew<vtkFloatArray> textureCoordinates; - textureCoordinates->SetNumberOfComponents(3); - textureCoordinates->SetName("TextureCoordinates"); + // Set VTK Texture coordinates + vtkNew<vtkFloatArray> textureCoordinates; + textureCoordinates->SetNumberOfComponents(3); + textureCoordinates->SetName("TextureCoordinates"); - auto texCoords = mesh->getTextureCoordinates(); - for(auto &coord : texCoords) - { - float tuple[3] = {coord[0],coord[1],0.0}; - textureCoordinates->InsertNextTuple(tuple); + auto texCoords = mesh->getTextureCoordinates(); + for(auto &coord : texCoords) + { + float tuple[3] = {coord[0],coord[1],0.0}; + textureCoordinates->InsertNextTuple(tuple); + } + unstructuredMesh->GetPointData()->SetTCoords(textureCoordinates.GetPointer()); } - unstructuredMesh->GetPointData()->SetTCoords(textureCoordinates.GetPointer()); } + // Render Normals dataSet = unstructuredMesh.GetPointer(); if (renderDetail && renderDetail->renderNormals()) { vtkSmartPointer<vtkGeometryFilter> geometry = vtkGeometryFilter::New(); geometry->SetInputData(unstructuredMesh.GetPointer()); - + vtkSmartPointer<vtkPolyDataNormals> normals = vtkPolyDataNormals::New(); + normals->SetSplitting(false); normals->SetInputConnection(geometry->GetOutputPort()); normals->AutoOrientNormalsOn(); - mapper = vtkPolyDataMapper::New(); + mapper = CustomGLPolyDataMapper::New(); + + /// TODO : The tangent computation needs to go out of the this block..tansel mapper->SetInputConnection(normals->GetOutputPort()); + auto mapperCustom = CustomGLPolyDataMapper::SafeDownCast(mapper); + mapperCustom->renderDetail = renderDetail; + mesh->computeVertexNeighbors(); + if (mesh->getMeshType() == (int)IOMesh::MeshFileType::OBJ) + { + mesh->setUseOBJTexture(true); + } + else + { + mesh->setUseThreDSTexture(true); + } + mesh->computeTriangleTangents(); + mapperCustom->tangents = mesh->getVertexTangents(); + + if(renderDetail->hasShaders()) + { + auto glMapper = vtkOpenGLPolyDataMapper::SafeDownCast(mapper); + std::string shaderProgramName =renderDetail->getShaderProgram(); + this->setShadersProgram(glMapper, shaderProgramName); + } } else { mapper = vtkDataSetMapper::New(); mapper->SetInputDataObject(unstructuredMesh.GetPointer()); } - - if(texture.GetPointer()) - { - actor->SetTexture(texture); - } actor->SetMapper(mapper.GetPointer()); } @@ -219,7 +304,79 @@ vtkActor *MeshRenderDelegate::getActor() void MeshRenderDelegate::modified() { if (this->dataSet) + { dataSet->Modified(); + } +} + +void CustomGLPolyDataMapper::initDraw() +{ + cout << "init" << endl; +} + +void CustomGLPolyDataMapper::BuildBufferObjects(vtkRenderer *ren, vtkActor *act) +{ + tangentsBuffer = vtkOpenGLBufferObject::New(); + tangentsBuffer->Bind(); + if (tangentsBuffer->Upload(this->tangents, vtkOpenGLBufferObject::ArrayBuffer)) + { + cout << "Completed Tangents Binding"<<endl; + } + tangentsBuffer->Release(); + vtkOpenGLPolyDataMapper::BuildBufferObjects(ren,act); +} + +void CustomGLPolyDataMapper::SetMapperShaderParameters(vtkOpenGLHelper &cellBO, vtkRenderer *ren, vtkActor *act) +{ + float lightPower = 5.0; + float roughness = 160.0; + static double testColor3 = 0.01; + vtkShaderProgram *program = cellBO.Program; + + testColor3 += 0.01; + program->SetUniformf("lightPower", lightPower); + program->SetUniformf("roughness", roughness); + + std::map<std::string, TextureDetail>& textures = renderDetail->getTextures(); + + for (auto &t : textures) + { + TextureDetail &textureDetail = t.second; + textureDetail.vtexture->GetTextureObject(); + textureDetail.vtexture->Load(ren); + + program->SetUniformi(textureDetail.shaderBinding.c_str(), textureDetail.vtexture->GetTextureUnit()); + } + cellBO.VAO->Bind(); + + if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->tangentsBuffer, + "vertTangents", 0, + 0, VTK_DOUBLE, 3, false)) + { + vtkErrorMacro(<< "Error setting 'vertTangents' in shader VAO."); + } + vtkOpenGLPolyDataMapper::SetMapperShaderParameters(cellBO, ren, act); +} + +void VTKRenderDelegate::setShadersProgram(vtkOpenGLPolyDataMapper *mapper, + const std::string &shaderPrograms) +{ + std::map<std::string, ShaderDetail>& shaders = Shaders::getShaderPrograms(); + if (shaders.find(shaderPrograms) == shaders.end()) + { + return; + } + + ShaderDetail &shaderDetail = shaders[shaderPrograms]; + if (shaderDetail.initialized) + { + return; + } + + mapper->SetFragmentShaderCode(shaderDetail.fragmentShaderSource.c_str()); + mapper->SetVertexShaderCode(shaderDetail.vertexShaderSource.c_str()); + if (shaderDetail.geometryShaderExists) + mapper->SetGeometryShaderCode(shaderDetail.geometryShaderSource.c_str()); } RegisterFactoryClass(RenderDelegate, diff --git a/VTKRendering/VTKPlaneRenderDelegate.cpp b/VTKRendering/VTKPlaneRenderDelegate.cpp index c90b0ca2b426d69e9f10c7e0fc845b347b88a451..2fb2c36df8cec07ae8a24487c57b6507907446c4 100644 --- a/VTKRendering/VTKPlaneRenderDelegate.cpp +++ b/VTKRendering/VTKPlaneRenderDelegate.cpp @@ -58,9 +58,9 @@ void PlaneRenderDelegate::initDraw() auto renderDetail = plane->getRenderDetail(); if(renderDetail) { - auto ambientColor = renderDetail->getColorAmbient().getValue(); - auto diffuseColor = renderDetail->getColorDiffuse().getValue(); - auto specularColor = renderDetail->getColorSpecular().getValue(); + auto ambientColor = renderDetail->getAmbientColor().getValue(); + auto diffuseColor = renderDetail->getDiffuseColor().getValue(); + auto specularColor = renderDetail->getSpecularColor().getValue(); auto specularPower = renderDetail->getShininess(); auto opacity = renderDetail->getOpacity(); actor->GetProperty()->SetAmbient(ambientColor[3]); @@ -82,9 +82,9 @@ void PlaneRenderDelegate::initDraw() auto normal = plane->getUnitNormal(); core::Vec3d xp = normal.cross(core::Vec3d(0., 1., 0.)); if (xp.squaredNorm() < 1e-8) - xp = normal.cross(core::Vec3d(0., 0., 1.)).normalized(); + xp = normal.cross(core::Vec3d(0., 0., 1.)).normalized(); else - xp = xp.normalized(); + xp = xp.normalized(); core::Vec3d yp = normal.cross(xp).normalized(); double planeSize = plane->getWidth(); diff --git a/VTKRendering/VTKRenderDelegate.h b/VTKRendering/VTKRenderDelegate.h index ec359794a3f1c07e1da6dea01509fede5ee6a1c0..cf7ae543c565eb77691f3024a44cc3498c253837 100644 --- a/VTKRendering/VTKRenderDelegate.h +++ b/VTKRendering/VTKRenderDelegate.h @@ -1,9 +1,27 @@ #ifndef VTKRENDERABLE_H #define VTKRENDERABLE_H +#include <vtkOpenGLPolyDataMapper.h> #include "Core/RenderDelegate.h" +//#include "Core/RenderDetail.h" class vtkActor; +class Shaders; + +class CustomGLPolyDataMapper :public vtkOpenGLPolyDataMapper{ +public: + static CustomGLPolyDataMapper* New(); + std::shared_ptr<RenderDetail> renderDetail; + vtkOpenGLBufferObject * tangentsBuffer; + //vtkOpenGLVertexBufferObject* tangentsBuffer; + std::vector<core::Vec3d>tangents; + vtkTypeMacro(CustomGLPolyDataMapper, vtkOpenGLPolyDataMapper) + virtual void initDraw(); + virtual void modified() {} + virtual void draw() const { } + virtual void SetMapperShaderParameters(vtkOpenGLHelper &cellBO, vtkRenderer *ren, vtkActor *act) override; + void BuildBufferObjects(vtkRenderer *ren, vtkActor *act); +}; class VTKRenderDelegate : public RenderDelegate { @@ -11,8 +29,35 @@ public: virtual vtkActor *getActor() = 0; virtual void initDraw() override{} virtual void modified() override{} - virtual void draw() const override - { } + virtual void draw() const override{ } + + + void setShadersProgram(vtkOpenGLPolyDataMapper *mapper,const std::string &shaderPrograms); + + template<typename ShaderProgramType> + void setShadersProgramReplacements(vtkOpenGLPolyDataMapper *mapper, + const ShaderProgramType &shaderPrograms); }; + + + +template<typename ShaderProgramType> +void VTKRenderDelegate::setShadersProgramReplacements(vtkOpenGLPolyDataMapper *mapper, + const ShaderProgramType &shaderPrograms) +{ + for(auto &shader : shaderPrograms) + { + for(auto &program : shader.second) + { + mapper->AddShaderReplacement(static_cast<vtkShader::Type>(shader.first), + program[0], + true, + program[1], + false); + + } + } +} + #endif // SMRENDERABLE_H diff --git a/VTKRendering/VTKStaticSceneObjectRenderDelegate.cpp b/VTKRendering/VTKStaticSceneObjectRenderDelegate.cpp index e3c28dee7da7f44f835a7feaa49985f072be57d2..e56c9bed68bad1cb18367df814e648b31ff8d5ef 100644 --- a/VTKRendering/VTKStaticSceneObjectRenderDelegate.cpp +++ b/VTKRendering/VTKStaticSceneObjectRenderDelegate.cpp @@ -62,8 +62,7 @@ vtkActor *StaticSceneObjectRenderDelegate::getActor() return delegate->getActor(); } - auto meshModel = std::dynamic_pointer_cast<MeshModel>( - geom->getModel()); + auto meshModel = std::dynamic_pointer_cast<MeshModel>(geom->getModel()); if(meshModel) {