
uniform sampler2D t1;
uniform sampler2D depthpacked;


uniform float fadein;
uniform float clear;
uniform float fadeout;

uniform float brighten;
uniform float amount;
uniform float yAmount;

vec2 pixel = vec2(1.0)/vec2(3.0,3.0+yAmount);

float factor = brighten * 64.0;
float radius;
float unpackFloatFromVec3i(const vec3 value)
{
	const vec3 bitSh = vec3( 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);
	return(dot(value, bitSh));
}

float getdepth(vec2 xy)
{
	float depth;
	vec3 col=texture2D(depthpacked,xy).xyz;
	if(col.x==0.0 && col.y==0.0 && col.z==0.0)
		depth=1000000000.0;
	else
		depth=unpackFloatFromVec3i(col);
	return depth;
}

float getdepth2(vec2 xy)
{
	vec2 uv = xy;
	float d = getdepth(uv)*10000.0;
	if(d>fadein && d<fadein+clear)
		return 0.0;

	if(d<fadein)
		return amount*(fadein-d)/fadein;
	if(d>fadein+clear+fadeout)
		return amount;
	if(d>fadein+clear)
		return amount*(d-fadein-clear)/fadeout;

	return d;
}
vec4 tex(vec2 uv){

	return texture2D(t1, vec2(uv.x,uv.y));
}

vec4 blur(vec2 uv, float currentDepth){
	vec4 accumCol = vec4(0.0);
	vec4 accumW = vec4(0.0);
	vec2 uv2=vec2(0);
	for (float j = -5.0; j < 5.0; j += 1.0)
	for (float i = -5.0; i < 5.0; i += 1.0){
		vec2 offset = pixel * vec2(i + j, j - i);
		uv2 = uv + offset * radius;

		vec4 col = tex(uv2);
		if(getdepth2(uv2) < currentDepth) {
			col = tex(uv);
		}
		vec4 bokeh = vec4(1.0) + col * col * col * vec4(factor);

		accumCol += col * bokeh;
		accumW += bokeh;

	}
	return accumCol/accumW;
}


void main(void)
{
	vec2 uv = gl_TexCoord[0].xy;


	float depth2 = getdepth2(uv);
	float a = depth2*amount/200.0;

	//float depth = getdepth(uv);
	radius =  (amount*depth2) / 45.0;

	gl_FragColor = blur(uv ,depth2);
}

