Broad Phase: Uniform Grid
The simplest broad phase is a uniform grid: cut the world into square cells, record which cells each object's bounding box covers, and only test objects that share a cell. Two objects in cells far apart are never even looked at. Grids are the go-to structure for many objects of similar size: bullets, particles, crowds, boids, the debris in a 2D shooter.
Building the grid
For each object, convert its AABB to a range of cell coordinates with floor(min / cellSize) and floor(max / cellSize), and add the object's index to every cell in that range. An object smaller than a cell covers at most 4 cells in 2D (8 in 3D).
Storing a full 2D array of cells wastes memory in big, mostly empty worlds, so many implementations use a spatial hash instead: hash the integer cell coordinates (cx, cy) to a key in a hash map. Only occupied cells take memory, and the world can be unbounded.
#include <iostream>
#include <iomanip>
#include <vector>
#include <unordered_map>
#include <cmath>
#include <cstdint>
struct Box { double minX, minY, maxX, maxY; };
int64_t cellKey(int cx, int cy) { return (int64_t(cx) << 32) ^ uint32_t(cy); } // pack two ints into one key
int main() {
const double cell = 4.0;
std::vector<Box> boxes = {
{1.0, 1.0, 2.5, 2.5}, // 0: inside cell (0,0)
{3.0, 3.0, 5.0, 5.0}, // 1: straddles four cells
{4.5, 0.5, 6.0, 2.0}, // 2: cell (1,0)
{9.0, 9.0, 10.0, 10.0}, // 3: far away, cell (2,2)
{-3.0, 1.0, -1.0, 2.0}, // 4: negative coordinates, cell (-1,0)
};
std::unordered_map<int64_t, std::vector<int>> grid;
for (int i = 0; i < (int)boxes.size(); i++) {
const Box& b = boxes[i];
int x0 = (int)std::floor(b.minX / cell), x1 = (int)std::floor(b.maxX / cell);
int y0 = (int)std::floor(b.minY / cell), y1 = (int)std::floor(b.maxY / cell);
std::cout << "box " << i << " covers cells x " << x0 << ".." << x1 << ", y " << y0 << ".." << y1 << "\n";
for (int cx = x0; cx <= x1; cx++)
for (int cy = y0; cy <= y1; cy++) grid[cellKey(cx, cy)].push_back(i);
}
std::cout << "occupied cells: " << grid.size() << "\n";
}box 0 covers cells x 0..0, y 0..0
box 1 covers cells x 0..1, y 0..1
box 2 covers cells x 1..1, y 0..0
box 3 covers cells x 2..2, y 2..2
box 4 covers cells x -1..-1, y 0..0
occupied cells: 6
Note std::floor, not a cast: (int)(-1.0 / 4.0) is 0, which would put box 4 in the same column as box 0. Casting truncates toward zero; the grid needs rounding toward minus infinity.
Finding pairs without duplicates
Now walk the occupied cells and test every pair inside each cell. A pair of boxes that share two cells would be reported twice, so the pairs need deduplication. Two common fixes:
- Collect pairs as
(min(i, j), max(i, j))in a set (simple, costs a hash insert per pair). - Report a pair only from one cell: the cell that contains the corner
max(a.min, b.min)of their overlap region. Each overlapping pair has exactly one such corner, so no set is needed.
This program builds a grid for 300 scattered boxes and compares the work against brute force, for several cell sizes:
#include <iostream>
#include <iomanip>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <cmath>
#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 Box { double minX, minY, maxX, maxY; };
bool overlap(const Box& a, const Box& b) {
return a.minX <= b.maxX && b.minX <= a.maxX && a.minY <= b.maxY && b.minY <= a.maxY;
}
int64_t key(int cx, int cy) { return (int64_t(cx) << 32) ^ uint32_t(cy); }
int main() {
Lcg g; g.seed(7);
std::vector<Box> boxes;
for (int i = 0; i < 300; i++) {
double x = g.next() * 200, y = g.next() * 200, s = 1 + g.next() * 3; // sizes 1..4
boxes.push_back({x, y, x + s, y + s});
}
long brute = 0, truePairs = 0;
for (size_t i = 0; i < boxes.size(); i++)
for (size_t j = i + 1; j < boxes.size(); j++) { brute++; if (overlap(boxes[i], boxes[j])) truePairs++; }
std::cout << "brute force: " << brute << " tests, " << truePairs << " overlapping pairs\n";
for (double cell : {1.0, 4.0, 8.0, 32.0, 200.0}) {
std::unordered_map<int64_t, std::vector<int>> grid;
for (int i = 0; i < (int)boxes.size(); i++) {
const Box& b = boxes[i];
for (int cx = (int)std::floor(b.minX / cell); cx <= (int)std::floor(b.maxX / cell); cx++)
for (int cy = (int)std::floor(b.minY / cell); cy <= (int)std::floor(b.maxY / cell); cy++)
grid[key(cx, cy)].push_back(i);
}
long tests = 0, found = 0;
for (auto& [k, list] : grid) {
int cx = int(k >> 32), cy = int(uint32_t(k));
for (size_t i = 0; i < list.size(); i++)
for (size_t j = i + 1; j < list.size(); j++) {
const Box &a = boxes[list[i]], &b = boxes[list[j]];
tests++;
if (!overlap(a, b)) continue;
// report only from the cell holding the overlap's min corner
double ox = std::max(a.minX, b.minX), oy = std::max(a.minY, b.minY);
if ((int)std::floor(ox / cell) == cx && (int)std::floor(oy / cell) == cy) found++;
}
}
std::cout << "cell " << std::setw(5) << std::setprecision(0) << std::fixed << cell
<< ": " << std::setw(5) << grid.size() << " cells, " << std::setw(5) << tests
<< " tests, " << found << " pairs\n";
}
}brute force: 44850 tests, 29 overlapping pairs
cell 1: 3610 cells, 190 tests, 29 pairs
cell 4: 672 cells, 130 tests, 29 pairs
cell 8: 362 cells, 211 tests, 29 pairs
cell 32: 49 cells, 1321 tests, 29 pairs
cell 200: 3 cells, 44877 tests, 29 pairs
Every cell size finds the same pairs as brute force; only the amount of work changes. The table shows the classic trade-off:
- Cells much smaller than the objects (size 1): the pair tests are few, but each box covers up to 25 cells, so the grid needs 3,610 cell entries and the same overlapping pair is tested again in every cell it shares. Building the grid becomes the cost.
- Cells much larger than the objects (size 200 is the whole world): almost everything lands in one cell and you are back to brute force. It is even slightly worse here (44,877 tests), because boxes near the far edge also spill into a neighbouring cell and get tested twice.
- The sweet spot is a cell size around the size of a typical object (here 4): each object covers 1 to 4 cells and each cell holds only its close neighbours. 130 tests instead of 44,850.
Tip: A rule of thumb is a cell size of about twice the typical object size. If a few objects are much larger than the rest (a boss, a long wall), keep them out of the grid and test them separately, or use a second, coarser grid for them. One huge object in a fine grid covers hundreds of cells.
Grids in a moving world
Real games rebuild or update the grid every physics step. Two practical points:
- Rebuild from scratch when most objects move (particles, bullets). Clearing and refilling flat arrays is fast and simple. A counting-sort layout (count objects per cell, prefix-sum, then fill) avoids per-cell vectors entirely.
- Update incrementally when most objects are at rest: only move an object to new cells when its cell range changes.
Grids are weak when sizes vary a lot or the world is mostly empty space with dense clusters. That is where sweep and prune and the BVH do better. Grids are also handy outside physics: AI neighbour searches, "which enemies are near the explosion", fog-of-war updates.
Test yourself
Why compute cell coordinates with floor(x / cellSize) instead of (int)(x / cellSize)?
- floor is faster
- A cast truncates toward zero, so cells -1 and 0 would merge for negative coordinates
- The cast doesn't compile for doubles
- floor rounds to the nearest cell
Two boxes overlap and both cover the same two cells. Without deduplication, what happens?
- The pair is missed
- The pair is reported twice
- The grid crashes
- Nothing; grids never duplicate pairs
What happens to a uniform grid when the cell is as large as the whole world?
- It becomes optimal
- Every object lands in one cell and it degrades to brute force
- It finds fewer pairs
- It uses no memory