SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
VulkanSwapchain.cpp
Go to the documentation of this file.
2
3#include <Core/Window.hpp>
4#include <algorithm>
5#include <cstdint>
6#include <limits>
7#include <optional>
8#include <vector>
9#include "Core/Logger.hpp"
10#include "SDL3/SDL_video.h"
11
12namespace Sleak {
13 namespace RenderEngine {
14
15 namespace {
16
17 /// Short name of a present mode for logs.
18 const char* PresentModeName(VkPresentModeKHR mode) {
19 switch (mode) {
20 case VK_PRESENT_MODE_IMMEDIATE_KHR:
21 return "IMMEDIATE";
22 case VK_PRESENT_MODE_MAILBOX_KHR:
23 return "MAILBOX";
24 case VK_PRESENT_MODE_FIFO_KHR:
25 return "FIFO";
26 case VK_PRESENT_MODE_FIFO_RELAXED_KHR:
27 return "FIFO_RELAXED";
28 default:
29 return "OTHER";
30 }
31 }
32
33 } // namespace
34
35/// Creates the swapchain from the queried surface capabilities.
36bool VulkanRenderer::CreateSwapChain() {
37 auto details = QuerySwapchain();
38 if (!details.has_value())
39 return false;
40
41 if (details->formats.empty() && details->presentModes.empty())
42 SLEAK_RETURN_ERR("Swapchain is not supported for this GPU!");
43
44 auto format = ChooseFormat(details->formats);
45 auto mode = ChoosePresentMode(details->presentModes);
46 auto extent = ChooseExtend(details->caps);
47
48 uint32_t imageCount = details->caps.minImageCount + 1;
49 if (details->caps.maxImageCount > 0 &&
50 imageCount > details->caps.maxImageCount)
51 imageCount = details->caps.maxImageCount;
52
53 VkSwapchainCreateInfoKHR info{};
54 info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
55 info.minImageCount = imageCount;
56 info.imageColorSpace = format.colorSpace;
57 info.imageFormat = format.format;
58 info.imageExtent = extent;
59 info.imageArrayLayers = 1;
60 info.presentMode = mode;
61 info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
62 m_swapchainTransferSrc =
63 m_captureMode &&
64 (details->caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
65 if (m_swapchainTransferSrc)
66 info.imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
67
68 uint32_t indices[] = {QueueIDs.GraphicsIndex, QueueIDs.PresentIndex};
69
70 if (QueueIDs.GraphicsIndex != QueueIDs.PresentIndex) {
71 info.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
72 info.queueFamilyIndexCount = 2;
73 info.pQueueFamilyIndices = indices;
74 } else {
75 info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
76 }
77
78 info.surface = surface;
79 info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
80 info.preTransform = details->caps.currentTransform;
81 info.clipped = VK_TRUE;
82 info.oldSwapchain = VK_NULL_HANDLE;
83
84 VkResult result =
85 vkCreateSwapchainKHR(device, &info, nullptr, &swapChain);
86 if (result != VK_SUCCESS)
87 SLEAK_RETURN_ERR("Failed to create swap chain for renderer!")
88
89 uint32_t scImageCount = 0;
90 vkGetSwapchainImagesKHR(device, swapChain, &scImageCount, nullptr);
91 swapChainImages.resize(scImageCount);
92 vkGetSwapchainImagesKHR(device, swapChain, &scImageCount,
93 swapChainImages.data());
94
95 scImageFormat = format.format;
96 scExtent = extent;
97
98 SLEAK_INFO("Swapchain: {}x{}, {} images, format {}, present mode {}",
99 extent.width, extent.height, scImageCount,
100 static_cast<int>(format.format), PresentModeName(mode));
101 return true;
102}
103
104/// Destroys the swapchain, its image views, and framebuffers.
105void VulkanRenderer::CleanupSwapChain() {
106 CleanupDepthResources();
107 CleanupMSAAColorResources();
108
109 for (auto framebuffer : swapChainFramebuffers) {
110 vkDestroyFramebuffer(device, framebuffer, nullptr);
111 }
112 swapChainFramebuffers.clear();
113
114 for (auto imageView : swapChainImageViews) {
115 vkDestroyImageView(device, imageView, nullptr);
116 }
117 swapChainImageViews.clear();
118
119 if (swapChain) {
120 vkDestroySwapchainKHR(device, swapChain, nullptr);
121 swapChain = VK_NULL_HANDLE;
122 }
123}
124
125/// Creates the MSAA color image used as the multisampled render target.
126bool VulkanRenderer::CreateMSAAColorResources() {
127 if (m_msaaSamples == VK_SAMPLE_COUNT_1_BIT)
128 return true; // No MSAA image needed
129
130 VkImageCreateInfo imageInfo{};
131 imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
132 imageInfo.imageType = VK_IMAGE_TYPE_2D;
133 imageInfo.extent.width = scExtent.width;
134 imageInfo.extent.height = scExtent.height;
135 imageInfo.extent.depth = 1;
136 imageInfo.mipLevels = 1;
137 imageInfo.arrayLayers = 1;
138 imageInfo.format = scImageFormat;
139 imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
140 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
141 imageInfo.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
142 imageInfo.samples = m_msaaSamples;
143 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
144
145 if (vkCreateImage(device, &imageInfo, nullptr, &m_msaaColorImage) != VK_SUCCESS)
146 SLEAK_RETURN_ERR("Failed to create MSAA color image!");
147
148 VkMemoryRequirements memRequirements;
149 vkGetImageMemoryRequirements(device, m_msaaColorImage, &memRequirements);
150
151 VkMemoryAllocateInfo allocInfo{};
152 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
153 allocInfo.allocationSize = memRequirements.size;
154 allocInfo.memoryTypeIndex = FindMemoryType(
155 memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
156
157 if (vkAllocateMemory(device, &allocInfo, nullptr, &m_msaaColorImageMemory) != VK_SUCCESS)
158 SLEAK_RETURN_ERR("Failed to allocate MSAA color image memory!");
159
160 vkBindImageMemory(device, m_msaaColorImage, m_msaaColorImageMemory, 0);
161
162 VkImageViewCreateInfo viewInfo{};
163 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
164 viewInfo.image = m_msaaColorImage;
165 viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
166 viewInfo.format = scImageFormat;
167 viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
168 viewInfo.subresourceRange.baseMipLevel = 0;
169 viewInfo.subresourceRange.levelCount = 1;
170 viewInfo.subresourceRange.baseArrayLayer = 0;
171 viewInfo.subresourceRange.layerCount = 1;
172
173 if (vkCreateImageView(device, &viewInfo, nullptr, &m_msaaColorImageView) != VK_SUCCESS)
174 SLEAK_RETURN_ERR("Failed to create MSAA color image view!");
175
176 return true;
177}
178
179/// Destroys the MSAA color image, view, and memory.
180void VulkanRenderer::CleanupMSAAColorResources() {
181 if (m_msaaColorImageView) {
182 vkDestroyImageView(device, m_msaaColorImageView, nullptr);
183 m_msaaColorImageView = VK_NULL_HANDLE;
184 }
185 if (m_msaaColorImage) {
186 vkDestroyImage(device, m_msaaColorImage, nullptr);
187 m_msaaColorImage = VK_NULL_HANDLE;
188 }
189 if (m_msaaColorImageMemory) {
190 vkFreeMemory(device, m_msaaColorImageMemory, nullptr);
191 m_msaaColorImageMemory = VK_NULL_HANDLE;
192 }
193}
194
195/// Queries the highest MSAA sample count the GPU supports.
196VkSampleCountFlagBits VulkanRenderer::GetMaxUsableSampleCount() {
197 VkPhysicalDeviceProperties props;
198 vkGetPhysicalDeviceProperties(physicalDevice, &props);
199 VkSampleCountFlags counts = props.limits.framebufferColorSampleCounts
200 & props.limits.framebufferDepthSampleCounts;
201 if (counts & VK_SAMPLE_COUNT_8_BIT) return VK_SAMPLE_COUNT_8_BIT;
202 if (counts & VK_SAMPLE_COUNT_4_BIT) return VK_SAMPLE_COUNT_4_BIT;
203 if (counts & VK_SAMPLE_COUNT_2_BIT) return VK_SAMPLE_COUNT_2_BIT;
204 return VK_SAMPLE_COUNT_1_BIT;
205}
206
207/// Creates an image view for each swapchain image.
208bool VulkanRenderer::CreateImageViews() {
209 swapChainImageViews.resize(swapChainImages.size());
210
211 for (size_t i = 0; i < swapChainImageViews.size(); i++) {
212 VkImageViewCreateInfo info{};
213 info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
214 info.image = swapChainImages[i];
215 info.viewType = VK_IMAGE_VIEW_TYPE_2D;
216 info.format = scImageFormat;
217
218 info.components = {VK_COMPONENT_SWIZZLE_IDENTITY,
219 VK_COMPONENT_SWIZZLE_IDENTITY,
220 VK_COMPONENT_SWIZZLE_IDENTITY,
221 VK_COMPONENT_SWIZZLE_IDENTITY};
222
223 info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
224 info.subresourceRange.baseMipLevel = 0;
225 info.subresourceRange.levelCount = 1;
226 info.subresourceRange.baseArrayLayer = 0;
227 info.subresourceRange.layerCount = 1;
228
229 auto result = vkCreateImageView(device, &info, nullptr,
230 &swapChainImageViews[i]);
231 if (result != VK_SUCCESS)
233 "Failed to create image view of swapchain, index: {}", i);
234 }
235
236 return true;
237}
238
239/// Creates the depth image, memory, and image view.
240bool VulkanRenderer::CreateDepthResources() {
241 depthFormat = FindDepthFormat();
242
243 // Create depth image
244 VkImageCreateInfo imageInfo{};
245 imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
246 imageInfo.imageType = VK_IMAGE_TYPE_2D;
247 imageInfo.extent.width = scExtent.width;
248 imageInfo.extent.height = scExtent.height;
249 imageInfo.extent.depth = 1;
250 imageInfo.mipLevels = 1;
251 imageInfo.arrayLayers = 1;
252 imageInfo.format = depthFormat;
253 imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
254 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
255 // Always add SAMPLED_BIT so deferred lighting pass can read depth.
256 // When deferred is enabled, force 1x samples (GBuffer is non-MSAA).
257 // TRANSFER_SRC_BIT: scene-read snapshot for transparent formats.
258 VkSampleCountFlagBits depthSamples = m_deferredEnabled
259 ? VK_SAMPLE_COUNT_1_BIT : m_msaaSamples;
260 imageInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT |
261 VK_IMAGE_USAGE_SAMPLED_BIT |
262 VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
263 imageInfo.samples = depthSamples;
264 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
265
266 if (vkCreateImage(device, &imageInfo, nullptr, &depthImage) !=
267 VK_SUCCESS)
268 SLEAK_RETURN_ERR("Failed to create depth image!");
269
270 // Allocate memory
271 VkMemoryRequirements memRequirements;
272 vkGetImageMemoryRequirements(device, depthImage, &memRequirements);
273
274 VkMemoryAllocateInfo allocInfo{};
275 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
276 allocInfo.allocationSize = memRequirements.size;
277 allocInfo.memoryTypeIndex = FindMemoryType(
278 memRequirements.memoryTypeBits,
279 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
280
281 if (vkAllocateMemory(device, &allocInfo, nullptr, &depthImageMemory) !=
282 VK_SUCCESS)
283 SLEAK_RETURN_ERR("Failed to allocate depth image memory!");
284
285 vkBindImageMemory(device, depthImage, depthImageMemory, 0);
286
287 // Create image view
288 VkImageViewCreateInfo viewInfo{};
289 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
290 viewInfo.image = depthImage;
291 viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
292 viewInfo.format = depthFormat;
293 viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
294 viewInfo.subresourceRange.baseMipLevel = 0;
295 viewInfo.subresourceRange.levelCount = 1;
296 viewInfo.subresourceRange.baseArrayLayer = 0;
297 viewInfo.subresourceRange.layerCount = 1;
298
299 if (vkCreateImageView(device, &viewInfo, nullptr, &depthImageView) !=
300 VK_SUCCESS)
301 SLEAK_RETURN_ERR("Failed to create depth image view!");
302
303 return true;
304}
305
306/// Destroys the depth image, memory, and image view.
307void VulkanRenderer::CleanupDepthResources() {
308 if (depthImageView) {
309 vkDestroyImageView(device, depthImageView, nullptr);
310 depthImageView = VK_NULL_HANDLE;
311 }
312 if (depthImage) {
313 vkDestroyImage(device, depthImage, nullptr);
314 depthImage = VK_NULL_HANDLE;
315 }
316 if (depthImageMemory) {
317 vkFreeMemory(device, depthImageMemory, nullptr);
318 depthImageMemory = VK_NULL_HANDLE;
319 }
320}
321
322/// Picks the first supported depth-stencil format from the candidate list.
323VkFormat VulkanRenderer::FindDepthFormat() {
324 std::vector<VkFormat> candidates = {VK_FORMAT_D32_SFLOAT,
325 VK_FORMAT_D32_SFLOAT_S8_UINT,
326 VK_FORMAT_D24_UNORM_S8_UINT};
327
328 for (VkFormat format : candidates) {
329 VkFormatProperties props;
330 vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &props);
331
332 if (props.optimalTilingFeatures &
333 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) {
334 return format;
335 }
336 }
337
338 return VK_FORMAT_D32_SFLOAT; // fallback
339}
340
341/// Finds a memory type index matching the filter and property flags.
342uint32_t VulkanRenderer::FindMemoryType(
343 uint32_t typeFilter, VkMemoryPropertyFlags properties) {
344 VkPhysicalDeviceMemoryProperties memProperties;
345 vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
346
347 for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
348 if ((typeFilter & (1 << i)) &&
349 (memProperties.memoryTypes[i].propertyFlags & properties) ==
350 properties) {
351 return i;
352 }
353 }
354
355 SLEAK_ERROR("Failed to find suitable memory type!");
356 return 0;
357}
358
359/// Queries surface capabilities, formats, and present modes.
360std::optional<SwapchainDetails> VulkanRenderer::QuerySwapchain() {
361 SwapchainDetails details;
362
363 VkResult result = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
364 physicalDevice, surface, &details.caps);
365 if (result != VK_SUCCESS) {
366 SLEAK_ERROR("Failed to retrieve surface information!");
367 return {};
368 }
369
370 // Fixed: use resize() not reserve()
371 uint32_t formatCount = 0;
372 result = vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface,
373 &formatCount, nullptr);
374 if (result != VK_SUCCESS || formatCount < 1) {
375 SLEAK_ERROR("Failed to retrieve supported surface formats");
376 return {};
377 }
378
379 details.formats.resize(formatCount);
380 vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface,
381 &formatCount,
382 details.formats.data());
383
384 // Get surface present modes
385 uint32_t modeCount = 0;
386 result = vkGetPhysicalDeviceSurfacePresentModesKHR(
387 physicalDevice, surface, &modeCount, nullptr);
388 if (result != VK_SUCCESS || modeCount < 1) {
389 SLEAK_ERROR("Failed to retrieve present modes!");
390 return {};
391 }
392
393 details.presentModes.resize(modeCount);
394 vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface,
395 &modeCount,
396 details.presentModes.data());
397
398 return details;
399}
400
401/// Picks a UNORM surface format to avoid double sRGB encoding.
402VkSurfaceFormatKHR VulkanRenderer::ChooseFormat(
403 const std::vector<VkSurfaceFormatKHR>& formats) {
404 // Prefer UNORM so the GPU does NOT apply automatic sRGB gamma encoding
405 // on output. The game renders in sRGB/gamma space already (no linear
406 // pipeline), so using _SRGB would gamma-encode everything twice —
407 // producing a washed-out, overbright image. _UNORM writes values as-is,
408 // matching the behaviour of DX11/DX12 DXGI_FORMAT_*_UNORM swap chains.
409 for (auto& format : formats)
410 if (format.format == VK_FORMAT_B8G8R8A8_UNORM &&
411 format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
412 return format;
413
414 // Second preference: R8G8B8A8_UNORM
415 for (auto& format : formats)
416 if (format.format == VK_FORMAT_R8G8B8A8_UNORM &&
417 format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
418 return format;
419
420 return formats[0];
421}
422
423/// Picks FIFO when VSync is on, otherwise MAILBOX or IMMEDIATE.
424VkPresentModeKHR VulkanRenderer::ChoosePresentMode(
425 const std::vector<VkPresentModeKHR>& modes) {
426 if (m_vsync) {
427 // VSync ON: FIFO is guaranteed and provides VSync
428 return VK_PRESENT_MODE_FIFO_KHR;
429 }
430
431 // VSync OFF: prefer MAILBOX (no tearing, uncapped), then IMMEDIATE
432 for (auto& mode : modes)
433 if (mode == VK_PRESENT_MODE_MAILBOX_KHR)
434 return mode;
435 for (auto& mode : modes)
436 if (mode == VK_PRESENT_MODE_IMMEDIATE_KHR)
437 return mode;
438
439 return VK_PRESENT_MODE_FIFO_KHR;
440}
441
442/// Clamps the window size to the surface's supported extent.
443// Fixed: clamp height using height, not width
444VkExtent2D VulkanRenderer::ChooseExtend(const VkSurfaceCapabilitiesKHR& caps) {
445 if (caps.currentExtent.width != std::numeric_limits<uint32_t>::max())
446 return caps.currentExtent;
447
448 int width, height;
449 SDL_GetWindowSizeInPixels(sdlWindow->GetSDLWindow(), &width, &height);
450
451 VkExtent2D actualExtent = {static_cast<uint32_t>(width),
452 static_cast<uint32_t>(height)};
453
454 actualExtent.width =
455 std::clamp(actualExtent.width, caps.minImageExtent.width,
456 caps.maxImageExtent.width);
457
458 actualExtent.height =
459 std::clamp(actualExtent.height, caps.minImageExtent.height,
460 caps.maxImageExtent.height);
461
462 return actualExtent;
463}
464
465/// True when the surface now wants a different extent than the swapchain
466/// has. A failed query keeps the current swapchain.
467bool VulkanRenderer::SurfaceExtentChanged() {
468 VkSurfaceCapabilitiesKHR caps{};
469 if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface,
470 &caps) != VK_SUCCESS)
471 return false;
472 const VkExtent2D extent = ChooseExtend(caps);
473 return extent.width != scExtent.width || extent.height != scExtent.height;
474}
475}
476}
int width
int height
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_RETURN_ERR(...)
Definition Logger.hpp:25
#define SLEAK_INFO(...)
Definition Logger.hpp:20
Backend-facing rendering layer shared by the four graphics backends.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10