#define MAX_LIGHTS 8
varying vec3 alightVec[MAX_LIGHTS];
varying vec3 aeyeVec[MAX_LIGHTS];
varying vec2 texCoord;
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 float invRadius;

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;

	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.0 - 1.0);

	//diffuse = max( dot(lVec, bump), 0.0 );
	diffuse = clamp( dot(lVec, bump), 0.0, 1.0 );
//	vDiffuse = gl_LightSource[i].diffuse * gl_FrontMaterial.diffuse * diffuse *
	vDiffuse = gl_LightSource[i].diffuse * diffuse *
		texture2D(lightMap, vec2(diffuse-0.01,lightMapSelect[i]));
	accvDiffuse = accvDiffuse + vDiffuse;

	specular = pow(clamp(dot(reflect(-lVec, bump), vVec), 0.0, 1.0),
	           gl_FrontMaterial.shininess );
	//vec4 vSpecular = gl_LightSource[0].specular * gl_FrontMaterial.specular * specular;
//	vSpecular = gl_LightSource[i].specular * gl_FrontMaterial.specular * specular *
	vSpecular = gl_LightSource[i].specular * specular *
		texture2D(lightMap, vec2(specular-0.01,lightMapSelect[i]));
	accvSpecular = accvSpecular + vSpecular;
	}
   }
	gl_FragColor = ( vAmbient*base + accvDiffuse*base + accvSpecular) * att;
	//gl_FragColor = ( vAmbient*base + vDiffuse*base + vSpecular) * att;
	//gl_FragColor = ( vAmbient*base + vDiffuse*base + texture2D(lightMap, vec2(1.0-specular,0))) * att;
}

/*
uniform sampler2D color_texture;
uniform sampler2D normal_texture;

void main() {

// Extract the normal from the normal map
vec3 normal = normalize(texture2D(normal_texture, gl_TexCoord[0].st).rgb * 2.0 - 1.0);

// Determine where the light is positioned (this can be set however you like)
vec3 light_pos = normalize(vec3(1.0, 1.0, 1.5));

// Calculate the lighting diffuse value
float diffuse = max(dot(normal, light_pos), 0.0);

vec3 color = diffuse * texture2D(color_texture, gl_TexCoord[0].st).rgb;

// Set the output color of our current pixel
gl_FragColor = vec4(color, 1.0);
}
*/
