Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 2 additions & 6 deletions docs/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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

Expand Down
18 changes: 17 additions & 1 deletion shaders/common.slang
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand All @@ -56,7 +73,6 @@ public struct DrawConstants
public Draw* draws;
public Transform* transforms;
public Material* materials;
public uint drawIndex;
public uint cascadeIndex;
};

Expand Down
76 changes: 76 additions & 0 deletions shaders/cull.slang
Original file line number Diff line number Diff line change
@@ -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;
}
9 changes: 6 additions & 3 deletions shaders/scene.slang
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
}

Expand Down Expand Up @@ -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)
Expand Down
9 changes: 6 additions & 3 deletions shaders/shadow.slang
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,29 @@ 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;
}

// Alpha-masked surfaces (Sponza's plants and chains) cut the same holes into the shadow map as into the scene.
[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)
Expand Down
29 changes: 23 additions & 6 deletions src/app.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "vk/check.h"

#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <limits>
Expand All @@ -34,6 +35,7 @@ App::App(RunMode mode)
environment_{orThrow(Texture::loadHdr(device_, allocator_, commandPool_, environmentPath))},
bindlessTextures_{device_, static_cast<uint32_t>(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",
Expand Down Expand Up @@ -88,6 +90,7 @@ void App::run()
if (shaderWatcher_.poll() || reloadRequested_)
{
reloadRequested_ = false;
cullPass_.reloadShaders();
shadowPass_.reloadShaders();
scenePass_.reloadShaders();
tonemapPass_.reloadShaders();
Expand Down Expand Up @@ -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_);
Expand All @@ -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<uint32_t, 1> visibleDrawCount{};
frame.visibleDrawCount.read(visibleDrawCount);
visibleDrawCount_ = visibleDrawCount[0];

// Acquire next image
const auto [acquireStatus, imageIndex] = swapchain_.acquireNextImage(frame.imageAcquired.get());
if (acquireStatus == SwapchainStatus::OutOfDate)
Expand Down Expand Up @@ -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},
Expand All @@ -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});
}

Expand All @@ -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");
Expand Down
4 changes: 4 additions & 0 deletions src/app.h
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -92,6 +93,7 @@ class App
ShaderCompiler shaderCompiler_;
PipelineCache pipelineCache_;
std::filesystem::path shaderDirectory_;
CullPass cullPass_;
ShadowPass shadowPass_;
ScenePass scenePass_;
TonemapPass tonemapPass_;
Expand All @@ -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<GpuTiming> gpuTimings_;
uint32_t visibleDrawCount_{0};
float cpuRecordMilliseconds_{0.0f};
Benchmark benchmark_;
glm::vec2 mouseDelta_{};
Expand Down
Loading
Loading