OpenGL lighting not working, GL_POSITION is in homogenous coordinates

Alec Jacobson

September 23, 2013

weblog/

A while ago I somehow introduced a bug in my opengl app that occasionally caused my app to render a shaded object without lighting like this:

gl lighting not working

instead of what I wanted which was this:

gl lighting working

Now, there must be 101 ways that you can screw up the opengl lighting. What I was doing was setting the light position incorrectly. I was calling something like:

float light[4];
light[0] = x;
light[1] = y;
light[2] = z;
glLightfv(GL_LIGHT0,GL_POSITION,light);

I new enough to use a 4-dimensional (homogenous) vector for the light direction. But I wasn't setting the w-component. I guess occasionally this was getting a crazy value like NaN and killing the lights.

float light[4];
light[0] = x;
light[1] = y;
light[2] = z;
light[2] = w;// e.g. w = 0 or 1
glLightfv(GL_LIGHT0,GL_POSITION,light);