How do I write ShaderMaterial depth to DepthRenderer (infinite far plane)

Hello everyone!

I am having issues writing to a DepthRenderer with a ShaderMaterial when the far plane is at infinity (maxZ=0)

This is a follow-up to a previous question that did not use the far plane at infinity: How to write ShaderMaterial to DepthRenderer

TLDR: writing the ShaderMaterial’s depth to a DepthRenderer required another material tailored for that purpose.

Now when setting maxZ=0, this approach no longer works as nothing is written on the DepthRenderer:

I looked for inspiration in the engine code and found the same vDepthMetric code:

I don’t understand what BabylonJS materials do differently to work with maxZ=0, does anyone know what I am missing?

cc @Evgeni_Popov

1 Like

It’s expected, because the depth is converted from [-near,+far] to [0,1] (which is the value generated by the shader) by doing (z+near)/(near+far). But with an infinite far plane, you will get always 0 ((z+near)/∞ = 0). In fact, you get 1 because when the far plane is at infinity, we set far (=maxZ) to 0, but the result is the same, you get a fixed constant depth value whatever the Z coordinate is.

You can’t get meaningfull screen depth values in this case, only depth in camera space is something that could be of any use (that, is the Z coordinate in camera view space). That’s something you can enable in the depth renderer by passing true for the storeCameraSpaceZ parameter of the depth renderer constructor. When you do this, STORE_CAMERASPACE_Z is defined in the shader, so you should do the same thing in your custom shader:

You will have to come very close to the plane to see the green parts, because the Z values goes from near (0.01) to +∞ and you quickly go above 1 when you move back from the plane (which yields a yellow in the texture, since we force green to always be 1 in the emissive color).

2 Likes

That makes a ton of sense, thanks for your inexhaustible knowledge of these things :slight_smile:

1 Like