PDA

View Full Version : Screen Coordinates to OpenGL Coordinates

Rong Yao
12-09-2002, 04:42 AM
How can I convert a mouse point's screen coordinates to its OpenGL drawing coordinates if the drawing is a 2-D one? Thanks!

jebus
12-09-2002, 05:57 AM
if you use an orthographic projection (using glOrtho) the mouse coordinates map directly to window coordinates.

jebus

Rong Yao
12-09-2002, 09:22 AM
Most of the time, the screen coordinates's unit is pixel. When we draw points, we need to know the positions of the points. However, in this case we do not know the unit. That is to say, if we use glVertex2f(1.0f, 1.0f), we do not know the unit of these 1.0s. How can I solve the problem? That is to say, if my mouse screen coordinates are (100, 200), how much is the 100 in OpenGL? 1.0f? 0.5f? 2.0f?....

nexusone
12-09-2002, 09:52 AM
Of course we know the unit take the following ortho view.

void glOrtho( GLdouble left,
GLdouble right,
GLdouble bottom,
GLdouble top,
GLdouble zNear,
GLdouble zFar )

gluOrtho2D(-10.0, 10.0, -10.0, 10.0, -1, 1)

glViewport(0,0, 500, 500) Screen 500 x 500

Given that:

mouse_x = 0 = -10.0 openGL units
mouse_y = 0 = 10.0 openGL units

And we know the screen, we can make the following code:

x = -10.0 - (500 / (mouse_x + 1) * 20)

y = 10 - (500 / (mouse_y + 1) * 20)

Will give you the current mouse position in the current openGL units.

Originally posted by Rong Yao:
Most of the time, the screen coordinates's unit is pixel. When we draw points, we need to know the positions of the points. However, in this case we do not know the unit. That is to say, if we use glVertex2f(1.0f, 1.0f), we do not know the unit of these 1.0s. How can I solve the problem? That is to say, if my mouse screen coordinates are (100, 200), how much is the 100 in OpenGL? 1.0f? 0.5f? 2.0f?....

Rong Yao
12-09-2002, 10:44 AM
Thanks a lot, Jebus and nexusone!

Rong Yao
12-09-2002, 11:24 AM
nexusone,

Do you mean 500 pixels = 20 OpenGL units in your case? If so, could it be

x = -10.0 + mouse_x/500 * 20
y = 10 - mouse_y/500 * 20

?

Why do you use mouse_x + 1 in your formula?

nexusone
12-09-2002, 11:48 AM
I am a bit brian dead from the flu.

Sorry you are correct on the math, could be one other error on x or y in which should get the + or - 10.

http://www.opengl.org/discussion_boards/ubb/smile.gif

Originally posted by Rong Yao:
nexusone,

Do you mean 500 pixels = 20 OpenGL units in your case? If so, could it be

x = -10.0 + mouse_x/500 * 20
y = 10 - mouse_y/500 * 20

?

Why do you use mouse_x + 1 in your formula?