From 14ce96ee896989da27fd4ea809ca19fae4f54576 Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Tue, 17 Nov 2026 10:42:35 -0500 Subject: [PATCH] Occlusion culling in the G-buffer pass (Hi-Z, two phase, on the GPU) Meshes that other meshes hide are no longer drawn. Phase 0 draws what was visible last frame, a depth pyramid is built from that depth, phase 1 tests every mesh in view against it and a second render pass draws the rest. The pyramid uses this frame's camera, so nothing pops. Adds the --occlusion-culling run setting, a GPU Options checkbox and an Occluded count, a CPU twin of the test (OcclusionTest.h) with a randomized no-visible-mesh-hidden test, and Docs/occlusion-culling.md. Closes #252 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017NN37QrCqnwEJe9CqoCjqA --- AGENTS.md | 9 +- Assets/Shaders/Occlusion/cull.comp | 130 +++++ Assets/Shaders/Occlusion/hiz_downsample.comp | 47 ++ Docs/agent-guide.md | 1 + Docs/architecture-overview.md | 2 +- Docs/occlusion-culling.md | 55 ++ Docs/threading-model.md | 2 +- Docs/time-and-ticks.md | 1 + FlingEngine/Application/src/Engine.cpp | 1 + FlingEngine/Core/inc/LaunchOptions.h | 6 + FlingEngine/Core/inc/RunSettings.h | 19 +- FlingEngine/Core/src/LaunchOptions.cpp | 4 +- FlingEngine/Core/src/RunSettings.cpp | 13 +- FlingEngine/Editor/src/BaseEditor.cpp | 11 +- FlingEngine/Engine/inc/RunControls.h | 6 + FlingEngine/Engine/src/RunControls.cpp | 10 + FlingEngine/Graphics/CMakeLists.txt | 2 + FlingEngine/Graphics/inc/MeshCuller.h | 6 + FlingEngine/Graphics/inc/OcclusionTest.h | 96 +++ FlingEngine/Graphics/inc/VulkanApp.h | 7 + FlingEngine/Graphics/src/CommandBuffer.cpp | 12 + FlingEngine/Graphics/src/CommandBuffer.h | 3 + FlingEngine/Graphics/src/FrameBuffer.cpp | 139 +++-- FlingEngine/Graphics/src/FrameBuffer.h | 15 + FlingEngine/Graphics/src/OcclusionCuller.cpp | 545 ++++++++++++++++++ FlingEngine/Graphics/src/OcclusionCuller.h | 143 +++++ FlingEngine/Graphics/src/OcclusionTest.cpp | 140 +++++ FlingEngine/Graphics/src/OffscreenSubpass.cpp | 154 ++++- FlingEngine/Graphics/src/OffscreenSubpass.h | 42 +- FlingEngine/Graphics/src/VulkanApp.cpp | 14 +- FlingEngine/Graphics/src/VulkanFunctions.inl | 3 + FlingTests/Core/RunSettingsTests.cpp | 34 +- FlingTests/Engine/RunControlsTests.cpp | 5 + FlingTests/Graphics/OcclusionCullingTests.cpp | 237 ++++++++ .../Resources/RunSettingsConfigTests.cpp | 8 +- 35 files changed, 1831 insertions(+), 91 deletions(-) create mode 100644 Assets/Shaders/Occlusion/cull.comp create mode 100644 Assets/Shaders/Occlusion/hiz_downsample.comp create mode 100644 Docs/occlusion-culling.md create mode 100644 FlingEngine/Graphics/inc/OcclusionTest.h create mode 100644 FlingEngine/Graphics/src/OcclusionCuller.cpp create mode 100644 FlingEngine/Graphics/src/OcclusionCuller.h create mode 100644 FlingEngine/Graphics/src/OcclusionTest.cpp create mode 100644 FlingTests/Graphics/OcclusionCullingTests.cpp diff --git a/AGENTS.md b/AGENTS.md index 6d371f9c..49075409 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,9 +46,10 @@ platform setup (Vulkan SDK, GLFW, etc.). main thread's frames capped at the monitor's refresh rate (no cap headless). `--exec direct|inline|threaded`, `--sim-hz N`, `--max-fps N` (0: no cap), `--vsync on|off` (on by default), `--interpolation on|off` (on by - default) and `--frustum-culling on|off` (on by default) override, as do - `[Engine] Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation` and - `FrustumCulling` in + default), `--frustum-culling on|off` (on by default) and + `--occlusion-culling on|off` (on by default) override, as do + `[Engine] Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation`, + `FrustumCulling` and `OcclusionCulling` in `Config/EngineConf.ini`. A test that depends on a mode or a rate sets it. The startup log line `Run settings: ...` says each value and where it came from. The editor's GPU Options window (menu Windows; drawn in `--play` too) changes @@ -112,6 +113,8 @@ platform setup (Vulkan SDK, GLFW, etc.). [`Docs/time-and-ticks.md`](Docs/time-and-ticks.md). The game thread, the published copy, exec modes and the determinism tests: [`Docs/threading-model.md`](Docs/threading-model.md). +- Occlusion culling in the G-buffer pass (a two phase Hi-Z pass on the GPU, its CPU twin + and tests): [`Docs/occlusion-culling.md`](Docs/occlusion-culling.md). - One self-contained guide to all of the above, written to be loaded as context by an AI coding agent: [`Docs/agent-guide.md`](Docs/agent-guide.md). The handoff for the original Fling authors (what changed since the first commit, diff --git a/Assets/Shaders/Occlusion/cull.comp b/Assets/Shaders/Occlusion/cull.comp new file mode 100644 index 00000000..ff803a95 --- /dev/null +++ b/Assets/Shaders/Occlusion/cull.comp @@ -0,0 +1,130 @@ +#version 450 + +// Occlusion culling of the G-buffer pass, two phases (see OcclusionCuller.h). +// Phase 0: the meshes that were visible last frame and are in the view get the first draw. +// Phase 1: every mesh in the view is tested against the depth pyramid of that first draw. A +// mesh that is not hidden and was not drawn yet gets the second draw. +// The test is the same as Occlusion::ProjectBounds and Occlusion::IsOccluded (OcclusionTest.cpp). + +layout(local_size_x = 64) in; + +struct Slot +{ + mat4 World; + vec4 BoundsMin; + vec4 BoundsMax; + // x: index count (0: nothing to draw), y: bit 0 in the view, bit 1 has bounds + uvec4 Info; +}; + +struct DrawCmd +{ + uint indexCount; + uint instanceCount; + uint firstIndex; + int vertexOffset; + uint firstInstance; +}; + +layout(std140, set = 0, binding = 0) uniform Params +{ + mat4 ViewProjection; + // x: slot count + uvec4 Counts; +} u; + +layout(std430, set = 0, binding = 1) readonly buffer Slots { Slot slots[]; }; +layout(std430, set = 0, binding = 2) writeonly buffer Draw1 { DrawCmd draw1[]; }; +layout(std430, set = 0, binding = 3) writeonly buffer Draw2 { DrawCmd draw2[]; }; +layout(std430, set = 0, binding = 4) buffer Visible { uint visible[]; }; +layout(std430, set = 0, binding = 5) buffer Stats { uint occluded; } stats; +layout(set = 0, binding = 6) uniform sampler2D uPyramid; + +layout(push_constant) uniform Phase { uint Value; } phase; + +const float DepthBias = 1.0e-5; + +bool IsOccluded(const Slot slot) +{ + const mat4 mvp = u.ViewProjection * slot.World; + vec2 uvMin = vec2(1.0e30); + vec2 uvMax = vec2(-1.0e30); + float nearest = 1.0e30; + for (uint i = 0; i < 8; ++i) + { + const vec3 corner = vec3(((i & 1u) != 0u) ? slot.BoundsMax.x : slot.BoundsMin.x, + ((i & 2u) != 0u) ? slot.BoundsMax.y : slot.BoundsMin.y, + ((i & 4u) != 0u) ? slot.BoundsMax.z : slot.BoundsMin.z); + const vec4 clip = mvp * vec4(corner, 1.0); + if (clip.w <= 1.0e-4) + { + return false; + } + const vec2 uv = clip.xy / clip.w * 0.5 + 0.5; + uvMin = min(uvMin, uv); + uvMax = max(uvMax, uv); + nearest = min(nearest, clip.z / clip.w); + } + uvMin = clamp(uvMin, vec2(0.0), vec2(1.0)); + uvMax = clamp(uvMax, vec2(0.0), vec2(1.0)); + nearest = max(nearest, 0.0); + + const ivec2 size = textureSize(uPyramid, 0); + const ivec2 maxTexel = size - 1; + const ivec2 lo = clamp(ivec2(floor(uvMin * vec2(size))), ivec2(0), maxTexel); + const ivec2 hi = clamp(ivec2(floor(uvMax * vec2(size))), ivec2(0), maxTexel); + + const int span = max(hi.x - lo.x, hi.y - lo.y) + 1; + const int levels = textureQueryLevels(uPyramid); + int level = 0; + while ((1 << level) < span && level + 1 < levels) + { + ++level; + } + + const ivec2 levelMax = textureSize(uPyramid, level) - 1; + const ivec2 a = min(lo >> level, levelMax); + const ivec2 b = min(hi >> level, levelMax); + float farthest = 0.0; + for (int y = a.y; y <= b.y; ++y) + { + for (int x = a.x; x <= b.x; ++x) + { + farthest = max(farthest, texelFetch(uPyramid, ivec2(x, y), level).r); + } + } + return nearest > farthest + DepthBias; +} + +void main() +{ + const uint s = gl_GlobalInvocationID.x; + if (s >= u.Counts.x) + { + return; + } + + const Slot slot = slots[s]; + const uint indexCount = slot.Info.x; + const bool inView = (slot.Info.y & 1u) != 0u && indexCount != 0u; + const bool drawnFirst = inView && visible[s] != 0u; + + if (phase.Value == 0u) + { + draw1[s] = DrawCmd(indexCount, drawnFirst ? 1u : 0u, 0u, 0, 0u); + return; + } + + bool hidden = false; + if (inView && (slot.Info.y & 2u) != 0u) + { + hidden = IsOccluded(slot); + } + const bool shown = inView && !hidden; + draw2[s] = DrawCmd(indexCount, (shown && !drawnFirst) ? 1u : 0u, 0u, 0, 0u); + visible[s] = shown ? 1u : 0u; + if (inView && hidden) + { + atomicAdd(stats.occluded, 1u); + } +} diff --git a/Assets/Shaders/Occlusion/hiz_downsample.comp b/Assets/Shaders/Occlusion/hiz_downsample.comp new file mode 100644 index 00000000..36876dc0 --- /dev/null +++ b/Assets/Shaders/Occlusion/hiz_downsample.comp @@ -0,0 +1,47 @@ +#version 450 + +// One level of the depth pyramid. Level 0 copies the depth image. Each later level holds the +// farthest depth of the texels below it. Keep in step with DepthPyramid::Build (OcclusionTest.cpp). + +layout(local_size_x = 8, local_size_y = 8) in; + +layout(set = 0, binding = 0) uniform sampler2D uSrc; +layout(set = 0, binding = 1, r32f) uniform writeonly image2D uDst; + +layout(push_constant) uniform Params +{ + ivec2 SrcSize; + ivec2 DstSize; + int Copy; +} pc; + +void main() +{ + const ivec2 d = ivec2(gl_GlobalInvocationID.xy); + if (d.x >= pc.DstSize.x || d.y >= pc.DstSize.y) + { + return; + } + + if (pc.Copy != 0) + { + imageStore(uDst, d, vec4(texelFetch(uSrc, d, 0).r)); + return; + } + + const ivec2 lo = d * 2; + ivec2 hi = lo + 1; + // The last row or column also covers the extra source row or column of an odd size + if (d.x == pc.DstSize.x - 1) hi.x = pc.SrcSize.x - 1; + if (d.y == pc.DstSize.y - 1) hi.y = pc.SrcSize.y - 1; + + float farthest = 0.0; + for (int y = lo.y; y <= hi.y; ++y) + { + for (int x = lo.x; x <= hi.x; ++x) + { + farthest = max(farthest, texelFetch(uSrc, ivec2(x, y), 0).r); + } + } + imageStore(uDst, d, vec4(farthest)); +} diff --git a/Docs/agent-guide.md b/Docs/agent-guide.md index ffd57e69..8c0837ab 100644 --- a/Docs/agent-guide.md +++ b/Docs/agent-guide.md @@ -769,6 +769,7 @@ flag or key. The startup line `Run settings: ...` names each value and its sourc | VSync | `--vsync on\|off` | `VSync` | on | GPU Options (swap chain rebuilt) | | Interpolation | `--interpolation on\|off` | `Interpolation` | on | GPU Options | | Frustum culling | `--frustum-culling on\|off` | `FrustumCulling` | on | GPU Options | +| Occlusion culling | `--occlusion-culling on\|off` | `OcclusionCulling` | on | GPU Options | | Thread jitter (tests) | `--thread-jitter S:U` (threaded only; an error otherwise) | none | off | no | Other flags: `--null-render` (no window or GPU, virtual clock), `--offscreen` (render diff --git a/Docs/architecture-overview.md b/Docs/architecture-overview.md index 2250baf3..c1db1f92 100644 --- a/Docs/architecture-overview.md +++ b/Docs/architecture-overview.md @@ -385,7 +385,7 @@ must be started from there. With Ninja the program is | Dump ticks | `build\Sandbox\bin\Sandbox.exe --null-render --unattended --seed 1 --frames 120 --replay-input Sandbox/Tests/Input/look_camera_cuts.input.jsonl --dump-ticks ticks.txt` (a recording replays only at its rate: `look_camera_cuts_60hz.input.jsonl` needs `--sim-hz 60`) | | Windowed demo (look camera; threaded, 30 Hz, frames capped at the monitor's refresh rate) | `build\Sandbox\bin\Sandbox.exe --play` | | The same, unattended (the exit line has the average frame time) | `build\Sandbox\bin\Sandbox.exe --play --unattended --frames 300` (it runs until tick 300 is shown, so for about 10 s at 30 Hz) | -| Other settings | `--exec direct` or `inline`, `--sim-hz N` (1 to 1000), `--max-fps N` (0: no cap), `--vsync on\|off`, `--interpolation on\|off`, `--frustum-culling on\|off`; or the same keys in `[Engine]` of `Config/EngineConf.ini` (`Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation`, `FrustumCulling`) | +| Other settings | `--exec direct` or `inline`, `--sim-hz N` (1 to 1000), `--max-fps N` (0: no cap), `--vsync on\|off`, `--interpolation on\|off`, `--frustum-culling on\|off`, `--occlusion-culling on\|off`; or the same keys in `[Engine]` of `Config/EngineConf.ini` (`Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation`, `FrustumCulling`, `OcclusionCulling`) | | Change them while the game runs | The editor UI is drawn in `--play` too, and the Sandbox opens the "GPU Options" window at start in `--play` (menu Windows closes and opens it): VSync (On or Off, with the present mode in use), frame cap, simulation rate, render interpolation, frustum culling (with the meshes drawn and culled), with what the frame limiter does and the measured rates. Press M first if the cursor is hidden | ## 11. Where to read more diff --git a/Docs/occlusion-culling.md b/Docs/occlusion-culling.md new file mode 100644 index 00000000..45bdda42 --- /dev/null +++ b/Docs/occlusion-culling.md @@ -0,0 +1,55 @@ +# Occlusion culling + +The G-buffer pass does not draw a mesh that other meshes hide. It runs on the GPU, after the +frustum test ([`MeshCuller`](../FlingEngine/Graphics/inc/MeshCuller.h)), and it only removes +draws, so the picture is the same. Issue #252. + +## Settings + +| How | What | +| --- | --- | +| `--occlusion-culling on|off` | Run setting. On by default | +| `[Engine] OcclusionCulling` | The same, in `Config/EngineConf.ini` | +| Editor, GPU Options | A checkbox, and the count of hidden meshes (the value of the previous frame) | + +The pass turns itself off when the compute shaders did not load, or the device cannot sample the +depth format or store `R32_SFLOAT` images. It works on a software driver (llvmpipe). + +## How it works + +Two phases in one command buffer (`OcclusionCuller`, `Assets/Shaders/Occlusion/`): + +1. **Phase 0** (compute). Each slot that is in the view and was visible in the last frame gets an + indirect draw (`Draw1`). +2. The **first render pass** draws `Draw1` and clears the images as before. +3. A **depth pyramid** (`R32_SFLOAT`, each texel is the farthest depth below it) is built from + that depth (`hiz_downsample.comp`). +4. **Phase 1** (compute). Every slot in the view is tested against the pyramid. A slot that is not + hidden and was not drawn in step 2 gets a draw in `Draw2`. The slot's visible flag is saved for + the next frame, and the hidden slots are counted. +5. The **second render pass** (`FrameBuffer::GetLoadRenderPassHandle`, load ops, same frame buffer) + draws `Draw2`. + +The pyramid comes from this frame's depth with this frame's camera and meshes, so a mesh is never +hidden by an old picture: no popping and no reprojection. A mesh that comes into view is not +visible in the last frame, so it is tested in phase 1 and drawn in the second pass. The first +frame (or a new buffer) draws everything in the second pass. + +The test must never hide a visible mesh. It uses the nearest depth of the mesh's bounding box, +the farthest depth under the box's screen rectangle (a pyramid level that covers it with 2 x 2 +texels), and a small bias (`Occlusion::DepthBias`). A box that reaches the camera's plane is never +hidden. Both phases write every slot's command, so the recorded draw calls do not change from frame +to frame. A resize makes the pyramid again (`OffscreenSubpass::OnSwapchainResized`). + +## The CPU twin + +`Occlusion::ProjectBounds`, `Occlusion::IsOccluded` and `DepthPyramid` (`OcclusionTest.h`) do the +same as the shaders. `FlingTests/Graphics/OcclusionCullingTests.cpp` runs them without a window, +including a randomized scene (rotated boxes, moving camera) that checks no visible box is hidden. +Keep the shaders and the CPU code in step. + +## Check it + +`Sandbox --offscreen --unattended --frames 60 --seed 1 --screenshot a.png --occlusion-culling on` +and the same with `off` give the same picture. Set `EnableValidationLayers=true` in +`Config/EngineConf.ini` to run with the validation layers. diff --git a/Docs/threading-model.md b/Docs/threading-model.md index d3b730a9..93be5abc 100644 --- a/Docs/threading-model.md +++ b/Docs/threading-model.md @@ -224,7 +224,7 @@ The camera is only final in `VulkanApp::Update`, after the frame systems ran, so the snapshot's blend and matrix work is not culled; a test against the last frame's camera would not be conservative. Lights are not culled (the deferred lighting pass is full screen), and there is no shadow pass. `--frustum-culling -on|off`, `[Engine] FrustumCulling` and the GPU Options window, which also shows +on|off`, `[Engine] FrustumCulling` (and `--occlusion-culling on|off`, `[Engine] OcclusionCulling`) and the GPU Options window, which also shows the meshes drawn and culled in the last frame. Tests: `GraphicsTests "[culling]"` (`FrustumCullingTests.cpp`). diff --git a/Docs/time-and-ticks.md b/Docs/time-and-ticks.md index 88a80c48..20a81b06 100644 --- a/Docs/time-and-ticks.md +++ b/Docs/time-and-ticks.md @@ -75,6 +75,7 @@ outside `--exec threaded` is an error. | VSync | `--vsync on\|off` | `VSync` | on | GPU Options, the swap chain is made again | | Interpolation | `--interpolation on\|off` | `Interpolation` | on | GPU Options, from the next frame | | Frustum culling | `--frustum-culling on\|off` | `FrustumCulling` | on | GPU Options, from the next frame | +| Occlusion culling | `--occlusion-culling on\|off` | `OcclusionCulling` | on | GPU Options, from the next frame | | Thread jitter (tests) | `--thread-jitter S:U` (`--exec threaded` only) | none | off | no | `RunSettings` does not change after startup. The live values are in diff --git a/FlingEngine/Application/src/Engine.cpp b/FlingEngine/Application/src/Engine.cpp index 56336fdd..d3ca1601 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -705,6 +705,7 @@ namespace Fling // the swap chain again after this frame's present. VulkanApp::Get().SetVSync(m_Controls->VSync()); VulkanApp::Get().SetFrustumCulling(m_Controls->FrustumCulling()); + VulkanApp::Get().SetOcclusionCulling(m_Controls->OcclusionCulling()); VulkanApp::Get().Update(t_DeltaTime, m_World->GetPresentedStorage()); // Offscreen there is no window: no focus, no monitor, and no frame cap (headless) diff --git a/FlingEngine/Core/inc/LaunchOptions.h b/FlingEngine/Core/inc/LaunchOptions.h index 378500ad..4e80a6ce 100644 --- a/FlingEngine/Core/inc/LaunchOptions.h +++ b/FlingEngine/Core/inc/LaunchOptions.h @@ -78,6 +78,9 @@ namespace Fling * --frustum-culling on|off * Skip the meshes outside the camera's view (on) or draw every mesh * (off). Overrides [Engine] FrustumCulling + * --occlusion-culling on|off + * Skip the meshes that other meshes hide (on) or draw every mesh + * (off). Overrides [Engine] OcclusionCulling * --thread-jitter S:U --exec threaded only: sleep a random 0..U microseconds (seed S) before each wake * and after each publish on the game thread, and before each frame */ @@ -160,6 +163,9 @@ namespace Fling /** --frustum-culling on or off. Empty: not on the command line. */ std::optional FrustumCulling; + /** --occlusion-culling on or off. Empty: not on the command line. */ + std::optional OcclusionCulling; + /** --thread-jitter: the seed and the longest sleep in microseconds. 0 microseconds means off. */ uint32 JitterSeed = 0; uint32 JitterMaxMicroseconds = 0; diff --git a/FlingEngine/Core/inc/RunSettings.h b/FlingEngine/Core/inc/RunSettings.h index 26aaf186..58235e3e 100644 --- a/FlingEngine/Core/inc/RunSettings.h +++ b/FlingEngine/Core/inc/RunSettings.h @@ -45,6 +45,7 @@ namespace Fling static constexpr const char* VSyncKey = "VSync"; static constexpr const char* InterpolationKey = "Interpolation"; static constexpr const char* FrustumCullingKey = "FrustumCulling"; + static constexpr const char* OcclusionCullingKey = "OcclusionCulling"; String Exec; String SimHz; @@ -52,6 +53,7 @@ namespace Fling String VSync; String Interpolation; String FrustumCulling; + String OcclusionCulling; /** * Each key's text from t_GetKey, which returns the text of one [Engine] key, or empty @@ -65,7 +67,8 @@ namespace Fling .MaxFps = t_GetKey(MaxFpsKey), .VSync = t_GetKey(VSyncKey), .Interpolation = t_GetKey(InterpolationKey), - .FrustumCulling = t_GetKey(FrustumCullingKey)}; + .FrustumCulling = t_GetKey(FrustumCullingKey), + .OcclusionCulling = t_GetKey(OcclusionCullingKey)}; } }; @@ -83,11 +86,12 @@ namespace Fling * | VSync | [Engine] VSync | --vsync | on | * | Interpolation | [Engine] Interpolation | --interpolation | on | * | FrustumCulling | [Engine] FrustumCulling | --frustum-culling | on | + * | OcclusionCulling | [Engine] OcclusionCulling | --occlusion-culling | on | * * The values here do not change after startup. The GPU Options window changes VSync, the - * frame cap, the simulation rate, interpolation and frustum culling while the game runs; RunControls holds - * those live values, starting from these. Edit mode in the editor always runs on one - * thread, whatever Exec says. + * frame cap, the simulation rate, interpolation, frustum culling and occlusion culling while the game runs; + * RunControls holds those live values, starting from these. Edit mode in the editor always runs on one thread, + * whatever Exec says. */ struct RunSettings { @@ -128,6 +132,13 @@ namespace Fling bool FrustumCulling = true; SettingSource FrustumCullingSource = SettingSource::Default; + /** + * The renderer does not draw a mesh that other meshes hide from the camera (the GPU + * occlusion test in Graphics). Presentation only: the simulation never reads it. + */ + bool OcclusionCulling = true; + SettingSource OcclusionCullingSource = SettingSource::Default; + /** The refresh rate of the window's monitor at startup (ResolveFrameCap). Empty when not known, and headless. */ std::optional MonitorHz; diff --git a/FlingEngine/Core/src/LaunchOptions.cpp b/FlingEngine/Core/src/LaunchOptions.cpp index f0517fe1..24e266e9 100644 --- a/FlingEngine/Core/src/LaunchOptions.cpp +++ b/FlingEngine/Core/src/LaunchOptions.cpp @@ -38,6 +38,7 @@ namespace Fling constexpr StringView VSyncFlag = "vsync"; constexpr StringView InterpolationFlag = "interpolation"; constexpr StringView FrustumCullingFlag = "frustum-culling"; + constexpr StringView OcclusionCullingFlag = "occlusion-culling"; constexpr StringView ThreadJitterFlag = "thread-jitter"; /** * Flags that are refused with the name of the flag that does their job, so a script @@ -394,7 +395,8 @@ namespace Fling !ReadOptionalUint32(t_CmdLine, MaxFpsFlag, t_Out.MaxFps, t_OutError) || !ReadOptionalOnOff(t_CmdLine, VSyncFlag, t_Out.VSync, t_OutError) || !ReadOptionalOnOff(t_CmdLine, InterpolationFlag, t_Out.Interpolation, t_OutError) || - !ReadOptionalOnOff(t_CmdLine, FrustumCullingFlag, t_Out.FrustumCulling, t_OutError)) + !ReadOptionalOnOff(t_CmdLine, FrustumCullingFlag, t_Out.FrustumCulling, t_OutError) || + !ReadOptionalOnOff(t_CmdLine, OcclusionCullingFlag, t_Out.OcclusionCulling, t_OutError)) { return false; } diff --git a/FlingEngine/Core/src/RunSettings.cpp b/FlingEngine/Core/src/RunSettings.cpp index d55c5132..4c44ca06 100644 --- a/FlingEngine/Core/src/RunSettings.cpp +++ b/FlingEngine/Core/src/RunSettings.cpp @@ -196,6 +196,12 @@ namespace Fling Keys::FrustumCullingKey, t_Out.FrustumCulling, t_Out.FrustumCullingSource, + t_OutError) || + !PickOnOff(t_Options.OcclusionCulling, + t_Config.OcclusionCulling, + Keys::OcclusionCullingKey, + t_Out.OcclusionCulling, + t_Out.OcclusionCullingSource, t_OutError)) { return false; @@ -216,6 +222,10 @@ namespace Fling { t_Out.Ignored.push_back("--frustum-culling does nothing with --null-render: nothing is drawn"); } + if (t_Options.NullRender && t_Options.OcclusionCulling) + { + t_Out.Ignored.push_back("--occlusion-culling does nothing with --null-render: nothing is drawn"); + } return true; } @@ -264,7 +274,8 @@ namespace Fling ExecModeName(Exec) + " (" + SettingSourceName(ExecSource) + "), frame cap " + Cap + " (" + CapSource + "), vsync " + OnOffName(VSync) + " (" + SettingSourceName(VSyncSource) + "), interpolation " + OnOffName(Interpolation) + " (" + SettingSourceName(InterpolationSource) + "), frustum culling " + - OnOffName(FrustumCulling) + " (" + SettingSourceName(FrustumCullingSource) + ")"; + OnOffName(FrustumCulling) + " (" + SettingSourceName(FrustumCullingSource) + "), occlusion culling " + + OnOffName(OcclusionCulling) + " (" + SettingSourceName(OcclusionCullingSource) + ")"; } uint32 LimiterFps(const uint32 t_MaxFps, diff --git a/FlingEngine/Editor/src/BaseEditor.cpp b/FlingEngine/Editor/src/BaseEditor.cpp index d965dd78..ea2a7a19 100644 --- a/FlingEngine/Editor/src/BaseEditor.cpp +++ b/FlingEngine/Editor/src/BaseEditor.cpp @@ -455,8 +455,17 @@ namespace Fling m_ControlsError.clear(); Controls.SetFrustumCulling(bFrustumCulling); } + bool bOcclusionCulling = Controls.OcclusionCulling(); + if (ImGui::Checkbox("Occlusion culling", &bOcclusionCulling)) + { + m_ControlsError.clear(); + Controls.SetOcclusionCulling(bOcclusionCulling); + } const CullStats Culled = VulkanApp::Get().GetCullStats(); - ImGui::TextDisabled("Last frame: %u meshes drawn, %u outside the view", Culled.Drawn, Culled.Culled); + ImGui::TextDisabled("Last frame: %u meshes drawn, %u outside the view, %u occluded (hidden by other meshes)", + Culled.Drawn, + Culled.Culled, + Culled.Occluded); if (!m_ControlsError.empty()) { diff --git a/FlingEngine/Engine/inc/RunControls.h b/FlingEngine/Engine/inc/RunControls.h index e3c655ec..9d6b8cc5 100644 --- a/FlingEngine/Engine/inc/RunControls.h +++ b/FlingEngine/Engine/inc/RunControls.h @@ -45,6 +45,7 @@ namespace Fling * - MaxFps: Engine::Present puts LimiterFps into the FrameLimiter, on the next frame. * - Interpolation: World::SetInterpolation, which holds it, on the next frame. * - FrustumCulling: Engine::Present gives it to VulkanApp::SetFrustumCulling, on the next frame. + * - OcclusionCulling: Engine::Present gives it to VulkanApp::SetOcclusionCulling, on the next frame. * - SimHz: World::RequestSimHz, a SetRate clock command applied between two ticks, at the * next wake. The world holds the rate. * @@ -84,6 +85,10 @@ namespace Fling bool FrustumCulling() const { return m_FrustumCulling; } void SetFrustumCulling(bool t_On); + /** Occlusion culling in the renderer (RunSettings::OcclusionCulling). */ + bool OcclusionCulling() const { return m_OcclusionCulling; } + void SetOcclusionCulling(bool t_On); + /** * Ask for a new simulation rate (World::RequestSimHz, applied at the next tick * boundary). False, with the reason, for a rate that is not from 1 to 1000, or while @@ -140,6 +145,7 @@ namespace Fling bool m_VSync = true; bool m_FrustumCulling = true; + bool m_OcclusionCulling = true; uint32 m_MaxFps = 0; /** True while the cap is the monitor's refresh rate and no one has set it. */ diff --git a/FlingEngine/Engine/src/RunControls.cpp b/FlingEngine/Engine/src/RunControls.cpp index 56749634..d1e207a7 100644 --- a/FlingEngine/Engine/src/RunControls.cpp +++ b/FlingEngine/Engine/src/RunControls.cpp @@ -32,6 +32,7 @@ namespace Fling m_InputTickRate(t_Startup.SimHz), m_VSync(t_Startup.VSync), m_FrustumCulling(t_Startup.FrustumCulling), + m_OcclusionCulling(t_Startup.OcclusionCulling), m_MaxFps(t_Startup.MaxFps), m_MaxFpsFollowsMonitor(t_Startup.MaxFpsSource == SettingSource::Monitor), m_MonitorHz(t_Startup.MonitorHz) @@ -56,6 +57,15 @@ namespace Fling } } + void RunControls::SetOcclusionCulling(const bool t_On) + { + if (t_On != m_OcclusionCulling) + { + m_OcclusionCulling = t_On; + F_LOG_TRACE("Occlusion culling {}", t_On ? "on" : "off"); + } + } + bool RunControls::SetMaxFps(const uint32 t_Fps, String& t_OutError) { t_OutError.clear(); diff --git a/FlingEngine/Graphics/CMakeLists.txt b/FlingEngine/Graphics/CMakeLists.txt index 2a8a1f10..d3de90bc 100644 --- a/FlingEngine/Graphics/CMakeLists.txt +++ b/FlingEngine/Graphics/CMakeLists.txt @@ -39,6 +39,8 @@ fling_add_shaders(Graphics "${FLING_ENGINE_SHADER_DIR}/Deferred/deferred.frag" "${FLING_ENGINE_SHADER_DIR}/Deferred/mrt.vert" "${FLING_ENGINE_SHADER_DIR}/Deferred/mrt.frag" + "${FLING_ENGINE_SHADER_DIR}/Occlusion/cull.comp" + "${FLING_ENGINE_SHADER_DIR}/Occlusion/hiz_downsample.comp" "${FLING_ENGINE_SHADER_DIR}/imgui/ui.vert" "${FLING_ENGINE_SHADER_DIR}/imgui/ui.frag" "${FLING_ENGINE_SHADER_DIR}/skybox/skybox.vert" diff --git a/FlingEngine/Graphics/inc/MeshCuller.h b/FlingEngine/Graphics/inc/MeshCuller.h index a5d38220..cda71233 100644 --- a/FlingEngine/Graphics/inc/MeshCuller.h +++ b/FlingEngine/Graphics/inc/MeshCuller.h @@ -18,6 +18,12 @@ namespace Fling /** Meshes the pass would draw, but that are outside the camera's view. */ uint32 Culled = 0; + + /** + * Meshes that are in the camera's view but that other meshes hide (occlusion culling). + * Counted by the GPU, so it is the value of the previous frame. Not part of Culled. + */ + uint32 Occluded = 0; }; /** diff --git a/FlingEngine/Graphics/inc/OcclusionTest.h b/FlingEngine/Graphics/inc/OcclusionTest.h new file mode 100644 index 00000000..fcbd6229 --- /dev/null +++ b/FlingEngine/Graphics/inc/OcclusionTest.h @@ -0,0 +1,96 @@ +#pragma once + +#include "FlingMath.h" +#include "FlingTypes.h" +#include "Frustum.h" +#include "GraphicsAPI.h" + +#include +#include + +namespace Fling +{ + /** + * The bounds of a mesh on the screen, for the occlusion test: the rectangle (in 0 to 1 + * screen space, y down like the frame buffer) and the depth of the nearest point. + */ + struct ScreenBounds + { + glm::vec2 MinUv{0.0f}; + glm::vec2 MaxUv{1.0f}; + + /** The smallest depth (0 near, 1 far) of the box, never below 0 */ + float NearDepth = 0.0f; + + /** + * False when the box reaches the plane of the camera, so the box has no safe screen + * rectangle. Such a box is never occluded. + */ + bool Testable = false; + }; + + /** + * A depth pyramid: level 0 is the depth image, and each texel of the next level holds the + * farthest (largest) depth of the texels below it. A level is half the size of the one + * before (rounded down, at least 1), and a last row or column that has an odd size covers + * the extra source row or column. The compute shaders (Occlusion/hiz_downsample.comp and + * Occlusion/cull.comp) do the same, so the test runs on the CPU for tests. + */ + class DepthPyramid + { + public: + /** Build every level from t_Depth, t_Width * t_Height values in rows, y down */ + GRAPHICS_API void Build(std::span t_Depth, uint32 t_Width, uint32 t_Height); + + uint32 LevelCount() const { return static_cast(m_Levels.size()); } + uint32 Width(const uint32 t_Level) const { return m_Levels[t_Level].Width; } + uint32 Height(const uint32 t_Level) const { return m_Levels[t_Level].Height; } + + /** The farthest depth under one texel of a level */ + float Texel(const uint32 t_Level, const uint32 t_X, const uint32 t_Y) const + { + const Level& L = m_Levels[t_Level]; + return L.Texels[size_t{t_Y} * L.Width + t_X]; + } + + /** The number of levels a pyramid of this size has: down to 1 x 1 */ + GRAPHICS_API static uint32 LevelsFor(uint32 t_Width, uint32 t_Height); + + /** The size of a level after t_Size: half, at least 1 */ + static uint32 NextSize(const uint32 t_Size) { return t_Size > 1 ? t_Size >> 1 : 1; } + + private: + struct Level + { + uint32 Width = 0; + uint32 Height = 0; + std::vector Texels; + }; + std::vector m_Levels; + }; + + namespace Occlusion + { + /** + * A box is occluded when its nearest depth is farther than the farthest depth under it + * by more than this. It keeps a mesh that fills its own box from hiding itself, because + * the shader and the rasterizer do not round the same way. + */ + constexpr float DepthBias = 1.0e-5f; + + /** + * Project the box t_Local, placed by t_World, with t_ViewProjection (the matrix the + * G-buffer shader uses). Never hides anything: a box that reaches the camera's plane + * is Testable = false. + */ + GRAPHICS_API ScreenBounds ProjectBounds(const Aabb& t_Local, + const glm::mat4& t_World, + const glm::mat4& t_ViewProjection); + + /** + * True if the pyramid shows that every pixel of the box is hidden: the box is farther + * than the farthest depth under its screen rectangle. Conservative: false when unsure. + */ + GRAPHICS_API bool IsOccluded(const DepthPyramid& t_Pyramid, const ScreenBounds& t_Bounds); + } // namespace Occlusion +} // namespace Fling diff --git a/FlingEngine/Graphics/inc/VulkanApp.h b/FlingEngine/Graphics/inc/VulkanApp.h index b320d2d7..480fc7c8 100644 --- a/FlingEngine/Graphics/inc/VulkanApp.h +++ b/FlingEngine/Graphics/inc/VulkanApp.h @@ -135,6 +135,13 @@ namespace Fling */ void SetFrustumCulling(bool t_On); + /** + * Occlusion culling on or off (RunSettings::OcclusionCulling) for the next frame. On: the + * meshes that other meshes hide from the camera are not drawn. The mesh pass holds the + * value, so it does nothing before Init; Engine::Present calls it before every frame. + */ + void SetOcclusionCulling(bool t_On); + /** The meshes the last frame drew and culled. Zero before the first frame and under --null-render. */ CullStats GetCullStats() const; diff --git a/FlingEngine/Graphics/src/CommandBuffer.cpp b/FlingEngine/Graphics/src/CommandBuffer.cpp index 81e089eb..2bcf88f0 100644 --- a/FlingEngine/Graphics/src/CommandBuffer.cpp +++ b/FlingEngine/Graphics/src/CommandBuffer.cpp @@ -67,6 +67,18 @@ namespace Fling vkCmdBeginRenderPass(GetHandle(), &begin_info, VK_SUBPASS_CONTENTS_INLINE); } + void CommandBuffer::BeginLoadRenderPass(const FrameBuffer& t_frameBuf) + { + VkRenderPassBeginInfo begin_info{ VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO }; + begin_info.renderPass = t_frameBuf.GetLoadRenderPassHandle(); + begin_info.framebuffer = t_frameBuf.GetHandle(); + begin_info.renderArea.offset = { 0, 0 }; + begin_info.renderArea.extent.width = t_frameBuf.GetWidth(); + begin_info.renderArea.extent.height = t_frameBuf.GetHeight(); + // Nothing is cleared, so there are no clear values + vkCmdBeginRenderPass(GetHandle(), &begin_info, VK_SUBPASS_CONTENTS_INLINE); + } + void CommandBuffer::NextSubpass() { // track pipeline state ? diff --git a/FlingEngine/Graphics/src/CommandBuffer.h b/FlingEngine/Graphics/src/CommandBuffer.h index 24e88dfb..67682b76 100644 --- a/FlingEngine/Graphics/src/CommandBuffer.h +++ b/FlingEngine/Graphics/src/CommandBuffer.h @@ -46,6 +46,9 @@ namespace Fling void BeginRenderPass(const FrameBuffer& t_frameBuf, const std::vector& t_ClearVales); + /** Begin the frame buffer's load render pass: it keeps the contents the first pass drew */ + void BeginLoadRenderPass(const FrameBuffer& t_frameBuf); + void NextSubpass(); void BindPipeline(VkPipelineBindPoint t_BindPoint, VkPipeline t_Pipeline); diff --git a/FlingEngine/Graphics/src/FrameBuffer.cpp b/FlingEngine/Graphics/src/FrameBuffer.cpp index d7185c4a..ca142e39 100644 --- a/FlingEngine/Graphics/src/FrameBuffer.cpp +++ b/FlingEngine/Graphics/src/FrameBuffer.cpp @@ -163,6 +163,8 @@ namespace Fling AttachmentCreation.push_back(Attachment->GetCreationInfo()); } + const bool bHadLoadPass = m_LoadRenderPass != VK_NULL_HANDLE; + // Destroy the old stuff-------------------------------- for (FrameBufferAttachment* Attachment : m_Attachments) { @@ -176,6 +178,12 @@ namespace Fling m_RenderPass = VK_NULL_HANDLE; } + if (m_LoadRenderPass != VK_NULL_HANDLE) + { + vkDestroyRenderPass(m_Device->GetVkDevice(), m_LoadRenderPass, nullptr); + m_LoadRenderPass = VK_NULL_HANDLE; + } + if (m_FrameBuffer != VK_NULL_HANDLE) { vkDestroyFramebuffer(m_Device->GetVkDevice(), m_FrameBuffer, nullptr); @@ -191,6 +199,10 @@ namespace Fling } VK_CHECK_RESULT(CreateRenderPass()); + if (bHadLoadPass) + { + VK_CHECK_RESULT(CreateLoadRenderPass()); + } } void FrameBuffer::Release() @@ -214,19 +226,78 @@ namespace Fling vkDestroyRenderPass(m_Device->GetVkDevice(), m_RenderPass, nullptr); } + if (m_LoadRenderPass != VK_NULL_HANDLE) + { + vkDestroyRenderPass(m_Device->GetVkDevice(), m_LoadRenderPass, nullptr); + } + if (m_FrameBuffer != VK_NULL_HANDLE) { vkDestroyFramebuffer(m_Device->GetVkDevice(), m_FrameBuffer, nullptr); } } + VkResult FrameBuffer::CreateLoadRenderPass() + { + assert(m_RenderPass != VK_NULL_HANDLE); + return BuildRenderPass(true, m_LoadRenderPass); + } + VkResult FrameBuffer::CreateRenderPass() + { + VK_CHECK_RESULT(BuildRenderPass(false, m_RenderPass)); + + std::vector attachmentViews; + for (auto& attachment : m_Attachments) + { + attachmentViews.push_back(attachment->GetViewHandle()); + } + + // Find. max number of layers across attachments + uint32 maxLayers = 0; + for (auto& attachment : m_Attachments) + { + if (attachment->GetSubresourceRange().layerCount > maxLayers) + { + maxLayers = attachment->GetSubresourceRange().layerCount; + } + } + + VkFramebufferCreateInfo framebufferInfo = {}; + framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + framebufferInfo.renderPass = m_RenderPass; + framebufferInfo.pAttachments = attachmentViews.data(); + framebufferInfo.attachmentCount = static_cast(attachmentViews.size()); + framebufferInfo.width = m_Width; + framebufferInfo.height = m_Height; + framebufferInfo.layers = maxLayers; + + if (m_FrameBuffer != VK_NULL_HANDLE) + { + vkDestroyFramebuffer(m_Device->GetVkDevice(), m_FrameBuffer, nullptr); + m_FrameBuffer = VK_NULL_HANDLE; + } + + VK_CHECK_RESULT(vkCreateFramebuffer(m_Device->GetVkDevice(), &framebufferInfo, nullptr, &m_FrameBuffer)); + + return VK_SUCCESS; + } + + VkResult FrameBuffer::BuildRenderPass(const bool t_Load, VkRenderPass& t_Out) { // Gather attachment descriptions std::vector attachmentDescriptions; for (auto& attachment : m_Attachments) { - attachmentDescriptions.push_back(attachment->GetDescription()); + VkAttachmentDescription Description = attachment->GetDescription(); + if (t_Load) + { + // Keep what the first pass drew, and start in the layout it ended in + Description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; + Description.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + Description.initialLayout = Description.finalLayout; + } + attachmentDescriptions.push_back(Description); } // Collect attachment references @@ -268,23 +339,35 @@ namespace Fling subpass.pDepthStencilAttachment = &depthReference; } - // Use subpass dependencies for attachment layout transitions + // Use subpass dependencies for attachment layout transitions. They cover the depth + // stages too, and let a compute shader read the attachments after the pass (the + // occlusion culling pass builds a depth pyramid from the depth). + constexpr VkPipelineStageFlags AttachmentStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | + VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + constexpr VkAccessFlags AttachmentAccess = + VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + std::array dependencies; dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; dependencies[0].dstSubpass = 0; - dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; - dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + // The same for the load pass and the default pass, as render passes that share a frame + // buffer must have the same dependencies. The load pass follows compute work that read the depth. + dependencies[0].srcStageMask = AttachmentStages | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; + dependencies[0].dstStageMask = AttachmentStages; + dependencies[0].srcAccessMask = AttachmentAccess | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + dependencies[0].dstAccessMask = AttachmentAccess; dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; dependencies[1].srcSubpass = 0; dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; - dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; + dependencies[1].srcStageMask = AttachmentStages; + dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; + dependencies[1].srcAccessMask = AttachmentAccess; + dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_SHADER_READ_BIT; dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; // Create render pass @@ -296,41 +379,7 @@ namespace Fling renderPassInfo.pSubpasses = &subpass; renderPassInfo.dependencyCount = static_cast(dependencies.size()); renderPassInfo.pDependencies = dependencies.data(); - VK_CHECK_RESULT(vkCreateRenderPass(m_Device->GetVkDevice(), &renderPassInfo, nullptr, &m_RenderPass)); - - std::vector attachmentViews; - for (auto& attachment : m_Attachments) - { - attachmentViews.push_back(attachment->GetViewHandle()); - } - - // Find. max number of layers across attachments - uint32 maxLayers = 0; - for (auto& attachment : m_Attachments) - { - if (attachment->GetSubresourceRange().layerCount > maxLayers) - { - maxLayers = attachment->GetSubresourceRange().layerCount; - } - } - - VkFramebufferCreateInfo framebufferInfo = {}; - framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; - framebufferInfo.renderPass = m_RenderPass; - framebufferInfo.pAttachments = attachmentViews.data(); - framebufferInfo.attachmentCount = static_cast(attachmentViews.size()); - framebufferInfo.width = m_Width; - framebufferInfo.height = m_Height; - framebufferInfo.layers = maxLayers; - - if (m_FrameBuffer != VK_NULL_HANDLE) - { - vkDestroyFramebuffer(m_Device->GetVkDevice(), m_FrameBuffer, nullptr); - m_FrameBuffer = VK_NULL_HANDLE; - } - - VK_CHECK_RESULT(vkCreateFramebuffer(m_Device->GetVkDevice(), &framebufferInfo, nullptr, &m_FrameBuffer)); - + VK_CHECK_RESULT(vkCreateRenderPass(m_Device->GetVkDevice(), &renderPassInfo, nullptr, &t_Out)); return VK_SUCCESS; } diff --git a/FlingEngine/Graphics/src/FrameBuffer.h b/FlingEngine/Graphics/src/FrameBuffer.h index ceb00dd2..22399394 100644 --- a/FlingEngine/Graphics/src/FrameBuffer.h +++ b/FlingEngine/Graphics/src/FrameBuffer.h @@ -87,6 +87,17 @@ namespace Fling VkFramebuffer GetHandle() const { return m_FrameBuffer; } VkRenderPass GetRenderPassHandle() const { return m_RenderPass; } + /** + * A render pass that is compatible with GetRenderPassHandle but keeps the contents of + * every attachment (load op LOAD) instead of clearing them. It starts from the layouts + * the default pass ends in. A second pass over the same frame buffer uses it. Made by + * CreateLoadRenderPass; null before that. + */ + VkRenderPass GetLoadRenderPassHandle() const { return m_LoadRenderPass; } + + /** Make the load render pass (see GetLoadRenderPassHandle). Call it after CreateRenderPass. */ + VkResult CreateLoadRenderPass(); + /** * Create the default render pass of this frame buffer * based on the given attachments it has. Should be called @@ -117,11 +128,15 @@ namespace Fling inline int32 GetHeight() const { return m_Height; } private: + /** Build a render pass over the attachments. t_Load: keep the contents, as CreateLoadRenderPass says. */ + VkResult BuildRenderPass(bool t_Load, VkRenderPass& t_Out); + int32 m_Width = 0; int32 m_Height = 0; VkFramebuffer m_FrameBuffer = VK_NULL_HANDLE; VkRenderPass m_RenderPass = VK_NULL_HANDLE; + VkRenderPass m_LoadRenderPass = VK_NULL_HANDLE; VkSampler m_Sampler = VK_NULL_HANDLE; const LogicalDevice* m_Device; diff --git a/FlingEngine/Graphics/src/OcclusionCuller.cpp b/FlingEngine/Graphics/src/OcclusionCuller.cpp new file mode 100644 index 00000000..653dd6f3 --- /dev/null +++ b/FlingEngine/Graphics/src/OcclusionCuller.cpp @@ -0,0 +1,545 @@ +#include "Buffer.h" +#include "GraphicsHelpers.h" +#include "Logger.h" +#include "LogicalDevice.h" +#include "OcclusionCuller.h" +#include "OcclusionTest.h" +#include "PhyscialDevice.h" +#include "Shader.h" + +#include +#include +#include + +namespace Fling +{ + namespace + { + constexpr VkFormat PyramidFormat = VK_FORMAT_R32_SFLOAT; + constexpr uint32 MaxLevels = 16; + constexpr uint32 CullGroupSize = 64; + constexpr uint32 DownsampleGroupSize = 8; + constexpr VkMemoryPropertyFlags HostVisible = + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + + /** The std140 block Params of cull.comp */ + struct alignas(16) CullParams + { + glm::mat4 ViewProjection{1.0f}; + glm::uvec4 Counts{0u}; + }; + + /** The push constant block of hiz_downsample.comp */ + struct DownsamplePush + { + int32 SrcSize[2]; + int32 DstSize[2]; + int32 Copy; + }; + + VkDescriptorSetLayoutBinding Binding(const uint32 t_Binding, const VkDescriptorType t_Type) + { + VkDescriptorSetLayoutBinding B = {}; + B.binding = t_Binding; + B.descriptorType = t_Type; + B.descriptorCount = 1; + B.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + return B; + } + + void ComputeBarrier(VkCommandBuffer t_Cmd, + const VkPipelineStageFlags t_SrcStage, + const VkAccessFlags t_SrcAccess, + const VkPipelineStageFlags t_DstStage, + const VkAccessFlags t_DstAccess) + { + VkMemoryBarrier Barrier = {}; + Barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; + Barrier.srcAccessMask = t_SrcAccess; + Barrier.dstAccessMask = t_DstAccess; + vkCmdPipelineBarrier(t_Cmd, t_SrcStage, t_DstStage, 0, 1, &Barrier, 0, nullptr, 0, nullptr); + } + } // namespace + + OcclusionCuller::OcclusionCuller(const LogicalDevice* t_Device, + std::shared_ptr t_Downsample, + std::shared_ptr t_Cull) + : m_Device(t_Device) + { + assert(m_Device); + if (!t_Downsample || !t_Cull || t_Downsample->GetShaderModule() == VK_NULL_HANDLE || + t_Cull->GetShaderModule() == VK_NULL_HANDLE) + { + F_LOG_WARN("Occlusion culling is off: its compute shaders did not load"); + return; + } + + const VkDevice Dev = m_Device->GetVkDevice(); + CreatePipelines(t_Downsample, t_Cull); + + VkSamplerCreateInfo SamplerInfo = {}; + SamplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + SamplerInfo.magFilter = VK_FILTER_NEAREST; + SamplerInfo.minFilter = VK_FILTER_NEAREST; + SamplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + SamplerInfo.addressModeU = SamplerInfo.addressModeV = SamplerInfo.addressModeW = + VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + SamplerInfo.maxLod = static_cast(MaxLevels); + VK_CHECK_RESULT(vkCreateSampler(Dev, &SamplerInfo, nullptr, &m_Sampler)); + + const std::array PoolSizes = { + VkDescriptorPoolSize{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, MaxLevels + 2}, + VkDescriptorPoolSize{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, MaxLevels}, + VkDescriptorPoolSize{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}, + VkDescriptorPoolSize{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 5}}; + VkDescriptorPoolCreateInfo PoolInfo = {}; + PoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + PoolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; + PoolInfo.maxSets = MaxLevels + 1; + PoolInfo.poolSizeCount = static_cast(PoolSizes.size()); + PoolInfo.pPoolSizes = PoolSizes.data(); + VK_CHECK_RESULT(vkCreateDescriptorPool(Dev, &PoolInfo, nullptr, &m_Pool)); + + VkDescriptorSetAllocateInfo Alloc = {}; + Alloc.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + Alloc.descriptorPool = m_Pool; + Alloc.descriptorSetCount = 1; + Alloc.pSetLayouts = &m_CullSetLayout; + VK_CHECK_RESULT(vkAllocateDescriptorSets(Dev, &Alloc, &m_CullSet)); + + m_Params = new Buffer(sizeof(CullParams), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, HostVisible); + m_Params->MapMemory(sizeof(CullParams)); + m_Stats = new Buffer( + sizeof(uint32) * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, HostVisible); + m_Stats->MapMemory(sizeof(uint32) * 4); + std::memset(m_Stats->m_MappedMem, 0, sizeof(uint32) * 4); + + m_Supported = true; + } + + OcclusionCuller::~OcclusionCuller() + { + const VkDevice Dev = m_Device->GetVkDevice(); + DestroyPyramid(); + for (Buffer* B : m_Retired) + { + delete B; + } + delete m_Params; + delete m_Slots; + delete m_Draw2; + delete m_Visible; + delete m_Stats; + if (m_Sampler != VK_NULL_HANDLE) + { + vkDestroySampler(Dev, m_Sampler, nullptr); + } + if (m_Pool != VK_NULL_HANDLE) + { + vkDestroyDescriptorPool(Dev, m_Pool, nullptr); + } + if (m_CullPipeline != VK_NULL_HANDLE) + vkDestroyPipeline(Dev, m_CullPipeline, nullptr); + if (m_DownsamplePipeline != VK_NULL_HANDLE) + vkDestroyPipeline(Dev, m_DownsamplePipeline, nullptr); + if (m_CullPipelineLayout != VK_NULL_HANDLE) + vkDestroyPipelineLayout(Dev, m_CullPipelineLayout, nullptr); + if (m_DownsamplePipelineLayout != VK_NULL_HANDLE) + vkDestroyPipelineLayout(Dev, m_DownsamplePipelineLayout, nullptr); + if (m_CullSetLayout != VK_NULL_HANDLE) + vkDestroyDescriptorSetLayout(Dev, m_CullSetLayout, nullptr); + if (m_DownsampleSetLayout != VK_NULL_HANDLE) + vkDestroyDescriptorSetLayout(Dev, m_DownsampleSetLayout, nullptr); + } + + void OcclusionCuller::CreatePipelines(const std::shared_ptr& t_Downsample, + const std::shared_ptr& t_Cull) + { + const VkDevice Dev = m_Device->GetVkDevice(); + + auto MakeLayout = [&](const std::vector& t_Bindings, + const uint32 t_PushSize, + VkDescriptorSetLayout& t_SetLayout, + VkPipelineLayout& t_PipelineLayout) + { + VkDescriptorSetLayoutCreateInfo SetInfo = {}; + SetInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + SetInfo.bindingCount = static_cast(t_Bindings.size()); + SetInfo.pBindings = t_Bindings.data(); + VK_CHECK_RESULT(vkCreateDescriptorSetLayout(Dev, &SetInfo, nullptr, &t_SetLayout)); + + VkPushConstantRange Push = {VK_SHADER_STAGE_COMPUTE_BIT, 0, t_PushSize}; + VkPipelineLayoutCreateInfo LayoutInfo = {}; + LayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + LayoutInfo.setLayoutCount = 1; + LayoutInfo.pSetLayouts = &t_SetLayout; + LayoutInfo.pushConstantRangeCount = 1; + LayoutInfo.pPushConstantRanges = &Push; + VK_CHECK_RESULT(vkCreatePipelineLayout(Dev, &LayoutInfo, nullptr, &t_PipelineLayout)); + }; + + auto MakePipeline = [&](const std::shared_ptr& t_Shader, VkPipelineLayout t_Layout, VkPipeline& t_Out) + { + VkComputePipelineCreateInfo Info = {}; + Info.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; + Info.layout = t_Layout; + Info.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + Info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + Info.stage.module = t_Shader->GetShaderModule(); + Info.stage.pName = "main"; + VK_CHECK_RESULT(vkCreateComputePipelines(Dev, VK_NULL_HANDLE, 1, &Info, nullptr, &t_Out)); + }; + + MakeLayout({Binding(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER), + Binding(1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER), + Binding(2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER), + Binding(3, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER), + Binding(4, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER), + Binding(5, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER), + Binding(6, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)}, + sizeof(uint32), + m_CullSetLayout, + m_CullPipelineLayout); + MakePipeline(t_Cull, m_CullPipelineLayout, m_CullPipeline); + + MakeLayout( + {Binding(0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER), Binding(1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE)}, + sizeof(DownsamplePush), + m_DownsampleSetLayout, + m_DownsamplePipelineLayout); + MakePipeline(t_Downsample, m_DownsamplePipelineLayout, m_DownsamplePipeline); + } + + void OcclusionCuller::DestroyPyramid() + { + const VkDevice Dev = m_Device->GetVkDevice(); + if (!m_DownsampleSets.empty()) + { + vkFreeDescriptorSets(Dev, m_Pool, static_cast(m_DownsampleSets.size()), m_DownsampleSets.data()); + m_DownsampleSets.clear(); + } + for (VkImageView View : m_LevelViews) + { + vkDestroyImageView(Dev, View, nullptr); + } + m_LevelViews.clear(); + if (m_PyramidAllLevels != VK_NULL_HANDLE) + { + vkDestroyImageView(Dev, m_PyramidAllLevels, nullptr); + m_PyramidAllLevels = VK_NULL_HANDLE; + } + if (m_PyramidImage != VK_NULL_HANDLE) + { + vkDestroyImage(Dev, m_PyramidImage, nullptr); + m_PyramidImage = VK_NULL_HANDLE; + } + if (m_PyramidMemory != VK_NULL_HANDLE) + { + vkFreeMemory(Dev, m_PyramidMemory, nullptr); + m_PyramidMemory = VK_NULL_HANDLE; + } + } + + void OcclusionCuller::SetDepth(const VkImageView t_DepthView, + const uint32 t_Width, + const uint32 t_Height, + const VkFormat t_DepthFormat) + { + if (!m_Supported) + { + return; + } + const PhysicalDevice* Phys = m_Device->GetPhysicalDevice(); + const bool bSampleDepth = + (Phys->GetFormatProperties(t_DepthFormat).optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0; + const bool bStorage = + (Phys->GetFormatProperties(PyramidFormat).optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0; + const uint32 Levels = DepthPyramid::LevelsFor(t_Width, t_Height); + if (!bSampleDepth || !bStorage || Levels > MaxLevels) + { + F_LOG_WARN("Occlusion culling is off: the device cannot sample the depth format or store the pyramid"); + m_Supported = false; + return; + } + + const VkDevice Dev = m_Device->GetVkDevice(); + DestroyPyramid(); + m_Width = t_Width; + m_Height = t_Height; + m_DepthView = t_DepthView; + + GraphicsHelpers::CreateVkImage(Dev, + t_Width, + t_Height, + Levels, + 1, + 1, + PyramidFormat, + VK_IMAGE_TILING_OPTIMAL, + VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + 0, + m_PyramidImage, + m_PyramidMemory, + VK_SAMPLE_COUNT_1_BIT); + + auto MakeView = [&](const uint32 t_Base, const uint32 t_Count) + { + VkImageViewCreateInfo Info = {}; + Info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + Info.image = m_PyramidImage; + Info.viewType = VK_IMAGE_VIEW_TYPE_2D; + Info.format = PyramidFormat; + Info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, t_Base, t_Count, 0, 1}; + VkImageView View = VK_NULL_HANDLE; + VK_CHECK_RESULT(vkCreateImageView(Dev, &Info, nullptr, &View)); + return View; + }; + m_PyramidAllLevels = MakeView(0, Levels); + for (uint32 L = 0; L < Levels; ++L) + { + m_LevelViews.push_back(MakeView(L, 1)); + } + + // One set per level: the source (the depth, then the level above) and the level it writes + std::vector Layouts(Levels, m_DownsampleSetLayout); + m_DownsampleSets.resize(Levels); + VkDescriptorSetAllocateInfo Alloc = {}; + Alloc.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + Alloc.descriptorPool = m_Pool; + Alloc.descriptorSetCount = Levels; + Alloc.pSetLayouts = Layouts.data(); + VK_CHECK_RESULT(vkAllocateDescriptorSets(Dev, &Alloc, m_DownsampleSets.data())); + + std::vector ImageInfos(size_t{Levels} * 2); + std::vector Writes; + Writes.reserve(size_t{Levels} * 2); + for (uint32 L = 0; L < Levels; ++L) + { + VkDescriptorImageInfo& Src = ImageInfos[size_t{L} * 2]; + Src.sampler = m_Sampler; + Src.imageView = L == 0 ? m_DepthView : m_LevelViews[L - 1]; + Src.imageLayout = L == 0 ? VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL; + VkDescriptorImageInfo& Dst = ImageInfos[size_t{L} * 2 + 1]; + Dst.sampler = VK_NULL_HANDLE; + Dst.imageView = m_LevelViews[L]; + Dst.imageLayout = VK_IMAGE_LAYOUT_GENERAL; + + VkWriteDescriptorSet Write = {}; + Write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + Write.dstSet = m_DownsampleSets[L]; + Write.descriptorCount = 1; + Write.dstBinding = 0; + Write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + Write.pImageInfo = &Src; + Writes.push_back(Write); + Write.dstBinding = 1; + Write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; + Write.pImageInfo = &Dst; + Writes.push_back(Write); + } + vkUpdateDescriptorSets(Dev, static_cast(Writes.size()), Writes.data(), 0, nullptr); + + WriteCullDescriptors(); + } + + bool OcclusionCuller::EnsureCapacity(const size_t t_Slots, Buffer* t_Draw1) + { + if (!m_Supported) + { + return false; + } + if (m_Slots != nullptr && m_Capacity >= t_Slots && m_Draw1 == t_Draw1) + { + return false; + } + + if (m_Capacity < t_Slots || m_Slots == nullptr) + { + const size_t Capacity = std::max(t_Slots, 64); + for (Buffer* Old : {m_Slots, m_Draw2, m_Visible}) + { + if (Old != nullptr) + { + m_Retired.push_back(Old); + } + } + m_Slots = new Buffer(sizeof(OcclusionSlot) * Capacity, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, HostVisible); + m_Slots->MapMemory(sizeof(OcclusionSlot) * Capacity); + std::memset(m_Slots->m_MappedMem, 0, sizeof(OcclusionSlot) * Capacity); + m_Draw2 = new Buffer(sizeof(VkDrawIndexedIndirectCommand) * Capacity, + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, + HostVisible); + m_Draw2->MapMemory(sizeof(VkDrawIndexedIndirectCommand) * Capacity); + std::memset(m_Draw2->m_MappedMem, 0, sizeof(VkDrawIndexedIndirectCommand) * Capacity); + // Nothing was visible yet, so the first frame draws everything in the second pass + m_Visible = new Buffer(sizeof(uint32) * Capacity, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, HostVisible); + m_Visible->MapMemory(sizeof(uint32) * Capacity); + std::memset(m_Visible->m_MappedMem, 0, sizeof(uint32) * Capacity); + m_Capacity = Capacity; + } + m_Draw1 = t_Draw1; + WriteCullDescriptors(); + return true; + } + + void OcclusionCuller::ReleaseRetired() + { + for (Buffer* B : m_Retired) + { + delete B; + } + m_Retired.clear(); + } + + void OcclusionCuller::WriteCullDescriptors() const + { + if (m_Slots == nullptr || m_Draw1 == nullptr || m_PyramidAllLevels == VK_NULL_HANDLE) + { + return; + } + const VkDescriptorBufferInfo Infos[6] = {{m_Params->GetVkBuffer(), 0, sizeof(CullParams)}, + {m_Slots->GetVkBuffer(), 0, VK_WHOLE_SIZE}, + {m_Draw1->GetVkBuffer(), 0, VK_WHOLE_SIZE}, + {m_Draw2->GetVkBuffer(), 0, VK_WHOLE_SIZE}, + {m_Visible->GetVkBuffer(), 0, VK_WHOLE_SIZE}, + {m_Stats->GetVkBuffer(), 0, VK_WHOLE_SIZE}}; + const VkDescriptorImageInfo Pyramid = {m_Sampler, m_PyramidAllLevels, VK_IMAGE_LAYOUT_GENERAL}; + + std::array Writes = {}; + for (uint32 i = 0; i < 6; ++i) + { + Writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + Writes[i].dstSet = m_CullSet; + Writes[i].dstBinding = i; + Writes[i].descriptorCount = 1; + Writes[i].descriptorType = i == 0 ? VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER : VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + Writes[i].pBufferInfo = &Infos[i]; + } + Writes[6].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + Writes[6].dstSet = m_CullSet; + Writes[6].dstBinding = 6; + Writes[6].descriptorCount = 1; + Writes[6].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + Writes[6].pImageInfo = &Pyramid; + vkUpdateDescriptorSets(m_Device->GetVkDevice(), static_cast(Writes.size()), Writes.data(), 0, nullptr); + } + + OcclusionSlot* OcclusionCuller::MappedSlots() const + { + return m_Slots != nullptr ? static_cast(m_Slots->m_MappedMem) : nullptr; + } + + uint32 OcclusionCuller::ReadOccludedCount() const + { + return m_Stats != nullptr ? *static_cast(m_Stats->m_MappedMem) : 0; + } + + void OcclusionCuller::WriteParams(const glm::mat4& t_ViewProjection, const uint32 t_SlotCount) + { + m_SlotCount = t_SlotCount; + CullParams Params; + Params.ViewProjection = t_ViewProjection; + Params.Counts = glm::uvec4(t_SlotCount, 0u, 0u, 0u); + std::memcpy(m_Params->m_MappedMem, &Params, sizeof(Params)); + } + + void OcclusionCuller::Dispatch(VkCommandBuffer t_Cmd, const uint32 t_Phase) const + { + vkCmdBindPipeline(t_Cmd, VK_PIPELINE_BIND_POINT_COMPUTE, m_CullPipeline); + vkCmdBindDescriptorSets( + t_Cmd, VK_PIPELINE_BIND_POINT_COMPUTE, m_CullPipelineLayout, 0, 1, &m_CullSet, 0, nullptr); + vkCmdPushConstants(t_Cmd, m_CullPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32), &t_Phase); + // The recording holds the group count, so it covers the capacity. The shader stops at the slot count. + vkCmdDispatch(t_Cmd, static_cast((m_Capacity + CullGroupSize - 1) / CullGroupSize), 1, 1); + } + + void OcclusionCuller::RecordFirstPhase(VkCommandBuffer t_Cmd) const + { + // The pyramid is made again each frame, so its old contents do not matter. Phase 0 does not + // read it, but the descriptor set that it binds holds it, so it must be in its layout by then. + VkImageMemoryBarrier ToGeneral = {}; + ToGeneral.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + ToGeneral.srcAccessMask = 0; + ToGeneral.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT; + ToGeneral.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + ToGeneral.newLayout = VK_IMAGE_LAYOUT_GENERAL; + ToGeneral.srcQueueFamilyIndex = ToGeneral.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + ToGeneral.image = m_PyramidImage; + ToGeneral.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, static_cast(m_LevelViews.size()), 0, 1}; + vkCmdPipelineBarrier(t_Cmd, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + 0, + 0, + nullptr, + 0, + nullptr, + 1, + &ToGeneral); + + // The count of hidden meshes starts at 0 for this frame + vkCmdFillBuffer(t_Cmd, m_Stats->GetVkBuffer(), 0, VK_WHOLE_SIZE, 0); + ComputeBarrier(t_Cmd, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); + + Dispatch(t_Cmd, 0); + + // The first render pass reads the commands. Phase 1 reads the visible flags that this phase read. + ComputeBarrier(t_Cmd, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_SHADER_WRITE_BIT, + VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); + } + + void OcclusionCuller::RecordSecondPhase(VkCommandBuffer t_Cmd) const + { + vkCmdBindPipeline(t_Cmd, VK_PIPELINE_BIND_POINT_COMPUTE, m_DownsamplePipeline); + uint32 SrcW = m_Width; + uint32 SrcH = m_Height; + for (uint32 L = 0; L < m_LevelViews.size(); ++L) + { + const uint32 DstW = L == 0 ? m_Width : DepthPyramid::NextSize(SrcW); + const uint32 DstH = L == 0 ? m_Height : DepthPyramid::NextSize(SrcH); + DownsamplePush Push = {}; + Push.SrcSize[0] = static_cast(SrcW); + Push.SrcSize[1] = static_cast(SrcH); + Push.DstSize[0] = static_cast(DstW); + Push.DstSize[1] = static_cast(DstH); + Push.Copy = L == 0 ? 1 : 0; + vkCmdBindDescriptorSets(t_Cmd, + VK_PIPELINE_BIND_POINT_COMPUTE, + m_DownsamplePipelineLayout, + 0, + 1, + &m_DownsampleSets[L], + 0, + nullptr); + vkCmdPushConstants(t_Cmd, m_DownsamplePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &Push); + vkCmdDispatch(t_Cmd, + (DstW + DownsampleGroupSize - 1) / DownsampleGroupSize, + (DstH + DownsampleGroupSize - 1) / DownsampleGroupSize, + 1); + ComputeBarrier(t_Cmd, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_SHADER_WRITE_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT); + SrcW = DstW; + SrcH = DstH; + } + + Dispatch(t_Cmd, 1); + + // The second render pass reads the commands, and the CPU reads the count next frame + ComputeBarrier(t_Cmd, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_SHADER_WRITE_BIT, + VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_HOST_BIT, + VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_HOST_READ_BIT); + } +} // namespace Fling diff --git a/FlingEngine/Graphics/src/OcclusionCuller.h b/FlingEngine/Graphics/src/OcclusionCuller.h new file mode 100644 index 00000000..451dfde0 --- /dev/null +++ b/FlingEngine/Graphics/src/OcclusionCuller.h @@ -0,0 +1,143 @@ +#pragma once + +#include "FlingMath.h" +#include "FlingTypes.h" +#include "FlingVulkan.h" + +#include +#include + +namespace Fling +{ + class Buffer; + class LogicalDevice; + class Shader; + + /** + * What the cull shader reads about one proxy slot, written by the CPU each frame. The std430 + * layout of Slot in Occlusion/cull.comp. + */ + struct alignas(16) OcclusionSlot + { + enum Flags : uint32 + { + /** The slot passed the frustum test this frame */ + InView = 1u, + /** BoundsMin and BoundsMax are known */ + HasBounds = 2u, + }; + + glm::mat4 World{1.0f}; + glm::vec4 BoundsMin{0.0f}; + glm::vec4 BoundsMax{0.0f}; + /** x: index count (0: nothing to draw), y: Flags */ + glm::uvec4 Info{0u}; + }; + static_assert(sizeof(OcclusionSlot) == 112); + + /** + * Occlusion culling of the G-buffer pass on the GPU (a Hi-Z depth pyramid), in two phases. + * + * Phase 0 runs before the pass: the meshes that were visible in the last frame (and are in + * the view) get a draw. The pass draws them first (Draw1). Then the pyramid is built from + * the depth of that draw, and phase 1 tests every mesh in the view against it: a mesh that + * is not hidden and was not drawn yet gets a draw (Draw2), which a second render pass over + * the same frame buffer makes. Because the pyramid comes from this frame's own camera and + * meshes, nothing is ever hidden by an old picture: no popping, and no reprojection. + * + * Both phases write the indirect draw commands of every slot, so the recorded draws are the + * same for every frame. The per frame inputs are the slot data and the parameters. The count + * of hidden meshes comes back through a host visible buffer, one frame late. + * + * The test is the same as Occlusion::IsOccluded (OcclusionTest.h), which GraphicsTests runs on the CPU. + */ + class OcclusionCuller + { + public: + OcclusionCuller(const LogicalDevice* t_Device, + std::shared_ptr t_Downsample, + std::shared_ptr t_Cull); + ~OcclusionCuller(); + + OcclusionCuller(const OcclusionCuller&) = delete; + OcclusionCuller& operator=(const OcclusionCuller&) = delete; + + /** False when the device cannot do this (no shaders, or the depth format cannot be sampled) */ + bool IsSupported() const { return m_Supported; } + + /** + * Make the pyramid for a depth image, and point the shaders at it. Call it when the + * pass makes its frame buffer, and again when that is made again (a resize). The depth + * image must have the sampled usage and be in DEPTH_STENCIL_READ_ONLY_OPTIMAL after the first pass. + */ + void SetDepth(VkImageView t_DepthView, uint32 t_Width, uint32 t_Height, VkFormat t_DepthFormat); + + /** + * Make the per slot buffers hold t_Slots slots, and use t_Draw1 for the first draw + * commands. @return True if a buffer is new, so that recorded command buffers are old. + */ + bool EnsureCapacity(size_t t_Slots, Buffer* t_Draw1); + + /** Delete the buffers that EnsureCapacity replaced. The GPU is done with the frame that used them. */ + void ReleaseRetired(); + + /** The slot data, one per slot, for the CPU to fill. Valid after EnsureCapacity. */ + OcclusionSlot* MappedSlots() const; + + /** The second draw commands, one per slot: the draws that the second render pass reads */ + const Buffer* Draw2() const { return m_Draw2; } + + /** The meshes the previous frame found hidden, read from the GPU's counter */ + uint32 ReadOccludedCount() const; + + /** Write this frame's parameters: the camera matrix and the slot count */ + void WriteParams(const glm::mat4& t_ViewProjection, uint32 t_SlotCount); + + /** Record phase 0 (before the first render pass) */ + void RecordFirstPhase(VkCommandBuffer t_Cmd) const; + + /** Record the pyramid and phase 1 (between the two render passes) */ + void RecordSecondPhase(VkCommandBuffer t_Cmd) const; + + private: + void DestroyPyramid(); + void CreatePipelines(const std::shared_ptr& t_Downsample, const std::shared_ptr& t_Cull); + void WriteCullDescriptors() const; + void Dispatch(VkCommandBuffer t_Cmd, uint32 t_Phase) const; + + const LogicalDevice* m_Device; + bool m_Supported = false; + + VkDescriptorSetLayout m_CullSetLayout = VK_NULL_HANDLE; + VkPipelineLayout m_CullPipelineLayout = VK_NULL_HANDLE; + VkPipeline m_CullPipeline = VK_NULL_HANDLE; + VkDescriptorSetLayout m_DownsampleSetLayout = VK_NULL_HANDLE; + VkPipelineLayout m_DownsamplePipelineLayout = VK_NULL_HANDLE; + VkPipeline m_DownsamplePipeline = VK_NULL_HANDLE; + + VkDescriptorPool m_Pool = VK_NULL_HANDLE; + VkDescriptorSet m_CullSet = VK_NULL_HANDLE; + VkSampler m_Sampler = VK_NULL_HANDLE; + + // The pyramid + VkImage m_PyramidImage = VK_NULL_HANDLE; + VkDeviceMemory m_PyramidMemory = VK_NULL_HANDLE; + VkImageView m_PyramidAllLevels = VK_NULL_HANDLE; + std::vector m_LevelViews; + std::vector m_DownsampleSets; + uint32 m_Width = 0; + uint32 m_Height = 0; + VkImageView m_DepthView = VK_NULL_HANDLE; + + // Per slot buffers + Buffer* m_Params = nullptr; + Buffer* m_Slots = nullptr; + Buffer* m_Draw2 = nullptr; + Buffer* m_Visible = nullptr; + Buffer* m_Stats = nullptr; + Buffer* m_Draw1 = nullptr; + size_t m_Capacity = 0; + uint32 m_SlotCount = 0; + std::vector m_Retired; + }; +} // namespace Fling diff --git a/FlingEngine/Graphics/src/OcclusionTest.cpp b/FlingEngine/Graphics/src/OcclusionTest.cpp new file mode 100644 index 00000000..48c95124 --- /dev/null +++ b/FlingEngine/Graphics/src/OcclusionTest.cpp @@ -0,0 +1,140 @@ +#include "OcclusionTest.h" + +#include +#include + +namespace Fling +{ + uint32 DepthPyramid::LevelsFor(const uint32 t_Width, const uint32 t_Height) + { + uint32 Size = std::max({t_Width, t_Height, 1u}); + uint32 Levels = 1; + while (Size > 1) + { + Size >>= 1; + ++Levels; + } + return Levels; + } + + void DepthPyramid::Build(const std::span t_Depth, const uint32 t_Width, const uint32 t_Height) + { + m_Levels.clear(); + if (t_Width == 0 || t_Height == 0 || t_Depth.size() < size_t{t_Width} * t_Height) + { + return; + } + + Level Base; + Base.Width = t_Width; + Base.Height = t_Height; + Base.Texels.assign(t_Depth.begin(), t_Depth.begin() + size_t{t_Width} * t_Height); + m_Levels.push_back(std::move(Base)); + + const uint32 Count = LevelsFor(t_Width, t_Height); + for (uint32 L = 1; L < Count; ++L) + { + const Level& Src = m_Levels[L - 1]; + Level Dst; + Dst.Width = NextSize(Src.Width); + Dst.Height = NextSize(Src.Height); + Dst.Texels.resize(size_t{Dst.Width} * Dst.Height); + for (uint32 y = 0; y < Dst.Height; ++y) + { + for (uint32 x = 0; x < Dst.Width; ++x) + { + const uint32 X0 = x * 2; + const uint32 Y0 = y * 2; + const uint32 X1 = (x == Dst.Width - 1) ? Src.Width - 1 : X0 + 1; + const uint32 Y1 = (y == Dst.Height - 1) ? Src.Height - 1 : Y0 + 1; + float Farthest = 0.0f; + for (uint32 sy = Y0; sy <= Y1; ++sy) + { + for (uint32 sx = X0; sx <= X1; ++sx) + { + Farthest = std::max(Farthest, Src.Texels[size_t{sy} * Src.Width + sx]); + } + } + Dst.Texels[size_t{y} * Dst.Width + x] = Farthest; + } + } + m_Levels.push_back(std::move(Dst)); + } + } + + namespace Occlusion + { + ScreenBounds ProjectBounds(const Aabb& t_Local, const glm::mat4& t_World, const glm::mat4& t_ViewProjection) + { + ScreenBounds Result; + if (!t_Local.IsValid()) + { + return Result; + } + + const glm::mat4 Mvp = t_ViewProjection * t_World; + glm::vec2 Min{1.0e30f}; + glm::vec2 Max{-1.0e30f}; + float Nearest = 1.0e30f; + for (uint32 i = 0; i < 8; ++i) + { + const glm::vec3 Corner{(i & 1u) ? t_Local.Max.x : t_Local.Min.x, + (i & 2u) ? t_Local.Max.y : t_Local.Min.y, + (i & 4u) ? t_Local.Max.z : t_Local.Min.z}; + const glm::vec4 Clip = Mvp * glm::vec4(Corner, 1.0f); + if (Clip.w <= 1.0e-4f) + { + return Result; + } + const glm::vec2 Uv = glm::vec2(Clip.x, Clip.y) / Clip.w * 0.5f + 0.5f; + Min = glm::min(Min, Uv); + Max = glm::max(Max, Uv); + Nearest = std::min(Nearest, Clip.z / Clip.w); + } + + Result.MinUv = glm::clamp(Min, glm::vec2(0.0f), glm::vec2(1.0f)); + Result.MaxUv = glm::clamp(Max, glm::vec2(0.0f), glm::vec2(1.0f)); + Result.NearDepth = std::max(Nearest, 0.0f); + Result.Testable = true; + return Result; + } + + bool IsOccluded(const DepthPyramid& t_Pyramid, const ScreenBounds& t_Bounds) + { + if (!t_Bounds.Testable || t_Pyramid.LevelCount() == 0) + { + return false; + } + + const float W = static_cast(t_Pyramid.Width(0)); + const float H = static_cast(t_Pyramid.Height(0)); + const int32 MaxX = static_cast(t_Pyramid.Width(0)) - 1; + const int32 MaxY = static_cast(t_Pyramid.Height(0)) - 1; + const int32 X0 = std::clamp(static_cast(std::floor(t_Bounds.MinUv.x * W)), 0, MaxX); + const int32 X1 = std::clamp(static_cast(std::floor(t_Bounds.MaxUv.x * W)), 0, MaxX); + const int32 Y0 = std::clamp(static_cast(std::floor(t_Bounds.MinUv.y * H)), 0, MaxY); + const int32 Y1 = std::clamp(static_cast(std::floor(t_Bounds.MaxUv.y * H)), 0, MaxY); + + // The level where the rectangle covers at most 2 x 2 texels + const int32 Span = std::max(X1 - X0, Y1 - Y0) + 1; + uint32 Level = 0; + while ((1 << Level) < Span && Level + 1 < t_Pyramid.LevelCount()) + { + ++Level; + } + + const int32 LX1 = static_cast(t_Pyramid.Width(Level)) - 1; + const int32 LY1 = static_cast(t_Pyramid.Height(Level)) - 1; + float Farthest = 0.0f; + for (int32 y = std::min(Y0 >> Level, LY1); y <= std::min(Y1 >> Level, LY1); ++y) + { + for (int32 x = std::min(X0 >> Level, LX1); x <= std::min(X1 >> Level, LX1); ++x) + { + Farthest = + std::max(Farthest, t_Pyramid.Texel(Level, static_cast(x), static_cast(y))); + } + } + return t_Bounds.NearDepth > Farthest + DepthBias; + } + } // namespace Occlusion +} // namespace Fling diff --git a/FlingEngine/Graphics/src/OffscreenSubpass.cpp b/FlingEngine/Graphics/src/OffscreenSubpass.cpp index d664fe0a..d3838198 100644 --- a/FlingEngine/Graphics/src/OffscreenSubpass.cpp +++ b/FlingEngine/Graphics/src/OffscreenSubpass.cpp @@ -23,7 +23,9 @@ namespace Fling const Swapchain* t_Swap, FirstPersonCamera* t_Cam, std::shared_ptr t_Vert, - std::shared_ptr t_Frag) + std::shared_ptr t_Frag, + std::shared_ptr t_HizDownsample, + std::shared_ptr t_HizCull) : Subpass(t_Dev, t_Swap, t_Vert, t_Frag), m_Camera(t_Cam) { // Set the clear values for the G Buffer @@ -60,10 +62,17 @@ namespace Fling // Tell the Vulkan app that the draw command buffers need to WAIT on this offscreen semaphore PrepareAttachments(); + + if (t_HizDownsample && t_HizCull) + { + m_Occlusion = std::make_unique(m_Device, t_HizDownsample, t_HizCull); + SetOcclusionDepth(); + } } OffscreenSubpass::~OffscreenSubpass() { + m_Occlusion.reset(); // Destroy any allocated semaphores for (size_t i = 0; i < m_OffscreenSemaphores.size(); ++i) { @@ -103,6 +112,20 @@ namespace Fling // The previous frame is done on the GPU, so the resources of destroyed meshes can go ReleaseRetiredMeshResources(); + const bool bOcclusion = OcclusionActive(); + if (m_Occlusion) + { + m_Occlusion->ReleaseRetired(); + } + // The GPU counted the hidden meshes of the previous frame + m_OccludedCount = bOcclusion ? m_Occlusion->ReadOccludedCount() : 0; + if (bOcclusion != m_RecordedOcclusion) + { + // The recordings hold either one pass or the two phase passes + InvalidateCommandBuffers(); + m_RecordedOcclusion = bOcclusion; + } + // The meshes in this frame's snapshot: new ones get a proxy, gone ones release theirs SyncProxies(t_Snapshot); @@ -119,7 +142,20 @@ namespace Fling CullMeshes(t_Snapshot); UpdateMeshUniformBuffers(t_Snapshot); - WriteDrawCommands(); + if (bOcclusion) + { + // The GPU writes the draw commands, from the slot data and this frame's camera + if (m_Occlusion->EnsureCapacity(m_DrawCommandCapacity, m_DrawCommands)) + { + InvalidateCommandBuffers(); + } + WriteOcclusionSlots(t_Snapshot); + m_Occlusion->WriteParams(m_CameraViewProjection, static_cast(m_GpuMeshes.size())); + } + else + { + WriteDrawCommands(); + } // The command buffer holds only draw calls and descriptor bindings, not // UBO data. Keep the last recording if the draw list did not change. @@ -209,6 +245,41 @@ namespace Fling m_Culler.Cull(t_Snapshot.Meshes, m_ItemSlots, m_FrustumCulling ? &View : nullptr); } + void OffscreenSubpass::WriteOcclusionSlots(const RenderSnapshot& t_Snapshot) + { + OcclusionSlot* Slots = m_Occlusion->MappedSlots(); + for (uint32 Slot = 0; Slot < m_GpuMeshes.size(); ++Slot) + { + const GpuMesh& Mesh = m_GpuMeshes[Slot]; + Slots[Slot].Info = glm::uvec4(IsDrawable(Mesh) ? Mesh.MeshModel->GetIndexCount() : 0u, 0u, 0u, 0u); + } + for (size_t i = 0; i < t_Snapshot.Meshes.size() && i < m_ItemSlots.size(); ++i) + { + const uint32 Slot = m_ItemSlots[i]; + const GpuMesh& Mesh = m_GpuMeshes[Slot]; + if (!IsDrawable(Mesh)) + { + continue; + } + const Aabb& Bounds = Mesh.MeshModel->GetLocalBounds(); + OcclusionSlot& Out = Slots[Slot]; + Out.World = t_Snapshot.Meshes[i].World; + Out.BoundsMin = glm::vec4(Bounds.Min, 0.0f); + Out.BoundsMax = glm::vec4(Bounds.Max, 0.0f); + Out.Info.y = (m_Culler.IsVisible(Slot) ? OcclusionSlot::InView : 0u) | + (Bounds.IsValid() ? OcclusionSlot::HasBounds : 0u); + } + } + + void OffscreenSubpass::SetOcclusionDepth() + { + // The depth is the last attachment of the offscreen frame buffer + FrameBufferAttachment* Depth = m_OffscreenFrameBuf->GetAttachmentAtIndex(5); + assert(Depth); + m_Occlusion->SetDepth( + Depth->GetViewHandle(), m_OffscreenFrameBuf->GetWidth(), m_OffscreenFrameBuf->GetHeight(), Depth->GetFormat()); + } + void OffscreenSubpass::EnsureDrawCommandCapacity() { const size_t Needed = std::max(m_GpuMeshes.size(), 1); @@ -229,7 +300,7 @@ namespace Fling } const VkDeviceSize Size = sizeof(VkDrawIndexedIndirectCommand) * Capacity; m_DrawCommands = new Buffer(Size, - VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); m_DrawCommands->MapMemory(Size); m_DrawCommandCapacity = Capacity; @@ -281,27 +352,8 @@ namespace Fling } } - void OffscreenSubpass::BuildOffscreenCommandBuffer(CommandBuffer& t_CmdBuf) + void OffscreenSubpass::RecordDraws(CommandBuffer& t_CmdBuf, const Buffer& t_Commands) { - // Set viewport and scissors to the offscreen frame buffer - VkViewport viewport = Initializers::Viewport(static_cast(m_OffscreenFrameBuf->GetWidth()), - static_cast(m_OffscreenFrameBuf->GetHeight()), - 0.0f, - 1.0f); - - VkRect2D scissor = Initializers::Rect2D(m_OffscreenFrameBuf->GetWidth(), - m_OffscreenFrameBuf->GetHeight(), - /** offsetX */ 0, - /** offsetY */ 0); - - t_CmdBuf.Begin(); - t_CmdBuf.BeginRenderPass(*m_OffscreenFrameBuf, m_ClearValues); - - t_CmdBuf.SetViewport(0, {viewport}); - t_CmdBuf.SetScissor(0, {scissor}); - - vkCmdBindPipeline(t_CmdBuf.GetHandle(), VK_PIPELINE_BIND_POINT_GRAPHICS, m_GraphicsPipeline->GetPipeline()); - VkDeviceSize offsets[1] = {0}; for (uint32 Slot = 0; Slot < m_GpuMeshes.size(); ++Slot) @@ -330,14 +382,58 @@ namespace Fling vkCmdBindIndexBuffer( t_CmdBuf.GetHandle(), Model->GetIndexBuffer()->GetVkBuffer(), 0, Model->GetIndexType()); vkCmdDrawIndexedIndirect(t_CmdBuf.GetHandle(), - m_DrawCommands->GetVkBuffer(), + t_Commands.GetVkBuffer(), sizeof(VkDrawIndexedIndirectCommand) * Slot, 1, sizeof(VkDrawIndexedIndirectCommand)); } + } + void OffscreenSubpass::BuildOffscreenCommandBuffer(CommandBuffer& t_CmdBuf) + { + // Set viewport and scissors to the offscreen frame buffer + VkViewport viewport = Initializers::Viewport(static_cast(m_OffscreenFrameBuf->GetWidth()), + static_cast(m_OffscreenFrameBuf->GetHeight()), + 0.0f, + 1.0f); + + VkRect2D scissor = Initializers::Rect2D(m_OffscreenFrameBuf->GetWidth(), + m_OffscreenFrameBuf->GetHeight(), + /** offsetX */ 0, + /** offsetY */ 0); + + auto BeginDraws = [&]() + { + t_CmdBuf.SetViewport(0, {viewport}); + t_CmdBuf.SetScissor(0, {scissor}); + vkCmdBindPipeline( + t_CmdBuf.GetHandle(), VK_PIPELINE_BIND_POINT_GRAPHICS, m_GraphicsPipeline->GetPipeline()); + }; + + t_CmdBuf.Begin(); + const bool bOcclusion = m_RecordedOcclusion && OcclusionActive(); + if (bOcclusion) + { + // Phase 0: what was visible last frame draws first + m_Occlusion->RecordFirstPhase(t_CmdBuf.GetHandle()); + } + + t_CmdBuf.BeginRenderPass(*m_OffscreenFrameBuf, m_ClearValues); + BeginDraws(); + RecordDraws(t_CmdBuf, *m_DrawCommands); t_CmdBuf.EndRenderPass(); + if (bOcclusion) + { + // Phase 1: test everything in view against the depth of the first draw, then draw + // what it did not hide and was not drawn yet, over the same images + m_Occlusion->RecordSecondPhase(t_CmdBuf.GetHandle()); + t_CmdBuf.BeginLoadRenderPass(*m_OffscreenFrameBuf); + BeginDraws(); + RecordDraws(t_CmdBuf, *m_Occlusion->Draw2()); + t_CmdBuf.EndRenderPass(); + } + t_CmdBuf.End(); } @@ -427,13 +523,15 @@ namespace Fling // Attachment 3: Depth attachmentInfo.Format = attDepthFormat; - attachmentInfo.Usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; + // Sampled, so that the occlusion culling pass can build a depth pyramid from it + attachmentInfo.Usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; m_OffscreenFrameBuf->AddAttachment(attachmentInfo); // Create sampler to sample from the color attachments VK_CHECK_RESULT(m_OffscreenFrameBuf->CreateSampler( VK_FILTER_NEAREST, VK_FILTER_NEAREST, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE)); VK_CHECK_RESULT(m_OffscreenFrameBuf->CreateRenderPass()); + VK_CHECK_RESULT(m_OffscreenFrameBuf->CreateLoadRenderPass()); F_LOG_TRACE("Offscreen render pass created..."); // Create the descriptor pool for off screen things. Each mesh holds one set, so @@ -518,6 +616,7 @@ namespace Fling } m_GpuMeshes.clear(); m_Culler.Clear(); + m_Occlusion.reset(); m_Proxies.Clear(); m_ItemSlots.clear(); ReleaseRetiredMeshResources(); @@ -535,6 +634,11 @@ namespace Fling if (m_OffscreenFrameBuf) { m_OffscreenFrameBuf->ResizeAndRecreate(NewSize.width, NewSize.height); + if (m_Occlusion) + { + // The depth image is new, so the pyramid is made again + SetOcclusionDepth(); + } // The offscreen render pass is new. Rebuild the pipeline that uses it. CreateGraphicsPipeline(); } diff --git a/FlingEngine/Graphics/src/OffscreenSubpass.h b/FlingEngine/Graphics/src/OffscreenSubpass.h index 6156c0b5..8583f771 100644 --- a/FlingEngine/Graphics/src/OffscreenSubpass.h +++ b/FlingEngine/Graphics/src/OffscreenSubpass.h @@ -4,6 +4,7 @@ #include "GpuMesh.h" #include "MeshCuller.h" #include "MeshProxyTable.h" +#include "OcclusionCuller.h" #include "Subpass.h" #include @@ -47,7 +48,9 @@ namespace Fling const Swapchain* t_Swap, FirstPersonCamera* t_Cam, std::shared_ptr t_Vert, - std::shared_ptr t_Frag); + std::shared_ptr t_Frag, + std::shared_ptr t_HizDownsample = nullptr, + std::shared_ptr t_HizCull = nullptr); virtual ~OffscreenSubpass(); @@ -79,8 +82,19 @@ namespace Fling */ void SetFrustumCulling(const bool t_On) { m_FrustumCulling = t_On; } + /** + * Occlusion culling on or off (RunSettings::OcclusionCulling). Takes effect on the next + * Draw. The pass turns it off by itself when it cannot run (see OcclusionCuller). + */ + void SetOcclusionCulling(const bool t_On) { m_OcclusionCulling = t_On; } + /** What the last Draw drew and culled. */ - const CullStats& GetCullStats() const { return m_Culler.Stats(); } + CullStats GetCullStats() const + { + CullStats Stats = m_Culler.Stats(); + Stats.Occluded = m_OccludedCount; + return Stats; + } private: /** @@ -106,6 +120,18 @@ namespace Fling */ void CullMeshes(const RenderSnapshot& t_Snapshot); + /** True if this frame runs the occlusion passes (the setting is on and the device can) */ + bool OcclusionActive() const { return m_OcclusionCulling && m_Occlusion && m_Occlusion->IsSupported(); } + + /** Point the occlusion passes at the depth image of the frame buffer, and make the pyramid for its size */ + void SetOcclusionDepth(); + + /** Write each slot's data for the cull shader (m_Occlusion), from the snapshot and the frustum test */ + void WriteOcclusionSlots(const RenderSnapshot& t_Snapshot); + + /** Record the indirect draws of every drawable slot, from t_Commands, with the pipeline already bound */ + void RecordDraws(CommandBuffer& t_CmdBuf, const Buffer& t_Commands); + /** Make m_DrawCommands hold one command per slot. A new buffer makes the recordings out of date. */ void EnsureDrawCommandCapacity(); @@ -182,6 +208,18 @@ namespace Fling /** @see SetFrustumCulling */ bool m_FrustumCulling = true; + /** @see SetOcclusionCulling */ + bool m_OcclusionCulling = true; + + /** The GPU occlusion passes. Null when the shaders were not given. */ + std::unique_ptr m_Occlusion; + + /** Whether the recordings hold the two phase draw (OcclusionActive when they were made) */ + bool m_RecordedOcclusion = false; + + /** Meshes the GPU found hidden in the previous frame */ + uint32 m_OccludedCount = 0; + /** * Descriptor sets of meshes that are gone. They are freed at the start of the next * Draw. The previous frame has finished on the GPU then, and every command buffer diff --git a/FlingEngine/Graphics/src/VulkanApp.cpp b/FlingEngine/Graphics/src/VulkanApp.cpp index 6ce36e86..6acb31c8 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -422,6 +422,14 @@ namespace Fling } } + void VulkanApp::SetOcclusionCulling(const bool t_On) + { + if (m_MeshPass != nullptr) + { + m_MeshPass->SetOcclusionCulling(t_On); + } + } + CullStats VulkanApp::GetCullStats() const { return m_MeshPass != nullptr ? m_MeshPass->GetCullStats() : CullStats{}; @@ -527,8 +535,12 @@ namespace Fling Shader::Create(AssetPath("Deferred/mrt.vert.spv"), m_LogicalDevice); std::shared_ptr OffscreenFrag = Shader::Create(AssetPath("Deferred/mrt.frag.spv"), m_LogicalDevice); + std::shared_ptr HizDownsample = + Shader::Create(AssetPath("Occlusion/hiz_downsample.comp.spv"), m_LogicalDevice); + std::shared_ptr HizCull = + Shader::Create(AssetPath("Occlusion/cull.comp.spv"), m_LogicalDevice); Subpasses.emplace_back(std::make_unique( - m_LogicalDevice, m_SwapChain, m_Camera, OffscreenVert, OffscreenFrag)); + m_LogicalDevice, m_SwapChain, m_Camera, OffscreenVert, OffscreenFrag, HizDownsample, HizCull)); // Create geometry pass ------ // These shaders do not have any vertex input and do the final processing to the screen diff --git a/FlingEngine/Graphics/src/VulkanFunctions.inl b/FlingEngine/Graphics/src/VulkanFunctions.inl index 059fa01d..cc77cf48 100644 --- a/FlingEngine/Graphics/src/VulkanFunctions.inl +++ b/FlingEngine/Graphics/src/VulkanFunctions.inl @@ -86,10 +86,12 @@ FLING_VK_DEVICE(vkCmdBlitImage) FLING_VK_DEVICE(vkCmdCopyBuffer) FLING_VK_DEVICE(vkCmdCopyBufferToImage) FLING_VK_DEVICE(vkCmdCopyImageToBuffer) +FLING_VK_DEVICE(vkCmdDispatch) FLING_VK_DEVICE(vkCmdDraw) FLING_VK_DEVICE(vkCmdDrawIndexed) FLING_VK_DEVICE(vkCmdDrawIndexedIndirect) FLING_VK_DEVICE(vkCmdEndRenderPass) +FLING_VK_DEVICE(vkCmdFillBuffer) FLING_VK_DEVICE(vkCmdNextSubpass) FLING_VK_DEVICE(vkCmdPipelineBarrier) FLING_VK_DEVICE(vkCmdPushConstants) @@ -97,6 +99,7 @@ FLING_VK_DEVICE(vkCmdSetScissor) FLING_VK_DEVICE(vkCmdSetViewport) FLING_VK_DEVICE(vkCreateBuffer) FLING_VK_DEVICE(vkCreateCommandPool) +FLING_VK_DEVICE(vkCreateComputePipelines) FLING_VK_DEVICE(vkCreateDescriptorPool) FLING_VK_DEVICE(vkCreateDescriptorSetLayout) FLING_VK_DEVICE(vkCreateFence) diff --git a/FlingTests/Core/RunSettingsTests.cpp b/FlingTests/Core/RunSettingsTests.cpp index 5540403a..82111b6c 100644 --- a/FlingTests/Core/RunSettingsTests.cpp +++ b/FlingTests/Core/RunSettingsTests.cpp @@ -39,6 +39,8 @@ TEST_CASE("Run settings: the defaults are threaded play at 30 Hz with VSync and REQUIRE(Settings.InterpolationSource == SettingSource::Default); REQUIRE(Settings.FrustumCulling); REQUIRE(Settings.FrustumCullingSource == SettingSource::Default); + REQUIRE(Settings.OcclusionCulling); + REQUIRE(Settings.OcclusionCullingSource == SettingSource::Default); REQUIRE(Settings.Ignored.empty()); REQUIRE(SimRate::StepNs(Settings.SimHz) == 33'333'333); REQUIRE(SimRate::StepNs(60) == 16'666'667); @@ -117,7 +119,8 @@ TEST_CASE("Run settings: the command line wins over the config file, which wins .MaxFps = "120", .VSync = "off", .Interpolation = "off", - .FrustumCulling = "off"}; + .FrustumCulling = "off", + .OcclusionCulling = "off"}; REQUIRE(Resolve({}, Config, Settings, Error)); REQUIRE(Settings.Exec == ExecMode::Direct); @@ -132,6 +135,8 @@ TEST_CASE("Run settings: the command line wins over the config file, which wins REQUIRE(Settings.InterpolationSource == SettingSource::Config); REQUIRE_FALSE(Settings.FrustumCulling); REQUIRE(Settings.FrustumCullingSource == SettingSource::Config); + REQUIRE_FALSE(Settings.OcclusionCulling); + REQUIRE(Settings.OcclusionCullingSource == SettingSource::Config); REQUIRE(Resolve({"--exec", "inline", @@ -144,6 +149,8 @@ TEST_CASE("Run settings: the command line wins over the config file, which wins "--interpolation", "on", "--frustum-culling", + "on", + "--occlusion-culling", "on"}, Config, Settings, @@ -151,14 +158,14 @@ TEST_CASE("Run settings: the command line wins over the config file, which wins Settings.ResolveFrameCap(144u); REQUIRE(Settings.Describe() == "tick rate 20 Hz (command line), exec inline (command line), frame cap 75 fps " "(command line), vsync on (command line), interpolation on (command line), " - "frustum culling on (command line)"); + "frustum culling on (command line), occlusion culling on (command line)"); // A key with no value is the default REQUIRE(Resolve({}, RunSettingsConfig{}, Settings, Error)); Settings.ResolveFrameCap(144u); REQUIRE(Settings.Describe() == "tick rate 30 Hz (default), exec threaded (default), frame cap 144 fps (the " "monitor's refresh rate), vsync on (default), interpolation on (default), " - "frustum culling on (default)"); + "frustum culling on (default), occlusion culling on (default)"); } TEST_CASE("Run settings: every config key is read by its name", "[RunSettings]") @@ -169,6 +176,7 @@ TEST_CASE("Run settings: every config key is read by its name", "[RunSettings]") {"VSync", "off"}, {"Interpolation", "off"}, {"FrustumCulling", "off"}, + {"OcclusionCulling", "off"}, {"PresentMode", "mailbox"}}; const RunSettingsConfig Config = RunSettingsConfig::Read( [&File](const char* t_Key) @@ -182,6 +190,7 @@ TEST_CASE("Run settings: every config key is read by its name", "[RunSettings]") REQUIRE(Config.VSync == "off"); REQUIRE(Config.Interpolation == "off"); REQUIRE(Config.FrustumCulling == "off"); + REQUIRE(Config.OcclusionCulling == "off"); } TEST_CASE("Run settings: a bad value in a config key is an error, also when a flag wins over it", "[RunSettings]") @@ -219,6 +228,9 @@ TEST_CASE("Run settings: a bad value in a config key is an error, also when a fl Fails(Args({"--frustum-culling", "on"}), {.FrustumCulling = "yes"}, "[Engine] FrustumCulling in EngineConf.ini must be on or off"); + Fails(Args({"--occlusion-culling", "on"}), + {.OcclusionCulling = "yes"}, + "[Engine] OcclusionCulling in EngineConf.ini must be on or off"); } } @@ -282,6 +294,22 @@ TEST_CASE("Run settings: --frustum-culling with --null-render does nothing, and REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--frustum-culling")); } +TEST_CASE("Run settings: --occlusion-culling with --null-render does nothing, and says so; --offscreen draws", + "[RunSettings]") +{ + RunSettings Settings; + String Error; + REQUIRE(Resolve({"--null-render", "--occlusion-culling", "off"}, {}, Settings, Error)); + REQUIRE_FALSE(Settings.OcclusionCulling); + REQUIRE(Settings.Ignored == + std::vector{"--occlusion-culling does nothing with --null-render: nothing is drawn"}); + REQUIRE(Resolve({"--offscreen", "--occlusion-culling", "off"}, {}, Settings, Error)); + REQUIRE(Settings.Ignored.empty()); + LaunchOptions Options; + REQUIRE_FALSE(TestArgs::ParseLaunchArgs({"--occlusion-culling", "maybe"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--occlusion-culling")); +} + TEST_CASE("Run settings: the frame limiter keeps the lower of the cap and the display's refresh rate", "[RunSettings]") { SECTION("The display does not pace the frames (VSync off): the cap, whatever the display") diff --git a/FlingTests/Engine/RunControlsTests.cpp b/FlingTests/Engine/RunControlsTests.cpp index 12ef1af1..dbdc1f2a 100644 --- a/FlingTests/Engine/RunControlsTests.cpp +++ b/FlingTests/Engine/RunControlsTests.cpp @@ -39,10 +39,12 @@ TEST_CASE("Run controls: the live values start from the startup settings, which RunSettings Settings = OnMonitor(60); Settings.VSync = false; Settings.FrustumCulling = false; + Settings.OcclusionCulling = false; const RunSettings Startup = Settings; RunControls Controls(Settings, Harness.GetWorld()); REQUIRE_FALSE(Controls.VSync()); REQUIRE_FALSE(Controls.FrustumCulling()); + REQUIRE_FALSE(Controls.OcclusionCulling()); REQUIRE(Controls.MaxFps() == 60); REQUIRE(Controls.MonitorHz() == 60u); @@ -51,12 +53,15 @@ TEST_CASE("Run controls: the live values start from the startup settings, which REQUIRE(Controls.SetMaxFps(90, Error)); Controls.SetInterpolation(false); Controls.SetFrustumCulling(true); + Controls.SetOcclusionCulling(true); REQUIRE(Controls.VSync()); REQUIRE(Controls.MaxFps() == 90); REQUIRE(Controls.FrustumCulling()); + REQUIRE(Controls.OcclusionCulling()); REQUIRE(Settings.Describe() == Startup.Describe()); REQUIRE_FALSE(Settings.VSync); REQUIRE_FALSE(Settings.FrustumCulling); + REQUIRE_FALSE(Settings.OcclusionCulling); } TEST_CASE("Run controls: the frame cap takes 0 to 1000, and an error is cleared by the next good value", diff --git a/FlingTests/Graphics/OcclusionCullingTests.cpp b/FlingTests/Graphics/OcclusionCullingTests.cpp new file mode 100644 index 00000000..0992302e --- /dev/null +++ b/FlingTests/Graphics/OcclusionCullingTests.cpp @@ -0,0 +1,237 @@ +#include "FlingMath.h" +#include "OcclusionTest.h" +#include "SimRandom.h" + +#include +#include +#include +#include + +using namespace Fling; + +namespace +{ + constexpr uint32 Size = 64; + + glm::mat4 ViewProjection(const glm::vec3& t_Eye, const glm::vec3& t_Target) + { + glm::mat4 Projection = glm::perspective(glm::radians(80.0f), 1.0f, 0.1f, 200.0f); + Projection[1][1] *= -1.0f; + return Projection * glm::lookAt(t_Eye, t_Target, glm::vec3(0.0f, 1.0f, 0.0f)); + } + + struct Box + { + Aabb Local; + glm::mat4 World{1.0f}; + }; + + /** A pixel ray: the world positions at depth 0 and depth 1 of the pixel centre */ + struct Ray + { + glm::vec3 Origin; + glm::vec3 Dir; + }; + + Ray PixelRay(const glm::mat4& t_InverseVp, const uint32 t_X, const uint32 t_Y) + { + const float Nx = (static_cast(t_X) + 0.5f) / Size * 2.0f - 1.0f; + const float Ny = (static_cast(t_Y) + 0.5f) / Size * 2.0f - 1.0f; + auto Unproject = [&](const float t_Z) + { + const glm::vec4 P = t_InverseVp * glm::vec4(Nx, Ny, t_Z, 1.0f); + return glm::vec3(P) / P.w; + }; + const glm::vec3 Near = Unproject(0.0f); + return {Near, glm::normalize(Unproject(1.0f) - Near)}; + } + + /** The depth (0 to 1) where the ray first meets the box, or a negative number for a miss */ + float HitDepth(const Box& t_Box, const Ray& t_Ray, const glm::mat4& t_Vp) + { + const glm::mat4 Inverse = glm::inverse(t_Box.World); + const glm::vec3 O = glm::vec3(Inverse * glm::vec4(t_Ray.Origin, 1.0f)); + const glm::vec3 D = glm::vec3(Inverse * glm::vec4(t_Ray.Dir, 0.0f)); + float T0 = 0.0f; + float T1 = std::numeric_limits::max(); + for (int Axis = 0; Axis < 3; ++Axis) + { + if (std::abs(D[Axis]) < 1.0e-9f) + { + if (O[Axis] < t_Box.Local.Min[Axis] || O[Axis] > t_Box.Local.Max[Axis]) + { + return -1.0f; + } + continue; + } + float A = (t_Box.Local.Min[Axis] - O[Axis]) / D[Axis]; + float B = (t_Box.Local.Max[Axis] - O[Axis]) / D[Axis]; + if (A > B) + { + std::swap(A, B); + } + T0 = std::max(T0, A); + T1 = std::min(T1, B); + if (T0 > T1) + { + return -1.0f; + } + } + const glm::vec4 Clip = t_Vp * glm::vec4(t_Ray.Origin + t_Ray.Dir * T0, 1.0f); + return Clip.z / Clip.w; + } + + float Random(SimRandom& t_Rng, const float t_Lo, const float t_Hi) + { + return t_Lo + (t_Hi - t_Lo) * t_Rng.NextFloat01(); + } +} // namespace + +TEST_CASE("DepthPyramid keeps the farthest depth under each texel", "[Occlusion]") +{ + SimRandom Rng(7, 1); + for (const auto& [W, H] : std::vector>{{8, 8}, {5, 3}, {1, 7}, {13, 1}, {64, 33}, {1, 1}}) + { + std::vector Depth(size_t{W} * H); + for (float& D : Depth) + { + D = Rng.NextFloat01(); + } + DepthPyramid Pyramid; + Pyramid.Build(Depth, W, H); + REQUIRE(Pyramid.LevelCount() == DepthPyramid::LevelsFor(W, H)); + REQUIRE(Pyramid.Width(Pyramid.LevelCount() - 1) == 1); + REQUIRE(Pyramid.Height(Pyramid.LevelCount() - 1) == 1); + + // The last level is the farthest depth of the whole image + REQUIRE(Pyramid.Texel(Pyramid.LevelCount() - 1, 0, 0) == *std::max_element(Depth.begin(), Depth.end())); + + // Every texel of the image is covered by a texel of each level that is at least as far + for (uint32 L = 1; L < Pyramid.LevelCount(); ++L) + { + for (uint32 y = 0; y < H; ++y) + { + for (uint32 x = 0; x < W; ++x) + { + const uint32 Lx = std::min(x >> L, Pyramid.Width(L) - 1); + const uint32 Ly = std::min(y >> L, Pyramid.Height(L) - 1); + REQUIRE(Pyramid.Texel(L, Lx, Ly) >= Depth[size_t{y} * W + x]); + } + } + } + } +} + +TEST_CASE("A wall hides a box behind it and not a box in front of it", "[Occlusion]") +{ + const glm::mat4 Vp = ViewProjection(glm::vec3(0.0f), glm::vec3(0.0f, 0.0f, -1.0f)); + const glm::mat4 InverseVp = glm::inverse(Vp); + + Box Wall; + Wall.Local = Aabb::Of(std::vector{{-3, -3, -0.5f}, {3, 3, 0.5f}}); + Wall.World = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -10.0f)); + + std::vector Depth(size_t{Size} * Size, 1.0f); + for (uint32 y = 0; y < Size; ++y) + { + for (uint32 x = 0; x < Size; ++x) + { + const float D = HitDepth(Wall, PixelRay(InverseVp, x, y), Vp); + if (D >= 0.0f) + { + Depth[size_t{y} * Size + x] = D; + } + } + } + DepthPyramid Pyramid; + Pyramid.Build(Depth, Size, Size); + + const Aabb Unit = Aabb::Of(std::vector{{-0.5f, -0.5f, -0.5f}, {0.5f, 0.5f, 0.5f}}); + const auto Test = [&](const glm::vec3& t_At) + { + return Occlusion::IsOccluded(Pyramid, + Occlusion::ProjectBounds(Unit, glm::translate(glm::mat4(1.0f), t_At), Vp)); + }; + + CHECK(Test(glm::vec3(0.0f, 0.0f, -20.0f))); + CHECK(Test(glm::vec3(2.0f, 1.0f, -30.0f))); + CHECK_FALSE(Test(glm::vec3(0.0f, 0.0f, -5.0f))); + // Beside the wall, in the clear + CHECK_FALSE(Test(glm::vec3(10.0f, 0.0f, -20.0f))); + // Reaching the plane of the camera: never hidden + CHECK_FALSE(Test(glm::vec3(0.0f, 0.0f, 0.0f))); + CHECK_FALSE(Test(glm::vec3(0.0f, 0.0f, 3.0f))); + // A box that is not known + CHECK_FALSE(Occlusion::IsOccluded(Pyramid, Occlusion::ProjectBounds(Aabb{}, glm::mat4(1.0f), Vp))); +} + +TEST_CASE("Occlusion never hides a mesh that can be seen", "[Occlusion]") +{ + SimRandom Rng(2024, 1); + uint32 Hidden = 0; + uint32 Tested = 0; + + for (uint32 Trial = 0; Trial < 150; ++Trial) + { + // A random scene of boxes, turned and scaled, and a random camera + std::vector Boxes(24); + for (Box& B : Boxes) + { + const glm::vec3 Half{Random(Rng, 0.2f, 4.0f), Random(Rng, 0.2f, 4.0f), Random(Rng, 0.2f, 1.5f)}; + B.Local = Aabb::Of(std::vector{-Half, Half}); + B.World = + glm::translate( + glm::mat4(1.0f), + glm::vec3(Random(Rng, -25.0f, 25.0f), Random(Rng, -10.0f, 10.0f), Random(Rng, -60.0f, 5.0f))) * + glm::rotate(glm::mat4(1.0f), Random(Rng, 0.0f, 6.28f), glm::vec3(0.0f, 1.0f, 0.0f)); + } + const glm::vec3 Eye{Random(Rng, -8.0f, 8.0f), Random(Rng, -3.0f, 3.0f), Random(Rng, 0.0f, 12.0f)}; + const glm::vec3 Target{Random(Rng, -10.0f, 10.0f), Random(Rng, -5.0f, 5.0f), Random(Rng, -50.0f, -10.0f)}; + const glm::mat4 Vp = ViewProjection(Eye, Target); + const glm::mat4 InverseVp = glm::inverse(Vp); + + // The depth image of every box, a box included: the least that a pyramid could hold + std::vector Depth(size_t{Size} * Size, 1.0f); + std::vector> Own(Boxes.size(), std::vector(size_t{Size} * Size, -1.0f)); + for (uint32 y = 0; y < Size; ++y) + { + for (uint32 x = 0; x < Size; ++x) + { + const Ray R = PixelRay(InverseVp, x, y); + for (size_t i = 0; i < Boxes.size(); ++i) + { + const float D = HitDepth(Boxes[i], R, Vp); + Own[i][size_t{y} * Size + x] = D; + if (D >= 0.0f) + { + Depth[size_t{y} * Size + x] = std::min(Depth[size_t{y} * Size + x], D); + } + } + } + } + DepthPyramid Pyramid; + Pyramid.Build(Depth, Size, Size); + + for (size_t i = 0; i < Boxes.size(); ++i) + { + ++Tested; + if (!Occlusion::IsOccluded(Pyramid, Occlusion::ProjectBounds(Boxes[i].Local, Boxes[i].World, Vp))) + { + continue; + } + ++Hidden; + // Hidden: the box must not be the nearest thing at any pixel where it is hit + for (size_t p = 0; p < Depth.size(); ++p) + { + if (Own[i][p] >= 0.0f) + { + INFO("trial " << Trial << " box " << i << " pixel " << p); + REQUIRE(Own[i][p] > Depth[p]); + } + } + } + } + // The test is not empty: some boxes were hidden and some were not + CHECK(Hidden > 20); + CHECK(Hidden < Tested); +} diff --git a/FlingTests/Resources/RunSettingsConfigTests.cpp b/FlingTests/Resources/RunSettingsConfigTests.cpp index 89e4bfcf..e5af4a81 100644 --- a/FlingTests/Resources/RunSettingsConfigTests.cpp +++ b/FlingTests/Resources/RunSettingsConfigTests.cpp @@ -15,7 +15,8 @@ TEST_CASE("Run settings: the [Engine] keys of an ini file reach the run settings const std::filesystem::path Path = std::filesystem::temp_directory_path() / "fling_run_settings_test.ini"; { std::ofstream File(Path, std::ios::trunc); - File << "[Engine]\nExec=inline\nSimHz=60\nMaxFps=90\nVSync=off\nInterpolation=off\nFrustumCulling=off\n"; + File << "[Engine]\nExec=inline\nSimHz=60\nMaxFps=90\nVSync=off\nInterpolation=off\nFrustumCulling=" + "off\nOcclusionCulling=off\n"; } REQUIRE(FlingConfig::Get().LoadConfigFile(Path.string())); @@ -25,7 +26,8 @@ TEST_CASE("Run settings: the [Engine] keys of an ini file reach the run settings RunSettings Settings; String Error; REQUIRE(RunSettings::Resolve(LaunchOptions{}, Config, Settings, Error)); - REQUIRE(Settings.Describe() == "tick rate 60 Hz (config), exec inline (config), frame cap 90 fps (config), vsync " - "off (config), interpolation off (config), frustum culling off (config)"); + REQUIRE(Settings.Describe() == + "tick rate 60 Hz (config), exec inline (config), frame cap 90 fps (config), vsync " + "off (config), interpolation off (config), frustum culling off (config), occlusion culling off (config)"); std::filesystem::remove(Path); }