我正在使用C ++ / Qt / OpenGL 4.3来实现OpenGL查看器,但我坚持将鼠标坐标转换为世界坐标。
更新:阅读评论和答案后,我发现此代码可以正常工作:
float depth;
double mouseX;
double mouseY;
_app->getCurPos(mouseX, mouseY);
glReadPixels(mouseX, _h - mouseY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, (void *)&depth);
float x = (2.0f * mouseX) / _w - 1.0f;
float y = 1.0f - (2.0f * mouseY) / _h;
float z = depth * 2.0 - 1.0; // convert to NDC
QVector4D pos(x, y, z, 1.0);
QMatrix4x4 invVM(_app->camera()->ViewMatrix().inverted());
QMatrix4x4 invPM(_app->camera()->ProjectionMatrix().inverted());
QVector4D world = invVM * invPM * pos;
world /= world.w();
qDebug() << "world" << world;
(来自原始问题...) 该代码在哪里出错?其输出如下。
代码:
// mouse coordinates to world coordinates
QVector3D GLCamera::transformScreen(float mouseX, float mouseY)
{
// our 3D view has Y as "UP"
float x = (2.0f * mouseX) / _w - 1.0f;
float y = 0.0f;
float z = 1.0f - (2.0f * mouseY) / _h;
// hard code NDC to upper-right of screen
x = 1.0;
y = 0.0;
z = 1.0;
QVector4D ndc = QVector4D(x, y, z, 1);
QVector4D point1 = ndc * mProjectionMatrix.inverted();
qDebug() << point1;
QVector3D point3D = QVector3D(point1) / point1.w();
qDebug() << point3D;
QVector3D point2 = point3D * mViewMatrix.inverted();
qDebug() << point2;
qDebug() << "mViewMatrix: " << mViewMatrix;
qDebug() << "inv : " << mViewMatrix.inverted();
qDebug() << "mProjMatrix: " << mProjectionMatrix;
qDebug() << "inv : " << mProjectionMatrix.inverted();
return point2;
}
输出:
qDebug: QVector4D(1, 0, 1, 1)
qDebug: QVector4D(0.742599, 0, -49.995, 49.005)
qDebug: QVector3D(0.0151535, 0, -1.0202)
# This is the returned value x seems so much smaller than z
qDebug: QVector3D(-0.000938916, -0.0418856, 0.0473429)
qDebug: mViewMatrix: QMatrix4x4(type:Translation,Rotation
1 0 0 0
0 0.748955 -0.662621 -0.626549
0 0.662621 0.748955 -22.9856
0 0 0 1
)
qDebug: inv : QMatrix4x4(type:Translation,Rotation
1 0 0 0
0 0.748955 0.662621 15.7
0 -0.662621 0.748955 16.8
0 0 0 1
)
qDebug: mProjMatrix: QMatrix4x4(type:General
1.34662 0 0 0
0 2.41421 0 0
0 0 -1.0002 -0.020002
0 0 -1 0
)
qDebug: inv : QMatrix4x4(type:General
0.742599 0 0 0
0 0.414214 0 0
0 0 0 -1
0 0 -49.995 50.005
)
答案 0 :(得分:0)
在NDC中,屏幕的右上角是(1, 1, depth)
。您需要一个合理的深度值才能获得所需的点。否则,您只会得到射线。
您显示的矩阵应该用于右乘法:
QVector4D point1 = mProjectionMatrix.inverted() * ndc;
QVector3D point2 = mViewMatrix.inverted() * point3D;
视角鸿沟应该发生在最后,而不是在两者之间。到此为止,继续使用4D向量。否则,将视空间位置(point1
)作为QVector3D
传递将将w分量设置为0,并且您将失去任何平移。您可以将其作为QPoint3D
传递,它将设置w = 1,但是保留4D向量是最安全的选择。
QVector3D point3D = QVector3D(point1) / point1.w();
我也建议合理地命名中间结果(而不仅仅是pointX
)。将它们命名为pointClipSpace
,pointViewSpace
,pointWorldSpace
或类似名称。
再次,确定NDC深度对于获得可解释的结果非常重要。