Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Resolved Sampling a depth buffer (without a camera)

Discussion in 'General Graphics' started by Neto_Kokku, Feb 22, 2022.

  1. Neto_Kokku

    Neto_Kokku

    Joined:
    Feb 15, 2018
    Posts:
    1,751
    I'm using Graphics.ExecuteCommandBuffer() to draw some meshes to a custom low res render target, no cameras involved. The goal is to use the depth buffer to generate a depth pyramid for occlusion culling.

    Except Unity just won't let me get the render target depth buffer data no matter what. All CommandBuffer APIs I tried passing the RenderTexture.depthBuffer to end up using the color attachment instead. This includes trying to bind the depthBuffer as a shader texture parameter (global, or compute shader param), trying to pass it as source to CommandBuffer.CopyTexture().

    Is there any trick to this that doesn't involve setting up an actual camera to have Unity magically invoke CopyDepth to produce the _CameraDepthTexture?
     
  2. Neto_Kokku

    Neto_Kokku

    Joined:
    Feb 15, 2018
    Posts:
    1,751
    Found it. Creating two separate RenderTextures, one for color and one for depth (colorFormat = RenderTextureFormat.Depth), both with depth bits set to zero, then binding them using:

    Code (CSharp):
    1. cb.SetRenderTarget(colorTarget, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare, depthTarget, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
    ...did the trick. The 2nd RenderTexture is used directly as depth attachment, so it can be used correctly by subsequent draw/dispatch calls.

    Still angry that RenderTexture.depthBuffer did not work as advertised, and the "correct" way is the non-obvious one.
     
    poka_ and mabulous like this.