实现光线拾取 [英] Implementing Ray Picking

查看:60
本文介绍了实现光线拾取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 directx 和 openGL 的渲染器,以及一个 3d 场景.视口和窗口的尺寸相同.

I have a renderer using directx and openGL, and a 3d scene. The viewport and the window are of the same dimensions.

如何以独立于平台的方式选择给定的鼠标坐标 x 和 y?

How do I implement picking given mouse coordinates x and y in a platform independent way?

推荐答案

如果可以,通过鼠标指针计算来自眼睛的光线并将其与您的模型相交,从而在 CPU 上进行拾取.

If you can, do the picking on the CPU by calculating a ray from the eye through the mouse pointer and intersect it with your models.

如果这不是一个选项,我会使用某种类型的 ID 渲染.为您想要选择的每个对象指定一个独特的颜色,使用这些颜色渲染对象,最后在鼠标指针下从帧缓冲区中读出颜色.

If this isn't an option I would go with some type of ID rendering. Assign each object you want to pick a unique color, render the objects with these colors and finally read out the color from the framebuffer under the mouse pointer.

如果问题是如何根据鼠标坐标构造光线,您需要以下内容:投影矩阵 P 和相机变换 C.如果鼠标指针的坐标为(x, y),视口的大小为(width, height),则裁剪空间中沿射线的一个位置为:

If the question is how to construct the ray from the mouse coordinates you need the following: a projection matrix P and the camera transform C. If the coordinates of the mouse pointer is (x, y) and the size of the viewport is (width, height) one position in clip space along the ray is:

mouse_clip = [
  float(x) * 2 / float(width) - 1,
  1 - float(y) * 2 / float(height),
  0,
  1]

(注意我翻转了 y 轴,因为鼠标坐标的原点通常在左上角)

(Notice that I flipped the y-axis since often the origin of the mouse coordinates are in the upper left corner)

以下也成立:

mouse_clip = P * C * mouse_worldspace

给出:

mouse_worldspace = inverse(C) * inverse(P) * mouse_clip

我们现在有:

p = C.position(); //origin of camera in worldspace
n = normalize(mouse_worldspace - p); //unit vector from p through mouse pos in worldspace

这篇关于实现光线拾取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆