1. Find whether ray itnersects triangle plane.
2. Find if the intersection point lies inside the plane.
Heres my code:
// r is ray, i is intersection point, n is normal at intersection point, t is the //triangle intersected
bool ray_triangle_intersection(ray **r, triangle t, vector **i, vector **n)
{
vector temp;
// First I calculate the distance using famous formula
// t = -(O-A) dot n / (d dot n)
vector_sub(&((*r)->origin), &t.a, &temp); // Finding (O-A)
double dotnum;
dotnum = vector_dot(&temp, &t.n); // finding (O-A) dot n
double dotdenom;
dotdenom = vector_dot(&((*r)->d), &t.n); // finding d dot n
if(fabs(dotdenom) <= TOLERANCE) // if it is zero then the ray is parallel to
return FALSE; // plane of triangle
double dist = -dotnum/dotdenom; // find distance
if(dist < 0.0) // if distance is -ve then point is behind the origin of ray
return FALSE;
(*r)->t = dist;
**n = t.n;
(*i)->x = (*r)->origin.x + dist * (*r)->d.x; // Calculating intersection
(*i)->y = (*r)->origin.y + dist * (*r)->d.y; // point
(*i)->z = (*r)->origin.z + dist * (*r)->d.z;
vector temp1, temp2, temp3;
double dot00, dot01, dot02;
// condition for intersection point to be inside the triangle is:
// ((b-a) cross (i-a) ) dot n >= 0
// and ((c-b) cross(i-b)) dot n >= 0
// and ((a-c) cross (i-c)) dot n >=0
vector_cross(vector_sub(&t.b, &t.a, &temp1), vector_sub(*i, &t.a, &temp2), &temp3); // (b-a) cross (i - a)
dot00 = vector_dot(&temp3, &t.n); // ((b-a) cross (i-a) ) dot n
vector_cross(vector_sub(&t.c, &t.b, &temp1), vector_sub(*i, &t.b, &temp2), &temp3); // (c-b) cross (i-b)
dot01 = vector_dot(&temp3, &t.n); // ((c-b) cross (i-b) ) dot n
vector_cross(vector_sub(&t.a, &t.c, &temp1), vector_sub(*i, &t.c, &temp2), &temp3); // (a-c) cross (i-c)
dot02 = vector_dot(&temp3, &t.n); // ((a-c) cross (i-c) ) dot n
if(dot00 >= 0.0 && dot01 >= 0.0 && dot02 >= 0.0) // condition
{
//printf("ip: %f %f %f closest distance: %f\n", i->x, i->y, i->z, r->t);
return TRUE;
}
else
return FALSE;
}












