I had no idea Unity’s graphics pipeline was extensible like this. Very cool, thanks for the pointers. Here are some notes on what I ended up doing for anyone else reading this in the future. I’m still trying to debug one issue but I’ll post about that next.
Unity supports multiple rendering pipelines. The two built-ins are forward and deferred. Depending on which pipeline you’re using for you project, you can bind to different CameraEvents.
credit
private Camera cam;
private CommandBuffer cbuf;
...
void OnEnable()
{
this.cam.AddCommandBuffer(CameraEvent.AfterForwardOpaque, this.cbuf);
}
The output of draw commands will be written to the color buffer. If your shader is writing depth information it can be half4 encoded into the color channels. You can set a render target if you need to capture the depth texture for usage in a later shader.
private RenderTexture rt;
...
void Update()
{
this.cbuf.Clear();
this.rt = RenderTexture.GetTemporary(this.cam.pixelWidth, this.cam.pixelHeight, 16, RenderTextureFormat.Depth);
this.cbuf.SetRenderTarget(this.rt);
this.cbuf.ClearRenderTarget(true, true, Color.black);
foreach (Renderer r in this.ship.GetComponentsInChildren<Renderer>())
{
if (r.enabled)
{
this.cbuf.DrawRenderer(r, this.depthMat);
}
}
}
When allocating a RenderTexture with a depth format specified, it appears to be the case that the RenderTexture’s color buffer is allocated per. the format specification – in the case of the snippet above, 16 bits per pixel.
The size of the depth buffer values (needs?) to match the output of the fragment shader type – so half4 for 16 bit.
In my case, I want to use this depth buffer in a full screen post processing shader. To do that I just bind the the render texture to the fullscreen shader material
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
this.sfMat.SetTexture("_DepthTex", this.rt);
Graphics.Blit(source, destination, this.sfMat);
RenderTexture.ReleaseTemporary(this.rt);
}
Lastly, use SAMPLE_DEPTH_TEXUTURE to pull a float from the depth texture.
float depth = SAMPLE_DEPTH_TEXTURE(_DepthTex, i.uv);