3
$\begingroup$

I've searched everywhere for an equation that suits my needs but i couldn't find anything useful. I'm making a voxel ray-tracer so I need an equation that gets me the intersection of a ray with a box, and the box's normal.

I looked at inigo quilez's intersection code but I can't derive the equation from the code shown so i need the equation itself rather than code.


Say we have the ray's origin $O(-5, 1, 0)$ and the box position $B(0, 0, 0)$ with the ray's direction as a unit vector being $(1, 0, 0)$ and the box's side lengths being $(2, 2, 2)$

  1. I need the equation to return the distance between the point where the ray hits the box, and the ray's origin

  2. I need the box's normal where the intersection is

$\endgroup$

2 Answers 2

2
$\begingroup$

PBRT has code for axis-aligned bounding boxes.

https://www.pbr-book.org/3ed-2018/Shapes/Basic_Shape_Interface#Bounds3::IntersectP

They only have an intersection predicate for occlusion rays, but extending this to give you the normals and support non-axis-aligned bounding boxes is simple.

To acquire the normals, you create a normal in the proper direction for the hit slab. It loops through the x, y, and z directions, and since this is axis aligned, you return (1, 0, 0), (0, 1, 0), or (0, 0, 1). There is also a check to see if the hit values are reversed, in which case the normals are reversed, e.g. (-1, 0, 0).

If you want to support non-axis-aligned bounding boxes, it's probably easiest to apply the inverse of the box's transform to the intersection ray and then do the axis-aligned test as above. In the end, you apply the transform to the output normals (remember that transforming normals has different rules than transforming vectors).

$\endgroup$
1
$\begingroup$

Denote you ray as $\vec{P} + \vec{D}*t $ and $\vec{S}_h$ be the half size of the box (ie $ \vec{S}_h = (1,1,1)$). The following equation must be satisfied (with abusive notation): $ || \frac{\vec{P} + \vec{D}*t}{\vec{S}_h} - 1 ||_{L_{\infty}} = 1 $ where vector-division is defined as $\frac{\vec{a}}{\vec{b}} = (a_1/b_1,a_2/b_2,a_3/b_3,...)$ and subtraction $\vec{a} - b = (a_1-b,a_2-b,a_3-b,...)$. Note that the max norm is used. There are branchless solutions to finding both solutions to $t$ in this equation.

To get the normal after computing $t$: evaluate the vector inside the norm, find the basis vector corresponding to the component with largest absolute value and multiply it by the sign of the component.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.