Added resizing + swap chain recreation

This commit is contained in:
Ano-sys
2025-04-03 23:00:32 +02:00
parent 811b5e0ae6
commit 5944a08abc
3 changed files with 822 additions and 765 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
#define DEBUG #define DEBUG 1
#include <iostream> #include <iostream>
#include "vulkan/vulkan_app.hpp" #include "vulkan/vulkan_app.hpp"
+164 -111
View File
@@ -5,43 +5,52 @@
#include "vulkan_app.hpp" #include "vulkan_app.hpp"
namespace vapp{ namespace vapp{
const std::vector<const char*> validationLayers = {
const std::vector<const char*> validationLayers = {
"VK_LAYER_KHRONOS_validation" "VK_LAYER_KHRONOS_validation"
}; };
const std::vector<const char*> deviceExtensions = { const std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_SWAPCHAIN_EXTENSION_NAME,
}; };
static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, void *pUserData){ static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
void *pUserData){
std::cerr << "Validation Layer: " << pCallbackData->pMessage << std::endl; std::cerr << "Validation Layer: " << pCallbackData->pMessage << std::endl;
return VK_FALSE; return VK_FALSE;
} }
VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDebugUtilsMessengerEXT *pDebugMessenger){ VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo,
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT"); const VkAllocationCallbacks *pAllocator,
VkDebugUtilsMessengerEXT *pDebugMessenger){
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(
instance, "vkCreateDebugUtilsMessengerEXT");
if(func == nullptr) return VK_ERROR_EXTENSION_NOT_PRESENT; if(func == nullptr) return VK_ERROR_EXTENSION_NOT_PRESENT;
if(func == nullptr) return VK_ERROR_EXTENSION_NOT_PRESENT; if(func == nullptr) return VK_ERROR_EXTENSION_NOT_PRESENT;
return func(instance, pCreateInfo, pAllocator, pDebugMessenger); return func(instance, pCreateInfo, pAllocator, pDebugMessenger);
} }
void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks *pAllocator){ void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger,
if(auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT"); func != nullptr){ const VkAllocationCallbacks *pAllocator){
if(auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(
instance, "vkDestroyDebugUtilsMessengerEXT"); func != nullptr){
func(instance, debugMessenger, pAllocator); func(instance, debugMessenger, pAllocator);
} }
} }
void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT &createInfo){ void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo){
createInfo = {}; createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
// set which type of messages the callback is notified about // set which type of messages the callback is notified about
createInfo.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; createInfo.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;
createInfo.pfnUserCallback = debugCallback; createInfo.pfnUserCallback = debugCallback;
} }
static std::vector<char> readFile(const std::string &filename){ static std::vector<char> readFile(const std::string& filename){
std::ifstream file(filename, std::ios::ate | std::ios::binary); std::ifstream file(filename, std::ios::ate | std::ios::binary);
if(!file.is_open()){ if(!file.is_open()){
@@ -56,16 +65,16 @@ static std::vector<char> readFile(const std::string &filename){
file.close(); file.close();
return buffer; return buffer;
} }
bool Vulkan::checkValidationLayerSupport(){ bool Vulkan::checkValidationLayerSupport(){
uint32_t layerCount; uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr); vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount); std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
for(const char* layerName : validationLayers){ for(const char *layerName : validationLayers){
bool layerFound = false; bool layerFound = false;
for(const auto& layerProperties : availableLayers){ for(const auto& layerProperties : availableLayers){
@@ -78,9 +87,9 @@ bool Vulkan::checkValidationLayerSupport(){
} }
return true; return true;
} }
std::vector<const char*> Vulkan::getRequiredExtensions(){ std::vector<const char*> Vulkan::getRequiredExtensions(){
uint32_t glfwExtensionCount = 0; uint32_t glfwExtensionCount = 0;
const char **glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); const char **glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
@@ -89,9 +98,9 @@ std::vector<const char*> Vulkan::getRequiredExtensions(){
if(enableValidationLayers) extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); if(enableValidationLayers) extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
return extensions; return extensions;
} }
void Vulkan::createInstance(){ void Vulkan::createInstance(){
if(enableValidationLayers && !checkValidationLayerSupport()){ if(enableValidationLayers && !checkValidationLayerSupport()){
throw std::runtime_error("Func: createInstance\nError: Validation Layers requested, but not available!\n"); throw std::runtime_error("Func: createInstance\nError: Validation Layers requested, but not available!\n");
} }
@@ -139,9 +148,9 @@ void Vulkan::createInstance(){
std::cout << '\t' << extension.extensionName << '\n'; std::cout << '\t' << extension.extensionName << '\n';
} }
} }
} }
void Vulkan::setupDebugMessenger(){ void Vulkan::setupDebugMessenger(){
if(!enableValidationLayers) return; if(!enableValidationLayers) return;
VkDebugUtilsMessengerCreateInfoEXT createInfo{}; VkDebugUtilsMessengerCreateInfoEXT createInfo{};
populateDebugMessengerCreateInfo(createInfo); populateDebugMessengerCreateInfo(createInfo);
@@ -149,9 +158,9 @@ void Vulkan::setupDebugMessenger(){
if(CreateDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS){ if(CreateDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS){
throw std::runtime_error("Func: setupDebugMessenger\nError: Failed to set up Debug Messenger!\n"); throw std::runtime_error("Func: setupDebugMessenger\nError: Failed to set up Debug Messenger!\n");
} }
} }
void Vulkan::pickPhysicalDevice(){ void Vulkan::pickPhysicalDevice(){
uint32_t deviceCount = 0; uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if(deviceCount == 0){ if(deviceCount == 0){
@@ -171,13 +180,13 @@ void Vulkan::pickPhysicalDevice(){
if(physicalDevice == VK_NULL_HANDLE){ if(physicalDevice == VK_NULL_HANDLE){
throw std::runtime_error("Func: pickPhysicalDevice\nError: Failed to find suitable GPU!\n"); throw std::runtime_error("Func: pickPhysicalDevice\nError: Failed to find suitable GPU!\n");
} }
} }
void Vulkan::createLogicalDevice(){ void Vulkan::createLogicalDevice(){
QueueFamilyIndices indices = findQueueFamilies(physicalDevice); QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() }; std::set<uint32_t> uniqueQueueFamilies = {indices.graphicsFamily.value(), indices.presentFamily.value()};
float queuePriority = 1.0f; float queuePriority = 1.0f;
for(uint32_t queueFamily : uniqueQueueFamilies){ for(uint32_t queueFamily : uniqueQueueFamilies){
@@ -216,9 +225,9 @@ void Vulkan::createLogicalDevice(){
vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue); vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue); vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
} }
QueueFamilyIndices Vulkan::findQueueFamilies(VkPhysicalDevice device){ QueueFamilyIndices Vulkan::findQueueFamilies(VkPhysicalDevice device){
QueueFamilyIndices indices; QueueFamilyIndices indices;
uint32_t queueFamilyCount = 0; uint32_t queueFamilyCount = 0;
@@ -238,9 +247,9 @@ QueueFamilyIndices Vulkan::findQueueFamilies(VkPhysicalDevice device){
} }
return indices; return indices;
} }
bool Vulkan::checkDeviceExtensionSupport(VkPhysicalDevice device){ bool Vulkan::checkDeviceExtensionSupport(VkPhysicalDevice device){
uint32_t extensionCount; uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr); vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
@@ -254,9 +263,9 @@ bool Vulkan::checkDeviceExtensionSupport(VkPhysicalDevice device){
} }
return requiredExtensions.empty(); return requiredExtensions.empty();
} }
bool Vulkan::isDeviceSuitable(VkPhysicalDevice device){ bool Vulkan::isDeviceSuitable(VkPhysicalDevice device){
/* /*
VkPhysicalDeviceProperties deviceProperties; VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(device, &deviceProperties); vkGetPhysicalDeviceProperties(device, &deviceProperties);
@@ -274,15 +283,15 @@ bool Vulkan::isDeviceSuitable(VkPhysicalDevice device){
swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty(); swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
} }
return indices.isComplete() && extensionSupported && swapChainAdequate; return indices.isComplete() && extensionSupported && swapChainAdequate;
} }
void Vulkan::createSurface(){ void Vulkan::createSurface(){
if(glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS){ if(glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS){
throw std::runtime_error("Func: createSurface\nError: Failed to create Window Surface!\n"); throw std::runtime_error("Func: createSurface\nError: Failed to create Window Surface!\n");
} }
} }
SwapChainSupportDetails Vulkan::querySwapChainSupport(VkPhysicalDevice device){ SwapChainSupportDetails Vulkan::querySwapChainSupport(VkPhysicalDevice device){
SwapChainSupportDetails details; SwapChainSupportDetails details;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
@@ -304,29 +313,32 @@ SwapChainSupportDetails Vulkan::querySwapChainSupport(VkPhysicalDevice device){
} }
return details; return details;
} }
VkSurfaceFormatKHR Vulkan::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats){ VkSurfaceFormatKHR Vulkan::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats){
for(const VkSurfaceFormatKHR availableFormat : availableFormats){ for(const VkSurfaceFormatKHR availableFormat : availableFormats){
if(availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR){ if(availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace ==
VK_COLOR_SPACE_SRGB_NONLINEAR_KHR){
return availableFormat; return availableFormat;
} }
} }
return availableFormats[0]; return availableFormats[0];
} }
VkPresentModeKHR Vulkan::chooseSwapPresentMode(const std::vector<VkPresentModeKHR> availablePresentModes){ VkPresentModeKHR Vulkan::chooseSwapPresentMode(const std::vector<VkPresentModeKHR> availablePresentModes){
for(const VkPresentModeKHR availablePresentMode : availablePresentModes){ for(const VkPresentModeKHR availablePresentMode : availablePresentModes){
if(availablePresentMode == WISHED_PRESENT_MODE){ if(availablePresentMode == WISHED_PRESENT_MODE){
return availablePresentMode; return availablePresentMode;
} }
} }
return VK_PRESENT_MODE_FIFO_KHR; // always available return VK_PRESENT_MODE_FIFO_KHR; // always available
} }
VkExtent2D Vulkan::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities){ VkExtent2D Vulkan::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities){
if(capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()){ return capabilities.currentExtent; } if(capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()){
return capabilities.currentExtent;
}
int width, height; int width, height;
glfwGetFramebufferSize(window, &width, &height); glfwGetFramebufferSize(window, &width, &height);
@@ -336,13 +348,15 @@ VkExtent2D Vulkan::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities
static_cast<uint32_t>(height) static_cast<uint32_t>(height)
}; };
actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width); actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width,
actualExtent.width = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height); capabilities.maxImageExtent.width);
actualExtent.width = std::clamp(actualExtent.height, capabilities.minImageExtent.height,
capabilities.maxImageExtent.height);
return actualExtent; return actualExtent;
} }
void Vulkan::createSwapChain(){ void Vulkan::createSwapChain(){
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice); SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
@@ -366,7 +380,7 @@ void Vulkan::createSwapChain(){
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
QueueFamilyIndices indices = findQueueFamilies(physicalDevice); QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
uint32_t queueFamiliyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; uint32_t queueFamiliyIndices[] = {indices.graphicsFamily.value(), indices.presentFamily.value()};
if(indices.graphicsFamily != indices.presentFamily){ if(indices.graphicsFamily != indices.presentFamily){
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
@@ -395,9 +409,9 @@ void Vulkan::createSwapChain(){
swapChainImageFormat = surfaceFormat.format; swapChainImageFormat = surfaceFormat.format;
swapChainExtent = extent; swapChainExtent = extent;
} }
void Vulkan::createImageViews(){ void Vulkan::createImageViews(){
swapChainImageViews.resize(swapChainImages.size()); swapChainImageViews.resize(swapChainImages.size());
for(size_t i = 0; i < swapChainImages.size(); i++){ for(size_t i = 0; i < swapChainImages.size(); i++){
@@ -423,9 +437,9 @@ void Vulkan::createImageViews(){
throw std::runtime_error("Func: createImageViews\nError: Failed to create Image Views!\n"); throw std::runtime_error("Func: createImageViews\nError: Failed to create Image Views!\n");
} }
} }
} }
void Vulkan::createGraphicsPipeline(){ void Vulkan::createGraphicsPipeline(){
// TODO: find solution for file location // TODO: find solution for file location
std::vector<char> vertShaderCode; std::vector<char> vertShaderCode;
std::vector<char> fragShaderCode; std::vector<char> fragShaderCode;
@@ -454,7 +468,7 @@ void Vulkan::createGraphicsPipeline(){
fragShaderStageInfo.module = fragShaderModule; fragShaderStageInfo.module = fragShaderModule;
fragShaderStageInfo.pName = "main"; fragShaderStageInfo.pName = "main";
VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo }; VkPipelineShaderStageCreateInfo shaderStages[] = {vertShaderStageInfo, fragShaderStageInfo};
// Dynamics are done to not reinitialize every pipeline for example resizes // Dynamics are done to not reinitialize every pipeline for example resizes
std::vector<VkDynamicState> dynamicStates = { std::vector<VkDynamicState> dynamicStates = {
@@ -563,15 +577,16 @@ void Vulkan::createGraphicsPipeline(){
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
*/ */
if(vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS){ if(vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline) !=
VK_SUCCESS){
throw std::runtime_error("Func; createGraphicsPipeline\nError: Failed to create graphics pipeline!\n"); throw std::runtime_error("Func; createGraphicsPipeline\nError: Failed to create graphics pipeline!\n");
} }
vkDestroyShaderModule(device, vertShaderModule, nullptr); vkDestroyShaderModule(device, vertShaderModule, nullptr);
vkDestroyShaderModule(device, fragShaderModule, nullptr); vkDestroyShaderModule(device, fragShaderModule, nullptr);
} }
VkShaderModule Vulkan::createShaderModule(const std::vector<char> &code){ VkShaderModule Vulkan::createShaderModule(const std::vector<char>& code){
VkShaderModuleCreateInfo createInfo{}; VkShaderModuleCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
createInfo.codeSize = code.size(); createInfo.codeSize = code.size();
@@ -583,9 +598,9 @@ VkShaderModule Vulkan::createShaderModule(const std::vector<char> &code){
} }
return shaderModule; return shaderModule;
} }
void Vulkan::createRenderPass(){ void Vulkan::createRenderPass(){
VkAttachmentDescription colorAttachment{}; VkAttachmentDescription colorAttachment{};
colorAttachment.format = swapChainImageFormat; colorAttachment.format = swapChainImageFormat;
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
@@ -625,13 +640,13 @@ void Vulkan::createRenderPass(){
if(vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS){ if(vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS){
throw std::runtime_error("Func: createRenderPass\nError: Failed to create render pass!\n"); throw std::runtime_error("Func: createRenderPass\nError: Failed to create render pass!\n");
} }
} }
void Vulkan::createFrameBuffers(){ void Vulkan::createFrameBuffers(){
swapChainFramebuffers.resize(swapChainImageViews.size()); swapChainFramebuffers.resize(swapChainImageViews.size());
for(size_t i = 0; i < swapChainImageViews.size(); i++){ for(size_t i = 0; i < swapChainImageViews.size(); i++){
VkImageView attachements[] = { swapChainImageViews[i] }; VkImageView attachements[] = {swapChainImageViews[i]};
VkFramebufferCreateInfo framebufferInfo{}; VkFramebufferCreateInfo framebufferInfo{};
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
@@ -646,9 +661,9 @@ void Vulkan::createFrameBuffers(){
throw std::runtime_error("Func: createFrameBuffers\nError: Failed to create Framebuffer!\n"); throw std::runtime_error("Func: createFrameBuffers\nError: Failed to create Framebuffer!\n");
} }
} }
} }
void Vulkan::createCommandPool(){ void Vulkan::createCommandPool(){
QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice); QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice);
VkCommandPoolCreateInfo poolInfo{}; VkCommandPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
@@ -658,9 +673,9 @@ void Vulkan::createCommandPool(){
if(vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS){ if(vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS){
throw std::runtime_error("Func: createCommandPool\nError: Failed to create Command Pool!\n"); throw std::runtime_error("Func: createCommandPool\nError: Failed to create Command Pool!\n");
} }
} }
void Vulkan::createCommandBuffers(){ void Vulkan::createCommandBuffers(){
commandBuffers.resize(MAX_FRAMES_IN_FLIGHT); commandBuffers.resize(MAX_FRAMES_IN_FLIGHT);
VkCommandBufferAllocateInfo allocInfo{}; VkCommandBufferAllocateInfo allocInfo{};
@@ -672,9 +687,9 @@ void Vulkan::createCommandBuffers(){
if(vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS){ if(vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS){
throw std::runtime_error("Func: createCommandBuffer\nError: Failed to allocate Command Buffers!\n"); throw std::runtime_error("Func: createCommandBuffer\nError: Failed to allocate Command Buffers!\n");
} }
} }
void Vulkan::recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIndex){ void Vulkan::recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIndex){
VkCommandBufferBeginInfo beginInfo{}; VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
@@ -686,7 +701,7 @@ void Vulkan::recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIn
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = renderPass; renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = swapChainFramebuffers[imageIndex]; renderPassInfo.framebuffer = swapChainFramebuffers[imageIndex];
renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.offset = {0, 0};
renderPassInfo.renderArea.extent = swapChainExtent; renderPassInfo.renderArea.extent = swapChainExtent;
VkClearValue clearColor = {{{0.01f, 0.01f, 0.01f, 1.0f}}}; // Background color after clear (Black 100%) VkClearValue clearColor = {{{0.01f, 0.01f, 0.01f, 1.0f}}}; // Background color after clear (Black 100%)
@@ -706,7 +721,7 @@ void Vulkan::recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIn
vkCmdSetViewport(commandBuffer, 0, 1, &viewport); vkCmdSetViewport(commandBuffer, 0, 1, &viewport);
VkRect2D scissor{}; VkRect2D scissor{};
scissor.offset = { 0, 0 }; scissor.offset = {0, 0};
scissor.extent = swapChainExtent; scissor.extent = swapChainExtent;
vkCmdSetScissor(commandBuffer, 0, 1, &scissor); vkCmdSetScissor(commandBuffer, 0, 1, &scissor);
@@ -716,9 +731,9 @@ void Vulkan::recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIn
if(vkEndCommandBuffer(commandBuffer) != VK_SUCCESS){ if(vkEndCommandBuffer(commandBuffer) != VK_SUCCESS){
throw std::runtime_error("Func: recordCommandBuffer\nError: Failed to record command buffer!\n"); throw std::runtime_error("Func: recordCommandBuffer\nError: Failed to record command buffer!\n");
} }
} }
void Vulkan::createSyncObjects(){ void Vulkan::createSyncObjects(){
imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT); imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT); renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
inFlightFences.resize(MAX_FRAMES_IN_FLIGHT); inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
@@ -737,14 +752,17 @@ void Vulkan::createSyncObjects(){
throw std::runtime_error("Func: createSyncObjects\nError: Failed to create semaphores!\n"); throw std::runtime_error("Func: createSyncObjects\nError: Failed to create semaphores!\n");
} }
} }
} }
void Vulkan::drawFrame(){ void Vulkan::drawFrame(){
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]); vkResetFences(device, 1, &inFlightFences[currentFrame]);
uint32_t imageIndex; uint32_t imageIndex;
vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
// INFO: is this right here?
// vkResetFences(device, 1, &inFlightFences[currentFrame]);
vkResetCommandBuffer(commandBuffers[currentFrame], 0); vkResetCommandBuffer(commandBuffers[currentFrame], 0);
recordCommandBuffer(commandBuffers[currentFrame], imageIndex); recordCommandBuffer(commandBuffers[currentFrame], imageIndex);
@@ -752,8 +770,8 @@ void Vulkan::drawFrame(){
VkSubmitInfo submitInfo{}; VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore waitSemaphores[] = { imageAvailableSemaphores[currentFrame] }; VkSemaphore waitSemaphores[] = {imageAvailableSemaphores[currentFrame]};
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; VkPipelineStageFlags waitStages[] = {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
submitInfo.waitSemaphoreCount = 1; submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores; submitInfo.pWaitSemaphores = waitSemaphores;
@@ -761,7 +779,7 @@ void Vulkan::drawFrame(){
submitInfo.commandBufferCount = 1; submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffers[currentFrame]; submitInfo.pCommandBuffers = &commandBuffers[currentFrame];
VkSemaphore signalSemaphore[] = { renderFinishedSemaphores[currentFrame] }; VkSemaphore signalSemaphore[] = {renderFinishedSemaphores[currentFrame]};
submitInfo.signalSemaphoreCount = 1; submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphore; submitInfo.pSignalSemaphores = signalSemaphore;
@@ -774,24 +792,65 @@ void Vulkan::drawFrame(){
presentInfo.waitSemaphoreCount = 1; presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = signalSemaphore; presentInfo.pWaitSemaphores = signalSemaphore;
VkSwapchainKHR swapChains[] = { swapChain }; VkSwapchainKHR swapChains[] = {swapChain};
presentInfo.swapchainCount = 1; presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains; presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex; presentInfo.pImageIndices = &imageIndex;
vkQueuePresentKHR(presentQueue, &presentInfo); vkQueuePresentKHR(presentQueue, &presentInfo);
currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT; if(result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized){
} framebufferResized = false;
recreateSwapChain();
}
else if(result != VK_SUCCESS){
throw std::runtime_error("Func: drawFrame\nError: Failed to acquire swap chain image!\n");
}
void Vulkan::initWindow(const char* windowName){ currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
}
void Vulkan::cleanupSwapChain(){
for(const auto & swapChainFramebuffer : swapChainFramebuffers)
{ vkDestroyFramebuffer(device, swapChainFramebuffer, nullptr); }
for(const auto & swapChainImageView : swapChainImageViews)
{ vkDestroyImageView(device, swapChainImageView, nullptr); }
vkDestroySwapchainKHR(device, swapChain, nullptr);
}
void Vulkan::recreateSwapChain(){
int width = 0, height = 0;
glfwGetFramebufferSize(window, &width, &height);
while(width == 0 || height == 0){
glfwGetFramebufferSize(window, &width, &height);
glfwPollEvents();
}
vkDeviceWaitIdle(device);
cleanupSwapChain();
createSwapChain();
createImageViews();
createFrameBuffers();
}
static void framebufferResizeCallback(GLFWwindow *window, int width, int height){
auto app = reinterpret_cast<Vulkan*>(glfwGetWindowUserPointer(window));
app->framebufferResized = true;
}
void Vulkan::initWindow(const char *windowName){
glfwInit(); glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); // tell glfw to not use opengl glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); // tell glfw to not use opengl
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); // disable window resize glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // disable window resize
this->window = glfwCreateWindow(static_cast<int>(_width), static_cast<int>(_height), windowName, nullptr, nullptr); this->window = glfwCreateWindow(static_cast<int>(_width), static_cast<int>(_height), windowName, nullptr, nullptr);
} glfwSetWindowUserPointer(window, this);
glfwSetFramebufferSizeCallback(window, framebufferResizeCallback);
}
void Vulkan::initVulkan(){ void Vulkan::initVulkan(){
createInstance(); createInstance();
setupDebugMessenger(); setupDebugMessenger();
createSurface(); createSurface();
@@ -805,19 +864,26 @@ void Vulkan::initVulkan(){
createCommandPool(); createCommandPool();
createCommandBuffers(); createCommandBuffers();
createSyncObjects(); createSyncObjects();
} }
void Vulkan::mainLoop(){ void Vulkan::mainLoop(){
while(!glfwWindowShouldClose(this->window)){ while(!glfwWindowShouldClose(this->window)){
// glfwSwapBuffers(window); // glfwSwapBuffers(window);
glfwPollEvents(); glfwPollEvents();
drawFrame(); drawFrame();
} }
vkDeviceWaitIdle(device); vkDeviceWaitIdle(device);
} }
void Vulkan::cleanup(){ void Vulkan::cleanup(){
// Vulkan // Vulkan
cleanupSwapChain();
vkDestroyPipeline(device, graphicsPipeline, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyRenderPass(device, renderPass, nullptr);
for(size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++){ for(size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++){
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr); vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr); vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
@@ -826,19 +892,6 @@ void Vulkan::cleanup(){
vkDestroyCommandPool(device, commandPool, nullptr); vkDestroyCommandPool(device, commandPool, nullptr);
for(VkFramebuffer framebuffer : swapChainFramebuffers){
vkDestroyFramebuffer(device, framebuffer, nullptr);
}
vkDestroyPipeline(device, graphicsPipeline, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyRenderPass(device, renderPass, nullptr);
for(VkImageView imageView : swapChainImageViews){
vkDestroyImageView(device, imageView, nullptr);
}
vkDestroySwapchainKHR(device, swapChain, nullptr);
vkDestroyDevice(device, nullptr); vkDestroyDevice(device, nullptr);
if(enableValidationLayers){ if(enableValidationLayers){
@@ -853,9 +906,9 @@ void Vulkan::cleanup(){
// GLFW // GLFW
glfwDestroyWindow(this->window); glfwDestroyWindow(this->window);
glfwTerminate(); glfwTerminate();
} }
void Vulkan::run(const char* windowName, const uint32_t width, const uint32_t height){ void Vulkan::run(const char *windowName, const uint32_t width, const uint32_t height){
this->_width = width; this->_width = width;
this->_height = height; this->_height = height;
@@ -863,5 +916,5 @@ void Vulkan::run(const char* windowName, const uint32_t width, const uint32_t he
initVulkan(); initVulkan();
mainLoop(); mainLoop();
cleanup(); cleanup();
} }
} }
+4
View File
@@ -109,6 +109,8 @@ private:
void recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIndex); void recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIndex);
void createSyncObjects(); void createSyncObjects();
void drawFrame(); void drawFrame();
void cleanupSwapChain();
void recreateSwapChain();
void initWindow(const char* windowName); void initWindow(const char* windowName);
void initVulkan(); void initVulkan();
void mainLoop(); void mainLoop();
@@ -121,6 +123,8 @@ public:
const bool enableValidationLayers = false; const bool enableValidationLayers = false;
#endif #endif
bool framebufferResized = false;
void run(const char* windowName, const uint32_t width = 800, const uint32_t height = 600); void run(const char* windowName, const uint32_t width = 800, const uint32_t height = 600);
}; };
} // vapp } // vapp