/* uses some snippets from:
 * "Seascape" by Alexander Alekseev aka TDM - 2014
 * License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
 * Contact: tdmaav@gmail.com
 */

//precision mediump float;
#version 460
uniform int m;
out vec4 o;
float u_time = m/float(44100);
const float PI = 22./7.;

vec3 no(vec3 v) { return normalize(v); }
float cl(float a, float b, float c) { return clamp(a,b,c); }

// Rotate
mat2 rot2D(float angle) {
    float s = sin(angle), c = cos(angle);
    return mat2(c, -s, s, c);
}

float smax( float a, float b, float k )
{
    float h = max(k-abs(a-b),0.0);
    return max(a, b) + h*h*0.25/k;
}

float hash(vec2 p, int algo)
{
    if (algo == 1) {
        float h = dot(p,vec2(127.1,311.7));
        return fract(sin(h)*43758.5453123);
    }
    p = 50. * fract( p*0.3183099);
    return fract( p.x*p.y*(p.x+p.y) );
}

float noise(vec2 p, float scale, int a)
{
    vec2 i = floor( p ),
    f = fract( p ),
	u = f*f*(3.-2.*f);
    float sc = scale;
    if (a == 1) sc = 2.;
    return -scale+sc*mix( mix( hash( i + vec2(0.), a),
                              hash( i + vec2(1.0,0.0), a ), u.x),
                         mix( hash( i + vec2(0.0,1.0), a),
                              hash( i + vec2(1.), a), u.x), u.y);
}

/////////////////
//   GEOMETRY  //
/////////////////
/*float sdSphere(vec3 p, float r) {
    return length(p)-r;
}*/

float sdCappedCylinder( vec3 p, float h, float r )
{
  vec2 d = abs(vec2(length(p.xy),p.z)) - vec2(r,h);
  return min(max(d.x,d.y),0.0) + length(max(d,0.0));
}

float sdBox2(vec3 p, vec3 b) {
    vec3 q = abs(p) - b;
    return length(max(q,0.)) + min(max(q.x,max(q.y,q.z)),0.);
}

float sdTriPrism( vec3 p, vec2 h, float rot )
{
    p.xy *= rot2D(rot);
    vec3 q = abs(p);
    return max(q.z-h.y,max(q.x*.866025+p.y*.5,-p.y)-h.x*.5);
}

float sdPyramid( vec3 p, float s)
{
  p = abs(p);
  return (p.x+p.y+p.z-s)*0.577;// 35027;
}

//////////////////
//   ANIMATION  //
//////////////////

// POSITIONS
//const vec3 glyph1Pos = vec3(1.7,-1.1,0.0);
//const vec3 glyph2Pos = vec3(2.0,0.0,0.0);

//const vec3 glyph4Pos = vec3(0.0,2.0,0.0)
//const vec3 glyph6Pos = vec3(1.5 * -1.,1.4,0.0);
//const vec3 glyph7Pos = vec3(1.7 * -1.,-1.1,0.0);

// DELAYS
float STARTDELAY = 9., glow = 0.;

// POSITIONS


// COLORS
vec3 chevronColor = vec3(0.36, 0.9, 0.0);

//  with duration d, startTime s and speed up with timeFact
float timedSine(vec3 i) {
    return min((u_time  - i.y)*i.z, i.x*PI);
}

float calcFactor (float startTime)
{
    return STARTDELAY + STARTDELAY*cl(sin(timedSine(vec3(1.5, startTime, 4.)) * 0.06), -.9, .9);
}

// Animate ring movements
vec3 ringAnim(vec3 p) {
    for (float i = 0.; i < 7.; i++) {
        float rotateDelay = STARTDELAY + (i * 3.), o=1.;
        if(u_time > rotateDelay) {
            if(mod(i,2.) >= 1.) o = -1.;
            p.xy *= rot2D(calcFactor(rotateDelay)*o);
        }
    }
    return p;
}

// Animate prism movements
float prismAnim(vec2 i) {
    if(u_time >= i.y) {
        i.x += (.045*cl(sin((timedSine(vec3(3., i.y, 40.)) * .4)),-.8, .8));
    }
    return i.x;
}

//////////////
//   SCENE  //
//////////////
float sea_octave(vec2 uv, float choppy) {
    uv += noise(uv, 1., 1);
    vec2 wv = 1.0-abs(sin(uv));
    wv = mix(wv, abs(cos(uv)),wv);
    return pow(1.0-pow(wv.x * wv.y,0.65),choppy);
}

vec3 map(vec3 p, int displace)
{
    float mat = 0., glo = 1e3,
    // Ring boxes
    an = PI/12.,
    step,
    anRot = floor(atan(p.y,p.x)/an + .5)*an;
    vec3 q = p;
    q.xy = rot2D(anRot)*q.xy;
    float d = length(max(abs(q.xy - vec2(1.8,0.))-vec2(0.24,0.14),0.)) - .02,

    // Main ring
    d2 = abs(length(p.xy) - 1.8) - .2;
    d = min(d,d2);

    // Inner ring
    d2 = smax(  abs(length(p.xy) - 1.75) - .08, abs(p.z - .1)-.04, .005 );
    d = max(-d2,d);

    // Depth slice rings
    d = smax( d, abs(p.z)-.1, .02 );

    //Rotating glyphs
    vec3 p2 = ringAnim(p), q2=p2;
    an = PI/16.;
    q2.xy = rot2D(floor((atan(p2.y,p2.x)/an) + .5)*an)*q2.xy;
    d2 = sdBox2( q2.xyz - vec3(1.75,0.,0.), vec3(.04, .14, .05) ) - .02 + noise(p.xy*100.,1e-3,0);
    d = min(d, d2);
    if (d==d2) mat = 6.;

    // Gate Base
    d2 = 1e3;
    float stepDist = 1.5, h = 0.0, d3, choppy=4., freq=0.6, amp=.2;
    for(int i = 0; i < 4; i++) {
        step = sdBox2(vec3(p.x,p.y+stepDist+0.05,p.z), vec3(2., .2,stepDist)) - .05;
        d2 = min(d2, step);
        stepDist += .2;
    }
    d2 += noise(p.xz * 50.+200., .007, 0);
    d = min(d, d2);
    if (d==d2) mat = 2.0;

    if (displace == 1) {
        vec2 uv = p.xy;
        for(int i = 0; i < 4; i++) {
            d3 = sea_octave((uv+u_time)*freq,choppy);
            d3 += sea_octave((uv-u_time)*freq,choppy);
            h += d3 * amp;
            uv *= mat2(1.6,1.2,-1.2,1.6); freq *= 1.9; amp *= 0.22;
            choppy = mix(choppy,1.0,0.4);
        }
    }
    d2 = max(-sdCappedCylinder(p, 2.0, min((1.7 - (u_time - 28.9)*2.5),2.3)), sdCappedCylinder(p, .025, 1.6) - h*0.15);
    d2 = max(d2, sdCappedCylinder ( p, 0.3, 1.7));
    d = min(d, d2);
    if (d==d2) {
        mat = 1.0;
    }

    // sand
    d2 = (p.y +3.7) + noise((vec2((p.x),(p.z*.44-40.))*.04)+100., 20., 0) + .25*sin(p.z*.5+u_time);
    d = min(d,d2);
    if (d==d2) mat = 3.0;

    // pyradmid
    d2 = sdPyramid(p+vec3(-75., 0., 100.), 60.);
    d = min(d, d2);
    if (d==d2) mat=3.;
    // Prisms
    for(float i = 0.; i < 8.; i++ ) {
        q = p;
        anRot = 24.67 / (PI * 2.) + (i+1.) * PI / 4.;

        // Nudge first and the last prism out of the ground
        if (i == 1.) anRot += .2;
        if (i == 7.) anRot -= .2;
        q.xy = rot2D(anRot) * q.xy;
        float rotateDelay = STARTDELAY + (i - 1.) * 3. + 1.5;
        // We can now call each prism by it's index
        // draw all except the middle bottom prism
        if (i > 0.) {
            q.x -= 1.95;
            vec3 q2 = q; // new point for movable parts
            if(u_time > rotateDelay) q2.x = prismAnim(vec2(q2.x, rotateDelay));
            float prismTop = sdTriPrism(vec3(q.x - .06, q.y, q.z), vec2(.1,.15), .5) -.01;
            d2 = max(-sdTriPrism(vec3(q2.x - .14, q2.y - 0. , q2.z), vec2(.22), .5) - .01 , sdTriPrism(vec3(q2.x, q2.y, q2.z ), vec2(.2,.12), .5) - .02);
            d2 = min(d2, prismTop);
            d = min(d, d2);
            // glyph locking thing material
            if (d == d2) mat = 4.;
            // glyph locking prism material
            if( d == prismTop) if(u_time > rotateDelay + .2) {
                mat = 5.;
                glo = min(d2, prismTop);
            }
        }
    }

    return vec3( d, mat, glo);
}

////////////////
//   DRAWING  //
////////////////

float rayMarch(vec3 ro, vec3 rd, int a) {
    vec3 d;
    float t = 0.; // total distance travelled
    // Raymarching
    for (int i = 0; i < 100; i++) {
        d = map(ro + rd * t, 0); // Get distance to objects
        if (a==0&&d.z<0.3) glow += pow(0.01/d.z,0.8)*0.6;
        t += d.x; // "march" the ray
        if (d.x < 1e-3 || t > 500.) break;
    }
    return t;
}

vec3 getNormal(vec3 p) {
    vec2 e = vec2(.01, 0.);
    vec3 n = map(p, 1).x - vec3(
        map(p-e.xyy,1).x,
        map(p-e.yxy,1).x,
        map(p-e.yyx,1).x);
    return no(n);
}

float getLight(vec3 p, vec3 lightPos, float intensity, float shadow, vec3 n, float atte) {
    vec3 l = no(lightPos - p);
    float len = length( lightPos - p ); // Distance from the light to the surface point.
    float dif = cl(dot(n, l)*intensity, 0., intensity) * 1.0 / (1.0 + atte*len),
    d = rayMarch(p+n*.0025, l, 1);
    if(d<length(lightPos-p)) dif *= shadow;
    return dif;
}

// lighting
float diffuse(vec3 n,vec3 l,float p) {
    return pow(dot(n,l) * 0.4 + 0.6,p);
}

float specular(vec3 normal,vec3 lightPos,vec3 rayOrigin,float specular) {
    float nrm = (specular + 8.0) / (PI * 8.0);
    return pow(max(dot(reflect(rayOrigin,normal),lightPos),0.0),specular) * nrm;
}

vec3 getSeaColor(vec3 p, vec3 n, vec3 l, vec3 eye) {

    vec3 color = vec3(0.0, 0.1, 0.3) + diffuse(n,l,60.0) * vec3(0.11, 0.16, 0.18) * 0.3;
    color -= vec3(0.73, 0.15, 0.66) * pow(cl(1.-dot(n, -eye), 0., 1.), .7);
    color += vec3(specular(n,l,eye,60.0))*0.2;
    return color;
}


vec3 applyFog(vec3 col, float t, vec3 rd, vec3  lightDir, float b ) {
    vec3 fogColor = mix( vec3(0.34, 0.11, 0.34), // blue
                         vec3(0.93, 0.37, 0.16), // yellow
                         pow(max( dot(rd, lightDir), 0.) ,8.));
    return mix( col, fogColor, 1.0 - exp(-t*b) );
}

vec3 getCameraRayDir(vec2 uv, vec3 p, vec3 l, float z)
{
    vec3 f = no(l-p),
        r = no(cross(vec3(0.,1.,0.), f)),
        u = cross(f,r),
        c = f*z,
        i = c + uv.x*r + uv.y*u,
        d = no(i);
    return d;
}

vec3 postProcess(vec3 col) {
    // Vignette
    //col *= smoothstep(0.9, 0.5, length(gl_FragCoord.xy/u_resolution.xy-vec2(.5)));
    // Colour mapping
    col *= vec3(.9, 0.8, 0.7);
    // gamma
    col = pow( col, vec3(.45) );
    // Contrast = a
    col = smoothstep(0., 1., col);

    // fade out at the end
    col += 1.0 - vec3(cl((46. - u_time)*.5, 0., 1.0));
    return col;
}

vec3 cameraPos()
{
    // first zoom in to the gate
    vec3 cPos = vec3(0., cl(6.-u_time,2.,6.), cl((100.-u_time*11.),6.,100.));
    if (u_time > 7.5) cPos += vec3(0., cl(7.5-u_time,-1.,0.), 0.);
    // close up shot for 1st glyph lock
    if (u_time > 10.5) cPos = vec3(2.,-1.,1.);
    // zoom away for 2nd glyph animation
    if (u_time > 12.) cPos = vec3(-1., -.7, 4.);
    if (u_time > 14.5) {
    cPos = vec3(0., 0., 4.);
    cPos.yz *= rot2D(-0.6-(cos(u_time-15.))*0.05);
    cPos.xz *= rot2D(sin((u_time-16.5)*0.1));
    }
    if (u_time > 23.5)
    {
        cPos = vec3(3., -.7, 4.);
    }
    if (u_time > 32.5)
    {
        cPos = vec3(-20.,10.,50.);
    }
    if (u_time > 36.5) {
        cPos = vec3(3., -.7, 4.);
        cPos.yz *= rot2D(((1.-cos(u_time-36.5))*-0.025));
        cPos.xz *= rot2D(sin((u_time-36.5)*0.07));
    }

    return cPos;
}

vec3 cameraPointAt() {
    vec3 p = vec3(0., -.5, 0.);
    // look at 1st glyph
    if (u_time > 10.5) p = vec3(1.7,-1.1,0.);
    // look gate at distance
    if(u_time > 12.) p = vec3(0.);
    if(u_time > 14.5) p = mix(vec3(1.5,1.4,0.0),vec3(-1.5,1.4,0.0), (u_time-16.5)*0.13);
    if(u_time > 23.5) p = vec3(0.);
    return p;
}

// flash screen with glyph color when it is locked
vec3 colorFlashesAnim(vec3 col) {
    if(u_time > 10.75) {
        float x = smoothstep(-1.,.8,sin((timedSine(vec3(.8, 10.75, 8.))*2.)));
        col = mix(col, chevronColor * (x * 1.4), x *.76);
    }
    return col;
}

vec3 addSpecular(vec3 nor, vec3 rod, float amount, float phong)
{
    return vec3(specular(nor,no(vec3(0.0,0.3,0.8)),no(rod),pow(10.,phong)))*amount;
}

vec3 sceneGate(vec2 uv)
{
    // Initialization
    vec3 ro = cameraPos(),
    rd = getCameraRayDir(uv, ro, cameraPointAt(), cl((43.-u_time)*-2.,2.,25.)),
    col = vec3(0.);
    float d = rayMarch(ro, rd,0), mat = 0.;

    if (d < 500.) {
        // Lighting
        vec3 p = ro + rd * d,
        n = getNormal(p);
        mat = map(p,0).y;
        // Light 1 Arguments
        // 1: Ray starting point
        // 2: Light position
        // 3: Light intensity
        // 4: Shadow intensity

        // Lights
        col += vec3(0.82, 0.5, 0.9) * getLight(p,  vec3( 10., 15., 25.), 1., .2,n,1e-10);
        col += vec3(0.79, 0.66, 0.43) * getLight(p,  vec3( 4., 2., -15.), 1., 1.,n,1e-10);
        col += vec3(0.0, 0.06, 0.7) * getLight(p,  vec3( 0., 0., 5.),cl((u_time-29.0)*100.,0.,50.), 0.0,n,3.1);
        // indirect lightning -> vec3 in normalize is light direction
        col += vec3(0.29, 0.28, 0.33) * cl( dot( n, no(vec3(0. , 1., 10.))), 0., 1.);

        if(mat==0.)
            col *= vec3(0.2, 0.3, 0.3) + addSpecular(n,rd,.5, 2.);
        if(mat==1.)
            col *= getSeaColor(p, n, no(vec3(0.0,0.3,0.8)),no(rd));
        if(mat==2.)
            col *= vec3(0.7, 0.7, 0.4) + noise (p.xz*3.+1.5, 0.1,0);
        if(mat==3.)
            col *= vec3(.8, .8, .5) + noise(p.xz*500.+1e5, .3,0);
        if(mat==4.)
            col *= vec3(0.0, 0.08, 0.11) + addSpecular(n,rd,0.3,0.7);
        if(mat ==5.)
           col = chevronColor*0.4;// * pow(cl(1. -dot(n, -rd), 0., 1.), .3);
        if(mat == 6.)
            col *= vec3(0.01, 0.04, 0.06) + addSpecular(n,rd,.1, 2.5);
   }
   col += glow * chevronColor*.25;
   return postProcess(colorFlashesAnim(applyFog(col, d, rd, vec3(0., -.1, -1.), .01)));
}

void main() {
    vec2 u_resolution = vec2(1920,1080);
    vec2 qor = gl_FragCoord.xy/u_resolution.xy;
	vec2 resoultion = -1.0+2.0*qor;
	resoultion.x *= u_resolution.x/u_resolution.y;
    o = vec4(sceneGate( resoultion ),1.);
}