 // shader.frag
 
#version 150 core

// uniform shader-parameters
uniform vec3		light_vector;
uniform vec4		light_color;
uniform vec4		ambient_color;
uniform sampler2D	texture_color;
uniform sampler2DShadow	shadowMap;
//uniform sampler2D	shadowMap;

// fragment-shader input variables
in vec3 world_normal;
in vec2 frag_texCoord;
in vec4 SM_texCoord;

// fragment-shader output variable (-> stored in the frame-buffer, i.e. "the pixel you see")
out vec4 fragColor;


void main()
{
	vec3 normal = normalize(world_normal);
    
	vec4 texel = texture2D(texture_color, frag_texCoord);

	// calculate lighting
    vec4 ambient = ambient_color * texel;
	float NdotL = max(0.0, dot(normal, light_vector));
    vec4 diffuse = texel * light_color * NdotL;


	// -------- SHADOW MAP LOOKUP
	// perspective division, depth-comparison and PCF is implicitly carried out by the GPU
	float bias = -0.001 * SM_texCoord.w;
	vec4 coordPos = SM_texCoord;
	coordPos.z = coordPos.z + bias;
	float shadow = textureProj(shadowMap, coordPos);

	//vec3 coordPos  = SM_texCoord.xyz / SM_texCoord.w;
	//float shadow = texture(shadowMap, coordPos.xy).r < (coordPos.z - 0.001) ? 0.0 : 1.0;

	// -------- SHADOW MAP LOOKUP
	
    // write color to output
	fragColor = ambient + shadow*diffuse;
}
