#version 400

uniform sampler2D colorMap;
uniform sampler2D depthMap;

uniform int maxBlurRadius;
uniform vec2 texelSize;
uniform vec2 planes;
uniform bool horizontal;

uniform float blurCoefficient;
uniform float focusDistance;
uniform float PPM;

smooth in vec2 VS_TexCoord;

layout(location = 0) out vec4 colorOut;
layout(location = 1) out vec4 blurAmountOut;


void main()
{
	vec2 texelOffset;
	float blurAmount;
	if(horizontal)
	{
		float depthMapDepth = texture(depthMap, VS_TexCoord).x;
		float depthReal = planes.y / (planes.x + depthMapDepth);

		//compute blur amount
		float xd = abs(depthReal - focusDistance);
		float xdd = (depthReal < focusDistance) ? (focusDistance - xd) : (focusDistance + xd);
		float b = blurCoefficient * (xd / xdd);
		blurAmount = clamp( b * PPM, 1, maxBlurRadius);

		//save blur amount
		blurAmountOut.x = blurAmount;
		texelOffset = vec2(texelSize.x, 0.0);
	}
	else
	{
		blurAmount = texture(depthMap, VS_TexCoord).x;
		texelOffset = vec2(0.0, texelSize.y);
	}

	//blur color map
	colorOut = vec4(0.0);
	float halfBlur = blurAmount * 0.5;
	for(int i = 0; i < blurAmount; ++i)
	{
		vec2 vOffset = VS_TexCoord + (texelOffset * (i - halfBlur));
		colorOut += texture(colorMap, vOffset);
	}
	colorOut = colorOut / ceil(blurAmount);
}	
