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

#define NSAMPLES 8
const int Npoly = 3;
const float TWOPI = 6.283185;
float colpos = 0.01*(50.0 - 60.0 * mod(0.1*iGlobalTime, 1.0));

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(mod(pos.z - colpos, 0.02) < 0.01);
    return vec4(vec3(c), 1.0);
}

vec4 sampleme(vec2 pos) {
    vec2 uv = pos - 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)));
    return col * min(1.0, fogfactor);
}

void main()
{
	color = sampleme(UV);
    vec2 r = vec2(0.5) / iResolution;

    for (int i = 0; i < NSAMPLES; i++) {
        float angle = 0.1 + float(i) * 2.0 * 3.141 / float(NSAMPLES);
        vec2 jitter = r * vec2(cos(angle), sin(angle));
        color += sampleme(UV + jitter);
    }

    color = color / float(NSAMPLES + 1);
}
