0
\$\begingroup\$

I'm a total beginner with Directx/3D programming. I need help with implementing hardware instancing on Directx 11. I'm trying to render multiple cubes on the screen, to create some sort of Minecraft-esque voxel engine. The problem is, I don't know where to start to achieve this. This is how my "render frame" function looks:

void RenderFrame(void)
{
    D3DXMATRIX matView, matProjection;
    D3DXMATRIX matFinal;

    // create a view matrix
    D3DXMatrixLookAtLH(&matView,
    &D3DXVECTOR3(0.0f, 9.0f, 24.0f),   // the camera position
    &D3DXVECTOR3(0.0f, 0.0f, 0.0f),    // the look-at position
    &D3DXVECTOR3(0.0f, 1.0f, 0.0f));   // the up direction

    // create a projection matrix
    D3DXMatrixPerspectiveFovLH(&matProjection,
    (FLOAT)D3DXToRadian(45),                    // field of view
    (FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, // aspect ratio
    1.0f,                                       // near view-plane
    100.0f);                                    // far view-plane

    // create the final transform
    matFinal = matView * matProjection;

    devcon->ClearRenderTargetView(backbuffer, D3DXCOLOR(0.0f, 0.2f, 0.4f, 1.0f));

    devcon->ClearDepthStencilView(zbuffer, D3D11_CLEAR_DEPTH, 1.0f, 0);

    UINT stride = sizeof(VERTEX);
    UINT offset = 0;
    devcon->IASetVertexBuffers(0, 1, &pVBuffer, &stride, &offset);
    devcon->IASetIndexBuffer(pIBuffer, DXGI_FORMAT_R32_UINT, 0);
    devcon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    devcon->UpdateSubresource(pCBuffer, 0, 0, &matFinal, 0, 0);
    devcon->DrawIndexed(24, 0, 0);

    swapchain->Present(0, 0);
}

Notice that there's a single vertex buffer containing the verteces of a cube, and index buffer containing its indeces. I want to render many (5000+) cubes on the screen at once on a single draw call, without performance issues, so I know instancing is the way to go, but I don't know how to implement it in my code. What changes do I need to do to my code in order to display multiple instances of the cube?

Thanks in advance!

\$\endgroup\$
  • \$\begingroup\$ Instancing will not be enough to get good performance from a large voxel world. Instead, you should be looking into combining cubes into chunk meshes, with invisible faces removed, then rendering these chunks. You can also apply culling on the chunks to further reduce unnecessary drawing. \$\endgroup\$ – DMGregory Apr 20 at 10:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.