#version 400

// Information from the vertex shader about the eye-space location
//    of this fragment we're working on
in vec4 esFragPos;
in vec4 esFragNormal;

// Where to store the color we compute
out vec4 result;

uniform float useLambertian;  // Asked to use a Lambertian shading scheme?
uniform vec4 color;           // Surface color (we treat as either ambient or diffuse)
uniform vec4 esLightPos;      // Location of the light, relative to the eye

uniform mat4 shadMapMatrix;   // A matrix: eye-space position -> shadow map texture coordinate

// Our shadow map texture.  
uniform sampler2DShadow shadowTex;  


// This is the actual code that is executed.
void main( void )
{	
	// Transform from eye-space to shadow map texture coordinates
	vec4 smTexCoord = shadMapMatrix * esFragPos;
	smTexCoord /= smTexCoord.w;
	
	// Query depth from texture.  The x/y coordinates are used to select the pixel, the
	//    z-coordinate is used as the comparison reference to decide if the pixel is in
	//    shadow.  Basically, shadowTex(x,y) is queried, which returns a float 'val'.  'val'
	//    is compared to smTexCoord.z, and isShadowed is 1 or 0 depending on the result.
	// Basically: isShadowed = texture(shadowTex, smTexCoord.xy) < smTexCoord.z ? 1 : 0;
	//    if we were using normal textures, rather than a shadow sampler
	
	float isShadowed     = texture(shadowTex, smTexCoord.xyz); 
	
	// Find simple vectors for basic shading
	vec3 toLight = normalize( esLightPos.xyz - esFragPos.xyz);
	vec3 toEye   = normalize( -esFragPos.xyz );
	
	// Figure out the Lambertian color (if shadowed, set to 0)
	vec3 lambert = isShadowed * useLambertian * max( 0.0f, dot( normalize(esFragNormal.xyz), toLight ) ) * color.xyz;
	
	// Figure out the ambient color (if shadowed, set to 0)
	vec3 ambient = isShadowed * (1.0-useLambertian) * color.xyz;
	
	// The ambient & lambertian terms we computed above are mutually
	//    independent, so we simply add them together, giving us a correct
	//    answer, no matter which display approach the user has chosen.
	result = vec4( lambert + ambient, 1.0f );
}