
uniform sampler2D texture0;
uniform sampler2D texture1;
varying vec2 uvVarying;

uniform vec2 agk_resolution;
uniform vec4 AmbientColor;
uniform vec3 Falloff;

uniform float LightCount;
uniform vec3 LightPosition[8];
uniform vec4 LightColor[8];

vec3 light(vec3 LightPos, vec4 LightColor)
{
	LightPos.y = agk_resolution.y -LightPos.y;
	vec3 normal = texture2D(texture1, uvVarying.xy).rgb;
	vec3 LightDir = vec3(LightPos.xy -gl_FragCoord.xy, LightPos.z);
    vec3 LDIR=normalize(LightDir);
	
	normal = normal * 2.0 - 1.0;
	vec3 NDIR=normalize(normal);
	
	float dist = length(LightDir);
	float Attenuation = clamp((1.0 / (Falloff.x +(Falloff.y * dist) +(Falloff.z * dist * dist))) * LightColor.w,0.0,1.0);
	return LightColor.rgb * max(dot(NDIR, LDIR), 0.0) * Attenuation;
}

void main()
{
	
    vec4 diffuse = texture2D(texture0, uvVarying.xy);
	vec3 Light = vec3( 0.0, 0.0, 0.0 );
	for(int i=0; i < int(LightCount); i++)
	{
		Light = Light + light(LightPosition[i], LightColor[i]);
	}

	gl_FragColor = diffuse * (AmbientColor + vec4(Light,0.0));

}