#version 330 core
in vec2 UV;
out vec4 shadowcoef;

uniform sampler2D postex;
uniform sampler2D shadowmap;
uniform float shadowmapDimension;
uniform mat4 depthMVP;

float occlusion(vec3 pos, vec2 jitter) {
	vec4 candidate = depthMVP * vec4(pos, 1.0);
	return 1.0 - float(texture(shadowmap, jitter + candidate.xy * .5 + 0.5).r < candidate.z * .5 + .5);
}

float shadowterm(vec3 pos) {
	const int kernelr = 4;
	const int kernelw = 2 * kernelr + 1;
	float occ = 0.0;
	for (int i = -1 * kernelr; i <= kernelr; i++) {
		for (int j = -1 * kernelr; j <= kernelr; j++) {
			vec2 jitter = vec2(float(i), float(j)) / shadowmapDimension;
			occ += occlusion(pos, 1.0 * jitter);
		}
	}
	return occ / (kernelw * kernelw);
}

void main() {
	float shadow = shadowterm(texture(postex, UV).xyz);
	shadowcoef = vec4(vec3(shadow), 1.0);
}
