#version 400

uniform sampler2DMS  theRenderTex;
uniform sampler2D    alphaTex;
uniform int          numSamples; 
uniform vec4         color;

in vec4 esFragNormal;
in vec4 esFragPos;
in vec4  ndcPos;
in float vertID;

layout(location = 0) out vec4 result;
layout(location = 1) out vec4 outAlpha;


// This is the actual code that is executed.
void main( void )
{
	vec4 ndc        = ndcPos / ndcPos.w;
	vec2 fTexCoord  = 0.5 * ndc.xy + 0.5;
	ivec2 iTexCoord = ivec2(textureSize(theRenderTex) * fTexCoord);
	
	vec3 fragColor = color.xyz * abs( dot( normalize( esFragNormal.xyz ), normalize( -esFragPos.xyz ) ) );
	
	float visCount = 0;
	float R        = 0;
	for(int i = 0; i < numSamples; i++)
	{
		vec4 sampleDepth = texelFetch(theRenderTex, iTexCoord, i);
		visCount        += (gl_FragCoord.z <= (sampleDepth.x+5e-5)) ? 1.0f : 0.0f; 
		//visCount        += (gl_FragCoord.z <= sampleDepth.x) ? 1.0f : 0.0f; 
		R               += sampleDepth.x <= 1.0f ? 1.0f : 0.0f; 
	}
	
	// Output the color to the appropriate multisamples
	float fragAlpha = (color.w * visCount) / float(numSamples);
	result = vec4( fragColor * fragAlpha, fragAlpha );
	
	// We're going to use a second buffer to multiply the alphas of all frags for this pixel
	outAlpha = vec4( 1.0f - color.w, 0, 0, 0 );
}