// Copyright 2011 Riccardo Monica

#version 120

vec4 ApplyLight(in vec4 oColor, in vec3 relativepos, in vec3 normal,in int lightIndex)
  {
  vec3 intensity = vec3(0.0,0.0,0.0);

  vec3 lightpos = gl_LightSource[lightIndex].position.xyz / gl_LightSource[lightIndex].position.w;
  vec3 lightrelative = normalize(lightpos - relativepos); // incident light vector
      
  /* ambient */
  intensity += gl_LightSource[lightIndex].ambient.rgb * gl_LightSource[lightIndex].ambient.a * oColor.rgb;

  float dotp = dot(lightrelative,normal);
  if (dotp > 0.0) /* if face is not oriented towards light, apply only ambient light */
    {
    /* diffuse */
      {
      vec3 diffuse = gl_LightSource[lightIndex].diffuse.rgb * dotp * gl_LightSource[lightIndex].diffuse.a * oColor.rgb;
      intensity += diffuse;
      }
    /* specular */
      {
      vec3 reflected = reflect(lightrelative,normal);
      vec3 viewr = normalize(relativepos);
      float weight = pow(max(0.0,dot(reflected,viewr)),gl_FrontMaterial.shininess/4.0);
        // divide shininess by 4 to make it similar to Blinn-Phong model
      intensity += gl_LightSource[lightIndex].specular.rgb * weight * gl_LightSource[lightIndex].specular.a * 
        gl_FrontMaterial.specular.rgb * gl_FrontMaterial.specular.a;
      }
    }

  return vec4(clamp(intensity,0.0,1.0),oColor.a);
  }
