To find if the cube is entirely within the sphere, you can get away with testing only one vertex - the one furthest from the center of the sphere. You can determine which vertex to test by comparing the center points of the cube and sphere.
For example, given a cube centered at (cx,cy,cz)
and with an edge half-length of l
, and a sphere at (sx,sy,sz)
with radius r
, the point to test will be
tx = cx + ( cx > sx ? l : -l );
ty = cy + ( cy > sy ? l : -l );
tz = cz + ( cz > sz ? l : -l );
However, testing the corners of the cube against the sphere will not catch all cases of intersection - consider a cube from (-5,-5,-5) to (5,5,5) and a sphere at (0,0,6) with radius 2. The two volumes do intersect but no vertex is inside the sphere.
I'd go for a multi-pass approach:
- Check the axis-aligned bounding box of the sphere against the cube -
really simple check with quick rejection for
obviously-not-intersecting cases.
- Check if the sphere center lies within the cube
- This possibility may be precluded in your system, but you should
also do a bounding box check for the case where the sphere is
entirely within the cube.
- At this point, there's little choice but to go ahead and check for intersections between the sphere and the cube faces.
For the purposes of walking an octree though, I would be tempted just treat the sphere as an axis-aligned bounding box and live with the small false-positive rate. I wouldn't be at all surprised to learn that this would be faster than getting the absolutely correct intersection results.