PDA

View Full Version : glReadPixels reading unexpected results



Rifat Aras
01-08-2008, 02:19 PM
Hello Everyone,

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



if (state == GLUT_DOWN)
{
switch (button)
{
case GLUT_LEFT_BUTTON:

GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
headSkinPatch->renderPatch();

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...

Luhtor
01-08-2008, 03:59 PM
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 ?

Relic
01-09-2008, 05:13 AM
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.

Rifat Aras
01-09-2008, 12:17 PM
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.