生成一个向量

use*_*323 -4 c++ math

我有一条射线从 (x0, y0, z0) 开始,结束于屏幕上的一个像素。此外,我有一个具有 A x B 像素的单屏。

如何在 (i,j) 像素处生成从起点到终点的光线?

我知道这个公式,但我无法在 C++ 中实现它。感谢帮助

Aln*_*tak 5

您的信息不足。

你得知道:

  1. 视点(即相机正在看什么点)
  2. 视野范围
  3. “向上”和“向右”向量定义相机相对于世界坐标的方向。

这是我自己的光线追踪器中的一些相关代码:

camera::camera(const point3& _eye, const point3& _center) :
    eye(_eye), center(_center)
{
    up.set(0, 1, 0);
    recalc();

    fov(30);
    m_aspect = 4.0 / 3;
}

camera::camera(const point3& _eye, const point3& _center, const vector3& _up) :
    eye(_eye), center(_center), up(_up)
{
    recalc();

    fov(30);
    m_aspect = 4.0 / 3;
}

void camera::recalc()
{
    // renormalise the up vector
    up.normalise();

    // calculate unit view direction vector
    view = vector3(eye, center);
    view.normalise();

    // and the right hand view vector
    right.cross(view, up);
    right.normalise();

    // and re-base the up vector (may not be normalised)
    up.cross(right, view);
}

void camera::fov(double fovy)
{
    m_fovy = math::deg2rad(fovy) / 2.0;
    m_tanf = tan(m_fovy);
}

void camera::aspect(double aspect)
{
    m_aspect = aspect;
}

void camera::aspect(int x, int y)
{
    m_aspect = (double)x / y;
}

ray camera::cast_ray(double x, double y) const
{
    vector3 dir(view);  
    dir.add_scaled(right, m_tanf * m_aspect * x);
    dir.add_scaled(up, m_tanf * y);
    dir.normalise();

    return ray(eye, dir, 0, 1.0);
}
Run Code Online (Sandbox Code Playgroud)