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 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.
Here is some of the relevant header and source file code:
Can you show me how to modify the code to use std::shared_ptr for the relevant objects?
Assistant
Sure, here's how to modify the code to use std::shared_ptr for Texture and Material objects. I will show key modification in certain parts of the code, and you can follow the same pattern for other objects if needed. Focus on comments marked // <<<--- CHANGES.
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize(const Mesh& mesh, const Material& material)
{
this->mesh = mesh; // copy or share mesh data
this->material = material; // copy or share material data
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();
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)
this->initialized = false;
}
for (int x = 0; x < worldSize; ++x) {
for (int z = 0; z < worldSize; ++z) {
float noiseValue = noise.noise(x * scale, z * scale);
heightMap[x][z] = noiseValue;
}
}
}
void Terrain::ConvertHeightMapToMeshData() {
// … Convert height map to vertices and indices (code from the previous example)
}
// Initialize terrainMaterial with the loaded shaders and texture
// Assume descriptorSetLayout and descriptorPool are created before this call
terrainMaterial.Initialize("C:/shaders/vert.spv", "C:/shaders/frag.spv", "C:/textures/texture.jpg", *device, descriptorSetLayout, descriptorPool, *physicalDevice, *commandPool, *graphicsQueue);
terrainObject.Initialize(terrainMesh, terrainMaterial);
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set, pipeline layout, and other required objects for the material
// …
}
void Material::Cleanup()
{
// Clean up resources, if necessary
// (depending on how Shader and Texture resources are managed)
}
I am getting an error in the Texture::Cleanup method saying "A heap has been corrupted". Do you know what might be causing this error and how to fix it? There could be and issue of shared ownership of resources between Terrain and GameObject.
The issue may be caused by improper or invalid handling of objects in the Texture, GameObject, Mesh, or Material classes. Getting the "heap has been corrupted" error can mean that there's memory corruption or an object was deleted when it shouldn't have been. Reviewing these classes, there are a few potential areas of concern that could cause memory corruption.
Texture is initialized in Material via LoadTexture and cleaned up in the Texture::~Texture() destructor. It is possible that there is an issue when the Texture object is copied between classes, and this happens when assigning a Texture object to new Material class in the Material::Initialize() method in Terrain::GenerateTerrain(). Since it is a shallow copy, the destructors can be called multiple times, causing double deletions of the Vulkan resource. You can consider using shared ownership (e.g., use std::shared_ptr or similar) for handling resources or not copying the Texture object in the Material class.
When the Material class is copied between classes (in Terrain, GameObject classes), the same issue could happen with the Vulkan resource in the destructor. The same solution mentioned for the Texture class (using shared ownership or not copying the Material object) needs to be applied here.
When initializing the Mesh object in the Terrain class, it is passed as a const reference during the setup of the GameObject object. Although the Mesh object is a wrapper for the memory-owning buffers and shouldn't cause issues if different objects use the same instance of the Mesh object, it might cause issues if a Mesh object is deleted in some point of the timeline causing crashes if it tries to free memory again. In this case, consider using std::shared_ptr<Mesh> and std::shared_ptr<Material> so that the memory will be managed automatically.
Ensure that each object is destroyed and memory cleaned up when you are done using them. The GameObject class that wraps the Mesh and Material objects can have issues with the ownership of resources as well. Make sure to appropriately destroy these objects when the Scene and Terrain objects are shut down.
To summarize, managing shared Vulkan resources can be quite challenging. You may want to consider using shared ownership for resources such as the Texture or Material classes, which are prone to multiple ownership scenarios. Utilizing std::shared_ptr or a similar approach can help ensure your resources are managed appropriately and avoid memory corruption errors. Additionally, Vulkan resources should be cleaned up and destroyed when no longer needed for proper resource management.
Now, modify Material.cpp to use std::shared_ptr:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
// Cleanup function will still be called automatically when shared_ptr is destroyed
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Load shaders and texture
// <<<--- CHANGES: Create new Texture instance wrapped in shared_ptr when loading texture
texture = std::make_shared<Texture>();
texture->LoadFromFile(texturePath, device, physicalDevice, commandPool, graphicsQueue);
// ...
}
// ...
// <<<--- CHANGES: Change