aiquadtreejs: Spatial Partitioning
aiquadtreejs is a 2D quadtree built specifically for per-frame rebuilds. It only does the broadphase: insert AABBs, query a candidate list, and let the caller do the precise collision test. The design target is PixiJS games with 500–10,000 active entities.
Install
Section titled “Install”npm install aiquadtreejsQuick Start
Section titled “Quick Start”import { createQuadtree, type AABB } from "aiquadtreejs";
type Body = { id: number } & AABB;
// 1. Create the quadtree (usually once is enough)const qt = createQuadtree<Body>({ bounds: { x: 0, y: 0, width: 800, height: 600 }, maxObjects: 10, // A node splits only when it holds more than this many objects maxLevels: 4, // Maximum depth});
// 2. Every frame: clear + insert againfunction rebuild(entities: Body[]) { qt.clear(); for (const e of entities) qt.insert(e);}
// Exact AABB overlap test, right-open: x + width and y + height are exclusivefunction overlaps(a: AABB, b: AABB): boolean { return ( a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y );}
// 3. Query: get candidates from the broadphase, then do the precise testfunction checkCollisions(player: Body) { const region: AABB = { x: player.x - 32, y: player.y - 32, width: 64, height: 64, }; const candidates = qt.retrieve(region); // Deduplicated candidate array return candidates.filter((c) => c.id !== player.id && overlaps(c, player));}Interactive Demo
Section titled “Interactive Demo”Bullet-hell shooters and RTS unit crowds must find every potentially colliding pair each frame, and checking every pair costs n². The demo below rebuilds the quadtree every frame: the player’s candidates are drawn in the accent colour, the ones that truly overlap after the exact test in orange, and the status line compares the arena’s candidate pairs with the n² brute-force pair checks live.
Demo source
/** * BroadphaseArena: bullet-hell collision broadphase with aiquadtreejs. * * About 220 bullets and one player box bounce around an 800 x 400 arena. Every frame: * 1. rebuild the quadtree from scratch (clear + insert), which is how aiquadtreejs is meant to be used; * 2. ask the tree for each body's candidates and count the pair checks that are left; * 3. run the exact AABB test on the player's candidates to find its real overlaps; * 4. draw the node subdivisions, the leaves the player touches, its candidates and its overlaps. * * The readout compares the quadtree's candidate pairs with the n(n - 1) / 2 pair checks * of a brute-force double loop. */import { createQuadtree, type AABB } from 'aiquadtreejs';import { Container, Graphics, type Application } from 'pixi.js';import type { DemoContext, DemoHandle } from './types';
const ARENA: AABB = { x: 0, y: 0, width: 800, height: 400 };const MAX_OBJECTS = 8; // a node splits once more than this many bodies overlap itconst MAX_LEVELS = 4; // ...but never deeper than thisconst BULLET_COUNT = 220;const MAX_STEP_MS = 50; // clamp long frames (tab switches, hiccups) so bodies do not jumpconst REPORT_EVERY_MS = 250; // the text readout does not need 60 updates a second
interface Body extends AABB { id: number; vx: number; // px per second vy: number;}
/** Exact AABB test (the narrowphase). Right-open like aiquadtreejs: a box covers [x, x + width). */function overlaps(a: AABB, b: AABB): boolean { return a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;}
function randomBetween(min: number, max: number): number { return min + Math.random() * (max - min);}
function createBody(id: number, size: number, speed: number): Body { const angle = Math.random() * Math.PI * 2; return { id, x: randomBetween(0, ARENA.width - size), y: randomBetween(0, ARENA.height - size), width: size, height: size, vx: Math.cos(angle) * speed, vy: Math.sin(angle) * speed, };}
/** Moves a body and bounces it off the walls, so it always stays inside the tree bounds. */function move(body: Body, seconds: number): void { body.x += body.vx * seconds; body.y += body.vy * seconds; if (body.x < 0 || body.x + body.width > ARENA.width) { body.vx = -body.vx; body.x = Math.min(Math.max(body.x, 0), ARENA.width - body.width); } if (body.y < 0 || body.y + body.height > ARENA.height) { body.vy = -body.vy; body.y = Math.min(Math.max(body.y, 0), ARENA.height - body.height); }}
/** * aiquadtreejs keeps its nodes private, so for drawing only we re-derive the leaves with the * documented rule: a node splits at its midpoints once more than MAX_OBJECTS bodies overlap it, * down to MAX_LEVELS. All collision queries go through the real tree. */function collectLeaves(node: AABB, bodies: Body[], level: number, leaves: AABB[]): void { if (bodies.length <= MAX_OBJECTS || level >= MAX_LEVELS) { leaves.push(node); return; } const width = node.width / 2; const height = node.height / 2; const children: AABB[] = [ { x: node.x, y: node.y, width, height }, { x: node.x + width, y: node.y, width, height }, { x: node.x, y: node.y + height, width, height }, { x: node.x + width, y: node.y + height, width, height }, ]; for (const child of children) { collectLeaves(child, bodies.filter((body) => overlaps(body, child)), level + 1, leaves); }}
/** Colours come from the site's CSS tokens, so the demo follows the light and dark themes. */function readColors(cssColor: DemoContext['cssColor']) { return { grid: cssColor('--sl-color-gray-4'), bullet: cssColor('--sl-color-gray-3'), candidate: cssColor('--sl-color-accent'), overlap: cssColor('--sl-color-orange'), player: cssColor('--sl-color-text'), };}
interface Stats { candidates: number; overlaps: number; pairChecks: string; bruteForce: string; percent: string;}
const READOUT = { 'zh-TW': (s: Stats) => `玩家:${s.candidates} 個候選、${s.overlaps} 個實際重疊|全場:${s.pairChecks} 次候選配對 vs ${s.bruteForce} 次 n² 配對檢查(${s.percent}%)`, en: (s: Stats) => `Player: candidates ${s.candidates}, overlaps ${s.overlaps} | Arena: candidate pairs ${s.pairChecks} vs n² pair checks ${s.bruteForce} (${s.percent}%)`,};
export function mount(app: Application, { lang, setStatus, cssColor }: DemoContext): DemoHandle { const tree = createQuadtree<Body>({ bounds: ARENA, maxObjects: MAX_OBJECTS, maxLevels: MAX_LEVELS });
const player = createBody(0, 36, 70); const bodies: Body[] = [player]; for (let id = 1; id <= BULLET_COUNT; id++) { bodies.push(createBody(id, randomBetween(4, 12), randomBetween(80, 220))); } const bruteForcePairs = (bodies.length * (bodies.length - 1)) / 2;
// Scene: one container scaled to fit the canvas, with a grid layer under a box layer. const arena = new Container(); const grid = new Graphics(); const boxes = new Graphics(); arena.addChild(grid, boxes); app.stage.addChild(arena);
const fit = () => { const scale = Math.min(app.screen.width / ARENA.width, app.screen.height / ARENA.height); arena.scale.set(scale); arena.position.set( (app.screen.width - ARENA.width * scale) / 2, (app.screen.height - ARENA.height * scale) / 2, ); }; fit(); app.renderer.on('resize', fit);
let colors = readColors(cssColor); const scratch: Body[] = []; // reused by retrieveInto(), which clears it before writing const candidates: Body[] = []; let sinceReport = 0;
/** Rebuilds the tree, runs the broadphase, redraws, and optionally updates the readout. */ function frame(report: boolean): void { // 1. Per-frame rebuild. The tree stores references, so rebuild after every move. tree.clear(); for (const body of bodies) tree.insert(body);
// 2. Broadphase for the whole arena. Keeping only other.id > body.id visits each // unordered pair once, exactly like a brute-force double loop would. let pairChecks = 0; for (const body of bodies) { for (const other of tree.retrieveInto(body, scratch)) { if (other.id > body.id) pairChecks++; // a game would run overlaps(body, other) here } }
// 3. The player: broadphase candidates versus exact overlaps. tree.retrieveInto(player, candidates); const candidateSet = new Set(candidates); const hits = candidates.filter((body) => body !== player && overlaps(body, player));
// 4. Draw. Leaves the player touches are tinted: their bodies are exactly its candidates. const leaves: AABB[] = []; collectLeaves(ARENA, bodies, 0, leaves); grid.clear(); for (const leaf of leaves) { if (overlaps(leaf, player)) { grid.rect(leaf.x, leaf.y, leaf.width, leaf.height).fill({ color: colors.candidate, alpha: 0.12 }); } } for (const leaf of leaves) grid.rect(leaf.x, leaf.y, leaf.width, leaf.height); grid.stroke({ width: 1, color: colors.grid, alpha: 0.6 });
boxes.clear(); for (const body of bodies) { if (!candidateSet.has(body)) boxes.rect(body.x, body.y, body.width, body.height); } boxes.fill({ color: colors.bullet, alpha: 0.8 }); for (const body of candidates) { if (body !== player && !hits.includes(body)) boxes.rect(body.x, body.y, body.width, body.height); } boxes.fill({ color: colors.candidate }); for (const body of hits) boxes.rect(body.x, body.y, body.width, body.height); boxes.fill({ color: colors.overlap }); boxes .rect(player.x, player.y, player.width, player.height) .fill({ color: colors.player, alpha: 0.25 }) .stroke({ width: 2, color: colors.player });
if (report) { const format = (n: number) => n.toLocaleString(lang); setStatus( READOUT[lang]({ candidates: candidates.length - 1, // minus the player itself overlaps: hits.length, pairChecks: format(pairChecks), bruteForce: format(bruteForcePairs), percent: ((pairChecks / bruteForcePairs) * 100).toFixed(1), }), ); } }
frame(true); // the first frame is drawn even if the demo never plays (reduced motion)
return { update(deltaMS) { const seconds = Math.min(deltaMS, MAX_STEP_MS) / 1000; for (const body of bodies) move(body, seconds); sinceReport += deltaMS; const report = sinceReport >= REPORT_EVERY_MS; if (report) sinceReport = 0; frame(report); }, onThemeChange() { colors = readColors(cssColor); frame(true); }, dispose() { app.renderer.off('resize', fit); tree.dispose(); arena.destroy({ children: true }); }, };}Per-Frame Rebuild Is Deliberate
Section titled “Per-Frame Rebuild Is Deliberate”Tracking which leaf an entity moved to would in theory save re-inserts, but it is easy to get wrong. clear() plus a full re-insert() is fast in a tree 4 levels deep, and the logic is clear. This is the core trade-off of aiquadtreejs.
AABB Coordinate Semantics
Section titled “AABB Coordinate Semantics”x + width and y + height are exclusive (an open interval), consistent with the PixiJS getBounds() convention.
Nodes store shared boundaries: the right and bottom child nodes reuse the parent’s x + width / y + height directly, so an object on the edge of fractional bounds such as x: -0.3, width: 2.4 is not missed either. As long as an object is inside bounds and overlaps the query region, it is guaranteed to appear in the result. Inserted objects are stored by reference and re-read when a node splits, so do not move them before the next clear().
Errors
Section titled “Errors”createQuadtree()throwsQuadtreeErrorwhen the options object orboundsis missing, instead of theTypeErrorpreviously produced by destructuring.- Non-finite coordinates, negative width / height, and a
retrieveInto()target that is not an array all throwQuadtreeError. - Every
QuadtreeErrormessage starts withaiquadtreejs:, so match on the error class plus a regex, not on the full string. Afterdispose(), every method exceptdispose()itself throwsQuadtreeDisposedError.
Deliberately Excluded Features
Section titled “Deliberately Excluded Features”- Precise collision: the broadphase only gives candidates; the caller does the AABB/circle/pixel precise test
- 3D / octree / R-tree / KD-tree: outside the design scope of simple 2D AABBs
- Circle / Line primitives: only rectangular AABBs are supported
- Movement tracking: replaced by
clear()+ re-insert()
Common Pairings
Section titled “Common Pairings”- With
aiecsjs: an entity’s SoA Position columns form the AABB inserted into the quadtree directly, with no separate objects needed - With
aipooljs: the Pool manages bullet objects and the quadtree does the spatial query that decides which ones need a precise test - Standalone: game enemy AI vision queries, area event triggers and so on