From 91b672ede6d71303e26620b79ac6e0908d26d84e Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Sun, 15 Nov 2026 16:00:17 +0000 Subject: [PATCH 1/4] 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/4] 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/4] 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 59bbd8adc22043f612fb3ca3d0c6217be8ea8788 Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Mon, 16 Nov 2026 18:49:16 +0000 Subject: [PATCH 4/4] Screenshots no longer stall the frame A capture is now a copy in the frame's own command buffer plus a writer thread, instead of a queue-idle copy and a PNG encode on the main thread. - FrameCapturer records vkCmdCopyImageToBuffer into the frame after the render pass, into a reused, mapped staging buffer. After the frame's fence the buffer goes to the "Screenshot Writer" thread, which converts, encodes the PNG once and writes it to every requested path. Callbacks run on the main thread on a later frame. The thread and buffers are made on the first capture only. - The swap chain images get TRANSFER_SRC once (when the surface allows it; always offscreen), so a capture never rebuilds the swap chain. - Offscreen frames skip the present semaphores, removing two empty vkQueueSubmit calls per frame. - deferred.frag's llvmpipe workaround runs only on CPU drivers, through a specialization constant, so GPUs keep the plain light loops. - FlingPaths::SaveFile replaces three copies of "make the folders, then write the file". - VulkanApp::FinishScreenshots waits for the writes at the end of a run, so --screenshot still checks every file before it exits. Co-Authored-By: Claude Opus 5.5 --- Assets/Shaders/Deferred/deferred.frag | 24 +- FlingEngine/Application/src/Engine.cpp | 22 +- FlingEngine/Core/inc/FlingPaths.h | 10 + FlingEngine/Core/inc/Screenshot.h | 7 +- FlingEngine/Core/src/FlingPaths.cpp | 33 +- FlingEngine/Core/src/Input/InputRecording.cpp | 28 +- FlingEngine/Graphics/inc/VulkanApp.h | 34 +- FlingEngine/Graphics/src/FrameCapture.cpp | 448 +++++++++++++----- FlingEngine/Graphics/src/FrameCapture.h | 141 +++++- FlingEngine/Graphics/src/GeometrySubpass.cpp | 5 + FlingEngine/Graphics/src/GraphicsPipeline.cpp | 26 +- FlingEngine/Graphics/src/GraphicsPipeline.h | 21 + FlingEngine/Graphics/src/SwapChain.cpp | 59 +-- FlingEngine/Graphics/src/SwapChain.h | 36 +- FlingEngine/Graphics/src/VulkanApp.cpp | 120 ++--- FlingTests/Core/FlingPathsTests.cpp | 56 +++ Skills/testing.md | 31 +- 17 files changed, 701 insertions(+), 400 deletions(-) create mode 100644 FlingTests/Core/FlingPathsTests.cpp diff --git a/Assets/Shaders/Deferred/deferred.frag b/Assets/Shaders/Deferred/deferred.frag index 23d03e01..415d033d 100644 --- a/Assets/Shaders/Deferred/deferred.frag +++ b/Assets/Shaders/Deferred/deferred.frag @@ -12,6 +12,9 @@ layout (binding = 4) uniform sampler2D samplerMetal; layout (binding = 5) uniform sampler2D samplerRoughness; // In UV from the vertex shader +// True on a CPU driver such as llvmpipe (VK_PHYSICAL_DEVICE_TYPE_CPU): see the loop counts in main +layout (constant_id = 0) const bool CPU_DRIVER = false; + layout (location = 0) in vec2 inUV; // Final screen color @@ -60,13 +63,20 @@ 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); + // The loop counts. On a CPU driver only (CPU_DRIVER, set by GeometrySubpass), the min with + // a value only the GPU knows (the G-buffer size, never 0) changes nothing, but keeps the + // 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). A GPU driver removes the branch when it + // specializes the shader, so it pays nothing + uint DirLightCount = lights.DirLightCount; + uint PointLightCount = lights.PointLightCount; + if (CPU_DRIVER) + { + const uint NotInlined = uint(textureSize(samplerposition, 0).x) + 128u; + DirLightCount = min(DirLightCount, NotInlined); + PointLightCount = min(PointLightCount, NotInlined); + } // Ambient part vec3 LightColor = vec3(0.0, 0.0, 0.0); diff --git a/FlingEngine/Application/src/Engine.cpp b/FlingEngine/Application/src/Engine.cpp index 2947227a..eaf7d4e9 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -367,9 +367,6 @@ 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; @@ -637,6 +634,12 @@ namespace Fling m_World->GetTickCount(), AverageFrameMs, AverageFrameMs > 0.0 ? 1000.0 / AverageFrameMs : 0.0); + // The screenshots that frames copied are written on a thread: wait for them, so the checks + // below see every result + if (!m_Options.NullRender) + { + VulkanApp::Get().FinishScreenshots(); + } // 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"); @@ -827,17 +830,10 @@ namespace Fling 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) + String WriteError; + if (!FlingPaths::SaveFile(Path, Dump.Doc.Dump(2) + '\n', WriteError)) { - F_LOG_ERROR("--dump-state: cannot write {}", Path); + F_LOG_ERROR("--dump-state: {}", WriteError); ++m_StateDumpsFailed; continue; } diff --git a/FlingEngine/Core/inc/FlingPaths.h b/FlingEngine/Core/inc/FlingPaths.h index 6e8d63bd..ad275d6e 100644 --- a/FlingEngine/Core/inc/FlingPaths.h +++ b/FlingEngine/Core/inc/FlingPaths.h @@ -76,6 +76,16 @@ namespace Fling */ static void GetCurrentWorkingDir(char* t_OutBuf, size_t t_BufSize); + /** + * Write t_Bytes to a file, replacing it. Missing folders are made. Any thread. + * + * @param t_Path The file (UTF-8) + * @param t_Bytes What to write, as is (binary) + * @param t_OutError Receives why it failed + * @return True when every byte was written + */ + static bool SaveFile(StringView t_Path, StringView t_Bytes, String& t_OutError); + // TODO: Add options to get the current user's home path }; } // namespace Fling \ No newline at end of file diff --git a/FlingEngine/Core/inc/Screenshot.h b/FlingEngine/Core/inc/Screenshot.h index a409ed22..a7d8350b 100644 --- a/FlingEngine/Core/inc/Screenshot.h +++ b/FlingEngine/Core/inc/Screenshot.h @@ -36,9 +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. + * It costs nothing when nobody asks: a frame with no request does one atomic load. A + * request does not stall the frame either: the GPU copies the frame in its own command + * buffer, and a writer thread encodes and writes the PNG. The callback arrives a few + * frames later. * * 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 diff --git a/FlingEngine/Core/src/FlingPaths.cpp b/FlingEngine/Core/src/FlingPaths.cpp index c92711d5..bf04be08 100644 --- a/FlingEngine/Core/src/FlingPaths.cpp +++ b/FlingEngine/Core/src/FlingPaths.cpp @@ -4,6 +4,8 @@ #include #include +#include +#include namespace Fling { @@ -101,4 +103,33 @@ namespace Fling } return PathToUtf8(PathFromUtf8(Root) / Path); } -} // namespace Fling \ No newline at end of file + + bool FlingPaths::SaveFile(const StringView t_Path, const StringView t_Bytes, String& t_OutError) + { + const std::filesystem::path Path = PathFromUtf8(t_Path); + if (Path.has_parent_path()) + { + std::error_code Error; + std::filesystem::create_directories(Path.parent_path(), Error); + if (Error) + { + t_OutError = "cannot make the folder " + PathToUtf8(Path.parent_path()) + ": " + Error.message(); + return false; + } + } + std::ofstream File(Path, std::ios::binary | std::ios::trunc); + if (!File) + { + t_OutError = "cannot open " + String(t_Path) + " to write"; + return false; + } + File.write(t_Bytes.data(), static_cast(t_Bytes.size())); + File.flush(); + if (!File) + { + t_OutError = "cannot write " + String(t_Path); + return false; + } + return true; + } +} // namespace Fling diff --git a/FlingEngine/Core/src/Input/InputRecording.cpp b/FlingEngine/Core/src/Input/InputRecording.cpp index c3da0d8b..db80a462 100644 --- a/FlingEngine/Core/src/Input/InputRecording.cpp +++ b/FlingEngine/Core/src/Input/InputRecording.cpp @@ -1,3 +1,4 @@ +#include "FlingPaths.h" #include "Input/InputRecording.h" #include "Strings/String.h" @@ -1098,32 +1099,7 @@ namespace Fling bool SaveInputRecording(const StringView t_Path, const InputRecording& t_Recording, String& t_OutError) { - namespace fs = std::filesystem; - std::error_code Code; - const fs::path Path = PathFromUtf8(t_Path); - if (Path.has_parent_path()) - { - fs::create_directories(Path.parent_path(), Code); - if (Code) - { - t_OutError = "cannot make folder '" + Path.parent_path().string() + "': " + Code.message(); - return false; - } - } - std::ofstream File(Path, std::ios::binary | std::ios::trunc); - if (!File) - { - t_OutError = "cannot write '" + String(t_Path) + "'"; - return false; - } - File << WriteInputRecording(t_Recording); - File.flush(); - if (!File) - { - t_OutError = "error while writing '" + String(t_Path) + "'"; - return false; - } - return true; + return FlingPaths::SaveFile(t_Path, WriteInputRecording(t_Recording), t_OutError); } String DescribeRecordedMessage(double t_TimeSeconds, StringView t_DeviceName, const InputMessage& t_Message) diff --git a/FlingEngine/Graphics/inc/VulkanApp.h b/FlingEngine/Graphics/inc/VulkanApp.h index 57724f0c..df6de8d1 100644 --- a/FlingEngine/Graphics/inc/VulkanApp.h +++ b/FlingEngine/Graphics/inc/VulkanApp.h @@ -39,13 +39,6 @@ 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; @@ -58,6 +51,7 @@ namespace Fling class FirstPersonCamera; class DepthBuffer; class IDebugUI; + class FrameCapturer; /** * Core rendering functionality of the Fling Engine. Controls what Render pipelines @@ -81,6 +75,13 @@ namespace Fling /** Wait for the GPU, then free the render pipelines, the device, and the window. */ void ShutdownRenderer(); + /** + * Wait for the screenshots that are being written (Screenshot::Request) and call their + * callbacks. A frame copies a screenshot; a writer thread saves it later, so a run that + * counts its screenshots calls this before it ends. Main thread. + */ + void FinishScreenshots(); + /** * Specify default constructible so that we have more explicit * control with Init and Shutdown @@ -217,22 +218,7 @@ namespace Fling /** @see SetRenderSurface */ RenderSurfaceDesc m_SurfaceDesc; - /** - * 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(); - - /** - * 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; + /** Serves Screenshot::Request: the copy in the frame, and the PNG on a writer thread. */ + std::unique_ptr m_Capturer; }; } // namespace Fling diff --git a/FlingEngine/Graphics/src/FrameCapture.cpp b/FlingEngine/Graphics/src/FrameCapture.cpp index 9732c2ce..bebe170b 100644 --- a/FlingEngine/Graphics/src/FrameCapture.cpp +++ b/FlingEngine/Graphics/src/FrameCapture.cpp @@ -1,13 +1,13 @@ +#include "Buffer.h" +#include "FlingPaths.h" #include "FrameCapture.h" -#include "GraphicsHelpers.h" -#include "LogicalDevice.h" -#include "PhyscialDevice.h" -#include "VulkanApp.h" +#include "Logger.h" +#include "SwapChain.h" +#include "Threading/CommandRunnable.h" +#include "Threading/Thread.h" #include -#include -#include -#include +#include #define STB_IMAGE_WRITE_IMPLEMENTATION #define STB_IMAGE_WRITE_STATIC @@ -17,10 +17,10 @@ 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) + /** stbi_write_png_to_func's callback: append to a String. */ + void AppendToString(void* t_Context, void* t_Data, int t_Size) { - static_cast(t_Context)->write(static_cast(t_Data), t_Size); + static_cast(t_Context)->append(static_cast(t_Data), static_cast(t_Size)); } bool IsBgra(const VkFormat t_Format) @@ -36,146 +36,334 @@ namespace Fling namespace FrameCapture { + bool ToRgba(const VkFormat t_Format, uint8* t_Pixels, const size_t t_Size) + { + if (!IsBgra(t_Format) && !IsRgba(t_Format)) + { + return false; + } + const bool bSwap = IsBgra(t_Format); + for (size_t i = 0; i + 3 < t_Size; i += 4) + { + if (bSwap) + { + std::swap(t_Pixels[i], t_Pixels[i + 2]); + } + t_Pixels[i + 3] = 255; + } + return true; + } + + bool EncodePng(const uint32 t_Width, const uint32 t_Height, const uint8* t_Rgba, String& t_OutPng) + { + t_OutPng.clear(); + const int Stride = static_cast(t_Width) * 4; + return stbi_write_png_to_func(&AppendToString, + &t_OutPng, + static_cast(t_Width), + static_cast(t_Height), + 4, + t_Rgba, + Stride) != 0; + } + 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()) + String Png; + if (!EncodePng(t_Width, t_Height, t_Rgba, Png)) { - std::filesystem::create_directories(Path.parent_path(), Error); + t_OutError = "cannot encode the PNG file " + String(t_Path); + return false; } - std::ofstream File(Path, std::ios::binary | std::ios::trunc); - if (!File) + return FlingPaths::SaveFile(t_Path, Png, t_OutError); + } + } // namespace FrameCapture + + FrameCapturer::FrameCapturer() = default; + + FrameCapturer::~FrameCapturer() + { + // VulkanApp calls Release before the device goes; this only stops the thread + Flush(); + } + + FrameCapturer::Slot* FrameCapturer::AcquireSlot(const VkDeviceSize t_Size) + { + for (std::unique_ptr& Each : m_Slots) + { + if (Each->InUse.load(std::memory_order_acquire)) { - t_OutError = "cannot open " + String(t_Path) + " to write"; - return false; + continue; } - 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) + // The frame size changed (a resize): a buffer of the new size + if (Each->Staging == nullptr || Each->Staging->GetSize() != t_Size) { - t_OutError = "cannot write the PNG file " + String(t_Path); - return false; + Each->Staging.reset(); + Each->Mapped = nullptr; } - return true; + return Each.get(); } + if (m_Slots.size() >= MaxSlots) + { + return nullptr; + } + m_Slots.emplace_back(std::make_unique()); + return m_Slots.back().get(); + } - 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) + void FrameCapturer::Fail(std::vector& t_Requests, const StringView t_Error) + { + for (Screenshot::Pending& Request : t_Requests) { - if (!IsBgra(t_Format) && !IsRgba(t_Format)) + ScreenshotResult Result; + Result.Path = Request.Path; + Result.Error = String(t_Error); + Screenshot::Finish(Request, Result); + } + t_Requests.clear(); + } + + void FrameCapturer::RecordCopy(const VkCommandBuffer t_Cmd, const Swapchain& t_SwapChain, const uint32 t_ImageIndex) + { + // The common case, every frame: nobody asked, so no lock + if (!Screenshot::HasPending() && m_Waiting.empty()) + { + return; + } + for (Screenshot::Pending& Request : Screenshot::TakePending()) + { + m_Waiting.push_back(std::move(Request)); + } + if (m_Waiting.empty()) + { + return; + } + + if (!t_SwapChain.CanCopyImages()) + { + Fail(m_Waiting, "the window's surface does not allow copying its images; use --offscreen"); + return; + } + const VkFormat Format = t_SwapChain.GetImageFormat(); + if (!IsBgra(Format) && !IsRgba(Format)) + { + Fail(m_Waiting, + "the frame's format (" + std::to_string(static_cast(Format)) + ") is not 8-bit RGBA or BGRA"); + return; + } + + const VkExtent2D Extent = t_SwapChain.GetExtents(); + const VkDeviceSize Size = static_cast(Extent.width) * Extent.height * 4; + Slot* Target = AcquireSlot(Size); + if (Target == nullptr) + { + // Every staging buffer is with the writer: a later frame serves these requests + return; + } + if (Target->Staging == nullptr) + { + // Host-visible memory that the writer thread reads, kept mapped. Made on the first + // capture of this size only + Target->Staging = + std::make_unique(Size, + VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + const VkResult MapResult = Target->Staging->MapMemory(); + if (MapResult != VK_SUCCESS || Target->Staging->m_MappedMem == nullptr) { - t_OutError = - "the frame's format (" + std::to_string(static_cast(t_Format)) + ") is not 8-bit RGBA or BGRA"; - return false; + Target->Staging.reset(); + Fail(m_Waiting, + "cannot map the screenshot's staging memory (VkResult " + + std::to_string(static_cast(MapResult)) + ")"); + return; } + Target->Mapped = Target->Staging->m_MappedMem; + } - 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); - 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 VkImage Image = t_SwapChain.GetImages()[t_ImageIndex]; + const VkImageLayout Layout = t_SwapChain.GetFinalLayout(); - const bool bSwap = IsBgra(t_Format); - for (size_t i = 0; i < t_OutRgba.size(); i += 4) + VkImageSubresourceRange Range = {}; + Range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + Range.levelCount = 1; + Range.layerCount = 1; + + // After the render pass's writes (and its final layout change), the copy reads the image. + // All commands: only a capture frame pays for the wide wait + 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 = Layout; + ToCopy.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + ToCopy.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + ToCopy.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + ToCopy.image = Image; + ToCopy.subresourceRange = Range; + vkCmdPipelineBarrier(t_Cmd, + VK_PIPELINE_STAGE_ALL_COMMANDS_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 = {Extent.width, Extent.height, 1}; + vkCmdCopyImageToBuffer( + t_Cmd, Image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, Target->Staging->GetVkBuffer(), 1, &Region); + + // Back to the layout the present (or the next frame) expects, 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 = 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 = Target->Staging->GetVkBuffer(); + ToHost.size = VK_WHOLE_SIZE; + vkCmdPipelineBarrier(t_Cmd, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, + 0, + nullptr, + 1, + &ToHost, + Layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ? 0u : 1u, + &Back); + + Target->InUse.store(true, std::memory_order_release); + m_Recorded = std::make_shared(); + m_Recorded->Target = Target; + m_Recorded->Extent = Extent; + m_Recorded->Format = Format; + m_Recorded->Requests = std::move(m_Waiting); + m_Waiting.clear(); + } + + void FrameCapturer::OnFrameDone() + { + if (m_Recorded == nullptr) + { + return; + } + if (m_WriterThread == nullptr) + { + // Made on the first capture: a run that takes none has no writer thread + m_Writer = std::make_shared(); + m_WriterThread = + Thread::Create(m_Writer, {.Name = "Screenshot Writer", .Priority = ThreadPriority::BelowNormal}); + if (m_WriterThread == nullptr) { - if (bSwap) - { - std::swap(t_OutRgba[i], t_OutRgba[i + 2]); - } - t_OutRgba[i + 3] = 255; + // No thread: write here. Slow, but the request is not lost + F_LOG_WARN("Cannot start the screenshot writer thread; writing on the main thread"); + m_Writer.reset(); } - return true; } - } // namespace FrameCapture + std::shared_ptr Capture = std::move(m_Recorded); + m_Recorded.reset(); + if (m_Writer == nullptr) + { + Write(*Capture); + DeliverResults(); + return; + } + m_Writer->Enqueue([this, Capture]() { Write(*Capture); }); + } + + void FrameCapturer::Write(Recorded& t_Capture) + { + Slot& Target = *t_Capture.Target; + const size_t Size = static_cast(t_Capture.Extent.width) * t_Capture.Extent.height * 4; + + // One read of the staging memory (it can be slow to read: uncached), then the slot is + // free for the next capture while this one encodes + std::vector Pixels(Size); + std::memcpy(Pixels.data(), Target.Mapped, Size); + Target.InUse.store(false, std::memory_order_release); + + String Error; + String Png; + bool bEncoded = FrameCapture::ToRgba(t_Capture.Format, Pixels.data(), Pixels.size()); + if (!bEncoded) + { + Error = "the frame's format is not 8-bit RGBA or BGRA"; + } + else if (!FrameCapture::EncodePng(t_Capture.Extent.width, t_Capture.Extent.height, Pixels.data(), Png)) + { + bEncoded = false; + Error = "cannot encode the PNG file"; + } + + // Encoded once, written once for each request + for (Screenshot::Pending& Request : t_Capture.Requests) + { + Finished Done; + Done.Result.Path = Request.Path; + Done.Result.Error = Error; + Done.Result.Ok = bEncoded && FlingPaths::SaveFile(Request.Path, Png, Done.Result.Error); + if (Done.Result.Ok) + { + Done.Result.Width = t_Capture.Extent.width; + Done.Result.Height = t_Capture.Extent.height; + } + Done.Request = std::move(Request); + m_Finished.Push(std::move(Done)); + m_FinishedCount.fetch_add(1, std::memory_order_release); + } + } + + void FrameCapturer::DeliverResults() + { + // The common case, every frame: nothing finished, so no lock + if (m_FinishedCount.load(std::memory_order_acquire) <= 0) + { + return; + } + const uint32 Count = + m_Finished.Drain([](Finished& t_Done) { Screenshot::Finish(t_Done.Request, t_Done.Result); }); + m_FinishedCount.fetch_sub(static_cast(Count), std::memory_order_acq_rel); + } + + void FrameCapturer::Flush() + { + // A copy that was recorded but whose frame never finished: nothing to write + if (m_Recorded != nullptr) + { + m_Recorded->Target->InUse.store(false, std::memory_order_release); + Fail(m_Recorded->Requests, "the frame was not finished"); + m_Recorded.reset(); + } + if (m_WriterThread != nullptr) + { + // Kill runs the writes that are queued, then joins. A later capture starts it again + m_WriterThread->Kill(); + m_WriterThread.reset(); + m_Writer.reset(); + } + DeliverResults(); + } + + void FrameCapturer::Release() + { + Flush(); + Fail(m_Waiting, "the renderer shut down before the next frame was drawn"); + m_Slots.clear(); + } } // namespace Fling diff --git a/FlingEngine/Graphics/src/FrameCapture.h b/FlingEngine/Graphics/src/FrameCapture.h index a15a0a64..01a08744 100644 --- a/FlingEngine/Graphics/src/FrameCapture.h +++ b/FlingEngine/Graphics/src/FrameCapture.h @@ -2,44 +2,137 @@ #include "FlingTypes.h" #include "FlingVulkan.h" +#include "Screenshot.h" #include "Strings/String.h" +#include "Threading/ThreadQueue.h" +#include +#include #include namespace Fling { - class LogicalDevice; + class Buffer; + class CommandRunnable; + class Swapchain; + class Thread; namespace FrameCapture { /** - * 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. - * - * @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_OutRgba Receives the pixels - * @param t_OutError Receives why it failed - * @return False if the format is not supported + * Turn the pixels of a copied frame into RGBA8 in place (4 bytes a pixel, rows top to + * bottom): BGRA formats are swizzled, and alpha is written as opaque (the frame's clear + * alpha is not meant to be seen). False if t_Format is not 8-bit RGBA or BGRA. */ - bool ReadImageRgba(LogicalDevice& t_Device, - VkImage t_Image, - VkFormat t_Format, - VkExtent2D t_Extent, - VkImageLayout t_Layout, - std::vector& t_OutRgba, - String& t_OutError); + bool ToRgba(VkFormat t_Format, uint8* t_Pixels, size_t t_Size); /** - * 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. + * Encode RGBA8 pixels (4 bytes a pixel, rows top to bottom) as PNG bytes. Pure CPU + * work: the tests call it with no GPU. False if the encoder fails. */ + bool EncodePng(uint32 t_Width, uint32 t_Height, const uint8* t_Rgba, String& t_OutPng); + + /** EncodePng, then FlingPaths::SaveFile. */ bool WritePng(StringView t_Path, uint32 t_Width, uint32 t_Height, const uint8* t_Rgba, String& t_OutError); } // namespace FrameCapture + + /** + * Serves Screenshot::Request for VulkanApp without stalling the frame: + * + * 1. RecordCopy (main thread, in the frame): when a request waits, the frame's own command + * buffer copies the finished image into a staging buffer, after the render pass. That + * is GPU work in the same submit; the CPU does not wait for it. + * 2. OnFrameDone (main thread, after the frame's fence): the copy is done, so the staging + * buffer goes to the writer thread. Nothing is copied on the main thread. + * 3. The writer thread converts the pixels, encodes the PNG once, writes each file, and + * frees the staging buffer for the next capture. + * 4. DeliverResults (main thread, next frames): the requests' callbacks. + * + * A frame with no request costs one atomic load in RecordCopy and one in DeliverResults. + * The writer thread and the staging buffers are made on the first capture only. + */ + class FrameCapturer + { + public: + FrameCapturer(); + ~FrameCapturer(); + + FrameCapturer(const FrameCapturer&) = delete; + FrameCapturer& operator=(const FrameCapturer&) = delete; + + /** + * Record the copy of t_SwapChain's image t_ImageIndex into t_Cmd, outside of a render + * pass, after everything that draws to it. Takes the waiting requests. Main thread. + */ + void RecordCopy(VkCommandBuffer t_Cmd, const Swapchain& t_SwapChain, uint32 t_ImageIndex); + + /** The fence of the frame that RecordCopy recorded into has signaled: start the writes. Main thread. */ + void OnFrameDone(); + + /** Call the callbacks of the captures that the writer finished. Main thread. */ + void DeliverResults(); + + /** + * Wait for the writer to finish every capture, then DeliverResults: the end of a run + * (its exit code counts the screenshots), and before the device is destroyed. Main thread. + */ + void Flush(); + + /** Flush, then free the staging buffers. Before the logical device is destroyed. */ + void Release(); + + private: + /** One staging buffer. The writer owns it while InUse. */ + struct Slot + { + std::unique_ptr Staging; + void* Mapped = nullptr; + std::atomic InUse{false}; + }; + + /** A copy that RecordCopy recorded, waiting for its frame's fence. */ + struct Recorded + { + Slot* Target = nullptr; + VkExtent2D Extent = {}; + VkFormat Format = VK_FORMAT_UNDEFINED; + std::vector Requests; + }; + + /** A finished request, for the main thread. */ + struct Finished + { + Screenshot::Pending Request; + ScreenshotResult Result; + }; + + /** A free slot that holds t_Size bytes, or null when all are with the writer and there are MaxSlots. */ + Slot* AcquireSlot(VkDeviceSize t_Size); + + /** The writer thread's work for one capture. */ + void Write(Recorded& t_Capture); + + /** Fail t_Requests with t_Error now (main thread). */ + void Fail(std::vector& t_Requests, StringView t_Error); + + /** At most this many captures in flight; more requests wait for a frame with a free slot. */ + static constexpr size_t MaxSlots = 3; + + std::vector> m_Slots; + + /** Requests taken from Screenshot that wait for a free slot. */ + std::vector m_Waiting; + + /** The copy recorded into this frame, if any. */ + std::shared_ptr m_Recorded; + + std::shared_ptr m_Writer; + std::shared_ptr m_WriterThread; + + /** Writer thread to main thread. */ + ThreadQueue m_Finished; + + /** Items in m_Finished: one atomic load answers "nothing to deliver". */ + std::atomic m_FinishedCount{0}; + }; } // namespace Fling diff --git a/FlingEngine/Graphics/src/GeometrySubpass.cpp b/FlingEngine/Graphics/src/GeometrySubpass.cpp index 7c9e8a92..07864d57 100644 --- a/FlingEngine/Graphics/src/GeometrySubpass.cpp +++ b/FlingEngine/Graphics/src/GeometrySubpass.cpp @@ -237,6 +237,11 @@ namespace Fling m_GraphicsPipeline->m_RasterizationState = Initializers::PipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_FRONT_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE); + // deferred.frag's CPU_DRIVER: its llvmpipe workaround runs on a CPU driver only + const bool bCpuDriver = + VulkanApp::Get().GetPhysicalDevice()->GetDeviceProps().deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU; + m_GraphicsPipeline->SetFragmentConstant(0, bCpuDriver ? 1u : 0u); + // Create it otherwise with defaults m_GraphicsPipeline->CreateGraphicsPipeline(m_GlobalRenderPass, nullptr); } diff --git a/FlingEngine/Graphics/src/GraphicsPipeline.cpp b/FlingEngine/Graphics/src/GraphicsPipeline.cpp index 18a6516c..e9100d93 100644 --- a/FlingEngine/Graphics/src/GraphicsPipeline.cpp +++ b/FlingEngine/Graphics/src/GraphicsPipeline.cpp @@ -102,6 +102,27 @@ namespace Fling { // Shader stages std::vector shaderStages; + // The fragment shader's specialization constants (SetFragmentConstant), 4 bytes each + std::vector FragmentEntries; + for (size_t i = 0; i < m_FragmentConstants.size(); ++i) + { + VkSpecializationMapEntry Entry = {}; + Entry.constantID = m_FragmentConstants[i].first; + Entry.offset = static_cast(i * sizeof(uint32)); + Entry.size = sizeof(uint32); + FragmentEntries.push_back(Entry); + } + std::vector FragmentData; + for (const std::pair& Constant : m_FragmentConstants) + { + FragmentData.push_back(Constant.second); + } + VkSpecializationInfo FragmentSpecialization = {}; + FragmentSpecialization.mapEntryCount = static_cast(FragmentEntries.size()); + FragmentSpecialization.pMapEntries = FragmentEntries.data(); + FragmentSpecialization.dataSize = FragmentData.size() * sizeof(uint32); + FragmentSpecialization.pData = FragmentData.data(); + for (Shader* shader : m_Shaders) { VkPipelineShaderStageCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; @@ -110,7 +131,10 @@ namespace Fling { createInfo.pName = "main"; createInfo.flags = 0; createInfo.pNext = nullptr; - createInfo.pSpecializationInfo = nullptr; + createInfo.pSpecializationInfo = + (shader->GetStage() == VK_SHADER_STAGE_FRAGMENT_BIT && !FragmentEntries.empty()) + ? &FragmentSpecialization + : nullptr; shaderStages.push_back(createInfo); } diff --git a/FlingEngine/Graphics/src/GraphicsPipeline.h b/FlingEngine/Graphics/src/GraphicsPipeline.h index 58134301..a7ba0460 100644 --- a/FlingEngine/Graphics/src/GraphicsPipeline.h +++ b/FlingEngine/Graphics/src/GraphicsPipeline.h @@ -4,6 +4,7 @@ #include "Shader.h" #include "Vertex.h" +#include #include namespace Fling @@ -33,6 +34,23 @@ namespace Fling const std::vector GetShaders() const { return m_Shaders; } + /** + * Set a 32-bit specialization constant of the fragment shader (layout(constant_id = + * t_Id)), for example a bool as 0 or 1. Used by the next CreateGraphicsPipeline. + */ + void SetFragmentConstant(uint32 t_Id, uint32 t_Value) + { + for (std::pair& Constant : m_FragmentConstants) + { + if (Constant.first == t_Id) + { + Constant.second = t_Value; + return; + } + } + m_FragmentConstants.emplace_back(t_Id, t_Value); + } + Depth GetDepth() const { return m_Depth; } VkPrimitiveTopology GetTopology() const { return m_Topology; } VkPolygonMode GetPolygonMode() const { return m_PolygonMode; } @@ -74,6 +92,9 @@ namespace Fling * given reads unbound memory: software drivers such as llvmpipe crash on it. */ bool m_HasVertexInput = true; + + /** @see SetFragmentConstant: (constant id, value). */ + std::vector> m_FragmentConstants; VkPipelineInputAssemblyStateCreateInfo m_InputAssemblyState = {}; VkPipelineRasterizationStateCreateInfo m_RasterizationState = {}; std::vector m_ColorBlendAttachmentStates; diff --git a/FlingEngine/Graphics/src/SwapChain.cpp b/FlingEngine/Graphics/src/SwapChain.cpp index 2cd831e1..3ba398ce 100644 --- a/FlingEngine/Graphics/src/SwapChain.cpp +++ b/FlingEngine/Graphics/src/SwapChain.cpp @@ -34,14 +34,8 @@ namespace Fling LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, VkSurfaceKHR 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) + const bool t_VSync) + : m_VSync(t_VSync), m_Extents{t_Extent}, m_Device(t_Dev), m_PhysicalDevice(t_PhysDev), m_Surface(t_Surface) { assert(m_Device && m_PhysicalDevice && m_Surface); Recreate(m_Extents); @@ -50,16 +44,14 @@ namespace Fling Swapchain::Swapchain(const VkExtent2D& t_Extent, LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, - const uint32 t_ImageCount, - const bool t_Copyable) + 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), - m_WantCopy(t_Copyable) + m_OffscreenImageCount(t_ImageCount) { assert(m_Device && m_PhysicalDevice && m_OffscreenImageCount > 0); // Nothing is presented, so nothing waits for a display @@ -168,15 +160,10 @@ namespace Fling m_Extents.height, static_cast(m_ImageFormat)); - // 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; - } + // Always copyable: a capture (Screenshot::Request) copies from the image in the frame's + // own command buffer, and there is no display whose compression the usage could cost + m_CanCopyImages = true; + const VkImageUsageFlags Usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; m_Images.resize(m_OffscreenImageCount); m_ImageMemory.resize(m_OffscreenImageCount); for (uint32 i = 0; i < m_OffscreenImageCount; ++i) @@ -229,11 +216,10 @@ namespace Fling CreateInfo.imageExtent = m_Extents; CreateInfo.imageArrayLayers = 1; CreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - // 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; + // A capture (Screenshot::Request) copies from the image in the frame's own command + // buffer. The usage is set once, when the surface allows it, so a capture never makes + // the swap chain again. It costs no CPU time; desktop drivers keep their compression + m_CanCopyImages = (SwapChainSupport.Capabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) != 0; if (m_CanCopyImages) { CreateInfo.imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; @@ -329,14 +315,10 @@ namespace Fling 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 + // Each image in turn, with no GPU work: the image is free, because the last frame's + // fence was waited on, and VulkanApp::Update does not wait on t_CompletedSemaphore 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); + return VK_SUCCESS; } VkDevice Device = m_Device->GetVkDevice(); @@ -353,15 +335,8 @@ namespace Fling { 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); + // Nothing to show, and no GPU work: VulkanApp::Update does not signal t_WaitSemaphore + return VK_SUCCESS; } VkPresentInfoKHR presentInfo = {}; diff --git a/FlingEngine/Graphics/src/SwapChain.h b/FlingEngine/Graphics/src/SwapChain.h index c94b8597..f5d759b8 100644 --- a/FlingEngine/Graphics/src/SwapChain.h +++ b/FlingEngine/Graphics/src/SwapChain.h @@ -27,15 +27,15 @@ namespace Fling public: /** t_VSync: SetVSync. */ - Swapchain(const VkExtent2D& t_Extent, LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, VkSurfaceKHR t_Surface, bool t_VSync, bool t_Copyable = false); + 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. + * nothing. Neither does GPU work or touches the semaphores: VulkanApp::Update skips + * the present semaphores offscreen. */ - Swapchain(const VkExtent2D& t_Extent, LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, uint32 t_ImageCount, bool t_Copyable = false); + Swapchain(const VkExtent2D& t_Extent, LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, uint32 t_ImageCount); ~Swapchain(); @@ -64,30 +64,18 @@ namespace Fling /** * 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). + * Offscreen nothing presents it, and a capture copies from it: TRANSFER_SRC. */ VkImageLayout GetFinalLayout() const { - 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; + 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; } - /** - * 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. + * True when the images can be copied from (VK_IMAGE_USAGE_TRANSFER_SRC_BIT), for a + * capture. Always offscreen; with a surface, when the surface allows the usage. */ - 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; } + bool CanCopyImages() const { return m_CanCopyImages; } /** The present mode it was made with. */ PresentMode GetPresentMode() const { return m_PresentMode; } @@ -133,12 +121,6 @@ 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 2c51d237..7d6d68a0 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -20,7 +20,6 @@ #include "PhyscialDevice.h" #include "RenderPipeline.h" #include "RenderSnapshot.h" -#include "Screenshot.h" #include "SkyboxSubpass.h" #include "Strings/String.h" #include "SwapChain.h" @@ -188,11 +187,7 @@ 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_SurfaceDesc.CopyableFrames); + m_SwapChain = new Swapchain(Extent, m_LogicalDevice, m_PhysicalDevice, VkConfig::MAX_FRAMES_IN_FLIGHT); } else { @@ -200,10 +195,11 @@ namespace Fling m_LogicalDevice, m_PhysicalDevice, m_State->m_Surface, - m_VSync, - m_SurfaceDesc.CopyableFrames); + m_VSync); } assert(m_SwapChain); + // Holds nothing until the first Screenshot::Request: no thread and no buffer + m_Capturer = std::make_unique(); GraphicsHelpers::CreateCommandPool(&m_State->m_CommandPool, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT); @@ -446,90 +442,18 @@ namespace Fling return m_SwapChain ? m_SwapChain->GetExtents().height : 0; } - void VulkanApp::PrepareScreenshots() + void VulkanApp::FinishScreenshots() { - // 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()) - { - return; - } - - // 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()) - { - ReadError = "the swap chain images cannot be copied (no VK_IMAGE_USAGE_TRANSFER_SRC_BIT); use --offscreen"; - } - else - { - bRead = FrameCapture::ReadImageRgba(*m_LogicalDevice, - m_SwapChain->GetActiveImage(), - m_SwapChain->GetImageFormat(), - Extent, - m_SwapChain->GetFinalLayout(), - Rgba, - ReadError); - } - - for (Screenshot::Pending& Request : Requests) - { - 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); - } - - // 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()) + if (m_Capturer) { - m_CopyableForRequest = false; - m_SwapChain->SetCopyable(false); - bSwapchainOutOfDate = true; + m_Capturer->Flush(); } } void VulkanApp::RecreateSwapchain() { F_LOG_TRACE("Making the swap chain again"); - // Offscreen images keep their size (there is no window); they are made again only to - // change whether they can be copied (Screenshot::Request) + // Offscreen images keep their size (there is no window) if (m_CurrentWindow != nullptr && !m_CurrentWindow->WaitForNewWindowSize()) { // The window was closed while minimized. ShouldTick sees the close next. @@ -705,8 +629,11 @@ namespace Fling m_Camera->SetLookRotation(View->Yaw, View->Pitch); } - // A screenshot was asked for: copyable images for this frame (nothing when none was) - PrepareScreenshots(); + // The screenshots that the writer thread finished: their callbacks (one atomic load when none) + m_Capturer->DeliverResults(); + + // Offscreen there is no present engine: no semaphores between the acquire, the frame and the present + const bool bPresentSync = !m_SwapChain->IsOffscreen(); // Aquire the active image index VkResult iResult = m_SwapChain->AquireNextImage(m_State->m_PresentCompleteSemaphores[CurrentFrameIndex]); @@ -778,6 +705,10 @@ namespace Fling CmdBuf->EndRenderPass(); + // A screenshot waits: the GPU copies this frame out in the same command buffer + // (nothing is recorded when none waits) + m_Capturer->RecordCopy(CmdBuf->GetHandle(), *m_SwapChain, ImageIndex); + // End command buffer recording CmdBuf->End(); } @@ -808,7 +739,7 @@ namespace Fling OffscreenSubmission.pWaitDstStageMask = waitStages; // Wait on Present complete OffscreenSubmission.pWaitSemaphores = &m_State->m_PresentCompleteSemaphores[CurrentFrameIndex]; - OffscreenSubmission.waitSemaphoreCount = 1; + OffscreenSubmission.waitSemaphoreCount = bPresentSync ? 1 : 0; // Signal that the dependent semaphores are done when this is complete OffscreenSubmission.pSignalSemaphores = SemaphoresToWaitOn.data(); @@ -835,7 +766,7 @@ namespace Fling else { // Track any semaphores that we may need to wait on for the render pipeline - FinalScreenSubmitInfo.waitSemaphoreCount = 1; + FinalScreenSubmitInfo.waitSemaphoreCount = bPresentSync ? 1 : 0; FinalScreenSubmitInfo.pWaitSemaphores = &m_State->m_PresentCompleteSemaphores[CurrentFrameIndex]; } @@ -850,7 +781,7 @@ namespace Fling FinalScreenSubmitInfo.commandBufferCount = (uint32)submitCommandBuffers.size(); // Actually present the swap chain queue. This is always going to be the signal for the final semaphore - FinalScreenSubmitInfo.signalSemaphoreCount = 1; + FinalScreenSubmitInfo.signalSemaphoreCount = bPresentSync ? 1 : 0; FinalScreenSubmitInfo.pSignalSemaphores = &m_State->m_RenderFinishedSemaphores[ImageIndex]; VK_CHECK_RESULT(vkQueueSubmit(m_LogicalDevice->GetGraphicsQueue(), @@ -865,8 +796,8 @@ namespace Fling VK_TRUE, std::numeric_limits::max()); - // The frame is drawn: copy it out before it is presented (Screenshot::Request) - SaveScreenshots(); + // The frame is drawn, and so is a screenshot's copy: the writer thread takes it from here + m_Capturer->OnFrameDone(); // Present the swap chain with the renderer finished semaphore iResult = m_SwapChain->QueuePresent(m_LogicalDevice->GetPresentQueue(), @@ -918,6 +849,13 @@ namespace Fling delete m_Camera; m_Camera = nullptr; + // Screenshots: the writes that are queued finish, and the staging buffers go before the device + if (m_Capturer) + { + m_Capturer->Release(); + m_Capturer.reset(); + } + // Destroy swap chain (created in Prepare) ----------- delete m_SwapChain; m_SwapChain = nullptr; diff --git a/FlingTests/Core/FlingPathsTests.cpp b/FlingTests/Core/FlingPathsTests.cpp new file mode 100644 index 00000000..f5716d2b --- /dev/null +++ b/FlingTests/Core/FlingPathsTests.cpp @@ -0,0 +1,56 @@ +#include "FlingPaths.h" +#include "Strings/String.h" + +#include +#include +#include +#include +#include + +using Fling::FlingPaths; +using Fling::String; + +namespace +{ + String ReadAll(const std::filesystem::path& t_Path) + { + std::ifstream File(t_Path, std::ios::binary); + return String(std::istreambuf_iterator(File), std::istreambuf_iterator()); + } +} // namespace + +TEST_CASE("FlingPaths::SaveFile makes the folders and replaces the file", "[FlingPaths]") +{ + const std::filesystem::path Root = std::filesystem::temp_directory_path() / "FlingPathsSaveFileTest"; + std::error_code Ignored; + std::filesystem::remove_all(Root, Ignored); + const std::filesystem::path File = Root / "a" / "b" / "out.bin"; + + String Error; + // Binary: a zero byte and a newline are written as is + const String Bytes("one\0two\n", 8); + REQUIRE(FlingPaths::SaveFile(Fling::PathToUtf8(File), Bytes, Error)); + REQUIRE(Error.empty()); + REQUIRE(ReadAll(File) == Bytes); + + // Replaced, not appended to + REQUIRE(FlingPaths::SaveFile(Fling::PathToUtf8(File), "short", Error)); + REQUIRE(ReadAll(File) == "short"); + + std::filesystem::remove_all(Root, Ignored); +} + +TEST_CASE("FlingPaths::SaveFile says why it failed", "[FlingPaths]") +{ + const std::filesystem::path Root = std::filesystem::temp_directory_path() / "FlingPathsSaveFileFail"; + std::error_code Ignored; + std::filesystem::remove_all(Root, Ignored); + std::filesystem::create_directories(Root / "folder", Ignored); + + // The path is a folder, so it cannot be opened as a file + String Error; + REQUIRE_FALSE(FlingPaths::SaveFile(Fling::PathToUtf8(Root / "folder"), "x", Error)); + REQUIRE_FALSE(Error.empty()); + + std::filesystem::remove_all(Root, Ignored); +} diff --git a/Skills/testing.md b/Skills/testing.md index 6e7306e4..8fba171c 100644 --- a/Skills/testing.md +++ b/Skills/testing.md @@ -246,22 +246,31 @@ Fling::Screenshot::Request("Saved/door_open.png", }); ``` -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 +The renderer copies its next frame for every waiting request, and a writer thread saves +the PNG files, then 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. -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. +Cost: nothing when nobody asks, and no stall when somebody does (`FrameCapturer` in +`Graphics/src/FrameCapture.h`): + +- A frame with no request does two atomic loads (`Screenshot::HasPending()`, and "any + results to deliver"). No lock, no allocation. The writer thread and the staging buffers + are made on the first capture only. +- The frame of a capture records one more barrier and a `vkCmdCopyImageToBuffer` into its + own command buffer, after the render pass. That is GPU work in the frame's submit; the + CPU does not wait for it, and the swap chain is never made again. +- After the frame's fence, the staging buffer goes to the `Screenshot Writer` thread, + which converts the pixels, encodes the PNG once and writes it to each requested path. + The main thread copies nothing. At 1920x1080 on llvmpipe the encode takes about a second + on the writer while the frames keep their normal time. +- The callbacks run on the main thread at a later frame. A run's end waits for the writes + (`VulkanApp::FinishScreenshots`), so `--screenshot` checks every file before it exits. +- The swap chain images are made with `VK_IMAGE_USAGE_TRANSFER_SRC_BIT` once, when the + surface allows it (always offscreen). It costs no CPU time, and desktop drivers keep + their framebuffer compression with it. ## Unattended crash tests