#version 330 core

// inputz
in vec2 UV;
uniform vec2 iResolution;
uniform sampler2D iChannel0;
uniform float iGlobalTime;
uniform float duckuppage;

// outputs
out vec4 color;

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

mat3 fuckup = mat3(-0.5,1.9,-0.5,0.5,0, 0.5,-0.5,1.9,-0.5);
vec3 getblock(vec2 c, vec2 r, float d){
    vec3 f = vec3(0);
    vec2 o = vec2(d);
    f += texture(iChannel0, c).rgb;
    c += o;
    f *= texture(iChannel0, c+o).rgb;
    c.x -= 2.0*o.x;
    f *= texture(iChannel0, c+o).rgb;
    c.y -= 2.0*o.y;
    f *= texture(iChannel0, c+o).rgb;
    c.x += 2.0*o.x;
    f *= texture(iChannel0, c+o).rgb;
    return 1.0*pow(f, vec3(0.25));
}

void main()
{
	vec2 uv = UV;
	vec2 block = floor((iResolution * uv)/vec2(iResolution.y/ceil(4.0+pow(mod(20.0*rand(vec2(iGlobalTime)),20.0),1.5))));
	vec2 uv_noise = block / vec2( floor(5.0*rand(vec2(iGlobalTime*0.1))) ); // TODO: idp rands?
	uv_noise += floor(vec2(iGlobalTime) * vec2(1234.0, 3543.0)) / vec2(64);
	
    float block_thresh = pow(fract(iGlobalTime * 26.0453), 2.0) * 0.6;
	float line_thresh = pow(fract(iGlobalTime * 16.0351), 3.0) * 0.9;
	
	vec2 uv_r = uv, uv_g = uv, uv_b = uv;

    block_thresh *= 1.0+9.0*pow(rand(vec2(iGlobalTime*0.073)), 8.0);
    
	// glitch some blocks and lines
    //float f = 0.5*texture2D(iChannel0, uv).w;
	if (rand(uv_noise) < 5.5*block_thresh ||
		rand(vec2(uv_noise.y, 0.0)) < 5.5*line_thresh) {
		
		vec2 dist = 0.3*(fract(uv_noise) - 0.5) * pow(rand(vec2(iGlobalTime*0.31)), 2.0);
		uv_r += dist * 0.125;
		uv_g += dist * 0.2;
		uv_b -= dist * 0.1;
    } else {
        //return;
        discard;
    }
	
	vec4 outpt = vec4(0.0);
	outpt.r = texture(iChannel0, uv_r).r;
	outpt.g = texture(iChannel0, uv_g).g;
	outpt.b = texture(iChannel0, uv_b).b;
	outpt.a = 1.0;

	// loose luma for some blocks
	if (rand(uv_noise) < block_thresh)
		outpt.rgb = texture(iChannel0, uv_r).rgb*fuckup;//1.333*texture2D(iChannel0, uv_r).ggg;

	// discolor block lines
	if (rand(vec2(uv_noise.y, 0.0)) * 3.5 < line_thresh)
        //discard;
		outpt.rgb = vec3(0.0, dot(outpt.rgb, vec3(1.0)), 0.0);

	// interleave lines in some blocks
	if (rand(uv_noise) * 1.5 < block_thresh ||
		rand(vec2(uv_noise.y, 0.0)) * 2.5 < line_thresh) {
		float line = fract(iResolution.y * UV.y / 3.0);
		vec3 mask = (texture(iChannel0, uv_r).rgb);
		if (line > 0.333)
			mask = (texture(iChannel0, uv_g).rgb);
		else if (line > 0.666)
			mask = (texture(iChannel0, uv_b).rgb);
		//discard;
        outpt.rgb = mask;
	}
    
    vec3 shitstain = max(vec3(0.01), outpt.rgb - getblock(uv, iResolution.xy, -2.0/800.0));
    outpt.rgb += 2.0*pow(shitstain, vec3(2));
    outpt.rgb = min(vec3(0.85), outpt.rgb);
    color = mix(texture(iChannel0, uv), outpt, vec4(duckuppage));
}
