├── .gitattributes ├── .gitignore ├── .gitmodules ├── README.md ├── VolumeStyleRendering.sln ├── VolumeStyleRendering ├── CubicSpline.cpp ├── CubicSpline.h ├── Light.h ├── Postprocess.cpp ├── Postprocess.h ├── RaycastVolume.cpp ├── RaycastVolume.h ├── RenderingParams.cpp ├── RenderingParams.h ├── StyleTransferFunction.cpp ├── StyleTransferFunction.h ├── StyleTransferFunctionUi.cpp ├── StyleTransferFunctionUi.h ├── TransferFunction.cpp ├── TransferFunction.h ├── TransferFunctionPoint.cpp ├── TransferFunctionPoint.h ├── VolumeRenderingApp.cpp ├── VolumeRenderingAppUi.cpp ├── VolumeRenderingAppUi.h ├── VolumeStyleRendering.vcxproj ├── VolumeStyleRendering.vcxproj.filters └── assets │ ├── fonts │ └── DroidSans.ttf │ ├── images │ ├── default.png │ └── noise.png │ └── shaders │ ├── average.frag │ ├── blur.frag │ ├── fs_quad.vert │ ├── fxaa.frag │ ├── gradients.comp │ ├── histogram.comp │ ├── inverse.frag │ ├── multiply.frag │ ├── positions.frag │ ├── positions.vert │ ├── raycast.vert │ ├── raycast_rendertargets.frag │ ├── smooth_gradients.comp │ ├── ssao.frag │ └── tonemapping.frag └── screenshots ├── 1.png └── 2.png /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "VolumeStyleRendering/external/Cinder-ImGui"] 2 | path = VolumeStyleRendering/external/Cinder-ImGui 3 | url = git@github.com:simongeilfus/Cinder-ImGui.git 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![alt tag](screenshots/1.png) 2 | 3 | ![alt tag](screenshots/2.png) -------------------------------------------------------------------------------- /VolumeStyleRendering.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26403.7 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "VolumeStyleRendering", "VolumeStyleRendering\VolumeStyleRendering.vcxproj", "{8AD996D0-9B41-4AF1-8368-92ABD6621F40}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x64 = Debug|x64 11 | Debug|x86 = Debug|x86 12 | Release|x64 = Release|x64 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {8AD996D0-9B41-4AF1-8368-92ABD6621F40}.Debug|x64.ActiveCfg = Debug|x64 17 | {8AD996D0-9B41-4AF1-8368-92ABD6621F40}.Debug|x64.Build.0 = Debug|x64 18 | {8AD996D0-9B41-4AF1-8368-92ABD6621F40}.Debug|x86.ActiveCfg = Debug|Win32 19 | {8AD996D0-9B41-4AF1-8368-92ABD6621F40}.Debug|x86.Build.0 = Debug|Win32 20 | {8AD996D0-9B41-4AF1-8368-92ABD6621F40}.Release|x64.ActiveCfg = Release|x64 21 | {8AD996D0-9B41-4AF1-8368-92ABD6621F40}.Release|x64.Build.0 = Release|x64 22 | {8AD996D0-9B41-4AF1-8368-92ABD6621F40}.Release|x86.ActiveCfg = Release|Win32 23 | {8AD996D0-9B41-4AF1-8368-92ABD6621F40}.Release|x86.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /VolumeStyleRendering/CubicSpline.cpp: -------------------------------------------------------------------------------- 1 | #include "CubicSpline.h" 2 | using namespace glm; 3 | 4 | CubicSpline::CubicSpline(vec3 a, vec3 b, vec3 c, vec3 d) 5 | { 6 | this->a = a; 7 | this->b = b; 8 | this->c = c; 9 | this->d = d; 10 | } 11 | 12 | vec3 CubicSpline::getPointOnSpline(float s) const 13 | { 14 | return (((d * s) + c) * s + b) * s + a; 15 | } 16 | 17 | std::vector CubicSpline::CalculateCubicSpline(std::vector points) 18 | { 19 | auto n = points.size() - 1; 20 | auto& v = points; 21 | std::vector gamma(n + 1); 22 | std::vector delta(n + 1); 23 | std::vector D(n + 1); 24 | 25 | int i; 26 | /* We need to solve the equation 27 | * taken from: http://mathworld.wolfram.com/CubicSpline.html 28 | [2 1 ] [D[0]] [3(v[1] - v[0]) ] 29 | |1 4 1 | |D[1]| |3(v[2] - v[0]) | 30 | | 1 4 1 | | . | = | . | 31 | | ..... | | . | | . | 32 | | 1 4 1| | . | |3(v[n] - v[n-2])| 33 | [ 1 2] [D[n]] [3(v[n] - v[n-1])] 34 | 35 | by converting the matrix to upper triangular. 36 | The D[i] are the derivatives at the control points. 37 | */ 38 | 39 | //this builds the coefficients of the left matrix 40 | gamma[0] = vec3(0); 41 | gamma[0].x = 1.0f / 2.0f; 42 | gamma[0].y = 1.0f / 2.0f; 43 | gamma[0].z = 1.0f / 2.0f; 44 | 45 | for (i = 1; i < n; i++) 46 | { 47 | gamma[i] = vec3(1) / ((4.0f * vec3(1)) - gamma[i - 1]); 48 | } 49 | 50 | gamma[n] = vec3(1) / ((2.0f * vec3(1)) - gamma[n - 1]); 51 | 52 | delta[0] = 3.0f * (v[1] - v[0]) * gamma[0]; 53 | 54 | for (i = 1; i < n; i++) 55 | { 56 | delta[i] = (3.0f * (v[i + 1] - v[i - 1]) - delta[i - 1]) * gamma[i]; 57 | } 58 | 59 | delta[n] = (3.0f * (v[n] - v[n - 1]) - delta[n - 1]) * gamma[n]; 60 | 61 | D[n] = delta[n]; 62 | 63 | for (i = n - 1; i >= 0; i--) 64 | { 65 | D[i] = delta[i] - gamma[i] * D[i + 1]; 66 | } 67 | 68 | // now compute the coefficients of the cubics 69 | std::vector C(n); 70 | 71 | for (i = 0; i < n; i++) 72 | { 73 | C[i] = CubicSpline(v[i], D[i], 3.0f * (v[i + 1] - v[i]) - 2.0f * D[i] - D[i + 1], 2.0f * (v[i] - v[i + 1]) + D[i] + D[i + 1]); 74 | } 75 | 76 | return C; 77 | } -------------------------------------------------------------------------------- /VolumeStyleRendering/CubicSpline.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | class CubicSpline 6 | { 7 | public: 8 | CubicSpline() = default; 9 | CubicSpline(glm::vec3 a, glm::vec3 b, glm::vec3 c, glm::vec3 d); 10 | //evaluate the point using a cubic equation 11 | glm::vec3 getPointOnSpline(float s) const; 12 | static std::vector CalculateCubicSpline(std::vector points); 13 | private: 14 | glm::vec3 a; 15 | glm::vec3 b; 16 | glm::vec3 c; 17 | glm::vec3 d; 18 | }; -------------------------------------------------------------------------------- /VolumeStyleRendering/Light.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class Light 5 | { 6 | public: 7 | glm::vec3 direction; 8 | glm::vec3 diffuse; 9 | glm::vec3 ambient; 10 | 11 | Light() : direction(0.0f, 0.0f, 1.0f), diffuse(1.0f, 1.0f, 1.0f), ambient(0.1f, 0.1f, 0.1f) {} 12 | }; 13 | -------------------------------------------------------------------------------- /VolumeStyleRendering/Postprocess.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "PostProcess.h" 6 | #include "RenderingParams.h" 7 | 8 | using namespace ci; 9 | using namespace glm; 10 | using namespace app; 11 | 12 | void PostProcess::displayTexture(const gl::Texture2dRef colorTex) const 13 | { 14 | const gl::ScopedTextureBind scopedTextureBind(colorTex ? colorTex : getColorTexture(), 0); 15 | const gl::ScopedViewport scopedViewport(ivec2(0), toPixels(getWindowSize())); 16 | const gl::ScopedMatrices scopedMatrices; 17 | const gl::ScopedDepth depth(false); 18 | gl::clear(); 19 | 20 | // translate to center and scale to fit whole screen 21 | gl::translate(getWindowCenter()); 22 | gl::scale(getWindowSize()); 23 | 24 | // draw quad with mapped texture 25 | textureRect->draw(); 26 | } 27 | 28 | void PostProcess::displayFXAA(const gl::Texture2dRef& texture) const 29 | { 30 | const gl::ScopedTextureBind scopedTextureBind(texture ? texture : getColorTexture(), 0); 31 | const gl::ScopedViewport scopedViewport(ivec2(0), toPixels(getWindowSize())); 32 | const gl::ScopedMatrices scopedMatrices; 33 | const gl::ScopedDepth depth(false); 34 | gl::clear(); 35 | 36 | // custom uniforms 37 | auto& prog = fxaaRect->getGlslProg(); 38 | prog->uniform("pixelSize", vec2(1.0f) / vec2(toPixels(getWindowSize()))); 39 | 40 | // translate to center and scale to fit whole screen 41 | gl::translate(getWindowCenter()); 42 | gl::scale(getWindowSize()); 43 | 44 | // draw quad with mapped texture 45 | fxaaRect->draw(); 46 | } 47 | 48 | void PostProcess::toneMapping(const gl::Texture2dRef& hdrBuffer, bool local) const 49 | { 50 | if (local) Start(); 51 | 52 | const gl::ScopedTextureBind scopedTextureBind(hdrBuffer ? hdrBuffer : getColorTexture(), 0); 53 | 54 | // custom uniforms 55 | auto& prog = toneMappingRect->getGlslProg(); 56 | prog->uniform("gamma", RenderingParams::GetGamma()); 57 | prog->uniform("exposure", RenderingParams::GetExposure()); 58 | 59 | // draw quad with mapped texture 60 | toneMappingRect->draw(); 61 | 62 | if (local) End(); 63 | } 64 | 65 | void PostProcess::blurHorizontal(int blurType, const gl::Texture2dRef& texture, bool local) const 66 | { 67 | if (local) Start(); 68 | 69 | const gl::ScopedTextureBind scopedTextureBind(texture ? texture : getColorTexture(), 0); 70 | 71 | // custom uniforms 72 | auto& prog = blurRect->getGlslProg(); 73 | prog->uniform("blurDirection", vec2(1.0f / static_cast(currentFbo->getSize().x), 0.0f)); 74 | prog->uniform("blurType", blurType); 75 | 76 | // first pass blur 77 | blurRect->draw(); 78 | 79 | if (local) End(); 80 | } 81 | 82 | void PostProcess::blurVertical(int blurType, const gl::Texture2dRef& texture, bool local) const 83 | { 84 | if (local) Start(); 85 | 86 | const gl::ScopedTextureBind scopedTextureBind(texture ? texture : getColorTexture(), 0); 87 | 88 | // custom uniforms 89 | auto& prog = blurRect->getGlslProg(); 90 | prog->uniform("blurDirection", vec2(0.0f, 1.0f / static_cast(currentFbo->getSize().y))); 91 | prog->uniform("blurType", blurType); 92 | 93 | // first pass blur 94 | blurRect->draw(); 95 | 96 | if (local) End(); 97 | } 98 | 99 | void PostProcess::inverse(const gl::Texture2dRef& texture, bool local) const 100 | { 101 | if (local) Start(); 102 | 103 | const gl::ScopedTextureBind scopedTextureBind(texture ? texture : getColorTexture(), 0); 104 | 105 | // draw quad with mapped texture 106 | inverseRect->draw(); 107 | 108 | if (local) End(); 109 | } 110 | 111 | void PostProcess::multiply(const gl::Texture2dRef& texture0, const gl::Texture2dRef& texture1, bool local) const 112 | { 113 | if (local) Start(); 114 | 115 | const gl::ScopedTextureBind scopedTextureBind0(texture0, 0); 116 | const gl::ScopedTextureBind scopedTextureBind1(texture1 ? texture1 : getColorTexture(), 1); 117 | 118 | // draw quad with mapped texture 119 | multiplyRect->draw(); 120 | 121 | if (local) End(); 122 | } 123 | 124 | void PostProcess::average(const gl::Texture2dRef& texture, bool local) const 125 | { 126 | if (local) Start(); 127 | 128 | auto& tex = texture ? texture : getColorTexture(); 129 | const gl::ScopedTextureBind scopedTextureBind0(tex, 0); 130 | 131 | // custom uniforms 132 | auto& prog = averageRect->getGlslProg(); 133 | prog->uniform("texelSize", 1.0f / static_cast(tex->getSize())); 134 | 135 | // draw quad with mapped texture 136 | averageRect->draw(); 137 | 138 | if (local) End(); 139 | } 140 | 141 | void PostProcess::SSAO(const gl::Texture2dRef& position, const gl::Texture2dRef& normal, const Camera& camera, bool local) 142 | { 143 | if (local) Start(); 144 | 145 | const gl::ScopedTextureBind scopedTextureBind0(normal, 0); 146 | const gl::ScopedTextureBind scopedTextureBind1(position, 1); 147 | const gl::ScopedTextureBind scopedTextureBind2(ssaoNoiseTexture, 2); 148 | 149 | // custom uniforms 150 | auto& prog = ssaoRect->getGlslProg(); 151 | prog->uniform("projectionMatrix", camera.getProjectionMatrix()); 152 | prog->uniform("radius", RenderingParams::SSAORadius()); 153 | prog->uniform("bias", RenderingParams::SSAOBias()); 154 | prog->uniform("power", RenderingParams::SSAOPower()); 155 | 156 | for (int i = 0; i < ssaoKernel.size(); i++) 157 | { 158 | prog->uniform("ssaoKernel[" + std::to_string(i) + "]", ssaoKernel[i]); 159 | } 160 | 161 | gl::setDefaultShaderVars(); 162 | 163 | // draw quad with mapped texture 164 | ssaoRect->draw(); 165 | 166 | if (local) End(); 167 | } 168 | 169 | void PostProcess::Start() 170 | { 171 | gl::context()->pushFramebuffer(instance().currentFbo); 172 | gl::context()->pushViewport({ivec2(0), instance().currentFbo->getSize()}); 173 | gl::pushMatrices(); 174 | gl::context()->pushBoolState(GL_DEPTH_TEST, false); 175 | gl::context()->pushDepthMask(false); 176 | gl::clear(); 177 | 178 | // translate to center and scale to fit whole screen 179 | gl::translate(getWindowCenter()); 180 | gl::scale(getWindowSize()); 181 | } 182 | 183 | void PostProcess::End() 184 | { 185 | gl::context()->popFramebuffer(); 186 | gl::context()->popViewport(); 187 | gl::popMatrices(); 188 | gl::context()->popBoolState(GL_DEPTH_TEST); 189 | gl::context()->popDepthMask(); 190 | 191 | // swap current fbo for write 192 | instance().swapFbo(); 193 | } 194 | 195 | const gl::Texture2dRef& PostProcess::getColorTexture() const 196 | { 197 | // returns the color texture of the fbo before swap 198 | return currentFbo == auxiliaryFbo ? colorTexture : auxiliaryTexture; 199 | } 200 | 201 | void PostProcess::resizeFbos() 202 | { 203 | // temporal accumulated texture 204 | gl::Texture2d::Format colorAccFormat = gl::Texture2d::Format().internalFormat(GL_RGB16F) 205 | .magFilter(GL_NEAREST) 206 | .minFilter(GL_NEAREST) 207 | .wrap(GL_REPEAT); 208 | const ivec2 winSize = getWindowSize(); 209 | const int32_t h = winSize.y; 210 | const int32_t w = winSize.x; 211 | 212 | try 213 | { 214 | // create temporal texture 215 | colorTexture = gl::Texture2d::create(w, h, colorAccFormat); 216 | auxiliaryTexture = gl::Texture2d::create(w, h, colorAccFormat); 217 | 218 | // post process result fbo 219 | gl::Fbo::Format colorFormat; 220 | colorFormat.attachment(GL_COLOR_ATTACHMENT0, colorTexture); 221 | colorFormat.depthBuffer(); 222 | colorFbo = gl::Fbo::create(w, h, colorFormat); 223 | 224 | // post process auxiliary result fbo 225 | gl::Fbo::Format auxColorFormat; 226 | auxColorFormat.attachment(GL_COLOR_ATTACHMENT0, auxiliaryTexture); 227 | auxColorFormat.depthBuffer(); 228 | auxiliaryFbo = gl::Fbo::create(w, h, auxColorFormat); 229 | } 230 | catch (const Exception& e) 231 | { 232 | CI_LOG_EXCEPTION("Fbo/Renderbuffer create", e); 233 | } 234 | } 235 | 236 | PostProcess& PostProcess::instance() 237 | { 238 | static PostProcess postProcess; 239 | return postProcess; 240 | } 241 | 242 | void PostProcess::swapFbo() 243 | { 244 | currentFbo = currentFbo == auxiliaryFbo ? colorFbo : auxiliaryFbo; 245 | } 246 | 247 | PostProcess::PostProcess() 248 | { 249 | // create fbos 250 | resizeFbos(); 251 | // post process programs 252 | auto toneMappingProg = gl::GlslProg::create(gl::GlslProg::Format() 253 | .vertex(loadAsset("shaders/fs_quad.vert")) 254 | .fragment(loadAsset("shaders/tonemapping.frag"))); 255 | auto fxaaProg = gl::GlslProg::create(gl::GlslProg::Format() 256 | .vertex(loadAsset("shaders/fs_quad.vert")) 257 | .fragment(loadAsset("shaders/fxaa.frag"))); 258 | auto blurProg = gl::GlslProg::create(gl::GlslProg::Format() 259 | .vertex(loadAsset("shaders/fs_quad.vert")) 260 | .fragment(loadAsset("shaders/blur.frag"))); 261 | auto inverseProg = gl::GlslProg::create(gl::GlslProg::Format() 262 | .vertex(loadAsset("shaders/fs_quad.vert")) 263 | .fragment(loadAsset("shaders/inverse.frag"))); 264 | auto multiplyProg = gl::GlslProg::create(gl::GlslProg::Format() 265 | .vertex(loadAsset("shaders/fs_quad.vert")) 266 | .fragment(loadAsset("shaders/multiply.frag"))); 267 | auto ssaoProg = gl::GlslProg::create(gl::GlslProg::Format() 268 | .vertex(loadAsset("shaders/fs_quad.vert")) 269 | .fragment(loadAsset("shaders/ssao.frag"))); 270 | auto averageProg = gl::GlslProg::create(gl::GlslProg::Format() 271 | .vertex(loadAsset("shaders/fs_quad.vert")) 272 | .fragment(loadAsset("shaders/average.frag"))); 273 | // create fs quad for single texture display 274 | const gl::GlslProgRef stockTexture = gl::context()->getStockShader(gl::ShaderDef().texture(GL_TEXTURE_2D)); 275 | const gl::VboMeshRef rect = gl::VboMesh::create(geom::Rect()); 276 | textureRect = gl::Batch::create(rect, stockTexture); 277 | toneMappingRect = gl::Batch::create(rect, toneMappingProg); 278 | fxaaRect = gl::Batch::create(rect, fxaaProg); 279 | blurRect = gl::Batch::create(rect, blurProg); 280 | inverseRect = gl::Batch::create(rect, inverseProg); 281 | multiplyRect = gl::Batch::create(rect, multiplyProg); 282 | ssaoRect = gl::Batch::create(rect, ssaoProg); 283 | averageRect = gl::Batch::create(rect, averageProg); 284 | // sets targets 285 | currentFbo = colorFbo; 286 | 287 | // SSAO setup 288 | std::uniform_real_distribution randomFloats(0.0, 1.0); // random floats between 0.0 - 1.0 289 | std::default_random_engine generator; 290 | 291 | // Create random sampling kernel 292 | for (GLuint i = 0; i < 64; ++i) 293 | { 294 | vec3 sample 295 | ( 296 | randomFloats(generator) * 2.0 - 1.0, 297 | randomFloats(generator) * 2.0 - 1.0, 298 | randomFloats(generator) 299 | ); 300 | sample = glm::normalize(sample); 301 | sample *= randomFloats(generator); 302 | GLfloat scale = GLfloat(i) / 64.0; 303 | scale = lerp(0.1f, 1.0f, scale * scale); 304 | sample *= scale; 305 | ssaoKernel.push_back(sample); 306 | } 307 | 308 | // Random kernel rotations 309 | std::vector ssaoNoise; 310 | for (GLuint i = 0; i < 16; i++) 311 | { 312 | vec3 noise 313 | ( 314 | randomFloats(generator) * 2.0 - 1.0, 315 | randomFloats(generator) * 2.0 - 1.0, 316 | 0.0f 317 | ); 318 | ssaoNoise.push_back(noise); 319 | } 320 | 321 | auto noiseFormat = gl::Texture2d::Format() 322 | .magFilter(GL_NEAREST) 323 | .minFilter(GL_NEAREST) 324 | .wrap(GL_REPEAT) 325 | .internalFormat(GL_RGB); 326 | noiseFormat.dataType(GL_FLOAT); 327 | ssaoNoiseTexture = gl::Texture2d::create(ssaoNoise.data(), GL_RGB, 4, 4, noiseFormat); 328 | } 329 | -------------------------------------------------------------------------------- /VolumeStyleRendering/Postprocess.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class PostProcess 5 | { 6 | public: 7 | /** 8 | * \brief Displays the given texture on a full screen quad. If colorTex is 9 | * null then it displays the color output of the last post-process effect 10 | * \param colorTex The texture to display 11 | */ 12 | void displayTexture(const ci::gl::Texture2dRef colorTex = nullptr) const; 13 | /** 14 | * \brief Displays the given texture with fast approximate anti-aliasing post effect 15 | * \param texture The color buffer texture 16 | */ 17 | void displayFXAA(const ci::gl::Texture2dRef &texture = nullptr) const; 18 | /** 19 | * \brief Reinhard tonemapping and gamma correction 20 | * \param hdrBuffer An unclampled (floating point) color buffer 21 | * \param local if true will call Start and End at the beginning and the end of function respectively 22 | */ 23 | void toneMapping(const ci::gl::Texture2dRef& hdrBuffer = nullptr, bool local = true) const; 24 | /** 25 | * \brief Horizontal pass to generate a gaussian blurred texture from the given texture 26 | * \param texture The source texture to blur, if null uses the current color texture 27 | * \param local if true will call Start and End at the beginning and the end of function respectively 28 | */ 29 | void blurHorizontal(int blurType = 1, const ci::gl::Texture2dRef& texture = nullptr, bool local = true) const; 30 | /** 31 | * \brief Horizontal pass to generate a gaussian blurred texture from the given texture 32 | * \param texture The source texture to blur, if null uses the current color texture 33 | * \param local if true will call Start and End at the beginning and the end of function respectively 34 | */ 35 | void blurVertical(int blurType = 1, const ci::gl::Texture2dRef& texture = nullptr, bool local = true) const; 36 | /** 37 | * \brief Generates de inverse of the given texture 38 | * \param texture The source texture, if null uses the current color texture 39 | * \param local if true will call Start and End at the beginning and the end of function respectively 40 | */ 41 | void inverse(const ci::gl::Texture2dRef& texture = nullptr, bool local = true) const; 42 | /** 43 | * \brief Multiplies the given textures 44 | * \param texture0 The right source texture for multiplication 45 | * \param texture0 The left source texture for multiplication, if null uses the current color texture 46 | * \param local if true will call Start and End at the beginning and the end of function respectively 47 | */ 48 | void multiply(const ci::gl::Texture2dRef& texture0, const ci::gl::Texture2dRef& texture1 = nullptr, bool local = true) const; 49 | /** 50 | * \brief 4x4 Average gaussian filter 51 | * \param texture Texture to blur 52 | * \param local if true will call Start and End at the beginning and the end of function respectively 53 | */ 54 | void average(const ci::gl::Texture2dRef& texture = nullptr, bool local = true) const; 55 | /** 56 | * \brief Generates the ambient occlusion approximation using screen space ambient occlusion 57 | * \param position Source positions texture 58 | * \param normal Source normals texture 59 | * \param camera Current rendering camera 60 | * \param local if true will call Start and End at the beginning and the end of function respectively 61 | */ 62 | void SSAO(const ci::gl::Texture2dRef& position, const ci::gl::Texture2dRef& normal, const ci::Camera &camera, bool local = true); 63 | /** 64 | * \brief Sets the appropiate flags for fullscreen effects and binds the internal Fbo for drawing 65 | */ 66 | static void Start(); 67 | /** 68 | * \brief Restores the previous rendering flags and unbinds the internal Fbo 69 | */ 70 | static void End(); 71 | /** 72 | * \brief The temporal color texture contains the output color result of 73 | * the last post-process effect executed 74 | * \return The temporal color texture 75 | */ 76 | const ci::gl::Texture2dRef &getColorTexture() const; 77 | /** 78 | * \brief Resizes the created framebuffers to the actual window's size 79 | */ 80 | void resizeFbos(); 81 | /** 82 | * \brief PostProcess follows a singleton pattern 83 | * \return The unique PostProcess instance 84 | */ 85 | static PostProcess& instance(); 86 | private: 87 | // fs screen effects 88 | ci::gl::BatchRef textureRect; 89 | ci::gl::BatchRef toneMappingRect; 90 | ci::gl::BatchRef fxaaRect; 91 | ci::gl::BatchRef blurRect; 92 | ci::gl::BatchRef inverseRect; 93 | ci::gl::BatchRef multiplyRect; 94 | ci::gl::BatchRef ssaoRect; 95 | ci::gl::BatchRef averageRect; 96 | 97 | // current color texture 98 | ci::gl::Texture2dRef colorTexture; 99 | ci::gl::FboRef colorFbo; 100 | // auxiliary for when trying to write to itself 101 | ci::gl::Texture2dRef auxiliaryTexture; 102 | ci::gl::FboRef auxiliaryFbo; 103 | 104 | // draw to this fbo 105 | ci::gl::FboRef currentFbo; 106 | 107 | // SSAO 108 | std::vector ssaoKernel; 109 | ci::gl::Texture2dRef ssaoNoiseTexture; 110 | 111 | void swapFbo(); 112 | PostProcess(); 113 | }; 114 | 115 | -------------------------------------------------------------------------------- /VolumeStyleRendering/RaycastVolume.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "RaycastVolume.h" 5 | #include "StyleTransferFunction.h" 6 | #include "RenderingParams.h" 7 | #include "PostProcess.h" 8 | 9 | using namespace ci; 10 | using namespace glm; 11 | using namespace app; 12 | 13 | RaycastVolume::RaycastVolume() : aspectRatios(1), scaleFactor(vec3(1)), stepScale(1), shadowStepScale(3) 14 | { 15 | // positions shader 16 | positionsProg = gl::GlslProg::create(gl::GlslProg::Format() 17 | .vertex(loadAsset("shaders/positions.vert")) 18 | .fragment(loadAsset("shaders/positions.frag"))); 19 | // raycast shader 20 | raycastShaderRendertargets = gl::GlslProg::create(gl::GlslProg::Format() 21 | .vertex(loadAsset("shaders/raycast.vert")) 22 | .fragment(loadAsset("shaders/raycast_rendertargets.frag"))); 23 | // histogram calculation 24 | histogramCompute = gl::GlslProg::create(gl::GlslProg::Format() 25 | .compute(loadAsset("shaders/histogram.comp"))); 26 | // gradient computation 27 | gradientsCompute = gl::GlslProg::create(gl::GlslProg::Format() 28 | .compute(loadAsset("shaders/gradients.comp"))); 29 | smoothGradientsCompute = gl::GlslProg::create(gl::GlslProg::Format() 30 | .compute(loadAsset("shaders/smooth_gradients.comp"))); 31 | // noise texture to reduce volume banding artifacts 32 | noiseTexture = gl::Texture2d::create(loadImage(loadAsset("images/noise.png")), gl::Texture2d::Format() 33 | .wrapS(GL_REPEAT) 34 | .wrapT(GL_REPEAT) 35 | .magFilter(GL_NEAREST) 36 | .minFilter(GL_NEAREST)); 37 | // create clockwise bbox for volume rendering 38 | createCubeVbo(); 39 | // create frame buffer object 40 | resizeFbos(); 41 | } 42 | 43 | RaycastVolume::~RaycastVolume() {} 44 | 45 | vec3 RaycastVolume::centerPoint() const 46 | { 47 | return vec3(0.5) * scaleFactor; 48 | } 49 | 50 | const float& RaycastVolume::getStepScale() const 51 | { 52 | return stepScale; 53 | } 54 | 55 | void RaycastVolume::setStepScale(const float& value) 56 | { 57 | stepScale = max(value, 0.1f); 58 | } 59 | 60 | const float& RaycastVolume::getShadowStepScale() const 61 | { 62 | return shadowStepScale; 63 | } 64 | 65 | void RaycastVolume::setShadowStepScale(const float& value) 66 | { 67 | shadowStepScale = max(value, 0.5f); 68 | } 69 | 70 | const vec3& RaycastVolume::getAspectRatios() const 71 | { 72 | return aspectRatios; 73 | } 74 | 75 | void RaycastVolume::setAspectratios(const vec3& value) 76 | { 77 | aspectRatios = max(value, vec3(0)); 78 | // volume scale 79 | scaleFactor = vec3(1) / ((vec3(1) * maxSize) / (dimensions * aspectRatios)); 80 | } 81 | 82 | void RaycastVolume::createCubeVbo() 83 | { 84 | cubeMesh = TriMesh::create(geom::Cube()); 85 | 86 | // move cube to 0 - 1 coordinates 87 | for (auto& pos : cubeMesh->getBufferPositions()) { pos += .5; } 88 | 89 | cubeVao = gl::Vao::create(); 90 | // bind vertex buffer object 91 | gl::ScopedVao scopedVao(cubeVao); 92 | { 93 | cubeVerticesBuffer = gl::Vbo::create(GL_ARRAY_BUFFER, sizeof(vec3) * cubeMesh->getNumVertices(), 94 | cubeMesh->getPositions<3>(), GL_STATIC_DRAW); 95 | { 96 | gl::ScopedBuffer scopedBuffer(cubeVerticesBuffer); 97 | gl::vertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, static_cast(nullptr)); 98 | gl::enableVertexAttribArray(0); 99 | } 100 | cubeIndicesBuffer = gl::Vbo::create(GL_ELEMENT_ARRAY_BUFFER, cubeMesh->getIndices(), GL_STATIC_DRAW); 101 | { 102 | gl::ScopedBuffer scopedBuffer(cubeIndicesBuffer); 103 | } 104 | } 105 | } 106 | 107 | void RaycastVolume::readVolumeFromFile8(const std::string filepath) 108 | { 109 | // open file and read 110 | std::ifstream file(filepath, std::ios::binary | std::ios::ate); 111 | 112 | // error opening given filepath 113 | if (!file.good()) return; 114 | 115 | // determine volume size 116 | std::streamsize size = file.tellg(); 117 | file.seekg(0, std::ios::beg); 118 | // reserve space for data 119 | std::vector buffer(size); 120 | 121 | if (file.read(reinterpret_cast(buffer.data()), size)) 122 | { 123 | // create 3D texture 124 | auto format = gl::Texture3d::Format().magFilter(GL_LINEAR) 125 | .minFilter(GL_LINEAR) 126 | .wrapS(GL_CLAMP_TO_BORDER) 127 | .wrapR(GL_CLAMP_TO_BORDER) 128 | .wrapT(GL_CLAMP_TO_BORDER); 129 | format.setDataType(GL_UNSIGNED_BYTE); 130 | format.setInternalFormat(GL_RED); 131 | format.setSwizzleMask(GL_RED, GL_RED, GL_RED, GL_RED); 132 | volumeTexture = gl::Texture3d::create(buffer.data(), GL_RED, 133 | dimensions.x, dimensions.y, dimensions.z, format); 134 | // finally has drawable data 135 | isDrawable = true; 136 | } 137 | 138 | file.close(); 139 | } 140 | 141 | void RaycastVolume::readVolumeFromFile16(const std::string filepath) 142 | { 143 | // open file and read 144 | std::ifstream file(filepath, std::ios::binary | std::ios::ate); 145 | 146 | // error opening given filepath 147 | if (!file.good()) return; 148 | 149 | // determine volume size 150 | std::streamsize size = file.tellg(); 151 | file.seekg(0, std::ios::beg); 152 | // reserve space for data 153 | std::vector buffer(size); 154 | 155 | if (file.read(reinterpret_cast(buffer.data()), size)) 156 | { 157 | // create 3D texture 158 | auto format = gl::Texture3d::Format().magFilter(GL_LINEAR) 159 | .minFilter(GL_LINEAR) 160 | .wrapS(GL_CLAMP_TO_BORDER) 161 | .wrapR(GL_CLAMP_TO_BORDER) 162 | .wrapT(GL_CLAMP_TO_BORDER); 163 | format.setDataType(GL_UNSIGNED_SHORT); 164 | format.setInternalFormat(GL_RED); 165 | format.setSwizzleMask(GL_RED, GL_RED, GL_RED, GL_RED); 166 | volumeTexture = gl::Texture3d::create(buffer.data(), GL_RED, 167 | dimensions.x, dimensions.y, dimensions.z, format); 168 | // finally has drawable data 169 | isDrawable = true; 170 | } 171 | 172 | file.close(); 173 | } 174 | 175 | void RaycastVolume::loadFromFile(const vec3& dimensions, const vec3& ratios, const std::string filepath, 176 | bool is16Bits) 177 | { 178 | // compute step size and number of iterations for the given volume dimensions 179 | this->dimensions = dimensions; 180 | maxSize = max(dimensions.x, max(dimensions.y, dimensions.z)); 181 | stepSize = vec3(1.0f / (dimensions.x * (maxSize / dimensions.x)), 182 | 1.0f / (dimensions.y * (maxSize / dimensions.y)), 183 | 1.0f / (dimensions.z * (maxSize / dimensions.z))); 184 | setAspectratios(ratios); 185 | // create volume texture 186 | is16Bits ? readVolumeFromFile16(filepath) : readVolumeFromFile8(filepath); 187 | // histogram compute 188 | extractHistogram(); 189 | // gradients 190 | generateGradients(); 191 | } 192 | 193 | void RaycastVolume::drawCubeFaces() const 194 | { 195 | gl::ScopedDepth depth(true); 196 | // draw front face 197 | { 198 | gl::ScopedFramebuffer scopedFramebuffer(frontFbo); 199 | gl::ScopedViewport scopedViewport(ivec2(0), frontFbo->getSize()); 200 | gl::ScopedFaceCulling faceCulling(true, GL_BACK); 201 | // draw front face cube positions to render target 202 | gl::clear(); 203 | positionsProg->bind(); 204 | positionsProg->uniform("renderingFront", true); 205 | gl::setDefaultShaderVars(); 206 | gl::drawElements(gl::toGl(cubeMesh->getPrimitive()), cubeMesh->getNumIndices(), 207 | GL_UNSIGNED_INT, static_cast(nullptr)); 208 | } 209 | // draw back face 210 | { 211 | gl::ScopedFramebuffer scopedFramebuffer(backFbo); 212 | gl::ScopedViewport scopedViewport(ivec2(0), backFbo->getSize()); 213 | gl::ScopedFaceCulling faceCulling(true, GL_FRONT); 214 | // draw back face cube positions to render target 215 | gl::clear(); 216 | gl::drawElements(gl::toGl(cubeMesh->getPrimitive()), cubeMesh->getNumIndices(), 217 | GL_UNSIGNED_INT, static_cast(nullptr)); 218 | } 219 | } 220 | 221 | void RaycastVolume::drawVolume(const Camera& camera) 222 | { 223 | if (!isDrawable) return; 224 | 225 | // volume raycast 226 | { 227 | gl::ScopedMatrices scopedMatrices; 228 | gl::ScopedVao scopedCubeVao(cubeVao); 229 | gl::ScopedBuffer scopedCubeIndicesBuffer(cubeIndicesBuffer); 230 | 231 | // set model matrix for model 232 | gl::setMatrices(camera); 233 | gl::rotate(modelRotation); 234 | gl::translate(modelPosition); 235 | gl::scale(scaleFactor); 236 | 237 | // draw cube positions 238 | drawCubeFaces(); 239 | 240 | // ray cast cube 241 | auto program = raycastShaderRendertargets; 242 | gl::ScopedGlslProg scopedProg(program); 243 | gl::ScopedBlend blend(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 244 | gl::ScopedDepth depth(false); 245 | 246 | // bind textures 247 | gl::ScopedTextureBind frontTex(frontTexture, 0); 248 | gl::ScopedTextureBind backTex(backTexture, 1); 249 | gl::ScopedTextureBind volumeTex(volumeTexture, 2); 250 | gl::ScopedTextureBind gradientTex(gradientTexture, 3); 251 | gl::ScopedTextureBind noiseTex(noiseTexture, 4); 252 | gl::ScopedTextureBind colorTex(transferFunction->getColorMappingTexture(), 5); 253 | gl::ScopedTextureBind transferTex(transferFunction->getTransferFunctionTexture(), 6); 254 | gl::ScopedTextureBind indexTex(transferFunction->getIndexFunctionTexture(), 7); 255 | gl::ScopedTextureBind styleTex(transferFunction->getStyleFunctionTexture(), 8); 256 | gl::ScopedTextureBind ambientOcclusionTex(volumeAO, 9); 257 | 258 | // raycast parameters 259 | program->uniform("threshold", vec2(transferFunction->getThreshold()) / 255.0f); 260 | program->uniform("stepSize", stepSize * stepScale); 261 | program->uniform("shadowStepSize", stepSize * shadowStepScale); 262 | program->uniform("stepScale", stepScale); 263 | program->uniform("iterations", static_cast(maxSize * (1.0f / stepScale) * 2.0f)); 264 | 265 | // lighting 266 | program->uniform("raycastShadows", RenderingParams::ShadowsEnabled()); 267 | program->uniform("diffuseShading", RenderingParams::DiffuseShadingEnabled()); 268 | program->uniform("ambientOcclusion", RenderingParams::SSAOEnabled()); 269 | program->uniform("light.direction", light.direction); 270 | program->uniform("light.ambient", light.ambient); 271 | program->uniform("light.diffuse", light.diffuse); 272 | gl::setDefaultShaderVars(); 273 | 274 | // draw volume to render targets 275 | { 276 | const gl::ScopedFramebuffer scopedFramebuffer(volumeRBuffer); 277 | { 278 | const static GLenum buffers[] = 279 | { 280 | GL_COLOR_ATTACHMENT0, 281 | GL_COLOR_ATTACHMENT1, 282 | GL_COLOR_ATTACHMENT2, 283 | GL_COLOR_ATTACHMENT3 284 | }; 285 | gl::drawBuffers(4, buffers); 286 | } 287 | const gl::ScopedViewport scopedViewport(ivec2(0), volumeRBuffer->getSize()); 288 | gl::clear(); 289 | 290 | // draw cube 291 | gl::drawElements(gl::toGl(cubeMesh->getPrimitive()), cubeMesh->getNumIndices(), 292 | GL_UNSIGNED_INT, static_cast(nullptr)); 293 | } 294 | } 295 | // post-process 296 | { 297 | // ambient occlusion 298 | { 299 | PostProcess::instance().SSAO(volumePosition, volumeNormal, camera); 300 | // write blurred result 301 | { 302 | const gl::ScopedViewport scopedViewport(ivec2(0), volumeAOFbo->getSize()); 303 | const gl::ScopedMatrices matrices; 304 | const gl::ScopedDepth depth(false); 305 | const gl::ScopedFramebuffer scopedFramebuffer(volumeAOFbo); 306 | 307 | // translate to center and scale to fit whole screen 308 | gl::translate(getWindowCenter()); 309 | gl::scale(getWindowSize()); 310 | 311 | // gaussian filter 312 | PostProcess::instance().average(nullptr, false); 313 | } 314 | } 315 | 316 | // shadow mapping 317 | if (RenderingParams::ShadowsEnabled()) 318 | { 319 | // invert the shadow color map so shadower areas are black 320 | { 321 | PostProcess::instance().inverse(volumeShadows); 322 | } 323 | // blur to avoid aliasing 324 | { 325 | PostProcess::instance().blurHorizontal(); 326 | PostProcess::instance().blurVertical(); 327 | } 328 | // final shadowing 329 | { 330 | PostProcess::instance().multiply(volumeColor); 331 | } 332 | 333 | // do tonemapping with resulting postprocess's texture 334 | PostProcess::instance().toneMapping(); 335 | } 336 | else // tonemapping with volume's texture 337 | { 338 | PostProcess::instance().toneMapping(volumeColor); 339 | } 340 | 341 | // anti aliasing 342 | if (RenderingParams::FXAAEnabled()) 343 | { 344 | PostProcess::instance().displayFXAA(); 345 | } 346 | else 347 | { 348 | PostProcess::instance().displayTexture(); 349 | } 350 | } 351 | } 352 | 353 | void RaycastVolume::resizeFbos() 354 | { 355 | gl::Texture2d::Format hdrFormat = gl::Texture2d::Format().internalFormat(GL_RGBA16F) 356 | .magFilter(GL_NEAREST) 357 | .minFilter(GL_NEAREST) 358 | .wrap(GL_REPEAT) 359 | .dataType(GL_FLOAT); 360 | gl::Texture2d::Format dataFormat = gl::Texture2d::Format().internalFormat(GL_RGB16F) 361 | .magFilter(GL_NEAREST) 362 | .minFilter(GL_NEAREST) 363 | .wrap(GL_REPEAT) 364 | .dataType(GL_FLOAT); 365 | gl::Texture2d::Format sFormat = gl::Texture2d::Format().internalFormat(GL_R8) 366 | .magFilter(GL_LINEAR) 367 | .minFilter(GL_LINEAR) 368 | .wrap(GL_REPEAT) 369 | .dataType(GL_UNSIGNED_BYTE) 370 | .swizzleMask(GL_RED, GL_RED, GL_RED, GL_RED); 371 | 372 | const ivec2 winSize = getWindowSize(); 373 | const int32_t h = winSize.y; 374 | const int32_t w = winSize.x; 375 | 376 | try 377 | { 378 | // cube positions rendering 379 | gl::Fbo::Format frontFormat, backFormat; 380 | frontTexture = gl::Texture2d::create(w, h, dataFormat); 381 | backTexture = gl::Texture2d::create(w, h, dataFormat); 382 | volumeColor = gl::Texture2d::create(w, h, hdrFormat); 383 | volumeNormal = gl::Texture2d::create(w, h, dataFormat); 384 | volumeShadows = gl::Texture2d::create(w, h, sFormat); 385 | volumePosition = gl::Texture2d::create(w, h, dataFormat); 386 | volumeAO = gl::Texture2d::create(w, h, sFormat); 387 | 388 | // front fbo 389 | frontFormat.attachment(GL_COLOR_ATTACHMENT0, frontTexture); 390 | frontFormat.depthBuffer(); 391 | frontFbo = gl::Fbo::create(w, h, frontFormat); 392 | 393 | // back fbo 394 | backFormat.attachment(GL_COLOR_ATTACHMENT0, backTexture); 395 | backFormat.depthBuffer(); 396 | backFbo = gl::Fbo::create(w, h, backFormat); 397 | 398 | // raycast rendering rendertargets 399 | gl::Fbo::Format gBufferFormat; 400 | gBufferFormat.attachment(GL_COLOR_ATTACHMENT0, volumeColor); 401 | gBufferFormat.attachment(GL_COLOR_ATTACHMENT1, volumeNormal); 402 | gBufferFormat.attachment(GL_COLOR_ATTACHMENT2, volumeShadows); 403 | gBufferFormat.attachment(GL_COLOR_ATTACHMENT3, volumePosition); 404 | gBufferFormat.depthBuffer(); 405 | volumeRBuffer = gl::Fbo::create(w, h, gBufferFormat); 406 | 407 | // ambient occlusion 408 | gl::Fbo::Format aoFormat; 409 | aoFormat.attachment(GL_COLOR_ATTACHMENT0, volumeAO); 410 | aoFormat.depthBuffer(); 411 | volumeAOFbo = gl::Fbo::create(w, h, aoFormat); 412 | } 413 | catch (const Exception& e) 414 | { 415 | CI_LOG_EXCEPTION("Fbo/Renderbuffer create", e); 416 | } 417 | } 418 | 419 | void RaycastVolume::extractHistogram() 420 | { 421 | std::array histogramData = {0}; 422 | // create shader storage buffer 423 | histogramSsbo = gl::Ssbo::create(256 * sizeof(uint32_t), histogramData.data(), GL_DYNAMIC_COPY); 424 | histogramSsbo->bindBase(1); 425 | 426 | // compute histogram 427 | { 428 | // bind histogram compute shader 429 | histogramCompute->bind(); 430 | // volume texture 431 | glBindImageTexture(0, volumeTexture->getId(), 0, true, 0, GL_READ_ONLY, GL_R8UI); 432 | bindBufferBase(histogramSsbo->getTarget(), 1, histogramSsbo); 433 | // compute histogram 434 | gl::dispatchCompute(1, 1, 1); 435 | // block to ensure completion 436 | gl::memoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); 437 | } 438 | 439 | // extract histogram values 440 | uint32_t* ssboValues = reinterpret_cast(histogramSsbo->map(GL_WRITE_ONLY)); 441 | memcpy(histogramData.data(), ssboValues, 256 * sizeof(uint32_t)); 442 | histogramSsbo->unmap(); 443 | // convert to normalized floating values 444 | auto maxValue = max_element(histogramData.begin(), histogramData.end()); 445 | 446 | // normalize and insert values 447 | for (int i = 0; i < 256; i++) 448 | { 449 | histogram[i] = static_cast(histogramData[i]) / *maxValue; 450 | } 451 | } 452 | 453 | void RaycastVolume::generateGradients() 454 | { 455 | auto format = gl::Texture3d::Format().magFilter(GL_LINEAR) 456 | .minFilter(GL_LINEAR) 457 | .wrapS(GL_CLAMP_TO_BORDER) 458 | .wrapR(GL_CLAMP_TO_BORDER) 459 | .wrapT(GL_CLAMP_TO_BORDER) 460 | .internalFormat(GL_RG16F); 461 | format.setDataType(GL_FLOAT); 462 | gradientTexture = gl::Texture3d::create(dimensions.x, dimensions.y, dimensions.z, format); 463 | 464 | // compute gradients 465 | { 466 | gradientsCompute->bind(); 467 | // pass textures 468 | glBindImageTexture(0, volumeTexture->getId(), 0, true, 0, GL_READ_ONLY, GL_R8UI); 469 | glBindImageTexture(1, gradientTexture->getId(), 0, true, 0, GL_WRITE_ONLY, GL_RG16F); 470 | // compute gradients 471 | gl::dispatchCompute(ceil(dimensions.x / 8), ceil(dimensions.y / 8), ceil(dimensions.z / 8)); 472 | } 473 | // smooth gradients 474 | { 475 | smoothGradientsCompute->bind(); 476 | // pass textures 477 | glBindImageTexture(0, gradientTexture->getId(), 0, true, 0, GL_READ_WRITE, GL_RG16F); 478 | // compute gradients 479 | gl::dispatchCompute(ceil(dimensions.x / 8), ceil(dimensions.y / 8), ceil(dimensions.z / 8)); 480 | } 481 | } 482 | 483 | const std::array& RaycastVolume::getHistogram() const 484 | { 485 | return histogram; 486 | } 487 | 488 | void RaycastVolume::setTransferFunction(const std::shared_ptr& transferFunction) 489 | { 490 | this->transferFunction = transferFunction; 491 | } 492 | 493 | void RaycastVolume::setLight(vec3 direction, vec3 ambient, vec3 diffuse) 494 | { 495 | light.direction = direction; 496 | light.ambient = ambient; 497 | light.diffuse = diffuse; 498 | } 499 | 500 | const Light& RaycastVolume::getLight() const { return light; } 501 | 502 | const quat& RaycastVolume::getRotation() const { return modelRotation; } 503 | 504 | void RaycastVolume::setRotation(const quat& rotation) { modelRotation = rotation; } 505 | 506 | const vec3& RaycastVolume::getPosition() const { return modelPosition; } 507 | 508 | void RaycastVolume::setPosition(const vec3& position) { modelPosition = position; } 509 | 510 | const gl::Texture2dRef& RaycastVolume::getColorTexture() const 511 | { 512 | return volumeColor; 513 | } 514 | 515 | const gl::Texture2dRef& RaycastVolume::getNormalTexture() const 516 | { 517 | return volumeNormal; 518 | } 519 | 520 | const gl::Texture2dRef& RaycastVolume::getDepthTexture() const 521 | { 522 | return volumeRBuffer->getDepthTexture(); 523 | } 524 | -------------------------------------------------------------------------------- /VolumeStyleRendering/RaycastVolume.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "Light.h" 4 | 5 | class StyleTransferFunction; 6 | 7 | /** 8 | * \brief Defines a volume rendered with volume raycasting 9 | */ 10 | class RaycastVolume 11 | { 12 | public: 13 | /** 14 | * \brief Loads the raw data from the given filepath into a 3d texture 15 | * \param dimensions The volume dimensions 16 | * \param ratios The volume aspect ratios 17 | * \param filepath The volume's raw data filepath 18 | * \param is16Bits Determines if the volume is 8 o 16 bits depth 19 | */ 20 | void loadFromFile(const glm::vec3& dimensions, const glm::vec3& ratios, const std::string filepath, bool is16Bits = false); 21 | /** 22 | * \brief Renders the volume using raycasting to the specified output 23 | * \param camera Main rendering camera 24 | * \param toRendertargets If true it renders the raycasting result to color, normal and depth render targets 25 | */ 26 | 27 | void drawVolume(const cinder::Camera& camera); 28 | /** 29 | * \brief Updates frame buffer objects to the current size of the main window 30 | */ 31 | void resizeFbos(); 32 | 33 | explicit RaycastVolume(); 34 | ~RaycastVolume(); 35 | 36 | // getters and setters 37 | /** 38 | * \brief The volume resides inside a 0-1 bouding box, this returns the post-scale center point 39 | * \return The volume center point 40 | */ 41 | glm::vec3 centerPoint() const; 42 | /** 43 | * \brief Raycasting's step scale 44 | * \return The step scale of the raycasting ray 45 | */ 46 | const float &getStepScale() const; 47 | /** 48 | * \brief Sets the volume raycasting's ray step scale 49 | * \param value The new step scale 50 | */ 51 | void setStepScale(const float& value); 52 | /** 53 | * \brief Raycasting's step scale for the occlusion check ray 54 | * \return The step scale of the raycasting ray 55 | */ 56 | const float &getShadowStepScale() const; 57 | /** 58 | * \brief Sets the volume raycasting's ray step scale for the occlusion check ray 59 | * \param value The new step scale 60 | */ 61 | void setShadowStepScale(const float& value); 62 | /** 63 | * \brief Volume's aspect ratios per axis 64 | * \return Volume's aspect ratios 65 | */ 66 | const glm::vec3 &getAspectRatios() const; 67 | /** 68 | * \brief Sets the volume's aspect ratio 69 | * \param value The new aspect ratio 70 | */ 71 | void setAspectratios(const glm::vec3& value); 72 | /** 73 | * \brief The volume's histogram contains the normalized [0..1] frequencies of each opacity value 74 | * \return The volume's data histogram 75 | */ 76 | const std::array &getHistogram() const; 77 | /** 78 | * \brief Sets the color mapping transfer function, used to set the color of each opacity value 79 | * \param transferFunction Color transfer function 80 | */ 81 | void setTransferFunction(const std::shared_ptr& transferFunction); 82 | /** 83 | * \brief Sets the volume raycast directional light 84 | * \param direction Light's direction 85 | * \param ambient Light's ambient color 86 | * \param diffuse Light's diffuse color 87 | */ 88 | void setLight(glm::vec3 direction, glm::vec3 ambient, glm::vec3 diffuse); 89 | /** 90 | * \brief Directional light used for simple lighting in the volume raycasting 91 | * \return The volume raycast's directional light 92 | */ 93 | const Light &getLight() const; 94 | /** 95 | * \brief The volume's model rotation 96 | * \return Model quaternion rotation 97 | */ 98 | const glm::quat &getRotation() const; 99 | /** 100 | * \brief Sets the volume's model rotation 101 | * \param rotation The new rotation 102 | */ 103 | void setRotation(const glm::quat& rotation); 104 | /** 105 | * \brief The volume's model position 106 | * \return 3d position in world space 107 | */ 108 | const glm::vec3 &getPosition() const; 109 | /** 110 | * \brief Sets the volume's model position in world space 111 | * \param position The new volume position in world space 112 | */ 113 | void setPosition(const glm::vec3& position); 114 | 115 | /** 116 | * \brief When rendering is done to render targets this texture contains the color output 117 | * \return The color output render target 118 | */ 119 | const ci::gl::Texture2dRef &getColorTexture() const; 120 | /** 121 | * \brief When rendering is done to render targets this texture contains the normal output 122 | * \return The normal output render target 123 | */ 124 | const cinder::gl::Texture2dRef &getNormalTexture() const; 125 | /** 126 | * \brief When rendering is done to render targets this texture contains the depth output 127 | * \return The depth output render target 128 | */ 129 | const cinder::gl::Texture2dRef &getDepthTexture() const; 130 | private: 131 | // histogram data 132 | std::array histogram; 133 | 134 | // cube for positions 135 | ci::TriMeshRef cubeMesh; 136 | ci::gl::VboRef cubeVerticesBuffer; 137 | ci::gl::VboRef cubeIndicesBuffer; 138 | ci::gl::VaoRef cubeVao; 139 | 140 | // volume texture 141 | ci::gl::Texture3dRef gradientTexture; 142 | ci::gl::Texture3dRef volumeTexture; 143 | 144 | // fbos 145 | ci::gl::FboRef frontFbo; 146 | ci::gl::FboRef backFbo; 147 | ci::gl::FboRef volumeRBuffer; 148 | ci::gl::FboRef volumeAOFbo; 149 | 150 | // volume raycast 151 | ci::gl::GlslProgRef raycastShaderRendertargets; 152 | ci::gl::GlslProgRef positionsProg; 153 | std::shared_ptr transferFunction; 154 | 155 | // lighting 156 | ci::gl::GlslProgRef applyBlurredShadows; 157 | Light light; 158 | 159 | // compute shaders 160 | ci::gl::SsboRef histogramSsbo; 161 | ci::gl::GlslProgRef histogramCompute; 162 | ci::gl::GlslProgRef gradientsCompute; 163 | ci::gl::GlslProgRef smoothGradientsCompute; 164 | 165 | // render targets 166 | ci::gl::Texture2dRef frontTexture; 167 | ci::gl::Texture2dRef backTexture; 168 | ci::gl::Texture2dRef volumeNormal; 169 | ci::gl::Texture2dRef volumeColor; 170 | ci::gl::Texture2dRef volumeShadows; 171 | ci::gl::Texture2dRef volumePosition; 172 | ci::gl::Texture2dRef volumeAO; 173 | 174 | // raycast parameters 175 | ci::gl::Texture2dRef noiseTexture; 176 | glm::vec3 dimensions; 177 | glm::vec3 stepSize; 178 | glm::vec3 aspectRatios; 179 | glm::vec3 scaleFactor; 180 | float stepScale; 181 | float shadowStepScale; 182 | float maxSize; 183 | 184 | // model 185 | bool isDrawable; 186 | glm::quat modelRotation; 187 | glm::vec3 modelPosition; 188 | 189 | /** 190 | * \brief Draws the bounding cube back and front face to the position Rendertargets 191 | */ 192 | void drawCubeFaces() const; 193 | /** 194 | * \brief Creates the bounding cube vertex buffer object, used for drawing 195 | */ 196 | void createCubeVbo(); 197 | /** 198 | * \brief Reads the raw data at filepath and creates a 3d texture 199 | * \param filepath The 8 bits depth raw file path 200 | */ 201 | void readVolumeFromFile8(const std::string filepath); 202 | /** 203 | * \brief Reads the raw data at filepath and creates a 3d texture 204 | * \param filepath The 18 bits depth raw file path 205 | */ 206 | void readVolumeFromFile16(const std::string filepath); 207 | /** 208 | * \brief Uses a compute shader to extract the frequency of each opacity value within the volume 209 | * and creates a normalized histogram with this data 210 | */ 211 | void extractHistogram(); 212 | /** 213 | * \brief Creates a 3d texture containing the gradient at each voxel and smooths the values using 214 | * a 3x3x3 average filter 215 | */ 216 | void generateGradients(); 217 | }; 218 | -------------------------------------------------------------------------------- /VolumeStyleRendering/RenderingParams.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "RenderingParams.h" 4 | 5 | using namespace glm; 6 | 7 | float RenderingParams::gammaValue = 2.2f; 8 | float RenderingParams::exposureValue = 1.0f; 9 | bool RenderingParams::fxaa = true; 10 | bool RenderingParams::diffuseShading = true; 11 | bool RenderingParams::shadows = true; 12 | bool RenderingParams::ssao = true; 13 | float RenderingParams::ssaoBias = 0.025f; 14 | float RenderingParams::ssaoRadius = 0.5f; 15 | float RenderingParams::ssaoPower = 1.0f; 16 | 17 | float RenderingParams::GetExposure() 18 | { 19 | return exposureValue; 20 | } 21 | 22 | void RenderingParams::SetExposure(const float exposure) 23 | { 24 | exposureValue = min(max(epsilon(), exposure), 8.0f); 25 | } 26 | 27 | float RenderingParams::GetGamma() 28 | { 29 | return gammaValue; 30 | } 31 | 32 | void RenderingParams::SetGamma(const float gamma) 33 | { 34 | gammaValue = min(max(epsilon(), gamma), 10.0f); 35 | } 36 | 37 | void RenderingParams::FXAAEnabled(const bool enabled) 38 | { 39 | fxaa = enabled; 40 | } 41 | 42 | bool RenderingParams::FXAAEnabled() 43 | { 44 | return fxaa; 45 | } 46 | 47 | void RenderingParams::DiffuseShadingEnabled(const bool enabled) 48 | { 49 | diffuseShading = enabled; 50 | } 51 | 52 | bool RenderingParams::DiffuseShadingEnabled() 53 | { 54 | return diffuseShading; 55 | } 56 | 57 | void RenderingParams::ShadowsEnabled(const bool enabled) 58 | { 59 | shadows = enabled; 60 | } 61 | 62 | bool RenderingParams::ShadowsEnabled() 63 | { 64 | return shadows; 65 | } 66 | 67 | void RenderingParams::SSAOEnabled(const bool enabled) 68 | { 69 | ssao = enabled; 70 | } 71 | 72 | bool RenderingParams::SSAOEnabled() 73 | { 74 | return ssao; 75 | } 76 | 77 | void RenderingParams::SSAOBias(const float bias) 78 | { 79 | ssaoBias = clamp(bias, 0.0f, 0.5f); 80 | } 81 | 82 | float RenderingParams::SSAOBias() 83 | { 84 | return ssaoBias; 85 | } 86 | 87 | void RenderingParams::SSAORadius(const float radius) 88 | { 89 | ssaoRadius = clamp(radius, 0.001f, 8.0f); 90 | } 91 | 92 | float RenderingParams::SSAORadius() 93 | { 94 | return ssaoRadius; 95 | } 96 | 97 | void RenderingParams::SSAOPower(const float power) 98 | { 99 | ssaoPower = clamp(power, 0.0f, 32.0f); 100 | } 101 | 102 | float RenderingParams::SSAOPower() 103 | { 104 | return ssaoPower; 105 | } 106 | -------------------------------------------------------------------------------- /VolumeStyleRendering/RenderingParams.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | class RenderingParams 3 | { 4 | public: 5 | static float GetExposure(); 6 | static void SetExposure(const float exposure); 7 | static float GetGamma(); 8 | static void SetGamma(const float gamma); 9 | static void FXAAEnabled(const bool enabled); 10 | static bool FXAAEnabled(); 11 | static void DiffuseShadingEnabled(const bool enabled); 12 | static bool DiffuseShadingEnabled(); 13 | static void ShadowsEnabled(const bool enabled); 14 | static bool ShadowsEnabled(); 15 | static void SSAOEnabled(const bool enabled); 16 | static bool SSAOEnabled(); 17 | static void SSAOBias(const float bias); 18 | static float SSAOBias(); 19 | static void SSAORadius(const float radius); 20 | static float SSAORadius(); 21 | static void SSAOPower(const float power); 22 | static float SSAOPower(); 23 | private: 24 | static float gammaValue; 25 | static float exposureValue; 26 | static bool fxaa; 27 | static bool diffuseShading; 28 | static bool shadows; 29 | static bool ssao; 30 | static float ssaoBias; 31 | static float ssaoRadius; 32 | static float ssaoPower; 33 | }; 34 | 35 | -------------------------------------------------------------------------------- /VolumeStyleRendering/StyleTransferFunction.cpp: -------------------------------------------------------------------------------- 1 | #include "StyleTransferFunction.h" 2 | #include 3 | #include 4 | using namespace glm; 5 | using namespace ci; 6 | using namespace app; 7 | std::vector