# vec4 for vec3 multiplication while calculating the specular value

I'm following this tutorial to calculate the specular color of a vertex.

I use OpenGL 2.1 with GLSL version 120.

This is the formula that I apply:

spec= (R*eye)^s * Ls * Lm

With:

L= direction vector light-vertex;
N= vector normal;
eye= direction vector vertex-eye;
R= -2N * (L*N) + L;

Now the problem is that following this way I need to multiply a vec3 for a vec4.

This is what I tried to do:

vec4 L= normalize(gl_LightSource[0].position - gl_Position);
vec3 N= normalize (gl_NormalMatrix * gl_Normal);
vec4 eye= normalize(-gl_Position);
vec4 R= -2.0*N*(L*N)+L;  // Syntax error: N is a vec3
vec4 spec= (R*eye)* gl_LightSource[0].specular;


I wouldn't get a vec3 result when calculating the specular value, this value I would be ignoring the alpha value. How do I go around this?

It needs to be a vec3 because the 4th component of the homogeneous coordinates is only used for 3D transformations. If you use them for eg. dot products, they will likely pollute the final result.

Speaking of dot products, R*eye is most probably wrong; you want dot(R,eye) instead.

Also, the dot product should be saturated to avoid negative values.

This code should work better:

vec3 L = normalize(gl_LightSource[0].position.xyz - gl_Position.xyz);
vec3 N = normalize((gl_NormalMatrix * gl_Normal).xyz);
vec3 eye = normalize(-gl_Position.xyz);
vec3 R = -2.0 * N * max(dot(L, N), 0.0) + L;
vec3 spec = max(dot(R, eye), 0.0) * gl_LightSource[0].specular.rgb;


Finally, the specular power (sometimes called shininess) should be applied to dot(R, eye) before being multiplied by the specular colour, so something like this:

vec3 spec = pow(max(dot(R, eye), 0.0), shininess)
* gl_LightSource[0].specular.rgb;

• This was I'm missing the alpha value, may I just set it to 1.0? Like this: gl_FragColor+= vec4(spec,1.0); ? – Ramy Al Zuhouri Feb 2 '13 at 20:26
• @RamyAlZuhouri Usually the alpha value does not come from the same light calculations as the colour value. You can certainly set it to 1.0 if your object is supposed to be opaque. – sam hocevar Feb 2 '13 at 20:38