Ray-triangle交叉算法不相交(C ++)

时间:2015-11-19 22:20:54

标签: c++ algorithm graphics

我一直在尝试在我的光线跟踪代码中实现Moller-Trumbore ray-triangle intersection algorithm。该代码应该在网格和光源中读取,从光源发射光线,并从每个光线相交的网格返回三角形。这是我对算法的实现:

//Moller-Trumbore intersection algorithm
void getFaceIntersect(modelStruct m, ray r, hitFaceStruct& hitFaces)
{
    // Constant thoughout loop
    point origin = r.p0;
    point direction = r.u;
    hitFaces.isHit = false;

    for (int i = 0; i < m.faces; i++)
    {
        // Get face vertices
        point v1 = m.vertList[m.faceList[i].v1];
        point v2 = m.vertList[m.faceList[i].v2];
        point v3 = m.vertList[m.faceList[i].v3];

        // Get two edgess
        point edge1 = v2 - v1;
        point edge2 = v3 - v1;

        // Get p
        point p = direction.cross(direction, edge2);
        // Use p to find determinant
        double det = p.dot(edge1, p);

        // If the determinant is about 0, the ray lies in the plane of the triangle
        if (abs(det) < 0.00000000001)
        {
            continue;
        }

        double inverseDet = 1 / det;

        point v1ToOrigin = (origin - v1);

        double u = v1ToOrigin.dot(v1ToOrigin, p) * inverseDet;

        // If u is not between 0 and 1, no hit
        if (u < 0 || u > 1)
        {
            continue;
        }

        // Used for calculating v
        point q = v1ToOrigin.cross(v1ToOrigin, edge1);
        double v = direction.dot(direction, q) * inverseDet;

        if (v < 0 || (u + v) > 1)
        {
            continue;
        }

        double t = q.dot(edge2, q) * inverseDet;

        // gets closest face
        if (t < abs(hitFaces.s)) {

            hitFaceStruct goodStruct = hitFaceStruct();
            goodStruct.face = i;
            goodStruct.hitPoint = p;
            goodStruct.isHit = true;
            goodStruct.s = t;
            hitFaces = goodStruct;
            break;
        }
    }
}

hitFaceStruct和modelStruct的相关代码如下:

typedef struct _hitFaceStruct
{
    int face; // the index of the sphere in question in the list of faces
    float s;  // the distance from the ray that hit it
    bool isHit;
    point hitPoint;
} hitFaceStruct;

typedef struct _modelStruct {
    char *fileName;
    float scale;
    float rot_x, rot_y, rot_z;
    float x, y, z;
    float r_amb, g_amb, b_amb;
    float r_dif, g_dif, b_dif;
    float r_spec, g_spec, b_spec;
    float k_amb, k_dif, k_spec, k_reflective, k_refractive;
    float spec_exp, index_refraction;
    int verts, faces, norms = 0;    // Number of vertices, faces, normals, and spheres in the system
    point *vertList, *normList;     // Vertex and Normal Lists
    faceStruct *faceList;           // Face List
} modelStruct;

每当我拍摄一条光线时,算法代码中u或v的值总是出现一个较大的负数,而不是预期的小的正数。在将光线传递到交叉点代码之前,光线的方向矢量被归一化,而我是正面的,我正在发射通常会撞击网格的光线。有人可以帮我看看我的错误吗?

谢谢!

0 个答案:

没有答案