upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src/vulkan_present.h
diff options
context:
space:
mode:
authorRyx <118130241+Ryx69@users.noreply.github.com>2026-11-21 20:44:40 +0100
committerRyx <118130241+Ryx69@users.noreply.github.com>2026-11-22 04:54:51 +0100
commite876fc830e4dfaaad2f63626df2e24f05d026b20 (patch)
tree214e19a8a189185dbf90e84ec3fb00cd23c84651 /runtime/src/vulkan_present.h
parent4a36bb19979b611f525d027f92e0fefad1626546 (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/src/vulkan_present.h')
-rw-r--r--runtime/src/vulkan_present.h350
1 files changed, 350 insertions, 0 deletions
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
20namespace leonida {
21
22class VulkanPresenter {
23public:
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 = &image;
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
167private:
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