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/.github/workflows/windows-pipeline.yml b/.github/workflows/windows-pipeline.yml index da8c03e7..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 diff --git a/AGENTS.md b/AGENTS.md index 534cdc9c..37e935e0 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) | @@ -33,7 +34,8 @@ 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. +- 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`. @@ -55,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. @@ -323,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 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/CMakeLists.txt b/CMakeLists.txt index e2416f9d..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 @@ -27,6 +32,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/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/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 4f62e28d..b555e5cd 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 @@ -33,7 +36,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), /** @@ -62,9 +65,6 @@ struct native_window { }; namespace dev { - /** - * deleter of a window, without context - */ struct window_deleter { void operator()(RGFW_window*) const; }; @@ -75,6 +75,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 { @@ -131,10 +132,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(); @@ -171,8 +173,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()` @@ -180,11 +182,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 @@ -201,9 +212,9 @@ class Window { /** * closes the window and frees it - * @pre the window is not `nullptr` + * @details the last window of RGFW deinitializes RGFW */ - 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(); } @@ -214,6 +225,7 @@ class Window { Config _config; cvk::unique_handle _handle{}; + std::vector _events{}; public: Window(Window const& other) = delete; @@ -232,7 +244,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/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_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..4abaffd1 --- /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::DEL}; + 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/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..81440f23 100644 --- a/cgfw/src/window/window.cpp +++ b/cgfw/src/window/window.cpp @@ -1,6 +1,8 @@ #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" #include "cvk/utility/format.hpp" @@ -25,7 +27,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,9 +35,16 @@ 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)); + + 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); } +void dev::window_deleter::operator()(RGFW_window* rgfwWindow) const { + Window::destroy(*rgfwWindow); +} Window::Window(Config config) : _config{std::move(config)} {} @@ -53,6 +62,20 @@ 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(); } + + // the queue holds the events between two pollEvents(), also the first ones of a window + RGFW_setQueueEvents(RGFW_TRUE); + } + auto* const rgfwWindow = RGFW_createWindow( _config.title.c_str(), 0, @@ -61,11 +84,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); } @@ -117,10 +139,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 { @@ -146,13 +178,12 @@ 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(); } -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..30fce454 --- /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::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}); + 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/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/base/core.hpp b/cvk/incl/cvk/base/core.hpp index 08b2ee2f..3d4900bb 100644 --- a/cvk/incl/cvk/base/core.hpp +++ b/cvk/incl/cvk/base/core.hpp @@ -179,17 +179,11 @@ 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; @@ -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/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/incl/cvk/data/buffer/base_buffer.hpp b/cvk/incl/cvk/data/buffer/base_buffer.hpp index 4c86c91e..2c5a6720 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 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/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/descriptor/descriptor.hpp b/cvk/incl/cvk/data/descriptor/descriptor.hpp index 1409703d..aa4b9329 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/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/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/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 e388a2aa..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(); @@ -537,6 +528,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 */ @@ -560,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; }; } @@ -645,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/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/incl/cvk/render/sync/barrier.hpp b/cvk/incl/cvk/render/sync/barrier.hpp index 4176ec70..dc961bd3 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` @@ -218,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, @@ -234,11 +212,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 +254,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 +267,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/surface.hpp b/cvk/incl/cvk/surface/surface.hpp index 9cfc32ac..01e6d3c4 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 @@ -120,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 93eeb49b..313a7b5d 100644 --- a/cvk/incl/cvk/surface/swapchain.hpp +++ b/cvk/incl/cvk/surface/swapchain.hpp @@ -103,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 @@ -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,9 +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 + * @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()` */ @@ -190,29 +194,11 @@ 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; - - /** - * @return an image is acquired, without its `present()` 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(); } [[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; } @@ -255,64 +241,36 @@ 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: - //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 wrapper: = default moves of the swapchain tear down in the member order, the + // swapchain destroys its images itself /** - * 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 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()); } Image image; - OwnedImage(OwnedImage const& other) = delete; - OwnedImage(OwnedImage&& other) noexcept = default; - OwnedImage& operator=(OwnedImage const& other) = delete; - OwnedImage& operator=(OwnedImage&& other) noexcept = default; + // the user-declared destructor suppresses the implicit moves + ReleasingImage(ReleasingImage&& other) noexcept = default; + ReleasingImage& operator=(ReleasingImage&& other) noexcept = default; }; - /** - * 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() { - 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; - }; - - /** - * @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(); @@ -321,13 +279,12 @@ 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{}; - std::vector _acquired{}; + std::vector _images{}; core_handle _handle; diff --git a/cvk/incl/cvk/utility/device/device_features.hpp b/cvk/incl/cvk/utility/device/device_features.hpp index 8eaa0e16..04e2b58b 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/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 3920ef07..9968a2bc 100644 --- a/cvk/incl/cvk/utility/vk_error_code.hpp +++ b/cvk/incl/cvk/utility/vk_error_code.hpp @@ -5,9 +5,9 @@ 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 +// 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 /** * error category of `VkResult` * @details 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..335b6c81 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 @@ -89,7 +87,7 @@ namespace { } /** - * @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, 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..d296d2b0 --- /dev/null +++ b/cvk/src/base/queue/submit_info.cpp @@ -0,0 +1,79 @@ +#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, + }; + } + + 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/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/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/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/src/surface/swapchain.cpp b/cvk/src/surface/swapchain.cpp index dec923a8..80fd90bd 100644 --- a/cvk/src/surface/swapchain.cpp +++ b/cvk/src/surface/swapchain.cpp @@ -116,12 +116,11 @@ 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(); _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, @@ -177,50 +173,36 @@ 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 - ) {} - // 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(); - VkFence const vkFence = fence.get(); + 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 = &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 = &vkWaitSemaphore, .swapchainCount = 1, .pSwapchains = &vkSwapchain, .pImageIndices = &imageIndex, .pResults = nullptr, }; - auto const result = _presentQueue.rawPresent(info); - _acquired[imageIndex] = false; - return result; + return _presentQueue.rawPresent(info); } 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; @@ -235,18 +217,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 { - debug_check(*this); - - return std::ranges::all_of( - _presentFences, - [](PresentFence const& presentFence) { return presentFence.fence.signaled(); } - ); } void destroy(DeviceTable table, VkSwapchainKHR vkSwapchain) { @@ -313,16 +283,12 @@ 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 ); } - - _acquired.assign(count, false); } void Swapchain::forget() { 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/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/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/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..649c487d 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" @@ -300,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 @@ -333,7 +317,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/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/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/surface/swapchain_test.cpp b/cvk/tests/src/surface/swapchain_test.cpp index 1b7ca6d2..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,32 +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(); - EXPECT_FALSE(old.acquired()); old.destroy(); EXPECT_EQ(present_cleared_image(context, swapchain), VK_SUCCESS); } -CVK_TEST(Swapchain, acquired_and_presented) { +CVK_TEST(Swapchain, present_fences_are_created_signaled) { test::PresentContext const context{}; Swapchain swapchain{context.core, context.queue(), context.surface(), {}, EXTENT}; - EXPECT_FALSE(swapchain.acquired()); - 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); + 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()); - 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}); - EXPECT_TRUE(swapchain.presented()); + 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) { @@ -325,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); @@ -336,16 +386,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 +423,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); } @@ -393,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/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 b7b5812e..e225832c 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") @@ -13,38 +6,18 @@ 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) -# 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/cube/src/main.cpp b/demo/cube/src/main.cpp index 7467d33f..6441edcc 100644 --- a/demo/cube/src/main.cpp +++ b/demo/cube/src/main.cpp @@ -6,10 +6,12 @@ #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" +#include "timgui/imgui.hpp" + #include "cgfw/window/window.hpp" #include "cvk/base/cvk.hpp" @@ -17,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" @@ -25,16 +28,21 @@ #include +#include +#include #include #include +#include #include #include #include +#include +#include + #include #include -#include #include #include #include @@ -44,7 +52,9 @@ #include #include #include +#include #include +#include #include #include @@ -55,7 +65,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, @@ -64,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}; @@ -74,6 +85,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}; @@ -233,7 +246,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} }, @@ -277,48 +290,290 @@ struct Cube { jvk::Sampler sampler; }; +//IMPLEMENT moves into an engine library +/** + * frame times of the last `CAPACITY` frames, in ms + * @details ring buffer: full -> a new time overwrites the oldest one + */ +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; + /** - * 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 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(); +} + +/** + * 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 + * - the scene stage records the cube, the ui stage records ImGui over it and presents the image + * - 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 */ cth::co::executor_task draw_frames( - cgfw::Window const& window, + 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, std::optional& targetsOpt ) { bool uploaded = false; 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()) { - window.pollEvents(); - auto& stage = (co_await graph.nextFrame()).stage(CUBE_STAGE_ID); + auto const iterationStart = cth::chrono::clock_t::now(); + if(lastIterationStartOpt.has_value()) + frameTimes.add(iterationStart - *lastIterationStartOpt); + lastIterationStartOpt = iterationStart; - auto const image = co_await presenter.acquire( - stage, + window.pollEvents(); + auto imguiFrame = imgui.frame(); + frame_time_window(frameTimes, frameTimeCollapsed); + auto& drawData = imguiFrame.render(); + + 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 frame.acquire( + surface, + scene, + ui, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT ); - // extent 0: no image, the next nextFrame() skips the stage + // extent 0: no image if(!image) { + 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; @@ -348,60 +603,23 @@ cth::co::executor_task draw_frames( .sampler = cube.sampler.idx(), }; - auto const submit = stage.begin(); - if(!uploaded) { - cube.upload(stage, *submit); - uploaded = true; - } - 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); + uploaded = true; } } /** * 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 presenter is destroyed before the graph: its present jobs wait for the semaphores of the graph + * - the cube, the pipeline, the ImGui and the targets live until `~StageGraph()` waited for the gpu + * - the surface is destroyed after the graph: the stages present to it */ 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(); @@ -413,13 +631,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(); @@ -445,17 +663,36 @@ 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}}; + 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), + }; + // 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, presenter, pipeline, cube, targetsOpt) + draw_frames(window, core, graph, surface, pipeline, cube, imgui, targetsOpt) ); } } diff --git a/demo/triangle/CMakeLists.txt b/demo/triangle/CMakeLists.txt index 5a4b0d7d..750678e3 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}) @@ -13,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/demo/triangle/src/main.cpp b/demo/triangle/src/main.cpp index 671d91b0..25933935 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, @@ -83,26 +83,29 @@ 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 const& window, + cgfw::Window& window, jvk::Core const& core, jvk::StageGraph& graph, - jvk::Presenter& presenter, + jvk::Surface& surface, cvk::GraphicsPipeline const& pipeline, std::optional& msaaOpt ) { 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 presenter.acquire( + auto const image = co_await frame.acquire( + surface, 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; } @@ -141,11 +144,11 @@ 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 after the graph: the stages present to it */ 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(); @@ -157,9 +160,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{ @@ -178,15 +181,15 @@ void run() { cvk::GraphicsPipeline const pipeline{core, std::move(pipelineConfig), cvk::create}; 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), }; + jvk::StageGraph graph{core, {.stages = {{.queueIdx = QUEUE_IDX}}}}; - 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/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/incl/jvk/base/core.hpp b/jvk/incl/jvk/base/core.hpp index 3b9a70cc..6272e33e 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" @@ -15,9 +15,11 @@ #include #include +#include #include #include #include +#include namespace cvk { @@ -30,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: @@ -40,7 +44,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()` @@ -98,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(); @@ -112,11 +118,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 @@ -154,31 +171,50 @@ 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: + void createQueues(); + + /** the queues first: the driver threads run their strands */ + void destroyQueues(); + Config _config; - cvk::Core _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; + + // 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 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; - //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{}; // 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 + /** 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 - std::optional _resourceHeapOpt{}; - std::optional _samplerHeapOpt{}; + ResourceHeap _resourceHeap; ///< not created without counts, see `HeapsConfig` + SamplerHeap _samplerHeap; ///< not created without counts, see `HeapsConfig` 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/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/incl/jvk/base/queue.hpp b/jvk/incl/jvk/base/queue.hpp index f56eefdf..65dfb162 100644 --- a/jvk/incl/jvk/base/queue.hpp +++ b/jvk/incl/jvk/base/queue.hpp @@ -8,6 +8,7 @@ #include +#include #include #include #include @@ -15,30 +16,67 @@ #include #include +#include +#include namespace cth::co { class scheduler; } +namespace cvk { +class Semaphore; +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::transfer()` 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{}; + + /** + * 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(); + } +}; + /** * serialized vulkan queue * @details * - refers to the queue of the cvk core * - runs its work in one strand - * - releases the queue family ownership of resources - * @see `release()` + * - submits and presents, marks the jvk signals of its submits + * - 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()` */ @@ -52,27 +90,62 @@ class Queue { */ void waitIdle() const; - //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 - //TODO review 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 + * submits the batch in the strand, then marks the jvk signals + * @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()` + */ + [[nodiscard]] cth::co::executor_task submit(SubmitInfo const&); + + /** + * 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 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( + cvk::Swapchain& swapchain, + uint32_t imageIdx + ); + + // 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 + // converts to the cvk one + /** + * 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 = {} + ); /** * @return executor of the strand @@ -81,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 */ @@ -97,40 +172,48 @@ class Queue { [[nodiscard]] constexpr VkQueue get() const { return _queue->get(); } private: - /** - * command buffer of one release - * @details owns its command pool, see `PrimaryCmdBuffer` - */ - struct ReleaseCmd { + void submitInStrand(SubmitInfo const&); + + struct TransferCmd { PrimaryCmdBuffer cmd; - /** - * value of the release counter for the last submit of `ReleaseCmd::cmd`, free once reached - */ - uint64_t value = 0; + uint64_t value = 0; ///< free once the transfer counter reached it }; - /** - * a command buffer whose last release 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(); 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 + // used in the strand only, members and no locals: they keep their capacity + std::deque _transferCmds{}; + SubmitInfo _transferInfo{}; - //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 + std::vector _cmdBufferInfos{}; + std::vector _waitInfos{}; + std::vector _signalInfos{}; + + /** + * the counter decides the reuse of the transfer command buffers, no reactor wait: a transfer + * reads it + */ + Semaphore _transferred; 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; }; } + +namespace jvk::dev { +/** 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, + cth::co::catching_scope& submissions +); +} 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/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/base/stasis.hpp b/jvk/incl/jvk/base/stasis.hpp index f61b7310..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; } @@ -123,9 +132,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 bee7a92a..bda4e3d5 100644 --- a/jvk/incl/jvk/cmd/cmd_buffer.hpp +++ b/jvk/incl/jvk/cmd/cmd_buffer.hpp @@ -1,12 +1,14 @@ #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" #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,56 @@ 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::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&); + + /** + * 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()` @@ -191,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&, @@ -203,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); @@ -278,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()` */ @@ -354,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(); } @@ -395,12 +444,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 @@ -414,21 +465,19 @@ 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; 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(); + template void addAccesses( cvk::Barrier& barrier, @@ -441,7 +490,7 @@ class BasicCmdBuffer { addAccesses(barrier, rest...); } - ResourceStates _states{}; + ResourceTracker _states{}; std::unique_ptr _poolPtr; @@ -453,6 +502,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 +537,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 @@ -498,7 +578,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>) @@ -533,12 +613,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/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..2a405680 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,21 +69,53 @@ 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(); /** - * @pre no handle and no cell in a stasis of the heap is left + * destroys the cvk heap and forgets the cells + * @pre `created()` + * @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 */ - ~ResourceHeap(); + void destroy(); + + /** + * if `created()` -> calls `destroy()` + */ + void optDestroy() { + if(created()) + destroy(); + } /** * 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 @@ -104,6 +137,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,36 +164,34 @@ 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: + 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 `_mutex` is locked - */ + /** the caller holds `_mutexPtr` */ 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..764ee153 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 @@ -32,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: @@ -42,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(); /** - * @pre no handle and no cell in a stasis of the heap is left + * 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 */ - ~SamplerHeap(); + void destroy(); + + /** + * if `created()` -> calls `destroy()` + */ + 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()` */ @@ -64,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()` */ @@ -75,38 +109,33 @@ 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: - /** - * adds a handle of the cell - */ + void forget(); + 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{}; }; - 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/frame.hpp b/jvk/incl/jvk/graph/frame.hpp index 8e4128f4..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 @@ -39,6 +43,55 @@ 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); } + + /** + * 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 04ff3d79..b1882a69 100644 --- a/jvk/incl/jvk/graph/presenter.hpp +++ b/jvk/incl/jvk/graph/presenter.hpp @@ -1,27 +1,26 @@ #pragma once -#include "jvk/cmd/cmd_buffer.hpp" -#include "jvk/graph/swapchain.hpp" -#include "jvk/sync/resource_states.hpp" #include "jvk/sync/semaphore.hpp" -#include "jvk/utility/first_error.hpp" #include "cvk/render/sync/semaphore.hpp" -#include "cvk/surface/surface.hpp" #include "cvk/surface/swapchain.hpp" #include -#include +#include #include +#include #include -#include #include -#include #include #include #include +#include +#include #include +#include +#include +#include #include @@ -31,423 +30,424 @@ class ImageView; } namespace jvk { -class Core; class Queue; -class Stage; -class StageGraph; -class scoped_acquire; -} - -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` - */ -struct SwapchainImage { - cth::ref_wrapper image; - cth::ref_wrapper view; - - uint32_t imageIdx; ///< index of the image in the swapchain - - VkExtent2D extent; ///< extent of the swapchain at the acquire -}; - -/** - * config of a `Presenter` - */ -struct PresenterConfig { - /** - * @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{}; - - /** - * frames that the gpu works on at the same time, one acquire semaphore each - * @pre `framesInFlight > 0` - * @pre `framesInFlight >= StageGraphConfig::frameSlots` of the graph of the stages - */ - uint32_t framesInFlight = 2; - - static constexpr void debug_check(PresenterConfig const&); -}; /** - * presents to a surface + * orchestrates the images of one swapchain * @details - * - 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 - * - 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 - * @attention not thread safe + * - `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 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 + * - the destructor releases the spares, see `cvk::Swapchain::unacquire()` */ class Presenter { public: - using Config = PresenterConfig; + class AcquiredImage; /** - * base constructor - * @details the queue presents and runs the present submits - * @pre the config passes `Config::debug_check()` + * wait of the first use of an image: its acquire semaphore or the ready point of its drop */ - Presenter(Core const&, Queue const&, Config); + using wait_t = std::variant, SemaphoreSubmitInfo>; + // no base constructor and create(): the presenter has no wrap or release /** - * constructs and creates - * @details calls @ref Presenter(Core const&, Queue const&, Config), `create()` + * 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 + * @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(Core const&, Queue const&, Config, cvk::Surface); + Presenter(Queue& presentQueue, cvk::Swapchain& swapchain, uint32_t framesInFlight); /** - * @note calls `optDestroy()` + * releases the spares, destroys the acquire semaphores + * @details a failed release does not stop the destruction + * @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 + * @pre the submits that wait for the acquire semaphores or signal the ready semaphores + * completed: VUID-vkDestroySemaphore-semaphore-05149 + * @see `finished()` */ - ~Presenter() { optDestroy(); } + ~Presenter(); /** - * 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 - * @pre `Core::created()` - * @pre `cvk::Surface::created()` - * @pre the queue can present to the 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 + * 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 */ - void create(cvk::Surface); + [[nodiscard]] cth::co::executor_task> acquire(); /** - * waits for the present jobs, destroys and forgets + * hands the image back for its present * @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 - * - 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()` + * - 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 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 + * image and after the wait for `AcquiredImage::wait()` */ - void destroy(); + [[nodiscard]] cth::co::executor_task present(AcquiredImage image); /** - * if `created()` -> calls `destroy()` + * 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 + * @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 optDestroy() { - if(created()) - destroy(); - } + void drop(AcquiredImage image); /** - * 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 - * `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 - * 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 - * `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 - * @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 - * @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 - * @attention `vkAcquireNextImageKHR()` can block (FIFO: the vsync throttle): it occupies a driver thread, - * `CoreConfig::driverThreads` `0` -> the calling worker - * @see `Stage::await()` + * 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, 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]] cth::co::executor_task acquire( - Stage&, - VkPipelineStageFlags2 stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT - ); + [[nodiscard]] bool finished() const; /** - * 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` + * 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 present(Stage&); + void waitPresents(); - [[nodiscard]] constexpr bool created() const { return _surface.created(); } - [[nodiscard]] constexpr Config const& config() const { return _config; } - - /** - * @details created once the surface extent is `> 0` - * @pre `created()` - */ - [[nodiscard]] constexpr Swapchain const& swapchain() const { - debug_check(*this); - return _swapchain; + [[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: - /** - * 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` + struct Free {}; - /** - * value of `Presenter::_semaphore` for the last submit of `PresentSubmit::cmd`, free once reached - */ - uint64_t value = 0; + /** 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; }; /** - * 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 + * state of an acquire semaphore, a `SemaphoreSubmitInfo`: free once the ready point of the + * drop is reached */ - 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 + using reuse_t = std::variant; + + struct Spare { + uint32_t imageIdx; + wait_t wait; }; - //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 + /** 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; + /** - * 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: 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 - * - 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 - * @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 present: stores the error - * @param image the acquired image - * @param lastState of the image in the stage primary - * @param value of `Presenter::_semaphore` for the submit - * @pre the command buffer of the submit belongs to the queue family of the queue + * 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 presentJob( - Queue const& stageQueue, - Semaphore const& stageSemaphore, - uint64_t frameNumber, - SwapchainImage image, - ImageState lastState, - uint64_t value - ); + [[nodiscard]] cth::co::executor_task tryInStrand(); /** - * 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 `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 - * @throws cvk::cvk_exception reason: the surface offers no allowed format or present mode - * @throws cvk::vk_result_exception result of `vkCreateSwapchainKHR()` + * @return the image, `std::nullopt` -> retry */ - void updateSwapchain(VkExtent2D extent, StageGraph* graphPtr); + [[nodiscard]] cth::co::executor_task> fallback(Fallback); /** - * @return `PresenterConfig::swapchain`, `minImageCount` `0` -> `minImageCount` of the surface + `framesInFlight` + * 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]] Swapchain::Config swapchainConfig() const; + [[nodiscard]] std::optional recycle(); /** - * 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()` - * @throws cvk::vk_result_exception result of `vkReleaseSwapchainImagesKHR()` + * blocks until the present fence of a presented image signals + * @return the free acquire semaphore + * @pre in the fallback, an acquire semaphore is `Presented` */ - void unacquireImage(); - - cth::ref_wrapper _core; - cth::ref_wrapper _queue; - Config _config; + [[nodiscard]] size_t awaitPresentFence(); - // destroyed after the swapchain - cvk::Surface _surface; + /** + * @return the images whose present fence is pending, locks + */ + [[nodiscard]] std::vector pendingFences() const; - /** created once the surface extent is `> 0`, `Presenter::_semaphore` orders its uses */ - Swapchain _swapchain; + /** + * 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); /** - * ring of `PresenterConfig::framesInFlight`, signaled by the acquires + * @return the failure of a present, `nullptr` -> none, the presenter forgets it */ - std::vector _acquireSemaphores{}; + [[nodiscard]] std::exception_ptr takeError(); - /** the semaphore in `Presenter::_acquireSemaphores` for the next acquire */ - size_t _acquireSemaphoreIdx = 0; + /** + * 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 + ); - Semaphore _semaphore; ///< signaled by the present submits, each submit signals the next value + // the helpers below lock nothing, the caller holds _mutex + [[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 */ + void handBack(uint64_t acquireNumber); - std::vector _submits{}; ///< one per swapchain image + [[nodiscard]] size_t semaphoreIdx(cvk::Semaphore const& semaphore) const { + return static_cast(&semaphore - _acquireSemaphores.data()); + } - /** the acquired image without a present */ - std::optional _acquiredOpt = std::nullopt; + 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{}; /** - * `VK_ERROR_OUT_OF_DATE_KHR` of a present of the current swapchain, the next `acquire()` recreates the swapchain + * 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::atomic _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{}; + std::vector _readySemaphores{}; + + 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; + /** + * 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 + 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; - - static constexpr void debug_check(Presenter const&); }; } namespace jvk { /** - * acquired swapchain image of a stage for the scope, presents it at its end + * acquired swapchain image of a `Presenter` while the engine holds it, handed back exactly once * @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 - * - no image or a moved-from scope: nothing - * - a failure at the end, e.g. an allocation: the next `Presenter::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 + * - `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 */ -class scoped_acquire { +class Presenter::AcquiredImage { 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 /** + * constructs the image of an acquire, `Presenter::acquire()` constructs it * @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 + * @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 + */ + AcquiredImage(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 */ - scoped_acquire( - Presenter& presenter, - Stage& stage, - std::optional imageOpt, - dev::first_error& error, - int uncaughtExceptions - ) noexcept; + [[nodiscard]] cvk::Image const& image() const { + return presenter().swapchain().image(imageIdx()); + } - ~scoped_acquire(); + /** + * @pre not handed back + */ + [[nodiscard]] cvk::ImageView const& view() const { + return presenter().swapchain().view(imageIdx()); + } /** - * 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 `Presenter::present()` + * @pre not handed back */ - void present(); + [[nodiscard]] VkExtent2D extent() const { return presenter().swapchain().extent(); } /** - * ends the scope without a present, the end of the scope does nothing - * @details the next `Presenter::acquire()` or `Presenter::destroy()` unacquires the image - * @pre an image - * @see `Presenter::acquire()` + * @return the semaphore that the present waits for, a submit signals it + * @pre not handed back */ - void unacquire(); + [[nodiscard]] cvk::Semaphore const& presentSemaphore() const { + return presenter().swapchain().presentSemaphore(imageIdx()); + } - [[nodiscard]] constexpr explicit operator bool() const { return _imageOpt.has_value(); } + /** + * @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; } /** - * @pre an image + * @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]] constexpr SwapchainImage const* operator->() const { return &*_imageOpt; } + [[nodiscard]] SemaphoreSubmitInfo ready() const { + return SemaphoreSubmitInfo{ + .semaphore = presenter()._readySemaphores[imageIdx()], + .value = acquireNumber(), + }; + } /** - * @pre an image + * @return index of the image in the swapchain */ - [[nodiscard]] constexpr SwapchainImage const& operator*() const { return *_imageOpt; } + [[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: - 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 - int _uncaughtExceptions; ///< of the calling thread at the start of `Presenter::acquire()` + // the presenter owns the acquired image: its present() and drop() take 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: - 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; + AcquiredImage(AcquiredImage const& other) = delete; + AcquiredImage(AcquiredImage&& other) noexcept = default; + AcquiredImage& operator=(AcquiredImage const& other) = delete; + AcquiredImage& operator=(AcquiredImage&& other) noexcept = default; - static constexpr void debug_check(scoped_acquire const&); + static void debug_check(AcquiredImage const&); }; } namespace jvk { -constexpr void PresenterConfig::debug_check(PresenterConfig const& config) { - CTH_CRITICAL(config.framesInFlight == 0, "framesInFlight must be > 0") {} - CTH_CRITICAL( - config.swapchain.queueFamilies.size() >= 2, - "the swapchain images must stay exclusive, got {} queue families", - config.swapchain.queueFamilies.size() - ) {} -} - -constexpr void Presenter::debug_check(Presenter const& presenter) { - CTH_CRITICAL(!presenter.created(), "presenter must be created") {} -} - -constexpr void scoped_acquire::debug_check(scoped_acquire const& image) { - CTH_CRITICAL( - !image._presenterPtr, - "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") {} +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/incl/jvk/graph/stage.hpp b/jvk/incl/jvk/graph/stage.hpp index e2776545..21c9afe8 100644 --- a/jvk/incl/jvk/graph/stage.hpp +++ b/jvk/incl/jvk/graph/stage.hpp @@ -2,15 +2,18 @@ #include "jvk/base/queue.hpp" #include "jvk/base/stasis.hpp" #include "jvk/cmd/cmd_buffer.hpp" +#include "jvk/graph/presenter.hpp" +#include "jvk/sync/resource_tracker.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" #include "cvk/data/img/image.hpp" +#include "cvk/render/sync/barrier.hpp" #include +#include #include #include #include @@ -37,19 +40,19 @@ class scoped_submit; } namespace jvk::dev { -//TODO review name: like cvk::SubmitInfo and the legacy jvk::SubmitInfo /** * prebuilt submit of a stage slot * @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 + * - fills the `SubmitInfo` of the next submit or skip: a skip has no command buffers */ -struct SubmitInfo { - /** `StageSlot::prologue`, `StageSlot::primary` */ +struct SlotSubmit { + /** `StageSlot::prologue`, `StageSlot::primary`, `StageSlot::epilogue` */ 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 submission 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 @@ -61,38 +64,30 @@ 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 + * 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 - * @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, + void skipInfo( + SubmitInfo& info, 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, 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 skip( - Queue const& queue, - std::span extraWaits, - std::span extraBinaryWaits - ) const; + void addCmdBuffers(SubmitInfo& info, bool prologue, bool epilogue) const; /** * 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); @@ -100,7 +95,7 @@ struct SubmitInfo { /** * 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 */ @@ -108,8 +103,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: `SlotSubmit::signal` and `SlotSubmit::cmdBuffers` refer to members, +// the mutex does not move /** * resources of a stage in one frame slot * @details @@ -121,30 +116,27 @@ 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 */ StageSlot( StageGraph& graph, - first_error& error, size_t stageId, size_t slot, - Queue const& queue, + Queue& queue, size_t secondaries ); cth::ref_wrapper graph; - /** the first error of the graph, the scopes of the stages store into it */ - cth::ref_wrapper error; - 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 @@ -159,10 +151,59 @@ 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; + /** 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 submission clears them */ + std::vector extraWaits{}; + + /** the binary waits of `Stage::await()` in the frame of the slot, the submission clears them */ + std::vector extraBinaryWaits{}; + + /** + * 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{}; + + /** + * the submit or the skip of the frame of the slot + * @details + * - 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 submission refills them, they keep their capacity + /** 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{}; + + /** + * the releases of the presented images to the queue family of their presenter queue + * @details after `StageSlot::epilogueBarriers` in the epilogue + */ + cvk::Barrier presentReleases{}; + + /** + * 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` + */ + cth::co::counter_event submitDone; /** the stage in the frame slot before, submits first */ cth::ref_wrapper previous; @@ -171,6 +212,12 @@ struct StageSlot { PrimaryCmdBuffer primary; + /** + * 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 /** @@ -180,7 +227,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; @@ -235,7 +283,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` @@ -269,7 +317,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 @@ -288,7 +336,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)` @@ -313,26 +361,49 @@ class Stage { VkPipelineStageFlags2 stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT ); + /** + * presents the image after the submit of this frame + * @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 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: 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 + */ + void present(Presenter::AcquiredImage image); + /** * 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 * @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 @@ -374,7 +445,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); } @@ -404,17 +475,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 - /** 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{}; + dev::RetainedResources _retained{}; ///< under `StageSlot::stasisMutex` public: Stage(Stage const& other) = delete; @@ -430,25 +491,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 first error as a parameter: scoped_submit is no nested class, Stage::begin() hands it the error - // 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 * @pre `Stage::begin()` began the primary */ - scoped_submit(Stage& stage, dev::first_error& error) noexcept : + explicit scoped_submit(Stage& stage) noexcept : _stagePtr{&stage}, - _error{error}, _uncaughtExceptions{std::uncaught_exceptions()} {} ~scoped_submit(); @@ -458,7 +515,6 @@ class scoped_submit { private: cth::move_ptr _stagePtr; - cth::ref_wrapper _error; ///< the first error of the graph int _uncaughtExceptions; public: @@ -470,7 +526,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 91a4dc91..93495bb9 100644 --- a/jvk/incl/jvk/graph/stage_graph.hpp +++ b/jvk/incl/jvk/graph/stage_graph.hpp @@ -4,15 +4,14 @@ #include "stage_graph_config.hpp" #include "jvk/base/stasis.hpp" -#include "jvk/sync/resource_states.hpp" -#include "jvk/utility/first_error.hpp" +#include "jvk/sync/resource_tracker.hpp" #include "cvk/base/queue/submit_info.hpp" #include "cvk/render/sync/barrier.hpp" #include -#include +#include #include #include #include @@ -52,7 +51,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 @@ -64,26 +63,35 @@ 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 of an unsubmitted stage drops its binary waits: their semaphores, e.g. the acquire semaphores of a - * `Presenter`, 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 + * - 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 + * @attention blocks the calling thread: a worker of the core must be free for the submissions */ ~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 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 `Stage::submitted()` of its stages, then each stage: the gpu finished - * it + * @details the old frame of the slot: awaits `StageSlot::submitDone` of its stages: their + * 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` * @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 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 * @attention not thread safe */ [[nodiscard]] cth::co::executor_task nextFrame(); @@ -96,40 +104,59 @@ 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 + * - the images of `Stage::present()`: uses after the primary, in the epilogue, the submit + * 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, 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` + * - 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 * @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 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()` * @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 * @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 - * @see `ResourceStates::assume()` + * @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); @@ -162,151 +189,78 @@ 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; - //TODO review name - using semaphore_waits_t = std::vector; + /** a failure stores its error, the stage stays `UNSUBMITTED` */ + void detachSubmission(Stage&, Stage::Status targetStatus) noexcept; - /** - * 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 waits and retained resources, the exception - * destroys the graph - * @param targetStatus `SUBMITTED` or `SKIPPED` - */ - 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 - /** - * 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 - * - the binary extra waits: no await on the cpu - * - `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 - * - 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 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 - * @see `Stage::submitted()` - */ - [[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, - std::vector extraWaits, - semaphore_waits_t extraBinaryWaits, dev::RetainedResources retained, Stasis::pos stasisEnd, 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 `ResourceStates::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( - ResourceStates const& recording, - Queue const& queue, + ResourceTracker const& recording, + Queue& queue, cvk::Barrier& prologue, release_map_t& releases ); - //TODO review 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::release()` - */ + // jvk waits: they join the jvk extra waits of the stage [[nodiscard]] cth::co::executor_task> release( release_map_t releases ); + void presentBarriers(dev::StageSlot&); + /** - * removes the states and the last queues of the mip levels - * @pre the caller holds `StageGraph::_statesMutex` + * 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` */ - void eraseStates(VkImage, uint32_t mipLevels); + [[nodiscard]] cth::co::executor_task present(dev::StageSlot&, uint64_t frameNumber); /** - * removes the state and the last queue of the buffer - * @pre the caller holds `StageGraph::_statesMutex` + * 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); + + /** 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` - */ - std::mutex _statesMutex{}; + std::mutex _statesMutex{}; ///< locks `_states`, `_imageQueues` and `_bufferQueues` - ResourceStates _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 first error of a submit job or a scope of a stage, `nextFrame()` rethrows it - */ - dev::first_error _error{}; + cth::co::catching_scope _submissions{}; - /** the running submit jobs, `~StageGraph()` waits for them */ - cth::co::simple_counting_scope _jobs{}; + uint64_t _firstFrameNumber; - //TODO review name firstFrameNumber - uint64_t _firstFrameNumber; ///< see `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/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/graph/surface.hpp b/jvk/incl/jvk/graph/surface.hpp new file mode 100644 index 00000000..a2ab53c9 --- /dev/null +++ b/jvk/incl/jvk/graph/surface.hpp @@ -0,0 +1,208 @@ +#pragma once +#include "jvk/base/queue.hpp" +#include "jvk/graph/presenter.hpp" +#include "jvk/graph/swapchain.hpp" + +#include "cvk/surface/surface.hpp" +#include "cvk/surface/swapchain.hpp" + +#include + +#include +#include +#include + +#include +#include + + +namespace cvk { +class Image; +class ImageView; +} + +namespace jvk { +class Core; +} + +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 + * `Frame::acquire()` + */ +struct SwapchainImage { + cth::ref_wrapper image; + cth::ref_wrapper view; + + uint32_t imageIdx; ///< index of the image in the swapchain + + VkExtent2D extent; ///< extent of the swapchain at the acquire +}; + +/** + * config of a `Surface` + */ +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` + */ + cvk::Swapchain::Config swapchain{}; + + /** + * frames that the gpu works on at the same time, the acquire semaphores of each presenter + * @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` + */ + uint32_t framesInFlight = 2; + + static constexpr void debug_check(SurfaceConfig const&); +}; + +/** + * 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()` + * - 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 + */ +class Surface { +public: + using Config = SurfaceConfig; + + /** + * base constructor + * @details the queue presents the images + * @pre the config passes `Config::debug_check()` + */ + Surface(Core const&, Queue&, Config); + + /** + * constructs and creates + * @details calls @ref Surface(Core const&, Queue&, Config), `create()` + */ + Surface(Core const&, Queue&, Config, cvk::Surface); + + /** + * @note calls `optDestroy()` + */ + ~Surface() { optDestroy(); } + + /** + * 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 + * @pre `Core::created()` + * @pre `cvk::Surface::created()` + * @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 or its presenter + */ + void create(cvk::Surface); + + /** + * 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 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(); + + /** + * if `created()` -> calls `destroy()` + */ + void optDestroy() { + if(created()) + destroy(); + } + + /** + * 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 + * @return the image, `std::nullopt` -> surface extent `0`: no image + * @pre `created()` + * @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 `Frame::acquire()` + */ + [[nodiscard]] cth::co::executor_task> acquire(); + + [[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` + * @pre `created()` + */ + [[nodiscard]] constexpr Swapchain const& swapchain() const { + debug_check(*this); + return _swapchain; + } + +private: + /** + * creates the swapchain or recreates it for a new extent or out of date + */ + void updateSwapchain(VkExtent2D extent, bool outOfDate); + + [[nodiscard]] Swapchain::Config swapchainConfig() const; + + cth::ref_wrapper _core; + cth::ref_wrapper _queue; + Config _config; + + // destroyed after the swapchain + cvk::Surface _surface; + + Swapchain _swapchain; + +public: + 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(Surface const&); +}; +} + +namespace jvk { +constexpr void SurfaceConfig::debug_check(SurfaceConfig const& config) { + CTH_CRITICAL(config.framesInFlight == 0, "framesInFlight must be > 0") {} + CTH_CRITICAL( + config.swapchain.queueFamilies.size() >= 2, + "the swapchain images must stay exclusive, got {} queue families", + config.swapchain.queueFamilies.size() + ) {} +} + +constexpr void Surface::debug_check(Surface const& surface) { + CTH_CRITICAL(!surface.created(), "surface must be created") {} +} +} diff --git a/jvk/incl/jvk/graph/swapchain.hpp b/jvk/incl/jvk/graph/swapchain.hpp index 2e5e2fae..bfd47570 100644 --- a/jvk/incl/jvk/graph/swapchain.hpp +++ b/jvk/incl/jvk/graph/swapchain.hpp @@ -1,33 +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; +} + +namespace jvk::dev { /** - * swapchain with the swapchains it replaced + * 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, 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 - * - 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` + * - `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 { public: @@ -35,9 +72,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()` @@ -45,31 +89,41 @@ 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 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 + * - 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 `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(); @@ -82,15 +136,14 @@ 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 + * 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 the current swapchain retired by a failed `recreate()` -> `std::nullopt` + * @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(); /** * @return the swapchain of the next acquires, its address stays until its destruction @@ -98,7 +151,7 @@ class Swapchain { */ [[nodiscard]] cvk::Swapchain& current() { debug_check(*this); - return _swapchains.back(); + return _swapchains.back().swapchain; } /** @@ -106,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(); } @@ -118,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 - * @details a deque: the addresses stay at the end and the front changes + * @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/incl/jvk/sync/family_transfer.hpp b/jvk/incl/jvk/sync/family_transfer.hpp index 1d828bb7..3b8ce79a 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,24 +10,9 @@ 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 - }; -} +/** 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, @@ -36,8 +21,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, @@ -45,14 +31,7 @@ namespace jvk::dev { }; } -/** - * 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, @@ -61,8 +40,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, @@ -70,37 +51,28 @@ namespace jvk::dev { }; } -/** - * 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, 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, + }; } -/** - * 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, 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 89% rename from jvk/incl/jvk/sync/resource_states.hpp rename to jvk/incl/jvk/sync/resource_tracker.hpp index 93ba459b..fe2af4c1 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 }; /** @@ -43,7 +42,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 @@ -55,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 }; /** @@ -67,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 @@ -76,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 @@ -130,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 @@ -215,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, + }; } ); } @@ -242,8 +253,8 @@ class ResourceStates { 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::optional firstOpt; @@ -254,7 +265,7 @@ class ResourceStates { }; struct buffer_states { - VkSharingMode sharingMode; ///< of the buffer + VkSharingMode sharingMode; /** `std::nullopt` -> `assume()` before the first access */ std::optional firstOpt; diff --git a/jvk/incl/jvk/sync/semaphore.hpp b/jvk/incl/jvk/sync/semaphore.hpp index ab5b7adf..b7d1423d 100644 --- a/jvk/incl/jvk/sync/semaphore.hpp +++ b/jvk/incl/jvk/sync/semaphore.hpp @@ -1,39 +1,38 @@ #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 #include #include #include -#include -#include #include #include -#include 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 + * @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 @@ -42,57 +41,25 @@ 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); -private: - //TODO review 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 - */ - void awaitReactor(cth::co::context::await_func cb) const; - - cth::ref_wrapper _semaphore; - uint64_t _value; -}; - -//TODO review name: snake_case like semaphore_awaiter -/** - * 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 + * @throws cth::except::coro_exception reason: the wait failed, `code()` is + * `cvk::make_error_code()` of the result */ - [[nodiscard]] bool await_ready() const; - - /** - * registers the resume of the caller with the semaphore - * @details resumes on the context of the caller - * @see `Semaphore::awaitSubmitted()` - */ - 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 - constexpr void await_resume() const noexcept {} + void await_resume() const; private: + // a private helper: the reactor needs the complete jvk::Core, the template stays in the header + void awaitReactor(); + cth::ref_wrapper _semaphore; - uint64_t _value; + TimelineReactor::Waiter _waiter; }; } @@ -103,6 +70,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: @@ -130,7 +98,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` @@ -150,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()` @@ -174,15 +141,15 @@ 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 - * - 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; @@ -192,25 +159,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); } - //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 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; - /** * waits until the semaphore reaches the value * @details @@ -222,7 +178,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 @@ -244,7 +200,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(); } @@ -257,31 +213,11 @@ class Semaphore { constexpr operator cvk::TimelineSemaphore const&() const { return _semaphore; } private: - /** - * callback of `awaitSubmitted()` - */ - 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 `awaitSubmitted()` 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{}; public: Semaphore(Semaphore const& other) = delete; @@ -294,8 +230,7 @@ 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 +// in semaphore.hpp next to Semaphore: it is small, no own header /** * wait or signal of a submit on a jvk semaphore * @details @@ -318,23 +253,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 - * 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); @@ -342,14 +260,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))); -} - -template requires cth::co::this_coro_compatible -void submitted_awaiter::await_suspend(std::coroutine_handle caller) { - _semaphore->awaitSubmitted( - _value, - dev::post_to(caller.promise().context(), [caller](std::error_code) { caller.resume(); }) - ); + _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 db293e0c..5c7e04a3 100644 --- a/jvk/incl/jvk/sync/timeline_reactor.hpp +++ b/jvk/incl/jvk/sync/timeline_reactor.hpp @@ -4,11 +4,13 @@ #include #include -#include #include +#include #include +#include #include +#include #include #include #include @@ -19,25 +21,25 @@ 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 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 */ 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()` @@ -56,7 +58,7 @@ class TimelineReactor { /** * stops the thread, destroys the wake semaphore * @pre `created()` - * @pre no callback is pending + * @pre no waiter is pending */ void destroy(); @@ -69,85 +71,79 @@ 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; + struct Pending { + VkSemaphore vkSemaphore; + cth::ref_wrapper waiter; }; - 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 - * @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::_mutex` - * @throws cvk::vk_result_exception result of `vkSignalSemaphore()` - */ + /** the caller holds `_mutexPtr` */ void wake() const; - /** - * stores the error, takes every pending callback - * @return the callbacks to post with the error - * @pre the caller holds `TimelineReactor::_mutex` - */ - [[nodiscard]] std::vector fail(std::error_code) const; - - /** - * posts the callback to the workers - */ - void post(cth::co::context::await_func cb, std::error_code) const; + /** the caller holds `_mutexPtr` */ + void fail(std::error_code, std::vector>& waiters) const; - cth::ref_wrapper _workers; + /** 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; - 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 - * @details an entry exists while the semaphore has waiters - * @see `std::ranges::push_heap()` - */ - 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 + mutable std::error_code _error{}; // destroyed first: destroy() stops it before the members std::jthread _thread{}; 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; +}; +} + +namespace jvk { +/** + * 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 + */ +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 }; } diff --git a/jvk/incl/jvk/utility/first_error.hpp b/jvk/incl/jvk/utility/first_error.hpp deleted file mode 100644 index 3b926e35..00000000 --- a/jvk/incl/jvk/utility/first_error.hpp +++ /dev/null @@ -1,78 +0,0 @@ -#pragma once -#include "cvk/utility/vk_exceptions.hpp" - -#include -#include - -#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; -}; - -/** - * 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/core.cpp b/jvk/src/base/core.cpp index f9e9fdc5..e7446326 100644 --- a/jvk/src/base/core.cpp +++ b/jvk/src/base/core.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -20,11 +21,15 @@ using std::span; Core::Core(cvk::Instance const& instance, Config config) : _config{std::move(config)}, - _core{instance}, + _corePtr{std::make_unique(instance)}, _workers{ - _config.workers == 0 ? std::max(std::thread::hardware_concurrency(), 1u) : _config.workers + _config.workers == 0 + ? std::max(std::thread::hardware_concurrency(), 1u) + : _config.workers }, - _reactor{_core, _workers} {} + _reactor{*_corePtr}, + _resourceHeap{*_corePtr, _config.heaps.resources}, + _samplerHeap{*_corePtr, _config.heaps.samplers} {} Core::Core( cvk::Instance const& instance, @@ -45,25 +50,25 @@ 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(); _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); + _samplerHeap.create(); } catch(...) { - _resourceHeapOpt.reset(); - _queuesOpt.reset(); + _resourceHeap.optDestroy(); + destroyQueues(); _reactor.optDestroy(); _workers.await_stop(); - _core.destroy(); + _corePtr->destroy(); throw; } } @@ -75,7 +80,7 @@ void Core::destroy() { // 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; @@ -107,34 +112,59 @@ void Core::destroy() { } } - _queuesOpt.reset(); - _samplerHeapOpt.reset(); - _resourceHeapOpt.reset(); + destroyQueues(); + _samplerHeap.optDestroy(); + _resourceHeap.optDestroy(); _reactor.destroy(); _workers.await_stop(); - _core.destroy(); -} - -Queue const& Core::queue(size_t queueIdx) const { - debug_check(*this); - return _queuesOpt->queue(queueIdx); + _corePtr->destroy(); } 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 = _corePtr->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, _corePtr->queue(queueIdx), scheduler); + } +} + +void Core::destroyQueues() { + _queues.clear(); + _queueIndices.clear(); + _driverSchedulerOpt.reset(); } 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/base/queue.cpp b/jvk/src/base/queue.cpp index 919500fb..46c119ab 100644 --- a/jvk/src/base/queue.cpp +++ b/jvk/src/base/queue.cpp @@ -1,20 +1,35 @@ #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" #include #include #include +#include +#include namespace jvk { +using std::span; + +namespace { + 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}, _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( @@ -25,37 +40,117 @@ void Queue::waitIdle() const { ); } -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::submit(SubmitInfo const& info) { + co_await executor().schedule(); + + submitInStrand(info); + mark(info.signals); +} + +cth::co::executor_task Queue::present(cvk::Swapchain& swapchain, uint32_t imageIdx) { + co_await executor().schedule(); + co_return swapchain.present(imageIdx); +} + +cth::co::executor_task Queue::transfer( + cvk::Barrier barriers, + span waits, + span binarySignals +) { + // 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()}; - _queue->submit({.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; - _released.markSubmitted(signal.value); + transferCmd.value = signal.value; + mark(info.signals); co_return signal; } -auto Queue::freeReleaseCmd() const -> ReleaseCmd& { - auto const reached = _released.gpuValue(); +void Queue::submitInStrand(SubmitInfo const& info) { + _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)); + + _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::freeTransferCmd() -> 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()}}); + return _transferCmds.emplace_back( + TransferCmd{PrimaryCmdBuffer{*_core, _queue->familyIndex(), cvk::create}} + ); +} + +namespace dev { + cth::co::executor_task skip_submit( + Queue& queue, + SubmitInfo const& info, + cth::co::catching_scope& submissions + ) { + // every failure but a device loss terminates: nobody marks the signals, the waiters would + // hang + 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 skip submit failed, got {}", e.vkResult()) {} + std::terminate(); + } + submissions.store(std::current_exception()); + // the failed submit marked nothing: the waiters of the marks go on + mark(info.signals); + } + catch(...) { std::terminate(); } + } } } 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/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 000d5674..eb67c7f6 100644 --- a/jvk/src/cmd/cmd_buffer.cpp +++ b/jvk/src/cmd/cmd_buffer.cpp @@ -12,15 +12,10 @@ #include #include #include -#include 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, @@ -54,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, @@ -74,9 +66,6 @@ namespace { }; } - /** - * access of a depth or stencil attachment - */ [[nodiscard]] ImageAccess depth_stencil_access( cvk::RenderingAttachment const& attachment, bool writes @@ -100,37 +89,23 @@ namespace { } - /** - * access of an attachment to the mip level of its image - */ - 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{}; - + // a callable, no vector: no allocation per rendering + 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 +127,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 +145,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 +163,6 @@ namespace { if(stencil.has_value() && !(shared && stencil->resolveViewPtr == depth->resolveViewPtr)) resolve(*stencil); - return accesses; } } @@ -206,16 +174,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{}; @@ -275,8 +286,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); @@ -287,13 +302,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(); } @@ -356,7 +375,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); @@ -375,6 +394,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 +409,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 +453,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/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..a52c24aa 100644 --- a/jvk/src/data/sampler_heap.cpp +++ b/jvk/src/data/sampler_heap.cpp @@ -10,20 +10,34 @@ 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() { +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( _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 { - 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 +68,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) {} @@ -69,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/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 ee2fe0da..7dfad396 100644 --- a/jvk/src/graph/presenter.cpp +++ b/jvk/src/graph/presenter.cpp @@ -1,407 +1,492 @@ #include "jvk/graph/presenter.hpp" -#include "jvk/base/core.hpp" #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/surface/surface.hpp" #include "cvk/utility/vk_exceptions.hpp" -#include "cvk/utility/vk_overloads.hpp" -#include #include #include +#include #include -#include +#include +#include #include -#include namespace jvk { -using std::vector; +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); + } -Presenter::Presenter(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); } + template + [[nodiscard]] constexpr bool holds(auto const& variant) { + return std::holds_alternative(variant); + } -Presenter::Presenter(Core const& core, Queue const& queue, Config config, cvk::Surface surface) : - Presenter{core, queue, std::move(config)} { create(std::move(surface)); } + /** + * @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; + } +} -void Presenter::create(cvk::Surface surface) { - Core::debug_check(*_core); - cvk::Surface::debug_check(surface); - optDestroy(); +Presenter::Presenter(Queue& presentQueue, cvk::Swapchain& swapchain, uint32_t framesInFlight) : + _queue{presentQueue}, + _swapchain{swapchain}, + _blockingAcquireLimit{blocking_acquire_limit(swapchain)}, + _reuses(framesInFlight, Free{}), + _pendingFences(swapchain.imageCount(), false) { + 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); + + // 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); +} - _surface = std::move(surface); - cvk::Core const& vkCore = *_core; +Presenter::~Presenter() { + CTH_CRITICAL( + _handedBack.value() != _acquires, + "every image must be handed back after its present, {} of {} are", + _handedBack.value(), + _acquires + ) {} - try { - _semaphore.create(); - _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); - } - catch(...) { - destroy(); - throw; + 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()) {} } } -void Presenter::destroy() { - debug_check(*this); +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); + } - _jobs.wait(); + if(_fallback) + fallbackValue = _fallbacks; + else if(std::ranges::all_of(_reuses, holds)) + handBackValue = _handBacks.value() + 1; + } - // a failed wait leaves the gpu work, the destruction goes on - if(_semaphore.created()) { - try { - cvk::TimelineSemaphore const& semaphore = _semaphore; - semaphore.wait(_semaphore.value()); + if(fallbackValue != 0) { + co_await _fallbacksDone.wait(fallbackValue); + continue; } - catch(cvk::vk_result_exception const& e) { - JVK_STABLE_ERR( - true, - "failed to wait for the present submits in destroy(), got {}", - e.vkResult() - ) {} + if(handBackValue != 0) { + co_await _handBacks.wait(handBackValue); + continue; } - } - //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 - // no job runs, no acquire is pending: nothing else uses the swapchain - if(_acquiredOpt.has_value()) { - try { unacquireImage(); } - catch(cvk::vk_result_exception const& e) { - JVK_STABLE_ERR( - true, - "failed to unacquire the swapchain image in destroy(), got {}", - e.vkResult() - ) {} - _acquiredOpt.reset(); + 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); } } +} - _submits.clear(); - _acquireSemaphores.clear(); - _semaphore.optDestroy(); - _swapchain.optDestroy(); - _surface.destroy(); +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 + static_cast(image._presenter.release()); + + // 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 { + ++_presentsStarted; + fencePending = _pendingFences[imageIdx]; + } + } + if(fallbackValue == 0) + break; + co_await _fallbacksDone.wait(fallbackValue); + } - _acquireSemaphoreIdx = 0; - _outOfDate = false; - _error.clear(); + VkResult result = VK_ERROR_UNKNOWN; + std::exception_ptr error = nullptr; + 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}; + 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) + _error = error; + } else if(result == VK_ERROR_OUT_OF_DATE_KHR) + _outOfDate = true; + + handBack(acquireNumber); + _presentsDone.set(_presentsDone.value() + 1); } -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( - _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() - ) {} - 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); - // 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 - co_await cth::co::executor{_queue->scheduler()}.schedule(); +void Presenter::drop(AcquiredImage image) { + 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()); - if(_acquiredOpt.has_value()) - unacquireImage(); + spare(imageIdx, acquireNumber, wait, ready); +} - cvk::Core const& vkCore = *_core; - std::optional imageIdxOpt = std::nullopt; - auto const& acquireSemaphore = _acquireSemaphores[_acquireSemaphoreIdx]; +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 || _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); + for(auto const& spare : _spares) + if(auto const* const readyPtr = std::get_if(&spare.wait)) + readyPoints.push_back(*readyPtr); + } - 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}; - updateSwapchain(extent, &stage.graph()); + // no vulkan call behind the mutex + return std::ranges::all_of( + readyPoints, + [](SemaphoreSubmitInfo const& ready) { + return ready.semaphore->gpuValue() >= ready.value; + } + ) + && std::ranges::all_of( + pendingIndices, + [this](uint32_t imageIdx) { return _swapchain->presentFence(imageIdx).signaled(); } + ); +} - // no image -> out of date, the next round recreates the swapchain - imageIdxOpt = _swapchain.acquire(acquireSemaphore).imageIndex; - if(!imageIdxOpt.has_value()) - _outOfDate = true; - } +void Presenter::waitPresents() { waitPresents(pendingFences()); } - auto const imageIdx = *imageIdxOpt; - auto const& swapchain = _swapchain.current(); - SwapchainImage const image{ - .image = swapchain.image(imageIdx), - .view = swapchain.view(imageIdx), - .imageIdx = imageIdx, - .extent = swapchain.extent(), - }; - _acquireSemaphoreIdx = (_acquireSemaphoreIdx + 1) % _config.framesInFlight; - _acquiredOpt = AcquiredImage{ - .image = image, - .stageSemaphore = stage.semaphore(), - .frameNumber = stage.frameNumber(), - }; +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(); - // the first barrier of the image chains with the wait for the acquire - stage.await(acquireSemaphore, stages); - stage.graph().assume( - *image.image, - ImageState{.layout = VK_IMAGE_LAYOUT_UNDEFINED, .scope = {.stages = stages}} - ); + { + std::scoped_lock const lock{_mutex}; + // changed since the check before the strand + if(_fallback || _outOfDate || !_spares.empty()) + co_return Retry{}; + } - co_return scoped_acquire{*this, stage, image, _error, uncaughtExceptions}; -} + 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{}; + } -void Presenter::present(Stage& stage) { - debug_check(*this); - CTH_CRITICAL(!_acquiredOpt.has_value(), "the presenter must have an acquired image") {} - CTH_CRITICAL(stage.status() != Stage::Status::SUBMITTED, "the stage must be submitted") {} + // 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); - 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 - ) {} + 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{}; + } - // 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(); + // VK_NOT_READY + co_return startFallback(semaphoreIdxOpt); } -cth::co::executor_task Presenter::presentJob( - Queue const& stageQueue, - Semaphore const& stageSemaphore, - uint64_t frameNumber, - SwapchainImage image, - ImageState lastState, - uint64_t value +cth::co::executor_task> Presenter::fallback( + Fallback start ) { - 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(); - - vector waits{{.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); - // 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); - - bool submitted = false; + // 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 { - 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) - ); - waits.push_back(co_await stageQueue.release(std::move(release))); + 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; + } - 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, - } + 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 + waitPresents(pendingFences()); + 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]} ); + } - // 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 - auto& submit = _submits[image.imageIdx]; - 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 - }, - } - ); - submit.value = value; - submitted = true; + 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; } - 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 - ); + if(handBackValue != 0) + co_await _handBacks.wait(handBackValue); + co_return std::nullopt; +} + +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; } - 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; + // 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; } - catch(cvk::vk_result_exception const&) { _error.store(std::current_exception()); } - } + if(auto const* const readyPtr = std::get_if(&reuse)) + return readyPtr->semaphore->gpuValue() >= readyPtr->value; + return false; + }; - // after the present: the next acquire() awaits it - _semaphore.markSubmitted(value); + 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{}; + // 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; } -void Presenter::updateSwapchain(VkExtent2D extent, StageGraph* graphPtr) { - if(_swapchain.created() && !_outOfDate && _swapchain.current().extent() == extent) - return; +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, a fence + // that is not pending is free at the next recycle + waitPresents(std::array{imageIdx}); + } +} - 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)); - _swapchain.recreate(extent); - } else - _swapchain.create(swapchainConfig(), extent); - _outOfDate = false; +std::exception_ptr Presenter::takeError() { + std::scoped_lock const lock{_mutex}; + return std::exchange(_error, nullptr); +} - while(_submits.size() < _swapchain.current().imageCount()) - _submits.push_back( - PresentSubmit{.cmd = PrimaryCmdBuffer{*_core, _queue->vk().familyIndex()}} - ); +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; } -Swapchain::Config Presenter::swapchainConfig() const { - auto config = _config.swapchain; - if(config.minImageCount != 0) - return config; +void Presenter::waitPresents(std::span imageIndices) { + // no vulkan call behind the mutex + for(auto const imageIdx : imageIndices) + _swapchain->presentFence(imageIdx).wait(); - cvk::Core const& vkCore = *_core; - config.minImageCount = - _surface.capabilities(vkCore.physicalDevice()).minImageCount + _config.framesInFlight; - return config; + std::scoped_lock const lock{_mutex}; + for(auto const imageIdx : imageIndices) + _pendingFences[imageIdx] = false; } -void Presenter::unacquireImage() { - _swapchain.current().unacquire(std::array{_acquiredOpt->image.imageIdx}); - _acquiredOpt.reset(); +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 { + _fallback = true; + ++_fallbacks; + return Fallback{.semaphoreIdxOpt = semaphoreIdxOpt, .presents = _presentsStarted}; } -namespace jvk { -scoped_acquire::scoped_acquire( - Presenter& presenter, - Stage& stage, - std::optional imageOpt, - dev::first_error& error, - int uncaughtExceptions -) noexcept : - _presenterPtr{&presenter}, - _stage{stage}, - _imageOpt{std::move(imageOpt)}, - _error{error}, - _uncaughtExceptions{uncaughtExceptions} {} - -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 - ) {} +void Presenter::endFallback() { + _fallback = false; + _fallbacksDone.set(_fallbacks); +} - // skipped or unsubmitted: the next acquire() or destroy() unacquires the image - if(stage.status() != Stage::Status::SUBMITTED) - return; +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); - // a destructor does not throw: the next acquire() rethrows - try { _presenterPtr->present(stage); } - catch(...) { _error->store(std::current_exception()); } + _handBacks.set(_handBacks.value() + 1); } -void scoped_acquire::present() { - debug_check(*this); - CTH_CRITICAL(_stage->status() == Stage::Status::SKIPPED, "the stage must not be skipped") {} +void Presenter::spare( + uint32_t imageIdx, + uint64_t acquireNumber, + wait_t const& wait, + std::optional const& readyOpt +) { + using semaphore_ref_t = cth::ref_wrapper; - if(_stage->status() == Stage::Status::UNSUBMITTED) - _stage->submit(); - _presenterPtr.release()->present(*_stage); -} + 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; -void scoped_acquire::unacquire() { - debug_check(*this); - // the next acquire() or destroy() unacquires the image - static_cast(_presenterPtr.release()); + _spares.push_back( + Spare{.imageIdx = imageIdx, .wait = readyOpt.has_value() ? wait_t{*readyOpt} : wait} + ); + handBack(acquireNumber); } } diff --git a/jvk/src/graph/stage.cpp b/jvk/src/graph/stage.cpp index c6b60423..dc86f73d 100644 --- a/jvk/src/graph/stage.cpp +++ b/jvk/src/graph/stage.cpp @@ -11,7 +11,6 @@ #include #include -#include #include #include #include @@ -19,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()); @@ -37,77 +33,55 @@ 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, +void SlotSubmit::skipInfo( + SubmitInfo& info, std::span extraWaits, - std::span extraBinaryWaits, - bool prologue + std::span extraBinaryWaits ) const { - cvk::SubmitInfo submitInfo{ - .waits = all_waits(*this, extraWaits, extraBinaryWaits), - .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.clear(); + info.waits.reserve(waits.size() + extraWaits.size()); + info.waits.append_range(waits); + info.waits.append_range(extraWaits); + info.binaryWaits.append_range(extraBinaryWaits); + info.signals.push_back(signal); } -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, 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( StageGraph& graph, - first_error& error, size_t stageId, size_t slot, - Queue const& queue, + Queue& queue, size_t secondaries ) : graph{graph}, - error{error}, stageId{stageId}, slot{slot}, 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}}, + submitDone{graph.firstFrameNumber() - 1}, 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}, + epilogue{graph.core(), queue.vk().familyIndex(), cvk::create}, stasis{graph.core()} { - submitInfo.cmdBuffers = {prologue, primary}; + slotSubmit.cmdBuffers = {prologue, primary, epilogue}; 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); } } @@ -128,7 +102,7 @@ scoped_submit Stage::begin() { if(samplerHeapPtr != nullptr) vk.bind(*samplerHeapPtr); - return scoped_submit{*this, _stageSlot->error}; + return scoped_submit{*this}; } SecondaryCmdBuffer& Stage::beginSecondary( @@ -155,31 +129,36 @@ 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) { 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); } +void Stage::present(Presenter::AcquiredImage image) { + CTH_CRITICAL(_status != Status::UNSUBMITTED, "the stage must be unsubmitted") {} + _stageSlot->presents.push_back(std::move(image)); +} + +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; - try { _stagePtr->submit(); } - catch(...) { _error->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 9af33c26..689bf841 100644 --- a/jvk/src/graph/stage_graph.cpp +++ b/jvk/src/graph/stage_graph.cpp @@ -4,31 +4,33 @@ #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" #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 #include #include namespace jvk { +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) @@ -37,10 +39,20 @@ namespace { return maxOffset + 1; } - /** - * 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()` - */ + constexpr ImageState PRESENT_STATE{ + .layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + .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, uint32_t mipLevel @@ -73,7 +85,6 @@ StageGraph::StageGraph(Core& core, Config config) : for(size_t stageId = 0; stageId < stages.size(); ++stageId) frameSlot.stageSlots.emplace_back( *this, - _error, stageId, slot, core.queue(stages[stageId].queueIdx), @@ -94,7 +105,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, @@ -106,26 +117,29 @@ 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(): 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; - //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 - stage._extraBinaryWaits.clear(); - try { skip(stage); } - catch(std::exception const& e) { + // 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, - "failed to skip stage {} in ~StageGraph(), got {}", + "the skip of an unsubmitted stage in ~StageGraph() failed, got stage {} of " + "frame {}", stage.id(), - e.what() + stage.frameNumber() ) {} + std::terminate(); } } - _jobs.wait(); + _submissions.wait(); for(auto& frameSlot : _frameSlots) for(auto& stageSlot : frameSlot.stageSlots) { @@ -146,27 +160,38 @@ StageGraph::~StageGraph() { } cth::co::executor_task StageGraph::nextFrame() { - if(_error) - _error.rethrow(); + 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); - - for(auto const& stage : frameSlot.stages) - co_await stage.submitted(); - for(auto const& stage : frameSlot.stages) - co_await stage; + // 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) { + return stage._stageSlot->submitDone.wait(stage.frameNumber()); + } + ) + ); + co_await cth::co::all(std::execution::seq, frameSlot.stages); } frameSlot.frameOpt.reset(); @@ -178,24 +203,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); - detachJob(stage, Stage::Status::SUBMITTED); +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); - detachJob(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); @@ -224,81 +236,76 @@ 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::detachJob(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( - _jobs, - submitJob( - stageSlot, - stage._frameNumber, - std::move(stage._extraWaits), - std::move(stage._extraBinaryWaits), - std::move(retained), - stasisEnd, - targetStatus - ) - ); - stage._status = targetStatus; + catch(...) { _submissions.store(std::current_exception()); } } -cth::co::executor_task StageGraph::submitJob( +cth::co::executor_task StageGraph::submission( dev::StageSlot& stageSlot, uint64_t frameNumber, - vector extraWaits, - semaphore_waits_t extraBinaryWaits, dev::RetainedResources retained, Stasis::pos stasisEnd, Stage::Status targetStatus ) { - auto const& info = stageSlot.submitInfo; - auto const& queue = *stageSlot.queue; + auto& slotSubmit = stageSlot.slotSubmit; + auto& info = stageSlot.submitInfo; + 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 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) + for(auto const& wait : stageSlot.extraWaits) co_await wait.semaphore->submitted(wait.value); + // 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); + }(); + // the stage of the next frame of the slot adds its own + stageSlot.extraWaits.clear(); + 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 { @@ -307,49 +314,88 @@ cth::co::executor_task StageGraph::submitJob( { std::scoped_lock const lock{_statesMutex}; append(stageSlot.primary.states(), queue, prologue, releases); + // 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& image : stageSlot.presents) + epilogueUses.access(image.image(), 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()) - 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 + // 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); prologue.execute(stageSlot.prologue); stageSlot.prologue.end(); } + 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(); + } + + // 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()); - co_await queue.executor().schedule(); - info.submit(queue, extraWaits, extraBinaryWaits, withPrologue); + slotSubmit.addCmdBuffers(info, withPrologue, withEpilogue); + co_await queue.submit(info); submitted = true; } - catch(...) { _error.store(std::current_exception()); } + // 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) { - co_await queue.executor().schedule(); - dev::fallback_submit([&] { info.skip(queue, extraWaits, extraBinaryWaits); }, _error); + else { + // noexcept: a failed start of the skip submit leaves the slot unmarked, the waiters would + // 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, _submissions); + }(); + co_await std::move(skip); + + // the skip signaled the ready points: the spares wait for them + for(auto& image : stageSlot.presents) + handBack(std::move(image)); + stageSlot.presents.clear(); } - stageSlot.submitInfo.next(_config.frameSlots); - stageSlot.semaphore.markSubmitted(frameNumber); + // 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); - // 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(); - - // 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; + // 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; } - 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; + + // 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); { std::scoped_lock const lock{_statesMutex}; @@ -364,8 +410,8 @@ cth::co::executor_task StageGraph::submitJob( } void StageGraph::append( - ResourceStates const& recording, - Queue const& queue, + ResourceTracker const& recording, + Queue& queue, cvk::Barrier& prologue, release_map_t& releases ) { @@ -373,7 +419,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; @@ -382,7 +428,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; @@ -392,11 +438,11 @@ 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; - // 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) { @@ -424,7 +470,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; @@ -440,17 +486,90 @@ 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) { + auto const family = stageSlot.queue->vk().familyIndex(); + auto& releases = stageSlot.presentReleases; + releases.clear(); + + for(auto const& image : stageSlot.presents) { + auto const presentFamily = image.presenter().queue().vk().familyIndex(); + if(presentFamily == family) + continue; + cvk::Image const& vkImage = image.image(); + releases.add( + vkImage.get(), + vkImage.aspectMask(), + dev::release_half(PRESENT_STATE, PRESENT_STATE, family, presentFamily, 0) + ); + } +} + +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& image : stageSlot.presents) { + auto& presenter = image.presenter(); + auto& presentQueue = presenter.queue(); + auto const presentFamily = presentQueue.vk().familyIndex(); + if(presentFamily == family) { + erase(image.image()); + 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 { + 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: 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()) { + 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 + // submissions ended + try { co_await transferredOpt->semaphore->wait(transferredOpt->value); } + catch(...) { _submissions.store(std::current_exception()); } + } + 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()); 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/src/graph/surface.cpp b/jvk/src/graph/surface.cpp new file mode 100644 index 00000000..ce3eb572 --- /dev/null +++ b/jvk/src/graph/surface.cpp @@ -0,0 +1,86 @@ +#include "jvk/graph/surface.hpp" + +#include "jvk/base/core.hpp" +#include "jvk/base/queue.hpp" + +#include "cvk/base/core.hpp" + +#include + + +namespace jvk { +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, _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)); } + +void Surface::create(cvk::Surface surface) { + Core::debug_check(*_core); + cvk::Surface::debug_check(surface); + optDestroy(); + + _surface = std::move(surface); + cvk::Core const& vkCore = *_core; + + try { + auto const extent = _surface.extent(vkCore.physicalDevice()); + if(extent.width > 0 && extent.height > 0) + updateSwapchain(extent, false); + } + catch(...) { + destroy(); + throw; + } +} + +void Surface::destroy() { + debug_check(*this); + + _swapchain.optDestroy(); + _surface.destroy(); +} + +cth::co::executor_task> Surface::acquire() { + debug_check(*this); + + cvk::Core const& vkCore = *_core; + // out of date -> the next round recreates the swapchain + bool outOfDate = false; + for(;;) { + auto const extent = _surface.extent(vkCore.physicalDevice()); + if(extent.width == 0 || extent.height == 0) + co_return std::nullopt; + + updateSwapchain(extent, outOfDate); + auto imageOpt = co_await _swapchain.acquire(); + if(imageOpt.has_value()) + co_return std::move(imageOpt); + outOfDate = true; + } +} + +void Surface::updateSwapchain(VkExtent2D extent, bool outOfDate) { + if(!_swapchain.created()) { + _swapchain.create(swapchainConfig(), extent); + return; + } + if(outOfDate || _swapchain.current().extent() != extent) + _swapchain.recreate(extent); +} + +Swapchain::Config Surface::swapchainConfig() const { + auto config = _config.swapchain; + if(config.minImageCount != 0) + return config; + + cvk::Core const& vkCore = *_core; + config.minImageCount = + _surface.capabilities(vkCore.physicalDevice()).minImageCount + _config.framesInFlight; + return config; +} +} diff --git a/jvk/src/graph/swapchain.cpp b/jvk/src/graph/swapchain.cpp index 4a20e734..8cf003b0 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/utility/exception.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,23 +57,53 @@ 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() { 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; } -cvk::Swapchain::Acquired Swapchain::acquire(cvk::Semaphore const& signal, uint64_t timeout) { +cth::co::executor_task> Swapchain::acquire() { debug_check(*this); - while(retired() != 0 && !_swapchains.front().acquired() && _swapchains.front().presented()) + while(retired() != 0 && _swapchains.front().presenter.finished()) _swapchains.pop_front(); - return current().acquire(signal, timeout); + if(_currentRetired) + co_return std::nullopt; + co_return co_await presenter().acquire(); } } diff --git a/jvk/src/sync/resource_states.cpp b/jvk/src/sync/resource_tracker.cpp similarity index 83% rename from jvk/src/sync/resource_states.cpp rename to jvk/src/sync/resource_tracker.cpp index 4f1e13c5..08aec19e 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" @@ -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,28 +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, scope.queueFamilyIndex}; + 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, - scope.queueFamilyIndex - }; + 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, @@ -63,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, @@ -92,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 @@ -114,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, @@ -151,7 +125,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 +166,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 +197,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 +225,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 +245,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 +265,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 +336,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..302ced7f 100644 --- a/jvk/src/sync/semaphore.cpp +++ b/jvk/src/sync/semaphore.cpp @@ -3,28 +3,30 @@ #include "jvk/base/core.hpp" #include "jvk/sync/timeline_reactor.hpp" +#include #include -#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(await_func cb) const { - _semaphore->core().reactor().await(_semaphore->get(), _value, std::move(cb)); +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); } -bool submitted_awaiter::await_ready() const { return _semaphore->submittedValue() >= _value; } - +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}, - _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 +38,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 +60,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::awaitSubmitted(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/src/sync/timeline_reactor.cpp b/jvk/src/sync/timeline_reactor.cpp index 074d9a8c..c4092bda 100644 --- a/jvk/src/sync/timeline_reactor.cpp +++ b/jvk/src/sync/timeline_reactor.cpp @@ -6,23 +6,20 @@ #include "cvk/utility/vk_error_code.hpp" #include "cvk/utility/vk_exceptions.hpp" -#include #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(); @@ -43,11 +40,11 @@ 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", - _waiters.size() + !_pending.empty(), + "no waiter must be pending, got {}", + _pending.size() ) {} _thread.request_stop(); @@ -66,64 +63,83 @@ void TimelineReactor::destroy() { _thread.join(); _thread = {}; - _waiters.clear(); + _pending.clear(); _error = {}; _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{_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 - auto const it = _waiters.find(vkSemaphore); - bool const first = it == _waiters.end(); - if(first || value < it->second.front().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 - 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); + _pending.push_back({.vkSemaphore = vkSemaphore, .waiter = waiter}); return; } - error = _error; + waiter.error = _error; } - post(std::move(cb), error); + cth::ref_wrapper const failed{waiter}; + post({&failed, 1}); } bool TimelineReactor::pending(VkSemaphore vkSemaphore) const { - std::scoped_lock const lock{_mutex}; - return _waiters.contains(vkSemaphore); + std::scoped_lock const lock{*_mutexPtr}; + 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{}; - vector reached{}; - vector failed{}; + // 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{_mutex}; + std::scoped_lock const lock{*_mutexPtr}; if(stop.stop_requested()) return; vkSemaphores.assign({_wake.get()}); values.assign({_wake.value() + 1}); - for(auto const& [vkSemaphore, waiters] : _waiters) { - vkSemaphores.push_back(vkSemaphore); - values.push_back(waiters.front().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); + } } } @@ -141,69 +157,77 @@ void TimelineReactor::run(std::stop_token stop) { std::numeric_limits::max() ); - { - std::scoped_lock const lock{_mutex}; - - for(auto it = _waiters.begin(); result == VK_SUCCESS && it != _waiters.end();) { - auto& [vkSemaphore, waiters] = *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(); - } - - // erase() keeps the other iterators valid - if(waiters.empty()) - _waiters.erase(it++); - else - ++it; - } + // 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] + ); + } - if(result != VK_SUCCESS) { + reached.clear(); + { + std::scoped_lock const lock{*_mutexPtr}; + + 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); } } - 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() - if(error) { - for(auto& cb : failed) - post(std::move(cb), error); + // the error ends the thread, later waiters get the error at once in await() + if(error) return; - } } } void TimelineReactor::wake() const { _wake.signal(); } -vector TimelineReactor::fail(std::error_code error) const { +void TimelineReactor::fail( + std::error_code error, + vector>& waiters +) const { _error = error; - vector callbacks{}; - for(auto& [vkSemaphore, waiters] : _waiters) - for(auto& waiter : waiters) - callbacks.push_back(std::move(waiter.cb)); - _waiters.clear(); - - return callbacks; + for(auto const& pending : _pending) { + pending.waiter->error = error; + waiters.push_back(pending.waiter); + } + _pending.clear(); } -void TimelineReactor::post(await_func cb, std::error_code error) const { - _workers->post([cb = std::move(cb), error]() mutable { cb(error); }); +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 caller = waiter.caller; + waiter.contextPtr->post([caller] { caller.resume(); }); + } } } 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/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/base/core_test.cpp b/jvk/tests/src/base/core_test.cpp index 861bc8fd..37daaa95 100644 --- a/jvk/tests/src/base/core_test.cpp +++ b/jvk/tests/src/base/core_test.cpp @@ -5,14 +5,13 @@ #include "jvk/base/queue.hpp" #include "jvk/base/queue_sets.hpp" -//TEMP compile check of the phase 6 headers until their sources exist -#include "jvk/graph/presenter.hpp" -#include "jvk/graph/stage_graph.hpp" +#include "jvk/data/sampler_heap.hpp" #include "jvk/sync/semaphore.hpp" #include "jvk/sync/timeline_reactor.hpp" #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" @@ -30,6 +29,7 @@ #include #include #include +#include #include @@ -129,6 +129,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& 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}; @@ -191,21 +219,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/base/queue_test.cpp b/jvk/tests/src/base/queue_test.cpp index b9c17f51..68278c6a 100644 --- a/jvk/tests/src/base/queue_test.cpp +++ b/jvk/tests/src/base/queue_test.cpp @@ -6,18 +6,25 @@ #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/semaphore.hpp" #include "cvk/render/sync/timeline_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 @@ -145,20 +152,25 @@ namespace { } /** - * the queue family ownership transfer of the image, without layout transition when the layouts are equal + * @param[out] coreOpt gets a core with a queue that presents to the surface + * @return `false` -> no device presents to a headless surface */ - [[nodiscard]] cvk::ImageBarrierInfo image_transfer( - cvk::BarrierScope src, - cvk::BarrierScope dst, - VkImageLayout oldLayout, - VkImageLayout newLayout + [[nodiscard]] bool create_present_core( + std::optional& coreOpt, + test::Context const& context, + cvk::Surface const& surface ) { - return cvk::ImageBarrierInfo{ - .src = src, - .dst = dst, - .newLayout = newLayout, - .oldLayout = oldLayout - }; + 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; } /** @@ -187,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{ @@ -220,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)); @@ -229,11 +241,30 @@ 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(), {}}; - 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) @@ -244,7 +275,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); @@ -255,28 +286,31 @@ 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)); + 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 - PrimaryCmdBuffer read{core, receiverFamily}; + PrimaryCmdBuffer read{core, receiverFamily, cvk::create}; read.begin(); 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( @@ -299,12 +333,86 @@ 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 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) + 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{}; - 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) @@ -318,7 +426,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); @@ -331,12 +439,13 @@ 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))); + 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()); @@ -344,16 +453,18 @@ 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) 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) { @@ -375,8 +486,125 @@ 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(); } + +JVK_TEST(Queue, submit_marks_the_jvk_signals) { + test::Context const context{}; + auto& 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& 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, 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 submissions{}; + + context.core.executor().sync_wait( + dev::skip_submit(queue, {.signals = {{.semaphore = semaphore, .value = 1}}}, submissions) + ); + + EXPECT_FALSE(submissions.failed()); + EXPECT_EQ(semaphore.submittedValue(), 1); + static_cast(semaphore).wait(1); +} + +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{}; + if(!create_present_core(coreOpt, context, surface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + auto& queue = core.queue(0); + auto const& executor = core.executor(); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, EXTENT}; + 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( + swapchain.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 in its own job + executor.sync_wait( + queue.submit( + { + .cmdBuffers = {cmd}, + .binaryWaits = {acquired}, + .signals = {{.semaphore = presented, .value = value}}, + .binarySignals = {swapchain.presentSemaphore(*imageIdxOpt)}, + } + ) + ); + EXPECT_EQ(presented.submittedValue(), value); + auto const result = executor.sync_wait(queue.present(swapchain, *imageIdxOpt)); + + EXPECT_TRUE(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) + << "present result: " << result; + // 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/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/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/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/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 49185ec4..f280a13d 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" @@ -193,6 +192,135 @@ 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, 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); + + SamplerHeap moved{std::move(heap)}; + EXPECT_EQ(moved.insert(cvk::SamplerConfig{}).idx().get(), 0); + + 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{}); + 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(); @@ -285,7 +413,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( @@ -318,7 +446,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/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(); diff --git a/jvk/tests/src/graph/presenter_test.cpp b/jvk/tests/src/graph/presenter_test.cpp index 4bcd0b3d..ba4d9c06 100644 --- a/jvk/tests/src/graph/presenter_test.cpp +++ b/jvk/tests/src/graph/presenter_test.cpp @@ -5,28 +5,29 @@ #include "jvk/base/core.hpp" #include "jvk/base/queue.hpp" -#include "jvk/data/image.hpp" -#include "jvk/graph/stage_graph.hpp" +#include "jvk/cmd/cmd_buffer.hpp" #include "jvk/sync/semaphore.hpp" -#include "cvk/base/physical_device.hpp" -#include "cvk/data/img/image_view.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 "cvk/utility/vk_overloads.hpp" -#include +#include + #include #include #include #include -#include #include +#include #include +#include #include #include #include +#include #include @@ -34,26 +35,21 @@ namespace jvk { namespace { using enum cvk::QueueFamilyProperties; - constexpr VkPipelineStageFlags2 ATTACHMENT_OUTPUT = - VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT; - 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}; /** - * creates a core with the queues that present to the surface - * @param[out] coreOpt gets the core + * @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, - std::vector queueProperties = {GRAPHICS | PRESENT}, - size_t driverThreads = 0 + cvk::Surface const& surface ) { auto config = test::Context::CONFIG; - config.vk.queueProperties = std::move(queueProperties); - config.driverThreads = driverThreads; + config.vk.queueProperties = {GRAPHICS | PRESENT}; try { coreOpt.emplace( context.instance, @@ -65,18 +61,6 @@ namespace { return true; } - struct test_exception {}; - - Frame& next_frame(Core const& core, StageGraph& graph) { - 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)); - } - - cth::co::executor_task await_stage(Stage const& stage) { co_await stage; } - /** * signals the semaphore from the host, without a mark */ @@ -91,713 +75,716 @@ namespace { ASSERT_EQ(vk.functions()->vkSignalSemaphore(vk.vkDevice(), &info), VK_SUCCESS); } - - void wait(Core const& core, Stage const& stage) { - core.executor().sync_wait(await_stage(stage)); - } - /** - * @return number of the acquired images of the swapchain + * @return the acquire semaphore of the wait of the image, `nullptr` -> a ready point */ - [[nodiscard]] size_t acquired_images(Presenter const& presenter) { - size_t acquired = 0; - for(uint32_t imageIdx = 0; imageIdx < presenter.swapchain().current().imageCount(); ++ - imageIdx) - if(presenter.swapchain().current().acquired(imageIdx)) - ++acquired; - return acquired; + [[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; } /** - * reads the acquire state of the image in the strand of the presenter queue + * 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` */ - cth::co::executor_task acquired_in_strand( - Queue const& queue, - Presenter const& presenter, - uint32_t imageIdx + void add_waits( + SubmitInfo& info, + Presenter::AcquiredImage const& image, + Semaphore const* gatePtr ) { - co_await queue.executor().schedule(); - co_return presenter.swapchain().current().acquired(imageIdx); + 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())); } /** - * @return the image is no longer acquired before the timeout, e.g. presented + * the submits of a test + * @details the destructor waits until the queue is idle: the command buffers and the + * semaphores go after the gpu */ - [[nodiscard]] bool reaches_unacquired( + 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::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{}; + 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, signals its ready point + * @param gatePtr `nullptr` -> no gate, else the submit waits for its value `1` too + * @return the ready point of a drop, see `Presenter::AcquiredImage::ready()` + */ + SemaphoreSubmitInfo ready( + Presenter::AcquiredImage const& image, + Semaphore const* gatePtr = nullptr + ) { + SubmitInfo info{.signals = {image.ready()}}; + add_waits(info, image, gatePtr); + core->executor().sync_wait(queue->submit(info)); + return image.ready(); + } + + /** + * transitions and presents the image + */ + void present(Presenter& presenter, Presenter::AcquiredImage 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, - Queue const& queue, - Presenter const& presenter, - uint32_t imageIdx + Presenter& presenter ) { - auto const deadline = std::chrono::steady_clock::now() + TIMEOUT; - while(core.executor().sync_wait(acquired_in_strand(queue, presenter, imageIdx))) { - if(std::chrono::steady_clock::now() > deadline) - return false; - std::this_thread::sleep_for(std::chrono::milliseconds{1}); - } - return true; + return core.executor().sync_wait(presenter.acquire()); } - /** - * rendering that clears the image - */ - [[nodiscard]] cvk::RenderingInfo clear_info(SwapchainImage const& image) { - return cvk::RenderingInfo{ - .colorAttachments = { - { - .view = image.view, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .clearValue = {.color = {{0.f, 0.5f, 1.f, 1.f}}}, - } - }, - }; + /** 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); } /** - * records a clear of the image, the scope ends the rendering + * presents, then reports the result for every swapchain */ - void clear(PrimaryCmdBuffer& primary, SwapchainImage const& image) { - auto const rendering = primary.beginRendering(clear_info(image)); + 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; } /** - * 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 - * @return the image + * reports a failure without an enqueue: nothing presents, the fence and the semaphores stay */ - SwapchainImage present_behind_gate( - Core const& core, - Stage& stage, - Presenter& presenter, - Semaphore const& gate - ) { - stage.await(gate, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, 1); - auto const image = acquire(core, presenter, stage); - EXPECT_TRUE(image); - auto const primary = stage.begin(); - clear(*primary, *image); - return *image; + VKAPI_ATTR VkResult VKAPI_CALL unenqueued_present(VkQueue, VkPresentInfoKHR const*) { + return VK_ERROR_OUT_OF_HOST_MEMORY; } - constexpr VkSampleCountFlagBits MSAA_SAMPLES = VK_SAMPLE_COUNT_4_BIT; + /** count of the calls of `out_of_date_acquire()` */ + std::atomic outOfDateAcquires = 0; - [[nodiscard]] bool supports_msaa(Core const& core) { - cvk::Core const& vk = core; - return (vk.physicalDevice().limits().framebufferColorSampleCounts & MSAA_SAMPLES) != 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; } - /** - * multisampled color image of the frames and its view, the rendering resolves it into the swapchain image - */ - struct MsaaTarget { - MsaaTarget(Core const& core, VkFormat format, VkExtent2D extent) : - image{ - core, - { - .format = format, - .usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT - | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT, - .samples = MSAA_SAMPLES, - }, - extent - }, - view{image, {}, cvk::create} {} - - Image image; - cvk::ImageView view; - }; + PFN_vkGetFenceStatus realGetFenceStatus = nullptr; + PFN_vkWaitForFences realWaitForFences = nullptr; - /** - * 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 a new extent: the stage retains the old target, then a new one - * @param[out] msaaOpt the target of the frames - * @return the image - */ - SwapchainImage present_msaa_frame( - Core const& core, - StageGraph& graph, - Presenter& presenter, - std::optional& msaaOpt - ) { - auto& stage = next_frame(core, graph).stage(0); - auto const image = acquire(core, presenter, 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); - } + /** `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; - auto const primary = stage.begin(); - auto const rendering = primary->beginRendering( - { - .colorAttachments = { - { - .view = msaaOpt->view, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .clearValue = {.color = {{0.f, 0.5f, 1.f, 1.f}}}, - .resolveViewPtr = &*image->view, - .resolveMode = VK_RESOLVE_MODE_AVERAGE_BIT, - } - }, - } - ); - return *image; + VKAPI_ATTR VkResult VKAPI_CALL held_fence_status(VkDevice device, VkFence fence) { + return fencesHeld ? VK_NOT_READY : realGetFenceStatus(device, fence); } /** - * 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 the acquire comes before `Stage::begin()` - * @return the image + * ends the hold of the fences, then waits */ - SwapchainImage present_frame(Core const& core, StageGraph& graph, Presenter& presenter) { - auto& stage = next_frame(core, graph).stage(0); - auto const image = acquire(core, presenter, stage); - EXPECT_TRUE(image); - auto const primary = stage.begin(); - clear(*primary, *image); - return *image; + 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); } -} -JVK_TEST(Presenter, frame_loop_clears_and_presents) { - constexpr size_t FRAMES = 6; - test::Context const context{}; - auto 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; - - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; - ASSERT_TRUE(presenter.created()); - ASSERT_TRUE(presenter.swapchain().created()); - - for(size_t i = 0; i < FRAMES; ++i) { - auto const image = present_frame(core, graph, presenter); - EXPECT_EQ(image.extent, test::HEADLESS_EXTENT); - EXPECT_LT(image.imageIdx, presenter.swapchain().current().imageCount()); + /** + * 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()); } - presenter.destroy(); - EXPECT_FALSE(presenter.created()); -} + /** + * 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(); } -JVK_TEST(Presenter, frame_loop_with_driver_threads_presents) { - constexpr size_t FRAMES = 6; - test::Context const context{}; - auto surface = test::headless_surface(context.instance); - std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface, {GRAPHICS | PRESENT}, 2)) - GTEST_SKIP() << "no device presents to a headless surface"; - auto& core = *coreOpt; + cth::ref_wrapper function; + cth::ref_wrapper real; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + Hook(Hook const& other) = delete; + Hook& operator=(Hook const& other) = delete; + }; - for(size_t i = 0; i < FRAMES; ++i) - EXPECT_EQ(present_frame(core, graph, presenter).extent, test::HEADLESS_EXTENT); + /** + * 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, extent_0_gives_no_image_until_the_extent_is_larger) { +JVK_TEST(Presenter, acquire_and_present_round_trips) { + constexpr size_t FRAMES = 8; test::Context const context{}; - std::atomic windowExtent{VkExtent2D{0, 0}}; - auto surface = test::headless_surface( - context.instance, - [&windowExtent] { return windowExtent.load(); } - ); + 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); - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; - EXPECT_FALSE(presenter.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); + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + EXPECT_EQ(presenter.framesInFlight(), 2); { - auto const image = acquire(core, presenter, stage); - EXPECT_FALSE(image); - auto const primary = stage.begin(); + 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)); + } } - EXPECT_EQ(stage.status(), Stage::Status::SUBMITTED); - windowExtent = VkExtent2D{32, 24}; - auto const image = present_frame(core, graph, presenter); - EXPECT_EQ(image.extent, (VkExtent2D{32, 24})); - EXPECT_TRUE(presenter.swapchain().created()); + // the queue is idle: the present fences signaled + EXPECT_TRUE(presenter.finished()); } -JVK_TEST(Presenter, new_extent_recreates_the_swapchain) { +JVK_TEST(Presenter, presents_follow_the_acquire_order) { test::Context const context{}; - std::atomic windowExtent{VkExtent2D{32, 32}}; - auto surface = test::headless_surface( - context.instance, - [&windowExtent] { return windowExtent.load(); } - ); + 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)); - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; - - EXPECT_EQ(present_frame(core, graph, presenter).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})); + core.executor().sync_wait(presenter.present(std::move(*firstOpt))); + EXPECT_TRUE(presentedSignal.try_acquire_for(TIMEOUT)); + presenting.join(); - // the next frames present on the new swapchain - EXPECT_EQ(present_frame(core, graph, presenter).extent, (VkExtent2D{48, 40})); + EXPECT_EQ(presentedIndices, (std::vector{firstIdx, secondIdx})); } -JVK_TEST(Presenter, multisampled_frames_resolve_into_the_image_and_present) { - constexpr size_t FRAMES = 4; +JVK_TEST(Presenter, drop_spares_the_image_with_its_acquire_semaphore) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + 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; - if(!supports_msaa(core)) - GTEST_SKIP() << "no 4x msaa for color attachments"; - - // 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)}; - - // 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, - test::HEADLESS_EXTENT - ); + 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); + // 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); + 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, recreation_retains_the_multisampled_target_of_the_old_extent) { +JVK_TEST(Presenter, drop_with_a_ready_point_spares_the_image_behind_it) { test::Context const context{}; - std::atomic windowExtent{VkExtent2D{32, 32}}; - auto surface = test::headless_surface( - context.instance, - [&windowExtent] { return windowExtent.load(); } - ); + 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; - if(!supports_msaa(core)) - GTEST_SKIP() << "no 4x msaa for color attachments"; - - std::optional msaaOpt{}; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + auto& queue = core.queue(0); - EXPECT_EQ(present_msaa_frame(core, graph, presenter, msaaOpt).extent, (VkExtent2D{32, 32})); + 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}; - // 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(msaaOpt->image.extent(), (VkExtent2D{48, 40})); + 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)); + 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 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})); + // 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, acquire_waits_for_the_present_before) { +JVK_TEST(Presenter, ready_point_of_the_last_acquire_semaphore_holds_the_acquire_back) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + 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); - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + 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& first = next_frame(core, graph).stage(0); - present_behind_gate(core, first, presenter, gate); + auto droppedOpt = acquire(core, presenter); + ASSERT_TRUE(droppedOpt.has_value()); + submits.ready(*droppedOpt, &gate); + presenter.drop(std::move(*droppedOpt)); + auto spareOpt = acquire(core, presenter); + ASSERT_TRUE(spareOpt.has_value()); - // 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); + // no spare, the only acquire semaphore waits for the ready point + std::optional nextOpt{}; std::binary_semaphore acquiredSignal{0}; - size_t acquiredImages = 0; - std::jthread frame{ + std::jthread acquiring{ [&] { - auto const image = acquire(core, presenter, second); - acquiredImages = acquired_images(presenter); + nextOpt = acquire(core, presenter); acquiredSignal.release(); - EXPECT_TRUE(image); - auto const primary = second.begin(); - if(image) - clear(*primary, *image); } }; + EXPECT_FALSE(acquiredSignal.try_acquire_for(PENDING)); - EXPECT_FALSE(acquiredSignal.try_acquire_for(std::chrono::milliseconds{50})); - - // 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); + acquiring.join(); + ASSERT_TRUE(nextOpt.has_value()); + EXPECT_NE(nextOpt->imageIdx(), spareOpt->imageIdx()); - present_frame(core, graph, presenter); + submits.present(presenter, std::move(*spareOpt)); + submits.present(presenter, std::move(*nextOpt)); } -JVK_TEST(Presenter, recreation_retires_the_old_swapchain_until_its_presents_ended) { +JVK_TEST(Presenter, destroyed_image_is_dropped) { test::Context const context{}; - std::atomic windowExtent{VkExtent2D{32, 32}}; - auto surface = test::headless_surface( - context.instance, - [&windowExtent] { return windowExtent.load(); } - ); + 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); - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; - - EXPECT_EQ(present_frame(core, graph, presenter).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); + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; - // 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); + 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, scope_unacquire_leaves_the_image_to_the_next_acquire) { +JVK_TEST(Presenter, destructor_releases_the_spares) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + 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); - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; - - auto& stage = next_frame(core, graph).stage(0); + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + auto const imageCount = swapchain.imageCount(); { - auto image = acquire(core, presenter, stage); - ASSERT_TRUE(image); - image.unacquire(); - - // the submit waits for the acquire semaphore - auto const primary = stage.begin(); + 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()); + submits.ready(*secondOpt); + firstOpt.reset(); + presenter.drop(std::move(*secondOpt)); } - // the scoped_acquire did nothing at its end, the image stays acquired - EXPECT_EQ(acquired_images(presenter), 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); - ASSERT_TRUE(image); - EXPECT_EQ(acquired_images(presenter), 1); - auto const primary = next.begin(); - clear(*primary, *image); + // 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)); } - - present_frame(core, graph, presenter); + // the destructor of the images drops them, the destructor of the presenter releases them } -JVK_TEST(Presenter, next_acquire_after_a_skipped_stage_unacquires_the_image) { +JVK_TEST(Presenter, not_ready_try_falls_back_until_a_hand_back) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + 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; - - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; - - // 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); - ASSERT_TRUE(image); - clear(*primary, *image); - - // the skip discards the recording and waits for the acquire semaphore - stage.skip(); + 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)); } - EXPECT_EQ(stage.status(), Stage::Status::SKIPPED); - EXPECT_EQ(acquired_images(presenter), 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); - ASSERT_TRUE(image); - EXPECT_EQ(acquired_images(presenter), 1); - auto const primary = next.begin(); - clear(*primary, *image); - } + // 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)); - present_frame(core, graph, presenter); + 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, image_scope_ending_before_the_submit_leaves_the_image_to_the_next_acquire) { +JVK_TEST(Presenter, fallback_waits_for_the_present_fence_of_the_last_acquire_semaphore) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + 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); - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; - - auto& stage = next_frame(core, graph).stage(0); - { - auto const image = acquire(core, presenter, stage); - ASSERT_TRUE(image); - } - EXPECT_EQ(acquired_images(presenter), 1); + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 1}; + Submits submits{core, queue}; - // the submit waits for the acquire semaphore, nothing uses the image - { - auto const primary = stage.begin(); - } + auto firstOpt = acquire(core, presenter); + ASSERT_TRUE(firstOpt.has_value()); + submits.present(presenter, std::move(*firstOpt)); - // the next acquire waits for the submit on the gpu and gives the image back first - auto& next = next_frame(core, graph).stage(0); + // 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{}; { - auto const image = acquire(core, presenter, next); - ASSERT_TRUE(image); - EXPECT_EQ(acquired_images(presenter), 1); - auto const primary = next.begin(); - clear(*primary, *image); + Hook const status{table.vkGetFenceStatus, held_fence_status, realGetFenceStatus}; + Hook const wait{table.vkWaitForFences, releasing_fence_wait, realWaitForFences}; + nextOpt = acquire(core, presenter); } - - present_frame(core, graph, 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, present_inside_the_rendering_scope_submits_and_presents_once) { +JVK_TEST(Presenter, failed_present_arrives_once_at_the_next_acquire) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + 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); - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; - auto& stage = next_frame(core, graph).stage(0); { - auto image = acquire(core, presenter, stage); - ASSERT_TRUE(image); - 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); + 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"; } - wait(core, stage); + catch(cvk::vk_result_exception const& e) { EXPECT_EQ(e.vkResult(), VK_ERROR_SURFACE_LOST_KHR); } - present_frame(core, graph, presenter); + auto imageOpt = acquire(core, presenter); + ASSERT_TRUE(imageOpt.has_value()); + submits.present(presenter, std::move(*imageOpt)); } -JVK_TEST(Presenter, moved_scopes_act_once) { +JVK_TEST(Presenter, present_without_an_enqueue_leaves_no_fence_pending) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + 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); - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; - 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 const movedImage = std::move(image); - ASSERT_TRUE(movedImage); - auto primary = stage.begin(); - auto const movedPrimary = std::move(primary); - clear(*movedPrimary, *movedImage); + 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))); } - EXPECT_EQ(stage.status(), Stage::Status::SUBMITTED); - wait(core, stage); - present_frame(core, graph, presenter); -} - -JVK_TEST(Presenter, exception_in_the_recording_submits_and_presents_nothing) { - test::Context const context{}; - auto 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; - - StageGraph graph{core, {.stages = {{.queueIdx = 0}}, .frameSlots = 2}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; - - 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 primary = stage.begin(); - auto const rendering = primary->beginRendering(clear_info(*image)); - if(i == 2) { - stagePtr = &stage; - imageIdx = image->imageIdx; - throw test_exception{}; - } - } + [[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); } - catch(test_exception const&) {} - - ASSERT_NE(stagePtr, nullptr); - EXPECT_EQ(stagePtr->status(), Stage::Status::UNSUBMITTED); - EXPECT_TRUE(presenter.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); + // the image stays acquired: the presenter has work left, no fence of it is pending + EXPECT_FALSE(presenter.finished()); + fencesHeld = false; + fenceWaits = 0; { - auto const image = acquire(core, presenter, stage); - ASSERT_TRUE(image); - EXPECT_EQ(acquired_images(presenter), 1); - auto const primary = stage.begin(); - clear(*primary, *image); + auto& table = device_table(core); + Hook const wait{table.vkWaitForFences, releasing_fence_wait, realWaitForFences}; + presenter.waitPresents(); } + EXPECT_EQ(fenceWaits, 0); - present_frame(core, graph, presenter); + // 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, exception_after_the_submit_presents_the_image) { +JVK_TEST(Presenter, rejected_present_leaves_its_fence_pending) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + 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); - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; - auto& stage = next_frame(core, graph).stage(0); - std::optional imageIdxOpt = std::nullopt; - try { - auto const image = acquire(core, presenter, stage); - auto const primary = stage.begin(); - if(image) { - imageIdxOpt = image->imageIdx; - clear(*primary, *image); - } - stage.submit(); - throw test_exception{}; + // 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)); } - catch(test_exception const&) {} - ASSERT_TRUE(imageIdxOpt.has_value()); - 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)); - wait(core, stage); - - present_frame(core, graph, presenter); + 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, exception_propagated_to_the_end_destroys_graph_and_presenter) { +JVK_TEST(Presenter, out_of_date_present_gives_no_image_from_then_on) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + 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); - auto const run = [&core, &surface] { - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(0), {}, std::move(surface)}; - for(size_t i = 0;; ++i) { - auto& stage = next_frame(core, graph).stage(0); - auto const image = acquire(core, presenter, stage); - auto const primary = stage.begin(); - auto const rendering = primary->beginRendering(clear_info(*image)); - if(i == 2) - throw test_exception{}; - } - }; - EXPECT_THROW(run(), test_exception); -} + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; -JVK_TEST(Presenter, present_queue_of_the_same_family) { - constexpr size_t FRAMES = 4; - test::Context const context{}; - auto surface = test::headless_surface(context.instance); - std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface, {GRAPHICS, GRAPHICS | PRESENT})) - GTEST_SKIP() << "no device presents to a headless surface"; - auto& core = *coreOpt; - if(&core.queue(0) == &core.queue(1) - || 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}}}}; - Presenter presenter{core, core.queue(1), {}, std::move(surface)}; + { + PresentHook const hook{core, failing_present}; + auto imageOpt = acquire(core, presenter); + ASSERT_TRUE(imageOpt.has_value()); + submits.present(presenter, std::move(*imageOpt)); + } - for(size_t i = 0; i < FRAMES; ++i) - present_frame(core, graph, presenter); + EXPECT_FALSE(acquire(core, presenter).has_value()); + EXPECT_FALSE(acquire(core, presenter).has_value()); } -JVK_TEST(Presenter, present_queue_of_another_family) { - constexpr size_t FRAMES = 4; +JVK_TEST(Presenter, out_of_date_acquire_gives_no_image_from_then_on) { test::Context const context{}; - auto surface = test::headless_surface(context.instance); + auto const surface = test::headless_surface(context.instance); std::optional coreOpt{}; - if(!create_present_core(coreOpt, context, surface, {GRAPHICS, COMPUTE | PRESENT})) + if(!create_present_core(coreOpt, context, surface)) 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()) - GTEST_SKIP() << "needs two queue families, e.g. ANV_QUEUE_OVERRIDE=gc=2,c=1"; + auto& queue = core.queue(0); + + cvk::Swapchain swapchain{core, queue.vk(), surface, {}, test::HEADLESS_EXTENT}; + Presenter presenter{queue, swapchain, 2}; + Submits submits{core, queue}; - StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; - Presenter presenter{core, core.queue(1), {}, std::move(surface)}; + auto imageOpt = acquire(core, presenter); + ASSERT_TRUE(imageOpt.has_value()); - for(size_t i = 0; i < FRAMES; ++i) - present_frame(core, graph, presenter); - presenter.destroy(); + 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); - // 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{})); - EXPECT_EQ(next.value, FRAMES + 1); - stageQueue.waitIdle(); + // the image acquired before still presents + submits.present(presenter, std::move(*imageOpt)); } } diff --git a/jvk/tests/src/graph/stage_graph_test.cpp b/jvk/tests/src/graph/stage_graph_test.cpp index 9346434b..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 @@ -235,7 +237,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(); @@ -333,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) { @@ -438,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}); @@ -451,24 +452,26 @@ 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) { 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, @@ -476,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, {}}; @@ -517,7 +546,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}}}) ); @@ -527,6 +556,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{}; @@ -592,7 +642,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}}; @@ -610,7 +660,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( @@ -622,12 +672,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); @@ -692,7 +743,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(); @@ -717,7 +768,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(); @@ -726,7 +777,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(); @@ -756,7 +807,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); @@ -773,8 +825,8 @@ 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 const next = core.executor().sync_wait(writerQueue.release(cvk::Barrier{})); + auto& writerQueue = core.queue(0); + auto const next = core.executor().sync_wait(writerQueue.transfer(cvk::Barrier{})); EXPECT_EQ(next.value, 2); writerQueue.waitIdle(); } @@ -782,7 +834,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}}}}; @@ -814,7 +866,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(); } diff --git a/jvk/tests/src/graph/surface_test.cpp b/jvk/tests/src/graph/surface_test.cpp new file mode 100644 index 00000000..e0f78fe8 --- /dev/null +++ b/jvk/tests/src/graph/surface_test.cpp @@ -0,0 +1,1157 @@ +#include "jvk/graph/surface.hpp" + +#include "context.hpp" +#include "test.hpp" + +#include "jvk/base/core.hpp" +#include "jvk/base/queue.hpp" +#include "jvk/data/image.hpp" +#include "jvk/graph/stage_graph.hpp" +#include "jvk/sync/semaphore.hpp" + +#include "cvk/base/physical_device.hpp" +#include "cvk/data/img/image_view.hpp" +#include "cvk/render/sync/barrier.hpp" +#include "cvk/utility/vk_exceptions.hpp" +#include "cvk/utility/vk_overloads.hpp" + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace jvk { +namespace { + using enum cvk::QueueFamilyProperties; + + constexpr VkPipelineStageFlags2 ATTACHMENT_OUTPUT = + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT; + + constexpr auto TIMEOUT = std::chrono::seconds{5}; + + /** + * creates a core with the queues that present to the surface + * @param[out] coreOpt gets the core + * @return `false` -> no device presents to a headless surface + */ + [[nodiscard]] bool create_present_core( + std::optional& coreOpt, + test::Context const& context, + cvk::Surface const& windowSurface, + std::vector queueProperties = {GRAPHICS | PRESENT}, + size_t driverThreads = 0 + ) { + auto config = test::Context::CONFIG; + config.vk.queueProperties = std::move(queueProperties); + config.driverThreads = driverThreads; + try { + coreOpt.emplace( + context.instance, + std::move(config), + std::array{cth::ref_wrapper{windowSurface}} + ); + } + catch(cvk::cvk_exception const&) { return false; } + return true; + } + + struct test_exception {}; + + Frame& next_frame(Core const& core, StageGraph& graph) { + return core.executor().sync_wait(graph.nextFrame()); + } + + [[nodiscard]] std::optional acquire( + Core const& core, + Frame& frame, + Surface& surface, + Stage& stage + ) { + 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( + frame.acquire(surface, acquireStage, presentStage, ATTACHMENT_OUTPUT) + ); + } + + cth::co::executor_task await_stage(Stage const& stage) { co_await stage; } + + /** + * 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); + } + + + void wait(Core const& core, Stage const& stage) { + 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; + } + + /** + * 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 + */ + 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; + }; + + /** + * @return number of the acquired images of the current swapchain + */ + [[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( + AcquireTracker const& tracker, + Surface const& surface, + uint32_t imageIdx + ) { + auto const deadline = std::chrono::steady_clock::now() + TIMEOUT; + 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}); + } + return true; + } + + /** + * rendering that clears the image + */ + [[nodiscard]] cvk::RenderingInfo clear_info(SwapchainImage const& image) { + return cvk::RenderingInfo{ + .colorAttachments = { + { + .view = image.view, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .clearValue = {.color = {{0.f, 0.5f, 1.f, 1.f}}}, + } + }, + }; + } + + /** + * records a clear of the image, the scope ends the rendering + */ + void clear(PrimaryCmdBuffer& primary, SwapchainImage const& image) { + auto const rendering = primary.beginRendering(clear_info(image)); + } + + /** + * 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, + 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, frame, surface, stage); + EXPECT_TRUE(image); + auto const primary = stage.begin(); + clear(*primary, *image); + return *image; + } + + constexpr VkSampleCountFlagBits MSAA_SAMPLES = VK_SAMPLE_COUNT_4_BIT; + + [[nodiscard]] bool supports_msaa(Core const& core) { + cvk::Core const& vk = core; + return (vk.physicalDevice().limits().framebufferColorSampleCounts & MSAA_SAMPLES) != 0; + } + + /** + * multisampled color image of the frames and its view, the rendering resolves it into the swapchain image + */ + struct MsaaTarget { + MsaaTarget(Core const& core, VkFormat format, VkExtent2D extent) : + image{ + core, + { + .format = format, + .usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT + | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT, + .samples = MSAA_SAMPLES, + }, + extent + }, + view{image, {}, cvk::create} {} + + Image image; + cvk::ImageView view; + }; + + /** + * 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 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 + */ + SwapchainImage present_msaa_frame( + Core const& core, + StageGraph& graph, + Surface& surface, + std::optional& msaaOpt + ) { + 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()) { + stage.retain(std::move(msaaOpt->view)); + stage.retain(std::move(msaaOpt->image)); + } + msaaOpt.emplace(core, surface.swapchain().current().format(), image->extent); + } + + auto const primary = stage.begin(); + auto const rendering = primary->beginRendering( + { + .colorAttachments = { + { + .view = msaaOpt->view, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .clearValue = {.color = {{0.f, 0.5f, 1.f, 1.f}}}, + .resolveViewPtr = &*image->view, + .resolveMode = VK_RESOLVE_MODE_AVERAGE_BIT, + } + }, + } + ); + return *image; + } + + /** + * acquires, clears and presents the image of the stage in the next frame + * @details only the scope: `scoped_submit` submits, the submission presents + * @details the acquire comes before `Stage::begin()` + * @return the image + */ + SwapchainImage present_frame(Core const& core, StageGraph& graph, Surface& surface) { + 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); + 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 + */ + 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, frame, 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) { + constexpr size_t FRAMES = 6; + 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; + + // 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()); + + for(size_t i = 0; i < FRAMES; ++i) { + auto const image = present_frame(core, graph, surface); + EXPECT_EQ(image.extent, test::HEADLESS_EXTENT); + EXPECT_LT(image.imageIdx, surface.swapchain().current().imageCount()); + } +} + +JVK_TEST(Surface, destroy_after_the_graph_of_the_stages) { + 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()); +} + +JVK_TEST(Surface, frame_loop_with_driver_threads_presents) { + constexpr size_t FRAMES = 6; + test::Context const context{}; + auto windowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, windowSurface, {GRAPHICS | PRESENT}, 2)) + 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}}}}; + + for(size_t i = 0; i < FRAMES; ++i) + EXPECT_EQ(present_frame(core, graph, surface).extent, test::HEADLESS_EXTENT); +} + +JVK_TEST(Surface, extent_0_gives_no_image_until_the_extent_is_larger) { + test::Context const context{}; + std::atomic windowExtent{VkExtent2D{0, 0}}; + auto windowSurface = test::headless_surface( + context.instance, + [&windowExtent] { return windowExtent.load(); } + ); + 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}}}}; + EXPECT_FALSE(surface.swapchain().created()); + + // no image, no wait, no present: the stage submits without the image + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); + { + auto const image = acquire(core, frame, surface, stage); + EXPECT_FALSE(image.has_value()); + auto const primary = stage.begin(); + } + EXPECT_EQ(stage.status(), Stage::Status::SUBMITTED); + + windowExtent = VkExtent2D{32, 24}; + auto const image = present_frame(core, graph, surface); + EXPECT_EQ(image.extent, (VkExtent2D{32, 24})); + EXPECT_TRUE(surface.swapchain().created()); +} + +JVK_TEST(Surface, new_extent_recreates_the_swapchain) { + test::Context const context{}; + std::atomic windowExtent{VkExtent2D{32, 32}}; + auto windowSurface = test::headless_surface( + context.instance, + [&windowExtent] { return windowExtent.load(); } + ); + 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}}}}; + + EXPECT_EQ(present_frame(core, graph, surface).extent, (VkExtent2D{32, 32})); + + windowExtent = 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, surface).extent, (VkExtent2D{48, 40})); +} + +JVK_TEST(Surface, multisampled_frames_resolve_into_the_image_and_present) { + 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; + if(!supports_msaa(core)) + GTEST_SKIP() << "no 4x msaa for color attachments"; + + // before the graph: the target lives until the gpu finished the frames + std::optional msaaOpt{}; + 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) + EXPECT_EQ( + present_msaa_frame(core, graph, surface, msaaOpt).extent, + test::HEADLESS_EXTENT + ); +} + +JVK_TEST(Surface, recreation_retains_the_multisampled_target_of_the_old_extent) { + test::Context const context{}; + std::atomic windowExtent{VkExtent2D{32, 32}}; + auto windowSurface = test::headless_surface( + context.instance, + [&windowExtent] { return windowExtent.load(); } + ); + std::optional coreOpt{}; + if(!create_present_core(coreOpt, context, windowSurface)) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + if(!supports_msaa(core)) + GTEST_SKIP() << "no 4x msaa for color attachments"; + + std::optional msaaOpt{}; + 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})); + + // the new extent recreates the swapchain, the frame retains the old target + windowExtent = 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, surface, msaaOpt).extent, (VkExtent2D{48, 40})); +} + +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{}; + 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}}}}; + Semaphore const gate{core, cvk::create}; + + 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& secondFrame = next_frame(core, graph); + auto& second = secondFrame.stage(0); + std::optional secondImageOpt{}; + std::binary_semaphore acquiredSignal{0}; + std::jthread frame{ + [&] { + secondImageOpt = acquire(core, secondFrame, surface, second); + acquiredSignal.release(); + } + }; + 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); + frame.join(); + 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_presenter_finished) { + test::Context const context{}; + std::atomic windowExtent{VkExtent2D{32, 32}}; + auto windowSurface = test::headless_surface( + context.instance, + [&windowExtent] { return windowExtent.load(); } + ); + 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}}}}; + + EXPECT_EQ(present_frame(core, graph, surface).extent, (VkExtent2D{32, 32})); + + // 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 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, skipped_stage_drops_the_image_for_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; + AcquireTracker const tracker{core}; + + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + // 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& frame = next_frame(core, graph); + auto& stage = frame.stage(0); + uint32_t imageIdx = 0; + { + auto const primary = stage.begin(); + auto const image = acquire(core, frame, 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 + stage.skip(); + } + EXPECT_EQ(stage.status(), Stage::Status::SKIPPED); + EXPECT_EQ(acquired_images(tracker, surface), 1); + + // the dropped image comes first, it waits for the skip on the gpu: no validation error + auto& nextFrame = next_frame(core, graph); + auto& next = nextFrame.stage(0); + { + 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); + auto const primary = next.begin(); + clear(*primary, *image); + } + + 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); + std::optional coreOpt{}; + 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}}}}; + + // the epilogue transitions the image from VK_IMAGE_LAYOUT_UNDEFINED + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); + uint32_t imageIdx = 0; + { + auto const image = acquire(core, frame, surface, stage); + ASSERT_TRUE(image.has_value()); + imageIdx = image->imageIdx; + auto const primary = stage.begin(); + } + EXPECT_TRUE(reaches_unacquired(tracker, surface, imageIdx)); + wait(core, stage); + + present_frame(core, graph, surface); +} + +JVK_TEST(Surface, exception_in_the_recording_submits_and_presents_nothing) { + 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; + AcquireTracker const tracker{core}; + + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + // 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; + try { + for(size_t i = 0;; ++i) { + 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) { + stagePtr = &stage; + imageIdx = image->imageIdx; + throw test_exception{}; + } + } + } + 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::SKIPPED); + EXPECT_TRUE(tracker.acquired(surface.swapchain().current(), imageIdx)); + + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); + { + 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); + auto const primary = stage.begin(); + clear(*primary, *image); + } + + present_frame(core, graph, surface); +} + +JVK_TEST(Surface, exception_after_the_submit_presents_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; + AcquireTracker const tracker{core}; + + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; + + auto& frame = next_frame(core, graph); + auto& stage = frame.stage(0); + std::optional imageIdxOpt = std::nullopt; + try { + auto const image = acquire(core, frame, surface, stage); + auto const primary = stage.begin(); + if(image) { + imageIdxOpt = image->imageIdx; + clear(*primary, *image); + } + stage.submit(); + throw test_exception{}; + } + catch(test_exception const&) {} + ASSERT_TRUE(imageIdxOpt.has_value()); + EXPECT_EQ(stage.status(), Stage::Status::SUBMITTED); + + // the stage is submitted: its submission presents the image + EXPECT_TRUE(reaches_unacquired(tracker, surface, *imageIdxOpt)); + wait(core, stage); + + present_frame(core, graph, surface); +} + +JVK_TEST(Surface, exception_propagated_to_the_end_destroys_graph_and_surface) { + 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 const run = [&core, &windowSurface] { + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + StageGraph graph{core, {.stages = {{.queueIdx = 0}}}}; + for(size_t i = 0;; ++i) { + 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) + throw test_exception{}; + } + }; + 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)}; + // 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 + 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& 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, 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); } + 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{}; + 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; + AcquireTracker const tracker{core}; + + 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, frame, 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(tracker.acquired(surface.swapchain().current(), imageIdx)); + { + auto const ui = frame[UI].begin(); + } + EXPECT_TRUE(reaches_unacquired(tracker, 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; + AcquireTracker const tracker{core}; + + Surface surface{core, core.queue(0), {}, std::move(windowSurface)}; + // 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, frame, 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 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, next, 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); + } + { + 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, frame, 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&) {} + + // 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); +} + +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; + AcquireTracker const tracker{core}; + + 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, 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()); + { + 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(tracker, first, firstImage->imageIdx)); + EXPECT_TRUE(reaches_unacquired(tracker, second, secondImage->imageIdx)); + } +} + +JVK_TEST(Surface, present_queue_of_the_same_family) { + 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, GRAPHICS | PRESENT})) + GTEST_SKIP() << "no device presents to a headless surface"; + auto& core = *coreOpt; + if(&core.queue(0) == &core.queue(1) + || 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"; + + 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); +} + +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, frame, 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{}; + auto windowSurface = test::headless_surface(context.instance); + std::optional coreOpt{}; + 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); + 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"; + + 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(); + + // 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); + surfaceQueue.waitIdle(); +} +} diff --git a/jvk/tests/src/graph/swapchain_test.cpp b/jvk/tests/src/graph/swapchain_test.cpp index befa651e..ec8ceb30 100644 --- a/jvk/tests/src/graph/swapchain_test.cpp +++ b/jvk/tests/src/graph/swapchain_test.cpp @@ -6,11 +6,10 @@ #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 + #include #include @@ -46,19 +45,33 @@ namespace { return true; } + /** the functions of the device table before the hooks */ + PFN_vkCreateSwapchainKHR realCreateSwapchain = nullptr; + + 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 */ - [[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()); } } @@ -70,15 +83,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()); @@ -92,22 +109,60 @@ 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); - auto& old = swapchain.current(); - auto const oldIdx = acquire(core, swapchain); - // the retired swapchain holds an acquired image: the acquire keeps it + // 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.recreate({32, 32}); - auto const currentIdx = acquire(core, swapchain); + auto firstOpt = acquire(core, swapchain); + ASSERT_TRUE(firstOpt.has_value()); EXPECT_EQ(swapchain.retired(), 1); - old.unacquire(std::array{oldIdx}); - swapchain.current().unacquire(std::array{currentIdx}); - static_cast(acquire(core, swapchain)); + // 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); + firstOpt.reset(); + secondOpt.reset(); 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()); + imageOpt.reset(); +} } 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/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..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.awaitSubmitted( - 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/jvk/tests/src/sync/timeline_reactor_test.cpp b/jvk/tests/src/sync/timeline_reactor_test.cpp index 94e6fdbc..2ecfb1ac 100644 --- a/jvk/tests/src/sync/timeline_reactor_test.cpp +++ b/jvk/tests/src/sync/timeline_reactor_test.cpp @@ -7,13 +7,21 @@ #include "cvk/render/sync/timeline_semaphore.hpp" +#include +#include #include +#include +#include #include +#include #include #include #include +#include #include +#include +#include #include @@ -21,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; } @@ -88,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()); @@ -110,7 +181,28 @@ JVK_TEST(TimelineReactor, create_and_destroy) { EXPECT_TRUE(reactor.created()); } -JVK_TEST(TimelineReactor, gpu_signal_calls_the_callback_on_a_worker) { +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}; + + TimelineReactor moved{std::move(reactor)}; + TimelineReactor other{context.core}; + other = std::move(moved); + other.create(); + EXPECT_TRUE(other.created()); + + auto result = await_value(other, workers, semaphore.get(), 1); + host_signal(semaphore, 1); + + ASSERT_TRUE(reached(result)); + auto const [error, onWorker] = result.get(); + EXPECT_FALSE(error); + EXPECT_TRUE(onWorker); +} + +JVK_TEST(TimelineReactor, gpu_signal_resumes_the_waiter_on_its_context) { test::Context const context{}; cvk::TimelineSemaphore const semaphore{context.core, cvk::create}; @@ -150,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}; @@ -182,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)); @@ -192,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}; 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/rgfw.cmake b/lib/cmake/rgfw.cmake index b0651fb9..a7fefa76 100644 --- a/lib/cmake/rgfw.cmake +++ b/lib/cmake/rgfw.cmake @@ -16,12 +16,15 @@ 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 target_compile_definitions(rgfw INTERFACE NOMINMAX) - # RGFW loads winmm, dwmapi, shcore and opengl32 at run time - target_link_libraries(rgfw INTERFACE gdi32 user32 shell32) + # 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) @@ -36,7 +39,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 +47,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 +75,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/cth b/lib/cth index e970abb6..e92f8269 160000 --- a/lib/cth +++ b/lib/cth @@ -1 +1 @@ -Subproject commit e970abb6a453473d5bf7a21630460ddfa7eb9cf2 +Subproject commit e92f826967a0491f1f33daecd5d730daeb26a01b diff --git a/lib/cth_cmake b/lib/cth_cmake index b50690b6..22e80160 160000 --- a/lib/cth_cmake +++ b/lib/cth_cmake @@ -1 +1 @@ -Subproject commit b50690b6f4e5b3eb6b796a92271d5801c808291f +Subproject commit 22e80160faebd0e31ff9139341f7a93ec6c17c5e diff --git a/lib/rgfw b/lib/rgfw index 70c07fd8..ad849de5 160000 --- a/lib/rgfw +++ b/lib/rgfw @@ -1 +1 @@ -Subproject commit 70c07fd8ff4d2d9c3817a5fbca7d6f2b7c81e06e +Subproject commit ad849de5a1520638de4a8c7c1ceadaef97c90fa9 diff --git a/timgui/CMakeLists.txt b/timgui/CMakeLists.txt new file mode 100644 index 00000000..6a69374f --- /dev/null +++ b/timgui/CMakeLists.txt @@ -0,0 +1,79 @@ +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 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") +set(TIMGUI_SHADER_HEADERS "") + +foreach (GLSL_FILE ${TIMGUI_GLSL}) + get_filename_component(GLSL_NAME ${GLSL_FILE} NAME) + 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(HEADER_FILE "${TIMGUI_GENERATED_SRC}/shaders/${HEADER_NAME}.hpp") + + add_custom_command( + OUTPUT ${HEADER_FILE} + COMMAND ${CMAKE_COMMAND} + -DSPIRV_FILE=${SPIRV_FILE} -DHEADER_FILE=${HEADER_FILE} -DARRAY_NAME=${ARRAY_NAME} + -P ${TIMGUI_SPIRV_HEADER_SCRIPT} + DEPENDS ${SPIRV_FILE} ${TIMGUI_SPIRV_HEADER_SCRIPT} + COMMENT "Embedding ${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}) +add_dependencies(timgui timgui_shaders) + +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..4ea924ab --- /dev/null +++ b/timgui/cmake/spirv_header.cmake @@ -0,0 +1,60 @@ +#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 +# -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..3a0557d0 --- /dev/null +++ b/timgui/incl/timgui/imgui.hpp @@ -0,0 +1,175 @@ +#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), + * 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 + */ +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, the textures and the buffers + * @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 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); + + /** + * 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; + /** 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 +}; +} + +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..37b5f4e2 --- /dev/null +++ b/timgui/src/imgui.cpp @@ -0,0 +1,586 @@ +#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 "jvk/graph/stage_graph.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 +#include +#include + + +namespace timgui::dev { +namespace { + /** one `Frame` 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; +}; + +/** + * 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 + */ +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{}; + + /** + * 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 +}; +} + +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}, + }; + + /** 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_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_MAPPED_BIT + | 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, + }; + + /** 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)); + + void make_current(dev::ImguiState const& state) { + ImGui::SetCurrentContext(state.context.get()); + ImPlot::SetCurrentContext(state.plotContext.get()); + } + + /** `+ 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; + } + + [[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)}; + } + + [[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)}, + }; + } + + /** 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, + .stencilFormat = config.stencilFormat, + }; + 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}; + } + + 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)); + } + + /** + * 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 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, + 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) { + 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& state = *_state; + cvk::Core const& vk = *state.core; + + // 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); + + 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; + } +} + +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&); +template void Imgui::draw(jvk::Stage&, jvk::SecondaryCmdBuffer&, ImDrawData 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..8f228c04 --- /dev/null +++ b/timgui/tests/src/imgui_test.cpp @@ -0,0 +1,524 @@ +#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_tracker.hpp" + +#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 +#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 + * @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, + 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(info); + 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, 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()}; + 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, 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}; + + 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",