跳到內容

aiquadtreejs — 空間分割

aiquadtreejs 是一個專為 per-frame rebuild 設計的 2D quadtree。它只做廣泛相(broadphase):插入 AABB、查詢候選清單、由呼叫方做精確碰撞判斷。設計目標是 PixiJS 遊戲 500–10,000 個活躍 entity 的規模。

終端機視窗
npm install aiquadtreejs
import { createQuadtree, type AABB } from "aiquadtreejs";
type Body = { id: number } & AABB;
// 1. 建立 quadtree(通常建一次就好)
const qt = createQuadtree<Body>({
bounds: { x: 0, y: 0, width: 800, height: 600 },
maxObjects: 10, // 一個節點超過這個數量才分裂
maxLevels: 4, // 最大深度
});
// 2. 每幀:clear + 重新 insert
function rebuild(entities: Body[]) {
qt.clear();
for (const e of entities) qt.insert(e);
}
// 精確 AABB 重疊判斷,右開區間:x + width、y + height 不含
function 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. 查詢:broadphase 取候選,再做精確判斷
function checkCollisions(player: Body) {
const region: AABB = {
x: player.x - 32,
y: player.y - 32,
width: 64,
height: 64,
};
const candidates = qt.retrieve(region); // 已去重的候選陣列
return candidates.filter((c) => c.id !== player.id && overlaps(c, player));
}

彈幕遊戲的子彈、RTS 的單位群都要在每幀找出可能碰撞的配對,逐對檢查需要 n² 次。下方示範每幀重建 quadtree,玩家方塊的候選以強調色標示,精確判斷後真正重疊的以橘色標示,狀態列即時比較全場的候選配對數與 n² 暴力配對數。

互動示範載入中…

BroadphaseArena:彈幕遊戲的碰撞粗篩
示範原始碼
src/demos/quadtree-broadphase.ts
/**
* 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 it
const MAX_LEVELS = 4; // ...but never deeper than this
const BULLET_COUNT = 220;
const MAX_STEP_MS = 50; // clamp long frames (tab switches, hiccups) so bodies do not jump
const 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 });
},
};
}

追蹤 entity 移動到哪個 leaf 的做法理論上省 re-insert,但實作容易出錯。clear() + 全量重新 insert() 在 4 層深度的樹裡很快,而且邏輯清楚。這是 aiquadtreejs 的核心取捨。

x + width、y + height 是開區間(exclusive),與 PixiJS getBounds() 的慣例一致。

節點保存共用的邊界:右、下子節點直接沿用父節點的 x + width / y + height,因此 x: -0.3, width: 2.4 這類小數 bounds 的邊緣物件也不會漏掉。只要物件在 bounds 內且與查詢範圍重疊,就保證出現在結果中。插入的物件以參照保存,節點分裂時會重新讀取,在下次 clear() 前不要移動它們。

  • createQuadtree() 缺少 options 物件或 bounds 時丟出 QuadtreeError,不再是解構時產生的 TypeError。
  • 非有限數值的座標、負的 width / height,以及不是陣列的 retrieveInto() target 都會丟出 QuadtreeError。
  • 所有 QuadtreeError 訊息都以 aiquadtreejs: 開頭,請以 error class 加 regex 比對,不要比對完整字串。dispose() 後除了 dispose() 本身,其他方法都會丟出 QuadtreeDisposedError。
  • 精確碰撞:broadphase 只給候選,caller 負責 AABB/圓形/pixel 精確判斷
  • 3D / octree / R-tree / KD-tree:不在 2D 簡單 AABB 的設計範疇
  • Circle / Line primitives:只支援矩形 AABB
  • 移動追蹤:用 clear() + re-insert() 取代
  • 與 aiecsjs 搭配:ECS entity 的 SoA Position 欄位直接組成 AABB 插入 quadtree,不需要另外建物件
  • 與 aipooljs 搭配:Pool 管理子彈物件,quadtree 做空間查詢決定哪些要精確判斷
  • 獨立使用:遊戲 enemy AI 視野查詢、區域事件觸發等