#ifndef CARD_STENCIL_FADE_INCLUDED
#define CARD_STENCIL_FADE_INCLUDED


#include "UnityCG.cginc"
#include "Lighting.cginc"
#include "AutoLight.cginc"


sampler2D _MainTex;
float4 _MainTex_ST;

fixed4 _Color;

half _Cutoff;
half _Glossiness;
half _Metallic;

half _MaskFade;
float _DitherSeed;


#ifndef CARD_MASK_LEVEL
    #define CARD_MASK_LEVEL 0
#endif

#ifndef CARD_MASK_MAX_LEVEL
    #define CARD_MASK_MAX_LEVEL 3
#endif


// ============================================================
// Vertex data
// ============================================================

struct appdata
{
    float4 vertex : POSITION;
    float3 normal : NORMAL;
    float2 uv : TEXCOORD0;

    UNITY_VERTEX_INPUT_INSTANCE_ID
};


struct v2f
{
    float4 pos : SV_POSITION;
    float2 uv : TEXCOORD0;

    float3 worldPos : TEXCOORD1;
    half3 worldNormal : TEXCOORD2;

    float4 screenPos : TEXCOORD3;

    UNITY_FOG_COORDS(4)
    UNITY_SHADOW_COORDS(5)

    UNITY_VERTEX_OUTPUT_STEREO
};


v2f vert(appdata v)
{
    v2f o;

    UNITY_SETUP_INSTANCE_ID(v);
    UNITY_INITIALIZE_OUTPUT(v2f, o);
    UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);

    o.pos =
        UnityObjectToClipPos(v.vertex);

    o.uv =
        TRANSFORM_TEX(
            v.uv,
            _MainTex
        );

    o.worldPos =
        mul(
            unity_ObjectToWorld,
            v.vertex
        ).xyz;

    o.worldNormal =
        UnityObjectToWorldNormal(
            v.normal
        );

    o.screenPos =
        ComputeScreenPos(
            o.pos
        );

    UNITY_TRANSFER_FOG(
        o,
        o.pos
    );

    TRANSFER_SHADOW(o);

    return o;
}


// ============================================================
// Bayer dithering
// ============================================================

float Bayer2(float2 pixel)
{
    float2 parity =
        fmod(
            floor(pixel),
            2.0
        );

    return
        parity.x * 2.0
        + parity.y * 3.0
        - parity.x * parity.y * 4.0;
}


float Bayer8(float2 pixel)
{
    float rank =
        Bayer2(pixel) * 16.0;

    rank +=
        Bayer2(
            floor(pixel * 0.5)
        ) * 4.0;

    rank +=
        Bayer2(
            floor(pixel * 0.25)
        );

    return
        (rank + 0.5) / 64.0;
}


// ============================================================
// Common card sampling / clipping
// ============================================================

struct CardSurface
{
    half3 albedo;
    half alpha;
};


CardSurface GetCardSurface(v2f i)
{
    CardSurface s;

    fixed4 texColor =
        tex2D(
            _MainTex,
            i.uv
        );


    // --------------------------------------------------------
    // Screen pixel position
    // --------------------------------------------------------

    float2 screenUV =
        i.screenPos.xy
        / i.screenPos.w;

    float2 screenPixel =
        floor(
            screenUV
            * _ScreenParams.xy
        );


    // --------------------------------------------------------
    // Volume-mask fade.
    //
    // level 0 -> 0
    // level 1 -> 1/3
    // level 2 -> 2/3
    // level 3 -> 1
    // --------------------------------------------------------

    float maskThreshold = 0.0;

#if CARD_MASK_LEVEL > 0

    float t =
        (float)CARD_MASK_LEVEL
        / (float)CARD_MASK_MAX_LEVEL;

    t = pow(t, 0.7);

    maskThreshold =
        _MaskFade
        * t;

#endif


    // --------------------------------------------------------
    // Combined fade, tested against one dither sample.
    //
    // _Color.a = 1 => fully visible
    // _Color.a = 0 => fully removed
    //
    // The animated _Color.a and the volume-mask fade are
    // independent coverage factors, so they multiply. Clipping
    // them separately picked two overlapping pixel sets out of
    // the same 8x8 grid instead of compounding, which is why a
    // card fading in inside a mask shell dithered blotchily
    // rather than at the product of the two densities.
    //
    // At level 0 this reduces to the old _Color.a clip, which
    // the stencil-0 pass of the Outside shader also runs, so
    // both keep the same pixels and the card does not double up.
    // --------------------------------------------------------

    float coverage =
        _Color.a
        * (1.0 - maskThreshold);

    clip(
        coverage
        - Bayer8(screenPixel)
    );


    // --------------------------------------------------------
    // Texture alpha cutout with derivative-based edge coverage.
    //
    // AlphaToMask converts this alpha into MSAA sample coverage
    // in the base pass.
    // --------------------------------------------------------

    half alphaWidth =
        max(
            fwidth(texColor.a),
            1.0h / 255.0h
        );

    half edgeCoverage =
        saturate(
            (texColor.a - _Cutoff)
            / alphaWidth
            + 0.5h
        );

    clip(
        edgeCoverage
        - 1.0h / 255.0h
    );


    s.albedo =
        texColor.rgb
        * _Color.rgb;

    s.alpha =
        edgeCoverage;

    return s;
}


// ============================================================
// Metallic workflow helper
//
// This isn't Unity's generated Surface Shader code anymore,
// but follows the same basic metallic-PBR model:
//
// dielectric F0 ~= 0.04
// metallic interpolates specular F0 toward albedo.
// ============================================================

half3 FresnelSchlick(
    half cosTheta,
    half3 F0
)
{
    half x =
        1.0h
        - saturate(cosTheta);

    half x2 = x * x;
    half x5 = x2 * x2 * x;

    return
        F0
        + (1.0h - F0) * x5;
}


half DistributionGGX(
    half NdotH,
    half roughness
)
{
    half a =
        roughness * roughness;

    half a2 =
        a * a;

    half denom =
        NdotH * NdotH
        * (a2 - 1.0h)
        + 1.0h;

    return
        a2
        / max(
            UNITY_PI
            * denom
            * denom,
            0.0001h
        );
}


half GeometrySchlickGGX(
    half NdotV,
    half roughness
)
{
    half r =
        roughness + 1.0h;

    half k =
        (r * r)
        / 8.0h;

    return
        NdotV
        / max(
            NdotV * (1.0h - k)
            + k,
            0.0001h
        );
}


half GeometrySmith(
    half NdotV,
    half NdotL,
    half roughness
)
{
    return
        GeometrySchlickGGX(
            NdotV,
            roughness
        )
        *
        GeometrySchlickGGX(
            NdotL,
            roughness
        );
}


// ============================================================
// Direct PBR lighting
// ============================================================

half3 EvaluateDirectLight(
    half3 albedo,
    half3 normal,
    half3 viewDir,
    half3 lightDir,
    half3 lightColor,
    half attenuation
)
{
    half3 N =
        normalize(normal);

    half3 V =
        normalize(viewDir);

    half3 L =
        normalize(lightDir);

    half3 H =
        normalize(V + L);


    half NdotL =
        saturate(
            dot(N, L)
        );

    half NdotV =
        saturate(
            dot(N, V)
        );

    half NdotH =
        saturate(
            dot(N, H)
        );

    half VdotH =
        saturate(
            dot(V, H)
        );


    half metallic =
        saturate(_Metallic);

    half smoothness =
        saturate(_Glossiness);

    half roughness =
        max(
            1.0h - smoothness,
            0.04h
        );


    half3 F0 =
        lerp(
            half3(
                0.04h,
                0.04h,
                0.04h
            ),
            albedo,
            metallic
        );


    half3 F =
        FresnelSchlick(
            VdotH,
            F0
        );

    half D =
        DistributionGGX(
            NdotH,
            roughness
        );

    half G =
        GeometrySmith(
            NdotV,
            NdotL,
            roughness
        );


    half3 specular =
        D
        * G
        * F
        /
        max(
            4.0h
            * NdotV
            * NdotL,
            0.001h
        );


    half3 kS =
        F;

    half3 kD =
        (1.0h - kS)
        * (1.0h - metallic);


    half3 diffuse =
        kD
        * albedo
        / UNITY_PI;


    return
        (diffuse + specular)
        * lightColor
        * attenuation
        * NdotL;
}


// ============================================================
// Forward Base
// ============================================================

fixed4 fragBase(v2f i) : SV_Target
{
    UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);

    CardSurface surface =
        GetCardSurface(i);


    half3 N =
        normalize(
            i.worldNormal
        );

    half3 V =
        normalize(
            _WorldSpaceCameraPos
            - i.worldPos
        );


    half3 L =
        normalize(
            UnityWorldSpaceLightDir(
                i.worldPos
            )
        );


    UNITY_LIGHT_ATTENUATION(
        attenuation,
        i,
        i.worldPos
    );


    half3 direct =
        EvaluateDirectLight(
            surface.albedo,
            N,
            V,
            L,
            _LightColor0.rgb,
            attenuation
        );


    // --------------------------------------------------------
    // Ambient / light probes.
    //
    // ShadeSH9 gives us Unity's spherical-harmonic ambient and
    // baked probe contribution.
    // --------------------------------------------------------

    half3 ambient =
        ShadeSH9(
            half4(
                N,
                1.0h
            )
        );

    half metallic =
        saturate(
            _Metallic
        );

    half3 indirectDiffuse =
        surface.albedo
        * ambient
        * (1.0h - metallic);


    half3 finalColor =
        direct
        + indirectDiffuse;


    fixed4 result =
        fixed4(
            finalColor,
            surface.alpha
        );


    UNITY_APPLY_FOG(
        i.fogCoord,
        result
    );

    return result;
}


// ============================================================
// Forward Add
//
// Only the contribution of the additional light is returned.
// The pass itself uses:
//     Blend One One
// ============================================================

fixed4 fragAdd(v2f i) : SV_Target
{
    UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);

    CardSurface surface =
        GetCardSurface(i);


    half3 N =
        normalize(
            i.worldNormal
        );

    half3 V =
        normalize(
            _WorldSpaceCameraPos
            - i.worldPos
        );

    half3 L =
        normalize(
            UnityWorldSpaceLightDir(
                i.worldPos
            )
        );


    UNITY_LIGHT_ATTENUATION(
        attenuation,
        i,
        i.worldPos
    );


    half3 direct =
        EvaluateDirectLight(
            surface.albedo,
            N,
            V,
            L,
            _LightColor0.rgb,
            attenuation
        );


    fixed4 result =
        fixed4(
            direct,
            0.0h
        );


    UNITY_APPLY_FOG_COLOR(
        i.fogCoord,
        result,
        fixed4(0,0,0,0)
    );

    return result;
}


#endif