Advertisement Jump to content
Sign in to follow this  

Ray Bounding box intersection

This topic is 1761 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Need a help in understanding the logic behind the Ray-Box intersection.

Ray Box Intersection does the following

nt intersectBox_cpu(Ray_cpu r, float3 boxmin, float3 boxmax, float *tnear, float *tfar)
    // compute intersection of ray with all six bbox planes
    float3 invR = {1.0/r.d.x,1.0/r.d.y,1.0/r.d.z};
    float3 tbot = {invR.x*(boxmin.x - r.o.x), invR.y*(boxmin.y - r.o.y), invR.z*(boxmin.z - r.o.z)};
    float3 ttop = {invR.x*(boxmax.x - r.o.x), invR.y*(boxmax.y - r.o.y), invR.z*(boxmax.z - r.o.z)};

    // re-order intersections to find smallest and largest on each axis
    float3 tmin = fminf(ttop, tbot);
    float3 tmax = fmaxf(ttop, tbot);

    // find the largest tmin and the smallest tmax
    float largest_tmin = fmaxf(fmaxf(tmin.x, tmin.y), fmaxf(tmin.x, tmin.z));
    float smallest_tmax = fminf(fminf(tmax.x, tmax.y), fminf(tmax.x, tmax.z));

    *tnear = largest_tmin;
    *tfar = smallest_tmax;

    return smallest_tmax > largest_tmin;

I understood the first part. It finds the intersection Ray and six planes. 

But the second part, finding  the largest tmin and the smallest tmax, is not very intuitive.


Can anyone help.

Edited by rajesh_nest

Share this post

Link to post
Share on other sites

In one dimension, your ray is going to travel through the near plane and then through the far plane. In order to get into the cube, you need to pass the near plane in all three dimensions without passing any far plane. So the max(tmin) tells you the entry point, and the min(tmax) tells you the exit. If you exit before you enter then you don't intersect.


Note, however, that this code isn't going to do so well when your ray is axis aligned (division by zero in calculating invR).

Edited by tobiasjs

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!