bool IntersectTriangle(const MeshTriangle & tri, std::vector<G3D::Vector3>::const_iterator points, const G3D::Ray & ray, float & distance) { static const float EPS = 1e-5f; // See RTR2 ch. 13.7 for the algorithm. const G3D::Vector3 e1 = points[tri.idx1] - points[tri.idx0]; const G3D::Vector3 e2 = points[tri.idx2] - points[tri.idx0]; const G3D::Vector3 p(ray.direction().cross(e2)); const float a = e1.dot(p); if(abs(a) < EPS) { // Determinant is ill-conditioned; abort early return false; } const float f = 1.0f / a; const G3D::Vector3 s(ray.origin() - points[tri.idx0]); const float u = f * s.dot(p); if((u < 0.0f) || (u > 1.0f)) { // We hit the plane of the m_geometry, but outside the m_geometry return false; } const G3D::Vector3 q(s.cross(e1)); const float v = f * ray.direction().dot(q); if((v < 0.0f) || ((u + v) > 1.0f)) { // We hit the plane of the triangle, but outside the triangle return false; } const float t = f * e2.dot(q); if((t > 0.0f) && (t < distance)) { // This is a new hit, closer than the previous one distance = t; /* baryCoord[0] = 1.0 - u - v; baryCoord[1] = u; baryCoord[2] = v; */ return true; } // This hit is after the previous hit, so ignore it return false; }