#include "version.sh"


#ifdef mileage_alpha_size_5
const int size = 5;
#endif

uniform float alphaMileages[size];
uniform lowp float alphaValues[size];

uniform sampler2D texUnit;
uniform lowp float colorTexYOffsets[10]; // 存的是color index 对应的纹理中的v坐标
uniform float colorTransLength;

uniform lowp vec4 mainColor; // 默认颜色
uniform float useMainColor; // 是否使用默认颜色


uniform float alphaRatio;

in highp vec2 uv_f;
flat in vec2 colorSecMileage;
flat in ivec4 colorFlags;


layout(location = 0) out vec4 fragColor;

void main()
{
    float mileage_f = uv_f.y;
    
    // 颜色过渡
    bool useSingleColor = (useMainColor > 0.5);
    vec4 sampleColor = texture(texUnit, vec2(uv_f.x, colorTexYOffsets[colorFlags.y]) );
    vec4 color = useSingleColor ? mainColor : sampleColor;
    bool needTrans = !useSingleColor && colorFlags.x > 0;
    if (needTrans) {

        float transLength = min(colorTransLength, (colorSecMileage.y - colorSecMileage.x) * 0.5);

        float transMileage = mileage_f < colorSecMileage.x + transLength ? colorSecMileage.x : colorSecMileage.y;

        float ratio = smoothstep(transMileage - transLength, transMileage + transLength, mileage_f);

        if (mileage_f < colorSecMileage.x + transLength)
        {
            vec4 preColor = texture(texUnit, vec2(uv_f.x, colorTexYOffsets[colorFlags.w]));
            color = mix(preColor, color, ratio);
        }
        else
        {
            vec4 afterColor = texture(texUnit, vec2(uv_f.x, colorTexYOffsets[colorFlags.z]));
            color = mix(color, afterColor, ratio);
        }
    }

    // alpha过渡
    int index = 0;
    for (int i = 0; i < size; ++i)
        if (mileage_f > alphaMileages[i] - 0.01)
            index = i;
        
    float mixAlpha = alphaValues[index];
    if(mixAlpha < -0.1) // 只有过渡区域会走到if分支里
    {
        float ratio = smoothstep(alphaMileages[index], alphaMileages[index + 1], mileage_f);
        mixAlpha = mix(alphaValues[index-1], alphaValues[index+1], ratio);
    }
    
    fragColor = vec4(color.xyz, color.w * mixAlpha * alphaRatio);
}

