Data structureadvanced
Sphere tree
Also called bounding sphere hierarchy.
A hierarchy of spheres that cover an object, often built from the medial axis, used for fast and interruptible collision detection.
- Implements
- Spatial index
- Time
- O(n log^2 n) build_expectedO(2^L) interrupted_queryO(n m) queryO(1) sphere_test
- Space
- Θ(n) total
- Where
- L = the level at which an interrupted query stops; m = the number of triangles of the second object; n = the number of triangles of the first object
- Model
- Real RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Philip M. Hubbard, 1996
A sphere tree is a bounding volume hierarchy whose volumes are spheres. Each node stores a sphere that holds the part of the object below it. Two spheres overlap exactly when the distance between their centers is at most the sum of their radii, so the test is the cheapest of all volumes. A sphere does not change when the object turns, so a moving object moves only the centers. The fit is poor for long or flat parts. Hubbard built sphere trees from an approximation of the medial axis, so that the spheres of each level follow the shape. He used them for time-critical collision detection: the query goes down the trees one level at a time and can stop at any level, and the overlapping spheres at that level are an approximate answer.
In plain words
Cover the object with one large ball. Then cover each half of the object with a smaller ball, then each quarter, and so on, until each ball holds one small piece. Two objects can touch only where their balls touch, and to check whether two balls touch you compare one distance with the sum of two radii.
A program that must answer on time, like a game or a simulator, can go down the two trees one level at a time and stop when its time is up. The balls that still touch at that level are its best guess. With more time, the guess gets finer.
The abstract type
A sphere tree is a static spatial index over the triangles of one rigid object. The operations are:
- BUILD: make the tree for the triangle set .
- OVERLAP: when is placed by the rigid motion in the frame of , the pairs of a triangle of and a triangle of that meet and that the query resolved, and the pairs of nodes whose spheres still overlap when the query stops at the level .
With no limit, the second list is empty and the first one is the exact answer. The tree does not support insert or delete.
Representation
A node stores a center and a radius . An inner node has two children, and a leaf holds one triangle. The invariant is:
- (B) Bounds. The sphere of each node contains every triangle below it.
The code is in the plane, with circles. It fits each node with the smallest circle that holds the vertices below it, by Welzl's algorithm with a fixed seed, and it splits the triangles at the median along the wider spread of their centroids. This top-down build is the code's choice, because it is short and it keeps (B) by construction. Hubbard instead built the spheres of each level from the medial axis of the object, and Bradshaw and O'Sullivan made this fit tighter.
Operations
BUILD(T) ▷ T: triangles; one per leaf- 1
(c, r) ← the smallest circle that holds the vertices of T - 2
if |T| = 1 then return a leaf with (c, r) - 3
a ← the coordinate axis with the wider spread of the triangle centroids - 4
sort T along a; return a node with (c, r) and the children BUILD(first half), BUILD(second half)
OVERLAP(A, B, R, t, L) ▷ B placed by x → R x + t- 1
the moved center of a node b of B is R c(b) + t; its radius stays r(b) - 2
frontier ← [(root(A), root(B))]; for the levels 0, 1, 2, ... while the frontier is not empty - 3
for each pair (a, b) in the frontier: if dist(c(a), R c(b) + t) > r(a) + r(b) then skip it - 4
if a and b are leaves then if their triangles meet, report the pair - 5
else if this level is L then add (a, b) to the possible pairs - 6
else put (left(a), b), (right(a), b) in the next frontier if a has the larger sphere and is not a leaf; else (a, left(b)), (a, right(b))
The query is breadth first, so it refines all overlapping pairs of one level before it goes to the next. This is what makes it interruptible. A depth-first query that stops early would have resolved a few pairs to the leaves and left the others at the roots.
Example
Take an object of 4 triangles in a row, for . The root circle has the center and the radius , with the vertices and on a diameter. The two inner circles have the centers and and the radius . Each leaf circle has the radius . Let be a copy turned by and moved by , so that the first triangle of stands on the last triangle of .
| level limit | circle tests | reported pairs | possible pairs (triangles of a, triangles of b) |
|---|---|---|---|
| 0 | 1 | none | (0 to 3, 0 to 3) |
| 1 | 3 | none | (2 and 3, 0 to 3) |
| 2 | 5 | none | (2 and 3, 0 and 1) |
| 3 | 7 | none | (3, 0 and 1) |
| none | 9 | (3, 0) | none |
Each row narrows the possible contact, and the full query finds the pair , like the brute-force method over all 16 pairs. On random scenes of small triangles, with the two objects on top of each other, the full query did between 1209 and 1655 circle tests in 3 trials. A query stopped at the level 8 did between 131 and 169 tests and returned between 28 and 39 possible pairs.
Correctness
The proof is in proofs/correctness.md. A disk is convex, so a circle that holds the vertices below a node holds its triangles, and (B) holds for any circle that holds the vertices, even one that is not the smallest. A rigid motion maps a disk to the disk with the moved center and the same radius, so the moved spheres of hold the moved triangles. If two triangles meet at a point , every pair of their ancestors has two spheres that hold , so the query never prunes such a pair. It either reaches the two leaves and reports the pair, or it stops at the level limit with an ancestor pair in the possible list. So the stopped query never misses a contact, and the full query is exact.
Proof: The sphere tree query is exact when it runs to the leaves and covers every contact when it stops earlyfull
Let be a set of triangles and a set of triangles in the plane, and let be a rigid motion, with a rotation. Let be the set of the pairs such that the closed triangle meets the closed triangle . We work in the real RAM. For a node let be the triangles below it, and let and be the center and the radius of its circle .
Lemma 1 (the build). The build makes a tree with leaves, one for each triangle, and nodes. Each circle contains every triangle of .
Proof. The radius is the radius of a circle that holds every vertex below , grown by a margin . The disk is convex, so it holds each triangle of , which is the convex hull of three of these vertices. The circle need not be the smallest one for this lemma, so the lemma does not depend on the seed of the shuffle. A node with triangles is split at the median of a sorted list into two nonempty halves, so the recursion ends at leaves of one triangle, and a binary tree with leaves in which every inner node has two children has nodes.
The three loops in the code are Welzl's algorithm: the outer loop keeps the smallest circle of the first points, the middle loop the smallest circle of the first points with on the boundary, and the inner loop the circle with and on the boundary. Its correctness is on the page of Welzl's algorithm. The query needs only Lemma 1.
Lemma 2 (the moved circle). The disk with the center and the radius is , and it contains for each node of .
Proof. A rigid motion keeps distances, so it maps the disk with the center and the radius onto the disk with the center and the radius . It maps into .
Two closed disks meet exactly when the distance of their centers is at most the sum of their radii, so the circle test of the code is exact for disks.
Theorem. The query terminates after at most circle tests. Every pair that it reports is in . With no level limit, it reports all of and returns no possible pairs. With the level limit , it does at most tests, and for each that it does not report, there is a returned possible pair with , and .
Proof. Each pair in the frontier of round is (child, same) or (same, child) of a pair in the frontier of round , so each pair of nodes is reached at most once, along the unique path of pairs from (root, root), and the depth of the pairs in round is . This bounds the number of tests by the number of pairs of nodes, and the query terminates. A pair is refined into two pairs, so the frontier of round has at most pairs. With the limit , no pair is pushed after round , so the tests are at most .
Soundness. The code adds only at a pair of leaves, after the exact separating axis test of the two triangles on their 6 edge normals. So every reported pair is in . A possible pair is returned only after its circle test succeeds, so its disks meet.
Coverage. Let , with a point in . Call a pair of nodes good if and . The pair (root, root) is good and is in the first frontier. If a good pair is tested, then by Lemma 1 and by Lemma 2, so the disks meet and the test does not prune it. Then one of three things happens. If both nodes are leaves, they are the leaves of and , and the code reports . If the round is the limit , the code returns as a possible pair, which has the stated property. 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 in the next frontier. The depth of the good pair grows by one in each round, so one of the first two cases happens. With no limit, only the first case can happen, so is reported, and no possible pair is ever returned.
Remarks. The same proof holds in 3D with balls, and it holds for a tree whose spheres come from the medial axis, as long as the sphere of each node holds all the geometry below it. The margin of times the scale in the code only grows the radii, so the theorem holds for it, and it keeps a contact on a circle from being lost to rounding in floating point.
Complexity
The model is the real RAM. Welzl's algorithm takes expected linear time over the random order, so each level of the build costs expected for the circles and for the sort, over levels.
| operation | time | case |
|---|---|---|
| build | expected over the shuffle | |
| sphere test | one distance and one sum | |
| full query | worst; far fewer tests on typical scenes, as measured above | |
| query stopped at the level | each level at most doubles the frontier | |
| space | nodes |
The bound does not depend on the size of the objects, so the time of a stopped query is known in advance. This is the point of the time-critical query.
Variants
- Medial-axis builds. Hubbard placed spheres on an approximation of the medial axis, found from the Voronoi diagram of points on the surface, and merged them into the spheres of the higher levels. Bradshaw and O'Sullivan refined the approximation where the fit was poor. These trees follow the shape closely, but they cost much more to build.
- Octree builds. A simpler build puts a sphere around each occupied cell of an octree of the object. It is fast and loose.
- Fit measures. A tight tree keeps the spheres from sticking far out of the object. The Hausdorff distance between the union of the spheres of a level and the object is a natural measure of this error.
- Other volumes. OBB trees and k-DOP trees fit better but cost more to test or to update. Swept sphere volumes add a radius to a segment or a rectangle, and they keep the cheap test for long parts.
- Deformable objects. Each sphere can be refitted from the vertices below it, or grown to hold its two child spheres, which is fast but loose.
When to use it
Use a sphere tree when the test must be cheap, when objects turn often, or when the query must meet a time limit, as in interactive simulation, games and haptics. The level limit gives a direct trade between time and accuracy. For exact contacts between long, flat or tightly fitting parts, an OBB tree usually needs far fewer tests.
Pitfalls
- Loose spheres. A sphere around a thin rod or a flat plate is mostly empty. On such objects a sphere tree reports many false overlaps and goes deep before it prunes.
- A stopped query is not a contact. The possible pairs at the level limit are only overlapping spheres. They can be far from a true contact. Treat them as an approximation and pass them to a response that accepts this.
- A sphere that does not hold its part. In a medial-axis build, a child sphere need not be inside its parent. This is fine, but the query is safe only if each sphere holds all the geometry below it. Check this invariant after the build.
- Rounding. Grow the radii by a small margin, as in the code, so that a contact on a circle is not lost.
- A bad seed. Welzl's algorithm is randomized. The circle does not depend on the seed, but the time is cubic in the worst order. Shuffle the points.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sphere-tree/. The authors are listed in prov/0FMTPB.jsonl.
"""A tree of circles over the triangles of a 2D object, with a breadth-first overlap query that can stop at a level.
Each node stores the smallest circle that holds the vertices of the triangles below it, found
by Welzl's randomized algorithm with a fixed seed. A circle does not change when the object
turns, so the query moves only the centers. The query goes down both trees one level at a time.
If it stops at a level limit, it returns the exact pairs found so far and the pairs of nodes
whose circles still overlap, which cover every contact that it has not yet resolved. This is
the interruptible query of Hubbard. Hubbard built the circles from the medial axis; this code
builds them top down, which is simpler and gives a valid tree.
"""
from __future__ import annotations
import math
import random
from dataclasses import dataclass
EPS = 1e-9 # each radius grows by EPS times the scale, so that rounding cannot remove a contact
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 _circle2(a, b):
c = ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2)
return c, math.dist(a, c)
def _circle3(a, b, c):
bx, by = b[0] - a[0], b[1] - a[1]
cx, cy = c[0] - a[0], c[1] - a[1]
d = 2 * (bx * cy - by * cx)
if d == 0: # collinear: the circle on the farthest pair
return max((_circle2(p, q) for p, q in ((a, b), (a, c), (b, c))), key=lambda x: x[1])
ux = (cy * (bx * bx + by * by) - by * (cx * cx + cy * cy)) / d
uy = (bx * (cx * cx + cy * cy) - cx * (bx * bx + by * by)) / d
o = (a[0] + ux, a[1] + uy)
return o, max(math.dist(o, a), math.dist(o, b), math.dist(o, c))
def _inside(circle, p):
c, r = circle
return math.dist(c, p) <= r * (1 + 1e-12) + 1e-12
def min_enclosing_circle(points, seed=0):
"""The smallest circle that holds the points: Welzl's algorithm, written as three loops."""
P = list(points)
random.Random(seed).shuffle(P)
circle = (P[0], 0.0)
for i in range(1, len(P)):
if _inside(circle, P[i]):
continue
circle = (P[i], 0.0)
for j in range(i):
if _inside(circle, P[j]):
continue
circle = _circle2(P[i], P[j])
for k in range(j):
if not _inside(circle, P[k]):
circle = _circle3(P[i], P[j], P[k])
return circle
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 = [n[0] * x[0] + n[1] * x[1] for x in T]
p2 = [n[0] * x[0] + n[1] * x[1] for x in U]
if max(p1) < min(p2) or max(p2) < min(p1):
return False
return True
@dataclass
class Node:
center: tuple
radius: float
tris: list
left: "Node | None" = None
right: "Node | None" = None
@property
def leaf(self):
return self.left is None
def build(tris) -> Node:
"""The sphere tree over the triangles, one triangle per leaf, split at the median."""
return _build(tris, list(range(len(tris))))
def _build(tris, idx) -> Node:
pts = [p for i in idx for p in tris[i]]
c, r = min_enclosing_circle(pts) # @line L1
scale = max(1.0, max(abs(x) for p in pts for x in p))
node = Node(c, r + EPS * scale, idx)
if len(idx) == 1: # @line L2
return node
cent = {i: (sum(p[0] for p in tris[i]) / 3, sum(p[1] for p in tris[i]) / 3) for i in idx}
spread = [max(cent[i][a] for i in idx) - min(cent[i][a] for i in idx) for a in (0, 1)]
axis = 0 if spread[0] >= spread[1] else 1 # @line L3
s = sorted(idx, key=lambda i: cent[i][axis])
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), max_level=None):
"""Breadth-first overlap query of A and of B moved by x -> R x + t.
Returns (pairs, possible, tests): the pairs (i, j) of triangles that meet and were resolved,
the pairs of nodes whose circles overlap at the level limit, and the number of circle tests.
With max_level=None the query runs to the leaves and possible is empty.
"""
moved = {}
def center(b):
if id(b) not in moved:
moved[id(b)] = apply(R, t, b.center) # @line L5
return moved[id(b)]
pairs, possible, tests = set(), [], 0
level, frontier = 0, [(A, B)]
while frontier: # @line L6
nxt = []
for a, b in frontier:
tests += 1
if math.dist(a.center, center(b)) > a.radius + b.radius: # @line L7
continue
if a.leaf and b.leaf: # @line L8
i, j = a.tris[0], b.tris[0]
if triangles_overlap(trisA[i], tuple(apply(R, t, p) for p in trisB[j])):
pairs.add((i, j))
elif max_level is not None and level == max_level: # @line L9
possible.append((a, b))
elif b.leaf or (not a.leaf and a.radius >= b.radius): # @line L10
nxt += [(a.left, b), (a.right, b)]
else:
nxt += [(a, b.left), (a, b.right)]
frontier, level = nxt, level + 1
return pairs, possible, tests
test_sphere_tree.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sphere-tree/. The authors are listed in prov/0FMTPB.jsonl.
import itertools
import math
import random
from sphere_tree import (
_circle2,
_circle3,
apply,
build,
min_enclosing_circle,
overlap_pairs,
rotation,
triangles_overlap,
)
def brute_circle(points):
"""The smallest circle through 2 or 3 of the points that holds all of them."""
best = None
cands = [_circle2(a, b) for a, b in itertools.combinations(points, 2)]
cands += [_circle3(a, b, c) for a, b, c in itertools.combinations(points, 3)]
for c, r in cands:
if all(math.dist(c, p) <= r + 1e-9 for p in points) and (best is None or r < best[1]):
best = (c, r)
return best
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 chain():
return [((2 * k, 0), (2 * k + 1.5, 0), (2 * k + 0.5, 1)) for k in range(4)]
def test_page_example():
root = build(chain())
# the root circle: the vertices (0, 0) and (7.5, 0) are a diameter, and every other vertex is inside
assert abs(root.center[0] - 3.75) < 1e-9 and abs(root.center[1]) < 1e-9
assert abs(root.radius - 3.75) < 1e-6
tris = chain()
pairs, possible, tests = overlap_pairs(root, tris, root, tris, rotation(math.pi / 2), (7.0, 0.5))
assert pairs == {(3, 0)} and possible == []
pairs, possible, tests = overlap_pairs(root, tris, root, tris, rotation(math.pi / 2), (20.0, 0.0))
assert pairs == set() and tests == 1
def test_min_enclosing_circle_against_brute_force():
rng = random.Random(1)
for _ in range(200):
pts = [(rng.uniform(-5, 5), rng.uniform(-5, 5)) for _ in range(rng.randint(2, 9))]
c, r = min_enclosing_circle(pts, seed=rng.randint(0, 99))
bc, br = brute_circle(pts)
assert all(math.dist(c, p) <= r + 1e-9 for p in pts)
assert abs(r - br) < 1e-9
def test_circle_does_not_depend_on_the_seed():
rng = random.Random(2)
for _ in range(50):
pts = [(rng.gauss(0, 3), rng.gauss(0, 1)) for _ in range(40)]
radii = [min_enclosing_circle(pts, seed=s)[1] for s in range(5)]
assert max(radii) - min(radii) < 1e-9
def test_triangle_overlap_on_simple_cases():
T = ((0, 0), (2, 0), (0, 2))
assert triangles_overlap(T, ((1, 1), (3, 1), (1, 3))) # they share the point (1, 1)
assert not triangles_overlap(T, ((1.1, 1.1), (3, 1), (1, 3)))
assert triangles_overlap(T, ((0.2, 0.2), (0.5, 0.2), (0.2, 0.5))) # one inside the other
def test_every_circle_holds_its_triangles():
rng = random.Random(3)
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(math.dist(n.center, p) <= n.radius 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(4)
total = 0
for _ in range(25):
trisA, trisB = random_object(rng, 40), 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, possible, tests = overlap_pairs(root_a, trisA, root_b, trisB, R, t)
assert got == brute_pairs(trisA, trisB, R, t) and possible == []
assert tests <= (2 * 40 - 1) ** 2
total += len(got)
assert total > 100
def test_a_stopped_query_covers_every_contact():
rng = random.Random(5)
for _ in range(15):
trisA, trisB = random_object(rng, 30), random_object(rng, 30)
root_a, root_b = build(trisA), build(trisB)
R, t = rotation(rng.uniform(0, 2 * math.pi)), (rng.uniform(-5, 5), rng.uniform(-5, 5))
want = brute_pairs(trisA, trisB, R, t)
last = None
for level in range(0, 14):
got, possible, tests = overlap_pairs(root_a, trisA, root_b, trisB, R, t, max_level=level)
assert got <= want
covered = set(got)
for a, b in possible:
assert math.dist(a.center, apply(R, t, b.center)) <= a.radius + b.radius
covered |= {(i, j) for i in a.tris for j in b.tris}
assert want <= covered
if last is not None:
assert tests >= last
last = tests
full = overlap_pairs(root_a, trisA, root_b, trisB, R, t)
assert full[0] == want
History
Hubbard (1996) built sphere trees from an approximation of the medial axis and gave the breadth-first, interruptible query, for collision detection that must meet a time limit. Bradshaw and O'Sullivan (2004) gave an adaptive approximation of the medial axis that builds tighter sphere trees. The smallest enclosing circle that the code uses is due to Welzl (1991).
References
- Philip M. Hubbard, Approximating polyhedra with spheres for time-critical collision detection, ACM Transactions on Graphics 15(3), 1996, 179 to 210, the build of sphere trees from an approximation of the medial axis, and the interruptible breadth-first collision query
- Gareth Bradshaw and Carol O'Sullivan, Adaptive medial-axis approximation for sphere-tree construction, ACM Transactions on Graphics 23(1), 2004, 1 to 26, the build of tighter sphere trees from an adaptive approximation of the medial axis
- Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005, the chapters on bounding volumes (spheres) 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 0FMTPB Edit this page History Report an error Markdown