#version 330 core
in vec2 UV;
uniform float iGlobalTime;
uniform vec2 iResolution;
uniform sampler2D iChannel0;
out vec4 color;

/////////////////////// Uniforms
uniform int Npoly;
uniform float addAlpha;
uniform float orig;
// int Npoly = int(3.0 + floor(mod(iGlobalTime, 5.0))); // TODO: uniform
// float addAlpha = 0.9 * mod(iGlobalTime, 1.0); // TODO: uniform
// const float orig = 0.0; // TODO: uniform
/////////////////////// Uniforms

const float TWOPI = 6.283185;
float colpos = 0.25;

float rand(vec2 co){
    return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}

vec3 rayPlane(vec3 p, vec3 o, vec3 n, vec3 d) {
    float dn = dot(d, n);
    float s = 1e8;
    
    if (dn != 0.0) {
        s = dot(p - o, n) / dn;
        s += float(s < 0.0) * 1e8; // (takana oleva kama ei kelpaa)
    }
    return o + s * d;;
}

vec3 rayTriangle(vec3 o, vec3 ray) {
    const float R = 2.0;
    vec3 cand = o;
	float cdist = 1e10;
    float phase = 1.0 * iGlobalTime;
    
    for (int i = 0; i < 64; i++) { // TODO: probly different ray tests for different Npolys?
        if (i >= Npoly) {
            break;
        }
        vec3 p = R * vec3(cos(TWOPI * float(i) / float(Npoly) + phase),
                          sin(TWOPI * float(i) / float(Npoly) + phase),
                          0.0);
        vec3 n = normalize(-p);
        vec3 rh = rayPlane(p, o, n, ray);
        float dist = length(rh - o);
        
        if (dist < cdist) {
            cand = rh;
            cdist = dist;
        }
    }
    return cand;
}

vec4 colorize(vec3 pos) {
    // TODO: colpos kinda legacy.
    // TODO: tune density etcs
    float c = float(abs(pos.z - colpos) < 0.05);
    return vec4(vec3(addAlpha * c), 1.0);
}

void main()
{
	vec2 uv = UV - vec2(0.5);
    uv.x *= iResolution.x / iResolution.y;
    vec3 ray = normalize(vec3(uv, 5.0/200.0));
   	vec3 hitpos = rayTriangle(vec3(0.0), ray);
    vec4 col = colorize(hitpos);
    
	color = (orig + col) * texture2D(iChannel0, UV);
}
