// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.

namespace Stride.Rendering.Images
{
    /// <summary>
    /// Makes back-objects transparent for the front out-of-focus area.  
    /// </summary>
    shader ThresholdAlphaCoCFront: ImageEffectShader
    {

        // Previous CoC value (higher level in the negative values)
        float CoCReference;

        // Current CoC value
        float CoCCurrent;

        stage override float4 Shading()
        {
            float4 color = Texture0.Sample(Sampler, streams.TexCoord).rgba;

            float4 result = color;

            float minCoC = - Texture1.Sample(Sampler, streams.TexCoord).x;

            // To sample multiple neighbors
            /*
            float neighborCoC[5];

            neighborCoC[0] =  - Texture1.Sample(Sampler, streams.TexCoord).x;
            neighborCoC[1] =  - Texture1.Sample(Sampler, streams.TexCoord + Texture0TexelSize * float2(0, 1)).x;
            neighborCoC[2] =  - Texture1.Sample(Sampler, streams.TexCoord + Texture0TexelSize * float2(0, -1)).x;
            neighborCoC[3] =  - Texture1.Sample(Sampler, streams.TexCoord + Texture0TexelSize * float2(1,0)).x;
            neighborCoC[4] =  - Texture1.Sample(Sampler, streams.TexCoord + Texture0TexelSize * float2(-1, 0)).x;

            float minCoC = 1;
            [unroll]
            for (int i = 0; i < 1; i++) 
            {
                minCoC = min(minCoC, neighborCoC[i]);
            }
            */

            // Pixel higher than the current CoC level will be opaque. 
            // Under the CoC of the previous pass, completely transparent.
            // Between the two CoC, lerp. 
            float range = CoCCurrent - CoCReference;
            result.a = saturate( lerp(0, 1, (minCoC - CoCReference) / range ) );

            return result;
        }
    };
}
