// normalMappingShader.vert

#version 150 core

// uniform shader-parameters
uniform vec4		light_color;
uniform vec4		ambient_color;

uniform sampler2D	texture_color;
uniform sampler2D	normalMap;
uniform sampler2DShadow	shadowMap;
//uniform sampler2D   shadowMap;

in vec2 frag_texCoord;	// to access textures, coordinates are needed
in vec2 frag_normalCoord;
in vec3 tangentLightDirection;
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 lightDirection = normalize(tangentLightDirection);

	// Since the normals in the normal map are in the (color) range [0, 1] we need to uncompress them
	// to "real" normal (vector) directions.
	// Decompress vector ([0, 1] -> [-1, 1])
	vec3 normalOutOfTexture = normalize(texture2D(normalMap, frag_normalCoord).rgb * 2.0 - 1.0);

	// enhance the normal mapping effect
	normalOutOfTexture = normalOutOfTexture*2.0f;

	// access texture at specified coordinates
	vec4 colorOutOfTexture = texture2D(texture_color, frag_texCoord);


	// calculate lighting
    vec4 ambient = ambient_color * colorOutOfTexture;
    vec4 diffuse = colorOutOfTexture * light_color * max(0.0, dot(normalOutOfTexture, lightDirection));


	// -------- 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;
}
