#include #include #include #include namespace XCEngine { namespace RHI { StaticMeshComponent::StaticMeshComponent() { } StaticMeshComponent::~StaticMeshComponent() { if (m_vertexBuffer) { delete m_vertexBuffer; } for (auto& pair : m_subMeshes) { delete pair.second; } } bool StaticMeshComponent::Initialize(ICommandList* commandList, const char* filePath) { D3D12CommandList* d3d12CmdList = static_cast(commandList); D3D12Device* device = d3d12CmdList->GetDevice(); FILE* file = nullptr; if (fopen_s(&file, filePath, "rb") != 0) { return false; } int vertexCount = 0; fread(&vertexCount, 4, 1, file); m_vertexCount = vertexCount; MeshVertex* vertices = new MeshVertex[vertexCount]; fread(vertices, sizeof(MeshVertex), vertexCount, file); CreateVertexBuffer(device, commandList, vertices, sizeof(MeshVertex) * vertexCount, sizeof(MeshVertex), &m_vertexBuffer); delete[] vertices; while (!feof(file)) { int nameLength = 0; fread(&nameLength, 4, 1, file); if (feof(file)) break; char name[256] = {0}; fread(name, 1, nameLength, file); int indexCount = 0; fread(&indexCount, 4, 1, file); uint32_t* indices = new uint32_t[indexCount]; fread(indices, sizeof(uint32_t), indexCount, file); IIndexBuffer* indexBuffer = nullptr; CreateIndexBuffer(device, commandList, indices, sizeof(uint32_t) * indexCount, &indexBuffer); delete[] indices; SubMesh* submesh = new SubMesh(); submesh->indexBuffer = indexBuffer; submesh->indexCount = indexCount; m_subMeshes[std::string(name)] = submesh; } fclose(file); return true; } void StaticMeshComponent::Render(ICommandList* commandList) { if (!m_vertexBuffer) return; commandList->SetVertexBuffer(0, m_vertexBuffer, 0, sizeof(MeshVertex)); if (m_subMeshes.empty()) { commandList->DrawInstanced(m_vertexCount, 1, 0, 0); } else { for (auto& pair : m_subMeshes) { SubMesh* submesh = pair.second; commandList->SetIndexBuffer(submesh->indexBuffer, 0); commandList->DrawIndexedInstanced(submesh->indexCount, 1, 0, 0, 0); } } } } // namespace RHI } // namespace XCEngine