View Full Version : Is it really that I can't get a correct 3D coordinate from 2D screen?

helenw

05-13-2006, 09:19 PM

I wish to convert 2D screen coordinate to 3D(code below). But the Z value converted always can't control well. It's often worry.

How can I do?

glGetDoublev(GL_MODELVIEW_MATRIX, modelview);

glGetDoublev(GL_PROJECTION_MATRIX, projection);

glGetIntegerv(GL_VIEWPORT, viewport);

winX=(float)mouse_x;

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

glReadPixels(mouse_x,

int(winY),

1,1,

GL_DEPTH_COMPONENT,

GL_FLOAT,

&winZ);

gluUnProject((GLdouble)winX,(GLdouble)winY,(GLdoub le)winZ,modelview,projection,viewport,&object_x,&object_y,&object_z);

Overmind

05-14-2006, 05:27 PM

I see nothing wrong with your code. Of course, you might get some numerical errors, floating point math can never be exact.

Perhaps the modelview matrix at the time your code gets executed is not the same as the one used when drawing...

Btw. I don't think this is an advanced question ;)

helenw

05-14-2006, 07:29 PM

But I can't get the correct 3D coordinate. The x,y and z, especially z, are worry with these codes. It is difficultly to control the Z value.

I have the same problem and I can not get the z coordinate from the z buffer. Please, somebody help us

Andrew Adinetz

05-15-2006, 02:35 AM

Well, these difficulties may be connected to internal conversion of depth values. Remember that if you have set near and far depth with glDepthRange(n, f) or if your are using default values n = 0 and f = 1, the depth is converted according to the following formula:

zw = ((f-n)/2) * z + (f+n)/2;

Therfore, in the most simple case you just get your depth value divided by 2 before actually being written to the depth buffer (remember that after projection the depth value is between -1 and 1). I've had a problem with this once; so, you could just transform the value back (that is, multiply by 2 and subtract 1 in the simplest case) to get the value you think is correct.

jtipton

05-15-2006, 09:04 AM

The y coordinate should actually be

newY = height - y - 1

Secondly, the depth coordinates are not part of a linear scale. The closer the depth is to the near clipping plane, the better the accuracy. The farther it is, the more likely you are to run into issues. Make sure your near and far clipping planes are only as far apart as you need them to be, otherwise you are introducing greater error.

Powered by vBulletin® Version 4.2.5 Copyright © 2018 vBulletin Solutions Inc. All rights reserved.