From 312c41acd9f865156c0dd76d2eccfa23cadb7298 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:18:18 +0100 Subject: [PATCH 01/68] lib: cth with the input types and the keys by scan code --- lib/cth | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/cth b/lib/cth index e970abb6..a6256e47 160000 --- a/lib/cth +++ b/lib/cth @@ -1 +1 @@ -Subproject commit e970abb6a453473d5bf7a21630460ddfa7eb9cf2 +Subproject commit a6256e47caa7c4abf9167a9ca446cecd47c687c9 From ac716b9f726127a43531f49de8a9b8e43a67af21 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:18:18 +0100 Subject: [PATCH 02/68] rgfw: current upstream, cgfw initializes RGFW for the first window - lib/rgfw: our fork on upstream main, with the fixes upstream still needs - RGFW no longer initializes in createWindow: the first cgfw window calls RGFW_init with Vulkan, the last one RGFW_deinit - FULLSCREEN is RGFW_windowFullscreenBorderless, the old meaning - rgfw.cmake: pointer-warp protocol, advapi32, dl, the Vulkan platform defines for the surface types in RGFW.h --- cgfw/incl/cgfw/window/window.hpp | 6 ++++-- cgfw/src/window/rgfw.c | 6 ++++++ cgfw/src/window/rgfw_info.h | 17 +++++++++++++++++ cgfw/src/window/window.cpp | 32 ++++++++++++++++++++++++++------ lib/cmake/rgfw.cmake | 16 +++++++++++----- lib/rgfw | 2 +- 6 files changed, 65 insertions(+), 14 deletions(-) create mode 100644 cgfw/src/window/rgfw_info.h diff --git a/cgfw/incl/cgfw/window/window.hpp b/cgfw/incl/cgfw/window/window.hpp index 4f62e28d..3cd4cea4 100644 --- a/cgfw/incl/cgfw/window/window.hpp +++ b/cgfw/incl/cgfw/window/window.hpp @@ -33,7 +33,7 @@ enum class WindowFlags : uint32_t { NONE = 0, NO_BORDER = cth::en::flag_val(0), NO_RESIZE = cth::en::flag_val(1), - FULLSCREEN = cth::en::flag_val(4), + FULLSCREEN = cth::en::flag_val(19), ///< borderless, the monitor keeps its video mode CENTER = cth::en::flag_val(6), SCALE_TO_MONITOR = cth::en::flag_val(8), /** @@ -131,10 +131,11 @@ class Window { /** * creates the window with the config - * @details no window exists -> initializes RGFW first + * @details RGFW is not initialized -> initializes RGFW with Vulkan first * @pre `Config::debug_check()` passes for the config * @post `created()` * @note calls `optDestroy()` + * @throws cgfw::cgfw_exception reason: `RGFW_init()` failed, e.g. no display * @throws cgfw::cgfw_exception reason: `RGFW_createWindow()` failed */ void create(); @@ -201,6 +202,7 @@ class Window { /** * closes the window and frees it + * @details the last window of RGFW deinitializes RGFW * @pre the window is not `nullptr` */ static void destroy(RGFW_window*); diff --git a/cgfw/src/window/rgfw.c b/cgfw/src/window/rgfw.c index 40827fc9..8aee599c 100644 --- a/cgfw/src/window/rgfw.c +++ b/cgfw/src/window/rgfw.c @@ -1,8 +1,14 @@ // the RGFW implementation, no other source file defines RGFW_IMPLEMENTATION // C: the Wayland part of RGFW is no valid C++ (void* conversions, designator order) +#include "window/rgfw_info.h" // volk first: RGFW includes vulkan.h, volk needs VK_NO_PROTOTYPES before it #include #define RGFW_IMPLEMENTATION #include + +size_t cgfw_rgfw_window_count(void) { + RGFW_info const* const info = RGFW_getInfo(); + return info == NULL ? 0 : (size_t)info->windowCount; +} diff --git a/cgfw/src/window/rgfw_info.h b/cgfw/src/window/rgfw_info.h new file mode 100644 index 00000000..8a8625c4 --- /dev/null +++ b/cgfw/src/window/rgfw_info.h @@ -0,0 +1,17 @@ +#pragma once +// the state of RGFW for window.cpp, rgfw.c defines the functions: only there RGFW_info is complete + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @return windows of RGFW, `0` -> no window or RGFW is not initialized + */ +size_t cgfw_rgfw_window_count(void); + +#ifdef __cplusplus +} +#endif diff --git a/cgfw/src/window/window.cpp b/cgfw/src/window/window.cpp index 434d22f1..41c4492f 100644 --- a/cgfw/src/window/window.cpp +++ b/cgfw/src/window/window.cpp @@ -1,6 +1,7 @@ #include "cgfw/window/window.hpp" #include "cgfw/utility/exception.hpp" +#include "window/rgfw_info.h" #include "cvk/base/instance.hpp" #include "cvk/utility/format.hpp" @@ -25,7 +26,7 @@ namespace { static_assert(same_flag(WindowFlags::NO_BORDER, RGFW_windowNoBorder)); static_assert(same_flag(WindowFlags::NO_RESIZE, RGFW_windowNoResize)); - static_assert(same_flag(WindowFlags::FULLSCREEN, RGFW_windowFullscreen)); + static_assert(same_flag(WindowFlags::FULLSCREEN, RGFW_windowFullscreenBorderless)); static_assert(same_flag(WindowFlags::CENTER, RGFW_windowCenter)); static_assert(same_flag(WindowFlags::SCALE_TO_MONITOR, RGFW_windowScaleToMonitor)); static_assert(same_flag(WindowFlags::HIDE, RGFW_windowHide)); @@ -33,6 +34,14 @@ namespace { static_assert(same_flag(WindowFlags::FLOATING, RGFW_windowFloating)); static_assert(same_flag(WindowFlags::FOCUS_ON_SHOW, RGFW_windowFocusOnShow)); static_assert(same_flag(WindowFlags::MINIMIZE, RGFW_windowMinimize)); + + /** + * deinitializes RGFW if it is initialized and has no window + */ + void deinit_without_windows() { + if(RGFW_getInfo() != nullptr && cgfw_rgfw_window_count() == 0) + RGFW_deinit(); + } } void dev::window_deleter::operator()(RGFW_window* rgfwWindow) const { Window::destroy(rgfwWindow); } @@ -53,6 +62,17 @@ void Window::create() { Config::debug_check(_config); optDestroy(); + // RGFW_initVulkan: RGFW_window_createSurface_Vulkan() needs the Vulkan library of RGFW + if(RGFW_getInfo() == nullptr) { + auto const initResult = RGFW_init(nullptr, RGFW_initVulkan); + CGFW_STABLE_THROW( + initResult < 0, + "failed to initialize RGFW for the window {}, e.g. no display, got {}", + _config.title, + initResult + ) { forget(); } + } + auto* const rgfwWindow = RGFW_createWindow( _config.title.c_str(), 0, @@ -61,11 +81,10 @@ void Window::create() { static_cast(_config.extent.height), static_cast(_config.flags) ); - CGFW_STABLE_THROW( - rgfwWindow == nullptr, - "failed to create the window {}, e.g. no display", - _config.title - ) { forget(); } + CGFW_STABLE_THROW(rgfwWindow == nullptr, "failed to create the window {}", _config.title) { + deinit_without_windows(); + forget(); + } _handle.reset(rgfwWindow); } @@ -150,6 +169,7 @@ void Window::destroy(RGFW_window* rgfwWindow) { CTH_CRITICAL(rgfwWindow == nullptr, "rgfwWindow must not be nullptr") {} RGFW_window_close(rgfwWindow); + deinit_without_windows(); } void Window::forget() {} diff --git a/lib/cmake/rgfw.cmake b/lib/cmake/rgfw.cmake index b0651fb9..10b87a11 100644 --- a/lib/cmake/rgfw.cmake +++ b/lib/cmake/rgfw.cmake @@ -20,10 +20,14 @@ if (NOT TARGET rgfw::rgfw) if (WIN32) # RGFW includes windows.h: no min and max macros target_compile_definitions(rgfw INTERFACE NOMINMAX) - # RGFW loads winmm, dwmapi, shcore and opengl32 at run time - target_link_libraries(rgfw INTERFACE gdi32 user32 shell32) + # the Vulkan types of the surface in RGFW.h: vulkan.h can come before RGFW.h, empty like the define of RGFW + target_compile_definitions(rgfw INTERFACE "VK_USE_PLATFORM_WIN32_KHR=") + # RGFW loads winmm, dwmapi, shcore and opengl32 at run time, advapi32 reads the registry + target_link_libraries(rgfw INTERFACE gdi32 user32 shell32 advapi32) elseif (CMAKE_SYSTEM_NAME STREQUAL "Linux") target_compile_definitions(rgfw INTERFACE RGFW_WAYLAND RGFW_NO_X11) + # the Vulkan types of the surface in RGFW.h: vulkan.h can come before RGFW.h, empty like the define of RGFW + target_compile_definitions(rgfw INTERFACE "VK_USE_PLATFORM_WAYLAND_KHR=") # wayland and xkbcommon come from the system, the vcpkg ports of them are empty on linux find_package(PkgConfig REQUIRED) @@ -36,7 +40,7 @@ if (NOT TARGET rgfw::rgfw) message(FATAL_ERROR "wayland-protocols not found, vcpkg installs it on linux") endif () - # the protocols that RGFW includes, see the xdg-shell.c rule in lib/rgfw/Makefile + # the protocols that RGFW includes, see WAYLAND_PROTO in lib/rgfw/wayland.mk set(RGFW_WAYLAND_PROTOCOLS "stable/xdg-shell/xdg-shell.xml" "unstable/xdg-decoration/xdg-decoration-unstable-v1.xml" @@ -44,6 +48,7 @@ if (NOT TARGET rgfw::rgfw) "unstable/xdg-output/xdg-output-unstable-v1.xml" "unstable/relative-pointer/relative-pointer-unstable-v1.xml" "unstable/pointer-constraints/pointer-constraints-unstable-v1.xml" + "staging/pointer-warp/pointer-warp-v1.xml" ) set(RGFW_PROTOCOL_DIR "${CMAKE_BINARY_DIR}/lib/rgfw/wayland") @@ -71,9 +76,10 @@ if (NOT TARGET rgfw::rgfw) target_include_directories(rgfw_wayland_protocols PUBLIC "${RGFW_PROTOCOL_DIR}") target_link_libraries(rgfw_wayland_protocols PUBLIC PkgConfig::RGFW_WAYLAND) - target_link_libraries(rgfw INTERFACE rgfw_wayland_protocols) + # RGFW loads libvulkan and libdecor with dlopen() + target_link_libraries(rgfw INTERFACE rgfw_wayland_protocols ${CMAKE_DL_LIBS}) - #TODO libdecor for frames on GNOME, GNOME has no xdg-decoration (KDE and sway have it), vcpkg has no port + # libdecor: frames on GNOME, which has no xdg-decoration, RGFW loads libdecor-0.so.0 at run time else () message(FATAL_ERROR "RGFW: only Windows and Linux (Wayland) are supported, got ${CMAKE_SYSTEM_NAME}") endif () diff --git a/lib/rgfw b/lib/rgfw index 70c07fd8..0eef7957 160000 --- a/lib/rgfw +++ b/lib/rgfw @@ -1 +1 @@ -Subproject commit 70c07fd8ff4d2d9c3817a5fbca7d6f2b7c81e06e +Subproject commit 0eef7957012d58f274876b387ea670479bbef037 From a144885cd7e457855491061ec0f1aa1ddabc6f63 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:25:08 +0100 Subject: [PATCH 03/68] lib: rgfw with the OS time in the input events (ColleagueRiley/RGFW#615) --- lib/rgfw | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/rgfw b/lib/rgfw index 0eef7957..04542bac 160000 --- a/lib/rgfw +++ b/lib/rgfw @@ -1 +1 @@ -Subproject commit 0eef7957012d58f274876b387ea670479bbef037 +Subproject commit 04542bac7e4cf174bba120d048580a8cdc7c1b3b From 673ade1badbbebbffcc8fbe8c6cdfacb5ad29842 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:34:26 +0100 Subject: [PATCH 04/68] agents: the pull request of a work branch is a normal pull request --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 534cdc9c..bd7313cd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,7 @@ Read it before you change a file. Match the existing code. ## Branches - `master` is the main branch. -- Work happens on a work branch off `master`. Its draft pull request into `master` runs the CI on every push. +- Work happens on a work branch off `master`. Its pull request into `master` runs the CI on every push. - `v2`, `_v2/...`, `dev` and `_dev/...` are old. Do not use them. - Work locally. Do not open pull requests for single steps. - CI runs on pushes and pull requests to `master`. From b494c7822d1abc793b5ae316f23af325fcd97441 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:35:05 +0100 Subject: [PATCH 05/68] agents: the pull request of a work branch stays a draft until the work is finished --- AGENTS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AGENTS.md b/AGENTS.md index bd7313cd..699ac0a3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,6 +34,7 @@ Read it before you change a file. Match the existing code. - `master` is the main branch. - Work happens on a work branch off `master`. Its pull request into `master` runs the CI on every push. +- The pull request of a work branch stays a draft until the work is finished. - `v2`, `_v2/...`, `dev` and `_dev/...` are old. Do not use them. - Work locally. Do not open pull requests for single steps. - CI runs on pushes and pull requests to `master`. From ea2c793250b45da1e565a1fc267c04e25f9534be Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:51:05 +0100 Subject: [PATCH 06/68] cgfw: window events, keys, axes, text and focus - Window::events(): the input events of the last pollEvents() as cgfw::window_event (cth::io::key_update, cth::io::axis_update, TextEvent, FocusEvent) - keys by position with the character of the layout (RGFW_physicalToKeyChar of our fork), mouse buttons as keys - the OS time of the events as steady_clock time points - RGFW_MAX_EVENTS 1024: a full queue drops events --- cgfw/incl/cgfw/window/event.hpp | 39 +++ cgfw/incl/cgfw/window/window.hpp | 20 +- cgfw/src/window/rgfw_event.cpp | 100 ++++++++ cgfw/src/window/rgfw_event.hpp | 214 ++++++++++++++++ cgfw/src/window/window.cpp | 18 +- cgfw/tests/CMakeLists.txt | 5 +- cgfw/tests/src/window/event_test.cpp | 336 ++++++++++++++++++++++++++ cgfw/tests/src/window/window_test.cpp | 16 +- demo/cube/src/main.cpp | 4 +- demo/triangle/src/main.cpp | 4 +- lib/cmake/rgfw.cmake | 3 + lib/rgfw | 2 +- 12 files changed, 744 insertions(+), 17 deletions(-) create mode 100644 cgfw/incl/cgfw/window/event.hpp create mode 100644 cgfw/src/window/rgfw_event.cpp create mode 100644 cgfw/src/window/rgfw_event.hpp create mode 100644 cgfw/tests/src/window/event_test.cpp diff --git a/cgfw/incl/cgfw/window/event.hpp b/cgfw/incl/cgfw/window/event.hpp new file mode 100644 index 00000000..c4955153 --- /dev/null +++ b/cgfw/incl/cgfw/window/event.hpp @@ -0,0 +1,39 @@ +#pragma once +#include +#include +#include + +#include +#include + + +namespace cgfw { +/** + * text input of a window + * @details one event per character, a dead key and the next key give one character + */ +struct TextEvent { + std::string text; ///< UTF-8 + cth::chrono::time_point_t time; + + [[nodiscard]] constexpr bool operator==(TextEvent const&) const = default; +}; + +/** + * the window gets or loses the keyboard focus + */ +struct FocusEvent { + bool focused; + cth::chrono::time_point_t time; + + [[nodiscard]] constexpr bool operator==(FocusEvent const&) const = default; +}; + +/** + * input event of a window + * @details + * - keys and mouse buttons: `cth::io::key_update` + * - mouse position and scroll: `cth::io::axis_update` + */ +using window_event = std::variant; +} diff --git a/cgfw/incl/cgfw/window/window.hpp b/cgfw/incl/cgfw/window/window.hpp index 3cd4cea4..3cf20b59 100644 --- a/cgfw/incl/cgfw/window/window.hpp +++ b/cgfw/incl/cgfw/window/window.hpp @@ -1,4 +1,6 @@ #pragma once +#include "cgfw/window/event.hpp" + #include "cvk/surface/surface.hpp" #include "cvk/utility/constants.hpp" #include "cvk/utility/handle/unique_handle.hpp" @@ -11,6 +13,7 @@ #include #include +#include #include #include @@ -75,6 +78,7 @@ namespace dev { * @details a window of the platform: Win32 or Wayland * @details the first window initializes RGFW, the destruction of the last one deinitializes it * @details `pollEvents()` handles the events of every window + * @details `events()` holds the input events of the window * @attention not thread safe, also across windows */ class Window { @@ -181,11 +185,20 @@ class Window { [[nodiscard]] VkExtent2D extent() const; /** - * handles the pending events of every window - * @details returns at once, no wait for an event: for a render loop, it answers the pings of the compositor + * handles the pending events of every window, keeps the input events of this window + * @details + * - returns at once, no wait for an event: for a render loop, it answers the pings of the compositor + * - replaces `events()` + * - the events of the other windows stay queued until their `pollEvents()` * @pre `created()` */ - void pollEvents() const; + void pollEvents(); + + /** + * @return the input events of the last `pollEvents()`, in order + * @details valid until the next `pollEvents()` + */ + [[nodiscard]] std::span events() const { return _events; } /** * @return the user or the platform requested to close the window @@ -216,6 +229,7 @@ class Window { Config _config; cvk::unique_handle _handle{}; + std::vector _events{}; public: Window(Window const& other) = delete; diff --git a/cgfw/src/window/rgfw_event.cpp b/cgfw/src/window/rgfw_event.cpp new file mode 100644 index 00000000..738f52b1 --- /dev/null +++ b/cgfw/src/window/rgfw_event.cpp @@ -0,0 +1,100 @@ +#include "window/rgfw_event.hpp" + +#include + +#ifdef CTH_PLATFORM_WINDOWS +#include +#else +#include +#endif + + +namespace cgfw::dev { +uint32_t os_input_time() { +#ifdef CTH_PLATFORM_WINDOWS + return static_cast(GetTickCount()); +#else + timespec time{}; + clock_gettime(CLOCK_MONOTONIC, &time); + + // the input times wrap at 2^32 milliseconds, the truncation wraps the same + auto const milliseconds = static_cast(time.tv_sec) * 1000 + + static_cast(time.tv_nsec) / 1'000'000; + return static_cast(milliseconds); +#endif +} + +std::optional to_event( + RGFW_event const& rgfwEvent, + input_clock const& clock, + u32 (*keyChar)(RGFW_key) +) { + using cth::io::Axis; + using cth::io::axis_state; + using cth::io::axis_update; + using cth::io::key_state; + using cth::io::key_update; + + switch(rgfwEvent.common.type) { + case RGFW_keyPressed: + case RGFW_keyReleased: { + auto const& key = rgfwEvent.key; + auto const exKey = to_ex_key(key.value); + if(!exKey) + return std::nullopt; + + return key_update{ + .data = key_state{ + *exKey, + key.state != RGFW_FALSE, + to_utf8(static_cast(keyChar(key.value))), + key.repeat != RGFW_FALSE + }, + .time = clock.timePoint(key.time) + }; + } + case RGFW_mouseButtonPressed: + case RGFW_mouseButtonReleased: { + auto const& button = rgfwEvent.button; + auto const key = to_mouse_key(button.value); + if(!key) + return std::nullopt; + + return key_update{ + .data = key_state{*key, false, button.state != RGFW_FALSE}, + .time = clock.timePoint(button.time) + }; + } + case RGFW_mouseMotion: { + auto const& mouse = rgfwEvent.mouse; + return axis_update{ + .data = axis_state{ + .axis = Axis::MOUSE_POSITION, + .value = {static_cast(mouse.x), static_cast(mouse.y)} + }, + .time = clock.timePoint(mouse.time) + }; + } + case RGFW_mouseScroll: { + auto const& delta = rgfwEvent.delta; + return axis_update{ + .data = axis_state{.axis = Axis::MOUSE_SCROLL, .value = {delta.x, delta.y}}, + .time = clock.timePoint(delta.time) + }; + } + case RGFW_keyChar: { + auto const& keyCharEvent = rgfwEvent.keyChar; + auto text = to_utf8(static_cast(keyCharEvent.value)); + if(text.empty()) + return std::nullopt; + + return TextEvent{.text = std::move(text), .time = clock.timePoint(keyCharEvent.time)}; + } + // RGFW gives focus events no OS time + case RGFW_windowFocusIn: return FocusEvent{.focused = true, .time = clock.now}; + case RGFW_windowFocusOut: return FocusEvent{.focused = false, .time = clock.now}; + + default: return std::nullopt; + } +} +} diff --git a/cgfw/src/window/rgfw_event.hpp b/cgfw/src/window/rgfw_event.hpp new file mode 100644 index 00000000..aa0bb8fe --- /dev/null +++ b/cgfw/src/window/rgfw_event.hpp @@ -0,0 +1,214 @@ +#pragma once +#include "cgfw/window/event.hpp" + +#include + +#include +#include + +#include +#include +#include +#include +#include + + +namespace cgfw::dev { +/** + * @return current time of the OS clock of the input events, in milliseconds + * @details + * - Linux: `CLOCK_MONOTONIC`, assumes the Wayland compositor takes its input times from it + * - Windows: `GetTickCount()`, the clock of `GetMessageTime()` + */ +[[nodiscard]] uint32_t os_input_time(); + +/** + * `cth::chrono::clock_t` and the OS clock of the input events at one moment + */ +struct input_clock { + cth::chrono::time_point_t now; + uint32_t osNow; ///< OS clock at `now`, in milliseconds, see `os_input_time()` + + /** + * @return the clocks now + */ + [[nodiscard]] static input_clock Now() { + return {cth::chrono::clock_t::now(), os_input_time()}; + } + + /** + * converts the OS time of an input event + * @param osTime in milliseconds, `0` -> no OS time + * @return `now - (osNow - osTime) mod 2^32` + * @details + * - `osTime == 0` -> `now` + * - `osTime` after `osNow` (another clock) -> `now` + */ + [[nodiscard]] constexpr cth::chrono::time_point_t timePoint(uint32_t osTime) const; +}; + +/** + * @return UTF-8 of the codepoint, `0` or no Unicode scalar value -> empty + */ +[[nodiscard]] constexpr std::string to_utf8(char32_t codepoint); + +/** + * @return the key at the position of the RGFW key, `std::nullopt` -> no `cth::io::Key` for it + * @details keypad keys and right modifiers set `cth::io::ex_key::right` + */ +[[nodiscard]] constexpr std::optional to_ex_key(RGFW_key); + +/** + * @return the key of the mouse button, `std::nullopt` -> no `cth::io::Key` for it + */ +[[nodiscard]] constexpr std::optional to_mouse_key(RGFW_mouseButton); + +/** + * converts an RGFW event + * @param keyChar codepoint of a physical key in the layout, see `RGFW_physicalToKeyChar()` + * @return `std::nullopt` -> no `window_event` for it + * @details + * - key -> `cth::io::key_update`, `cth::io::key_state::character` from `keyChar` + * - mouse button -> `cth::io::key_update` of a mouse key + * - mouse position, scroll -> `cth::io::axis_update` + * - key character -> `TextEvent`, focus -> `FocusEvent` + * - time: `input_clock::timePoint()` of the OS time, focus -> `input_clock::now` + */ +[[nodiscard]] std::optional to_event( + RGFW_event const& rgfwEvent, + input_clock const& clock, + u32 (*keyChar)(RGFW_key) +); +} + +namespace cgfw::dev { +constexpr cth::chrono::time_point_t input_clock::timePoint(uint32_t osTime) const { + if(osTime == 0) + return now; + + // unsigned: the age is right across the wrap of the OS clock + auto const age = static_cast(osNow - osTime); + if(age > static_cast(std::numeric_limits::max())) + return now; + + return now - std::chrono::milliseconds{age}; +} + +constexpr std::string to_utf8(char32_t codepoint) { + auto const value = static_cast(codepoint); + if(value == 0 || value > 0x10FFFF || (value >= 0xD800 && value <= 0xDFFF)) + return {}; + + auto const byte = [](uint32_t bits) { + return static_cast(static_cast(bits)); + }; + + if(value < 0x80) + return std::string{byte(value)}; + if(value < 0x800) + return std::string{byte(0xC0 | (value >> 6)), byte(0x80 | (value & 0x3F))}; + if(value < 0x10000) + return std::string{ + byte(0xE0 | (value >> 12)), + byte(0x80 | ((value >> 6) & 0x3F)), + byte(0x80 | (value & 0x3F)) + }; + return std::string{ + byte(0xF0 | (value >> 18)), + byte(0x80 | ((value >> 12) & 0x3F)), + byte(0x80 | ((value >> 6) & 0x3F)), + byte(0x80 | (value & 0x3F)) + }; +} + +constexpr std::optional to_ex_key(RGFW_key key) { + using cth::io::Key; + using cth::io::ex_key; + + auto const offset = [](RGFW_key from, RGFW_key first, Key to) { + return static_cast(*to + (from - first)); + }; + + if(key >= RGFW_keyA && key <= RGFW_keyZ) + return ex_key{offset(key, RGFW_keyA, Key::A)}; + if(key >= RGFW_key0 && key <= RGFW_key9) + return ex_key{offset(key, RGFW_key0, Key::DIGIT_0)}; + if(key >= RGFW_keyF1 && key <= RGFW_keyF12) + return ex_key{offset(key, RGFW_keyF1, Key::F1)}; + if(key >= RGFW_keyF13 && key <= RGFW_keyF24) + return ex_key{offset(key, RGFW_keyF13, Key::F13)}; + if(key >= RGFW_keyPad1 && key <= RGFW_keyPad9) + return ex_key{offset(key, RGFW_keyPad1, Key::DIGIT_1), true}; + + switch(key) { + case RGFW_keyEscape: return ex_key{Key::ESCAPE}; + case RGFW_keyBacktick: return ex_key{Key::BACKTICK}; + case RGFW_keyMinus: return ex_key{Key::MINUS}; + case RGFW_keyEqual: return ex_key{Key::EQUAL}; + case RGFW_keyBackSpace: return ex_key{Key::BACKSPACE}; + case RGFW_keyTab: return ex_key{Key::TAB}; + case RGFW_keySpace: return ex_key{Key::SPACE}; + case RGFW_keyPeriod: return ex_key{Key::PERIOD}; + case RGFW_keyComma: return ex_key{Key::COMMA}; + case RGFW_keySlash: return ex_key{Key::SLASH}; + case RGFW_keyBracket: return ex_key{Key::OPEN_BRACKET}; + case RGFW_keyCloseBracket: return ex_key{Key::CLOSE_BRACKET}; + case RGFW_keySemicolon: return ex_key{Key::SEMICOLON}; + case RGFW_keyApostrophe: return ex_key{Key::QUOTE}; + case RGFW_keyBackSlash: return ex_key{Key::BACKSLASH}; + case RGFW_keyReturn: return ex_key{Key::ENTER}; + case RGFW_keyDelete: return ex_key{Key::DELETE}; + case RGFW_keyWorld1: return ex_key{Key::LESS_THAN}; + + case RGFW_keyCapsLock: return ex_key{Key::CAPS_LOCK}; + case RGFW_keyShiftL: return ex_key{Key::SHIFT}; + case RGFW_keyShiftR: return ex_key{Key::SHIFT, true}; + case RGFW_keyControlL: return ex_key{Key::CONTROL}; + case RGFW_keyControlR: return ex_key{Key::CONTROL, true}; + case RGFW_keyAltL: return ex_key{Key::ALT}; + case RGFW_keyAltR: return ex_key{Key::ALT, true}; + case RGFW_keySuperL: return ex_key{Key::PLATFORM}; + case RGFW_keySuperR: return ex_key{Key::PLATFORM, true}; + case RGFW_keyMenu: return ex_key{Key::MENU}; + + case RGFW_keyUp: return ex_key{Key::ARROW_UP}; + case RGFW_keyDown: return ex_key{Key::ARROW_DOWN}; + case RGFW_keyLeft: return ex_key{Key::ARROW_LEFT}; + case RGFW_keyRight: return ex_key{Key::ARROW_RIGHT}; + case RGFW_keyInsert: return ex_key{Key::INSERT}; + case RGFW_keyEnd: return ex_key{Key::END}; + case RGFW_keyHome: return ex_key{Key::HOME}; + case RGFW_keyPageUp: return ex_key{Key::PAGE_UP}; + case RGFW_keyPageDown: return ex_key{Key::PAGE_DOWN}; + + case RGFW_keyNumLock: return ex_key{Key::NUM_LOCK}; + case RGFW_keyPadSlash: return ex_key{Key::SLASH, true}; + case RGFW_keyPadMultiply: return ex_key{Key::STAR, true}; + case RGFW_keyPadPlus: return ex_key{Key::PLUS, true}; + case RGFW_keyPadMinus: return ex_key{Key::MINUS, true}; + case RGFW_keyPadEqual: return ex_key{Key::EQUAL, true}; + case RGFW_keyPad0: return ex_key{Key::DIGIT_0, true}; + case RGFW_keyPadPeriod: return ex_key{Key::PERIOD, true}; + case RGFW_keyPadReturn: return ex_key{Key::ENTER, true}; + + case RGFW_keyScrollLock: return ex_key{Key::SCROLL_LOCK}; + case RGFW_keyPrintScreen: return ex_key{Key::PRINT_SCREEN}; + case RGFW_keyPause: return ex_key{Key::PAUSE}; + + default: return std::nullopt; + } +} + +constexpr std::optional to_mouse_key(RGFW_mouseButton button) { + using cth::io::Key; + + switch(button) { + case RGFW_mouseLeft: return Key::MOUSE_LEFT; + case RGFW_mouseRight: return Key::MOUSE_RIGHT; + case RGFW_mouseMiddle: return Key::MOUSE_MIDDLE; + case RGFW_mouseMisc1: return Key::MOUSE_4; + case RGFW_mouseMisc2: return Key::MOUSE_5; + default: return std::nullopt; + } +} +} diff --git a/cgfw/src/window/window.cpp b/cgfw/src/window/window.cpp index 41c4492f..cce2602a 100644 --- a/cgfw/src/window/window.cpp +++ b/cgfw/src/window/window.cpp @@ -1,6 +1,7 @@ #include "cgfw/window/window.hpp" #include "cgfw/utility/exception.hpp" +#include "window/rgfw_event.hpp" #include "window/rgfw_info.h" #include "cvk/base/instance.hpp" @@ -71,6 +72,9 @@ void Window::create() { _config.title, initResult ) { forget(); } + + // the queue holds the events between two pollEvents(), also the first ones of a window + RGFW_setQueueEvents(RGFW_TRUE); } auto* const rgfwWindow = RGFW_createWindow( @@ -136,10 +140,20 @@ VkExtent2D Window::extent() const { }; } -void Window::pollEvents() const { +void Window::pollEvents() { debug_check(*this); + _events.clear(); RGFW_pollEvents(); + + auto const clock = dev::input_clock::Now(); + + RGFW_event rgfwEvent{}; + while(RGFW_window_checkQueuedEvent(_handle.get(), &rgfwEvent) != RGFW_FALSE) { + auto event = dev::to_event(rgfwEvent, clock, &RGFW_physicalToKeyChar); + if(event) + _events.push_back(std::move(*event)); + } } bool Window::shouldClose() const { @@ -172,7 +186,7 @@ void Window::destroy(RGFW_window* rgfwWindow) { deinit_without_windows(); } -void Window::forget() {} +void Window::forget() { _events.clear(); } std::vector instance_extensions() { size_t count = 0; diff --git a/cgfw/tests/CMakeLists.txt b/cgfw/tests/CMakeLists.txt index 773945cd..8fde9948 100644 --- a/cgfw/tests/CMakeLists.txt +++ b/cgfw/tests/CMakeLists.txt @@ -4,9 +4,10 @@ add_executable(cgfw_tests ${CGFW_TESTS_SRC}) cth_target_enable_build_cache(cgfw_tests OPTIONAL) +# ../src: the tests reach the RGFW event conversion of cgfw, which needs RGFW.h target_include_directories( cgfw_tests - PRIVATE src + PRIVATE src "${CMAKE_CURRENT_SOURCE_DIR}/../src" ) target_precompile_headers( @@ -17,7 +18,7 @@ target_precompile_headers( find_package(GTest CONFIG REQUIRED) -target_link_libraries(cgfw_tests PRIVATE GTest::gtest_main cgfw) +target_link_libraries(cgfw_tests PRIVATE GTest::gtest_main cgfw rgfw::rgfw) # one process: RGFW keeps one global state add_test(NAME cgfw_tests COMMAND cgfw_tests) diff --git a/cgfw/tests/src/window/event_test.cpp b/cgfw/tests/src/window/event_test.cpp new file mode 100644 index 00000000..4dfdc02b --- /dev/null +++ b/cgfw/tests/src/window/event_test.cpp @@ -0,0 +1,336 @@ +#include "test.hpp" + +#include "window/rgfw_event.hpp" + +#include + +#include +#include +#include +#include +#include + + +namespace cgfw::dev { +namespace { + using cth::io::Axis; + using cth::io::axis_update; + using cth::io::ex_key; + using cth::io::Key; + using cth::io::key_update; + using std::chrono::milliseconds; + + constexpr uint32_t OS_NOW = 100'000; + + /** + * fixed clocks: the tests know the time points + */ + [[nodiscard]] input_clock test_clock() { + return input_clock{.now = cth::chrono::time_point_t{std::chrono::hours{1}}, .osNow = OS_NOW}; + } + + /** + * `A` gives `a`, `Q` gives `€`, the other keys give none + */ + [[nodiscard]] u32 test_key_char(RGFW_key key) { + if(key == RGFW_keyA) + return 'a'; + if(key == RGFW_keyQ) + return U'\x20AC'; + return 0; + } + + [[nodiscard]] std::optional convert(RGFW_event const& rgfwEvent) { + return to_event(rgfwEvent, test_clock(), &test_key_char); + } + + [[nodiscard]] RGFW_event key_event(RGFW_eventType type, RGFW_key key, bool repeat, uint32_t time) { + RGFW_event rgfwEvent{}; + rgfwEvent.key.type = type; + rgfwEvent.key.value = key; + rgfwEvent.key.repeat = repeat ? RGFW_TRUE : RGFW_FALSE; + rgfwEvent.key.state = type == RGFW_keyPressed ? RGFW_TRUE : RGFW_FALSE; + rgfwEvent.key.time = time; + return rgfwEvent; + } + + [[nodiscard]] RGFW_event button_event(RGFW_eventType type, RGFW_mouseButton button, uint32_t time) { + RGFW_event rgfwEvent{}; + rgfwEvent.button.type = type; + rgfwEvent.button.value = button; + rgfwEvent.button.state = type == RGFW_mouseButtonPressed ? RGFW_TRUE : RGFW_FALSE; + rgfwEvent.button.time = time; + return rgfwEvent; + } + + [[nodiscard]] RGFW_event type_event(RGFW_eventType type) { + RGFW_event rgfwEvent{}; + rgfwEvent.common.type = type; + return rgfwEvent; + } +} + +CGFW_TEST(to_ex_key, letters_and_digits) { + static_assert(to_ex_key(RGFW_keyA) == ex_key{Key::A}); + static_assert(to_ex_key(RGFW_keyZ) == ex_key{Key::Z}); + static_assert(to_ex_key(RGFW_key0) == ex_key{Key::DIGIT_0}); + static_assert(to_ex_key(RGFW_key9) == ex_key{Key::DIGIT_9}); +} + +CGFW_TEST(to_ex_key, symbols_by_us_position) { + static_assert(to_ex_key(RGFW_keyBacktick) == ex_key{Key::BACKTICK}); + static_assert(to_ex_key(RGFW_keyMinus) == ex_key{Key::MINUS}); + static_assert(to_ex_key(RGFW_keyEqual) == ex_key{Key::EQUAL}); + static_assert(to_ex_key(RGFW_keyBracket) == ex_key{Key::OPEN_BRACKET}); + static_assert(to_ex_key(RGFW_keyCloseBracket) == ex_key{Key::CLOSE_BRACKET}); + static_assert(to_ex_key(RGFW_keyBackSlash) == ex_key{Key::BACKSLASH}); + static_assert(to_ex_key(RGFW_keySemicolon) == ex_key{Key::SEMICOLON}); + static_assert(to_ex_key(RGFW_keyApostrophe) == ex_key{Key::QUOTE}); + static_assert(to_ex_key(RGFW_keyComma) == ex_key{Key::COMMA}); + static_assert(to_ex_key(RGFW_keyPeriod) == ex_key{Key::PERIOD}); + static_assert(to_ex_key(RGFW_keySlash) == ex_key{Key::SLASH}); + static_assert(to_ex_key(RGFW_keyWorld1) == ex_key{Key::LESS_THAN}); +} + +CGFW_TEST(to_ex_key, editing_and_navigation) { + static_assert(to_ex_key(RGFW_keyEscape) == ex_key{Key::ESCAPE}); + static_assert(to_ex_key(RGFW_keyBackSpace) == ex_key{Key::BACKSPACE}); + static_assert(to_ex_key(RGFW_keyTab) == ex_key{Key::TAB}); + static_assert(to_ex_key(RGFW_keyReturn) == ex_key{Key::ENTER}); + static_assert(to_ex_key(RGFW_keySpace) == ex_key{Key::SPACE}); + static_assert(to_ex_key(RGFW_keyDelete) == ex_key{Key::DELETE}); + static_assert(to_ex_key(RGFW_keyInsert) == ex_key{Key::INSERT}); + static_assert(to_ex_key(RGFW_keyHome) == ex_key{Key::HOME}); + static_assert(to_ex_key(RGFW_keyEnd) == ex_key{Key::END}); + static_assert(to_ex_key(RGFW_keyPageUp) == ex_key{Key::PAGE_UP}); + static_assert(to_ex_key(RGFW_keyPageDown) == ex_key{Key::PAGE_DOWN}); + static_assert(to_ex_key(RGFW_keyUp) == ex_key{Key::ARROW_UP}); + static_assert(to_ex_key(RGFW_keyDown) == ex_key{Key::ARROW_DOWN}); + static_assert(to_ex_key(RGFW_keyLeft) == ex_key{Key::ARROW_LEFT}); + static_assert(to_ex_key(RGFW_keyRight) == ex_key{Key::ARROW_RIGHT}); +} + +CGFW_TEST(to_ex_key, function_and_system_keys) { + static_assert(to_ex_key(RGFW_keyF1) == ex_key{Key::F1}); + static_assert(to_ex_key(RGFW_keyF12) == ex_key{Key::F12}); + static_assert(to_ex_key(RGFW_keyF13) == ex_key{Key::F13}); + static_assert(to_ex_key(RGFW_keyF24) == ex_key{Key::F24}); + static_assert(to_ex_key(RGFW_keyCapsLock) == ex_key{Key::CAPS_LOCK}); + static_assert(to_ex_key(RGFW_keyNumLock) == ex_key{Key::NUM_LOCK}); + static_assert(to_ex_key(RGFW_keyScrollLock) == ex_key{Key::SCROLL_LOCK}); + static_assert(to_ex_key(RGFW_keyPrintScreen) == ex_key{Key::PRINT_SCREEN}); + static_assert(to_ex_key(RGFW_keyPause) == ex_key{Key::PAUSE}); + static_assert(to_ex_key(RGFW_keyMenu) == ex_key{Key::MENU}); +} + +CGFW_TEST(to_ex_key, modifiers_set_right_for_the_right_copy) { + static_assert(to_ex_key(RGFW_keyShiftL) == ex_key{Key::SHIFT}); + static_assert(to_ex_key(RGFW_keyShiftR) == ex_key{Key::SHIFT, true}); + static_assert(to_ex_key(RGFW_keyControlL) == ex_key{Key::CONTROL}); + static_assert(to_ex_key(RGFW_keyControlR) == ex_key{Key::CONTROL, true}); + static_assert(to_ex_key(RGFW_keyAltL) == ex_key{Key::ALT}); + static_assert(to_ex_key(RGFW_keyAltR) == ex_key{Key::ALT, true}); + static_assert(to_ex_key(RGFW_keySuperL) == ex_key{Key::PLATFORM}); + static_assert(to_ex_key(RGFW_keySuperR) == ex_key{Key::PLATFORM, true}); +} + +CGFW_TEST(to_ex_key, keypad_is_the_main_key_and_right) { + static_assert(to_ex_key(RGFW_keyPad0) == ex_key{Key::DIGIT_0, true}); + static_assert(to_ex_key(RGFW_keyPad1) == ex_key{Key::DIGIT_1, true}); + static_assert(to_ex_key(RGFW_keyPad9) == ex_key{Key::DIGIT_9, true}); + static_assert(to_ex_key(RGFW_keyPadPeriod) == ex_key{Key::PERIOD, true}); + static_assert(to_ex_key(RGFW_keyPadSlash) == ex_key{Key::SLASH, true}); + static_assert(to_ex_key(RGFW_keyPadMultiply) == ex_key{Key::STAR, true}); + static_assert(to_ex_key(RGFW_keyPadMinus) == ex_key{Key::MINUS, true}); + static_assert(to_ex_key(RGFW_keyPadPlus) == ex_key{Key::PLUS, true}); + static_assert(to_ex_key(RGFW_keyPadEqual) == ex_key{Key::EQUAL, true}); + static_assert(to_ex_key(RGFW_keyPadReturn) == ex_key{Key::ENTER, true}); +} + +CGFW_TEST(to_ex_key, keys_without_a_cth_key) { + static_assert(!to_ex_key(RGFW_keyNULL).has_value()); + static_assert(!to_ex_key(RGFW_keyF25).has_value()); + static_assert(!to_ex_key(RGFW_keyWorld2).has_value()); +} + +CGFW_TEST(to_mouse_key, buttons) { + static_assert(to_mouse_key(RGFW_mouseLeft) == Key::MOUSE_LEFT); + static_assert(to_mouse_key(RGFW_mouseRight) == Key::MOUSE_RIGHT); + static_assert(to_mouse_key(RGFW_mouseMiddle) == Key::MOUSE_MIDDLE); + static_assert(to_mouse_key(RGFW_mouseMisc1) == Key::MOUSE_4); + static_assert(to_mouse_key(RGFW_mouseMisc2) == Key::MOUSE_5); + static_assert(!to_mouse_key(RGFW_mouseMisc3).has_value()); +} + +CGFW_TEST(to_utf8, one_to_four_bytes) { + static_assert(to_utf8(U'\x20AC') == "\xE2\x82\xAC"); + + EXPECT_EQ(to_utf8(U'a'), "a"); + EXPECT_EQ(to_utf8(U'\r'), "\r"); + EXPECT_EQ(to_utf8(U'\x7F'), "\x7F"); + EXPECT_EQ(to_utf8(U'\xDF'), "\xC3\x9F"); + EXPECT_EQ(to_utf8(U'\x7FF'), "\xDF\xBF"); + EXPECT_EQ(to_utf8(U'\x20AC'), "\xE2\x82\xAC"); + EXPECT_EQ(to_utf8(U'\xFFFF'), "\xEF\xBF\xBF"); + EXPECT_EQ(to_utf8(U'\x1F600'), "\xF0\x9F\x98\x80"); + EXPECT_EQ(to_utf8(U'\x10FFFF'), "\xF4\x8F\xBF\xBF"); +} + +CGFW_TEST(to_utf8, no_scalar_value_is_empty) { + EXPECT_EQ(to_utf8(0), ""); + EXPECT_EQ(to_utf8(char32_t{0xD800}), ""); + EXPECT_EQ(to_utf8(char32_t{0xDFFF}), ""); + EXPECT_EQ(to_utf8(char32_t{0x110000}), ""); +} + +CGFW_TEST(input_clock, time_point_is_now_minus_the_age) { + auto const clock = test_clock(); + + EXPECT_EQ(clock.timePoint(OS_NOW), clock.now); + EXPECT_EQ(clock.timePoint(OS_NOW - 16), clock.now - milliseconds{16}); +} + +CGFW_TEST(input_clock, age_is_right_across_the_wrap) { + constexpr input_clock clock{.now = cth::chrono::time_point_t{std::chrono::hours{1}}, .osNow = 5}; + static_assert(clock.timePoint(0xFFFF'FFF6) == clock.now - milliseconds{15}); + + EXPECT_EQ(clock.timePoint(0xFFFF'FFF6), clock.now - milliseconds{15}); +} + +CGFW_TEST(input_clock, no_os_time_and_a_time_after_now_give_now) { + auto const clock = test_clock(); + + EXPECT_EQ(clock.timePoint(0), clock.now); + EXPECT_EQ(clock.timePoint(OS_NOW + 10), clock.now); +} + +CGFW_TEST(input_clock, now_reads_both_clocks) { + auto const before = cth::chrono::clock_t::now(); + auto const clock = input_clock::Now(); + + EXPECT_GE(clock.now, before); + EXPECT_EQ(clock.timePoint(clock.osNow), clock.now); +} + +CGFW_TEST(to_event, key_press) { + auto const event = convert(key_event(RGFW_keyPressed, RGFW_keyA, false, OS_NOW - 5)); + + ASSERT_TRUE(event.has_value()); + ASSERT_TRUE(std::holds_alternative(*event)); + EXPECT_EQ( + std::get(*event), + (key_update{.data = {ex_key{Key::A}, true, "a", false}, .time = test_clock().now - milliseconds{5}}) + ); +} + +CGFW_TEST(to_event, key_release_and_repeat) { + auto const release = convert(key_event(RGFW_keyReleased, RGFW_keyQ, false, OS_NOW)); + auto const repeat = convert(key_event(RGFW_keyPressed, RGFW_keyQ, true, OS_NOW)); + + ASSERT_TRUE(release.has_value() && repeat.has_value()); + EXPECT_EQ( + std::get(*release).data, + (cth::io::key_state{ex_key{Key::Q}, false, "\xE2\x82\xAC", false}) + ); + EXPECT_EQ( + std::get(*repeat).data, + (cth::io::key_state{ex_key{Key::Q}, true, "\xE2\x82\xAC", true}) + ); +} + +CGFW_TEST(to_event, keypad_key_without_character) { + auto const event = convert(key_event(RGFW_keyPressed, RGFW_keyPadReturn, false, OS_NOW)); + + ASSERT_TRUE(event.has_value()); + EXPECT_EQ(std::get(*event).data, (cth::io::key_state{ex_key{Key::ENTER, true}, true})); +} + +CGFW_TEST(to_event, mouse_button) { + auto const press = convert(button_event(RGFW_mouseButtonPressed, RGFW_mouseMisc1, OS_NOW - 1)); + auto const release = convert(button_event(RGFW_mouseButtonReleased, RGFW_mouseLeft, OS_NOW)); + + ASSERT_TRUE(press.has_value() && release.has_value()); + EXPECT_EQ( + std::get(*press), + (key_update{.data = {Key::MOUSE_4, false, true}, .time = test_clock().now - milliseconds{1}}) + ); + EXPECT_EQ(std::get(*release).data, (cth::io::key_state{Key::MOUSE_LEFT, false, false})); +} + +CGFW_TEST(to_event, mouse_position) { + RGFW_event rgfwEvent{}; + rgfwEvent.mouse.type = RGFW_mouseMotion; + rgfwEvent.mouse.x = 12; + rgfwEvent.mouse.y = -3; + rgfwEvent.mouse.time = OS_NOW - 2; + + auto const event = convert(rgfwEvent); + + ASSERT_TRUE(event.has_value()); + EXPECT_EQ( + std::get(*event), + (axis_update{ + .data = {.axis = Axis::MOUSE_POSITION, .value = {12.f, -3.f}}, + .time = test_clock().now - milliseconds{2} + }) + ); +} + +CGFW_TEST(to_event, mouse_scroll) { + RGFW_event rgfwEvent{}; + rgfwEvent.delta.type = RGFW_mouseScroll; + rgfwEvent.delta.x = 0.5f; + rgfwEvent.delta.y = -1.f; + rgfwEvent.delta.time = OS_NOW; + + auto const event = convert(rgfwEvent); + + ASSERT_TRUE(event.has_value()); + EXPECT_EQ( + std::get(*event).data, + (cth::io::axis_state{.axis = Axis::MOUSE_SCROLL, .value = {0.5f, -1.f}}) + ); +} + +CGFW_TEST(to_event, key_char_is_text) { + RGFW_event rgfwEvent{}; + rgfwEvent.keyChar.type = RGFW_keyChar; + rgfwEvent.keyChar.value = U'\x1F600'; + rgfwEvent.keyChar.time = OS_NOW - 3; + + auto const event = convert(rgfwEvent); + + ASSERT_TRUE(event.has_value()); + EXPECT_EQ( + std::get(*event), + (TextEvent{.text = "\xF0\x9F\x98\x80", .time = test_clock().now - milliseconds{3}}) + ); +} + +CGFW_TEST(to_event, focus_takes_the_time_of_the_conversion) { + auto const in = convert(type_event(RGFW_windowFocusIn)); + auto const out = convert(type_event(RGFW_windowFocusOut)); + + ASSERT_TRUE(in.has_value() && out.has_value()); + EXPECT_EQ(std::get(*in), (FocusEvent{.focused = true, .time = test_clock().now})); + EXPECT_EQ(std::get(*out), (FocusEvent{.focused = false, .time = test_clock().now})); +} + +CGFW_TEST(to_event, skips_events_without_a_window_event) { + EXPECT_FALSE(convert(key_event(RGFW_keyPressed, RGFW_keyWorld2, false, OS_NOW)).has_value()); + EXPECT_FALSE(convert(button_event(RGFW_mouseButtonPressed, RGFW_mouseMisc3, OS_NOW)).has_value()); + + RGFW_event rawMotion{}; + rawMotion.delta.type = RGFW_mouseRawMotion; + EXPECT_FALSE(convert(rawMotion).has_value()); + + RGFW_event noCharacter{}; + noCharacter.keyChar.type = RGFW_keyChar; + noCharacter.keyChar.value = 0xD800; + EXPECT_FALSE(convert(noCharacter).has_value()); + + EXPECT_FALSE(convert(type_event(RGFW_windowResized)).has_value()); + EXPECT_FALSE(convert(type_event(RGFW_windowClose)).has_value()); + EXPECT_FALSE(convert(type_event(RGFW_mouseEnter)).has_value()); +} +} diff --git a/cgfw/tests/src/window/window_test.cpp b/cgfw/tests/src/window/window_test.cpp index 66b9be05..1d33bb2d 100644 --- a/cgfw/tests/src/window/window_test.cpp +++ b/cgfw/tests/src/window/window_test.cpp @@ -23,6 +23,12 @@ CGFW_TEST(Window, base_constructor_does_not_create) { EXPECT_EQ(window.config().title, test::window_config().title); } +CGFW_TEST(Window, events_are_empty_before_poll_events) { + Window const window{test::window_config()}; + + EXPECT_TRUE(window.events().empty()); +} + CGFW_TEST(Window, create_and_destroy) { CGFW_SKIP_WITHOUT_DISPLAY(); Window window{test::window_config()}; @@ -63,7 +69,7 @@ CGFW_TEST(Window, move_keeps_the_window) { Window window{test::window_config(), create}; auto const rgfwWindow = window.get(); - Window const moved{std::move(window)}; + Window moved{std::move(window)}; EXPECT_FALSE(window.created()); EXPECT_EQ(moved.get(), rgfwWindow); @@ -73,7 +79,7 @@ CGFW_TEST(Window, move_keeps_the_window) { CGFW_TEST(Window, poll_events_returns_without_events) { CGFW_SKIP_WITHOUT_DISPLAY(); - Window const window{test::window_config(), create}; + Window window{test::window_config(), create}; // a render loop polls every frame: no wait for an event, the bound is far above a poll auto const start = std::chrono::steady_clock::now(); @@ -99,7 +105,7 @@ CGFW_TEST(Window, move_assignment_destroys_the_old_window) { CGFW_TEST(Window, windows_exist_at_the_same_time) { CGFW_SKIP_WITHOUT_DISPLAY(); - std::array const windows{ + std::array windows{ Window{test::window_config("first"), create}, Window{test::window_config("second"), create}, Window{test::window_config("third"), create}, @@ -149,7 +155,7 @@ CGFW_TEST(Window, surface_of_an_instance_with_the_extensions) { CGFW_TEST(Window, extent_is_the_size_of_the_window) { CGFW_SKIP_WITHOUT_DISPLAY(); - Window const window{test::window_config(), create}; + Window window{test::window_config(), create}; window.pollEvents(); // the window manager can change the size of the config, a tiling one does @@ -162,7 +168,7 @@ CGFW_TEST(Window, extent_is_the_size_of_the_window) { CGFW_TEST(Window, extent_callback_of_the_surface_reads_the_window) { CGFW_SKIP_WITHOUT_DISPLAY(); test::InstanceContext const context{}; - Window const window{test::window_config(), create}; + Window window{test::window_config(), create}; window.pollEvents(); auto surface = window.surface(context.instance); diff --git a/demo/cube/src/main.cpp b/demo/cube/src/main.cpp index 7467d33f..3757f2a3 100644 --- a/demo/cube/src/main.cpp +++ b/demo/cube/src/main.cpp @@ -282,7 +282,7 @@ struct Cube { * @details only the scopes: the `jvk::scoped_submit` ends first and submits, then the `jvk::scoped_acquire` presents */ cth::co::executor_task draw_frames( - cgfw::Window const& window, + cgfw::Window& window, jvk::Core const& core, jvk::StageGraph& graph, jvk::Presenter& presenter, @@ -401,7 +401,7 @@ cth::co::executor_task draw_frames( */ void run() { cvk::Cvk const cvk{}; - cgfw::Window const window{{.title = "cube", .extent = WINDOW_EXTENT}, cgfw::create}; + cgfw::Window window{{.title = "cube", .extent = WINDOW_EXTENT}, cgfw::create}; // the surface extensions of the window and the instance extensions of a present queue auto extensions = cgfw::instance_extensions(); diff --git a/demo/triangle/src/main.cpp b/demo/triangle/src/main.cpp index 671d91b0..f093e29b 100644 --- a/demo/triangle/src/main.cpp +++ b/demo/triangle/src/main.cpp @@ -86,7 +86,7 @@ struct MsaaTarget { * @details only the scopes: the `jvk::scoped_submit` ends first and submits, then the `jvk::scoped_acquire` presents */ cth::co::executor_task draw_frames( - cgfw::Window const& window, + cgfw::Window& window, jvk::Core const& core, jvk::StageGraph& graph, jvk::Presenter& presenter, @@ -145,7 +145,7 @@ cth::co::executor_task draw_frames( */ void run() { cvk::Cvk const cvk{}; - cgfw::Window const window{{.title = "triangle", .extent = WINDOW_EXTENT}, cgfw::create}; + cgfw::Window window{{.title = "triangle", .extent = WINDOW_EXTENT}, cgfw::create}; // the surface extensions of the window and the instance extensions of a present queue auto extensions = cgfw::instance_extensions(); diff --git a/lib/cmake/rgfw.cmake b/lib/cmake/rgfw.cmake index 10b87a11..1dc38686 100644 --- a/lib/cmake/rgfw.cmake +++ b/lib/cmake/rgfw.cmake @@ -16,6 +16,9 @@ if (NOT TARGET rgfw::rgfw) target_include_directories(rgfw INTERFACE "${RGFW_DIR}") # RGFWDEF empty: the functions have external linkage, the default inline needs the definitions in every user target_compile_definitions(rgfw INTERFACE RGFW_VULKAN "RGFWDEF=") + # the queue holds the events of every window between two polls, a full queue drops all events + # the default 32 fills with the mouse motion of one frame + target_compile_definitions(rgfw INTERFACE "RGFW_MAX_EVENTS=1024") if (WIN32) # RGFW includes windows.h: no min and max macros diff --git a/lib/rgfw b/lib/rgfw index 04542bac..e81924e8 160000 --- a/lib/rgfw +++ b/lib/rgfw @@ -1 +1 @@ -Subproject commit 04542bac7e4cf174bba120d048580a8cdc7c1b3b +Subproject commit e81924e858a420cacd63bdf0eed2a5a808b9e4a1 From d8329284b0fa6d39cc76e1a5989facb320d44185 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:21:09 +0100 Subject: [PATCH 07/68] cgfw: Key::DELETE next to windows.h, which defines DELETE --- cgfw/src/window/rgfw_event.hpp | 4 ++++ cgfw/tests/src/window/event_test.cpp | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/cgfw/src/window/rgfw_event.hpp b/cgfw/src/window/rgfw_event.hpp index aa0bb8fe..279b02a6 100644 --- a/cgfw/src/window/rgfw_event.hpp +++ b/cgfw/src/window/rgfw_event.hpp @@ -157,7 +157,11 @@ constexpr std::optional to_ex_key(RGFW_key key) { case RGFW_keyApostrophe: return ex_key{Key::QUOTE}; case RGFW_keyBackSlash: return ex_key{Key::BACKSLASH}; case RGFW_keyReturn: return ex_key{Key::ENTER}; +// windows.h defines DELETE +#pragma push_macro("DELETE") +#undef DELETE case RGFW_keyDelete: return ex_key{Key::DELETE}; +#pragma pop_macro("DELETE") case RGFW_keyWorld1: return ex_key{Key::LESS_THAN}; case RGFW_keyCapsLock: return ex_key{Key::CAPS_LOCK}; diff --git a/cgfw/tests/src/window/event_test.cpp b/cgfw/tests/src/window/event_test.cpp index 4dfdc02b..0452d987 100644 --- a/cgfw/tests/src/window/event_test.cpp +++ b/cgfw/tests/src/window/event_test.cpp @@ -98,7 +98,11 @@ CGFW_TEST(to_ex_key, editing_and_navigation) { static_assert(to_ex_key(RGFW_keyTab) == ex_key{Key::TAB}); static_assert(to_ex_key(RGFW_keyReturn) == ex_key{Key::ENTER}); static_assert(to_ex_key(RGFW_keySpace) == ex_key{Key::SPACE}); +// windows.h defines DELETE +#pragma push_macro("DELETE") +#undef DELETE static_assert(to_ex_key(RGFW_keyDelete) == ex_key{Key::DELETE}); +#pragma pop_macro("DELETE") static_assert(to_ex_key(RGFW_keyInsert) == ex_key{Key::INSERT}); static_assert(to_ex_key(RGFW_keyHome) == ex_key{Key::HOME}); static_assert(to_ex_key(RGFW_keyEnd) == ex_key{Key::END}); From 7dc769759f9b78a7c408190097651827bdc181bb Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:28:49 +0100 Subject: [PATCH 08/68] rgfw: our fixes for keycodes, init and deinit, key repeat, Vulkan surface functions, window list, scroll - lib/rgfw: six fix branches of our fork, each off upstream for later PRs - rgfw.cmake: no Vulkan platform defines, RGFW.h keeps the Vulkan platform types in its implementation now --- lib/cmake/rgfw.cmake | 4 ---- lib/rgfw | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/lib/cmake/rgfw.cmake b/lib/cmake/rgfw.cmake index 1dc38686..a7fefa76 100644 --- a/lib/cmake/rgfw.cmake +++ b/lib/cmake/rgfw.cmake @@ -23,14 +23,10 @@ if (NOT TARGET rgfw::rgfw) if (WIN32) # RGFW includes windows.h: no min and max macros target_compile_definitions(rgfw INTERFACE NOMINMAX) - # the Vulkan types of the surface in RGFW.h: vulkan.h can come before RGFW.h, empty like the define of RGFW - target_compile_definitions(rgfw INTERFACE "VK_USE_PLATFORM_WIN32_KHR=") # RGFW loads winmm, dwmapi, shcore and opengl32 at run time, advapi32 reads the registry target_link_libraries(rgfw INTERFACE gdi32 user32 shell32 advapi32) elseif (CMAKE_SYSTEM_NAME STREQUAL "Linux") target_compile_definitions(rgfw INTERFACE RGFW_WAYLAND RGFW_NO_X11) - # the Vulkan types of the surface in RGFW.h: vulkan.h can come before RGFW.h, empty like the define of RGFW - target_compile_definitions(rgfw INTERFACE "VK_USE_PLATFORM_WAYLAND_KHR=") # wayland and xkbcommon come from the system, the vcpkg ports of them are empty on linux find_package(PkgConfig REQUIRED) diff --git a/lib/rgfw b/lib/rgfw index e81924e8..2df67538 160000 --- a/lib/rgfw +++ b/lib/rgfw @@ -1 +1 @@ -Subproject commit e81924e858a420cacd63bdf0eed2a5a808b9e4a1 +Subproject commit 2df67538a329f7c7bae0a25076cfd58d40b73b6c From 60e4945b21ede99419acab0110ae72d2315b088b Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:56:57 +0100 Subject: [PATCH 09/68] cgfw: Key::DEL, no DELETE guards; lib: cth with Key::DEL, rgfw with the waiting PR texts --- cgfw/src/window/rgfw_event.hpp | 6 +----- cgfw/tests/src/window/event_test.cpp | 6 +----- lib/cth | 2 +- lib/rgfw | 2 +- 4 files changed, 4 insertions(+), 12 deletions(-) diff --git a/cgfw/src/window/rgfw_event.hpp b/cgfw/src/window/rgfw_event.hpp index 279b02a6..4abaffd1 100644 --- a/cgfw/src/window/rgfw_event.hpp +++ b/cgfw/src/window/rgfw_event.hpp @@ -157,11 +157,7 @@ constexpr std::optional to_ex_key(RGFW_key key) { case RGFW_keyApostrophe: return ex_key{Key::QUOTE}; case RGFW_keyBackSlash: return ex_key{Key::BACKSLASH}; case RGFW_keyReturn: return ex_key{Key::ENTER}; -// windows.h defines DELETE -#pragma push_macro("DELETE") -#undef DELETE - case RGFW_keyDelete: return ex_key{Key::DELETE}; -#pragma pop_macro("DELETE") + case RGFW_keyDelete: return ex_key{Key::DEL}; case RGFW_keyWorld1: return ex_key{Key::LESS_THAN}; case RGFW_keyCapsLock: return ex_key{Key::CAPS_LOCK}; diff --git a/cgfw/tests/src/window/event_test.cpp b/cgfw/tests/src/window/event_test.cpp index 0452d987..30fce454 100644 --- a/cgfw/tests/src/window/event_test.cpp +++ b/cgfw/tests/src/window/event_test.cpp @@ -98,11 +98,7 @@ CGFW_TEST(to_ex_key, editing_and_navigation) { static_assert(to_ex_key(RGFW_keyTab) == ex_key{Key::TAB}); static_assert(to_ex_key(RGFW_keyReturn) == ex_key{Key::ENTER}); static_assert(to_ex_key(RGFW_keySpace) == ex_key{Key::SPACE}); -// windows.h defines DELETE -#pragma push_macro("DELETE") -#undef DELETE - static_assert(to_ex_key(RGFW_keyDelete) == ex_key{Key::DELETE}); -#pragma pop_macro("DELETE") + static_assert(to_ex_key(RGFW_keyDelete) == ex_key{Key::DEL}); static_assert(to_ex_key(RGFW_keyInsert) == ex_key{Key::INSERT}); static_assert(to_ex_key(RGFW_keyHome) == ex_key{Key::HOME}); static_assert(to_ex_key(RGFW_keyEnd) == ex_key{Key::END}); diff --git a/lib/cth b/lib/cth index a6256e47..c4e62452 160000 --- a/lib/cth +++ b/lib/cth @@ -1 +1 @@ -Subproject commit a6256e47caa7c4abf9167a9ca446cecd47c687c9 +Subproject commit c4e62452d9c133a5cb7a060d5ff18e79607c4630 diff --git a/lib/rgfw b/lib/rgfw index 2df67538..482af80a 160000 --- a/lib/rgfw +++ b/lib/rgfw @@ -1 +1 @@ -Subproject commit 2df67538a329f7c7bae0a25076cfd58d40b73b6c +Subproject commit 482af80a4a95ff4e5339e0b8dd11db72fdec5d75 From 1cfee16d60640479df8d84e22bc5c35f026b7881 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:29:45 +0100 Subject: [PATCH 10/68] timgui: ImGui and ImPlot on jvk and cgfw, the cube demo shows the frame time - Imgui: one per window, owns the ImGui and ImPlot contexts, the pipeline and the ImGui textures - frame() and Frame::render(), the input of window.events(), letters and digits by the layout - upload() and draw() for primary and secondary command buffers, the textures ready to sample before the rendering - the shaders compiled into the library, vertex pulling, sRGB targets get linear vertex colors --- AGENTS.md | 1 + CMakeLists.txt | 1 + Doxyfile | 2 +- demo/cube/CMakeLists.txt | 2 +- demo/cube/src/main.cpp | 41 +- timgui/CMakeLists.txt | 81 ++++ timgui/cmake/spirv_header.cmake | 59 +++ timgui/incl/timgui/imgui.hpp | 168 ++++++++ timgui/shaders/imgui.frag | 16 + timgui/shaders/imgui.glsl | 27 ++ timgui/shaders/imgui.vert | 29 ++ timgui/src/imgui.cpp | 547 +++++++++++++++++++++++++++ timgui/src/input.cpp | 47 +++ timgui/src/input.hpp | 212 +++++++++++ timgui/src/pch/glob/cth.hpp | 5 + timgui/src/pch/glob/imgui.hpp | 2 + timgui/src/pch/glob/implot.hpp | 2 + timgui/src/pch/glob/std.hpp | 11 + timgui/src/pch/glob/volk.hpp | 2 + timgui/src/pch/pch.hpp | 8 + timgui/tests/CMakeLists.txt | 24 ++ timgui/tests/src/context.cpp | 50 +++ timgui/tests/src/context.hpp | 47 +++ timgui/tests/src/environment.cpp | 26 ++ timgui/tests/src/imgui_test.cpp | 425 +++++++++++++++++++++ timgui/tests/src/input_test.cpp | 332 ++++++++++++++++ timgui/tests/src/pch/glob/gtest.hpp | 2 + timgui/tests/src/pch/glob/imgui.hpp | 2 + timgui/tests/src/pch/glob/implot.hpp | 2 + timgui/tests/src/pch/pch.hpp | 7 + timgui/tests/src/test.hpp | 60 +++ vcpkg.json | 2 + 32 files changed, 2236 insertions(+), 6 deletions(-) create mode 100644 timgui/CMakeLists.txt create mode 100644 timgui/cmake/spirv_header.cmake create mode 100644 timgui/incl/timgui/imgui.hpp create mode 100644 timgui/shaders/imgui.frag create mode 100644 timgui/shaders/imgui.glsl create mode 100644 timgui/shaders/imgui.vert create mode 100644 timgui/src/imgui.cpp create mode 100644 timgui/src/input.cpp create mode 100644 timgui/src/input.hpp create mode 100644 timgui/src/pch/glob/cth.hpp create mode 100644 timgui/src/pch/glob/imgui.hpp create mode 100644 timgui/src/pch/glob/implot.hpp create mode 100644 timgui/src/pch/glob/std.hpp create mode 100644 timgui/src/pch/glob/volk.hpp create mode 100644 timgui/src/pch/pch.hpp create mode 100644 timgui/tests/CMakeLists.txt create mode 100644 timgui/tests/src/context.cpp create mode 100644 timgui/tests/src/context.hpp create mode 100644 timgui/tests/src/environment.cpp create mode 100644 timgui/tests/src/imgui_test.cpp create mode 100644 timgui/tests/src/input_test.cpp create mode 100644 timgui/tests/src/pch/glob/gtest.hpp create mode 100644 timgui/tests/src/pch/glob/imgui.hpp create mode 100644 timgui/tests/src/pch/glob/implot.hpp create mode 100644 timgui/tests/src/pch/pch.hpp create mode 100644 timgui/tests/src/test.hpp diff --git a/AGENTS.md b/AGENTS.md index 699ac0a3..401dad40 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,6 +10,7 @@ Read it before you change a file. Match the existing code. | `cvk/` | C++ wrapper of the Vulkan C API: one class per Vulkan object, objects own their handle | | `cgfw/` | C++ wrapper of RGFW: windows of the platform (Win32, Wayland) and their Vulkan surface | | `jvk/` | coroutine layer on top of `cvk` (in progress): threads, queues, stage graph, object lifetimes | +| `timgui/` | ImGui on `jvk` and `cgfw`: input from a window, draws into a rendering | | `tests/` | loader smoke tests | | `lib/cth` | cth (submodule), `lib/cmake/cth.cmake` adds it with only the components the engine needs | | `lib/cth_cmake` | cmake utilities (submodule) | diff --git a/CMakeLists.txt b/CMakeLists.txt index e2416f9d..0ca94481 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,6 +27,7 @@ endif () add_subdirectory(cvk) add_subdirectory(cgfw) add_subdirectory(jvk) +add_subdirectory(timgui) # Demos add_subdirectory(demo/triangle) diff --git a/Doxyfile b/Doxyfile index e8ab5a27..6f6e64a2 100644 --- a/Doxyfile +++ b/Doxyfile @@ -1,7 +1,7 @@ # only the values that differ from the doxygen defaults, run: doxygen (from the repository root) PROJECT_NAME = cth_engine OUTPUT_DIRECTORY = out/doxygen -INPUT = cvk/incl jvk/incl cgfw/incl +INPUT = cvk/incl jvk/incl cgfw/incl timgui/incl RECURSIVE = YES FILE_PATTERNS = *.hpp JAVADOC_AUTOBRIEF = YES diff --git a/demo/cube/CMakeLists.txt b/demo/cube/CMakeLists.txt index b7b5812e..ae4a5e08 100644 --- a/demo/cube/CMakeLists.txt +++ b/demo/cube/CMakeLists.txt @@ -13,7 +13,7 @@ add_executable(cube ${CUBE_SRC}) cth_target_enable_build_cache(cube OPTIONAL) -target_link_libraries(cube PRIVATE cgfw jvk glm::glm-header-only) +target_link_libraries(cube PRIVATE cgfw jvk timgui glm::glm-header-only) target_compile_definitions(cube PRIVATE GLM_FORCE_DEPTH_ZERO_TO_ONE) diff --git a/demo/cube/src/main.cpp b/demo/cube/src/main.cpp index 3757f2a3..7b589239 100644 --- a/demo/cube/src/main.cpp +++ b/demo/cube/src/main.cpp @@ -10,6 +10,8 @@ #include "jvk/graph/stage.hpp" #include "jvk/graph/stage_graph.hpp" +#include "timgui/imgui.hpp" + #include "cgfw/window/window.hpp" #include "cvk/base/cvk.hpp" @@ -32,6 +34,8 @@ #include #include +#include + #include #include #include @@ -278,8 +282,22 @@ struct Cube { }; /** - * draws the spinning cube in every frame until the window closes - * @details only the scopes: the `jvk::scoped_submit` ends first and submits, then the `jvk::scoped_acquire` presents + * ImGui window with the frame time and the frames per second + */ +void stats_window() { + auto const framerate = ImGui::GetIO().Framerate; + ImGui::Begin("stats"); + ImGui::Text("%.2f ms", 1000.f / framerate); + ImGui::Text("%.0f fps", framerate); + ImGui::End(); +} + +/** + * draws the spinning cube and the ImGui window in every frame until the window closes + * @details + * - only the scopes: the `jvk::scoped_submit` ends first and submits + * - then the `jvk::scoped_acquire` presents + * - the ImGui frame comes first: it takes the events also in a frame without an image */ cth::co::executor_task draw_frames( cgfw::Window& window, @@ -288,6 +306,7 @@ cth::co::executor_task draw_frames( jvk::Presenter& presenter, cvk::GraphicsPipeline const& pipeline, Cube const& cube, + timgui::Imgui& imgui, std::optional& targetsOpt ) { bool uploaded = false; @@ -296,6 +315,10 @@ cth::co::executor_task draw_frames( while(!window.shouldClose()) { window.pollEvents(); + auto imguiFrame = imgui.frame(); + stats_window(); + auto& drawData = imguiFrame.render(); + auto& stage = (co_await graph.nextFrame()).stage(CUBE_STAGE_ID); auto const image = co_await presenter.acquire( @@ -353,6 +376,7 @@ cth::co::executor_task draw_frames( cube.upload(stage, *submit); uploaded = true; } + imgui.upload(stage, *submit, drawData); submit->use(cube.sampled, VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT); submit->use( cube.vertices, @@ -390,13 +414,16 @@ cth::co::executor_task draw_frames( submit->bindIndices(cube.indices); submit->pushData(draw); submit->drawIndexed(36); + + // the rendering of the cube: the formats and samples of the targets + imgui.draw(stage, *submit, drawData); } } /** * creates the window, the vulkan objects, the cube and the pipeline, then draws until the window closes * @details the declaration order is the destruction order backwards: - * - the cube, the pipeline and the targets live until `~StageGraph()` waited for the gpu + * - the cube, the pipeline, the ImGui and the targets live until `~StageGraph()` waited for the gpu * - the presenter is destroyed before the graph: its present jobs wait for the semaphores of the graph */ void run() { @@ -445,6 +472,12 @@ void run() { pipelineConfig.descriptorMappings.append_range(core.samplerHeap().mappings()); cvk::GraphicsPipeline const pipeline{core, std::move(pipelineConfig), cvk::create}; + timgui::Imgui imgui{ + core, + window, + {.colorFormat = SURFACE_FORMAT.format, .depthFormat = DEPTH_FORMAT, .samples = MSAA_SAMPLES} + }; + std::optional targetsOpt{}; jvk::StageGraph graph{core, {.stages = {{.queueIdx = QUEUE_IDX}}}}; jvk::Presenter presenter{ @@ -455,7 +488,7 @@ void run() { }; core.executor().sync_wait( - draw_frames(window, core, graph, presenter, pipeline, cube, targetsOpt) + draw_frames(window, core, graph, presenter, pipeline, cube, imgui, targetsOpt) ); } } diff --git a/timgui/CMakeLists.txt b/timgui/CMakeLists.txt new file mode 100644 index 00000000..a19c459b --- /dev/null +++ b/timgui/CMakeLists.txt @@ -0,0 +1,81 @@ +# glslc of the PATH or of the Vulkan SDK, without it no timgui: the Windows CI has none +cth_find_program(GLSLC_EXECUTABLE glslc OPTIONAL HINTS ENV VULKAN_SDK PATH_SUFFIXES bin) +if (NOT GLSLC_EXECUTABLE) + message(STATUS "glslc not found, no timgui") + return() +endif () + +find_package(imgui CONFIG REQUIRED) +find_package(implot CONFIG REQUIRED) + +cth_glob_cpp(TIMGUI_SRC "src") +cth_glob_cpp(TIMGUI_INCL "incl") + +add_library(timgui STATIC ${TIMGUI_SRC} ${TIMGUI_INCL}) + +cth_target_enable_build_cache(timgui OPTIONAL) + +# the SPIR-V of the shaders in generated headers, the library embeds it: no SPIR-V files at run time +set(TIMGUI_SHADER_DIR "${CMAKE_CURRENT_BINARY_DIR}/shaders") +set(TIMGUI_SHADER_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/shaders") +set(TIMGUI_GENERATED_SRC "${CMAKE_CURRENT_BINARY_DIR}/generated/src") +set(TIMGUI_SPIRV_HEADER_SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/cmake/spirv_header.cmake") +get_target_property(JVK_GLSL_INCLUDE_DIR jvk JVK_GLSL_INCLUDE_DIR) + +set(TIMGUI_GLSL "${TIMGUI_SHADER_SRC_DIR}/imgui.vert" "${TIMGUI_SHADER_SRC_DIR}/imgui.frag") +set(TIMGUI_GLSL_SHARED "${TIMGUI_SHADER_SRC_DIR}/imgui.glsl") +# the includes of the shaders: a change compiles them again +set(TIMGUI_GLSL_INCLUDES ${TIMGUI_GLSL_SHARED} "${JVK_GLSL_INCLUDE_DIR}/jvk/heaps.glsl") +set(TIMGUI_SHADER_HEADERS "") + +foreach (GLSL_FILE ${TIMGUI_GLSL}) + get_filename_component(GLSL_NAME ${GLSL_FILE} NAME) + # imgui.vert -> shaders/imgui_vert.hpp with IMGUI_VERT + string(REPLACE "." "_" HEADER_NAME ${GLSL_NAME}) + string(TOUPPER ${HEADER_NAME} ARRAY_NAME) + set(SPIRV_FILE "${TIMGUI_SHADER_DIR}/${GLSL_NAME}.spv") + set(HEADER_FILE "${TIMGUI_GENERATED_SRC}/shaders/${HEADER_NAME}.hpp") + + add_custom_command( + OUTPUT ${HEADER_FILE} + COMMAND ${CMAKE_COMMAND} -E make_directory ${TIMGUI_SHADER_DIR} + COMMAND ${GLSLC_EXECUTABLE} --target-env=vulkan1.3 -O + -I ${JVK_GLSL_INCLUDE_DIR} -I ${TIMGUI_SHADER_SRC_DIR} ${GLSL_FILE} -o ${SPIRV_FILE} + COMMAND ${CMAKE_COMMAND} + -DSPIRV_FILE=${SPIRV_FILE} -DHEADER_FILE=${HEADER_FILE} -DARRAY_NAME=${ARRAY_NAME} + -P ${TIMGUI_SPIRV_HEADER_SCRIPT} + DEPENDS ${GLSL_FILE} ${TIMGUI_GLSL_INCLUDES} ${TIMGUI_SPIRV_HEADER_SCRIPT} + COMMENT "Compiling ${GLSL_NAME}" + VERBATIM + ) + + list(APPEND TIMGUI_SHADER_HEADERS ${HEADER_FILE}) +endforeach () + +# the generated headers as sources: the build writes them before it compiles the library +target_sources(timgui PRIVATE ${TIMGUI_SHADER_HEADERS} ${TIMGUI_GLSL} ${TIMGUI_GLSL_SHARED}) + +target_include_directories( + timgui + PUBLIC incl + PRIVATE src "${TIMGUI_GENERATED_SRC}" +) + +target_precompile_headers( + timgui + PRIVATE + src/pch/pch.hpp +) + +# the public header declares cgfw::Window only +# implot before imgui: the implot target does not link imgui, a static link needs the order +target_link_libraries( + timgui + PUBLIC jvk implot::implot imgui::imgui + PRIVATE cgfw +) + +# tests +if (JOLLY_ENABLE_TESTS) + add_subdirectory(tests) +endif () diff --git a/timgui/cmake/spirv_header.cmake b/timgui/cmake/spirv_header.cmake new file mode 100644 index 00000000..943d3f39 --- /dev/null +++ b/timgui/cmake/spirv_header.cmake @@ -0,0 +1,59 @@ +# writes a SPIR-V file as a header with a constexpr array of its words, run: cmake -P +# -DSPIRV_FILE: the SPIR-V of glslc, little endian words +# -DHEADER_FILE: the header to write +# -DARRAY_NAME: the name of the array in timgui::dev::shaders + +foreach (VAR SPIRV_FILE HEADER_FILE ARRAY_NAME) + if (NOT DEFINED ${VAR}) + message(FATAL_ERROR "spirv_header.cmake: -D${VAR} is missing") + endif () +endforeach () + +file(READ "${SPIRV_FILE}" SPIRV_BYTES HEX) +string(LENGTH "${SPIRV_BYTES}" SPIRV_HEX_LENGTH) +math(EXPR SPIRV_REST "${SPIRV_HEX_LENGTH} % 8") +if (SPIRV_HEX_LENGTH EQUAL 0 OR NOT SPIRV_REST EQUAL 0) + message(FATAL_ERROR "spirv_header.cmake: ${SPIRV_FILE} is no sequence of 32 bit words") +endif () + +# 8 hex digits per word, the bytes of a word reversed: little endian +string(REGEX REPLACE "(..)(..)(..)(..)" "0x\\4\\3\\2\\1;" SPIRV_WORDS "${SPIRV_BYTES}") +list(POP_BACK SPIRV_WORDS) +list(GET SPIRV_WORDS 0 SPIRV_MAGIC) +if (NOT SPIRV_MAGIC STREQUAL "0x07230203") + message(FATAL_ERROR "spirv_header.cmake: ${SPIRV_FILE} has no little endian SPIR-V magic number") +endif () +list(LENGTH SPIRV_WORDS SPIRV_WORD_COUNT) + +# 8 words per line +set(SPIRV_LINES "") +set(SPIRV_LINE "") +set(SPIRV_LINE_WORDS 0) +foreach (WORD ${SPIRV_WORDS}) + string(APPEND SPIRV_LINE " ${WORD},") + math(EXPR SPIRV_LINE_WORDS "${SPIRV_LINE_WORDS} + 1") + if (SPIRV_LINE_WORDS EQUAL 8) + string(APPEND SPIRV_LINES " ${SPIRV_LINE}\n") + set(SPIRV_LINE "") + set(SPIRV_LINE_WORDS 0) + endif () +endforeach () +if (NOT SPIRV_LINE_WORDS EQUAL 0) + string(APPEND SPIRV_LINES " ${SPIRV_LINE}\n") +endif () + +get_filename_component(SPIRV_NAME "${SPIRV_FILE}" NAME) +file( + WRITE "${HEADER_FILE}" + "#pragma once\n" + "// generated by timgui/cmake/spirv_header.cmake from ${SPIRV_NAME}, do not edit\n" + "#include \n" + "#include \n" + "\n" + "\n" + "namespace timgui::dev::shaders {\n" + "inline constexpr std::array ${ARRAY_NAME}{\n" + "${SPIRV_LINES}" + "};\n" + "}\n" +) diff --git a/timgui/incl/timgui/imgui.hpp b/timgui/incl/timgui/imgui.hpp new file mode 100644 index 00000000..d8865c60 --- /dev/null +++ b/timgui/incl/timgui/imgui.hpp @@ -0,0 +1,168 @@ +#pragma once +#include "jvk/data/heap_idx.hpp" +#include "jvk/data/resource_heap.hpp" + +#include +#include +#include + +#include +#include +#include + + +namespace cgfw { +class Window; +} + +namespace jvk { +class Core; +class Stage; +class PrimaryCmdBuffer; +class SecondaryCmdBuffer; +} + +namespace timgui { +namespace dev { + struct ImguiState; + + /** + * command buffer that `Imgui` records into + * @details the .cpp of `Imgui` instantiates `upload()` and `draw()` for these two types + */ + template + concept cmd_buffer = std::same_as + || std::same_as; +} + +/** + * ImGui on a cgfw window, drawn with a jvk core + * @details + * - owns: the ImGui context, the ImPlot context, the pipeline, the ImGui textures (font atlas) + * - one object per window: input from the window, draws for its renderings + * - ImGui and ImPlot calls only inside a `Frame` of this object + * @attention one `Frame` at a time: ImGui and ImPlot keep the current context in a global + */ +class Imgui { +public: + struct Config; + class Frame; + + /** + * creates the ImGui context, the ImPlot context and the pipeline + * @details makes the contexts current + * @param window input and extent of the frames, outlives this object + * @pre the core has a resource heap and a sampler heap, see `jvk::HeapsConfig` + * @throws cvk::vk_result_exception result of the shader, pipeline or sampler creation + * @throws jvk::jvk_exception reason: every cell of the sampler heap is in use + */ + Imgui(jvk::Core const&, cgfw::Window const& window, Config const&); + + /** + * destroys the ImPlot context, the ImGui context, the pipeline and the textures + * @pre the gpu finished every frame that `draw()` recorded into, e.g. `~StageGraph()` waited + */ + ~Imgui(); + + /** + * starts an ImGui frame + * @details + * - makes the ImGui and the ImPlot context of this object current + * - passes the events of the last `cgfw::Window::pollEvents()` + * - passes the extent and the time since the last frame + * - calls `ImGui::NewFrame()` + * @pre no `Frame` of any `Imgui` exists + */ + [[nodiscard]] Frame frame(); + + /** + * records the texture requests of the draw data: create, update, destroy + * @details + * - copies through a staging buffer, `stage` retains it until the gpu finished + * - a destroyed texture goes to `stage` too + * - an update copies the whole texture + * - leaves the textures ready to sample in the fragment shader + * - `draw()` needs no barrier in its rendering + * @param stage of `cmd` + * @param cmd outside a rendering, before the `draw()` of `drawData` + * @param[out] drawData its textures get `ImTextureStatus_OK` or `ImTextureStatus_Destroyed` + */ + void upload(jvk::Stage& stage, dev::cmd_buffer auto& cmd, ImDrawData& drawData); + + /** + * records the draws of the draw data + * @details + * - writes the vertices and indices into host buffers + * - `stage` retains the buffers until the gpu finished + * - binds the pipeline, sets the viewport and a scissor per draw command + * - `TotalVtxCount == 0` or an empty framebuffer -> records nothing + * @param stage of `cmd` + * @param cmd inside a rendering with the formats and samples of `Config` + * @param drawData of `Frame::render()` + * @pre `upload()` of `drawData` before + */ + void draw(jvk::Stage& stage, dev::cmd_buffer auto& cmd, ImDrawData const& drawData) const; + + /** + * ImGui texture of an image of the resource heap, for `ImGui::Image()` + * @details the shader samples it with the sampler of this object + */ + [[nodiscard]] ImTextureRef texture(jvk::heap_idx imageIdx) const; + +private: + std::unique_ptr _state; + +public: + Imgui(Imgui const&) = delete; + Imgui& operator=(Imgui const&) = delete; + Imgui(Imgui&&) noexcept; + Imgui& operator=(Imgui&&) noexcept; +}; +} + +namespace timgui { +struct Imgui::Config { + /** + * color attachment of the renderings of `draw()` + * @details sRGB format -> the shader converts the colors of ImGui to linear + */ + VkFormat colorFormat; + /** depth attachment of those renderings, `VK_FORMAT_UNDEFINED` -> none */ + VkFormat depthFormat = VK_FORMAT_UNDEFINED; + VkSampleCountFlagBits samples = VK_SAMPLE_COUNT_1_BIT; ///< samples of those renderings + std::filesystem::path iniFile{}; ///< ImGui settings file, empty -> no file +}; +} + +namespace timgui { +/** + * scope of an ImGui frame + * @details the destructor ends a frame without `render()`, no draw data (e.g. on an exception) + */ +class Imgui::Frame { +public: + /** + * starts the frame, see `Imgui::frame()` + * @pre no `Frame` of any `Imgui` exists + */ + explicit Frame(Imgui& imgui); + ~Frame(); + + /** + * ends the frame and builds the draw data + * @return valid until the next `Imgui::frame()` + * @pre `render()` was not called + */ + [[nodiscard]] ImDrawData& render(); + +private: + cth::ref_wrapper _imgui; + bool _rendered = false; + +public: + Frame(Frame const&) = delete; + Frame& operator=(Frame const&) = delete; + Frame(Frame&&) = delete; + Frame& operator=(Frame&&) = delete; +}; +} diff --git a/timgui/shaders/imgui.frag b/timgui/shaders/imgui.frag new file mode 100644 index 00000000..083a4297 --- /dev/null +++ b/timgui/shaders/imgui.frag @@ -0,0 +1,16 @@ +#version 460 +#extension GL_GOOGLE_include_directive : require +#extension GL_EXT_buffer_reference : require + +#include +#include "imgui.glsl" + +layout(location = 0) in vec4 inColor; +layout(location = 1) in vec2 inUv; + +layout(location = 0) out vec4 outColor; + +void main() { + vec4 texel = texture(sampler2D(jvk_textures2D[draw.textureIdx], jvk_samplers[draw.samplerIdx]), inUv); + outColor = inColor * texel; +} diff --git a/timgui/shaders/imgui.glsl b/timgui/shaders/imgui.glsl new file mode 100644 index 00000000..3ebc2502 --- /dev/null +++ b/timgui/shaders/imgui.glsl @@ -0,0 +1,27 @@ +// the vertex and the push data of the ImGui draws, mirrored by `ImDrawVert` and `dev::Draw` in imgui.cpp +// needs GL_EXT_buffer_reference in the including shader +#ifndef TIMGUI_IMGUI_GLSL +#define TIMGUI_IMGUI_GLSL + +// `ImDrawVert`: only scalars, std430 gives the stride of 20 bytes without the scalar block layout +struct Vertex { + float x; + float y; + float u; + float v; + uint color; // RGBA8, R in the lowest byte +}; + +layout(buffer_reference, std430) readonly buffer Vertices { + Vertex vertices[]; +}; + +layout(push_constant, std430) uniform Draw { + Vertices vertices; + vec2 scale; // display to clip space + vec2 translate; + uint textureIdx; + uint samplerIdx; +} draw; + +#endif diff --git a/timgui/shaders/imgui.vert b/timgui/shaders/imgui.vert new file mode 100644 index 00000000..71cc3afa --- /dev/null +++ b/timgui/shaders/imgui.vert @@ -0,0 +1,29 @@ +#version 460 +#extension GL_GOOGLE_include_directive : require +#extension GL_EXT_buffer_reference : require + +#include "imgui.glsl" + +// the color attachment has an sRGB format: it encodes the linear output +layout(constant_id = 0) const bool SRGB_TARGET = false; + +layout(location = 0) out vec4 outColor; +layout(location = 1) out vec2 outUv; + +// the sRGB colors of ImGui to linear +vec3 to_linear(vec3 srgb) { + bvec3 low = lessThanEqual(srgb, vec3(0.04045)); + return mix(pow((srgb + 0.055) / 1.055, vec3(2.4)), srgb / 12.92, low); +} + +void main() { + // gl_VertexIndex includes the vertex offset of the draw + Vertex vertex = draw.vertices.vertices[gl_VertexIndex]; + vec4 color = unpackUnorm4x8(vertex.color); + if(SRGB_TARGET) + color.rgb = to_linear(color.rgb); + + outColor = color; + outUv = vec2(vertex.u, vertex.v); + gl_Position = vec4(vec2(vertex.x, vertex.y) * draw.scale + draw.translate, 0.0, 1.0); +} diff --git a/timgui/src/imgui.cpp b/timgui/src/imgui.cpp new file mode 100644 index 00000000..cb98b50a --- /dev/null +++ b/timgui/src/imgui.cpp @@ -0,0 +1,547 @@ +#include "timgui/imgui.hpp" + +#include "input.hpp" +#include "shaders/imgui_frag.hpp" +#include "shaders/imgui_vert.hpp" + +#include "jvk/base/core.hpp" +#include "jvk/cmd/cmd_buffer.hpp" +#include "jvk/data/buffer.hpp" +#include "jvk/data/image.hpp" +#include "jvk/data/sampler_heap.hpp" +#include "jvk/graph/stage.hpp" + +#include "cgfw/window/window.hpp" + +#include "cvk/data/buffer/base_buffer.hpp" +#include "cvk/data/buffer/device_ptr.hpp" +#include "cvk/data/descriptor/image_descriptor.hpp" +#include "cvk/data/img/image_config.hpp" +#include "cvk/data/img/sampler_config.hpp" +#include "cvk/render/pipeline/graphics_pipeline.hpp" +#include "cvk/render/pipeline/shader/shader.hpp" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace timgui::dev { +namespace { + /** + * `Frame` of an `Imgui` exists, one in the program: ImGui keeps the current context in a global + */ + bool frameExists = false; +} + +/** + * push data of the draws, `Draw` of imgui.glsl in std430 layout + */ +struct Draw { + cvk::device_ptr vertices; + ImVec2 scale; ///< display to clip space + ImVec2 translate; ///< display to clip space + jvk::heap_idx texture; + jvk::heap_idx sampler; +}; +static_assert(offsetof(Draw, scale) == 8 && offsetof(Draw, translate) == 16); +static_assert(offsetof(Draw, texture) == 24 && offsetof(Draw, sampler) == 28); +static_assert(sizeof(Draw) == 32, "the push data must match `Draw` of imgui.glsl"); + +static_assert(sizeof(ImDrawVert) == 20, "the vertices must match `Vertex` of imgui.glsl"); +static_assert(offsetof(ImDrawVert, uv) == 8 && offsetof(ImDrawVert, col) == 16); + +/** + * ImGui texture on the gpu + * @details the heap cell refers to the image: the texture does not move + */ +struct Texture { + /** + * creates the image with the size of the texture data and its heap cell + */ + Texture(jvk::Core const& core, ImTextureData const& data); + + jvk::Image image; + jvk::SampledImage sampled; +}; + +/** + * deleter of the ImGui and the ImPlot context + */ +struct context_deleter { + void operator()(ImGuiContext* context) const { ImGui::DestroyContext(context); } + void operator()(ImPlotContext* context) const { ImPlot::DestroyContext(context); } +}; + +/** + * state of an `Imgui` + * @details the members of the ImGui context come before it: it uses them up to its destruction + */ +struct ImguiState { + /** + * creates the ImGui context, the ImPlot context, the pipeline and the sampler + * @details makes the contexts current + */ + ImguiState(jvk::Core const& core, cgfw::Window const& window, Imgui::Config const& config); + + cth::ref_wrapper core; + cth::ref_wrapper window; + + /** + * `Imgui::Config::iniFile` in UTF-8, `ImGuiIO::IniFilename` points into it + * @details the destruction of the context saves the settings to it + */ + std::string iniFile; + + std::unique_ptr context; + + /** after `context`: destroyed before it */ + std::unique_ptr plotContext{}; + + cvk::GraphicsPipeline pipeline; + jvk::Sampler sampler; + + /** + * the textures that the gpu has, per ImGui texture + * @details `std::unique_ptr`: a rehash moves the values, the heap cell refers to the image + */ + cth::dt::flat_hash_map> textures{}; + + modifier_keys modifiers{}; + + std::optional lastFrameOpt{}; ///< `std::nullopt` -> no frame yet +}; +} + +namespace timgui { +namespace { + constexpr float FIRST_DELTA_TIME = 1.f / 60.f; ///< seconds, ImGui needs a positive time + + constexpr cvk::ImageConfig TEXTURE_CONFIG{ + .format = VK_FORMAT_R8G8B8A8_UNORM, + .usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, + }; + + constexpr cvk::BaseBuffer::Config STAGING_CONFIG{ + .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + .memory = {.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT}, + }; + + constexpr cvk::BaseBuffer::Config VERTEX_CONFIG{ + .usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + .memory = {.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT}, + }; + + constexpr cvk::BaseBuffer::Config INDEX_CONFIG{ + .usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + .memory = {.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT}, + }; + + constexpr cvk::SamplerConfig SAMPLER_CONFIG{ + .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .maxAnisotropy = 0.f, + }; + + /** + * alpha blending, the alpha of the attachment gets the coverage of the draws + */ + constexpr VkPipelineColorBlendAttachmentState BLENDING{ + .blendEnable = VK_TRUE, + .srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA, + .dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, + .colorBlendOp = VK_BLEND_OP_ADD, + .srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE, + .dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, + .alphaBlendOp = VK_BLEND_OP_ADD, + .colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT + | VK_COLOR_COMPONENT_B_BIT + | VK_COLOR_COMPONENT_A_BIT, + }; + + constexpr auto TEXTURE_OFFSET = static_cast(offsetof(dev::Draw, texture)); + + /** + * makes the ImGui and the ImPlot context of the state current + */ + void make_current(dev::ImguiState const& state) { + ImGui::SetCurrentContext(state.context.get()); + ImPlot::SetCurrentContext(state.plotContext.get()); + } + + /** + * the heap index as ImGui texture id + * @details `+ 1`: `ImTextureID_Invalid` is `0`, the heap index `0` is a valid cell + * @see `to_heap_idx()` + */ + [[nodiscard]] constexpr ImTextureID to_texture_id(jvk::heap_idx idx) { + return ImTextureID{idx.get()} + 1; + } + + /** + * the heap index of the ImGui texture id + * @pre `id != ImTextureID_Invalid` + * @see `to_texture_id()` + */ + [[nodiscard]] constexpr jvk::heap_idx to_heap_idx(ImTextureID id) { + CTH_CRITICAL(id == ImTextureID_Invalid, "the texture id must be valid") {} + return jvk::heap_idx{static_cast(id - 1)}; + } + + /** + * @return the clip rectangle in the framebuffer, clamped to it, `std::nullopt` -> empty + * @param offset of the display + * @param scale from the display to the framebuffer + */ + [[nodiscard]] constexpr std::optional to_scissor( + ImVec4 const& clipRect, + ImVec2 offset, + ImVec2 scale, + VkExtent2D extent + ) { + auto const width = static_cast(extent.width); + auto const height = static_cast(extent.height); + auto const minX = std::max((clipRect.x - offset.x) * scale.x, 0.f); + auto const minY = std::max((clipRect.y - offset.y) * scale.y, 0.f); + auto const maxX = std::min((clipRect.z - offset.x) * scale.x, width); + auto const maxY = std::min((clipRect.w - offset.y) * scale.y, height); + if(maxX <= minX || maxY <= minY) + return std::nullopt; + + return VkRect2D{ + .offset = {static_cast(minX), static_cast(minY)}, + .extent = {static_cast(maxX - minX), static_cast(maxY - minY)}, + }; + } + + /** + * creates the pipeline of the draws + * @details the config of the pipeline keeps the destroyed shaders: no second `create()` + */ + [[nodiscard]] cvk::GraphicsPipeline create_pipeline( + jvk::Core const& core, + Imgui::Config const& config + ) { + cvk::Shader const vertex{core, VK_SHADER_STAGE_VERTEX_BIT, dev::shaders::IMGUI_VERT}; + cvk::Shader const fragment{core, VK_SHADER_STAGE_FRAGMENT_BIT, dev::shaders::IMGUI_FRAG}; + + // `SRGB_TARGET` of imgui.vert + VkBool32 const srgbTarget = vkuFormatIsSRGB(config.colorFormat) ? VK_TRUE : VK_FALSE; + VkSpecializationMapEntry const srgbEntry{ + .constantID = 0, + .offset = 0, + .size = sizeof(srgbTarget), + }; + VkSpecializationInfo const specialization{ + .mapEntryCount = 1, + .pMapEntries = &srgbEntry, + .dataSize = sizeof(srgbTarget), + .pData = &srgbTarget, + }; + + cvk::GraphicsPipeline::Config pipelineConfig{ + .colorBlendAttachments = {BLENDING}, + .colorFormats = {config.colorFormat}, + .depthFormat = config.depthFormat, + }; + pipelineConfig.rasterization.cullMode = VK_CULL_MODE_NONE; + pipelineConfig.multisample.rasterizationSamples = config.samples; + pipelineConfig.depthStencil.depthTestEnable = VK_FALSE; + pipelineConfig.depthStencil.depthWriteEnable = VK_FALSE; + pipelineConfig.addStage(vertex, &specialization).addStage(fragment); + pipelineConfig.descriptorMappings = core.resourceHeap().mappings(); + pipelineConfig.descriptorMappings.append_range(core.samplerHeap().mappings()); + + return cvk::GraphicsPipeline{core, std::move(pipelineConfig), cvk::create}; + } + + /** + * records the copy of every pixel of the texture data into the image + * @details + * - copies through a staging buffer, `stage` retains it + * - leaves the sampled image ready for the fragment shader + */ + void copy_pixels( + jvk::Stage& stage, + dev::cmd_buffer auto& cmd, + dev::Texture const& texture, + ImTextureData const& data + ) { + std::span const pixels{ + data.Pixels, + static_cast(data.GetSizeInBytes()) + }; + jvk::Buffer staging{cmd.core(), STAGING_CONFIG, pixels.size()}; + staging.write(pixels); + + texture.image.copy(cmd, staging); + cmd.use(texture.sampled, VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT); + + stage.retain(std::move(staging)); + } + + /** + * writes the vertices or the indices of the draw lists one after the other + * @param member `ImDrawList::VtxBuffer` or `ImDrawList::IdxBuffer` + */ + template + void write_lists( + cvk::Buffer const& buffer, + ImVector const& lists, + ImVector ImDrawList::* member + ) { + auto const mapping = buffer.map(); + auto out = mapping.begin(); + for(ImDrawList const* list : lists) + out = std::ranges::copy(list->*member, out).out; + buffer.flush(); + } +} +} + +namespace timgui::dev { +Texture::Texture(jvk::Core const& core, ImTextureData const& data) : + image{ + core, + TEXTURE_CONFIG, + VkExtent2D{static_cast(data.Width), static_cast(data.Height)} + }, + sampled{core.resourceHeap().insert(cvk::SampledImageDescriptor{image})} {} + +ImguiState::ImguiState( + jvk::Core const& core, + cgfw::Window const& window, + Imgui::Config const& config +) : + core{core}, + window{window}, + iniFile{std::from_range, config.iniFile.u8string()}, + context{ImGui::CreateContext()}, + pipeline{create_pipeline(core, config)}, + sampler{core.samplerHeap().insert(SAMPLER_CONFIG)} { + // ImPlot allocates through the current ImGui context + ImGui::SetCurrentContext(context.get()); + plotContext.reset(ImPlot::CreateContext()); + make_current(*this); + + auto& io = ImGui::GetIO(); + io.BackendPlatformName = "timgui_cgfw"; + io.BackendRendererName = "timgui_jvk"; + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures + | ImGuiBackendFlags_RendererHasVtxOffset; + io.IniFilename = iniFile.empty() ? nullptr : iniFile.c_str(); + io.Fonts->TexDesiredFormat = ImTextureFormat_RGBA32; +} +} + +namespace timgui { +Imgui::Imgui(jvk::Core const& core, cgfw::Window const& window, Config const& config) : + _state{std::make_unique(core, window, config)} {} + +Imgui::~Imgui() = default; + +Imgui::Frame Imgui::frame() { return Frame{*this}; } + +void Imgui::upload(jvk::Stage& stage, dev::cmd_buffer auto& cmd, ImDrawData& drawData) { + CTH_CRITICAL(cmd.insideRendering(), "the command buffer must be outside a rendering") {} + if(drawData.Textures == nullptr) + return; + + auto& state = *_state; + for(ImTextureData* dataPtr : *drawData.Textures) { + auto& data = *dataPtr; + switch(data.Status) { + case ImTextureStatus_WantCreate: { + CTH_CRITICAL( + data.Format != ImTextureFormat_RGBA32, + "the texture must be RGBA32, got {}", + static_cast(data.Format) + ) {} + CTH_CRITICAL(state.textures.contains(&data), "the texture must be new") {} + + auto texture = std::make_unique(state.core, data); + copy_pixels(stage, cmd, *texture, data); + data.SetTexID(to_texture_id(texture->sampled.idx())); + state.textures.emplace(&data, std::move(texture)); + data.SetStatus(ImTextureStatus_OK); + break; + } + case ImTextureStatus_WantUpdates: { + auto const textureIt = state.textures.find(&data); + CTH_CRITICAL(textureIt == state.textures.end(), "the texture must exist") {} + + copy_pixels(stage, cmd, *textureIt->second, data); + data.SetStatus(ImTextureStatus_OK); + break; + } + case ImTextureStatus_WantDestroy: { + auto const textureIt = state.textures.find(&data); + CTH_CRITICAL(textureIt == state.textures.end(), "the texture must exist") {} + + // frames in flight may still sample it: the stage keeps the heap cell and the image + auto const texture = std::move(textureIt->second); + state.textures.erase(textureIt); + stage.retain(std::move(texture->sampled)); + stage.retain(std::move(texture->image)); + + data.SetTexID(ImTextureID_Invalid); + data.SetStatus(ImTextureStatus_Destroyed); + break; + } + default: break; + } + } +} + +void Imgui::draw(jvk::Stage& stage, dev::cmd_buffer auto& cmd, ImDrawData const& drawData) const { + CTH_CRITICAL(!cmd.insideRendering(), "the command buffer must be inside a rendering") {} + + VkExtent2D const extent{ + static_cast(drawData.DisplaySize.x * drawData.FramebufferScale.x), + static_cast(drawData.DisplaySize.y * drawData.FramebufferScale.y), + }; + if(drawData.TotalVtxCount == 0 || extent.width == 0 || extent.height == 0) + return; + + auto const& state = *_state; + cvk::Core const& vk = *state.core; + + auto const vertexCount = static_cast(drawData.TotalVtxCount); + auto const indexCount = static_cast(drawData.TotalIdxCount); + jvk::Buffer vertices{vk, VERTEX_CONFIG, vertexCount}; + jvk::Buffer indices{vk, INDEX_CONFIG, indexCount}; + write_lists(vertices, drawData.CmdLists, &ImDrawList::VtxBuffer); + write_lists(indices, drawData.CmdLists, &ImDrawList::IdxBuffer); + + ImVec2 const scale{2.f / drawData.DisplaySize.x, 2.f / drawData.DisplaySize.y}; + dev::Draw const push{ + .vertices = vertices.address(), + .scale = scale, + .translate = { + -1.f - drawData.DisplayPos.x * scale.x, + -1.f - drawData.DisplayPos.y * scale.y + }, + .texture = {}, + .sampler = state.sampler.idx(), + }; + + // the render state: at the start and for `ImDrawCallback_ResetRenderState` + auto const bindState = [&] { + cmd.bind(state.pipeline); + cmd.bindIndices(indices); + cmd.setViewport(extent); + cmd.pushData(push); + }; + bindState(); + + // one buffer for all lists: the offsets of the list in it + uint32_t firstIndex = 0; + int32_t firstVertex = 0; + for(ImDrawList const* list : drawData.CmdLists) { + for(ImDrawCmd const& drawCmd : list->CmdBuffer) { + if(drawCmd.UserCallback != nullptr) { + if(drawCmd.UserCallback == ImDrawCallback_ResetRenderState) + bindState(); + else + drawCmd.UserCallback(list, &drawCmd); + continue; + } + + auto const scissorOpt = to_scissor( + drawCmd.ClipRect, + drawData.DisplayPos, + drawData.FramebufferScale, + extent + ); + if(!scissorOpt) + continue; + + cmd.setScissor(*scissorOpt); + cmd.pushData(to_heap_idx(drawCmd.GetTexID()), TEXTURE_OFFSET); + cmd.drawIndexed( + drawCmd.ElemCount, + 1, + firstIndex + drawCmd.IdxOffset, + firstVertex + static_cast(drawCmd.VtxOffset) + ); + } + firstIndex += static_cast(list->IdxBuffer.Size); + firstVertex += list->VtxBuffer.Size; + } + + stage.retain(std::move(vertices)); + stage.retain(std::move(indices)); +} + +ImTextureRef Imgui::texture(jvk::heap_idx imageIdx) const { + return ImTextureRef{to_texture_id(imageIdx)}; +} + +Imgui::Imgui(Imgui&&) noexcept = default; +Imgui& Imgui::operator=(Imgui&&) noexcept = default; + +template void Imgui::upload(jvk::Stage&, jvk::PrimaryCmdBuffer&, ImDrawData&); +template void Imgui::upload(jvk::Stage&, jvk::SecondaryCmdBuffer&, ImDrawData&); +template void Imgui::draw(jvk::Stage&, jvk::PrimaryCmdBuffer&, ImDrawData const&) const; +template void Imgui::draw(jvk::Stage&, jvk::SecondaryCmdBuffer&, ImDrawData const&) const; +} + +namespace timgui { +Imgui::Frame::Frame(Imgui& imgui) : _imgui{imgui} { + CTH_CRITICAL(dev::frameExists, "no frame of any imgui may exist") {} + + auto& state = *imgui._state; + make_current(state); + auto& io = ImGui::GetIO(); + + auto const extent = state.window->extent(); + io.DisplaySize = ImVec2{static_cast(extent.width), static_cast(extent.height)}; + + auto const now = cth::chrono::clock_t::now(); + io.DeltaTime = state.lastFrameOpt.has_value() + ? std::chrono::duration(now - *state.lastFrameOpt).count() + : FIRST_DELTA_TIME; + state.lastFrameOpt = now; + + for(auto const& event : state.window->events()) + dev::add_event(io, event, state.modifiers); + + ImGui::NewFrame(); + dev::frameExists = true; +} + +Imgui::Frame::~Frame() { + if(!_rendered) { + make_current(*_imgui->_state); + ImGui::EndFrame(); + } + dev::frameExists = false; +} + +ImDrawData& Imgui::Frame::render() { + CTH_CRITICAL(_rendered, "render() must not be called twice") {} + + make_current(*_imgui->_state); + ImGui::Render(); + _rendered = true; + return *ImGui::GetDrawData(); +} +} diff --git a/timgui/src/input.cpp b/timgui/src/input.cpp new file mode 100644 index 00000000..c6c2f149 --- /dev/null +++ b/timgui/src/input.cpp @@ -0,0 +1,47 @@ +#include "input.hpp" + +#include + +#include + + +namespace timgui::dev { +void add_event(ImGuiIO& io, cgfw::window_event const& event, modifier_keys& modifiers) { + using cth::io::Axis; + + std::visit( + cth::var::overload{ + [&](cth::io::key_update const& update) { + auto const& state = update.data; + if(auto const buttonOpt = to_imgui_button(state.exKey.key)) { + io.AddMouseButtonEvent(*buttonOpt, state.down); + return; + } + + auto const key = to_imgui_key(state); + if(key == ImGuiKey_None) + return; + + if(auto const mod = to_imgui_mod(key); mod != ImGuiMod_None) + io.AddKeyEvent(mod, modifiers.set(key, state.down)); + io.AddKeyEvent(key, state.down); + }, + [&](cth::io::axis_update const& update) { + auto const& [axis, value] = update.data; + if(axis == Axis::MOUSE_POSITION) + io.AddMousePosEvent(value[0], value[1]); + else if(axis == Axis::MOUSE_SCROLL) + io.AddMouseWheelEvent(value[0], value[1]); + }, + [&](cgfw::TextEvent const& text) { io.AddInputCharactersUTF8(text.text.c_str()); }, + [&](cgfw::FocusEvent const& focus) { + // ImGui forgets its keys at the loss: a release without focus sends no event + if(!focus.focused) + modifiers = modifier_keys{}; + io.AddFocusEvent(focus.focused); + }, + }, + event + ); +} +} diff --git a/timgui/src/input.hpp b/timgui/src/input.hpp new file mode 100644 index 00000000..79412ba0 --- /dev/null +++ b/timgui/src/input.hpp @@ -0,0 +1,212 @@ +#pragma once +#include "cgfw/window/event.hpp" + +#include + +#include +#include + +#include +#include +#include + + +namespace timgui::dev { +/** + * @return the ImGui key of the key state, `ImGuiKey_None` -> no ImGui key + * @details + * - not `cth::io::ex_key::right`, `cth::io::key_state::character` is one ASCII letter or digit + * -> the key of the character: the shortcuts follow the layout + * - else the key at the position + * - `cth::io::ex_key::right` -> the right modifier or the keypad key + * - mouse key -> `ImGuiKey_None`, see `to_imgui_button()` + */ +[[nodiscard]] constexpr ImGuiKey to_imgui_key(cth::io::key_state const&); + +/** + * @return the modifier of the left or the right modifier key, `ImGuiMod_None` -> no modifier key + */ +[[nodiscard]] constexpr ImGuiKey to_imgui_mod(ImGuiKey); + +/** + * @return the ImGui mouse button of the mouse key, `std::nullopt` -> no mouse key + * @details left `0`, right `1`, middle `2`, `MOUSE_4` `3`, `MOUSE_5` `4` + */ +[[nodiscard]] constexpr std::optional to_imgui_button(cth::io::Key); + +/** + * the modifier keys that are down + * @details a modifier is down while its left or its right key is down + */ +class modifier_keys { +public: + /** + * sets the state of the modifier key + * @return the modifier of the key is down + * @pre `to_imgui_mod(key) != ImGuiMod_None` + */ + constexpr bool set(ImGuiKey key, bool down); + +private: + /** the left keys, then the right keys */ + static constexpr size_t SIDE_KEYS = ImGuiKey_RightCtrl - ImGuiKey_LeftCtrl; + + std::array _down{}; ///< from `ImGuiKey_LeftCtrl` to `ImGuiKey_RightSuper` +}; + +/** + * passes the window event to ImGui + * @details + * - key -> `ImGuiIO::AddKeyEvent()` of `to_imgui_key()` + * - modifier key -> its `ImGuiMod_*` first + * - repeat -> passes `down`, ImGui repeats itself + * - mouse key -> `ImGuiIO::AddMouseButtonEvent()` of `to_imgui_button()` + * - `cth::io::Axis::MOUSE_POSITION` -> `ImGuiIO::AddMousePosEvent()` + * - `cth::io::Axis::MOUSE_SCROLL` -> `ImGuiIO::AddMouseWheelEvent()` + * - scroll: positive y up, positive x left, like ImGui + * - `cgfw::TextEvent` -> `ImGuiIO::AddInputCharactersUTF8()` + * - `cgfw::FocusEvent` -> `ImGuiIO::AddFocusEvent()` + * - focus loss -> forgets the modifier keys, like ImGui forgets its keys + * @param[out] io gets the events + * @param[out] modifiers the modifier keys that are down + */ +void add_event(ImGuiIO& io, cgfw::window_event const& event, modifier_keys& modifiers); +} + +namespace timgui::dev { +constexpr ImGuiKey to_imgui_key(cth::io::key_state const& state) { + using cth::io::Key; + + auto const key = state.exKey.key; + auto const offset = [key](Key first, ImGuiKey to) { + return static_cast(to + (*key - *first)); + }; + + if(state.exKey.right) { + if(key >= Key::DIGIT_0 && key <= Key::DIGIT_9) + return offset(Key::DIGIT_0, ImGuiKey_Keypad0); + + switch(key) { + case Key::PERIOD: return ImGuiKey_KeypadDecimal; + case Key::SLASH: return ImGuiKey_KeypadDivide; + case Key::STAR: return ImGuiKey_KeypadMultiply; + case Key::MINUS: return ImGuiKey_KeypadSubtract; + case Key::PLUS: return ImGuiKey_KeypadAdd; + case Key::ENTER: return ImGuiKey_KeypadEnter; + case Key::EQUAL: return ImGuiKey_KeypadEqual; + + case Key::CONTROL: return ImGuiKey_RightCtrl; + case Key::SHIFT: return ImGuiKey_RightShift; + case Key::ALT: return ImGuiKey_RightAlt; + case Key::PLATFORM: return ImGuiKey_RightSuper; + + default: break; + } + } + else if(state.character.size() == 1) { + auto const character = state.character[0]; + if(character >= 'a' && character <= 'z') + return static_cast(ImGuiKey_A + (character - 'a')); + if(character >= 'A' && character <= 'Z') + return static_cast(ImGuiKey_A + (character - 'A')); + if(character >= '0' && character <= '9') + return static_cast(ImGuiKey_0 + (character - '0')); + } + + if(key >= Key::A && key <= Key::Z) + return offset(Key::A, ImGuiKey_A); + if(key >= Key::DIGIT_0 && key <= Key::DIGIT_9) + return offset(Key::DIGIT_0, ImGuiKey_0); + if(key >= Key::F1 && key <= Key::F12) + return offset(Key::F1, ImGuiKey_F1); + if(key >= Key::F13 && key <= Key::F24) + return offset(Key::F13, ImGuiKey_F13); + + switch(key) { + case Key::SPACE: return ImGuiKey_Space; + case Key::BACKTICK: return ImGuiKey_GraveAccent; + case Key::MINUS: return ImGuiKey_Minus; + case Key::EQUAL: return ImGuiKey_Equal; + case Key::OPEN_BRACKET: return ImGuiKey_LeftBracket; + case Key::CLOSE_BRACKET: return ImGuiKey_RightBracket; + case Key::BACKSLASH: return ImGuiKey_Backslash; + case Key::SEMICOLON: return ImGuiKey_Semicolon; + case Key::QUOTE: return ImGuiKey_Apostrophe; + case Key::COMMA: return ImGuiKey_Comma; + case Key::PERIOD: return ImGuiKey_Period; + case Key::SLASH: return ImGuiKey_Slash; + case Key::LESS_THAN: return ImGuiKey_Oem102; + + case Key::BACKSPACE: return ImGuiKey_Backspace; + case Key::CAPS_LOCK: return ImGuiKey_CapsLock; + case Key::DEL: return ImGuiKey_Delete; + case Key::END: return ImGuiKey_End; + case Key::ENTER: return ImGuiKey_Enter; + case Key::ESCAPE: return ImGuiKey_Escape; + case Key::HOME: return ImGuiKey_Home; + case Key::INSERT: return ImGuiKey_Insert; + case Key::PAGE_DOWN: return ImGuiKey_PageDown; + case Key::PAGE_UP: return ImGuiKey_PageUp; + case Key::TAB: return ImGuiKey_Tab; + + case Key::ARROW_DOWN: return ImGuiKey_DownArrow; + case Key::ARROW_LEFT: return ImGuiKey_LeftArrow; + case Key::ARROW_RIGHT: return ImGuiKey_RightArrow; + case Key::ARROW_UP: return ImGuiKey_UpArrow; + + case Key::CONTROL: return ImGuiKey_LeftCtrl; + case Key::SHIFT: return ImGuiKey_LeftShift; + case Key::ALT: return ImGuiKey_LeftAlt; + case Key::PLATFORM: return ImGuiKey_LeftSuper; + + case Key::NUM_LOCK: return ImGuiKey_NumLock; + case Key::PRINT_SCREEN: return ImGuiKey_PrintScreen; + case Key::SCROLL_LOCK: return ImGuiKey_ScrollLock; + case Key::PAUSE: return ImGuiKey_Pause; + case Key::MENU: return ImGuiKey_Menu; + + default: return ImGuiKey_None; + } +} + +constexpr ImGuiKey to_imgui_mod(ImGuiKey key) { + switch(key) { + case ImGuiKey_LeftCtrl: + case ImGuiKey_RightCtrl: return ImGuiMod_Ctrl; + case ImGuiKey_LeftShift: + case ImGuiKey_RightShift: return ImGuiMod_Shift; + case ImGuiKey_LeftAlt: + case ImGuiKey_RightAlt: return ImGuiMod_Alt; + case ImGuiKey_LeftSuper: + case ImGuiKey_RightSuper: return ImGuiMod_Super; + default: return ImGuiMod_None; + } +} + +constexpr std::optional to_imgui_button(cth::io::Key key) { + using cth::io::Key; + + switch(key) { + case Key::MOUSE_LEFT: return ImGuiMouseButton_Left; + case Key::MOUSE_RIGHT: return ImGuiMouseButton_Right; + case Key::MOUSE_MIDDLE: return ImGuiMouseButton_Middle; + case Key::MOUSE_4: return 3; + case Key::MOUSE_5: return 4; + default: return std::nullopt; + } +} + +constexpr bool modifier_keys::set(ImGuiKey key, bool down) { + CTH_CRITICAL( + to_imgui_mod(key) == ImGuiMod_None, + "the key must be a modifier key, got {}", + static_cast(key) + ) {} + + auto const keyIdx = static_cast(key - ImGuiKey_LeftCtrl); + _down[keyIdx] = down; + + auto const leftIdx = keyIdx % SIDE_KEYS; + return _down[leftIdx] || _down[leftIdx + SIDE_KEYS]; +} +} diff --git a/timgui/src/pch/glob/cth.hpp b/timgui/src/pch/glob/cth.hpp new file mode 100644 index 00000000..03d68b0a --- /dev/null +++ b/timgui/src/pch/glob/cth.hpp @@ -0,0 +1,5 @@ +#pragma once +#include +#include +#include +#include diff --git a/timgui/src/pch/glob/imgui.hpp b/timgui/src/pch/glob/imgui.hpp new file mode 100644 index 00000000..a3e2df15 --- /dev/null +++ b/timgui/src/pch/glob/imgui.hpp @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/timgui/src/pch/glob/implot.hpp b/timgui/src/pch/glob/implot.hpp new file mode 100644 index 00000000..e4976423 --- /dev/null +++ b/timgui/src/pch/glob/implot.hpp @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/timgui/src/pch/glob/std.hpp b/timgui/src/pch/glob/std.hpp new file mode 100644 index 00000000..1835249c --- /dev/null +++ b/timgui/src/pch/glob/std.hpp @@ -0,0 +1,11 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/timgui/src/pch/glob/volk.hpp b/timgui/src/pch/glob/volk.hpp new file mode 100644 index 00000000..e78ae406 --- /dev/null +++ b/timgui/src/pch/glob/volk.hpp @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/timgui/src/pch/pch.hpp b/timgui/src/pch/pch.hpp new file mode 100644 index 00000000..0ac7ab15 --- /dev/null +++ b/timgui/src/pch/pch.hpp @@ -0,0 +1,8 @@ +#pragma once + +#include "glob/cth.hpp" +#include "glob/std.hpp" + +#include "glob/imgui.hpp" +#include "glob/implot.hpp" +#include "glob/volk.hpp" diff --git a/timgui/tests/CMakeLists.txt b/timgui/tests/CMakeLists.txt new file mode 100644 index 00000000..e4d5141a --- /dev/null +++ b/timgui/tests/CMakeLists.txt @@ -0,0 +1,24 @@ +cth_glob_cpp(TIMGUI_TESTS_SRC "src") + +add_executable(timgui_tests ${TIMGUI_TESTS_SRC}) + +cth_target_enable_build_cache(timgui_tests OPTIONAL) + +# ../src: the tests reach the input mapping of timgui +target_include_directories( + timgui_tests + PRIVATE src "${CMAKE_CURRENT_SOURCE_DIR}/../src" +) + +target_precompile_headers( + timgui_tests + PRIVATE + src/pch/pch.hpp +) + +find_package(GTest CONFIG REQUIRED) + +target_link_libraries(timgui_tests PRIVATE GTest::gtest_main timgui cgfw) + +# one process: the tests share the vulkan loader, RGFW keeps one global state +add_test(NAME timgui_tests COMMAND timgui_tests) diff --git a/timgui/tests/src/context.cpp b/timgui/tests/src/context.cpp new file mode 100644 index 00000000..41824345 --- /dev/null +++ b/timgui/tests/src/context.cpp @@ -0,0 +1,50 @@ +#include "context.hpp" + +#include "cvk/base/queue/queue_family.hpp" + +#include + +#include +#include + + +namespace timgui::test { +jvk::Core::Config const Context::CONFIG{ + .vk = {.queueProperties = {cvk::QueueFamilyProperties::GRAPHICS}}, +}; + +namespace { + size_t errors = 0; + + VKAPI_ATTR VkBool32 VKAPI_CALL count_errors( + VkDebugUtilsMessageSeverityFlagBitsEXT severity, + VkDebugUtilsMessageTypeFlagsEXT types, + VkDebugUtilsMessengerCallbackDataEXT const* callbackData, + void* userData + ) { + if(severity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) + ++errors; + return cvk::default_debug_callback(severity, types, callbackData, userData); + } +} + +bool display_available() { +#ifdef CTH_PLATFORM_WINDOWS + return true; +#else + return std::getenv("WAYLAND_DISPLAY") != nullptr; +#endif +} + +cvk::DebugMessenger::Config counting_messenger() { + return cvk::DebugMessenger::Config{.callback = count_errors}; +} + +Context::ValidationCheck::ValidationCheck() { errors = 0; } + +Context::ValidationCheck::~ValidationCheck() { EXPECT_EQ(errors, 0); } + +Context::Context() : + instance{instance_config({}, counting_messenger()), cvk::create}, + core{instance, CONFIG, {}} {} +} diff --git a/timgui/tests/src/context.hpp b/timgui/tests/src/context.hpp new file mode 100644 index 00000000..e15a305f --- /dev/null +++ b/timgui/tests/src/context.hpp @@ -0,0 +1,47 @@ +#pragma once +#include "test.hpp" + +#include "jvk/base/core.hpp" + +#include "cvk/base/instance.hpp" +#include "cvk/debug/debug_messenger.hpp" + + +namespace timgui::test { +/** + * messenger config that logs every message and counts the errors + * @details a small copy of the cvk tests, the instance create info gets it too: + * counts the errors of `vkDestroyInstance()`, e.g. leaked objects + */ +[[nodiscard]] cvk::DebugMessenger::Config counting_messenger(); + +/** + * own instance and core, fails the test on validation errors + * @details the check runs after the instance is destroyed + */ +struct Context { + /** + * one graphics queue, the heaps of `jvk::HeapsConfig` + */ + static jvk::Core::Config const CONFIG; + + /** + * resets the error count, the destructor fails the test on errors + */ + struct ValidationCheck { + ValidationCheck(); + ~ValidationCheck(); + }; + + Context(); + + ValidationCheck validationCheck; + cvk::Instance instance; + jvk::Core core; + + Context(Context const& other) = delete; + Context(Context&& other) = delete; + Context& operator=(Context const& other) = delete; + Context& operator=(Context&& other) = delete; +}; +} diff --git a/timgui/tests/src/environment.cpp b/timgui/tests/src/environment.cpp new file mode 100644 index 00000000..8b29cef6 --- /dev/null +++ b/timgui/tests/src/environment.cpp @@ -0,0 +1,26 @@ +#include "cvk/base/cvk.hpp" + +#include + +#include + + +namespace timgui::test { +namespace { + /** + * holds the vulkan loader for all tests + */ + class Environment : public testing::Environment { + public: + void SetUp() override { _cvk.emplace(); } + void TearDown() override { _cvk.reset(); } + + private: + std::optional _cvk{}; + }; + + [[maybe_unused]] testing::Environment* const ENVIRONMENT = testing::AddGlobalTestEnvironment( + new Environment{} + ); +} +} diff --git a/timgui/tests/src/imgui_test.cpp b/timgui/tests/src/imgui_test.cpp new file mode 100644 index 00000000..e71ba6b6 --- /dev/null +++ b/timgui/tests/src/imgui_test.cpp @@ -0,0 +1,425 @@ +#include "timgui/imgui.hpp" + +#include "context.hpp" +#include "test.hpp" + +#include "jvk/base/core.hpp" +#include "jvk/data/buffer.hpp" +#include "jvk/data/image.hpp" +#include "jvk/data/resource_heap.hpp" +#include "jvk/graph/frame.hpp" +#include "jvk/graph/stage.hpp" +#include "jvk/graph/stage_graph.hpp" +#include "jvk/sync/resource_states.hpp" + +#include "cgfw/window/window.hpp" + +#include "cvk/data/buffer/buffer.hpp" +#include "cvk/data/descriptor/image_descriptor.hpp" +#include "cvk/data/img/image_view.hpp" +#include "cvk/render/cmd/rendering_info.hpp" + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + + +namespace timgui { +namespace { + constexpr VkExtent2D EXTENT = test::WINDOW_EXTENT; + + constexpr ImU32 RED = IM_COL32(255, 0, 0, 255); + constexpr ImU32 GRAY = IM_COL32(128, 128, 128, 255); + constexpr uint32_t CLEAR = 0; ///< transparent black + + constexpr cvk::BaseBuffer::Config STAGING_CONFIG{ + .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + .memory = {.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT}, + }; + + constexpr cvk::BaseBuffer::Config READBACK_CONFIG{ + .usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT, + .memory = {.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT}, + }; + + constexpr jvk::BufferAccess HOST_READ{VK_PIPELINE_STAGE_2_HOST_BIT, VK_ACCESS_2_HOST_READ_BIT}; + + /** + * color attachment of the draws and the buffer it is copied to + */ + struct Target { + Target(jvk::Core const& core, VkFormat format) : + image{ + core, + { + .format = format, + .usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, + }, + EXTENT + }, + view{image, {}, cvk::create}, + readback{core, READBACK_CONFIG, size_t{EXTENT.width} * EXTENT.height} {} + + /** + * @return RGBA8 of the pixel, R in the lowest byte + * @pre the gpu finished the copy into `readback` + */ + [[nodiscard]] uint32_t pixel(uint32_t x, uint32_t y) const { + auto const mapping = readback.map(); + readback.invalidate(); + return mapping[size_t{y} * EXTENT.width + x]; + } + + jvk::Image image; + cvk::ImageView view; + cvk::Buffer readback; + }; + + /** + * @return the byte of the channel, `0` is R + */ + [[nodiscard]] constexpr int channel(uint32_t pixel, uint32_t channelIdx) { + return static_cast((pixel >> (8 * channelIdx)) & 0xFF); + } + + cth::co::executor_task await_stage(jvk::Stage const& stage) { co_await stage; } + + /** + * @return stage 0 of the next frame + */ + [[nodiscard]] jvk::Stage& next_stage(jvk::Core const& core, jvk::StageGraph& graph) { + return core.executor().sync_wait(graph.nextFrame()).stage(0); + } + + /** + * submits the uploads of the draw data in the next frame + */ + void upload_frame( + jvk::Core const& core, + jvk::StageGraph& graph, + Imgui& imgui, + ImDrawData& drawData + ) { + auto& stage = next_stage(core, graph); + auto const submit = stage.begin(); + imgui.upload(stage, *submit, drawData); + } + + /** + * uploads and draws the draw data into the cleared target in the next frame + * @details copies the target to its buffer, waits until the gpu finished + */ + void draw_frame( + jvk::Core const& core, + jvk::StageGraph& graph, + Imgui& imgui, + ImDrawData& drawData, + Target const& target + ) { + auto& stage = next_stage(core, graph); + { + auto const submit = stage.begin(); + imgui.upload(stage, *submit, drawData); + { + auto const rendering = submit->beginRendering( + { + .colorAttachments = { + cvk::RenderingAttachment{ + .view = target.view, + .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + }, + }, + } + ); + imgui.draw(stage, *submit, drawData); + } + target.image.copyTo(*submit, target.readback); + submit->use(target.readback, HOST_READ); + } + core.executor().sync_wait(await_stage(stage)); + } + + /** + * ImGui frame without a window, in the current context: `DisplaySize` is `EXTENT` + * @param draw records into the foreground draw list + * @return the draw data of the frame + */ + template + [[nodiscard]] ImDrawData& windowless_frame(Record const& draw) { + auto& io = ImGui::GetIO(); + io.DisplaySize = ImVec2{ + static_cast(EXTENT.width), + static_cast(EXTENT.height) + }; + io.DeltaTime = 1.f / 60.f; + + ImGui::NewFrame(); + draw(*ImGui::GetForegroundDrawList()); + ImGui::Render(); + return *ImGui::GetDrawData(); + } + + /** + * a rectangle over the whole display + */ + [[nodiscard]] ImDrawData& rect_frame(ImU32 color) { + return windowless_frame( + [color](ImDrawList& drawList) { + drawList.AddRectFilled(ImVec2{0.f, 0.f}, ImGui::GetIO().DisplaySize, color); + } + ); + } +} + +TIMGUI_TEST(Imgui, constructor_makes_the_contexts_current) { + test::Context context{}; + cgfw::Window const window{test::window_config()}; + + Imgui const imgui{context.core, window, {.colorFormat = VK_FORMAT_R8G8B8A8_UNORM}}; + + ASSERT_NE(ImGui::GetCurrentContext(), nullptr); + EXPECT_NE(ImPlot::GetCurrentContext(), nullptr); + auto const& io = ImGui::GetIO(); + EXPECT_NE(io.BackendFlags & ImGuiBackendFlags_RendererHasTextures, 0); + EXPECT_NE(io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset, 0); + EXPECT_EQ(io.IniFilename, nullptr); +} + +TIMGUI_TEST(Imgui, destructor_destroys_the_contexts) { + test::Context context{}; + cgfw::Window const window{test::window_config()}; + + { Imgui const imgui{context.core, window, {.colorFormat = VK_FORMAT_R8G8B8A8_UNORM}}; } + + // the destruction of the current contexts clears the current contexts + EXPECT_EQ(ImGui::GetCurrentContext(), nullptr); + EXPECT_EQ(ImPlot::GetCurrentContext(), nullptr); +} + +TIMGUI_TEST(Imgui, upload_creates_updates_and_destroys_a_texture) { + test::Context context{}; + cgfw::Window const window{test::window_config()}; + Imgui imgui{context.core, window, {.colorFormat = VK_FORMAT_R8G8B8A8_UNORM}}; + jvk::StageGraph graph{context.core, {.stages = {{.queueIdx = 0}}}}; + + ImTextureData data{}; + data.Create(ImTextureFormat_RGBA32, 4, 4); + ImVector textures{}; + textures.push_back(&data); + ImDrawData drawData{}; + drawData.Textures = &textures; + + upload_frame(context.core, graph, imgui, drawData); + EXPECT_EQ(data.Status, ImTextureStatus_OK); + auto const id = data.GetTexID(); + EXPECT_NE(id, ImTextureID_Invalid); + + data.SetStatus(ImTextureStatus_WantUpdates); + upload_frame(context.core, graph, imgui, drawData); + EXPECT_EQ(data.Status, ImTextureStatus_OK); + EXPECT_EQ(data.GetTexID(), id); + + // a destroy that ImGui plans + data.WantDestroyNextFrame = true; + data.SetStatus(ImTextureStatus_WantDestroy); + upload_frame(context.core, graph, imgui, drawData); + EXPECT_EQ(data.Status, ImTextureStatus_Destroyed); + EXPECT_EQ(data.GetTexID(), ImTextureID_Invalid); +} + +TIMGUI_TEST(Imgui, draw_fills_with_the_vertex_color) { + test::Context context{}; + cgfw::Window const window{test::window_config()}; + Imgui imgui{context.core, window, {.colorFormat = VK_FORMAT_R8G8B8A8_UNORM}}; + Target const target{context.core, VK_FORMAT_R8G8B8A8_UNORM}; + jvk::StageGraph graph{context.core, {.stages = {{.queueIdx = 0}}}}; + + auto& drawData = rect_frame(RED); + draw_frame(context.core, graph, imgui, drawData, target); + + EXPECT_EQ(target.pixel(EXTENT.width / 2, EXTENT.height / 2), RED); +} + +TIMGUI_TEST(Imgui, srgb_target_keeps_the_srgb_color) { + test::Context context{}; + cgfw::Window const window{test::window_config()}; + Imgui imgui{context.core, window, {.colorFormat = VK_FORMAT_R8G8B8A8_SRGB}}; + Target const target{context.core, VK_FORMAT_R8G8B8A8_SRGB}; + jvk::StageGraph graph{context.core, {.stages = {{.queueIdx = 0}}}}; + + auto& drawData = rect_frame(GRAY); + draw_frame(context.core, graph, imgui, drawData, target); + + // without the conversion to linear the attachment would store 188 + auto const pixel = target.pixel(EXTENT.width / 2, EXTENT.height / 2); + for(uint32_t channelIdx = 0; channelIdx < 3; ++channelIdx) + EXPECT_LE(std::abs(channel(pixel, channelIdx) - 128), 1) << "channel " << channelIdx; + EXPECT_EQ(channel(pixel, 3), 255); +} + +TIMGUI_TEST(Imgui, draw_clips_to_the_clip_rect) { + test::Context context{}; + cgfw::Window const window{test::window_config()}; + Imgui imgui{context.core, window, {.colorFormat = VK_FORMAT_R8G8B8A8_UNORM}}; + Target const target{context.core, VK_FORMAT_R8G8B8A8_UNORM}; + jvk::StageGraph graph{context.core, {.stages = {{.queueIdx = 0}}}}; + + auto& drawData = windowless_frame( + [](ImDrawList& drawList) { + auto const display = ImGui::GetIO().DisplaySize; + drawList.PushClipRect(ImVec2{0.f, 0.f}, ImVec2{display.x / 2, display.y}); + drawList.AddRectFilled(ImVec2{0.f, 0.f}, display, RED); + drawList.PopClipRect(); + } + ); + draw_frame(context.core, graph, imgui, drawData, target); + + EXPECT_EQ(target.pixel(EXTENT.width / 4, EXTENT.height / 2), RED); + EXPECT_EQ(target.pixel(EXTENT.width * 3 / 4, EXTENT.height / 2), CLEAR); +} + +TIMGUI_TEST(Imgui, draw_records_an_implot_plot) { + constexpr std::array VALUES{0.f, 1.f, 0.5f}; + + test::Context context{}; + cgfw::Window const window{test::window_config()}; + Imgui imgui{context.core, window, {.colorFormat = VK_FORMAT_R8G8B8A8_UNORM}}; + Target const target{context.core, VK_FORMAT_R8G8B8A8_UNORM}; + jvk::StageGraph graph{context.core, {.stages = {{.queueIdx = 0}}}}; + + auto& drawData = windowless_frame( + [&](ImDrawList&) { + ImGui::SetNextWindowPos(ImVec2{0.f, 0.f}); + ImGui::SetNextWindowSize(ImGui::GetIO().DisplaySize); + ImGui::Begin("plot"); + if(ImPlot::BeginPlot("values")) { + ImPlot::PlotLine("line", VALUES.data(), static_cast(VALUES.size())); + ImPlot::EndPlot(); + } + ImGui::End(); + } + ); + draw_frame(context.core, graph, imgui, drawData, target); + + // the window background at least + EXPECT_NE(target.pixel(EXTENT.width / 2, EXTENT.height / 2), CLEAR); +} + +TIMGUI_TEST(Imgui, draw_without_vertices_records_nothing) { + test::Context context{}; + cgfw::Window const window{test::window_config()}; + Imgui imgui{context.core, window, {.colorFormat = VK_FORMAT_R8G8B8A8_UNORM}}; + Target const target{context.core, VK_FORMAT_R8G8B8A8_UNORM}; + jvk::StageGraph graph{context.core, {.stages = {{.queueIdx = 0}}}}; + + auto& drawData = windowless_frame([](ImDrawList&) {}); + ASSERT_EQ(drawData.TotalVtxCount, 0); + draw_frame(context.core, graph, imgui, drawData, target); + + EXPECT_EQ(target.pixel(EXTENT.width / 2, EXTENT.height / 2), CLEAR); +} + +TIMGUI_TEST(Imgui, texture_draws_an_image_of_the_heap) { + constexpr std::array GREEN{0, 255, 0, 255}; + + test::Context context{}; + cgfw::Window const window{test::window_config()}; + Imgui imgui{context.core, window, {.colorFormat = VK_FORMAT_R8G8B8A8_UNORM}}; + Target const target{context.core, VK_FORMAT_R8G8B8A8_UNORM}; + jvk::Image const image{ + context.core, + { + .format = VK_FORMAT_R8G8B8A8_UNORM, + .usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, + }, + VkExtent2D{1, 1} + }; + auto const sampled = context.core.resourceHeap().insert(cvk::SampledImageDescriptor{image}); + jvk::StageGraph graph{context.core, {.stages = {{.queueIdx = 0}}}}; + + // the image: one green pixel, ready for the fragment shader + { + jvk::Buffer staging{context.core, STAGING_CONFIG, GREEN.size()}; + staging.write(GREEN); + auto& stage = next_stage(context.core, graph); + auto const submit = stage.begin(); + image.copy(*submit, staging); + submit->use(sampled, VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT); + stage.retain(std::move(staging)); + } + + auto& drawData = windowless_frame( + [&](ImDrawList& drawList) { + drawList.AddImage( + imgui.texture(sampled.idx()), + ImVec2{0.f, 0.f}, + ImGui::GetIO().DisplaySize + ); + } + ); + draw_frame(context.core, graph, imgui, drawData, target); + + EXPECT_EQ(target.pixel(EXTENT.width / 2, EXTENT.height / 2), IM_COL32(0, 255, 0, 255)); +} + +TIMGUI_TEST(Frame, passes_the_extent_and_the_first_delta_time) { + TIMGUI_SKIP_WITHOUT_DISPLAY(); + test::Context context{}; + cgfw::Window window{test::window_config(), cgfw::create}; + Imgui imgui{context.core, window, {.colorFormat = VK_FORMAT_R8G8B8A8_UNORM}}; + + window.pollEvents(); + auto frame = imgui.frame(); + auto const extent = window.extent(); + auto const& io = ImGui::GetIO(); + EXPECT_EQ(io.DisplaySize.x, static_cast(extent.width)); + EXPECT_EQ(io.DisplaySize.y, static_cast(extent.height)); + EXPECT_EQ(io.DeltaTime, 1.f / 60.f); + + auto const& drawData = frame.render(); + EXPECT_EQ(drawData.DisplaySize.x, io.DisplaySize.x); + EXPECT_EQ(drawData.DisplaySize.y, io.DisplaySize.y); +} + +TIMGUI_TEST(Frame, next_frame_passes_the_time_since_the_last) { + TIMGUI_SKIP_WITHOUT_DISPLAY(); + test::Context context{}; + cgfw::Window window{test::window_config(), cgfw::create}; + Imgui imgui{context.core, window, {.colorFormat = VK_FORMAT_R8G8B8A8_UNORM}}; + + window.pollEvents(); + { auto const frame = imgui.frame(); } + window.pollEvents(); + auto const frame = imgui.frame(); + + EXPECT_GT(ImGui::GetIO().DeltaTime, 0.f); + EXPECT_EQ(ImGui::GetFrameCount(), 2); +} + +TIMGUI_TEST(Frame, destructor_without_render_ends_the_frame) { + TIMGUI_SKIP_WITHOUT_DISPLAY(); + test::Context context{}; + cgfw::Window window{test::window_config(), cgfw::create}; + Imgui imgui{context.core, window, {.colorFormat = VK_FORMAT_R8G8B8A8_UNORM}}; + + window.pollEvents(); + { + auto const frame = imgui.frame(); + EXPECT_TRUE(ImGui::GetCurrentContext()->WithinFrameScope); + } + + EXPECT_FALSE(ImGui::GetCurrentContext()->WithinFrameScope); +} +} diff --git a/timgui/tests/src/input_test.cpp b/timgui/tests/src/input_test.cpp new file mode 100644 index 00000000..b5899e1d --- /dev/null +++ b/timgui/tests/src/input_test.cpp @@ -0,0 +1,332 @@ +#include "test.hpp" + +#include "input.hpp" + +#include "cgfw/window/event.hpp" + +#include +#include + +#include +#include +#include + +#include +#include +#include + + +namespace timgui::dev { +namespace { + using cth::io::Axis; + using cth::io::Key; + using cth::io::key_state; + + /** + * own ImGui context for the scope, current while it lives + */ + class ScopedContext { + public: + ScopedContext() : _context{ImGui::CreateContext()} { ImGui::SetCurrentContext(_context); } + ~ScopedContext() { ImGui::DestroyContext(_context); } + + /** + * @return the events that the io queued, in order + */ + [[nodiscard]] ImVector const& events() const { + return _context->InputEventsQueue; + } + + private: + ImGuiContext* _context; + + public: + ScopedContext(ScopedContext const& other) = delete; + ScopedContext(ScopedContext&& other) = delete; + ScopedContext& operator=(ScopedContext const& other) = delete; + ScopedContext& operator=(ScopedContext&& other) = delete; + }; + + [[nodiscard]] cgfw::window_event key_event( + Key key, + bool right, + bool down, + std::string character = {}, + bool repeat = false + ) { + return cth::io::key_update{ + .data = key_state{key, right, down, std::move(character), repeat}, + .time = cth::chrono::clock_t::now() + }; + } + + [[nodiscard]] cgfw::window_event axis_event(Axis axis, float x, float y) { + return cth::io::axis_update{ + .data = {.axis = axis, .value = {x, y}}, + .time = cth::chrono::clock_t::now() + }; + } + + /** the key and down of each key event */ + using key_events_t = std::vector>; + + /** + * @return the key events of the queue, in order + */ + [[nodiscard]] key_events_t key_events(ScopedContext const& context) { + key_events_t keys{}; + for(auto const& event : context.events()) + if(event.Type == ImGuiInputEventType_Key) + keys.emplace_back(event.Key.Key, event.Key.Down); + return keys; + } +} + +TIMGUI_TEST(to_imgui_key, letters_follow_the_layout) { + static_assert(to_imgui_key(key_state{Key::Q, false, true, "a"}) == ImGuiKey_A); + static_assert(to_imgui_key(key_state{Key::Y, false, true, "z"}) == ImGuiKey_Z); + static_assert(to_imgui_key(key_state{Key::A, false, true, "A"}) == ImGuiKey_A); + // AZERTY: m on the key right of L + static_assert(to_imgui_key(key_state{Key::SEMICOLON, false, true, "m"}) == ImGuiKey_M); +} + +TIMGUI_TEST(to_imgui_key, digits_follow_the_layout) { + static_assert(to_imgui_key(key_state{Key::DIGIT_1, false, true, "1"}) == ImGuiKey_1); + static_assert(to_imgui_key(key_state{Key::Q, false, true, "7"}) == ImGuiKey_7); +} + +TIMGUI_TEST(to_imgui_key, other_characters_map_by_position) { + // AZERTY: & on the key of 1 + static_assert(to_imgui_key(key_state{Key::DIGIT_1, false, true, "&"}) == ImGuiKey_1); + // German: ö right of L, not ASCII + static_assert( + to_imgui_key(key_state{Key::SEMICOLON, false, true, "\xC3\xB6"}) == ImGuiKey_Semicolon + ); + static_assert(to_imgui_key(key_state{Key::Q, false, true}) == ImGuiKey_Q); + static_assert(to_imgui_key(key_state{Key::ENTER, false, true, "\r"}) == ImGuiKey_Enter); + static_assert(to_imgui_key(key_state{Key::SPACE, false, true, " "}) == ImGuiKey_Space); + static_assert(to_imgui_key(key_state{Key::LESS_THAN, false, true, "<"}) == ImGuiKey_Oem102); +} + +TIMGUI_TEST(to_imgui_key, function_keys) { + static_assert(to_imgui_key(key_state{Key::F1, false, true}) == ImGuiKey_F1); + static_assert(to_imgui_key(key_state{Key::F12, false, true}) == ImGuiKey_F12); + static_assert(to_imgui_key(key_state{Key::F13, false, true}) == ImGuiKey_F13); + static_assert(to_imgui_key(key_state{Key::F24, false, true}) == ImGuiKey_F24); +} + +TIMGUI_TEST(to_imgui_key, right_is_the_keypad) { + static_assert(to_imgui_key(key_state{Key::DIGIT_0, true, true}) == ImGuiKey_Keypad0); + static_assert(to_imgui_key(key_state{Key::DIGIT_9, true, true}) == ImGuiKey_Keypad9); + // the character does not move a keypad key + static_assert(to_imgui_key(key_state{Key::DIGIT_5, true, true, "5"}) == ImGuiKey_Keypad5); + static_assert(to_imgui_key(key_state{Key::ENTER, true, true, "\r"}) == ImGuiKey_KeypadEnter); + static_assert(to_imgui_key(key_state{Key::PERIOD, true, true}) == ImGuiKey_KeypadDecimal); + static_assert(to_imgui_key(key_state{Key::SLASH, true, true}) == ImGuiKey_KeypadDivide); + static_assert(to_imgui_key(key_state{Key::STAR, true, true}) == ImGuiKey_KeypadMultiply); + static_assert(to_imgui_key(key_state{Key::MINUS, true, true}) == ImGuiKey_KeypadSubtract); + static_assert(to_imgui_key(key_state{Key::PLUS, true, true}) == ImGuiKey_KeypadAdd); + static_assert(to_imgui_key(key_state{Key::EQUAL, true, true}) == ImGuiKey_KeypadEqual); +} + +TIMGUI_TEST(to_imgui_key, modifiers_by_side) { + static_assert(to_imgui_key(key_state{Key::CONTROL, false, true}) == ImGuiKey_LeftCtrl); + static_assert(to_imgui_key(key_state{Key::CONTROL, true, true}) == ImGuiKey_RightCtrl); + static_assert(to_imgui_key(key_state{Key::SHIFT, false, true}) == ImGuiKey_LeftShift); + static_assert(to_imgui_key(key_state{Key::SHIFT, true, true}) == ImGuiKey_RightShift); + static_assert(to_imgui_key(key_state{Key::ALT, false, true}) == ImGuiKey_LeftAlt); + static_assert(to_imgui_key(key_state{Key::ALT, true, true}) == ImGuiKey_RightAlt); + static_assert(to_imgui_key(key_state{Key::PLATFORM, false, true}) == ImGuiKey_LeftSuper); + static_assert(to_imgui_key(key_state{Key::PLATFORM, true, true}) == ImGuiKey_RightSuper); +} + +TIMGUI_TEST(to_imgui_key, no_imgui_key) { + static_assert(to_imgui_key(key_state{Key::NONE, false, true}) == ImGuiKey_None); + static_assert(to_imgui_key(key_state{Key::META, false, true}) == ImGuiKey_None); + static_assert(to_imgui_key(key_state{Key::MOUSE_LEFT, false, true}) == ImGuiKey_None); + static_assert(to_imgui_key(key_state{Key::CUSTOM_0, false, true}) == ImGuiKey_None); +} + +TIMGUI_TEST(to_imgui_mod, both_sides) { + static_assert(to_imgui_mod(ImGuiKey_LeftCtrl) == ImGuiMod_Ctrl); + static_assert(to_imgui_mod(ImGuiKey_RightCtrl) == ImGuiMod_Ctrl); + static_assert(to_imgui_mod(ImGuiKey_LeftShift) == ImGuiMod_Shift); + static_assert(to_imgui_mod(ImGuiKey_RightShift) == ImGuiMod_Shift); + static_assert(to_imgui_mod(ImGuiKey_LeftAlt) == ImGuiMod_Alt); + static_assert(to_imgui_mod(ImGuiKey_RightAlt) == ImGuiMod_Alt); + static_assert(to_imgui_mod(ImGuiKey_LeftSuper) == ImGuiMod_Super); + static_assert(to_imgui_mod(ImGuiKey_RightSuper) == ImGuiMod_Super); + static_assert(to_imgui_mod(ImGuiKey_A) == ImGuiMod_None); +} + +TIMGUI_TEST(to_imgui_button, mouse_keys) { + static_assert(to_imgui_button(Key::MOUSE_LEFT) == 0); + static_assert(to_imgui_button(Key::MOUSE_RIGHT) == 1); + static_assert(to_imgui_button(Key::MOUSE_MIDDLE) == 2); + static_assert(to_imgui_button(Key::MOUSE_4) == 3); + static_assert(to_imgui_button(Key::MOUSE_5) == 4); + static_assert(!to_imgui_button(Key::A).has_value()); +} + +TIMGUI_TEST(modifier_keys, down_while_one_side_is_down) { + modifier_keys modifiers{}; + + EXPECT_TRUE(modifiers.set(ImGuiKey_LeftCtrl, true)); + EXPECT_TRUE(modifiers.set(ImGuiKey_RightCtrl, true)); + EXPECT_TRUE(modifiers.set(ImGuiKey_LeftCtrl, false)); + EXPECT_FALSE(modifiers.set(ImGuiKey_RightCtrl, false)); +} + +TIMGUI_TEST(modifier_keys, modifiers_are_apart) { + modifier_keys modifiers{}; + + EXPECT_TRUE(modifiers.set(ImGuiKey_LeftShift, true)); + EXPECT_FALSE(modifiers.set(ImGuiKey_RightAlt, false)); + EXPECT_TRUE(modifiers.set(ImGuiKey_RightSuper, true)); + EXPECT_FALSE(modifiers.set(ImGuiKey_LeftShift, false)); +} + +TIMGUI_TEST(add_event, key_follows_the_layout) { + ScopedContext const context{}; + modifier_keys modifiers{}; + + add_event(ImGui::GetIO(), key_event(Key::Q, false, true, "a"), modifiers); + add_event(ImGui::GetIO(), key_event(Key::Q, false, false, "a"), modifiers); + + EXPECT_EQ(key_events(context), (key_events_t{{ImGuiKey_A, true}, {ImGuiKey_A, false}})); +} + +TIMGUI_TEST(add_event, modifier_event_before_the_key) { + ScopedContext const context{}; + modifier_keys modifiers{}; + auto& io = ImGui::GetIO(); + + add_event(io, key_event(Key::CONTROL, false, true), modifiers); + add_event(io, key_event(Key::CONTROL, true, true), modifiers); + add_event(io, key_event(Key::CONTROL, false, false), modifiers); + add_event(io, key_event(Key::CONTROL, true, false), modifiers); + + // ImGui drops an event without a change: the second down and the first up of ImGuiMod_Ctrl + EXPECT_EQ( + key_events(context), + (key_events_t{ + {ImGuiMod_Ctrl, true}, + {ImGuiKey_LeftCtrl, true}, + {ImGuiKey_RightCtrl, true}, + {ImGuiKey_LeftCtrl, false}, + {ImGuiMod_Ctrl, false}, + {ImGuiKey_RightCtrl, false}, + }) + ); +} + +TIMGUI_TEST(add_event, repeat_keeps_the_key_down) { + ScopedContext const context{}; + modifier_keys modifiers{}; + auto& io = ImGui::GetIO(); + + add_event(io, key_event(Key::DEL, false, true, "\x7F"), modifiers); + add_event(io, key_event(Key::DEL, false, true, "\x7F", true), modifiers); + + EXPECT_EQ(key_events(context), (key_events_t{{ImGuiKey_Delete, true}})); +} + +TIMGUI_TEST(add_event, mouse_button) { + ScopedContext const context{}; + modifier_keys modifiers{}; + + add_event(ImGui::GetIO(), key_event(Key::MOUSE_4, false, true), modifiers); + + ASSERT_EQ(context.events().Size, 1); + auto const& event = context.events()[0]; + EXPECT_EQ(event.Type, ImGuiInputEventType_MouseButton); + EXPECT_EQ(event.MouseButton.Button, 3); + EXPECT_TRUE(event.MouseButton.Down); +} + +TIMGUI_TEST(add_event, mouse_position) { + ScopedContext const context{}; + modifier_keys modifiers{}; + + add_event(ImGui::GetIO(), axis_event(Axis::MOUSE_POSITION, 10.f, 20.f), modifiers); + + ASSERT_EQ(context.events().Size, 1); + auto const& event = context.events()[0]; + EXPECT_EQ(event.Type, ImGuiInputEventType_MousePos); + EXPECT_EQ(event.MousePos.PosX, 10.f); + EXPECT_EQ(event.MousePos.PosY, 20.f); +} + +TIMGUI_TEST(add_event, scroll_keeps_the_sign) { + ScopedContext const context{}; + modifier_keys modifiers{}; + + add_event(ImGui::GetIO(), axis_event(Axis::MOUSE_SCROLL, 0.5f, -1.f), modifiers); + + ASSERT_EQ(context.events().Size, 1); + auto const& event = context.events()[0]; + EXPECT_EQ(event.Type, ImGuiInputEventType_MouseWheel); + EXPECT_EQ(event.MouseWheel.WheelX, 0.5f); + EXPECT_EQ(event.MouseWheel.WheelY, -1.f); +} + +TIMGUI_TEST(add_event, text) { + ScopedContext const context{}; + modifier_keys modifiers{}; + + add_event( + ImGui::GetIO(), + cgfw::TextEvent{.text = "\xC3\xA9", .time = cth::chrono::clock_t::now()}, + modifiers + ); + + ASSERT_EQ(context.events().Size, 1); + auto const& event = context.events()[0]; + EXPECT_EQ(event.Type, ImGuiInputEventType_Text); + EXPECT_EQ(event.Text.Char, 0xE9u); +} + +TIMGUI_TEST(add_event, focus) { + ScopedContext const context{}; + modifier_keys modifiers{}; + + // a new context has the focus: a gain is no change + add_event( + ImGui::GetIO(), + cgfw::FocusEvent{.focused = false, .time = cth::chrono::clock_t::now()}, + modifiers + ); + + ASSERT_EQ(context.events().Size, 1); + auto const& event = context.events()[0]; + EXPECT_EQ(event.Type, ImGuiInputEventType_Focus); + EXPECT_FALSE(event.AppFocused.Focused); +} + +TIMGUI_TEST(add_event, focus_loss_forgets_the_modifier_keys) { + ScopedContext const context{}; + modifier_keys modifiers{}; + auto& io = ImGui::GetIO(); + + add_event(io, key_event(Key::SHIFT, false, true), modifiers); + add_event( + io, + cgfw::FocusEvent{.focused = false, .time = cth::chrono::clock_t::now()}, + modifiers + ); + + // the left shift went up without focus + EXPECT_TRUE(modifiers.set(ImGuiKey_RightShift, true)); + EXPECT_FALSE(modifiers.set(ImGuiKey_RightShift, false)); +} + +TIMGUI_TEST(add_event, no_imgui_key_adds_nothing) { + ScopedContext const context{}; + modifier_keys modifiers{}; + + add_event(ImGui::GetIO(), key_event(Key::CUSTOM_0, false, true), modifiers); + add_event(ImGui::GetIO(), axis_event(Axis::CUSTOM_0, 1.f, 1.f), modifiers); + + EXPECT_EQ(context.events().Size, 0); +} +} diff --git a/timgui/tests/src/pch/glob/gtest.hpp b/timgui/tests/src/pch/glob/gtest.hpp new file mode 100644 index 00000000..e469bb31 --- /dev/null +++ b/timgui/tests/src/pch/glob/gtest.hpp @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/timgui/tests/src/pch/glob/imgui.hpp b/timgui/tests/src/pch/glob/imgui.hpp new file mode 100644 index 00000000..a3e2df15 --- /dev/null +++ b/timgui/tests/src/pch/glob/imgui.hpp @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/timgui/tests/src/pch/glob/implot.hpp b/timgui/tests/src/pch/glob/implot.hpp new file mode 100644 index 00000000..e4976423 --- /dev/null +++ b/timgui/tests/src/pch/glob/implot.hpp @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/timgui/tests/src/pch/pch.hpp b/timgui/tests/src/pch/pch.hpp new file mode 100644 index 00000000..28272c3c --- /dev/null +++ b/timgui/tests/src/pch/pch.hpp @@ -0,0 +1,7 @@ +#pragma once +#include "glob/gtest.hpp" +#include "glob/imgui.hpp" +#include "glob/implot.hpp" + +#include "context.hpp" +#include "test.hpp" diff --git a/timgui/tests/src/test.hpp b/timgui/tests/src/test.hpp new file mode 100644 index 00000000..0d0c8d82 --- /dev/null +++ b/timgui/tests/src/test.hpp @@ -0,0 +1,60 @@ +#pragma once +#include "cgfw/window/window.hpp" + +#include "cvk/base/instance_config.hpp" + +#include + +#include +#include +#include +#include +#include + +#define TIMGUI_TEST(suite, test_name) S_TEST(timgui, suite, test_name) + +/** + * skips the test without a display + */ +#define TIMGUI_SKIP_WITHOUT_DISPLAY() \ + if(!timgui::test::display_available()) GTEST_SKIP() << "no display" + +namespace timgui::test { +constexpr std::string_view APP_NAME = "timgui_tests"; + +/** + * size of `window_config()` + */ +inline constexpr VkExtent2D WINDOW_EXTENT{64, 64}; + +/** + * @return a display exists, linux: `WAYLAND_DISPLAY` is set + */ +[[nodiscard]] bool display_available(); + +/** + * hidden window: a test run shows no window + */ +[[nodiscard]] inline cgfw::Window::Config window_config() { + return cgfw::Window::Config{ + .title = "timgui test", + .extent = WINDOW_EXTENT, + .flags = cgfw::WindowFlags::HIDE + }; +} + +/** + * instance config with `APP_NAME` + * @param debugMessengerOpt see `cvk::InstanceConfig::debugMessenger` + */ +[[nodiscard]] inline cvk::InstanceConfig instance_config( + std::vector extensions = {}, + std::optional debugMessengerOpt = std::nullopt +) { + return cvk::InstanceConfig{ + .appName = std::string{APP_NAME}, + .extensions = std::move(extensions), + .debugMessenger = debugMessengerOpt, + }; +} +} diff --git a/vcpkg.json b/vcpkg.json index 25b943f4..7cae2a60 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -5,6 +5,8 @@ "glm", "gtl", "gtest", + "imgui", + "implot", "volk", "vulkan-memory-allocator", "vulkan-utility-libraries", From ebfa76df16032cdf284c2430eb87162087533444 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:56:06 +0100 Subject: [PATCH 11/68] lib: rgfw with the window list setup after the platform creation (ColleagueRiley/RGFW#612) --- lib/rgfw | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/rgfw b/lib/rgfw index 482af80a..6da695de 160000 --- a/lib/rgfw +++ b/lib/rgfw @@ -1 +1 @@ -Subproject commit 482af80a4a95ff4e5339e0b8dd11db72fdec5d75 +Subproject commit 6da695de7357c7bef230a0130187da51baaca7e8 From 8f3e07db3880a3c47c2006609f50d01be3ee71fe Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:05:01 +0100 Subject: [PATCH 12/68] demo/cube: frame time window, median, p75 and p99 of the last 240 frames and an ImPlot graph --- demo/cube/src/main.cpp | 148 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 140 insertions(+), 8 deletions(-) diff --git a/demo/cube/src/main.cpp b/demo/cube/src/main.cpp index 7b589239..81519301 100644 --- a/demo/cube/src/main.cpp +++ b/demo/cube/src/main.cpp @@ -27,14 +27,17 @@ #include +#include #include #include +#include #include #include #include #include +#include #include #include @@ -48,7 +51,9 @@ #include #include #include +#include #include +#include #include #include @@ -281,23 +286,141 @@ struct Cube { jvk::Sampler sampler; }; +//IMPLEMENT moves into an engine library /** - * ImGui window with the frame time and the frames per second + * frame times of the last `CAPACITY` frames, in ms + * @details ring buffer: full -> a new time overwrites the oldest one */ -void stats_window() { - auto const framerate = ImGui::GetIO().Framerate; - ImGui::Begin("stats"); - ImGui::Text("%.2f ms", 1000.f / framerate); - ImGui::Text("%.0f fps", framerate); +class FrameTimes { +public: + static constexpr size_t CAPACITY = 240; + + /** + * stores the time of a frame, in ms + * @details full -> overwrites the oldest time + */ + constexpr void add(cth::chrono::clock_t::duration frameTime) { + _times[_nextIdx] = std::chrono::duration{frameTime}.count(); + _nextIdx = (_nextIdx + 1) % CAPACITY; + _count = std::min(_count + 1, CAPACITY); + } + + /** + * @return the stored time at the rank `fraction * (count - 1)` of the sorted times + * @details the rank is rounded down + * @pre `!empty()` + * @pre `0 <= fraction <= 1` + */ + [[nodiscard]] constexpr float percentile(float fraction) const { + CTH_CRITICAL(empty(), "no frame time is stored") {} + CTH_CRITICAL( + fraction < 0.f || fraction > 1.f, + "the fraction must be in [0, 1], got {}", + fraction + ) {} + + auto sorted = _times; + auto const stored = std::span{sorted}.first(_count); + auto const rank = static_cast(fraction * static_cast(_count - 1)); + std::ranges::nth_element(stored, stored.begin() + static_cast(rank)); + return stored[rank]; + } + + [[nodiscard]] constexpr float median() const { return percentile(0.5f); } + [[nodiscard]] constexpr float p75() const { return percentile(0.75f); } + [[nodiscard]] constexpr float p99() const { return percentile(0.99f); } + + /** + * @return the stored times in storage order, the oldest at `oldestIdx()` + */ + [[nodiscard]] constexpr std::span values() const { + return std::span{_times}.first(_count); + } + + /** + * @return index of the oldest time in `values()` + */ + [[nodiscard]] constexpr size_t oldestIdx() const { return _count < CAPACITY ? 0 : _nextIdx; } + + [[nodiscard]] constexpr bool empty() const { return _count == 0; } + +private: + std::array _times{}; + size_t _nextIdx = 0; ///< of the next `add()` + size_t _count = 0; +}; + +constexpr float FRAME_TIME_WINDOW_WIDTH = 360.f; ///< at the first frame, the user can resize it +constexpr float FRAME_TIME_PLOT_HEIGHT = 120.f; + +/** + * ImGui window of the frame times: the percentiles and a plot of the stored times + * @details the collapsed window shows the percentiles in its title + * @param[out] collapsed the window was collapsed in the last frame, gets the state of this frame + */ +void frame_time_window(FrameTimes const& times, bool& collapsed) { + // ImGui knows the collapsed state only inside Begin(): the title follows one frame later + auto const title = collapsed && !times.empty() + ? std::format( + "frame time (med {:.2f}ms, p75 {:.2f}ms, p99 {:.2f}ms)###frame_time", + times.median(), + times.p75(), + times.p99() + ) + : std::string{"frame time###frame_time"}; + + ImGui::SetNextWindowSize(ImVec2{FRAME_TIME_WINDOW_WIDTH, 0.f}, ImGuiCond_FirstUseEver); + bool const visible = ImGui::Begin(title.c_str()); + collapsed = ImGui::IsWindowCollapsed(); + + if(visible && !times.empty()) { + ImGui::TextUnformatted(std::format("med {:.2f}ms", times.median()).c_str()); + ImGui::TextUnformatted(std::format("p75 {:.2f}ms", times.p75()).c_str()); + ImGui::TextUnformatted(std::format("p99 {:.2f}ms", times.p99()).c_str()); + + if(ImPlot::BeginPlot( + "##frame_times", + ImVec2{-1.f, FRAME_TIME_PLOT_HEIGHT}, + ImPlotFlags_NoLegend | ImPlotFlags_NoMenus + )) { + // x: the frames, the newest at 0; y: the ms, labels on the right + ImPlot::SetupAxes( + nullptr, + nullptr, + ImPlotAxisFlags_None, + ImPlotAxisFlags_AutoFit | ImPlotAxisFlags_Opposite + ); + ImPlot::SetupAxisLimits( + ImAxis_X1, + -static_cast(FrameTimes::CAPACITY), + 0., + ImPlotCond_Always + ); + + auto const values = times.values(); + ImPlotSpec spec{}; + spec.Offset = static_cast(times.oldestIdx()); + ImPlot::PlotLine( + "##ms", + values.data(), + static_cast(values.size()), + 1., + -static_cast(values.size() - 1), + spec + ); + ImPlot::EndPlot(); + } + } ImGui::End(); } /** - * draws the spinning cube and the ImGui window in every frame until the window closes + * draws the spinning cube and the frame time window in every frame until the window closes * @details * - only the scopes: the `jvk::scoped_submit` ends first and submits * - then the `jvk::scoped_acquire` presents * - the ImGui frame comes first: it takes the events also in a frame without an image + * - frame time: the time between the starts of two iterations, the first iteration has none */ cth::co::executor_task draw_frames( cgfw::Window& window, @@ -313,10 +436,19 @@ cth::co::executor_task draw_frames( glm::quat rotation{1.f, 0.f, 0.f, 0.f}; auto last = std::chrono::steady_clock::now(); + FrameTimes frameTimes{}; + std::optional lastIterationStartOpt{}; + bool frameTimeCollapsed = false; + while(!window.shouldClose()) { + auto const iterationStart = cth::chrono::clock_t::now(); + if(lastIterationStartOpt.has_value()) + frameTimes.add(iterationStart - *lastIterationStartOpt); + lastIterationStartOpt = iterationStart; + window.pollEvents(); auto imguiFrame = imgui.frame(); - stats_window(); + frame_time_window(frameTimes, frameTimeCollapsed); auto& drawData = imguiFrame.render(); auto& stage = (co_await graph.nextFrame()).stage(CUBE_STAGE_ID); From 7515908d49c1e606b84b1b1e562d67b0097f6e7e Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:10:49 +0100 Subject: [PATCH 13/68] cmake: glslc from the vcpkg port shaderc, one lookup for timgui and the demos, no glslc is a configure error --- CMakeLists.txt | 1 + demo/cube/CMakeLists.txt | 7 ------- demo/triangle/CMakeLists.txt | 7 ------- lib/cmake/shaderc.cmake | 16 ++++++++++++++++ timgui/CMakeLists.txt | 7 ------- vcpkg.json | 4 ++++ 6 files changed, 21 insertions(+), 21 deletions(-) create mode 100644 lib/cmake/shaderc.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index 0ca94481..5770c7ac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -18,6 +18,7 @@ endif () include(lib/cmake/cth.cmake) include(lib/cmake/rgfw.cmake) +include(lib/cmake/shaderc.cmake) if (JOLLY_ENABLE_TESTS) enable_testing() diff --git a/demo/cube/CMakeLists.txt b/demo/cube/CMakeLists.txt index ae4a5e08..499695db 100644 --- a/demo/cube/CMakeLists.txt +++ b/demo/cube/CMakeLists.txt @@ -1,10 +1,3 @@ -# glslc of the PATH or of the Vulkan SDK, without it no demo: the Windows CI has none -cth_find_program(GLSLC_EXECUTABLE glslc OPTIONAL HINTS ENV VULKAN_SDK PATH_SUFFIXES bin) -if (NOT GLSLC_EXECUTABLE) - message(STATUS "glslc not found, no cube demo") - return() -endif () - find_package(glm CONFIG REQUIRED) cth_glob_cpp(CUBE_SRC "src") diff --git a/demo/triangle/CMakeLists.txt b/demo/triangle/CMakeLists.txt index 5a4b0d7d..31ab4dee 100644 --- a/demo/triangle/CMakeLists.txt +++ b/demo/triangle/CMakeLists.txt @@ -1,10 +1,3 @@ -# glslc of the PATH or of the Vulkan SDK, without it no demo: the Windows CI has none -cth_find_program(GLSLC_EXECUTABLE glslc OPTIONAL HINTS ENV VULKAN_SDK PATH_SUFFIXES bin) -if (NOT GLSLC_EXECUTABLE) - message(STATUS "glslc not found, no triangle demo") - return() -endif () - cth_glob_cpp(TRIANGLE_SRC "src") add_executable(triangle ${TRIANGLE_SRC}) diff --git a/lib/cmake/shaderc.cmake b/lib/cmake/shaderc.cmake new file mode 100644 index 00000000..059c5a3e --- /dev/null +++ b/lib/cmake/shaderc.cmake @@ -0,0 +1,16 @@ +# glslc of the vcpkg port shaderc, a host dependency in vcpkg.json: the build compiles the shaders with it +# sets GLSLC_EXECUTABLE, no glslc -> configure error + +# vcpkg defines VCPKG_HOST_TRIPLET only if the user sets it, a native build has the target triplet as host +if (DEFINED VCPKG_HOST_TRIPLET AND NOT VCPKG_HOST_TRIPLET STREQUAL "") + set(SHADERC_HOST_TRIPLET "${VCPKG_HOST_TRIPLET}") +else () + set(SHADERC_HOST_TRIPLET "${VCPKG_TARGET_TRIPLET}") +endif () + +# the tools of vcpkg first, then the PATH +cth_find_program( + GLSLC_EXECUTABLE glslc + HINTS "${VCPKG_INSTALLED_DIR}/${SHADERC_HOST_TRIPLET}/tools/shaderc" +) +message(STATUS "glslc: ${GLSLC_EXECUTABLE}") diff --git a/timgui/CMakeLists.txt b/timgui/CMakeLists.txt index a19c459b..5c2a94e4 100644 --- a/timgui/CMakeLists.txt +++ b/timgui/CMakeLists.txt @@ -1,10 +1,3 @@ -# glslc of the PATH or of the Vulkan SDK, without it no timgui: the Windows CI has none -cth_find_program(GLSLC_EXECUTABLE glslc OPTIONAL HINTS ENV VULKAN_SDK PATH_SUFFIXES bin) -if (NOT GLSLC_EXECUTABLE) - message(STATUS "glslc not found, no timgui") - return() -endif () - find_package(imgui CONFIG REQUIRED) find_package(implot CONFIG REQUIRED) diff --git a/vcpkg.json b/vcpkg.json index 7cae2a60..d3e083e0 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -7,6 +7,10 @@ "gtest", "imgui", "implot", + { + "name": "shaderc", + "host": true + }, "volk", "vulkan-memory-allocator", "vulkan-utility-libraries", From ea8731dae02f8257b07477f10424816fc7043e35 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:19:48 +0100 Subject: [PATCH 14/68] cmake: glslc from the Vulkan SDK or the system, not from vcpkg - the SDK is needed for the validation layers anyway, it has glslc - the Windows CI installs the latest Vulkan SDK - README and AGENTS.md name the SDK (Windows) and the system packages (Linux) --- .github/actions/setup-windows/action.yml | 12 +++++++++++- AGENTS.md | 2 ++ CMakeLists.txt | 2 +- README.md | 2 ++ lib/cmake/glslc.cmake | 4 ++++ lib/cmake/shaderc.cmake | 16 ---------------- vcpkg.json | 4 ---- 7 files changed, 20 insertions(+), 22 deletions(-) create mode 100644 lib/cmake/glslc.cmake delete mode 100644 lib/cmake/shaderc.cmake diff --git a/.github/actions/setup-windows/action.yml b/.github/actions/setup-windows/action.yml index 647a7ff0..941437c5 100644 --- a/.github/actions/setup-windows/action.yml +++ b/.github/actions/setup-windows/action.yml @@ -1,5 +1,5 @@ name: 'Setup Windows Environment' -description: 'Sets up MSVC, Vcpkg, BuildCache, CMake and Ninja' +description: 'Sets up MSVC, Vcpkg, BuildCache, the Vulkan SDK, CMake and Ninja' inputs: compiler: description: 'compiler of the CI preset (msvc or clang)' @@ -27,6 +27,16 @@ runs: Expand-Archive buildcache.zip -DestinationPath c:\buildcache echo "c:\buildcache\buildcache\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + - name: Install Vulkan SDK + shell: pwsh + run: | + # glslc compiles the shaders: the latest SDK of LunarG + Invoke-WebRequest -Uri "https://sdk.lunarg.com/sdk/download/latest/windows/vulkan-sdk.exe" -OutFile "$env:RUNNER_TEMP\vulkan-sdk.exe" + Start-Process -FilePath "$env:RUNNER_TEMP\vulkan-sdk.exe" -ArgumentList "--root", "C:\VulkanSDK", "--accept-licenses", "--default-answer", "--confirm-command", "install" -Wait -NoNewWindow + & "C:\VulkanSDK\Bin\glslc.exe" --version + "VULKAN_SDK=C:\VulkanSDK" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + echo "C:\VulkanSDK\Bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + - name: Install LLVM if: inputs.compiler == 'clang' shell: pwsh diff --git a/AGENTS.md b/AGENTS.md index 401dad40..55e1caf4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,6 +57,8 @@ ctest --test-dir out/build/gcc_release --output-on-failure - Tests that need a device use `test::Context` (`cvk/tests/src/context.hpp`). It fails the test on validation errors, leaked objects included. - `VCPKG_ROOT` must point at vcpkg. +- `glslc` and the validation layers come from the Vulkan SDK (Windows) or the system packages (Linux), not from + vcpkg. - `doxygen` in the repository root checks the docs (`Doxyfile`, output in `out/doxygen`). A change adds no doxygen warning. diff --git a/CMakeLists.txt b/CMakeLists.txt index 5770c7ac..9358ca72 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -18,7 +18,7 @@ endif () include(lib/cmake/cth.cmake) include(lib/cmake/rgfw.cmake) -include(lib/cmake/shaderc.cmake) +include(lib/cmake/glslc.cmake) if (JOLLY_ENABLE_TESTS) enable_testing() diff --git a/README.md b/README.md index 27cce920..988a10bf 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,8 @@ built and tested with: - [vcpkg](https://github.com/microsoft/vcpkg) with `VCPKG_ROOT` set - gcc 16, clang 23 or msvc - a vulkan 1.3 driver +- windows: the [vulkan sdk](https://vulkan.lunarg.com/sdk/home), linux: the packages of the validation layers and shaderc + - glslc compiles the shaders, debug builds enable the validation layers ## build & test ```bash diff --git a/lib/cmake/glslc.cmake b/lib/cmake/glslc.cmake new file mode 100644 index 00000000..89754330 --- /dev/null +++ b/lib/cmake/glslc.cmake @@ -0,0 +1,4 @@ +# glslc of the Vulkan SDK or of the system: the build compiles the shaders with it +# sets GLSLC_EXECUTABLE, no glslc -> configure error +cth_find_program(GLSLC_EXECUTABLE glslc HINTS ENV VULKAN_SDK PATH_SUFFIXES bin Bin) +message(STATUS "glslc: ${GLSLC_EXECUTABLE}") diff --git a/lib/cmake/shaderc.cmake b/lib/cmake/shaderc.cmake deleted file mode 100644 index 059c5a3e..00000000 --- a/lib/cmake/shaderc.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# glslc of the vcpkg port shaderc, a host dependency in vcpkg.json: the build compiles the shaders with it -# sets GLSLC_EXECUTABLE, no glslc -> configure error - -# vcpkg defines VCPKG_HOST_TRIPLET only if the user sets it, a native build has the target triplet as host -if (DEFINED VCPKG_HOST_TRIPLET AND NOT VCPKG_HOST_TRIPLET STREQUAL "") - set(SHADERC_HOST_TRIPLET "${VCPKG_HOST_TRIPLET}") -else () - set(SHADERC_HOST_TRIPLET "${VCPKG_TARGET_TRIPLET}") -endif () - -# the tools of vcpkg first, then the PATH -cth_find_program( - GLSLC_EXECUTABLE glslc - HINTS "${VCPKG_INSTALLED_DIR}/${SHADERC_HOST_TRIPLET}/tools/shaderc" -) -message(STATUS "glslc: ${GLSLC_EXECUTABLE}") diff --git a/vcpkg.json b/vcpkg.json index d3e083e0..7cae2a60 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -7,10 +7,6 @@ "gtest", "imgui", "implot", - { - "name": "shaderc", - "host": true - }, "volk", "vulkan-memory-allocator", "vulkan-utility-libraries", From b8e19be73b8882e5cdb676258580315ae0ee5ba5 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:26:42 +0100 Subject: [PATCH 15/68] timgui: Config::stencilFormat, the stencil attachment of the renderings like cvk::GraphicsPipeline::Config --- timgui/incl/timgui/imgui.hpp | 2 + timgui/src/imgui.cpp | 1 + timgui/tests/src/imgui_test.cpp | 86 ++++++++++++++++++++++++++++----- 3 files changed, 76 insertions(+), 13 deletions(-) diff --git a/timgui/incl/timgui/imgui.hpp b/timgui/incl/timgui/imgui.hpp index d8865c60..671cf28a 100644 --- a/timgui/incl/timgui/imgui.hpp +++ b/timgui/incl/timgui/imgui.hpp @@ -129,6 +129,8 @@ struct Imgui::Config { VkFormat colorFormat; /** depth attachment of those renderings, `VK_FORMAT_UNDEFINED` -> none */ VkFormat depthFormat = VK_FORMAT_UNDEFINED; + /** stencil attachment of those renderings, `VK_FORMAT_UNDEFINED` -> none */ + VkFormat stencilFormat = VK_FORMAT_UNDEFINED; VkSampleCountFlagBits samples = VK_SAMPLE_COUNT_1_BIT; ///< samples of those renderings std::filesystem::path iniFile{}; ///< ImGui settings file, empty -> no file }; diff --git a/timgui/src/imgui.cpp b/timgui/src/imgui.cpp index cb98b50a..58b27a1a 100644 --- a/timgui/src/imgui.cpp +++ b/timgui/src/imgui.cpp @@ -261,6 +261,7 @@ namespace { .colorBlendAttachments = {BLENDING}, .colorFormats = {config.colorFormat}, .depthFormat = config.depthFormat, + .stencilFormat = config.stencilFormat, }; pipelineConfig.rasterization.cullMode = VK_CULL_MODE_NONE; pipelineConfig.multisample.rasterizationSamples = config.samples; diff --git a/timgui/tests/src/imgui_test.cpp b/timgui/tests/src/imgui_test.cpp index e71ba6b6..2cff9b60 100644 --- a/timgui/tests/src/imgui_test.cpp +++ b/timgui/tests/src/imgui_test.cpp @@ -14,10 +14,13 @@ #include "cgfw/window/window.hpp" +#include "cvk/base/core.hpp" +#include "cvk/base/physical_device.hpp" #include "cvk/data/buffer/buffer.hpp" #include "cvk/data/descriptor/image_descriptor.hpp" #include "cvk/data/img/image_view.hpp" #include "cvk/render/cmd/rendering_info.hpp" +#include "cvk/utility/vk_exceptions.hpp" #include #include @@ -118,31 +121,43 @@ namespace { /** * uploads and draws the draw data into the cleared target in the next frame * @details copies the target to its buffer, waits until the gpu finished + * @param depthStencilViewPtr `nullptr` -> no depth and no stencil attachment, else both */ void draw_frame( jvk::Core const& core, jvk::StageGraph& graph, Imgui& imgui, ImDrawData& drawData, - Target const& target + Target const& target, + cvk::ImageView const* depthStencilViewPtr = nullptr ) { + cvk::RenderingInfo info{ + .colorAttachments = { + cvk::RenderingAttachment{ + .view = target.view, + .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + }, + }, + }; + if(depthStencilViewPtr != nullptr) { + cvk::RenderingAttachment const depthStencil{ + .view = *depthStencilViewPtr, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .clearValue = {.depthStencil = {.depth = 1.f, .stencil = 0}}, + }; + info.depthAttachment = depthStencil; + info.stencilAttachment = depthStencil; + } + auto& stage = next_stage(core, graph); { auto const submit = stage.begin(); imgui.upload(stage, *submit, drawData); { - auto const rendering = submit->beginRendering( - { - .colorAttachments = { - cvk::RenderingAttachment{ - .view = target.view, - .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_STORE, - }, - }, - } - ); + auto const rendering = submit->beginRendering(info); imgui.draw(stage, *submit, drawData); } target.image.copyTo(*submit, target.readback); @@ -252,6 +267,51 @@ TIMGUI_TEST(Imgui, draw_fills_with_the_vertex_color) { EXPECT_EQ(target.pixel(EXTENT.width / 2, EXTENT.height / 2), RED); } +TIMGUI_TEST(Imgui, draw_into_a_depth_stencil_rendering) { + constexpr std::array CANDIDATES{ + VK_FORMAT_D24_UNORM_S8_UINT, + VK_FORMAT_D32_SFLOAT_S8_UINT, + VK_FORMAT_D16_UNORM_S8_UINT, + }; + + test::Context context{}; + cvk::Core const& vk = context.core; + VkFormat depthStencilFormat = VK_FORMAT_UNDEFINED; + try { + depthStencilFormat = vk.physicalDevice().findSupportedFormat( + CANDIDATES, + VK_IMAGE_TILING_OPTIMAL, + VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT + ); + } + catch(cvk::cvk_exception const&) { GTEST_SKIP() << "no depth stencil format"; } + + cgfw::Window const window{test::window_config()}; + Imgui imgui{ + context.core, + window, + { + .colorFormat = VK_FORMAT_R8G8B8A8_UNORM, + .depthFormat = depthStencilFormat, + .stencilFormat = depthStencilFormat, + } + }; + Target const target{context.core, VK_FORMAT_R8G8B8A8_UNORM}; + jvk::Image const depthStencil{ + context.core, + {.format = depthStencilFormat, .usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT}, + EXTENT + }; + cvk::ImageView const depthStencilView{depthStencil, {}, cvk::create}; + jvk::StageGraph graph{context.core, {.stages = {{.queueIdx = 0}}}}; + + auto& drawData = rect_frame(RED); + draw_frame(context.core, graph, imgui, drawData, target, &depthStencilView); + + // no depth test: the cleared depth does not hide the draw + EXPECT_EQ(target.pixel(EXTENT.width / 2, EXTENT.height / 2), RED); +} + TIMGUI_TEST(Imgui, srgb_target_keeps_the_srgb_color) { test::Context context{}; cgfw::Window const window{test::window_config()}; From 68c4e7813e0502e8c99186edf782f372e7098dd9 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:37:08 +0100 Subject: [PATCH 16/68] lib: rgfw without VK_USE_PLATFORM_* in RGFW.h, the platform of vulkan.h stays the same in a file (Windows build) --- lib/rgfw | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/rgfw b/lib/rgfw index 6da695de..ad849de5 160000 --- a/lib/rgfw +++ b/lib/rgfw @@ -1 +1 @@ -Subproject commit 6da695de7357c7bef230a0130187da51baaca7e8 +Subproject commit ad849de5a1520638de4a8c7c1ceadaef97c90fa9 From 9912c154f4c4d54ec3af57ebd59a2a9fdf2d5fb3 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:05:46 +0100 Subject: [PATCH 17/68] ci: buildcache log of the Windows clang build, TEMP diagnosis of the stale precompiled header --- .github/workflows/windows-pipeline.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/.github/workflows/windows-pipeline.yml b/.github/workflows/windows-pipeline.yml index da8c03e7..85b94d10 100644 --- a/.github/workflows/windows-pipeline.yml +++ b/.github/workflows/windows-pipeline.yml @@ -29,8 +29,23 @@ jobs: with: compiler: ${{ inputs.compiler }} + #TEMP buildcache diagnosis: the most verbose log of buildcache for the clang build + - name: Enable BuildCache log + if: inputs.compiler == 'clang' + run: | + echo "BUILDCACHE_DEBUG=1" >> "$GITHUB_ENV" + echo "BUILDCACHE_LOG_FILE=$RUNNER_TEMP/buildcache.log" >> "$GITHUB_ENV" + - name: Build uses: ./.github/actions/build-engine with: cache_prefix: engine-windows preset: ci_windows_${{ inputs.compiler }} + + #TEMP buildcache diagnosis: the log also of a failed build + - name: Upload BuildCache log + if: always() && inputs.compiler == 'clang' + uses: actions/upload-artifact@v7 + with: + name: buildcache-log-windows-clang + path: ${{ runner.temp }}/buildcache.log From e830a0645684e53a734019bbbe5105a72ade31e7 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:25:17 +0100 Subject: [PATCH 18/68] cmake: shaders with the GLSL language of cth_cmake, no run-time shader compile - lib/cth_cmake: GLSL language (codethinki/cth_cmake#11), glslc.cmake removed - timgui, demos, cvk and jvk tests: shaders in OBJECT libraries, the includes come from target_include_directories - demos and tests read the .spv files from the object folder, no copy - cvk: Shader::compile() and the compile constructor removed, the tests load SPIR-V of the build - jvk tests: no committed SPIR-V --- CMakeLists.txt | 6 +- ci/docker/linux/Dockerfile | 2 +- .../cvk/render/pipeline/shader/shader.hpp | 30 - cvk/src/render/pipeline/shader/shader.cpp | 79 +- cvk/tests/CMakeLists.txt | 12 +- cvk/tests/shaders/bindless.frag | 2 + cvk/tests/shaders/buffer_color.frag | 1 + cvk/tests/shaders/fill.vert | 1 + cvk/tests/shaders/heap.comp | 2 + cvk/tests/shaders/local_read.frag | 1 + cvk/tests/shaders/texture.frag | 2 + cvk/tests/shaders/triangle.frag | 1 + cvk/tests/shaders/triangle.vert | 1 + cvk/tests/shaders/values.comp | 1 + .../data/descriptor/descriptor_draw_test.cpp | 14 +- .../data/descriptor/descriptor_heap_test.cpp | 3 +- cvk/tests/src/render/cmd/draw_test.cpp | 5 +- cvk/tests/src/render/cmd/local_read_test.cpp | 7 +- .../render/pipeline/compute_pipeline_test.cpp | 3 +- .../pipeline/graphics_pipeline_test.cpp | 5 +- .../render/pipeline/shader/shader_test.cpp | 80 +- cvk/tests/src/shaders.hpp | 1622 ----------------- cvk/tests/src/test.hpp | 2 +- demo/cube/CMakeLists.txt | 36 +- demo/triangle/CMakeLists.txt | 30 +- jvk/CMakeLists.txt | 4 +- jvk/tests/CMakeLists.txt | 14 + jvk/tests/shaders/heap_copy.comp | 2 + jvk/tests/src/data/heap_test.cpp | 3 +- jvk/tests/src/shaders.hpp | 318 ---- jvk/tests/src/test.hpp | 6 + lib/cmake/glslc.cmake | 4 - lib/cth_cmake | 2 +- timgui/CMakeLists.txt | 39 +- timgui/cmake/spirv_header.cmake | 1 + 35 files changed, 126 insertions(+), 2215 deletions(-) delete mode 100644 cvk/tests/src/shaders.hpp delete mode 100644 jvk/tests/src/shaders.hpp delete mode 100644 lib/cmake/glslc.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index 9358ca72..f388e95c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,6 +8,11 @@ include(cth_setup_utilities) cth_set_compiler_specifics() cth_set_latest_c_cpp_standard() +# the shaders: the GLSL language of cth_cmake, glslc of the Vulkan SDK or of the system +enable_language(GLSL) +# the Vulkan of the engine is a requirement of the project, no user flag of CMAKE_GLSL_FLAGS +add_compile_options($<$:--target-env=vulkan1.3>) + set(CMAKE_CXX_SCAN_FOR_MODULES OFF) # lld links much faster than the default linker @@ -18,7 +23,6 @@ endif () include(lib/cmake/cth.cmake) include(lib/cmake/rgfw.cmake) -include(lib/cmake/glslc.cmake) if (JOLLY_ENABLE_TESTS) enable_testing() diff --git a/ci/docker/linux/Dockerfile b/ci/docker/linux/Dockerfile index 24ab254d..686015f5 100644 --- a/ci/docker/linux/Dockerfile +++ b/ci/docker/linux/Dockerfile @@ -2,7 +2,7 @@ FROM cachyos/cachyos:latest # vulkan-swrast: lavapipe, the cpu vulkan driver of mesa # vulkan-validation-layers: debug builds enable them with synchronization validation -# shaderc: glslc for the shader compile tests +# shaderc: glslc of the GLSL language, the build compiles the shaders # wayland, libxkbcommon: the RGFW Wayland backend of cgfw, the vcpkg ports of them are empty on linux RUN pacman -Syu --noconfirm && \ pacman -S --noconfirm \ diff --git a/cvk/incl/cvk/render/pipeline/shader/shader.hpp b/cvk/incl/cvk/render/pipeline/shader/shader.hpp index 1c7456d5..80f22882 100644 --- a/cvk/incl/cvk/render/pipeline/shader/shader.hpp +++ b/cvk/incl/cvk/render/pipeline/shader/shader.hpp @@ -11,7 +11,6 @@ #include #include #include -#include #include #include @@ -27,8 +26,6 @@ class Shader { struct State; using path_t = std::filesystem::path; - static constexpr std::string_view DEFAULT_COMPILER = "glslc"; - /** * base constructor * @param stage of the shader @@ -53,19 +50,6 @@ class Shader { */ Shader(Core const&, VkShaderStageFlagBits stage, path_t const& spvPath); - /** - * constructs, compiles the glsl file, loads and creates - * @details calls `compile()`, @ref Shader(Core const&, VkShaderStageFlagBits, path_t const&) - * @note warns in release builds: compile the shaders at build time - */ - Shader( - Core const&, - VkShaderStageFlagBits stage, - path_t const& spvPath, - path_t const& glslPath, - path_t const& compilerPath = DEFAULT_COMPILER - ); - /** * @note calls `optDestroy()` */ @@ -134,20 +118,6 @@ class Shader { */ [[nodiscard]] static std::vector load(path_t const& spvPath); - /** - * compiles a glsl file to a SPIR-V file - * @param compilerPath glslc compatible compiler - * @param flags for the compiler - * @details compiler output without error -> logged as warning - * @throws cvk::cvk_exception reason: glsl file missing, compiler failed, details: compiler output - */ - static void compile( - path_t const& glslPath, - path_t const& spvPath, - path_t const& compilerPath = DEFAULT_COMPILER, - std::string_view flags = "-O" - ); - [[nodiscard]] constexpr bool created() const { return static_cast(_handle); } [[nodiscard]] constexpr VkShaderModule get() const { return _handle.get(); } [[nodiscard]] constexpr VkShaderStageFlagBits stage() const { return _stage; } diff --git a/cvk/src/render/pipeline/shader/shader.cpp b/cvk/src/render/pipeline/shader/shader.cpp index 84ee371f..b99ae30b 100644 --- a/cvk/src/render/pipeline/shader/shader.cpp +++ b/cvk/src/render/pipeline/shader/shader.cpp @@ -1,14 +1,9 @@ #include "cvk/render/pipeline/shader/shader.hpp" #include "cvk/base/core.hpp" -#include "cvk/utility/constants.hpp" #include "cvk/utility/vk_exceptions.hpp" -#include -#include - -#include -#include +#include #include @@ -31,22 +26,6 @@ Shader::Shader(Core const& core, VkShaderStageFlagBits stage, path_t const& spvP stage } { create(spvPath); } -Shader::Shader( - Core const& core, - VkShaderStageFlagBits stage, - path_t const& spvPath, - path_t const& glslPath, - path_t const& compilerPath -) : Shader{core, stage} { - CTH_STABLE_WARN( - !constants::DEBUG_MODE, - "compiles shaders at run time, use this in debug builds only" - ) {} - - compile(glslPath, spvPath, compilerPath); - create(spvPath); -} - void Shader::wrap(State const& state) { Core::debug_check(core()); @@ -147,62 +126,6 @@ std::vector Shader::load(path_t const& spvPath) { return spv; } -void Shader::compile( - path_t const& glslPath, - path_t const& spvPath, - path_t const& compilerPath, - std::string_view flags -) { - CVK_STABLE_THROW( - !std::filesystem::exists(glslPath), - "glsl file {} does not exist", - glslPath.string() - ) {} - -#ifdef CTH_PLATFORM_WINDOWS - constexpr std::string_view nullDevice = "NUL"; -#else - constexpr std::string_view nullDevice = "/dev/null"; -#endif - // one log per SPIR-V path: two processes that compile into other directories do not share a log - auto logPath = spvPath; - logPath += ".log"; - - auto command = std::format( - R"("{}" {} -c "{}" -o "{}" >{} 2>"{}")", - compilerPath.string(), - flags, - glslPath.string(), - spvPath.string(), - nullDevice, - logPath.string() - ); -#ifdef CTH_PLATFORM_WINDOWS - // cmd.exe /c removes the outer quotes of a command that starts with a quote - command = std::format("\"{}\"", command); -#endif - - int const result = std::system(command.c_str()); - - std::vector output{}; - if(std::filesystem::exists(logPath)) { - output = cth::io::file::chop(logPath); - std::erase_if(output, [](std::string const& line) { return line.empty(); }); - std::filesystem::remove(logPath); - } - - CVK_STABLE_THROW(result != 0, "shader compilation of {} failed", glslPath.string()) { - details->add("command: {}", command); - for(auto const& line : output) - details->add("{}", line); - } - - CTH_STABLE_WARN(!output.empty(), "shader compiler output for {}", glslPath.string()) { - for(auto const& line : output) - details->add("{}", line); - } -} - void destroy(DeviceTable table, VkShaderModule vkShader) { CTH_WARN(vkShader == VK_NULL_HANDLE, "vkShader invalid (VK_NULL_HANDLE)") {} diff --git a/cvk/tests/CMakeLists.txt b/cvk/tests/CMakeLists.txt index e8e66ebf..3a9d10ce 100644 --- a/cvk/tests/CMakeLists.txt +++ b/cvk/tests/CMakeLists.txt @@ -15,7 +15,17 @@ target_precompile_headers( src/pch/pch.hpp ) -target_compile_definitions(cvk_tests PRIVATE CVK_TEST_SHADER_DIR="${CMAKE_CURRENT_SOURCE_DIR}/shaders") +# the test shaders: GLSL objects, the tests load them from the object folder +cth_glob(CVK_TESTS_GLSL "shaders" PATTERNS *.vert *.frag *.comp) +add_library(cvk_tests_shaders OBJECT ${CVK_TESTS_GLSL}) +add_dependencies(cvk_tests cvk_tests_shaders) + +# the shaders of one source folder share one object folder +target_compile_definitions( + cvk_tests + PRIVATE + CVK_TEST_SHADER_DIR="$,0>>" +) find_package(GTest CONFIG REQUIRED) diff --git a/cvk/tests/shaders/bindless.frag b/cvk/tests/shaders/bindless.frag index 81de6559..d9c2a9f3 100644 --- a/cvk/tests/shaders/bindless.frag +++ b/cvk/tests/shaders/bindless.frag @@ -1,3 +1,5 @@ +// fragment shader: set 0 binding 0 runtime array of sampled images, binding 1 sampler, push data +// `uint` index #version 450 #extension GL_EXT_nonuniform_qualifier : require diff --git a/cvk/tests/shaders/buffer_color.frag b/cvk/tests/shaders/buffer_color.frag index 586ec493..fdc0e4e3 100644 --- a/cvk/tests/shaders/buffer_color.frag +++ b/cvk/tests/shaders/buffer_color.frag @@ -1,3 +1,4 @@ +// fragment shader: push data address of a `vec4` color, location 0 color output #version 450 #extension GL_EXT_buffer_reference : require diff --git a/cvk/tests/shaders/fill.vert b/cvk/tests/shaders/fill.vert index 3df30248..0c6130e3 100644 --- a/cvk/tests/shaders/fill.vert +++ b/cvk/tests/shaders/fill.vert @@ -1,3 +1,4 @@ +// vertex shader: location 0 `vec3` position, no descriptors #version 450 layout(location = 0) in vec3 position; diff --git a/cvk/tests/shaders/heap.comp b/cvk/tests/shaders/heap.comp index 19849591..22e59d3d 100644 --- a/cvk/tests/shaders/heap.comp +++ b/cvk/tests/shaders/heap.comp @@ -1,3 +1,5 @@ +// compute shader: set 0 binding 0 sampled images, binding 1 samplers, binding 2 storage images, +// push data `uint` indices: stores the center of the sampled image at texel 0 of the storage image #version 450 #extension GL_EXT_nonuniform_qualifier : require diff --git a/cvk/tests/shaders/local_read.frag b/cvk/tests/shaders/local_read.frag index a64508b1..ba1189eb 100644 --- a/cvk/tests/shaders/local_read.frag +++ b/cvk/tests/shaders/local_read.frag @@ -1,3 +1,4 @@ +// fragment shader: set 0 binding 0 input attachment index 0, location 0 color output of its value #version 450 layout(input_attachment_index = 0, set = 0, binding = 0) uniform subpassInput color; diff --git a/cvk/tests/shaders/texture.frag b/cvk/tests/shaders/texture.frag index 11b7c0fc..024ecfb1 100644 --- a/cvk/tests/shaders/texture.frag +++ b/cvk/tests/shaders/texture.frag @@ -1,3 +1,5 @@ +// fragment shader: set 0 binding 0 sampled image, binding 1 sampler, location 0 color output of its +// center #version 450 layout(set = 0, binding = 0) uniform texture2D tex; diff --git a/cvk/tests/shaders/triangle.frag b/cvk/tests/shaders/triangle.frag index 459e1b3e..f79a043e 100644 --- a/cvk/tests/shaders/triangle.frag +++ b/cvk/tests/shaders/triangle.frag @@ -1,3 +1,4 @@ +// fragment shader: push data `vec4` color, location 0 color output #version 450 layout(push_constant) uniform Push { diff --git a/cvk/tests/shaders/triangle.vert b/cvk/tests/shaders/triangle.vert index e4db99db..ddca3675 100644 --- a/cvk/tests/shaders/triangle.vert +++ b/cvk/tests/shaders/triangle.vert @@ -1,3 +1,4 @@ +// vertex shader: location 0 `vec3` position, push data offset 16 `mat4` view projection #version 450 layout(location = 0) in vec3 position; diff --git a/cvk/tests/shaders/values.comp b/cvk/tests/shaders/values.comp index 5d1892c3..104aadfa 100644 --- a/cvk/tests/shaders/values.comp +++ b/cvk/tests/shaders/values.comp @@ -1,3 +1,4 @@ +// compute shader: local size 64, push data address of `uint values[]`, value `i = 3 * i` #version 450 #extension GL_EXT_buffer_reference : require diff --git a/cvk/tests/src/data/descriptor/descriptor_draw_test.cpp b/cvk/tests/src/data/descriptor/descriptor_draw_test.cpp index e4ecdc4c..04fbb19c 100644 --- a/cvk/tests/src/data/descriptor/descriptor_draw_test.cpp +++ b/cvk/tests/src/data/descriptor/descriptor_draw_test.cpp @@ -1,5 +1,4 @@ #include "context.hpp" -#include "shaders.hpp" #include "test.hpp" #include "cvk/data/buffer/buffer.hpp" @@ -16,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -35,10 +35,10 @@ namespace { struct Fill { Fill( Core const& core, - std::span fragmentCode, + std::filesystem::path const& fragmentPath, std::vector mappings = {} - ) : vertex{core, VK_SHADER_STAGE_VERTEX_BIT, test::shaders::FILL_VERT}, - fragment{core, VK_SHADER_STAGE_FRAGMENT_BIT, fragmentCode}, + ) : vertex{core, VK_SHADER_STAGE_VERTEX_BIT, test::SHADER_DIR / "fill.vert.spv"}, + fragment{core, VK_SHADER_STAGE_FRAGMENT_BIT, fragmentPath}, pipeline{core, config(vertex, fragment, std::move(mappings)), create}, vertices{ core, @@ -139,7 +139,7 @@ namespace { CVK_TEST(DescriptorDraw, color_from_a_pushed_buffer_address) { test::Context const context{}; - Fill const fill{context.core, test::shaders::BUFFER_COLOR_FRAG}; + Fill const fill{context.core, test::SHADER_DIR / "buffer_color.frag.spv"}; Target const target{context.core}; Buffer> color{ @@ -189,8 +189,8 @@ namespace { Fill const fill{ context.core, afterRecording - ? std::span{test::shaders::BINDLESS_FRAG} - : std::span{test::shaders::TEXTURE_FRAG}, + ? test::SHADER_DIR / "bindless.frag.spv" + : test::SHADER_DIR / "texture.frag.spv", {resources.sampledImages().mapping(0, 0), samplers.samplers().mapping(0, 1)} }; Target const target{context.core}; diff --git a/cvk/tests/src/data/descriptor/descriptor_heap_test.cpp b/cvk/tests/src/data/descriptor/descriptor_heap_test.cpp index 360653ff..80647dc0 100644 --- a/cvk/tests/src/data/descriptor/descriptor_heap_test.cpp +++ b/cvk/tests/src/data/descriptor/descriptor_heap_test.cpp @@ -1,5 +1,4 @@ #include "context.hpp" -#include "shaders.hpp" #include "test.hpp" #include "cvk/base/physical_device.hpp" @@ -333,7 +332,7 @@ namespace { samplers{core, {.samplers = 3}, create}, texture{pixel(core, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)}, image{pixel(core, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT)}, - shader{core, VK_SHADER_STAGE_COMPUTE_BIT, test::shaders::HEAP_COMP}, + shader{core, VK_SHADER_STAGE_COMPUTE_BIT, test::SHADER_DIR / "heap.comp.spv"}, pipeline{ core, { diff --git a/cvk/tests/src/render/cmd/draw_test.cpp b/cvk/tests/src/render/cmd/draw_test.cpp index f2894809..bc43bb2b 100644 --- a/cvk/tests/src/render/cmd/draw_test.cpp +++ b/cvk/tests/src/render/cmd/draw_test.cpp @@ -1,5 +1,4 @@ #include "context.hpp" -#include "shaders.hpp" #include "test.hpp" #include "cvk/data/buffer/buffer.hpp" @@ -57,9 +56,9 @@ namespace { explicit Fill(Core const& core) : vertex{ core, VK_SHADER_STAGE_VERTEX_BIT, - test::shaders::FILL_VERT + test::SHADER_DIR / "fill.vert.spv" }, - fragment{core, VK_SHADER_STAGE_FRAGMENT_BIT, test::shaders::TRIANGLE_FRAG}, + fragment{core, VK_SHADER_STAGE_FRAGMENT_BIT, test::SHADER_DIR / "triangle.frag.spv"}, pipeline{core, test::fullscreen_config(vertex, fragment, COLOR_FORMATS), create}, vertices{ core, diff --git a/cvk/tests/src/render/cmd/local_read_test.cpp b/cvk/tests/src/render/cmd/local_read_test.cpp index 45063722..fc64c2d1 100644 --- a/cvk/tests/src/render/cmd/local_read_test.cpp +++ b/cvk/tests/src/render/cmd/local_read_test.cpp @@ -1,5 +1,4 @@ #include "context.hpp" -#include "shaders.hpp" #include "test.hpp" #include "cvk/data/buffer/buffer.hpp" @@ -151,9 +150,9 @@ namespace { */ struct Draws { Draws(Core const& core, Image const& first) : - vertex{core, VK_SHADER_STAGE_VERTEX_BIT, test::shaders::FILL_VERT}, - color{core, VK_SHADER_STAGE_FRAGMENT_BIT, test::shaders::TRIANGLE_FRAG}, - localRead{core, VK_SHADER_STAGE_FRAGMENT_BIT, test::shaders::LOCAL_READ_FRAG}, + vertex{core, VK_SHADER_STAGE_VERTEX_BIT, test::SHADER_DIR / "fill.vert.spv"}, + color{core, VK_SHADER_STAGE_FRAGMENT_BIT, test::SHADER_DIR / "triangle.frag.spv"}, + localRead{core, VK_SHADER_STAGE_FRAGMENT_BIT, test::SHADER_DIR / "local_read.frag.spv"}, heap{core, {.inputAttachments = 1}, create}, pushedHeap{core, {.inputAttachments = PUSHED_IDX + 1}, create}, write{core, fullscreen(vertex, color, write_first()), create}, diff --git a/cvk/tests/src/render/pipeline/compute_pipeline_test.cpp b/cvk/tests/src/render/pipeline/compute_pipeline_test.cpp index 311729cc..260008ff 100644 --- a/cvk/tests/src/render/pipeline/compute_pipeline_test.cpp +++ b/cvk/tests/src/render/pipeline/compute_pipeline_test.cpp @@ -1,5 +1,4 @@ #include "context.hpp" -#include "shaders.hpp" #include "test.hpp" #include "cvk/data/buffer/buffer.hpp" @@ -32,7 +31,7 @@ namespace { explicit Values(Core const& core) : shader{ core, VK_SHADER_STAGE_COMPUTE_BIT, - test::shaders::VALUES_COMP + test::SHADER_DIR / "values.comp.spv" } {} [[nodiscard]] ComputePipeline::Config config() const { diff --git a/cvk/tests/src/render/pipeline/graphics_pipeline_test.cpp b/cvk/tests/src/render/pipeline/graphics_pipeline_test.cpp index 05065121..55db09aa 100644 --- a/cvk/tests/src/render/pipeline/graphics_pipeline_test.cpp +++ b/cvk/tests/src/render/pipeline/graphics_pipeline_test.cpp @@ -1,5 +1,4 @@ #include "context.hpp" -#include "shaders.hpp" #include "test.hpp" #include "cvk/render/cmd/cmd_buffer.hpp" @@ -24,9 +23,9 @@ namespace { explicit Triangle(Core const& core) : vertex{ core, VK_SHADER_STAGE_VERTEX_BIT, - test::shaders::TRIANGLE_VERT + test::SHADER_DIR / "triangle.vert.spv" }, - fragment{core, VK_SHADER_STAGE_FRAGMENT_BIT, test::shaders::TRIANGLE_FRAG} {} + fragment{core, VK_SHADER_STAGE_FRAGMENT_BIT, test::SHADER_DIR / "triangle.frag.spv"} {} [[nodiscard]] GraphicsPipeline::Config config() const { GraphicsPipeline::Config config{ diff --git a/cvk/tests/src/render/pipeline/shader/shader_test.cpp b/cvk/tests/src/render/pipeline/shader/shader_test.cpp index 962c4217..e92050cb 100644 --- a/cvk/tests/src/render/pipeline/shader/shader_test.cpp +++ b/cvk/tests/src/render/pipeline/shader/shader_test.cpp @@ -1,5 +1,4 @@ #include "context.hpp" -#include "shaders.hpp" #include "test.hpp" #include "cvk/render/pipeline/shader/shader.hpp" @@ -9,13 +8,10 @@ #ifdef CTH_PLATFORM_WINDOWS #include -#define CVK_NULL_DEVICE "NUL" #else #include -#define CVK_NULL_DEVICE "/dev/null" #endif -#include #include #include #include @@ -24,15 +20,7 @@ namespace cvk { namespace { - using test::shaders::TRIANGLE_VERT; - - /** - * @return glslc runs, the check runs once per process - */ - bool glslc_available() { - static bool const available = std::system("glslc --version >" CVK_NULL_DEVICE " 2>&1") == 0; - return available; - } + std::filesystem::path const TRIANGLE_VERT = test::SHADER_DIR / "triangle.vert.spv"; auto process_id() { #ifdef CTH_PLATFORM_WINDOWS @@ -83,8 +71,9 @@ CVK_TEST(Shader, base_constructor_does_not_create) { CVK_TEST(Shader, create_from_spv) { test::Context const context{}; + auto const spv = Shader::load(TRIANGLE_VERT); - Shader const shader{context.core, VK_SHADER_STAGE_VERTEX_BIT, TRIANGLE_VERT}; + Shader const shader{context.core, VK_SHADER_STAGE_VERTEX_BIT, spv}; ASSERT_TRUE(shader.created()); @@ -98,18 +87,20 @@ CVK_TEST(Shader, create_from_spv) { CVK_TEST(Shader, create_from_file) { test::Context const context{}; - std::span const bytes{ - reinterpret_cast(TRIANGLE_VERT.data()), - sizeof(TRIANGLE_VERT) - }; - auto const path = write_temp("cvk_test_triangle.vert.spv", bytes); - Shader const shader{context.core, VK_SHADER_STAGE_VERTEX_BIT, path}; + Shader const shader{context.core, VK_SHADER_STAGE_VERTEX_BIT, TRIANGLE_VERT}; EXPECT_TRUE(shader.created()); - EXPECT_TRUE(std::ranges::equal(Shader::load(path), TRIANGLE_VERT)); +} + +CVK_TEST(Shader, load_reads_the_words) { + constexpr uint32_t SPIRV_MAGIC = 0x07230203; - std::filesystem::remove(path); + auto const spv = Shader::load(TRIANGLE_VERT); + + EXPECT_EQ(spv.size() * sizeof(uint32_t), std::filesystem::file_size(TRIANGLE_VERT)); + ASSERT_FALSE(spv.empty()); + EXPECT_EQ(spv.front(), SPIRV_MAGIC); } CVK_TEST(Shader, load_rejects_bad_files) { @@ -141,7 +132,11 @@ CVK_TEST(Shader, release_and_wrap) { CVK_TEST(Shader, move_assignment_destroys_the_old_shader) { test::Context const context{}; Shader shader{context.core, VK_SHADER_STAGE_VERTEX_BIT, TRIANGLE_VERT}; - Shader other{context.core, VK_SHADER_STAGE_FRAGMENT_BIT, test::shaders::TRIANGLE_FRAG}; + Shader other{ + context.core, + VK_SHADER_STAGE_FRAGMENT_BIT, + test::SHADER_DIR / "triangle.frag.spv" + }; auto const vkShader = other.get(); shader = std::move(other); @@ -151,45 +146,6 @@ CVK_TEST(Shader, move_assignment_destroys_the_old_shader) { EXPECT_FALSE(other.created()); } -CVK_TEST(Shader, compile_and_create) { - if(!glslc_available()) - GTEST_SKIP() << "glslc not found"; - test::Context const context{}; - auto const spvPath = temp_dir() / "cvk_test_compiled.vert.spv"; - - Shader const shader{ - context.core, - VK_SHADER_STAGE_VERTEX_BIT, - spvPath, - test::SHADER_DIR / "triangle.vert" - }; - - EXPECT_TRUE(shader.created()); - EXPECT_TRUE(std::filesystem::exists(spvPath)); - EXPECT_FALSE(std::filesystem::exists(spvPath.string() + ".log")); - - std::filesystem::remove(spvPath); -} - -CVK_TEST(Shader, compile_error_throws) { - if(!glslc_available()) - GTEST_SKIP() << "glslc not found"; - constexpr std::string_view broken = "#version 450\nvoid main() { undeclared = 1; }\n"; - auto const glslPath = write_temp("cvk_test_broken.vert", broken); - auto const spvPath = temp_dir() / "cvk_test_broken.vert.spv"; - - EXPECT_THROW(Shader::compile(glslPath, spvPath), cvk_exception); - EXPECT_FALSE(std::filesystem::exists(spvPath.string() + ".log")); - - std::filesystem::remove(glslPath); -} - -CVK_TEST(Shader, compile_missing_glsl_throws) { - auto const missing = temp_dir() / "cvk_test_missing.vert"; - - EXPECT_THROW(Shader::compile(missing, missing.string() + ".spv"), cvk_exception); -} - CVK_TEST(Shader, decompose_returns_the_released_handle) { // a leak shows up when the shared device is destroyed test::Context const context{}; diff --git a/cvk/tests/src/shaders.hpp b/cvk/tests/src/shaders.hpp deleted file mode 100644 index 781abb32..00000000 --- a/cvk/tests/src/shaders.hpp +++ /dev/null @@ -1,1622 +0,0 @@ -#pragma once -#include -#include - -/** - * generated from cvk/tests/shaders, regenerate with: - * `glslc --target-env=vulkan1.3 -O -mfmt=num -o .num ` - */ -namespace cvk::test::shaders { -/** - * vertex shader: location 0 `vec3` position, push data offset 16 `mat4` view projection - */ -inline constexpr std::array TRIANGLE_VERT{ - 0x07230203, - 0x00010600, - 0x000d000b, - 0x00000023, - 0x00000000, - 0x00020011, - 0x00000001, - 0x0006000b, - 0x00000001, - 0x4c534c47, - 0x6474732e, - 0x3035342e, - 0x00000000, - 0x0003000e, - 0x00000000, - 0x00000001, - 0x0008000f, - 0x00000000, - 0x00000004, - 0x6e69616d, - 0x00000000, - 0x0000000d, - 0x00000013, - 0x00000019, - 0x00030047, - 0x0000000b, - 0x00000002, - 0x00050048, - 0x0000000b, - 0x00000000, - 0x0000000b, - 0x00000000, - 0x00050048, - 0x0000000b, - 0x00000001, - 0x0000000b, - 0x00000001, - 0x00050048, - 0x0000000b, - 0x00000002, - 0x0000000b, - 0x00000003, - 0x00050048, - 0x0000000b, - 0x00000003, - 0x0000000b, - 0x00000004, - 0x00030047, - 0x00000011, - 0x00000002, - 0x00040048, - 0x00000011, - 0x00000000, - 0x00000005, - 0x00050048, - 0x00000011, - 0x00000000, - 0x00000007, - 0x00000010, - 0x00050048, - 0x00000011, - 0x00000000, - 0x00000023, - 0x00000010, - 0x00040047, - 0x00000019, - 0x0000001e, - 0x00000000, - 0x00020013, - 0x00000002, - 0x00030021, - 0x00000003, - 0x00000002, - 0x00030016, - 0x00000006, - 0x00000020, - 0x00040017, - 0x00000007, - 0x00000006, - 0x00000004, - 0x00040015, - 0x00000008, - 0x00000020, - 0x00000000, - 0x0004002b, - 0x00000008, - 0x00000009, - 0x00000001, - 0x0004001c, - 0x0000000a, - 0x00000006, - 0x00000009, - 0x0006001e, - 0x0000000b, - 0x00000007, - 0x00000006, - 0x0000000a, - 0x0000000a, - 0x00040020, - 0x0000000c, - 0x00000003, - 0x0000000b, - 0x0004003b, - 0x0000000c, - 0x0000000d, - 0x00000003, - 0x00040015, - 0x0000000e, - 0x00000020, - 0x00000001, - 0x0004002b, - 0x0000000e, - 0x0000000f, - 0x00000000, - 0x00040018, - 0x00000010, - 0x00000007, - 0x00000004, - 0x0003001e, - 0x00000011, - 0x00000010, - 0x00040020, - 0x00000012, - 0x00000009, - 0x00000011, - 0x0004003b, - 0x00000012, - 0x00000013, - 0x00000009, - 0x00040020, - 0x00000014, - 0x00000009, - 0x00000010, - 0x00040017, - 0x00000017, - 0x00000006, - 0x00000003, - 0x00040020, - 0x00000018, - 0x00000001, - 0x00000017, - 0x0004003b, - 0x00000018, - 0x00000019, - 0x00000001, - 0x0004002b, - 0x00000006, - 0x0000001b, - 0x3f800000, - 0x00040020, - 0x00000021, - 0x00000003, - 0x00000007, - 0x00050036, - 0x00000002, - 0x00000004, - 0x00000000, - 0x00000003, - 0x000200f8, - 0x00000005, - 0x00050041, - 0x00000014, - 0x00000015, - 0x00000013, - 0x0000000f, - 0x0004003d, - 0x00000010, - 0x00000016, - 0x00000015, - 0x0004003d, - 0x00000017, - 0x0000001a, - 0x00000019, - 0x00050051, - 0x00000006, - 0x0000001c, - 0x0000001a, - 0x00000000, - 0x00050051, - 0x00000006, - 0x0000001d, - 0x0000001a, - 0x00000001, - 0x00050051, - 0x00000006, - 0x0000001e, - 0x0000001a, - 0x00000002, - 0x00070050, - 0x00000007, - 0x0000001f, - 0x0000001c, - 0x0000001d, - 0x0000001e, - 0x0000001b, - 0x00050091, - 0x00000007, - 0x00000020, - 0x00000016, - 0x0000001f, - 0x00050041, - 0x00000021, - 0x00000022, - 0x0000000d, - 0x0000000f, - 0x0003003e, - 0x00000022, - 0x00000020, - 0x000100fd, - 0x00010038, -}; - -/** - * fragment shader: push data `vec4` color, location 0 color output - */ -inline constexpr std::array TRIANGLE_FRAG{ - 0x07230203, - 0x00010600, - 0x000d000b, - 0x00000012, - 0x00000000, - 0x00020011, - 0x00000001, - 0x0006000b, - 0x00000001, - 0x4c534c47, - 0x6474732e, - 0x3035342e, - 0x00000000, - 0x0003000e, - 0x00000000, - 0x00000001, - 0x0007000f, - 0x00000004, - 0x00000004, - 0x6e69616d, - 0x00000000, - 0x00000009, - 0x0000000c, - 0x00030010, - 0x00000004, - 0x00000007, - 0x00040047, - 0x00000009, - 0x0000001e, - 0x00000000, - 0x00030047, - 0x0000000a, - 0x00000002, - 0x00050048, - 0x0000000a, - 0x00000000, - 0x00000023, - 0x00000000, - 0x00020013, - 0x00000002, - 0x00030021, - 0x00000003, - 0x00000002, - 0x00030016, - 0x00000006, - 0x00000020, - 0x00040017, - 0x00000007, - 0x00000006, - 0x00000004, - 0x00040020, - 0x00000008, - 0x00000003, - 0x00000007, - 0x0004003b, - 0x00000008, - 0x00000009, - 0x00000003, - 0x0003001e, - 0x0000000a, - 0x00000007, - 0x00040020, - 0x0000000b, - 0x00000009, - 0x0000000a, - 0x0004003b, - 0x0000000b, - 0x0000000c, - 0x00000009, - 0x00040015, - 0x0000000d, - 0x00000020, - 0x00000001, - 0x0004002b, - 0x0000000d, - 0x0000000e, - 0x00000000, - 0x00040020, - 0x0000000f, - 0x00000009, - 0x00000007, - 0x00050036, - 0x00000002, - 0x00000004, - 0x00000000, - 0x00000003, - 0x000200f8, - 0x00000005, - 0x00050041, - 0x0000000f, - 0x00000010, - 0x0000000c, - 0x0000000e, - 0x0004003d, - 0x00000007, - 0x00000011, - 0x00000010, - 0x0003003e, - 0x00000009, - 0x00000011, - 0x000100fd, - 0x00010038, -}; - -/** - * vertex shader: location 0 `vec3` position, no descriptors - */ -inline constexpr std::array FILL_VERT{ - 0x07230203, - 0x00010600, - 0x000d000b, - 0x0000001b, - 0x00000000, - 0x00020011, - 0x00000001, - 0x0006000b, - 0x00000001, - 0x4c534c47, - 0x6474732e, - 0x3035342e, - 0x00000000, - 0x0003000e, - 0x00000000, - 0x00000001, - 0x0007000f, - 0x00000000, - 0x00000004, - 0x6e69616d, - 0x00000000, - 0x0000000d, - 0x00000012, - 0x00030047, - 0x0000000b, - 0x00000002, - 0x00050048, - 0x0000000b, - 0x00000000, - 0x0000000b, - 0x00000000, - 0x00050048, - 0x0000000b, - 0x00000001, - 0x0000000b, - 0x00000001, - 0x00050048, - 0x0000000b, - 0x00000002, - 0x0000000b, - 0x00000003, - 0x00050048, - 0x0000000b, - 0x00000003, - 0x0000000b, - 0x00000004, - 0x00040047, - 0x00000012, - 0x0000001e, - 0x00000000, - 0x00020013, - 0x00000002, - 0x00030021, - 0x00000003, - 0x00000002, - 0x00030016, - 0x00000006, - 0x00000020, - 0x00040017, - 0x00000007, - 0x00000006, - 0x00000004, - 0x00040015, - 0x00000008, - 0x00000020, - 0x00000000, - 0x0004002b, - 0x00000008, - 0x00000009, - 0x00000001, - 0x0004001c, - 0x0000000a, - 0x00000006, - 0x00000009, - 0x0006001e, - 0x0000000b, - 0x00000007, - 0x00000006, - 0x0000000a, - 0x0000000a, - 0x00040020, - 0x0000000c, - 0x00000003, - 0x0000000b, - 0x0004003b, - 0x0000000c, - 0x0000000d, - 0x00000003, - 0x00040015, - 0x0000000e, - 0x00000020, - 0x00000001, - 0x0004002b, - 0x0000000e, - 0x0000000f, - 0x00000000, - 0x00040017, - 0x00000010, - 0x00000006, - 0x00000003, - 0x00040020, - 0x00000011, - 0x00000001, - 0x00000010, - 0x0004003b, - 0x00000011, - 0x00000012, - 0x00000001, - 0x0004002b, - 0x00000006, - 0x00000014, - 0x3f800000, - 0x00040020, - 0x00000019, - 0x00000003, - 0x00000007, - 0x00050036, - 0x00000002, - 0x00000004, - 0x00000000, - 0x00000003, - 0x000200f8, - 0x00000005, - 0x0004003d, - 0x00000010, - 0x00000013, - 0x00000012, - 0x00050051, - 0x00000006, - 0x00000015, - 0x00000013, - 0x00000000, - 0x00050051, - 0x00000006, - 0x00000016, - 0x00000013, - 0x00000001, - 0x00050051, - 0x00000006, - 0x00000017, - 0x00000013, - 0x00000002, - 0x00070050, - 0x00000007, - 0x00000018, - 0x00000015, - 0x00000016, - 0x00000017, - 0x00000014, - 0x00050041, - 0x00000019, - 0x0000001a, - 0x0000000d, - 0x0000000f, - 0x0003003e, - 0x0000001a, - 0x00000018, - 0x000100fd, - 0x00010038, -}; - -/** - * fragment shader: push data address of a `vec4` color, location 0 color output - */ -inline constexpr std::array BUFFER_COLOR_FRAG{ - 0x07230203, - 0x00010600, - 0x000d000b, - 0x00000017, - 0x00000000, - 0x00020011, - 0x00000001, - 0x00020011, - 0x000014e3, - 0x0006000b, - 0x00000001, - 0x4c534c47, - 0x6474732e, - 0x3035342e, - 0x00000000, - 0x0003000e, - 0x000014e4, - 0x00000001, - 0x0007000f, - 0x00000004, - 0x00000004, - 0x6e69616d, - 0x00000000, - 0x00000009, - 0x0000000e, - 0x00030010, - 0x00000004, - 0x00000007, - 0x00040047, - 0x00000009, - 0x0000001e, - 0x00000000, - 0x00030047, - 0x0000000b, - 0x00000002, - 0x00050048, - 0x0000000b, - 0x00000000, - 0x00000023, - 0x00000000, - 0x00030047, - 0x0000000c, - 0x00000002, - 0x00040048, - 0x0000000c, - 0x00000000, - 0x00000018, - 0x00050048, - 0x0000000c, - 0x00000000, - 0x00000023, - 0x00000000, - 0x00020013, - 0x00000002, - 0x00030021, - 0x00000003, - 0x00000002, - 0x00030016, - 0x00000006, - 0x00000020, - 0x00040017, - 0x00000007, - 0x00000006, - 0x00000004, - 0x00040020, - 0x00000008, - 0x00000003, - 0x00000007, - 0x0004003b, - 0x00000008, - 0x00000009, - 0x00000003, - 0x00030027, - 0x0000000a, - 0x000014e5, - 0x0003001e, - 0x0000000b, - 0x0000000a, - 0x0003001e, - 0x0000000c, - 0x00000007, - 0x00040020, - 0x0000000a, - 0x000014e5, - 0x0000000c, - 0x00040020, - 0x0000000d, - 0x00000009, - 0x0000000b, - 0x0004003b, - 0x0000000d, - 0x0000000e, - 0x00000009, - 0x00040015, - 0x0000000f, - 0x00000020, - 0x00000001, - 0x0004002b, - 0x0000000f, - 0x00000010, - 0x00000000, - 0x00040020, - 0x00000011, - 0x00000009, - 0x0000000a, - 0x00040020, - 0x00000014, - 0x000014e5, - 0x00000007, - 0x00050036, - 0x00000002, - 0x00000004, - 0x00000000, - 0x00000003, - 0x000200f8, - 0x00000005, - 0x00050041, - 0x00000011, - 0x00000012, - 0x0000000e, - 0x00000010, - 0x0004003d, - 0x0000000a, - 0x00000013, - 0x00000012, - 0x00050041, - 0x00000014, - 0x00000015, - 0x00000013, - 0x00000010, - 0x0006003d, - 0x00000007, - 0x00000016, - 0x00000015, - 0x00000002, - 0x00000010, - 0x0003003e, - 0x00000009, - 0x00000016, - 0x000100fd, - 0x00010038, -}; - -/** - * fragment shader: set 0 binding 0 runtime array of sampled images, binding 1 sampler, push data `uint` index - */ -inline constexpr std::array BINDLESS_FRAG{ - 0x07230203, - 0x00010600, - 0x000d000b, - 0x00000025, - 0x00000000, - 0x00020011, - 0x00000001, - 0x00020011, - 0x000014b5, - 0x00020011, - 0x000014b6, - 0x00020011, - 0x000014bb, - 0x0006000b, - 0x00000001, - 0x4c534c47, - 0x6474732e, - 0x3035342e, - 0x00000000, - 0x0003000e, - 0x00000000, - 0x00000001, - 0x0009000f, - 0x00000004, - 0x00000004, - 0x6e69616d, - 0x00000000, - 0x00000009, - 0x0000000d, - 0x00000011, - 0x0000001d, - 0x00030010, - 0x00000004, - 0x00000007, - 0x00040047, - 0x00000009, - 0x0000001e, - 0x00000000, - 0x00040047, - 0x0000000d, - 0x00000021, - 0x00000000, - 0x00040047, - 0x0000000d, - 0x00000022, - 0x00000000, - 0x00030047, - 0x0000000f, - 0x00000002, - 0x00050048, - 0x0000000f, - 0x00000000, - 0x00000023, - 0x00000000, - 0x00030047, - 0x00000017, - 0x000014b4, - 0x00030047, - 0x00000019, - 0x000014b4, - 0x00030047, - 0x0000001a, - 0x000014b4, - 0x00040047, - 0x0000001d, - 0x00000021, - 0x00000001, - 0x00040047, - 0x0000001d, - 0x00000022, - 0x00000000, - 0x00020013, - 0x00000002, - 0x00030021, - 0x00000003, - 0x00000002, - 0x00030016, - 0x00000006, - 0x00000020, - 0x00040017, - 0x00000007, - 0x00000006, - 0x00000004, - 0x00040020, - 0x00000008, - 0x00000003, - 0x00000007, - 0x0004003b, - 0x00000008, - 0x00000009, - 0x00000003, - 0x00090019, - 0x0000000a, - 0x00000006, - 0x00000001, - 0x00000000, - 0x00000000, - 0x00000000, - 0x00000001, - 0x00000000, - 0x0003001d, - 0x0000000b, - 0x0000000a, - 0x00040020, - 0x0000000c, - 0x00000000, - 0x0000000b, - 0x0004003b, - 0x0000000c, - 0x0000000d, - 0x00000000, - 0x00040015, - 0x0000000e, - 0x00000020, - 0x00000000, - 0x0003001e, - 0x0000000f, - 0x0000000e, - 0x00040020, - 0x00000010, - 0x00000009, - 0x0000000f, - 0x0004003b, - 0x00000010, - 0x00000011, - 0x00000009, - 0x00040015, - 0x00000012, - 0x00000020, - 0x00000001, - 0x0004002b, - 0x00000012, - 0x00000013, - 0x00000000, - 0x00040020, - 0x00000014, - 0x00000009, - 0x0000000e, - 0x00040020, - 0x00000018, - 0x00000000, - 0x0000000a, - 0x0002001a, - 0x0000001b, - 0x00040020, - 0x0000001c, - 0x00000000, - 0x0000001b, - 0x0004003b, - 0x0000001c, - 0x0000001d, - 0x00000000, - 0x0003001b, - 0x0000001f, - 0x0000000a, - 0x00040017, - 0x00000021, - 0x00000006, - 0x00000002, - 0x0004002b, - 0x00000006, - 0x00000022, - 0x3f000000, - 0x0005002c, - 0x00000021, - 0x00000023, - 0x00000022, - 0x00000022, - 0x00050036, - 0x00000002, - 0x00000004, - 0x00000000, - 0x00000003, - 0x000200f8, - 0x00000005, - 0x00050041, - 0x00000014, - 0x00000015, - 0x00000011, - 0x00000013, - 0x0004003d, - 0x0000000e, - 0x00000016, - 0x00000015, - 0x00040053, - 0x0000000e, - 0x00000017, - 0x00000016, - 0x00050041, - 0x00000018, - 0x00000019, - 0x0000000d, - 0x00000017, - 0x0004003d, - 0x0000000a, - 0x0000001a, - 0x00000019, - 0x0004003d, - 0x0000001b, - 0x0000001e, - 0x0000001d, - 0x00050056, - 0x0000001f, - 0x00000020, - 0x0000001a, - 0x0000001e, - 0x00050057, - 0x00000007, - 0x00000024, - 0x00000020, - 0x00000023, - 0x0003003e, - 0x00000009, - 0x00000024, - 0x000100fd, - 0x00010038, -}; - -/** - * fragment shader: set 0 binding 0 input attachment index 0, location 0 color output of its value - */ -inline constexpr std::array LOCAL_READ_FRAG{ - 0x07230203, - 0x00010600, - 0x000d000b, - 0x00000013, - 0x00000000, - 0x00020011, - 0x00000001, - 0x00020011, - 0x00000028, - 0x0006000b, - 0x00000001, - 0x4c534c47, - 0x6474732e, - 0x3035342e, - 0x00000000, - 0x0003000e, - 0x00000000, - 0x00000001, - 0x0007000f, - 0x00000004, - 0x00000004, - 0x6e69616d, - 0x00000000, - 0x00000009, - 0x0000000c, - 0x00030010, - 0x00000004, - 0x00000007, - 0x00040047, - 0x00000009, - 0x0000001e, - 0x00000000, - 0x00040047, - 0x0000000c, - 0x00000021, - 0x00000000, - 0x00040047, - 0x0000000c, - 0x00000022, - 0x00000000, - 0x00040047, - 0x0000000c, - 0x0000002b, - 0x00000000, - 0x00020013, - 0x00000002, - 0x00030021, - 0x00000003, - 0x00000002, - 0x00030016, - 0x00000006, - 0x00000020, - 0x00040017, - 0x00000007, - 0x00000006, - 0x00000004, - 0x00040020, - 0x00000008, - 0x00000003, - 0x00000007, - 0x0004003b, - 0x00000008, - 0x00000009, - 0x00000003, - 0x00090019, - 0x0000000a, - 0x00000006, - 0x00000006, - 0x00000000, - 0x00000000, - 0x00000000, - 0x00000002, - 0x00000000, - 0x00040020, - 0x0000000b, - 0x00000000, - 0x0000000a, - 0x0004003b, - 0x0000000b, - 0x0000000c, - 0x00000000, - 0x00040015, - 0x0000000e, - 0x00000020, - 0x00000001, - 0x0004002b, - 0x0000000e, - 0x0000000f, - 0x00000000, - 0x00040017, - 0x00000010, - 0x0000000e, - 0x00000002, - 0x0005002c, - 0x00000010, - 0x00000011, - 0x0000000f, - 0x0000000f, - 0x00050036, - 0x00000002, - 0x00000004, - 0x00000000, - 0x00000003, - 0x000200f8, - 0x00000005, - 0x0004003d, - 0x0000000a, - 0x0000000d, - 0x0000000c, - 0x00050062, - 0x00000007, - 0x00000012, - 0x0000000d, - 0x00000011, - 0x0003003e, - 0x00000009, - 0x00000012, - 0x000100fd, - 0x00010038, -}; - -/** - * fragment shader: set 0 binding 0 sampled image, binding 1 sampler, location 0 color output of its center - */ -inline constexpr std::array TEXTURE_FRAG{ - 0x07230203, - 0x00010600, - 0x000d000b, - 0x00000018, - 0x00000000, - 0x00020011, - 0x00000001, - 0x0006000b, - 0x00000001, - 0x4c534c47, - 0x6474732e, - 0x3035342e, - 0x00000000, - 0x0003000e, - 0x00000000, - 0x00000001, - 0x0008000f, - 0x00000004, - 0x00000004, - 0x6e69616d, - 0x00000000, - 0x00000009, - 0x0000000c, - 0x00000010, - 0x00030010, - 0x00000004, - 0x00000007, - 0x00040047, - 0x00000009, - 0x0000001e, - 0x00000000, - 0x00040047, - 0x0000000c, - 0x00000021, - 0x00000000, - 0x00040047, - 0x0000000c, - 0x00000022, - 0x00000000, - 0x00040047, - 0x00000010, - 0x00000021, - 0x00000001, - 0x00040047, - 0x00000010, - 0x00000022, - 0x00000000, - 0x00020013, - 0x00000002, - 0x00030021, - 0x00000003, - 0x00000002, - 0x00030016, - 0x00000006, - 0x00000020, - 0x00040017, - 0x00000007, - 0x00000006, - 0x00000004, - 0x00040020, - 0x00000008, - 0x00000003, - 0x00000007, - 0x0004003b, - 0x00000008, - 0x00000009, - 0x00000003, - 0x00090019, - 0x0000000a, - 0x00000006, - 0x00000001, - 0x00000000, - 0x00000000, - 0x00000000, - 0x00000001, - 0x00000000, - 0x00040020, - 0x0000000b, - 0x00000000, - 0x0000000a, - 0x0004003b, - 0x0000000b, - 0x0000000c, - 0x00000000, - 0x0002001a, - 0x0000000e, - 0x00040020, - 0x0000000f, - 0x00000000, - 0x0000000e, - 0x0004003b, - 0x0000000f, - 0x00000010, - 0x00000000, - 0x0003001b, - 0x00000012, - 0x0000000a, - 0x00040017, - 0x00000014, - 0x00000006, - 0x00000002, - 0x0004002b, - 0x00000006, - 0x00000015, - 0x3f000000, - 0x0005002c, - 0x00000014, - 0x00000016, - 0x00000015, - 0x00000015, - 0x00050036, - 0x00000002, - 0x00000004, - 0x00000000, - 0x00000003, - 0x000200f8, - 0x00000005, - 0x0004003d, - 0x0000000a, - 0x0000000d, - 0x0000000c, - 0x0004003d, - 0x0000000e, - 0x00000011, - 0x00000010, - 0x00050056, - 0x00000012, - 0x00000013, - 0x0000000d, - 0x00000011, - 0x00050057, - 0x00000007, - 0x00000017, - 0x00000013, - 0x00000016, - 0x0003003e, - 0x00000009, - 0x00000017, - 0x000100fd, - 0x00010038, -}; - -/** - * compute shader: local size 64, push data address of `uint values[]`, value `i = 3 * i` - */ -inline constexpr std::array VALUES_COMP{ - 0x07230203, - 0x00010600, - 0x000d000b, - 0x0000001f, - 0x00000000, - 0x00020011, - 0x00000001, - 0x00020011, - 0x000014e3, - 0x0006000b, - 0x00000001, - 0x4c534c47, - 0x6474732e, - 0x3035342e, - 0x00000000, - 0x0003000e, - 0x000014e4, - 0x00000001, - 0x0007000f, - 0x00000005, - 0x00000004, - 0x6e69616d, - 0x00000000, - 0x0000000c, - 0x00000014, - 0x00060010, - 0x00000004, - 0x00000011, - 0x00000040, - 0x00000001, - 0x00000001, - 0x00030047, - 0x00000007, - 0x00000002, - 0x00050048, - 0x00000007, - 0x00000000, - 0x00000023, - 0x00000000, - 0x00040047, - 0x00000009, - 0x00000006, - 0x00000004, - 0x00030047, - 0x0000000a, - 0x00000002, - 0x00050048, - 0x0000000a, - 0x00000000, - 0x00000023, - 0x00000000, - 0x00040047, - 0x00000014, - 0x0000000b, - 0x0000001c, - 0x00020013, - 0x00000002, - 0x00030021, - 0x00000003, - 0x00000002, - 0x00030027, - 0x00000006, - 0x000014e5, - 0x0003001e, - 0x00000007, - 0x00000006, - 0x00040015, - 0x00000008, - 0x00000020, - 0x00000000, - 0x0003001d, - 0x00000009, - 0x00000008, - 0x0003001e, - 0x0000000a, - 0x00000009, - 0x00040020, - 0x00000006, - 0x000014e5, - 0x0000000a, - 0x00040020, - 0x0000000b, - 0x00000009, - 0x00000007, - 0x0004003b, - 0x0000000b, - 0x0000000c, - 0x00000009, - 0x00040015, - 0x0000000d, - 0x00000020, - 0x00000001, - 0x0004002b, - 0x0000000d, - 0x0000000e, - 0x00000000, - 0x00040020, - 0x0000000f, - 0x00000009, - 0x00000006, - 0x00040017, - 0x00000012, - 0x00000008, - 0x00000003, - 0x00040020, - 0x00000013, - 0x00000001, - 0x00000012, - 0x0004003b, - 0x00000013, - 0x00000014, - 0x00000001, - 0x0004002b, - 0x00000008, - 0x00000015, - 0x00000000, - 0x00040020, - 0x00000016, - 0x00000001, - 0x00000008, - 0x0004002b, - 0x00000008, - 0x0000001b, - 0x00000003, - 0x00040020, - 0x0000001d, - 0x000014e5, - 0x00000008, - 0x00050036, - 0x00000002, - 0x00000004, - 0x00000000, - 0x00000003, - 0x000200f8, - 0x00000005, - 0x00050041, - 0x0000000f, - 0x00000010, - 0x0000000c, - 0x0000000e, - 0x0004003d, - 0x00000006, - 0x00000011, - 0x00000010, - 0x00050041, - 0x00000016, - 0x00000017, - 0x00000014, - 0x00000015, - 0x0004003d, - 0x00000008, - 0x00000018, - 0x00000017, - 0x00050084, - 0x00000008, - 0x0000001c, - 0x00000018, - 0x0000001b, - 0x00060041, - 0x0000001d, - 0x0000001e, - 0x00000011, - 0x0000000e, - 0x00000018, - 0x0005003e, - 0x0000001e, - 0x0000001c, - 0x00000002, - 0x00000004, - 0x000100fd, - 0x00010038, -}; - -/** - * compute shader: set 0 binding 0 sampled images, binding 1 samplers, binding 2 storage images, - * push data `uint` indices: stores the center of the sampled image at texel 0 of the storage image - */ -inline constexpr std::array HEAP_COMP{ - 0x07230203, - 0x00010600, - 0x000d000b, - 0x00000037, - 0x00000000, - 0x00020011, - 0x00000001, - 0x00020011, - 0x000014b6, - 0x0006000b, - 0x00000001, - 0x4c534c47, - 0x6474732e, - 0x3035342e, - 0x00000000, - 0x0003000e, - 0x00000000, - 0x00000001, - 0x0009000f, - 0x00000005, - 0x00000004, - 0x6e69616d, - 0x00000000, - 0x0000000d, - 0x00000011, - 0x0000001d, - 0x0000002e, - 0x00060010, - 0x00000004, - 0x00000011, - 0x00000001, - 0x00000001, - 0x00000001, - 0x00040047, - 0x0000000d, - 0x00000021, - 0x00000000, - 0x00040047, - 0x0000000d, - 0x00000022, - 0x00000000, - 0x00030047, - 0x0000000f, - 0x00000002, - 0x00050048, - 0x0000000f, - 0x00000000, - 0x00000023, - 0x00000000, - 0x00050048, - 0x0000000f, - 0x00000001, - 0x00000023, - 0x00000004, - 0x00050048, - 0x0000000f, - 0x00000002, - 0x00000023, - 0x00000008, - 0x00040047, - 0x0000001d, - 0x00000021, - 0x00000001, - 0x00040047, - 0x0000001d, - 0x00000022, - 0x00000000, - 0x00030047, - 0x0000002e, - 0x00000019, - 0x00040047, - 0x0000002e, - 0x00000021, - 0x00000002, - 0x00040047, - 0x0000002e, - 0x00000022, - 0x00000000, - 0x00020013, - 0x00000002, - 0x00030021, - 0x00000003, - 0x00000002, - 0x00030016, - 0x00000006, - 0x00000020, - 0x00040017, - 0x00000007, - 0x00000006, - 0x00000004, - 0x00090019, - 0x0000000a, - 0x00000006, - 0x00000001, - 0x00000000, - 0x00000000, - 0x00000000, - 0x00000001, - 0x00000000, - 0x0003001d, - 0x0000000b, - 0x0000000a, - 0x00040020, - 0x0000000c, - 0x00000000, - 0x0000000b, - 0x0004003b, - 0x0000000c, - 0x0000000d, - 0x00000000, - 0x00040015, - 0x0000000e, - 0x00000020, - 0x00000000, - 0x0005001e, - 0x0000000f, - 0x0000000e, - 0x0000000e, - 0x0000000e, - 0x00040020, - 0x00000010, - 0x00000009, - 0x0000000f, - 0x0004003b, - 0x00000010, - 0x00000011, - 0x00000009, - 0x00040015, - 0x00000012, - 0x00000020, - 0x00000001, - 0x0004002b, - 0x00000012, - 0x00000013, - 0x00000000, - 0x00040020, - 0x00000014, - 0x00000009, - 0x0000000e, - 0x00040020, - 0x00000017, - 0x00000000, - 0x0000000a, - 0x0002001a, - 0x0000001a, - 0x0003001d, - 0x0000001b, - 0x0000001a, - 0x00040020, - 0x0000001c, - 0x00000000, - 0x0000001b, - 0x0004003b, - 0x0000001c, - 0x0000001d, - 0x00000000, - 0x0004002b, - 0x00000012, - 0x0000001e, - 0x00000001, - 0x00040020, - 0x00000021, - 0x00000000, - 0x0000001a, - 0x0003001b, - 0x00000024, - 0x0000000a, - 0x00040017, - 0x00000026, - 0x00000006, - 0x00000002, - 0x0004002b, - 0x00000006, - 0x00000027, - 0x3f000000, - 0x0005002c, - 0x00000026, - 0x00000028, - 0x00000027, - 0x00000027, - 0x0004002b, - 0x00000006, - 0x00000029, - 0x00000000, - 0x00090019, - 0x0000002b, - 0x00000006, - 0x00000001, - 0x00000000, - 0x00000000, - 0x00000000, - 0x00000002, - 0x00000004, - 0x0003001d, - 0x0000002c, - 0x0000002b, - 0x00040020, - 0x0000002d, - 0x00000000, - 0x0000002c, - 0x0004003b, - 0x0000002d, - 0x0000002e, - 0x00000000, - 0x0004002b, - 0x00000012, - 0x0000002f, - 0x00000002, - 0x00040020, - 0x00000032, - 0x00000000, - 0x0000002b, - 0x00040017, - 0x00000035, - 0x00000012, - 0x00000002, - 0x0005002c, - 0x00000035, - 0x00000036, - 0x00000013, - 0x00000013, - 0x00050036, - 0x00000002, - 0x00000004, - 0x00000000, - 0x00000003, - 0x000200f8, - 0x00000005, - 0x00050041, - 0x00000014, - 0x00000015, - 0x00000011, - 0x00000013, - 0x0004003d, - 0x0000000e, - 0x00000016, - 0x00000015, - 0x00050041, - 0x00000017, - 0x00000018, - 0x0000000d, - 0x00000016, - 0x0004003d, - 0x0000000a, - 0x00000019, - 0x00000018, - 0x00050041, - 0x00000014, - 0x0000001f, - 0x00000011, - 0x0000001e, - 0x0004003d, - 0x0000000e, - 0x00000020, - 0x0000001f, - 0x00050041, - 0x00000021, - 0x00000022, - 0x0000001d, - 0x00000020, - 0x0004003d, - 0x0000001a, - 0x00000023, - 0x00000022, - 0x00050056, - 0x00000024, - 0x00000025, - 0x00000019, - 0x00000023, - 0x00070058, - 0x00000007, - 0x0000002a, - 0x00000025, - 0x00000028, - 0x00000002, - 0x00000029, - 0x00050041, - 0x00000014, - 0x00000030, - 0x00000011, - 0x0000002f, - 0x0004003d, - 0x0000000e, - 0x00000031, - 0x00000030, - 0x00050041, - 0x00000032, - 0x00000033, - 0x0000002e, - 0x00000031, - 0x0004003d, - 0x0000002b, - 0x00000034, - 0x00000033, - 0x00040063, - 0x00000034, - 0x00000036, - 0x0000002a, - 0x000100fd, - 0x00010038, -}; -} diff --git a/cvk/tests/src/test.hpp b/cvk/tests/src/test.hpp index f82fbd87..2d589931 100644 --- a/cvk/tests/src/test.hpp +++ b/cvk/tests/src/test.hpp @@ -30,7 +30,7 @@ constexpr std::string_view APP_NAME = "cvk_tests"; } /** - * glsl sources of the test shaders + * SPIR-V of the test shaders of cvk/tests/shaders: `..spv` */ inline std::filesystem::path const SHADER_DIR{CVK_TEST_SHADER_DIR}; } diff --git a/demo/cube/CMakeLists.txt b/demo/cube/CMakeLists.txt index 499695db..e225832c 100644 --- a/demo/cube/CMakeLists.txt +++ b/demo/cube/CMakeLists.txt @@ -10,34 +10,14 @@ target_link_libraries(cube PRIVATE cgfw jvk timgui glm::glm-header-only) target_compile_definitions(cube PRIVATE GLM_FORCE_DEPTH_ZERO_TO_ONE) -# SPIR-V in the build directory of the target, the program reads it from there -set(CUBE_SHADER_DIR "${CMAKE_CURRENT_BINARY_DIR}/shaders") -set(CUBE_SHADER_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/shaders") -get_target_property(JVK_GLSL_INCLUDE_DIR jvk JVK_GLSL_INCLUDE_DIR) - -set(CUBE_GLSL "${CUBE_SHADER_SRC_DIR}/cube.vert" "${CUBE_SHADER_SRC_DIR}/cube.frag") -# the includes of the shaders: a change compiles them again -set(CUBE_GLSL_INCLUDES "${CUBE_SHADER_SRC_DIR}/cube.glsl" "${JVK_GLSL_INCLUDE_DIR}/jvk/heaps.glsl") -set(CUBE_SPIRV "") - -foreach (GLSL_FILE ${CUBE_GLSL}) - get_filename_component(GLSL_NAME ${GLSL_FILE} NAME) - set(SPIRV_FILE "${CUBE_SHADER_DIR}/${GLSL_NAME}.spv") - - add_custom_command( - OUTPUT ${SPIRV_FILE} - COMMAND ${CMAKE_COMMAND} -E make_directory ${CUBE_SHADER_DIR} - COMMAND ${GLSLC_EXECUTABLE} --target-env=vulkan1.3 -I ${JVK_GLSL_INCLUDE_DIR} -I ${CUBE_SHADER_SRC_DIR} - ${GLSL_FILE} -o ${SPIRV_FILE} - DEPENDS ${GLSL_FILE} ${CUBE_GLSL_INCLUDES} - COMMENT "Compiling ${GLSL_NAME}" - VERBATIM - ) - - list(APPEND CUBE_SPIRV ${SPIRV_FILE}) -endforeach () - -add_custom_target(cube_shaders DEPENDS ${CUBE_SPIRV} SOURCES ${CUBE_GLSL} ${CUBE_GLSL_INCLUDES}) +# the shaders: GLSL objects, the program reads them from the object folder +# cube.glsl is an include of them and no object +cth_glob(CUBE_GLSL "shaders" PATTERNS *.vert *.frag *.glsl) +add_library(cube_shaders OBJECT ${CUBE_GLSL}) +# +target_link_libraries(cube_shaders PRIVATE jvk) add_dependencies(cube cube_shaders) +# the shaders of one source folder share one object folder +set(CUBE_SHADER_DIR "$,0>>") target_compile_definitions(cube PRIVATE CUBE_SHADER_DIR="${CUBE_SHADER_DIR}") diff --git a/demo/triangle/CMakeLists.txt b/demo/triangle/CMakeLists.txt index 31ab4dee..750678e3 100644 --- a/demo/triangle/CMakeLists.txt +++ b/demo/triangle/CMakeLists.txt @@ -6,31 +6,11 @@ cth_target_enable_build_cache(triangle OPTIONAL) target_link_libraries(triangle PRIVATE cgfw jvk) -# SPIR-V in the build directory of the target, the program reads it from there -set(TRIANGLE_SHADER_DIR "${CMAKE_CURRENT_BINARY_DIR}/shaders") -set(TRIANGLE_GLSL - "${CMAKE_CURRENT_SOURCE_DIR}/shaders/triangle.vert" - "${CMAKE_CURRENT_SOURCE_DIR}/shaders/triangle.frag" -) -set(TRIANGLE_SPIRV "") - -foreach (GLSL_FILE ${TRIANGLE_GLSL}) - get_filename_component(GLSL_NAME ${GLSL_FILE} NAME) - set(SPIRV_FILE "${TRIANGLE_SHADER_DIR}/${GLSL_NAME}.spv") - - add_custom_command( - OUTPUT ${SPIRV_FILE} - COMMAND ${CMAKE_COMMAND} -E make_directory ${TRIANGLE_SHADER_DIR} - COMMAND ${GLSLC_EXECUTABLE} --target-env=vulkan1.3 ${GLSL_FILE} -o ${SPIRV_FILE} - DEPENDS ${GLSL_FILE} - COMMENT "Compiling ${GLSL_NAME}" - VERBATIM - ) - - list(APPEND TRIANGLE_SPIRV ${SPIRV_FILE}) -endforeach () - -add_custom_target(triangle_shaders DEPENDS ${TRIANGLE_SPIRV} SOURCES ${TRIANGLE_GLSL}) +# the shaders: GLSL objects, the program reads them from the object folder +cth_glob(TRIANGLE_GLSL "shaders" PATTERNS *.vert *.frag) +add_library(triangle_shaders OBJECT ${TRIANGLE_GLSL}) add_dependencies(triangle triangle_shaders) +# the shaders of one source folder share one object folder +set(TRIANGLE_SHADER_DIR "$,0>>") target_compile_definitions(triangle PRIVATE TRIANGLE_SHADER_DIR="${TRIANGLE_SHADER_DIR}") diff --git a/jvk/CMakeLists.txt b/jvk/CMakeLists.txt index 0e44500f..fad7fd35 100644 --- a/jvk/CMakeLists.txt +++ b/jvk/CMakeLists.txt @@ -11,6 +11,7 @@ set(JVK_HEAP_SAMPLED_IMAGE_BINDING 0) set(JVK_HEAP_STORAGE_IMAGE_BINDING 1) set(JVK_HEAP_SAMPLER_BINDING 2) +# the generated include dir is PUBLIC: a GLSL target that links jvk includes set(JVK_GENERATED_INCL "${CMAKE_CURRENT_BINARY_DIR}/generated/incl") configure_file(config/heap_bindings.hpp.in "${JVK_GENERATED_INCL}/jvk/heap_bindings.hpp" @ONLY) configure_file(config/heaps.glsl.in "${JVK_GENERATED_INCL}/jvk/heaps.glsl" @ONLY) @@ -21,9 +22,6 @@ target_include_directories( PRIVATE src ) -# glslc -I of the shaders that include "jvk/heaps.glsl": get_target_property( jvk JVK_GLSL_INCLUDE_DIR) -set_target_properties(jvk PROPERTIES JVK_GLSL_INCLUDE_DIR "${JVK_GENERATED_INCL}") - target_precompile_headers( jvk PRIVATE diff --git a/jvk/tests/CMakeLists.txt b/jvk/tests/CMakeLists.txt index 604cb9d3..bd15df22 100644 --- a/jvk/tests/CMakeLists.txt +++ b/jvk/tests/CMakeLists.txt @@ -15,6 +15,20 @@ target_precompile_headers( src/pch/pch.hpp ) +# the test shaders: GLSL objects, the tests load them from the object folder +cth_glob(JVK_TESTS_GLSL "shaders" PATTERNS *.comp) +add_library(jvk_tests_shaders OBJECT ${JVK_TESTS_GLSL}) +# "jvk/heaps.glsl" +target_link_libraries(jvk_tests_shaders PRIVATE jvk) +add_dependencies(jvk_tests jvk_tests_shaders) + +# the shaders of one source folder share one object folder +target_compile_definitions( + jvk_tests + PRIVATE + JVK_TEST_SHADER_DIR="$,0>>" +) + find_package(GTest CONFIG REQUIRED) target_link_libraries(jvk_tests PRIVATE GTest::gtest_main jvk) diff --git a/jvk/tests/shaders/heap_copy.comp b/jvk/tests/shaders/heap_copy.comp index d86dd0e1..a5c9fd31 100644 --- a/jvk/tests/shaders/heap_copy.comp +++ b/jvk/tests/shaders/heap_copy.comp @@ -1,3 +1,5 @@ +// compute shader: `jvk/heaps.glsl`, push data `uint` texture, sampler and image index, stores the +// center of the sampled image at texel 0 of the storage image #version 460 #extension GL_GOOGLE_include_directive : require diff --git a/jvk/tests/src/data/heap_test.cpp b/jvk/tests/src/data/heap_test.cpp index 49185ec4..c2669a55 100644 --- a/jvk/tests/src/data/heap_test.cpp +++ b/jvk/tests/src/data/heap_test.cpp @@ -1,7 +1,6 @@ #include "jvk/data/resource_heap.hpp" #include "jvk/data/sampler_heap.hpp" #include "context.hpp" -#include "shaders.hpp" #include "test.hpp" #include "jvk/base/core.hpp" @@ -318,7 +317,7 @@ namespace { sampled{core.resourceHeap().insert(cvk::SampledImageDescriptor{texture})}, storage{core.resourceHeap().insert(cvk::StorageImageDescriptor{target})}, sampler{core.samplerHeap().insert(cvk::SamplerConfig{})}, - shader{core, VK_SHADER_STAGE_COMPUTE_BIT, test::shaders::HEAP_COPY_COMP}, + shader{core, VK_SHADER_STAGE_COMPUTE_BIT, test::SHADER_DIR / "heap_copy.comp.spv"}, pipeline{ core, {.stage = shader.stageInfo(), .descriptorMappings = mappings(core)}, diff --git a/jvk/tests/src/shaders.hpp b/jvk/tests/src/shaders.hpp deleted file mode 100644 index 3539da88..00000000 --- a/jvk/tests/src/shaders.hpp +++ /dev/null @@ -1,318 +0,0 @@ -#pragma once -#include -#include - -/** - * generated from jvk/tests/shaders, regenerate with: - * `glslc --target-env=vulkan1.3 -O -mfmt=num -I /jvk/generated/incl -o .num ` - * @details `-I`: the `JVK_GLSL_INCLUDE_DIR` of the jvk target, with `jvk/heaps.glsl` - */ -namespace jvk::test::shaders { -/** - * compute shader: `jvk/heaps.glsl`, push data `uint` texture, sampler and image index, - * stores the center of the sampled image at texel 0 of the storage image - */ -inline constexpr std::array HEAP_COPY_COMP{ - 0x07230203, - 0x00010600, - 0x000d000b, - 0x00000037, - 0x00000000, - 0x00020011, - 0x00000001, - 0x00020011, - 0x0000002d, - 0x00020011, - 0x00000038, - 0x00020011, - 0x000014b6, - 0x0006000b, - 0x00000001, - 0x4c534c47, - 0x6474732e, - 0x3035342e, - 0x00000000, - 0x0003000e, - 0x00000000, - 0x00000001, - 0x0009000f, - 0x00000005, - 0x00000004, - 0x6e69616d, - 0x00000000, - 0x0000000d, - 0x00000011, - 0x0000001d, - 0x0000002e, - 0x00060010, - 0x00000004, - 0x00000011, - 0x00000001, - 0x00000001, - 0x00000001, - 0x00040047, - 0x0000000d, - 0x00000021, - 0x00000000, - 0x00040047, - 0x0000000d, - 0x00000022, - 0x00000000, - 0x00030047, - 0x0000000f, - 0x00000002, - 0x00050048, - 0x0000000f, - 0x00000000, - 0x00000023, - 0x00000000, - 0x00050048, - 0x0000000f, - 0x00000001, - 0x00000023, - 0x00000004, - 0x00050048, - 0x0000000f, - 0x00000002, - 0x00000023, - 0x00000008, - 0x00040047, - 0x0000001d, - 0x00000021, - 0x00000002, - 0x00040047, - 0x0000001d, - 0x00000022, - 0x00000000, - 0x00040047, - 0x0000002e, - 0x00000021, - 0x00000001, - 0x00040047, - 0x0000002e, - 0x00000022, - 0x00000000, - 0x00020013, - 0x00000002, - 0x00030021, - 0x00000003, - 0x00000002, - 0x00030016, - 0x00000006, - 0x00000020, - 0x00040017, - 0x00000007, - 0x00000006, - 0x00000004, - 0x00090019, - 0x0000000a, - 0x00000006, - 0x00000001, - 0x00000000, - 0x00000000, - 0x00000000, - 0x00000001, - 0x00000000, - 0x0003001d, - 0x0000000b, - 0x0000000a, - 0x00040020, - 0x0000000c, - 0x00000000, - 0x0000000b, - 0x0004003b, - 0x0000000c, - 0x0000000d, - 0x00000000, - 0x00040015, - 0x0000000e, - 0x00000020, - 0x00000000, - 0x0005001e, - 0x0000000f, - 0x0000000e, - 0x0000000e, - 0x0000000e, - 0x00040020, - 0x00000010, - 0x00000009, - 0x0000000f, - 0x0004003b, - 0x00000010, - 0x00000011, - 0x00000009, - 0x00040015, - 0x00000012, - 0x00000020, - 0x00000001, - 0x0004002b, - 0x00000012, - 0x00000013, - 0x00000000, - 0x00040020, - 0x00000014, - 0x00000009, - 0x0000000e, - 0x00040020, - 0x00000017, - 0x00000000, - 0x0000000a, - 0x0002001a, - 0x0000001a, - 0x0003001d, - 0x0000001b, - 0x0000001a, - 0x00040020, - 0x0000001c, - 0x00000000, - 0x0000001b, - 0x0004003b, - 0x0000001c, - 0x0000001d, - 0x00000000, - 0x0004002b, - 0x00000012, - 0x0000001e, - 0x00000001, - 0x00040020, - 0x00000021, - 0x00000000, - 0x0000001a, - 0x0003001b, - 0x00000024, - 0x0000000a, - 0x00040017, - 0x00000026, - 0x00000006, - 0x00000002, - 0x0004002b, - 0x00000006, - 0x00000027, - 0x3f000000, - 0x0005002c, - 0x00000026, - 0x00000028, - 0x00000027, - 0x00000027, - 0x0004002b, - 0x00000006, - 0x00000029, - 0x00000000, - 0x00090019, - 0x0000002b, - 0x00000006, - 0x00000001, - 0x00000000, - 0x00000000, - 0x00000000, - 0x00000002, - 0x00000000, - 0x0003001d, - 0x0000002c, - 0x0000002b, - 0x00040020, - 0x0000002d, - 0x00000000, - 0x0000002c, - 0x0004003b, - 0x0000002d, - 0x0000002e, - 0x00000000, - 0x0004002b, - 0x00000012, - 0x0000002f, - 0x00000002, - 0x00040020, - 0x00000032, - 0x00000000, - 0x0000002b, - 0x00040017, - 0x00000035, - 0x00000012, - 0x00000002, - 0x0005002c, - 0x00000035, - 0x00000036, - 0x00000013, - 0x00000013, - 0x00050036, - 0x00000002, - 0x00000004, - 0x00000000, - 0x00000003, - 0x000200f8, - 0x00000005, - 0x00050041, - 0x00000014, - 0x00000015, - 0x00000011, - 0x00000013, - 0x0004003d, - 0x0000000e, - 0x00000016, - 0x00000015, - 0x00050041, - 0x00000017, - 0x00000018, - 0x0000000d, - 0x00000016, - 0x0004003d, - 0x0000000a, - 0x00000019, - 0x00000018, - 0x00050041, - 0x00000014, - 0x0000001f, - 0x00000011, - 0x0000001e, - 0x0004003d, - 0x0000000e, - 0x00000020, - 0x0000001f, - 0x00050041, - 0x00000021, - 0x00000022, - 0x0000001d, - 0x00000020, - 0x0004003d, - 0x0000001a, - 0x00000023, - 0x00000022, - 0x00050056, - 0x00000024, - 0x00000025, - 0x00000019, - 0x00000023, - 0x00070058, - 0x00000007, - 0x0000002a, - 0x00000025, - 0x00000028, - 0x00000002, - 0x00000029, - 0x00050041, - 0x00000014, - 0x00000030, - 0x00000011, - 0x0000002f, - 0x0004003d, - 0x0000000e, - 0x00000031, - 0x00000030, - 0x00050041, - 0x00000032, - 0x00000033, - 0x0000002e, - 0x00000031, - 0x0004003d, - 0x0000002b, - 0x00000034, - 0x00000033, - 0x00040063, - 0x00000034, - 0x00000036, - 0x0000002a, - 0x000100fd, - 0x00010038, -}; -} diff --git a/jvk/tests/src/test.hpp b/jvk/tests/src/test.hpp index 8c38cb03..cf2c7288 100644 --- a/jvk/tests/src/test.hpp +++ b/jvk/tests/src/test.hpp @@ -3,6 +3,7 @@ #include +#include #include #include #include @@ -28,4 +29,9 @@ constexpr std::string_view APP_NAME = "jvk_tests"; .debugMessenger = debugMessengerOpt, }; } + +/** + * SPIR-V of the test shaders of jvk/tests/shaders: `..spv` + */ +inline std::filesystem::path const SHADER_DIR{JVK_TEST_SHADER_DIR}; } diff --git a/lib/cmake/glslc.cmake b/lib/cmake/glslc.cmake deleted file mode 100644 index 89754330..00000000 --- a/lib/cmake/glslc.cmake +++ /dev/null @@ -1,4 +0,0 @@ -# glslc of the Vulkan SDK or of the system: the build compiles the shaders with it -# sets GLSLC_EXECUTABLE, no glslc -> configure error -cth_find_program(GLSLC_EXECUTABLE glslc HINTS ENV VULKAN_SDK PATH_SUFFIXES bin Bin) -message(STATUS "glslc: ${GLSLC_EXECUTABLE}") diff --git a/lib/cth_cmake b/lib/cth_cmake index b50690b6..c8e7bf52 160000 --- a/lib/cth_cmake +++ b/lib/cth_cmake @@ -1 +1 @@ -Subproject commit b50690b6f4e5b3eb6b796a92271d5801c808291f +Subproject commit c8e7bf52dd66a820688141e17a06cc6c4dd9c043 diff --git a/timgui/CMakeLists.txt b/timgui/CMakeLists.txt index 5c2a94e4..6a69374f 100644 --- a/timgui/CMakeLists.txt +++ b/timgui/CMakeLists.txt @@ -8,37 +8,41 @@ add_library(timgui STATIC ${TIMGUI_SRC} ${TIMGUI_INCL}) cth_target_enable_build_cache(timgui OPTIONAL) -# the SPIR-V of the shaders in generated headers, the library embeds it: no SPIR-V files at run time -set(TIMGUI_SHADER_DIR "${CMAKE_CURRENT_BINARY_DIR}/shaders") -set(TIMGUI_SHADER_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/shaders") +# the shaders: GLSL objects, imgui.glsl is an include of them and no object +cth_glob(TIMGUI_GLSL "shaders" PATTERNS *.vert *.frag *.glsl) +add_library(timgui_shaders OBJECT ${TIMGUI_GLSL}) +# +target_link_libraries(timgui_shaders PRIVATE jvk) + +#TEMP until MSVC has #embed: generated headers embed the SPIR-V +# the library has the SPIR-V: no SPIR-V files at run time set(TIMGUI_GENERATED_SRC "${CMAKE_CURRENT_BINARY_DIR}/generated/src") set(TIMGUI_SPIRV_HEADER_SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/cmake/spirv_header.cmake") -get_target_property(JVK_GLSL_INCLUDE_DIR jvk JVK_GLSL_INCLUDE_DIR) - -set(TIMGUI_GLSL "${TIMGUI_SHADER_SRC_DIR}/imgui.vert" "${TIMGUI_SHADER_SRC_DIR}/imgui.frag") -set(TIMGUI_GLSL_SHARED "${TIMGUI_SHADER_SRC_DIR}/imgui.glsl") -# the includes of the shaders: a change compiles them again -set(TIMGUI_GLSL_INCLUDES ${TIMGUI_GLSL_SHARED} "${JVK_GLSL_INCLUDE_DIR}/jvk/heaps.glsl") set(TIMGUI_SHADER_HEADERS "") foreach (GLSL_FILE ${TIMGUI_GLSL}) get_filename_component(GLSL_NAME ${GLSL_FILE} NAME) - # imgui.vert -> shaders/imgui_vert.hpp with IMGUI_VERT + get_filename_component(GLSL_STAGE ${GLSL_FILE} LAST_EXT) + string(SUBSTRING ${GLSL_STAGE} 1 -1 GLSL_STAGE) + # the includes have no object + if (NOT GLSL_STAGE IN_LIST CMAKE_GLSL_SOURCE_FILE_EXTENSIONS) + continue() + endif () + + # imgui.vert -> object imgui.vert.spv -> shaders/imgui_vert.hpp with IMGUI_VERT + string(REPLACE "." "\\." SPIRV_NAME_REGEX "/${GLSL_NAME}.spv") + set(SPIRV_FILE "$,INCLUDE,${SPIRV_NAME_REGEX}>") string(REPLACE "." "_" HEADER_NAME ${GLSL_NAME}) string(TOUPPER ${HEADER_NAME} ARRAY_NAME) - set(SPIRV_FILE "${TIMGUI_SHADER_DIR}/${GLSL_NAME}.spv") set(HEADER_FILE "${TIMGUI_GENERATED_SRC}/shaders/${HEADER_NAME}.hpp") add_custom_command( OUTPUT ${HEADER_FILE} - COMMAND ${CMAKE_COMMAND} -E make_directory ${TIMGUI_SHADER_DIR} - COMMAND ${GLSLC_EXECUTABLE} --target-env=vulkan1.3 -O - -I ${JVK_GLSL_INCLUDE_DIR} -I ${TIMGUI_SHADER_SRC_DIR} ${GLSL_FILE} -o ${SPIRV_FILE} COMMAND ${CMAKE_COMMAND} -DSPIRV_FILE=${SPIRV_FILE} -DHEADER_FILE=${HEADER_FILE} -DARRAY_NAME=${ARRAY_NAME} -P ${TIMGUI_SPIRV_HEADER_SCRIPT} - DEPENDS ${GLSL_FILE} ${TIMGUI_GLSL_INCLUDES} ${TIMGUI_SPIRV_HEADER_SCRIPT} - COMMENT "Compiling ${GLSL_NAME}" + DEPENDS ${SPIRV_FILE} ${TIMGUI_SPIRV_HEADER_SCRIPT} + COMMENT "Embedding ${GLSL_NAME}" VERBATIM ) @@ -46,7 +50,8 @@ foreach (GLSL_FILE ${TIMGUI_GLSL}) endforeach () # the generated headers as sources: the build writes them before it compiles the library -target_sources(timgui PRIVATE ${TIMGUI_SHADER_HEADERS} ${TIMGUI_GLSL} ${TIMGUI_GLSL_SHARED}) +target_sources(timgui PRIVATE ${TIMGUI_SHADER_HEADERS}) +add_dependencies(timgui timgui_shaders) target_include_directories( timgui diff --git a/timgui/cmake/spirv_header.cmake b/timgui/cmake/spirv_header.cmake index 943d3f39..4ea924ab 100644 --- a/timgui/cmake/spirv_header.cmake +++ b/timgui/cmake/spirv_header.cmake @@ -1,3 +1,4 @@ +#TEMP until MSVC has #embed # writes a SPIR-V file as a header with a constexpr array of its words, run: cmake -P # -DSPIRV_FILE: the SPIR-V of glslc, little endian words # -DHEADER_FILE: the header to write From d1b8ac3e19a2b106e5178dee91ae98b2343195d9 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:37:59 +0100 Subject: [PATCH 19/68] lib: cth_cmake with cth_assert_true in the GLSL compiler check (codethinki/cth_cmake#11) --- lib/cth_cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/cth_cmake b/lib/cth_cmake index c8e7bf52..3038f7b7 160000 --- a/lib/cth_cmake +++ b/lib/cth_cmake @@ -1 +1 @@ -Subproject commit c8e7bf52dd66a820688141e17a06cc6c4dd9c043 +Subproject commit 3038f7b73ee98d8694455df2be07701f74bf3964 From 72abb52c7a9f05a70e72d2dbcebfe3ec9547887a Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:54:38 +0100 Subject: [PATCH 20/68] jvk: lifecycle of the command buffers, review markers of the first batch resolved - jvk command buffers: base constructor, create(), wrap(State), release(), destroy(), State with the pool and the command buffer - cvk::Swapchain: PresentFence -> WaitingFence, no deleted copy members in the wrappers - the accepted //TODO review markers removed, their reasons stay as comments where the code does not show them --- cgfw/incl/cgfw/window/window.hpp | 4 +- cvk/incl/cvk/surface/surface.hpp | 1 - cvk/incl/cvk/surface/swapchain.hpp | 22 ++-- cvk/incl/cvk/utility/vk_error_code.hpp | 4 +- cvk/src/surface/swapchain.cpp | 2 +- jvk/incl/jvk/base/queue.hpp | 2 +- jvk/incl/jvk/cmd/cmd_buffer.hpp | 116 ++++++++++++++++++-- jvk/incl/jvk/graph/stage.hpp | 7 +- jvk/incl/jvk/graph/stage_graph.hpp | 4 +- jvk/incl/jvk/sync/resource_states.hpp | 1 - jvk/incl/jvk/sync/semaphore.hpp | 8 +- jvk/src/base/queue.cpp | 4 +- jvk/src/cmd/cmd_buffer.cpp | 80 +++++++++++++- jvk/src/graph/presenter.cpp | 7 +- jvk/src/graph/stage.cpp | 8 +- jvk/src/graph/stage_graph.cpp | 5 +- jvk/tests/src/base/queue_test.cpp | 8 +- jvk/tests/src/cmd/cmd_buffer_test.cpp | 141 +++++++++++++++++++++---- jvk/tests/src/data/buffer_test.cpp | 2 +- jvk/tests/src/data/heap_test.cpp | 2 +- jvk/tests/src/data/image_test.cpp | 2 +- 21 files changed, 348 insertions(+), 82 deletions(-) diff --git a/cgfw/incl/cgfw/window/window.hpp b/cgfw/incl/cgfw/window/window.hpp index 3cf20b59..7c1ae32c 100644 --- a/cgfw/incl/cgfw/window/window.hpp +++ b/cgfw/incl/cgfw/window/window.hpp @@ -176,8 +176,8 @@ class Window { */ [[nodiscard]] cvk::Surface surface(cvk::Instance const&) const; - //TODO review the size of RGFW: our fork keeps the buffer scale of Wayland at 1, the size is in buffer pixels - //TODO the buffer scale of Wayland (HiDPI): the surface stays at scale 1, a scaled output upscales the window + //TODO the buffer scale of Wayland (HiDPI): the size is in buffer pixels, our fork of RGFW keeps + // the buffer scale at 1, a scaled output upscales the window /** * @return current size of the framebuffer in pixels * @pre `created()` diff --git a/cvk/incl/cvk/surface/surface.hpp b/cvk/incl/cvk/surface/surface.hpp index 9cfc32ac..1037b17b 100644 --- a/cvk/incl/cvk/surface/surface.hpp +++ b/cvk/incl/cvk/surface/surface.hpp @@ -97,7 +97,6 @@ class Surface { */ [[nodiscard]] std::vector formats(PhysicalDevice const&) const; - //TODO review a 0 of the callback stays 0, no clamp: a minimized window has no image /** * @return extent of the swapchain images for the surface * @details diff --git a/cvk/incl/cvk/surface/swapchain.hpp b/cvk/incl/cvk/surface/swapchain.hpp index 93eeb49b..4deb6c9e 100644 --- a/cvk/incl/cvk/surface/swapchain.hpp +++ b/cvk/incl/cvk/surface/swapchain.hpp @@ -263,8 +263,8 @@ class Swapchain { } private: - //TODO review element wrappers: = default moves of the swapchain tear down in the member order, the swapchain - // destroys its images itself and the present fences must signal before their destruction + // the element wrappers: = default moves of the swapchain tear down in the member order, the + // swapchain destroys its images itself, the present fences must signal before their destruction /** * image of the swapchain, the swapchain destroys it * @details the destruction releases the image, it does not destroy it @@ -278,9 +278,8 @@ class Swapchain { Image image; - OwnedImage(OwnedImage const& other) = delete; + // the user-declared destructor suppresses the implicit moves OwnedImage(OwnedImage&& other) noexcept = default; - OwnedImage& operator=(OwnedImage const& other) = delete; OwnedImage& operator=(OwnedImage&& other) noexcept = default; }; @@ -288,19 +287,18 @@ class Swapchain { * present fence of an image * @details the destruction waits for the present that signals it */ - struct PresentFence { - explicit PresentFence(Fence fence) : fence{std::move(fence)} {} - ~PresentFence() { + struct WaitingFence { + explicit WaitingFence(Fence fence) : fence{std::move(fence)} {} + ~WaitingFence() { if(fence.created()) fence.wait(); } Fence fence; - PresentFence(PresentFence const& other) = delete; - PresentFence(PresentFence&& other) noexcept = default; - PresentFence& operator=(PresentFence const& other) = delete; - PresentFence& operator=(PresentFence&& other) noexcept = default; + // the user-declared destructor suppresses the implicit moves + WaitingFence(WaitingFence&& other) noexcept = default; + WaitingFence& operator=(WaitingFence&& other) noexcept = default; }; /** @@ -323,7 +321,7 @@ class Swapchain { // the objects of the images before the handle, in the order of their teardown: = default moves wait for the // presents, release the images, destroy the views and semaphores, then the swapchain - std::vector _presentFences{}; + std::vector _presentFences{}; std::vector _presentSemaphores{}; std::vector _views{}; std::vector _images{}; diff --git a/cvk/incl/cvk/utility/vk_error_code.hpp b/cvk/incl/cvk/utility/vk_error_code.hpp index 3920ef07..3e262ea0 100644 --- a/cvk/incl/cvk/utility/vk_error_code.hpp +++ b/cvk/incl/cvk/utility/vk_error_code.hpp @@ -6,8 +6,8 @@ namespace cvk { //TODO review own header next to vk_exceptions.hpp: error codes are no exceptions -//TODO review no std::is_error_code_enum: VkResult lives in the global namespace, the implicit conversion -// finds make_error_code() only through ADL there, a global make_error_code() would be needed +// no std::is_error_code_enum: VkResult lives in the global namespace, the implicit +// conversion finds make_error_code() only through ADL there, a global make_error_code() would be needed /** * error category of `VkResult` * @details diff --git a/cvk/src/surface/swapchain.cpp b/cvk/src/surface/swapchain.cpp index dec923a8..322ac3da 100644 --- a/cvk/src/surface/swapchain.cpp +++ b/cvk/src/surface/swapchain.cpp @@ -245,7 +245,7 @@ bool Swapchain::presented() const { return std::ranges::all_of( _presentFences, - [](PresentFence const& presentFence) { return presentFence.fence.signaled(); } + [](WaitingFence const& presentFence) { return presentFence.fence.signaled(); } ); } diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index f56eefdf..430d3da7 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -55,7 +55,7 @@ class Queue { //TODO review an executor_task: the receiving submit job awaits it before its own submit, so the release is // submitted first and the counter only changes in the strand (returning at once needs a lock around the value // and the post) - //TODO review const like executor(): Queues hands out Queue const&, the release members are mutable + // const like executor(): Queues hands out Queue const&, the release members are mutable //TODO review returns the jvk SemaphoreSubmitInfo: it keeps the counter for Semaphore::submitted(), it converts to // the cvk one /** diff --git a/jvk/incl/jvk/cmd/cmd_buffer.hpp b/jvk/incl/jvk/cmd/cmd_buffer.hpp index bee7a92a..2d3b8272 100644 --- a/jvk/incl/jvk/cmd/cmd_buffer.hpp +++ b/jvk/incl/jvk/cmd/cmd_buffer.hpp @@ -7,6 +7,8 @@ #include "cvk/render/cmd/cmd_buffer.hpp" #include "cvk/render/cmd/cmd_pool.hpp" #include "cvk/render/cmd/rendering_info.hpp" +#include "cvk/utility/constants.hpp" +#include "cvk/utility/types.hpp" #include @@ -19,6 +21,7 @@ #include #include #include +#include #include @@ -98,8 +101,6 @@ class scoped_rendering { } namespace jvk::dev { -//TODO review no wrap(), create(), destroy() or release(): the constructor creates the pool and the command buffer, -// they live with the object /** * base of the jvk command buffers * @details @@ -113,8 +114,55 @@ namespace jvk::dev { template class BasicCmdBuffer { public: + struct State; + static constexpr VkCommandPoolCreateFlags POOL_FLAGS = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; + /** + * wraps the state + * @details the resource states start empty + * @pre `cvk::Core::created()` + * @pre `State::vkPool` was created with the queue family of the object and `POOL_FLAGS` + * @pre `State::vkBuffer` is the only command buffer of `State::vkPool`, with the level of `Cvk` + * @pre the command buffer is not recording + * @post `created()` + * @note calls `optDestroy()` + */ + void wrap(State const&); + + /** + * creates the own command pool and the command buffer + * @details the resource states start empty + * @pre `cvk::Core::created()` + * @post `created()` + * @note calls `optDestroy()` + * @throws cvk::vk_result_exception result of `vkCreateCommandPool()` or `vkAllocateCommandBuffers()` + */ + void create(); + + /** + * frees the command buffer, destroys the pool and forgets + * @details drops the resource states + * @pre `created()` + * @pre the command buffer is not pending + */ + void destroy(); + + /** + * if `created()` -> calls `destroy()` + */ + void optDestroy() { + if(created()) + destroy(); + } + + /** + * releases ownership of the command buffer and the pool, returns the state and forgets + * @details drops the resource states + * @pre `created()` + */ + State release(); + /** * ends the recording * @see `cvk::BaseCmdBuffer::end()` @@ -395,12 +443,14 @@ class BasicCmdBuffer { protected: /** - * creates the own command pool and the command buffer + * base constructor */ BasicCmdBuffer(cvk::Core const&, cvk::queue_family_index_t); - // frees the command buffer before the members destroy the pool - ~BasicCmdBuffer() { _cmdBuffer.optDestroy(); } + /** + * @note calls `optDestroy()` + */ + ~BasicCmdBuffer() { optDestroy(); } /** * resets the pool and the resource states @@ -429,6 +479,8 @@ class BasicCmdBuffer { */ void record(cvk::Barrier&) const; + void forget(); + template void addAccesses( cvk::Barrier& barrier, @@ -453,6 +505,22 @@ class BasicCmdBuffer { }; } +namespace jvk::dev { +template +struct BasicCmdBuffer::State { + cvk::vk_not_null vkPool; ///< the own pool, it allocated `vkBuffer` + cvk::vk_not_null vkBuffer; + + /** + * the raw handles to destroy, in destruction order: the command buffer, then the pool + */ + [[nodiscard]] constexpr std::tuple, VkCommandPool> + decompose() && { + return {std::tuple{vkPool.get(), vkBuffer.get()}, vkPool.get()}; + } +}; +} + namespace jvk::dev { extern template class BasicCmdBuffer; extern template class BasicCmdBuffer; @@ -472,12 +540,27 @@ class SecondaryCmdBuffer; class PrimaryCmdBuffer : public dev::BasicCmdBuffer { public: /** - * creates the own command pool and the command buffer + * base constructor * @param queueFamilyIndex of the queues it is submitted to - * @throws cvk::vk_result_exception result of `vkCreateCommandPool()` or `vkAllocateCommandBuffers()` */ PrimaryCmdBuffer(cvk::Core const&, cvk::queue_family_index_t queueFamilyIndex); + /** + * constructs and wraps + * @details calls @ref PrimaryCmdBuffer(cvk::Core const&, cvk::queue_family_index_t), `wrap()` + */ + PrimaryCmdBuffer(cvk::Core const&, cvk::queue_family_index_t queueFamilyIndex, State const&); + + /** + * constructs and creates + * @details calls @ref PrimaryCmdBuffer(cvk::Core const&, cvk::queue_family_index_t), `create()` + */ + explicit PrimaryCmdBuffer( + cvk::Core const&, + cvk::queue_family_index_t queueFamilyIndex, + cvk::create_t + ); + /** * begins the recording * @details resets the pool and the resource states @@ -533,12 +616,27 @@ class SecondaryCmdBuffer : public dev::BasicCmdBuffer { using Inheritance = cvk::SecondaryCmdBuffer::Inheritance; /** - * creates the own command pool and the command buffer + * base constructor * @param queueFamilyIndex of the queues its primaries are submitted to - * @throws cvk::vk_result_exception result of `vkCreateCommandPool()` or `vkAllocateCommandBuffers()` */ SecondaryCmdBuffer(cvk::Core const&, cvk::queue_family_index_t queueFamilyIndex); + /** + * constructs and wraps + * @details calls @ref SecondaryCmdBuffer(cvk::Core const&, cvk::queue_family_index_t), `wrap()` + */ + SecondaryCmdBuffer(cvk::Core const&, cvk::queue_family_index_t queueFamilyIndex, State const&); + + /** + * constructs and creates + * @details calls @ref SecondaryCmdBuffer(cvk::Core const&, cvk::queue_family_index_t), `create()` + */ + explicit SecondaryCmdBuffer( + cvk::Core const&, + cvk::queue_family_index_t queueFamilyIndex, + cvk::create_t + ); + /** * begins the recording outside of a rendering * @details resets the pool and the resource states diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index e2776545..4ab77787 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -37,7 +37,6 @@ class scoped_submit; } namespace jvk::dev { -//TODO review name: like cvk::SubmitInfo and the legacy jvk::SubmitInfo /** * prebuilt submit of a stage slot * @details @@ -108,8 +107,8 @@ struct RetainedResources { std::vector buffers{}; }; -//TODO review a constructor, no aggregate: `SubmitInfo::signal` and `SubmitInfo::cmdBuffers` refer to members, the -// mutex does not move +// a constructor, no aggregate: `SubmitInfo::signal` and `SubmitInfo::cmdBuffers` refer to members, +// the mutex does not move /** * resources of a stage in one frame slot * @details @@ -404,7 +403,7 @@ class Stage { uint64_t _frameNumber; Status _status = Status::UNSUBMITTED; - //TODO review names: the extra waits per kind, the jvk ones keep the jvk semaphore + // one list per kind of wait: the jvk waits keep the jvk semaphore /** the waits of @ref await(SemaphoreSubmitInfo const&) */ std::vector _extraWaits{}; diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index 91a4dc91..ceda20e1 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -52,7 +52,7 @@ class StageGraph { public: using Config = StageGraphConfig; - //TODO review no base constructor and create(): the graph has no wrap or release + // no base constructor and create(): the graph has no wrap or release /** * creates the stage slots and the frame slots * @details computes `firstFrameNumber()` from the config @@ -166,7 +166,6 @@ class StageGraph { using release_map_t = cth::dt::flat_hash_map; - //TODO review name using semaphore_waits_t = std::vector; /** @@ -300,7 +299,6 @@ class StageGraph { /** the running submit jobs, `~StageGraph()` waits for them */ cth::co::simple_counting_scope _jobs{}; - //TODO review name firstFrameNumber uint64_t _firstFrameNumber; ///< see `firstFrameNumber()` /** diff --git a/jvk/incl/jvk/sync/resource_states.hpp b/jvk/incl/jvk/sync/resource_states.hpp index 93ba459b..ac9b04c6 100644 --- a/jvk/incl/jvk/sync/resource_states.hpp +++ b/jvk/incl/jvk/sync/resource_states.hpp @@ -43,7 +43,6 @@ struct ImageAccess { /** (`VK_REMAINING_MIP_LEVELS` => to the last mip level) */ uint32_t mipLevels = VK_REMAINING_MIP_LEVELS; - //TODO review /** * the access does not need the previous contents * @attention all layers and aspects of the mip levels lose their contents diff --git a/jvk/incl/jvk/sync/semaphore.hpp b/jvk/incl/jvk/sync/semaphore.hpp index ab5b7adf..c3da2594 100644 --- a/jvk/incl/jvk/sync/semaphore.hpp +++ b/jvk/incl/jvk/sync/semaphore.hpp @@ -23,7 +23,6 @@ namespace jvk { class Core; class Semaphore; -//TODO review name: snake_case like the awaiters of cth (general type, like std) /** * awaiter of `Semaphore::wait()` and of `co_await` on a `Stage` * @details resumes the caller on its context, a failed wait throws in the caller @@ -63,7 +62,6 @@ class semaphore_awaiter : public cth::co::this_coro_awaiter_base, uint64_t _value; }; -//TODO review name: snake_case like semaphore_awaiter /** * awaiter of `Semaphore::submitted()` * @details resumes the caller on its context @@ -87,7 +85,7 @@ class submitted_awaiter : public cth::co::this_coro_awaiter_base { template requires cth::co::this_coro_compatible void await_suspend(std::coroutine_handle caller); - //TODO review no error: the jvk submit paths mark every signal value, also after an error of the submit + // no error: the jvk submit paths mark every signal value, also after an error of the submit constexpr void await_resume() const noexcept {} private: @@ -130,7 +128,7 @@ class Semaphore { */ ~Semaphore() { optDestroy(); } - //TODO review the submitted value of a wrap: State::value, the values given out before the wrap count as submitted + // the values given out before the wrap count as submitted /** * wraps the state * @details `submittedValue()` becomes `State::value` @@ -294,7 +292,6 @@ class Semaphore { } namespace jvk { -//TODO review name: cvk::SemaphoreSubmitInfo with the jvk semaphore and a fixed value //TODO review in semaphore.hpp next to Semaphore: it is small, no own header /** * wait or signal of a submit on a jvk semaphore @@ -319,7 +316,6 @@ struct SemaphoreSubmitInfo { } namespace jvk::dev { -//TODO review name post_to /** * callback that posts the callback to the context * @details the reactor and `Semaphore::markSubmitted()` call on a worker, the awaiters resume on the context of the diff --git a/jvk/src/base/queue.cpp b/jvk/src/base/queue.cpp index 919500fb..3197aba6 100644 --- a/jvk/src/base/queue.cpp +++ b/jvk/src/base/queue.cpp @@ -56,6 +56,8 @@ auto Queue::freeReleaseCmd() const -> ReleaseCmd& { if(it != _releaseCmds.end()) return *it; - return _releaseCmds.emplace_back(ReleaseCmd{PrimaryCmdBuffer{*_core, _queue->familyIndex()}}); + return _releaseCmds.emplace_back( + ReleaseCmd{PrimaryCmdBuffer{*_core, _queue->familyIndex(), cvk::create}} + ); } } diff --git a/jvk/src/cmd/cmd_buffer.cpp b/jvk/src/cmd/cmd_buffer.cpp index 000d5674..0341bbe1 100644 --- a/jvk/src/cmd/cmd_buffer.cpp +++ b/jvk/src/cmd/cmd_buffer.cpp @@ -206,16 +206,59 @@ BasicCmdBuffer::BasicCmdBuffer( BasicCmdBuffer{ std::make_unique( core, - cvk::CmdPool::Config{.queueFamilyIndex = queueFamilyIndex, .flags = POOL_FLAGS}, - cvk::create + cvk::CmdPool::Config{.queueFamilyIndex = queueFamilyIndex, .flags = POOL_FLAGS} ) } {} template BasicCmdBuffer::BasicCmdBuffer(std::unique_ptr poolPtr) : - _cmdBuffer{*poolPtr, cvk::create}, + _cmdBuffer{*poolPtr}, _poolPtr{std::move(poolPtr)} {} +template +void BasicCmdBuffer::wrap(State const& state) { + optDestroy(); + + _poolPtr->wrap(cvk::CmdPool::State{.vkPool = state.vkPool}); + _cmdBuffer.wrap(cvk::BaseCmdBuffer::State{.vkPool = state.vkPool, .vkBuffer = state.vkBuffer}); +} + +template +void BasicCmdBuffer::create() { + optDestroy(); + + _poolPtr->create(); + + // the command buffer needs the created pool, only a catch destroys the pool when the allocation fails + try { _cmdBuffer.create(); } + catch(...) { + _poolPtr->destroy(); + throw; + } +} + +template +void BasicCmdBuffer::destroy() { + Cvk::debug_check(_cmdBuffer); + + _cmdBuffer.destroy(); + _poolPtr->destroy(); + + forget(); +} + +template +auto BasicCmdBuffer::release() -> State { + Cvk::debug_check(_cmdBuffer); + + // the command buffer first: the pool releases only without counted command buffers + auto const cmdBuffer = _cmdBuffer.release(); + auto const pool = _poolPtr->release(); + + forget(); + return State{.vkPool = pool.vkPool, .vkBuffer = cmdBuffer.vkBuffer}; +} + template void BasicCmdBuffer::use(cvk::Image const& image, ImageAccess const& access) { cvk::Barrier barrier{}; @@ -375,6 +418,9 @@ void BasicCmdBuffer::record(cvk::Barrier& barrier) const { barrier.execute(_cmdBuffer); } +template +void BasicCmdBuffer::forget() { _states.clear(); } + template class BasicCmdBuffer; template class BasicCmdBuffer; } @@ -387,6 +433,20 @@ PrimaryCmdBuffer::PrimaryCmdBuffer( ) : BasicCmdBuffer{core, queueFamilyIndex} {} +PrimaryCmdBuffer::PrimaryCmdBuffer( + cvk::Core const& core, + cvk::queue_family_index_t queueFamilyIndex, + State const& state +) : + PrimaryCmdBuffer{core, queueFamilyIndex} { wrap(state); } + +PrimaryCmdBuffer::PrimaryCmdBuffer( + cvk::Core const& core, + cvk::queue_family_index_t queueFamilyIndex, + cvk::create_t +) : + PrimaryCmdBuffer{core, queueFamilyIndex} { create(); } + void PrimaryCmdBuffer::begin(VkCommandBufferUsageFlags usage) { reset(); _cmdBuffer.begin(usage); @@ -417,6 +477,20 @@ SecondaryCmdBuffer::SecondaryCmdBuffer( ) : BasicCmdBuffer{core, queueFamilyIndex} {} +SecondaryCmdBuffer::SecondaryCmdBuffer( + cvk::Core const& core, + cvk::queue_family_index_t queueFamilyIndex, + State const& state +) : + SecondaryCmdBuffer{core, queueFamilyIndex} { wrap(state); } + +SecondaryCmdBuffer::SecondaryCmdBuffer( + cvk::Core const& core, + cvk::queue_family_index_t queueFamilyIndex, + cvk::create_t +) : + SecondaryCmdBuffer{core, queueFamilyIndex} { create(); } + void SecondaryCmdBuffer::begin(VkCommandBufferUsageFlags usage, cvk::HeapInheritance const& heaps) { reset(); _cmdBuffer.begin(usage, heaps); diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index ee2fe0da..06e1f663 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -83,8 +83,9 @@ void Presenter::destroy() { } } - //TODO review after the wait for the present submits: the earlier frames that used the image ended on the gpu - // (VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786), the stage of the image is under the @pre + // after the wait for the present submits: the earlier frames that used the image ended on the + // gpu (VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786), the stage of the image is under + // the @pre // no job runs, no acquire is pending: nothing else uses the swapchain if(_acquiredOpt.has_value()) { try { unacquireImage(); } @@ -330,7 +331,7 @@ void Presenter::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { while(_submits.size() < _swapchain.current().imageCount()) _submits.push_back( - PresentSubmit{.cmd = PrimaryCmdBuffer{*_core, _queue->vk().familyIndex()}} + PresentSubmit{.cmd = PrimaryCmdBuffer{*_core, _queue->vk().familyIndex(), cvk::create}} ); } diff --git a/jvk/src/graph/stage.cpp b/jvk/src/graph/stage.cpp index c6b60423..c03af750 100644 --- a/jvk/src/graph/stage.cpp +++ b/jvk/src/graph/stage.cpp @@ -100,14 +100,14 @@ StageSlot::StageSlot( semaphore{graph.core(), cvk::create, graph.firstFrameNumber() - 1}, submitInfo{.signal = {.semaphore = semaphore, .value = graph.firstFrameNumber() + slot}}, previous{*this}, - prologue{graph.core(), queue.vk().familyIndex()}, - primary{graph.core(), queue.vk().familyIndex()}, + prologue{graph.core(), queue.vk().familyIndex(), cvk::create}, + primary{graph.core(), queue.vk().familyIndex(), cvk::create}, stasis{graph.core()} { submitInfo.cmdBuffers = {prologue, primary}; this->secondaries.reserve(secondaries); for(size_t i = 0; i < secondaries; ++i) - this->secondaries.emplace_back(graph.core(), queue.vk().familyIndex()); + this->secondaries.emplace_back(graph.core(), queue.vk().familyIndex(), cvk::create); } } @@ -155,7 +155,7 @@ SecondaryCmdBuffer& Stage::secondary(size_t secondaryIdx) { } SecondaryCmdBuffer Stage::persistentSecondary() const { - return SecondaryCmdBuffer{_stageSlot->graph->core(), queue().vk().familyIndex()}; + return SecondaryCmdBuffer{_stageSlot->graph->core(), queue().vk().familyIndex(), cvk::create}; } void Stage::await(SemaphoreSubmitInfo const& wait) { diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index 9af33c26..f53a90d4 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -111,8 +111,9 @@ StageGraph::~StageGraph() { for(auto& stage : frameSlot.stages) { if(stage.status() != Stage::Status::UNSUBMITTED) continue; - //TODO review the binary waits dropped: a presenter is destroyed before the graph, its present submits wait - // for the semaphores of the graph, the acquire semaphore of an unpresented image is destroyed already + // the binary waits dropped: a presenter is destroyed before the graph, its present + // submits wait for the semaphores of the graph, the acquire semaphore of an unpresented + // image is destroyed already stage._extraBinaryWaits.clear(); try { skip(stage); } catch(std::exception const& e) { diff --git a/jvk/tests/src/base/queue_test.cpp b/jvk/tests/src/base/queue_test.cpp index b9c17f51..931f962e 100644 --- a/jvk/tests/src/base/queue_test.cpp +++ b/jvk/tests/src/base/queue_test.cpp @@ -244,7 +244,7 @@ JVK_TEST(Queue, release_transfers_an_image_to_another_family) { Buffer const readback{core, test::READBACK_CONFIG, PIXELS}; // written on the family of the owner - PrimaryCmdBuffer write{core, ownerFamily}; + PrimaryCmdBuffer write{core, ownerFamily, cvk::create}; write.begin(); write.assume(image, UNDEFINED); image.copy(write, staging); @@ -266,7 +266,7 @@ JVK_TEST(Queue, release_transfers_an_image_to_another_family) { EXPECT_EQ(released.semaphore->submittedValue(), released.value); // the acquire half on the family of the receiver, then the read - PrimaryCmdBuffer read{core, receiverFamily}; + PrimaryCmdBuffer read{core, receiverFamily, cvk::create}; read.begin(); cvk::Barrier acquire{}; acquire.add( @@ -318,7 +318,7 @@ JVK_TEST(Queue, several_releases_in_a_row) { readbacks.emplace_back(core, test::READBACK_CONFIG, PIXELS); } - PrimaryCmdBuffer write{core, ownerFamily}; + PrimaryCmdBuffer write{core, ownerFamily, cvk::create}; write.begin(); for(auto const& buffer : buffers) buffer.copy(write, staging); @@ -344,7 +344,7 @@ JVK_TEST(Queue, several_releases_in_a_row) { } // the wait for the last value covers the earlier releases - PrimaryCmdBuffer read{core, receiverFamily}; + PrimaryCmdBuffer read{core, receiverFamily, cvk::create}; read.begin(); cvk::Barrier acquire{}; for(auto const& buffer : buffers) diff --git a/jvk/tests/src/cmd/cmd_buffer_test.cpp b/jvk/tests/src/cmd/cmd_buffer_test.cpp index 178ebc20..b2e686eb 100644 --- a/jvk/tests/src/cmd/cmd_buffer_test.cpp +++ b/jvk/tests/src/cmd/cmd_buffer_test.cpp @@ -4,6 +4,7 @@ #include "test.hpp" #include "jvk/base/queue.hpp" +#include "jvk/base/stasis.hpp" #include "jvk/data/buffer.hpp" #include "jvk/data/image.hpp" @@ -152,7 +153,7 @@ JVK_TEST(CmdBuffer, use_of_several_resources_records_their_barriers) { Image const image{context.core, IMAGE_CONFIG, EXTENT}; auto const staging = counting_staging(context); Buffer const readback{context.core, READBACK_CONFIG, PIXELS}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; constexpr ImageAccess TRANSFER_DST{ .layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .stages = VK_PIPELINE_STAGE_2_TRANSFER_BIT, @@ -197,7 +198,7 @@ JVK_TEST(CmdBuffer, use_of_several_resources_records_their_barriers) { JVK_TEST(CmdBuffer, owns_its_pool) { test::Context const context{}; - PrimaryCmdBuffer const primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer const primary{context.core, test::queue_family(context), cvk::create}; ASSERT_TRUE(primary.created()); EXPECT_EQ(primary.pool().config().flags, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT); @@ -207,7 +208,7 @@ JVK_TEST(CmdBuffer, owns_its_pool) { JVK_TEST(CmdBuffer, begin_resets_the_states) { test::Context const context{}; cvk::Image const image{context.core, IMAGE_CONFIG, EXTENT}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; primary.begin(); primary.assume(image, UNDEFINED); @@ -225,7 +226,7 @@ JVK_TEST(CmdBuffer, tracked_copies_are_synchronized) { Image const image{context.core, IMAGE_CONFIG, EXTENT}; auto const staging = counting_staging(context); Buffer const readback{context.core, READBACK_CONFIG, PIXELS}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; primary.begin(); primary.assume(image, UNDEFINED); @@ -248,7 +249,7 @@ JVK_TEST(CmdBuffer, submit_twice_without_a_new_recording) { Image const image{context.core, IMAGE_CONFIG, EXTENT}; auto const staging = counting_staging(context); Buffer const readback{context.core, READBACK_CONFIG, PIXELS}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; primary.begin(); primary.assume(image, UNDEFINED); @@ -267,9 +268,9 @@ JVK_TEST(CmdBuffer, execute_appends_the_states_of_the_secondaries) { Image const image{context.core, IMAGE_CONFIG, EXTENT}; auto const staging = counting_staging(context); Buffer const readback{context.core, READBACK_CONFIG, PIXELS}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; - SecondaryCmdBuffer first{context.core, test::queue_family(context)}; - SecondaryCmdBuffer second{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; + SecondaryCmdBuffer first{context.core, test::queue_family(context), cvk::create}; + SecondaryCmdBuffer second{context.core, test::queue_family(context), cvk::create}; // the secondaries do not know the image: their accesses are first uses first.begin(); @@ -301,7 +302,7 @@ JVK_TEST(CmdBuffer, begin_rendering_records_the_attachments) { Image const image{context.core, COLOR_CONFIG, EXTENT}; cvk::ImageView const view{image, {}, cvk::create}; cvk::Buffer const readback{context.core, READBACK_CONFIG, PIXELS}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; primary.begin(); primary.assume(image, UNDEFINED); @@ -339,7 +340,7 @@ JVK_TEST(CmdBuffer, begin_rendering_records_the_attachments) { JVK_TEST(CmdBuffer, rendering_scope_ends_the_rendering_at_its_end) { test::Context const context{}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; primary.begin(); { @@ -362,7 +363,7 @@ JVK_TEST(CmdBuffer, rendering_scope_ends_the_rendering_at_its_end) { JVK_TEST(CmdBuffer, rendering_scope_does_nothing_after_an_end_or_a_move) { test::Context const context{}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; // a second end fails its check primary.begin(); @@ -394,7 +395,7 @@ JVK_TEST(CmdBuffer, use_inside_a_rendering_records_a_local_read_barrier) { if(!local_read_supported(context)) GTEST_SKIP() << "needs dynamicRenderingLocalRead"; LocalRead const localRead{context}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; primary.begin(); primary.assume(localRead.image, UNDEFINED); @@ -427,7 +428,7 @@ JVK_TEST(CmdBuffer, copy_after_a_rendering_with_a_local_read) { LocalRead const localRead{context}; auto const staging = counting_staging(context); Buffer const readback{context.core, READBACK_CONFIG, PIXELS}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; primary.begin(); primary.assume(localRead.image, UNDEFINED); @@ -454,8 +455,8 @@ JVK_TEST(CmdBuffer, continuing_secondary_records_a_local_read_barrier) { GTEST_SKIP() << "needs dynamicRenderingLocalRead"; LocalRead const localRead{context}; Buffer const readback{context.core, READBACK_CONFIG, PIXELS}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; - SecondaryCmdBuffer secondary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; + SecondaryCmdBuffer secondary{context.core, test::queue_family(context), cvk::create}; primary.begin(); primary.assume(localRead.image, UNDEFINED); @@ -504,7 +505,7 @@ JVK_TEST(CmdBuffer, bind_records_the_buffer_access) { {.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT}, PIXELS }; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; primary.begin(); vertices.copy(primary, staging); @@ -531,7 +532,7 @@ JVK_TEST(CmdBuffer, converts_to_the_const_cvk_type) { JVK_TEST(CmdBuffer, submit_info_takes_the_jvk_buffer) { test::Context const context{}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; primary.begin(); primary.end(); @@ -547,7 +548,7 @@ JVK_TEST(CmdBuffer, submit_info_takes_the_jvk_buffer) { JVK_TEST(CmdBuffer, cvk_function_records_untracked) { test::Context const context{}; cvk::Image const image{context.core, IMAGE_CONFIG, EXTENT}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; primary.begin(); cvk::Barrier barrier{}; @@ -571,7 +572,7 @@ JVK_TEST(CmdBuffer, cvk_function_records_untracked) { JVK_TEST(CmdBuffer, move_keeps_the_pool) { test::Context const context{}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; auto const vkBuffer = primary.get(); PrimaryCmdBuffer moved{std::move(primary)}; @@ -580,8 +581,108 @@ JVK_TEST(CmdBuffer, move_keeps_the_pool) { EXPECT_EQ(moved.get(), vkBuffer); - PrimaryCmdBuffer other{context.core, test::queue_family(context)}; + PrimaryCmdBuffer other{context.core, test::queue_family(context), cvk::create}; other = std::move(moved); EXPECT_EQ(other.get(), vkBuffer); } + +JVK_TEST(CmdBuffer, base_constructor_does_not_create) { + test::Context const context{}; + + PrimaryCmdBuffer const primary{context.core, test::queue_family(context)}; + + EXPECT_FALSE(primary.created()); + EXPECT_FALSE(primary.pool().created()); +} + +JVK_TEST(CmdBuffer, create_and_destroy) { + test::Context const context{}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + + primary.create(); + ASSERT_TRUE(primary.created()); + EXPECT_TRUE(primary.pool().created()); + + primary.destroy(); + EXPECT_FALSE(primary.created()); + EXPECT_FALSE(primary.pool().created()); + + // a leak shows up when the shared device is destroyed + primary.optDestroy(); + primary.create(); + primary.optDestroy(); + EXPECT_FALSE(primary.created()); +} + +JVK_TEST(CmdBuffer, destroy_drops_the_states) { + test::Context const context{}; + cvk::Image const image{context.core, IMAGE_CONFIG, EXTENT}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; + + primary.begin(); + primary.assume(image, UNDEFINED); + primary.end(); + ASSERT_FALSE(primary.states().empty()); + + primary.destroy(); + EXPECT_TRUE(primary.states().empty()); + + primary.create(); + EXPECT_TRUE(primary.states().empty()); +} + +JVK_TEST(CmdBuffer, release_and_wrap) { + test::Context const context{}; + cvk::Image const image{context.core, IMAGE_CONFIG, EXTENT}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; + auto const vkBuffer = primary.get(); + auto const vkPool = primary.pool().get(); + + primary.begin(); + primary.assume(image, UNDEFINED); + primary.end(); + + auto const state = primary.release(); + EXPECT_FALSE(primary.created()); + EXPECT_FALSE(primary.pool().created()); + EXPECT_TRUE(primary.states().empty()); + EXPECT_EQ(state.vkBuffer.get(), vkBuffer); + EXPECT_EQ(state.vkPool.get(), vkPool); + + PrimaryCmdBuffer wrapped{context.core, test::queue_family(context), state}; + ASSERT_TRUE(wrapped.created()); + EXPECT_EQ(wrapped.get(), vkBuffer); + EXPECT_EQ(wrapped.pool().get(), vkPool); + EXPECT_TRUE(wrapped.states().empty()); + + // the wrapped command buffer records and submits + wrapped.begin(); + wrapped.end(); + test::submit_and_wait(context, wrapped); +} + +JVK_TEST(CmdBuffer, secondary_release_and_wrap) { + test::Context const context{}; + SecondaryCmdBuffer secondary{context.core, test::queue_family(context), cvk::create}; + auto const vkBuffer = secondary.get(); + + auto const state = secondary.release(); + SecondaryCmdBuffer const wrapped{context.core, test::queue_family(context), state}; + + EXPECT_FALSE(secondary.created()); + EXPECT_EQ(wrapped.get(), vkBuffer); +} + +JVK_TEST(CmdBuffer, stasis_destroys_the_released_state) { + // a leak shows up when the shared device is destroyed + test::Context const context{}; + Stasis stasis{context.core}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; + + stasis.add(primary.release()); + + // the command buffer, then the pool + EXPECT_EQ(stasis.size(), 2); + stasis.clear(); +} } diff --git a/jvk/tests/src/data/buffer_test.cpp b/jvk/tests/src/data/buffer_test.cpp index a06a76ef..5442040e 100644 --- a/jvk/tests/src/data/buffer_test.cpp +++ b/jvk/tests/src/data/buffer_test.cpp @@ -29,7 +29,7 @@ JVK_TEST(Buffer, copies_record_their_accesses) { staging.write(VALUES); Buffer const device{context.core, DEVICE_CONFIG, VALUES.size()}; Buffer const readback{context.core, READBACK_CONFIG, VALUES.size()}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; primary.begin(); device.copy(primary, staging); diff --git a/jvk/tests/src/data/heap_test.cpp b/jvk/tests/src/data/heap_test.cpp index c2669a55..121c9a33 100644 --- a/jvk/tests/src/data/heap_test.cpp +++ b/jvk/tests/src/data/heap_test.cpp @@ -284,7 +284,7 @@ JVK_TEST(CmdBuffer, use_of_a_handle_tracks_the_layout_of_its_type_on_the_mip_lev auto const storage = heap.insert(cvk::StorageImageDescriptor{.image = image, .view = view(1)}); auto const input = heap.insert(cvk::InputAttachmentDescriptor{.image = image, .view = view(2)}); - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; primary.begin(); primary.use(sampled, VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT); primary.use( diff --git a/jvk/tests/src/data/image_test.cpp b/jvk/tests/src/data/image_test.cpp index aa05c86d..8543c71c 100644 --- a/jvk/tests/src/data/image_test.cpp +++ b/jvk/tests/src/data/image_test.cpp @@ -33,7 +33,7 @@ JVK_TEST(Image, blit_mip_levels_records_its_accesses) { Buffer staging{context.core, STAGING_CONFIG, size_t{EXTENT.width} * EXTENT.height}; staging.write(std::vector(size_t{EXTENT.width} * EXTENT.height, WHITE)); Buffer const readback{context.core, READBACK_CONFIG, 1}; - PrimaryCmdBuffer primary{context.core, test::queue_family(context)}; + PrimaryCmdBuffer primary{context.core, test::queue_family(context), cvk::create}; auto const lastLevel = image.mipLevels() - 1; primary.begin(); From 0ab2708256ecc6c3a9538148cd85f4e3a08bc1df Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:07:41 +0100 Subject: [PATCH 21/68] jvk, cvk: review markers of the second batch, Queues into Core, ResourceTracker, barrier scopes without queue family - jvk::Queues removed: the queues are a std::vector of jvk::Core, Queue moves - ResourceHeap, TimelineReactor, SamplerHeap: standard lifecycle or = default moves, the mutexes behind std::unique_ptr - ResourceStates -> ResourceTracker, images() gives ImageMip - nextFrame() awaits the old frame with cth::co::all - cvk::BarrierScope without queue family: the families are fields of the image and buffer barrier infos, memory barriers are VkMemoryBarrier2, no QueueTransition() factories - ReleasingImage, Window::destroy(RGFW_window&), Semaphore::onSubmitted(), scoped_acquire without uncaught exceptions - the accepted //TODO review markers removed --- cgfw/incl/cgfw/window/window.hpp | 5 +- cgfw/src/window/window.cpp | 10 +- cvk/incl/cvk/data/buffer/buffer_config.hpp | 2 +- cvk/incl/cvk/data/img/image_config.hpp | 2 +- cvk/incl/cvk/render/cmd/cmd_buffer.hpp | 1 + cvk/incl/cvk/render/sync/barrier.hpp | 127 ++++++-------- cvk/incl/cvk/surface/swapchain.hpp | 12 +- .../cvk/utility/handle/instance_handle.hpp | 5 +- cvk/incl/cvk/utility/vk_error_code.hpp | 2 +- cvk/src/render/sync/barrier.cpp | 158 ++++++++---------- cvk/tests/src/render/sync/barrier_test.cpp | 46 +++-- jvk/incl/jvk/base/core.hpp | 31 +++- jvk/incl/jvk/base/queue.hpp | 12 +- jvk/incl/jvk/base/queues.hpp | 61 ------- jvk/incl/jvk/cmd/cmd_buffer.hpp | 23 +-- jvk/incl/jvk/data/buffer.hpp | 2 +- jvk/incl/jvk/data/image.hpp | 2 +- jvk/incl/jvk/data/resource_heap.hpp | 62 +++++-- jvk/incl/jvk/data/sampler_heap.hpp | 16 +- jvk/incl/jvk/graph/presenter.hpp | 18 +- jvk/incl/jvk/graph/stage.hpp | 9 +- jvk/incl/jvk/graph/stage_graph.hpp | 30 ++-- jvk/incl/jvk/graph/stage_graph_config.hpp | 1 - jvk/incl/jvk/sync/family_transfer.hpp | 43 +++-- ...source_states.hpp => resource_tracker.hpp} | 30 +++- jvk/incl/jvk/sync/semaphore.hpp | 21 ++- jvk/incl/jvk/sync/timeline_reactor.hpp | 13 +- jvk/src/base/core.cpp | 57 +++++-- jvk/src/base/queues.cpp | 49 ------ jvk/src/cmd/cmd_buffer.cpp | 2 +- jvk/src/data/resource_heap.cpp | 29 +++- jvk/src/data/sampler_heap.cpp | 9 +- jvk/src/graph/presenter.cpp | 24 +-- jvk/src/graph/stage_graph.cpp | 18 +- ...source_states.cpp => resource_tracker.cpp} | 54 +++--- jvk/src/sync/semaphore.cpp | 2 +- jvk/src/sync/timeline_reactor.cpp | 10 +- jvk/tests/src/base/queue_test.cpp | 84 ++++++---- jvk/tests/src/base/queues_test.cpp | 23 --- jvk/tests/src/data/heap_test.cpp | 81 +++++++++ ...tes_test.cpp => resource_tracker_test.cpp} | 74 ++++---- jvk/tests/src/sync/semaphore_test.cpp | 2 +- jvk/tests/src/sync/timeline_reactor_test.cpp | 26 +++ timgui/tests/src/imgui_test.cpp | 2 +- 44 files changed, 688 insertions(+), 602 deletions(-) delete mode 100644 jvk/incl/jvk/base/queues.hpp rename jvk/incl/jvk/sync/{resource_states.hpp => resource_tracker.hpp} (90%) delete mode 100644 jvk/src/base/queues.cpp rename jvk/src/sync/{resource_states.cpp => resource_tracker.cpp} (87%) delete mode 100644 jvk/tests/src/base/queues_test.cpp rename jvk/tests/src/sync/{resource_states_test.cpp => resource_tracker_test.cpp} (88%) diff --git a/cgfw/incl/cgfw/window/window.hpp b/cgfw/incl/cgfw/window/window.hpp index 7c1ae32c..8fd210b9 100644 --- a/cgfw/incl/cgfw/window/window.hpp +++ b/cgfw/incl/cgfw/window/window.hpp @@ -216,9 +216,8 @@ class Window { /** * closes the window and frees it * @details the last window of RGFW deinitializes RGFW - * @pre the window is not `nullptr` */ - static void destroy(RGFW_window*); + static void destroy(RGFW_window&); [[nodiscard]] constexpr bool created() const { return static_cast(_handle); } [[nodiscard]] constexpr handle_t get() const { return _handle.get(); } @@ -248,7 +247,7 @@ class Window { namespace cgfw { struct Window::State { - //TODO review stays a not_null pointer: the raw handle of RGFW, like vk_not_null for Vulkan handles + // stays a not_null pointer: the raw handle of RGFW, like vk_not_null for Vulkan handles cth::not_null_ptr rgfwWindow; }; } diff --git a/cgfw/src/window/window.cpp b/cgfw/src/window/window.cpp index cce2602a..518a342c 100644 --- a/cgfw/src/window/window.cpp +++ b/cgfw/src/window/window.cpp @@ -45,7 +45,9 @@ namespace { } } -void dev::window_deleter::operator()(RGFW_window* rgfwWindow) const { Window::destroy(rgfwWindow); } +void dev::window_deleter::operator()(RGFW_window* rgfwWindow) const { + Window::destroy(*rgfwWindow); +} Window::Window(Config config) : _config{std::move(config)} {} @@ -179,10 +181,8 @@ native_window Window::nativeWindow() const { #endif } -void Window::destroy(RGFW_window* rgfwWindow) { - CTH_CRITICAL(rgfwWindow == nullptr, "rgfwWindow must not be nullptr") {} - - RGFW_window_close(rgfwWindow); +void Window::destroy(RGFW_window& rgfwWindow) { + RGFW_window_close(&rgfwWindow); deinit_without_windows(); } diff --git a/cvk/incl/cvk/data/buffer/buffer_config.hpp b/cvk/incl/cvk/data/buffer/buffer_config.hpp index 764464c7..320478f2 100644 --- a/cvk/incl/cvk/data/buffer/buffer_config.hpp +++ b/cvk/incl/cvk/data/buffer/buffer_config.hpp @@ -32,7 +32,7 @@ struct BufferConfig { /** memory of the buffer, `VMA_MEMORY_USAGE_AUTO` picks the memory type from `usage` */ MemoryConfig memory{}; - //TODO review one place for the rule: the create info and the jvk tracking read it + // one place for the rule: the create info and the jvk tracking read it /** * @return `VK_SHARING_MODE_CONCURRENT` for two or more `queueFamilies`, else `VK_SHARING_MODE_EXCLUSIVE` */ diff --git a/cvk/incl/cvk/data/img/image_config.hpp b/cvk/incl/cvk/data/img/image_config.hpp index 8c63a347..9d3b5a6a 100644 --- a/cvk/incl/cvk/data/img/image_config.hpp +++ b/cvk/incl/cvk/data/img/image_config.hpp @@ -96,7 +96,7 @@ struct ImageConfig { }; } - //TODO review one place for the rule: the create info and the jvk tracking read it + // one place for the rule: the create info and the jvk tracking read it /** * @return `VK_SHARING_MODE_CONCURRENT` for two or more `queueFamilies`, else `VK_SHARING_MODE_EXCLUSIVE` */ diff --git a/cvk/incl/cvk/render/cmd/cmd_buffer.hpp b/cvk/incl/cvk/render/cmd/cmd_buffer.hpp index e388a2aa..fd518743 100644 --- a/cvk/incl/cvk/render/cmd/cmd_buffer.hpp +++ b/cvk/incl/cvk/render/cmd/cmd_buffer.hpp @@ -537,6 +537,7 @@ class PrimaryCmdBuffer : public BaseCmdBuffer { */ void execute(std::span const> secondaries) const; + //TEMP until libstdc++ has std::span from a braced list (P2447) /** * records the secondary command buffers of a braced list */ diff --git a/cvk/incl/cvk/render/sync/barrier.hpp b/cvk/incl/cvk/render/sync/barrier.hpp index 4176ec70..9666b45d 100644 --- a/cvk/incl/cvk/render/sync/barrier.hpp +++ b/cvk/incl/cvk/render/sync/barrier.hpp @@ -23,11 +23,6 @@ class Image; struct BarrierScope { VkPipelineStageFlags2 stages = VK_PIPELINE_STAGE_2_NONE; VkAccessFlags2 access = VK_ACCESS_2_NONE; - - /** - * `VK_QUEUE_FAMILY_IGNORED` -> no queue family ownership transfer - */ - queue_family_index_t queueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; }; /** @@ -37,6 +32,10 @@ struct ImageBarrierInfo { BarrierScope src{}; BarrierScope dst{}; + /** `== dstQueueFamilyIndex` -> no queue family ownership transfer */ + queue_family_index_t srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + queue_family_index_t dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + VkImageLayout newLayout = VK_IMAGE_LAYOUT_UNDEFINED; ///< `== oldLayout` -> no layout transition /** @@ -74,16 +73,6 @@ struct ImageBarrierInfo { .mipLevels = mipLevels, }; } - - /** - * queue family ownership transfer without layout transition, `dst` and `src` name the families - * @param layout of the image - */ - [[nodiscard]] static constexpr ImageBarrierInfo QueueTransition( - VkImageLayout layout, - BarrierScope const& dst, - BarrierScope const& src - ) { return ImageBarrierInfo{.src = src, .dst = dst, .newLayout = layout, .oldLayout = layout}; } }; /** @@ -93,36 +82,22 @@ struct BufferBarrierInfo { BarrierScope src{}; BarrierScope dst{}; + /** `== dstQueueFamilyIndex` -> no queue family ownership transfer */ + queue_family_index_t srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + queue_family_index_t dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + size_t offset = 0; ///< in bytes size_t size = VK_WHOLE_SIZE; ///< in bytes (`VK_WHOLE_SIZE` => to the end) - - /** - * queue family ownership transfer, `dst` and `src` name the families - */ - [[nodiscard]] static constexpr BufferBarrierInfo QueueTransition( - BarrierScope const& dst, - BarrierScope const& src - ) { return BufferBarrierInfo{.src = src, .dst = dst}; } -}; - -/** - * global memory part of a barrier - */ -struct MemoryBarrierInfo { - BarrierScope src{}; - BarrierScope dst{}; }; -//TODO review the memory barriers stay infos: they refer to no object, the family check stays in execute() /** * pipeline barrier * @details * - memory, buffer and image barriers in one `vkCmdPipelineBarrier2()` - * - the buffer and image barriers are the vulkan structs: they keep no reference to the objects + * - the barriers are the vulkan structs: they keep no reference to the objects */ struct Barrier { - using MemoryInfo = MemoryBarrierInfo; using ImageInfo = ImageBarrierInfo; using BufferInfo = BufferBarrierInfo; @@ -134,7 +109,7 @@ struct Barrier { /** `VK_DEPENDENCY_BY_REGION_BIT` -> the dependency is per framebuffer region */ VkDependencyFlags flags = 0; - std::vector memory{}; + std::vector memory{}; std::vector buffers{}; std::vector images{}; @@ -142,9 +117,32 @@ struct Barrier { * adds a global memory barrier */ constexpr void add(BarrierScope const& dst, BarrierScope const& src) { - memory.push_back({.src = src, .dst = dst}); + memory.push_back( + VkMemoryBarrier2{ + .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, + .pNext = nullptr, + .srcStageMask = src.stages, + .srcAccessMask = src.access, + .dstStageMask = dst.stages, + .dstAccessMask = dst.access, + } + ); } + /** + * adds a buffer barrier + * @pre the buffer is created + * @pre the range lies in the buffer + */ + void add(BaseBuffer const&, BufferInfo const&); + + // the handle overloads: the add() of the objects calls them, the jvk tracking has no objects + /** + * adds a buffer barrier of the buffer handle + * @details no check of the buffer: the caller knows its size + */ + constexpr void add(VkBuffer, BufferInfo const&); + /** * adds an image barrier * @pre the image is created @@ -153,7 +151,6 @@ struct Barrier { */ void add(Image const&, ImageInfo const&); - //TODO review the handle overloads: the add() of the objects calls them, the jvk tracking has no objects /** * adds an image barrier of the image handle * @details @@ -179,24 +176,10 @@ struct Barrier { uint32_t mipLevels = VK_REMAINING_MIP_LEVELS ); - /** - * adds a buffer barrier - * @pre the buffer is created - * @pre the range lies in the buffer - */ - void add(BaseBuffer const&, BufferInfo const&); - - /** - * adds a buffer barrier of the buffer handle - * @details no check of the buffer: the caller knows its size - */ - constexpr void add(VkBuffer, BufferInfo const&); - /** * records the barriers * @pre `BaseCmdBuffer::recording()` * @pre the images and buffers are not destroyed - * @pre memory barriers have no queue family ownership transfer * @pre `BaseCmdBuffer::insideRendering()` -> framebuffer space stages and `VK_DEPENDENCY_BY_REGION_BIT` * @pre `BaseCmdBuffer::insideRendering()` -> no layout transition and no queue family ownership transfer * @pre `BaseCmdBuffer::insideRendering()` with multiview -> `VK_DEPENDENCY_VIEW_LOCAL_BIT` @@ -234,11 +217,29 @@ struct Barrier { } namespace cvk { +constexpr void Barrier::add(VkBuffer vkBuffer, BufferInfo const& info) { + buffers.push_back( + VkBufferMemoryBarrier2{ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER_2, + .pNext = nullptr, + .srcStageMask = info.src.stages, + .srcAccessMask = info.src.access, + .dstStageMask = info.dst.stages, + .dstAccessMask = info.dst.access, + .srcQueueFamilyIndex = info.srcQueueFamilyIndex, + .dstQueueFamilyIndex = info.dstQueueFamilyIndex, + .buffer = vkBuffer, + .offset = info.offset, + .size = info.size, + } + ); +} + constexpr void Barrier::add(VkImage vkImage, VkImageAspectFlags aspectMask, ImageInfo const& info) { CTH_CRITICAL(info.mipLevels == 0, "mip levels must not be 0") {} CTH_CRITICAL(info.arrayLayers == 0, "array layers must not be 0") {} - bool const transfer = info.src.queueFamilyIndex != info.dst.queueFamilyIndex; + bool const transfer = info.srcQueueFamilyIndex != info.dstQueueFamilyIndex; CTH_CRITICAL( (info.oldLayout != info.newLayout || transfer) && (info.newLayout == VK_IMAGE_LAYOUT_UNDEFINED @@ -258,8 +259,8 @@ constexpr void Barrier::add(VkImage vkImage, VkImageAspectFlags aspectMask, Imag .dstAccessMask = info.dst.access, .oldLayout = info.oldLayout, .newLayout = info.newLayout, - .srcQueueFamilyIndex = info.src.queueFamilyIndex, - .dstQueueFamilyIndex = info.dst.queueFamilyIndex, + .srcQueueFamilyIndex = info.srcQueueFamilyIndex, + .dstQueueFamilyIndex = info.dstQueueFamilyIndex, .image = vkImage, .subresourceRange = { .aspectMask = info.aspectMask != 0 ? info.aspectMask : aspectMask, @@ -271,24 +272,6 @@ constexpr void Barrier::add(VkImage vkImage, VkImageAspectFlags aspectMask, Imag } ); } - -constexpr void Barrier::add(VkBuffer vkBuffer, BufferInfo const& info) { - buffers.push_back( - VkBufferMemoryBarrier2{ - .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER_2, - .pNext = nullptr, - .srcStageMask = info.src.stages, - .srcAccessMask = info.src.access, - .dstStageMask = info.dst.stages, - .dstAccessMask = info.dst.access, - .srcQueueFamilyIndex = info.src.queueFamilyIndex, - .dstQueueFamilyIndex = info.dst.queueFamilyIndex, - .buffer = vkBuffer, - .offset = info.offset, - .size = info.size, - } - ); -} } namespace cvk { diff --git a/cvk/incl/cvk/surface/swapchain.hpp b/cvk/incl/cvk/surface/swapchain.hpp index 4deb6c9e..960de5b1 100644 --- a/cvk/incl/cvk/surface/swapchain.hpp +++ b/cvk/incl/cvk/surface/swapchain.hpp @@ -269,9 +269,9 @@ class Swapchain { * image of the swapchain, the swapchain destroys it * @details the destruction releases the image, it does not destroy it */ - struct OwnedImage { - explicit OwnedImage(Image image) : image{std::move(image)} {} - ~OwnedImage() { + struct ReleasingImage { + explicit ReleasingImage(Image image) : image{std::move(image)} {} + ~ReleasingImage() { if(image.created()) static_cast(image.release()); } @@ -279,8 +279,8 @@ class Swapchain { Image image; // the user-declared destructor suppresses the implicit moves - OwnedImage(OwnedImage&& other) noexcept = default; - OwnedImage& operator=(OwnedImage&& other) noexcept = default; + ReleasingImage(ReleasingImage&& other) noexcept = default; + ReleasingImage& operator=(ReleasingImage&& other) noexcept = default; }; /** @@ -324,7 +324,7 @@ class Swapchain { std::vector _presentFences{}; std::vector _presentSemaphores{}; std::vector _views{}; - std::vector _images{}; + std::vector _images{}; std::vector _acquired{}; core_handle _handle; diff --git a/cvk/incl/cvk/utility/handle/instance_handle.hpp b/cvk/incl/cvk/utility/handle/instance_handle.hpp index 6fcfedc5..91b56f13 100644 --- a/cvk/incl/cvk/utility/handle/instance_handle.hpp +++ b/cvk/incl/cvk/utility/handle/instance_handle.hpp @@ -18,8 +18,9 @@ namespace cvk { */ class instance_deleter { public: - //TODO review a nullptr constructor, no default constructor: the base constructor of the owner has no created - // instance, the context comes with the handle; a reset() without context still does not compile + // a nullptr constructor, no default constructor: the base constructor of the owner has no + // created instance, the context comes with the handle; a reset() without context still does + // not compile /** * without context, for an owner without a handle */ diff --git a/cvk/incl/cvk/utility/vk_error_code.hpp b/cvk/incl/cvk/utility/vk_error_code.hpp index 3e262ea0..9968a2bc 100644 --- a/cvk/incl/cvk/utility/vk_error_code.hpp +++ b/cvk/incl/cvk/utility/vk_error_code.hpp @@ -5,7 +5,7 @@ namespace cvk { -//TODO review own header next to vk_exceptions.hpp: error codes are no exceptions +// own header next to vk_exceptions.hpp: error codes are no exceptions // no std::is_error_code_enum: VkResult lives in the global namespace, the implicit // conversion finds make_error_code() only through ADL there, a global make_error_code() would be needed /** diff --git a/cvk/src/render/sync/barrier.cpp b/cvk/src/render/sync/barrier.cpp index 5169a9de..a77b6f71 100644 --- a/cvk/src/render/sync/barrier.cpp +++ b/cvk/src/render/sync/barrier.cpp @@ -24,21 +24,20 @@ namespace { VkPipelineStageFlags2 srcStages, VkPipelineStageFlags2 dstStages ) { return ((srcStages | dstStages) & ~FRAMEBUFFER_STAGES) == 0; } +} - VkMemoryBarrier2 memory_barrier(MemoryBarrierInfo const& info) { - bool const transfer = info.src.queueFamilyIndex != VK_QUEUE_FAMILY_IGNORED - || info.dst.queueFamilyIndex != VK_QUEUE_FAMILY_IGNORED; - CTH_CRITICAL(transfer, "memory barriers have no queue family ownership transfer") {} - - return VkMemoryBarrier2{ - .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, - .pNext = nullptr, - .srcStageMask = info.src.stages, - .srcAccessMask = info.src.access, - .dstStageMask = info.dst.stages, - .dstAccessMask = info.dst.access, - }; - } +void Barrier::add(BaseBuffer const& buffer, BufferInfo const& info) { + BaseBuffer::debug_check(buffer); + CTH_CRITICAL( + info.offset > buffer.size() + || (info.size != VK_WHOLE_SIZE && info.size > buffer.size() - info.offset), + "range must lie in the buffer ({}), got {} from {}", + buffer.size(), + info.size, + info.offset + ) {} + + add(buffer.get(), info); } void Barrier::add(Image const& image, ImageInfo const& info) { @@ -75,18 +74,65 @@ void Barrier::add(Image const& image, ImageInfo const& info) { add(image.get(), image.aspectMask(), info); } -void Barrier::add(BaseBuffer const& buffer, BufferInfo const& info) { - BaseBuffer::debug_check(buffer); +void Barrier::addTransition( + Image const& image, + VkImageLayout newLayout, + VkImageLayout oldLayout, + VkPipelineStageFlags2 shaderStages, + uint32_t firstMipLevel, + uint32_t mipLevels +) { + auto const transition = layout_transition( + newLayout, + oldLayout, + image.aspectMask(), + shaderStages + ); CTH_CRITICAL( - info.offset > buffer.size() - || (info.size != VK_WHOLE_SIZE && info.size > buffer.size() - info.offset), - "range must lie in the buffer ({}), got {} from {}", - buffer.size(), - info.size, - info.offset + !transition.has_value(), + "layout transition {} -> {} has no scope for a layout, use add() with scopes", + oldLayout, + newLayout ) {} - add(buffer.get(), info); + add( + image, + ImageInfo::LayoutTransition( + newLayout, + oldLayout, + transition->dst, + transition->src, + firstMipLevel, + mipLevels + ) + ); +} + +void Barrier::execute(BaseCmdBuffer const& cmdBuffer) const { + BaseCmdBuffer::debug_check(cmdBuffer); + CTH_CRITICAL(!cmdBuffer.recording(), "command buffer must be recording") {} + + if(cmdBuffer.insideRendering()) + debug_check_rendering( + cmdBuffer.rendering(), + cmdBuffer.renderingViewMask(), + memory, + buffers, + images + ); + + VkDependencyInfo const dependency{ + .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, + .pNext = nullptr, + .dependencyFlags = flags, + .memoryBarrierCount = static_cast(memory.size()), + .pMemoryBarriers = memory.data(), + .bufferMemoryBarrierCount = static_cast(buffers.size()), + .pBufferMemoryBarriers = buffers.data(), + .imageMemoryBarrierCount = static_cast(images.size()), + .pImageMemoryBarriers = images.data(), + }; + cmdBuffer.core().functions()->vkCmdPipelineBarrier2(cmdBuffer.get(), &dependency); } void Barrier::debug_check_rendering( @@ -162,70 +208,4 @@ void Barrier::debug_check_rendering( ) {} } } - -void Barrier::addTransition( - Image const& image, - VkImageLayout newLayout, - VkImageLayout oldLayout, - VkPipelineStageFlags2 shaderStages, - uint32_t firstMipLevel, - uint32_t mipLevels -) { - auto const transition = layout_transition( - newLayout, - oldLayout, - image.aspectMask(), - shaderStages - ); - CTH_CRITICAL( - !transition.has_value(), - "layout transition {} -> {} has no scope for a layout, use add() with scopes", - oldLayout, - newLayout - ) {} - - add( - image, - ImageInfo::LayoutTransition( - newLayout, - oldLayout, - transition->dst, - transition->src, - firstMipLevel, - mipLevels - ) - ); -} - -void Barrier::execute(BaseCmdBuffer const& cmdBuffer) const { - BaseCmdBuffer::debug_check(cmdBuffer); - CTH_CRITICAL(!cmdBuffer.recording(), "command buffer must be recording") {} - - std::vector memoryBarriers{}; - memoryBarriers.reserve(memory.size()); - for(auto const& info : memory) - memoryBarriers.push_back(memory_barrier(info)); - - if(cmdBuffer.insideRendering()) - debug_check_rendering( - cmdBuffer.rendering(), - cmdBuffer.renderingViewMask(), - memoryBarriers, - buffers, - images - ); - - VkDependencyInfo const dependency{ - .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, - .pNext = nullptr, - .dependencyFlags = flags, - .memoryBarrierCount = static_cast(memoryBarriers.size()), - .pMemoryBarriers = memoryBarriers.data(), - .bufferMemoryBarrierCount = static_cast(buffers.size()), - .pBufferMemoryBarriers = buffers.data(), - .imageMemoryBarrierCount = static_cast(images.size()), - .pImageMemoryBarriers = images.data(), - }; - cmdBuffer.core().functions()->vkCmdPipelineBarrier2(cmdBuffer.get(), &dependency); -} } diff --git a/cvk/tests/src/render/sync/barrier_test.cpp b/cvk/tests/src/render/sync/barrier_test.cpp index 1b20054d..1fbbbcec 100644 --- a/cvk/tests/src/render/sync/barrier_test.cpp +++ b/cvk/tests/src/render/sync/barrier_test.cpp @@ -179,17 +179,30 @@ CVK_TEST(Barrier, layout_transition_info_covers_the_remaining_mip_levels) { static_assert(info.src.access == VK_ACCESS_2_NONE); } -CVK_TEST(Barrier, queue_transition_info_keeps_the_layout) { - constexpr auto info = ImageBarrierInfo::QueueTransition( - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - {.queueFamilyIndex = 1}, - {.queueFamilyIndex = 0} +CVK_TEST(Barrier, the_queue_families_reach_the_vulkan_structs) { + static_assert( + [] { + Barrier barrier{}; + barrier.add( + VkBuffer{VK_NULL_HANDLE}, + BufferBarrierInfo{.srcQueueFamilyIndex = 0, .dstQueueFamilyIndex = 1} + ); + barrier.add( + VkImage{VK_NULL_HANDLE}, + VK_IMAGE_ASPECT_COLOR_BIT, + ImageBarrierInfo{ + .srcQueueFamilyIndex = 0, + .dstQueueFamilyIndex = 1, + .newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + .oldLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + } + ); + auto const& buffer = barrier.buffers.front(); + auto const& image = barrier.images.front(); + return buffer.srcQueueFamilyIndex == 0 && buffer.dstQueueFamilyIndex == 1 + && image.srcQueueFamilyIndex == 0 && image.dstQueueFamilyIndex == 1; + }() ); - - static_assert(info.newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - static_assert(info.oldLayout == info.newLayout); - static_assert(info.dst.queueFamilyIndex == 1); - static_assert(info.src.queueFamilyIndex == 0); } CVK_TEST(Barrier, memory_barriers_are_constexpr) { @@ -198,7 +211,7 @@ CVK_TEST(Barrier, memory_barriers_are_constexpr) { Barrier barrier{VK_DEPENDENCY_BY_REGION_BIT}; barrier.add(FRAGMENT_READ, TRANSFER_WRITE); bool const added = !barrier.empty(); - bool const ordered = barrier.memory.front().dst.access == FRAGMENT_READ.access; + bool const ordered = barrier.memory.front().dstAccessMask == FRAGMENT_READ.access; barrier.clear(); return added && ordered && barrier.empty(); }() @@ -211,7 +224,16 @@ CVK_TEST(Barrier, aggregate_is_constexpr) { //TEMP not const: gcc 16 rejects a const aggregate with a vector and another member in a constant expression Barrier barrier{ .flags = VK_DEPENDENCY_BY_REGION_BIT, - .memory = {{TRANSFER_WRITE, FRAGMENT_READ}}, + .memory = { + VkMemoryBarrier2{ + .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, + .pNext = nullptr, + .srcStageMask = TRANSFER_WRITE.stages, + .srcAccessMask = TRANSFER_WRITE.access, + .dstStageMask = FRAGMENT_READ.stages, + .dstAccessMask = FRAGMENT_READ.access, + } + }, }; return !barrier.empty() && barrier.memory.size() == 1 && barrier.buffers.empty(); }() diff --git a/jvk/incl/jvk/base/core.hpp b/jvk/incl/jvk/base/core.hpp index 3b9a70cc..fe718069 100644 --- a/jvk/incl/jvk/base/core.hpp +++ b/jvk/incl/jvk/base/core.hpp @@ -1,6 +1,6 @@ #pragma once #include "core_config.hpp" -#include "queues.hpp" +#include "queue.hpp" #include "jvk/data/resource_heap.hpp" #include "jvk/data/sampler_heap.hpp" @@ -18,6 +18,7 @@ #include #include #include +#include namespace cvk { @@ -40,7 +41,7 @@ class Core { */ Core(cvk::Instance const&, Config); - //TODO review no default for the surfaces, like cvk::Core::create(): a core without windows passes {} + // no default for the surfaces, like cvk::Core::create(): a core without windows passes {} /** * constructs and creates * @details calls @ref Core(cvk::Instance const&, Config), `create()` @@ -160,18 +161,34 @@ class Core { [[nodiscard]] constexpr Config const& config() const { return _config; } private: + /** + * constructs the driver threads and one queue per vulkan queue + * @pre the cvk core and the reactor are created + * @throws cvk::vk_result_exception result of `vkCreateSemaphore()` for the release counters + */ + void createQueues(); + + /** + * destroys the queues, then the driver threads that run their strands + */ + void destroyQueues(); + Config _config; cvk::Core _core; cth::co::scheduler _workers; // destroyed after the queues, before the workers and the cvk core: it posts to the workers TimelineReactor _reactor; - //TODO review stays a std::optional: Queues owns no vulkan object, the device owns the queues, its construction - // needs the created cvk core and starts the driver threads + + // destroyed after the queues: their strands run on it + std::optional _driverSchedulerOpt{}; ///< see `CoreConfig::driverThreads` // destroyed before the reactor, the workers and the cvk core - std::optional _queuesOpt{}; - //TODO review std::optional like the queues: the heaps need the created cvk core, no heap without counts + std::vector _queues{}; ///< one per vulkan queue + /** index in `_queues` per index of `cvk::CoreConfig::queueProperties` */ + std::vector _queueIndices{}; + // destroyed before the cvk core - std::optional _resourceHeapOpt{}; + ResourceHeap _resourceHeap; ///< not created without counts, see `HeapsConfig` + // the sampler heap needs the created cvk core, no heap without counts std::optional _samplerHeapOpt{}; public: diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index 430d3da7..5be53a4e 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -52,12 +52,12 @@ class Queue { */ void waitIdle() const; - //TODO review an executor_task: the receiving submit job awaits it before its own submit, so the release is + // an executor_task: the receiving submit job awaits it before its own submit, so the release is // submitted first and the counter only changes in the strand (returning at once needs a lock around the value // and the post) - // const like executor(): Queues hands out Queue const&, the release members are mutable - //TODO review returns the jvk SemaphoreSubmitInfo: it keeps the counter for Semaphore::submitted(), it converts to - // the cvk one + // const like executor(): the core hands out Queue const&, the release members are mutable + // returns the jvk SemaphoreSubmitInfo: it keeps the counter for Semaphore::submitted(), it + // converts to the cvk one /** * releases the queue family ownership of the resources in the strand * @details @@ -129,8 +129,8 @@ class Queue { public: Queue(Queue const& other) = delete; - Queue(Queue&& other) = delete; + Queue(Queue&& other) noexcept = default; Queue& operator=(Queue const& other) = delete; - Queue& operator=(Queue&& other) = delete; + Queue& operator=(Queue&& other) noexcept = default; }; } diff --git a/jvk/incl/jvk/base/queues.hpp b/jvk/incl/jvk/base/queues.hpp deleted file mode 100644 index 024204a7..00000000 --- a/jvk/incl/jvk/base/queues.hpp +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once -#include "queue.hpp" - -#include - -#include -#include -#include -#include - - -namespace cvk { -class Core; -} - -namespace jvk { -class Core; -} - -namespace jvk { -/** - * serialized queues of a core - * @details - * - their strands run on the workers of the core or on the driver threads, see `CoreConfig::driverThreads` - * - the indices of one vulkan queue share one `Queue` - * - a `Queue` keeps its address - */ -class Queues { -public: - //TODO review the scheduler as a parameter like in TimelineReactor, no accessor of the workers on Core - /** - * constructs the queues of the core and the driver threads - * @param workers run the strands for `driverThreads` `0`, the core passes its workers - * @param driverThreads see `CoreConfig::driverThreads` - * @pre the cvk core and the reactor of the core are created - * @throws cvk::vk_result_exception result of `vkCreateSemaphore()` for the release counters - */ - Queues(Core const&, cth::co::scheduler const& workers, size_t driverThreads); - - /** - * @param queueIdx index of the queue in `cvk::CoreConfig::queueProperties` - * @return serialized queue, the indices of one vulkan queue return the same object - * @pre `queueIdx` < size of `cvk::Core::queueIndices()` - */ - [[nodiscard]] Queue const& queue(size_t queueIdx) const; - -private: - // before the queues: destroyed after the strands that run on it - std::optional _driverSchedulerOpt{}; ///< the driver threads - std::deque _queues{}; - - /** index in `_queues` per index of `cvk::CoreConfig::queueProperties` */ - std::vector _queueIndices{}; - -public: - Queues(Queues const& other) = delete; - Queues(Queues&& other) = delete; - Queues& operator=(Queues const& other) = delete; - Queues& operator=(Queues&& other) = delete; -}; -} diff --git a/jvk/incl/jvk/cmd/cmd_buffer.hpp b/jvk/incl/jvk/cmd/cmd_buffer.hpp index 2d3b8272..0c71f0d2 100644 --- a/jvk/incl/jvk/cmd/cmd_buffer.hpp +++ b/jvk/incl/jvk/cmd/cmd_buffer.hpp @@ -1,6 +1,6 @@ #pragma once #include "jvk/data/resource_heap.hpp" -#include "jvk/sync/resource_states.hpp" +#include "jvk/sync/resource_tracker.hpp" #include "cvk/base/queue/queue_family.hpp" #include "cvk/data/buffer/buffer.hpp" @@ -123,10 +123,11 @@ class BasicCmdBuffer { * @details the resource states start empty * @pre `cvk::Core::created()` * @pre `State::vkPool` was created with the queue family of the object and `POOL_FLAGS` - * @pre `State::vkBuffer` is the only command buffer of `State::vkPool`, with the level of `Cvk` + * @pre `State::vkPool` allocated `State::vkBuffer` with the level of `Cvk` * @pre the command buffer is not recording * @post `created()` * @note calls `optDestroy()` + * @note takes the whole pool: `reset()` and `destroy()` act on every command buffer of the pool */ void wrap(State const&); @@ -239,7 +240,7 @@ class BasicCmdBuffer { /** * sets the tracked state of the mip levels after untracked code * @pre `recording()` - * @see `ResourceStates::assume()` + * @see `ResourceTracker::assume()` */ void assume( cvk::Image const&, @@ -251,7 +252,7 @@ class BasicCmdBuffer { /** * sets the tracked state of the buffer after untracked code * @pre `recording()` - * @see `ResourceStates::assume()` + * @see `ResourceTracker::assume()` */ void assume(cvk::BaseBuffer const&, BufferState const& state); @@ -326,7 +327,7 @@ class BasicCmdBuffer { */ void dispatchIndirect(cvk::BaseBuffer const&, size_t offset = 0); - //TODO review the forwarders keep the constness of cvk + // the forwarders keep the constness of cvk /** * @see `cvk::BaseCmdBuffer::setAttachmentMapping()` */ @@ -402,9 +403,9 @@ class BasicCmdBuffer { _cmdBuffer.dispatch(groupCountX, groupCountY, groupCountZ); } - [[nodiscard]] constexpr ResourceStates const& states() const { return _states; } + [[nodiscard]] constexpr ResourceTracker const& states() const { return _states; } - //TODO review no level() forwarder: the type tells it + // no level() forwarder: the type tells it [[nodiscard]] constexpr bool created() const { return _cmdBuffer.created(); } [[nodiscard]] constexpr VkCommandBuffer get() const { return _cmdBuffer.get(); } [[nodiscard]] constexpr cvk::Core const& core() const { return _cmdBuffer.core(); } @@ -464,9 +465,9 @@ class BasicCmdBuffer { * @details records the barriers for its first accesses * @pre the preconditions of `cvk::Barrier::execute()` */ - void appendStates(ResourceStates const& next); + void appendStates(ResourceTracker const& next); - //TODO review protected member: begin() and execute() of the derived classes record into it + // protected member: begin() and execute() of the derived classes record into it // declared before the pool: the move assignment frees the old command buffer before the old pool Cvk _cmdBuffer; @@ -493,7 +494,7 @@ class BasicCmdBuffer { addAccesses(barrier, rest...); } - ResourceStates _states{}; + ResourceTracker _states{}; std::unique_ptr _poolPtr; @@ -581,7 +582,7 @@ class PrimaryCmdBuffer : public dev::BasicCmdBuffer { */ void execute(std::span const>); - //TODO review braced list overload like cvk: libstdc++ 16 has no std::span constructor from a braced list + //TEMP until libstdc++ has std::span from a braced list (P2447) /** * executes the secondaries of a braced list * @see @ref execute(std::span const>) diff --git a/jvk/incl/jvk/data/buffer.hpp b/jvk/incl/jvk/data/buffer.hpp index 3fc44bc3..ab330ca6 100644 --- a/jvk/incl/jvk/data/buffer.hpp +++ b/jvk/incl/jvk/data/buffer.hpp @@ -1,6 +1,6 @@ #pragma once #include "jvk/cmd/cmd_buffer.hpp" -#include "jvk/sync/resource_states.hpp" +#include "jvk/sync/resource_tracker.hpp" #include "cvk/data/buffer/buffer.hpp" #include "cvk/data/img/image.hpp" diff --git a/jvk/incl/jvk/data/image.hpp b/jvk/incl/jvk/data/image.hpp index 79331025..cf8a9871 100644 --- a/jvk/incl/jvk/data/image.hpp +++ b/jvk/incl/jvk/data/image.hpp @@ -1,6 +1,6 @@ #pragma once #include "jvk/cmd/cmd_buffer.hpp" -#include "jvk/sync/resource_states.hpp" +#include "jvk/sync/resource_tracker.hpp" #include "cvk/data/buffer/base_buffer.hpp" #include "cvk/data/img/image.hpp" diff --git a/jvk/incl/jvk/data/resource_heap.hpp b/jvk/incl/jvk/data/resource_heap.hpp index 4bec9e8a..3a369441 100644 --- a/jvk/incl/jvk/data/resource_heap.hpp +++ b/jvk/incl/jvk/data/resource_heap.hpp @@ -6,6 +6,7 @@ #include "cvk/data/descriptor/image_descriptor.hpp" #include "cvk/data/descriptor/resource_heap.hpp" #include "cvk/data/img/image.hpp" +#include "cvk/utility/constants.hpp" #include @@ -32,7 +33,7 @@ namespace jvk { * - the destructor of a handle returns its cell, `Stage::retain()` keeps it while the gpu uses it * - the shader convention: `mappings()` and `jvk/heaps.glsl` * - owns a `cvk::ResourceHeap`, `vk()` reads it - * - thread safe + * - `insert()` and the handles: thread safe */ class ResourceHeap { public: @@ -68,17 +69,46 @@ class ResourceHeap { using InputAttachment = ImageHandle; /** - * creates the cvk heap + * base constructor + */ + ResourceHeap(cvk::Core const&, Config const&); + + /** + * constructs and creates + * @details calls @ref ResourceHeap(cvk::Core const&, Config const&), `create()` + */ + explicit ResourceHeap(cvk::Core const&, Config const&, cvk::create_t); + + /** + * @note calls `optDestroy()` + */ + ~ResourceHeap() { optDestroy(); } + + /** + * creates the cvk heap, every cell is free * @pre `cvk::Core::created()` * @pre the preconditions of `cvk::ResourceHeap::create()` + * @post `created()` + * @note calls `optDestroy()` * @throws cvk::cvk_exception the exceptions of `cvk::ResourceHeap::create()` */ - ResourceHeap(cvk::Core const&, Config const&); + void create(); /** + * destroys the cvk heap and forgets the cells + * @pre `created()` * @pre no handle and no cell in a stasis of the heap is left + * @pre the gpu does not use the heap */ - ~ResourceHeap(); + void destroy(); + + /** + * if `created()` -> calls `destroy()` + */ + void optDestroy() { + if(created()) + destroy(); + } /** * places the descriptor into a free cell of its type @@ -104,6 +134,7 @@ class ResourceHeap { /** * @return the mappings of the shader convention: the sampled images and the storage images + * @pre `created()` * @details set `constants::HEAP_SET` * @details bindings `constants::HEAP_SAMPLED_IMAGE_BINDING`, `constants::HEAP_STORAGE_IMAGE_BINDING` * @see `jvk/heaps.glsl`, `SamplerHeap::mappings()` @@ -130,9 +161,15 @@ class ResourceHeap { */ [[nodiscard]] constexpr cvk::ResourceHeap const& vk() const { return _vk; } + [[nodiscard]] constexpr bool created() const { return _vk.created(); } [[nodiscard]] constexpr Config const& config() const { return _vk.config(); } private: + /** + * frees every cell + */ + void forget(); + template Descriptor> [[nodiscard]] ImageHandle insertImage(Descriptor const&) const; @@ -144,22 +181,23 @@ class ResourceHeap { /** * @return the free list of the type - * @pre `_mutex` is locked + * @pre `_mutexPtr` is locked */ template Descriptor> [[nodiscard]] dev::free_list& freeList() const; - mutable std::mutex _mutex{}; - mutable cvk::ResourceHeap _vk; ///< written under `_mutex` - mutable dev::free_list _sampledImages; ///< under `_mutex` - mutable dev::free_list _storageImages; ///< under `_mutex` - mutable dev::free_list _inputAttachments; ///< under `_mutex` + // behind a std::unique_ptr: the mutex is not movable, the moves stay = default + std::unique_ptr _mutexPtr = std::make_unique(); + mutable cvk::ResourceHeap _vk; ///< written under `_mutexPtr` + mutable dev::free_list _sampledImages; ///< under `_mutexPtr` + mutable dev::free_list _storageImages; ///< under `_mutexPtr` + mutable dev::free_list _inputAttachments; ///< under `_mutexPtr` public: ResourceHeap(ResourceHeap const& other) = delete; - ResourceHeap(ResourceHeap&& other) = delete; + ResourceHeap(ResourceHeap&& other) noexcept = default; ResourceHeap& operator=(ResourceHeap const& other) = delete; - ResourceHeap& operator=(ResourceHeap&& other) = delete; + ResourceHeap& operator=(ResourceHeap&& other) noexcept = default; }; } diff --git a/jvk/incl/jvk/data/sampler_heap.hpp b/jvk/incl/jvk/data/sampler_heap.hpp index 6a707776..2c00c811 100644 --- a/jvk/incl/jvk/data/sampler_heap.hpp +++ b/jvk/incl/jvk/data/sampler_heap.hpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -96,17 +97,18 @@ class SamplerHeap { cvk::SamplerConfig config{}; }; - mutable std::mutex _mutex{}; - mutable cvk::SamplerHeap _vk; ///< written under `_mutex` - mutable dev::free_list _cells; ///< under `_mutex` - mutable cth::dt::flat_hash_map _indices{}; ///< under `_mutex` - mutable std::vector _slots; ///< one per cell, under `_mutex` + // behind a std::unique_ptr: the mutex is not movable, the moves stay = default + std::unique_ptr _mutexPtr = std::make_unique(); + mutable cvk::SamplerHeap _vk; ///< written under `_mutexPtr` + mutable dev::free_list _cells; ///< under `_mutexPtr` + mutable cth::dt::flat_hash_map _indices{}; ///< under `_mutexPtr` + mutable std::vector _slots; ///< one per cell, under `_mutexPtr` public: SamplerHeap(SamplerHeap const& other) = delete; - SamplerHeap(SamplerHeap&& other) = delete; + SamplerHeap(SamplerHeap&& other) noexcept = default; SamplerHeap& operator=(SamplerHeap const& other) = delete; - SamplerHeap& operator=(SamplerHeap&& other) = delete; + SamplerHeap& operator=(SamplerHeap&& other) noexcept = default; }; } diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/presenter.hpp index 04ff3d79..14ee0c28 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -1,7 +1,7 @@ #pragma once #include "jvk/cmd/cmd_buffer.hpp" #include "jvk/graph/swapchain.hpp" -#include "jvk/sync/resource_states.hpp" +#include "jvk/sync/resource_tracker.hpp" #include "jvk/sync/semaphore.hpp" #include "jvk/utility/first_error.hpp" @@ -239,9 +239,11 @@ class Presenter { uint64_t frameNumber; ///< `Stage::frameNumber()`, the value of `stageSemaphore` to wait for }; - //TODO review no submitted_awaiter parameter: the job takes it from the stage semaphore and the frame number - //TODO review the image as a parameter: the job reads no presenter state outside of the strand - //TODO review the submit mark of the present job before awaited: acquire() no longer orders the present jobs + // no submitted_awaiter parameter: the job takes it from the stage semaphore and the frame + // number + // the image as a parameter: the job reads no presenter state outside of the strand + // the submit mark of the present job before awaited: acquire() no longer orders the present + // jobs /** * present job of `present()` * @details the order: @@ -362,22 +364,17 @@ namespace jvk { */ class scoped_acquire { public: - //TODO review the uncaught exceptions as a parameter: acquire() reads them on the calling thread before it moves - // onto `Queue::scheduler()`, the scope is constructed there /** * @param presenter of the image * @param stage of the acquire * @param imageOpt `std::nullopt` -> no image * @param error the first error of the presenter, gets a failure at the end - * @param uncaughtExceptions of the calling thread at the start of `Presenter::acquire()`, tell the exception at - * the end */ scoped_acquire( Presenter& presenter, Stage& stage, std::optional imageOpt, - dev::first_error& error, - int uncaughtExceptions + dev::first_error& error ) noexcept; ~scoped_acquire(); @@ -417,7 +414,6 @@ class scoped_acquire { cth::ref_wrapper _stage; std::optional _imageOpt; cth::ref_wrapper _error; ///< the first error of the presenter - int _uncaughtExceptions; ///< of the calling thread at the start of `Presenter::acquire()` public: scoped_acquire(scoped_acquire const& other) = delete; diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index 4ab77787..0d7fd7d4 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -48,7 +48,8 @@ struct SubmitInfo { /** `StageSlot::prologue`, `StageSlot::primary` */ std::vector> cmdBuffers{}; - //TODO review no queueWaits: the submit job awaits the marks of every wait, its append follows the dependency order + // no queueWaits: the submit job awaits the marks of every wait, its append follows the + // dependency order /** * one per `StageConfig::waits`: `StageSlot::semaphore` of the waited stage slot * @details the waited stage slot: stage `StageWait::stageId`, `StageWait::frameOffset` frame slots before @@ -158,7 +159,7 @@ struct StageSlot { */ Semaphore semaphore; - //TODO review a member of the stage slot: it refers to StageSlot::semaphore, StageSlot::prologue, + // a member of the stage slot: it refers to StageSlot::semaphore, StageSlot::prologue, // StageSlot::primary and the semaphores of the waited stage slots, they live as long as the graph /** the waits and the signal of the next submit or skip, see `SubmitInfo::next()` */ SubmitInfo submitInfo; @@ -234,7 +235,7 @@ class Stage { */ [[nodiscard]] PrimaryCmdBuffer& primary() { return _stageSlot->primary; } - //TODO review std::optional instead of a default inheritance {}: an empty inheritance continues a rendering + // std::optional instead of a default inheritance {}: an empty inheritance continues a rendering /** * begins the secondary command buffer of the frame slot * @details inherits the heaps of the primary, see `StageSlot::heaps` @@ -287,7 +288,7 @@ class Stage { await(SemaphoreSubmitInfo{semaphore, stages, value}); } - //TODO review deleted: without it a jvk semaphore takes the binary overload through the private base of + // deleted: without it a jvk semaphore takes the binary overload through the private base of // cvk::TimelineSemaphore and fails with an inaccessible base error. no reason: MSVC lacks C++26 delete("...") /** * a jvk semaphore needs a value: `await(semaphore, stages, value)` diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index ceda20e1..1f9e5fa8 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -4,7 +4,7 @@ #include "stage_graph_config.hpp" #include "jvk/base/stasis.hpp" -#include "jvk/sync/resource_states.hpp" +#include "jvk/sync/resource_tracker.hpp" #include "jvk/utility/first_error.hpp" #include "cvk/base/queue/submit_info.hpp" @@ -74,16 +74,20 @@ class StageGraph { */ ~StageGraph(); - //TODO review awaits Stage::submitted() of the old frame: the gpu can finish before the graph job marks the submit + // awaits Stage::submitted() of the old frame: the gpu can finish before the graph job marks the + // submit /** * constructs the frame and its stages in the next slot * @details the frame before: skips its stages without `Stage::submit()` or `Stage::skip()`, warns for a waited one - * @details the old frame of the slot: awaits `Stage::submitted()` of its stages, then each stage: the gpu finished - * it + * @details the old frame of the slot: awaits `Stage::submitted()` of its stages, then the + * stages: the gpu finished them, both with `cth::co::all()` * @return the frame of the slot * @pre no stage of the frame before records or submits: `nextFrame()` ends the frame * @throws cvk::vk_result_exception the first error of a submit job or a scope, stored before the call: an error * during the waits -> the next `nextFrame()` rethrows it + * @throws cth::except::group_coro_exception reason: the wait for a stage of the old frame + * failed, after the waits for all its stages: `exceptions()` holds the + * `cth::except::coro_exception` per stage * @attention not thread safe */ [[nodiscard]] cth::co::executor_task nextFrame(); @@ -129,7 +133,7 @@ class StageGraph { * - the first use of the next submit starts from the state * - thread safe * @pre the jobs of the submits before that use the image appended their states: they are marked - * @see `ResourceStates::assume()` + * @see `ResourceTracker::assume()` */ void assume(cvk::Image const&, ImageState const& state); @@ -187,9 +191,10 @@ class StageGraph { */ void detachJob(Stage&, Stage::Status targetStatus); - //TODO review no marks as parameters: the job awaits Semaphore::submitted() of the slots, they live as long as - // the graph - //TODO review next() before the mark: the job of the next frame of the slot awaits the mark, it reads the values + // no marks as parameters: the job awaits Semaphore::submitted() of the slots, they live as + // long as the graph + // next() before the mark: the job of the next frame of the slot awaits the mark, it reads the + // values /** * submit job of `submit()` and `skip()` * @details the order: @@ -226,7 +231,8 @@ class StageGraph { * @details the first use of a mip level or a buffer after the last state: * - unknown image: from `VK_IMAGE_LAYOUT_UNDEFINED` * - unknown buffer: no barrier - * - the same queue family, or `VK_SHARING_MODE_CONCURRENT`: the barrier of `ResourceStates::append()` + * - the same queue family, or `VK_SHARING_MODE_CONCURRENT`: the barrier of + * `ResourceTracker::append()` * - another queue family, `EXCLUSIVE`, contents needed: release half for the last queue, acquire half * - another queue family, discard or `VK_IMAGE_LAYOUT_UNDEFINED`: from `VK_IMAGE_LAYOUT_UNDEFINED`, no transfer * - an `assume()` before the first use: no barrier @@ -236,13 +242,13 @@ class StageGraph { * @pre the caller holds `StageGraph::_statesMutex` */ void append( - ResourceStates const& recording, + ResourceTracker const& recording, Queue const& queue, cvk::Barrier& prologue, release_map_t& releases ); - //TODO review jvk waits: they join the jvk extra waits of the stage + // jvk waits: they join the jvk extra waits of the stage /** * releases the resources on their last queues * @param releases the release halves per last queue, from `append()` @@ -280,7 +286,7 @@ class StageGraph { */ std::mutex _statesMutex{}; - ResourceStates _states{}; ///< resource states after all submits + ResourceTracker _states{}; ///< resource states after all submits /** * last queue per mip level of an image, for the queue family ownership transfers diff --git a/jvk/incl/jvk/graph/stage_graph_config.hpp b/jvk/incl/jvk/graph/stage_graph_config.hpp index 2602e57c..4b880426 100644 --- a/jvk/incl/jvk/graph/stage_graph_config.hpp +++ b/jvk/incl/jvk/graph/stage_graph_config.hpp @@ -42,7 +42,6 @@ struct StageConfig { * config of a `StageGraph` */ struct StageGraphConfig { - //TODO review id = index instead of the hash map of the old sketch std::vector stages{}; ///< the stages, the id of a stage is its index /** diff --git a/jvk/incl/jvk/sync/family_transfer.hpp b/jvk/incl/jvk/sync/family_transfer.hpp index 1d828bb7..5c0befc1 100644 --- a/jvk/incl/jvk/sync/family_transfer.hpp +++ b/jvk/incl/jvk/sync/family_transfer.hpp @@ -1,5 +1,5 @@ #pragma once -#include "jvk/sync/resource_states.hpp" +#include "jvk/sync/resource_tracker.hpp" #include "cvk/base/queue/queue_family.hpp" #include "cvk/render/sync/barrier.hpp" @@ -10,15 +10,8 @@ namespace jvk::dev { -/** - * src of an acquire half: waits for the release wait of the submit, `VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT` - */ -[[nodiscard]] constexpr cvk::BarrierScope acquire_src(cvk::queue_family_index_t lastFamily) { - return cvk::BarrierScope{ - .stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, - .queueFamilyIndex = lastFamily - }; -} +/** src of an acquire half: waits for the release wait of the submit */ +constexpr cvk::BarrierScope ACQUIRE_SRC{.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}; /** * release half of the queue family ownership transfer of a mip level, transitions to the first layout @@ -36,8 +29,9 @@ namespace jvk::dev { uint32_t mipLevel ) { return cvk::ImageBarrierInfo{ - .src = {last.scope.stages, last.scope.access, lastFamily}, - .dst = {.queueFamilyIndex = family}, + .src = last.scope, + .srcQueueFamilyIndex = lastFamily, + .dstQueueFamilyIndex = family, .newLayout = first.layout, .oldLayout = last.layout, .firstMipLevel = mipLevel, @@ -61,8 +55,10 @@ namespace jvk::dev { uint32_t mipLevel ) { return cvk::ImageBarrierInfo{ - .src = acquire_src(lastFamily), - .dst = {first.scope.stages, first.scope.access, family}, + .src = ACQUIRE_SRC, + .dst = first.scope, + .srcQueueFamilyIndex = lastFamily, + .dstQueueFamilyIndex = family, .newLayout = first.layout, .oldLayout = last.layout, .firstMipLevel = mipLevel, @@ -81,10 +77,11 @@ namespace jvk::dev { cvk::queue_family_index_t lastFamily, cvk::queue_family_index_t family ) { - return cvk::BufferBarrierInfo::QueueTransition( - {.queueFamilyIndex = family}, - {last.scope.stages, last.scope.access, lastFamily} - ); + return cvk::BufferBarrierInfo{ + .src = last.scope, + .srcQueueFamilyIndex = lastFamily, + .dstQueueFamilyIndex = family, + }; } /** @@ -98,9 +95,11 @@ namespace jvk::dev { cvk::queue_family_index_t lastFamily, cvk::queue_family_index_t family ) { - return cvk::BufferBarrierInfo::QueueTransition( - {first.scope.stages, first.scope.access, family}, - acquire_src(lastFamily) - ); + return cvk::BufferBarrierInfo{ + .src = ACQUIRE_SRC, + .dst = first.scope, + .srcQueueFamilyIndex = lastFamily, + .dstQueueFamilyIndex = family, + }; } } diff --git a/jvk/incl/jvk/sync/resource_states.hpp b/jvk/incl/jvk/sync/resource_tracker.hpp similarity index 90% rename from jvk/incl/jvk/sync/resource_states.hpp rename to jvk/incl/jvk/sync/resource_tracker.hpp index ac9b04c6..6646c5af 100644 --- a/jvk/incl/jvk/sync/resource_states.hpp +++ b/jvk/incl/jvk/sync/resource_tracker.hpp @@ -9,7 +9,6 @@ #include #include #include -#include #include @@ -25,7 +24,7 @@ namespace jvk { struct ImageState { VkImageLayout layout; - cvk::BarrierScope scope; ///< `VK_QUEUE_FAMILY_IGNORED` -> the family of the recording + cvk::BarrierScope scope; ///< stages and access of the access }; /** @@ -54,7 +53,7 @@ struct ImageAccess { * state of a buffer after an access */ struct BufferState { - cvk::BarrierScope scope; ///< `VK_QUEUE_FAMILY_IGNORED` -> the family of the recording + cvk::BarrierScope scope; ///< stages and access of the access }; /** @@ -66,6 +65,16 @@ struct BufferAccess { VkAccessFlags2 access; }; +/** + * mip level of an image with a state in a `ResourceTracker` + */ +struct ImageMip { + VkImage vkImage; + uint32_t mipLevel; + VkImageAspectFlags aspectMask; ///< of the image + VkSharingMode sharingMode; ///< of the image +}; + /** * resource state tracker of one recording * @details @@ -75,7 +84,7 @@ struct BufferAccess { * @attention not thread safe * @attention call `erase()` before an image or buffer is destroyed: a new one can get its handle */ -class ResourceStates { +class ResourceTracker { public: /** * records the access of the mip levels @@ -129,7 +138,7 @@ class ResourceStates { * appends the states of a later recording * @param[out] barrier gets the barriers, record it before the commands of next */ - void append(ResourceStates const& next, cvk::Barrier& barrier); + void append(ResourceTracker const& next, cvk::Barrier& barrier); /** * @return `std::nullopt` -> no access or an `assume()` before it @@ -214,16 +223,19 @@ class ResourceStates { [[nodiscard]] bool empty() const { return _images.empty() && _buffers.empty(); } - //TODO review tuples, no new struct: the callers name the parts with a structured binding /** - * @return view of the mip levels with a state: `std::tuple` of the image, the mip level, the aspect mask and the - * sharing mode of the image + * @return view of the mip levels with a state */ [[nodiscard]] auto images() const { return _images | std::views::transform( [](auto const& entry) { auto const& [key, states] = entry; - return std::tuple{key.first, key.second, states.aspectMask, states.sharingMode}; + return ImageMip{ + .vkImage = key.first, + .mipLevel = key.second, + .aspectMask = states.aspectMask, + .sharingMode = states.sharingMode, + }; } ); } diff --git a/jvk/incl/jvk/sync/semaphore.hpp b/jvk/incl/jvk/sync/semaphore.hpp index c3da2594..bc547c5b 100644 --- a/jvk/incl/jvk/sync/semaphore.hpp +++ b/jvk/incl/jvk/sync/semaphore.hpp @@ -52,7 +52,7 @@ class semaphore_awaiter : public cth::co::this_coro_awaiter_base, void await_suspend(std::coroutine_handle caller); private: - //TODO review a private helper: the reactor needs the complete jvk::Core, the template stays in the header + // a private helper: the reactor needs the complete jvk::Core, the template stays in the header /** * registers the callback with the reactor of the core */ @@ -80,7 +80,7 @@ class submitted_awaiter : public cth::co::this_coro_awaiter_base { /** * registers the resume of the caller with the semaphore * @details resumes on the context of the caller - * @see `Semaphore::awaitSubmitted()` + * @see `Semaphore::onSubmitted()` */ template requires cth::co::this_coro_compatible void await_suspend(std::coroutine_handle caller); @@ -172,12 +172,11 @@ class Semaphore { */ State release(); - //TODO review @pre rising values, like the signal values of a timeline semaphore /** * marks the signal of the value as submitted * @details * - for the jvk submit paths, after the `vkQueueSubmit2()` of the signal - * - posts the callbacks of `awaitSubmitted()` up to the value to the workers of the core + * - posts the callbacks of `onSubmitted()` up to the value to the workers of the core * - thread safe * @pre `created()` * @pre `value > submittedValue()` @@ -197,17 +196,17 @@ class Semaphore { return submitted_awaiter{*this, value}; } - //TODO review like TimelineReactor::await(): marked -> posts the callback at once, no bool result /** * calls the callback on a worker of the core once `markSubmitted()` reached the value * @details + * - the callback form of `submitted()` * - the callback gets an empty `std::error_code` * - marked -> posts the callback at once * - thread safe * @pre `created()` * @see `submitted()` */ - void awaitSubmitted(uint64_t value, cth::co::context::await_func cb) const; + void onSubmitted(uint64_t value, cth::co::context::await_func cb) const; /** * waits until the semaphore reaches the value @@ -220,7 +219,7 @@ class Semaphore { return semaphore_awaiter{*this, value}; } - //TODO review the counter forwarded: next(), value(), gpuValue(); signal() not: a host signal bypasses + // the counter forwarded: next(), value(), gpuValue(); signal() not: a host signal bypasses // markSubmitted() /** * advances the counter @@ -256,7 +255,7 @@ class Semaphore { private: /** - * callback of `awaitSubmitted()` + * callback of `onSubmitted()` */ struct SubmittedWaiter { uint64_t value; @@ -271,7 +270,7 @@ class Semaphore { uint64_t value = 0; ///< see `submittedValue()` - /** the callbacks of `awaitSubmitted()` above `Submitted::value` */ + /** the callbacks of `onSubmitted()` above `Submitted::value` */ std::vector waiters{}; }; @@ -292,7 +291,7 @@ class Semaphore { } namespace jvk { -//TODO review in semaphore.hpp next to Semaphore: it is small, no own header +// in semaphore.hpp next to Semaphore: it is small, no own header /** * wait or signal of a submit on a jvk semaphore * @details @@ -343,7 +342,7 @@ void semaphore_awaiter::await_suspend(std::coroutine_handle caller) { template requires cth::co::this_coro_compatible void submitted_awaiter::await_suspend(std::coroutine_handle caller) { - _semaphore->awaitSubmitted( + _semaphore->onSubmitted( _value, dev::post_to(caller.promise().context(), [caller](std::error_code) { caller.resume(); }) ); diff --git a/jvk/incl/jvk/sync/timeline_reactor.hpp b/jvk/incl/jvk/sync/timeline_reactor.hpp index db293e0c..a0326809 100644 --- a/jvk/incl/jvk/sync/timeline_reactor.hpp +++ b/jvk/incl/jvk/sync/timeline_reactor.hpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -30,6 +31,7 @@ namespace jvk { * - posts the callbacks to the worker scheduler, the thread runs no callback * - wakes only when a waited value is reached or a smaller wait comes in * - thread safe + * - a created reactor does not move and takes no move assignment: its thread refers to it */ class TimelineReactor { public: @@ -108,7 +110,7 @@ class TimelineReactor { /** * raises the wake semaphore, the thread waits again with the new values - * @pre the caller holds `TimelineReactor::_mutex` + * @pre the caller holds `TimelineReactor::_mutexPtr` * @throws cvk::vk_result_exception result of `vkSignalSemaphore()` */ void wake() const; @@ -116,7 +118,7 @@ class TimelineReactor { /** * stores the error, takes every pending callback * @return the callbacks to post with the error - * @pre the caller holds `TimelineReactor::_mutex` + * @pre the caller holds `TimelineReactor::_mutexPtr` */ [[nodiscard]] std::vector fail(std::error_code) const; @@ -130,7 +132,8 @@ class TimelineReactor { /** the thread waits for it next to the semaphores with waiters */ mutable cvk::TimelineSemaphore _wake; - mutable std::mutex _mutex{}; + // behind a std::unique_ptr: the mutex is not movable, the moves stay = default + std::unique_ptr _mutexPtr = std::make_unique(); /** * min-heap of the waiters by value per semaphore @@ -146,8 +149,8 @@ class TimelineReactor { public: TimelineReactor(TimelineReactor const& other) = delete; - TimelineReactor(TimelineReactor&& other) = delete; + TimelineReactor(TimelineReactor&& other) noexcept = default; TimelineReactor& operator=(TimelineReactor const& other) = delete; - TimelineReactor& operator=(TimelineReactor&& other) = delete; + TimelineReactor& operator=(TimelineReactor&& other) noexcept = default; }; } diff --git a/jvk/src/base/core.cpp b/jvk/src/base/core.cpp index f9e9fdc5..beda5ed5 100644 --- a/jvk/src/base/core.cpp +++ b/jvk/src/base/core.cpp @@ -24,7 +24,8 @@ Core::Core(cvk::Instance const& instance, Config config) : _workers{ _config.workers == 0 ? std::max(std::thread::hardware_concurrency(), 1u) : _config.workers }, - _reactor{_core, _workers} {} + _reactor{_core, _workers}, + _resourceHeap{_core, _config.heaps.resources} {} Core::Core( cvk::Instance const& instance, @@ -52,15 +53,15 @@ void Core::create(span const> surfaces) { try { _workers.start(); _reactor.create(); - _queuesOpt.emplace(*this, _workers, _config.driverThreads); + createQueues(); if(_config.heaps.createsResourceHeap()) - _resourceHeapOpt.emplace(_core, _config.heaps.resources); + _resourceHeap.create(); if(_config.heaps.createsSamplerHeap()) _samplerHeapOpt.emplace(_core, _config.heaps.samplers); } catch(...) { - _resourceHeapOpt.reset(); - _queuesOpt.reset(); + _resourceHeap.optDestroy(); + destroyQueues(); _reactor.optDestroy(); _workers.await_stop(); _core.destroy(); @@ -107,9 +108,9 @@ void Core::destroy() { } } - _queuesOpt.reset(); + destroyQueues(); _samplerHeapOpt.reset(); - _resourceHeapOpt.reset(); + _resourceHeap.optDestroy(); _reactor.destroy(); _workers.await_stop(); _core.destroy(); @@ -117,16 +118,52 @@ void Core::destroy() { Queue const& Core::queue(size_t queueIdx) const { debug_check(*this); - return _queuesOpt->queue(queueIdx); + CTH_CRITICAL( + queueIdx >= _queueIndices.size(), + "queue index must be < {}, got {}", + _queueIndices.size(), + queueIdx + ) {} + return _queues[_queueIndices[queueIdx]]; } ResourceHeap const& Core::resourceHeap() const { debug_check(*this); CTH_CRITICAL( - !_resourceHeapOpt.has_value(), + !_resourceHeap.created(), "the core must have a resource heap, see HeapsConfig" ) {} - return *_resourceHeapOpt; + return _resourceHeap; +} + +void Core::createQueues() { + if(_config.driverThreads > 0) + _driverSchedulerOpt.emplace(cth::co::autostart, _config.driverThreads); + cth::co::scheduler const& scheduler = _driverSchedulerOpt.has_value() + ? *_driverSchedulerOpt + : _workers; + + auto const indices = _core.queueIndices(); + _queues.reserve(indices.size()); + _queueIndices.reserve(indices.size()); + + for(size_t queueIdx = 0; queueIdx < indices.size(); ++queueIdx) { + auto const firstIdx = + static_cast(std::ranges::find(indices, indices[queueIdx]) - indices.begin()); + if(firstIdx < queueIdx) { + _queueIndices.push_back(_queueIndices[firstIdx]); + continue; + } + + _queueIndices.push_back(_queues.size()); + _queues.emplace_back(*this, _core.queue(queueIdx), scheduler); + } +} + +void Core::destroyQueues() { + _queues.clear(); + _queueIndices.clear(); + _driverSchedulerOpt.reset(); } SamplerHeap const& Core::samplerHeap() const { diff --git a/jvk/src/base/queues.cpp b/jvk/src/base/queues.cpp deleted file mode 100644 index a4d01245..00000000 --- a/jvk/src/base/queues.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include "jvk/base/queues.hpp" - -#include "jvk/base/core.hpp" - -#include "cvk/base/core.hpp" - -#include - -#include -#include - - -namespace jvk { -Queues::Queues(Core const& core, cth::co::scheduler const& workers, size_t driverThreads) { - cvk::Core const& vk = core; - cvk::Core::debug_check(vk); - - if(driverThreads > 0) - _driverSchedulerOpt.emplace(cth::co::autostart, driverThreads); - cth::co::scheduler const& scheduler = _driverSchedulerOpt.has_value() - ? *_driverSchedulerOpt - : workers; - - auto const indices = vk.queueIndices(); - _queueIndices.reserve(indices.size()); - - for(size_t queueIdx = 0; queueIdx < indices.size(); ++queueIdx) { - auto const firstIdx = - static_cast(std::ranges::find(indices, indices[queueIdx]) - indices.begin()); - if(firstIdx < queueIdx) { - _queueIndices.push_back(_queueIndices[firstIdx]); - continue; - } - - _queueIndices.push_back(_queues.size()); - _queues.emplace_back(core, vk.queue(queueIdx), scheduler); - } -} - -Queue const& Queues::queue(size_t queueIdx) const { - CTH_CRITICAL( - queueIdx >= _queueIndices.size(), - "queue index must be < {}, got {}", - _queueIndices.size(), - queueIdx - ) {} - return _queues[_queueIndices[queueIdx]]; -} -} diff --git a/jvk/src/cmd/cmd_buffer.cpp b/jvk/src/cmd/cmd_buffer.cpp index 0341bbe1..0dea0c86 100644 --- a/jvk/src/cmd/cmd_buffer.cpp +++ b/jvk/src/cmd/cmd_buffer.cpp @@ -399,7 +399,7 @@ void BasicCmdBuffer::reset() { } template -void BasicCmdBuffer::appendStates(ResourceStates const& next) { +void BasicCmdBuffer::appendStates(ResourceTracker const& next) { cvk::Barrier barrier{}; _states.append(next, barrier); record(barrier); diff --git a/jvk/src/data/resource_heap.cpp b/jvk/src/data/resource_heap.cpp index 4c91eb4a..6db1663a 100644 --- a/jvk/src/data/resource_heap.cpp +++ b/jvk/src/data/resource_heap.cpp @@ -12,12 +12,22 @@ namespace jvk { ResourceHeap::ResourceHeap(cvk::Core const& core, Config const& config) : - _vk{core, config, cvk::create}, + _vk{core, config}, _sampledImages{config.sampledImages}, _storageImages{config.storageImages}, _inputAttachments{config.inputAttachments} {} -ResourceHeap::~ResourceHeap() { +ResourceHeap::ResourceHeap(cvk::Core const& core, Config const& config, cvk::create_t) : + ResourceHeap{core, config} { create(); } + +void ResourceHeap::create() { + optDestroy(); + + _vk.create(); +} + +void ResourceHeap::destroy() { + cvk::ResourceHeap::debug_check(_vk); CTH_CRITICAL( _sampledImages.used() + _storageImages.used() + _inputAttachments.used() != 0, "every handle of the heap must be gone, got {} sampled images, {} storage images, {} input attachments", @@ -25,6 +35,10 @@ ResourceHeap::~ResourceHeap() { _storageImages.used(), _inputAttachments.used() ) {} + + _vk.destroy(); + + forget(); } auto ResourceHeap::insert(cvk::SampledImageDescriptor const& descriptor) const -> SampledImage { @@ -67,7 +81,7 @@ auto ResourceHeap::insertImage(Descriptor const& descriptor) const -> ImageHandl ImageHandle::LAYOUT ) {} - std::scoped_lock const lock{_mutex}; + std::scoped_lock const lock{*_mutexPtr}; auto& free = freeList(); auto const idxOpt = free.insert(); @@ -87,7 +101,7 @@ auto ResourceHeap::insertImage(Descriptor const& descriptor) const -> ImageHandl template Descriptor> void ResourceHeap::erase(uint32_t idx) const { - std::scoped_lock const lock{_mutex}; + std::scoped_lock const lock{*_mutexPtr}; freeList().erase(idx); } @@ -101,6 +115,13 @@ dev::free_list& ResourceHeap::freeList() const { return _inputAttachments; } +void ResourceHeap::forget() { + auto const& config = _vk.config(); + _sampledImages = dev::free_list{config.sampledImages}; + _storageImages = dev::free_list{config.storageImages}; + _inputAttachments = dev::free_list{config.inputAttachments}; +} + template void ResourceHeap::erase(uint32_t) const; template void ResourceHeap::erase(uint32_t) const; template void ResourceHeap::erase(uint32_t) const; diff --git a/jvk/src/data/sampler_heap.cpp b/jvk/src/data/sampler_heap.cpp index a0c2c9da..bd4368ef 100644 --- a/jvk/src/data/sampler_heap.cpp +++ b/jvk/src/data/sampler_heap.cpp @@ -15,15 +15,16 @@ SamplerHeap::SamplerHeap(cvk::Core const& core, Config const& config) : _slots(config.samplers) {} SamplerHeap::~SamplerHeap() { + // a moved-from heap has no cvk heap CTH_CRITICAL( - _cells.used() != 0, + _vk.created() && _cells.used() != 0, "every sampler of the heap must be gone, got {}", _cells.used() ) {} } auto SamplerHeap::insert(cvk::SamplerConfig const& config) const -> Sampler { - std::scoped_lock const lock{_mutex}; + std::scoped_lock const lock{*_mutexPtr}; if(auto const it = _indices.find(config); it != _indices.end()) { ++_slots[it->second].refs; @@ -54,13 +55,13 @@ std::vector SamplerHeap::mappings() const { } void SamplerHeap::ref(uint32_t idx) const { - std::scoped_lock const lock{_mutex}; + std::scoped_lock const lock{*_mutexPtr}; CTH_CRITICAL(_slots[idx].refs == 0, "the cell {} must be in use", idx) {} ++_slots[idx].refs; } void SamplerHeap::unref(uint32_t idx) const { - std::scoped_lock const lock{_mutex}; + std::scoped_lock const lock{*_mutexPtr}; auto& [refs, config] = _slots[idx]; CTH_CRITICAL(refs == 0, "the cell {} must be in use", idx) {} diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index 06e1f663..2724bee5 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -114,9 +114,6 @@ cth::co::executor_task Presenter::acquire( Stage& stage, VkPipelineStageFlags2 stages ) { - // on the calling thread: the scope compares them at its end - auto const uncaughtExceptions = std::uncaught_exceptions(); - debug_check(*this); CTH_CRITICAL(stage.status() != Stage::Status::UNSUBMITTED, "the stage must be unsubmitted") {} CTH_CRITICAL( @@ -148,7 +145,7 @@ cth::co::executor_task Presenter::acquire( while(!imageIdxOpt.has_value()) { auto const extent = _surface.extent(vkCore.physicalDevice()); if(extent.width == 0 || extent.height == 0) - co_return scoped_acquire{*this, stage, std::nullopt, _error, uncaughtExceptions}; + co_return scoped_acquire{*this, stage, std::nullopt, _error}; updateSwapchain(extent, &stage.graph()); // no image -> out of date, the next round recreates the swapchain @@ -179,7 +176,7 @@ cth::co::executor_task Presenter::acquire( ImageState{.layout = VK_IMAGE_LAYOUT_UNDEFINED, .scope = {.stages = stages}} ); - co_return scoped_acquire{*this, stage, image, _error, uncaughtExceptions}; + co_return scoped_acquire{*this, stage, image, _error}; } void Presenter::present(Stage& stage) { @@ -357,31 +354,18 @@ scoped_acquire::scoped_acquire( Presenter& presenter, Stage& stage, std::optional imageOpt, - dev::first_error& error, - int uncaughtExceptions + dev::first_error& error ) noexcept : _presenterPtr{&presenter}, _stage{stage}, _imageOpt{std::move(imageOpt)}, - _error{error}, - _uncaughtExceptions{uncaughtExceptions} {} + _error{error} {} scoped_acquire::~scoped_acquire() { if(!_presenterPtr || !_imageOpt.has_value()) return; auto& stage = *_stage; - // an exception after the submit: the frame is complete - bool const exception = std::uncaught_exceptions() > _uncaughtExceptions; - if(exception && stage.status() != Stage::Status::SUBMITTED) - return; - CTH_CRITICAL( - stage.status() == Stage::Status::UNSUBMITTED && stage.primary().recording() - && stage.primary().states().last(_imageOpt->image->get(), 0).has_value(), - "the open primary of the stage uses the swapchain image {}, declare scoped_acquire before scoped_submit", - _imageOpt->imageIdx - ) {} - // skipped or unsubmitted: the next acquire() or destroy() unacquires the image if(stage.status() != Stage::Status::SUBMITTED) return; diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index f53a90d4..4117d881 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -11,6 +11,7 @@ #include "cvk/render/sync/timeline_semaphore.hpp" #include "cvk/utility/vk_exceptions.hpp" +#include #include #include #include @@ -18,6 +19,7 @@ #include #include #include +#include #include #include @@ -164,10 +166,12 @@ cth::co::executor_task StageGraph::nextFrame() { // a failed skip in an earlier nextFrame() leaves a stage of an older frame unsubmitted skipUnsubmitted(frameSlot); - for(auto const& stage : frameSlot.stages) - co_await stage.submitted(); - for(auto const& stage : frameSlot.stages) - co_await stage; + // the marks first: the gpu can finish before the graph job marks the submit + co_await cth::co::all( + frameSlot.stages + | std::views::transform([](Stage const& stage) { return stage.submitted(); }) + ); + co_await cth::co::all(frameSlot.stages); } frameSlot.frameOpt.reset(); @@ -365,7 +369,7 @@ cth::co::executor_task StageGraph::submitJob( } void StageGraph::append( - ResourceStates const& recording, + ResourceTracker const& recording, Queue const& queue, cvk::Barrier& prologue, release_map_t& releases @@ -383,7 +387,7 @@ void StageGraph::append( for(auto const& [vkImage, mipLevel, aspectMask, sharingMode] : recording.images()) { auto const firstOpt = recording.first(vkImage, mipLevel); - // an assume() before the first use: ResourceStates::append() takes the state + // an assume() before the first use: ResourceTracker::append() takes the state if(!firstOpt.has_value()) continue; @@ -397,7 +401,7 @@ void StageGraph::append( if(lastQueuePtr == nullptr || sharingMode != VK_SHARING_MODE_EXCLUSIVE) continue; - // ResourceStates::append() inserts the state of the recording without a barrier + // ResourceTracker::append() inserts the state of the recording without a barrier _states.erase(vkImage, mipLevel); if(recording.discards(vkImage, mipLevel) || lastOpt->layout == VK_IMAGE_LAYOUT_UNDEFINED) { diff --git a/jvk/src/sync/resource_states.cpp b/jvk/src/sync/resource_tracker.cpp similarity index 87% rename from jvk/src/sync/resource_states.cpp rename to jvk/src/sync/resource_tracker.cpp index 4f1e13c5..01194b03 100644 --- a/jvk/src/sync/resource_states.cpp +++ b/jvk/src/sync/resource_tracker.cpp @@ -1,4 +1,4 @@ -#include "jvk/sync/resource_states.hpp" +#include "jvk/sync/resource_tracker.hpp" #include "cvk/data/buffer/base_buffer.hpp" #include "cvk/data/img/image.hpp" @@ -32,7 +32,7 @@ namespace { * src of a barrier after the scope, only the writes of its access */ [[nodiscard]] constexpr BarrierScope src_scope(BarrierScope const& scope) { - return BarrierScope{scope.stages, scope.access & WRITES, scope.queueFamilyIndex}; + return BarrierScope{scope.stages, scope.access & WRITES}; } /** @@ -40,11 +40,7 @@ namespace { */ [[nodiscard]] constexpr BarrierScope merge(BarrierScope const& scope, BarrierScope const& other) { - return BarrierScope{ - scope.stages | other.stages, - scope.access | other.access, - scope.queueFamilyIndex - }; + return BarrierScope{scope.stages | other.stages, scope.access | other.access}; } /** @@ -151,7 +147,7 @@ namespace { } } -void ResourceStates::access(Image const& image, ImageAccess const& access, cvk::Barrier& barrier) { +void ResourceTracker::access(Image const& image, ImageAccess const& access, cvk::Barrier& barrier) { auto const count = mip_count(image, access.firstMipLevel, access.mipLevels); ImageState const next{ .layout = access.layout, @@ -192,7 +188,7 @@ void ResourceStates::access(Image const& image, ImageAccess const& access, cvk:: } } -void ResourceStates::access( +void ResourceTracker::access( BaseBuffer const& buffer, BufferAccess const& access, cvk::Barrier& barrier @@ -223,7 +219,7 @@ void ResourceStates::access( states.firstOpt->scope = merge(states.firstOpt->scope, next.scope); } -void ResourceStates::assume( +void ResourceTracker::assume( Image const& image, ImageState const& state, uint32_t firstMipLevel, @@ -251,7 +247,7 @@ void ResourceStates::assume( } } -void ResourceStates::assume(BaseBuffer const& buffer, BufferState const& state) { +void ResourceTracker::assume(BaseBuffer const& buffer, BufferState const& state) { BaseBuffer::debug_check(buffer); auto const [it, inserted] = _buffers.try_emplace( @@ -271,7 +267,7 @@ void ResourceStates::assume(BaseBuffer const& buffer, BufferState const& state) states.barrier = true; } -void ResourceStates::extend( +void ResourceTracker::extend( Image const& image, BarrierScope const& scope, uint32_t firstMipLevel, @@ -291,7 +287,7 @@ void ResourceStates::extend( } } -void ResourceStates::append(ResourceStates const& next, cvk::Barrier& barrier) { +void ResourceTracker::append(ResourceTracker const& next, cvk::Barrier& barrier) { for(auto const& [key, nextStates] : next._images) { auto const [it, inserted] = _images.try_emplace(key, nextStates); if(inserted) @@ -362,72 +358,72 @@ void ResourceStates::append(ResourceStates const& next, cvk::Barrier& barrier) { } } -std::optional ResourceStates::first(VkImage vkImage, uint32_t mipLevel) const { +std::optional ResourceTracker::first(VkImage vkImage, uint32_t mipLevel) const { auto const it = _images.find(image_key_t{vkImage, mipLevel}); return it == _images.end() ? std::nullopt : it->second.firstOpt; } -bool ResourceStates::discards(VkImage vkImage, uint32_t mipLevel) const { +bool ResourceTracker::discards(VkImage vkImage, uint32_t mipLevel) const { auto const it = _images.find(image_key_t{vkImage, mipLevel}); return it != _images.end() && it->second.discard; } -std::optional ResourceStates::last(VkImage vkImage, uint32_t mipLevel) const { +std::optional ResourceTracker::last(VkImage vkImage, uint32_t mipLevel) const { auto const it = _images.find(image_key_t{vkImage, mipLevel}); return it == _images.end() ? std::nullopt : std::optional{it->second.last}; } -std::optional ResourceStates::first(VkBuffer vkBuffer) const { +std::optional ResourceTracker::first(VkBuffer vkBuffer) const { auto const it = _buffers.find(vkBuffer); return it == _buffers.end() ? std::nullopt : it->second.firstOpt; } -std::optional ResourceStates::last(VkBuffer vkBuffer) const { +std::optional ResourceTracker::last(VkBuffer vkBuffer) const { auto const it = _buffers.find(vkBuffer); return it == _buffers.end() ? std::nullopt : std::optional{it->second.last}; } -std::optional ResourceStates::first(Image const& image, uint32_t mipLevel) const { +std::optional ResourceTracker::first(Image const& image, uint32_t mipLevel) const { return first(image.get(), mipLevel); } -bool ResourceStates::discards(Image const& image, uint32_t mipLevel) const { +bool ResourceTracker::discards(Image const& image, uint32_t mipLevel) const { return discards(image.get(), mipLevel); } -std::optional ResourceStates::last(Image const& image, uint32_t mipLevel) const { +std::optional ResourceTracker::last(Image const& image, uint32_t mipLevel) const { return last(image.get(), mipLevel); } -std::optional ResourceStates::first(BaseBuffer const& buffer) const { +std::optional ResourceTracker::first(BaseBuffer const& buffer) const { return first(buffer.get()); } -std::optional ResourceStates::last(BaseBuffer const& buffer) const { +std::optional ResourceTracker::last(BaseBuffer const& buffer) const { return last(buffer.get()); } -void ResourceStates::erase(Image const& image) { +void ResourceTracker::erase(Image const& image) { for(uint32_t level = 0; level < image.mipLevels(); ++level) erase(image.get(), level); } -void ResourceStates::erase(BaseBuffer const& buffer) { erase(buffer.get()); } +void ResourceTracker::erase(BaseBuffer const& buffer) { erase(buffer.get()); } -void ResourceStates::erase(VkImage vkImage, uint32_t mipLevel) { +void ResourceTracker::erase(VkImage vkImage, uint32_t mipLevel) { _images.erase(image_key_t{vkImage, mipLevel}); } -void ResourceStates::erase(VkBuffer vkBuffer) { _buffers.erase(vkBuffer); } +void ResourceTracker::erase(VkBuffer vkBuffer) { _buffers.erase(vkBuffer); } -bool ResourceStates::contains(Image const& image) const { +bool ResourceTracker::contains(Image const& image) const { for(uint32_t level = 0; level < image.mipLevels(); ++level) if(_images.contains(image_key_t{image.get(), level})) return true; return false; } -bool ResourceStates::contains(BaseBuffer const& buffer) const { +bool ResourceTracker::contains(BaseBuffer const& buffer) const { return _buffers.contains(buffer.get()); } } diff --git a/jvk/src/sync/semaphore.cpp b/jvk/src/sync/semaphore.cpp index 640173b2..a2a401df 100644 --- a/jvk/src/sync/semaphore.cpp +++ b/jvk/src/sync/semaphore.cpp @@ -106,7 +106,7 @@ void Semaphore::markSubmitted(uint64_t value) const { workers.post([cb = std::move(cb)]() mutable { cb({}); }); } -void Semaphore::awaitSubmitted(uint64_t value, await_func cb) const { +void Semaphore::onSubmitted(uint64_t value, await_func cb) const { debug_check(*this); { diff --git a/jvk/src/sync/timeline_reactor.cpp b/jvk/src/sync/timeline_reactor.cpp index 074d9a8c..014f9827 100644 --- a/jvk/src/sync/timeline_reactor.cpp +++ b/jvk/src/sync/timeline_reactor.cpp @@ -43,7 +43,7 @@ void TimelineReactor::destroy() { CTH_CRITICAL(!created(), "reactor must be created") {} { - std::scoped_lock const lock{_mutex}; + std::scoped_lock const lock{*_mutexPtr}; CTH_CRITICAL( !_waiters.empty(), "no callback must be pending, got {} semaphores", @@ -77,7 +77,7 @@ void TimelineReactor::await(VkSemaphore vkSemaphore, uint64_t value, await_func std::error_code error{}; { - std::scoped_lock const lock{_mutex}; + std::scoped_lock const lock{*_mutexPtr}; if(!_error) { // the thread waits for the smallest value per semaphore, a new smallest value needs a new wait @@ -100,7 +100,7 @@ void TimelineReactor::await(VkSemaphore vkSemaphore, uint64_t value, await_func } bool TimelineReactor::pending(VkSemaphore vkSemaphore) const { - std::scoped_lock const lock{_mutex}; + std::scoped_lock const lock{*_mutexPtr}; return _waiters.contains(vkSemaphore); } @@ -115,7 +115,7 @@ void TimelineReactor::run(std::stop_token stop) { while(true) { { - std::scoped_lock const lock{_mutex}; + std::scoped_lock const lock{*_mutexPtr}; if(stop.stop_requested()) return; @@ -142,7 +142,7 @@ void TimelineReactor::run(std::stop_token stop) { ); { - std::scoped_lock const lock{_mutex}; + std::scoped_lock const lock{*_mutexPtr}; for(auto it = _waiters.begin(); result == VK_SUCCESS && it != _waiters.end();) { auto& [vkSemaphore, waiters] = *it; diff --git a/jvk/tests/src/base/queue_test.cpp b/jvk/tests/src/base/queue_test.cpp index 931f962e..62fc5802 100644 --- a/jvk/tests/src/base/queue_test.cpp +++ b/jvk/tests/src/base/queue_test.cpp @@ -6,11 +6,13 @@ #include "jvk/data/buffer.hpp" #include "jvk/data/image.hpp" +#include "cvk/base/core.hpp" #include "cvk/base/queue/submit_info.hpp" #include "cvk/render/sync/barrier.hpp" #include "cvk/render/sync/fence.hpp" #include "cvk/render/sync/timeline_semaphore.hpp" +#include #include #include @@ -144,23 +146,6 @@ namespace { return true; } - /** - * the queue family ownership transfer of the image, without layout transition when the layouts are equal - */ - [[nodiscard]] cvk::ImageBarrierInfo image_transfer( - cvk::BarrierScope src, - cvk::BarrierScope dst, - VkImageLayout oldLayout, - VkImageLayout newLayout - ) { - return cvk::ImageBarrierInfo{ - .src = src, - .dst = dst, - .newLayout = newLayout, - .oldLayout = oldLayout - }; - } - /** * submits inside the strand */ @@ -229,6 +214,25 @@ JVK_TEST(Queue, wait_idle_waits_for_the_submits) { EXPECT_EQ(semaphore.gpuValue(), 1); } +JVK_TEST(Queue, a_moved_queue_runs_its_strand) { + test::Context const context{}; + cvk::Core const& vk = context.core; + cth::co::scheduler const workers{cth::co::autostart}; + cvk::TimelineSemaphore const semaphore{context.core, cvk::create}; + Queue queue{context.core, vk.queue(0), workers}; + + Queue moved{std::move(queue)}; + moved.executor().sync_wait(signal(moved, semaphore)); + moved.waitIdle(); + EXPECT_EQ(semaphore.gpuValue(), 1); + + Queue other{context.core, vk.queue(0), workers}; + other = std::move(moved); + other.executor().sync_wait(signal(other, semaphore)); + other.waitIdle(); + EXPECT_EQ(semaphore.gpuValue(), 2); +} + JVK_TEST(Queue, release_transfers_an_image_to_another_family) { test::Context const context{}; Core const core{context.instance, two_families(), {}}; @@ -255,12 +259,13 @@ JVK_TEST(Queue, release_transfers_an_image_to_another_family) { cvk::Barrier release{}; release.add( image, - image_transfer( - {TRANSFER_WRITE.stages, TRANSFER_WRITE.access, ownerFamily}, - {.queueFamilyIndex = receiverFamily}, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL - ) + cvk::ImageBarrierInfo{ + .src = TRANSFER_WRITE, + .srcQueueFamilyIndex = ownerFamily, + .dstQueueFamilyIndex = receiverFamily, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + } ); auto const released = core.executor().sync_wait(owner.release(release)); EXPECT_EQ(released.semaphore->submittedValue(), released.value); @@ -271,12 +276,14 @@ JVK_TEST(Queue, release_transfers_an_image_to_another_family) { cvk::Barrier acquire{}; acquire.add( image, - image_transfer( - {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, .queueFamilyIndex = ownerFamily}, - {TRANSFER_READ.stages, TRANSFER_READ.access, receiverFamily}, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL - ) + cvk::ImageBarrierInfo{ + .src = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, + .dst = TRANSFER_READ, + .srcQueueFamilyIndex = ownerFamily, + .dstQueueFamilyIndex = receiverFamily, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + } ); acquire.execute(read); read.assume( @@ -331,10 +338,11 @@ JVK_TEST(Queue, several_releases_in_a_row) { cvk::Barrier release{}; release.add( buffer, - cvk::BufferBarrierInfo::QueueTransition( - {.queueFamilyIndex = receiverFamily}, - {TRANSFER_WRITE.stages, TRANSFER_WRITE.access, ownerFamily} - ) + cvk::BufferBarrierInfo{ + .src = TRANSFER_WRITE, + .srcQueueFamilyIndex = ownerFamily, + .dstQueueFamilyIndex = receiverFamily, + } ); released.push_back(core.executor().sync_wait(owner.release(release))); } @@ -350,10 +358,12 @@ JVK_TEST(Queue, several_releases_in_a_row) { for(auto const& buffer : buffers) acquire.add( buffer, - cvk::BufferBarrierInfo::QueueTransition( - {TRANSFER_READ.stages, TRANSFER_READ.access, receiverFamily}, - {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, .queueFamilyIndex = ownerFamily} - ) + cvk::BufferBarrierInfo{ + .src = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, + .dst = TRANSFER_READ, + .srcQueueFamilyIndex = ownerFamily, + .dstQueueFamilyIndex = receiverFamily, + } ); acquire.execute(read); for(size_t i = 0; i < RELEASES; ++i) { diff --git a/jvk/tests/src/base/queues_test.cpp b/jvk/tests/src/base/queues_test.cpp deleted file mode 100644 index ed6187f0..00000000 --- a/jvk/tests/src/base/queues_test.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include "jvk/base/queues.hpp" - -#include "context.hpp" -#include "test.hpp" - -#include "cvk/base/core.hpp" - -#include - - -namespace jvk { -JVK_TEST(Queues, queue_refers_to_its_cvk_queue) { - test::Context const context{}; - cvk::Core const& vk = context.core; - cth::co::scheduler const workers{cth::co::autostart}; - - Queues const queues{context.core, workers, 0}; - - EXPECT_EQ(&queues.queue(0).vk(), &vk.queue(0)); - EXPECT_EQ(queues.queue(0).get(), vk.queue(0).get()); - queues.queue(0).waitIdle(); -} -} diff --git a/jvk/tests/src/data/heap_test.cpp b/jvk/tests/src/data/heap_test.cpp index 121c9a33..cb45be32 100644 --- a/jvk/tests/src/data/heap_test.cpp +++ b/jvk/tests/src/data/heap_test.cpp @@ -192,6 +192,87 @@ JVK_TEST(ResourceHeap, a_retained_cell_comes_back_after_the_gpu_finished) { EXPECT_TRUE(reaches_cell(heap, descriptor, idx)); } +JVK_TEST(ResourceHeap, base_constructor_does_not_create) { + test::Context const context{}; + + ResourceHeap const heap{context.core, {.sampledImages = 4}}; + + EXPECT_FALSE(heap.created()); + EXPECT_EQ(heap.config().sampledImages, 4); +} + +JVK_TEST(ResourceHeap, create_and_destroy) { + test::Context const context{}; + ResourceHeap heap{context.core, {.sampledImages = 4}}; + + heap.create(); + EXPECT_TRUE(heap.created()); + + heap.destroy(); + EXPECT_FALSE(heap.created()); + + // a leak shows up when the shared device is destroyed + heap.optDestroy(); + ResourceHeap const created{context.core, {.sampledImages = 4}, cvk::create}; + EXPECT_TRUE(created.created()); +} + +JVK_TEST(ResourceHeap, destroy_frees_every_cell) { + test::Context const context{}; + ResourceHeap heap{context.core, {.sampledImages = 4}, cvk::create}; + cvk::Image const texture{context.core, TEXTURE_CONFIG, VkExtent2D{1, 1}}; + + { + auto first = heap.insert(cvk::SampledImageDescriptor{texture}); + auto second = heap.insert(cvk::SampledImageDescriptor{texture}); + ASSERT_EQ(first.idx().get(), 0); + ASSERT_EQ(second.idx().get(), 1); + + // the cell of the last erased handle comes first, cell 1 here + { auto const gone = std::move(first); } + { auto const gone = std::move(second); } + } + + heap.destroy(); + heap.create(); + + // every cell is free again: the first insert gets cell 0 + EXPECT_EQ(heap.insert(cvk::SampledImageDescriptor{texture}).idx().get(), 0); +} + +JVK_TEST(ResourceHeap, a_moved_heap_inserts) { + test::Context const context{}; + ResourceHeap heap{context.core, {.sampledImages = 4}, cvk::create}; + cvk::Image const texture{context.core, TEXTURE_CONFIG, VkExtent2D{1, 1}}; + + ResourceHeap moved{std::move(heap)}; + ASSERT_TRUE(moved.created()); + EXPECT_EQ(moved.insert(cvk::SampledImageDescriptor{texture}).idx().get(), 0); + + ResourceHeap other{context.core, {.sampledImages = 1}, cvk::create}; + other = std::move(moved); + EXPECT_EQ(other.config().sampledImages, 4); + EXPECT_EQ(other.insert(cvk::SampledImageDescriptor{texture}).idx().get(), 0); +} + +JVK_TEST(SamplerHeap, a_moved_heap_inserts) { + test::Context const context{}; + SamplerHeap heap{context.core, {.samplers = 2}}; + cvk::SamplerConfig const nearest{.magFilter = VK_FILTER_NEAREST}; + // the moved-from heaps keep the count of the returned cell + EXPECT_EQ(heap.insert(cvk::SamplerConfig{}).idx().get(), 0); + + SamplerHeap moved{std::move(heap)}; + EXPECT_EQ(moved.insert(cvk::SamplerConfig{}).idx().get(), 0); + + SamplerHeap other{context.core, {.samplers = 1}}; + other = std::move(moved); + EXPECT_EQ(other.config().samplers, 2); + auto const linearSampler = other.insert(cvk::SamplerConfig{}); + auto const nearestSampler = other.insert(nearest); + EXPECT_NE(linearSampler.idx(), nearestSampler.idx()); +} + JVK_TEST(SamplerHeap, equal_configs_share_a_cell) { test::Context const context{}; auto const& heap = context.core.samplerHeap(); diff --git a/jvk/tests/src/sync/resource_states_test.cpp b/jvk/tests/src/sync/resource_tracker_test.cpp similarity index 88% rename from jvk/tests/src/sync/resource_states_test.cpp rename to jvk/tests/src/sync/resource_tracker_test.cpp index 1e6c1dbd..039b30fd 100644 --- a/jvk/tests/src/sync/resource_states_test.cpp +++ b/jvk/tests/src/sync/resource_tracker_test.cpp @@ -1,4 +1,4 @@ -#include "jvk/sync/resource_states.hpp" +#include "jvk/sync/resource_tracker.hpp" #include "context.hpp" #include "test.hpp" @@ -68,10 +68,10 @@ namespace { } } -JVK_TEST(ResourceStates, unknown_image_has_no_state) { +JVK_TEST(ResourceTracker, unknown_image_has_no_state) { test::Context const context{}; Image const image{context.core, IMAGE_CONFIG, EXTENT}; - ResourceStates const states{}; + ResourceTracker const states{}; EXPECT_TRUE(states.empty()); EXPECT_FALSE(states.contains(image)); @@ -79,10 +79,10 @@ JVK_TEST(ResourceStates, unknown_image_has_no_state) { EXPECT_FALSE(states.last(image, 2).has_value()); } -JVK_TEST(ResourceStates, first_access_is_a_first_use) { +JVK_TEST(ResourceTracker, first_access_is_a_first_use) { test::Context const context{}; Image const image{context.core, IMAGE_CONFIG, EXTENT}; - ResourceStates states{}; + ResourceTracker states{}; cvk::Barrier barrier{}; states.access(image, FRAGMENT_READ, barrier); @@ -95,10 +95,10 @@ JVK_TEST(ResourceStates, first_access_is_a_first_use) { EXPECT_FALSE(states.discards(image, 2)); } -JVK_TEST(ResourceStates, known_state_gets_a_barrier) { +JVK_TEST(ResourceTracker, known_state_gets_a_barrier) { test::Context const context{}; Image const image{context.core, IMAGE_CONFIG, EXTENT}; - ResourceStates states{}; + ResourceTracker states{}; cvk::Barrier barrier{}; states.assume(image, UNDEFINED); @@ -121,10 +121,10 @@ JVK_TEST(ResourceStates, known_state_gets_a_barrier) { EXPECT_EQ(states.last(image, 0)->layout, VK_IMAGE_LAYOUT_UNDEFINED); } -JVK_TEST(ResourceStates, read_after_read_needs_no_barrier) { +JVK_TEST(ResourceTracker, read_after_read_needs_no_barrier) { test::Context const context{}; Image const image{context.core, IMAGE_CONFIG, EXTENT}; - ResourceStates states{}; + ResourceTracker states{}; cvk::Barrier barrier{}; states.access(image, FRAGMENT_READ, barrier); @@ -138,10 +138,10 @@ JVK_TEST(ResourceStates, read_after_read_needs_no_barrier) { EXPECT_EQ(states.first(image, 0)->scope.stages, stages); } -JVK_TEST(ResourceStates, write_after_write_gets_a_barrier) { +JVK_TEST(ResourceTracker, write_after_write_gets_a_barrier) { test::Context const context{}; Image const image{context.core, IMAGE_CONFIG, EXTENT}; - ResourceStates states{}; + ResourceTracker states{}; cvk::Barrier barrier{}; states.access(image, with_mips(TRANSFER_WRITE, 0, 1), barrier); @@ -154,10 +154,10 @@ JVK_TEST(ResourceStates, write_after_write_gets_a_barrier) { EXPECT_EQ(vkBarrier.srcAccessMask, VK_ACCESS_2_TRANSFER_WRITE_BIT); } -JVK_TEST(ResourceStates, a_barrier_ends_the_first_use) { +JVK_TEST(ResourceTracker, a_barrier_ends_the_first_use) { test::Context const context{}; Image const image{context.core, IMAGE_CONFIG, EXTENT}; - ResourceStates states{}; + ResourceTracker states{}; cvk::Barrier barrier{}; states.access(image, FRAGMENT_READ, barrier); @@ -169,10 +169,10 @@ JVK_TEST(ResourceStates, a_barrier_ends_the_first_use) { EXPECT_EQ(states.last(image, 0)->layout, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); } -JVK_TEST(ResourceStates, read_after_read_only_makes_writes_available) { +JVK_TEST(ResourceTracker, read_after_read_only_makes_writes_available) { test::Context const context{}; Image const image{context.core, IMAGE_CONFIG, EXTENT}; - ResourceStates states{}; + ResourceTracker states{}; cvk::Barrier barrier{}; states.access(image, FRAGMENT_READ, barrier); @@ -183,10 +183,10 @@ JVK_TEST(ResourceStates, read_after_read_only_makes_writes_available) { EXPECT_EQ(barrier.images[0].srcAccessMask, VK_ACCESS_2_NONE); } -JVK_TEST(ResourceStates, discard_comes_from_undefined) { +JVK_TEST(ResourceTracker, discard_comes_from_undefined) { test::Context const context{}; Image const image{context.core, IMAGE_CONFIG, EXTENT}; - ResourceStates states{}; + ResourceTracker states{}; cvk::Barrier barrier{}; auto discard = TRANSFER_WRITE; discard.discard = true; @@ -203,10 +203,10 @@ JVK_TEST(ResourceStates, discard_comes_from_undefined) { EXPECT_EQ(barrier.images[1].newLayout, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); } -JVK_TEST(ResourceStates, assume_a_mip_range) { +JVK_TEST(ResourceTracker, assume_a_mip_range) { test::Context const context{}; Image const image{context.core, IMAGE_CONFIG, EXTENT}; - ResourceStates states{}; + ResourceTracker states{}; states.assume(image, {.layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .scope = {}}, 1, 2); @@ -218,10 +218,10 @@ JVK_TEST(ResourceStates, assume_a_mip_range) { EXPECT_FALSE(states.last(image, 3).has_value()); } -JVK_TEST(ResourceStates, assume_the_remaining_mip_levels) { +JVK_TEST(ResourceTracker, assume_the_remaining_mip_levels) { test::Context const context{}; Image const image{context.core, IMAGE_CONFIG, EXTENT}; - ResourceStates states{}; + ResourceTracker states{}; states.assume(image, {.layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .scope = {}}); states.assume(image, {.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, .scope = {}}, 2); @@ -234,10 +234,10 @@ JVK_TEST(ResourceStates, assume_the_remaining_mip_levels) { ); } -JVK_TEST(ResourceStates, assume_keeps_the_first_use) { +JVK_TEST(ResourceTracker, assume_keeps_the_first_use) { test::Context const context{}; Image const image{context.core, IMAGE_CONFIG, EXTENT}; - ResourceStates states{}; + ResourceTracker states{}; cvk::Barrier barrier{}; states.access(image, FRAGMENT_READ, barrier); @@ -258,10 +258,10 @@ JVK_TEST(ResourceStates, assume_keeps_the_first_use) { ); } -JVK_TEST(ResourceStates, buffer_barriers) { +JVK_TEST(ResourceTracker, buffer_barriers) { test::Context const context{}; BaseBuffer const buffer{context.core, BUFFER_CONFIG, SIZE}; - ResourceStates states{}; + ResourceTracker states{}; cvk::Barrier barrier{}; states.access(buffer, SHADER_WRITE, barrier); @@ -279,10 +279,10 @@ JVK_TEST(ResourceStates, buffer_barriers) { EXPECT_EQ(states.last(buffer)->scope.access, VK_ACCESS_2_SHADER_STORAGE_READ_BIT); } -JVK_TEST(ResourceStates, assume_a_buffer) { +JVK_TEST(ResourceTracker, assume_a_buffer) { test::Context const context{}; BaseBuffer const buffer{context.core, BUFFER_CONFIG, SIZE}; - ResourceStates states{}; + ResourceTracker states{}; cvk::Barrier barrier{}; states.assume( @@ -296,13 +296,13 @@ JVK_TEST(ResourceStates, assume_a_buffer) { EXPECT_EQ(barrier.buffers[0].srcAccessMask, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT); } -JVK_TEST(ResourceStates, append_gets_barriers_for_the_first_uses_of_next) { +JVK_TEST(ResourceTracker, append_gets_barriers_for_the_first_uses_of_next) { test::Context const context{}; Image const image{context.core, IMAGE_CONFIG, EXTENT}; Image const other{context.core, IMAGE_CONFIG, EXTENT}; BaseBuffer const buffer{context.core, BUFFER_CONFIG, SIZE}; - ResourceStates states{}; - ResourceStates next{}; + ResourceTracker states{}; + ResourceTracker next{}; cvk::Barrier barrier{}; states.assume(image, UNDEFINED); states.access(buffer, SHADER_WRITE, barrier); @@ -326,11 +326,11 @@ JVK_TEST(ResourceStates, append_gets_barriers_for_the_first_uses_of_next) { EXPECT_EQ(states.last(buffer)->scope.access, VK_ACCESS_2_SHADER_STORAGE_READ_BIT); } -JVK_TEST(ResourceStates, append_without_a_first_use_of_next_needs_no_barrier) { +JVK_TEST(ResourceTracker, append_without_a_first_use_of_next_needs_no_barrier) { test::Context const context{}; Image const image{context.core, IMAGE_CONFIG, EXTENT}; - ResourceStates states{}; - ResourceStates next{}; + ResourceTracker states{}; + ResourceTracker next{}; cvk::Barrier barrier{}; states.assume(image, UNDEFINED); next.assume(image, {.layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .scope = {}}); @@ -341,10 +341,10 @@ JVK_TEST(ResourceStates, append_without_a_first_use_of_next_needs_no_barrier) { EXPECT_EQ(states.last(image, 0)->layout, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); } -JVK_TEST(ResourceStates, follows_the_handle_when_the_image_moves) { +JVK_TEST(ResourceTracker, follows_the_handle_when_the_image_moves) { test::Context const context{}; Image image{context.core, IMAGE_CONFIG, EXTENT}; - ResourceStates states{}; + ResourceTracker states{}; states.assume(image, {.layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .scope = {}}); Image const moved{std::move(image)}; @@ -352,12 +352,12 @@ JVK_TEST(ResourceStates, follows_the_handle_when_the_image_moves) { EXPECT_EQ(states.last(moved, 0)->layout, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); } -JVK_TEST(ResourceStates, erase_and_clear) { +JVK_TEST(ResourceTracker, erase_and_clear) { test::Context const context{}; Image const first{context.core, IMAGE_CONFIG, EXTENT}; Image const second{context.core, IMAGE_CONFIG, EXTENT}; BaseBuffer const buffer{context.core, BUFFER_CONFIG, SIZE}; - ResourceStates states{}; + ResourceTracker states{}; states.assume(first, UNDEFINED); states.assume(second, UNDEFINED); states.assume(buffer, BufferState{}); diff --git a/jvk/tests/src/sync/semaphore_test.cpp b/jvk/tests/src/sync/semaphore_test.cpp index ad3f73d7..95cb11d2 100644 --- a/jvk/tests/src/sync/semaphore_test.cpp +++ b/jvk/tests/src/sync/semaphore_test.cpp @@ -88,7 +88,7 @@ namespace { ) { std::promise promise{}; auto future = promise.get_future(); - semaphore.awaitSubmitted( + semaphore.onSubmitted( value, [promise = std::move(promise)](std::error_code error) mutable { promise.set_value(error); diff --git a/jvk/tests/src/sync/timeline_reactor_test.cpp b/jvk/tests/src/sync/timeline_reactor_test.cpp index 94e6fdbc..76a85ee6 100644 --- a/jvk/tests/src/sync/timeline_reactor_test.cpp +++ b/jvk/tests/src/sync/timeline_reactor_test.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include @@ -110,6 +111,31 @@ JVK_TEST(TimelineReactor, create_and_destroy) { EXPECT_TRUE(reactor.created()); } +JVK_TEST(TimelineReactor, a_moved_reactor_creates_and_calls_the_callback) { + test::Context const context{}; + cth::co::scheduler workers{cth::co::autostart}; + cvk::TimelineSemaphore semaphore{context.core, cvk::create}; + TimelineReactor reactor{context.core, workers}; + + TimelineReactor moved{std::move(reactor)}; + TimelineReactor other{context.core, workers}; + other = std::move(moved); + other.create(); + EXPECT_TRUE(other.created()); + + std::promise promise{}; + auto result = promise.get_future(); + other.await( + semaphore.get(), + 1, + [promise = std::move(promise)](std::error_code error) mutable { promise.set_value(error); } + ); + host_signal(semaphore, 1); + + ASSERT_EQ(result.wait_for(REACHED_TIMEOUT), std::future_status::ready); + EXPECT_FALSE(result.get()); +} + JVK_TEST(TimelineReactor, gpu_signal_calls_the_callback_on_a_worker) { test::Context const context{}; cvk::TimelineSemaphore const semaphore{context.core, cvk::create}; diff --git a/timgui/tests/src/imgui_test.cpp b/timgui/tests/src/imgui_test.cpp index 2cff9b60..1fd2fab8 100644 --- a/timgui/tests/src/imgui_test.cpp +++ b/timgui/tests/src/imgui_test.cpp @@ -10,7 +10,7 @@ #include "jvk/graph/frame.hpp" #include "jvk/graph/stage.hpp" #include "jvk/graph/stage_graph.hpp" -#include "jvk/sync/resource_states.hpp" +#include "jvk/sync/resource_tracker.hpp" #include "cgfw/window/window.hpp" From 6a376c96fa5b074e20a0425a84fdd1dda85404fc Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:21:54 +0100 Subject: [PATCH 22/68] jvk: the submitted values of the semaphores in a cth::co::counter_event (codethinki/cth#34) - jvk::Semaphore: no mutex, no std::unique_ptr, no waiter vector, the moves stay = default - submitted_awaiter, onSubmitted() and the double post through the workers removed --- jvk/incl/jvk/graph/presenter.hpp | 2 +- jvk/incl/jvk/graph/stage.hpp | 3 +- jvk/incl/jvk/sync/semaphore.hpp | 95 ++++----------------------- jvk/src/sync/semaphore.cpp | 79 +++------------------- jvk/tests/src/sync/semaphore_test.cpp | 42 ++++-------- lib/cth | 2 +- 6 files changed, 35 insertions(+), 188 deletions(-) diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/presenter.hpp index 14ee0c28..d7af475c 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -239,7 +239,7 @@ class Presenter { uint64_t frameNumber; ///< `Stage::frameNumber()`, the value of `stageSemaphore` to wait for }; - // no submitted_awaiter parameter: the job takes it from the stage semaphore and the frame + // no awaiter parameter: the job takes `submitted()` from the stage semaphore and the frame // number // the image as a parameter: the job reads no presenter state outside of the strand // the submit mark of the present job before awaited: acquire() no longer orders the present diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index 0d7fd7d4..52cf598d 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -11,6 +11,7 @@ #include +#include #include #include #include @@ -374,7 +375,7 @@ class Stage { * - `Semaphore::submitted()` of `semaphore()` with `frameNumber()` * @see `operator co_await()` */ - [[nodiscard]] constexpr submitted_awaiter submitted() const { + [[nodiscard]] constexpr cth::co::counter_event::awaiter submitted() const { return _stageSlot->semaphore.submitted(_frameNumber); } diff --git a/jvk/incl/jvk/sync/semaphore.hpp b/jvk/incl/jvk/sync/semaphore.hpp index bc547c5b..812e38bf 100644 --- a/jvk/incl/jvk/sync/semaphore.hpp +++ b/jvk/incl/jvk/sync/semaphore.hpp @@ -7,16 +7,14 @@ #include #include +#include #include #include #include #include -#include -#include #include #include -#include namespace jvk { @@ -61,37 +59,6 @@ class semaphore_awaiter : public cth::co::this_coro_awaiter_base, cth::ref_wrapper _semaphore; uint64_t _value; }; - -/** - * awaiter of `Semaphore::submitted()` - * @details resumes the caller on its context - */ -class submitted_awaiter : public cth::co::this_coro_awaiter_base { -public: - constexpr submitted_awaiter(Semaphore const& semaphore, uint64_t value) : - _semaphore{semaphore}, - _value{value} {} - - /** - * @return `Semaphore::submittedValue()` reached the value - */ - [[nodiscard]] bool await_ready() const; - - /** - * registers the resume of the caller with the semaphore - * @details resumes on the context of the caller - * @see `Semaphore::onSubmitted()` - */ - template requires cth::co::this_coro_compatible - void await_suspend(std::coroutine_handle caller); - - // no error: the jvk submit paths mark every signal value, also after an error of the submit - constexpr void await_resume() const noexcept {} - -private: - cth::ref_wrapper _semaphore; - uint64_t _value; -}; } namespace jvk { @@ -101,6 +68,7 @@ namespace jvk { * - holds a `cvk::TimelineSemaphore`, converts to it * - `wait()`: the reactor of the core waits for the gpu, no thread blocks * - `submitted()`: waits for the submit of a signal, the jvk submit paths call `markSubmitted()` + * - a semaphore with a pending `submitted()` does not move, see `cth::co::counter_event` */ class Semaphore { public: @@ -176,10 +144,11 @@ class Semaphore { * marks the signal of the value as submitted * @details * - for the jvk submit paths, after the `vkQueueSubmit2()` of the signal - * - posts the callbacks of `onSubmitted()` up to the value to the workers of the core - * - thread safe + * - posts the resume of every reached `submitted()` to the context of its caller + * - thread safe against `submitted()` and `submittedValue()` * @pre `created()` * @pre `value > submittedValue()` + * @pre no concurrent `markSubmitted()` */ void markSubmitted(uint64_t value) const; @@ -189,25 +158,14 @@ class Semaphore { * - not until the gpu reached the value * - resumes on the context of the caller * - marked -> no suspend + * - no error: the jvk submit paths mark every signal value, also after an error of the submit * @pre `created()` * @see `markSubmitted()`, `wait()` */ - [[nodiscard]] constexpr submitted_awaiter submitted(uint64_t value) const { - return submitted_awaiter{*this, value}; + [[nodiscard]] constexpr cth::co::counter_event::awaiter submitted(uint64_t value) const { + return _submitted.wait(value); } - /** - * calls the callback on a worker of the core once `markSubmitted()` reached the value - * @details - * - the callback form of `submitted()` - * - the callback gets an empty `std::error_code` - * - marked -> posts the callback at once - * - thread safe - * @pre `created()` - * @see `submitted()` - */ - void onSubmitted(uint64_t value, cth::co::context::await_func cb) const; - /** * waits until the semaphore reaches the value * @details @@ -241,7 +199,7 @@ class Semaphore { * @return the largest value of `markSubmitted()`, the initial value before * @details thread safe */ - [[nodiscard]] uint64_t submittedValue() const; + [[nodiscard]] uint64_t submittedValue() const { return _submitted.value(); } [[nodiscard]] constexpr bool created() const { return _semaphore.created(); } [[nodiscard]] constexpr VkSemaphore get() const { return _semaphore.get(); } @@ -254,31 +212,11 @@ class Semaphore { constexpr operator cvk::TimelineSemaphore const&() const { return _semaphore; } private: - /** - * callback of `onSubmitted()` - */ - struct SubmittedWaiter { - uint64_t value; - cth::co::context::await_func cb; - }; - - /** - * the submitted value with its waiters - */ - struct Submitted { - std::mutex mutex{}; - - uint64_t value = 0; ///< see `submittedValue()` - - /** the callbacks of `onSubmitted()` above `Submitted::value` */ - std::vector waiters{}; - }; - cth::ref_wrapper _core; cvk::TimelineSemaphore _semaphore; - //TODO review behind a std::unique_ptr: the mutex is not movable, the moves stay = default - std::unique_ptr _submittedPtr; + // mutable: markSubmitted() is const like the submit paths that call it + mutable cth::co::counter_event _submitted{}; ///< see `submittedValue()` public: Semaphore(Semaphore const& other) = delete; @@ -317,8 +255,7 @@ struct SemaphoreSubmitInfo { namespace jvk::dev { /** * callback that posts the callback to the context - * @details the reactor and `Semaphore::markSubmitted()` call on a worker, the awaiters resume on the context of the - * caller + * @details the reactor calls on a worker, the awaiter resumes on the context of the caller */ [[nodiscard]] inline cth::co::context::await_func post_to( cth::co::context const& context, @@ -339,12 +276,4 @@ template requires cth::co::this_coro_compatible void semaphore_awaiter::await_suspend(std::coroutine_handle caller) { awaitReactor(dev::post_to(caller.promise().context(), resume(caller))); } - -template requires cth::co::this_coro_compatible -void submitted_awaiter::await_suspend(std::coroutine_handle caller) { - _semaphore->onSubmitted( - _value, - dev::post_to(caller.promise().context(), [caller](std::error_code) { caller.resume(); }) - ); -} } diff --git a/jvk/src/sync/semaphore.cpp b/jvk/src/sync/semaphore.cpp index a2a401df..dde99bc6 100644 --- a/jvk/src/sync/semaphore.cpp +++ b/jvk/src/sync/semaphore.cpp @@ -5,9 +5,7 @@ #include -#include #include -#include namespace jvk { @@ -19,12 +17,7 @@ void semaphore_awaiter::awaitReactor(await_func cb) const { _semaphore->core().reactor().await(_semaphore->get(), _value, std::move(cb)); } -bool submitted_awaiter::await_ready() const { return _semaphore->submittedValue() >= _value; } - - -Semaphore::Semaphore(Core const& core) : _core{core}, - _semaphore{core}, - _submittedPtr{std::make_unique()} {} +Semaphore::Semaphore(Core const& core) : _core{core}, _semaphore{core} {} Semaphore::Semaphore(Core const& core, State const& state) : Semaphore{core} { wrap(state); } @@ -36,29 +29,21 @@ void Semaphore::wrap(State const& state) { optDestroy(); _semaphore.wrap(state); - - std::scoped_lock const lock{_submittedPtr->mutex}; - _submittedPtr->value = state.value; + _submitted = cth::co::counter_event{state.value}; } void Semaphore::create(uint64_t initialValue) { optDestroy(); _semaphore.create(initialValue); - - std::scoped_lock const lock{_submittedPtr->mutex}; - _submittedPtr->value = initialValue; + _submitted = cth::co::counter_event{initialValue}; } void Semaphore::destroy() { debug_check(*this); CTH_CRITICAL(core().reactor().pending(get()), "no wait() must be pending") {} - - { - std::scoped_lock const lock{_submittedPtr->mutex}; - CTH_CRITICAL(!_submittedPtr->waiters.empty(), "no submitted() must be pending") {} - _submittedPtr->value = 0; - } + // the assignment checks that no submitted() is pending + _submitted = cth::co::counter_event{}; _semaphore.destroy(); } @@ -66,62 +51,14 @@ void Semaphore::destroy() { Semaphore::State Semaphore::release() { debug_check(*this); CTH_CRITICAL(core().reactor().pending(get()), "no wait() must be pending") {} - - { - std::scoped_lock const lock{_submittedPtr->mutex}; - CTH_CRITICAL(!_submittedPtr->waiters.empty(), "no submitted() must be pending") {} - _submittedPtr->value = 0; - } + // the assignment checks that no submitted() is pending + _submitted = cth::co::counter_event{}; return _semaphore.release(); } void Semaphore::markSubmitted(uint64_t value) const { debug_check(*this); - - std::vector reached{}; - { - std::scoped_lock const lock{_submittedPtr->mutex}; - CTH_CRITICAL( - value <= _submittedPtr->value, - "value must be > submittedValue(), got {} <= {}", - value, - _submittedPtr->value - ) {} - - _submittedPtr->value = value; - - auto& waiters = _submittedPtr->waiters; - auto const marked = std::ranges::partition( - waiters, - [value](SubmittedWaiter const& waiter) { return waiter.value > value; } - ); - for(auto& waiter : marked) - reached.push_back(std::move(waiter.cb)); - waiters.erase(marked.begin(), marked.end()); - } - - auto const& workers = core().executor().context(); - for(auto& cb : reached) - workers.post([cb = std::move(cb)]() mutable { cb({}); }); -} - -void Semaphore::onSubmitted(uint64_t value, await_func cb) const { - debug_check(*this); - - { - std::scoped_lock const lock{_submittedPtr->mutex}; - if(value > _submittedPtr->value) { - _submittedPtr->waiters.push_back(SubmittedWaiter{value, std::move(cb)}); - return; - } - } - - core().executor().context().post([cb = std::move(cb)]() mutable { cb({}); }); -} - -uint64_t Semaphore::submittedValue() const { - std::scoped_lock const lock{_submittedPtr->mutex}; - return _submittedPtr->value; + _submitted.set(value); } } diff --git a/jvk/tests/src/sync/semaphore_test.cpp b/jvk/tests/src/sync/semaphore_test.cpp index 95cb11d2..bbb91ea5 100644 --- a/jvk/tests/src/sync/semaphore_test.cpp +++ b/jvk/tests/src/sync/semaphore_test.cpp @@ -14,7 +14,6 @@ #include #include #include -#include #include #include #include @@ -78,25 +77,6 @@ namespace { ); } - /** - * registers a callback for the submitted value - * @return the callback ran - */ - [[nodiscard]] std::future await_mark( - Semaphore const& semaphore, - uint64_t value - ) { - std::promise promise{}; - auto future = promise.get_future(); - semaphore.onSubmitted( - value, - [promise = std::move(promise)](std::error_code error) mutable { - promise.set_value(error); - } - ); - return future; - } - template [[nodiscard]] bool reached(std::future const& future) { return future.wait_for(REACHED_TIMEOUT) == std::future_status::ready; @@ -243,35 +223,35 @@ JVK_TEST(Semaphore, reached_values_do_not_suspend) { EXPECT_TRUE(context.core.executor().sync_wait(await_submitted(context.core, semaphore, 4))); } -JVK_TEST(Semaphore, mark_submitted_calls_the_waiters_up_to_the_value) { +JVK_TEST(Semaphore, mark_submitted_resumes_the_waits_up_to_the_value) { test::Context const context{}; Semaphore const semaphore{context.core, cvk::create}; - auto third = await_mark(semaphore, 3); - auto first = await_mark(semaphore, 1); - auto second = await_mark(semaphore, 2); + auto third = start(context.core, await_submitted(context.core, semaphore, 3)); + auto first = start(context.core, await_submitted(context.core, semaphore, 1)); + auto second = start(context.core, await_submitted(context.core, semaphore, 2)); semaphore.markSubmitted(2); EXPECT_EQ(semaphore.submittedValue(), 2); ASSERT_TRUE(reached(first)); ASSERT_TRUE(reached(second)); - EXPECT_FALSE(first.get()); - EXPECT_FALSE(second.get()); + EXPECT_TRUE(first.get()); + EXPECT_TRUE(second.get()); EXPECT_TRUE(pending(third)); semaphore.markSubmitted(3); ASSERT_TRUE(reached(third)); - EXPECT_FALSE(third.get()); + EXPECT_TRUE(third.get()); } -JVK_TEST(Semaphore, marked_value_calls_the_callback_at_once) { +JVK_TEST(Semaphore, a_marked_value_does_not_suspend) { test::Context const context{}; Semaphore const semaphore{context.core, cvk::create}; semaphore.markSubmitted(2); - auto result = await_mark(semaphore, 1); - - EXPECT_TRUE(reached(result)); + EXPECT_TRUE(semaphore.submitted(1).await_ready()); + EXPECT_TRUE(semaphore.submitted(2).await_ready()); + EXPECT_TRUE(context.core.executor().sync_wait(await_submitted(context.core, semaphore, 1))); } JVK_TEST(Semaphore, submitted_resumes_on_a_worker_after_the_mark) { diff --git a/lib/cth b/lib/cth index c4e62452..714a2e7b 160000 --- a/lib/cth +++ b/lib/cth @@ -1 +1 @@ -Subproject commit c4e62452d9c133a5cb7a060d5ff18e79607c4630 +Subproject commit 714a2e7b3fa0f1fd5fa62da3e2f944cc862b98d1 From 7e81a951b54df1f92723143d0c020b7bcc854623 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:27:13 +0100 Subject: [PATCH 23/68] lib: cth with the lifetime fix of counter_event (codethinki/cth#34) --- lib/cth | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/cth b/lib/cth index 714a2e7b..a9b2c8d3 160000 --- a/lib/cth +++ b/lib/cth @@ -1 +1 @@ -Subproject commit 714a2e7b3fa0f1fd5fa62da3e2f944cc862b98d1 +Subproject commit a9b2c8d3387d403fa00cadbfbc35122d025f4276 From a72ba92fb057519042ad38b979c284ec004827aa Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:40:32 +0100 Subject: [PATCH 24/68] jvk: Queue::submit() and Queue::present() with jvk::SubmitInfo, no vkQueue call outside Queue - submit(): vkQueueSubmit2 in the strand, then the marks of the jvk signals; a failed submit marks nothing - present(): submit and vkQueuePresentKHR in one strand job, then the marks: the present order stays - the graph: dev::SlotSubmit builds the jvk::SubmitInfo, the fallback submit goes through Queue::submit() - the presenter: an out of date present shows in the next acquire(), no flag written after the mark --- jvk/incl/jvk/base/queue.hpp | 86 +++++++++++++++- jvk/incl/jvk/graph/presenter.hpp | 28 +++--- jvk/incl/jvk/graph/stage.hpp | 48 ++++----- jvk/incl/jvk/graph/stage_graph.hpp | 15 +-- jvk/incl/jvk/utility/first_error.hpp | 21 ---- jvk/src/base/queue.cpp | 94 +++++++++++++++++- jvk/src/graph/presenter.cpp | 53 +++------- jvk/src/graph/stage.cpp | 53 +++------- jvk/src/graph/stage_graph.cpp | 32 +++--- jvk/tests/src/base/queue_test.cpp | 142 +++++++++++++++++++++++++++ 10 files changed, 404 insertions(+), 168 deletions(-) diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index 5be53a4e..eb388de5 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -1,6 +1,7 @@ #pragma once #include "jvk/cmd/cmd_buffer.hpp" #include "jvk/sync/semaphore.hpp" +#include "jvk/utility/first_error.hpp" #include "cvk/base/queue/queue.hpp" #include "cvk/base/queue/submit_info.hpp" @@ -15,24 +16,47 @@ #include #include +#include namespace cth::co { class scheduler; } +namespace cvk { +class Swapchain; +} + namespace jvk { class Core; -//TODO review no jvk::Semaphore per queue that every submit signals (optional, 2026-11-09), it does not fit yet: -// submits go through vk() in the strand, the queue sees none of them, only the graph could add the signal +// in queue.hpp next to Queue: it is small, no own header +/** + * one batch of a submit on a `Queue` + * @details + * - `Queue::submit()` and `Queue::present()` mark the jvk signals after the submit, see + * `Semaphore::markSubmitted()` + * - the binary semaphores get no mark + */ +struct SubmitInfo { + /** the gpu executes them in order */ + std::vector> cmdBuffers{}; + + std::vector waits{}; + std::vector binaryWaits{}; + + std::vector signals{}; ///< marked after the submit + std::vector binarySignals{}; +}; + /** * serialized vulkan queue * @details * - refers to the queue of the cvk core * - runs its work in one strand + * - submits and presents, marks the jvk signals of its submits * - releases the queue family ownership of resources - * @see `release()` + * @see `submit()`, `present()`, `release()` */ class Queue { public: @@ -52,6 +76,37 @@ class Queue { */ void waitIdle() const; + /** + * submits the batch in the strand, then marks the jvk signals + * @details a failed submit marks nothing: the caller submits a fallback, see + * `dev::fallback_submit()` + * @pre the preconditions of `cvk::Queue::submit()` + * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` + * @see `present()` + */ + [[nodiscard]] cth::co::executor_task submit(SubmitInfo) const; + + /** + * submits the batch and presents the image in one job of the strand, then marks the jvk signals + * @details + * - the submit signals `cvk::Swapchain::presentSemaphore()` of the image too + * - no other job of the strand runs between the submit and the present + * - a failed submit marks nothing and presents nothing + * - a failed present marks the signals before it throws: the submit reached the queue + * @param swapchain of the image + * @param imageIdx of the acquired image + * @return `VK_SUCCESS`, `VK_SUBOPTIMAL_KHR` or `VK_ERROR_OUT_OF_DATE_KHR` + * @pre `cvk::Queue::canPresent()` + * @pre the preconditions of `cvk::Queue::submit()` and of `cvk::Swapchain::present()` + * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` + * @throws cvk::vk_result_exception other result of `vkQueuePresentKHR()` + */ + [[nodiscard]] cth::co::executor_task present( + SubmitInfo, + cvk::Swapchain& swapchain, + uint32_t imageIdx + ) const; + // an executor_task: the receiving submit job awaits it before its own submit, so the release is // submitted first and the counter only changes in the strand (returning at once needs a lock around the value // and the post) @@ -97,6 +152,13 @@ class Queue { [[nodiscard]] constexpr VkQueue get() const { return _queue->get(); } private: + /** + * submits the batch through the cvk queue + * @pre runs in the strand + * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` + */ + void submitInStrand(SubmitInfo const&) const; + /** * command buffer of one release * @details owns its command pool, see `PrimaryCmdBuffer` @@ -134,3 +196,21 @@ class Queue { Queue& operator=(Queue&& other) noexcept = default; }; } + +namespace jvk::dev { +/** + * the empty submit after a failed submit: the waiters of its jvk signals go on + * @details + * - `Queue::submit()` marks the signals + * - `VK_ERROR_DEVICE_LOST` -> stores the error, marks the signals: the gpu waits end on their own + * @param queue of the failed submit + * @param info waits and signals of the failed submit, no command buffers + * @param[out] error gets a device loss + * @throws cvk::vk_result_exception other results of the submit: the waiters would hang + */ +[[nodiscard]] cth::co::executor_task fallback_submit( + Queue const& queue, + SubmitInfo info, + first_error& error +); +} diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/presenter.hpp index d7af475c..9c767e40 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -17,7 +17,6 @@ #include #include -#include #include #include #include @@ -159,7 +158,7 @@ class Presenter { * - waits until the last present job called `vkQueuePresentKHR()`: the acquire and the present share the * swapchain, a blocking acquire before that present delays it by one refresh (FIFO) * - runs on `Queue::scheduler()`, outside the strand - * - `VK_ERROR_OUT_OF_DATE_KHR` of a present or an acquire of the current swapchain, or a changed + * - `VK_ERROR_OUT_OF_DATE_KHR` of an acquire of the current swapchain, or a changed * `cvk::Surface::extent()` -> recreates the swapchain first, erases the old images in the graph of the stage, * see `StageGraph::erase()`, `Swapchain::recreate()` * - an acquired image without a present, e.g. after an exception or a skip: waits until the gpu finished the @@ -190,7 +189,8 @@ class Presenter { * - transitions the image to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` from its last state in the stage primary * - a stage of another queue family: the job releases the image on the stage queue, the images stay * `VK_SHARING_MODE_EXCLUSIVE` - * - `VK_ERROR_OUT_OF_DATE_KHR` -> the next `acquire()` recreates the swapchain + * - `VK_ERROR_OUT_OF_DATE_KHR` -> the acquire of the next `acquire()` fails with it, then + * recreates the swapchain * - a failure of the job: the next `acquire()` rethrows it * @pre an acquired image without a present * @pre `Stage::status()` is `SUBMITTED` @@ -252,15 +252,17 @@ class Presenter { * - off the strand: awaits `Semaphore::submitted()` of `Presenter::_semaphore` with the value before: the present * jobs submit and present in the order of `present()` * - off the strand: records the command buffer, the present jobs run one at a time - * - in the strand of the queue: submits through `Queue::vk()`, presents through the current swapchain: a - * recreation only happens in `acquire()`, after the last present - * - the submit waits for the semaphore of the stage and the release, signals the present semaphore and - * `Presenter::_semaphore` with the value + * - `Queue::present()` with the current swapchain: a recreation only happens in `acquire()`, + * after the last present + * - the submit waits for the semaphore of the stage and the release, signals + * `Presenter::_semaphore` with the value, `Queue::present()` marks it after the present * - the command buffer: the acquire half of another family, the transition to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` - * - `Semaphore::markSubmitted()` of `Presenter::_semaphore` with the value, after the present + * - the result of the present: unused, the next `acquire()` runs after the mark * @details the errors: - * - a failed submit: stores the error, then an empty submit that signals only `Presenter::_semaphore`, no present - * - a failed empty submit: `VK_ERROR_DEVICE_LOST` -> stores the error, else terminates: the waiters would hang + * - a failed submit: stores the error, then `dev::fallback_submit()` that signals only + * `Presenter::_semaphore`, no present + * - a failed empty submit: `VK_ERROR_DEVICE_LOST` -> stores the error, marks, else terminates: + * the waiters would hang * - a failed present: stores the error * @param image the acquired image * @param lastState of the image in the stage primary @@ -328,10 +330,8 @@ class Presenter { /** the acquired image without a present */ std::optional _acquiredOpt = std::nullopt; - /** - * `VK_ERROR_OUT_OF_DATE_KHR` of a present of the current swapchain, the next `acquire()` recreates the swapchain - */ - std::atomic _outOfDate = false; + /** an acquire of the current swapchain gave no image, the next `acquire()` round recreates */ + bool _outOfDate = false; dev::first_error _error{}; ///< the first error of a job or a scope, `acquire()` rethrows it diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index 52cf598d..49e56397 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -43,9 +43,9 @@ namespace jvk::dev { * @details * - the graph builds it once, at its construction * - holds the values of the next submit or skip of the slot - * - a skip submits the waits and the signal without the command buffers + * - builds the `SubmitInfo` of the next submit or skip: a skip has no command buffers */ -struct SubmitInfo { +struct SlotSubmit { /** `StageSlot::prologue`, `StageSlot::primary` */ std::vector> cmdBuffers{}; @@ -62,34 +62,23 @@ struct SubmitInfo { SemaphoreSubmitInfo signal; ///< `StageSlot::semaphore` with the frame number /** - * submits the command buffers on the queue - * @details waits for `SubmitInfo::waits` and the extra waits, signals `SubmitInfo::signal` - * @param queue of the stage slot - * @param extraWaits the jvk waits of the stage and of the releases + * the skip of the slot: the waits and the signal without the command buffers + * @details waits for `SlotSubmit::waits` and the extra waits, signals `SlotSubmit::signal` + * @param extraWaits the jvk waits of the stage * @param extraBinaryWaits the binary waits of the stage - * @param prologue `false` -> without `StageSlot::prologue`: the prologue is empty - * @pre runs in the strand of the queue - * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` - * @see `skip()` + * @see `addCmdBuffers()` */ - void submit( - Queue const& queue, + [[nodiscard]] SubmitInfo skipInfo( std::span extraWaits, - std::span extraBinaryWaits, - bool prologue + std::span extraBinaryWaits ) const; /** - * submits the waits and the signal without the command buffers - * @details the parameters of `submit()` - * @pre runs in the strand of the queue - * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` + * adds the command buffers of the submit, the prologue first + * @param[out] info gets the command buffers + * @param prologue `false` -> without `StageSlot::prologue`: the prologue is empty */ - void skip( - Queue const& queue, - std::span extraWaits, - std::span extraBinaryWaits - ) const; + void addCmdBuffers(SubmitInfo& info, bool prologue) const; /** * advances every wait and signal value to the next frame of the slot @@ -109,7 +98,7 @@ struct RetainedResources { std::vector buffers{}; }; -// a constructor, no aggregate: `SubmitInfo::signal` and `SubmitInfo::cmdBuffers` refer to members, +// a constructor, no aggregate: `SlotSubmit::signal` and `SlotSubmit::cmdBuffers` refer to members, // the mutex does not move /** * resources of a stage in one frame slot @@ -122,8 +111,9 @@ struct StageSlot { * creates the semaphore and the command buffers of the stage slot * @details * - the semaphore starts at `StageGraph::firstFrameNumber() - 1` - * - `SubmitInfo::signal`: the semaphore with the first frame number of the slot - * - the graph sets `StageSlot::previous` and the waits of `StageSlot::submitInfo` once all slots exist + * - `SlotSubmit::signal`: the semaphore with the first frame number of the slot + * - the graph sets `StageSlot::previous` and the waits of `StageSlot::slotSubmit` once all + * slots exist * - `secondaries`: `StageConfig::secondaries` of the stage * @pre `StageGraph::firstFrameNumber()` is set * @throws cvk::vk_result_exception result of a create of the semaphore or the command buffers @@ -162,8 +152,8 @@ struct StageSlot { // a member of the stage slot: it refers to StageSlot::semaphore, StageSlot::prologue, // StageSlot::primary and the semaphores of the waited stage slots, they live as long as the graph - /** the waits and the signal of the next submit or skip, see `SubmitInfo::next()` */ - SubmitInfo submitInfo; + /** the waits and the signal of the next submit or skip, see `SlotSubmit::next()` */ + SlotSubmit slotSubmit; /** the stage in the frame slot before, submits first */ cth::ref_wrapper previous; @@ -471,7 +461,7 @@ class scoped_submit { } namespace jvk::dev { -constexpr void SubmitInfo::next(size_t frameSlots) { +constexpr void SlotSubmit::next(size_t frameSlots) { for(auto& wait : waits) wait.value += frameSlots; signal.value += frameSlots; diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index 1f9e5fa8..07125419 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -198,19 +198,22 @@ class StageGraph { /** * submit job of `submit()` and `skip()` * @details the order: - * - off the strand: awaits `Semaphore::submitted()` of the stage in the frame before, of the waits of - * `StageSlot::submitInfo` and of every jvk extra wait: the appends follow the dependency order + * - off the strand: awaits `Semaphore::submitted()` of the stage in the frame before, of the + * waits of `StageSlot::slotSubmit` and of every jvk extra wait: the appends follow the + * dependency order * - the binary extra waits: no await on the cpu + * - `SlotSubmit::skipInfo()` of the frame, then `SlotSubmit::next()` * - `SUBMITTED`: `append()` of the states of the primary under `StageGraph::_statesMutex`, `release()` of the * release halves, records the prologue, an empty prologue: no record, the submit without it - * - in the strand: `SubmitInfo::submit()` with the release waits - * - `SKIPPED` or a failed submit: in the strand, `SubmitInfo::skip()` - * - in the strand: `SubmitInfo::next()`, then `Semaphore::markSubmitted()` of the slot with the frame number + * - `SUBMITTED`: `Queue::submit()` with the release waits, it marks the slot with the frame + * number + * - `SKIPPED` or a failed submit: `dev::fallback_submit()` of the skip info * - on the workers of the core: after the gpu finished, erases the states of the retained resources, then * `Stasis::clear()` to `stasisEnd` * @details the errors: * - a failed submit: stores the error, see `dev::first_error`, then skips - * - a failed skip: `VK_ERROR_DEVICE_LOST` -> stores the error, else terminates: the waiters would hang + * - a failed skip: `VK_ERROR_DEVICE_LOST` -> stores the error, marks the slot, else terminates: + * the waiters would hang * - a failed gpu wait: stores the error, keeps the retained objects for the destruction of the graph * @param targetStatus the status the job reaches: `SUBMITTED` or `SKIPPED` * @param stasisEnd `Stasis::end()` of the stage slot at the submit or the skip diff --git a/jvk/incl/jvk/utility/first_error.hpp b/jvk/incl/jvk/utility/first_error.hpp index 3b926e35..31409a08 100644 --- a/jvk/incl/jvk/utility/first_error.hpp +++ b/jvk/incl/jvk/utility/first_error.hpp @@ -1,10 +1,6 @@ #pragma once -#include "cvk/utility/vk_exceptions.hpp" - #include -#include -#include #include #include #include @@ -58,21 +54,4 @@ class first_error { mutable std::mutex _mutex{}; std::exception_ptr _errorPtr = nullptr; }; - -/** - * the empty submit after a failed submit: the waiters of its signals go on - * @details `VK_ERROR_DEVICE_LOST` -> stores the error, the waits end on their own - * @param submit runs the empty submit - * @param[out] error gets a device loss - * @throws cvk::vk_result_exception other results of the submit: the waiters would hang - */ -template -void fallback_submit(Submit&& submit, first_error& error) { - try { std::forward(submit)(); } - catch(cvk::vk_result_exception const& e) { - if(e.vkResult() != VK_ERROR_DEVICE_LOST) - throw; - error.store(std::current_exception()); - } -} } diff --git a/jvk/src/base/queue.cpp b/jvk/src/base/queue.cpp index 3197aba6..cae37807 100644 --- a/jvk/src/base/queue.cpp +++ b/jvk/src/base/queue.cpp @@ -2,13 +2,48 @@ #include "jvk/base/core.hpp" +#include "cvk/surface/swapchain.hpp" +#include "cvk/utility/vk_exceptions.hpp" + #include #include #include +#include +#include +#include namespace jvk { +namespace { + /** + * the cvk batch: the jvk semaphores, then the binary ones + */ + [[nodiscard]] cvk::SubmitInfo to_cvk(SubmitInfo const& info) { + cvk::SubmitInfo vkInfo{}; + vkInfo.cmdBuffers.reserve(info.cmdBuffers.size()); + for(PrimaryCmdBuffer const& cmdBuffer : info.cmdBuffers) + vkInfo.cmdBuffers.emplace_back(cmdBuffer); + + vkInfo.waits.reserve(info.waits.size() + info.binaryWaits.size()); + vkInfo.waits.append_range(info.waits); + vkInfo.waits.append_range(info.binaryWaits); + + vkInfo.signals.reserve(info.signals.size() + info.binarySignals.size()); + vkInfo.signals.append_range(info.signals); + vkInfo.signals.append_range(info.binarySignals); + return vkInfo; + } + + /** + * marks the jvk signals, see `Semaphore::markSubmitted()` + */ + void mark(std::span signals) { + for(auto const& signal : signals) + signal.semaphore->markSubmitted(signal.value); + } +} + Queue::Queue(Core const& core, cvk::Queue const& queue, cth::co::scheduler const& queueScheduler) : _core{core}, _queue{queue}, @@ -25,6 +60,38 @@ void Queue::waitIdle() const { ); } +cth::co::executor_task Queue::submit(SubmitInfo info) const { + co_await executor().schedule(); + + submitInStrand(info); + mark(info.signals); +} + +cth::co::executor_task Queue::present( + SubmitInfo info, + cvk::Swapchain& swapchain, + uint32_t imageIdx +) const { + info.binarySignals.emplace_back(swapchain.presentSemaphore(imageIdx)); + + // no suspension between the submit and the present: the presents follow the order of the + // submits + co_await executor().schedule(); + submitInStrand(info); + + // the marks after the present: a waiter for them uses the swapchain after vkQueuePresentKHR() + VkResult result{}; + try { result = swapchain.present(imageIdx); } + catch(cvk::vk_result_exception const&) { + // the submit reached the queue: the gpu signals the values + mark(info.signals); + throw; + } + mark(info.signals); + + co_return result; +} + cth::co::executor_task Queue::release(cvk::Barrier barriers) const { // all in the strand: it serializes the release command buffers, the counter values follow the submit order co_await executor().schedule(); @@ -37,15 +104,18 @@ cth::co::executor_task Queue::release(cvk::Barrier barriers cmd.end(); SemaphoreSubmitInfo const signal{.semaphore = _released, .value = _released.next()}; - _queue->submit({.cmdBuffers = {cmd}, .signals = {signal}}); + SubmitInfo const info{.cmdBuffers = {cmd}, .signals = {signal}}; + submitInStrand(info); // after the submit: a failed submit leaves the command buffer free releaseCmd.value = signal.value; - _released.markSubmitted(signal.value); + mark(info.signals); co_return signal; } +void Queue::submitInStrand(SubmitInfo const& info) const { _queue->submit(to_cvk(info)); } + auto Queue::freeReleaseCmd() const -> ReleaseCmd& { auto const reached = _released.gpuValue(); @@ -60,4 +130,24 @@ auto Queue::freeReleaseCmd() const -> ReleaseCmd& { ReleaseCmd{PrimaryCmdBuffer{*_core, _queue->familyIndex(), cvk::create}} ); } + +namespace dev { + cth::co::executor_task fallback_submit( + Queue const& queue, + SubmitInfo info, + first_error& error + ) { + // a copy: the submit takes the info + auto const signals = info.signals; + + try { co_await queue.submit(std::move(info)); } + catch(cvk::vk_result_exception const& e) { + if(e.vkResult() != VK_ERROR_DEVICE_LOST) + throw; + error.store(std::current_exception()); + // the failed submit marked nothing: the waiters of the marks go on + mark(signals); + } + } +} } diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index 2724bee5..3e4e67a9 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -227,7 +227,6 @@ cth::co::executor_task Presenter::presentJob( // buffers and signals the value before co_await _semaphore.submitted(value - 1); - bool submitted = false; try { ImageState const presentState{ .layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, @@ -269,47 +268,27 @@ cth::co::executor_task Presenter::presentJob( submit.cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); barrier.execute(submit.cmd); submit.cmd.end(); - - // in the strand the submit and the present, no suspension: the presents follow the order of present() - co_await queue.executor().schedule(); - queue.vk().submit( - { - .cmdBuffers = {submit.cmd}, - .waits = {waits.begin(), waits.end()}, - .signals = { - cvk::SemaphoreSubmitInfo{_swapchain.current().presentSemaphore(image.imageIdx)}, - signal - }, - } - ); + // before the submit: the empty submit of a failed one signals the value too submit.value = value; - submitted = true; - } - catch(...) { _error.store(std::current_exception()); } - // a failed submit: the timeline signal for the waits on the presenter, the present semaphore stays unsignaled - if(!submitted) { - co_await queue.executor().schedule(); - dev::fallback_submit( - [&] { - queue.vk().submit({.waits = {waits.begin(), waits.end()}, .signals = {signal}}); - }, - _error + // the swapchain of the image is the current one: a recreation only happens in acquire(), + // after the mark of the last present + // no use of the result: the next acquire() runs after the mark, an out of date swapchain + // fails its acquire + static_cast( + co_await queue.present( + {.cmdBuffers = {submit.cmd}, .waits = waits, .signals = {signal}}, + _swapchain.current(), + image.imageIdx + ) ); } + catch(...) { _error.store(std::current_exception()); } - if(submitted) { - try { - // the swapchain of the image is the current one: a recreation only happens in acquire(), after the last - // present called vkQueuePresentKHR() - if(_swapchain.current().present(image.imageIdx) == VK_ERROR_OUT_OF_DATE_KHR) - _outOfDate = true; - } - catch(cvk::vk_result_exception const&) { _error.store(std::current_exception()); } - } - - // after the present: the next acquire() awaits it - _semaphore.markSubmitted(value); + // a failed submit marks nothing: the empty submit signals the value for the waits on the + // presenter + if(_semaphore.submittedValue() < value) + co_await dev::fallback_submit(queue, {.waits = waits, .signals = {signal}}, _error); } void Presenter::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { diff --git a/jvk/src/graph/stage.cpp b/jvk/src/graph/stage.cpp index c03af750..99233271 100644 --- a/jvk/src/graph/stage.cpp +++ b/jvk/src/graph/stage.cpp @@ -37,50 +37,25 @@ namespace { .samplerHeapPtr = heaps.createsSamplerHeap() ? &core.samplerHeap().vk() : nullptr, }; } - - /** - * the waits of the submit info, then the extra waits - */ - [[nodiscard]] std::vector all_waits( - SubmitInfo const& info, - std::span extraWaits, - std::span extraBinaryWaits - ) { - std::vector waits{}; - waits.reserve(info.waits.size() + extraWaits.size() + extraBinaryWaits.size()); - waits.append_range(info.waits); - waits.append_range(extraWaits); - waits.append_range(extraBinaryWaits); - return waits; - } } -void SubmitInfo::submit( - Queue const& queue, +SubmitInfo SlotSubmit::skipInfo( std::span extraWaits, - std::span extraBinaryWaits, - bool prologue + std::span extraBinaryWaits ) const { - cvk::SubmitInfo submitInfo{ - .waits = all_waits(*this, extraWaits, extraBinaryWaits), - .signals = {signal} + SubmitInfo info{ + .binaryWaits = {extraBinaryWaits.begin(), extraBinaryWaits.end()}, + .signals = {signal}, }; - submitInfo.cmdBuffers.reserve(cmdBuffers.size()); - // the prologue comes first - for(PrimaryCmdBuffer const& cmdBuffer : cmdBuffers | std::views::drop(prologue ? 0 : 1)) - submitInfo.cmdBuffers.emplace_back(cmdBuffer); - - queue.vk().submit(submitInfo); + info.waits.reserve(waits.size() + extraWaits.size()); + info.waits.append_range(waits); + info.waits.append_range(extraWaits); + return info; } -void SubmitInfo::skip( - Queue const& queue, - std::span extraWaits, - std::span extraBinaryWaits -) const { - queue.vk().submit( - {.waits = all_waits(*this, extraWaits, extraBinaryWaits), .signals = {signal}} - ); +void SlotSubmit::addCmdBuffers(SubmitInfo& info, bool prologue) const { + // the prologue comes first + info.cmdBuffers.append_range(cmdBuffers | std::views::drop(prologue ? 0 : 1)); } StageSlot::StageSlot( @@ -98,12 +73,12 @@ StageSlot::StageSlot( queue{queue}, heaps{stage_heaps(graph.core(), queue)}, semaphore{graph.core(), cvk::create, graph.firstFrameNumber() - 1}, - submitInfo{.signal = {.semaphore = semaphore, .value = graph.firstFrameNumber() + slot}}, + slotSubmit{.signal = {.semaphore = semaphore, .value = graph.firstFrameNumber() + slot}}, previous{*this}, prologue{graph.core(), queue.vk().familyIndex(), cvk::create}, primary{graph.core(), queue.vk().familyIndex(), cvk::create}, stasis{graph.core()} { - submitInfo.cmdBuffers = {prologue, primary}; + slotSubmit.cmdBuffers = {prologue, primary}; this->secondaries.reserve(secondaries); for(size_t i = 0; i < secondaries; ++i) diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index 4117d881..0ff4b3e5 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -96,7 +96,7 @@ StageGraph::StageGraph(Core& core, Config config) : auto const& waited = _frameSlots[waitedSlot].stageSlots[wait.stageId]; // the first frame of the slot waits for the frame frameOffset frames before it - stageSlot.submitInfo.waits.push_back( + stageSlot.slotSubmit.waits.push_back( SemaphoreSubmitInfo{ .semaphore = waited.semaphore, .stages = wait.stages, @@ -293,17 +293,22 @@ cth::co::executor_task StageGraph::submitJob( Stasis::pos stasisEnd, Stage::Status targetStatus ) { - auto const& info = stageSlot.submitInfo; + auto& slotSubmit = stageSlot.slotSubmit; auto const& queue = *stageSlot.queue; // the marks first, off the strand: a wait before the signal on one queue would block it, the appends follow the // dependency order co_await stageSlot.previous->semaphore.submitted(frameNumber - 1); - for(auto const& wait : info.waits) + for(auto const& wait : slotSubmit.waits) co_await wait.semaphore->submitted(wait.value); for(auto const& wait : extraWaits) co_await wait.semaphore->submitted(wait.value); + // the values of this frame, then next(): the job of the next frame of the slot reads them after + // the mark + auto info = slotSubmit.skipInfo(extraWaits, extraBinaryWaits); + slotSubmit.next(_config.frameSlots); + bool submitted = false; if(targetStatus == Stage::Status::SUBMITTED) { try { @@ -313,8 +318,9 @@ cth::co::executor_task StageGraph::submitJob( std::scoped_lock const lock{_statesMutex}; append(stageSlot.primary.states(), queue, prologue, releases); } + // the skip of a failed submit waits for the releases too if(!releases.empty()) - extraWaits.append_range(co_await release(std::move(releases))); + info.waits.append_range(co_await release(std::move(releases))); // off the strand: the prologue belongs to the job of the slot, an empty one stays out of the submit bool const withPrologue = !prologue.empty(); @@ -324,25 +330,17 @@ cth::co::executor_task StageGraph::submitJob( stageSlot.prologue.end(); } - co_await queue.executor().schedule(); - info.submit(queue, extraWaits, extraBinaryWaits, withPrologue); + auto submitInfo = info; + slotSubmit.addCmdBuffers(submitInfo, withPrologue); + co_await queue.submit(std::move(submitInfo)); submitted = true; } catch(...) { _error.store(std::current_exception()); } } // a skip, also of a failed submit: the gpu waits of other stages and the waits in ~StageGraph() end - if(!submitted) { - co_await queue.executor().schedule(); - dev::fallback_submit([&] { info.skip(queue, extraWaits, extraBinaryWaits); }, _error); - } - - stageSlot.submitInfo.next(_config.frameSlots); - stageSlot.semaphore.markSubmitted(frameNumber); - - // back on the workers: the cleanup destroys retained objects, the strand stays free for the next submits, one post - // per stage and frame, off the critical path - co_await core().executor().schedule(); + if(!submitted) + co_await dev::fallback_submit(queue, std::move(info), _error); // the job never touches the stage: nextFrame() destroys the stages after the gpu wait bool reached = false; diff --git a/jvk/tests/src/base/queue_test.cpp b/jvk/tests/src/base/queue_test.cpp index 62fc5802..8850a468 100644 --- a/jvk/tests/src/base/queue_test.cpp +++ b/jvk/tests/src/base/queue_test.cpp @@ -5,21 +5,26 @@ #include "jvk/data/buffer.hpp" #include "jvk/data/image.hpp" +#include "jvk/graph/swapchain.hpp" #include "cvk/base/core.hpp" #include "cvk/base/queue/submit_info.hpp" #include "cvk/render/sync/barrier.hpp" #include "cvk/render/sync/fence.hpp" +#include "cvk/render/sync/semaphore.hpp" #include "cvk/render/sync/timeline_semaphore.hpp" +#include "cvk/utility/vk_exceptions.hpp" #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -146,6 +151,28 @@ namespace { return true; } + /** + * @param[out] coreOpt gets a core with a queue that presents to the surface + * @return `false` -> no device presents to a headless surface + */ + [[nodiscard]] bool create_present_core( + std::optional& coreOpt, + test::Context const& context, + cvk::Surface const& surface + ) { + auto config = test::Context::CONFIG; + config.vk.queueProperties = {GRAPHICS | PRESENT}; + try { + coreOpt.emplace( + context.instance, + std::move(config), + std::array{cth::ref_wrapper{surface}} + ); + } + catch(cvk::cvk_exception const&) { return false; } + return true; + } + /** * submits inside the strand */ @@ -389,4 +416,119 @@ JVK_TEST(Queue, several_releases_in_a_row) { EXPECT_EQ(next.value, released.back().value + 1); owner.waitIdle(); } + +JVK_TEST(Queue, submit_marks_the_jvk_signals) { + test::Context const context{}; + auto const& queue = context.core.queue(0); + Semaphore const first{context.core, cvk::create}; + Semaphore const second{context.core, cvk::create}; + + context.core.executor().sync_wait( + queue.submit( + {.signals = {{.semaphore = first, .value = 1}, {.semaphore = second, .value = 2}}} + ) + ); + + EXPECT_EQ(first.submittedValue(), 1); + EXPECT_EQ(second.submittedValue(), 2); + static_cast(second).wait(2); + EXPECT_EQ(first.gpuValue(), 1); +} + +JVK_TEST(Queue, submit_waits_for_the_jvk_and_the_binary_waits) { + test::Context const context{}; + auto const& queue = context.core.queue(0); + cvk::Semaphore const binary{context.core, cvk::create}; + Semaphore const gate{context.core, cvk::create}; + Semaphore const done{context.core, cvk::create}; + + auto const& executor = context.core.executor(); + executor.sync_wait( + queue.submit({.signals = {{.semaphore = gate, .value = 1}}, .binarySignals = {binary}}) + ); + executor.sync_wait( + queue.submit( + { + .waits = {{.semaphore = gate, .value = 1}}, + .binaryWaits = {binary}, + .signals = {{.semaphore = done, .value = 1}}, + } + ) + ); + + EXPECT_EQ(done.submittedValue(), 1); + static_cast(done).wait(1); +} + +JVK_TEST(Queue, fallback_submit_marks_through_the_submit) { + test::Context const context{}; + auto const& queue = context.core.queue(0); + Semaphore const semaphore{context.core, cvk::create}; + dev::first_error error{}; + + context.core.executor().sync_wait( + dev::fallback_submit(queue, {.signals = {{.semaphore = semaphore, .value = 1}}}, error) + ); + + EXPECT_FALSE(error); + EXPECT_EQ(semaphore.submittedValue(), 1); + static_cast(semaphore).wait(1); +} + +JVK_TEST(Queue, present_submits_presents_and_marks) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto const& core = *coreOpt; + auto const& queue = core.queue(0); + + Swapchain swapchain{core, queue.vk(), surface}; + swapchain.create({}, EXTENT); + auto& current = swapchain.current(); + Semaphore const presented{core, cvk::create}; + PrimaryCmdBuffer cmd{core, queue.vk().familyIndex(), cvk::create}; + + // two presents in a row: each one transitions its image after the wait for its acquire + for(uint64_t value = 1; value <= 2; ++value) { + cvk::Semaphore const acquired{core, cvk::create}; + auto const imageIdxOpt = swapchain.acquire(acquired).imageIndex; + ASSERT_TRUE(imageIdxOpt.has_value()); + + // the command buffer of the present before is free once the gpu reached its value + static_cast(presented).wait(value - 1); + cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); + cvk::Barrier barrier{}; + barrier.add( + current.image(*imageIdxOpt), + cvk::ImageBarrierInfo{ + .src = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, + .dst = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, + .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + } + ); + barrier.execute(cmd); + cmd.end(); + + auto const result = core.executor().sync_wait( + queue.present( + { + .cmdBuffers = {cmd}, + .binaryWaits = {acquired}, + .signals = {{.semaphore = presented, .value = value}}, + }, + current, + *imageIdxOpt + ) + ); + + EXPECT_TRUE(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) + << "present result: " << result; + EXPECT_EQ(presented.submittedValue(), value); + // the acquire semaphore goes after the gpu waited for it + static_cast(presented).wait(value); + } +} } From 0d3567dc7c2aaaeb0d3c2f877ba912cc16067bda Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:43:55 +0100 Subject: [PATCH 25/68] jvk: Core moves while it is not created - the cvk core and the workers behind std::unique_ptr: the reactor and the heaps refer to them from the base constructor on - the moves are = default, a created core neither moves nor takes a move assignment --- jvk/incl/jvk/base/core.hpp | 24 ++++++++++++++------ jvk/src/base/core.cpp | 39 ++++++++++++++++++-------------- jvk/tests/src/base/core_test.cpp | 30 ++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 24 deletions(-) diff --git a/jvk/incl/jvk/base/core.hpp b/jvk/incl/jvk/base/core.hpp index fe718069..c9d7a168 100644 --- a/jvk/incl/jvk/base/core.hpp +++ b/jvk/incl/jvk/base/core.hpp @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -31,6 +32,8 @@ namespace jvk { * jvk core * @details owns the cvk core, the workers, the timeline reactor, the serialized queues and the descriptor heaps * @details the indices of one vulkan queue share one `Queue` + * @details a created core neither moves nor takes a move assignment: its queues, heaps, command + * buffers and reactor refer to it */ class Core { public: @@ -125,7 +128,7 @@ class Core { */ [[nodiscard]] constexpr cth::co::executor executor() const { debug_check(*this); - return cth::co::executor{_workers}; + return cth::co::executor{*_workersPtr}; } /** @@ -155,9 +158,12 @@ class Core { * the cvk core * @attention `cvk::Core::queue()` returns the queue without its strand */ - constexpr operator cvk::Core const&() const { return _core; } + constexpr operator cvk::Core const&() const { return *_corePtr; } - [[nodiscard]] constexpr bool created() const { return _core.created(); } + // a moved-from core has no cvk core, its destructor asks + [[nodiscard]] constexpr bool created() const { + return _corePtr != nullptr && _corePtr->created(); + } [[nodiscard]] constexpr Config const& config() const { return _config; } private: @@ -174,8 +180,12 @@ class Core { void destroyQueues(); Config _config; - cvk::Core _core; - cth::co::scheduler _workers; + + // behind a std::unique_ptr: the reactor and the heaps refer to them also before create(), the + // moves stay = default + std::unique_ptr _corePtr; + std::unique_ptr _workersPtr; + // destroyed after the queues, before the workers and the cvk core: it posts to the workers TimelineReactor _reactor; @@ -193,9 +203,9 @@ class Core { public: Core(Core const& other) = delete; - Core(Core&& other) = delete; + Core(Core&& other) noexcept = default; Core& operator=(Core const& other) = delete; - Core& operator=(Core&& other) = delete; + Core& operator=(Core&& other) noexcept = default; static constexpr void debug_check(Core const&); }; diff --git a/jvk/src/base/core.cpp b/jvk/src/base/core.cpp index beda5ed5..d6c3e64f 100644 --- a/jvk/src/base/core.cpp +++ b/jvk/src/base/core.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -20,12 +21,16 @@ using std::span; Core::Core(cvk::Instance const& instance, Config config) : _config{std::move(config)}, - _core{instance}, - _workers{ - _config.workers == 0 ? std::max(std::thread::hardware_concurrency(), 1u) : _config.workers + _corePtr{std::make_unique(instance)}, + _workersPtr{ + std::make_unique( + _config.workers == 0 + ? std::max(std::thread::hardware_concurrency(), 1u) + : _config.workers + ) }, - _reactor{_core, _workers}, - _resourceHeap{_core, _config.heaps.resources} {} + _reactor{*_corePtr, *_workersPtr}, + _resourceHeap{*_corePtr, _config.heaps.resources} {} Core::Core( cvk::Instance const& instance, @@ -46,37 +51,37 @@ void Core::create(span const> surfaces) { config.queueSets = queue_sets(config.queueProperties); config.features.merge(constants::DEVICE_FEATURES); - _core.create(surfaces, config); + _corePtr->create(surfaces, config); // the cvk core exists before the workers, the reactor and the queues, only a catch can destroy it when a later // step fails try { - _workers.start(); + _workersPtr->start(); _reactor.create(); createQueues(); if(_config.heaps.createsResourceHeap()) _resourceHeap.create(); if(_config.heaps.createsSamplerHeap()) - _samplerHeapOpt.emplace(_core, _config.heaps.samplers); + _samplerHeapOpt.emplace(*_corePtr, _config.heaps.samplers); } catch(...) { _resourceHeap.optDestroy(); destroyQueues(); _reactor.optDestroy(); - _workers.await_stop(); - _core.destroy(); + _workersPtr->await_stop(); + _corePtr->destroy(); throw; } } void Core::destroy() { debug_check(*this); - CTH_CRITICAL(_workers.owns_thread(), "destroy() must not run on a worker of the core") {} + CTH_CRITICAL(_workersPtr->owns_thread(), "destroy() must not run on a worker of the core") {} // one wait per vulkan queue: the first index of each vulkan queue // swallow errors bc destructor - auto const indices = _core.queueIndices(); + auto const indices = _corePtr->queueIndices(); for(size_t qIdx = 0; qIdx < indices.size(); ++qIdx) { if(std::ranges::contains(indices.first(qIdx), indices[qIdx])) continue; @@ -112,8 +117,8 @@ void Core::destroy() { _samplerHeapOpt.reset(); _resourceHeap.optDestroy(); _reactor.destroy(); - _workers.await_stop(); - _core.destroy(); + _workersPtr->await_stop(); + _corePtr->destroy(); } Queue const& Core::queue(size_t queueIdx) const { @@ -141,9 +146,9 @@ void Core::createQueues() { _driverSchedulerOpt.emplace(cth::co::autostart, _config.driverThreads); cth::co::scheduler const& scheduler = _driverSchedulerOpt.has_value() ? *_driverSchedulerOpt - : _workers; + : *_workersPtr; - auto const indices = _core.queueIndices(); + auto const indices = _corePtr->queueIndices(); _queues.reserve(indices.size()); _queueIndices.reserve(indices.size()); @@ -156,7 +161,7 @@ void Core::createQueues() { } _queueIndices.push_back(_queues.size()); - _queues.emplace_back(*this, _core.queue(queueIdx), scheduler); + _queues.emplace_back(*this, _corePtr->queue(queueIdx), scheduler); } } diff --git a/jvk/tests/src/base/core_test.cpp b/jvk/tests/src/base/core_test.cpp index 861bc8fd..a7b90f26 100644 --- a/jvk/tests/src/base/core_test.cpp +++ b/jvk/tests/src/base/core_test.cpp @@ -5,6 +5,7 @@ #include "jvk/base/queue.hpp" #include "jvk/base/queue_sets.hpp" +#include "jvk/data/sampler_heap.hpp" //TEMP compile check of the phase 6 headers until their sources exist #include "jvk/graph/presenter.hpp" #include "jvk/graph/stage_graph.hpp" @@ -13,6 +14,7 @@ #include "cvk/base/device.hpp" #include "cvk/base/physical_device.hpp" +#include "cvk/data/img/sampler_config.hpp" #include "cvk/render/sync/fence.hpp" #include "cvk/render/sync/timeline_semaphore.hpp" #include "cvk/utility/constant/os_constants.hpp" @@ -129,6 +131,34 @@ JVK_TEST(Core, base_constructor_does_not_create) { EXPECT_EQ(core.config().driverThreads, test::Context::CONFIG.driverThreads); } +JVK_TEST(Core, a_base_constructed_core_moves_then_creates_and_works) { + test::Context const context{}; + Core core{context.instance, test::Context::CONFIG}; + + Core moved{std::move(core)}; + Core other{context.instance, test::Context::CONFIG}; + other = std::move(moved); + EXPECT_FALSE(other.created()); + + other.create({}); + ASSERT_TRUE(other.created()); + + // the queues, the reactor and the workers of the moved core + Semaphore const semaphore{other, cvk::create}; + auto task = [](Core const& c, Semaphore const& s) -> cth::co::executor_task { + co_await c.queue(0).submit({.signals = {{.semaphore = s, .value = 1}}}); + co_await s.wait(1); + co_return c.executor().context().owns_thread(); + }; + EXPECT_TRUE(other.executor().sync_wait(task(other, semaphore))); + + auto const& heaps = other.config().heaps; + if(heaps.createsResourceHeap()) + EXPECT_TRUE(other.resourceHeap().created()); + if(heaps.createsSamplerHeap()) + EXPECT_EQ(other.samplerHeap().insert(cvk::SamplerConfig{}).idx().get(), 0); +} + JVK_TEST(Core, create_and_destroy) { test::Context const context{}; Core core{context.instance, test::Context::CONFIG}; From dec6367e4d407bba735ce682a3bd0ca68a261478 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:16:51 +0100 Subject: [PATCH 26/68] ci: buildcache direct mode off in the Windows CI, TEMP for the stale precompiled headers - direct mode keys on the headers of clang -H, -H does not list the headers of -include - CMake includes the precompiled header with -include: a changed header still gives a cache hit - buildcache 0.31.7 of the Windows CI has direct mode on by default, the Linux image has it off - removes the TEMP diagnosis steps of 9912c15 --- .github/workflows/windows-pipeline.yml | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/.github/workflows/windows-pipeline.yml b/.github/workflows/windows-pipeline.yml index 85b94d10..00472b48 100644 --- a/.github/workflows/windows-pipeline.yml +++ b/.github/workflows/windows-pipeline.yml @@ -16,6 +16,15 @@ jobs: build: name: Windows (${{ inputs.compiler }}) runs-on: windows-latest + #TEMP buildcache direct mode gives stale precompiled headers + # - direct mode keys on the headers of clang -H, -H does not list the headers of -include + # - CMake includes the precompiled header with -include: a changed header of it still hits, + # the build takes the old precompiled header and old objects, no error + # - only Windows: buildcache 0.31.7 of this job has direct mode on by default, the + # buildcache-git 0.28.1 of the Linux image (cachyos repo) has it off + # - remove when direct mode takes its inputs from the depfile or the -include operands + env: + BUILDCACHE_DIRECT_MODE: false defaults: run: shell: bash # Forces Git Bash for consistency with Linux scripts @@ -29,23 +38,8 @@ jobs: with: compiler: ${{ inputs.compiler }} - #TEMP buildcache diagnosis: the most verbose log of buildcache for the clang build - - name: Enable BuildCache log - if: inputs.compiler == 'clang' - run: | - echo "BUILDCACHE_DEBUG=1" >> "$GITHUB_ENV" - echo "BUILDCACHE_LOG_FILE=$RUNNER_TEMP/buildcache.log" >> "$GITHUB_ENV" - - name: Build uses: ./.github/actions/build-engine with: cache_prefix: engine-windows preset: ci_windows_${{ inputs.compiler }} - - #TEMP buildcache diagnosis: the log also of a failed build - - name: Upload BuildCache log - if: always() && inputs.compiler == 'clang' - uses: actions/upload-artifact@v7 - with: - name: buildcache-log-windows-clang - path: ${{ runner.temp }}/buildcache.log From baadb3e65010ad38eabc5ef3a23da4d92d789777 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:19:01 +0100 Subject: [PATCH 27/68] jvk: an out of date present sets the out of date flag of the presenter again - the present job stores VK_ERROR_OUT_OF_DATE_KHR of Queue::present() in the atomic _outOfDate - the store comes after the mark: the next acquire() can miss it, a later one recreates the swapchain - no extra sync: acquire() keeps its wait on the mark of the last present - before: the result was ignored, a driver that reports out of date only at the present with the same extent never got a recreation --- jvk/incl/jvk/graph/presenter.hpp | 20 ++++++++++++-------- jvk/src/graph/presenter.cpp | 26 ++++++++++++++------------ 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/presenter.hpp index 9c767e40..854b989e 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -158,9 +159,9 @@ class Presenter { * - waits until the last present job called `vkQueuePresentKHR()`: the acquire and the present share the * swapchain, a blocking acquire before that present delays it by one refresh (FIFO) * - runs on `Queue::scheduler()`, outside the strand - * - `VK_ERROR_OUT_OF_DATE_KHR` of an acquire of the current swapchain, or a changed - * `cvk::Surface::extent()` -> recreates the swapchain first, erases the old images in the graph of the stage, - * see `StageGraph::erase()`, `Swapchain::recreate()` + * - an out of date acquire of the current swapchain, an out of date present, or a changed + * `cvk::Surface::extent()` -> recreates the swapchain first, erases the old images in the + * graph of the stage, see `StageGraph::erase()`, `Swapchain::recreate()` * - an acquired image without a present, e.g. after an exception or a skip: waits until the gpu finished the * submit or the skip of its stage, then unacquires it * @param stages pipeline stages of the stage that wait for the acquire @@ -189,8 +190,8 @@ class Presenter { * - transitions the image to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` from its last state in the stage primary * - a stage of another queue family: the job releases the image on the stage queue, the images stay * `VK_SHARING_MODE_EXCLUSIVE` - * - `VK_ERROR_OUT_OF_DATE_KHR` -> the acquire of the next `acquire()` fails with it, then - * recreates the swapchain + * - `VK_ERROR_OUT_OF_DATE_KHR` -> a later `acquire()` recreates the swapchain, the next one can + * still use the old swapchain * - a failure of the job: the next `acquire()` rethrows it * @pre an acquired image without a present * @pre `Stage::status()` is `SUBMITTED` @@ -257,7 +258,7 @@ class Presenter { * - the submit waits for the semaphore of the stage and the release, signals * `Presenter::_semaphore` with the value, `Queue::present()` marks it after the present * - the command buffer: the acquire half of another family, the transition to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` - * - the result of the present: unused, the next `acquire()` runs after the mark + * - `VK_ERROR_OUT_OF_DATE_KHR` of the present: sets `Presenter::_outOfDate` after the mark * @details the errors: * - a failed submit: stores the error, then `dev::fallback_submit()` that signals only * `Presenter::_semaphore`, no present @@ -330,8 +331,11 @@ class Presenter { /** the acquired image without a present */ std::optional _acquiredOpt = std::nullopt; - /** an acquire of the current swapchain gave no image, the next `acquire()` round recreates */ - bool _outOfDate = false; + /** + * set by an out of date acquire and by the present jobs, `acquire()` reads it + * @details a late store -> a later `acquire()` recreates the swapchain + */ + std::atomic _outOfDate{false}; dev::first_error _error{}; ///< the first error of a job or a scope, `acquire()` rethrows it diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index 3e4e67a9..4af95d1d 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -106,7 +107,7 @@ void Presenter::destroy() { _surface.destroy(); _acquireSemaphoreIdx = 0; - _outOfDate = false; + _outOfDate.store(false, std::memory_order_relaxed); _error.clear(); } @@ -151,7 +152,7 @@ cth::co::executor_task Presenter::acquire( // no image -> out of date, the next round recreates the swapchain imageIdxOpt = _swapchain.acquire(acquireSemaphore).imageIndex; if(!imageIdxOpt.has_value()) - _outOfDate = true; + _outOfDate.store(true, std::memory_order_relaxed); } auto const imageIdx = *imageIdxOpt; @@ -273,15 +274,15 @@ cth::co::executor_task Presenter::presentJob( // the swapchain of the image is the current one: a recreation only happens in acquire(), // after the mark of the last present - // no use of the result: the next acquire() runs after the mark, an out of date swapchain - // fails its acquire - static_cast( - co_await queue.present( - {.cmdBuffers = {submit.cmd}, .waits = waits, .signals = {signal}}, - _swapchain.current(), - image.imageIdx - ) + auto const result = co_await queue.present( + {.cmdBuffers = {submit.cmd}, .waits = waits, .signals = {signal}}, + _swapchain.current(), + image.imageIdx ); + // relaxed: the flag carries no data + // after the mark: the next acquire() can miss it, a later one recreates the swapchain + if(result == VK_ERROR_OUT_OF_DATE_KHR) + _outOfDate.store(true, std::memory_order_relaxed); } catch(...) { _error.store(std::current_exception()); } @@ -292,7 +293,8 @@ cth::co::executor_task Presenter::presentJob( } void Presenter::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { - if(_swapchain.created() && !_outOfDate && _swapchain.current().extent() == extent) + if(_swapchain.created() && !_outOfDate.load(std::memory_order_relaxed) + && _swapchain.current().extent() == extent) return; if(_swapchain.created()) { @@ -303,7 +305,7 @@ void Presenter::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { _swapchain.recreate(extent); } else _swapchain.create(swapchainConfig(), extent); - _outOfDate = false; + _outOfDate.store(false, std::memory_order_relaxed); while(_submits.size() < _swapchain.current().imageCount()) _submits.push_back( From 1f2b14c1b82c1184e24b16810d0325bad47cdcc8 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:22:34 +0100 Subject: [PATCH 28/68] demo/cube: the mip levels of the texture in a constant, no narrowing on the MSVC STL - std::bit_width() returns int, the designated initializer of mipLevels narrows it to uint32_t - the MSVC STL takes a non-constexpr intrinsic path outside a manifestly constant evaluated context: the call is no constant there, clang rejects the narrowing - TEXTURE_MIP_LEVELS uses cvk::mip_level_count(), its initializer is manifestly constant evaluated --- demo/cube/src/main.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/demo/cube/src/main.cpp b/demo/cube/src/main.cpp index 81519301..9fc5cf51 100644 --- a/demo/cube/src/main.cpp +++ b/demo/cube/src/main.cpp @@ -19,6 +19,7 @@ #include "cvk/base/physical_device.hpp" #include "cvk/base/queue/queue_family.hpp" #include "cvk/data/buffer/device_ptr.hpp" +#include "cvk/data/img/image.hpp" #include "cvk/data/img/image_view.hpp" #include "cvk/render/pipeline/graphics_pipeline.hpp" #include "cvk/render/pipeline/shader/shader.hpp" @@ -41,7 +42,6 @@ #include #include -#include #include #include #include @@ -83,6 +83,8 @@ constexpr float SPEED = 1.f; ///< radians per second glm::vec3 const AXIS = glm::normalize(glm::vec3{0.3f, 1.f, 0.2f}); constexpr uint32_t TEXTURE_SIZE = 256; +/** full mip chain */ +constexpr uint32_t TEXTURE_MIP_LEVELS = cvk::mip_level_count({TEXTURE_SIZE, TEXTURE_SIZE}); constexpr uint32_t CHECKER_SIZE = 32; ///< pixels per square of the checkerboard std::filesystem::path const SHADER_DIR{CUBE_SHADER_DIR}; @@ -242,7 +244,7 @@ struct Cube { .format = VK_FORMAT_R8G8B8A8_SRGB, .usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, - .mipLevels = std::bit_width(TEXTURE_SIZE), + .mipLevels = TEXTURE_MIP_LEVELS, }, VkExtent2D{TEXTURE_SIZE, TEXTURE_SIZE} }, From d1977e888b176db3bee3e64f8470d0c92bb32928 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:58:31 +0100 Subject: [PATCH 29/68] jvk: acquire() waits for the end of the last present job, the out of date flag a plain bool - Presenter::_presented: a counter event, the present job sets it to its value as its last step - acquire() and the next present job wait for it, not for the mark of the presenter semaphore: the mark comes before the job has the result of the present - the present job writes _outOfDate before the set: the next acquire() always sees it, no late flag after a recreation, no second recreation - replaces the atomic flag of baadb3e --- jvk/incl/jvk/graph/presenter.hpp | 39 +++++++++++++++++------------- jvk/src/graph/presenter.cpp | 41 +++++++++++++++++--------------- 2 files changed, 44 insertions(+), 36 deletions(-) diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/presenter.hpp index 854b989e..20894e3c 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -11,13 +11,13 @@ #include +#include #include #include #include #include #include -#include #include #include #include @@ -81,8 +81,8 @@ struct PresenterConfig { * - owns the surface and the swapchain * - recreates the swapchain in `acquire()`, a retired swapchain stays until its presents ended, see `Swapchain` * - submits and presents in the strand of its queue, acquires outside the strand on `Queue::scheduler()` - * - `Presenter::_semaphore` orders the uses of the swapchain: a present job marks after `vkQueuePresentKHR()`, the - * next `acquire()` waits for that mark + * - `Presenter::_presented` orders the uses of the swapchain: a present job sets it at its end, the + * next `acquire()` waits for it * - one acquired image at a time, in a scope: `scoped_acquire` presents it at its end * - an image without a present: the next `acquire()` or `destroy()` unacquires it, `acquire()` after the gpu finished * its stage @@ -156,7 +156,7 @@ class Presenter { * - adds the wait for the acquire to the stage: `Stage::await()` with the acquire semaphore and the stages * - the state of the image in the graph of the stage: `VK_IMAGE_LAYOUT_UNDEFINED` with the wait stages, see * `StageGraph::assume()`: the first barrier of the image chains with the wait - * - waits until the last present job called `vkQueuePresentKHR()`: the acquire and the present share the + * - waits until the last present job ended: the acquire and the present share the * swapchain, a blocking acquire before that present delays it by one refresh (FIFO) * - runs on `Queue::scheduler()`, outside the strand * - an out of date acquire of the current swapchain, an out of date present, or a changed @@ -190,8 +190,7 @@ class Presenter { * - transitions the image to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` from its last state in the stage primary * - a stage of another queue family: the job releases the image on the stage queue, the images stay * `VK_SHARING_MODE_EXCLUSIVE` - * - `VK_ERROR_OUT_OF_DATE_KHR` -> a later `acquire()` recreates the swapchain, the next one can - * still use the old swapchain + * - `VK_ERROR_OUT_OF_DATE_KHR` -> the next `acquire()` recreates the swapchain * - a failure of the job: the next `acquire()` rethrows it * @pre an acquired image without a present * @pre `Stage::status()` is `SUBMITTED` @@ -243,22 +242,23 @@ class Presenter { // no awaiter parameter: the job takes `submitted()` from the stage semaphore and the frame // number // the image as a parameter: the job reads no presenter state outside of the strand - // the submit mark of the present job before awaited: acquire() no longer orders the present - // jobs + // `_presented` of the job before awaited: acquire() no longer orders the present jobs /** * present job of `present()` * @details the order: * - off the strand: awaits `Semaphore::submitted()` of the stage semaphore with the frame number * - stage of another family -> `Queue::release()` of the image on the stage queue - * - off the strand: awaits `Semaphore::submitted()` of `Presenter::_semaphore` with the value before: the present - * jobs submit and present in the order of `present()` + * - off the strand: awaits `Presenter::_presented` of the job before: the present jobs run one + * at a time, in the order of `present()` * - off the strand: records the command buffer, the present jobs run one at a time * - `Queue::present()` with the current swapchain: a recreation only happens in `acquire()`, * after the last present * - the submit waits for the semaphore of the stage and the release, signals * `Presenter::_semaphore` with the value, `Queue::present()` marks it after the present * - the command buffer: the acquire half of another family, the transition to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` - * - `VK_ERROR_OUT_OF_DATE_KHR` of the present: sets `Presenter::_outOfDate` after the mark + * - `VK_ERROR_OUT_OF_DATE_KHR` of the present: sets `Presenter::_outOfDate` before + * `Presenter::_presented` + * - the last step, also after a failure: sets `Presenter::_presented` to the value * @details the errors: * - a failed submit: stores the error, then `dev::fallback_submit()` that signals only * `Presenter::_semaphore`, no present @@ -287,7 +287,8 @@ class Presenter { * - grows `Presenter::_submits` to the image count * @param extent of the surface, `> 0` * @param graphPtr of the acquiring stage, `nullptr` -> no graph - * @pre no present job uses the swapchain: `create()`, or `acquire()` after the mark of the last present + * @pre no present job uses the swapchain: `create()`, or `acquire()` after the end of the last + * present job * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode * @throws cvk::vk_result_exception result of `vkCreateSwapchainKHR()` */ @@ -301,7 +302,8 @@ class Presenter { /** * gives the acquired image back to the current swapchain * @pre an acquired image of the current swapchain - * @pre no present job uses the swapchain: `acquire()` after the mark of the last present, or `destroy()` + * @pre no present job uses the swapchain: `acquire()` after the end of the last present job, or + * `destroy()` * @throws cvk::vk_result_exception result of `vkReleaseSwapchainImagesKHR()` */ void unacquireImage(); @@ -313,7 +315,7 @@ class Presenter { // destroyed after the swapchain cvk::Surface _surface; - /** created once the surface extent is `> 0`, `Presenter::_semaphore` orders its uses */ + /** created once the surface extent is `> 0`, `Presenter::_presented` orders its uses */ Swapchain _swapchain; /** @@ -326,16 +328,19 @@ class Presenter { Semaphore _semaphore; ///< signaled by the present submits, each submit signals the next value + /** value of the last ended present job, `acquire()` and the next present job wait for it */ + cth::co::counter_event _presented{}; + std::vector _submits{}; ///< one per swapchain image /** the acquired image without a present */ std::optional _acquiredOpt = std::nullopt; /** - * set by an out of date acquire and by the present jobs, `acquire()` reads it - * @details a late store -> a later `acquire()` recreates the swapchain + * set by an out of date acquire and by the present jobs + * @details `acquire()` reads it after `Presenter::_presented` reached the last present */ - std::atomic _outOfDate{false}; + bool _outOfDate = false; dev::first_error _error{}; ///< the first error of a job or a scope, `acquire()` rethrows it diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index 4af95d1d..5eff6739 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -20,7 +20,6 @@ #include #include -#include #include #include #include @@ -103,11 +102,13 @@ void Presenter::destroy() { _submits.clear(); _acquireSemaphores.clear(); _semaphore.optDestroy(); + // the semaphore starts at 0 again + _presented = cth::co::counter_event{}; _swapchain.optDestroy(); _surface.destroy(); _acquireSemaphoreIdx = 0; - _outOfDate.store(false, std::memory_order_relaxed); + _outOfDate = false; _error.clear(); } @@ -126,14 +127,14 @@ cth::co::executor_task Presenter::acquire( if(_error) _error.rethrow(); - // present N before acquire N + 1: a blocking acquire would delay the present (FIFO) - auto const value = _semaphore.value(); - if(value > 0) - co_await _semaphore.submitted(value); + // present N before acquire N + 1: the acquire and the present share the swapchain + // (externally synchronized), a blocking acquire would delay the present (FIFO), the flag of + // the present is final + co_await _presented.wait(_semaphore.value()); // the unacquire needs the gpu done with its stage: VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786 if(_acquiredOpt.has_value()) co_await _acquiredOpt->stageSemaphore->wait(_acquiredOpt->frameNumber); - // outside the strand: the present marks order the swapchain uses + // outside the strand: the ends of the present jobs order the swapchain uses co_await cth::co::executor{_queue->scheduler()}.schedule(); if(_acquiredOpt.has_value()) @@ -152,7 +153,7 @@ cth::co::executor_task Presenter::acquire( // no image -> out of date, the next round recreates the swapchain imageIdxOpt = _swapchain.acquire(acquireSemaphore).imageIndex; if(!imageIdxOpt.has_value()) - _outOfDate.store(true, std::memory_order_relaxed); + _outOfDate = true; } auto const imageIdx = *imageIdxOpt; @@ -224,9 +225,9 @@ cth::co::executor_task Presenter::presentJob( // off the strand: a wait before the signal on one queue would block it, the release needs the submit of the stage, // the next acquire() sets the state of the image in the graph after the submit job of the stage appended its states co_await stageSemaphore.submitted(frameNumber); - // the present jobs submit and present in order, also a failed one: the job before wrote the values of the command - // buffers and signals the value before - co_await _semaphore.submitted(value - 1); + // the present jobs run one at a time, also a failed one: the job before ended, it wrote the + // values of the command buffers, signaled the value before and wrote the flag + co_await _presented.wait(value - 1); try { ImageState const presentState{ @@ -264,7 +265,7 @@ cth::co::executor_task Presenter::presentJob( // the last submit of the command buffer, a swapchain before a recreation used it too co_await _semaphore.wait(_submits[image.imageIdx].value); - // off the strand: the present jobs run one at a time, the mark of the job before orders them + // off the strand: the present jobs run one at a time, the end of the job before orders them auto& submit = _submits[image.imageIdx]; submit.cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); barrier.execute(submit.cmd); @@ -273,16 +274,15 @@ cth::co::executor_task Presenter::presentJob( submit.value = value; // the swapchain of the image is the current one: a recreation only happens in acquire(), - // after the mark of the last present + // after the end of the last present job auto const result = co_await queue.present( {.cmdBuffers = {submit.cmd}, .waits = waits, .signals = {signal}}, _swapchain.current(), image.imageIdx ); - // relaxed: the flag carries no data - // after the mark: the next acquire() can miss it, a later one recreates the swapchain + // before _presented.set(): the next acquire() reads it if(result == VK_ERROR_OUT_OF_DATE_KHR) - _outOfDate.store(true, std::memory_order_relaxed); + _outOfDate = true; } catch(...) { _error.store(std::current_exception()); } @@ -290,11 +290,14 @@ cth::co::executor_task Presenter::presentJob( // presenter if(_semaphore.submittedValue() < value) co_await dev::fallback_submit(queue, {.waits = waits, .signals = {signal}}, _error); + + // the last step, also after a failure, an escaped exception terminates anyway (detach) + // one set() at a time, rising: the next job waits for this value + _presented.set(value); } void Presenter::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { - if(_swapchain.created() && !_outOfDate.load(std::memory_order_relaxed) - && _swapchain.current().extent() == extent) + if(_swapchain.created() && !_outOfDate && _swapchain.current().extent() == extent) return; if(_swapchain.created()) { @@ -305,7 +308,7 @@ void Presenter::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { _swapchain.recreate(extent); } else _swapchain.create(swapchainConfig(), extent); - _outOfDate.store(false, std::memory_order_relaxed); + _outOfDate = false; while(_submits.size() < _swapchain.current().imageCount()) _submits.push_back( From 96acb110de188341347c89bd2ae7abb84d0a0bbf Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:15:21 +0100 Subject: [PATCH 30/68] jvk: cth::co::catching_scope replaces dev::first_error, the jobs terminate before their marks - StageGraph and Presenter: one catching_scope _jobs, first_error.hpp removed - scoped_submit, scoped_acquire, StageSlot and fallback_submit() take the scope, the two scope destructors store their failure themselves: a destructor is no task - an escaped exception after the mark of a job: the scope stores it, the failed gpu wait of the submit job escapes now - before the mark the waiters would hang: fallback_submit() terminates on a failure other than VK_ERROR_DEVICE_LOST, the skip info, the waits and the fallback start are noexcept - lib/cth: catching_scope --- jvk/incl/jvk/base/queue.hpp | 11 +++--- jvk/incl/jvk/graph/presenter.hpp | 25 ++++++------ jvk/incl/jvk/graph/stage.hpp | 20 +++++----- jvk/incl/jvk/graph/stage_graph.hpp | 21 +++++----- jvk/incl/jvk/utility/first_error.hpp | 57 ---------------------------- jvk/src/base/queue.cpp | 14 +++++-- jvk/src/graph/presenter.cpp | 41 +++++++++++++------- jvk/src/graph/stage.cpp | 9 +++-- jvk/src/graph/stage_graph.cpp | 36 +++++++++--------- jvk/tests/src/base/queue_test.cpp | 6 +-- lib/cth | 2 +- 11 files changed, 103 insertions(+), 139 deletions(-) delete mode 100644 jvk/incl/jvk/utility/first_error.hpp diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index eb388de5..b4789130 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -1,7 +1,6 @@ #pragma once #include "jvk/cmd/cmd_buffer.hpp" #include "jvk/sync/semaphore.hpp" -#include "jvk/utility/first_error.hpp" #include "cvk/base/queue/queue.hpp" #include "cvk/base/queue/submit_info.hpp" @@ -9,6 +8,7 @@ #include +#include #include #include #include @@ -202,15 +202,16 @@ namespace jvk::dev { * the empty submit after a failed submit: the waiters of its jvk signals go on * @details * - `Queue::submit()` marks the signals - * - `VK_ERROR_DEVICE_LOST` -> stores the error, marks the signals: the gpu waits end on their own + * - `VK_ERROR_DEVICE_LOST` -> stores the error in the scope, marks the signals: the gpu waits end + * on their own + * - another failure terminates: the waiters would hang * @param queue of the failed submit * @param info waits and signals of the failed submit, no command buffers - * @param[out] error gets a device loss - * @throws cvk::vk_result_exception other results of the submit: the waiters would hang + * @param[out] jobs of the caller, gets a device loss */ [[nodiscard]] cth::co::executor_task fallback_submit( Queue const& queue, SubmitInfo info, - first_error& error + cth::co::catching_scope& jobs ); } diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/presenter.hpp index 20894e3c..14744312 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -3,7 +3,6 @@ #include "jvk/graph/swapchain.hpp" #include "jvk/sync/resource_tracker.hpp" #include "jvk/sync/semaphore.hpp" -#include "jvk/utility/first_error.hpp" #include "cvk/render/sync/semaphore.hpp" #include "cvk/surface/surface.hpp" @@ -11,8 +10,8 @@ #include +#include #include -#include #include #include #include @@ -172,8 +171,9 @@ class Presenter { * @pre an acquired image without a present of this frame: its stage is submitted or skipped * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode * @throws cvk::vk_result_exception other result of `vkAcquireNextImageKHR()` or `vkCreateSwapchainKHR()` - * @throws cvk::vk_result_exception the first error of a present job or a scope, stored before the call: an error - * of the last present job during the waits -> the next `acquire()` rethrows it + * @throws std::exception the first error of a present job or a scope, stored before the call: + * an error of the last present job during the waits -> the next `acquire()` rethrows it, see + * `cth::co::catching_scope` * @attention `vkAcquireNextImageKHR()` can block (FIFO: the vsync throttle): it occupies a driver thread, * `CoreConfig::driverThreads` `0` -> the calling worker * @see `Stage::await()` @@ -265,6 +265,8 @@ class Presenter { * - a failed empty submit: `VK_ERROR_DEVICE_LOST` -> stores the error, marks, else terminates: * the waiters would hang * - a failed present: stores the error + * - before the end: every other failure terminates, the waiters on `Presenter::_presented` + * would hang * @param image the acquired image * @param lastState of the image in the stage primary * @param value of `Presenter::_semaphore` for the submit @@ -342,10 +344,11 @@ class Presenter { */ bool _outOfDate = false; - dev::first_error _error{}; ///< the first error of a job or a scope, `acquire()` rethrows it - - /** the running present jobs, `destroy()` waits for them */ - cth::co::simple_counting_scope _jobs{}; + /** + * the running present jobs, `destroy()` waits for them + * @details the first error of a job or a scope, `acquire()` rethrows it + */ + cth::co::catching_scope _jobs{}; public: Presenter(Presenter const& other) = delete; @@ -377,13 +380,13 @@ class scoped_acquire { * @param presenter of the image * @param stage of the acquire * @param imageOpt `std::nullopt` -> no image - * @param error the first error of the presenter, gets a failure at the end + * @param jobs of the presenter, gets a failure at the end */ scoped_acquire( Presenter& presenter, Stage& stage, std::optional imageOpt, - dev::first_error& error + cth::co::catching_scope& jobs ) noexcept; ~scoped_acquire(); @@ -422,7 +425,7 @@ class scoped_acquire { cth::move_ptr _presenterPtr; ///< `nullptr` -> the end does nothing cth::ref_wrapper _stage; std::optional _imageOpt; - cth::ref_wrapper _error; ///< the first error of the presenter + cth::ref_wrapper _jobs; ///< of the presenter public: scoped_acquire(scoped_acquire const& other) = delete; diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index 49e56397..399ab62a 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -3,7 +3,6 @@ #include "jvk/base/stasis.hpp" #include "jvk/cmd/cmd_buffer.hpp" #include "jvk/sync/semaphore.hpp" -#include "jvk/utility/first_error.hpp" #include "cvk/base/queue/submit_info.hpp" #include "cvk/data/buffer/base_buffer.hpp" @@ -11,6 +10,7 @@ #include +#include #include #include #include @@ -120,7 +120,7 @@ struct StageSlot { */ StageSlot( StageGraph& graph, - first_error& error, + cth::co::catching_scope& jobs, size_t stageId, size_t slot, Queue const& queue, @@ -129,8 +129,8 @@ struct StageSlot { cth::ref_wrapper graph; - /** the first error of the graph, the scopes of the stages store into it */ - cth::ref_wrapper error; + /** the jobs of the graph, the scopes of the stages store their errors into it */ + cth::ref_wrapper jobs; size_t stageId; ///< id of the stage, see `StageGraphConfig::stages` @@ -429,17 +429,17 @@ namespace jvk { */ class scoped_submit { public: - //TODO review the first error as a parameter: scoped_submit is no nested class, Stage::begin() hands it the error - // of the graph from its stage slot + //TODO review the jobs of the graph as a parameter: scoped_submit is no nested class, + // Stage::begin() hands it the jobs of the graph from its stage slot /** * @details the uncaught exceptions of the calling thread at the construction tell the exception at the end * @param stage with the begun primary - * @param error the first error of the graph, gets a failure of the submit at the end + * @param jobs of the graph, gets a failure of the submit at the end * @pre `Stage::begin()` began the primary */ - scoped_submit(Stage& stage, dev::first_error& error) noexcept : + scoped_submit(Stage& stage, cth::co::catching_scope& jobs) noexcept : _stagePtr{&stage}, - _error{error}, + _jobs{jobs}, _uncaughtExceptions{std::uncaught_exceptions()} {} ~scoped_submit(); @@ -449,7 +449,7 @@ class scoped_submit { private: cth::move_ptr _stagePtr; - cth::ref_wrapper _error; ///< the first error of the graph + cth::ref_wrapper _jobs; ///< of the graph int _uncaughtExceptions; public: diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index 07125419..eb3cb0b4 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -5,14 +5,13 @@ #include "jvk/base/stasis.hpp" #include "jvk/sync/resource_tracker.hpp" -#include "jvk/utility/first_error.hpp" #include "cvk/base/queue/submit_info.hpp" #include "cvk/render/sync/barrier.hpp" #include -#include +#include #include #include #include @@ -83,8 +82,8 @@ class StageGraph { * stages: the gpu finished them, both with `cth::co::all()` * @return the frame of the slot * @pre no stage of the frame before records or submits: `nextFrame()` ends the frame - * @throws cvk::vk_result_exception the first error of a submit job or a scope, stored before the call: an error - * during the waits -> the next `nextFrame()` rethrows it + * @throws std::exception the first error of a submit job or a scope, stored before the call: an + * error during the waits -> the next `nextFrame()` rethrows it, see `cth::co::catching_scope` * @throws cth::except::group_coro_exception reason: the wait for a stage of the old frame * failed, after the waits for all its stages: `exceptions()` holds the * `cth::except::coro_exception` per stage @@ -211,10 +210,12 @@ class StageGraph { * - on the workers of the core: after the gpu finished, erases the states of the retained resources, then * `Stasis::clear()` to `stasisEnd` * @details the errors: - * - a failed submit: stores the error, see `dev::first_error`, then skips + * - a failed submit: stores the error in `StageGraph::_jobs`, then skips * - a failed skip: `VK_ERROR_DEVICE_LOST` -> stores the error, marks the slot, else terminates: * the waiters would hang - * - a failed gpu wait: stores the error, keeps the retained objects for the destruction of the graph + * - before the mark: every other failure terminates, the waiters would hang + * - after the mark: an escaped exception ends the job, `StageGraph::_jobs` stores it + * - a failed gpu wait escapes: the retained objects stay for the destruction of the graph * @param targetStatus the status the job reaches: `SUBMITTED` or `SKIPPED` * @param stasisEnd `Stasis::end()` of the stage slot at the submit or the skip * @see `Stage::submitted()` @@ -301,12 +302,10 @@ class StageGraph { //TODO review the error stays: every nextFrame() rethrows it, the errors of the jobs are fatal /** - * the first error of a submit job or a scope of a stage, `nextFrame()` rethrows it + * the running submit jobs, `~StageGraph()` waits for them + * @details the first error of a job or a scope of a stage, `nextFrame()` rethrows it */ - dev::first_error _error{}; - - /** the running submit jobs, `~StageGraph()` waits for them */ - cth::co::simple_counting_scope _jobs{}; + cth::co::catching_scope _jobs{}; uint64_t _firstFrameNumber; ///< see `firstFrameNumber()` diff --git a/jvk/incl/jvk/utility/first_error.hpp b/jvk/incl/jvk/utility/first_error.hpp deleted file mode 100644 index 31409a08..00000000 --- a/jvk/incl/jvk/utility/first_error.hpp +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once -#include - -#include -#include -#include - - -namespace jvk::dev { -/** - * the first error of the jobs and the scopes of an owner, the owner rethrows it - * @details thread safe - * @details `store()` keeps only the first error, the owner calls `clear()` only in its `destroy()`: a check with - * `operator bool()` and the `rethrow()` after it do not race - */ -class first_error { -public: - /** - * stores the error if it is the first - */ - void store(std::exception_ptr errorPtr) noexcept { - std::scoped_lock const lock{_mutex}; - if(!_errorPtr) - _errorPtr = std::move(errorPtr); - } - - /** - * forgets the error, the next `store()` stores the first error again - */ - void clear() noexcept { - std::scoped_lock const lock{_mutex}; - _errorPtr = nullptr; - } - - /** - * rethrows the first error - * @pre an error is stored - */ - void rethrow() const { - std::scoped_lock const lock{_mutex}; - CTH_CRITICAL(!_errorPtr, "rethrow() needs a stored error") {} - std::rethrow_exception(_errorPtr); - } - - /** - * @return an error is stored - */ - [[nodiscard]] explicit operator bool() const { - std::scoped_lock const lock{_mutex}; - return static_cast(_errorPtr); - } - -private: - mutable std::mutex _mutex{}; - std::exception_ptr _errorPtr = nullptr; -}; -} diff --git a/jvk/src/base/queue.cpp b/jvk/src/base/queue.cpp index cae37807..98c906f7 100644 --- a/jvk/src/base/queue.cpp +++ b/jvk/src/base/queue.cpp @@ -1,6 +1,7 @@ #include "jvk/base/queue.hpp" #include "jvk/base/core.hpp" +#include "jvk/utility/exception.hpp" #include "cvk/surface/swapchain.hpp" #include "cvk/utility/vk_exceptions.hpp" @@ -135,19 +136,24 @@ namespace dev { cth::co::executor_task fallback_submit( Queue const& queue, SubmitInfo info, - first_error& error + cth::co::catching_scope& jobs ) { // a copy: the submit takes the info auto const signals = info.signals; + // every failure but a device loss terminates: nobody marks the signals, the waiters would + // hang try { co_await queue.submit(std::move(info)); } catch(cvk::vk_result_exception const& e) { - if(e.vkResult() != VK_ERROR_DEVICE_LOST) - throw; - error.store(std::current_exception()); + if(e.vkResult() != VK_ERROR_DEVICE_LOST) { + JVK_STABLE_ERR(true, "the fallback submit failed, got {}", e.vkResult()) {} + std::terminate(); + } + jobs.store(std::current_exception()); // the failed submit marked nothing: the waiters of the marks go on mark(signals); } + catch(...) { std::terminate(); } } } } diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index 5eff6739..4794a5aa 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -109,13 +109,17 @@ void Presenter::destroy() { _acquireSemaphoreIdx = 0; _outOfDate = false; - _error.clear(); + // after _jobs.wait(): no job stores anymore + _jobs.clear(); } cth::co::executor_task Presenter::acquire( Stage& stage, VkPipelineStageFlags2 stages ) { + if(_jobs.failed()) + _jobs.rethrow(); + debug_check(*this); CTH_CRITICAL(stage.status() != Stage::Status::UNSUBMITTED, "the stage must be unsubmitted") {} CTH_CRITICAL( @@ -124,8 +128,6 @@ cth::co::executor_task Presenter::acquire( "a second acquire in frame {}: submit or skip the stage of the first image first", stage.frameNumber() ) {} - if(_error) - _error.rethrow(); // present N before acquire N + 1: the acquire and the present share the swapchain // (externally synchronized), a blocking acquire would delay the present (FIFO), the flag of @@ -147,7 +149,7 @@ cth::co::executor_task Presenter::acquire( while(!imageIdxOpt.has_value()) { auto const extent = _surface.extent(vkCore.physicalDevice()); if(extent.width == 0 || extent.height == 0) - co_return scoped_acquire{*this, stage, std::nullopt, _error}; + co_return scoped_acquire{*this, stage, std::nullopt, _jobs}; updateSwapchain(extent, &stage.graph()); // no image -> out of date, the next round recreates the swapchain @@ -178,7 +180,7 @@ cth::co::executor_task Presenter::acquire( ImageState{.layout = VK_IMAGE_LAYOUT_UNDEFINED, .scope = {.stages = stages}} ); - co_return scoped_acquire{*this, stage, image, _error}; + co_return scoped_acquire{*this, stage, image, _jobs}; } void Presenter::present(Stage& stage) { @@ -219,7 +221,10 @@ cth::co::executor_task Presenter::presentJob( auto const vkImage = image.image->get(); auto const aspectMask = image.image->aspectMask(); - vector waits{{.semaphore = stageSemaphore, .value = frameNumber}}; + // noexcept: without the waits no fallback signals the value, the waiters would hang + auto waits = [&]() noexcept { + return vector{{.semaphore = stageSemaphore, .value = frameNumber}}; + }(); SemaphoreSubmitInfo const signal{.semaphore = _semaphore, .value = value}; // off the strand: a wait before the signal on one queue would block it, the release needs the submit of the stage, @@ -284,14 +289,21 @@ cth::co::executor_task Presenter::presentJob( if(result == VK_ERROR_OUT_OF_DATE_KHR) _outOfDate = true; } - catch(...) { _error.store(std::current_exception()); } + // the job goes on with the fallback and _presented.set() + catch(...) { _jobs.store(std::current_exception()); } // a failed submit marks nothing: the empty submit signals the value for the waits on the // presenter - if(_semaphore.submittedValue() < value) - co_await dev::fallback_submit(queue, {.waits = waits, .signals = {signal}}, _error); + if(_semaphore.submittedValue() < value) { + // noexcept: a failed start of the fallback leaves the value unmarked, the waiters would + // hang + auto fallback = [&]() noexcept { + return dev::fallback_submit(queue, {.waits = waits, .signals = {signal}}, _jobs); + }(); + co_await std::move(fallback); + } - // the last step, also after a failure, an escaped exception terminates anyway (detach) + // the last step, also after a failure: nothing before it escapes, the waiters would hang // one set() at a time, rising: the next job waits for this value _presented.set(value); } @@ -338,12 +350,12 @@ scoped_acquire::scoped_acquire( Presenter& presenter, Stage& stage, std::optional imageOpt, - dev::first_error& error + cth::co::catching_scope& jobs ) noexcept : _presenterPtr{&presenter}, _stage{stage}, _imageOpt{std::move(imageOpt)}, - _error{error} {} + _jobs{jobs} {} scoped_acquire::~scoped_acquire() { if(!_presenterPtr || !_imageOpt.has_value()) @@ -354,9 +366,10 @@ scoped_acquire::~scoped_acquire() { if(stage.status() != Stage::Status::SUBMITTED) return; - // a destructor does not throw: the next acquire() rethrows + // a destructor does not throw and is no task: it stores the failure, the next acquire() + // rethrows try { _presenterPtr->present(stage); } - catch(...) { _error->store(std::current_exception()); } + catch(...) { _jobs->store(std::current_exception()); } } void scoped_acquire::present() { diff --git a/jvk/src/graph/stage.cpp b/jvk/src/graph/stage.cpp index 99233271..1a258002 100644 --- a/jvk/src/graph/stage.cpp +++ b/jvk/src/graph/stage.cpp @@ -60,14 +60,14 @@ void SlotSubmit::addCmdBuffers(SubmitInfo& info, bool prologue) const { StageSlot::StageSlot( StageGraph& graph, - first_error& error, + cth::co::catching_scope& jobs, size_t stageId, size_t slot, Queue const& queue, size_t secondaries ) : graph{graph}, - error{error}, + jobs{jobs}, stageId{stageId}, slot{slot}, queue{queue}, @@ -103,7 +103,7 @@ scoped_submit Stage::begin() { if(samplerHeapPtr != nullptr) vk.bind(*samplerHeapPtr); - return scoped_submit{*this, _stageSlot->error}; + return scoped_submit{*this, _stageSlot->jobs}; } SecondaryCmdBuffer& Stage::beginSecondary( @@ -154,7 +154,8 @@ scoped_submit::~scoped_submit() { if(_stagePtr->status() != Stage::Status::UNSUBMITTED) return; + // a destructor is no task: it stores the failure itself try { _stagePtr->submit(); } - catch(...) { _error->store(std::current_exception()); } + catch(...) { _jobs->store(std::current_exception()); } } } diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index 0ff4b3e5..7bb5d88f 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -4,7 +4,6 @@ #include "jvk/base/queue.hpp" #include "jvk/sync/family_transfer.hpp" #include "jvk/utility/exception.hpp" -#include "jvk/utility/first_error.hpp" #include "cvk/data/buffer/base_buffer.hpp" #include "cvk/data/img/image.hpp" @@ -12,7 +11,6 @@ #include "cvk/utility/vk_exceptions.hpp" #include -#include #include #include @@ -75,7 +73,7 @@ StageGraph::StageGraph(Core& core, Config config) : for(size_t stageId = 0; stageId < stages.size(); ++stageId) frameSlot.stageSlots.emplace_back( *this, - _error, + _jobs, stageId, slot, core.queue(stages[stageId].queueIdx), @@ -149,8 +147,8 @@ StageGraph::~StageGraph() { } cth::co::executor_task StageGraph::nextFrame() { - if(_error) - _error.rethrow(); + if(_jobs.failed()) + _jobs.rethrow(); auto const number = ++_frameNumber; auto const slotOf = [this](uint64_t frameNumber) -> dev::FrameSlot& { @@ -306,7 +304,8 @@ cth::co::executor_task StageGraph::submitJob( // the values of this frame, then next(): the job of the next frame of the slot reads them after // the mark - auto info = slotSubmit.skipInfo(extraWaits, extraBinaryWaits); + // noexcept: without the skip info no fallback marks the slot, the waiters would hang + auto info = [&]() noexcept { return slotSubmit.skipInfo(extraWaits, extraBinaryWaits); }(); slotSubmit.next(_config.frameSlots); bool submitted = false; @@ -335,24 +334,23 @@ cth::co::executor_task StageGraph::submitJob( co_await queue.submit(std::move(submitInfo)); submitted = true; } - catch(...) { _error.store(std::current_exception()); } + // the job goes on with the skip + catch(...) { _jobs.store(std::current_exception()); } } // a skip, also of a failed submit: the gpu waits of other stages and the waits in ~StageGraph() end - if(!submitted) - co_await dev::fallback_submit(queue, std::move(info), _error); + if(!submitted) { + // noexcept: a failed start of the fallback leaves the slot unmarked, the waiters would hang + auto fallback = [&]() noexcept { + return dev::fallback_submit(queue, std::move(info), _jobs); + }(); + co_await std::move(fallback); + } + // after the mark: a failed gpu wait escapes, _jobs stores it, the retained objects stay for + // the destruction of the graph // the job never touches the stage: nextFrame() destroys the stages after the gpu wait - bool reached = false; - try { - co_await stageSlot.semaphore.wait(frameNumber); - reached = true; - } - catch(cth::except::coro_exception const&) { _error.store(std::current_exception()); } - catch(cvk::vk_result_exception const&) { _error.store(std::current_exception()); } - // the gpu can still use the retained objects, the destruction of the graph destroys them - if(!reached) - co_return; + co_await stageSlot.semaphore.wait(frameNumber); { std::scoped_lock const lock{_statesMutex}; diff --git a/jvk/tests/src/base/queue_test.cpp b/jvk/tests/src/base/queue_test.cpp index 8850a468..0a3a550f 100644 --- a/jvk/tests/src/base/queue_test.cpp +++ b/jvk/tests/src/base/queue_test.cpp @@ -464,13 +464,13 @@ JVK_TEST(Queue, fallback_submit_marks_through_the_submit) { test::Context const context{}; auto const& queue = context.core.queue(0); Semaphore const semaphore{context.core, cvk::create}; - dev::first_error error{}; + cth::co::catching_scope jobs{}; context.core.executor().sync_wait( - dev::fallback_submit(queue, {.signals = {{.semaphore = semaphore, .value = 1}}}, error) + dev::fallback_submit(queue, {.signals = {{.semaphore = semaphore, .value = 1}}}, jobs) ); - EXPECT_FALSE(error); + EXPECT_FALSE(jobs.failed()); EXPECT_EQ(semaphore.submittedValue(), 1); static_cast(semaphore).wait(1); } diff --git a/lib/cth b/lib/cth index a9b2c8d3..638a02f7 160000 --- a/lib/cth +++ b/lib/cth @@ -1 +1 @@ -Subproject commit a9b2c8d3387d403fa00cadbfbc35122d025f4276 +Subproject commit 638a02f7921c731131a789a7ea54bbe728791923 From bb8597762d12719aa4cf6464e5535e1e30c343ca Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:18:52 +0100 Subject: [PATCH 31/68] jvk: the gpu wait of a semaphore without allocation, the reactor resumes the caller directly - TimelineReactor::Waiter: a node in semaphore_awaiter, the frame of the suspended caller holds it - the reactor keeps an intrusive list per semaphore, sorted by value, no vector of callbacks - a reached waiter: the reactor posts the resume straight to the context of the caller, one post instead of two, no worker in between - removed: dev::post_to(), the await_func callback API, the workers of the reactor - per frame (headless MAILBOX, 2 workers): operator new 52 -> 45, mutex locks 31 -> 27 --- jvk/incl/jvk/base/core.hpp | 7 +- jvk/incl/jvk/sync/semaphore.hpp | 50 +++---- jvk/incl/jvk/sync/timeline_reactor.hpp | 92 ++++++------ jvk/src/base/core.cpp | 2 +- jvk/src/sync/semaphore.cpp | 17 ++- jvk/src/sync/timeline_reactor.cpp | 101 +++++++------ jvk/tests/src/base/core_test.cpp | 27 ++-- jvk/tests/src/sync/timeline_reactor_test.cpp | 140 ++++++++++++++----- 8 files changed, 269 insertions(+), 167 deletions(-) diff --git a/jvk/incl/jvk/base/core.hpp b/jvk/incl/jvk/base/core.hpp index c9d7a168..686782f3 100644 --- a/jvk/incl/jvk/base/core.hpp +++ b/jvk/incl/jvk/base/core.hpp @@ -181,12 +181,13 @@ class Core { Config _config; - // behind a std::unique_ptr: the reactor and the heaps refer to them also before create(), the - // moves stay = default + // behind a std::unique_ptr: the reactor and the heaps refer to the cvk core also before + // create(), the moves stay = default std::unique_ptr _corePtr; std::unique_ptr _workersPtr; - // destroyed after the queues, before the workers and the cvk core: it posts to the workers + // destroyed after the queues, before the workers and the cvk core: it posts the resumes of its + // waiters to their contexts TimelineReactor _reactor; // destroyed after the queues: their strands run on it diff --git a/jvk/incl/jvk/sync/semaphore.hpp b/jvk/incl/jvk/sync/semaphore.hpp index 812e38bf..0a7088a3 100644 --- a/jvk/incl/jvk/sync/semaphore.hpp +++ b/jvk/incl/jvk/sync/semaphore.hpp @@ -1,11 +1,12 @@ #pragma once +#include "jvk/sync/timeline_reactor.hpp" + #include "cvk/base/queue/submit_info.hpp" #include "cvk/render/sync/timeline_semaphore.hpp" #include "cvk/utility/constants.hpp" #include -#include #include #include #include @@ -23,14 +24,15 @@ class Semaphore; /** * awaiter of `Semaphore::wait()` and of `co_await` on a `Stage` - * @details resumes the caller on its context, a failed wait throws in the caller + * @details + * - resumes the caller on its context, a failed wait throws in the caller + * - holds the waiter of the reactor: the frame of the suspended caller holds it, no allocation */ -class semaphore_awaiter : public cth::co::this_coro_awaiter_base, - public cth::co::wait_awaiter_base { +class semaphore_awaiter : public cth::co::this_coro_awaiter_base { public: constexpr semaphore_awaiter(Semaphore const& semaphore, uint64_t value) : _semaphore{semaphore}, - _value{value} {} + _waiter{.value = value} {} /** * @return the semaphore reached the value @@ -39,25 +41,28 @@ class semaphore_awaiter : public cth::co::this_coro_awaiter_base, [[nodiscard]] bool await_ready() const; /** - * registers the resume of the caller with the reactor of the core - * @details - * - the callback of `cth::co::wait_awaiter_base::resume()`, posted to the context of the caller - * - a failed wait: `await_resume()` throws `cth::except::coro_exception`, `code()` is `cvk::make_error_code()` - * of the result + * hands the waiter to the reactor of the core, it posts the resume to the context of the caller + * @details after the hand over nothing touches the awaiter: the resumed caller can end at once * @see `TimelineReactor::await()` */ template requires cth::co::this_coro_compatible void await_suspend(std::coroutine_handle caller); + /** + * @throws cth::except::coro_exception reason: the wait failed, `code()` is + * `cvk::make_error_code()` of the result + */ + void await_resume() const; + private: // a private helper: the reactor needs the complete jvk::Core, the template stays in the header /** - * registers the callback with the reactor of the core + * hands the waiter to the reactor of the core */ - void awaitReactor(cth::co::context::await_func cb) const; + void awaitReactor(); cth::ref_wrapper _semaphore; - uint64_t _value; + TimelineReactor::Waiter _waiter; }; } @@ -252,21 +257,6 @@ struct SemaphoreSubmitInfo { }; } -namespace jvk::dev { -/** - * callback that posts the callback to the context - * @details the reactor calls on a worker, the awaiter resumes on the context of the caller - */ -[[nodiscard]] inline cth::co::context::await_func post_to( - cth::co::context const& context, - cth::co::context::await_func cb -) { - return [&context, cb = std::move(cb)](std::error_code error) mutable { - context.post([cb = std::move(cb), error]() mutable { cb(error); }); - }; -} -} - namespace jvk { constexpr void Semaphore::debug_check(Semaphore const& semaphore) { cvk::TimelineSemaphore::debug_check(semaphore); @@ -274,6 +264,8 @@ constexpr void Semaphore::debug_check(Semaphore const& semaphore) { template requires cth::co::this_coro_compatible void semaphore_awaiter::await_suspend(std::coroutine_handle caller) { - awaitReactor(dev::post_to(caller.promise().context(), resume(caller))); + _waiter.caller = caller; + _waiter.contextPtr = &caller.promise().context(); + awaitReactor(); } } diff --git a/jvk/incl/jvk/sync/timeline_reactor.hpp b/jvk/incl/jvk/sync/timeline_reactor.hpp index a0326809..1fcf7c7d 100644 --- a/jvk/incl/jvk/sync/timeline_reactor.hpp +++ b/jvk/incl/jvk/sync/timeline_reactor.hpp @@ -5,41 +5,39 @@ #include #include -#include +#include #include #include #include #include #include #include -#include namespace cvk { class Core; } -namespace cth::co { -class scheduler; -} - namespace jvk { /** * waits for timeline semaphores on one thread * @details - * - posts the callbacks to the worker scheduler, the thread runs no callback + * - posts the resume of a reached waiter to the context of its caller, the thread resumes no caller * - wakes only when a waited value is reached or a smaller wait comes in + * - no allocation per wait: the waiter is a node in the awaiter of the caller, see + * `semaphore_awaiter` * - thread safe * - a created reactor does not move and takes no move assignment: its thread refers to it */ class TimelineReactor { public: + struct Waiter; + /** * base constructor - * @param workers run the callbacks */ - TimelineReactor(cvk::Core const&, cth::co::scheduler const& workers); + explicit TimelineReactor(cvk::Core const&); /** * @note calls `optDestroy()` @@ -58,7 +56,7 @@ class TimelineReactor { /** * stops the thread, destroys the wake semaphore * @pre `created()` - * @pre no callback is pending + * @pre no waiter is pending */ void destroy(); @@ -71,39 +69,38 @@ class TimelineReactor { } /** - * calls the callback on a worker once the semaphore reaches the value - * @details the callback gets the result of the wait: - * - empty `std::error_code` -> reached - * - a failed `vkWaitSemaphores()` of the thread -> every pending callback gets `cvk::make_error_code()` of the - * result, the thread ends, later callbacks get the same code at once - * @param cb to call + * resumes the caller of the waiter on its context once the semaphore reaches the value + * @details + * - posts the resume to `Waiter::contextPtr`, also for a value that is reached already + * - `Waiter::error` empty -> reached + * - a failed `vkWaitSemaphores()` of the thread -> every pending waiter gets + * `cvk::make_error_code()` of the result in `Waiter::error`, the thread ends, later waiters + * get the same code at once + * - the reactor holds the waiter until the post of its resume, then never touches it again + * @param[out] waiter with `Waiter::value`, `Waiter::caller` and `Waiter::contextPtr`, gets the + * error * @pre `created()` * @pre the semaphore is a timeline semaphore of the core - * @pre the semaphore is not destroyed while the callback is pending - * @throws cvk::vk_result_exception result of `vkSignalSemaphore()` for the wake semaphore + * @pre the semaphore and the waiter are not destroyed while the waiter is pending + * @throws cvk::vk_result_exception result of `vkSignalSemaphore()` for the wake semaphore, the + * waiter stays out */ - void await(VkSemaphore, uint64_t value, cth::co::context::await_func cb) const; + void await(VkSemaphore, Waiter& waiter) const; /** - * @return a callback waits for the semaphore + * @return a waiter waits for the semaphore */ [[nodiscard]] bool pending(VkSemaphore) const; [[nodiscard]] constexpr bool created() const { return _wake.created(); } private: - /** - * callback for a value of a semaphore - */ - struct Waiter { - uint64_t value; - cth::co::context::await_func cb; - }; - - using waiter_map_t = cth::dt::flat_hash_map>; + /** the first waiter per semaphore, the list is sorted by `Waiter::value` */ + using waiter_map_t = cth::dt::flat_hash_map; /** - * thread function: waits for the semaphores with waiters and the wake semaphore, posts the reached callbacks + * thread function: waits for the semaphores with waiters and the wake semaphore, posts the + * reached resumes * @details stop request -> ends at the next wake */ void run(std::stop_token); @@ -116,18 +113,20 @@ class TimelineReactor { void wake() const; /** - * stores the error, takes every pending callback - * @return the callbacks to post with the error + * stores the error, takes every pending waiter with the error + * @return the list of the waiters, linked by `Waiter::nextPtr` * @pre the caller holds `TimelineReactor::_mutexPtr` */ - [[nodiscard]] std::vector fail(std::error_code) const; + [[nodiscard]] Waiter* fail(std::error_code) const; /** - * posts the callback to the workers + * posts the resume of every waiter of the list to its context + * @details reads `Waiter::nextPtr` before the post: the resumed caller can destroy the waiter + * at once + * @param waiters the list, linked by `Waiter::nextPtr`, `nullptr` -> none + * @pre the caller holds no lock of the reactor */ - void post(cth::co::context::await_func cb, std::error_code) const; - - cth::ref_wrapper _workers; + static void post(Waiter* waiters); /** the thread waits for it next to the semaphores with waiters */ mutable cvk::TimelineSemaphore _wake; @@ -136,9 +135,8 @@ class TimelineReactor { std::unique_ptr _mutexPtr = std::make_unique(); /** - * min-heap of the waiters by value per semaphore + * the waiters per semaphore * @details an entry exists while the semaphore has waiters - * @see `std::ranges::push_heap()` */ mutable waiter_map_t _waiters{}; @@ -154,3 +152,19 @@ class TimelineReactor { TimelineReactor& operator=(TimelineReactor&& other) noexcept = default; }; } + +namespace jvk { +/** + * suspended wait for a value of a timeline semaphore, a node of the reactor + * @details + * - lives in the awaiter in the frame of the suspended caller, see `semaphore_awaiter` + * - the reactor reads and writes it until it posts the resume, then never again + */ +struct TimelineReactor::Waiter { + uint64_t value; ///< to wait for + std::coroutine_handle<> caller{}; + cth::co::context const* contextPtr = nullptr; ///< of the caller, gets the post of the resume + std::error_code error{}; ///< the result of a failed wait of the reactor, empty -> reached + Waiter* nextPtr = nullptr; ///< in the list of the semaphore, then in the list of the resumes +}; +} diff --git a/jvk/src/base/core.cpp b/jvk/src/base/core.cpp index d6c3e64f..20f4641e 100644 --- a/jvk/src/base/core.cpp +++ b/jvk/src/base/core.cpp @@ -29,7 +29,7 @@ Core::Core(cvk::Instance const& instance, Config config) : : _config.workers ) }, - _reactor{*_corePtr, *_workersPtr}, + _reactor{*_corePtr}, _resourceHeap{*_corePtr, _config.heaps.resources} {} Core::Core( diff --git a/jvk/src/sync/semaphore.cpp b/jvk/src/sync/semaphore.cpp index dde99bc6..302ced7f 100644 --- a/jvk/src/sync/semaphore.cpp +++ b/jvk/src/sync/semaphore.cpp @@ -3,18 +3,27 @@ #include "jvk/base/core.hpp" #include "jvk/sync/timeline_reactor.hpp" +#include #include #include namespace jvk { -using await_func = cth::co::context::await_func; +bool semaphore_awaiter::await_ready() const { return _semaphore->gpuValue() >= _waiter.value; } -bool semaphore_awaiter::await_ready() const { return _semaphore->gpuValue() >= _value; } +void semaphore_awaiter::awaitReactor() { + // the last access to the awaiter: the reactor can post the resume before await() returns + _semaphore->core().reactor().await(_semaphore->get(), _waiter); +} -void semaphore_awaiter::awaitReactor(await_func cb) const { - _semaphore->core().reactor().await(_semaphore->get(), _value, std::move(cb)); +void semaphore_awaiter::await_resume() const { + CTH_CORO_CODE_STABLE_THROW( + _waiter.error, + _waiter.error, + "wait failed, got {}", + _waiter.error.message() + ) {} } Semaphore::Semaphore(Core const& core) : _core{core}, _semaphore{core} {} diff --git a/jvk/src/sync/timeline_reactor.cpp b/jvk/src/sync/timeline_reactor.cpp index 014f9827..fea42a78 100644 --- a/jvk/src/sync/timeline_reactor.cpp +++ b/jvk/src/sync/timeline_reactor.cpp @@ -6,23 +6,18 @@ #include "cvk/utility/vk_error_code.hpp" #include "cvk/utility/vk_exceptions.hpp" -#include #include -#include #include -#include #include #include +#include namespace jvk { using std::vector; -using await_func = cth::co::context::await_func; -TimelineReactor::TimelineReactor(cvk::Core const& core, cth::co::scheduler const& workers) : - _workers{workers}, - _wake{core} {} +TimelineReactor::TimelineReactor(cvk::Core const& core) : _wake{core} {} void TimelineReactor::create() { optDestroy(); @@ -46,7 +41,7 @@ void TimelineReactor::destroy() { std::scoped_lock const lock{*_mutexPtr}; CTH_CRITICAL( !_waiters.empty(), - "no callback must be pending, got {} semaphores", + "no waiter must be pending, got {} semaphores", _waiters.size() ) {} @@ -71,32 +66,37 @@ void TimelineReactor::destroy() { _wake.destroy(); } -void TimelineReactor::await(VkSemaphore vkSemaphore, uint64_t value, await_func cb) const { +void TimelineReactor::await(VkSemaphore vkSemaphore, Waiter& waiter) const { CTH_CRITICAL(!created(), "reactor must be created") {} CTH_CRITICAL(vkSemaphore == VK_NULL_HANDLE, "the semaphore must not be VK_NULL_HANDLE") {} + CTH_CRITICAL(waiter.contextPtr == nullptr, "the waiter must have the context of its caller") {} - std::error_code error{}; { std::scoped_lock const lock{*_mutexPtr}; if(!_error) { - // the thread waits for the smallest value per semaphore, a new smallest value needs a new wait + // the thread waits for the head per semaphore, a new head needs a new wait auto const it = _waiters.find(vkSemaphore); - bool const first = it == _waiters.end(); - if(first || value < it->second.front().value) + Waiter** linkPtr = it == _waiters.end() ? nullptr : &it->second; + if(linkPtr == nullptr || waiter.value < (*linkPtr)->value) wake(); // after the wake: a failed wake registers nothing - auto& waiters = first ? _waiters[vkSemaphore] : it->second; - waiters.push_back(Waiter{value, std::move(cb)}); - std::ranges::push_heap(waiters, std::ranges::greater{}, &Waiter::value); + if(linkPtr == nullptr) + linkPtr = &_waiters[vkSemaphore]; + // sorted by value, behind the equal values + while(*linkPtr != nullptr && (*linkPtr)->value <= waiter.value) + linkPtr = &(*linkPtr)->nextPtr; + waiter.nextPtr = *linkPtr; + *linkPtr = &waiter; return; } - error = _error; + waiter.error = _error; + waiter.nextPtr = nullptr; } - post(std::move(cb), error); + post(&waiter); } bool TimelineReactor::pending(VkSemaphore vkSemaphore) const { @@ -107,10 +107,9 @@ bool TimelineReactor::pending(VkSemaphore vkSemaphore) const { void TimelineReactor::run(std::stop_token stop) { auto const table = _wake.core().deviceTable(); + // reused per round: the vectors keep their capacity vector vkSemaphores{}; vector values{}; - vector reached{}; - vector failed{}; std::error_code error{}; while(true) { @@ -121,9 +120,9 @@ void TimelineReactor::run(std::stop_token stop) { vkSemaphores.assign({_wake.get()}); values.assign({_wake.value() + 1}); - for(auto const& [vkSemaphore, waiters] : _waiters) { + for(auto const& [vkSemaphore, head] : _waiters) { vkSemaphores.push_back(vkSemaphore); - values.push_back(waiters.front().value); + values.push_back(head->value); } } @@ -141,25 +140,35 @@ void TimelineReactor::run(std::stop_token stop) { std::numeric_limits::max() ); + // the reached waiters of every semaphore in one list, sorted by value per semaphore + Waiter* reached = nullptr; + Waiter** reachedTailPtr = &reached; + Waiter* failed = nullptr; { std::scoped_lock const lock{*_mutexPtr}; for(auto it = _waiters.begin(); result == VK_SUCCESS && it != _waiters.end();) { - auto& [vkSemaphore, waiters] = *it; + auto& [vkSemaphore, head] = *it; uint64_t counter = 0; result = table->vkGetSemaphoreCounterValue(table.device(), vkSemaphore, &counter); if(result != VK_SUCCESS) break; - while(!waiters.empty() && waiters.front().value <= counter) { - std::ranges::pop_heap(waiters, std::ranges::greater{}, &Waiter::value); - reached.push_back(std::move(waiters.back().cb)); - waiters.pop_back(); + // the reached head part moves to the reached list, the list stays sorted + Waiter* last = nullptr; + for(auto* waiter = head; waiter != nullptr && waiter->value <= counter; + waiter = waiter->nextPtr) + last = waiter; + if(last != nullptr) { + *reachedTailPtr = head; + reachedTailPtr = &last->nextPtr; + head = last->nextPtr; + last->nextPtr = nullptr; } // erase() keeps the other iterators valid - if(waiters.empty()) + if(head == nullptr) _waiters.erase(it++); else ++it; @@ -176,14 +185,11 @@ void TimelineReactor::run(std::stop_token stop) { } } - for(auto& cb : reached) - post(std::move(cb), {}); - reached.clear(); + post(reached); - // the error ends the thread, later callbacks get the error at once in await() + // the error ends the thread, later waiters get the error at once in await() if(error) { - for(auto& cb : failed) - post(std::move(cb), error); + post(failed); return; } } @@ -191,19 +197,30 @@ void TimelineReactor::run(std::stop_token stop) { void TimelineReactor::wake() const { _wake.signal(); } -vector TimelineReactor::fail(std::error_code error) const { +auto TimelineReactor::fail(std::error_code error) const -> Waiter* { _error = error; - vector callbacks{}; - for(auto& [vkSemaphore, waiters] : _waiters) - for(auto& waiter : waiters) - callbacks.push_back(std::move(waiter.cb)); + Waiter* failed = nullptr; + for(auto& [vkSemaphore, head] : _waiters) + while(head != nullptr) { + auto* const waiter = head; + head = waiter->nextPtr; + waiter->error = error; + waiter->nextPtr = failed; + failed = waiter; + } _waiters.clear(); - return callbacks; + return failed; } -void TimelineReactor::post(await_func cb, std::error_code error) const { - _workers->post([cb = std::move(cb), error]() mutable { cb(error); }); +void TimelineReactor::post(Waiter* waiters) { + while(waiters != nullptr) { + // the resumed caller can destroy the waiter at once: nothing touches it after the post + auto* const next = waiters->nextPtr; + auto const caller = waiters->caller; + waiters->contextPtr->post([caller] { caller.resume(); }); + waiters = next; + } } } diff --git a/jvk/tests/src/base/core_test.cpp b/jvk/tests/src/base/core_test.cpp index a7b90f26..7ae4be56 100644 --- a/jvk/tests/src/base/core_test.cpp +++ b/jvk/tests/src/base/core_test.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include @@ -221,21 +222,23 @@ JVK_TEST(Core, reactor_waits_after_a_new_create) { for(size_t round = 0; round < 2; ++round) { ASSERT_TRUE(core.reactor().created()); - cvk::TimelineSemaphore semaphore{core, cvk::create}; - - std::promise promise{}; - auto result = promise.get_future(); - core.reactor().await( - semaphore.get(), - 1, - [promise = std::move(promise)](std::error_code error) mutable { - promise.set_value(error); - } + Semaphore semaphore{core, cvk::create}; + + auto wait = [](Semaphore const& s) -> cth::co::executor_task { co_await s.wait(1); }; + auto result = std::async( + std::launch::async, + [&core, &semaphore, wait] { core.executor().sync_wait(wait(semaphore)); } ); - [[maybe_unused]] auto const signaled = semaphore.signal(); + auto const end = std::chrono::steady_clock::now() + std::chrono::seconds{5}; + while(!core.reactor().pending(semaphore.get()) && std::chrono::steady_clock::now() < end) + std::this_thread::yield(); + ASSERT_TRUE(core.reactor().pending(semaphore.get())); + core.executor().sync_wait( + core.queue(0).submit({.signals = {{.semaphore = semaphore, .value = 1}}}) + ); ASSERT_EQ(result.wait_for(std::chrono::seconds{5}), std::future_status::ready); - EXPECT_FALSE(result.get()); + result.get(); semaphore.destroy(); core.destroy(); diff --git a/jvk/tests/src/sync/timeline_reactor_test.cpp b/jvk/tests/src/sync/timeline_reactor_test.cpp index 76a85ee6..2ecfb1ac 100644 --- a/jvk/tests/src/sync/timeline_reactor_test.cpp +++ b/jvk/tests/src/sync/timeline_reactor_test.cpp @@ -7,13 +7,20 @@ #include "cvk/render/sync/timeline_semaphore.hpp" +#include +#include #include +#include +#include #include +#include #include #include #include +#include #include +#include #include #include @@ -22,43 +29,108 @@ namespace jvk { namespace { using namespace std::chrono_literals; - constexpr auto REACHED_TIMEOUT = 5s; ///< a reached value calls its callback before it - constexpr auto PENDING_TIMEOUT = 50ms; ///< a pending callback does not come within it + constexpr auto REACHED_TIMEOUT = 5s; ///< a reached value resumes its waiter before it + constexpr auto PENDING_TIMEOUT = 50ms; ///< a pending waiter does not resume within it /** - * what the callback of a wait got + * what a wait got at its resume */ - struct CallbackResult { + struct WaitResult { std::error_code error; bool onWorker; }; /** - * registers a callback with the reactor of the core - * @return result of the callback + * awaiter of a wait of the reactor: the waiter lives in the frame of the caller */ - [[nodiscard]] std::future await_value( - Core const& core, + class reactor_wait : public cth::co::this_coro_awaiter_base { + public: + reactor_wait( + TimelineReactor const& reactor, + VkSemaphore vkSemaphore, + uint64_t value, + std::atomic& registered + ) : + _reactor{reactor}, + _vkSemaphore{vkSemaphore}, + _waiter{.value = value}, + _registered{registered} {} + + [[nodiscard]] static constexpr bool await_ready() noexcept { return false; } + + template + void await_suspend(std::coroutine_handle caller) { + _waiter.caller = caller; + _waiter.contextPtr = &caller.promise().context(); + // the resume can end the frame before await() returns: the flag lives outside of it + auto& registered = _registered; + _reactor.await(_vkSemaphore, _waiter); + registered = true; + } + + [[nodiscard]] std::error_code await_resume() const noexcept { return _waiter.error; } + + private: + TimelineReactor const& _reactor; + VkSemaphore _vkSemaphore; + TimelineReactor::Waiter _waiter; + std::atomic& _registered; + }; + + /** + * waits with the reactor, then gives the result + */ + cth::co::executor_task wait_task( + TimelineReactor const& reactor, + cth::co::context const& workers, + VkSemaphore vkSemaphore, + uint64_t value, + std::shared_ptr> registered, + std::promise promise + ) { + auto const error = co_await reactor_wait{reactor, vkSemaphore, value, *registered}; + promise.set_value({error, workers.owns_thread()}); + } + + /** + * starts a wait of the reactor on the workers, returns once the reactor has the waiter + * @return result of the wait + */ + [[nodiscard]] std::future await_value( + TimelineReactor const& reactor, + cth::co::context const& workers, VkSemaphore vkSemaphore, uint64_t value ) { - std::promise promise{}; + auto registered = std::make_shared>(false); + std::promise promise{}; auto future = promise.get_future(); - core.reactor().await( - vkSemaphore, - value, - [&core, promise = std::move(promise)](std::error_code error) mutable { - promise.set_value({error, core.executor().context().owns_thread()}); - } + cth::co::executor{workers}.detach( + wait_task(reactor, workers, vkSemaphore, value, registered, std::move(promise)) ); + auto const end = std::chrono::steady_clock::now() + REACHED_TIMEOUT; + while(!registered->load() && std::chrono::steady_clock::now() < end) + std::this_thread::yield(); + EXPECT_TRUE(registered->load()) << "the reactor got no waiter"; return future; } - [[nodiscard]] bool reached(std::future const& future) { + /** + * a wait with the reactor of the core + */ + [[nodiscard]] std::future await_value( + Core const& core, + VkSemaphore vkSemaphore, + uint64_t value + ) { + return await_value(core.reactor(), core.executor().context(), vkSemaphore, value); + } + + [[nodiscard]] bool reached(std::future const& future) { return future.wait_for(REACHED_TIMEOUT) == std::future_status::ready; } - [[nodiscard]] bool pending(std::future const& future) { + [[nodiscard]] bool pending(std::future const& future) { return future.wait_for(PENDING_TIMEOUT) == std::future_status::timeout; } @@ -89,17 +161,15 @@ namespace { JVK_TEST(TimelineReactor, base_constructor_does_not_create) { test::Context const context{}; - cth::co::scheduler const workers{}; - TimelineReactor const reactor{context.core, workers}; + TimelineReactor const reactor{context.core}; EXPECT_FALSE(reactor.created()); } JVK_TEST(TimelineReactor, create_and_destroy) { test::Context const context{}; - cth::co::scheduler workers{cth::co::autostart}; - TimelineReactor reactor{context.core, workers}; + TimelineReactor reactor{context.core}; reactor.create(); EXPECT_TRUE(reactor.created()); @@ -111,32 +181,28 @@ JVK_TEST(TimelineReactor, create_and_destroy) { EXPECT_TRUE(reactor.created()); } -JVK_TEST(TimelineReactor, a_moved_reactor_creates_and_calls_the_callback) { +JVK_TEST(TimelineReactor, a_moved_reactor_creates_and_resumes_a_waiter) { test::Context const context{}; cth::co::scheduler workers{cth::co::autostart}; cvk::TimelineSemaphore semaphore{context.core, cvk::create}; - TimelineReactor reactor{context.core, workers}; + TimelineReactor reactor{context.core}; TimelineReactor moved{std::move(reactor)}; - TimelineReactor other{context.core, workers}; + TimelineReactor other{context.core}; other = std::move(moved); other.create(); EXPECT_TRUE(other.created()); - std::promise promise{}; - auto result = promise.get_future(); - other.await( - semaphore.get(), - 1, - [promise = std::move(promise)](std::error_code error) mutable { promise.set_value(error); } - ); + auto result = await_value(other, workers, semaphore.get(), 1); host_signal(semaphore, 1); - ASSERT_EQ(result.wait_for(REACHED_TIMEOUT), std::future_status::ready); - EXPECT_FALSE(result.get()); + ASSERT_TRUE(reached(result)); + auto const [error, onWorker] = result.get(); + EXPECT_FALSE(error); + EXPECT_TRUE(onWorker); } -JVK_TEST(TimelineReactor, gpu_signal_calls_the_callback_on_a_worker) { +JVK_TEST(TimelineReactor, gpu_signal_resumes_the_waiter_on_its_context) { test::Context const context{}; cvk::TimelineSemaphore const semaphore{context.core, cvk::create}; @@ -176,7 +242,7 @@ JVK_TEST(TimelineReactor, several_semaphores_and_values_out_of_order) { EXPECT_TRUE(reached(first3)); } -JVK_TEST(TimelineReactor, host_signal_calls_the_callback) { +JVK_TEST(TimelineReactor, host_signal_resumes_the_waiter) { test::Context const context{}; cvk::TimelineSemaphore semaphore{context.core, cvk::create}; @@ -208,7 +274,7 @@ JVK_TEST(TimelineReactor, many_waits_on_one_value) { test::Context const context{}; cvk::TimelineSemaphore const semaphore{context.core, cvk::create}; - std::vector> results{}; + std::vector> results{}; for(size_t i = 0; i < WAITS; ++i) results.push_back(await_value(context.core, semaphore.get(), 1)); @@ -218,7 +284,7 @@ JVK_TEST(TimelineReactor, many_waits_on_one_value) { EXPECT_TRUE(reached(result)); } -JVK_TEST(TimelineReactor, reached_value_calls_the_callback) { +JVK_TEST(TimelineReactor, a_reached_value_resumes_the_waiter) { test::Context const context{}; cvk::TimelineSemaphore const semaphore{context.core, cvk::create, 3}; From ddffabda6fd3b737127e5f7a2614c778ca5f4458 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:14:20 +0100 Subject: [PATCH 32/68] jvk, cvk: the submit infos without allocations per frame - reused storage: each stage slot keeps its SubmitInfo and the extra waits of its stage, the presenter keeps one for its present jobs, cleared and refilled per frame - Queue::submit(), Queue::present() and dev::fallback_submit() take the info by const&: no copy for the fallback, also not for the skips that go through it every frame - no cvk::SubmitInfo in between: jvk::Queue converts its info into strand-only Vulkan arrays and calls cvk::Queue::rawSubmit() - cvk: wait_submit_info(), signal_submit_info() and cmd_buffer_submit_info() public, used by cvk::Queue::submit() too - the present semaphore goes straight into the conversion - per frame (headless MAILBOX, 2 workers): operator new 45 -> 22 --- cvk/incl/cvk/base/queue/submit_info.hpp | 20 ++++++ cvk/src/base/queue/queue.cpp | 66 ++----------------- cvk/src/base/queue/submit_info.cpp | 82 ++++++++++++++++++++++++ cvk/tests/src/base/queue/submit_test.cpp | 32 +++++++++ jvk/incl/jvk/base/queue.hpp | 41 ++++++++++-- jvk/incl/jvk/graph/presenter.hpp | 11 +++- jvk/incl/jvk/graph/stage.hpp | 35 ++++++---- jvk/incl/jvk/graph/stage_graph.hpp | 11 ++-- jvk/src/base/queue.cpp | 75 +++++++++++++--------- jvk/src/graph/presenter.cpp | 31 +++++---- jvk/src/graph/stage.cpp | 15 ++--- jvk/src/graph/stage_graph.cpp | 24 +++---- jvk/tests/src/graph/stage_graph_test.cpp | 21 ++++++ 13 files changed, 309 insertions(+), 155 deletions(-) create mode 100644 cvk/src/base/queue/submit_info.cpp diff --git a/cvk/incl/cvk/base/queue/submit_info.hpp b/cvk/incl/cvk/base/queue/submit_info.hpp index 2195e43e..7d792b99 100644 --- a/cvk/incl/cvk/base/queue/submit_info.hpp +++ b/cvk/incl/cvk/base/queue/submit_info.hpp @@ -61,4 +61,24 @@ struct SubmitInfo { std::vector waits{}; std::vector signals{}; }; + +/** + * vulkan info of a wait + * @details timeline semaphore, `std::nullopt` value -> waits for `TimelineSemaphore::value()` + * @pre the semaphore is created + */ +[[nodiscard]] VkSemaphoreSubmitInfo wait_submit_info(SemaphoreSubmitInfo const& wait); + +/** + * vulkan info of a signal + * @details timeline semaphore, `std::nullopt` value -> signals `TimelineSemaphore::next()` + * @pre the semaphore is created + */ +[[nodiscard]] VkSemaphoreSubmitInfo signal_submit_info(SemaphoreSubmitInfo const& signal); + +/** + * vulkan info of a command buffer of a submit + * @pre the command buffer is created and ended its recording + */ +[[nodiscard]] VkCommandBufferSubmitInfo cmd_buffer_submit_info(PrimaryCmdBuffer const& cmdBuffer); } diff --git a/cvk/src/base/queue/queue.cpp b/cvk/src/base/queue/queue.cpp index 1b9ab098..e35c2dfb 100644 --- a/cvk/src/base/queue/queue.cpp +++ b/cvk/src/base/queue/queue.cpp @@ -2,58 +2,14 @@ #include "cvk/render/cmd/cmd_buffer.hpp" #include "cvk/render/sync/fence.hpp" -#include "cvk/render/sync/semaphore.hpp" -#include "cvk/render/sync/timeline_semaphore.hpp" #include "cvk/utility/vk_exceptions.hpp" -#include -#include #include namespace cvk { using std::span; -namespace { - VkSemaphoreSubmitInfo vk_semaphore_info( - VkSemaphore vkSemaphore, - uint64_t value, - VkPipelineStageFlags2 stages - ) { - return VkSemaphoreSubmitInfo{ - .sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO, - .pNext = nullptr, - .semaphore = vkSemaphore, - .value = value, - .stageMask = stages, - .deviceIndex = 0, - }; - } - - /** - * @param resolve the value of a timeline semaphore without value - */ - template - VkSemaphoreSubmitInfo semaphore_info(SemaphoreSubmitInfo const& info, Resolve resolve) { - return std::visit( - [&](cth::ref_wrapper semaphore) { - T::debug_check(semaphore); - - if constexpr(std::same_as) { - auto const value = info.value.has_value() - ? *info.value - : resolve(semaphore.get()); - return vk_semaphore_info(semaphore.get().get(), value, info.stages); - } else { - CTH_CRITICAL(info.value.has_value(), "binary semaphores have no value") {} - return vk_semaphore_info(semaphore.get().get(), 0, info.stages); - } - }, - info.semaphore - ); - } -} - Queue::Queue(QueueFamilyProperties familyProperties, State const& state) : _familyProperties {familyProperties}, _functionsPtr{&state.functions.get()}, @@ -81,32 +37,18 @@ void Queue::submit(span infos, Fence const* fencePtr) const { std::vector submits{}; submits.reserve(infos.size()); - auto const waitValue = [](TimelineSemaphore const& timeline) { return timeline.value(); }; - auto const signalValue = [](TimelineSemaphore const& timeline) { return timeline.next(); }; - for(auto const& info : infos) { auto const* const waits = semaphores.data() + semaphores.size(); for(auto const& wait : info.waits) - semaphores.push_back(semaphore_info(wait, waitValue)); + semaphores.push_back(wait_submit_info(wait)); auto const* const signals = semaphores.data() + semaphores.size(); for(auto const& signal : info.signals) - semaphores.push_back(semaphore_info(signal, signalValue)); + semaphores.push_back(signal_submit_info(signal)); auto const* const buffers = cmdBuffers.data() + cmdBuffers.size(); - for(PrimaryCmdBuffer const& cmdBuffer : info.cmdBuffers) { - BaseCmdBuffer::debug_check(cmdBuffer); - CTH_CRITICAL(cmdBuffer.recording(), "command buffers must end their recording first") {} - - cmdBuffers.push_back( - VkCommandBufferSubmitInfo{ - .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO, - .pNext = nullptr, - .commandBuffer = cmdBuffer.get(), - .deviceMask = 0, - } - ); - } + for(PrimaryCmdBuffer const& cmdBuffer : info.cmdBuffers) + cmdBuffers.push_back(cmd_buffer_submit_info(cmdBuffer)); submits.push_back( VkSubmitInfo2{ diff --git a/cvk/src/base/queue/submit_info.cpp b/cvk/src/base/queue/submit_info.cpp new file mode 100644 index 00000000..d7503523 --- /dev/null +++ b/cvk/src/base/queue/submit_info.cpp @@ -0,0 +1,82 @@ +#include "cvk/base/queue/submit_info.hpp" + +#include "cvk/render/cmd/cmd_buffer.hpp" +#include "cvk/render/sync/semaphore.hpp" +#include "cvk/render/sync/timeline_semaphore.hpp" + +#include + +#include +#include + + +namespace cvk { +namespace { + [[nodiscard]] VkSemaphoreSubmitInfo vk_semaphore_info( + VkSemaphore vkSemaphore, + uint64_t value, + VkPipelineStageFlags2 stages + ) { + return VkSemaphoreSubmitInfo{ + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO, + .pNext = nullptr, + .semaphore = vkSemaphore, + .value = value, + .stageMask = stages, + .deviceIndex = 0, + }; + } + + /** + * @param resolve the value of a timeline semaphore without value + */ + template + [[nodiscard]] VkSemaphoreSubmitInfo semaphore_info( + SemaphoreSubmitInfo const& info, + Resolve resolve + ) { + return std::visit( + [&](cth::ref_wrapper semaphore) { + T::debug_check(semaphore); + + if constexpr(std::same_as) { + auto const value = info.value.has_value() + ? *info.value + : resolve(semaphore.get()); + return vk_semaphore_info(semaphore.get().get(), value, info.stages); + } else { + CTH_CRITICAL(info.value.has_value(), "binary semaphores have no value") {} + return vk_semaphore_info(semaphore.get().get(), 0, info.stages); + } + }, + info.semaphore + ); + } +} + +VkSemaphoreSubmitInfo wait_submit_info(SemaphoreSubmitInfo const& wait) { + return semaphore_info( + wait, + [](TimelineSemaphore const& timeline) { return timeline.value(); } + ); +} + +VkSemaphoreSubmitInfo signal_submit_info(SemaphoreSubmitInfo const& signal) { + return semaphore_info( + signal, + [](TimelineSemaphore const& timeline) { return timeline.next(); } + ); +} + +VkCommandBufferSubmitInfo cmd_buffer_submit_info(PrimaryCmdBuffer const& cmdBuffer) { + BaseCmdBuffer::debug_check(cmdBuffer); + CTH_CRITICAL(cmdBuffer.recording(), "command buffers must end their recording first") {} + + return VkCommandBufferSubmitInfo{ + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO, + .pNext = nullptr, + .commandBuffer = cmdBuffer.get(), + .deviceMask = 0, + }; +} +} diff --git a/cvk/tests/src/base/queue/submit_test.cpp b/cvk/tests/src/base/queue/submit_test.cpp index fa664849..40e6e880 100644 --- a/cvk/tests/src/base/queue/submit_test.cpp +++ b/cvk/tests/src/base/queue/submit_test.cpp @@ -34,6 +34,38 @@ CVK_TEST(Submit, semaphore_info_takes_the_kind_from_the_semaphore) { EXPECT_EQ(timelineInfo.value, 3); } +CVK_TEST(Submit, wait_info_takes_the_counter_signal_info_the_next_value) { + test::Context const context{}; + Semaphore const binary{context.core, create}; + TimelineSemaphore const timeline{context.core, create}; + + auto const wait = wait_submit_info({timeline, VK_PIPELINE_STAGE_2_TRANSFER_BIT}); + auto const signal = signal_submit_info({timeline}); + auto const explicitSignal = signal_submit_info({timeline, VK_PIPELINE_STAGE_2_NONE, 5}); + auto const binaryWait = wait_submit_info({binary}); + + EXPECT_EQ(wait.semaphore, timeline.get()); + EXPECT_EQ(wait.value, 0); + EXPECT_EQ(wait.stageMask, VK_PIPELINE_STAGE_2_TRANSFER_BIT); + EXPECT_EQ(signal.value, 1); + EXPECT_EQ(explicitSignal.value, 5); + EXPECT_EQ(timeline.value(), 1); + EXPECT_EQ(binaryWait.semaphore, binary.get()); + EXPECT_EQ(binaryWait.value, 0); +} + +CVK_TEST(Submit, cmd_buffer_info_takes_the_handle) { + test::Context const context{}; + CmdPool const pool{context.core, test::pool_config(context.core), create}; + PrimaryCmdBuffer primary{pool, create}; + + auto const info = cmd_buffer_submit_info(primary); + + EXPECT_EQ(info.sType, VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO); + EXPECT_EQ(info.commandBuffer, primary.get()); + EXPECT_EQ(info.deviceMask, 0); +} + CVK_TEST(Submit, command_buffer_without_fence) { test::Context const context{}; CmdPool const pool{context.core, test::pool_config(context.core), create}; diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index b4789130..730d7b16 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -24,6 +24,7 @@ class scheduler; } namespace cvk { +class Semaphore; class Swapchain; } @@ -47,6 +48,18 @@ struct SubmitInfo { std::vector signals{}; ///< marked after the submit std::vector binarySignals{}; + + /** + * removes the command buffers and the semaphores + * @details keeps the capacity: a refill allocates nothing once the vectors are large enough + */ + constexpr void clear() { + cmdBuffers.clear(); + waits.clear(); + binaryWaits.clear(); + signals.clear(); + binarySignals.clear(); + } }; /** @@ -80,11 +93,12 @@ class Queue { * submits the batch in the strand, then marks the jvk signals * @details a failed submit marks nothing: the caller submits a fallback, see * `dev::fallback_submit()` + * @pre the info lives until the end of the task, nothing changes it * @pre the preconditions of `cvk::Queue::submit()` * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` * @see `present()` */ - [[nodiscard]] cth::co::executor_task submit(SubmitInfo) const; + [[nodiscard]] cth::co::executor_task submit(SubmitInfo const&) const; /** * submits the batch and presents the image in one job of the strand, then marks the jvk signals @@ -97,12 +111,13 @@ class Queue { * @param imageIdx of the acquired image * @return `VK_SUCCESS`, `VK_SUBOPTIMAL_KHR` or `VK_ERROR_OUT_OF_DATE_KHR` * @pre `cvk::Queue::canPresent()` + * @pre the info lives until the end of the task, nothing changes it * @pre the preconditions of `cvk::Queue::submit()` and of `cvk::Swapchain::present()` * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` * @throws cvk::vk_result_exception other result of `vkQueuePresentKHR()` */ [[nodiscard]] cth::co::executor_task present( - SubmitInfo, + SubmitInfo const&, cvk::Swapchain& swapchain, uint32_t imageIdx ) const; @@ -153,11 +168,18 @@ class Queue { private: /** - * submits the batch through the cvk queue + * submits the batch through `cvk::Queue::rawSubmit()` + * @details resolves the `std::nullopt` timeline values in order: the waits, then the signals + * @param presentSemaphorePtr `nullptr` -> no present semaphore, else signaled after the signals + * of the info * @pre runs in the strand + * @pre the preconditions of `cvk::Queue::submit()` * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` */ - void submitInStrand(SubmitInfo const&) const; + void submitInStrand( + SubmitInfo const&, + cvk::Semaphore const* presentSemaphorePtr = nullptr + ) const; /** * command buffer of one release @@ -186,6 +208,14 @@ class Queue { mutable std::deque _releaseCmds{}; ///< used in the strand only + // members, no locals: submitInStrand() refills them, they keep their capacity + /** the command buffers of the submit in `submitInStrand()`, used in the strand only */ + mutable std::vector _cmdBufferInfos{}; + /** the waits of the submit in `submitInStrand()`, used in the strand only */ + mutable std::vector _waitInfos{}; + /** the signals of the submit in `submitInStrand()`, used in the strand only */ + mutable std::vector _signalInfos{}; + //TODO review the counter decides the reuse of the release command buffers, no reactor wait: a release reads it mutable Semaphore _released; ///< the release counter, raised by each release submit @@ -208,10 +238,11 @@ namespace jvk::dev { * @param queue of the failed submit * @param info waits and signals of the failed submit, no command buffers * @param[out] jobs of the caller, gets a device loss + * @pre the info lives until the end of the task, nothing changes it */ [[nodiscard]] cth::co::executor_task fallback_submit( Queue const& queue, - SubmitInfo info, + SubmitInfo const& info, cth::co::catching_scope& jobs ); } diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/presenter.hpp index 14744312..e411e392 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -1,4 +1,5 @@ #pragma once +#include "jvk/base/queue.hpp" #include "jvk/cmd/cmd_buffer.hpp" #include "jvk/graph/swapchain.hpp" #include "jvk/sync/resource_tracker.hpp" @@ -31,7 +32,6 @@ class ImageView; namespace jvk { class Core; -class Queue; class Stage; class StageGraph; class scoped_acquire; @@ -247,9 +247,10 @@ class Presenter { * present job of `present()` * @details the order: * - off the strand: awaits `Semaphore::submitted()` of the stage semaphore with the frame number - * - stage of another family -> `Queue::release()` of the image on the stage queue * - off the strand: awaits `Presenter::_presented` of the job before: the present jobs run one * at a time, in the order of `present()` + * - fills `Presenter::_submitInfo`: the job before ended its use + * - stage of another family -> `Queue::release()` of the image on the stage queue * - off the strand: records the command buffer, the present jobs run one at a time * - `Queue::present()` with the current swapchain: a recreation only happens in `acquire()`, * after the last present @@ -335,6 +336,12 @@ class Presenter { std::vector _submits{}; ///< one per swapchain image + /** + * the submit of the present job that runs, `Presenter::_presented` orders its uses + * @details each present job fills it: it keeps its capacity for the next jobs + */ + SubmitInfo _submitInfo{}; + /** the acquired image without a present */ std::optional _acquiredOpt = std::nullopt; diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index 399ab62a..23b6c8c2 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -43,7 +43,7 @@ namespace jvk::dev { * @details * - the graph builds it once, at its construction * - holds the values of the next submit or skip of the slot - * - builds the `SubmitInfo` of the next submit or skip: a skip has no command buffers + * - fills the `SubmitInfo` of the next submit or skip: a skip has no command buffers */ struct SlotSubmit { /** `StageSlot::prologue`, `StageSlot::primary` */ @@ -62,13 +62,15 @@ struct SlotSubmit { SemaphoreSubmitInfo signal; ///< `StageSlot::semaphore` with the frame number /** - * the skip of the slot: the waits and the signal without the command buffers + * fills the info with the skip of the slot: the waits and the signal, no command buffers * @details waits for `SlotSubmit::waits` and the extra waits, signals `SlotSubmit::signal` + * @param[out] info gets the skip, `SubmitInfo::clear()` first * @param extraWaits the jvk waits of the stage * @param extraBinaryWaits the binary waits of the stage * @see `addCmdBuffers()` */ - [[nodiscard]] SubmitInfo skipInfo( + void skipInfo( + SubmitInfo& info, std::span extraWaits, std::span extraBinaryWaits ) const; @@ -155,6 +157,24 @@ struct StageSlot { /** the waits and the signal of the next submit or skip, see `SlotSubmit::next()` */ SlotSubmit slotSubmit; + // the next three in the stage slot, not in the stage: they keep their capacity for the next + // frames of the slot + // one list per kind of wait: the jvk waits keep the jvk semaphore + /** the jvk waits of `Stage::await()` in the frame of the slot, the submit job clears them */ + std::vector extraWaits{}; + + /** the binary waits of `Stage::await()` in the frame of the slot, the submit job clears them */ + std::vector extraBinaryWaits{}; + + /** + * the submit or the skip of the frame of the slot + * @details + * - the submit job fills it, see `SlotSubmit::skipInfo()` + * - one job at a time: `StageGraph::nextFrame()` hands out the slot again after the mark of + * the job + */ + SubmitInfo submitInfo{}; + /** the stage in the frame slot before, submits first */ cth::ref_wrapper previous; @@ -395,15 +415,6 @@ class Stage { uint64_t _frameNumber; Status _status = Status::UNSUBMITTED; - // one list per kind of wait: the jvk waits keep the jvk semaphore - /** the waits of @ref await(SemaphoreSubmitInfo const&) */ - std::vector _extraWaits{}; - - /** - * the waits of @ref await(cvk::Semaphore const&, VkPipelineStageFlags2) - */ - std::vector _extraBinaryWaits{}; - /** the images and buffers of `retain()`, under `StageSlot::stasisMutex` */ dev::RetainedResources _retained{}; diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index eb3cb0b4..f5104c93 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -169,8 +169,6 @@ class StageGraph { using release_map_t = cth::dt::flat_hash_map; - using semaphore_waits_t = std::vector; - /** * skips the stages of the frame in the slot without `Stage::submit()` or `Stage::skip()` * @details a skipped stage that other stages wait for: warns @@ -184,8 +182,8 @@ class StageGraph { * @details * - takes `Stasis::end()` of the stage slot and the retained resources of the stage under * `StageSlot::stasisMutex` - * - a failed allocation: the stage stays `UNSUBMITTED` without its waits and retained resources, the exception - * destroys the graph + * - a failed allocation: the stage stays `UNSUBMITTED` without its retained resources, the exception destroys + * the graph * @param targetStatus `SUBMITTED` or `SKIPPED` */ void detachJob(Stage&, Stage::Status targetStatus); @@ -201,7 +199,8 @@ class StageGraph { * waits of `StageSlot::slotSubmit` and of every jvk extra wait: the appends follow the * dependency order * - the binary extra waits: no await on the cpu - * - `SlotSubmit::skipInfo()` of the frame, then `SlotSubmit::next()` + * - `SlotSubmit::skipInfo()` of the frame into `StageSlot::submitInfo`, clears the extra waits + * of the slot, then `SlotSubmit::next()` * - `SUBMITTED`: `append()` of the states of the primary under `StageGraph::_statesMutex`, `release()` of the * release halves, records the prologue, an empty prologue: no record, the submit without it * - `SUBMITTED`: `Queue::submit()` with the release waits, it marks the slot with the frame @@ -223,8 +222,6 @@ class StageGraph { [[nodiscard]] cth::co::executor_task submitJob( dev::StageSlot&, uint64_t frameNumber, - std::vector extraWaits, - semaphore_waits_t extraBinaryWaits, dev::RetainedResources retained, Stasis::pos stasisEnd, Stage::Status targetStatus diff --git a/jvk/src/base/queue.cpp b/jvk/src/base/queue.cpp index 98c906f7..5e22ceaa 100644 --- a/jvk/src/base/queue.cpp +++ b/jvk/src/base/queue.cpp @@ -12,30 +12,10 @@ #include #include #include -#include namespace jvk { namespace { - /** - * the cvk batch: the jvk semaphores, then the binary ones - */ - [[nodiscard]] cvk::SubmitInfo to_cvk(SubmitInfo const& info) { - cvk::SubmitInfo vkInfo{}; - vkInfo.cmdBuffers.reserve(info.cmdBuffers.size()); - for(PrimaryCmdBuffer const& cmdBuffer : info.cmdBuffers) - vkInfo.cmdBuffers.emplace_back(cmdBuffer); - - vkInfo.waits.reserve(info.waits.size() + info.binaryWaits.size()); - vkInfo.waits.append_range(info.waits); - vkInfo.waits.append_range(info.binaryWaits); - - vkInfo.signals.reserve(info.signals.size() + info.binarySignals.size()); - vkInfo.signals.append_range(info.signals); - vkInfo.signals.append_range(info.binarySignals); - return vkInfo; - } - /** * marks the jvk signals, see `Semaphore::markSubmitted()` */ @@ -61,7 +41,7 @@ void Queue::waitIdle() const { ); } -cth::co::executor_task Queue::submit(SubmitInfo info) const { +cth::co::executor_task Queue::submit(SubmitInfo const& info) const { co_await executor().schedule(); submitInStrand(info); @@ -69,16 +49,14 @@ cth::co::executor_task Queue::submit(SubmitInfo info) const { } cth::co::executor_task Queue::present( - SubmitInfo info, + SubmitInfo const& info, cvk::Swapchain& swapchain, uint32_t imageIdx ) const { - info.binarySignals.emplace_back(swapchain.presentSemaphore(imageIdx)); - // no suspension between the submit and the present: the presents follow the order of the // submits co_await executor().schedule(); - submitInStrand(info); + submitInStrand(info, &swapchain.presentSemaphore(imageIdx)); // the marks after the present: a waiter for them uses the swapchain after vkQueuePresentKHR() VkResult result{}; @@ -115,7 +93,43 @@ cth::co::executor_task Queue::release(cvk::Barrier barriers co_return signal; } -void Queue::submitInStrand(SubmitInfo const& info) const { _queue->submit(to_cvk(info)); } +void Queue::submitInStrand( + SubmitInfo const& info, + cvk::Semaphore const* presentSemaphorePtr +) const { + _cmdBufferInfos.clear(); + for(PrimaryCmdBuffer const& cmdBuffer : info.cmdBuffers) + _cmdBufferInfos.push_back(cvk::cmd_buffer_submit_info(cmdBuffer)); + + // the waits first: the order of the value resolution in cvk::Queue::submit() + _waitInfos.clear(); + for(auto const& wait : info.waits) + _waitInfos.push_back(cvk::wait_submit_info(wait)); + for(auto const& wait : info.binaryWaits) + _waitInfos.push_back(cvk::wait_submit_info(wait)); + + _signalInfos.clear(); + for(auto const& signal : info.signals) + _signalInfos.push_back(cvk::signal_submit_info(signal)); + for(auto const& signal : info.binarySignals) + _signalInfos.push_back(cvk::signal_submit_info(signal)); + if(presentSemaphorePtr != nullptr) + _signalInfos.push_back(cvk::signal_submit_info({*presentSemaphorePtr})); + + _queue->rawSubmit( + VkSubmitInfo2{ + .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO_2, + .pNext = nullptr, + .flags = 0, + .waitSemaphoreInfoCount = static_cast(_waitInfos.size()), + .pWaitSemaphoreInfos = _waitInfos.data(), + .commandBufferInfoCount = static_cast(_cmdBufferInfos.size()), + .pCommandBufferInfos = _cmdBufferInfos.data(), + .signalSemaphoreInfoCount = static_cast(_signalInfos.size()), + .pSignalSemaphoreInfos = _signalInfos.data(), + } + ); +} auto Queue::freeReleaseCmd() const -> ReleaseCmd& { auto const reached = _released.gpuValue(); @@ -135,15 +149,12 @@ auto Queue::freeReleaseCmd() const -> ReleaseCmd& { namespace dev { cth::co::executor_task fallback_submit( Queue const& queue, - SubmitInfo info, + SubmitInfo const& info, cth::co::catching_scope& jobs ) { - // a copy: the submit takes the info - auto const signals = info.signals; - // every failure but a device loss terminates: nobody marks the signals, the waiters would // hang - try { co_await queue.submit(std::move(info)); } + try { co_await queue.submit(info); } catch(cvk::vk_result_exception const& e) { if(e.vkResult() != VK_ERROR_DEVICE_LOST) { JVK_STABLE_ERR(true, "the fallback submit failed, got {}", e.vkResult()) {} @@ -151,7 +162,7 @@ namespace dev { } jobs.store(std::current_exception()); // the failed submit marked nothing: the waiters of the marks go on - mark(signals); + mark(info.signals); } catch(...) { std::terminate(); } } diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index 4794a5aa..3d05d4bf 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -22,12 +22,9 @@ #include #include #include -#include namespace jvk { -using std::vector; - Presenter::Presenter(Core const& core, Queue const& queue, Config config) : _core{core}, _queue{queue}, @@ -221,12 +218,6 @@ cth::co::executor_task Presenter::presentJob( auto const vkImage = image.image->get(); auto const aspectMask = image.image->aspectMask(); - // noexcept: without the waits no fallback signals the value, the waiters would hang - auto waits = [&]() noexcept { - return vector{{.semaphore = stageSemaphore, .value = frameNumber}}; - }(); - SemaphoreSubmitInfo const signal{.semaphore = _semaphore, .value = value}; - // off the strand: a wait before the signal on one queue would block it, the release needs the submit of the stage, // the next acquire() sets the state of the image in the graph after the submit job of the stage appended its states co_await stageSemaphore.submitted(frameNumber); @@ -234,6 +225,16 @@ cth::co::executor_task Presenter::presentJob( // values of the command buffers, signaled the value before and wrote the flag co_await _presented.wait(value - 1); + // after the job before: it used the info until its end + // noexcept: without the wait and the signal no fallback signals the value, the waiters would + // hang + auto& info = _submitInfo; + [&]() noexcept { + info.clear(); + info.waits.push_back({.semaphore = stageSemaphore, .value = frameNumber}); + info.signals.push_back({.semaphore = _semaphore, .value = value}); + }(); + try { ImageState const presentState{ .layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, @@ -248,7 +249,7 @@ cth::co::executor_task Presenter::presentJob( aspectMask, dev::release_half(lastState, presentState, stageFamily, family, 0) ); - waits.push_back(co_await stageQueue.release(std::move(release))); + info.waits.push_back(co_await stageQueue.release(std::move(release))); barrier.add( vkImage, @@ -277,14 +278,11 @@ cth::co::executor_task Presenter::presentJob( submit.cmd.end(); // before the submit: the empty submit of a failed one signals the value too submit.value = value; + info.cmdBuffers.push_back(submit.cmd); // the swapchain of the image is the current one: a recreation only happens in acquire(), // after the end of the last present job - auto const result = co_await queue.present( - {.cmdBuffers = {submit.cmd}, .waits = waits, .signals = {signal}}, - _swapchain.current(), - image.imageIdx - ); + auto const result = co_await queue.present(info, _swapchain.current(), image.imageIdx); // before _presented.set(): the next acquire() reads it if(result == VK_ERROR_OUT_OF_DATE_KHR) _outOfDate = true; @@ -298,7 +296,8 @@ cth::co::executor_task Presenter::presentJob( // noexcept: a failed start of the fallback leaves the value unmarked, the waiters would // hang auto fallback = [&]() noexcept { - return dev::fallback_submit(queue, {.waits = waits, .signals = {signal}}, _jobs); + info.cmdBuffers.clear(); + return dev::fallback_submit(queue, info, _jobs); }(); co_await std::move(fallback); } diff --git a/jvk/src/graph/stage.cpp b/jvk/src/graph/stage.cpp index 1a258002..b5dd968e 100644 --- a/jvk/src/graph/stage.cpp +++ b/jvk/src/graph/stage.cpp @@ -39,18 +39,17 @@ namespace { } } -SubmitInfo SlotSubmit::skipInfo( +void SlotSubmit::skipInfo( + SubmitInfo& info, std::span extraWaits, std::span extraBinaryWaits ) const { - SubmitInfo info{ - .binaryWaits = {extraBinaryWaits.begin(), extraBinaryWaits.end()}, - .signals = {signal}, - }; + info.clear(); info.waits.reserve(waits.size() + extraWaits.size()); info.waits.append_range(waits); info.waits.append_range(extraWaits); - return info; + info.binaryWaits.append_range(extraBinaryWaits); + info.signals.push_back(signal); } void SlotSubmit::addCmdBuffers(SubmitInfo& info, bool prologue) const { @@ -135,12 +134,12 @@ SecondaryCmdBuffer Stage::persistentSecondary() const { void Stage::await(SemaphoreSubmitInfo const& wait) { CTH_CRITICAL(_status != Status::UNSUBMITTED, "the stage must be unsubmitted") {} - _extraWaits.push_back(wait); + _stageSlot->extraWaits.push_back(wait); } void Stage::await(cvk::Semaphore const& binary, VkPipelineStageFlags2 stages) { CTH_CRITICAL(_status != Status::UNSUBMITTED, "the stage must be unsubmitted") {} - _extraBinaryWaits.emplace_back(binary, stages); + _stageSlot->extraBinaryWaits.emplace_back(binary, stages); } void Stage::submit() { _stageSlot->graph->submit(*this); } diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index 7bb5d88f..1e6de044 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -114,7 +114,7 @@ StageGraph::~StageGraph() { // the binary waits dropped: a presenter is destroyed before the graph, its present // submits wait for the semaphores of the graph, the acquire semaphore of an unpresented // image is destroyed already - stage._extraBinaryWaits.clear(); + stage._stageSlot->extraBinaryWaits.clear(); try { skip(stage); } catch(std::exception const& e) { JVK_STABLE_ERR( @@ -272,8 +272,6 @@ void StageGraph::detachJob(Stage& stage, Stage::Status targetStatus) { submitJob( stageSlot, stage._frameNumber, - std::move(stage._extraWaits), - std::move(stage._extraBinaryWaits), std::move(retained), stasisEnd, targetStatus @@ -285,13 +283,12 @@ void StageGraph::detachJob(Stage& stage, Stage::Status targetStatus) { cth::co::executor_task StageGraph::submitJob( dev::StageSlot& stageSlot, uint64_t frameNumber, - vector extraWaits, - semaphore_waits_t extraBinaryWaits, dev::RetainedResources retained, Stasis::pos stasisEnd, Stage::Status targetStatus ) { auto& slotSubmit = stageSlot.slotSubmit; + auto& info = stageSlot.submitInfo; auto const& queue = *stageSlot.queue; // the marks first, off the strand: a wait before the signal on one queue would block it, the appends follow the @@ -299,13 +296,18 @@ cth::co::executor_task StageGraph::submitJob( co_await stageSlot.previous->semaphore.submitted(frameNumber - 1); for(auto const& wait : slotSubmit.waits) co_await wait.semaphore->submitted(wait.value); - for(auto const& wait : extraWaits) + for(auto const& wait : stageSlot.extraWaits) co_await wait.semaphore->submitted(wait.value); // the values of this frame, then next(): the job of the next frame of the slot reads them after // the mark // noexcept: without the skip info no fallback marks the slot, the waiters would hang - auto info = [&]() noexcept { return slotSubmit.skipInfo(extraWaits, extraBinaryWaits); }(); + [&]() noexcept { + slotSubmit.skipInfo(info, stageSlot.extraWaits, stageSlot.extraBinaryWaits); + }(); + // the stage of the next frame of the slot adds its own + stageSlot.extraWaits.clear(); + stageSlot.extraBinaryWaits.clear(); slotSubmit.next(_config.frameSlots); bool submitted = false; @@ -329,9 +331,8 @@ cth::co::executor_task StageGraph::submitJob( stageSlot.prologue.end(); } - auto submitInfo = info; - slotSubmit.addCmdBuffers(submitInfo, withPrologue); - co_await queue.submit(std::move(submitInfo)); + slotSubmit.addCmdBuffers(info, withPrologue); + co_await queue.submit(info); submitted = true; } // the job goes on with the skip @@ -342,7 +343,8 @@ cth::co::executor_task StageGraph::submitJob( if(!submitted) { // noexcept: a failed start of the fallback leaves the slot unmarked, the waiters would hang auto fallback = [&]() noexcept { - return dev::fallback_submit(queue, std::move(info), _jobs); + info.cmdBuffers.clear(); + return dev::fallback_submit(queue, info, _jobs); }(); co_await std::move(fallback); } diff --git a/jvk/tests/src/graph/stage_graph_test.cpp b/jvk/tests/src/graph/stage_graph_test.cpp index 9346434b..bf36b62d 100644 --- a/jvk/tests/src/graph/stage_graph_test.cpp +++ b/jvk/tests/src/graph/stage_graph_test.cpp @@ -527,6 +527,27 @@ JVK_TEST(StageGraph, extra_jvk_wait_and_binary_wait) { EXPECT_EQ(external.gpuValue(), 1); } +JVK_TEST(StageGraph, extra_waits_end_with_their_frame) { + test::Context const context{}; + Core core{context.instance, test::Context::CONFIG, {}}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; + cvk::Semaphore const binary{core, cvk::create}; + + core.executor().sync_wait(submit(core.queue(0), {.signals = {binary}})); + auto& first = next_frame(core, graph).stage(0); + first.await(binary); + submit_empty(first); + wait(core, first); + + // up to the next frame of the slot: the binary semaphore has no signal, a wait for it fails + // the validation + for(size_t i = 0; i < graph.config().frameSlots; ++i) { + auto& stage = next_frame(core, graph).stage(0); + submit_empty(stage); + wait(core, stage); + } +} + JVK_TEST(StageGraph, secondaries_record_on_several_threads) { constexpr size_t SECONDARIES = 4; test::Context const context{}; From c6dcb683524acbc10dbc8384def7d4daa3910eab Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:14:20 +0100 Subject: [PATCH 33/68] jvk: the reactor keeps its waiters in one std::vector, no intrusive list - Pending{vkSemaphore, waiter} in one vector for all semaphores, it keeps its capacity - the wait arrays take the smallest value per semaphore, std::ranges::partition takes out the reached waiters, the counters are read outside the lock - the waiter loses its link, the map and the sorted insert go away --- jvk/incl/jvk/sync/timeline_reactor.hpp | 36 +++--- jvk/src/sync/timeline_reactor.cpp | 159 +++++++++++++------------ 2 files changed, 102 insertions(+), 93 deletions(-) diff --git a/jvk/incl/jvk/sync/timeline_reactor.hpp b/jvk/incl/jvk/sync/timeline_reactor.hpp index 1fcf7c7d..17a09881 100644 --- a/jvk/incl/jvk/sync/timeline_reactor.hpp +++ b/jvk/incl/jvk/sync/timeline_reactor.hpp @@ -4,15 +4,17 @@ #include #include -#include +#include #include #include #include #include +#include #include #include #include +#include namespace cvk { @@ -25,8 +27,8 @@ namespace jvk { * @details * - posts the resume of a reached waiter to the context of its caller, the thread resumes no caller * - wakes only when a waited value is reached or a smaller wait comes in - * - no allocation per wait: the waiter is a node in the awaiter of the caller, see - * `semaphore_awaiter` + * - no allocation per wait: the waiter lives in the awaiter of the caller, see + * `semaphore_awaiter`, the pending list keeps its capacity * - thread safe * - a created reactor does not move and takes no move assignment: its thread refers to it */ @@ -95,8 +97,11 @@ class TimelineReactor { [[nodiscard]] constexpr bool created() const { return _wake.created(); } private: - /** the first waiter per semaphore, the list is sorted by `Waiter::value` */ - using waiter_map_t = cth::dt::flat_hash_map; + /** pending waiter and its semaphore */ + struct Pending { + VkSemaphore vkSemaphore; + cth::ref_wrapper waiter; + }; /** * thread function: waits for the semaphores with waiters and the wake semaphore, posts the @@ -114,19 +119,17 @@ class TimelineReactor { /** * stores the error, takes every pending waiter with the error - * @return the list of the waiters, linked by `Waiter::nextPtr` + * @param[out] waiters gets the pending waiters * @pre the caller holds `TimelineReactor::_mutexPtr` */ - [[nodiscard]] Waiter* fail(std::error_code) const; + void fail(std::error_code, std::vector>& waiters) const; /** - * posts the resume of every waiter of the list to its context - * @details reads `Waiter::nextPtr` before the post: the resumed caller can destroy the waiter - * at once - * @param waiters the list, linked by `Waiter::nextPtr`, `nullptr` -> none + * posts the resume of every waiter to its context + * @details touches no waiter after its post: the resumed caller can destroy it at once * @pre the caller holds no lock of the reactor */ - static void post(Waiter* waiters); + static void post(std::span const> waiters); /** the thread waits for it next to the semaphores with waiters */ mutable cvk::TimelineSemaphore _wake; @@ -135,10 +138,10 @@ class TimelineReactor { std::unique_ptr _mutexPtr = std::make_unique(); /** - * the waiters per semaphore - * @details an entry exists while the semaphore has waiters + * the pending waiters of every semaphore, in no order + * @details keeps its capacity: no allocation once it is large enough */ - mutable waiter_map_t _waiters{}; + mutable std::vector _pending{}; mutable std::error_code _error{}; ///< the result of a failed wait of the thread, empty -> none @@ -155,7 +158,7 @@ class TimelineReactor { namespace jvk { /** - * suspended wait for a value of a timeline semaphore, a node of the reactor + * suspended wait for a value of a timeline semaphore * @details * - lives in the awaiter in the frame of the suspended caller, see `semaphore_awaiter` * - the reactor reads and writes it until it posts the resume, then never again @@ -165,6 +168,5 @@ struct TimelineReactor::Waiter { std::coroutine_handle<> caller{}; cth::co::context const* contextPtr = nullptr; ///< of the caller, gets the post of the resume std::error_code error{}; ///< the result of a failed wait of the reactor, empty -> reached - Waiter* nextPtr = nullptr; ///< in the list of the semaphore, then in the list of the resumes }; } diff --git a/jvk/src/sync/timeline_reactor.cpp b/jvk/src/sync/timeline_reactor.cpp index fea42a78..c4092bda 100644 --- a/jvk/src/sync/timeline_reactor.cpp +++ b/jvk/src/sync/timeline_reactor.cpp @@ -8,8 +8,10 @@ #include +#include #include #include +#include #include #include @@ -40,9 +42,9 @@ void TimelineReactor::destroy() { { std::scoped_lock const lock{*_mutexPtr}; CTH_CRITICAL( - !_waiters.empty(), - "no waiter must be pending, got {} semaphores", - _waiters.size() + !_pending.empty(), + "no waiter must be pending, got {}", + _pending.size() ) {} _thread.request_stop(); @@ -61,7 +63,7 @@ void TimelineReactor::destroy() { _thread.join(); _thread = {}; - _waiters.clear(); + _pending.clear(); _error = {}; _wake.destroy(); } @@ -75,43 +77,53 @@ void TimelineReactor::await(VkSemaphore vkSemaphore, Waiter& waiter) const { std::scoped_lock const lock{*_mutexPtr}; if(!_error) { - // the thread waits for the head per semaphore, a new head needs a new wait - auto const it = _waiters.find(vkSemaphore); - Waiter** linkPtr = it == _waiters.end() ? nullptr : &it->second; - if(linkPtr == nullptr || waiter.value < (*linkPtr)->value) + // the thread waits for the smallest value per semaphore, a smaller one needs a new wait + bool const smallest = std::ranges::none_of( + _pending, + [&](Pending const& pending) { + return pending.vkSemaphore == vkSemaphore + && pending.waiter->value <= waiter.value; + } + ); + if(smallest) wake(); // after the wake: a failed wake registers nothing - if(linkPtr == nullptr) - linkPtr = &_waiters[vkSemaphore]; - // sorted by value, behind the equal values - while(*linkPtr != nullptr && (*linkPtr)->value <= waiter.value) - linkPtr = &(*linkPtr)->nextPtr; - waiter.nextPtr = *linkPtr; - *linkPtr = &waiter; + _pending.push_back({.vkSemaphore = vkSemaphore, .waiter = waiter}); return; } waiter.error = _error; - waiter.nextPtr = nullptr; } - post(&waiter); + cth::ref_wrapper const failed{waiter}; + post({&failed, 1}); } bool TimelineReactor::pending(VkSemaphore vkSemaphore) const { std::scoped_lock const lock{*_mutexPtr}; - return _waiters.contains(vkSemaphore); + return std::ranges::contains(_pending, vkSemaphore, &Pending::vkSemaphore); } void TimelineReactor::run(std::stop_token stop) { auto const table = _wake.core().deviceTable(); // reused per round: the vectors keep their capacity + // the wait arrays: the wake semaphore first, then each semaphore with its smallest value vector vkSemaphores{}; vector values{}; + // the counter per semaphore of the wait arrays + vector counters{}; + // the waiters to post, after a failure every pending one + vector> reached{}; std::error_code error{}; + // the index of the semaphore in the wait arrays, the size -> not in them + auto const indexOf = [&vkSemaphores](VkSemaphore vkSemaphore) { + auto const it = std::ranges::find(vkSemaphores, vkSemaphore); + return static_cast(it - vkSemaphores.begin()); + }; + while(true) { { std::scoped_lock const lock{*_mutexPtr}; @@ -120,9 +132,14 @@ void TimelineReactor::run(std::stop_token stop) { vkSemaphores.assign({_wake.get()}); values.assign({_wake.value() + 1}); - for(auto const& [vkSemaphore, head] : _waiters) { - vkSemaphores.push_back(vkSemaphore); - values.push_back(head->value); + for(auto const& [vkSemaphore, waiter] : _pending) { + auto const semaphoreIdx = indexOf(vkSemaphore); + if(semaphoreIdx < vkSemaphores.size()) + values[semaphoreIdx] = std::min(values[semaphoreIdx], waiter->value); + else { + vkSemaphores.push_back(vkSemaphore); + values.push_back(waiter->value); + } } } @@ -140,87 +157,77 @@ void TimelineReactor::run(std::stop_token stop) { std::numeric_limits::max() ); - // the reached waiters of every semaphore in one list, sorted by value per semaphore - Waiter* reached = nullptr; - Waiter** reachedTailPtr = &reached; - Waiter* failed = nullptr; + // off the lock: the semaphores of the wait arrays keep their waiters until the partition + // below, the wake semaphore needs no counter + counters.resize(vkSemaphores.size()); + for(size_t semaphoreIdx = 1; semaphoreIdx < vkSemaphores.size(); ++semaphoreIdx) { + // the first failure ends the reads, also a failed wait + if(result != VK_SUCCESS) + break; + result = table->vkGetSemaphoreCounterValue( + table.device(), + vkSemaphores[semaphoreIdx], + &counters[semaphoreIdx] + ); + } + + reached.clear(); { std::scoped_lock const lock{*_mutexPtr}; - for(auto it = _waiters.begin(); result == VK_SUCCESS && it != _waiters.end();) { - auto& [vkSemaphore, head] = *it; - - uint64_t counter = 0; - result = table->vkGetSemaphoreCounterValue(table.device(), vkSemaphore, &counter); - if(result != VK_SUCCESS) - break; - - // the reached head part moves to the reached list, the list stays sorted - Waiter* last = nullptr; - for(auto* waiter = head; waiter != nullptr && waiter->value <= counter; - waiter = waiter->nextPtr) - last = waiter; - if(last != nullptr) { - *reachedTailPtr = head; - reachedTailPtr = &last->nextPtr; - head = last->nextPtr; - last->nextPtr = nullptr; - } - - // erase() keeps the other iterators valid - if(head == nullptr) - _waiters.erase(it++); - else - ++it; - } - - if(result != VK_SUCCESS) { + if(result == VK_SUCCESS) { + // the reached waiters to the end, a semaphore outside of the wait arrays stays: its + // await() woke the thread for the next wait + auto const reachedRange = std::ranges::partition( + _pending, + [&](Pending const& pending) { + auto const semaphoreIdx = indexOf(pending.vkSemaphore); + return semaphoreIdx == vkSemaphores.size() + || pending.waiter->value > counters[semaphoreIdx]; + } + ); + for(auto const& pending : reachedRange) + reached.push_back(pending.waiter); + _pending.erase(reachedRange.begin(), reachedRange.end()); + } else { JVK_STABLE_ERR( true, "the reactor failed to wait for the semaphores, got {}", result ) {} error = cvk::make_error_code(result); - failed = fail(error); + fail(error, reached); } } post(reached); // the error ends the thread, later waiters get the error at once in await() - if(error) { - post(failed); + if(error) return; - } } } void TimelineReactor::wake() const { _wake.signal(); } -auto TimelineReactor::fail(std::error_code error) const -> Waiter* { +void TimelineReactor::fail( + std::error_code error, + vector>& waiters +) const { _error = error; - Waiter* failed = nullptr; - for(auto& [vkSemaphore, head] : _waiters) - while(head != nullptr) { - auto* const waiter = head; - head = waiter->nextPtr; - waiter->error = error; - waiter->nextPtr = failed; - failed = waiter; - } - _waiters.clear(); - - return failed; + for(auto const& pending : _pending) { + pending.waiter->error = error; + waiters.push_back(pending.waiter); + } + _pending.clear(); } -void TimelineReactor::post(Waiter* waiters) { - while(waiters != nullptr) { +void TimelineReactor::post(std::span const> waiters) { + for(Waiter& waiter : waiters) { // the resumed caller can destroy the waiter at once: nothing touches it after the post - auto* const next = waiters->nextPtr; - auto const caller = waiters->caller; - waiters->contextPtr->post([caller] { caller.resume(); }); - waiters = next; + auto const caller = waiter.caller; + waiter.contextPtr->post([caller] { caller.resume(); }); } } } From ac45bab8bb65be028a1910de08134f764108b378 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:30:25 +0100 Subject: [PATCH 34/68] lib: cth with co::all() over a range without allocations for ready children --- lib/cth | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/cth b/lib/cth index 638a02f7..7c5f1f74 160000 --- a/lib/cth +++ b/lib/cth @@ -1 +1 @@ -Subproject commit 638a02f7921c731131a789a7ea54bbe728791923 +Subproject commit 7c5f1f7445a7fe6f0af6349721f3f01d3347ed97 From c7727bd909e232968569cb218f984edfb64a6f33 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:29:25 +0100 Subject: [PATCH 35/68] jvk: dev::fallback_submit() is dev::skip_submit(), one name for the submit of a skip - most calls are the plain skip of a stage, the failed submit is the rarer case - "fallback" and "empty submit" become "skip submit" in the docs, comments and the test --- jvk/incl/jvk/base/queue.hpp | 12 ++++++------ jvk/incl/jvk/graph/presenter.hpp | 4 ++-- jvk/incl/jvk/graph/stage_graph.hpp | 6 +++--- jvk/src/base/queue.cpp | 4 ++-- jvk/src/graph/presenter.cpp | 18 +++++++++--------- jvk/src/graph/stage_graph.cpp | 11 ++++++----- jvk/tests/src/base/queue_test.cpp | 4 ++-- 7 files changed, 30 insertions(+), 29 deletions(-) diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index 730d7b16..a34a7d3a 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -91,8 +91,7 @@ class Queue { /** * submits the batch in the strand, then marks the jvk signals - * @details a failed submit marks nothing: the caller submits a fallback, see - * `dev::fallback_submit()` + * @details a failed submit marks nothing: the caller skips it, see `dev::skip_submit()` * @pre the info lives until the end of the task, nothing changes it * @pre the preconditions of `cvk::Queue::submit()` * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` @@ -229,18 +228,19 @@ class Queue { namespace jvk::dev { /** - * the empty submit after a failed submit: the waiters of its jvk signals go on + * submits the waits and the signals of a skip, no command buffers * @details + * - a skip, also of a failed submit: the waiters of the jvk signals go on * - `Queue::submit()` marks the signals * - `VK_ERROR_DEVICE_LOST` -> stores the error in the scope, marks the signals: the gpu waits end * on their own * - another failure terminates: the waiters would hang - * @param queue of the failed submit - * @param info waits and signals of the failed submit, no command buffers + * @param queue of the skipped submit + * @param info waits and signals of the skipped submit, no command buffers * @param[out] jobs of the caller, gets a device loss * @pre the info lives until the end of the task, nothing changes it */ -[[nodiscard]] cth::co::executor_task fallback_submit( +[[nodiscard]] cth::co::executor_task skip_submit( Queue const& queue, SubmitInfo const& info, cth::co::catching_scope& jobs diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/presenter.hpp index e411e392..f58803b7 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -261,9 +261,9 @@ class Presenter { * `Presenter::_presented` * - the last step, also after a failure: sets `Presenter::_presented` to the value * @details the errors: - * - a failed submit: stores the error, then `dev::fallback_submit()` that signals only + * - a failed submit: stores the error, then `dev::skip_submit()` that signals only * `Presenter::_semaphore`, no present - * - a failed empty submit: `VK_ERROR_DEVICE_LOST` -> stores the error, marks, else terminates: + * - a failed skip submit: `VK_ERROR_DEVICE_LOST` -> stores the error, marks, else terminates: * the waiters would hang * - a failed present: stores the error * - before the end: every other failure terminates, the waiters on `Presenter::_presented` diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index f5104c93..8db38594 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -116,10 +116,10 @@ class StageGraph { * submits no work for the stage in this frame * @details sets the status of the stage to `SKIPPED`, thread safe for different stages * @details returns at once, the strand of the queue submits after the waited stages submitted - * @details empty submit on the queue of the stage: + * @details skip submit on the queue of the stage, no command buffers: * - waits for the stage waits of the config and the waits of `Stage::await()` * - signals `Stage::semaphore()` with `Stage::frameNumber()` - * @details after the gpu finished the empty submit: destroys the retained objects + * @details after the gpu finished the skip submit: destroys the retained objects * @details a begun primary: ends its rendering and the primary, discards the recording * @pre the stage is of this graph * @pre `Stage::status()` is `UNSUBMITTED` @@ -205,7 +205,7 @@ class StageGraph { * release halves, records the prologue, an empty prologue: no record, the submit without it * - `SUBMITTED`: `Queue::submit()` with the release waits, it marks the slot with the frame * number - * - `SKIPPED` or a failed submit: `dev::fallback_submit()` of the skip info + * - `SKIPPED` or a failed submit: `dev::skip_submit()` of the skip info * - on the workers of the core: after the gpu finished, erases the states of the retained resources, then * `Stasis::clear()` to `stasisEnd` * @details the errors: diff --git a/jvk/src/base/queue.cpp b/jvk/src/base/queue.cpp index 5e22ceaa..0b2121f0 100644 --- a/jvk/src/base/queue.cpp +++ b/jvk/src/base/queue.cpp @@ -147,7 +147,7 @@ auto Queue::freeReleaseCmd() const -> ReleaseCmd& { } namespace dev { - cth::co::executor_task fallback_submit( + cth::co::executor_task skip_submit( Queue const& queue, SubmitInfo const& info, cth::co::catching_scope& jobs @@ -157,7 +157,7 @@ namespace dev { try { co_await queue.submit(info); } catch(cvk::vk_result_exception const& e) { if(e.vkResult() != VK_ERROR_DEVICE_LOST) { - JVK_STABLE_ERR(true, "the fallback submit failed, got {}", e.vkResult()) {} + JVK_STABLE_ERR(true, "the skip submit failed, got {}", e.vkResult()) {} std::terminate(); } jobs.store(std::current_exception()); diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index 3d05d4bf..d9796fb4 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -226,8 +226,8 @@ cth::co::executor_task Presenter::presentJob( co_await _presented.wait(value - 1); // after the job before: it used the info until its end - // noexcept: without the wait and the signal no fallback signals the value, the waiters would - // hang + // noexcept: without the wait and the signal no skip submit signals the value, the waiters + // would hang auto& info = _submitInfo; [&]() noexcept { info.clear(); @@ -276,7 +276,7 @@ cth::co::executor_task Presenter::presentJob( submit.cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); barrier.execute(submit.cmd); submit.cmd.end(); - // before the submit: the empty submit of a failed one signals the value too + // before the submit: the skip submit of a failed one signals the value too submit.value = value; info.cmdBuffers.push_back(submit.cmd); @@ -287,19 +287,19 @@ cth::co::executor_task Presenter::presentJob( if(result == VK_ERROR_OUT_OF_DATE_KHR) _outOfDate = true; } - // the job goes on with the fallback and _presented.set() + // the job goes on with the skip submit and _presented.set() catch(...) { _jobs.store(std::current_exception()); } - // a failed submit marks nothing: the empty submit signals the value for the waits on the + // a failed submit marks nothing: the skip submit signals the value for the waits on the // presenter if(_semaphore.submittedValue() < value) { - // noexcept: a failed start of the fallback leaves the value unmarked, the waiters would + // noexcept: a failed start of the skip submit leaves the value unmarked, the waiters would // hang - auto fallback = [&]() noexcept { + auto skip = [&]() noexcept { info.cmdBuffers.clear(); - return dev::fallback_submit(queue, info, _jobs); + return dev::skip_submit(queue, info, _jobs); }(); - co_await std::move(fallback); + co_await std::move(skip); } // the last step, also after a failure: nothing before it escapes, the waiters would hang diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index 1e6de044..985a7218 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -301,7 +301,7 @@ cth::co::executor_task StageGraph::submitJob( // the values of this frame, then next(): the job of the next frame of the slot reads them after // the mark - // noexcept: without the skip info no fallback marks the slot, the waiters would hang + // noexcept: without the skip info no skip submit marks the slot, the waiters would hang [&]() noexcept { slotSubmit.skipInfo(info, stageSlot.extraWaits, stageSlot.extraBinaryWaits); }(); @@ -341,12 +341,13 @@ cth::co::executor_task StageGraph::submitJob( // a skip, also of a failed submit: the gpu waits of other stages and the waits in ~StageGraph() end if(!submitted) { - // noexcept: a failed start of the fallback leaves the slot unmarked, the waiters would hang - auto fallback = [&]() noexcept { + // noexcept: a failed start of the skip submit leaves the slot unmarked, the waiters would + // hang + auto skip = [&]() noexcept { info.cmdBuffers.clear(); - return dev::fallback_submit(queue, info, _jobs); + return dev::skip_submit(queue, info, _jobs); }(); - co_await std::move(fallback); + co_await std::move(skip); } // after the mark: a failed gpu wait escapes, _jobs stores it, the retained objects stay for diff --git a/jvk/tests/src/base/queue_test.cpp b/jvk/tests/src/base/queue_test.cpp index 0a3a550f..307fdbda 100644 --- a/jvk/tests/src/base/queue_test.cpp +++ b/jvk/tests/src/base/queue_test.cpp @@ -460,14 +460,14 @@ JVK_TEST(Queue, submit_waits_for_the_jvk_and_the_binary_waits) { static_cast(done).wait(1); } -JVK_TEST(Queue, fallback_submit_marks_through_the_submit) { +JVK_TEST(Queue, skip_submit_marks_through_the_submit) { test::Context const context{}; auto const& queue = context.core.queue(0); Semaphore const semaphore{context.core, cvk::create}; cth::co::catching_scope jobs{}; context.core.executor().sync_wait( - dev::fallback_submit(queue, {.signals = {{.semaphore = semaphore, .value = 1}}}, jobs) + dev::skip_submit(queue, {.signals = {{.semaphore = semaphore, .value = 1}}}, jobs) ); EXPECT_FALSE(jobs.failed()); From bcdd1ce7adc3cf02bf7ce751f1e7874c816cdb71 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:38:11 +0100 Subject: [PATCH 36/68] jvk: the workers of the core are a plain cth::co::scheduler again - since the reactor takes no workers, nothing refers to them before create() - only the cvk core stays behind a std::unique_ptr, the moves stay = default --- jvk/incl/jvk/base/core.hpp | 6 ++++-- jvk/src/base/core.cpp | 20 +++++++++----------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/jvk/incl/jvk/base/core.hpp b/jvk/incl/jvk/base/core.hpp index 686782f3..3b00c6c2 100644 --- a/jvk/incl/jvk/base/core.hpp +++ b/jvk/incl/jvk/base/core.hpp @@ -128,7 +128,7 @@ class Core { */ [[nodiscard]] constexpr cth::co::executor executor() const { debug_check(*this); - return cth::co::executor{*_workersPtr}; + return cth::co::executor{_workers}; } /** @@ -184,7 +184,9 @@ class Core { // behind a std::unique_ptr: the reactor and the heaps refer to the cvk core also before // create(), the moves stay = default std::unique_ptr _corePtr; - std::unique_ptr _workersPtr; + + // destroyed after the reactor and the queues, before the cvk core + cth::co::scheduler _workers; // destroyed after the queues, before the workers and the cvk core: it posts the resumes of its // waiters to their contexts diff --git a/jvk/src/base/core.cpp b/jvk/src/base/core.cpp index 20f4641e..4d948217 100644 --- a/jvk/src/base/core.cpp +++ b/jvk/src/base/core.cpp @@ -22,12 +22,10 @@ using std::span; Core::Core(cvk::Instance const& instance, Config config) : _config{std::move(config)}, _corePtr{std::make_unique(instance)}, - _workersPtr{ - std::make_unique( - _config.workers == 0 - ? std::max(std::thread::hardware_concurrency(), 1u) - : _config.workers - ) + _workers{ + _config.workers == 0 + ? std::max(std::thread::hardware_concurrency(), 1u) + : _config.workers }, _reactor{*_corePtr}, _resourceHeap{*_corePtr, _config.heaps.resources} {} @@ -56,7 +54,7 @@ void Core::create(span const> surfaces) { // the cvk core exists before the workers, the reactor and the queues, only a catch can destroy it when a later // step fails try { - _workersPtr->start(); + _workers.start(); _reactor.create(); createQueues(); if(_config.heaps.createsResourceHeap()) @@ -68,7 +66,7 @@ void Core::create(span const> surfaces) { _resourceHeap.optDestroy(); destroyQueues(); _reactor.optDestroy(); - _workersPtr->await_stop(); + _workers.await_stop(); _corePtr->destroy(); throw; } @@ -76,7 +74,7 @@ void Core::create(span const> surfaces) { void Core::destroy() { debug_check(*this); - CTH_CRITICAL(_workersPtr->owns_thread(), "destroy() must not run on a worker of the core") {} + CTH_CRITICAL(_workers.owns_thread(), "destroy() must not run on a worker of the core") {} // one wait per vulkan queue: the first index of each vulkan queue @@ -117,7 +115,7 @@ void Core::destroy() { _samplerHeapOpt.reset(); _resourceHeap.optDestroy(); _reactor.destroy(); - _workersPtr->await_stop(); + _workers.await_stop(); _corePtr->destroy(); } @@ -146,7 +144,7 @@ void Core::createQueues() { _driverSchedulerOpt.emplace(cth::co::autostart, _config.driverThreads); cth::co::scheduler const& scheduler = _driverSchedulerOpt.has_value() ? *_driverSchedulerOpt - : *_workersPtr; + : _workers; auto const indices = _corePtr->queueIndices(); _queues.reserve(indices.size()); From 71eb2c93d71d0a2f52bc95f83c94cb036ed8987a Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:33:28 +0100 Subject: [PATCH 37/68] lib: cth with the fix of a foreign thread that calls into a context at its destruction --- lib/cth | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/cth b/lib/cth index 7c5f1f74..329aee48 160000 --- a/lib/cth +++ b/lib/cth @@ -1 +1 @@ -Subproject commit 7c5f1f7445a7fe6f0af6349721f3f01d3347ed97 +Subproject commit 329aee4828e4d3a7b1d99567335c54562c493942 From 4eb7154e326a45be4e5272b0bad0296fb156be29 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:45:51 +0100 Subject: [PATCH 38/68] jvk: the attachment accesses without a vector per rendering, 4 workers by default - visit_attachment_accesses() hands each access to a callable: no allocation in beginRendering() and endRendering() - CoreConfig::workers defaults to 4, 0 stays std::thread::hardware_concurrency() --- jvk/incl/jvk/base/core_config.hpp | 2 +- jvk/src/cmd/cmd_buffer.cpp | 105 ++++++++++++++---------------- 2 files changed, 49 insertions(+), 58 deletions(-) diff --git a/jvk/incl/jvk/base/core_config.hpp b/jvk/incl/jvk/base/core_config.hpp index d1f3aa0a..a103d102 100644 --- a/jvk/incl/jvk/base/core_config.hpp +++ b/jvk/incl/jvk/base/core_config.hpp @@ -63,7 +63,7 @@ struct CoreConfig { * @details `std::thread::hardware_concurrency()` is `0` -> one thread * @details `driverThreads` `0` -> the workers call the driver too */ - size_t workers = 0; + size_t workers = 4; /** * threads for the vulkan driver calls, `0` -> the workers diff --git a/jvk/src/cmd/cmd_buffer.cpp b/jvk/src/cmd/cmd_buffer.cpp index 0dea0c86..95c48470 100644 --- a/jvk/src/cmd/cmd_buffer.cpp +++ b/jvk/src/cmd/cmd_buffer.cpp @@ -12,7 +12,6 @@ #include #include #include -#include namespace jvk::dev { @@ -100,37 +99,28 @@ namespace { } + // a callable, no vector: no allocation per rendering /** - * access of an attachment to the mip level of its image + * hands the access of each attachment to the mip level of its image to the callable + * @details the order: color, depth and stencil, resolve + * @param visit called with the image and the access */ - struct AttachmentAccess { - cth::ref_wrapper image; - ImageAccess access; - }; - - /** - * @return the accesses of the attachments: color, depth and stencil, resolve - */ - [[nodiscard]] std::vector - attachment_accesses(cvk::RenderingInfo const& info) { - std::vector accesses{}; - + template + void visit_attachment_accesses(cvk::RenderingInfo const& info, Visit visit) { for(auto const& attachment : info.colorAttachments) { auto const access = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT | (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ? VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT : VK_ACCESS_2_NONE); - accesses.push_back( - { - attachment.view->image(), - view_access( - attachment.view, - attachment.layout, - VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, - access, - discards(attachment.loadOp) - ), - } + visit( + attachment.view->image(), + view_access( + attachment.view, + attachment.layout, + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, + access, + discards(attachment.loadOp) + ) ); } @@ -152,21 +142,17 @@ namespace { !stencil_read_only(stencil->layout) ).access; access.discard = discards(depth->loadOp) && discards(stencil->loadOp); - accesses.push_back({depth->view->image(), access}); + visit(depth->view->image(), access); } else { if(depth.has_value()) - accesses.push_back( - { - depth->view->image(), - depth_stencil_access(*depth, !depth_read_only(depth->layout)), - } + visit( + depth->view->image(), + depth_stencil_access(*depth, !depth_read_only(depth->layout)) ); if(stencil.has_value()) - accesses.push_back( - { - stencil->view->image(), - depth_stencil_access(*stencil, !stencil_read_only(stencil->layout)), - } + visit( + stencil->view->image(), + depth_stencil_access(*stencil, !stencil_read_only(stencil->layout)) ); } @@ -174,17 +160,15 @@ namespace { if(attachment.resolveViewPtr == nullptr) return; cvk::ImageView const& resolveView = *attachment.resolveViewPtr; - accesses.push_back( - { - resolveView.image(), - view_access( - resolveView, - attachment.resolveLayout, - VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT, - false - ), - } + visit( + resolveView.image(), + view_access( + resolveView, + attachment.resolveLayout, + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT, + false + ) ); }; for(auto const& attachment : info.colorAttachments) @@ -194,7 +178,6 @@ namespace { if(stencil.has_value() && !(shared && stencil->resolveViewPtr == depth->resolveViewPtr)) resolve(*stencil); - return accesses; } } @@ -318,8 +301,12 @@ scoped_rendering> BasicCmdBuffer::beginRendering( cvk::RenderingInfo const& info ) { cvk::Barrier barrier{}; - for(auto const& [image, access] : attachment_accesses(info)) - _states.access(*image, access, barrier); + visit_attachment_accesses( + info, + [&](cvk::Image const& image, ImageAccess const& access) { + _states.access(image, access, barrier); + } + ); record(barrier); _cmdBuffer.beginRendering(info); @@ -330,13 +317,17 @@ template void BasicCmdBuffer::endRendering() { CTH_CRITICAL(rendering() == nullptr, "command buffer must be inside its own rendering") {} - for(auto const& [image, access] : attachment_accesses(*rendering())) - _states.extend( - *image, - cvk::BarrierScope{.stages = access.stages, .access = access.access}, - access.firstMipLevel, - access.mipLevels - ); + visit_attachment_accesses( + *rendering(), + [this](cvk::Image const& image, ImageAccess const& access) { + _states.extend( + image, + cvk::BarrierScope{.stages = access.stages, .access = access.access}, + access.firstMipLevel, + access.mipLevels + ); + } + ); _cmdBuffer.endRendering(); } From f6f9ec252dc83a5197ed7f6811cddfa2835d23b7 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:05:01 +0100 Subject: [PATCH 39/68] jvk, cvk: Queue::transfer() for both halves of a family transfer, one present for several swapchains - Queue::transfer() replaces Queue::release(): release or acquire halves with the queue's own command buffers and counter, an optional wait and binary signals - Queue::present() takes a span of PresentImage: one vkQueuePresentKHR for all, a result per image, plus a present-only variant without a submit - cvk: Swapchain::preparePresent() waits for and resets the present fence of the image, used by present() too --- cvk/incl/cvk/surface/swapchain.hpp | 24 ++- cvk/src/surface/swapchain.cpp | 47 ++--- jvk/incl/jvk/base/core.hpp | 2 +- jvk/incl/jvk/base/queue.hpp | 141 ++++++++++----- jvk/incl/jvk/graph/presenter.hpp | 2 +- jvk/incl/jvk/graph/stage_graph.hpp | 5 +- jvk/src/base/queue.cpp | 112 +++++++++--- jvk/src/graph/presenter.cpp | 9 +- jvk/src/graph/stage_graph.cpp | 2 +- jvk/tests/src/base/queue_test.cpp | 213 ++++++++++++++++++++++- jvk/tests/src/graph/presenter_test.cpp | 2 +- jvk/tests/src/graph/stage_graph_test.cpp | 4 +- 12 files changed, 452 insertions(+), 111 deletions(-) diff --git a/cvk/incl/cvk/surface/swapchain.hpp b/cvk/incl/cvk/surface/swapchain.hpp index 960de5b1..6c84088e 100644 --- a/cvk/incl/cvk/surface/swapchain.hpp +++ b/cvk/incl/cvk/surface/swapchain.hpp @@ -56,6 +56,16 @@ class Swapchain { std::optional imageIndex; }; + /** + * handles of one image in a `vkQueuePresentKHR()`, see `preparePresent()` + */ + struct PresentHandles { + VkSwapchainKHR vkSwapchain; + uint32_t imageIndex; + VkSemaphore vkWaitSemaphore; ///< `presentSemaphore()` of the image + VkFence vkFence; ///< `presentFence()` of the image, reset + }; + /** * base constructor */ @@ -165,6 +175,18 @@ class Swapchain { */ [[nodiscard]] VkResult present(uint32_t imageIndex); + /** + * prepares the present of the image in a `vkQueuePresentKHR()` of the caller + * @details waits for the present fence of the last present of the image first, then resets it + * @details the image counts as presented: the caller presents it through the present queue at + * once + * @return the handles for the present info, the fence for `VkSwapchainPresentFenceInfoKHR` + * @pre the image is acquired + * @pre a submit signals `presentSemaphore()` of the image + * @see `present()` + */ + [[nodiscard]] PresentHandles preparePresent(uint32_t imageIndex); + /** * gives acquired images back without a present * @pre the images are acquired and all uses of them completed @@ -198,7 +220,7 @@ class Swapchain { [[nodiscard]] bool presented() const; /** - * @return an image is acquired, without its `present()` or `unacquire()` + * @return an image is acquired, without its `present()`, `preparePresent()` or `unacquire()` */ [[nodiscard]] constexpr bool acquired() const { return std::ranges::contains(_acquired, true); } diff --git a/cvk/src/surface/swapchain.cpp b/cvk/src/surface/swapchain.cpp index 322ac3da..a99daecd 100644 --- a/cvk/src/surface/swapchain.cpp +++ b/cvk/src/surface/swapchain.cpp @@ -176,41 +176,48 @@ Swapchain::Acquired Swapchain::acquire(Semaphore const& signal, uint64_t timeout } VkResult Swapchain::present(uint32_t imageIndex) { - debug_check(*this); - CTH_CRITICAL( - imageIndex >= imageCount() || !acquired(imageIndex), - "image {} must be acquired", - imageIndex - ) {} + auto const handles = preparePresent(imageIndex); - // signaled by the last present of the image or created signaled - auto const& fence = presentFence(imageIndex); - fence.waitReset(); - - VkFence const vkFence = fence.get(); VkSwapchainPresentFenceInfoKHR const fenceInfo{ .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_KHR, .pNext = nullptr, .swapchainCount = 1, - .pFences = &vkFence, + .pFences = &handles.vkFence, }; - - VkSemaphore const vkSemaphore = presentSemaphore(imageIndex).get(); - VkSwapchainKHR const vkSwapchain = get(); VkPresentInfoKHR const info{ .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .pNext = &fenceInfo, .waitSemaphoreCount = 1, - .pWaitSemaphores = &vkSemaphore, + .pWaitSemaphores = &handles.vkWaitSemaphore, .swapchainCount = 1, - .pSwapchains = &vkSwapchain, - .pImageIndices = &imageIndex, + .pSwapchains = &handles.vkSwapchain, + .pImageIndices = &handles.imageIndex, .pResults = nullptr, }; - auto const result = _presentQueue.rawPresent(info); + return _presentQueue.rawPresent(info); +} + +auto Swapchain::preparePresent(uint32_t imageIndex) -> PresentHandles { + debug_check(*this); + CTH_CRITICAL( + imageIndex >= imageCount() || !acquired(imageIndex), + "image {} must be acquired", + imageIndex + ) {} + + // signaled by the last present of the image or created signaled + auto const& fence = presentFence(imageIndex); + fence.waitReset(); + + // before the present: also a failed present ends the acquire of the image _acquired[imageIndex] = false; - return result; + return PresentHandles{ + .vkSwapchain = get(), + .imageIndex = imageIndex, + .vkWaitSemaphore = presentSemaphore(imageIndex).get(), + .vkFence = fence.get(), + }; } void Swapchain::unacquire(span imageIndices) { diff --git a/jvk/incl/jvk/base/core.hpp b/jvk/incl/jvk/base/core.hpp index 3b00c6c2..75e314c7 100644 --- a/jvk/incl/jvk/base/core.hpp +++ b/jvk/incl/jvk/base/core.hpp @@ -170,7 +170,7 @@ class Core { /** * constructs the driver threads and one queue per vulkan queue * @pre the cvk core and the reactor are created - * @throws cvk::vk_result_exception result of `vkCreateSemaphore()` for the release counters + * @throws cvk::vk_result_exception result of `vkCreateSemaphore()` for the transfer counters */ void createQueues(); diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index a34a7d3a..bcc0c6ee 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -16,6 +16,7 @@ #include #include +#include #include @@ -62,20 +63,28 @@ struct SubmitInfo { } }; +/** + * acquired image of a swapchain for `Queue::present()` + */ +struct PresentImage { + cth::ref_wrapper swapchain; + uint32_t imageIdx; ///< index of the acquired image in the swapchain +}; + /** * serialized vulkan queue * @details * - refers to the queue of the cvk core * - runs its work in one strand * - submits and presents, marks the jvk signals of its submits - * - releases the queue family ownership of resources - * @see `submit()`, `present()`, `release()` + * - transfers the queue family ownership of resources + * @see `submit()`, `present()`, `transfer()` */ class Queue { public: /** - * constructs the strand on the scheduler, creates the release counter - * @details the release command buffers and the release counter come from the core + * constructs the strand on the scheduler, creates the transfer counter + * @details the transfer command buffers and the transfer counter come from the core * @pre the cvk core and the reactor of the core are created * @throws cvk::vk_result_exception result of `vkCreateSemaphore()` */ @@ -100,48 +109,78 @@ class Queue { [[nodiscard]] cth::co::executor_task submit(SubmitInfo const&) const; /** - * submits the batch and presents the image in one job of the strand, then marks the jvk signals + * submits the batch and presents the images in one strand job, then marks the jvk signals * @details - * - the submit signals `cvk::Swapchain::presentSemaphore()` of the image too + * - the submit signals `cvk::Swapchain::presentSemaphore()` of every image too + * - one `vkQueuePresentKHR()` for all images * - no other job of the strand runs between the submit and the present * - a failed submit marks nothing and presents nothing * - a failed present marks the signals before it throws: the submit reached the queue - * @param swapchain of the image - * @param imageIdx of the acquired image - * @return `VK_SUCCESS`, `VK_SUBOPTIMAL_KHR` or `VK_ERROR_OUT_OF_DATE_KHR` + * @param images one per swapchain + * @param[out] results one per image: `VK_SUCCESS`, `VK_SUBOPTIMAL_KHR`, + * `VK_ERROR_OUT_OF_DATE_KHR` or the error of its swapchain, also after a failed present * @pre `cvk::Queue::canPresent()` - * @pre the info lives until the end of the task, nothing changes it - * @pre the preconditions of `cvk::Queue::submit()` and of `cvk::Swapchain::present()` + * @pre `results.size() == images.size()` + * @pre the info, the images and the results live until the end of the task, unchanged + * @pre the preconditions of `cvk::Queue::submit()` and of `cvk::Swapchain::preparePresent()` + * @pre the swapchains present through this queue * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` * @throws cvk::vk_result_exception other result of `vkQueuePresentKHR()` */ - [[nodiscard]] cth::co::executor_task present( + [[nodiscard]] cth::co::executor_task present( SubmitInfo const&, - cvk::Swapchain& swapchain, - uint32_t imageIdx + std::span images, + std::span results + ) const; + + /** + * presents the images in one job of the strand, without a submit + * @details one `vkQueuePresentKHR()` for all images + * @param images one per swapchain, a submit before signals their present semaphores + * @param[out] results one per image, see the submit overload + * @pre `cvk::Queue::canPresent()` + * @pre `results.size() == images.size()` + * @pre the images and the results live until the end of the task, nothing changes them + * @pre the preconditions of `cvk::Swapchain::preparePresent()` + * @pre the swapchains present through this queue + * @throws cvk::vk_result_exception other result of `vkQueuePresentKHR()` + */ + [[nodiscard]] cth::co::executor_task present( + std::span images, + std::span results ) const; - // an executor_task: the receiving submit job awaits it before its own submit, so the release is - // submitted first and the counter only changes in the strand (returning at once needs a lock around the value - // and the post) - // const like executor(): the core hands out Queue const&, the release members are mutable + // an executor_task: the receiving submit job awaits it before its own submit, so the transfer + // is submitted first and the counter only changes in the strand (returning at once needs a lock + // around the value and the post) + // const like executor(): the core hands out Queue const&, the transfer members are mutable // returns the jvk SemaphoreSubmitInfo: it keeps the counter for Semaphore::submitted(), it // converts to the cvk one /** - * releases the queue family ownership of the resources in the strand + * transfers the queue family ownership of resources in the strand: release or acquire halves * @details - * - records the barriers into a release command buffer of the queue family of the queue, submits it - * - the submit signals the next value of the release counter, `Semaphore::markSubmitted()` marks it + * - records the barriers into a transfer command buffer of the family of the queue, submits it + * - the submit waits for the waits, signals the next value of the transfer counter and the + * binary signals, `Semaphore::markSubmitted()` marks the counter * - reuses the command buffers whose value the counter reached - * @param barriers the release halves of the queue family ownership transfers - * @return wait for the release counter, stages `VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT`, the receiver can narrow them - * @pre the barriers hold only queue family releases from the queue family of the queue - * @pre the barriers come after the last use of the resources on this queue - * @pre the receiver records the acquire halves and waits for the returned value + * @param barriers the release or the acquire halves of the ownership transfers, for the family + * of the queue + * @param waits of the submit, e.g. the submit of the release halves before acquire halves + * @param binarySignals of the submit, e.g. the present semaphores of the transferred images + * @return wait for the transfer counter, stages `VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT`, the + * receiver can narrow them + * @pre release halves: after the last use of the resources on this queue, the receiver records + * the acquire halves and waits for the returned value + * @pre acquire halves: the waits cover the submit of their release halves + * @pre the waits and the binary signals live until the end of the task, unchanged * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` * @throws cvk::vk_result_exception result of `vkCreateCommandPool()` or `vkAllocateCommandBuffers()` */ - [[nodiscard]] cth::co::executor_task release(cvk::Barrier barriers) const; + [[nodiscard]] cth::co::executor_task transfer( + cvk::Barrier barriers, + std::span waits = {}, + std::span binarySignals = {} + ) const; /** * @return executor of the strand @@ -169,43 +208,48 @@ class Queue { /** * submits the batch through `cvk::Queue::rawSubmit()` * @details resolves the `std::nullopt` timeline values in order: the waits, then the signals - * @param presentSemaphorePtr `nullptr` -> no present semaphore, else signaled after the signals - * of the info + * @param presents their present semaphores are signaled after the signals of the info * @pre runs in the strand * @pre the preconditions of `cvk::Queue::submit()` * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` */ - void submitInStrand( - SubmitInfo const&, - cvk::Semaphore const* presentSemaphorePtr = nullptr - ) const; + void submitInStrand(SubmitInfo const&, std::span presents = {}) const; + + /** + * presents the images in one `cvk::Queue::rawPresent()` + * @param[out] results one per image, also written by a failed present + * @pre runs in the strand + * @pre the preconditions of `present()` + * @throws cvk::vk_result_exception other result of `vkQueuePresentKHR()` + */ + void presentInStrand(std::span images, std::span results) const; /** - * command buffer of one release + * command buffer of one transfer * @details owns its command pool, see `PrimaryCmdBuffer` */ - struct ReleaseCmd { + struct TransferCmd { PrimaryCmdBuffer cmd; - /** - * value of the release counter for the last submit of `ReleaseCmd::cmd`, free once reached - */ + /** value of the transfer counter for the last submit of `cmd`, free once reached */ uint64_t value = 0; }; /** - * a command buffer whose last release the gpu finished, or a new one + * a command buffer whose last transfer the gpu finished, or a new one * @details reads the counter, no wait * @pre runs in the strand */ - [[nodiscard]] ReleaseCmd& freeReleaseCmd() const; + [[nodiscard]] TransferCmd& freeTransferCmd() const; cth::ref_wrapper _core; cth::ref_wrapper _queue; cth::ref_wrapper _scheduler; cth::co::strand _strand; - mutable std::deque _releaseCmds{}; ///< used in the strand only + mutable std::deque _transferCmds{}; ///< used in the strand only + /** the submit of `transfer()`, used in the strand only: it keeps its capacity */ + mutable SubmitInfo _transferInfo{}; // members, no locals: submitInStrand() refills them, they keep their capacity /** the command buffers of the submit in `submitInStrand()`, used in the strand only */ @@ -215,8 +259,19 @@ class Queue { /** the signals of the submit in `submitInStrand()`, used in the strand only */ mutable std::vector _signalInfos{}; - //TODO review the counter decides the reuse of the release command buffers, no reactor wait: a release reads it - mutable Semaphore _released; ///< the release counter, raised by each release submit + // members, no locals: presentInStrand() refills them, they keep their capacity + /** the swapchains of the present in `presentInStrand()`, used in the strand only */ + mutable std::vector _presentSwapchains{}; + /** the image indices of the present in `presentInStrand()`, used in the strand only */ + mutable std::vector _presentImageIndices{}; + /** the present semaphores of the present in `presentInStrand()`, used in the strand only */ + mutable std::vector _presentWaits{}; + /** the present fences of the present in `presentInStrand()`, used in the strand only */ + mutable std::vector _presentFences{}; + + //TODO review the counter decides the reuse of the transfer command buffers, no reactor wait: a + // transfer reads it + mutable Semaphore _transferred; ///< the transfer counter, raised by each transfer submit public: Queue(Queue const& other) = delete; diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/presenter.hpp index f58803b7..53970a06 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -250,7 +250,7 @@ class Presenter { * - off the strand: awaits `Presenter::_presented` of the job before: the present jobs run one * at a time, in the order of `present()` * - fills `Presenter::_submitInfo`: the job before ended its use - * - stage of another family -> `Queue::release()` of the image on the stage queue + * - stage of another family -> `Queue::transfer()` of the release half on the stage queue * - off the strand: records the command buffer, the present jobs run one at a time * - `Queue::present()` with the current swapchain: a recreation only happens in `acquire()`, * after the last present diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index 8db38594..e300f4b9 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -99,7 +99,8 @@ class StageGraph { * - returns at once, the strand of the queue submits after the waited stages submitted * - resolves the first uses of the primary against the resource states after all submits * - an unknown image: the prologue transitions it from `VK_IMAGE_LAYOUT_UNDEFINED` - * - an `EXCLUSIVE` resource of another queue family: `Queue::release()` on its last queue, the prologue acquires it + * - an `EXCLUSIVE` resource of another queue family: `Queue::transfer()` of the release half on + * its last queue, the prologue acquires it * - waits for the stage waits of the config and the waits of `Stage::await()` * - signals `Stage::semaphore()` with `Stage::frameNumber()` * - an error: skips, `nextFrame()` rethrows the error @@ -254,7 +255,7 @@ class StageGraph { * releases the resources on their last queues * @param releases the release halves per last queue, from `append()` * @return the waits for the releases - * @see `Queue::release()` + * @see `Queue::transfer()` */ [[nodiscard]] cth::co::executor_task> release( release_map_t releases diff --git a/jvk/src/base/queue.cpp b/jvk/src/base/queue.cpp index 0b2121f0..ddc26259 100644 --- a/jvk/src/base/queue.cpp +++ b/jvk/src/base/queue.cpp @@ -15,6 +15,8 @@ namespace jvk { +using std::span; + namespace { /** * marks the jvk signals, see `Semaphore::markSubmitted()` @@ -30,7 +32,7 @@ Queue::Queue(Core const& core, cvk::Queue const& queue, cth::co::scheduler const _queue{queue}, _scheduler{queueScheduler}, _strand{queueScheduler}, - _released{core, cvk::create} { cvk::Queue::debug_check(queue); } + _transferred{core, cvk::create} { cvk::Queue::debug_check(queue); } void Queue::waitIdle() const { executor().sync_wait( @@ -48,55 +50,67 @@ cth::co::executor_task Queue::submit(SubmitInfo const& info) const { mark(info.signals); } -cth::co::executor_task Queue::present( +cth::co::executor_task Queue::present( SubmitInfo const& info, - cvk::Swapchain& swapchain, - uint32_t imageIdx + span images, + span results ) const { // no suspension between the submit and the present: the presents follow the order of the // submits co_await executor().schedule(); - submitInStrand(info, &swapchain.presentSemaphore(imageIdx)); + submitInStrand(info, images); - // the marks after the present: a waiter for them uses the swapchain after vkQueuePresentKHR() - VkResult result{}; - try { result = swapchain.present(imageIdx); } + // the marks after the present: a waiter for them uses the swapchains after vkQueuePresentKHR() + try { presentInStrand(images, results); } catch(cvk::vk_result_exception const&) { // the submit reached the queue: the gpu signals the values mark(info.signals); throw; } mark(info.signals); +} - co_return result; +cth::co::executor_task Queue::present( + span images, + span results +) const { + co_await executor().schedule(); + presentInStrand(images, results); } -cth::co::executor_task Queue::release(cvk::Barrier barriers) const { - // all in the strand: it serializes the release command buffers, the counter values follow the submit order +cth::co::executor_task Queue::transfer( + cvk::Barrier barriers, + span waits, + span binarySignals +) const { + // all in the strand: it serializes the transfer command buffers, the counter values follow the + // submit order co_await executor().schedule(); - auto& releaseCmd = freeReleaseCmd(); - auto& cmd = releaseCmd.cmd; + auto& transferCmd = freeTransferCmd(); + auto& cmd = transferCmd.cmd; cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); barriers.execute(cmd); cmd.end(); - SemaphoreSubmitInfo const signal{.semaphore = _released, .value = _released.next()}; - SubmitInfo const info{.cmdBuffers = {cmd}, .signals = {signal}}; + SemaphoreSubmitInfo const signal{.semaphore = _transferred, .value = _transferred.next()}; + auto& info = _transferInfo; + info.clear(); + info.cmdBuffers.push_back(cmd); + info.waits.append_range(waits); + info.signals.push_back(signal); + info.binarySignals.append_range(binarySignals); submitInStrand(info); // after the submit: a failed submit leaves the command buffer free - releaseCmd.value = signal.value; + transferCmd.value = signal.value; mark(info.signals); co_return signal; } -void Queue::submitInStrand( - SubmitInfo const& info, - cvk::Semaphore const* presentSemaphorePtr -) const { +void Queue::submitInStrand(SubmitInfo const& info, span presents) const { _cmdBufferInfos.clear(); for(PrimaryCmdBuffer const& cmdBuffer : info.cmdBuffers) _cmdBufferInfos.push_back(cvk::cmd_buffer_submit_info(cmdBuffer)); @@ -113,8 +127,8 @@ void Queue::submitInStrand( _signalInfos.push_back(cvk::signal_submit_info(signal)); for(auto const& signal : info.binarySignals) _signalInfos.push_back(cvk::signal_submit_info(signal)); - if(presentSemaphorePtr != nullptr) - _signalInfos.push_back(cvk::signal_submit_info({*presentSemaphorePtr})); + for(auto const& [swapchain, imageIdx] : presents) + _signalInfos.push_back(cvk::signal_submit_info({swapchain->presentSemaphore(imageIdx)})); _queue->rawSubmit( VkSubmitInfo2{ @@ -131,18 +145,58 @@ void Queue::submitInStrand( ); } -auto Queue::freeReleaseCmd() const -> ReleaseCmd& { - auto const reached = _released.gpuValue(); +void Queue::presentInStrand(span images, span results) const { + CTH_CRITICAL( + results.size() != images.size(), + "one result per image, got {} results for {} images", + results.size(), + images.size() + ) {} + + _presentSwapchains.clear(); + _presentImageIndices.clear(); + _presentWaits.clear(); + _presentFences.clear(); + for(auto const& [swapchain, imageIdx] : images) { + auto const handles = swapchain->preparePresent(imageIdx); + _presentSwapchains.push_back(handles.vkSwapchain); + _presentImageIndices.push_back(handles.imageIndex); + _presentWaits.push_back(handles.vkWaitSemaphore); + _presentFences.push_back(handles.vkFence); + } + + VkSwapchainPresentFenceInfoKHR const fenceInfo{ + .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_KHR, + .pNext = nullptr, + .swapchainCount = static_cast(_presentFences.size()), + .pFences = _presentFences.data(), + }; + static_cast(_queue->rawPresent( + VkPresentInfoKHR{ + .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, + .pNext = &fenceInfo, + .waitSemaphoreCount = static_cast(_presentWaits.size()), + .pWaitSemaphores = _presentWaits.data(), + .swapchainCount = static_cast(_presentSwapchains.size()), + .pSwapchains = _presentSwapchains.data(), + .pImageIndices = _presentImageIndices.data(), + .pResults = results.data(), + } + )); +} + +auto Queue::freeTransferCmd() const -> TransferCmd& { + auto const reached = _transferred.gpuValue(); auto const it = std::ranges::find_if( - _releaseCmds, - [reached](ReleaseCmd const& releaseCmd) { return releaseCmd.value <= reached; } + _transferCmds, + [reached](TransferCmd const& transferCmd) { return transferCmd.value <= reached; } ); - if(it != _releaseCmds.end()) + if(it != _transferCmds.end()) return *it; - return _releaseCmds.emplace_back( - ReleaseCmd{PrimaryCmdBuffer{*_core, _queue->familyIndex(), cvk::create}} + return _transferCmds.emplace_back( + TransferCmd{PrimaryCmdBuffer{*_core, _queue->familyIndex(), cvk::create}} ); } diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index d9796fb4..c35298d8 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -249,7 +249,7 @@ cth::co::executor_task Presenter::presentJob( aspectMask, dev::release_half(lastState, presentState, stageFamily, family, 0) ); - info.waits.push_back(co_await stageQueue.release(std::move(release))); + info.waits.push_back(co_await stageQueue.transfer(std::move(release))); barrier.add( vkImage, @@ -282,7 +282,12 @@ cth::co::executor_task Presenter::presentJob( // the swapchain of the image is the current one: a recreation only happens in acquire(), // after the end of the last present job - auto const result = co_await queue.present(info, _swapchain.current(), image.imageIdx); + std::array const images{ + PresentImage{.swapchain = _swapchain.current(), .imageIdx = image.imageIdx} + }; + std::array results{}; + co_await queue.present(info, images, results); + auto const result = results[0]; // before _presented.set(): the next acquire() reads it if(result == VK_ERROR_OUT_OF_DATE_KHR) _outOfDate = true; diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index 985a7218..cb4611c4 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -454,7 +454,7 @@ cth::co::executor_task> StageGraph::release(release_ vector waits{}; waits.reserve(releases.size()); for(auto& [queuePtr, barrier] : releases) - waits.push_back(co_await queuePtr->release(std::move(barrier))); + waits.push_back(co_await queuePtr->transfer(std::move(barrier))); co_return waits; } diff --git a/jvk/tests/src/base/queue_test.cpp b/jvk/tests/src/base/queue_test.cpp index 307fdbda..9a665cc8 100644 --- a/jvk/tests/src/base/queue_test.cpp +++ b/jvk/tests/src/base/queue_test.cpp @@ -294,7 +294,7 @@ JVK_TEST(Queue, release_transfers_an_image_to_another_family) { .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, } ); - auto const released = core.executor().sync_wait(owner.release(release)); + auto const released = core.executor().sync_wait(owner.transfer(release)); EXPECT_EQ(released.semaphore->submittedValue(), released.value); // the acquire half on the family of the receiver, then the read @@ -333,6 +333,80 @@ JVK_TEST(Queue, release_transfers_an_image_to_another_family) { EXPECT_TRUE(counts(readback)); } +JVK_TEST(Queue, transfer_of_the_acquire_half_waits_and_signals) { + test::Context const context{}; + Core const core{context.instance, two_families(), {}}; + auto const& owner = core.queue(0); + auto const& receiver = core.queue(1); + auto const ownerFamily = owner.vk().familyIndex(); + auto const receiverFamily = receiver.vk().familyIndex(); + if(ownerFamily == receiverFamily) + GTEST_SKIP() << "needs two queue families, e.g. ANV_QUEUE_OVERRIDE=gc=2,c=1"; + + Image const image{core, IMAGE_CONFIG, EXTENT}; + auto const staging = counting_staging(core); + Buffer const readback{core, test::READBACK_CONFIG, PIXELS}; + + PrimaryCmdBuffer write{core, ownerFamily, cvk::create}; + write.begin(); + write.assume(image, UNDEFINED); + image.copy(write, staging); + write.end(); + auto const& executor = core.executor(); + executor.sync_wait(submit(owner, {.cmdBuffers = {write}}, nullptr)); + + cvk::Barrier release{}; + release.add( + image, + cvk::ImageBarrierInfo{ + .src = TRANSFER_WRITE, + .srcQueueFamilyIndex = ownerFamily, + .dstQueueFamilyIndex = receiverFamily, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + } + ); + auto const released = executor.sync_wait(owner.transfer(release)); + + // the acquire half on the receiver: waits for the release, signals the binary semaphore + cvk::Barrier acquire{}; + acquire.add( + image, + cvk::ImageBarrierInfo{ + .src = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, + .dst = TRANSFER_READ, + .srcQueueFamilyIndex = ownerFamily, + .dstQueueFamilyIndex = receiverFamily, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + } + ); + cvk::Semaphore const acquired{core, cvk::create}; + std::array const waits{released}; + std::array const binarySignals{cvk::SemaphoreSubmitInfo{acquired}}; + auto const transferred = executor.sync_wait(receiver.transfer(acquire, waits, binarySignals)); + EXPECT_EQ(transferred.semaphore->submittedValue(), transferred.value); + + PrimaryCmdBuffer read{core, receiverFamily, cvk::create}; + read.begin(); + read.assume( + image, + { + .layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .scope = {TRANSFER_READ.stages, TRANSFER_READ.access} + } + ); + image.copyTo(read, readback); + read.use(readback, HOST_READ); + read.end(); + + cvk::Fence const fence{core, cvk::create}; + executor.sync_wait(submit(receiver, {.cmdBuffers = {read}, .waits = {acquired}}, &fence)); + fence.wait(); + + EXPECT_TRUE(counts(readback)); +} + JVK_TEST(Queue, several_releases_in_a_row) { constexpr size_t RELEASES = 4; test::Context const context{}; @@ -371,7 +445,7 @@ JVK_TEST(Queue, several_releases_in_a_row) { .dstQueueFamilyIndex = receiverFamily, } ); - released.push_back(core.executor().sync_wait(owner.release(release))); + released.push_back(core.executor().sync_wait(owner.transfer(release))); } for(size_t i = 1; i < RELEASES; ++i) { EXPECT_EQ(&released[i].semaphore.get(), &released[0].semaphore.get()); @@ -412,7 +486,7 @@ JVK_TEST(Queue, several_releases_in_a_row) { // the gpu finished the releases: the next release reuses a command buffer receiver.waitIdle(); owner.waitIdle(); - auto const next = core.executor().sync_wait(owner.release(cvk::Barrier{})); + auto const next = core.executor().sync_wait(owner.transfer(cvk::Barrier{})); EXPECT_EQ(next.value, released.back().value + 1); owner.waitIdle(); } @@ -512,23 +586,146 @@ JVK_TEST(Queue, present_submits_presents_and_marks) { barrier.execute(cmd); cmd.end(); - auto const result = core.executor().sync_wait( + std::array const images{PresentImage{.swapchain = current, .imageIdx = *imageIdxOpt}}; + std::array results{VK_ERROR_UNKNOWN}; + core.executor().sync_wait( queue.present( { .cmdBuffers = {cmd}, .binaryWaits = {acquired}, .signals = {{.semaphore = presented, .value = value}}, }, - current, - *imageIdxOpt + images, + results ) ); - EXPECT_TRUE(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) - << "present result: " << result; + EXPECT_TRUE(results[0] == VK_SUCCESS || results[0] == VK_SUBOPTIMAL_KHR) + << "present result: " << results[0]; EXPECT_EQ(presented.submittedValue(), value); // the acquire semaphore goes after the gpu waited for it static_cast(presented).wait(value); } } + +JVK_TEST(Queue, present_of_two_swapchains_in_one_call) { + test::Context const context{}; + auto const firstSurface = test::headless_surface(context.instance); + auto const secondSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, firstSurface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto const& core = *coreOpt; + auto const& queue = core.queue(0); + + Swapchain first{core, queue.vk(), firstSurface}; + first.create({}, EXTENT); + Swapchain second{core, queue.vk(), secondSurface}; + second.create({}, EXTENT); + Semaphore const presented{core, cvk::create}; + + // one submit transitions both images, one vkQueuePresentKHR() presents both + cvk::Semaphore const firstAcquired{core, cvk::create}; + cvk::Semaphore const secondAcquired{core, cvk::create}; + auto const firstIdxOpt = first.acquire(firstAcquired).imageIndex; + auto const secondIdxOpt = second.acquire(secondAcquired).imageIndex; + ASSERT_TRUE(firstIdxOpt.has_value()); + ASSERT_TRUE(secondIdxOpt.has_value()); + + PrimaryCmdBuffer cmd{core, queue.vk().familyIndex(), cvk::create}; + cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); + cvk::Barrier barrier{}; + for(auto const& [swapchainPtr, imageIdx] : + std::array{std::pair{&first, *firstIdxOpt}, std::pair{&second, *secondIdxOpt}}) + barrier.add( + swapchainPtr->current().image(imageIdx), + cvk::ImageBarrierInfo{ + .src = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, + .dst = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, + .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + } + ); + barrier.execute(cmd); + cmd.end(); + + std::array const images{ + PresentImage{.swapchain = first.current(), .imageIdx = *firstIdxOpt}, + PresentImage{.swapchain = second.current(), .imageIdx = *secondIdxOpt}, + }; + std::array results{VK_ERROR_UNKNOWN, VK_ERROR_UNKNOWN}; + core.executor().sync_wait( + queue.present( + { + .cmdBuffers = {cmd}, + .binaryWaits = {firstAcquired, secondAcquired}, + .signals = {{.semaphore = presented, .value = 1}}, + }, + images, + results + ) + ); + + for(auto const result : results) + EXPECT_TRUE(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) + << "present result: " << result; + EXPECT_FALSE(first.current().acquired()); + EXPECT_FALSE(second.current().acquired()); + static_cast(presented).wait(1); +} + +JVK_TEST(Queue, present_without_a_submit_after_the_submit_of_the_present_semaphore) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto const& core = *coreOpt; + auto const& queue = core.queue(0); + + Swapchain swapchain{core, queue.vk(), surface}; + swapchain.create({}, EXTENT); + auto& current = swapchain.current(); + Semaphore const presented{core, cvk::create}; + + cvk::Semaphore const acquired{core, cvk::create}; + auto const imageIdxOpt = swapchain.acquire(acquired).imageIndex; + ASSERT_TRUE(imageIdxOpt.has_value()); + + PrimaryCmdBuffer cmd{core, queue.vk().familyIndex(), cvk::create}; + cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); + cvk::Barrier barrier{}; + barrier.add( + current.image(*imageIdxOpt), + cvk::ImageBarrierInfo{ + .src = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, + .dst = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, + .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + } + ); + barrier.execute(cmd); + cmd.end(); + + // the submit signals the present semaphore, the present follows without a submit + auto const& executor = core.executor(); + executor.sync_wait( + queue.submit( + { + .cmdBuffers = {cmd}, + .binaryWaits = {acquired}, + .signals = {{.semaphore = presented, .value = 1}}, + .binarySignals = {current.presentSemaphore(*imageIdxOpt)}, + } + ) + ); + std::array const images{PresentImage{.swapchain = current, .imageIdx = *imageIdxOpt}}; + std::array results{VK_ERROR_UNKNOWN}; + executor.sync_wait(queue.present(images, results)); + + EXPECT_TRUE(results[0] == VK_SUCCESS || results[0] == VK_SUBOPTIMAL_KHR) + << "present result: " << results[0]; + EXPECT_FALSE(current.acquired()); + static_cast(presented).wait(1); +} } diff --git a/jvk/tests/src/graph/presenter_test.cpp b/jvk/tests/src/graph/presenter_test.cpp index 4bcd0b3d..7fd3f1ab 100644 --- a/jvk/tests/src/graph/presenter_test.cpp +++ b/jvk/tests/src/graph/presenter_test.cpp @@ -796,7 +796,7 @@ JVK_TEST(Presenter, present_queue_of_another_family) { presenter.destroy(); // one release on the stage queue per frame: the next release gets the next value of its counter - auto const next = core.executor().sync_wait(stageQueue.release(cvk::Barrier{})); + auto const next = core.executor().sync_wait(stageQueue.transfer(cvk::Barrier{})); EXPECT_EQ(next.value, FRAMES + 1); stageQueue.waitIdle(); } diff --git a/jvk/tests/src/graph/stage_graph_test.cpp b/jvk/tests/src/graph/stage_graph_test.cpp index bf36b62d..f4a377a2 100644 --- a/jvk/tests/src/graph/stage_graph_test.cpp +++ b/jvk/tests/src/graph/stage_graph_test.cpp @@ -795,7 +795,7 @@ JVK_TEST(StageGraph, image_and_buffer_move_to_another_queue_family) { // one release on the writer queue for both: the next release gets the second value of its counter auto const& writerQueue = core.queue(0); - auto const next = core.executor().sync_wait(writerQueue.release(cvk::Barrier{})); + auto const next = core.executor().sync_wait(writerQueue.transfer(cvk::Barrier{})); EXPECT_EQ(next.value, 2); writerQueue.waitIdle(); } @@ -835,7 +835,7 @@ JVK_TEST(StageGraph, erase_removes_the_state_and_the_last_queue_of_an_image) { wait(core, second.stage(1)); EXPECT_TRUE(counts(readback)); - auto const next = core.executor().sync_wait(firstQueue.release(cvk::Barrier{})); + auto const next = core.executor().sync_wait(firstQueue.transfer(cvk::Barrier{})); EXPECT_EQ(next.value, 1); firstQueue.waitIdle(); } From c11f6a1abfbe4f9921f14a86c4c8566f3fb1fe9d Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:05:01 +0100 Subject: [PATCH 40/68] jvk: Presenter is jvk::Surface, no behavior change - Presenter and PresenterConfig are Surface and SurfaceConfig in jvk/graph/surface.hpp - the cvk surface variables of the window are windowSurface in the demos and tests --- demo/cube/src/main.cpp | 22 +- demo/triangle/src/main.cpp | 22 +- jvk/incl/jvk/graph/stage_graph.hpp | 2 +- .../jvk/graph/{presenter.hpp => surface.hpp} | 104 +++--- jvk/incl/jvk/graph/swapchain.hpp | 2 +- jvk/src/graph/stage_graph.cpp | 2 +- jvk/src/graph/{presenter.cpp => surface.cpp} | 40 +-- jvk/tests/src/base/core_test.cpp | 2 +- .../{presenter_test.cpp => surface_test.cpp} | 306 +++++++++--------- 9 files changed, 251 insertions(+), 251 deletions(-) rename jvk/incl/jvk/graph/{presenter.hpp => surface.hpp} (82%) rename jvk/src/graph/{presenter.cpp => surface.cpp} (92%) rename jvk/tests/src/graph/{presenter_test.cpp => surface_test.cpp} (68%) diff --git a/demo/cube/src/main.cpp b/demo/cube/src/main.cpp index 9fc5cf51..f90482da 100644 --- a/demo/cube/src/main.cpp +++ b/demo/cube/src/main.cpp @@ -6,7 +6,7 @@ #include "jvk/data/resource_heap.hpp" #include "jvk/data/sampler_heap.hpp" #include "jvk/graph/frame.hpp" -#include "jvk/graph/presenter.hpp" +#include "jvk/graph/surface.hpp" #include "jvk/graph/stage.hpp" #include "jvk/graph/stage_graph.hpp" @@ -64,7 +64,7 @@ using enum cvk::QueueFamilyProperties; constexpr VkExtent2D WINDOW_EXTENT{800, 600}; /** - * format of the swapchain and the pipeline, fixed: the pipeline is declared before the presenter, see `run()` + * format of the swapchain and the pipeline, fixed: the pipeline is declared before the surface, see `run()` */ constexpr VkSurfaceFormatKHR SURFACE_FORMAT{ VK_FORMAT_B8G8R8A8_SRGB, @@ -428,7 +428,7 @@ cth::co::executor_task draw_frames( cgfw::Window& window, jvk::Core const& core, jvk::StageGraph& graph, - jvk::Presenter& presenter, + jvk::Surface& surface, cvk::GraphicsPipeline const& pipeline, Cube const& cube, timgui::Imgui& imgui, @@ -455,7 +455,7 @@ cth::co::executor_task draw_frames( auto& stage = (co_await graph.nextFrame()).stage(CUBE_STAGE_ID); - auto const image = co_await presenter.acquire( + auto const image = co_await surface.acquire( stage, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT ); @@ -558,7 +558,7 @@ cth::co::executor_task draw_frames( * creates the window, the vulkan objects, the cube and the pipeline, then draws until the window closes * @details the declaration order is the destruction order backwards: * - the cube, the pipeline, the ImGui and the targets live until `~StageGraph()` waited for the gpu - * - the presenter is destroyed before the graph: its present jobs wait for the semaphores of the graph + * - the surface is destroyed before the graph: its present jobs wait for the semaphores of the graph */ void run() { cvk::Cvk const cvk{}; @@ -574,13 +574,13 @@ void run() { cvk::create }; - // the core picks a queue that presents to the surface, the presenter takes the surface + // the core picks a queue that presents to the surface, the jvk surface takes it // scalar block layout: the vertices and the push data of cube.glsl - auto surface = window.surface(instance); + auto windowSurface = window.surface(instance); jvk::Core core{ instance, {.vk = {.queueProperties = {GRAPHICS | PRESENT}, .features = {.scalarBlockLayout = true}}}, - {surface} + {windowSurface} }; cvk::Core const& vk = core; auto const& limits = vk.physicalDevice().limits(); @@ -614,15 +614,15 @@ void run() { std::optional targetsOpt{}; jvk::StageGraph graph{core, {.stages = {{.queueIdx = QUEUE_IDX}}}}; - jvk::Presenter presenter{ + jvk::Surface surface{ core, core.queue(QUEUE_IDX), {.swapchain = {.formats = {SURFACE_FORMAT}}}, - std::move(surface), + std::move(windowSurface), }; core.executor().sync_wait( - draw_frames(window, core, graph, presenter, pipeline, cube, imgui, targetsOpt) + draw_frames(window, core, graph, surface, pipeline, cube, imgui, targetsOpt) ); } } diff --git a/demo/triangle/src/main.cpp b/demo/triangle/src/main.cpp index f093e29b..3e88f644 100644 --- a/demo/triangle/src/main.cpp +++ b/demo/triangle/src/main.cpp @@ -2,7 +2,7 @@ #include "jvk/base/queue.hpp" #include "jvk/data/image.hpp" #include "jvk/graph/frame.hpp" -#include "jvk/graph/presenter.hpp" +#include "jvk/graph/surface.hpp" #include "jvk/graph/stage.hpp" #include "jvk/graph/stage_graph.hpp" @@ -42,7 +42,7 @@ using enum cvk::QueueFamilyProperties; constexpr VkExtent2D WINDOW_EXTENT{800, 600}; /** - * format of the swapchain and the pipeline, fixed: the pipeline is declared before the presenter, see `run()` + * format of the swapchain and the pipeline, fixed: the pipeline is declared before the surface, see `run()` */ constexpr VkSurfaceFormatKHR SURFACE_FORMAT{ VK_FORMAT_B8G8R8A8_SRGB, @@ -89,7 +89,7 @@ cth::co::executor_task draw_frames( cgfw::Window& window, jvk::Core const& core, jvk::StageGraph& graph, - jvk::Presenter& presenter, + jvk::Surface& surface, cvk::GraphicsPipeline const& pipeline, std::optional& msaaOpt ) { @@ -97,7 +97,7 @@ cth::co::executor_task draw_frames( window.pollEvents(); auto& stage = (co_await graph.nextFrame()).stage(TRIANGLE_STAGE_ID); - auto const image = co_await presenter.acquire( + auto const image = co_await surface.acquire( stage, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT ); @@ -141,7 +141,7 @@ cth::co::executor_task draw_frames( * creates the window, the vulkan objects and the pipeline, then draws until the window closes * @details the declaration order is the destruction order backwards: * - the pipeline and the multisampled target live until `~StageGraph()` waited for the gpu - * - the presenter is destroyed before the graph: its present jobs wait for the semaphores of the graph + * - the surface is destroyed before the graph: its present jobs wait for the semaphores of the graph */ void run() { cvk::Cvk const cvk{}; @@ -157,9 +157,9 @@ void run() { cvk::create }; - // the core picks a queue that presents to the surface, the presenter takes the surface - auto surface = window.surface(instance); - jvk::Core core{instance, {.vk = {.queueProperties = {GRAPHICS | PRESENT}}}, {surface}}; + // the core picks a queue that presents to the surface, the jvk surface takes it + auto windowSurface = window.surface(instance); + jvk::Core core{instance, {.vk = {.queueProperties = {GRAPHICS | PRESENT}}}, {windowSurface}}; cvk::Core const& vk = core; if((vk.physicalDevice().limits().framebufferColorSampleCounts & MSAA_SAMPLES) == 0) throw std::runtime_error{ @@ -179,14 +179,14 @@ void run() { std::optional msaaOpt{}; jvk::StageGraph graph{core, {.stages = {{.queueIdx = QUEUE_IDX}}}}; - jvk::Presenter presenter{ + jvk::Surface surface{ core, core.queue(QUEUE_IDX), {.swapchain = {.formats = {SURFACE_FORMAT}}}, - std::move(surface), + std::move(windowSurface), }; - core.executor().sync_wait(draw_frames(window, core, graph, presenter, pipeline, msaaOpt)); + core.executor().sync_wait(draw_frames(window, core, graph, surface, pipeline, msaaOpt)); } } diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index e300f4b9..92dba174 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -66,7 +66,7 @@ class StageGraph { * @details * - skips the unsubmitted stages first, e.g. after an exception in their recording: their waiters go on * - the skip of an unsubmitted stage drops its binary waits: their semaphores, e.g. the acquire semaphores of a - * `Presenter`, can be destroyed before the graph + * `Surface`, can be destroyed before the graph * - waits for the end of every submit job * - a failed skip or wait does not stop the destruction * @attention blocks the calling thread: a worker of the core must be free for the jobs diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/surface.hpp similarity index 82% rename from jvk/incl/jvk/graph/presenter.hpp rename to jvk/incl/jvk/graph/surface.hpp index 53970a06..67754bee 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/surface.hpp @@ -54,9 +54,9 @@ struct SwapchainImage { }; /** - * config of a `Presenter` + * config of a `Surface` */ -struct PresenterConfig { +struct SurfaceConfig { /** * @details `cvk::SwapchainConfig::minImageCount` `0` -> `minImageCount` of the surface + `framesInFlight`: an * image for each frame in flight beside the images of the presentation engine @@ -71,16 +71,16 @@ struct PresenterConfig { */ uint32_t framesInFlight = 2; - static constexpr void debug_check(PresenterConfig const&); + static constexpr void debug_check(SurfaceConfig const&); }; /** - * presents to a surface + * cvk surface with its swapchain, acquires and presents its images * @details - * - owns the surface and the swapchain + * - owns the cvk surface and the swapchain * - recreates the swapchain in `acquire()`, a retired swapchain stays until its presents ended, see `Swapchain` * - submits and presents in the strand of its queue, acquires outside the strand on `Queue::scheduler()` - * - `Presenter::_presented` orders the uses of the swapchain: a present job sets it at its end, the + * - `Surface::_presented` orders the uses of the swapchain: a present job sets it at its end, the * next `acquire()` waits for it * - one acquired image at a time, in a scope: `scoped_acquire` presents it at its end * - an image without a present: the next `acquire()` or `destroy()` unacquires it, `acquire()` after the gpu finished @@ -88,27 +88,27 @@ struct PresenterConfig { * - the present jobs run detached, `destroy()` waits for them * @attention not thread safe */ -class Presenter { +class Surface { public: - using Config = PresenterConfig; + using Config = SurfaceConfig; /** * base constructor * @details the queue presents and runs the present submits * @pre the config passes `Config::debug_check()` */ - Presenter(Core const&, Queue const&, Config); + Surface(Core const&, Queue const&, Config); /** * constructs and creates - * @details calls @ref Presenter(Core const&, Queue const&, Config), `create()` + * @details calls @ref Surface(Core const&, Queue const&, Config), `create()` */ - Presenter(Core const&, Queue const&, Config, cvk::Surface); + Surface(Core const&, Queue const&, Config, cvk::Surface); /** * @note calls `optDestroy()` */ - ~Presenter() { optDestroy(); } + ~Surface() { optDestroy(); } /** * takes the surface, creates the swapchain, the semaphores and the command buffers @@ -222,7 +222,7 @@ class Presenter { PrimaryCmdBuffer cmd; ///< the barrier of the image to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` /** - * value of `Presenter::_semaphore` for the last submit of `PresentSubmit::cmd`, free once reached + * value of `Surface::_semaphore` for the last submit of `PresentSubmit::cmd`, free once reached */ uint64_t value = 0; }; @@ -241,36 +241,36 @@ class Presenter { // no awaiter parameter: the job takes `submitted()` from the stage semaphore and the frame // number - // the image as a parameter: the job reads no presenter state outside of the strand + // the image as a parameter: the job reads no surface state outside of the strand // `_presented` of the job before awaited: acquire() no longer orders the present jobs /** * present job of `present()` * @details the order: * - off the strand: awaits `Semaphore::submitted()` of the stage semaphore with the frame number - * - off the strand: awaits `Presenter::_presented` of the job before: the present jobs run one + * - off the strand: awaits `Surface::_presented` of the job before: the present jobs run one * at a time, in the order of `present()` - * - fills `Presenter::_submitInfo`: the job before ended its use + * - fills `Surface::_submitInfo`: the job before ended its use * - stage of another family -> `Queue::transfer()` of the release half on the stage queue * - off the strand: records the command buffer, the present jobs run one at a time * - `Queue::present()` with the current swapchain: a recreation only happens in `acquire()`, * after the last present * - the submit waits for the semaphore of the stage and the release, signals - * `Presenter::_semaphore` with the value, `Queue::present()` marks it after the present + * `Surface::_semaphore` with the value, `Queue::present()` marks it after the present * - the command buffer: the acquire half of another family, the transition to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` - * - `VK_ERROR_OUT_OF_DATE_KHR` of the present: sets `Presenter::_outOfDate` before - * `Presenter::_presented` - * - the last step, also after a failure: sets `Presenter::_presented` to the value + * - `VK_ERROR_OUT_OF_DATE_KHR` of the present: sets `Surface::_outOfDate` before + * `Surface::_presented` + * - the last step, also after a failure: sets `Surface::_presented` to the value * @details the errors: * - a failed submit: stores the error, then `dev::skip_submit()` that signals only - * `Presenter::_semaphore`, no present + * `Surface::_semaphore`, no present * - a failed skip submit: `VK_ERROR_DEVICE_LOST` -> stores the error, marks, else terminates: * the waiters would hang * - a failed present: stores the error - * - before the end: every other failure terminates, the waiters on `Presenter::_presented` + * - before the end: every other failure terminates, the waiters on `Surface::_presented` * would hang * @param image the acquired image * @param lastState of the image in the stage primary - * @param value of `Presenter::_semaphore` for the submit + * @param value of `Surface::_semaphore` for the submit * @pre the command buffer of the submit belongs to the queue family of the queue */ [[nodiscard]] cth::co::executor_task presentJob( @@ -287,7 +287,7 @@ class Presenter { * @details * - the first creation: the config of `swapchainConfig()` * - a recreation erases the old images in the graph first: the new images can reuse their handles - * - grows `Presenter::_submits` to the image count + * - grows `Surface::_submits` to the image count * @param extent of the surface, `> 0` * @param graphPtr of the acquiring stage, `nullptr` -> no graph * @pre no present job uses the swapchain: `create()`, or `acquire()` after the end of the last @@ -298,7 +298,7 @@ class Presenter { void updateSwapchain(VkExtent2D extent, StageGraph* graphPtr); /** - * @return `PresenterConfig::swapchain`, `minImageCount` `0` -> `minImageCount` of the surface + `framesInFlight` + * @return `SurfaceConfig::swapchain`, `minImageCount` `0` -> `minImageCount` of the surface + `framesInFlight` */ [[nodiscard]] Swapchain::Config swapchainConfig() const; @@ -318,15 +318,15 @@ class Presenter { // destroyed after the swapchain cvk::Surface _surface; - /** created once the surface extent is `> 0`, `Presenter::_presented` orders its uses */ + /** created once the surface extent is `> 0`, `Surface::_presented` orders its uses */ Swapchain _swapchain; /** - * ring of `PresenterConfig::framesInFlight`, signaled by the acquires + * ring of `SurfaceConfig::framesInFlight`, signaled by the acquires */ std::vector _acquireSemaphores{}; - /** the semaphore in `Presenter::_acquireSemaphores` for the next acquire */ + /** the semaphore in `Surface::_acquireSemaphores` for the next acquire */ size_t _acquireSemaphoreIdx = 0; Semaphore _semaphore; ///< signaled by the present submits, each submit signals the next value @@ -337,7 +337,7 @@ class Presenter { std::vector _submits{}; ///< one per swapchain image /** - * the submit of the present job that runs, `Presenter::_presented` orders its uses + * the submit of the present job that runs, `Surface::_presented` orders its uses * @details each present job fills it: it keeps its capacity for the next jobs */ SubmitInfo _submitInfo{}; @@ -347,7 +347,7 @@ class Presenter { /** * set by an out of date acquire and by the present jobs - * @details `acquire()` reads it after `Presenter::_presented` reached the last present + * @details `acquire()` reads it after `Surface::_presented` reached the last present */ bool _outOfDate = false; @@ -358,12 +358,12 @@ class Presenter { cth::co::catching_scope _jobs{}; public: - Presenter(Presenter const& other) = delete; - Presenter(Presenter&& other) = delete; - Presenter& operator=(Presenter const& other) = delete; - Presenter& operator=(Presenter&& other) = delete; + Surface(Surface const& other) = delete; + Surface(Surface&& other) = delete; + Surface& operator=(Surface const& other) = delete; + Surface& operator=(Surface&& other) = delete; - static constexpr void debug_check(Presenter const&); + static constexpr void debug_check(Surface const&); }; } @@ -371,12 +371,12 @@ namespace jvk { /** * acquired swapchain image of a stage for the scope, presents it at its end * @details - * - `Presenter::acquire()` returns it - * - end, by `Stage::status()`: `SUBMITTED` -> `Presenter::present()`, also after an exception: the frame is complete - * - end, by `Stage::status()`: `SKIPPED` or `UNSUBMITTED` -> nothing, the next `Presenter::acquire()` or - * `Presenter::destroy()` unacquires the image + * - `Surface::acquire()` returns it + * - end, by `Stage::status()`: `SUBMITTED` -> `Surface::present()`, also after an exception: the frame is complete + * - end, by `Stage::status()`: `SKIPPED` or `UNSUBMITTED` -> nothing, the next `Surface::acquire()` or + * `Surface::destroy()` unacquires the image * - no image or a moved-from scope: nothing - * - a failure at the end, e.g. an allocation: the next `Presenter::acquire()` rethrows it + * - a failure at the end, e.g. an allocation: the next `Surface::acquire()` rethrows it * - `->` and `*` reach the image * - declare it before the `scoped_submit` of the stage: the `scoped_submit` ends first and submits * @attention a coroutine destroyed while suspended with the scope alive presents the image of a submitted stage @@ -384,13 +384,13 @@ namespace jvk { class scoped_acquire { public: /** - * @param presenter of the image + * @param surface of the image * @param stage of the acquire * @param imageOpt `std::nullopt` -> no image - * @param jobs of the presenter, gets a failure at the end + * @param jobs of the surface, gets a failure at the end */ scoped_acquire( - Presenter& presenter, + Surface& surface, Stage& stage, std::optional imageOpt, cth::co::catching_scope& jobs @@ -404,15 +404,15 @@ class scoped_acquire { * @pre an image * @pre `Stage::status()` is not `SKIPPED` * @pre the recording of the stage uses the image - * @see `Presenter::present()` + * @see `Surface::present()` */ void present(); /** * ends the scope without a present, the end of the scope does nothing - * @details the next `Presenter::acquire()` or `Presenter::destroy()` unacquires the image + * @details the next `Surface::acquire()` or `Surface::destroy()` unacquires the image * @pre an image - * @see `Presenter::acquire()` + * @see `Surface::acquire()` */ void unacquire(); @@ -429,10 +429,10 @@ class scoped_acquire { [[nodiscard]] constexpr SwapchainImage const& operator*() const { return *_imageOpt; } private: - cth::move_ptr _presenterPtr; ///< `nullptr` -> the end does nothing + cth::move_ptr _surfacePtr; ///< `nullptr` -> the end does nothing cth::ref_wrapper _stage; std::optional _imageOpt; - cth::ref_wrapper _jobs; ///< of the presenter + cth::ref_wrapper _jobs; ///< of the surface public: scoped_acquire(scoped_acquire const& other) = delete; @@ -445,7 +445,7 @@ class scoped_acquire { } namespace jvk { -constexpr void PresenterConfig::debug_check(PresenterConfig const& config) { +constexpr void SurfaceConfig::debug_check(SurfaceConfig const& config) { CTH_CRITICAL(config.framesInFlight == 0, "framesInFlight must be > 0") {} CTH_CRITICAL( config.swapchain.queueFamilies.size() >= 2, @@ -454,13 +454,13 @@ constexpr void PresenterConfig::debug_check(PresenterConfig const& config) { ) {} } -constexpr void Presenter::debug_check(Presenter const& presenter) { - CTH_CRITICAL(!presenter.created(), "presenter must be created") {} +constexpr void Surface::debug_check(Surface const& surface) { + CTH_CRITICAL(!surface.created(), "surface must be created") {} } constexpr void scoped_acquire::debug_check(scoped_acquire const& image) { CTH_CRITICAL( - !image._presenterPtr, + !image._surfacePtr, "the scope must hold the image, got a moved-from or ended scope" ) {} CTH_CRITICAL(!image._imageOpt.has_value(), "the scope must hold an image, got none") {} diff --git a/jvk/incl/jvk/graph/swapchain.hpp b/jvk/incl/jvk/graph/swapchain.hpp index 2e5e2fae..41adff0d 100644 --- a/jvk/incl/jvk/graph/swapchain.hpp +++ b/jvk/incl/jvk/graph/swapchain.hpp @@ -27,7 +27,7 @@ namespace jvk { * - `recreate()` creates the next swapchain with the current one as the old swapchain, the old one retires * - a retired swapchain still presents its acquired images * - `acquire()` destroys the retired swapchains that finished their presents first - * @attention not thread safe: the presenter orders its uses, see `Presenter` + * @attention not thread safe: the surface orders its uses, see `Surface` */ class Swapchain { public: diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index cb4611c4..df3ff35c 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -111,7 +111,7 @@ StageGraph::~StageGraph() { for(auto& stage : frameSlot.stages) { if(stage.status() != Stage::Status::UNSUBMITTED) continue; - // the binary waits dropped: a presenter is destroyed before the graph, its present + // the binary waits dropped: a surface is destroyed before the graph, its present // submits wait for the semaphores of the graph, the acquire semaphore of an unpresented // image is destroyed already stage._stageSlot->extraBinaryWaits.clear(); diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/surface.cpp similarity index 92% rename from jvk/src/graph/presenter.cpp rename to jvk/src/graph/surface.cpp index c35298d8..2b763e11 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/surface.cpp @@ -1,4 +1,4 @@ -#include "jvk/graph/presenter.hpp" +#include "jvk/graph/surface.hpp" #include "jvk/base/core.hpp" #include "jvk/base/queue.hpp" @@ -25,7 +25,7 @@ namespace jvk { -Presenter::Presenter(Core const& core, Queue const& queue, Config config) : +Surface::Surface(Core const& core, Queue const& queue, Config config) : _core{core}, _queue{queue}, _config{std::move(config)}, @@ -33,10 +33,10 @@ Presenter::Presenter(Core const& core, Queue const& queue, Config config) : _swapchain{core, queue.vk(), _surface}, _semaphore{core} { Config::debug_check(_config); } -Presenter::Presenter(Core const& core, Queue const& queue, Config config, cvk::Surface surface) : - Presenter{core, queue, std::move(config)} { create(std::move(surface)); } +Surface::Surface(Core const& core, Queue const& queue, Config config, cvk::Surface surface) : + Surface{core, queue, std::move(config)} { create(std::move(surface)); } -void Presenter::create(cvk::Surface surface) { +void Surface::create(cvk::Surface surface) { Core::debug_check(*_core); cvk::Surface::debug_check(surface); optDestroy(); @@ -60,7 +60,7 @@ void Presenter::create(cvk::Surface surface) { } } -void Presenter::destroy() { +void Surface::destroy() { debug_check(*this); _jobs.wait(); @@ -110,7 +110,7 @@ void Presenter::destroy() { _jobs.clear(); } -cth::co::executor_task Presenter::acquire( +cth::co::executor_task Surface::acquire( Stage& stage, VkPipelineStageFlags2 stages ) { @@ -180,9 +180,9 @@ cth::co::executor_task Presenter::acquire( co_return scoped_acquire{*this, stage, image, _jobs}; } -void Presenter::present(Stage& stage) { +void Surface::present(Stage& stage) { debug_check(*this); - CTH_CRITICAL(!_acquiredOpt.has_value(), "the presenter must have an acquired image") {} + CTH_CRITICAL(!_acquiredOpt.has_value(), "the surface must have an acquired image") {} CTH_CRITICAL(stage.status() != Stage::Status::SUBMITTED, "the stage must be submitted") {} auto const image = _acquiredOpt->image; @@ -203,7 +203,7 @@ void Presenter::present(Stage& stage) { _acquiredOpt.reset(); } -cth::co::executor_task Presenter::presentJob( +cth::co::executor_task Surface::presentJob( Queue const& stageQueue, Semaphore const& stageSemaphore, uint64_t frameNumber, @@ -296,7 +296,7 @@ cth::co::executor_task Presenter::presentJob( catch(...) { _jobs.store(std::current_exception()); } // a failed submit marks nothing: the skip submit signals the value for the waits on the - // presenter + // surface if(_semaphore.submittedValue() < value) { // noexcept: a failed start of the skip submit leaves the value unmarked, the waiters would // hang @@ -312,7 +312,7 @@ cth::co::executor_task Presenter::presentJob( _presented.set(value); } -void Presenter::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { +void Surface::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { if(_swapchain.created() && !_outOfDate && _swapchain.current().extent() == extent) return; @@ -332,7 +332,7 @@ void Presenter::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { ); } -Swapchain::Config Presenter::swapchainConfig() const { +Swapchain::Config Surface::swapchainConfig() const { auto config = _config.swapchain; if(config.minImageCount != 0) return config; @@ -343,7 +343,7 @@ Swapchain::Config Presenter::swapchainConfig() const { return config; } -void Presenter::unacquireImage() { +void Surface::unacquireImage() { _swapchain.current().unacquire(std::array{_acquiredOpt->image.imageIdx}); _acquiredOpt.reset(); } @@ -351,18 +351,18 @@ void Presenter::unacquireImage() { namespace jvk { scoped_acquire::scoped_acquire( - Presenter& presenter, + Surface& surface, Stage& stage, std::optional imageOpt, cth::co::catching_scope& jobs ) noexcept : - _presenterPtr{&presenter}, + _surfacePtr{&surface}, _stage{stage}, _imageOpt{std::move(imageOpt)}, _jobs{jobs} {} scoped_acquire::~scoped_acquire() { - if(!_presenterPtr || !_imageOpt.has_value()) + if(!_surfacePtr || !_imageOpt.has_value()) return; auto& stage = *_stage; @@ -372,7 +372,7 @@ scoped_acquire::~scoped_acquire() { // a destructor does not throw and is no task: it stores the failure, the next acquire() // rethrows - try { _presenterPtr->present(stage); } + try { _surfacePtr->present(stage); } catch(...) { _jobs->store(std::current_exception()); } } @@ -382,12 +382,12 @@ void scoped_acquire::present() { if(_stage->status() == Stage::Status::UNSUBMITTED) _stage->submit(); - _presenterPtr.release()->present(*_stage); + _surfacePtr.release()->present(*_stage); } void scoped_acquire::unacquire() { debug_check(*this); // the next acquire() or destroy() unacquires the image - static_cast(_presenterPtr.release()); + static_cast(_surfacePtr.release()); } } diff --git a/jvk/tests/src/base/core_test.cpp b/jvk/tests/src/base/core_test.cpp index 7ae4be56..e67517a7 100644 --- a/jvk/tests/src/base/core_test.cpp +++ b/jvk/tests/src/base/core_test.cpp @@ -7,7 +7,7 @@ #include "jvk/base/queue_sets.hpp" #include "jvk/data/sampler_heap.hpp" //TEMP compile check of the phase 6 headers until their sources exist -#include "jvk/graph/presenter.hpp" +#include "jvk/graph/surface.hpp" #include "jvk/graph/stage_graph.hpp" #include "jvk/sync/semaphore.hpp" #include "jvk/sync/timeline_reactor.hpp" diff --git a/jvk/tests/src/graph/presenter_test.cpp b/jvk/tests/src/graph/surface_test.cpp similarity index 68% rename from jvk/tests/src/graph/presenter_test.cpp rename to jvk/tests/src/graph/surface_test.cpp index 7fd3f1ab..371ccee7 100644 --- a/jvk/tests/src/graph/presenter_test.cpp +++ b/jvk/tests/src/graph/surface_test.cpp @@ -1,4 +1,4 @@ -#include "jvk/graph/presenter.hpp" +#include "jvk/graph/surface.hpp" #include "context.hpp" #include "test.hpp" @@ -47,7 +47,7 @@ namespace { [[nodiscard]] bool create_present_core( std::optional& coreOpt, test::Context const& context, - cvk::Surface const& surface, + cvk::Surface const& windowSurface, std::vector queueProperties = {GRAPHICS | PRESENT}, size_t driverThreads = 0 ) { @@ -58,7 +58,7 @@ namespace { coreOpt.emplace( context.instance, std::move(config), - std::array{cth::ref_wrapper{surface}} + std::array{cth::ref_wrapper{windowSurface}} ); } catch(cvk::cvk_exception const&) { return false; } @@ -71,8 +71,8 @@ namespace { return core.executor().sync_wait(graph.nextFrame()); } - [[nodiscard]] scoped_acquire acquire(Core const& core, Presenter& presenter, Stage& stage) { - return core.executor().sync_wait(presenter.acquire(stage, ATTACHMENT_OUTPUT)); + [[nodiscard]] scoped_acquire acquire(Core const& core, Surface& surface, Stage& stage) { + return core.executor().sync_wait(surface.acquire(stage, ATTACHMENT_OUTPUT)); } cth::co::executor_task await_stage(Stage const& stage) { co_await stage; } @@ -99,25 +99,25 @@ namespace { /** * @return number of the acquired images of the swapchain */ - [[nodiscard]] size_t acquired_images(Presenter const& presenter) { + [[nodiscard]] size_t acquired_images(Surface const& surface) { size_t acquired = 0; - for(uint32_t imageIdx = 0; imageIdx < presenter.swapchain().current().imageCount(); ++ + for(uint32_t imageIdx = 0; imageIdx < surface.swapchain().current().imageCount(); ++ imageIdx) - if(presenter.swapchain().current().acquired(imageIdx)) + if(surface.swapchain().current().acquired(imageIdx)) ++acquired; return acquired; } /** - * reads the acquire state of the image in the strand of the presenter queue + * reads the acquire state of the image in the strand of the surface queue */ cth::co::executor_task acquired_in_strand( Queue const& queue, - Presenter const& presenter, + Surface const& surface, uint32_t imageIdx ) { co_await queue.executor().schedule(); - co_return presenter.swapchain().current().acquired(imageIdx); + co_return surface.swapchain().current().acquired(imageIdx); } /** @@ -126,11 +126,11 @@ namespace { [[nodiscard]] bool reaches_unacquired( Core const& core, Queue const& queue, - Presenter const& presenter, + Surface const& surface, uint32_t imageIdx ) { auto const deadline = std::chrono::steady_clock::now() + TIMEOUT; - while(core.executor().sync_wait(acquired_in_strand(queue, presenter, imageIdx))) { + while(core.executor().sync_wait(acquired_in_strand(queue, surface, imageIdx))) { if(std::chrono::steady_clock::now() > deadline) return false; std::this_thread::sleep_for(std::chrono::milliseconds{1}); @@ -168,11 +168,11 @@ namespace { SwapchainImage present_behind_gate( Core const& core, Stage& stage, - Presenter& presenter, + Surface& surface, Semaphore const& gate ) { stage.await(gate, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, 1); - auto const image = acquire(core, presenter, stage); + auto const image = acquire(core, surface, stage); EXPECT_TRUE(image); auto const primary = stage.begin(); clear(*primary, *image); @@ -217,18 +217,18 @@ namespace { SwapchainImage present_msaa_frame( Core const& core, StageGraph& graph, - Presenter& presenter, + Surface& surface, std::optional& msaaOpt ) { auto& stage = next_frame(core, graph).stage(0); - auto const image = acquire(core, presenter, stage); + auto const image = acquire(core, surface, stage); EXPECT_TRUE(image); if(!msaaOpt.has_value() || msaaOpt->image.extent() != image->extent) { if(msaaOpt.has_value()) { stage.retain(std::move(msaaOpt->view)); stage.retain(std::move(msaaOpt->image)); } - msaaOpt.emplace(core, presenter.swapchain().current().format(), image->extent); + msaaOpt.emplace(core, surface.swapchain().current().format(), image->extent); } auto const primary = stage.begin(); @@ -255,9 +255,9 @@ namespace { * @details the acquire comes before `Stage::begin()` * @return the image */ - SwapchainImage present_frame(Core const& core, StageGraph& graph, Presenter& presenter) { + SwapchainImage present_frame(Core const& core, StageGraph& graph, Surface& surface) { auto& stage = next_frame(core, graph).stage(0); - auto const image = acquire(core, presenter, stage); + auto const image = acquire(core, surface, stage); EXPECT_TRUE(image); auto const primary = stage.begin(); clear(*primary, *image); @@ -265,108 +265,108 @@ namespace { } } -JVK_TEST(Presenter, frame_loop_clears_and_presents) { +JVK_TEST(Surface, frame_loop_clears_and_presents) { constexpr size_t FRAMES = 6; test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; - ASSERT_TRUE(presenter.created()); - ASSERT_TRUE(presenter.swapchain().created()); + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + ASSERT_TRUE(surface.created()); + ASSERT_TRUE(surface.swapchain().created()); for(size_t i = 0; i < FRAMES; ++i) { - auto const image = present_frame(core, graph, presenter); + auto const image = present_frame(core, graph, surface); EXPECT_EQ(image.extent, test::HEADLESS_EXTENT); - EXPECT_LT(image.imageIdx, presenter.swapchain().current().imageCount()); + EXPECT_LT(image.imageIdx, surface.swapchain().current().imageCount()); } - presenter.destroy(); - EXPECT_FALSE(presenter.created()); + surface.destroy(); + EXPECT_FALSE(surface.created()); } -JVK_TEST(Presenter, frame_loop_with_driver_threads_presents) { +JVK_TEST(Surface, frame_loop_with_driver_threads_presents) { constexpr size_t FRAMES = 6; test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface, {GRAPHICS | PRESENT}, 2)) + if(!create_present_core(coreOpt, context, windowSurface, {GRAPHICS | PRESENT}, 2)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; for(size_t i = 0; i < FRAMES; ++i) - EXPECT_EQ(present_frame(core, graph, presenter).extent, test::HEADLESS_EXTENT); + EXPECT_EQ(present_frame(core, graph, surface).extent, test::HEADLESS_EXTENT); } -JVK_TEST(Presenter, extent_0_gives_no_image_until_the_extent_is_larger) { +JVK_TEST(Surface, extent_0_gives_no_image_until_the_extent_is_larger) { test::Context const context{}; std::atomic windowExtent{VkExtent2D{0, 0}}; - auto surface = test::headless_surface( + auto windowSurface = test::headless_surface( context.instance, [&windowExtent] { return windowExtent.load(); } ); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; - EXPECT_FALSE(presenter.swapchain().created()); + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + EXPECT_FALSE(surface.swapchain().created()); // no image, no wait: the stage submits without the image, the scoped_acquire does nothing auto& stage = next_frame(core, graph).stage(0); { - auto const image = acquire(core, presenter, stage); + auto const image = acquire(core, surface, stage); EXPECT_FALSE(image); auto const primary = stage.begin(); } EXPECT_EQ(stage.status(), Stage::Status::SUBMITTED); windowExtent = VkExtent2D{32, 24}; - auto const image = present_frame(core, graph, presenter); + auto const image = present_frame(core, graph, surface); EXPECT_EQ(image.extent, (VkExtent2D{32, 24})); - EXPECT_TRUE(presenter.swapchain().created()); + EXPECT_TRUE(surface.swapchain().created()); } -JVK_TEST(Presenter, new_extent_recreates_the_swapchain) { +JVK_TEST(Surface, new_extent_recreates_the_swapchain) { test::Context const context{}; std::atomic windowExtent{VkExtent2D{32, 32}}; - auto surface = test::headless_surface( + auto windowSurface = test::headless_surface( context.instance, [&windowExtent] { return windowExtent.load(); } ); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; - EXPECT_EQ(present_frame(core, graph, presenter).extent, (VkExtent2D{32, 32})); + EXPECT_EQ(present_frame(core, graph, surface).extent, (VkExtent2D{32, 32})); windowExtent = VkExtent2D{48, 40}; - EXPECT_EQ(present_frame(core, graph, presenter).extent, (VkExtent2D{48, 40})); - EXPECT_EQ(presenter.swapchain().current().extent(), (VkExtent2D{48, 40})); + EXPECT_EQ(present_frame(core, graph, surface).extent, (VkExtent2D{48, 40})); + EXPECT_EQ(surface.swapchain().current().extent(), (VkExtent2D{48, 40})); // the next frames present on the new swapchain - EXPECT_EQ(present_frame(core, graph, presenter).extent, (VkExtent2D{48, 40})); + EXPECT_EQ(present_frame(core, graph, surface).extent, (VkExtent2D{48, 40})); } -JVK_TEST(Presenter, multisampled_frames_resolve_into_the_image_and_present) { +JVK_TEST(Surface, multisampled_frames_resolve_into_the_image_and_present) { constexpr size_t FRAMES = 4; test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; if(!supports_msaa(core)) @@ -375,25 +375,25 @@ JVK_TEST(Presenter, multisampled_frames_resolve_into_the_image_and_present) { // before the graph: the target lives until the gpu finished the frames std::optional msaaOpt{}; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; // the resolve writes the image, the present transition starts from the resolve state for(size_t i = 0; i < FRAMES; ++i) EXPECT_EQ( - present_msaa_frame(core, graph, presenter, msaaOpt).extent, + present_msaa_frame(core, graph, surface, msaaOpt).extent, test::HEADLESS_EXTENT ); } -JVK_TEST(Presenter, recreation_retains_the_multisampled_target_of_the_old_extent) { +JVK_TEST(Surface, recreation_retains_the_multisampled_target_of_the_old_extent) { test::Context const context{}; std::atomic windowExtent{VkExtent2D{32, 32}}; - auto surface = test::headless_surface( + auto windowSurface = test::headless_surface( context.instance, [&windowExtent] { return windowExtent.load(); } ); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; if(!supports_msaa(core)) @@ -401,34 +401,34 @@ JVK_TEST(Presenter, recreation_retains_the_multisampled_target_of_the_old_extent std::optional msaaOpt{}; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; - EXPECT_EQ(present_msaa_frame(core, graph, presenter, msaaOpt).extent, (VkExtent2D{32, 32})); + EXPECT_EQ(present_msaa_frame(core, graph, surface, msaaOpt).extent, (VkExtent2D{32, 32})); // the new extent recreates the swapchain, the frame retains the old target windowExtent = VkExtent2D{48, 40}; - EXPECT_EQ(present_msaa_frame(core, graph, presenter, msaaOpt).extent, (VkExtent2D{48, 40})); + EXPECT_EQ(present_msaa_frame(core, graph, surface, msaaOpt).extent, (VkExtent2D{48, 40})); EXPECT_EQ(msaaOpt->image.extent(), (VkExtent2D{48, 40})); // the graph destroys the old target after the gpu finished its frame for(size_t i = 0; i < 3; ++i) - EXPECT_EQ(present_msaa_frame(core, graph, presenter, msaaOpt).extent, (VkExtent2D{48, 40})); + EXPECT_EQ(present_msaa_frame(core, graph, surface, msaaOpt).extent, (VkExtent2D{48, 40})); } -JVK_TEST(Presenter, acquire_waits_for_the_present_before) { +JVK_TEST(Surface, acquire_waits_for_the_present_before) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; Semaphore const gate{core, cvk::create}; auto& first = next_frame(core, graph).stage(0); - present_behind_gate(core, first, presenter, gate); + present_behind_gate(core, first, surface, gate); // the present of the first frame waits for the mark of the gate, the next acquire for the present auto& second = next_frame(core, graph).stage(0); @@ -436,8 +436,8 @@ JVK_TEST(Presenter, acquire_waits_for_the_present_before) { size_t acquiredImages = 0; std::jthread frame{ [&] { - auto const image = acquire(core, presenter, second); - acquiredImages = acquired_images(presenter); + auto const image = acquire(core, surface, second); + acquiredImages = acquired_images(surface); acquiredSignal.release(); EXPECT_TRUE(image); auto const primary = second.begin(); @@ -458,51 +458,51 @@ JVK_TEST(Presenter, acquire_waits_for_the_present_before) { wait(core, second); - present_frame(core, graph, presenter); + present_frame(core, graph, surface); } -JVK_TEST(Presenter, recreation_retires_the_old_swapchain_until_its_presents_ended) { +JVK_TEST(Surface, recreation_retires_the_old_swapchain_until_its_presents_ended) { test::Context const context{}; std::atomic windowExtent{VkExtent2D{32, 32}}; - auto surface = test::headless_surface( + auto windowSurface = test::headless_surface( context.instance, [&windowExtent] { return windowExtent.load(); } ); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; - EXPECT_EQ(present_frame(core, graph, presenter).extent, (VkExtent2D{32, 32})); + EXPECT_EQ(present_frame(core, graph, surface).extent, (VkExtent2D{32, 32})); // the new extent recreates the swapchain, the old one stays until its presents ended windowExtent = VkExtent2D{48, 40}; - EXPECT_EQ(present_frame(core, graph, presenter).extent, (VkExtent2D{48, 40})); - EXPECT_LE(presenter.swapchain().retired(), 1); + EXPECT_EQ(present_frame(core, graph, surface).extent, (VkExtent2D{48, 40})); + EXPECT_LE(surface.swapchain().retired(), 1); // a later acquire destroys the retired swapchain once its presents ended, the bound only ends a broken loop - for(size_t i = 0; i < 16 && presenter.swapchain().retired() != 0; ++i) - present_frame(core, graph, presenter); - EXPECT_EQ(presenter.swapchain().retired(), 0); + for(size_t i = 0; i < 16 && surface.swapchain().retired() != 0; ++i) + present_frame(core, graph, surface); + EXPECT_EQ(surface.swapchain().retired(), 0); } -JVK_TEST(Presenter, scope_unacquire_leaves_the_image_to_the_next_acquire) { +JVK_TEST(Surface, scope_unacquire_leaves_the_image_to_the_next_acquire) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; auto& stage = next_frame(core, graph).stage(0); { - auto image = acquire(core, presenter, stage); + auto image = acquire(core, surface, stage); ASSERT_TRUE(image); image.unacquire(); @@ -510,37 +510,37 @@ JVK_TEST(Presenter, scope_unacquire_leaves_the_image_to_the_next_acquire) { auto const primary = stage.begin(); } // the scoped_acquire did nothing at its end, the image stays acquired - EXPECT_EQ(acquired_images(presenter), 1); + EXPECT_EQ(acquired_images(surface), 1); // the next acquire waits for the stage on the gpu and gives the image back first auto& next = next_frame(core, graph).stage(0); { - auto const image = acquire(core, presenter, next); + auto const image = acquire(core, surface, next); ASSERT_TRUE(image); - EXPECT_EQ(acquired_images(presenter), 1); + EXPECT_EQ(acquired_images(surface), 1); auto const primary = next.begin(); clear(*primary, *image); } - present_frame(core, graph, presenter); + present_frame(core, graph, surface); } -JVK_TEST(Presenter, next_acquire_after_a_skipped_stage_unacquires_the_image) { +JVK_TEST(Surface, next_acquire_after_a_skipped_stage_unacquires_the_image) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; // Stage::begin() before the acquire works too auto& stage = next_frame(core, graph).stage(0); { auto const primary = stage.begin(); - auto const image = acquire(core, presenter, stage); + auto const image = acquire(core, surface, stage); ASSERT_TRUE(image); clear(*primary, *image); @@ -548,38 +548,38 @@ JVK_TEST(Presenter, next_acquire_after_a_skipped_stage_unacquires_the_image) { stage.skip(); } EXPECT_EQ(stage.status(), Stage::Status::SKIPPED); - EXPECT_EQ(acquired_images(presenter), 1); + EXPECT_EQ(acquired_images(surface), 1); // at once: the acquire waits for the skip on the gpu before the unacquire, no validation error auto& next = next_frame(core, graph).stage(0); { - auto const image = acquire(core, presenter, next); + auto const image = acquire(core, surface, next); ASSERT_TRUE(image); - EXPECT_EQ(acquired_images(presenter), 1); + EXPECT_EQ(acquired_images(surface), 1); auto const primary = next.begin(); clear(*primary, *image); } - present_frame(core, graph, presenter); + present_frame(core, graph, surface); } -JVK_TEST(Presenter, image_scope_ending_before_the_submit_leaves_the_image_to_the_next_acquire) { +JVK_TEST(Surface, image_scope_ending_before_the_submit_leaves_the_image_to_the_next_acquire) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; auto& stage = next_frame(core, graph).stage(0); { - auto const image = acquire(core, presenter, stage); + auto const image = acquire(core, surface, stage); ASSERT_TRUE(image); } - EXPECT_EQ(acquired_images(presenter), 1); + EXPECT_EQ(acquired_images(surface), 1); // the submit waits for the acquire semaphore, nothing uses the image { @@ -589,30 +589,30 @@ JVK_TEST(Presenter, image_scope_ending_before_the_submit_leaves_the_image_to_the // the next acquire waits for the submit on the gpu and gives the image back first auto& next = next_frame(core, graph).stage(0); { - auto const image = acquire(core, presenter, next); + auto const image = acquire(core, surface, next); ASSERT_TRUE(image); - EXPECT_EQ(acquired_images(presenter), 1); + EXPECT_EQ(acquired_images(surface), 1); auto const primary = next.begin(); clear(*primary, *image); } - present_frame(core, graph, presenter); + present_frame(core, graph, surface); } -JVK_TEST(Presenter, present_inside_the_rendering_scope_submits_and_presents_once) { +JVK_TEST(Surface, present_inside_the_rendering_scope_submits_and_presents_once) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; auto& stage = next_frame(core, graph).stage(0); { - auto image = acquire(core, presenter, stage); + auto image = acquire(core, surface, stage); ASSERT_TRUE(image); auto const primary = stage.begin(); auto const rendering = primary->beginRendering(clear_info(*image)); @@ -624,24 +624,24 @@ JVK_TEST(Presenter, present_inside_the_rendering_scope_submits_and_presents_once } wait(core, stage); - present_frame(core, graph, presenter); + present_frame(core, graph, surface); } -JVK_TEST(Presenter, moved_scopes_act_once) { +JVK_TEST(Surface, moved_scopes_act_once) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; auto& stage = next_frame(core, graph).stage(0); { // the moved-from scopes end after the moved ones: a second submit or present fails - auto image = acquire(core, presenter, stage); + auto image = acquire(core, surface, stage); auto const movedImage = std::move(image); ASSERT_TRUE(movedImage); auto primary = stage.begin(); @@ -651,26 +651,26 @@ JVK_TEST(Presenter, moved_scopes_act_once) { EXPECT_EQ(stage.status(), Stage::Status::SUBMITTED); wait(core, stage); - present_frame(core, graph, presenter); + present_frame(core, graph, surface); } -JVK_TEST(Presenter, exception_in_the_recording_submits_and_presents_nothing) { +JVK_TEST(Surface, exception_in_the_recording_submits_and_presents_nothing) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; StageGraph graph{core, {.stages = {{.queueIdx = 0}}, .frameSlots = 2}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; Stage const* stagePtr = nullptr; uint32_t imageIdx = 0; try { for(size_t i = 0;; ++i) { auto& stage = next_frame(core, graph).stage(0); - auto const image = acquire(core, presenter, stage); + auto const image = acquire(core, surface, stage); auto const primary = stage.begin(); auto const rendering = primary->beginRendering(clear_info(*image)); if(i == 2) { @@ -684,37 +684,37 @@ JVK_TEST(Presenter, exception_in_the_recording_submits_and_presents_nothing) { ASSERT_NE(stagePtr, nullptr); EXPECT_EQ(stagePtr->status(), Stage::Status::UNSUBMITTED); - EXPECT_TRUE(presenter.swapchain().current().acquired(imageIdx)); + EXPECT_TRUE(surface.swapchain().current().acquired(imageIdx)); // the next frame skips the stage, the next acquire gives the image back first auto& stage = next_frame(core, graph).stage(0); EXPECT_EQ(stagePtr->status(), Stage::Status::SKIPPED); { - auto const image = acquire(core, presenter, stage); + auto const image = acquire(core, surface, stage); ASSERT_TRUE(image); - EXPECT_EQ(acquired_images(presenter), 1); + EXPECT_EQ(acquired_images(surface), 1); auto const primary = stage.begin(); clear(*primary, *image); } - present_frame(core, graph, presenter); + present_frame(core, graph, surface); } -JVK_TEST(Presenter, exception_after_the_submit_presents_the_image) { +JVK_TEST(Surface, exception_after_the_submit_presents_the_image) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; auto& stage = next_frame(core, graph).stage(0); std::optional imageIdxOpt = std::nullopt; try { - auto const image = acquire(core, presenter, stage); + auto const image = acquire(core, surface, stage); auto const primary = stage.begin(); if(image) { imageIdxOpt = image->imageIdx; @@ -728,26 +728,26 @@ JVK_TEST(Presenter, exception_after_the_submit_presents_the_image) { EXPECT_EQ(stage.status(), Stage::Status::SUBMITTED); // the frame is complete: the scoped_acquire presents the image - EXPECT_TRUE(reaches_unacquired(core, core.queue(0), presenter, *imageIdxOpt)); + EXPECT_TRUE(reaches_unacquired(core, core.queue(0), surface, *imageIdxOpt)); wait(core, stage); - present_frame(core, graph, presenter); + present_frame(core, graph, surface); } -JVK_TEST(Presenter, exception_propagated_to_the_end_destroys_graph_and_presenter) { +JVK_TEST(Surface, exception_propagated_to_the_end_destroys_graph_and_surface) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) + if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; - auto const run = [&core, &surface] { + auto const run = [&core, &windowSurface] { StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; for(size_t i = 0;; ++i) { auto& stage = next_frame(core, graph).stage(0); - auto const image = acquire(core, presenter, stage); + auto const image = acquire(core, surface, stage); auto const primary = stage.begin(); auto const rendering = primary->beginRendering(clear_info(*image)); if(i == 2) @@ -757,12 +757,12 @@ JVK_TEST(Presenter, exception_propagated_to_the_end_destroys_graph_and_presenter EXPECT_THROW(run(), test_exception); } -JVK_TEST(Presenter, present_queue_of_the_same_family) { +JVK_TEST(Surface, present_queue_of_the_same_family) { constexpr size_t FRAMES = 4; test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface, {GRAPHICS, GRAPHICS | PRESENT})) + if(!create_present_core(coreOpt, context, windowSurface, {GRAPHICS, GRAPHICS | PRESENT})) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; if(&core.queue(0) == &core.queue(1) @@ -770,18 +770,18 @@ JVK_TEST(Presenter, present_queue_of_the_same_family) { GTEST_SKIP() << "needs two vulkan queues of one family, e.g. ANV_QUEUE_OVERRIDE=gc=2,c=1"; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(1), {}, std::move(surface)}; + Surface surface{core, core.queue(1), {}, std::move(windowSurface)}; for(size_t i = 0; i < FRAMES; ++i) - present_frame(core, graph, presenter); + present_frame(core, graph, surface); } -JVK_TEST(Presenter, present_queue_of_another_family) { +JVK_TEST(Surface, present_queue_of_another_family) { constexpr size_t FRAMES = 4; test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface, {GRAPHICS, COMPUTE | PRESENT})) + if(!create_present_core(coreOpt, context, windowSurface, {GRAPHICS, COMPUTE | PRESENT})) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; auto const& stageQueue = core.queue(0); @@ -789,11 +789,11 @@ JVK_TEST(Presenter, present_queue_of_another_family) { GTEST_SKIP() << "needs two queue families, e.g. ANV_QUEUE_OVERRIDE=gc=2,c=1"; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(1), {}, std::move(surface)}; + Surface surface{core, core.queue(1), {}, std::move(windowSurface)}; for(size_t i = 0; i < FRAMES; ++i) - present_frame(core, graph, presenter); - presenter.destroy(); + present_frame(core, graph, surface); + surface.destroy(); // one release on the stage queue per frame: the next release gets the next value of its counter auto const next = core.executor().sync_wait(stageQueue.transfer(cvk::Barrier{})); From 094233efeb112bfcf072c1f5e53cb7d2f3146171 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:05:01 +0100 Subject: [PATCH 41/68] jvk: acquire and present split across stages, the present fused into the submit of its stage - Surface::acquire(acquireStage, presentStage): the wait for the acquire in the first, the present after the submit of the second, returns std::optional - the present stage owns a dev::PendingPresent: presented by its submit job, dropped on a skip - the end barrier goes into an epilogue command buffer, recorded after append(): no extra submit - the submit job presents by the queue of the surface: with its own submit, present-only, or after a transfer of the acquire half; several surfaces present after one stage - removed: scoped_acquire, Presenter::present(), the present jobs, the semaphore and command buffers of the surface - per frame (headless MAILBOX, 2 workers): vkQueueSubmit2 2 -> 1, operator new 14 -> 10.5, mutex locks 26 -> 20 --- demo/cube/src/main.cpp | 7 +- demo/triangle/src/main.cpp | 6 +- jvk/incl/jvk/graph/frame.hpp | 5 + jvk/incl/jvk/graph/pending_present.hpp | 149 +++++++++ jvk/incl/jvk/graph/stage.hpp | 76 ++++- jvk/incl/jvk/graph/stage_graph.hpp | 52 ++- jvk/incl/jvk/graph/surface.hpp | 358 +++++--------------- jvk/src/graph/pending_present.cpp | 17 + jvk/src/graph/stage.cpp | 20 +- jvk/src/graph/stage_graph.cpp | 223 ++++++++++++- jvk/src/graph/surface.cpp | 313 ++++------------- jvk/tests/src/graph/surface_test.cpp | 443 +++++++++++++++++-------- 12 files changed, 967 insertions(+), 702 deletions(-) create mode 100644 jvk/incl/jvk/graph/pending_present.hpp create mode 100644 jvk/src/graph/pending_present.cpp diff --git a/demo/cube/src/main.cpp b/demo/cube/src/main.cpp index f90482da..a5ea173c 100644 --- a/demo/cube/src/main.cpp +++ b/demo/cube/src/main.cpp @@ -419,8 +419,7 @@ void frame_time_window(FrameTimes const& times, bool& collapsed) { /** * draws the spinning cube and the frame time window in every frame until the window closes * @details - * - only the scopes: the `jvk::scoped_submit` ends first and submits - * - then the `jvk::scoped_acquire` presents + * - only the scope: the `jvk::scoped_submit` submits, the job of the stage presents * - the ImGui frame comes first: it takes the events also in a frame without an image * - frame time: the time between the starts of two iterations, the first iteration has none */ @@ -558,7 +557,7 @@ cth::co::executor_task draw_frames( * creates the window, the vulkan objects, the cube and the pipeline, then draws until the window closes * @details the declaration order is the destruction order backwards: * - the cube, the pipeline, the ImGui and the targets live until `~StageGraph()` waited for the gpu - * - the surface is destroyed before the graph: its present jobs wait for the semaphores of the graph + * - the surface is destroyed after the graph: the stages present to it */ void run() { cvk::Cvk const cvk{}; @@ -613,13 +612,13 @@ void run() { }; std::optional targetsOpt{}; - jvk::StageGraph graph{core, {.stages = {{.queueIdx = QUEUE_IDX}}}}; jvk::Surface surface{ core, core.queue(QUEUE_IDX), {.swapchain = {.formats = {SURFACE_FORMAT}}}, std::move(windowSurface), }; + jvk::StageGraph graph{core, {.stages = {{.queueIdx = QUEUE_IDX}}}}; core.executor().sync_wait( draw_frames(window, core, graph, surface, pipeline, cube, imgui, targetsOpt) diff --git a/demo/triangle/src/main.cpp b/demo/triangle/src/main.cpp index 3e88f644..48cefb77 100644 --- a/demo/triangle/src/main.cpp +++ b/demo/triangle/src/main.cpp @@ -83,7 +83,7 @@ struct MsaaTarget { /** * draws the triangle in every frame until the window closes - * @details only the scopes: the `jvk::scoped_submit` ends first and submits, then the `jvk::scoped_acquire` presents + * @details only the scope: the `jvk::scoped_submit` submits, the job of the stage presents */ cth::co::executor_task draw_frames( cgfw::Window& window, @@ -141,7 +141,7 @@ cth::co::executor_task draw_frames( * creates the window, the vulkan objects and the pipeline, then draws until the window closes * @details the declaration order is the destruction order backwards: * - the pipeline and the multisampled target live until `~StageGraph()` waited for the gpu - * - the surface is destroyed before the graph: its present jobs wait for the semaphores of the graph + * - the surface is destroyed after the graph: the stages present to it */ void run() { cvk::Cvk const cvk{}; @@ -178,13 +178,13 @@ void run() { cvk::GraphicsPipeline const pipeline{core, std::move(pipelineConfig), cvk::create}; std::optional msaaOpt{}; - jvk::StageGraph graph{core, {.stages = {{.queueIdx = QUEUE_IDX}}}}; jvk::Surface surface{ core, core.queue(QUEUE_IDX), {.swapchain = {.formats = {SURFACE_FORMAT}}}, std::move(windowSurface), }; + jvk::StageGraph graph{core, {.stages = {{.queueIdx = QUEUE_IDX}}}}; core.executor().sync_wait(draw_frames(window, core, graph, surface, pipeline, msaaOpt)); } diff --git a/jvk/incl/jvk/graph/frame.hpp b/jvk/incl/jvk/graph/frame.hpp index 8e4128f4..ff7c9d5d 100644 --- a/jvk/incl/jvk/graph/frame.hpp +++ b/jvk/incl/jvk/graph/frame.hpp @@ -39,6 +39,11 @@ class Frame { */ [[nodiscard]] Stage& stage(size_t stageId); + /** + * @return the stage in this frame, see `stage()` + */ + [[nodiscard]] Stage& operator[](size_t stageId) { return stage(stageId); } + /** * @return number of the frame, the first frame is `StageGraph::firstFrameNumber()` */ diff --git a/jvk/incl/jvk/graph/pending_present.hpp b/jvk/incl/jvk/graph/pending_present.hpp new file mode 100644 index 00000000..6ce62698 --- /dev/null +++ b/jvk/incl/jvk/graph/pending_present.hpp @@ -0,0 +1,149 @@ +#pragma once +#include "jvk/base/queue.hpp" +#include "jvk/sync/semaphore.hpp" + +#include "cvk/surface/swapchain.hpp" + +#include + +#include +#include +#include + +#include +#include +#include + + +namespace cvk { +class Image; +} + +namespace jvk::dev { +/** + * state of a `Surface` that the pending present of its last image resolves + * @details written before `PresentState::resolved`, `Surface::acquire()` reads it after its wait + */ +struct PresentState { + /** value of the last resolved image of the surface, the images count from `1` */ + cth::co::counter_event resolved{}; + + /** set by an out of date acquire or present, `Surface::acquire()` recreates the swapchain */ + bool outOfDate = false; + + /** + * the last image was dropped: `Surface::acquire()` unacquires it + * @details the gpu finished the stages that used it before its resolve + */ + bool dropped = false; + + /** + * resolves the image as presented + * @details `VK_ERROR_OUT_OF_DATE_KHR` -> sets `PresentState::outOfDate` + * @param value of the image + * @param result of the present of the image + * @pre the images before the image are resolved + */ + void present(uint64_t value, VkResult result); + + /** + * resolves the image as dropped: the next `Surface::acquire()` unacquires it + * @param value of the image + * @pre the images before the image are resolved + * @pre the gpu finished the stages that used the image, or no stage submitted a use of it + */ + void drop(uint64_t value); +}; + +/** + * deleter of a pending present: drops the image + */ +struct present_dropper { + uint64_t value; ///< of the image in `PresentState::resolved` + + void operator()(PresentState* state) const { state->drop(value); } +}; + +/** + * present of an acquired swapchain image after the submit of its present stage + * @details + * - `Surface::acquire()` hands it to the present stage, see `Stage::present()` + * - the submit job of the present stage presents the image, a skip drops it + * - resolves the image exactly once: `present()`, `drop()`, or its destruction as dropped + * - destroyed pending: only after the gpu finished the stages that used the image, e.g. in + * `~StageGraph()`, or before a stage submitted a use of it + * - a moved-from present resolves nothing + */ +class PendingPresent { +public: + /** + * @param state of the surface + * @param value of the image in `PresentState::resolved` + * @param queue of the surface, presents the image + * @param swapchain the current swapchain of the surface + * @param imageIdx of the acquired image + */ + PendingPresent( + PresentState& state, + uint64_t value, + Queue const& queue, + cvk::Swapchain& swapchain, + uint32_t imageIdx + ) : + _state{&state, present_dropper{.value = value}}, + _queue{queue}, + _swapchain{swapchain}, + _imageIdx{imageIdx} {} + + /** + * resolves the image as presented + * @param result of the present of the image + * @pre not resolved + * @see `PresentState::present()` + */ + void present(VkResult result) { + debug_check(*this); + auto const value = _state.get_deleter().value; + _state.release()->present(value, result); + } + + /** + * resolves the image as dropped + * @pre not resolved + * @pre the gpu finished the stages that used the image + * @see `PresentState::drop()` + */ + void drop() { + debug_check(*this); + _state.reset(); + } + + [[nodiscard]] Queue const& queue() const { return *_queue; } + [[nodiscard]] PresentImage image() const { return {_swapchain, _imageIdx}; } + + /** + * @return the image in the swapchain + */ + [[nodiscard]] cvk::Image const& swapchainImage() const { return _swapchain->image(_imageIdx); } + +private: + std::unique_ptr _state; ///< `nullptr` -> resolved or moved from + cth::ref_wrapper _queue; + cth::ref_wrapper _swapchain; + uint32_t _imageIdx; + +public: + PendingPresent(PendingPresent const& other) = delete; + PendingPresent(PendingPresent&& other) noexcept = default; + PendingPresent& operator=(PendingPresent const& other) = delete; + PendingPresent& operator=(PendingPresent&& other) noexcept = default; + + static void debug_check(PendingPresent const&); +}; +} + +namespace jvk::dev { +inline void PendingPresent::debug_check(PendingPresent const& present) { + CTH_CRITICAL(present._state == nullptr, "the present must be pending") {} +} +} diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index 23b6c8c2..0b610650 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -2,11 +2,14 @@ #include "jvk/base/queue.hpp" #include "jvk/base/stasis.hpp" #include "jvk/cmd/cmd_buffer.hpp" +#include "jvk/graph/pending_present.hpp" +#include "jvk/sync/resource_tracker.hpp" #include "jvk/sync/semaphore.hpp" #include "cvk/base/queue/submit_info.hpp" #include "cvk/data/buffer/base_buffer.hpp" #include "cvk/data/img/image.hpp" +#include "cvk/render/sync/barrier.hpp" #include @@ -46,7 +49,7 @@ namespace jvk::dev { * - fills the `SubmitInfo` of the next submit or skip: a skip has no command buffers */ struct SlotSubmit { - /** `StageSlot::prologue`, `StageSlot::primary` */ + /** `StageSlot::prologue`, `StageSlot::primary`, `StageSlot::epilogue` */ std::vector> cmdBuffers{}; // no queueWaits: the submit job awaits the marks of every wait, its append follows the @@ -76,11 +79,12 @@ struct SlotSubmit { ) const; /** - * adds the command buffers of the submit, the prologue first + * adds the command buffers of the submit, the prologue first, the epilogue last * @param[out] info gets the command buffers * @param prologue `false` -> without `StageSlot::prologue`: the prologue is empty + * @param epilogue `false` -> without `StageSlot::epilogue`: no image to present */ - void addCmdBuffers(SubmitInfo& info, bool prologue) const; + void addCmdBuffers(SubmitInfo& info, bool prologue, bool epilogue) const; /** * advances every wait and signal value to the next frame of the slot @@ -90,6 +94,20 @@ struct SlotSubmit { constexpr void next(size_t frameSlots); }; +/** + * the images of one queue in the presents of a submit job + * @see `StageSlot::presentImages` + */ +struct PresentGroup { + cth::ref_wrapper queue; ///< the queue of the surfaces of the images + + size_t first; ///< index of the first image in `StageSlot::presentImages` + size_t count; ///< of the images + + /** the present ran, also a failed one: the images resolve as presented, else dropped */ + bool presented = false; +}; + /** * the images and buffers of `Stage::retain()` in one frame * @details the submit job erases their graph states before it destroys them, see `StageGraph::erase()` @@ -166,15 +184,46 @@ struct StageSlot { /** the binary waits of `Stage::await()` in the frame of the slot, the submit job clears them */ std::vector extraBinaryWaits{}; + /** + * the presents of the frame of the slot, see `Stage::present()` + * @details the submit job presents them after the submit or drops them on a skip, then + * clears the list + */ + std::vector presents{}; + /** * the submit or the skip of the frame of the slot * @details * - the submit job fills it, see `SlotSubmit::skipInfo()` - * - one job at a time: `StageGraph::nextFrame()` hands out the slot again after the mark of - * the job + * - one job at a time: `StageGraph::nextFrame()` hands out the slot again after + * `StageSlot::submitDone` of the job */ SubmitInfo submitInfo{}; + // the scratch of the presents: the submit job refills them, they keep their capacity + /** the barriers of the presented images, recorded into `StageSlot::epilogue` */ + cvk::Barrier epilogueBarriers{}; + + /** per entry of `StageSlot::presents`: the state of its image before the epilogue */ + std::vector presentStates{}; + + /** the images of `StageSlot::presents`, the images of one queue in a row */ + std::vector presentImages{}; + + std::vector presentResults{}; ///< per entry of `StageSlot::presentImages` + + std::vector presentGroups{}; ///< one per queue of `StageSlot::presents` + + /** the present semaphores of a transfer to the queue family of a surface */ + std::vector presentSignals{}; + + /** + * frame number of the last job of the slot that ended its submit or skip and its presents + * @details `StageGraph::nextFrame()` awaits it before it hands out the slot again + * @details initial value: `StageGraph::firstFrameNumber() - 1` + */ + cth::co::counter_event submitDone; + /** the stage in the frame slot before, submits first */ cth::ref_wrapper previous; @@ -182,6 +231,9 @@ struct StageSlot { PrimaryCmdBuffer primary; + /** barriers of the presented images, submitted after the primary, see `Stage::present()` */ + PrimaryCmdBuffer epilogue; + std::vector secondaries{}; ///< `StageConfig::secondaries` of them /** @@ -324,6 +376,20 @@ class Stage { VkPipelineStageFlags2 stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT ); + /** + * presents the swapchain image of the present after the submit of this frame + * @details `Surface::acquire()` calls it for its present stage + * @details the submit job of the frame: + * - records the barrier of the image to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` into the epilogue, + * after the primary, see `StageSlot::epilogue` + * - presents the image after the submit, the images of one queue in one `vkQueuePresentKHR()` + * - a skip or a failed submit drops the image + * @param present of the image, the stage owns it until its job resolves it + * @pre `status()` is `UNSUBMITTED` + * @attention not thread safe + */ + void present(dev::PendingPresent present); + /** * submits the primary of the frame * @details calls `StageGraph::submit()` of the graph of the stage diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index 92dba174..f5de43bc 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -65,8 +65,7 @@ class StageGraph { * waits until the gpu finished the submits of every slot, destroys the slots * @details * - skips the unsubmitted stages first, e.g. after an exception in their recording: their waiters go on - * - the skip of an unsubmitted stage drops its binary waits: their semaphores, e.g. the acquire semaphores of a - * `Surface`, can be destroyed before the graph + * - the skip drops the presents of the stage, see `Surface::acquire()` * - waits for the end of every submit job * - a failed skip or wait does not stop the destruction * @attention blocks the calling thread: a worker of the core must be free for the jobs @@ -78,8 +77,9 @@ class StageGraph { /** * constructs the frame and its stages in the next slot * @details the frame before: skips its stages without `Stage::submit()` or `Stage::skip()`, warns for a waited one - * @details the old frame of the slot: awaits `Stage::submitted()` of its stages, then the - * stages: the gpu finished them, both with `cth::co::all()` + * @details the old frame of the slot: awaits `StageSlot::submitDone` of its stages: their jobs + * ended the submits and the presents, then the stages: the gpu finished them, both with + * `cth::co::all()` * @return the frame of the slot * @pre no stage of the frame before records or submits: `nextFrame()` ends the frame * @throws std::exception the first error of a submit job or a scope, stored before the call: an @@ -103,6 +103,8 @@ class StageGraph { * its last queue, the prologue acquires it * - waits for the stage waits of the config and the waits of `Stage::await()` * - signals `Stage::semaphore()` with `Stage::frameNumber()` + * - the images of `Stage::present()`: the epilogue after the primary transitions them, the + * presents follow the submit, see `Surface::acquire()` * - an error: skips, `nextFrame()` rethrows the error * - after the gpu finished: destroys the retained objects * @pre the stage is of this graph @@ -120,6 +122,7 @@ class StageGraph { * @details skip submit on the queue of the stage, no command buffers: * - waits for the stage waits of the config and the waits of `Stage::await()` * - signals `Stage::semaphore()` with `Stage::frameNumber()` + * @details drops the images of `Stage::present()`, see `Surface::acquire()` * @details after the gpu finished the skip submit: destroys the retained objects * @details a begun primary: ends its rendering and the primary, discards the recording * @pre the stage is of this graph @@ -204,9 +207,13 @@ class StageGraph { * of the slot, then `SlotSubmit::next()` * - `SUBMITTED`: `append()` of the states of the primary under `StageGraph::_statesMutex`, `release()` of the * release halves, records the prologue, an empty prologue: no record, the submit without it - * - `SUBMITTED`: `Queue::submit()` with the release waits, it marks the slot with the frame - * number - * - `SKIPPED` or a failed submit: `dev::skip_submit()` of the skip info + * - `SUBMITTED`: `presentBarriers()` under the same lock, records the epilogue, no presents: no + * record, the submit without it + * - `SUBMITTED`: `submitAndPresent()` with the release waits, the submit marks the slot with + * the frame number + * - `SKIPPED` or a failed submit: `dev::skip_submit()` of the skip info, then drops the + * presents after the gpu finished it + * - then sets `StageSlot::submitDone`: the job ended its use of the slot before the gpu wait * - on the workers of the core: after the gpu finished, erases the states of the retained resources, then * `Stasis::clear()` to `stasisEnd` * @details the errors: @@ -261,6 +268,37 @@ class StageGraph { release_map_t releases ); + /** + * fills `StageSlot::epilogueBarriers` with the barriers of the presented images + * @details per image of `StageSlot::presents`, from its state after all submits: + * - the queue of its surface has the family of the stage: to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` + * - another family: the release half towards the family of the surface + * @details stores the state before the barrier in `StageSlot::presentStates`, sets the state + * after it in `StageGraph::_states` + * @pre the caller holds `StageGraph::_statesMutex` + * @pre `append()` of the recording of the stage ran + */ + void presentBarriers(dev::StageSlot&); + + /** + * submits `StageSlot::submitInfo`, presents the images of `StageSlot::presents` after it + * @details the images grouped by the queues of their surfaces: + * - the queue of the stage: `Queue::present()` with the submit, one strand job + * - another queue of the family: the submit signals their present semaphores, then + * `Queue::present()` without a submit on that queue + * - another family: after the submit `Queue::transfer()` of the acquire halves on that queue, + * it signals the present semaphores, then the present, then the wait until the gpu finished + * the transfer: it waits for the semaphore of the slot + * @details the end: each image resolves with its result, an image without a present (failed + * transfer) drops after the gpu finished the submit, then clears `StageSlot::presents` + * @details a failed present or transfer: `StageGraph::_jobs` stores the error + * @throws std::exception reason: the submit failed, nothing is presented or resolved + */ + [[nodiscard]] cth::co::executor_task submitAndPresent( + dev::StageSlot&, + uint64_t frameNumber + ); + /** * removes the states and the last queues of the mip levels * @pre the caller holds `StageGraph::_statesMutex` diff --git a/jvk/incl/jvk/graph/surface.hpp b/jvk/incl/jvk/graph/surface.hpp index 67754bee..47644568 100644 --- a/jvk/incl/jvk/graph/surface.hpp +++ b/jvk/incl/jvk/graph/surface.hpp @@ -1,9 +1,7 @@ #pragma once #include "jvk/base/queue.hpp" -#include "jvk/cmd/cmd_buffer.hpp" +#include "jvk/graph/pending_present.hpp" #include "jvk/graph/swapchain.hpp" -#include "jvk/sync/resource_tracker.hpp" -#include "jvk/sync/semaphore.hpp" #include "cvk/render/sync/semaphore.hpp" #include "cvk/surface/surface.hpp" @@ -11,16 +9,12 @@ #include -#include -#include #include #include -#include #include #include #include -#include #include #include @@ -34,7 +28,6 @@ namespace jvk { class Core; class Stage; class StageGraph; -class scoped_acquire; } namespace jvk { @@ -42,7 +35,8 @@ namespace jvk { * acquired swapchain image * @details * - tracked like every image: the commands that use it record its accesses - * - valid until the end of its scope, see `scoped_acquire` + * - valid until the present stage of its acquire presented or dropped it, see + * `Surface::acquire()` */ struct SwapchainImage { cth::ref_wrapper image; @@ -58,9 +52,11 @@ struct SwapchainImage { */ struct SurfaceConfig { /** - * @details `cvk::SwapchainConfig::minImageCount` `0` -> `minImageCount` of the surface + `framesInFlight`: an - * image for each frame in flight beside the images of the presentation engine - * @pre `cvk::SwapchainConfig::queueFamilies.size() < 2`: the images stay `VK_SHARING_MODE_EXCLUSIVE` + * @details `cvk::SwapchainConfig::minImageCount` `0` -> `minImageCount` of the surface + + * `framesInFlight`: an image for each frame in flight beside the images of the presentation + * engine + * @pre `cvk::SwapchainConfig::queueFamilies.size() < 2`: the images stay + * `VK_SHARING_MODE_EXCLUSIVE` */ cvk::Swapchain::Config swapchain{}; @@ -75,17 +71,17 @@ struct SurfaceConfig { }; /** - * cvk surface with its swapchain, acquires and presents its images + * cvk surface with its swapchain, acquires its images for stages that present them * @details * - owns the cvk surface and the swapchain - * - recreates the swapchain in `acquire()`, a retired swapchain stays until its presents ended, see `Swapchain` - * - submits and presents in the strand of its queue, acquires outside the strand on `Queue::scheduler()` - * - `Surface::_presented` orders the uses of the swapchain: a present job sets it at its end, the - * next `acquire()` waits for it - * - one acquired image at a time, in a scope: `scoped_acquire` presents it at its end - * - an image without a present: the next `acquire()` or `destroy()` unacquires it, `acquire()` after the gpu finished - * its stage - * - the present jobs run detached, `destroy()` waits for them + * - recreates the swapchain in `acquire()`, a retired swapchain stays until its presents ended, see + * `Swapchain` + * - acquires outside the strand of its queue on `Queue::scheduler()` + * - the present stage of an image presents it after its submit, see `acquire()`: the surface has + * no jobs, the errors of the presents go to the graph of the present stage + * - one acquired image at a time: `acquire()` waits until the last image is presented or dropped + * - a dropped image: the next `acquire()` or `destroy()` unacquires it after the gpu finished its + * stages * @attention not thread safe */ class Surface { @@ -94,7 +90,7 @@ class Surface { /** * base constructor - * @details the queue presents and runs the present submits + * @details the queue presents the images * @pre the config passes `Config::debug_check()` */ Surface(Core const&, Queue const&, Config); @@ -111,33 +107,34 @@ class Surface { ~Surface() { optDestroy(); } /** - * takes the surface, creates the swapchain, the semaphores and the command buffers - * @details `cvk::Surface::extent()` `0` -> the first `acquire()` with an extent `> 0` creates the swapchain - * @details a failure destroys the parts and the surface + * takes the cvk surface, creates the swapchain and the acquire semaphores + * @details `cvk::Surface::extent()` `0` -> the first `acquire()` with an extent `> 0` creates + * the swapchain + * @details a failure destroys the parts and the cvk surface * @pre `Core::created()` * @pre `cvk::Surface::created()` - * @pre the queue can present to the surface + * @pre the queue can present to the cvk surface * @post `created()` * @note calls `optDestroy()` * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode - * @throws cvk::vk_result_exception result of a create of the swapchain, semaphores or command buffers + * @throws cvk::vk_result_exception result of a create of the swapchain or the semaphores */ void create(cvk::Surface); /** - * waits for the present jobs, destroys and forgets + * waits for the last image, destroys and forgets * @details - * - waits for the present jobs, then until the gpu finished the present submits - * - then unacquires an image without a present, e.g. after an exception: the earlier frames that used it ended - * - destroys the command buffers, the semaphores, the swapchain, then the surface + * - blocks until the last acquired image is presented or dropped + * - a dropped last image: blocks until the gpu finished its stages, then unacquires it + * - destroys the acquire semaphores, the swapchain, then the cvk surface * - a failed wait does not stop the destruction * @pre `created()` * @pre no `acquire()` is pending - * @pre every `scoped_acquire` ended - * @pre the graph of the presented stages and of the stage of an image without a present lives: the present jobs - * wait for its semaphores - * @pre a stage that waits for an acquire without a present: finished on the gpu, or unsubmitted until - * `~StageGraph()` + * @pre the present stage of the last image is submitted or skipped, or its graph is destroyed: + * else the wait never ends, e.g. destroy the graphs of the stages first + * @pre the submits that wait for the acquire semaphores finished on the gpu + * @attention blocks the calling thread: a worker of the core must be free for the jobs of the + * graph */ void destroy(); @@ -150,58 +147,66 @@ class Surface { } /** - * acquires the next swapchain image for the stage - * @details - * - adds the wait for the acquire to the stage: `Stage::await()` with the acquire semaphore and the stages - * - the state of the image in the graph of the stage: `VK_IMAGE_LAYOUT_UNDEFINED` with the wait stages, see + * acquires the next swapchain image, the present stage presents it after its submit + * @details the acquire stage: + * - waits for the acquire: `Stage::await()` with the acquire semaphore and the stages + * - the state of the image in its graph: `VK_IMAGE_LAYOUT_UNDEFINED` with the wait stages, see * `StageGraph::assume()`: the first barrier of the image chains with the wait - * - waits until the last present job ended: the acquire and the present share the - * swapchain, a blocking acquire before that present delays it by one refresh (FIFO) + * @details the present stage gets the present of the image, see `Stage::present()`: + * - its submit ends with the barrier of the image to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR`, from + * the state that the stages before left: the epilogue, after the primary + * - another queue family than the queue of the surface: the epilogue releases the image, the + * queue of the surface acquires it, see `Queue::transfer()` + * - after its submit: the present on the queue of the surface, one `vkQueuePresentKHR()` for + * the images of one queue + * - a failed present: the graph stores the error, `StageGraph::nextFrame()` rethrows it + * - a skip or a failed submit drops the image: the next `acquire()` unacquires it + * @details the surface: + * - waits until the last image is presented or dropped + * - a dropped last image: waits until the gpu finished its stages, then unacquires it + * - an out of date acquire or present, or a changed `cvk::Surface::extent()` -> recreates the + * swapchain first, erases the old images in the graph, see `StageGraph::erase()`, + * `Swapchain::recreate()` * - runs on `Queue::scheduler()`, outside the strand - * - an out of date acquire of the current swapchain, an out of date present, or a changed - * `cvk::Surface::extent()` -> recreates the swapchain first, erases the old images in the - * graph of the stage, see `StageGraph::erase()`, `Swapchain::recreate()` - * - an acquired image without a present, e.g. after an exception or a skip: waits until the gpu finished the - * submit or the skip of its stage, then unacquires it - * @param stages pipeline stages of the stage that wait for the acquire - * @return scope of the image, see `scoped_acquire`, no image -> surface extent `0`, no wait + * @param acquireStage waits for the acquire, the first use of the image + * @param presentStage presents the image after its submit + * @param stages pipeline stages of the acquire stage that wait for the acquire + * @return the image, `std::nullopt` -> surface extent `0`: no image, no wait, no present * @pre `created()` - * @pre `Stage::status()` is `UNSUBMITTED` - * @pre the `scoped_acquire` of the last acquire ended - * @pre an acquired image without a present of this frame: its stage is submitted or skipped + * @pre `Stage::status()` of both stages is `UNSUBMITTED` + * @pre both stages belong to one frame of one graph + * @pre the present stage is the acquire stage or waits for it in the frame, directly or through + * other stages, see `StageWait` + * @pre the present stage of the last image of this surface is submitted or skipped: else the + * wait never ends + * @pre the last use of the image before the present is on the queue family of the present stage * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode - * @throws cvk::vk_result_exception other result of `vkAcquireNextImageKHR()` or `vkCreateSwapchainKHR()` - * @throws std::exception the first error of a present job or a scope, stored before the call: - * an error of the last present job during the waits -> the next `acquire()` rethrows it, see - * `cth::co::catching_scope` - * @attention `vkAcquireNextImageKHR()` can block (FIFO: the vsync throttle): it occupies a driver thread, - * `CoreConfig::driverThreads` `0` -> the calling worker + * @throws cvk::vk_result_exception other result of `vkAcquireNextImageKHR()` or + * `vkCreateSwapchainKHR()` + * @attention `vkAcquireNextImageKHR()` can block (FIFO: the vsync throttle): it occupies a + * driver thread, `CoreConfig::driverThreads` `0` -> the calling worker * @see `Stage::await()` */ - [[nodiscard]] cth::co::executor_task acquire( - Stage&, + [[nodiscard]] cth::co::executor_task> acquire( + Stage& acquireStage, + Stage& presentStage, VkPipelineStageFlags2 stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT ); /** - * presents the acquired image after the submitted stage - * @details - * - returns at once, a job presents after the submit of the stage reached `vkQueueSubmit2()` - * - transitions the image to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` from its last state in the stage primary - * - a stage of another queue family: the job releases the image on the stage queue, the images stay - * `VK_SHARING_MODE_EXCLUSIVE` - * - `VK_ERROR_OUT_OF_DATE_KHR` -> the next `acquire()` recreates the swapchain - * - a failure of the job: the next `acquire()` rethrows it - * @pre an acquired image without a present - * @pre `Stage::status()` is `SUBMITTED` - * @pre the stage recording uses the image - * @pre the stage is the last use of the image in the frame or waits for the other uses - * @see `scoped_acquire` + * acquires the next swapchain image for one stage that uses and presents it + * @details calls @ref acquire(Stage&, Stage&, VkPipelineStageFlags2) with the stage for both */ - void present(Stage&); + [[nodiscard]] cth::co::executor_task> acquire( + Stage& stage, + VkPipelineStageFlags2 stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT + ) { + return acquire(stage, stage, stages); + } [[nodiscard]] constexpr bool created() const { return _surface.created(); } [[nodiscard]] constexpr Config const& config() const { return _config; } + [[nodiscard]] constexpr Queue const& queue() const { return *_queue; } /** * @details created once the surface extent is `> 0` @@ -213,104 +218,26 @@ class Surface { } private: - /** - * submit before the present of one swapchain image - * @details signals the present semaphore of the image - * @see `cvk::Swapchain::presentSemaphore()` - */ - struct PresentSubmit { - PrimaryCmdBuffer cmd; ///< the barrier of the image to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` - - /** - * value of `Surface::_semaphore` for the last submit of `PresentSubmit::cmd`, free once reached - */ - uint64_t value = 0; - }; - - /** - * acquired image without a present - * @details its stage waits for the acquire semaphore on the gpu: the unacquire waits until the gpu finished the - * submit or the skip of the stage - */ - struct AcquiredImage { - SwapchainImage image; - /** `Stage::semaphore()` of the stage of the acquire */ - cth::ref_wrapper stageSemaphore; - uint64_t frameNumber; ///< `Stage::frameNumber()`, the value of `stageSemaphore` to wait for - }; - - // no awaiter parameter: the job takes `submitted()` from the stage semaphore and the frame - // number - // the image as a parameter: the job reads no surface state outside of the strand - // `_presented` of the job before awaited: acquire() no longer orders the present jobs - /** - * present job of `present()` - * @details the order: - * - off the strand: awaits `Semaphore::submitted()` of the stage semaphore with the frame number - * - off the strand: awaits `Surface::_presented` of the job before: the present jobs run one - * at a time, in the order of `present()` - * - fills `Surface::_submitInfo`: the job before ended its use - * - stage of another family -> `Queue::transfer()` of the release half on the stage queue - * - off the strand: records the command buffer, the present jobs run one at a time - * - `Queue::present()` with the current swapchain: a recreation only happens in `acquire()`, - * after the last present - * - the submit waits for the semaphore of the stage and the release, signals - * `Surface::_semaphore` with the value, `Queue::present()` marks it after the present - * - the command buffer: the acquire half of another family, the transition to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` - * - `VK_ERROR_OUT_OF_DATE_KHR` of the present: sets `Surface::_outOfDate` before - * `Surface::_presented` - * - the last step, also after a failure: sets `Surface::_presented` to the value - * @details the errors: - * - a failed submit: stores the error, then `dev::skip_submit()` that signals only - * `Surface::_semaphore`, no present - * - a failed skip submit: `VK_ERROR_DEVICE_LOST` -> stores the error, marks, else terminates: - * the waiters would hang - * - a failed present: stores the error - * - before the end: every other failure terminates, the waiters on `Surface::_presented` - * would hang - * @param image the acquired image - * @param lastState of the image in the stage primary - * @param value of `Surface::_semaphore` for the submit - * @pre the command buffer of the submit belongs to the queue family of the queue - */ - [[nodiscard]] cth::co::executor_task presentJob( - Queue const& stageQueue, - Semaphore const& stageSemaphore, - uint64_t frameNumber, - SwapchainImage image, - ImageState lastState, - uint64_t value - ); - /** * creates or recreates the swapchain if it is not created, out of date or of another extent * @details * - the first creation: the config of `swapchainConfig()` - * - a recreation erases the old images in the graph first: the new images can reuse their handles - * - grows `Surface::_submits` to the image count + * - a recreation erases the old images in the graph first: the new images can reuse their + * handles * @param extent of the surface, `> 0` * @param graphPtr of the acquiring stage, `nullptr` -> no graph - * @pre no present job uses the swapchain: `create()`, or `acquire()` after the end of the last - * present job + * @pre no present uses the swapchain: `create()`, or `acquire()` after the last image resolved * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode * @throws cvk::vk_result_exception result of `vkCreateSwapchainKHR()` */ void updateSwapchain(VkExtent2D extent, StageGraph* graphPtr); /** - * @return `SurfaceConfig::swapchain`, `minImageCount` `0` -> `minImageCount` of the surface + `framesInFlight` + * @return `SurfaceConfig::swapchain`, `minImageCount` `0` -> `minImageCount` of the surface + + * `framesInFlight` */ [[nodiscard]] Swapchain::Config swapchainConfig() const; - /** - * gives the acquired image back to the current swapchain - * @pre an acquired image of the current swapchain - * @pre no present job uses the swapchain: `acquire()` after the end of the last present job, or - * `destroy()` - * @throws cvk::vk_result_exception result of `vkReleaseSwapchainImagesKHR()` - */ - void unacquireImage(); - cth::ref_wrapper _core; cth::ref_wrapper _queue; Config _config; @@ -318,7 +245,7 @@ class Surface { // destroyed after the swapchain cvk::Surface _surface; - /** created once the surface extent is `> 0`, `Surface::_presented` orders its uses */ + /** created once the surface extent is `> 0`, the resolve of the last image orders its uses */ Swapchain _swapchain; /** @@ -329,33 +256,13 @@ class Surface { /** the semaphore in `Surface::_acquireSemaphores` for the next acquire */ size_t _acquireSemaphoreIdx = 0; - Semaphore _semaphore; ///< signaled by the present submits, each submit signals the next value - - /** value of the last ended present job, `acquire()` and the next present job wait for it */ - cth::co::counter_event _presented{}; - - std::vector _submits{}; ///< one per swapchain image + /** written by the pending present of the last image, see `dev::PendingPresent` */ + dev::PresentState _presentState{}; - /** - * the submit of the present job that runs, `Surface::_presented` orders its uses - * @details each present job fills it: it keeps its capacity for the next jobs - */ - SubmitInfo _submitInfo{}; + /** value of the last acquired image in `PresentState::resolved`, `0` -> none */ + uint64_t _lastValue = 0; - /** the acquired image without a present */ - std::optional _acquiredOpt = std::nullopt; - - /** - * set by an out of date acquire and by the present jobs - * @details `acquire()` reads it after `Surface::_presented` reached the last present - */ - bool _outOfDate = false; - - /** - * the running present jobs, `destroy()` waits for them - * @details the first error of a job or a scope, `acquire()` rethrows it - */ - cth::co::catching_scope _jobs{}; + uint32_t _lastImageIdx = 0; ///< index of the last acquired image in the current swapchain public: Surface(Surface const& other) = delete; @@ -367,83 +274,6 @@ class Surface { }; } -namespace jvk { -/** - * acquired swapchain image of a stage for the scope, presents it at its end - * @details - * - `Surface::acquire()` returns it - * - end, by `Stage::status()`: `SUBMITTED` -> `Surface::present()`, also after an exception: the frame is complete - * - end, by `Stage::status()`: `SKIPPED` or `UNSUBMITTED` -> nothing, the next `Surface::acquire()` or - * `Surface::destroy()` unacquires the image - * - no image or a moved-from scope: nothing - * - a failure at the end, e.g. an allocation: the next `Surface::acquire()` rethrows it - * - `->` and `*` reach the image - * - declare it before the `scoped_submit` of the stage: the `scoped_submit` ends first and submits - * @attention a coroutine destroyed while suspended with the scope alive presents the image of a submitted stage - */ -class scoped_acquire { -public: - /** - * @param surface of the image - * @param stage of the acquire - * @param imageOpt `std::nullopt` -> no image - * @param jobs of the surface, gets a failure at the end - */ - scoped_acquire( - Surface& surface, - Stage& stage, - std::optional imageOpt, - cth::co::catching_scope& jobs - ) noexcept; - - ~scoped_acquire(); - - /** - * presents the image now, the end of the scope does nothing - * @details `Stage::status()` is `UNSUBMITTED` -> calls `Stage::submit()` first - * @pre an image - * @pre `Stage::status()` is not `SKIPPED` - * @pre the recording of the stage uses the image - * @see `Surface::present()` - */ - void present(); - - /** - * ends the scope without a present, the end of the scope does nothing - * @details the next `Surface::acquire()` or `Surface::destroy()` unacquires the image - * @pre an image - * @see `Surface::acquire()` - */ - void unacquire(); - - [[nodiscard]] constexpr explicit operator bool() const { return _imageOpt.has_value(); } - - /** - * @pre an image - */ - [[nodiscard]] constexpr SwapchainImage const* operator->() const { return &*_imageOpt; } - - /** - * @pre an image - */ - [[nodiscard]] constexpr SwapchainImage const& operator*() const { return *_imageOpt; } - -private: - cth::move_ptr _surfacePtr; ///< `nullptr` -> the end does nothing - cth::ref_wrapper _stage; - std::optional _imageOpt; - cth::ref_wrapper _jobs; ///< of the surface - -public: - scoped_acquire(scoped_acquire const& other) = delete; - scoped_acquire(scoped_acquire&& other) noexcept = default; - scoped_acquire& operator=(scoped_acquire const& other) = delete; - scoped_acquire& operator=(scoped_acquire&& other) = delete; - - static constexpr void debug_check(scoped_acquire const&); -}; -} - namespace jvk { constexpr void SurfaceConfig::debug_check(SurfaceConfig const& config) { CTH_CRITICAL(config.framesInFlight == 0, "framesInFlight must be > 0") {} @@ -457,12 +287,4 @@ constexpr void SurfaceConfig::debug_check(SurfaceConfig const& config) { constexpr void Surface::debug_check(Surface const& surface) { CTH_CRITICAL(!surface.created(), "surface must be created") {} } - -constexpr void scoped_acquire::debug_check(scoped_acquire const& image) { - CTH_CRITICAL( - !image._surfacePtr, - "the scope must hold the image, got a moved-from or ended scope" - ) {} - CTH_CRITICAL(!image._imageOpt.has_value(), "the scope must hold an image, got none") {} -} } diff --git a/jvk/src/graph/pending_present.cpp b/jvk/src/graph/pending_present.cpp new file mode 100644 index 00000000..cc410650 --- /dev/null +++ b/jvk/src/graph/pending_present.cpp @@ -0,0 +1,17 @@ +#include "jvk/graph/pending_present.hpp" + + +namespace jvk::dev { +void PresentState::present(uint64_t value, VkResult result) { + if(result == VK_ERROR_OUT_OF_DATE_KHR) + outOfDate = true; + dropped = false; + // the last write: Surface::acquire() reads the state after the wait for the value + resolved.set(value); +} + +void PresentState::drop(uint64_t value) { + dropped = true; + resolved.set(value); +} +} diff --git a/jvk/src/graph/stage.cpp b/jvk/src/graph/stage.cpp index b5dd968e..3e7db6bb 100644 --- a/jvk/src/graph/stage.cpp +++ b/jvk/src/graph/stage.cpp @@ -11,7 +11,6 @@ #include #include -#include #include #include #include @@ -52,9 +51,13 @@ void SlotSubmit::skipInfo( info.signals.push_back(signal); } -void SlotSubmit::addCmdBuffers(SubmitInfo& info, bool prologue) const { - // the prologue comes first - info.cmdBuffers.append_range(cmdBuffers | std::views::drop(prologue ? 0 : 1)); +void SlotSubmit::addCmdBuffers(SubmitInfo& info, bool prologue, bool epilogue) const { + // the order of SlotSubmit::cmdBuffers: the prologue, the primary, the epilogue + if(prologue) + info.cmdBuffers.push_back(cmdBuffers[0]); + info.cmdBuffers.push_back(cmdBuffers[1]); + if(epilogue) + info.cmdBuffers.push_back(cmdBuffers[2]); } StageSlot::StageSlot( @@ -73,11 +76,13 @@ StageSlot::StageSlot( heaps{stage_heaps(graph.core(), queue)}, semaphore{graph.core(), cvk::create, graph.firstFrameNumber() - 1}, slotSubmit{.signal = {.semaphore = semaphore, .value = graph.firstFrameNumber() + slot}}, + submitDone{graph.firstFrameNumber() - 1}, previous{*this}, prologue{graph.core(), queue.vk().familyIndex(), cvk::create}, primary{graph.core(), queue.vk().familyIndex(), cvk::create}, + epilogue{graph.core(), queue.vk().familyIndex(), cvk::create}, stasis{graph.core()} { - slotSubmit.cmdBuffers = {prologue, primary}; + slotSubmit.cmdBuffers = {prologue, primary, epilogue}; this->secondaries.reserve(secondaries); for(size_t i = 0; i < secondaries; ++i) @@ -142,6 +147,11 @@ void Stage::await(cvk::Semaphore const& binary, VkPipelineStageFlags2 stages) { _stageSlot->extraBinaryWaits.emplace_back(binary, stages); } +void Stage::present(dev::PendingPresent present) { + CTH_CRITICAL(_status != Status::UNSUBMITTED, "the stage must be unsubmitted") {} + _stageSlot->presents.push_back(std::move(present)); +} + void Stage::submit() { _stageSlot->graph->submit(*this); } void Stage::skip() { _stageSlot->graph->skip(*this); } diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index df3ff35c..2ddef82f 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -15,14 +15,18 @@ #include #include +#include #include #include +#include #include +#include #include #include namespace jvk { +using std::span; using std::vector; namespace { @@ -37,6 +41,12 @@ namespace { return maxOffset + 1; } + /** state of a presented image after the epilogue */ + constexpr ImageState PRESENT_STATE{ + .layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + .scope = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, + }; + /** * transition of the first use from `VK_IMAGE_LAYOUT_UNDEFINED`, no queue family ownership transfer * @details `src` waits for the stages of the first use, no access: like `cvk::layout_transition()` @@ -111,10 +121,7 @@ StageGraph::~StageGraph() { for(auto& stage : frameSlot.stages) { if(stage.status() != Stage::Status::UNSUBMITTED) continue; - // the binary waits dropped: a surface is destroyed before the graph, its present - // submits wait for the semaphores of the graph, the acquire semaphore of an unpresented - // image is destroyed already - stage._stageSlot->extraBinaryWaits.clear(); + // the skip drops the presents of the stage: the surfaces outlive the graph try { skip(stage); } catch(std::exception const& e) { JVK_STABLE_ERR( @@ -164,10 +171,15 @@ cth::co::executor_task StageGraph::nextFrame() { // a failed skip in an earlier nextFrame() leaves a stage of an older frame unsubmitted skipUnsubmitted(frameSlot); - // the marks first: the gpu can finish before the graph job marks the submit + // the jobs first: the gpu can finish before the job marks the submit, the job uses the + // slot until it ended its presents co_await cth::co::all( frameSlot.stages - | std::views::transform([](Stage const& stage) { return stage.submitted(); }) + | std::views::transform( + [](Stage const& stage) { + return stage._stageSlot->submitDone.wait(stage.frameNumber()); + } + ) ); co_await cth::co::all(frameSlot.stages); } @@ -318,21 +330,30 @@ cth::co::executor_task StageGraph::submitJob( { std::scoped_lock const lock{_statesMutex}; append(stageSlot.primary.states(), queue, prologue, releases); + // after the append: the states that the stages before and this one left + presentBarriers(stageSlot); } // the skip of a failed submit waits for the releases too if(!releases.empty()) info.waits.append_range(co_await release(std::move(releases))); - // off the strand: the prologue belongs to the job of the slot, an empty one stays out of the submit + // off the strand: the prologue and the epilogue belong to the job of the slot, an empty + // one stays out of the submit bool const withPrologue = !prologue.empty(); if(withPrologue) { stageSlot.prologue.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); prologue.execute(stageSlot.prologue); stageSlot.prologue.end(); } + bool const withEpilogue = !stageSlot.epilogueBarriers.empty(); + if(withEpilogue) { + stageSlot.epilogue.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); + stageSlot.epilogueBarriers.execute(stageSlot.epilogue); + stageSlot.epilogue.end(); + } - slotSubmit.addCmdBuffers(info, withPrologue); - co_await queue.submit(info); + slotSubmit.addCmdBuffers(info, withPrologue, withEpilogue); + co_await submitAndPresent(stageSlot, frameNumber); submitted = true; } // the job goes on with the skip @@ -345,11 +366,24 @@ cth::co::executor_task StageGraph::submitJob( // hang auto skip = [&]() noexcept { info.cmdBuffers.clear(); + // the present semaphores of a failed submit: no present waits for them + info.binarySignals.clear(); return dev::skip_submit(queue, info, _jobs); }(); co_await std::move(skip); + + // the presents of the skip: dropped after the gpu finished it, the next acquire of each + // surface unacquires its image at once + if(!stageSlot.presents.empty()) { + try { co_await stageSlot.semaphore.wait(frameNumber); } + catch(...) { _jobs.store(std::current_exception()); } + stageSlot.presents.clear(); + } } + // the last use of the slot by the job before the gpu wait: nextFrame() hands it out after it + stageSlot.submitDone.set(frameNumber); + // after the mark: a failed gpu wait escapes, _jobs stores it, the retained objects stay for // the destruction of the graph // the job never touches the stage: nextFrame() destroys the stages after the gpu wait @@ -450,6 +484,177 @@ void StageGraph::append( _bufferQueues.insert_or_assign(vkBuffer, cth::ref_wrapper{queue}); } +void StageGraph::presentBarriers(dev::StageSlot& stageSlot) { + auto const family = stageSlot.queue->vk().familyIndex(); + auto& barriers = stageSlot.epilogueBarriers; + barriers.clear(); + stageSlot.presentStates.clear(); + + for(auto const& present : stageSlot.presents) { + cvk::Image const& image = present.swapchainImage(); + // Surface::acquire() assumed the image: it has a state + auto const lastOpt = _states.last(image.get(), 0); + CTH_CRITICAL(!lastOpt.has_value(), "the presented image must have a state") {} + + auto const presentFamily = present.queue().vk().familyIndex(); + if(presentFamily == family) + barriers.add( + image.get(), + image.aspectMask(), + cvk::ImageBarrierInfo{ + .src = lastOpt->scope, + .dst = PRESENT_STATE.scope, + .newLayout = PRESENT_STATE.layout, + .oldLayout = lastOpt->layout, + } + ); + else + barriers.add( + image.get(), + image.aspectMask(), + dev::release_half(*lastOpt, PRESENT_STATE, family, presentFamily, 0) + ); + + stageSlot.presentStates.push_back(*lastOpt); + _states.assume(image, PRESENT_STATE); + } +} + +cth::co::executor_task StageGraph::submitAndPresent( + dev::StageSlot& stageSlot, + uint64_t frameNumber +) { + auto& info = stageSlot.submitInfo; + auto const& queue = *stageSlot.queue; + auto const family = queue.vk().familyIndex(); + auto& presents = stageSlot.presents; + auto& images = stageSlot.presentImages; + auto& results = stageSlot.presentResults; + auto& groups = stageSlot.presentGroups; + + // the images of one queue in a row, the queue of the stage first: its present follows the + // submit in one strand job + images.clear(); + groups.clear(); + auto const addGroup = [&](Queue const& groupQueue) { + auto const first = images.size(); + for(auto const& present : presents) + if(&present.queue() == &groupQueue) + images.push_back(present.image()); + groups.push_back({.queue = groupQueue, .first = first, .count = images.size() - first}); + }; + auto const queueOf = [](dev::PendingPresent const& present) { return &present.queue(); }; + if(std::ranges::contains(presents, &queue, queueOf)) + addGroup(queue); + for(auto it = presents.begin(); it != presents.end(); ++it) { + auto const* queuePtr = &it->queue(); + // the first present of a queue opens its group + if(queuePtr != &queue && !std::ranges::contains(presents.begin(), it, queuePtr, queueOf)) + addGroup(*queuePtr); + } + results.assign(images.size(), VK_ERROR_UNKNOWN); + + // another queue of the family: the submit of the stage signals the present semaphores + for(auto const& group : groups) + if(&*group.queue != &queue && group.queue->vk().familyIndex() == family) + for(auto const& [swapchain, imageIdx] : span{images}.subspan(group.first, group.count)) + info.binarySignals.emplace_back(swapchain->presentSemaphore(imageIdx)); + + bool const ownGroup = !groups.empty() && &*groups.front().queue == &queue; + try { + if(ownGroup) { + auto const& own = groups.front(); + co_await queue.present( + info, + span{images}.subspan(own.first, own.count), + span{results}.subspan(own.first, own.count) + ); + } else + co_await queue.submit(info); + } + catch(...) { + // a failed submit marks nothing: the caller skips, the presents stay pending + if(stageSlot.semaphore.submittedValue() < frameNumber) + throw; + // a failed present after the submit: the images resolve with their results + _jobs.store(std::current_exception()); + } + if(ownGroup) + groups.front().presented = true; + + // the presents on other queues after the submit + SemaphoreSubmitInfo const submitted{.semaphore = stageSlot.semaphore, .value = frameNumber}; + for(auto& group : groups) { + auto const& groupQueue = *group.queue; + if(&groupQueue == &queue) + continue; + + try { + // another family: the queue of the surfaces acquires the images, the transfer signals + // their present semaphores + auto const groupFamily = groupQueue.vk().familyIndex(); + std::optional transferredOpt = std::nullopt; + if(groupFamily != family) { + cvk::Barrier acquire{}; + auto& signals = stageSlot.presentSignals; + signals.clear(); + for(size_t presentIdx = 0; presentIdx < presents.size(); ++presentIdx) { + auto const& present = presents[presentIdx]; + if(&present.queue() != &groupQueue) + continue; + cvk::Image const& image = present.swapchainImage(); + acquire.add( + image.get(), + image.aspectMask(), + dev::acquire_half( + stageSlot.presentStates[presentIdx], + PRESENT_STATE, + family, + groupFamily, + 0 + ) + ); + auto const [swapchain, imageIdx] = present.image(); + signals.emplace_back(swapchain->presentSemaphore(imageIdx)); + } + std::array const waits{submitted}; + transferredOpt = co_await groupQueue.transfer(std::move(acquire), waits, signals); + } + + group.presented = true; + co_await groupQueue.present( + span{images}.subspan(group.first, group.count), + span{results}.subspan(group.first, group.count) + ); + + // the transfer waits for the semaphore of the slot: ~StageGraph() destroys it after + // the jobs ended + if(transferredOpt.has_value()) + co_await transferredOpt->semaphore->wait(transferredOpt->value); + } + // a failed transfer drops the images of the queue, a failed present presented them + catch(...) { _jobs.store(std::current_exception()); } + } + + // each image of a group resolves with its result, in the order of the group + for(auto const& group : groups) { + if(!group.presented) + continue; + auto resultIdx = group.first; + for(auto& present : presents) + if(&present.queue() == &*group.queue) + present.present(results[resultIdx++]); + } + + // the images of a failed transfer: dropped after the gpu finished the submit, the clear drops + // them + if(std::ranges::any_of(groups, [](auto const& group) { return !group.presented; })) { + try { co_await stageSlot.semaphore.wait(frameNumber); } + catch(...) { _jobs.store(std::current_exception()); } + } + presents.clear(); +} + cth::co::executor_task> StageGraph::release(release_map_t releases) { vector waits{}; waits.reserve(releases.size()); diff --git a/jvk/src/graph/surface.cpp b/jvk/src/graph/surface.cpp index 2b763e11..1b76d448 100644 --- a/jvk/src/graph/surface.cpp +++ b/jvk/src/graph/surface.cpp @@ -4,18 +4,13 @@ #include "jvk/base/queue.hpp" #include "jvk/graph/stage.hpp" #include "jvk/graph/stage_graph.hpp" -#include "jvk/sync/family_transfer.hpp" #include "jvk/utility/exception.hpp" #include "cvk/base/core.hpp" -#include "cvk/base/queue/submit_info.hpp" #include "cvk/data/img/image.hpp" -#include "cvk/render/sync/barrier.hpp" -#include "cvk/render/sync/timeline_semaphore.hpp" #include "cvk/utility/vk_exceptions.hpp" -#include "cvk/utility/vk_overloads.hpp" -#include +#include #include #include @@ -25,13 +20,21 @@ namespace jvk { +namespace { + /** + * waits until the counter reaches the value + */ + cth::co::executor_task await_value(cth::co::counter_event const& event, uint64_t value) { + co_await event.wait(value); + } +} + Surface::Surface(Core const& core, Queue const& queue, Config config) : _core{core}, _queue{queue}, _config{std::move(config)}, _surface{static_cast(core).instance()}, - _swapchain{core, queue.vk(), _surface}, - _semaphore{core} { Config::debug_check(_config); } + _swapchain{core, queue.vk(), _surface} { Config::debug_check(_config); } Surface::Surface(Core const& core, Queue const& queue, Config config, cvk::Surface surface) : Surface{core, queue, std::move(config)} { create(std::move(surface)); } @@ -45,7 +48,6 @@ void Surface::create(cvk::Surface surface) { cvk::Core const& vkCore = *_core; try { - _semaphore.create(); _acquireSemaphores.reserve(_config.framesInFlight); for(uint32_t i = 0; i < _config.framesInFlight; ++i) _acquireSemaphores.emplace_back(vkCore, cvk::create); @@ -63,81 +65,62 @@ void Surface::create(cvk::Surface surface) { void Surface::destroy() { debug_check(*this); - _jobs.wait(); + // the job of the present stage resolves the last image + if(_presentState.resolved.value() < _lastValue) + _core->executor().sync_wait(await_value(_presentState.resolved, _lastValue)); - // a failed wait leaves the gpu work, the destruction goes on - if(_semaphore.created()) { - try { - cvk::TimelineSemaphore const& semaphore = _semaphore; - semaphore.wait(_semaphore.value()); - } - catch(cvk::vk_result_exception const& e) { - JVK_STABLE_ERR( - true, - "failed to wait for the present submits in destroy(), got {}", - e.vkResult() - ) {} - } - } - - // after the wait for the present submits: the earlier frames that used the image ended on the - // gpu (VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786), the stage of the image is under - // the @pre - // no job runs, no acquire is pending: nothing else uses the swapchain - if(_acquiredOpt.has_value()) { - try { unacquireImage(); } + // the drop resolved after the gpu finished the stages of the image: + // VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786 + if(_presentState.dropped) { + // a failed unacquire does not stop the destruction + try { _swapchain.current().unacquire(std::array{_lastImageIdx}); } catch(cvk::vk_result_exception const& e) { JVK_STABLE_ERR( true, "failed to unacquire the swapchain image in destroy(), got {}", e.vkResult() ) {} - _acquiredOpt.reset(); } } - _submits.clear(); _acquireSemaphores.clear(); - _semaphore.optDestroy(); - // the semaphore starts at 0 again - _presented = cth::co::counter_event{}; _swapchain.optDestroy(); _surface.destroy(); + // the counter starts at 0 again + _presentState = dev::PresentState{}; + _lastValue = 0; + _lastImageIdx = 0; _acquireSemaphoreIdx = 0; - _outOfDate = false; - // after _jobs.wait(): no job stores anymore - _jobs.clear(); } -cth::co::executor_task Surface::acquire( - Stage& stage, +cth::co::executor_task> Surface::acquire( + Stage& acquireStage, + Stage& presentStage, VkPipelineStageFlags2 stages ) { - if(_jobs.failed()) - _jobs.rethrow(); - debug_check(*this); - CTH_CRITICAL(stage.status() != Stage::Status::UNSUBMITTED, "the stage must be unsubmitted") {} CTH_CRITICAL( - _acquiredOpt.has_value() && _acquiredOpt->frameNumber == stage.frameNumber() - && _acquiredOpt->stageSemaphore->submittedValue() < _acquiredOpt->frameNumber, - "a second acquire in frame {}: submit or skip the stage of the first image first", - stage.frameNumber() + acquireStage.status() != Stage::Status::UNSUBMITTED + || presentStage.status() != Stage::Status::UNSUBMITTED, + "the acquire stage and the present stage must be unsubmitted" + ) {} + CTH_CRITICAL( + &acquireStage.graph() != &presentStage.graph() + || acquireStage.frameNumber() != presentStage.frameNumber(), + "the acquire stage and the present stage must belong to one frame of one graph" ) {} - // present N before acquire N + 1: the acquire and the present share the swapchain - // (externally synchronized), a blocking acquire would delay the present (FIFO), the flag of - // the present is final - co_await _presented.wait(_semaphore.value()); - // the unacquire needs the gpu done with its stage: VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786 - if(_acquiredOpt.has_value()) - co_await _acquiredOpt->stageSemaphore->wait(_acquiredOpt->frameNumber); - // outside the strand: the ends of the present jobs order the swapchain uses + // the last image first: the acquire and the present share the swapchain (externally + // synchronized), a blocking acquire before that present would delay it (FIFO) + co_await _presentState.resolved.wait(_lastValue); + // outside the strand: the resolve of the last image orders the swapchain uses co_await cth::co::executor{_queue->scheduler()}.schedule(); - if(_acquiredOpt.has_value()) - unacquireImage(); + // the drop resolved after the gpu finished the stages of the image: + // VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786 + if(std::exchange(_presentState.dropped, false)) + _swapchain.current().unacquire(std::array{_lastImageIdx}); cvk::Core const& vkCore = *_core; std::optional imageIdxOpt = std::nullopt; @@ -146,17 +129,17 @@ cth::co::executor_task Surface::acquire( while(!imageIdxOpt.has_value()) { auto const extent = _surface.extent(vkCore.physicalDevice()); if(extent.width == 0 || extent.height == 0) - co_return scoped_acquire{*this, stage, std::nullopt, _jobs}; - updateSwapchain(extent, &stage.graph()); + co_return std::nullopt; + updateSwapchain(extent, &acquireStage.graph()); // no image -> out of date, the next round recreates the swapchain imageIdxOpt = _swapchain.acquire(acquireSemaphore).imageIndex; if(!imageIdxOpt.has_value()) - _outOfDate = true; + _presentState.outOfDate = true; } auto const imageIdx = *imageIdxOpt; - auto const& swapchain = _swapchain.current(); + auto& swapchain = _swapchain.current(); SwapchainImage const image{ .image = swapchain.image(imageIdx), .view = swapchain.view(imageIdx), @@ -164,156 +147,25 @@ cth::co::executor_task Surface::acquire( .extent = swapchain.extent(), }; _acquireSemaphoreIdx = (_acquireSemaphoreIdx + 1) % _config.framesInFlight; - _acquiredOpt = AcquiredImage{ - .image = image, - .stageSemaphore = stage.semaphore(), - .frameNumber = stage.frameNumber(), - }; + _lastImageIdx = imageIdx; + auto const value = ++_lastValue; // the first barrier of the image chains with the wait for the acquire - stage.await(acquireSemaphore, stages); - stage.graph().assume( + acquireStage.await(acquireSemaphore, stages); + acquireStage.graph().assume( *image.image, ImageState{.layout = VK_IMAGE_LAYOUT_UNDEFINED, .scope = {.stages = stages}} ); - co_return scoped_acquire{*this, stage, image, _jobs}; -} - -void Surface::present(Stage& stage) { - debug_check(*this); - CTH_CRITICAL(!_acquiredOpt.has_value(), "the surface must have an acquired image") {} - CTH_CRITICAL(stage.status() != Stage::Status::SUBMITTED, "the stage must be submitted") {} - - auto const image = _acquiredOpt->image; - auto const lastOpt = stage.primary().states().last(image.image->get(), 0); - CTH_CRITICAL( - !lastOpt.has_value(), - "the stage recording must use the swapchain image {}", - image.imageIdx - ) {} - - // the counter after the detach: a failed allocation leaves no value that nobody signals - auto const value = _semaphore.value() + 1; - _core->executor().detach( - _jobs, - presentJob(stage.queue(), stage.semaphore(), stage.frameNumber(), image, *lastOpt, value) - ); - static_cast(_semaphore.next()); - _acquiredOpt.reset(); -} - -cth::co::executor_task Surface::presentJob( - Queue const& stageQueue, - Semaphore const& stageSemaphore, - uint64_t frameNumber, - SwapchainImage image, - ImageState lastState, - uint64_t value -) { - auto const& queue = *_queue; - auto const stageFamily = stageQueue.vk().familyIndex(); - auto const family = queue.vk().familyIndex(); - bool const otherFamily = stageFamily != family; - auto const vkImage = image.image->get(); - auto const aspectMask = image.image->aspectMask(); - - // off the strand: a wait before the signal on one queue would block it, the release needs the submit of the stage, - // the next acquire() sets the state of the image in the graph after the submit job of the stage appended its states - co_await stageSemaphore.submitted(frameNumber); - // the present jobs run one at a time, also a failed one: the job before ended, it wrote the - // values of the command buffers, signaled the value before and wrote the flag - co_await _presented.wait(value - 1); - - // after the job before: it used the info until its end - // noexcept: without the wait and the signal no skip submit signals the value, the waiters - // would hang - auto& info = _submitInfo; - [&]() noexcept { - info.clear(); - info.waits.push_back({.semaphore = stageSemaphore, .value = frameNumber}); - info.signals.push_back({.semaphore = _semaphore, .value = value}); - }(); + // a failure drops the image at once, no stage submitted a use of it: the next acquire + // unacquires it + presentStage.present(dev::PendingPresent{_presentState, value, *_queue, swapchain, imageIdx}); - try { - ImageState const presentState{ - .layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - .scope = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, - }; - - cvk::Barrier barrier{}; - if(otherFamily) { - cvk::Barrier release{}; - release.add( - vkImage, - aspectMask, - dev::release_half(lastState, presentState, stageFamily, family, 0) - ); - info.waits.push_back(co_await stageQueue.transfer(std::move(release))); - - barrier.add( - vkImage, - aspectMask, - dev::acquire_half(lastState, presentState, stageFamily, family, 0) - ); - } else - barrier.add( - vkImage, - aspectMask, - cvk::ImageBarrierInfo{ - .src = lastState.scope, - .dst = presentState.scope, - .newLayout = presentState.layout, - .oldLayout = lastState.layout, - } - ); - - // the last submit of the command buffer, a swapchain before a recreation used it too - co_await _semaphore.wait(_submits[image.imageIdx].value); - - // off the strand: the present jobs run one at a time, the end of the job before orders them - auto& submit = _submits[image.imageIdx]; - submit.cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); - barrier.execute(submit.cmd); - submit.cmd.end(); - // before the submit: the skip submit of a failed one signals the value too - submit.value = value; - info.cmdBuffers.push_back(submit.cmd); - - // the swapchain of the image is the current one: a recreation only happens in acquire(), - // after the end of the last present job - std::array const images{ - PresentImage{.swapchain = _swapchain.current(), .imageIdx = image.imageIdx} - }; - std::array results{}; - co_await queue.present(info, images, results); - auto const result = results[0]; - // before _presented.set(): the next acquire() reads it - if(result == VK_ERROR_OUT_OF_DATE_KHR) - _outOfDate = true; - } - // the job goes on with the skip submit and _presented.set() - catch(...) { _jobs.store(std::current_exception()); } - - // a failed submit marks nothing: the skip submit signals the value for the waits on the - // surface - if(_semaphore.submittedValue() < value) { - // noexcept: a failed start of the skip submit leaves the value unmarked, the waiters would - // hang - auto skip = [&]() noexcept { - info.cmdBuffers.clear(); - return dev::skip_submit(queue, info, _jobs); - }(); - co_await std::move(skip); - } - - // the last step, also after a failure: nothing before it escapes, the waiters would hang - // one set() at a time, rising: the next job waits for this value - _presented.set(value); + co_return image; } void Surface::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { - if(_swapchain.created() && !_outOfDate && _swapchain.current().extent() == extent) + if(_swapchain.created() && !_presentState.outOfDate && _swapchain.current().extent() == extent) return; if(_swapchain.created()) { @@ -324,12 +176,7 @@ void Surface::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { _swapchain.recreate(extent); } else _swapchain.create(swapchainConfig(), extent); - _outOfDate = false; - - while(_submits.size() < _swapchain.current().imageCount()) - _submits.push_back( - PresentSubmit{.cmd = PrimaryCmdBuffer{*_core, _queue->vk().familyIndex(), cvk::create}} - ); + _presentState.outOfDate = false; } Swapchain::Config Surface::swapchainConfig() const { @@ -342,52 +189,4 @@ Swapchain::Config Surface::swapchainConfig() const { _surface.capabilities(vkCore.physicalDevice()).minImageCount + _config.framesInFlight; return config; } - -void Surface::unacquireImage() { - _swapchain.current().unacquire(std::array{_acquiredOpt->image.imageIdx}); - _acquiredOpt.reset(); -} -} - -namespace jvk { -scoped_acquire::scoped_acquire( - Surface& surface, - Stage& stage, - std::optional imageOpt, - cth::co::catching_scope& jobs -) noexcept : - _surfacePtr{&surface}, - _stage{stage}, - _imageOpt{std::move(imageOpt)}, - _jobs{jobs} {} - -scoped_acquire::~scoped_acquire() { - if(!_surfacePtr || !_imageOpt.has_value()) - return; - - auto& stage = *_stage; - // skipped or unsubmitted: the next acquire() or destroy() unacquires the image - if(stage.status() != Stage::Status::SUBMITTED) - return; - - // a destructor does not throw and is no task: it stores the failure, the next acquire() - // rethrows - try { _surfacePtr->present(stage); } - catch(...) { _jobs->store(std::current_exception()); } -} - -void scoped_acquire::present() { - debug_check(*this); - CTH_CRITICAL(_stage->status() == Stage::Status::SKIPPED, "the stage must not be skipped") {} - - if(_stage->status() == Stage::Status::UNSUBMITTED) - _stage->submit(); - _surfacePtr.release()->present(*_stage); -} - -void scoped_acquire::unacquire() { - debug_check(*this); - // the next acquire() or destroy() unacquires the image - static_cast(_surfacePtr.release()); -} } diff --git a/jvk/tests/src/graph/surface_test.cpp b/jvk/tests/src/graph/surface_test.cpp index 371ccee7..aa446d6a 100644 --- a/jvk/tests/src/graph/surface_test.cpp +++ b/jvk/tests/src/graph/surface_test.cpp @@ -71,10 +71,25 @@ namespace { return core.executor().sync_wait(graph.nextFrame()); } - [[nodiscard]] scoped_acquire acquire(Core const& core, Surface& surface, Stage& stage) { + [[nodiscard]] std::optional acquire( + Core const& core, + Surface& surface, + Stage& stage + ) { return core.executor().sync_wait(surface.acquire(stage, ATTACHMENT_OUTPUT)); } + [[nodiscard]] std::optional acquire( + Core const& core, + Surface& surface, + Stage& acquireStage, + Stage& presentStage + ) { + return core.executor().sync_wait( + surface.acquire(acquireStage, presentStage, ATTACHMENT_OUTPUT) + ); + } + cth::co::executor_task await_stage(Stage const& stage) { co_await stage; } /** @@ -161,8 +176,8 @@ namespace { } /** - * acquires and clears the image of the stage, the scopes submit and present - * @details the submit job waits for the gate, the present job for the submit: the present stays pending + * acquires and clears the image of the stage, the scope submits, the job presents + * @details the submit job waits for the gate: the present stays pending * @return the image */ SwapchainImage present_behind_gate( @@ -209,7 +224,7 @@ namespace { /** * acquires the image of the next frame, clears the multisampled target and resolves it into the image - * @details only the scopes: `scoped_submit` submits, then `scoped_acquire` presents + * @details only the scope: `scoped_submit` submits, the job presents * @details a new extent: the stage retains the old target, then a new one * @param[out] msaaOpt the target of the frames * @return the image @@ -251,7 +266,7 @@ namespace { /** * acquires, clears and presents the image of the stage in the next frame - * @details only the scopes: `scoped_submit` submits, then `scoped_acquire` presents + * @details only the scope: `scoped_submit` submits, the job presents * @details the acquire comes before `Stage::begin()` * @return the image */ @@ -263,6 +278,50 @@ namespace { clear(*primary, *image); return *image; } + + /** + * the scene stage clears the image, the ui stage draws over it and presents + * @details the ui stage waits for the scene stage in the frame + */ + StageGraph::Config scene_and_ui(size_t uiQueueIdx = 0) { + return {.stages = {{.queueIdx = 0}, {.queueIdx = uiQueueIdx, .waits = {{.stageId = 0}}}}}; + } + + constexpr size_t SCENE = 0; + constexpr size_t UI = 1; + + /** + * the scene stage clears the image, the ui stage loads and clears its upper half, the ui stage + * presents + * @return the image + */ + SwapchainImage present_scene_and_ui(Core const& core, StageGraph& graph, Surface& surface) { + auto& frame = next_frame(core, graph); + auto const image = acquire(core, surface, frame[SCENE], frame[UI]); + EXPECT_TRUE(image); + { + auto const scene = frame[SCENE].begin(); + clear(*scene, *image); + } + { + auto const ui = frame[UI].begin(); + auto const rendering = ui->beginRendering( + { + .colorAttachments = { + { + .view = image->view, + .loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, + } + }, + .area = VkRect2D{ + .offset = {0, 0}, + .extent = {image->extent.width, image->extent.height / 2}, + }, + } + ); + } + return *image; + } } JVK_TEST(Surface, frame_loop_clears_and_presents) { @@ -274,8 +333,9 @@ JVK_TEST(Surface, frame_loop_clears_and_presents) { GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; + // before the graph: the presents of the graph refer to the surface Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; ASSERT_TRUE(surface.created()); ASSERT_TRUE(surface.swapchain().created()); @@ -284,7 +344,21 @@ JVK_TEST(Surface, frame_loop_clears_and_presents) { EXPECT_EQ(image.extent, test::HEADLESS_EXTENT); EXPECT_LT(image.imageIdx, surface.swapchain().current().imageCount()); } +} + +JVK_TEST(Surface, destroy_waits_for_the_present_of_the_last_image) { + test::Context const context{}; + auto windowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, windowSurface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + { + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; + present_frame(core, graph, surface); + } surface.destroy(); EXPECT_FALSE(surface.created()); } @@ -298,8 +372,8 @@ JVK_TEST(Surface, frame_loop_with_driver_threads_presents) { GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; for(size_t i = 0; i < FRAMES; ++i) EXPECT_EQ(present_frame(core, graph, surface).extent, test::HEADLESS_EXTENT); @@ -317,15 +391,15 @@ JVK_TEST(Surface, extent_0_gives_no_image_until_the_extent_is_larger) { GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; EXPECT_FALSE(surface.swapchain().created()); - // no image, no wait: the stage submits without the image, the scoped_acquire does nothing + // no image, no wait, no present: the stage submits without the image auto& stage = next_frame(core, graph).stage(0); { auto const image = acquire(core, surface, stage); - EXPECT_FALSE(image); + EXPECT_FALSE(image.has_value()); auto const primary = stage.begin(); } EXPECT_EQ(stage.status(), Stage::Status::SUBMITTED); @@ -348,8 +422,8 @@ JVK_TEST(Surface, new_extent_recreates_the_swapchain) { GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; EXPECT_EQ(present_frame(core, graph, surface).extent, (VkExtent2D{32, 32})); @@ -374,8 +448,8 @@ JVK_TEST(Surface, multisampled_frames_resolve_into_the_image_and_present) { // before the graph: the target lives until the gpu finished the frames std::optional msaaOpt{}; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; // the resolve writes the image, the present transition starts from the resolve state for(size_t i = 0; i < FRAMES; ++i) @@ -400,8 +474,8 @@ JVK_TEST(Surface, recreation_retains_the_multisampled_target_of_the_old_extent) GTEST_SKIP() << "no 4x msaa for color attachments"; std::optional msaaOpt{}; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; EXPECT_EQ(present_msaa_frame(core, graph, surface, msaaOpt).extent, (VkExtent2D{32, 32})); @@ -423,14 +497,14 @@ JVK_TEST(Surface, acquire_waits_for_the_present_before) { GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Semaphore const gate{core, cvk::create}; auto& first = next_frame(core, graph).stage(0); present_behind_gate(core, first, surface, gate); - // the present of the first frame waits for the mark of the gate, the next acquire for the present + // the job of the first frame waits for the mark of the gate, the next acquire for its present auto& second = next_frame(core, graph).stage(0); std::binary_semaphore acquiredSignal{0}; size_t acquiredImages = 0; @@ -473,8 +547,8 @@ JVK_TEST(Surface, recreation_retires_the_old_swapchain_until_its_presents_ended) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; EXPECT_EQ(present_frame(core, graph, surface).extent, (VkExtent2D{32, 32})); @@ -489,42 +563,6 @@ JVK_TEST(Surface, recreation_retires_the_old_swapchain_until_its_presents_ended) EXPECT_EQ(surface.swapchain().retired(), 0); } -JVK_TEST(Surface, scope_unacquire_leaves_the_image_to_the_next_acquire) { - test::Context const context{}; - auto windowSurface = test::headless_surface(context.instance); - std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, windowSurface)) - GTEST_SKIP() << "no device presents to a headless surface"; - auto& core = *coreOpt; - - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; - - auto& stage = next_frame(core, graph).stage(0); - { - auto image = acquire(core, surface, stage); - ASSERT_TRUE(image); - image.unacquire(); - - // the submit waits for the acquire semaphore - auto const primary = stage.begin(); - } - // the scoped_acquire did nothing at its end, the image stays acquired - EXPECT_EQ(acquired_images(surface), 1); - - // the next acquire waits for the stage on the gpu and gives the image back first - auto& next = next_frame(core, graph).stage(0); - { - auto const image = acquire(core, surface, next); - ASSERT_TRUE(image); - EXPECT_EQ(acquired_images(surface), 1); - auto const primary = next.begin(); - clear(*primary, *image); - } - - present_frame(core, graph, surface); -} - JVK_TEST(Surface, next_acquire_after_a_skipped_stage_unacquires_the_image) { test::Context const context{}; auto windowSurface = test::headless_surface(context.instance); @@ -533,18 +571,18 @@ JVK_TEST(Surface, next_acquire_after_a_skipped_stage_unacquires_the_image) { GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; // Stage::begin() before the acquire works too auto& stage = next_frame(core, graph).stage(0); { auto const primary = stage.begin(); auto const image = acquire(core, surface, stage); - ASSERT_TRUE(image); + ASSERT_TRUE(image.has_value()); clear(*primary, *image); - // the skip discards the recording and waits for the acquire semaphore + // the skip discards the recording, waits for the acquire semaphore, drops the image stage.skip(); } EXPECT_EQ(stage.status(), Stage::Status::SKIPPED); @@ -554,7 +592,7 @@ JVK_TEST(Surface, next_acquire_after_a_skipped_stage_unacquires_the_image) { auto& next = next_frame(core, graph).stage(0); { auto const image = acquire(core, surface, next); - ASSERT_TRUE(image); + ASSERT_TRUE(image.has_value()); EXPECT_EQ(acquired_images(surface), 1); auto const primary = next.begin(); clear(*primary, *image); @@ -563,7 +601,7 @@ JVK_TEST(Surface, next_acquire_after_a_skipped_stage_unacquires_the_image) { present_frame(core, graph, surface); } -JVK_TEST(Surface, image_scope_ending_before_the_submit_leaves_the_image_to_the_next_acquire) { +JVK_TEST(Surface, image_without_a_use_presents_after_the_submit) { test::Context const context{}; auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; @@ -571,84 +609,19 @@ JVK_TEST(Surface, image_scope_ending_before_the_submit_leaves_the_image_to_the_n GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; - - auto& stage = next_frame(core, graph).stage(0); - { - auto const image = acquire(core, surface, stage); - ASSERT_TRUE(image); - } - EXPECT_EQ(acquired_images(surface), 1); - - // the submit waits for the acquire semaphore, nothing uses the image - { - auto const primary = stage.begin(); - } - - // the next acquire waits for the submit on the gpu and gives the image back first - auto& next = next_frame(core, graph).stage(0); - { - auto const image = acquire(core, surface, next); - ASSERT_TRUE(image); - EXPECT_EQ(acquired_images(surface), 1); - auto const primary = next.begin(); - clear(*primary, *image); - } - - present_frame(core, graph, surface); -} - -JVK_TEST(Surface, present_inside_the_rendering_scope_submits_and_presents_once) { - test::Context const context{}; - auto windowSurface = test::headless_surface(context.instance); - std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, windowSurface)) - GTEST_SKIP() << "no device presents to a headless surface"; - auto& core = *coreOpt; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + // the epilogue transitions the image from VK_IMAGE_LAYOUT_UNDEFINED auto& stage = next_frame(core, graph).stage(0); + uint32_t imageIdx = 0; { - auto image = acquire(core, surface, stage); - ASSERT_TRUE(image); + auto const image = acquire(core, surface, stage); + ASSERT_TRUE(image.has_value()); + imageIdx = image->imageIdx; auto const primary = stage.begin(); - auto const rendering = primary->beginRendering(clear_info(*image)); - - // the submit ends the rendering and the primary, the ends of the scopes do nothing - image.present(); - EXPECT_EQ(stage.status(), Stage::Status::SUBMITTED); - EXPECT_EQ(primary->rendering(), nullptr); } - wait(core, stage); - - present_frame(core, graph, surface); -} - -JVK_TEST(Surface, moved_scopes_act_once) { - test::Context const context{}; - auto windowSurface = test::headless_surface(context.instance); - std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, windowSurface)) - GTEST_SKIP() << "no device presents to a headless surface"; - auto& core = *coreOpt; - - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; - - auto& stage = next_frame(core, graph).stage(0); - { - // the moved-from scopes end after the moved ones: a second submit or present fails - auto image = acquire(core, surface, stage); - auto const movedImage = std::move(image); - ASSERT_TRUE(movedImage); - auto primary = stage.begin(); - auto const movedPrimary = std::move(primary); - clear(*movedPrimary, *movedImage); - } - EXPECT_EQ(stage.status(), Stage::Status::SUBMITTED); + EXPECT_TRUE(reaches_unacquired(core, core.queue(0), surface, imageIdx)); wait(core, stage); present_frame(core, graph, surface); @@ -662,8 +635,8 @@ JVK_TEST(Surface, exception_in_the_recording_submits_and_presents_nothing) { GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}, .frameSlots = 2}}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}, .frameSlots = 2}}; Stage const* stagePtr = nullptr; uint32_t imageIdx = 0; @@ -686,12 +659,12 @@ JVK_TEST(Surface, exception_in_the_recording_submits_and_presents_nothing) { EXPECT_EQ(stagePtr->status(), Stage::Status::UNSUBMITTED); EXPECT_TRUE(surface.swapchain().current().acquired(imageIdx)); - // the next frame skips the stage, the next acquire gives the image back first + // the next frame skips the stage and drops the image, the next acquire gives it back first auto& stage = next_frame(core, graph).stage(0); EXPECT_EQ(stagePtr->status(), Stage::Status::SKIPPED); { auto const image = acquire(core, surface, stage); - ASSERT_TRUE(image); + ASSERT_TRUE(image.has_value()); EXPECT_EQ(acquired_images(surface), 1); auto const primary = stage.begin(); clear(*primary, *image); @@ -708,8 +681,8 @@ JVK_TEST(Surface, exception_after_the_submit_presents_the_image) { GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; auto& stage = next_frame(core, graph).stage(0); std::optional imageIdxOpt = std::nullopt; @@ -727,7 +700,7 @@ JVK_TEST(Surface, exception_after_the_submit_presents_the_image) { ASSERT_TRUE(imageIdxOpt.has_value()); EXPECT_EQ(stage.status(), Stage::Status::SUBMITTED); - // the frame is complete: the scoped_acquire presents the image + // the stage is submitted: its job presents the image EXPECT_TRUE(reaches_unacquired(core, core.queue(0), surface, *imageIdxOpt)); wait(core, stage); @@ -743,8 +716,8 @@ JVK_TEST(Surface, exception_propagated_to_the_end_destroys_graph_and_surface) { auto& core = *coreOpt; auto const run = [&core, &windowSurface] { - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; for(size_t i = 0;; ++i) { auto& stage = next_frame(core, graph).stage(0); auto const image = acquire(core, surface, stage); @@ -757,6 +730,184 @@ JVK_TEST(Surface, exception_propagated_to_the_end_destroys_graph_and_surface) { EXPECT_THROW(run(), test_exception); } +JVK_TEST(Surface, acquire_in_one_stage_presents_after_another) { + constexpr size_t FRAMES = 4; + test::Context const context{}; + auto windowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, windowSurface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, scene_and_ui()}; + + // the ui stage loads what the scene stage cleared, its epilogue transitions the image + for(size_t i = 0; i < FRAMES; ++i) + EXPECT_EQ(present_scene_and_ui(core, graph, surface).extent, test::HEADLESS_EXTENT); +} + +JVK_TEST(Surface, present_stage_without_a_use_presents_the_image_of_the_acquire_stage) { + test::Context const context{}; + auto windowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, windowSurface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, scene_and_ui()}; + + // the epilogue of the ui stage starts from the state that the scene stage left + auto& frame = next_frame(core, graph); + uint32_t imageIdx = 0; + { + auto const image = acquire(core, surface, frame[SCENE], frame[UI]); + ASSERT_TRUE(image.has_value()); + imageIdx = image->imageIdx; + auto const scene = frame[SCENE].begin(); + clear(*scene, *image); + } + // the scene stage submitted, the image stays acquired until the ui stage + EXPECT_EQ(frame[SCENE].status(), Stage::Status::SUBMITTED); + wait(core, frame[SCENE]); + EXPECT_TRUE(surface.swapchain().current().acquired(imageIdx)); + { + auto const ui = frame[UI].begin(); + } + EXPECT_TRUE(reaches_unacquired(core, core.queue(0), surface, imageIdx)); + + present_scene_and_ui(core, graph, surface); +} + +JVK_TEST(Surface, skipped_present_stage_drops_the_image) { + test::Context const context{}; + auto windowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, windowSurface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, scene_and_ui()}; + + auto& frame = next_frame(core, graph); + { + auto const image = acquire(core, surface, frame[SCENE], frame[UI]); + ASSERT_TRUE(image.has_value()); + auto const scene = frame[SCENE].begin(); + clear(*scene, *image); + } + frame[UI].skip(); + EXPECT_EQ(acquired_images(surface), 1); + + // the next acquire waits for the skip on the gpu, then unacquires the image + auto& next = next_frame(core, graph); + { + auto const image = acquire(core, surface, next[SCENE], next[UI]); + ASSERT_TRUE(image.has_value()); + EXPECT_EQ(acquired_images(surface), 1); + auto const scene = next[SCENE].begin(); + clear(*scene, *image); + } + { + auto const ui = next[UI].begin(); + } + + present_scene_and_ui(core, graph, surface); +} + +JVK_TEST(Surface, exception_in_the_present_stage_drops_the_image) { + test::Context const context{}; + auto windowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, windowSurface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, scene_and_ui()}; + + auto& frame = next_frame(core, graph); + try { + auto const image = acquire(core, surface, frame[SCENE], frame[UI]); + ASSERT_TRUE(image.has_value()); + { + auto const scene = frame[SCENE].begin(); + clear(*scene, *image); + } + auto const ui = frame[UI].begin(); + throw test_exception{}; + } + catch(test_exception const&) {} + EXPECT_EQ(frame[UI].status(), Stage::Status::UNSUBMITTED); + + // the next frame skips the ui stage and drops the image, the next acquire unacquires it + present_scene_and_ui(core, graph, surface); + EXPECT_EQ(frame[UI].status(), Stage::Status::SKIPPED); + present_scene_and_ui(core, graph, surface); +} + +JVK_TEST(Surface, two_surfaces_present_after_one_stage) { + constexpr size_t FRAMES = 4; + test::Context const context{}; + auto firstWindowSurface = test::headless_surface(context.instance); + auto secondWindowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, firstWindowSurface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + + Surface first{core, core.queue(0), {}, std::move(firstWindowSurface)}; + Surface second{core, core.queue(0), {}, std::move(secondWindowSurface)}; + StageGraph graph{core, scene_and_ui()}; + + // each surface has its scene stage, both present after the ui stage in one present + for(size_t i = 0; i < FRAMES; ++i) { + auto& frame = next_frame(core, graph); + auto const firstImage = acquire(core, first, frame[SCENE], frame[UI]); + auto const secondImage = acquire(core, second, frame[SCENE], frame[UI]); + ASSERT_TRUE(firstImage.has_value()); + ASSERT_TRUE(secondImage.has_value()); + { + auto const scene = frame[SCENE].begin(); + clear(*scene, *firstImage); + clear(*scene, *secondImage); + } + { + auto const ui = frame[UI].begin(); + } + wait(core, frame[UI]); + EXPECT_TRUE(reaches_unacquired(core, core.queue(0), first, firstImage->imageIdx)); + EXPECT_TRUE(reaches_unacquired(core, core.queue(0), second, secondImage->imageIdx)); + } +} + +#ifdef CTH_DEBUG_MODE +JVK_TEST(Surface, acquire_for_a_submitted_present_stage_crashes) { + // the child runs the test again: the parent has device threads + GTEST_FLAG_SET(death_test_style, "threadsafe"); + test::Context const context{}; + auto windowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, windowSurface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, scene_and_ui()}; + + auto& frame = next_frame(core, graph); + frame[UI].skip(); + ASSERT_DEATH( + [[maybe_unused]] + auto const image = acquire(core, surface, frame[SCENE], frame[UI]), + ".*" + ); + frame[SCENE].skip(); +} +#endif + JVK_TEST(Surface, present_queue_of_the_same_family) { constexpr size_t FRAMES = 4; test::Context const context{}; @@ -769,9 +920,10 @@ JVK_TEST(Surface, present_queue_of_the_same_family) { || core.queue(0).vk().familyIndex() != core.queue(1).vk().familyIndex()) GTEST_SKIP() << "needs two vulkan queues of one family, e.g. ANV_QUEUE_OVERRIDE=gc=2,c=1"; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Surface surface{core, core.queue(1), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; + // the submit of the stage signals the present semaphores, the queue of the surface presents for(size_t i = 0; i < FRAMES; ++i) present_frame(core, graph, surface); } @@ -785,19 +937,22 @@ JVK_TEST(Surface, present_queue_of_another_family) { GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; auto const& stageQueue = core.queue(0); - if(stageQueue.vk().familyIndex() == core.queue(1).vk().familyIndex()) + auto const& surfaceQueue = core.queue(1); + if(stageQueue.vk().familyIndex() == surfaceQueue.vk().familyIndex()) GTEST_SKIP() << "needs two queue families, e.g. ANV_QUEUE_OVERRIDE=gc=2,c=1"; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Surface surface{core, core.queue(1), {}, std::move(windowSurface)}; - - for(size_t i = 0; i < FRAMES; ++i) - present_frame(core, graph, surface); + Surface surface{core, surfaceQueue, {}, std::move(windowSurface)}; + { + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; + for(size_t i = 0; i < FRAMES; ++i) + present_frame(core, graph, surface); + } surface.destroy(); - // one release on the stage queue per frame: the next release gets the next value of its counter - auto const next = core.executor().sync_wait(stageQueue.transfer(cvk::Barrier{})); + // the epilogue releases the image, one transfer per frame on the queue of the surface acquires + // it: the next transfer gets the next value of its counter + auto const next = core.executor().sync_wait(surfaceQueue.transfer(cvk::Barrier{})); EXPECT_EQ(next.value, FRAMES + 1); - stageQueue.waitIdle(); + surfaceQueue.waitIdle(); } } From b74cf1f239fef023ba4bdddb5e14700218fc482c Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:17:21 +0100 Subject: [PATCH 42/68] jvk: Queue without mutable members, its submits, presents and transfers are non-const - submit(), present() and transfer() change the queue: they are non-const, the 11 mutable qualifiers are gone - Core::queue() with deducing this: Queue& from a non-const core, Queue const& from a const one - the holders that submit keep a Queue&: the stage slots, Surface, PendingPresent, skip_submit() --- jvk/incl/jvk/base/core.hpp | 15 +++++++-- jvk/incl/jvk/base/queue.hpp | 37 +++++++++++----------- jvk/incl/jvk/graph/pending_present.hpp | 6 ++-- jvk/incl/jvk/graph/stage.hpp | 6 ++-- jvk/incl/jvk/graph/stage_graph.hpp | 6 ++-- jvk/incl/jvk/graph/surface.hpp | 8 ++--- jvk/src/base/core.cpp | 11 ------- jvk/src/base/queue.cpp | 16 +++++----- jvk/src/graph/stage.cpp | 2 +- jvk/src/graph/stage_graph.cpp | 22 ++++++------- jvk/src/graph/surface.cpp | 4 +-- jvk/tests/src/base/core_test.cpp | 2 +- jvk/tests/src/base/queue_test.cpp | 40 ++++++++++++------------ jvk/tests/src/context.cpp | 2 +- jvk/tests/src/context.hpp | 2 +- jvk/tests/src/graph/stage_graph_test.cpp | 4 +-- jvk/tests/src/graph/surface_test.cpp | 2 +- 17 files changed, 92 insertions(+), 93 deletions(-) diff --git a/jvk/incl/jvk/base/core.hpp b/jvk/incl/jvk/base/core.hpp index 75e314c7..9a766d68 100644 --- a/jvk/incl/jvk/base/core.hpp +++ b/jvk/incl/jvk/base/core.hpp @@ -116,11 +116,22 @@ class Core { /** * @param queueIdx index of the queue in `cvk::CoreConfig::queueProperties` - * @return serialized queue, the indices of one vulkan queue return the same object + * @return serialized queue, the indices of one vulkan queue return the same object, `const` for + * a `const` core: the submits change the queue * @pre `created()` * @pre `queueIdx` < size of `cvk::CoreConfig::queueProperties` */ - [[nodiscard]] Queue const& queue(size_t queueIdx) const; + template + [[nodiscard]] auto& queue(this Self& self, size_t queueIdx) { + debug_check(self); + CTH_CRITICAL( + queueIdx >= self._queueIndices.size(), + "queue index must be < {}, got {}", + self._queueIndices.size(), + queueIdx + ) {} + return self._queues[self._queueIndices[queueIdx]]; + } /** * @return executor of the workers diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index bcc0c6ee..44946bb7 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -106,7 +106,7 @@ class Queue { * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` * @see `present()` */ - [[nodiscard]] cth::co::executor_task submit(SubmitInfo const&) const; + [[nodiscard]] cth::co::executor_task submit(SubmitInfo const&); /** * submits the batch and presents the images in one strand job, then marks the jvk signals @@ -131,7 +131,7 @@ class Queue { SubmitInfo const&, std::span images, std::span results - ) const; + ); /** * presents the images in one job of the strand, without a submit @@ -148,12 +148,11 @@ class Queue { [[nodiscard]] cth::co::executor_task present( std::span images, std::span results - ) const; + ); // an executor_task: the receiving submit job awaits it before its own submit, so the transfer // is submitted first and the counter only changes in the strand (returning at once needs a lock // around the value and the post) - // const like executor(): the core hands out Queue const&, the transfer members are mutable // returns the jvk SemaphoreSubmitInfo: it keeps the counter for Semaphore::submitted(), it // converts to the cvk one /** @@ -180,7 +179,7 @@ class Queue { cvk::Barrier barriers, std::span waits = {}, std::span binarySignals = {} - ) const; + ); /** * @return executor of the strand @@ -213,7 +212,7 @@ class Queue { * @pre the preconditions of `cvk::Queue::submit()` * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` */ - void submitInStrand(SubmitInfo const&, std::span presents = {}) const; + void submitInStrand(SubmitInfo const&, std::span presents = {}); /** * presents the images in one `cvk::Queue::rawPresent()` @@ -222,7 +221,7 @@ class Queue { * @pre the preconditions of `present()` * @throws cvk::vk_result_exception other result of `vkQueuePresentKHR()` */ - void presentInStrand(std::span images, std::span results) const; + void presentInStrand(std::span images, std::span results); /** * command buffer of one transfer @@ -240,38 +239,38 @@ class Queue { * @details reads the counter, no wait * @pre runs in the strand */ - [[nodiscard]] TransferCmd& freeTransferCmd() const; + [[nodiscard]] TransferCmd& freeTransferCmd(); cth::ref_wrapper _core; cth::ref_wrapper _queue; cth::ref_wrapper _scheduler; cth::co::strand _strand; - mutable std::deque _transferCmds{}; ///< used in the strand only + std::deque _transferCmds{}; ///< used in the strand only /** the submit of `transfer()`, used in the strand only: it keeps its capacity */ - mutable SubmitInfo _transferInfo{}; + SubmitInfo _transferInfo{}; // members, no locals: submitInStrand() refills them, they keep their capacity /** the command buffers of the submit in `submitInStrand()`, used in the strand only */ - mutable std::vector _cmdBufferInfos{}; + std::vector _cmdBufferInfos{}; /** the waits of the submit in `submitInStrand()`, used in the strand only */ - mutable std::vector _waitInfos{}; + std::vector _waitInfos{}; /** the signals of the submit in `submitInStrand()`, used in the strand only */ - mutable std::vector _signalInfos{}; + std::vector _signalInfos{}; // members, no locals: presentInStrand() refills them, they keep their capacity /** the swapchains of the present in `presentInStrand()`, used in the strand only */ - mutable std::vector _presentSwapchains{}; + std::vector _presentSwapchains{}; /** the image indices of the present in `presentInStrand()`, used in the strand only */ - mutable std::vector _presentImageIndices{}; + std::vector _presentImageIndices{}; /** the present semaphores of the present in `presentInStrand()`, used in the strand only */ - mutable std::vector _presentWaits{}; + std::vector _presentWaits{}; /** the present fences of the present in `presentInStrand()`, used in the strand only */ - mutable std::vector _presentFences{}; + std::vector _presentFences{}; //TODO review the counter decides the reuse of the transfer command buffers, no reactor wait: a // transfer reads it - mutable Semaphore _transferred; ///< the transfer counter, raised by each transfer submit + Semaphore _transferred; ///< the transfer counter, raised by each transfer submit public: Queue(Queue const& other) = delete; @@ -296,7 +295,7 @@ namespace jvk::dev { * @pre the info lives until the end of the task, nothing changes it */ [[nodiscard]] cth::co::executor_task skip_submit( - Queue const& queue, + Queue& queue, SubmitInfo const& info, cth::co::catching_scope& jobs ); diff --git a/jvk/incl/jvk/graph/pending_present.hpp b/jvk/incl/jvk/graph/pending_present.hpp index 6ce62698..f60a777f 100644 --- a/jvk/incl/jvk/graph/pending_present.hpp +++ b/jvk/incl/jvk/graph/pending_present.hpp @@ -86,7 +86,7 @@ class PendingPresent { PendingPresent( PresentState& state, uint64_t value, - Queue const& queue, + Queue& queue, cvk::Swapchain& swapchain, uint32_t imageIdx ) : @@ -118,7 +118,7 @@ class PendingPresent { _state.reset(); } - [[nodiscard]] Queue const& queue() const { return *_queue; } + [[nodiscard]] Queue& queue() const { return *_queue; } [[nodiscard]] PresentImage image() const { return {_swapchain, _imageIdx}; } /** @@ -128,7 +128,7 @@ class PendingPresent { private: std::unique_ptr _state; ///< `nullptr` -> resolved or moved from - cth::ref_wrapper _queue; + cth::ref_wrapper _queue; cth::ref_wrapper _swapchain; uint32_t _imageIdx; diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index 0b610650..2b60a296 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -99,7 +99,7 @@ struct SlotSubmit { * @see `StageSlot::presentImages` */ struct PresentGroup { - cth::ref_wrapper queue; ///< the queue of the surfaces of the images + cth::ref_wrapper queue; ///< the queue of the surfaces of the images size_t first; ///< index of the first image in `StageSlot::presentImages` size_t count; ///< of the images @@ -143,7 +143,7 @@ struct StageSlot { cth::co::catching_scope& jobs, size_t stageId, size_t slot, - Queue const& queue, + Queue& queue, size_t secondaries ); @@ -155,7 +155,7 @@ struct StageSlot { size_t stageId; ///< id of the stage, see `StageGraphConfig::stages` size_t slot; - cth::ref_wrapper queue; + cth::ref_wrapper queue; /** * the heaps of the core that the stage binds and that its secondaries inherit diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index f5de43bc..6627564b 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -169,9 +169,9 @@ class StageGraph { using image_mip_t = std::pair; template - using last_queue_map_t = cth::dt::flat_hash_map>; + using last_queue_map_t = cth::dt::flat_hash_map>; - using release_map_t = cth::dt::flat_hash_map; + using release_map_t = cth::dt::flat_hash_map; /** * skips the stages of the frame in the slot without `Stage::submit()` or `Stage::skip()` @@ -252,7 +252,7 @@ class StageGraph { */ void append( ResourceTracker const& recording, - Queue const& queue, + Queue& queue, cvk::Barrier& prologue, release_map_t& releases ); diff --git a/jvk/incl/jvk/graph/surface.hpp b/jvk/incl/jvk/graph/surface.hpp index 47644568..ad4950b5 100644 --- a/jvk/incl/jvk/graph/surface.hpp +++ b/jvk/incl/jvk/graph/surface.hpp @@ -93,13 +93,13 @@ class Surface { * @details the queue presents the images * @pre the config passes `Config::debug_check()` */ - Surface(Core const&, Queue const&, Config); + Surface(Core const&, Queue&, Config); /** * constructs and creates - * @details calls @ref Surface(Core const&, Queue const&, Config), `create()` + * @details calls @ref Surface(Core const&, Queue&, Config), `create()` */ - Surface(Core const&, Queue const&, Config, cvk::Surface); + Surface(Core const&, Queue&, Config, cvk::Surface); /** * @note calls `optDestroy()` @@ -239,7 +239,7 @@ class Surface { [[nodiscard]] Swapchain::Config swapchainConfig() const; cth::ref_wrapper _core; - cth::ref_wrapper _queue; + cth::ref_wrapper _queue; Config _config; // destroyed after the swapchain diff --git a/jvk/src/base/core.cpp b/jvk/src/base/core.cpp index 4d948217..9856f51d 100644 --- a/jvk/src/base/core.cpp +++ b/jvk/src/base/core.cpp @@ -119,17 +119,6 @@ void Core::destroy() { _corePtr->destroy(); } -Queue const& Core::queue(size_t queueIdx) const { - debug_check(*this); - CTH_CRITICAL( - queueIdx >= _queueIndices.size(), - "queue index must be < {}, got {}", - _queueIndices.size(), - queueIdx - ) {} - return _queues[_queueIndices[queueIdx]]; -} - ResourceHeap const& Core::resourceHeap() const { debug_check(*this); CTH_CRITICAL( diff --git a/jvk/src/base/queue.cpp b/jvk/src/base/queue.cpp index ddc26259..e209f585 100644 --- a/jvk/src/base/queue.cpp +++ b/jvk/src/base/queue.cpp @@ -43,7 +43,7 @@ void Queue::waitIdle() const { ); } -cth::co::executor_task Queue::submit(SubmitInfo const& info) const { +cth::co::executor_task Queue::submit(SubmitInfo const& info) { co_await executor().schedule(); submitInStrand(info); @@ -54,7 +54,7 @@ cth::co::executor_task Queue::present( SubmitInfo const& info, span images, span results -) const { +) { // no suspension between the submit and the present: the presents follow the order of the // submits co_await executor().schedule(); @@ -73,7 +73,7 @@ cth::co::executor_task Queue::present( cth::co::executor_task Queue::present( span images, span results -) const { +) { co_await executor().schedule(); presentInStrand(images, results); } @@ -82,7 +82,7 @@ cth::co::executor_task Queue::transfer( cvk::Barrier barriers, span waits, span binarySignals -) const { +) { // all in the strand: it serializes the transfer command buffers, the counter values follow the // submit order co_await executor().schedule(); @@ -110,7 +110,7 @@ cth::co::executor_task Queue::transfer( co_return signal; } -void Queue::submitInStrand(SubmitInfo const& info, span presents) const { +void Queue::submitInStrand(SubmitInfo const& info, span presents) { _cmdBufferInfos.clear(); for(PrimaryCmdBuffer const& cmdBuffer : info.cmdBuffers) _cmdBufferInfos.push_back(cvk::cmd_buffer_submit_info(cmdBuffer)); @@ -145,7 +145,7 @@ void Queue::submitInStrand(SubmitInfo const& info, span pres ); } -void Queue::presentInStrand(span images, span results) const { +void Queue::presentInStrand(span images, span results) { CTH_CRITICAL( results.size() != images.size(), "one result per image, got {} results for {} images", @@ -185,7 +185,7 @@ void Queue::presentInStrand(span images, span resu )); } -auto Queue::freeTransferCmd() const -> TransferCmd& { +auto Queue::freeTransferCmd() -> TransferCmd& { auto const reached = _transferred.gpuValue(); auto const it = std::ranges::find_if( @@ -202,7 +202,7 @@ auto Queue::freeTransferCmd() const -> TransferCmd& { namespace dev { cth::co::executor_task skip_submit( - Queue const& queue, + Queue& queue, SubmitInfo const& info, cth::co::catching_scope& jobs ) { diff --git a/jvk/src/graph/stage.cpp b/jvk/src/graph/stage.cpp index 3e7db6bb..4fc30ed4 100644 --- a/jvk/src/graph/stage.cpp +++ b/jvk/src/graph/stage.cpp @@ -65,7 +65,7 @@ StageSlot::StageSlot( cth::co::catching_scope& jobs, size_t stageId, size_t slot, - Queue const& queue, + Queue& queue, size_t secondaries ) : graph{graph}, diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index 2ddef82f..e22fdf14 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -301,7 +301,7 @@ cth::co::executor_task StageGraph::submitJob( ) { auto& slotSubmit = stageSlot.slotSubmit; auto& info = stageSlot.submitInfo; - auto const& queue = *stageSlot.queue; + auto& queue = *stageSlot.queue; // the marks first, off the strand: a wait before the signal on one queue would block it, the appends follow the // dependency order @@ -403,7 +403,7 @@ cth::co::executor_task StageGraph::submitJob( void StageGraph::append( ResourceTracker const& recording, - Queue const& queue, + Queue& queue, cvk::Barrier& prologue, release_map_t& releases ) { @@ -411,7 +411,7 @@ void StageGraph::append( // the last queue if it has another family, nullptr -> no last queue or the same family auto const otherFamilyQueue = [family - ](auto const& lastQueues, auto const& key) -> Queue const* { + ](auto const& lastQueues, auto const& key) -> Queue* { auto const it = lastQueues.find(key); if(it == lastQueues.end() || it->second->vk().familyIndex() == family) return nullptr; @@ -430,7 +430,7 @@ void StageGraph::append( continue; } - auto const* lastQueuePtr = otherFamilyQueue(_imageQueues, image_mip_t{vkImage, mipLevel}); + auto* const lastQueuePtr = otherFamilyQueue(_imageQueues, image_mip_t{vkImage, mipLevel}); if(lastQueuePtr == nullptr || sharingMode != VK_SHARING_MODE_EXCLUSIVE) continue; @@ -462,7 +462,7 @@ void StageGraph::append( if(!firstOpt.has_value() || !lastOpt.has_value()) continue; - auto const* lastQueuePtr = otherFamilyQueue(_bufferQueues, vkBuffer); + auto* const lastQueuePtr = otherFamilyQueue(_bufferQueues, vkBuffer); if(lastQueuePtr == nullptr || sharingMode != VK_SHARING_MODE_EXCLUSIVE) continue; @@ -478,10 +478,10 @@ void StageGraph::append( for(auto const& [vkImage, mipLevel, aspectMask, sharingMode] : recording.images()) _imageQueues.insert_or_assign( image_mip_t{vkImage, mipLevel}, - cth::ref_wrapper{queue} + cth::ref_wrapper{queue} ); for(auto const& [vkBuffer, sharingMode] : recording.buffers()) - _bufferQueues.insert_or_assign(vkBuffer, cth::ref_wrapper{queue}); + _bufferQueues.insert_or_assign(vkBuffer, cth::ref_wrapper{queue}); } void StageGraph::presentBarriers(dev::StageSlot& stageSlot) { @@ -525,7 +525,7 @@ cth::co::executor_task StageGraph::submitAndPresent( uint64_t frameNumber ) { auto& info = stageSlot.submitInfo; - auto const& queue = *stageSlot.queue; + auto& queue = *stageSlot.queue; auto const family = queue.vk().familyIndex(); auto& presents = stageSlot.presents; auto& images = stageSlot.presentImages; @@ -536,7 +536,7 @@ cth::co::executor_task StageGraph::submitAndPresent( // submit in one strand job images.clear(); groups.clear(); - auto const addGroup = [&](Queue const& groupQueue) { + auto const addGroup = [&](Queue& groupQueue) { auto const first = images.size(); for(auto const& present : presents) if(&present.queue() == &groupQueue) @@ -547,7 +547,7 @@ cth::co::executor_task StageGraph::submitAndPresent( if(std::ranges::contains(presents, &queue, queueOf)) addGroup(queue); for(auto it = presents.begin(); it != presents.end(); ++it) { - auto const* queuePtr = &it->queue(); + auto* const queuePtr = &it->queue(); // the first present of a queue opens its group if(queuePtr != &queue && !std::ranges::contains(presents.begin(), it, queuePtr, queueOf)) addGroup(*queuePtr); @@ -585,7 +585,7 @@ cth::co::executor_task StageGraph::submitAndPresent( // the presents on other queues after the submit SemaphoreSubmitInfo const submitted{.semaphore = stageSlot.semaphore, .value = frameNumber}; for(auto& group : groups) { - auto const& groupQueue = *group.queue; + auto& groupQueue = *group.queue; if(&groupQueue == &queue) continue; diff --git a/jvk/src/graph/surface.cpp b/jvk/src/graph/surface.cpp index 1b76d448..eccc7ef3 100644 --- a/jvk/src/graph/surface.cpp +++ b/jvk/src/graph/surface.cpp @@ -29,14 +29,14 @@ namespace { } } -Surface::Surface(Core const& core, Queue const& queue, Config config) : +Surface::Surface(Core const& core, Queue& queue, Config config) : _core{core}, _queue{queue}, _config{std::move(config)}, _surface{static_cast(core).instance()}, _swapchain{core, queue.vk(), _surface} { Config::debug_check(_config); } -Surface::Surface(Core const& core, Queue const& queue, Config config, cvk::Surface surface) : +Surface::Surface(Core const& core, Queue& queue, Config config, cvk::Surface surface) : Surface{core, queue, std::move(config)} { create(std::move(surface)); } void Surface::create(cvk::Surface surface) { diff --git a/jvk/tests/src/base/core_test.cpp b/jvk/tests/src/base/core_test.cpp index e67517a7..a18aa08d 100644 --- a/jvk/tests/src/base/core_test.cpp +++ b/jvk/tests/src/base/core_test.cpp @@ -146,7 +146,7 @@ JVK_TEST(Core, a_base_constructed_core_moves_then_creates_and_works) { // the queues, the reactor and the workers of the moved core Semaphore const semaphore{other, cvk::create}; - auto task = [](Core const& c, Semaphore const& s) -> cth::co::executor_task { + auto task = [](Core& c, Semaphore const& s) -> cth::co::executor_task { co_await c.queue(0).submit({.signals = {{.semaphore = s, .value = 1}}}); co_await s.wait(1); co_return c.executor().context().owns_thread(); diff --git a/jvk/tests/src/base/queue_test.cpp b/jvk/tests/src/base/queue_test.cpp index 9a665cc8..994d02ac 100644 --- a/jvk/tests/src/base/queue_test.cpp +++ b/jvk/tests/src/base/queue_test.cpp @@ -199,7 +199,7 @@ namespace { JVK_TEST(Queue, jobs_of_two_coroutines_never_overlap) { test::Context const context{}; - auto const& queue = context.core.queue(0); + auto& queue = context.core.queue(0); StrandJobs jobs{}; std::jthread other{ @@ -232,7 +232,7 @@ JVK_TEST(Queue, strand_runs_on_the_driver_threads) { JVK_TEST(Queue, wait_idle_waits_for_the_submits) { test::Context const context{}; - auto const& queue = context.core.queue(0); + auto& queue = context.core.queue(0); cvk::TimelineSemaphore const semaphore{context.core, cvk::create}; queue.executor().sync_wait(signal(queue, semaphore)); @@ -262,9 +262,9 @@ JVK_TEST(Queue, a_moved_queue_runs_its_strand) { JVK_TEST(Queue, release_transfers_an_image_to_another_family) { test::Context const context{}; - Core const core{context.instance, two_families(), {}}; - auto const& owner = core.queue(0); - auto const& receiver = core.queue(1); + Core core{context.instance, two_families(), {}}; + auto& owner = core.queue(0); + auto& receiver = core.queue(1); auto const ownerFamily = owner.vk().familyIndex(); auto const receiverFamily = receiver.vk().familyIndex(); if(ownerFamily == receiverFamily) @@ -335,9 +335,9 @@ JVK_TEST(Queue, release_transfers_an_image_to_another_family) { JVK_TEST(Queue, transfer_of_the_acquire_half_waits_and_signals) { test::Context const context{}; - Core const core{context.instance, two_families(), {}}; - auto const& owner = core.queue(0); - auto const& receiver = core.queue(1); + Core core{context.instance, two_families(), {}}; + auto& owner = core.queue(0); + auto& receiver = core.queue(1); auto const ownerFamily = owner.vk().familyIndex(); auto const receiverFamily = receiver.vk().familyIndex(); if(ownerFamily == receiverFamily) @@ -410,9 +410,9 @@ JVK_TEST(Queue, transfer_of_the_acquire_half_waits_and_signals) { JVK_TEST(Queue, several_releases_in_a_row) { constexpr size_t RELEASES = 4; test::Context const context{}; - Core const core{context.instance, two_families(), {}}; - auto const& owner = core.queue(0); - auto const& receiver = core.queue(1); + Core core{context.instance, two_families(), {}}; + auto& owner = core.queue(0); + auto& receiver = core.queue(1); auto const ownerFamily = owner.vk().familyIndex(); auto const receiverFamily = receiver.vk().familyIndex(); if(ownerFamily == receiverFamily) @@ -493,7 +493,7 @@ JVK_TEST(Queue, several_releases_in_a_row) { JVK_TEST(Queue, submit_marks_the_jvk_signals) { test::Context const context{}; - auto const& queue = context.core.queue(0); + auto& queue = context.core.queue(0); Semaphore const first{context.core, cvk::create}; Semaphore const second{context.core, cvk::create}; @@ -511,7 +511,7 @@ JVK_TEST(Queue, submit_marks_the_jvk_signals) { JVK_TEST(Queue, submit_waits_for_the_jvk_and_the_binary_waits) { test::Context const context{}; - auto const& queue = context.core.queue(0); + auto& queue = context.core.queue(0); cvk::Semaphore const binary{context.core, cvk::create}; Semaphore const gate{context.core, cvk::create}; Semaphore const done{context.core, cvk::create}; @@ -536,7 +536,7 @@ JVK_TEST(Queue, submit_waits_for_the_jvk_and_the_binary_waits) { JVK_TEST(Queue, skip_submit_marks_through_the_submit) { test::Context const context{}; - auto const& queue = context.core.queue(0); + auto& queue = context.core.queue(0); Semaphore const semaphore{context.core, cvk::create}; cth::co::catching_scope jobs{}; @@ -555,8 +555,8 @@ JVK_TEST(Queue, present_submits_presents_and_marks) { std::optional coreOpt{}; if(!create_present_core(coreOpt, context, surface)) GTEST_SKIP() << "no device presents to a headless surface"; - auto const& core = *coreOpt; - auto const& queue = core.queue(0); + auto& core = *coreOpt; + auto& queue = core.queue(0); Swapchain swapchain{core, queue.vk(), surface}; swapchain.create({}, EXTENT); @@ -615,8 +615,8 @@ JVK_TEST(Queue, present_of_two_swapchains_in_one_call) { std::optional coreOpt{}; if(!create_present_core(coreOpt, context, firstSurface)) GTEST_SKIP() << "no device presents to a headless surface"; - auto const& core = *coreOpt; - auto const& queue = core.queue(0); + auto& core = *coreOpt; + auto& queue = core.queue(0); Swapchain first{core, queue.vk(), firstSurface}; first.create({}, EXTENT); @@ -680,8 +680,8 @@ JVK_TEST(Queue, present_without_a_submit_after_the_submit_of_the_present_semapho std::optional coreOpt{}; if(!create_present_core(coreOpt, context, surface)) GTEST_SKIP() << "no device presents to a headless surface"; - auto const& core = *coreOpt; - auto const& queue = core.queue(0); + auto& core = *coreOpt; + auto& queue = core.queue(0); Swapchain swapchain{core, queue.vk(), surface}; swapchain.create({}, EXTENT); diff --git a/jvk/tests/src/context.cpp b/jvk/tests/src/context.cpp index cdd636b3..011a6627 100644 --- a/jvk/tests/src/context.cpp +++ b/jvk/tests/src/context.cpp @@ -48,7 +48,7 @@ namespace { return *shared; } - Core const& shared_core() { + Core& shared_core() { auto& contexts = shared_contexts(); if(!contexts.core.has_value()) contexts.core.emplace(contexts.instance, Context::CONFIG, NO_SURFACES); diff --git a/jvk/tests/src/context.hpp b/jvk/tests/src/context.hpp index 95506854..9a0e6d14 100644 --- a/jvk/tests/src/context.hpp +++ b/jvk/tests/src/context.hpp @@ -74,7 +74,7 @@ struct Context { ValidationCheck validationCheck; cvk::Instance const& instance; - Core const& core; + Core& core; Context(Context const& other) = delete; Context(Context&& other) = delete; diff --git a/jvk/tests/src/graph/stage_graph_test.cpp b/jvk/tests/src/graph/stage_graph_test.cpp index f4a377a2..a55af238 100644 --- a/jvk/tests/src/graph/stage_graph_test.cpp +++ b/jvk/tests/src/graph/stage_graph_test.cpp @@ -794,7 +794,7 @@ JVK_TEST(StageGraph, image_and_buffer_move_to_another_queue_family) { EXPECT_TRUE(counts(bufferReadback)); // one release on the writer queue for both: the next release gets the second value of its counter - auto const& writerQueue = core.queue(0); + auto& writerQueue = core.queue(0); auto const next = core.executor().sync_wait(writerQueue.transfer(cvk::Barrier{})); EXPECT_EQ(next.value, 2); writerQueue.waitIdle(); @@ -803,7 +803,7 @@ JVK_TEST(StageGraph, image_and_buffer_move_to_another_queue_family) { JVK_TEST(StageGraph, erase_removes_the_state_and_the_last_queue_of_an_image) { test::Context const context{}; Core core{context.instance, two_families(), {}}; - auto const& firstQueue = core.queue(0); + auto& firstQueue = core.queue(0); if(firstQueue.vk().familyIndex() == core.queue(1).vk().familyIndex()) GTEST_SKIP() << "needs two queue families, e.g. ANV_QUEUE_OVERRIDE=gc=2,c=1"; StageGraph graph{core, {.stages = {{.queueIdx = 0}, {.queueIdx = 1}}}}; diff --git a/jvk/tests/src/graph/surface_test.cpp b/jvk/tests/src/graph/surface_test.cpp index aa446d6a..0a170928 100644 --- a/jvk/tests/src/graph/surface_test.cpp +++ b/jvk/tests/src/graph/surface_test.cpp @@ -937,7 +937,7 @@ JVK_TEST(Surface, present_queue_of_another_family) { GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; auto const& stageQueue = core.queue(0); - auto const& surfaceQueue = core.queue(1); + auto& surfaceQueue = core.queue(1); if(stageQueue.vk().familyIndex() == surfaceQueue.vk().familyIndex()) GTEST_SKIP() << "needs two queue families, e.g. ANV_QUEUE_OVERRIDE=gc=2,c=1"; From 807efaf199e6310490deb2a6f5eeeb514e7358ae Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:17:21 +0100 Subject: [PATCH 43/68] docs: private members and module helpers get no doc, only a comment for a quirk - AGENTS.md: docs are for the users of the API - cvk, jvk, cgfw, timgui: the docs of private members, anonymous namespaces and module-only dev:: helpers removed, a // comment kept where it states a quirk (a lock, an order, a lifetime) --- AGENTS.md | 2 + cgfw/incl/cgfw/window/window.hpp | 3 - cgfw/src/window/window.cpp | 3 - cvk/incl/cvk/base/core.hpp | 19 +-- cvk/incl/cvk/base/cvk.hpp | 6 - cvk/incl/cvk/base/device.hpp | 16 --- cvk/incl/cvk/base/instance.hpp | 4 - cvk/incl/cvk/base/physical_device.hpp | 3 - cvk/incl/cvk/data/buffer/base_buffer.hpp | 8 +- cvk/incl/cvk/data/buffer/buffer.hpp | 3 - cvk/incl/cvk/data/descriptor/descriptor.hpp | 54 +------- .../cvk/data/descriptor/descriptor_span.hpp | 2 +- cvk/incl/cvk/data/descriptor/heap_buffer.hpp | 24 ---- .../cvk/data/descriptor/resource_heap.hpp | 3 - cvk/incl/cvk/data/img/image.hpp | 3 - cvk/incl/cvk/data/img/sampler_config.hpp | 3 - cvk/incl/cvk/data/memory/memory.hpp | 3 - cvk/incl/cvk/render/cmd/cmd_buffer.hpp | 17 --- .../cvk/render/pipeline/graphics_pipeline.hpp | 2 +- cvk/incl/cvk/render/sync/barrier.hpp | 5 - cvk/incl/cvk/surface/surface.hpp | 2 +- cvk/incl/cvk/surface/swapchain.hpp | 18 +-- .../cvk/utility/device/device_features.hpp | 10 +- cvk/incl/cvk/utility/device/feature_chain.hpp | 3 - cvk/incl/cvk/utility/enumerate.hpp | 18 --- cvk/src/base/core.cpp | 3 - cvk/src/base/instance.cpp | 3 - cvk/src/base/physical_device.cpp | 8 +- cvk/src/base/queue/submit_info.cpp | 3 - cvk/src/data/descriptor/descriptor.cpp | 6 - cvk/src/utility/device/feature_chain.cpp | 3 - cvk/src/utility/vk_error_code.cpp | 3 - jvk/incl/jvk/base/core.hpp | 17 +-- jvk/incl/jvk/base/queue.hpp | 55 +------- jvk/incl/jvk/base/queue_sets.hpp | 9 -- jvk/incl/jvk/base/stasis.hpp | 4 +- jvk/incl/jvk/cmd/cmd_buffer.hpp | 4 - jvk/incl/jvk/data/free_list.hpp | 2 +- jvk/incl/jvk/data/resource_heap.hpp | 19 +-- jvk/incl/jvk/data/sampler_heap.hpp | 17 +-- jvk/incl/jvk/graph/pending_present.hpp | 2 +- jvk/incl/jvk/graph/stage.hpp | 4 +- jvk/incl/jvk/graph/stage_graph.hpp | 128 ++---------------- jvk/incl/jvk/graph/surface.hpp | 29 +--- jvk/incl/jvk/graph/swapchain.hpp | 6 +- jvk/incl/jvk/sync/family_transfer.hpp | 31 +---- jvk/incl/jvk/sync/resource_tracker.hpp | 14 +- jvk/incl/jvk/sync/semaphore.hpp | 5 +- jvk/incl/jvk/sync/timeline_reactor.hpp | 31 +---- jvk/src/base/queue.cpp | 3 - jvk/src/base/stasis.cpp | 3 - jvk/src/cmd/cmd_buffer.cpp | 15 -- jvk/src/graph/stage.cpp | 3 - jvk/src/graph/stage_graph.cpp | 9 +- jvk/src/graph/surface.cpp | 3 - jvk/src/sync/resource_tracker.cpp | 22 --- timgui/src/imgui.cpp | 44 +----- timgui/src/input.hpp | 4 +- 58 files changed, 76 insertions(+), 670 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 55e1caf4..f89dd3cf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -327,6 +327,8 @@ this code base. ``@details calls @ref Instance(Config), `wrap()` ``, `@ref create(Config const&)`. Do not write `(...)`: it does not link. - Do not document what the signature already tells. A getter without conditions needs no comment. +- Docs are for the users of the API: private members and the helpers that only the module uses get no doc, only a + `//` comment for a quirk that the code cannot say. - The brief is the purpose. Side effects the caller must know go to `@details`. - `@details` holds one fact per line, starting with its keyword, so a reader can scan for it. No text walls. - one item: inline on the tag line: ``@details calls `optEnd()` on the secondaries`` diff --git a/cgfw/incl/cgfw/window/window.hpp b/cgfw/incl/cgfw/window/window.hpp index 8fd210b9..b555e5cd 100644 --- a/cgfw/incl/cgfw/window/window.hpp +++ b/cgfw/incl/cgfw/window/window.hpp @@ -65,9 +65,6 @@ struct native_window { }; namespace dev { - /** - * deleter of a window, without context - */ struct window_deleter { void operator()(RGFW_window*) const; }; diff --git a/cgfw/src/window/window.cpp b/cgfw/src/window/window.cpp index 518a342c..81440f23 100644 --- a/cgfw/src/window/window.cpp +++ b/cgfw/src/window/window.cpp @@ -36,9 +36,6 @@ namespace { static_assert(same_flag(WindowFlags::FOCUS_ON_SHOW, RGFW_windowFocusOnShow)); static_assert(same_flag(WindowFlags::MINIMIZE, RGFW_windowMinimize)); - /** - * deinitializes RGFW if it is initialized and has no window - */ void deinit_without_windows() { if(RGFW_getInfo() != nullptr && cgfw_rgfw_window_count() == 0) RGFW_deinit(); diff --git a/cvk/incl/cvk/base/core.hpp b/cvk/incl/cvk/base/core.hpp index 08b2ee2f..c55fab65 100644 --- a/cvk/incl/cvk/base/core.hpp +++ b/cvk/incl/cvk/base/core.hpp @@ -179,23 +179,17 @@ class Core { [[nodiscard]] constexpr std::span queueIndices() const { return _queueIndices; } private: - /** - * features and extensions of the device - */ struct device_requirements { DeviceFeatures features; std::vector extensions; }; - /** - * physical device for a queue set and the mapping of the queues - */ struct device_pick { std::unique_ptr physicalDevice; std::vector uniqueQueueFamilyIndices; std::vector queuesToUniqueQueues; - /** `std::nullopt` -> the config had no queue sets */ + // `std::nullopt` -> the config had no queue sets std::optional queueSetIndex = std::nullopt; }; struct queue_set_relations { @@ -205,16 +199,8 @@ class Core { void forget(); - /** - * @return the base set, the config and the present set with a present queue - */ [[nodiscard]] static device_requirements requirements(Config const&); - /** - * picks a physical device for the first possible queue set - * @throws cvk::cvk_exception reason: no physical device meets the requirements - * @throws cvk::cvk_exception reason: `Config::device` is missing or does not meet the requirements - */ [[nodiscard]] device_pick pickPhysicalDevice( std::span const> surfaces, Config const&, @@ -226,9 +212,6 @@ class Core { std::span queueProperties ); - /** - * @return `std::nullopt` -> no physical device supports the queue set - */ [[nodiscard]] std::optional tryPickPhysicalDevice( std::span const> surfaces, Config const&, diff --git a/cvk/incl/cvk/base/cvk.hpp b/cvk/incl/cvk/base/cvk.hpp index d9f6f651..79e92270 100644 --- a/cvk/incl/cvk/base/cvk.hpp +++ b/cvk/incl/cvk/base/cvk.hpp @@ -32,14 +32,8 @@ class Cvk { [[nodiscard]] static bool initialized(); private: - /** - * @return the switch that loads and unloads the loader - */ [[nodiscard]] static cth::co::global_switch& loader(); - /** - * @throws cvk::vk_result_exception result of `volkInitialize()` - */ static void load(); static void unload(); diff --git a/cvk/incl/cvk/base/device.hpp b/cvk/incl/cvk/base/device.hpp index a51e6f88..a7667f50 100644 --- a/cvk/incl/cvk/base/device.hpp +++ b/cvk/incl/cvk/base/device.hpp @@ -136,30 +136,14 @@ class Device { private: void forget(); - /** - * @param familyIndices family index of each queue - * @return count of queues per family, one entry per family of the physical device - * @pre the physical device has a family for each index - */ [[nodiscard]] std::vector calcQueueFamiliesQueueCounts( std::span familyIndices ) const; - /** - * creates the device with `_features` and `_extensions` - * @param queueFamiliesQueueCounts count of queues per family, the index is the family index - * @pre some count > 0 - * @throws cvk::vk_result_exception result of `vkCreateDevice()` - */ void createLogicalDevice(std::span queueFamiliesQueueCounts); void loadFunctionTable(VkDevice vkDevice) const; - /** - * retrieves the queues - * @param familyIndices family index of each queue - * @pre the device has the queues - */ void createQueues(std::span familyIndices); diff --git a/cvk/incl/cvk/base/instance.hpp b/cvk/incl/cvk/base/instance.hpp index 6d7a28ec..8b22b36c 100644 --- a/cvk/incl/cvk/base/instance.hpp +++ b/cvk/incl/cvk/base/instance.hpp @@ -144,10 +144,6 @@ class Instance { private: void forget(); - /** - * the config the messenger is created with - * @return `std::nullopt` -> no messenger, debug builds: the config of `Config::debugMessenger` or the default - */ [[nodiscard]] constexpr std::optional messengerConfig() const; static void loadInstanceFunctions(vk_not_null); diff --git a/cvk/incl/cvk/base/physical_device.hpp b/cvk/incl/cvk/base/physical_device.hpp index 996b2188..e69b553c 100644 --- a/cvk/incl/cvk/base/physical_device.hpp +++ b/cvk/incl/cvk/base/physical_device.hpp @@ -207,9 +207,6 @@ struct PhysicalDevicePick { } namespace cvk::dev { -/** - * @return rank of the device type for the pick, 0 is the best: discrete, integrated, virtual, cpu, other - */ [[nodiscard]] constexpr uint32_t device_type_rank(VkPhysicalDeviceType type) { switch(type) { case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return 0; diff --git a/cvk/incl/cvk/data/buffer/base_buffer.hpp b/cvk/incl/cvk/data/buffer/base_buffer.hpp index 4c86c91e..eaa82845 100644 --- a/cvk/incl/cvk/data/buffer/base_buffer.hpp +++ b/cvk/incl/cvk/data/buffer/base_buffer.hpp @@ -190,14 +190,8 @@ class BaseBuffer { private: void forget(); - /** - * @return `vkGetBufferDeviceAddress()`, `0` -> the usage has no `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT` - */ [[nodiscard]] VkDeviceAddress queryAddress() const; - /** - * @pre `memory() != nullptr` - */ [[nodiscard]] constexpr Memory const& ownMemory() const; // declared before the memory: move assignment destroys the old buffer before its memory @@ -205,7 +199,7 @@ class BaseBuffer { std::optional _memoryOpt = std::nullopt; Config _config; size_t _size = 0; - /** `0` -> the usage has no `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT` */ + // `0` -> the usage has no `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT` VkDeviceAddress _address = 0; public: diff --git a/cvk/incl/cvk/data/buffer/buffer.hpp b/cvk/incl/cvk/data/buffer/buffer.hpp index 057b1c4e..7bb24cef 100644 --- a/cvk/incl/cvk/data/buffer/buffer.hpp +++ b/cvk/incl/cvk/data/buffer/buffer.hpp @@ -144,9 +144,6 @@ class Buffer : public BaseBuffer { } private: - /** - * @param count (`VK_WHOLE_SIZE` => `VK_WHOLE_SIZE`) - */ [[nodiscard]] static constexpr size_t bytes(size_t count) { return count == VK_WHOLE_SIZE ? VK_WHOLE_SIZE : count * sizeof(T); } diff --git a/cvk/incl/cvk/data/descriptor/descriptor.hpp b/cvk/incl/cvk/data/descriptor/descriptor.hpp index 1409703d..9cdfc019 100644 --- a/cvk/incl/cvk/data/descriptor/descriptor.hpp +++ b/cvk/incl/cvk/data/descriptor/descriptor.hpp @@ -53,10 +53,7 @@ concept descriptor_of = descriptor && std::same_as, Heap>; } namespace cvk::dev { -/** - * shader variables that a descriptor of `T` serves - * @details image descriptors with `Sampled` 2: with and without `NonWritable` - */ +// image descriptors with `Sampled` 2: with and without `NonWritable` template inline constexpr VkSpirvResourceTypeFlagsEXT resource_mask = [] { if constexpr(std::same_as) @@ -68,15 +65,6 @@ inline constexpr VkSpirvResourceTypeFlagsEXT resource_mask = [] { | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; }(); -/** - * maps a shader array of `T` at the set and binding onto the cells of a heap - * @details element `i` of the array -> the cell at `offset + i * stride` - * @param set of the shader array - * @param binding of the shader array - * @param offset of the first cell in bytes - * @param stride of the cells in bytes - * @pre `offset` and `stride` fit into 32 bits - */ template [[nodiscard]] constexpr VkDescriptorSetAndBindingMappingEXT heap_mapping( uint32_t set, @@ -112,24 +100,8 @@ template }; } -/** - * checks the push offset of an index for the device - * @details `pushOffset + 4 <= maxPushDataSize` - */ void debug_check_push_offset(Core const&, uint32_t pushOffset); -/** - * maps a shader variable of `T` at the set and binding onto the cell at an index in the push data - * @details the cell at `offset + index * stride`, `index`: the `uint32_t` at `pushOffset` in the push data - * @details an array: element `i` -> `i` cells after it - * @param set of the shader variable - * @param binding of the shader variable - * @param offset of the first cell in bytes - * @param stride of the cells in bytes - * @param pushOffset of the index in the push data, in bytes - * @pre `offset` and `stride` fit into 32 bits - * @pre `pushOffset` is a multiple of 4 - */ template [[nodiscard]] constexpr VkDescriptorSetAndBindingMappingEXT heap_push_mapping( uint32_t set, @@ -176,15 +148,6 @@ template }; } -/** - * encodes the descriptor into the cell of the heap, then flushes the cell - * @param heap buffer of the heap - * @param offset of the cell in bytes - * @param size of the cell in bytes - * @pre `ImageViewConfig::debug_check()` passes for the view and the image - * @throws cvk::vk_result_exception result of `vkWriteResourceDescriptorsEXT()` - * @throws cvk::vk_result_exception result of `vmaFlushAllocation()` - */ void write_descriptor( BaseBuffer const& heap, size_t offset, @@ -192,9 +155,6 @@ void write_descriptor( SampledImageDescriptor const& ); -/** - * @see @ref write_descriptor(BaseBuffer const&, size_t, size_t, SampledImageDescriptor const&) - */ void write_descriptor( BaseBuffer const& heap, size_t offset, @@ -202,9 +162,6 @@ void write_descriptor( StorageImageDescriptor const& ); -/** - * @see @ref write_descriptor(BaseBuffer const&, size_t, size_t, SampledImageDescriptor const&) - */ void write_descriptor( BaseBuffer const& heap, size_t offset, @@ -212,14 +169,5 @@ void write_descriptor( InputAttachmentDescriptor const& ); -/** - * encodes the sampler into the cell of the heap, then flushes the cell - * @param heap buffer of the heap - * @param offset of the cell in bytes - * @param size of the cell in bytes - * @details clamps `SamplerConfig::maxAnisotropy` to `maxSamplerAnisotropy` of the device, warns if it clamps - * @throws cvk::vk_result_exception result of `vkWriteSamplerDescriptorsEXT()` - * @throws cvk::vk_result_exception result of `vmaFlushAllocation()` - */ void write_descriptor(BaseBuffer const& heap, size_t offset, size_t size, SamplerConfig const&); } diff --git a/cvk/incl/cvk/data/descriptor/descriptor_span.hpp b/cvk/incl/cvk/data/descriptor/descriptor_span.hpp index f5a8f3b1..c72f5aa6 100644 --- a/cvk/incl/cvk/data/descriptor/descriptor_span.hpp +++ b/cvk/incl/cvk/data/descriptor/descriptor_span.hpp @@ -96,7 +96,7 @@ class DescriptorSpan::reference { reference const& operator=(Descriptor const& descriptor) const; private: - DescriptorSpan _span; ///< a copy: the reference outlives a temporary span + DescriptorSpan _span; // a copy: the reference outlives a temporary span uint32_t _idx; public: diff --git a/cvk/incl/cvk/data/descriptor/heap_buffer.hpp b/cvk/incl/cvk/data/descriptor/heap_buffer.hpp index 438b3acb..d3ab5ee5 100644 --- a/cvk/incl/cvk/data/descriptor/heap_buffer.hpp +++ b/cvk/incl/cvk/data/descriptor/heap_buffer.hpp @@ -8,11 +8,6 @@ namespace cvk::dev { -/** - * buffer config of a descriptor heap - * @details usage: descriptor heap and device address - * @details memory: mapped, sequential host writes, prefers device memory - */ inline constexpr BaseBuffer::Config HEAP_BUFFER_CONFIG{ .usage = VK_BUFFER_USAGE_DESCRIPTOR_HEAP_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, .memory = { @@ -22,21 +17,6 @@ inline constexpr BaseBuffer::Config HEAP_BUFFER_CONFIG{ }, }; -/** - * creates the buffer of a descriptor heap - * @param[out] buffer gets a buffer with `HEAP_BUFFER_CONFIG` and the alignment - * @param size in bytes - * @param alignment of the heap address - * @param maxSize device limit of the heap size - * @param heap name of the heap for the messages - * @details memory not device local -> warns: the gpu fetches the descriptors from host memory - * @pre `Core::created()` - * @pre `0 < size` - * @post `buffer.created()` - * @note calls `BaseBuffer::optDestroy()` - * @throws cvk::cvk_exception reason: `size > maxSize` - * @throws cvk::vk_result_exception result of `vmaCreateBuffer()` - */ void create_heap_buffer( BaseBuffer& buffer, size_t size, @@ -45,10 +25,6 @@ void create_heap_buffer( std::string_view heap ); -/** - * @return bind info of the whole buffer with the reserved range - * @pre `buffer.created()` - */ [[nodiscard]] VkBindHeapInfoEXT heap_bind_info( BaseBuffer const& buffer, size_t reservedOffset, diff --git a/cvk/incl/cvk/data/descriptor/resource_heap.hpp b/cvk/incl/cvk/data/descriptor/resource_heap.hpp index 89c7c1d8..5aa43234 100644 --- a/cvk/incl/cvk/data/descriptor/resource_heap.hpp +++ b/cvk/incl/cvk/data/descriptor/resource_heap.hpp @@ -171,9 +171,6 @@ class ResourceHeap { [[nodiscard]] constexpr Config const& config() const { return _config; } private: - /** - * @return byte offset of the first descriptor of the type - */ template Descriptor> [[nodiscard]] constexpr size_t offset() const; diff --git a/cvk/incl/cvk/data/img/image.hpp b/cvk/incl/cvk/data/img/image.hpp index 04c1cb75..893568d3 100644 --- a/cvk/incl/cvk/data/img/image.hpp +++ b/cvk/incl/cvk/data/img/image.hpp @@ -178,9 +178,6 @@ class Image { } private: - /** - * @return region of the whole mip level at the buffer offset - */ [[nodiscard]] VkBufferImageCopy2 bufferCopy( BaseCmdBuffer const&, BaseBuffer const& buffer, diff --git a/cvk/incl/cvk/data/img/sampler_config.hpp b/cvk/incl/cvk/data/img/sampler_config.hpp index dea8d01e..42ef77a7 100644 --- a/cvk/incl/cvk/data/img/sampler_config.hpp +++ b/cvk/incl/cvk/data/img/sampler_config.hpp @@ -63,9 +63,6 @@ struct SamplerConfig { } namespace cvk::dev { -/** - * @return hash of the members, equal configs hash equal - */ [[nodiscard]] inline size_t hash(SamplerConfig const& config) noexcept { return cth::hash::combine( config.magFilter, diff --git a/cvk/incl/cvk/data/memory/memory.hpp b/cvk/incl/cvk/data/memory/memory.hpp index 5273c6fb..13697501 100644 --- a/cvk/incl/cvk/data/memory/memory.hpp +++ b/cvk/incl/cvk/data/memory/memory.hpp @@ -171,9 +171,6 @@ class Memory { template friend class Mapping; - /** - * unmaps the memory once, the destructor of a `Mapping` calls it - */ void unmap() const; void forget(); diff --git a/cvk/incl/cvk/render/cmd/cmd_buffer.hpp b/cvk/incl/cvk/render/cmd/cmd_buffer.hpp index fd518743..d1f54c3c 100644 --- a/cvk/incl/cvk/render/cmd/cmd_buffer.hpp +++ b/cvk/incl/cvk/render/cmd/cmd_buffer.hpp @@ -423,9 +423,6 @@ class BaseCmdBuffer { std::optional _continuedViewMaskOpt = std::nullopt; private: - /** - * frees the command buffer through its pool, the pool stops to count it - */ class pool_deleter { public: constexpr explicit pool_deleter(CmdPool const& pool) : _pool{pool} {} @@ -439,14 +436,8 @@ class BaseCmdBuffer { cth::ref_wrapper _pool; }; - /** - * records the attachment mapping of `rendering()` - */ void recordAttachmentMapping() const; - /** - * records the bytes as push data - */ void pushDataBytes(std::span data, uint32_t offset) const; void forget(); @@ -561,11 +552,6 @@ class PrimaryCmdBuffer : public BaseCmdBuffer { [[nodiscard]] RenderingInheritance inheritance() const; private: - /** - * records `vkCmdExecuteCommands()` with the command buffers - * @pre `recording()` - * @pre `rendering()` -> `VK_RENDERING_CONTENTS_SECONDARY_COMMAND_BUFFERS_BIT` - */ void recordExecute(std::span) const; }; } @@ -646,9 +632,6 @@ class SecondaryCmdBuffer : public BaseCmdBuffer { } private: - /** - * begins the recording with the inheritance info, chains the inherited heaps in front of its `pNext` - */ void beginInherited( VkCommandBufferInheritanceInfo, VkCommandBufferUsageFlags usage, diff --git a/cvk/incl/cvk/render/pipeline/graphics_pipeline.hpp b/cvk/incl/cvk/render/pipeline/graphics_pipeline.hpp index 0e963a6b..d03a9bf8 100644 --- a/cvk/incl/cvk/render/pipeline/graphics_pipeline.hpp +++ b/cvk/incl/cvk/render/pipeline/graphics_pipeline.hpp @@ -68,7 +68,7 @@ class GraphicsPipeline : public BasePipeline { [[nodiscard]] constexpr Config const& config() const { return _config; } private: - GraphicsPipeline const* _parentPtr = nullptr; ///< `nullptr` -> not a derivative pipeline + GraphicsPipeline const* _parentPtr = nullptr; Config _config; }; } diff --git a/cvk/incl/cvk/render/sync/barrier.hpp b/cvk/incl/cvk/render/sync/barrier.hpp index 9666b45d..dc961bd3 100644 --- a/cvk/incl/cvk/render/sync/barrier.hpp +++ b/cvk/incl/cvk/render/sync/barrier.hpp @@ -201,11 +201,6 @@ struct Barrier { } private: - /** - * checks the rules of barriers inside a dynamic rendering - * @param renderingPtr the rendering the command buffer began, `nullptr` -> a secondary continues the rendering - * @param viewMask of the rendering - */ void debug_check_rendering( RenderingInfo const* renderingPtr, uint32_t viewMask, diff --git a/cvk/incl/cvk/surface/surface.hpp b/cvk/incl/cvk/surface/surface.hpp index 1037b17b..01e6d3c4 100644 --- a/cvk/incl/cvk/surface/surface.hpp +++ b/cvk/incl/cvk/surface/surface.hpp @@ -119,7 +119,7 @@ class Surface { cth::ref_wrapper _instance; instance_handle _handle{nullptr}; - extent_callback_t _extentCallback{}; ///< see `State::extentCallback` + extent_callback_t _extentCallback{}; public: Surface(Surface const& other) = delete; diff --git a/cvk/incl/cvk/surface/swapchain.hpp b/cvk/incl/cvk/surface/swapchain.hpp index 6c84088e..00a66f62 100644 --- a/cvk/incl/cvk/surface/swapchain.hpp +++ b/cvk/incl/cvk/surface/swapchain.hpp @@ -287,10 +287,7 @@ class Swapchain { private: // the element wrappers: = default moves of the swapchain tear down in the member order, the // swapchain destroys its images itself, the present fences must signal before their destruction - /** - * image of the swapchain, the swapchain destroys it - * @details the destruction releases the image, it does not destroy it - */ + // the destruction releases the image, it does not destroy it: the swapchain destroys its images struct ReleasingImage { explicit ReleasingImage(Image image) : image{std::move(image)} {} ~ReleasingImage() { @@ -305,10 +302,7 @@ class Swapchain { ReleasingImage& operator=(ReleasingImage&& other) noexcept = default; }; - /** - * present fence of an image - * @details the destruction waits for the present that signals it - */ + // the destruction waits for the present that signals the fence struct WaitingFence { explicit WaitingFence(Fence fence) : fence{std::move(fence)} {} ~WaitingFence() { @@ -323,16 +317,8 @@ class Swapchain { WaitingFence& operator=(WaitingFence&& other) noexcept = default; }; - /** - * @return the first allowed format and present mode of the config that the surface offers - * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode - */ [[nodiscard]] std::pair pick(Config const&) const; - /** - * gets the images, creates their views, present semaphores and present fences - * @throws cvk::vk_result_exception result of `vkGetSwapchainImagesKHR()` or of a create - */ void createImages(); void forget(); diff --git a/cvk/incl/cvk/utility/device/device_features.hpp b/cvk/incl/cvk/utility/device/device_features.hpp index 8eaa0e16..36a0a38e 100644 --- a/cvk/incl/cvk/utility/device/device_features.hpp +++ b/cvk/incl/cvk/utility/device/device_features.hpp @@ -181,23 +181,15 @@ struct DeviceFeatures { } namespace cvk::dev { -/** - * feature bits in `DeviceFeatures`, every field is a bool without padding - */ +// every field of `DeviceFeatures` is a bool without padding inline constexpr size_t FEATURE_COUNT = sizeof(DeviceFeatures); using feature_bits_t = std::array; -/** - * @return field i of the features as element i - */ [[nodiscard]] constexpr feature_bits_t to_bits(DeviceFeatures const& features) { return std::bit_cast(features); } -/** - * @return element i of the bits as field i - */ [[nodiscard]] constexpr DeviceFeatures to_features(feature_bits_t const& bits) { return std::bit_cast(bits); } diff --git a/cvk/incl/cvk/utility/device/feature_chain.hpp b/cvk/incl/cvk/utility/device/feature_chain.hpp index e70ae986..70af10cd 100644 --- a/cvk/incl/cvk/utility/device/feature_chain.hpp +++ b/cvk/incl/cvk/utility/device/feature_chain.hpp @@ -228,9 +228,6 @@ class FeatureChain { } private: - /** - * links the `pNext` members of the structs in `_linked` - */ void link(); feature_structs_t _structs; diff --git a/cvk/incl/cvk/utility/enumerate.hpp b/cvk/incl/cvk/utility/enumerate.hpp index 2a8b8340..162ac8bc 100644 --- a/cvk/incl/cvk/utility/enumerate.hpp +++ b/cvk/incl/cvk/utility/enumerate.hpp @@ -11,9 +11,6 @@ namespace cvk::dev { -/** - * element type of a two-call query: the pointee of its last parameter - */ template struct enumerate_element {}; @@ -27,23 +24,8 @@ struct enumerate_element { template using enumerate_element_t = enumerate_element::type; -/** - * max count and write rounds of `enumerate()` while the result is `VK_INCOMPLETE` - */ constexpr uint32_t MAX_QUERY_ATTEMPTS = 4; -/** - * calls a two-call query as `fn(args..., &count, data)`, first for the count, then for the elements - * @param what name of the elements for the error message - * @param fn function pointer: a volk global or a `VolkDeviceTable` member - * @param args arguments before the count - * @details `VkResult` `fn` -> repeats both calls while the result is `VK_INCOMPLETE`, - * at most `MAX_QUERY_ATTEMPTS` rounds - * @details `void` `fn` -> one count and one write call - * @return the elements, as many as the last call wrote - * @throws cvk::vk_result_exception result of `fn` other than `VK_SUCCESS` or `VK_INCOMPLETE` - * @throws cvk::vk_result_exception `VK_INCOMPLETE` in all `MAX_QUERY_ATTEMPTS` rounds - */ template [[nodiscard]] std::vector> enumerate( [[maybe_unused]] std::string_view what, diff --git a/cvk/src/base/core.cpp b/cvk/src/base/core.cpp index 597032d3..5f1c70dc 100644 --- a/cvk/src/base/core.cpp +++ b/cvk/src/base/core.cpp @@ -18,9 +18,6 @@ using std::span; using std::vector; namespace { - /** - * @return the uuid as hex in the 8-4-4-4-12 form - */ [[nodiscard]] std::string uuid_string(device_uuid_t const& uuid) { std::string result{}; for(auto const [index, byte] : std::views::enumerate(uuid)) { diff --git a/cvk/src/base/instance.cpp b/cvk/src/base/instance.cpp index 9897ebee..5c25ab55 100644 --- a/cvk/src/base/instance.cpp +++ b/cvk/src/base/instance.cpp @@ -17,9 +17,6 @@ using std::string_view; using std::vector; namespace { - /** - * @return the names that are not available - */ [[nodiscard]] vector missing( std::ranges::range auto const& names, vector const& available diff --git a/cvk/src/base/physical_device.cpp b/cvk/src/base/physical_device.cpp index e4c74c00..46a11913 100644 --- a/cvk/src/base/physical_device.cpp +++ b/cvk/src/base/physical_device.cpp @@ -44,9 +44,7 @@ namespace { device_uuid_t uuid; }; - /** - * @param extensions of the device, the query includes the descriptor heap properties only with its extension - */ + // the query includes the descriptor heap properties only with their extension [[nodiscard]] queried_properties query_properties( vk_not_null vkDevice, span extensions @@ -88,9 +86,7 @@ namespace { return properties; } - /** - * @param surfaces a family presents only if it presents to every surface, empty -> no present support - */ + // a family presents only if it presents to every surface, empty surfaces -> no present support [[nodiscard]] vector query_queue_families( span const> surfaces, vk_not_null vkDevice diff --git a/cvk/src/base/queue/submit_info.cpp b/cvk/src/base/queue/submit_info.cpp index d7503523..d296d2b0 100644 --- a/cvk/src/base/queue/submit_info.cpp +++ b/cvk/src/base/queue/submit_info.cpp @@ -27,9 +27,6 @@ namespace { }; } - /** - * @param resolve the value of a timeline semaphore without value - */ template [[nodiscard]] VkSemaphoreSubmitInfo semaphore_info( SemaphoreSubmitInfo const& info, diff --git a/cvk/src/data/descriptor/descriptor.cpp b/cvk/src/data/descriptor/descriptor.cpp index 4b8b8cea..332176c3 100644 --- a/cvk/src/data/descriptor/descriptor.cpp +++ b/cvk/src/data/descriptor/descriptor.cpp @@ -9,9 +9,6 @@ namespace cvk::dev { namespace { - /** - * @return the mapped cell of the heap - */ [[nodiscard]] VkHostAddressRangeEXT host_cell( BaseBuffer const& heap, size_t offset, @@ -30,9 +27,6 @@ namespace { return VkHostAddressRangeEXT{.address = mapped.data() + offset, .size = size}; } - /** - * encodes the image descriptor of the type into the cell, then flushes the cell - */ void write_image( BaseBuffer const& heap, size_t offset, diff --git a/cvk/src/utility/device/feature_chain.cpp b/cvk/src/utility/device/feature_chain.cpp index 82713208..c258638b 100644 --- a/cvk/src/utility/device/feature_chain.cpp +++ b/cvk/src/utility/device/feature_chain.cpp @@ -9,9 +9,6 @@ namespace cvk::dev { using std::span; namespace { - /** - * @return the `VkBool32` flags of the feature struct - */ template [[nodiscard]] auto flags(T& features) { using feature_t = std::remove_const_t; diff --git a/cvk/src/utility/vk_error_code.cpp b/cvk/src/utility/vk_error_code.cpp index 080b3722..89a6a8db 100644 --- a/cvk/src/utility/vk_error_code.cpp +++ b/cvk/src/utility/vk_error_code.cpp @@ -7,9 +7,6 @@ namespace cvk { namespace { - /** - * error category of `VkResult`, see `vk_category()` - */ class vk_error_category final : public std::error_category { public: [[nodiscard]] char const* name() const noexcept override { return "vulkan"; } diff --git a/jvk/incl/jvk/base/core.hpp b/jvk/incl/jvk/base/core.hpp index 9a766d68..a4eae08f 100644 --- a/jvk/incl/jvk/base/core.hpp +++ b/jvk/incl/jvk/base/core.hpp @@ -178,16 +178,9 @@ class Core { [[nodiscard]] constexpr Config const& config() const { return _config; } private: - /** - * constructs the driver threads and one queue per vulkan queue - * @pre the cvk core and the reactor are created - * @throws cvk::vk_result_exception result of `vkCreateSemaphore()` for the transfer counters - */ void createQueues(); - /** - * destroys the queues, then the driver threads that run their strands - */ + // the queues first: the driver threads run their strands void destroyQueues(); Config _config; @@ -204,14 +197,14 @@ class Core { TimelineReactor _reactor; // destroyed after the queues: their strands run on it - std::optional _driverSchedulerOpt{}; ///< see `CoreConfig::driverThreads` + std::optional _driverSchedulerOpt{}; // destroyed before the reactor, the workers and the cvk core - std::vector _queues{}; ///< one per vulkan queue - /** index in `_queues` per index of `cvk::CoreConfig::queueProperties` */ + std::vector _queues{}; // one per vulkan queue: the indices of one vulkan queue share it + // index in `_queues` per index of `cvk::CoreConfig::queueProperties` std::vector _queueIndices{}; // destroyed before the cvk core - ResourceHeap _resourceHeap; ///< not created without counts, see `HeapsConfig` + ResourceHeap _resourceHeap; // not created without counts, see `HeapsConfig` // the sampler heap needs the created cvk core, no heap without counts std::optional _samplerHeapOpt{}; diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index 44946bb7..1a8cbcbb 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -204,41 +204,17 @@ class Queue { [[nodiscard]] constexpr VkQueue get() const { return _queue->get(); } private: - /** - * submits the batch through `cvk::Queue::rawSubmit()` - * @details resolves the `std::nullopt` timeline values in order: the waits, then the signals - * @param presents their present semaphores are signaled after the signals of the info - * @pre runs in the strand - * @pre the preconditions of `cvk::Queue::submit()` - * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` - */ void submitInStrand(SubmitInfo const&, std::span presents = {}); - /** - * presents the images in one `cvk::Queue::rawPresent()` - * @param[out] results one per image, also written by a failed present - * @pre runs in the strand - * @pre the preconditions of `present()` - * @throws cvk::vk_result_exception other result of `vkQueuePresentKHR()` - */ void presentInStrand(std::span images, std::span results); - /** - * command buffer of one transfer - * @details owns its command pool, see `PrimaryCmdBuffer` - */ struct TransferCmd { PrimaryCmdBuffer cmd; - /** value of the transfer counter for the last submit of `cmd`, free once reached */ + // free once the transfer counter reached it uint64_t value = 0; }; - /** - * a command buffer whose last transfer the gpu finished, or a new one - * @details reads the counter, no wait - * @pre runs in the strand - */ [[nodiscard]] TransferCmd& freeTransferCmd(); cth::ref_wrapper _core; @@ -246,31 +222,22 @@ class Queue { cth::ref_wrapper _scheduler; cth::co::strand _strand; - std::deque _transferCmds{}; ///< used in the strand only - /** the submit of `transfer()`, used in the strand only: it keeps its capacity */ + // used in the strand only, members and no locals: they keep their capacity + std::deque _transferCmds{}; SubmitInfo _transferInfo{}; - // members, no locals: submitInStrand() refills them, they keep their capacity - /** the command buffers of the submit in `submitInStrand()`, used in the strand only */ std::vector _cmdBufferInfos{}; - /** the waits of the submit in `submitInStrand()`, used in the strand only */ std::vector _waitInfos{}; - /** the signals of the submit in `submitInStrand()`, used in the strand only */ std::vector _signalInfos{}; - // members, no locals: presentInStrand() refills them, they keep their capacity - /** the swapchains of the present in `presentInStrand()`, used in the strand only */ std::vector _presentSwapchains{}; - /** the image indices of the present in `presentInStrand()`, used in the strand only */ std::vector _presentImageIndices{}; - /** the present semaphores of the present in `presentInStrand()`, used in the strand only */ std::vector _presentWaits{}; - /** the present fences of the present in `presentInStrand()`, used in the strand only */ std::vector _presentFences{}; //TODO review the counter decides the reuse of the transfer command buffers, no reactor wait: a // transfer reads it - Semaphore _transferred; ///< the transfer counter, raised by each transfer submit + Semaphore _transferred; public: Queue(Queue const& other) = delete; @@ -281,19 +248,7 @@ class Queue { } namespace jvk::dev { -/** - * submits the waits and the signals of a skip, no command buffers - * @details - * - a skip, also of a failed submit: the waiters of the jvk signals go on - * - `Queue::submit()` marks the signals - * - `VK_ERROR_DEVICE_LOST` -> stores the error in the scope, marks the signals: the gpu waits end - * on their own - * - another failure terminates: the waiters would hang - * @param queue of the skipped submit - * @param info waits and signals of the skipped submit, no command buffers - * @param[out] jobs of the caller, gets a device loss - * @pre the info lives until the end of the task, nothing changes it - */ +// terminates on a failure other than a device loss: the waiters of the signals would hang [[nodiscard]] cth::co::executor_task skip_submit( Queue& queue, SubmitInfo const& info, diff --git a/jvk/incl/jvk/base/queue_sets.hpp b/jvk/incl/jvk/base/queue_sets.hpp index ff114fa7..3d23bb0e 100644 --- a/jvk/incl/jvk/base/queue_sets.hpp +++ b/jvk/incl/jvk/base/queue_sets.hpp @@ -30,9 +30,6 @@ namespace jvk { } namespace jvk::dev { -/** - * @return combined properties of the group of the queue - */ [[nodiscard]] inline cvk::QueueFamilyProperties group_properties( cvk::Core::queue_set_t const& set, std::span queues, @@ -47,12 +44,6 @@ namespace jvk::dev { return result; } -/** - * appends one set per merge of two groups that match - * @param[out] sets - * @param match(lhs, rhs) properties of two groups, `true` -> the groups merge - * @pre `!sets.empty()` - */ template void merge_groups( std::vector& sets, diff --git a/jvk/incl/jvk/base/stasis.hpp b/jvk/incl/jvk/base/stasis.hpp index f61b7310..7e46594e 100644 --- a/jvk/incl/jvk/base/stasis.hpp +++ b/jvk/incl/jvk/base/stasis.hpp @@ -123,9 +123,9 @@ class Stasis { std::vector _handles{}; std::vector _pooledHandles{}; - /** handles destroyed by `clear()`, the position of `_handles.front()` */ + // handles destroyed by `clear()`: the position of `_handles.front()` size_t _clearedHandles = 0; - /** pooled handles destroyed by `clear()`, the position of the first one */ + // pooled handles destroyed by `clear()`: the position of the first one size_t _clearedPooledHandles = 0; public: diff --git a/jvk/incl/jvk/cmd/cmd_buffer.hpp b/jvk/incl/jvk/cmd/cmd_buffer.hpp index 0c71f0d2..bda4e3d5 100644 --- a/jvk/incl/jvk/cmd/cmd_buffer.hpp +++ b/jvk/incl/jvk/cmd/cmd_buffer.hpp @@ -474,10 +474,6 @@ class BasicCmdBuffer { private: explicit BasicCmdBuffer(std::unique_ptr); - /** - * records the barrier if it is not empty - * @details inside a rendering: adds `VK_DEPENDENCY_BY_REGION_BIT`, with multiview `VK_DEPENDENCY_VIEW_LOCAL_BIT` - */ void record(cvk::Barrier&) const; void forget(); diff --git a/jvk/incl/jvk/data/free_list.hpp b/jvk/incl/jvk/data/free_list.hpp index 4fbf052a..bb5749f9 100644 --- a/jvk/incl/jvk/data/free_list.hpp +++ b/jvk/incl/jvk/data/free_list.hpp @@ -45,7 +45,7 @@ class free_list { private: uint32_t _size; - uint32_t _next = 0; ///< the cells from here on were never in use + uint32_t _next = 0; // the cells from here on were never in use std::vector _erased{}; }; } diff --git a/jvk/incl/jvk/data/resource_heap.hpp b/jvk/incl/jvk/data/resource_heap.hpp index 3a369441..3577d5cc 100644 --- a/jvk/incl/jvk/data/resource_heap.hpp +++ b/jvk/incl/jvk/data/resource_heap.hpp @@ -165,33 +165,24 @@ class ResourceHeap { [[nodiscard]] constexpr Config const& config() const { return _vk.config(); } private: - /** - * frees every cell - */ void forget(); template Descriptor> [[nodiscard]] ImageHandle insertImage(Descriptor const&) const; - /** - * returns the cell to the free list of its type - */ template Descriptor> void erase(uint32_t idx) const; - /** - * @return the free list of the type - * @pre `_mutexPtr` is locked - */ + // the caller holds `_mutexPtr` template Descriptor> [[nodiscard]] dev::free_list& freeList() const; // behind a std::unique_ptr: the mutex is not movable, the moves stay = default std::unique_ptr _mutexPtr = std::make_unique(); - mutable cvk::ResourceHeap _vk; ///< written under `_mutexPtr` - mutable dev::free_list _sampledImages; ///< under `_mutexPtr` - mutable dev::free_list _storageImages; ///< under `_mutexPtr` - mutable dev::free_list _inputAttachments; ///< under `_mutexPtr` + mutable cvk::ResourceHeap _vk; // written under `_mutexPtr` + mutable dev::free_list _sampledImages; // under `_mutexPtr` + mutable dev::free_list _storageImages; // under `_mutexPtr` + mutable dev::free_list _inputAttachments; // under `_mutexPtr` public: ResourceHeap(ResourceHeap const& other) = delete; diff --git a/jvk/incl/jvk/data/sampler_heap.hpp b/jvk/incl/jvk/data/sampler_heap.hpp index 2c00c811..5093b2d3 100644 --- a/jvk/incl/jvk/data/sampler_heap.hpp +++ b/jvk/incl/jvk/data/sampler_heap.hpp @@ -79,19 +79,10 @@ class SamplerHeap { [[nodiscard]] constexpr Config const& config() const { return _vk.config(); } private: - /** - * adds a handle of the cell - */ void ref(uint32_t idx) const; - /** - * removes a handle of the cell, the last one returns the cell - */ void unref(uint32_t idx) const; - /** - * the handles and the config of a cell - */ struct slot { uint32_t refs = 0; cvk::SamplerConfig config{}; @@ -99,10 +90,10 @@ class SamplerHeap { // behind a std::unique_ptr: the mutex is not movable, the moves stay = default std::unique_ptr _mutexPtr = std::make_unique(); - mutable cvk::SamplerHeap _vk; ///< written under `_mutexPtr` - mutable dev::free_list _cells; ///< under `_mutexPtr` - mutable cth::dt::flat_hash_map _indices{}; ///< under `_mutexPtr` - mutable std::vector _slots; ///< one per cell, under `_mutexPtr` + mutable cvk::SamplerHeap _vk; // written under `_mutexPtr` + mutable dev::free_list _cells; // under `_mutexPtr` + mutable cth::dt::flat_hash_map _indices{}; // under `_mutexPtr` + mutable std::vector _slots; // one per cell, under `_mutexPtr` public: SamplerHeap(SamplerHeap const& other) = delete; diff --git a/jvk/incl/jvk/graph/pending_present.hpp b/jvk/incl/jvk/graph/pending_present.hpp index f60a777f..a01262cd 100644 --- a/jvk/incl/jvk/graph/pending_present.hpp +++ b/jvk/incl/jvk/graph/pending_present.hpp @@ -127,7 +127,7 @@ class PendingPresent { [[nodiscard]] cvk::Image const& swapchainImage() const { return _swapchain->image(_imageIdx); } private: - std::unique_ptr _state; ///< `nullptr` -> resolved or moved from + std::unique_ptr _state; // `nullptr` -> resolved or moved from cth::ref_wrapper _queue; cth::ref_wrapper _swapchain; uint32_t _imageIdx; diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index 2b60a296..45afe177 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -481,7 +481,7 @@ class Stage { uint64_t _frameNumber; Status _status = Status::UNSUBMITTED; - /** the images and buffers of `retain()`, under `StageSlot::stasisMutex` */ + // under `StageSlot::stasisMutex` dev::RetainedResources _retained{}; public: @@ -526,7 +526,7 @@ class scoped_submit { private: cth::move_ptr _stagePtr; - cth::ref_wrapper _jobs; ///< of the graph + cth::ref_wrapper _jobs; int _uncaughtExceptions; public: diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index 6627564b..e9f8446e 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -173,60 +173,15 @@ class StageGraph { using release_map_t = cth::dt::flat_hash_map; - /** - * skips the stages of the frame in the slot without `Stage::submit()` or `Stage::skip()` - * @details a skipped stage that other stages wait for: warns - * @details no frame in the slot -> nothing - */ void skipUnsubmitted(dev::FrameSlot&); //TODO review one helper for submit() and skip(): they differ in the status only - /** - * detaches the submit job, then sets the status of the stage - * @details - * - takes `Stasis::end()` of the stage slot and the retained resources of the stage under - * `StageSlot::stasisMutex` - * - a failed allocation: the stage stays `UNSUBMITTED` without its retained resources, the exception destroys - * the graph - * @param targetStatus `SUBMITTED` or `SKIPPED` - */ void detachJob(Stage&, Stage::Status targetStatus); // no marks as parameters: the job awaits Semaphore::submitted() of the slots, they live as // long as the graph // next() before the mark: the job of the next frame of the slot awaits the mark, it reads the // values - /** - * submit job of `submit()` and `skip()` - * @details the order: - * - off the strand: awaits `Semaphore::submitted()` of the stage in the frame before, of the - * waits of `StageSlot::slotSubmit` and of every jvk extra wait: the appends follow the - * dependency order - * - the binary extra waits: no await on the cpu - * - `SlotSubmit::skipInfo()` of the frame into `StageSlot::submitInfo`, clears the extra waits - * of the slot, then `SlotSubmit::next()` - * - `SUBMITTED`: `append()` of the states of the primary under `StageGraph::_statesMutex`, `release()` of the - * release halves, records the prologue, an empty prologue: no record, the submit without it - * - `SUBMITTED`: `presentBarriers()` under the same lock, records the epilogue, no presents: no - * record, the submit without it - * - `SUBMITTED`: `submitAndPresent()` with the release waits, the submit marks the slot with - * the frame number - * - `SKIPPED` or a failed submit: `dev::skip_submit()` of the skip info, then drops the - * presents after the gpu finished it - * - then sets `StageSlot::submitDone`: the job ended its use of the slot before the gpu wait - * - on the workers of the core: after the gpu finished, erases the states of the retained resources, then - * `Stasis::clear()` to `stasisEnd` - * @details the errors: - * - a failed submit: stores the error in `StageGraph::_jobs`, then skips - * - a failed skip: `VK_ERROR_DEVICE_LOST` -> stores the error, marks the slot, else terminates: - * the waiters would hang - * - before the mark: every other failure terminates, the waiters would hang - * - after the mark: an escaped exception ends the job, `StageGraph::_jobs` stores it - * - a failed gpu wait escapes: the retained objects stay for the destruction of the graph - * @param targetStatus the status the job reaches: `SUBMITTED` or `SKIPPED` - * @param stasisEnd `Stasis::end()` of the stage slot at the submit or the skip - * @see `Stage::submitted()` - */ [[nodiscard]] cth::co::executor_task submitJob( dev::StageSlot&, uint64_t frameNumber, @@ -235,21 +190,7 @@ class StageGraph { Stage::Status targetStatus ); - /** - * appends the states of a submit on the queue to the resource states after all submits - * @details the first use of a mip level or a buffer after the last state: - * - unknown image: from `VK_IMAGE_LAYOUT_UNDEFINED` - * - unknown buffer: no barrier - * - the same queue family, or `VK_SHARING_MODE_CONCURRENT`: the barrier of - * `ResourceTracker::append()` - * - another queue family, `EXCLUSIVE`, contents needed: release half for the last queue, acquire half - * - another queue family, discard or `VK_IMAGE_LAYOUT_UNDEFINED`: from `VK_IMAGE_LAYOUT_UNDEFINED`, no transfer - * - an `assume()` before the first use: no barrier - * @details sets the queue as the last queue of the resources - * @param[out] prologue gets the barriers for the first uses of the submit, the acquire halves included - * @param[out] releases gets the release halves per last queue of another family - * @pre the caller holds `StageGraph::_statesMutex` - */ + // the caller holds `_statesMutex` void append( ResourceTracker const& recording, Queue& queue, @@ -258,97 +199,46 @@ class StageGraph { ); // jvk waits: they join the jvk extra waits of the stage - /** - * releases the resources on their last queues - * @param releases the release halves per last queue, from `append()` - * @return the waits for the releases - * @see `Queue::transfer()` - */ [[nodiscard]] cth::co::executor_task> release( release_map_t releases ); - /** - * fills `StageSlot::epilogueBarriers` with the barriers of the presented images - * @details per image of `StageSlot::presents`, from its state after all submits: - * - the queue of its surface has the family of the stage: to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` - * - another family: the release half towards the family of the surface - * @details stores the state before the barrier in `StageSlot::presentStates`, sets the state - * after it in `StageGraph::_states` - * @pre the caller holds `StageGraph::_statesMutex` - * @pre `append()` of the recording of the stage ran - */ + // the caller holds `_statesMutex`, after `append()` void presentBarriers(dev::StageSlot&); - /** - * submits `StageSlot::submitInfo`, presents the images of `StageSlot::presents` after it - * @details the images grouped by the queues of their surfaces: - * - the queue of the stage: `Queue::present()` with the submit, one strand job - * - another queue of the family: the submit signals their present semaphores, then - * `Queue::present()` without a submit on that queue - * - another family: after the submit `Queue::transfer()` of the acquire halves on that queue, - * it signals the present semaphores, then the present, then the wait until the gpu finished - * the transfer: it waits for the semaphore of the slot - * @details the end: each image resolves with its result, an image without a present (failed - * transfer) drops after the gpu finished the submit, then clears `StageSlot::presents` - * @details a failed present or transfer: `StageGraph::_jobs` stores the error - * @throws std::exception reason: the submit failed, nothing is presented or resolved - */ + // throws only for a failed submit: nothing is presented or resolved then [[nodiscard]] cth::co::executor_task submitAndPresent( dev::StageSlot&, uint64_t frameNumber ); - /** - * removes the states and the last queues of the mip levels - * @pre the caller holds `StageGraph::_statesMutex` - */ + // the caller holds `_statesMutex` void eraseStates(VkImage, uint32_t mipLevels); - /** - * removes the state and the last queue of the buffer - * @pre the caller holds `StageGraph::_statesMutex` - */ + // the caller holds `_statesMutex` void eraseStates(VkBuffer); - /** - * ends an open rendering and the primary - */ static void endPrimary(PrimaryCmdBuffer&); cth::ref_wrapper _core; Config _config; - std::deque _frameSlots{}; ///< one per frame slot, with its stage slots + std::deque _frameSlots{}; - /** - * locks `StageGraph::_states`, `StageGraph::_imageQueues` and `StageGraph::_bufferQueues` - */ + // locks `_states`, `_imageQueues` and `_bufferQueues` std::mutex _statesMutex{}; - ResourceTracker _states{}; ///< resource states after all submits + ResourceTracker _states{}; - /** - * last queue per mip level of an image, for the queue family ownership transfers - */ last_queue_map_t _imageQueues{}; - /** last queue per buffer, for the queue family ownership transfers */ last_queue_map_t _bufferQueues{}; //TODO review the error stays: every nextFrame() rethrows it, the errors of the jobs are fatal - /** - * the running submit jobs, `~StageGraph()` waits for them - * @details the first error of a job or a scope of a stage, `nextFrame()` rethrows it - */ cth::co::catching_scope _jobs{}; - uint64_t _firstFrameNumber; ///< see `firstFrameNumber()` + uint64_t _firstFrameNumber; - /** - * number of the last frame that `nextFrame()` handed out - * @details `firstFrameNumber() - 1` before the first frame - */ uint64_t _frameNumber; public: diff --git a/jvk/incl/jvk/graph/surface.hpp b/jvk/incl/jvk/graph/surface.hpp index ad4950b5..fd93c8eb 100644 --- a/jvk/incl/jvk/graph/surface.hpp +++ b/jvk/incl/jvk/graph/surface.hpp @@ -218,24 +218,10 @@ class Surface { } private: - /** - * creates or recreates the swapchain if it is not created, out of date or of another extent - * @details - * - the first creation: the config of `swapchainConfig()` - * - a recreation erases the old images in the graph first: the new images can reuse their - * handles - * @param extent of the surface, `> 0` - * @param graphPtr of the acquiring stage, `nullptr` -> no graph - * @pre no present uses the swapchain: `create()`, or `acquire()` after the last image resolved - * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode - * @throws cvk::vk_result_exception result of `vkCreateSwapchainKHR()` - */ + // a recreation erases the old images in the graph first: the new images can reuse their + // handles; only when no present uses the swapchain void updateSwapchain(VkExtent2D extent, StageGraph* graphPtr); - /** - * @return `SurfaceConfig::swapchain`, `minImageCount` `0` -> `minImageCount` of the surface + - * `framesInFlight` - */ [[nodiscard]] Swapchain::Config swapchainConfig() const; cth::ref_wrapper _core; @@ -245,24 +231,19 @@ class Surface { // destroyed after the swapchain cvk::Surface _surface; - /** created once the surface extent is `> 0`, the resolve of the last image orders its uses */ + // the resolve of the last image orders its uses Swapchain _swapchain; - /** - * ring of `SurfaceConfig::framesInFlight`, signaled by the acquires - */ std::vector _acquireSemaphores{}; - /** the semaphore in `Surface::_acquireSemaphores` for the next acquire */ size_t _acquireSemaphoreIdx = 0; - /** written by the pending present of the last image, see `dev::PendingPresent` */ dev::PresentState _presentState{}; - /** value of the last acquired image in `PresentState::resolved`, `0` -> none */ + // `0` -> none uint64_t _lastValue = 0; - uint32_t _lastImageIdx = 0; ///< index of the last acquired image in the current swapchain + uint32_t _lastImageIdx = 0; public: Surface(Surface const& other) = delete; diff --git a/jvk/incl/jvk/graph/swapchain.hpp b/jvk/incl/jvk/graph/swapchain.hpp index 41adff0d..34926c9a 100644 --- a/jvk/incl/jvk/graph/swapchain.hpp +++ b/jvk/incl/jvk/graph/swapchain.hpp @@ -121,10 +121,8 @@ class Swapchain { cth::ref_wrapper _presentQueue; cth::ref_wrapper _surface; - /** - * `back()` is the current swapchain, the others are retired, the oldest first - * @details a deque: the addresses stay at the end and the front changes - */ + // `back()` is the current swapchain, the others are retired, the oldest first; a deque: the + // addresses stay at the end std::deque _swapchains{}; public: diff --git a/jvk/incl/jvk/sync/family_transfer.hpp b/jvk/incl/jvk/sync/family_transfer.hpp index 5c0befc1..f401c9f1 100644 --- a/jvk/incl/jvk/sync/family_transfer.hpp +++ b/jvk/incl/jvk/sync/family_transfer.hpp @@ -10,17 +10,9 @@ namespace jvk::dev { -/** src of an acquire half: waits for the release wait of the submit */ +// waits for the release wait of the submit constexpr cvk::BarrierScope ACQUIRE_SRC{.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}; -/** - * release half of the queue family ownership transfer of a mip level, transitions to the first layout - * @param last state on the last queue - * @param first state of the first use - * @param lastFamily of the last queue - * @param family of the first use - * @param mipLevel to transfer - */ [[nodiscard]] constexpr cvk::ImageBarrierInfo release_half( ImageState const& last, ImageState const& first, @@ -39,14 +31,7 @@ constexpr cvk::BarrierScope ACQUIRE_SRC{.stages = VK_PIPELINE_STAGE_2_ALL_COMMAN }; } -/** - * acquire half of the queue family ownership transfer of a mip level, the layouts of `release_half()` - * @param last state on the last queue - * @param first state of the first use - * @param lastFamily of the last queue - * @param family of the first use - * @param mipLevel to transfer - */ +// the layouts of `release_half()`: both halves of a transfer have the same layouts [[nodiscard]] constexpr cvk::ImageBarrierInfo acquire_half( ImageState const& last, ImageState const& first, @@ -66,12 +51,6 @@ constexpr cvk::BarrierScope ACQUIRE_SRC{.stages = VK_PIPELINE_STAGE_2_ALL_COMMAN }; } -/** - * release half of the queue family ownership transfer of a buffer - * @param last state on the last queue - * @param lastFamily of the last queue - * @param family of the first use - */ [[nodiscard]] constexpr cvk::BufferBarrierInfo release_half( BufferState const& last, cvk::queue_family_index_t lastFamily, @@ -84,12 +63,6 @@ constexpr cvk::BarrierScope ACQUIRE_SRC{.stages = VK_PIPELINE_STAGE_2_ALL_COMMAN }; } -/** - * acquire half of the queue family ownership transfer of a buffer - * @param first state of the first use - * @param lastFamily of the last queue - * @param family of the first use - */ [[nodiscard]] constexpr cvk::BufferBarrierInfo acquire_half( BufferState const& first, cvk::queue_family_index_t lastFamily, diff --git a/jvk/incl/jvk/sync/resource_tracker.hpp b/jvk/incl/jvk/sync/resource_tracker.hpp index 6646c5af..c6857db6 100644 --- a/jvk/incl/jvk/sync/resource_tracker.hpp +++ b/jvk/incl/jvk/sync/resource_tracker.hpp @@ -253,25 +253,25 @@ class ResourceTracker { using image_key_t = std::pair; struct image_states { - VkImageAspectFlags aspectMask; ///< of the image, the barriers take it - VkSharingMode sharingMode; ///< of the image + VkImageAspectFlags aspectMask; + VkSharingMode sharingMode; - /** `std::nullopt` -> `assume()` before the first access */ + // `std::nullopt` -> `assume()` before the first access std::optional firstOpt; ImageState last; bool discard = false; - bool barrier = false; ///< a barrier or `assume()` after the first use: `firstOpt` is final + bool barrier = false; // a barrier or `assume()` after the first use: `firstOpt` is final }; struct buffer_states { - VkSharingMode sharingMode; ///< of the buffer + VkSharingMode sharingMode; - /** `std::nullopt` -> `assume()` before the first access */ + // `std::nullopt` -> `assume()` before the first access std::optional firstOpt; BufferState last; - bool barrier = false; ///< a barrier or `assume()` after the first use: `firstOpt` is final + bool barrier = false; // a barrier or `assume()` after the first use: `firstOpt` is final }; cth::dt::flat_hash_map _images{}; diff --git a/jvk/incl/jvk/sync/semaphore.hpp b/jvk/incl/jvk/sync/semaphore.hpp index 0a7088a3..b3312e97 100644 --- a/jvk/incl/jvk/sync/semaphore.hpp +++ b/jvk/incl/jvk/sync/semaphore.hpp @@ -56,9 +56,6 @@ class semaphore_awaiter : public cth::co::this_coro_awaiter_base { private: // a private helper: the reactor needs the complete jvk::Core, the template stays in the header - /** - * hands the waiter to the reactor of the core - */ void awaitReactor(); cth::ref_wrapper _semaphore; @@ -221,7 +218,7 @@ class Semaphore { cvk::TimelineSemaphore _semaphore; // mutable: markSubmitted() is const like the submit paths that call it - mutable cth::co::counter_event _submitted{}; ///< see `submittedValue()` + mutable cth::co::counter_event _submitted{}; public: Semaphore(Semaphore const& other) = delete; diff --git a/jvk/incl/jvk/sync/timeline_reactor.hpp b/jvk/incl/jvk/sync/timeline_reactor.hpp index 17a09881..689ff5b2 100644 --- a/jvk/incl/jvk/sync/timeline_reactor.hpp +++ b/jvk/incl/jvk/sync/timeline_reactor.hpp @@ -97,53 +97,30 @@ class TimelineReactor { [[nodiscard]] constexpr bool created() const { return _wake.created(); } private: - /** pending waiter and its semaphore */ struct Pending { VkSemaphore vkSemaphore; cth::ref_wrapper waiter; }; - /** - * thread function: waits for the semaphores with waiters and the wake semaphore, posts the - * reached resumes - * @details stop request -> ends at the next wake - */ void run(std::stop_token); - /** - * raises the wake semaphore, the thread waits again with the new values - * @pre the caller holds `TimelineReactor::_mutexPtr` - * @throws cvk::vk_result_exception result of `vkSignalSemaphore()` - */ + // the caller holds `_mutexPtr` void wake() const; - /** - * stores the error, takes every pending waiter with the error - * @param[out] waiters gets the pending waiters - * @pre the caller holds `TimelineReactor::_mutexPtr` - */ + // the caller holds `_mutexPtr` void fail(std::error_code, std::vector>& waiters) const; - /** - * posts the resume of every waiter to its context - * @details touches no waiter after its post: the resumed caller can destroy it at once - * @pre the caller holds no lock of the reactor - */ + // the caller holds no lock of the reactor static void post(std::span const> waiters); - /** the thread waits for it next to the semaphores with waiters */ mutable cvk::TimelineSemaphore _wake; // behind a std::unique_ptr: the mutex is not movable, the moves stay = default std::unique_ptr _mutexPtr = std::make_unique(); - /** - * the pending waiters of every semaphore, in no order - * @details keeps its capacity: no allocation once it is large enough - */ mutable std::vector _pending{}; - mutable std::error_code _error{}; ///< the result of a failed wait of the thread, empty -> none + mutable std::error_code _error{}; // destroyed first: destroy() stops it before the members std::jthread _thread{}; diff --git a/jvk/src/base/queue.cpp b/jvk/src/base/queue.cpp index e209f585..50dab450 100644 --- a/jvk/src/base/queue.cpp +++ b/jvk/src/base/queue.cpp @@ -18,9 +18,6 @@ namespace jvk { using std::span; namespace { - /** - * marks the jvk signals, see `Semaphore::markSubmitted()` - */ void mark(std::span signals) { for(auto const& signal : signals) signal.semaphore->markSubmitted(signal.value); diff --git a/jvk/src/base/stasis.cpp b/jvk/src/base/stasis.cpp index c254ea96..0fcda9c2 100644 --- a/jvk/src/base/stasis.cpp +++ b/jvk/src/base/stasis.cpp @@ -15,9 +15,6 @@ namespace jvk { namespace { - /** - * @return number of the handles before the position, the first `cleared` are destroyed - */ [[nodiscard]] constexpr size_t count_before(size_t position, size_t cleared, size_t size) { CTH_CRITICAL( position > cleared + size, diff --git a/jvk/src/cmd/cmd_buffer.cpp b/jvk/src/cmd/cmd_buffer.cpp index 95c48470..eb67c7f6 100644 --- a/jvk/src/cmd/cmd_buffer.cpp +++ b/jvk/src/cmd/cmd_buffer.cpp @@ -16,10 +16,6 @@ namespace jvk::dev { namespace { - /** - * @return the shader access of the image of the handle, in the layout of its type, on the subresource range of - * its view - */ template [[nodiscard]] constexpr ImageAccess shader_access( Handle const& handle, @@ -53,9 +49,6 @@ namespace { || layout == VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL; } - /** - * access of the mip level of the view - */ [[nodiscard]] ImageAccess view_access( cvk::ImageView const& view, VkImageLayout layout, @@ -73,9 +66,6 @@ namespace { }; } - /** - * access of a depth or stencil attachment - */ [[nodiscard]] ImageAccess depth_stencil_access( cvk::RenderingAttachment const& attachment, bool writes @@ -100,11 +90,6 @@ namespace { // a callable, no vector: no allocation per rendering - /** - * hands the access of each attachment to the mip level of its image to the callable - * @details the order: color, depth and stencil, resolve - * @param visit called with the image and the access - */ template void visit_attachment_accesses(cvk::RenderingInfo const& info, Visit visit) { for(auto const& attachment : info.colorAttachments) { diff --git a/jvk/src/graph/stage.cpp b/jvk/src/graph/stage.cpp index 4fc30ed4..405a8bfe 100644 --- a/jvk/src/graph/stage.cpp +++ b/jvk/src/graph/stage.cpp @@ -18,9 +18,6 @@ namespace jvk::dev { namespace { - /** - * @return the heaps of the core, none on a family without graphics and compute - */ [[nodiscard]] cvk::HeapInheritance stage_heaps(Core const& core, Queue const& queue) { cvk::Core const& vk = core; auto const* familyPtr = vk.physicalDevice().queueFamily(queue.vk().familyIndex()); diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index e22fdf14..9d802f95 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -30,9 +30,6 @@ using std::span; using std::vector; namespace { - /** - * @return `1 +` the largest `StageWait::frameOffset` of the config - */ [[nodiscard]] uint64_t first_frame_number(StageGraphConfig const& config) { uint64_t maxOffset = 0; for(auto const& stage : config.stages) @@ -41,16 +38,12 @@ namespace { return maxOffset + 1; } - /** state of a presented image after the epilogue */ constexpr ImageState PRESENT_STATE{ .layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, .scope = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, }; - /** - * transition of the first use from `VK_IMAGE_LAYOUT_UNDEFINED`, no queue family ownership transfer - * @details `src` waits for the stages of the first use, no access: like `cvk::layout_transition()` - */ + // `src` waits for the stages of the first use, no access: like `cvk::layout_transition()` [[nodiscard]] constexpr cvk::ImageBarrierInfo from_undefined( ImageState const& first, uint32_t mipLevel diff --git a/jvk/src/graph/surface.cpp b/jvk/src/graph/surface.cpp index eccc7ef3..9ada57de 100644 --- a/jvk/src/graph/surface.cpp +++ b/jvk/src/graph/surface.cpp @@ -21,9 +21,6 @@ namespace jvk { namespace { - /** - * waits until the counter reaches the value - */ cth::co::executor_task await_value(cth::co::counter_event const& event, uint64_t value) { co_await event.wait(value); } diff --git a/jvk/src/sync/resource_tracker.cpp b/jvk/src/sync/resource_tracker.cpp index 01194b03..08aec19e 100644 --- a/jvk/src/sync/resource_tracker.cpp +++ b/jvk/src/sync/resource_tracker.cpp @@ -12,9 +12,6 @@ using cvk::BaseBuffer; using cvk::Image; namespace { - /** - * the write accesses - */ constexpr VkAccessFlags2 WRITES = VK_ACCESS_2_SHADER_WRITE_BIT | VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT | VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT @@ -28,24 +25,15 @@ namespace { [[nodiscard]] constexpr bool writes(VkAccessFlags2 access) { return (access & WRITES) != 0; } - /** - * src of a barrier after the scope, only the writes of its access - */ [[nodiscard]] constexpr BarrierScope src_scope(BarrierScope const& scope) { return BarrierScope{scope.stages, scope.access & WRITES}; } - /** - * the stages and accesses of both scopes - */ [[nodiscard]] constexpr BarrierScope merge(BarrierScope const& scope, BarrierScope const& other) { return BarrierScope{scope.stages | other.stages, scope.access | other.access}; } - /** - * @return the access after the state needs a barrier - */ [[nodiscard]] constexpr bool needs_barrier( ImageState const& last, ImageState const& next, @@ -59,9 +47,6 @@ namespace { return writes(last.scope.access) || writes(next.scope.access); } - /** - * @return the mip level count, `VK_REMAINING_MIP_LEVELS` resolved - */ [[nodiscard]] uint32_t mip_count( Image const& image, uint32_t firstMipLevel, @@ -88,9 +73,6 @@ namespace { return count; } - /** - * @return the barriers differ in the mip levels only, `next` starts after the levels of `last` - */ [[nodiscard]] constexpr bool next_mip_levels( VkImageMemoryBarrier2 const& last, VkImageMemoryBarrier2 const& next @@ -110,10 +92,6 @@ namespace { && lastRange.baseMipLevel + lastRange.levelCount == nextRange.baseMipLevel; } - /** - * appends the barrier of one mip level, merges it into an equal barrier of the level before - * @param[out] barrier - */ void add_image_barrier( cvk::Barrier& barrier, VkImage vkImage, diff --git a/timgui/src/imgui.cpp b/timgui/src/imgui.cpp index 58b27a1a..f053d166 100644 --- a/timgui/src/imgui.cpp +++ b/timgui/src/imgui.cpp @@ -45,9 +45,7 @@ namespace timgui::dev { namespace { - /** - * `Frame` of an `Imgui` exists, one in the program: ImGui keeps the current context in a global - */ + // one `Frame` in the program: ImGui keeps the current context in a global bool frameExists = false; } @@ -132,7 +130,7 @@ struct ImguiState { namespace timgui { namespace { - constexpr float FIRST_DELTA_TIME = 1.f / 60.f; ///< seconds, ImGui needs a positive time + constexpr float FIRST_DELTA_TIME = 1.f / 60.f; // seconds, ImGui needs a positive time constexpr cvk::ImageConfig TEXTURE_CONFIG{ .format = VK_FORMAT_R8G8B8A8_UNORM, @@ -161,9 +159,7 @@ namespace { .maxAnisotropy = 0.f, }; - /** - * alpha blending, the alpha of the attachment gets the coverage of the draws - */ + // the alpha of the attachment gets the coverage of the draws constexpr VkPipelineColorBlendAttachmentState BLENDING{ .blendEnable = VK_TRUE, .srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA, @@ -179,38 +175,21 @@ namespace { constexpr auto TEXTURE_OFFSET = static_cast(offsetof(dev::Draw, texture)); - /** - * makes the ImGui and the ImPlot context of the state current - */ void make_current(dev::ImguiState const& state) { ImGui::SetCurrentContext(state.context.get()); ImPlot::SetCurrentContext(state.plotContext.get()); } - /** - * the heap index as ImGui texture id - * @details `+ 1`: `ImTextureID_Invalid` is `0`, the heap index `0` is a valid cell - * @see `to_heap_idx()` - */ + // `+ 1`: `ImTextureID_Invalid` is `0`, the heap index `0` is a valid cell [[nodiscard]] constexpr ImTextureID to_texture_id(jvk::heap_idx idx) { return ImTextureID{idx.get()} + 1; } - /** - * the heap index of the ImGui texture id - * @pre `id != ImTextureID_Invalid` - * @see `to_texture_id()` - */ [[nodiscard]] constexpr jvk::heap_idx to_heap_idx(ImTextureID id) { CTH_CRITICAL(id == ImTextureID_Invalid, "the texture id must be valid") {} return jvk::heap_idx{static_cast(id - 1)}; } - /** - * @return the clip rectangle in the framebuffer, clamped to it, `std::nullopt` -> empty - * @param offset of the display - * @param scale from the display to the framebuffer - */ [[nodiscard]] constexpr std::optional to_scissor( ImVec4 const& clipRect, ImVec2 offset, @@ -232,10 +211,7 @@ namespace { }; } - /** - * creates the pipeline of the draws - * @details the config of the pipeline keeps the destroyed shaders: no second `create()` - */ + // the config of the pipeline keeps the destroyed shaders: no second `create()` [[nodiscard]] cvk::GraphicsPipeline create_pipeline( jvk::Core const& core, Imgui::Config const& config @@ -274,12 +250,6 @@ namespace { return cvk::GraphicsPipeline{core, std::move(pipelineConfig), cvk::create}; } - /** - * records the copy of every pixel of the texture data into the image - * @details - * - copies through a staging buffer, `stage` retains it - * - leaves the sampled image ready for the fragment shader - */ void copy_pixels( jvk::Stage& stage, dev::cmd_buffer auto& cmd, @@ -299,10 +269,6 @@ namespace { stage.retain(std::move(staging)); } - /** - * writes the vertices or the indices of the draw lists one after the other - * @param member `ImDrawList::VtxBuffer` or `ImDrawList::IdxBuffer` - */ template void write_lists( cvk::Buffer const& buffer, diff --git a/timgui/src/input.hpp b/timgui/src/input.hpp index 79412ba0..fa7efdd5 100644 --- a/timgui/src/input.hpp +++ b/timgui/src/input.hpp @@ -48,10 +48,10 @@ class modifier_keys { constexpr bool set(ImGuiKey key, bool down); private: - /** the left keys, then the right keys */ + // the left keys, then the right keys static constexpr size_t SIDE_KEYS = ImGuiKey_RightCtrl - ImGuiKey_LeftCtrl; - std::array _down{}; ///< from `ImGuiKey_LeftCtrl` to `ImGuiKey_RightSuper` + std::array _down{}; // from `ImGuiKey_LeftCtrl` to `ImGuiKey_RightSuper` }; /** From cb8e1b424d06fc901500aa93286f2706e2f8c7a4 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:37:56 +0100 Subject: [PATCH 44/68] docs: the quirks of private members as normal doc comments - the // comments on private declarations from 807efaf are ///< or /** */ docs, as everywhere - comments inside function bodies stay // - AGENTS.md: private members and module helpers get a doc only for a quirk the code cannot say --- AGENTS.md | 4 ++-- cvk/incl/cvk/base/core.hpp | 2 +- cvk/incl/cvk/data/buffer/base_buffer.hpp | 2 +- cvk/incl/cvk/data/descriptor/descriptor.hpp | 2 +- cvk/incl/cvk/data/descriptor/descriptor_span.hpp | 2 +- cvk/incl/cvk/surface/swapchain.hpp | 6 ++++-- cvk/incl/cvk/utility/device/device_features.hpp | 2 +- cvk/src/base/physical_device.cpp | 6 ++++-- jvk/incl/jvk/base/core.hpp | 9 +++++---- jvk/incl/jvk/base/queue.hpp | 5 ++--- jvk/incl/jvk/base/stasis.hpp | 4 ++-- jvk/incl/jvk/data/free_list.hpp | 2 +- jvk/incl/jvk/data/resource_heap.hpp | 10 +++++----- jvk/incl/jvk/data/sampler_heap.hpp | 8 ++++---- jvk/incl/jvk/graph/pending_present.hpp | 2 +- jvk/incl/jvk/graph/stage.hpp | 3 +-- jvk/incl/jvk/graph/stage_graph.hpp | 13 ++++++------- jvk/incl/jvk/graph/surface.hpp | 12 ++++++------ jvk/incl/jvk/graph/swapchain.hpp | 6 ++++-- jvk/incl/jvk/sync/family_transfer.hpp | 4 ++-- jvk/incl/jvk/sync/resource_tracker.hpp | 8 ++++---- jvk/incl/jvk/sync/timeline_reactor.hpp | 6 +++--- jvk/src/graph/stage_graph.cpp | 2 +- timgui/src/imgui.cpp | 10 +++++----- timgui/src/input.hpp | 4 ++-- 25 files changed, 69 insertions(+), 65 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f89dd3cf..37e935e0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -327,8 +327,8 @@ this code base. ``@details calls @ref Instance(Config), `wrap()` ``, `@ref create(Config const&)`. Do not write `(...)`: it does not link. - Do not document what the signature already tells. A getter without conditions needs no comment. -- Docs are for the users of the API: private members and the helpers that only the module uses get no doc, only a - `//` comment for a quirk that the code cannot say. +- Docs are for the users of the API: private members and the helpers that only the module uses get a doc only for a + quirk that the code cannot say. - The brief is the purpose. Side effects the caller must know go to `@details`. - `@details` holds one fact per line, starting with its keyword, so a reader can scan for it. No text walls. - one item: inline on the tag line: ``@details calls `optEnd()` on the secondaries`` diff --git a/cvk/incl/cvk/base/core.hpp b/cvk/incl/cvk/base/core.hpp index c55fab65..3d4900bb 100644 --- a/cvk/incl/cvk/base/core.hpp +++ b/cvk/incl/cvk/base/core.hpp @@ -189,7 +189,7 @@ class Core { std::vector uniqueQueueFamilyIndices; std::vector queuesToUniqueQueues; - // `std::nullopt` -> the config had no queue sets + /** `std::nullopt` -> the config had no queue sets */ std::optional queueSetIndex = std::nullopt; }; struct queue_set_relations { diff --git a/cvk/incl/cvk/data/buffer/base_buffer.hpp b/cvk/incl/cvk/data/buffer/base_buffer.hpp index eaa82845..2c5a6720 100644 --- a/cvk/incl/cvk/data/buffer/base_buffer.hpp +++ b/cvk/incl/cvk/data/buffer/base_buffer.hpp @@ -199,7 +199,7 @@ class BaseBuffer { std::optional _memoryOpt = std::nullopt; Config _config; size_t _size = 0; - // `0` -> the usage has no `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT` + /** `0` -> the usage has no `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT` */ VkDeviceAddress _address = 0; public: diff --git a/cvk/incl/cvk/data/descriptor/descriptor.hpp b/cvk/incl/cvk/data/descriptor/descriptor.hpp index 9cdfc019..aa4b9329 100644 --- a/cvk/incl/cvk/data/descriptor/descriptor.hpp +++ b/cvk/incl/cvk/data/descriptor/descriptor.hpp @@ -53,7 +53,7 @@ concept descriptor_of = descriptor && std::same_as, Heap>; } namespace cvk::dev { -// image descriptors with `Sampled` 2: with and without `NonWritable` +/** image descriptors with `Sampled` 2: with and without `NonWritable` */ template inline constexpr VkSpirvResourceTypeFlagsEXT resource_mask = [] { if constexpr(std::same_as) diff --git a/cvk/incl/cvk/data/descriptor/descriptor_span.hpp b/cvk/incl/cvk/data/descriptor/descriptor_span.hpp index c72f5aa6..f5a8f3b1 100644 --- a/cvk/incl/cvk/data/descriptor/descriptor_span.hpp +++ b/cvk/incl/cvk/data/descriptor/descriptor_span.hpp @@ -96,7 +96,7 @@ class DescriptorSpan::reference { reference const& operator=(Descriptor const& descriptor) const; private: - DescriptorSpan _span; // a copy: the reference outlives a temporary span + DescriptorSpan _span; ///< a copy: the reference outlives a temporary span uint32_t _idx; public: diff --git a/cvk/incl/cvk/surface/swapchain.hpp b/cvk/incl/cvk/surface/swapchain.hpp index 00a66f62..5c6e764c 100644 --- a/cvk/incl/cvk/surface/swapchain.hpp +++ b/cvk/incl/cvk/surface/swapchain.hpp @@ -287,7 +287,9 @@ class Swapchain { private: // the element wrappers: = default moves of the swapchain tear down in the member order, the // swapchain destroys its images itself, the present fences must signal before their destruction - // the destruction releases the image, it does not destroy it: the swapchain destroys its images + /** + * the destruction releases the image, it does not destroy it: the swapchain destroys its images + */ struct ReleasingImage { explicit ReleasingImage(Image image) : image{std::move(image)} {} ~ReleasingImage() { @@ -302,7 +304,7 @@ class Swapchain { ReleasingImage& operator=(ReleasingImage&& other) noexcept = default; }; - // the destruction waits for the present that signals the fence + /** the destruction waits for the present that signals the fence */ struct WaitingFence { explicit WaitingFence(Fence fence) : fence{std::move(fence)} {} ~WaitingFence() { diff --git a/cvk/incl/cvk/utility/device/device_features.hpp b/cvk/incl/cvk/utility/device/device_features.hpp index 36a0a38e..04e2b58b 100644 --- a/cvk/incl/cvk/utility/device/device_features.hpp +++ b/cvk/incl/cvk/utility/device/device_features.hpp @@ -181,7 +181,7 @@ struct DeviceFeatures { } namespace cvk::dev { -// every field of `DeviceFeatures` is a bool without padding +/** every field of `DeviceFeatures` is a bool without padding */ inline constexpr size_t FEATURE_COUNT = sizeof(DeviceFeatures); using feature_bits_t = std::array; diff --git a/cvk/src/base/physical_device.cpp b/cvk/src/base/physical_device.cpp index 46a11913..335b6c81 100644 --- a/cvk/src/base/physical_device.cpp +++ b/cvk/src/base/physical_device.cpp @@ -44,7 +44,7 @@ namespace { device_uuid_t uuid; }; - // the query includes the descriptor heap properties only with their extension + /** the query includes the descriptor heap properties only with their extension */ [[nodiscard]] queried_properties query_properties( vk_not_null vkDevice, span extensions @@ -86,7 +86,9 @@ namespace { return properties; } - // a family presents only if it presents to every surface, empty surfaces -> no present support + /** + * a family presents only if it presents to every surface, empty surfaces -> no present support + */ [[nodiscard]] vector query_queue_families( span const> surfaces, vk_not_null vkDevice diff --git a/jvk/incl/jvk/base/core.hpp b/jvk/incl/jvk/base/core.hpp index a4eae08f..eec4b23b 100644 --- a/jvk/incl/jvk/base/core.hpp +++ b/jvk/incl/jvk/base/core.hpp @@ -180,7 +180,7 @@ class Core { private: void createQueues(); - // the queues first: the driver threads run their strands + /** the queues first: the driver threads run their strands */ void destroyQueues(); Config _config; @@ -199,12 +199,13 @@ class Core { // destroyed after the queues: their strands run on it std::optional _driverSchedulerOpt{}; // destroyed before the reactor, the workers and the cvk core - std::vector _queues{}; // one per vulkan queue: the indices of one vulkan queue share it - // index in `_queues` per index of `cvk::CoreConfig::queueProperties` + /** one per vulkan queue: the indices of one vulkan queue share it */ + std::vector _queues{}; + /** index in `_queues` per index of `cvk::CoreConfig::queueProperties` */ std::vector _queueIndices{}; // destroyed before the cvk core - ResourceHeap _resourceHeap; // not created without counts, see `HeapsConfig` + ResourceHeap _resourceHeap; ///< not created without counts, see `HeapsConfig` // the sampler heap needs the created cvk core, no heap without counts std::optional _samplerHeapOpt{}; diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index 1a8cbcbb..8f2d5f60 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -211,8 +211,7 @@ class Queue { struct TransferCmd { PrimaryCmdBuffer cmd; - // free once the transfer counter reached it - uint64_t value = 0; + uint64_t value = 0; ///< free once the transfer counter reached it }; [[nodiscard]] TransferCmd& freeTransferCmd(); @@ -248,7 +247,7 @@ class Queue { } namespace jvk::dev { -// terminates on a failure other than a device loss: the waiters of the signals would hang +/** terminates on a failure other than a device loss: the waiters of the signals would hang */ [[nodiscard]] cth::co::executor_task skip_submit( Queue& queue, SubmitInfo const& info, diff --git a/jvk/incl/jvk/base/stasis.hpp b/jvk/incl/jvk/base/stasis.hpp index 7e46594e..1dc15f66 100644 --- a/jvk/incl/jvk/base/stasis.hpp +++ b/jvk/incl/jvk/base/stasis.hpp @@ -123,9 +123,9 @@ class Stasis { std::vector _handles{}; std::vector _pooledHandles{}; - // handles destroyed by `clear()`: the position of `_handles.front()` + /** handles destroyed by `clear()`: the position of `_handles.front()` */ size_t _clearedHandles = 0; - // pooled handles destroyed by `clear()`: the position of the first one + /** pooled handles destroyed by `clear()`: the position of the first one */ size_t _clearedPooledHandles = 0; public: diff --git a/jvk/incl/jvk/data/free_list.hpp b/jvk/incl/jvk/data/free_list.hpp index bb5749f9..4fbf052a 100644 --- a/jvk/incl/jvk/data/free_list.hpp +++ b/jvk/incl/jvk/data/free_list.hpp @@ -45,7 +45,7 @@ class free_list { private: uint32_t _size; - uint32_t _next = 0; // the cells from here on were never in use + uint32_t _next = 0; ///< the cells from here on were never in use std::vector _erased{}; }; } diff --git a/jvk/incl/jvk/data/resource_heap.hpp b/jvk/incl/jvk/data/resource_heap.hpp index 3577d5cc..f7246830 100644 --- a/jvk/incl/jvk/data/resource_heap.hpp +++ b/jvk/incl/jvk/data/resource_heap.hpp @@ -173,16 +173,16 @@ class ResourceHeap { template Descriptor> void erase(uint32_t idx) const; - // the caller holds `_mutexPtr` + /** the caller holds `_mutexPtr` */ template Descriptor> [[nodiscard]] dev::free_list& freeList() const; // behind a std::unique_ptr: the mutex is not movable, the moves stay = default std::unique_ptr _mutexPtr = std::make_unique(); - mutable cvk::ResourceHeap _vk; // written under `_mutexPtr` - mutable dev::free_list _sampledImages; // under `_mutexPtr` - mutable dev::free_list _storageImages; // under `_mutexPtr` - mutable dev::free_list _inputAttachments; // under `_mutexPtr` + mutable cvk::ResourceHeap _vk; ///< written under `_mutexPtr` + mutable dev::free_list _sampledImages; ///< under `_mutexPtr` + mutable dev::free_list _storageImages; ///< under `_mutexPtr` + mutable dev::free_list _inputAttachments; ///< under `_mutexPtr` public: ResourceHeap(ResourceHeap const& other) = delete; diff --git a/jvk/incl/jvk/data/sampler_heap.hpp b/jvk/incl/jvk/data/sampler_heap.hpp index 5093b2d3..5c16090d 100644 --- a/jvk/incl/jvk/data/sampler_heap.hpp +++ b/jvk/incl/jvk/data/sampler_heap.hpp @@ -90,10 +90,10 @@ class SamplerHeap { // behind a std::unique_ptr: the mutex is not movable, the moves stay = default std::unique_ptr _mutexPtr = std::make_unique(); - mutable cvk::SamplerHeap _vk; // written under `_mutexPtr` - mutable dev::free_list _cells; // under `_mutexPtr` - mutable cth::dt::flat_hash_map _indices{}; // under `_mutexPtr` - mutable std::vector _slots; // one per cell, under `_mutexPtr` + mutable cvk::SamplerHeap _vk; ///< written under `_mutexPtr` + mutable dev::free_list _cells; ///< under `_mutexPtr` + mutable cth::dt::flat_hash_map _indices{}; ///< under `_mutexPtr` + mutable std::vector _slots; ///< one per cell, under `_mutexPtr` public: SamplerHeap(SamplerHeap const& other) = delete; diff --git a/jvk/incl/jvk/graph/pending_present.hpp b/jvk/incl/jvk/graph/pending_present.hpp index a01262cd..f60a777f 100644 --- a/jvk/incl/jvk/graph/pending_present.hpp +++ b/jvk/incl/jvk/graph/pending_present.hpp @@ -127,7 +127,7 @@ class PendingPresent { [[nodiscard]] cvk::Image const& swapchainImage() const { return _swapchain->image(_imageIdx); } private: - std::unique_ptr _state; // `nullptr` -> resolved or moved from + std::unique_ptr _state; ///< `nullptr` -> resolved or moved from cth::ref_wrapper _queue; cth::ref_wrapper _swapchain; uint32_t _imageIdx; diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index 45afe177..7f50824b 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -481,8 +481,7 @@ class Stage { uint64_t _frameNumber; Status _status = Status::UNSUBMITTED; - // under `StageSlot::stasisMutex` - dev::RetainedResources _retained{}; + dev::RetainedResources _retained{}; ///< under `StageSlot::stasisMutex` public: Stage(Stage const& other) = delete; diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index e9f8446e..18c99fa8 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -190,7 +190,7 @@ class StageGraph { Stage::Status targetStatus ); - // the caller holds `_statesMutex` + /** the caller holds `_statesMutex` */ void append( ResourceTracker const& recording, Queue& queue, @@ -203,19 +203,19 @@ class StageGraph { release_map_t releases ); - // the caller holds `_statesMutex`, after `append()` + /** the caller holds `_statesMutex`, after `append()` */ void presentBarriers(dev::StageSlot&); - // throws only for a failed submit: nothing is presented or resolved then + /** throws only for a failed submit: nothing is presented or resolved then */ [[nodiscard]] cth::co::executor_task submitAndPresent( dev::StageSlot&, uint64_t frameNumber ); - // the caller holds `_statesMutex` + /** the caller holds `_statesMutex` */ void eraseStates(VkImage, uint32_t mipLevels); - // the caller holds `_statesMutex` + /** the caller holds `_statesMutex` */ void eraseStates(VkBuffer); static void endPrimary(PrimaryCmdBuffer&); @@ -225,8 +225,7 @@ class StageGraph { std::deque _frameSlots{}; - // locks `_states`, `_imageQueues` and `_bufferQueues` - std::mutex _statesMutex{}; + std::mutex _statesMutex{}; ///< locks `_states`, `_imageQueues` and `_bufferQueues` ResourceTracker _states{}; diff --git a/jvk/incl/jvk/graph/surface.hpp b/jvk/incl/jvk/graph/surface.hpp index fd93c8eb..7ed0ee37 100644 --- a/jvk/incl/jvk/graph/surface.hpp +++ b/jvk/incl/jvk/graph/surface.hpp @@ -218,8 +218,10 @@ class Surface { } private: - // a recreation erases the old images in the graph first: the new images can reuse their - // handles; only when no present uses the swapchain + /** + * a recreation erases the old images in the graph first: the new images can reuse their handles + * only when no present uses the swapchain + */ void updateSwapchain(VkExtent2D extent, StageGraph* graphPtr); [[nodiscard]] Swapchain::Config swapchainConfig() const; @@ -231,8 +233,7 @@ class Surface { // destroyed after the swapchain cvk::Surface _surface; - // the resolve of the last image orders its uses - Swapchain _swapchain; + Swapchain _swapchain; ///< the resolve of the last image orders its uses std::vector _acquireSemaphores{}; @@ -240,8 +241,7 @@ class Surface { dev::PresentState _presentState{}; - // `0` -> none - uint64_t _lastValue = 0; + uint64_t _lastValue = 0; ///< `0` -> none uint32_t _lastImageIdx = 0; diff --git a/jvk/incl/jvk/graph/swapchain.hpp b/jvk/incl/jvk/graph/swapchain.hpp index 34926c9a..427fa16f 100644 --- a/jvk/incl/jvk/graph/swapchain.hpp +++ b/jvk/incl/jvk/graph/swapchain.hpp @@ -121,8 +121,10 @@ class Swapchain { cth::ref_wrapper _presentQueue; cth::ref_wrapper _surface; - // `back()` is the current swapchain, the others are retired, the oldest first; a deque: the - // addresses stay at the end + /** + * `back()` is the current swapchain, the others are retired, the oldest first + * a deque: the addresses stay at the end + */ std::deque _swapchains{}; public: diff --git a/jvk/incl/jvk/sync/family_transfer.hpp b/jvk/incl/jvk/sync/family_transfer.hpp index f401c9f1..3b8ce79a 100644 --- a/jvk/incl/jvk/sync/family_transfer.hpp +++ b/jvk/incl/jvk/sync/family_transfer.hpp @@ -10,7 +10,7 @@ namespace jvk::dev { -// waits for the release wait of the submit +/** waits for the release wait of the submit */ constexpr cvk::BarrierScope ACQUIRE_SRC{.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}; [[nodiscard]] constexpr cvk::ImageBarrierInfo release_half( @@ -31,7 +31,7 @@ constexpr cvk::BarrierScope ACQUIRE_SRC{.stages = VK_PIPELINE_STAGE_2_ALL_COMMAN }; } -// the layouts of `release_half()`: both halves of a transfer have the same layouts +/** the layouts of `release_half()`: both halves of a transfer have the same layouts */ [[nodiscard]] constexpr cvk::ImageBarrierInfo acquire_half( ImageState const& last, ImageState const& first, diff --git a/jvk/incl/jvk/sync/resource_tracker.hpp b/jvk/incl/jvk/sync/resource_tracker.hpp index c6857db6..fe2af4c1 100644 --- a/jvk/incl/jvk/sync/resource_tracker.hpp +++ b/jvk/incl/jvk/sync/resource_tracker.hpp @@ -256,22 +256,22 @@ class ResourceTracker { VkImageAspectFlags aspectMask; VkSharingMode sharingMode; - // `std::nullopt` -> `assume()` before the first access + /** `std::nullopt` -> `assume()` before the first access */ std::optional firstOpt; ImageState last; bool discard = false; - bool barrier = false; // a barrier or `assume()` after the first use: `firstOpt` is final + bool barrier = false; ///< a barrier or `assume()` after the first use: `firstOpt` is final }; struct buffer_states { VkSharingMode sharingMode; - // `std::nullopt` -> `assume()` before the first access + /** `std::nullopt` -> `assume()` before the first access */ std::optional firstOpt; BufferState last; - bool barrier = false; // a barrier or `assume()` after the first use: `firstOpt` is final + bool barrier = false; ///< a barrier or `assume()` after the first use: `firstOpt` is final }; cth::dt::flat_hash_map _images{}; diff --git a/jvk/incl/jvk/sync/timeline_reactor.hpp b/jvk/incl/jvk/sync/timeline_reactor.hpp index 689ff5b2..5c7e04a3 100644 --- a/jvk/incl/jvk/sync/timeline_reactor.hpp +++ b/jvk/incl/jvk/sync/timeline_reactor.hpp @@ -104,13 +104,13 @@ class TimelineReactor { void run(std::stop_token); - // the caller holds `_mutexPtr` + /** the caller holds `_mutexPtr` */ void wake() const; - // the caller holds `_mutexPtr` + /** the caller holds `_mutexPtr` */ void fail(std::error_code, std::vector>& waiters) const; - // the caller holds no lock of the reactor + /** the caller holds no lock of the reactor */ static void post(std::span const> waiters); mutable cvk::TimelineSemaphore _wake; diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index 9d802f95..9139b2b9 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -43,7 +43,7 @@ namespace { .scope = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, }; - // `src` waits for the stages of the first use, no access: like `cvk::layout_transition()` + /** `src` waits for the stages of the first use, no access: like `cvk::layout_transition()` */ [[nodiscard]] constexpr cvk::ImageBarrierInfo from_undefined( ImageState const& first, uint32_t mipLevel diff --git a/timgui/src/imgui.cpp b/timgui/src/imgui.cpp index f053d166..e5b92409 100644 --- a/timgui/src/imgui.cpp +++ b/timgui/src/imgui.cpp @@ -45,7 +45,7 @@ namespace timgui::dev { namespace { - // one `Frame` in the program: ImGui keeps the current context in a global + /** one `Frame` in the program: ImGui keeps the current context in a global */ bool frameExists = false; } @@ -130,7 +130,7 @@ struct ImguiState { namespace timgui { namespace { - constexpr float FIRST_DELTA_TIME = 1.f / 60.f; // seconds, ImGui needs a positive time + constexpr float FIRST_DELTA_TIME = 1.f / 60.f; ///< seconds, ImGui needs a positive time constexpr cvk::ImageConfig TEXTURE_CONFIG{ .format = VK_FORMAT_R8G8B8A8_UNORM, @@ -159,7 +159,7 @@ namespace { .maxAnisotropy = 0.f, }; - // the alpha of the attachment gets the coverage of the draws + /** the alpha of the attachment gets the coverage of the draws */ constexpr VkPipelineColorBlendAttachmentState BLENDING{ .blendEnable = VK_TRUE, .srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA, @@ -180,7 +180,7 @@ namespace { ImPlot::SetCurrentContext(state.plotContext.get()); } - // `+ 1`: `ImTextureID_Invalid` is `0`, the heap index `0` is a valid cell + /** `+ 1`: `ImTextureID_Invalid` is `0`, the heap index `0` is a valid cell */ [[nodiscard]] constexpr ImTextureID to_texture_id(jvk::heap_idx idx) { return ImTextureID{idx.get()} + 1; } @@ -211,7 +211,7 @@ namespace { }; } - // the config of the pipeline keeps the destroyed shaders: no second `create()` + /** the config of the pipeline keeps the destroyed shaders: no second `create()` */ [[nodiscard]] cvk::GraphicsPipeline create_pipeline( jvk::Core const& core, Imgui::Config const& config diff --git a/timgui/src/input.hpp b/timgui/src/input.hpp index fa7efdd5..79412ba0 100644 --- a/timgui/src/input.hpp +++ b/timgui/src/input.hpp @@ -48,10 +48,10 @@ class modifier_keys { constexpr bool set(ImGuiKey key, bool down); private: - // the left keys, then the right keys + /** the left keys, then the right keys */ static constexpr size_t SIDE_KEYS = ImGuiKey_RightCtrl - ImGuiKey_LeftCtrl; - std::array _down{}; // from `ImGuiKey_LeftCtrl` to `ImGuiKey_RightSuper` + std::array _down{}; ///< from `ImGuiKey_LeftCtrl` to `ImGuiKey_RightSuper` }; /** From ded06c79e0e97dcabb457b851179baea66738bcf Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:21:06 +0100 Subject: [PATCH 45/68] lib: cth with CTH_CRITICAL_MODE and scoped detaches without the scheduler registry --- lib/cth | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/cth b/lib/cth index 329aee48..1c737209 160000 --- a/lib/cth +++ b/lib/cth @@ -1 +1 @@ -Subproject commit 329aee4828e4d3a7b1d99567335c54562c493942 +Subproject commit 1c737209c8340a7868a5ffef5bfbe9975ea8b179 From 2393ad7fe8e7e2335dc4039bd0f54c0ac92b1c74 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:21:06 +0100 Subject: [PATCH 46/68] jvk: Surface::acquire() checks that the present stage waits for the acquire stage - StageGraphConfig::waitsFor(): a wait in the same frame, directly or through other stages - a CTH_CRITICAL in acquire(), the @pre stays in the docs - [[gnu::pure]] on the recursive walk: gcc and clang drop it in release --- jvk/incl/jvk/graph/stage_graph_config.hpp | 18 +++++++++++++++++ jvk/src/graph/surface.cpp | 8 ++++++++ jvk/tests/src/graph/stage_graph_test.cpp | 17 ++++++++++++++++ jvk/tests/src/graph/surface_test.cpp | 24 +++++++++++++++++++++++ 4 files changed, 67 insertions(+) diff --git a/jvk/incl/jvk/graph/stage_graph_config.hpp b/jvk/incl/jvk/graph/stage_graph_config.hpp index 4b880426..44c28311 100644 --- a/jvk/incl/jvk/graph/stage_graph_config.hpp +++ b/jvk/incl/jvk/graph/stage_graph_config.hpp @@ -50,6 +50,15 @@ struct StageGraphConfig { */ size_t frameSlots = 2; + /** + * checks if a stage waits for another stage in the frame, directly or through other stages + * @details only the waits with `frameOffset == 0` + * @param waiterId id of the waiting stage + * @param waitedId id of the waited stage + * @pre `debug_check()` passes + */ + [[nodiscard, gnu::pure]] constexpr bool waitsFor(size_t waiterId, size_t waitedId) const; + /** * checks the config * @details checks: @@ -61,6 +70,15 @@ struct StageGraphConfig { } namespace jvk { +constexpr bool StageGraphConfig::waitsFor(size_t waiterId, size_t waitedId) const { + // gnu::pure: a release CTH_CRITICAL drops the call, the compilers do not prove that a + // recursion returns + for(auto const& wait : stages[waiterId].waits) + if(wait.frameOffset == 0 && (wait.stageId == waitedId || waitsFor(wait.stageId, waitedId))) + return true; + return false; +} + constexpr void StageGraphConfig::debug_check(StageGraphConfig const& config) { CTH_CRITICAL(config.frameSlots == 0, "frameSlots must be > 0") {} diff --git a/jvk/src/graph/surface.cpp b/jvk/src/graph/surface.cpp index 9ada57de..341d84b0 100644 --- a/jvk/src/graph/surface.cpp +++ b/jvk/src/graph/surface.cpp @@ -107,6 +107,14 @@ cth::co::executor_task> Surface::acquire( || acquireStage.frameNumber() != presentStage.frameNumber(), "the acquire stage and the present stage must belong to one frame of one graph" ) {} + CTH_CRITICAL( + presentStage.id() != acquireStage.id() + && !acquireStage.graph().config().waitsFor(presentStage.id(), acquireStage.id()), + "the present stage must be the acquire stage or wait for it in the frame, got present {}, " + "acquire {}", + presentStage.id(), + acquireStage.id() + ) {} // the last image first: the acquire and the present share the swapchain (externally // synchronized), a blocking acquire before that present would delay it (FIFO) diff --git a/jvk/tests/src/graph/stage_graph_test.cpp b/jvk/tests/src/graph/stage_graph_test.cpp index a55af238..8e950aa4 100644 --- a/jvk/tests/src/graph/stage_graph_test.cpp +++ b/jvk/tests/src/graph/stage_graph_test.cpp @@ -173,6 +173,23 @@ namespace { } } +JVK_TEST(StageGraphConfig, waits_for_directly_or_through_other_stages) { + // 2 waits for 1, 1 waits for 0, 3 waits for 2 in the previous frame + static_assert([] { + //TEMP not const: gcc 16 rejects a const aggregate with a vector and another member in a constant expression + StageGraph::Config config{ + .stages = { + {.queueIdx = 0}, + {.queueIdx = 0, .waits = {{.stageId = 0}}}, + {.queueIdx = 0, .waits = {{.stageId = 1}}}, + {.queueIdx = 0, .waits = {{.stageId = 2, .frameOffset = 1}}}, + }, + }; + return config.waitsFor(1, 0) && config.waitsFor(2, 0) && !config.waitsFor(0, 2) + && !config.waitsFor(3, 2) && !config.waitsFor(0, 0); + }()); +} + JVK_TEST(StageGraph, first_frame_number_is_above_the_largest_frame_offset) { test::Context const context{}; Core core{context.instance, test::Context::CONFIG, {}}; diff --git a/jvk/tests/src/graph/surface_test.cpp b/jvk/tests/src/graph/surface_test.cpp index 0a170928..840ad5ab 100644 --- a/jvk/tests/src/graph/surface_test.cpp +++ b/jvk/tests/src/graph/surface_test.cpp @@ -906,6 +906,30 @@ JVK_TEST(Surface, acquire_for_a_submitted_present_stage_crashes) { ); frame[SCENE].skip(); } + +JVK_TEST(Surface, acquire_for_a_present_stage_that_does_not_wait_for_the_acquire_stage_crashes) { + // the child runs the test again: the parent has device threads + GTEST_FLAG_SET(death_test_style, "threadsafe"); + test::Context const context{}; + auto windowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, windowSurface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, scene_and_ui()}; + + // the scene stage does not wait for the ui stage + auto& frame = next_frame(core, graph); + ASSERT_DEATH( + [[maybe_unused]] + auto const image = acquire(core, surface, frame[UI], frame[SCENE]), + "the present stage must be the acquire stage or wait for it" + ); + frame[SCENE].skip(); + frame[UI].skip(); +} #endif JVK_TEST(Surface, present_queue_of_the_same_family) { From ed2b4b25ab0c62520cb0c750d0775e85a4b85182 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:40:49 +0100 Subject: [PATCH 47/68] jvk: the check of the present stage's wait in Surface::acquire() goes again - reverts 2393ad7: a member function that exists only for a check makes it no normal check - the @pre in the docs of acquire() stays, the cheap checks stay --- jvk/incl/jvk/graph/stage_graph_config.hpp | 18 ----------------- jvk/src/graph/surface.cpp | 8 -------- jvk/tests/src/graph/stage_graph_test.cpp | 17 ---------------- jvk/tests/src/graph/surface_test.cpp | 24 ----------------------- 4 files changed, 67 deletions(-) diff --git a/jvk/incl/jvk/graph/stage_graph_config.hpp b/jvk/incl/jvk/graph/stage_graph_config.hpp index 44c28311..4b880426 100644 --- a/jvk/incl/jvk/graph/stage_graph_config.hpp +++ b/jvk/incl/jvk/graph/stage_graph_config.hpp @@ -50,15 +50,6 @@ struct StageGraphConfig { */ size_t frameSlots = 2; - /** - * checks if a stage waits for another stage in the frame, directly or through other stages - * @details only the waits with `frameOffset == 0` - * @param waiterId id of the waiting stage - * @param waitedId id of the waited stage - * @pre `debug_check()` passes - */ - [[nodiscard, gnu::pure]] constexpr bool waitsFor(size_t waiterId, size_t waitedId) const; - /** * checks the config * @details checks: @@ -70,15 +61,6 @@ struct StageGraphConfig { } namespace jvk { -constexpr bool StageGraphConfig::waitsFor(size_t waiterId, size_t waitedId) const { - // gnu::pure: a release CTH_CRITICAL drops the call, the compilers do not prove that a - // recursion returns - for(auto const& wait : stages[waiterId].waits) - if(wait.frameOffset == 0 && (wait.stageId == waitedId || waitsFor(wait.stageId, waitedId))) - return true; - return false; -} - constexpr void StageGraphConfig::debug_check(StageGraphConfig const& config) { CTH_CRITICAL(config.frameSlots == 0, "frameSlots must be > 0") {} diff --git a/jvk/src/graph/surface.cpp b/jvk/src/graph/surface.cpp index 341d84b0..9ada57de 100644 --- a/jvk/src/graph/surface.cpp +++ b/jvk/src/graph/surface.cpp @@ -107,14 +107,6 @@ cth::co::executor_task> Surface::acquire( || acquireStage.frameNumber() != presentStage.frameNumber(), "the acquire stage and the present stage must belong to one frame of one graph" ) {} - CTH_CRITICAL( - presentStage.id() != acquireStage.id() - && !acquireStage.graph().config().waitsFor(presentStage.id(), acquireStage.id()), - "the present stage must be the acquire stage or wait for it in the frame, got present {}, " - "acquire {}", - presentStage.id(), - acquireStage.id() - ) {} // the last image first: the acquire and the present share the swapchain (externally // synchronized), a blocking acquire before that present would delay it (FIFO) diff --git a/jvk/tests/src/graph/stage_graph_test.cpp b/jvk/tests/src/graph/stage_graph_test.cpp index 8e950aa4..a55af238 100644 --- a/jvk/tests/src/graph/stage_graph_test.cpp +++ b/jvk/tests/src/graph/stage_graph_test.cpp @@ -173,23 +173,6 @@ namespace { } } -JVK_TEST(StageGraphConfig, waits_for_directly_or_through_other_stages) { - // 2 waits for 1, 1 waits for 0, 3 waits for 2 in the previous frame - static_assert([] { - //TEMP not const: gcc 16 rejects a const aggregate with a vector and another member in a constant expression - StageGraph::Config config{ - .stages = { - {.queueIdx = 0}, - {.queueIdx = 0, .waits = {{.stageId = 0}}}, - {.queueIdx = 0, .waits = {{.stageId = 1}}}, - {.queueIdx = 0, .waits = {{.stageId = 2, .frameOffset = 1}}}, - }, - }; - return config.waitsFor(1, 0) && config.waitsFor(2, 0) && !config.waitsFor(0, 2) - && !config.waitsFor(3, 2) && !config.waitsFor(0, 0); - }()); -} - JVK_TEST(StageGraph, first_frame_number_is_above_the_largest_frame_offset) { test::Context const context{}; Core core{context.instance, test::Context::CONFIG, {}}; diff --git a/jvk/tests/src/graph/surface_test.cpp b/jvk/tests/src/graph/surface_test.cpp index 840ad5ab..0a170928 100644 --- a/jvk/tests/src/graph/surface_test.cpp +++ b/jvk/tests/src/graph/surface_test.cpp @@ -906,30 +906,6 @@ JVK_TEST(Surface, acquire_for_a_submitted_present_stage_crashes) { ); frame[SCENE].skip(); } - -JVK_TEST(Surface, acquire_for_a_present_stage_that_does_not_wait_for_the_acquire_stage_crashes) { - // the child runs the test again: the parent has device threads - GTEST_FLAG_SET(death_test_style, "threadsafe"); - test::Context const context{}; - auto windowSurface = test::headless_surface(context.instance); - std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, windowSurface)) - GTEST_SKIP() << "no device presents to a headless surface"; - auto& core = *coreOpt; - - Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; - StageGraph graph{core, scene_and_ui()}; - - // the scene stage does not wait for the ui stage - auto& frame = next_frame(core, graph); - ASSERT_DEATH( - [[maybe_unused]] - auto const image = acquire(core, surface, frame[UI], frame[SCENE]), - "the present stage must be the acquire stage or wait for it" - ); - frame[SCENE].skip(); - frame[UI].skip(); -} #endif JVK_TEST(Surface, present_queue_of_the_same_family) { From af46d31746c5b58f4ac804db5615152bf6617d05 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:40:49 +0100 Subject: [PATCH 48/68] lib: cth with the TODO for [[assume]] in CTH_CRITICAL --- lib/cth | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/cth b/lib/cth index 1c737209..d94d093a 160000 --- a/lib/cth +++ b/lib/cth @@ -1 +1 @@ -Subproject commit 1c737209c8340a7868a5ffef5bfbe9975ea8b179 +Subproject commit d94d093a4c1d8fe95e4219f5207728facc1995ec From 0f078495616acf8bb9a3843fe59b5fe6346fc243 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:23:53 +0100 Subject: [PATCH 49/68] jvk: the jobs of the graph are submissions, a submission waits for the gpu only to free something - submitJob() is submission(), detachJob() is detachSubmission(), _jobs is _submissions, the parameters and docs follow - the gpu wait and the cleanup run only if the submission retained images, buffers or stasis entries, then as early as before; else the submission ends after its submit - Stasis::empty(pos): nothing before the position to clear - per frame (headless MAILBOX, 2 workers): mutex locks 18 -> 14 --- jvk/incl/jvk/base/queue.hpp | 4 +- jvk/incl/jvk/base/stasis.hpp | 9 ++++ jvk/incl/jvk/graph/pending_present.hpp | 2 +- jvk/incl/jvk/graph/stage.hpp | 54 ++++++++++--------- jvk/incl/jvk/graph/stage_graph.hpp | 35 +++++++------ jvk/incl/jvk/graph/surface.hpp | 6 +-- jvk/src/base/queue.cpp | 4 +- jvk/src/graph/stage.cpp | 8 +-- jvk/src/graph/stage_graph.cpp | 67 ++++++++++++++---------- jvk/src/graph/surface.cpp | 2 +- jvk/tests/src/base/queue_test.cpp | 6 +-- jvk/tests/src/graph/stage_graph_test.cpp | 25 +++++---- jvk/tests/src/graph/surface_test.cpp | 13 ++--- 13 files changed, 130 insertions(+), 105 deletions(-) diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index 8f2d5f60..a2f7a242 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -150,7 +150,7 @@ class Queue { std::span results ); - // an executor_task: the receiving submit job awaits it before its own submit, so the transfer + // an executor_task: the receiving submission awaits it before its own submit, so the transfer // is submitted first and the counter only changes in the strand (returning at once needs a lock // around the value and the post) // returns the jvk SemaphoreSubmitInfo: it keeps the counter for Semaphore::submitted(), it @@ -251,6 +251,6 @@ namespace jvk::dev { [[nodiscard]] cth::co::executor_task skip_submit( Queue& queue, SubmitInfo const& info, - cth::co::catching_scope& jobs + cth::co::catching_scope& submissions ); } diff --git a/jvk/incl/jvk/base/stasis.hpp b/jvk/incl/jvk/base/stasis.hpp index 1dc15f66..02332c42 100644 --- a/jvk/incl/jvk/base/stasis.hpp +++ b/jvk/incl/jvk/base/stasis.hpp @@ -110,6 +110,15 @@ class Stasis { return _handles.empty() && _pooledHandles.empty(); } + /** + * checks if the handles before the position are destroyed: `clear()` with it destroys nothing + * @pre `position` comes from `end()` of this stasis + */ + [[nodiscard]] constexpr bool empty(pos const& position) const { + return position.handles <= _clearedHandles + && position.pooledHandles <= _clearedPooledHandles; + } + [[nodiscard]] constexpr cvk::DeviceTable table() const { return _table; } [[nodiscard]] constexpr VmaAllocator allocator() const { return _vmaAllocator; } diff --git a/jvk/incl/jvk/graph/pending_present.hpp b/jvk/incl/jvk/graph/pending_present.hpp index f60a777f..56e35385 100644 --- a/jvk/incl/jvk/graph/pending_present.hpp +++ b/jvk/incl/jvk/graph/pending_present.hpp @@ -68,7 +68,7 @@ struct present_dropper { * present of an acquired swapchain image after the submit of its present stage * @details * - `Surface::acquire()` hands it to the present stage, see `Stage::present()` - * - the submit job of the present stage presents the image, a skip drops it + * - the submission of the present stage presents the image, a skip drops it * - resolves the image exactly once: `present()`, `drop()`, or its destruction as dropped * - destroyed pending: only after the gpu finished the stages that used the image, e.g. in * `~StageGraph()`, or before a stage submitted a use of it diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index 7f50824b..b0ec5de0 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -52,7 +52,7 @@ struct SlotSubmit { /** `StageSlot::prologue`, `StageSlot::primary`, `StageSlot::epilogue` */ std::vector> cmdBuffers{}; - // no queueWaits: the submit job awaits the marks of every wait, its append follows the + // no queueWaits: the submission awaits the marks of every wait, its append follows the // dependency order /** * one per `StageConfig::waits`: `StageSlot::semaphore` of the waited stage slot @@ -88,14 +88,14 @@ struct SlotSubmit { /** * advances every wait and signal value to the next frame of the slot - * @details never reads the waited semaphores: their submit jobs run at the same time, a read can see an old frame + * @details never reads the waited semaphores: their submissions run at the same time, a read can see an old frame * @param frameSlots `StageGraphConfig::frameSlots`, the values rise by it */ constexpr void next(size_t frameSlots); }; /** - * the images of one queue in the presents of a submit job + * the images of one queue in the presents of a submission * @see `StageSlot::presentImages` */ struct PresentGroup { @@ -110,7 +110,7 @@ struct PresentGroup { /** * the images and buffers of `Stage::retain()` in one frame - * @details the submit job erases their graph states before it destroys them, see `StageGraph::erase()` + * @details the submission erases their graph states before it destroys them, see `StageGraph::erase()` */ struct RetainedResources { /** the handle and the mip levels of each image */ @@ -140,7 +140,7 @@ struct StageSlot { */ StageSlot( StageGraph& graph, - cth::co::catching_scope& jobs, + cth::co::catching_scope& submissions, size_t stageId, size_t slot, Queue& queue, @@ -149,8 +149,8 @@ struct StageSlot { cth::ref_wrapper graph; - /** the jobs of the graph, the scopes of the stages store their errors into it */ - cth::ref_wrapper jobs; + /** the submissions of the graph, the scopes of the stages store their errors into it */ + cth::ref_wrapper submissions; size_t stageId; ///< id of the stage, see `StageGraphConfig::stages` @@ -178,15 +178,15 @@ struct StageSlot { // the next three in the stage slot, not in the stage: they keep their capacity for the next // frames of the slot // one list per kind of wait: the jvk waits keep the jvk semaphore - /** the jvk waits of `Stage::await()` in the frame of the slot, the submit job clears them */ + /** the jvk waits of `Stage::await()` in the frame of the slot, the submission clears them */ std::vector extraWaits{}; - /** the binary waits of `Stage::await()` in the frame of the slot, the submit job clears them */ + /** the binary waits of `Stage::await()` in the frame of the slot, the submission clears them */ std::vector extraBinaryWaits{}; /** * the presents of the frame of the slot, see `Stage::present()` - * @details the submit job presents them after the submit or drops them on a skip, then + * @details the submission presents them after the submit or drops them on a skip, then * clears the list */ std::vector presents{}; @@ -194,13 +194,13 @@ struct StageSlot { /** * the submit or the skip of the frame of the slot * @details - * - the submit job fills it, see `SlotSubmit::skipInfo()` - * - one job at a time: `StageGraph::nextFrame()` hands out the slot again after - * `StageSlot::submitDone` of the job + * - the submission fills it, see `SlotSubmit::skipInfo()` + * - one submission at a time: `StageGraph::nextFrame()` hands out the slot again after + * `StageSlot::submitDone` of the submission */ SubmitInfo submitInfo{}; - // the scratch of the presents: the submit job refills them, they keep their capacity + // the scratch of the presents: the submission refills them, they keep their capacity /** the barriers of the presented images, recorded into `StageSlot::epilogue` */ cvk::Barrier epilogueBarriers{}; @@ -218,7 +218,8 @@ struct StageSlot { std::vector presentSignals{}; /** - * frame number of the last job of the slot that ended its submit or skip and its presents + * frame number of the last submission of the slot that ended its submit or skip and its + * presents * @details `StageGraph::nextFrame()` awaits it before it hands out the slot again * @details initial value: `StageGraph::firstFrameNumber() - 1` */ @@ -243,7 +244,8 @@ struct StageSlot { /** * the objects of `Stage::retain()` - * @details the job of a frame destroys them up to the `Stasis::end()` of its submit or skip + * @details the submission of a frame destroys them up to the `Stasis::end()` of its submit or + * skip */ Stasis stasis; @@ -332,7 +334,7 @@ class Stage { /** * adds a wait on a jvk semaphore to the submit of this frame - * @details `submit()` and `skip()` wait for it, the submit job first awaits its `Semaphore::submitted()` + * @details `submit()` and `skip()` wait for it, the submission first awaits its `Semaphore::submitted()` * @pre `status()` is `UNSUBMITTED` * @pre the semaphore lives until the gpu finished the submit * @attention not thread safe @@ -379,12 +381,12 @@ class Stage { /** * presents the swapchain image of the present after the submit of this frame * @details `Surface::acquire()` calls it for its present stage - * @details the submit job of the frame: + * @details the submission of the frame: * - records the barrier of the image to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` into the epilogue, * after the primary, see `StageSlot::epilogue` * - presents the image after the submit, the images of one queue in one `vkQueuePresentKHR()` * - a skip or a failed submit drops the image - * @param present of the image, the stage owns it until its job resolves it + * @param present of the image, the stage owns it until its submission resolves it * @pre `status()` is `UNSUBMITTED` * @attention not thread safe */ @@ -409,7 +411,7 @@ class Stage { * @details * - releases the object at once, the stasis of the stage slot holds its handles * - the recordings keep no reference to the object: the caller can destroy it - * - an image or a buffer: the job erases its graph state before it destroys it + * - an image or a buffer: the submission erases its graph state before it destroys it * - thread safe * @pre `status()` is `UNSUBMITTED` * @pre its users on other queues finish before this submit: this submit waits for them @@ -505,17 +507,17 @@ namespace jvk { */ class scoped_submit { public: - //TODO review the jobs of the graph as a parameter: scoped_submit is no nested class, - // Stage::begin() hands it the jobs of the graph from its stage slot + //TODO review the submissions of the graph as a parameter: scoped_submit is no nested class, + // Stage::begin() hands it the submissions of the graph from its stage slot /** * @details the uncaught exceptions of the calling thread at the construction tell the exception at the end * @param stage with the begun primary - * @param jobs of the graph, gets a failure of the submit at the end + * @param submissions of the graph, gets a failure of the submit at the end * @pre `Stage::begin()` began the primary */ - scoped_submit(Stage& stage, cth::co::catching_scope& jobs) noexcept : + scoped_submit(Stage& stage, cth::co::catching_scope& submissions) noexcept : _stagePtr{&stage}, - _jobs{jobs}, + _submissions{submissions}, _uncaughtExceptions{std::uncaught_exceptions()} {} ~scoped_submit(); @@ -525,7 +527,7 @@ class scoped_submit { private: cth::move_ptr _stagePtr; - cth::ref_wrapper _jobs; + cth::ref_wrapper _submissions; int _uncaughtExceptions; public: diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index 18c99fa8..57ec69cf 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -66,23 +66,23 @@ class StageGraph { * @details * - skips the unsubmitted stages first, e.g. after an exception in their recording: their waiters go on * - the skip drops the presents of the stage, see `Surface::acquire()` - * - waits for the end of every submit job + * - waits for the end of every submission * - a failed skip or wait does not stop the destruction - * @attention blocks the calling thread: a worker of the core must be free for the jobs + * @attention blocks the calling thread: a worker of the core must be free for the submissions */ ~StageGraph(); - // awaits Stage::submitted() of the old frame: the gpu can finish before the graph job marks the - // submit + // awaits Stage::submitted() of the old frame: the gpu can finish before the submission marks + // the submit /** * constructs the frame and its stages in the next slot * @details the frame before: skips its stages without `Stage::submit()` or `Stage::skip()`, warns for a waited one - * @details the old frame of the slot: awaits `StageSlot::submitDone` of its stages: their jobs - * ended the submits and the presents, then the stages: the gpu finished them, both with - * `cth::co::all()` + * @details the old frame of the slot: awaits `StageSlot::submitDone` of its stages: their + * submissions ended the submits and the presents, then the stages: the gpu finished them, both + * with `cth::co::all()` * @return the frame of the slot * @pre no stage of the frame before records or submits: `nextFrame()` ends the frame - * @throws std::exception the first error of a submit job or a scope, stored before the call: an + * @throws std::exception the first error of a submission or a scope, stored before the call: an * error during the waits -> the next `nextFrame()` rethrows it, see `cth::co::catching_scope` * @throws cth::except::group_coro_exception reason: the wait for a stage of the old frame * failed, after the waits for all its stages: `exceptions()` holds the @@ -135,7 +135,7 @@ class StageGraph { * @details * - the first use of the next submit starts from the state * - thread safe - * @pre the jobs of the submits before that use the image appended their states: they are marked + * @pre the submissions before that use the image appended their states: they are marked * @see `ResourceTracker::assume()` */ void assume(cvk::Image const&, ImageState const& state); @@ -176,13 +176,13 @@ class StageGraph { void skipUnsubmitted(dev::FrameSlot&); //TODO review one helper for submit() and skip(): they differ in the status only - void detachJob(Stage&, Stage::Status targetStatus); + void detachSubmission(Stage&, Stage::Status targetStatus); - // no marks as parameters: the job awaits Semaphore::submitted() of the slots, they live as - // long as the graph - // next() before the mark: the job of the next frame of the slot awaits the mark, it reads the - // values - [[nodiscard]] cth::co::executor_task submitJob( + // no marks as parameters: the submission awaits Semaphore::submitted() of the slots, they live + // as long as the graph + // next() before the mark: the submission of the next frame of the slot awaits the mark, it + // reads the values + [[nodiscard]] cth::co::executor_task submission( dev::StageSlot&, uint64_t frameNumber, dev::RetainedResources retained, @@ -233,8 +233,9 @@ class StageGraph { last_queue_map_t _bufferQueues{}; - //TODO review the error stays: every nextFrame() rethrows it, the errors of the jobs are fatal - cth::co::catching_scope _jobs{}; + //TODO review the error stays: every nextFrame() rethrows it, the errors of the submissions are + // fatal + cth::co::catching_scope _submissions{}; uint64_t _firstFrameNumber; diff --git a/jvk/incl/jvk/graph/surface.hpp b/jvk/incl/jvk/graph/surface.hpp index 7ed0ee37..63229f58 100644 --- a/jvk/incl/jvk/graph/surface.hpp +++ b/jvk/incl/jvk/graph/surface.hpp @@ -78,7 +78,7 @@ struct SurfaceConfig { * `Swapchain` * - acquires outside the strand of its queue on `Queue::scheduler()` * - the present stage of an image presents it after its submit, see `acquire()`: the surface has - * no jobs, the errors of the presents go to the graph of the present stage + * no submissions, the errors of the presents go to the graph of the present stage * - one acquired image at a time: `acquire()` waits until the last image is presented or dropped * - a dropped image: the next `acquire()` or `destroy()` unacquires it after the gpu finished its * stages @@ -133,8 +133,8 @@ class Surface { * @pre the present stage of the last image is submitted or skipped, or its graph is destroyed: * else the wait never ends, e.g. destroy the graphs of the stages first * @pre the submits that wait for the acquire semaphores finished on the gpu - * @attention blocks the calling thread: a worker of the core must be free for the jobs of the - * graph + * @attention blocks the calling thread: a worker of the core must be free for the submissions + * of the graph */ void destroy(); diff --git a/jvk/src/base/queue.cpp b/jvk/src/base/queue.cpp index 50dab450..c0fbe6e0 100644 --- a/jvk/src/base/queue.cpp +++ b/jvk/src/base/queue.cpp @@ -201,7 +201,7 @@ namespace dev { cth::co::executor_task skip_submit( Queue& queue, SubmitInfo const& info, - cth::co::catching_scope& jobs + cth::co::catching_scope& submissions ) { // every failure but a device loss terminates: nobody marks the signals, the waiters would // hang @@ -211,7 +211,7 @@ namespace dev { JVK_STABLE_ERR(true, "the skip submit failed, got {}", e.vkResult()) {} std::terminate(); } - jobs.store(std::current_exception()); + submissions.store(std::current_exception()); // the failed submit marked nothing: the waiters of the marks go on mark(info.signals); } diff --git a/jvk/src/graph/stage.cpp b/jvk/src/graph/stage.cpp index 405a8bfe..f6035ee4 100644 --- a/jvk/src/graph/stage.cpp +++ b/jvk/src/graph/stage.cpp @@ -59,14 +59,14 @@ void SlotSubmit::addCmdBuffers(SubmitInfo& info, bool prologue, bool epilogue) c StageSlot::StageSlot( StageGraph& graph, - cth::co::catching_scope& jobs, + cth::co::catching_scope& submissions, size_t stageId, size_t slot, Queue& queue, size_t secondaries ) : graph{graph}, - jobs{jobs}, + submissions{submissions}, stageId{stageId}, slot{slot}, queue{queue}, @@ -104,7 +104,7 @@ scoped_submit Stage::begin() { if(samplerHeapPtr != nullptr) vk.bind(*samplerHeapPtr); - return scoped_submit{*this, _stageSlot->jobs}; + return scoped_submit{*this, _stageSlot->submissions}; } SecondaryCmdBuffer& Stage::beginSecondary( @@ -162,6 +162,6 @@ scoped_submit::~scoped_submit() { // a destructor is no task: it stores the failure itself try { _stagePtr->submit(); } - catch(...) { _jobs->store(std::current_exception()); } + catch(...) { _submissions->store(std::current_exception()); } } } diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index 9139b2b9..f16ab76e 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -76,7 +76,7 @@ StageGraph::StageGraph(Core& core, Config config) : for(size_t stageId = 0; stageId < stages.size(); ++stageId) frameSlot.stageSlots.emplace_back( *this, - _jobs, + _submissions, stageId, slot, core.queue(stages[stageId].queueIdx), @@ -109,7 +109,8 @@ StageGraph::StageGraph(Core& core, Config config) : } StageGraph::~StageGraph() { - // the waiters of an unsubmitted stage would hang in _jobs.wait(), e.g. after an exception in the recording + // the waiters of an unsubmitted stage would hang in _submissions.wait(), e.g. after an + // exception in the recording for(auto& frameSlot : _frameSlots) for(auto& stage : frameSlot.stages) { if(stage.status() != Stage::Status::UNSUBMITTED) @@ -126,7 +127,7 @@ StageGraph::~StageGraph() { } } - _jobs.wait(); + _submissions.wait(); for(auto& frameSlot : _frameSlots) for(auto& stageSlot : frameSlot.stageSlots) { @@ -147,8 +148,8 @@ StageGraph::~StageGraph() { } cth::co::executor_task StageGraph::nextFrame() { - if(_jobs.failed()) - _jobs.rethrow(); + if(_submissions.failed()) + _submissions.rethrow(); auto const number = ++_frameNumber; auto const slotOf = [this](uint64_t frameNumber) -> dev::FrameSlot& { @@ -164,8 +165,8 @@ cth::co::executor_task StageGraph::nextFrame() { // a failed skip in an earlier nextFrame() leaves a stage of an older frame unsubmitted skipUnsubmitted(frameSlot); - // the jobs first: the gpu can finish before the job marks the submit, the job uses the - // slot until it ended its presents + // the submissions first: the gpu can finish before the submission marks the submit, the + // submission uses the slot until it ended its presents co_await cth::co::all( frameSlot.stages | std::views::transform( @@ -192,7 +193,7 @@ void StageGraph::submit(Stage& stage) { CTH_CRITICAL(stage._status != Stage::Status::UNSUBMITTED, "the stage must be unsubmitted") {} endPrimary(stageSlot.primary); - detachJob(stage, Stage::Status::SUBMITTED); + detachSubmission(stage, Stage::Status::SUBMITTED); } void StageGraph::skip(Stage& stage) { @@ -202,7 +203,7 @@ void StageGraph::skip(Stage& stage) { // the recording of a begun primary is discarded, the next begin resets it endPrimary(stageSlot.primary); - detachJob(stage, Stage::Status::SKIPPED); + detachSubmission(stage, Stage::Status::SKIPPED); } void StageGraph::assume(cvk::Image const& image, ImageState const& state) { @@ -260,7 +261,7 @@ void StageGraph::skipUnsubmitted(dev::FrameSlot& frameSlot) { } } -void StageGraph::detachJob(Stage& stage, Stage::Status targetStatus) { +void StageGraph::detachSubmission(Stage& stage, Stage::Status targetStatus) { auto& stageSlot = *stage._stageSlot; // the status after the detach: a failed allocation leaves the stage unsubmitted, the moved data is lost @@ -273,8 +274,8 @@ void StageGraph::detachJob(Stage& stage, Stage::Status targetStatus) { } core().executor().detach( - _jobs, - submitJob( + _submissions, + submission( stageSlot, stage._frameNumber, std::move(retained), @@ -285,7 +286,7 @@ void StageGraph::detachJob(Stage& stage, Stage::Status targetStatus) { stage._status = targetStatus; } -cth::co::executor_task StageGraph::submitJob( +cth::co::executor_task StageGraph::submission( dev::StageSlot& stageSlot, uint64_t frameNumber, dev::RetainedResources retained, @@ -304,8 +305,8 @@ cth::co::executor_task StageGraph::submitJob( for(auto const& wait : stageSlot.extraWaits) co_await wait.semaphore->submitted(wait.value); - // the values of this frame, then next(): the job of the next frame of the slot reads them after - // the mark + // the values of this frame, then next(): the submission of the next frame of the slot reads + // them after the mark // noexcept: without the skip info no skip submit marks the slot, the waiters would hang [&]() noexcept { slotSubmit.skipInfo(info, stageSlot.extraWaits, stageSlot.extraBinaryWaits); @@ -330,8 +331,8 @@ cth::co::executor_task StageGraph::submitJob( if(!releases.empty()) info.waits.append_range(co_await release(std::move(releases))); - // off the strand: the prologue and the epilogue belong to the job of the slot, an empty - // one stays out of the submit + // off the strand: the prologue and the epilogue belong to the submission of the slot, + // an empty one stays out of the submit bool const withPrologue = !prologue.empty(); if(withPrologue) { stageSlot.prologue.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); @@ -349,8 +350,8 @@ cth::co::executor_task StageGraph::submitJob( co_await submitAndPresent(stageSlot, frameNumber); submitted = true; } - // the job goes on with the skip - catch(...) { _jobs.store(std::current_exception()); } + // the submission goes on with the skip + catch(...) { _submissions.store(std::current_exception()); } } // a skip, also of a failed submit: the gpu waits of other stages and the waits in ~StageGraph() end @@ -361,7 +362,7 @@ cth::co::executor_task StageGraph::submitJob( info.cmdBuffers.clear(); // the present semaphores of a failed submit: no present waits for them info.binarySignals.clear(); - return dev::skip_submit(queue, info, _jobs); + return dev::skip_submit(queue, info, _submissions); }(); co_await std::move(skip); @@ -369,17 +370,25 @@ cth::co::executor_task StageGraph::submitJob( // surface unacquires its image at once if(!stageSlot.presents.empty()) { try { co_await stageSlot.semaphore.wait(frameNumber); } - catch(...) { _jobs.store(std::current_exception()); } + catch(...) { _submissions.store(std::current_exception()); } stageSlot.presents.clear(); } } - // the last use of the slot by the job before the gpu wait: nextFrame() hands it out after it + // the last use of the slot by the submission before the gpu wait: nextFrame() hands it out + // after it stageSlot.submitDone.set(frameNumber); - // after the mark: a failed gpu wait escapes, _jobs stores it, the retained objects stay for - // the destruction of the graph - // the job never touches the stage: nextFrame() destroys the stages after the gpu wait + // nothing to free: no gpu wait, the submission ends + if(retained.images.empty() && retained.buffers.empty()) { + std::scoped_lock const lock{stageSlot.stasisMutex}; + if(stageSlot.stasis.empty(stasisEnd)) + co_return; + } + + // after the mark: a failed gpu wait escapes, _submissions stores it, the retained objects stay + // for the destruction of the graph + // the submission never touches the stage: nextFrame() destroys the stages after the gpu wait co_await stageSlot.semaphore.wait(frameNumber); { @@ -570,7 +579,7 @@ cth::co::executor_task StageGraph::submitAndPresent( if(stageSlot.semaphore.submittedValue() < frameNumber) throw; // a failed present after the submit: the images resolve with their results - _jobs.store(std::current_exception()); + _submissions.store(std::current_exception()); } if(ownGroup) groups.front().presented = true; @@ -621,12 +630,12 @@ cth::co::executor_task StageGraph::submitAndPresent( ); // the transfer waits for the semaphore of the slot: ~StageGraph() destroys it after - // the jobs ended + // the submissions ended if(transferredOpt.has_value()) co_await transferredOpt->semaphore->wait(transferredOpt->value); } // a failed transfer drops the images of the queue, a failed present presented them - catch(...) { _jobs.store(std::current_exception()); } + catch(...) { _submissions.store(std::current_exception()); } } // each image of a group resolves with its result, in the order of the group @@ -643,7 +652,7 @@ cth::co::executor_task StageGraph::submitAndPresent( // them if(std::ranges::any_of(groups, [](auto const& group) { return !group.presented; })) { try { co_await stageSlot.semaphore.wait(frameNumber); } - catch(...) { _jobs.store(std::current_exception()); } + catch(...) { _submissions.store(std::current_exception()); } } presents.clear(); } diff --git a/jvk/src/graph/surface.cpp b/jvk/src/graph/surface.cpp index 9ada57de..095f724d 100644 --- a/jvk/src/graph/surface.cpp +++ b/jvk/src/graph/surface.cpp @@ -62,7 +62,7 @@ void Surface::create(cvk::Surface surface) { void Surface::destroy() { debug_check(*this); - // the job of the present stage resolves the last image + // the submission of the present stage resolves the last image if(_presentState.resolved.value() < _lastValue) _core->executor().sync_wait(await_value(_presentState.resolved, _lastValue)); diff --git a/jvk/tests/src/base/queue_test.cpp b/jvk/tests/src/base/queue_test.cpp index 994d02ac..265a3579 100644 --- a/jvk/tests/src/base/queue_test.cpp +++ b/jvk/tests/src/base/queue_test.cpp @@ -538,13 +538,13 @@ JVK_TEST(Queue, skip_submit_marks_through_the_submit) { test::Context const context{}; auto& queue = context.core.queue(0); Semaphore const semaphore{context.core, cvk::create}; - cth::co::catching_scope jobs{}; + cth::co::catching_scope submissions{}; context.core.executor().sync_wait( - dev::skip_submit(queue, {.signals = {{.semaphore = semaphore, .value = 1}}}, jobs) + dev::skip_submit(queue, {.signals = {{.semaphore = semaphore, .value = 1}}}, submissions) ); - EXPECT_FALSE(jobs.failed()); + EXPECT_FALSE(submissions.failed()); EXPECT_EQ(semaphore.submittedValue(), 1); static_cast(semaphore).wait(1); } diff --git a/jvk/tests/src/graph/stage_graph_test.cpp b/jvk/tests/src/graph/stage_graph_test.cpp index a55af238..9ebd0e8b 100644 --- a/jvk/tests/src/graph/stage_graph_test.cpp +++ b/jvk/tests/src/graph/stage_graph_test.cpp @@ -235,7 +235,8 @@ JVK_TEST(StageGraph, chain_on_one_queue_submitted_in_reverse) { auto& writer = frame.stage(0); auto& reader = frame.stage(1); - // the reader submits first, from another thread: its job waits for the mark of the writer + // the reader submits first, from another thread: its submission waits for the mark of the + // writer std::jthread{ [&] { auto const primary = reader.begin(); @@ -468,7 +469,7 @@ JVK_TEST(StageGraph, destruction_after_an_exception_skips_the_unsubmitted_stage) test::Context const context{}; Core core{context.instance, test::Context::CONFIG, {}}; - // the waiter is submitted, ~StageGraph() skips the waited stage, else its job hangs + // the waiter is submitted, ~StageGraph() skips the waited stage, else its submission hangs auto const run = [&core] { StageGraph graph{ core, @@ -517,7 +518,7 @@ JVK_TEST(StageGraph, extra_jvk_wait_and_binary_wait) { stage.await(binary); submit_empty(stage); - // the job waits for the mark of the external wait before its submit + // the submission waits for the mark of the external wait before its submit core.executor().sync_wait( submit(queue, {.signals = {SemaphoreSubmitInfo{.semaphore = external, .value = 1}}}) ); @@ -613,7 +614,7 @@ JVK_TEST(StageGraph, retain_lives_until_the_gpu_finished_the_submit) { EXPECT_TRUE(reaches_allocations(core, before - 1)); } -JVK_TEST(StageGraph, retain_of_the_next_frame_survives_the_job_of_the_frame_before) { +JVK_TEST(StageGraph, retain_of_the_next_frame_survives_the_submission_of_the_frame_before) { test::Context const context{}; Core core{context.instance, test::Context::CONFIG, {}}; StageGraph graph{core, {.stages = {{.queueIdx = 0}}, .frameSlots = 1}}; @@ -631,7 +632,7 @@ JVK_TEST(StageGraph, retain_of_the_next_frame_survives_the_job_of_the_frame_befo gate.markSubmitted(1); core.executor().sync_wait(await_submitted(stage)); - // the job waits for the gpu: its resume comes behind this strand job + // the submission waits for the gpu: its resume comes behind this strand job std::binary_semaphore blocking{0}; std::binary_semaphore unblock{0}; queue.executor().context().post( @@ -643,12 +644,13 @@ JVK_TEST(StageGraph, retain_of_the_next_frame_survives_the_job_of_the_frame_befo ASSERT_TRUE(blocking.try_acquire_for(TIMEOUT)); host_signal(gate, 1); - // the same slot: the gpu finished the frame before, its job did not destroy the retained objects yet + // the same slot: the gpu finished the frame before, its submission did not destroy the retained + // objects yet auto& next = next_frame(core, graph).stage(0); next.retain(std::move(second)); unblock.release(); - // the job of the frame before destroys its own retained buffer only + // the submission of the frame before destroys its own retained buffer only EXPECT_TRUE(reaches_allocations(core, before - 1)); core.executor().sync_wait(enter_strand(queue)); EXPECT_EQ(allocations(core), before - 1); @@ -713,7 +715,7 @@ JVK_TEST(StageGraph, retained_transient_image_starts_from_undefined) { image.copy(*primary, staging); image.copyTo(*primary, readback); primary->use(readback, HOST_READ); - // the last use: the job records the transition from undefined after the release + // the last use: the submission records the transition from undefined after the release stage.retain(std::move(image)); stage.submit(); @@ -738,7 +740,7 @@ JVK_TEST(StageGraph, image_moved_after_the_submit_keeps_its_prologue) { std::optional firstOpt{std::in_place, core, IMAGE_CONFIG, EXTENT}; std::optional secondOpt{}; - // the job awaits the mark of the gate before its append + // the submission awaits the mark of the gate before its append auto& stage = next_frame(core, graph).stage(0); stage.await(gate, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, 1); auto const primary = stage.begin(); @@ -747,7 +749,7 @@ JVK_TEST(StageGraph, image_moved_after_the_submit_keeps_its_prologue) { primary->use(readback, HOST_READ); stage.submit(); - // the recorded object is gone before the job records the prologue + // the recorded object is gone before the submission records the prologue secondOpt.emplace(std::move(*firstOpt)); firstOpt.reset(); @@ -777,7 +779,8 @@ JVK_TEST(StageGraph, image_and_buffer_move_to_another_queue_family) { auto& writer = frame.stage(0); auto& reader = frame.stage(1); - // the reader submits first: its job appends after the writer, the writer queue releases both + // the reader submits first: its submission appends after the writer, the writer queue releases + // both auto const readerPrimary = reader.begin(); image.copyTo(*readerPrimary, imageReadback); bufferReadback.copy(*readerPrimary, buffer); diff --git a/jvk/tests/src/graph/surface_test.cpp b/jvk/tests/src/graph/surface_test.cpp index 0a170928..09c01d3e 100644 --- a/jvk/tests/src/graph/surface_test.cpp +++ b/jvk/tests/src/graph/surface_test.cpp @@ -176,8 +176,8 @@ namespace { } /** - * acquires and clears the image of the stage, the scope submits, the job presents - * @details the submit job waits for the gate: the present stays pending + * acquires and clears the image of the stage, the scope submits, the submission presents + * @details the submission waits for the gate: the present stays pending * @return the image */ SwapchainImage present_behind_gate( @@ -224,7 +224,7 @@ namespace { /** * acquires the image of the next frame, clears the multisampled target and resolves it into the image - * @details only the scope: `scoped_submit` submits, the job presents + * @details only the scope: `scoped_submit` submits, the submission presents * @details a new extent: the stage retains the old target, then a new one * @param[out] msaaOpt the target of the frames * @return the image @@ -266,7 +266,7 @@ namespace { /** * acquires, clears and presents the image of the stage in the next frame - * @details only the scope: `scoped_submit` submits, the job presents + * @details only the scope: `scoped_submit` submits, the submission presents * @details the acquire comes before `Stage::begin()` * @return the image */ @@ -504,7 +504,8 @@ JVK_TEST(Surface, acquire_waits_for_the_present_before) { auto& first = next_frame(core, graph).stage(0); present_behind_gate(core, first, surface, gate); - // the job of the first frame waits for the mark of the gate, the next acquire for its present + // the submission of the first frame waits for the mark of the gate, the next acquire for its + // present auto& second = next_frame(core, graph).stage(0); std::binary_semaphore acquiredSignal{0}; size_t acquiredImages = 0; @@ -700,7 +701,7 @@ JVK_TEST(Surface, exception_after_the_submit_presents_the_image) { ASSERT_TRUE(imageIdxOpt.has_value()); EXPECT_EQ(stage.status(), Stage::Status::SUBMITTED); - // the stage is submitted: its job presents the image + // the stage is submitted: its submission presents the image EXPECT_TRUE(reaches_unacquired(core, core.queue(0), surface, *imageIdxOpt)); wait(core, stage); From 6deca4c130f7dd7150ef171f5b6fdad112dce4e9 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:46:36 +0100 Subject: [PATCH 50/68] jvk: submit() and skip() store their failure, the frame flow has no implicit skips - StageGraph::submit(), StageGraph::skip() and the Stage forms are noexcept - a failure stays in the graph, the stage stays UNSUBMITTED - the next nextFrame() rethrows the failure - scoped_submit(Stage&): normal end -> submit(), exception -> skip() - nextFrame() skips nothing - its first statement rethrows a stored failure - a debug check: every stage of the frame before is submitted or skipped - ~StageGraph() skips the stages that are still UNSUBMITTED, their waiters go on - a failed present goes to its surface, the next Surface::acquire() rethrows it - one path for the submit and the skip of a stage - the review markers go, the transfer counter probe stays - the demos skip the stage when acquire() gives no image - tests: test::fail_next_allocation(), a failed submit, a failed present, an exception through scoped_submit --- demo/cube/src/main.cpp | 3 +- demo/triangle/src/main.cpp | 3 +- jvk/incl/jvk/base/queue.hpp | 6 +- jvk/incl/jvk/graph/pending_present.hpp | 15 ++- jvk/incl/jvk/graph/stage.hpp | 27 ++-- jvk/incl/jvk/graph/stage_graph.hpp | 32 +++-- jvk/incl/jvk/graph/surface.hpp | 9 +- jvk/incl/jvk/sync/semaphore.hpp | 1 - jvk/src/graph/pending_present.cpp | 16 ++- jvk/src/graph/stage.cpp | 21 ++- jvk/src/graph/stage_graph.cpp | 162 ++++++++++------------- jvk/src/graph/surface.cpp | 3 + jvk/tests/src/allocation.cpp | 29 ++++ jvk/tests/src/allocation.hpp | 10 ++ jvk/tests/src/graph/stage_graph_test.cpp | 98 +++++++++----- jvk/tests/src/graph/surface_test.cpp | 60 ++++++++- 16 files changed, 307 insertions(+), 188 deletions(-) create mode 100644 jvk/tests/src/allocation.cpp create mode 100644 jvk/tests/src/allocation.hpp diff --git a/demo/cube/src/main.cpp b/demo/cube/src/main.cpp index a5ea173c..20ca3f22 100644 --- a/demo/cube/src/main.cpp +++ b/demo/cube/src/main.cpp @@ -458,8 +458,9 @@ cth::co::executor_task draw_frames( stage, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT ); - // extent 0: no image, the next nextFrame() skips the stage + // extent 0: no image if(!image) { + stage.skip(); co_await cth::co::this_coro::wait(IDLE_WAIT); continue; } diff --git a/demo/triangle/src/main.cpp b/demo/triangle/src/main.cpp index 48cefb77..1ecb5da0 100644 --- a/demo/triangle/src/main.cpp +++ b/demo/triangle/src/main.cpp @@ -101,8 +101,9 @@ cth::co::executor_task draw_frames( stage, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT ); - // extent 0: no image, the next nextFrame() skips the stage + // extent 0: no image if(!image) { + stage.skip(); co_await cth::co::this_coro::wait(IDLE_WAIT); continue; } diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index a2f7a242..ce09bb93 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -234,8 +234,10 @@ class Queue { std::vector _presentWaits{}; std::vector _presentFences{}; - //TODO review the counter decides the reuse of the transfer command buffers, no reactor wait: a - // transfer reads it + /** + * the counter decides the reuse of the transfer command buffers, no reactor wait: a transfer + * reads it + */ Semaphore _transferred; public: diff --git a/jvk/incl/jvk/graph/pending_present.hpp b/jvk/incl/jvk/graph/pending_present.hpp index 56e35385..5db581b8 100644 --- a/jvk/incl/jvk/graph/pending_present.hpp +++ b/jvk/incl/jvk/graph/pending_present.hpp @@ -11,8 +11,10 @@ #include #include +#include #include #include +#include namespace cvk { @@ -37,14 +39,20 @@ struct PresentState { */ bool dropped = false; + /** error of the failed present of the last image, `Surface::acquire()` rethrows it */ + std::exception_ptr error = nullptr; + /** * resolves the image as presented * @details `VK_ERROR_OUT_OF_DATE_KHR` -> sets `PresentState::outOfDate` + * @details another result than `VK_SUCCESS`, `VK_SUBOPTIMAL_KHR` and `VK_ERROR_OUT_OF_DATE_KHR` + * sets `PresentState::error`: `error`, `nullptr` -> a `cvk::vk_result_exception` of the result * @param value of the image * @param result of the present of the image + * @param error exception of the present, `nullptr` -> none * @pre the images before the image are resolved */ - void present(uint64_t value, VkResult result); + void present(uint64_t value, VkResult result, std::exception_ptr error); /** * resolves the image as dropped: the next `Surface::acquire()` unacquires it @@ -98,13 +106,14 @@ class PendingPresent { /** * resolves the image as presented * @param result of the present of the image + * @param error exception of the present, `nullptr` -> none * @pre not resolved * @see `PresentState::present()` */ - void present(VkResult result) { + void present(VkResult result, std::exception_ptr error) { debug_check(*this); auto const value = _state.get_deleter().value; - _state.release()->present(value, result); + _state.release()->present(value, result, std::move(error)); } /** diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index b0ec5de0..a509a02f 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -13,7 +13,6 @@ #include -#include #include #include #include @@ -106,6 +105,9 @@ struct PresentGroup { /** the present ran, also a failed one: the images resolve as presented, else dropped */ bool presented = false; + + /** exception of a failed present, the surfaces of its images get it, `nullptr` -> none */ + std::exception_ptr error = nullptr; }; /** @@ -140,7 +142,6 @@ struct StageSlot { */ StageSlot( StageGraph& graph, - cth::co::catching_scope& submissions, size_t stageId, size_t slot, Queue& queue, @@ -149,9 +150,6 @@ struct StageSlot { cth::ref_wrapper graph; - /** the submissions of the graph, the scopes of the stages store their errors into it */ - cth::ref_wrapper submissions; - size_t stageId; ///< id of the stage, see `StageGraphConfig::stages` size_t slot; @@ -395,16 +393,18 @@ class Stage { /** * submits the primary of the frame * @details calls `StageGraph::submit()` of the graph of the stage + * @details a failure: no throw, see `StageGraph::submit()` * @pre the preconditions of `StageGraph::submit()` */ - void submit(); + void submit() noexcept; /** * submits no work in this frame * @details calls `StageGraph::skip()` of the graph of the stage + * @details a failure: no throw, see `StageGraph::submit()` * @pre the preconditions of `StageGraph::skip()` */ - void skip(); + void skip() noexcept; /** * keeps the object until the gpu finished the submit or the skip of this frame @@ -499,25 +499,21 @@ namespace jvk { * @details * - `Stage::begin()` returns it * - normal end: `Stage::submit()` if the stage is `UNSUBMITTED` - * - exception: nothing, the next `StageGraph::nextFrame()` skips the stage - * - a moved-from scope does nothing - * - a failure of the submit at the end, e.g. an allocation: `StageGraph::nextFrame()` rethrows it + * - exception: `Stage::skip()` if the stage is `UNSUBMITTED` + * - a submitted or skipped stage, a moved-from scope: nothing + * - a failure of the submit or the skip at the end: no throw, see `StageGraph::submit()` * - `->` and `*` reach the primary * @attention a coroutine destroyed while suspended with the scope alive submits the stage */ class scoped_submit { public: - //TODO review the submissions of the graph as a parameter: scoped_submit is no nested class, - // Stage::begin() hands it the submissions of the graph from its stage slot /** * @details the uncaught exceptions of the calling thread at the construction tell the exception at the end * @param stage with the begun primary - * @param submissions of the graph, gets a failure of the submit at the end * @pre `Stage::begin()` began the primary */ - scoped_submit(Stage& stage, cth::co::catching_scope& submissions) noexcept : + explicit scoped_submit(Stage& stage) noexcept : _stagePtr{&stage}, - _submissions{submissions}, _uncaughtExceptions{std::uncaught_exceptions()} {} ~scoped_submit(); @@ -527,7 +523,6 @@ class scoped_submit { private: cth::move_ptr _stagePtr; - cth::ref_wrapper _submissions; int _uncaughtExceptions; public: diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index 57ec69cf..65fc8f5b 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -63,8 +63,11 @@ class StageGraph { /** * waits until the gpu finished the submits of every slot, destroys the slots + * @details skips the unsubmitted stages first, their waiters go on: + * - the stages of the frame of the last `nextFrame()` + * - a stage with an exception outside of a `scoped_submit` + * - a stage that a failed `submit()` or `skip()` left `UNSUBMITTED` * @details - * - skips the unsubmitted stages first, e.g. after an exception in their recording: their waiters go on * - the skip drops the presents of the stage, see `Surface::acquire()` * - waits for the end of every submission * - a failed skip or wait does not stop the destruction @@ -76,14 +79,15 @@ class StageGraph { // the submit /** * constructs the frame and its stages in the next slot - * @details the frame before: skips its stages without `Stage::submit()` or `Stage::skip()`, warns for a waited one * @details the old frame of the slot: awaits `StageSlot::submitDone` of its stages: their * submissions ended the submits and the presents, then the stages: the gpu finished them, both * with `cth::co::all()` * @return the frame of the slot + * @pre every stage of the frame before is submitted or skipped: `Stage::submit()`, + * `Stage::skip()` or the end of its `scoped_submit` * @pre no stage of the frame before records or submits: `nextFrame()` ends the frame - * @throws std::exception the first error of a submission or a scope, stored before the call: an - * error during the waits -> the next `nextFrame()` rethrows it, see `cth::co::catching_scope` + * @throws std::exception the first error of a submission, a `submit()` or a `skip()`, stored + * before the call * @throws cth::except::group_coro_exception reason: the wait for a stage of the old frame * failed, after the waits for all its stages: `exceptions()` holds the * `cth::except::coro_exception` per stage @@ -105,15 +109,20 @@ class StageGraph { * - signals `Stage::semaphore()` with `Stage::frameNumber()` * - the images of `Stage::present()`: the epilogue after the primary transitions them, the * presents follow the submit, see `Surface::acquire()` - * - an error: skips, `nextFrame()` rethrows the error + * - an error of the submission: skips, `nextFrame()` rethrows the error + * - a failed present: the surface of the image gets the error, see `Surface::acquire()` * - after the gpu finished: destroys the retained objects + * @details a failure here, `vkEndCommandBuffer()` or the allocation of the submission: + * - no throw, the stage stays `UNSUBMITTED` + * - the next `nextFrame()` rethrows the failure + * - `~StageGraph()` skips the stage * @pre the stage is of this graph * @pre `Stage::begin()` in this frame * @pre `Stage::status()` is `UNSUBMITTED` * @pre the primary and its executed secondaries belong to the queue family of `Stage::queue()` * @note ends the rendering and the primary */ - void submit(Stage&); + void submit(Stage&) noexcept; /** * submits no work for the stage in this frame @@ -125,10 +134,11 @@ class StageGraph { * @details drops the images of `Stage::present()`, see `Surface::acquire()` * @details after the gpu finished the skip submit: destroys the retained objects * @details a begun primary: ends its rendering and the primary, discards the recording + * @details a failure: the failure of `submit()` * @pre the stage is of this graph * @pre `Stage::status()` is `UNSUBMITTED` */ - void skip(Stage&); + void skip(Stage&) noexcept; /** * sets the state of the image after all submits, without a barrier @@ -173,10 +183,8 @@ class StageGraph { using release_map_t = cth::dt::flat_hash_map; - void skipUnsubmitted(dev::FrameSlot&); - - //TODO review one helper for submit() and skip(): they differ in the status only - void detachSubmission(Stage&, Stage::Status targetStatus); + /** a failure stores its error, the stage stays `UNSUBMITTED` */ + void detachSubmission(Stage&, Stage::Status targetStatus) noexcept; // no marks as parameters: the submission awaits Semaphore::submitted() of the slots, they live // as long as the graph @@ -233,8 +241,6 @@ class StageGraph { last_queue_map_t _bufferQueues{}; - //TODO review the error stays: every nextFrame() rethrows it, the errors of the submissions are - // fatal cth::co::catching_scope _submissions{}; uint64_t _firstFrameNumber; diff --git a/jvk/incl/jvk/graph/surface.hpp b/jvk/incl/jvk/graph/surface.hpp index 63229f58..2d28ed2b 100644 --- a/jvk/incl/jvk/graph/surface.hpp +++ b/jvk/incl/jvk/graph/surface.hpp @@ -77,8 +77,8 @@ struct SurfaceConfig { * - recreates the swapchain in `acquire()`, a retired swapchain stays until its presents ended, see * `Swapchain` * - acquires outside the strand of its queue on `Queue::scheduler()` - * - the present stage of an image presents it after its submit, see `acquire()`: the surface has - * no submissions, the errors of the presents go to the graph of the present stage + * - the present stage of an image presents it after its submit, see `acquire()` + * - a failed present: the next `acquire()` rethrows its error * - one acquired image at a time: `acquire()` waits until the last image is presented or dropped * - a dropped image: the next `acquire()` or `destroy()` unacquires it after the gpu finished its * stages @@ -128,6 +128,7 @@ class Surface { * - a dropped last image: blocks until the gpu finished its stages, then unacquires it * - destroys the acquire semaphores, the swapchain, then the cvk surface * - a failed wait does not stop the destruction + * - drops the error of a failed present of the last image * @pre `created()` * @pre no `acquire()` is pending * @pre the present stage of the last image is submitted or skipped, or its graph is destroyed: @@ -159,7 +160,8 @@ class Surface { * queue of the surface acquires it, see `Queue::transfer()` * - after its submit: the present on the queue of the surface, one `vkQueuePresentKHR()` for * the images of one queue - * - a failed present: the graph stores the error, `StageGraph::nextFrame()` rethrows it + * - a failed present, an exception of `Queue::present()` or another result than `VK_SUCCESS`, + * `VK_SUBOPTIMAL_KHR` and `VK_ERROR_OUT_OF_DATE_KHR`: the next `acquire()` rethrows the error * - a skip or a failed submit drops the image: the next `acquire()` unacquires it * @details the surface: * - waits until the last image is presented or dropped @@ -183,6 +185,7 @@ class Surface { * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode * @throws cvk::vk_result_exception other result of `vkAcquireNextImageKHR()` or * `vkCreateSwapchainKHR()` + * @throws std::exception the error of the failed present of the last image, once * @attention `vkAcquireNextImageKHR()` can block (FIFO: the vsync throttle): it occupies a * driver thread, `CoreConfig::driverThreads` `0` -> the calling worker * @see `Stage::await()` diff --git a/jvk/incl/jvk/sync/semaphore.hpp b/jvk/incl/jvk/sync/semaphore.hpp index b3312e97..b7d1423d 100644 --- a/jvk/incl/jvk/sync/semaphore.hpp +++ b/jvk/incl/jvk/sync/semaphore.hpp @@ -118,7 +118,6 @@ class Semaphore { */ void create(uint64_t initialValue = 0); - //TODO evaluate: destroy() with pending waits cancels them (operation_canceled), like asio /** * destroys and forgets * @pre `created()` diff --git a/jvk/src/graph/pending_present.cpp b/jvk/src/graph/pending_present.cpp index cc410650..07271537 100644 --- a/jvk/src/graph/pending_present.cpp +++ b/jvk/src/graph/pending_present.cpp @@ -1,10 +1,24 @@ #include "jvk/graph/pending_present.hpp" +#include "cvk/utility/vk_exceptions.hpp" + +#include +#include + namespace jvk::dev { -void PresentState::present(uint64_t value, VkResult result) { +void PresentState::present(uint64_t value, VkResult result, std::exception_ptr error) { if(result == VK_ERROR_OUT_OF_DATE_KHR) outOfDate = true; + if(result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR && result != VK_ERROR_OUT_OF_DATE_KHR) { + // a result without an exception of the present: a failed construction keeps its own error, + // the image resolves anyway + if(error == nullptr) { + try { throw cvk::vk_result_exception{result, "failed to present the image"}; } + catch(...) { error = std::current_exception(); } + } + this->error = std::move(error); + } dropped = false; // the last write: Surface::acquire() reads the state after the wait for the value resolved.set(value); diff --git a/jvk/src/graph/stage.cpp b/jvk/src/graph/stage.cpp index f6035ee4..ef81e225 100644 --- a/jvk/src/graph/stage.cpp +++ b/jvk/src/graph/stage.cpp @@ -59,14 +59,12 @@ void SlotSubmit::addCmdBuffers(SubmitInfo& info, bool prologue, bool epilogue) c StageSlot::StageSlot( StageGraph& graph, - cth::co::catching_scope& submissions, size_t stageId, size_t slot, Queue& queue, size_t secondaries ) : graph{graph}, - submissions{submissions}, stageId{stageId}, slot{slot}, queue{queue}, @@ -104,7 +102,7 @@ scoped_submit Stage::begin() { if(samplerHeapPtr != nullptr) vk.bind(*samplerHeapPtr); - return scoped_submit{*this, _stageSlot->submissions}; + return scoped_submit{*this}; } SecondaryCmdBuffer& Stage::beginSecondary( @@ -149,19 +147,18 @@ void Stage::present(dev::PendingPresent present) { _stageSlot->presents.push_back(std::move(present)); } -void Stage::submit() { _stageSlot->graph->submit(*this); } +void Stage::submit() noexcept { _stageSlot->graph->submit(*this); } -void Stage::skip() { _stageSlot->graph->skip(*this); } +void Stage::skip() noexcept { _stageSlot->graph->skip(*this); } scoped_submit::~scoped_submit() { - // an exception: the next nextFrame() skips the stage - if(!_stagePtr || std::uncaught_exceptions() > _uncaughtExceptions) - return; - if(_stagePtr->status() != Stage::Status::UNSUBMITTED) + if(!_stagePtr || _stagePtr->status() != Stage::Status::UNSUBMITTED) return; - // a destructor is no task: it stores the failure itself - try { _stagePtr->submit(); } - catch(...) { _submissions->store(std::current_exception()); } + // an exception: the recording is incomplete, the skip lets the waiters go on + if(std::uncaught_exceptions() > _uncaughtExceptions) + _stagePtr->skip(); + else + _stagePtr->submit(); } } diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index f16ab76e..41ca3349 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -76,7 +76,6 @@ StageGraph::StageGraph(Core& core, Config config) : for(size_t stageId = 0; stageId < stages.size(); ++stageId) frameSlot.stageSlots.emplace_back( *this, - _submissions, stageId, slot, core.queue(stages[stageId].queueIdx), @@ -109,22 +108,14 @@ StageGraph::StageGraph(Core& core, Config config) : } StageGraph::~StageGraph() { - // the waiters of an unsubmitted stage would hang in _submissions.wait(), e.g. after an - // exception in the recording + // the waiters of an unsubmitted stage would hang in _submissions.wait(): the frame of the last + // nextFrame(), an exception outside of a scope, a failed submit() or skip() for(auto& frameSlot : _frameSlots) for(auto& stage : frameSlot.stages) { if(stage.status() != Stage::Status::UNSUBMITTED) continue; // the skip drops the presents of the stage: the surfaces outlive the graph - try { skip(stage); } - catch(std::exception const& e) { - JVK_STABLE_ERR( - true, - "failed to skip stage {} in ~StageGraph(), got {}", - stage.id(), - e.what() - ) {} - } + skip(stage); } _submissions.wait(); @@ -151,20 +142,22 @@ cth::co::executor_task StageGraph::nextFrame() { if(_submissions.failed()) _submissions.rethrow(); - auto const number = ++_frameNumber; auto const slotOf = [this](uint64_t frameNumber) -> dev::FrameSlot& { return _frameSlots[(frameNumber - _firstFrameNumber) % _config.frameSlots]; }; + if(_frameNumber >= _firstFrameNumber) + for(auto const& stage : slotOf(_frameNumber).stages) + CTH_CRITICAL( + stage.status() == Stage::Status::UNSUBMITTED, + "every stage of the frame before must be submitted or skipped, got stage {} of " + "frame {}", + stage.id(), + _frameNumber + ) {} - // the frame before ends now: its gpu work and its waiters do not wait for the reuse of its slot - if(number > _firstFrameNumber) - skipUnsubmitted(slotOf(number - 1)); - + auto const number = ++_frameNumber; auto& frameSlot = slotOf(number); if(frameSlot.frameOpt.has_value()) { - // a failed skip in an earlier nextFrame() leaves a stage of an older frame unsubmitted - skipUnsubmitted(frameSlot); - // the submissions first: the gpu can finish before the submission marks the submit, the // submission uses the slot until it ended its presents co_await cth::co::all( @@ -187,24 +180,11 @@ cth::co::executor_task StageGraph::nextFrame() { co_return *frameSlot.frameOpt; } -void StageGraph::submit(Stage& stage) { - auto& stageSlot = *stage._stageSlot; - CTH_CRITICAL(&*stageSlot.graph != this, "the stage must be of this graph") {} - CTH_CRITICAL(stage._status != Stage::Status::UNSUBMITTED, "the stage must be unsubmitted") {} - - endPrimary(stageSlot.primary); +void StageGraph::submit(Stage& stage) noexcept { detachSubmission(stage, Stage::Status::SUBMITTED); } -void StageGraph::skip(Stage& stage) { - auto& stageSlot = *stage._stageSlot; - CTH_CRITICAL(&*stageSlot.graph != this, "the stage must be of this graph") {} - CTH_CRITICAL(stage._status != Stage::Status::UNSUBMITTED, "the stage must be unsubmitted") {} - - // the recording of a begun primary is discarded, the next begin resets it - endPrimary(stageSlot.primary); - detachSubmission(stage, Stage::Status::SKIPPED); -} +void StageGraph::skip(Stage& stage) noexcept { detachSubmission(stage, Stage::Status::SKIPPED); } void StageGraph::assume(cvk::Image const& image, ImageState const& state) { cvk::Image::debug_check(image); @@ -233,57 +213,40 @@ void StageGraph::endPrimary(PrimaryCmdBuffer& primary) { primary.optEnd(); } -void StageGraph::skipUnsubmitted(dev::FrameSlot& frameSlot) { - if(!frameSlot.frameOpt.has_value()) - return; +void StageGraph::detachSubmission(Stage& stage, Stage::Status targetStatus) noexcept { + auto& stageSlot = *stage._stageSlot; + CTH_CRITICAL(&*stageSlot.graph != this, "the stage must be of this graph") {} + CTH_CRITICAL(stage._status != Stage::Status::UNSUBMITTED, "the stage must be unsubmitted") {} - for(auto& stage : frameSlot.stages) { - if(stage.status() != Stage::Status::UNSUBMITTED) - continue; + // a failure: the stage stays unsubmitted, the next nextFrame() rethrows the error, + // ~StageGraph() skips the stage + try { + // a skip discards the recording of a begun primary, the next begin resets it + endPrimary(stageSlot.primary); + + // the status after the detach: a failed allocation leaves the stage unsubmitted, the moved + // data is lost + dev::RetainedResources retained{}; + Stasis::pos stasisEnd{}; + { + std::scoped_lock const lock{stageSlot.stasisMutex}; + retained = std::move(stage._retained); + stasisEnd = stageSlot.stasis.end(); + } - bool const waited = std::ranges::any_of( - _config.stages, - [&stage](StageConfig const& config) { - return std::ranges::any_of( - config.waits, - [&stage](StageWait const& wait) { return wait.stageId == stage.id(); } - ); - } + core().executor().detach( + _submissions, + submission( + stageSlot, + stage._frameNumber, + std::move(retained), + stasisEnd, + targetStatus + ) ); - CTH_WARN( - waited, - "stage {} of frame {} has no submit or skip, nextFrame() skips it, its waiters waited until now", - stage.id(), - stage.frameNumber() - ) {} - - skip(stage); - } -} - -void StageGraph::detachSubmission(Stage& stage, Stage::Status targetStatus) { - auto& stageSlot = *stage._stageSlot; - - // the status after the detach: a failed allocation leaves the stage unsubmitted, the moved data is lost - dev::RetainedResources retained{}; - Stasis::pos stasisEnd{}; - { - std::scoped_lock const lock{stageSlot.stasisMutex}; - retained = std::move(stage._retained); - stasisEnd = stageSlot.stasis.end(); + stage._status = targetStatus; } - - core().executor().detach( - _submissions, - submission( - stageSlot, - stage._frameNumber, - std::move(retained), - stasisEnd, - targetStatus - ) - ); - stage._status = targetStatus; + catch(...) { _submissions.store(std::current_exception()); } } cth::co::executor_task StageGraph::submission( @@ -576,10 +539,11 @@ cth::co::executor_task StageGraph::submitAndPresent( } catch(...) { // a failed submit marks nothing: the caller skips, the presents stay pending - if(stageSlot.semaphore.submittedValue() < frameNumber) + if(!ownGroup || stageSlot.semaphore.submittedValue() < frameNumber) throw; - // a failed present after the submit: the images resolve with their results - _submissions.store(std::current_exception()); + // a failed present after the submit: the images resolve with their results, the surfaces + // get the error + groups.front().error = std::current_exception(); } if(ownGroup) groups.front().presented = true; @@ -591,11 +555,11 @@ cth::co::executor_task StageGraph::submitAndPresent( if(&groupQueue == &queue) continue; + std::optional transferredOpt = std::nullopt; try { // another family: the queue of the surfaces acquires the images, the transfer signals // their present semaphores auto const groupFamily = groupQueue.vk().familyIndex(); - std::optional transferredOpt = std::nullopt; if(groupFamily != family) { cvk::Barrier acquire{}; auto& signals = stageSlot.presentSignals; @@ -622,20 +586,30 @@ cth::co::executor_task StageGraph::submitAndPresent( std::array const waits{submitted}; transferredOpt = co_await groupQueue.transfer(std::move(acquire), waits, signals); } + } + // a failed transfer drops the images of the queue + catch(...) { + _submissions.store(std::current_exception()); + continue; + } - group.presented = true; + // a failed present presented the images: they resolve with their results, the surfaces get + // the error + group.presented = true; + try { co_await groupQueue.present( span{images}.subspan(group.first, group.count), span{results}.subspan(group.first, group.count) ); + } + catch(...) { group.error = std::current_exception(); } - // the transfer waits for the semaphore of the slot: ~StageGraph() destroys it after - // the submissions ended - if(transferredOpt.has_value()) - co_await transferredOpt->semaphore->wait(transferredOpt->value); + // the transfer waits for the semaphore of the slot: ~StageGraph() destroys it after the + // submissions ended + if(transferredOpt.has_value()) { + try { co_await transferredOpt->semaphore->wait(transferredOpt->value); } + catch(...) { _submissions.store(std::current_exception()); } } - // a failed transfer drops the images of the queue, a failed present presented them - catch(...) { _submissions.store(std::current_exception()); } } // each image of a group resolves with its result, in the order of the group @@ -645,7 +619,7 @@ cth::co::executor_task StageGraph::submitAndPresent( auto resultIdx = group.first; for(auto& present : presents) if(&present.queue() == &*group.queue) - present.present(results[resultIdx++]); + present.present(results[resultIdx++], group.error); } // the images of a failed transfer: dropped after the gpu finished the submit, the clear drops diff --git a/jvk/src/graph/surface.cpp b/jvk/src/graph/surface.cpp index 095f724d..3a10f96a 100644 --- a/jvk/src/graph/surface.cpp +++ b/jvk/src/graph/surface.cpp @@ -111,6 +111,9 @@ cth::co::executor_task> Surface::acquire( // the last image first: the acquire and the present share the swapchain (externally // synchronized), a blocking acquire before that present would delay it (FIFO) co_await _presentState.resolved.wait(_lastValue); + // written before the resolve: the error of the present of the last image + if(_presentState.error != nullptr) + std::rethrow_exception(std::exchange(_presentState.error, nullptr)); // outside the strand: the resolve of the last image orders the swapchain uses co_await cth::co::executor{_queue->scheduler()}.schedule(); diff --git a/jvk/tests/src/allocation.cpp b/jvk/tests/src/allocation.cpp new file mode 100644 index 00000000..0d1c58dc --- /dev/null +++ b/jvk/tests/src/allocation.cpp @@ -0,0 +1,29 @@ +#include "allocation.hpp" + +#include +#include +#include +#include + + +namespace { +// trivially initialized: an allocation can come before the dynamic initialization of a thread +thread_local bool failNext = false; +} + +namespace jvk::test { +void fail_next_allocation() noexcept { failNext = true; } +} + +// the replaced global operator new, the other forms of new and delete forward to it or match it +void* operator new(std::size_t size) { + if(std::exchange(failNext, false)) + throw std::bad_alloc{}; + if(void* const ptr = std::malloc(size == 0 ? 1 : size)) + return ptr; + throw std::bad_alloc{}; +} + +void operator delete(void* ptr) noexcept { std::free(ptr); } + +void operator delete(void* ptr, std::size_t) noexcept { std::free(ptr); } diff --git a/jvk/tests/src/allocation.hpp b/jvk/tests/src/allocation.hpp new file mode 100644 index 00000000..6a982c5f --- /dev/null +++ b/jvk/tests/src/allocation.hpp @@ -0,0 +1,10 @@ +#pragma once + + +namespace jvk::test { +/** + * the next allocation of the calling thread through the global `operator new` throws + * `std::bad_alloc` + */ +void fail_next_allocation() noexcept; +} diff --git a/jvk/tests/src/graph/stage_graph_test.cpp b/jvk/tests/src/graph/stage_graph_test.cpp index 9ebd0e8b..4b611db5 100644 --- a/jvk/tests/src/graph/stage_graph_test.cpp +++ b/jvk/tests/src/graph/stage_graph_test.cpp @@ -1,5 +1,6 @@ #include "jvk/graph/stage_graph.hpp" +#include "allocation.hpp" #include "context.hpp" #include "test.hpp" @@ -20,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -334,33 +336,23 @@ JVK_TEST(StageGraph, skip_lets_the_waiter_go_on) { EXPECT_GE(frame.stage(0).semaphore().gpuValue(), frame.number()); } -JVK_TEST(StageGraph, next_frame_skips_a_forgotten_stage_of_the_frame_before) { +JVK_TEST(StageGraph, destruction_skips_a_stage_without_submit_or_skip_its_waiter_goes_on) { test::Context const context{}; Core core{context.instance, test::Context::CONFIG, {}}; - StageGraph graph{ - core, - { - .stages = {{.queueIdx = 0}, {.queueIdx = 0, .waits = {TRANSFER_WAIT_ON_0}}}, - .frameSlots = 2 - }, - }; - // the writer of the first frame gets no submit or skip, its waiter waits - auto& first = next_frame(core, graph); - submit_empty(first.stage(1)); - - // the next frame skips it, not the reuse of its slot - auto& second = next_frame(core, graph); - ASSERT_EQ(first.stage(0).status(), Stage::Status::SKIPPED); - - // its waiter and the writer of the next frame go on before the frame after - submit_empty(second.stage(0)); - wait(core, first.stage(1)); - wait(core, second.stage(0)); - EXPECT_GE(first.stage(0).semaphore().gpuValue(), first.number()); + { + StageGraph graph{ + core, + {.stages = {{.queueIdx = 0}, {.queueIdx = 0, .waits = {TRANSFER_WAIT_ON_0}}}} + }; - submit_empty(second.stage(1)); - wait(core, second.stage(1)); + // the writer of the last frame gets no submit or skip, its waiter waits + auto& frame = next_frame(core, graph); + submit_empty(frame.stage(1)); + EXPECT_EQ(frame.stage(0).status(), Stage::Status::UNSUBMITTED); + EXPECT_LT(frame.stage(1).semaphore().submittedValue(), frame.number()); + } + // ~StageGraph() skipped the writer: its wait for the submission of the waiter ended } JVK_TEST(StageGraph, scoped_submit_submits_at_its_end) { @@ -439,12 +431,20 @@ JVK_TEST(StageGraph, skip_discards_a_begun_primary) { wait(core, next); } -JVK_TEST(StageGraph, exception_in_scoped_submit_submits_nothing) { +JVK_TEST(StageGraph, exception_through_scoped_submit_skips_the_stage_its_waiter_goes_on) { test::Context const context{}; Core core{context.instance, test::Context::CONFIG, {}}; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}, .frameSlots = 2}}; + StageGraph graph{ + core, + { + .stages = {{.queueIdx = 0}, {.queueIdx = 0, .waits = {TRANSFER_WAIT_ON_0}}}, + .frameSlots = 2 + }, + }; - auto& stage = next_frame(core, graph).stage(0); + auto& frame = next_frame(core, graph); + submit_empty(frame.stage(1)); + auto& stage = frame.stage(0); try { auto const primary = stage.begin(); auto const rendering = primary->beginRendering({.area = AREA}); @@ -452,17 +452,19 @@ JVK_TEST(StageGraph, exception_in_scoped_submit_submits_nothing) { } catch(test_exception const&) {} - EXPECT_EQ(stage.status(), Stage::Status::UNSUBMITTED); - // the scoped_rendering ends the rendering on both paths + // the skip discards the recording + EXPECT_EQ(stage.status(), Stage::Status::SKIPPED); EXPECT_EQ(stage.primary().rendering(), nullptr); - EXPECT_TRUE(stage.primary().recording()); + EXPECT_FALSE(stage.primary().recording()); - // the next frame skips the stage - auto& next = next_frame(core, graph).stage(0); - EXPECT_EQ(stage.status(), Stage::Status::SKIPPED); - submit_empty(next); - wait(core, next); + wait(core, frame.stage(1)); wait(core, stage); + EXPECT_GE(stage.semaphore().gpuValue(), frame.number()); + + auto& next = next_frame(core, graph); + submit_empty(next.stage(0)); + submit_empty(next.stage(1)); + wait(core, next.stage(1)); } JVK_TEST(StageGraph, destruction_after_an_exception_skips_the_unsubmitted_stage) { @@ -477,12 +479,38 @@ JVK_TEST(StageGraph, destruction_after_an_exception_skips_the_unsubmitted_stage) }; auto& frame = next_frame(core, graph); submit_empty(frame.stage(1)); - auto const primary = frame.stage(0).begin(); + // before the scope of the waited stage: it stays unsubmitted throw test_exception{}; }; EXPECT_THROW(run(), test_exception); } +JVK_TEST(StageGraph, failed_submit_next_frame_rethrows_the_destruction_skips_the_stage) { + test::Context const context{}; + Core core{context.instance, test::Context::CONFIG, {}}; + + { + StageGraph graph{ + core, + {.stages = {{.queueIdx = 0}, {.queueIdx = 0, .waits = {TRANSFER_WAIT_ON_0}}}} + }; + + auto& frame = next_frame(core, graph); + submit_empty(frame.stage(1)); + auto& stage = frame.stage(0); + { + auto const primary = stage.begin(); + // the end of the scope submits: its first allocation fails + test::fail_next_allocation(); + } + EXPECT_EQ(stage.status(), Stage::Status::UNSUBMITTED); + + EXPECT_THROW(next_frame(core, graph), std::bad_alloc); + EXPECT_EQ(stage.status(), Stage::Status::UNSUBMITTED); + } + // ~StageGraph() skipped the stage: its waiter went on, the destruction ended +} + JVK_TEST(StageGraph, submitted_and_co_await_of_a_stage) { test::Context const context{}; Core core{context.instance, test::Context::CONFIG, {}}; diff --git a/jvk/tests/src/graph/surface_test.cpp b/jvk/tests/src/graph/surface_test.cpp index 09c01d3e..4fe8160d 100644 --- a/jvk/tests/src/graph/surface_test.cpp +++ b/jvk/tests/src/graph/surface_test.cpp @@ -15,6 +15,8 @@ #include "cvk/utility/vk_exceptions.hpp" #include "cvk/utility/vk_overloads.hpp" +#include + #include #include @@ -279,6 +281,21 @@ namespace { return *image; } + /** the `vkQueuePresentKHR()` of the device table before `lost_present()` */ + PFN_vkQueuePresentKHR realQueuePresent = nullptr; + + /** + * presents, then reports a lost surface for every swapchain + */ + VKAPI_ATTR VkResult VKAPI_CALL lost_present(VkQueue queue, VkPresentInfoKHR const* info) { + if(auto const result = realQueuePresent(queue, info); result < 0) + return result; + if(info->pResults != nullptr) + for(uint32_t i = 0; i < info->swapchainCount; ++i) + info->pResults[i] = VK_ERROR_SURFACE_LOST_KHR; + return VK_ERROR_SURFACE_LOST_KHR; + } + /** * the scene stage clears the image, the ui stage draws over it and presents * @details the ui stage waits for the scene stage in the frame @@ -656,13 +673,12 @@ JVK_TEST(Surface, exception_in_the_recording_submits_and_presents_nothing) { } catch(test_exception const&) {} + // the scope skipped the stage, the skip drops the image, the next acquire gives it back first ASSERT_NE(stagePtr, nullptr); - EXPECT_EQ(stagePtr->status(), Stage::Status::UNSUBMITTED); + EXPECT_EQ(stagePtr->status(), Stage::Status::SKIPPED); EXPECT_TRUE(surface.swapchain().current().acquired(imageIdx)); - // the next frame skips the stage and drops the image, the next acquire gives it back first auto& stage = next_frame(core, graph).stage(0); - EXPECT_EQ(stagePtr->status(), Stage::Status::SKIPPED); { auto const image = acquire(core, surface, stage); ASSERT_TRUE(image.has_value()); @@ -731,6 +747,39 @@ JVK_TEST(Surface, exception_propagated_to_the_end_destroys_graph_and_surface) { EXPECT_THROW(run(), test_exception); } +JVK_TEST(Surface, failed_present_arrives_at_the_next_acquire_and_not_at_next_frame) { + test::Context const context{}; + auto windowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, windowSurface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; + + // the core reads the device table at each call: the presents report a lost surface until the + // restore + cvk::Core const& vkCore = core; + auto* const table = const_cast(vkCore.functions()); + realQueuePresent = std::exchange(table->vkQueuePresentKHR, lost_present); + present_frame(core, graph, surface); + + auto& stage = next_frame(core, graph).stage(0); + // the acquire waits for the present of the last image, then rethrows its error + try { + [[maybe_unused]] auto const image = acquire(core, surface, stage); + ADD_FAILURE() << "the acquire must rethrow the error of the present"; + } + catch(cvk::vk_result_exception const& e) { EXPECT_EQ(e.vkResult(), VK_ERROR_SURFACE_LOST_KHR); } + table->vkQueuePresentKHR = realQueuePresent; + stage.skip(); + + // the graph has no error, the surface rethrew it once + EXPECT_NO_THROW(present_frame(core, graph, surface)); + EXPECT_NO_THROW(present_frame(core, graph, surface)); +} + JVK_TEST(Surface, acquire_in_one_stage_presents_after_another) { constexpr size_t FRAMES = 4; test::Context const context{}; @@ -841,12 +890,11 @@ JVK_TEST(Surface, exception_in_the_present_stage_drops_the_image) { throw test_exception{}; } catch(test_exception const&) {} - EXPECT_EQ(frame[UI].status(), Stage::Status::UNSUBMITTED); - // the next frame skips the ui stage and drops the image, the next acquire unacquires it - present_scene_and_ui(core, graph, surface); + // the scope skipped the ui stage, the skip drops the image, the next acquire unacquires it EXPECT_EQ(frame[UI].status(), Stage::Status::SKIPPED); present_scene_and_ui(core, graph, surface); + present_scene_and_ui(core, graph, surface); } JVK_TEST(Surface, two_surfaces_present_after_one_stage) { From 6416f9bf24a198af200cc5a320d0802f029d9311 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:52:18 +0100 Subject: [PATCH 51/68] jvk: a failed skip in ~StageGraph() logs and terminates - the stage got no submission: its waiters and _submissions.wait() would hang without a message - the same handling as dev::skip_submit() - a death test with a failed allocation of the skip --- jvk/incl/jvk/graph/stage_graph.hpp | 3 ++- jvk/src/graph/stage_graph.cpp | 12 ++++++++++++ jvk/tests/src/graph/stage_graph_test.cpp | 15 +++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index 65fc8f5b..18e7174a 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -70,7 +70,8 @@ class StageGraph { * @details * - the skip drops the presents of the stage, see `Surface::acquire()` * - waits for the end of every submission - * - a failed skip or wait does not stop the destruction + * - a failed skip terminates: the waiters of the stage would hang + * - a failed wait does not stop the destruction * @attention blocks the calling thread: a worker of the core must be free for the submissions */ ~StageGraph(); diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index 41ca3349..b19d034f 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -116,6 +116,18 @@ StageGraph::~StageGraph() { continue; // the skip drops the presents of the stage: the surfaces outlive the graph skip(stage); + // a failed skip leaves the stage unsubmitted: nothing marks it, its waiters and + // _submissions.wait() would hang + if(stage.status() == Stage::Status::UNSUBMITTED) { + JVK_STABLE_ERR( + true, + "the skip of an unsubmitted stage in ~StageGraph() failed, got stage {} of " + "frame {}", + stage.id(), + stage.frameNumber() + ) {} + std::terminate(); + } } _submissions.wait(); diff --git a/jvk/tests/src/graph/stage_graph_test.cpp b/jvk/tests/src/graph/stage_graph_test.cpp index 4b611db5..fcf51794 100644 --- a/jvk/tests/src/graph/stage_graph_test.cpp +++ b/jvk/tests/src/graph/stage_graph_test.cpp @@ -511,6 +511,21 @@ JVK_TEST(StageGraph, failed_submit_next_frame_rethrows_the_destruction_skips_the // ~StageGraph() skipped the stage: its waiter went on, the destruction ended } +JVK_TEST(StageGraph, failed_skip_in_the_destruction_terminates) { + // the child runs the test again: the parent has device threads + GTEST_FLAG_SET(death_test_style, "threadsafe"); + test::Context const context{}; + Core core{context.instance, test::Context::CONFIG, {}}; + + auto const destroy = [&core] { + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; + [[maybe_unused]] auto const& frame = next_frame(core, graph); + // the destruction skips the unsubmitted stage: its first allocation fails + test::fail_next_allocation(); + }; + ASSERT_DEATH(destroy(), "the skip of an unsubmitted stage in ~StageGraph\\(\\) failed"); +} + JVK_TEST(StageGraph, submitted_and_co_await_of_a_stage) { test::Context const context{}; Core core{context.instance, test::Context::CONFIG, {}}; From 70adf52a0312ef8b570fdf6285f83cfaa3fdbcbd Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:56:42 +0100 Subject: [PATCH 52/68] tests: no death tests - removes the death tests of ~StageGraph(), Surface::acquire() and DescriptorSpan - nothing replaces them --- .../data/descriptor/descriptor_heap_test.cpp | 15 ----------- jvk/tests/src/graph/stage_graph_test.cpp | 15 ----------- jvk/tests/src/graph/surface_test.cpp | 25 ------------------- 3 files changed, 55 deletions(-) diff --git a/cvk/tests/src/data/descriptor/descriptor_heap_test.cpp b/cvk/tests/src/data/descriptor/descriptor_heap_test.cpp index 80647dc0..649c487d 100644 --- a/cvk/tests/src/data/descriptor/descriptor_heap_test.cpp +++ b/cvk/tests/src/data/descriptor/descriptor_heap_test.cpp @@ -299,21 +299,6 @@ CVK_TEST(DescriptorSpan, mapping_is_the_mapping_of_the_heap) { ); } -#ifdef CTH_DEBUG_MODE -CVK_TEST(DescriptorSpan, index_out_of_the_span_crashes) { - // the child runs the test again: the parent has device threads - GTEST_FLAG_SET(death_test_style, "threadsafe"); - test::Context const context{}; - SamplerHeap heap{context.core, {.samplers = 2}, create}; - - ASSERT_DEATH( - [[maybe_unused]] - auto const cell = heap.samplers()[2], - ".*" - ); -} -#endif - namespace { /** * heaps, texture and storage image of the heap compute shader diff --git a/jvk/tests/src/graph/stage_graph_test.cpp b/jvk/tests/src/graph/stage_graph_test.cpp index fcf51794..4b611db5 100644 --- a/jvk/tests/src/graph/stage_graph_test.cpp +++ b/jvk/tests/src/graph/stage_graph_test.cpp @@ -511,21 +511,6 @@ JVK_TEST(StageGraph, failed_submit_next_frame_rethrows_the_destruction_skips_the // ~StageGraph() skipped the stage: its waiter went on, the destruction ended } -JVK_TEST(StageGraph, failed_skip_in_the_destruction_terminates) { - // the child runs the test again: the parent has device threads - GTEST_FLAG_SET(death_test_style, "threadsafe"); - test::Context const context{}; - Core core{context.instance, test::Context::CONFIG, {}}; - - auto const destroy = [&core] { - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - [[maybe_unused]] auto const& frame = next_frame(core, graph); - // the destruction skips the unsubmitted stage: its first allocation fails - test::fail_next_allocation(); - }; - ASSERT_DEATH(destroy(), "the skip of an unsubmitted stage in ~StageGraph\\(\\) failed"); -} - JVK_TEST(StageGraph, submitted_and_co_await_of_a_stage) { test::Context const context{}; Core core{context.instance, test::Context::CONFIG, {}}; diff --git a/jvk/tests/src/graph/surface_test.cpp b/jvk/tests/src/graph/surface_test.cpp index 4fe8160d..2629702b 100644 --- a/jvk/tests/src/graph/surface_test.cpp +++ b/jvk/tests/src/graph/surface_test.cpp @@ -932,31 +932,6 @@ JVK_TEST(Surface, two_surfaces_present_after_one_stage) { } } -#ifdef CTH_DEBUG_MODE -JVK_TEST(Surface, acquire_for_a_submitted_present_stage_crashes) { - // the child runs the test again: the parent has device threads - GTEST_FLAG_SET(death_test_style, "threadsafe"); - test::Context const context{}; - auto windowSurface = test::headless_surface(context.instance); - std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, windowSurface)) - GTEST_SKIP() << "no device presents to a headless surface"; - auto& core = *coreOpt; - - Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; - StageGraph graph{core, scene_and_ui()}; - - auto& frame = next_frame(core, graph); - frame[UI].skip(); - ASSERT_DEATH( - [[maybe_unused]] - auto const image = acquire(core, surface, frame[SCENE], frame[UI]), - ".*" - ); - frame[SCENE].skip(); -} -#endif - JVK_TEST(Surface, present_queue_of_the_same_family) { constexpr size_t FRAMES = 4; test::Context const context{}; From 9b14a838c71ac6190b2429c72467ec0889ac53db Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:58:52 +0100 Subject: [PATCH 53/68] jvk: core_test without the compile check of the graph headers, their sources and tests exist --- jvk/tests/src/base/core_test.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/jvk/tests/src/base/core_test.cpp b/jvk/tests/src/base/core_test.cpp index a18aa08d..37daaa95 100644 --- a/jvk/tests/src/base/core_test.cpp +++ b/jvk/tests/src/base/core_test.cpp @@ -6,9 +6,6 @@ #include "jvk/base/queue.hpp" #include "jvk/base/queue_sets.hpp" #include "jvk/data/sampler_heap.hpp" -//TEMP compile check of the phase 6 headers until their sources exist -#include "jvk/graph/surface.hpp" -#include "jvk/graph/stage_graph.hpp" #include "jvk/sync/semaphore.hpp" #include "jvk/sync/timeline_reactor.hpp" From 70b653a8d8302ccb17b4d2318357eb0fb9302e8f Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:39:55 +0100 Subject: [PATCH 54/68] jvk: SamplerHeap has the lifecycle of ResourceHeap, Core holds it without std::optional - base constructor, cvk::create form, create(), destroy(), optDestroy(), created() - Core creates it with sampler counts, destroys it before the resource heap - destroy() of both heaps: every handle and every Stasis with a cell of the heap is destroyed - insert() and mappings() of both heaps: @pre created(), vk() has no @pre - lifecycle tests like the ResourceHeap ones --- jvk/incl/jvk/base/core.hpp | 7 ++-- jvk/incl/jvk/data/resource_heap.hpp | 5 ++- jvk/incl/jvk/data/sampler_heap.hpp | 46 ++++++++++++++++++++++--- jvk/src/base/core.cpp | 11 +++--- jvk/src/data/sampler_heap.cpp | 28 +++++++++++++--- jvk/tests/src/data/heap_test.cpp | 52 +++++++++++++++++++++++++++-- 6 files changed, 129 insertions(+), 20 deletions(-) diff --git a/jvk/incl/jvk/base/core.hpp b/jvk/incl/jvk/base/core.hpp index eec4b23b..6272e33e 100644 --- a/jvk/incl/jvk/base/core.hpp +++ b/jvk/incl/jvk/base/core.hpp @@ -102,7 +102,9 @@ class Core { * @details a failed wait does not stop the destruction * @pre `created()` * @pre the calling thread runs no job of the core - * @pre no handle of the heaps is left, the stage graphs of the core are destroyed + * @pre every `ResourceHeap::ImageHandle` and every `SamplerHeap::Sampler` of the heaps is + * destroyed + * @pre every `StageGraph` of the core is destroyed */ void destroy(); @@ -206,8 +208,7 @@ class Core { // destroyed before the cvk core ResourceHeap _resourceHeap; ///< not created without counts, see `HeapsConfig` - // the sampler heap needs the created cvk core, no heap without counts - std::optional _samplerHeapOpt{}; + SamplerHeap _samplerHeap; ///< not created without counts, see `HeapsConfig` public: Core(Core const& other) = delete; diff --git a/jvk/incl/jvk/data/resource_heap.hpp b/jvk/incl/jvk/data/resource_heap.hpp index f7246830..2a405680 100644 --- a/jvk/incl/jvk/data/resource_heap.hpp +++ b/jvk/incl/jvk/data/resource_heap.hpp @@ -97,7 +97,9 @@ class ResourceHeap { /** * destroys the cvk heap and forgets the cells * @pre `created()` - * @pre no handle and no cell in a stasis of the heap is left + * @pre every `ImageHandle` of the heap is destroyed + * @pre every `Stasis` with a cell of the heap is destroyed, e.g. the `StageGraph` of a stage + * that retained a handle of the heap * @pre the gpu does not use the heap */ void destroy(); @@ -113,6 +115,7 @@ class ResourceHeap { /** * places the descriptor into a free cell of its type * @return the owning handle of the cell + * @pre `created()` * @pre the layout of the descriptor is the `ImageHandle::LAYOUT` of its handle * @pre the preconditions of `cvk::ResourceHeap::write()` besides the index * @throws jvk::jvk_exception reason: every cell of the type is in use diff --git a/jvk/incl/jvk/data/sampler_heap.hpp b/jvk/incl/jvk/data/sampler_heap.hpp index 5c16090d..764ee153 100644 --- a/jvk/incl/jvk/data/sampler_heap.hpp +++ b/jvk/incl/jvk/data/sampler_heap.hpp @@ -33,7 +33,7 @@ namespace jvk { * - `Stage::retain()` keeps a handle while the gpu uses it * - the shader convention: `mappings()` and `jvk/heaps.glsl` * - owns a `cvk::SamplerHeap`, `vk()` reads it - * - thread safe + * - `insert()` and the handles: thread safe */ class SamplerHeap { public: @@ -43,21 +43,53 @@ class SamplerHeap { class Sampler; /** - * creates the cvk heap + * base constructor + */ + SamplerHeap(cvk::Core const&, Config const&); + + /** + * constructs and creates + * @details calls @ref SamplerHeap(cvk::Core const&, Config const&), `create()` + */ + explicit SamplerHeap(cvk::Core const&, Config const&, cvk::create_t); + + /** + * @note calls `optDestroy()` + */ + ~SamplerHeap() { optDestroy(); } + + /** + * creates the cvk heap, every cell is free * @pre `cvk::Core::created()` * @pre the preconditions of `cvk::SamplerHeap::create()` + * @post `created()` + * @note calls `optDestroy()` * @throws cvk::cvk_exception the exceptions of `cvk::SamplerHeap::create()` */ - SamplerHeap(cvk::Core const&, Config const&); + void create(); + + /** + * destroys the cvk heap and forgets the cells + * @pre `created()` + * @pre every `Sampler` of the heap is destroyed + * @pre every `Stasis` with a cell of the heap is destroyed, e.g. the `StageGraph` of a stage + * that retained a handle of the heap + * @pre the gpu does not use the heap + */ + void destroy(); /** - * @pre no handle and no cell in a stasis of the heap is left + * if `created()` -> calls `destroy()` */ - ~SamplerHeap(); + void optDestroy() { + if(created()) + destroy(); + } /** * the cell of the config: an equal config -> its cell, else a free cell with the config * @return a counted handle of the cell + * @pre `created()` * @throws jvk::jvk_exception reason: every cell is in use * @throws cvk::vk_result_exception the exceptions of `cvk::SamplerHeap::write()` */ @@ -65,6 +97,7 @@ class SamplerHeap { /** * @return the mappings of the shader convention: the samplers + * @pre `created()` * @details at `constants::HEAP_SET`, `constants::HEAP_SAMPLER_BINDING` * @see `jvk/heaps.glsl`, `ResourceHeap::mappings()` */ @@ -76,9 +109,12 @@ class SamplerHeap { */ [[nodiscard]] constexpr cvk::SamplerHeap const& vk() const { return _vk; } + [[nodiscard]] constexpr bool created() const { return _vk.created(); } [[nodiscard]] constexpr Config const& config() const { return _vk.config(); } private: + void forget(); + void ref(uint32_t idx) const; void unref(uint32_t idx) const; diff --git a/jvk/src/base/core.cpp b/jvk/src/base/core.cpp index 9856f51d..e7446326 100644 --- a/jvk/src/base/core.cpp +++ b/jvk/src/base/core.cpp @@ -28,7 +28,8 @@ Core::Core(cvk::Instance const& instance, Config config) : : _config.workers }, _reactor{*_corePtr}, - _resourceHeap{*_corePtr, _config.heaps.resources} {} + _resourceHeap{*_corePtr, _config.heaps.resources}, + _samplerHeap{*_corePtr, _config.heaps.samplers} {} Core::Core( cvk::Instance const& instance, @@ -60,7 +61,7 @@ void Core::create(span const> surfaces) { if(_config.heaps.createsResourceHeap()) _resourceHeap.create(); if(_config.heaps.createsSamplerHeap()) - _samplerHeapOpt.emplace(*_corePtr, _config.heaps.samplers); + _samplerHeap.create(); } catch(...) { _resourceHeap.optDestroy(); @@ -112,7 +113,7 @@ void Core::destroy() { } destroyQueues(); - _samplerHeapOpt.reset(); + _samplerHeap.optDestroy(); _resourceHeap.optDestroy(); _reactor.destroy(); _workers.await_stop(); @@ -161,9 +162,9 @@ void Core::destroyQueues() { SamplerHeap const& Core::samplerHeap() const { debug_check(*this); CTH_CRITICAL( - !_samplerHeapOpt.has_value(), + !_samplerHeap.created(), "the core must have a sampler heap, see HeapsConfig" ) {} - return *_samplerHeapOpt; + return _samplerHeap; } } // namespace jvk diff --git a/jvk/src/data/sampler_heap.cpp b/jvk/src/data/sampler_heap.cpp index bd4368ef..a52c24aa 100644 --- a/jvk/src/data/sampler_heap.cpp +++ b/jvk/src/data/sampler_heap.cpp @@ -10,17 +10,30 @@ namespace jvk { SamplerHeap::SamplerHeap(cvk::Core const& core, Config const& config) : - _vk{core, config, cvk::create}, + _vk{core, config}, _cells{config.samplers}, _slots(config.samplers) {} -SamplerHeap::~SamplerHeap() { - // a moved-from heap has no cvk heap +SamplerHeap::SamplerHeap(cvk::Core const& core, Config const& config, cvk::create_t) : + SamplerHeap{core, config} { create(); } + +void SamplerHeap::create() { + optDestroy(); + + _vk.create(); +} + +void SamplerHeap::destroy() { + cvk::SamplerHeap::debug_check(_vk); CTH_CRITICAL( - _vk.created() && _cells.used() != 0, + _cells.used() != 0, "every sampler of the heap must be gone, got {}", _cells.used() ) {} + + _vk.destroy(); + + forget(); } auto SamplerHeap::insert(cvk::SamplerConfig const& config) const -> Sampler { @@ -70,4 +83,11 @@ void SamplerHeap::unref(uint32_t idx) const { _indices.erase(config); _cells.erase(idx); } + +void SamplerHeap::forget() { + auto const& config = _vk.config(); + _cells = dev::free_list{config.samplers}; + _indices.clear(); + _slots.assign(config.samplers, slot{}); +} } diff --git a/jvk/tests/src/data/heap_test.cpp b/jvk/tests/src/data/heap_test.cpp index cb45be32..f280a13d 100644 --- a/jvk/tests/src/data/heap_test.cpp +++ b/jvk/tests/src/data/heap_test.cpp @@ -255,9 +255,57 @@ JVK_TEST(ResourceHeap, a_moved_heap_inserts) { EXPECT_EQ(other.insert(cvk::SampledImageDescriptor{texture}).idx().get(), 0); } -JVK_TEST(SamplerHeap, a_moved_heap_inserts) { +JVK_TEST(SamplerHeap, base_constructor_does_not_create) { + test::Context const context{}; + + SamplerHeap const heap{context.core, {.samplers = 2}}; + + EXPECT_FALSE(heap.created()); + EXPECT_EQ(heap.config().samplers, 2); +} + +JVK_TEST(SamplerHeap, create_and_destroy) { test::Context const context{}; SamplerHeap heap{context.core, {.samplers = 2}}; + + heap.create(); + EXPECT_TRUE(heap.created()); + + heap.destroy(); + EXPECT_FALSE(heap.created()); + + // a leak shows up when the shared device is destroyed + heap.optDestroy(); + SamplerHeap const created{context.core, {.samplers = 2}, cvk::create}; + EXPECT_TRUE(created.created()); +} + +JVK_TEST(SamplerHeap, destroy_frees_every_cell) { + test::Context const context{}; + SamplerHeap heap{context.core, {.samplers = 2}, cvk::create}; + cvk::SamplerConfig const nearest{.magFilter = VK_FILTER_NEAREST}; + + { + auto linearSampler = heap.insert(cvk::SamplerConfig{}); + auto nearestSampler = heap.insert(nearest); + ASSERT_EQ(linearSampler.idx().get(), 0); + ASSERT_EQ(nearestSampler.idx().get(), 1); + + // the cell of the last erased handle comes first, cell 1 here + { auto const gone = std::move(linearSampler); } + { auto const gone = std::move(nearestSampler); } + } + + heap.destroy(); + heap.create(); + + // every cell is free and no config is known: the first insert gets cell 0 + EXPECT_EQ(heap.insert(nearest).idx().get(), 0); +} + +JVK_TEST(SamplerHeap, a_moved_heap_inserts) { + test::Context const context{}; + SamplerHeap heap{context.core, {.samplers = 2}, cvk::create}; cvk::SamplerConfig const nearest{.magFilter = VK_FILTER_NEAREST}; // the moved-from heaps keep the count of the returned cell EXPECT_EQ(heap.insert(cvk::SamplerConfig{}).idx().get(), 0); @@ -265,7 +313,7 @@ JVK_TEST(SamplerHeap, a_moved_heap_inserts) { SamplerHeap moved{std::move(heap)}; EXPECT_EQ(moved.insert(cvk::SamplerConfig{}).idx().get(), 0); - SamplerHeap other{context.core, {.samplers = 1}}; + SamplerHeap other{context.core, {.samplers = 1}, cvk::create}; other = std::move(moved); EXPECT_EQ(other.config().samplers, 2); auto const linearSampler = other.insert(cvk::SamplerConfig{}); From ad3bc958d97b9b55db0bde533d9e5310bf41095b Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:40:05 +0100 Subject: [PATCH 55/68] lib: cth_cmake on main after #11, same content --- lib/cth_cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/cth_cmake b/lib/cth_cmake index 3038f7b7..22e80160 160000 --- a/lib/cth_cmake +++ b/lib/cth_cmake @@ -1 +1 @@ -Subproject commit 3038f7b73ee98d8694455df2be07701f74bf3964 +Subproject commit 22e80160faebd0e31ff9139341f7a93ec6c17c5e From 94c06c6d57a91d566633dc5ea5478b18c6deb09c Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:10:48 +0100 Subject: [PATCH 56/68] lib: cth on master after #34, same content --- lib/cth | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/cth b/lib/cth index d94d093a..03336d0d 160000 --- a/lib/cth +++ b/lib/cth @@ -1 +1 @@ -Subproject commit d94d093a4c1d8fe95e4219f5207728facc1995ec +Subproject commit 03336d0d1f8cd916c5b33afc26e446ffe8d6720f From 6aba0c1331d347d8a3aa05f4255c1cc71bd41da0 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:18:25 +0100 Subject: [PATCH 57/68] jvk: the present is a use of the image in the epilogue of the present stage - the epilogue uses go through append(): another family of the last use -> the last queue releases the image, the epilogue acquires it - presentBarriers() only releases to the family of the surface queue, in a second barrier after the epilogue uses - StageSlot::presentStates removed: the state before the release is PRESENT_STATE - Surface::acquire(): the @pre "the last use is on the family of the present stage" removed - Surface::acquire(): the present stage waits for every stage of the frame that uses the image - test: a present stage of another family without a use of the image --- jvk/incl/jvk/graph/stage.hpp | 28 ++++++++--- jvk/incl/jvk/graph/stage_graph.hpp | 7 +-- jvk/incl/jvk/graph/surface.hpp | 11 ++-- jvk/src/graph/stage_graph.cpp | 75 +++++++++++++--------------- jvk/tests/src/graph/surface_test.cpp | 29 +++++++++++ 5 files changed, 97 insertions(+), 53 deletions(-) diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index a509a02f..9ed95e62 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -199,11 +199,20 @@ struct StageSlot { SubmitInfo submitInfo{}; // the scratch of the presents: the submission refills them, they keep their capacity - /** the barriers of the presented images, recorded into `StageSlot::epilogue` */ + /** the presents as uses of their images after the primary, appended to the graph states */ + ResourceTracker epilogueUses{}; + + /** + * the barriers of the uses in `StageSlot::epilogueUses`, recorded into `StageSlot::epilogue` + * @details first in the epilogue + */ cvk::Barrier epilogueBarriers{}; - /** per entry of `StageSlot::presents`: the state of its image before the epilogue */ - std::vector presentStates{}; + /** + * the releases of the presented images to the queue family of their surface queue + * @details after `StageSlot::epilogueBarriers` in the epilogue + */ + cvk::Barrier presentReleases{}; /** the images of `StageSlot::presents`, the images of one queue in a row */ std::vector presentImages{}; @@ -230,7 +239,10 @@ struct StageSlot { PrimaryCmdBuffer primary; - /** barriers of the presented images, submitted after the primary, see `Stage::present()` */ + /** + * the uses of the presented images, submitted after the primary, see `Stage::present()` + * @details records `StageSlot::epilogueBarriers`, then `StageSlot::presentReleases` + */ PrimaryCmdBuffer epilogue; std::vector secondaries{}; ///< `StageConfig::secondaries` of them @@ -380,8 +392,12 @@ class Stage { * presents the swapchain image of the present after the submit of this frame * @details `Surface::acquire()` calls it for its present stage * @details the submission of the frame: - * - records the barrier of the image to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` into the epilogue, - * after the primary, see `StageSlot::epilogue` + * - the present is a use of the image after the primary, in the epilogue: the barrier to + * `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR`, see `StageSlot::epilogue` + * - another queue family of the last use: the last queue releases the image, the epilogue + * acquires it + * - another queue family of the surface queue: the epilogue releases the image, the queue of + * the surface acquires it * - presents the image after the submit, the images of one queue in one `vkQueuePresentKHR()` * - a skip or a failed submit drops the image * @param present of the image, the stage owns it until its submission resolves it diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index 18e7174a..335e2ae5 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -108,8 +108,10 @@ class StageGraph { * its last queue, the prologue acquires it * - waits for the stage waits of the config and the waits of `Stage::await()` * - signals `Stage::semaphore()` with `Stage::frameNumber()` - * - the images of `Stage::present()`: the epilogue after the primary transitions them, the - * presents follow the submit, see `Surface::acquire()` + * - the images of `Stage::present()`: uses after the primary, in the epilogue, the presents + * follow the submit, see `Surface::acquire()` + * - another queue family of the last use of a presented image: the last queue releases it, + * the epilogue acquires it * - an error of the submission: skips, `nextFrame()` rethrows the error * - a failed present: the surface of the image gets the error, see `Surface::acquire()` * - after the gpu finished: destroys the retained objects @@ -212,7 +214,6 @@ class StageGraph { release_map_t releases ); - /** the caller holds `_statesMutex`, after `append()` */ void presentBarriers(dev::StageSlot&); /** throws only for a failed submit: nothing is presented or resolved then */ diff --git a/jvk/incl/jvk/graph/surface.hpp b/jvk/incl/jvk/graph/surface.hpp index 2d28ed2b..0e48bec6 100644 --- a/jvk/incl/jvk/graph/surface.hpp +++ b/jvk/incl/jvk/graph/surface.hpp @@ -154,8 +154,10 @@ class Surface { * - the state of the image in its graph: `VK_IMAGE_LAYOUT_UNDEFINED` with the wait stages, see * `StageGraph::assume()`: the first barrier of the image chains with the wait * @details the present stage gets the present of the image, see `Stage::present()`: - * - its submit ends with the barrier of the image to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR`, from - * the state that the stages before left: the epilogue, after the primary + * - the present is a use of the image by the present stage after its primary, in the epilogue: + * the barrier to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` from the state that the stages before left + * - another queue family of the last use: the last queue releases the image, the epilogue + * acquires it * - another queue family than the queue of the surface: the epilogue releases the image, the * queue of the surface acquires it, see `Queue::transfer()` * - after its submit: the present on the queue of the surface, one `vkQueuePresentKHR()` for @@ -177,11 +179,10 @@ class Surface { * @pre `created()` * @pre `Stage::status()` of both stages is `UNSUBMITTED` * @pre both stages belong to one frame of one graph - * @pre the present stage is the acquire stage or waits for it in the frame, directly or through - * other stages, see `StageWait` + * @pre the present stage waits for every stage of the frame that uses the image, the acquire + * stage included, directly or through other stages, or is that stage, see `StageWait` * @pre the present stage of the last image of this surface is submitted or skipped: else the * wait never ends - * @pre the last use of the image before the present is on the queue family of the present stage * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode * @throws cvk::vk_result_exception other result of `vkAcquireNextImageKHR()` or * `vkCreateSwapchainKHR()` diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index b19d034f..ceb3ad9a 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -43,6 +43,14 @@ namespace { .scope = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, }; + /** the present as a use of the image, its state is `PRESENT_STATE` */ + constexpr ImageAccess PRESENT_ACCESS{ + .layout = PRESENT_STATE.layout, + .stages = PRESENT_STATE.scope.stages, + .access = PRESENT_STATE.scope.access, + .mipLevels = 1, + }; + /** `src` waits for the stages of the first use, no access: like `cvk::layout_transition()` */ [[nodiscard]] constexpr cvk::ImageBarrierInfo from_undefined( ImageState const& first, @@ -299,9 +307,20 @@ cth::co::executor_task StageGraph::submission( { std::scoped_lock const lock{_statesMutex}; append(stageSlot.primary.states(), queue, prologue, releases); - // after the append: the states that the stages before and this one left - presentBarriers(stageSlot); + // the presents after the primary: uses of the images in the epilogue + auto& epilogueUses = stageSlot.epilogueUses; + epilogueUses.clear(); + stageSlot.epilogueBarriers.clear(); + // the first use of each image in the tracker: no barrier + for(auto const& present : stageSlot.presents) + epilogueUses.access( + present.swapchainImage(), + PRESENT_ACCESS, + stageSlot.epilogueBarriers + ); + append(epilogueUses, queue, stageSlot.epilogueBarriers, releases); } + presentBarriers(stageSlot); // the skip of a failed submit waits for the releases too if(!releases.empty()) info.waits.append_range(co_await release(std::move(releases))); @@ -314,10 +333,13 @@ cth::co::executor_task StageGraph::submission( prologue.execute(stageSlot.prologue); stageSlot.prologue.end(); } - bool const withEpilogue = !stageSlot.epilogueBarriers.empty(); + bool const withEpilogue = + !stageSlot.epilogueBarriers.empty() || !stageSlot.presentReleases.empty(); if(withEpilogue) { stageSlot.epilogue.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); + // two executes: two barriers of one image in one execute have no order stageSlot.epilogueBarriers.execute(stageSlot.epilogue); + stageSlot.presentReleases.execute(stageSlot.epilogue); stageSlot.epilogue.end(); } @@ -463,37 +485,19 @@ void StageGraph::append( void StageGraph::presentBarriers(dev::StageSlot& stageSlot) { auto const family = stageSlot.queue->vk().familyIndex(); - auto& barriers = stageSlot.epilogueBarriers; - barriers.clear(); - stageSlot.presentStates.clear(); + auto& releases = stageSlot.presentReleases; + releases.clear(); for(auto const& present : stageSlot.presents) { - cvk::Image const& image = present.swapchainImage(); - // Surface::acquire() assumed the image: it has a state - auto const lastOpt = _states.last(image.get(), 0); - CTH_CRITICAL(!lastOpt.has_value(), "the presented image must have a state") {} - auto const presentFamily = present.queue().vk().familyIndex(); if(presentFamily == family) - barriers.add( - image.get(), - image.aspectMask(), - cvk::ImageBarrierInfo{ - .src = lastOpt->scope, - .dst = PRESENT_STATE.scope, - .newLayout = PRESENT_STATE.layout, - .oldLayout = lastOpt->layout, - } - ); - else - barriers.add( - image.get(), - image.aspectMask(), - dev::release_half(*lastOpt, PRESENT_STATE, family, presentFamily, 0) - ); - - stageSlot.presentStates.push_back(*lastOpt); - _states.assume(image, PRESENT_STATE); + continue; + cvk::Image const& image = present.swapchainImage(); + releases.add( + image.get(), + image.aspectMask(), + dev::release_half(PRESENT_STATE, PRESENT_STATE, family, presentFamily, 0) + ); } } @@ -576,21 +580,14 @@ cth::co::executor_task StageGraph::submitAndPresent( cvk::Barrier acquire{}; auto& signals = stageSlot.presentSignals; signals.clear(); - for(size_t presentIdx = 0; presentIdx < presents.size(); ++presentIdx) { - auto const& present = presents[presentIdx]; + for(auto const& present : presents) { if(&present.queue() != &groupQueue) continue; cvk::Image const& image = present.swapchainImage(); acquire.add( image.get(), image.aspectMask(), - dev::acquire_half( - stageSlot.presentStates[presentIdx], - PRESENT_STATE, - family, - groupFamily, - 0 - ) + dev::acquire_half(PRESENT_STATE, PRESENT_STATE, family, groupFamily, 0) ); auto const [swapchain, imageIdx] = present.image(); signals.emplace_back(swapchain->presentSemaphore(imageIdx)); diff --git a/jvk/tests/src/graph/surface_test.cpp b/jvk/tests/src/graph/surface_test.cpp index 2629702b..cac0e8c5 100644 --- a/jvk/tests/src/graph/surface_test.cpp +++ b/jvk/tests/src/graph/surface_test.cpp @@ -952,6 +952,35 @@ JVK_TEST(Surface, present_queue_of_the_same_family) { present_frame(core, graph, surface); } +JVK_TEST(Surface, present_stage_of_another_family_without_a_use_acquires_the_image) { + constexpr size_t FRAMES = 4; + test::Context const context{}; + auto windowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, windowSurface, {GRAPHICS | PRESENT, COMPUTE})) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + if(core.queue(0).vk().familyIndex() == core.queue(1).vk().familyIndex()) + GTEST_SKIP() << "needs two queue families, e.g. ANV_QUEUE_OVERRIDE=gc=2,c=1"; + + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, scene_and_ui(1)}; + + // the scene stage on the family of the surface queue clears the image, the ui stage on the + // other family presents it without a use: its epilogue acquires the image from the scene queue + // each acquire waits for the present of the image before + for(size_t i = 0; i < FRAMES; ++i) { + auto& frame = next_frame(core, graph); + auto const image = acquire(core, surface, frame[SCENE], frame[UI]); + ASSERT_TRUE(image.has_value()); + { + auto const scene = frame[SCENE].begin(); + clear(*scene, *image); + } + auto const ui = frame[UI].begin(); + } +} + JVK_TEST(Surface, present_queue_of_another_family) { constexpr size_t FRAMES = 4; test::Context const context{}; From 6c91d13a08de53625ca51cdf7839f3deeedcc6b6 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:29:47 +0100 Subject: [PATCH 58/68] demo: the cube demo has a scene stage and a ui stage - scene stage: waits for the acquire, the cube into the multisampled targets, resolved into the image - ui stage: waits for the scene stage, ImGui in its own rendering that loads the image, presents - timgui renders with one sample and no depth - the two recordings are two tasks of one cth::co::all() - no image: both stages skip --- demo/cube/src/main.cpp | 205 +++++++++++++++++++++++++++-------------- 1 file changed, 137 insertions(+), 68 deletions(-) diff --git a/demo/cube/src/main.cpp b/demo/cube/src/main.cpp index 20ca3f22..8215b37c 100644 --- a/demo/cube/src/main.cpp +++ b/demo/cube/src/main.cpp @@ -29,6 +29,7 @@ #include #include +#include #include #include #include @@ -73,8 +74,9 @@ constexpr VkSurfaceFormatKHR SURFACE_FORMAT{ constexpr VkFormat DEPTH_FORMAT = VK_FORMAT_D32_SFLOAT; constexpr VkSampleCountFlagBits MSAA_SAMPLES = VK_SAMPLE_COUNT_4_BIT; -constexpr size_t QUEUE_IDX = 0; ///< the graphics queue that presents -constexpr size_t CUBE_STAGE_ID = 0; +constexpr size_t QUEUE_IDX = 0; ///< the graphics queue of both stages, presents +constexpr size_t SCENE_STAGE_ID = 0; ///< the cube, waits for the acquire +constexpr size_t UI_STAGE_ID = 1; ///< ImGui over the scene, presents /** after a frame without an image, e.g. minimized */ constexpr auto IDLE_WAIT = std::chrono::milliseconds{16}; @@ -416,11 +418,112 @@ void frame_time_window(FrameTimes const& times, bool& collapsed) { ImGui::End(); } +/** + * records the scene stage: the cube into the multisampled targets, resolved into the image + * @details + * - `upload` -> records the copies of the cube first + * - a new extent: the stage retains the old targets until the gpu finished them + * - the end of the scope submits + */ +cth::co::executor_task record_scene( + jvk::Core const& core, + jvk::Stage& stage, + jvk::SwapchainImage const& image, + cvk::GraphicsPipeline const& pipeline, + Cube const& cube, + Draw const& draw, + bool upload, + std::optional& targetsOpt +) { + if(!targetsOpt.has_value() || targetsOpt->color.extent() != image.extent) { + if(targetsOpt.has_value()) { + stage.retain(std::move(targetsOpt->colorView)); + stage.retain(std::move(targetsOpt->depthView)); + stage.retain(std::move(targetsOpt->color)); + stage.retain(std::move(targetsOpt->depth)); + } + targetsOpt.emplace(core, image.extent); + } + + auto const submit = stage.begin(); + if(upload) + cube.upload(stage, *submit); + submit->use(cube.sampled, VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT); + submit->use( + cube.vertices, + {VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT} + ); + // before the rendering: no barrier inside it, the bind inside it then needs none + submit->use(cube.indices, {VK_PIPELINE_STAGE_2_INDEX_INPUT_BIT, VK_ACCESS_2_INDEX_READ_BIT}); + + auto const rendering = submit->beginRendering( + { + .colorAttachments = { + { + .view = targetsOpt->colorView, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .clearValue = {.color = {.float32 = {0.02f, 0.02f, 0.03f, 1.f}}}, + .resolveViewPtr = &*image.view, + .resolveMode = VK_RESOLVE_MODE_AVERAGE_BIT, + } + }, + .depthAttachment = cvk::RenderingAttachment{ + .view = targetsOpt->depthView, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .clearValue = {.depthStencil = {.depth = 1.f, .stencil = 0}}, + }, + } + ); + submit->bind(pipeline); + submit->setViewport(image.extent); + submit->setScissor(image.extent); + submit->bindIndices(cube.indices); + submit->pushData(draw); + submit->drawIndexed(36); + co_return; +} + +/** + * records the ui stage: the ImGui frame over the scene in the image + * @details + * - its rendering loads the image, the graph orders it after the resolve of the scene stage + * - the end of the scope submits + */ +cth::co::executor_task record_ui( + jvk::Stage& stage, + jvk::SwapchainImage const& image, + timgui::Imgui& imgui, + ImDrawData& drawData +) { + auto const submit = stage.begin(); + imgui.upload(stage, *submit, drawData); + + auto const rendering = submit->beginRendering( + { + .colorAttachments = { + { + .view = image.view, + .loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + } + }, + } + ); + // the rendering of the ui: the format of the image, one sample, no depth + imgui.draw(stage, *submit, drawData); + co_return; +} + /** * draws the spinning cube and the frame time window in every frame until the window closes * @details - * - only the scope: the `jvk::scoped_submit` submits, the job of the stage presents + * - the scene stage records the cube, the ui stage records ImGui over it and presents the image + * - the two stages record in two tasks of one `cth::co::all()`, see `record_scene()`, + * `record_ui()` * - the ImGui frame comes first: it takes the events also in a frame without an image + * - no image: both stages skip * - frame time: the time between the starts of two iterations, the first iteration has none */ cth::co::executor_task draw_frames( @@ -452,30 +555,24 @@ cth::co::executor_task draw_frames( frame_time_window(frameTimes, frameTimeCollapsed); auto& drawData = imguiFrame.render(); - auto& stage = (co_await graph.nextFrame()).stage(CUBE_STAGE_ID); + auto& frame = co_await graph.nextFrame(); + auto& scene = frame.stage(SCENE_STAGE_ID); + auto& ui = frame.stage(UI_STAGE_ID); + // the scene stage waits for the acquire, the ui stage presents auto const image = co_await surface.acquire( - stage, + scene, + ui, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT ); // extent 0: no image if(!image) { - stage.skip(); + scene.skip(); + ui.skip(); co_await cth::co::this_coro::wait(IDLE_WAIT); continue; } - // a new extent: the frame keeps the old targets until the gpu finished them - if(!targetsOpt.has_value() || targetsOpt->color.extent() != image->extent) { - if(targetsOpt.has_value()) { - stage.retain(std::move(targetsOpt->colorView)); - stage.retain(std::move(targetsOpt->depthView)); - stage.retain(std::move(targetsOpt->color)); - stage.retain(std::move(targetsOpt->depth)); - } - targetsOpt.emplace(core, image->extent); - } - auto const now = std::chrono::steady_clock::now(); float const dt = std::chrono::duration(now - last).count(); last = now; @@ -505,52 +602,11 @@ cth::co::executor_task draw_frames( .sampler = cube.sampler.idx(), }; - auto const submit = stage.begin(); - if(!uploaded) { - cube.upload(stage, *submit); - uploaded = true; - } - imgui.upload(stage, *submit, drawData); - submit->use(cube.sampled, VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT); - submit->use( - cube.vertices, - {VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT} - ); - // before the rendering: no barrier inside it, the bind inside it then needs none - submit->use( - cube.indices, - {VK_PIPELINE_STAGE_2_INDEX_INPUT_BIT, VK_ACCESS_2_INDEX_READ_BIT} - ); - - auto const rendering = submit->beginRendering( - { - .colorAttachments = { - { - .view = targetsOpt->colorView, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .clearValue = {.color = {.float32 = {0.02f, 0.02f, 0.03f, 1.f}}}, - .resolveViewPtr = &*image->view, - .resolveMode = VK_RESOLVE_MODE_AVERAGE_BIT, - } - }, - .depthAttachment = cvk::RenderingAttachment{ - .view = targetsOpt->depthView, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .clearValue = {.depthStencil = {.depth = 1.f, .stencil = 0}}, - }, - } + co_await cth::co::all( + record_scene(core, scene, *image, pipeline, cube, draw, !uploaded, targetsOpt), + record_ui(ui, *image, imgui, drawData) ); - submit->bind(pipeline); - submit->setViewport(extent); - submit->setScissor(extent); - submit->bindIndices(cube.indices); - submit->pushData(draw); - submit->drawIndexed(36); - - // the rendering of the cube: the formats and samples of the targets - imgui.draw(stage, *submit, drawData); + uploaded = true; } } @@ -606,11 +662,7 @@ void run() { pipelineConfig.descriptorMappings.append_range(core.samplerHeap().mappings()); cvk::GraphicsPipeline const pipeline{core, std::move(pipelineConfig), cvk::create}; - timgui::Imgui imgui{ - core, - window, - {.colorFormat = SURFACE_FORMAT.format, .depthFormat = DEPTH_FORMAT, .samples = MSAA_SAMPLES} - }; + timgui::Imgui imgui{core, window, {.colorFormat = SURFACE_FORMAT.format}}; std::optional targetsOpt{}; jvk::Surface surface{ @@ -619,7 +671,24 @@ void run() { {.swapchain = {.formats = {SURFACE_FORMAT}}}, std::move(windowSurface), }; - jvk::StageGraph graph{core, {.stages = {{.queueIdx = QUEUE_IDX}}}}; + // the ui stage loads the image after the resolve of the scene stage + jvk::StageGraph graph{ + core, + { + .stages = { + {.queueIdx = QUEUE_IDX}, + { + .queueIdx = QUEUE_IDX, + .waits = { + { + .stageId = SCENE_STAGE_ID, + .stages = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, + } + }, + }, + }, + }, + }; core.executor().sync_wait( draw_frames(window, core, graph, surface, pipeline, cube, imgui, targetsOpt) From 2e671159dcfd02815e76de0b5b6e49a21426c334 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:15:33 +0100 Subject: [PATCH 59/68] jvk, demo: cth::co::all() with execution policies, the cube stages record at the same time - lib: cth on feat/all-policy, co::all() takes std::execution::seq or par, par by default - StageGraph::nextFrame(): both all() calls with seq, the children only wait - cube demo: the default par posts record_scene(), record_ui() runs inline --- demo/cube/src/main.cpp | 4 ++-- jvk/incl/jvk/graph/stage_graph.hpp | 2 +- jvk/src/graph/stage_graph.cpp | 5 ++++- lib/cth | 2 +- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/demo/cube/src/main.cpp b/demo/cube/src/main.cpp index 8215b37c..4a1629c4 100644 --- a/demo/cube/src/main.cpp +++ b/demo/cube/src/main.cpp @@ -520,8 +520,8 @@ cth::co::executor_task record_ui( * draws the spinning cube and the frame time window in every frame until the window closes * @details * - the scene stage records the cube, the ui stage records ImGui over it and presents the image - * - the two stages record in two tasks of one `cth::co::all()`, see `record_scene()`, - * `record_ui()` + * - the two stages record at the same time: two tasks of one `cth::co::all()` with its default + * `std::execution::par`, see `record_scene()`, `record_ui()` * - the ImGui frame comes first: it takes the events also in a frame without an image * - no image: both stages skip * - frame time: the time between the starts of two iterations, the first iteration has none diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index 335e2ae5..60d992b9 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -82,7 +82,7 @@ class StageGraph { * constructs the frame and its stages in the next slot * @details the old frame of the slot: awaits `StageSlot::submitDone` of its stages: their * submissions ended the submits and the presents, then the stages: the gpu finished them, both - * with `cth::co::all()` + * with `cth::co::all()` and `std::execution::seq` * @return the frame of the slot * @pre every stage of the frame before is submitted or skipped: `Stage::submit()`, * `Stage::skip()` or the end of its `scoped_submit` diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index ceb3ad9a..016c7080 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -180,7 +181,9 @@ cth::co::executor_task StageGraph::nextFrame() { if(frameSlot.frameOpt.has_value()) { // the submissions first: the gpu can finish before the submission marks the submit, the // submission uses the slot until it ended its presents + // seq: the children only wait, a post buys nothing co_await cth::co::all( + std::execution::seq, frameSlot.stages | std::views::transform( [](Stage const& stage) { @@ -188,7 +191,7 @@ cth::co::executor_task StageGraph::nextFrame() { } ) ); - co_await cth::co::all(frameSlot.stages); + co_await cth::co::all(std::execution::seq, frameSlot.stages); } frameSlot.frameOpt.reset(); diff --git a/lib/cth b/lib/cth index 03336d0d..91dff820 160000 --- a/lib/cth +++ b/lib/cth @@ -1 +1 @@ -Subproject commit 03336d0d1f8cd916c5b33afc26e446ffe8d6720f +Subproject commit 91dff820f016f894445713f64ab03e307bf93d07 From abb80e7e3cc5713e6a659dc2982cf7f0cdd643b7 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:52:19 +0100 Subject: [PATCH 60/68] jvk: Queue::tryAcquire(), Surface::acquire() tries the acquire in the strand first - Queue::tryAcquire(): vkAcquireNextImageKHR with timeout 0 in the strand, serialized with the presents - Surface::acquire(): the try first, VK_NOT_READY, a new extent or out of date -> the fallback outside the strand - //TEMP the try runs only after the resolve of the last image: the present state holds one image - the Presenter replaces it in its step 2 --- jvk/incl/jvk/base/queue.hpp | 21 ++++++++- jvk/incl/jvk/graph/surface.hpp | 19 +++++--- jvk/src/base/queue.cpp | 9 ++++ jvk/src/graph/surface.cpp | 67 +++++++++++++++++++--------- jvk/tests/src/graph/surface_test.cpp | 43 ++++++++++++++++++ 5 files changed, 133 insertions(+), 26 deletions(-) diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index ce09bb93..b8909fa1 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -5,6 +5,7 @@ #include "cvk/base/queue/queue.hpp" #include "cvk/base/queue/submit_info.hpp" #include "cvk/render/sync/barrier.hpp" +#include "cvk/surface/swapchain.hpp" #include @@ -26,11 +27,11 @@ class scheduler; namespace cvk { class Semaphore; -class Swapchain; } namespace jvk { class Core; +class Swapchain; // in queue.hpp next to Queue: it is small, no own header /** @@ -150,6 +151,24 @@ class Queue { std::span results ); + /** + * tries to acquire the next image of the swapchain in the strand, without a wait + * @details `vkAcquireNextImageKHR()` with timeout `0`: never blocks the strand + * @details serialized with the presents of the queue: the external synchronization of the + * swapchain + * @details the retired swapchains: see `Swapchain::acquire()` + * @param swapchain to acquire from + * @param signal signaled when the image is ready + * @return `VK_NOT_READY` -> no image now, see `cvk::Swapchain::acquire()` + * @pre the preconditions of `Swapchain::acquire()` + * @pre the swapchains present through this queue + * @throws cvk::vk_result_exception other result of `vkAcquireNextImageKHR()` + */ + [[nodiscard]] cth::co::executor_task tryAcquire( + Swapchain& swapchain, + cvk::Semaphore const& signal + ); + // an executor_task: the receiving submission awaits it before its own submit, so the transfer // is submitted first and the counter only changes in the strand (returning at once needs a lock // around the value and the post) diff --git a/jvk/incl/jvk/graph/surface.hpp b/jvk/incl/jvk/graph/surface.hpp index 0e48bec6..65bd8f32 100644 --- a/jvk/incl/jvk/graph/surface.hpp +++ b/jvk/incl/jvk/graph/surface.hpp @@ -76,7 +76,8 @@ struct SurfaceConfig { * - owns the cvk surface and the swapchain * - recreates the swapchain in `acquire()`, a retired swapchain stays until its presents ended, see * `Swapchain` - * - acquires outside the strand of its queue on `Queue::scheduler()` + * - tries the acquire in the strand of its queue without a wait, else acquires outside the strand + * on `Queue::scheduler()`, see `acquire()` * - the present stage of an image presents it after its submit, see `acquire()` * - a failed present: the next `acquire()` rethrows its error * - one acquired image at a time: `acquire()` waits until the last image is presented or dropped @@ -168,10 +169,12 @@ class Surface { * @details the surface: * - waits until the last image is presented or dropped * - a dropped last image: waits until the gpu finished its stages, then unacquires it - * - an out of date acquire or present, or a changed `cvk::Surface::extent()` -> recreates the - * swapchain first, erases the old images in the graph, see `StageGraph::erase()`, - * `Swapchain::recreate()` - * - runs on `Queue::scheduler()`, outside the strand + * - the try: `vkAcquireNextImageKHR()` with timeout `0` in the strand of the queue, see + * `Queue::tryAcquire()` + * - no image from the try (`VK_NOT_READY`), out of date or a changed `cvk::Surface::extent()` + * -> the fallback: a blocking acquire on `Queue::scheduler()`, outside the strand + * - the fallback recreates an out of date swapchain or one with another extent first, erases + * the old images in the graph, see `StageGraph::erase()`, `Swapchain::recreate()` * @param acquireStage waits for the acquire, the first use of the image * @param presentStage presents the image after its submit * @param stages pipeline stages of the acquire stage that wait for the acquire @@ -222,6 +225,12 @@ class Surface { } private: + /** + * rethrows the error of the present of the last image, unacquires a dropped last image + * @details only after the resolve of the last image + */ + void handleLastPresent(); + /** * a recreation erases the old images in the graph first: the new images can reuse their handles * only when no present uses the swapchain diff --git a/jvk/src/base/queue.cpp b/jvk/src/base/queue.cpp index c0fbe6e0..6e1035a8 100644 --- a/jvk/src/base/queue.cpp +++ b/jvk/src/base/queue.cpp @@ -1,6 +1,7 @@ #include "jvk/base/queue.hpp" #include "jvk/base/core.hpp" +#include "jvk/graph/swapchain.hpp" #include "jvk/utility/exception.hpp" #include "cvk/surface/swapchain.hpp" @@ -75,6 +76,14 @@ cth::co::executor_task Queue::present( presentInStrand(images, results); } +cth::co::executor_task Queue::tryAcquire( + Swapchain& swapchain, + cvk::Semaphore const& signal +) { + co_await executor().schedule(); + co_return swapchain.acquire(signal, 0); +} + cth::co::executor_task Queue::transfer( cvk::Barrier barriers, span waits, diff --git a/jvk/src/graph/surface.cpp b/jvk/src/graph/surface.cpp index 3a10f96a..dc7fe4d3 100644 --- a/jvk/src/graph/surface.cpp +++ b/jvk/src/graph/surface.cpp @@ -108,34 +108,50 @@ cth::co::executor_task> Surface::acquire( "the acquire stage and the present stage must belong to one frame of one graph" ) {} - // the last image first: the acquire and the present share the swapchain (externally - // synchronized), a blocking acquire before that present would delay it (FIFO) - co_await _presentState.resolved.wait(_lastValue); - // written before the resolve: the error of the present of the last image - if(_presentState.error != nullptr) - std::rethrow_exception(std::exchange(_presentState.error, nullptr)); - // outside the strand: the resolve of the last image orders the swapchain uses - co_await cth::co::executor{_queue->scheduler()}.schedule(); - - // the drop resolved after the gpu finished the stages of the image: - // VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786 - if(std::exchange(_presentState.dropped, false)) - _swapchain.current().unacquire(std::array{_lastImageIdx}); - cvk::Core const& vkCore = *_core; std::optional imageIdxOpt = std::nullopt; auto const& acquireSemaphore = _acquireSemaphores[_acquireSemaphoreIdx]; - while(!imageIdxOpt.has_value()) { + //TEMP the try only after the resolve of the last image: the present state holds one image, a + // try while the last image presents needs the state of several images + if(_presentState.resolved.value() >= _lastValue) { + handleLastPresent(); + auto const extent = _surface.extent(vkCore.physicalDevice()); if(extent.width == 0 || extent.height == 0) co_return std::nullopt; - updateSwapchain(extent, &acquireStage.graph()); - // no image -> out of date, the next round recreates the swapchain - imageIdxOpt = _swapchain.acquire(acquireSemaphore).imageIndex; - if(!imageIdxOpt.has_value()) - _presentState.outOfDate = true; + // a recreation takes the fallback: in the strand it would hold up the submits + if(_swapchain.created() && !_presentState.outOfDate + && _swapchain.current().extent() == extent) { + auto const acquired = co_await _queue->tryAcquire(_swapchain, acquireSemaphore); + imageIdxOpt = acquired.imageIndex; + if(acquired.result == VK_ERROR_OUT_OF_DATE_KHR) + _presentState.outOfDate = true; + } + } + + // the fallback: no image from the try, a new extent or out of date + if(!imageIdxOpt.has_value()) { + // the last image first: then no present of the surface is pending, the blocking acquire + // and the recreation need no strand, a blocking acquire before that present would delay it + // (FIFO) + co_await _presentState.resolved.wait(_lastValue); + // outside the strand: the resolve of the last image orders the swapchain uses + co_await cth::co::executor{_queue->scheduler()}.schedule(); + handleLastPresent(); + + while(!imageIdxOpt.has_value()) { + auto const extent = _surface.extent(vkCore.physicalDevice()); + if(extent.width == 0 || extent.height == 0) + co_return std::nullopt; + updateSwapchain(extent, &acquireStage.graph()); + + // no image -> out of date, the next round recreates the swapchain + imageIdxOpt = _swapchain.acquire(acquireSemaphore).imageIndex; + if(!imageIdxOpt.has_value()) + _presentState.outOfDate = true; + } } auto const imageIdx = *imageIdxOpt; @@ -164,6 +180,17 @@ cth::co::executor_task> Surface::acquire( co_return image; } +void Surface::handleLastPresent() { + // written before the resolve: the error of the present of the last image + if(_presentState.error != nullptr) + std::rethrow_exception(std::exchange(_presentState.error, nullptr)); + + // the drop resolved after the gpu finished the stages of the image: + // VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786 + if(std::exchange(_presentState.dropped, false)) + _swapchain.current().unacquire(std::array{_lastImageIdx}); +} + void Surface::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { if(_swapchain.created() && !_presentState.outOfDate && _swapchain.current().extent() == extent) return; diff --git a/jvk/tests/src/graph/surface_test.cpp b/jvk/tests/src/graph/surface_test.cpp index cac0e8c5..9f9a8f36 100644 --- a/jvk/tests/src/graph/surface_test.cpp +++ b/jvk/tests/src/graph/surface_test.cpp @@ -7,6 +7,7 @@ #include "jvk/base/queue.hpp" #include "jvk/data/image.hpp" #include "jvk/graph/stage_graph.hpp" +#include "jvk/graph/swapchain.hpp" #include "jvk/sync/semaphore.hpp" #include "cvk/base/physical_device.hpp" @@ -932,6 +933,48 @@ JVK_TEST(Surface, two_surfaces_present_after_one_stage) { } } +JVK_TEST(Surface, try_acquire_in_the_strand_gives_images_until_not_ready) { + test::Context const context{}; + auto windowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, windowSurface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + cvk::Core const& vk = core; + + Swapchain swapchain{vk, queue.vk(), windowSurface}; + swapchain.create({}, test::HEADLESS_EXTENT); + auto const imageCount = swapchain.current().imageCount(); + + // one acquire semaphore per try, one more than the images: the last try finds no image + std::vector signals{}; + for(uint32_t i = 0; i <= imageCount; ++i) + signals.emplace_back(vk, cvk::create); + std::vector acquired{}; + VkResult last = VK_SUCCESS; + for(auto const& signal : signals) { + auto const result = core.executor().sync_wait(queue.tryAcquire(swapchain, signal)); + if(!result.imageIndex.has_value()) { + last = result.result; + break; + } + acquired.push_back(*result.imageIndex); + } + EXPECT_FALSE(acquired.empty()); + EXPECT_LE(acquired.size(), imageCount); + EXPECT_EQ(last, VK_NOT_READY); + + // the acquire semaphores signal: a submit waits for them before the unacquire and their + // destruction + SubmitInfo info{}; + for(size_t i = 0; i < acquired.size(); ++i) + info.binaryWaits.emplace_back(signals[i]); + core.executor().sync_wait(queue.submit(info)); + queue.waitIdle(); + swapchain.current().unacquire(acquired); +} + JVK_TEST(Surface, present_queue_of_the_same_family) { constexpr size_t FRAMES = 4; test::Context const context{}; From 66f8615de72187d0811c24425ef08f163d509582 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:52:19 +0100 Subject: [PATCH 61/68] jvk: Presenter, the images of one swapchain behind acquire, present and drop - acquire(): a spare first, else the try in the strand, else the fallback on a driver thread - the fallback blocks only within imageCount - minImageCount acquired images (VUID-01802) - present(): in acquire order, never throws, the next acquire() rethrows the first failure - drop(), drop(ready): instant, the image becomes a spare - Image: move-only, its destructor drops it - the destructor releases the spares, finished() tells when that is allowed - cvk::Swapchain::surface() - not used yet: jvk::Swapchain, Surface and StageGraph switch over in step 2 --- cvk/incl/cvk/surface/swapchain.hpp | 1 + jvk/incl/jvk/graph/presenter.hpp | 402 ++++++++++++++ jvk/src/graph/presenter.cpp | 415 +++++++++++++++ jvk/tests/src/graph/presenter_test.cpp | 690 +++++++++++++++++++++++++ 4 files changed, 1508 insertions(+) create mode 100644 jvk/incl/jvk/graph/presenter.hpp create mode 100644 jvk/src/graph/presenter.cpp create mode 100644 jvk/tests/src/graph/presenter_test.cpp diff --git a/cvk/incl/cvk/surface/swapchain.hpp b/cvk/incl/cvk/surface/swapchain.hpp index 5c6e764c..2e63f801 100644 --- a/cvk/incl/cvk/surface/swapchain.hpp +++ b/cvk/incl/cvk/surface/swapchain.hpp @@ -235,6 +235,7 @@ class Swapchain { [[nodiscard]] constexpr VkSwapchainKHR get() const { return _handle.get(); } [[nodiscard]] constexpr Core const& core() const { return _handle.core(); } [[nodiscard]] constexpr Config const& config() const { return _config; } + [[nodiscard]] constexpr Surface const& surface() const { return *_surface; } [[nodiscard]] constexpr VkExtent2D extent() const { return _extent; } [[nodiscard]] constexpr VkFormat format() const { return _surfaceFormat.format; } diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/presenter.hpp new file mode 100644 index 00000000..b0f1c5f8 --- /dev/null +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -0,0 +1,402 @@ +#pragma once +#include "jvk/sync/semaphore.hpp" + +#include "cvk/render/sync/semaphore.hpp" +#include "cvk/surface/swapchain.hpp" + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace cvk { +class Image; +class ImageView; +} + +namespace jvk { +class Queue; + +/** + * orchestrates the images of one swapchain + * @details + * - `acquire()` hands out an `Image`, `present()` or `drop()` hands it back + * - the presents follow the acquire order + * - a dropped image is a spare: the next `acquire()` hands it out first + * - owns `framesInFlight()` acquire semaphores + * - thread safe: `acquire()`, `present()` and `drop()` from any thread + * - the strand of the queue runs the vulkan calls of the swapchain, except the fallback of + * `acquire()`: it excludes the presents and the tries of the presenter + * - the destructor releases the spares, see `cvk::Swapchain::unacquire()` + */ +class Presenter { +public: + class Image; + + /** + * wait of the first use of an image: its acquire semaphore or the ready point of a drop + */ + using wait_t = std::variant, SemaphoreSubmitInfo>; + + // no base constructor and create(): the presenter has no wrap or release + /** + * creates the acquire semaphores + * @param presentQueue presents the images, its strand runs the tries and the presents + * @param swapchain of the images + * @param framesInFlight count of the acquire semaphores + * @details reads `minImageCount` of the surface for the fallback of `acquire()` + * @pre `cvk::Swapchain::created()` + * @pre `swapchain` presents through `presentQueue` + * @pre `framesInFlight > 0` + * @throws cvk::vk_result_exception result of `vkCreateSemaphore()` or + * `vkGetPhysicalDeviceSurfaceCapabilitiesKHR()` + */ + Presenter(Queue& presentQueue, cvk::Swapchain& swapchain, uint32_t framesInFlight); + + /** + * releases the spares, destroys the acquire semaphores + * @details a failed release does not stop the destruction + * @pre every `Image` of the presenter is handed back + * @pre no `acquire()` and no `present()` is pending + * @pre the ready points of the spares are reached: + * VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786 + * @pre the submits that wait for the acquire semaphores completed: + * VUID-vkDestroySemaphore-semaphore-05149 + * @see `finished()` + */ + ~Presenter(); + + /** + * hands out the next image of the swapchain + * @details the image: + * - a spare first + * - else the try: `vkAcquireNextImageKHR()` with timeout `0` in the strand of the queue + * - the try returns `VK_NOT_READY` -> the fallback: waits until no present of the presenter + * is pending, then `vkAcquireNextImageKHR()` on a driver thread + * - the fallback blocks only with at most `imageCount - minImageCount` of the surface acquired + * images, else it waits for the present fences, then tries: + * VUID-vkAcquireNextImageKHR-swapchain-01802 + * - `VK_SUBOPTIMAL_KHR` counts as success + * @details waits for a hand back: + * - every acquire semaphore is with an image that is not presented or dropped + * - the try of the fallback returns `VK_NOT_READY` + * @details no free acquire semaphore: + * - a presented image -> the fallback waits for its present fence + * - else waits for the ready point of a drop, see `Semaphore::wait()` + * @return the image, `std::nullopt` -> out of date: the acquire or a present returned + * `VK_ERROR_OUT_OF_DATE_KHR`, every later acquire returns `std::nullopt` + * @pre the swapchain is not retired: VUID-vkAcquireNextImageKHR-swapchain-01285 + * @throws std::exception the first failure of a present before, once + * @throws cvk::vk_result_exception other result of `vkAcquireNextImageKHR()` + * @throws cvk::vk_result_exception result of `vkGetFenceStatus()`, `vkWaitForFences()` or + * `vkGetSemaphoreCounterValue()` + * @throws cth::except::coro_exception reason: the wait for a ready point failed + * @attention a hand back that never comes -> waits forever, e.g. the caller holds + * `framesInFlight()` images + */ + [[nodiscard]] cth::co::executor_task> acquire(); + + /** + * hands the image back for its present + * @details + * - waits until every image acquired before is handed back: the presents follow the acquire + * order + * - waits for the end of a fallback of `acquire()` + * - one `vkQueuePresentKHR()` in the strand of the queue, see `Queue::present()` + * - ends after `vkQueuePresentKHR()` + * - never throws: the next `acquire()` rethrows the first failure, + * `VK_ERROR_OUT_OF_DATE_KHR` -> it returns `std::nullopt` + * @pre the image is of this presenter + * @pre the image is in `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` + * @pre a submitted batch signals `Image::presentSemaphore()`, after the uses of the image and + * after the wait for `Image::wait()` + */ + [[nodiscard]] cth::co::executor_task present(Image image); + + /** + * hands the image back without a present: the image becomes a spare + * @details the spare keeps `Image::wait()` + * @pre the image is of this presenter + * @pre no submitted batch uses the image or waits for `Image::wait()` + */ + void drop(Image image); + + /** + * hands the image back without a present: the image becomes a spare that waits for the ready + * point + * @details the acquire semaphore of the image is free once the ready point is reached + * @param image to drop + * @param ready reached after the uses of the image and after the wait for `Image::wait()` + * @pre the image is of this presenter + */ + void drop(Image image, SemaphoreSubmitInfo ready); + + /** + * checks without a wait that the presenter has no work left + * @return every `Image` is handed back, no present is pending, every ready point is reached, + * every present fence of the swapchain is signaled + * @pre no `acquire()` runs at the same time: a present of its image resets a present fence + * @throws cvk::vk_result_exception result of `vkGetSemaphoreCounterValue()` or + * `vkGetFenceStatus()` + */ + [[nodiscard]] bool finished() const; + + [[nodiscard]] constexpr Queue& queue() const { return *_queue; } + [[nodiscard]] constexpr cvk::Swapchain& swapchain() const { return *_swapchain; } + [[nodiscard]] constexpr uint32_t framesInFlight() const { + return static_cast(_acquireSemaphores.size()); + } + +private: + struct Free {}; + + /** with an image of a caller or a spare */ + struct Held {}; + + /** free once the present fence of the image signals */ + struct Presented { + uint32_t imageIdx; + }; + + /** + * state of an acquire semaphore, a `SemaphoreSubmitInfo`: free once the ready point of the + * drop is reached + */ + using reuse_t = std::variant; + + struct Spare { + uint32_t imageIdx; + wait_t wait; + }; + + /** the state changed during the try, `acquire()` checks it again */ + struct Retry {}; + + struct Fallback { + /** `std::nullopt` -> the fallback waits for a present fence */ + std::optional semaphoreIdxOpt; + /** count of the started presents at the start, the fallback waits for their end */ + uint64_t presents; + }; + + /** result of a try: the image, a retry, the ready point to wait for or the fallback */ + using try_t = std::variant; + + /** + * the semaphore choice and the try in the strand + * @details `VK_NOT_READY` or only present fences to wait for -> starts the fallback + */ + [[nodiscard]] cth::co::executor_task tryInStrand(); + + /** + * @return the image, `std::nullopt` -> retry + */ + [[nodiscard]] cth::co::executor_task> fallback(Fallback); + + /** + * frees the acquire semaphores whose ready point or present fence is reached + * @return a free acquire semaphore, `std::nullopt` -> none + * @pre in the strand or in the fallback: the presents reset the present fences + */ + [[nodiscard]] std::optional recycle(); + + /** + * blocks until the present fence of a presented image signals + * @return the free acquire semaphore + * @pre in the fallback, an acquire semaphore is `Presented` + */ + [[nodiscard]] size_t awaitPresentFence(); + + [[nodiscard]] bool reached(reuse_t const&) const; + + /** + * @return the failure of a present, `nullptr` -> none, the presenter forgets it + */ + [[nodiscard]] std::exception_ptr takeError(); + + /** + * hands the image back as a spare + * @param readyOpt `std::nullopt` -> the spare keeps the wait + */ + void spare( + uint32_t imageIdx, + uint64_t acquireNumber, + wait_t const& wait, + std::optional const& readyOpt + ); + + // the helpers below lock nothing, the caller holds _mutex + [[nodiscard]] Image handOut(uint32_t imageIdx, wait_t wait); + [[nodiscard]] Fallback startFallback(std::optional semaphoreIdxOpt); + void endFallback(); + /** advances `_handedBack` over the hand backs in acquire order */ + void handBack(uint64_t acquireNumber); + + [[nodiscard]] size_t semaphoreIdx(cvk::Semaphore const& semaphore) const { + return static_cast(&semaphore - _acquireSemaphores.data()); + } + + cth::ref_wrapper _queue; + cth::ref_wrapper _swapchain; + + /** `imageCount - minImageCount` of the surface: more acquired images -> no blocking acquire */ + uint32_t _blockingAcquireLimit; + std::vector _acquireSemaphores{}; + + mutable std::mutex _mutex{}; + + // behind _mutex + std::vector _reuses; ///< one per acquire semaphore + std::vector _spares{}; + /** acquire number of the last handed out image, the numbers start at `1` */ + uint64_t _acquires = 0; + /** handed back while an image acquired before is not */ + cth::dt::flat_hash_set _handedBackAhead{}; + /** acquired from the swapchain, not presented or released: the images of callers and spares */ + uint32_t _acquiredImages = 0; + uint64_t _presentsStarted = 0; + uint64_t _fallbacks = 0; ///< count of the started fallbacks + bool _fallback = false; ///< a fallback runs + bool _outOfDate = false; + std::exception_ptr _error = nullptr; ///< first failure of a present + + // set behind _mutex + /** every image up to the acquire number is handed back, a present after its end */ + cth::co::counter_event _handedBack{}; + cth::co::counter_event _handBacks{}; ///< count of the hand backs + cth::co::counter_event _presentsDone{}; ///< count of the ended presents + cth::co::counter_event _fallbacksDone{}; ///< count of the ended fallbacks + +public: + Presenter(Presenter const& other) = delete; + Presenter(Presenter&& other) = delete; + Presenter& operator=(Presenter const& other) = delete; + Presenter& operator=(Presenter&& other) = delete; +}; +} + +namespace jvk { +/** + * image of a `Presenter`, handed back exactly once + * @details + * - `Presenter::present()` or `Presenter::drop()` hands it back, the destruction drops it + * - the content is undefined: the first use transitions it from `VK_IMAGE_LAYOUT_UNDEFINED` + * - the first use waits for `wait()` + * - a moved-from image hands back nothing + */ +class Presenter::Image { +public: + /** + * constructs the image of an acquire, `Presenter::acquire()` constructs it + * @param presenter of the image + * @param imageIdx index of the image in the swapchain + * @param acquireNumber order of the acquire, the presents follow it + * @param wait of the first use + */ + Image(Presenter& presenter, uint32_t imageIdx, uint64_t acquireNumber, wait_t wait) : + _presenter{ + &presenter, + dropper{.imageIdx = imageIdx, .acquireNumber = acquireNumber, .wait = std::move(wait)} + } {} + + /** + * @return the presenter of the image + * @pre not handed back + */ + [[nodiscard]] Presenter& presenter() const { + debug_check(*this); + return *_presenter; + } + + /** + * @return the image in the swapchain + * @pre not handed back + */ + [[nodiscard]] cvk::Image const& image() const { + return presenter().swapchain().image(imageIdx()); + } + + /** + * @pre not handed back + */ + [[nodiscard]] cvk::ImageView const& view() const { + return presenter().swapchain().view(imageIdx()); + } + + /** + * @pre not handed back + */ + [[nodiscard]] VkExtent2D extent() const { return presenter().swapchain().extent(); } + + /** + * @return the semaphore that the present waits for, a submit signals it + * @pre not handed back + */ + [[nodiscard]] cvk::Semaphore const& presentSemaphore() const { + return presenter().swapchain().presentSemaphore(imageIdx()); + } + + /** + * @return wait of the first use, the ready point keeps the stages of its drop + */ + [[nodiscard]] wait_t const& wait() const { return _presenter.get_deleter().wait; } + + /** + * @return index of the image in the swapchain + */ + [[nodiscard]] uint32_t imageIdx() const { return _presenter.get_deleter().imageIdx; } + + /** + * @return order of the acquire, the numbers start at `1` + */ + [[nodiscard]] uint64_t acquireNumber() const { return _presenter.get_deleter().acquireNumber; } + +private: + // the presenter takes the hand back in present() and drop(): a public way to take it would let + // a caller skip the hand back + friend class Presenter; + + /** + * deleter of the image: drops it without a ready point + */ + struct dropper { + uint32_t imageIdx; + uint64_t acquireNumber; + wait_t wait; + + void operator()(Presenter* presenter) const { + presenter->spare(imageIdx, acquireNumber, wait, std::nullopt); + } + }; + + std::unique_ptr _presenter; ///< `nullptr` -> handed back or moved from + +public: + Image(Image const& other) = delete; + Image(Image&& other) noexcept = default; + Image& operator=(Image const& other) = delete; + Image& operator=(Image&& other) noexcept = default; + + static void debug_check(Image const&); +}; +} + +namespace jvk { +inline void Presenter::Image::debug_check(Image const& image) { + CTH_CRITICAL(image._presenter == nullptr, "the image must not be handed back") {} +} +} diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp new file mode 100644 index 00000000..619418d5 --- /dev/null +++ b/jvk/src/graph/presenter.cpp @@ -0,0 +1,415 @@ +#include "jvk/graph/presenter.hpp" + +#include "jvk/base/queue.hpp" +#include "jvk/utility/exception.hpp" + +#include "cvk/base/core.hpp" +#include "cvk/surface/surface.hpp" +#include "cvk/utility/vk_exceptions.hpp" + +#include +#include + +#include +#include +#include +#include + + +namespace jvk { +namespace { + /** + * @return count of the acquired images that allow a blocking acquire: + * VUID-vkAcquireNextImageKHR-swapchain-01802 + */ + [[nodiscard]] uint32_t blocking_acquire_limit(cvk::Swapchain const& swapchain) { + cvk::Swapchain::debug_check(swapchain); + auto const capabilities = swapchain.surface().capabilities( + swapchain.core().physicalDevice() + ); + auto const imageCount = swapchain.imageCount(); + return imageCount - std::min(capabilities.minImageCount, imageCount); + } + + template + [[nodiscard]] constexpr bool holds(auto const& variant) { + return std::holds_alternative(variant); + } +} + +Presenter::Presenter(Queue& presentQueue, cvk::Swapchain& swapchain, uint32_t framesInFlight) : + _queue{presentQueue}, + _swapchain{swapchain}, + _blockingAcquireLimit{blocking_acquire_limit(swapchain)}, + _reuses(framesInFlight, Free{}) { + CTH_CRITICAL(framesInFlight == 0, "framesInFlight must be > 0") {} + + _acquireSemaphores.reserve(framesInFlight); + for(uint32_t i = 0; i < framesInFlight; ++i) + _acquireSemaphores.emplace_back(swapchain.core(), cvk::create); +} + +Presenter::~Presenter() { + CTH_CRITICAL( + _handedBack.value() != _acquires, + "every image must be handed back after its present, {} of {} are", + _handedBack.value(), + _acquires + ) {} + + auto const imageIndices = _spares | std::views::transform(&Spare::imageIdx) + | std::ranges::to(); + // a failed release does not stop the destruction + try { _swapchain->unacquire(imageIndices); } + catch(cvk::vk_result_exception const& e) { + JVK_STABLE_ERR(true, "failed to release the spares, got {}", e.vkResult()) {} + } +} + +cth::co::executor_task> Presenter::acquire() { + if(auto const error = takeError(); error != nullptr) + std::rethrow_exception(error); + + for(;;) { + // 0 -> no wait + uint64_t fallbackValue = 0; + uint64_t handBackValue = 0; + { + std::scoped_lock const lock{_mutex}; + if(_outOfDate) + co_return std::nullopt; + if(!_spares.empty()) { + auto const spare = std::move(_spares.back()); + _spares.pop_back(); + co_return handOut(spare.imageIdx, spare.wait); + } + + if(_fallback) + fallbackValue = _fallbacks; + else if(std::ranges::all_of(_reuses, holds)) + handBackValue = _handBacks.value() + 1; + } + + if(fallbackValue != 0) { + co_await _fallbacksDone.wait(fallbackValue); + continue; + } + if(handBackValue != 0) { + co_await _handBacks.wait(handBackValue); + continue; + } + + auto tried = co_await tryInStrand(); + if(auto* const imagePtr = std::get_if(&tried)) + co_return std::move(*imagePtr); + + if(auto const* const readyPtr = std::get_if(&tried)) + co_await readyPtr->semaphore->wait(readyPtr->value); + else if(auto const* const fallbackPtr = std::get_if(&tried)) { + auto imageOpt = co_await fallback(*fallbackPtr); + if(imageOpt.has_value()) + co_return std::move(imageOpt); + } + } +} + +cth::co::executor_task Presenter::present(Image image) { + CTH_CRITICAL(image._presenter.get() != this, "the image must be of this presenter") {} + auto const [imageIdx, acquireNumber, wait] = image._presenter.get_deleter(); + // the present hands the image back + static_cast(image._presenter.release()); + + // the images acquired before first: the presents follow the acquire order + co_await _handedBack.wait(acquireNumber - 1); + + for(;;) { + uint64_t fallbackValue = 0; + { + std::scoped_lock const lock{_mutex}; + if(_fallback) + fallbackValue = _fallbacks; + else + ++_presentsStarted; + } + if(fallbackValue == 0) + break; + co_await _fallbacksDone.wait(fallbackValue); + } + + std::array const images{PresentImage{.swapchain = *_swapchain, .imageIdx = imageIdx}}; + std::array results{VK_ERROR_UNKNOWN}; + std::exception_ptr error = nullptr; + try { co_await _queue->present(images, results); } + catch(...) { error = std::current_exception(); } + + std::scoped_lock const lock{_mutex}; + // also a failed present ends the acquire, see cvk::Swapchain::preparePresent() + --_acquiredImages; + if(auto const* const semaphorePtr = std::get_if>(&wait)) + _reuses[semaphoreIdx(**semaphorePtr)] = Presented{imageIdx}; + + if(error != nullptr) { + if(_error == nullptr) + _error = error; + } else if(results[0] == VK_ERROR_OUT_OF_DATE_KHR) + _outOfDate = true; + + handBack(acquireNumber); + _presentsDone.set(_presentsDone.value() + 1); +} + +void Presenter::drop(Image image) { + CTH_CRITICAL(image._presenter.get() != this, "the image must be of this presenter") {} + // the dropper spares the image + image._presenter.reset(); +} + +void Presenter::drop(Image image, SemaphoreSubmitInfo ready) { + CTH_CRITICAL(image._presenter.get() != this, "the image must be of this presenter") {} + auto const [imageIdx, acquireNumber, wait] = image._presenter.get_deleter(); + static_cast(image._presenter.release()); + + spare(imageIdx, acquireNumber, wait, ready); +} + +bool Presenter::finished() const { + std::vector readyPoints{}; + { + std::scoped_lock const lock{_mutex}; + // a present hands back after vkQueuePresentKHR() + if(_handedBack.value() != _acquires) + return false; + + for(auto const& reuse : _reuses) + if(auto const* const readyPtr = std::get_if(&reuse)) + readyPoints.push_back(*readyPtr); + for(auto const& spare : _spares) + if(auto const* const readyPtr = std::get_if(&spare.wait)) + readyPoints.push_back(*readyPtr); + } + + // no vulkan call behind the mutex + return std::ranges::all_of( + readyPoints, + [](SemaphoreSubmitInfo const& ready) { + return ready.semaphore->gpuValue() >= ready.value; + } + ) + && _swapchain->presented(); +} + +cth::co::executor_task Presenter::tryInStrand() { + // the strand serializes the tries and the presents of the presenter, a try starts the fallback + co_await _queue->executor().schedule(); + + { + std::scoped_lock const lock{_mutex}; + // changed since the check before the strand + if(_fallback || _outOfDate || !_spares.empty()) + co_return Retry{}; + } + + auto const semaphoreIdxOpt = recycle(); + if(!semaphoreIdxOpt.has_value()) { + std::scoped_lock const lock{_mutex}; + // a present fence signals soon after the gpu work, a ready point can be far + if(std::ranges::any_of(_reuses, holds)) + co_return startFallback(std::nullopt); + + auto const readyIt = std::ranges::find_if(_reuses, holds); + if(readyIt != _reuses.end()) + co_return std::get(*readyIt); + // every semaphore is held again + co_return Retry{}; + } + + // without the lock: the strand serializes the swapchain, only the tries and the fallback take + // a free semaphore + auto const& semaphore = _acquireSemaphores[*semaphoreIdxOpt]; + auto const acquired = _swapchain->acquire(semaphore, 0); + + std::scoped_lock const lock{_mutex}; + if(acquired.imageIndex.has_value()) { + _reuses[*semaphoreIdxOpt] = Held{}; + ++_acquiredImages; + co_return handOut(*acquired.imageIndex, cth::ref_wrapper{semaphore}); + } + if(acquired.result == VK_ERROR_OUT_OF_DATE_KHR) { + _outOfDate = true; + co_return Retry{}; + } + + // VK_NOT_READY + co_return startFallback(semaphoreIdxOpt); +} + +cth::co::executor_task> Presenter::fallback(Fallback start) { + // no present of the presenter is pending: the blocking acquire waits for no present that the + // fallback holds back + co_await _presentsDone.wait(start.presents); + // a driver thread: the blocking calls stay out of the strand + co_await cth::co::executor{_queue->scheduler()}.schedule(); + + auto semaphoreIdxOpt = start.semaphoreIdxOpt; + // std::nullopt -> a spare, the retry takes it + std::optional acquiredOpt = std::nullopt; + std::exception_ptr error = nullptr; + try { + if(!semaphoreIdxOpt.has_value()) + semaphoreIdxOpt = awaitPresentFence(); + + bool spare = false; + bool blocking = false; + { + std::scoped_lock const lock{_mutex}; + spare = !_spares.empty(); + // more acquired images: the presentation engine may never give one, only the try: + // VUID-vkAcquireNextImageKHR-swapchain-01802 + blocking = _acquiredImages <= _blockingAcquireLimit; + } + + if(!spare && blocking) + acquiredOpt = _swapchain->acquire(_acquireSemaphores[*semaphoreIdxOpt]); + else if(!spare) { + // the presents before reach the presentation engine first, it can give their images + // back: no present resets a fence during the fallback + for(uint32_t imageIdx = 0; imageIdx < _swapchain->imageCount(); ++imageIdx) + _swapchain->presentFence(imageIdx).wait(); + acquiredOpt = _swapchain->acquire(_acquireSemaphores[*semaphoreIdxOpt], 0); + } + } + catch(...) { error = std::current_exception(); } + + uint64_t handBackValue = 0; + { + std::scoped_lock const lock{_mutex}; + endFallback(); + if(error != nullptr) + std::rethrow_exception(error); + + if(acquiredOpt.has_value() && acquiredOpt->imageIndex.has_value()) { + _reuses[*semaphoreIdxOpt] = Held{}; + ++_acquiredImages; + co_return handOut( + *acquiredOpt->imageIndex, + cth::ref_wrapper{_acquireSemaphores[*semaphoreIdxOpt]} + ); + } + + if(acquiredOpt.has_value() && acquiredOpt->result == VK_ERROR_OUT_OF_DATE_KHR) + _outOfDate = true; + // VK_NOT_READY of the try: only a hand back gives an image, a spare comes at once + else if(acquiredOpt.has_value() && _spares.empty()) + handBackValue = _handBacks.value() + 1; + } + if(handBackValue != 0) + co_await _handBacks.wait(handBackValue); + co_return std::nullopt; +} + +std::optional Presenter::recycle() { + std::vector reuses{}; + { + std::scoped_lock const lock{_mutex}; + auto const freeIt = std::ranges::find_if(_reuses, holds); + if(freeIt != _reuses.end()) + return static_cast(freeIt - _reuses.begin()); + reuses = _reuses; + } + + // no vulkan call behind the mutex, only the recycle frees a presented or dropped semaphore + std::optional semaphoreIdxOpt = std::nullopt; + for(size_t i = 0; i < reuses.size(); ++i) + if(reached(reuses[i])) { + reuses[i] = Free{}; + semaphoreIdxOpt = semaphoreIdxOpt.value_or(i); + } + if(!semaphoreIdxOpt.has_value()) + return std::nullopt; + + std::scoped_lock const lock{_mutex}; + for(size_t i = 0; i < reuses.size(); ++i) + if(holds(reuses[i])) + _reuses[i] = Free{}; + return semaphoreIdxOpt; +} + +size_t Presenter::awaitPresentFence() { + for(;;) { + if(auto const semaphoreIdxOpt = recycle(); semaphoreIdxOpt.has_value()) + return *semaphoreIdxOpt; + + uint32_t imageIdx = 0; + { + std::scoped_lock const lock{_mutex}; + auto const presentedIt = std::ranges::find_if(_reuses, holds); + CTH_CRITICAL( + presentedIt == _reuses.end(), + "an acquire semaphore must wait for a present fence" + ) {} + imageIdx = std::get(*presentedIt).imageIdx; + } + // the fallback holds the presents back: no reset of the fence during the wait + _swapchain->presentFence(imageIdx).wait(); + } +} + +std::exception_ptr Presenter::takeError() { + std::scoped_lock const lock{_mutex}; + return std::exchange(_error, nullptr); +} + +bool Presenter::reached(reuse_t const& reuse) const { + if(auto const* const presentedPtr = std::get_if(&reuse)) + return _swapchain->presentFence(presentedPtr->imageIdx).signaled(); + if(auto const* const readyPtr = std::get_if(&reuse)) + return readyPtr->semaphore->gpuValue() >= readyPtr->value; + return false; +} + +auto Presenter::handOut(uint32_t imageIdx, wait_t wait) -> Image { + return Image{*this, imageIdx, ++_acquires, std::move(wait)}; +} + +auto Presenter::startFallback(std::optional semaphoreIdxOpt) -> Fallback { + _fallback = true; + ++_fallbacks; + return Fallback{.semaphoreIdxOpt = semaphoreIdxOpt, .presents = _presentsStarted}; +} + +void Presenter::endFallback() { + _fallback = false; + _fallbacksDone.set(_fallbacks); +} + +void Presenter::handBack(uint64_t acquireNumber) { + _handedBackAhead.insert(acquireNumber); + auto handedBack = _handedBack.value(); + while(_handedBackAhead.erase(handedBack + 1) != 0) + ++handedBack; + if(handedBack != _handedBack.value()) + _handedBack.set(handedBack); + + _handBacks.set(_handBacks.value() + 1); +} + +void Presenter::spare( + uint32_t imageIdx, + uint64_t acquireNumber, + wait_t const& wait, + std::optional const& readyOpt +) { + using semaphore_ref_t = cth::ref_wrapper; + + std::scoped_lock const lock{_mutex}; + // the ready point frees the acquire semaphore once reached, the spare waits for it instead + if(readyOpt.has_value()) + if(auto const* const semaphorePtr = std::get_if(&wait)) + _reuses[semaphoreIdx(**semaphorePtr)] = *readyOpt; + + _spares.push_back( + Spare{.imageIdx = imageIdx, .wait = readyOpt.has_value() ? wait_t{*readyOpt} : wait} + ); + handBack(acquireNumber); +} +} diff --git a/jvk/tests/src/graph/presenter_test.cpp b/jvk/tests/src/graph/presenter_test.cpp new file mode 100644 index 00000000..98ab643c --- /dev/null +++ b/jvk/tests/src/graph/presenter_test.cpp @@ -0,0 +1,690 @@ +#include "jvk/graph/presenter.hpp" + +#include "context.hpp" +#include "test.hpp" + +#include "jvk/base/core.hpp" +#include "jvk/base/queue.hpp" +#include "jvk/cmd/cmd_buffer.hpp" +#include "jvk/sync/semaphore.hpp" + +#include "cvk/render/sync/barrier.hpp" +#include "cvk/render/sync/semaphore.hpp" +#include "cvk/surface/swapchain.hpp" +#include "cvk/utility/vk_exceptions.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace jvk { +namespace { + using enum cvk::QueueFamilyProperties; + + constexpr auto TIMEOUT = std::chrono::seconds{5}; + /** a wait that ends in this time counts as not pending */ + constexpr auto PENDING = std::chrono::milliseconds{50}; + + /** + * @param[out] coreOpt gets a core with a queue that presents to the surface + * @return `false` -> no device presents to a headless surface + */ + [[nodiscard]] bool create_present_core( + std::optional& coreOpt, + test::Context const& context, + cvk::Surface const& surface + ) { + auto config = test::Context::CONFIG; + config.vk.queueProperties = {GRAPHICS | PRESENT}; + try { + coreOpt.emplace( + context.instance, + std::move(config), + std::array{cth::ref_wrapper{surface}} + ); + } + catch(cvk::cvk_exception const&) { return false; } + return true; + } + + /** + * signals the semaphore from the host, without a mark + */ + void host_signal(Semaphore const& semaphore, uint64_t value) { + cvk::Core const& vk = semaphore.core(); + VkSemaphoreSignalInfo const info{ + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO, + .pNext = nullptr, + .semaphore = semaphore.get(), + .value = value, + }; + ASSERT_EQ(vk.functions()->vkSignalSemaphore(vk.vkDevice(), &info), VK_SUCCESS); + } + + /** + * @return the acquire semaphore of the wait of the image, `nullptr` -> a ready point + */ + [[nodiscard]] cvk::Semaphore const* acquire_semaphore(Presenter::Image const& image) { + auto const* const semaphorePtr = + std::get_if>(&image.wait()); + return semaphorePtr != nullptr ? &semaphorePtr->get() : nullptr; + } + + /** + * adds the wait of the image and the gate to the submit + * @param gatePtr `nullptr` -> no gate, else the submit waits for its value `1` + */ + void add_waits(SubmitInfo& info, Presenter::Image const& image, Semaphore const* gatePtr) { + if(gatePtr != nullptr) + info.waits.push_back({.semaphore = *gatePtr, .value = 1}); + if(auto const* const semaphorePtr = acquire_semaphore(image)) + info.binaryWaits.emplace_back(*semaphorePtr); + else + info.waits.push_back(std::get(image.wait())); + } + + /** + * the submits of a test + * @details the destructor waits until the queue is idle: the command buffers and the + * semaphores go after the gpu + */ + struct Submits { + Submits(Core const& core, Queue& queue) : + core{core}, + queue{queue}, + done{core, cvk::create} {} + ~Submits() { queue->waitIdle(); } + + /** + * transitions the image to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` after its wait, signals its + * present semaphore + * @param gatePtr `nullptr` -> no gate, else the submit waits for its value `1` too + */ + void transition(Presenter::Image const& image, Semaphore const* gatePtr = nullptr) { + auto& cmd = cmds.emplace_back(*core, queue->vk().familyIndex(), cvk::create); + cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); + cvk::Barrier barrier{}; + barrier.add( + image.image(), + cvk::ImageBarrierInfo{ + .src = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, + .dst = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, + .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + } + ); + barrier.execute(cmd); + cmd.end(); + + SubmitInfo info{ + .cmdBuffers = {cmd}, + .signals = {{.semaphore = done, .value = done.next()}}, + .binarySignals = {image.presentSemaphore()}, + }; + add_waits(info, image, gatePtr); + core->executor().sync_wait(queue->submit(info)); + } + + /** + * waits for the image without a use + * @param gatePtr `nullptr` -> no gate, else the submit waits for its value `1` too + * @return the signal of the submit, the ready point of a drop + */ + [[nodiscard]] SemaphoreSubmitInfo ready( + Presenter::Image const& image, + Semaphore const* gatePtr = nullptr + ) { + SemaphoreSubmitInfo const signal{.semaphore = done, .value = done.next()}; + SubmitInfo info{.signals = {signal}}; + add_waits(info, image, gatePtr); + core->executor().sync_wait(queue->submit(info)); + return signal; + } + + /** + * transitions and presents the image + */ + void present(Presenter& presenter, Presenter::Image image) { + transition(image); + core->executor().sync_wait(presenter.present(std::move(image))); + } + + cth::ref_wrapper core; + cth::ref_wrapper queue; + Semaphore done; + std::deque cmds{}; + }; + + [[nodiscard]] std::optional acquire(Core const& core, Presenter& presenter) { + return core.executor().sync_wait(presenter.acquire()); + } + + /** the `vkQueuePresentKHR()` of the device table before the hook */ + PFN_vkQueuePresentKHR realQueuePresent = nullptr; + + /** the images of the presents through `recording_present()`, in present order */ + std::vector presentedIndices{}; + + VKAPI_ATTR VkResult VKAPI_CALL recording_present(VkQueue queue, VkPresentInfoKHR const* info) { + for(uint32_t i = 0; i < info->swapchainCount; ++i) + presentedIndices.push_back(info->pImageIndices[i]); + return realQueuePresent(queue, info); + } + + /** + * presents, then reports the result for every swapchain + */ + template + VKAPI_ATTR VkResult VKAPI_CALL failing_present(VkQueue queue, VkPresentInfoKHR const* info) { + if(auto const result = realQueuePresent(queue, info); result < 0) + return result; + if(info->pResults != nullptr) + for(uint32_t i = 0; i < info->swapchainCount; ++i) + info->pResults[i] = Result; + return Result; + } + + /** count of the calls of `out_of_date_acquire()` */ + std::atomic outOfDateAcquires = 0; + + VKAPI_ATTR VkResult VKAPI_CALL out_of_date_acquire( + VkDevice, + VkSwapchainKHR, + uint64_t, + VkSemaphore, + VkFence, + uint32_t* + ) { + ++outOfDateAcquires; + return VK_ERROR_OUT_OF_DATE_KHR; + } + + PFN_vkGetFenceStatus realGetFenceStatus = nullptr; + PFN_vkWaitForFences realWaitForFences = nullptr; + + /** `true` -> `held_fence_status()` reports every fence as unsignaled */ + std::atomic fencesHeld = false; + /** count of the calls of `releasing_fence_wait()` */ + std::atomic fenceWaits = 0; + + VKAPI_ATTR VkResult VKAPI_CALL held_fence_status(VkDevice device, VkFence fence) { + return fencesHeld ? VK_NOT_READY : realGetFenceStatus(device, fence); + } + + /** + * ends the hold of the fences, then waits + */ + VKAPI_ATTR VkResult VKAPI_CALL releasing_fence_wait( + VkDevice device, + uint32_t fenceCount, + VkFence const* fences, + VkBool32 waitAll, + uint64_t timeout + ) { + ++fenceWaits; + fencesHeld = false; + return realWaitForFences(device, fenceCount, fences, waitAll, timeout); + } + + /** + * the device table of the core, it reads the table at each call + */ + [[nodiscard]] VolkDeviceTable& device_table(Core const& core) { + return *const_cast(static_cast(core).functions()); + } + + /** + * replaces a function in the device table of the core until the destruction + */ + template + struct Hook { + Hook(Pfn& function, Pfn hook, Pfn& real) : function{function}, real{real} { + real = std::exchange(function, hook); + } + ~Hook() { function.get() = real.get(); } + + cth::ref_wrapper function; + cth::ref_wrapper real; + + Hook(Hook const& other) = delete; + Hook& operator=(Hook const& other) = delete; + }; + + /** + * replaces `vkQueuePresentKHR()` of the core until the destruction + */ + struct PresentHook : Hook { + PresentHook(Core const& core, PFN_vkQueuePresentKHR hook) : + Hook{device_table(core).vkQueuePresentKHR, hook, realQueuePresent} {} + }; +} + +JVK_TEST(Presenter, acquire_and_present_round_trips) { + constexpr size_t FRAMES = 8; + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + EXPECT_EQ(presenter.framesInFlight(), 2); + { + Submits submits{core, queue}; + for(size_t i = 0; i < FRAMES; ++i) { + auto imageOpt = acquire(core, presenter); + ASSERT_TRUE(imageOpt.has_value()); + EXPECT_EQ(imageOpt->acquireNumber(), i + 1); + EXPECT_EQ(imageOpt->extent(), test::HEADLESS_EXTENT); + EXPECT_LT(imageOpt->imageIdx(), swapchain.imageCount()); + EXPECT_EQ(&imageOpt->image(), &swapchain.image(imageOpt->imageIdx())); + // a new image waits for its acquire + EXPECT_NE(acquire_semaphore(*imageOpt), nullptr); + submits.present(presenter, std::move(*imageOpt)); + } + } + + // the queue is idle: the present fences signaled + EXPECT_TRUE(presenter.finished()); +} + +JVK_TEST(Presenter, presents_follow_the_acquire_order) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; + presentedIndices.clear(); + PresentHook const hook{core, recording_present}; + + auto firstOpt = acquire(core, presenter); + auto secondOpt = acquire(core, presenter); + ASSERT_TRUE(firstOpt.has_value()); + ASSERT_TRUE(secondOpt.has_value()); + auto const firstIdx = firstOpt->imageIdx(); + auto const secondIdx = secondOpt->imageIdx(); + submits.transition(*firstOpt); + submits.transition(*secondOpt); + + // the second image is handed back first, its present waits for the first image + std::binary_semaphore presentedSignal{0}; + std::jthread presenting{ + [&] { + core.executor().sync_wait(presenter.present(std::move(*secondOpt))); + presentedSignal.release(); + } + }; + EXPECT_FALSE(presentedSignal.try_acquire_for(PENDING)); + + core.executor().sync_wait(presenter.present(std::move(*firstOpt))); + EXPECT_TRUE(presentedSignal.try_acquire_for(TIMEOUT)); + presenting.join(); + + EXPECT_EQ(presentedIndices, (std::vector{firstIdx, secondIdx})); +} + +JVK_TEST(Presenter, drop_spares_the_image_with_its_acquire_semaphore) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; + + auto droppedOpt = acquire(core, presenter); + ASSERT_TRUE(droppedOpt.has_value()); + auto const imageIdx = droppedOpt->imageIdx(); + auto const* const semaphorePtr = acquire_semaphore(*droppedOpt); + presenter.drop(std::move(*droppedOpt)); + + // the spare comes first, with the wait of the drop + auto spareOpt = acquire(core, presenter); + ASSERT_TRUE(spareOpt.has_value()); + EXPECT_EQ(spareOpt->imageIdx(), imageIdx); + EXPECT_EQ(acquire_semaphore(*spareOpt), semaphorePtr); + EXPECT_EQ(spareOpt->acquireNumber(), 2); + submits.present(presenter, std::move(*spareOpt)); +} + +JVK_TEST(Presenter, drop_with_a_ready_point_spares_the_image_behind_it) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + // one acquire semaphore: the acquire after the drop reuses it once the ready point is reached + Presenter presenter{queue, swapchain, 1}; + Submits submits{core, queue}; + Semaphore const gate{core, cvk::create}; + + auto droppedOpt = acquire(core, presenter); + ASSERT_TRUE(droppedOpt.has_value()); + auto const imageIdx = droppedOpt->imageIdx(); + auto const ready = submits.ready(*droppedOpt, &gate); + presenter.drop(std::move(*droppedOpt), ready); + EXPECT_FALSE(presenter.finished()); + + // the spare waits for the ready point + auto spareOpt = acquire(core, presenter); + ASSERT_TRUE(spareOpt.has_value()); + EXPECT_EQ(spareOpt->imageIdx(), imageIdx); + ASSERT_TRUE(std::holds_alternative(spareOpt->wait())); + auto const& wait = std::get(spareOpt->wait()); + EXPECT_EQ(&*wait.semaphore, &*ready.semaphore); + EXPECT_EQ(wait.value, ready.value); + + // the gate before the present: the present waits for no signal that the gpu holds back + host_signal(gate, 1); + submits.present(presenter, std::move(*spareOpt)); + + // the acquire semaphore is free once the gpu reached the ready point + auto nextOpt = acquire(core, presenter); + ASSERT_TRUE(nextOpt.has_value()); + EXPECT_NE(acquire_semaphore(*nextOpt), nullptr); + submits.present(presenter, std::move(*nextOpt)); +} + +JVK_TEST(Presenter, ready_point_of_the_last_acquire_semaphore_holds_the_acquire_back) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 1}; + Submits submits{core, queue}; + Semaphore const gate{core, cvk::create}; + + auto droppedOpt = acquire(core, presenter); + ASSERT_TRUE(droppedOpt.has_value()); + auto const ready = submits.ready(*droppedOpt, &gate); + presenter.drop(std::move(*droppedOpt), ready); + auto spareOpt = acquire(core, presenter); + ASSERT_TRUE(spareOpt.has_value()); + + // no spare, the only acquire semaphore waits for the ready point + std::optional nextOpt{}; + std::binary_semaphore acquiredSignal{0}; + std::jthread acquiring{ + [&] { + nextOpt = acquire(core, presenter); + acquiredSignal.release(); + } + }; + EXPECT_FALSE(acquiredSignal.try_acquire_for(PENDING)); + + host_signal(gate, 1); + EXPECT_TRUE(acquiredSignal.try_acquire_for(TIMEOUT)); + acquiring.join(); + ASSERT_TRUE(nextOpt.has_value()); + EXPECT_NE(nextOpt->imageIdx(), spareOpt->imageIdx()); + + submits.present(presenter, std::move(*spareOpt)); + submits.present(presenter, std::move(*nextOpt)); +} + +JVK_TEST(Presenter, destroyed_image_is_dropped) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; + + uint32_t firstIdx = 0; + { + auto imageOpt = acquire(core, presenter); + ASSERT_TRUE(imageOpt.has_value()); + firstIdx = imageOpt->imageIdx(); + } + auto firstOpt = acquire(core, presenter); + ASSERT_TRUE(firstOpt.has_value()); + EXPECT_EQ(firstOpt->imageIdx(), firstIdx); + + // the move assignment drops the image it replaces + auto secondOpt = acquire(core, presenter); + ASSERT_TRUE(secondOpt.has_value()); + auto const secondIdx = secondOpt->imageIdx(); + *secondOpt = std::move(*firstOpt); + EXPECT_EQ(secondOpt->imageIdx(), firstIdx); + auto spareOpt = acquire(core, presenter); + ASSERT_TRUE(spareOpt.has_value()); + EXPECT_EQ(spareOpt->imageIdx(), secondIdx); + + submits.present(presenter, std::move(*secondOpt)); + submits.present(presenter, std::move(*spareOpt)); +} + +JVK_TEST(Presenter, destructor_releases_the_spares) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + { + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; + + // a spare with its acquire semaphore and a spare behind a ready point + auto firstOpt = acquire(core, presenter); + auto secondOpt = acquire(core, presenter); + ASSERT_TRUE(firstOpt.has_value()); + ASSERT_TRUE(secondOpt.has_value()); + auto const ready = submits.ready(*secondOpt); + presenter.drop(std::move(*firstOpt)); + presenter.drop(std::move(*secondOpt), ready); + EXPECT_TRUE(swapchain.acquired()); + } + + EXPECT_FALSE(swapchain.acquired()); +} + +JVK_TEST(Presenter, not_ready_try_falls_back_until_a_hand_back) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + auto const imageCount = swapchain.imageCount(); + // a semaphore for every image and one for the acquire that finds none + Presenter presenter{queue, swapchain, imageCount + 1}; + Submits submits{core, queue}; + + std::vector images{}; + for(uint32_t i = 0; i < imageCount; ++i) { + auto imageOpt = acquire(core, presenter); + ASSERT_TRUE(imageOpt.has_value()); + images.push_back(std::move(*imageOpt)); + } + + // every image is acquired: the try returns VK_NOT_READY, the fallback does not block + std::optional nextOpt{}; + std::binary_semaphore acquiredSignal{0}; + std::jthread acquiring{ + [&] { + nextOpt = acquire(core, presenter); + acquiredSignal.release(); + } + }; + EXPECT_FALSE(acquiredSignal.try_acquire_for(PENDING)); + + auto const firstIdx = images.front().imageIdx(); + submits.present(presenter, std::move(images.front())); + EXPECT_TRUE(acquiredSignal.try_acquire_for(TIMEOUT)); + acquiring.join(); + ASSERT_TRUE(nextOpt.has_value()); + // the headless surface gives the presented image back at once + EXPECT_EQ(nextOpt->imageIdx(), firstIdx); + + for(auto& image : images | std::views::drop(1)) + submits.present(presenter, std::move(image)); + submits.present(presenter, std::move(*nextOpt)); +} + +JVK_TEST(Presenter, fallback_waits_for_the_present_fence_of_the_last_acquire_semaphore) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 1}; + Submits submits{core, queue}; + + auto firstOpt = acquire(core, presenter); + ASSERT_TRUE(firstOpt.has_value()); + submits.present(presenter, std::move(*firstOpt)); + + // the present fence counts as unsignaled until a wait for it: no try, the fallback waits + auto& table = device_table(core); + fencesHeld = true; + fenceWaits = 0; + std::optional nextOpt{}; + { + Hook const status{table.vkGetFenceStatus, held_fence_status, realGetFenceStatus}; + Hook const wait{table.vkWaitForFences, releasing_fence_wait, realWaitForFences}; + nextOpt = acquire(core, presenter); + } + EXPECT_EQ(fenceWaits, 1); + ASSERT_TRUE(nextOpt.has_value()); + EXPECT_NE(acquire_semaphore(*nextOpt), nullptr); + submits.present(presenter, std::move(*nextOpt)); +} + +JVK_TEST(Presenter, failed_present_arrives_once_at_the_next_acquire) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; + + { + PresentHook const hook{core, failing_present}; + auto imageOpt = acquire(core, presenter); + ASSERT_TRUE(imageOpt.has_value()); + // the present does not throw + EXPECT_NO_THROW(submits.present(presenter, std::move(*imageOpt))); + } + + try { + [[maybe_unused]] auto const imageOpt = acquire(core, presenter); + ADD_FAILURE() << "the acquire must rethrow the failure of the present"; + } + catch(cvk::vk_result_exception const& e) { EXPECT_EQ(e.vkResult(), VK_ERROR_SURFACE_LOST_KHR); } + + auto imageOpt = acquire(core, presenter); + ASSERT_TRUE(imageOpt.has_value()); + submits.present(presenter, std::move(*imageOpt)); +} + +JVK_TEST(Presenter, out_of_date_present_gives_no_image_from_then_on) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; + + { + PresentHook const hook{core, failing_present}; + auto imageOpt = acquire(core, presenter); + ASSERT_TRUE(imageOpt.has_value()); + submits.present(presenter, std::move(*imageOpt)); + } + + EXPECT_FALSE(acquire(core, presenter).has_value()); + EXPECT_FALSE(acquire(core, presenter).has_value()); +} + +JVK_TEST(Presenter, out_of_date_acquire_gives_no_image_from_then_on) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; + + auto imageOpt = acquire(core, presenter); + ASSERT_TRUE(imageOpt.has_value()); + + outOfDateAcquires = 0; + { + PFN_vkAcquireNextImageKHR real = nullptr; + Hook const hook{device_table(core).vkAcquireNextImageKHR, out_of_date_acquire, real}; + EXPECT_FALSE(acquire(core, presenter).has_value()); + // out of date stays: no second try + EXPECT_FALSE(acquire(core, presenter).has_value()); + } + EXPECT_EQ(outOfDateAcquires, 1); + + // the image acquired before still presents + submits.present(presenter, std::move(*imageOpt)); +} +} From 2e723eaec53d5f21b0aaa089876cfd746f94fd58 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:05:47 +0100 Subject: [PATCH 62/68] cvk, jvk: no acquired tracking in cvk::Swapchain - removed: _acquired (std::vector), both acquired() overloads, the two CTH_CRITICAL checks, the writes - the validation layers check the acquired images (VUID-VkPresentInfoKHR-pImageIndices-01430) - jvk::Swapchain destroys a retired swapchain on presented() alone: no image of a retired swapchain is acquired - jvk::Swapchain::recreate(): @pre no image of the current swapchain is acquired - tests: hooks of the device table in place of acquired() --- cvk/incl/cvk/surface/swapchain.hpp | 16 +-- cvk/src/surface/swapchain.cpp | 24 +--- cvk/tests/src/surface/swapchain_test.cpp | 46 +++---- jvk/incl/jvk/graph/swapchain.hpp | 5 +- jvk/src/graph/presenter.cpp | 2 +- jvk/src/graph/swapchain.cpp | 2 +- jvk/tests/src/base/queue_test.cpp | 3 - jvk/tests/src/graph/presenter_test.cpp | 12 +- jvk/tests/src/graph/surface_test.cpp | 160 ++++++++++++++++++----- jvk/tests/src/graph/swapchain_test.cpp | 29 ++-- 10 files changed, 189 insertions(+), 110 deletions(-) diff --git a/cvk/incl/cvk/surface/swapchain.hpp b/cvk/incl/cvk/surface/swapchain.hpp index 2e63f801..8f6c25d0 100644 --- a/cvk/incl/cvk/surface/swapchain.hpp +++ b/cvk/incl/cvk/surface/swapchain.hpp @@ -178,8 +178,7 @@ class Swapchain { /** * prepares the present of the image in a `vkQueuePresentKHR()` of the caller * @details waits for the present fence of the last present of the image first, then resets it - * @details the image counts as presented: the caller presents it through the present queue at - * once + * @details present the image at once, through the present queue: the fence is reset * @return the handles for the present info, the fence for `VkSwapchainPresentFenceInfoKHR` * @pre the image is acquired * @pre a submit signals `presentSemaphore()` of the image @@ -219,18 +218,6 @@ class Swapchain { */ [[nodiscard]] bool presented() const; - /** - * @return an image is acquired, without its `present()`, `preparePresent()` or `unacquire()` - */ - [[nodiscard]] constexpr bool acquired() const { return std::ranges::contains(_acquired, true); } - - /** - * @pre `imageIndex < imageCount()` - */ - [[nodiscard]] constexpr bool acquired(uint32_t imageIndex) const { - return _acquired[imageIndex]; - } - [[nodiscard]] constexpr bool created() const { return static_cast(_handle); } [[nodiscard]] constexpr VkSwapchainKHR get() const { return _handle.get(); } [[nodiscard]] constexpr Core const& core() const { return _handle.core(); } @@ -336,7 +323,6 @@ class Swapchain { std::vector _presentSemaphores{}; std::vector _views{}; std::vector _images{}; - std::vector _acquired{}; core_handle _handle; diff --git a/cvk/src/surface/swapchain.cpp b/cvk/src/surface/swapchain.cpp index a99daecd..e29f0363 100644 --- a/cvk/src/surface/swapchain.cpp +++ b/cvk/src/surface/swapchain.cpp @@ -121,7 +121,6 @@ void Swapchain::destroy() { _presentSemaphores.clear(); _views.clear(); _images.clear(); - _acquired.clear(); _handle.reset(); forget(); @@ -134,7 +133,6 @@ Swapchain::State Swapchain::release() { _presentSemaphores.clear(); _views.clear(); _images.clear(); - _acquired.clear(); State const state{ .vkSwapchain = _handle.release(), @@ -161,10 +159,8 @@ Swapchain::Acquired Swapchain::acquire(Semaphore const& signal, uint64_t timeout &imageIndex ); - if(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { - _acquired[imageIndex] = true; + if(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) return {result, imageIndex}; - } CVK_RESULT_STABLE_THROW( result != VK_ERROR_OUT_OF_DATE_KHR && result != VK_TIMEOUT && result != VK_NOT_READY, @@ -200,18 +196,11 @@ VkResult Swapchain::present(uint32_t imageIndex) { auto Swapchain::preparePresent(uint32_t imageIndex) -> PresentHandles { debug_check(*this); - CTH_CRITICAL( - imageIndex >= imageCount() || !acquired(imageIndex), - "image {} must be acquired", - imageIndex - ) {} // signaled by the last present of the image or created signaled auto const& fence = presentFence(imageIndex); fence.waitReset(); - // before the present: also a failed present ends the acquire of the image - _acquired[imageIndex] = false; return PresentHandles{ .vkSwapchain = get(), .imageIndex = imageIndex, @@ -222,12 +211,6 @@ auto Swapchain::preparePresent(uint32_t imageIndex) -> PresentHandles { void Swapchain::unacquire(span imageIndices) { debug_check(*this); - for(auto const index : imageIndices) - CTH_CRITICAL( - index >= imageCount() || !acquired(index), - "image {} must be acquired", - index - ) {} if(imageIndices.empty()) return; @@ -242,9 +225,6 @@ void Swapchain::unacquire(span imageIndices) { auto const result = core().functions()->vkReleaseSwapchainImagesKHR(core().vkDevice(), &info); CVK_RESULT_STABLE_THROW(result != VK_SUCCESS, result, "failed to unacquire swapchain images") {} - - for(auto const index : imageIndices) - _acquired[index] = false; } bool Swapchain::presented() const { @@ -328,8 +308,6 @@ void Swapchain::createImages() { } ); } - - _acquired.assign(count, false); } void Swapchain::forget() { diff --git a/cvk/tests/src/surface/swapchain_test.cpp b/cvk/tests/src/surface/swapchain_test.cpp index 1b7ca6d2..b2df3b34 100644 --- a/cvk/tests/src/surface/swapchain_test.cpp +++ b/cvk/tests/src/surface/swapchain_test.cpp @@ -279,27 +279,17 @@ CVK_TEST(Swapchain, old_swapchain_presents_its_acquired_image) { << "present result: " << presented; fence.wait(); - EXPECT_FALSE(old.acquired()); old.destroy(); EXPECT_EQ(present_cleared_image(context, swapchain), VK_SUCCESS); } -CVK_TEST(Swapchain, acquired_and_presented) { +CVK_TEST(Swapchain, presented_once_the_presents_ended) { test::PresentContext const context{}; Swapchain swapchain{context.core, context.queue(), context.surface(), {}, EXTENT}; - EXPECT_FALSE(swapchain.acquired()); + // the present fences are created signaled EXPECT_TRUE(swapchain.presented()); - Semaphore const acquired{context.core, create}; - auto const [result, index] = swapchain.acquire(acquired); - ASSERT_TRUE(index.has_value()); - EXPECT_TRUE(swapchain.acquired()); - swapchain.unacquire(std::array{*index}); - EXPECT_FALSE(swapchain.acquired()); - consume(context, acquired); - EXPECT_EQ(present_cleared_image(context, swapchain), VK_SUCCESS); - EXPECT_FALSE(swapchain.acquired()); // the headless surface completes presents at once, the bound only ends a broken loop for(uint32_t i = 0; i < 1000 && !swapchain.presented(); ++i) std::this_thread::sleep_for(std::chrono::milliseconds{1}); @@ -336,16 +326,29 @@ CVK_TEST(Swapchain, present_fences_are_exportable) { CVK_TEST(Swapchain, unacquire_gives_the_image_back) { test::PresentContext const context{}; Swapchain swapchain{context.core, context.queue(), context.surface(), {}, EXTENT}; - Semaphore const acquired{context.core, create}; - auto const [result, index] = swapchain.acquire(acquired); - ASSERT_TRUE(index.has_value()); - EXPECT_TRUE(swapchain.acquired(*index)); - - swapchain.unacquire(std::array{*index}); - - EXPECT_FALSE(swapchain.acquired(*index)); - consume(context, acquired); + // every image acquired: the next acquire without a wait finds none + std::vector signals{}; + for(uint32_t i = 0; i <= swapchain.imageCount(); ++i) + signals.emplace_back(context.core, create); + std::vector indices{}; + for(uint32_t i = 0; i < swapchain.imageCount(); ++i) { + auto const [result, index] = swapchain.acquire(signals[i], 0); + ASSERT_TRUE(index.has_value()) << "acquire result: " << result; + indices.push_back(*index); + } + for(uint32_t i = 0; i < swapchain.imageCount(); ++i) + consume(context, signals[i]); + EXPECT_EQ(swapchain.acquire(signals.back(), 0).result, VK_NOT_READY); + + // the image goes back to the swapchain: the next acquire gets it + swapchain.unacquire(std::array{indices.front()}); + auto const [result, index] = swapchain.acquire(signals.back(), 0); + ASSERT_TRUE(index.has_value()) << "acquire result: " << result; + EXPECT_EQ(*index, indices.front()); + consume(context, signals.back()); + + swapchain.unacquire(indices); } CVK_TEST(Swapchain, old_swapchain_unacquires_its_image) { @@ -360,7 +363,6 @@ CVK_TEST(Swapchain, old_swapchain_unacquires_its_image) { old.unacquire(std::array{*index}); consume(context, acquired); - EXPECT_FALSE(old.acquired()); EXPECT_EQ(present_cleared_image(context, swapchain), VK_SUCCESS); } diff --git a/jvk/incl/jvk/graph/swapchain.hpp b/jvk/incl/jvk/graph/swapchain.hpp index 427fa16f..8e702326 100644 --- a/jvk/incl/jvk/graph/swapchain.hpp +++ b/jvk/incl/jvk/graph/swapchain.hpp @@ -25,7 +25,6 @@ namespace jvk { * @details * - holds the current `cvk::Swapchain` and the retired ones, at stable addresses * - `recreate()` creates the next swapchain with the current one as the old swapchain, the old one retires - * - a retired swapchain still presents its acquired images * - `acquire()` destroys the retired swapchains that finished their presents first * @attention not thread safe: the surface orders its uses, see `Surface` */ @@ -58,6 +57,8 @@ class Swapchain { * creates the next swapchain with the current one as the old swapchain, the old one retires * @details with the config of the current swapchain, see `cvk::Swapchain::create()` * @pre `created()` + * @pre no image of the current swapchain is acquired: `acquire()` destroys a retired + * swapchain once its presents ended * @pre the preconditions of `cvk::Swapchain::create()` * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode, the current swapchain * stays @@ -83,7 +84,7 @@ class Swapchain { /** * destroys the finished retired swapchains, then acquires the next image of the current swapchain - * @details finished: `cvk::Swapchain::presented()` and not `cvk::Swapchain::acquired()`, from the oldest on + * @details finished: `cvk::Swapchain::presented()`, from the oldest on * @pre `created()` * @see `cvk::Swapchain::acquire()` */ diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index 619418d5..b47d9d4b 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -143,7 +143,7 @@ cth::co::executor_task Presenter::present(Image image) { catch(...) { error = std::current_exception(); } std::scoped_lock const lock{_mutex}; - // also a failed present ends the acquire, see cvk::Swapchain::preparePresent() + // a failed present counts too: nothing presents the image again --_acquiredImages; if(auto const* const semaphorePtr = std::get_if>(&wait)) _reuses[semaphoreIdx(**semaphorePtr)] = Presented{imageIdx}; diff --git a/jvk/src/graph/swapchain.cpp b/jvk/src/graph/swapchain.cpp index 4a20e734..bd66ea4f 100644 --- a/jvk/src/graph/swapchain.cpp +++ b/jvk/src/graph/swapchain.cpp @@ -43,7 +43,7 @@ void Swapchain::destroy() { cvk::Swapchain::Acquired Swapchain::acquire(cvk::Semaphore const& signal, uint64_t timeout) { debug_check(*this); - while(retired() != 0 && !_swapchains.front().acquired() && _swapchains.front().presented()) + while(retired() != 0 && _swapchains.front().presented()) _swapchains.pop_front(); return current().acquire(signal, timeout); diff --git a/jvk/tests/src/base/queue_test.cpp b/jvk/tests/src/base/queue_test.cpp index 265a3579..4d0ba2e4 100644 --- a/jvk/tests/src/base/queue_test.cpp +++ b/jvk/tests/src/base/queue_test.cpp @@ -669,8 +669,6 @@ JVK_TEST(Queue, present_of_two_swapchains_in_one_call) { for(auto const result : results) EXPECT_TRUE(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) << "present result: " << result; - EXPECT_FALSE(first.current().acquired()); - EXPECT_FALSE(second.current().acquired()); static_cast(presented).wait(1); } @@ -725,7 +723,6 @@ JVK_TEST(Queue, present_without_a_submit_after_the_submit_of_the_present_semapho EXPECT_TRUE(results[0] == VK_SUCCESS || results[0] == VK_SUBOPTIMAL_KHR) << "present result: " << results[0]; - EXPECT_FALSE(current.acquired()); static_cast(presented).wait(1); } } diff --git a/jvk/tests/src/graph/presenter_test.cpp b/jvk/tests/src/graph/presenter_test.cpp index 98ab643c..ec2a31d3 100644 --- a/jvk/tests/src/graph/presenter_test.cpp +++ b/jvk/tests/src/graph/presenter_test.cpp @@ -505,6 +505,7 @@ JVK_TEST(Presenter, destructor_releases_the_spares) { auto& queue = core.queue(0); cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + auto const imageCount = swapchain.imageCount(); { Presenter presenter{queue, swapchain, 2}; Submits submits{core, queue}; @@ -517,10 +518,17 @@ JVK_TEST(Presenter, destructor_releases_the_spares) { auto const ready = submits.ready(*secondOpt); presenter.drop(std::move(*firstOpt)); presenter.drop(std::move(*secondOpt), ready); - EXPECT_TRUE(swapchain.acquired()); } - EXPECT_FALSE(swapchain.acquired()); + // the spares are back in the swapchain: the next presenter acquires every image + Presenter presenter{queue, swapchain, imageCount}; + std::vector images{}; + for(uint32_t i = 0; i < imageCount; ++i) { + auto imageOpt = acquire(core, presenter); + ASSERT_TRUE(imageOpt.has_value()); + images.push_back(std::move(*imageOpt)); + } + // the destructor of the images drops them, the destructor of the presenter releases them } JVK_TEST(Presenter, not_ready_try_falls_back_until_a_hand_back) { diff --git a/jvk/tests/src/graph/surface_test.cpp b/jvk/tests/src/graph/surface_test.cpp index 9f9a8f36..38f7d225 100644 --- a/jvk/tests/src/graph/surface_test.cpp +++ b/jvk/tests/src/graph/surface_test.cpp @@ -21,11 +21,13 @@ #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -114,41 +116,125 @@ namespace { core.executor().sync_wait(await_stage(stage)); } + /** the image `vkAcquireNextImageKHR()` gave, without its present or release */ + struct TrackedImage { + VkSwapchainKHR vkSwapchain; + uint32_t imageIdx; + + constexpr bool operator==(TrackedImage const& other) const = default; + }; + + std::mutex trackedMutex{}; + std::vector trackedImages{}; + + /** the functions of the device table before the tracking hooks */ + PFN_vkAcquireNextImageKHR trackedAcquire = nullptr; + PFN_vkQueuePresentKHR trackedPresent = nullptr; + PFN_vkReleaseSwapchainImagesKHR trackedRelease = nullptr; + + void untrack(VkSwapchainKHR vkSwapchain, uint32_t imageIdx) { + std::scoped_lock const lock{trackedMutex}; + std::erase(trackedImages, TrackedImage{vkSwapchain, imageIdx}); + } + + VKAPI_ATTR VkResult VKAPI_CALL tracking_acquire( + VkDevice device, + VkSwapchainKHR vkSwapchain, + uint64_t timeout, + VkSemaphore vkSemaphore, + VkFence vkFence, + uint32_t* imageIdx + ) { + auto const result = + trackedAcquire(device, vkSwapchain, timeout, vkSemaphore, vkFence, imageIdx); + if(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { + std::scoped_lock const lock{trackedMutex}; + trackedImages.push_back({vkSwapchain, *imageIdx}); + } + return result; + } + + VKAPI_ATTR VkResult VKAPI_CALL tracking_present(VkQueue queue, VkPresentInfoKHR const* info) { + auto const result = trackedPresent(queue, info); + for(uint32_t i = 0; i < info->swapchainCount; ++i) + untrack(info->pSwapchains[i], info->pImageIndices[i]); + return result; + } + + VKAPI_ATTR VkResult VKAPI_CALL tracking_release( + VkDevice device, + VkReleaseSwapchainImagesInfoKHR const* info + ) { + auto const result = trackedRelease(device, info); + if(result == VK_SUCCESS) + for(uint32_t i = 0; i < info->imageIndexCount; ++i) + untrack(info->swapchain, info->pImageIndices[i]); + return result; + } + /** - * @return number of the acquired images of the swapchain + * tracks the acquired images of the core through hooks of its device table + * @details + * - an acquire adds the image, a present or a release removes it + * - thread safe: the hooks run in the strands and on the driver threads + * - the core reads the device table at each call */ - [[nodiscard]] size_t acquired_images(Surface const& surface) { - size_t acquired = 0; - for(uint32_t imageIdx = 0; imageIdx < surface.swapchain().current().imageCount(); ++ - imageIdx) - if(surface.swapchain().current().acquired(imageIdx)) - ++acquired; - return acquired; - } + class AcquireTracker { + public: + explicit AcquireTracker(Core const& core) : + _table{*const_cast(static_cast(core).functions())} { + trackedImages.clear(); + trackedAcquire = std::exchange(_table->vkAcquireNextImageKHR, tracking_acquire); + trackedPresent = std::exchange(_table->vkQueuePresentKHR, tracking_present); + trackedRelease = std::exchange(_table->vkReleaseSwapchainImagesKHR, tracking_release); + } + + ~AcquireTracker() { + _table->vkAcquireNextImageKHR = trackedAcquire; + _table->vkQueuePresentKHR = trackedPresent; + _table->vkReleaseSwapchainImagesKHR = trackedRelease; + } + + /** + * @return number of the acquired images of the swapchain + */ + [[nodiscard]] size_t count(cvk::Swapchain const& swapchain) const { + std::scoped_lock const lock{trackedMutex}; + return static_cast( + std::ranges::count(trackedImages, swapchain.get(), &TrackedImage::vkSwapchain) + ); + } + + [[nodiscard]] bool acquired(cvk::Swapchain const& swapchain, uint32_t imageIdx) const { + std::scoped_lock const lock{trackedMutex}; + return std::ranges::contains(trackedImages, TrackedImage{swapchain.get(), imageIdx}); + } + + private: + cth::ref_wrapper _table; + + public: + AcquireTracker(AcquireTracker const& other) = delete; + AcquireTracker& operator=(AcquireTracker const& other) = delete; + }; /** - * reads the acquire state of the image in the strand of the surface queue + * @return number of the acquired images of the current swapchain */ - cth::co::executor_task acquired_in_strand( - Queue const& queue, - Surface const& surface, - uint32_t imageIdx - ) { - co_await queue.executor().schedule(); - co_return surface.swapchain().current().acquired(imageIdx); + [[nodiscard]] size_t acquired_images(AcquireTracker const& tracker, Surface const& surface) { + return tracker.count(surface.swapchain().current()); } /** * @return the image is no longer acquired before the timeout, e.g. presented */ [[nodiscard]] bool reaches_unacquired( - Core const& core, - Queue const& queue, + AcquireTracker const& tracker, Surface const& surface, uint32_t imageIdx ) { auto const deadline = std::chrono::steady_clock::now() + TIMEOUT; - while(core.executor().sync_wait(acquired_in_strand(queue, surface, imageIdx))) { + while(tracker.acquired(surface.swapchain().current(), imageIdx)) { if(std::chrono::steady_clock::now() > deadline) return false; std::this_thread::sleep_for(std::chrono::milliseconds{1}); @@ -514,6 +600,7 @@ JVK_TEST(Surface, acquire_waits_for_the_present_before) { if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; + AcquireTracker const tracker{core}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; @@ -530,7 +617,7 @@ JVK_TEST(Surface, acquire_waits_for_the_present_before) { std::jthread frame{ [&] { auto const image = acquire(core, surface, second); - acquiredImages = acquired_images(surface); + acquiredImages = acquired_images(tracker, surface); acquiredSignal.release(); EXPECT_TRUE(image); auto const primary = second.begin(); @@ -589,6 +676,7 @@ JVK_TEST(Surface, next_acquire_after_a_skipped_stage_unacquires_the_image) { if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; + AcquireTracker const tracker{core}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; @@ -605,14 +693,14 @@ JVK_TEST(Surface, next_acquire_after_a_skipped_stage_unacquires_the_image) { stage.skip(); } EXPECT_EQ(stage.status(), Stage::Status::SKIPPED); - EXPECT_EQ(acquired_images(surface), 1); + EXPECT_EQ(acquired_images(tracker, surface), 1); // at once: the acquire waits for the skip on the gpu before the unacquire, no validation error auto& next = next_frame(core, graph).stage(0); { auto const image = acquire(core, surface, next); ASSERT_TRUE(image.has_value()); - EXPECT_EQ(acquired_images(surface), 1); + EXPECT_EQ(acquired_images(tracker, surface), 1); auto const primary = next.begin(); clear(*primary, *image); } @@ -627,6 +715,7 @@ JVK_TEST(Surface, image_without_a_use_presents_after_the_submit) { if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; + AcquireTracker const tracker{core}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; @@ -640,7 +729,7 @@ JVK_TEST(Surface, image_without_a_use_presents_after_the_submit) { imageIdx = image->imageIdx; auto const primary = stage.begin(); } - EXPECT_TRUE(reaches_unacquired(core, core.queue(0), surface, imageIdx)); + EXPECT_TRUE(reaches_unacquired(tracker, surface, imageIdx)); wait(core, stage); present_frame(core, graph, surface); @@ -653,6 +742,7 @@ JVK_TEST(Surface, exception_in_the_recording_submits_and_presents_nothing) { if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; + AcquireTracker const tracker{core}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; StageGraph graph{core, {.stages = {{.queueIdx = 0}}, .frameSlots = 2}}; @@ -677,13 +767,13 @@ JVK_TEST(Surface, exception_in_the_recording_submits_and_presents_nothing) { // the scope skipped the stage, the skip drops the image, the next acquire gives it back first ASSERT_NE(stagePtr, nullptr); EXPECT_EQ(stagePtr->status(), Stage::Status::SKIPPED); - EXPECT_TRUE(surface.swapchain().current().acquired(imageIdx)); + EXPECT_TRUE(tracker.acquired(surface.swapchain().current(), imageIdx)); auto& stage = next_frame(core, graph).stage(0); { auto const image = acquire(core, surface, stage); ASSERT_TRUE(image.has_value()); - EXPECT_EQ(acquired_images(surface), 1); + EXPECT_EQ(acquired_images(tracker, surface), 1); auto const primary = stage.begin(); clear(*primary, *image); } @@ -698,6 +788,7 @@ JVK_TEST(Surface, exception_after_the_submit_presents_the_image) { if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; + AcquireTracker const tracker{core}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; @@ -719,7 +810,7 @@ JVK_TEST(Surface, exception_after_the_submit_presents_the_image) { EXPECT_EQ(stage.status(), Stage::Status::SUBMITTED); // the stage is submitted: its submission presents the image - EXPECT_TRUE(reaches_unacquired(core, core.queue(0), surface, *imageIdxOpt)); + EXPECT_TRUE(reaches_unacquired(tracker, surface, *imageIdxOpt)); wait(core, stage); present_frame(core, graph, surface); @@ -805,6 +896,7 @@ JVK_TEST(Surface, present_stage_without_a_use_presents_the_image_of_the_acquire_ if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; + AcquireTracker const tracker{core}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; StageGraph graph{core, scene_and_ui()}; @@ -822,11 +914,11 @@ JVK_TEST(Surface, present_stage_without_a_use_presents_the_image_of_the_acquire_ // the scene stage submitted, the image stays acquired until the ui stage EXPECT_EQ(frame[SCENE].status(), Stage::Status::SUBMITTED); wait(core, frame[SCENE]); - EXPECT_TRUE(surface.swapchain().current().acquired(imageIdx)); + EXPECT_TRUE(tracker.acquired(surface.swapchain().current(), imageIdx)); { auto const ui = frame[UI].begin(); } - EXPECT_TRUE(reaches_unacquired(core, core.queue(0), surface, imageIdx)); + EXPECT_TRUE(reaches_unacquired(tracker, surface, imageIdx)); present_scene_and_ui(core, graph, surface); } @@ -838,6 +930,7 @@ JVK_TEST(Surface, skipped_present_stage_drops_the_image) { if(!create_present_core(coreOpt, context, windowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; + AcquireTracker const tracker{core}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; StageGraph graph{core, scene_and_ui()}; @@ -850,14 +943,14 @@ JVK_TEST(Surface, skipped_present_stage_drops_the_image) { clear(*scene, *image); } frame[UI].skip(); - EXPECT_EQ(acquired_images(surface), 1); + EXPECT_EQ(acquired_images(tracker, surface), 1); // the next acquire waits for the skip on the gpu, then unacquires the image auto& next = next_frame(core, graph); { auto const image = acquire(core, surface, next[SCENE], next[UI]); ASSERT_TRUE(image.has_value()); - EXPECT_EQ(acquired_images(surface), 1); + EXPECT_EQ(acquired_images(tracker, surface), 1); auto const scene = next[SCENE].begin(); clear(*scene, *image); } @@ -907,6 +1000,7 @@ JVK_TEST(Surface, two_surfaces_present_after_one_stage) { if(!create_present_core(coreOpt, context, firstWindowSurface)) GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; + AcquireTracker const tracker{core}; Surface first{core, core.queue(0), {}, std::move(firstWindowSurface)}; Surface second{core, core.queue(0), {}, std::move(secondWindowSurface)}; @@ -928,8 +1022,8 @@ JVK_TEST(Surface, two_surfaces_present_after_one_stage) { auto const ui = frame[UI].begin(); } wait(core, frame[UI]); - EXPECT_TRUE(reaches_unacquired(core, core.queue(0), first, firstImage->imageIdx)); - EXPECT_TRUE(reaches_unacquired(core, core.queue(0), second, secondImage->imageIdx)); + EXPECT_TRUE(reaches_unacquired(tracker, first, firstImage->imageIdx)); + EXPECT_TRUE(reaches_unacquired(tracker, second, secondImage->imageIdx)); } } diff --git a/jvk/tests/src/graph/swapchain_test.cpp b/jvk/tests/src/graph/swapchain_test.cpp index befa651e..3e0ed241 100644 --- a/jvk/tests/src/graph/swapchain_test.cpp +++ b/jvk/tests/src/graph/swapchain_test.cpp @@ -11,6 +11,8 @@ #include "cvk/render/sync/semaphore.hpp" #include "cvk/utility/vk_exceptions.hpp" +#include + #include #include @@ -46,6 +48,13 @@ namespace { return true; } + /** the `vkGetFenceStatus()` of the device table before `unsignaled_fence_status()` */ + PFN_vkGetFenceStatus realGetFenceStatus = nullptr; + + VKAPI_ATTR VkResult VKAPI_CALL unsignaled_fence_status(VkDevice, VkFence) { + return VK_NOT_READY; + } + /** * acquires an image of the current swapchain * @return the image index, the semaphore of the acquire is waited for @@ -94,17 +103,21 @@ JVK_TEST(Swapchain, acquire_destroys_the_finished_retired_swapchains) { Swapchain swapchain{core, core.queue(0).vk(), surface}; swapchain.create({}, EXTENT); - auto& old = swapchain.current(); - auto const oldIdx = acquire(core, swapchain); - - // the retired swapchain holds an acquired image: the acquire keeps it + swapchain.current().unacquire(std::array{acquire(core, swapchain)}); swapchain.recreate({32, 32}); - auto const currentIdx = acquire(core, swapchain); EXPECT_EQ(swapchain.retired(), 1); - old.unacquire(std::array{oldIdx}); - swapchain.current().unacquire(std::array{currentIdx}); - static_cast(acquire(core, swapchain)); + // the present fences count as unsignaled: the presents of the retired swapchain did not end + { + cvk::Core const& vk = core; + auto& table = *const_cast(vk.functions()); + realGetFenceStatus = std::exchange(table.vkGetFenceStatus, unsignaled_fence_status); + swapchain.current().unacquire(std::array{acquire(core, swapchain)}); + table.vkGetFenceStatus = realGetFenceStatus; + } + EXPECT_EQ(swapchain.retired(), 1); + + swapchain.current().unacquire(std::array{acquire(core, swapchain)}); EXPECT_EQ(swapchain.retired(), 0); swapchain.destroy(); From 3bd4259e99cb90e6e748b9b73920f92b3fe619ad Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:05:47 +0100 Subject: [PATCH 63/68] jvk: Presenter::Image is Presenter::AcquiredImage - an acquired swapchain image while the engine holds it, handed back exactly once - the friend comment: the presenter owns the acquired image --- jvk/incl/jvk/graph/presenter.hpp | 56 +++++++++++++------------- jvk/src/graph/presenter.cpp | 18 +++++---- jvk/tests/src/graph/presenter_test.cpp | 29 ++++++++----- 3 files changed, 56 insertions(+), 47 deletions(-) diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/presenter.hpp index b0f1c5f8..20ebbe4c 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -34,7 +34,7 @@ class Queue; /** * orchestrates the images of one swapchain * @details - * - `acquire()` hands out an `Image`, `present()` or `drop()` hands it back + * - `acquire()` hands out an `AcquiredImage`, `present()` or `drop()` hands it back * - the presents follow the acquire order * - a dropped image is a spare: the next `acquire()` hands it out first * - owns `framesInFlight()` acquire semaphores @@ -45,7 +45,7 @@ class Queue; */ class Presenter { public: - class Image; + class AcquiredImage; /** * wait of the first use of an image: its acquire semaphore or the ready point of a drop @@ -70,7 +70,7 @@ class Presenter { /** * releases the spares, destroys the acquire semaphores * @details a failed release does not stop the destruction - * @pre every `Image` of the presenter is handed back + * @pre every `AcquiredImage` of the presenter is handed back * @pre no `acquire()` and no `present()` is pending * @pre the ready points of the spares are reached: * VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786 @@ -108,7 +108,7 @@ class Presenter { * @attention a hand back that never comes -> waits forever, e.g. the caller holds * `framesInFlight()` images */ - [[nodiscard]] cth::co::executor_task> acquire(); + [[nodiscard]] cth::co::executor_task> acquire(); /** * hands the image back for its present @@ -122,33 +122,34 @@ class Presenter { * `VK_ERROR_OUT_OF_DATE_KHR` -> it returns `std::nullopt` * @pre the image is of this presenter * @pre the image is in `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` - * @pre a submitted batch signals `Image::presentSemaphore()`, after the uses of the image and - * after the wait for `Image::wait()` + * @pre a submitted batch signals `AcquiredImage::presentSemaphore()`, after the uses of the + * image and after the wait for `AcquiredImage::wait()` */ - [[nodiscard]] cth::co::executor_task present(Image image); + [[nodiscard]] cth::co::executor_task present(AcquiredImage image); /** * hands the image back without a present: the image becomes a spare - * @details the spare keeps `Image::wait()` + * @details the spare keeps `AcquiredImage::wait()` * @pre the image is of this presenter - * @pre no submitted batch uses the image or waits for `Image::wait()` + * @pre no submitted batch uses the image or waits for `AcquiredImage::wait()` */ - void drop(Image image); + void drop(AcquiredImage image); /** * hands the image back without a present: the image becomes a spare that waits for the ready * point * @details the acquire semaphore of the image is free once the ready point is reached * @param image to drop - * @param ready reached after the uses of the image and after the wait for `Image::wait()` + * @param ready reached after the uses of the image and after the wait for + * `AcquiredImage::wait()` * @pre the image is of this presenter */ - void drop(Image image, SemaphoreSubmitInfo ready); + void drop(AcquiredImage image, SemaphoreSubmitInfo ready); /** * checks without a wait that the presenter has no work left - * @return every `Image` is handed back, no present is pending, every ready point is reached, - * every present fence of the swapchain is signaled + * @return every `AcquiredImage` is handed back, no present is pending, every ready point is + * reached, every present fence of the swapchain is signaled * @pre no `acquire()` runs at the same time: a present of its image resets a present fence * @throws cvk::vk_result_exception result of `vkGetSemaphoreCounterValue()` or * `vkGetFenceStatus()` @@ -194,7 +195,7 @@ class Presenter { }; /** result of a try: the image, a retry, the ready point to wait for or the fallback */ - using try_t = std::variant; + using try_t = std::variant; /** * the semaphore choice and the try in the strand @@ -205,7 +206,7 @@ class Presenter { /** * @return the image, `std::nullopt` -> retry */ - [[nodiscard]] cth::co::executor_task> fallback(Fallback); + [[nodiscard]] cth::co::executor_task> fallback(Fallback); /** * frees the acquire semaphores whose ready point or present fence is reached @@ -240,7 +241,7 @@ class Presenter { ); // the helpers below lock nothing, the caller holds _mutex - [[nodiscard]] Image handOut(uint32_t imageIdx, wait_t wait); + [[nodiscard]] AcquiredImage handOut(uint32_t imageIdx, wait_t wait); [[nodiscard]] Fallback startFallback(std::optional semaphoreIdxOpt); void endFallback(); /** advances `_handedBack` over the hand backs in acquire order */ @@ -291,14 +292,14 @@ class Presenter { namespace jvk { /** - * image of a `Presenter`, handed back exactly once + * acquired swapchain image of a `Presenter` while the engine holds it, handed back exactly once * @details * - `Presenter::present()` or `Presenter::drop()` hands it back, the destruction drops it * - the content is undefined: the first use transitions it from `VK_IMAGE_LAYOUT_UNDEFINED` * - the first use waits for `wait()` * - a moved-from image hands back nothing */ -class Presenter::Image { +class Presenter::AcquiredImage { public: /** * constructs the image of an acquire, `Presenter::acquire()` constructs it @@ -307,7 +308,7 @@ class Presenter::Image { * @param acquireNumber order of the acquire, the presents follow it * @param wait of the first use */ - Image(Presenter& presenter, uint32_t imageIdx, uint64_t acquireNumber, wait_t wait) : + AcquiredImage(Presenter& presenter, uint32_t imageIdx, uint64_t acquireNumber, wait_t wait) : _presenter{ &presenter, dropper{.imageIdx = imageIdx, .acquireNumber = acquireNumber, .wait = std::move(wait)} @@ -366,8 +367,7 @@ class Presenter::Image { [[nodiscard]] uint64_t acquireNumber() const { return _presenter.get_deleter().acquireNumber; } private: - // the presenter takes the hand back in present() and drop(): a public way to take it would let - // a caller skip the hand back + // the presenter owns the acquired image: its present() and drop() take the hand back friend class Presenter; /** @@ -386,17 +386,17 @@ class Presenter::Image { std::unique_ptr _presenter; ///< `nullptr` -> handed back or moved from public: - Image(Image const& other) = delete; - Image(Image&& other) noexcept = default; - Image& operator=(Image const& other) = delete; - Image& operator=(Image&& other) noexcept = default; + AcquiredImage(AcquiredImage const& other) = delete; + AcquiredImage(AcquiredImage&& other) noexcept = default; + AcquiredImage& operator=(AcquiredImage const& other) = delete; + AcquiredImage& operator=(AcquiredImage&& other) noexcept = default; - static void debug_check(Image const&); + static void debug_check(AcquiredImage const&); }; } namespace jvk { -inline void Presenter::Image::debug_check(Image const& image) { +inline void Presenter::AcquiredImage::debug_check(AcquiredImage const& image) { CTH_CRITICAL(image._presenter == nullptr, "the image must not be handed back") {} } } diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index b47d9d4b..d76a6d44 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -66,7 +66,7 @@ Presenter::~Presenter() { } } -cth::co::executor_task> Presenter::acquire() { +cth::co::executor_task> Presenter::acquire() { if(auto const error = takeError(); error != nullptr) std::rethrow_exception(error); @@ -100,7 +100,7 @@ cth::co::executor_task> Presenter::acquire() { } auto tried = co_await tryInStrand(); - if(auto* const imagePtr = std::get_if(&tried)) + if(auto* const imagePtr = std::get_if(&tried)) co_return std::move(*imagePtr); if(auto const* const readyPtr = std::get_if(&tried)) @@ -113,7 +113,7 @@ cth::co::executor_task> Presenter::acquire() { } } -cth::co::executor_task Presenter::present(Image image) { +cth::co::executor_task Presenter::present(AcquiredImage image) { CTH_CRITICAL(image._presenter.get() != this, "the image must be of this presenter") {} auto const [imageIdx, acquireNumber, wait] = image._presenter.get_deleter(); // the present hands the image back @@ -158,13 +158,13 @@ cth::co::executor_task Presenter::present(Image image) { _presentsDone.set(_presentsDone.value() + 1); } -void Presenter::drop(Image image) { +void Presenter::drop(AcquiredImage image) { CTH_CRITICAL(image._presenter.get() != this, "the image must be of this presenter") {} // the dropper spares the image image._presenter.reset(); } -void Presenter::drop(Image image, SemaphoreSubmitInfo ready) { +void Presenter::drop(AcquiredImage image, SemaphoreSubmitInfo ready) { CTH_CRITICAL(image._presenter.get() != this, "the image must be of this presenter") {} auto const [imageIdx, acquireNumber, wait] = image._presenter.get_deleter(); static_cast(image._presenter.release()); @@ -243,7 +243,9 @@ cth::co::executor_task Presenter::tryInStrand() { co_return startFallback(semaphoreIdxOpt); } -cth::co::executor_task> Presenter::fallback(Fallback start) { +cth::co::executor_task> Presenter::fallback( + Fallback start +) { // no present of the presenter is pending: the blocking acquire waits for no present that the // fallback holds back co_await _presentsDone.wait(start.presents); @@ -367,8 +369,8 @@ bool Presenter::reached(reuse_t const& reuse) const { return false; } -auto Presenter::handOut(uint32_t imageIdx, wait_t wait) -> Image { - return Image{*this, imageIdx, ++_acquires, std::move(wait)}; +auto Presenter::handOut(uint32_t imageIdx, wait_t wait) -> AcquiredImage { + return AcquiredImage{*this, imageIdx, ++_acquires, std::move(wait)}; } auto Presenter::startFallback(std::optional semaphoreIdxOpt) -> Fallback { diff --git a/jvk/tests/src/graph/presenter_test.cpp b/jvk/tests/src/graph/presenter_test.cpp index ec2a31d3..e4f34067 100644 --- a/jvk/tests/src/graph/presenter_test.cpp +++ b/jvk/tests/src/graph/presenter_test.cpp @@ -78,7 +78,7 @@ namespace { /** * @return the acquire semaphore of the wait of the image, `nullptr` -> a ready point */ - [[nodiscard]] cvk::Semaphore const* acquire_semaphore(Presenter::Image const& image) { + [[nodiscard]] cvk::Semaphore const* acquire_semaphore(Presenter::AcquiredImage const& image) { auto const* const semaphorePtr = std::get_if>(&image.wait()); return semaphorePtr != nullptr ? &semaphorePtr->get() : nullptr; @@ -88,7 +88,11 @@ namespace { * adds the wait of the image and the gate to the submit * @param gatePtr `nullptr` -> no gate, else the submit waits for its value `1` */ - void add_waits(SubmitInfo& info, Presenter::Image const& image, Semaphore const* gatePtr) { + void add_waits( + SubmitInfo& info, + Presenter::AcquiredImage const& image, + Semaphore const* gatePtr + ) { if(gatePtr != nullptr) info.waits.push_back({.semaphore = *gatePtr, .value = 1}); if(auto const* const semaphorePtr = acquire_semaphore(image)) @@ -114,7 +118,7 @@ namespace { * present semaphore * @param gatePtr `nullptr` -> no gate, else the submit waits for its value `1` too */ - void transition(Presenter::Image const& image, Semaphore const* gatePtr = nullptr) { + void transition(Presenter::AcquiredImage const& image, Semaphore const* gatePtr = nullptr) { auto& cmd = cmds.emplace_back(*core, queue->vk().familyIndex(), cvk::create); cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); cvk::Barrier barrier{}; @@ -145,7 +149,7 @@ namespace { * @return the signal of the submit, the ready point of a drop */ [[nodiscard]] SemaphoreSubmitInfo ready( - Presenter::Image const& image, + Presenter::AcquiredImage const& image, Semaphore const* gatePtr = nullptr ) { SemaphoreSubmitInfo const signal{.semaphore = done, .value = done.next()}; @@ -158,7 +162,7 @@ namespace { /** * transitions and presents the image */ - void present(Presenter& presenter, Presenter::Image image) { + void present(Presenter& presenter, Presenter::AcquiredImage image) { transition(image); core->executor().sync_wait(presenter.present(std::move(image))); } @@ -169,7 +173,10 @@ namespace { std::deque cmds{}; }; - [[nodiscard]] std::optional acquire(Core const& core, Presenter& presenter) { + [[nodiscard]] std::optional acquire( + Core const& core, + Presenter& presenter + ) { return core.executor().sync_wait(presenter.acquire()); } @@ -438,7 +445,7 @@ JVK_TEST(Presenter, ready_point_of_the_last_acquire_semaphore_holds_the_acquire_ ASSERT_TRUE(spareOpt.has_value()); // no spare, the only acquire semaphore waits for the ready point - std::optional nextOpt{}; + std::optional nextOpt{}; std::binary_semaphore acquiredSignal{0}; std::jthread acquiring{ [&] { @@ -522,7 +529,7 @@ JVK_TEST(Presenter, destructor_releases_the_spares) { // the spares are back in the swapchain: the next presenter acquires every image Presenter presenter{queue, swapchain, imageCount}; - std::vector images{}; + std::vector images{}; for(uint32_t i = 0; i < imageCount; ++i) { auto imageOpt = acquire(core, presenter); ASSERT_TRUE(imageOpt.has_value()); @@ -546,7 +553,7 @@ JVK_TEST(Presenter, not_ready_try_falls_back_until_a_hand_back) { Presenter presenter{queue, swapchain, imageCount + 1}; Submits submits{core, queue}; - std::vector images{}; + std::vector images{}; for(uint32_t i = 0; i < imageCount; ++i) { auto imageOpt = acquire(core, presenter); ASSERT_TRUE(imageOpt.has_value()); @@ -554,7 +561,7 @@ JVK_TEST(Presenter, not_ready_try_falls_back_until_a_hand_back) { } // every image is acquired: the try returns VK_NOT_READY, the fallback does not block - std::optional nextOpt{}; + std::optional nextOpt{}; std::binary_semaphore acquiredSignal{0}; std::jthread acquiring{ [&] { @@ -598,7 +605,7 @@ JVK_TEST(Presenter, fallback_waits_for_the_present_fence_of_the_last_acquire_sem auto& table = device_table(core); fencesHeld = true; fenceWaits = 0; - std::optional nextOpt{}; + std::optional nextOpt{}; { Hook const status{table.vkGetFenceStatus, held_fence_status, realGetFenceStatus}; Hook const wait{table.vkWaitForFences, releasing_fence_wait, realWaitForFences}; From 72ef756460343be6266826e44e6e88f7e88f9645 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:07:15 +0100 Subject: [PATCH 64/68] timgui: persistent vertex and index buffers per frame slot - one mapped vertex and index buffer per frame slot of the graph of the stage, no map per frame - write_lists() copies into the mapped memory, flushes the written range - a buffer too small -> a new one with std::bit_ceil(count) elements replaces it at once, never shrinks - Imgui::draw() is no longer const, @pre at most one draw() per frame, the stages of one graph - removes the two speeds of the draw: a new buffer, a map and a free in every frame --- timgui/incl/timgui/imgui.hpp | 15 +++-- timgui/src/imgui.cpp | 108 ++++++++++++++++++++++++++------ timgui/tests/src/imgui_test.cpp | 39 ++++++++++++ 3 files changed, 139 insertions(+), 23 deletions(-) diff --git a/timgui/incl/timgui/imgui.hpp b/timgui/incl/timgui/imgui.hpp index 671cf28a..3a0557d0 100644 --- a/timgui/incl/timgui/imgui.hpp +++ b/timgui/incl/timgui/imgui.hpp @@ -38,7 +38,8 @@ namespace dev { /** * ImGui on a cgfw window, drawn with a jvk core * @details - * - owns: the ImGui context, the ImPlot context, the pipeline, the ImGui textures (font atlas) + * - owns: the ImGui context, the ImPlot context, the pipeline, the ImGui textures (font atlas), + * the vertex and index buffers of the draws * - one object per window: input from the window, draws for its renderings * - ImGui and ImPlot calls only inside a `Frame` of this object * @attention one `Frame` at a time: ImGui and ImPlot keep the current context in a global @@ -59,7 +60,7 @@ class Imgui { Imgui(jvk::Core const&, cgfw::Window const& window, Config const&); /** - * destroys the ImPlot context, the ImGui context, the pipeline and the textures + * destroys the ImPlot context, the ImGui context, the pipeline, the textures and the buffers * @pre the gpu finished every frame that `draw()` recorded into, e.g. `~StageGraph()` waited */ ~Imgui(); @@ -92,16 +93,20 @@ class Imgui { /** * records the draws of the draw data * @details - * - writes the vertices and indices into host buffers - * - `stage` retains the buffers until the gpu finished + * - writes the vertices and indices into a vertex and an index buffer of the frame slot of + * `stage`, mapped for their lifetime + * - a buffer too small -> a new one with the next power of two of the count replaces it at + * once, the buffers never shrink * - binds the pipeline, sets the viewport and a scissor per draw command * - `TotalVtxCount == 0` or an empty framebuffer -> records nothing * @param stage of `cmd` * @param cmd inside a rendering with the formats and samples of `Config` * @param drawData of `Frame::render()` * @pre `upload()` of `drawData` before + * @pre at most one `draw()` per frame, the stages of one graph at a time: the frame slot + * reuses the buffers once `jvk::StageGraph::nextFrame()` waited for the frame before */ - void draw(jvk::Stage& stage, dev::cmd_buffer auto& cmd, ImDrawData const& drawData) const; + void draw(jvk::Stage& stage, dev::cmd_buffer auto& cmd, ImDrawData const& drawData); /** * ImGui texture of an image of the resource heap, for `ImGui::Image()` diff --git a/timgui/src/imgui.cpp b/timgui/src/imgui.cpp index e5b92409..37b5f4e2 100644 --- a/timgui/src/imgui.cpp +++ b/timgui/src/imgui.cpp @@ -10,6 +10,7 @@ #include "jvk/data/image.hpp" #include "jvk/data/sampler_heap.hpp" #include "jvk/graph/stage.hpp" +#include "jvk/graph/stage_graph.hpp" #include "cgfw/window/window.hpp" @@ -33,6 +34,7 @@ #include #include +#include #include #include #include @@ -41,6 +43,7 @@ #include #include #include +#include namespace timgui::dev { @@ -80,6 +83,20 @@ struct Texture { jvk::SampledImage sampled; }; +/** + * vertex and index buffer of the draws of one frame slot + * @details persistently mapped host memory, the buffers only grow + */ +struct DrawBuffers { + /** + * constructs the buffers, creates none + */ + explicit DrawBuffers(cvk::Core const& core); + + jvk::Buffer vertices; + jvk::Buffer indices; +}; + /** * deleter of the ImGui and the ImPlot context */ @@ -122,6 +139,12 @@ struct ImguiState { */ cth::dt::flat_hash_map> textures{}; + /** + * the buffers of `Imgui::draw()`, one per frame slot of the graph of its stages + * @details `StageGraph::nextFrame()` waited for the gpu work of the frame before in the slot + */ + std::vector drawBuffers{}; + modifier_keys modifiers{}; std::optional lastFrameOpt{}; ///< `std::nullopt` -> no frame yet @@ -142,14 +165,22 @@ namespace { .memory = {.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT}, }; + /** mapped for the lifetime of the buffer: no map per frame */ constexpr cvk::BaseBuffer::Config VERTEX_CONFIG{ .usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - .memory = {.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT}, + .memory = { + .flags = VMA_ALLOCATION_CREATE_MAPPED_BIT + | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT + }, }; + /** mapped for the lifetime of the buffer: no map per frame */ constexpr cvk::BaseBuffer::Config INDEX_CONFIG{ .usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT, - .memory = {.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT}, + .memory = { + .flags = VMA_ALLOCATION_CREATE_MAPPED_BIT + | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT + }, }; constexpr cvk::SamplerConfig SAMPLER_CONFIG{ @@ -269,22 +300,62 @@ namespace { stage.retain(std::move(staging)); } + /** + * makes room for the elements + * @details too small -> a new buffer with the next power of two of `count` elements replaces + * it, the old one is destroyed at once: its last use was the frame before in the slot + * @param[out] buffer gets the new buffer + */ + template + void reserve( + cvk::Core const& core, + jvk::Buffer& buffer, + cvk::BaseBuffer::Config const& config, + size_t count + ) { + if(buffer.created() && buffer.elements() >= count) + return; + + buffer = jvk::Buffer{core, config, std::bit_ceil(count)}; + } + + /** + * writes the elements of the lists one after the other into the mapped memory of the buffer + * @pre the memory is mapped, the elements fit + */ template void write_lists( cvk::Buffer const& buffer, ImVector const& lists, ImVector ImDrawList::* member ) { - auto const mapping = buffer.map(); - auto out = mapping.begin(); - for(ImDrawList const* list : lists) - out = std::ranges::copy(list->*member, out).out; - buffer.flush(); + auto const mapped = buffer.memory()->mapped(); + CTH_CRITICAL(mapped.empty(), "the memory of the buffer must be mapped") {} + + auto out = mapped.begin(); + size_t count = 0; + for(ImDrawList const* list : lists) { + std::span const elements{(list->*member).begin(), (list->*member).end()}; + CTH_CRITICAL( + count + elements.size() > buffer.elements(), + "the elements must fit into the buffer, got {} of {}", + count + elements.size(), + buffer.elements() + ) {} + out = std::ranges::copy(std::as_bytes(elements), out).out; + count += elements.size(); + } + // host coherent memory -> no flush, see `cvk::Memory::flush()` + buffer.flush({.size = count}); } } } namespace timgui::dev { +DrawBuffers::DrawBuffers(cvk::Core const& core) : + vertices{core, VERTEX_CONFIG}, + indices{core, INDEX_CONFIG} {} + Texture::Texture(jvk::Core const& core, ImTextureData const& data) : image{ core, @@ -378,7 +449,7 @@ void Imgui::upload(jvk::Stage& stage, dev::cmd_buffer auto& cmd, ImDrawData& dra } } -void Imgui::draw(jvk::Stage& stage, dev::cmd_buffer auto& cmd, ImDrawData const& drawData) const { +void Imgui::draw(jvk::Stage& stage, dev::cmd_buffer auto& cmd, ImDrawData const& drawData) { CTH_CRITICAL(!cmd.insideRendering(), "the command buffer must be inside a rendering") {} VkExtent2D const extent{ @@ -388,13 +459,17 @@ void Imgui::draw(jvk::Stage& stage, dev::cmd_buffer auto& cmd, ImDrawData const& if(drawData.TotalVtxCount == 0 || extent.width == 0 || extent.height == 0) return; - auto const& state = *_state; + auto& state = *_state; cvk::Core const& vk = *state.core; - auto const vertexCount = static_cast(drawData.TotalVtxCount); - auto const indexCount = static_cast(drawData.TotalIdxCount); - jvk::Buffer vertices{vk, VERTEX_CONFIG, vertexCount}; - jvk::Buffer indices{vk, INDEX_CONFIG, indexCount}; + // the gpu finished the frame before in the slot: its buffers are free to overwrite + auto const frameSlots = stage.graph().config().frameSlots; + while(state.drawBuffers.size() < frameSlots) + state.drawBuffers.emplace_back(vk); + auto& [vertices, indices] = state.drawBuffers[stage.slot()]; + + reserve(vk, vertices, VERTEX_CONFIG, static_cast(drawData.TotalVtxCount)); + reserve(vk, indices, INDEX_CONFIG, static_cast(drawData.TotalIdxCount)); write_lists(vertices, drawData.CmdLists, &ImDrawList::VtxBuffer); write_lists(indices, drawData.CmdLists, &ImDrawList::IdxBuffer); @@ -453,9 +528,6 @@ void Imgui::draw(jvk::Stage& stage, dev::cmd_buffer auto& cmd, ImDrawData const& firstIndex += static_cast(list->IdxBuffer.Size); firstVertex += list->VtxBuffer.Size; } - - stage.retain(std::move(vertices)); - stage.retain(std::move(indices)); } ImTextureRef Imgui::texture(jvk::heap_idx imageIdx) const { @@ -467,8 +539,8 @@ Imgui& Imgui::operator=(Imgui&&) noexcept = default; template void Imgui::upload(jvk::Stage&, jvk::PrimaryCmdBuffer&, ImDrawData&); template void Imgui::upload(jvk::Stage&, jvk::SecondaryCmdBuffer&, ImDrawData&); -template void Imgui::draw(jvk::Stage&, jvk::PrimaryCmdBuffer&, ImDrawData const&) const; -template void Imgui::draw(jvk::Stage&, jvk::SecondaryCmdBuffer&, ImDrawData const&) const; +template void Imgui::draw(jvk::Stage&, jvk::PrimaryCmdBuffer&, ImDrawData const&); +template void Imgui::draw(jvk::Stage&, jvk::SecondaryCmdBuffer&, ImDrawData const&); } namespace timgui { diff --git a/timgui/tests/src/imgui_test.cpp b/timgui/tests/src/imgui_test.cpp index 1fd2fab8..8f228c04 100644 --- a/timgui/tests/src/imgui_test.cpp +++ b/timgui/tests/src/imgui_test.cpp @@ -391,6 +391,45 @@ TIMGUI_TEST(Imgui, draw_without_vertices_records_nothing) { EXPECT_EQ(target.pixel(EXTENT.width / 2, EXTENT.height / 2), CLEAR); } +TIMGUI_TEST(Imgui, draw_grows_its_buffers_over_the_frames) { + // the rects per side of the grid in each frame: more vertices than the buffers of the slot + // hold, then fewer + constexpr std::array SIDES{1, 2, 4, 8, 16, 32, 1}; + + test::Context context{}; + cgfw::Window const window{test::window_config()}; + Imgui imgui{context.core, window, {.colorFormat = VK_FORMAT_R8G8B8A8_UNORM}}; + Target const target{context.core, VK_FORMAT_R8G8B8A8_UNORM}; + jvk::StageGraph graph{context.core, {.stages = {{.queueIdx = 0}}}}; + + for(size_t frameIdx = 0; frameIdx < SIDES.size(); ++frameIdx) { + auto const side = SIDES[frameIdx]; + auto const color = frameIdx % 2 == 0 ? RED : GRAY; + auto& drawData = windowless_frame( + [side, color](ImDrawList& drawList) { + auto const display = ImGui::GetIO().DisplaySize; + auto const count = static_cast(side); + ImVec2 const cell{display.x / count, display.y / count}; + for(uint32_t i = 0; i < side; ++i) + for(uint32_t j = 0; j < side; ++j) { + ImVec2 const min{ + static_cast(i) * cell.x, + static_cast(j) * cell.y + }; + drawList.AddRectFilled(min, ImVec2{min.x + cell.x, min.y + cell.y}, color); + } + } + ); + // 4 vertices per rect + ASSERT_EQ(drawData.TotalVtxCount, static_cast(4 * side * side)); + draw_frame(context.core, graph, imgui, drawData, target); + + EXPECT_EQ(target.pixel(0, 0), color) << "frame " << frameIdx; + EXPECT_EQ(target.pixel(EXTENT.width / 2, EXTENT.height / 2), color) << "frame " << frameIdx; + EXPECT_EQ(target.pixel(EXTENT.width - 1, EXTENT.height - 1), color) << "frame " << frameIdx; + } +} + TIMGUI_TEST(Imgui, texture_draws_an_image_of_the_heap) { constexpr std::array GREEN{0, 255, 0, 255}; From f25e3c72c00b10b956f1c90d30589ec613f5b340 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:47:28 +0100 Subject: [PATCH 65/68] cvk, jvk: the Presenter orchestrates every acquire and present - jvk::Swapchain holds a cvk::Swapchain and its Presenter per swapchain, current and retired - a retired entry is destroyed once its Presenter::finished(), its images are erased in the graph then - a failed recreate retires the old swapchain: no acquire until the next recreate (VUID-01285) - Surface::acquire() is the bridge: the presenter's acquire, the stage wait, the assume, Stage::present() - the submission of the present stage presents after its submit, a skip drops the image with its ready point - another family: the epilogue releases, Queue::transfer() acquires and signals the present semaphore - removed: PendingPresent, dev::PresentState, the present groups of StageGraph, Queue::tryAcquire(), the try of Surface - Queue::present(): one image, no batching of swapchains - docs: an acquire from a retired swapchain is invalid (VUID-01285), not VK_ERROR_OUT_OF_DATE_KHR --- cvk/incl/cvk/surface/swapchain.hpp | 28 +--- cvk/src/surface/swapchain.cpp | 32 ++-- jvk/incl/jvk/base/queue.hpp | 88 ++--------- jvk/incl/jvk/graph/pending_present.hpp | 158 -------------------- jvk/incl/jvk/graph/stage.hpp | 57 ++----- jvk/incl/jvk/graph/stage_graph.hpp | 29 ++-- jvk/incl/jvk/graph/surface.hpp | 110 +++++--------- jvk/incl/jvk/graph/swapchain.hpp | 125 ++++++++++++---- jvk/src/base/queue.cpp | 80 +--------- jvk/src/graph/pending_present.cpp | 31 ---- jvk/src/graph/presenter.cpp | 8 +- jvk/src/graph/stage.cpp | 4 +- jvk/src/graph/stage_graph.cpp | 199 +++++++------------------ jvk/src/graph/surface.cpp | 161 +++++--------------- jvk/src/graph/swapchain.cpp | 76 ++++++++-- jvk/tests/src/base/queue_test.cpp | 148 ++---------------- jvk/tests/src/graph/surface_test.cpp | 115 +++++--------- jvk/tests/src/graph/swapchain_test.cpp | 99 +++++++++--- 18 files changed, 487 insertions(+), 1061 deletions(-) delete mode 100644 jvk/incl/jvk/graph/pending_present.hpp delete mode 100644 jvk/src/graph/pending_present.cpp diff --git a/cvk/incl/cvk/surface/swapchain.hpp b/cvk/incl/cvk/surface/swapchain.hpp index 8f6c25d0..e5407a5f 100644 --- a/cvk/incl/cvk/surface/swapchain.hpp +++ b/cvk/incl/cvk/surface/swapchain.hpp @@ -56,16 +56,6 @@ class Swapchain { std::optional imageIndex; }; - /** - * handles of one image in a `vkQueuePresentKHR()`, see `preparePresent()` - */ - struct PresentHandles { - VkSwapchainKHR vkSwapchain; - uint32_t imageIndex; - VkSemaphore vkWaitSemaphore; ///< `presentSemaphore()` of the image - VkFence vkFence; ///< `presentFence()` of the image, reset - }; - /** * base constructor */ @@ -113,8 +103,8 @@ class Swapchain { * @param extent of the window, a fixed `currentExtent` of the surface wins * @param oldSwapchainPtr the swapchain that this one replaces, `nullptr` -> none * @details the first entries of `Config::formats` and `Config::presentModes` that the surface offers win - * @details an old swapchain retires, also on a failure: it presents its acquired images, its acquires fail with - * `VK_ERROR_OUT_OF_DATE_KHR`, see `vkCreateSwapchainKHR()` + * @details an old swapchain retires, also on a failure: its acquired images still present, no + * acquire on it (VUID-vkAcquireNextImageKHR-swapchain-01285), see `vkCreateSwapchainKHR()` * @pre `Core::created()`, `Surface::created()` * @pre the queue can present to the surface * @pre the device enables `constants::PRESENT_DEVICE_EXTENSIONS`, a present queue of the core does @@ -167,7 +157,8 @@ class Swapchain { /** * presents the image once its present semaphore signals * @return `VK_SUCCESS`, `VK_SUBOPTIMAL_KHR` or `VK_ERROR_OUT_OF_DATE_KHR` - * @details waits for the present fence of the last present of the image first + * @details waits for the present fence of the last present of the image first, the present + * signals it again, see `presentFence()` * @details `VK_ERROR_OUT_OF_DATE_KHR` -> the present still waits for the semaphore * @pre the image is acquired * @pre a submit signals `presentSemaphore()` of the image @@ -175,17 +166,6 @@ class Swapchain { */ [[nodiscard]] VkResult present(uint32_t imageIndex); - /** - * prepares the present of the image in a `vkQueuePresentKHR()` of the caller - * @details waits for the present fence of the last present of the image first, then resets it - * @details present the image at once, through the present queue: the fence is reset - * @return the handles for the present info, the fence for `VkSwapchainPresentFenceInfoKHR` - * @pre the image is acquired - * @pre a submit signals `presentSemaphore()` of the image - * @see `present()` - */ - [[nodiscard]] PresentHandles preparePresent(uint32_t imageIndex); - /** * gives acquired images back without a present * @pre the images are acquired and all uses of them completed diff --git a/cvk/src/surface/swapchain.cpp b/cvk/src/surface/swapchain.cpp index e29f0363..ce678b59 100644 --- a/cvk/src/surface/swapchain.cpp +++ b/cvk/src/surface/swapchain.cpp @@ -172,43 +172,35 @@ Swapchain::Acquired Swapchain::acquire(Semaphore const& signal, uint64_t timeout } VkResult Swapchain::present(uint32_t imageIndex) { - auto const handles = preparePresent(imageIndex); + debug_check(*this); + // signaled by the last present of the image or created signaled + auto const& fence = presentFence(imageIndex); + fence.waitReset(); + + auto const vkSwapchain = get(); + auto const vkWaitSemaphore = presentSemaphore(imageIndex).get(); + auto const vkFence = fence.get(); VkSwapchainPresentFenceInfoKHR const fenceInfo{ .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_KHR, .pNext = nullptr, .swapchainCount = 1, - .pFences = &handles.vkFence, + .pFences = &vkFence, }; VkPresentInfoKHR const info{ .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .pNext = &fenceInfo, .waitSemaphoreCount = 1, - .pWaitSemaphores = &handles.vkWaitSemaphore, + .pWaitSemaphores = &vkWaitSemaphore, .swapchainCount = 1, - .pSwapchains = &handles.vkSwapchain, - .pImageIndices = &handles.imageIndex, + .pSwapchains = &vkSwapchain, + .pImageIndices = &imageIndex, .pResults = nullptr, }; return _presentQueue.rawPresent(info); } -auto Swapchain::preparePresent(uint32_t imageIndex) -> PresentHandles { - debug_check(*this); - - // signaled by the last present of the image or created signaled - auto const& fence = presentFence(imageIndex); - fence.waitReset(); - - return PresentHandles{ - .vkSwapchain = get(), - .imageIndex = imageIndex, - .vkWaitSemaphore = presentSemaphore(imageIndex).get(), - .vkFence = fence.get(), - }; -} - void Swapchain::unacquire(span imageIndices) { debug_check(*this); diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index b8909fa1..f627694d 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -5,7 +5,6 @@ #include "cvk/base/queue/queue.hpp" #include "cvk/base/queue/submit_info.hpp" #include "cvk/render/sync/barrier.hpp" -#include "cvk/surface/swapchain.hpp" #include @@ -27,17 +26,17 @@ class scheduler; namespace cvk { class Semaphore; +class Swapchain; } namespace jvk { class Core; -class Swapchain; // in queue.hpp next to Queue: it is small, no own header /** * one batch of a submit on a `Queue` * @details - * - `Queue::submit()` and `Queue::present()` mark the jvk signals after the submit, see + * - `Queue::submit()` and `Queue::transfer()` mark the jvk signals after the submit, see * `Semaphore::markSubmitted()` * - the binary semaphores get no mark */ @@ -64,14 +63,6 @@ struct SubmitInfo { } }; -/** - * acquired image of a swapchain for `Queue::present()` - */ -struct PresentImage { - cth::ref_wrapper swapchain; - uint32_t imageIdx; ///< index of the acquired image in the swapchain -}; - /** * serialized vulkan queue * @details @@ -105,68 +96,24 @@ class Queue { * @pre the info lives until the end of the task, nothing changes it * @pre the preconditions of `cvk::Queue::submit()` * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` - * @see `present()` */ [[nodiscard]] cth::co::executor_task submit(SubmitInfo const&); /** - * submits the batch and presents the images in one strand job, then marks the jvk signals - * @details - * - the submit signals `cvk::Swapchain::presentSemaphore()` of every image too - * - one `vkQueuePresentKHR()` for all images - * - no other job of the strand runs between the submit and the present - * - a failed submit marks nothing and presents nothing - * - a failed present marks the signals before it throws: the submit reached the queue - * @param images one per swapchain - * @param[out] results one per image: `VK_SUCCESS`, `VK_SUBOPTIMAL_KHR`, - * `VK_ERROR_OUT_OF_DATE_KHR` or the error of its swapchain, also after a failed present - * @pre `cvk::Queue::canPresent()` - * @pre `results.size() == images.size()` - * @pre the info, the images and the results live until the end of the task, unchanged - * @pre the preconditions of `cvk::Queue::submit()` and of `cvk::Swapchain::preparePresent()` - * @pre the swapchains present through this queue - * @throws cvk::vk_result_exception result of `vkQueueSubmit2()` - * @throws cvk::vk_result_exception other result of `vkQueuePresentKHR()` - */ - [[nodiscard]] cth::co::executor_task present( - SubmitInfo const&, - std::span images, - std::span results - ); - - /** - * presents the images in one job of the strand, without a submit - * @details one `vkQueuePresentKHR()` for all images - * @param images one per swapchain, a submit before signals their present semaphores - * @param[out] results one per image, see the submit overload + * presents the image in one job of the strand + * @details one `vkQueuePresentKHR()` with the present fence of the image, see + * `cvk::Swapchain::present()` + * @param swapchain of the image, presents through this queue + * @param imageIdx of the acquired image, a submit before signals its present semaphore + * @return `VK_SUCCESS`, `VK_SUBOPTIMAL_KHR` or `VK_ERROR_OUT_OF_DATE_KHR` * @pre `cvk::Queue::canPresent()` - * @pre `results.size() == images.size()` - * @pre the images and the results live until the end of the task, nothing changes them - * @pre the preconditions of `cvk::Swapchain::preparePresent()` - * @pre the swapchains present through this queue + * @pre the swapchain lives until the end of the task + * @pre the preconditions of `cvk::Swapchain::present()` * @throws cvk::vk_result_exception other result of `vkQueuePresentKHR()` */ - [[nodiscard]] cth::co::executor_task present( - std::span images, - std::span results - ); - - /** - * tries to acquire the next image of the swapchain in the strand, without a wait - * @details `vkAcquireNextImageKHR()` with timeout `0`: never blocks the strand - * @details serialized with the presents of the queue: the external synchronization of the - * swapchain - * @details the retired swapchains: see `Swapchain::acquire()` - * @param swapchain to acquire from - * @param signal signaled when the image is ready - * @return `VK_NOT_READY` -> no image now, see `cvk::Swapchain::acquire()` - * @pre the preconditions of `Swapchain::acquire()` - * @pre the swapchains present through this queue - * @throws cvk::vk_result_exception other result of `vkAcquireNextImageKHR()` - */ - [[nodiscard]] cth::co::executor_task tryAcquire( - Swapchain& swapchain, - cvk::Semaphore const& signal + [[nodiscard]] cth::co::executor_task present( + cvk::Swapchain& swapchain, + uint32_t imageIdx ); // an executor_task: the receiving submission awaits it before its own submit, so the transfer @@ -223,9 +170,7 @@ class Queue { [[nodiscard]] constexpr VkQueue get() const { return _queue->get(); } private: - void submitInStrand(SubmitInfo const&, std::span presents = {}); - - void presentInStrand(std::span images, std::span results); + void submitInStrand(SubmitInfo const&); struct TransferCmd { PrimaryCmdBuffer cmd; @@ -248,11 +193,6 @@ class Queue { std::vector _waitInfos{}; std::vector _signalInfos{}; - std::vector _presentSwapchains{}; - std::vector _presentImageIndices{}; - std::vector _presentWaits{}; - std::vector _presentFences{}; - /** * the counter decides the reuse of the transfer command buffers, no reactor wait: a transfer * reads it diff --git a/jvk/incl/jvk/graph/pending_present.hpp b/jvk/incl/jvk/graph/pending_present.hpp deleted file mode 100644 index 5db581b8..00000000 --- a/jvk/incl/jvk/graph/pending_present.hpp +++ /dev/null @@ -1,158 +0,0 @@ -#pragma once -#include "jvk/base/queue.hpp" -#include "jvk/sync/semaphore.hpp" - -#include "cvk/surface/swapchain.hpp" - -#include - -#include -#include -#include - -#include -#include -#include -#include -#include - - -namespace cvk { -class Image; -} - -namespace jvk::dev { -/** - * state of a `Surface` that the pending present of its last image resolves - * @details written before `PresentState::resolved`, `Surface::acquire()` reads it after its wait - */ -struct PresentState { - /** value of the last resolved image of the surface, the images count from `1` */ - cth::co::counter_event resolved{}; - - /** set by an out of date acquire or present, `Surface::acquire()` recreates the swapchain */ - bool outOfDate = false; - - /** - * the last image was dropped: `Surface::acquire()` unacquires it - * @details the gpu finished the stages that used it before its resolve - */ - bool dropped = false; - - /** error of the failed present of the last image, `Surface::acquire()` rethrows it */ - std::exception_ptr error = nullptr; - - /** - * resolves the image as presented - * @details `VK_ERROR_OUT_OF_DATE_KHR` -> sets `PresentState::outOfDate` - * @details another result than `VK_SUCCESS`, `VK_SUBOPTIMAL_KHR` and `VK_ERROR_OUT_OF_DATE_KHR` - * sets `PresentState::error`: `error`, `nullptr` -> a `cvk::vk_result_exception` of the result - * @param value of the image - * @param result of the present of the image - * @param error exception of the present, `nullptr` -> none - * @pre the images before the image are resolved - */ - void present(uint64_t value, VkResult result, std::exception_ptr error); - - /** - * resolves the image as dropped: the next `Surface::acquire()` unacquires it - * @param value of the image - * @pre the images before the image are resolved - * @pre the gpu finished the stages that used the image, or no stage submitted a use of it - */ - void drop(uint64_t value); -}; - -/** - * deleter of a pending present: drops the image - */ -struct present_dropper { - uint64_t value; ///< of the image in `PresentState::resolved` - - void operator()(PresentState* state) const { state->drop(value); } -}; - -/** - * present of an acquired swapchain image after the submit of its present stage - * @details - * - `Surface::acquire()` hands it to the present stage, see `Stage::present()` - * - the submission of the present stage presents the image, a skip drops it - * - resolves the image exactly once: `present()`, `drop()`, or its destruction as dropped - * - destroyed pending: only after the gpu finished the stages that used the image, e.g. in - * `~StageGraph()`, or before a stage submitted a use of it - * - a moved-from present resolves nothing - */ -class PendingPresent { -public: - /** - * @param state of the surface - * @param value of the image in `PresentState::resolved` - * @param queue of the surface, presents the image - * @param swapchain the current swapchain of the surface - * @param imageIdx of the acquired image - */ - PendingPresent( - PresentState& state, - uint64_t value, - Queue& queue, - cvk::Swapchain& swapchain, - uint32_t imageIdx - ) : - _state{&state, present_dropper{.value = value}}, - _queue{queue}, - _swapchain{swapchain}, - _imageIdx{imageIdx} {} - - /** - * resolves the image as presented - * @param result of the present of the image - * @param error exception of the present, `nullptr` -> none - * @pre not resolved - * @see `PresentState::present()` - */ - void present(VkResult result, std::exception_ptr error) { - debug_check(*this); - auto const value = _state.get_deleter().value; - _state.release()->present(value, result, std::move(error)); - } - - /** - * resolves the image as dropped - * @pre not resolved - * @pre the gpu finished the stages that used the image - * @see `PresentState::drop()` - */ - void drop() { - debug_check(*this); - _state.reset(); - } - - [[nodiscard]] Queue& queue() const { return *_queue; } - [[nodiscard]] PresentImage image() const { return {_swapchain, _imageIdx}; } - - /** - * @return the image in the swapchain - */ - [[nodiscard]] cvk::Image const& swapchainImage() const { return _swapchain->image(_imageIdx); } - -private: - std::unique_ptr _state; ///< `nullptr` -> resolved or moved from - cth::ref_wrapper _queue; - cth::ref_wrapper _swapchain; - uint32_t _imageIdx; - -public: - PendingPresent(PendingPresent const& other) = delete; - PendingPresent(PendingPresent&& other) noexcept = default; - PendingPresent& operator=(PendingPresent const& other) = delete; - PendingPresent& operator=(PendingPresent&& other) noexcept = default; - - static void debug_check(PendingPresent const&); -}; -} - -namespace jvk::dev { -inline void PendingPresent::debug_check(PendingPresent const& present) { - CTH_CRITICAL(present._state == nullptr, "the present must be pending") {} -} -} diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index 9ed95e62..39b159c3 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -2,7 +2,7 @@ #include "jvk/base/queue.hpp" #include "jvk/base/stasis.hpp" #include "jvk/cmd/cmd_buffer.hpp" -#include "jvk/graph/pending_present.hpp" +#include "jvk/graph/presenter.hpp" #include "jvk/sync/resource_tracker.hpp" #include "jvk/sync/semaphore.hpp" @@ -93,23 +93,6 @@ struct SlotSubmit { constexpr void next(size_t frameSlots); }; -/** - * the images of one queue in the presents of a submission - * @see `StageSlot::presentImages` - */ -struct PresentGroup { - cth::ref_wrapper queue; ///< the queue of the surfaces of the images - - size_t first; ///< index of the first image in `StageSlot::presentImages` - size_t count; ///< of the images - - /** the present ran, also a failed one: the images resolve as presented, else dropped */ - bool presented = false; - - /** exception of a failed present, the surfaces of its images get it, `nullptr` -> none */ - std::exception_ptr error = nullptr; -}; - /** * the images and buffers of `Stage::retain()` in one frame * @details the submission erases their graph states before it destroys them, see `StageGraph::erase()` @@ -183,11 +166,11 @@ struct StageSlot { std::vector extraBinaryWaits{}; /** - * the presents of the frame of the slot, see `Stage::present()` - * @details the submission presents them after the submit or drops them on a skip, then + * the images to present in the frame of the slot, see `Stage::present()` + * @details the submission presents them after the submit or drops them after a skip, then * clears the list */ - std::vector presents{}; + std::vector presents{}; /** * the submit or the skip of the frame of the slot @@ -209,24 +192,14 @@ struct StageSlot { cvk::Barrier epilogueBarriers{}; /** - * the releases of the presented images to the queue family of their surface queue + * the releases of the presented images to the queue family of their presenter queue * @details after `StageSlot::epilogueBarriers` in the epilogue */ cvk::Barrier presentReleases{}; - /** the images of `StageSlot::presents`, the images of one queue in a row */ - std::vector presentImages{}; - - std::vector presentResults{}; ///< per entry of `StageSlot::presentImages` - - std::vector presentGroups{}; ///< one per queue of `StageSlot::presents` - - /** the present semaphores of a transfer to the queue family of a surface */ - std::vector presentSignals{}; - /** - * frame number of the last submission of the slot that ended its submit or skip and its - * presents + * frame number of the last submission of the slot that ended its submit or skip, its + * presents and its drops * @details `StageGraph::nextFrame()` awaits it before it hands out the slot again * @details initial value: `StageGraph::firstFrameNumber() - 1` */ @@ -389,22 +362,24 @@ class Stage { ); /** - * presents the swapchain image of the present after the submit of this frame + * presents the image after the submit of this frame * @details `Surface::acquire()` calls it for its present stage * @details the submission of the frame: * - the present is a use of the image after the primary, in the epilogue: the barrier to * `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR`, see `StageSlot::epilogue` * - another queue family of the last use: the last queue releases the image, the epilogue * acquires it - * - another queue family of the surface queue: the epilogue releases the image, the queue of - * the surface acquires it - * - presents the image after the submit, the images of one queue in one `vkQueuePresentKHR()` - * - a skip or a failed submit drops the image - * @param present of the image, the stage owns it until its submission resolves it + * - the submit signals `Presenter::AcquiredImage::presentSemaphore()` + * - another queue family of the presenter queue: the epilogue releases the image, the + * presenter queue acquires it and signals the present semaphore, see `Queue::transfer()` + * - after the submit: `Presenter::present()` + * - a skip or a failed submit: `Presenter::drop()` with the signal of the skip as the ready + * point + * @param image the stage holds it until its submission presents or drops it * @pre `status()` is `UNSUBMITTED` * @attention not thread safe */ - void present(dev::PendingPresent present); + void present(Presenter::AcquiredImage image); /** * submits the primary of the frame diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index 60d992b9..90d69fec 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -68,7 +68,7 @@ class StageGraph { * - a stage with an exception outside of a `scoped_submit` * - a stage that a failed `submit()` or `skip()` left `UNSUBMITTED` * @details - * - the skip drops the presents of the stage, see `Surface::acquire()` + * - the skip drops the images of `Stage::present()`, see `StageGraph::skip()` * - waits for the end of every submission * - a failed skip terminates: the waiters of the stage would hang * - a failed wait does not stop the destruction @@ -81,8 +81,8 @@ class StageGraph { /** * constructs the frame and its stages in the next slot * @details the old frame of the slot: awaits `StageSlot::submitDone` of its stages: their - * submissions ended the submits and the presents, then the stages: the gpu finished them, both - * with `cth::co::all()` and `std::execution::seq` + * submissions ended the submits, the presents and the drops, then the stages: the gpu + * finished them, both with `cth::co::all()` and `std::execution::seq` * @return the frame of the slot * @pre every stage of the frame before is submitted or skipped: `Stage::submit()`, * `Stage::skip()` or the end of its `scoped_submit` @@ -108,12 +108,16 @@ class StageGraph { * its last queue, the prologue acquires it * - waits for the stage waits of the config and the waits of `Stage::await()` * - signals `Stage::semaphore()` with `Stage::frameNumber()` - * - the images of `Stage::present()`: uses after the primary, in the epilogue, the presents - * follow the submit, see `Surface::acquire()` + * - the images of `Stage::present()`: uses after the primary, in the epilogue, the submit + * signals their present semaphores, `Presenter::present()` follows the submit, see + * `Stage::present()` * - another queue family of the last use of a presented image: the last queue releases it, * the epilogue acquires it + * - another queue family of the presenter queue: the epilogue releases the image, + * `Queue::transfer()` on the presenter queue acquires it and signals the present semaphore * - an error of the submission: skips, `nextFrame()` rethrows the error - * - a failed present: the surface of the image gets the error, see `Surface::acquire()` + * - a failed present: the presenter of the image gets the error, see `Presenter::present()` + * - a failed transfer: drops the image with the signal of the submit as the ready point * - after the gpu finished: destroys the retained objects * @details a failure here, `vkEndCommandBuffer()` or the allocation of the submission: * - no throw, the stage stays `UNSUBMITTED` @@ -134,7 +138,8 @@ class StageGraph { * @details skip submit on the queue of the stage, no command buffers: * - waits for the stage waits of the config and the waits of `Stage::await()` * - signals `Stage::semaphore()` with `Stage::frameNumber()` - * @details drops the images of `Stage::present()`, see `Surface::acquire()` + * @details drops the images of `Stage::present()` with the signal of the skip as the ready + * point, see `Presenter::drop()`: the skip waited for the acquire semaphores * @details after the gpu finished the skip submit: destroys the retained objects * @details a begun primary: ends its rendering and the primary, discards the recording * @details a failure: the failure of `submit()` @@ -216,11 +221,11 @@ class StageGraph { void presentBarriers(dev::StageSlot&); - /** throws only for a failed submit: nothing is presented or resolved then */ - [[nodiscard]] cth::co::executor_task submitAndPresent( - dev::StageSlot&, - uint64_t frameNumber - ); + /** + * presents the images of the stage slot after the submit, a failed transfer drops its image + * @details no throw: a failure goes to `_submissions` + */ + [[nodiscard]] cth::co::executor_task present(dev::StageSlot&, uint64_t frameNumber); /** the caller holds `_statesMutex` */ void eraseStates(VkImage, uint32_t mipLevels); diff --git a/jvk/incl/jvk/graph/surface.hpp b/jvk/incl/jvk/graph/surface.hpp index 65bd8f32..335c6723 100644 --- a/jvk/incl/jvk/graph/surface.hpp +++ b/jvk/incl/jvk/graph/surface.hpp @@ -1,9 +1,8 @@ #pragma once #include "jvk/base/queue.hpp" -#include "jvk/graph/pending_present.hpp" +#include "jvk/graph/presenter.hpp" #include "jvk/graph/swapchain.hpp" -#include "cvk/render/sync/semaphore.hpp" #include "cvk/surface/surface.hpp" #include "cvk/surface/swapchain.hpp" @@ -13,10 +12,8 @@ #include #include -#include #include #include -#include namespace cvk { @@ -35,6 +32,7 @@ namespace jvk { * acquired swapchain image * @details * - tracked like every image: the commands that use it record its accesses + * - a view of the `Presenter::AcquiredImage` that the present stage holds * - valid until the present stage of its acquire presented or dropped it, see * `Surface::acquire()` */ @@ -61,9 +59,10 @@ struct SurfaceConfig { cvk::Swapchain::Config swapchain{}; /** - * frames that the gpu works on at the same time, one acquire semaphore each + * frames that the gpu works on at the same time, the acquire semaphores of each presenter + * @details `< StageGraphConfig::frameSlots` of the graph of the stages -> an acquire can wait + * for the present of an earlier frame, see `Presenter::acquire()` * @pre `framesInFlight > 0` - * @pre `framesInFlight >= StageGraphConfig::frameSlots` of the graph of the stages */ uint32_t framesInFlight = 2; @@ -73,16 +72,13 @@ struct SurfaceConfig { /** * cvk surface with its swapchain, acquires its images for stages that present them * @details - * - owns the cvk surface and the swapchain - * - recreates the swapchain in `acquire()`, a retired swapchain stays until its presents ended, see - * `Swapchain` - * - tries the acquire in the strand of its queue without a wait, else acquires outside the strand - * on `Queue::scheduler()`, see `acquire()` - * - the present stage of an image presents it after its submit, see `acquire()` + * - owns the cvk surface and the swapchain with its presenters, see `Swapchain` + * - recreates the swapchain in `acquire()`, a retired swapchain stays until its presenter + * finished + * - the presenter of the current swapchain acquires the images, see `Presenter::acquire()` + * - the present stage of an image presents it after its submit, a skip drops it, see + * `Stage::present()` * - a failed present: the next `acquire()` rethrows its error - * - one acquired image at a time: `acquire()` waits until the last image is presented or dropped - * - a dropped image: the next `acquire()` or `destroy()` unacquires it after the gpu finished its - * stages * @attention not thread safe */ class Surface { @@ -108,7 +104,7 @@ class Surface { ~Surface() { optDestroy(); } /** - * takes the cvk surface, creates the swapchain and the acquire semaphores + * takes the cvk surface, creates the swapchain and its presenter * @details `cvk::Surface::extent()` `0` -> the first `acquire()` with an extent `> 0` creates * the swapchain * @details a failure destroys the parts and the cvk surface @@ -118,25 +114,17 @@ class Surface { * @post `created()` * @note calls `optDestroy()` * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode - * @throws cvk::vk_result_exception result of a create of the swapchain or the semaphores + * @throws cvk::vk_result_exception result of a create of the swapchain or its presenter */ void create(cvk::Surface); /** - * waits for the last image, destroys and forgets - * @details - * - blocks until the last acquired image is presented or dropped - * - a dropped last image: blocks until the gpu finished its stages, then unacquires it - * - destroys the acquire semaphores, the swapchain, then the cvk surface - * - a failed wait does not stop the destruction - * - drops the error of a failed present of the last image + * destroys the swapchains with their presenters, then the cvk surface, and forgets + * @details the presenters release their spares, see `~Presenter()` * @pre `created()` * @pre no `acquire()` is pending - * @pre the present stage of the last image is submitted or skipped, or its graph is destroyed: - * else the wait never ends, e.g. destroy the graphs of the stages first - * @pre the submits that wait for the acquire semaphores finished on the gpu - * @attention blocks the calling thread: a worker of the core must be free for the submissions - * of the graph + * @pre every image of the surface is presented or dropped and the gpu finished its stages: + * e.g. `~StageGraph()` of the graph of the stages */ void destroy(); @@ -150,31 +138,18 @@ class Surface { /** * acquires the next swapchain image, the present stage presents it after its submit + * @details the surface: + * - a new `cvk::Surface::extent()` or out of date -> recreates the swapchain, see + * `Swapchain::recreate()` + * - the presenter of the current swapchain acquires the image, see `Presenter::acquire()` + * - out of date -> recreates the swapchain and acquires again * @details the acquire stage: - * - waits for the acquire: `Stage::await()` with the acquire semaphore and the stages + * - waits for `Presenter::AcquiredImage::wait()` with the stages, see `Stage::await()`: the + * acquire semaphore or the ready point of a dropped image * - the state of the image in its graph: `VK_IMAGE_LAYOUT_UNDEFINED` with the wait stages, see * `StageGraph::assume()`: the first barrier of the image chains with the wait - * @details the present stage gets the present of the image, see `Stage::present()`: - * - the present is a use of the image by the present stage after its primary, in the epilogue: - * the barrier to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` from the state that the stages before left - * - another queue family of the last use: the last queue releases the image, the epilogue - * acquires it - * - another queue family than the queue of the surface: the epilogue releases the image, the - * queue of the surface acquires it, see `Queue::transfer()` - * - after its submit: the present on the queue of the surface, one `vkQueuePresentKHR()` for - * the images of one queue - * - a failed present, an exception of `Queue::present()` or another result than `VK_SUCCESS`, - * `VK_SUBOPTIMAL_KHR` and `VK_ERROR_OUT_OF_DATE_KHR`: the next `acquire()` rethrows the error - * - a skip or a failed submit drops the image: the next `acquire()` unacquires it - * @details the surface: - * - waits until the last image is presented or dropped - * - a dropped last image: waits until the gpu finished its stages, then unacquires it - * - the try: `vkAcquireNextImageKHR()` with timeout `0` in the strand of the queue, see - * `Queue::tryAcquire()` - * - no image from the try (`VK_NOT_READY`), out of date or a changed `cvk::Surface::extent()` - * -> the fallback: a blocking acquire on `Queue::scheduler()`, outside the strand - * - the fallback recreates an out of date swapchain or one with another extent first, erases - * the old images in the graph, see `StageGraph::erase()`, `Swapchain::recreate()` + * @details the present stage holds the image until its submission presents or drops it, see + * `Stage::present()` * @param acquireStage waits for the acquire, the first use of the image * @param presentStage presents the image after its submit * @param stages pipeline stages of the acquire stage that wait for the acquire @@ -184,14 +159,14 @@ class Surface { * @pre both stages belong to one frame of one graph * @pre the present stage waits for every stage of the frame that uses the image, the acquire * stage included, directly or through other stages, or is that stage, see `StageWait` - * @pre the present stage of the last image of this surface is submitted or skipped: else the - * wait never ends + * @pre the graphs of the images that a skip dropped exist: the image waits for the semaphore + * of the stage, see `StageGraph::skip()` * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode * @throws cvk::vk_result_exception other result of `vkAcquireNextImageKHR()` or * `vkCreateSwapchainKHR()` - * @throws std::exception the error of the failed present of the last image, once - * @attention `vkAcquireNextImageKHR()` can block (FIFO: the vsync throttle): it occupies a - * driver thread, `CoreConfig::driverThreads` `0` -> the calling worker + * @throws std::exception the error of a failed present before, once, see `Presenter::acquire()` + * @attention the fallback of `Presenter::acquire()` can block (FIFO: the vsync throttle): it + * occupies a driver thread, `CoreConfig::driverThreads` `0` -> a worker * @see `Stage::await()` */ [[nodiscard]] cth::co::executor_task> acquire( @@ -226,16 +201,9 @@ class Surface { private: /** - * rethrows the error of the present of the last image, unacquires a dropped last image - * @details only after the resolve of the last image - */ - void handleLastPresent(); - - /** - * a recreation erases the old images in the graph first: the new images can reuse their handles - * only when no present uses the swapchain + * creates the swapchain or recreates it for a new extent or out of date */ - void updateSwapchain(VkExtent2D extent, StageGraph* graphPtr); + void updateSwapchain(VkExtent2D extent, bool outOfDate); [[nodiscard]] Swapchain::Config swapchainConfig() const; @@ -246,17 +214,7 @@ class Surface { // destroyed after the swapchain cvk::Surface _surface; - Swapchain _swapchain; ///< the resolve of the last image orders its uses - - std::vector _acquireSemaphores{}; - - size_t _acquireSemaphoreIdx = 0; - - dev::PresentState _presentState{}; - - uint64_t _lastValue = 0; ///< `0` -> none - - uint32_t _lastImageIdx = 0; + Swapchain _swapchain; public: Surface(Surface const& other) = delete; diff --git a/jvk/incl/jvk/graph/swapchain.hpp b/jvk/incl/jvk/graph/swapchain.hpp index 8e702326..6f853d55 100644 --- a/jvk/incl/jvk/graph/swapchain.hpp +++ b/jvk/incl/jvk/graph/swapchain.hpp @@ -1,31 +1,70 @@ #pragma once +#include "jvk/graph/presenter.hpp" + #include "cvk/surface/swapchain.hpp" #include +#include #include #include #include #include #include -#include +#include namespace cvk { class Core; -class Queue; -class Semaphore; class Surface; } +namespace jvk { +class Queue; +class StageGraph; +} + +namespace jvk::dev { +/** + * swapchain with the presenter of its images + * @details the presenter refers to the swapchain: the pair does not move + */ +struct PresentedSwapchain { + /** + * creates the swapchain, then its presenter with `framesInFlight` acquire semaphores + * @details see `cvk::Swapchain::create()` and `Presenter()` + */ + PresentedSwapchain( + cvk::Core const& core, + Queue& presentQueue, + cvk::Surface const& surface, + cvk::Swapchain::Config config, + VkExtent2D extent, + cvk::Swapchain const* oldSwapchainPtr, + uint32_t framesInFlight + ); + + cvk::Swapchain swapchain; + Presenter presenter; ///< after the swapchain: destroyed before it + + PresentedSwapchain(PresentedSwapchain const& other) = delete; + PresentedSwapchain(PresentedSwapchain&& other) = delete; + PresentedSwapchain& operator=(PresentedSwapchain const& other) = delete; + PresentedSwapchain& operator=(PresentedSwapchain&& other) = delete; +}; +} + namespace jvk { /** - * swapchain with the swapchains it replaced + * swapchain with the swapchains it replaced, each with the `Presenter` of its images * @details * - holds the current `cvk::Swapchain` and the retired ones, at stable addresses - * - `recreate()` creates the next swapchain with the current one as the old swapchain, the old one retires - * - `acquire()` destroys the retired swapchains that finished their presents first + * - `recreate()` creates the next swapchain with the current one as the old swapchain, the old one + * retires + * - only the presenter of the current swapchain acquires, a retired one presents and drops the + * images it handed out + * - `acquire()` destroys the retired swapchains whose presenter finished first * @attention not thread safe: the surface orders its uses, see `Surface` */ class Swapchain { @@ -34,9 +73,16 @@ class Swapchain { /** * base constructor - * @details the swapchains present through the queue + * @details the presenters present through the queue, each with `framesInFlight` acquire + * semaphores + * @pre `framesInFlight > 0` */ - Swapchain(cvk::Core const&, cvk::Queue const& presentQueue, cvk::Surface const&); + Swapchain( + cvk::Core const&, + Queue& presentQueue, + cvk::Surface const&, + uint32_t framesInFlight + ); /** * @note calls `optDestroy()` @@ -44,33 +90,36 @@ class Swapchain { ~Swapchain() { optDestroy(); } /** - * creates the first swapchain + * creates the first swapchain and its presenter * @details see `cvk::Swapchain::create()` * @post `created()` * @note calls `optDestroy()` * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode - * @throws cvk::vk_result_exception result of `vkCreateSwapchainKHR()` or `vkGetSwapchainImagesKHR()` + * @throws cvk::vk_result_exception result of `vkCreateSwapchainKHR()` or + * `vkGetSwapchainImagesKHR()` + * @throws cvk::vk_result_exception the exceptions of `Presenter()` */ void create(Config, VkExtent2D extent); /** - * creates the next swapchain with the current one as the old swapchain, the old one retires + * creates the next swapchain and its presenter, the current one as the old swapchain retires * @details with the config of the current swapchain, see `cvk::Swapchain::create()` * @pre `created()` - * @pre no image of the current swapchain is acquired: `acquire()` destroys a retired - * swapchain once its presents ended * @pre the preconditions of `cvk::Swapchain::create()` - * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode, the current swapchain - * stays - * @throws cvk::vk_result_exception result of `vkCreateSwapchainKHR()` or `vkGetSwapchainImagesKHR()`, the - * current swapchain stays retired: its acquires fail with `VK_ERROR_OUT_OF_DATE_KHR` + * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode, the + * current swapchain stays + * @throws cvk::vk_result_exception result of `vkCreateSwapchainKHR()` or + * `vkGetSwapchainImagesKHR()` or the exceptions of `Presenter()`: the current swapchain stays, + * retired, `acquire()` returns `std::nullopt` until the next `recreate()` */ void recreate(VkExtent2D extent); /** - * destroys every swapchain and forgets + * destroys every presenter and its swapchain and forgets + * @details the oldest first, the presenter before its swapchain * @pre `created()` - * @pre the preconditions of `cvk::Swapchain::destroy()` for every swapchain + * @pre the preconditions of `~Presenter()` and of `cvk::Swapchain::destroy()` for every + * swapchain */ void destroy(); @@ -83,14 +132,17 @@ class Swapchain { } /** - * destroys the finished retired swapchains, then acquires the next image of the current swapchain - * @details finished: `cvk::Swapchain::presented()`, from the oldest on + * destroys the finished retired swapchains, then acquires the next image of the current one + * @details finished: `Presenter::finished()`, from the oldest on + * @details erases the images of a destroyed swapchain in the graph, see `StageGraph::erase()` + * @details the current swapchain retired by a failed `recreate()` -> `std::nullopt` + * @param graphPtr of the images, `nullptr` -> none + * @return the image, `std::nullopt` -> out of date, `recreate()` the swapchain * @pre `created()` - * @see `cvk::Swapchain::acquire()` + * @see `Presenter::acquire()` */ - [[nodiscard]] cvk::Swapchain::Acquired acquire( - cvk::Semaphore const& signal, - uint64_t timeout = std::numeric_limits::max() + [[nodiscard]] cth::co::executor_task> acquire( + StageGraph* graphPtr ); /** @@ -99,7 +151,7 @@ class Swapchain { */ [[nodiscard]] cvk::Swapchain& current() { debug_check(*this); - return _swapchains.back(); + return _swapchains.back().swapchain; } /** @@ -107,7 +159,16 @@ class Swapchain { */ [[nodiscard]] cvk::Swapchain const& current() const { debug_check(*this); - return _swapchains.back(); + return _swapchains.back().swapchain; + } + + /** + * @return the presenter of the current swapchain + * @pre `created()` + */ + [[nodiscard]] Presenter& presenter() { + debug_check(*this); + return _swapchains.back().presenter; } [[nodiscard]] bool created() const { return !_swapchains.empty(); } @@ -119,14 +180,18 @@ class Swapchain { private: cth::ref_wrapper _core; - cth::ref_wrapper _presentQueue; + cth::ref_wrapper _presentQueue; cth::ref_wrapper _surface; + uint32_t _framesInFlight; /** * `back()` is the current swapchain, the others are retired, the oldest first - * a deque: the addresses stay at the end + * @details a deque: the addresses stay at the end */ - std::deque _swapchains{}; + std::deque _swapchains{}; + + /** a failed `recreate()` retired the current swapchain */ + bool _currentRetired = false; public: Swapchain(Swapchain const& other) = delete; diff --git a/jvk/src/base/queue.cpp b/jvk/src/base/queue.cpp index 6e1035a8..46c119ab 100644 --- a/jvk/src/base/queue.cpp +++ b/jvk/src/base/queue.cpp @@ -1,7 +1,6 @@ #include "jvk/base/queue.hpp" #include "jvk/base/core.hpp" -#include "jvk/graph/swapchain.hpp" #include "jvk/utility/exception.hpp" #include "cvk/surface/swapchain.hpp" @@ -48,40 +47,9 @@ cth::co::executor_task Queue::submit(SubmitInfo const& info) { mark(info.signals); } -cth::co::executor_task Queue::present( - SubmitInfo const& info, - span images, - span results -) { - // no suspension between the submit and the present: the presents follow the order of the - // submits - co_await executor().schedule(); - submitInStrand(info, images); - - // the marks after the present: a waiter for them uses the swapchains after vkQueuePresentKHR() - try { presentInStrand(images, results); } - catch(cvk::vk_result_exception const&) { - // the submit reached the queue: the gpu signals the values - mark(info.signals); - throw; - } - mark(info.signals); -} - -cth::co::executor_task Queue::present( - span images, - span results -) { - co_await executor().schedule(); - presentInStrand(images, results); -} - -cth::co::executor_task Queue::tryAcquire( - Swapchain& swapchain, - cvk::Semaphore const& signal -) { +cth::co::executor_task Queue::present(cvk::Swapchain& swapchain, uint32_t imageIdx) { co_await executor().schedule(); - co_return swapchain.acquire(signal, 0); + co_return swapchain.present(imageIdx); } cth::co::executor_task Queue::transfer( @@ -116,7 +84,7 @@ cth::co::executor_task Queue::transfer( co_return signal; } -void Queue::submitInStrand(SubmitInfo const& info, span presents) { +void Queue::submitInStrand(SubmitInfo const& info) { _cmdBufferInfos.clear(); for(PrimaryCmdBuffer const& cmdBuffer : info.cmdBuffers) _cmdBufferInfos.push_back(cvk::cmd_buffer_submit_info(cmdBuffer)); @@ -133,8 +101,6 @@ void Queue::submitInStrand(SubmitInfo const& info, span pres _signalInfos.push_back(cvk::signal_submit_info(signal)); for(auto const& signal : info.binarySignals) _signalInfos.push_back(cvk::signal_submit_info(signal)); - for(auto const& [swapchain, imageIdx] : presents) - _signalInfos.push_back(cvk::signal_submit_info({swapchain->presentSemaphore(imageIdx)})); _queue->rawSubmit( VkSubmitInfo2{ @@ -151,46 +117,6 @@ void Queue::submitInStrand(SubmitInfo const& info, span pres ); } -void Queue::presentInStrand(span images, span results) { - CTH_CRITICAL( - results.size() != images.size(), - "one result per image, got {} results for {} images", - results.size(), - images.size() - ) {} - - _presentSwapchains.clear(); - _presentImageIndices.clear(); - _presentWaits.clear(); - _presentFences.clear(); - for(auto const& [swapchain, imageIdx] : images) { - auto const handles = swapchain->preparePresent(imageIdx); - _presentSwapchains.push_back(handles.vkSwapchain); - _presentImageIndices.push_back(handles.imageIndex); - _presentWaits.push_back(handles.vkWaitSemaphore); - _presentFences.push_back(handles.vkFence); - } - - VkSwapchainPresentFenceInfoKHR const fenceInfo{ - .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_KHR, - .pNext = nullptr, - .swapchainCount = static_cast(_presentFences.size()), - .pFences = _presentFences.data(), - }; - static_cast(_queue->rawPresent( - VkPresentInfoKHR{ - .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, - .pNext = &fenceInfo, - .waitSemaphoreCount = static_cast(_presentWaits.size()), - .pWaitSemaphores = _presentWaits.data(), - .swapchainCount = static_cast(_presentSwapchains.size()), - .pSwapchains = _presentSwapchains.data(), - .pImageIndices = _presentImageIndices.data(), - .pResults = results.data(), - } - )); -} - auto Queue::freeTransferCmd() -> TransferCmd& { auto const reached = _transferred.gpuValue(); diff --git a/jvk/src/graph/pending_present.cpp b/jvk/src/graph/pending_present.cpp deleted file mode 100644 index 07271537..00000000 --- a/jvk/src/graph/pending_present.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "jvk/graph/pending_present.hpp" - -#include "cvk/utility/vk_exceptions.hpp" - -#include -#include - - -namespace jvk::dev { -void PresentState::present(uint64_t value, VkResult result, std::exception_ptr error) { - if(result == VK_ERROR_OUT_OF_DATE_KHR) - outOfDate = true; - if(result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR && result != VK_ERROR_OUT_OF_DATE_KHR) { - // a result without an exception of the present: a failed construction keeps its own error, - // the image resolves anyway - if(error == nullptr) { - try { throw cvk::vk_result_exception{result, "failed to present the image"}; } - catch(...) { error = std::current_exception(); } - } - this->error = std::move(error); - } - dropped = false; - // the last write: Surface::acquire() reads the state after the wait for the value - resolved.set(value); -} - -void PresentState::drop(uint64_t value) { - dropped = true; - resolved.set(value); -} -} diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index d76a6d44..f0065000 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -11,7 +11,6 @@ #include #include -#include #include #include @@ -136,10 +135,9 @@ cth::co::executor_task Presenter::present(AcquiredImage image) { co_await _fallbacksDone.wait(fallbackValue); } - std::array const images{PresentImage{.swapchain = *_swapchain, .imageIdx = imageIdx}}; - std::array results{VK_ERROR_UNKNOWN}; + VkResult result = VK_ERROR_UNKNOWN; std::exception_ptr error = nullptr; - try { co_await _queue->present(images, results); } + try { result = co_await _queue->present(*_swapchain, imageIdx); } catch(...) { error = std::current_exception(); } std::scoped_lock const lock{_mutex}; @@ -151,7 +149,7 @@ cth::co::executor_task Presenter::present(AcquiredImage image) { if(error != nullptr) { if(_error == nullptr) _error = error; - } else if(results[0] == VK_ERROR_OUT_OF_DATE_KHR) + } else if(result == VK_ERROR_OUT_OF_DATE_KHR) _outOfDate = true; handBack(acquireNumber); diff --git a/jvk/src/graph/stage.cpp b/jvk/src/graph/stage.cpp index ef81e225..dc86f73d 100644 --- a/jvk/src/graph/stage.cpp +++ b/jvk/src/graph/stage.cpp @@ -142,9 +142,9 @@ void Stage::await(cvk::Semaphore const& binary, VkPipelineStageFlags2 stages) { _stageSlot->extraBinaryWaits.emplace_back(binary, stages); } -void Stage::present(dev::PendingPresent present) { +void Stage::present(Presenter::AcquiredImage image) { CTH_CRITICAL(_status != Status::UNSUBMITTED, "the stage must be unsubmitted") {} - _stageSlot->presents.push_back(std::move(present)); + _stageSlot->presents.push_back(std::move(image)); } void Stage::submit() noexcept { _stageSlot->graph->submit(*this); } diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index 016c7080..725bd318 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -315,12 +315,8 @@ cth::co::executor_task StageGraph::submission( epilogueUses.clear(); stageSlot.epilogueBarriers.clear(); // the first use of each image in the tracker: no barrier - for(auto const& present : stageSlot.presents) - epilogueUses.access( - present.swapchainImage(), - PRESENT_ACCESS, - stageSlot.epilogueBarriers - ); + for(auto const& image : stageSlot.presents) + epilogueUses.access(image.image(), PRESENT_ACCESS, stageSlot.epilogueBarriers); append(epilogueUses, queue, stageSlot.epilogueBarriers, releases); } presentBarriers(stageSlot); @@ -346,16 +342,25 @@ cth::co::executor_task StageGraph::submission( stageSlot.epilogue.end(); } + // the queue of the stage and the presenter queue of one family: the submit signals the + // present semaphore, another family: the transfer to the presenter queue signals it + auto const family = queue.vk().familyIndex(); + for(auto const& image : stageSlot.presents) + if(image.presenter().queue().vk().familyIndex() == family) + info.binarySignals.emplace_back(image.presentSemaphore()); + slotSubmit.addCmdBuffers(info, withPrologue, withEpilogue); - co_await submitAndPresent(stageSlot, frameNumber); + co_await queue.submit(info); submitted = true; } // the submission goes on with the skip catch(...) { _submissions.store(std::current_exception()); } } + if(submitted) + co_await present(stageSlot, frameNumber); // a skip, also of a failed submit: the gpu waits of other stages and the waits in ~StageGraph() end - if(!submitted) { + else { // noexcept: a failed start of the skip submit leaves the slot unmarked, the waiters would // hang auto skip = [&]() noexcept { @@ -366,17 +371,15 @@ cth::co::executor_task StageGraph::submission( }(); co_await std::move(skip); - // the presents of the skip: dropped after the gpu finished it, the next acquire of each - // surface unacquires its image at once - if(!stageSlot.presents.empty()) { - try { co_await stageSlot.semaphore.wait(frameNumber); } - catch(...) { _submissions.store(std::current_exception()); } - stageSlot.presents.clear(); - } + // the skip waited for the waits of the stage: the spares wait for its signal + SemaphoreSubmitInfo const ready{.semaphore = stageSlot.semaphore, .value = frameNumber}; + for(auto& image : stageSlot.presents) + image.presenter().drop(std::move(image), ready); + stageSlot.presents.clear(); } - // the last use of the slot by the submission before the gpu wait: nextFrame() hands it out - // after it + // the last use of the slot by the submission, after the presents and the drops, before the + // gpu wait: nextFrame() hands the slot out after it stageSlot.submitDone.set(frameNumber); // nothing to free: no gpu wait, the submission ends @@ -491,156 +494,62 @@ void StageGraph::presentBarriers(dev::StageSlot& stageSlot) { auto& releases = stageSlot.presentReleases; releases.clear(); - for(auto const& present : stageSlot.presents) { - auto const presentFamily = present.queue().vk().familyIndex(); + for(auto const& image : stageSlot.presents) { + auto const presentFamily = image.presenter().queue().vk().familyIndex(); if(presentFamily == family) continue; - cvk::Image const& image = present.swapchainImage(); + cvk::Image const& vkImage = image.image(); releases.add( - image.get(), - image.aspectMask(), + vkImage.get(), + vkImage.aspectMask(), dev::release_half(PRESENT_STATE, PRESENT_STATE, family, presentFamily, 0) ); } } -cth::co::executor_task StageGraph::submitAndPresent( - dev::StageSlot& stageSlot, - uint64_t frameNumber -) { - auto& info = stageSlot.submitInfo; - auto& queue = *stageSlot.queue; - auto const family = queue.vk().familyIndex(); - auto& presents = stageSlot.presents; - auto& images = stageSlot.presentImages; - auto& results = stageSlot.presentResults; - auto& groups = stageSlot.presentGroups; - - // the images of one queue in a row, the queue of the stage first: its present follows the - // submit in one strand job - images.clear(); - groups.clear(); - auto const addGroup = [&](Queue& groupQueue) { - auto const first = images.size(); - for(auto const& present : presents) - if(&present.queue() == &groupQueue) - images.push_back(present.image()); - groups.push_back({.queue = groupQueue, .first = first, .count = images.size() - first}); - }; - auto const queueOf = [](dev::PendingPresent const& present) { return &present.queue(); }; - if(std::ranges::contains(presents, &queue, queueOf)) - addGroup(queue); - for(auto it = presents.begin(); it != presents.end(); ++it) { - auto* const queuePtr = &it->queue(); - // the first present of a queue opens its group - if(queuePtr != &queue && !std::ranges::contains(presents.begin(), it, queuePtr, queueOf)) - addGroup(*queuePtr); - } - results.assign(images.size(), VK_ERROR_UNKNOWN); - - // another queue of the family: the submit of the stage signals the present semaphores - for(auto const& group : groups) - if(&*group.queue != &queue && group.queue->vk().familyIndex() == family) - for(auto const& [swapchain, imageIdx] : span{images}.subspan(group.first, group.count)) - info.binarySignals.emplace_back(swapchain->presentSemaphore(imageIdx)); - - bool const ownGroup = !groups.empty() && &*groups.front().queue == &queue; - try { - if(ownGroup) { - auto const& own = groups.front(); - co_await queue.present( - info, - span{images}.subspan(own.first, own.count), - span{results}.subspan(own.first, own.count) - ); - } else - co_await queue.submit(info); - } - catch(...) { - // a failed submit marks nothing: the caller skips, the presents stay pending - if(!ownGroup || stageSlot.semaphore.submittedValue() < frameNumber) - throw; - // a failed present after the submit: the images resolve with their results, the surfaces - // get the error - groups.front().error = std::current_exception(); - } - if(ownGroup) - groups.front().presented = true; - - // the presents on other queues after the submit +cth::co::executor_task StageGraph::present(dev::StageSlot& stageSlot, uint64_t frameNumber) { + auto const family = stageSlot.queue->vk().familyIndex(); SemaphoreSubmitInfo const submitted{.semaphore = stageSlot.semaphore, .value = frameNumber}; - for(auto& group : groups) { - auto& groupQueue = *group.queue; - if(&groupQueue == &queue) + + for(auto& image : stageSlot.presents) { + auto& presenter = image.presenter(); + auto& presentQueue = presenter.queue(); + auto const presentFamily = presentQueue.vk().familyIndex(); + if(presentFamily == family) { + co_await presenter.present(std::move(image)); continue; + } + // another family: the presenter queue acquires the image, the transfer signals its present + // semaphore std::optional transferredOpt = std::nullopt; try { - // another family: the queue of the surfaces acquires the images, the transfer signals - // their present semaphores - auto const groupFamily = groupQueue.vk().familyIndex(); - if(groupFamily != family) { - cvk::Barrier acquire{}; - auto& signals = stageSlot.presentSignals; - signals.clear(); - for(auto const& present : presents) { - if(&present.queue() != &groupQueue) - continue; - cvk::Image const& image = present.swapchainImage(); - acquire.add( - image.get(), - image.aspectMask(), - dev::acquire_half(PRESENT_STATE, PRESENT_STATE, family, groupFamily, 0) - ); - auto const [swapchain, imageIdx] = present.image(); - signals.emplace_back(swapchain->presentSemaphore(imageIdx)); - } - std::array const waits{submitted}; - transferredOpt = co_await groupQueue.transfer(std::move(acquire), waits, signals); - } + cvk::Image const& vkImage = image.image(); + cvk::Barrier acquire{}; + acquire.add( + vkImage.get(), + vkImage.aspectMask(), + dev::acquire_half(PRESENT_STATE, PRESENT_STATE, family, presentFamily, 0) + ); + std::array const waits{submitted}; + std::array const signals{cvk::SemaphoreSubmitInfo{image.presentSemaphore()}}; + transferredOpt = co_await presentQueue.transfer(std::move(acquire), waits, signals); } - // a failed transfer drops the images of the queue - catch(...) { - _submissions.store(std::current_exception()); + // a failed transfer: the image goes back behind the submit that released it + catch(...) { _submissions.store(std::current_exception()); } + if(!transferredOpt.has_value()) { + presenter.drop(std::move(image), submitted); continue; } - // a failed present presented the images: they resolve with their results, the surfaces get - // the error - group.presented = true; - try { - co_await groupQueue.present( - span{images}.subspan(group.first, group.count), - span{results}.subspan(group.first, group.count) - ); - } - catch(...) { group.error = std::current_exception(); } + co_await presenter.present(std::move(image)); // the transfer waits for the semaphore of the slot: ~StageGraph() destroys it after the // submissions ended - if(transferredOpt.has_value()) { - try { co_await transferredOpt->semaphore->wait(transferredOpt->value); } - catch(...) { _submissions.store(std::current_exception()); } - } - } - - // each image of a group resolves with its result, in the order of the group - for(auto const& group : groups) { - if(!group.presented) - continue; - auto resultIdx = group.first; - for(auto& present : presents) - if(&present.queue() == &*group.queue) - present.present(results[resultIdx++], group.error); - } - - // the images of a failed transfer: dropped after the gpu finished the submit, the clear drops - // them - if(std::ranges::any_of(groups, [](auto const& group) { return !group.presented; })) { - try { co_await stageSlot.semaphore.wait(frameNumber); } + try { co_await transferredOpt->semaphore->wait(transferredOpt->value); } catch(...) { _submissions.store(std::current_exception()); } } - presents.clear(); + stageSlot.presents.clear(); } cth::co::executor_task> StageGraph::release(release_map_t releases) { diff --git a/jvk/src/graph/surface.cpp b/jvk/src/graph/surface.cpp index dc7fe4d3..b420eebd 100644 --- a/jvk/src/graph/surface.cpp +++ b/jvk/src/graph/surface.cpp @@ -4,34 +4,21 @@ #include "jvk/base/queue.hpp" #include "jvk/graph/stage.hpp" #include "jvk/graph/stage_graph.hpp" -#include "jvk/utility/exception.hpp" #include "cvk/base/core.hpp" #include "cvk/data/img/image.hpp" -#include "cvk/utility/vk_exceptions.hpp" -#include -#include -#include - -#include -#include #include +#include namespace jvk { -namespace { - cth::co::executor_task await_value(cth::co::counter_event const& event, uint64_t value) { - co_await event.wait(value); - } -} - Surface::Surface(Core const& core, Queue& queue, Config config) : _core{core}, _queue{queue}, _config{std::move(config)}, _surface{static_cast(core).instance()}, - _swapchain{core, queue.vk(), _surface} { Config::debug_check(_config); } + _swapchain{core, queue, _surface, _config.framesInFlight} { Config::debug_check(_config); } Surface::Surface(Core const& core, Queue& queue, Config config, cvk::Surface surface) : Surface{core, queue, std::move(config)} { create(std::move(surface)); } @@ -45,13 +32,9 @@ void Surface::create(cvk::Surface surface) { cvk::Core const& vkCore = *_core; try { - _acquireSemaphores.reserve(_config.framesInFlight); - for(uint32_t i = 0; i < _config.framesInFlight; ++i) - _acquireSemaphores.emplace_back(vkCore, cvk::create); - auto const extent = _surface.extent(vkCore.physicalDevice()); if(extent.width > 0 && extent.height > 0) - updateSwapchain(extent, nullptr); + updateSwapchain(extent, false); } catch(...) { destroy(); @@ -62,33 +45,8 @@ void Surface::create(cvk::Surface surface) { void Surface::destroy() { debug_check(*this); - // the submission of the present stage resolves the last image - if(_presentState.resolved.value() < _lastValue) - _core->executor().sync_wait(await_value(_presentState.resolved, _lastValue)); - - // the drop resolved after the gpu finished the stages of the image: - // VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786 - if(_presentState.dropped) { - // a failed unacquire does not stop the destruction - try { _swapchain.current().unacquire(std::array{_lastImageIdx}); } - catch(cvk::vk_result_exception const& e) { - JVK_STABLE_ERR( - true, - "failed to unacquire the swapchain image in destroy(), got {}", - e.vkResult() - ) {} - } - } - - _acquireSemaphores.clear(); _swapchain.optDestroy(); _surface.destroy(); - - // the counter starts at 0 again - _presentState = dev::PresentState{}; - _lastValue = 0; - _lastImageIdx = 0; - _acquireSemaphoreIdx = 0; } cth::co::executor_task> Surface::acquire( @@ -109,101 +67,54 @@ cth::co::executor_task> Surface::acquire( ) {} cvk::Core const& vkCore = *_core; - std::optional imageIdxOpt = std::nullopt; - auto const& acquireSemaphore = _acquireSemaphores[_acquireSemaphoreIdx]; - - //TEMP the try only after the resolve of the last image: the present state holds one image, a - // try while the last image presents needs the state of several images - if(_presentState.resolved.value() >= _lastValue) { - handleLastPresent(); + auto& graph = acquireStage.graph(); + std::optional imageOpt = std::nullopt; + // out of date -> the next round recreates the swapchain + bool outOfDate = false; + while(!imageOpt.has_value()) { auto const extent = _surface.extent(vkCore.physicalDevice()); if(extent.width == 0 || extent.height == 0) co_return std::nullopt; - // a recreation takes the fallback: in the strand it would hold up the submits - if(_swapchain.created() && !_presentState.outOfDate - && _swapchain.current().extent() == extent) { - auto const acquired = co_await _queue->tryAcquire(_swapchain, acquireSemaphore); - imageIdxOpt = acquired.imageIndex; - if(acquired.result == VK_ERROR_OUT_OF_DATE_KHR) - _presentState.outOfDate = true; - } - } - - // the fallback: no image from the try, a new extent or out of date - if(!imageIdxOpt.has_value()) { - // the last image first: then no present of the surface is pending, the blocking acquire - // and the recreation need no strand, a blocking acquire before that present would delay it - // (FIFO) - co_await _presentState.resolved.wait(_lastValue); - // outside the strand: the resolve of the last image orders the swapchain uses - co_await cth::co::executor{_queue->scheduler()}.schedule(); - handleLastPresent(); - - while(!imageIdxOpt.has_value()) { - auto const extent = _surface.extent(vkCore.physicalDevice()); - if(extent.width == 0 || extent.height == 0) - co_return std::nullopt; - updateSwapchain(extent, &acquireStage.graph()); - - // no image -> out of date, the next round recreates the swapchain - imageIdxOpt = _swapchain.acquire(acquireSemaphore).imageIndex; - if(!imageIdxOpt.has_value()) - _presentState.outOfDate = true; - } + updateSwapchain(extent, outOfDate); + imageOpt = co_await _swapchain.acquire(&graph); + outOfDate = !imageOpt.has_value(); } - auto const imageIdx = *imageIdxOpt; - auto& swapchain = _swapchain.current(); - SwapchainImage const image{ - .image = swapchain.image(imageIdx), - .view = swapchain.view(imageIdx), - .imageIdx = imageIdx, - .extent = swapchain.extent(), + auto& image = *imageOpt; + SwapchainImage const swapchainImage{ + .image = image.image(), + .view = image.view(), + .imageIdx = image.imageIdx(), + .extent = image.extent(), }; - _acquireSemaphoreIdx = (_acquireSemaphoreIdx + 1) % _config.framesInFlight; - _lastImageIdx = imageIdx; - auto const value = ++_lastValue; - - // the first barrier of the image chains with the wait for the acquire - acquireStage.await(acquireSemaphore, stages); - acquireStage.graph().assume( - *image.image, + + // the first barrier of the image chains with the wait + if(auto const* const semaphorePtr = + std::get_if>(&image.wait())) + acquireStage.await(**semaphorePtr, stages); + else { + auto ready = std::get(image.wait()); + ready.stages = stages; + acquireStage.await(ready); + } + graph.assume( + *swapchainImage.image, ImageState{.layout = VK_IMAGE_LAYOUT_UNDEFINED, .scope = {.stages = stages}} ); - // a failure drops the image at once, no stage submitted a use of it: the next acquire - // unacquires it - presentStage.present(dev::PendingPresent{_presentState, value, *_queue, swapchain, imageIdx}); - - co_return image; -} - -void Surface::handleLastPresent() { - // written before the resolve: the error of the present of the last image - if(_presentState.error != nullptr) - std::rethrow_exception(std::exchange(_presentState.error, nullptr)); - - // the drop resolved after the gpu finished the stages of the image: - // VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786 - if(std::exchange(_presentState.dropped, false)) - _swapchain.current().unacquire(std::array{_lastImageIdx}); + presentStage.present(std::move(image)); + co_return swapchainImage; } -void Surface::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { - if(_swapchain.created() && !_presentState.outOfDate && _swapchain.current().extent() == extent) +void Surface::updateSwapchain(VkExtent2D extent, bool outOfDate) { + if(!_swapchain.created()) { + _swapchain.create(swapchainConfig(), extent); return; - - if(_swapchain.created()) { - auto const& old = _swapchain.current(); - if(graphPtr != nullptr) - for(uint32_t imageIdx = 0; imageIdx < old.imageCount(); ++imageIdx) - graphPtr->erase(old.image(imageIdx)); + } + if(outOfDate || _swapchain.current().extent() != extent) _swapchain.recreate(extent); - } else - _swapchain.create(swapchainConfig(), extent); - _presentState.outOfDate = false; } Swapchain::Config Surface::swapchainConfig() const { diff --git a/jvk/src/graph/swapchain.cpp b/jvk/src/graph/swapchain.cpp index bd66ea4f..8f33671c 100644 --- a/jvk/src/graph/swapchain.cpp +++ b/jvk/src/graph/swapchain.cpp @@ -1,27 +1,55 @@ #include "jvk/graph/swapchain.hpp" +#include "jvk/base/queue.hpp" +#include "jvk/graph/stage_graph.hpp" + #include "cvk/base/core.hpp" -#include "cvk/base/queue/queue.hpp" -#include "cvk/render/sync/semaphore.hpp" #include "cvk/surface/surface.hpp" +#include "cvk/utility/vk_exceptions.hpp" #include +namespace jvk::dev { +PresentedSwapchain::PresentedSwapchain( + cvk::Core const& core, + Queue& presentQueue, + cvk::Surface const& surface, + cvk::Swapchain::Config config, + VkExtent2D extent, + cvk::Swapchain const* oldSwapchainPtr, + uint32_t framesInFlight +) : + swapchain{core, presentQueue.vk(), surface, std::move(config), extent, oldSwapchainPtr}, + presenter{presentQueue, swapchain, framesInFlight} {} +} + namespace jvk { Swapchain::Swapchain( cvk::Core const& core, - cvk::Queue const& presentQueue, - cvk::Surface const& surface + Queue& presentQueue, + cvk::Surface const& surface, + uint32_t framesInFlight ) : _core{core}, _presentQueue{presentQueue}, - _surface{surface} {} + _surface{surface}, + _framesInFlight{framesInFlight} { + CTH_CRITICAL(framesInFlight == 0, "framesInFlight must be > 0") {} +} void Swapchain::create(Config config, VkExtent2D extent) { optDestroy(); - _swapchains.emplace_back(*_core, *_presentQueue, *_surface, std::move(config), extent); + _swapchains.emplace_back( + *_core, + *_presentQueue, + *_surface, + std::move(config), + extent, + nullptr, + _framesInFlight + ); } void Swapchain::recreate(VkExtent2D extent) { @@ -29,7 +57,23 @@ void Swapchain::recreate(VkExtent2D extent) { auto const& old = current(); // emplace_back keeps the addresses of the other swapchains, a throw leaves the deque as it was - _swapchains.emplace_back(*_core, *_presentQueue, *_surface, old.config(), extent, &old); + try { + _swapchains.emplace_back( + *_core, + *_presentQueue, + *_surface, + old.config(), + extent, + &old, + _framesInFlight + ); + } + catch(cvk::vk_result_exception const&) { + // vkCreateSwapchainKHR() retired the old swapchain, also on a failure + _currentRetired = true; + throw; + } + _currentRetired = false; } void Swapchain::destroy() { @@ -38,14 +82,26 @@ void Swapchain::destroy() { // the oldest first: the retired swapchains end before the current one while(!_swapchains.empty()) _swapchains.pop_front(); + _currentRetired = false; } -cvk::Swapchain::Acquired Swapchain::acquire(cvk::Semaphore const& signal, uint64_t timeout) { +cth::co::executor_task> Swapchain::acquire( + StageGraph* graphPtr +) { debug_check(*this); - while(retired() != 0 && _swapchains.front().presented()) + while(retired() != 0 && _swapchains.front().presenter.finished()) { + // the gpu finished the uses of the images: a new image can get their handles + if(graphPtr != nullptr) { + auto const& retiredSwapchain = _swapchains.front().swapchain; + for(uint32_t imageIdx = 0; imageIdx < retiredSwapchain.imageCount(); ++imageIdx) + graphPtr->erase(retiredSwapchain.image(imageIdx)); + } _swapchains.pop_front(); + } - return current().acquire(signal, timeout); + if(_currentRetired) + co_return std::nullopt; + co_return co_await presenter().acquire(); } } diff --git a/jvk/tests/src/base/queue_test.cpp b/jvk/tests/src/base/queue_test.cpp index 4d0ba2e4..4220b86f 100644 --- a/jvk/tests/src/base/queue_test.cpp +++ b/jvk/tests/src/base/queue_test.cpp @@ -5,7 +5,6 @@ #include "jvk/data/buffer.hpp" #include "jvk/data/image.hpp" -#include "jvk/graph/swapchain.hpp" #include "cvk/base/core.hpp" #include "cvk/base/queue/submit_info.hpp" @@ -13,6 +12,7 @@ #include "cvk/render/sync/fence.hpp" #include "cvk/render/sync/semaphore.hpp" #include "cvk/render/sync/timeline_semaphore.hpp" +#include "cvk/surface/swapchain.hpp" #include "cvk/utility/vk_exceptions.hpp" #include @@ -549,7 +549,7 @@ JVK_TEST(Queue, skip_submit_marks_through_the_submit) { static_cast(semaphore).wait(1); } -JVK_TEST(Queue, present_submits_presents_and_marks) { +JVK_TEST(Queue, present_after_the_submit_of_the_present_semaphore) { test::Context const context{}; auto const surface = test::headless_surface(context.instance); std::optional coreOpt{}; @@ -557,10 +557,9 @@ JVK_TEST(Queue, present_submits_presents_and_marks) { GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; auto& queue = core.queue(0); + auto const& executor = core.executor(); - Swapchain swapchain{core, queue.vk(), surface}; - swapchain.create({}, EXTENT); - auto& current = swapchain.current(); + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, EXTENT}; Semaphore const presented{core, cvk::create}; PrimaryCmdBuffer cmd{core, queue.vk().familyIndex(), cvk::create}; @@ -575,7 +574,7 @@ JVK_TEST(Queue, present_submits_presents_and_marks) { cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); cvk::Barrier barrier{}; barrier.add( - current.image(*imageIdxOpt), + swapchain.image(*imageIdxOpt), cvk::ImageBarrierInfo{ .src = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, .dst = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, @@ -586,143 +585,24 @@ JVK_TEST(Queue, present_submits_presents_and_marks) { barrier.execute(cmd); cmd.end(); - std::array const images{PresentImage{.swapchain = current, .imageIdx = *imageIdxOpt}}; - std::array results{VK_ERROR_UNKNOWN}; - core.executor().sync_wait( - queue.present( + // the submit signals the present semaphore, the present follows in its own job + executor.sync_wait( + queue.submit( { .cmdBuffers = {cmd}, .binaryWaits = {acquired}, .signals = {{.semaphore = presented, .value = value}}, - }, - images, - results + .binarySignals = {swapchain.presentSemaphore(*imageIdxOpt)}, + } ) ); - - EXPECT_TRUE(results[0] == VK_SUCCESS || results[0] == VK_SUBOPTIMAL_KHR) - << "present result: " << results[0]; EXPECT_EQ(presented.submittedValue(), value); - // the acquire semaphore goes after the gpu waited for it - static_cast(presented).wait(value); - } -} - -JVK_TEST(Queue, present_of_two_swapchains_in_one_call) { - test::Context const context{}; - auto const firstSurface = test::headless_surface(context.instance); - auto const secondSurface = test::headless_surface(context.instance); - std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, firstSurface)) - GTEST_SKIP() << "no device presents to a headless surface"; - auto& core = *coreOpt; - auto& queue = core.queue(0); - - Swapchain first{core, queue.vk(), firstSurface}; - first.create({}, EXTENT); - Swapchain second{core, queue.vk(), secondSurface}; - second.create({}, EXTENT); - Semaphore const presented{core, cvk::create}; - - // one submit transitions both images, one vkQueuePresentKHR() presents both - cvk::Semaphore const firstAcquired{core, cvk::create}; - cvk::Semaphore const secondAcquired{core, cvk::create}; - auto const firstIdxOpt = first.acquire(firstAcquired).imageIndex; - auto const secondIdxOpt = second.acquire(secondAcquired).imageIndex; - ASSERT_TRUE(firstIdxOpt.has_value()); - ASSERT_TRUE(secondIdxOpt.has_value()); - - PrimaryCmdBuffer cmd{core, queue.vk().familyIndex(), cvk::create}; - cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); - cvk::Barrier barrier{}; - for(auto const& [swapchainPtr, imageIdx] : - std::array{std::pair{&first, *firstIdxOpt}, std::pair{&second, *secondIdxOpt}}) - barrier.add( - swapchainPtr->current().image(imageIdx), - cvk::ImageBarrierInfo{ - .src = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, - .dst = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, - .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, - } - ); - barrier.execute(cmd); - cmd.end(); - - std::array const images{ - PresentImage{.swapchain = first.current(), .imageIdx = *firstIdxOpt}, - PresentImage{.swapchain = second.current(), .imageIdx = *secondIdxOpt}, - }; - std::array results{VK_ERROR_UNKNOWN, VK_ERROR_UNKNOWN}; - core.executor().sync_wait( - queue.present( - { - .cmdBuffers = {cmd}, - .binaryWaits = {firstAcquired, secondAcquired}, - .signals = {{.semaphore = presented, .value = 1}}, - }, - images, - results - ) - ); + auto const result = executor.sync_wait(queue.present(swapchain, *imageIdxOpt)); - for(auto const result : results) EXPECT_TRUE(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) << "present result: " << result; - static_cast(presented).wait(1); -} - -JVK_TEST(Queue, present_without_a_submit_after_the_submit_of_the_present_semaphore) { - test::Context const context{}; - auto const surface = test::headless_surface(context.instance); - std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface)) - GTEST_SKIP() << "no device presents to a headless surface"; - auto& core = *coreOpt; - auto& queue = core.queue(0); - - Swapchain swapchain{core, queue.vk(), surface}; - swapchain.create({}, EXTENT); - auto& current = swapchain.current(); - Semaphore const presented{core, cvk::create}; - - cvk::Semaphore const acquired{core, cvk::create}; - auto const imageIdxOpt = swapchain.acquire(acquired).imageIndex; - ASSERT_TRUE(imageIdxOpt.has_value()); - - PrimaryCmdBuffer cmd{core, queue.vk().familyIndex(), cvk::create}; - cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); - cvk::Barrier barrier{}; - barrier.add( - current.image(*imageIdxOpt), - cvk::ImageBarrierInfo{ - .src = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, - .dst = {.stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, - .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, - } - ); - barrier.execute(cmd); - cmd.end(); - - // the submit signals the present semaphore, the present follows without a submit - auto const& executor = core.executor(); - executor.sync_wait( - queue.submit( - { - .cmdBuffers = {cmd}, - .binaryWaits = {acquired}, - .signals = {{.semaphore = presented, .value = 1}}, - .binarySignals = {current.presentSemaphore(*imageIdxOpt)}, - } - ) - ); - std::array const images{PresentImage{.swapchain = current, .imageIdx = *imageIdxOpt}}; - std::array results{VK_ERROR_UNKNOWN}; - executor.sync_wait(queue.present(images, results)); - - EXPECT_TRUE(results[0] == VK_SUCCESS || results[0] == VK_SUBOPTIMAL_KHR) - << "present result: " << results[0]; - static_cast(presented).wait(1); + // the acquire semaphore goes after the gpu waited for it + static_cast(presented).wait(value); + } } } diff --git a/jvk/tests/src/graph/surface_test.cpp b/jvk/tests/src/graph/surface_test.cpp index 38f7d225..2628448c 100644 --- a/jvk/tests/src/graph/surface_test.cpp +++ b/jvk/tests/src/graph/surface_test.cpp @@ -7,7 +7,6 @@ #include "jvk/base/queue.hpp" #include "jvk/data/image.hpp" #include "jvk/graph/stage_graph.hpp" -#include "jvk/graph/swapchain.hpp" #include "jvk/sync/semaphore.hpp" #include "cvk/base/physical_device.hpp" @@ -450,7 +449,7 @@ JVK_TEST(Surface, frame_loop_clears_and_presents) { } } -JVK_TEST(Surface, destroy_waits_for_the_present_of_the_last_image) { +JVK_TEST(Surface, destroy_after_the_graph_of_the_stages) { test::Context const context{}; auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; @@ -593,7 +592,7 @@ JVK_TEST(Surface, recreation_retains_the_multisampled_target_of_the_old_extent) EXPECT_EQ(present_msaa_frame(core, graph, surface, msaaOpt).extent, (VkExtent2D{48, 40})); } -JVK_TEST(Surface, acquire_waits_for_the_present_before) { +JVK_TEST(Surface, acquire_does_not_wait_for_the_present_before) { test::Context const context{}; auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; @@ -607,41 +606,37 @@ JVK_TEST(Surface, acquire_waits_for_the_present_before) { Semaphore const gate{core, cvk::create}; auto& first = next_frame(core, graph).stage(0); - present_behind_gate(core, first, surface, gate); + auto const firstImage = present_behind_gate(core, first, surface, gate); - // the submission of the first frame waits for the mark of the gate, the next acquire for its - // present + // the submission of the first frame waits for the mark of the gate: its present is pending, + // the next acquire gives another image at once auto& second = next_frame(core, graph).stage(0); + std::optional secondImageOpt{}; std::binary_semaphore acquiredSignal{0}; - size_t acquiredImages = 0; std::jthread frame{ [&] { - auto const image = acquire(core, surface, second); - acquiredImages = acquired_images(tracker, surface); + secondImageOpt = acquire(core, surface, second); acquiredSignal.release(); - EXPECT_TRUE(image); - auto const primary = second.begin(); - if(image) - clear(*primary, *image); } }; - - EXPECT_FALSE(acquiredSignal.try_acquire_for(std::chrono::milliseconds{50})); + EXPECT_TRUE(acquiredSignal.try_acquire_for(TIMEOUT)); + EXPECT_EQ(acquired_images(tracker, surface), 2); // the signal before the mark: the present waits for no signal that is not submitted host_signal(gate, 1); gate.markSubmitted(1); - EXPECT_TRUE(acquiredSignal.try_acquire_for(TIMEOUT)); frame.join(); - // the first image is presented - EXPECT_EQ(acquiredImages, 1); - - wait(core, second); + ASSERT_TRUE(secondImageOpt.has_value()); + EXPECT_NE(secondImageOpt->imageIdx, firstImage.imageIdx); + { + auto const primary = second.begin(); + clear(*primary, *secondImageOpt); + } present_frame(core, graph, surface); } -JVK_TEST(Surface, recreation_retires_the_old_swapchain_until_its_presents_ended) { +JVK_TEST(Surface, recreation_retires_the_old_swapchain_until_its_presenter_finished) { test::Context const context{}; std::atomic windowExtent{VkExtent2D{32, 32}}; auto windowSurface = test::headless_surface( @@ -658,18 +653,19 @@ JVK_TEST(Surface, recreation_retires_the_old_swapchain_until_its_presents_ended) EXPECT_EQ(present_frame(core, graph, surface).extent, (VkExtent2D{32, 32})); - // the new extent recreates the swapchain, the old one stays until its presents ended + // the new extent recreates the swapchain, the old one stays until its presenter finished windowExtent = VkExtent2D{48, 40}; EXPECT_EQ(present_frame(core, graph, surface).extent, (VkExtent2D{48, 40})); EXPECT_LE(surface.swapchain().retired(), 1); - // a later acquire destroys the retired swapchain once its presents ended, the bound only ends a broken loop + // a later acquire destroys the retired swapchain once its presenter finished, the bound only + // ends a broken loop for(size_t i = 0; i < 16 && surface.swapchain().retired() != 0; ++i) present_frame(core, graph, surface); EXPECT_EQ(surface.swapchain().retired(), 0); } -JVK_TEST(Surface, next_acquire_after_a_skipped_stage_unacquires_the_image) { +JVK_TEST(Surface, skipped_stage_drops_the_image_for_the_next_acquire) { test::Context const context{}; auto windowSurface = test::headless_surface(context.instance); std::optional coreOpt{}; @@ -679,14 +675,17 @@ JVK_TEST(Surface, next_acquire_after_a_skipped_stage_unacquires_the_image) { AcquireTracker const tracker{core}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; + // one frame slot: the next frame waits for the submission of the skip, its drop included + StageGraph graph{core, {.stages = {{.queueIdx = 0}}, .frameSlots = 1}}; // Stage::begin() before the acquire works too auto& stage = next_frame(core, graph).stage(0); + uint32_t imageIdx = 0; { auto const primary = stage.begin(); auto const image = acquire(core, surface, stage); ASSERT_TRUE(image.has_value()); + imageIdx = image->imageIdx; clear(*primary, *image); // the skip discards the recording, waits for the acquire semaphore, drops the image @@ -695,11 +694,12 @@ JVK_TEST(Surface, next_acquire_after_a_skipped_stage_unacquires_the_image) { EXPECT_EQ(stage.status(), Stage::Status::SKIPPED); EXPECT_EQ(acquired_images(tracker, surface), 1); - // at once: the acquire waits for the skip on the gpu before the unacquire, no validation error + // the dropped image comes first, it waits for the skip on the gpu: no validation error auto& next = next_frame(core, graph).stage(0); { auto const image = acquire(core, surface, next); ASSERT_TRUE(image.has_value()); + EXPECT_EQ(image->imageIdx, imageIdx); EXPECT_EQ(acquired_images(tracker, surface), 1); auto const primary = next.begin(); clear(*primary, *image); @@ -745,7 +745,8 @@ JVK_TEST(Surface, exception_in_the_recording_submits_and_presents_nothing) { AcquireTracker const tracker{core}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}, .frameSlots = 2}}; + // one frame slot: the next frame waits for the submission of the skip, its drop included + StageGraph graph{core, {.stages = {{.queueIdx = 0}}, .frameSlots = 1}}; Stage const* stagePtr = nullptr; uint32_t imageIdx = 0; @@ -773,6 +774,7 @@ JVK_TEST(Surface, exception_in_the_recording_submits_and_presents_nothing) { { auto const image = acquire(core, surface, stage); ASSERT_TRUE(image.has_value()); + EXPECT_EQ(image->imageIdx, imageIdx); EXPECT_EQ(acquired_images(tracker, surface), 1); auto const primary = stage.begin(); clear(*primary, *image); @@ -848,7 +850,8 @@ JVK_TEST(Surface, failed_present_arrives_at_the_next_acquire_and_not_at_next_fra auto& core = *coreOpt; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; + // one frame slot: the next frame waits for the present of the frame before + StageGraph graph{core, {.stages = {{.queueIdx = 0}}, .frameSlots = 1}}; // the core reads the device table at each call: the presents report a lost surface until the // restore @@ -858,7 +861,7 @@ JVK_TEST(Surface, failed_present_arrives_at_the_next_acquire_and_not_at_next_fra present_frame(core, graph, surface); auto& stage = next_frame(core, graph).stage(0); - // the acquire waits for the present of the last image, then rethrows its error + // the acquire rethrows the error of the present before try { [[maybe_unused]] auto const image = acquire(core, surface, stage); ADD_FAILURE() << "the acquire must rethrow the error of the present"; @@ -933,23 +936,29 @@ JVK_TEST(Surface, skipped_present_stage_drops_the_image) { AcquireTracker const tracker{core}; Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; - StageGraph graph{core, scene_and_ui()}; + // one frame slot: the next frame waits for the submission of the skip, its drop included + auto config = scene_and_ui(); + config.frameSlots = 1; + StageGraph graph{core, std::move(config)}; auto& frame = next_frame(core, graph); + uint32_t imageIdx = 0; { auto const image = acquire(core, surface, frame[SCENE], frame[UI]); ASSERT_TRUE(image.has_value()); + imageIdx = image->imageIdx; auto const scene = frame[SCENE].begin(); clear(*scene, *image); } frame[UI].skip(); EXPECT_EQ(acquired_images(tracker, surface), 1); - // the next acquire waits for the skip on the gpu, then unacquires the image + // the dropped image comes first, it waits for the skip of the ui stage on the gpu auto& next = next_frame(core, graph); { auto const image = acquire(core, surface, next[SCENE], next[UI]); ASSERT_TRUE(image.has_value()); + EXPECT_EQ(image->imageIdx, imageIdx); EXPECT_EQ(acquired_images(tracker, surface), 1); auto const scene = next[SCENE].begin(); clear(*scene, *image); @@ -985,7 +994,7 @@ JVK_TEST(Surface, exception_in_the_present_stage_drops_the_image) { } catch(test_exception const&) {} - // the scope skipped the ui stage, the skip drops the image, the next acquire unacquires it + // the scope skipped the ui stage, the skip drops the image, a later acquire gives it back EXPECT_EQ(frame[UI].status(), Stage::Status::SKIPPED); present_scene_and_ui(core, graph, surface); present_scene_and_ui(core, graph, surface); @@ -1027,48 +1036,6 @@ JVK_TEST(Surface, two_surfaces_present_after_one_stage) { } } -JVK_TEST(Surface, try_acquire_in_the_strand_gives_images_until_not_ready) { - test::Context const context{}; - auto windowSurface = test::headless_surface(context.instance); - std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, windowSurface)) - GTEST_SKIP() << "no device presents to a headless surface"; - auto& core = *coreOpt; - auto& queue = core.queue(0); - cvk::Core const& vk = core; - - Swapchain swapchain{vk, queue.vk(), windowSurface}; - swapchain.create({}, test::HEADLESS_EXTENT); - auto const imageCount = swapchain.current().imageCount(); - - // one acquire semaphore per try, one more than the images: the last try finds no image - std::vector signals{}; - for(uint32_t i = 0; i <= imageCount; ++i) - signals.emplace_back(vk, cvk::create); - std::vector acquired{}; - VkResult last = VK_SUCCESS; - for(auto const& signal : signals) { - auto const result = core.executor().sync_wait(queue.tryAcquire(swapchain, signal)); - if(!result.imageIndex.has_value()) { - last = result.result; - break; - } - acquired.push_back(*result.imageIndex); - } - EXPECT_FALSE(acquired.empty()); - EXPECT_LE(acquired.size(), imageCount); - EXPECT_EQ(last, VK_NOT_READY); - - // the acquire semaphores signal: a submit waits for them before the unacquire and their - // destruction - SubmitInfo info{}; - for(size_t i = 0; i < acquired.size(); ++i) - info.binaryWaits.emplace_back(signals[i]); - core.executor().sync_wait(queue.submit(info)); - queue.waitIdle(); - swapchain.current().unacquire(acquired); -} - JVK_TEST(Surface, present_queue_of_the_same_family) { constexpr size_t FRAMES = 4; test::Context const context{}; diff --git a/jvk/tests/src/graph/swapchain_test.cpp b/jvk/tests/src/graph/swapchain_test.cpp index 3e0ed241..82eaecaa 100644 --- a/jvk/tests/src/graph/swapchain_test.cpp +++ b/jvk/tests/src/graph/swapchain_test.cpp @@ -6,9 +6,6 @@ #include "jvk/base/core.hpp" #include "jvk/base/queue.hpp" -#include "cvk/base/queue/queue.hpp" -#include "cvk/render/sync/fence.hpp" -#include "cvk/render/sync/semaphore.hpp" #include "cvk/utility/vk_exceptions.hpp" #include @@ -48,26 +45,38 @@ namespace { return true; } - /** the `vkGetFenceStatus()` of the device table before `unsignaled_fence_status()` */ + /** the functions of the device table before the hooks */ PFN_vkGetFenceStatus realGetFenceStatus = nullptr; + PFN_vkCreateSwapchainKHR realCreateSwapchain = nullptr; VKAPI_ATTR VkResult VKAPI_CALL unsignaled_fence_status(VkDevice, VkFence) { return VK_NOT_READY; } + VKAPI_ATTR VkResult VKAPI_CALL failing_create_swapchain( + VkDevice, + VkSwapchainCreateInfoKHR const*, + VkAllocationCallbacks const*, + VkSwapchainKHR* + ) { + return VK_ERROR_OUT_OF_HOST_MEMORY; + } + + /** + * the device table of the core, it reads the table at each call + */ + [[nodiscard]] VolkDeviceTable& device_table(Core const& core) { + return *const_cast(static_cast(core).functions()); + } + /** - * acquires an image of the current swapchain - * @return the image index, the semaphore of the acquire is waited for + * acquires an image of the current presenter, without a graph */ - [[nodiscard]] uint32_t acquire(Core const& core, Swapchain& swapchain) { - cvk::Semaphore const acquired{core, cvk::create}; - auto const [result, index] = swapchain.acquire(acquired); - EXPECT_TRUE(index.has_value()) << "acquire result: " << result; - - cvk::Fence const fence{core, cvk::create}; - core.queue(0).vk().submit({.waits = {acquired}}, &fence); - fence.wait(); - return index.value_or(0); + [[nodiscard]] std::optional acquire( + Core const& core, + Swapchain& swapchain + ) { + return core.executor().sync_wait(swapchain.acquire(nullptr)); } } @@ -79,15 +88,19 @@ JVK_TEST(Swapchain, recreate_retires_the_current_swapchain) { GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; - Swapchain swapchain{core, core.queue(0).vk(), surface}; + Swapchain swapchain{core, core.queue(0), surface, 2}; EXPECT_FALSE(swapchain.created()); swapchain.create({}, EXTENT); auto const* old = &swapchain.current(); + auto const* oldPresenter = &swapchain.presenter(); + EXPECT_EQ(&oldPresenter->swapchain(), old); + EXPECT_EQ(oldPresenter->framesInFlight(), 2); swapchain.recreate({32, 32}); EXPECT_EQ(swapchain.retired(), 1); EXPECT_NE(&swapchain.current(), old); + EXPECT_EQ(&swapchain.presenter().swapchain(), &swapchain.current()); EXPECT_EQ(swapchain.current().extent().width, 32); // the address of the retired swapchain stays EXPECT_TRUE(old->created()); @@ -101,26 +114,66 @@ JVK_TEST(Swapchain, acquire_destroys_the_finished_retired_swapchains) { GTEST_SKIP() << "no device presents to a headless surface"; auto& core = *coreOpt; - Swapchain swapchain{core, core.queue(0).vk(), surface}; + Swapchain swapchain{core, core.queue(0), surface, 2}; swapchain.create({}, EXTENT); - swapchain.current().unacquire(std::array{acquire(core, swapchain)}); + + // a spare of the retired presenter: it finished, its destruction releases the spare + auto oldImageOpt = acquire(core, swapchain); + ASSERT_TRUE(oldImageOpt.has_value()); + swapchain.presenter().drop(std::move(*oldImageOpt)); swapchain.recreate({32, 32}); EXPECT_EQ(swapchain.retired(), 1); - // the present fences count as unsignaled: the presents of the retired swapchain did not end + // the present fences count as unsignaled: the retired presenter did not finish { - cvk::Core const& vk = core; - auto& table = *const_cast(vk.functions()); + auto& table = device_table(core); realGetFenceStatus = std::exchange(table.vkGetFenceStatus, unsignaled_fence_status); - swapchain.current().unacquire(std::array{acquire(core, swapchain)}); + auto imageOpt = acquire(core, swapchain); table.vkGetFenceStatus = realGetFenceStatus; + ASSERT_TRUE(imageOpt.has_value()); + swapchain.presenter().drop(std::move(*imageOpt)); } EXPECT_EQ(swapchain.retired(), 1); - swapchain.current().unacquire(std::array{acquire(core, swapchain)}); + auto imageOpt = acquire(core, swapchain); + ASSERT_TRUE(imageOpt.has_value()); EXPECT_EQ(swapchain.retired(), 0); + swapchain.presenter().drop(std::move(*imageOpt)); swapchain.destroy(); EXPECT_FALSE(swapchain.created()); } + +JVK_TEST(Swapchain, failed_recreate_gives_no_image_until_the_next_recreate) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + + Swapchain swapchain{core, core.queue(0), surface, 2}; + swapchain.create({}, EXTENT); + + // the old swapchain counts as retired: no acquire on it + { + auto& table = device_table(core); + realCreateSwapchain = std::exchange(table.vkCreateSwapchainKHR, failing_create_swapchain); + try { + swapchain.recreate({32, 32}); + ADD_FAILURE() << "the recreate must throw"; + } + catch(cvk::vk_result_exception const& e) { + EXPECT_EQ(e.vkResult(), VK_ERROR_OUT_OF_HOST_MEMORY); + } + table.vkCreateSwapchainKHR = realCreateSwapchain; + } + EXPECT_EQ(swapchain.retired(), 0); + EXPECT_FALSE(acquire(core, swapchain).has_value()); + + swapchain.recreate({32, 32}); + auto imageOpt = acquire(core, swapchain); + ASSERT_TRUE(imageOpt.has_value()); + swapchain.presenter().drop(std::move(*imageOpt)); +} } From dd6e0db7c8b88b3e8838a5ac02350ea1b534f119 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:01:16 +0100 Subject: [PATCH 66/68] cvk, jvk: the presenter tracks the pending present fences, cvk waits on none - cvk::Swapchain keeps the present fences but waits on none: present() resets, destroy() has @pre no fence pending - cvk::Swapchain::presented() and WaitingFence removed: no wait or throw in a destructor on VK_ERROR_DEVICE_LOST - jvk::Presenter: a fence is pending once its present is enqueued, VK_SUCCESS, VK_SUBOPTIMAL_KHR or a rejected but enqueued error - a present that was not enqueued leaves no fence pending: the next present of the image and the teardown do not hang - Presenter::waitPresents(), jvk::Swapchain::destroy() waits for the pending fences --- cvk/incl/cvk/surface/swapchain.hpp | 50 ++++------ cvk/src/surface/swapchain.cpp | 25 ++--- cvk/tests/src/surface/swapchain_test.cpp | 84 ++++++++++++++--- jvk/incl/jvk/graph/presenter.hpp | 41 +++++++- jvk/incl/jvk/graph/swapchain.hpp | 13 ++- jvk/src/graph/presenter.cpp | 115 +++++++++++++++++++---- jvk/src/graph/swapchain.cpp | 14 ++- jvk/tests/src/base/queue_test.cpp | 4 +- jvk/tests/src/graph/presenter_test.cpp | 85 +++++++++++++++++ jvk/tests/src/graph/swapchain_test.cpp | 31 ++---- 10 files changed, 350 insertions(+), 112 deletions(-) diff --git a/cvk/incl/cvk/surface/swapchain.hpp b/cvk/incl/cvk/surface/swapchain.hpp index e5407a5f..313a7b5d 100644 --- a/cvk/incl/cvk/surface/swapchain.hpp +++ b/cvk/incl/cvk/surface/swapchain.hpp @@ -118,10 +118,12 @@ class Swapchain { void create(VkExtent2D extent, Swapchain const* oldSwapchainPtr = nullptr); /** - * waits for the present fences, destroys the swapchain and forgets + * destroys the swapchain and forgets * @details destroys the views, present semaphores and present fences, the swapchain destroys its images * @pre `created()` - * @pre no present semaphore is signaled without its present + * @pre no present fence is pending: the presentation engine took its reference to the payloads + * @pre the submits that signal the present semaphores completed: + * VUID-vkDestroySemaphore-semaphore-05149 */ void destroy(); @@ -134,10 +136,10 @@ class Swapchain { } /** - * waits for the present fences, releases ownership, returns the state and forgets + * releases ownership, returns the state and forgets * @details destroys the views, present semaphores and present fences * @pre `created()` - * @pre no present semaphore is signaled without its present + * @pre the preconditions of `destroy()` for the present fences and semaphores */ State release(); @@ -157,10 +159,11 @@ class Swapchain { /** * presents the image once its present semaphore signals * @return `VK_SUCCESS`, `VK_SUBOPTIMAL_KHR` or `VK_ERROR_OUT_OF_DATE_KHR` - * @details waits for the present fence of the last present of the image first, the present - * signals it again, see `presentFence()` + * @details resets the present fence of the image, the present signals it, see `presentFence()` * @details `VK_ERROR_OUT_OF_DATE_KHR` -> the present still waits for the semaphore * @pre the image is acquired + * @pre the present fence of the image is not pending: signaled, or reset by a present that was + * not enqueued, see `vkQueuePresentKHR()` * @pre a submit signals `presentSemaphore()` of the image * @throws cvk::vk_result_exception other result of `vkQueuePresentKHR()` */ @@ -191,13 +194,6 @@ class Swapchain { VkSurfaceCapabilitiesKHR const& ); - /** - * @return every present fence is signaled: the presentation engine finished the presents - * @details reads the fence status, one `vkGetFenceStatus()` per image - * @pre `created()` - */ - [[nodiscard]] bool presented() const; - [[nodiscard]] constexpr bool created() const { return static_cast(_handle); } [[nodiscard]] constexpr VkSwapchainKHR get() const { return _handle.get(); } [[nodiscard]] constexpr Core const& core() const { return _handle.core(); } @@ -245,16 +241,17 @@ class Swapchain { /** * @return the fence that the last present of the image signals, created signaled * @details exportable with `constants::OS_FENCE_HANDLE_TYPE` + * @details the swapchain waits on none of them: the caller knows which ones are pending * @pre `imageIndex < imageCount()` * @see `Fence::extractOsHandle()` */ [[nodiscard]] constexpr Fence const& presentFence(uint32_t imageIndex) const { - return _presentFences[imageIndex].fence; + return _presentFences[imageIndex]; } private: - // the element wrappers: = default moves of the swapchain tear down in the member order, the - // swapchain destroys its images itself, the present fences must signal before their destruction + // the element wrapper: = default moves of the swapchain tear down in the member order, the + // swapchain destroys its images itself /** * the destruction releases the image, it does not destroy it: the swapchain destroys its images */ @@ -272,21 +269,6 @@ class Swapchain { ReleasingImage& operator=(ReleasingImage&& other) noexcept = default; }; - /** the destruction waits for the present that signals the fence */ - struct WaitingFence { - explicit WaitingFence(Fence fence) : fence{std::move(fence)} {} - ~WaitingFence() { - if(fence.created()) - fence.wait(); - } - - Fence fence; - - // the user-declared destructor suppresses the implicit moves - WaitingFence(WaitingFence&& other) noexcept = default; - WaitingFence& operator=(WaitingFence&& other) noexcept = default; - }; - [[nodiscard]] std::pair pick(Config const&) const; void createImages(); @@ -297,9 +279,9 @@ class Swapchain { cth::ref_wrapper _surface; Config _config; - // the objects of the images before the handle, in the order of their teardown: = default moves wait for the - // presents, release the images, destroy the views and semaphores, then the swapchain - std::vector _presentFences{}; + // the objects of the images before the handle, in the order of their teardown: = default moves destroy the + // fences and semaphores, release the images, destroy the views, then the swapchain + std::vector _presentFences{}; std::vector _presentSemaphores{}; std::vector _views{}; std::vector _images{}; diff --git a/cvk/src/surface/swapchain.cpp b/cvk/src/surface/swapchain.cpp index ce678b59..80fd90bd 100644 --- a/cvk/src/surface/swapchain.cpp +++ b/cvk/src/surface/swapchain.cpp @@ -116,7 +116,7 @@ void Swapchain::create(VkExtent2D extent, Swapchain const* oldSwapchainPtr) { void Swapchain::destroy() { debug_check(*this); - // the teardown order of the members: the presents end, the images release, the swapchain destroys them + // the teardown order of the members: the images release, the swapchain destroys them _presentFences.clear(); _presentSemaphores.clear(); _views.clear(); @@ -174,9 +174,9 @@ Swapchain::Acquired Swapchain::acquire(Semaphore const& signal, uint64_t timeout VkResult Swapchain::present(uint32_t imageIndex) { debug_check(*this); - // signaled by the last present of the image or created signaled + // not pending: signaled by the last present of the image, created signaled or not enqueued auto const& fence = presentFence(imageIndex); - fence.waitReset(); + fence.reset(); auto const vkSwapchain = get(); auto const vkWaitSemaphore = presentSemaphore(imageIndex).get(); @@ -219,15 +219,6 @@ void Swapchain::unacquire(span imageIndices) { CVK_RESULT_STABLE_THROW(result != VK_SUCCESS, result, "failed to unacquire swapchain images") {} } -bool Swapchain::presented() const { - debug_check(*this); - - return std::ranges::all_of( - _presentFences, - [](WaitingFence const& presentFence) { return presentFence.fence.signaled(); } - ); -} - void destroy(DeviceTable table, VkSwapchainKHR vkSwapchain) { CTH_WARN(vkSwapchain == VK_NULL_HANDLE, "vkSwapchain invalid (VK_NULL_HANDLE)") {} @@ -292,12 +283,10 @@ void Swapchain::createImages() { for(uint32_t i = 0; i < count; ++i) { _presentSemaphores.emplace_back(core(), cvk::create); _presentFences.emplace_back( - Fence{ - core(), - cvk::create, - VK_FENCE_CREATE_SIGNALED_BIT, - constants::OS_FENCE_HANDLE_TYPE - } + core(), + cvk::create, + VK_FENCE_CREATE_SIGNALED_BIT, + constants::OS_FENCE_HANDLE_TYPE ); } } diff --git a/cvk/tests/src/surface/swapchain_test.cpp b/cvk/tests/src/surface/swapchain_test.cpp index b2df3b34..abd95d6c 100644 --- a/cvk/tests/src/surface/swapchain_test.cpp +++ b/cvk/tests/src/surface/swapchain_test.cpp @@ -19,7 +19,6 @@ #include #include #include -#include #include #include @@ -49,7 +48,7 @@ namespace { } /** - * acquires an image, clears it and presents it + * acquires an image, clears it and presents it, waits for its present fence * @return result of `Swapchain::present()` */ VkResult present_cleared_image(test::PresentContext const& context, Swapchain& swapchain) { @@ -107,10 +106,19 @@ namespace { ); auto const presented = swapchain.present(*index); fence.wait(); + // not pending afterwards: the next present of the image and the destruction need it + swapchain.presentFence(*index).wait(); return presented; } + /** + * reports a failure without an enqueue: nothing presents, the fence and the semaphore stay + */ + VKAPI_ATTR VkResult VKAPI_CALL unenqueued_present(VkQueue, VkPresentInfoKHR const*) { + return VK_ERROR_OUT_OF_HOST_MEMORY; + } + /** * waits for the acquire semaphore of an image that was not presented */ @@ -278,22 +286,74 @@ CVK_TEST(Swapchain, old_swapchain_presents_its_acquired_image) { ) << "present result: " << presented; fence.wait(); + // the destruction waits for no present fence + old.presentFence(*index).wait(); old.destroy(); EXPECT_EQ(present_cleared_image(context, swapchain), VK_SUCCESS); } -CVK_TEST(Swapchain, presented_once_the_presents_ended) { +CVK_TEST(Swapchain, present_fences_are_created_signaled) { test::PresentContext const context{}; Swapchain swapchain{context.core, context.queue(), context.surface(), {}, EXTENT}; - // the present fences are created signaled - EXPECT_TRUE(swapchain.presented()); + for(uint32_t i = 0; i < swapchain.imageCount(); ++i) + EXPECT_TRUE(swapchain.presentFence(i).signaled()); + // the present resets the fence of its image, the presentation engine signals it again EXPECT_EQ(present_cleared_image(context, swapchain), VK_SUCCESS); - // the headless surface completes presents at once, the bound only ends a broken loop - for(uint32_t i = 0; i < 1000 && !swapchain.presented(); ++i) - std::this_thread::sleep_for(std::chrono::milliseconds{1}); - EXPECT_TRUE(swapchain.presented()); + for(uint32_t i = 0; i < swapchain.imageCount(); ++i) + EXPECT_TRUE(swapchain.presentFence(i).signaled()); +} + +CVK_TEST(Swapchain, present_after_a_present_that_was_not_enqueued) { + test::PresentContext const context{}; + Swapchain swapchain{context.core, context.queue(), context.surface(), {}, EXTENT}; + Semaphore const acquired{context.core, create}; + auto const [result, index] = swapchain.acquire(acquired); + ASSERT_TRUE(index.has_value()); + + CmdPool const pool{context.core, test::pool_config(context.core), create}; + PrimaryCmdBuffer cmd{pool, create}; + cmd.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); + Barrier toPresent{}; + toPresent.addTransition( + swapchain.image(*index), + VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + VK_IMAGE_LAYOUT_UNDEFINED + ); + toPresent.execute(cmd); + cmd.end(); + Fence const fence{context.core, create}; + context.queue().submit( + { + .cmdBuffers = {cmd}, + .waits = {{acquired, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}}, + .signals = {swapchain.presentSemaphore(*index)}, + }, + &fence + ); + + // the core reads the device table at each call: the present fails without an enqueue + auto* const table = const_cast(context.core.functions()); + auto const realQueuePresent = std::exchange(table->vkQueuePresentKHR, unenqueued_present); + try { + static_cast(swapchain.present(*index)); + ADD_FAILURE() << "the present must throw"; + } + catch(vk_result_exception const& e) { EXPECT_EQ(e.vkResult(), VK_ERROR_OUT_OF_HOST_MEMORY); } + table->vkQueuePresentKHR = realQueuePresent; + + // the image stays acquired, its semaphore signaled, its fence reset and not pending + EXPECT_FALSE(swapchain.presentFence(*index).signaled()); + auto const presented = swapchain.present(*index); + EXPECT_TRUE(presented == VK_SUCCESS || presented == VK_SUBOPTIMAL_KHR) + << "present result: " << presented; + fence.wait(); + swapchain.presentFence(*index).wait(); + + // no wait in the destruction + swapchain.destroy(); + EXPECT_FALSE(swapchain.created()); } CVK_TEST(Swapchain, present_fences_are_exportable) { @@ -315,7 +375,7 @@ CVK_TEST(Swapchain, present_fences_are_exportable) { EXPECT_TRUE(fence.signaled()); } - // the presents and the destruction wait for the exported fences + // the presents after the export reset the fences, the presentation engine signals them again for(uint32_t frame = 0; frame < swapchain.imageCount() + 1; ++frame) EXPECT_EQ(present_cleared_image(context, swapchain), VK_SUCCESS); @@ -395,11 +455,11 @@ CVK_TEST(Swapchain, move_assignment_destroys_the_old_swapchain) { EXPECT_EQ(present_cleared_image(context, swapchain), VK_SUCCESS); } -CVK_TEST(Swapchain, move_assignment_over_a_swapchain_with_a_present_in_flight) { +CVK_TEST(Swapchain, move_assignment_over_a_swapchain_after_a_present) { test::PresentContext const context{}; auto const other = test::headless_surface(context.instance); Swapchain swapchain{context.core, context.queue(), context.surface(), {}, EXTENT}; - // the move assignment waits for the present fence, then destroys the swapchain + // the present fence signaled: the move assignment destroys the swapchain without a wait EXPECT_EQ(present_cleared_image(context, swapchain), VK_SUCCESS); Swapchain moved{context.core, context.queue(), other, {}, EXTENT}; diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/presenter.hpp index 20ebbe4c..76fa91ad 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -116,10 +117,19 @@ class Presenter { * - waits until every image acquired before is handed back: the presents follow the acquire * order * - waits for the end of a fallback of `acquire()` + * - waits for the present fence of the image while the last present of the image left it + * pending: the present resets it * - one `vkQueuePresentKHR()` in the strand of the queue, see `Queue::present()` * - ends after `vkQueuePresentKHR()` * - never throws: the next `acquire()` rethrows the first failure, * `VK_ERROR_OUT_OF_DATE_KHR` -> it returns `std::nullopt` + * @details the fence of the present: + * - pending once the present is enqueued: `VK_SUCCESS`, `VK_SUBOPTIMAL_KHR` and the rejected + * presents `VK_ERROR_OUT_OF_DATE_KHR`, `VK_ERROR_SURFACE_LOST_KHR`, + * `VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT`, `VK_ERROR_PRESENT_TIMING_QUEUE_FULL_EXT`, + * see `vkQueuePresentKHR()` + * - another failure enqueues nothing: the image stays acquired and its acquire semaphore + * held, `finished()` stays `false` * @pre the image is of this presenter * @pre the image is in `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` * @pre a submitted batch signals `AcquiredImage::presentSemaphore()`, after the uses of the @@ -149,13 +159,21 @@ class Presenter { /** * checks without a wait that the presenter has no work left * @return every `AcquiredImage` is handed back, no present is pending, every ready point is - * reached, every present fence of the swapchain is signaled + * reached, no present fence is pending, every present was enqueued * @pre no `acquire()` runs at the same time: a present of its image resets a present fence * @throws cvk::vk_result_exception result of `vkGetSemaphoreCounterValue()` or * `vkGetFenceStatus()` */ [[nodiscard]] bool finished() const; + /** + * blocks until no present fence of the swapchain is pending + * @details for the teardown: `cvk::Swapchain::destroy()` waits for no fence + * @pre no `present()` runs at the same time + * @throws cvk::vk_result_exception result of `vkWaitForFences()`, e.g. `VK_ERROR_DEVICE_LOST` + */ + void waitPresents(); + [[nodiscard]] constexpr Queue& queue() const { return *_queue; } [[nodiscard]] constexpr cvk::Swapchain& swapchain() const { return *_swapchain; } [[nodiscard]] constexpr uint32_t framesInFlight() const { @@ -222,7 +240,16 @@ class Presenter { */ [[nodiscard]] size_t awaitPresentFence(); - [[nodiscard]] bool reached(reuse_t const&) const; + /** + * @return the images whose present fence is pending, locks + */ + [[nodiscard]] std::vector pendingFences() const; + + /** + * blocks until the present fences of the images signaled, then counts them as not pending + * @pre no present of the images runs at the same time: it resets the fence + */ + void waitPresents(std::span imageIndices); /** * @return the failure of a present, `nullptr` -> none, the presenter forgets it @@ -269,6 +296,16 @@ class Presenter { cth::dt::flat_hash_set _handedBackAhead{}; /** acquired from the swapchain, not presented or released: the images of callers and spares */ uint32_t _acquiredImages = 0; + /** + * per image: an enqueued present left its fence pending, the fence did not signal since + * @details the swapchain resets the fence at the next present: the present waits for it first + */ + std::vector _pendingFences; + /** + * presents that failed without an enqueue: their images stay acquired, no end of the gpu work + * of their submits is known + */ + uint32_t _unenqueuedPresents = 0; uint64_t _presentsStarted = 0; uint64_t _fallbacks = 0; ///< count of the started fallbacks bool _fallback = false; ///< a fallback runs diff --git a/jvk/incl/jvk/graph/swapchain.hpp b/jvk/incl/jvk/graph/swapchain.hpp index 6f853d55..25e2c155 100644 --- a/jvk/incl/jvk/graph/swapchain.hpp +++ b/jvk/incl/jvk/graph/swapchain.hpp @@ -116,10 +116,15 @@ class Swapchain { /** * destroys every presenter and its swapchain and forgets - * @details the oldest first, the presenter before its swapchain + * @details + * - the oldest first, the presenter before its swapchain + * - waits for the pending present fences first, see `Presenter::waitPresents()` + * - a failed wait does not stop the destruction, e.g. `VK_ERROR_DEVICE_LOST` * @pre `created()` - * @pre the preconditions of `~Presenter()` and of `cvk::Swapchain::destroy()` for every - * swapchain + * @pre no `Presenter::present()` runs + * @pre the preconditions of `~Presenter()` for every presenter + * @pre the submits that signal the present semaphores completed, see + * `cvk::Swapchain::destroy()` */ void destroy(); @@ -133,7 +138,7 @@ class Swapchain { /** * destroys the finished retired swapchains, then acquires the next image of the current one - * @details finished: `Presenter::finished()`, from the oldest on + * @details finished: `Presenter::finished()`, from the oldest on: no present fence is pending * @details erases the images of a destroyed swapchain in the graph, see `StageGraph::erase()` * @details the current swapchain retired by a failed `recreate()` -> `std::nullopt` * @param graphPtr of the images, `nullptr` -> none diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index f0065000..20fc5763 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -11,7 +11,9 @@ #include #include +#include #include +#include #include @@ -34,13 +36,26 @@ namespace { [[nodiscard]] constexpr bool holds(auto const& variant) { return std::holds_alternative(variant); } + + /** + * @return the queue operations of the present are enqueued: its fence signals + * @details the rejected presents too: "the set of queue operations is still considered to be + * enqueued", see `vkQueuePresentKHR()` + */ + [[nodiscard]] constexpr bool enqueued(VkResult result) { + return result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR + || result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_ERROR_SURFACE_LOST_KHR + || result == VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT + || result == VK_ERROR_PRESENT_TIMING_QUEUE_FULL_EXT; + } } Presenter::Presenter(Queue& presentQueue, cvk::Swapchain& swapchain, uint32_t framesInFlight) : _queue{presentQueue}, _swapchain{swapchain}, _blockingAcquireLimit{blocking_acquire_limit(swapchain)}, - _reuses(framesInFlight, Free{}) { + _reuses(framesInFlight, Free{}), + _pendingFences(swapchain.imageCount(), false) { CTH_CRITICAL(framesInFlight == 0, "framesInFlight must be > 0") {} _acquireSemaphores.reserve(framesInFlight); @@ -121,14 +136,17 @@ cth::co::executor_task Presenter::present(AcquiredImage image) { // the images acquired before first: the presents follow the acquire order co_await _handedBack.wait(acquireNumber - 1); + bool fencePending = false; for(;;) { uint64_t fallbackValue = 0; { std::scoped_lock const lock{_mutex}; if(_fallback) fallbackValue = _fallbacks; - else + else { ++_presentsStarted; + fencePending = _pendingFences[imageIdx]; + } } if(fallbackValue == 0) break; @@ -137,14 +155,31 @@ cth::co::executor_task Presenter::present(AcquiredImage image) { VkResult result = VK_ERROR_UNKNOWN; std::exception_ptr error = nullptr; - try { result = co_await _queue->present(*_swapchain, imageIdx); } + try { + // the present resets the fence: the last present of the image signals it first + if(fencePending) + waitPresents(std::array{imageIdx}); + result = co_await _queue->present(*_swapchain, imageIdx); + } + catch(cvk::vk_result_exception const& e) { + result = e.vkResult(); + error = std::current_exception(); + } catch(...) { error = std::current_exception(); } std::scoped_lock const lock{_mutex}; - // a failed present counts too: nothing presents the image again - --_acquiredImages; - if(auto const* const semaphorePtr = std::get_if>(&wait)) - _reuses[semaphoreIdx(**semaphorePtr)] = Presented{imageIdx}; + if(enqueued(result)) { + // the present ends the acquire, its fence signals once the presentation engine has the + // references + _pendingFences[imageIdx] = true; + --_acquiredImages; + if(auto const* const semaphorePtr = + std::get_if>(&wait)) + _reuses[semaphoreIdx(**semaphorePtr)] = Presented{imageIdx}; + } else + // not enqueued: the image stays acquired, the acquire semaphore stays held, no end of the + // gpu work of its submit is known + ++_unenqueuedPresents; if(error != nullptr) { if(_error == nullptr) @@ -172,12 +207,17 @@ void Presenter::drop(AcquiredImage image, SemaphoreSubmitInfo ready) { bool Presenter::finished() const { std::vector readyPoints{}; + std::vector pendingIndices{}; { std::scoped_lock const lock{_mutex}; // a present hands back after vkQueuePresentKHR() - if(_handedBack.value() != _acquires) + if(_handedBack.value() != _acquires || _unenqueuedPresents != 0) return false; + for(uint32_t imageIdx = 0; imageIdx < _pendingFences.size(); ++imageIdx) + if(_pendingFences[imageIdx]) + pendingIndices.push_back(imageIdx); + for(auto const& reuse : _reuses) if(auto const* const readyPtr = std::get_if(&reuse)) readyPoints.push_back(*readyPtr); @@ -193,9 +233,14 @@ bool Presenter::finished() const { return ready.semaphore->gpuValue() >= ready.value; } ) - && _swapchain->presented(); + && std::ranges::all_of( + pendingIndices, + [this](uint32_t imageIdx) { return _swapchain->presentFence(imageIdx).signaled(); } + ); } +void Presenter::waitPresents() { waitPresents(pendingFences()); } + cth::co::executor_task Presenter::tryInStrand() { // the strand serializes the tries and the presents of the presenter, a try starts the fallback co_await _queue->executor().schedule(); @@ -273,8 +318,7 @@ cth::co::executor_task> Presenter::fallb else if(!spare) { // the presents before reach the presentation engine first, it can give their images // back: no present resets a fence during the fallback - for(uint32_t imageIdx = 0; imageIdx < _swapchain->imageCount(); ++imageIdx) - _swapchain->presentFence(imageIdx).wait(); + waitPresents(pendingFences()); acquiredOpt = _swapchain->acquire(_acquireSemaphores[*semaphoreIdxOpt], 0); } } @@ -309,15 +353,33 @@ cth::co::executor_task> Presenter::fallb std::optional Presenter::recycle() { std::vector reuses{}; + std::vector pendingFences{}; { std::scoped_lock const lock{_mutex}; auto const freeIt = std::ranges::find_if(_reuses, holds); if(freeIt != _reuses.end()) return static_cast(freeIt - _reuses.begin()); reuses = _reuses; + pendingFences = _pendingFences; } // no vulkan call behind the mutex, only the recycle frees a presented or dropped semaphore + std::vector signaledIndices{}; + auto const reached = [&](reuse_t const& reuse) { + if(auto const* const presentedPtr = std::get_if(&reuse)) { + auto const imageIdx = presentedPtr->imageIdx; + if(!pendingFences[imageIdx]) + return true; + if(!_swapchain->presentFence(imageIdx).signaled()) + return false; + signaledIndices.push_back(imageIdx); + return true; + } + if(auto const* const readyPtr = std::get_if(&reuse)) + return readyPtr->semaphore->gpuValue() >= readyPtr->value; + return false; + }; + std::optional semaphoreIdxOpt = std::nullopt; for(size_t i = 0; i < reuses.size(); ++i) if(reached(reuses[i])) { @@ -331,6 +393,9 @@ std::optional Presenter::recycle() { for(size_t i = 0; i < reuses.size(); ++i) if(holds(reuses[i])) _reuses[i] = Free{}; + // in the strand or the fallback: no present of the images reset the fences since the reads + for(auto const imageIdx : signaledIndices) + _pendingFences[imageIdx] = false; return semaphoreIdxOpt; } @@ -349,8 +414,9 @@ size_t Presenter::awaitPresentFence() { ) {} imageIdx = std::get(*presentedIt).imageIdx; } - // the fallback holds the presents back: no reset of the fence during the wait - _swapchain->presentFence(imageIdx).wait(); + // the fallback holds the presents back: no reset of the fence during the wait, a fence + // that is not pending is free at the next recycle + waitPresents(std::array{imageIdx}); } } @@ -359,12 +425,23 @@ std::exception_ptr Presenter::takeError() { return std::exchange(_error, nullptr); } -bool Presenter::reached(reuse_t const& reuse) const { - if(auto const* const presentedPtr = std::get_if(&reuse)) - return _swapchain->presentFence(presentedPtr->imageIdx).signaled(); - if(auto const* const readyPtr = std::get_if(&reuse)) - return readyPtr->semaphore->gpuValue() >= readyPtr->value; - return false; +std::vector Presenter::pendingFences() const { + std::scoped_lock const lock{_mutex}; + std::vector imageIndices{}; + for(uint32_t imageIdx = 0; imageIdx < _pendingFences.size(); ++imageIdx) + if(_pendingFences[imageIdx]) + imageIndices.push_back(imageIdx); + return imageIndices; +} + +void Presenter::waitPresents(std::span imageIndices) { + // no vulkan call behind the mutex + for(auto const imageIdx : imageIndices) + _swapchain->presentFence(imageIdx).wait(); + + std::scoped_lock const lock{_mutex}; + for(auto const imageIdx : imageIndices) + _pendingFences[imageIdx] = false; } auto Presenter::handOut(uint32_t imageIdx, wait_t wait) -> AcquiredImage { diff --git a/jvk/src/graph/swapchain.cpp b/jvk/src/graph/swapchain.cpp index 8f33671c..f1ec6a7f 100644 --- a/jvk/src/graph/swapchain.cpp +++ b/jvk/src/graph/swapchain.cpp @@ -2,6 +2,7 @@ #include "jvk/base/queue.hpp" #include "jvk/graph/stage_graph.hpp" +#include "jvk/utility/exception.hpp" #include "cvk/base/core.hpp" #include "cvk/surface/surface.hpp" @@ -80,8 +81,19 @@ void Swapchain::destroy() { debug_check(*this); // the oldest first: the retired swapchains end before the current one - while(!_swapchains.empty()) + while(!_swapchains.empty()) { + // the swapchain destroys its present fences without a wait, a failed wait does not stop + // the destruction: the device is lost + try { _swapchains.front().presenter.waitPresents(); } + catch(cvk::vk_result_exception const& e) { + JVK_STABLE_ERR( + true, + "failed to wait for the present fences in destroy(), got {}", + e.vkResult() + ) {} + } _swapchains.pop_front(); + } _currentRetired = false; } diff --git a/jvk/tests/src/base/queue_test.cpp b/jvk/tests/src/base/queue_test.cpp index 4220b86f..68278c6a 100644 --- a/jvk/tests/src/base/queue_test.cpp +++ b/jvk/tests/src/base/queue_test.cpp @@ -601,8 +601,10 @@ JVK_TEST(Queue, present_after_the_submit_of_the_present_semaphore) { EXPECT_TRUE(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) << "present result: " << result; - // the acquire semaphore goes after the gpu waited for it + // the acquire semaphore goes after the gpu waited for it, the next present of the image + // and the destruction need the present fence signaled static_cast(presented).wait(value); + swapchain.presentFence(*imageIdxOpt).wait(); } } } diff --git a/jvk/tests/src/graph/presenter_test.cpp b/jvk/tests/src/graph/presenter_test.cpp index e4f34067..4dc8f7dc 100644 --- a/jvk/tests/src/graph/presenter_test.cpp +++ b/jvk/tests/src/graph/presenter_test.cpp @@ -205,6 +205,13 @@ namespace { return Result; } + /** + * reports a failure without an enqueue: nothing presents, the fence and the semaphores stay + */ + VKAPI_ATTR VkResult VKAPI_CALL unenqueued_present(VkQueue, VkPresentInfoKHR const*) { + return VK_ERROR_OUT_OF_HOST_MEMORY; + } + /** count of the calls of `out_of_date_acquire()` */ std::atomic outOfDateAcquires = 0; @@ -649,6 +656,84 @@ JVK_TEST(Presenter, failed_present_arrives_once_at_the_next_acquire) { submits.present(presenter, std::move(*imageOpt)); } +JVK_TEST(Presenter, present_without_an_enqueue_leaves_no_fence_pending) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; + + { + PresentHook const hook{core, unenqueued_present}; + auto imageOpt = acquire(core, presenter); + ASSERT_TRUE(imageOpt.has_value()); + EXPECT_NO_THROW(submits.present(presenter, std::move(*imageOpt))); + } + + try { + [[maybe_unused]] auto const imageOpt = acquire(core, presenter); + ADD_FAILURE() << "the acquire must rethrow the failure of the present"; + } + catch(cvk::vk_result_exception const& e) { + EXPECT_EQ(e.vkResult(), VK_ERROR_OUT_OF_HOST_MEMORY); + } + + // the image stays acquired: the presenter has work left, no fence of it is pending + EXPECT_FALSE(presenter.finished()); + fencesHeld = false; + fenceWaits = 0; + { + auto& table = device_table(core); + Hook const wait{table.vkWaitForFences, releasing_fence_wait, realWaitForFences}; + presenter.waitPresents(); + } + EXPECT_EQ(fenceWaits, 0); + + // the other images still present, the teardown waits for no fence of the failed present + auto nextOpt = acquire(core, presenter); + ASSERT_TRUE(nextOpt.has_value()); + submits.present(presenter, std::move(*nextOpt)); + presenter.waitPresents(); +} + +JVK_TEST(Presenter, rejected_present_leaves_its_fence_pending) { + test::Context const context{}; + auto const surface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; + + // the presentation engine rejects the present: it is enqueued, its fence signals + { + PresentHook const hook{core, failing_present}; + auto imageOpt = acquire(core, presenter); + ASSERT_TRUE(imageOpt.has_value()); + submits.present(presenter, std::move(*imageOpt)); + } + + fencesHeld = false; + fenceWaits = 0; + { + auto& table = device_table(core); + Hook const wait{table.vkWaitForFences, releasing_fence_wait, realWaitForFences}; + presenter.waitPresents(); + } + EXPECT_EQ(fenceWaits, 1); + EXPECT_TRUE(presenter.finished()); +} + JVK_TEST(Presenter, out_of_date_present_gives_no_image_from_then_on) { test::Context const context{}; auto const surface = test::headless_surface(context.instance); diff --git a/jvk/tests/src/graph/swapchain_test.cpp b/jvk/tests/src/graph/swapchain_test.cpp index 82eaecaa..c744f9be 100644 --- a/jvk/tests/src/graph/swapchain_test.cpp +++ b/jvk/tests/src/graph/swapchain_test.cpp @@ -46,13 +46,8 @@ namespace { } /** the functions of the device table before the hooks */ - PFN_vkGetFenceStatus realGetFenceStatus = nullptr; PFN_vkCreateSwapchainKHR realCreateSwapchain = nullptr; - VKAPI_ATTR VkResult VKAPI_CALL unsignaled_fence_status(VkDevice, VkFence) { - return VK_NOT_READY; - } - VKAPI_ATTR VkResult VKAPI_CALL failing_create_swapchain( VkDevice, VkSwapchainCreateInfoKHR const*, @@ -116,30 +111,24 @@ JVK_TEST(Swapchain, acquire_destroys_the_finished_retired_swapchains) { Swapchain swapchain{core, core.queue(0), surface, 2}; swapchain.create({}, EXTENT); + auto& oldPresenter = swapchain.presenter(); - // a spare of the retired presenter: it finished, its destruction releases the spare + // an image of the retired presenter is not handed back: it did not finish auto oldImageOpt = acquire(core, swapchain); ASSERT_TRUE(oldImageOpt.has_value()); - swapchain.presenter().drop(std::move(*oldImageOpt)); swapchain.recreate({32, 32}); + auto firstOpt = acquire(core, swapchain); + ASSERT_TRUE(firstOpt.has_value()); EXPECT_EQ(swapchain.retired(), 1); - // the present fences count as unsignaled: the retired presenter did not finish - { - auto& table = device_table(core); - realGetFenceStatus = std::exchange(table.vkGetFenceStatus, unsignaled_fence_status); - auto imageOpt = acquire(core, swapchain); - table.vkGetFenceStatus = realGetFenceStatus; - ASSERT_TRUE(imageOpt.has_value()); - swapchain.presenter().drop(std::move(*imageOpt)); - } - EXPECT_EQ(swapchain.retired(), 1); - - auto imageOpt = acquire(core, swapchain); - ASSERT_TRUE(imageOpt.has_value()); + // handed back as a spare: the retired presenter finished, its destruction releases the spare + oldPresenter.drop(std::move(*oldImageOpt)); + auto secondOpt = acquire(core, swapchain); + ASSERT_TRUE(secondOpt.has_value()); EXPECT_EQ(swapchain.retired(), 0); - swapchain.presenter().drop(std::move(*imageOpt)); + swapchain.presenter().drop(std::move(*firstOpt)); + swapchain.presenter().drop(std::move(*secondOpt)); swapchain.destroy(); EXPECT_FALSE(swapchain.created()); } From c7a619b42748d0a8bf151f71af273bf7188d5d14 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:15:22 +0100 Subject: [PATCH 67/68] jvk, demo: presenting without the graph, Frame::acquire() is the bridge - Surface, jvk::Swapchain and Presenter know no graph and no stages - Presenter owns the ready points: one timeline semaphore per image, the value is the acquire number - the present stage signals the ready point in its submit and its skip, drop() takes no ready point - the graph erases the state of an image right before its present or drop, no erase at the retirement - Frame::acquire(Surface&, Stage&, Stage&): the surface acquire, the stage wait, the assume, Stage::present() - Surface::acquire() takes no stages and returns the AcquiredImage, the demos use frame.acquire() --- demo/cube/src/main.cpp | 3 +- demo/triangle/src/main.cpp | 6 +- jvk/incl/jvk/base/queue.hpp | 2 + jvk/incl/jvk/graph/frame.hpp | 48 ++++++++++ jvk/incl/jvk/graph/presenter.hpp | 52 +++++++---- jvk/incl/jvk/graph/stage.hpp | 11 +-- jvk/incl/jvk/graph/stage_graph.hpp | 19 ++-- jvk/incl/jvk/graph/surface.hpp | 52 ++--------- jvk/incl/jvk/graph/swapchain.hpp | 7 +- jvk/src/graph/frame.cpp | 55 ++++++++++++ jvk/src/graph/presenter.cpp | 12 +-- jvk/src/graph/stage_graph.cpp | 23 +++-- jvk/src/graph/surface.cpp | 56 ++---------- jvk/src/graph/swapchain.cpp | 14 +-- jvk/tests/src/graph/presenter_test.cpp | 26 +++--- jvk/tests/src/graph/surface_test.cpp | 120 +++++++++++++++++-------- jvk/tests/src/graph/swapchain_test.cpp | 16 ++-- 17 files changed, 308 insertions(+), 214 deletions(-) diff --git a/demo/cube/src/main.cpp b/demo/cube/src/main.cpp index 4a1629c4..6441edcc 100644 --- a/demo/cube/src/main.cpp +++ b/demo/cube/src/main.cpp @@ -560,7 +560,8 @@ cth::co::executor_task draw_frames( auto& ui = frame.stage(UI_STAGE_ID); // the scene stage waits for the acquire, the ui stage presents - auto const image = co_await surface.acquire( + auto const image = co_await frame.acquire( + surface, scene, ui, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT diff --git a/demo/triangle/src/main.cpp b/demo/triangle/src/main.cpp index 1ecb5da0..25933935 100644 --- a/demo/triangle/src/main.cpp +++ b/demo/triangle/src/main.cpp @@ -95,9 +95,11 @@ cth::co::executor_task draw_frames( ) { while(!window.shouldClose()) { window.pollEvents(); - auto& stage = (co_await graph.nextFrame()).stage(TRIANGLE_STAGE_ID); + auto& frame = co_await graph.nextFrame(); + auto& stage = frame.stage(TRIANGLE_STAGE_ID); - auto const image = co_await surface.acquire( + auto const image = co_await frame.acquire( + surface, stage, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT ); diff --git a/jvk/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index f627694d..65dfb162 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -154,6 +154,8 @@ class Queue { return cth::co::executor{_strand}; } + [[nodiscard]] constexpr Core const& core() const { return *_core; } + /** * @return the scheduler of the strand, for work of the queue outside the strand */ diff --git a/jvk/incl/jvk/graph/frame.hpp b/jvk/incl/jvk/graph/frame.hpp index ff7c9d5d..a93b4ab4 100644 --- a/jvk/incl/jvk/graph/frame.hpp +++ b/jvk/incl/jvk/graph/frame.hpp @@ -1,6 +1,10 @@ #pragma once #include "stage.hpp" +#include "surface.hpp" +#include + +#include #include #include @@ -44,6 +48,50 @@ class Frame { */ [[nodiscard]] Stage& operator[](size_t stageId) { return stage(stageId); } + /** + * acquires the next image of the surface for a stage that waits for it and a stage that + * presents it + * @details the image, see `Surface::acquire()` + * @details the acquire stage: + * - waits for `Presenter::AcquiredImage::wait()` with the stages, see `Stage::await()`: the + * acquire semaphore or the ready point of a dropped image + * - the state of the image in the graph: `VK_IMAGE_LAYOUT_UNDEFINED` with the wait stages, see + * `StageGraph::assume()`: the first barrier of the image chains with the wait + * @details the present stage holds the image until its submission presents or drops it, see + * `Stage::present()` + * @param surface of the image + * @param acquireStage waits for the acquire, the first use of the image + * @param presentStage presents the image after its submit + * @param stages pipeline stages of the acquire stage that wait for the acquire + * @return view of the image, `std::nullopt` -> surface extent `0`: no image, no wait, no + * present + * @pre `Stage::status()` of both stages is `UNSUBMITTED` + * @pre both stages belong to this frame + * @pre the present stage waits for every stage of the frame that uses the image, the acquire + * stage included, directly or through other stages, or is that stage, see `StageWait` + * @pre the preconditions of `Surface::acquire()` + * @throws std::exception the exceptions of `Surface::acquire()` + */ + [[nodiscard]] cth::co::executor_task> acquire( + Surface& surface, + Stage& acquireStage, + Stage& presentStage, + VkPipelineStageFlags2 stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT + ); + + /** + * acquires the next image of the surface for one stage that uses and presents it + * @details calls @ref acquire(Surface&, Stage&, Stage&, VkPipelineStageFlags2) with the stage + * for both + */ + [[nodiscard]] cth::co::executor_task> acquire( + Surface& surface, + Stage& stage, + VkPipelineStageFlags2 stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT + ) { + return acquire(surface, stage, stage, stages); + } + /** * @return number of the frame, the first frame is `StageGraph::firstFrameNumber()` */ diff --git a/jvk/incl/jvk/graph/presenter.hpp b/jvk/incl/jvk/graph/presenter.hpp index 76fa91ad..b1882a69 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -38,7 +38,8 @@ class Queue; * - `acquire()` hands out an `AcquiredImage`, `present()` or `drop()` hands it back * - the presents follow the acquire order * - a dropped image is a spare: the next `acquire()` hands it out first - * - owns `framesInFlight()` acquire semaphores + * - owns `framesInFlight()` acquire semaphores and one ready semaphore per image: the ready + * points of the drops * - thread safe: `acquire()`, `present()` and `drop()` from any thread * - the strand of the queue runs the vulkan calls of the swapchain, except the fallback of * `acquire()`: it excludes the presents and the tries of the presenter @@ -49,13 +50,13 @@ class Presenter { class AcquiredImage; /** - * wait of the first use of an image: its acquire semaphore or the ready point of a drop + * wait of the first use of an image: its acquire semaphore or the ready point of its drop */ using wait_t = std::variant, SemaphoreSubmitInfo>; // no base constructor and create(): the presenter has no wrap or release /** - * creates the acquire semaphores + * creates the acquire semaphores and the ready semaphores * @param presentQueue presents the images, its strand runs the tries and the presents * @param swapchain of the images * @param framesInFlight count of the acquire semaphores @@ -75,8 +76,8 @@ class Presenter { * @pre no `acquire()` and no `present()` is pending * @pre the ready points of the spares are reached: * VUID-VkReleaseSwapchainImagesInfoKHR-pImageIndices-07786 - * @pre the submits that wait for the acquire semaphores completed: - * VUID-vkDestroySemaphore-semaphore-05149 + * @pre the submits that wait for the acquire semaphores or signal the ready semaphores + * completed: VUID-vkDestroySemaphore-semaphore-05149 * @see `finished()` */ ~Presenter(); @@ -129,7 +130,8 @@ class Presenter { * `VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT`, `VK_ERROR_PRESENT_TIMING_QUEUE_FULL_EXT`, * see `vkQueuePresentKHR()` * - another failure enqueues nothing: the image stays acquired and its acquire semaphore - * held, `finished()` stays `false` + * held until the teardown, `finished()` stays `false`: these results are out of memory, + * device lost or unknown, practically fatal, the next `acquire()` rethrows the error * @pre the image is of this presenter * @pre the image is in `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` * @pre a submitted batch signals `AcquiredImage::presentSemaphore()`, after the uses of the @@ -138,23 +140,16 @@ class Presenter { [[nodiscard]] cth::co::executor_task present(AcquiredImage image); /** - * hands the image back without a present: the image becomes a spare - * @details the spare keeps `AcquiredImage::wait()` - * @pre the image is of this presenter - * @pre no submitted batch uses the image or waits for `AcquiredImage::wait()` - */ - void drop(AcquiredImage image); - - /** - * hands the image back without a present: the image becomes a spare that waits for the ready - * point + * hands the image back without a present: the image becomes a spare that waits for + * `AcquiredImage::ready()` * @details the acquire semaphore of the image is free once the ready point is reached - * @param image to drop - * @param ready reached after the uses of the image and after the wait for + * @details the destruction of an image drops it without a ready point: the spare keeps * `AcquiredImage::wait()` * @pre the image is of this presenter + * @pre a batch signals `AcquiredImage::ready()`, after the uses of the image and after the + * wait for `AcquiredImage::wait()` */ - void drop(AcquiredImage image, SemaphoreSubmitInfo ready); + void drop(AcquiredImage image); /** * checks without a wait that the presenter has no work left @@ -284,6 +279,11 @@ class Presenter { /** `imageCount - minImageCount` of the surface: more acquired images -> no blocking acquire */ uint32_t _blockingAcquireLimit; std::vector _acquireSemaphores{}; + /** + * one per image, a batch signals the acquire number of a drop, see `AcquiredImage::ready()` + * @details the batches of one image follow its acquires: the values rise + */ + std::vector _readySemaphores{}; mutable std::mutex _mutex{}; @@ -332,6 +332,7 @@ namespace jvk { * acquired swapchain image of a `Presenter` while the engine holds it, handed back exactly once * @details * - `Presenter::present()` or `Presenter::drop()` hands it back, the destruction drops it + * without a ready point * - the content is undefined: the first use transitions it from `VK_IMAGE_LAYOUT_UNDEFINED` * - the first use waits for `wait()` * - a moved-from image hands back nothing @@ -393,6 +394,19 @@ class Presenter::AcquiredImage { */ [[nodiscard]] wait_t const& wait() const { return _presenter.get_deleter().wait; } + /** + * @return the ready point of a drop: the ready semaphore of the image with `acquireNumber()` + * @details a batch after the uses of the image and after the wait for `wait()` signals it, the + * spare of `Presenter::drop()` waits for it + * @pre not handed back + */ + [[nodiscard]] SemaphoreSubmitInfo ready() const { + return SemaphoreSubmitInfo{ + .semaphore = presenter()._readySemaphores[imageIdx()], + .value = acquireNumber(), + }; + } + /** * @return index of the image in the swapchain */ diff --git a/jvk/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index 39b159c3..21c9afe8 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -363,18 +363,19 @@ class Stage { /** * presents the image after the submit of this frame - * @details `Surface::acquire()` calls it for its present stage + * @details `Frame::acquire()` calls it for its present stage * @details the submission of the frame: * - the present is a use of the image after the primary, in the epilogue: the barrier to * `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR`, see `StageSlot::epilogue` * - another queue family of the last use: the last queue releases the image, the epilogue * acquires it - * - the submit signals `Presenter::AcquiredImage::presentSemaphore()` + * - the submit signals `Presenter::AcquiredImage::presentSemaphore()`, the submit or the skip + * signals `Presenter::AcquiredImage::ready()` * - another queue family of the presenter queue: the epilogue releases the image, the * presenter queue acquires it and signals the present semaphore, see `Queue::transfer()` - * - after the submit: `Presenter::present()` - * - a skip or a failed submit: `Presenter::drop()` with the signal of the skip as the ready - * point + * - after the submit: erases the state of the image in the graph, `Presenter::present()` + * - a skip or a failed submit: erases the state of the image in the graph, + * `Presenter::drop()` * @param image the stage holds it until its submission presents or drops it * @pre `status()` is `UNSUBMITTED` * @attention not thread safe diff --git a/jvk/incl/jvk/graph/stage_graph.hpp b/jvk/incl/jvk/graph/stage_graph.hpp index 90d69fec..93495bb9 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -109,15 +109,17 @@ class StageGraph { * - waits for the stage waits of the config and the waits of `Stage::await()` * - signals `Stage::semaphore()` with `Stage::frameNumber()` * - the images of `Stage::present()`: uses after the primary, in the epilogue, the submit - * signals their present semaphores, `Presenter::present()` follows the submit, see - * `Stage::present()` + * signals their present semaphores and their ready points, `Presenter::present()` follows + * the submit, see `Stage::present()` + * - erases the state of a presented image in the graph before `Presenter::present()`: the + * next acquire of the image assumes it again * - another queue family of the last use of a presented image: the last queue releases it, * the epilogue acquires it * - another queue family of the presenter queue: the epilogue releases the image, * `Queue::transfer()` on the presenter queue acquires it and signals the present semaphore * - an error of the submission: skips, `nextFrame()` rethrows the error * - a failed present: the presenter of the image gets the error, see `Presenter::present()` - * - a failed transfer: drops the image with the signal of the submit as the ready point + * - a failed transfer: drops the image, see `Presenter::drop()` * - after the gpu finished: destroys the retained objects * @details a failure here, `vkEndCommandBuffer()` or the allocation of the submission: * - no throw, the stage stays `UNSUBMITTED` @@ -138,8 +140,8 @@ class StageGraph { * @details skip submit on the queue of the stage, no command buffers: * - waits for the stage waits of the config and the waits of `Stage::await()` * - signals `Stage::semaphore()` with `Stage::frameNumber()` - * @details drops the images of `Stage::present()` with the signal of the skip as the ready - * point, see `Presenter::drop()`: the skip waited for the acquire semaphores + * @details the skip signals the ready points of the images of `Stage::present()`, then erases + * their states in the graph and drops them, see `Presenter::drop()` * @details after the gpu finished the skip submit: destroys the retained objects * @details a begun primary: ends its rendering and the primary, discards the recording * @details a failure: the failure of `submit()` @@ -223,10 +225,17 @@ class StageGraph { /** * presents the images of the stage slot after the submit, a failed transfer drops its image + * @details erases the state of each image in the graph before its hand back * @details no throw: a failure goes to `_submissions` */ [[nodiscard]] cth::co::executor_task present(dev::StageSlot&, uint64_t frameNumber); + /** + * erases the state of the image in the graph, then drops it, see `Presenter::drop()` + * @pre the submit or the skip of its stage signaled `Presenter::AcquiredImage::ready()` + */ + void handBack(Presenter::AcquiredImage); + /** the caller holds `_statesMutex` */ void eraseStates(VkImage, uint32_t mipLevels); diff --git a/jvk/incl/jvk/graph/surface.hpp b/jvk/incl/jvk/graph/surface.hpp index 335c6723..a2ab53c9 100644 --- a/jvk/incl/jvk/graph/surface.hpp +++ b/jvk/incl/jvk/graph/surface.hpp @@ -23,8 +23,6 @@ class ImageView; namespace jvk { class Core; -class Stage; -class StageGraph; } namespace jvk { @@ -34,7 +32,7 @@ namespace jvk { * - tracked like every image: the commands that use it record its accesses * - a view of the `Presenter::AcquiredImage` that the present stage holds * - valid until the present stage of its acquire presented or dropped it, see - * `Surface::acquire()` + * `Frame::acquire()` */ struct SwapchainImage { cth::ref_wrapper image; @@ -60,7 +58,7 @@ struct SurfaceConfig { /** * frames that the gpu works on at the same time, the acquire semaphores of each presenter - * @details `< StageGraphConfig::frameSlots` of the graph of the stages -> an acquire can wait + * @details `< StageGraphConfig::frameSlots` of the graph of the images -> an acquire can wait * for the present of an earlier frame, see `Presenter::acquire()` * @pre `framesInFlight > 0` */ @@ -70,14 +68,13 @@ struct SurfaceConfig { }; /** - * cvk surface with its swapchain, acquires its images for stages that present them + * cvk surface with its swapchain, acquires the images of the current swapchain * @details * - owns the cvk surface and the swapchain with its presenters, see `Swapchain` * - recreates the swapchain in `acquire()`, a retired swapchain stays until its presenter * finished * - the presenter of the current swapchain acquires the images, see `Presenter::acquire()` - * - the present stage of an image presents it after its submit, a skip drops it, see - * `Stage::present()` + * - knows no graph: `Frame::acquire()` hands an image to the stages of a frame * - a failed present: the next `acquire()` rethrows its error * @attention not thread safe */ @@ -137,54 +134,23 @@ class Surface { } /** - * acquires the next swapchain image, the present stage presents it after its submit - * @details the surface: + * acquires the next image of the current swapchain + * @details * - a new `cvk::Surface::extent()` or out of date -> recreates the swapchain, see * `Swapchain::recreate()` * - the presenter of the current swapchain acquires the image, see `Presenter::acquire()` * - out of date -> recreates the swapchain and acquires again - * @details the acquire stage: - * - waits for `Presenter::AcquiredImage::wait()` with the stages, see `Stage::await()`: the - * acquire semaphore or the ready point of a dropped image - * - the state of the image in its graph: `VK_IMAGE_LAYOUT_UNDEFINED` with the wait stages, see - * `StageGraph::assume()`: the first barrier of the image chains with the wait - * @details the present stage holds the image until its submission presents or drops it, see - * `Stage::present()` - * @param acquireStage waits for the acquire, the first use of the image - * @param presentStage presents the image after its submit - * @param stages pipeline stages of the acquire stage that wait for the acquire - * @return the image, `std::nullopt` -> surface extent `0`: no image, no wait, no present + * @return the image, `std::nullopt` -> surface extent `0`: no image * @pre `created()` - * @pre `Stage::status()` of both stages is `UNSUBMITTED` - * @pre both stages belong to one frame of one graph - * @pre the present stage waits for every stage of the frame that uses the image, the acquire - * stage included, directly or through other stages, or is that stage, see `StageWait` - * @pre the graphs of the images that a skip dropped exist: the image waits for the semaphore - * of the stage, see `StageGraph::skip()` * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode * @throws cvk::vk_result_exception other result of `vkAcquireNextImageKHR()` or * `vkCreateSwapchainKHR()` * @throws std::exception the error of a failed present before, once, see `Presenter::acquire()` * @attention the fallback of `Presenter::acquire()` can block (FIFO: the vsync throttle): it * occupies a driver thread, `CoreConfig::driverThreads` `0` -> a worker - * @see `Stage::await()` + * @see `Frame::acquire()` */ - [[nodiscard]] cth::co::executor_task> acquire( - Stage& acquireStage, - Stage& presentStage, - VkPipelineStageFlags2 stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT - ); - - /** - * acquires the next swapchain image for one stage that uses and presents it - * @details calls @ref acquire(Stage&, Stage&, VkPipelineStageFlags2) with the stage for both - */ - [[nodiscard]] cth::co::executor_task> acquire( - Stage& stage, - VkPipelineStageFlags2 stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT - ) { - return acquire(stage, stage, stages); - } + [[nodiscard]] cth::co::executor_task> acquire(); [[nodiscard]] constexpr bool created() const { return _surface.created(); } [[nodiscard]] constexpr Config const& config() const { return _config; } diff --git a/jvk/incl/jvk/graph/swapchain.hpp b/jvk/incl/jvk/graph/swapchain.hpp index 25e2c155..bfd47570 100644 --- a/jvk/incl/jvk/graph/swapchain.hpp +++ b/jvk/incl/jvk/graph/swapchain.hpp @@ -22,7 +22,6 @@ class Surface; namespace jvk { class Queue; -class StageGraph; } namespace jvk::dev { @@ -139,16 +138,12 @@ class Swapchain { /** * destroys the finished retired swapchains, then acquires the next image of the current one * @details finished: `Presenter::finished()`, from the oldest on: no present fence is pending - * @details erases the images of a destroyed swapchain in the graph, see `StageGraph::erase()` * @details the current swapchain retired by a failed `recreate()` -> `std::nullopt` - * @param graphPtr of the images, `nullptr` -> none * @return the image, `std::nullopt` -> out of date, `recreate()` the swapchain * @pre `created()` * @see `Presenter::acquire()` */ - [[nodiscard]] cth::co::executor_task> acquire( - StageGraph* graphPtr - ); + [[nodiscard]] cth::co::executor_task> acquire(); /** * @return the swapchain of the next acquires, its address stays until its destruction diff --git a/jvk/src/graph/frame.cpp b/jvk/src/graph/frame.cpp index 6775d469..ae692ae2 100644 --- a/jvk/src/graph/frame.cpp +++ b/jvk/src/graph/frame.cpp @@ -1,7 +1,14 @@ #include "jvk/graph/frame.hpp" +#include "jvk/graph/stage_graph.hpp" + +#include "cvk/data/img/image.hpp" + #include +#include +#include + namespace jvk { Frame::Frame(dev::FrameSlot& frameSlot, uint64_t number) : _frameSlot{frameSlot}, _number{number} {} @@ -16,4 +23,52 @@ Stage& Frame::stage(size_t stageId) { ) {} return stages[stageId]; } + +cth::co::executor_task> Frame::acquire( + Surface& surface, + Stage& acquireStage, + Stage& presentStage, + VkPipelineStageFlags2 stages +) { + CTH_CRITICAL( + acquireStage.status() != Stage::Status::UNSUBMITTED + || presentStage.status() != Stage::Status::UNSUBMITTED, + "the acquire stage and the present stage must be unsubmitted" + ) {} + CTH_CRITICAL( + &acquireStage.graph() != &*_frameSlot->graph + || &presentStage.graph() != &*_frameSlot->graph + || acquireStage.frameNumber() != _number || presentStage.frameNumber() != _number, + "the acquire stage and the present stage must belong to this frame" + ) {} + + auto imageOpt = co_await surface.acquire(); + if(!imageOpt.has_value()) + co_return std::nullopt; + + auto& image = *imageOpt; + SwapchainImage const swapchainImage{ + .image = image.image(), + .view = image.view(), + .imageIdx = image.imageIdx(), + .extent = image.extent(), + }; + + // the first barrier of the image chains with the wait + if(auto const* const semaphorePtr = + std::get_if>(&image.wait())) + acquireStage.await(**semaphorePtr, stages); + else { + auto ready = std::get(image.wait()); + ready.stages = stages; + acquireStage.await(ready); + } + _frameSlot->graph->assume( + *swapchainImage.image, + ImageState{.layout = VK_IMAGE_LAYOUT_UNDEFINED, .scope = {.stages = stages}} + ); + + presentStage.present(std::move(image)); + co_return swapchainImage; +} } diff --git a/jvk/src/graph/presenter.cpp b/jvk/src/graph/presenter.cpp index 20fc5763..7dfad396 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -61,6 +61,11 @@ Presenter::Presenter(Queue& presentQueue, cvk::Swapchain& swapchain, uint32_t fr _acquireSemaphores.reserve(framesInFlight); for(uint32_t i = 0; i < framesInFlight; ++i) _acquireSemaphores.emplace_back(swapchain.core(), cvk::create); + + // reserved: a semaphore with a pending Semaphore::submitted() does not move + _readySemaphores.reserve(swapchain.imageCount()); + for(uint32_t imageIdx = 0; imageIdx < swapchain.imageCount(); ++imageIdx) + _readySemaphores.emplace_back(presentQueue.core(), cvk::create); } Presenter::~Presenter() { @@ -193,12 +198,7 @@ cth::co::executor_task Presenter::present(AcquiredImage image) { void Presenter::drop(AcquiredImage image) { CTH_CRITICAL(image._presenter.get() != this, "the image must be of this presenter") {} - // the dropper spares the image - image._presenter.reset(); -} - -void Presenter::drop(AcquiredImage image, SemaphoreSubmitInfo ready) { - CTH_CRITICAL(image._presenter.get() != this, "the image must be of this presenter") {} + auto const ready = image.ready(); auto const [imageIdx, acquireNumber, wait] = image._presenter.get_deleter(); static_cast(image._presenter.release()); diff --git a/jvk/src/graph/stage_graph.cpp b/jvk/src/graph/stage_graph.cpp index 725bd318..689bf841 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -302,6 +302,10 @@ cth::co::executor_task StageGraph::submission( stageSlot.extraBinaryWaits.clear(); slotSubmit.next(_config.frameSlots); + // the submit or the skip comes after every use of the images: the ready point of a drop + for(auto const& image : stageSlot.presents) + info.signals.push_back(image.ready()); + bool submitted = false; if(targetStatus == Stage::Status::SUBMITTED) { try { @@ -371,10 +375,9 @@ cth::co::executor_task StageGraph::submission( }(); co_await std::move(skip); - // the skip waited for the waits of the stage: the spares wait for its signal - SemaphoreSubmitInfo const ready{.semaphore = stageSlot.semaphore, .value = frameNumber}; + // the skip signaled the ready points: the spares wait for them for(auto& image : stageSlot.presents) - image.presenter().drop(std::move(image), ready); + handBack(std::move(image)); stageSlot.presents.clear(); } @@ -516,6 +519,7 @@ cth::co::executor_task StageGraph::present(dev::StageSlot& stageSlot, uint auto& presentQueue = presenter.queue(); auto const presentFamily = presentQueue.vk().familyIndex(); if(presentFamily == family) { + erase(image.image()); co_await presenter.present(std::move(image)); continue; } @@ -535,13 +539,15 @@ cth::co::executor_task StageGraph::present(dev::StageSlot& stageSlot, uint std::array const signals{cvk::SemaphoreSubmitInfo{image.presentSemaphore()}}; transferredOpt = co_await presentQueue.transfer(std::move(acquire), waits, signals); } - // a failed transfer: the image goes back behind the submit that released it + // a failed transfer: the image goes back behind the submit that released it, the submit + // signaled its ready point catch(...) { _submissions.store(std::current_exception()); } if(!transferredOpt.has_value()) { - presenter.drop(std::move(image), submitted); + handBack(std::move(image)); continue; } + erase(image.image()); co_await presenter.present(std::move(image)); // the transfer waits for the semaphore of the slot: ~StageGraph() destroys it after the @@ -552,6 +558,13 @@ cth::co::executor_task StageGraph::present(dev::StageSlot& stageSlot, uint stageSlot.presents.clear(); } +void StageGraph::handBack(Presenter::AcquiredImage image) { + // the image leaves the graph: an acquire of the image assumes its state again + erase(image.image()); + auto& presenter = image.presenter(); + presenter.drop(std::move(image)); +} + cth::co::executor_task> StageGraph::release(release_map_t releases) { vector waits{}; waits.reserve(releases.size()); diff --git a/jvk/src/graph/surface.cpp b/jvk/src/graph/surface.cpp index b420eebd..ce3eb572 100644 --- a/jvk/src/graph/surface.cpp +++ b/jvk/src/graph/surface.cpp @@ -2,14 +2,10 @@ #include "jvk/base/core.hpp" #include "jvk/base/queue.hpp" -#include "jvk/graph/stage.hpp" -#include "jvk/graph/stage_graph.hpp" #include "cvk/base/core.hpp" -#include "cvk/data/img/image.hpp" #include -#include namespace jvk { @@ -49,63 +45,23 @@ void Surface::destroy() { _surface.destroy(); } -cth::co::executor_task> Surface::acquire( - Stage& acquireStage, - Stage& presentStage, - VkPipelineStageFlags2 stages -) { +cth::co::executor_task> Surface::acquire() { debug_check(*this); - CTH_CRITICAL( - acquireStage.status() != Stage::Status::UNSUBMITTED - || presentStage.status() != Stage::Status::UNSUBMITTED, - "the acquire stage and the present stage must be unsubmitted" - ) {} - CTH_CRITICAL( - &acquireStage.graph() != &presentStage.graph() - || acquireStage.frameNumber() != presentStage.frameNumber(), - "the acquire stage and the present stage must belong to one frame of one graph" - ) {} cvk::Core const& vkCore = *_core; - auto& graph = acquireStage.graph(); - - std::optional imageOpt = std::nullopt; // out of date -> the next round recreates the swapchain bool outOfDate = false; - while(!imageOpt.has_value()) { + for(;;) { auto const extent = _surface.extent(vkCore.physicalDevice()); if(extent.width == 0 || extent.height == 0) co_return std::nullopt; updateSwapchain(extent, outOfDate); - imageOpt = co_await _swapchain.acquire(&graph); - outOfDate = !imageOpt.has_value(); - } - - auto& image = *imageOpt; - SwapchainImage const swapchainImage{ - .image = image.image(), - .view = image.view(), - .imageIdx = image.imageIdx(), - .extent = image.extent(), - }; - - // the first barrier of the image chains with the wait - if(auto const* const semaphorePtr = - std::get_if>(&image.wait())) - acquireStage.await(**semaphorePtr, stages); - else { - auto ready = std::get(image.wait()); - ready.stages = stages; - acquireStage.await(ready); + auto imageOpt = co_await _swapchain.acquire(); + if(imageOpt.has_value()) + co_return std::move(imageOpt); + outOfDate = true; } - graph.assume( - *swapchainImage.image, - ImageState{.layout = VK_IMAGE_LAYOUT_UNDEFINED, .scope = {.stages = stages}} - ); - - presentStage.present(std::move(image)); - co_return swapchainImage; } void Surface::updateSwapchain(VkExtent2D extent, bool outOfDate) { diff --git a/jvk/src/graph/swapchain.cpp b/jvk/src/graph/swapchain.cpp index f1ec6a7f..8cf003b0 100644 --- a/jvk/src/graph/swapchain.cpp +++ b/jvk/src/graph/swapchain.cpp @@ -1,7 +1,6 @@ #include "jvk/graph/swapchain.hpp" #include "jvk/base/queue.hpp" -#include "jvk/graph/stage_graph.hpp" #include "jvk/utility/exception.hpp" #include "cvk/base/core.hpp" @@ -97,20 +96,11 @@ void Swapchain::destroy() { _currentRetired = false; } -cth::co::executor_task> Swapchain::acquire( - StageGraph* graphPtr -) { +cth::co::executor_task> Swapchain::acquire() { debug_check(*this); - while(retired() != 0 && _swapchains.front().presenter.finished()) { - // the gpu finished the uses of the images: a new image can get their handles - if(graphPtr != nullptr) { - auto const& retiredSwapchain = _swapchains.front().swapchain; - for(uint32_t imageIdx = 0; imageIdx < retiredSwapchain.imageCount(); ++imageIdx) - graphPtr->erase(retiredSwapchain.image(imageIdx)); - } + while(retired() != 0 && _swapchains.front().presenter.finished()) _swapchains.pop_front(); - } if(_currentRetired) co_return std::nullopt; diff --git a/jvk/tests/src/graph/presenter_test.cpp b/jvk/tests/src/graph/presenter_test.cpp index 4dc8f7dc..ba4d9c06 100644 --- a/jvk/tests/src/graph/presenter_test.cpp +++ b/jvk/tests/src/graph/presenter_test.cpp @@ -144,19 +144,18 @@ namespace { } /** - * waits for the image without a use + * waits for the image without a use, signals its ready point * @param gatePtr `nullptr` -> no gate, else the submit waits for its value `1` too - * @return the signal of the submit, the ready point of a drop + * @return the ready point of a drop, see `Presenter::AcquiredImage::ready()` */ - [[nodiscard]] SemaphoreSubmitInfo ready( + SemaphoreSubmitInfo ready( Presenter::AcquiredImage const& image, Semaphore const* gatePtr = nullptr ) { - SemaphoreSubmitInfo const signal{.semaphore = done, .value = done.next()}; - SubmitInfo info{.signals = {signal}}; + SubmitInfo info{.signals = {image.ready()}}; add_waits(info, image, gatePtr); core->executor().sync_wait(queue->submit(info)); - return signal; + return image.ready(); } /** @@ -377,7 +376,8 @@ JVK_TEST(Presenter, drop_spares_the_image_with_its_acquire_semaphore) { ASSERT_TRUE(droppedOpt.has_value()); auto const imageIdx = droppedOpt->imageIdx(); auto const* const semaphorePtr = acquire_semaphore(*droppedOpt); - presenter.drop(std::move(*droppedOpt)); + // the destruction drops the image without a ready point + droppedOpt.reset(); // the spare comes first, with the wait of the drop auto spareOpt = acquire(core, presenter); @@ -407,7 +407,7 @@ JVK_TEST(Presenter, drop_with_a_ready_point_spares_the_image_behind_it) { ASSERT_TRUE(droppedOpt.has_value()); auto const imageIdx = droppedOpt->imageIdx(); auto const ready = submits.ready(*droppedOpt, &gate); - presenter.drop(std::move(*droppedOpt), ready); + presenter.drop(std::move(*droppedOpt)); EXPECT_FALSE(presenter.finished()); // the spare waits for the ready point @@ -446,8 +446,8 @@ JVK_TEST(Presenter, ready_point_of_the_last_acquire_semaphore_holds_the_acquire_ auto droppedOpt = acquire(core, presenter); ASSERT_TRUE(droppedOpt.has_value()); - auto const ready = submits.ready(*droppedOpt, &gate); - presenter.drop(std::move(*droppedOpt), ready); + submits.ready(*droppedOpt, &gate); + presenter.drop(std::move(*droppedOpt)); auto spareOpt = acquire(core, presenter); ASSERT_TRUE(spareOpt.has_value()); @@ -529,9 +529,9 @@ JVK_TEST(Presenter, destructor_releases_the_spares) { auto secondOpt = acquire(core, presenter); ASSERT_TRUE(firstOpt.has_value()); ASSERT_TRUE(secondOpt.has_value()); - auto const ready = submits.ready(*secondOpt); - presenter.drop(std::move(*firstOpt)); - presenter.drop(std::move(*secondOpt), ready); + submits.ready(*secondOpt); + firstOpt.reset(); + presenter.drop(std::move(*secondOpt)); } // the spares are back in the swapchain: the next presenter acquires every image diff --git a/jvk/tests/src/graph/surface_test.cpp b/jvk/tests/src/graph/surface_test.cpp index 2628448c..e0f78fe8 100644 --- a/jvk/tests/src/graph/surface_test.cpp +++ b/jvk/tests/src/graph/surface_test.cpp @@ -77,20 +77,22 @@ namespace { [[nodiscard]] std::optional acquire( Core const& core, + Frame& frame, Surface& surface, Stage& stage ) { - return core.executor().sync_wait(surface.acquire(stage, ATTACHMENT_OUTPUT)); + return core.executor().sync_wait(frame.acquire(surface, stage, ATTACHMENT_OUTPUT)); } [[nodiscard]] std::optional acquire( Core const& core, + Frame& frame, Surface& surface, Stage& acquireStage, Stage& presentStage ) { return core.executor().sync_wait( - surface.acquire(acquireStage, presentStage, ATTACHMENT_OUTPUT) + frame.acquire(surface, acquireStage, presentStage, ATTACHMENT_OUTPUT) ); } @@ -264,18 +266,20 @@ namespace { } /** - * acquires and clears the image of the stage, the scope submits, the submission presents + * acquires and clears the image of stage `0` of the frame, the scope submits, the submission + * presents * @details the submission waits for the gate: the present stays pending * @return the image */ SwapchainImage present_behind_gate( Core const& core, - Stage& stage, + Frame& frame, Surface& surface, Semaphore const& gate ) { + auto& stage = frame.stage(0); stage.await(gate, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, 1); - auto const image = acquire(core, surface, stage); + auto const image = acquire(core, frame, surface, stage); EXPECT_TRUE(image); auto const primary = stage.begin(); clear(*primary, *image); @@ -323,8 +327,9 @@ namespace { Surface& surface, std::optional& msaaOpt ) { - auto& stage = next_frame(core, graph).stage(0); - auto const image = acquire(core, surface, stage); + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); + auto const image = acquire(core, frame, surface, stage); EXPECT_TRUE(image); if(!msaaOpt.has_value() || msaaOpt->image.extent() != image->extent) { if(msaaOpt.has_value()) { @@ -359,8 +364,9 @@ namespace { * @return the image */ SwapchainImage present_frame(Core const& core, StageGraph& graph, Surface& surface) { - auto& stage = next_frame(core, graph).stage(0); - auto const image = acquire(core, surface, stage); + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); + auto const image = acquire(core, frame, surface, stage); EXPECT_TRUE(image); auto const primary = stage.begin(); clear(*primary, *image); @@ -400,7 +406,7 @@ namespace { */ SwapchainImage present_scene_and_ui(Core const& core, StageGraph& graph, Surface& surface) { auto& frame = next_frame(core, graph); - auto const image = acquire(core, surface, frame[SCENE], frame[UI]); + auto const image = acquire(core, frame, surface, frame[SCENE], frame[UI]); EXPECT_TRUE(image); { auto const scene = frame[SCENE].begin(); @@ -499,9 +505,10 @@ JVK_TEST(Surface, extent_0_gives_no_image_until_the_extent_is_larger) { EXPECT_FALSE(surface.swapchain().created()); // no image, no wait, no present: the stage submits without the image - auto& stage = next_frame(core, graph).stage(0); + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); { - auto const image = acquire(core, surface, stage); + auto const image = acquire(core, frame, surface, stage); EXPECT_FALSE(image.has_value()); auto const primary = stage.begin(); } @@ -605,17 +612,18 @@ JVK_TEST(Surface, acquire_does_not_wait_for_the_present_before) { StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; Semaphore const gate{core, cvk::create}; - auto& first = next_frame(core, graph).stage(0); - auto const firstImage = present_behind_gate(core, first, surface, gate); + auto& firstFrame = next_frame(core, graph); + auto const firstImage = present_behind_gate(core, firstFrame, surface, gate); // the submission of the first frame waits for the mark of the gate: its present is pending, // the next acquire gives another image at once - auto& second = next_frame(core, graph).stage(0); + auto& secondFrame = next_frame(core, graph); + auto& second = secondFrame.stage(0); std::optional secondImageOpt{}; std::binary_semaphore acquiredSignal{0}; std::jthread frame{ [&] { - secondImageOpt = acquire(core, surface, second); + secondImageOpt = acquire(core, secondFrame, surface, second); acquiredSignal.release(); } }; @@ -679,11 +687,12 @@ JVK_TEST(Surface, skipped_stage_drops_the_image_for_the_next_acquire) { StageGraph graph{core, {.stages = {{.queueIdx = 0}}, .frameSlots = 1}}; // Stage::begin() before the acquire works too - auto& stage = next_frame(core, graph).stage(0); + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); uint32_t imageIdx = 0; { auto const primary = stage.begin(); - auto const image = acquire(core, surface, stage); + auto const image = acquire(core, frame, surface, stage); ASSERT_TRUE(image.has_value()); imageIdx = image->imageIdx; clear(*primary, *image); @@ -695,9 +704,10 @@ JVK_TEST(Surface, skipped_stage_drops_the_image_for_the_next_acquire) { EXPECT_EQ(acquired_images(tracker, surface), 1); // the dropped image comes first, it waits for the skip on the gpu: no validation error - auto& next = next_frame(core, graph).stage(0); + auto& nextFrame = next_frame(core, graph); + auto& next = nextFrame.stage(0); { - auto const image = acquire(core, surface, next); + auto const image = acquire(core, nextFrame, surface, next); ASSERT_TRUE(image.has_value()); EXPECT_EQ(image->imageIdx, imageIdx); EXPECT_EQ(acquired_images(tracker, surface), 1); @@ -708,6 +718,32 @@ JVK_TEST(Surface, skipped_stage_drops_the_image_for_the_next_acquire) { present_frame(core, graph, surface); } +JVK_TEST(Surface, dropped_image_of_a_destroyed_graph_comes_to_the_next_graph) { + test::Context const context{}; + auto windowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, windowSurface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + uint32_t imageIdx = 0; + { + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); + auto const image = acquire(core, frame, surface, stage); + ASSERT_TRUE(image.has_value()); + imageIdx = image->imageIdx; + stage.skip(); + } + + // the spare waits for the ready semaphore of the presenter: the destroyed graph does not matter + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; + EXPECT_EQ(present_frame(core, graph, surface).imageIdx, imageIdx); + present_frame(core, graph, surface); +} + JVK_TEST(Surface, image_without_a_use_presents_after_the_submit) { test::Context const context{}; auto windowSurface = test::headless_surface(context.instance); @@ -721,10 +757,11 @@ JVK_TEST(Surface, image_without_a_use_presents_after_the_submit) { StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; // the epilogue transitions the image from VK_IMAGE_LAYOUT_UNDEFINED - auto& stage = next_frame(core, graph).stage(0); + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); uint32_t imageIdx = 0; { - auto const image = acquire(core, surface, stage); + auto const image = acquire(core, frame, surface, stage); ASSERT_TRUE(image.has_value()); imageIdx = image->imageIdx; auto const primary = stage.begin(); @@ -752,8 +789,9 @@ JVK_TEST(Surface, exception_in_the_recording_submits_and_presents_nothing) { uint32_t imageIdx = 0; try { for(size_t i = 0;; ++i) { - auto& stage = next_frame(core, graph).stage(0); - auto const image = acquire(core, surface, stage); + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); + auto const image = acquire(core, frame, surface, stage); auto const primary = stage.begin(); auto const rendering = primary->beginRendering(clear_info(*image)); if(i == 2) { @@ -770,9 +808,10 @@ JVK_TEST(Surface, exception_in_the_recording_submits_and_presents_nothing) { EXPECT_EQ(stagePtr->status(), Stage::Status::SKIPPED); EXPECT_TRUE(tracker.acquired(surface.swapchain().current(), imageIdx)); - auto& stage = next_frame(core, graph).stage(0); + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); { - auto const image = acquire(core, surface, stage); + auto const image = acquire(core, frame, surface, stage); ASSERT_TRUE(image.has_value()); EXPECT_EQ(image->imageIdx, imageIdx); EXPECT_EQ(acquired_images(tracker, surface), 1); @@ -795,10 +834,11 @@ JVK_TEST(Surface, exception_after_the_submit_presents_the_image) { Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - auto& stage = next_frame(core, graph).stage(0); + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); std::optional imageIdxOpt = std::nullopt; try { - auto const image = acquire(core, surface, stage); + auto const image = acquire(core, frame, surface, stage); auto const primary = stage.begin(); if(image) { imageIdxOpt = image->imageIdx; @@ -830,8 +870,9 @@ JVK_TEST(Surface, exception_propagated_to_the_end_destroys_graph_and_surface) { Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; for(size_t i = 0;; ++i) { - auto& stage = next_frame(core, graph).stage(0); - auto const image = acquire(core, surface, stage); + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); + auto const image = acquire(core, frame, surface, stage); auto const primary = stage.begin(); auto const rendering = primary->beginRendering(clear_info(*image)); if(i == 2) @@ -860,10 +901,11 @@ JVK_TEST(Surface, failed_present_arrives_at_the_next_acquire_and_not_at_next_fra realQueuePresent = std::exchange(table->vkQueuePresentKHR, lost_present); present_frame(core, graph, surface); - auto& stage = next_frame(core, graph).stage(0); + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); // the acquire rethrows the error of the present before try { - [[maybe_unused]] auto const image = acquire(core, surface, stage); + [[maybe_unused]] auto const image = acquire(core, frame, surface, stage); ADD_FAILURE() << "the acquire must rethrow the error of the present"; } catch(cvk::vk_result_exception const& e) { EXPECT_EQ(e.vkResult(), VK_ERROR_SURFACE_LOST_KHR); } @@ -908,7 +950,7 @@ JVK_TEST(Surface, present_stage_without_a_use_presents_the_image_of_the_acquire_ auto& frame = next_frame(core, graph); uint32_t imageIdx = 0; { - auto const image = acquire(core, surface, frame[SCENE], frame[UI]); + auto const image = acquire(core, frame, surface, frame[SCENE], frame[UI]); ASSERT_TRUE(image.has_value()); imageIdx = image->imageIdx; auto const scene = frame[SCENE].begin(); @@ -944,7 +986,7 @@ JVK_TEST(Surface, skipped_present_stage_drops_the_image) { auto& frame = next_frame(core, graph); uint32_t imageIdx = 0; { - auto const image = acquire(core, surface, frame[SCENE], frame[UI]); + auto const image = acquire(core, frame, surface, frame[SCENE], frame[UI]); ASSERT_TRUE(image.has_value()); imageIdx = image->imageIdx; auto const scene = frame[SCENE].begin(); @@ -956,7 +998,7 @@ JVK_TEST(Surface, skipped_present_stage_drops_the_image) { // the dropped image comes first, it waits for the skip of the ui stage on the gpu auto& next = next_frame(core, graph); { - auto const image = acquire(core, surface, next[SCENE], next[UI]); + auto const image = acquire(core, next, surface, next[SCENE], next[UI]); ASSERT_TRUE(image.has_value()); EXPECT_EQ(image->imageIdx, imageIdx); EXPECT_EQ(acquired_images(tracker, surface), 1); @@ -983,7 +1025,7 @@ JVK_TEST(Surface, exception_in_the_present_stage_drops_the_image) { auto& frame = next_frame(core, graph); try { - auto const image = acquire(core, surface, frame[SCENE], frame[UI]); + auto const image = acquire(core, frame, surface, frame[SCENE], frame[UI]); ASSERT_TRUE(image.has_value()); { auto const scene = frame[SCENE].begin(); @@ -1018,8 +1060,8 @@ JVK_TEST(Surface, two_surfaces_present_after_one_stage) { // each surface has its scene stage, both present after the ui stage in one present for(size_t i = 0; i < FRAMES; ++i) { auto& frame = next_frame(core, graph); - auto const firstImage = acquire(core, first, frame[SCENE], frame[UI]); - auto const secondImage = acquire(core, second, frame[SCENE], frame[UI]); + auto const firstImage = acquire(core, frame, first, frame[SCENE], frame[UI]); + auto const secondImage = acquire(core, frame, second, frame[SCENE], frame[UI]); ASSERT_TRUE(firstImage.has_value()); ASSERT_TRUE(secondImage.has_value()); { @@ -1075,7 +1117,7 @@ JVK_TEST(Surface, present_stage_of_another_family_without_a_use_acquires_the_ima // each acquire waits for the present of the image before for(size_t i = 0; i < FRAMES; ++i) { auto& frame = next_frame(core, graph); - auto const image = acquire(core, surface, frame[SCENE], frame[UI]); + auto const image = acquire(core, frame, surface, frame[SCENE], frame[UI]); ASSERT_TRUE(image.has_value()); { auto const scene = frame[SCENE].begin(); diff --git a/jvk/tests/src/graph/swapchain_test.cpp b/jvk/tests/src/graph/swapchain_test.cpp index c744f9be..ec8ceb30 100644 --- a/jvk/tests/src/graph/swapchain_test.cpp +++ b/jvk/tests/src/graph/swapchain_test.cpp @@ -65,13 +65,13 @@ namespace { } /** - * acquires an image of the current presenter, without a graph + * acquires an image of the current presenter */ [[nodiscard]] std::optional acquire( Core const& core, Swapchain& swapchain ) { - return core.executor().sync_wait(swapchain.acquire(nullptr)); + return core.executor().sync_wait(swapchain.acquire()); } } @@ -111,7 +111,6 @@ JVK_TEST(Swapchain, acquire_destroys_the_finished_retired_swapchains) { Swapchain swapchain{core, core.queue(0), surface, 2}; swapchain.create({}, EXTENT); - auto& oldPresenter = swapchain.presenter(); // an image of the retired presenter is not handed back: it did not finish auto oldImageOpt = acquire(core, swapchain); @@ -121,14 +120,15 @@ JVK_TEST(Swapchain, acquire_destroys_the_finished_retired_swapchains) { ASSERT_TRUE(firstOpt.has_value()); EXPECT_EQ(swapchain.retired(), 1); - // handed back as a spare: the retired presenter finished, its destruction releases the spare - oldPresenter.drop(std::move(*oldImageOpt)); + // destroyed without a use: a spare of the retired presenter that finished, the destruction + // of the presenter releases it + oldImageOpt.reset(); auto secondOpt = acquire(core, swapchain); ASSERT_TRUE(secondOpt.has_value()); EXPECT_EQ(swapchain.retired(), 0); - swapchain.presenter().drop(std::move(*firstOpt)); - swapchain.presenter().drop(std::move(*secondOpt)); + firstOpt.reset(); + secondOpt.reset(); swapchain.destroy(); EXPECT_FALSE(swapchain.created()); } @@ -163,6 +163,6 @@ JVK_TEST(Swapchain, failed_recreate_gives_no_image_until_the_next_recreate) { swapchain.recreate({32, 32}); auto imageOpt = acquire(core, swapchain); ASSERT_TRUE(imageOpt.has_value()); - swapchain.presenter().drop(std::move(*imageOpt)); + imageOpt.reset(); } } From 177a352b570c065d84f9fd6658d1332247387e55 Mon Sep 17 00:00:00 2001 From: lukas <89145039+codethinki@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:51:11 +0100 Subject: [PATCH 68/68] lib: cth on master after #36, same content --- lib/cth | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/cth b/lib/cth index 91dff820..e92f8269 160000 --- a/lib/cth +++ b/lib/cth @@ -1 +1 @@ -Subproject commit 91dff820f016f894445713f64ab03e307bf93d07 +Subproject commit e92f826967a0491f1f33daecd5d730daeb26a01b