Algorithm Search⌘K

Data structurecore

OBB tree

Also called OBBTree, oriented bounding box tree.

A bounding volume hierarchy of tight oriented boxes fitted by principal axes, tested for overlap with the separating axis test on 15 axes.

Implements
Spatial index
Time
O(1) box_testO(n log^2 n) build_balancedO(n^2 log n) build_worstO(n m) query
Space
Θ(n) total
Where
m = the number of triangles of the second object; n = the number of triangles of the first object
Properties
not concurrentnot externalnot persistent
Origin
Stefan Gottschalk, Ming C. Lin, Dinesh Manocha, 1996

An OBB tree is a bounding volume hierarchy whose volumes are oriented bounding boxes. Each node stores a box that can turn freely, with its axes along the principal directions of the geometry below it. For long, thin or tilted parts, such a box fits much tighter than an axis-aligned box or a sphere. Two boxes are tested for overlap by the separating axis test, on 15 axes in 3D and on 4 axes in 2D. A rigid object keeps its tree in its own frame, and the query moves the boxes of one tree into the frame of the other, so the tree is never rebuilt while the object moves. The OBB tree is the broad and middle phase of exact collision detection between two rigid triangle meshes.

In plain words

To find where two complex objects touch, you put the object in a box, split it into two halves with their own boxes, and go on until each box holds one triangle. Two objects can touch only where their boxes touch, so you skip all the pairs of parts whose boxes are apart.

The trick of the OBB tree is that each box turns to fit its part. A thin rod that lies at an angle gets a thin box at the same angle, not a large square box with mostly empty space. Tight boxes give fewer false alarms when two objects are close. A test of two turned boxes costs more than a test of two upright ones, but you need far fewer of them.

The abstract type

An OBB tree is a static spatial index over the nn triangles of one rigid object. The operations are:

  • BUILD(T)(T): make the tree for the triangle set TT.
  • OVERLAP(A,B,g)(A, B, g): the pairs of a triangle of AA and a triangle of BB that meet, when BB is placed by the rigid motion g(x)=Rx+tg(x) = Rx + t in the frame of AA.

A query for the first contact only, or for all pairs closer than a distance, uses the same traversal with a different test at the leaves. The tree does not support insert or delete. A deformable mesh needs a refit or a rebuild, which is costly for oriented boxes.

Representation

A node stores a box with a center cc, a unit axis uu, the second axis u⊥u^\perp, and the half extents h1,h2h_1, h_2. In 3D it stores three axes and three half extents. An inner node has two children. A leaf holds one triangle. The invariant is:

  • (B) Bounds. The box of each node contains every triangle below it.

The build fits the box of a node in two steps. First it chooses the axes as the eigenvectors of the covariance of the convex hull of the vertices below the node. Gottschalk, Lin and Manocha use the hull triangles with a uniform density over their area. The 2D code here uses the hull edges with a uniform density over their length. The hull makes the fit depend on the shape and not on how densely it is sampled. Then it projects all the vertices on the axes and takes the smallest and the largest value on each axis. The axes affect only the tightness of the box. Any axes give a valid box, because the box is the range of the projections.

Operations

  1. BUILD(T) ▷ T: triangles; one per leaf
  2. 1H ← the convex hull of the vertices of T
  3. 2u ← the principal axis of the covariance of the boundary of H
  4. 3box ← the range of the projections of the vertices on u and on u⊥
  5. 4if |T| = 1 then return a leaf with box
  6. 5a ← the longer axis of box; s ← the mean of the projections of the triangle centroids on a
  7. 6T1, T2 ← the triangles with a centroid below and above s; if one is empty, split at the median
  8. 7return a node with box and the children BUILD(T1), BUILD(T2)

The paper cuts along the longest axis of the box. The code cuts at the mean of the centroids, and falls back to the median when all centroids are on one side, so that each child gets at least one triangle.

  1. OVERLAP(A, B, R, t) ▷ B placed by x → R x + t
  2. 1stack ← [(root(A), root(B))]; pop (a, b) while the stack is not empty
  3. 2if the separating axis test finds an axis between box(a) and R box(b) + t then continue
  4. 3if a and b are leaves then if their triangles meet, report the pair; continue
  5. 4if b is a leaf, or a is not a leaf and box(a) is at least as large, push (left(a), b), (right(a), b); else push (a, left(b)), (a, right(b))

Line L9 moves the box of bb: its center goes to Rc+tRc + t and its axes to RuRu, and the half extents stay the same. In 2D, for the boxes PP and QQ and each of the 4 axes LL of the two boxes, the test compares ∣L⋅(cQ−cP)∣|L \cdot (c_Q - c_P)| with ∑khkP∣L⋅ukP∣+∑khkQ∣L⋅ukQ∣\sum_k h^P_k |L \cdot u^P_k| + \sum_k h^Q_k |L \cdot u^Q_k|. In 3D the axes are the 3 face normals of each box and the 9 cross products of an axis of one box with an axis of the other. Gottschalk, Lin and Manocha compute the test in the frame of one box, so that many terms are simple.

Example

Take a 4×14 \times 1 rectangle turned by 30°30°, given by 6 points on its boundary. The axis-aligned box of the points is (23+1/2)×(2+3/2)≈3.964×2.866(2\sqrt{3} + 1/2) \times (2 + \sqrt{3}/2) \approx 3.964 \times 2.866, with the area 11.3611.36. The covariance of the hull boundary has its main eigenvector at 30°30°, and the fitted box is the rectangle itself, with the area 4. So the oriented box covers less than half the area of the upright box.

For a query, take an object of 4 triangles in a row, (2k,0),(2k+1.5,0),(2k+0.5,1)(2k, 0), (2k + 1.5, 0), (2k + 0.5, 1) for k=0,…,3k = 0, \dots, 3. Its tree has a root with the 4 triangles, two inner nodes with 2 triangles each, and 4 leaves. Let BB be a copy turned by 90°90° and moved by t=(7,0.5)t = (7, 0.5), so that the first triangle of BB stands on the last triangle of AA. The query does 9 box tests and 1 triangle test, and it reports the pair (3,0)(3, 0). The brute-force method tests all 16 pairs of triangles and finds the same pair. With t=(20,0)t = (20, 0), the first box test at the roots separates the objects, and the query stops. On random scenes of n=m=256n = m = 256 small triangles at a fixed density, with the two objects placed on top of each other, the query did between 641 and 1619 box tests in 5 trials, against 6553665536 pairs for the brute-force method, and reported between 14 and 45 pairs.

Correctness

The proof is in proofs/correctness.md. The box of a node is the range of the projections of all vertices below it, so (B) holds for any choice of axes. A rigid motion keeps containment, so the moved box of a node of BB still contains its moved triangles. In the plane, two disjoint convex polygons have a separating line parallel to one of their edges, so the 4 box axes give an exact overlap test. If two triangles meet at a point xx, then every pair of their ancestors has two boxes that contain xx. So the traversal never prunes such a pair and reaches the two leaves, where the exact triangle test reports the pair. Each pair of nodes is visited at most once, so the query stops after at most (2n−1)(2m−1)(2n - 1)(2m - 1) box tests.

Proof: The OBB tree query reports exactly the pairs of triangles that meetfull

Let AA be a set of nn triangles and BB a set of mm triangles in the plane, and let g(x)=Rx+tg(x) = Rx + t be a rigid motion, with RR a rotation. The query must report the set SS of the pairs (i,j)(i, j) such that the closed triangle AiA_i meets the closed triangle g(Bj)g(B_j). We work in the real RAM. For a node vv let T(v)T(v) be the triangles below it and β(v)\beta(v) its box.

Lemma 1 (the build). The build makes a tree with nn leaves, one for each triangle, and 2n−12n - 1 nodes. Each box contains every vertex of every triangle below its node.

Proof. The box of a node has a unit axis uu, the axis u⊥u^\perp, and the intervals [min⁡pu⋅p,max⁡pu⋅p][\min_p u \cdot p, \max_p u \cdot p] and [min⁡pu⊥⋅p,max⁡pu⊥⋅p][\min_p u^\perp \cdot p, \max_p u^\perp \cdot p] over the vertices pp below the node, each grown by a margin ≥0\ge 0. A point is in the box exactly when its two coordinates are in the two intervals, so every vertex below the node is in the box. This holds for any choice of uu, so the principal axis is a matter of a tight fit, not of correctness. A node with k≥2k \ge 2 triangles splits them into two nonempty sets: by the mean, or by the median if the mean leaves one side empty. So the sizes go down, the recursion ends at leaves of one triangle, and a binary tree with nn leaves in which every inner node has two children has 2n−12n - 1 nodes. □\square

The boxes are convex, so by Lemma 1 the box of vv contains every triangle of T(v)T(v), which is the convex hull of its vertices.

Lemma 2 (the box test is exact). For two boxes PP and QQ, the test returns false exactly when PP and QQ are disjoint.

Proof. The test projects both boxes on each of the 4 axes uP,uP⊥,uQ,uQ⊥u_P, u_P^\perp, u_Q, u_Q^\perp. The projection of a box with the center cc, the axes u,u⊥u, u^\perp and the half extents h1,h2h_1, h_2 on a unit vector LL is the interval with the center L⋅cL \cdot c and the radius h1∣L⋅u∣+h2∣L⋅u⊥∣h_1 |L \cdot u| + h_2 |L \cdot u^\perp|. The test returns false when the two intervals on some axis are disjoint, and then the boxes are disjoint. Conversely, by the separating axis theorem in the plane, two disjoint convex polygons have a separating line parallel to an edge of one of them. Then their projections on the normal of that edge are disjoint. The edge normals of a box are its two axes, so one of the 4 axes separates them. □\square

The same argument with the 6 edge normals shows that the triangle test is exact.

Theorem. The query terminates after at most (2n−1)(2m−1)(2n - 1)(2m - 1) box tests and returns SS.

Proof. A rigid motion keeps containment, so g(β(w))g(\beta(w)) contains g(T(w))g(T(w)) for each node ww of BB, and the code moves the box of ww by gg. A pushed pair is always (child, same) or (same, child) of the popped pair, so each pair of nodes (a,b)(a, b) is reached at most once, along the unique path of pairs from (root, root). This gives the bound on the tests, and the query terminates.

Soundness. The code adds (i,j)(i, j) only at a pair of leaves after the exact triangle test, so every reported pair is in SS.

Completeness. Let (i,j)∈S(i, j) \in S, with a point xx in Ai∩g(Bj)A_i \cap g(B_j). Call a pair of nodes (a,b)(a, b) good if Ai∈T(a)A_i \in T(a) and Bj∈T(b)B_j \in T(b). The pair (root, root) is good. If a good pair is popped, then x∈β(a)x \in \beta(a) and x∈g(β(b))x \in g(\beta(b)), so the boxes meet, and by Lemma 2 the test does not prune the pair. If both nodes are leaves, they are the leaves of ii and jj, and the code reports (i,j)(i, j). Otherwise the code pushes the two pairs for the two children of one node, and the child that holds the triangle gives a good pair. The depth of a good pair grows at each step, so after finitely many steps the leaves of ii and jj are popped together, and (i,j)(i, j) is reported. ■\blacksquare

Remarks. In 3D the same proof works with the 15 axes of Gottschalk, Lin and Manocha: the 3 face normals of each box and the 9 cross products of an edge direction of one box with an edge direction of the other. The code grows each box by a margin of 10−910^{-9} times the scale of the coordinates, so that rounding in floating point cannot remove a contact point from a box. The theorem holds for any margin ≥0\ge 0.

Complexity

The model is the real RAM. A node with kk triangles costs O(klog⁡k)O(k \log k) for the hull and O(k)O(k) for the covariance, the projections and the split. A 3D fit also needs the eigenvectors of a 3×33 \times 3 symmetric matrix, for example by the Jacobi method, in O(1)O(1).

operation time case
build O(nlog⁡2n)O(n \log^2 n) when the splits are balanced
build O(n2log⁡n)O(n^2 \log n) worst, when each split takes off one triangle
box test O(1)O(1) 4 axes in 2D, 15 in 3D
overlap O(nm)O(n m) worst; far fewer tests on typical scenes, as measured above
space Θ(n)\Theta(n) 2n−12n - 1 nodes

The worst case of the query is real: two objects can be placed so that Θ(nm)\Theta(n m) pairs of triangles meet, and then any method that reports all pairs needs that many steps. The cost on objects in close contact, where many boxes overlap but few triangles meet, depends on the fit, and this is where tight boxes pay off.

Variants

  • The fit. The covariance of the vertices is cheaper but depends on the sampling of the mesh. The covariance of the hull triangles, as in the paper, does not. In 2D the smallest box has one side on an edge of the hull, so trying each hull edge with rotating calipers gives the optimal box in linear time after the hull. In 3D the smallest box is much harder to find.
  • Other volumes. Sphere trees have the cheapest test and a poor fit. k-DOP trees have fixed directions, so their test compares intervals only, but they must be refitted when the object turns. Swept sphere volumes add a radius to a rectangle or a segment, and test the distance between their cores.
  • The descent rule. Line L11 splits the larger box. Other rules split the node with more triangles, or both nodes at once.
  • Distance queries. The same tree with a lower bound on the distance between two boxes answers the distance of two objects, and the closest pair is found by pruning pairs of boxes that are farther than the best distance so far.

When to use it

Use an OBB tree for exact collision detection between rigid triangle meshes, in particular when the objects are often close or in contact along a large area, for example parts in an assembly, a robot near an obstacle or a haptic probe on a surface. Then many pairs of loose boxes overlap, and the tight fit of oriented boxes saves many tests. For deformable meshes, or for scenes where the objects are mostly far apart, an AABB tree is cheaper to build and to refit. For a quick broad phase over many objects, use sweep and prune first.

Pitfalls

  • A box from the wrong covariance. The covariance of the vertices, and not of the hull, gives a bad axis for a mesh with a dense cluster of small triangles on one side.
  • Equal eigenvalues. For a square or a regular polygon, the covariance is a multiple of the identity, and the eigenvectors are arbitrary. The box is still valid, but it can be loose. Some implementations try a few axes and keep the smallest box.
  • Rounding. The box test in floating point can miss a contact on the boundary of a box. Grow the boxes by a small margin, as in the code, or compute the test with a small tolerance.
  • The cost of the 3D test. The 15-axis test costs much more than an AABB test. An early exit on the first separating axis helps, and the order of the axes matters.
  • Deformation. When the mesh deforms, the boxes must be fitted again from the vertices. A refit that keeps the old axes is valid but grows loose.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

obb_tree.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/obb-tree/. The authors are listed in prov/FZV7G9.jsonl.

"""An OBB tree over the triangles of a 2D object, and the overlap query of two such trees.

Each node stores an oriented box. The axes of the box are the principal axes of the convex hull
of the vertices below the node: the eigenvectors of the covariance of the hull boundary, with a
uniform density along the edges. This is the 2D form of the rule of Gottschalk, Lin and Manocha,
who use the area-weighted covariance of the hull triangles in 3D. A node splits along the
longest axis of its box at the mean of the projected triangle centroids, or at the median if the
mean puts all triangles on one side.

The query takes the pose (R, t) of the object B in the frame of A. It moves the boxes of B on the
fly, so the tree of a rigid object never needs a rebuild. Two boxes in 2D are disjoint exactly
when one of the 4 box axes separates them, the 2D form of the 15 axes in 3D.
"""

from __future__ import annotations

import math
from dataclasses import dataclass, field

EPS = 1e-9  # the boxes grow by EPS times the scale, so that rounding cannot make the test miss a contact


def _sub(p, q):
    return (p[0] - q[0], p[1] - q[1])


def _dot(u, v):
    return u[0] * v[0] + u[1] * v[1]


def _cross(o, a, b):
    return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])


def convex_hull(points):
    """Andrew's monotone chain, counterclockwise, without collinear points."""
    pts = sorted(set(points))
    if len(pts) <= 2:
        return pts
    lower: list = []
    for p in pts:
        while len(lower) >= 2 and _cross(lower[-2], lower[-1], p) <= 0:
            lower.pop()
        lower.append(p)
    upper: list = []
    for p in reversed(pts):
        while len(upper) >= 2 and _cross(upper[-2], upper[-1], p) <= 0:
            upper.pop()
        upper.append(p)
    return lower[:-1] + upper[:-1]


def principal_axis(points):
    """The unit eigenvector of the largest eigenvalue of the covariance of the hull boundary."""
    hull = convex_hull(points)
    if len(hull) == 1:
        return (1.0, 0.0)
    if len(hull) == 2:
        d = _sub(hull[1], hull[0])
        L = math.hypot(*d)
        return (d[0] / L, d[1] / L)
    total = mx = my = sxx = sxy = syy = 0.0
    for i in range(len(hull)):
        a, b = hull[i], hull[(i + 1) % len(hull)]
        L = math.dist(a, b)
        total += L
        mx += L * (a[0] + b[0]) / 2
        my += L * (a[1] + b[1]) / 2
        # the integral of x x^T along the segment, divided by its length: (a a^T + b b^T) / 3 + (a b^T + b a^T) / 6
        sxx += L * ((a[0] * a[0] + b[0] * b[0]) / 3 + a[0] * b[0] / 3)
        syy += L * ((a[1] * a[1] + b[1] * b[1]) / 3 + a[1] * b[1] / 3)
        sxy += L * ((a[0] * a[1] + b[0] * b[1]) / 3 + (a[0] * b[1] + b[0] * a[1]) / 6)
    mx, my = mx / total, my / total
    cxx, cyy, cxy = sxx / total - mx * mx, syy / total - my * my, sxy / total - mx * my
    theta = 0.5 * math.atan2(2 * cxy, cxx - cyy)
    return (math.cos(theta), math.sin(theta))


@dataclass
class OBB:
    center: tuple
    u: tuple  # the first unit axis; the second axis is (-u[1], u[0])
    half: tuple  # the half extents along u and along the second axis

    @property
    def v(self):
        return (-self.u[1], self.u[0])

    def corners(self):
        c, u, v, (hu, hv) = self.center, self.u, self.v, self.half
        return [(c[0] + su * hu * u[0] + sv * hv * v[0], c[1] + su * hu * u[1] + sv * hv * v[1]) for su, sv in ((-1, -1), (1, -1), (1, 1), (-1, 1))]

    def moved(self, R, t):
        """The box under the rigid motion x -> R x + t, with R a 2 by 2 rotation matrix."""
        c = apply(R, t, self.center)
        u = (R[0][0] * self.u[0] + R[0][1] * self.u[1], R[1][0] * self.u[0] + R[1][1] * self.u[1])
        return OBB(c, u, self.half)


def fit_obb(points) -> OBB:
    u = principal_axis(points)
    v = (-u[1], u[0])
    pu = [_dot(p, u) for p in points]
    pv = [_dot(p, v) for p in points]
    a, b = (min(pu) + max(pu)) / 2, (min(pv) + max(pv)) / 2
    scale = max(1.0, max(abs(x) for p in points for x in p))
    hu, hv = (max(pu) - min(pu)) / 2 + EPS * scale, (max(pv) - min(pv)) / 2 + EPS * scale
    return OBB((a * u[0] + b * v[0], a * u[1] + b * v[1]), u, (hu, hv))


def obb_overlap(A: OBB, B: OBB) -> bool:
    """Separating axis test on the 4 axes of the two boxes: True if the closed boxes meet."""
    d = _sub(B.center, A.center)
    for L in (A.u, A.v, B.u, B.v):
        ra = A.half[0] * abs(_dot(L, A.u)) + A.half[1] * abs(_dot(L, A.v))
        rb = B.half[0] * abs(_dot(L, B.u)) + B.half[1] * abs(_dot(L, B.v))
        if abs(_dot(L, d)) > ra + rb:
            return False
    return True


def apply(R, t, p):
    return (R[0][0] * p[0] + R[0][1] * p[1] + t[0], R[1][0] * p[0] + R[1][1] * p[1] + t[1])


def rotation(angle):
    c, s = math.cos(angle), math.sin(angle)
    return ((c, -s), (s, c))


def triangles_overlap(T, U) -> bool:
    """Separating axis test on the 6 edge normals: True if the closed triangles meet."""
    for P in (T, U):
        for i in range(3):
            a, b = P[i], P[(i + 1) % 3]
            n = (a[1] - b[1], b[0] - a[0])
            p1 = [_dot(n, x) for x in T]
            p2 = [_dot(n, x) for x in U]
            if max(p1) < min(p2) or max(p2) < min(p1):
                return False
    return True


@dataclass
class Node:
    box: OBB
    tris: list  # the triangle indices below the node
    left: "Node | None" = None
    right: "Node | None" = None
    size: float = field(default=0.0)

    @property
    def leaf(self):
        return self.left is None


def build(tris) -> Node:
    """The OBB tree over the list of triangles (each a tuple of 3 points), one triangle per leaf."""
    return _build(tris, list(range(len(tris))))


def _build(tris, idx) -> Node:
    pts = [p for i in idx for p in tris[i]]
    box = fit_obb(pts)  # @line L1 L2 L3
    node = Node(box, idx, size=box.half[0] * box.half[1])
    if len(idx) == 1:  # @line L4
        return node
    axis = box.u if box.half[0] >= box.half[1] else box.v  # @line L5
    key = {i: _dot(axis, ((tris[i][0][0] + tris[i][1][0] + tris[i][2][0]) / 3, (tris[i][0][1] + tris[i][1][1] + tris[i][2][1]) / 3)) for i in idx}
    mean = sum(key.values()) / len(idx)
    lo = [i for i in idx if key[i] < mean]
    hi = [i for i in idx if key[i] >= mean]
    if not lo or not hi:  # @line L6
        s = sorted(idx, key=lambda i: key[i])
        lo, hi = s[: len(s) // 2], s[len(s) // 2:]
    node.left, node.right = _build(tris, lo), _build(tris, hi)  # @line L7
    return node


def overlap_pairs(A: Node, trisA, B: Node, trisB, R=((1.0, 0.0), (0.0, 1.0)), t=(0.0, 0.0)):
    """The pairs (i, j) such that triangle i of A meets triangle j of B moved by x -> R x + t.

    Returns the set of pairs and the number of box tests.
    """
    moved_tris = {}
    pairs = set()
    tests = 0
    stack = [(A, B)]  # @line L8
    while stack:
        a, b = stack.pop()
        tests += 1
        if not obb_overlap(a.box, b.box.moved(R, t)):  # @line L9
            continue
        if a.leaf and b.leaf:  # @line L10
            i, j = a.tris[0], b.tris[0]
            if j not in moved_tris:
                moved_tris[j] = tuple(apply(R, t, p) for p in trisB[j])
            if triangles_overlap(trisA[i], moved_tris[j]):
                pairs.add((i, j))
        elif b.leaf or (not a.leaf and a.size >= b.size):  # @line L11
            stack += [(a.left, b), (a.right, b)]
        else:
            stack += [(a, b.left), (a, b.right)]
    return pairs, tests
test_obb_tree.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/obb-tree/. The authors are listed in prov/FZV7G9.jsonl.

import math
import random

from obb_tree import (
    OBB,
    apply,
    build,
    fit_obb,
    obb_overlap,
    overlap_pairs,
    principal_axis,
    rotation,
    triangles_overlap,
)


def _orient(a, b, c):
    v = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
    return (v > 0) - (v < 0)


def _inside_convex(p, P):
    """p in the closed convex polygon P, in either orientation."""
    s = {_orient(P[i], P[(i + 1) % len(P)], p) for i in range(len(P))}
    return not (1 in s and -1 in s)


def _cross_segments(a, b, c, d):
    return _orient(a, b, c) * _orient(a, b, d) < 0 and _orient(c, d, a) * _orient(c, d, b) < 0


def convex_overlap_reference(P, Q):
    """Two convex polygons meet if a vertex of one is in the other or two edges cross."""
    if any(_inside_convex(p, Q) for p in P) or any(_inside_convex(q, P) for q in Q):
        return True
    return any(_cross_segments(P[i], P[(i + 1) % len(P)], Q[j], Q[(j + 1) % len(Q)]) for i in range(len(P)) for j in range(len(Q)))


def random_object(rng, n, spread=10.0, size=1.5):
    tris = []
    for _ in range(n):
        c = (rng.uniform(-spread, spread), rng.uniform(-spread / 3, spread / 3))
        tris.append(tuple((c[0] + rng.uniform(-size, size), c[1] + rng.uniform(-size, size)) for _ in range(3)))
    return tris


def brute_pairs(trisA, trisB, R, t):
    moved = [tuple(apply(R, t, p) for p in T) for T in trisB]
    return {(i, j) for i, T in enumerate(trisA) for j, U in enumerate(moved) if triangles_overlap(T, U)}


def all_nodes(node):
    out = [node]
    if not node.leaf:
        out += all_nodes(node.left) + all_nodes(node.right)
    return out


def inside_box(p, box, tol=1e-9):
    d = (p[0] - box.center[0], p[1] - box.center[1])
    return abs(d[0] * box.u[0] + d[1] * box.u[1]) <= box.half[0] + tol and abs(d[0] * box.v[0] + d[1] * box.v[1]) <= box.half[1] + tol


def test_page_example():
    # a 4 by 1 rectangle turned by 30 degrees: the fitted box has the same axes and area
    R = rotation(math.radians(30))
    pts = [apply(R, (0, 0), p) for p in ((0, 0), (4, 0), (4, 1), (0, 1), (2, 0), (1, 1))]
    box = fit_obb(pts)
    assert abs(abs(box.u[0]) - math.cos(math.radians(30))) < 1e-9
    assert abs(4 * box.half[0] * box.half[1] - 4) < 1e-7
    # the axis-aligned box of the same points is much larger
    xs, ys = [p[0] for p in pts], [p[1] for p in pts]
    assert abs((max(xs) - min(xs)) * (max(ys) - min(ys)) - (2 * math.sqrt(3) + 0.5) * (2 + math.sqrt(3) / 2)) < 1e-9


def test_principal_axis_of_a_thin_shape():
    rng = random.Random(1)
    for _ in range(50):
        a = rng.uniform(0, math.pi)
        R = rotation(a)
        pts = [apply(R, (0, 0), (rng.uniform(-5, 5), rng.uniform(-0.2, 0.2))) for _ in range(30)]
        pts += [apply(R, (0, 0), (-5, 0)), apply(R, (0, 0), (5, 0))]
        u = principal_axis(pts)
        assert abs(u[0] * math.cos(a) + u[1] * math.sin(a)) > 0.99


def test_box_overlap_against_a_reference():
    rng = random.Random(2)
    hits = 0
    for _ in range(2000):
        boxes = []
        for _ in range(2):
            a = rng.uniform(0, math.pi)
            boxes.append(OBB((rng.uniform(-3, 3), rng.uniform(-3, 3)), (math.cos(a), math.sin(a)), (rng.uniform(0.1, 2), rng.uniform(0.1, 2))))
        A, B = boxes
        expect = convex_overlap_reference(A.corners(), B.corners())
        assert obb_overlap(A, B) == expect
        hits += expect
    assert 400 < hits < 1600


def test_triangle_overlap_against_a_reference():
    rng = random.Random(3)
    for _ in range(2000):
        T = tuple((rng.uniform(-2, 2), rng.uniform(-2, 2)) for _ in range(3))
        U = tuple((rng.uniform(-2, 2), rng.uniform(-2, 2)) for _ in range(3))
        assert triangles_overlap(T, U) == convex_overlap_reference(T, U)


def test_every_box_holds_its_triangles():
    rng = random.Random(4)
    for _ in range(10):
        tris = random_object(rng, rng.randint(1, 60))
        root = build(tris)
        nodes = all_nodes(root)
        assert len(nodes) == 2 * len(tris) - 1
        assert sorted(n.tris[0] for n in nodes if n.leaf) == list(range(len(tris)))
        for n in nodes:
            assert all(inside_box(p, n.box) for i in n.tris for p in tris[i])
            if not n.leaf:
                assert sorted(n.left.tris + n.right.tris) == sorted(n.tris)


def test_overlap_query_against_brute_force():
    rng = random.Random(5)
    total = 0
    for _ in range(25):
        trisA = random_object(rng, 40)
        trisB = random_object(rng, 40)
        root_a, root_b = build(trisA), build(trisB)
        for _ in range(3):
            R = rotation(rng.uniform(0, 2 * math.pi))
            t = (rng.uniform(-8, 8), rng.uniform(-8, 8))
            got, tests = overlap_pairs(root_a, trisA, root_b, trisB, R, t)
            want = brute_pairs(trisA, trisB, R, t)
            assert got == want
            total += len(want)
    assert total > 100


def test_far_objects_need_one_box_test():
    rng = random.Random(6)
    trisA, trisB = random_object(rng, 30), random_object(rng, 30)
    got, tests = overlap_pairs(build(trisA), trisA, build(trisB), trisB, rotation(1.0), (100.0, 0.0))
    assert got == set() and tests == 1

History

Gottschalk, Lin and Manocha (1996) gave a fast overlap test of two oriented boxes on 15 separating axes and a top-down build with boxes fitted by the covariance of the convex hull. Their RAPID library implements the method for exact interference tests between rigid triangle meshes. Klosowski and others (1998) compared it with hierarchies of k-DOPs, which have a cheaper test and a looser fit.

References

  1. Stefan Gottschalk, Ming C. Lin and Dinesh Manocha, OBBTree, a hierarchical structure for rapid interference detection, SIGGRAPH 1996, 171 to 180, the fit of a box by the covariance of the hull triangles, the top-down build, and the separating axis test on 15 axes
  2. James T. Klosowski, Martin Held, Joseph S. B. Mitchell, Henry Sowizral and Karel Zikan, Efficient collision detection using bounding volume hierarchies of k-DOPs, IEEE Transactions on Visualization and Computer Graphics 4(1), 1998, 21 to 36, the comparison of hierarchies of k-DOPs with the OBB tree
  3. Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005, the chapters on bounding volumes (oriented boxes) and on bounding volume hierarchies

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.box_test
  • a full proof of time.build_balanced
  • a full proof of time.build_worst
  • a full proof of time.query
  • a full proof of space.total
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/FZV7G9/text.yaml