Normalized z-depth shader (based on the cycles camera data node) I'm trying to create a shader that displays the normalized (0 to 1) camera Z-dpeth on top of the viewed object.

Yeah, I know I can easily do this in post with the normalize node if I render out the z depth pass, but I prefer to have this in a shader.

I tried to do this with an OSL script using the clamp function but it didn't really do what I wanted. See image below for clarification:


You can see the desired result on the right (achieved with compositor nodes), and the existing result on the left (with shader nodes).

This is the OSL script that didn't quite get me where I wanted, but might be a good start (I intended to use it between the camera data and emission nodes, the same way I use the normalize node in the compositor):

shader normalize_value(
    float inputValue = 0.0,
    output float normalizedValue = 0.0
){
    normalizedValue = clamp(inputValue, 0, 1);
}


I'm of course open to any other method, for instance involving other shader nodes (I couldn't find a way to get the same result but hey who knows!).
If it's ok to put in some values manually, you can use a Cycles shader like this. You have to know the distance of your scene from the camera and the scene size along camera z. In this example the object starts 3 units away from the camera and has a size along camera z of 2 units.

Input the values into the two red value nodes.