user2027722
user2027722

Reputation: 195

OpenGL depth buffer isn't working

I am attempting to make a simple drawing using openGL. However, the depth buffer doesn't appear to be working.

Other people with a similar problem are typically doing one of two things wrong:

  1. Not including glEnable(GL_DEPTH_TEST)

  2. Bad clipping values

However, my code does not have either of these problems.

...
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

gluPerspective(25.0,1.0,10.0,200.0);

// Set the camera location
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(20.0, 10.0, 50.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);

// Enable depth test
glEnable(GL_DEPTH_TEST);

// Cull backfacing polygons
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE)

drawCoordinateAxis();

drawBox(5.0,2.0,5.0,0.8,0.0,0.0);

glTranslated(1.0,-1.0,1.0); //The box is 5x2x5, it is shifted 1 unit down and 1 in the x and z directions
drawBox(5.0,2.0,5.0,0.0,1.0,1.0);
...

When I execute my code, this is drawn. https://i.sstatic.net/eCcND.jpg

Note that the blue box and the red box collide, so the red box should be covering part of the blue box.

The functions drawCoordinateAxis() and drawBox() just draw a few primitives, nothing fancy inside.

I am running this on Debian squeeze.

Upvotes: 1

Views: 2744

Answers (1)

JohnD
JohnD

Reputation: 1159

void reshape(GLint width, GLint height)
{
   g_Width = width;
   g_Height = height;
   glViewport(0, 0, g_Width, g_Height);
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   gluPerspective(65.0, (float)g_Width / g_Height, g_nearPlane, g_farPlane);
   glMatrixMode(GL_MODELVIEW);
}

So set Matrix Mode to GL_PROJECTION first, then gluPerspective.... and then back to MODELVIEW mode.

Upvotes: 1

Related Questions