glReadPixels reading unexpected results

Hello Everyone,

I have a problem using glReadPixels function. Let me post little code segment:

if (state == GLUT_DOWN)
		switch (button)

				GLint viewport[4];
				GLdouble modelview[16];
				GLdouble projection[16];

				glGetIntegerv(GL_VIEWPORT, viewport);
				glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
				glGetDoublev(GL_PROJECTION_MATRIX, projection);

				GLfloat winX, winY, winZ;
				winX = (float)x;
				winY = (float)viewport[3] - (float)y;
				glReadPixels(winX, winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
				GLdouble posX, posY, posZ;

				gluUnProject(winX,winY,winZ, modelview, projection, viewport, &posX, &posY, &posZ);

As you see in the code piece, after issuing glClear function, I only draw the object that I want to check with glReadPixels. After the checking is performed, I clear the buffer again and do the other drawing stuff. So on the screen, “the other drawing stuff” is shown. In this code piece, I expect to capture the coordinate information of the single drawn object, however I could not get the correct information.

What is wrong with my thinking? I would be grateful if you show me a solution…

Thanks in advance…

I do exactly the same and it works perfectly.

Give us an exemple of value taken by PosZ ?

Are you sure your matrix are correct ?

winY = (float)viewport[3] - (float)y;

Mind that your winY is off by one line.

viewport[3] is height of the viewport (e.g. 1024)
but mouse coordinates go from 0 to viewport[3] - 1 (e.g.1023)

The pixel-exact position would be
GLint winY = viewport[3] - 1 - y;

Use GLint for winX and winY because glReadPixels takes integer coordinates, where glUnProject takes GLdouble.

I think I have found the problem. I was trying this code in the mouse callback part. It was working well in the display callback. And in front of the display callback, there was regular OpenGL stuff like glMatrixMode(GL_MODELVIEW), glLoadIdentity… etc.

When I put the same stuff in front of the mouse callback, I saw that I could capture the coordinates correctly.

So I guess as Luhtor suggested my matrices were incorrect…

Thanks for replying.