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 have written the code for the foundations of the engine.
The basic class structure is as follows:
Core:
class Engine
This is the main class that will initialize, run, and shut down other subsystems of the engine (e.g., Window, Renderer, Input, etc.)
Window:
class Window
This class will handle window creation, resizing, and destruction using GLFW. It should also handle keyboard and mouse input events.
Renderer:
class Renderer
This class will manage Vulkan objects (e.g., instance, device, swapchain, command buffers) and rendering pipelines.
class Shader
To handle shader modules creation and destruction.
class Texture
To handle texture loading and destruction.
class Pipeline
To encapsulate the description and creation of a Vulkan graphics or compute pipeline.
Scene:
class Scene
This class will manage the list of objects in the vector, update their transforms, and send them to the Renderer for rendering.
class GameObject
To represent individual objects in the scene, store their transformation matrices, and bind the relevant data like vertices and indices.
class Camera
To store and manage camera properties such as position, rotation, view, and projection matrices.
class Mesh
To handle mesh data (e.g., vertices, indices, etc.) for individual objects.
class Material
To store and manage material properties such as colors, shaders, and textures.
Math:
Utilize GLM library to handle vector and matrix math operations.
I am having some issues with the Renderer class. Here is are the header and source files for the Renderer class:
The unhandled exception error in the CleanupCommandPool method might be due to an improper shutdown sequence or incorrect usage of Vulkan resources. To find the root cause of the problem and possible fix, check the following:
User
It is now throwing an access violation error in the CleanupRenderPass method.
Assistant
I suspect that the access violation error in the CleanupRenderPass() method might be caused by executing the destruction of the render pass before finishing the rendering operations.
To fix this problem, you must sync the rendering before destroying the render pass. You can do this by using the vkDeviceWaitIdle function before calling the Shutdown() method. This function will make sure that all rendering operations are completed before starting the cleanup process. It should be called in the function where you handle your main loop or just before calling Shutdown().
Here's an example of where you can add it:
int main() {
// ...
// Initialization and main loop code
// ...
vkDeviceWaitIdle(device); // Wait for rendering to complete
renderer.Shutdown(); // Call the Shutdown method
// ...
// Cleanup and exit code
// ...
}
This change should prevent the access violation error during the CleanupRenderPass() call. Make sure that you are following the correct order of creation and destruction of Vulkan resources and make use of synchronization primitives offered by Vulkan to manage access to resources properly.
User
I have added vkDeviceWaitIdle(device) but it seems to be causing an access violation error
Assistant
I apologize for the confusion. I see now that the device field is declared as private inside the Renderer class, and that's why you cannot access it directly from the main function. Instead, add a new public method called WaitForDeviceIdle() to the Renderer class and call that method just before calling the Shutdown() method.
Here's how you can do this:
Add a new public method called WaitForDeviceIdle() to the Renderer class in the Renderer.h file:
class Renderer {
public:
// ...
// Other declarations
// ...
void WaitForDeviceIdle();
private:
// ...
// Other declarations
// ...
};
Implement the WaitForDeviceIdle() method in the Renderer.cpp file:
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];
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
vkDestroyCommandPool(device, commandPool, nullptr);
}
void Renderer::CleanupFramebuffers()
{
for (auto framebuffer : framebuffers)
{
if (framebuffer != VK_NULL_HANDLE)
{
vkDestroyFramebuffer(device, framebuffer, nullptr);
}
}
framebuffers.clear(); // Make sure to clear the framebuffers vector after destroying each framebuffer
}
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data());
int i = 0;
for (const auto& queueFamily : queueFamilies)
{
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
indices.graphicsFamily = i;
}
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport);
if (presentSupport)
{
indices.presentFamily = i;
}
if (indices.IsComplete())
{
break;
}
i++;
}
return indices;
}
There are issues with the Shutdown process. I am getting an unhandled exception error un the CleanupCommandPool method. Do you know what the problem might be and how to fix it?
Ensure proper shutdown sequence: Make sure the shutdown sequence of the different Vulkan objects follows the reverse order of their creation. In the Shutdown() method, after calling CleanupCommandBuffers(), try calling CleanupFramebuffers() before CleanupCommandPool(), like this:
Ensure the command buffers are properly cleaned up before destroying the command pool: In the CleanupCommandPool() method, before calling vkDestroyCommandPool(), make sure to free the command buffers. Add a CleanupCommandBuffers() method to free the allocated command buffers before destroying the command pool:
Then, in Shutdown() method, call CleanupCommandBuffers() just before calling CleanupCommandPool():
void Renderer::Shutdown()
{
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandBuffers(); // Free command buffers before destroying the command pool
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
DestroySurface();
CleanupDevice();
CleanupInstance();
}
Check for any Vulkan validation errors: During runtime, it is helpful to check for Vulkan validation errors to ensure you are correctly using Vulkan resources. This can be done by enabling the VK_LAYER_KHRONOS_validation layer when creating the instance. Also, make sure to install the Vulkan SDK and set the environment variable VK_LAYER_PATH to the Vulkan layers installation path. This will give you more debug information and help identify issues in the code.
Remember that it's essential to follow the correct order of creation and destruction of Vulkan resources, and always free or destroy resources before destroying their parent objects.
Please modify your code following the suggestions above and see if it resolves the unhandled exception error during the shutdown process.
Call this new method just before calling the Shutdown() method in your main function or where you handle your main loop:
int main() {
// ...
// Initialization and main loop code
// ...
renderer.WaitForDeviceIdle(); // Wait for rendering to complete
renderer.Shutdown(); // Call the Shutdown method
// ...
// Cleanup and exit code
// ...
}
This change should help you avoid the access violation error, as it ensures that all rendering operations are completed before starting the cleanup process. Make sure that the order of creation and destruction of Vulkan resources is followed correctly, and make use of synchronization primitives offered by Vulkan to manage access to resources properly.