#version 430 core

uniform float fGlobalTime; // in seconds
uniform vec2 v2Resolution; // viewport resolution (in pixels)

uniform sampler1D texFFT; // towards 0.0 is bass / lower freq, towards 1.0 is higher / treble freq
uniform sampler1D texFFTSmoothed; // this one has longer falloff and less harsh transients
uniform sampler2D texBricks;
uniform sampler2D texGrunge;
uniform sampler2D texMono;
uniform sampler2D texNoise;
uniform sampler2D texNormal;
uniform sampler2D texPaper;
uniform sampler2D texPooBrain;

layout(location = 0) out vec4 out_color; // out_color must be written in order to see anything

vec4 plas( vec2 v, float time )
{
  float c = 0.5 + sin( v.x * 10.0 ) + cos( sin( time + v.y ) * 20.0 );
  return vec4( sin(c * 0.2 + cos(time)), c * 0.15, cos( c * 0.1 + time / .4 ) * .25, 1.0 );
}

float tn(vec3 pos) {
   float y = pos.y;
   pos = abs(fract(pos)-.5);

   
   float a;
   a = .3;
   pos.xz *= mat2(cos(a),-sin(a),sin(a),cos(a));
   pos.xz += vec2(-.2,0);
   pos = abs(pos);


   a = .8;
   pos.xz *= mat2(cos(a),-sin(a),sin(a),cos(a));
   pos.xz += vec2(.2,0);
   pos = abs(pos);


   a = .8;
   pos.xz *= mat2(cos(a),-sin(a),sin(a),cos(a));
   pos.xz += vec2(.2,0);
   pos = abs(pos);


   a = .3;
   pos.xz *= mat2(cos(a),-sin(a),sin(a),cos(a));
   pos.xz += vec2(.2,0);
   pos = abs(pos);

    y -= texture(texFFTSmoothed,0)*5.3-.03;

   return min(y+1., max(pos.x-.1,y+.25));
}




void main(void)
{
  vec2 uv = vec2(gl_FragCoord.x / v2Resolution.x, gl_FragCoord.y / v2Resolution.y);
  uv -= 0.5;
  uv /= vec2(v2Resolution.y / v2Resolution.x, 1);

  vec3 pos = vec3(0.,0.,-3.5+fGlobalTime);
  vec3 dir = normalize(vec3(uv,1));


  vec3 pos2 = pos;
  float t = 0.;
  for (int i = 0; i < 100; i++) {
    float f = tn(pos2.zyx+vec3(0,-.4,.5));
    pos2 += f*dir;
    t += f;
  } 

  vec3 colour2 = vec3(1./t)*step(fract(pos2.z*10.),.9)*step(fract(pos2.y*10.+.5),.9);
  if (abs(pos2.x) < 5.) {
    dir.x = -dir.x;
    pos2 = pos;
  }

  vec3 colour = vec3(0);
  float t2 = t;

    pos *= 2.;

   float a2 = .3+texture(texFFTSmoothed,0)*1.+fGlobalTime*.3;

  for (int i = 0; i < 50; i++) {
    pos2 = pos;

    mat3 mat = mat3(cos(a2),sin(a2),0,-sin(a2),cos(a2),0,0,0,1);
    for (int j = 0; j < 3; j++) {
      pos2 *= 1.3;
      pos2 *= mat;
      pos2 = pos2.yzx;
      pos2 = abs(fract(pos2)-.5)-.25;
      pos2 += .2;
    }
    pos2 /= 2.1;


    vec3 im = sqrt(pos2*pos2+pos2.yxz*pos2.yzx);
    float f = min(min(im.x,im.y),im.z);
    pos += dir*f;
    t2 += f;
    if (t2 > t*3.) break;
    colour += 1./(im+.001);
  }
  colour *= .001;

   colour = max(vec3(0),min(vec3(1),colour))*.8 + colour2;




  out_color = vec4(colour,0);
}