#ifdef GL_ES
// Set default precision to medium
precision mediump int;
precision mediump float;
#endif

uniform vec3 eyeWorldPos;
uniform vec3 lightWorldPos;

uniform sampler2D texDiffuse;
uniform sampler2D texNormalMap;
uniform float alpha;

// interpolated values
varying vec3 v_WorldPos;
varying vec3 v_CamPos;
varying vec3 v_normal;
varying vec2 v_texcoord;
varying mat3 normalMat;

void main() {

	// diffuse fragment color

	vec4 ambient = texture2D(texDiffuse, v_texcoord);
	vec4 diffuse = ambient * vec4(0.8, 0.8, 0.8, 1.0);
	vec4 specular = vec4(1,1,1,1);

	// get the normal from the normal map
	//vec3 normal = vec3(0,0,1);
	vec3 normal = normalize(texture2D(texNormalMap, v_texcoord).rgb - 0.5) * 2.0;
	// and convert from texture's normal-space into the object's normal-space using the normal-matrix
	normal = normalize(normalMat * normal);


	// direction from fragment towards the light
	vec3 lightDir = normalize(lightWorldPos - v_WorldPos);

	// direction from fragment towards the eye
	vec3 eyeDir = normalize(eyeWorldPos - v_WorldPos);


	// diffuse lighting
	float diffuseIntensity = max(dot(lightDir, normal), 0.0);

	// specular lighting
//	vec3 h = normalize(lightDir + eyeDir);
//	float intSpec = max(dot(h, normal), 0.0);
//	float specularIntensity = pow(intSpec, 2.0);
	float specularIntensity = pow(max(0.0, dot(eyeDir, reflect(-lightDir, normal))), 16.0);


	// distance between fragment and light (in meter)
	float distToLight_m = length(lightWorldPos - v_WorldPos);
	float lightInt = 1.0;//clamp(1.0 / (distToLight_m / 10.0), 0.0, 1.0);

	// Set fragment color from texture
	vec4 finalColor =
	    ambient * 0.30 +
	    diffuse * 0.70 * diffuseIntensity * lightInt +
		clamp(specular * specularIntensity, 0.0, 1.0) * 1.0;

	gl_FragColor = clamp(finalColor, 0.0, 1.0);
	gl_FragColor.a = alpha;

	// FOG
	//float mixing = pow((1.0 - v_CamPos.z * 3.0), 2);
	//gl_FragColor = mix(gl_FragColor, vec4(0.5, 0.5, 0.5, 1.0), 1.0-mixing);

	//gl_FragColor = gl_FragColor * 1;

//	gl_FragColor =
//		ambient * 0.001 +
//		diffuse * 0.009 * diffuseIntensity +
//		specular * 0.6 * specularIntensity;


}
