2D Screen Position to 3D Position

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

Recommended Posts

Hello! I have this function that is supposed to use the (x, y) of the mouse find the 3D position the mouse is pointing at. It seems to be returning the position relative to the camera rather than real-world coordinates. How do I get the real-world coordinates rather than these camera-relative coordinates?

My code takes the (x, y) of the mouse and gets the depth value at that (x, y) location and then hands it gluUnProject with the viewport and modelview/projection matrices.

In my test-case scenario I have +Y as up in my scene, and +Y as up for my camera. The ViewPort is 800x600 with the camera rotated (0, 0, 0) and translated (0, 0, -2). I then draw a plane from (-100, -100, 0) to (100, 100, 0). From there I have taken a series of "test-clicks" with the mouse at (0, 0), (800, 0), (800, 600), (0, 600), and (400, 300).

The code and test-case output are as follows:

vector3df get3DLocation(s32 x, s32 y) {    GLint viewport[4];    f64 modelview[16];    f64 projection[16];    f32 winX, winY, winZ;    f64 posX, posY, posZ;    glGetDoublev(GL_MODELVIEW_MATRIX, modelview);    glGetDoublev(GL_PROJECTION_MATRIX, projection);    glGetIntegerv(GL_VIEWPORT, viewport);    winX = (f32)x;    winY = (f32)y;    glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);    gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);    return vector3df((f32)posX, (f32)posY, (f32)posZ);}Mouse Location 1: 0, 0Real Location 1: -1.104570, -0.828427, -2.000000Mouse Location 2: 800, 0Real Location 2: 1.104570, -0.828427, -2.000000Mouse Location 3: 800, 600Real Location 3: 1.104570, 0.828427, -2.000000Mouse Location 4: 0, 600Real Location 4: -1.104570, 0.828427, -2.00000Mouse Location 5: 400, 300 (center of the screen)Real Location 5: 0.000000, 0.000000, -2.00000

The Z coordinate from the Real-locations appear to be relative to the depth-factor. The x/y coordinates seem to be relative to the center of the screen.

How would I get the real-world coordinates from OGL, or convert these to real-world coordinates? Thanks beforehand!

EDIT: An additional note, the calls to get3DLocation() are happening after the scene is rendered, aka after camera transformations.

[Edited by - thefrost on July 17, 2010 5:41:41 PM]

Share on other sites
I apologize, it appears my post was premature: I was able to find the solution. Turns out that I needed to retrieve the modelview/projections matrices from OpenGL immediately after performing the camera transformations.

1. 1
Rutin
40
2. 2
3. 3
4. 4
5. 5

• 18
• 20
• 12
• 14
• 9
• Forum Statistics

• Total Topics
633363
• Total Posts
3011512
• Who's Online (See full list)

There are no registered users currently online

×