#version 330 core
uniform float iGlobalTime;
uniform vec2 iResolution;
in vec2 UV;
layout(location = 0) out vec4 color;

const int Npoly = 3;
const float TWOPI = 6.283185;
float colpos = 5.0 * sin(iGlobalTime);

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 = 0.2 * iGlobalTime;
    
    for (int i = 0; i < Npoly; i++) {
        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));
    return vec4(vec3(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);
    
    // fog me beautiful
    float fogfactor = exp(3.5 - 2.0 * length(hitpos - vec3(0.0)));
	color = col * min(1.0, fogfactor);
    color += 0.1*rand(UV + 0.1*iGlobalTime);
}
