longchute

about

Axis-Aligned Bounding Box

07 May 2012

NOTE: I originally posted this on Snipplr.

make-aabb [a-point b-point] [a-point b-point]: Creates a 3D Axis-Aligned Bounding Box (AABB).

aabb-contains? [a-box a-point]: Returns true if a 3D AABB contains a given point.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(ns aabb)

(defn ^{
    :doc "Creates a 3D Axis-Aligned Bounding Box (AABB)."
} make-aabb [a-point b-point] [a-point b-point])

(defn ^{
    :doc "Returns true if a 3D AABB contains a given point.
         
            >   A point U belongs to the axis-aligned bounding box, if U[i] >= A[i] and 
            >   U[u] <= B[i], assuming A[i] < B[i], for i is an element of {x, y, z}.
         
                - Vlastimil Havran, Heuristic Ray Shooting Algorithms (Revision 1.1, 8 May 2001), page 3"
} aabb-contains? [a-box a-point]
    (let [[a b] a-box
          axes  (eval `(map vector ~a ~b ~a-point))]
        (loop [[an-axe & more] axes]
            (let [[a-coord b-coord a-point-coord] an-axe]
                (if (or (< a-point-coord a-coord) (> a-point-coord b-coord))
                    false
                    (if (empty? more)
                        true
                        (recur more)))))))