varying vec3 nor, lightPos;
/*uniform bool two_sided_light;*/
/*uniform int nbLights;*/
#define two_sided_light true
#define nbLights 4

vec4 light_(in vec4 color, in gl_MaterialParameters mat, in gl_LightModelProducts lmp)
{
  vec3 n = normalize(nor);

  if(two_sided_light && !gl_FrontFacing)
    n = -n;

  vec4 light = lmp.sceneColor;
  vec4 specular = vec4(0.0);

  for(int i = 0 ; i < nbLights ; i++)
  {
    vec3 ld;
    if(gl_LightSource[i].position.w == 0)
      ld = gl_LightSource[i].position.xyz;
    else
      ld = gl_LightSource[i].position.xyz/gl_LightSource[i].position.w - lightPos;

    float l = length(ld);
    if(l > 0)
    {
      ld /= l;
      float dld = dot(n,ld);
      float lightIntensity = max(dld, 0.0);

      vec4 diffuseLight = lightIntensity * (color * gl_LightSource[i].diffuse);

      float spot = 1.0;
      if(gl_LightSource[i].spotCutoff != 180)
      {
        if(-dld >= gl_LightSource[i].spotCosCutoff)
          spot = pow(dot(-ld,gl_LightSource[i].spotDirection), gl_LightSource[i].spotExponent);
        else
          spot = 0.0;
      }
      float ldl = length(ld);
      float att = 1.0;
      if(gl_LightSource[i].position.w != 0)
      {
        att = 1.0 / (gl_LightSource[i].constantAttenuation +
                     gl_LightSource[i].linearAttenuation*ldl +
                     gl_LightSource[i].quadraticAttenuation*ldl*ldl);
      }

      vec3 halfVector = normalize(gl_LightSource[i].halfVector.xyz);
      float spec = pow(max(dot(n, normalize(halfVector)), 0.0), mat.shininess);
      vec4 specularLight = (lightIntensity != 0 ? spec * (mat.specular * gl_LightSource[i].specular) : vec4(0.0));

      light += spot*att*(diffuseLight + color * gl_LightSource[i].ambient);
      specular += spot*att*specularLight;
    }
  }
  vec4 result;
  result = light + specular;
  result.a = color.a;
  return result;
}

vec4 light(in vec4 color)
{
  if(gl_FrontFacing)
    return light_(color, gl_FrontMaterial, gl_FrontLightModelProduct);
  else
    return light_(color, gl_BackMaterial, gl_BackLightModelProduct);
}
