From 91b672ede6d71303e26620b79ac6e0908d26d84e Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Sun, 15 Nov 2026 16:00:17 +0000 Subject: [PATCH 1/6] Headless state dumps and offscreen screenshots for agents Agents can now see a run without opening a window. --dump-state F [--dump-state-ticks L] writes the simulation state as JSON on the game thread right after each tick: every entity and singleton of the types the state hash covers (rollback state) plus the saved ones, with every field, the tick and its state hash. Works with --null-render. The same run writes the same bytes in every exec mode. --offscreen renders with Vulkan into images the renderer owns: no window, no surface, no GLFW, no window system extension, with the virtual clock and no frame cap of --null-render. --screenshot F [--screenshot-ticks L] saves the frame that first shows each tick as a PNG, offscreen or windowed. --resolution WxH sets the frame or window size. A capture that was asked for and not made fails the run (code 1). Also fixes two crashes on software Vulkan (llvmpipe), which agent and CI machines use. Both were also in windowed play: - The skybox pipeline declared mesh vertex input but drew with no vertex buffer (GraphicsPipeline::m_HasVertexInput). - llvmpipe's uniform inlining miscompiles the two light loops of deferred.frag; the loop bounds now depend on a value it cannot inline. The surface and swap chain Vulkan commands are optional in the loader table and checked only when there is a window. Tests: LaunchOptions and RunSettings cases, World state dump tests, the CTests "Sandbox: headless state dump" (direct and threaded dumps are byte-identical) and, with FLING_TEST_OFFSCREEN=ON, "Sandbox: offscreen screenshots". Documented in Skills/testing.md. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 + Assets/Shaders/Deferred/deferred.frag | 12 +- Docs/agent-guide.md | 9 +- FlingEngine/Application/inc/Engine.h | 31 ++- FlingEngine/Application/src/Engine.cpp | 215 +++++++++++++++--- FlingEngine/Core/inc/LaunchOptions.h | 45 ++++ FlingEngine/Core/inc/RunSettings.h | 3 + FlingEngine/Core/src/LaunchOptions.cpp | 141 ++++++++++++ FlingEngine/Core/src/RunSettings.cpp | 9 +- FlingEngine/Engine/inc/Ecs/TypeRegistry.h | 3 + FlingEngine/Engine/inc/World.h | 39 +++- FlingEngine/Engine/src/Ecs/Reflection.cpp | 2 +- FlingEngine/Engine/src/World.cpp | 137 ++++++++++- FlingEngine/Graphics/inc/VulkanApp.h | 62 +++++ FlingEngine/Graphics/src/FrameCapture.cpp | 189 +++++++++++++++ FlingEngine/Graphics/src/FrameCapture.h | 45 ++++ FlingEngine/Graphics/src/GraphicsPipeline.cpp | 14 +- FlingEngine/Graphics/src/GraphicsPipeline.h | 8 + FlingEngine/Graphics/src/Instance.cpp | 22 +- FlingEngine/Graphics/src/Instance.h | 14 +- FlingEngine/Graphics/src/LogicalDevice.cpp | 16 +- FlingEngine/Graphics/src/SkyboxSubpass.cpp | 3 + FlingEngine/Graphics/src/SwapChain.cpp | 107 ++++++++- FlingEngine/Graphics/src/SwapChain.h | 38 ++++ FlingEngine/Graphics/src/VulkanApp.cpp | 139 +++++++++-- FlingEngine/Graphics/src/VulkanFunctions.inl | 27 ++- FlingEngine/Graphics/src/VulkanLoader.cpp | 44 ++++ FlingEngine/Graphics/src/VulkanLoader.h | 10 + FlingTests/Core/LaunchOptionsTests.cpp | 110 +++++++++ FlingTests/Core/RunSettingsTests.cpp | 8 + FlingTests/Engine/WorldStateDumpTests.cpp | 190 ++++++++++++++++ Plans/improve-ai-iteration.md | 13 +- Sandbox/CMakeLists.txt | 44 ++++ Sandbox/Tests/CheckCaptures.cmake | 75 ++++++ Skills/testing.md | 66 ++++++ 35 files changed, 1804 insertions(+), 92 deletions(-) create mode 100644 FlingEngine/Graphics/src/FrameCapture.cpp create mode 100644 FlingEngine/Graphics/src/FrameCapture.h create mode 100644 FlingTests/Engine/WorldStateDumpTests.cpp create mode 100644 Sandbox/Tests/CheckCaptures.cmake diff --git a/AGENTS.md b/AGENTS.md index 46dc62ff..9d024475 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,6 +53,12 @@ platform setup (Vulkan SDK, GLFW, etc.). The editor's GPU Options window (menu Windows; drawn in `--play` too) changes the rate, the cap, VSync and interpolation at run time. Detail: [`Docs/time-and-ticks.md`](Docs/time-and-ticks.md) section 2. +- See a run without a window: `--dump-state ` writes the simulation + state as JSON at chosen ticks (works with `--null-render`), and `--offscreen + --screenshot ` renders with Vulkan into offscreen images and saves PNG + files (no window, no display; a software driver such as llvmpipe is enough). + Prefer the state dump; use screenshots for rendering work. Detail: + [`Skills/testing.md`](Skills/testing.md#seeing-the-game-without-a-window). - Drive a headless run with `--replay-input `. Agents can write their own `.input.jsonl` files. Format and flags: [`Skills/input-playback.md`](Skills/input-playback.md). - Load a level other than `[Game] StartLevel` with `--level ` (relative diff --git a/Assets/Shaders/Deferred/deferred.frag b/Assets/Shaders/Deferred/deferred.frag index 8501131f..23d03e01 100644 --- a/Assets/Shaders/Deferred/deferred.frag +++ b/Assets/Shaders/Deferred/deferred.frag @@ -60,10 +60,18 @@ void main() // so that calculations only have to be done for visible fragments // independent of no. of lights. + // The loop counts. The min with a value only the GPU knows (the G-buffer size, never 0) + // changes nothing, but keeps a driver from compiling the shader again for each count: + // llvmpipe's uniform inlining does that for loop bounds read from a uniform buffer, and + // its code for these two loops reads a null pointer (a crash on CPU rendering) + const uint NotInlined = uint(textureSize(samplerposition, 0).x) + 128u; + const uint DirLightCount = min(lights.DirLightCount, NotInlined); + const uint PointLightCount = min(lights.PointLightCount, NotInlined); + // Ambient part vec3 LightColor = vec3(0.0, 0.0, 0.0); // Directional lights ------------------------- - for(uint i = 0; i < lights.DirLightCount; i++) + for(uint i = 0; i < DirLightCount; i++) { LightColor += DirLightPBR( lights.DirLights[i], @@ -78,7 +86,7 @@ void main() } // Point lights ------------------------- - for(uint i = 0; i < lights.PointLightCount; i++) + for(uint i = 0; i < PointLightCount; i++) { // Vector to light vec3 L = lights.PointLights[i].Pos.xyz - fragPos; diff --git a/Docs/agent-guide.md b/Docs/agent-guide.md index c6e94523..beec0e06 100644 --- a/Docs/agent-guide.md +++ b/Docs/agent-guide.md @@ -770,7 +770,11 @@ flag or key. The startup line `Run settings: ...` names each value and its sourc | Interpolation | `--interpolation on\|off` | `Interpolation` | 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), `--unattended` (no +Other flags: `--null-render` (no window or GPU, virtual clock), `--offscreen` (render +with the GPU into images, no window, with the timing of `--null-render`), +`--resolution WxH`, `--screenshot ` and `--screenshot-ticks L` (PNG of the +frame that shows each tick), `--dump-state ` and `--dump-state-ticks L` (the +simulation state as JSON after each tick), `--unattended` (no dialogs; a crash exits 2 with a stack trace), `--frames N` (see below), `--frames-per-tick N` (headless frames between ticks), `--seed S`, `--level ` (relative to `Assets/`), `--play`, `--dump-schedule`, `--validate-schedule`, `--dump-ticks `, @@ -829,6 +833,9 @@ the tests from the repository root. clang-cl configure flags are in Headless run: `Sandbox --null-render --unattended --frames 120 --seed 1` (the last log lines print `Sandbox: 754 transforms, checksum ...` and `Fling exit: code=0 ticks=120 ...`). +To see what a run did without a window, read the state (`--dump-state`), or render +offscreen and look at a PNG (`--offscreen --screenshot`; a software Vulkan driver such +as llvmpipe is enough): `Skills/testing.md`, "Seeing the game without a window". Test layout (Catch2 3; each executable links only its module): diff --git a/FlingEngine/Application/inc/Engine.h b/FlingEngine/Application/inc/Engine.h index 5318a889..55d21201 100644 --- a/FlingEngine/Application/inc/Engine.h +++ b/FlingEngine/Application/inc/Engine.h @@ -25,6 +25,8 @@ #include #include #include +#include +#include /** * Triggers a breakpoint at the call site, halting execution if a debugger is attached. @@ -50,8 +52,9 @@ namespace Fling * along with all startup/shutdown ordering. * * The loop does not need a window: with --null-render the engine makes no - * window and no GPU device, and ticks with a fixed delta. See LaunchOptions - * for the launch flags. + * window and no GPU device, and ticks with a fixed delta. With --offscreen it + * renders with the GPU into images it owns, still with no window, on the same + * fixed delta. See LaunchOptions for the launch flags. */ class Engine { @@ -238,6 +241,30 @@ namespace Fling /** Writes the ledger rows of the ticks since the last call to the --dump-ticks file (main thread). */ void DumpNewTicks(); + /** Writes the state dumps that the ticks made since the last call to their --dump-state files (main thread). */ + void WriteStateDumps(); + + /** Before the frame is drawn: ask the renderer to save it for each --screenshot tick that it shows. */ + void RequestScreenshots(); + + /** After the frame is drawn: log the screenshots that it saved, or why not. */ + void SaveScreenshots(); + + /** --dump-state: the ticks whose state has not been written yet. Sorted. */ + std::vector m_PendingStateDumps; + + /** --dump-state: files that could not be written. */ + uint32 m_StateDumpsFailed = 0; + + /** --screenshot: the ticks whose frame has not been saved yet. Sorted. */ + std::vector m_PendingScreenshots; + + /** --screenshot: for each capture asked for this frame, the tick asked for and the tick the frame shows. */ + std::vector> m_ScreenshotShownTicks; + + /** --screenshot: captures that failed. */ + uint32 m_ScreenshotsFailed = 0; + /** The exec mode's policies: the world's mode and last tick, and for threaded play the game thread and input. */ void SetUpExecMode(); diff --git a/FlingEngine/Application/src/Engine.cpp b/FlingEngine/Application/src/Engine.cpp index be314e83..ef49ed5d 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -23,6 +23,7 @@ #include "VulkanApp.h" #include +#include #include #include #include @@ -286,10 +287,10 @@ namespace Fling ResourceManager::Get().Init(); Timing::Get().Init(); - // A headless run has no real time: the platform clock is virtual, and the loop - // moves it by a fixed step per frame. Install it before input, so every input - // message time comes from it. - if (m_Options.NullRender) + // A headless run (--null-render or --offscreen) has no real time: the platform clock + // is virtual, and the loop moves it by a fixed step per frame. Install it before + // input, so every input message time comes from it. + if (m_Options.IsHeadless()) { m_HeadlessClock = std::make_unique(HeadlessFrameNs(0)); PlatformTime::UseVirtualClock(m_HeadlessClock.get()); @@ -361,11 +362,27 @@ namespace Fling } else { + RenderSurfaceDesc Surface; + Surface.Offscreen = m_Options.Offscreen; + Surface.Width = m_Options.ResolutionWidth; + Surface.Height = m_Options.ResolutionHeight; + VulkanApp::Get().SetRenderSurface(Surface); + + uint32 Pipelines = PipelineFlags::DEFERRED | PipelineFlags::CUBEMAP; + if (m_Options.Offscreen) + { + // The developer UI is ImGui, which reads its input from a window: offscreen there + // is none, so the frames show the game only + F_LOG_TRACE("Fling render: offscreen (--offscreen), no window"); + m_DebugUI.reset(); + } + else + { + Pipelines |= PipelineFlags::IMGUI; + } VulkanApp::Get().SetVSync(m_Settings.VSync); - VulkanApp::Get().Init( - static_cast(PipelineFlags::DEFERRED | PipelineFlags::CUBEMAP | PipelineFlags::IMGUI), - Storage, - m_DebugUI); + VulkanApp::Get().Init(static_cast(Pipelines), Storage, m_DebugUI); + F_LOG_TRACE("Render size: {}x{}", VulkanApp::Get().GetFrameWidth(), VulkanApp::Get().GetFrameHeight()); } // The frame cap's default is the refresh rate of the window's monitor @@ -410,11 +427,12 @@ namespace Fling m_World->SetTickClock([]() { return PlatformTime::NowNanoseconds(); }); // The per-tick state hash costs about 0.7 ms a tick in a Debug Sandbox (754 // transforms): on for headless runs and --dump-ticks, off for a windowed game. - m_World->SetStateHashEnabled(m_Options.NullRender || !m_Options.DumpTicks.empty()); + m_World->SetStateHashEnabled(m_Options.IsHeadless() || !m_Options.DumpTicks.empty() || + !m_Options.DumpState.empty()); m_World->SetInterpolation(m_Settings.Interpolation); m_Controls = std::make_unique(m_Settings, *m_World); UpdateFrameLimiter(); - if (m_Options.NullRender) + if (m_Options.IsHeadless()) { m_World->SetTickTimelineStart(HeadlessFrameNs(1) - TickNs()); m_World->SetTickClockOnlyMovesWithFrames(true); @@ -430,7 +448,7 @@ namespace Fling // every exec mode; World::MakeTickInputConfig says how a game thread waits for it: a // headless run or a replay waits for every message of the window (the cuts are the // same as in Direct), live windowed play does not wait. - const int64 WatermarkWaitNs = (m_Options.NullRender || !m_Options.ReplayInput.empty()) ? -1 : 0; + const int64 WatermarkWaitNs = (m_Options.IsHeadless() || !m_Options.ReplayInput.empty()) ? -1 : 0; auto TickInputs = std::make_shared(Input::Get(), m_World->MakeTickInputConfig(WatermarkWaitNs)); m_World->SetTickInputSource([TickInputs](TickInput& t_Out, const TickWindow& t_Window) @@ -450,6 +468,25 @@ namespace Fling m_World->KeepTickRecords(); } + // --dump-state and --screenshot: at the listed ticks, or the last tick of the run + if (!m_Options.DumpState.empty()) + { + m_PendingStateDumps = + m_Options.DumpStateTicks.empty() ? std::vector{LastTickOfRun()} : m_Options.DumpStateTicks; + m_World->SetStateDumpTicks(m_PendingStateDumps); + F_LOG_TRACE("Writing the state at {} tick(s) to {} (--dump-state)", + m_PendingStateDumps.size(), + FlingPaths::ResolveProjectPath(m_Options.DumpState)); + } + if (!m_Options.Screenshot.empty()) + { + m_PendingScreenshots = + m_Options.ScreenshotTicks.empty() ? std::vector{LastTickOfRun()} : m_Options.ScreenshotTicks; + F_LOG_TRACE("Saving the frames of {} tick(s) to {} (--screenshot)", + m_PendingScreenshots.size(), + FlingPaths::ResolveProjectPath(m_Options.Screenshot)); + } + // The runner fills PendingInput for the frame side with the messages after the cut of the tick // it shows (RealFrameTime::Latest: the packet in the mirror in Inline and Threaded // play), without consuming them. UI capture comes from the stream, so it drops the @@ -478,7 +515,7 @@ namespace Fling F_LOG_TRACE("Fling debug UI: Disabled"); } - if (!m_Options.NullRender) + if (!m_Options.IsHeadless()) { // The window exists now. Its events are pumped by the GLFW input interface m_InputWindow = GetInputWindowHandle(VulkanApp::Get().GetCurrentWindow()); @@ -551,7 +588,7 @@ namespace Fling // Under --null-render each frame has the same delta and never waits on real time // for its ticks, so a run is as fast as the CPU allows - const float DeltaTime = m_Options.NullRender ? NullRenderDeltaTime : Timing.GetDeltaTime(); + const float DeltaTime = m_Options.IsHeadless() ? NullRenderDeltaTime : Timing.GetDeltaTime(); Stats::Frames::FrameStats(DeltaTime); PumpInput(DeltaTime); @@ -561,6 +598,7 @@ namespace Fling // threaded play), the ticks' outbox, then the frame systems on what the world shows m_World->Update(DeltaTime); DumpNewTicks(); + WriteStateDumps(); HandleAppRequests(); if (m_World->ShouldQuit()) @@ -576,7 +614,10 @@ namespace Fling } else { + // A window, or offscreen images (--offscreen) + RequestScreenshots(); Present(DeltaTime); + SaveScreenshots(); } Timing.UpdateFps(); } @@ -590,6 +631,18 @@ namespace Fling m_World->GetTickCount(), AverageFrameMs, AverageFrameMs > 0.0 ? 1000.0 / AverageFrameMs : 0.0); + // A screenshot that was asked for and not taken fails the run, so a script does not read an old file + bool bCapturesOk = m_ScreenshotsFailed == 0; + for (const uint64 Tick : m_PendingScreenshots) + { + F_LOG_ERROR( + "--screenshot: no frame showed tick {} (the run showed up to tick {})", Tick, m_World->GetShownTick()); + bCapturesOk = false; + } + if (!bCapturesOk) + { + return ExitCode::Failure; + } #if WITH_INPUT_RECORDING if (Input::Get().GetPlayback().HasOverrun()) { @@ -623,7 +676,7 @@ namespace Fling { for (const AppRequest Request : m_World->TakeAppRequests()) { - if (Request == AppRequest::ToggleCursor && !m_Options.NullRender) + if (Request == AppRequest::ToggleCursor && !m_Options.IsHeadless()) { FlingWindow* Window = VulkanApp::Get().GetCurrentWindow(); if (Window) @@ -641,20 +694,24 @@ namespace Fling VulkanApp::Get().SetVSync(m_Controls->VSync()); VulkanApp::Get().Update(t_DeltaTime, m_World->GetPresentedStorage()); - const bool bInBackground = !VulkanApp::Get().GetCurrentWindow()->IsFocused(); - if (bInBackground != m_Controls->InBackground()) + // Offscreen there is no window: no focus, no monitor, and no frame cap (headless) + if (const FlingWindow* Window = VulkanApp::Get().GetCurrentWindow()) { - m_Controls->SetInBackground(bInBackground); - F_LOG_TRACE("Window in the {}", bInBackground ? "background" : "front"); - } - // The window can move to another monitor; a frame cap that came from the monitor follows - const int64 NowNs = PlatformTime::NowNanoseconds(); - if (NowNs >= m_NextMonitorCheckNs) - { - m_NextMonitorCheckNs = NowNs + MonitorCheckIntervalNs; - m_Controls->SetMonitorHz(WindowMonitorHz()); + const bool bInBackground = !Window->IsFocused(); + if (bInBackground != m_Controls->InBackground()) + { + m_Controls->SetInBackground(bInBackground); + F_LOG_TRACE("Window in the {}", bInBackground ? "background" : "front"); + } + // The window can move to another monitor; a frame cap that came from the monitor follows + const int64 NowNs = PlatformTime::NowNanoseconds(); + if (NowNs >= m_NextMonitorCheckNs) + { + m_NextMonitorCheckNs = NowNs + MonitorCheckIntervalNs; + m_Controls->SetMonitorHz(WindowMonitorHz()); + } + UpdateFrameLimiter(); } - UpdateFrameLimiter(); // The game ticks on its own clock, so it runs at the same speed, only shown less often m_FrameLimiter.WaitForNextFrame(); @@ -662,14 +719,15 @@ namespace Fling std::optional Engine::WindowMonitorHz() const { - const FlingWindow* Window = m_Options.NullRender ? nullptr : VulkanApp::Get().GetCurrentWindow(); + const FlingWindow* Window = m_Options.IsHeadless() ? nullptr : VulkanApp::Get().GetCurrentWindow(); return Window != nullptr ? std::optional(Window->GetRefreshRate()) : std::nullopt; } void Engine::UpdateFrameLimiter() { // Headless there is no swap chain and no refresh rate, so the cap applies as it is - const bool bDisplayPacesFrames = !m_Options.NullRender && DisplayPacesFrames(VulkanApp::Get().GetPresentMode()); + const bool bDisplayPacesFrames = + !m_Options.IsHeadless() && DisplayPacesFrames(VulkanApp::Get().GetPresentMode()); const uint32 LimiterFps = m_Controls->LimiterFps(bDisplayPacesFrames); if (LimiterFps != m_FrameLimiter.GetMaxFps()) { @@ -677,7 +735,7 @@ namespace Fling F_LOG_TRACE("Frame limiter: {} (cap {} fps, present mode {})", m_Controls->DescribeLimiter(bDisplayPacesFrames), m_Controls->MaxFps(), - m_Options.NullRender ? "none" : PresentModeName(VulkanApp::Get().GetPresentMode())); + m_Options.IsHeadless() ? "none" : PresentModeName(VulkanApp::Get().GetPresentMode())); } } @@ -701,7 +759,7 @@ namespace Fling // as soon as it is due. Input::Get().SetWriterLane(Lane::Frame); GameLaneDesc Desc; - Desc.Pacing = m_Options.NullRender ? GameLanePacing::AsFastAsPossible : GameLanePacing::RealTime; + Desc.Pacing = m_Options.IsHeadless() ? GameLanePacing::AsFastAsPossible : GameLanePacing::RealTime; Desc.JitterSeed = m_Options.JitterSeed; Desc.JitterMaxMicroseconds = m_Options.JitterMaxMicroseconds; m_World->SetGameLaneDesc(Desc); @@ -748,6 +806,83 @@ namespace Fling m_DumpTicksFile->flush(); } + void Engine::WriteStateDumps() + { + if (!m_World || m_Options.DumpState.empty()) + { + return; + } + const bool bManyTicks = m_Options.DumpStateTicks.size() > 1; + for (const World::StateDump& Dump : m_World->TakeStateDumps()) + { + std::erase(m_PendingStateDumps, Dump.Tick); + const String Path = + FlingPaths::ResolveProjectPath(CaptureFilePath(m_Options.DumpState, Dump.Tick, bManyTicks)); + std::error_code DirError; + const std::filesystem::path FsPath = PathFromUtf8(Path); + if (FsPath.has_parent_path()) + { + std::filesystem::create_directories(FsPath.parent_path(), DirError); + } + std::ofstream File(FsPath, std::ios::binary | std::ios::trunc); + File << Dump.Doc.Dump(2) << '\n'; + if (!File) + { + F_LOG_ERROR("--dump-state: cannot write {}", Path); + ++m_StateDumpsFailed; + continue; + } + F_LOG_TRACE("Wrote the state of tick {} ({} entities, state hash {}) to {}", + Dump.Tick, + Dump.Doc.GetUInt64("entityCount"), + Dump.Doc.GetString("stateHash"), + Path); + } + } + + void Engine::RequestScreenshots() + { + // The frame that first shows each tick. With threaded play the frame side can show a + // later tick than the one asked for; the log line says which tick the file shows. + const uint64 Shown = m_World->GetShownTick(); + const bool bManyTicks = m_Options.ScreenshotTicks.size() > 1; + while (!m_PendingScreenshots.empty() && m_PendingScreenshots.front() <= Shown) + { + const uint64 Tick = m_PendingScreenshots.front(); + m_PendingScreenshots.erase(m_PendingScreenshots.begin()); + const String Path = FlingPaths::ResolveProjectPath(CaptureFilePath(m_Options.Screenshot, Tick, bManyTicks)); + VulkanApp::Get().RequestCapture(Path); + m_ScreenshotShownTicks.push_back({Tick, Shown}); + } + } + + void Engine::SaveScreenshots() + { + std::vector Results = VulkanApp::Get().TakeCaptureResults(); + for (size_t i = 0; i < Results.size(); ++i) + { + const CaptureResult& Result = Results[i]; + const std::pair Ticks = + i < m_ScreenshotShownTicks.size() ? m_ScreenshotShownTicks[i] : std::pair{0, 0}; + if (!Result.Ok) + { + F_LOG_ERROR("--screenshot: cannot save {}: {}", Result.Path, Result.Error); + ++m_ScreenshotsFailed; + continue; + } + F_LOG_TRACE("Saved the frame of tick {} (it shows tick {}, {}x{}) to {}", + Ticks.first, + Ticks.second, + VulkanApp::Get().GetFrameWidth(), + VulkanApp::Get().GetFrameHeight(), + Result.Path); + } + // A frame that was not drawn (a window resize) keeps its captures for the next frame + const size_t Done = std::min(Results.size(), m_ScreenshotShownTicks.size()); + m_ScreenshotShownTicks.erase(m_ScreenshotShownTicks.begin(), + m_ScreenshotShownTicks.begin() + static_cast(Done)); + } + bool Engine::ShouldTick() const { // --frames: the run ends after N frames, once the frame side shows the last tick (the @@ -760,7 +895,7 @@ namespace Fling return false; } - if (!m_Options.NullRender && VulkanApp::Get().GetCurrentWindow()->ShouldClose()) + if (!m_Options.IsHeadless() && VulkanApp::Get().GetCurrentWindow()->ShouldClose()) { return false; } @@ -775,6 +910,22 @@ namespace Fling { m_World->Shutdown(); m_TicksAtExit = m_World->GetTickCount(); + + // The game thread has joined: a dump that it made after the last frame is here now + WriteStateDumps(); + if (!m_Options.DumpState.empty() && t_Code == ExitCode::Success) + { + bool bDumpsOk = m_StateDumpsFailed == 0; + for (const uint64 Tick : m_PendingStateDumps) + { + F_LOG_ERROR("--dump-state: tick {} did not run (the run ran {} ticks)", Tick, m_TicksAtExit); + bDumpsOk = false; + } + if (!bDumpsOk) + { + t_Code = ExitCode::Failure; + } + } } // The world still holds the game until the world is destroyed below @@ -841,7 +992,7 @@ namespace Fling { const double WallSeconds = std::chrono::duration(std::chrono::steady_clock::now() - m_StartTime).count(); - const char* Render = m_Options.NullRender ? "null" : "vulkan"; + const char* Render = m_Options.NullRender ? "null" : (m_Options.Offscreen ? "offscreen" : "vulkan"); if (m_Options.Format == LogFormat::Json) { diff --git a/FlingEngine/Core/inc/LaunchOptions.h b/FlingEngine/Core/inc/LaunchOptions.h index eaa4236b..546eaa4b 100644 --- a/FlingEngine/Core/inc/LaunchOptions.h +++ b/FlingEngine/Core/inc/LaunchOptions.h @@ -6,6 +6,7 @@ #include "Strings/String.h" #include +#include namespace Fling { @@ -27,6 +28,21 @@ namespace Fling * LaunchOptions::Parse. * * --null-render No window, no swapchain, no GPU work + * --offscreen Render with the GPU into images the engine owns: no window and no + * surface. Timing is the same as --null-render (a virtual clock, no + * frame cap), so a run gives the same ticks. For --screenshot + * --resolution WxH The size of the frames (--offscreen) or of the window, for example 1280x720. + * Overrides [Engine] WindowWidth and WindowHeight + * --screenshot F Save the rendered frame as a PNG file F (relative to the project). + * Needs a renderer (--offscreen or a window), not --null-render + * --screenshot-ticks L The ticks to save a frame at, a comma list such as 30,60,120: the + * first frame that shows each tick. With more than one tick, or with + * {tick} in F, each file name gets the tick. Without it: the last tick + * of the run (needs --frames) + * --dump-state F Write the simulation state (every saved component and singleton) as + * JSON to file F, on the game thread right after a tick. Works with + * --null-render + * --dump-state-ticks L The ticks to write the state at (the same rules as --screenshot-ticks) * --unattended No modal dialogs. A crash prints a stack trace and exits with code 2 * --frames N Run N frames, then exit, in every exec mode. No tick runs after * tick N / frames-per-tick (rounded up), and the run ends once that @@ -65,6 +81,28 @@ namespace Fling { bool NullRender = false; + /** Render into offscreen images: no window, no surface (--offscreen). */ + bool Offscreen = false; + + /** --resolution: the frame or window size. 0 means use the config. */ + uint32 ResolutionWidth = 0; + uint32 ResolutionHeight = 0; + + /** The PNG file to save rendered frames to (--screenshot). Empty means none. */ + String Screenshot; + + /** The ticks to save a frame at (--screenshot-ticks). Empty: the last tick of the run. Sorted. */ + std::vector ScreenshotTicks; + + /** The JSON file to write the simulation state to (--dump-state). Empty means none. */ + String DumpState; + + /** The ticks to write the state at (--dump-state-ticks). Empty: the last tick of the run. Sorted. */ + std::vector DumpStateTicks; + + /** True with no window (--null-render, --offscreen): a virtual clock and no frame cap. */ + bool IsHeadless() const { return NullRender || Offscreen; } + bool Unattended = false; /** Number of frames to run before the engine exits (--frames). 0 means no limit. */ @@ -157,6 +195,13 @@ namespace Fling static bool Parse(const CommandLine& t_CmdLine, LaunchOptions& t_Out, String& t_OutError); }; + /** + * The file name of one capture (--screenshot, --dump-state) at a tick. "{tick}" in the path + * is replaced with the tick. Without it, when there is more than one tick, "_tick" goes + * before the extension (shot.png: shot_tick30.png). Otherwise the path is used as it is. + */ + String CaptureFilePath(StringView t_Path, uint64 t_Tick, bool t_ManyTicks); + /** Read "on" or "off" (a switch setting such as --vsync or [Engine] VSync). False for any other text. */ inline bool ParseOnOff(const StringView t_Text, bool& t_Out) { diff --git a/FlingEngine/Core/inc/RunSettings.h b/FlingEngine/Core/inc/RunSettings.h index e857bf4d..dc4a1ccb 100644 --- a/FlingEngine/Core/inc/RunSettings.h +++ b/FlingEngine/Core/inc/RunSettings.h @@ -124,6 +124,9 @@ namespace Fling /** True for a --null-render run: no monitor, and no frame cap unless a setting asks for one. */ bool Headless = false; + /** The flag that made the run headless, for messages: "--null-render" or "--offscreen". */ + const char* HeadlessFlag = "--null-render"; + /** Settings that were given but do nothing in this run, one line each, for the startup log. */ std::vector Ignored; diff --git a/FlingEngine/Core/src/LaunchOptions.cpp b/FlingEngine/Core/src/LaunchOptions.cpp index 36d91bcc..f4dd412f 100644 --- a/FlingEngine/Core/src/LaunchOptions.cpp +++ b/FlingEngine/Core/src/LaunchOptions.cpp @@ -3,11 +3,19 @@ #include "Strings/String.h" #include "Strings/StringUtils.h" +#include + namespace Fling { namespace { constexpr StringView NullRenderFlag = "null-render"; + constexpr StringView OffscreenFlag = "offscreen"; + constexpr StringView ResolutionFlag = "resolution"; + constexpr StringView ScreenshotFlag = "screenshot"; + constexpr StringView ScreenshotTicksFlag = "screenshot-ticks"; + constexpr StringView DumpStateFlag = "dump-state"; + constexpr StringView DumpStateTicksFlag = "dump-state-ticks"; constexpr StringView UnattendedFlag = "unattended"; constexpr StringView FramesFlag = "frames"; constexpr StringView FramesPerTickFlag = "frames-per-tick"; @@ -137,6 +145,48 @@ namespace Fling return true; } + /** Read a list of tick numbers, such as 30,60,120 (each 1 or more). The result is sorted, with no repeats. */ + bool + ReadTickList(const CommandLine& t_CmdLine, StringView t_Flag, std::vector& t_Out, String& t_OutError) + { + const std::optional Value = t_CmdLine.GetValueAsString(t_Flag); + if (!Value) + { + return true; + } + StringView Rest = *Value; + const auto Fail = [&]() + { + t_OutError = "--" + String(t_Flag) + + " needs a comma list of ticks (1 or more), for example 30,60,120, not '" + String(*Value) + + "'"; + return false; + }; + if (Rest.empty() || Rest == "true") + { + return Fail(); + } + while (true) + { + const size_t Comma = Rest.find(','); + const StringView Item = Rest.substr(0, Comma); + uint32 Tick = 0; + if (!TryParseUint32(Item, Tick) || Tick == 0) + { + return Fail(); + } + t_Out.push_back(Tick); + if (Comma == StringView::npos) + { + break; + } + Rest = Rest.substr(Comma + 1); + } + std::sort(t_Out.begin(), t_Out.end()); + t_Out.erase(std::unique(t_Out.begin(), t_Out.end()), t_Out.end()); + return true; + } + /** Read a uint32 flag into an optional: empty when the flag is not given. */ bool ReadOptionalUint32(const CommandLine& t_CmdLine, StringView t_Flag, @@ -172,6 +222,59 @@ namespace Fling return false; } + if (!ReadBool(t_CmdLine, OffscreenFlag, t_Out.Offscreen, t_OutError)) + { + return false; + } + if (t_Out.Offscreen && t_Out.NullRender) + { + t_OutError = "--offscreen and --null-render cannot be used together: --offscreen renders, --null-render " + "does not"; + return false; + } + + if (const std::optional Resolution = t_CmdLine.GetValueAsString(ResolutionFlag)) + { + const StringView Str = *Resolution; + const size_t X = Str.find('x'); + uint32 Width = 0; + uint32 Height = 0; + if (X == StringView::npos || !TryParseUint32(Str.substr(0, X), Width) || + !TryParseUint32(Str.substr(X + 1), Height) || Width == 0 || Height == 0 || Width > 8192 || + Height > 8192) + { + t_OutError = "--resolution needs x from 1 to 8192, for example 1280x720, not '" + + String(Str) + "'"; + return false; + } + t_Out.ResolutionWidth = Width; + t_Out.ResolutionHeight = Height; + } + + if (!ReadPath(t_CmdLine, ScreenshotFlag, t_Out.Screenshot, t_OutError) || + !ReadTickList(t_CmdLine, ScreenshotTicksFlag, t_Out.ScreenshotTicks, t_OutError) || + !ReadPath(t_CmdLine, DumpStateFlag, t_Out.DumpState, t_OutError) || + !ReadTickList(t_CmdLine, DumpStateTicksFlag, t_Out.DumpStateTicks, t_OutError)) + { + return false; + } + if (!t_Out.ScreenshotTicks.empty() && t_Out.Screenshot.empty()) + { + t_OutError = "--screenshot-ticks needs --screenshot "; + return false; + } + if (!t_Out.DumpStateTicks.empty() && t_Out.DumpState.empty()) + { + t_OutError = "--dump-state-ticks needs --dump-state "; + return false; + } + if (!t_Out.Screenshot.empty() && t_Out.NullRender) + { + t_OutError = "--screenshot needs a renderer: use --offscreen instead of --null-render (or --dump-state " + "for the state as text)"; + return false; + } + if (!ReadBool(t_CmdLine, DumpScheduleFlag, t_Out.DumpSchedule, t_OutError) || !ReadBool(t_CmdLine, ValidateScheduleFlag, t_Out.ValidateSchedule, t_OutError)) { @@ -337,6 +440,44 @@ namespace Fling } #endif + // A capture with no tick list is at the last tick of the run, so the run must have one + if (t_Out.Frames == 0) + { + if (!t_Out.Screenshot.empty() && t_Out.ScreenshotTicks.empty()) + { + t_OutError = "--screenshot needs --frames N (a frame at the last tick) or --screenshot-ticks"; + return false; + } + if (!t_Out.DumpState.empty() && t_Out.DumpStateTicks.empty()) + { + t_OutError = "--dump-state needs --frames N (the state at the last tick) or --dump-state-ticks"; + return false; + } + } + return true; } + + String CaptureFilePath(const StringView t_Path, const uint64 t_Tick, const bool t_ManyTicks) + { + String Path(t_Path); + const String TickText = std::to_string(t_Tick); + constexpr StringView Placeholder = "{tick}"; + if (const size_t At = Path.find(Placeholder); At != String::npos) + { + Path.replace(At, Placeholder.size(), TickText); + return Path; + } + if (!t_ManyTicks) + { + return Path; + } + // Before the extension, if the file name has one + const size_t Slash = Path.find_last_of("/\\"); + const size_t Dot = Path.find_last_of('.'); + const bool bHasExtension = Dot != String::npos && (Slash == String::npos || Dot > Slash); + const size_t InsertAt = bHasExtension ? Dot : Path.size(); + Path.insert(InsertAt, "_tick" + TickText); + return Path; + } } // namespace Fling diff --git a/FlingEngine/Core/src/RunSettings.cpp b/FlingEngine/Core/src/RunSettings.cpp index 2411bfd7..d20f11a2 100644 --- a/FlingEngine/Core/src/RunSettings.cpp +++ b/FlingEngine/Core/src/RunSettings.cpp @@ -162,7 +162,8 @@ namespace Fling using Keys = RunSettingsConfig; t_Out = RunSettings{}; t_OutError.clear(); - t_Out.Headless = t_Options.NullRender; + t_Out.Headless = t_Options.IsHeadless(); + t_Out.HeadlessFlag = t_Options.Offscreen ? "--offscreen" : "--null-render"; const NumberRange SimHzRange{.Min = SimRate::MinHz, .Max = SimRate::MaxHz, .Unit = "ticks a second"}; const NumberRange MaxFpsRange{.Min = 1, .Max = MaxMaxFps, .AllowZero = true, .Unit = "frames a second"}; @@ -202,7 +203,8 @@ namespace Fling } if (t_Out.Headless && t_Options.VSync) { - t_Out.Ignored.push_back("--vsync does nothing with --null-render: there is no swap chain"); + t_Out.Ignored.push_back(String("--vsync does nothing with ") + t_Out.HeadlessFlag + + ": there is no swap chain"); } return true; } @@ -241,7 +243,8 @@ namespace Fling String CapSource = SettingSourceName(MaxFpsSource); if (MaxFpsSource == SettingSource::Default) { - CapSource = Headless ? "default for --null-render" : "default: the monitor refresh rate is not known"; + CapSource = + Headless ? String("default for ") + HeadlessFlag : "default: the monitor refresh rate is not known"; } else if (MaxFpsSource == SettingSource::Monitor) { diff --git a/FlingEngine/Engine/inc/Ecs/TypeRegistry.h b/FlingEngine/Engine/inc/Ecs/TypeRegistry.h index 01ad4355..5cdd7a87 100644 --- a/FlingEngine/Engine/inc/Ecs/TypeRegistry.h +++ b/FlingEngine/Engine/inc/Ecs/TypeRegistry.h @@ -96,6 +96,9 @@ namespace Fling /** Ids that the save gives to entities with none (or a shared one): the document has them, the storage not. */ const std::unordered_map* NewGuids = nullptr; + + /** Write Transient fields too (World::SaveStateToJson): a state dump shows every field, a level does not. */ + bool IncludeTransientFields = false; }; /** What a load needs beyond the object: how to find an entity from a saved EntityGuid. */ diff --git a/FlingEngine/Engine/inc/World.h b/FlingEngine/Engine/inc/World.h index 9a6aae8f..af75f290 100644 --- a/FlingEngine/Engine/inc/World.h +++ b/FlingEngine/Engine/inc/World.h @@ -146,6 +146,24 @@ namespace Fling /** The ledger records of the ticks since the last call, in tick order (KeepTickRecords). */ std::vector TakeNewTickRecords(); + /** The simulation state after one tick (SetStateDumpTicks). */ + struct StateDump + { + uint64 Tick = 0; + + /** SaveStateToJson's document. */ + Json Doc; + }; + + /** + * Write the state (SaveStateToJson) right after each of these ticks, on the thread that + * runs the ticks, for TakeStateDumps (--dump-state). Sorted. Call it before play starts. + */ + void SetStateDumpTicks(std::vector t_Ticks) { m_StateDumpTicks = std::move(t_Ticks); } + + /** The state dumps of the ticks since the last call, in tick order (SetStateDumpTicks). */ + std::vector TakeStateDumps(); + /** * Set the function that reads the input after a sequence, for the frame side * (see SystemRunner::SetPendingInputSource). Set it before Init. @@ -344,6 +362,19 @@ namespace Fling */ bool SaveToJson(Json& t_OutDoc, StringView t_Title) const; + /** + * Write the simulation state to a document, for an agent or a test to read (--dump-state). + * The types are the ones the state hash covers (rollback state) and the ones a level + * saves, with every field (Transient fields too). Top level: "tick", "stateHash" + * (TickRecord::StateHash, 0 when off), "simHz", "entityCount", "entities" (in handle + * order: "entity" index:generation, "name" when it has one, "guid", then one object per + * component) and "singletons". An entity with no EntityGuid gets an id made from its + * handle, not a random one, so the same run writes the same document. It is not a level + * file: LoadFromJson does not read it. Call it on the thread that owns the simulation + * storage (OnTickDone does). + */ + bool SaveStateToJson(Json& t_OutDoc, uint64 t_Tick) const; + /** * Remove all entities, then make the entities in a level document. A component * loads after the components that it requires, and one that the document does not @@ -404,7 +435,7 @@ namespace Fling TickHost& AsTickHost() { return *this; } /** A new EntityGuid for each entity that has none, or the same one as an entity before it. */ - std::unordered_map MakeMissingEntityGuids() const; + std::unordered_map MakeMissingEntityGuids(bool t_FromHandles = false) const; /** Run the pending start or stop request, if there is one */ void ProcessPlayRequest(); @@ -595,6 +626,12 @@ namespace Fling /** Tick thread to main thread: @see KeepTickRecords */ ThreadQueue m_NewTickRecords; + /** @see SetStateDumpTicks. Set before play; the tick thread reads it. */ + std::vector m_StateDumpTicks; + + /** Tick thread to main thread: @see SetStateDumpTicks */ + ThreadQueue m_StateDumps; + // The main thread's state /** The newest tick whose outbox entry was applied. An entry that is not newer is a repeat. */ diff --git a/FlingEngine/Engine/src/Ecs/Reflection.cpp b/FlingEngine/Engine/src/Ecs/Reflection.cpp index 63cbd217..31501088 100644 --- a/FlingEngine/Engine/src/Ecs/Reflection.cpp +++ b/FlingEngine/Engine/src/Ecs/Reflection.cpp @@ -607,7 +607,7 @@ namespace Fling for (const FieldDesc& field : type.Fields) { - if (!field.Transient) + if (!field.Transient || context.IncludeTransientFields) { SaveField(field, object, out, context); } diff --git a/FlingEngine/Engine/src/World.cpp b/FlingEngine/Engine/src/World.cpp index b09d06f5..8831e718 100644 --- a/FlingEngine/Engine/src/World.cpp +++ b/FlingEngine/Engine/src/World.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -611,6 +612,15 @@ namespace Fling { m_NewTickRecords.Push(*m_Runner->GetLedger().Latest()); } + if (std::binary_search(m_StateDumpTicks.begin(), m_StateDumpTicks.end(), t_Tick)) + { + StateDump Dump; + Dump.Tick = t_Tick; + if (SaveStateToJson(Dump.Doc, t_Tick)) + { + m_StateDumps.Push(std::move(Dump)); + } + } AppRequests* Queue = m_Storage.TryGetSingleton(); if (!Queue || Queue->Requests.empty()) { @@ -737,6 +747,13 @@ namespace Fling return Records; } + std::vector World::TakeStateDumps() + { + std::vector Dumps; + m_StateDumps.Drain([&Dumps](StateDump& t_Dump) { Dumps.push_back(std::move(t_Dump)); }); + return Dumps; + } + bool World::RequestSimHz(const uint32 t_Hz, String& t_OutError, const uint64 t_BeforeTick) { t_OutError.clear(); @@ -819,7 +836,7 @@ namespace Fling return root.SaveToFile(FullPath); } - std::unordered_map World::MakeMissingEntityGuids() const + std::unordered_map World::MakeMissingEntityGuids(const bool t_FromHandles) const { std::unordered_set UsedGuids; std::vector NeedGuid; @@ -840,13 +857,15 @@ namespace Fling { return NewGuids; } - std::mt19937_64 Generator{std::random_device{}()}; + // A state dump makes the same ids in the same run: each one comes from the handle, + // with the top bit set so it is not 0, and the next free value if it is taken + std::mt19937_64 Generator{t_FromHandles ? 0u : std::random_device{}()}; for (const Fling::Entity Entity : NeedGuid) { - uint64 Value = 0; + uint64 Value = t_FromHandles ? (Entity.ToBits() | (uint64{1} << 63)) : 0; while (Value == 0 || !UsedGuids.insert(Value).second) { - Value = Generator(); + Value = t_FromHandles ? Value + 1 : Generator(); } NewGuids.emplace(Entity, Value); } @@ -956,6 +975,116 @@ namespace Fling return true; } + bool World::SaveStateToJson(Json& t_OutDoc, const uint64 t_Tick) const + { + if (!m_TypesBuilt) + { + F_LOG_ERROR("Cannot write the world state before World::Init"); + return false; + } + + // The types that the state hash covers (rollback state) and the ones a level saves, + // with every field, Transient ones too + std::vector ComponentTypes; + std::vector SingletonTypes; + for (const TypeDesc& Type : m_Types.All()) + { + if (!Type.IsSaved() && !Type.IsRollbackState()) + { + continue; + } + if (Type.IsSingleton()) + { + SingletonTypes.push_back(&Type); + } + else if (!IsReservedEntityKey(Type.Name)) + { + ComponentTypes.push_back(&Type); + } + } + const auto ByName = [](const TypeDesc* a, const TypeDesc* b) + { + return a->Name < b->Name; + }; + std::sort(ComponentTypes.begin(), ComponentTypes.end(), ByName); + std::sort(SingletonTypes.begin(), SingletonTypes.end(), ByName); + + // Entities in handle order, which is the same for the same run. Ids made from the handles, + // so Entity fields name their targets the same way in every run + const std::unordered_map NewGuids = MakeMissingEntityGuids(/* t_FromHandles */ true); + SaveContext Context{&m_Storage, &NewGuids}; + Context.IncludeTransientFields = true; + std::vector Entities; + m_Storage.EachEntity([&](const Fling::Entity t_Entity) { Entities.push_back(t_Entity); }); + std::sort(Entities.begin(), Entities.end()); + + Json EntitiesJson = Json::Array(); + for (const Fling::Entity Each : Entities) + { + Json EntityJson = Json::Object(); + char Handle[32]; + std::snprintf(Handle, sizeof(Handle), "%u:%u", Each.Index, Each.Generation); + EntityJson.Set("entity", StringView(Handle)); + if (const NameComponent* Named = m_Storage.TryGet(Each)) + { + EntityJson.Set("name", Named->Name.ToView()); + } + if (const auto Found = NewGuids.find(Each); Found != NewGuids.end()) + { + EntityJson.SetUInt64("guid", Found->second); + } + else if (const EntityGuid* Guid = m_Storage.TryGet(Each)) + { + EntityJson.SetUInt64("guid", Guid->Value); + } + for (const TypeDesc* Type : ComponentTypes) + { + if (Type->Has == nullptr || !Type->Has(m_Storage, Each) || Type->Name == EntityGuid::Component.Name) + { + continue; + } + Json ComponentJson = Json::Object(); + if (!Type->IsTag() && Type->GetConst) + { + SaveObject(*Type, Type->GetConst(m_Storage, Each), ComponentJson, Context); + } + EntityJson.Set(Type->Name, ComponentJson); + } + EntitiesJson.PushBack(EntityJson); + } + + Json Singletons = Json::Object(); + for (const TypeDesc* Type : SingletonTypes) + { + if (const void* Object = Type->GetSingletonConst ? Type->GetSingletonConst(m_Storage) : nullptr) + { + Json SingletonJson = Json::Object(); + SaveObject(*Type, Object, SingletonJson, Context); + Singletons.Set(Type->Name, SingletonJson); + } + } + + uint64 StateHash = 0; + if (m_Runner) + { + if (const TickRecord* Latest = m_Runner->GetLedger().Latest(); Latest && Latest->Stamp.Tick == t_Tick) + { + StateHash = Latest->Stamp.StateHash; + } + } + char HashText[17]; + std::snprintf(HashText, sizeof(HashText), "%016llx", static_cast(StateHash)); + + t_OutDoc = Json::Object(); + t_OutDoc.SetUInt64("tick", t_Tick); + t_OutDoc.Set("stateHash", StringView(HashText)); + t_OutDoc.SetUInt64("simHz", GetSimHz()); + t_OutDoc.SetUInt64("entityCount", Entities.size()); + t_OutDoc.Set("entities", EntitiesJson); + t_OutDoc.Set("singletons", Singletons); + return true; + } + bool World::LoadLevelFile(const StringView t_LevelToLoad) { if (!m_TypesBuilt) diff --git a/FlingEngine/Graphics/inc/VulkanApp.h b/FlingEngine/Graphics/inc/VulkanApp.h index 57e4b8e9..787bb2bd 100644 --- a/FlingEngine/Graphics/inc/VulkanApp.h +++ b/FlingEngine/Graphics/inc/VulkanApp.h @@ -7,6 +7,7 @@ #include "Strings/String.h" #include +#include #include namespace Fling @@ -23,6 +24,35 @@ namespace Fling ALL = 0xff }; + /** + * What the renderer draws to. Set it with VulkanApp::SetRenderSurface before Init. + */ + struct RenderSurfaceDesc + { + /** + * True: draw into images that the renderer owns (--offscreen). There is no window, no + * surface, and no window system: a run works on a machine with no display, and opens + * nothing on a machine that has one. Captures (RequestCapture) still work. + */ + bool Offscreen = false; + + /** The size of the frames (offscreen) or the window. 0: [Engine] WindowWidth and WindowHeight. */ + uint32 Width = 0; + uint32 Height = 0; + }; + + /** The result of one RequestCapture. */ + struct CaptureResult + { + /** The file that was asked for. */ + String Path; + + bool Ok = false; + + /** Why it failed, when Ok is false. */ + String Error; + }; + class Instance; class LogicalDevice; class PhysicalDevice; @@ -100,6 +130,26 @@ namespace Fling /** The present mode of the swap chain. */ PresentMode GetPresentMode() const; + /** What to draw to: a window or offscreen images, and the size. Call it before Init. */ + void SetRenderSurface(const RenderSurfaceDesc& t_Desc) { m_SurfaceDesc = t_Desc; } + + /** True when the renderer draws offscreen (RenderSurfaceDesc::Offscreen): there is no window. */ + bool IsOffscreen() const { return m_SurfaceDesc.Offscreen; } + + /** The size of the frames the renderer draws, in pixels. 0 x 0 before Init. */ + uint32 GetFrameWidth() const; + uint32 GetFrameHeight() const; + + /** + * Save the next frame that Update draws as a PNG file (t_Path, already resolved), + * offscreen or with a window. More than one call before that frame saves the same + * frame to each path. TakeCaptureResults says how each went. + */ + void RequestCapture(StringView t_Path) { m_PendingCaptures.emplace_back(t_Path); } + + /** The results of the captures since the last call, in request order. */ + std::vector TakeCaptureResults() { return std::exchange(m_CaptureResults, {}); } + protected: void Init() override {} void Shutdown() override {} @@ -178,5 +228,17 @@ namespace Fling FirstPersonCamera* m_Camera = nullptr; std::unique_ptr m_State; + + /** @see SetRenderSurface */ + RenderSurfaceDesc m_SurfaceDesc; + + /** @see RequestCapture */ + std::vector m_PendingCaptures; + + /** @see TakeCaptureResults */ + std::vector m_CaptureResults; + + /** Save the frame in the active image to the pending captures (Update, after the frame's fence). */ + void SaveCaptures(); }; } // namespace Fling diff --git a/FlingEngine/Graphics/src/FrameCapture.cpp b/FlingEngine/Graphics/src/FrameCapture.cpp new file mode 100644 index 00000000..00d5632a --- /dev/null +++ b/FlingEngine/Graphics/src/FrameCapture.cpp @@ -0,0 +1,189 @@ +#include "FrameCapture.h" +#include "GraphicsHelpers.h" +#include "LogicalDevice.h" +#include "PhyscialDevice.h" +#include "VulkanApp.h" + +#include +#include +#include +#include + +#define STB_IMAGE_WRITE_IMPLEMENTATION +#define STB_IMAGE_WRITE_STATIC +#include + +namespace Fling +{ + namespace + { + /** stbi_write_png_to_func's callback: append to a stream. */ + void WriteToStream(void* t_Context, void* t_Data, int t_Size) + { + static_cast(t_Context)->write(static_cast(t_Data), t_Size); + } + + bool IsBgra(const VkFormat t_Format) + { + return t_Format == VK_FORMAT_B8G8R8A8_UNORM || t_Format == VK_FORMAT_B8G8R8A8_SRGB; + } + + bool IsRgba(const VkFormat t_Format) + { + return t_Format == VK_FORMAT_R8G8B8A8_UNORM || t_Format == VK_FORMAT_R8G8B8A8_SRGB; + } + } // namespace + + namespace FrameCapture + { + bool WritePng(const StringView t_Path, + const uint32 t_Width, + const uint32 t_Height, + const uint8* t_Rgba, + String& t_OutError) + { + const std::filesystem::path Path = PathFromUtf8(t_Path); + std::error_code Error; + if (Path.has_parent_path()) + { + std::filesystem::create_directories(Path.parent_path(), Error); + } + std::ofstream File(Path, std::ios::binary | std::ios::trunc); + if (!File) + { + t_OutError = "cannot open " + String(t_Path) + " to write"; + return false; + } + const int Stride = static_cast(t_Width) * 4; + if (stbi_write_png_to_func( + &WriteToStream, &File, static_cast(t_Width), static_cast(t_Height), 4, t_Rgba, Stride) == + 0 || + !File) + { + t_OutError = "cannot write the PNG file " + String(t_Path); + return false; + } + return true; + } + + bool SaveImageAsPng(LogicalDevice& t_Device, + const VkImage t_Image, + const VkFormat t_Format, + const VkExtent2D t_Extent, + const VkImageLayout t_Layout, + const std::vector& t_Paths, + String& t_OutError) + { + if (!IsBgra(t_Format) && !IsRgba(t_Format)) + { + t_OutError = + "the frame's format (" + std::to_string(static_cast(t_Format)) + ") is not 8-bit RGBA or BGRA"; + return false; + } + + const VkDevice Device = t_Device.GetVkDevice(); + const VkDeviceSize Size = static_cast(t_Extent.width) * t_Extent.height * 4; + + VkBuffer Staging = VK_NULL_HANDLE; + VkDeviceMemory StagingMemory = VK_NULL_HANDLE; + GraphicsHelpers::CreateBuffer(Device, + VulkanApp::Get().GetPhysicalDevice()->GetVkPhysicalDevice(), + Size, + VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + Staging, + StagingMemory); + + VkCommandBuffer Cmd = GraphicsHelpers::BeginSingleTimeCommands(); + + VkImageSubresourceRange Range = {}; + Range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + Range.levelCount = 1; + Range.layerCount = 1; + + // The frame's color writes, then the copy reads the image + VkImageMemoryBarrier ToCopy = {}; + ToCopy.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + ToCopy.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + ToCopy.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + ToCopy.oldLayout = t_Layout; + ToCopy.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + ToCopy.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + ToCopy.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + ToCopy.image = t_Image; + ToCopy.subresourceRange = Range; + vkCmdPipelineBarrier(Cmd, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, + 0, + nullptr, + 0, + nullptr, + 1, + &ToCopy); + + VkBufferImageCopy Region = {}; + Region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + Region.imageSubresource.layerCount = 1; + Region.imageExtent = {t_Extent.width, t_Extent.height, 1}; + vkCmdCopyImageToBuffer(Cmd, t_Image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, Staging, 1, &Region); + + // Back to the layout it was in (the present waits on it), and the copy's writes to the host + VkImageMemoryBarrier Back = ToCopy; + Back.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + Back.dstAccessMask = 0; + Back.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + Back.newLayout = t_Layout; + + VkBufferMemoryBarrier ToHost = {}; + ToHost.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + ToHost.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + ToHost.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + ToHost.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + ToHost.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + ToHost.buffer = Staging; + ToHost.size = VK_WHOLE_SIZE; + vkCmdPipelineBarrier(Cmd, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, + 0, + nullptr, + 1, + &ToHost, + 1, + &Back); + + // Submits and waits for the queue to be idle + GraphicsHelpers::EndSingleTimeCommands(Cmd); + + void* Mapped = nullptr; + vkMapMemory(Device, StagingMemory, 0, Size, 0, &Mapped); + std::vector Rgba(static_cast(Size)); + std::memcpy(Rgba.data(), Mapped, static_cast(Size)); + vkUnmapMemory(Device, StagingMemory); + vkDestroyBuffer(Device, Staging, nullptr); + vkFreeMemory(Device, StagingMemory, nullptr); + + const bool bSwap = IsBgra(t_Format); + for (size_t i = 0; i < Rgba.size(); i += 4) + { + if (bSwap) + { + std::swap(Rgba[i], Rgba[i + 2]); + } + Rgba[i + 3] = 255; + } + + for (const String& Path : t_Paths) + { + if (!WritePng(Path, t_Extent.width, t_Extent.height, Rgba.data(), t_OutError)) + { + return false; + } + } + return true; + } + } // namespace FrameCapture +} // namespace Fling diff --git a/FlingEngine/Graphics/src/FrameCapture.h b/FlingEngine/Graphics/src/FrameCapture.h new file mode 100644 index 00000000..b0846260 --- /dev/null +++ b/FlingEngine/Graphics/src/FrameCapture.h @@ -0,0 +1,45 @@ +#pragma once + +#include "FlingTypes.h" +#include "FlingVulkan.h" +#include "Strings/String.h" + +#include + +namespace Fling +{ + class LogicalDevice; + + namespace FrameCapture + { + /** + * Copy a color image that the GPU has finished drawing to host memory, and save it as + * a PNG file at each path (--screenshot). The image must have been made with + * VK_IMAGE_USAGE_TRANSFER_SRC_BIT. It is left in t_Layout. Alpha is written as opaque: + * the frame's clear alpha is not meant to be seen. + * + * Waits for the graphics queue to be idle, so call it only for a capture. + * + * @param t_Image The image to copy + * @param t_Format VK_FORMAT_B8G8R8A8_* or VK_FORMAT_R8G8B8A8_* (other formats are refused) + * @param t_Extent The size of the image + * @param t_Layout The layout the image is in now (PRESENT_SRC or TRANSFER_SRC) + * @param t_Paths The files to write, already resolved. Missing folders are made + * @param t_OutError Receives why the capture failed + * @return False if the format is not supported or a file could not be written + */ + bool SaveImageAsPng(LogicalDevice& t_Device, + VkImage t_Image, + VkFormat t_Format, + VkExtent2D t_Extent, + VkImageLayout t_Layout, + const std::vector& t_Paths, + String& t_OutError); + + /** + * Encode RGBA8 pixels (4 bytes a pixel, rows top to bottom) as a PNG file. Missing + * folders are made. Pure CPU work: the tests call it with no GPU. + */ + bool WritePng(StringView t_Path, uint32 t_Width, uint32 t_Height, const uint8* t_Rgba, String& t_OutError); + } // namespace FrameCapture +} // namespace Fling diff --git a/FlingEngine/Graphics/src/GraphicsPipeline.cpp b/FlingEngine/Graphics/src/GraphicsPipeline.cpp index b3941ee8..18a6516c 100644 --- a/FlingEngine/Graphics/src/GraphicsPipeline.cpp +++ b/FlingEngine/Graphics/src/GraphicsPipeline.cpp @@ -118,12 +118,16 @@ namespace Fling { VkVertexInputBindingDescription BindingDescription = Vertex::GetBindingDescription(); std::array AttributeDescriptions = Vertex::GetAttributeDescriptions(); + m_VertexInputStateCreateInfo = {}; m_VertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; - m_VertexInputStateCreateInfo.vertexBindingDescriptionCount = 1; - m_VertexInputStateCreateInfo.pVertexBindingDescriptions = &BindingDescription; - m_VertexInputStateCreateInfo.vertexAttributeDescriptionCount = - static_cast(AttributeDescriptions.size()); - m_VertexInputStateCreateInfo.pVertexAttributeDescriptions = AttributeDescriptions.data(); + if (m_HasVertexInput) + { + m_VertexInputStateCreateInfo.vertexBindingDescriptionCount = 1; + m_VertexInputStateCreateInfo.pVertexBindingDescriptions = &BindingDescription; + m_VertexInputStateCreateInfo.vertexAttributeDescriptionCount = + static_cast(AttributeDescriptions.size()); + m_VertexInputStateCreateInfo.pVertexAttributeDescriptions = AttributeDescriptions.data(); + } // Create graphics pipeline ------------------------ m_PipelineCreateInfo = {}; diff --git a/FlingEngine/Graphics/src/GraphicsPipeline.h b/FlingEngine/Graphics/src/GraphicsPipeline.h index 117139cd..58134301 100644 --- a/FlingEngine/Graphics/src/GraphicsPipeline.h +++ b/FlingEngine/Graphics/src/GraphicsPipeline.h @@ -66,6 +66,14 @@ namespace Fling VkDescriptorSetLayout m_DescriptorSetLayout; VkPipelineVertexInputStateCreateInfo m_VertexInputStateCreateInfo = {}; + + /** + * True (the default): the pipeline reads mesh vertices (Vertex) from binding 0. False: it + * has no vertex input, for a draw that makes its positions from gl_VertexIndex and binds + * no vertex buffer (a full screen triangle). A pipeline that declares input it is never + * given reads unbound memory: software drivers such as llvmpipe crash on it. + */ + bool m_HasVertexInput = true; VkPipelineInputAssemblyStateCreateInfo m_InputAssemblyState = {}; VkPipelineRasterizationStateCreateInfo m_RasterizationState = {}; std::vector m_ColorBlendAttachmentStates; diff --git a/FlingEngine/Graphics/src/Instance.cpp b/FlingEngine/Graphics/src/Instance.cpp index 01c778d7..faf89b56 100644 --- a/FlingEngine/Graphics/src/Instance.cpp +++ b/FlingEngine/Graphics/src/Instance.cpp @@ -12,8 +12,12 @@ namespace Fling { - Instance::Instance() + Instance::Instance(const bool t_WithSurface) : m_WithSurface(t_WithSurface) { + if (m_WithSurface) + { + m_DeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); + } m_EnableValidationLayers = FlingConfig::GetBool("Vulkan", "EnableValidationLayers", false); F_LOG_TRACE("[Renderer] m_EnableValidationLayers is {}", (m_EnableValidationLayers ? "TRUE" : "FALSE")); @@ -121,11 +125,17 @@ namespace Fling std::vector Instance::GetRequiredExtensions() { - uint32 glfwExtensionCount = 0; - const char** glfwExtensions; - glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); - - std::vector extensions(glfwExtensions, glfwExtensions + glfwExtensionCount); + std::vector extensions; + // An offscreen renderer has no window, so it needs no window system extension (and no glfwInit) + if (m_WithSurface) + { + uint32 glfwExtensionCount = 0; + const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); + if (glfwExtensions != nullptr) + { + extensions.assign(glfwExtensions, glfwExtensions + glfwExtensionCount); + } + } if (m_EnableValidationLayers) { diff --git a/FlingEngine/Graphics/src/Instance.h b/FlingEngine/Graphics/src/Instance.h index 84ed28ca..ae425d87 100644 --- a/FlingEngine/Graphics/src/Instance.h +++ b/FlingEngine/Graphics/src/Instance.h @@ -17,7 +17,12 @@ namespace Fling Instance(const Instance&) = delete; Instance& operator=(const Instance&) = delete; - explicit Instance(); + /** + * t_WithSurface: enable the extensions that a window needs (GLFW's instance extensions + * and VK_KHR_swapchain on the device). False for an offscreen renderer, which needs no + * window system at all. + */ + explicit Instance(bool t_WithSurface = true); ~Instance(); @@ -47,6 +52,9 @@ namespace Fling */ uint8 m_EnableValidationLayers : 1; + /** @see Instance() */ + bool m_WithSurface = true; + /** * Create the VkInstance of this object and application information */ @@ -99,7 +107,7 @@ namespace Fling /** The validation layers that we want to look for on this instance */ const std::vector m_ValidationLayers = {"VK_LAYER_LUNARG_standard_validation"}; - /** Device extension support for the swap chain */ - const std::vector m_DeviceExtensions = {VK_KHR_SWAPCHAIN_EXTENSION_NAME}; + /** The device extensions to enable: VK_KHR_swapchain with a surface, none offscreen */ + std::vector m_DeviceExtensions; }; } // namespace Fling \ No newline at end of file diff --git a/FlingEngine/Graphics/src/LogicalDevice.cpp b/FlingEngine/Graphics/src/LogicalDevice.cpp index f11d1d57..172cba99 100644 --- a/FlingEngine/Graphics/src/LogicalDevice.cpp +++ b/FlingEngine/Graphics/src/LogicalDevice.cpp @@ -41,10 +41,18 @@ namespace Fling m_SupportedQueues |= VK_QUEUE_GRAPHICS_BIT; } - // Check for presentation support. - VkBool32 presentSupport; - vkGetPhysicalDeviceSurfaceSupportKHR( - m_PhysicalDevice->GetVkPhysicalDevice(), i, m_Surface, &presentSupport); + // Check for presentation support. With no surface (offscreen) nothing is presented, + // and the "present" queue is the graphics queue + VkBool32 presentSupport = VK_FALSE; + if (m_Surface != VK_NULL_HANDLE) + { + vkGetPhysicalDeviceSurfaceSupportKHR( + m_PhysicalDevice->GetVkPhysicalDevice(), i, m_Surface, &presentSupport); + } + else + { + presentSupport = (QueueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) ? VK_TRUE : VK_FALSE; + } if (QueueFamilies[i].queueCount > 0 && presentSupport) { diff --git a/FlingEngine/Graphics/src/SkyboxSubpass.cpp b/FlingEngine/Graphics/src/SkyboxSubpass.cpp index 2fbc7023..6973aefa 100644 --- a/FlingEngine/Graphics/src/SkyboxSubpass.cpp +++ b/FlingEngine/Graphics/src/SkyboxSubpass.cpp @@ -118,6 +118,9 @@ namespace Fling m_GraphicsPipeline->m_RasterizationState = Initializers::PipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE); + // The vertex shader makes the triangle from gl_VertexIndex: no vertex buffer is bound + m_GraphicsPipeline->m_HasVertexInput = false; + m_GraphicsPipeline->m_DepthStencilState.depthTestEnable = VK_FALSE; m_GraphicsPipeline->m_DepthStencilState.depthWriteEnable = VK_FALSE; diff --git a/FlingEngine/Graphics/src/SwapChain.cpp b/FlingEngine/Graphics/src/SwapChain.cpp index afe4f671..6b1d6a09 100644 --- a/FlingEngine/Graphics/src/SwapChain.cpp +++ b/FlingEngine/Graphics/src/SwapChain.cpp @@ -1,5 +1,6 @@ #include "FlingIntegers.h" #include "FlingWindow.h" +#include "GraphicsHelpers.h" #include "Logger.h" #include "LogicalDevice.h" #include "PhyscialDevice.h" @@ -40,6 +41,24 @@ namespace Fling Recreate(m_Extents); } + Swapchain::Swapchain(const VkExtent2D& t_Extent, + LogicalDevice* t_Dev, + PhysicalDevice* t_PhysDev, + const uint32 t_ImageCount) + : m_VSync(false), + m_Extents{t_Extent}, + m_Device(t_Dev), + m_PhysicalDevice(t_PhysDev), + m_Surface(VK_NULL_HANDLE), + m_Offscreen(true), + m_OffscreenImageCount(t_ImageCount) + { + assert(m_Device && m_PhysicalDevice && m_OffscreenImageCount > 0); + // Nothing is presented, so nothing waits for a display + m_PresentMode = PresentMode::Immediate; + Recreate(m_Extents); + } + Swapchain::~Swapchain() { Cleanup(); @@ -62,7 +81,7 @@ namespace Fling assert(m_Device); VkDevice Device = m_Device->GetVkDevice(); - // Image views + // Image views. Cleared, so a second Cleanup (the destructor after a resize) frees nothing twice for (size_t i = 0; i < m_ImageViews.size(); i++) { if (m_ImageViews[i] != VK_NULL_HANDLE) @@ -70,11 +89,25 @@ namespace Fling vkDestroyImageView(Device, m_ImageViews[i], nullptr); } } + m_ImageViews.clear(); if (m_SwapChain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(Device, m_SwapChain, nullptr); + m_SwapChain = VK_NULL_HANDLE; } + + // Offscreen: this swap chain made the images, so it frees them + if (m_Offscreen) + { + for (size_t i = 0; i < m_Images.size(); ++i) + { + vkDestroyImage(Device, m_Images[i], nullptr); + vkFreeMemory(Device, m_ImageMemory[i], nullptr); + } + m_ImageMemory.clear(); + } + m_Images.clear(); } SwapChainSupportDetails Swapchain::QuerySwapChainSupport() @@ -110,8 +143,49 @@ namespace Fling return Details; } + void Swapchain::CreateOffscreenImages() + { + // The format a surface would most likely give (ChooseSwapChainSurfaceFormat), so the + // pipelines are the same as with a window. RGBA if the device cannot draw to BGRA. + m_ImageFormat = VK_FORMAT_B8G8R8A8_UNORM; + VkFormatProperties Props = {}; + vkGetPhysicalDeviceFormatProperties(m_PhysicalDevice->GetVkPhysicalDevice(), m_ImageFormat, &Props); + if (!(Props.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) + { + m_ImageFormat = VK_FORMAT_R8G8B8A8_UNORM; + } + F_LOG_TRACE("Offscreen swap chain: {} images of {}x{}, format {}", + m_OffscreenImageCount, + m_Extents.width, + m_Extents.height, + static_cast(m_ImageFormat)); + + m_CanCopyImages = true; + m_Images.resize(m_OffscreenImageCount); + m_ImageMemory.resize(m_OffscreenImageCount); + for (uint32 i = 0; i < m_OffscreenImageCount; ++i) + { + GraphicsHelpers::CreateVkImage(m_Device->GetVkDevice(), + m_Extents.width, + m_Extents.height, + m_ImageFormat, + VK_IMAGE_TILING_OPTIMAL, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + m_Images[i], + m_ImageMemory[i]); + } + // AquireNextImage moves to the next image first, so the first frame draws to image 0 + m_ActiveImageIndex = m_OffscreenImageCount - 1; + } + void Swapchain::CreateResources() { + if (m_Offscreen) + { + CreateOffscreenImages(); + return; + } assert(m_Device && m_Surface); SwapChainSupportDetails SwapChainSupport = QuerySwapChainSupport(); @@ -139,6 +213,12 @@ namespace Fling CreateInfo.imageExtent = m_Extents; CreateInfo.imageArrayLayers = 1; CreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + // A capture (--screenshot) copies from the image before it is presented + m_CanCopyImages = (SwapChainSupport.Capabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) != 0; + if (m_CanCopyImages) + { + CreateInfo.imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + } // Specify the handling of multiple queue families uint32 GraphicsFam = m_Device->GetGraphicsFamily(); @@ -228,6 +308,18 @@ namespace Fling { assert(m_Device); + if (m_Offscreen) + { + // Each image in turn. The frame's work waits on the semaphore, so signal it now: + // the image is free, because the last frame's fence was waited on + m_ActiveImageIndex = (m_ActiveImageIndex + 1) % static_cast(m_Images.size()); + VkSubmitInfo Signal = {}; + Signal.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + Signal.signalSemaphoreCount = 1; + Signal.pSignalSemaphores = &t_CompletedSemaphore; + return vkQueueSubmit(m_Device->GetGraphicsQueue(), 1, &Signal, VK_NULL_HANDLE); + } + VkDevice Device = m_Device->GetVkDevice(); VkResult iRes = vkAcquireNextImageKHR(Device, m_SwapChain, @@ -240,6 +332,19 @@ namespace Fling VkResult Swapchain::QueuePresent(const VkQueue& t_PresentQueue, const VkSemaphore& t_WaitSemaphore) { + if (m_Offscreen) + { + // Nothing to show. Wait on the semaphore all the same, so it is unsignaled before + // the frame that uses this image again signals it + const VkPipelineStageFlags WaitStage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + VkSubmitInfo Wait = {}; + Wait.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + Wait.waitSemaphoreCount = 1; + Wait.pWaitSemaphores = &t_WaitSemaphore; + Wait.pWaitDstStageMask = &WaitStage; + return vkQueueSubmit(t_PresentQueue, 1, &Wait, VK_NULL_HANDLE); + } + VkPresentInfoKHR presentInfo = {}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; diff --git a/FlingEngine/Graphics/src/SwapChain.h b/FlingEngine/Graphics/src/SwapChain.h index 09a877b5..e568b7da 100644 --- a/FlingEngine/Graphics/src/SwapChain.h +++ b/FlingEngine/Graphics/src/SwapChain.h @@ -29,6 +29,14 @@ namespace Fling /** t_VSync: SetVSync. */ Swapchain(const VkExtent2D& t_Extent, LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, VkSurfaceKHR t_Surface, bool t_VSync); + /** + * An offscreen swap chain (--offscreen): t_ImageCount images that it makes and owns, with + * no surface. AquireNextImage takes the next image in turn and QueuePresent shows + * nothing; both still signal and wait on the semaphores, so VulkanApp::Update runs the + * same way with or without a window. + */ + Swapchain(const VkExtent2D& t_Extent, LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, uint32 t_ImageCount); + ~Swapchain(); VkResult AquireNextImage(const VkSemaphore& t_CompletedSemaphore); @@ -51,6 +59,21 @@ namespace Fling const VkSwapchainKHR& GetVkSwapChain() const { return m_SwapChain; } + /** True for an offscreen swap chain: no surface, no present. */ + bool IsOffscreen() const { return m_Offscreen; } + + /** + * The layout of an image after the frame's render pass: PRESENT_SRC with a surface, + * TRANSFER_SRC offscreen (nothing presents it; a capture copies from it). + */ + VkImageLayout GetFinalLayout() const + { + return m_Offscreen ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + } + + /** True when the images can be copied from (VK_IMAGE_USAGE_TRANSFER_SRC_BIT), for a capture. */ + bool CanCopyImages() const { return m_CanCopyImages; } + /** The present mode it was made with. */ PresentMode GetPresentMode() const { return m_PresentMode; } @@ -83,6 +106,21 @@ namespace Fling const PhysicalDevice* m_PhysicalDevice; const VkSurfaceKHR m_Surface; + /** @see IsOffscreen */ + const bool m_Offscreen = false; + + /** Offscreen: how many images to make. */ + uint32 m_OffscreenImageCount = 0; + + /** Offscreen: the memory of each image. */ + std::vector m_ImageMemory; + + /** @see CanCopyImages */ + bool m_CanCopyImages = false; + + /** Offscreen CreateResources: make the images and their memory. */ + void CreateOffscreenImages(); + /** The images inside of the swap chain */ std::vector m_Images; std::vector m_ImageViews; diff --git a/FlingEngine/Graphics/src/VulkanApp.cpp b/FlingEngine/Graphics/src/VulkanApp.cpp index 32db0422..08f2e882 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -8,6 +8,7 @@ #include "FlingConfig.h" #include "FlingIntegers.h" #include "FlingWindow.h" +#include "FrameCapture.h" #include "GeometrySubpass.h" #include "GitVersion.h" #include "GraphicsHelpers.h" @@ -140,25 +141,62 @@ namespace Fling void VulkanApp::Prepare() { - CreateGameWindow(FlingConfig::GetInt("Engine", "WindowWidth", FLING_DEFAULT_WINDOW_WIDTH), - FlingConfig::GetInt("Engine", "WindowHeight", FLING_DEFAULT_WINDOW_WIDTH)); + // --resolution, else the config + const uint32 Width = m_SurfaceDesc.Width > 0 + ? m_SurfaceDesc.Width + : FlingConfig::GetInt("Engine", "WindowWidth", FLING_DEFAULT_WINDOW_WIDTH); + const uint32 Height = m_SurfaceDesc.Height > 0 + ? m_SurfaceDesc.Height + : FlingConfig::GetInt("Engine", "WindowHeight", FLING_DEFAULT_WINDOW_HEIGHT); + const bool bOffscreen = m_SurfaceDesc.Offscreen; - m_Instance = new Instance(); + // Offscreen: no window, no glfwInit, and no window system extension + if (!bOffscreen) + { + CreateGameWindow(Width, Height); + } + + m_Instance = new Instance(/* t_WithSurface */ !bOffscreen); assert(m_Instance); - m_CurrentWindow->CreateSurface(m_Instance->GetRawVkInstance(), &m_State->m_Surface); + if (!bOffscreen) + { + if (const char* Missing = VulkanLoader::MissingSurfaceCommand()) + { + F_LOG_ERROR("The Vulkan driver has no {}: a window cannot be shown", Missing); + F_LOG_FATAL("The Vulkan driver cannot show a window (no VK_KHR_surface). Try --offscreen"); + } + m_CurrentWindow->CreateSurface(m_Instance->GetRawVkInstance(), &m_State->m_Surface); + } m_PhysicalDevice = new PhysicalDevice(m_Instance->GetBestPhysicalDevice()); assert(m_PhysicalDevice); + F_LOG_TRACE("Render device: {} ({})", GetPhysicalDeviceName(), bOffscreen ? "offscreen" : "window"); m_LogicalDevice = new LogicalDevice(m_Instance, m_PhysicalDevice, m_State->m_Surface); assert(m_LogicalDevice); + if (!bOffscreen) + { + if (const char* Missing = VulkanLoader::MissingSwapchainCommand()) + { + F_LOG_ERROR("The Vulkan driver has no {}: a window cannot be shown", Missing); + F_LOG_FATAL("The Vulkan driver cannot show a window (no VK_KHR_swapchain). Try --offscreen"); + } + } - m_SwapChain = new Swapchain(ChooseSwapExtent(m_CurrentWindow, m_PhysicalDevice, m_State->m_Surface), - m_LogicalDevice, - m_PhysicalDevice, - m_State->m_Surface, - m_VSync); + if (bOffscreen) + { + const VkExtent2D Extent = {std::max(Width, 1), std::max(Height, 1)}; + m_SwapChain = new Swapchain(Extent, m_LogicalDevice, m_PhysicalDevice, VkConfig::MAX_FRAMES_IN_FLIGHT); + } + else + { + m_SwapChain = new Swapchain(ChooseSwapExtent(m_CurrentWindow, m_PhysicalDevice, m_State->m_Surface), + m_LogicalDevice, + m_PhysicalDevice, + m_State->m_Surface, + m_VSync); + } assert(m_SwapChain); GraphicsHelpers::CreateCommandPool(&m_State->m_CommandPool, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT); @@ -168,7 +206,10 @@ namespace Fling // Create the camera float CamMoveSpeed = FlingConfig::GetFloat("Camera", "MoveSpeed", 10.0f); float CamRotSpeed = FlingConfig::GetFloat("Camera", "RotationSpeed", 40.0f); - m_Camera = new FirstPersonCamera(m_CurrentWindow->GetAspectRatio(), CamMoveSpeed, CamRotSpeed); + const float Aspect = m_CurrentWindow ? m_CurrentWindow->GetAspectRatio() + : static_cast(m_SwapChain->GetExtents().width) / + static_cast(m_SwapChain->GetExtents().height); + m_Camera = new FirstPersonCamera(Aspect, CamMoveSpeed, CamRotSpeed); BuildSwapChainResources(); } @@ -228,7 +269,8 @@ namespace Fling colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + // PRESENT_SRC for a window; offscreen, TRANSFER_SRC (a capture copies from it) + colorAttachment.finalLayout = m_SwapChain->GetFinalLayout(); VkAttachmentDescription depthAttachment = {}; depthAttachment.format = DepthBuffer::GetDepthBufferFormat(); @@ -388,8 +430,52 @@ namespace Fling return m_SwapChain ? m_SwapChain->GetPresentMode() : PresentMode::Fifo; } + uint32 VulkanApp::GetFrameWidth() const + { + return m_SwapChain ? m_SwapChain->GetExtents().width : 0; + } + + uint32 VulkanApp::GetFrameHeight() const + { + return m_SwapChain ? m_SwapChain->GetExtents().height : 0; + } + + void VulkanApp::SaveCaptures() + { + if (m_PendingCaptures.empty()) + { + return; + } + std::vector Paths = std::exchange(m_PendingCaptures, {}); + String Error; + bool bOk = false; + if (!m_SwapChain->CanCopyImages()) + { + Error = "the swap chain images cannot be copied (no VK_IMAGE_USAGE_TRANSFER_SRC_BIT); use --offscreen"; + } + else + { + bOk = FrameCapture::SaveImageAsPng(*m_LogicalDevice, + m_SwapChain->GetActiveImage(), + m_SwapChain->GetImageFormat(), + m_SwapChain->GetExtents(), + m_SwapChain->GetFinalLayout(), + Paths, + Error); + } + for (String& Path : Paths) + { + m_CaptureResults.push_back(CaptureResult{std::move(Path), bOk, bOk ? String() : Error}); + } + } + void VulkanApp::RecreateSwapchain() { + // Offscreen images never go out of date: there is no window to resize + if (m_CurrentWindow == nullptr) + { + return; + } F_LOG_TRACE("Making the swap chain again"); if (!m_CurrentWindow->WaitForNewWindowSize()) { @@ -509,7 +595,12 @@ namespace Fling ); }*/ - if (t_Conf & PipelineFlags::IMGUI) + if ((t_Conf & PipelineFlags::IMGUI) && m_CurrentWindow == nullptr) + { + // ImGui reads its input from the window + F_LOG_WARN("IMGUI render pipeline needs a window: there is none offscreen, so it is left out"); + } + else if (t_Conf & PipelineFlags::IMGUI) { #if WITH_IMGUI F_LOG_TRACE("Bulid IMGUI render pipeline! "); @@ -540,9 +631,17 @@ namespace Fling const RenderSnapshot& Snapshot = SnapshotPtr ? *SnapshotPtr : s_EmptySnapshot; // Prepare the frame for submission by waiting for the swap chain - m_CurrentWindow->Update(); - m_Camera->SetViewportSize(static_cast(m_CurrentWindow->GetFramebufferWidth()), - static_cast(m_CurrentWindow->GetFramebufferHeight())); + if (m_CurrentWindow) + { + m_CurrentWindow->Update(); + m_Camera->SetViewportSize(static_cast(m_CurrentWindow->GetFramebufferWidth()), + static_cast(m_CurrentWindow->GetFramebufferHeight())); + } + else + { + m_Camera->SetViewportSize(static_cast(m_SwapChain->GetExtents().width), + static_cast(m_SwapChain->GetExtents().height)); + } m_Camera->Update(DeltaTime); // A game's view (CameraView, written by its frame system) turns the camera. The debug camera still moves it. const CameraView* View = t_Reg.TryGetSingleton(); @@ -708,6 +807,9 @@ namespace Fling VK_TRUE, std::numeric_limits::max()); + // The frame is drawn: copy it out before it is presented (--screenshot) + SaveCaptures(); + // Present the swap chain with the renderer finished semaphore iResult = m_SwapChain->QueuePresent(m_LogicalDevice->GetPresentQueue(), m_State->m_RenderFinishedSemaphores[ImageIndex]); @@ -794,7 +896,12 @@ namespace Fling delete m_LogicalDevice; m_LogicalDevice = nullptr; - vkDestroySurfaceKHR(m_Instance->GetRawVkInstance(), m_State->m_Surface, nullptr); + // Offscreen there is no surface + if (m_State->m_Surface != VK_NULL_HANDLE) + { + vkDestroySurfaceKHR(m_Instance->GetRawVkInstance(), m_State->m_Surface, nullptr); + m_State->m_Surface = VK_NULL_HANDLE; + } delete m_PhysicalDevice; m_PhysicalDevice = nullptr; diff --git a/FlingEngine/Graphics/src/VulkanFunctions.inl b/FlingEngine/Graphics/src/VulkanFunctions.inl index 7c779c75..05818299 100644 --- a/FlingEngine/Graphics/src/VulkanFunctions.inl +++ b/FlingEngine/Graphics/src/VulkanFunctions.inl @@ -51,7 +51,6 @@ FLING_VK_GLOBAL_OPTIONAL(vkEnumerateInstanceVersion) FLING_VK_INSTANCE(vkCreateDevice) FLING_VK_INSTANCE(vkDestroyInstance) -FLING_VK_INSTANCE(vkDestroySurfaceKHR) FLING_VK_INSTANCE(vkEnumerateDeviceExtensionProperties) FLING_VK_INSTANCE(vkEnumeratePhysicalDevices) FLING_VK_INSTANCE(vkGetDeviceProcAddr) @@ -60,15 +59,18 @@ FLING_VK_INSTANCE(vkGetPhysicalDeviceFormatProperties) FLING_VK_INSTANCE(vkGetPhysicalDeviceMemoryProperties) FLING_VK_INSTANCE(vkGetPhysicalDeviceProperties) FLING_VK_INSTANCE(vkGetPhysicalDeviceQueueFamilyProperties) -FLING_VK_INSTANCE(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) -FLING_VK_INSTANCE(vkGetPhysicalDeviceSurfaceFormatsKHR) -FLING_VK_INSTANCE(vkGetPhysicalDeviceSurfacePresentModesKHR) -FLING_VK_INSTANCE(vkGetPhysicalDeviceSurfaceSupportKHR) FLING_VK_INSTANCE_OPTIONAL(vkCreateDebugUtilsMessengerEXT) FLING_VK_INSTANCE_OPTIONAL(vkDestroyDebugUtilsMessengerEXT) -FLING_VK_DEVICE(vkAcquireNextImageKHR) +// VK_KHR_surface: an offscreen renderer (--offscreen) does not enable it. +// VulkanLoader::MissingPresentCommand checks them when there is a window. +FLING_VK_INSTANCE_OPTIONAL(vkDestroySurfaceKHR) +FLING_VK_INSTANCE_OPTIONAL(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) +FLING_VK_INSTANCE_OPTIONAL(vkGetPhysicalDeviceSurfaceFormatsKHR) +FLING_VK_INSTANCE_OPTIONAL(vkGetPhysicalDeviceSurfacePresentModesKHR) +FLING_VK_INSTANCE_OPTIONAL(vkGetPhysicalDeviceSurfaceSupportKHR) + FLING_VK_DEVICE(vkAllocateCommandBuffers) FLING_VK_DEVICE(vkAllocateDescriptorSets) FLING_VK_DEVICE(vkAllocateMemory) @@ -83,6 +85,7 @@ FLING_VK_DEVICE(vkCmdBindVertexBuffers) FLING_VK_DEVICE(vkCmdBlitImage) FLING_VK_DEVICE(vkCmdCopyBuffer) FLING_VK_DEVICE(vkCmdCopyBufferToImage) +FLING_VK_DEVICE(vkCmdCopyImageToBuffer) FLING_VK_DEVICE(vkCmdDraw) FLING_VK_DEVICE(vkCmdDrawIndexed) FLING_VK_DEVICE(vkCmdEndRenderPass) @@ -106,7 +109,6 @@ FLING_VK_DEVICE(vkCreateRenderPass) FLING_VK_DEVICE(vkCreateSampler) FLING_VK_DEVICE(vkCreateSemaphore) FLING_VK_DEVICE(vkCreateShaderModule) -FLING_VK_DEVICE(vkCreateSwapchainKHR) FLING_VK_DEVICE(vkDestroyBuffer) FLING_VK_DEVICE(vkDestroyCommandPool) FLING_VK_DEVICE(vkDestroyDescriptorPool) @@ -123,7 +125,6 @@ FLING_VK_DEVICE(vkDestroyRenderPass) FLING_VK_DEVICE(vkDestroySampler) FLING_VK_DEVICE(vkDestroySemaphore) FLING_VK_DEVICE(vkDestroyShaderModule) -FLING_VK_DEVICE(vkDestroySwapchainKHR) FLING_VK_DEVICE(vkDeviceWaitIdle) FLING_VK_DEVICE(vkEndCommandBuffer) FLING_VK_DEVICE(vkFlushMappedMemoryRanges) @@ -133,9 +134,7 @@ FLING_VK_DEVICE(vkFreeMemory) FLING_VK_DEVICE(vkGetBufferMemoryRequirements) FLING_VK_DEVICE(vkGetDeviceQueue) FLING_VK_DEVICE(vkGetImageMemoryRequirements) -FLING_VK_DEVICE(vkGetSwapchainImagesKHR) FLING_VK_DEVICE(vkMapMemory) -FLING_VK_DEVICE(vkQueuePresentKHR) FLING_VK_DEVICE(vkQueueSubmit) FLING_VK_DEVICE(vkQueueWaitIdle) FLING_VK_DEVICE(vkResetFences) @@ -143,6 +142,14 @@ FLING_VK_DEVICE(vkUnmapMemory) FLING_VK_DEVICE(vkUpdateDescriptorSets) FLING_VK_DEVICE(vkWaitForFences) +// VK_KHR_swapchain: an offscreen renderer (--offscreen) does not enable it. +// VulkanLoader::MissingPresentCommand checks them when there is a window. +FLING_VK_DEVICE_OPTIONAL(vkAcquireNextImageKHR) +FLING_VK_DEVICE_OPTIONAL(vkCreateSwapchainKHR) +FLING_VK_DEVICE_OPTIONAL(vkDestroySwapchainKHR) +FLING_VK_DEVICE_OPTIONAL(vkGetSwapchainImagesKHR) +FLING_VK_DEVICE_OPTIONAL(vkQueuePresentKHR) + #ifdef FLING_VK_CLEAR_GLOBAL #undef FLING_VK_GLOBAL #undef FLING_VK_CLEAR_GLOBAL diff --git a/FlingEngine/Graphics/src/VulkanLoader.cpp b/FlingEngine/Graphics/src/VulkanLoader.cpp index 42a72007..37de93f4 100644 --- a/FlingEngine/Graphics/src/VulkanLoader.cpp +++ b/FlingEngine/Graphics/src/VulkanLoader.cpp @@ -4,7 +4,9 @@ #include "Strings/String.h" #include "VulkanLoader.h" +#include #include +#include extern "C" { @@ -169,6 +171,48 @@ namespace Fling #undef FLING_VK_DEVICE } + namespace + { + /** The name of the first null command, or null. */ + const char* FirstMissing(std::initializer_list> t_Commands) + { + for (const auto& [Name, Command] : t_Commands) + { + if (Command == nullptr) + { + return Name; + } + } + return nullptr; + } + } // namespace + + const char* VulkanLoader::MissingSurfaceCommand() + { + return FirstMissing({ + {"vkDestroySurfaceKHR", reinterpret_cast(vkDestroySurfaceKHR)}, + {"vkGetPhysicalDeviceSurfaceCapabilitiesKHR", + reinterpret_cast(vkGetPhysicalDeviceSurfaceCapabilitiesKHR)}, + {"vkGetPhysicalDeviceSurfaceFormatsKHR", + reinterpret_cast(vkGetPhysicalDeviceSurfaceFormatsKHR)}, + {"vkGetPhysicalDeviceSurfacePresentModesKHR", + reinterpret_cast(vkGetPhysicalDeviceSurfacePresentModesKHR)}, + {"vkGetPhysicalDeviceSurfaceSupportKHR", + reinterpret_cast(vkGetPhysicalDeviceSurfaceSupportKHR)}, + }); + } + + const char* VulkanLoader::MissingSwapchainCommand() + { + return FirstMissing({ + {"vkAcquireNextImageKHR", reinterpret_cast(vkAcquireNextImageKHR)}, + {"vkCreateSwapchainKHR", reinterpret_cast(vkCreateSwapchainKHR)}, + {"vkDestroySwapchainKHR", reinterpret_cast(vkDestroySwapchainKHR)}, + {"vkGetSwapchainImagesKHR", reinterpret_cast(vkGetSwapchainImagesKHR)}, + {"vkQueuePresentKHR", reinterpret_cast(vkQueuePresentKHR)}, + }); + } + void VulkanLoader::UnloadLoader() { #define FLING_VK_GLOBAL(name) ClearProc(name); diff --git a/FlingEngine/Graphics/src/VulkanLoader.h b/FlingEngine/Graphics/src/VulkanLoader.h index 2f2ef2d7..b04e0a51 100644 --- a/FlingEngine/Graphics/src/VulkanLoader.h +++ b/FlingEngine/Graphics/src/VulkanLoader.h @@ -34,5 +34,15 @@ namespace Fling * Call this after vkDestroyInstance. */ static void UnloadLoader(); + + /** + * The name of the first surface command (VK_KHR_surface, loaded with the instance) that + * did not load, or null when all did. A renderer with a window needs them; an offscreen + * one does not. + */ + static const char* MissingSurfaceCommand(); + + /** The same for the swap chain commands (VK_KHR_swapchain, loaded with the device). */ + static const char* MissingSwapchainCommand(); }; } // namespace Fling diff --git a/FlingTests/Core/LaunchOptionsTests.cpp b/FlingTests/Core/LaunchOptionsTests.cpp index 26a935fe..534f769b 100644 --- a/FlingTests/Core/LaunchOptionsTests.cpp +++ b/FlingTests/Core/LaunchOptionsTests.cpp @@ -263,3 +263,113 @@ TEST_CASE("Launch Options", "[Launch Options]") REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--present-mode is not a flag: --vsync on|off")); } } + +TEST_CASE("Launch Options: offscreen rendering and captures", "[Launch Options]") +{ + using namespace Fling; + + LaunchOptions Options; + String Error; + + SECTION("Defaults: a window, no captures") + { + REQUIRE(ParseLaunchArgs({}, Options, Error)); + REQUIRE_FALSE(Options.Offscreen); + REQUIRE_FALSE(Options.IsHeadless()); + REQUIRE(Options.ResolutionWidth == 0); + REQUIRE(Options.Screenshot.empty()); + REQUIRE(Options.DumpState.empty()); + } + + SECTION("--offscreen is headless, and renders") + { + REQUIRE(ParseLaunchArgs({"--offscreen", "--resolution", "1280x720"}, Options, Error)); + REQUIRE(Options.Offscreen); + REQUIRE_FALSE(Options.NullRender); + REQUIRE(Options.IsHeadless()); + REQUIRE(Options.ResolutionWidth == 1280); + REQUIRE(Options.ResolutionHeight == 720); + + REQUIRE(ParseLaunchArgs({"--null-render"}, Options, Error)); + REQUIRE(Options.IsHeadless()); + + REQUIRE_FALSE(ParseLaunchArgs({"--offscreen", "--null-render"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("cannot be used together")); + } + + SECTION("--resolution must be x") + { + for (const char* Bad : {"1280", "1280x", "x720", "0x720", "1280x0", "99999x10", "wide"}) + { + REQUIRE_FALSE(ParseLaunchArgs({"--resolution", Bad}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--resolution")); + } + } + + SECTION("Captures at a tick list, sorted, with no repeats") + { + REQUIRE(ParseLaunchArgs({"--offscreen", + "--screenshot", + "shot.png", + "--screenshot-ticks", + "60,30,60", + "--dump-state", + "state.json", + "--dump-state-ticks", + "5"}, + Options, + Error)); + REQUIRE(Options.Screenshot == "shot.png"); + REQUIRE(Options.ScreenshotTicks == std::vector{30, 60}); + REQUIRE(Options.DumpState == "state.json"); + REQUIRE(Options.DumpStateTicks == std::vector{5}); + + for (const char* Bad : {"0", "1,,2", "a", "3,"}) + { + REQUIRE_FALSE(ParseLaunchArgs({"--dump-state", "s.json", "--dump-state-ticks", Bad}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--dump-state-ticks")); + } + } + + SECTION("A capture with no tick list is at the last tick, so it needs --frames") + { + REQUIRE(ParseLaunchArgs({"--null-render", "--frames", "30", "--dump-state", "s.json"}, Options, Error)); + REQUIRE(Options.DumpStateTicks.empty()); + + REQUIRE_FALSE(ParseLaunchArgs({"--null-render", "--dump-state", "s.json"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--dump-state needs --frames")); + REQUIRE_FALSE(ParseLaunchArgs({"--offscreen", "--screenshot", "s.png"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--screenshot needs --frames")); + } + + SECTION("Misused capture flags are errors") + { + REQUIRE_FALSE(ParseLaunchArgs({"--screenshot-ticks", "3"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("needs --screenshot")); + REQUIRE_FALSE(ParseLaunchArgs({"--dump-state-ticks", "3"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("needs --dump-state")); + + // There is no frame to save without a renderer; the state dump is the text view + REQUIRE_FALSE(ParseLaunchArgs({"--null-render", "--frames", "5", "--screenshot", "s.png"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--offscreen")); + REQUIRE_FALSE(ParseLaunchArgs({"--screenshot"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("needs a file path")); + } +} + +TEST_CASE("Capture file names", "[Launch Options]") +{ + using Fling::CaptureFilePath; + + // One tick: the path as it is + REQUIRE(CaptureFilePath("Saved/shot.png", 30, false) == "Saved/shot.png"); + // More than one: the tick before the extension + REQUIRE(CaptureFilePath("Saved/shot.png", 30, true) == "Saved/shot_tick30.png"); + REQUIRE(CaptureFilePath("state", 7, true) == "state_tick7"); + // A dot in a folder name is not an extension + REQUIRE(CaptureFilePath("out.d/state", 7, true) == "out.d/state_tick7"); + REQUIRE(CaptureFilePath("out.d\\state", 7, true) == "out.d\\state_tick7"); + // {tick} puts the tick where the caller wants it, with one tick or many + REQUIRE(CaptureFilePath("frames/{tick}.png", 120, false) == "frames/120.png"); + REQUIRE(CaptureFilePath("frames/f{tick}.png", 5, true) == "frames/f5.png"); +} diff --git a/FlingTests/Core/RunSettingsTests.cpp b/FlingTests/Core/RunSettingsTests.cpp index 9f98cdf6..ee2f5faa 100644 --- a/FlingTests/Core/RunSettingsTests.cpp +++ b/FlingTests/Core/RunSettingsTests.cpp @@ -83,6 +83,14 @@ TEST_CASE("Run settings: the frame cap is the monitor's refresh rate, else 60", Settings.ResolveFrameCap(std::nullopt); REQUIRE(Settings.MaxFps == 30); REQUIRE(Settings.MaxFpsSource == SettingSource::CommandLine); + + // --offscreen renders, but it is headless too: no monitor, no cap + REQUIRE(Resolve({"--offscreen"}, {}, Settings, Error)); + REQUIRE(Settings.Headless); + Settings.ResolveFrameCap(144u); + REQUIRE(Settings.MaxFps == 0); + REQUIRE_THAT(Settings.Describe(), + Catch::Matchers::ContainsSubstring("frame cap none (default for --offscreen)")); } SECTION("A set cap wins over the monitor; 0 is no cap") { diff --git a/FlingTests/Engine/WorldStateDumpTests.cpp b/FlingTests/Engine/WorldStateDumpTests.cpp new file mode 100644 index 00000000..3d302dfd --- /dev/null +++ b/FlingTests/Engine/WorldStateDumpTests.cpp @@ -0,0 +1,190 @@ +#include "Components/Name.hpp" +#include "Components/Transform.h" +#include "Ecs/ModuleRegistration.h" +#include "Ecs/RegisterEngine.h" +#include "Ecs/SystemBase.h" +#include "Game.h" +#include "Json.h" +#include "Logger.h" +#include "Strings/String.h" +#include "World.h" + +#include +#include +#include + +using Fling::String; + +namespace +{ + constexpr uint32 TestSimHz = 60; + + /** A frame a little longer than one fixed step (1/60 s): each Update runs one tick */ + constexpr float OneTickFrame = 0.017f; + + /** + * Simulation state that a level does not save (Transient) but a rollback restores: the + * state dump must show it, as the state hash covers it. + */ + struct DumpCounter + { + static constexpr Fling::ComponentInfo Component{.Name = "Test.DumpCounter", + .Kind = Fling::ComponentKind::Singleton, + .Transient = true, + .Rollback = Fling::RollbackClass::Restore}; + int Ticks = 0; + }; + + /** A setting that is neither saved nor rolled back: the state dump leaves it out. */ + struct DumpScratch + { + static constexpr Fling::ComponentInfo Component{.Name = "Test.DumpScratch", + .Kind = Fling::ComponentKind::Singleton, + .Transient = true, + .Rollback = Fling::RollbackClass::Keep}; + int Value = 7; + }; + + /** Counts the ticks and moves every transform one unit along x each tick. */ + class DumpTickSystem final + : public Fling::System, Fling::Write>> + { + public: + static constexpr Fling::SystemInfo Info{.Name = "Test.DumpTicks", .In = Fling::Order::Input}; + + void OnCreate(Setup& setup) const { setup.AddSingleton(); } + + void OnDestroy(Setup& setup) const { setup.RemoveSingleton(); } + + void FixedUpdate(Context& ctx) const + { + ++ctx.Singleton().Ticks; + for (auto [Entity, Trans] : ctx.Query()) + { + Trans.Position.x += 1.0f; + } + } + }; + + class DumpTestGame : public Fling::Game + { + public: + void Init(Fling::EntityStorage&) override {} + void OnStartGame(Fling::EntityStorage&) override {} + void OnStopGame(Fling::EntityStorage&) override {} + void Shutdown(Fling::EntityStorage&) override {} + + void Register(Fling::ModuleRegistration& t_Modules) override + { + Fling::RegisterEngine(t_Modules); + t_Modules.Component([](Fling::TypeBuilder& t_Type) + { t_Type.Field("ticks", &DumpCounter::Ticks); }); + t_Modules.Component([](Fling::TypeBuilder& t_Type) + { t_Type.Field("value", &DumpScratch::Value); }); + t_Modules.System(); + } + }; + + void InitTestLogger() + { + Fling::Logger::Get().Init(); + Fling::Logger::GetCurrentConsole()->set_level(spdlog::level::off); + Fling::Logger::GetCurrentLogFile()->set_level(spdlog::level::off); + } + + /** Make a world with two named entities, start play, and run t_Ticks ticks. */ + std::vector RunAndDump(const std::vector& t_DumpTicks, const int t_Ticks) + { + using namespace Fling; + World TestWorld(std::make_shared()); + TestWorld.SetExecMode(ExecMode::Direct); + TestWorld.SetSystemRunnerConfig(SystemRunnerConfig{.SimHz = TestSimHz}); + TestWorld.SetStateHashEnabled(true); + TestWorld.SetStateDumpTicks(t_DumpTicks); + TestWorld.Init(); + + EntityStorage& Reg = TestWorld.GetStorage(); + for (const char* EntityName : {"Ball", "Wall"}) + { + const Entity Each = Reg.Create(); + Reg.Add(Each).Name = Name(EntityName); + Reg.Add(Each); + } + Reg.SetSingleton(); + + TestWorld.RequestGameStart(); + std::vector Dumps; + for (int i = 0; i < t_Ticks; ++i) + { + TestWorld.Update(OneTickFrame); + for (World::StateDump& Dump : TestWorld.TakeStateDumps()) + { + Dumps.push_back(std::move(Dump)); + } + } + TestWorld.Shutdown(); + return Dumps; + } +} // namespace + +TEST_CASE("World state dump at chosen ticks", "[world][state-dump]") +{ + using namespace Fling; + InitTestLogger(); + + const std::vector Dumps = RunAndDump({2, 4}, 5); + REQUIRE(Dumps.size() == 2); + REQUIRE(Dumps[0].Tick == 2); + REQUIRE(Dumps[1].Tick == 4); + + const Json& Doc = Dumps[1].Doc; + REQUIRE(Doc.GetUInt64("tick") == 4); + REQUIRE(Doc.GetUInt64("simHz") == TestSimHz); + REQUIRE(Doc.GetUInt64("entityCount") == 2); + // On: the hash of the tick, as 16 hex digits + REQUIRE(Doc.GetString("stateHash").size() == 16); + REQUIRE(Doc.GetString("stateHash") != "0000000000000000"); + + SECTION("Entities have their name, handle, id and components with every field") + { + const Json Entities = Doc.Get("entities"); + REQUIRE(Entities.IsArray()); + REQUIRE(Entities.Size() == 2); + std::vector Names; + for (std::size_t i = 0; i < Entities.Size(); ++i) + { + const Json Entity = Entities.At(i); + Names.push_back(Entity.GetString("name")); + REQUIRE_FALSE(Entity.GetString("entity").empty()); + REQUIRE(Entity.GetUInt64("guid") != 0); + // Four ticks moved it four units along x + REQUIRE(Entity.Get("Transform").GetVec3("position").x == Catch::Approx(4.0f)); + } + // In handle order, which is the order they were made in + REQUIRE(Names == std::vector{"Ball", "Wall"}); + } + + SECTION("Singletons: rollback state is in (even Transient), Keep state is out") + { + const Json Singletons = Doc.Get("singletons"); + REQUIRE(Singletons.Contains("Test.DumpCounter")); + REQUIRE(Singletons.Get("Test.DumpCounter").GetInt("ticks") == 4); + REQUIRE_FALSE(Singletons.Contains("Test.DumpScratch")); + } + + SECTION("The same run writes the same document") + { + const std::vector Again = RunAndDump({2, 4}, 5); + REQUIRE(Again.size() == 2); + REQUIRE(Again[1].Doc.Dump(2) == Doc.Dump(2)); + // A different tick has a different state, so a different document + REQUIRE(Dumps[0].Doc.Dump(2) != Doc.Dump(2)); + } +} + +TEST_CASE("World state dump: a tick that does not run makes no dump", "[world][state-dump]") +{ + InitTestLogger(); + REQUIRE(RunAndDump({50}, 3).empty()); + REQUIRE(RunAndDump({}, 3).empty()); +} diff --git a/Plans/improve-ai-iteration.md b/Plans/improve-ai-iteration.md index 831eae92..61154156 100644 --- a/Plans/improve-ai-iteration.md +++ b/Plans/improve-ai-iteration.md @@ -268,10 +268,21 @@ Done. The rules that it establishes are in `improve-time.md`. The tick clocks (`FixedTickClock`) come with T1 and T2. - JSON logs go to the existing `Logs/` folder (`fling_log.jsonl`), not to `Saved/Logs/`. Move them when `project-model.md` adds `Saved/`. -- `--dump-state` is not done. It needs the state hash from phase C. +- `--dump-state ` (with `--dump-state-ticks`) is done: the state at chosen + ticks as JSON, written on the game thread after the tick, with the tick's state + hash. See [`Skills/testing.md`](../Skills/testing.md#seeing-the-game-without-a-window). - CTest runs the Sandbox headless and runs `CrashProbe` to check that each kind of crash exits with code 2, with a stack trace and no dialog. +### Phase F status + +Offscreen capture is done, before phases C to E: `--offscreen` renders into images +that the renderer owns (no window, no surface, no GLFW), with the headless timing of +`--null-render`, and `--screenshot` saves PNG files at chosen ticks, offscreen or +windowed. See [`Skills/testing.md`](../Skills/testing.md#seeing-the-game-without-a-window). +The `screenshot` command of the command layer (section 5) can call the same +`VulkanApp::RequestCapture`. The MCP wrapper and hot reload are not done. + ## Open questions - Where does `TickInput` live: Core (with `Input`) or Engine (with diff --git a/Sandbox/CMakeLists.txt b/Sandbox/CMakeLists.txt index 3cfbe9cc..a6450d1c 100644 --- a/Sandbox/CMakeLists.txt +++ b/Sandbox/CMakeLists.txt @@ -333,6 +333,50 @@ if( FLING_BUILD_TESTS ) PASS_REGULAR_EXPRESSION "Run settings: tick rate 30 Hz \\(default\\), exec threaded \\(default\\), frame cap none \\(default for --null-render\\), vsync on \\(default\\), interpolation on \\(default\\).*Fling exit: code=0 ticks=10" ) + # --dump-state: the simulation state as JSON at chosen ticks, with no window and no GPU. + # The same bytes in --exec direct and threaded (Sandbox/Tests/CheckCaptures.cmake). + add_test( NAME "Sandbox: headless state dump" + COMMAND ${CMAKE_COMMAND} + -DSANDBOX=$ + -DROOT=${FLING_ROOT_DIR} + -DOUT=${CMAKE_BINARY_DIR}/TestOutput/StateDump + -DKIND=state + -P "${FLING_ROOT_DIR}/Sandbox/Tests/CheckCaptures.cmake" + ) + set_tests_properties( "Sandbox: headless state dump" PROPERTIES + PASS_REGULAR_EXPRESSION "Captures are the same in --exec direct and threaded" + TIMEOUT 120 + ) + + # A capture that was asked for and not made fails the run, so a script never reads an old file + add_test( NAME "Sandbox: state dump of a tick that does not run" + COMMAND ${PROJECT_NAME} --null-render --unattended --frames 10 --seed 1 + --dump-state ${CMAKE_BINARY_DIR}/TestOutput/NoState.json --dump-state-ticks 99 + WORKING_DIRECTORY "${FLING_ROOT_DIR}" + ) + set_tests_properties( "Sandbox: state dump of a tick that does not run" PROPERTIES + PASS_REGULAR_EXPRESSION "--dump-state: tick 99 did not run.*Fling exit: code=1" + ) + + # --offscreen --screenshot renders with the GPU into images and saves PNG files, with no + # window. It needs a Vulkan driver (llvmpipe is enough, no display), which CI machines may + # not have, so it is off unless FLING_TEST_OFFSCREEN is on. + option( FLING_TEST_OFFSCREEN "Add the CTest that renders offscreen (needs a Vulkan driver, no display)" OFF ) + if( FLING_TEST_OFFSCREEN ) + add_test( NAME "Sandbox: offscreen screenshots" + COMMAND ${CMAKE_COMMAND} + -DSANDBOX=$ + -DROOT=${FLING_ROOT_DIR} + -DOUT=${CMAKE_BINARY_DIR}/TestOutput/Screenshots + -DKIND=screenshot + -P "${FLING_ROOT_DIR}/Sandbox/Tests/CheckCaptures.cmake" + ) + set_tests_properties( "Sandbox: offscreen screenshots" PROPERTIES + PASS_REGULAR_EXPRESSION "Captures are the same in --exec direct and threaded" + TIMEOUT 300 + ) + endif() + # The linked binary must not import libvulkan / vulkan-1.dll. The loader is # opened at runtime by Fling::DynamicLibrary. add_test(NAME "Sandbox: no Vulkan import" diff --git a/Sandbox/Tests/CheckCaptures.cmake b/Sandbox/Tests/CheckCaptures.cmake new file mode 100644 index 00000000..33c13c10 --- /dev/null +++ b/Sandbox/Tests/CheckCaptures.cmake @@ -0,0 +1,75 @@ +# Runs the Sandbox headless twice, in --exec direct and --exec threaded, each writing captures +# at two ticks, then fails unless every file is there and the two runs wrote the same bytes: +# a capture shows the simulation, which does not depend on threads (Docs/threading-model.md +# section 9). +# +# KIND=state --null-render with --dump-state (JSON). Needs no GPU. +# KIND=screenshot --offscreen with --screenshot (PNG). Needs a Vulkan driver (a software one, +# such as llvmpipe, is enough) but no display. +# +# -DSANDBOX= -DROOT= -DOUT= -DKIND=state|screenshot + +foreach( _var SANDBOX ROOT OUT KIND ) + if( NOT DEFINED ${_var} ) + message( FATAL_ERROR "CheckCaptures.cmake needs -D${_var}=..." ) + endif() +endforeach() + +set( _ticks 10 30 ) +if( KIND STREQUAL "state" ) + set( _render --null-render ) + set( _flags --dump-state "{tick}.json" --dump-state-ticks 10,30 ) + set( _ext json ) +elseif( KIND STREQUAL "screenshot" ) + set( _render --offscreen --resolution 320x180 ) + set( _flags --screenshot "{tick}.png" --screenshot-ticks 10,30 ) + set( _ext png ) +else() + message( FATAL_ERROR "KIND must be state or screenshot, not ${KIND}" ) +endif() + +file( REMOVE_RECURSE "${OUT}" ) +foreach( _exec direct threaded ) + set( _dir "${OUT}/${_exec}" ) + file( MAKE_DIRECTORY "${_dir}" ) + # The file names are relative to the project, so give the folder as an absolute path + string( REPLACE "{tick}" "${_dir}/{tick}" _run_flags "${_flags}" ) + execute_process( + COMMAND "${SANDBOX}" ${_render} --unattended --frames 30 --seed 1 --exec ${_exec} ${_run_flags} + WORKING_DIRECTORY "${ROOT}" + RESULT_VARIABLE _code + OUTPUT_VARIABLE _out + ERROR_VARIABLE _out + ) + if( NOT _code EQUAL 0 ) + message( FATAL_ERROR "--exec ${_exec} exited with ${_code}:\n${_out}" ) + endif() + foreach( _tick IN LISTS _ticks ) + if( NOT EXISTS "${_dir}/${_tick}.${_ext}" ) + message( FATAL_ERROR "--exec ${_exec} wrote no ${_dir}/${_tick}.${_ext}:\n${_out}" ) + endif() + endforeach() +endforeach() + +foreach( _tick IN LISTS _ticks ) + file( SHA256 "${OUT}/direct/${_tick}.${_ext}" _direct ) + file( SHA256 "${OUT}/threaded/${_tick}.${_ext}" _threaded ) + if( NOT _direct STREQUAL _threaded ) + message( FATAL_ERROR "The ${KIND} of tick ${_tick} differs between --exec direct and threaded" ) + endif() +endforeach() + +if( KIND STREQUAL "state" ) + file( READ "${OUT}/direct/30.json" _doc ) + if( NOT _doc MATCHES "\"tick\": 30" OR NOT _doc MATCHES "\"Transform\"" ) + message( FATAL_ERROR "The state of tick 30 has no tick or no Transform:\n${_doc}" ) + endif() +else() + # A PNG file starts with these 8 bytes + file( READ "${OUT}/direct/30.png" _sig LIMIT 8 HEX ) + if( NOT _sig STREQUAL "89504e470d0a1a0a" ) + message( FATAL_ERROR "30.png is not a PNG file (it starts with ${_sig})" ) + endif() +endif() + +message( STATUS "Captures are the same in --exec direct and threaded" ) diff --git a/Skills/testing.md b/Skills/testing.md index 7a8b8887..814adb8f 100644 --- a/Skills/testing.md +++ b/Skills/testing.md @@ -159,6 +159,72 @@ Rules for code that can run under `--null-render`: headless, check the JSON exit summary, and check that a bad argument exits with code 3. +## Seeing the game without a window + +An agent (or a script) can look at a run in two ways, and neither opens a window. +Read the state first: it is cheaper than an image and you can check it exactly. Use a +screenshot only when the question is about what the frame looks like. + +### The state as text: `--dump-state` + +```bash +./build/Sandbox/bin/Sandbox --null-render --unattended --frames 60 --seed 1 \ + --dump-state Saved/state.json --dump-state-ticks 10,60 +# writes Saved/state_tick10.json and Saved/state_tick60.json +``` + +| Flag | What it does | +| --- | --- | +| `--dump-state F` | Write the simulation state as JSON to `F` (relative to the project folder, or absolute; missing folders are made). Works with `--null-render`: no GPU | +| `--dump-state-ticks L` | The ticks to write, a comma list such as `10,60`. Without it: the last tick of the run (`--frames` is then required) | + +Each file is written on the game thread right after its tick, so it is the state the +tick left (`World::SaveStateToJson`). It holds: + +- `tick`, `simHz`, `entityCount` and `stateHash` (the same hash as `--dump-ticks`). +- `entities`, in handle order: `entity` (`index:generation`), `name` when it has a + `NameComponent`, `guid`, then one object for each component, with every reflected field. +- `singletons`: one object for each singleton. + +The types are the ones the state hash covers (rollback state, Transient ones too) and +the ones a level saves. A type that is neither (a `RollbackClass::Keep` setting, a +render cache) is left out. The same seed, input and flags write the same bytes in +every exec mode, so two dumps can be diffed. It is not a level file: `--level` cannot +load it. + +### The rendered frame: `--offscreen` and `--screenshot` + +```bash +./build/Sandbox/bin/Sandbox --offscreen --unattended --frames 30 --seed 1 \ + --resolution 640x360 --screenshot Saved/shot.png --screenshot-ticks 1,30 +# writes Saved/shot_tick1.png and Saved/shot_tick30.png +``` + +| Flag | What it does | +| --- | --- | +| `--offscreen` | Render with Vulkan into images that the renderer owns. No window, no surface, no window system extension, and no GLFW: it runs on a machine with no display, and opens nothing on a machine that has one. The timing is the same as `--null-render` (a virtual clock, no frame cap), so the ticks are the same as a `--null-render` run. There is no developer UI (ImGui needs a window). Cannot be used with `--null-render` | +| `--resolution WxH` | The size of the frames (`--offscreen`) or of the window. Overrides `[Engine] WindowWidth` and `WindowHeight` | +| `--screenshot F` | Save the frame as a PNG file `F`. Works with `--offscreen` and with a window (then the editor UI is in the image too). Not with `--null-render` | +| `--screenshot-ticks L` | Save the first frame that shows each of these ticks. Without it: the last tick of the run (`--frames` is then required). The log line `Saved the frame of tick N (it shows tick M, WxH) to F` says which tick the frame shows | + +File names: with one tick the path is used as it is. With more than one, `_tick` goes +before the extension. `{tick}` in the path puts the tick where you want it +(`--screenshot frames/{tick}.png`). `CaptureFilePath` in `LaunchOptions.h` has the rule. + +A capture that was asked for and not made (the tick never ran, the file cannot be +written) logs an error and the run exits with code 1, so a script never reads an +old file. + +`--offscreen` needs a Vulkan driver, but a software one is enough: Mesa's lavapipe +(`llvmpipe`, package `mesa-vulkan-drivers` on Ubuntu) renders the Sandbox at 640x360 +in about 5 s for 30 ticks. The same flags give the same image in every exec mode. +`FLING_TEST_OFFSCREEN=ON` adds the CTest `Sandbox: offscreen screenshots`; it is off by +default because CI machines may have no Vulkan driver. `Sandbox: headless state dump` +always runs. + +To view a PNG, an agent reads the file (most agent tools show images). Choose a small +`--resolution` to keep the image cheap. + ## Unattended crash tests `FlingTests/CMakeLists.txt` adds `Unattended crash: ` tests. Each runs From b7e51e5a77f3935e1ec63dda1ab790ac9513e8d5 Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Mon, 16 Nov 2026 03:01:05 +0000 Subject: [PATCH 2/6] Screenshot API in Core and a Take screenshot button in GPU Options Fling::Screenshot::Request(path, callback) (Core/inc/Screenshot.h) asks for the next frame the renderer draws to be saved as a PNG. It is safe on any thread and needs no Graphics header, so the editor, frame systems, tools and tests can all call it. The renderer serves every waiting request at its next frame, before the present, and runs each callback on the main thread. With no path the file goes to Saved/Screenshots/Screenshot__.png. Under --null-render, and at the end of a run, waiting requests fail with the reason, so a caller always hears back. --screenshot now goes through the same API, which replaces VulkanApp::RequestCapture. FrameCapture reads the frame once and writes one PNG per request. The editor's GPU Options window has a Take screenshot button that saves the next frame, editor UI included, and shows the path. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 +- FlingEngine/Application/inc/Engine.h | 8 +- FlingEngine/Application/src/Engine.cpp | 61 ++++++------ FlingEngine/Core/inc/LaunchOptions.h | 3 +- FlingEngine/Core/inc/Screenshot.h | 83 ++++++++++++++++ FlingEngine/Core/src/Screenshot.cpp | 83 ++++++++++++++++ FlingEngine/Editor/inc/BaseEditor.h | 9 +- FlingEngine/Editor/src/BaseEditor.cpp | 26 +++++- FlingEngine/Graphics/inc/VulkanApp.h | 38 ++------ FlingEngine/Graphics/src/FrameCapture.cpp | 32 +++---- FlingEngine/Graphics/src/FrameCapture.h | 28 +++--- FlingEngine/Graphics/src/VulkanApp.cpp | 50 ++++++---- FlingTests/Core/ScreenshotTests.cpp | 109 ++++++++++++++++++++++ Skills/testing.md | 30 +++++- 14 files changed, 437 insertions(+), 127 deletions(-) create mode 100644 FlingEngine/Core/inc/Screenshot.h create mode 100644 FlingEngine/Core/src/Screenshot.cpp create mode 100644 FlingTests/Core/ScreenshotTests.cpp diff --git a/AGENTS.md b/AGENTS.md index 9d024475..88c10f0f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,7 +57,9 @@ platform setup (Vulkan SDK, GLFW, etc.). state as JSON at chosen ticks (works with `--null-render`), and `--offscreen --screenshot ` renders with Vulkan into offscreen images and saves PNG files (no window, no display; a software driver such as llvmpipe is enough). - Prefer the state dump; use screenshots for rendering work. Detail: + Prefer the state dump; use screenshots for rendering work. From C++ (any + module, any thread): `Fling::Screenshot::Request(path, callback)` in + `Screenshot.h`; the editor's GPU Options window has a Take screenshot button. Detail: [`Skills/testing.md`](Skills/testing.md#seeing-the-game-without-a-window). - Drive a headless run with `--replay-input `. Agents can write their own `.input.jsonl` files. Format and flags: [`Skills/input-playback.md`](Skills/input-playback.md). diff --git a/FlingEngine/Application/inc/Engine.h b/FlingEngine/Application/inc/Engine.h index 55d21201..d3e5f7d3 100644 --- a/FlingEngine/Application/inc/Engine.h +++ b/FlingEngine/Application/inc/Engine.h @@ -244,12 +244,9 @@ namespace Fling /** Writes the state dumps that the ticks made since the last call to their --dump-state files (main thread). */ void WriteStateDumps(); - /** Before the frame is drawn: ask the renderer to save it for each --screenshot tick that it shows. */ + /** Before the frame is drawn: a Screenshot::Request for each --screenshot tick that it shows. */ void RequestScreenshots(); - /** After the frame is drawn: log the screenshots that it saved, or why not. */ - void SaveScreenshots(); - /** --dump-state: the ticks whose state has not been written yet. Sorted. */ std::vector m_PendingStateDumps; @@ -259,9 +256,6 @@ namespace Fling /** --screenshot: the ticks whose frame has not been saved yet. Sorted. */ std::vector m_PendingScreenshots; - /** --screenshot: for each capture asked for this frame, the tick asked for and the tick the frame shows. */ - std::vector> m_ScreenshotShownTicks; - /** --screenshot: captures that failed. */ uint32 m_ScreenshotsFailed = 0; diff --git a/FlingEngine/Application/src/Engine.cpp b/FlingEngine/Application/src/Engine.cpp index ef49ed5d..2df93364 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -17,6 +17,7 @@ #include "PresentMode.h" #include "Random.h" #include "RegisterGraphics.h" +#include "Screenshot.h" #include "Strings/String.h" #include "Threading/Lane.h" #include "Threading/Thread.h" @@ -609,15 +610,17 @@ namespace Fling if (m_Options.NullRender) { + // No renderer to serve a Screenshot::Request: it fails now, so its caller hears back + Screenshot::FailPending("there is no renderer (--null-render); use --offscreen"); // No cap unless a setting asks for one (RunSettings::ResolveFrameCap), so tests stay fast m_FrameLimiter.WaitForNextFrame(); } else { - // A window, or offscreen images (--offscreen) + // A window, or offscreen images (--offscreen). The present saves the screenshots + // that are waiting (Screenshot::Request), from --screenshot or anywhere else RequestScreenshots(); Present(DeltaTime); - SaveScreenshots(); } Timing.UpdateFps(); } @@ -631,7 +634,10 @@ namespace Fling m_World->GetTickCount(), AverageFrameMs, AverageFrameMs > 0.0 ? 1000.0 / AverageFrameMs : 0.0); - // A screenshot that was asked for and not taken fails the run, so a script does not read an old file + // A request that no frame served (the loop ended first) fails, so its caller hears back + Screenshot::FailPending("the run ended before the next frame was drawn"); + + // A screenshot that was asked for and not made fails the run, so a script does not read an old file bool bCapturesOk = m_ScreenshotsFailed == 0; for (const uint64 Tick : m_PendingScreenshots) { @@ -850,39 +856,25 @@ namespace Fling { const uint64 Tick = m_PendingScreenshots.front(); m_PendingScreenshots.erase(m_PendingScreenshots.begin()); - const String Path = FlingPaths::ResolveProjectPath(CaptureFilePath(m_Options.Screenshot, Tick, bManyTicks)); - VulkanApp::Get().RequestCapture(Path); - m_ScreenshotShownTicks.push_back({Tick, Shown}); + // The renderer serves it at this frame's present; the callback runs on this thread + Screenshot::Request(CaptureFilePath(m_Options.Screenshot, Tick, bManyTicks), + [this, Tick, Shown](const ScreenshotResult& t_Result) + { + if (!t_Result.Ok) + { + ++m_ScreenshotsFailed; + return; + } + F_LOG_TRACE("Saved the frame of tick {} (it shows tick {}, {}x{}) to {}", + Tick, + Shown, + t_Result.Width, + t_Result.Height, + t_Result.Path); + }); } } - void Engine::SaveScreenshots() - { - std::vector Results = VulkanApp::Get().TakeCaptureResults(); - for (size_t i = 0; i < Results.size(); ++i) - { - const CaptureResult& Result = Results[i]; - const std::pair Ticks = - i < m_ScreenshotShownTicks.size() ? m_ScreenshotShownTicks[i] : std::pair{0, 0}; - if (!Result.Ok) - { - F_LOG_ERROR("--screenshot: cannot save {}: {}", Result.Path, Result.Error); - ++m_ScreenshotsFailed; - continue; - } - F_LOG_TRACE("Saved the frame of tick {} (it shows tick {}, {}x{}) to {}", - Ticks.first, - Ticks.second, - VulkanApp::Get().GetFrameWidth(), - VulkanApp::Get().GetFrameHeight(), - Result.Path); - } - // A frame that was not drawn (a window resize) keeps its captures for the next frame - const size_t Done = std::min(Results.size(), m_ScreenshotShownTicks.size()); - m_ScreenshotShownTicks.erase(m_ScreenshotShownTicks.begin(), - m_ScreenshotShownTicks.begin() + static_cast(Done)); - } - bool Engine::ShouldTick() const { // --frames: the run ends after N frames, once the frame side shows the last tick (the @@ -911,6 +903,9 @@ namespace Fling m_World->Shutdown(); m_TicksAtExit = m_World->GetTickCount(); + // No frame is drawn from here on: a screenshot request still waiting fails, so its caller hears back + Screenshot::FailPending("the engine shut down before the next frame was drawn"); + // The game thread has joined: a dump that it made after the last frame is here now WriteStateDumps(); if (!m_Options.DumpState.empty() && t_Code == ExitCode::Success) diff --git a/FlingEngine/Core/inc/LaunchOptions.h b/FlingEngine/Core/inc/LaunchOptions.h index 546eaa4b..b285c7f2 100644 --- a/FlingEngine/Core/inc/LaunchOptions.h +++ b/FlingEngine/Core/inc/LaunchOptions.h @@ -32,7 +32,8 @@ namespace Fling * surface. Timing is the same as --null-render (a virtual clock, no * frame cap), so a run gives the same ticks. For --screenshot * --resolution WxH The size of the frames (--offscreen) or of the window, for example 1280x720. - * Overrides [Engine] WindowWidth and WindowHeight + * Overrides [Engine] WindowWidth and WindowHeight. A window is still + * made smaller to fit the screen * --screenshot F Save the rendered frame as a PNG file F (relative to the project). * Needs a renderer (--offscreen or a window), not --null-render * --screenshot-ticks L The ticks to save a frame at, a comma list such as 30,60,120: the diff --git a/FlingEngine/Core/inc/Screenshot.h b/FlingEngine/Core/inc/Screenshot.h new file mode 100644 index 00000000..4df8fbca --- /dev/null +++ b/FlingEngine/Core/inc/Screenshot.h @@ -0,0 +1,83 @@ +#pragma once + +#include "CoreAPI.h" +#include "FlingTypes.h" +#include "Strings/String.h" + +#include +#include + +namespace Fling +{ + /** How one screenshot went (Screenshot::Request). */ + struct ScreenshotResult + { + /** The file that was asked for, resolved to an absolute path. */ + String Path; + + /** True when the PNG file was written. */ + bool Ok = false; + + /** Why it failed, when Ok is false. */ + String Error; + + /** The size of the frame in pixels. 0 when it failed. */ + uint32 Width = 0; + uint32 Height = 0; + }; + + /** Called once for each request, on the main thread, after the file is written or the request fails. */ + using ScreenshotCallback = std::function; + + /** + * Save the next frame that the renderer draws as a PNG file, from anywhere in the engine: + * the editor, a frame system, a tool, a test. Request is safe on any thread, and needs no + * Graphics header: the renderer (VulkanApp) takes the requests at its next frame. It + * works with a window (the image then has the editor UI in it) and with --offscreen. + * Under --null-render there is no renderer, so each request fails at the next frame. + * + * A frame shows the simulation state that the frame side has, not a tick on the game + * thread. To save the frame of a given tick, use --screenshot-ticks, which calls this + * when the frame side first shows that tick. + * + * Fling::Screenshot::Request("Saved/door_open.png", + * [](const Fling::ScreenshotResult& t_Result) { F_LOG_TRACE("Saved: {}", t_Result.Ok); }); + * + * Do not call it from simulation code to change the simulation: the result arrives on + * the main thread, out of step with the ticks. + */ + class CORE_API Screenshot + { + public: + /** One request waiting for a frame. The renderer side reads it. */ + struct Pending + { + String Path; + ScreenshotCallback OnDone; + }; + + /** + * Ask for the next frame to be saved. Safe on any thread. + * + * @param t_Path The PNG file. Relative paths are relative to the project folder. + * Missing folders are made. Empty: DefaultPath() + * @param t_OnDone Optional. Called on the main thread when the file is written or the + * request fails. A result is also logged either way + * @return The resolved path the file will be written to + */ + static String Request(StringView t_Path = {}, ScreenshotCallback t_OnDone = {}); + + /** A new file name under Saved/Screenshots, named with the local time, for example + * Screenshot_2026-11-16_14-03-22_1.png. */ + static String DefaultPath(); + + /** Renderer side (main thread): the requests since the last call, in request order. */ + static std::vector TakePending(); + + /** Renderer side (main thread): log the result and call the request's callback. */ + static void Finish(Pending& t_Request, const ScreenshotResult& t_Result); + + /** Fail every waiting request with t_Reason (--null-render, or shutdown). Main thread. */ + static void FailPending(StringView t_Reason); + }; +} // namespace Fling diff --git a/FlingEngine/Core/src/Screenshot.cpp b/FlingEngine/Core/src/Screenshot.cpp new file mode 100644 index 00000000..7a5ea189 --- /dev/null +++ b/FlingEngine/Core/src/Screenshot.cpp @@ -0,0 +1,83 @@ +#include "FlingPaths.h" +#include "Logger.h" +#include "Screenshot.h" +#include "Threading/ThreadQueue.h" + +#include +#include +#include +#include +#include + +namespace Fling +{ + namespace + { + /** Any thread to the main thread: the requests waiting for a frame. */ + ThreadQueue& PendingQueue() + { + static ThreadQueue s_Queue; + return s_Queue; + } + + /** Makes DefaultPath names unique within one second. */ + std::atomic s_DefaultPathCount{0}; + } // namespace + + String Screenshot::DefaultPath() + { + const std::time_t Now = std::time(nullptr); + std::tm LocalTime = {}; +#if defined(_WIN32) + localtime_s(&LocalTime, &Now); +#else + localtime_r(&Now, &LocalTime); +#endif + std::ostringstream Name; + Name << FlingPaths::ProjectSavedDir() << "/Screenshots/Screenshot_" + << std::put_time(&LocalTime, "%Y-%m-%d_%H-%M-%S") << "_" + << s_DefaultPathCount.fetch_add(1, std::memory_order_relaxed) + 1 << ".png"; + return Name.str(); + } + + String Screenshot::Request(const StringView t_Path, ScreenshotCallback t_OnDone) + { + const String Path = t_Path.empty() ? DefaultPath() : FlingPaths::ResolveProjectPath(t_Path); + PendingQueue().Push(Pending{Path, std::move(t_OnDone)}); + return Path; + } + + std::vector Screenshot::TakePending() + { + std::vector Requests; + PendingQueue().Drain([&Requests](Pending& t_Request) { Requests.push_back(std::move(t_Request)); }); + return Requests; + } + + void Screenshot::Finish(Pending& t_Request, const ScreenshotResult& t_Result) + { + if (t_Result.Ok) + { + F_LOG_TRACE("Screenshot saved ({}x{}) to {}", t_Result.Width, t_Result.Height, t_Result.Path); + } + else + { + F_LOG_ERROR("Screenshot not saved to {}: {}", t_Result.Path, t_Result.Error); + } + if (t_Request.OnDone) + { + t_Request.OnDone(t_Result); + } + } + + void Screenshot::FailPending(const StringView t_Reason) + { + for (Pending& Request : TakePending()) + { + ScreenshotResult Result; + Result.Path = Request.Path; + Result.Error = String(t_Reason); + Finish(Request, Result); + } + } +} // namespace Fling diff --git a/FlingEngine/Editor/inc/BaseEditor.h b/FlingEngine/Editor/inc/BaseEditor.h index c5c30022..510dac2e 100644 --- a/FlingEngine/Editor/inc/BaseEditor.h +++ b/FlingEngine/Editor/inc/BaseEditor.h @@ -53,6 +53,12 @@ namespace Fling float m_FrameTimeMax = 0.0f; bool m_DisplayGpuOptions = false; + + /** + * The last screenshot taken with the GPU Options button: what the window shows under it. + * Shared, so a result that arrives after the editor is gone writes nowhere. + */ + std::shared_ptr m_ScreenshotStatus = std::make_shared(); bool m_DisplayComponentEditor = true; bool m_DisplayWorldOutline = true; bool m_DisplayWindowOptions = false; @@ -81,7 +87,8 @@ namespace Fling /** * The GPU Options window: the device, VSync (with the present mode in use), the frame * cap, the simulation rate and render interpolation, with what the frame limiter does - * and the measured rates. Each control + * and the measured rates, and a button that saves the next frame as a PNG + * (Screenshot::Request). Each control * calls RunControls, which checks the request; a number box applies when its edit is * committed (Enter or focus loss). */ diff --git a/FlingEngine/Editor/src/BaseEditor.cpp b/FlingEngine/Editor/src/BaseEditor.cpp index 1b5c62bd..83f92cc8 100644 --- a/FlingEngine/Editor/src/BaseEditor.cpp +++ b/FlingEngine/Editor/src/BaseEditor.cpp @@ -16,6 +16,7 @@ #include "MeshRenderer.h" #include "PresentMode.h" #include "RunControls.h" +#include "Screenshot.h" #include "SimRate.h" #include "Timing.h" #include "TransformUtil.h" @@ -410,7 +411,7 @@ namespace Fling // Right of the World Outline and Entity Editor windows, so none covers another on // first use, and wide enough for the limiter and measured lines ImGui::SetNextWindowPos(ImVec2(520, 30), ImGuiCond_FirstUseEver); - ImGui::SetNextWindowSize(ImVec2(600, 340), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(ImVec2(600, 400), ImGuiCond_FirstUseEver); ImGui::Begin("GPU Options"); const String DeviceName = VulkanApp::Get().GetPhysicalDeviceName(); @@ -453,6 +454,29 @@ namespace Fling ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", m_ControlsError.c_str()); } + ImGui::Separator(); + // The next frame as it is shown, this window included, to Saved/Screenshots + if (ImGui::Button("Take screenshot")) + { + const std::weak_ptr Status = m_ScreenshotStatus; + const String Path = Screenshot::Request({}, + [Status](const ScreenshotResult& t_Result) + { + if (const std::shared_ptr Text = Status.lock()) + { + *Text = t_Result.Ok ? "Saved " + t_Result.Path + : "Not saved: " + t_Result.Error; + } + }); + *m_ScreenshotStatus = "Saving " + Path; + } + ImGui::SameLine(); + ImGui::TextDisabled("The next frame, with the editor UI, as a PNG"); + if (!m_ScreenshotStatus->empty()) + { + ImGui::TextWrapped("%s", m_ScreenshotStatus->c_str()); + } + ImGui::Separator(); const float Fps = static_cast(Timing::Get().GetFrameCount()); ImGui::TextWrapped("%s", Controls.DescribeMeasured(Fps).c_str()); diff --git a/FlingEngine/Graphics/inc/VulkanApp.h b/FlingEngine/Graphics/inc/VulkanApp.h index 787bb2bd..252db1d6 100644 --- a/FlingEngine/Graphics/inc/VulkanApp.h +++ b/FlingEngine/Graphics/inc/VulkanApp.h @@ -32,7 +32,7 @@ namespace Fling /** * True: draw into images that the renderer owns (--offscreen). There is no window, no * surface, and no window system: a run works on a machine with no display, and opens - * nothing on a machine that has one. Captures (RequestCapture) still work. + * nothing on a machine that has one. Screenshots (Screenshot::Request) still work. */ bool Offscreen = false; @@ -41,18 +41,6 @@ namespace Fling uint32 Height = 0; }; - /** The result of one RequestCapture. */ - struct CaptureResult - { - /** The file that was asked for. */ - String Path; - - bool Ok = false; - - /** Why it failed, when Ok is false. */ - String Error; - }; - class Instance; class LogicalDevice; class PhysicalDevice; @@ -140,16 +128,6 @@ namespace Fling uint32 GetFrameWidth() const; uint32 GetFrameHeight() const; - /** - * Save the next frame that Update draws as a PNG file (t_Path, already resolved), - * offscreen or with a window. More than one call before that frame saves the same - * frame to each path. TakeCaptureResults says how each went. - */ - void RequestCapture(StringView t_Path) { m_PendingCaptures.emplace_back(t_Path); } - - /** The results of the captures since the last call, in request order. */ - std::vector TakeCaptureResults() { return std::exchange(m_CaptureResults, {}); } - protected: void Init() override {} void Shutdown() override {} @@ -232,13 +210,11 @@ namespace Fling /** @see SetRenderSurface */ RenderSurfaceDesc m_SurfaceDesc; - /** @see RequestCapture */ - std::vector m_PendingCaptures; - - /** @see TakeCaptureResults */ - std::vector m_CaptureResults; - - /** Save the frame in the active image to the pending captures (Update, after the frame's fence). */ - void SaveCaptures(); + /** + * Save the frame in the active image for the Screenshot requests that are waiting + * (Screenshot::Request, from any module or thread). Update calls it after the frame's + * fence, before the present. + */ + void SaveScreenshots(); }; } // namespace Fling diff --git a/FlingEngine/Graphics/src/FrameCapture.cpp b/FlingEngine/Graphics/src/FrameCapture.cpp index 00d5632a..9732c2ce 100644 --- a/FlingEngine/Graphics/src/FrameCapture.cpp +++ b/FlingEngine/Graphics/src/FrameCapture.cpp @@ -66,13 +66,13 @@ namespace Fling return true; } - bool SaveImageAsPng(LogicalDevice& t_Device, - const VkImage t_Image, - const VkFormat t_Format, - const VkExtent2D t_Extent, - const VkImageLayout t_Layout, - const std::vector& t_Paths, - String& t_OutError) + bool ReadImageRgba(LogicalDevice& t_Device, + const VkImage t_Image, + const VkFormat t_Format, + const VkExtent2D t_Extent, + const VkImageLayout t_Layout, + std::vector& t_OutRgba, + String& t_OutError) { if (!IsBgra(t_Format) && !IsRgba(t_Format)) { @@ -160,28 +160,20 @@ namespace Fling void* Mapped = nullptr; vkMapMemory(Device, StagingMemory, 0, Size, 0, &Mapped); - std::vector Rgba(static_cast(Size)); - std::memcpy(Rgba.data(), Mapped, static_cast(Size)); + t_OutRgba.resize(static_cast(Size)); + std::memcpy(t_OutRgba.data(), Mapped, static_cast(Size)); vkUnmapMemory(Device, StagingMemory); vkDestroyBuffer(Device, Staging, nullptr); vkFreeMemory(Device, StagingMemory, nullptr); const bool bSwap = IsBgra(t_Format); - for (size_t i = 0; i < Rgba.size(); i += 4) + for (size_t i = 0; i < t_OutRgba.size(); i += 4) { if (bSwap) { - std::swap(Rgba[i], Rgba[i + 2]); - } - Rgba[i + 3] = 255; - } - - for (const String& Path : t_Paths) - { - if (!WritePng(Path, t_Extent.width, t_Extent.height, Rgba.data(), t_OutError)) - { - return false; + std::swap(t_OutRgba[i], t_OutRgba[i + 2]); } + t_OutRgba[i + 3] = 255; } return true; } diff --git a/FlingEngine/Graphics/src/FrameCapture.h b/FlingEngine/Graphics/src/FrameCapture.h index b0846260..a15a0a64 100644 --- a/FlingEngine/Graphics/src/FrameCapture.h +++ b/FlingEngine/Graphics/src/FrameCapture.h @@ -13,10 +13,10 @@ namespace Fling namespace FrameCapture { /** - * Copy a color image that the GPU has finished drawing to host memory, and save it as - * a PNG file at each path (--screenshot). The image must have been made with - * VK_IMAGE_USAGE_TRANSFER_SRC_BIT. It is left in t_Layout. Alpha is written as opaque: - * the frame's clear alpha is not meant to be seen. + * Copy a color image that the GPU has finished drawing to host memory as RGBA8 (4 + * bytes a pixel, rows top to bottom; Screenshot requests). The image must have been + * made with VK_IMAGE_USAGE_TRANSFER_SRC_BIT. It is left in t_Layout. Alpha is written + * as opaque: the frame's clear alpha is not meant to be seen. * * Waits for the graphics queue to be idle, so call it only for a capture. * @@ -24,17 +24,17 @@ namespace Fling * @param t_Format VK_FORMAT_B8G8R8A8_* or VK_FORMAT_R8G8B8A8_* (other formats are refused) * @param t_Extent The size of the image * @param t_Layout The layout the image is in now (PRESENT_SRC or TRANSFER_SRC) - * @param t_Paths The files to write, already resolved. Missing folders are made - * @param t_OutError Receives why the capture failed - * @return False if the format is not supported or a file could not be written + * @param t_OutRgba Receives the pixels + * @param t_OutError Receives why it failed + * @return False if the format is not supported */ - bool SaveImageAsPng(LogicalDevice& t_Device, - VkImage t_Image, - VkFormat t_Format, - VkExtent2D t_Extent, - VkImageLayout t_Layout, - const std::vector& t_Paths, - String& t_OutError); + bool ReadImageRgba(LogicalDevice& t_Device, + VkImage t_Image, + VkFormat t_Format, + VkExtent2D t_Extent, + VkImageLayout t_Layout, + std::vector& t_OutRgba, + String& t_OutError); /** * Encode RGBA8 pixels (4 bytes a pixel, rows top to bottom) as a PNG file. Missing diff --git a/FlingEngine/Graphics/src/VulkanApp.cpp b/FlingEngine/Graphics/src/VulkanApp.cpp index 08f2e882..7611a22d 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -20,6 +20,7 @@ #include "PhyscialDevice.h" #include "RenderPipeline.h" #include "RenderSnapshot.h" +#include "Screenshot.h" #include "SkyboxSubpass.h" #include "Strings/String.h" #include "SwapChain.h" @@ -440,32 +441,47 @@ namespace Fling return m_SwapChain ? m_SwapChain->GetExtents().height : 0; } - void VulkanApp::SaveCaptures() + void VulkanApp::SaveScreenshots() { - if (m_PendingCaptures.empty()) + std::vector Requests = Screenshot::TakePending(); + if (Requests.empty()) { return; } - std::vector Paths = std::exchange(m_PendingCaptures, {}); - String Error; - bool bOk = false; + + // One copy of the frame for every request that is waiting + std::vector Rgba; + String ReadError; + const VkExtent2D Extent = m_SwapChain->GetExtents(); + bool bRead = false; if (!m_SwapChain->CanCopyImages()) { - Error = "the swap chain images cannot be copied (no VK_IMAGE_USAGE_TRANSFER_SRC_BIT); use --offscreen"; + ReadError = "the swap chain images cannot be copied (no VK_IMAGE_USAGE_TRANSFER_SRC_BIT); use --offscreen"; } else { - bOk = FrameCapture::SaveImageAsPng(*m_LogicalDevice, - m_SwapChain->GetActiveImage(), - m_SwapChain->GetImageFormat(), - m_SwapChain->GetExtents(), - m_SwapChain->GetFinalLayout(), - Paths, - Error); + bRead = FrameCapture::ReadImageRgba(*m_LogicalDevice, + m_SwapChain->GetActiveImage(), + m_SwapChain->GetImageFormat(), + Extent, + m_SwapChain->GetFinalLayout(), + Rgba, + ReadError); } - for (String& Path : Paths) + + for (Screenshot::Pending& Request : Requests) { - m_CaptureResults.push_back(CaptureResult{std::move(Path), bOk, bOk ? String() : Error}); + ScreenshotResult Result; + Result.Path = Request.Path; + Result.Error = ReadError; + Result.Ok = + bRead && FrameCapture::WritePng(Request.Path, Extent.width, Extent.height, Rgba.data(), Result.Error); + if (Result.Ok) + { + Result.Width = Extent.width; + Result.Height = Extent.height; + } + Screenshot::Finish(Request, Result); } } @@ -807,8 +823,8 @@ namespace Fling VK_TRUE, std::numeric_limits::max()); - // The frame is drawn: copy it out before it is presented (--screenshot) - SaveCaptures(); + // The frame is drawn: copy it out before it is presented (Screenshot::Request) + SaveScreenshots(); // Present the swap chain with the renderer finished semaphore iResult = m_SwapChain->QueuePresent(m_LogicalDevice->GetPresentQueue(), diff --git a/FlingTests/Core/ScreenshotTests.cpp b/FlingTests/Core/ScreenshotTests.cpp new file mode 100644 index 00000000..2df68e3f --- /dev/null +++ b/FlingTests/Core/ScreenshotTests.cpp @@ -0,0 +1,109 @@ +#include "FlingPaths.h" +#include "Screenshot.h" +#include "Strings/String.h" + +#include +#include +#include + +using Fling::Screenshot; +using Fling::ScreenshotResult; +using Fling::String; + +TEST_CASE("Screenshot requests wait for the renderer, in order", "[Screenshot]") +{ + // Nothing left from another test + Screenshot::FailPending("test start"); + + const String First = Screenshot::Request("Saved/a.png"); + const String Second = Screenshot::Request("Saved/b.png"); + REQUIRE(First == Fling::FlingPaths::ResolveProjectPath("Saved/a.png")); + + std::vector Pending = Screenshot::TakePending(); + REQUIRE(Pending.size() == 2); + REQUIRE(Pending[0].Path == First); + REQUIRE(Pending[1].Path == Second); + // Taken once + REQUIRE(Screenshot::TakePending().empty()); +} + +TEST_CASE("Screenshot with no path gets a new file under Saved/Screenshots", "[Screenshot]") +{ + Screenshot::FailPending("test start"); + + const String A = Screenshot::Request(); + const String B = Screenshot::Request(); + REQUIRE(A != B); + REQUIRE_THAT(A, Catch::Matchers::StartsWith(Fling::FlingPaths::ProjectSavedDir() + "/Screenshots/Screenshot_")); + REQUIRE_THAT(A, Catch::Matchers::EndsWith(".png")); + Screenshot::FailPending("test end"); +} + +TEST_CASE("Screenshot callbacks hear the result", "[Screenshot]") +{ + Screenshot::FailPending("test start"); + + std::vector Results; + const auto Keep = [&Results](const ScreenshotResult& t_Result) + { + Results.push_back(t_Result); + }; + + SECTION("Finish passes the renderer's result on") + { + Screenshot::Request("Saved/ok.png", Keep); + std::vector Pending = Screenshot::TakePending(); + REQUIRE(Pending.size() == 1); + ScreenshotResult Done; + Done.Path = Pending[0].Path; + Done.Ok = true; + Done.Width = 320; + Done.Height = 180; + Screenshot::Finish(Pending[0], Done); + + REQUIRE(Results.size() == 1); + REQUIRE(Results[0].Ok); + REQUIRE(Results[0].Width == 320); + } + + SECTION("FailPending fails each waiting request with the reason (no renderer)") + { + Screenshot::Request("Saved/one.png", Keep); + Screenshot::Request("Saved/two.png", Keep); + Screenshot::FailPending("there is no renderer"); + + REQUIRE(Results.size() == 2); + for (const ScreenshotResult& Result : Results) + { + REQUIRE_FALSE(Result.Ok); + REQUIRE(Result.Error == "there is no renderer"); + } + REQUIRE_THAT(Results[1].Path, Catch::Matchers::EndsWith("two.png")); + REQUIRE(Screenshot::TakePending().empty()); + } +} + +TEST_CASE("Screenshot requests from many threads all arrive", "[Screenshot]") +{ + Screenshot::FailPending("test start"); + + constexpr int ThreadCount = 4; + constexpr int PerThread = 50; + std::vector Threads; + for (int t = 0; t < ThreadCount; ++t) + { + Threads.emplace_back( + [t]() + { + for (int i = 0; i < PerThread; ++i) + { + Screenshot::Request("Saved/t" + std::to_string(t) + "_" + std::to_string(i) + ".png"); + } + }); + } + for (std::thread& Each : Threads) + { + Each.join(); + } + REQUIRE(Screenshot::TakePending().size() == ThreadCount * PerThread); +} diff --git a/Skills/testing.md b/Skills/testing.md index 814adb8f..186b522e 100644 --- a/Skills/testing.md +++ b/Skills/testing.md @@ -203,7 +203,7 @@ load it. | Flag | What it does | | --- | --- | | `--offscreen` | Render with Vulkan into images that the renderer owns. No window, no surface, no window system extension, and no GLFW: it runs on a machine with no display, and opens nothing on a machine that has one. The timing is the same as `--null-render` (a virtual clock, no frame cap), so the ticks are the same as a `--null-render` run. There is no developer UI (ImGui needs a window). Cannot be used with `--null-render` | -| `--resolution WxH` | The size of the frames (`--offscreen`) or of the window. Overrides `[Engine] WindowWidth` and `WindowHeight` | +| `--resolution WxH` | The size of the frames (`--offscreen`) or of the window. Overrides `[Engine] WindowWidth` and `WindowHeight`. A window is still made smaller to fit the screen's work area; offscreen frames are always this size | | `--screenshot F` | Save the frame as a PNG file `F`. Works with `--offscreen` and with a window (then the editor UI is in the image too). Not with `--null-render` | | `--screenshot-ticks L` | Save the first frame that shows each of these ticks. Without it: the last tick of the run (`--frames` is then required). The log line `Saved the frame of tick N (it shows tick M, WxH) to F` says which tick the frame shows | @@ -225,6 +225,34 @@ always runs. To view a PNG, an agent reads the file (most agent tools show images). Choose a small `--resolution` to keep the image cheap. +### Screenshots from the editor or from C++ + +The editor's GPU Options window (menu Windows; open in `--play` too) has a **Take +screenshot** button. It saves the next frame as it is shown, editor UI included, to +`Saved/Screenshots/Screenshot__.png`, and shows the path under the button. + +Code anywhere in the engine can do the same with `Fling::Screenshot` (`Screenshot.h`, in +Core, so a module needs no Graphics header): + +```cpp +#include "Screenshot.h" + +// Any thread. Empty path: a new file under Saved/Screenshots +Fling::Screenshot::Request("Saved/door_open.png", + [](const Fling::ScreenshotResult& t_Result) + { + // On the main thread, after the file is written (or not) + F_LOG_TRACE("{}: {}", t_Result.Path, t_Result.Ok ? "saved" : t_Result.Error); + }); +``` + +The renderer saves every waiting request at its next frame, before the present, and logs +`Screenshot saved (WxH) to ` or the error. The callback is optional. Under +`--null-render` there is no renderer, so a request fails at the next frame with that +reason; a request still waiting when the run ends fails too. `--screenshot` uses this API. +Use it for tools, tests and debugging, not to feed results back into the simulation: the +callback arrives on the main thread, out of step with the ticks. + ## Unattended crash tests `FlingTests/CMakeLists.txt` adds `Unattended crash: ` tests. Each runs From a0c1f5352f52b5d29b31c90a8d35e1a3dc1d68bb Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Mon, 16 Nov 2026 13:23:36 +0000 Subject: [PATCH 3/6] Screenshots cost nothing when nobody asks for one Before, every frame paid for screenshots even with none requested: - the renderer locked the request queue each frame (and so did the --null-render loop); - every swap chain image, and every offscreen image, was made with VK_IMAGE_USAGE_TRANSFER_SRC_BIT, which can turn off framebuffer compression on some GPUs. Now: - Screenshot::HasPending is one atomic load; TakePending and FailPending take no lock and allocate nothing when it is false. - Swapchain::SetCopyable decides whether its images get the copy usage. It is off by default. A run with --screenshot is copyable from the start (RenderSurfaceDesc::CopyableFrames) and never rebuilds the swap chain. Otherwise a request makes the swap chain again with copyable images for its frame (VulkanApp::PrepareScreenshots), saves it, and makes it again without them after that frame's present. - Offscreen images that are not copyable end the frame in COLOR_ATTACHMENT_OPTIMAL, as TRANSFER_SRC_OPTIMAL needs the usage. RecreateSwapchain works offscreen too. - Engine::RequestScreenshots returns at once with no --screenshot tick pending. Checked with the validation layer: --screenshot at launch, a runtime request offscreen, no request, and the GPU Options button in a window. Co-Authored-By: Claude Opus 5.5 --- FlingEngine/Application/src/Engine.cpp | 7 +++ FlingEngine/Core/inc/Screenshot.h | 15 ++++++- FlingEngine/Core/src/Screenshot.cpp | 18 ++++++++ FlingEngine/Graphics/inc/VulkanApp.h | 18 ++++++++ FlingEngine/Graphics/src/SwapChain.cpp | 35 +++++++++++---- FlingEngine/Graphics/src/SwapChain.h | 31 ++++++++++--- FlingEngine/Graphics/src/VulkanApp.cpp | 60 ++++++++++++++++++++++---- FlingTests/Core/ScreenshotTests.cpp | 18 ++++++++ Skills/testing.md | 10 +++++ 9 files changed, 189 insertions(+), 23 deletions(-) diff --git a/FlingEngine/Application/src/Engine.cpp b/FlingEngine/Application/src/Engine.cpp index 2df93364..2947227a 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -367,6 +367,9 @@ namespace Fling Surface.Offscreen = m_Options.Offscreen; Surface.Width = m_Options.ResolutionWidth; Surface.Height = m_Options.ResolutionHeight; + // A run that will take screenshots keeps its frames copyable; any other run makes them + // copyable only for a frame that a Screenshot::Request needs + Surface.CopyableFrames = !m_Options.Screenshot.empty(); VulkanApp::Get().SetRenderSurface(Surface); uint32 Pipelines = PipelineFlags::DEFERRED | PipelineFlags::CUBEMAP; @@ -848,6 +851,10 @@ namespace Fling void Engine::RequestScreenshots() { + if (m_PendingScreenshots.empty()) + { + return; + } // The frame that first shows each tick. With threaded play the frame side can show a // later tick than the one asked for; the log line says which tick the file shows. const uint64 Shown = m_World->GetShownTick(); diff --git a/FlingEngine/Core/inc/Screenshot.h b/FlingEngine/Core/inc/Screenshot.h index 4df8fbca..a409ed22 100644 --- a/FlingEngine/Core/inc/Screenshot.h +++ b/FlingEngine/Core/inc/Screenshot.h @@ -36,6 +36,10 @@ namespace Fling * works with a window (the image then has the editor UI in it) and with --offscreen. * Under --null-render there is no renderer, so each request fails at the next frame. * + * It costs nothing when nobody asks: a frame with no request does one atomic load. The + * frames are made copyable only while a capture needs it (--screenshot at launch, or + * the one frame a request is for), so normal frames keep every GPU optimization. + * * A frame shows the simulation state that the frame side has, not a tick on the game * thread. To save the frame of a given tick, use --screenshot-ticks, which calls this * when the frame side first shows that tick. @@ -71,7 +75,16 @@ namespace Fling * Screenshot_2026-11-16_14-03-22_1.png. */ static String DefaultPath(); - /** Renderer side (main thread): the requests since the last call, in request order. */ + /** + * True when a request is waiting. One atomic load and no lock, so the renderer can ask + * every frame for free. Any thread. + */ + static bool HasPending(); + + /** + * Renderer side (main thread): the requests since the last call, in request order. + * With none waiting it takes no lock and allocates nothing. + */ static std::vector TakePending(); /** Renderer side (main thread): log the result and call the request's callback. */ diff --git a/FlingEngine/Core/src/Screenshot.cpp b/FlingEngine/Core/src/Screenshot.cpp index 7a5ea189..f4c0246d 100644 --- a/FlingEngine/Core/src/Screenshot.cpp +++ b/FlingEngine/Core/src/Screenshot.cpp @@ -20,6 +20,12 @@ namespace Fling return s_Queue; } + /** + * The requests in the queue: one atomic load answers HasPending, so a frame with no + * request takes no lock. Signed: a drain can take an item before its push adds 1. + */ + std::atomic s_PendingCount{0}; + /** Makes DefaultPath names unique within one second. */ std::atomic s_DefaultPathCount{0}; } // namespace @@ -44,13 +50,25 @@ namespace Fling { const String Path = t_Path.empty() ? DefaultPath() : FlingPaths::ResolveProjectPath(t_Path); PendingQueue().Push(Pending{Path, std::move(t_OnDone)}); + s_PendingCount.fetch_add(1, std::memory_order_release); return Path; } + bool Screenshot::HasPending() + { + return s_PendingCount.load(std::memory_order_acquire) > 0; + } + std::vector Screenshot::TakePending() { std::vector Requests; + // The common case, every frame: nothing asked for, so no lock and no allocation + if (!HasPending()) + { + return Requests; + } PendingQueue().Drain([&Requests](Pending& t_Request) { Requests.push_back(std::move(t_Request)); }); + s_PendingCount.fetch_sub(static_cast(Requests.size()), std::memory_order_acq_rel); return Requests; } diff --git a/FlingEngine/Graphics/inc/VulkanApp.h b/FlingEngine/Graphics/inc/VulkanApp.h index 252db1d6..57724f0c 100644 --- a/FlingEngine/Graphics/inc/VulkanApp.h +++ b/FlingEngine/Graphics/inc/VulkanApp.h @@ -39,6 +39,13 @@ namespace Fling /** The size of the frames (offscreen) or the window. 0: [Engine] WindowWidth and WindowHeight. */ uint32 Width = 0; uint32 Height = 0; + + /** + * Make the frames copyable (VK_IMAGE_USAGE_TRANSFER_SRC_BIT) for the whole run: a run that + * will take screenshots (--screenshot). Off: a Screenshot::Request makes the frames + * copyable for the frame it needs only, and the run pays nothing when nobody asks. + */ + bool CopyableFrames = false; }; class Instance; @@ -216,5 +223,16 @@ namespace Fling * fence, before the present. */ void SaveScreenshots(); + + /** + * Before the frame: when a Screenshot::Request waits and the frames are not copyable, + * make the swap chain again with copyable images. A frame with no request costs one + * atomic load here. + */ + void PrepareScreenshots(); + + /** True while the frames are copyable for a request only, not for the run (RenderSurfaceDesc::CopyableFrames). + */ + bool m_CopyableForRequest = false; }; } // namespace Fling diff --git a/FlingEngine/Graphics/src/SwapChain.cpp b/FlingEngine/Graphics/src/SwapChain.cpp index 6b1d6a09..2cd831e1 100644 --- a/FlingEngine/Graphics/src/SwapChain.cpp +++ b/FlingEngine/Graphics/src/SwapChain.cpp @@ -34,8 +34,14 @@ namespace Fling LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, VkSurfaceKHR t_Surface, - const bool t_VSync) - : m_VSync(t_VSync), m_Extents{t_Extent}, m_Device(t_Dev), m_PhysicalDevice(t_PhysDev), m_Surface(t_Surface) + const bool t_VSync, + const bool t_Copyable) + : m_VSync(t_VSync), + m_Extents{t_Extent}, + m_Device(t_Dev), + m_PhysicalDevice(t_PhysDev), + m_Surface(t_Surface), + m_WantCopy(t_Copyable) { assert(m_Device && m_PhysicalDevice && m_Surface); Recreate(m_Extents); @@ -44,14 +50,16 @@ namespace Fling Swapchain::Swapchain(const VkExtent2D& t_Extent, LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, - const uint32 t_ImageCount) + const uint32 t_ImageCount, + const bool t_Copyable) : m_VSync(false), m_Extents{t_Extent}, m_Device(t_Dev), m_PhysicalDevice(t_PhysDev), m_Surface(VK_NULL_HANDLE), m_Offscreen(true), - m_OffscreenImageCount(t_ImageCount) + m_OffscreenImageCount(t_ImageCount), + m_WantCopy(t_Copyable) { assert(m_Device && m_PhysicalDevice && m_OffscreenImageCount > 0); // Nothing is presented, so nothing waits for a display @@ -160,7 +168,15 @@ namespace Fling m_Extents.height, static_cast(m_ImageFormat)); - m_CanCopyImages = true; + // Copyable only when a capture needs it: the usage can cost on every frame (it can turn + // off framebuffer compression on some GPUs) + m_CopySupported = true; + m_CanCopyImages = m_WantCopy; + VkImageUsageFlags Usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + if (m_CanCopyImages) + { + Usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + } m_Images.resize(m_OffscreenImageCount); m_ImageMemory.resize(m_OffscreenImageCount); for (uint32 i = 0; i < m_OffscreenImageCount; ++i) @@ -170,7 +186,7 @@ namespace Fling m_Extents.height, m_ImageFormat, VK_IMAGE_TILING_OPTIMAL, - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, + Usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, m_Images[i], m_ImageMemory[i]); @@ -213,8 +229,11 @@ namespace Fling CreateInfo.imageExtent = m_Extents; CreateInfo.imageArrayLayers = 1; CreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - // A capture (--screenshot) copies from the image before it is presented - m_CanCopyImages = (SwapChainSupport.Capabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) != 0; + // A capture (Screenshot::Request) copies from the image before it is presented. Only + // while one needs it (SetCopyable): the usage can cost on every frame, for example by + // turning off framebuffer compression on some GPUs + m_CopySupported = (SwapChainSupport.Capabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) != 0; + m_CanCopyImages = m_WantCopy && m_CopySupported; if (m_CanCopyImages) { CreateInfo.imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; diff --git a/FlingEngine/Graphics/src/SwapChain.h b/FlingEngine/Graphics/src/SwapChain.h index e568b7da..c94b8597 100644 --- a/FlingEngine/Graphics/src/SwapChain.h +++ b/FlingEngine/Graphics/src/SwapChain.h @@ -27,7 +27,7 @@ namespace Fling public: /** t_VSync: SetVSync. */ - Swapchain(const VkExtent2D& t_Extent, LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, VkSurfaceKHR t_Surface, bool t_VSync); + Swapchain(const VkExtent2D& t_Extent, LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, VkSurfaceKHR t_Surface, bool t_VSync, bool t_Copyable = false); /** * An offscreen swap chain (--offscreen): t_ImageCount images that it makes and owns, with @@ -35,7 +35,7 @@ namespace Fling * nothing; both still signal and wait on the semaphores, so VulkanApp::Update runs the * same way with or without a window. */ - Swapchain(const VkExtent2D& t_Extent, LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, uint32 t_ImageCount); + Swapchain(const VkExtent2D& t_Extent, LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, uint32 t_ImageCount, bool t_Copyable = false); ~Swapchain(); @@ -63,17 +63,32 @@ namespace Fling bool IsOffscreen() const { return m_Offscreen; } /** - * The layout of an image after the frame's render pass: PRESENT_SRC with a surface, - * TRANSFER_SRC offscreen (nothing presents it; a capture copies from it). + * The layout of an image after the frame's render pass: PRESENT_SRC with a surface. + * Offscreen nothing presents it: TRANSFER_SRC when a capture copies from it, else + * COLOR_ATTACHMENT (TRANSFER_SRC needs the copy usage, which costs; see SetCopyable). */ VkImageLayout GetFinalLayout() const { - return m_Offscreen ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + if (!m_Offscreen) + { + return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + } + return m_CanCopyImages ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; } /** True when the images can be copied from (VK_IMAGE_USAGE_TRANSFER_SRC_BIT), for a capture. */ bool CanCopyImages() const { return m_CanCopyImages; } + /** + * Whether the next Recreate makes images that can be copied from. Off by default: the + * usage can cost on every frame (some GPUs turn off framebuffer compression for it), + * so it is on only while a capture needs it. + */ + void SetCopyable(bool t_Copyable) { m_WantCopy = t_Copyable; } + + /** True when the images could be made copyable (the surface allows it; always offscreen). */ + bool IsCopySupported() const { return m_CopySupported; } + /** The present mode it was made with. */ PresentMode GetPresentMode() const { return m_PresentMode; } @@ -118,6 +133,12 @@ namespace Fling /** @see CanCopyImages */ bool m_CanCopyImages = false; + /** @see SetCopyable */ + bool m_WantCopy = false; + + /** @see IsCopySupported */ + bool m_CopySupported = false; + /** Offscreen CreateResources: make the images and their memory. */ void CreateOffscreenImages(); diff --git a/FlingEngine/Graphics/src/VulkanApp.cpp b/FlingEngine/Graphics/src/VulkanApp.cpp index 7611a22d..2c51d237 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -188,7 +188,11 @@ namespace Fling if (bOffscreen) { const VkExtent2D Extent = {std::max(Width, 1), std::max(Height, 1)}; - m_SwapChain = new Swapchain(Extent, m_LogicalDevice, m_PhysicalDevice, VkConfig::MAX_FRAMES_IN_FLIGHT); + m_SwapChain = new Swapchain(Extent, + m_LogicalDevice, + m_PhysicalDevice, + VkConfig::MAX_FRAMES_IN_FLIGHT, + m_SurfaceDesc.CopyableFrames); } else { @@ -196,7 +200,8 @@ namespace Fling m_LogicalDevice, m_PhysicalDevice, m_State->m_Surface, - m_VSync); + m_VSync, + m_SurfaceDesc.CopyableFrames); } assert(m_SwapChain); @@ -441,8 +446,34 @@ namespace Fling return m_SwapChain ? m_SwapChain->GetExtents().height : 0; } + void VulkanApp::PrepareScreenshots() + { + // The common case, every frame: nobody asked + if (!Screenshot::HasPending() || m_SwapChain->CanCopyImages() || !m_SwapChain->IsCopySupported()) + { + return; + } + // Copyable images for this frame only; SaveScreenshots turns it off again after it + F_LOG_TRACE("Screenshot requested: making the frames copyable"); + m_CopyableForRequest = true; + m_SwapChain->SetCopyable(true); + RecreateSwapchain(); + } + void VulkanApp::SaveScreenshots() { + // The common case, every frame: nobody asked, so no lock + if (!Screenshot::HasPending()) + { + return; + } + // A request that came in during this frame, from another thread: the next frame makes + // the images copyable and serves it + if (!m_SwapChain->CanCopyImages() && m_SwapChain->IsCopySupported()) + { + return; + } + std::vector Requests = Screenshot::TakePending(); if (Requests.empty()) { @@ -483,17 +514,23 @@ namespace Fling } Screenshot::Finish(Request, Result); } + + // Copyable for a request only: back to the cheaper images after this frame's present, + // unless another request is waiting + if (m_CopyableForRequest && !Screenshot::HasPending()) + { + m_CopyableForRequest = false; + m_SwapChain->SetCopyable(false); + bSwapchainOutOfDate = true; + } } void VulkanApp::RecreateSwapchain() { - // Offscreen images never go out of date: there is no window to resize - if (m_CurrentWindow == nullptr) - { - return; - } F_LOG_TRACE("Making the swap chain again"); - if (!m_CurrentWindow->WaitForNewWindowSize()) + // Offscreen images keep their size (there is no window); they are made again only to + // change whether they can be copied (Screenshot::Request) + if (m_CurrentWindow != nullptr && !m_CurrentWindow->WaitForNewWindowSize()) { // The window was closed while minimized. ShouldTick sees the close next. return; @@ -502,7 +539,9 @@ namespace Fling CleanupSwapChainResources(); - m_SwapChain->Recreate(ChooseSwapExtent(m_CurrentWindow, m_PhysicalDevice, m_State->m_Surface)); + m_SwapChain->Recreate(m_CurrentWindow != nullptr + ? ChooseSwapExtent(m_CurrentWindow, m_PhysicalDevice, m_State->m_Surface) + : m_SwapChain->GetExtents()); BuildSwapChainResources(); @@ -666,6 +705,9 @@ namespace Fling m_Camera->SetLookRotation(View->Yaw, View->Pitch); } + // A screenshot was asked for: copyable images for this frame (nothing when none was) + PrepareScreenshots(); + // Aquire the active image index VkResult iResult = m_SwapChain->AquireNextImage(m_State->m_PresentCompleteSemaphores[CurrentFrameIndex]); uint32 ImageIndex = m_SwapChain->GetActiveImageIndex(); diff --git a/FlingTests/Core/ScreenshotTests.cpp b/FlingTests/Core/ScreenshotTests.cpp index 2df68e3f..e4aa32c1 100644 --- a/FlingTests/Core/ScreenshotTests.cpp +++ b/FlingTests/Core/ScreenshotTests.cpp @@ -27,6 +27,23 @@ TEST_CASE("Screenshot requests wait for the renderer, in order", "[Screenshot]") REQUIRE(Screenshot::TakePending().empty()); } +TEST_CASE("Screenshot::HasPending is the free check the renderer makes every frame", "[Screenshot]") +{ + Screenshot::FailPending("test start"); + REQUIRE_FALSE(Screenshot::HasPending()); + // With nothing waiting, TakePending returns at once (no lock, nothing allocated) + REQUIRE(Screenshot::TakePending().empty()); + + Screenshot::Request("Saved/pending.png"); + REQUIRE(Screenshot::HasPending()); + REQUIRE(Screenshot::TakePending().size() == 1); + REQUIRE_FALSE(Screenshot::HasPending()); + + Screenshot::Request("Saved/failed.png"); + Screenshot::FailPending("no renderer"); + REQUIRE_FALSE(Screenshot::HasPending()); +} + TEST_CASE("Screenshot with no path gets a new file under Saved/Screenshots", "[Screenshot]") { Screenshot::FailPending("test start"); @@ -106,4 +123,5 @@ TEST_CASE("Screenshot requests from many threads all arrive", "[Screenshot]") Each.join(); } REQUIRE(Screenshot::TakePending().size() == ThreadCount * PerThread); + REQUIRE_FALSE(Screenshot::HasPending()); } diff --git a/Skills/testing.md b/Skills/testing.md index 186b522e..6e7306e4 100644 --- a/Skills/testing.md +++ b/Skills/testing.md @@ -253,6 +253,16 @@ reason; a request still waiting when the run ends fails too. `--screenshot` uses Use it for tools, tests and debugging, not to feed results back into the simulation: the callback arrives on the main thread, out of step with the ticks. +Cost: nothing when nobody asks. The renderer checks `Screenshot::HasPending()` each frame +(one atomic load, no lock). The frames are made copyable (`VK_IMAGE_USAGE_TRANSFER_SRC_BIT`, +which can turn off framebuffer compression on some GPUs) only while a capture needs it: + +- a run with `--screenshot`: from the start (`RenderSurfaceDesc::CopyableFrames`), so it + never makes the swap chain again; +- any other run: a request makes the swap chain again with copyable images for its frame, + saves it, and makes it again without them after that frame's present. That is a short + hitch (the GPU waits to be idle twice) on the frame of the screenshot only. + ## Unattended crash tests `FlingTests/CMakeLists.txt` adds `Unattended crash: ` tests. Each runs From 3f3cbc80f6c32556962e58051b90d81e3a0564f7 Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Mon, 16 Nov 2026 13:40:31 +0000 Subject: [PATCH 4/6] Frame-side frustum culling in the offscreen (G-buffer) pass The renderer now skips the draw call and uniform buffer write of each mesh whose world box is outside this frame's camera view. The test runs in OffscreenSubpass after the camera is final, against exactly the projection and view the shader uses (Vulkan clip volume, depth 0..1, y flip), with the item's drawn (blended) world matrix and the model's local AABB, which Model now computes at load. Conservative: a mesh is culled only when its world box is strictly outside one plane; unknown bounds are never culled. The publish path, TickPacket and RenderSnapshot are unchanged: the snapshot still holds every mesh, so a culled mesh keeps its proxy slot and GPU resources. A change in the visible set re-records the cached command buffers. - Frustum and Aabb (Graphics/inc/Frustum.h): plane extraction and box test - MeshCuller (Graphics/inc/MeshCuller.h): per-slot visibility and stats, no GPU data, so it is tested without a device - --frustum-culling on|off, [Engine] FrustumCulling (default on), RunControls, and a GPU Options checkbox with drawn/culled counts - GraphicsTests "[culling]": planes against the clip test, boxes inside, outside each plane, straddling, behind, turned camera, turned and scaled boxes, a randomized never-cull-a-visible-box check, and the snapshot to proxy to culler path Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 9 +- Config/EngineConf.ini | 7 +- Docs/agent-guide.md | 1 + Docs/architecture-overview.md | 4 +- Docs/threading-model.md | 15 + Docs/time-and-ticks.md | 1 + FlingEngine/Application/src/Engine.cpp | 2 + FlingEngine/Core/inc/LaunchOptions.h | 6 + FlingEngine/Core/inc/RunSettings.h | 17 +- FlingEngine/Core/src/LaunchOptions.cpp | 4 +- FlingEngine/Core/src/RunSettings.cpp | 13 +- FlingEngine/Editor/inc/BaseEditor.h | 3 +- FlingEngine/Editor/src/BaseEditor.cpp | 9 + FlingEngine/Engine/inc/RunControls.h | 10 +- FlingEngine/Engine/src/RunControls.cpp | 10 + FlingEngine/Graphics/inc/Frustum.h | 63 +++ FlingEngine/Graphics/inc/MeshCuller.h | 79 ++++ FlingEngine/Graphics/inc/VulkanApp.h | 19 + FlingEngine/Graphics/src/Frustum.cpp | 90 +++++ FlingEngine/Graphics/src/MeshCuller.cpp | 61 +++ FlingEngine/Graphics/src/Model.cpp | 13 + FlingEngine/Graphics/src/Model.h | 10 + FlingEngine/Graphics/src/OffscreenSubpass.cpp | 27 +- FlingEngine/Graphics/src/OffscreenSubpass.h | 28 +- FlingEngine/Graphics/src/VulkanApp.cpp | 17 + FlingTests/Core/RunSettingsTests.cpp | 52 ++- FlingTests/Engine/RunControlsTests.cpp | 5 + FlingTests/Graphics/FrustumCullingTests.cpp | 380 ++++++++++++++++++ .../Resources/RunSettingsConfigTests.cpp | 4 +- 29 files changed, 932 insertions(+), 27 deletions(-) create mode 100644 FlingEngine/Graphics/inc/Frustum.h create mode 100644 FlingEngine/Graphics/inc/MeshCuller.h create mode 100644 FlingEngine/Graphics/src/Frustum.cpp create mode 100644 FlingEngine/Graphics/src/MeshCuller.cpp create mode 100644 FlingTests/Graphics/FrustumCullingTests.cpp diff --git a/AGENTS.md b/AGENTS.md index 88c10f0f..6d371f9c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,13 +45,14 @@ platform setup (Vulkan SDK, GLFW, etc.). - Play runs threaded (a game thread for the ticks) at a fixed 30 Hz, with the 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) and `--interpolation on|off` (on by - default) override, as do `[Engine] Exec`, `SimHz`, `MaxFps`, `VSync` and - `Interpolation` in + `--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 `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 - the rate, the cap, VSync and interpolation at run time. + the rate, the cap, VSync, interpolation and frustum culling at run time. Detail: [`Docs/time-and-ticks.md`](Docs/time-and-ticks.md) section 2. - See a run without a window: `--dump-state ` writes the simulation state as JSON at chosen ticks (works with `--null-render`), and `--offscreen diff --git a/Config/EngineConf.ini b/Config/EngineConf.ini index 5827f3a7..3f8badcb 100644 --- a/Config/EngineConf.ini +++ b/Config/EngineConf.ini @@ -25,13 +25,18 @@ DisplayVersionInfoInTitle=true ; Interpolation ; on (default): the renderer draws between the latest two ticks; off: the ; latest tick only. Presentation only. Flag: --interpolation +; FrustumCulling +; on (default): the renderer skips the meshes outside the camera's view; +; off: it draws every mesh. Presentation only. Flag: --frustum-culling ; Every key here is checked in every run, also when a flag overrides it. The editor's -; GPU Options window changes SimHz, MaxFps, VSync and Interpolation at run time. +; GPU Options window changes SimHz, MaxFps, VSync, Interpolation and FrustumCulling at +; run time. ;Exec=threaded ;SimHz=30 ;MaxFps= ;VSync=on ;Interpolation=on +;FrustumCulling=on ; resizes window to a small window [Windowed] diff --git a/Docs/agent-guide.md b/Docs/agent-guide.md index beec0e06..5d8105b2 100644 --- a/Docs/agent-guide.md +++ b/Docs/agent-guide.md @@ -768,6 +768,7 @@ flag or key. The startup line `Run settings: ...` names each value and its sourc | Frame cap | `--max-fps N` (0: none, max 1000) | `MaxFps` | monitor refresh rate, else 60 (`FallbackMaxFps`); none with `--null-render` | GPU Options | | 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 | | 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 efa98477..2250baf3 100644 --- a/Docs/architecture-overview.md +++ b/Docs/architecture-overview.md @@ -385,8 +385,8 @@ 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`; or the same keys in `[Engine]` of `Config/EngineConf.ini` (`Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation`) | -| 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, with what the frame limiter does and the measured rates. Press M first if the cursor is hidden | +| 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`) | +| 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/threading-model.md b/Docs/threading-model.md index ca9bd748..0191d3aa 100644 --- a/Docs/threading-model.md +++ b/Docs/threading-model.md @@ -210,6 +210,21 @@ lighting test: 42 224 bytes). The frame side copies nothing: it indexes the new tick of each packet it takes. The render snapshot does a blend and a matrix per moving entity, and only a compare per entity that did not move. +**Frustum culling** is on the frame side only, in the renderer, after the +snapshot: the packet and the snapshot still hold every mesh. The offscreen +(G-buffer) pass tests each mesh's world box (the model's local bounds, placed +by the item's drawn matrix) against the planes of this frame's camera +(`Frustum`, `MeshCuller` in `FlingEngine/Graphics/inc/`), and skips the draw +call and the uniform buffer write of a mesh that is outside. A culled mesh +keeps its proxy slot and GPU resources, so it costs nothing to bring back. +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 +the meshes drawn and culled in the last frame. Tests: `GraphicsTests +"[culling]"` (`FrustumCullingTests.cpp`). + **Tests.** `EngineTests "[interp]"` (`EcsBlendTests.cpp`: each packet carries the latest two ticks of the marked types only; new, destroyed, changed and reused entities; after skipped packets `BlendFrom` is still the tick before diff --git a/Docs/time-and-ticks.md b/Docs/time-and-ticks.md index bf3e63b1..88a80c48 100644 --- a/Docs/time-and-ticks.md +++ b/Docs/time-and-ticks.md @@ -74,6 +74,7 @@ outside `--exec threaded` is an error. | Frame cap | `--max-fps N` (0: none, up to 1000) | `MaxFps` | the refresh rate of the window's monitor, else 60; none with `--null-render` | GPU Options, from the next frame | | 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 | | 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 2947227a..1152de3b 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -385,6 +385,7 @@ namespace Fling Pipelines |= PipelineFlags::IMGUI; } VulkanApp::Get().SetVSync(m_Settings.VSync); + VulkanApp::Get().SetFrustumCulling(m_Settings.FrustumCulling); VulkanApp::Get().Init(static_cast(Pipelines), Storage, m_DebugUI); F_LOG_TRACE("Render size: {}x{}", VulkanApp::Get().GetFrameWidth(), VulkanApp::Get().GetFrameHeight()); } @@ -701,6 +702,7 @@ namespace Fling // During Inline or Threaded play the renderer reads the mirror. A VSync change makes // the swap chain again after this frame's present. VulkanApp::Get().SetVSync(m_Controls->VSync()); + VulkanApp::Get().SetFrustumCulling(m_Controls->FrustumCulling()); 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 b285c7f2..378500ad 100644 --- a/FlingEngine/Core/inc/LaunchOptions.h +++ b/FlingEngine/Core/inc/LaunchOptions.h @@ -75,6 +75,9 @@ namespace Fling * --interpolation on|off * Draw between the latest two published ticks (on) or the latest tick * only. Overrides [Engine] Interpolation + * --frustum-culling on|off + * Skip the meshes outside the camera's view (on) or draw every mesh + * (off). Overrides [Engine] FrustumCulling * --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 */ @@ -154,6 +157,9 @@ namespace Fling /** --interpolation on or off. Empty: not on the command line. */ std::optional Interpolation; + /** --frustum-culling on or off. Empty: not on the command line. */ + std::optional FrustumCulling; + /** --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 dc4a1ccb..26aaf186 100644 --- a/FlingEngine/Core/inc/RunSettings.h +++ b/FlingEngine/Core/inc/RunSettings.h @@ -44,12 +44,14 @@ namespace Fling static constexpr const char* MaxFpsKey = "MaxFps"; static constexpr const char* VSyncKey = "VSync"; static constexpr const char* InterpolationKey = "Interpolation"; + static constexpr const char* FrustumCullingKey = "FrustumCulling"; String Exec; String SimHz; String MaxFps; String VSync; String Interpolation; + String FrustumCulling; /** * Each key's text from t_GetKey, which returns the text of one [Engine] key, or empty @@ -62,7 +64,8 @@ namespace Fling .SimHz = t_GetKey(SimHzKey), .MaxFps = t_GetKey(MaxFpsKey), .VSync = t_GetKey(VSyncKey), - .Interpolation = t_GetKey(InterpolationKey)}; + .Interpolation = t_GetKey(InterpolationKey), + .FrustumCulling = t_GetKey(FrustumCullingKey)}; } }; @@ -79,9 +82,10 @@ namespace Fling * | MaxFps | [Engine] MaxFps | --max-fps | monitor refresh, else 60; none headless. 0: no cap | * | VSync | [Engine] VSync | --vsync | on | * | Interpolation | [Engine] Interpolation | --interpolation | on | + * | FrustumCulling | [Engine] FrustumCulling | --frustum-culling | on | * * The values here do not change after startup. The GPU Options window changes VSync, the - * frame cap, the simulation rate and interpolation while the game runs; RunControls holds + * 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. */ @@ -117,6 +121,13 @@ namespace Fling bool Interpolation = true; SettingSource InterpolationSource = SettingSource::Default; + /** + * The renderer does not draw a mesh whose bounds are outside the camera's view this + * frame (MeshCuller in Graphics). Presentation only: the simulation never reads it. + */ + bool FrustumCulling = true; + SettingSource FrustumCullingSource = SettingSource::Default; + /** The refresh rate of the window's monitor at startup (ResolveFrameCap). Empty when not known, and headless. */ std::optional MonitorHz; @@ -164,7 +175,7 @@ namespace Fling /** * One line for the startup log with each value and where it came from, for example * "tick rate 30 Hz (default), exec threaded (default), frame cap 144 fps (the monitor's refresh rate), - * vsync on (default), interpolation on (default)". + * vsync on (default), interpolation on (default), frustum culling on (default)". */ CORE_API String Describe() const; }; diff --git a/FlingEngine/Core/src/LaunchOptions.cpp b/FlingEngine/Core/src/LaunchOptions.cpp index f4dd412f..f0517fe1 100644 --- a/FlingEngine/Core/src/LaunchOptions.cpp +++ b/FlingEngine/Core/src/LaunchOptions.cpp @@ -37,6 +37,7 @@ namespace Fling constexpr StringView MaxFpsFlag = "max-fps"; constexpr StringView VSyncFlag = "vsync"; constexpr StringView InterpolationFlag = "interpolation"; + constexpr StringView FrustumCullingFlag = "frustum-culling"; constexpr StringView ThreadJitterFlag = "thread-jitter"; /** * Flags that are refused with the name of the flag that does their job, so a script @@ -392,7 +393,8 @@ namespace Fling if (!ReadOptionalUint32(t_CmdLine, SimHzFlag, t_Out.SimHz, t_OutError) || !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, InterpolationFlag, t_Out.Interpolation, t_OutError) || + !ReadOptionalOnOff(t_CmdLine, FrustumCullingFlag, t_Out.FrustumCulling, t_OutError)) { return false; } diff --git a/FlingEngine/Core/src/RunSettings.cpp b/FlingEngine/Core/src/RunSettings.cpp index d20f11a2..d55c5132 100644 --- a/FlingEngine/Core/src/RunSettings.cpp +++ b/FlingEngine/Core/src/RunSettings.cpp @@ -190,6 +190,12 @@ namespace Fling Keys::InterpolationKey, t_Out.Interpolation, t_Out.InterpolationSource, + t_OutError) || + !PickOnOff(t_Options.FrustumCulling, + t_Config.FrustumCulling, + Keys::FrustumCullingKey, + t_Out.FrustumCulling, + t_Out.FrustumCullingSource, t_OutError)) { return false; @@ -206,6 +212,10 @@ namespace Fling t_Out.Ignored.push_back(String("--vsync does nothing with ") + t_Out.HeadlessFlag + ": there is no swap chain"); } + if (t_Options.NullRender && t_Options.FrustumCulling) + { + t_Out.Ignored.push_back("--frustum-culling does nothing with --null-render: nothing is drawn"); + } return true; } @@ -253,7 +263,8 @@ namespace Fling return "tick rate " + std::to_string(SimHz) + " Hz (" + SettingSourceName(SimHzSource) + "), exec " + ExecModeName(Exec) + " (" + SettingSourceName(ExecSource) + "), frame cap " + Cap + " (" + CapSource + "), vsync " + OnOffName(VSync) + " (" + SettingSourceName(VSyncSource) + "), interpolation " + - OnOffName(Interpolation) + " (" + SettingSourceName(InterpolationSource) + ")"; + OnOffName(Interpolation) + " (" + SettingSourceName(InterpolationSource) + "), frustum culling " + + OnOffName(FrustumCulling) + " (" + SettingSourceName(FrustumCullingSource) + ")"; } uint32 LimiterFps(const uint32 t_MaxFps, diff --git a/FlingEngine/Editor/inc/BaseEditor.h b/FlingEngine/Editor/inc/BaseEditor.h index 510dac2e..fccaa642 100644 --- a/FlingEngine/Editor/inc/BaseEditor.h +++ b/FlingEngine/Editor/inc/BaseEditor.h @@ -86,7 +86,8 @@ namespace Fling /** * The GPU Options window: the device, VSync (with the present mode in use), the frame - * cap, the simulation rate and render interpolation, with what the frame limiter does + * cap, the simulation rate, render interpolation and frustum culling (with the meshes + * drawn and culled), with what the frame limiter does * and the measured rates, and a button that saves the next frame as a PNG * (Screenshot::Request). Each control * calls RunControls, which checks the request; a number box applies when its edit is diff --git a/FlingEngine/Editor/src/BaseEditor.cpp b/FlingEngine/Editor/src/BaseEditor.cpp index 83f92cc8..d965dd78 100644 --- a/FlingEngine/Editor/src/BaseEditor.cpp +++ b/FlingEngine/Editor/src/BaseEditor.cpp @@ -449,6 +449,15 @@ namespace Fling Controls.SetInterpolation(bInterpolation); } + bool bFrustumCulling = Controls.FrustumCulling(); + if (ImGui::Checkbox("Frustum culling", &bFrustumCulling)) + { + m_ControlsError.clear(); + Controls.SetFrustumCulling(bFrustumCulling); + } + const CullStats Culled = VulkanApp::Get().GetCullStats(); + ImGui::TextDisabled("Last frame: %u meshes drawn, %u outside the view", Culled.Drawn, Culled.Culled); + if (!m_ControlsError.empty()) { ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", m_ControlsError.c_str()); diff --git a/FlingEngine/Engine/inc/RunControls.h b/FlingEngine/Engine/inc/RunControls.h index 8bd86039..e3c655ec 100644 --- a/FlingEngine/Engine/inc/RunControls.h +++ b/FlingEngine/Engine/inc/RunControls.h @@ -34,8 +34,8 @@ namespace Fling /** * The live values of the run settings that change while the game runs: the ones a person - * sets in the editor's GPU Options window (VSync, the frame cap, the simulation rate and - * render interpolation), and the ones the window system reports (the monitor's refresh + * sets in the editor's GPU Options window (VSync, the frame cap, the simulation rate, + * render interpolation and frustum culling), and the ones the window system reports (the monitor's refresh * rate, and whether the window is in the background). They start from the RunSettings * that the engine resolved at startup, which do not change. Each setter checks its * request, so the window only draws and calls them. @@ -44,6 +44,7 @@ namespace Fling * on the resize path, after the next present. * - 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. * - SimHz: World::RequestSimHz, a SetRate clock command applied between two ticks, at the * next wake. The world holds the rate. * @@ -79,6 +80,10 @@ namespace Fling bool Interpolation() const; void SetInterpolation(bool t_On); + /** Frustum culling in the renderer (RunSettings::FrustumCulling). */ + bool FrustumCulling() const { return m_FrustumCulling; } + void SetFrustumCulling(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 @@ -134,6 +139,7 @@ namespace Fling uint32 m_InputTickRate = 0; bool m_VSync = true; + bool m_FrustumCulling = 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 78933000..56749634 100644 --- a/FlingEngine/Engine/src/RunControls.cpp +++ b/FlingEngine/Engine/src/RunControls.cpp @@ -31,6 +31,7 @@ namespace Fling : m_World(t_World), m_InputTickRate(t_Startup.SimHz), m_VSync(t_Startup.VSync), + m_FrustumCulling(t_Startup.FrustumCulling), m_MaxFps(t_Startup.MaxFps), m_MaxFpsFollowsMonitor(t_Startup.MaxFpsSource == SettingSource::Monitor), m_MonitorHz(t_Startup.MonitorHz) @@ -46,6 +47,15 @@ namespace Fling } } + void RunControls::SetFrustumCulling(const bool t_On) + { + if (t_On != m_FrustumCulling) + { + m_FrustumCulling = t_On; + F_LOG_TRACE("Frustum culling {}", t_On ? "on" : "off"); + } + } + bool RunControls::SetMaxFps(const uint32 t_Fps, String& t_OutError) { t_OutError.clear(); diff --git a/FlingEngine/Graphics/inc/Frustum.h b/FlingEngine/Graphics/inc/Frustum.h new file mode 100644 index 00000000..e67b460d --- /dev/null +++ b/FlingEngine/Graphics/inc/Frustum.h @@ -0,0 +1,63 @@ +#pragma once + +#include "FlingMath.h" +#include "FlingTypes.h" +#include "GraphicsAPI.h" + +#include + +namespace Fling +{ + /** An axis-aligned box in a mesh's own space. A box with Min above Max on any axis is empty (not known). */ + struct Aabb + { + glm::vec3 Min{1.0f}; + glm::vec3 Max{-1.0f}; + + /** False for an empty box: nothing was added, so the bounds are not known. */ + bool IsValid() const { return Min.x <= Max.x && Min.y <= Max.y && Min.z <= Max.z; } + + /** The box around every point. Empty when there are none. */ + GRAPHICS_API static Aabb Of(std::span t_Points); + }; + + /** + * The six planes of a camera's view volume, in world space, for culling. Each plane is + * (n, d) with n pointing in: a point p is on the inside of the plane when dot(n, p) + d >= 0. + * + * The planes are those of the clip volume that Vulkan keeps: -w <= x <= w, -w <= y <= w and + * 0 <= z <= w. A y flip in the projection (Vulkan's y points down) only swaps the top and + * bottom planes, so the set is the same with or without it. + */ + struct Frustum + { + enum Side : uint32 + { + Left = 0, + Right, + Bottom, + Top, + Near, + Far, + Count + }; + + glm::vec4 Planes[Side::Count] = {}; + + /** + * The planes of t_ViewProjection (projection * view), the matrix that takes a world + * position to clip space. Each plane is normalized, so its distance is in world units. + */ + GRAPHICS_API static Frustum FromViewProjection(const glm::mat4& t_ViewProjection); + + /** + * True if any part of the box t_Local, placed in the world by t_World, can be inside the + * view volume. Conservative: it can say true for a box that is just outside a corner of + * the volume, never false for a box that is inside. An empty box is always visible. + */ + GRAPHICS_API bool Intersects(const Aabb& t_Local, const glm::mat4& t_World) const; + + /** True if any part of the world space box with centre t_Centre and half size t_Extents can be inside. */ + GRAPHICS_API bool IntersectsWorldBox(const glm::vec3& t_Centre, const glm::vec3& t_Extents) const; + }; +} // namespace Fling diff --git a/FlingEngine/Graphics/inc/MeshCuller.h b/FlingEngine/Graphics/inc/MeshCuller.h new file mode 100644 index 00000000..465454d7 --- /dev/null +++ b/FlingEngine/Graphics/inc/MeshCuller.h @@ -0,0 +1,79 @@ +#pragma once + +#include "FlingTypes.h" +#include "Frustum.h" +#include "GraphicsAPI.h" +#include "RenderSnapshot.h" + +#include +#include + +namespace Fling +{ + /** What the last MeshCuller::Cull did, for the GPU Options window. */ + struct CullStats + { + /** Meshes the pass draws this frame. */ + uint32 Drawn = 0; + + /** Meshes the pass would draw, but that are outside the camera's view. */ + uint32 Culled = 0; + }; + + /** + * Frame side frustum culling for one render pass: which of its proxy slots (MeshProxyTable) + * are in the camera's view this frame. It holds no GPU data, so it can be tested without a + * device. The pass gives it each slot's local bounds when the slot's mesh is made, and calls + * Cull once a frame with the snapshot, after MeshProxyTable::Sync. + * + * The test uses the item's World matrix, the one the pass draws with (blended between the + * latest two ticks), and the camera of this frame. A slot whose bounds are not known is + * always visible. A culled mesh keeps its slot and its GPU resources: only its draw call + * and its uniform buffer write are skipped, so a mesh that comes back into view costs + * nothing to bring back. + */ + class MeshCuller + { + public: + /** + * A slot was made or changed. t_Drawn: the pass draws this slot's mesh at all (its + * material belongs to the pass). t_LocalBounds: the mesh's bounds in its own space. + */ + GRAPHICS_API void SetSlot(uint32 t_Slot, bool t_Drawn, const Aabb& t_LocalBounds); + + /** A slot was freed. */ + GRAPHICS_API void ClearSlot(uint32 t_Slot); + + /** Free every slot. */ + GRAPHICS_API void Clear(); + + /** + * Find the visible slots of this frame. + * + * @param t_Items The snapshot's meshes + * @param t_ItemSlots The slot of each item (MeshProxyTable::SyncResult::ItemSlots) + * @param t_Frustum The camera's view volume. Null: no culling, every drawn slot is visible + * @return True if a slot became visible or hidden, so a recorded draw list is out of date + */ + GRAPHICS_API bool + Cull(std::span t_Items, std::span t_ItemSlots, const Frustum* t_Frustum); + + /** True if the pass draws t_Slot this frame: it is drawn and in view, or culling is off. */ + bool IsVisible(const uint32 t_Slot) const { return t_Slot < m_Slots.size() && m_Slots[t_Slot].Visible; } + + const CullStats& Stats() const { return m_Stats; } + + private: + struct SlotState + { + Aabb LocalBounds; + bool Drawn = false; + bool Visible = false; + }; + + SlotState& At(uint32 t_Slot); + + std::vector m_Slots; + CullStats m_Stats; + }; +} // namespace Fling diff --git a/FlingEngine/Graphics/inc/VulkanApp.h b/FlingEngine/Graphics/inc/VulkanApp.h index 57724f0c..cae855ed 100644 --- a/FlingEngine/Graphics/inc/VulkanApp.h +++ b/FlingEngine/Graphics/inc/VulkanApp.h @@ -2,6 +2,7 @@ #include "Ecs/EntityStorage.h" #include "FlingTypes.h" +#include "MeshCuller.h" #include "PresentMode.h" #include "Singleton.hpp" #include "Strings/String.h" @@ -58,6 +59,7 @@ namespace Fling class FirstPersonCamera; class DepthBuffer; class IDebugUI; + class OffscreenSubpass; /** * Core rendering functionality of the Fling Engine. Controls what Render pipelines @@ -125,6 +127,17 @@ namespace Fling /** The present mode of the swap chain. */ PresentMode GetPresentMode() const; + /** + * Frustum culling on or off (RunSettings::FrustumCulling). On: the meshes outside the + * camera's view this frame are not drawn (MeshCuller). Before Init or after, from the + * next frame. + */ + void SetFrustumCulling(bool t_On); + bool GetFrustumCulling() const { return m_FrustumCulling; } + + /** The meshes the last frame drew and culled. Zero before the first frame and under --null-render. */ + CullStats GetCullStats() const; + /** What to draw to: a window or offscreen images, and the size. Call it before Init. */ void SetRenderSurface(const RenderSurfaceDesc& t_Desc) { m_SurfaceDesc = t_Desc; } @@ -198,6 +211,12 @@ namespace Fling /** @see SetVSync */ bool m_VSync = true; + /** @see SetFrustumCulling */ + bool m_FrustumCulling = true; + + /** The pass that draws the meshes, which culls them. Owned by m_RenderPipelines. */ + OffscreenSubpass* m_MeshPass = nullptr; + /** Keep a vector of command buffers that we want to use so that we can have one for each active frame */ std::vector m_DrawCmdBuffers; diff --git a/FlingEngine/Graphics/src/Frustum.cpp b/FlingEngine/Graphics/src/Frustum.cpp new file mode 100644 index 00000000..1b34ad18 --- /dev/null +++ b/FlingEngine/Graphics/src/Frustum.cpp @@ -0,0 +1,90 @@ +#include "Frustum.h" + +namespace Fling +{ + namespace + { + /** Row t_Row of a glm matrix (glm is column major: m[column][row]). */ + glm::vec4 Row(const glm::mat4& t_M, const int t_Row) + { + return glm::vec4(t_M[0][t_Row], t_M[1][t_Row], t_M[2][t_Row], t_M[3][t_Row]); + } + + glm::vec4 Normalized(const glm::vec4& t_Plane) + { + const float Length = glm::length(glm::vec3(t_Plane)); + return Length > 0.0f ? t_Plane / Length : t_Plane; + } + } // namespace + + Aabb Aabb::Of(const std::span t_Points) + { + Aabb Box; + if (t_Points.empty()) + { + return Box; + } + Box.Min = t_Points[0]; + Box.Max = t_Points[0]; + for (const glm::vec3& Point : t_Points) + { + Box.Min = glm::min(Box.Min, Point); + Box.Max = glm::max(Box.Max, Point); + } + return Box; + } + + Frustum Frustum::FromViewProjection(const glm::mat4& t_ViewProjection) + { + // A world point p is in the volume when its clip coordinates (row i . p) keep + // -w <= x <= w, -w <= y <= w and 0 <= z <= w (Gribb and Hartmann, with Vulkan's depth) + const glm::vec4 X = Row(t_ViewProjection, 0); + const glm::vec4 Y = Row(t_ViewProjection, 1); + const glm::vec4 Z = Row(t_ViewProjection, 2); + const glm::vec4 W = Row(t_ViewProjection, 3); + + Frustum Out; + Out.Planes[Left] = Normalized(W + X); + Out.Planes[Right] = Normalized(W - X); + Out.Planes[Bottom] = Normalized(W + Y); + Out.Planes[Top] = Normalized(W - Y); + Out.Planes[Near] = Normalized(Z); + Out.Planes[Far] = Normalized(W - Z); + return Out; + } + + bool Frustum::IntersectsWorldBox(const glm::vec3& t_Centre, const glm::vec3& t_Extents) const + { + for (const glm::vec4& Plane : Planes) + { + const glm::vec3 Normal(Plane); + // How far the box reaches toward the inside of the plane, from its centre + const float Reach = glm::dot(glm::abs(Normal), t_Extents); + // Strictly outside only: a box that touches the plane stays, and a NaN never culls + if (glm::dot(Normal, t_Centre) + Plane.w + Reach < 0.0f) + { + return false; + } + } + return true; + } + + bool Frustum::Intersects(const Aabb& t_Local, const glm::mat4& t_World) const + { + if (!t_Local.IsValid()) + { + return true; + } + // The world box around the placed local box: its centre moves with the matrix, and each + // world half size is the sum of the absolute linear parts (exact for an affine matrix) + const glm::vec3 LocalCentre = (t_Local.Min + t_Local.Max) * 0.5f; + const glm::vec3 LocalExtents = (t_Local.Max - t_Local.Min) * 0.5f; + const glm::vec3 Centre = glm::vec3(t_World * glm::vec4(LocalCentre, 1.0f)); + glm::vec3 Extents(0.0f); + for (int Axis = 0; Axis < 3; ++Axis) + { + Extents += glm::abs(glm::vec3(t_World[Axis])) * LocalExtents[Axis]; + } + return IntersectsWorldBox(Centre, Extents); + } +} // namespace Fling diff --git a/FlingEngine/Graphics/src/MeshCuller.cpp b/FlingEngine/Graphics/src/MeshCuller.cpp new file mode 100644 index 00000000..cc9bb11b --- /dev/null +++ b/FlingEngine/Graphics/src/MeshCuller.cpp @@ -0,0 +1,61 @@ +#include "MeshCuller.h" + +namespace Fling +{ + MeshCuller::SlotState& MeshCuller::At(const uint32 t_Slot) + { + if (t_Slot >= m_Slots.size()) + { + m_Slots.resize(size_t{t_Slot} + 1); + } + return m_Slots[t_Slot]; + } + + void MeshCuller::SetSlot(const uint32 t_Slot, const bool t_Drawn, const Aabb& t_LocalBounds) + { + SlotState& Slot = At(t_Slot); + Slot.LocalBounds = t_LocalBounds; + Slot.Drawn = t_Drawn; + // Not visible until the next Cull decides, so a new mesh counts as a change there + Slot.Visible = false; + } + + void MeshCuller::ClearSlot(const uint32 t_Slot) + { + if (t_Slot < m_Slots.size()) + { + m_Slots[t_Slot] = SlotState{}; + } + } + + void MeshCuller::Clear() + { + m_Slots.clear(); + m_Stats = {}; + } + + bool MeshCuller::Cull(const std::span t_Items, + const std::span t_ItemSlots, + const Frustum* t_Frustum) + { + bool bChanged = false; + m_Stats = {}; + for (size_t i = 0; i < t_Items.size() && i < t_ItemSlots.size(); ++i) + { + if (t_ItemSlots[i] >= m_Slots.size()) + { + continue; + } + SlotState& Slot = m_Slots[t_ItemSlots[i]]; + if (!Slot.Drawn) + { + continue; + } + const bool bVisible = t_Frustum == nullptr || t_Frustum->Intersects(Slot.LocalBounds, t_Items[i].World); + bChanged |= bVisible != Slot.Visible; + Slot.Visible = bVisible; + ++(bVisible ? m_Stats.Drawn : m_Stats.Culled); + } + return bChanged; + } +} // namespace Fling diff --git a/FlingEngine/Graphics/src/Model.cpp b/FlingEngine/Graphics/src/Model.cpp index d1fa49cc..044ef4e8 100644 --- a/FlingEngine/Graphics/src/Model.cpp +++ b/FlingEngine/Graphics/src/Model.cpp @@ -92,6 +92,7 @@ namespace Fling static_cast(m_Verts.size()), m_Indices.data(), static_cast(m_Indices.size())); + CalculateLocalBounds(); CreateBuffers(); } @@ -149,9 +150,21 @@ namespace Fling m_Indices.data(), static_cast(m_Indices.size())); + CalculateLocalBounds(); CreateBuffers(); } + void Model::CalculateLocalBounds() + { + std::vector Positions; + Positions.reserve(m_Verts.size()); + for (const Vertex& Vert : m_Verts) + { + Positions.push_back(Vert.Pos); + } + m_LocalBounds = Aabb::Of(Positions); + } + void Model::CreateBuffers() { // Under --null-render there is no GPU device. Keep the CPU vertex and index data only. diff --git a/FlingEngine/Graphics/src/Model.h b/FlingEngine/Graphics/src/Model.h index 5af900fa..053c0833 100644 --- a/FlingEngine/Graphics/src/Model.h +++ b/FlingEngine/Graphics/src/Model.h @@ -1,6 +1,7 @@ #pragma once #include "Buffer.h" +#include "Frustum.h" #include "Resource.h" #include "Vertex.h" @@ -46,14 +47,23 @@ namespace Fling constexpr static VkIndexType GetIndexType() { return VK_INDEX_TYPE_UINT32; } + /** The box around every vertex, in the model's own space. Empty when the model has no vertices. */ + FORCEINLINE const Aabb& GetLocalBounds() const { return m_LocalBounds; } + private: void CreateBuffers(); + /** Set m_LocalBounds from m_Verts */ + void CalculateLocalBounds(); + static void CalculateVertexTangents(Vertex* verts, uint32 numVerts, uint32* indices, uint32 numIndices); std::vector m_Verts; std::vector m_Indices; + /** @see GetLocalBounds */ + Aabb m_LocalBounds; + Buffer* m_VertexBuffer = nullptr; Buffer* m_IndexBuffer = nullptr; diff --git a/FlingEngine/Graphics/src/OffscreenSubpass.cpp b/FlingEngine/Graphics/src/OffscreenSubpass.cpp index d38a52c3..2e9d4b86 100644 --- a/FlingEngine/Graphics/src/OffscreenSubpass.cpp +++ b/FlingEngine/Graphics/src/OffscreenSubpass.cpp @@ -109,6 +109,10 @@ namespace Fling CameraUBO.View = m_Camera->GetViewMatrix(); memcpy(m_CameraUboBuffer->m_MappedMem, &CameraUBO, sizeof(CameraUBO)); + // The view volume of exactly the matrices the shader uses this frame + m_CameraViewProjection = CameraUBO.Projection * CameraUBO.View; + CullMeshes(t_Snapshot); + UpdateMeshUniformBuffers(t_Snapshot); // The command buffer holds only draw calls and descriptor bindings, not @@ -130,6 +134,7 @@ namespace Fling for (const uint32 Slot : Result.Removed) { RetireGpuMesh(m_GpuMeshes[Slot]); + m_Culler.ClearSlot(Slot); } auto Prepare = [&](const uint32 Slot) @@ -137,6 +142,7 @@ namespace Fling GpuMesh& Mesh = m_GpuMeshes[Slot]; const bool bHasAssets = ResolveMeshAssets(m_Proxies.At(Slot), Mesh); Mesh.Drawn = bHasAssets && Mesh.MeshMaterial->GetType() == Material::Type::Default; + m_Culler.SetSlot(Slot, Mesh.Drawn, Mesh.Drawn ? Mesh.MeshModel->GetLocalBounds() : Aabb{}); if (!Mesh.Drawn) { // Another pass draws it (a debug material), or there is no model @@ -186,13 +192,24 @@ namespace Fling t_Mesh = GpuMesh{}; } + void OffscreenSubpass::CullMeshes(const RenderSnapshot& t_Snapshot) + { + const Frustum View = Frustum::FromViewProjection(m_CameraViewProjection); + if (m_Culler.Cull(t_Snapshot.Meshes, m_ItemSlots, m_FrustumCulling ? &View : nullptr)) + { + InvalidateCommandBuffers(); + } + } + void OffscreenSubpass::UpdateMeshUniformBuffers(const RenderSnapshot& t_Snapshot) { for (size_t i = 0; i < t_Snapshot.Meshes.size() && i < m_ItemSlots.size(); ++i) { const MeshDrawItem& Item = t_Snapshot.Meshes[i]; - GpuMesh& Mesh = m_GpuMeshes[m_ItemSlots[i]]; - if (!Mesh.Drawn || Mesh.Ubo == nullptr) + const uint32 Slot = m_ItemSlots[i]; + GpuMesh& Mesh = m_GpuMeshes[Slot]; + // A culled mesh keeps its last upload; its version shows that it is old when it is back in view + if (!Mesh.Drawn || Mesh.Ubo == nullptr || !m_Culler.IsVisible(Slot)) { continue; } @@ -234,9 +251,10 @@ namespace Fling VkDeviceSize offsets[1] = {0}; - for (const GpuMesh& Mesh : m_GpuMeshes) + for (uint32 Slot = 0; Slot < m_GpuMeshes.size(); ++Slot) { - if (!Mesh.Drawn || Mesh.MeshModel == nullptr || Mesh.Set == VK_NULL_HANDLE) + const GpuMesh& Mesh = m_GpuMeshes[Slot]; + if (!Mesh.Drawn || Mesh.MeshModel == nullptr || Mesh.Set == VK_NULL_HANDLE || !m_Culler.IsVisible(Slot)) { continue; } @@ -438,6 +456,7 @@ namespace Fling RetireGpuMesh(Mesh); } m_GpuMeshes.clear(); + m_Culler.Clear(); m_Proxies.Clear(); m_ItemSlots.clear(); ReleaseRetiredMeshResources(); diff --git a/FlingEngine/Graphics/src/OffscreenSubpass.h b/FlingEngine/Graphics/src/OffscreenSubpass.h index 805eb086..fef2e268 100644 --- a/FlingEngine/Graphics/src/OffscreenSubpass.h +++ b/FlingEngine/Graphics/src/OffscreenSubpass.h @@ -2,6 +2,7 @@ #include "FlingMath.h" #include "GpuMesh.h" +#include "MeshCuller.h" #include "MeshProxyTable.h" #include "Subpass.h" @@ -70,6 +71,16 @@ namespace Fling virtual void OnSwapchainResized() override final; + /** + * Frustum culling on or off (RunSettings::FrustumCulling). On: a mesh whose bounds are + * outside the camera's view is not drawn and its uniform buffer is not written. Takes + * effect on the next Draw. + */ + void SetFrustumCulling(const bool t_On) { m_FrustumCulling = t_On; } + + /** What the last Draw drew and culled. */ + const CullStats& GetCullStats() const { return m_Culler.Stats(); } + private: /** * Match the proxies to the snapshot: release the resources of meshes that are @@ -88,7 +99,13 @@ namespace Fling /** Write the UBO of each mesh whose world matrix changed since its last upload */ void UpdateMeshUniformBuffers(const RenderSnapshot& t_Snapshot); - /** Record the draw calls for every drawn proxy into the given command buffer */ + /** + * Find the meshes in the camera's view (m_Culler), from this frame's camera and the + * snapshot's world matrices. The command buffers record again when the set changes. + */ + void CullMeshes(const RenderSnapshot& t_Snapshot); + + /** Record the draw calls for every visible proxy into the given command buffer */ void BuildOffscreenCommandBuffer(CommandBuffer& t_CmdBuf); /** Make each offscreen command buffer record again on its next use */ @@ -112,6 +129,9 @@ namespace Fling /** Camera UBO that every mesh descriptor set points to */ Buffer* m_CameraUboBuffer = nullptr; + /** Projection * view of this frame's camera UBO, for culling */ + glm::mat4 m_CameraViewProjection{1.0f}; + /** * Goes up by one each time the draw list changes. A command buffer records * again only when its recorded version is different from this value. @@ -130,6 +150,12 @@ namespace Fling /** The proxy slot of each snapshot mesh, from the last SyncProxies */ std::vector m_ItemSlots; + /** Which slots are in the camera's view, indexed by slot like m_GpuMeshes */ + MeshCuller m_Culler; + + /** @see SetFrustumCulling */ + bool m_FrustumCulling = true; + /** * 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 2c51d237..c43dbb45 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -417,6 +417,20 @@ namespace Fling bSwapchainOutOfDate = true; } + void VulkanApp::SetFrustumCulling(const bool t_On) + { + m_FrustumCulling = t_On; + if (m_MeshPass != nullptr) + { + m_MeshPass->SetFrustumCulling(t_On); + } + } + + CullStats VulkanApp::GetCullStats() const + { + return m_MeshPass != nullptr ? m_MeshPass->GetCullStats() : CullStats{}; + } + void VulkanApp::SetVSync(const bool t_VSync) { if (t_VSync == m_VSync) @@ -596,6 +610,8 @@ namespace Fling // These shaders do not have any vertex input and do the final processing to the screen OffscreenSubpass* Offscreen = static_cast(Subpasses[0].get()); assert(Offscreen); + Offscreen->SetFrustumCulling(m_FrustumCulling); + m_MeshPass = Offscreen; FrameBuffer* OffscreenBuf = Offscreen->GetOffscreenFrameBuffer(); assert(OffscreenBuf); @@ -895,6 +911,7 @@ namespace Fling m_LogicalDevice->WaitForIdle(); // Cleanup render pipelines (created in BuildRenderPipelines) ----------------- + m_MeshPass = nullptr; for (RenderPipeline* pipeline : m_RenderPipelines) { if (pipeline) diff --git a/FlingTests/Core/RunSettingsTests.cpp b/FlingTests/Core/RunSettingsTests.cpp index ee2f5faa..5540403a 100644 --- a/FlingTests/Core/RunSettingsTests.cpp +++ b/FlingTests/Core/RunSettingsTests.cpp @@ -37,6 +37,8 @@ TEST_CASE("Run settings: the defaults are threaded play at 30 Hz with VSync and REQUIRE(Settings.VSyncSource == SettingSource::Default); REQUIRE(Settings.Interpolation); REQUIRE(Settings.InterpolationSource == SettingSource::Default); + REQUIRE(Settings.FrustumCulling); + REQUIRE(Settings.FrustumCullingSource == SettingSource::Default); REQUIRE(Settings.Ignored.empty()); REQUIRE(SimRate::StepNs(Settings.SimHz) == 33'333'333); REQUIRE(SimRate::StepNs(60) == 16'666'667); @@ -110,8 +112,12 @@ TEST_CASE("Run settings: the command line wins over the config file, which wins { RunSettings Settings; String Error; - const RunSettingsConfig Config{ - .Exec = "direct", .SimHz = "60", .MaxFps = "120", .VSync = "off", .Interpolation = "off"}; + const RunSettingsConfig Config{.Exec = "direct", + .SimHz = "60", + .MaxFps = "120", + .VSync = "off", + .Interpolation = "off", + .FrustumCulling = "off"}; REQUIRE(Resolve({}, Config, Settings, Error)); REQUIRE(Settings.Exec == ExecMode::Direct); @@ -124,20 +130,35 @@ TEST_CASE("Run settings: the command line wins over the config file, which wins REQUIRE(Settings.VSyncSource == SettingSource::Config); REQUIRE_FALSE(Settings.Interpolation); REQUIRE(Settings.InterpolationSource == SettingSource::Config); + REQUIRE_FALSE(Settings.FrustumCulling); + REQUIRE(Settings.FrustumCullingSource == SettingSource::Config); - REQUIRE(Resolve({"--exec", "inline", "--sim-hz", "20", "--max-fps", "75", "--vsync", "on", "--interpolation", "on"}, + REQUIRE(Resolve({"--exec", + "inline", + "--sim-hz", + "20", + "--max-fps", + "75", + "--vsync", + "on", + "--interpolation", + "on", + "--frustum-culling", + "on"}, Config, Settings, Error)); 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)"); + "(command line), vsync on (command line), interpolation on (command line), " + "frustum 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)"); + "monitor's refresh rate), vsync on (default), interpolation on (default), " + "frustum culling on (default)"); } TEST_CASE("Run settings: every config key is read by its name", "[RunSettings]") @@ -147,6 +168,7 @@ TEST_CASE("Run settings: every config key is read by its name", "[RunSettings]") {"MaxFps", "90"}, {"VSync", "off"}, {"Interpolation", "off"}, + {"FrustumCulling", "off"}, {"PresentMode", "mailbox"}}; const RunSettingsConfig Config = RunSettingsConfig::Read( [&File](const char* t_Key) @@ -159,6 +181,7 @@ TEST_CASE("Run settings: every config key is read by its name", "[RunSettings]") REQUIRE(Config.MaxFps == "90"); REQUIRE(Config.VSync == "off"); REQUIRE(Config.Interpolation == "off"); + REQUIRE(Config.FrustumCulling == "off"); } TEST_CASE("Run settings: a bad value in a config key is an error, also when a flag wins over it", "[RunSettings]") @@ -193,6 +216,9 @@ TEST_CASE("Run settings: a bad value in a config key is an error, also when a fl Fails(Args({"--interpolation", "on"}), {.Interpolation = "1"}, "[Engine] Interpolation in EngineConf.ini must be on or off"); + Fails(Args({"--frustum-culling", "on"}), + {.FrustumCulling = "yes"}, + "[Engine] FrustumCulling in EngineConf.ini must be on or off"); } } @@ -240,6 +266,22 @@ TEST_CASE("Run settings: --vsync with --null-render does nothing, and says so", REQUIRE(Settings.Ignored.empty()); } +TEST_CASE("Run settings: --frustum-culling with --null-render does nothing, and says so; --offscreen draws", + "[RunSettings]") +{ + RunSettings Settings; + String Error; + REQUIRE(Resolve({"--null-render", "--frustum-culling", "off"}, {}, Settings, Error)); + REQUIRE_FALSE(Settings.FrustumCulling); + REQUIRE(Settings.Ignored == + std::vector{"--frustum-culling does nothing with --null-render: nothing is drawn"}); + REQUIRE(Resolve({"--offscreen", "--frustum-culling", "off"}, {}, Settings, Error)); + REQUIRE(Settings.Ignored.empty()); + LaunchOptions Options; + REQUIRE_FALSE(TestArgs::ParseLaunchArgs({"--frustum-culling", "maybe"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--frustum-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 d1d20a63..12ef1af1 100644 --- a/FlingTests/Engine/RunControlsTests.cpp +++ b/FlingTests/Engine/RunControlsTests.cpp @@ -38,9 +38,11 @@ TEST_CASE("Run controls: the live values start from the startup settings, which ThreadedWorldHarness Harness(HarnessOptions{}); RunSettings Settings = OnMonitor(60); Settings.VSync = false; + Settings.FrustumCulling = false; const RunSettings Startup = Settings; RunControls Controls(Settings, Harness.GetWorld()); REQUIRE_FALSE(Controls.VSync()); + REQUIRE_FALSE(Controls.FrustumCulling()); REQUIRE(Controls.MaxFps() == 60); REQUIRE(Controls.MonitorHz() == 60u); @@ -48,10 +50,13 @@ TEST_CASE("Run controls: the live values start from the startup settings, which Controls.SetVSync(true); REQUIRE(Controls.SetMaxFps(90, Error)); Controls.SetInterpolation(false); + Controls.SetFrustumCulling(true); REQUIRE(Controls.VSync()); REQUIRE(Controls.MaxFps() == 90); + REQUIRE(Controls.FrustumCulling()); REQUIRE(Settings.Describe() == Startup.Describe()); REQUIRE_FALSE(Settings.VSync); + REQUIRE_FALSE(Settings.FrustumCulling); } 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/FrustumCullingTests.cpp b/FlingTests/Graphics/FrustumCullingTests.cpp new file mode 100644 index 00000000..799613e2 --- /dev/null +++ b/FlingTests/Graphics/FrustumCullingTests.cpp @@ -0,0 +1,380 @@ +#include "Components/Transform.h" +#include "Ecs/SystemRegistry.h" +#include "Ecs/SystemRunner.h" +#include "FlingMath.h" +#include "Frustum.h" +#include "MeshCuller.h" +#include "MeshProxyTable.h" +#include "MeshRenderer.h" +#include "RenderSnapshot.h" +#include "SimRandom.h" +#include "Systems/PublishSnapshotSystem.h" +#include "Systems/TransformSystem.h" + +#include +#include +#include +#include + +using namespace Fling; + +namespace +{ + /** + * The renderer's matrices for a camera at t_Eye looking at t_Target: a 90 degree + * perspective, aspect 1, near 0.1, far 100, with Vulkan's y flip when t_FlipY (the + * offscreen pass flips it). + */ + glm::mat4 ViewProjection(const glm::vec3& t_Eye, const glm::vec3& t_Target, const bool t_FlipY = true) + { + glm::mat4 Projection = glm::perspective(glm::radians(90.0f), 1.0f, 0.1f, 100.0f); + if (t_FlipY) + { + Projection[1][1] *= -1.0f; + } + const glm::mat4 View = glm::lookAt(t_Eye, t_Target, glm::vec3(0.0f, 1.0f, 0.0f)); + return Projection * View; + } + + /** The default camera of these tests: at the origin, looking down -z. */ + glm::mat4 ForwardCamera(const bool t_FlipY = true) + { + return ViewProjection(glm::vec3(0.0f), glm::vec3(0.0f, 0.0f, -1.0f), t_FlipY); + } + + /** What the GPU keeps: the point's clip coordinates are in -w <= x, y <= w and 0 <= z <= w. */ + bool InClipVolume(const glm::mat4& t_ViewProjection, const glm::vec3& t_Point) + { + const glm::vec4 Clip = t_ViewProjection * glm::vec4(t_Point, 1.0f); + return Clip.w > 0.0f && -Clip.w <= Clip.x && Clip.x <= Clip.w && -Clip.w <= Clip.y && Clip.y <= Clip.w && + 0.0f <= Clip.z && Clip.z <= Clip.w; + } + + bool InsideAllPlanes(const Frustum& t_Frustum, const glm::vec3& t_Point) + { + for (const glm::vec4& Plane : t_Frustum.Planes) + { + if (glm::dot(glm::vec3(Plane), t_Point) + Plane.w < 0.0f) + { + return false; + } + } + return true; + } + + const Aabb UnitCube{glm::vec3(-0.5f), glm::vec3(0.5f)}; + + glm::mat4 At(const glm::vec3& t_Position) + { + return glm::translate(glm::mat4(1.0f), t_Position); + } + + float Uniform(SimRandom& t_Random, const float t_Min, const float t_Max) + { + return t_Random.Range(t_Min, t_Max); + } + + /** A world with only Engine.Transform and Graphics.PublishSnapshot, as the renderer sees it. */ + struct PublishHarness + { + EntityStorage Storage; + SystemRegistry Systems; + std::unique_ptr Runner; + + PublishHarness() + { + Systems.Add(); + Systems.Add(); + ScheduleResult schedule = Systems.BuildSchedule(); + REQUIRE(schedule.ErrorReport() == ""); + SystemRunnerConfig config; + config.OneTickPerFrame = true; + Runner = std::make_unique(Systems, std::move(schedule.Value), Storage, config); + Runner->Create(); + } + + ~PublishHarness() { Runner->Destroy(); } + + const RenderSnapshot& Frame() + { + Runner->RunTick(WorldRole::Play); + Runner->RunFrame(std::chrono::milliseconds(16), WorldRole::Play); + return Storage.Singleton(); + } + + Entity Mesh(const glm::vec3& t_Position) + { + const Entity Made = Storage.Create(); + Storage.Add(Made, Transform{t_Position}); + Storage.Add(Made, MeshRenderer("Models/cube.obj")); + return Made; + } + }; + + /** The renderer's per frame steps on the CPU side: sync the proxies, give new slots their bounds, cull. */ + struct PassHarness + { + MeshProxyTable Proxies; + MeshCuller Culler; + std::vector ItemSlots; + + bool Draw(const RenderSnapshot& t_Snapshot, const Frustum* t_Frustum) + { + MeshProxyTable::SyncResult Result = Proxies.Sync(t_Snapshot.Meshes); + for (const uint32 Slot : Result.Removed) + { + Culler.ClearSlot(Slot); + } + for (const uint32 Slot : Result.Added) + { + Culler.SetSlot(Slot, true, UnitCube); + } + ItemSlots = std::move(Result.ItemSlots); + return Culler.Cull(t_Snapshot.Meshes, ItemSlots, t_Frustum); + } + + bool Visible(const Entity t_Entity) const { return Culler.IsVisible(Proxies.SlotOf(t_Entity.ToBits())); } + }; +} // namespace + +TEST_CASE("Frustum: the planes keep exactly the points of Vulkan's clip volume", "[graphics][culling]") +{ + for (const bool bFlipY : {true, false}) + { + CAPTURE(bFlipY); + const glm::mat4 Matrix = ForwardCamera(bFlipY); + const Frustum View = Frustum::FromViewProjection(Matrix); + + // Each plane is normalized, and the near and far planes face along the view axis + for (const glm::vec4& Plane : View.Planes) + { + REQUIRE(glm::length(glm::vec3(Plane)) == Catch::Approx(1.0f)); + } + REQUIRE(View.Planes[Frustum::Near].z == Catch::Approx(-1.0f)); + REQUIRE(View.Planes[Frustum::Near].w == Catch::Approx(-0.1f)); + REQUIRE(View.Planes[Frustum::Far].z == Catch::Approx(1.0f)); + REQUIRE(View.Planes[Frustum::Far].w == Catch::Approx(100.0f)); + + REQUIRE(InsideAllPlanes(View, glm::vec3(0.0f, 0.0f, -1.0f))); + // Outside each of the six planes in turn + REQUIRE_FALSE(InsideAllPlanes(View, glm::vec3(-2.0f, 0.0f, -1.0f))); + REQUIRE_FALSE(InsideAllPlanes(View, glm::vec3(2.0f, 0.0f, -1.0f))); + REQUIRE_FALSE(InsideAllPlanes(View, glm::vec3(0.0f, -2.0f, -1.0f))); + REQUIRE_FALSE(InsideAllPlanes(View, glm::vec3(0.0f, 2.0f, -1.0f))); + REQUIRE_FALSE(InsideAllPlanes(View, glm::vec3(0.0f, 0.0f, -0.05f))); + REQUIRE_FALSE(InsideAllPlanes(View, glm::vec3(0.0f, 0.0f, -101.0f))); + + // The same answer as the clip test for points all around the camera + SimRandom Random(7, 1); + int Inside = 0; + for (int i = 0; i < 2000; ++i) + { + const glm::vec3 Point( + Uniform(Random, -60.0f, 60.0f), Uniform(Random, -60.0f, 60.0f), Uniform(Random, -120.0f, 10.0f)); + const glm::vec4 Clip = Matrix * glm::vec4(Point, 1.0f); + // Points within a hair of a plane can round either way + const float Margin = 1e-3f * glm::abs(Clip.w); + if (glm::abs(Clip.w - glm::abs(Clip.x)) < Margin || glm::abs(Clip.w - glm::abs(Clip.y)) < Margin || + glm::abs(Clip.z) < Margin || glm::abs(Clip.w - Clip.z) < Margin) + { + continue; + } + CAPTURE(Point.x, Point.y, Point.z); + const bool bInClip = InClipVolume(Matrix, Point); + REQUIRE(InsideAllPlanes(View, Point) == bInClip); + Inside += bInClip ? 1 : 0; + } + // Both answers were tested many times + REQUIRE(Inside > 100); + REQUIRE(Inside < 1900); + } +} + +TEST_CASE("Frustum: boxes inside, outside each plane, straddling, and behind the camera", "[graphics][culling]") +{ + const Frustum View = Frustum::FromViewProjection(ForwardCamera()); + + // At z = -5 the view is 5 wide on each side of the axis + REQUIRE(View.Intersects(UnitCube, At({0.0f, 0.0f, -5.0f}))); + REQUIRE_FALSE(View.Intersects(UnitCube, At({-10.0f, 0.0f, -5.0f}))); + REQUIRE_FALSE(View.Intersects(UnitCube, At({10.0f, 0.0f, -5.0f}))); + REQUIRE_FALSE(View.Intersects(UnitCube, At({0.0f, -10.0f, -5.0f}))); + REQUIRE_FALSE(View.Intersects(UnitCube, At({0.0f, 10.0f, -5.0f}))); + REQUIRE_FALSE(View.Intersects(UnitCube, At({0.0f, 0.0f, -200.0f}))); + + // Behind the camera, also where the clip w is negative + REQUIRE_FALSE(View.Intersects(UnitCube, At({0.0f, 0.0f, 5.0f}))); + REQUIRE_FALSE(View.Intersects(UnitCube, At({3.0f, 3.0f, 5.0f}))); + + // The centre is outside the right plane, but the near left edge is inside + REQUIRE(View.Intersects(UnitCube, At({5.3f, 0.0f, -5.0f}))); + // The centre is past the far plane, but the near face is inside + REQUIRE(View.Intersects(UnitCube, At({0.0f, 0.0f, -100.3f}))); + // Across the near plane, around the camera + REQUIRE(View.Intersects(UnitCube, At({0.0f, 0.0f, 0.0f}))); + // A box much bigger than the view, around the camera + REQUIRE(View.Intersects(Aabb{glm::vec3(-1000.0f), glm::vec3(1000.0f)}, glm::mat4(1.0f))); + + // A box whose bounds are not known is never culled + REQUIRE_FALSE(Aabb{}.IsValid()); + REQUIRE(View.Intersects(Aabb{}, At({0.0f, 0.0f, 50.0f}))); +} + +TEST_CASE("Frustum: the world matrix places, turns and scales the box", "[graphics][culling]") +{ + const Frustum View = Frustum::FromViewProjection(ForwardCamera()); + + // A long thin box whose centre is outside the right plane at z = -5 (x = 7) + const Aabb Rod{glm::vec3(-4.0f, -0.1f, -0.1f), glm::vec3(4.0f, 0.1f, 0.1f)}; + REQUIRE(View.Intersects(Rod, At({7.0f, 0.0f, -5.0f}))); + // Turned to point along y, it no longer reaches across the right plane + const glm::mat4 Turned = glm::rotate(At({7.0f, 0.0f, -5.0f}), glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f)); + REQUIRE_FALSE(View.Intersects(Rod, Turned)); + + // A unit cube at x = 8 is outside; scaled by 6 it reaches back to z = -8, where the view is 8 wide + REQUIRE_FALSE(View.Intersects(UnitCube, At({8.0f, 0.0f, -5.0f}))); + REQUIRE(View.Intersects(UnitCube, glm::scale(At({8.0f, 0.0f, -5.0f}), glm::vec3(6.0f)))); +} + +TEST_CASE("Frustum: a turned camera culls by its own view", "[graphics][culling]") +{ + // At (0, 0, 10), looking along +x + const glm::vec3 Eye(0.0f, 0.0f, 10.0f); + const Frustum View = Frustum::FromViewProjection(ViewProjection(Eye, Eye + glm::vec3(1.0f, 0.0f, 0.0f))); + REQUIRE(View.Intersects(UnitCube, At(Eye + glm::vec3(5.0f, 0.0f, 0.0f)))); + REQUIRE_FALSE(View.Intersects(UnitCube, At(Eye + glm::vec3(-5.0f, 0.0f, 0.0f)))); + REQUIRE_FALSE(View.Intersects(UnitCube, At(Eye + glm::vec3(0.0f, 0.0f, -5.0f)))); + REQUIRE_FALSE(View.Intersects(UnitCube, At(glm::vec3(0.0f)))); + + // Looking down, a little turned: what is under the camera is in view, what is above is not + const Frustum Down = Frustum::FromViewProjection(ViewProjection(Eye, Eye + glm::vec3(0.1f, -1.0f, 0.2f))); + REQUIRE(Down.Intersects(UnitCube, At(Eye + glm::vec3(0.0f, -5.0f, 0.0f)))); + REQUIRE_FALSE(Down.Intersects(UnitCube, At(Eye + glm::vec3(0.0f, 5.0f, 0.0f)))); +} + +TEST_CASE("Frustum: a box with any point in the clip volume is never culled", "[graphics][culling]") +{ + // Random cameras and random turned, scaled boxes. A culled box must have no visible + // point: test its corners, its centre and a grid through it against the clip volume. + SimRandom Random(11, 1); + int Culled = 0; + int Kept = 0; + for (int i = 0; i < 400; ++i) + { + const glm::vec3 Eye(Uniform(Random, -5.0f, 5.0f), Uniform(Random, -5.0f, 5.0f), Uniform(Random, -5.0f, 5.0f)); + const glm::vec3 Look(Uniform(Random, -1.0f, 1.0f), Uniform(Random, -0.9f, 0.9f), Uniform(Random, -1.0f, 1.0f)); + if (glm::length(Look) < 0.1f) + { + continue; + } + const glm::mat4 Matrix = ViewProjection(Eye, Eye + Look); + const Frustum View = Frustum::FromViewProjection(Matrix); + + const glm::vec3 Half(Uniform(Random, 0.1f, 3.0f), Uniform(Random, 0.1f, 3.0f), Uniform(Random, 0.1f, 3.0f)); + const Aabb Box{-Half, Half}; + glm::mat4 World = At( + glm::vec3(Uniform(Random, -30.0f, 30.0f), Uniform(Random, -30.0f, 30.0f), Uniform(Random, -30.0f, 30.0f))); + World = + glm::rotate(World, + Uniform(Random, 0.0f, 6.28f), + glm::normalize(glm::vec3( + Uniform(Random, 0.1f, 1.0f), Uniform(Random, -1.0f, 1.0f), Uniform(Random, -1.0f, 1.0f)))); + World = glm::scale(World, glm::vec3(Uniform(Random, 0.5f, 2.0f))); + + if (View.Intersects(Box, World)) + { + ++Kept; + continue; + } + ++Culled; + constexpr int Steps = 6; + for (int x = 0; x <= Steps; ++x) + { + for (int y = 0; y <= Steps; ++y) + { + for (int z = 0; z <= Steps; ++z) + { + const glm::vec3 Local = Box.Min + (Box.Max - Box.Min) * glm::vec3(x, y, z) / float(Steps); + const glm::vec3 Point = glm::vec3(World * glm::vec4(Local, 1.0f)); + CAPTURE(i, Point.x, Point.y, Point.z); + REQUIRE_FALSE(InClipVolume(Matrix, Point)); + } + } + } + } + REQUIRE(Culled > 50); + REQUIRE(Kept > 20); +} + +TEST_CASE("Frustum culling: the pass draws a straddling mesh and skips an off-screen one", "[graphics][culling]") +{ + PublishHarness World; + const Entity InView = World.Mesh({0.0f, 0.0f, -5.0f}); + const Entity Behind = World.Mesh({0.0f, 0.0f, 5.0f}); + const Entity FarRight = World.Mesh({20.0f, 0.0f, -5.0f}); + // The centre is right of the view at z = -5 (x = 5); the left half is inside + const Entity Straddling = World.Mesh({5.3f, 0.0f, -5.0f}); + + const Frustum View = Frustum::FromViewProjection(ForwardCamera()); + PassHarness Pass; + const RenderSnapshot& Snapshot = World.Frame(); + // Culling is the renderer's: the snapshot still has every mesh, so no proxy is freed + REQUIRE(Snapshot.Meshes.size() == 4); + REQUIRE(Pass.Draw(Snapshot, &View)); + REQUIRE(Pass.Proxies.LiveCount() == 4); + + REQUIRE(Pass.Visible(InView)); + REQUIRE(Pass.Visible(Straddling)); + REQUIRE_FALSE(Pass.Visible(Behind)); + REQUIRE_FALSE(Pass.Visible(FarRight)); + REQUIRE(Pass.Culler.Stats().Drawn == 2); + REQUIRE(Pass.Culler.Stats().Culled == 2); + + // The same frame again changes nothing, so the recorded draw list stays + REQUIRE_FALSE(Pass.Draw(World.Frame(), &View)); + + // The mesh moves into view: a change, and it is drawn + World.Storage.Get(FarRight).Position = glm::vec3(1.0f, 0.0f, -5.0f); + REQUIRE(Pass.Draw(World.Frame(), &View)); + REQUIRE(Pass.Visible(FarRight)); + REQUIRE(Pass.Culler.Stats().Drawn == 3); + + // The camera turns around: what was behind it is in view, the rest is not + const Frustum Back = Frustum::FromViewProjection(ViewProjection(glm::vec3(0.0f), glm::vec3(0.0f, 0.0f, 1.0f))); + REQUIRE(Pass.Draw(World.Frame(), &Back)); + REQUIRE(Pass.Visible(Behind)); + REQUIRE_FALSE(Pass.Visible(InView)); + REQUIRE_FALSE(Pass.Visible(Straddling)); + REQUIRE_FALSE(Pass.Visible(FarRight)); + + // Culling off: every mesh is drawn + REQUIRE(Pass.Draw(World.Frame(), nullptr)); + REQUIRE(Pass.Culler.Stats().Drawn == 4); + REQUIRE(Pass.Culler.Stats().Culled == 0); + + // A destroyed mesh's slot is cleared, and a new mesh in it starts from its own test + World.Storage.Destroy(InView); + REQUIRE_FALSE(Pass.Draw(World.Frame(), nullptr)); + REQUIRE(Pass.Culler.Stats().Drawn == 3); +} + +TEST_CASE("Frustum culling: a slot the pass does not draw is neither drawn nor culled", "[graphics][culling]") +{ + MeshCuller Culler; + std::vector Items(2); + Items[0].World = At({0.0f, 0.0f, -5.0f}); + Items[1].World = At({0.0f, 0.0f, -5.0f}); + const std::vector Slots = {0, 1}; + Culler.SetSlot(0, true, UnitCube); + // Another pass draws slot 1 (a debug material) + Culler.SetSlot(1, false, UnitCube); + + const Frustum View = Frustum::FromViewProjection(ForwardCamera()); + REQUIRE(Culler.Cull(Items, Slots, &View)); + REQUIRE(Culler.IsVisible(0)); + REQUIRE_FALSE(Culler.IsVisible(1)); + REQUIRE(Culler.Stats().Drawn == 1); + REQUIRE(Culler.Stats().Culled == 0); + // A slot it never heard of is not visible + REQUIRE_FALSE(Culler.IsVisible(7)); +} diff --git a/FlingTests/Resources/RunSettingsConfigTests.cpp b/FlingTests/Resources/RunSettingsConfigTests.cpp index af11f077..89e4bfcf 100644 --- a/FlingTests/Resources/RunSettingsConfigTests.cpp +++ b/FlingTests/Resources/RunSettingsConfigTests.cpp @@ -15,7 +15,7 @@ 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\n"; + File << "[Engine]\nExec=inline\nSimHz=60\nMaxFps=90\nVSync=off\nInterpolation=off\nFrustumCulling=off\n"; } REQUIRE(FlingConfig::Get().LoadConfigFile(Path.string())); @@ -26,6 +26,6 @@ TEST_CASE("Run settings: the [Engine] keys of an ini file reach the run 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)"); + "off (config), interpolation off (config), frustum culling off (config)"); std::filesystem::remove(Path); } From 4a3053862c5202c54b07c4c94a4c38e01daa4c66 Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Mon, 16 Nov 2026 14:33:12 +0000 Subject: [PATCH 5/6] Frustum culling: indirect draws, so a moving camera records nothing Review fixes for the frame-side frustum culling: - Each drawable mesh is recorded once as an indirect draw. The CPU writes its instance count (1 in view, 0 culled) every frame, so a change of the visible set no longer makes every offscreen command buffer record again. They record only when the draw list changes, as before culling. - The culler counts a slot as drawable with the same test the recording uses (IsDrawable: drawn, a model and a descriptor set), so the GPU Options count matches the draws. - The renderer keeps one copy of the culling switch, in the mesh pass. VulkanApp passes it on; Engine::Present sets it before every frame. - Model bounds are built point by point (Aabb::Add), with no temporary vector of positions. A NaN never starts the box again. Co-Authored-By: Claude Opus 5.5 --- Docs/threading-model.md | 5 +- FlingEngine/Application/src/Engine.cpp | 1 - FlingEngine/Graphics/inc/Frustum.h | 3 + FlingEngine/Graphics/inc/MeshCuller.h | 2 +- FlingEngine/Graphics/inc/VulkanApp.h | 10 +-- FlingEngine/Graphics/src/Frustum.cpp | 22 +++--- FlingEngine/Graphics/src/Model.cpp | 6 +- FlingEngine/Graphics/src/OffscreenSubpass.cpp | 69 +++++++++++++++++-- FlingEngine/Graphics/src/OffscreenSubpass.h | 37 ++++++++-- FlingEngine/Graphics/src/VulkanApp.cpp | 2 - FlingEngine/Graphics/src/VulkanFunctions.inl | 1 + FlingTests/Graphics/FrustumCullingTests.cpp | 37 ++++++++++ 12 files changed, 162 insertions(+), 33 deletions(-) diff --git a/Docs/threading-model.md b/Docs/threading-model.md index 0191d3aa..d3b730a9 100644 --- a/Docs/threading-model.md +++ b/Docs/threading-model.md @@ -215,8 +215,11 @@ snapshot: the packet and the snapshot still hold every mesh. The offscreen (G-buffer) pass tests each mesh's world box (the model's local bounds, placed by the item's drawn matrix) against the planes of this frame's camera (`Frustum`, `MeshCuller` in `FlingEngine/Graphics/inc/`), and skips the draw -call and the uniform buffer write of a mesh that is outside. A culled mesh +and the uniform buffer write of a mesh that is outside. A culled mesh keeps its proxy slot and GPU resources, so it costs nothing to bring back. +Each mesh is recorded as an indirect draw; the CPU writes its instance count +(1 in view, 0 culled) every frame, so a moving camera never makes the command +buffers record again (they record only when the draw list changes). 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 diff --git a/FlingEngine/Application/src/Engine.cpp b/FlingEngine/Application/src/Engine.cpp index 1152de3b..3e165f53 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -385,7 +385,6 @@ namespace Fling Pipelines |= PipelineFlags::IMGUI; } VulkanApp::Get().SetVSync(m_Settings.VSync); - VulkanApp::Get().SetFrustumCulling(m_Settings.FrustumCulling); VulkanApp::Get().Init(static_cast(Pipelines), Storage, m_DebugUI); F_LOG_TRACE("Render size: {}x{}", VulkanApp::Get().GetFrameWidth(), VulkanApp::Get().GetFrameHeight()); } diff --git a/FlingEngine/Graphics/inc/Frustum.h b/FlingEngine/Graphics/inc/Frustum.h index e67b460d..0eead1f8 100644 --- a/FlingEngine/Graphics/inc/Frustum.h +++ b/FlingEngine/Graphics/inc/Frustum.h @@ -17,6 +17,9 @@ namespace Fling /** False for an empty box: nothing was added, so the bounds are not known. */ bool IsValid() const { return Min.x <= Max.x && Min.y <= Max.y && Min.z <= Max.z; } + /** Grow the box to hold t_Point. Adding to an empty box makes the box of that point alone. */ + GRAPHICS_API void Add(const glm::vec3& t_Point); + /** The box around every point. Empty when there are none. */ GRAPHICS_API static Aabb Of(std::span t_Points); }; diff --git a/FlingEngine/Graphics/inc/MeshCuller.h b/FlingEngine/Graphics/inc/MeshCuller.h index 465454d7..a5d38220 100644 --- a/FlingEngine/Graphics/inc/MeshCuller.h +++ b/FlingEngine/Graphics/inc/MeshCuller.h @@ -53,7 +53,7 @@ namespace Fling * @param t_Items The snapshot's meshes * @param t_ItemSlots The slot of each item (MeshProxyTable::SyncResult::ItemSlots) * @param t_Frustum The camera's view volume. Null: no culling, every drawn slot is visible - * @return True if a slot became visible or hidden, so a recorded draw list is out of date + * @return True if a slot became visible or hidden since the last Cull */ GRAPHICS_API bool Cull(std::span t_Items, std::span t_ItemSlots, const Frustum* t_Frustum); diff --git a/FlingEngine/Graphics/inc/VulkanApp.h b/FlingEngine/Graphics/inc/VulkanApp.h index cae855ed..984a13e0 100644 --- a/FlingEngine/Graphics/inc/VulkanApp.h +++ b/FlingEngine/Graphics/inc/VulkanApp.h @@ -128,12 +128,11 @@ namespace Fling PresentMode GetPresentMode() const; /** - * Frustum culling on or off (RunSettings::FrustumCulling). On: the meshes outside the - * camera's view this frame are not drawn (MeshCuller). Before Init or after, from the - * next frame. + * Frustum culling on or off (RunSettings::FrustumCulling) for the next frame. On: the + * meshes outside the camera's view are not drawn (MeshCuller). The mesh pass holds the + * value, so it does nothing before Init; Engine::Present calls it before every frame. */ void SetFrustumCulling(bool t_On); - bool GetFrustumCulling() const { return m_FrustumCulling; } /** The meshes the last frame drew and culled. Zero before the first frame and under --null-render. */ CullStats GetCullStats() const; @@ -211,9 +210,6 @@ namespace Fling /** @see SetVSync */ bool m_VSync = true; - /** @see SetFrustumCulling */ - bool m_FrustumCulling = true; - /** The pass that draws the meshes, which culls them. Owned by m_RenderPipelines. */ OffscreenSubpass* m_MeshPass = nullptr; diff --git a/FlingEngine/Graphics/src/Frustum.cpp b/FlingEngine/Graphics/src/Frustum.cpp index 1b34ad18..16a20039 100644 --- a/FlingEngine/Graphics/src/Frustum.cpp +++ b/FlingEngine/Graphics/src/Frustum.cpp @@ -17,19 +17,25 @@ namespace Fling } } // namespace - Aabb Aabb::Of(const std::span t_Points) + void Aabb::Add(const glm::vec3& t_Point) { - Aabb Box; - if (t_Points.empty()) + // Only the empty box starts again. A box made invalid by a NaN stays invalid, so it is never culled + if (Min.x > Max.x) { - return Box; + Min = t_Point; + Max = t_Point; + return; } - Box.Min = t_Points[0]; - Box.Max = t_Points[0]; + Min = glm::min(Min, t_Point); + Max = glm::max(Max, t_Point); + } + + Aabb Aabb::Of(const std::span t_Points) + { + Aabb Box; for (const glm::vec3& Point : t_Points) { - Box.Min = glm::min(Box.Min, Point); - Box.Max = glm::max(Box.Max, Point); + Box.Add(Point); } return Box; } diff --git a/FlingEngine/Graphics/src/Model.cpp b/FlingEngine/Graphics/src/Model.cpp index 044ef4e8..7b3ed4d3 100644 --- a/FlingEngine/Graphics/src/Model.cpp +++ b/FlingEngine/Graphics/src/Model.cpp @@ -156,13 +156,11 @@ namespace Fling void Model::CalculateLocalBounds() { - std::vector Positions; - Positions.reserve(m_Verts.size()); + m_LocalBounds = Aabb{}; for (const Vertex& Vert : m_Verts) { - Positions.push_back(Vert.Pos); + m_LocalBounds.Add(Vert.Pos); } - m_LocalBounds = Aabb::Of(Positions); } void Model::CreateBuffers() diff --git a/FlingEngine/Graphics/src/OffscreenSubpass.cpp b/FlingEngine/Graphics/src/OffscreenSubpass.cpp index 2e9d4b86..2988a694 100644 --- a/FlingEngine/Graphics/src/OffscreenSubpass.cpp +++ b/FlingEngine/Graphics/src/OffscreenSubpass.cpp @@ -15,6 +15,8 @@ #include "SwapChain.h" #include "UniformBufferObject.h" +#include + namespace Fling { OffscreenSubpass::OffscreenSubpass(const LogicalDevice* t_Dev, @@ -83,6 +85,9 @@ namespace Fling delete m_CameraUboBuffer; m_CameraUboBuffer = nullptr; + + delete m_DrawCommands; + m_DrawCommands = nullptr; } void OffscreenSubpass::Draw(CommandBuffer& t_CmdBuf, @@ -114,6 +119,7 @@ namespace Fling CullMeshes(t_Snapshot); UpdateMeshUniformBuffers(t_Snapshot); + 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. @@ -142,11 +148,11 @@ namespace Fling GpuMesh& Mesh = m_GpuMeshes[Slot]; const bool bHasAssets = ResolveMeshAssets(m_Proxies.At(Slot), Mesh); Mesh.Drawn = bHasAssets && Mesh.MeshMaterial->GetType() == Material::Type::Default; - m_Culler.SetSlot(Slot, Mesh.Drawn, Mesh.Drawn ? Mesh.MeshModel->GetLocalBounds() : Aabb{}); if (!Mesh.Drawn) { // Another pass draws it (a debug material), or there is no model RetireGpuMesh(Mesh); + m_Culler.SetSlot(Slot, false, Aabb{}); return; } @@ -160,6 +166,8 @@ namespace Fling } CreateMeshDescriptorSet(Mesh); Mesh.UploadedVersion = 0; + // The same test the recording uses, so the culler counts only what gets a draw call + m_Culler.SetSlot(Slot, IsDrawable(Mesh), Mesh.MeshModel->GetLocalBounds()); }; for (const uint32 Slot : Result.Added) @@ -177,6 +185,7 @@ namespace Fling { InvalidateCommandBuffers(); } + EnsureDrawCommandCapacity(); } void OffscreenSubpass::RetireGpuMesh(GpuMesh& t_Mesh) @@ -194,10 +203,54 @@ namespace Fling void OffscreenSubpass::CullMeshes(const RenderSnapshot& t_Snapshot) { + // A change of the visible set needs no new recording: WriteDrawCommands gives each + // recorded indirect draw its instance count (0 or 1) for this frame const Frustum View = Frustum::FromViewProjection(m_CameraViewProjection); - if (m_Culler.Cull(t_Snapshot.Meshes, m_ItemSlots, m_FrustumCulling ? &View : nullptr)) + m_Culler.Cull(t_Snapshot.Meshes, m_ItemSlots, m_FrustumCulling ? &View : nullptr); + } + + void OffscreenSubpass::EnsureDrawCommandCapacity() + { + const size_t Needed = std::max(m_GpuMeshes.size(), 1); + if (m_DrawCommands != nullptr && m_DrawCommandCapacity >= Needed) { - InvalidateCommandBuffers(); + return; + } + // Grow by doubling. The recordings point at the old buffer, so they record again; it + // is deleted with the retired UBOs, once the GPU is done with the frame that used it + size_t Capacity = std::max(m_DrawCommandCapacity, 64); + while (Capacity < Needed) + { + Capacity *= 2; + } + if (m_DrawCommands != nullptr) + { + m_RetiredUniformBuffers.emplace_back(m_DrawCommands); + } + const VkDeviceSize Size = sizeof(VkDrawIndexedIndirectCommand) * Capacity; + m_DrawCommands = new Buffer(Size, + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + m_DrawCommands->MapMemory(Size); + m_DrawCommandCapacity = Capacity; + InvalidateCommandBuffers(); + } + + void OffscreenSubpass::WriteDrawCommands() + { + // One buffer is enough: each frame waits for the GPU to finish before the next frame + // writes it (as with the camera UBO) + auto* Commands = static_cast(m_DrawCommands->m_MappedMem); + for (uint32 Slot = 0; Slot < m_GpuMeshes.size(); ++Slot) + { + const GpuMesh& Mesh = m_GpuMeshes[Slot]; + VkDrawIndexedIndirectCommand& Command = Commands[Slot]; + Command = {}; + if (IsDrawable(Mesh)) + { + Command.indexCount = Mesh.MeshModel->GetIndexCount(); + Command.instanceCount = m_Culler.IsVisible(Slot) ? 1 : 0; + } } } @@ -254,7 +307,9 @@ namespace Fling for (uint32 Slot = 0; Slot < m_GpuMeshes.size(); ++Slot) { const GpuMesh& Mesh = m_GpuMeshes[Slot]; - if (!Mesh.Drawn || Mesh.MeshModel == nullptr || Mesh.Set == VK_NULL_HANDLE || !m_Culler.IsVisible(Slot)) + // Every drawable slot is recorded, in view or not: its indirect command's instance + // count, written each frame, decides whether it draws + if (!IsDrawable(Mesh)) { continue; } @@ -274,7 +329,11 @@ namespace Fling vkCmdBindVertexBuffers(t_CmdBuf.GetHandle(), 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer( t_CmdBuf.GetHandle(), Model->GetIndexBuffer()->GetVkBuffer(), 0, Model->GetIndexType()); - vkCmdDrawIndexed(t_CmdBuf.GetHandle(), Model->GetIndexCount(), 1, 0, 0, 0); + vkCmdDrawIndexedIndirect(t_CmdBuf.GetHandle(), + m_DrawCommands->GetVkBuffer(), + sizeof(VkDrawIndexedIndirectCommand) * Slot, + 1, + sizeof(VkDrawIndexedIndirectCommand)); } t_CmdBuf.EndRenderPass(); diff --git a/FlingEngine/Graphics/src/OffscreenSubpass.h b/FlingEngine/Graphics/src/OffscreenSubpass.h index fef2e268..6156c0b5 100644 --- a/FlingEngine/Graphics/src/OffscreenSubpass.h +++ b/FlingEngine/Graphics/src/OffscreenSubpass.h @@ -74,7 +74,8 @@ namespace Fling /** * Frustum culling on or off (RunSettings::FrustumCulling). On: a mesh whose bounds are * outside the camera's view is not drawn and its uniform buffer is not written. Takes - * effect on the next Draw. + * effect on the next Draw. The pass holds the renderer's only copy: VulkanApp passes the + * value on, and Engine::Present sets it before every frame from RunControls. */ void SetFrustumCulling(const bool t_On) { m_FrustumCulling = t_On; } @@ -101,11 +102,26 @@ namespace Fling /** * Find the meshes in the camera's view (m_Culler), from this frame's camera and the - * snapshot's world matrices. The command buffers record again when the set changes. + * snapshot's world matrices. A change of the visible set does not record again. */ void CullMeshes(const RenderSnapshot& t_Snapshot); - /** Record the draw calls for every visible proxy into the given command buffer */ + /** Make m_DrawCommands hold one command per slot. A new buffer makes the recordings out of date. */ + void EnsureDrawCommandCapacity(); + + /** Write each slot's indirect draw for this frame: its index count, and 1 instance if visible, else 0 */ + void WriteDrawCommands(); + + /** True if the pass records a draw for the mesh: the pass draws it and it has its GPU resources */ + static bool IsDrawable(const GpuMesh& t_Mesh) + { + return t_Mesh.Drawn && t_Mesh.MeshModel != nullptr && t_Mesh.Set != VK_NULL_HANDLE; + } + + /** + * Record an indirect draw for every drawable proxy, visible or not, into the given + * command buffer. The recording changes only with the draw list, not with the camera. + */ void BuildOffscreenCommandBuffer(CommandBuffer& t_CmdBuf); /** Make each offscreen command buffer record again on its next use */ @@ -132,6 +148,16 @@ namespace Fling /** Projection * view of this frame's camera UBO, for culling */ glm::mat4 m_CameraViewProjection{1.0f}; + /** + * One VkDrawIndexedIndirectCommand per proxy slot, which the recorded draws read. The + * CPU writes the instance counts each frame (WriteDrawCommands), so culling a mesh or + * bringing it back needs no new recording. + */ + Buffer* m_DrawCommands = nullptr; + + /** The number of commands m_DrawCommands holds */ + size_t m_DrawCommandCapacity = 0; + /** * Goes up by one each time the draw list changes. A command buffer records * again only when its recorded version is different from this value. @@ -163,7 +189,10 @@ namespace Fling */ std::vector m_RetiredDescriptorSets; - /** UBOs of destroyed meshes. Deleted at the same time as m_RetiredDescriptorSets. */ + /** + * UBOs of destroyed meshes, and draw command buffers that were replaced by a larger one. + * Deleted at the same time as m_RetiredDescriptorSets. + */ std::vector m_RetiredUniformBuffers; }; } // namespace Fling \ No newline at end of file diff --git a/FlingEngine/Graphics/src/VulkanApp.cpp b/FlingEngine/Graphics/src/VulkanApp.cpp index c43dbb45..e1d6fcdc 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -419,7 +419,6 @@ namespace Fling void VulkanApp::SetFrustumCulling(const bool t_On) { - m_FrustumCulling = t_On; if (m_MeshPass != nullptr) { m_MeshPass->SetFrustumCulling(t_On); @@ -610,7 +609,6 @@ namespace Fling // These shaders do not have any vertex input and do the final processing to the screen OffscreenSubpass* Offscreen = static_cast(Subpasses[0].get()); assert(Offscreen); - Offscreen->SetFrustumCulling(m_FrustumCulling); m_MeshPass = Offscreen; FrameBuffer* OffscreenBuf = Offscreen->GetOffscreenFrameBuffer(); assert(OffscreenBuf); diff --git a/FlingEngine/Graphics/src/VulkanFunctions.inl b/FlingEngine/Graphics/src/VulkanFunctions.inl index 05818299..059fa01d 100644 --- a/FlingEngine/Graphics/src/VulkanFunctions.inl +++ b/FlingEngine/Graphics/src/VulkanFunctions.inl @@ -88,6 +88,7 @@ FLING_VK_DEVICE(vkCmdCopyBufferToImage) FLING_VK_DEVICE(vkCmdCopyImageToBuffer) FLING_VK_DEVICE(vkCmdDraw) FLING_VK_DEVICE(vkCmdDrawIndexed) +FLING_VK_DEVICE(vkCmdDrawIndexedIndirect) FLING_VK_DEVICE(vkCmdEndRenderPass) FLING_VK_DEVICE(vkCmdNextSubpass) FLING_VK_DEVICE(vkCmdPipelineBarrier) diff --git a/FlingTests/Graphics/FrustumCullingTests.cpp b/FlingTests/Graphics/FrustumCullingTests.cpp index 799613e2..195499bb 100644 --- a/FlingTests/Graphics/FrustumCullingTests.cpp +++ b/FlingTests/Graphics/FrustumCullingTests.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include @@ -378,3 +379,39 @@ TEST_CASE("Frustum culling: a slot the pass does not draw is neither drawn nor c // A slot it never heard of is not visible REQUIRE_FALSE(Culler.IsVisible(7)); } + +TEST_CASE("Frustum: a box grows point by point, and a NaN point never makes it cullable", "[graphics][culling]") +{ + Aabb Box; + REQUIRE_FALSE(Box.IsValid()); + Box.Add({1.0f, 2.0f, 3.0f}); + REQUIRE(Box.IsValid()); + REQUIRE(Box.Min == glm::vec3(1.0f, 2.0f, 3.0f)); + REQUIRE(Box.Max == glm::vec3(1.0f, 2.0f, 3.0f)); + Box.Add({-1.0f, 5.0f, 0.0f}); + REQUIRE(Box.Min == glm::vec3(-1.0f, 2.0f, 0.0f)); + REQUIRE(Box.Max == glm::vec3(1.0f, 5.0f, 3.0f)); + + // Of is the same as adding each point + const std::vector Points = {{1.0f, 2.0f, 3.0f}, {-1.0f, 5.0f, 0.0f}}; + const Aabb Made = Aabb::Of(Points); + REQUIRE(Made.Min == Box.Min); + REQUIRE(Made.Max == Box.Max); + REQUIRE_FALSE(Aabb::Of({}).IsValid()); + + // A NaN point never lets the box lose a point in view, wherever it comes + const float NaN = std::numeric_limits::quiet_NaN(); + const Frustum View = Frustum::FromViewProjection(ForwardCamera()); + const glm::vec3 InView{0.0f, 0.0f, -5.0f}; + const glm::vec3 FarAway{1000.0f, 0.0f, -5.0f}; + for (const std::vector& Order : std::vector>{ + {glm::vec3(NaN), InView, FarAway}, {InView, glm::vec3(NaN), FarAway}, {InView, FarAway, glm::vec3(NaN)}}) + { + Aabb Mixed; + for (const glm::vec3& Point : Order) + { + Mixed.Add(Point); + } + REQUIRE(View.Intersects(Mixed, glm::mat4(1.0f))); + } +} From 86cd72f22833f58ac25647cca1098b19bbdc0d59 Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Mon, 16 Nov 2026 18:40:48 +0000 Subject: [PATCH 6/6] Vulkan validation: use VK_LAYER_KHRONOS_validation, and run without it when missing [Vulkan] EnableValidationLayers=true asked for VK_LAYER_LUNARG_standard_validation, which the Vulkan SDK replaced with VK_LAYER_KHRONOS_validation in 1.1.106 (2019). No current SDK has it, so vkCreateInstance failed and the engine could not start with validation on. - Ask for VK_LAYER_KHRONOS_validation. - When the layer is not installed, log a warning and turn validation off, instead of asking for it anyway and failing to create the instance. Checked with the layer installed: the debug messenger is set up and the offscreen runs of Level_1 (look camera replay) and PhysicsTest, culling on and off, report no validation errors. Without the layer: the warning, then the run goes on without validation. Co-Authored-By: Claude Opus 5.5 --- FlingEngine/Graphics/src/Instance.cpp | 5 ++++- FlingEngine/Graphics/src/Instance.h | 8 ++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/FlingEngine/Graphics/src/Instance.cpp b/FlingEngine/Graphics/src/Instance.cpp index faf89b56..39841604 100644 --- a/FlingEngine/Graphics/src/Instance.cpp +++ b/FlingEngine/Graphics/src/Instance.cpp @@ -32,7 +32,10 @@ namespace Fling { if (m_EnableValidationLayers && !CheckValidationLayerSupport()) { - F_LOG_WARN("Validation layers are requested, but not available!"); + // Asking for a layer that is not installed makes vkCreateInstance fail, so run without it + F_LOG_WARN("Validation layers are requested, but not available! Install the Vulkan SDK (or the " + "Khronos validation layer package). Running without validation."); + m_EnableValidationLayers = false; } // Basic app data that we can modify diff --git a/FlingEngine/Graphics/src/Instance.h b/FlingEngine/Graphics/src/Instance.h index ae425d87..607c2de2 100644 --- a/FlingEngine/Graphics/src/Instance.h +++ b/FlingEngine/Graphics/src/Instance.h @@ -104,8 +104,12 @@ namespace Fling void SetupDebugMessages(); #endif - /** The validation layers that we want to look for on this instance */ - const std::vector m_ValidationLayers = {"VK_LAYER_LUNARG_standard_validation"}; + /** + * The validation layers that we want to look for on this instance. VK_LAYER_KHRONOS_validation + * is the one validation layer of every Vulkan SDK since 1.1.106 (2019); it replaced + * VK_LAYER_LUNARG_standard_validation, which current SDKs do not have. + */ + const std::vector m_ValidationLayers = {"VK_LAYER_KHRONOS_validation"}; /** The device extensions to enable: VK_KHR_swapchain with a surface, none offscreen */ std::vector m_DeviceExtensions;