TExcelTAD
Home › Game Physics & Animation › Broad Phase: Sweep and Prune

Broad Phase: Sweep and Prune

Two AABBs can only overlap if their intervals overlap on every axis. Sweep and prune (SAP, also called sort and sweep) uses that on one axis: sort all boxes by their minX, then sweep from left to right. A box only needs to be tested against boxes whose x-interval is still "open" when it starts. Everything that ended earlier is pruned without a test.

It handles objects of very different sizes better than a uniform grid, needs no cell size, and has one more trick: from one physics step to the next, objects barely move, so the sorted order barely changes. Re-sorting an almost-sorted list is nearly free.

The sweep

  1. Sort boxes by minX.
  2. Keep an active list of boxes whose interval may still overlap.
  3. For each box in order: drop every active box whose maxX is less than this box's minX (they ended before this one started), test this box against the rest on the y axis (and z in 3D), then add it to the active list.
cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <string>

struct Box { std::string name; double minX, minY, maxX, maxY; };

int main() {
    std::vector<Box> boxes = {
        {"A", 0, 0, 3, 2}, {"B", 2, 1, 5, 3}, {"C", 4, 5, 6, 7},
        {"D", 7, 0, 9, 2}, {"E", 8, 1, 12, 2}, {"F", 1, 6, 2, 8},
    };
    std::sort(boxes.begin(), boxes.end(), [](const Box& a, const Box& b) { return a.minX < b.minX; });
    std::vector<const Box*> active;
    int tests = 0;
    for (const Box& b : boxes) {
        // prune: remove active boxes that ended before b starts
        active.erase(std::remove_if(active.begin(), active.end(),
                     [&](const Box* a) { return a->maxX < b.minX; }), active.end());
        std::cout << b.name << " starts at x=" << b.minX << ", active:";
        for (const Box* a : active) std::cout << " " << a->name;
        std::cout << "\n";
        for (const Box* a : active) {
            tests++;                                                   // x already overlaps; check y
            if (a->minY <= b.maxY && b.minY <= a->maxY) std::cout << "   pair " << a->name << "-" << b.name << "\n";
        }
        active.push_back(&b);
    }
    std::cout << "y tests: " << tests << " (brute force: " << boxes.size() * (boxes.size() - 1) / 2 << ")\n";
}
A starts at x=0, active:
F starts at x=1, active: A
B starts at x=2, active: A F
   pair A-B
C starts at x=4, active: B
D starts at x=7, active:
E starts at x=8, active: D
   pair D-E
y tests: 5 (brute force: 15)

Follow box C: when it starts at x = 4, box A (ended at 3) and box F (ended at 2) have already been pruned, so C is only compared with B. C and B overlap on x but not on y, so the test fails. F and C overlap on y, but their x-intervals don't touch, and SAP never had to look at them as a pair.

Choosing the axis

SAP works best when objects are spread out along the sweep axis. A side-scrolling level is wide, so sweeping x is good. A tall vertical shaft sorted on x would put every object in the active list at once, and SAP degrades to brute force. Common fixes:

  • pick the axis with the largest variance of box centres (recompute every few frames);
  • in 3D, sort on all three axes and only report pairs that overlap on all of them (the original "SAP with three lists").

Temporal coherence: insertion sort

std::sort costs O(n log n) from scratch. But a physics step moves objects by a tiny amount, so last frame's order is almost correct. Insertion sort on an almost-sorted array runs in O(n + k), where k is the number of swaps, that is, the number of objects that changed order. This program sorts once, moves the objects a little each step, and counts the swaps:

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <vector>
#include <cstdint>

struct Lcg {
    uint32_t s;
    void seed(uint32_t v) { s = v; }
    double next() { s = s * 1664525u + 1013904223u; return (s >> 8) / 16777216.0; }
};
struct Body { double minX, velX; };

long insertionSort(std::vector<Body>& v) {
    long swaps = 0;
    for (size_t i = 1; i < v.size(); i++)
        for (size_t j = i; j > 0 && v[j - 1].minX > v[j].minX; j--) { std::swap(v[j - 1], v[j]); swaps++; }
    return swaps;
}

int main() {
    Lcg g; g.seed(3);
    std::vector<Body> bodies;
    for (int i = 0; i < 1000; i++) bodies.push_back({g.next() * 1000, (g.next() - 0.5) * 20});  // speed -10..10
    std::cout << "first sort (unsorted input): " << insertionSort(bodies) << " swaps\n";
    const double dt = 1.0 / 60;
    for (int step = 1; step <= 5; step++) {
        for (Body& b : bodies) b.minX += b.velX * dt;
        std::cout << "step " << step << ": " << insertionSort(bodies) << " swaps\n";
    }
}
first sort (unsorted input): 253322 swaps
step 1: 56 swaps
step 2: 52 swaps
step 3: 48 swaps
step 4: 57 swaps
step 5: 38 swaps

The first sort of 1,000 shuffled values needs about n²/4 swaps. After that, each step needs only a handful: the few neighbours that overtook each other. That is why SAP has long been a favourite of physics engines with mostly coherent motion; PhysX's classic broad phases are sweep-and-prune variants.

Note: Coherence breaks when objects teleport (respawns, level streaming) or when many objects move very fast. Then a full re-sort (or a BVH rebuild) is cheaper than thousands of swaps.

Endpoints and incremental pair updates

Production SAP implementations don't keep one entry per box. They store each box's two endpoints (min and max) in one sorted array. During the insertion sort, each swap of two endpoints means one interval started or stopped overlapping another on that axis:

Swap Meaning
a min moves left past a max the intervals start to overlap: maybe add the pair (check the other axes)
a min moves right past a max the intervals stop overlapping: remove the pair
min past min, or max past max no change in overlap

So the pair list is updated incrementally by the swaps themselves, and objects at rest cost nothing. Pairs persist from step to step, which also helps the solver reuse contact data (warm starting, see stacking).

Test yourself

During the sweep, when is an active box removed from the active list?

  1. When it overlaps the current box
  2. When its maxX is less than the current box's minX
  3. After a fixed number of steps
  4. When the list is full

Why is insertion sort a good fit for sweep and prune in a physics step?

  1. It is O(n log n) in the worst case
  2. The order changes little between steps, and insertion sort is near-linear on almost-sorted data
  3. It uses no comparisons
  4. It works only on integers

When does sweeping along the x axis perform badly?

  1. When the level is wide and flat
  2. When most objects overlap on x, for example a tall vertical shaft
  3. When boxes are small
  4. When objects are at rest