#version 400 core

in vec2 fTexcoord;

out vec4 outColor;

uniform sampler2D tex;

float LinearizeDepth(float depth) {
    float z = depth * 2.0 - 1.0; // Back to NDC
	float near = 2.0;
	float far = 500.0;
    return (2.0 * near * far) / (far + near - z * (far - near));
}

void main(void) {             
    float depthValue = texture(tex, fTexcoord).x;
    outColor = vec4(vec3(LinearizeDepth(depthValue) / 500.0), 1.0); // perspective
    //outColor = vec4(vec3(depthValue), 1.0); // orthographic
	//outColor = vec4(depthValue, 0.0, 0, 1);
	//outColor = vec4(0);

	float distributeValue = 256.0f;
	float distInv = 1.0f / distributeValue;
	vec2 texSize = 1.0 / textureSize(tex, 0);
	float filtersize = 5;
	float rectangleSize = filtersize + 1;
	float recHalf = rectangleSize / 2.0f;

	vec4 upperLeft = texture2D(tex, fTexcoord.xy + vec2(-recHalf, recHalf) * texSize);
	vec4 upperRight = texture2D(tex, fTexcoord.xy + vec2(recHalf, recHalf) * texSize);
	vec4 bottomLeft = texture2D(tex, fTexcoord.xy + vec2(-recHalf, -recHalf) * texSize);
	vec4 bottomRight = texture2D(tex, fTexcoord.xy + vec2(recHalf, -recHalf) * texSize);

	vec4 pcfValue = bottomRight - bottomLeft - upperRight + upperLeft;
	pcfValue = vec4(pcfValue.xy + pcfValue.zw * distInv, 0, 0);
	pcfValue = pcfValue / pow(rectangleSize, 2);
	outColor = vec4(pcfValue.x);
} 

