第一次深入研究非托管 DirectX 11(请多多包涵),有一个问题,尽管在论坛上被问了好几次,但仍然给我留下了疑问。
我正在开发作为应用程序,其中随着时间的推移将对象添加到场景中。在每个渲染循环中,我想收集场景中的所有顶点并重新使用单个顶点和索引缓冲区来渲染它们,以获得性能和最佳实践。我的问题是关于动态顶点和索引缓冲区的使用。当场景内容发生变化时,我无法完全理解它们的正确用法。
vertexBufferDescription.Usage = D3D11_USAGE_DYNAMIC;
vertexBufferDescription.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDescription.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexBufferDescription.MiscFlags = 0;
vertexBufferDescription.StructureByteStride = 0;
我应该在场景初始化时创建缓冲区并以某种方式在每一帧中更新它们的内容吗?如果是这样,我应该在缓冲区描述中设置什么 ByteSize?我用什么初始化它?
或者,我应该在第一次渲染场景时(第 1 帧)使用当前顶点数作为其大小来创建它吗?如果是这样,当我向场景中添加另一个对象时,我不需要重新创建缓冲区并将缓冲区描述的 ByteWidth 更改为新的顶点数吗?如果我的场景在每一帧上不断更新它的顶点,那么单个动态缓冲区的使用会以这种方式失去它的目的......
我一直在测试第一次渲染场景时初始化缓冲区,然后在每一帧上使用 Map/Unmap。我首先用所有场景对象填充向量列表,然后像这样更新资源:
void Scene::Render()
{
(...)
std::vector<VERTEX> totalVertices;
std::vector<int> totalIndices;
int totalVertexCount = 0;
int totalIndexCount = 0;
for (shapeIterator = models.begin(); shapeIterator != models.end(); ++shapeIterator)
{
Model* currentModel = (*shapeIterator);
// totalVertices gets filled here...
}
// At this point totalVertices and totalIndices have all scene data
if (isVertexBufferSet)
{
// This is where it copies the new vertices to the buffer.
// but it's causing flickering in the entire screen...
D3D11_MAPPED_SUBRESOURCE resource;
context->Map(vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &resource);
memcpy(resource.pData, &totalVertices[0], sizeof(totalVertices));
context->Unmap(vertexBuffer, 0);
}
else
{
// This is run in the first frame. But what if new vertices are added to the scene?
vertexBufferDescription.ByteWidth = sizeof(VERTEX) * totalVertexCount;
UINT stride = sizeof(VERTEX);
UINT offset = 0;
D3D11_SUBRESOURCE_DATA resourceData;
ZeroMemory(&resourceData, sizeof(resourceData));
resourceData.pSysMem = &totalVertices[0];
device->CreateBuffer(&vertexBufferDescription, &resourceData, &vertexBuffer);
context->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset);
isVertexBufferSet = true;
}
在渲染循环结束时,在跟踪每个对象的顶点的缓冲区位置的同时,我最终调用了 Draw():
context->Draw(objectVertexCount, currentVertexOffset);
}
我当前的实现导致我的整个场景闪烁。但没有内存泄漏。想知道这是否与我使用 Map/Unmap API 的方式有关?
此外,在这种情况下,何时调用 buffer->Release() 是理想的?提示或代码示例会很棒!提前致谢!