Reputation:
I am experimenting with Direct3D 11 API and I am not very familiar with D3D. I have always OpenGL for my projects. So far I've managed to draw simple triangle. Now I want to draw some more complicated objects but there is a problem. I don't know how to enable depth test (or does it use totally different concept?). I am getting something like this:
I initialize D3D like this:
DXGI_SWAP_CHAIN_DESC swapChainDesc;
ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
swapChainDesc.BufferCount = 1;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.OutputWindow = hWnd;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.Windowed = true;
HRESULT result = D3D11CreateDeviceAndSwapChain(
NULL,
D3D_DRIVER_TYPE::D3D_DRIVER_TYPE_HARDWARE,
NULL,
0,
NULL,
0,
D3D11_SDK_VERSION,
&swapChainDesc,
&SwapChain,
&Device,
NULL,
&DeviceContext);
if (result != S_OK)
throw "Direct3D initialization error";
ID3D11Texture2D *backBufferTexture;
result = SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID *)&backBufferTexture);
if (result != S_OK)
{
[error handling here]
}
result = Device->CreateRenderTargetView(backBufferTexture, NULL, &BackBuffer);
backBufferTexture->Release();
if (result != S_OK)
{
[error handling here]
}
DeviceContext->OMSetRenderTargets(1, &BackBuffer, NULL);
After that comes shader loading, matrix setup, vertex and index buffers initialization. I bet there is something missing here but don't know what.
Upvotes: 1
Views: 2594
Reputation:
Ok, I have found out what was missing. Depth buffer needs to be created explicitly. What's interesting, depth and stencil buffers are merged into one buffer.
D3D11_TEXTURE2D_DESC depthTextureDesc;
ZeroMemory(&depthTextureDesc, sizeof(depthTextureDesc));
depthTextureDesc.Width = width;
depthTextureDesc.Height = height;
depthTextureDesc.MipLevels = 1;
depthTextureDesc.ArraySize = 1;
depthTextureDesc.SampleDesc.Count = 1;
depthTextureDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthTextureDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
ID3D11Texture2D *DepthStencilTexture;
result = Device->CreateTexture2D(&depthTextureDesc, NULL, &DepthStencilTexture);
if (result != S_OK) [error handling code]
D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
ZeroMemory(&dsvDesc, sizeof(dsvDesc));
dsvDesc.Format = depthTextureDesc.Format;
dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
result = Device->CreateDepthStencilView(DepthStencilTexture, &dsvDesc, &DepthBuffer);
DepthStencilTexture->Release();
if (result != S_OK) [error handling code]
DeviceContext->OMSetRenderTargets(1, &BackBuffer, DepthBuffer);
Of course, clearing of that buffer is needed every frame.
DeviceContext->ClearDepthStencilView(DepthBuffer, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
Upvotes: 3