I want to update the vertices of a DirectX11 ID3D11Buffer, but it is not working. I followed the guide How to use dynamic resources from Microsoft.
This is my code for the buffer:
// Create vertex buffer
int verticesAmount = 5;
pVertices = new XMFLOAT3[verticesAmount];
pVertices[0] = XMFLOAT3( -0.1f, -0.1f, 0 );
pVertices[1] = XMFLOAT3( -0.1f, 0.1f, 0 );
pVertices[2] = XMFLOAT3( 0.1f, 0.1f, 0 );
pVertices[3] = XMFLOAT3( 0.1f, -0.1f, 0 );
pVertices[4] = XMFLOAT3( -0.1f, -0.1f, 0 );
D3D11_BUFFER_DESC bd;
ZeroMemory( &bd, sizeof(bd) );
bd.Usage = D3D11_USAGE_DYNAMIC;
bd.ByteWidth = sizeof( XMFLOAT3 ) * verticesAmount;//sizeof(vertices);
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;
bd.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA InitData;
ZeroMemory( &InitData, sizeof(InitData) );
InitData.pSysMem = pVertices;
InitData.SysMemPitch = 0;
InitData.SysMemSlicePitch = 0;
result = pDevice->CreateBuffer( &bd, &InitData, &pLineStripBuffer )
This is my code when updating:
//pVertices[2].x += 0.1f; commented because I want to test whether it updates at all
D3D11_MAPPED_SUBRESOURCE mappedResource;
ZeroMemory(&mappedResource, sizeof(D3D11_MAPPED_SUBRESOURCE));
// Disable GPU access to the vertex buffer data.
pContext->Map(pLineStripBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
// Update the vertex buffer here.
memcpy(mappedResource.pData, pVertices, 5);
// Reenable GPU access to the vertex buffer data.
pContext->Unmap(pLineStripBuffer, 0)
This is what it looks like when the update code above is commented out:
This is what is looks like uncommented:
The screenshot of the updated buffer should be the same as the one above because the vertices didn't change positions.
It turned out that the size memcpy was to small. The code in the question only copies the x of the first XMFLOAT3 vector. When I would render the buffer, the first line would go from the center to x of the first vector.
memcpy(mappedResource.pData, pVertices, 5 * sizeof(XMFLOAT3));