Drawing behind another object

Hi, can I display rectangle r1 behind rectangle r2 even if I displayed r1 first? See code below


//this is r1

glBegin(GL_QUADS);
	glTexCoord2d(0, 1);
	glVertex2d(0, 100);

	glTexCoord2d(1, 1);
	glVertex2d(100, 100);

	glTexCoord2d(1, 0);
	glVertex2d(100, 0);

	glTexCoord2d(0, 0);
	glVertex2d(0, 0);
glEnd();

And then I created another rectangle r2 but I want this to be printed behind r1


//this is r2

glBegin(GL_QUADS);
	glTexCoord2d(0, 1);
	glVertex2d(0, 100);

	glTexCoord2d(1, 1);
	glVertex2d(100, 100);

	glTexCoord2d(1, 0);
	glVertex2d(100, 0);

	glTexCoord2d(0, 0);
	glVertex2d(0, 0);
glEnd();

Is there a function say for example “glDrawBehind()” where I will call before the glBegin() of r2? So that it will be displayed behind r1? Thanks!

Take a look at OpenGL Redbook Chapter 5 Section “A Hidden-Surface Removal Survival Kit”

Somewhere in your iniitailization you need to enable once


glutInitDisplayMode(GLUT_DEPTH|...); // may have to find equivalent command in SDL or whatever library you use
glEnable(GL_DEPTH_TEST);

Then draw your r2 rectangle behind r2 by setting z2 < z1. To do this you must use glVertex3d ie add a z-component to all your vertex calls (and change “2d” to “3d”


glClear(...| GL_DEPTH_BUFFER_BIT); //add to your present glClear

//this is r1

glBegin(GL_QUADS);
	glTexCoord2d(0, 1);
	glVertex3d(0, 100, 0.1);

	glTexCoord2d(1, 1);
	glVertex3d(100, 100, 0.1);

	glTexCoord2d(1, 0);
	glVertex3d(100, 0, 0.1);

	glTexCoord2d(0, 0);
	glVertex3d(0, 0, 0.1);
glEnd();

//this is r2

glBegin(GL_QUADS);
	glTexCoord2d(0, 1);
	glVertex3d(0, 100, -0.1);

	glTexCoord2d(1, 1);
	glVertex3d(100, 100, -0.1);

	glTexCoord2d(1, 0);
	glVertex3d(100, 0, -0.1);

	glTexCoord2d(0, 0);
	glVertex3d(0, 0, -0.1);
glEnd();


I think there is much better and easier way to solve the problem… Using glDepthFunc(GL_LEQUAL).

The glDepthFunc() function specifies the function used to compare each incoming fragment z value with the z value present in the Z-buffer. The comparison is performed only if depth testing is enabled. Default value is GL_LESS, which means only fragments with depth less than already stored will be drawn. The precision of the calculation depends on the distance of the near and far clipping planes. Keep them near each other, and everything will work fine.