#version 330 core
// Floodlight multi-pass: pass 4 (select + merge).
//
// Composites the blurred highlight (output of passes 2/3) with the
// natural-orient YUV original. Direct port of Android's
// `EditorImageFloodlightSelectFilter`:
//
//   result = original + highlight * 5 * sin(coverPercent * pi/2)
//
// The CPU passes `u_selectEase = sin(cp * pi/2)`; the * 5 strength
// constant is baked in here to match Android.

out vec4 FragColor;
in  vec2 TexCoord;

uniform sampler2D u_highlight;   // RGBA from previous blur pass
uniform sampler2D tex_aY;
uniform sampler2D tex_aU;
uniform sampler2D tex_aV;
uniform float     u_selectEase;  // 0 .. 1
uniform int       u_aFlipX;
uniform int       u_aFlipY;
uniform float     u_aRotRad;

vec2 applyOrient(vec2 uv, int flipX, int flipY, float rotRad) {
    if (rotRad != 0.0) {
        vec2 c = uv - vec2(0.5);
        float s  = sin(rotRad);
        float co = cos(rotRad);
        uv = vec2(co * c.x - s * c.y, s * c.x + co * c.y) + vec2(0.5);
    }
    if (flipX != 0) uv.x = 1.0 - uv.x;
    if (flipY != 0) uv.y = 1.0 - uv.y;
    return uv;
}

vec3 yuvToRgb(float y, float u, float v) {
    y = (y - 16.0/255.0)  * (255.0/219.0);
    u = (u - 128.0/255.0) * (255.0/224.0);
    v = (v - 128.0/255.0) * (255.0/224.0);
    float r = y + 1.5748 * v;
    float g = y - 0.1873 * u - 0.4681 * v;
    float b = y + 1.8556 * u;
    return clamp(vec3(r, g, b), 0.0, 1.0);
}

void main() {
    // FBO scratch sampled with the V-flip dance (see blur shader's
    // explanation). YUV original sampled with normal applyOrient.
    vec2 uvHl = vec2(TexCoord.x, 1.0 - TexCoord.y);
    vec3 hl = texture(u_highlight, uvHl).rgb;

    vec2 uvO = applyOrient(TexCoord, u_aFlipX, u_aFlipY, u_aRotRad);
    vec3 orig = yuvToRgb(texture(tex_aY, uvO).r,
                         texture(tex_aU, uvO).r,
                         texture(tex_aV, uvO).r);

    vec3 result = clamp(orig + hl * 5.0 * u_selectEase, 0.0, 1.0);
    FragColor = vec4(result, 1.0);
}
