varying vec2 v_texCoord;

uniform vec4 ellipse;
uniform vec2 texSize;
uniform float gradientSize;


vec3 rgb2hsv(vec3 c)
{
    vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
    vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
    vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
    
    float d = q.x - min(q.w, q.y);
    float e = 1.0e-3;
    vec3 ret =  vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
    
    ret.x = clamp(ret.x, 0.0, 1.0);
    ret.y = clamp(ret.y, 0.0, 1.0);
    ret.z = clamp(ret.z, 0.0, 1.0);
    
    return ret;
    
}

vec3 hsv2rgb(vec3 c)
{
    vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
    vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
    //return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
    vec3 ret = c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
    ret.x = clamp(ret.x, 0.0, 1.0);
    ret.y = clamp(ret.y, 0.0, 1.0);
    ret.z = clamp(ret.z, 0.0, 1.0);
    
    return ret;
}

void main()
{
    vec4 color = texture2D(CC_Texture0, v_texCoord);
    
    vec3 colorHSV = rgb2hsv(color.rgb);
    
    //desaturate and stuff
    colorHSV.y *= 0.65;
    colorHSV.z *= 0.15;
    
    vec3 desaturated = hsv2rgb(colorHSV);
    
    vec2 px = v_texCoord * texSize;
    
    vec2 dist = abs(ellipse.xy - px);
    dist = max(dist - ellipse.zw, 0.0);
    float l = length(dist);
    
    float desaturation = min(l / gradientSize, 1.0);
    
    gl_FragColor = vec4(mix(color.rgb, desaturated, desaturation), color.a);
}
