#extension GL_ARB_texture_rectangle : enable

uniform sampler2DRect texture0; // depth texture
uniform sampler2DRect texture1; // rendered scene color texture

uniform vec2 camerarange;
uniform vec2 screensize;

uniform float mul;
uniform float uao;
uniform float aoCap;
uniform float finCapSub;
uniform float finCapStart;
uniform float finCapEnd;

varying vec2 texCoord;


float readDepth( in vec2 coord ) {

//F = far clip, N = near.
//d = depth value
//float Depth = F*N / ( F - d * (F-N));

	//return (2.0 * camerarange.x) / (camerarange.y + camerarange.x - texture2DRect( texture0, coord ).x * (camerarange.y - camerarange.x));
	
	return camerarange.y * camerarange.x / ( camerarange.x - texture2DRect( texture0, coord ).x * (camerarange.y - camerarange.x) );
		
}

float getblah( float pw,float ph,float depth,float aoMultiplier,float depthTolerance)
{
	float d=readDepth( vec2(texCoord.x+pw,texCoord.y+ph));
	float ao=0.0;
	float aot=0.0;
	
	float div=1.0;
	
	aot=min(aoCap,max(0.0,depth-d-depthTolerance) * aoMultiplier);
	ao+=div/(1.0+aot*aot);

	d=readDepth( vec2(texCoord.x-pw,texCoord.y+ph));
	aot=min(aoCap,max(0.0,depth-d-depthTolerance) * aoMultiplier);
	ao+=div/(1.0+aot*aot);

	d=readDepth( vec2(texCoord.x+pw,texCoord.y-ph));
	aot=min(aoCap,max(0.0,depth-d-depthTolerance) * aoMultiplier);
	ao+=div/(1.0+aot*aot);

	d=readDepth( vec2(texCoord.x-pw,texCoord.y-ph));
	aot=min(aoCap,max(0.0,depth-d-depthTolerance) * aoMultiplier);
	ao+=div/(1.0+aot*aot);

	d=readDepth( vec2(texCoord.x-pw,texCoord.y));
	aot=min(aoCap,max(0.0,depth-d-depthTolerance) * aoMultiplier);
	ao+=div/(1.0+aot*aot);

	d=readDepth( vec2(texCoord.x+pw,texCoord.y));
	aot=min(aoCap,max(0.0,depth-d-depthTolerance) * aoMultiplier);
	ao+=div/(1.0+aot*aot);

	d=readDepth( vec2(texCoord.x,texCoord.y-ph));
	aot=min(aoCap,max(0.0,depth-d-depthTolerance) * aoMultiplier);
	ao+=div/(1.0+aot*aot);

	d=readDepth( vec2(texCoord.x,texCoord.y+ph));
	aot=min(aoCap,max(0.0,depth-d-depthTolerance) * aoMultiplier);
	ao+=div/(1.0+aot*aot);

	return ao;

}


void main(void)
{	
	float depth = readDepth( texCoord );
	float d;
	
	float ao = uao;
	float aoMultiplier=10000.0*mul;
	float depthTolerance = 0.0001;


	float pw=2.0;
	float ph=2.0;
	
	float multi=1.5;
	
	ao+=getblah(pw,ph,depth,aoMultiplier,depthTolerance);


	pw*=multi;
	ph*=multi;
	aoMultiplier*=0.9;
	ao+=getblah(pw,ph,depth,aoMultiplier,depthTolerance);
/*
	pw*=multi;
	ph*=multi;
	aoMultiplier*=0.9;
	ao+=getblah(pw,ph,depth,aoMultiplier,depthTolerance);
*/

	pw=20.0;
	ph=20.0;
	aoMultiplier*=0.8;
	ao+=getblah(pw,ph,depth,aoMultiplier,depthTolerance);

	ao/=24.0;

	vec4 finalColor=texture2DRect(texture1,texCoord);;

	if(depth==1.0)
	{
	}
	else
	{
		//ao=smoothstep(0.6, 1.0, ao-0.18);
		ao=smoothstep(finCapStart, finCapEnd, ao-finCapSub);
		
		finalColor=vec4(ao);
	}
	gl_FragColor =  finalColor;

	//gl_FragColor = texture2DRect(texture1,texCoord);
	//gl_FragColor = texture2DRect(texture1,texCoord);
}


