diff options
| author | Ryx <118130241+Ryx69@users.noreply.github.com> | 2026-11-21 20:44:40 +0100 |
|---|---|---|
| committer | Ryx <118130241+Ryx69@users.noreply.github.com> | 2026-11-22 04:54:51 +0100 |
| commit | e876fc830e4dfaaad2f63626df2e24f05d026b20 (patch) | |
| tree | 214e19a8a189185dbf90e84ec3fb00cd23c84651 /runtime | |
| parent | 4a36bb19979b611f525d027f92e0fefad1626546 (diff) | |
Runtime: present D3D12 back buffers to a window on Vulkan (milestone M0)
- vulkan_present.h: VulkanPresenter blits a back buffer (an ordinary texture
in D3D12's PRESENT state, layout tracked like any other) to an acquired
swapchain image and presents it on the same VkQueue, after the
application's work. Two frames in flight, a present semaphore per image,
FIFO for vsync else MAILBOX/IMMEDIATE, swapchain recreated on resize or
out-of-date/suboptimal, minimised windows skip presents.
- rt::d3d12::create_window_presenter / WindowPresenter: Win32 surface for a
Vulkan device created with presentation; holds the device. This is the back
end a DXGI shim or PresentX would call; the game's own front end is still
open (docs question 6), so neither is invented here.
- Standalone device enables VK_KHR_surface/win32_surface and VK_KHR_swapchain
when present; the test helper can too.
Test: d3d12_present_test opens a window and presents 60 frames through the
Xbox-ABI proxy (reset, PRESENT->RENDER_TARGET, clear, ->PRESENT, execute,
present, fence), resizes the window (swapchain recreated, scaled blit),
switches to unsynchronised presents, and reads the screen with GDI:
51,153,229 for a 51,153,230 clear. Clean under the Khronos validation layer,
as are the other GPU tests; 6/6 ctest.
Diffstat (limited to 'runtime')
| -rw-r--r-- | runtime/CMakeLists.txt | 6 | ||||
| -rw-r--r-- | runtime/README.md | 4 | ||||
| -rw-r--r-- | runtime/shims/d3d12_com.h | 30 | ||||
| -rw-r--r-- | runtime/shims/d3d12_vulkan_device.cpp | 72 | ||||
| -rw-r--r-- | runtime/src/vulkan_backend.h | 1 | ||||
| -rw-r--r-- | runtime/src/vulkan_present.h | 350 | ||||
| -rw-r--r-- | runtime/test/d3d12_present_test.cpp | 198 | ||||
| -rw-r--r-- | runtime/test/vk_test_device.h | 17 |
8 files changed, 673 insertions, 5 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index a6d2d4de1..b4be4a8ef 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt | |||
| @@ -661,6 +661,12 @@ if(TARGET Vulkan::Headers) | |||
| 661 | target_compile_definitions(d3d12_resource_desc_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) | 661 | target_compile_definitions(d3d12_resource_desc_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) |
| 662 | target_compile_options(d3d12_resource_desc_test PRIVATE /W4 /permissive- /utf-8) | 662 | target_compile_options(d3d12_resource_desc_test PRIVATE /W4 /permissive- /utf-8) |
| 663 | 663 | ||
| 664 | # Milestone M0: a window, 60 cleared frames presented through the proxy on Vulkan. | ||
| 665 | add_executable(d3d12_present_test test/d3d12_present_test.cpp) | ||
| 666 | target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32) | ||
| 667 | target_compile_definitions(d3d12_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) | ||
| 668 | target_compile_options(d3d12_present_test PRIVATE /W4 /permissive- /utf-8) | ||
| 669 | |||
| 664 | # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). | 670 | # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). |
| 665 | if(TARGET gta6rt) | 671 | if(TARGET gta6rt) |
| 666 | target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com) | 672 | target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com) |
diff --git a/runtime/README.md b/runtime/README.md index 47ec48566..6575d5443 100644 --- a/runtime/README.md +++ b/runtime/README.md | |||
| @@ -161,7 +161,9 @@ when the Vulkan SDK is found: | |||
| 161 | - `vk_harness` — hand-written RDNA2 shader programs on a real Vulkan device. | 161 | - `vk_harness` — hand-written RDNA2 shader programs on a real Vulkan device. |
| 162 | - `vk_texture_test`, `vk_compute_test`, `vk_store_test` — texture, LDS/compute, and buffer-store paths. | 162 | - `vk_texture_test`, `vk_compute_test`, `vk_store_test` — texture, LDS/compute, and buffer-store paths. |
| 163 | - `vk_command_replay_test`, `d3d12_com_test`, `d3d12_vulkan_device_test` — the D3D12 command path on | 163 | - `vk_command_replay_test`, `d3d12_com_test`, `d3d12_vulkan_device_test` — the D3D12 command path on |
| 164 | Vulkan: replay, the COM command objects, and the Vulkan device behind the Xbox-ABI proxy. Set | 164 | Vulkan: replay, the COM command objects, and the Vulkan device behind the Xbox-ABI proxy. |
| 165 | - `d3d12_present_test` — milestone M0: opens a window and presents 60 cleared frames through the proxy on | ||
| 166 | Vulkan, resizes it, and checks the colour on screen. Set | ||
| 165 | `LEONIDA_VK_VALIDATION=1` to run them under the Khronos validation layer. | 167 | `LEONIDA_VK_VALIDATION=1` to run them under the Khronos validation layer. |
| 166 | - `vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--max-bytes N]` - | 168 | - `vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--max-bytes N]` - |
| 167 | creates a shader module and, for compute shaders, a pipeline for every entry in the translator's | 169 | creates a shader module and, for compute shaders, a pipeline for every entry in the translator's |
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 066020a7b..17b825bc5 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h | |||
| @@ -15,6 +15,12 @@ | |||
| 15 | 15 | ||
| 16 | #include "../src/vulkan_backend.h" | 16 | #include "../src/vulkan_backend.h" |
| 17 | 17 | ||
| 18 | #include <memory> | ||
| 19 | |||
| 20 | namespace leonida { | ||
| 21 | class VulkanPresenter; | ||
| 22 | } | ||
| 23 | |||
| 18 | namespace rt::d3d12 { | 24 | namespace rt::d3d12 { |
| 19 | 25 | ||
| 20 | // `device` (optional) is what the object's GetDevice returns; the object holds a reference to it. | 26 | // `device` (optional) is what the object's GetDevice returns; the object holds a reference to it. |
| @@ -61,6 +67,7 @@ struct VulkanDeviceInfo { | |||
| 61 | // are only zero or non-zero; without pipelineStatisticsQuery, pipeline-statistics query heaps are refused. | 67 | // are only zero or non-zero; without pipelineStatisticsQuery, pipeline-statistics query heaps are refused. |
| 62 | bool occlusion_query_precise = false; | 68 | bool occlusion_query_precise = false; |
| 63 | bool pipeline_statistics_query = false; | 69 | bool pipeline_statistics_query = false; |
| 70 | bool presentation = false; // VK_KHR_surface + VK_KHR_win32_surface on the instance, VK_KHR_swapchain on the device | ||
| 64 | }; | 71 | }; |
| 65 | 72 | ||
| 66 | // A Vulkan-backed ID3D12Device (PC ABI, up to ID3D12Device11) on caller-owned Vulkan objects, which must outlive | 73 | // A Vulkan-backed ID3D12Device (PC ABI, up to ID3D12Device11) on caller-owned Vulkan objects, which must outlive |
| @@ -101,6 +108,29 @@ bool device_upload_in_vram(ID3D12Device* device); | |||
| 101 | VkDescriptorSet bindless_set(ID3D12Device* device); | 108 | VkDescriptorSet bindless_set(ID3D12Device* device); |
| 102 | VkDescriptorSetLayout bindless_set_layout(ID3D12Device* device); | 109 | VkDescriptorSetLayout bindless_set_layout(ID3D12Device* device); |
| 103 | 110 | ||
| 111 | // Puts back buffers of a device from create_vulkan_device* into a window (leonida::VulkanPresenter), for the | ||
| 112 | // presentation front end the game uses (DXGI or PresentX, still open). Holds a reference to the device. | ||
| 113 | class WindowPresenter { | ||
| 114 | public: | ||
| 115 | WindowPresenter(IUnknown* device, std::unique_ptr<leonida::VulkanPresenter> presenter); | ||
| 116 | ~WindowPresenter(); | ||
| 117 | WindowPresenter(const WindowPresenter&) = delete; | ||
| 118 | WindowPresenter& operator=(const WindowPresenter&) = delete; | ||
| 119 | |||
| 120 | // `back_buffer` is a colour texture in D3D12's PRESENT state. sync_interval 0 presents without vsync. | ||
| 121 | // S_OK also covers a skipped present while the window is minimised. | ||
| 122 | HRESULT present(ID3D12Resource* back_buffer, UINT sync_interval); | ||
| 123 | VkExtent2D extent() const; | ||
| 124 | std::uint64_t presented() const; | ||
| 125 | |||
| 126 | private: | ||
| 127 | IUnknown* device_; | ||
| 128 | std::unique_ptr<leonida::VulkanPresenter> presenter_; | ||
| 129 | }; | ||
| 130 | |||
| 131 | // Null when `device` is not a Vulkan device created with presentation, or the window cannot be presented to. | ||
| 132 | std::unique_ptr<WindowPresenter> create_window_presenter(ID3D12Device* device, HWND window); | ||
| 133 | |||
| 104 | // ExecuteCommandLists returns void; this is what the last call on the queue did. | 134 | // ExecuteCommandLists returns void; this is what the last call on the queue did. |
| 105 | leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue); | 135 | leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue); |
| 106 | 136 | ||
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index f07876055..157123389 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp | |||
| @@ -14,6 +14,9 @@ | |||
| 14 | #include "../src/vulkan_bindless.h" | 14 | #include "../src/vulkan_bindless.h" |
| 15 | #include "../src/vulkan_memory.h" | 15 | #include "../src/vulkan_memory.h" |
| 16 | #include "../src/resource_tiling.h" | 16 | #include "../src/resource_tiling.h" |
| 17 | #include "../src/vulkan_present.h" | ||
| 18 | |||
| 19 | #include <vulkan/vulkan_win32.h> | ||
| 17 | 20 | ||
| 18 | #include <algorithm> | 21 | #include <algorithm> |
| 19 | #include <atomic> | 22 | #include <atomic> |
| @@ -1320,6 +1323,8 @@ public: | |||
| 1320 | const VulkanDeviceInfo& info() const { return state_.info; } | 1323 | const VulkanDeviceInfo& info() const { return state_.info; } |
| 1321 | bool upload_in_vram() const { return state_.upload_in_vram; } | 1324 | bool upload_in_vram() const { return state_.upload_in_vram; } |
| 1322 | const leonida::BindlessSet* bindless() const { return state_.bindless.get(); } | 1325 | const leonida::BindlessSet* bindless() const { return state_.bindless.get(); } |
| 1326 | const DeviceState& state() const { return state_; } | ||
| 1327 | IUnknown* holder() { return identity(); } | ||
| 1323 | void own(const OwnedRuntime& owned) { owned_ = owned; } | 1328 | void own(const OwnedRuntime& owned) { owned_ = owned; } |
| 1324 | void set_outer(IUnknown* outer) { outer_ = outer; } | 1329 | void set_outer(IUnknown* outer) { outer_ = outer; } |
| 1325 | 1330 | ||
| @@ -2770,6 +2775,53 @@ VkDescriptorSetLayout bindless_set_layout(ID3D12Device* device) { | |||
| 2770 | return set ? set->layout() : VK_NULL_HANDLE; | 2775 | return set ? set->layout() : VK_NULL_HANDLE; |
| 2771 | } | 2776 | } |
| 2772 | 2777 | ||
| 2778 | WindowPresenter::WindowPresenter(IUnknown* device, std::unique_ptr<leonida::VulkanPresenter> presenter) | ||
| 2779 | : device_(device), presenter_(std::move(presenter)) { | ||
| 2780 | device_->AddRef(); | ||
| 2781 | } | ||
| 2782 | |||
| 2783 | WindowPresenter::~WindowPresenter() { | ||
| 2784 | presenter_.reset(); // before the device it runs on | ||
| 2785 | device_->Release(); | ||
| 2786 | } | ||
| 2787 | |||
| 2788 | HRESULT WindowPresenter::present(ID3D12Resource* back_buffer, UINT sync_interval) { | ||
| 2789 | if (!back_buffer) return E_INVALIDARG; | ||
| 2790 | const VkResult result = presenter_->present(resource_id(back_buffer), sync_interval > 0); | ||
| 2791 | if (result == VK_SUCCESS) return S_OK; | ||
| 2792 | std::fprintf(stderr, "[rt] d3d12: present failed (VkResult %d)\n", int(result)); | ||
| 2793 | return result == VK_ERROR_DEVICE_LOST ? DXGI_ERROR_DEVICE_REMOVED : E_FAIL; | ||
| 2794 | } | ||
| 2795 | |||
| 2796 | VkExtent2D WindowPresenter::extent() const { return presenter_->extent(); } | ||
| 2797 | std::uint64_t WindowPresenter::presented() const { return presenter_->presented(); } | ||
| 2798 | |||
| 2799 | std::unique_ptr<WindowPresenter> create_window_presenter(ID3D12Device* device, HWND window) { | ||
| 2800 | Device* d = Device::from<Device>(device); | ||
| 2801 | if (!d || !window) return nullptr; | ||
| 2802 | const VulkanDeviceInfo& info = d->state().info; | ||
| 2803 | if (!info.presentation) { | ||
| 2804 | std::fprintf(stderr, "[rt] d3d12: the Vulkan device was created without presentation support\n"); | ||
| 2805 | return nullptr; | ||
| 2806 | } | ||
| 2807 | const auto create_surface = reinterpret_cast<PFN_vkCreateWin32SurfaceKHR>( | ||
| 2808 | info.get_instance_proc(info.instance, "vkCreateWin32SurfaceKHR")); | ||
| 2809 | if (!create_surface) return nullptr; | ||
| 2810 | VkWin32SurfaceCreateInfoKHR surface_info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; | ||
| 2811 | surface_info.hinstance = GetModuleHandleW(nullptr); | ||
| 2812 | surface_info.hwnd = window; | ||
| 2813 | VkSurfaceKHR surface = VK_NULL_HANDLE; | ||
| 2814 | if (create_surface(info.instance, &surface_info, nullptr, &surface) != VK_SUCCESS) return nullptr; | ||
| 2815 | auto presenter = std::make_unique<leonida::VulkanPresenter>(*d->state().context, info.get_instance_proc, | ||
| 2816 | info.instance, info.physical, info.queue, | ||
| 2817 | info.queue_family, surface); // owns the surface | ||
| 2818 | if (!presenter->ok()) { | ||
| 2819 | std::fprintf(stderr, "[rt] d3d12: cannot present to this window from the device's queue family\n"); | ||
| 2820 | return nullptr; | ||
| 2821 | } | ||
| 2822 | return std::make_unique<WindowPresenter>(d->holder(), std::move(presenter)); | ||
| 2823 | } | ||
| 2824 | |||
| 2773 | // Creates its own Vulkan 1.3 instance and device. LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation. | 2825 | // Creates its own Vulkan 1.3 instance and device. LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation. |
| 2774 | HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { | 2826 | HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { |
| 2775 | if (!out) return E_POINTER; | 2827 | if (!out) return E_POINTER; |
| @@ -2783,11 +2835,28 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { | |||
| 2783 | return E_FAIL; | 2835 | return E_FAIL; |
| 2784 | } | 2836 | } |
| 2785 | const auto create_instance = reinterpret_cast<PFN_vkCreateInstance>(get(nullptr, "vkCreateInstance")); | 2837 | const auto create_instance = reinterpret_cast<PFN_vkCreateInstance>(get(nullptr, "vkCreateInstance")); |
| 2838 | const auto instance_extensions = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>( | ||
| 2839 | get(nullptr, "vkEnumerateInstanceExtensionProperties")); | ||
| 2840 | std::uint32_t instance_extension_count = 0; | ||
| 2841 | instance_extensions(nullptr, &instance_extension_count, nullptr); | ||
| 2842 | std::vector<VkExtensionProperties> available(instance_extension_count); | ||
| 2843 | instance_extensions(nullptr, &instance_extension_count, available.data()); | ||
| 2844 | const auto has = [](const std::vector<VkExtensionProperties>& list, const char* name) { | ||
| 2845 | for (const auto& e : list) | ||
| 2846 | if (std::strcmp(e.extensionName, name) == 0) return true; | ||
| 2847 | return false; | ||
| 2848 | }; | ||
| 2849 | const char* surface_extensions[] = {VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME}; | ||
| 2850 | const bool surfaces = has(available, surface_extensions[0]) && has(available, surface_extensions[1]); | ||
| 2786 | VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; | 2851 | VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; |
| 2787 | app.pApplicationName = "gta6rt"; | 2852 | app.pApplicationName = "gta6rt"; |
| 2788 | app.apiVersion = VK_API_VERSION_1_3; | 2853 | app.apiVersion = VK_API_VERSION_1_3; |
| 2789 | VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; | 2854 | VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; |
| 2790 | instance_info.pApplicationInfo = &app; | 2855 | instance_info.pApplicationInfo = &app; |
| 2856 | if (surfaces) { | ||
| 2857 | instance_info.enabledExtensionCount = 2; | ||
| 2858 | instance_info.ppEnabledExtensionNames = surface_extensions; | ||
| 2859 | } | ||
| 2791 | const char* layer = "VK_LAYER_KHRONOS_validation"; | 2860 | const char* layer = "VK_LAYER_KHRONOS_validation"; |
| 2792 | const VkValidationFeatureEnableEXT sync_validation = VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT; | 2861 | const VkValidationFeatureEnableEXT sync_validation = VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT; |
| 2793 | VkValidationFeaturesEXT validation_features{VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT}; | 2862 | VkValidationFeaturesEXT validation_features{VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT}; |
| @@ -2959,6 +3028,9 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { | |||
| 2959 | std::vector<const char*> device_extensions; | 3028 | std::vector<const char*> device_extensions; |
| 2960 | if (info.conditional_rendering) device_extensions.push_back(conditional_extension); | 3029 | if (info.conditional_rendering) device_extensions.push_back(conditional_extension); |
| 2961 | if (info.host_image_copy) device_extensions.push_back(host_image_copy_name); | 3030 | if (info.host_image_copy) device_extensions.push_back(host_image_copy_name); |
| 3031 | const char* swapchain = VK_KHR_SWAPCHAIN_EXTENSION_NAME; | ||
| 3032 | info.presentation = surfaces && has(extensions, swapchain); | ||
| 3033 | if (info.presentation) device_extensions.push_back(swapchain); | ||
| 2962 | device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); | 3034 | device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); |
| 2963 | device_info.ppEnabledExtensionNames = device_extensions.data(); | 3035 | device_info.ppEnabledExtensionNames = device_extensions.data(); |
| 2964 | if (vkCreateDevice(info.physical, &device_info, nullptr, &owned.device) != VK_SUCCESS) | 3036 | if (vkCreateDevice(info.physical, &device_info, nullptr, &owned.device) != VK_SUCCESS) |
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 5c7ee7f7b..a7cc958aa 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h | |||
| @@ -196,6 +196,7 @@ public: | |||
| 196 | 196 | ||
| 197 | private: | 197 | private: |
| 198 | friend class VulkanQueue; | 198 | friend class VulkanQueue; |
| 199 | friend class VulkanPresenter; | ||
| 199 | 200 | ||
| 200 | const ResourceBinding* resolve(ResourceId id) const { | 201 | const ResourceBinding* resolve(ResourceId id) const { |
| 201 | const auto it = resources_.find(id); | 202 | const auto it = resources_.find(id); |
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h new file mode 100644 index 000000000..3f8232eeb --- /dev/null +++ b/runtime/src/vulkan_present.h | |||
| @@ -0,0 +1,350 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | // Puts a D3D12 back buffer on screen through a Vulkan swapchain, for whichever front end the game turns out to use | ||
| 4 | // (DXGI or the console's PresentX; docs/d3d12_vulkan.md question 6). The back buffer is an ordinary texture in the | ||
| 5 | // D3D12 PRESENT (common) state; present() blits it to the acquired swapchain image, scaling if the window size | ||
| 6 | // differs, and queues the present. The application's own work reaches the same VkQueue first, so every draw it | ||
| 7 | // submitted before present() is in the frame. | ||
| 8 | // | ||
| 9 | // Needs VK_KHR_swapchain on the device and a surface from the caller (which this object then owns). The swapchain | ||
| 10 | // is recreated when the window changes size or the surface reports it out of date; a minimised window skips | ||
| 11 | // presents. Two frames are in flight; present() waits for the older one before reusing its command buffer. | ||
| 12 | |||
| 13 | #include "vulkan_backend.h" | ||
| 14 | |||
| 15 | #include <algorithm> | ||
| 16 | #include <array> | ||
| 17 | #include <cstdint> | ||
| 18 | #include <vector> | ||
| 19 | |||
| 20 | namespace leonida { | ||
| 21 | |||
| 22 | class VulkanPresenter { | ||
| 23 | public: | ||
| 24 | VulkanPresenter(VulkanContext& context, PFN_vkGetInstanceProcAddr get_instance, VkInstance instance, | ||
| 25 | VkPhysicalDevice physical, VkQueue queue, std::uint32_t family, VkSurfaceKHR surface) | ||
| 26 | : context_(context), instance_(instance), physical_(physical), queue_(queue), surface_(surface) { | ||
| 27 | #define LEONIDA_INSTANCE_FN(name) name##_ = reinterpret_cast<PFN_##name>(get_instance(instance, #name)); | ||
| 28 | LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceSupportKHR) | ||
| 29 | LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) | ||
| 30 | LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceFormatsKHR) | ||
| 31 | LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfacePresentModesKHR) | ||
| 32 | LEONIDA_INSTANCE_FN(vkDestroySurfaceKHR) | ||
| 33 | LEONIDA_INSTANCE_FN(vkGetDeviceProcAddr) | ||
| 34 | #undef LEONIDA_INSTANCE_FN | ||
| 35 | if (!vkGetDeviceProcAddr_ || !vkDestroySurfaceKHR_) return; | ||
| 36 | const VkDevice device = context.device(); | ||
| 37 | #define LEONIDA_DEVICE_FN(name) name##_ = reinterpret_cast<PFN_##name>(vkGetDeviceProcAddr_(device, #name)); | ||
| 38 | LEONIDA_DEVICE_FN(vkCreateSwapchainKHR) | ||
| 39 | LEONIDA_DEVICE_FN(vkDestroySwapchainKHR) | ||
| 40 | LEONIDA_DEVICE_FN(vkGetSwapchainImagesKHR) | ||
| 41 | LEONIDA_DEVICE_FN(vkAcquireNextImageKHR) | ||
| 42 | LEONIDA_DEVICE_FN(vkQueuePresentKHR) | ||
| 43 | LEONIDA_DEVICE_FN(vkCmdBlitImage) | ||
| 44 | LEONIDA_DEVICE_FN(vkCreateFence) | ||
| 45 | LEONIDA_DEVICE_FN(vkDestroyFence) | ||
| 46 | LEONIDA_DEVICE_FN(vkWaitForFences) | ||
| 47 | LEONIDA_DEVICE_FN(vkResetFences) | ||
| 48 | #undef LEONIDA_DEVICE_FN | ||
| 49 | if (!vkCreateSwapchainKHR_ || !vkQueuePresentKHR_ || !vkCmdBlitImage_ || !vkCreateFence_) return; | ||
| 50 | |||
| 51 | VkBool32 supported = VK_FALSE; | ||
| 52 | vkGetPhysicalDeviceSurfaceSupportKHR_(physical, family, surface, &supported); | ||
| 53 | if (!supported) return; | ||
| 54 | |||
| 55 | auto& vk = context.vk; | ||
| 56 | VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; | ||
| 57 | pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; | ||
| 58 | pool.queueFamilyIndex = family; | ||
| 59 | if (vk.vkCreateCommandPool(device, &pool, nullptr, &pool_) != VK_SUCCESS) return; | ||
| 60 | for (Frame& frame : frames_) { | ||
| 61 | VkCommandBufferAllocateInfo allocate{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; | ||
| 62 | allocate.commandPool = pool_; | ||
| 63 | allocate.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; | ||
| 64 | allocate.commandBufferCount = 1; | ||
| 65 | VkFenceCreateInfo fence{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; | ||
| 66 | fence.flags = VK_FENCE_CREATE_SIGNALED_BIT; | ||
| 67 | VkSemaphoreCreateInfo semaphore{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; | ||
| 68 | if (vk.vkAllocateCommandBuffers(device, &allocate, &frame.commands) != VK_SUCCESS || | ||
| 69 | vkCreateFence_(device, &fence, nullptr, &frame.done) != VK_SUCCESS || | ||
| 70 | vk.vkCreateSemaphore(device, &semaphore, nullptr, &frame.acquired) != VK_SUCCESS) | ||
| 71 | return; | ||
| 72 | } | ||
| 73 | ok_ = recreate(true); | ||
| 74 | } | ||
| 75 | |||
| 76 | ~VulkanPresenter() { | ||
| 77 | auto& vk = context_.vk; | ||
| 78 | const VkDevice device = context_.device(); | ||
| 79 | { | ||
| 80 | std::lock_guard lock(context_.submit_mutex()); | ||
| 81 | vk.vkQueueWaitIdle(queue_); | ||
| 82 | } | ||
| 83 | release(swapchain_); | ||
| 84 | swapchain_ = VK_NULL_HANDLE; | ||
| 85 | for (Frame& frame : frames_) { | ||
| 86 | if (frame.done) vkDestroyFence_(device, frame.done, nullptr); | ||
| 87 | if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr); | ||
| 88 | } | ||
| 89 | if (pool_) vk.vkDestroyCommandPool(device, pool_, nullptr); | ||
| 90 | if (surface_ && vkDestroySurfaceKHR_) vkDestroySurfaceKHR_(instance_, surface_, nullptr); | ||
| 91 | } | ||
| 92 | |||
| 93 | VulkanPresenter(const VulkanPresenter&) = delete; | ||
| 94 | VulkanPresenter& operator=(const VulkanPresenter&) = delete; | ||
| 95 | |||
| 96 | bool ok() const { return ok_; } | ||
| 97 | VkExtent2D extent() const { return extent_; } | ||
| 98 | VkFormat format() const { return format_; } | ||
| 99 | std::uint64_t presented() const { return presented_; } | ||
| 100 | |||
| 101 | // Blits the colour texture `source` (mip 0, layer 0, in D3D12's PRESENT state) to the window and presents it. | ||
| 102 | // vsync: FIFO; otherwise MAILBOX or IMMEDIATE when the surface has them. VK_SUCCESS also covers a skipped | ||
| 103 | // present (minimised window); VK_ERROR_OUT_OF_DATE_KHR only if recreating the swapchain failed. | ||
| 104 | VkResult present(ResourceId source, bool vsync) { | ||
| 105 | if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; | ||
| 106 | if (vsync != vsync_ || stale_) { | ||
| 107 | if (!recreate(vsync)) return VK_ERROR_OUT_OF_DATE_KHR; | ||
| 108 | } | ||
| 109 | if (!swapchain_) { // minimised: try again next frame | ||
| 110 | stale_ = true; | ||
| 111 | return VK_SUCCESS; | ||
| 112 | } | ||
| 113 | auto& vk = context_.vk; | ||
| 114 | const VkDevice device = context_.device(); | ||
| 115 | Frame& frame = frames_[frame_index_ % frames_.size()]; | ||
| 116 | vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX); | ||
| 117 | |||
| 118 | std::uint32_t image = 0; | ||
| 119 | VkResult acquired = vkAcquireNextImageKHR_(device, swapchain_, UINT64_MAX, frame.acquired, VK_NULL_HANDLE, &image); | ||
| 120 | if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { | ||
| 121 | if (!recreate(vsync)) return acquired; | ||
| 122 | if (!swapchain_) return VK_SUCCESS; | ||
| 123 | acquired = vkAcquireNextImageKHR_(device, swapchain_, UINT64_MAX, frame.acquired, VK_NULL_HANDLE, &image); | ||
| 124 | } | ||
| 125 | if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; | ||
| 126 | if (acquired == VK_SUBOPTIMAL_KHR) stale_ = true; | ||
| 127 | |||
| 128 | { | ||
| 129 | // The back buffer's layout is tracked like any other texture; this holds the context while it is read. | ||
| 130 | std::lock_guard lock(context_.mutex_); | ||
| 131 | const ResourceBinding* binding = context_.resolve(source); | ||
| 132 | if (!binding || !binding->image || binding->aspects != VK_IMAGE_ASPECT_COLOR_BIT) return VK_ERROR_UNKNOWN; | ||
| 133 | record(frame.commands, *binding, source, image); | ||
| 134 | } | ||
| 135 | vkResetFences_(device, 1, &frame.done); | ||
| 136 | const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; | ||
| 137 | VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO}; | ||
| 138 | submit.waitSemaphoreCount = 1; | ||
| 139 | submit.pWaitSemaphores = &frame.acquired; | ||
| 140 | submit.pWaitDstStageMask = &wait_stage; | ||
| 141 | submit.commandBufferCount = 1; | ||
| 142 | submit.pCommandBuffers = &frame.commands; | ||
| 143 | submit.signalSemaphoreCount = 1; | ||
| 144 | submit.pSignalSemaphores = &ready_[image]; // one per image: reused only once that image comes back | ||
| 145 | VkPresentInfoKHR present{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; | ||
| 146 | present.waitSemaphoreCount = 1; | ||
| 147 | present.pWaitSemaphores = &ready_[image]; | ||
| 148 | present.swapchainCount = 1; | ||
| 149 | present.pSwapchains = &swapchain_; | ||
| 150 | present.pImageIndices = ℑ | ||
| 151 | VkResult result; | ||
| 152 | { | ||
| 153 | std::lock_guard lock(context_.submit_mutex()); | ||
| 154 | result = vk.vkQueueSubmit(queue_, 1, &submit, frame.done); | ||
| 155 | if (result != VK_SUCCESS) return result; | ||
| 156 | result = vkQueuePresentKHR_(queue_, &present); | ||
| 157 | } | ||
| 158 | ++frame_index_; | ||
| 159 | if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) { | ||
| 160 | stale_ = true; | ||
| 161 | result = VK_SUCCESS; | ||
| 162 | } | ||
| 163 | if (result == VK_SUCCESS) ++presented_; | ||
| 164 | return result; | ||
| 165 | } | ||
| 166 | |||
| 167 | private: | ||
| 168 | struct Frame { | ||
| 169 | VkCommandBuffer commands = VK_NULL_HANDLE; | ||
| 170 | VkFence done = VK_NULL_HANDLE; | ||
| 171 | VkSemaphore acquired = VK_NULL_HANDLE; | ||
| 172 | }; | ||
| 173 | |||
| 174 | void record(VkCommandBuffer commands, const ResourceBinding& binding, ResourceId source, std::uint32_t image) { | ||
| 175 | auto& vk = context_.vk; | ||
| 176 | const ReplayFunctions& fn = context_.replay_; | ||
| 177 | vk.vkResetCommandBuffer(commands, 0); | ||
| 178 | VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; | ||
| 179 | begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; | ||
| 180 | vk.vkBeginCommandBuffer(commands, &begin); | ||
| 181 | |||
| 182 | constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 183 | const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; | ||
| 184 | // PRESENT is D3D12's common state: GENERAL for an ordinary texture. A never-written back buffer is | ||
| 185 | // zero-filled first, as any committed resource is. | ||
| 186 | const VkImageLayout common = image_layout(binding, VK_IMAGE_LAYOUT_GENERAL); | ||
| 187 | auto pieces = detail::current(&context_.tracker_, source, range, common); | ||
| 188 | detail::initialize(fn, commands, binding, source, pieces, common, &context_.tracker_); | ||
| 189 | for (const auto& piece : pieces) | ||
| 190 | detail::image_barrier(fn, commands, binding, piece.range, piece.layout, | ||
| 191 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_MEMORY_WRITE_BIT, | ||
| 192 | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_READ_BIT, | ||
| 193 | VK_PIPELINE_STAGE_TRANSFER_BIT); | ||
| 194 | ResourceBinding target{}; // the swapchain image, for the barrier helpers | ||
| 195 | target.image = images_[image]; | ||
| 196 | target.format = format_; | ||
| 197 | target.aspects = VK_IMAGE_ASPECT_COLOR_BIT; | ||
| 198 | // The acquire semaphore is waited at the transfer stage, so the swapchain image's barrier starts there. | ||
| 199 | detail::image_barrier(fn, commands, target, range, VK_IMAGE_LAYOUT_UNDEFINED, | ||
| 200 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_PIPELINE_STAGE_TRANSFER_BIT, | ||
| 201 | VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); | ||
| 202 | |||
| 203 | const std::int32_t sw = std::int32_t(binding.width), sh = std::int32_t(binding.height); | ||
| 204 | const std::int32_t dw = std::int32_t(extent_.width), dh = std::int32_t(extent_.height); | ||
| 205 | VkImageBlit blit{}; | ||
| 206 | blit.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; | ||
| 207 | blit.srcOffsets[1] = {sw, sh, 1}; | ||
| 208 | blit.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; | ||
| 209 | blit.dstOffsets[1] = {dw, dh, 1}; | ||
| 210 | vkCmdBlitImage_(commands, binding.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, images_[image], | ||
| 211 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, | ||
| 212 | sw == dw && sh == dh ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); | ||
| 213 | |||
| 214 | detail::image_barrier(fn, commands, target, range, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, | ||
| 215 | VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_ACCESS_TRANSFER_WRITE_BIT, | ||
| 216 | VK_PIPELINE_STAGE_TRANSFER_BIT, 0, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); | ||
| 217 | for (const auto& piece : pieces) | ||
| 218 | detail::image_barrier(fn, commands, binding, piece.range, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, | ||
| 219 | piece.layout, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, any, | ||
| 220 | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); | ||
| 221 | vk.vkEndCommandBuffer(commands); | ||
| 222 | } | ||
| 223 | |||
| 224 | // (Re)creates the swapchain for the surface's current size. A zero-sized surface (minimised) leaves no | ||
| 225 | // swapchain and is retried on the next present. | ||
| 226 | bool recreate(bool vsync) { | ||
| 227 | auto& vk = context_.vk; | ||
| 228 | const VkDevice device = context_.device(); | ||
| 229 | { | ||
| 230 | std::lock_guard lock(context_.submit_mutex()); | ||
| 231 | vk.vkQueueWaitIdle(queue_); // the old swapchain's images and semaphores may still be in use | ||
| 232 | } | ||
| 233 | VkSurfaceCapabilitiesKHR caps{}; | ||
| 234 | if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR_(physical_, surface_, &caps) != VK_SUCCESS) return false; | ||
| 235 | vsync_ = vsync; | ||
| 236 | stale_ = false; | ||
| 237 | VkSwapchainKHR old = swapchain_; | ||
| 238 | swapchain_ = VK_NULL_HANDLE; | ||
| 239 | if (caps.currentExtent.width == 0 || caps.currentExtent.height == 0) { | ||
| 240 | release(old); | ||
| 241 | return true; | ||
| 242 | } | ||
| 243 | if (!(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT)) return false; | ||
| 244 | |||
| 245 | std::uint32_t count = 0; | ||
| 246 | vkGetPhysicalDeviceSurfaceFormatsKHR_(physical_, surface_, &count, nullptr); | ||
| 247 | std::vector<VkSurfaceFormatKHR> formats(count); | ||
| 248 | vkGetPhysicalDeviceSurfaceFormatsKHR_(physical_, surface_, &count, formats.data()); | ||
| 249 | if (formats.empty()) return false; | ||
| 250 | VkSurfaceFormatKHR chosen = formats[0]; | ||
| 251 | for (const auto& f : formats) | ||
| 252 | if ((f.format == VK_FORMAT_B8G8R8A8_UNORM || f.format == VK_FORMAT_R8G8B8A8_UNORM) && | ||
| 253 | f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { | ||
| 254 | chosen = f; | ||
| 255 | break; | ||
| 256 | } | ||
| 257 | vkGetPhysicalDeviceSurfacePresentModesKHR_(physical_, surface_, &count, nullptr); | ||
| 258 | std::vector<VkPresentModeKHR> modes(count); | ||
| 259 | vkGetPhysicalDeviceSurfacePresentModesKHR_(physical_, surface_, &count, modes.data()); | ||
| 260 | VkPresentModeKHR mode = VK_PRESENT_MODE_FIFO_KHR; // always available | ||
| 261 | if (!vsync) { | ||
| 262 | for (const VkPresentModeKHR wanted : {VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR}) | ||
| 263 | if (std::find(modes.begin(), modes.end(), wanted) != modes.end()) { | ||
| 264 | mode = wanted; | ||
| 265 | break; | ||
| 266 | } | ||
| 267 | } | ||
| 268 | |||
| 269 | VkSwapchainCreateInfoKHR info{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; | ||
| 270 | info.surface = surface_; | ||
| 271 | info.minImageCount = std::max(caps.minImageCount + 1, 2u); | ||
| 272 | if (caps.maxImageCount) info.minImageCount = std::min(info.minImageCount, caps.maxImageCount); | ||
| 273 | info.imageFormat = chosen.format; | ||
| 274 | info.imageColorSpace = chosen.colorSpace; | ||
| 275 | info.imageExtent = caps.currentExtent; | ||
| 276 | info.imageArrayLayers = 1; | ||
| 277 | info.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; | ||
| 278 | info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; | ||
| 279 | info.preTransform = caps.currentTransform; | ||
| 280 | info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; | ||
| 281 | if (!(caps.supportedCompositeAlpha & info.compositeAlpha)) info.compositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR; | ||
| 282 | info.presentMode = mode; | ||
| 283 | info.clipped = VK_TRUE; | ||
| 284 | info.oldSwapchain = old; | ||
| 285 | const VkResult created = vkCreateSwapchainKHR_(device, &info, nullptr, &swapchain_); | ||
| 286 | release(old); | ||
| 287 | if (created != VK_SUCCESS) { | ||
| 288 | swapchain_ = VK_NULL_HANDLE; | ||
| 289 | return false; | ||
| 290 | } | ||
| 291 | format_ = chosen.format; | ||
| 292 | extent_ = caps.currentExtent; | ||
| 293 | vkGetSwapchainImagesKHR_(device, swapchain_, &count, nullptr); | ||
| 294 | images_.resize(count); | ||
| 295 | vkGetSwapchainImagesKHR_(device, swapchain_, &count, images_.data()); | ||
| 296 | ready_.assign(count, VK_NULL_HANDLE); | ||
| 297 | for (VkSemaphore& semaphore : ready_) { | ||
| 298 | VkSemaphoreCreateInfo semaphore_info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; | ||
| 299 | if (vk.vkCreateSemaphore(device, &semaphore_info, nullptr, &semaphore) != VK_SUCCESS) return false; | ||
| 300 | } | ||
| 301 | return true; | ||
| 302 | } | ||
| 303 | |||
| 304 | // Destroys a swapchain that is being replaced (or the last one), with the per-image semaphores that went with it. | ||
| 305 | void release(VkSwapchainKHR swapchain) { | ||
| 306 | const VkDevice device = context_.device(); | ||
| 307 | for (VkSemaphore semaphore : ready_) | ||
| 308 | if (semaphore) context_.vk.vkDestroySemaphore(device, semaphore, nullptr); | ||
| 309 | ready_.clear(); | ||
| 310 | images_.clear(); | ||
| 311 | if (swapchain) vkDestroySwapchainKHR_(device, swapchain, nullptr); | ||
| 312 | } | ||
| 313 | |||
| 314 | VulkanContext& context_; | ||
| 315 | VkInstance instance_; | ||
| 316 | VkPhysicalDevice physical_; | ||
| 317 | VkQueue queue_; | ||
| 318 | VkSurfaceKHR surface_; | ||
| 319 | VkSwapchainKHR swapchain_ = VK_NULL_HANDLE; | ||
| 320 | VkFormat format_ = VK_FORMAT_UNDEFINED; | ||
| 321 | VkExtent2D extent_{}; | ||
| 322 | std::vector<VkImage> images_; | ||
| 323 | std::vector<VkSemaphore> ready_; // per swapchain image: blit done, present may start | ||
| 324 | std::array<Frame, 2> frames_{}; | ||
| 325 | VkCommandPool pool_ = VK_NULL_HANDLE; | ||
| 326 | std::uint64_t frame_index_ = 0; | ||
| 327 | std::uint64_t presented_ = 0; | ||
| 328 | bool vsync_ = true; | ||
| 329 | bool stale_ = false; | ||
| 330 | bool ok_ = false; | ||
| 331 | |||
| 332 | PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR_ = nullptr; | ||
| 333 | PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR_ = nullptr; | ||
| 334 | PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR_ = nullptr; | ||
| 335 | PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR_ = nullptr; | ||
| 336 | PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR_ = nullptr; | ||
| 337 | PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr_ = nullptr; | ||
| 338 | PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR_ = nullptr; | ||
| 339 | PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR_ = nullptr; | ||
| 340 | PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR_ = nullptr; | ||
| 341 | PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR_ = nullptr; | ||
| 342 | PFN_vkQueuePresentKHR vkQueuePresentKHR_ = nullptr; | ||
| 343 | PFN_vkCmdBlitImage vkCmdBlitImage_ = nullptr; | ||
| 344 | PFN_vkCreateFence vkCreateFence_ = nullptr; | ||
| 345 | PFN_vkDestroyFence vkDestroyFence_ = nullptr; | ||
| 346 | PFN_vkWaitForFences vkWaitForFences_ = nullptr; | ||
| 347 | PFN_vkResetFences vkResetFences_ = nullptr; | ||
| 348 | }; | ||
| 349 | |||
| 350 | } // namespace leonida | ||
diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp new file mode 100644 index 000000000..18ab22d5e --- /dev/null +++ b/runtime/test/d3d12_present_test.cpp | |||
| @@ -0,0 +1,198 @@ | |||
| 1 | // Milestone M0 (docs/d3d12_vulkan.md section 6): a window shows a stable clear colour for 60 frames, through the | ||
| 2 | // Vulkan-backed device behind the Xbox-ABI proxy, with no Vulkan validation errors. Each frame resets the list, | ||
| 3 | // moves the back buffer PRESENT -> RENDER_TARGET, clears it, moves it back, executes, presents and signals a fence. | ||
| 4 | // The window is then resized, which recreates the swapchain and scales the blit. Last, the colour on screen is read | ||
| 5 | // back with GDI when the window is in front (skipped otherwise, e.g. on a locked desktop). No shaders or game data. | ||
| 6 | // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. | ||
| 7 | #include "vk_test_device.h" | ||
| 8 | #include "../shims/d3d12_com.h" | ||
| 9 | #include "../shims/d3d12_xs_device.h" | ||
| 10 | |||
| 11 | #include <cstdint> | ||
| 12 | #include <cstdlib> | ||
| 13 | |||
| 14 | #define EXPECT(condition) do { \ | ||
| 15 | if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ | ||
| 16 | } while (0) | ||
| 17 | |||
| 18 | namespace { | ||
| 19 | |||
| 20 | using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: 8-byte handle in RAX | ||
| 21 | |||
| 22 | template<class T> | ||
| 23 | struct Ref { | ||
| 24 | T* p = nullptr; | ||
| 25 | ~Ref() { reset(); } | ||
| 26 | void reset() { | ||
| 27 | if (p) p->Release(); | ||
| 28 | p = nullptr; | ||
| 29 | } | ||
| 30 | T* operator->() const { return p; } | ||
| 31 | }; | ||
| 32 | |||
| 33 | LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM w, LPARAM l) { | ||
| 34 | return DefWindowProcW(window, message, w, l); | ||
| 35 | } | ||
| 36 | |||
| 37 | void pump() { | ||
| 38 | MSG message; | ||
| 39 | while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) { | ||
| 40 | TranslateMessage(&message); | ||
| 41 | DispatchMessageW(&message); | ||
| 42 | } | ||
| 43 | } | ||
| 44 | |||
| 45 | void set_client_size(HWND window, int width, int height) { | ||
| 46 | RECT rect{0, 0, width, height}; | ||
| 47 | AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE); | ||
| 48 | SetWindowPos(window, HWND_TOP, 0, 0, rect.right - rect.left, rect.bottom - rect.top, | ||
| 49 | SWP_NOMOVE | SWP_NOZORDER | SWP_SHOWWINDOW); | ||
| 50 | } | ||
| 51 | |||
| 52 | } // namespace | ||
| 53 | |||
| 54 | int main() { | ||
| 55 | vktest::Device d; | ||
| 56 | EXPECT(d.create(true)); | ||
| 57 | |||
| 58 | WNDCLASSW window_class{}; | ||
| 59 | window_class.lpfnWndProc = window_proc; | ||
| 60 | window_class.hInstance = GetModuleHandleW(nullptr); | ||
| 61 | window_class.lpszClassName = L"LeonidaPresentTest"; | ||
| 62 | window_class.hCursor = LoadCursorW(nullptr, reinterpret_cast<LPCWSTR>(IDC_ARROW)); | ||
| 63 | EXPECT(RegisterClassW(&window_class)); | ||
| 64 | constexpr int width = 320, height = 240; | ||
| 65 | RECT frame_rect{0, 0, width, height}; | ||
| 66 | AdjustWindowRect(&frame_rect, WS_OVERLAPPEDWINDOW, FALSE); | ||
| 67 | HWND window = CreateWindowExW(0, window_class.lpszClassName, L"Leonida M0: D3D12 clear on Vulkan", | ||
| 68 | WS_OVERLAPPEDWINDOW, 100, 100, frame_rect.right - frame_rect.left, | ||
| 69 | frame_rect.bottom - frame_rect.top, nullptr, nullptr, window_class.hInstance, | ||
| 70 | nullptr); | ||
| 71 | EXPECT(window); | ||
| 72 | ShowWindow(window, SW_SHOWNORMAL); | ||
| 73 | SetForegroundWindow(window); | ||
| 74 | UpdateWindow(window); | ||
| 75 | pump(); | ||
| 76 | |||
| 77 | const FLOAT colour[4] = {0.2f, 0.6f, 0.9f, 1.0f}; | ||
| 78 | bool screen_checked = false; | ||
| 79 | { | ||
| 80 | rt::d3d12::VulkanDeviceInfo info{}; | ||
| 81 | info.get_instance_proc = d.instance_proc; | ||
| 82 | info.instance = d.instance; | ||
| 83 | info.physical = d.physical; | ||
| 84 | info.device = d.device; | ||
| 85 | info.queue = d.queue; | ||
| 86 | info.queue_family = d.family; | ||
| 87 | info.presentation = true; | ||
| 88 | ID3D12Device* inner = nullptr; | ||
| 89 | EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); | ||
| 90 | Ref<ID3D12Device> device; | ||
| 91 | EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), | ||
| 92 | reinterpret_cast<void**>(&device.p)))); | ||
| 93 | rt::d3d12::set_device_outer(inner, device.p); | ||
| 94 | auto presenter = rt::d3d12::create_window_presenter(inner, window); | ||
| 95 | EXPECT(presenter); | ||
| 96 | |||
| 97 | D3D12_COMMAND_QUEUE_DESC queue_desc{}; | ||
| 98 | Ref<ID3D12CommandQueue> queue; | ||
| 99 | Ref<ID3D12CommandAllocator> allocator; | ||
| 100 | Ref<ID3D12GraphicsCommandList> list; | ||
| 101 | Ref<ID3D12Fence> fence; | ||
| 102 | Ref<ID3D12DescriptorHeap> rtv_heap; | ||
| 103 | Ref<ID3D12Resource> back_buffer; | ||
| 104 | EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); | ||
| 105 | EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); | ||
| 106 | EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, | ||
| 107 | IID_PPV_ARGS(&list.p)))); | ||
| 108 | EXPECT(SUCCEEDED(list->Close())); | ||
| 109 | EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); | ||
| 110 | const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; | ||
| 111 | EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); | ||
| 112 | const D3D12_CPU_DESCRIPTOR_HANDLE rtv{SIZE_T(reinterpret_cast<XboxHeapHandleFn>( | ||
| 113 | (*reinterpret_cast<void***>(rtv_heap.p))[9])(rtv_heap.p))}; | ||
| 114 | const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; | ||
| 115 | D3D12_RESOURCE_DESC desc{}; | ||
| 116 | desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; | ||
| 117 | desc.Width = width; | ||
| 118 | desc.Height = height; | ||
| 119 | desc.DepthOrArraySize = 1; | ||
| 120 | desc.MipLevels = 1; | ||
| 121 | desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; | ||
| 122 | desc.SampleDesc.Count = 1; | ||
| 123 | desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; | ||
| 124 | EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, | ||
| 125 | D3D12_RESOURCE_STATE_PRESENT, nullptr, | ||
| 126 | IID_PPV_ARGS(&back_buffer.p)))); | ||
| 127 | device->CreateRenderTargetView(back_buffer.p, nullptr, rtv); | ||
| 128 | |||
| 129 | D3D12_RESOURCE_BARRIER barrier{}; | ||
| 130 | barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; | ||
| 131 | barrier.Transition.pResource = back_buffer.p; | ||
| 132 | barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; | ||
| 133 | ID3D12CommandList* lists[] = {list.p}; | ||
| 134 | UINT64 signalled = 0; | ||
| 135 | const auto frame = [&](UINT sync_interval) -> bool { | ||
| 136 | pump(); | ||
| 137 | if (FAILED(fence->SetEventOnCompletion(signalled, nullptr))) return false; // the list's last run is done | ||
| 138 | if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return false; | ||
| 139 | barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT; | ||
| 140 | barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; | ||
| 141 | list->ResourceBarrier(1, &barrier); | ||
| 142 | list->ClearRenderTargetView(rtv, colour, 0, nullptr); | ||
| 143 | barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; | ||
| 144 | barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT; | ||
| 145 | list->ResourceBarrier(1, &barrier); | ||
| 146 | if (FAILED(list->Close())) return false; | ||
| 147 | queue->ExecuteCommandLists(1, lists); | ||
| 148 | if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false; | ||
| 149 | if (FAILED(presenter->present(back_buffer.p, sync_interval))) return false; | ||
| 150 | return SUCCEEDED(queue->Signal(fence.p, ++signalled)); | ||
| 151 | }; | ||
| 152 | |||
| 153 | for (int i = 0; i < 60; ++i) EXPECT(frame(1)); | ||
| 154 | EXPECT(presenter->presented() == 60); | ||
| 155 | const VkExtent2D first = presenter->extent(); | ||
| 156 | EXPECT(first.width == width && first.height == height); | ||
| 157 | |||
| 158 | // A resize recreates the swapchain; the 320x240 back buffer is scaled to the new size. Unsynchronised | ||
| 159 | // presents (sync interval 0) switch the present mode on the way. | ||
| 160 | set_client_size(window, 400, 300); | ||
| 161 | for (int i = 0; i < 10; ++i) EXPECT(frame(i < 5 ? 1 : 0)); | ||
| 162 | EXPECT(presenter->extent().width == 400 && presenter->extent().height == 300); | ||
| 163 | EXPECT(presenter->presented() == 70); | ||
| 164 | EXPECT(SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr))); | ||
| 165 | |||
| 166 | // What reached the screen: the centre of the client area, if the window is in front. | ||
| 167 | Sleep(200); | ||
| 168 | pump(); | ||
| 169 | if (GetForegroundWindow() == window && !IsIconic(window)) { | ||
| 170 | RECT client{}; | ||
| 171 | GetClientRect(window, &client); | ||
| 172 | POINT centre{(client.right - client.left) / 2, (client.bottom - client.top) / 2}; | ||
| 173 | ClientToScreen(window, ¢re); | ||
| 174 | HDC screen = GetDC(nullptr); | ||
| 175 | const COLORREF pixel = GetPixel(screen, centre.x, centre.y); | ||
| 176 | ReleaseDC(nullptr, screen); | ||
| 177 | const int r = GetRValue(pixel), g = GetGValue(pixel), b = GetBValue(pixel); | ||
| 178 | std::printf("screen pixel at the window centre: %d,%d,%d (cleared to 51,153,230)\n", r, g, b); | ||
| 179 | EXPECT(pixel != CLR_INVALID); | ||
| 180 | EXPECT(std::abs(r - 51) <= 3 && std::abs(g - 153) <= 3 && std::abs(b - 230) <= 3); | ||
| 181 | screen_checked = true; | ||
| 182 | } else { | ||
| 183 | std::printf("the window is not in front: on-screen colour check skipped\n"); | ||
| 184 | } | ||
| 185 | |||
| 186 | presenter.reset(); // before the device's queue and resources go | ||
| 187 | } | ||
| 188 | DestroyWindow(window); | ||
| 189 | UnregisterClassW(window_class.lpszClassName, window_class.hInstance); | ||
| 190 | |||
| 191 | if (d.validation_errors()) { | ||
| 192 | std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); | ||
| 193 | return 1; | ||
| 194 | } | ||
| 195 | std::printf("M0: 70 frames cleared and presented through the Xbox-ABI proxy on Vulkan, swapchain recreated on " | ||
| 196 | "resize%s\n", screen_checked ? ", colour confirmed on screen" : ""); | ||
| 197 | return 0; | ||
| 198 | } | ||
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 2f95ec015..a1cd3ea30 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h | |||
| @@ -105,9 +105,10 @@ public: | |||
| 105 | 105 | ||
| 106 | unsigned validation_errors() const { return validation_error_count(); } | 106 | unsigned validation_errors() const { return validation_error_count(); } |
| 107 | 107 | ||
| 108 | bool create() { return initialize() == DeviceStatus::ready; } | 108 | // presentation: also enable VK_KHR_surface + VK_KHR_win32_surface and VK_KHR_swapchain (Windows only). |
| 109 | bool create(bool presentation = false) { return initialize(presentation) == DeviceStatus::ready; } | ||
| 109 | 110 | ||
| 110 | DeviceStatus initialize() { | 111 | DeviceStatus initialize(bool presentation = false) { |
| 111 | const auto failure = [](const char* call, VkResult result) { | 112 | const auto failure = [](const char* call, VkResult result) { |
| 112 | std::fprintf(stderr, "%s failed (VkResult %d)\n", call, static_cast<int>(result)); | 113 | std::fprintf(stderr, "%s failed (VkResult %d)\n", call, static_cast<int>(result)); |
| 113 | return DeviceStatus::failed; | 114 | return DeviceStatus::failed; |
| @@ -145,6 +146,11 @@ public: | |||
| 145 | app.apiVersion = VK_API_VERSION_1_3; | 146 | app.apiVersion = VK_API_VERSION_1_3; |
| 146 | VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; | 147 | VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; |
| 147 | instance_info.pApplicationInfo = &app; | 148 | instance_info.pApplicationInfo = &app; |
| 149 | std::vector<const char*> instance_extensions; | ||
| 150 | if (presentation) { | ||
| 151 | instance_extensions.push_back("VK_KHR_surface"); | ||
| 152 | instance_extensions.push_back("VK_KHR_win32_surface"); | ||
| 153 | } | ||
| 148 | if (validation) { | 154 | if (validation) { |
| 149 | std::vector<VkLayerProperties> layers; | 155 | std::vector<VkLayerProperties> layers; |
| 150 | const VkResult layer_result = enumerate_all(layers, enumerate_layers); | 156 | const VkResult layer_result = enumerate_all(layers, enumerate_layers); |
| @@ -158,9 +164,10 @@ public: | |||
| 158 | instance_info.pNext = &validation_features; | 164 | instance_info.pNext = &validation_features; |
| 159 | instance_info.enabledLayerCount = 1; | 165 | instance_info.enabledLayerCount = 1; |
| 160 | instance_info.ppEnabledLayerNames = &layer; | 166 | instance_info.ppEnabledLayerNames = &layer; |
| 161 | instance_info.enabledExtensionCount = 1; | 167 | instance_extensions.push_back(debug_utils); |
| 162 | instance_info.ppEnabledExtensionNames = &debug_utils; | ||
| 163 | } | 168 | } |
| 169 | instance_info.enabledExtensionCount = std::uint32_t(instance_extensions.size()); | ||
| 170 | instance_info.ppEnabledExtensionNames = instance_extensions.data(); | ||
| 164 | VkResult result = create_instance(&instance_info, nullptr, &instance); | 171 | VkResult result = create_instance(&instance_info, nullptr, &instance); |
| 165 | if (result == VK_ERROR_INCOMPATIBLE_DRIVER) return DeviceStatus::unavailable; | 172 | if (result == VK_ERROR_INCOMPATIBLE_DRIVER) return DeviceStatus::unavailable; |
| 166 | if (result != VK_SUCCESS) return failure("vkCreateInstance", result); | 173 | if (result != VK_SUCCESS) return failure("vkCreateInstance", result); |
| @@ -302,6 +309,8 @@ public: | |||
| 302 | std::vector<const char*> device_extensions; | 309 | std::vector<const char*> device_extensions; |
| 303 | if (conditional_rendering) device_extensions.push_back(conditional_extension); | 310 | if (conditional_rendering) device_extensions.push_back(conditional_extension); |
| 304 | if (host_image_copy) device_extensions.push_back(host_image_copy_name); | 311 | if (host_image_copy) device_extensions.push_back(host_image_copy_name); |
| 312 | const char* swapchain = "VK_KHR_swapchain"; | ||
| 313 | if (presentation) device_extensions.push_back(swapchain); | ||
| 305 | device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); | 314 | device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); |
| 306 | device_info.ppEnabledExtensionNames = device_extensions.data(); | 315 | device_info.ppEnabledExtensionNames = device_extensions.data(); |
| 307 | result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device); | 316 | result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device); |