uniform sampler2D Texture;
uniform sampler2D NormalMap;
uniform sampler2D HeightMap;
uniform sampler2DShadow ShadowMap01;
uniform sampler2DShadow ShadowMap02;
uniform sampler2DShadow ShadowMap03;
uniform float AmbientValue;
uniform float Light0Intensity;
uniform float Light1Intensity;
uniform float SpecularExponent;
uniform float SpecularFactor;
uniform vec3 Color;
uniform float Transparency;


varying vec4 projCoordShadow01;
varying vec4 projCoordShadow02;
varying vec4 projCoordShadow03;
varying vec2 coordTex;

varying vec3 lightVec; 
varying vec3 eyeVec;


float fBumpScale = 0.07;

void main()
{

	vec4 shadowValue = vec4(Light0Intensity) * vec4(shadow2DProj(ShadowMap01, projCoordShadow01)) *
				vec4(Light1Intensity) * vec4(shadow2DProj(ShadowMap02, projCoordShadow02)) +
				vec4(shadow2DProj(ShadowMap03, projCoordShadow03));


	vec3 vVec = normalize(eyeVec);

	float fDepth = tex2D(HeightMap, coordTex).x;
	float2 vHalfOffset = vVec.xy * (fDepth) * fBumpScale;

	fDepth = (fDepth + tex2D(HeightMap, coordTex + vHalfOffset).x) * 0.5;
	vHalfOffset = vVec.xy * (fDepth) * fBumpScale;

	fDepth = (fDepth + tex2D(HeightMap, coordTex + vHalfOffset).x) * 0.5;
	vHalfOffset = vVec.xy * (fDepth) * fBumpScale;

	fDepth = (fDepth + tex2D(HeightMap, coordTex + vHalfOffset).x) * 0.5;
	vHalfOffset = vVec.xy * (fDepth) * fBumpScale;

	coordTex += vHalfOffset;
	
	vec4 lightValue;
	if (Color.r == 0.0 && Color.g == 0.0 && Color.b == 0.0)
	{
		lightValue = texture2D(Texture, coordTex);
		float distSqr = dot(lightVec, lightVec);
		
	    
		vec3 lVec = lightVec * inversesqrt(distSqr);
		vec3 bump = normalize(texture2D(NormalMap, coordTex).xyz * 2.0 - 1.0);
		float diffuse = max(dot(lVec, bump), 0.0);
		float specular = pow(clamp(dot(reflect(-lVec, bump), vVec), 0.0, 1.0), SpecularExponent) * SpecularFactor;
		
		//gl_FragColor = diffuse;
		//gl_FragColor = specular;
		gl_FragColor = AmbientValue * diffuse * lightValue + (1.0 - AmbientValue) * (diffuse * lightValue + specular) * shadowValue;
	}
	else if (Color.r != 0.0 || Color.g != 0.0 || Color.b != 0.0)
	{
		lightValue = vec4(Color, 1.0 - Transparency);
		gl_FragColor = lightValue;
	}

}