mikepa88
mikepa88

Reputation: 813

Lighting not working on OpenGL - Solid color

The lighting doesn't work, the object appears with solid color. The color itself changes with the material or lighting parameters but no shadow or anything just solid grey.

Here's part of the code:

glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glFrontFace(GL_CCW);
glShadeModel(GL_FLAT);
glEnable(GL_LIGHTING);

GLfloat amb[] = {0.6, 0.6, 0.6, 1.0};
GLfloat dif[] = {0.8, 0.8, 0.8, 1.0};
GLfloat spec[] = {0.5, 0.5, 0.5, 1.0};
GLfloat pos[] = {0.0, 0.0, 30.0};

glEnable(GL_LIGHT0);    

glLightfv(GL_LIGHT0, GL_AMBIENT, amb);
glLightfv(GL_LIGHT0, GL_DIFFUSE, dif);
glLightfv(GL_LIGHT0, GL_SPECULAR, spec);
glLightfv(GL_LIGHT0, GL_POSITION, pos);


GLfloat co[4]={0.5, 0.5, 0.5, 0.5};
GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_shininess[] = { 1.0 }; 
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, co);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);

for(int i=0; i < numofTr; i++)
{       
glBegin(GL_TRIANGLES);
  glNormal3f(tr[i].v1->n.x, tr[i].v1->n.y, tr[i].v1->n.z);
  glVertex3f(tr[i].v1->x, tr[i].v1->y, tr[i].v1->z);    
  glNormal3f(tr[i].v2->n.x, tr[i].v2->n.y, tr[i].v2->n.z);
  glVertex3f(tr[i].v2->x, tr[i].v2->y, tr[i].v2->z);    
  glNormal3f(tr[i].v3->n.x, tr[i].v3->n.y, tr[i].v3->n.z);
  glVertex3f(tr[i].v3->x, tr[i].v3->y, tr[i].v3->z);    
glEnd();
}

I don't know what I'm missing, the normals look good when displayed along with the object.

Upvotes: 1

Views: 1540

Answers (1)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39390

You are using dim light on a gray object. Obviously the result is gray.

If you mean that faces are flat shaded, that's because of glShadeModel(GL_FLAT);. Change it to GL_SMOOTH to enable interpolation.

If the object is in 3D, I think that the fact you are only passing 3 floats as position might be relevant; default value is [0,0,1,0], and the function expects four floats (4th being the W coordinate, which should in most cases be equal to 1, or 0 for lights in infinite distance).

Also double check that the data you give to glVertex and glNormal is correct. When rendering a sphere at 0,0,0, the normal of every vertex is the normalized position of such vertex (only holds for spheres, obviously).


As a side note, this code is obviously outdated, and as a disclaimer I would ditch it alltoghether, if you are only learning, and switch to something that's relatively modern and uses programmable pipeline.

Upvotes: 2

Related Questions