#version 330 core

out vec4 FragColor;

in vec2 TexCoord;

uniform float u_RocketRow;

uniform float u_AspectRatio;

uniform vec3 u_CamPosition;

uniform vec3 u_CamRotation;

mat3 getXRotMat(float a) {
    return mat3(
         1.0,  0.0,     0.0,
         0.0,  cos(a), -sin(a),
         0.0,  sin(a),  cos(a)
    );
}

mat3 getYRotMat(float a) {
    return mat3(
         cos(a),  0.0,  sin(a),
         0.0,     1.0,  0.0,
        -sin(a),  0.0,  cos(a)
    );
}

mat3 getZRotMat(float a) {
    return mat3(
         cos(a), -sin(a),  0.0,
         sin(a),  cos(a),  0.0,
         0.0,     0.0,     1.0
    );
}


float sdSphere(vec3 p, float s, vec3 pos) {
    return length(p - pos)-s;
}

float pulse(float offset) {
 return 1 - ((mod(u_RocketRow + offset, 8)) / 8);
}

float sdf(vec3 p) {
    return min(
        min(sdSphere(p,pulse(0) +.1, vec3(0, 0, 1.5)),
            sdSphere(p, pulse(3) +.1, vec3(2.5, 0, 3))),
        sdSphere(p, pulse(3) +.1, vec3(-2.5, 0, 3)));
}

float march(vec3 dir, vec3 origin) {
    float t = 0;
    float dist;
    for (int i = 0; i < 20; i++) {
        dist = sdf(origin + dir * t);
        t += dist;
    }
    return t;
}

void main() {
    vec3 dir = normalize(vec3(TexCoord * 2 - 1, 1));
    mat3 rot = getXRotMat(u_CamRotation.x) * getYRotMat(u_CamRotation.y) * getZRotMat(u_CamRotation.z);
    dir = rot * dir;
    dir.x *= u_AspectRatio;
    float t = march(dir, u_CamPosition);

    FragColor = vec4(t * 0.3, t * 0.2*t, t + 0.5*t, 1);
}
