diff --git a/CMakeLists.txt b/CMakeLists.txt index 626be45..c52df8a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -52,6 +52,8 @@ add_executable(vkdriven src/platform/file_watcher.h src/platform/window.cpp src/platform/window.h + src/profiling/benchmark.cpp + src/profiling/benchmark.h src/render/scene_draws.cpp src/render/scene_draws.h src/render/scene_pass.cpp @@ -94,6 +96,8 @@ add_executable(vkdriven src/vk/device.h src/vk/frame_resources.cpp src/vk/frame_resources.h + src/vk/gpu_timer.cpp + src/vk/gpu_timer.h src/vk/graphics_pipeline.cpp src/vk/graphics_pipeline.h src/vk/handle.h diff --git a/benchmarks/2026-10-11_210546_2bce5e4.csv b/benchmarks/2026-10-11_210546_2bce5e4.csv new file mode 100644 index 0000000..fc473ba --- /dev/null +++ b/benchmarks/2026-10-11_210546_2bce5e4.csv @@ -0,0 +1,19 @@ +commit,build,viewport,view,metric,samples,min_ms,median_ms,mean_ms,p95_ms +2bce5e4,release,1920x1080,Atrium,CPU record,500,0.0343,0.0456,0.0469,0.0523 +2bce5e4,release,1920x1080,Atrium,GPU Frame,500,0.9875,0.9952,1.0568,1.3229 +2bce5e4,release,1920x1080,Atrium,GPU Shadows,500,0.4417,0.4453,0.4814,0.7568 +2bce5e4,release,1920x1080,Atrium,GPU Scene,500,0.4823,0.4956,0.5157,0.8069 +2bce5e4,release,1920x1080,Atrium,GPU Tonemap,500,0.0133,0.0154,0.0177,0.0164 +2bce5e4,release,1920x1080,Atrium,GPU ImGui,500,0.0389,0.0389,0.0418,0.0420 +2bce5e4,release,1920x1080,Wall,CPU record,500,0.0366,0.0449,0.0468,0.0515 +2bce5e4,release,1920x1080,Wall,GPU Frame,500,0.8419,0.8573,0.9060,1.1898 +2bce5e4,release,1920x1080,Wall,GPU Shadows,500,0.4107,0.4193,0.4447,0.7228 +2bce5e4,release,1920x1080,Wall,GPU Scene,500,0.3738,0.3809,0.4029,0.7096 +2bce5e4,release,1920x1080,Wall,GPU Tonemap,500,0.0154,0.0164,0.0172,0.0184 +2bce5e4,release,1920x1080,Wall,GPU ImGui,500,0.0379,0.0389,0.0411,0.0399 +2bce5e4,release,1920x1080,Gallery,CPU record,500,0.0365,0.0476,0.0488,0.0539 +2bce5e4,release,1920x1080,Gallery,GPU Frame,500,0.9845,0.9932,1.0509,1.3185 +2bce5e4,release,1920x1080,Gallery,GPU Shadows,500,0.4299,0.4328,0.4659,0.7440 +2bce5e4,release,1920x1080,Gallery,GPU Scene,500,0.4997,0.5059,0.5253,0.8151 +2bce5e4,release,1920x1080,Gallery,GPU Tonemap,500,0.0133,0.0143,0.0154,0.0164 +2bce5e4,release,1920x1080,Gallery,GPU ImGui,500,0.0389,0.0399,0.0442,0.0399 diff --git a/docs/roadmap.md b/docs/roadmap.md index 66df6c1..864eb02 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -37,7 +37,6 @@ A **renderer**: it loads glTF models and scenes and draws them with modern Vulka ## 3. Development rules - [ ] **Short milestones.** Each phase is 3–6 weeks. If a milestone is heading past 8 weeks, cut scope. -- [ ] **Each milestone ends with 3 things:** a git tag, a README screenshot or gif, and a short blog post. - [ ] **Get it working, then generalize.** Hardcode the first version. Only refactor once something is needed a second time. - [ ] **Keep the build green.** CI builds on every push. The validation layers should report zero errors, always. - [ ] **When stuck, write a smaller test first.** Get the technique working in isolation before integrating it. diff --git a/src/app.cpp b/src/app.cpp index db4d70f..f9991e7 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -8,9 +8,12 @@ #include "vk/check.h" #include +#include +#include #include #include #include +#include namespace { @@ -21,10 +24,10 @@ constexpr const char* environmentPath = "assets/environment/kloofendal_48d_partl } // namespace -App::App() - : window_{"vkdriven", 1280, 720}, instance_{"vkdriven", window_.requiredInstanceExtensions()}, +App::App(RunMode mode) + : mode_{mode}, window_{"vkdriven", 1920, 1080}, instance_{"vkdriven", window_.requiredInstanceExtensions()}, surface_{instance_, window_}, device_{instance_, surface_}, allocator_{instance_, device_}, - swapchain_{device_, surface_, window_}, commandPool_{device_}, + swapchain_{device_, surface_, window_, mode != RunMode::Benchmark}, commandPool_{device_}, frames_{device_, allocator_, commandPool_, sizeof(FrameData)}, scene_{orThrow(Scene::loadGltf(device_, allocator_, commandPool_, scenePath))}, environment_{orThrow(Texture::loadHdr(device_, allocator_, commandPool_, environmentPath))}, @@ -63,8 +66,21 @@ App::~App() void App::run() { + // Gives the viewport panel a few frames to settle on its size before the benchmark records it. + constexpr uint32_t benchmarkStartFrame = 10; + uint32_t frameCount = 0; + while (true) { + if (mode_ == RunMode::Benchmark) + { + if (frameCount == benchmarkStartFrame) + benchmark_.start(); + else if (frameCount > benchmarkStartFrame && !benchmark_.running()) + return; + frameCount++; + } + if (!handleEvents()) return; @@ -86,11 +102,13 @@ void App::run() updateSwapchain_ = false; } - if (viewport_.needsResize(requestedViewportExtent_)) + // The benchmark always renders at the same size, so results don't depend on the window or panel layout. + const VkExtent2D viewportExtent = benchmark_.running() ? Benchmark::renderExtent : requestedViewportExtent_; + if (viewport_.needsResize(viewportExtent)) { // Earlier frames may still be rendering into or sampling the old images. device_.waitIdle(); - viewport_.resize(requestedViewportExtent_); + viewport_.resize(viewportExtent); const VkDescriptorImageInfo hdrInfo = viewport_.hdrDescriptorInfo(); bindlessTextures_.write(std::span{&hdrInfo, 1}, hdrTextureIndex()); @@ -98,7 +116,15 @@ void App::run() imgui_.beginFrame(); drawUi(); - camera_.update(window_, viewportHovered_, mouseDelta_); + if (benchmark_.running()) + { + const BenchmarkView& view = benchmark_.currentView(); + camera_.setPose(view.position, view.yawRadians, view.pitchRadians); + } + else + { + camera_.update(window_, viewportHovered_, mouseDelta_); + } imgui_.endFrame(); drawFrame(); } @@ -125,7 +151,7 @@ void App::drawUi() if (viewportPanel.requestedExtent) requestedViewportExtent_ = *viewportPanel.requestedExtent; viewportHovered_ = viewportPanel.hovered; - drawStatsPanel(scene_, viewport_); + drawStatsPanel(scene_, viewport_, camera_, gpuTimings_, cpuRecordMilliseconds_, benchmark_); drawLightPanel(light_); drawShadowPanel(shadowSettings_); drawTonemapPanel(tonemapSettings_); @@ -138,6 +164,14 @@ void App::drawFrame() // Wait on fence chk(vkWaitForFences(device_.handle(), 1, frame.inFlight.ptr(), VK_TRUE, std::numeric_limits::max())); + // The fence guarantees this frame's last timestamps are written; read them before recording resets the queries. + // A running average keeps the numbers readable in the stats panel. + const std::vector latestTimings = frame.gpuTimer.read(); + if (latestTimings.size() != gpuTimings_.size()) + gpuTimings_ = latestTimings; + for (size_t i = 0; i < latestTimings.size(); i++) + gpuTimings_[i].milliseconds = std::lerp(gpuTimings_[i].milliseconds, latestTimings[i].milliseconds, 0.05f); + // Acquire next image const auto [acquireStatus, imageIndex] = swapchain_.acquireNextImage(frame.imageAcquired.get()); if (acquireStatus == SwapchainStatus::OutOfDate) @@ -151,8 +185,13 @@ void App::drawFrame() } chk(vkResetFences(device_.handle(), 1, frame.inFlight.ptr())); + const auto recordStart = std::chrono::steady_clock::now(); updateFrameData(frame); recordCommandBuffer(frame.commandBuffer, imageIndex, frame); + const float cpuRecordMilliseconds = + std::chrono::duration(std::chrono::steady_clock::now() - recordStart).count(); + cpuRecordMilliseconds_ = std::lerp(cpuRecordMilliseconds_, cpuRecordMilliseconds, 0.05f); + benchmark_.addFrame(latestTimings, cpuRecordMilliseconds); // Submit command buffer VkSemaphoreSubmitInfo waitSemaphoreInfo{.sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO, @@ -203,17 +242,34 @@ void App::updateFrameData(Frame& frame) const frame.shaderData.write(std::span{&frameData, 1}); } -void App::recordCommandBuffer(VkCommandBuffer cb, uint32_t imageIndex, const Frame& frame) const +void App::recordCommandBuffer(VkCommandBuffer cb, uint32_t imageIndex, Frame& frame) const { chk(vkResetCommandBuffer(cb, 0)); VkCommandBufferBeginInfo cbBI{.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; chk(vkBeginCommandBuffer(cb, &cbBI)); + GpuTimer& timer = frame.gpuTimer; + timer.reset(cb); + const uint32_t frameScope = timer.begin(cb, "Frame"); + + 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()); + timer.end(cb, sceneScope); + + const uint32_t tonemapScope = timer.begin(cb, "Tonemap"); tonemapPass_.record(cb, viewport_, hdrTextureIndex(), tonemapSettings_); + timer.end(cb, tonemapScope); + + const uint32_t imguiScope = timer.begin(cb, "ImGui"); imgui_.record(cb, swapchain_, imageIndex); + timer.end(cb, imguiScope); + + timer.end(cb, frameScope); chk(vkEndCommandBuffer(cb)); } diff --git a/src/app.h b/src/app.h index e8b3e5f..5101f21 100644 --- a/src/app.h +++ b/src/app.h @@ -6,6 +6,7 @@ #include "platform/file_watcher.h" #include "platform/window.h" +#include "profiling/benchmark.h" #include "render/scene_pass.h" #include "render/shadow_pass.h" #include "render/tonemap_pass.h" @@ -28,6 +29,15 @@ #include #include +#include + +enum class RunMode +{ + Interactive, + // Runs the benchmark once the viewport has settled, then quits. Vsync is off, so the GPU never idles + // waiting on the display and its clocks stay up. + Benchmark, +}; // Owns the whole renderer. Members are declared in dependency order, so they're created top to // bottom and destroyed bottom to top; the destructor only has to wait for the GPU first. @@ -35,7 +45,7 @@ class App { public: - App(); + explicit App(RunMode mode); ~App(); App(const App&) = delete; @@ -50,7 +60,7 @@ class App void drawUi(); void drawFrame(); void updateFrameData(Frame& frame) const; - void recordCommandBuffer(VkCommandBuffer cb, uint32_t imageIndex, const Frame& frame) const; + void recordCommandBuffer(VkCommandBuffer cb, uint32_t imageIndex, Frame& frame) const; [[nodiscard]] uint32_t hdrTextureIndex() const { @@ -67,6 +77,7 @@ class App return shadowMapTextureIndex() + 1; } + RunMode mode_; Window window_; Instance instance_; Surface surface_; @@ -92,6 +103,9 @@ class App DirectionalLight light_; ShadowSettings shadowSettings_; TonemapSettings tonemapSettings_; + std::vector gpuTimings_; + float cpuRecordMilliseconds_{0.0f}; + Benchmark benchmark_; glm::vec2 mouseDelta_{}; bool viewportHovered_{false}; diff --git a/src/main.cpp b/src/main.cpp index 1a881e6..c08df75 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2,14 +2,21 @@ #include "app.h" +#include #include #include +#include +#include -int main(int, char**) +int main(int argc, char** argv) { + const std::span arguments{argv, static_cast(argc)}; + const bool benchmark = std::ranges::any_of( + arguments.subspan(1), [](const char* argument) { return std::string_view{argument} == "--benchmark"; }); + try { - App app; + App app{benchmark ? RunMode::Benchmark : RunMode::Interactive}; app.run(); } catch (const std::exception& e) diff --git a/src/profiling/benchmark.cpp b/src/profiling/benchmark.cpp new file mode 100644 index 0000000..c382829 --- /dev/null +++ b/src/profiling/benchmark.cpp @@ -0,0 +1,169 @@ +#include "profiling/benchmark.h" + +#include "vk/gpu_timer.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +// Sponza views: down the atrium, up close to a wall (most of the scene is out of view), and down the atrium from +// the upper gallery at the far end. +const auto benchmarkViews = std::to_array({ + {.name = "Atrium", .position = {-8.0f, 2.0f, 0.0f}, .yawRadians = glm::radians(90.0f), .pitchRadians = 0.0f}, + {.name = "Wall", + .position = {-0.5f, 2.0f, 1.5f}, + .yawRadians = 0.0f, + .pitchRadians = glm::radians(-8.0f)}, + {.name = "Gallery", + .position = {7.0f, 6.0f, 0.0f}, + .yawRadians = glm::radians(-90.0f), + .pitchRadians = glm::radians(-25.0f)}, +}); + +// The first line a shell command prints, or an empty string if it couldn't run. +std::string firstOutputLine(const char* command) +{ + const std::unique_ptr pipe{_popen(command, "r"), &_pclose}; + if (!pipe) + return {}; + + std::array buffer{}; + if (!std::fgets(buffer.data(), static_cast(buffer.size()), pipe.get())) + return {}; + + std::string line{buffer.data()}; + while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) + line.pop_back(); + return line; +} + +// The short commit hash, marked dirty when there are uncommitted changes, since those runs aren't of the commit. +std::string gitCommit() +{ + std::string commit = firstOutputLine("git rev-parse --short HEAD 2>nul"); + if (commit.empty()) + return "unknown"; + if (!firstOutputLine("git status --porcelain 2>nul").empty()) + commit += "-dirty"; + return commit; +} + +#ifdef NDEBUG +constexpr const char* buildType = "release"; +#else +constexpr const char* buildType = "debug"; +#endif + +} // namespace + +void Benchmark::start() +{ + viewIndex_ = 0; + frameInView_ = 0; + series_.clear(); + rows_.clear(); +} + +const BenchmarkView& Benchmark::currentView() const +{ + return benchmarkViews[*viewIndex_]; +} + +float Benchmark::progress() const +{ + if (!running()) + return 0.0f; + + const float framesPerView = static_cast(warmupFrames + sampleFrames); + const float framesDone = static_cast(*viewIndex_) * framesPerView + static_cast(frameInView_); + return framesDone / (framesPerView * static_cast(benchmarkViews.size())); +} + +void Benchmark::addFrame(std::span gpuTimings, float cpuRecordMilliseconds) +{ + if (!running()) + return; + + frameInView_++; + if (frameInView_ > warmupFrames) + { + record("CPU record", cpuRecordMilliseconds); + for (const GpuTiming& timing : gpuTimings) + record(std::format("GPU {}", timing.name), timing.milliseconds); + } + if (frameInView_ < warmupFrames + sampleFrames) + return; + + summarizeView(); + series_.clear(); + frameInView_ = 0; + ++*viewIndex_; + if (*viewIndex_ < benchmarkViews.size()) + return; + + viewIndex_.reset(); + writeResults(); +} + +void Benchmark::record(const std::string& metric, float milliseconds) +{ + const auto existing = std::ranges::find(series_, metric, &Series::metric); + if (existing != series_.end()) + { + existing->milliseconds.push_back(milliseconds); + return; + } + series_.push_back({.metric = metric, .milliseconds = {milliseconds}}); +} + +void Benchmark::summarizeView() +{ + for (Series& series : series_) + { + std::vector& values = series.milliseconds; + std::ranges::sort(values); + const size_t count = values.size(); + rows_.push_back({.view = currentView().name, + .metric = series.metric, + .samples = count, + .min = values.front(), + .median = values[count / 2], + .mean = std::accumulate(values.begin(), values.end(), 0.0f) / static_cast(count), + .p95 = values[std::min(count - 1, count * 95 / 100)]}); + } +} + +void Benchmark::writeResults() +{ + const std::string commit = gitCommit(); + const auto now = std::chrono::zoned_time{std::chrono::current_zone(), + std::chrono::floor(std::chrono::system_clock::now())}; + + std::filesystem::create_directories("benchmarks"); + const std::filesystem::path resultPath = + std::filesystem::path{"benchmarks"} / std::format("{:%Y-%m-%d_%H%M%S}_{}.csv", now, commit); + + std::ofstream file{resultPath}; + std::println(file, "commit,build,viewport,view,metric,samples,min_ms,median_ms,mean_ms,p95_ms"); + for (const Row& row : rows_) + std::println(file, "{},{},{}x{},{},{},{},{:.4f},{:.4f},{:.4f},{:.4f}", commit, buildType, + renderExtent.width, renderExtent.height, row.view, row.metric, row.samples, row.min, + row.median, row.mean, row.p95); + + std::println("Benchmark ({}, {}, {}x{}), median / p95 in ms:", commit, buildType, renderExtent.width, + renderExtent.height); + for (const Row& row : rows_) + std::println(" {:<10} {:<14} {:7.3f} / {:7.3f}", row.view, row.metric, row.median, row.p95); + std::println("Saved {}", resultPath.string()); +} diff --git a/src/profiling/benchmark.h b/src/profiling/benchmark.h new file mode 100644 index 0000000..abe898a --- /dev/null +++ b/src/profiling/benchmark.h @@ -0,0 +1,71 @@ +#pragma once + +#include + +#include + +#include +#include +#include +#include +#include + +struct GpuTiming; + +struct BenchmarkView +{ + const char* name{nullptr}; + glm::vec3 position{}; + float yawRadians{0.0f}; + float pitchRadians{0.0f}; +}; + +// Puts the camera at a few fixed views and records raw per-frame timings at each, then writes min / median / +// mean / p95 per pass to a CSV in benchmarks/, so runs from different commits can be compared. +class Benchmark +{ + public: + // Long enough for the GPU timer's two-frame delay and clock ramp-up after each camera jump. + static constexpr uint32_t warmupFrames = 120; + static constexpr uint32_t sampleFrames = 500; + static constexpr VkExtent2D renderExtent{.width = 1920, .height = 1080}; + + void start(); + void addFrame(std::span gpuTimings, float cpuRecordMilliseconds); + + [[nodiscard]] bool running() const + { + return viewIndex_.has_value(); + } + + // The view the camera should be at this frame. Only valid while running. + [[nodiscard]] const BenchmarkView& currentView() const; + [[nodiscard]] float progress() const; + + private: + struct Series + { + std::string metric; + std::vector milliseconds; + }; + + struct Row + { + std::string view; + std::string metric; + size_t samples{0}; + float min{0.0f}; + float median{0.0f}; + float mean{0.0f}; + float p95{0.0f}; + }; + + void record(const std::string& metric, float milliseconds); + void summarizeView(); + void writeResults(); + + std::optional viewIndex_; + uint32_t frameInView_{0}; + std::vector series_; + std::vector rows_; +}; diff --git a/src/scene/camera.cpp b/src/scene/camera.cpp index cb93308..a96c3bf 100644 --- a/src/scene/camera.cpp +++ b/src/scene/camera.cpp @@ -112,3 +112,12 @@ glm::vec3 Camera::forward() const { return {std::cos(pitch_) * std::sin(yaw_), std::sin(pitch_), -std::cos(pitch_) * std::cos(yaw_)}; } + +void Camera::setPose(glm::vec3 position, float yawRadians, float pitchRadians) +{ + position_ = position; + yaw_ = yawRadians; + pitch_ = pitchRadians; + velocity_ = {}; + pendingLook_ = {}; +} diff --git a/src/scene/camera.h b/src/scene/camera.h index 5bd9127..bc36699 100644 --- a/src/scene/camera.h +++ b/src/scene/camera.h @@ -21,6 +21,19 @@ class Camera [[nodiscard]] glm::mat4 projection(float aspect, float sliceNear, float sliceFar) const; [[nodiscard]] glm::vec3 worldPosition() const; + [[nodiscard]] float yawRadians() const + { + return yaw_; + } + + [[nodiscard]] float pitchRadians() const + { + return pitch_; + } + + // Jumps straight to a pose and drops any leftover movement, so a view can be reproduced exactly. + void setPose(glm::vec3 position, float yawRadians, float pitchRadians); + [[nodiscard]] float nearPlane() const { return nearPlane_; diff --git a/src/ui/panels.cpp b/src/ui/panels.cpp index 6109032..e313d1a 100644 --- a/src/ui/panels.cpp +++ b/src/ui/panels.cpp @@ -2,11 +2,14 @@ #include +#include "profiling/benchmark.h" #include "render/shadow_pass.h" #include "render/tonemap_pass.h" +#include "scene/camera.h" #include "scene/light.h" #include "scene/scene.h" #include "ui/viewport_target.h" +#include "vk/gpu_timer.h" #include #include @@ -24,8 +27,12 @@ ViewportPanelState drawViewportPanel(ImGuiID dockspace, const ViewportTarget& vi const ImVec2 available = ImGui::GetContentRegionAvail(); state.requestedExtent = VkExtent2D{.width = static_cast(std::max(available.x, 0.0f)), .height = static_cast(std::max(available.y, 0.0f))}; + // Normally the image matches the panel. When it's rendered at a fixed size instead (the benchmark), it's + // scaled to fit and keeps its aspect ratio. const VkExtent2D extent = viewport.extent(); - ImGui::Image(viewport.texture(), ImVec2{static_cast(extent.width), static_cast(extent.height)}); + const ImVec2 imageSize{static_cast(extent.width), static_cast(extent.height)}; + 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(); } ImGui::End(); @@ -34,17 +41,30 @@ ViewportPanelState drawViewportPanel(ImGuiID dockspace, const ViewportTarget& vi return state; } -void drawStatsPanel(const Scene& scene, const ViewportTarget& viewport) +void drawStatsPanel(const Scene& scene, const ViewportTarget& viewport, const Camera& camera, + std::span gpuTimings, float cpuRecordMilliseconds, const Benchmark& benchmark) { const ImGuiIO& io = ImGui::GetIO(); ImGui::Begin(ICON_FA_CHART_SIMPLE " Stats###Stats"); ImGui::Text("%.2f ms (%.0f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::Text("Viewport: %u x %u", viewport.extent().width, viewport.extent().height); + if (benchmark.running()) + ImGui::ProgressBar(benchmark.progress(), ImVec2{-1.0f, 0.0f}, benchmark.currentView().name); + + ImGui::Separator(); + ImGui::Text("CPU record %5.2f ms", cpuRecordMilliseconds); + ImGui::Text("GPU time"); + 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("Primitives: %zu", scene.primitives().size()); ImGui::Text("Vertices: %zu", static_cast(scene.vertexCount())); ImGui::Text("Indices: %zu", static_cast(scene.indexCount())); + 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::End(); } diff --git a/src/ui/panels.h b/src/ui/panels.h index ae8d5a1..3e6b9c1 100644 --- a/src/ui/panels.h +++ b/src/ui/panels.h @@ -5,12 +5,16 @@ #include #include +#include +class Benchmark; +class Camera; class Scene; class ViewportTarget; struct DirectionalLight; struct ShadowSettings; struct TonemapSettings; +struct GpuTiming; struct ViewportPanelState { @@ -21,7 +25,9 @@ struct ViewportPanelState // Shows the viewport image. ViewportPanelState drawViewportPanel(ImGuiID dockspace, const ViewportTarget& viewport); -void drawStatsPanel(const Scene& scene, const ViewportTarget& viewport); +// 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 drawLightPanel(DirectionalLight& light); void drawShadowPanel(ShadowSettings& settings); void drawTonemapPanel(TonemapSettings& settings); diff --git a/src/vk/device.cpp b/src/vk/device.cpp index e822a91..0bc3669 100644 --- a/src/vk/device.cpp +++ b/src/vk/device.cpp @@ -96,6 +96,13 @@ Device::Device(const Instance& instance, const Surface& surface) vkGetPhysicalDeviceProperties(physical_, &properties); std::println("Using GPU: {} ({}, vendor: {}, device: {})", properties.deviceName, string_VkPhysicalDeviceType(properties.deviceType), properties.vendorID, properties.deviceID); + timestampPeriod_ = properties.limits.timestampPeriod; + + uint32_t queueFamilyCount = 0; + vkGetPhysicalDeviceQueueFamilyProperties(physical_, &queueFamilyCount, nullptr); + std::vector queueFamilies(queueFamilyCount); + vkGetPhysicalDeviceQueueFamilyProperties(physical_, &queueFamilyCount, queueFamilies.data()); + timestampValidBits_ = queueFamilies[queueFamily_].timestampValidBits; const float queuePriority = 1.0f; VkDeviceQueueCreateInfo queueCI{.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, diff --git a/src/vk/device.h b/src/vk/device.h index fc307d2..3ea8aac 100644 --- a/src/vk/device.h +++ b/src/vk/device.h @@ -40,6 +40,17 @@ class Device return queueFamily_; } + // Nanoseconds per timestamp tick, and how many low bits of a timestamp on our queue are valid. + [[nodiscard]] float timestampPeriod() const + { + return timestampPeriod_; + } + + [[nodiscard]] uint32_t timestampValidBits() const + { + return timestampValidBits_; + } + [[nodiscard]] VkFormat depthFormat() const { return depthFormat_; @@ -53,4 +64,6 @@ class Device VkQueue queue_{VK_NULL_HANDLE}; uint32_t queueFamily_{0}; VkFormat depthFormat_{VK_FORMAT_UNDEFINED}; + float timestampPeriod_{0.0f}; + uint32_t timestampValidBits_{0}; }; diff --git a/src/vk/frame_resources.cpp b/src/vk/frame_resources.cpp index 99f17e2..e21aed9 100644 --- a/src/vk/frame_resources.cpp +++ b/src/vk/frame_resources.cpp @@ -15,6 +15,7 @@ FrameResources::FrameResources(const Device& device, const Allocator& allocator, commandPool.allocate(std::span{&frame.commandBuffer, 1}); frame.inFlight = createFence(device.handle(), VK_FENCE_CREATE_SIGNALED_BIT); frame.imageAcquired = createSemaphore(device.handle()); + frame.gpuTimer = GpuTimer{device}; 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 5da194a..0ab3d6e 100644 --- a/src/vk/frame_resources.h +++ b/src/vk/frame_resources.h @@ -3,6 +3,7 @@ #include #include "vk/buffer.h" +#include "vk/gpu_timer.h" #include "vk/handle.h" #include @@ -20,6 +21,7 @@ struct Frame DeviceHandle inFlight; DeviceHandle imageAcquired; Buffer shaderData; + GpuTimer gpuTimer; }; class FrameResources diff --git a/src/vk/gpu_timer.cpp b/src/vk/gpu_timer.cpp new file mode 100644 index 0000000..bb5bdc8 --- /dev/null +++ b/src/vk/gpu_timer.cpp @@ -0,0 +1,68 @@ +#include "vk/gpu_timer.h" + +#include "vk/check.h" +#include "vk/device.h" + +#include + +GpuTimer::GpuTimer(const Device& device) + : device_{device.handle()}, nanosecondsPerTick_{device.timestampPeriod()}, + validBitsMask_{device.timestampValidBits() >= 64 ? ~0ull : (1ull << device.timestampValidBits()) - 1} +{ + VkQueryPoolCreateInfo queryPoolCI{.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO, + .queryType = VK_QUERY_TYPE_TIMESTAMP, + .queryCount = maxScopes * 2}; + VkQueryPool queryPool{VK_NULL_HANDLE}; + chk(vkCreateQueryPool(device_, &queryPoolCI, nullptr, &queryPool)); + queryPool_ = {device_, queryPool}; +} + +std::vector GpuTimer::read() const +{ + if (scopeCount_ == 0) + return {}; + + // Each query is written as a value plus an availability word, so a scope that never ran reads as unavailable + // instead of failing the whole call. + std::array results{}; + chk(vkGetQueryPoolResults(device_, queryPool_.get(), 0, scopeCount_ * 2, sizeof(results), results.data(), + 2 * sizeof(uint64_t), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WITH_AVAILABILITY_BIT)); + + std::vector timings; + for (uint32_t scope = 0; scope < scopeCount_; scope++) + { + const uint64_t start = results[scope * 4]; + const bool startAvailable = results[scope * 4 + 1] != 0; + const uint64_t end = results[scope * 4 + 2]; + const bool endAvailable = results[scope * 4 + 3] != 0; + if (!startAvailable || !endAvailable) + continue; + + const uint64_t ticks = ((end & validBitsMask_) - (start & validBitsMask_)) & validBitsMask_; + timings.push_back({.name = names_[scope], + .milliseconds = static_cast(ticks) * nanosecondsPerTick_ / 1'000'000.0f}); + } + return timings; +} + +void GpuTimer::reset(VkCommandBuffer cb) +{ + vkCmdResetQueryPool(cb, queryPool_.get(), 0, maxScopes * 2); + scopeCount_ = 0; +} + +// ALL_COMMANDS: the timestamp is written once everything recorded before it has finished, so a scope covers +// exactly the work between its two timestamps instead of overlapping the previous pass. +uint32_t GpuTimer::begin(VkCommandBuffer cb, const char* name) +{ + assert(scopeCount_ < maxScopes); + const uint32_t scope = scopeCount_++; + names_[scope] = name; + vkCmdWriteTimestamp2(cb, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, queryPool_.get(), scope * 2); + return scope; +} + +void GpuTimer::end(VkCommandBuffer cb, uint32_t scope) const +{ + vkCmdWriteTimestamp2(cb, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, queryPool_.get(), scope * 2 + 1); +} diff --git a/src/vk/gpu_timer.h b/src/vk/gpu_timer.h new file mode 100644 index 0000000..97a355f --- /dev/null +++ b/src/vk/gpu_timer.h @@ -0,0 +1,44 @@ +#pragma once + +#include + +#include "vk/handle.h" + +#include +#include +#include + +class Device; + +struct GpuTiming +{ + const char* name{nullptr}; + float milliseconds{0.0f}; +}; + +// Measures how long sections of a command buffer take on the GPU with a pair of timestamp queries each. +// Meant to be one per frame in flight: read() returns the times from this timer's previous submission, +// so only call it after waiting on that submission's fence. +class GpuTimer +{ + public: + static constexpr uint32_t maxScopes = 8; + + GpuTimer() = default; + explicit GpuTimer(const Device& device); + + [[nodiscard]] std::vector read() const; + + // Starts a new recording; the previous results are gone after this, so read() them first. + void reset(VkCommandBuffer cb); + [[nodiscard]] uint32_t begin(VkCommandBuffer cb, const char* name); + void end(VkCommandBuffer cb, uint32_t scope) const; + + private: + VkDevice device_{VK_NULL_HANDLE}; + DeviceHandle queryPool_; + float nanosecondsPerTick_{0.0f}; + uint64_t validBitsMask_{0}; + std::array names_{}; + uint32_t scopeCount_{0}; +}; diff --git a/src/vk/handle.h b/src/vk/handle.h index 7a798fb..8f078b0 100644 --- a/src/vk/handle.h +++ b/src/vk/handle.h @@ -54,6 +54,11 @@ inline void destroyHandle(VkDevice device, VkDescriptorPool handle) vkDestroyDescriptorPool(device, handle, nullptr); } +inline void destroyHandle(VkDevice device, VkQueryPool handle) +{ + vkDestroyQueryPool(device, handle, nullptr); +} + inline void destroyHandle(VkDevice device, VkCommandPool handle) { vkDestroyCommandPool(device, handle, nullptr); diff --git a/src/vk/swapchain.cpp b/src/vk/swapchain.cpp index fd28ca8..e814623 100644 --- a/src/vk/swapchain.cpp +++ b/src/vk/swapchain.cpp @@ -8,9 +8,27 @@ #include #include +#include -Swapchain::Swapchain(const Device& device, const Surface& surface, const Window& window) - : device_{device.handle()}, physical_{device.physical()}, surface_{surface.handle()}, window_{window} +namespace +{ + +// FIFO is the only mode every surface has to support. +VkPresentModeKHR immediateIfSupported(VkPhysicalDevice physical, VkSurfaceKHR surface) +{ + uint32_t count = 0; + chk(vkGetPhysicalDeviceSurfacePresentModesKHR(physical, surface, &count, nullptr)); + std::vector modes(count); + chk(vkGetPhysicalDeviceSurfacePresentModesKHR(physical, surface, &count, modes.data())); + return std::ranges::contains(modes, VK_PRESENT_MODE_IMMEDIATE_KHR) ? VK_PRESENT_MODE_IMMEDIATE_KHR + : VK_PRESENT_MODE_FIFO_KHR; +} + +} // namespace + +Swapchain::Swapchain(const Device& device, const Surface& surface, const Window& window, bool vsync) + : device_{device.handle()}, physical_{device.physical()}, surface_{surface.handle()}, window_{window}, + presentMode_{vsync ? VK_PRESENT_MODE_FIFO_KHR : immediateIfSupported(device.physical(), surface.handle())} { const VkSurfaceCapabilitiesKHR capabilities = surfaceCapabilities(); create(capabilities, chooseExtent(capabilities)); @@ -102,7 +120,7 @@ void Swapchain::create(const VkSurfaceCapabilitiesKHR& capabilities, VkExtent2D .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, .preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, - .presentMode = VK_PRESENT_MODE_FIFO_KHR, + .presentMode = presentMode_, .oldSwapchain = oldSwapchain}; chk(vkCreateSwapchainKHR(device_, &swapchainCI, nullptr, &swapchain_)); extent_ = extent; diff --git a/src/vk/swapchain.h b/src/vk/swapchain.h index 7804363..1657223 100644 --- a/src/vk/swapchain.h +++ b/src/vk/swapchain.h @@ -29,7 +29,9 @@ struct AcquiredImage class Swapchain { public: - Swapchain(const Device& device, const Surface& surface, const Window& window); + // Without vsync, frames are presented immediately (tearing) when the surface supports it, so the GPU never + // waits on the display. Used for benchmarking. + Swapchain(const Device& device, const Surface& surface, const Window& window, bool vsync); ~Swapchain(); Swapchain(const Swapchain&) = delete; @@ -83,6 +85,7 @@ class Swapchain // UNORM because only ImGui draws to the swapchain, and its colors are already sRGB-encoded. VkFormat format_{VK_FORMAT_B8G8R8A8_UNORM}; VkExtent2D extent_{}; + VkPresentModeKHR presentMode_{VK_PRESENT_MODE_FIFO_KHR}; std::vector images_; std::vector> views_; std::vector> renderCompleteSemaphores_;