uniform mat4 u_ColorMatrix;
varying vec2 v_TexCoord;
varying vec2 v_TexCoord2;
varying vec2 v_TexCoord3;
varying vec2 v_Position;
uniform sampler2D u_Tex0;
uniform float u_Time;
uniform vec2 u_Resolution;


const float offset = 0.1 / 128.0;

const float alpha = 0.9;

const float speed = 6.0;
const float num_colors = 3.0;

const float PI = 3.1415926535897932;

float getAngle(float x, float y){
    float rad = atan(x, y);

    if (rad < 0.0){
        rad += 2.0 * PI;
    }

    float degrees = rad * 180.0 / PI;

    return degrees;
}

void main()
{
    vec4 colors[5];
    colors[0] = vec4(1.0, 0.0, 0.0, alpha);
    colors[1] = vec4(0.0, 1.0, 0.0, alpha);
    colors[2] = vec4(0.0, 0.0, 1.0, alpha);
    
    gl_FragColor = texture2D(u_Tex0, v_TexCoord);
    vec4 texcolor = texture2D(u_Tex0, v_TexCoord2);
    if(texcolor.r > 0.9) {
        gl_FragColor *= texcolor.g > 0.9 ? u_ColorMatrix[0] : u_ColorMatrix[1];
    } else if(texcolor.g > 0.9) {
        gl_FragColor *= u_ColorMatrix[2];
    } else if(texcolor.b > 0.9) {
        gl_FragColor *= u_ColorMatrix[3];
    }

    if(gl_FragColor.a < 0.01) {
        float a = texture2D(u_Tex0, vec2(v_TexCoord.x + offset, v_TexCoord.y)).a +
            texture2D(u_Tex0, vec2(v_TexCoord.x, v_TexCoord.y - offset)).a +
            texture2D(u_Tex0, vec2(v_TexCoord.x - offset, v_TexCoord.y)).a +
            texture2D(u_Tex0, vec2(v_TexCoord.x, v_TexCoord.y + offset)).a;

        if (a > 0.0) {
            float t = mod (u_Time * 100.0 * speed, 360.0);

            float angle = getAngle(v_Position.x, v_Position.y);

            angle = mod(angle + t, 360.0);

            float sector = 360.0 / num_colors;

            int cur_color = int(angle / sector);

            //cur_color = int (mod(float(cur_color) + t, num_colors));

            texcolor = colors[cur_color];

            gl_FragColor = texcolor;
        }
    }
}
