uniform sampler2D tex;

varying vec4 diffuse, ambient;
varying vec3 normal, pos;


void main() {
  vec3 n, l, refl, eye;
  float NdotL, RdotE;
  vec4 specularColor;
  float dist, distSq, att, specularFactor;
  
  n = normalize(normal);
  
  l = gl_LightSource[0].position.xyz - pos;
  
  distSq = dot(l, l);
  
  NdotL = dot(n, l);

  if (NdotL > 0.0) {
    dist = sqrt(distSq);
    
    att = 1.0 / (gl_LightSource[0].quadraticAttenuation * distSq);
    gl_FragColor = att * (diffuse * NdotL / dist + ambient) * texture2D(tex, gl_TexCoord[0].st);
    
    refl = reflect(-l, n);
    
    RdotE = -dot(refl, pos) / sqrt(dot(refl, refl) * dot(pos, pos));
    
    if(RdotE > 0.0) {
      specularFactor = att * pow(RdotE, gl_FrontMaterial.shininess);
      gl_FragColor += specularFactor * gl_FrontMaterial.specular * gl_LightSource[0].specular;
    }
  }
  else {
    gl_FragColor = vec4(0, 0, 0, 1);
  }
}
