I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
I have reviewed your code and found a potential issue in the BeginFrame method when waiting for fences. You are using currentFrame instead of imageIndex when waiting for fences to complete. Here's the updated code in BeginFrame:
void Renderer::BeginFrame()
{
// Wait for any previous work on this swapchain image to complete
vkWaitForFences(device, 1, &inFlightFences[imageIndex], VK_TRUE, UINT64_MAX); // use imageIndex instead of currentFrame
vkResetFences(device, 1, &inFlightFences[imageIndex]); // use imageIndex instead of currentFrame
// Acquire an image from the swapchain, then begin recording commands for the current frame.
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
...
}
I also noticed that you have hardcoded a value of 2 when calculating currentCmdBufferIndex. Although this works for your particular case where kMaxFramesInFlight = 2, it's better to use a general approach like this:
I am now getting a "vector subscript out of range" error
Assistant
Based on the information given, I suspect the issue is in the Renderer::EndFrame method when you set the currentFrame. Since the code is incrementing currentFrame following a modulo operation, it might go out of bounds. Here is the updated code for the Renderer::EndFrame method:
With this change, you should queue the commands submission with respect to the imageIndex instead of currentFrame. After implementing these modifications, the "vector subscript out of range" error should no longer occur.
User
It seems this did not fix the issue
Assistant
Apologies for the confusion. I took another look at your code and realized that I misunderstood the purpose of currentFrame; it should indeed be used with fences. I suggest changing the layer of the fence synchronization.
Here's the updated code for Renderer::BeginFrame:
void Renderer::BeginFrame()
{
// Wait for any previous work on this current frame to complete
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// Acquire an image from the swapchain, then begin recording commands for the current frame.
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
...
}
User
It seems the code has now been reverted to it's original state and the original error still persists.
Assistant
I apologize for the confusion. I reviewed your code again and found that the current synchronization logic might not work properly when there's a mismatch between the number of images in the swapchain and the number of in-flight frames. To avoid the "vector subscript out of range" error and still get proper synchronization, here's another approach:
Initialize the currentCmdBufferIndex to 0:
uint32_t currentCmdBufferIndex = 0;
Resize the commandBuffers vector to match the number of swapchain images:
There seems to be some progress. It now completes a full cycle of imageindices, but still hangs a bit later. Here is the last lines of console outputs:
Current Frame: 0 | Cmd Buffer Index: 1 | Image Index: 1
Calling vkBeginCommandBuffer
Assistant
I see that it hangs after a full cycle completes. This issue could be caused by improper synchronization with respect to the swapchain images. Since you're using a double-buffering approach with kMaxFramesInFlight = 2, it's possible that the GPU hasn't finished rendering to the swapchain image that is being acquired again.
To address this issue, you can use an additional set of fences called imagesInFlight to keep track of the status of each swapchain image. We
void Renderer::BeginFrame()
{
// Wait for any previous work on this swapchain image to complete
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// Acquire an image from the swapchain, then begin recording commands for the current frame.
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) {
throw std::runtime_error("Failed to acquire next swapchain image.");
}
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
//currentCommandBuffer = commandBuffers[currentFrame];
currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2;
currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex];
vkBeginCommandBuffer(currentCommandBuffer, &beginInfo);
VkRenderPassBeginInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = framebuffers[imageIndex];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = swapChainExtent;
// Set the clear color to black
VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
void Renderer::ChoosePhysicalDevice()
{
// Enumerate the available physical devices and choose one that supports required features
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0)
{
throw std::runtime_error("Failed to find a GPU with Vulkan support.");
}
std::vector<VkPhysicalDevice> allDevices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data());
for (const auto& testDevice : allDevices)
{
if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) &&
CheckPhysicalDeviceExtensionSupport(testDevice).empty() &&
GetQueueFamilyIndices(testDevice).IsComplete())
{
physicalDevice = testDevice;
break;
}
}
if (physicalDevice == VK_NULL_HANDLE)
{
throw std::runtime_error("Failed to find a suitable GPU.");
}
}
void Renderer::CreateDevice()
{
// Get the GPU’s queue family indices
const QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice);
// Set up the device queue create info
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<uint32_t> uniqueQueueFamilyIndices = { indices.graphicsFamily.value(),indices.presentFamily.value() };
float queuePriority = 1.0f;
for (uint32_t queueFamilyIndex : uniqueQueueFamilyIndices)
{
VkDeviceQueueCreateInfo queueCreateInfo{};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
}
// Set up the physical device features
VkPhysicalDeviceFeatures deviceFeatures{};
// Set up the device create info
VkDeviceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
createInfo.pQueueCreateInfos = queueCreateInfos.data();
createInfo.pEnabledFeatures = &deviceFeatures;
createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
createInfo.ppEnabledExtensionNames = deviceExtensions.data();
// Create the logical device
if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a logical device.");
}
// Retrieve the graphics queue and the present queue
vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
void Renderer::CreateCommandPool()
{
// Find a queue family index that supports graphics operations
QueueFamilyIndices queueFamilyIndices = GetQueueFamilyIndices(physicalDevice);
// Create a command pool for the queue family
VkCommandPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
poolInfo.flags = 0;
if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create command pool.");
}
CreateCommandBuffers(); // Create command buffers after creating the command pool
}
void Renderer::CleanupCommandPool()
{
// Clean up Vulkan command pool
CleanupCommandBuffers(); // Add this line to clean up command buffers before destroying the command pool
vkDestroyCommandPool(device, commandPool, nullptr);
}
void Renderer::CreateFramebuffers()
{
// Check if the framebuffers vector is not empty, and call CleanupFramebuffers()
if (!framebuffers.empty()) {
CleanupFramebuffers();
}
The issue seems to occur after completing an full cycle of the image indices and cycling back to Image Index 0. Can you check that the CreateSyncObjects method is workign correctly? I believe the issue might be in the way it is trying to sync swapchain images.
These changes should help fix the hanging issue you were encountering. If you still face any issues, please let me know!
To fix the "vector subscript out of range" error, ensure that all your vectors have been initialized properly with their appropriate size:
Check your CreateCommandBuffers method. Since currentCmdBufferIndex is set to kMaxFramesInFlight * 2, the commandBuffers vector size should also be set to kMaxFramesInFlight * 2.
void Renderer::CreateCommandBuffers()
{
commandBuffers.resize(kMaxFramesInFlight * 2); // Set size as kMaxFramesInFlight * 2
...
}
Verify that the framebuffers, imageAvailableSemaphores, renderFinishedSemaphores, and inFlightFences vectors have been resized accordingly in their respective methods (i.e., CreateFramebuffers, CreateSyncObjects).
After making these changes, you should resolve the "vector subscript out of range" error. If the issue persists, please let me know!
Update the Renderer::BeginFrame method:
void Renderer::BeginFrame()
{
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// Acquire an image from the swapchain
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
...
}
With these changes, the synchronization logic should work correctly, and you should not run into any hanging or "vector subscript out of range" errors. If you still face any issues, please let me know and provide more details if possible.