Debian Codegraph @

Sources/nCine/Graphics/RHI/Vulkan/VulkanDevice.cpp

raw
1 #include "VulkanDevice.h"
2 #include "VulkanShaderProgram.h"
3 #include "VulkanRenderTarget.h"
4 #include "VulkanTexture.h"
5 #include "VulkanBufferObject.h"
6 #include "VulkanCommon.h"
7
8 #include <cstdint>
9 #include <cstring>
10 #include <vector>
11 #include <unordered_map>
12
13 // vulkan.h comes from VulkanCommon.h (with VK_NO_PROTOTYPES). SDL_vulkan.h is included only here (the loader
14 // bootstrap + surface creation live in this translation unit); it must see the real Vulkan handle types.
15 #if defined(WITH_SDL2) || defined(WITH_SDL3)
16 # if !defined(CMAKE_BUILD) && defined(__has_include)
17 # if defined(WITH_SDL3) && __has_include("SDL3/SDL_vulkan.h")
18 # define __HAS_LOCAL_SDL3_VULKAN
19 # elif __has_include("SDL2/SDL_vulkan.h")
20 # define __HAS_LOCAL_SDL_VULKAN
21 # endif
22 # endif
23 # if defined(WITH_SDL3)
24 # if defined(__HAS_LOCAL_SDL3_VULKAN)
25 # include "SDL3/SDL.h"
26 # include "SDL3/SDL_vulkan.h"
27 # else
28 # include <SDL3/SDL.h>
29 # include <SDL3/SDL_vulkan.h>
30 # endif
31 # elif defined(__HAS_LOCAL_SDL_VULKAN)
32 # include "SDL2/SDL.h"
33 # include "SDL2/SDL_vulkan.h"
34 # else
35 # include <SDL.h>
36 # include <SDL_vulkan.h>
37 # endif
38 #endif
39
40 #include <Asserts.h>
41
42 namespace nCine::RHI::Vulkan
43 {
44 // -- Loader entry points (declared extern in VulkanCommon.h; resolved through vkGetInstanceProcAddr /
45 // vkGetDeviceProcAddr in the Load*Functions() below). Defined here at namespace scope so every backend
46 // translation unit shares them. --
47 PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = nullptr;
48
49 PFN_vkCreateInstance vkCreateInstance = nullptr;
50 PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties = nullptr;
51 PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties = nullptr;
52
53 PFN_vkDestroyInstance vkDestroyInstance = nullptr;
54 PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices = nullptr;
55 PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties = nullptr;
56 PFN_vkGetPhysicalDeviceFeatures vkGetPhysicalDeviceFeatures = nullptr;
57 PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties = nullptr;
58 PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties = nullptr;
59 PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties = nullptr;
60 PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties = nullptr;
61 PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR = nullptr;
62 PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR = nullptr;
63 PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR = nullptr;
64 PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR = nullptr;
65 PFN_vkCreateDevice vkCreateDevice = nullptr;
66 PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr = nullptr;
67 PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR = nullptr;
68 PFN_vkCreateDebugUtilsMessengerEXT vkCreateDebugUtilsMessengerEXT = nullptr;
69 PFN_vkDestroyDebugUtilsMessengerEXT vkDestroyDebugUtilsMessengerEXT = nullptr;
70
71 PFN_vkDestroyDevice vkDestroyDevice = nullptr;
72 PFN_vkDeviceWaitIdle vkDeviceWaitIdle = nullptr;
73 PFN_vkGetDeviceQueue vkGetDeviceQueue = nullptr;
74 PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR = nullptr;
75 PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR = nullptr;
76 PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR = nullptr;
77 PFN_vkCreateImageView vkCreateImageView = nullptr;
78 PFN_vkDestroyImageView vkDestroyImageView = nullptr;
79 PFN_vkCreateCommandPool vkCreateCommandPool = nullptr;
80 PFN_vkDestroyCommandPool vkDestroyCommandPool = nullptr;
81 PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers = nullptr;
82 PFN_vkFreeCommandBuffers vkFreeCommandBuffers = nullptr;
83 PFN_vkResetCommandBuffer vkResetCommandBuffer = nullptr;
84 PFN_vkBeginCommandBuffer vkBeginCommandBuffer = nullptr;
85 PFN_vkEndCommandBuffer vkEndCommandBuffer = nullptr;
86 PFN_vkCmdClearColorImage vkCmdClearColorImage = nullptr;
87 PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier = nullptr;
88 PFN_vkCreateSemaphore vkCreateSemaphore = nullptr;
89 PFN_vkDestroySemaphore vkDestroySemaphore = nullptr;
90 PFN_vkCreateFence vkCreateFence = nullptr;
91 PFN_vkDestroyFence vkDestroyFence = nullptr;
92 PFN_vkWaitForFences vkWaitForFences = nullptr;
93 PFN_vkResetFences vkResetFences = nullptr;
94 PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR = nullptr;
95 PFN_vkQueueSubmit vkQueueSubmit = nullptr;
96 PFN_vkQueuePresentKHR vkQueuePresentKHR = nullptr;
97 PFN_vkQueueWaitIdle vkQueueWaitIdle = nullptr;
98
99 PFN_vkCreateBuffer vkCreateBuffer = nullptr;
100 PFN_vkDestroyBuffer vkDestroyBuffer = nullptr;
101 PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements = nullptr;
102 PFN_vkBindBufferMemory vkBindBufferMemory = nullptr;
103 PFN_vkCreateImage vkCreateImage = nullptr;
104 PFN_vkDestroyImage vkDestroyImage = nullptr;
105 PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements = nullptr;
106 PFN_vkBindImageMemory vkBindImageMemory = nullptr;
107 PFN_vkAllocateMemory vkAllocateMemory = nullptr;
108 PFN_vkFreeMemory vkFreeMemory = nullptr;
109 PFN_vkMapMemory vkMapMemory = nullptr;
110 PFN_vkUnmapMemory vkUnmapMemory = nullptr;
111 PFN_vkCreateSampler vkCreateSampler = nullptr;
112 PFN_vkDestroySampler vkDestroySampler = nullptr;
113 PFN_vkCreateShaderModule vkCreateShaderModule = nullptr;
114 PFN_vkDestroyShaderModule vkDestroyShaderModule = nullptr;
115 PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout = nullptr;
116 PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout = nullptr;
117 PFN_vkCreateDescriptorPool vkCreateDescriptorPool = nullptr;
118 PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool = nullptr;
119 PFN_vkResetDescriptorPool vkResetDescriptorPool = nullptr;
120 PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets = nullptr;
121 PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets = nullptr;
122 PFN_vkCreatePipelineLayout vkCreatePipelineLayout = nullptr;
123 PFN_vkDestroyPipelineLayout vkDestroyPipelineLayout = nullptr;
124 PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines = nullptr;
125 PFN_vkDestroyPipeline vkDestroyPipeline = nullptr;
126 PFN_vkCreatePipelineCache vkCreatePipelineCache = nullptr;
127 PFN_vkDestroyPipelineCache vkDestroyPipelineCache = nullptr;
128 PFN_vkCmdCopyImageToBuffer vkCmdCopyImageToBuffer = nullptr;
129 PFN_vkCreateRenderPass vkCreateRenderPass = nullptr;
130 PFN_vkDestroyRenderPass vkDestroyRenderPass = nullptr;
131 PFN_vkCreateFramebuffer vkCreateFramebuffer = nullptr;
132 PFN_vkDestroyFramebuffer vkDestroyFramebuffer = nullptr;
133 PFN_vkCmdBeginRenderPass vkCmdBeginRenderPass = nullptr;
134 PFN_vkCmdEndRenderPass vkCmdEndRenderPass = nullptr;
135 PFN_vkCmdBindPipeline vkCmdBindPipeline = nullptr;
136 PFN_vkCmdBindVertexBuffers vkCmdBindVertexBuffers = nullptr;
137 PFN_vkCmdBindIndexBuffer vkCmdBindIndexBuffer = nullptr;
138 PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets = nullptr;
139 PFN_vkCmdSetViewport vkCmdSetViewport = nullptr;
140 PFN_vkCmdSetScissor vkCmdSetScissor = nullptr;
141 PFN_vkCmdDraw vkCmdDraw = nullptr;
142 PFN_vkCmdDrawIndexed vkCmdDrawIndexed = nullptr;
143 PFN_vkCmdCopyBuffer vkCmdCopyBuffer = nullptr;
144 PFN_vkCmdCopyBufferToImage vkCmdCopyBufferToImage = nullptr;
145 PFN_vkCmdClearAttachments vkCmdClearAttachments = nullptr;
146 PFN_vkCmdBlitImage vkCmdBlitImage = nullptr;
147
148 namespace
149 {
150 // -- Owned Vulkan objects --
151 VkInstance s_instance = VK_NULL_HANDLE;
152 VkDebugUtilsMessengerEXT s_debugMessenger = VK_NULL_HANDLE;
153 VkPhysicalDevice s_physicalDevice = VK_NULL_HANDLE;
154 VkPhysicalDeviceMemoryProperties s_memProps = {};
155 VkDevice s_device = VK_NULL_HANDLE;
156 VkSurfaceKHR s_surface = VK_NULL_HANDLE;
157 VkQueue s_graphicsQueue = VK_NULL_HANDLE;
158 VkQueue s_presentQueue = VK_NULL_HANDLE;
159 std::uint32_t s_graphicsFamily = 0;
160 std::uint32_t s_presentFamily = 0;
161 VkDeviceSize s_minUboAlign = 256;
162 // Physical-device limits published through VulkanRhiCapabilities (safe pre-creation defaults)
163 std::uint32_t s_maxImageDim2D = 16384;
164 std::uint32_t s_maxUniformRange = 64 * 1024;
165 bool s_depthClamp = false;
166
167 VkSwapchainKHR s_swapchain = VK_NULL_HANDLE;
168 VkFormat s_swapchainFormat = VK_FORMAT_B8G8R8A8_UNORM;
169 VkExtent2D s_swapchainExtent = { 0, 0 };
170 std::vector<VkImage> s_swapchainImages;
171 std::vector<VkImageView> s_swapchainImageViews;
172
173 VkCommandPool s_commandPool = VK_NULL_HANDLE;
174
175 // -- Frames in flight --
176 // Each in-flight frame owns a command buffer, an image-available semaphore, an in-flight fence, its own
177 // descriptor pools and a slice of the uniform ring, so the CPU can record frame N+1 while the GPU still
178 // runs frame N (BeginFrame waits only THIS slot's fence, not a global idle). The render-finished semaphore
179 // is per-SWAP-CHAIN-IMAGE (s_renderFinishedPerImage), never per-frame, so a binary semaphore is never
180 // re-signalled before the present that waits on it has consumed it - the resize / out-of-date hazard the
181 // old single-frame, two-binary-semaphore model deadlocked on.
182 // One frame in flight (serial): BeginFrame waits this slot's fence, so the previous frame's GPU work is
183 // fully complete before the next frame records/executes. This is REQUIRED for correctness here because the
184 // engine renders every frame into SHARED, single-instance render targets (the scene/bloom/lighting/combine
185 // targets, the screen image, and the per-frame-updated palette texture) that are reused across frames. With
186 // >1 frame in flight, frame N+1 would start writing those shared targets while the GPU still reads them for
187 // frame N - a cross-frame write-after-read the engine's intra-frame render-pass (VK_SUBPASS_EXTERNAL)
188 // dependencies do NOT cover - which surfaces as rare, random one-frame flashes of wrong content. Serial
189 // execution removes that race by construction. (Raising this again would require double-buffering every
190 // engine render target per frame slot; the machinery below stays parameterized on this constant so that is
191 // possible later.) The other Vulkan perf wins - no per-frame palette upload stall, within-frame descriptor/
192 // UBO reuse, per-swap-chain-image render-finished semaphores, deferred resource destruction - are all
193 // independent of the in-flight count and remain in effect.
194 static constexpr std::uint32_t MaxFramesInFlight = 1;
195 struct FrameData
196 {
197 VkCommandBuffer CommandBuffer = VK_NULL_HANDLE;
198 VkSemaphore ImageAvailable = VK_NULL_HANDLE;
199 VkFence InFlightFence = VK_NULL_HANDLE;
200 bool FenceInFlight = false; // true only between a successful submit and the next BeginFrame wait
201 std::vector<VkDescriptorPool> DescPools; // per-frame; reset when this slot is re-entered
202 std::size_t DescPoolCursor = 0;
203 VkDeviceSize UboCursor = 0; // relative to this frame's uniform-ring region base
204 std::vector<VkBuffer> PendingStagingBuffers; // texture-upload staging, freed once this slot's fence re-signals
205 std::vector<VkDeviceMemory> PendingStagingMemory;
206 };
207 FrameData s_frames[MaxFramesInFlight];
208 std::uint32_t s_currentFrame = 0;
209 VkCommandBuffer s_commandBuffer = VK_NULL_HANDLE; // == s_frames[s_currentFrame].CommandBuffer while recording (set in BeginFrame)
210
211 // One render-finished semaphore per swap-chain image (signalled by submit, waited by present) plus a fence
212 // per image tracking which in-flight frame last used it, so an image is never re-acquired while a previous
213 // frame that targeted it is still running (the standard imagesInFlight pattern).
214 std::vector<VkSemaphore> s_renderFinishedPerImage;
215 std::vector<VkFence> s_imagesInFlight;
216
217 // The "screen" (default framebuffer): every no-render-target draw goes here, then PresentFrame() blits
218 // it (vertically flipped) into the acquired swap-chain image. The whole scene is rendered GL-bottom-up
219 // (positive-height viewport, no projection flip), so off-screen render targets round-trip exactly like
220 // GL; the single flip at present is the only GL->Vulkan scan-out correction (mirrors the software
221 // backend's SDL_FLIP_VERTICAL and the D3D11 flip-blit).
222 VkImage s_screenImage = VK_NULL_HANDLE;
223 VkDeviceMemory s_screenMemory = VK_NULL_HANDLE;
224 VkImageView s_screenView = VK_NULL_HANDLE;
225 VkFramebuffer s_screenFramebuffer = VK_NULL_HANDLE;
226 VkImageLayout s_screenLayout = VK_IMAGE_LAYOUT_UNDEFINED;
227 VkExtent2D s_screenExtent = { 0, 0 };
228
229 bool s_vsync = true;
230 bool s_ready = false;
231 void* s_sdlWindow = nullptr;
232
233 // Per-frame uniform ring (host-visible, persistently mapped): every draw's _Globals + uniform-block
234 // bytes are copied here at device-aligned offsets, so the descriptor's UBO bind offset always meets
235 // minUniformBufferOffsetAlignment (the streaming buffer's own alignment can be smaller).
236 VkBuffer s_uboRing = VK_NULL_HANDLE;
237 VkDeviceMemory s_uboRingMem = VK_NULL_HANDLE;
238 std::uint8_t* s_uboRingMapped = nullptr;
239 VkDeviceSize s_uboRingSize = 0;
240 VkDeviceSize s_uboPerFrameSize = 0; // s_uboRingSize / MaxFramesInFlight; frame i uses [i*this, (i+1)*this)
241
242 // Descriptor pools are owned per in-flight frame (see FrameData::DescPools); a set is allocated per draw
243 // from the current frame's pools and the whole frame's pools are reset when that slot is re-entered.
244
245 // Within-frame reuse caches (cleared each BeginFrame, current-frame only): draws with identical uniform
246 // CONTENTS share one uniform-ring region, and draws with an identical binding tuple (program + textures +
247 // uniform region) share one descriptor set - so the common run of same-material draws skips the per-draw
248 // vkAllocateDescriptorSets + vkUpdateDescriptorSets + ring copy. Keyed by 64-bit FNV-1a (as s_pipelines is);
249 // UBO reuse additionally memcmp-verifies the bytes on a hash hit, so it is collision-proof.
250 std::unordered_map<std::uint64_t, VkDeviceSize> s_frameUboByHash;
251 std::unordered_map<std::uint64_t, VkDescriptorSet> s_frameSetByHash;
252 std::vector<std::uint8_t> s_uboScratch; // reused uniform-gather buffer
253
254 // Color-only render passes keyed by the full attachment-format signature - count + per-attachment format -
255 // (loadOp LOAD, layout COLOR_ATTACHMENT_OPTIMAL). Single-attachment targets and the screen use count 1;
256 // multi-render-target framebuffers get a compatible pass over all their attachments.
257 struct RenderPassKey
258 {
259 std::uint32_t count;
260 std::uint32_t formats[VulkanRenderTarget::MaxColorAttachments];
261 bool operator==(const RenderPassKey& o) const {
262 if (count != o.count) {
263 return false;
264 }
265 for (std::uint32_t i = 0; i < count; i++) {
266 if (formats[i] != o.formats[i]) {
267 return false;
268 }
269 }
270 return true;
271 }
272 };
273 struct RenderPassKeyHash
274 {
275 std::size_t operator()(const RenderPassKey& k) const {
276 std::uint64_t h = 1469598103934665603ull;
277 auto mix = [&h](std::uint64_t v) { h ^= v; h *= 1099511628211ull; };
278 mix(k.count);
279 for (std::uint32_t i = 0; i < k.count; i++) {
280 mix(k.formats[i]);
281 }
282 return std::size_t(h);
283 }
284 };
285 std::unordered_map<RenderPassKey, VkRenderPass, RenderPassKeyHash> s_renderPasses;
286
287 // 1x1 white fallback texture bound when a sampler has no texture (keeps the descriptor valid)
288 VkImage s_dummyImage = VK_NULL_HANDLE;
289 VkDeviceMemory s_dummyMemory = VK_NULL_HANDLE;
290 VkImageView s_dummyView = VK_NULL_HANDLE;
291 VkSampler s_dummySampler = VK_NULL_HANDLE;
292
293 // -- Graphics pipeline cache --
294 struct PipelineKey
295 {
296 std::uint32_t programHandle;
297 std::uint64_t renderPass;
298 std::uint32_t stride;
299 std::uint32_t blendKey;
300 std::uint32_t rasterKey;
301 std::uint32_t topology;
302 std::uint32_t hasVertexInput;
303 std::uint32_t colorAttachmentCount; // the subpass attachment count (the blend-state array is sized to it)
304 bool operator==(const PipelineKey& o) const {
305 return programHandle == o.programHandle && renderPass == o.renderPass && stride == o.stride &&
306 blendKey == o.blendKey && rasterKey == o.rasterKey && topology == o.topology &&
307 hasVertexInput == o.hasVertexInput && colorAttachmentCount == o.colorAttachmentCount;
308 }
309 };
310 struct PipelineKeyHash
311 {
312 std::size_t operator()(const PipelineKey& k) const {
313 std::uint64_t h = 1469598103934665603ull;
314 auto mix = [&h](std::uint64_t v) { h ^= v; h *= 1099511628211ull; };
315 mix(k.programHandle); mix(k.renderPass); mix(k.stride);
316 mix(k.blendKey); mix(k.rasterKey); mix(std::uint64_t(k.topology) | (std::uint64_t(k.hasVertexInput) << 32));
317 mix(k.colorAttachmentCount);
318 return std::size_t(h);
319 }
320 };
321 std::unordered_map<PipelineKey, VkPipeline, PipelineKeyHash> s_pipelines;
322
323 // -- Frame recording state --
324 bool s_frameActive = false;
325 bool s_renderPassOpen = false;
326 VulkanRenderTarget* s_activeRenderPassTarget = nullptr;
327
328 bool CheckVk(VkResult result, const char* what)
329 {
330 if (result != VK_SUCCESS) {
331 LOGE("{} failed (VkResult {})", what, static_cast<std::int32_t>(result));
332 return false;
333 }
334 return true;
335 }
336
337 // Defined near the loader at the bottom; forward-declared so CreateSwapchain can reference it
338 VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
339 VkDebugUtilsMessageTypeFlagsEXT types, const VkDebugUtilsMessengerCallbackDataEXT* data, void* user);
340
341 VkPrimitiveTopology MapPrimitive(PrimitiveType p)
342 {
343 switch (p) {
344 case PrimitiveType::Points: return VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
345 case PrimitiveType::Lines: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
346 case PrimitiveType::LineStrip:
347 case PrimitiveType::LineLoop: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
348 case PrimitiveType::Triangles: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
349 case PrimitiveType::TriangleStrip: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
350 case PrimitiveType::TriangleFan: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN;
351 default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
352 }
353 }
354
355 std::uint32_t BlendCode(nCine::BlendingFactor f)
356 {
357 switch (f) {
358 case nCine::BlendingFactor::Zero: return 0;
359 case nCine::BlendingFactor::One: return 1;
360 case nCine::BlendingFactor::SrcColor: return 2;
361 case nCine::BlendingFactor::OneMinusSrcColor: return 3;
362 case nCine::BlendingFactor::SrcAlpha: return 4;
363 case nCine::BlendingFactor::OneMinusSrcAlpha: return 5;
364 case nCine::BlendingFactor::DstAlpha: return 6;
365 case nCine::BlendingFactor::OneMinusDstAlpha: return 7;
366 case nCine::BlendingFactor::DstColor: return 8;
367 case nCine::BlendingFactor::OneMinusDstColor: return 9;
368 case nCine::BlendingFactor::SrcAlphaSaturate: return 10;
369 case nCine::BlendingFactor::ConstantColor: return 11;
370 case nCine::BlendingFactor::OneMinusConstantColor: return 12;
371 case nCine::BlendingFactor::ConstantAlpha: return 13;
372 case nCine::BlendingFactor::OneMinusConstantAlpha: return 14;
373 default: return 1;
374 }
375 }
376
377 VkBlendFactor MapBlend(nCine::BlendingFactor f)
378 {
379 // Vulkan applies each factor per-component (the alpha channel of e.g. SRC_COLOR is the source
380 // alpha), so unlike the D3D11 backend no separate color/alpha remapping is needed.
381 switch (f) {
382 case nCine::BlendingFactor::Zero: return VK_BLEND_FACTOR_ZERO;
383 case nCine::BlendingFactor::One: return VK_BLEND_FACTOR_ONE;
384 case nCine::BlendingFactor::SrcColor: return VK_BLEND_FACTOR_SRC_COLOR;
385 case nCine::BlendingFactor::OneMinusSrcColor: return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR;
386 case nCine::BlendingFactor::SrcAlpha: return VK_BLEND_FACTOR_SRC_ALPHA;
387 case nCine::BlendingFactor::OneMinusSrcAlpha: return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
388 case nCine::BlendingFactor::DstAlpha: return VK_BLEND_FACTOR_DST_ALPHA;
389 case nCine::BlendingFactor::OneMinusDstAlpha: return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA;
390 case nCine::BlendingFactor::DstColor: return VK_BLEND_FACTOR_DST_COLOR;
391 case nCine::BlendingFactor::OneMinusDstColor: return VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR;
392 case nCine::BlendingFactor::SrcAlphaSaturate: return VK_BLEND_FACTOR_SRC_ALPHA_SATURATE;
393 case nCine::BlendingFactor::ConstantColor: return VK_BLEND_FACTOR_CONSTANT_COLOR;
394 case nCine::BlendingFactor::OneMinusConstantColor: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR;
395 case nCine::BlendingFactor::ConstantAlpha: return VK_BLEND_FACTOR_CONSTANT_ALPHA;
396 case nCine::BlendingFactor::OneMinusConstantAlpha: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA;
397 default: return VK_BLEND_FACTOR_ONE;
398 }
399 }
400
401 VkFormat AttributeFormat(std::int32_t componentCount, std::uint32_t type, bool normalized)
402 {
403 // The recorded type uses the GL numeric constants (see VertexAttribType); 0 (unset) means float.
404 // Unsigned-byte attributes (e.g. the ImGui vertex color, 4 x u8 normalized) map to the R8 formats.
405 if (type == std::uint32_t(VertexAttribType::UnsignedByte)) {
406 if (normalized) {
407 switch (componentCount) {
408 case 1: return VK_FORMAT_R8_UNORM;
409 case 2: return VK_FORMAT_R8G8_UNORM;
410 case 3: return VK_FORMAT_R8G8B8_UNORM;
411 default: return VK_FORMAT_R8G8B8A8_UNORM;
412 }
413 }
414 switch (componentCount) {
415 case 1: return VK_FORMAT_R8_UINT;
416 case 2: return VK_FORMAT_R8G8_UINT;
417 case 3: return VK_FORMAT_R8G8B8_UINT;
418 default: return VK_FORMAT_R8G8B8A8_UINT;
419 }
420 }
421 switch (componentCount) {
422 case 1: return VK_FORMAT_R32_SFLOAT;
423 case 2: return VK_FORMAT_R32G32_SFLOAT;
424 case 3: return VK_FORMAT_R32G32B32_SFLOAT;
425 default: return VK_FORMAT_R32G32B32A32_SFLOAT;
426 }
427 }
428
429 void ImageBarrier(VkCommandBuffer cmd, VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout,
430 VkPipelineStageFlags srcStage, VkPipelineStageFlags dstStage, VkAccessFlags srcAccess, VkAccessFlags dstAccess)
431 {
432 VkImageMemoryBarrier b = {};
433 b.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
434 b.oldLayout = oldLayout;
435 b.newLayout = newLayout;
436 b.srcAccessMask = srcAccess;
437 b.dstAccessMask = dstAccess;
438 b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
439 b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
440 b.image = image;
441 b.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
442 vkCmdPipelineBarrier(cmd, srcStage, dstStage, 0, 0, nullptr, 0, nullptr, 1, &b);
443 }
444
445 VkDescriptorPool CreateDescriptorPool()
446 {
447 VkDescriptorPoolSize sizes[2];
448 sizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
449 sizes[0].descriptorCount = 4096;
450 sizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
451 sizes[1].descriptorCount = 4096;
452 VkDescriptorPoolCreateInfo pci = {};
453 pci.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
454 pci.maxSets = 4096;
455 pci.poolSizeCount = 2;
456 pci.pPoolSizes = sizes;
457 VkDescriptorPool pool = VK_NULL_HANDLE;
458 vkCreateDescriptorPool(s_device, &pci, nullptr, &pool);
459 return pool;
460 }
461
462 VkDescriptorSet AllocDescriptorSet(VkDescriptorSetLayout layout)
463 {
464 FrameData& fr = s_frames[s_currentFrame];
465 for (;;) {
466 if (fr.DescPoolCursor >= fr.DescPools.size()) {
467 VkDescriptorPool pool = CreateDescriptorPool();
468 if (pool == VK_NULL_HANDLE) {
469 return VK_NULL_HANDLE;
470 }
471 fr.DescPools.push_back(pool);
472 }
473 VkDescriptorSetAllocateInfo ai = {};
474 ai.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
475 ai.descriptorPool = fr.DescPools[fr.DescPoolCursor];
476 ai.descriptorSetCount = 1;
477 ai.pSetLayouts = &layout;
478 VkDescriptorSet set = VK_NULL_HANDLE;
479 const VkResult r = vkAllocateDescriptorSets(s_device, &ai, &set);
480 if (r == VK_SUCCESS) {
481 return set;
482 }
483 // Pool exhausted/fragmented: advance to the next pool (creating one if needed) and retry
484 fr.DescPoolCursor++;
485 }
486 }
487
488 // Bump-allocates an aligned range within the CURRENT frame's slice of the uniform ring; returns the
489 // absolute byte offset into s_uboRing. Each in-flight frame owns a disjoint [base, base+perFrame) region
490 // so a host write for frame N+1 never lands in bytes the GPU still reads for frame N.
491 bool AllocUbo(VkDeviceSize size, VkDeviceSize& outOffset)
492 {
493 if (size == 0) {
494 size = 16;
495 }
496 FrameData& fr = s_frames[s_currentFrame];
497 const VkDeviceSize base = VkDeviceSize(s_currentFrame) * s_uboPerFrameSize;
498 const VkDeviceSize alignedRel = (fr.UboCursor + s_minUboAlign - 1) & ~(s_minUboAlign - 1);
499 if (alignedRel + size > s_uboPerFrameSize) {
500 return false;
501 }
502 outOffset = base + alignedRel;
503 fr.UboCursor = alignedRel + size;
504 return true;
505 }
506
507 // -- Deferred resource destruction (see VkEnqueueDestroy in VulkanCommon.h) --
508 // A resource enqueued for destruction may still be referenced by any of the frames that were in flight at
509 // enqueue time (up to MaxFramesInFlight). Each entry carries a bitmask of the frame slots whose in-flight
510 // frame must still complete before it is safe to free; the mask starts with every slot's bit set. In
511 // BeginFrame, after a slot's fence has signalled (that slot's previous frame is done), that slot's bit is
512 // cleared on every pending entry; once an entry's mask reaches zero, every frame that could have referenced
513 // it has completed and it is freed. (A bitmask rather than a countdown so a slot whose fence is waited twice
514 // - e.g. an out-of-date-drop path that does not advance the frame index - can never free an entry early.)
515 struct PendingDestroy
516 {
517 VkDeferredResource Type;
518 std::uint64_t Handle;
519 std::uint32_t PendingSlots;
520 };
521 std::vector<PendingDestroy> s_pendingDestroys;
522
523 void FreeDeferredResource(const PendingDestroy& p)
524 {
525 if (s_device == VK_NULL_HANDLE || p.Handle == 0) {
526 return;
527 }
528 switch (p.Type) {
529 case VkDeferredResource::Image: vkDestroyImage(s_device, reinterpret_cast<VkImage>(p.Handle), nullptr); break;
530 case VkDeferredResource::ImageView: vkDestroyImageView(s_device, reinterpret_cast<VkImageView>(p.Handle), nullptr); break;
531 case VkDeferredResource::Sampler: vkDestroySampler(s_device, reinterpret_cast<VkSampler>(p.Handle), nullptr); break;
532 case VkDeferredResource::Buffer: vkDestroyBuffer(s_device, reinterpret_cast<VkBuffer>(p.Handle), nullptr); break;
533 case VkDeferredResource::DeviceMemory: vkFreeMemory(s_device, reinterpret_cast<VkDeviceMemory>(p.Handle), nullptr); break;
534 case VkDeferredResource::Framebuffer: vkDestroyFramebuffer(s_device, reinterpret_cast<VkFramebuffer>(p.Handle), nullptr); break;
535 }
536 }
537
538 // Clears the just-signalled slot's bit on every pending entry and frees those no in-flight frame can still
539 // reference. Called from BeginFrame right after waiting s_currentFrame's fence (so that slot's prior frame -
540 // the only one that could have owned that bit - is guaranteed complete before the bit is cleared).
541 void TickDeferredDestroys(std::uint32_t signalledSlot)
542 {
543 if (s_pendingDestroys.empty()) {
544 return;
545 }
546 const std::uint32_t slotBit = (1u << signalledSlot);
547 for (std::size_t i = 0; i < s_pendingDestroys.size(); ) {
548 PendingDestroy& p = s_pendingDestroys[i];
549 p.PendingSlots &= ~slotBit;
550 if (p.PendingSlots == 0) {
551 FreeDeferredResource(p);
552 s_pendingDestroys[i] = s_pendingDestroys.back();
553 s_pendingDestroys.pop_back();
554 } else {
555 i++;
556 }
557 }
558 }
559
560 // Frees every pending resource immediately, ignoring the fence bitmask. ONLY safe after a vkDeviceWaitIdle
561 // (no frame is in flight) - used by the resize / device-teardown paths so nothing leaks or dangles.
562 void FlushDeferredDestroys()
563 {
564 for (const PendingDestroy& p : s_pendingDestroys) {
565 FreeDeferredResource(p);
566 }
567 s_pendingDestroys.clear();
568 }
569 }
570
571 // -- Static state --
572
573 VulkanDevice::BlendingState VulkanDevice::_blending;
574 VulkanDevice::DepthTestState VulkanDevice::_depthTest;
575 VulkanDevice::CullFaceState VulkanDevice::_cullFace;
576 VulkanDevice::ScissorState VulkanDevice::_scissor;
577 Recti VulkanDevice::_viewport(0, 0, 0, 0);
578 Colorf VulkanDevice::_clearColor(0.0f, 0.0f, 0.0f, 0.0f);
579
580 VulkanShaderProgram* VulkanDevice::_currentProgram = nullptr;
581 const VulkanTexture* VulkanDevice::_boundTextures[MaxTextureUnits] = {};
582 VulkanDevice::UniformRange VulkanDevice::_boundUniformRanges[MaxUniformBindings] = {};
583 VulkanRenderTarget* VulkanDevice::_currentRenderTarget = nullptr;
584
585 // -- Shared context accessors (declared in VulkanCommon.h) --
586
587 VkDevice VkDeviceHandle() { return s_device; }
588 VkPhysicalDevice VkPhysicalDeviceHandle() { return s_physicalDevice; }
589 VkDeviceSize VkMinUniformBufferOffsetAlignment() { return s_minUboAlign; }
590
591 std::int32_t VulkanDevice::GetMaxTextureDimension()
592 {
593 return (s_maxImageDim2D > 0x7FFFFFFFu ? 0x7FFFFFFF : std::int32_t(s_maxImageDim2D));
594 }
595
596 std::int32_t VulkanDevice::GetUniformBufferOffsetAlignment()
597 {
598 return std::int32_t(s_minUboAlign);
599 }
600
601 std::int32_t VulkanDevice::GetMaxUniformBufferRange()
602 {
603 return (s_maxUniformRange > 0x7FFFFFFFu ? 0x7FFFFFFF : std::int32_t(s_maxUniformRange));
604 }
605
606 std::uint32_t VkFindMemoryType(std::uint32_t typeBits, VkMemoryPropertyFlags properties)
607 {
608 for (std::uint32_t i = 0; i < s_memProps.memoryTypeCount; i++) {
609 if ((typeBits & (1u << i)) != 0 && (s_memProps.memoryTypes[i].propertyFlags & properties) == properties) {
610 return i;
611 }
612 }
613 return UINT32_MAX;
614 }
615
616 VkCommandBuffer VkBeginOneTimeCommands()
617 {
618 if (s_device == VK_NULL_HANDLE || s_commandPool == VK_NULL_HANDLE) {
619 return VK_NULL_HANDLE;
620 }
621 VkCommandBufferAllocateInfo ai = {};
622 ai.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
623 ai.commandPool = s_commandPool;
624 ai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
625 ai.commandBufferCount = 1;
626 VkCommandBuffer cmd = VK_NULL_HANDLE;
627 if (vkAllocateCommandBuffers(s_device, &ai, &cmd) != VK_SUCCESS) {
628 return VK_NULL_HANDLE;
629 }
630 VkCommandBufferBeginInfo bi = {};
631 bi.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
632 bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
633 vkBeginCommandBuffer(cmd, &bi);
634 return cmd;
635 }
636
637 void VkEndOneTimeCommands(VkCommandBuffer cmd)
638 {
639 if (cmd == VK_NULL_HANDLE) {
640 return;
641 }
642 vkEndCommandBuffer(cmd);
643 VkSubmitInfo si = {};
644 si.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
645 si.commandBufferCount = 1;
646 si.pCommandBuffers = &cmd;
647 vkQueueSubmit(s_graphicsQueue, 1, &si, VK_NULL_HANDLE);
648 vkQueueWaitIdle(s_graphicsQueue);
649 vkFreeCommandBuffers(s_device, s_commandPool, 1, &cmd);
650 }
651
652 void VkRegisterFrameStaging(std::uint64_t buffer, std::uint64_t memory)
653 {
654 // The staging buffer for a texture upload recorded into the current frame's command buffer must outlive
655 // the GPU's copy. Hand it to the current in-flight frame; it is destroyed the next time that slot is
656 // entered (after its fence has signalled - see FreeFrameStaging in BeginFrame), never with a queue idle.
657 FrameData& fr = s_frames[s_currentFrame];
658 if (buffer != 0) {
659 fr.PendingStagingBuffers.push_back(reinterpret_cast<VkBuffer>(buffer));
660 }
661 if (memory != 0) {
662 fr.PendingStagingMemory.push_back(reinterpret_cast<VkDeviceMemory>(memory));
663 }
664 }
665
666 void VkEnqueueDestroy(VkDeferredResource type, std::uint64_t handle)
667 {
668 if (handle == 0) {
669 return;
670 }
671 if (s_device == VK_NULL_HANDLE) {
672 // The device (and every child object it owns) is already gone: nothing to free, nothing in flight.
673 return;
674 }
675 // The resource must outlive every frame currently in flight, so it is held until all MaxFramesInFlight
676 // frame slots have completed one more frame (each bit cleared by TickDeferredDestroys as its fence signals).
677 const std::uint32_t allSlots = (MaxFramesInFlight >= 32 ? 0xFFFFFFFFu : ((1u << MaxFramesInFlight) - 1u));
678 s_pendingDestroys.push_back(PendingDestroy{ type, handle, allSlots });
679 }
680
681 namespace
682 {
683 // Destroys the staging buffers/memory a frame slot queued last time it was recorded (safe: the caller has
684 // already waited that slot's fence, so the GPU is done reading them)
685 void FreeFrameStaging(FrameData& fr)
686 {
687 for (VkBuffer b : fr.PendingStagingBuffers) {
688 if (b != VK_NULL_HANDLE) { vkDestroyBuffer(s_device, b, nullptr); }
689 }
690 for (VkDeviceMemory m : fr.PendingStagingMemory) {
691 if (m != VK_NULL_HANDLE) { vkFreeMemory(s_device, m, nullptr); }
692 }
693 fr.PendingStagingBuffers.clear();
694 fr.PendingStagingMemory.clear();
695 }
696 }
697
698 VkRenderPass VkGetColorRenderPassMrt(const VkFormat* formats, std::uint32_t count)
699 {
700 if (count == 0 || count > VulkanRenderTarget::MaxColorAttachments) {
701 return VK_NULL_HANDLE;
702 }
703 RenderPassKey key = {};
704 key.count = count;
705 for (std::uint32_t i = 0; i < count; i++) {
706 key.formats[i] = std::uint32_t(formats[i]);
707 }
708 auto it = s_renderPasses.find(key);
709 if (it != s_renderPasses.end()) {
710 return it->second;
711 }
712
713 // Every color attachment is preserved (loadOp LOAD; the engine clears explicitly) and written by the
714 // single subpass; the external dependencies cover the sampled-image and blit consumers of ALL attachments
715 // (they are stage/access-scoped, not per-attachment, so the single-attachment scopes generalize as-is).
716 VkAttachmentDescription colors[VulkanRenderTarget::MaxColorAttachments] = {};
717 VkAttachmentReference refs[VulkanRenderTarget::MaxColorAttachments] = {};
718 for (std::uint32_t i = 0; i < count; i++) {
719 VkAttachmentDescription& color = colors[i];
720 color.format = formats[i];
721 color.samples = VK_SAMPLE_COUNT_1_BIT;
722 color.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
723 color.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
724 color.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
725 color.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
726 color.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
727 color.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
728 refs[i].attachment = i;
729 refs[i].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
730 }
731
732 VkSubpassDescription subpass = {};
733 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
734 subpass.colorAttachmentCount = count;
735 subpass.pColorAttachments = refs;
736
737 VkSubpassDependency deps[2] = {};
738 deps[0].srcSubpass = VK_SUBPASS_EXTERNAL;
739 deps[0].dstSubpass = 0;
740 deps[0].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT;
741 deps[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
742 deps[0].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT;
743 deps[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
744 deps[1].srcSubpass = 0;
745 deps[1].dstSubpass = VK_SUBPASS_EXTERNAL;
746 deps[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
747 deps[1].dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT;
748 deps[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
749 deps[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT;
750
751 VkRenderPassCreateInfo rpci = {};
752 rpci.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
753 rpci.attachmentCount = count;
754 rpci.pAttachments = colors;
755 rpci.subpassCount = 1;
756 rpci.pSubpasses = &subpass;
757 rpci.dependencyCount = 2;
758 rpci.pDependencies = deps;
759 VkRenderPass rp = VK_NULL_HANDLE;
760 if (vkCreateRenderPass(s_device, &rpci, nullptr, &rp) != VK_SUCCESS) {
761 return VK_NULL_HANDLE;
762 }
763 s_renderPasses[key] = rp;
764 return rp;
765 }
766
767 VkRenderPass VkGetColorRenderPass(VkFormat format)
768 {
769 return VkGetColorRenderPassMrt(&format, 1);
770 }
771
772 // -- Pipeline cache --
773
774 namespace
775 {
776 // Driver-level pipeline cache passed to every vkCreateGraphicsPipelines, so pipelines recreated after a
777 // swapchain rebuild (s_pipelines is dropped on resize) reuse the driver's cached compilation instead of
778 // recompiling the SPIR-V from scratch. Created lazily, destroyed with the device.
779 VkPipelineCache s_pipelineCache = VK_NULL_HANDLE;
780
781 // Last-bound state of the current command buffer (redundant vkCmd* elimination). Command-buffer state is
782 // reset by vkResetCommandBuffer, so BeginFrame() clears these; deferred destruction only frees GPU objects
783 // at that same boundary, so a recycled handle can never alias a value still cached here mid-frame.
784 VkPipeline s_lastPipeline = VK_NULL_HANDLE;
785 VkDescriptorSet s_lastDescriptorSet = VK_NULL_HANDLE;
786 VkPipelineLayout s_lastDescriptorLayout = VK_NULL_HANDLE;
787 VkBuffer s_lastVertexBuffer = VK_NULL_HANDLE;
788 VkBuffer s_lastIndexBuffer = VK_NULL_HANDLE;
789 VkIndexType s_lastIndexType = VK_INDEX_TYPE_MAX_ENUM;
790 VkViewport s_lastViewport = {};
791 VkRect2D s_lastScissor = {};
792 bool s_lastViewportValid = false;
793 bool s_lastScissorValid = false;
794
795 void ResetCommandBufferShadowState()
796 {
797 s_lastPipeline = VK_NULL_HANDLE;
798 s_lastDescriptorSet = VK_NULL_HANDLE;
799 s_lastDescriptorLayout = VK_NULL_HANDLE;
800 s_lastVertexBuffer = VK_NULL_HANDLE;
801 s_lastIndexBuffer = VK_NULL_HANDLE;
802 s_lastIndexType = VK_INDEX_TYPE_MAX_ENUM;
803 s_lastViewportValid = false;
804 s_lastScissorValid = false;
805 }
806
807 VkPipeline GetOrCreatePipeline(VulkanShaderProgram* prog, PrimitiveType primitive, VkRenderPass renderPass, std::uint32_t numColorAttachments)
808 {
809 VulkanShaderProgram::VertexAttrib attribs[16];
810 std::uint32_t attribCount = 0;
811 std::uint32_t stride = 0;
812 const bool hasVI = prog->HasVertexAttributes();
813 if (hasVI) {
814 attribCount = prog->GetVertexInput(attribs, 16, stride);
815 }
816 if (numColorAttachments == 0 || numColorAttachments > VulkanRenderTarget::MaxColorAttachments) {
817 numColorAttachments = 1;
818 }
819
820 const VulkanDevice::BlendingState blend = VulkanDevice::GetBlendingState();
821 const VulkanDevice::CullFaceState cull = VulkanDevice::GetCullFaceState();
822 const std::uint32_t blendKey = (blend.Enabled ? 1u : 0u) | (BlendCode(blend.SrcRgb) << 1) |
823 (BlendCode(blend.DstRgb) << 5) | (BlendCode(blend.SrcAlpha) << 9) | (BlendCode(blend.DstAlpha) << 13);
824 const std::uint32_t rasterKey = (cull.Enabled ? 1u : 0u) | (std::uint32_t(cull.Mode) << 1);
825
826 PipelineKey key;
827 key.programHandle = prog->GetUniqueId();
828 key.renderPass = reinterpret_cast<std::uint64_t>(renderPass);
829 key.stride = stride;
830 key.blendKey = blendKey;
831 key.rasterKey = rasterKey;
832 key.topology = std::uint32_t(MapPrimitive(primitive));
833 key.hasVertexInput = hasVI ? 1u : 0u;
834 key.colorAttachmentCount = numColorAttachments;
835
836 auto it = s_pipelines.find(key);
837 if (it != s_pipelines.end()) {
838 return it->second;
839 }
840
841 VkPipelineShaderStageCreateInfo stages[2] = {};
842 stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
843 stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
844 stages[0].module = reinterpret_cast<VkShaderModule>(prog->GetVsModule());
845 stages[0].pName = "main";
846 stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
847 stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
848 stages[1].module = reinterpret_cast<VkShaderModule>(prog->GetFsModule());
849 stages[1].pName = "main";
850
851 VkVertexInputBindingDescription binding = {};
852 VkVertexInputAttributeDescription viAttribs[16] = {};
853 std::uint32_t viAttribCount = 0;
854 if (hasVI && stride > 0) {
855 binding.binding = 0;
856 binding.stride = stride;
857 binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
858 for (std::uint32_t i = 0; i < attribCount; i++) {
859 VkVertexInputAttributeDescription& d = viAttribs[viAttribCount++];
860 d.location = attribs[i].Location;
861 d.binding = 0;
862 d.format = AttributeFormat(attribs[i].ComponentCount, attribs[i].Type, attribs[i].Normalized);
863 d.offset = attribs[i].Offset;
864 }
865 }
866 VkPipelineVertexInputStateCreateInfo vi = {};
867 vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
868 if (hasVI && stride > 0 && viAttribCount > 0) {
869 vi.vertexBindingDescriptionCount = 1;
870 vi.pVertexBindingDescriptions = &binding;
871 vi.vertexAttributeDescriptionCount = viAttribCount;
872 vi.pVertexAttributeDescriptions = viAttribs;
873 }
874
875 VkPipelineInputAssemblyStateCreateInfo ia = {};
876 ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
877 ia.topology = MapPrimitive(primitive);
878
879 VkPipelineViewportStateCreateInfo vp = {};
880 vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
881 vp.viewportCount = 1;
882 vp.scissorCount = 1;
883
884 VkPipelineRasterizationStateCreateInfo rs = {};
885 rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
886 rs.polygonMode = VK_POLYGON_MODE_FILL;
887 rs.cullMode = cull.Enabled
888 ? (cull.Mode == CullFaceMode::Front ? VK_CULL_MODE_FRONT_BIT : VK_CULL_MODE_BACK_BIT)
889 : VK_CULL_MODE_NONE;
890 rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; // GL default winding
891 rs.lineWidth = 1.0f;
892 // The engine's GL ortho produces clip.z in [-1,1]; enabling depth clamp disables near/far clipping
893 // so nothing is culled by Vulkan's [0,1] depth range (depth testing is off anyway - a 2D renderer).
894 rs.depthClampEnable = s_depthClamp ? VK_TRUE : VK_FALSE;
895
896 VkPipelineMultisampleStateCreateInfo ms = {};
897 ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
898 ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
899
900 VkPipelineDepthStencilStateCreateInfo ds = {};
901 ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
902 ds.depthTestEnable = VK_FALSE;
903 ds.depthWriteEnable = VK_FALSE;
904 ds.depthCompareOp = VK_COMPARE_OP_ALWAYS;
905
906 // One blend state per subpass color attachment (Vulkan requires attachmentCount to match the subpass).
907 // All entries share the same state, so the independentBlend device feature is not required.
908 VkPipelineColorBlendAttachmentState cba = {};
909 cba.blendEnable = blend.Enabled ? VK_TRUE : VK_FALSE;
910 cba.srcColorBlendFactor = MapBlend(blend.SrcRgb);
911 cba.dstColorBlendFactor = MapBlend(blend.DstRgb);
912 cba.colorBlendOp = VK_BLEND_OP_ADD;
913 cba.srcAlphaBlendFactor = MapBlend(blend.SrcAlpha);
914 cba.dstAlphaBlendFactor = MapBlend(blend.DstAlpha);
915 cba.alphaBlendOp = VK_BLEND_OP_ADD;
916 cba.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
917 VkPipelineColorBlendAttachmentState cbas[VulkanRenderTarget::MaxColorAttachments];
918 for (std::uint32_t i = 0; i < numColorAttachments; i++) {
919 cbas[i] = cba;
920 }
921 VkPipelineColorBlendStateCreateInfo cb = {};
922 cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
923 cb.attachmentCount = numColorAttachments;
924 cb.pAttachments = cbas;
925
926 const VkDynamicState dynStates[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
927 VkPipelineDynamicStateCreateInfo dyn = {};
928 dyn.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
929 dyn.dynamicStateCount = 2;
930 dyn.pDynamicStates = dynStates;
931
932 VkGraphicsPipelineCreateInfo gpci = {};
933 gpci.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
934 gpci.stageCount = 2;
935 gpci.pStages = stages;
936 gpci.pVertexInputState = &vi;
937 gpci.pInputAssemblyState = &ia;
938 gpci.pViewportState = &vp;
939 gpci.pRasterizationState = &rs;
940 gpci.pMultisampleState = &ms;
941 gpci.pDepthStencilState = &ds;
942 gpci.pColorBlendState = &cb;
943 gpci.pDynamicState = &dyn;
944 gpci.layout = reinterpret_cast<VkPipelineLayout>(prog->GetPipelineLayout());
945 gpci.renderPass = renderPass;
946 gpci.subpass = 0;
947
948 if (s_pipelineCache == VK_NULL_HANDLE && vkCreatePipelineCache != nullptr) {
949 VkPipelineCacheCreateInfo pcci = {};
950 pcci.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
951 vkCreatePipelineCache(s_device, &pcci, nullptr, &s_pipelineCache);
952 }
953
954 VkPipeline pipeline = VK_NULL_HANDLE;
955 if (vkCreateGraphicsPipelines(s_device, s_pipelineCache, 1, &gpci, nullptr, &pipeline) != VK_SUCCESS) {
956 LOGE("vkCreateGraphicsPipelines failed for program {}", prog->GetUniqueId());
957 return VK_NULL_HANDLE;
958 }
959 s_pipelines[key] = pipeline;
960 return pipeline;
961 }
962
963 // Ends the open render pass, if any
964 void EndRenderPassIfOpen()
965 {
966 if (s_renderPassOpen) {
967 vkCmdEndRenderPass(s_commandBuffer);
968 s_renderPassOpen = false;
969 }
970 }
971
972 // Transitions an image to COLOR_ATTACHMENT_OPTIMAL from its tracked layout (outside a render pass)
973 void ToColorAttachment(VkImage image, VkImageLayout& layout)
974 {
975 if (layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
976 return;
977 }
978 ImageBarrier(s_commandBuffer, image, layout, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
979 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
980 VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT);
981 layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
982 }
983
984 // Returns the (cached) render pass matching the current attachment signature of @p target - the screen's
985 // single-attachment pass when @p target is nullptr - and its subpass color-attachment count
986 VkRenderPass ResolveRenderPass(VulkanRenderTarget* target, std::uint32_t& outColorCount)
987 {
988 if (target == nullptr) {
989 outColorCount = 1;
990 return VkGetColorRenderPass(s_swapchainFormat);
991 }
992 const std::uint32_t count = target->GetAttachedCount();
993 if (count == 0) {
994 outColorCount = 0;
995 return VK_NULL_HANDLE;
996 }
997 VkFormat formats[VulkanRenderTarget::MaxColorAttachments];
998 for (std::uint32_t i = 0; i < count; i++) {
999 formats[i] = VkFormat(target->GetColorTexture(i)->GpuFormat());
1000 }
1001 outColorCount = count;
1002 return VkGetColorRenderPassMrt(formats, count);
1003 }
1004
1005 // Ensures a render pass is open for the current RHI render target (nullptr == the screen image)
1006 bool EnsureRenderPass(VulkanRenderTarget* target)
1007 {
1008 if (s_renderPassOpen && s_activeRenderPassTarget == target) {
1009 return true;
1010 }
1011 EndRenderPassIfOpen();
1012
1013 VkFramebuffer framebuffer = VK_NULL_HANDLE;
1014 VkRenderPass renderPass = VK_NULL_HANDLE;
1015 VkExtent2D extent = { 0, 0 };
1016 if (target == nullptr) {
1017 if (s_screenFramebuffer == VK_NULL_HANDLE) {
1018 return false;
1019 }
1020 ToColorAttachment(s_screenImage, s_screenLayout);
1021 framebuffer = s_screenFramebuffer;
1022 renderPass = VkGetColorRenderPass(s_swapchainFormat);
1023 extent = s_screenExtent;
1024 } else {
1025 VulkanTexture* color = target->GetColorTexture(0);
1026 const std::uint64_t fb = target->GetFramebuffer();
1027 if (color == nullptr || fb == 0) {
1028 return false;
1029 }
1030 // Every attachment of the framebuffer must be in COLOR_ATTACHMENT_OPTIMAL when the LOAD-op render
1031 // pass begins (each may have last been sampled, i.e. left in SHADER_READ_ONLY)
1032 const std::uint32_t count = target->GetAttachedCount();
1033 for (std::uint32_t i = 0; i < count; i++) {
1034 VulkanTexture* attachment = target->GetColorTexture(i);
1035 VkImage image = reinterpret_cast<VkImage>(attachment->GpuImage());
1036 VkImageLayout layout = VkImageLayout(attachment->GetCurrentLayout());
1037 ToColorAttachment(image, layout);
1038 attachment->SetCurrentLayout(std::uint32_t(layout));
1039 }
1040 std::uint32_t colorCount = 0;
1041 framebuffer = reinterpret_cast<VkFramebuffer>(fb);
1042 renderPass = ResolveRenderPass(target, colorCount);
1043 extent = { std::uint32_t(color->GetWidth()), std::uint32_t(color->GetHeight()) };
1044 }
1045 if (framebuffer == VK_NULL_HANDLE || renderPass == VK_NULL_HANDLE || extent.width == 0) {
1046 return false;
1047 }
1048
1049 VkRenderPassBeginInfo rpbi = {};
1050 rpbi.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
1051 rpbi.renderPass = renderPass;
1052 rpbi.framebuffer = framebuffer;
1053 rpbi.renderArea.offset = { 0, 0 };
1054 rpbi.renderArea.extent = extent;
1055 vkCmdBeginRenderPass(s_commandBuffer, &rpbi, VK_SUBPASS_CONTENTS_INLINE);
1056 s_renderPassOpen = true;
1057 s_activeRenderPassTarget = target;
1058 return true;
1059 }
1060 }
1061
1062 // -- Frame lifecycle --
1063
1064 namespace
1065 {
1066 void BeginFrame()
1067 {
1068 if (s_frameActive || !s_ready || s_device == VK_NULL_HANDLE) {
1069 return;
1070 }
1071 FrameData& fr = s_frames[s_currentFrame];
1072 // Wait for THIS frame slot's previous GPU work (NOT a global idle): its command buffer, descriptor
1073 // pools and uniform-ring region then become safe to reuse. With MaxFramesInFlight slots the CPU can
1074 // record this frame while the GPU still runs the other slot's frame. The fence is only waited on when
1075 // a submit actually put it in flight (FenceInFlight), so a frame that bailed before submitting - or
1076 // whose vkQueueSubmit failed and left the fence unsignalled - cannot deadlock this wait.
1077 if (fr.FenceInFlight) {
1078 vkWaitForFences(s_device, 1, &fr.InFlightFence, VK_TRUE, UINT64_MAX);
1079 fr.FenceInFlight = false;
1080 }
1081
1082 // The fence signalled => the GPU finished the frame that queued this slot's staging buffers; free them
1083 FreeFrameStaging(fr);
1084 // ...and clear this slot's bit on the deferred-destroy queue, freeing resources no in-flight frame can
1085 // still reference (a resource enqueued while this slot's frame was in flight is safe once that fence signals)
1086 TickDeferredDestroys(s_currentFrame);
1087
1088 fr.UboCursor = 0;
1089 for (VkDescriptorPool pool : fr.DescPools) {
1090 vkResetDescriptorPool(s_device, pool, 0);
1091 }
1092 fr.DescPoolCursor = 0;
1093 // The within-frame reuse caches reference this frame's (now reset) pools + ring region, so clear them
1094 s_frameUboByHash.clear();
1095 s_frameSetByHash.clear();
1096
1097 s_commandBuffer = fr.CommandBuffer;
1098 vkResetCommandBuffer(s_commandBuffer, 0);
1099 VkCommandBufferBeginInfo bi = {};
1100 bi.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1101 bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
1102 vkBeginCommandBuffer(s_commandBuffer, &bi);
1103 s_frameActive = true;
1104 s_renderPassOpen = false;
1105 s_activeRenderPassTarget = nullptr;
1106 ResetCommandBufferShadowState(); // the reset command buffer holds no bindings any more
1107
1108 // Clear the screen image to opaque black so unwritten regions are defined (the default framebuffer
1109 // starts cleared, like GL); the engine overwrites/clears again through its own passes. The screen
1110 // image is shared across in-flight frames, so the clear's source scope spans COLOR_ATTACHMENT_OUTPUT |
1111 // TRANSFER: via queue submission order this makes the clear wait for the OTHER in-flight frame's blit
1112 // read (TRANSFER) and colour writes of the screen before overwriting it (the shared-image WAR guard).
1113 if (s_screenImage != VK_NULL_HANDLE) {
1114 ImageBarrier(s_commandBuffer, s_screenImage, s_screenLayout, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1115 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
1116 VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_TRANSFER_WRITE_BIT);
1117 VkClearColorValue black = {};
1118 VkImageSubresourceRange range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
1119 vkCmdClearColorImage(s_commandBuffer, s_screenImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &black, 1, &range);
1120 ImageBarrier(s_commandBuffer, s_screenImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
1121 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
1122 s_screenLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1123 }
1124 }
1125 }
1126
1127 // -- Pipeline state (recorded; applied at draw time) --
1128
1129 void VulkanDevice::SetBlendingEnabled(bool enabled) { _blending.Enabled = enabled; }
1130
1131 void VulkanDevice::SetBlendingFactors(nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb, nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha)
1132 {
1133 _blending.SrcRgb = srcRgb;
1134 _blending.DstRgb = dstRgb;
1135 _blending.SrcAlpha = srcAlpha;
1136 _blending.DstAlpha = dstAlpha;
1137 }
1138
1139 VulkanDevice::BlendingState VulkanDevice::GetBlendingState() { return _blending; }
1140 void VulkanDevice::SetBlendingState(const BlendingState& state) { _blending = state; }
1141
1142 void VulkanDevice::SetDepthTestEnabled(bool enabled) { _depthTest.TestEnabled = enabled; }
1143 void VulkanDevice::SetDepthMaskEnabled(bool enabled) { _depthTest.MaskEnabled = enabled; }
1144 VulkanDevice::DepthTestState VulkanDevice::GetDepthTestState() { return _depthTest; }
1145 void VulkanDevice::SetDepthTestState(const DepthTestState& state) { _depthTest = state; }
1146
1147 void VulkanDevice::SetCullFaceEnabled(bool enabled) { _cullFace.Enabled = enabled; }
1148 VulkanDevice::CullFaceState VulkanDevice::GetCullFaceState() { return _cullFace; }
1149 void VulkanDevice::SetCullFaceState(const CullFaceState& state) { _cullFace = state; }
1150
1151 VulkanDevice::ScissorState VulkanDevice::GetScissorState() { return _scissor; }
1152 void VulkanDevice::SetScissorState(const ScissorState& state) { _scissor = state; }
1153 void VulkanDevice::SetScissor(const Recti& rect) { _scissor.Enabled = true; _scissor.Rect = rect; }
1154 void VulkanDevice::SetScissorTestEnabled(bool enabled) { _scissor.Enabled = enabled; }
1155
1156 Recti VulkanDevice::GetViewport() { return _viewport; }
1157 void VulkanDevice::SetViewport(const Recti& rect) { _viewport = rect; }
1158 void VulkanDevice::InitViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height) { _viewport = Recti(x, y, width, height); }
1159
1160 Colorf VulkanDevice::GetClearColor() { return _clearColor; }
1161 void VulkanDevice::SetClearColor(const Colorf& color) { _clearColor = color; }
1162
1163 void VulkanDevice::Clear(ClearFlags flags)
1164 {
1165 if ((flags & ClearFlags::Color) == ClearFlags::None) {
1166 return; // 2D renderer: no depth/stencil attachments
1167 }
1168 if (!s_ready) {
1169 return;
1170 }
1171 if (!s_frameActive) {
1172 BeginFrame();
1173 }
1174 if (!EnsureRenderPass(_currentRenderTarget)) {
1175 return;
1176 }
1177 // GL semantics: glClear covers every color attachment enabled for drawing, so clear all of the render
1178 // pass's attachments (bounded by the target's draw-buffer count, mirroring glDrawBuffers)
1179 std::uint32_t clearCount = 1;
1180 if (_currentRenderTarget != nullptr) {
1181 clearCount = _currentRenderTarget->GetAttachedCount();
1182 const std::uint32_t numDrawBuffers = _currentRenderTarget->GetNumDrawBuffers();
1183 if (numDrawBuffers > 0 && numDrawBuffers < clearCount) {
1184 clearCount = numDrawBuffers;
1185 }
1186 if (clearCount == 0) {
1187 return;
1188 }
1189 }
1190 VkClearAttachment cas[VulkanRenderTarget::MaxColorAttachments] = {};
1191 for (std::uint32_t i = 0; i < clearCount; i++) {
1192 VkClearAttachment& ca = cas[i];
1193 ca.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1194 ca.colorAttachment = i;
1195 ca.clearValue.color.float32[0] = _clearColor.R;
1196 ca.clearValue.color.float32[1] = _clearColor.G;
1197 ca.clearValue.color.float32[2] = _clearColor.B;
1198 ca.clearValue.color.float32[3] = _clearColor.A;
1199 }
1200 VkExtent2D extent = (_currentRenderTarget == nullptr) ? s_screenExtent
1201 : VkExtent2D{ std::uint32_t(_currentRenderTarget->GetColorTexture(0) ? _currentRenderTarget->GetColorTexture(0)->GetWidth() : 0),
1202 std::uint32_t(_currentRenderTarget->GetColorTexture(0) ? _currentRenderTarget->GetColorTexture(0)->GetHeight() : 0) };
1203 VkClearRect rect = {};
1204 rect.rect.offset = { 0, 0 };
1205 rect.rect.extent = extent;
1206 rect.baseArrayLayer = 0;
1207 rect.layerCount = 1;
1208 vkCmdClearAttachments(s_commandBuffer, clearCount, cas, 1, &rect);
1209 }
1210
1211 // -- Draws --
1212
1213 namespace
1214 {
1215 // FNV-1a 64-bit accumulation (same basis/prime as the pipeline cache) for the within-frame reuse caches
1216 inline void HashBytes(std::uint64_t& h, const void* data, std::size_t len)
1217 {
1218 const std::uint8_t* p = static_cast<const std::uint8_t*>(data);
1219 for (std::size_t i = 0; i < len; i++) {
1220 h ^= p[i];
1221 h *= 1099511628211ull;
1222 }
1223 }
1224 inline void HashU64(std::uint64_t& h, std::uint64_t v)
1225 {
1226 HashBytes(h, &v, sizeof(v));
1227 }
1228
1229 void BuildAndBindDescriptorSet(VulkanShaderProgram* prog)
1230 {
1231 const std::vector<VulkanShaderProgram::DescriptorBinding>& bindings = prog->GetDescriptorBindings();
1232 if (bindings.empty()) {
1233 return;
1234 }
1235 VkPipelineLayout layout = reinterpret_cast<VkPipelineLayout>(prog->GetPipelineLayout());
1236
1237 // Small fixed-capacity scratch (a program has only a handful of bindings)
1238 VkDescriptorBufferInfo bufferInfos[16];
1239 VkDescriptorImageInfo imageInfos[16];
1240 VkWriteDescriptorSet writes[16];
1241 std::uint32_t writeCount = 0;
1242
1243 // Resolve every binding's content into the writes/infos arrays and accumulate a binding-tuple hash.
1244 // UBO bytes are deduped by content so identical draws land on the same ring region (and thus the same
1245 // key), letting the whole descriptor set be reused below.
1246 std::uint64_t keyHash = 1469598103934665603ull;
1247 HashU64(keyHash, prog->GetUniqueId());
1248
1249 for (const VulkanShaderProgram::DescriptorBinding& b : bindings) {
1250 if (writeCount >= 16) {
1251 static bool warnedBindingOverflow = false;
1252 if (!warnedBindingOverflow) {
1253 warnedBindingOverflow = true;
1254 LOGW("Program {} declares more than 16 descriptor bindings, the rest are dropped", prog->GetUniqueId());
1255 }
1256 break;
1257 }
1258 VkWriteDescriptorSet& w = writes[writeCount];
1259 w = {};
1260 w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1261 w.dstSet = VK_NULL_HANDLE; // filled in below only if we actually allocate a fresh set
1262 w.dstBinding = b.binding;
1263 w.dstArrayElement = 0;
1264 w.descriptorCount = 1;
1265
1266 if (b.kind == VulkanShaderProgram::DescriptorBinding::Kind::Sampler) {
1267 const VulkanTexture* tex = VulkanDevice::GetBoundTexture(std::uint32_t(b.slot >= 0 ? b.slot : 0));
1268 VkDescriptorImageInfo& ii = imageInfos[writeCount];
1269 ii = {};
1270 if (tex != nullptr && tex->GpuView() != 0) {
1271 ii.imageView = reinterpret_cast<VkImageView>(tex->GpuView());
1272 ii.sampler = reinterpret_cast<VkSampler>(tex->GpuSampler());
1273 } else {
1274 ii.imageView = s_dummyView;
1275 ii.sampler = s_dummySampler;
1276 }
1277 ii.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1278 w.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1279 w.pImageInfo = &ii;
1280 HashU64(keyHash, 0x5a3d0000u | b.binding);
1281 HashU64(keyHash, reinterpret_cast<std::uint64_t>(ii.imageView));
1282 HashU64(keyHash, reinterpret_cast<std::uint64_t>(ii.sampler));
1283 writeCount++;
1284 continue;
1285 }
1286
1287 // UBO (Globals or a std140 block): gather the bytes into scratch, then dedupe by content
1288 VkDeviceSize size = 0;
1289 const std::uint8_t* src = nullptr;
1290 if (b.kind == VulkanShaderProgram::DescriptorBinding::Kind::Globals) {
1291 size = prog->GetGlobalsSize();
1292 } else {
1293 const std::uint32_t slot = std::uint32_t(b.slot);
1294 if (slot < VulkanDevice::MaxUniformBindingsPublic()) {
1295 const std::uint8_t* rangeData = nullptr;
1296 std::uint32_t rangeSize = 0;
1297 VulkanDevice::GetUniformRange(slot, rangeData, rangeSize);
1298 src = rangeData;
1299 size = rangeSize;
1300 }
1301 }
1302 if (size == 0) {
1303 size = 16; // keep a valid (if unused) binding
1304 }
1305 if (s_uboScratch.size() < std::size_t(size)) {
1306 s_uboScratch.resize(std::size_t(size));
1307 }
1308 std::uint8_t* gather = s_uboScratch.data();
1309 std::memset(gather, 0, std::size_t(size));
1310 if (b.kind == VulkanShaderProgram::DescriptorBinding::Kind::Globals) {
1311 // Gather the loose uniforms into their std140 slots from the program's committed values
1312 for (const VulkanShaderProgram::LooseUniform& lu : prog->GetLooseUniforms()) {
1313 const std::uint8_t* value = prog->ResolveUniform(lu.Name.data());
1314 if (value != nullptr && lu.Offset + lu.Size <= size) {
1315 std::memcpy(gather + lu.Offset, value, lu.Size);
1316 }
1317 }
1318 } else if (src != nullptr) {
1319 std::memcpy(gather, src, std::size_t(size));
1320 }
1321
1322 // Dedupe the ring region by content (hash then memcmp-verify => collision-proof)
1323 std::uint64_t contentHash = 1469598103934665603ull;
1324 HashU64(contentHash, std::uint64_t(size));
1325 HashBytes(contentHash, gather, std::size_t(size));
1326 VkDeviceSize offset = 0;
1327 auto it = s_frameUboByHash.find(contentHash);
1328 if (it != s_frameUboByHash.end() && std::memcmp(s_uboRingMapped + it->second, gather, std::size_t(size)) == 0) {
1329 offset = it->second;
1330 } else {
1331 if (!AllocUbo(size, offset)) {
1332 static bool warnedRingExhausted = false;
1333 if (!warnedRingExhausted) {
1334 warnedRingExhausted = true;
1335 LOGW("Per-frame uniform ring exhausted ({} bytes), draws are rendered with stale uniforms", s_uboPerFrameSize);
1336 }
1337 continue;
1338 }
1339 std::memcpy(s_uboRingMapped + offset, gather, std::size_t(size));
1340 s_frameUboByHash[contentHash] = offset;
1341 }
1342
1343 VkDescriptorBufferInfo& bufInfo = bufferInfos[writeCount];
1344 bufInfo = {};
1345 bufInfo.buffer = s_uboRing;
1346 bufInfo.offset = offset;
1347 bufInfo.range = size;
1348 w.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
1349 w.pBufferInfo = &bufInfo;
1350 HashU64(keyHash, 0x0b000000u | b.binding);
1351 HashU64(keyHash, std::uint64_t(offset));
1352 HashU64(keyHash, std::uint64_t(size));
1353 writeCount++;
1354 }
1355
1356 // Reuse a set with the identical binding tuple, else allocate + write one and cache it (both current-frame)
1357 VkDescriptorSet set = VK_NULL_HANDLE;
1358 auto sit = s_frameSetByHash.find(keyHash);
1359 if (sit != s_frameSetByHash.end()) {
1360 set = sit->second;
1361 } else {
1362 set = AllocDescriptorSet(reinterpret_cast<VkDescriptorSetLayout>(prog->GetDescriptorSetLayout()));
1363 if (set == VK_NULL_HANDLE) {
1364 return;
1365 }
1366 for (std::uint32_t i = 0; i < writeCount; i++) {
1367 writes[i].dstSet = set;
1368 }
1369 if (writeCount > 0) {
1370 vkUpdateDescriptorSets(s_device, writeCount, writes, 0, nullptr);
1371 }
1372 s_frameSetByHash.emplace(keyHash, set);
1373 }
1374 if (s_lastDescriptorSet != set || s_lastDescriptorLayout != layout) {
1375 vkCmdBindDescriptorSets(s_commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 0, 1, &set, 0, nullptr);
1376 s_lastDescriptorSet = set;
1377 s_lastDescriptorLayout = layout;
1378 }
1379 }
1380
1381 void ApplyViewportScissor()
1382 {
1383 const Recti vpRect = VulkanDevice::GetViewport();
1384 const VulkanDevice::ScissorState scState = VulkanDevice::GetScissorState();
1385 VkViewport vp = {};
1386 vp.x = float(vpRect.X);
1387 vp.y = float(vpRect.Y);
1388 vp.width = float(vpRect.W);
1389 vp.height = float(vpRect.H);
1390 vp.minDepth = 0.0f;
1391 vp.maxDepth = 1.0f;
1392 if (!s_lastViewportValid || std::memcmp(&s_lastViewport, &vp, sizeof(vp)) != 0) {
1393 vkCmdSetViewport(s_commandBuffer, 0, 1, &vp);
1394 s_lastViewport = vp;
1395 s_lastViewportValid = true;
1396 }
1397
1398 // The framebuffer stores rows exactly like GL (bottom-up), so the GL scissor (bottom-left origin)
1399 // maps to Vulkan framebuffer scissor with no flip; clamp it to the current render area.
1400 const VkExtent2D extent = (s_activeRenderPassTarget == nullptr) ? s_screenExtent
1401 : VkExtent2D{ std::uint32_t(s_activeRenderPassTarget->GetColorTexture(0) ? s_activeRenderPassTarget->GetColorTexture(0)->GetWidth() : 0),
1402 std::uint32_t(s_activeRenderPassTarget->GetColorTexture(0) ? s_activeRenderPassTarget->GetColorTexture(0)->GetHeight() : 0) };
1403 VkRect2D sc = {};
1404 if (scState.Enabled && scState.Rect.W > 0 && scState.Rect.H > 0) {
1405 std::int32_t x = scState.Rect.X < 0 ? 0 : scState.Rect.X;
1406 std::int32_t y = scState.Rect.Y < 0 ? 0 : scState.Rect.Y;
1407 std::int32_t w = scState.Rect.W;
1408 std::int32_t h = scState.Rect.H;
1409 if (std::uint32_t(x) > extent.width) x = std::int32_t(extent.width);
1410 if (std::uint32_t(y) > extent.height) y = std::int32_t(extent.height);
1411 if (std::uint32_t(x + w) > extent.width) w = std::int32_t(extent.width) - x;
1412 if (std::uint32_t(y + h) > extent.height) h = std::int32_t(extent.height) - y;
1413 sc.offset = { x, y };
1414 sc.extent = { std::uint32_t(w < 0 ? 0 : w), std::uint32_t(h < 0 ? 0 : h) };
1415 } else {
1416 sc.offset = { 0, 0 };
1417 sc.extent = extent;
1418 }
1419 if (!s_lastScissorValid || std::memcmp(&s_lastScissor, &sc, sizeof(sc)) != 0) {
1420 vkCmdSetScissor(s_commandBuffer, 0, 1, &sc);
1421 s_lastScissor = sc;
1422 s_lastScissorValid = true;
1423 }
1424 }
1425
1426 void DrawCommon(PrimitiveType primitive, std::int32_t firstVertex, std::uint32_t count,
1427 bool indexed, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex)
1428 {
1429 VulkanShaderProgram* prog = VulkanDevice::CurrentProgram();
1430 if (!s_ready || prog == nullptr || !prog->HasPipelineState() || count == 0) {
1431 return;
1432 }
1433 if (!s_frameActive) {
1434 BeginFrame();
1435 }
1436
1437 // Before opening the draw's render pass (barriers + buffer->image copies must be outside a render
1438 // pass), for each sampled texture: (1) flush a pending CPU texel upload into this frame's command
1439 // buffer - this replaces the old per-frame vkQueueWaitIdle upload (e.g. the palette re-uploaded every
1440 // frame); (2) else bring a sampled render-target image from COLOR_ATTACHMENT to SHADER_READ_ONLY.
1441 // Ends the current pass once if any transition/copy is due (the LOAD-op passes preserve contents).
1442 for (const VulkanShaderProgram::DescriptorBinding& b : prog->GetDescriptorBindings()) {
1443 if (b.kind != VulkanShaderProgram::DescriptorBinding::Kind::Sampler) {
1444 continue;
1445 }
1446 const VulkanTexture* tex = VulkanDevice::GetBoundTexture(std::uint32_t(b.slot >= 0 ? b.slot : 0));
1447 if (tex == nullptr) {
1448 continue;
1449 }
1450 tex->EnsureGpu();
1451 if (tex->HasPendingUpload()) {
1452 EndRenderPassIfOpen();
1453 tex->RecordStreamingUpload(reinterpret_cast<std::uint64_t>(s_commandBuffer));
1454 } else if (VkImageLayout(tex->GetCurrentLayout()) == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
1455 EndRenderPassIfOpen();
1456 ImageBarrier(s_commandBuffer, reinterpret_cast<VkImage>(tex->GpuImage()),
1457 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1458 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
1459 VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
1460 tex->SetCurrentLayout(std::uint32_t(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL));
1461 }
1462 }
1463
1464 if (!EnsureRenderPass(VulkanDevice::currentRenderTargetInternal())) {
1465 return;
1466 }
1467
1468 std::uint32_t colorCount = 0;
1469 VkRenderPass renderPass = ResolveRenderPass(s_activeRenderPassTarget, colorCount);
1470 VkPipeline pipeline = GetOrCreatePipeline(prog, primitive, renderPass, colorCount);
1471 if (pipeline == VK_NULL_HANDLE) {
1472 return;
1473 }
1474 if (s_lastPipeline != pipeline) {
1475 vkCmdBindPipeline(s_commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
1476 s_lastPipeline = pipeline;
1477 }
1478 ApplyViewportScissor();
1479 BuildAndBindDescriptorSet(prog);
1480
1481 if (prog->HasVertexAttributes()) {
1482 const VulkanBufferObject* vbo = prog->GetBoundVbo();
1483 const std::uint64_t vk = (vbo != nullptr ? vbo->GetVkBuffer() : 0);
1484 if (vk == 0) {
1485 return;
1486 }
1487 VkBuffer vertexBuffer = reinterpret_cast<VkBuffer>(vk);
1488 if (s_lastVertexBuffer != vertexBuffer) {
1489 VkDeviceSize vboOffset = 0;
1490 vkCmdBindVertexBuffers(s_commandBuffer, 0, 1, &vertexBuffer, &vboOffset);
1491 s_lastVertexBuffer = vertexBuffer;
1492 }
1493 if (indexed) {
1494 const VulkanBufferObject* ibo = prog->GetBoundIbo();
1495 const std::uint64_t ivk = (ibo != nullptr ? ibo->GetVkBuffer() : 0);
1496 if (ivk == 0) {
1497 return;
1498 }
1499 VkBuffer indexBuffer = reinterpret_cast<VkBuffer>(ivk);
1500 const VkIndexType indexType = (indexFormat == IndexFormat::UInt32 ? VK_INDEX_TYPE_UINT32 : VK_INDEX_TYPE_UINT16);
1501 if (s_lastIndexBuffer != indexBuffer || s_lastIndexType != indexType) {
1502 vkCmdBindIndexBuffer(s_commandBuffer, indexBuffer, 0, indexType);
1503 s_lastIndexBuffer = indexBuffer;
1504 s_lastIndexType = indexType;
1505 }
1506 }
1507 }
1508
1509 const std::uint32_t instances = (numInstances > 1 ? std::uint32_t(numInstances) : 1u);
1510 if (indexed) {
1511 const std::uint32_t indexSize = (indexFormat == IndexFormat::UInt32 ? 4u : 2u);
1512 const std::uint32_t firstIndex = std::uint32_t(indexOffset / indexSize);
1513 vkCmdDrawIndexed(s_commandBuffer, count, instances, firstIndex, baseVertex, 0);
1514 } else {
1515 vkCmdDraw(s_commandBuffer, count, instances, std::uint32_t(firstVertex), 0);
1516 }
1517 }
1518 }
1519
1520 void VulkanDevice::DrawArrays(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices)
1521 {
1522 DrawCommon(primitive, firstVertex, std::uint32_t(numVertices), false, IndexFormat::UInt16, 0, 1, 0);
1523 }
1524 void VulkanDevice::DrawArraysInstanced(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices, std::int32_t numInstances)
1525 {
1526 DrawCommon(primitive, firstVertex, std::uint32_t(numVertices), false, IndexFormat::UInt16, 0, numInstances, 0);
1527 }
1528 void VulkanDevice::DrawElements(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex)
1529 {
1530 DrawCommon(primitive, 0, numIndices, true, indexFormat, indexOffset, 1, baseVertex);
1531 }
1532 void VulkanDevice::DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex)
1533 {
1534 DrawCommon(primitive, 0, numIndices, true, indexFormat, indexOffset, numInstances, baseVertex);
1535 }
1536
1537 FenceHandle VulkanDevice::InsertFence() { return nullptr; }
1538 void VulkanDevice::DeleteFence(FenceHandle& fence) { fence = nullptr; }
1539 bool VulkanDevice::ClientWaitFence(FenceHandle fence, std::uint64_t timeoutNs)
1540 {
1541 static_cast<void>(fence);
1542 static_cast<void>(timeoutNs);
1543 return true;
1544 }
1545
1546 void VulkanDevice::SetupInitialState()
1547 {
1548 _blending = BlendingState{};
1549 _depthTest = DepthTestState{};
1550 _cullFace = CullFaceState{};
1551 _scissor = ScissorState{};
1552 }
1553
1554 // -- Backend extensions (recorders) --
1555
1556 void VulkanDevice::BindProgram(VulkanShaderProgram* program) { _currentProgram = program; }
1557 VulkanShaderProgram* VulkanDevice::CurrentProgram() { return _currentProgram; }
1558
1559 void VulkanDevice::BindTexture(std::uint32_t unit, const VulkanTexture* texture)
1560 {
1561 if (unit < MaxTextureUnits) {
1562 _boundTextures[unit] = texture;
1563 }
1564 }
1565
1566 void VulkanDevice::UnbindTexture(const VulkanTexture* texture)
1567 {
1568 for (std::uint32_t unit = 0; unit < MaxTextureUnits; unit++) {
1569 if (_boundTextures[unit] == texture) {
1570 _boundTextures[unit] = nullptr;
1571 }
1572 }
1573 }
1574
1575 const VulkanTexture* VulkanDevice::GetBoundTexture(std::uint32_t unit)
1576 {
1577 return (unit < MaxTextureUnits ? _boundTextures[unit] : nullptr);
1578 }
1579
1580 void VulkanDevice::BindUniformRange(std::uint32_t index, const std::uint8_t* data, std::uint32_t size)
1581 {
1582 if (index < MaxUniformBindings) {
1583 _boundUniformRanges[index].Data = data;
1584 _boundUniformRanges[index].Size = size;
1585 }
1586 }
1587
1588 void VulkanDevice::SetRenderTarget(VulkanRenderTarget* renderTarget) { _currentRenderTarget = renderTarget; }
1589
1590 void VulkanDevice::UnbindRenderTarget(const VulkanRenderTarget* renderTarget)
1591 {
1592 if (_currentRenderTarget == renderTarget) {
1593 _currentRenderTarget = nullptr;
1594 }
1595 }
1596
1597 void VulkanDevice::OnShaderProgramDestroyed(VulkanShaderProgram* program)
1598 {
1599 if (program == nullptr || s_device == VK_NULL_HANDLE) {
1600 return;
1601 }
1602 if (s_device != VK_NULL_HANDLE) {
1603 vkDeviceWaitIdle(s_device);
1604 }
1605 const std::uint32_t handle = program->GetUniqueId();
1606 for (auto it = s_pipelines.begin(); it != s_pipelines.end(); ) {
1607 if (it->first.programHandle == handle) {
1608 vkDestroyPipeline(s_device, it->second, nullptr);
1609 it = s_pipelines.erase(it);
1610 } else {
1611 ++it;
1612 }
1613 }
1614 if (_currentProgram == program) {
1615 _currentProgram = nullptr;
1616 }
1617 }
1618
1619 // Internal accessors used by the anonymous-namespace draw helpers
1620 VulkanRenderTarget* VulkanDevice::currentRenderTargetInternal() { return _currentRenderTarget; }
1621 std::uint32_t VulkanDevice::MaxUniformBindingsPublic() { return MaxUniformBindings; }
1622 void VulkanDevice::GetUniformRange(std::uint32_t index, const std::uint8_t*& data, std::uint32_t& size)
1623 {
1624 if (index < MaxUniformBindings) {
1625 data = _boundUniformRanges[index].Data;
1626 size = _boundUniformRanges[index].Size;
1627 } else {
1628 data = nullptr;
1629 size = 0;
1630 }
1631 }
1632
1633 // -- Vulkan device / swap-chain lifecycle --
1634
1635 namespace
1636 {
1637 VkPhysicalDevice PickPhysicalDevice(std::uint32_t& graphicsFamily, std::uint32_t& presentFamily)
1638 {
1639 std::uint32_t count = 0;
1640 vkEnumeratePhysicalDevices(s_instance, &count, nullptr);
1641 if (count == 0) {
1642 LOGE("No Vulkan physical devices found");
1643 return VK_NULL_HANDLE;
1644 }
1645 std::vector<VkPhysicalDevice> devices(count);
1646 vkEnumeratePhysicalDevices(s_instance, &count, devices.data());
1647
1648 VkPhysicalDevice best = VK_NULL_HANDLE;
1649 std::uint32_t bestGfx = 0, bestPresent = 0;
1650 bool bestIsDiscrete = false;
1651
1652 for (VkPhysicalDevice dev : devices) {
1653 std::uint32_t extCount = 0;
1654 vkEnumerateDeviceExtensionProperties(dev, nullptr, &extCount, nullptr);
1655 std::vector<VkExtensionProperties> exts(extCount);
1656 if (extCount > 0) {
1657 vkEnumerateDeviceExtensionProperties(dev, nullptr, &extCount, exts.data());
1658 }
1659 bool hasSwapchain = false;
1660 for (const VkExtensionProperties& e : exts) {
1661 if (std::strcmp(e.extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME) == 0) {
1662 hasSwapchain = true;
1663 break;
1664 }
1665 }
1666 if (!hasSwapchain) {
1667 continue;
1668 }
1669
1670 std::uint32_t qCount = 0;
1671 vkGetPhysicalDeviceQueueFamilyProperties(dev, &qCount, nullptr);
1672 std::vector<VkQueueFamilyProperties> families(qCount);
1673 vkGetPhysicalDeviceQueueFamilyProperties(dev, &qCount, families.data());
1674
1675 std::int32_t gfx = -1, present = -1;
1676 for (std::uint32_t i = 0; i < qCount; i++) {
1677 const bool isGfx = (families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0;
1678 VkBool32 canPresent = VK_FALSE;
1679 vkGetPhysicalDeviceSurfaceSupportKHR(dev, i, s_surface, &canPresent);
1680 if (isGfx && canPresent) {
1681 gfx = std::int32_t(i);
1682 present = std::int32_t(i);
1683 break;
1684 }
1685 if (isGfx && gfx < 0) {
1686 gfx = std::int32_t(i);
1687 }
1688 if (canPresent && present < 0) {
1689 present = std::int32_t(i);
1690 }
1691 }
1692 if (gfx < 0 || present < 0) {
1693 continue;
1694 }
1695
1696 std::uint32_t fmtCount = 0, pmCount = 0;
1697 vkGetPhysicalDeviceSurfaceFormatsKHR(dev, s_surface, &fmtCount, nullptr);
1698 vkGetPhysicalDeviceSurfacePresentModesKHR(dev, s_surface, &pmCount, nullptr);
1699 if (fmtCount == 0 || pmCount == 0) {
1700 continue;
1701 }
1702
1703 VkPhysicalDeviceProperties props;
1704 vkGetPhysicalDeviceProperties(dev, &props);
1705 const bool isDiscrete = (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU);
1706 if (best == VK_NULL_HANDLE || (isDiscrete && !bestIsDiscrete)) {
1707 best = dev;
1708 bestGfx = std::uint32_t(gfx);
1709 bestPresent = std::uint32_t(present);
1710 bestIsDiscrete = isDiscrete;
1711 }
1712 }
1713
1714 if (best != VK_NULL_HANDLE) {
1715 graphicsFamily = bestGfx;
1716 presentFamily = bestPresent;
1717 VkPhysicalDeviceProperties props;
1718 vkGetPhysicalDeviceProperties(best, &props);
1719 LOGI("Vulkan physical device selected: {} (graphics family {}, present family {})", props.deviceName, bestGfx, bestPresent);
1720 }
1721 return best;
1722 }
1723
1724 void DestroyScreenTarget()
1725 {
1726 if (s_device == VK_NULL_HANDLE) {
1727 return;
1728 }
1729 if (s_screenFramebuffer != VK_NULL_HANDLE) { vkDestroyFramebuffer(s_device, s_screenFramebuffer, nullptr); s_screenFramebuffer = VK_NULL_HANDLE; }
1730 if (s_screenView != VK_NULL_HANDLE) { vkDestroyImageView(s_device, s_screenView, nullptr); s_screenView = VK_NULL_HANDLE; }
1731 if (s_screenImage != VK_NULL_HANDLE) { vkDestroyImage(s_device, s_screenImage, nullptr); s_screenImage = VK_NULL_HANDLE; }
1732 if (s_screenMemory != VK_NULL_HANDLE) { vkFreeMemory(s_device, s_screenMemory, nullptr); s_screenMemory = VK_NULL_HANDLE; }
1733 s_screenLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1734 }
1735
1736 bool CreateScreenTarget(VkExtent2D extent)
1737 {
1738 DestroyScreenTarget();
1739 s_screenExtent = extent;
1740
1741 VkImageCreateInfo ici = {};
1742 ici.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1743 ici.imageType = VK_IMAGE_TYPE_2D;
1744 ici.format = s_swapchainFormat;
1745 ici.extent = { extent.width, extent.height, 1 };
1746 ici.mipLevels = 1;
1747 ici.arrayLayers = 1;
1748 ici.samples = VK_SAMPLE_COUNT_1_BIT;
1749 ici.tiling = VK_IMAGE_TILING_OPTIMAL;
1750 ici.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
1751 ici.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1752 ici.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1753 if (!CheckVk(vkCreateImage(s_device, &ici, nullptr, &s_screenImage), "vkCreateImage(screen)")) {
1754 return false;
1755 }
1756 VkMemoryRequirements req;
1757 vkGetImageMemoryRequirements(s_device, s_screenImage, &req);
1758 VkMemoryAllocateInfo mai = {};
1759 mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1760 mai.allocationSize = req.size;
1761 mai.memoryTypeIndex = VkFindMemoryType(req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
1762 if (mai.memoryTypeIndex == UINT32_MAX || !CheckVk(vkAllocateMemory(s_device, &mai, nullptr, &s_screenMemory), "vkAllocateMemory(screen)")) {
1763 return false;
1764 }
1765 vkBindImageMemory(s_device, s_screenImage, s_screenMemory, 0);
1766
1767 VkImageViewCreateInfo ivci = {};
1768 ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1769 ivci.image = s_screenImage;
1770 ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;
1771 ivci.format = s_swapchainFormat;
1772 ivci.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
1773 if (!CheckVk(vkCreateImageView(s_device, &ivci, nullptr, &s_screenView), "vkCreateImageView(screen)")) {
1774 return false;
1775 }
1776
1777 VkFramebufferCreateInfo fci = {};
1778 fci.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
1779 fci.renderPass = VkGetColorRenderPass(s_swapchainFormat);
1780 fci.attachmentCount = 1;
1781 fci.pAttachments = &s_screenView;
1782 fci.width = extent.width;
1783 fci.height = extent.height;
1784 fci.layers = 1;
1785 if (!CheckVk(vkCreateFramebuffer(s_device, &fci, nullptr, &s_screenFramebuffer), "vkCreateFramebuffer(screen)")) {
1786 return false;
1787 }
1788
1789 // Bring it to COLOR_ATTACHMENT_OPTIMAL so the LOAD-op render passes are valid from the first frame
1790 VkCommandBuffer cmd = VkBeginOneTimeCommands();
1791 if (cmd != VK_NULL_HANDLE) {
1792 ImageBarrier(cmd, s_screenImage, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
1793 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
1794 VkEndOneTimeCommands(cmd);
1795 s_screenLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1796 }
1797 return true;
1798 }
1799
1800 bool CreateDummyTexture()
1801 {
1802 VkImageCreateInfo ici = {};
1803 ici.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1804 ici.imageType = VK_IMAGE_TYPE_2D;
1805 ici.format = VK_FORMAT_R8G8B8A8_UNORM;
1806 ici.extent = { 1, 1, 1 };
1807 ici.mipLevels = 1;
1808 ici.arrayLayers = 1;
1809 ici.samples = VK_SAMPLE_COUNT_1_BIT;
1810 ici.tiling = VK_IMAGE_TILING_OPTIMAL;
1811 ici.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
1812 ici.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1813 ici.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1814 if (vkCreateImage(s_device, &ici, nullptr, &s_dummyImage) != VK_SUCCESS) {
1815 return false;
1816 }
1817 VkMemoryRequirements req;
1818 vkGetImageMemoryRequirements(s_device, s_dummyImage, &req);
1819 VkMemoryAllocateInfo mai = {};
1820 mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1821 mai.allocationSize = req.size;
1822 mai.memoryTypeIndex = VkFindMemoryType(req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
1823 if (mai.memoryTypeIndex == UINT32_MAX || vkAllocateMemory(s_device, &mai, nullptr, &s_dummyMemory) != VK_SUCCESS) {
1824 return false;
1825 }
1826 vkBindImageMemory(s_device, s_dummyImage, s_dummyMemory, 0);
1827
1828 VkCommandBuffer cmd = VkBeginOneTimeCommands();
1829 if (cmd != VK_NULL_HANDLE) {
1830 ImageBarrier(cmd, s_dummyImage, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1831 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, VK_ACCESS_SHADER_READ_BIT);
1832 VkEndOneTimeCommands(cmd);
1833 }
1834
1835 VkImageViewCreateInfo ivci = {};
1836 ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1837 ivci.image = s_dummyImage;
1838 ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;
1839 ivci.format = VK_FORMAT_R8G8B8A8_UNORM;
1840 ivci.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
1841 vkCreateImageView(s_device, &ivci, nullptr, &s_dummyView);
1842
1843 VkSamplerCreateInfo sci = {};
1844 sci.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
1845 sci.magFilter = VK_FILTER_NEAREST;
1846 sci.minFilter = VK_FILTER_NEAREST;
1847 sci.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
1848 sci.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
1849 sci.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
1850 sci.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
1851 vkCreateSampler(s_device, &sci, nullptr, &s_dummySampler);
1852 return true;
1853 }
1854
1855 // -- Synchronization-object lifecycle --
1856 // All sync objects are (re)created together with the swap chain (from CreateSwapchainObjects, after a
1857 // vkDeviceWaitIdle) and torn down in DestroySwapchainObjects, so a resize NEVER carries a binary semaphore
1858 // across in a signalled state - the core resize-freeze fix. The per-frame image-available semaphore + fence
1859 // are recreated too (belt and braces: guarantees no stale signalled state survives the resize).
1860
1861 // Defined with the secondary swap chains further down: they track which frame fence last used each of their
1862 // images, so every one of those references has to be dropped when the fences themselves are destroyed
1863 void ForgetFrameFencesInSecondarySwapchains();
1864
1865 void DestroyFrameSyncObjects()
1866 {
1867 ForgetFrameFencesInSecondarySwapchains();
1868
1869 for (FrameData& fr : s_frames) {
1870 if (fr.ImageAvailable != VK_NULL_HANDLE) { vkDestroySemaphore(s_device, fr.ImageAvailable, nullptr); fr.ImageAvailable = VK_NULL_HANDLE; }
1871 if (fr.InFlightFence != VK_NULL_HANDLE) { vkDestroyFence(s_device, fr.InFlightFence, nullptr); fr.InFlightFence = VK_NULL_HANDLE; }
1872 }
1873 }
1874
1875 bool CreateFrameSyncObjects()
1876 {
1877 VkSemaphoreCreateInfo semInfo = {};
1878 semInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
1879 VkFenceCreateInfo fenceInfo = {};
1880 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1881 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; // so the first BeginFrame wait returns immediately
1882 for (FrameData& fr : s_frames) {
1883 if (!CheckVk(vkCreateSemaphore(s_device, &semInfo, nullptr, &fr.ImageAvailable), "vkCreateSemaphore(imageAvailable)") ||
1884 !CheckVk(vkCreateFence(s_device, &fenceInfo, nullptr, &fr.InFlightFence), "vkCreateFence(inFlight)")) {
1885 return false;
1886 }
1887 fr.FenceInFlight = false; // fresh fence, nothing submitted against it yet
1888 }
1889 return true;
1890 }
1891
1892 void DestroySwapchainSyncObjects()
1893 {
1894 for (VkSemaphore sem : s_renderFinishedPerImage) {
1895 if (sem != VK_NULL_HANDLE) { vkDestroySemaphore(s_device, sem, nullptr); }
1896 }
1897 s_renderFinishedPerImage.clear();
1898 s_imagesInFlight.clear();
1899 }
1900
1901 bool CreateSwapchainSyncObjects(std::uint32_t imageCount)
1902 {
1903 VkSemaphoreCreateInfo semInfo = {};
1904 semInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
1905 s_renderFinishedPerImage.assign(imageCount, VK_NULL_HANDLE);
1906 for (std::uint32_t i = 0; i < imageCount; i++) {
1907 if (!CheckVk(vkCreateSemaphore(s_device, &semInfo, nullptr, &s_renderFinishedPerImage[i]), "vkCreateSemaphore(renderFinished)")) {
1908 return false;
1909 }
1910 }
1911 s_imagesInFlight.assign(imageCount, VK_NULL_HANDLE); // no owned fences; tracks the in-flight fence per image
1912 return true;
1913 }
1914
1915 void DestroySwapchainObjects()
1916 {
1917 if (s_device == VK_NULL_HANDLE) {
1918 return;
1919 }
1920 // Callers (ResizeSwapchain / DestroySwapchain) have already waited the device idle, so all sync objects
1921 // and queued staging buffers are safe to destroy here.
1922 DestroyFrameSyncObjects();
1923 DestroySwapchainSyncObjects();
1924 for (FrameData& fr : s_frames) {
1925 FreeFrameStaging(fr);
1926 }
1927 for (VkImageView view : s_swapchainImageViews) {
1928 if (view != VK_NULL_HANDLE) {
1929 vkDestroyImageView(s_device, view, nullptr);
1930 }
1931 }
1932 s_swapchainImageViews.clear();
1933 s_swapchainImages.clear();
1934 if (s_swapchain != VK_NULL_HANDLE) {
1935 vkDestroySwapchainKHR(s_device, s_swapchain, nullptr);
1936 s_swapchain = VK_NULL_HANDLE;
1937 }
1938 }
1939
1940 bool CreateSwapchainObjects(std::int32_t width, std::int32_t height)
1941 {
1942 VkSurfaceCapabilitiesKHR caps;
1943 if (!CheckVk(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(s_physicalDevice, s_surface, &caps), "vkGetPhysicalDeviceSurfaceCapabilitiesKHR")) {
1944 return false;
1945 }
1946
1947 std::uint32_t fmtCount = 0;
1948 vkGetPhysicalDeviceSurfaceFormatsKHR(s_physicalDevice, s_surface, &fmtCount, nullptr);
1949 std::vector<VkSurfaceFormatKHR> formats(fmtCount);
1950 vkGetPhysicalDeviceSurfaceFormatsKHR(s_physicalDevice, s_surface, &fmtCount, formats.data());
1951 VkSurfaceFormatKHR chosenFormat = formats.empty() ? VkSurfaceFormatKHR{ VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR } : formats[0];
1952 for (const VkSurfaceFormatKHR& f : formats) {
1953 if ((f.format == VK_FORMAT_B8G8R8A8_UNORM || f.format == VK_FORMAT_R8G8B8A8_UNORM) &&
1954 f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
1955 chosenFormat = f;
1956 break;
1957 }
1958 }
1959
1960 VkPresentModeKHR chosenPresent = VK_PRESENT_MODE_FIFO_KHR;
1961 if (!s_vsync) {
1962 std::uint32_t pmCount = 0;
1963 vkGetPhysicalDeviceSurfacePresentModesKHR(s_physicalDevice, s_surface, &pmCount, nullptr);
1964 std::vector<VkPresentModeKHR> modes(pmCount);
1965 vkGetPhysicalDeviceSurfacePresentModesKHR(s_physicalDevice, s_surface, &pmCount, modes.data());
1966 for (VkPresentModeKHR m : modes) {
1967 if (m == VK_PRESENT_MODE_MAILBOX_KHR) { chosenPresent = m; break; }
1968 if (m == VK_PRESENT_MODE_IMMEDIATE_KHR) { chosenPresent = VK_PRESENT_MODE_IMMEDIATE_KHR; }
1969 }
1970 }
1971
1972 VkExtent2D extent;
1973 if (caps.currentExtent.width != 0xFFFFFFFFu) {
1974 extent = caps.currentExtent;
1975 } else {
1976 extent.width = std::uint32_t(width < 1 ? 1 : width);
1977 extent.height = std::uint32_t(height < 1 ? 1 : height);
1978 if (extent.width < caps.minImageExtent.width) extent.width = caps.minImageExtent.width;
1979 if (extent.width > caps.maxImageExtent.width) extent.width = caps.maxImageExtent.width;
1980 if (extent.height < caps.minImageExtent.height) extent.height = caps.minImageExtent.height;
1981 if (extent.height > caps.maxImageExtent.height) extent.height = caps.maxImageExtent.height;
1982 }
1983 if (extent.width == 0 || extent.height == 0) {
1984 return false;
1985 }
1986
1987 std::uint32_t imageCount = caps.minImageCount + 1;
1988 if (caps.maxImageCount > 0 && imageCount > caps.maxImageCount) {
1989 imageCount = caps.maxImageCount;
1990 }
1991
1992 // The present blit needs TRANSFER_DST on the swap-chain images
1993 VkImageUsageFlags usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
1994 if (caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) {
1995 usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
1996 } else {
1997 LOGW("Swap-chain images lack TRANSFER_DST usage, the present blit may fail");
1998 }
1999
2000 VkSwapchainCreateInfoKHR sci = {};
2001 sci.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
2002 sci.surface = s_surface;
2003 sci.minImageCount = imageCount;
2004 sci.imageFormat = chosenFormat.format;
2005 sci.imageColorSpace = chosenFormat.colorSpace;
2006 sci.imageExtent = extent;
2007 sci.imageArrayLayers = 1;
2008 sci.imageUsage = usage;
2009 const std::uint32_t families[2] = { s_graphicsFamily, s_presentFamily };
2010 if (s_graphicsFamily != s_presentFamily) {
2011 sci.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
2012 sci.queueFamilyIndexCount = 2;
2013 sci.pQueueFamilyIndices = families;
2014 } else {
2015 sci.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
2016 }
2017 sci.preTransform = caps.currentTransform;
2018 sci.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
2019 sci.presentMode = chosenPresent;
2020 sci.clipped = VK_TRUE;
2021 sci.oldSwapchain = VK_NULL_HANDLE;
2022
2023 if (!CheckVk(vkCreateSwapchainKHR(s_device, &sci, nullptr, &s_swapchain), "vkCreateSwapchainKHR")) {
2024 return false;
2025 }
2026 s_swapchainFormat = chosenFormat.format;
2027 s_swapchainExtent = extent;
2028
2029 std::uint32_t realCount = 0;
2030 vkGetSwapchainImagesKHR(s_device, s_swapchain, &realCount, nullptr);
2031 s_swapchainImages.resize(realCount);
2032 vkGetSwapchainImagesKHR(s_device, s_swapchain, &realCount, s_swapchainImages.data());
2033 s_swapchainImageViews.assign(realCount, VK_NULL_HANDLE); // views unused (blit target), kept for symmetry
2034
2035 // (Re)create all sync objects fresh alongside the swap chain (the device is idle here), so no binary
2036 // semaphore survives a resize in a signalled state and renderFinished matches the new image count.
2037 if (!CreateFrameSyncObjects() || !CreateSwapchainSyncObjects(realCount)) {
2038 return false;
2039 }
2040 s_currentFrame = 0;
2041 for (FrameData& fr : s_frames) {
2042 fr.UboCursor = 0;
2043 fr.DescPoolCursor = 0;
2044 }
2045
2046 if (!CreateScreenTarget(extent)) {
2047 return false;
2048 }
2049
2050 LOGI("Vulkan swap chain created: {}x{}, {} images, format {}, {} frames in flight", extent.width, extent.height, realCount, static_cast<std::int32_t>(s_swapchainFormat), MaxFramesInFlight);
2051 return true;
2052 }
2053
2054 // -- Secondary swap chains (the windows ImGui spawns when a panel is dragged out of the main one) --
2055 // Only the PRESENTATION of such a window lives here; its contents are rendered through the ordinary RHI
2056 // path into an off-screen render target, so every usual convention (bottom-up rows, scissor mapping,
2057 // pipeline/render-pass caches) applies unchanged. QueueSecondaryPresent() then hands that target's texture
2058 // over for the frame, and PresentFrame() blits each one into its window's acquired image and joins it into
2059 // the single submit + present the frame already does. While nothing is undocked the pending list stays
2060 // empty and none of it runs, so the ordinary path keeps its exact behavior and cost.
2061
2062 struct SecondarySwapchain
2063 {
2064 VkSurfaceKHR Surface = VK_NULL_HANDLE;
2065 VkSwapchainKHR Swapchain = VK_NULL_HANDLE;
2066 VkExtent2D Extent = { 0, 0 };
2067 // The size that was asked for, which the platform may have clamped into Extent. Resize compares
2068 // against THIS, so a clamping platform cannot make every frame recreate the swap chain.
2069 std::int32_t RequestedWidth = 0;
2070 std::int32_t RequestedHeight = 0;
2071 std::vector<VkImage> Images;
2072 // Mirrors the main chain's synchronization exactly: render-finished is per swap-chain IMAGE (a binary
2073 // semaphore is then never re-signalled before the present waiting on it consumed it) and the fence of
2074 // the frame that last used an image is tracked so it is not re-acquired while that frame still runs.
2075 std::vector<VkSemaphore> RenderFinishedPerImage;
2076 std::vector<VkFence> ImagesInFlight;
2077 VkSemaphore ImageAvailable[MaxFramesInFlight] = {};
2078 bool Ready = false;
2079 };
2080
2081 struct PendingSecondaryPresent
2082 {
2083 SecondarySwapchain* Chain;
2084 const VulkanTexture* Source;
2085 };
2086
2087 // Every live secondary swap chain, so the per-frame fences they reference can be forgotten when those are
2088 // destroyed - a swap-chain resize recreates all of them, and a stale handle would then be waited on
2089 std::vector<SecondarySwapchain*> s_secondarySwapchains;
2090 std::vector<PendingSecondaryPresent> s_pendingSecondaryPresents;
2091 // Submit/present argument arrays, kept allocated across frames so the common path (nothing undocked, one
2092 // swap chain) only clears and refills them instead of allocating
2093 std::vector<VkSemaphore> s_submitWaitSemaphores;
2094 std::vector<VkPipelineStageFlags> s_submitWaitStages;
2095 std::vector<VkSemaphore> s_submitSignalSemaphores;
2096 std::vector<VkSwapchainKHR> s_presentSwapchains;
2097 std::vector<std::uint32_t> s_presentImageIndices;
2098 std::vector<VkResult> s_presentResults;
2099 // Aligned with s_presentSwapchains, so a per-swap-chain present result can be attributed back to its
2100 // window (entry 0 is the main swap chain and stays null)
2101 std::vector<SecondarySwapchain*> s_presentChains;
2102
2103 void ForgetFrameFencesInSecondarySwapchains()
2104 {
2105 for (SecondarySwapchain* sc : s_secondarySwapchains) {
2106 sc->ImagesInFlight.assign(sc->ImagesInFlight.size(), VK_NULL_HANDLE);
2107 }
2108 }
2109
2110 void DestroySecondarySwapchainObjects(SecondarySwapchain& sc)
2111 {
2112 // The caller has waited the device idle (or the objects were never used), so this is safe here
2113 sc.Ready = false;
2114 for (VkSemaphore sem : sc.RenderFinishedPerImage) {
2115 if (sem != VK_NULL_HANDLE) { vkDestroySemaphore(s_device, sem, nullptr); }
2116 }
2117 sc.RenderFinishedPerImage.clear();
2118 sc.ImagesInFlight.clear();
2119 for (VkSemaphore& sem : sc.ImageAvailable) {
2120 if (sem != VK_NULL_HANDLE) { vkDestroySemaphore(s_device, sem, nullptr); sem = VK_NULL_HANDLE; }
2121 }
2122 sc.Images.clear();
2123 if (sc.Swapchain != VK_NULL_HANDLE) {
2124 vkDestroySwapchainKHR(s_device, sc.Swapchain, nullptr);
2125 sc.Swapchain = VK_NULL_HANDLE;
2126 }
2127 }
2128
2129 bool CreateSecondarySwapchainObjects(SecondarySwapchain& sc, std::int32_t width, std::int32_t height)
2130 {
2131 sc.RequestedWidth = width;
2132 sc.RequestedHeight = height;
2133
2134 VkBool32 presentSupported = VK_FALSE;
2135 vkGetPhysicalDeviceSurfaceSupportKHR(s_physicalDevice, s_presentFamily, sc.Surface, &presentSupported);
2136 if (presentSupported != VK_TRUE) {
2137 LOGE("The present queue family cannot present to a secondary window's surface");
2138 return false;
2139 }
2140
2141 VkSurfaceCapabilitiesKHR caps;
2142 if (!CheckVk(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(s_physicalDevice, sc.Surface, &caps), "vkGetPhysicalDeviceSurfaceCapabilitiesKHR(secondary)")) {
2143 return false;
2144 }
2145
2146 std::uint32_t fmtCount = 0;
2147 vkGetPhysicalDeviceSurfaceFormatsKHR(s_physicalDevice, sc.Surface, &fmtCount, nullptr);
2148 std::vector<VkSurfaceFormatKHR> formats(fmtCount);
2149 vkGetPhysicalDeviceSurfaceFormatsKHR(s_physicalDevice, sc.Surface, &fmtCount, formats.data());
2150 VkSurfaceFormatKHR chosenFormat = formats.empty() ? VkSurfaceFormatKHR{ VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR } : formats[0];
2151 for (const VkSurfaceFormatKHR& f : formats) {
2152 if ((f.format == VK_FORMAT_B8G8R8A8_UNORM || f.format == VK_FORMAT_R8G8B8A8_UNORM) &&
2153 f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
2154 chosenFormat = f;
2155 break;
2156 }
2157 }
2158
2159 VkExtent2D extent;
2160 if (caps.currentExtent.width != 0xFFFFFFFFu) {
2161 extent = caps.currentExtent;
2162 } else {
2163 extent.width = std::uint32_t(width < 1 ? 1 : width);
2164 extent.height = std::uint32_t(height < 1 ? 1 : height);
2165 if (extent.width < caps.minImageExtent.width) extent.width = caps.minImageExtent.width;
2166 if (extent.width > caps.maxImageExtent.width) extent.width = caps.maxImageExtent.width;
2167 if (extent.height < caps.minImageExtent.height) extent.height = caps.minImageExtent.height;
2168 if (extent.height > caps.maxImageExtent.height) extent.height = caps.maxImageExtent.height;
2169 }
2170 if (extent.width == 0 || extent.height == 0) {
2171 return false; // hidden or zero-sized window; retried on the next resize / present
2172 }
2173
2174 std::uint32_t imageCount = caps.minImageCount + 1;
2175 if (caps.maxImageCount > 0 && imageCount > caps.maxImageCount) {
2176 imageCount = caps.maxImageCount;
2177 }
2178
2179 if ((caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) == 0) {
2180 LOGE("A secondary window's swap-chain images lack TRANSFER_DST usage, cannot present into them");
2181 return false;
2182 }
2183
2184 VkSwapchainCreateInfoKHR sci = {};
2185 sci.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
2186 sci.surface = sc.Surface;
2187 sci.minImageCount = imageCount;
2188 sci.imageFormat = chosenFormat.format;
2189 sci.imageColorSpace = chosenFormat.colorSpace;
2190 sci.imageExtent = extent;
2191 sci.imageArrayLayers = 1;
2192 sci.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
2193 const std::uint32_t families[2] = { s_graphicsFamily, s_presentFamily };
2194 if (s_graphicsFamily != s_presentFamily) {
2195 sci.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
2196 sci.queueFamilyIndexCount = 2;
2197 sci.pQueueFamilyIndices = families;
2198 } else {
2199 sci.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
2200 }
2201 sci.preTransform = caps.currentTransform;
2202 sci.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
2203 // Always FIFO: these windows carry UI, and the acquire below blocks, so a mode that can starve on an
2204 // occluded window is not worth the latency it would save
2205 sci.presentMode = VK_PRESENT_MODE_FIFO_KHR;
2206 sci.clipped = VK_TRUE;
2207
2208 if (!CheckVk(vkCreateSwapchainKHR(s_device, &sci, nullptr, &sc.Swapchain), "vkCreateSwapchainKHR(secondary)")) {
2209 return false;
2210 }
2211 sc.Extent = extent;
2212
2213 std::uint32_t realCount = 0;
2214 vkGetSwapchainImagesKHR(s_device, sc.Swapchain, &realCount, nullptr);
2215 sc.Images.resize(realCount);
2216 vkGetSwapchainImagesKHR(s_device, sc.Swapchain, &realCount, sc.Images.data());
2217
2218 VkSemaphoreCreateInfo semInfo = {};
2219 semInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
2220 sc.RenderFinishedPerImage.assign(realCount, VK_NULL_HANDLE);
2221 for (std::uint32_t i = 0; i < realCount; i++) {
2222 if (!CheckVk(vkCreateSemaphore(s_device, &semInfo, nullptr, &sc.RenderFinishedPerImage[i]), "vkCreateSemaphore(secondary renderFinished)")) {
2223 return false;
2224 }
2225 }
2226 sc.ImagesInFlight.assign(realCount, VK_NULL_HANDLE);
2227 for (VkSemaphore& sem : sc.ImageAvailable) {
2228 if (!CheckVk(vkCreateSemaphore(s_device, &semInfo, nullptr, &sem), "vkCreateSemaphore(secondary imageAvailable)")) {
2229 return false;
2230 }
2231 }
2232
2233 sc.Ready = true;
2234 return true;
2235 }
2236 }
2237
2238 #if defined(VULKAN_MRT_PROBE)
2239 namespace
2240 {
2241 // Synthetic multi-render-target self-test, compiled only when VULKAN_MRT_PROBE is defined (no runtime
2242 // cost otherwise). Run once at device creation: attaches TWO color textures to one render target, clears
2243 // attachment 0 red and attachment 1 green through the 2-attachment render pass / framebuffer, reads both
2244 // back through the regular readback path and logs PASS/FAIL. Exercises the MRT render-pass cache, the
2245 // multi-view framebuffer, per-attachment layout handling and multi-attachment clears.
2246 void RunMrtProbe()
2247 {
2248 constexpr std::int32_t Size = 4;
2249 VulkanTexture tex0(TextureTarget::Texture2D);
2250 VulkanTexture tex1(TextureTarget::Texture2D);
2251 tex0.TexStorage2D(1, PixelFormat::RGBA8, Size, Size);
2252 tex1.TexStorage2D(1, PixelFormat::RGBA8, Size, Size);
2253
2254 VulkanRenderTarget rt;
2255 rt.AttachColorTexture(tex0, 0);
2256 rt.AttachColorTexture(tex1, 1);
2257 rt.SetDrawBuffers(2);
2258
2259 // GetFramebuffer materializes both attachment images (left in COLOR_ATTACHMENT_OPTIMAL by EnsureGpu,
2260 // matching the LOAD-op render pass's initialLayout) and builds the 2-attachment framebuffer
2261 const std::uint64_t fb = rt.GetFramebuffer();
2262 VkFormat formats[2] = { VkFormat(tex0.GpuFormat()), VkFormat(tex1.GpuFormat()) };
2263 VkRenderPass renderPass = VkGetColorRenderPassMrt(formats, 2);
2264 if (fb == 0 || renderPass == VK_NULL_HANDLE) {
2265 LOGE("MRT probe FAILED: framebuffer={}, renderPass={}", fb, reinterpret_cast<std::uint64_t>(renderPass));
2266 return;
2267 }
2268
2269 VkCommandBuffer cmd = VkBeginOneTimeCommands();
2270 if (cmd == VK_NULL_HANDLE) {
2271 LOGE("MRT probe FAILED: could not begin a one-time command buffer");
2272 return;
2273 }
2274 VkRenderPassBeginInfo rpbi = {};
2275 rpbi.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
2276 rpbi.renderPass = renderPass;
2277 rpbi.framebuffer = reinterpret_cast<VkFramebuffer>(fb);
2278 rpbi.renderArea.offset = { 0, 0 };
2279 rpbi.renderArea.extent = { Size, Size };
2280 vkCmdBeginRenderPass(cmd, &rpbi, VK_SUBPASS_CONTENTS_INLINE);
2281 VkClearAttachment cas[2] = {};
2282 cas[0].aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2283 cas[0].colorAttachment = 0;
2284 cas[0].clearValue.color = { { 1.0f, 0.0f, 0.0f, 1.0f } }; // attachment 0: red
2285 cas[1].aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2286 cas[1].colorAttachment = 1;
2287 cas[1].clearValue.color = { { 0.0f, 1.0f, 0.0f, 1.0f } }; // attachment 1: green
2288 VkClearRect rect = {};
2289 rect.rect.extent = { Size, Size };
2290 rect.layerCount = 1;
2291 vkCmdClearAttachments(cmd, 2, cas, 1, &rect);
2292 vkCmdEndRenderPass(cmd);
2293 VkEndOneTimeCommands(cmd); // submits + waits idle
2294
2295 std::uint8_t px0[Size * Size * 4] = {};
2296 std::uint8_t px1[Size * Size * 4] = {};
2297 tex0.GetTexImage(0, PixelFormat::RGBA8, false, px0);
2298 tex1.GetTexImage(0, PixelFormat::RGBA8, false, px1);
2299 bool ok0 = true, ok1 = true;
2300 for (std::int32_t i = 0; i < Size * Size; i++) {
2301 ok0 = ok0 && (px0[i * 4 + 0] == 255 && px0[i * 4 + 1] == 0 && px0[i * 4 + 2] == 0 && px0[i * 4 + 3] == 255);
2302 ok1 = ok1 && (px1[i * 4 + 0] == 0 && px1[i * 4 + 1] == 255 && px1[i * 4 + 2] == 0 && px1[i * 4 + 3] == 255);
2303 }
2304 if (ok0 && ok1) {
2305 LOGI("MRT probe PASSED: attachment 0 = red, attachment 1 = green (2-attachment render pass / framebuffer / clears verified)");
2306 } else {
2307 LOGE("MRT probe FAILED: attachment 0 {} (got {},{},{},{}), attachment 1 {} (got {},{},{},{})",
2308 ok0 ? "OK" : "WRONG", px0[0], px0[1], px0[2], px0[3],
2309 ok1 ? "OK" : "WRONG", px1[0], px1[1], px1[2], px1[3]);
2310 }
2311 }
2312 }
2313 #endif
2314
2315 bool VulkanDevice::CreateSwapchain(void* windowHandle, std::int32_t width, std::int32_t height, bool vsync)
2316 {
2317 #if defined(WITH_SDL2) || defined(WITH_SDL3)
2318 s_vsync = vsync;
2319 s_sdlWindow = windowHandle;
2320 SDL_Window* window = reinterpret_cast<SDL_Window*>(windowHandle);
2321
2322 # if defined(WITH_SDL3)
2323 // SDL3 reports success as a bool (true), SDL2 as int 0
2324 if (!SDL_Vulkan_LoadLibrary(nullptr)) {
2325 # else
2326 if (SDL_Vulkan_LoadLibrary(nullptr) != 0) {
2327 # endif
2328 LOGE("SDL_Vulkan_LoadLibrary() failed: {}", SDL_GetError());
2329 return false;
2330 }
2331 vkGetInstanceProcAddr = reinterpret_cast<PFN_vkGetInstanceProcAddr>(SDL_Vulkan_GetVkGetInstanceProcAddr());
2332 if (vkGetInstanceProcAddr == nullptr) {
2333 LOGE("SDL_Vulkan_GetVkGetInstanceProcAddr() returned null");
2334 return false;
2335 }
2336 LoadGlobalFunctions();
2337 if (vkCreateInstance == nullptr) {
2338 LOGE("Failed to load vkCreateInstance() from Vulkan loader");
2339 return false;
2340 }
2341
2342 std::uint32_t sdlExtCount = 0;
2343 # if defined(WITH_SDL3)
2344 // SDL3: a single call returns the extension-name array directly (no window argument, no caller buffer)
2345 const char* const* sdlExts = SDL_Vulkan_GetInstanceExtensions(&sdlExtCount);
2346 if (sdlExts == nullptr) {
2347 LOGE("SDL_Vulkan_GetInstanceExtensions() failed: {}", SDL_GetError());
2348 return false;
2349 }
2350 std::vector<const char*> instanceExts(sdlExts, sdlExts + sdlExtCount);
2351 # else
2352 if (!SDL_Vulkan_GetInstanceExtensions(window, &sdlExtCount, nullptr)) {
2353 LOGE("SDL_Vulkan_GetInstanceExtensions(count) failed: {}", SDL_GetError());
2354 return false;
2355 }
2356 std::vector<const char*> instanceExts(sdlExtCount);
2357 if (sdlExtCount > 0 && !SDL_Vulkan_GetInstanceExtensions(window, &sdlExtCount, instanceExts.data())) {
2358 LOGE("SDL_Vulkan_GetInstanceExtensions(names) failed: {}", SDL_GetError());
2359 return false;
2360 }
2361 # endif
2362
2363 std::uint32_t availExtCount = 0;
2364 vkEnumerateInstanceExtensionProperties(nullptr, &availExtCount, nullptr);
2365 std::vector<VkExtensionProperties> availExts(availExtCount);
2366 if (availExtCount > 0) {
2367 vkEnumerateInstanceExtensionProperties(nullptr, &availExtCount, availExts.data());
2368 }
2369 auto hasInstanceExt = [&](const char* name) {
2370 for (const VkExtensionProperties& e : availExts) {
2371 if (std::strcmp(e.extensionName, name) == 0) return true;
2372 }
2373 return false;
2374 };
2375 bool hasValidationLayer = false;
2376 {
2377 std::uint32_t layerCount = 0;
2378 vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
2379 std::vector<VkLayerProperties> layers(layerCount);
2380 if (layerCount > 0) {
2381 vkEnumerateInstanceLayerProperties(&layerCount, layers.data());
2382 }
2383 for (const VkLayerProperties& l : layers) {
2384 if (std::strcmp(l.layerName, "VK_LAYER_KHRONOS_validation") == 0) { hasValidationLayer = true; break; }
2385 }
2386 }
2387 const bool wantValidation = hasValidationLayer && hasInstanceExt(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
2388 if (wantValidation) {
2389 instanceExts.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
2390 }
2391 const char* validationLayer = "VK_LAYER_KHRONOS_validation";
2392
2393 VkApplicationInfo appInfo = {};
2394 appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
2395 appInfo.pApplicationName = NCINE_APP;
2396 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
2397 appInfo.pEngineName = "nCine";
2398 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
2399 appInfo.apiVersion = VK_API_VERSION_1_0;
2400
2401 VkInstanceCreateInfo ici = {};
2402 ici.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
2403 ici.pApplicationInfo = &appInfo;
2404 ici.enabledExtensionCount = std::uint32_t(instanceExts.size());
2405 ici.ppEnabledExtensionNames = instanceExts.empty() ? nullptr : instanceExts.data();
2406 if (wantValidation) {
2407 ici.enabledLayerCount = 1;
2408 ici.ppEnabledLayerNames = &validationLayer;
2409 LOGI("Vulkan validation layer VK_LAYER_KHRONOS_validation enabled");
2410 }
2411
2412 if (!CheckVk(vkCreateInstance(&ici, nullptr, &s_instance), "vkCreateInstance")) {
2413 return false;
2414 }
2415 LoadInstanceFunctions();
2416
2417 if (wantValidation && vkCreateDebugUtilsMessengerEXT != nullptr) {
2418 VkDebugUtilsMessengerCreateInfoEXT dci = {};
2419 dci.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
2420 dci.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
2421 dci.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
2422 dci.pfnUserCallback = DebugCallback;
2423 vkCreateDebugUtilsMessengerEXT(s_instance, &dci, nullptr, &s_debugMessenger);
2424 }
2425
2426 #if defined(WITH_SDL3)
2427 // SDL3 added a VkAllocationCallbacks* parameter (null = default allocator)
2428 if (!SDL_Vulkan_CreateSurface(window, s_instance, nullptr, &s_surface)) {
2429 #else
2430 if (!SDL_Vulkan_CreateSurface(window, s_instance, &s_surface)) {
2431 #endif
2432 LOGE("SDL_Vulkan_CreateSurface() failed: {}", SDL_GetError());
2433 DestroySwapchain();
2434 return false;
2435 }
2436
2437 s_physicalDevice = PickPhysicalDevice(s_graphicsFamily, s_presentFamily);
2438 if (s_physicalDevice == VK_NULL_HANDLE) {
2439 LOGE("No suitable Vulkan physical device (needs graphics+present queue and VK_KHR_swapchain)");
2440 DestroySwapchain();
2441 return false;
2442 }
2443 vkGetPhysicalDeviceMemoryProperties(s_physicalDevice, &s_memProps);
2444 {
2445 VkPhysicalDeviceProperties props;
2446 vkGetPhysicalDeviceProperties(s_physicalDevice, &props);
2447 s_minUboAlign = props.limits.minUniformBufferOffsetAlignment;
2448 if (s_minUboAlign == 0) {
2449 s_minUboAlign = 16;
2450 }
2451 s_maxImageDim2D = props.limits.maxImageDimension2D;
2452 s_maxUniformRange = props.limits.maxUniformBufferRange;
2453 VkPhysicalDeviceFeatures feats;
2454 vkGetPhysicalDeviceFeatures(s_physicalDevice, &feats);
2455 s_depthClamp = (feats.depthClamp == VK_TRUE);
2456 }
2457
2458 const float queuePriority = 1.0f;
2459 VkDeviceQueueCreateInfo queueInfos[2] = {};
2460 std::uint32_t queueInfoCount = 1;
2461 queueInfos[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
2462 queueInfos[0].queueFamilyIndex = s_graphicsFamily;
2463 queueInfos[0].queueCount = 1;
2464 queueInfos[0].pQueuePriorities = &queuePriority;
2465 if (s_graphicsFamily != s_presentFamily) {
2466 queueInfos[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
2467 queueInfos[1].queueFamilyIndex = s_presentFamily;
2468 queueInfos[1].queueCount = 1;
2469 queueInfos[1].pQueuePriorities = &queuePriority;
2470 queueInfoCount = 2;
2471 }
2472
2473 VkPhysicalDeviceFeatures enabledFeatures = {};
2474 enabledFeatures.depthClamp = s_depthClamp ? VK_TRUE : VK_FALSE;
2475
2476 const char* deviceExts[] = { VK_KHR_SWAPCHAIN_EXTENSION_NAME };
2477 VkDeviceCreateInfo dci = {};
2478 dci.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
2479 dci.queueCreateInfoCount = queueInfoCount;
2480 dci.pQueueCreateInfos = queueInfos;
2481 dci.enabledExtensionCount = 1;
2482 dci.ppEnabledExtensionNames = deviceExts;
2483 dci.pEnabledFeatures = &enabledFeatures;
2484 if (!CheckVk(vkCreateDevice(s_physicalDevice, &dci, nullptr, &s_device), "vkCreateDevice")) {
2485 DestroySwapchain();
2486 return false;
2487 }
2488 LoadDeviceFunctions();
2489
2490 vkGetDeviceQueue(s_device, s_graphicsFamily, 0, &s_graphicsQueue);
2491 vkGetDeviceQueue(s_device, s_presentFamily, 0, &s_presentQueue);
2492
2493 // Command pool + one primary command buffer (re-recorded each frame)
2494 VkCommandPoolCreateInfo pci = {};
2495 pci.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
2496 pci.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
2497 pci.queueFamilyIndex = s_graphicsFamily;
2498 if (!CheckVk(vkCreateCommandPool(s_device, &pci, nullptr, &s_commandPool), "vkCreateCommandPool")) {
2499 DestroySwapchain();
2500 return false;
2501 }
2502 // One primary command buffer PER in-flight frame (re-recorded when its slot is entered);
2503 // RESET_COMMAND_BUFFER on the pool lets each be reset independently while the other is in flight.
2504 for (FrameData& fr : s_frames) {
2505 VkCommandBufferAllocateInfo cbai = {};
2506 cbai.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
2507 cbai.commandPool = s_commandPool;
2508 cbai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
2509 cbai.commandBufferCount = 1;
2510 if (!CheckVk(vkAllocateCommandBuffers(s_device, &cbai, &fr.CommandBuffer), "vkAllocateCommandBuffers")) {
2511 DestroySwapchain();
2512 return false;
2513 }
2514 }
2515 s_commandBuffer = s_frames[0].CommandBuffer;
2516
2517 // The image-available semaphores + in-flight fences (per frame) and render-finished semaphores (per
2518 // swap-chain image) are created in CreateSwapchainObjects, so a resize refreshes them with the swap chain.
2519
2520 // Uniform ring (host-visible, persistently mapped), split into one disjoint region per in-flight frame
2521 s_uboRingSize = 16u * 1024u * 1024u;
2522 s_uboPerFrameSize = s_uboRingSize / MaxFramesInFlight;
2523 {
2524 VkBufferCreateInfo bci = {};
2525 bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
2526 bci.size = s_uboRingSize;
2527 bci.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
2528 bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
2529 if (!CheckVk(vkCreateBuffer(s_device, &bci, nullptr, &s_uboRing), "vkCreateBuffer(uboRing)")) {
2530 DestroySwapchain();
2531 return false;
2532 }
2533 VkMemoryRequirements req;
2534 vkGetBufferMemoryRequirements(s_device, s_uboRing, &req);
2535 VkMemoryAllocateInfo mai = {};
2536 mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
2537 mai.allocationSize = req.size;
2538 mai.memoryTypeIndex = VkFindMemoryType(req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
2539 if (mai.memoryTypeIndex == UINT32_MAX || !CheckVk(vkAllocateMemory(s_device, &mai, nullptr, &s_uboRingMem), "vkAllocateMemory(uboRing)")) {
2540 DestroySwapchain();
2541 return false;
2542 }
2543 vkBindBufferMemory(s_device, s_uboRing, s_uboRingMem, 0);
2544 void* mapped = nullptr;
2545 vkMapMemory(s_device, s_uboRingMem, 0, VK_WHOLE_SIZE, 0, &mapped);
2546 s_uboRingMapped = static_cast<std::uint8_t*>(mapped);
2547 }
2548
2549 CreateDummyTexture();
2550
2551 if (!CreateSwapchainObjects(width, height)) {
2552 DestroySwapchain();
2553 return false;
2554 }
2555
2556 if (width > 0 && height > 0) {
2557 SetViewport(Recti(0, 0, width, height));
2558 }
2559 s_ready = true;
2560 LOGI("Vulkan device ready (depthClamp: {}, minUboAlign: {} bytes)",
2561 s_depthClamp ? "on" : "off", static_cast<std::int32_t>(s_minUboAlign));
2562 # if defined(VULKAN_MRT_PROBE)
2563 RunMrtProbe();
2564 # endif
2565 return true;
2566 #else
2567 static_cast<void>(windowHandle);
2568 static_cast<void>(width);
2569 static_cast<void>(height);
2570 static_cast<void>(vsync);
2571 LOGE("Vulkan backend requires the SDL2 window backend");
2572 return false;
2573 #endif
2574 }
2575
2576 namespace
2577 {
2578 // Current Vulkan drawable size of the SDL window (0x0 while minimized). Used by the present/acquire
2579 // out-of-date recovery so the swap chain is always rebuilt at the true new size (correct even on platforms
2580 // whose surface caps report 0xFFFFFFFF, where the stale s_swapchainExtent would have been wrong).
2581 void QueryDrawableSize(std::int32_t& outW, std::int32_t& outH)
2582 {
2583 outW = 0;
2584 outH = 0;
2585 #if defined(WITH_SDL2) || defined(WITH_SDL3)
2586 if (s_sdlWindow != nullptr) {
2587 int w = 0, h = 0;
2588 # if defined(WITH_SDL3)
2589 // SDL3 removed SDL_Vulkan_GetDrawableSize; the pixel size is queried via SDL_GetWindowSizeInPixels
2590 SDL_GetWindowSizeInPixels(reinterpret_cast<SDL_Window*>(s_sdlWindow), &w, &h);
2591 # else
2592 SDL_Vulkan_GetDrawableSize(reinterpret_cast<SDL_Window*>(s_sdlWindow), &w, &h);
2593 # endif
2594 outW = w;
2595 outH = h;
2596 }
2597 #endif
2598 }
2599 }
2600
2601 void VulkanDevice::ResizeSwapchain(std::int32_t width, std::int32_t height)
2602 {
2603 if (s_device == VK_NULL_HANDLE) {
2604 return;
2605 }
2606 // Idle first so the swap chain + ALL sync objects can be safely destroyed and recreated (DestroySwapchainObjects
2607 // tears down the per-frame + per-image semaphores/fences, so none survives the resize in a signalled state).
2608 vkDeviceWaitIdle(s_device);
2609 s_frameActive = false;
2610 s_renderPassOpen = false;
2611 DestroySwapchainObjects();
2612 // The device is idle, so every frame that could have referenced a deferred-destroy resource has completed;
2613 // free them now rather than carrying partial fence bitmasks across the swap-chain recreation.
2614 FlushDeferredDestroys();
2615 if (width <= 0 || height <= 0) {
2616 // Minimized / zero-size surface: stay not-ready without recreating. PresentFrame polls the drawable
2617 // size each frame and recreates once the window is restored (no wedge, no hang).
2618 s_ready = false;
2619 return;
2620 }
2621 if (CreateSwapchainObjects(width, height)) {
2622 SetViewport(Recti(0, 0, width, height));
2623 s_ready = true;
2624 } else {
2625 s_ready = false;
2626 }
2627 }
2628
2629 void* VulkanDevice::CreateSecondarySwapchain(void* windowHandle, std::int32_t width, std::int32_t height)
2630 {
2631 if (s_device == VK_NULL_HANDLE || s_instance == VK_NULL_HANDLE || windowHandle == nullptr) {
2632 return nullptr;
2633 }
2634
2635 SecondarySwapchain* sc = new SecondarySwapchain();
2636 SDL_Window* window = static_cast<SDL_Window*>(windowHandle);
2637 #if defined(WITH_SDL3)
2638 // SDL3 added a VkAllocationCallbacks* parameter (null = default allocator)
2639 const bool surfaceCreated = SDL_Vulkan_CreateSurface(window, s_instance, nullptr, &sc->Surface);
2640 #else
2641 const bool surfaceCreated = (SDL_Vulkan_CreateSurface(window, s_instance, &sc->Surface) == SDL_TRUE);
2642 #endif
2643 if (!surfaceCreated || sc->Surface == VK_NULL_HANDLE) {
2644 LOGE("SDL_Vulkan_CreateSurface() failed for a secondary window: {}", SDL_GetError());
2645 delete sc;
2646 return nullptr;
2647 }
2648
2649 s_secondarySwapchains.push_back(sc);
2650 if (!CreateSecondarySwapchainObjects(*sc, width, height)) {
2651 // Keep the handle alive without a swap chain: the window may still be zero-sized (hidden), and the
2652 // next resize retries. Only a failed surface is fatal.
2653 DestroySecondarySwapchainObjects(*sc);
2654 }
2655 return sc;
2656 }
2657
2658 void VulkanDevice::DestroySecondarySwapchain(void* handle)
2659 {
2660 SecondarySwapchain* sc = static_cast<SecondarySwapchain*>(handle);
2661 if (sc == nullptr) {
2662 return;
2663 }
2664
2665 // Anything queued for this chain this frame must go before its objects do
2666 for (std::size_t i = 0; i < s_pendingSecondaryPresents.size();) {
2667 if (s_pendingSecondaryPresents[i].Chain == sc) {
2668 s_pendingSecondaryPresents.erase(s_pendingSecondaryPresents.begin() + i);
2669 } else {
2670 i++;
2671 }
2672 }
2673 for (std::size_t i = 0; i < s_secondarySwapchains.size(); i++) {
2674 if (s_secondarySwapchains[i] == sc) {
2675 s_secondarySwapchains.erase(s_secondarySwapchains.begin() + i);
2676 break;
2677 }
2678 }
2679 if (s_device != VK_NULL_HANDLE) {
2680 // Its semaphores may still be in flight from the frame that just presented
2681 vkDeviceWaitIdle(s_device);
2682 DestroySecondarySwapchainObjects(*sc);
2683 if (sc->Surface != VK_NULL_HANDLE && vkDestroySurfaceKHR != nullptr) {
2684 vkDestroySurfaceKHR(s_instance, sc->Surface, nullptr);
2685 }
2686 }
2687 delete sc;
2688 }
2689
2690 void VulkanDevice::ResizeSecondarySwapchain(void* handle, std::int32_t width, std::int32_t height)
2691 {
2692 SecondarySwapchain* sc = static_cast<SecondarySwapchain*>(handle);
2693 if (sc == nullptr || s_device == VK_NULL_HANDLE || sc->Surface == VK_NULL_HANDLE) {
2694 return;
2695 }
2696 if (sc->Ready && sc->RequestedWidth == width && sc->RequestedHeight == height) {
2697 return;
2698 }
2699
2700 vkDeviceWaitIdle(s_device);
2701 DestroySecondarySwapchainObjects(*sc);
2702 if (!CreateSecondarySwapchainObjects(*sc, width, height)) {
2703 DestroySecondarySwapchainObjects(*sc); // leaves it not-ready; retried on the next resize
2704 }
2705 }
2706
2707 void VulkanDevice::QueueSecondaryPresent(void* handle, const VulkanTexture* source)
2708 {
2709 SecondarySwapchain* sc = static_cast<SecondarySwapchain*>(handle);
2710 if (sc == nullptr || !sc->Ready || source == nullptr) {
2711 return;
2712 }
2713 for (PendingSecondaryPresent& pending : s_pendingSecondaryPresents) {
2714 if (pending.Chain == sc) {
2715 pending.Source = source; // re-rendered within the same frame: the last content wins
2716 return;
2717 }
2718 }
2719 s_pendingSecondaryPresents.push_back(PendingSecondaryPresent{ sc, source });
2720 }
2721
2722 void VulkanDevice::PresentFrame()
2723 {
2724 // The queue of undocked ImGui windows is refilled every frame, so it must not survive this one - not even
2725 // through the early returns below that abandon the frame outright
2726 struct PendingPresentsReset
2727 {
2728 ~PendingPresentsReset() {
2729 s_pendingSecondaryPresents.clear();
2730 }
2731 } pendingPresentsReset;
2732
2733 if (s_device == VK_NULL_HANDLE) {
2734 return;
2735 }
2736 // Recover a lost / zero-size swap chain (e.g. after a minimize, or an out-of-date resize that left us
2737 // not-ready): try to recreate at the window's current drawable size; while it is still 0x0 (minimized)
2738 // drop the frame instead of blocking. This is what lets minimize -> restore recover cleanly.
2739 if (!s_ready || s_swapchain == VK_NULL_HANDLE) {
2740 std::int32_t dw = 0, dh = 0;
2741 QueryDrawableSize(dw, dh);
2742 if (dw > 0 && dh > 0) {
2743 ResizeSwapchain(dw, dh);
2744 }
2745 if (!s_ready || s_swapchain == VK_NULL_HANDLE) {
2746 if (s_frameActive) {
2747 vkEndCommandBuffer(s_commandBuffer);
2748 s_frameActive = false;
2749 }
2750 return;
2751 }
2752 }
2753
2754 // A frame with no draws still presents a (black) screen image
2755 if (!s_frameActive) {
2756 BeginFrame();
2757 if (!s_frameActive) {
2758 return;
2759 }
2760 }
2761
2762 EndRenderPassIfOpen();
2763
2764 FrameData& fr = s_frames[s_currentFrame];
2765 std::uint32_t imageIndex = 0;
2766 VkResult acquire = vkAcquireNextImageKHR(s_device, s_swapchain, UINT64_MAX, fr.ImageAvailable, VK_NULL_HANDLE, &imageIndex);
2767 if (acquire == VK_ERROR_OUT_OF_DATE_KHR) {
2768 // Acquire failed => fr.ImageAvailable was NOT signalled and nothing was submitted, so no binary
2769 // semaphore is left dangling. Abandon the recording and recreate at the true current size.
2770 vkEndCommandBuffer(s_commandBuffer);
2771 s_frameActive = false;
2772 std::int32_t dw = 0, dh = 0;
2773 QueryDrawableSize(dw, dh);
2774 ResizeSwapchain(dw, dh);
2775 return;
2776 }
2777 if (acquire != VK_SUCCESS && acquire != VK_SUBOPTIMAL_KHR) {
2778 vkEndCommandBuffer(s_commandBuffer);
2779 s_frameActive = false;
2780 return;
2781 }
2782 // SUBOPTIMAL falls through: the image WAS acquired (fr.ImageAvailable is signalled), so we must submit to
2783 // consume it, then recreate after present.
2784
2785 // If a previous in-flight frame still targets this image, wait its fence before we reuse the image
2786 // (standard imagesInFlight guard). Then record that this image is now owned by this frame's fence.
2787 if (s_imagesInFlight[imageIndex] != VK_NULL_HANDLE) {
2788 vkWaitForFences(s_device, 1, &s_imagesInFlight[imageIndex], VK_TRUE, UINT64_MAX);
2789 }
2790 s_imagesInFlight[imageIndex] = fr.InFlightFence;
2791
2792 VkImage swapImage = s_swapchainImages[imageIndex];
2793
2794 // screen (COLOR_ATTACHMENT) -> TRANSFER_SRC; swap-chain image (UNDEFINED) -> TRANSFER_DST
2795 ImageBarrier(s_commandBuffer, s_screenImage, s_screenLayout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
2796 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT);
2797 s_screenLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
2798 ImageBarrier(s_commandBuffer, swapImage, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
2799 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, VK_ACCESS_TRANSFER_WRITE_BIT);
2800
2801 // Vertically-flipped blit: the scene is stored GL-bottom-up, so map screen row 0 (game bottom) to the
2802 // swap-chain's bottom row and screen top to row 0 - the single GL->Vulkan scan-out correction.
2803 VkImageBlit blit = {};
2804 blit.srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 };
2805 blit.srcOffsets[0] = { 0, 0, 0 };
2806 blit.srcOffsets[1] = { std::int32_t(s_screenExtent.width), std::int32_t(s_screenExtent.height), 1 };
2807 blit.dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 };
2808 blit.dstOffsets[0] = { 0, std::int32_t(s_swapchainExtent.height), 0 };
2809 blit.dstOffsets[1] = { std::int32_t(s_swapchainExtent.width), 0, 1 };
2810 vkCmdBlitImage(s_commandBuffer, s_screenImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
2811 swapImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
2812
2813 // swap-chain image -> PRESENT_SRC; screen -> COLOR_ATTACHMENT for the next frame
2814 ImageBarrier(s_commandBuffer, swapImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
2815 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, 0);
2816 ImageBarrier(s_commandBuffer, s_screenImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
2817 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
2818 s_screenLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
2819
2820 // Submit waits on THIS frame's image-available semaphore and signals the PER-IMAGE render-finished
2821 // semaphore (never a per-frame one), which the present then waits on. A binary semaphore is therefore
2822 // never re-signalled before the present that consumes it has run (the image is not re-acquired until its
2823 // present has drained render-finished), so the resize / out-of-date semaphore-reuse deadlock cannot occur.
2824 // The arguments are gathered into arrays because an undocked ImGui window adds one entry to each: its own
2825 // acquired image to wait on, its own render-finished to signal and its own swap chain to present.
2826 VkSemaphore renderFinished = s_renderFinishedPerImage[imageIndex];
2827 s_submitWaitSemaphores.clear();
2828 s_submitWaitStages.clear();
2829 s_submitSignalSemaphores.clear();
2830 s_presentSwapchains.clear();
2831 s_presentImageIndices.clear();
2832 s_presentChains.clear();
2833 s_submitWaitSemaphores.push_back(fr.ImageAvailable);
2834 s_submitWaitStages.push_back(VK_PIPELINE_STAGE_TRANSFER_BIT);
2835 s_submitSignalSemaphores.push_back(renderFinished);
2836 s_presentSwapchains.push_back(s_swapchain);
2837 s_presentImageIndices.push_back(imageIndex);
2838 s_presentChains.push_back(nullptr);
2839
2840 // Undocked ImGui windows: each one's contents were rendered into an off-screen target earlier this frame
2841 // (through the ordinary RHI path), so all that is left is the same flipped blit the main window gets. The
2842 // loop does not run at all while nothing is undocked.
2843 for (PendingSecondaryPresent& pending : s_pendingSecondaryPresents) {
2844 SecondarySwapchain& sc = *pending.Chain;
2845 if (!sc.Ready) {
2846 continue;
2847 }
2848 VkSemaphore secImageAvailable = sc.ImageAvailable[s_currentFrame];
2849 std::uint32_t secImageIndex = 0;
2850 // Bounded wait, unlike the main window's: a UI window whose images nobody is consuming (occluded,
2851 // hidden but not reported minimized) must never be able to stall the game. TIMEOUT / NOT_READY leave
2852 // the semaphore unsignalled and no image acquired, so the window simply keeps last frame's contents
2853 // and is retried next frame.
2854 constexpr std::uint64_t SecondaryAcquireTimeout = 32 * 1000 * 1000; // ns, ~2 frames at 60 Hz
2855 const VkResult secAcquire = vkAcquireNextImageKHR(s_device, sc.Swapchain, SecondaryAcquireTimeout, secImageAvailable, VK_NULL_HANDLE, &secImageIndex);
2856 if (secAcquire == VK_TIMEOUT || secAcquire == VK_NOT_READY) {
2857 continue;
2858 }
2859 if (secAcquire != VK_SUCCESS && secAcquire != VK_SUBOPTIMAL_KHR) {
2860 // A real failure (out of date, surface lost) also leaves nothing signalled, so nothing dangles; the
2861 // window is left not-ready and rebuilt by the next resize (ImGui reports one whenever it changes)
2862 sc.Ready = false;
2863 continue;
2864 }
2865 // Do not reuse an image a still-running frame targets (the same guard as the main chain)
2866 if (sc.ImagesInFlight[secImageIndex] != VK_NULL_HANDLE) {
2867 vkWaitForFences(s_device, 1, &sc.ImagesInFlight[secImageIndex], VK_TRUE, UINT64_MAX);
2868 }
2869 sc.ImagesInFlight[secImageIndex] = fr.InFlightFence;
2870
2871 VkImage sourceImage = reinterpret_cast<VkImage>(pending.Source->GpuImage());
2872 VkImage secImage = sc.Images[secImageIndex];
2873 ImageBarrier(s_commandBuffer, sourceImage, VkImageLayout(pending.Source->GetCurrentLayout()), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
2874 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT);
2875 // Leave the tracked layout truthful: the next render pass into this texture transitions it back
2876 pending.Source->SetCurrentLayout(std::uint32_t(VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL));
2877 ImageBarrier(s_commandBuffer, secImage, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
2878 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, VK_ACCESS_TRANSFER_WRITE_BIT);
2879
2880 // Vertically flipped, exactly like the main present: the texture holds a GL-bottom-up image
2881 VkImageBlit secBlit = {};
2882 secBlit.srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 };
2883 secBlit.srcOffsets[0] = { 0, 0, 0 };
2884 secBlit.srcOffsets[1] = { pending.Source->GetWidth(), pending.Source->GetHeight(), 1 };
2885 secBlit.dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 };
2886 secBlit.dstOffsets[0] = { 0, std::int32_t(sc.Extent.height), 0 };
2887 secBlit.dstOffsets[1] = { std::int32_t(sc.Extent.width), 0, 1 };
2888 vkCmdBlitImage(s_commandBuffer, sourceImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
2889 secImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &secBlit, VK_FILTER_NEAREST);
2890
2891 ImageBarrier(s_commandBuffer, secImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
2892 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, 0);
2893
2894 s_submitWaitSemaphores.push_back(secImageAvailable);
2895 s_submitWaitStages.push_back(VK_PIPELINE_STAGE_TRANSFER_BIT);
2896 s_submitSignalSemaphores.push_back(sc.RenderFinishedPerImage[secImageIndex]);
2897 s_presentSwapchains.push_back(sc.Swapchain);
2898 s_presentImageIndices.push_back(secImageIndex);
2899 s_presentChains.push_back(&sc);
2900 }
2901
2902 vkEndCommandBuffer(s_commandBuffer);
2903
2904 VkSubmitInfo submit = {};
2905 submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
2906 submit.waitSemaphoreCount = std::uint32_t(s_submitWaitSemaphores.size());
2907 submit.pWaitSemaphores = s_submitWaitSemaphores.data();
2908 submit.pWaitDstStageMask = s_submitWaitStages.data();
2909 submit.commandBufferCount = 1;
2910 submit.pCommandBuffers = &s_commandBuffer;
2911 submit.signalSemaphoreCount = std::uint32_t(s_submitSignalSemaphores.size());
2912 submit.pSignalSemaphores = s_submitSignalSemaphores.data();
2913 vkResetFences(s_device, 1, &fr.InFlightFence);
2914 s_frameActive = false;
2915 if (vkQueueSubmit(s_graphicsQueue, 1, &submit, fr.InFlightFence) != VK_SUCCESS) {
2916 // Submit failed: the fence was reset but never enqueued, so it will never signal - FenceInFlight stays
2917 // false so the next BeginFrame does not deadlock waiting on it, and the image-in-flight entries are
2918 // cleared so a future acquire of those images does not wait on the same never-signalled fence.
2919 // fr.ImageAvailable stays signalled, but the next successful submit for this slot consumes it
2920 // (or the next resize recreates it).
2921 s_imagesInFlight[imageIndex] = VK_NULL_HANDLE;
2922 for (std::size_t i = 1; i < s_presentChains.size(); i++) {
2923 s_presentChains[i]->ImagesInFlight[s_presentImageIndices[i]] = VK_NULL_HANDLE;
2924 }
2925 LOGE("vkQueueSubmit() failed, dropping the frame");
2926 return;
2927 }
2928 fr.FenceInFlight = true;
2929
2930 VkPresentInfoKHR present = {};
2931 present.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
2932 present.waitSemaphoreCount = std::uint32_t(s_submitSignalSemaphores.size());
2933 present.pWaitSemaphores = s_submitSignalSemaphores.data();
2934 present.swapchainCount = std::uint32_t(s_presentSwapchains.size());
2935 present.pSwapchains = s_presentSwapchains.data();
2936 present.pImageIndices = s_presentImageIndices.data();
2937 if (s_presentSwapchains.size() > 1) {
2938 // With several swap chains the aggregate result cannot say WHICH one is out of date, so ask per chain
2939 s_presentResults.assign(s_presentSwapchains.size(), VK_SUCCESS);
2940 present.pResults = s_presentResults.data();
2941 }
2942 VkResult res = vkQueuePresentKHR(s_presentQueue, &present);
2943
2944 // Advance to the next in-flight slot (round-robin) now that this frame's fence/semaphores are in flight
2945 s_currentFrame = (s_currentFrame + 1) % MaxFramesInFlight;
2946
2947 if (present.pResults != nullptr) {
2948 // An undocked window going out of date must not drag the main swap chain into a recreation, so the
2949 // aggregate result is replaced by the main chain's own and the others only mark their window for rebuild
2950 res = s_presentResults[0];
2951 for (std::size_t i = 1; i < s_presentChains.size(); i++) {
2952 if (s_presentResults[i] == VK_ERROR_OUT_OF_DATE_KHR || s_presentResults[i] == VK_SUBOPTIMAL_KHR) {
2953 s_presentChains[i]->Ready = false;
2954 }
2955 }
2956 }
2957
2958 if (res == VK_ERROR_OUT_OF_DATE_KHR || res == VK_SUBOPTIMAL_KHR) {
2959 // The recreate destroys + rebuilds every sync object, so any render-finished semaphore left signalled
2960 // by an out-of-date present is discarded rather than re-signalled next frame.
2961 std::int32_t dw = 0, dh = 0;
2962 QueryDrawableSize(dw, dh);
2963 ResizeSwapchain(dw, dh);
2964 }
2965 }
2966
2967 void VulkanDevice::DestroySwapchain()
2968 {
2969 if (s_device != VK_NULL_HANDLE) {
2970 vkDeviceWaitIdle(s_device);
2971 }
2972 s_ready = false;
2973 s_frameActive = false;
2974 s_renderPassOpen = false;
2975
2976 if (s_device != VK_NULL_HANDLE) {
2977 for (auto& kv : s_pipelines) {
2978 vkDestroyPipeline(s_device, kv.second, nullptr);
2979 }
2980 s_pipelines.clear();
2981 for (auto& kv : s_renderPasses) {
2982 vkDestroyRenderPass(s_device, kv.second, nullptr);
2983 }
2984 s_renderPasses.clear();
2985 // Per-frame descriptor pools + any queued staging buffers (device is idle above)
2986 for (FrameData& fr : s_frames) {
2987 for (VkDescriptorPool pool : fr.DescPools) {
2988 vkDestroyDescriptorPool(s_device, pool, nullptr);
2989 }
2990 fr.DescPools.clear();
2991 fr.DescPoolCursor = 0;
2992 FreeFrameStaging(fr);
2993 }
2994 // Flush any resources still deferred for destruction (device is idle above, so all are safe to free);
2995 // otherwise their handles would leak past the vkDestroyDevice below.
2996 FlushDeferredDestroys();
2997
2998 if (s_dummySampler != VK_NULL_HANDLE) { vkDestroySampler(s_device, s_dummySampler, nullptr); s_dummySampler = VK_NULL_HANDLE; }
2999 if (s_dummyView != VK_NULL_HANDLE) { vkDestroyImageView(s_device, s_dummyView, nullptr); s_dummyView = VK_NULL_HANDLE; }
3000 if (s_dummyImage != VK_NULL_HANDLE) { vkDestroyImage(s_device, s_dummyImage, nullptr); s_dummyImage = VK_NULL_HANDLE; }
3001 if (s_dummyMemory != VK_NULL_HANDLE) { vkFreeMemory(s_device, s_dummyMemory, nullptr); s_dummyMemory = VK_NULL_HANDLE; }
3002
3003 if (s_uboRingMapped != nullptr) { vkUnmapMemory(s_device, s_uboRingMem); s_uboRingMapped = nullptr; }
3004 if (s_uboRing != VK_NULL_HANDLE) { vkDestroyBuffer(s_device, s_uboRing, nullptr); s_uboRing = VK_NULL_HANDLE; }
3005 if (s_uboRingMem != VK_NULL_HANDLE) { vkFreeMemory(s_device, s_uboRingMem, nullptr); s_uboRingMem = VK_NULL_HANDLE; }
3006
3007 DestroyScreenTarget();
3008
3009 // The swap chain AND all sync objects (per-frame image-available/fence, per-image render-finished) are
3010 // torn down here; destroying the command pool frees every per-frame command buffer.
3011 DestroySwapchainObjects();
3012 if (s_commandPool != VK_NULL_HANDLE) {
3013 vkDestroyCommandPool(s_device, s_commandPool, nullptr);
3014 s_commandPool = VK_NULL_HANDLE;
3015 for (FrameData& fr : s_frames) {
3016 fr.CommandBuffer = VK_NULL_HANDLE;
3017 }
3018 s_commandBuffer = VK_NULL_HANDLE;
3019 }
3020 if (s_pipelineCache != VK_NULL_HANDLE) {
3021 // Kept across swapchain rebuilds (so resized pipelines reuse the driver cache); dies with the device
3022 if (vkDestroyPipelineCache != nullptr) {
3023 vkDestroyPipelineCache(s_device, s_pipelineCache, nullptr);
3024 }
3025 s_pipelineCache = VK_NULL_HANDLE;
3026 }
3027 vkDestroyDevice(s_device, nullptr);
3028 s_device = VK_NULL_HANDLE;
3029 }
3030 if (s_instance != VK_NULL_HANDLE) {
3031 if (s_surface != VK_NULL_HANDLE && vkDestroySurfaceKHR != nullptr) {
3032 vkDestroySurfaceKHR(s_instance, s_surface, nullptr);
3033 s_surface = VK_NULL_HANDLE;
3034 }
3035 if (s_debugMessenger != VK_NULL_HANDLE && vkDestroyDebugUtilsMessengerEXT != nullptr) {
3036 vkDestroyDebugUtilsMessengerEXT(s_instance, s_debugMessenger, nullptr);
3037 s_debugMessenger = VK_NULL_HANDLE;
3038 }
3039 vkDestroyInstance(s_instance, nullptr);
3040 s_instance = VK_NULL_HANDLE;
3041 }
3042 s_physicalDevice = VK_NULL_HANDLE;
3043 s_graphicsQueue = VK_NULL_HANDLE;
3044 s_presentQueue = VK_NULL_HANDLE;
3045 }
3046
3047 // -- Loader --
3048
3049 namespace
3050 {
3051 VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
3052 VkDebugUtilsMessageTypeFlagsEXT, const VkDebugUtilsMessengerCallbackDataEXT* data, void*)
3053 {
3054 if (data == nullptr || data->pMessage == nullptr) {
3055 return VK_FALSE;
3056 }
3057 if (severity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
3058 LOGE("Vulkan: {}", data->pMessage);
3059 } else if (severity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
3060 LOGW("Vulkan: {}", data->pMessage);
3061 }
3062 return VK_FALSE;
3063 }
3064 }
3065
3066 void VulkanDevice::LoadGlobalFunctions()
3067 {
3068 vkCreateInstance = reinterpret_cast<PFN_vkCreateInstance>(vkGetInstanceProcAddr(nullptr, "vkCreateInstance"));
3069 vkEnumerateInstanceLayerProperties = reinterpret_cast<PFN_vkEnumerateInstanceLayerProperties>(vkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceLayerProperties"));
3070 vkEnumerateInstanceExtensionProperties = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>(vkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceExtensionProperties"));
3071 }
3072
3073 void VulkanDevice::LoadInstanceFunctions()
3074 {
3075 #define VK_LOAD_INSTANCE(name) name = reinterpret_cast<PFN_##name>(vkGetInstanceProcAddr(s_instance, #name))
3076 VK_LOAD_INSTANCE(vkDestroyInstance);
3077 VK_LOAD_INSTANCE(vkEnumeratePhysicalDevices);
3078 VK_LOAD_INSTANCE(vkGetPhysicalDeviceProperties);
3079 VK_LOAD_INSTANCE(vkGetPhysicalDeviceFeatures);
3080 VK_LOAD_INSTANCE(vkGetPhysicalDeviceMemoryProperties);
3081 VK_LOAD_INSTANCE(vkGetPhysicalDeviceFormatProperties);
3082 VK_LOAD_INSTANCE(vkGetPhysicalDeviceQueueFamilyProperties);
3083 VK_LOAD_INSTANCE(vkEnumerateDeviceExtensionProperties);
3084 VK_LOAD_INSTANCE(vkGetPhysicalDeviceSurfaceSupportKHR);
3085 VK_LOAD_INSTANCE(vkGetPhysicalDeviceSurfaceCapabilitiesKHR);
3086 VK_LOAD_INSTANCE(vkGetPhysicalDeviceSurfaceFormatsKHR);
3087 VK_LOAD_INSTANCE(vkGetPhysicalDeviceSurfacePresentModesKHR);
3088 VK_LOAD_INSTANCE(vkCreateDevice);
3089 VK_LOAD_INSTANCE(vkGetDeviceProcAddr);
3090 VK_LOAD_INSTANCE(vkDestroySurfaceKHR);
3091 VK_LOAD_INSTANCE(vkCreateDebugUtilsMessengerEXT);
3092 VK_LOAD_INSTANCE(vkDestroyDebugUtilsMessengerEXT);
3093 #undef VK_LOAD_INSTANCE
3094 }
3095
3096 void VulkanDevice::LoadDeviceFunctions()
3097 {
3098 #define VK_LOAD_DEVICE(name) name = reinterpret_cast<PFN_##name>(vkGetDeviceProcAddr(s_device, #name))
3099 VK_LOAD_DEVICE(vkDestroyDevice);
3100 VK_LOAD_DEVICE(vkDeviceWaitIdle);
3101 VK_LOAD_DEVICE(vkGetDeviceQueue);
3102 VK_LOAD_DEVICE(vkCreateSwapchainKHR);
3103 VK_LOAD_DEVICE(vkDestroySwapchainKHR);
3104 VK_LOAD_DEVICE(vkGetSwapchainImagesKHR);
3105 VK_LOAD_DEVICE(vkCreateImageView);
3106 VK_LOAD_DEVICE(vkDestroyImageView);
3107 VK_LOAD_DEVICE(vkCreateCommandPool);
3108 VK_LOAD_DEVICE(vkDestroyCommandPool);
3109 VK_LOAD_DEVICE(vkAllocateCommandBuffers);
3110 VK_LOAD_DEVICE(vkFreeCommandBuffers);
3111 VK_LOAD_DEVICE(vkResetCommandBuffer);
3112 VK_LOAD_DEVICE(vkBeginCommandBuffer);
3113 VK_LOAD_DEVICE(vkEndCommandBuffer);
3114 VK_LOAD_DEVICE(vkCmdClearColorImage);
3115 VK_LOAD_DEVICE(vkCmdPipelineBarrier);
3116 VK_LOAD_DEVICE(vkCreateSemaphore);
3117 VK_LOAD_DEVICE(vkDestroySemaphore);
3118 VK_LOAD_DEVICE(vkCreateFence);
3119 VK_LOAD_DEVICE(vkDestroyFence);
3120 VK_LOAD_DEVICE(vkWaitForFences);
3121 VK_LOAD_DEVICE(vkResetFences);
3122 VK_LOAD_DEVICE(vkAcquireNextImageKHR);
3123 VK_LOAD_DEVICE(vkQueueSubmit);
3124 VK_LOAD_DEVICE(vkQueuePresentKHR);
3125 VK_LOAD_DEVICE(vkQueueWaitIdle);
3126 VK_LOAD_DEVICE(vkCreateBuffer);
3127 VK_LOAD_DEVICE(vkDestroyBuffer);
3128 VK_LOAD_DEVICE(vkGetBufferMemoryRequirements);
3129 VK_LOAD_DEVICE(vkBindBufferMemory);
3130 VK_LOAD_DEVICE(vkCreateImage);
3131 VK_LOAD_DEVICE(vkDestroyImage);
3132 VK_LOAD_DEVICE(vkGetImageMemoryRequirements);
3133 VK_LOAD_DEVICE(vkBindImageMemory);
3134 VK_LOAD_DEVICE(vkAllocateMemory);
3135 VK_LOAD_DEVICE(vkFreeMemory);
3136 VK_LOAD_DEVICE(vkMapMemory);
3137 VK_LOAD_DEVICE(vkUnmapMemory);
3138 VK_LOAD_DEVICE(vkCreateSampler);
3139 VK_LOAD_DEVICE(vkDestroySampler);
3140 VK_LOAD_DEVICE(vkCreateShaderModule);
3141 VK_LOAD_DEVICE(vkDestroyShaderModule);
3142 VK_LOAD_DEVICE(vkCreateDescriptorSetLayout);
3143 VK_LOAD_DEVICE(vkDestroyDescriptorSetLayout);
3144 VK_LOAD_DEVICE(vkCreateDescriptorPool);
3145 VK_LOAD_DEVICE(vkDestroyDescriptorPool);
3146 VK_LOAD_DEVICE(vkResetDescriptorPool);
3147 VK_LOAD_DEVICE(vkAllocateDescriptorSets);
3148 VK_LOAD_DEVICE(vkUpdateDescriptorSets);
3149 VK_LOAD_DEVICE(vkCreatePipelineLayout);
3150 VK_LOAD_DEVICE(vkDestroyPipelineLayout);
3151 VK_LOAD_DEVICE(vkCreateGraphicsPipelines);
3152 VK_LOAD_DEVICE(vkDestroyPipeline);
3153 VK_LOAD_DEVICE(vkCreatePipelineCache);
3154 VK_LOAD_DEVICE(vkDestroyPipelineCache);
3155 VK_LOAD_DEVICE(vkCmdCopyImageToBuffer);
3156 VK_LOAD_DEVICE(vkCreateRenderPass);
3157 VK_LOAD_DEVICE(vkDestroyRenderPass);
3158 VK_LOAD_DEVICE(vkCreateFramebuffer);
3159 VK_LOAD_DEVICE(vkDestroyFramebuffer);
3160 VK_LOAD_DEVICE(vkCmdBeginRenderPass);
3161 VK_LOAD_DEVICE(vkCmdEndRenderPass);
3162 VK_LOAD_DEVICE(vkCmdBindPipeline);
3163 VK_LOAD_DEVICE(vkCmdBindVertexBuffers);
3164 VK_LOAD_DEVICE(vkCmdBindIndexBuffer);
3165 VK_LOAD_DEVICE(vkCmdBindDescriptorSets);
3166 VK_LOAD_DEVICE(vkCmdSetViewport);
3167 VK_LOAD_DEVICE(vkCmdSetScissor);
3168 VK_LOAD_DEVICE(vkCmdDraw);
3169 VK_LOAD_DEVICE(vkCmdDrawIndexed);
3170 VK_LOAD_DEVICE(vkCmdCopyBuffer);
3171 VK_LOAD_DEVICE(vkCmdCopyBufferToImage);
3172 VK_LOAD_DEVICE(vkCmdClearAttachments);
3173 VK_LOAD_DEVICE(vkCmdBlitImage);
3174 #undef VK_LOAD_DEVICE
3175 }
3176 }