#version 430 core

in vec2 UV;

//out vec4 color;

layout(location = 0) out vec4 color;

uniform sampler2D colorBuffer;
uniform sampler2D normalBuffer;
uniform sampler2D depthBuffer;

mat3 sx = mat3(
			1.0, 2.0, 1.0,
			0.0, 0.0, 0.0,
			-1.0, -2.0, -1.0
	);
mat3 sy = mat3(
			1.0, 0.0, -1.0, 
			2.0, 0.0, -2.0, 
			1.0, 0.0, -1.0
	);
	
	float linearize(float x){
		float n = 0.1f;
		float f = 200.0f;
		return (2.0*n)/(f+n-x*(f-n));
	}

void main(){
	
	//color = vec4(texture(colorBuffer, UV).rgb, 1);
	float zNear = 0.0f;
	float zFar = 20.0f;
	float depth = texture2D(depthBuffer, UV).x;
	//vec3 kk = vec3(kk);
	
	
	vec3 diffuse = texture(normalBuffer, UV).rgb;

	mat3 I;
	mat3 J;
	for (int i=0; i<3; i++){
		for(int j=0; j<3; j++){
			vec3 x = texelFetch(depthBuffer, ivec2(gl_FragCoord) + ivec2(i-1, j-1), 0).rgb;
			vec3 y = texelFetch(normalBuffer, ivec2(gl_FragCoord) + ivec2(i-1, j-1), 0).rgb;
			vec3 temp = vec3(linearize(x.x));
			
			I[i][j] = length(y);
			J[i][j] = length(temp);
		}
	}
	
	float gx = dot(sx[0], I[0]) + dot(sx[1], I[1]) + dot(sx[2], I[2]);
	float gy = dot(sy[0], I[0]) + dot(sy[1], I[1]) + dot(sy[2], I[2]);
	
	float blax = dot(sx[0], J[0]) + dot(sx[1], J[1]) + dot(sx[2], J[2]);
	float blay = dot(sy[0], J[0]) + dot(sy[1], J[1]) + dot(sy[2], J[2]);
	
	float g = sqrt(pow(gx, 2.0) + pow(gy, 2.0));
	float bla = sqrt(pow(blax, 2.0) + pow(blay, 2.0));
	
	g = smoothstep(0.2, 0.6, g);
	bla = smoothstep(0.2, 0.6, bla);
	g = g + bla;
	vec3 edgeColor = vec3(0.0, 0.0, 0.0);
	//color = vec4(diffuse - vec3(g), 1.0);
	//diffuse.a = 0.0;
	
	vec3 d = vec3(1.0);
	vec3 c = texture(colorBuffer, UV).rgb;
	
	//color = vec4(t, 1.0);
	color = vec4(mix(c, edgeColor, g), 1.0);
}
