Getting pixel depth from v2f_img from OnRenderImage

Hi.

I want to write a full screen fog shader as a material using Graphics.Blit in the OnRenderImage. However the pixel pos passed from v2f_img doesn’t contain distance from camera information (as presumably it’s a render texture)

So my next thought was to try to use the Z Buffer. I tried enabling the camera writing to the Z buffer, and then trying to read that Z Buffer value as noted in this post (Depth buffer values read in FS extremely inaccurate (in just a few units distance) - Unity Engine - Unity Discussions) like so:

            inline float ZBufferRead(float4 projpos)
            {
                return LinearEyeDepth(UNITY_SAMPLE_DEPTH(tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(projpos))));
            }

and calling it via

float distFromCam = ZBufferRead(i.pos);

However I’m getting a uniform number back from the ZBufferRead call across all frags, and this value is somewhere around 2^14, so I assume I’m doing something incorrectly here.

Is my approach wrong or am I missing something?

thanks

(Entire Shader::slight_smile:

// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld'

Shader "Custom/Fog"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _FogCol("FogColor", COLOR) = (1,0,0,1)
        _FogDistance("Fog Distance", float) = 10
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }

        Pass
        {
            CGPROGRAM
            #pragma vertex vert_img
            #pragma fragment frag
           
            #include "UnityCG.cginc"
            uniform sampler2D _CameraDepthTexture;

            inline float ZBufferRead(float4 projpos)
            {
                return LinearEyeDepth(UNITY_SAMPLE_DEPTH(tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(projpos))));
            }

            sampler2D _MainTex;
            float4 _FogCol;
            float _FogDistance;
           
            fixed4 frag (v2f_img i) : COLOR
            {
                fixed4 baseCol = tex2D(_MainTex, i.uv);
                float distFromCam = ZBufferRead(i.pos);
                float colorLerp = distFromCam / _FogDistance;
                fixed4 color = lerp(baseCol, _FogCol, colorLerp);
                return color;
            }
            ENDCG
        }
    }
}

You also need the vert function and v2f struct from that post you linked. That linked post passes a “projPos” to the fragment shader which is what you need to do as well.