Here's a complete implementation of MeshUploadManager with its own command queue, proper synchronization, and usage examples. The mesh description format remains unchanged, and we use D3D12 Memory Allocator:
#include "pch.hpp"
#include "D3D12MemAlloc.hpp"
#include <vector>
#include <queue>
#include <mutex>
#include <atomic>
namespace Rtx {
class MeshUploadManager {
public:
struct GPUMeshHandle {
D3D12MA::Allocation* allocation = nullptr;
Microsoft::WRL::ComPtr<ID3D12Resource> resource;
std::vector<D3D12_VERTEX_BUFFER_VIEW> vertexBufferViews;
D3D12_INDEX_BUFFER_VIEW indexBufferView;
bool hasIndices = false;
UINT64 fenceValue = 0;
u32 id = UINT32_MAX;
bool IsReady(ID3D12Fence* fence) const {
return fenceValue == 0 || (fence && fence->GetCompletedValue() >= fenceValue);
}
bool IsValid() const {
return id != UINT32_MAX && resource != nullptr;
}
};
MeshUploadManager() = default;
~MeshUploadManager() { Shutdown(); }
void Initialize(ID3D12Device* device, D3D12MA::Allocator* allocator, size_t uploadBufferSize = 256 * 1024 * 1024) {
std::lock_guard<std::mutex> lock(mtx);
// Create copy command queue
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_COPY;
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&m_cmdQueue));
// Create command allocator and command list
device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY,
IID_PPV_ARGS(&m_cmdAllocator));
device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY,
m_cmdAllocator.Get(), nullptr,
IID_PPV_ARGS(&m_cmdList));
m_cmdList->Close();
// Create fence and event
device->CreateFence(0, D3D12_FENCE_FLAG_NONE,
IID_PPV_ARGS(&m_fence));
m_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
// Store device and allocator
m_device = device;
m_allocator = allocator;
m_uploadBufferSize = uploadBufferSize;
// Initialize upload buffer
InitializeUploadBuffer();
}
void Shutdown() {
std::lock_guard<std::mutex> lock(mtx);
Flush();
if (m_uploadBuffer) {
m_uploadBuffer->Unmap(0, nullptr);
m_uploadBuffer.Reset();
}
m_cmdList.Reset();
m_cmdAllocator.Reset();
m_cmdQueue.Reset();
m_fence.Reset();
CloseHandle(m_fenceEvent);
m_fenceEvent = nullptr;
// Clean up all resources
for (auto& handle : m_meshHandles) {
if (handle.IsValid()) {
handle.allocation->Release();
handle.resource.Reset();
}
}
m_meshHandles.clear();
m_deferredReleases.clear();
}
u32 UploadMesh(const MeshDescription& desc) {
std::lock_guard<std::mutex> lock(mtx);
// Reset command list if needed
if (m_hasPendingUploads) {
m_cmdAllocator->Reset();
m_cmdList->Reset(m_cmdAllocator.Get());
}
// Calculate required size
size_t vertexSize = 0, indexSize = desc.indices.size;
// ... (same size calculation as before)
// Allocate space in upload buffer
size_t offset = FindSpaceInRingBuffer(totalSize);
if (offset == SIZE_MAX) return UINT32_MAX;
// Create destination resource
GPUMeshHandle handle;
D3D12MA::ALLOCATION_DESC allocDesc = {};
allocDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;
CD3DX12_RESOURCE_DESC bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(totalSize);
HRESULT hr = m_allocator->CreateResource(
&allocDesc, &bufferDesc,
D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
&handle.allocation, IID_PPV_ARGS(&handle.resource));
if (FAILED(hr)) return UINT32_MAX;
// Record copy commands
// ... (same copy operations as before)
// No resource barrier here - state remains COPY_DEST
// Finalize upload
m_cmdList->Close();
m_hasPendingUploads = true;
handle.fenceValue = m_currentFence++;
handle.id = GetNewHandleID();
m_meshHandles[handle.id] = handle;
m_inFlightRanges.push({offset, totalSize, handle.fenceValue});
return handle.id;
}
void SubmitUploads() {
std::lock_guard<std::mutex> lock(mtx);
if (!m_hasPendingUploads) return;
// Execute command list
ID3D12CommandList* lists[] = { m_cmdList.Get() };
m_cmdQueue->ExecuteCommandLists(1, lists);
// Signal fence
m_cmdQueue->Signal(m_fence.Get(), m_currentFence);
m_hasPendingUploads = false;
}
void CleanUpCompletedOperations() {
std::lock_guard<std::mutex> lock(mtx);
const UINT64 completed = m_fence->GetCompletedValue();
// Reclaim upload buffer space
while (!m_inFlightRanges.empty() &&
m_inFlightRanges.front().fence <= completed) {
m_inFlightRanges.pop();
}
// Release completed resources
while (!m_deferredReleases.empty() &&
m_deferredReleases.front().fence <= completed) {
auto& rel = m_deferredReleases.front();
rel.allocation->Release();
rel.resource.Reset();
m_deferredReleases.pop();
}
}
const GPUMeshHandle* GetMeshHandle(u32 id) {
std::lock_guard<std::mutex> lock(mtx);
auto it = m_meshHandles.find(id);
return (it != m_meshHandles.end() && it->second.IsValid())
? &it->second
: nullptr;
}
void ReleaseMesh(u32 id) {
std::lock_guard<std::mutex> lock(mtx);
auto it = m_meshHandles.find(id);
if (it == m_meshHandles.end() || !it->second.IsValid()) return;
m_deferredReleases.push({
it->second.allocation,
it->second.resource,
m_currentFence // Release after next fence
});
m_meshHandles.erase(it);
}
bool IsHandleReady(u32 id) {
std::lock_guard<std::mutex> lock(mtx);
auto it = m_meshHandles.find(id);
if (it == m_meshHandles.end()) return false;
return it->second.IsReady(m_fence.Get());
}
private:
// ... (helper methods like InitializeUploadBuffer, FindSpaceInRingBuffer, GetNewHandleID)
ID3D12Device* m_device = nullptr;
D3D12MA::Allocator* m_allocator = nullptr;
Microsoft::WRL::ComPtr<ID3D12CommandQueue> m_cmdQueue;
Microsoft::WRL::ComPtr<ID3D12CommandAllocator> m_cmdAllocator;
Microsoft::WRL::ComPtr<ID3D12CommandList> m_cmdList;
Microsoft::WRL::ComPtr<ID3D12Resource> m_uploadBuffer;
uint8_t* m_uploadData = nullptr;
size_t m_uploadBufferSize = 0;
size_t m_currentUploadOffset = 0;
std::mutex mtx;
std::unordered_map<u32, GPUMeshHandle> m_meshHandles;
std::queue<UploadRange> m_inFlightRanges;
std::queue<DeferredRelease> m_deferredReleases;
Microsoft::WRL::ComPtr<ID3D12Fence> m_fence;
HANDLE m_fenceEvent = nullptr;
UINT64 m_currentFence = 1;
bool m_hasPendingUploads = false;
};
// Game Loop Usage Example
void GameLoop() {
// Initialization
MeshUploadManager uploadMgr;
uploadMgr.Initialize(device, allocator);
while (!exitCondition) {
// 1. Record commands for this frame
{
// Upload new meshes (thread-safe)
u32 meshId = uploadMgr.UploadMesh(meshDesc);
// Submit upload commands
uploadMgr.SubmitUploads();
}
// 2. Check if previous uploads are complete
if (uploadMgr.IsHandleReady(meshId)) {
// 3. Transition resource state in main command list
CD3DX12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(
uploadMgr.GetMeshHandle(meshId)->resource.Get(),
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
mainCmdList->ResourceBarrier(1, &barrier);
// 4. Use the mesh in rendering commands
RenderMesh(meshId);
}
// 5. Present frame
PresentFrame();
// 6. Clean up completed operations
uploadMgr.CleanUpCompletedOperations();
// 7. Release meshes no longer needed
uploadMgr.ReleaseMesh(meshId);
// Move to next frame
MoveToNextFrame();
}
}
Key Features:
- Dedicated Upload Queue: Uses a separate command queue for copy operations
- Thread Safety: All methods use a mutex for synchronization
- Resource Management:
- Automatic ring buffer management
- Deferred resource release using fences
- D3D12 Memory Allocator integration
- Fence-Based Synchronization:
- Tracks upload completion with fences
- Provides
IsHandleReady() for application to check status
- State Transition Responsibility:
- Upload manager leaves resources in COPY_DEST state
- Main rendering code must transition to appropriate state
Usage Order:
- Initialize: Once during startup
- UploadMesh: When new meshes need uploading (can be called multiple times per frame)
- SubmitUploads: Once per frame before rendering
- IsHandleReady: Before using a mesh in rendering commands
- CleanUpCompletedOperations: Once per frame after presentation
- ReleaseMesh: When meshes are no longer needed
Important Notes:
- State Transitions: The main rendering command list must handle resource state transitions from COPY_DEST to VERTEX_BUFFER/INDEX_BUFFER
- Fence Synchronization: The main application should wait on the upload manager's fence if needed
- Thread Safety: While the manager is thread-safe, concurrent uploads from multiple threads may require additional synchronization
- Error Handling: Add proper error checking and logging in production code
This implementation provides a robust asynchronous upload system that integrates with D3D12's memory allocator and handles resource synchronization properly while maintaining the original mesh description format.