#version 330
out vec4 fragColor;

uniform mat4 proj, model, view;

uniform vec2 windowSize;

uniform sampler2D noise;
uniform vec3 noiseMov;
uniform samplerCube skybox;

in vec3 cubTexCoord;

vec2 rotate(in vec2 vector, float angle){
	return vec2(vector.x * cos(angle) - vector.y * sin(angle),
				vector.x * sin(angle) - vector.y * cos(angle));
}

float calculate_damage(){
	float val = texture(noise, rotate((gl_FragCoord.xy/windowSize) + (vec2(noiseMov.x,noiseMov.y)), clamp(length(noiseMov), 0.0, 1.0))).r;
	if(val > (noiseMov.z / 100.0)){
		return 1.0;
	} else {
		return val;
	}
}

float calculate_vignette(){
	// We consider that y < x == true
	vec2 ratioedSize = vec2(windowSize.y * 4/3, windowSize.y);
	float xMargin = (windowSize.x - ratioedSize.x) / 2;
	
	// On rajoute les barres noires pour le format 4:3
	if(gl_FragCoord.x < xMargin || gl_FragCoord.x > (windowSize.x - xMargin))
		return 0.0;

	return clamp(0.9-(length(gl_FragCoord.xy - ((ratioedSize/2) + vec2(xMargin,0.0))) / length(ratioedSize/2)), 0.0, 1.0);
}

float sigmoid(in float x){
	return 1/(1+exp(-6.5*(x-0.5)));
}

void main() {
	// Vignette pour effet vieux film
	float vignette = calculate_vignette();
	// Damage
	float damageVal = calculate_damage();

	vec4 col = texture(skybox, cubTexCoord);

	float gray =  0.2126*col.x + 0.7152*col.y + 0.0722*col.z;
	gray = sigmoid(gray);
	vec4 gray_col = vec4(gray,gray,gray, col.a);
	fragColor = gray_col * vignette * damageVal;
}
