#version 330 core
out vec4 FragColor;
  
in vec2 TexCoords;

uniform sampler2D screenTexture;
uniform sampler2D depthTexture;

uniform bool outlines;
uniform bool dead;


const float offset = 1.0 / 800.0;  

float kernel[9] = float[](
    1.0, 1.0, 1.0,
    1.0, -8.0, 1.0,
    1.0, 1.0, 1.0  
);

vec2 offsets[9] = vec2[](
        vec2(-offset,  offset), // top-left
        vec2( 0.0f,    offset), // top-center
        vec2( offset,  offset), // top-right
        vec2(-offset,  0.0f),   // center-left
        vec2( 0.0f,    0.0f),   // center-center
        vec2( offset,  0.0f),   // center-right
        vec2(-offset, -offset), // bottom-left
        vec2( 0.0f,   -offset), // bottom-center
        vec2( offset, -offset)  // bottom-right    
);

void main()
{ 
	float depth = texture(depthTexture, TexCoords).r;
	float depthLin = (2.0 * 0.1) / (80.0 + 0.1 - depth * (80.0 - 0.1));

	if (outlines) {
		vec3 sampleTex[9];
		for(int i = 0; i < 9; i++)
		{
			float depthSample = texture(depthTexture, TexCoords.st + offsets[i]).r;
			float depthSampleLin = (2.0 * 2.0) / (100.0 + 2.0 - depthSample * (100.0 - 2.0));

			sampleTex[i] = vec3(depthSampleLin);
		}
		vec3 col = vec3(0.0);

		for(int i = 0; i < 9; i++) {
			col += sampleTex[i] * kernel[i];
		}

		vec3 drawCol = vec3(0.0);

		vec3 edgeColor = vec3(0,0,0);

		if (col.x < 0.01) {
			if (dead) {
				vec4 temp = texture(screenTexture, TexCoords);
				float bw = (temp.x + temp.y + temp.z) / 3;
				FragColor = vec4(bw, bw, bw, 1.0);
			} else {
				FragColor = texture(screenTexture, TexCoords);
			}
		} else {
			FragColor = vec4(edgeColor, 1.0);
		}

		// Edges only
		// col.x = 1 - col.x;
		// FragColor = vec4(col.x, col.x, col.x, 1.0);

	} else {
		if (dead){
			vec4 temp = texture(screenTexture, TexCoords);
			float bw = (temp.x + temp.y + temp.z) / 3;
			FragColor = vec4(bw, bw, bw, 1.0);
		} else {
			FragColor = texture(screenTexture, TexCoords);
		}
		
	}

	// Depth only
	// FragColor = vec4(depthLin, depthLin, depthLin, 1.0);

}