Algorithm Search⌘K

Data structureadvanced

k-DOP tree

Also called discrete oriented polytope hierarchy.

A bounding volume hierarchy whose volumes are intersections of k fixed slabs, so that an overlap test compares k/2 pairs of intervals.

Implements
Spatial index
Time
O(n log^2 n + k n log n) buildO(k) dop_testO(k^2) moved_dopO(k n m + k^2 m) query
Space
Θ(k n) total
Where
k = the number of bounding directions with their opposites; m = the number of triangles of the second object; n = the number of triangles of the first object
Properties
not concurrentnot externalnot persistent
Origin
James T. Klosowski, Martin Held, Joseph S. B. Mitchell, Henry Sowizral, Karel Zikan, 1998

A k-DOP tree is a bounding volume hierarchy whose volumes are discrete oriented polytopes. A k-DOP is the intersection of k/2k/2 slabs whose normals come from a fixed set of directions, the same for every node. It is stored as k/2k/2 intervals, one for each direction. An axis-aligned box is the 4-DOP in 2D and the 6-DOP in 3D. More directions give a tighter fit, and the overlap test of two k-DOPs still compares k/2k/2 pairs of intervals. When an object turns, its k-DOPs are no longer aligned with the fixed directions, so the query computes a new k-DOP that contains each moved volume. The k-DOP tree is a middle phase of collision detection between triangle meshes.

In plain words

An upright box around a part is easy to test, but it often holds a lot of empty space. A k-DOP cuts off the corners of the box with more flat sides, at a few fixed angles that every part uses. In the plane, the 8-DOP uses the two axes and the two diagonals.

Because every part uses the same angles, two parts are compared by checking, for each angle, whether their two ranges overlap. If one range pair is apart, the parts are apart. When an object turns, its shapes no longer match the fixed angles, so each one gets a new, slightly larger shape that holds it.

The abstract type

A k-DOP tree is a static spatial index over the nn triangles of one 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.

As in the paper of Klosowski and others, AA is a static scene and BB is a flying object. The tree of AA never changes. The tree of BB keeps its shape, and the query computes the moved volumes of its nodes as they are needed. A deformable mesh needs a refit, which for a k-DOP is a pass over the vertices with k/2k/2 dot products each.

Representation

Fix k/2k/2 directions d1,…,dk/2d_1, \dots, d_{k/2}. The code uses the 8-DOP in the plane, with the directions (1,0)(1, 0), (0,1)(0, 1), (1,1)(1, 1) and (1,−1)(1, -1). A node stores the intervals [ℓj,hj][\ell_j, h_j] with ℓj=min⁡pdj⋅p\ell_j = \min_p d_j \cdot p and hj=max⁡pdj⋅ph_j = \max_p d_j \cdot p over the vertices pp below it, so its volume is {x:ℓj≤dj⋅x≤hj for all j}\{x : \ell_j \le d_j \cdot x \le h_j \text{ for all } j\}. An inner node has two children, and a leaf holds one triangle. The invariant is:

  • (B) Bounds. The k-DOP of each node contains every triangle below it.

In 3D, common choices are k=6k = 6 (the box), k=14k = 14 (the box with its 8 corners cut), k=18k = 18 (the box with its 12 edges cut) and k=26k = 26 (both). Klosowski and others studied these sizes.

Operations

  1. BUILD(T) ▷ T: triangles; one per leaf
  2. 1D ← for each direction d_j, the range of d_j · p over the vertices p of T
  3. 2if |T| = 1 then return a leaf with D
  4. 3d ← the direction with the widest spread of the triangle centroids
  5. 4sort T by d · centroid; return a node with D and the children BUILD(first half), BUILD(second half)
  1. OVERLAP(A, B, R, t) ▷ B placed by x → R x + t
  2. 1at the root of B: D ← the k-DOP of the moved vertices of B
  3. 2at the other nodes b of B: D ← the k-DOP of the moved corners of the stored k-DOP of b
  4. 3stack ← [(root(A), root(B))]; pop (a, b) while the stack is not empty
  5. 4if some interval of a is apart from the same interval of the moved k-DOP of b then continue
  6. 5if a and b are leaves then if their triangles meet, report the pair; continue
  7. 6if b is a leaf, or a is not a leaf and holds at least as many triangles, push (left(a), b), (right(a), b); else push (a, left(b)), (a, right(b))

Line L5 is exact. The paper finds the extreme vertices by hill climbing on the convex hull of the object, and the code scans all vertices. Line L6 is cheaper and looser: it moves the corners of the stored k-DOP, which is a convex polygon that holds the triangles, and takes the k-DOP of the moved corners. The code finds the corners by clipping the box with the two diagonal slabs. Both volumes contain the moved triangles, so the query stays exact.

Example

The triangle (0,0),(4,0),(0,4)(0, 0), (4, 0), (0, 4) has the 8-DOP with x∈[0,4]x \in [0, 4], y∈[0,4]y \in [0, 4], x+y∈[0,4]x + y \in [0, 4] and x−y∈[−4,4]x - y \in [-4, 4], which is the triangle itself. The square [3,5]×[3,5][3, 5] \times [3, 5] meets the box [0,4]×[0,4][0, 4] \times [0, 4] of the triangle, so the box test reports an overlap. The 8-DOP test finds x+y≥6x + y \ge 6 on the square and x+y≤4x + y \le 4 on the triangle, so it separates them.

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. The root has x∈[0,7.5]x \in [0, 7.5], y∈[0,1]y \in [0, 1], x+y∈[0,7.5]x + y \in [0, 7.5] and x−y∈[−0.5,7.5]x - y \in [-0.5, 7.5]. Its corners are (0,0),(7.5,0),(6.5,1),(0.5,1),(0,0.5)(0, 0), (7.5, 0), (6.5, 1), (0.5, 1), (0, 0.5). If the object turns by 30°30°, the k-DOP of the moved corners has x≥−0.25x \ge -0.25, from the moved corner (0,0.5)(0, 0.5), but the exact k-DOP of the moved vertices has x≥−0.067x \ge -0.067, from the moved vertex (0.5,1)(0.5, 1). This is the price of line L6. 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 tests of two 8-DOPs and 1 triangle test, and it reports the pair (3,0)(3, 0), like the brute-force method over all 16 pairs. With t=(20,0)t = (20, 0), the test at the roots separates the objects. On random scenes of n=m=256n = m = 256 small triangles, with the two objects on top of each other, the query did between 757 and 1969 tests of two 8-DOPs in 5 trials, against 65536 pairs for the brute-force method. An OBB tree on the same scenes did between 641 and 1619 box tests, each one more costly.

Correctness

The proof is in proofs/correctness.md. Each interval is the range of the projections of the vertices below the node, so the convex k-DOP contains these vertices and their triangles, and (B) holds. A stored k-DOP is the convex hull of its corners, and a rigid motion maps it to the hull of the moved corners, so the k-DOP of the moved corners contains the moved triangles. If two triangles meet at a point xx, every pair of their ancestors has two volumes that contain xx, so all intervals overlap and the traversal reaches the two leaves, where the exact triangle test reports the pair. In the plane the edges of an 8-DOP have normals among the 4 directions, so by the separating axis theorem the interval test is exact. In 3D the test is only conservative, which costs extra tests but not correctness. Each pair of nodes is visited at most once, so the query stops after at most (2n−1)(2m−1)(2n - 1)(2m - 1) tests.

Proof: The k-DOP 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. Let d1,…,d4d_1, \dots, d_4 be the fixed directions (1,0),(0,1),(1,1),(1,−1)(1, 0), (0, 1), (1, 1), (1, -1). An 8-DOP is a set D={x:ℓk≤dk⋅x≤hk for k=1,…,4}D = \{x : \ell_k \le d_k \cdot x \le h_k \text{ for } k = 1, \dots, 4\}, stored as its 4 intervals [ℓk,hk][\ell_k, h_k]. For a node vv let T(v)T(v) be the triangles below it and D(v)D(v) its stored 8-DOP.

Lemma 1 (the build). The build makes a tree with nn leaves, one for each triangle, and 2n−12n - 1 nodes. Each D(v)D(v) contains every triangle of T(v)T(v).

Proof. The interval kk of D(v)D(v) is the range of dk⋅pd_k \cdot p over the vertices pp below vv, grown by a margin ≥0\ge 0. So every such vertex satisfies the 4 pairs of inequalities and is in D(v)D(v). An 8-DOP is an intersection of half-planes, so it is convex, and it contains each triangle of T(v)T(v), which is the convex hull of three of these vertices. A node with k≥2k \ge 2 triangles is split at the median of a sorted list into two nonempty halves, so the recursion ends at leaves of one triangle. A binary tree with nn leaves in which every inner node has two children has 2n−12n - 1 nodes. □\square

Call an 8-DOP tight if each of its 4 intervals is equal to the projection of the set on dkd_k, that is, if each bound is attained by a point of the set.

Lemma 2 (the volumes are tight). Every 8-DOP that the code computes from a finite set XX of points is tight.

Proof. Without a margin, the interval kk is the range of dk⋅pd_k \cdot p over XX. The set contains XX and lies in the slab, so its projection is exactly this range. With a margin e>0e > 0, let O={y:∣dk⋅y∣≤e for all k}O = \{y : |d_k \cdot y| \le e \text{ for all } k\}. The points (±e,0)(\pm e, 0), (0,±e)(0, \pm e) and (±e/2,±e/2)(\pm e/2, \pm e/2) are in OO, so the projection of OO on each dkd_k is [−e,e][-e, e]. For p∈Xp \in X and y∈Oy \in O the point p+yp + y satisfies the grown bounds, so X+OX + O is in the grown 8-DOP. The projection of X+OX + O on dkd_k is the range over XX grown by ee on each side, which is the grown interval. So each grown bound is attained by a point of the set. □\square

Lemma 3 (the interval test is exact in the plane). For two tight 8-DOPs PP and QQ with the same 4 directions, the test returns false exactly when PP and QQ are disjoint.

Proof. The set PP lies in its 4 slabs. So if the intervals kk of PP and QQ are disjoint for some kk, the sets are disjoint. Conversely, let PP and QQ be disjoint. They are bounded convex polygons. By the separating axis theorem in the plane, there is a separating line parallel to an edge of PP or of QQ. Each edge of an 8-DOP lies on one of its 8 bounding lines dk⋅x=ℓkd_k \cdot x = \ell_k or dk⋅x=hkd_k \cdot x = h_k, so the normal of the separating line is some dkd_k, and the projections of PP and QQ on dkd_k are disjoint. The two DOPs are tight, so these projections are their intervals kk, and the test returns false. □\square

Lemma 4 (the moved volume). Let CC be the corners of D(w)D(w) for a node ww of BB, and let M(w)M(w) be the 8-DOP of the points g(c)g(c), c∈Cc \in C. Then M(w)M(w) contains g(T(w))g(T(w)). At the root rr of BB, the 8-DOP of the moved vertices of BB also contains g(T(r))g(T(r)).

Proof. D(w)D(w) is a bounded convex polygon, so it is the convex hull of its corners CC. The map gg is affine, so g(D(w))g(D(w)) is the convex hull of g(C)g(C). M(w)M(w) is convex and contains g(C)g(C), so it contains g(D(w))g(D(w)), which contains g(T(w))g(T(w)) by Lemma 1. At the root, the 8-DOP of the moved vertices contains the moved vertices, and by convexity the moved triangles. □\square

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

Proof. A pushed pair is always (child, same) or (same, child) of the popped pair, so each pair of nodes is reached at most once, along the unique path of pairs from (root, root). This gives the bound, and the query terminates.

Soundness. The code adds (i,j)(i, j) only at a pair of leaves, after the exact separating axis test of the two triangles on their 6 edge normals, which is exact by the same argument as Lemma 3. 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∈D(a)x \in D(a) by Lemma 1 and xx is in the moved volume of bb by Lemma 4. Both volumes are 8-DOPs with the fixed directions, they are tight by Lemma 2, they share the point xx, and by Lemma 3 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 the leaves of ii and jj are popped together after finitely many steps, and (i,j)(i, j) is reported. ■\blacksquare

Remarks. Completeness needs only that the test never prunes two volumes that meet, so it holds in 3D too, where the interval test on k/2k/2 directions can report an overlap for two disjoint k-DOPs. Then the test is conservative and the query does extra work, but the exact test at the leaves keeps the result exact. The margin of 10−910^{-9} times the scale in the code only grows the volumes, so the theorem holds for it, and it keeps a contact on the boundary of a volume from being lost to rounding in floating point.

Complexity

The model is the real RAM. A k-DOP of ss vertices costs O(ks)O(k s). Each level of the build fits all its nodes in O(kn)O(k n) and sorts in O(nlog⁡n)O(n \log n), and the median split gives O(log⁡n)O(\log n) levels. A k-DOP has O(k)O(k) corners, so a moved k-DOP costs O(k2)O(k^2), once for each node of BB.

operation time case
build O(nlog⁡2n+knlog⁡n)O(n \log^2 n + k n \log n) median splits
test of two k-DOPs O(k)O(k) k/2k/2 interval pairs
moved k-DOP O(k2)O(k^2) from the O(k)O(k) corners
overlap O(knm+k2m)O(k n m + k^2 m) worst; far fewer tests on typical scenes, as measured above
space Θ(kn)\Theta(k n) 2n−12n - 1 nodes of kk numbers

The worst case of the query is real, since two objects can have Θ(nm)\Theta(n m) pairs of triangles that meet.

Variants

  • The number of directions. More directions give a tighter fit and fewer tests, but each test and each update costs more. The best kk depends on the scene.
  • The update of a turning object. Line L6 can be replaced by an exact refit of the moved vertices of each node, which is tighter and costs a pass over the vertices, or by hill climbing on the hull of each node.
  • Other volumes. Sphere trees need no update when the object turns, but fit poorly. OBB trees fit long and tilted parts best and turn with the object, but their test is the most costly.
  • A broad phase. The 4-DOP or 6-DOP of each object is the axis-aligned box that sweep and prune sorts. More directions give more axes to sort.

When to use it

Use a k-DOP tree for collision detection between a moving object and a large static scene, for example a tool path through a machine or a virtual object in a walk-through. The static tree is built once, the interval test is cheap and simple, and the fit is better than that of a box tree for surfaces at an angle. For two objects that both turn and are in close contact, an OBB tree can need fewer tests. For deformable meshes, an AABB tree with a refit is simpler.

Pitfalls

  • Comparing different frames. The interval test works only for two k-DOPs with the same directions in the same frame. Testing the stored k-DOP of a turned object without the update gives wrong results.
  • A false claim of exactness. In 3D, two disjoint k-DOPs can have all their intervals overlap, so a test that says overlap must not be taken as a contact.
  • Loose updates. Each update of line L6 adds empty space, and the error does not grow with depth only because each node is updated from its own stored k-DOP. Updating a child from the moved volume of its parent would make the volumes grow larger at each level.
  • Corners of a degenerate k-DOP. A flat or point-like k-DOP has repeated corners. The clip must handle them, or the update must start from the vertices.
  • Rounding. Grow the intervals by a small margin, as in the code, so that a contact on the boundary of a volume is not lost.

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.

k_dop_tree.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-dop-tree/. The authors are listed in prov/ZJ32AH.jsonl.

"""A tree of 8-DOPs over the triangles of a 2D object, and the overlap query of two such trees.

An 8-DOP is the intersection of 4 slabs with the fixed normals (1, 0), (0, 1), (1, 1) and (1, -1).
It is stored as 4 intervals, one per normal. Two 8-DOPs overlap only if all 4 pairs of intervals
overlap. In 2D the edge normals of an 8-DOP are among the 4 normals, so this test is exact. In 3D
the interval test of k/2 pairs is only conservative.

When the object B turns, its stored 8-DOPs are no longer aligned with the fixed normals. As in the
paper of Klosowski and others, the query computes the exact 8-DOP of the moved geometry at the
root of B, and at the other nodes the 8-DOP of the moved corners of the stored 8-DOP, which is
cheaper and looser.
"""

from __future__ import annotations

import math
from dataclasses import dataclass

DIRS = ((1.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, -1.0))
EPS = 1e-9  # each interval grows by EPS times the scale, so that rounding cannot remove a contact


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


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 dop_of_points(points, margin=True):
    """The 8-DOP of the points: the interval of the projections on each of the 4 normals."""
    scale = max(1.0, max(abs(x) for p in points for x in p)) if margin else 0.0
    out = []
    for d in DIRS:
        pr = [_dot(d, p) for p in points]
        out.append((min(pr) - EPS * scale, max(pr) + EPS * scale))
    return tuple(out)


def dop_overlap(P, Q) -> bool:
    """True if all 4 pairs of intervals overlap."""
    return all(p[0] <= q[1] and q[0] <= p[1] for p, q in zip(P, Q))


def _clip(poly, d, c, keep_below):
    """Clip a convex polygon to the half-plane d . x <= c (or >= c)."""
    out = []
    n = len(poly)
    for i in range(n):
        a, b = poly[i], poly[(i + 1) % n]
        fa, fb = _dot(d, a) - c, _dot(d, b) - c
        if not keep_below:
            fa, fb = -fa, -fb
        if fa <= 0:
            out.append(a)
        if (fa < 0 < fb) or (fb < 0 < fa):
            s = fa / (fa - fb)
            out.append((a[0] + s * (b[0] - a[0]), a[1] + s * (b[1] - a[1])))
    return out


def dop_corners(D):
    """The corners of the 8-DOP D as a convex polygon, counterclockwise."""
    (x0, x1), (y0, y1) = D[0], D[1]
    poly = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
    for k in (2, 3):
        poly = _clip(poly, DIRS[k], D[k][0], keep_below=False)
        poly = _clip(poly, DIRS[k], D[k][1], keep_below=True)
    return poly


def moved_dop(D, R, t):
    """The 8-DOP of the corners of D moved by x -> R x + t: it contains the moved D."""
    return dop_of_points([apply(R, t, c) for c in dop_corners(D)])


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:
    dop: tuple
    tris: list
    left: "Node | None" = None
    right: "Node | None" = None

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


def build(tris) -> Node:
    """The 8-DOP tree over the triangles, one triangle per leaf, split at the median."""
    return _build(tris, list(range(len(tris))))


def _build(tris, idx) -> Node:
    node = Node(dop_of_points([p for i in idx for p in tris[i]]), idx)  # @line L1
    if len(idx) == 1:  # @line L2
        return node
    cent = {i: ((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}

    def spread(d):
        pr = [_dot(d, cent[i]) for i in idx]
        return (max(pr) - min(pr)) / math.hypot(*d)

    d = max(DIRS, key=spread)  # @line L3
    s = sorted(idx, key=lambda i: _dot(d, cent[i]))
    h = len(s) // 2
    node.left, node.right = _build(tris, s[:h]), _build(tris, s[h:])  # @line L4
    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 8-DOP tests.
    """
    moved_tris = {j: tuple(apply(R, t, p) for p in T) for j, T in enumerate(trisB)}
    world = {id(B): dop_of_points([p for j in B.tris for p in moved_tris[j]])}  # @line L5

    def dop_of(b):
        if id(b) not in world:
            world[id(b)] = moved_dop(b.dop, R, t)  # @line L6
        return world[id(b)]

    pairs = set()
    tests = 0
    stack = [(A, B)]
    while stack:  # @line L7
        a, b = stack.pop()
        tests += 1
        if not dop_overlap(a.dop, dop_of(b)):  # @line L8
            continue
        if a.leaf and b.leaf:  # @line L9
            i, j = a.tris[0], b.tris[0]
            if triangles_overlap(trisA[i], moved_tris[j]):
                pairs.add((i, j))
        elif b.leaf or (not a.leaf and len(a.tris) >= len(b.tris)):  # @line L10
            stack += [(a.left, b), (a.right, b)]
        else:
            stack += [(a, b.left), (a, b.right)]
    return pairs, tests
test_k_dop_tree.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-dop-tree/. The authors are listed in prov/ZJ32AH.jsonl.

import math
import random

from k_dop_tree import (
    DIRS,
    apply,
    build,
    dop_corners,
    dop_of_points,
    dop_overlap,
    moved_dop,
    overlap_pairs,
    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):
    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_dop(p, D, tol=1e-9):
    return all(lo - tol <= d[0] * p[0] + d[1] * p[1] <= hi + tol for d, (lo, hi) in zip(DIRS, D))


def test_page_example():
    # the triangle (0,0), (4,0), (0,4) has the 8-DOP x in [0,4], y in [0,4], x+y in [0,4], x-y in [-4,4]
    D = dop_of_points([(0, 0), (4, 0), (0, 4)], margin=False)
    assert D == ((0, 4), (0, 4), (0, 4), (-4, 4))
    corners = dop_corners(D)
    assert sorted(corners) == [(0, 0), (0, 4), (4, 0)]
    # the square [3,5] x [3,5] meets the box [0,4] x [0,4] but not the 8-DOP: x+y >= 6 > 4
    S = dop_of_points([(3, 3), (5, 3), (5, 5), (3, 5)], margin=False)
    assert not dop_overlap(D, S)
    assert dop_overlap(D[:2], S[:2])


def test_corners_of_random_dops():
    rng = random.Random(1)
    for _ in range(300):
        pts = [(rng.uniform(-5, 5), rng.uniform(-5, 5)) for _ in range(rng.randint(1, 8))]
        D = dop_of_points(pts, margin=False)
        C = dop_corners(D)
        assert 1 <= len(C) <= 8
        assert all(inside_dop(c, D) for c in C)
        # the corners have the same 8-DOP as the points
        E = dop_of_points(C, margin=False)
        assert all(abs(a - b) < 1e-9 for p, q in zip(D, E) for a, b in zip(p, q))


def test_interval_test_is_exact_in_the_plane():
    rng = random.Random(2)
    hits = 0
    for _ in range(1500):
        P = dop_of_points([(rng.uniform(-3, 3), rng.uniform(-3, 3)) for _ in range(rng.randint(2, 5))], margin=False)
        Q = dop_of_points([(rng.uniform(-3, 3), rng.uniform(-3, 3)) for _ in range(rng.randint(2, 5))], margin=False)
        expect = convex_overlap_reference(dop_corners(P), dop_corners(Q))
        assert dop_overlap(P, Q) == expect
        hits += expect
    assert 300 < hits < 1200


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_moved_dop_contains_the_moved_points():
    rng = random.Random(4)
    looser = 0
    for _ in range(300):
        pts = [(rng.uniform(-5, 5), rng.uniform(-5, 5)) for _ in range(6)]
        R, t = rotation(rng.uniform(0, 2 * math.pi)), (rng.uniform(-5, 5), rng.uniform(-5, 5))
        moved = [apply(R, t, p) for p in pts]
        M = moved_dop(dop_of_points(pts), R, t)
        tight = dop_of_points(moved)
        assert all(inside_dop(p, M) for p in moved)
        assert all(m[0] <= s[0] + 1e-9 and s[1] <= m[1] + 1e-9 for m, s in zip(M, tight))
        looser += any(m[1] - m[0] > s[1] - s[0] + 1e-6 for m, s in zip(M, tight))
    assert looser > 200


def test_every_dop_holds_its_triangles():
    rng = random.Random(5)
    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_dop(p, n.dop) 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(6)
    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)
            assert got == brute_pairs(trisA, trisB, R, t)
            assert tests <= (2 * 40 - 1) ** 2
            total += len(got)
    assert total > 100


def test_far_objects_need_one_test():
    rng = random.Random(7)
    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

Kay and Kajiya (1986) bounded objects by sets of parallel slabs to speed up ray tracing. Klosowski, Held, Mitchell, Sowizral and Zikan (1998) built hierarchies of k-DOPs for collision detection of a flying object in a static scene, studied several values of kk, and gave the two-level update of the moving tree. They compared their trees with the OBB tree of Gottschalk, Lin and Manocha.

References

  1. 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 definition of k-DOPs, the interval overlap test, and the update of the k-DOPs of the flying object by hill climbing at the root and by the k-DOP of the rotated k-DOP below it
  2. Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005, the chapters on bounding volumes (discrete oriented polytopes) 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.build
  • a full proof of time.dop_test
  • a full proof of time.moved_dop
  • 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)
WritingW2 basic
  • at least three sources