#version 330 core

uniform sampler2D normal_depth;

in vec2 uv;

layout (location = 0) out vec4 frag_color;

#include <deferred/gbuffer_include.frag>

#include <post/mssao_include.frag>

void main()
{
	vec4 nd[4];
	vec3 p[4];
	
	for (int i=0; i < 4; ++i)
	{
		vec2 uv_offs = uv + offsets[i]*TexelSize*0.5;
		nd[i] = texture(normal_depth, uv_offs);
		p[i] = calc_position(uv_offs, nd[i].w);
	}

	float maxZ = max(max(p[0].z, p[1].z), max(p[2].z, p[3].z));
	float minZ = min(min(p[0].z, p[1].z), min(p[2].z, p[3].z));

	int minPos = 0;
	int maxPos = 0;
	for (int i=0; i < 4; ++i)
	{
		if ( p[i].z == minZ )
		{
			minPos = i;
		}
		if ( p[i].z == maxZ )
		{
			maxPos = i;
		}
	}

	float d = distance(p[minPos], p[maxPos]);

	ivec2 median = ivec2(0, 0);
	int index = 0;

	for (int i = 0; i < 4 && index < 2; ++i)
	{
		if ( i != minPos && i != maxPos )
		{
			median[index++] = i;
		}
	}

	if ( d < 1.0 )
	{
		vec4 newND = (nd[median.x] + nd[median.y]) / 2.0;
		newND.xyz = normalize(newND.xyz);
		frag_color = newND;
	}
	else
	{
		frag_color = nd[median.x];
	}
}
