#version 330
out vec4 fragColor;

uniform mat4 proj, model, view;

uniform int objectId;

uniform vec3 camPos;

uniform vec4 couleur;
uniform vec2 windowSize;

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

uniform vec4 Lp;
uniform vec3 directional;

in vec4 vsoModPos;
in vec3 vsoNormal;

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() {
	// Valeur de luminance est standard
	
	// Vignette pour effet vieux film
	float vignette = calculate_vignette();
	// Damage
	float damageVal = calculate_damage();

	// Phong
	vec3 n = normalize(vsoNormal);
	vec3 viewVector = vsoModPos.xyz - camPos;
	vec3 Ld = normalize(directional);
	float intensite_diffus = clamp(dot(n, -Ld),0.0,1.0);
    // Specular
	vec3 R0 = reflect(Ld, n);
	float intensSpecular = pow(clamp(dot(-normalize(viewVector), R0),0.0,1.0),150.0);
	// Reflection
	vec3 viewR = reflect(viewVector , n);
	vec4 specular = intensSpecular * vec4(1.0);
	// Sampling the cubemap when drawing water
	if(objectId == 0)
		specular += texture(skybox, viewR) * 0.2;
	
	vec4 col = couleur * intensite_diffus + specular;	

    // Ajout de la positionelle
	vec3 distToLp = vsoModPos.xyz - Lp.xyz;
	Ld = normalize(distToLp);
	intensite_diffus = clamp(dot(n, Ld), 0.0, 1.0);
	if(objectId > 0 || Lp.y > 0.0)
		R0 = reflect(Ld, n);
	else // refraction quand sous l'eau
		viewVector = refract(viewVector, n, 1.333);
	intensSpecular = pow(clamp(dot(-normalize(viewVector), R0), 0.0, 1.0), 150.0);
	specular = intensSpecular * vec4(1.0);
	col += (couleur * intensite_diffus + specular) * clamp(Lp.w-length(distToLp),0.0,1.0);

	
	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 = vec4(gray_col.rgb * vignette * damageVal, gray_col.a);
	//décommenter si on veut désactiver les effets du fs facilement
	
	//fragColor = intensite_diffus * couleur + specular;
}
