Algorithmcore
Sweep and prune
Also called sort and sweep.
Find overlapping bounding boxes by keeping their interval endpoints sorted per axis and updating the sort incrementally between time steps.
- Solves
- Collision detection
- Time
- O(n log n + q) sort_and_sweepO(n + r) updateO(n^2) worst_update
- Space
- O(n + m) total
- Where
- m = the number of pairs that overlap on at least one axis; n = the number of boxes; q = the number of pairs whose intervals overlap on the sweep axis; r = the number of endpoint swaps in one update
- Model
- Real RAM
- Properties
- deterministicin placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David Baraff, Jonathan D. Cohen, Ming C. Lin, Dinesh Manocha, Madhav K. Ponamgi, 1992
Sweep and prune is a broad phase for collision detection. It finds all pairs of overlapping axis-aligned bounding boxes among boxes. For each axis it keeps a list of the interval endpoints in sorted order, and for each pair of boxes it keeps the number of axes on which their intervals overlap. Between time steps the boxes move only a little, so insertion sort repairs each list with few swaps, and each swap changes one counter. The pairs with a full count go to the narrow phase.
In plain words
Think of a set of boxes on a table. Look at them from the front, so that each box is a line segment on the floor line. Two boxes can touch only if their segments overlap. Do the same from the side. Two boxes overlap only if their segments overlap in both views.
To find overlapping segments fast, write all the segment ends in order along the line. When you pass the start of a segment, it is open, and it overlaps every segment that is open at that moment.
The boxes move only a little from one frame to the next. So the list of ends is almost in order already. Fix it with a few neighbor swaps. Each time the start of one segment passes the end of another, the two segments start or stop overlapping, and you update one count.
The problem
The input is closed boxes in the plane, given again at each time step with new values. The output at each step is the set of pairs with . Two closed boxes intersect exactly when their intervals intersect on each axis, so the problem splits into one interval problem per axis. This page uses 2D boxes. In 3D the method is the same with three lists.
This is the broad phase of collision detection. The boxes bound the objects, so a pair that is not reported cannot collide, and each reported pair goes to an exact test, for example GJK for convex shapes.
The algorithm
Each endpoint is a triple (value, kind, box), with kind 0 for a lower endpoint and 1 for an upper endpoint. Triples compare in lexicographic order. So at equal values a lower endpoint comes first, and boxes that only touch count as overlapping. The state is the sorted list for each axis , a counter for each pair that overlaps on at least one axis, and the set of pairs with .
UPDATE(E, c, P, box) ▷ box: the new boxes, same indices- 1
r ← 0 - 2
for each axis a do - 3
set the value of each endpoint in E[a] from box - 4
for i ← 1 to |E[a]| - 1 do - 5
j ← i - 6
while j > 0 and E[a][j - 1] > E[a][j] do - 7
x ← E[a][j]; y ← E[a][j - 1]; p ← the pair of the boxes of x and y - 8
if x is lower and y is upper then c[p] ← c[p] + 1; if c[p] = 2 then add p to P - 9
if x is upper and y is lower then if c[p] = 2 then remove p from P; c[p] ← c[p] - 1 - 10
swap E[a][j - 1] and E[a][j]; j ← j - 1; r ← r + 1 - 11
return P, r
Lines L4 to L10 are insertion sort. Line L8 is the case where the lower endpoint of one box passes to the left of the upper endpoint of another box: their intervals start to overlap on this axis. Line L9 is the opposite case: they stop overlapping. A swap of two lower endpoints or of two upper endpoints changes nothing.
The first frame has no sorted lists to repair. Sort each list once and set the counters with one sweep per axis: at each lower endpoint, add 1 to the counter of the new box and each box that is open. The same sweep on one axis, with a test of the other axis for each open box, is the one-shot method that is also called sort and sweep.
SORT-AND-SWEEP(box, a) ▷ a: the sweep axis- 1
sort the boxes by their lower value on axis a; active ← empty; out ← empty - 2
for each box i in this order do - 3
remove from active each j with hi_a(j) < lo_a(i) - 4
for each j in active do if B_i and B_j overlap on the other axis then add {i, j} to out - 5
add i to active - 6
return out
Example
Take four boxes: , , and . Write and for the lower and upper endpoints of box . After the first sort and sweep:
| axis | sorted list | overlaps on this axis |
|---|---|---|
| x | {0, 1}, {1, 2} | |
| y | {0, 1}, {0, 3}, {1, 3}, {1, 2} |
So , , and .
Now box 3 moves 4 units to the left and 2 units up, to . Line L3 writes the new values into the old lists, and insertion sort makes these swaps:
| axis | swap at line L10 | rule | counter | P |
|---|---|---|---|---|
| x | passes | L8 | no change | |
| x | passes | L8 | add {1, 3} | |
| x | passes | none | ||
| y | passes | none | ||
| y | passes | L8 | add {2, 3} | |
| y | passes | none |
The update makes swaps and returns , which is the brute force answer. The pair {0, 3} keeps : the boxes touch on y at the value 2, but on x the interval [5, 6] does not meet [0, 4]. In the last swap the two upper endpoints have the same value 5, and the box index breaks the tie, which changes no counter.
Correctness
The proof is in proofs/correctness.md. The main fact is that the relation "the lower endpoint of is before the upper endpoint of , and the lower endpoint of is before the upper endpoint of " is the overlap of the two closed intervals when the list is sorted. A swap of two neighbors changes this relation for the pair of their owners only, and only when one is a lower endpoint and the other an upper endpoint. Lines L8 and L9 follow these changes exactly, so after the sort each counter is the number of axes on which the pair overlaps. The two endpoints of one box are never swapped, because the lower endpoint is never larger than the upper one.
Proof: Incremental sweep and prune reports exactly the overlapping pairs, and one update makes r swapsfull
Let the boxes be for , closed, with and . On axis , box has two endpoints, and . Endpoints are compared as triples in lexicographic order, so at equal values a lower endpoint comes before an upper endpoint. This is the key of line L6. Write for this order. It is a strict total order on the endpoints of one axis, because the triples are distinct.
The state holds, for each axis , a list of the endpoints of the axis, a counter for each pair , and a set of pairs. The invariant is:
- (S) each list is sorted by ;
- (C) is the number of axes with and ;
- (P) .
Lemma 1 (order and overlap). On axis , the intervals of boxes intersect if and only if and .
Proof. holds if , or if the values are equal and the second fields compare . So it holds exactly when . In the same way holds exactly when . Two closed intervals intersect exactly when both inequalities hold.
So under (C) and (P), the set is the set of pairs of boxes that intersect on both axes, which is the set of pairs of intersecting boxes.
Lemma 2 (one swap). Let be adjacent in with before and , and let be after the swap of line L10. Let be the pair of the owners of and . Then the relation of Lemma 1 on axis changes only for . It changes from false to true if is a lower endpoint and is an upper endpoint, from true to false if is an upper endpoint and is a lower endpoint, and it does not change otherwise.
Proof. The relation of Lemma 1 for a pair depends only on the relative positions of the four endpoints of and in the list. Here the "position" order of the list and the key order are different things while the list is not sorted, so we define the relation by list positions: holds if is before and is before in the list. A swap of two adjacent elements changes the relative position of these two elements only. So can change only for the pair of the owners of and .
The two endpoints of one box are never swapped. Line L3 sets the values from boxes with , so , and line L6 swaps only a pair that is out of order.
Now let belong to box and to box . Suppose and . Before the swap, is before , so is false. After the swap, is before . Also is before , which is now directly after , so is before , which is before . So is true. Suppose and . After the swap, is before , so is false. Before the swap, was directly before , and is before , so was before and thus before , and was true. If and are both lower endpoints or both upper endpoints, the two conditions of compare a lower endpoint with an upper endpoint, and neither of them compares with , so neither changes.
We now use the invariant with in place of the relation of Lemma 1 in (C): is the number of axes with . When a list is sorted, and the relation of Lemma 1 agree, so after each completed update this is the same as (C).
Theorem. If the invariant holds before UPDATE, then UPDATE terminates, the invariant holds after it for the new boxes, and the returned number is the total number of inversions of the lists after line L3, that is, the number of pairs of endpoints that are in the wrong order.
Proof. Line L3 changes the values of the endpoints but not the list positions, so (C) and (P) hold for after line L3. (S) may fail.
Lines L4 to L10 are insertion sort on with the order . Each swap of line L10 exchanges an adjacent pair that is out of order, so it removes exactly one inversion and creates none. The number of inversions is finite and is at least 0, so the loop terminates, and the number of swaps is the number of inversions after line L3. When the loop of line L4 ends, the list is sorted, which is the standard invariant of insertion sort: before step the prefix is sorted, and the inner loop moves left until its left neighbor is smaller.
At each swap, Lemma 2 says how changes. Line L8 adds 1 to when changes from false to true, and line L9 subtracts 1 when it changes from true to false. No other counter changes, and by Lemma 2 no other changes. So (C) for holds after each swap. Line L8 adds to when the new counter is 2, and line L9 removes when the old counter is 2. Since a counter changes by one at a time, this keeps (P). After both axes are sorted, (S) holds, and equals the relation of Lemma 1, so (C) holds as stated.
Initialization. The constructor sorts each list, so (S) holds, and then sweeps each sorted list: at each lower endpoint of box it adds 1 to for each box whose interval is open at that moment, that is, whose lower endpoint was passed and whose upper endpoint was not. For a pair with , box is open at exactly when , and holds already because . So the counter gets 1 on axis exactly when the relation of Lemma 1 holds, and it is counted once, at the later of the two lower endpoints. So (C) and (P) hold.
The one-shot sweep. SORT-AND-SWEEP sorts the boxes by on the sweep axis and keeps the boxes whose interval contains the current . For processed after , the interval of is kept exactly when , and holds by the order, so is tested against exactly when the intervals on the sweep axis intersect. Each such pair is then tested on the other axis. Each pair is considered once, when the later box is processed. So the output is the set of intersecting pairs.
Complexity
The update does work per axis outside the swaps, and work per swap with a hash table for the counters. So it costs in the real RAM with hashing, where is the number of inversions that the motion makes in the lists. This bound is exact in terms of , but itself has no useful worst case bound: one step can reverse a list, and then . That is close to in a simulation is an observation about coherent motion, not a theorem.
The one-shot sort and sweep costs , where is the number of pairs whose intervals overlap on the sweep axis. The output size can be much smaller than . If all boxes are in a thin column along the sweep axis, every pair overlaps on that axis, so even when . Choosing the sweep axis with the largest spread of box centers helps, but it does not remove this case.
The space is for the lists and the counters of the pairs that overlap on at least one axis. Like , can be for clustered scenes.
Properties
- The output is exact for the boxes: no pair is lost and no pair is reported twice.
- The method is deterministic and in place on the lists.
- It is output sensitive only through and , not through the output size .
- It handles boxes that change size, not only boxes that move.
Variants and improvements
- Sort and sweep from scratch. Sort once per frame, for example with radix sort on the float keys, and sweep one axis. It does not keep counters between frames, so it has no cost for teleports and no memory for pairs.
- Three axes or one axis. I-COLLIDE keeps sorted lists on all three axes of 3D. Many engines keep one sorted axis and test the other axes directly for the open boxes, which uses less memory.
- Insertions and deletions. A new box can be put at the end of each list with the value and then moved into place with the update. A deleted box is moved to the end in the same way, and its counters are dropped.
- Several sweep and prune regions. A large world is cut into regions with one structure each, so that a cluster in one place does not make all lists long.
- Other broad phases. A uniform grid or spatial hashing is better when objects are of similar size and spread in all directions. A dynamic bounding volume hierarchy is better for many static objects and for ray queries. The offline problem of reporting all intersecting rectangles has an solution with an interval tree; see rectangle intersection reporting.
When to use it
Use sweep and prune as the broad phase of a simulation with many moving objects and small motion per step, which is the usual case in games and physics engines. Use sort and sweep from scratch when objects jump, appear and disappear often. Do not use it when many objects line up along an axis (a stack of boxes, a long road of cars), unless you choose the axis with care; a grid or a BVH is not sensitive to this.
Pitfalls
- Ties. Line L6 must use the same total order as the first sort. With lower endpoints before upper endpoints at equal values, touching boxes overlap. With the other order they do not. A mix of the two orders makes the counters wrong.
- Updating counters without the swap rules. Do not recompute a pair from its boxes at a swap and then add or subtract 1. A swap of two lower endpoints, or of two upper endpoints, must change nothing, and two equal values must not toggle anything.
- A counter of 0. Remove a pair from the table when its counter drops to 0, or the table grows with every pair that ever overlapped on one axis.
- Teleports. A box that jumps across the scene makes up to swaps on each axis. If this happens often, rebuild with a full sort.
- Clustering. A scene that is spread along one axis only, for example objects in a line on a floor, gives many overlaps on the other axis and makes and large.
- Float noise. Boxes that are computed from rotating objects change size every frame, so their endpoints swap back and forth around equal values. Grow the boxes by a small margin and update them only when an object leaves its grown box.
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/sweep-and-prune/. The authors are listed in prov/46M4XT.jsonl.
"""Sweep and prune for 2D axis-aligned boxes.
A box is a tuple (xlo, ylo, xhi, yhi) with xlo <= xhi and ylo <= yhi. Boxes are closed,
so two boxes that only touch overlap. The class keeps, for each axis, the list of the 2n
interval endpoints in sorted order, a counter per pair of boxes (the number of axes on which
the two intervals overlap) and the set of pairs whose counter is 2.
update() moves the boxes and repairs each list with insertion sort. Each swap of a lower
endpoint with an upper endpoint changes one counter by one. The cost of one update is
O(n + r) for r swaps. sort_and_sweep() is the one-shot version: O(n log n + q), where q is
the number of pairs whose intervals overlap on the sweep axis.
"""
from __future__ import annotations
Box = tuple[float, float, float, float]
Pair = tuple[int, int]
LO, HI = 0, 1
def _pair(i: int, j: int) -> Pair:
return (i, j) if i < j else (j, i)
def sort_and_sweep(boxes: list[Box], axis: int = 0) -> set[Pair]:
"""All pairs of overlapping boxes: sort on one axis, sweep, test the other axis."""
other = 1 - axis
order = sorted(range(len(boxes)), key=lambda i: boxes[i][axis])
active: list[int] = []
out: set[Pair] = set()
for i in order:
lo = boxes[i][axis]
active = [j for j in active if boxes[j][axis + 2] >= lo] # drop the intervals that ended
for j in active: # j overlaps i on the sweep axis
if boxes[i][other] <= boxes[j][other + 2] and boxes[j][other] <= boxes[i][other + 2]:
out.add(_pair(i, j))
active.append(i)
return out
class SweepAndPrune:
"""Incremental sweep and prune over n boxes that keep their index."""
def __init__(self, boxes: list[Box]) -> None:
self.boxes: list[Box] = list(boxes)
n = len(self.boxes)
# endpoint = [value, kind, id]; kind LO sorts before HI at equal values
self.ends: list[list[list]] = []
for a in range(2):
e = [[self.boxes[i][a], LO, i] for i in range(n)] + [[self.boxes[i][a + 2], HI, i] for i in range(n)]
e.sort()
self.ends.append(e)
self.count: dict[Pair, int] = {}
for a in range(2):
active: set[int] = set()
for v, kind, i in self.ends[a]:
if kind == LO:
for j in active:
p = _pair(i, j)
self.count[p] = self.count.get(p, 0) + 1
active.add(i)
else:
active.discard(i)
self.pairs: set[Pair] = {p for p, c in self.count.items() if c == 2}
def update(self, boxes: list[Box]) -> int:
"""Move the boxes to new positions and repair the state. Returns the number of swaps r."""
self.boxes = list(boxes)
r = 0 # @line L1
for a in range(2): # @line L2
e = self.ends[a]
for end in e: # @line L3
end[0] = self.boxes[end[2]][a + 2 * end[1]]
for i in range(1, len(e)): # @line L4
j = i # @line L5
while j > 0 and e[j - 1] > e[j]: # @line L6
x, y = e[j], e[j - 1] # @line L7
if x[2] != y[2]:
p = _pair(x[2], y[2])
if x[1] == LO and y[1] == HI: # @line L8
c = self.count.get(p, 0) + 1
self.count[p] = c
if c == 2:
self.pairs.add(p)
elif x[1] == HI and y[1] == LO: # @line L9
c = self.count[p]
if c == 2:
self.pairs.discard(p)
if c == 1:
del self.count[p]
else:
self.count[p] = c - 1
e[j - 1], e[j] = x, y # @line L10
j -= 1
r += 1
return r # @line L11
def overlapping_pairs(self) -> set[Pair]:
return set(self.pairs)
def check_invariant(self) -> None:
for a in range(2):
e = self.ends[a]
assert all(e[k] <= e[k + 1] for k in range(len(e) - 1))
n = len(self.boxes)
for i in range(n):
for j in range(i + 1, n):
c = sum(
1
for a in range(2)
if self.boxes[i][a] <= self.boxes[j][a + 2] and self.boxes[j][a] <= self.boxes[i][a + 2]
)
assert self.count.get((i, j), 0) == c
assert ((i, j) in self.pairs) == (c == 2)
test_sweep_and_prune.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sweep-and-prune/. The authors are listed in prov/46M4XT.jsonl.
import random
from sweep_and_prune import SweepAndPrune, sort_and_sweep
def brute(boxes):
out = set()
for i in range(len(boxes)):
for j in range(i + 1, len(boxes)):
a, b = boxes[i], boxes[j]
if a[0] <= b[2] and b[0] <= a[2] and a[1] <= b[3] and b[1] <= a[3]:
out.add((i, j))
return out
def inversions(sap, boxes):
total = 0
for a in range(2):
e = [[boxes[x[2]][a + 2 * x[1]], x[1], x[2]] for x in sap.ends[a]]
total += sum(1 for i in range(len(e)) for j in range(i + 1, len(e)) if e[i] > e[j])
return total
def page_example():
return [(0, 0, 4, 2), (3, 1, 6, 5), (5, 4, 8, 6), (9, 0, 10, 3)]
def test_page_example():
boxes = page_example()
sap = SweepAndPrune(boxes)
assert sap.overlapping_pairs() == {(0, 1), (1, 2)}
assert [(v, k, i) for v, k, i in sap.ends[0]] == [
(0, 0, 0), (3, 0, 1), (4, 1, 0), (5, 0, 2), (6, 1, 1), (8, 1, 2), (9, 0, 3), (10, 1, 3)
]
assert sap.count == {(0, 1): 2, (1, 2): 2, (0, 3): 1, (1, 3): 1}
moved = [(0, 0, 4, 2), (3, 1, 6, 5), (5, 4, 8, 6), (5, 2, 6, 5)] # box 3 moves 4 left and 2 up
r = sap.update(moved)
assert r == 6
assert sap.overlapping_pairs() == brute(moved) == {(0, 1), (1, 2), (1, 3), (2, 3)}
assert sap.count[(1, 3)] == 2 and sap.count[(2, 3)] == 2 and sap.count[(0, 3)] == 1
sap.check_invariant()
again = SweepAndPrune(boxes)
assert again.update([(0, 0, 4, 2), (3, 1, 6, 5), (5, 4, 8, 6), (7, 0, 8, 3)]) == 1
def test_sort_and_sweep_example():
assert sort_and_sweep(page_example()) == {(0, 1), (1, 2)}
assert sort_and_sweep(page_example(), axis=1) == {(0, 1), (1, 2)}
def test_edge_cases():
assert SweepAndPrune([]).overlapping_pairs() == set()
assert SweepAndPrune([(0, 0, 1, 1)]).overlapping_pairs() == set()
touching = [(0, 0, 1, 1), (1, 1, 2, 2)] # closed boxes that share a corner
assert SweepAndPrune(touching).overlapping_pairs() == {(0, 1)}
same = [(0, 0, 1, 1)] * 3
sap = SweepAndPrune(same)
assert sap.overlapping_pairs() == {(0, 1), (0, 2), (1, 2)}
assert sap.update(same) == 0
points = [(2, 2, 2, 2), (2, 2, 2, 2), (3, 2, 3, 2)] # degenerate boxes
sap = SweepAndPrune(points)
assert sap.overlapping_pairs() == {(0, 1)}
def random_boxes(rng, n, size):
out = []
for _ in range(n):
x, y = rng.randint(0, size), rng.randint(0, size)
w, h = rng.randint(0, 6), rng.randint(0, 6)
out.append((x, y, x + w, y + h))
return out
def test_random_moving_scenes_against_brute_force():
rng = random.Random(46)
for _ in range(60):
n = rng.randint(0, 25)
boxes = random_boxes(rng, n, 30)
sap = SweepAndPrune(boxes)
assert sap.overlapping_pairs() == brute(boxes)
assert sort_and_sweep(boxes) == brute(boxes)
vel = [(rng.randint(-2, 2), rng.randint(-2, 2)) for _ in range(n)]
for _ in range(10):
boxes = [(b[0] + v[0], b[1] + v[1], b[2] + v[0], b[3] + v[1]) for b, v in zip(boxes, vel)]
if rng.random() < 0.2: # sometimes one box jumps far
k = rng.randrange(n) if n else None
if k is not None:
b = random_boxes(rng, 1, 30)[0]
boxes[k] = b
expected_r = inversions(sap, boxes)
r = sap.update(boxes)
assert r == expected_r
assert sap.overlapping_pairs() == brute(boxes)
assert sort_and_sweep(boxes, axis=rng.randrange(2)) == brute(boxes)
sap.check_invariant()
def test_float_boxes():
rng = random.Random(7)
for _ in range(100):
boxes = []
for _ in range(12):
x, y = rng.uniform(0, 10), rng.uniform(0, 10)
boxes.append((x, y, x + rng.uniform(0, 3), y + rng.uniform(0, 3)))
sap = SweepAndPrune(boxes)
assert sap.overlapping_pairs() == brute(boxes)
boxes = [(b[0] + 0.5, b[1], b[2] + 0.5, b[3]) if i % 2 else b for i, b in enumerate(boxes)]
sap.update(boxes)
assert sap.overlapping_pairs() == brute(boxes)
History
Baraff (1992) used sorted lists of interval endpoints and the coherence between time steps for the box tests in his thesis on rigid body simulation. Cohen, Lin, Manocha and Ponamgi (1995) described sweep and prune in the I-COLLIDE system: they kept the endpoints of the boxes on each axis sorted, repaired the lists by insertion sort, and passed the pairs that overlap on all axes to the Lin-Canny closest feature test. Since then it is the broad phase of many physics engines, often with one sorted axis and a full sort per frame.
References
- Jonathan D. Cohen, Ming C. Lin, Dinesh Manocha and Madhav K. Ponamgi, I-COLLIDE, an interactive and exact collision detection system for large-scale environments, Proceedings of the 1995 Symposium on Interactive 3D Graphics, 189 to 196, the sweep and prune of bounding boxes with sorted endpoint lists, insertion sort between frames, and the use of coherence
- Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005, Chapter 7, Spatial Partitioning (the sort and sweep methods)
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 | W2 basic |
|
Tag 46M4XT Edit this page History Report an error Markdown