Using depth from rendertarget in shader

Is there any direct way to use the depth buffer assigned to a rendertarget in a shader? The depth buffer of the current camera is automatically set as _CameraDepthTexture. Is there any way to manually set a depth buffer as a global texture?

In my case I’ve rendered a prepass from a different view with both color and depth information. And I want to use both the color and depth information from this prepass in the main pass. The color part is easy, but for the depth part it seems I have to copy it to yet another rendertexture just so I have a way to set it as global texture.

Ok, I’ve managed to solve this, but it will only work if depth textures are supported by the platform.

In a few steps:

  1. Create a RenderTexture c with 0 depth bits of your format of choice.
  2. Create a RenderTexture d with 16 or 24 depth bits of the RenderTextureFormat.Depth format.
  3. Set the combination of the two on the camera with camera.SetTargetBuffers(c.colorBuffer, d.depthBuffer).
  4. Let the camera render as usual.
  5. Pass the RenderTexture d as a sampler2D to your shader.
  6. Sample RenderTexture d as you would the standard depth buffer. (SAMPLE_DEPTH_TEXTURE(_DepthTex, uv))

For the pics or it didn’t happen section. Here’s a planar reflection overlay, where the reflection itself is the difference between two depth buffers, showing the distance from the reflective surface to the surface visible in the reflection.

4 Likes