将光线从屏幕投影到模型以进行拾取

时间:2017-01-27 16:31:57

标签: c++ qt opengl 3d matrix-multiplication

我正在尝试从屏幕上的鼠标点击位置投射光线并将其转换为模型空间以进行三角交叉测试。我确信交叉口代码工作正常,我理解未投​​射射线背后的理论。但是我的代码不起作用。我已经尝试了几个相同的基本想法的实现,我得到的结果似乎到处都是。

以下代码是否存在基本缺失?

 // 1. Convert x, y from screen to normalized device coordinates [-1:1]
auto screenPos = pick->position();    
float x = (2.0f * screenPos.x()) / Viewer::window()->width() - 1.0f;
float y = 1.0f - (2.0f * screenPos.y()) / Viewer::window()->height();

// 2. Create a ray xy coordinates with a z pointing forward
QVector3D ray = QVector3D(x, y, -1.0f);

// 3. Convert from device space to view space using inverted projection matrix
QMatrix4x4 projectionMatrix = Viewer::window()->camera()->projectionMatrix();
ray = ray * projectionMatrix.inverted();

// 4. Convert from view space to world space using inverted view matrix
QMatrix4x4 viewMatrix = Viewer::window()->camera()->viewMatrix();
ray = ray * viewMatrix.inverted();
ray.normalize();

// 5. Convert from world space to object space using object transformation matrix
QMatrix4x4 modelMatrix = this->transform()->matrix();
ray = ray * modelMatrix.inverted();
ray.normalize();

// 6. Get camera position for ray origin and transform it to object coordinates
QVector3D camera_pos = Viewer::window()->camera()->position();
QVector3D origin = camera_pos * modelMatrix.inverted();

// 7. Find intersections
auto intersection = testRay(mesh.get(), origin, ray);

0 个答案:

没有答案