I am having an issue with my algorithm to check if my ray intersect a 3D triangle. It seems to be still drawing in the circle behind it(top left hand corner). I can't seem to find out where in my code is causing this slight error.
bool Mesh::intersectTriangle(Ray const &ray,
Triangle const &tri,
Intersection &hit) const{
// Extract vertex positions from the mesh data.
Vector const &p0 = positions[tri[0].pi];
Vector const &p1 = positions[tri[1].pi];
Vector const &p2 = positions[tri[2].pi];
Vector e1 = p1 - p0;
Vector e2 = p2 - p0;
Vector e1e2 = e1.cross(e2);
Vector p = ray.direction.cross(e2);
e1e2.normalized();
float a = e1.dot(p);
if(a < 0.000001)
return false;
float f = 1 / a;
Vector s = ray.origin - p0;
float u = f*(s.dot(p));
if(u < 0.0 || u > 1.0)
return false;
Vector q = s.cross(e1);
float v = f * (ray.direction.dot(q));
if(v < 0.0 || u + v > 1.0)
return false;
float t = f * (e2.dot(q));
hit.depth = t;
hit.normal = e1e2;
hit.position = hit.position *t;
return true;