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 MVP variable that you've placed in the GameObject::Initialize method has not been declared or initialized. Also, the GameObject::Initialize method does not currently have access to renderer.GetDevice(). Would it be better to simply pass the VkDevice and VkPhysicalDevice to the GameObject::Initialize method?
Assistant
Yes, you are right. In the code I provided, I accidentally referred to the renderer variable, which is not available in the GameObject::Initialize method. I apologize for the confusion. You can indeed pass the VkDevice and VkPhysicalDevice to the GameObject::Initialize method. Here's the updated code:
Modify the GameObject::Initialize method's signature to accept VkDevice and VkPhysicalDevice as input parameters:
Update the method definition to use the passed parameters:
void GameObject::Initialize(VkDevice device, VkPhysicalDevice physicalDevice)
{
mesh = new Mesh{};
material = new Material{};
this->initialized = true;
// Create MVP buffers
for (size_t i = 0; i < 2; ++i)
{
BufferUtils::CreateBuffer(device, physicalDevice,
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemories[i]);
}
}
User
The MVP variable that you’ve placed in the GameObject::Initialize method has not been declared or initialized. How do I hande this?
Assistant
Apologies for the oversight. The MVP variable used in the GameObject::Initialize method is not required, as we only need to create the MVP buffers in that method. We'll be updating the MVP data later in the GameObject::Render method.
Here's the corrected GameObject::Initialize method, without the mention of the MVP variable:
void GameObject::Initialize(VkDevice device, VkPhysicalDevice physicalDevice)
{
mesh = new Mesh{};
material = new Material{};
this->initialized = true;
// Create MVP buffers
for (size_t i = 0; i < 2; ++i)
{
BufferUtils::CreateBuffer(device, physicalDevice,
sizeof(glm::mat4) * 3, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemories[i]);
}
}
As you can see, the MVP variable has been removed, instead we use sizeof(glm::mat4) * 3 to allocate enough buffer space for the model, view, and projection matrices.
In the GameObject::Render method, the MVP variable is still used for updating the MVP data in the per-frame buffer.
User
Given the number of calls to renderer class objects and the likelihood that these buffers could be used across multiple GameObject, does it make more sense to incorporate this buffer logic into the renderer class?
Assistant
Assistant
I hope the solution provided for refactoring the buffer logic into the Renderer class is helpful. If you have further questions or need more guidance, please don't hesitate to ask. Good luck with your game engine!
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;
BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffer, mvpBufferMemory);
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkBuffer(ERROR / SPEC): msgNum: 653100552 - Validation Error: [ UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkBuffer ] Object 0: handle = 0xb9181f0000000029, type = VK_OBJECT_TYPE_BUFFER; Object 1: handle = 0xb097c90000000027, type = VK_OBJECT_TYPE_DESCRIPTOR_SET; Object 2: handle = 0x221c1afa4f0, type = VK_OBJECT_TYPE_COMMAND_BUFFER; | MessageID = 0x26ed8608 | You are adding vkCmdEndRenderPass to VkCommandBuffer 0x221c1afa4f0[] that is invalid because bound VkBuffer 0xb9181f0000000029[] was destroyed.
Objects: 3
[0] 0xb9181f0000000029, type: 9, name: NULL
[1] 0xb097c90000000027, type: 23, name: NULL
[2] 0x221c1afa4f0, type: 6, name: NULL
Based on some debugging, I believe the error is triggered near the end of the GameObject::Render method. How can I alter the code to fix this issue?
The error is happening because the buffer (mvpBuffer) used for the Model-View-Projection (MVP) matrix is being destroyed while the command buffer is still in use. You must ensure that the buffer persists as long as the command buffer is in use. One way to achieve this is to create a per-frame buffer for storing the MVP data and reuse it across multiple frames.
Here's a solution to maintain a per-frame MVP buffer in your GameObject class:
Modify class GameObject by adding a member for holding references to frame buffers for storing MVP data:
// Add these includes at the top
#include <array>
#include <vulkan/vulkan.h>
// ...
class GameObject
{
// ...
private:
// ...
std::array<VkBuffer, 2> mvpBuffers;
std::array<VkDeviceMemory, 2> mvpBufferMemories;
// ...
};
Update the GameObject::Initialize method to create frame buffers for storing MVP data:
Update the GameObject::Shutdown method to destroy frame buffers for storing MVP data:
void GameObject::Shutdown()
{
// ...
VkDevice device = *renderer.GetDevice();
for (size_t i = 0; i < 2; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemories[i], nullptr);
}
// ...
}
Modify the GameObject::Render method to remove the creation and destruction of the temporary buffer. Instead, use the per-frame buffer. Also, use the % 2 operation to cycle between the two available buffers:
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// ...
// Get index of the current frame buffer
size_t currentFrameBufferIndex = renderer.currentFrame % 2;
// Update MVP data in the current frame buffer
void* data = nullptr;
vkMapMemory(device, mvpBufferMemories[currentFrameBufferIndex], 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemories[currentFrameBufferIndex]);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffers[currentFrameBufferIndex], device, sizeof(MVP));
// ...
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
}
Now, your code utilizes a per-frame buffer for storing MVP data and ensures that these buffers stay valid while command buffers are in use. Make sure to test the changes in your application, and ensure other dependencies are updated.
Now you can pass the VkDevice and VkPhysicalDevice when initializing a GameObject. Make sure to update the calls to Initialize method accordingly in your program.
Yes, you are correct. If you plan to have multiple GameObject instances and since the buffer logic relies on several renderer properties, it is a good idea to incorporate the MVP buffer management logic into the Renderer class.
Here's how you can accomplish that:
Modify the Renderer class to store the MVP buffers:
Modify GameObject::Initialize and GameObject::Shutdown methods to no longer handle MVP buffers, and update the GameObject::Render method to now use the renderer's MVP buffers:
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// ...
// Get index of the current frame buffer
size_t currentFrameBufferIndex = renderer.currentFrame % 2;
// Update MVP data in the current frame buffer
VkDevice device = *renderer.GetDevice();
VkDeviceMemory mvpBufferMemory = renderer.GetMvpBufferMemories()[currentFrameBufferIndex];
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// Get current frame MVP buffer and use it
VkBuffer mvpBuffer = renderer.GetMvpBuffers()[currentFrameBufferIndex];
// ...
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
// ...
}
Now, the Renderer class handles the MVP buffers, and the GameObject class can utilize them. This change not only optimizes buffer usage across multiple GameObject instances, but also centralizes the buffer management logic in the Renderer class. Make sure to update any other dependencies and test the updated code in your application.