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.
The problem might stem from the use of synchronization objects (fences) in your code. You can wait for the fence of the current frame, reset it, and then provide it to the vkQueueSubmit() function. This will prevent the command buffer from being used simultaneously by different frames.
Modify the Renderer::BeginFrame by adding vkWaitForFences and vkResetFences calls before vkBeginCommandBuffer:
cpp
User
The changes you suggested are already present in the code
Assistant
I apologize for not catching that earlier. Here are a few more suggestions to investigate and resolve the issue:
User
What code should I implement and where should I put it in order to enable validation layers?
Assistant
You have already set up the validation layers in the provided code. It is guarded by the NDEBUG macro, so if you are running in Debug mode, it should be enabled automatically. Here's the relevant code snippet from your Renderer::CreateInstance():
void Renderer::ChoosePhysicalDevice()
{
// Enumerate the available physical devices and choose one that supports required features
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
code
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);
code
// 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);
code
// 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();
}
It compeltes 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
What changes to the code would fix this?
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.
// ...
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
// ...
}
Make sure you update the vkQueueSubmit() call in Renderer::EndFrame() to include the fence for the current frame:
These changes should prevent the hang in the vkBeginCommandBuffer call. However, if the issue persists, it might be due to other synchronization issues or problems within your rendering pipeline.
Additionally, enable the Vulkan validation layers in your code to check for any issues with synchronization or incorrect API usage (if you haven't already). To enable the validation layers, simply make sure the enableValidationLayers flag is set to true and check if your application runs without reporting any issues.
Check if resources are correctly acquired and released:
Ensure that you're properly acquiring and releasing resources, such as image indices, semaphores, and fences. Verify that these resources are not being reused incorrectly, leading to stalls in your renderer.
Verify swapchain recreation:
If the window is resized, you may need to recreate the swapchain. Ensure that the swapchain is being recreated when necessary, and during recreation, make sure to wait until the device is idle before destroying and creating new resources.
Debugging with RenderDoc:
Use RenderDoc, a graphics debugging tool, to gain insights into your application's behavior during rendering. RenderDoc could help you identify unexpected issues in your rendering pipeline, resource usage, or synchronization.
Check for additional messages from Vulkan Validation Layers:
Make sure you have Vulkan Validation Layers enabled, and check whether there are any messages or warnings reported. Validation layers can help identify incorrect API usage, resource leaks, or synchronization problems that may lead to a stall.
Before running your application, you can also set the VK_INSTANCE_LAYERS environment variable to VK_LAYER_KHRONOS_validation. This will enable the validation layers for your application. Ensure that the validation layers are installed on your system; otherwise, your application may fail to launch.
Note: Validation layers may negatively impact performance, so use them only for debugging purposes.
Run vkQueueWaitIdle before vkBeginCommandBuffer:
As a last resort, you can try calling vkQueueWaitIdle(graphicsQueue) before you call vkBeginCommandBuffer(currentCommandBuffer, &beginInfo), to ensure the graphics queue is idle before you start recording commands. If this resolves the issue, there might be a deeper synchronization problem in your code that needs further investigation.
Keep in mind that using vkQueueWaitIdle may introduce significant performance penalties, and it's not recommended for production code. If it helps fix the stall, it's a temporary solution to help diagnose the problem, but it's important to uncover the real underlying issue.
With these approaches, you should be able to identify the root cause of the hang in the vkBeginCommandBuffer call and fix it accordingly.
If you want to force enable the validation layers in both Debug and Release configurations, update the enableValidationLayers definition as follows:
cpp
const bool enableValidationLayers = true;
Make sure that the Vulkan SDK is installed on your system and the validation layers are available.
In your build settings, ensure that you are building in Debug mode. If you're using an IDE like Visual Studio, you can switch between Debug and Release modes using the dropdown menu in the toolbar. If you're using a build system like CMake, use the -DCMAKE_BUILD_TYPE=Debug flag when configuring your project.