From 3bb747bfaeb47cdfe65df05ea2e4bc766d35783a Mon Sep 17 00:00:00 2001 From: Lillian Salehi Date: Sun, 6 Oct 2024 20:17:19 -0500 Subject: [PATCH] Swap Chain's setup rudimentarily, resizing the window is not available as of yet, because that would invalidate the swap chain, but now we have a target to render to. --- src/DeviceLibrary.cpp | 201 ++++++++++++++++++++++++++++++++++++++++-- src/DeviceLibrary.h | 2 + src/global.cpp | 1 - src/main.cpp | 2 + 4 files changed, 198 insertions(+), 8 deletions(-) diff --git a/src/DeviceLibrary.cpp b/src/DeviceLibrary.cpp index 422d726..ffb562a 100644 --- a/src/DeviceLibrary.cpp +++ b/src/DeviceLibrary.cpp @@ -1,11 +1,15 @@ #include "DeviceLibrary.h" +#include "global.h" +#include #include +#include #include #include #include #include -#include +#include +#include namespace DeviceControl { @@ -15,6 +19,11 @@ namespace DeviceControl { VkPhysicalDeviceProperties deviceProperties; VkPhysicalDeviceFeatures deviceFeatures; + VkSwapchainKHR swapChain; + std::vector swapChainImages; + VkFormat swapChainImageFormat; + VkExtent2D swapChainExtent; + VkQueue graphicsQueue; VkQueue presentQueue; @@ -28,7 +37,14 @@ namespace DeviceControl { return graphicsFamily.has_value() && presentFamily.has_value(); } }; - + struct SwapChainSupportDetails { + VkSurfaceCapabilitiesKHR capabilities; + std::vector formats; + std::vector presentModes; + }; + const std::vector deviceExtensions = { + VK_KHR_SWAPCHAIN_EXTENSION_NAME + }; QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device) { // First we feed in a integer we want to use to hold the number of queued items, that fills it, then we create that amount of default constructed *VkQueueFamilyProperties* structs. // These store the flags, the amount of queued items in the family, and timestamp data. Queue families are simply group collections of tasks we want to get done. @@ -63,6 +79,49 @@ namespace DeviceControl { return indices; } + bool checkDeviceExtensionSupport(VkPhysicalDevice device) { + uint32_t extensionCount; + vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr); + + std::vector availableExtensions(extensionCount); + vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data()); + + std::set requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); + + for(const auto& extension : availableExtensions) { + requiredExtensions.erase(extension.extensionName); + } + + return requiredExtensions.empty(); + } + SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device) { + + // Swap chains are weird ngl, it's another one of those Vulkan platform agnosticity. The swapchain is basically a wrapper for GDI+, DXGI, X11, Wayland, etc. + // It lets us use the swap chain rather than create a different framebuffer handler for every targeted platform. + // Swap chains handle the ownership of buffers before sending them to the presentation engine. + // (still no fucking clue how it works though) + SwapChainSupportDetails details; + + vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); + + uint32_t formatCount; + vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); + + if(formatCount != 0) { + details.formats.resize(formatCount); + vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data()); + } + + uint32_t presentModeCount; + vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data()); + + if(presentModeCount != 0) { + details.presentModes.resize(presentModeCount); + vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data()); + } + + return details; + } bool isDeviceSuitable(VkPhysicalDevice device) { // These two are simple, create a structure to hold the apiVersion, driverVersion, vendorID, deviceID and type, name, and a few other settings. // Then populate it by passing in the device and the structure reference. @@ -73,10 +132,68 @@ namespace DeviceControl { // We need to find a device that supports graphical operations, or else we cant do much with it! This function just runs over all the queueFamilies and sees if there // is a queue family with the VK_QUEUE_GRAPHICS_BIT flipped! QueueFamilyIndices indices = findQueueFamilies(device); - - return deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU && deviceFeatures.multiViewport && deviceFeatures.geometryShader && indices.isComplete(); - } + bool extensionSupported = checkDeviceExtensionSupport(device); + bool swapChainAdequate = false; + if(extensionSupported) { + SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device); + swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty(); + } + + return deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU + && deviceFeatures.multiViewport + && deviceFeatures.geometryShader + && indices.isComplete() + && extensionSupported + && swapChainAdequate; + } +// -------------------------------------- Swap Chain Settings -----------------------------------------// + VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector& availableFormats) { + // One of three settings we can set, Surface Format controls the color space and format. + + for (const auto& availableFormat : availableFormats) { + if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { + // sRGB & 32bit BGRA + return availableFormat; + } + } + return availableFormats[0]; + } + VkPresentModeKHR chooseSwapPresentMode(const std::vector& availablePresentModes) { + // The second of the three settings, arguably the most important, the presentation mode! This dictates how images are displayed. + // MAILBOX is basically equivalent to triple buffering, it avoids screen tearing with fairly low latency, + // However, it is not always supported, so in the case that it isn't, currently we will default to FIFO, + // This is most similarly to standard V-Sync. + for(const auto& availablePresentMode : availablePresentModes) { + if(availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { + return availablePresentMode; + } + } + return VK_PRESENT_MODE_FIFO_KHR; + } + VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window) { + // Swap Extent is just a fancy way of saying the resolution of the swap images to display. + // This is almost always going to equal the resolution of the window in pixels. + + // The max int32 value tells us that the window manager lets us change the windth and height to what we wish! + if (capabilities.currentExtent.width != std::numeric_limits::max()) { + return capabilities.currentExtent; + } else { + int width, height; + glfwGetFramebufferSize(window, &width, &height); + + VkExtent2D actualExtent = { + static_cast(width), + static_cast(height) + }; + // Clamp the image size to the minimum extent values specified by vulkan for our window manager. + actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width); + actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height); + + return actualExtent; + } + } +// --------------------------------------- External Functions -----------------------------------------// void DeviceLibrary::pickPhysicalDevice(VkInstance& instance) { uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); @@ -135,8 +252,8 @@ namespace DeviceControl { createDeviceInfo.pQueueCreateInfos = queueCreateInfos.data(); createDeviceInfo.queueCreateInfoCount = static_cast(queueCreateInfos.size()); createDeviceInfo.pEnabledFeatures = &deviceFeatures; - createDeviceInfo.enabledExtensionCount = 0; - + createDeviceInfo.enabledExtensionCount = static_cast(deviceExtensions.size()); + createDeviceInfo.ppEnabledExtensionNames = deviceExtensions.data(); if(Global::enableValidationLayers) { createDeviceInfo.enabledLayerCount = static_cast(Global::validationLayers.size()); @@ -152,4 +269,74 @@ namespace DeviceControl { vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue); vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue); } + void DeviceLibrary::createSwapChain(GLFWwindow* window, VkDevice& device) { + SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice); + + VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); + VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); + VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities, window); + + // Number of images to hold in the swap chain, 1 over the minimum guarantees we won't have to wait on the driver to complete + // internal operations before acquiring another image. Absolutely a TODO to determine the best amount to queue. + uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; + // Make sure not to queue more than the max! 0 indicates that there is no maximum. + if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) { + imageCount = swapChainSupport.capabilities.maxImageCount; + } + + VkSwapchainCreateInfoKHR createSwapChainInfo{}; + createSwapChainInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; + createSwapChainInfo.surface = surface; + createSwapChainInfo.minImageCount = imageCount; + createSwapChainInfo.imageFormat = surfaceFormat.format; + createSwapChainInfo.imageColorSpace = surfaceFormat.colorSpace; + createSwapChainInfo.imageExtent = extent; + // Image array layers is always 1 unless we are developing for VR (Spoiler: we are, we will use a build flag.) + // Image Usage specifies what operations you use the images for, COLOR_ATTACH means we render directly to them, + // if you wanted to render to separate images for things like post processing, you can use TRANSFER_DST and use a + // memory operation to transfer the image to a swap chain, this is also a TODO item eventually. + createSwapChainInfo.imageArrayLayers = 1; + createSwapChainInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + + // This handles swap chain images across multiple queue families, ie, if the graphics queue family is different from the present queue + QueueFamilyIndices indices = findQueueFamilies(physicalDevice); + uint32_t queueFamilyIndices[] = {indices.graphicsFamily.value(), indices.presentFamily.value()}; + // Usage across multiple queue families without explicit transfer of ownership if they are different queue families. + // Otherwise, no sharing without explicit handoffs, faster, but not easily supported with multiple families. + // Presentation and Graphics families are usually merged on most hardware. + if (indices.graphicsFamily != indices.presentFamily) { + createSwapChainInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; + createSwapChainInfo.queueFamilyIndexCount = 2; + createSwapChainInfo.pQueueFamilyIndices = queueFamilyIndices; + } else { + createSwapChainInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; + } + // Transformation of image support. + createSwapChainInfo.preTransform = swapChainSupport.capabilities.currentTransform; + // Do NOT blend with other windows on the system. + createSwapChainInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + createSwapChainInfo.presentMode = presentMode; + // This is interesting, clip pixels that are obscured for performance, but that means you wont be able to reaf them reliably.. + // I am curious if this would affect screen-space rendering techniques, may be something to note. + createSwapChainInfo.clipped = VK_TRUE; + // This is something that needs to be implemented later, operations like resizing the window invalidate the swap chain and + // require you to recreate it and reference the old one specified here, will revisit in a few days. + createSwapChainInfo.oldSwapchain = VK_NULL_HANDLE; + + if(vkCreateSwapchainKHR(device, &createSwapChainInfo, nullptr, &swapChain) != VK_SUCCESS) { + throw std::runtime_error("Failed to create the swap chain!!"); + } + std::cout << "Swap Chain created successfully\n" << std::endl; + + vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr); + swapChainImages.resize(imageCount); + vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data()); + + swapChainImageFormat = surfaceFormat.format; + swapChainExtent = extent; + } + void DeviceLibrary::destroySwapChain(VkDevice& device) { + vkDestroySwapchainKHR(device, swapChain, nullptr); + std::cout << "Destroyed Swap Chain safely\n" << std::endl; + } } diff --git a/src/DeviceLibrary.h b/src/DeviceLibrary.h index 2a0f801..898e79c 100644 --- a/src/DeviceLibrary.h +++ b/src/DeviceLibrary.h @@ -8,6 +8,8 @@ namespace DeviceControl { void createLogicalDevice(VkDevice& device); void createSurface(VkInstance& instance, GLFWwindow* window); void destroySurface(VkInstance& instance); + void createSwapChain(GLFWwindow* window, VkDevice& device); + void destroySwapChain(VkDevice& device); }; } diff --git a/src/global.cpp b/src/global.cpp index d9fe9a2..107495b 100644 --- a/src/global.cpp +++ b/src/global.cpp @@ -4,7 +4,6 @@ namespace Global { const std::vector validationLayers = { "VK_LAYER_KHRONOS_validation" }; - #ifdef DEBUG const bool enableValidationLayers = true; #else diff --git a/src/main.cpp b/src/main.cpp index ca3d572..258be34 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -46,6 +46,7 @@ private: deviceLibs.createSurface(instance, window); deviceLibs.pickPhysicalDevice(instance); deviceLibs.createLogicalDevice(device); + deviceLibs.createSwapChain(window, device); } void createInstance() { @@ -75,6 +76,7 @@ private: } void cleanup() { // Similar to the last handoff, destroy the debug util in a safe manner in the library! + deviceLibs.destroySwapChain(device); vkDestroyDevice(device, nullptr); if(Global::enableValidationLayers) { debugController.DestroyDebugUtilsMessengerEXT(instance, nullptr);