#version 120

uniform sampler2D texture;
uniform sampler2D noiseTexture;

uniform float time = 1.0;

uniform float distortionResolutionX = 1280.0;
uniform float distortionResolutionY = 720.0;
uniform float distortionX = 0.01;
uniform float distortionY = 0.01;
uniform float noiseAlpha = 0.1;
uniform float shakeSizeY = 0.005;
uniform float glitchSize = 0.001;

float getDistortionFactor(vec2 coord)
{
	//pixelize distortion
	vec2 d = vec2(1.0,1.0)/vec2(distortionResolutionX, distortionResolutionY);
	coord.s = floor(coord.s/d.s)*d.s+time;
	coord.t = floor(coord.t/d.t)*d.t+time;
	
	return texture2D(noiseTexture,coord).r;
}

float getRandomNoise(vec2 coord)
{
	return texture2D(noiseTexture,coord).r;
}

vec4 distortion()
{
	vec2 coord = gl_TexCoord[0].st;

	vec2 pseudoRandomCoord = coord + vec2(1.,2.*tan(time*10))*time;
	float distortion = getDistortionFactor(pseudoRandomCoord);
	float random = getRandomNoise(pseudoRandomCoord);
	
	float noiseDistortionX = texture2D(texture,vec2(coord.t+time,0)).x*distortion*distortionX;

	coord.x = fract(coord.x + noiseDistortionX + tan(coord.y + time)*glitchSize*sin(time + 4*sin(time*4))*(1.0 + cos(time*80.)));
	
	float shakeY = shakeSizeY*sin(time*0.1*cos(time*2))*(sin(time)*sin(time*20) + 
										 (1.0 + sin(time*20)*cos(time)));
	
	float noiseDistortionY = texture2D(texture,vec2(0,coord.s+time)).x * distortion * distortionY;
	
	coord.y = fract(coord.y + shakeY + noiseDistortionY);
	
	vec4 result = texture2D(texture,coord)*(1.0 - noiseAlpha) + random*noiseAlpha;
	
	return result * gl_Color;
}

void main()
{
	gl_FragColor = distortion();
}
