0
\$\begingroup\$

I am new in Unity and now only studying for my work project. I need help with computing real distances from depth values. Can't figure it out. My shader is:

Shader "Custom/MyDepthShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        
    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert // compile function vert as vertex shader
            #pragma fragment frag // compile function frag as fragment shader

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex;
            sampler2D _CameraDepthTexture;

            fixed4 frag (v2f i) : SV_Target
            {
                float depth = tex2D(_CameraDepthTexture, i.uv).r;
                depth = Linear01Depth(depth);
                depth = depth * _ProjectionParams.z;
                return depth;
            }
            ENDCG
        }
    }
}

I Blit then these values from renderTexture to texture2D and use function GetPixel(i,j). Knowing, that a cube is at 1.5 units distance from camera I can't get this value from depth texture. Thank you for your help. Now I suspect that I have got distance values, but they are biased by 0.5 for some reason... Can anyone explain this as well?

I found how to get distances from depth texture, so basically I can answer this question, but there is still unexplained bias in measurements.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

As described in the docs, Linear01Depth() is for getting the depth as a fraction of the way between the near and far planes.

To get an eye space depth value in world units, you want LinearEyeDepth()

\$\endgroup\$
3
  • \$\begingroup\$ Thank you for your comment. I already applied this function and values seem to be right, except that they are biased by 0.5 units. For example I know that cube is 5 meters from camera, but value I have got is 4.5 \$\endgroup\$ Commented Jun 29, 2020 at 10:47
  • \$\begingroup\$ Because the near face of an unscaled Unity cube is 0.5 units away from its center point? \$\endgroup\$
    – DMGregory
    Commented Jun 29, 2020 at 10:48
  • \$\begingroup\$ Ah, okei. I was so stupid. Thank you so much. I am still studying in hurry Unity programming. You helped me a lot! \$\endgroup\$ Commented Jun 29, 2020 at 10:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .