From 08231dfb8c883b6e25396fcaca9a5ffec141b0d3 Mon Sep 17 00:00:00 2001 From: Matthew Zegar Date: Mon, 12 Oct 2026 00:17:05 -0700 Subject: [PATCH] Frusting culling --- CMakeLists.txt | 2 + docs/roadmap.md | 8 +-- shaders/common.slang | 18 +++++- shaders/cull.slang | 76 +++++++++++++++++++++++ shaders/scene.slang | 9 ++- shaders/shadow.slang | 9 ++- src/app.cpp | 29 +++++++-- src/app.h | 4 ++ src/render/cull_pass.cpp | 119 +++++++++++++++++++++++++++++++++++++ src/render/cull_pass.h | 83 ++++++++++++++++++++++++++ src/render/scene_draws.cpp | 36 ++++++++--- src/render/scene_draws.h | 5 ++ src/render/scene_pass.cpp | 4 +- src/render/scene_pass.h | 8 ++- src/scene/camera.cpp | 4 +- src/scene/camera.h | 18 +++++- src/scene/scene.cpp | 27 +++++++++ src/scene/scene.h | 16 +++++ src/ui/panels.cpp | 48 ++++++++++++--- src/ui/panels.h | 12 ++-- src/vk/buffer.h | 2 +- src/vk/device.cpp | 3 +- src/vk/frame_resources.cpp | 6 ++ src/vk/frame_resources.h | 2 + src/vk/sync.h | 7 +++ 25 files changed, 507 insertions(+), 48 deletions(-) create mode 100644 shaders/cull.slang create mode 100644 src/render/cull_pass.cpp create mode 100644 src/render/cull_pass.h diff --git a/CMakeLists.txt b/CMakeLists.txt index c52df8a..d9968d1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -54,6 +54,8 @@ add_executable(vkdriven src/platform/window.h src/profiling/benchmark.cpp src/profiling/benchmark.h + src/render/cull_pass.cpp + src/render/cull_pass.h src/render/scene_draws.cpp src/render/scene_draws.h src/render/scene_pass.cpp diff --git a/docs/roadmap.md b/docs/roadmap.md index 1fff48a..a44e6c6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -101,16 +101,13 @@ Follow [LearnOpenGL](https://learnopengl.com/)'s *Advanced Lighting* and *PBR* c - [x] **Cascaded shadow maps**: cascade splits, a layered depth image, cascade selection (*Guest Articles → Cascaded Shadow Mapping*). Beyond the tutorial: texel snapping to stop shimmering, and normal-offset bias. ### P4: GPU-driven rendering (~50h, 10 weeks). ★ The main feature -- [ ] **Compute frustum culling** per instance → writes a compacted draw list -- [ ] `vkCmdDrawIndexedIndirectCount`: the whole scene in one draw call +- [x] **Compute frustum culling** per instance → writes a compacted draw list +- [x] `vkCmdDrawIndexedIndirectCount`: the whole scene in one draw call - [ ] **Hi-Z depth pyramid** (compute downsample, min/max reduction) - [ ] **Two-pass occlusion culling**: draw last frame's visible objects, build Hi-Z, cull the rest, draw the newly visible ones - [ ] Add **meshoptimizer**. **Meshlets** built with `meshopt_buildMeshlets`. - [ ] **Mesh shaders** (`VK_EXT_mesh_shader`): task shader does per-meshlet frustum, occlusion, and **cone backface** culling; mesh shader outputs triangles -- [ ] Fallback path without mesh shaders (meshlet index buffer + indirect draw), so it runs on all hardware - [ ] Simple LOD (meshoptimizer `simplify`) chosen per instance in the culling shader -- [ ] Stress scene: 100k–1M instances (a procedurally scattered city or forest), or a large CAD-like assembly with heavy instancing -- [ ] ImGui: counts of instances, meshlets, and triangles submitted vs. culled, and time per pass - [ ] 📝 Blog: "GPU-driven culling: from N draw calls to 1". Include CPU time, GPU time, and triangle counts before and after. ### P5: Profiling case studies (~20h, alongside P3 onward) @@ -120,7 +117,6 @@ Follow [LearnOpenGL](https://learnopengl.com/)'s *Advanced Lighting* and *PBR* c - [ ] Write 2–3 case studies, each laid out as "this pass was slow → here's the capture → here's why → here's the fix → here's the new number". Candidates: - [ ] Culling shader occupancy (changing workgroup size, register usage) - [ ] Shadow pass cost vs. cascade count and resolution - - [ ] Mesh shader path vs. indirect-draw path, on one or more GPUs - [ ] (Optional) PNG vs. KTX2/BC7 textures (`KHR_texture_basisu`, transcoded with KTX-Software): VRAM, load time and frame time - [ ] 📝 Blog: one post per case study diff --git a/shaders/common.slang b/shaders/common.slang index 43957ab..bda07fc 100644 --- a/shaders/common.slang +++ b/shaders/common.slang @@ -22,6 +22,8 @@ public struct FrameData public float normalOffset; public uint showCascades; public uint environmentTextureIndex; + // World space, normals pointing inwards: p is on the inside when dot(plane.xyz, p) + plane.w >= 0. + public float4 frustumPlanes[6]; }; public struct Material @@ -37,6 +39,21 @@ public struct Material public uint padding; }; +public struct BoundingSphere +{ + public float3 center; + public float radius; +}; + +public struct Primitive +{ + public BoundingSphere bounds; + public uint firstIndex; + public uint indexCount; + public int vertexOffset; + public uint materialIndex; +}; + public struct Draw { public uint primitiveIndex; @@ -56,7 +73,6 @@ public struct DrawConstants public Draw* draws; public Transform* transforms; public Material* materials; - public uint drawIndex; public uint cascadeIndex; }; diff --git a/shaders/cull.slang b/shaders/cull.slang new file mode 100644 index 0000000..264e74f --- /dev/null +++ b/shaders/cull.slang @@ -0,0 +1,76 @@ +import common; + +// Laid out like VkDrawIndexedIndirectCommand. firstInstance carries the draw's index, so the scene shaders +// can still find their Draw once there's no per-draw push constant. +struct DrawCommand +{ + uint indexCount; + uint instanceCount; + uint firstIndex; + int vertexOffset; + uint firstInstance; +}; + +struct CullConstants +{ + FrameData* frame; + Draw* draws; + Transform* transforms; + Primitive* primitives; + DrawCommand* commands; + uint* commandCount; + uint drawCount; +}; + +[[vk::push_constant]] CullConstants cull; + +// Scaled by the largest axis scale, so the sphere still contains the mesh under non-uniform scale. +BoundingSphere WorldBounds(BoundingSphere bounds, float4x4 model) +{ + float3 axisScales = float3(length(mul(model, float4(1.0, 0.0, 0.0, 0.0)).xyz), + length(mul(model, float4(0.0, 1.0, 0.0, 0.0)).xyz), + length(mul(model, float4(0.0, 0.0, 1.0, 0.0)).xyz)); + BoundingSphere world; + world.center = mul(model, float4(bounds.center, 1.0)).xyz; + world.radius = bounds.radius * max(axisScales.x, max(axisScales.y, axisScales.z)); + return world; +} + +// Only rejects spheres entirely outside a single plane. A sphere near a frustum corner can be outside two +// planes at once without being fully outside either, and passes; that only costs a wasted draw. +bool IsInFrustum(BoundingSphere sphere) +{ + for (uint plane = 0; plane < 6; plane++) + { + float4 frustumPlane = cull.frame->frustumPlanes[plane]; + if (dot(frustumPlane.xyz, sphere.center) + frustumPlane.w < -sphere.radius) + return false; + } + return true; +} + +[shader("compute")] +[numthreads(64, 1, 1)] +void main(uint3 threadId: SV_DispatchThreadID) +{ + uint drawIndex = threadId.x; + if (drawIndex >= cull.drawCount) + return; + + Draw draw = cull.draws[drawIndex]; + Primitive primitive = cull.primitives[draw.primitiveIndex]; + BoundingSphere sphere = WorldBounds(primitive.bounds, cull.transforms[draw.transformIndex].model); + if (!IsInFrustum(sphere)) + return; + + uint slot; + InterlockedAdd(*cull.commandCount, 1, slot); + + DrawCommand command; + command.indexCount = primitive.indexCount; + command.instanceCount = 1; + command.firstIndex = primitive.firstIndex; + command.vertexOffset = primitive.vertexOffset; + command.firstInstance = drawIndex; + cull.commands[slot] = command; +} diff --git a/shaders/scene.slang b/shaders/scene.slang index a46caa4..9a43b24 100644 --- a/shaders/scene.slang +++ b/shaders/scene.slang @@ -9,12 +9,14 @@ struct VSOutput float3 Normal; float2 UV; float4 Tangent; + nointerpolation uint DrawIndex; }; +// Every draw has one instance whose firstInstance is the draw's index, so the instance index is the draw index. [shader("vertex")] -VSOutput main(VSInput input) +VSOutput main(VSInput input, uint drawIndex: SV_VulkanInstanceID) { - Draw draw = constants.draws[constants.drawIndex]; + Draw draw = constants.draws[drawIndex]; Transform transform = constants.transforms[draw.transformIndex]; float4x4 view = constants.frame->view; float4x4 projection = constants.frame->projection; @@ -29,6 +31,7 @@ VSOutput main(VSInput input) output.UV = input.UV; // Tangents lie along the surface, so they transform with the model matrix, not the normal matrix. output.Tangent = float4(mul((float3x3)transform.model, input.Tangent.xyz), input.Tangent.w); + output.DrawIndex = drawIndex; return output; } @@ -157,7 +160,7 @@ float3 Specular(float3 N, float3 V, float3 L, float3 H, float3 F, float roughnes [shader("fragment")] float4 main(VSOutput input) { - Draw draw = constants.draws[constants.drawIndex]; + Draw draw = constants.draws[input.DrawIndex]; Material material = constants.materials[draw.materialIndex]; float4 baseColor = material.baseColorFactor * textures[material.baseColorTextureIndex].Sample(input.UV); if (baseColor.a < material.alphaCutoff) diff --git a/shaders/shadow.slang b/shaders/shadow.slang index 9348131..a241b23 100644 --- a/shaders/shadow.slang +++ b/shaders/shadow.slang @@ -4,18 +4,21 @@ struct VSOutput { float4 Pos : SV_POSITION; float2 UV; + nointerpolation uint DrawIndex; }; +// Every draw has one instance whose firstInstance is the draw's index, so the instance index is the draw index. [shader("vertex")] -VSOutput main(VSInput input) +VSOutput main(VSInput input, uint drawIndex: SV_VulkanInstanceID) { - Draw draw = constants.draws[constants.drawIndex]; + Draw draw = constants.draws[drawIndex]; Transform transform = constants.transforms[draw.transformIndex]; VSOutput output; float4x4 lightViewProjection = constants.frame->lightViewProjections[constants.cascadeIndex]; output.Pos = mul(lightViewProjection, mul(transform.model, float4(input.Pos, 1.0))); output.UV = input.UV; + output.DrawIndex = drawIndex; return output; } @@ -23,7 +26,7 @@ VSOutput main(VSInput input) [shader("fragment")] void main(VSOutput input) { - Draw draw = constants.draws[constants.drawIndex]; + Draw draw = constants.draws[input.DrawIndex]; Material material = constants.materials[draw.materialIndex]; float alpha = material.baseColorFactor.a * textures[material.baseColorTextureIndex].Sample(input.UV).a; if (alpha < material.alphaCutoff) diff --git a/src/app.cpp b/src/app.cpp index 5d8b17e..544c483 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -8,6 +8,7 @@ #include "vk/check.h" #include +#include #include #include #include @@ -34,6 +35,7 @@ App::App(RunMode mode) environment_{orThrow(Texture::loadHdr(device_, allocator_, commandPool_, environmentPath))}, bindlessTextures_{device_, static_cast(scene_.textures().size()) + 3}, pipelineCache_{device_, pipelineCachePath}, shaderDirectory_{VKDRIVEN_SHADER_DIR}, + cullPass_{device_, allocator_, shaderCompiler_, pipelineCache_, scene_, shaderDirectory_ / "cull.slang"}, shadowPass_{device_, allocator_, shaderCompiler_, pipelineCache_, bindlessTextures_, shaderDirectory_ / "shadow.slang"}, scenePass_{device_, shaderCompiler_, pipelineCache_, bindlessTextures_, shaderDirectory_ / "scene.slang", @@ -88,6 +90,7 @@ void App::run() if (shaderWatcher_.poll() || reloadRequested_) { reloadRequested_ = false; + cullPass_.reloadShaders(); shadowPass_.reloadShaders(); scenePass_.reloadShaders(); tonemapPass_.reloadShaders(); @@ -148,11 +151,12 @@ bool App::handleEvents() void App::drawUi() { const ImGuiID dockspace = ImGui::DockSpaceOverViewport(); - const ViewportPanelState viewportPanel = drawViewportPanel(dockspace, viewport_); + const ViewportPanelState viewportPanel = drawViewportPanel(dockspace, viewport_, camera_, cullSettings_); if (viewportPanel.requestedExtent) requestedViewportExtent_ = *viewportPanel.requestedExtent; viewportHovered_ = viewportPanel.hovered; - drawStatsPanel(scene_, viewport_, camera_, gpuTimings_, cpuRecordMilliseconds_, benchmark_); + drawStatsPanel(scene_, viewport_, gpuTimings_, visibleDrawCount_, cpuRecordMilliseconds_, benchmark_); + drawCameraPanel(camera_, cullSettings_); drawLightPanel(light_); drawShadowPanel(shadowSettings_); drawTonemapPanel(tonemapSettings_); @@ -173,6 +177,10 @@ void App::drawFrame() for (auto [smoothed, latest] : std::views::zip(gpuTimings_, latestTimings)) smoothed.milliseconds = std::lerp(smoothed.milliseconds, latest.milliseconds, 0.05f); + std::array visibleDrawCount{}; + frame.visibleDrawCount.read(visibleDrawCount); + visibleDrawCount_ = visibleDrawCount[0]; + // Acquire next image const auto [acquireStatus, imageIndex] = swapchain_.acquireNextImage(frame.imageAcquired.get()); if (acquireStatus == SwapchainStatus::OutOfDate) @@ -228,8 +236,12 @@ void App::updateFrameData(Frame& frame) const const ShadowCascades cascades = computeShadowCascades(camera_, aspect, light_.directionToLight(), shadowSettings_); - const FrameData frameData{.view = camera_.view(), - .projection = camera_.projection(aspect), + const glm::mat4 view = camera_.view(); + const glm::mat4 projection = camera_.projection(aspect); + const glm::mat4 cullProjection = + camera_.projection(aspect, camera_.nearPlane(), camera_.farPlane(), cullSettings_.fovScale); + const FrameData frameData{.view = view, + .projection = projection, .directionToLight = glm::vec4{light_.directionToLight(), 0.0f}, .cameraPosition = glm::vec4{camera_.worldPosition(), 0.0f}, .lightRadiance = glm::vec4{light_.radiance(), 0.0f}, @@ -239,7 +251,8 @@ void App::updateFrameData(Frame& frame) const .shadowMapTextureIndex = shadowMapTextureIndex(), .normalOffset = shadowSettings_.normalOffset, .showCascades = shadowSettings_.showCascades ? 1u : 0u, - .environmentTextureIndex = environmentTextureIndex()}; + .environmentTextureIndex = environmentTextureIndex(), + .frustumPlanes = frustumPlanes(cullProjection * view)}; frame.shaderData.write(std::span{&frameData, 1}); } @@ -254,12 +267,16 @@ void App::recordCommandBuffer(VkCommandBuffer cb, uint32_t imageIndex, Frame& fr timer.reset(cb); const uint32_t frameScope = timer.begin(cb, "Frame"); + const uint32_t cullScope = timer.begin(cb, "Cull"); + cullPass_.record(cb, scene_, frame.shaderData.deviceAddress(), frame.visibleDrawCount); + timer.end(cb, cullScope); + const uint32_t shadowScope = timer.begin(cb, "Shadows"); shadowPass_.record(cb, scene_, frame.shaderData.deviceAddress(), shadowSettings_); timer.end(cb, shadowScope); const uint32_t sceneScope = timer.begin(cb, "Scene"); - scenePass_.record(cb, viewport_, scene_, frame.shaderData.deviceAddress()); + scenePass_.record(cb, viewport_, scene_, frame.shaderData.deviceAddress(), cullPass_); timer.end(cb, sceneScope); const uint32_t tonemapScope = timer.begin(cb, "Tonemap"); diff --git a/src/app.h b/src/app.h index 5101f21..afad77b 100644 --- a/src/app.h +++ b/src/app.h @@ -7,6 +7,7 @@ #include "platform/file_watcher.h" #include "platform/window.h" #include "profiling/benchmark.h" +#include "render/cull_pass.h" #include "render/scene_pass.h" #include "render/shadow_pass.h" #include "render/tonemap_pass.h" @@ -92,6 +93,7 @@ class App ShaderCompiler shaderCompiler_; PipelineCache pipelineCache_; std::filesystem::path shaderDirectory_; + CullPass cullPass_; ShadowPass shadowPass_; ScenePass scenePass_; TonemapPass tonemapPass_; @@ -101,9 +103,11 @@ class App Camera camera_{glm::vec3{-8.0f, 2.0f, 0.0f}, glm::radians(90.0f), 0.0f}; DirectionalLight light_; + CullSettings cullSettings_; ShadowSettings shadowSettings_; TonemapSettings tonemapSettings_; std::vector gpuTimings_; + uint32_t visibleDrawCount_{0}; float cpuRecordMilliseconds_{0.0f}; Benchmark benchmark_; glm::vec2 mouseDelta_{}; diff --git a/src/render/cull_pass.cpp b/src/render/cull_pass.cpp new file mode 100644 index 0000000..479b5b8 --- /dev/null +++ b/src/render/cull_pass.cpp @@ -0,0 +1,119 @@ +#include "render/cull_pass.h" + +#include "scene/scene.h" +#include "util/expected.h" +#include "vk/device.h" +#include "vk/pipeline_cache.h" +#include "vk/shader_compiler.h" +#include "vk/sync.h" + +#include +#include + +static_assert(sizeof(VkDrawIndexedIndirectCommand) == 20, "Must match DrawCommand in shaders/cull.slang"); + +// A clip-space point is inside when -w <= x <= w, -w <= y <= w and 0 <= z <= w. Each of those six +// inequalities is a plane: with rows r of viewProjection, x <= w becomes dot(r3 - r0, p) >= 0 (Gribb-Hartmann). +std::array frustumPlanes(const glm::mat4& viewProjection) +{ + const glm::mat4 rows = glm::transpose(viewProjection); + std::array planes{rows[3] + rows[0], rows[3] - rows[0], rows[3] + rows[1], + rows[3] - rows[1], rows[2], rows[3] - rows[2]}; + for (glm::vec4& plane : planes) + plane /= glm::length(glm::vec3{plane}); + return planes; +} + +CullPass::CullPass(const Device& device, const Allocator& allocator, const ShaderCompiler& shaderCompiler, + const PipelineCache& pipelineCache, const Scene& scene, std::filesystem::path shaderPath) + : device_{device}, shaderCompiler_{shaderCompiler}, pipelineCache_{pipelineCache}, + shaderPath_{std::move(shaderPath)}, pipeline_{orThrow(build())}, + commands_{allocator, scene.draws().size() * sizeof(VkDrawIndexedIndirectCommand), + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT}, + count_{allocator, sizeof(uint32_t), + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | + VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT} +{ +} + +void CullPass::reloadShaders() +{ + auto reloadedPipeline = build(); + if (!reloadedPipeline) + { + std::println(stderr, "{}", reloadedPipeline.error()); + return; + } + device_.waitIdle(); + pipeline_ = std::move(*reloadedPipeline); + std::println("Reloaded {}", shaderPath_.string()); +} + +std::expected CullPass::build() const +{ + return shaderCompiler_.compile(device_, shaderPath_) + .transform( + [&](const DeviceHandle& shaderModule) + { + return ComputePipeline{device_, pipelineCache_.handle(), shaderModule.get(), + {.pushConstantSize = sizeof(CullConstants)}}; + }); +} + +void CullPass::record(VkCommandBuffer cb, const Scene& scene, VkDeviceAddress frameData, + const Buffer& visibleDrawCount) const +{ + // Both buffers are reused every frame. The previous frame's cull shader wrote them, and its draws and count + // copy read them, so all of that has to finish before the count is reset and the commands are rewritten. + pipelineBarrier(cb, VkMemoryBarrier2{.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT | + VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT | + VK_PIPELINE_STAGE_2_COPY_BIT, + .srcAccessMask = VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, + .dstStageMask = + VK_PIPELINE_STAGE_2_CLEAR_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, + .dstAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT | + VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT}); + vkCmdFillBuffer(cb, count_.handle(), 0, sizeof(uint32_t), 0); + + // The cull shader's atomic add reads and writes the count, so the zero has to land first. + pipelineBarrier(cb, VkMemoryBarrier2{.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_CLEAR_BIT, + .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, + .dstAccessMask = VK_ACCESS_2_SHADER_STORAGE_READ_BIT | + VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT}); + + const auto drawCount = static_cast(scene.draws().size()); + const CullConstants constants{.frame = frameData, + .draws = scene.drawBufferAddress(), + .transforms = scene.transformBufferAddress(), + .primitives = scene.primitiveBufferAddress(), + .commands = commands_.deviceAddress(), + .commandCount = count_.deviceAddress(), + .drawCount = drawCount}; + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_.handle()); + vkCmdPushConstants(cb, pipeline_.layout(), VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(CullConstants), &constants); + vkCmdDispatch(cb, (drawCount + workgroupSize - 1) / workgroupSize, 1, 1); + + // The scene pass's indirect draw reads the commands and the count as draw parameters, which happens in + // the draw-indirect stage at the very start of the graphics pipeline, not in a shader. The count is also + // copied out for the CPU. + pipelineBarrier(cb, VkMemoryBarrier2{.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, + .srcAccessMask = VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, + .dstStageMask = + VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_2_COPY_BIT, + .dstAccessMask = VK_ACCESS_2_INDIRECT_COMMAND_READ_BIT | + VK_ACCESS_2_TRANSFER_READ_BIT}); + + const VkBufferCopy countCopy{.size = sizeof(uint32_t)}; + vkCmdCopyBuffer(cb, count_.handle(), visibleDrawCount.handle(), 1, &countCopy); + + // Waiting on the frame's fence doesn't by itself make the copy visible to the host. + pipelineBarrier(cb, VkMemoryBarrier2{.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_COPY_BIT, + .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_HOST_BIT, + .dstAccessMask = VK_ACCESS_2_HOST_READ_BIT}); +} diff --git a/src/render/cull_pass.h b/src/render/cull_pass.h new file mode 100644 index 0000000..d28d095 --- /dev/null +++ b/src/render/cull_pass.h @@ -0,0 +1,83 @@ +#pragma once + +#include + +#include + +#include "vk/buffer.h" +#include "vk/compute_pipeline.h" + +#include +#include +#include +#include +#include + +class Allocator; +class Device; +class PipelineCache; +class Scene; +class ShaderCompiler; + +// Below 1, the cull frustum is narrower than the one the camera renders with, so draws visibly get culled +// before they reach the screen edges. +struct CullSettings +{ + float fovScale{1.0f}; + bool showFrustum{true}; +}; + +struct CullConstants +{ + VkDeviceAddress frame; + VkDeviceAddress draws; + VkDeviceAddress transforms; + VkDeviceAddress primitives; + VkDeviceAddress commands; + VkDeviceAddress commandCount; + uint32_t drawCount; +}; + +// The six planes bounding what viewProjection maps into clip space, in the space it maps from, with normals +// pointing inwards. Order: the two x planes, the two y planes, then the two depth planes. +std::array frustumPlanes(const glm::mat4& viewProjection); + +// Tests every draw's bounding sphere against the camera frustum on the GPU, and writes a +// VkDrawIndexedIndirectCommand for each visible one plus how many there are, ready for an indirect draw. +// Throws std::runtime_error from the constructor if the shader fails to compile. +class CullPass +{ + public: + static constexpr uint32_t workgroupSize = 64; + + CullPass(const Device& device, const Allocator& allocator, const ShaderCompiler& shaderCompiler, + const PipelineCache& pipelineCache, const Scene& scene, std::filesystem::path shaderPath); + + // Keeps the current pipeline if the shader fails to compile. + void reloadShaders(); + + // Also copies the visible count into visibleDrawCount, a host-visible buffer the CPU reads after the fence. + void record(VkCommandBuffer cb, const Scene& scene, VkDeviceAddress frameData, + const Buffer& visibleDrawCount) const; + + [[nodiscard]] VkBuffer commandBuffer() const + { + return commands_.handle(); + } + + [[nodiscard]] VkBuffer countBuffer() const + { + return count_.handle(); + } + + private: + [[nodiscard]] std::expected build() const; + + const Device& device_; + const ShaderCompiler& shaderCompiler_; + const PipelineCache& pipelineCache_; + std::filesystem::path shaderPath_; + ComputePipeline pipeline_; + Buffer commands_; + Buffer count_; +}; diff --git a/src/render/scene_draws.cpp b/src/render/scene_draws.cpp index e6ca6a8..d40bbf7 100644 --- a/src/render/scene_draws.cpp +++ b/src/render/scene_draws.cpp @@ -1,16 +1,19 @@ #include "render/scene_draws.h" +#include "render/cull_pass.h" #include "render/scene_pass.h" #include "scene/scene.h" #include "vk/bindless_textures.h" #include "vk/shader_pipeline.h" -#include #include #include -void recordSceneDraws(VkCommandBuffer cb, const ShaderPipeline& pipeline, const BindlessTextures& textures, - const Scene& scene, VkDeviceAddress frameData, uint32_t cascadeIndex) +namespace +{ + +void bindScene(VkCommandBuffer cb, const ShaderPipeline& pipeline, const BindlessTextures& textures, + const Scene& scene, VkDeviceAddress frameData, uint32_t cascadeIndex) { vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.handle()); const VkDescriptorSet textureSet = textures.set(); @@ -20,20 +23,37 @@ void recordSceneDraws(VkCommandBuffer cb, const ShaderPipeline& pipeline, const vkCmdBindVertexBuffers(cb, 0, 1, &vertexBuffer, &vertexOffset); vkCmdBindIndexBuffer(cb, scene.indexBuffer(), 0, Scene::indexType); - constexpr VkShaderStageFlags pushStages = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; const DrawConstants constants{.frame = frameData, .draws = scene.drawBufferAddress(), .transforms = scene.transformBufferAddress(), .materials = scene.materialBufferAddress(), .cascadeIndex = cascadeIndex}; - vkCmdPushConstants(cb, pipeline.layout(), pushStages, 0, sizeof(DrawConstants), &constants); + vkCmdPushConstants(cb, pipeline.layout(), VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(DrawConstants), &constants); +} + +} // namespace + +// firstInstance carries the draw's index to the shaders, the same way the cull pass's indirect commands do. +void recordSceneDraws(VkCommandBuffer cb, const ShaderPipeline& pipeline, const BindlessTextures& textures, + const Scene& scene, VkDeviceAddress frameData, uint32_t cascadeIndex) +{ + bindScene(cb, pipeline, textures, scene, frameData, cascadeIndex); const std::span draws = scene.draws(); for (uint32_t drawIndex = 0; drawIndex < draws.size(); drawIndex++) { const Primitive& primitive = scene.primitives()[draws[drawIndex].primitiveIndex]; - vkCmdPushConstants(cb, pipeline.layout(), pushStages, offsetof(DrawConstants, drawIndex), sizeof(drawIndex), - &drawIndex); - vkCmdDrawIndexed(cb, primitive.indexCount, 1, primitive.firstIndex, primitive.vertexOffset, 0); + vkCmdDrawIndexed(cb, primitive.indexCount, 1, primitive.firstIndex, primitive.vertexOffset, drawIndex); } } + +// The GPU reads how many commands to run from the count buffer, capped at one per draw in the scene. +void recordCulledSceneDraws(VkCommandBuffer cb, const ShaderPipeline& pipeline, const BindlessTextures& textures, + const Scene& scene, VkDeviceAddress frameData, const CullPass& cullPass) +{ + bindScene(cb, pipeline, textures, scene, frameData, 0); + vkCmdDrawIndexedIndirectCount(cb, cullPass.commandBuffer(), 0, cullPass.countBuffer(), 0, + static_cast(scene.draws().size()), + sizeof(VkDrawIndexedIndirectCommand)); +} diff --git a/src/render/scene_draws.h b/src/render/scene_draws.h index df2c184..495a47a 100644 --- a/src/render/scene_draws.h +++ b/src/render/scene_draws.h @@ -3,6 +3,7 @@ #include class BindlessTextures; +class CullPass; class Scene; class ShaderPipeline; @@ -13,3 +14,7 @@ class ShaderPipeline; // cascadeIndex selects the light matrix when drawing into a shadow cascade. void recordSceneDraws(VkCommandBuffer cb, const ShaderPipeline& pipeline, const BindlessTextures& textures, const Scene& scene, VkDeviceAddress frameData, uint32_t cascadeIndex = 0); + +// The same, but only draws what the cull pass found visible, with one indirect draw. +void recordCulledSceneDraws(VkCommandBuffer cb, const ShaderPipeline& pipeline, const BindlessTextures& textures, + const Scene& scene, VkDeviceAddress frameData, const CullPass& cullPass); diff --git a/src/render/scene_pass.cpp b/src/render/scene_pass.cpp index d12fb40..d965263 100644 --- a/src/render/scene_pass.cpp +++ b/src/render/scene_pass.cpp @@ -34,7 +34,7 @@ ScenePass::ScenePass(const Device& device, const ShaderCompiler& shaderCompiler, } void ScenePass::record(VkCommandBuffer cb, const ViewportTarget& target, const Scene& scene, - VkDeviceAddress frameData) const + VkDeviceAddress frameData, const CullPass& cullPass) const { const VkExtent2D extent = target.extent(); @@ -86,7 +86,7 @@ void ScenePass::record(VkCommandBuffer cb, const ViewportTarget& target, const S setViewportAndScissor(cb, extent); - recordSceneDraws(cb, pipeline_, textures_, scene, frameData); + recordCulledSceneDraws(cb, pipeline_, textures_, scene, frameData, cullPass); // After the scene, so the depth test skips every pixel the geometry already covers. vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, skyboxPipeline_.handle()); diff --git a/src/render/scene_pass.h b/src/render/scene_pass.h index ff2d8f0..ea5c5c9 100644 --- a/src/render/scene_pass.h +++ b/src/render/scene_pass.h @@ -12,6 +12,7 @@ #include class BindlessTextures; +class CullPass; class Device; class Scene; class PipelineCache; @@ -33,9 +34,10 @@ struct FrameData float normalOffset; uint32_t showCascades; uint32_t environmentTextureIndex; + std::array frustumPlanes; }; static_assert(ShadowPass::cascadeCount == 4, "cascadeSplitDepths and cascadeTexelSizes hold one float per cascade"); -static_assert(sizeof(FrameData) == 480); +static_assert(sizeof(FrameData) == 576); struct DrawConstants { @@ -43,7 +45,6 @@ struct DrawConstants VkDeviceAddress draws; VkDeviceAddress transforms; VkDeviceAddress materials; - uint32_t drawIndex; uint32_t cascadeIndex; }; @@ -63,7 +64,8 @@ class ScenePass skyboxPipeline_.reload(); } - void record(VkCommandBuffer cb, const ViewportTarget& target, const Scene& scene, VkDeviceAddress frameData) const; + void record(VkCommandBuffer cb, const ViewportTarget& target, const Scene& scene, VkDeviceAddress frameData, + const CullPass& cullPass) const; private: const BindlessTextures& textures_; diff --git a/src/scene/camera.cpp b/src/scene/camera.cpp index a96c3bf..c7c5c62 100644 --- a/src/scene/camera.cpp +++ b/src/scene/camera.cpp @@ -94,10 +94,10 @@ glm::mat4 Camera::projection(float aspect) const return projection(aspect, nearPlane_, farPlane_); } -glm::mat4 Camera::projection(float aspect, float sliceNear, float sliceFar) const +glm::mat4 Camera::projection(float aspect, float sliceNear, float sliceFar, float fovScale) const { // Reverse-Z: near and far are swapped so depth 1 is the near plane and 0 is the far plane. - glm::mat4 projection = glm::perspective(verticalFovRadians_, aspect, sliceFar, sliceNear); + glm::mat4 projection = glm::perspective(verticalFovRadians_ * fovScale, aspect, sliceFar, sliceNear); // glTF is +Y up but Vulkan's clip space has +Y pointing down the screen. projection[1][1] *= -1.0f; return projection; diff --git a/src/scene/camera.h b/src/scene/camera.h index bc36699..e6dc228 100644 --- a/src/scene/camera.h +++ b/src/scene/camera.h @@ -18,7 +18,8 @@ class Camera [[nodiscard]] glm::mat4 view() const; [[nodiscard]] glm::mat4 projection(float aspect) const; // The same projection cut down to view depths [sliceNear, sliceFar], e.g. to find a shadow cascade's slice. - [[nodiscard]] glm::mat4 projection(float aspect, float sliceNear, float sliceFar) const; + // fovScale narrows (below 1) or widens the field of view. + [[nodiscard]] glm::mat4 projection(float aspect, float sliceNear, float sliceFar, float fovScale = 1.0f) const; [[nodiscard]] glm::vec3 worldPosition() const; [[nodiscard]] float yawRadians() const @@ -39,6 +40,21 @@ class Camera return nearPlane_; } + [[nodiscard]] float farPlane() const + { + return farPlane_; + } + + [[nodiscard]] float verticalFovRadians() const + { + return verticalFovRadians_; + } + + void setVerticalFovRadians(float verticalFovRadians) + { + verticalFovRadians_ = verticalFovRadians; + } + private: [[nodiscard]] bool updateLooking(const Window& window, bool viewportHovered); [[nodiscard]] glm::vec3 forward() const; diff --git a/src/scene/scene.cpp b/src/scene/scene.cpp index 2f85e0c..026ac60 100644 --- a/src/scene/scene.cpp +++ b/src/scene/scene.cpp @@ -9,9 +9,11 @@ #include "scene/vertex.h" #include "vk/upload.h" +#include #include #include #include +#include #include #include #include @@ -59,6 +61,28 @@ void generateSmoothNormals(std::span vertices, std::span } } +// Centered on the bounding box and reaching the farthest vertex. Not the smallest possible sphere, but close +// enough for culling and a single pass over the vertices. +BoundingSphere computeBoundingSphere(std::span vertices) +{ + if (vertices.empty()) + return {}; + + glm::vec3 min{std::numeric_limits::max()}; + glm::vec3 max{std::numeric_limits::lowest()}; + for (const Vertex& vertex : vertices) + { + min = glm::min(min, vertex.pos); + max = glm::max(max, vertex.pos); + } + + const glm::vec3 center = (min + max) * 0.5f; + float radius = 0.0f; + for (const Vertex& vertex : vertices) + radius = std::max(radius, glm::distance(center, vertex.pos)); + return {.center = center, .radius = radius}; +} + } // namespace std::expected Scene::loadGltf(const Device& device, const Allocator& allocator, @@ -204,6 +228,7 @@ std::expected Scene::loadGltf(const Device& device, const Al std::span{indices}.subspan(firstIndex)); primitives.push_back({ + .bounds = computeBoundingSphere(std::span{vertices}.subspan(firstVertex)), .firstIndex = static_cast(firstIndex), .indexCount = static_cast(indexAccessor.count), .vertexOffset = static_cast(firstVertex), @@ -251,6 +276,8 @@ std::expected Scene::loadGltf(const Device& device, const Al scene.indexBuffer_ = uploadDeviceLocalBuffer(allocator, commandPool, indices, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); scene.materialBuffer_ = uploadDeviceLocalBuffer(allocator, commandPool, materials, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); + scene.primitiveBuffer_ = + uploadDeviceLocalBuffer(allocator, commandPool, primitives, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); scene.drawBuffer_ = uploadDeviceLocalBuffer(allocator, commandPool, scene.draws_, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); scene.transformBuffer_ = diff --git a/src/scene/scene.h b/src/scene/scene.h index f173b1a..753b8de 100644 --- a/src/scene/scene.h +++ b/src/scene/scene.h @@ -19,15 +19,25 @@ class Allocator; class CommandPool; class Device; +// In the primitive's own (mesh) space; a draw's transform takes it to world space. +struct BoundingSphere +{ + glm::vec3 center{0.0f}; + float radius{0.0f}; +}; + // One draw's worth of geometry: a range in the scene's shared index buffer, plus the offset added // to every index so it points at this primitive's vertices in the shared vertex buffer. +// Uploaded to the GPU as-is, so it must match Primitive in shaders/common.slang. struct Primitive { + BoundingSphere bounds; uint32_t firstIndex{0}; uint32_t indexCount{0}; int32_t vertexOffset{0}; uint32_t materialIndex{0}; }; +static_assert(sizeof(Primitive) == 32); constexpr uint32_t whiteSrgbTextureIndex = 0; constexpr uint32_t whiteLinearTextureIndex = 1; @@ -130,6 +140,11 @@ class Scene return draws_; } + [[nodiscard]] VkDeviceAddress primitiveBufferAddress() const + { + return primitiveBuffer_.deviceAddress(); + } + [[nodiscard]] VkDeviceAddress drawBufferAddress() const { return drawBuffer_.deviceAddress(); @@ -161,6 +176,7 @@ class Scene Buffer vertexBuffer_; Buffer indexBuffer_; Buffer materialBuffer_; + Buffer primitiveBuffer_; Buffer drawBuffer_; Buffer transformBuffer_; std::vector primitives_; diff --git a/src/ui/panels.cpp b/src/ui/panels.cpp index e313d1a..01361f7 100644 --- a/src/ui/panels.cpp +++ b/src/ui/panels.cpp @@ -3,6 +3,7 @@ #include #include "profiling/benchmark.h" +#include "render/cull_pass.h" #include "render/shadow_pass.h" #include "render/tonemap_pass.h" #include "scene/camera.h" @@ -14,9 +15,30 @@ #include #include #include +#include #include -ViewportPanelState drawViewportPanel(ImGuiID dockspace, const ViewportTarget& viewport) +namespace +{ + +// The cull frustum shares the camera's position and direction, so from the camera its side planes are a centered +// rectangle on screen. The fraction of the screen it covers is the ratio of the two frustums' tan(fov / 2), and +// it's the same horizontally because both use the same aspect ratio. +void drawCullFrustumOverlay(ImVec2 imageMin, ImVec2 imageMax, const Camera& camera, float fovScale) +{ + const float halfFov = camera.verticalFovRadians() / 2.0f; + const float coverage = std::tan(halfFov * fovScale) / std::tan(halfFov); + const ImVec2 center{(imageMin.x + imageMax.x) / 2.0f, (imageMin.y + imageMax.y) / 2.0f}; + const ImVec2 halfSize{(imageMax.x - imageMin.x) / 2.0f * coverage, (imageMax.y - imageMin.y) / 2.0f * coverage}; + ImGui::GetWindowDrawList()->AddRect({center.x - halfSize.x, center.y - halfSize.y}, + {center.x + halfSize.x, center.y + halfSize.y}, IM_COL32(255, 200, 0, 255), + 0.0f, ImDrawFlags_None, 2.0f); +} + +} // namespace + +ViewportPanelState drawViewportPanel(ImGuiID dockspace, const ViewportTarget& viewport, const Camera& camera, + const CullSettings& cullSettings) { ViewportPanelState state; @@ -34,6 +56,8 @@ ViewportPanelState drawViewportPanel(ImGuiID dockspace, const ViewportTarget& vi const float scale = std::min({available.x / imageSize.x, available.y / imageSize.y, 1.0f}); ImGui::Image(viewport.texture(), ImVec2{imageSize.x * scale, imageSize.y * scale}); state.hovered = ImGui::IsItemHovered(); + if (cullSettings.showFrustum && cullSettings.fovScale < 1.0f) + drawCullFrustumOverlay(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), camera, cullSettings.fovScale); } ImGui::End(); ImGui::PopStyleVar(); @@ -41,8 +65,8 @@ ViewportPanelState drawViewportPanel(ImGuiID dockspace, const ViewportTarget& vi return state; } -void drawStatsPanel(const Scene& scene, const ViewportTarget& viewport, const Camera& camera, - std::span gpuTimings, float cpuRecordMilliseconds, const Benchmark& benchmark) +void drawStatsPanel(const Scene& scene, const ViewportTarget& viewport, std::span gpuTimings, + uint32_t visibleDrawCount, float cpuRecordMilliseconds, const Benchmark& benchmark) { const ImGuiIO& io = ImGui::GetIO(); ImGui::Begin(ICON_FA_CHART_SIMPLE " Stats###Stats"); @@ -57,14 +81,24 @@ void drawStatsPanel(const Scene& scene, const ViewportTarget& viewport, const Ca for (const GpuTiming& timing : gpuTimings) ImGui::Text(" %-8s %5.2f ms", timing.name, timing.milliseconds); ImGui::Separator(); - ImGui::Text("Draws: %zu", scene.draws().size()); + ImGui::Text("Draws: %u visible / %zu", visibleDrawCount, scene.draws().size()); ImGui::Text("Primitives: %zu", scene.primitives().size()); ImGui::Text("Vertices: %zu", static_cast(scene.vertexCount())); ImGui::Text("Indices: %zu", static_cast(scene.indexCount())); + ImGui::End(); +} + +void drawCameraPanel(Camera& camera, CullSettings& cullSettings) +{ + ImGui::Begin(ICON_FA_VIDEO " Camera###Camera"); + float verticalFovRadians = camera.verticalFovRadians(); + if (ImGui::SliderAngle("Vertical FOV", &verticalFovRadians, 20.0f, 120.0f)) + camera.setVerticalFovRadians(verticalFovRadians); ImGui::Separator(); - const glm::vec3 position = camera.worldPosition(); - ImGui::Text("Camera: %.2f, %.2f, %.2f", position.x, position.y, position.z); - ImGui::Text("Yaw %.1f, pitch %.1f", glm::degrees(camera.yawRadians()), glm::degrees(camera.pitchRadians())); + ImGui::SliderFloat("Cull FOV scale", &cullSettings.fovScale, 0.1f, 1.0f, "%.2f"); + ImGui::Checkbox("Show cull frustum", &cullSettings.showFrustum); + ImGui::SetItemTooltip("Culls with a narrower frustum than the camera renders with, so culled draws vanish " + "on screen instead of just past its edges."); ImGui::End(); } diff --git a/src/ui/panels.h b/src/ui/panels.h index 3e6b9c1..5701832 100644 --- a/src/ui/panels.h +++ b/src/ui/panels.h @@ -4,6 +4,7 @@ #include +#include #include #include @@ -11,6 +12,7 @@ class Benchmark; class Camera; class Scene; class ViewportTarget; +struct CullSettings; struct DirectionalLight; struct ShadowSettings; struct TonemapSettings; @@ -23,11 +25,13 @@ struct ViewportPanelState bool hovered{false}; }; -// Shows the viewport image. -ViewportPanelState drawViewportPanel(ImGuiID dockspace, const ViewportTarget& viewport); +// Shows the viewport image, outlined with the cull frustum when it's narrower than the camera's. +ViewportPanelState drawViewportPanel(ImGuiID dockspace, const ViewportTarget& viewport, const Camera& camera, + const CullSettings& cullSettings); // Shows a progress bar while the benchmark (run with --benchmark) is going. -void drawStatsPanel(const Scene& scene, const ViewportTarget& viewport, const Camera& camera, - std::span gpuTimings, float cpuRecordMilliseconds, const Benchmark& benchmark); +void drawStatsPanel(const Scene& scene, const ViewportTarget& viewport, std::span gpuTimings, + uint32_t visibleDrawCount, float cpuRecordMilliseconds, const Benchmark& benchmark); +void drawCameraPanel(Camera& camera, CullSettings& cullSettings); void drawLightPanel(DirectionalLight& light); void drawShadowPanel(ShadowSettings& settings); void drawTonemapPanel(TonemapSettings& settings); diff --git a/src/vk/buffer.h b/src/vk/buffer.h index 9d1ddbe..962088a 100644 --- a/src/vk/buffer.h +++ b/src/vk/buffer.h @@ -27,7 +27,7 @@ class Buffer template void write(const Range& data, VkDeviceSize offset = 0) { - write(std::as_bytes(std::span{data}), offset); + write(std::as_bytes(std::span>{data}), offset); } void read(std::span bytes, VkDeviceSize offset = 0) const; diff --git a/src/vk/device.cpp b/src/vk/device.cpp index 0bc3669..337a935 100644 --- a/src/vk/device.cpp +++ b/src/vk/device.cpp @@ -113,6 +113,7 @@ Device::Device(const Instance& instance, const Surface& surface) const auto deviceExtensions = std::to_array({VK_KHR_SWAPCHAIN_EXTENSION_NAME}); VkPhysicalDeviceVulkan12Features enabledVk12Features{.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, + .drawIndirectCount = true, .descriptorIndexing = true, .shaderSampledImageArrayNonUniformIndexing = true, .descriptorBindingVariableDescriptorCount = true, @@ -124,7 +125,7 @@ Device::Device(const Instance& instance, const Surface& surface) .synchronization2 = true, .dynamicRendering = true, }; - VkPhysicalDeviceFeatures enabledVk10Features{.samplerAnisotropy = VK_TRUE}; + VkPhysicalDeviceFeatures enabledVk10Features{.drawIndirectFirstInstance = VK_TRUE, .samplerAnisotropy = VK_TRUE}; VkDeviceCreateInfo deviceCI{.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, .pNext = &enabledVk13Features, diff --git a/src/vk/frame_resources.cpp b/src/vk/frame_resources.cpp index e21aed9..3a4ca92 100644 --- a/src/vk/frame_resources.cpp +++ b/src/vk/frame_resources.cpp @@ -5,6 +5,8 @@ #include "vk/device.h" #include "vk/sync.h" +#include +#include #include FrameResources::FrameResources(const Device& device, const Allocator& allocator, const CommandPool& commandPool, @@ -16,6 +18,10 @@ FrameResources::FrameResources(const Device& device, const Allocator& allocator, frame.inFlight = createFence(device.handle(), VK_FENCE_CREATE_SIGNALED_BIT); frame.imageAcquired = createSemaphore(device.handle()); frame.gpuTimer = GpuTimer{device}; + frame.visibleDrawCount = + Buffer{allocator, sizeof(uint32_t), VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT}; + frame.visibleDrawCount.write(std::array{0}); frame.shaderData = Buffer{allocator, shaderDataSize, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT}; diff --git a/src/vk/frame_resources.h b/src/vk/frame_resources.h index 0ab3d6e..55c9c34 100644 --- a/src/vk/frame_resources.h +++ b/src/vk/frame_resources.h @@ -22,6 +22,8 @@ struct Frame DeviceHandle imageAcquired; Buffer shaderData; GpuTimer gpuTimer; + // A CPU-readable copy of how many draws the cull pass found visible in this frame's last submission. + Buffer visibleDrawCount; }; class FrameResources diff --git a/src/vk/sync.h b/src/vk/sync.h index b2853f3..1e78655 100644 --- a/src/vk/sync.h +++ b/src/vk/sync.h @@ -41,3 +41,10 @@ inline void pipelineBarrier(VkCommandBuffer cb, const VkImageMemoryBarrier2& bar { pipelineBarrier(cb, std::span{&barrier, 1}); } + +inline void pipelineBarrier(VkCommandBuffer cb, const VkMemoryBarrier2& barrier) +{ + VkDependencyInfo dependencyInfo{ + .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .memoryBarrierCount = 1, .pMemoryBarriers = &barrier}; + vkCmdPipelineBarrier2(cb, &dependencyInfo); +}