话说这两天我写程序遇到一个bug,是关于如何创建的ID3D11Buffer的应该以一种怎样的方式在每帧渲染进行缓存资源的更新
我总结为下:
第一,当buffer是CPU访问写并且是动态的时候
//填充(顶点)缓存形容结构体和子资源数据结构体,并创建顶点缓存(这里用的是动态缓存)
D3D11_BUFFER_DESC vertexBufferDesc;
vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexBufferDesc.ByteWidth = sizeof(Vertex) * mVertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
这里此时每帧进行该缓存资源的更新应该用MAP和UMAP进行资源更新
vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
//锁定顶点缓存为了可以进行写入(动态缓存不能用UpdateSubResources写入)
D3D11_MAPPED_SUBRESOURCE mappedResource;
HR(d3dDeviceContext->Map(md3dVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));
//获取指向顶点缓存的指针
Vertex* verticesPtr;
verticesPtr = (Vertex*)mappedResource.pData;
//把数据复制进顶点缓存
memcpy(verticesPtr, (void*)vertexs, (sizeof(Vertex) * mVertexCount));
//解锁顶点缓存
d3dDeviceContext->Unmap(md3dVertexBuffer, 0);
第二,当buffer不是CPU访问写并且是默认的时候,用updatesubResouce
//,设置(常量)缓存形容结构体,并创建常量缓存
D3D11_BUFFER_DESC matrixBufferDesc;
ZeroMemory(&matrixBufferDesc, sizeof(matrixBufferDesc));
matrixBufferDesc.Usage =D3D11_USAGE_DEFAULT; //缓存
matrixBufferDesc.ByteWidth = sizeof(CBMatrix); //结构体大小,必须为16字节倍数
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = 0; //CPU访问写
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;
HR(d3dDevice->CreateBuffer(&matrixBufferDesc, NULL, &mCBMatrixBuffer));
这里 matrixBufferDesc.Usage =D3D11_USAGE_DEFAULT; //缓存
matrixBufferDesc.CPUAccessFlags = 0; //CPU访问写
CBMatrix cb;
XMMATRIX worldMa = XMMatrixTranspose(worldMatrix);
XMMATRIX viewMa = XMMatrixTranspose(viewMatrix);
XMMATRIX ProjMa = XMMatrixTranspose(ProjMatrix);
cb.mWorldMatrix = worldMa;
cb.mViewMatrix = viewMa;
cb.mProjMatrix = ProjMa;
d3dDeviceContext->UpdateSubresource(mCBMatrixBuffer, 0, NULL, &cb, 0, 0);
//上面创建Buffer设置的标志位不一样,更新资源的方式也不一样,如果不按指定方式更新资源将会造成资源无法写入缓存的后果
更具体的等我水平提高研究过在补充后续内容,更新每帧动态变化的尽量还是用MAP和UMAP吧