Pathtracing Ray Triangle Intersection

问题描述 投票:1回答:2

我正在写一个路径追踪器。现在我想实现光线 - 三角形交叉。所以我的三角形由三个点组成(v0,v1,v2)。我查看了关于这个主题的其他帖子(Raytracing - Ray/Triangle Intersection)。可悲的是它没有正常工作所以我想检查问题是否在交叉路口。这是我的两个三角函数:

public float intersect(Ray ray){
    Vector3D e1 = v1.sub(v0);
    Vector3D e2 = v2.sub(v0);
    Vector3D e1e2 = e1.cross(e2).normalize();

    Vector3D p = ray.direction.cross(e2);

    float a = e1.dot(p);
    if(a < 0.0)
        return -1.0f;

    float f = 1.0f / a;
    Vector3D s = ray.origin.sub(v0);
    float u = f*(s.dot(p));
    if(u < 0.0 || u > 1.0)
        return -1.0f; //no hit

    Vector3D q = s.cross(e1);
    float v = f * (ray.direction.dot(q));
    if(v < 0.0 || v > 1.0)
        return -1.0f; //no hit

    float t = f * (e2.dot(q)); //distance
    return t;
}

public Vector3D normal(Vector3D nVec){
    Vector3D e1 = v1.sub(v0);
    Vector3D e2 = v2.sub(v0);
    Vector3D e1e2 = e1.cross(e2).normalize();
    return e1e2;
}

那么这段代码是否正确?

graphics geometry raytracing
2个回答
1
投票

老实说,我觉得你的代码很难阅读,因为你没有使用非常具有描述性的名字。我打算给你我在伪代码中做的事情:

//1.Find intersection point of the ray and the infinite Plane created by triangle,
//or find if the ray is parralel to the plane (no intersection Point)
//2.Find out if the intersection point is within the triangle itself

Triangle: Vector A, Vector B, Vector C
ray: Vector rayOrig, Vector rayDir
Intersection: boolean hasHit = false, Vector hitPoint, float t

Vector normal = (B-A)CrossProduct(C-A) //I think you had basically the same with e1e2
float d = (normal)DotProduct(A)
float nd = (normal)DotProduct(rayDir)
if(nd!=0)
{    //The ray hits the triangles plane
    Intersection.t=(d- (normal).DotProduct(rayOrig))/nd
    Intersection.hitPoint=rayOrig+(rayDir*Intersection.t)
    if (pointInTriangle(Intersection.hitPoint, A, B, C))
    {
         Intersection.hasHit = true
    }
}
return Intersection

请注意,在获得与平面的交点后,将调用三角形中的函数点,该函数应返回布尔值。我得到了我的方法:http://www.blackpawn.com/texts/pointinpoly/使用第二个重心coordiantes,看起来你在这部分做了类似的事情

if(u < 0.0 || u > 1.0)
    return -1.0f; //no hit

Vector3D q = s.cross(e1);
float v = f * (ray.direction.dot(q));
if(v < 0.0 || v > 1.0)
    return -1.0f; //no hit

看起来你看起来并不是在检查光线平面交叉点,你是在做不同的功能吗?如果是这种情况,我不认为你实际上需要光线方向进行三角测试。


1
投票

您实施的是着名的Möller-Trumbore交叉算法。代码是正确的。如果您的代码没有检测到这一点,可能是因为它检查了背面剔除。您可以通过将第一个if-test更改为if (a == 0.0f)来删除该测试。

另外,在第四行Vector3D e1e2 = e1.cross(e2).normalize();,你正在计算三角形平面的法线向量,这是不必要的。

© www.soinside.com 2019 - 2024. All rights reserved.