Skip to content

broadphase

FreeBodyEngine.core.physics.broadphase #

Broad-phase collision pruning for the rigid-body physics system.

Checking every pair of bodies in the scene with the real (comparatively expensive) narrow-phase test in contact.py doesn't scale - a SpatialHash buckets bodies by their AABB into a uniform grid first, so only pairs that actually share a cell (i.e. could plausibly be touching) ever reach narrow-phase at all.

SpatialHash(cell_size=4.0) #

Buckets AABBs into a uniform grid of cell_size-sized cells. A body spanning multiple cells is inserted into every one its AABB touches. Rebuilt from scratch each physics step rather than incrementally maintained - bodies move only a little per step, but rebuilding is far simpler than tracking cell membership changes, and for the body counts an actual 2D game has (tens to low hundreds, not thousands), cheap enough to just redo every time.

cell_size should be roughly the size of a typical body in the scene - too small and most bodies span many cells (inflating the pair count with redundant lookups), too large and unrelated bodies on opposite sides of the world end up sharing a cell.

cell_size = cell_size instance-attribute #

cells = {} instance-attribute #

clear() #

Empties every cell, ready for the next step's insert() calls.

find_pairs() #

Returns the set of candidate item pairs that share at least one cell - deduplicated (a pair spanning several shared cells is only reported once) and order-independent (keyed by id() so the same pair is never reported as both (a, b) and (b, a)). Still just candidates - the real narrow-phase test still has to confirm each pair actually overlaps.

insert(item, aabb_min, aabb_max) #

Adds item to every cell its (aabb_min, aabb_max) box overlaps.