////// Maps and "constant" parameters
sampler colorMap;
sampler blurMap;

float2 pixelSizeColorMap;
float2 pixelSizeBlurMap;

// contains poisson-distributed positions on the unit circle
float2 poisson[8] = {  
  float2( 0.0,      0.0),
  float2( 0.527837,-0.085868),
  float2(-0.040088, 0.536087),
  float2(-0.670445,-0.179949),
  float2(-0.419418,-0.616039),
  float2( 0.440453,-0.639399),
  float2(-0.757088, 0.349334),
  float2( 0.574619, 0.685879)
};

////// Technical parameters
// maximum CoC radius and diameter in pixels
float2 vMaxCoC;

// scale factor for maximum CoC size on low res. image
float radiusScale;

// Number of taps
#define NUM_TAPS 8


float4 Main(float2 tex : TEXCOORD0) : COLOR
{	        	 
	float4 cOut = tex2D(colorMap, tex);  
	float centerDepth = cOut.a;
	
	// convert depth into blur radius in pixels
	float discRadiusColorMap = abs(centerDepth * vMaxCoC.y - vMaxCoC.x);

	// compute disc radius on low-res image
	float discRadiusBlurMap = discRadiusColorMap * radiusScale;

	cOut = 0;
	for(int t = 0; t < NUM_TAPS; t++)
	{
		float2 tapSourceCoord = tex + (pixelSizeColorMap * poisson[t] * discRadiusColorMap);
		float4 tapSourceColor = tex2D(colorMap, tapSourceCoord);
		
		float2 tapBlurCoord =  tex + (pixelSizeBlurMap * poisson[t] * discRadiusBlurMap);
		float4 tapBlurColor = tex2D(blurMap, tapBlurCoord);
		
		float tapBlur = abs(tapSourceColor.a * 2.0 - 1.0);
		float4 tapColor = lerp(tapSourceColor, tapBlurColor, tapBlur);
	
		tapColor.a = (tapColor.a >= centerDepth) ? 1.0 : abs(tapColor.a * 2.0 - 1.0);
		
		cOut.rgb += tapColor.rgb * tapColor.a;
		cOut.a += tapColor.a;
	}
	
	return (cOut / cOut.a);
}
