title: Directx 11 Z-Buffer not rendering and flickering
body: <p>I'm trying to setup a Z-buffer with DirectX 11 but it's not working as expected. Without the Z-Buffer it shows the further objects on top of the closer ones, as you'd expect. With the buffer it shows a blank screen then flickers through bits when moving it around as shown in <a href="https://dl.dropboxusercontent.com/u/2873587/ZBufferFail.mp4" rel="nofollow">this video</a>.</p>
  
  <p>Here's my Z Buffer initialization.</p>
  
  <pre><code>// Create a Z buffer texture
  D3D11_TEXTURE2D_DESC tex2dDesc;
  ZeroMemory(&amp;tex2dDesc, sizeof(tex2dDesc));
  
  tex2dDesc.Width = width;
  tex2dDesc.Height = height;
  tex2dDesc.ArraySize = 1;
  tex2dDesc.MipLevels = 1;
  tex2dDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
  tex2dDesc.SampleDesc.Count = sd.SampleDesc.Count;
  tex2dDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  tex2dDesc.Usage = D3D11_USAGE_DEFAULT;
  
  ID3D11Texture2D *pZBufferTexture;
  hr = g_pD3DDevice-&gt;CreateTexture2D(&amp;tex2dDesc, NULL, &amp;pZBufferTexture);
  
  if(FAILED(hr)) return hr;
  
  // Create the Z buffer
  D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
  ZeroMemory(&amp;dsvDesc, sizeof(dsvDesc));
  
  dsvDesc.Format = tex2dDesc.Format;
  dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
  
  g_pD3DDevice-&gt;CreateDepthStencilView(pZBufferTexture, &amp;dsvDesc, &amp;g_pZBuffer);
  pZBufferTexture-&gt;Release();
  
  
  // Set the render target view
  g_pImmediateContext-&gt;OMSetRenderTargets(1, &amp;g_pBackBufferRTView, g_pZBuffer);
  </code></pre>
  
  <p>Here's what runs in the rendering.</p>
  
  <pre><code>g_pImmediateContext-&gt;ClearRenderTargetView(g_pBackBufferRTView, g_clear_colour);
  
  g_pImmediateContext-&gt;ClearDepthStencilView
      (g_pZBuffer, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
  </code></pre>
  
  <p>I'm still much of a beginner when it comes to DirectX 11 so any help would be greatly appreciated. If more code is required I can provide.</p>