From 5be372d773dbad95d7cdc516f778aa0d5f6bc076 Mon Sep 17 00:00:00 2001 From: gs5579 Date: Tue, 1 Dec 2026 06:34:45 +0000 Subject: [PATCH] Post-processing: bloom, ambient occlusion, filmic tone mapping, colour grading, FXAA Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- CMakeLists.txt | 1 + src/app/AppUi.cpp | 77 +++++++- src/app/AppUi.h | 3 + src/app/Render.cpp | 4 +- src/app/main.cpp | 21 ++ src/render/GpuCaps.cpp | 2 + src/render/GpuCaps.h | 2 + src/render/PostFx.cpp | 415 +++++++++++++++++++++++++++++++++++++++ src/render/PostFx.h | 52 +++++ src/scene/LookSettings.h | 16 ++ src/scene/SceneFile.cpp | 30 ++- tests/test_main.cpp | 6 + 12 files changed, 619 insertions(+), 10 deletions(-) create mode 100644 src/render/PostFx.cpp create mode 100644 src/render/PostFx.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e152d3d..c2b6302 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -142,6 +142,7 @@ add_executable(model_renderer src/render/Grid.cpp src/render/ModelNode.cpp src/render/Look.cpp + src/render/PostFx.cpp src/render/TextureLoader.cpp src/render/Shaders.cpp src/render/GpuCaps.cpp diff --git a/src/app/AppUi.cpp b/src/app/AppUi.cpp index 79d2e71..39b6e93 100644 --- a/src/app/AppUi.cpp +++ b/src/app/AppUi.cpp @@ -74,11 +74,18 @@ App::App(osgViewer::Viewer& viewer, osg::Group* root, osgGA::TrackballManipulato root_->addUpdateCallback(new TickCallback(this)); viewer_.getCamera()->setProjectionResizePolicy(osg::Camera::FIXED); imgui_->attach(viewer_); + sceneRoot_ = new osg::Group; grid_ = createGrid(50.f, 5.f); - root_->addChild(grid_); + sceneRoot_->addChild(grid_); sceneGroup_ = new osg::Group; - root_->addChild(sceneGroup_); - sceneLook_ = std::make_unique(root_.get(), sceneGroup_.get()); + sceneRoot_->addChild(sceneGroup_); + sceneLook_ = std::make_unique(sceneRoot_.get(), sceneGroup_.get()); + // One post-processing chain per output camera; each camera's cull mask picks its own. + mainChain_ = new PostChain(sceneRoot_.get(), kMainViewMask); + popChain_ = new PostChain(sceneRoot_.get(), kPopViewMask); + renderChain_ = new PostChain(sceneRoot_.get(), kRenderViewMask); + for (PostChain* chain : {mainChain_.get(), popChain_.get(), renderChain_.get()}) root_->addChild(chain); + viewer_.getCamera()->setCullMask(kMainViewMask | kGridNodeMask); } void App::setLook(const LookSettings& look) { @@ -87,7 +94,20 @@ void App::setLook(const LookSettings& look) { } void App::updateLook() { - if (gpuCaps().probed) sceneLook_->setShadowsSupported(gpuCaps().shadows); + if (gpuCaps().probed) { + sceneLook_->setShadowsSupported(gpuCaps().shadows); + for (PostChain* chain : {mainChain_.get(), popChain_.get(), renderChain_.get()}) + chain->setSupported(gpuCaps().framebufferObjects, gpuCaps().floatTextures); + } + osg::Camera* master = viewer_.getCamera(); + if (const osg::Viewport* vp = master->getViewport()) + mainChain_->setSize(static_cast(vp->width()), static_cast(vp->height())); + mainChain_->setClearColor(master->getClearColor()); + if (popCamera_ && popCamera_->getViewport()) { + popChain_->setSize(static_cast(popCamera_->getViewport()->width()), + static_cast(popCamera_->getViewport()->height())); + popChain_->setClearColor(popCamera_->getClearColor()); + } // Shadows cover the characters; with only stages visible they cover a capped part of the stage. osg::BoundingSphere characters, stages; for (const auto& item : items_) { @@ -171,6 +191,7 @@ void App::updatePlacement(SceneItem& item) { } void App::applyViewSettings() { + for (PostChain* chain : {mainChain_.get(), popChain_.get(), renderChain_.get()}) chain->apply(look_); sceneLook_->apply(look_); for (auto& item : items_) { ModelNode* node = item->node.get(); @@ -359,6 +380,7 @@ void App::updatePopOut() { popCamera_->setClearMask(master->getClearMask()); // Slaves inherit the master's cull settings; the master's cull mask hides the scene. popCamera_->setInheritanceMask(popCamera_->getInheritanceMask() & ~osg::CullSettings::CULL_MASK); + popCamera_->setCullMask(kPopViewMask | kGridNodeMask); popCamera_->setDrawBuffer(GL_BACK); popCamera_->setReadBuffer(GL_BACK); viewer_.addSlave(popCamera_.get(), true); @@ -375,7 +397,7 @@ void App::updatePopOut() { popCamera_->setGraphicsContext(nullptr); } popCamera_ = nullptr; - master->setCullMask(~0u); + master->setCullMask(kMainViewMask | kGridNodeMask); } if (!popCamera_) return; const osg::GraphicsContext::Traits* traits = popCamera_->getGraphicsContext()->getTraits(); @@ -778,10 +800,14 @@ void App::drawLookWindow() { bool outlines; float rim; osg::Vec3f light; + bool bloom, ao, fxaa; + int toneMapping; + float saturation, vignette; }; - const Preset presets[] = {{"MMD classic", 0, true, 0.f, {0.6f, 0.6f, 0.6f}}, - {"Anime", 2, true, 0.6f, {0.85f, 0.82f, 0.8f}}, - {"Studio", 3, false, 0.35f, {0.95f, 0.9f, 0.82f}}}; + const Preset presets[] = { + {"MMD classic", 0, true, 0.f, {0.6f, 0.6f, 0.6f}, false, false, false, 0, 1.f, 0.f}, + {"Anime", 2, true, 0.6f, {0.85f, 0.82f, 0.8f}, true, false, true, 0, 1.1f, 0.f}, + {"Studio", 3, false, 0.35f, {0.95f, 0.9f, 0.82f}, true, true, true, 1, 1.f, 0.3f}}; for (const Preset& p : presets) { if (&p != presets) ImGui::SameLine(); if (ImGui::Button(p.name)) { @@ -790,6 +816,12 @@ void App::drawLookWindow() { look_.rimStrength = p.rim; look_.lightColor = p.light; look_.shadows = true; + look_.bloom = p.bloom; + look_.ambientOcclusion = p.ao; + look_.fxaa = p.fxaa; + look_.toneMapping = p.toneMapping; + look_.saturation = p.saturation; + look_.vignette = p.vignette; changed = true; } } @@ -836,6 +868,35 @@ void App::drawLookWindow() { changed |= ImGui::SliderFloat("Rim strength", &look_.rimStrength, 0.f, 1.5f, "%.2f"); changed |= ImGui::ColorEdit3("Rim color", look_.rimColor.ptr(), ImGuiColorEditFlags_Float); + ImGui::SeparatorText("Post-processing"); + const bool postOk = mainChain_->supported() || !gpuCaps().probed; + ImGui::BeginDisabled(!postOk); + changed |= ImGui::Checkbox("Bloom", &look_.bloom); + ImGui::BeginDisabled(!look_.bloom); + changed |= ImGui::SliderFloat("Bloom strength", &look_.bloomStrength, 0.f, 2.f, "%.2f"); + changed |= ImGui::SliderFloat("Bloom threshold", &look_.bloomThreshold, 0.f, 1.5f, "%.2f"); + changed |= ImGui::SliderFloat("Bloom size", &look_.bloomRadius, 0.25f, 4.f, "%.2f"); + ImGui::EndDisabled(); + changed |= ImGui::Checkbox("Ambient occlusion", &look_.ambientOcclusion); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Soft darkening in creases and where objects meet."); + ImGui::BeginDisabled(!look_.ambientOcclusion); + changed |= ImGui::SliderFloat("AO strength", &look_.aoStrength, 0.f, 3.f, "%.2f"); + changed |= ImGui::SliderFloat("AO radius", &look_.aoRadius, 0.2f, 6.f, "%.1f"); + ImGui::EndDisabled(); + changed |= ImGui::Checkbox("Anti-aliasing (FXAA)", &look_.fxaa); + + ImGui::SeparatorText("Colour grading"); + const char* toneMaps[] = {"Off", "Filmic"}; + changed |= ImGui::Combo("Tone mapping", &look_.toneMapping, toneMaps, IM_ARRAYSIZE(toneMaps)); + changed |= ImGui::SliderFloat("Exposure", &look_.exposure, 0.25f, 3.f, "%.2f"); + changed |= ImGui::SliderFloat("Contrast", &look_.contrast, 0.5f, 1.5f, "%.2f"); + changed |= ImGui::SliderFloat("Saturation", &look_.saturation, 0.f, 2.f, "%.2f"); + changed |= ImGui::SliderFloat("Temperature", &look_.temperature, -1.f, 1.f, "%.2f"); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Negative is cooler (blue), positive warmer (orange)."); + changed |= ImGui::SliderFloat("Vignette", &look_.vignette, 0.f, 1.f, "%.2f"); + ImGui::EndDisabled(); + if (!postOk) ImGui::TextDisabled("This GPU cannot run post-processing."); + ImGui::Separator(); if (ImGui::Button("Reset look")) { const int shading = look_.shading; diff --git a/src/app/AppUi.h b/src/app/AppUi.h index a458c5e..4008eec 100644 --- a/src/app/AppUi.h +++ b/src/app/AppUi.h @@ -8,6 +8,7 @@ #include "model/Motion.h" #include "render/Look.h" #include "render/ModelNode.h" +#include "render/PostFx.h" #include "ui/ImGuiOsg.h" #include @@ -89,7 +90,9 @@ private: osgViewer::Viewer& viewer_; osg::ref_ptr root_; + osg::ref_ptr sceneRoot_; // everything 3D; drawn through a post-processing chain osg::ref_ptr sceneGroup_; // models and stages + osg::ref_ptr mainChain_, popChain_, renderChain_; std::unique_ptr sceneLook_; osg::ref_ptr manipulator_; osg::ref_ptr imgui_; diff --git a/src/app/Render.cpp b/src/app/Render.cpp index 68f3188..cf390e9 100644 --- a/src/app/Render.cpp +++ b/src/app/Render.cpp @@ -80,10 +80,12 @@ void App::startRender() { cam->attach(osg::Camera::COLOR_BUFFER, render_.image.get(), 4, 0); cam->setReferenceFrame(osg::Transform::ABSOLUTE_RF); cam->setInheritanceMask(cam->getInheritanceMask() & ~osg::CullSettings::CULL_MASK); - cam->setCullMask(~kGridNodeMask); + cam->setCullMask(kRenderViewMask); osg::Vec4 clear = master->getClearColor(); if (render_.transparent) clear.a() = 0.f; cam->setClearColor(clear); + renderChain_->setSize(render_.width, render_.height); + renderChain_->setClearColor(clear); cam->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); viewer_.addSlave(cam.get(), true); if (!cam->getRenderer()) cam->setRenderer(new osgViewer::Renderer(cam.get())); diff --git a/src/app/main.cpp b/src/app/main.cpp index 415960c..15cf4b2 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -79,6 +79,10 @@ void printUsage() { " --shadows on|off shadow mapping (default on)\n" " --outlines on|off MMD edge outlines (default on)\n" " --rim S rim light strength (0 = off)\n" + " --bloom S bloom strength (0 = off)\n" + " --ao on|off ambient occlusion\n" + " --fxaa on|off FXAA anti-aliasing\n" + " --filmic on|off filmic tone mapping\n" " --pop-out show the 3D view in its own window\n" " --render DIR render PNG frames into DIR and exit\n" " --range A,B frames to render (default: whole timeline)\n" @@ -177,6 +181,8 @@ int main(int argc, char** argv) { std::string saveScenePath; bool orbitSet = false, physicsSet = false; int shading = -1, shadows = -1, outlines = -1; + float bloom = -1.f; + int ao = -1, fxaa = -1, filmic = -1; float rim = -1.f; int reloadTest = 0; std::string renderDir; @@ -256,6 +262,14 @@ int main(int argc, char** argv) { shadows = next() != "off" ? 1 : 0; } else if (a == "--outlines") { outlines = next() != "off" ? 1 : 0; + } else if (a == "--bloom") { + bloom = std::stof(next()); + } else if (a == "--ao") { + ao = next() != "off"; + } else if (a == "--fxaa") { + fxaa = next() != "off"; + } else if (a == "--filmic") { + filmic = next() != "off"; } else if (a == "--rim") { rim = std::strtof(next().c_str(), nullptr); } else if (a == "--reload-test") { @@ -319,6 +333,13 @@ int main(int argc, char** argv) { { mr::LookSettings look = app.look(); if (shading >= 0) look.shading = shading; + if (bloom >= 0.f) { + look.bloom = bloom > 0.f; + look.bloomStrength = bloom > 0.f ? bloom : look.bloomStrength; + } + if (ao >= 0) look.ambientOcclusion = ao == 1; + if (fxaa >= 0) look.fxaa = fxaa == 1; + if (filmic >= 0) look.toneMapping = filmic; if (shadows >= 0) look.shadows = shadows == 1; if (outlines >= 0) look.outlines = outlines == 1; if (rim >= 0.f) look.rimStrength = rim; diff --git a/src/render/GpuCaps.cpp b/src/render/GpuCaps.cpp index 71acd13..7e08fae 100644 --- a/src/render/GpuCaps.cpp +++ b/src/render/GpuCaps.cpp @@ -27,6 +27,8 @@ void GpuCapsProbe::operator()(osg::GraphicsContext* gc) { caps.skinning = vertexUnits > 0 && floatTextures; caps.shadows = osg::isGLExtensionOrVersionSupported(contextID, "GL_ARB_depth_texture", 1.4f) && osg::isGLExtensionOrVersionSupported(contextID, "GL_EXT_framebuffer_object", 3.0f); + caps.framebufferObjects = osg::isGLExtensionOrVersionSupported(contextID, "GL_EXT_framebuffer_object", 3.0f); + caps.floatTextures = floatTextures; caps.probed = true; if (next_) (*next_)(gc); } diff --git a/src/render/GpuCaps.h b/src/render/GpuCaps.h index 2168e90..22215a5 100644 --- a/src/render/GpuCaps.h +++ b/src/render/GpuCaps.h @@ -10,6 +10,8 @@ struct GpuCaps { bool probed = false; bool skinning = false; // vertex texture fetch + float textures bool shadows = false; // depth textures + framebuffer objects + bool framebufferObjects = false; + bool floatTextures = false; std::string renderer; }; diff --git a/src/render/PostFx.cpp b/src/render/PostFx.cpp new file mode 100644 index 0000000..f87bcc9 --- /dev/null +++ b/src/render/PostFx.cpp @@ -0,0 +1,415 @@ +#include "render/PostFx.h" + +#include +#include +#include +#include +#include + +#include +#include + +#ifndef GL_RGBA16F_ARB +#define GL_RGBA16F_ARB 0x881A +#endif +#ifndef GL_DEPTH_COMPONENT24 +#define GL_DEPTH_COMPONENT24 0x81A6 +#endif + +namespace mr { + +namespace { + +// GLSL 1.20 throughout, for macOS's legacy OpenGL profile. +const char* kQuadVertex = R"(#version 120 +varying vec2 v_uv; +void main() { + v_uv = gl_MultiTexCoord0.xy; + gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; +} +)"; + +// Downsample with a soft-knee threshold: only bright areas glow. +const char* kBrightFragment = R"(#version 120 +uniform sampler2D u_color; +uniform vec2 u_texel; +uniform float u_threshold; +varying vec2 v_uv; +void main() { + vec3 c = 0.25 * (texture2D(u_color, v_uv + u_texel * vec2(-1.0, -1.0)).rgb + + texture2D(u_color, v_uv + u_texel * vec2(1.0, -1.0)).rgb + + texture2D(u_color, v_uv + u_texel * vec2(-1.0, 1.0)).rgb + + texture2D(u_color, v_uv + u_texel * vec2(1.0, 1.0)).rgb); + float l = max(c.r, max(c.g, c.b)); + float knee = 0.5 * u_threshold + 1e-4; + float soft = clamp(l - u_threshold + knee, 0.0, 2.0 * knee); + soft = soft * soft / (4.0 * knee); + gl_FragColor = vec4(c * (max(soft, l - u_threshold) / max(l, 1e-4)), 1.0); +} +)"; + +// 9-tap Gaussian using bilinear taps. +const char* kBlurFragment = R"(#version 120 +uniform sampler2D u_src; +uniform vec2 u_dir; +varying vec2 v_uv; +void main() { + vec3 c = texture2D(u_src, v_uv).rgb * 0.227027; + c += (texture2D(u_src, v_uv + u_dir * 1.384615).rgb + texture2D(u_src, v_uv - u_dir * 1.384615).rgb) * 0.316216; + c += (texture2D(u_src, v_uv + u_dir * 3.230769).rgb + texture2D(u_src, v_uv - u_dir * 3.230769).rgb) * 0.070270; + gl_FragColor = vec4(c, 1.0); +} +)"; + +// Screen-space ambient occlusion from the depth buffer (normals from depth derivatives). +const char* kAoFragment = R"(#version 120 +uniform sampler2D u_depth; +uniform vec4 u_proj; // projection m00, m11, m20, m21 +uniform vec2 u_projZ; // projection m22, m32 +uniform float u_radius; +uniform float u_strength; +varying vec2 v_uv; +vec3 viewPos(vec2 uv) { + float zn = texture2D(u_depth, uv).r * 2.0 - 1.0; + float z = u_projZ.y / (zn + u_projZ.x); + vec2 ndc = uv * 2.0 - 1.0; + return vec3(z * (ndc.x + u_proj.z) / u_proj.x, z * (ndc.y + u_proj.w) / u_proj.y, z); +} +void main() { + if (texture2D(u_depth, v_uv).r >= 1.0) { gl_FragColor = vec4(1.0); return; } + vec3 p = viewPos(v_uv); + vec3 n = normalize(cross(dFdx(p), dFdy(p))); + if (n.z > 0.0) n = -n; + vec2 r = vec2(u_proj.x, u_proj.y) * (0.5 * u_radius / p.z); + float angle = 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))); + float occlusion = 0.0; + for (int i = 0; i < 12; ++i) { + float t = (float(i) + 0.5) / 12.0; + float a = angle + float(i) * 2.3999632; + vec3 v = viewPos(v_uv + vec2(cos(a), sin(a)) * t * r) - p; + float vv = dot(v, v); + float falloff = max(0.0, 1.0 - vv / (u_radius * u_radius)); + occlusion += falloff * max(0.0, dot(v, n) * inversesqrt(vv + 1e-6) - 0.15); + } + float ao = clamp(1.0 - u_strength * occlusion / 4.0, 0.0, 1.0); + gl_FragColor = vec4(ao, ao, ao, 1.0); +} +)"; + +const char* kCompositeFragment = R"(#version 120 +uniform sampler2D u_color; +uniform sampler2D u_bloom; +uniform sampler2D u_ao; +uniform vec2 u_aoTexel; +uniform int u_bloomOn; +uniform int u_aoOn; +uniform int u_toneMap; +uniform float u_bloomStrength; +uniform float u_exposure; +uniform float u_contrast; +uniform float u_saturation; +uniform vec3 u_tint; +uniform float u_vignette; +varying vec2 v_uv; +vec3 aces(vec3 x) { return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0); } +void main() { + vec4 src = texture2D(u_color, v_uv); + vec3 c = src.rgb; + if (u_aoOn == 1) { + float ao = 0.25 * (texture2D(u_ao, v_uv + u_aoTexel * vec2(-0.75, -0.75)).r + + texture2D(u_ao, v_uv + u_aoTexel * vec2(0.75, -0.75)).r + + texture2D(u_ao, v_uv + u_aoTexel * vec2(-0.75, 0.75)).r + + texture2D(u_ao, v_uv + u_aoTexel * vec2(0.75, 0.75)).r); + c *= ao; + } + if (u_bloomOn == 1) c += texture2D(u_bloom, v_uv).rgb * u_bloomStrength; + c *= u_exposure * u_tint; + // Filmic: ACES fit, scaled so white lands near 0.85 and highlights roll off instead of clipping. + if (u_toneMap == 1) c = pow(aces(max(c, 0.0) * 0.8) / 0.886, vec3(1.15)); + c = (c - 0.5) * u_contrast + 0.5; + float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); + c = mix(vec3(l), c, u_saturation); + vec2 d = v_uv - 0.5; + c *= 1.0 - u_vignette * smoothstep(0.25, 0.75, dot(d, d) * 2.0); + gl_FragColor = vec4(clamp(c, 0.0, 1.0), src.a); +} +)"; + +// FXAA (the compact "console" variant) or a plain copy. +const char* kFinalFragment = R"(#version 120 +uniform sampler2D u_src; +uniform vec2 u_texel; +uniform int u_fxaa; +varying vec2 v_uv; +float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); } +void main() { + vec4 m = texture2D(u_src, v_uv); + if (u_fxaa == 0) { gl_FragColor = m; return; } + float lNW = luma(texture2D(u_src, v_uv + vec2(-1.0, -1.0) * u_texel).rgb); + float lNE = luma(texture2D(u_src, v_uv + vec2(1.0, -1.0) * u_texel).rgb); + float lSW = luma(texture2D(u_src, v_uv + vec2(-1.0, 1.0) * u_texel).rgb); + float lSE = luma(texture2D(u_src, v_uv + vec2(1.0, 1.0) * u_texel).rgb); + float lM = luma(m.rgb); + float lMin = min(lM, min(min(lNW, lNE), min(lSW, lSE))); + float lMax = max(lM, max(max(lNW, lNE), max(lSW, lSE))); + vec2 dir = vec2(-((lNW + lNE) - (lSW + lSE)), (lNW + lSW) - (lNE + lSE)); + float reduce = max((lNW + lNE + lSW + lSE) * 0.03125, 1.0 / 128.0); + float rcp = 1.0 / (min(abs(dir.x), abs(dir.y)) + reduce); + dir = clamp(dir * rcp, vec2(-8.0), vec2(8.0)) * u_texel; + vec3 a = 0.5 * (texture2D(u_src, v_uv - dir / 6.0).rgb + texture2D(u_src, v_uv + dir / 6.0).rgb); + vec3 b = a * 0.5 + 0.25 * (texture2D(u_src, v_uv - dir * 0.5).rgb + texture2D(u_src, v_uv + dir * 0.5).rgb); + float lB = luma(b); + gl_FragColor = vec4((lB < lMin || lB > lMax) ? a : b, m.a); +} +)"; + +osg::ref_ptr makeTexture(GLint internalFormat, GLenum format, GLenum type, bool linear) { + osg::ref_ptr t = new osg::Texture2D; + t->setInternalFormat(internalFormat); + t->setSourceFormat(format); + t->setSourceType(type); + const osg::Texture::FilterMode f = linear ? osg::Texture::LINEAR : osg::Texture::NEAREST; + t->setFilter(osg::Texture::MIN_FILTER, f); + t->setFilter(osg::Texture::MAG_FILTER, f); + t->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); + t->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); + t->setResizeNonPowerOfTwoHint(false); + t->setTextureSize(4, 4); + return t; +} + +// A pass that draws one fullscreen quad with `fragment` into `target` (or into the parent camera). +osg::ref_ptr makePass(const char* name, const char* fragment, osg::Texture2D* target, int order) { + osg::ref_ptr cam = new osg::Camera; + cam->setName(name); + cam->setReferenceFrame(osg::Transform::ABSOLUTE_RF); + cam->setProjectionMatrix(osg::Matrixd::ortho2D(0.0, 1.0, 0.0, 1.0)); + cam->setViewMatrix(osg::Matrixd::identity()); + cam->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR); + cam->setInheritanceMask(cam->getInheritanceMask() & ~osg::CullSettings::CULL_MASK); + cam->setCullMask(~0u); + if (target) { + cam->setRenderOrder(osg::Camera::PRE_RENDER, order); + cam->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); + cam->setClearMask(0); + cam->attach(osg::Camera::COLOR_BUFFER, target); + } else { + cam->setRenderOrder(osg::Camera::NESTED_RENDER); + cam->setClearMask(0); + } + osg::ref_ptr geode = new osg::Geode; + geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0, 0, 0), osg::Vec3(1, 0, 0), osg::Vec3(0, 1, 0))); + geode->setCullingActive(false); + osg::StateSet* ss = geode->getOrCreateStateSet(); + osg::ref_ptr program = new osg::Program; + program->setName(name); + program->addShader(new osg::Shader(osg::Shader::VERTEX, kQuadVertex)); + program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragment)); + ss->setAttributeAndModes(program, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); + ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE); + ss->setMode(GL_BLEND, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE); + ss->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE); + ss->setAttributeAndModes(new osg::Depth(osg::Depth::ALWAYS, 0.0, 1.0, false), + osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); + cam->addChild(geode); + return cam; +} + +void bind(osg::Camera* pass, unsigned unit, osg::Texture2D* tex, const char* sampler) { + osg::StateSet* ss = pass->getChild(0)->getOrCreateStateSet(); + ss->setTextureAttribute(unit, tex, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); + ss->addUniform(new osg::Uniform(sampler, static_cast(unit))); +} + +osg::Uniform* uniform(osg::Camera* pass, osg::Uniform* u) { + pass->getChild(0)->getOrCreateStateSet()->addUniform(u); + return u; +} + +void resizeTarget(osg::Camera* cam, osg::Camera::BufferComponent buffer, osg::Texture2D* tex, int w, int h) { + tex->setTextureSize(w, h); + tex->dirtyTextureObject(); + cam->setViewport(0, 0, w, h); + cam->detach(buffer); + cam->attach(buffer, tex); + cam->setRenderingCache(nullptr); +} + +class ProjectionCallback : public osg::NodeCallback { +public: + void operator()(osg::Node* node, osg::NodeVisitor* nv) override { + if (auto* cv = nv->asCullVisitor()) + if (cv->getProjectionMatrix()) static_cast(node)->setProjection(*cv->getProjectionMatrix()); + traverse(node, nv); + } +}; + +} // namespace + +bool postFxActive(const LookSettings& s) { + return s.bloom || s.ambientOcclusion || s.toneMapping != 0 || s.fxaa || s.exposure != 1.f || s.contrast != 1.f || + s.saturation != 1.f || s.temperature != 0.f || s.vignette > 0.f; +} + +PostChain::PostChain(osg::Node* scene, unsigned viewMask) : scene_(scene) { + setNodeMask(viewMask); + setCullCallback(new ProjectionCallback); + addChild(scene_); +} + +void PostChain::setSupported(bool framebufferObjects, bool floatTextures) { + if (framebufferObjects == supported_ && floatTextures == floatColor_) return; + supported_ = framebufferObjects; + if (!built_) floatColor_ = floatTextures; + refresh(); +} + +void PostChain::apply(const LookSettings& settings) { + settings_ = settings; + refresh(); +} + +void PostChain::setClearColor(const osg::Vec4& color) { + clearColor_ = color; + if (sceneCam_) sceneCam_->setClearColor(color); +} + +void PostChain::setProjection(const osg::Matrixd& p) { + if (!proj_) return; + proj_->set(osg::Vec4f(p(0, 0), p(1, 1), p(2, 0), p(2, 1))); + projZ_->set(osg::Vec2f(p(2, 2), p(3, 2))); +} + +void PostChain::build() { + const GLint colorFormat = floatColor_ ? GL_RGBA16F_ARB : GL_RGBA8; + const GLenum colorType = floatColor_ ? GL_FLOAT : GL_UNSIGNED_BYTE; + color_ = makeTexture(colorFormat, GL_RGBA, colorType, true); + depth_ = makeTexture(GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false); + bloomA_ = makeTexture(colorFormat, GL_RGBA, colorType, true); + bloomB_ = makeTexture(colorFormat, GL_RGBA, colorType, true); + ao_ = makeTexture(GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, true); + ldr_ = makeTexture(GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, true); + + // Inherits the output camera's view, projection and cull mask. + sceneCam_ = new osg::Camera; + sceneCam_->setName("PostSceneCamera"); + sceneCam_->setReferenceFrame(osg::Transform::RELATIVE_RF); + sceneCam_->setRenderOrder(osg::Camera::PRE_RENDER, 0); + sceneCam_->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); + sceneCam_->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR); + sceneCam_->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + sceneCam_->setClearColor(clearColor_); + sceneCam_->attach(osg::Camera::COLOR_BUFFER, color_.get()); + sceneCam_->attach(osg::Camera::DEPTH_BUFFER, depth_.get()); + sceneCam_->addChild(scene_); + + brightCam_ = makePass("PostBright", kBrightFragment, bloomA_.get(), 1); + bind(brightCam_, 0, color_.get(), "u_color"); + brightTexel_ = uniform(brightCam_, new osg::Uniform("u_texel", osg::Vec2f())); + threshold_ = uniform(brightCam_, new osg::Uniform("u_threshold", 0.75f)); + + blurHCam_ = makePass("PostBlurH", kBlurFragment, bloomB_.get(), 2); + bind(blurHCam_, 0, bloomA_.get(), "u_src"); + blurHDir_ = uniform(blurHCam_, new osg::Uniform("u_dir", osg::Vec2f())); + blurVCam_ = makePass("PostBlurV", kBlurFragment, bloomA_.get(), 3); + bind(blurVCam_, 0, bloomB_.get(), "u_src"); + blurVDir_ = uniform(blurVCam_, new osg::Uniform("u_dir", osg::Vec2f())); + + aoCam_ = makePass("PostAo", kAoFragment, ao_.get(), 4); + bind(aoCam_, 0, depth_.get(), "u_depth"); + proj_ = uniform(aoCam_, new osg::Uniform("u_proj", osg::Vec4f(1, 1, 0, 0))); + projZ_ = uniform(aoCam_, new osg::Uniform("u_projZ", osg::Vec2f(-1, -0.2f))); + aoRadius_ = uniform(aoCam_, new osg::Uniform("u_radius", 1.5f)); + aoStrength_ = uniform(aoCam_, new osg::Uniform("u_strength", 1.f)); + + compositeCam_ = makePass("PostComposite", kCompositeFragment, ldr_.get(), 5); + bind(compositeCam_, 0, color_.get(), "u_color"); + bind(compositeCam_, 1, bloomA_.get(), "u_bloom"); + bind(compositeCam_, 2, ao_.get(), "u_ao"); + compositeAoTexel_ = uniform(compositeCam_, new osg::Uniform("u_aoTexel", osg::Vec2f())); + bloomOn_ = uniform(compositeCam_, new osg::Uniform("u_bloomOn", 0)); + aoOn_ = uniform(compositeCam_, new osg::Uniform("u_aoOn", 0)); + toneMap_ = uniform(compositeCam_, new osg::Uniform("u_toneMap", 0)); + bloomStrength_ = uniform(compositeCam_, new osg::Uniform("u_bloomStrength", 0.5f)); + exposure_ = uniform(compositeCam_, new osg::Uniform("u_exposure", 1.f)); + contrast_ = uniform(compositeCam_, new osg::Uniform("u_contrast", 1.f)); + saturation_ = uniform(compositeCam_, new osg::Uniform("u_saturation", 1.f)); + tint_ = uniform(compositeCam_, new osg::Uniform("u_tint", osg::Vec3f(1, 1, 1))); + vignette_ = uniform(compositeCam_, new osg::Uniform("u_vignette", 0.f)); + + finalCam_ = makePass("PostFinal", kFinalFragment, nullptr, 0); + bind(finalCam_, 0, ldr_.get(), "u_src"); + fxaaOn_ = uniform(finalCam_, new osg::Uniform("u_fxaa", 0)); + fxaaTexel_ = uniform(finalCam_, new osg::Uniform("u_texel", osg::Vec2f())); + built_ = true; + const int w = width_, h = height_; + width_ = height_ = 0; + setSize(std::max(w, 1), std::max(h, 1)); +} + +void PostChain::setSize(int width, int height) { + width = std::max(width, 1); + height = std::max(height, 1); + if (width == width_ && height == height_) return; + width_ = width; + height_ = height; + if (!built_) return; + const int bw = std::max(width / 4, 1), bh = std::max(height / 4, 1); + const int aw = std::max(width / 2, 1), ah = std::max(height / 2, 1); + resizeTarget(sceneCam_, osg::Camera::COLOR_BUFFER, color_, width, height); + resizeTarget(sceneCam_, osg::Camera::DEPTH_BUFFER, depth_, width, height); + resizeTarget(brightCam_, osg::Camera::COLOR_BUFFER, bloomA_, bw, bh); + resizeTarget(blurHCam_, osg::Camera::COLOR_BUFFER, bloomB_, bw, bh); + blurVCam_->setViewport(0, 0, bw, bh); + blurVCam_->setRenderingCache(nullptr); + resizeTarget(aoCam_, osg::Camera::COLOR_BUFFER, ao_, aw, ah); + resizeTarget(compositeCam_, osg::Camera::COLOR_BUFFER, ldr_, width, height); + brightTexel_->set(osg::Vec2f(1.f / width, 1.f / height)); + compositeAoTexel_->set(osg::Vec2f(1.f / aw, 1.f / ah)); + fxaaTexel_->set(osg::Vec2f(1.f / width, 1.f / height)); + refresh(); +} + +void PostChain::refresh() { + const bool active = supported_ && postFxActive(settings_); + if (active && !built_) build(); + if (active != active_) { + active_ = active; + removeChildren(0, getNumChildren()); + if (active) { + for (osg::Camera* cam : {sceneCam_.get(), brightCam_.get(), blurHCam_.get(), blurVCam_.get(), aoCam_.get(), + compositeCam_.get(), finalCam_.get()}) + addChild(cam); + } else { + addChild(scene_); + } + } + if (!built_) return; + const LookSettings& s = settings_; + const unsigned bloomMask = s.bloom ? ~0u : 0u; + brightCam_->setNodeMask(bloomMask); + blurHCam_->setNodeMask(bloomMask); + blurVCam_->setNodeMask(bloomMask); + aoCam_->setNodeMask(s.ambientOcclusion ? ~0u : 0u); + const float bw = static_cast(std::max(width_ / 4, 1)), bh = static_cast(std::max(height_ / 4, 1)); + // Blur radius scales with the image height so the glow looks the same at any resolution. + const float spread = s.bloomRadius * std::max(height_, 1) / 540.f; + blurHDir_->set(osg::Vec2f(spread / bw, 0.f)); + blurVDir_->set(osg::Vec2f(0.f, spread / bh)); + threshold_->set(s.bloomThreshold); + bloomOn_->set(s.bloom ? 1 : 0); + bloomStrength_->set(s.bloomStrength); + aoOn_->set(s.ambientOcclusion ? 1 : 0); + aoRadius_->set(s.aoRadius); + aoStrength_->set(s.aoStrength); + toneMap_->set(s.toneMapping); + exposure_->set(s.exposure); + contrast_->set(s.contrast); + saturation_->set(s.saturation); + const float t = std::clamp(s.temperature, -1.f, 1.f); + tint_->set(osg::Vec3f(1.f + 0.12f * t, 1.f + 0.02f * t, 1.f - 0.15f * t)); + vignette_->set(s.vignette); + fxaaOn_->set(s.fxaa ? 1 : 0); +} + +} // namespace mr diff --git a/src/render/PostFx.h b/src/render/PostFx.h new file mode 100644 index 0000000..a9d024a --- /dev/null +++ b/src/render/PostFx.h @@ -0,0 +1,52 @@ +#pragma once + +#include +#include +#include +#include + +#include "scene/LookSettings.h" + +namespace mr { + +// Node-mask bits that pick which output camera draws which post-processing chain. +constexpr unsigned kMainViewMask = 0x10; +constexpr unsigned kPopViewMask = 0x20; +constexpr unsigned kRenderViewMask = 0x40; + +// True when any post-processing effect is switched on. +bool postFxActive(const LookSettings& settings); + +// Post-processing for one output camera. Nested cameras render the scene into textures with the +// output camera's view and projection, then bloom, ambient occlusion, tone mapping, colour grading +// and FXAA are composited onto a fullscreen quad. With every effect off the scene is drawn directly. +class PostChain : public osg::Group { +public: + PostChain(osg::Node* scene, unsigned viewMask); + + void setSupported(bool framebufferObjects, bool floatTextures); + bool supported() const { return supported_; } + void apply(const LookSettings& settings); + void setSize(int width, int height); + void setClearColor(const osg::Vec4& color); + // Called while culling: the projection the scene is drawn with. + void setProjection(const osg::Matrixd& projection); + +private: + void build(); + void refresh(); + + osg::ref_ptr scene_; + LookSettings settings_; + bool supported_ = false, floatColor_ = false, built_ = false, active_ = false; + int width_ = 0, height_ = 0; + osg::Vec4 clearColor_{0.f, 0.f, 0.f, 1.f}; + + osg::ref_ptr color_, depth_, bloomA_, bloomB_, ao_, ldr_; + osg::ref_ptr sceneCam_, brightCam_, blurHCam_, blurVCam_, aoCam_, compositeCam_, finalCam_; + osg::ref_ptr brightTexel_, threshold_, blurHDir_, blurVDir_, aoTexel_, aoRadius_, aoStrength_, + proj_, projZ_, bloomOn_, aoOn_, bloomStrength_, toneMap_, exposure_, contrast_, saturation_, tint_, + vignette_, compositeAoTexel_, fxaaOn_, fxaaTexel_; +}; + +} // namespace mr diff --git a/src/scene/LookSettings.h b/src/scene/LookSettings.h index 2457f04..32c78c1 100644 --- a/src/scene/LookSettings.h +++ b/src/scene/LookSettings.h @@ -25,6 +25,22 @@ struct LookSettings { float rimStrength = 0.f; osg::Vec3f rimColor{1.f, 1.f, 1.f}; + + // Post-processing; with all of it off the scene is drawn directly, at no extra cost. + bool bloom = false; + float bloomStrength = 0.5f; + float bloomThreshold = 0.75f; + float bloomRadius = 1.f; + bool ambientOcclusion = false; + float aoStrength = 1.f; + float aoRadius = 1.5f; // world units; a character is about 20 tall + int toneMapping = 0; // 0 off, 1 filmic + float exposure = 1.f; + float contrast = 1.f; + float saturation = 1.f; + float temperature = 0.f; // -1 cool .. 1 warm + float vignette = 0.f; + bool fxaa = false; }; } // namespace mr diff --git a/src/scene/SceneFile.cpp b/src/scene/SceneFile.cpp index ba2d8f4..9c9974c 100644 --- a/src/scene/SceneFile.cpp +++ b/src/scene/SceneFile.cpp @@ -118,7 +118,21 @@ bool saveScene(const Scene& scene, const std::string& path, std::string& error) {"groundShadow", look.groundShadow}, {"groundShadowOpacity", look.groundShadowOpacity}, {"rimStrength", look.rimStrength}, - {"rimColor", vec(look.rimColor)}}; + {"rimColor", vec(look.rimColor)}, + {"bloom", look.bloom}, + {"bloomStrength", look.bloomStrength}, + {"bloomThreshold", look.bloomThreshold}, + {"bloomRadius", look.bloomRadius}, + {"ambientOcclusion", look.ambientOcclusion}, + {"aoStrength", look.aoStrength}, + {"aoRadius", look.aoRadius}, + {"toneMapping", look.toneMapping == 1 ? "filmic" : "off"}, + {"exposure", look.exposure}, + {"contrast", look.contrast}, + {"saturation", look.saturation}, + {"temperature", look.temperature}, + {"vignette", look.vignette}, + {"fxaa", look.fxaa}}; j["render"] = {{"width", scene.renderWidth}, {"height", scene.renderHeight}, {"transparent", scene.renderTransparent}, @@ -233,6 +247,20 @@ bool loadScene(const std::string& path, Scene& scene, std::string& error) { read(*it, "groundShadowOpacity", look.groundShadowOpacity); read(*it, "rimStrength", look.rimStrength); readVec(*it, "rimColor", look.rimColor); + read(*it, "bloom", look.bloom); + read(*it, "bloomStrength", look.bloomStrength); + read(*it, "bloomThreshold", look.bloomThreshold); + read(*it, "bloomRadius", look.bloomRadius); + read(*it, "ambientOcclusion", look.ambientOcclusion); + read(*it, "aoStrength", look.aoStrength); + read(*it, "aoRadius", look.aoRadius); + look.toneMapping = it->value("toneMapping", std::string("off")) == "filmic" ? 1 : 0; + read(*it, "exposure", look.exposure); + read(*it, "contrast", look.contrast); + read(*it, "saturation", look.saturation); + read(*it, "temperature", look.temperature); + read(*it, "vignette", look.vignette); + read(*it, "fxaa", look.fxaa); } if (auto it = j.find("render"); it != j.end() && it->is_object()) { read(*it, "width", scene.renderWidth); diff --git a/tests/test_main.cpp b/tests/test_main.cpp index 040bbd3..6498514 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -377,6 +377,10 @@ void testSceneFile() { scene.look.shadows = false; scene.look.rimStrength = 0.5f; scene.look.rimColor = osg::Vec3f(1.f, 0.5f, 0.25f); + scene.look.bloom = true; + scene.look.ambientOcclusion = true; + scene.look.toneMapping = 1; + scene.look.vignette = 0.3f; scene.renderWidth = 1280; const std::string file = mr::pathToUtf8(dir / "project" / "test.mrscene"); std::string error; @@ -405,6 +409,8 @@ void testSceneFile() { CHECK(loaded.look.shading == 2 && loaded.renderWidth == 1280); CHECK(!loaded.look.shadows && loaded.look.outlines && std::abs(loaded.look.rimStrength - 0.5f) < 1e-6f); CHECK(std::abs(loaded.look.rimColor.y() - 0.5f) < 1e-6f); + CHECK(loaded.look.bloom && loaded.look.ambientOcclusion && loaded.look.toneMapping == 1 && !loaded.look.fxaa); + CHECK(std::abs(loaded.look.vignette - 0.3f) < 1e-6f); CHECK(!loaded.audioPath.empty() && loaded.cameraMotionPath.empty()); const std::string bad = mr::pathToUtf8(dir / "bad.mrscene");