I am using OpenGL 2.1 and GLSL 1.20 .
I am trying to compute the fragment color applying the Phong lighting model.
This is the formula I have (the original formula has a summation, but since the light is only one it's not needed):
Ip = Ka * Ia + Kd * (Lm • N) * Id + Ks * (Rm • V)^s * Is
With:
Ka, Kd, Ks, s respectively material's ambient, diffuse, specular and shininess values;
Ia, Id, Is respectively light ambient, diffuse and specular values;
N surface normal;
Lm direction vector point-light;
Rm= 2.0 * (Lm • N) * N - Lm .
So this is the vertex shader:
#version 120
varying vec3 position; // I'll pass the position and the normal to
varying vec3 normal; // the fragment shader
varying vec4 diffuse; // I'll compute here the ambient and diffuse
varying vec4 ambient; // values and pass them to the fragment shader
void main()
{
gl_Position = ftransform();
position= vec3(gl_Position);
gl_TexCoord[0] = gl_MultiTexCoord0;
normal= normalize(gl_NormalMatrix * gl_Normal);
ambient= gl_FrontMaterial.ambient * gl_LightSource[0].ambient;
ambient+= gl_LightModel.ambient * gl_FrontMaterial.ambient;
diffuse= gl_FrontMaterial.diffuse * gl_LightSource[0].diffuse;
}
And this is the fragment shader:
#version 120
varying vec3 position;
varying vec3 normal;
varying vec4 diffuse;
varying vec4 ambient;
void main()
{
gl_FragColor= ambient+diffuse;
vec3 Lm= vec3(normalize(position-vec3(gl_LightSource[0].position)));
vec3 V= vec3(normalize(-position));
float LdotN= max(dot(Lm,normal),0.0); // Since I'll use this two times
// I compute it just once and reuse it
vec3 Rm= 2.0* LdotN * normal-Lm;
// First part of the formula: Kd * (Lm • N) * Id
gl_FragColor+= gl_FrontMaterial.diffuse * LdotN * gl_LightSource[0].diffuse;
// Second part: Ks * (Rm • V)^s * Is
gl_FragColor+= gl_FrontMaterial.specular* pow(max(dot(Rm,V),0.0),gl_FrontMaterial.shininess)* gl_LightSource[0].specular;
}
The result is unrealistic, it seems like the specular light is not really applied:
I tried with a teapot and this is the result:
After changing the camera position (the teapot was covering the light):
I think it's ok.