Reputation: 1477
I'm trying to understand how does a gl_Position
becomes a (x, y) position in the screen and how can I transform it back (to get the position of a mouse click, for example).
For example, let's say I have the following 3D vector:
V = [ -70.0, 0.27, -30.0, 1.0 ]
My MVP (model-view-projection), calculated from a pespective view, is
M = [[-1.34, 0.0 , 0.0 , 0.0 ],
[ 0.0, 1.26, 1.28, 0.40 ],
[ 0.0, -0.72, 0.71, 141.54 ],
[ 0.0, -0.71, 0.70, 142.13 ]]
If I multiply both, I obtain:
M * V = [ 94.11, -37.53, 120.079, 120.86 ]
After I set this value in gl_Position
, the vector is drawn in the following position in the window (my window is 800x600):
P = [ 702, 374 ]
What I can't understand is: how does M * V
becomes P
? I understand that this has something to do with the w
in V
, but I can't find a calculation where I get the same result as P
.
A secondary question would be, how to I transform P
in V
, to catch the 3D position of a mouse click, for example.
Upvotes: 3
Views: 666
Reputation: 725
From M*V to P you need to divide M*V by the last (w) component, which is called perspective divide, and then apply the viewport transformation to get to actual pixels. Have a look at these excellent explanations.
To get back from 2d to 3d is mathematically not possible without further depth information, which may be obtained using gluUnproject. Look here for information of how to use that. Beware, however, depending on your usecase, using this approach frequently per second may be very slow. Nevertheless this might give you an idea about how that all works.
Upvotes: 3