#version 120

precision highp float;
#define MAX_LIGHTS 8

in vec3 alightVec[MAX_LIGHTS];
in vec3 aeyeVec[MAX_LIGHTS];
in vec2 texCoord;

in vec4 vpos; 
uniform int renderingmirror;
uniform vec4 clipeq;

in float ShadowAngle;
in vec4 ShadowCoord;

uniform vec4 glColor;

uniform float bias;
uniform float lightsEnabled[MAX_LIGHTS];
uniform float lightsinvRadius[MAX_LIGHTS];
uniform float lightMapSelect[MAX_LIGHTS];
uniform sampler2D colorMap;
uniform sampler2D normalMap;
uniform sampler2D lightMap;


uniform sampler2D shadowMap;



void main (void)
{

vec3 lightVec;
vec3 eyeVec;
vec4 accvDiffuse = vec4(0.0);
vec4 accvSpecular = vec4(0.0);
float distSqr;
vec3 lVec;
vec3 vVec;
float att;
vec4 base;
vec4 vAmbient;
vec3 bump;
float diffuse;
vec4 vDiffuse;
vec4 vSpecular;
float specular;
vec3 nrmltexture;

   

    if (renderingmirror>0 && dot(clipeq, vpos) < 0) {
        discard;
    }
	base = texture2D(colorMap, texCoord);
	vAmbient = gl_LightSource[0].ambient * gl_FrontMaterial.ambient;
for (int i=0; i<MAX_LIGHTS; i++)
   {
	if (lightsEnabled[i]>0.0)
	{
        lightVec=alightVec[i];
        eyeVec=aeyeVec[i];
	distSqr = dot(lightVec, lightVec);
	att = clamp(1.0 - lightsinvRadius[i] * sqrt(distSqr), 0.0, 1.0);
	lVec = lightVec * inversesqrt(distSqr);
	vVec = normalize(eyeVec);

    
    
	
	bump = normalize( texture2D(normalMap, texCoord).xyz * 2.0f - 1.0);
	

	
	diffuse = clamp( dot(lVec, bump), 0.0, 1.0 );

	vDiffuse = gl_LightSource[i].diffuse * diffuse *
		texture2D(lightMap, vec2(diffuse-0.01,lightMapSelect[i]));
	accvDiffuse = accvDiffuse + vDiffuse;

	
	           

	
	
    specular = pow(diffuse,48.0f);

	

	vSpecular = gl_LightSource[i].specular * specular * texture2D(lightMap, vec2(specular-0.01,lightMapSelect[i]));
	accvSpecular = accvSpecular + vSpecular;
	}
   }
	
	



float biasx=bias;
float visibility = 1.0;
vec4 v1;
ShadowAngle=clamp(ShadowAngle,0.0f,1.0f);

if ( texture2D( shadowMap, ShadowCoord.xy ).z  <  ShadowCoord.z-biasx){ 
    visibility = 0.5;
}

if (ShadowCoord.x<0.0f) visibility=1.0;
if (ShadowCoord.x>1.0f) visibility=1.0;
if (ShadowCoord.y<0.0f) visibility=1.0;
if (ShadowCoord.y>1.0f) visibility=1.0;
    float r1=ShadowAngle;
    float g1=ShadowAngle;
    float b1=ShadowAngle;
    v1 = vec4((vec4(r1,g1,b1,1.0f)*visibility).rgb,1.0f);
    v1= vec4(1.0f,1.0f,1.0f,1.0f)-((vec4(1.0f,1.0f,1.0f,1.0f)-v1)/1.5f);

    
    

    
	gl_FragColor = base*glColor;



    
    
}
