#version 330

smooth in vec2 v_uv;

out vec4 result;

uniform sampler2D source;
uniform sampler2D noise;

uniform float time;
uniform float param;

uniform vec4 bounds;
uniform vec2 focus;

#define M_PI 3.1415926535897932384626433832795

void main()
{
  // basic stats
  vec2 levelpos = bounds.xy + v_uv * bounds.zw;
  vec2 offset = levelpos - focus;
  float dist = length(offset);
  float theta = atan(offset.y, offset.x);

  // Shockwaves
  vec3 wavefront = vec3(80.0 * param) - vec3(0.0, 25.0, 50.0);
  vec3 inwave = step(dist, wavefront);
  
  float shockwave = smoothstep(0.75, 0.25, abs(dist - wavefront.x));

  // Binary segments
  float segment = floor(dist);
  vec2 n_uv = vec2(theta / (2 * M_PI) + 0.5, 0.7 * segment);
  float bseg = step(texture(noise, n_uv).r, 0.5);

  // Partition wavefront
  // regular color OR unluminous OR black
  float blackwave = mix(inwave.y, inwave.z, bseg);
  float zapwave = mix(inwave.x, inwave.y, bseg);
  
  // Combine
  vec3 pixel = texture(source, v_uv).rgb;
  vec3 unluminosity = vec3(1.0 - dot(vec3(0.21, 0.72, 0.07), pixel.rgb));
  pixel = mix(pixel, unluminosity, zapwave);
  pixel *= 1.0 - blackwave;
  pixel = mix(pixel, vec3(1.0), shockwave); 

  result.rgb = pixel.rgb;
  result.a = 1.0;
}
