Shader "Hidden/RenderDepth"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {

        Tags{ "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline"}
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            HLSLPROGRAM
            #pragma target 5.0

            #pragma vertex Vert
            #pragma fragment frag

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.core/Runtime/Utilities/Blit.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareOpaqueTexture.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareDepthTexture.hlsl"

            sampler2D _MainTex; 

            RWStructuredBuffer<float> distBuffer;
            int res;
            bool _RenderDepth;

            float4 frag (Varyings i) : SV_Target
            {
                uint2 pixelIdx = uint2(i.positionCS.xy);
                float3 color = SampleSceneColor(i.texcoord);

                #if UNITY_REVERSED_Z
                    real depth = SampleSceneDepth(i.texcoord);
                #else
                    // Adjust z to match NDC for OpenGL
                    real depth = lerp(UNITY_NEAR_CLIP_VALUE, 1, SampleSceneDepth(i.texcoord)); 
                #endif
                depth = Linear01Depth(depth, _ZBufferParams);
                distBuffer[pixelIdx.y * _ScaledScreenParams.x + pixelIdx.x] = depth * _ProjectionParams.z;  
                return _RenderDepth ? float4(depth, depth, depth, 1) : float4(color, 1);
            }
            ENDHLSL
        }
    }
}
