A long time ago, when I wrote the Deferred Rendering article, in the last chapter I mentioned adding transparent objects to the rendering pipeline. To do that, we would need to restore the depth buffer, as if the objects in the scene were there. This information was lost when we began applying the different passes of deferred rendering.
In this month’s sample, I’ll show you how to restore the depth buffer, using the information stored inside a depth texture.
To make an example out of this, the sample does the following things:
- Render a ship on the scene, once on a render target that holds the color, and once on a render target that holds depth information
- Apply post processing effects on the color texture. In this sample, I simply blur the image a little, and add sepia
- Restore the color information into the back buffer, and restore depth values into the depth buffer
- Draw another ship
If at step 3, we would only restore the color information, the resulting image would have incorrect object intersections. When doing post processing on the initial scene, we lose all depth information, so the ship drawn at step 4 would appear in front of everything else
By restoring the depth buffer also, we can see how parts of the post processed image that should appear in front of the ship drawn at step 4 actually appear in front of it.
To achieve this, we used the DEPTH pixel shader output semantic. This semantic is used in a pixel shader to write a specific value to the depth buffer. By taking this values from the depth texture generated at step 1, you can actually restore the contents of the depth buffer. The shader code that does this can be found in RestoreBuffers.fx.
void RestoreBuffersPixelShader(in float2 texCoord : TEXCOORD0,
out float4 color: COLOR0,
out float depth : DEPTH)
//write the color
color = tex2D(ColorSampler, texCoord);
//write the depth
depth = tex2D(DepthSampler, texCoord).r;
When running the sample, use the R keyboard key to toggle the restoration of the depth buffer, and the P key to toggle post processing.
The sample is written in 3.0 CTP, but the technique works just as well in 2.0
The sample can be downloaded here: DepthRecovery.zip