Advertisement

What is your favourite ray-triangle intersection C++ code?

Started by June 19, 2020 07:39 PM
4 comments, last by taby 4 years, 7 months ago

Do you have a favourite ray-triangle intersection C++ code?

For instance, my favourite is listed below. The one problem is that it doesn't report the location of the intersection. Any ideas on going about calculating the location?

// https://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/moller-trumbore-ray-triangle-intersection

bool rayTriangleIntersect(const vertex_3 orig, const vertex_3 dir, const vertex_3 v0, const vertex_3 v1, const vertex_3 v2)
{
	vertex_3 v0v1 = v1 - v0;
	vertex_3 v0v2 = v2 - v0;

	vertex_3 pvec = dir.cross(v0v2);

	float det = v0v1.dot(pvec);

	if (det < 0.000001)
		return false;

	float invDet = 1.0 / det;

	vertex_3 tvec = orig - v0;

	float u = tvec.dot(pvec) * invDet;

	if (u < 0 || u > 1)
		return false;

	vertex_3 qvec = tvec.cross(v0v1);

	float v = dir.dot(qvec) * invDet;

	if (v < 0 || u + v > 1)
		return false;

	float t = v0v2.dot(qvec) * invDet;

	return true;
}

It looks like you're implementing the following algorithm but missing a part, there where your function ends with an unused float.
https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm

Advertisement

Thank you so much for the link!

Yeah, i guess t is the length of the ray (distance from origin to hit), and u,v, are barycentric triangle coordinates useful to interpolate on the triangle (e.g. smooth normal or UV coords).

Indeed, sir!

This topic is closed to new replies.

Advertisement