Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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;
share|improve this answer
    
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
1  
@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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.