OpenGL Math - 将屏幕空间投影到世界空间坐标 [英] OpenGL Math - Projecting Screen space to World space coords
问题描述
在一天结束时进行一些数学计算..
Time for a little bit of math for the end of the day..
我需要投影 4 个窗口大小的点:
<0,0> <1024,768>
<0,0> <1024,768>
进入世界空间坐标,因此它将形成一个四边形形状,稍后将用于地形剔除 - 没有 GluUnproject
Into a world space coordinates so it will form a quadrilateral shape that will later be used for terrain culling - without GluUnproject
仅用于测试,我使用鼠标坐标 - 并尝试将它们投影到世界坐标
For test only, I use mouse coordinates - and try to project them onto the world coords
推荐答案
RESOLVED
以下是具体的操作方法,一步一步.
Here's how to do it exactly, step by step.
- 获取客户区域内的鼠标坐标
- 如果不需要模型矩阵,请获取您的投影矩阵和视图矩阵.
- 乘法投影 * 查看
- 将乘法的结果求逆
构造一个由
- Obtain your mouse coordinates within the client area
- Get your Projection matrix and View matrix if no Model matrix required.
- Multiply Projection * View
- Inverse the results of multiplication
Construct a vector4 consisting of
x = mouseposition.x
在窗口 x 范围内
x = mouseposition.x
within a range of window x
- 转换为 -1 和 1 之间的值
y = mouseposition.y
窗口 y 范围内
y = mouseposition.y
within a range of window y
- 转换为 -1 和 1 之间的值
- 记得在需要时反转 mouseposition.y
z = 深度值
(这可以通过glReadPixel获得)
z = the depth value
( this can be obtained with glReadPixel)
- 你可以手动从 -1 到 1 ( zNear, zFar )
w = 1.0
将向量乘以之前创建的逆矩阵
Multiply the vector by inversed matrix created before
将结果向量除以矩阵乘法(透视除法)后的 w 分量
Divide result vector by it's w component after matrix multiplication ( perspective division )
POINT mousePos;
GetCursorPos(&mousePos);
ScreenToClient( this->GetWindowHWND(), &mousePos );
CMatrix4x4 matProjection = m_pCamera->getViewMatrix() * m_pCamera->getProjectionMatrix() ;
CMatrix4x4 matInverse = matProjection.inverse();
float in[4];
float winZ = 1.0;
in[0]=(2.0f*((float)(mousePos.x-0)/(this->GetResolution().x-0)))-1.0f,
in[1]=1.0f-(2.0f*((float)(mousePos.y-0)/(this->GetResolution().y-0)));
in[2]=2.0* winZ -1.0;
in[3]=1.0;
CVector4 vIn = CVector4(in[0],in[1],in[2],in[3]);
pos = vIn * matInverse;
pos.w = 1.0 / pos.w;
pos.x *= pos.w;
pos.y *= pos.w;
pos.z *= pos.w;
sprintf(strTitle,"%f %f %f / %f,%f,%f ",m_pCamera->m_vPosition.x,m_pCamera->m_vPosition.y,m_pCamera->m_vPosition.z,pos.x,pos.y,pos.z);
SetWindowText(this->GetWindowHWND(),strTitle);
这篇关于OpenGL Math - 将屏幕空间投影到世界空间坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!