c++ - 我的射线三角形交叉点代码正确吗?

标签 c++ math opengl intersection

我在这里问是否有人可以检查我的Ray-Triangle交集代码是否正确,或者我有一些错误,因为它似乎无法正常工作。

Vector3f:

struct Vector3f
{
    Vector3f(): x(0), y(0), z(0) { }
    Vector3f(GLfloat a, GLfloat b, GLfloat c): x(a), y(b), z(c) { }

    GLfloat x, y, z;
};

交叉产品和内部产品:
Vector3f CMath::CrossProduct(Vector3f a, Vector3f b)
{
    Vector3f result;

    result.x = (a.y * b.z) - (a.z * b.y);
    result.y = (a.z * b.x) - (a.x * b.z);
    result.z = (a.x * b.y) - (a.y * b.x);

    return result;
}
GLfloat CMath::InnerProduct(Vector3f a, Vector3f b)
{
    return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);
}

射线三角相交检查:
bool CMath::RayIntersectsTriangle(Vector3f p, Vector3f d, Vector3f v0, Vector3f v1, Vector3f v2, Vector3f &hitLocation)
{
    Vector3f e1, e2, h, s, q;
    GLfloat a, f, u, v, t;

    e1.x = v1.x - v0.x;
    e1.y = v1.y - v0.y;
    e1.z = v1.z - v0.z;

    e2.x = v2.x - v0.x;
    e2.y = v2.y - v0.y;
    e2.z = v2.z - v0.z;

    h = CrossProduct(d,e2);
    a = InnerProduct(e1,h);
    if(a > -0.00001 && a < 0.00001)
        return false;

    f = 1 / a;
    s.x = p.x - v0.x;
    s.y = p.y - v0.y;
    s.z = p.z - v0.z;
    u = f * InnerProduct(s,h);
    if(u < 0.0 || u > 1.0)
        return false;

    q = CrossProduct(s,e1);
    v = f * InnerProduct(d,q);
    if(v < 0.0 || u + v > 1.0)
        return false;

    t = f * InnerProduct(e2,d);
    if(t > 0.00001)
    {
        hitLocation.x = p.x + t * d.x;
        hitLocation.y = p.y + t * d.y;
        hitLocation.z = p.z + t * d.z;

        return true;
    }
    else
        return false;
}

只需检查这些功能是否有问题,以了解我的问题是否在其他地方。
预先感谢您的帮助。

最佳答案

首先,我建议将InnerProduct重命名为DotProduct(请参阅Dot product)。

您有一个由3个点v0v1v2定义的平面,以及一个由点p和方向d定义的射线。
在伪代码中,平面图与射线的交点为:

n = cross(v1-v0, v2-v0)        // normal vector of the plane
t = dot(v0 - p, n) / dot(d, n) // t scale d to the distance along d between p and the plane 
hitLocation = p + d * t

另请参阅Intersect a ray with a triangle in GLSL C++

当您将其应用于代码时,这意味着

Vector3f n = CrossProduct(e1, e2);

注意,由于sp - v0(而不是v0 - p),因此必须反转射线方向的比例:

t = - InnerProduct(s, n) / InnerProduct(d, n)

关于c++ - 我的射线三角形交叉点代码正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59912638/

相关文章:

Java根据数组列表中的项目计算百分比

linux - 如何使用linux内核和硬件加速绘制三角形?

c++ - 如何在 OpenGL 中捕捉准确的帧率

c++ - 使用 boost 缓冲区进行操作

c++ - 为什么模板只能在头文件中实现?

javascript - 如何在javascript中将数字格式化为字符串

javascript - 在列之间平均分配数字,例如。 12个糖果,10个人。 2人每人获得2颗糖果,其余人获得1颗

C++ 无法打开文件进行输出

c++ - 高级CFontDialog

将三角形带的顶点转换为多边形的算法