Below is a rewritten version of the MeshUploadManager class that addresses the issues, uses its own dedicated copy queue, and integrates with the D3D12 Memory Allocator (D3D12MA) library. The mesh description formats remain unchanged, and the renderer can check if a handle is ready for use. I'll also provide an example of how to use it in a game loop, including upload, defragmentation, and other operations.
Key Changes
- Dedicated Copy Queue: The
MeshUploadManager now creates and manages its own ID3D12CommandQueue of type D3D12_COMMAND_LIST_TYPE_COPY, ensuring no conflicts with the renderer's direct queue.
- Handle Readiness Check: The renderer can check if a
GPUMeshHandle is ready using the IsReady method, which checks the fence value.
- D3D12MA Integration: The code uses the D3D12MA library for memory allocation, as in the original code.
- Error Handling: Improved error handling with logging and null checks to prevent crashes.
- Game Loop Example: I'll provide a detailed example of how to use the
MeshUploadManager in a game loop, including upload, defragmentation, and rendering.
Code
#pragma once
#include "pch.hpp" // Common precompiled headers (d3d12.h, wrl.h, etc.)
#include "D3D12MemAlloc.hpp" // Include the D3D12 Memory Allocator header
#include <vector>
#include <queue>
#include <mutex>
#include <atomic>
#include <cassert>
namespace Rtx {
/**
* @brief Aligns a size to a specified alignment.
* @param size The size to align.
* @param alignment The alignment requirement.
* @return The aligned size.
*/
inline UINT64 Align(UINT64 size, UINT64 alignment)
{
return (size + alignment - 1) & ~(alignment - 1);
}
/**
* @brief Gets the size in bytes of a given rType.
*/
inline size_t GetTypeSize(rType type)
{
switch (type)
{
case rType::F32: return sizeof(float);
case rType::U32: return sizeof(u32);
case rType::U16: return sizeof(u16);
case rType::I32: return sizeof(i32);
default: return 0;
}
}
// --- Mesh Description Structures ---
// (Unchanged from your original code, assuming these are defined elsewhere)
// struct MeshDescription { ... };
// struct Attribute { rType type; void* data; size_t size; u32 elementCount; size_t stride; };
// struct Indices { rType type; void* data; size_t size; };
/**
* @brief Handle to a GPU mesh resource. Contains all views and metadata needed for rendering.
*/
struct GPUMeshHandle
{
D3D12MA::Allocation* allocation = nullptr; // D3D12MA allocation object.
Microsoft::WRL::ComPtr<ID3D12Resource> resource; // The GPU buffer (VBs and IB combined).
std::vector<D3D12_VERTEX_BUFFER_VIEW> vertexBufferViews;
D3D12_INDEX_BUFFER_VIEW indexBufferView;
bool hasIndices = false;
UINT64 fenceValue = 0; // Fence value signaled when the upload is complete.
u32 id = UINT32_MAX;
/**
* @brief Checks if the GPU has finished the upload copy for this mesh.
* @param fence The fence to check against.
*/
bool IsReady(ID3D12Fence* fence) const
{
assert(fence != nullptr && "Fence must not be null");
return (fenceValue == 0 || fence->GetCompletedValue() >= fenceValue);
}
bool IsValid() const { return id != UINT32_MAX && resource != nullptr; }
};
/**
* @brief Manages asynchronous uploading of mesh data from CPU to GPU default heap memory.
*
* This manager uses a single large upload buffer as a ring buffer for staging.
* It batches copy commands and uses fences to track GPU progress, allowing the ring
* buffer space to be safely reclaimed. It also defers the release of mesh resources
* until they are no longer in use by the GPU.
*/
class MeshUploadManager
{
public:
MeshUploadManager() = default;
~MeshUploadManager() { Shutdown(); }
/**
* @brief Initializes the manager.
* @param allocator A pointer to an initialized D3D12MA::Allocator.
* @param device A pointer to the ID3D12Device.
* @param uploadBufferSize The size of the internal staging ring buffer in bytes.
*/
bool Initialize(D3D12MA::Allocator* allocator, ID3D12Device* device, size_t uploadBufferSize = 256 * 1024 * 1024)
{
std::lock_guard lock(m_mutex);
if (!allocator || !device) {
// Log error: Invalid input parameters
return false;
}
m_d3d12ma_allocator = allocator;
m_device = device;
// Create a dedicated copy queue
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_COPY;
queueDesc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
queueDesc.NodeMask = 0;
HRESULT hr = m_device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&m_copyQueue));
if (FAILED(hr)) {
// Log error: Failed to create copy queue
return false;
}
// Create synchronization primitives
hr = m_device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m_fence));
if (FAILED(hr)) {
// Log error: Failed to create fence
m_copyQueue.Reset();
return false;
}
m_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
if (m_fenceEvent == nullptr) {
// Log error: Failed to create fence event
m_fence.Reset();
m_copyQueue.Reset();
return false;
}
// Create dedicated copy command list and allocator
hr = m_device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY, IID_PPV_ARGS(&m_copyAllocator));
if (FAILED(hr)) {
// Log error: Failed to create command allocator
m_fence.Reset();
CloseHandle(m_fenceEvent);
m_fenceEvent = nullptr;
m_copyQueue.Reset();
return false;
}
hr = m_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, m_copyAllocator.Get(), nullptr, IID_PPV_ARGS(&m_copyCommandList));
if (FAILED(hr)) {
// Log error: Failed to create command list
m_copyAllocator.Reset();
m_fence.Reset();
CloseHandle(m_fenceEvent);
m_fenceEvent = nullptr;
m_copyQueue.Reset();
return false;
}
m_copyCommandList->Close();
// Create and map the upload ring buffer
m_uploadBufferSize = uploadBufferSize;
if (!InitializeUploadBuffer()) {
// Log error: Failed to initialize upload buffer
m_copyCommandList.Reset();
m_copyAllocator.Reset();
m_fence.Reset();
CloseHandle(m_fenceEvent);
m_fenceEvent = nullptr;
m_copyQueue.Reset();
return false;
}
return true;
}
/**
* @brief Shuts down the manager, flushes all pending work, and releases resources.
*/
void Shutdown()
{
std::lock_guard lock(m_mutex);
Flush(); // Wait for all uploads to complete.
if (m_uploadBuffer)
{
m_uploadBuffer->Unmap(0, nullptr);
m_uploadCpuPtr = nullptr;
m_uploadBuffer.Reset();
}
m_copyCommandList.Reset();
m_copyAllocator.Reset();
m_fence.Reset();
CloseHandle(m_fenceEvent);
m_fenceEvent = nullptr;
m_copyQueue.Reset();
// Clean up any remaining mesh handles and deferred releases
for (auto& handle : m_meshHandles)
{
if (handle.IsValid())
{
handle.resource.Reset();
handle.allocation->Release();
}
}
m_meshHandles.clear();
while (!m_deferredReleaseQueue.empty())
{
m_deferredReleaseQueue.front().allocation->Release();
m_deferredReleaseQueue.pop();
}
m_d3d12ma_allocator = nullptr;
m_device.Reset();
}
/**
* @brief Enqueues a mesh for upload to the GPU.
* This is thread-safe. It records copy commands but does not submit them.
* @param desc The description of the mesh data.
* @return A unique ID for the mesh. Returns UINT32_MAX on failure.
*/
u32 UploadMesh(const MeshDescription& desc)
{
std::lock_guard lock(m_mutex);
if (!m_copyQueue || !m_fence) {
// Log error: Manager not initialized
return UINT32_MAX;
}
if (!m_hasPendingCopies) {
// This is the first upload in a new batch. Reset the command list.
HRESULT hr = m_copyAllocator->Reset();
if (FAILED(hr)) return UINT32_MAX;
hr = m_copyCommandList->Reset(m_copyAllocator.Get(), nullptr);
if (FAILED(hr)) return UINT32_MAX;
}
// 1. Calculate total size based on the MeshDescription
size_t totalVertexDataSize = 0;
size_t totalIndexDataSize = desc.indices.size;
if (desc.interleaved)
{
if (desc.interleavedVertexCount == 0 || desc.count == 0) return UINT32_MAX;
// For interleaved data, the stride is the sum of the sizes of all attributes.
size_t vertexStride = 0;
for (u32 i = 0; i < desc.count; ++i)
{
vertexStride += GetTypeSize(desc.attribute[i].type) * desc.attribute[i].elementCount;
}
totalVertexDataSize = vertexStride * desc.interleavedVertexCount;
}
else // SoA (Structure of Arrays)
{
// For SoA, total size is the sum of individual attribute buffer sizes.
for (u32 i = 0; i < desc.count; ++i)
{
totalVertexDataSize += desc.attribute[i].size;
}
}
const size_t totalRequiredSize = totalVertexDataSize + totalIndexDataSize;
if (totalRequiredSize == 0 || totalRequiredSize > m_uploadBufferSize)
{
return UINT32_MAX;
}
// 2. Allocate space in the ring buffer
size_t allocationOffset = FindSpaceInRingBuffer(totalRequiredSize);
if (allocationOffset == (size_t)-1)
{
return UINT32_MAX;
}
// 3. Create destination GPU resource
GPUMeshHandle newHandle;
D3D12MA::ALLOCATION_DESC allocDesc = {};
allocDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;
CD3DX12_RESOURCE_DESC bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(totalRequiredSize);
HRESULT hr = m_d3d12ma_allocator->CreateResource(&allocDesc, &bufferDesc, D3D12_RESOURCE_STATE_COMMON, nullptr, &newHandle.allocation, IID_PPV_ARGS(&newHandle.resource));
if (FAILED(hr)) return UINT32_MAX;
// 4. Copy data and record commands
uint8_t* uploadDst = m_uploadCpuPtr + allocationOffset;
size_t currentCpuOffset = 0;
size_t currentGpuOffset = 0;
// --- 4a. Vertex Data ---
if (desc.interleaved)
{
// Assumes the full interleaved data block is pointed to by the first attribute.
memcpy(uploadDst, desc.attribute[0].data, totalVertexDataSize);
m_copyCommandList->CopyBufferRegion(newHandle.resource.Get(), 0, m_uploadBuffer.Get(), allocationOffset, totalVertexDataSize);
size_t vertexStride = 0;
for (u32 i = 0; i < desc.count; ++i) vertexStride += GetTypeSize(desc.attribute[i].type) * desc.attribute[i].elementCount;
D3D12_VERTEX_BUFFER_VIEW vbv = {};
vbv.BufferLocation = newHandle.resource->GetGPUVirtualAddress();
vbv.SizeInBytes = static_cast<UINT>(totalVertexDataSize);
vbv.StrideInBytes = static_cast<UINT>(vertexStride);
newHandle.vertexBufferViews.push_back(vbv);
}
else // SoA
{
for (u32 i = 0; i < desc.count; ++i)
{
const auto& attr = desc.attribute[i];
if (attr.size > 0 && attr.data != nullptr)
{
memcpy(uploadDst + currentCpuOffset, attr.data, attr.size);
m_copyCommandList->CopyBufferRegion(newHandle.resource.Get(), currentGpuOffset, m_uploadBuffer.Get(), allocationOffset + currentCpuOffset, attr.size);
D3D12_VERTEX_BUFFER_VIEW vbv = {};
vbv.BufferLocation = newHandle.resource->GetGPUVirtualAddress() + currentGpuOffset;
vbv.SizeInBytes = static_cast<UINT>(attr.size);
// Use the provided stride if available, otherwise calculate it.
vbv.StrideInBytes = (attr.stride > 0)
? static_cast<UINT>(attr.stride)
: static_cast<UINT>(GetTypeSize(attr.type) * attr.elementCount);
newHandle.vertexBufferViews.push_back(vbv);
currentCpuOffset += attr.size;
currentGpuOffset += attr.size;
}
}
}
currentCpuOffset = totalVertexDataSize;
currentGpuOffset = totalVertexDataSize;
// --- 4b. Index Data ---
if (desc.indices.size > 0 && desc.indices.data != nullptr)
{
newHandle.hasIndices = true;
memcpy(uploadDst + currentCpuOffset, desc.indices.data, desc.indices.size);
m_copyCommandList->CopyBufferRegion(newHandle.resource.Get(), currentGpuOffset, m_uploadBuffer.Get(), allocationOffset + currentCpuOffset, desc.indices.size);
newHandle.indexBufferView.BufferLocation = newHandle.resource->GetGPUVirtualAddress() + currentGpuOffset;
newHandle.indexBufferView.SizeInBytes = static_cast<UINT>(desc.indices.size);
newHandle.indexBufferView.Format = (desc.indices.type == rType::U16) ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
}
m_hasPendingCopies = true;
// 5. Store handle and return ID
newHandle.fenceValue = m_fenceValue;
u32 id = GetNewHandleID();
newHandle.id = id;
m_meshHandles[id] = std::move(newHandle);
m_inFlightUploadRanges.push({ allocationOffset, totalRequiredSize, m_fenceValue });
m_currentUploadOffset = allocationOffset + totalRequiredSize;
return id;
}
/**
* @brief Submits all pending copy commands to the GPU.
* Should be called once per frame, before executing the main rendering command list.
*/
void SubmitUploads()
{
std::lock_guard lock(m_mutex);
if (!m_hasPendingCopies) return;
if (!m_copyQueue || !m_fence) {
// Log error: Manager not initialized
return;
}
HRESULT hr = m_copyCommandList->Close();
if (FAILED(hr)) {
// Log error: Failed to close command list
return;
}
ID3D12CommandList* lists[] = { m_copyCommandList.Get() };
m_copyQueue->ExecuteCommandLists(1, lists);
hr = m_copyQueue->Signal(m_fence.Get(), m_fenceValue);
if (FAILED(hr)) {
// Log error: Failed to signal fence
return;
}
// Increment fence for the next submission batch
m_fenceValue++;
hr = m_copyAllocator->Reset();
if (FAILED(hr)) {
// Log error: Failed to reset command allocator
return;
}
hr = m_copyCommandList->Reset(m_copyAllocator.Get(), nullptr);
if (FAILED(hr)) {
// Log error: Failed to reset command list
return;
}
m_hasPendingCopies = false;
}
/**
* @brief Releases a mesh by its ID, queueing its GPU resources for safe deletion.
* @param id The ID of the mesh to release.
*/
void ReleaseMesh(u32 id)
{
std::lock_guard lock(m_mutex);
if (id >= m_meshHandles.size() || !m_meshHandles[id].IsValid()) return;
// Move the allocation to the deferred release queue.
m_deferredReleaseQueue.push({ m_meshHandles[id].allocation, m_fenceValue });
// Invalidate the handle and add its ID to the free list for reuse.
m_meshHandles[id] = {}; // Reset the handle.
m_freeHandleIndices.push(id);
}
/**
* @brief Gets a constant pointer to a mesh handle by its ID.
* @param id The ID of the mesh.
* @return A pointer to the MeshHandle, or nullptr if the ID is invalid.
*/
const GPUMeshHandle* GetMeshHandle(u32 id) const
{
std::lock_guard lock(m_mutex);
if (id >= m_meshHandles.size() || !m_meshHandles[id].IsValid())
{
return nullptr;
}
return &m_meshHandles[id];
}
/**
* @brief Reclaims memory from completed uploads and deferred releases.
* Call this once per frame before queuing new uploads.
*/
void CleanUpCompletedOperations()
{
std::lock_guard lock(m_mutex);
if (!m_fence) return;
const UINT64 completedFenceValue = m_fence->GetCompletedValue();
// Reclaim space in the upload ring buffer
while (!m_inFlightUploadRanges.empty() && m_inFlightUploadRanges.front().fenceValue <= completedFenceValue)
{
m_inFlightUploadRanges.pop();
}
// Process the deferred release queue
while (!m_deferredReleaseQueue.empty() && m_deferredReleaseQueue.front().fenceValue <= completedFenceValue)
{
m_deferredReleaseQueue.front().allocation->Release();
m_deferredReleaseQueue.pop();
}
}
/**
* @brief Gets the fence used by the manager, for external synchronization.
*/
ID3D12Fence* GetFence() const { return m_fence.Get(); }
/**
* @brief Performs defragmentation of GPU memory using D3D12MA.
* @param defragPass Pointer to a D3D12MA::DefragmentationPass object to store defrag stats.
* @return True if defragmentation is complete, false if more passes are needed.
*/
bool Defragment(D3D12MA::DefragmentationPass* defragPass = nullptr)
{
std::lock_guard lock(m_mutex);
if (!m_d3d12ma_allocator) return true; // Nothing to defragment
// Collect all allocations
std::vector<D3D12MA::Allocation*> allocations;
for (auto& handle : m_meshHandles)
{
if (handle.IsValid())
{
allocations.push_back(handle.allocation);
}
}
if (allocations.empty()) return true;
// Begin defragmentation if not already started
if (!m_defragContext)
{
HRESULT hr = m_d3d12ma_allocator->BeginDefragmentation({}, &m_defragContext);
if (FAILED(hr)) {
// Log error: Failed to begin defragmentation
return true; // Consider defragmentation complete on failure
}
}
// Perform a defragmentation pass
D3D12MA::DEFRAGMENTATION_PASS_MOVE_INFO passInfo = {};
HRESULT hr = m_defragContext->BeginPass(&passInfo);
if (FAILED(hr)) {
// Log error: Failed to begin defragmentation pass
m_defragContext->Release();
m_defragContext = nullptr;
return true;
}
// Process moves (update resource pointers in handles)
for (UINT i = 0; i < passInfo.MoveCount; ++i)
{
auto& move = passInfo.pMoves[i];
for (auto& handle : m_meshHandles)
{
if (handle.IsValid() && handle.allocation == move.pSrcAllocation)
{
handle.resource = move.pDstTmpAllocation->GetResource();
handle.allocation = move.pDstTmpAllocation;
// Update buffer views
for (auto& vbv : handle.vertexBufferViews)
{
vbv.BufferLocation = handle.resource->GetGPUVirtualAddress();
}
if (handle.hasIndices)
{
handle.indexBufferView.BufferLocation = handle.resource->GetGPUVirtualAddress();
}
}
}
}
hr = m_defragContext->EndPass();
if (FAILED(hr)) {
// Log error: Failed to end defragmentation pass
m_defragContext->Release();
m_defragContext = nullptr;
return true;
}
if (defragPass) *defragPass = passInfo;
// Check if defragmentation is complete
D3D12MA::DEFRAGMENTATION_STATS stats;
hr = m_defragContext->GetStats(&stats);
if (FAILED(hr) || stats.BytesFreed == 0) {
m_defragContext->Release();
m_defragContext = nullptr;
return true;
}
return false; // More passes needed
}
private:
// D3D12 Objects & Synchronization
Microsoft::WRL::ComPtr<ID3D12Device> m_device;
Microsoft::WRL::ComPtr<ID3D12CommandQueue> m_copyQueue; // Dedicated copy queue
D3D12MA::Allocator* m_d3d12ma_allocator = nullptr;
Microsoft::WRL::ComPtr<ID3D12Fence> m_fence;
UINT64 m_fenceValue = 1;
HANDLE m_fenceEvent = nullptr;
// Copy-specific Command Objects
Microsoft::WRL::ComPtr<ID3D12CommandAllocator> m_copyAllocator;
Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList> m_copyCommandList;
bool m_hasPendingCopies = false;
// Upload Ring Buffer
Microsoft::WRL::ComPtr<ID3D12Resource> m_uploadBuffer;
uint8_t* m_uploadCpuPtr = nullptr;
size_t m_uploadBufferSize = 0;
size_t m_currentUploadOffset = 0;
struct UploadRange
{
size_t offset;
size_t size;
UINT64 fenceValue;
};
std::queue<UploadRange> m_inFlightUploadRanges;
// Mesh Handle Management
std::vector<GPUMeshHandle> m_meshHandles;
std::queue<u32> m_freeHandleIndices;
// Deferred Release Management
struct DeferredRelease
{
D3D12MA::Allocation* allocation;
UINT64 fenceValue;
};
std::queue<DeferredRelease> m_deferredReleaseQueue;
// Defragmentation
D3D12MA::DefragmentationContext* m_defragContext = nullptr;
// Thread Safety
mutable std::mutex m_mutex;
/**
* @brief Creates the upload buffer resource and maps it.
*/
bool InitializeUploadBuffer()
{
CD3DX12_HEAP_PROPERTIES uploadHeap(D3D12_HEAP_TYPE_UPLOAD);
CD3DX12_RESOURCE_DESC bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(m_uploadBufferSize);
HRESULT hr = m_device->CreateCommittedResource(
&uploadHeap,
D3D12_HEAP_FLAG_NONE,
&bufferDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&m_uploadBuffer));
if (FAILED(hr)) {
// Log error: Failed to create upload buffer
return false;
}
hr = m_uploadBuffer->Map(0, nullptr, reinterpret_cast<void**>(&m_uploadCpuPtr));
if (FAILED(hr)) {
// Log error: Failed to map upload buffer
m_uploadBuffer.Reset();
return false;
}
return true;
}
/**
* @brief Finds a contiguous block of memory in the ring buffer.
* Waits for the GPU if the buffer is full but space could be reclaimed.
*/
size_t FindSpaceInRingBuffer(size_t size)
{
// Align to D3D12's required alignment for copy source/dest.
size_t allocationOffset = Align(m_currentUploadOffset, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
if (allocationOffset + size > m_uploadBufferSize) // Needs to wrap
{
allocationOffset = 0; // Try from the beginning
// Check if the space we need at the beginning is still in-flight
if (!m_inFlightUploadRanges.empty())
{
const auto& oldestRange = m_inFlightUploadRanges.front();
if (oldestRange.offset < size)
{
// Space is in use, we must wait for the GPU to finish
const UINT64 fenceToWaitFor = oldestRange.fenceValue;
if (m_fence->GetCompletedValue() < fenceToWaitFor)
{
m_fence->SetEventOnCompletion(fenceToWaitFor, m_fenceEvent);
WaitForSingleObject(m_fenceEvent, INFINITE);
}
CleanUpCompletedOperations(); // Reclaim space
}
}
// After waiting and cleaning, check again.
if (!m_inFlightUploadRanges.empty() && m_inFlightUploadRanges.front().offset < size)
{
return (size_t)-1; // Failure
}
}
return allocationOffset;
}
/**
* @brief Waits for all submitted GPU work to complete.
*/
void Flush()
{
SubmitUploads(); // Ensure any pending work is on the GPU
if (!m_fence) return;
const UINT64 fenceToWaitFor = m_fenceValue - 1;
if (m_fence->GetCompletedValue() < fenceToWaitFor)
{
m_fence->SetEventOnCompletion(fenceToWaitFor, m_fenceEvent);
WaitForSingleObject(m_fenceEvent, INFINITE);
}
CleanUpCompletedOperations();
m_currentUploadOffset = 0;
}
/**
* @brief Gets a recycled or new ID for a mesh handle.
*/
u32 GetNewHandleID()
{
if (!m_freeHandleIndices.empty())
{
u32 id = m_freeHandleIndices.front();
m_freeHandleIndices.pop();
return id;
}
u32 id = static_cast<u32>(m_meshHandles.size());
m_meshHandles.emplace_back();
return id;
}
};
} // namespace Rtx
Example Usage in Game Loop
Below is an example of how to use the MeshUploadManager in a game loop, including initialization, uploading meshes, checking readiness, rendering, defragmentation, and cleanup.
#include "MeshUploadManager.hpp"
#include <iostream>
// Example renderer context (simplified)
struct RenderContext
{
Microsoft::WRL::ComPtr<ID3D12Device> device;
D3D12MA::Allocator* allocator = nullptr;
Rtx::MeshUploadManager meshM;
// Direct queue for rendering (not used by MeshUploadManager)
Microsoft::WRL::ComPtr<ID3D12CommandQueue> directQueue;
Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList> directCommandList;
Microsoft::WRL::ComPtr<ID3D12CommandAllocator> directAllocator;
// Frame synchronization
Microsoft::WRL::ComPtr<ID3D12Fence> renderFence;
UINT64 renderFenceValue = 0;
HANDLE renderFenceEvent = nullptr;
bool Initialize()
{
// Initialize D3D12 device, allocator, and queues (simplified)
// ... (Your D3D12 initialization code here)
// Initialize MeshUploadManager
if (!meshM.Initialize(allocator, device.Get())) {
std::cerr << "Failed to initialize MeshUploadManager\n";
return false;
}
// Initialize render fence
HRESULT hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&renderFence));
if (FAILED(hr)) return false;
renderFenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
if (!renderFenceEvent) return false;
return true;
}
void Shutdown()
{
meshM.Shutdown();
// ... (Your D3D12 shutdown code here)
CloseHandle(renderFenceEvent);
}
void RenderScene()
{
// Example rendering code
directAllocator->Reset();
directCommandList->Reset(directAllocator.Get(), nullptr);
// Transition resources to appropriate states for rendering
// ... (Your rendering code here)
// Use mesh handles that are ready
for (u32 meshId = 0; meshId < 10; ++meshId) // Example: 10 meshes
{
const Rtx::GPUMeshHandle* handle = meshM.GetMeshHandle(meshId);
if (handle && handle->IsReady(meshM.GetFence()))
{
// Bind vertex and index buffers
directCommandList->IASetVertexBuffers(0, static_cast<UINT>(handle->vertexBufferViews.size()), handle->vertexBufferViews.data());
if (handle->hasIndices)
{
directCommandList->IASetIndexBuffer(&handle->indexBufferView);
}
// Draw calls
// ... (Your draw calls here)
}
}
directCommandList->Close();
ID3D12CommandList* lists[] = { directCommandList.Get() };
directQueue->ExecuteCommandLists(1, lists);
// Signal render fence
directQueue->Signal(renderFence.Get(), renderFenceValue);
renderFenceValue++;
}
void PresentFrame()
{
// ... (Your swap chain present code here)
}
void MoveToNextFrame()
{
// Wait for the previous frame to complete
if (renderFence->GetCompletedValue() < renderFenceValue - 1)
{
renderFence->SetEventOnCompletion(renderFenceValue - 1, renderFenceEvent);
WaitForSingleObject(renderFenceEvent, INFINITE);
}
}
void OnResize()
{
// ... (Your resize handling code here)
}
};
int main()
{
RenderContext renderContext;
if (!renderContext.Initialize()) {
std::cerr << "Failed to initialize render context\n";
return 1;
}
// Example game loop
bool running = true;
bool stale = false; // Example flag for resize
u32 frameCount = 0;
while (running)
{
// Simulate loading new meshes (e.g., from a background thread or on demand)
if (frameCount < 10) // Example: Upload 10 meshes
{
Rtx::MeshDescription desc;
// Fill desc with your mesh data (interleaved or SoA)
// ... (Your mesh data setup here)
u32 meshId = renderContext.meshM.UploadMesh(desc);
if (meshId == UINT32_MAX) {
std::cerr << "Failed to upload mesh\n";
}
}
// Submit uploads to the GPU (do this early in the frame)
renderContext.meshM.SubmitUploads();
// Render ImGui (if applicable)
// ImGui::Render();
// Render the scene
renderContext.RenderScene();
// Render ImGui (if applicable)
// renderContext.RenderImGui();
// Present the frame
renderContext.PresentFrame();
// Move to the next frame
renderContext.MoveToNextFrame();
// Clean up completed upload operations (do this late in the frame)
renderContext.meshM.CleanUpCompletedOperations();
// Handle resize if needed
if (stale) {
renderContext.OnResize();
stale = false;
}
// Example: Perform defragmentation every 100 frames
if (frameCount % 100 == 0)
{
D3D12MA::DefragmentationPass defragPass;
while (!renderContext.meshM.Defragment(&defragPass))
{
// Process defragmentation passes
// Note: This might require GPU synchronization if moves are performed
}
}
// Example: Release a mesh (e.g., when no longer needed)
if (frameCount == 50) // Example: Release mesh 0 after 50 frames
{
renderContext.meshM.ReleaseMesh(0);
}
frameCount++;
}
// Shutdown
renderContext.Shutdown();
return 0;
}
Explanation of Usage
-
Initialization:
- The
RenderContext initializes the MeshUploadManager with the D3D12 device and allocator.
- The
MeshUploadManager creates its own copy queue, ensuring no conflicts with the renderer's direct queue.
-
Uploading Meshes:
UploadMesh is called to enqueue mesh data for upload. This can be done from any thread, as the method is thread-safe.
- The returned
meshId is used to track the mesh handle.
-
Submitting Uploads:
SubmitUploads is called early in the frame to submit copy commands to the GPU. This ensures uploads are processed before rendering.
-
Checking Readiness:
- The renderer checks if a mesh handle is ready using
handle->IsReady(meshM.GetFence()). Only ready handles are used for rendering.
-
Rendering:
- The renderer uses the vertex and index buffer views from ready handles to set up the input assembler and issue draw calls.
-
Cleanup:
CleanUpCompletedOperations is called late in the frame to reclaim upload buffer space and process deferred releases.
-
Defragmentation:
Defragment is called periodically (e.g., every 100 frames) to optimize GPU memory usage. Note that defragmentation might require additional GPU synchronization if moves are performed.
-
Releasing Meshes:
ReleaseMesh is called when a mesh is no longer needed, queuing its resources for safe deletion.
-
Shutdown:
Shutdown is called when the application exits, ensuring all resources are released.
Notes
- Error Handling: The example includes basic error handling, but you should add more robust logging and error recovery in a production environment.
- Synchronization: The example assumes a single-threaded game loop. If you use multiple threads (e.g., for loading), ensure all access to
MeshUploadManager is thread-safe.
- Defragmentation: The defragmentation example is simplified. In a real application, you might need to synchronize with the GPU to ensure moves are safe, especially if rendering is ongoing.
This rewritten version should be more robust, easier to use, and better integrated with the renderer, while maintaining the original mesh description formats.