struct vertex_t
{
    UNITY_VERTEX_INPUT_INSTANCE_ID
    float4 position : POSITION;
    float3 normal : NORMAL;
    float4 color : COLOR;
    float4 texcoord0 : TEXCOORD0;
    float4 texcoord1 : TEXCOORD1;
    float4 texcoord2 : TEXCOORD2;
    float4 texcoord3 : TEXCOORD3;
};

struct pixel_t
{
    UNITY_VERTEX_INPUT_INSTANCE_ID
    UNITY_VERTEX_OUTPUT_STEREO
    float4 position : SV_POSITION;
    float4 faceColor : COLOR;
    float4 outlineColor : COLOR1;
    float4 texcoord0 : TEXCOORD0; // Texture UV, Mask UV
    float4 param : TEXCOORD1; // Scale(x), BiasIn(y), BiasOut(z), Bias(w)
    float2 mask : TEXCOORD2; // Position in clip space(xy), Softness(zw)
    float3 normal : NORMAL;
    #if (UNDERLAY_ON | UNDERLAY_INNER)
    float4	texcoord1		: TEXCOORD3;		
    float2	underlayParam	: TEXCOORD4;			
    #endif
    float4 vert_data : TEXCOORD5; // vertex left bottom position (x, y, z), vertex width (w)
    float4 uv_data : TEXCOORD6; // UV left bottom position (x, y), UV width (z), size ratio (w)
    float4 rotation_data : TEXCOORD7;
};

float4 SRGBToLinear(float4 rgba)
{
    return float4(lerp(rgba.rgb / 12.92f, pow((rgba.rgb + 0.055f) / 1.055f, 2.4f), step(0.04045f, rgba.rgb)), rgba.a);
}

float _UIMaskSoftnessX;
float _UIMaskSoftnessY;

pixel_t VertShader(vertex_t input)
{
    pixel_t output;

    // UNITY_INITIALIZE_OUTPUT(pixel_t, output);
    UNITY_SETUP_INSTANCE_ID(input);
    UNITY_TRANSFER_INSTANCE_ID(input, output);
    UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);

    float bold = step(input.texcoord0.w, 0);

    float4 vert = input.position;
    vert.x += _VertexOffsetX;
    vert.y += _VertexOffsetY;
    float4 vPosition = GetVertexPositionInputs(vert).positionCS;

    float2 pixelSize = vPosition.w;
    pixelSize /= float2(_ScaleX, _ScaleY) * abs(mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy));

    float scale = rsqrt(dot(pixelSize, pixelSize));
    scale *= abs(input.texcoord0.w) * _GradientScale * (_Sharpness + 1);
    if (UNITY_MATRIX_P[3][3] == 0)
        scale = lerp(abs(scale) * (1 - _PerspectiveFilter), scale,
                     abs(dot(TransformObjectToWorldNormal(input.normal.xyz),
                             normalize(GetWorldSpaceViewDir(vert)))));

    float weight = lerp(_WeightNormal, _WeightBold, bold) / 4.0;
    weight = (weight + _FaceDilate) * _ScaleRatioA * 0.5;

    float layerScale = scale;

    scale /= 1 + (_OutlineSoftness * _ScaleRatioA * scale);
    float bias = (0.5 - weight) * scale - 0.5;
    float outline = _OutlineWidth * _ScaleRatioA * 0.5 * scale;

    // if (_UIVertexColorAlwaysGammaSpace && !IsGammaSpace())
    // {
    //     input.color.rgb = UIGammaToLinear(input.color.rgb);
    // }
    float opacity = input.color.a;
    #if (UNDERLAY_ON | UNDERLAY_INNER)
			opacity = 1.0;
    #endif

    float4 faceColor = float4(input.color.rgb, opacity) * _FaceColor;
    faceColor.rgb *= faceColor.a;

    float4 outlineColor = _OutlineColor;
    outlineColor.a *= opacity;
    outlineColor.rgb *= outlineColor.a;
    outlineColor = lerp(faceColor, outlineColor, sqrt(min(1.0, (outline * 2))));

    #if (UNDERLAY_ON | UNDERLAY_INNER)
			layerScale /= 1 + ((_UnderlaySoftness * _ScaleRatioC) * layerScale);
			float layerBias = (.5 - weight) * layerScale - .5 - ((_UnderlayDilate * _ScaleRatioC) * .5 * layerScale);

			float x = -(_UnderlayOffsetX * _ScaleRatioC) * _GradientScale / _TextureWidth;
			float y = -(_UnderlayOffsetY * _ScaleRatioC) * _GradientScale / _TextureHeight;
			float2 layerOffset = float2(x, y);
    #endif

    // Generate UV for the Masking Texture
    float4 clampedRect = clamp(_ClipRect, -2e10, 2e10);
    float2 maskUV = (vert.xy - clampedRect.xy) / (clampedRect.zw - clampedRect.xy);

    // Populate structure for pixel shader
    output.position = vPosition;
    output.faceColor = faceColor;
    output.outlineColor = outlineColor;
    output.texcoord0 = float4(input.texcoord0.x, input.texcoord0.y, maskUV.x, maskUV.y);
    output.param = half4(scale, bias - outline, bias + outline, bias);

    const half2 maskSoftness = half2(max(_UIMaskSoftnessX, _MaskSoftnessX), max(_UIMaskSoftnessY, _MaskSoftnessY));
    output.mask = half4(vert.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * maskSoftness + pixelSize.xy));
    #if (UNDERLAY_ON || UNDERLAY_INNER)
			output.texcoord1 = float4(input.texcoord0 + layerOffset, input.color.a, 0);
			output.underlayParam = half2(layerScale, layerBias);
    #endif

    // decal
    output.rotation_data = input.texcoord1;
    output.vert_data = input.texcoord2;
    output.uv_data = input.texcoord3;

    return output;
}

void CalculateDecalUV_float(float3 vertexPosition, float4 meshData, float4 uvData, float4 quaternion,
                          out float3 decalUV, out float3 decalClip)
{
    const float2 uv = (vertexPosition.xy / _ScaledScreenParams.xy);
    #if UNITY_REVERSED_Z
    float depth = SampleSceneDepth(uv);
    #else
    // Adjust Z to match NDC for OpenGL ([-1, 1])
    float depth = lerp(UNITY_NEAR_CLIP_VALUE, 1, SampleSceneDepth(uv));
    #endif
    const float3 world_pos = ComputeWorldSpacePosition(uv, depth, UNITY_MATRIX_I_VP);
    const float3 local_pos = TransformWorldToObject(world_pos);
    CalculateDecal_float(local_pos, meshData, uvData, quaternion, decalUV, decalClip);
}

float4 PixShader(pixel_t input) : SV_Target
{
    UNITY_SETUP_INSTANCE_ID(input);

    float3 decalUV;
    float3 decalClip;
    CalculateDecalUV_float(input.position, input.vert_data, input.uv_data, input.rotation_data, decalUV, decalClip);

    // half d = tex2D(_MainTex, input.texcoord0.xy).a * input.param.x;
    float d = tex2D(_MainTex, decalUV.xy).a * input.param.x;
    half4 c = input.faceColor * saturate(d - input.param.w);

    #ifdef OUTLINE_ON
    c = lerp(input.outlineColor, input.faceColor, saturate(d - input.param.z));
    c *= saturate(d - input.param.y);
    #endif

    #if UNDERLAY_ON
    d = tex2D(_MainTex, input.texcoord1.xy).a * input.underlayParam.x;
    c += float4(_UnderlayColor.rgb * _UnderlayColor.a, _UnderlayColor.a) * saturate(d - input.underlayParam.y) * (1 - c.a);
    #endif

    #if UNDERLAY_INNER
    half sd = saturate(d - input.param.z);
    d = tex2D(_MainTex, input.texcoord1.xy).a * input.underlayParam.x;
    c += float4(_UnderlayColor.rgb * _UnderlayColor.a, _UnderlayColor.a) * (1 - saturate(d - input.underlayParam.y)) * sd * (1 - c.a);
    #endif

    // Alternative implementation to UnityGet2DClipping with support for softness.
    #if UNITY_UI_CLIP_RECT
    half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(input.mask.xy)) * input.mask.zw);
    c *= m.x * m.y;
    #endif

    #if (UNDERLAY_ON | UNDERLAY_INNER)
    c *= input.texcoord1.z;
    #endif
    
    DecalClip_float(c, decalClip, c);

    #if UNITY_UI_ALPHACLIP
    clip(c.a - 0.001);
    #endif

    return c;
}
