Scratchapixel: Intersection
In Ray-Tracing Rendering Technique, a very common and important method is called
1. Represent a Ray
At first, we need to define the ray, so that we can use it to compute the intersection.
And it’s a really simple definition, a point and a direction. Just as:
1 | // the minimum requirement for defining a ray is a position and a direction |
And along this ray, we can define the point as: 1
2
3
4
5
6
7
8
9
10class Ray
{
public:
Ray(), orig(0), dir(0,0,-1) {}
Ray(const Vec3f &o, const Vec3f &d) : orig(o), dir(d) {}
// etc.
...
Vec3f orig;
Vec3f dir;
};
2. Finding the hit point in a plane
A plane can be represent as
Now we have a ray
We get the hit point
3. Excluding special cases
Before we try to compute the intersection, we need to exclue some special cases, so that the algorithm could be robust enough. If the ray is parallel to the plane, then there will be no intersection actually. And the same as the situation that the plane is behind origin of the ray.
3.1 Parallel
We can use the dot product to judge whether the ray and plane are parallel. If the normal of the plane and the ray are perpendicular. Then their dot product should be zero, and it means the situation of parallel happens.
3.2 Behind
We have computed the value of
4. Triangle
4.1 Geometric Solution
We can use the position of the hit point to judge whether the ray will intersect inside a triangle or not with just a simple process. As the following picture shows, there are two points
We know that the cross product follows the right-hand theorem. It means the direction after cross product will be determined by the order in the two sides of cross product. Such as
1 | Vec3f edge0 = v1 - v0; |
4.2 Möller-Trumbore Solution
Barycentric Coordinates
Barycentric coordinates can be used to express the position of any point located on the triangle plane. It can be inferred as:
And we can know that
Möller-Trumbore Algorithm
Now we use Barycentric coordinates to represent the hit point
We now know the vector
So,
where
Now we can use the above equations to compute
5. Sphere
Using the parametric form of ray and sphere, it’s simple to get:
And this is just a quadratic function, with
- When
, there is two intersections, like situation ; - When
, there is only one intersection, like situation ; - When
, there is no intersection, like situation .
Notice that we should exlude the situation
Besides, when we really implement the above algorithm, we will use the following equations instead to be more stable:
6. Plane and Disk
It’s easy to find intersection for Plane and Disk. Just like we find hit point before. We exlude the situation of parallel, then we can compute the intersection for Plane.
And we have one more step for Disk. We just need to compute the distance between the hit point and the center point of the disk, then we compare this distance and the radius of Disk.