//

// Fragment shader for replacing hue value
//
// Author: Shirley Carter
//
// updated to 330 and rvfx system
// the reason this shader is such an incredible mess is that
// the Pro5 version was a mess and it was wrong... thus we can't
// optimize the conversion and do this correctly because it will
// not give the same output as Pro5 does.
// I've left the fast routines in here in case we want to use them later


#version 330

uniform sampler2DRect inputTex;
uniform sampler2DRect maskTex;
uniform float uTransitionProgress=1.0;
uniform float testVar=1.0;
uniform float uBlendValue=1.0;

in vec2 fsTexture;
in vec2 fsMaskTexture;
in float pickedHue;
out vec4 outColor;


vec3 RGBtoHSV( float r, float g, float b )
{
    float minf, maxf, delta;
    vec3 hsv;

    minf = min(min( r, g), b);
    maxf = max(max( r, g), b);
    hsv.z = maxf;  // v

    delta = maxf - minf;

    if( abs(maxf) > 0.0 ) {
        hsv.y = delta/maxf; // s


    }
    else {
        // r = g = b = 0 // s = 0, v is undefined
        hsv.y = 0.0;  // *s = 0;
        hsv.x = -1.0;  //*h = -1;
    }

    if( abs(r-maxf)>0.0)
        hsv.x = ( g - b ) / delta; // between yellow & magenta
    else if( abs(g-maxf)>0.0 )
        hsv.x = 2.0 + ( b - r ) / delta; // between cyan & yellow
    else
        hsv.x = 4.0 + ( r - g ) / delta; // between magenta & cyan

    hsv.x = hsv.x*60.0; // degrees
    if( hsv.x < 0.0 )
        hsv.x = hsv.x+ 360.0;

    return hsv;
}


vec3 HSVtoRGB( float h, float s, float v )
{
    int i;
    float f, p, q, t;
    vec3 rgb;

    if( abs(s) > 0.0 ) {
        h  = h/60.0; // sector 0 to 5
        i = int(floor(h ));
        f = h - floor(h); // factorial part of h
        p = v * ( 1.0 - s );
        q = v * ( 1.0 - s * f );
        t = v * ( 1.0 - s * ( 1.0 - f ) );

        if ( i == 0 ) {
            rgb.r = v;
            rgb.g = t;
            rgb.b = p;
        }
        else if (i == 1) {
            rgb.r = q;
            rgb.g = v;
            rgb.b = p;
        }
        else if (i == 2 ){
            rgb.r = p;
            rgb.g = v;
            rgb.b = t;
        }
        else if (i == 3){
            rgb.r = p;
            rgb.g = q;
            rgb.b = v;
        }
        else if ( i == 4){
            rgb.r = t;
            rgb.g = p;
            rgb.b = v;
        }
        else {
            rgb.r = v;
            rgb.g = p;
            rgb.b = q;
        }
    }
    else {
        // achromatic (grey)
        rgb.r = v;
        rgb.g = v;
        rgb.b = v;
    }
    return rgb;

}


void main(void)
{
    vec3 hsv;
    vec4 texel = texture(inputTex, fsTexture);

    outColor.a=texel.a;

    hsv = RGBtoHSV(texel.r, texel.g, texel.b);
    hsv.r = pickedHue;
    outColor.rgb = HSVtoRGB(hsv.r, hsv.g, hsv.b);
    float blendValue=uBlendValue;
#ifdef USE_MASK
    blendValue*=texture(maskTex,fsMaskTexture).a;
#endif
    outColor.rgb=mix(texel.rgb,outColor.rgb,blendValue);
}

