# How do I set up a depth buffer in SharpDX?

I draw some instanced cubes, but when i rotate the camera (or the world) some cubes that should be behind other cubes are drawn before the cubes.

I already had this issue a long time before and i remembered that is was because the depth buffer.

I don't know how to set up a depth buffer in SharpDX.

My current trial:

DepthStencilView depthStencilView;


Init

var zBufferTextureDescription = new Texture2DDescription
{
Format = Format.D16_UNorm,
ArraySize = 1,
MipLevels = 1,
Width = this.RenderWindow.ClientSize.Width,
Height = this.RenderWindow.ClientSize.Height,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Default,
BindFlags = BindFlags.DepthStencil,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None
};
using (var zBufferTexture = new Texture2D(Device, zBufferTextureDescription))
depthStencilView = new DepthStencilView(Device, zBufferTexture);

DeviceContext.OutputMerger.SetTargets(depthStencilView, RenderTargetView);


Draw

//ClearRenderTargetView
DeviceContext.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth, 1f, 0);
//DrawInstanced(...);


My question: what steps do i have to do, to set up a depth buffer correctly?

(I don't use SharpDX.Toolkit)

• Create a depth-stencil state object and assign that to the output merger as well. You don't appear to be doing this. You'll need SharpDX's DepthStencilStateDescription for this, and to assign it via DeviceContext.OutputMerger.SetDepthStencilState or something.