Ray vs axis-aligned bounding box, via Bing's CoPilot

This is a classic problem, so I asked Bing's CoPilot for a Rust solution:

"I need a ray vs 3d axis-aligned box intersection test in Rust, preferably one that returns the hit point."

The code ran after one minor declaration fix. But I changed the test case and it got the wrong answer. The bounding box is at [1, 1, 1] to [2, 2, 2] and the ray cast is in the direction [1,1,1]. The code says the hit is at t=1, but it's actually at t=sqrt(3.0).

Anyone have the correct algorithm? I suspect Bing found someone's bad code and bashed it into Rust.

(Use case: mouse selection, not rendering. So the heavy-duty algorithms are overkill.)

Upon first look (just by trying to make sense of the maths) the code looks reasonable to me, except that it should probably be / ray.direction[d] instead of * ray.direction[d].

For your test case that doesn't even make a difference, but for most other cases it should be quite important.

As for your expected value, you should explain what t is and why you expect sqrt(3). My understanding would be that t is the factor such that the intersection is at origin+t*direction. If you want distance instead you'll have to multiply t by the lengths of distance vector.

Ah well, also the comment mentions Ray is supposed to have a "normalized direction" which your example doesn't have. Nonetheless, I still believe that the multiplication needs to be division.

If distance is normalized then t would turn out being exactly the distance from origin to the intersection point, too.

Excuse my minimal edits and hard-coded normalized version of the direction example (by dividing each entry by the original length of sqrt(3)), as I'm just modifying this on a phone, but like this, it appears to work fine (at least for the example input at hand): Rust Playground

Ah. My bad. Used an un-normalized direction in the test case.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.