#version 330 core
in vec2 UV;
in vec2 ray;
out vec4 fragColor;
uniform sampler2D iChannel0;
uniform sampler2D iChannel1;
uniform vec2 iResolution;
uniform float iGlobalTime;

uniform float amount; // = 1920.0/240.0; // TODO: gain
uniform float macroblocksize;
uniform float blockcontrol;

float sat( float t ) {
  return clamp( t, 0.0, 1.0 );
}
vec2 sat( vec2 t ) {
  return clamp( t, 0.0, 1.0 );
}
float remap  ( float t, float a, float b ) {
  return sat( (t - a) / (b - a) );
}
float linterp( float t ) {
  return sat( 1.0 - abs( 2.0*t - 1.0 ) );
}
vec3 spectrum_offset( float t ) {
  vec3 ret;
  float lo = step(t,0.5);
  float hi = 1.0-lo;
  float w = linterp( remap( t, 1.0/6.0, 5.0/6.0 ) );
  float neg_w = 1.0-w;
  ret = vec3(lo,1.0,hi) * vec3(neg_w, w, neg_w);
  return pow( ret, vec3(1.0/2.2) );
}

float rand(vec2 co){
    return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}

void main()
{
  //vec2 uv = 0.5+0.5-fragCoord.xy / iResolution.xy;
    //uv.x = -uv.x;
    vec2 uv = UV;
    uv.y *= iResolution.y/iResolution.x;
  float time = iGlobalTime;
    vec4 sum = texture2D(iChannel0, vec2(1.0,1.778)*uv);

    for(float i = 1.0; i < amount; i++){
        uv /= pow(mix(vec2(1.0), fract(macroblocksize*uv)+0.5, clamp(pow(length(texture2D(iChannel1, vec2(0.06*iGlobalTime)).xyz ), 15.0),0.0, 1.0)), vec2(blockcontrol)); // 0.30 vec2:ssa blockcontrol
        sum = clamp(sum, 0.1, 1.0);
        sum /= 0.1+0.9*texture(iChannel0, vec2(1.0,1.778)*uv+vec2(1.0/iResolution.x,i/iResolution.y));
      sum *= 0.1+0.9*texture(iChannel0, vec2(1.0,1.778)*uv+vec2(1.0/iResolution.x,-i/iResolution.y));
      sum *= 0.1+0.9*texture(iChannel0, vec2(1.0,1.778)*uv+vec2(-i/iResolution.x,i/iResolution.y));
      sum /= 0.1+0.9*texture(iChannel0, vec2(1.0,1.778)*uv+vec2(-i/iResolution.x,-i/iResolution.y));
        sum.xyz -= 0.01*spectrum_offset( 1.0-length(sum.xyz) );
      sum.xyz *= 1.0+0.01*spectrum_offset( length(sum.xyz) );
        
    }
    sum = 0.1+0.9*sum;
    float chromaf = pow(length(texture2D(iChannel1, vec2(0.0213*iGlobalTime)).xyz ), 2.0);
    //sum /= log( 5.0+(0.1+chromaf)-(2.0+0.9*chromaf)*length(sum) );
    //sum /= 3.0*log((1.0+0.1*chromaf)+(0.2-0.1*chromaf)*length(sum));
    sum /= length(sum);
    sum = (-0.2+2.0*sum)*0.9;
    //sum = (-0.4*chromaf + sum*(2.0+0.9*chromaf))*0.9;
    
    //sum /= 0.6*length(2.0*chromaf+0.5*chromaf*sum);
    
  fragColor = sum;
}
