Jump to content
  • Advertisement
Sign in to follow this  

OpenGL Slightly confusing Z value problem

This topic is 4851 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm working on writing a simple graphics engine, and I've got the window creation and setup for OGL working fine, but drawing seems to be another matter.
while( engine.run() ){
	driver->beginScene();	// clears the window with glClear




		glColor3f(1.0f, 1.0f, 1.0f);
		glVertex3f(0,   0,   1);
		glVertex3f(50,  100, 1);
		glVertex3f(100, 50,  1);



	driver->endScene();	// actually renders the window

Here's what I'm trying to draw just to make sure that drawing works. I have this drawing, but something is confusing me. Why am I able to see it? I was under the impression that when you draw something at a positive z value, then it is drawn behind the camera, and a negative z value is in front of the camera. I mean, I haven't moved the camera or anything. Here's my OGL init code, and the beginScene and endScene functions:
 * Initialises the video driver.
 * \param screenSize A dimension2d object containing the height and width of the screen
bool COpenGLDriver::initDriver(const video::dimension2d& screenSize)
	int nPixelFormat;

		sizeof(PIXELFORMATDESCRIPTOR),		// size of the structure
		1,									// version. Always set to 1
		PFD_DRAW_TO_WINDOW |				// support window
		PFD_SUPPORT_OPENGL |				// support opengl
		PFD_DOUBLEBUFFER,					// support double buffering
		PFD_TYPE_RGBA,						// RGBA color mode
		32,									// 32-bit color mode
		0, 0, 0, 0, 0, 0,					// ignore color bits, not used
		0,									// no alpha buffer
		0,									// ignore shift bit
		0,									// no accumulation buffer
		0, 0, 0, 0,							// ignore accumulation bits
		16,									// 16-bit z-buffer size
		0,									// no stencil buffer
		0,									// no auxillary buffer
		PFD_MAIN_PLANE,						// main drawing plane
		0,									// reserved
		0, 0, 0								// layer masks ignored

	// if get hdc fails
	if( !(hDC = GetDC(Window)) ){
		util::Message::print("COpenGLDriver::initDriver: Cannot create a GL device context.");
		return false;

	// chose best matching pixel format, return index
	if( !(nPixelFormat=ChoosePixelFormat(hDC, &pfd)) ){
		util::Message::print("COpenGLDriver::initDriver: Cannot find a suitable pixel format.");
		return false;

	// set pixel format to device context
	if( !SetPixelFormat(hDC, nPixelFormat, &pfd) ){
		util::Message::print("COpenGLDriver::initDriver: Cannot set the pixel format.");
		return false;

	// create rendering context
	if( !(hRC=wglCreateContext(hDC)) ){
		util::Message::print("COpenGLDriver::initDriver: Cannot create a GL rendering context.");
		return false;

	// activate rendering context
	if( !wglMakeCurrent(hDC, hRC) ){
		util::Message::print("COpenGLDriver::initDriver: Cannot activate GL rendering context.");
		return false;

	glViewport(0, 0, (int)screenSize.width, (int)screenSize.height);	// reset the current opengl viewport

	glShadeModel(GL_SMOOTH);		// enable smooth shading

	glDisable(GL_LIGHTING);			// lighting disabled
	glFrontFace(GL_CW);				//

	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);		// really nice perspective calculations

	glClearDepth(1.0f);			// set gl clear depth

	return true;	// init went well

 * Does OGL housekeeping, like clearing the screen and depth buffer
 * \param c A CColor object that represents the color to clear the screen to. Defaults to black.
void COpenGLDriver::beginScene(video::CColor c = video::CColor(0.0f,0.0f,0.0f))
	glClearColor(	c.getRedFloat(), c.getGreenFloat(),
					c.getBlueFloat(), c.getAlphaFloat()
				);						// Set clear color

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear Screen And Depth Buffer

 * Does OGL housekeeping for the end of rendering a frame.
void COpenGLDriver::endScene()
	SwapBuffers(hDC);	// render the scene to the window

Is it something that I've done in complete ignorance? I am able to see the triangle in a range of about -1 to +1. Any ideas? Because this doens't look different from other OGL init code that I've gotten from tutorials.

Share this post

Link to post
Share on other sites
Yes, you are correct about the way z values work.
To nitpick, opengl doesn't actually think of the view in terms of a "camera". Think of it in terms of moving the object you're drawing towards (positive) or away from (negative) the viewer. You can always perform a translation first if you prefer to use positive numbers. Do it before your calls to glBegin ... glEnd and not during.

glTranslatef(0.0f,0.0f,-10.0f) or something. What that's doing in english is moving the object 10 units into the screen along the z axis (away from the camera).

You can only see the triangle in a short range onscreen because the viewing frustum (what you can see onscreen) is set up this way by default. You can alter this:

glViewport (0, 0, (GLsizei)(windowwidth), (GLsizei)(windowheight)); // Reset The Current Viewport
glMatrixMode (GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity (); // Reset The Projection Matrix
gluPerspective (45.0f, (GLfloat)(windowwidth)/(GLfloat)(windowheight),1.0f, 500.0f); // Calculate The Aspect Ratio Of The Window
glMatrixMode (GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity (); // Reset The Modelview Matrix

Could be placed in the initialisation routine, although it would serve much better as part of a routine called when the window is resized as well. The key part is the gluPerspective call. (you'll need to #include <gl/glu.h>) 45.0f is the fov in the y direction (in degrees), and the 1.0f and 500.0f correspond to the front and back clipping planes of the view frustum, and are always positive values. In this example, you will only see things that are at least 1.0f in front of the "camera", and at most 500.0f units away from (still in front of) the camera. Try playing with these values.

When you rotate the camera around on the screen, you're actually rotating the objects around the camera (initially, but if you do translations followed by rotations this isn't true), but in any case it means that polygons with negative z values will be visible when you rotate them into view.

Hope that helps

Also, you're using the glVertex3f command, which expects coordinates specified using floats. Although it doesn't really matter that much, get into the habit of writing 1.0f instead of 1 (as that's an integer). Makes no difference to a human but it'll get rid of some compilation warnings (it's satisfying to see your code compile with 0 warnings & 0 errors :) )

i.e. glVertex3f(0.0f, 0.0f, 1.0f);

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!