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;


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);


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

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

(I don't use SharpDX.Toolkit)


1 Answer 1


To configure depth-stencil buffers, you need to do the following:

  • Create a depth-stencil resource (a 2D texture) and an associated view, and bind the view to the output merger state; you're already doing this in the code you posted.

  • 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.

  • Make sure to clear the buffer when appropriate, usually before rendering a frame. You're doing this too.

Basically it seems like you are only missing the step involving configuration and attaching the depth-stencil state; the state object controls whether or not the depth testing is enabled, what comparison function is used, and all that other useful stuff.

The MSDN has a good overview of the process that includes reasonable default values (for example, it's odd that you're trying to use a multi-sampled sample description in your depth-stencil texture resource). SharpDX is just a wrapper around the native API, so if you are familiar enough with the nomenclature mapping it uses to rename all the native API interfaces, you can usually just follow along with information for the native API and translate it.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .