@flare-engine/physics 0.4.17 → 0.4.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -10,6 +10,184 @@ function createCollider(shape, opts) {
10
10
  mask: opts?.mask ?? 4294967295
11
11
  };
12
12
  }
13
+ // src/cells.ts
14
+ const CELL = 64;
15
+ const KEY_RANGE = 65536;
16
+ const KEY_OFFSET = 32768;
17
+ function cellKey(cx, cy) {
18
+ return (cx + KEY_OFFSET) * KEY_RANGE + (cy + KEY_OFFSET);
19
+ }
20
+ const MIN_CELL = -32768;
21
+ const MAX_CELL = 32767;
22
+ function clampCell(c) {
23
+ if (c > MAX_CELL) return MAX_CELL;
24
+ if (c < MIN_CELL) return MIN_CELL;
25
+ return c;
26
+ }
27
+ /** Inclusive first cell, clamped, that contains world coordinate `v`. */
28
+ function cellMin(v) {
29
+ return clampCell(Math.floor(v / CELL));
30
+ }
31
+ /**
32
+ * Inclusive last cell, clamped, for a range ending at world coordinate `v`.
33
+ * Exclusive-end: a coord falling exactly on a cell boundary is NOT part of the
34
+ * adjacent cell — matches the strict-inequality overlap semantics of a query.
35
+ */
36
+ function cellMax(v) {
37
+ return clampCell(Math.ceil(v / CELL) - 1);
38
+ }
39
+ // src/collision-grid.ts
40
+ function createCollisionGrid() {
41
+ return {
42
+ _cells: /* @__PURE__ */ new Map(),
43
+ freeGroups: [],
44
+ gen: 0,
45
+ size: 0
46
+ };
47
+ }
48
+ function groupFor(grid, cell, layer, mask) {
49
+ const groups = cell.groups;
50
+ for (let g = 0; g < groups.length; g++) {
51
+ const group = groups[g];
52
+ if (group.layer === layer && group.mask === mask) return group;
53
+ }
54
+ let group = grid.freeGroups.pop();
55
+ if (group === void 0) group = {
56
+ layer,
57
+ mask,
58
+ index: groups.length,
59
+ items: []
60
+ };
61
+ else {
62
+ group.layer = layer;
63
+ group.mask = mask;
64
+ group.index = groups.length;
65
+ }
66
+ groups.push(group);
67
+ return group;
68
+ }
69
+ function link(grid, e) {
70
+ const { cxMin, cxMax, cyMin, cyMax } = e;
71
+ let n = 0;
72
+ for (let cx = cxMin; cx <= cxMax; cx++) for (let cy = cyMin; cy <= cyMax; cy++) {
73
+ const k = cellKey(cx, cy);
74
+ let cell = grid._cells.get(k);
75
+ if (cell === void 0) {
76
+ cell = {
77
+ cx,
78
+ cy,
79
+ groups: []
80
+ };
81
+ grid._cells.set(k, cell);
82
+ }
83
+ const group = groupFor(grid, cell, e.layer, e.mask);
84
+ e.cells[n] = cell;
85
+ e.groups[n] = group;
86
+ e.at[n] = group.items.length;
87
+ n++;
88
+ group.items.push(e);
89
+ }
90
+ e.cellCount = n;
91
+ }
92
+ /**
93
+ * Take an entry out of every cell it is linked into. O(1) per cell: the last
94
+ * entry of the group takes the vacated position, and its own record of where
95
+ * it sits in that cell is corrected to match. A group left empty leaves its
96
+ * cell the same way and goes back to the free list.
97
+ *
98
+ * `layer` and `mask` decide which group holds an entry, so they may only be
99
+ * rewritten while it is unlinked; follow with `gridRelink`.
100
+ */
101
+ function gridUnlink(grid, e) {
102
+ for (let n = 0; n < e.cellCount; n++) {
103
+ const cell = e.cells[n];
104
+ const group = e.groups[n];
105
+ const items = group.items;
106
+ const last = items.pop();
107
+ if (last !== e) {
108
+ const i = e.at[n];
109
+ items[i] = last;
110
+ last.at[(cell.cx - last.cxMin) * (last.cyMax - last.cyMin + 1) + (cell.cy - last.cyMin)] = i;
111
+ } else if (items.length === 0) {
112
+ const lastGroup = cell.groups.pop();
113
+ if (lastGroup !== group) {
114
+ cell.groups[group.index] = lastGroup;
115
+ lastGroup.index = group.index;
116
+ }
117
+ grid.freeGroups.push(group);
118
+ }
119
+ }
120
+ e.cellCount = 0;
121
+ }
122
+ function setBounds(e, minX, minY, maxX, maxY) {
123
+ e.minX = minX;
124
+ e.minY = minY;
125
+ e.maxX = maxX;
126
+ e.maxY = maxY;
127
+ e.cxMin = cellMin(minX);
128
+ e.cxMax = cellMax(maxX);
129
+ e.cyMin = cellMin(minY);
130
+ e.cyMax = cellMax(maxY);
131
+ }
132
+ /** Link a new entry at the given bounds. */
133
+ function gridInsert(grid, e, minX, minY, maxX, maxY) {
134
+ grid.size++;
135
+ setBounds(e, minX, minY, maxX, maxY);
136
+ link(grid, e);
137
+ }
138
+ /** Link an entry `gridUnlink` took out, at the given bounds. */
139
+ function gridRelink(grid, e, minX, minY, maxX, maxY) {
140
+ setBounds(e, minX, minY, maxX, maxY);
141
+ link(grid, e);
142
+ }
143
+ /** Move an entry whose layer and mask are unchanged. Touches no bucket while it stays in the same cells. */
144
+ function gridMove(grid, e, minX, minY, maxX, maxY) {
145
+ const cxMin = cellMin(minX);
146
+ const cxMax = cellMax(maxX);
147
+ const cyMin = cellMin(minY);
148
+ const cyMax = cellMax(maxY);
149
+ if (cxMin === e.cxMin && cxMax === e.cxMax && cyMin === e.cyMin && cyMax === e.cyMax) {
150
+ e.minX = minX;
151
+ e.minY = minY;
152
+ e.maxX = maxX;
153
+ e.maxY = maxY;
154
+ return;
155
+ }
156
+ gridUnlink(grid, e);
157
+ setBounds(e, minX, minY, maxX, maxY);
158
+ link(grid, e);
159
+ }
160
+ function gridRemove(grid, e) {
161
+ gridUnlink(grid, e);
162
+ grid.size--;
163
+ }
164
+ function gridClear(grid) {
165
+ grid._cells.clear();
166
+ grid.freeGroups.length = 0;
167
+ grid.size = 0;
168
+ }
169
+ /** Append every entry whose bounds overlap the rect to `out`, each once. Order is unspecified. */
170
+ function gridQuery(grid, minX, minY, maxX, maxY, out) {
171
+ const gen = ++grid.gen;
172
+ const cxMin = cellMin(minX);
173
+ const cxMax = cellMax(maxX);
174
+ const cyMin = cellMin(minY);
175
+ const cyMax = cellMax(maxY);
176
+ for (let cx = cxMin; cx <= cxMax; cx++) for (let cy = cyMin; cy <= cyMax; cy++) {
177
+ const cell = grid._cells.get(cellKey(cx, cy));
178
+ if (cell === void 0) continue;
179
+ const groups = cell.groups;
180
+ for (let g = 0; g < groups.length; g++) {
181
+ const items = groups[g].items;
182
+ for (let i = 0; i < items.length; i++) {
183
+ const e = items[i];
184
+ if (e.stamp === gen) continue;
185
+ e.stamp = gen;
186
+ if (e.maxX > minX && e.minX < maxX && e.maxY > minY && e.minY < maxY) out.push(e);
187
+ }
188
+ }
189
+ }
190
+ }
13
191
  // src/raycast.ts
14
192
  /** Scratch record `raycast()` hands to `rayVsShapeInto` per candidate. */
15
193
  const scratchHit = {
@@ -29,6 +207,13 @@ const scratchHit = {
29
207
  *
30
208
  * The returned hit is a fresh object — the caller may keep it; later calls do
31
209
  * not overwrite it. Among targets at equal distance the first in `targets` wins.
210
+ *
211
+ * A ray that starts inside a collider hits that collider at its exit
212
+ * distance, not at 0. The hit's `normal` is then the outward normal of the
213
+ * face the ray entered through behind its origin for a box, and the outward
214
+ * normal at the exit point for a circle. To skip the collider a ray starts in,
215
+ * leave it out of `targets`, or start the ray just past its edge: a ray that
216
+ * starts exactly on the edge still hits it, at distance 0.
32
217
  * @param ox Ray origin X
33
218
  * @param oy Ray origin Y
34
219
  * @param dx Ray direction X (should be normalized)
@@ -328,153 +513,6 @@ function aabbCircleOverlap(ax, ay, ahw, ahh, cx, cy, cr, out, flip) {
328
513
  out.depth = depth + cr;
329
514
  return out;
330
515
  }
331
- // src/spatial-index.ts
332
- const CELL = 64;
333
- const KEY_RANGE = 65536;
334
- const KEY_OFFSET = 32768;
335
- function _key(cx, cy) {
336
- return (cx + KEY_OFFSET) * KEY_RANGE + (cy + KEY_OFFSET);
337
- }
338
- function _cMin(v) {
339
- return Math.floor(v / CELL);
340
- }
341
- function _cMax(v) {
342
- return Math.ceil(v / CELL) - 1;
343
- }
344
- const MIN_CELL = -32768;
345
- const MAX_CELL = 32767;
346
- function _clampCell(c) {
347
- if (c > MAX_CELL) return MAX_CELL;
348
- if (c < MIN_CELL) return MIN_CELL;
349
- return c;
350
- }
351
- /**
352
- * Uniform spatial-hash broadphase.
353
- * `insert`, `remove`, and `update` are O(cells touched) — O(1) for typical entities.
354
- * `query` walks only the cells overlapping the given rect; result order is unspecified.
355
- * Zero-alloc in the query hot-path: duplicate suppression uses a monotone stamp counter,
356
- * not a per-call Set.
357
- */
358
- var SpatialIndex = class {
359
- _data = [];
360
- _slots = /* @__PURE__ */ new Map();
361
- _cells = /* @__PURE__ */ new Map();
362
- _gen = 0;
363
- /** Number of items in the index. */
364
- get size() {
365
- return this._data.length;
366
- }
367
- /**
368
- * Insert an item with a bounding rect. Inserting an item already in the index
369
- * replaces its bounds (upsert) — same as `update`.
370
- */
371
- insert(item, bounds) {
372
- if (this._slots.has(item)) {
373
- this.update(item, bounds);
374
- return;
375
- }
376
- const entry = {
377
- item,
378
- minX: bounds.x,
379
- minY: bounds.y,
380
- maxX: bounds.x + bounds.width,
381
- maxY: bounds.y + bounds.height,
382
- _stamp: 0
383
- };
384
- this._slots.set(item, this._data.length);
385
- this._data.push(entry);
386
- this._link(entry);
387
- }
388
- /** Remove an item. Returns false when the item was not present. */
389
- remove(item) {
390
- const slot = this._slots.get(item);
391
- if (slot === void 0) return false;
392
- const entry = this._data[slot];
393
- this._unlink(entry);
394
- this._slots.delete(item);
395
- const last = this._data.pop();
396
- if (slot < this._data.length) {
397
- this._data[slot] = last;
398
- this._slots.set(last.item, slot);
399
- }
400
- return true;
401
- }
402
- /** Update the bounds for an existing item. No-op when the item is absent. */
403
- update(item, bounds) {
404
- const slot = this._slots.get(item);
405
- if (slot === void 0) return;
406
- const entry = this._data[slot];
407
- this._unlink(entry);
408
- entry.minX = bounds.x;
409
- entry.minY = bounds.y;
410
- entry.maxX = bounds.x + bounds.width;
411
- entry.maxY = bounds.y + bounds.height;
412
- this._link(entry);
413
- }
414
- /**
415
- * Query all items whose bounds overlap the given rect.
416
- * Result order is unspecified. Appends to `result` when provided and returns it.
417
- */
418
- query(bounds, result) {
419
- const out = result ?? [];
420
- const gen = ++this._gen;
421
- const qMinX = bounds.x;
422
- const qMinY = bounds.y;
423
- const qMaxX = bounds.x + bounds.width;
424
- const qMaxY = bounds.y + bounds.height;
425
- const cxMin = _clampCell(_cMin(qMinX));
426
- const cxMax = _clampCell(_cMax(qMaxX));
427
- const cyMin = _clampCell(_cMin(qMinY));
428
- const cyMax = _clampCell(_cMax(qMaxY));
429
- for (let cx = cxMin; cx <= cxMax; cx++) for (let cy = cyMin; cy <= cyMax; cy++) {
430
- const bucket = this._cells.get(_key(cx, cy));
431
- if (bucket === void 0) continue;
432
- for (let i = 0; i < bucket.length; i++) {
433
- const e = bucket[i];
434
- if (e._stamp === gen) continue;
435
- e._stamp = gen;
436
- if (e.maxX > qMinX && e.minX < qMaxX && e.maxY > qMinY && e.minY < qMaxY) out.push(e.item);
437
- }
438
- }
439
- return out;
440
- }
441
- /** Remove all items. */
442
- clear() {
443
- this._data.length = 0;
444
- this._slots.clear();
445
- this._cells.clear();
446
- }
447
- _link(entry) {
448
- const cxMin = _clampCell(_cMin(entry.minX));
449
- const cxMax = _clampCell(_cMax(entry.maxX));
450
- const cyMin = _clampCell(_cMin(entry.minY));
451
- const cyMax = _clampCell(_cMax(entry.maxY));
452
- for (let cx = cxMin; cx <= cxMax; cx++) for (let cy = cyMin; cy <= cyMax; cy++) {
453
- const k = _key(cx, cy);
454
- let b = this._cells.get(k);
455
- if (b === void 0) {
456
- b = [];
457
- this._cells.set(k, b);
458
- }
459
- b.push(entry);
460
- }
461
- }
462
- _unlink(entry) {
463
- const cxMin = _clampCell(_cMin(entry.minX));
464
- const cxMax = _clampCell(_cMax(entry.maxX));
465
- const cyMin = _clampCell(_cMin(entry.minY));
466
- const cyMax = _clampCell(_cMax(entry.maxY));
467
- for (let cx = cxMin; cx <= cxMax; cx++) for (let cy = cyMin; cy <= cyMax; cy++) {
468
- const b = this._cells.get(_key(cx, cy));
469
- if (b === void 0) continue;
470
- const i = b.indexOf(entry);
471
- if (i !== -1) {
472
- const last = b.pop();
473
- if (i < b.length) b[i] = last;
474
- }
475
- }
476
- }
477
- };
478
516
  // src/collision-world.ts
479
517
  const ENTITY_SHIFT = 2 ** 26;
480
518
  /** Padding applied to a ray's query AABB — see `CollisionWorld.raycast`. */
@@ -493,6 +531,11 @@ function decodeHi(key) {
493
531
  /**
494
532
  * AABB collision world. Manages entities with shapes, detects overlaps each step,
495
533
  * and emits collision/trigger signals.
534
+ *
535
+ * The broadphase is a uniform grid of fixed 64-world-unit cells, with no option to
536
+ * change it. It suits colliders of roughly 16-64 units. In a world of one unit per
537
+ * tile, colliders crowd a few cells and `step` and `raycast` approach a scan of
538
+ * every collider, so scale world units up to match.
496
539
  */
497
540
  var CollisionWorld = class {
498
541
  onCollisionStart = new _flare_engine_events.Signal();
@@ -500,7 +543,7 @@ var CollisionWorld = class {
500
543
  onTriggerEnter = new _flare_engine_events.Signal();
501
544
  onTriggerExit = new _flare_engine_events.Signal();
502
545
  entries = /* @__PURE__ */ new Map();
503
- spatial = new SpatialIndex();
546
+ spatial = createCollisionGrid();
504
547
  /**
505
548
  * Two pre-allocated pair buffers — swapped each step (no per-frame allocation).
506
549
  * Keys are packed numbers via `encodePair(a, b)`.
@@ -508,9 +551,7 @@ var CollisionWorld = class {
508
551
  pairBufA = /* @__PURE__ */ new Set();
509
552
  pairBufB = /* @__PURE__ */ new Set();
510
553
  activePairs = this.pairBufA;
511
- /** Reusable query result buffer. */
512
- queryBuf = [];
513
- /** Reusable bounds rect — avoids per-entity Rect allocation in step(). */
554
+ /** Reusable bounds rect — avoids a Rect allocation per add / setPosition. */
514
555
  boundsBuf = {
515
556
  x: 0,
516
557
  y: 0,
@@ -522,32 +563,52 @@ var CollisionWorld = class {
522
563
  * follows the same rules.
523
564
  */
524
565
  add(entity, shape, x, y, isTrigger = false, layer = 1, mask = 4294967295) {
525
- const entry = {
526
- entity,
527
- shape,
528
- x,
529
- y,
530
- isTrigger,
531
- layer,
532
- mask
533
- };
534
- const previous = this.entries.get(entity);
535
- this.entries.set(entity, entry);
536
- shapeBoundsInto(shape, x, y, this.boundsBuf);
537
- if (previous === void 0) {
538
- this.spatial.insert(entity, this.boundsBuf);
566
+ const b = shapeBoundsInto(shape, x, y, this.boundsBuf);
567
+ const existing = this.entries.get(entity);
568
+ if (existing === void 0) {
569
+ const entry = {
570
+ entity,
571
+ shape,
572
+ x,
573
+ y,
574
+ isTrigger,
575
+ layer,
576
+ mask,
577
+ minX: 0,
578
+ minY: 0,
579
+ maxX: 0,
580
+ maxY: 0,
581
+ cxMin: 0,
582
+ cxMax: 0,
583
+ cyMin: 0,
584
+ cyMax: 0,
585
+ cellCount: 0,
586
+ cells: [],
587
+ groups: [],
588
+ at: [],
589
+ stamp: 0
590
+ };
591
+ this.entries.set(entity, entry);
592
+ gridInsert(this.spatial, entry, b.x, b.y, b.x + b.width, b.y + b.height);
539
593
  return;
540
594
  }
541
- this.spatial.update(entity, this.boundsBuf);
542
- if (previous.isTrigger === isTrigger) return;
595
+ const wasTrigger = existing.isTrigger;
596
+ gridUnlink(this.spatial, existing);
597
+ existing.shape = shape;
598
+ existing.x = x;
599
+ existing.y = y;
600
+ existing.isTrigger = isTrigger;
601
+ existing.layer = layer;
602
+ existing.mask = mask;
603
+ gridRelink(this.spatial, existing, b.x, b.y, b.x + b.width, b.y + b.height);
604
+ if (wasTrigger === isTrigger) return;
543
605
  for (const key of this.activePairs) {
544
606
  const lo = decodeLo(key);
545
607
  const hi = decodeHi(key);
546
608
  if (lo !== entity && hi !== entity) continue;
547
- const other = this.entries.get(lo === entity ? hi : lo);
548
- if (other?.isTrigger) continue;
609
+ if (this.entries.get(lo === entity ? hi : lo)?.isTrigger) continue;
549
610
  this.activePairs.delete(key);
550
- this.emitPair(lo, hi, previous, other, false);
611
+ this.emitPair(lo, hi, wasTrigger, false);
551
612
  }
552
613
  }
553
614
  /**
@@ -569,14 +630,14 @@ var CollisionWorld = class {
569
630
  const entry = this.entries.get(entity);
570
631
  if (!entry) return;
571
632
  this.entries.delete(entity);
572
- this.spatial.remove(entity);
633
+ gridRemove(this.spatial, entry);
573
634
  for (const key of this.activePairs) {
574
635
  const lo = decodeLo(key);
575
636
  const hi = decodeHi(key);
576
637
  if (lo !== entity && hi !== entity) continue;
577
638
  this.activePairs.delete(key);
578
- const otherEntity = lo === entity ? hi : lo;
579
- this.emitPair(lo, hi, entry, this.entries.get(otherEntity), false);
639
+ const other = this.entries.get(lo === entity ? hi : lo);
640
+ this.emitPair(lo, hi, entry.isTrigger || other?.isTrigger === true, false);
580
641
  }
581
642
  }
582
643
  /** Update an entity's position. */
@@ -585,8 +646,8 @@ var CollisionWorld = class {
585
646
  if (!entry) return;
586
647
  entry.x = x;
587
648
  entry.y = y;
588
- shapeBoundsInto(entry.shape, x, y, this.boundsBuf);
589
- this.spatial.update(entity, this.boundsBuf);
649
+ const b = shapeBoundsInto(entry.shape, x, y, this.boundsBuf);
650
+ gridMove(this.spatial, entry, b.x, b.y, b.x + b.width, b.y + b.height);
590
651
  }
591
652
  /** Number of entities in the world. */
592
653
  get size() {
@@ -600,45 +661,62 @@ var CollisionWorld = class {
600
661
  step() {
601
662
  const newPairs = this.activePairs === this.pairBufA ? this.pairBufB : this.pairBufA;
602
663
  newPairs.clear();
603
- for (const entryA of this.entries.values()) {
604
- const entityA = entryA.entity;
605
- shapeBoundsInto(entryA.shape, entryA.x, entryA.y, this.boundsBuf);
606
- this.queryBuf.length = 0;
607
- this.spatial.query(this.boundsBuf, this.queryBuf);
608
- for (let i = 0; i < this.queryBuf.length; i++) {
609
- const entityB = this.queryBuf[i];
610
- if (entityB <= entityA) continue;
611
- const entryB = this.entries.get(entityB);
612
- if (!entryB) continue;
613
- if ((entryA.layer & entryB.mask) === 0 && (entryB.layer & entryA.mask) === 0) continue;
614
- if (!shapeOverlap(entryA.shape, entryA.x, entryA.y, entryB.shape, entryB.x, entryB.y)) continue;
615
- newPairs.add(encodePair(entityA, entityB));
664
+ const grid = this.spatial;
665
+ for (const a of this.entries.values()) {
666
+ const entityA = a.entity;
667
+ const layerA = a.layer;
668
+ const maskA = a.mask;
669
+ const cells = a.cells;
670
+ const cellCount = a.cellCount;
671
+ const gen = cellCount > 1 ? ++grid.gen : 0;
672
+ for (let c = 0; c < cellCount; c++) {
673
+ const groups = cells[c].groups;
674
+ for (let g = 0; g < groups.length; g++) {
675
+ const group = groups[g];
676
+ if ((layerA & group.mask) === 0 && (group.layer & maskA) === 0) continue;
677
+ const items = group.items;
678
+ for (let i = 0; i < items.length; i++) {
679
+ const b = items[i];
680
+ if (b.entity <= entityA) continue;
681
+ if (cellCount > 1) {
682
+ if (b.stamp === gen) continue;
683
+ b.stamp = gen;
684
+ }
685
+ if (!(b.maxX > a.minX && b.minX < a.maxX && b.maxY > a.minY && b.minY < a.maxY)) continue;
686
+ if (!shapeOverlap(a.shape, a.x, a.y, b.shape, b.x, b.y)) continue;
687
+ newPairs.add(encodePair(entityA, b.entity));
688
+ }
689
+ }
616
690
  }
617
691
  }
618
692
  for (const key of newPairs) if (!this.activePairs.has(key)) {
619
693
  const lo = decodeLo(key);
620
694
  const hi = decodeHi(key);
621
- this.emitPair(lo, hi, this.entries.get(lo), this.entries.get(hi), true);
695
+ this.emitPair(lo, hi, this.isTriggerPair(lo, hi), true);
622
696
  }
623
697
  for (const key of this.activePairs) if (!newPairs.has(key)) {
624
698
  const lo = decodeLo(key);
625
699
  const hi = decodeHi(key);
626
- this.emitPair(lo, hi, this.entries.get(lo), this.entries.get(hi), false);
700
+ this.emitPair(lo, hi, this.isTriggerPair(lo, hi), false);
627
701
  }
628
702
  this.activePairs = newPairs;
629
703
  }
704
+ /** A pair is a trigger pair when either of its entities is a trigger. */
705
+ isTriggerPair(lo, hi) {
706
+ return this.entries.get(lo)?.isTrigger === true || this.entries.get(hi)?.isTrigger === true;
707
+ }
630
708
  /**
631
- * The one place that decides trigger vs collision for a pair and emits its
632
- * enter or exit signal. `a` and `b` are the pair's two entries in either
633
- * order. They are passed in rather than looked up because in `remove` the
634
- * removed entity is already gone from `entries`.
709
+ * The one place that emits a pair's enter or exit signal, in the trigger or
710
+ * the collision family. `trigger` is passed in rather than looked up because
711
+ * `remove` and a re-add classify by data `entries` no longer holds: the
712
+ * removed entry, and the `isTrigger` the entity had before the re-add.
635
713
  */
636
- emitPair(lo, hi, a, b, entering) {
714
+ emitPair(lo, hi, trigger, entering) {
637
715
  const pair = {
638
716
  entityA: lo,
639
717
  entityB: hi
640
718
  };
641
- if (a?.isTrigger || b?.isTrigger) {
719
+ if (trigger) {
642
720
  if (entering) this.onTriggerEnter.emit(pair);
643
721
  else this.onTriggerExit.emit(pair);
644
722
  } else if (entering) this.onCollisionStart.emit(pair);
@@ -665,18 +743,12 @@ var CollisionWorld = class {
665
743
  /** Remove all entities. */
666
744
  clear() {
667
745
  this.entries.clear();
668
- this.spatial.clear();
746
+ gridClear(this.spatial);
669
747
  this.pairBufA.clear();
670
748
  this.pairBufB.clear();
671
749
  this.activePairs = this.pairBufA;
672
750
  }
673
751
  /** Reused across raycasts — see `raycast`. */
674
- raycastBounds = {
675
- x: 0,
676
- y: 0,
677
- width: 0,
678
- height: 0
679
- };
680
752
  raycastCandidates = [];
681
753
  raycastHit = {
682
754
  entity: -1,
@@ -702,6 +774,13 @@ var CollisionWorld = class {
702
774
  * bits colliders already carry; it defaults to every layer. Triggers are
703
775
  * included — a ray asking "what is over there" wants them.
704
776
  *
777
+ * A ray that starts inside a collider hits that collider at its exit
778
+ * distance, not at 0. The hit's `normal` is then the outward normal of the
779
+ * face the ray entered through behind its origin for a box, and the outward
780
+ * normal at the exit point for a circle. To skip the collider a ray starts in,
781
+ * put it on a layer `mask` leaves out, or start the ray just past its edge: a
782
+ * ray that starts exactly on the edge still hits it, at distance 0.
783
+ *
705
784
  * The returned record is **reused between calls**: read it, or copy what you
706
785
  * need, before casting again. That is what keeps a per-frame ray allocation-
707
786
  * free; the standalone helper by contrast returns a fresh hit from each call
@@ -720,17 +799,17 @@ var CollisionWorld = class {
720
799
  const ey = oy + dy * maxDist;
721
800
  const minX = ox < ex ? ox : ex;
722
801
  const minY = oy < ey ? oy : ey;
723
- this.raycastBounds.x = minX - RAY_BOUNDS_PAD;
724
- this.raycastBounds.y = minY - RAY_BOUNDS_PAD;
725
- this.raycastBounds.width = Math.abs(ex - ox) + RAY_BOUNDS_PAD * 2;
726
- this.raycastBounds.height = Math.abs(ey - oy) + RAY_BOUNDS_PAD * 2;
727
- this.raycastCandidates.length = 0;
728
- this.spatial.query(this.raycastBounds, this.raycastCandidates);
802
+ const qMinX = minX - RAY_BOUNDS_PAD;
803
+ const qMinY = minY - RAY_BOUNDS_PAD;
804
+ const qMaxX = qMinX + (Math.abs(ex - ox) + RAY_BOUNDS_PAD * 2);
805
+ const qMaxY = qMinY + (Math.abs(ey - oy) + RAY_BOUNDS_PAD * 2);
806
+ const candidates = this.raycastCandidates;
807
+ candidates.length = 0;
808
+ gridQuery(this.spatial, qMinX, qMinY, qMaxX, qMaxY, candidates);
729
809
  let bestDist = Number.POSITIVE_INFINITY;
730
810
  let found = false;
731
- for (let i = 0; i < this.raycastCandidates.length; i++) {
732
- const entry = this.entries.get(this.raycastCandidates[i]);
733
- if (entry === void 0) continue;
811
+ for (let i = 0; i < candidates.length; i++) {
812
+ const entry = candidates[i];
734
813
  if ((entry.layer & mask) === 0) continue;
735
814
  const hit = rayVsShapeInto(ox, oy, dx, dy, maxDist, entry.entity, entry.shape, entry.x, entry.y, this.scratchHit);
736
815
  if (hit !== null && hit.distance < bestDist) {
@@ -760,6 +839,330 @@ var CollisionWorld = class {
760
839
  }
761
840
  };
762
841
  };
842
+ // src/mask.ts
843
+ /** An unturned pose at the origin: pivot at the frame's corner, 1 unit per px. */
844
+ function createMaskPose() {
845
+ return {
846
+ x: 0,
847
+ y: 0,
848
+ cos: 1,
849
+ sin: 0,
850
+ px: 0,
851
+ py: 0,
852
+ unit: 1
853
+ };
854
+ }
855
+ /**
856
+ * Build a mask from rows of text, top row first: `#` is solid, any other
857
+ * character clear. The bounds are the whole drawing — as wide as the longest
858
+ * row — placed at (`x`, `y`) in the frame. Allocates; call at load.
859
+ */
860
+ function createMaskShape(rows, x = 0, y = 0) {
861
+ let w = 0;
862
+ for (const row of rows) w = Math.max(w, row.length);
863
+ const stride = w + 31 >>> 5;
864
+ const words = new Uint32Array(rows.length * stride);
865
+ for (let r = 0; r < rows.length; r++) {
866
+ const row = rows[r];
867
+ for (let c = 0; c < row.length; c++) if (row[c] === "#") words[r * stride + (c >>> 5)] |= 1 << (c & 31);
868
+ }
869
+ return {
870
+ x,
871
+ y,
872
+ w,
873
+ h: rows.length,
874
+ words
875
+ };
876
+ }
877
+ function has(m, col, row) {
878
+ const cx = col - m.x;
879
+ const cy = row - m.y;
880
+ if (cx < 0 || cy < 0 || cx >= m.w || cy >= m.h) return false;
881
+ return ((m.words[cy * (m.w + 31 >>> 5) + (cx >>> 5)] ?? 0) >>> (cx & 31) & 1) === 1;
882
+ }
883
+ /**
884
+ * Whether the pixel at frame column `col`, row `row` (integers) is solid;
885
+ * outside the bounds nothing is. With `erode`, solid only when its four
886
+ * neighbours are solid too: the mask eroded by 1 px. Zero-alloc.
887
+ */
888
+ function isMaskSolidAt(m, col, row, erode = false) {
889
+ if (!has(m, col, row)) return false;
890
+ if (!erode) return true;
891
+ return has(m, col - 1, row) && has(m, col + 1, row) && has(m, col, row - 1) && has(m, col, row + 1);
892
+ }
893
+ /** The frame px of a world point, by the inverse turn. */
894
+ const LOCAL = {
895
+ x: 0,
896
+ y: 0
897
+ };
898
+ function toLocal(p, wx, wy) {
899
+ const dx = wx - p.x;
900
+ const dy = wy - p.y;
901
+ LOCAL.x = (dx * p.cos + dy * p.sin) / p.unit + p.px;
902
+ LOCAL.y = (-dx * p.sin + dy * p.cos) / p.unit + p.py;
903
+ }
904
+ /**
905
+ * The world bounding box of a posed mask's bounds rectangle: for a turned mask,
906
+ * the axis-aligned box around the turned rectangle. It bounds every solid pixel
907
+ * but is not shrunk to them. Zero-alloc — writes `out` and returns it.
908
+ */
909
+ function maskBoundsInto(m, p, out) {
910
+ const lx = m.x + m.w / 2 - p.px;
911
+ const ly = m.y + m.h / 2 - p.py;
912
+ const ac = Math.abs(p.cos);
913
+ const as = Math.abs(p.sin);
914
+ const hw = (m.w * ac + m.h * as) / 2 * p.unit;
915
+ const hh = (m.w * as + m.h * ac) / 2 * p.unit;
916
+ out.x = p.x + (lx * p.cos - ly * p.sin) * p.unit - hw;
917
+ out.y = p.y + (lx * p.sin + ly * p.cos) * p.unit - hh;
918
+ out.width = hw * 2;
919
+ out.height = hh * 2;
920
+ return out;
921
+ }
922
+ /** Allocating twin of `maskBoundsInto`. */
923
+ function maskBounds(m, p) {
924
+ return maskBoundsInto(m, p, {
925
+ x: 0,
926
+ y: 0,
927
+ width: 0,
928
+ height: 0
929
+ });
930
+ }
931
+ /**
932
+ * Whether a world box, centre (`cx`, `cy`) and half extents (`hw`, `hh`),
933
+ * overlaps a solid pixel. Touching an edge is not overlapping. `erode` tests
934
+ * the mask eroded by 1 px.
935
+ *
936
+ * The box is axis-aligned in the world, so against a turned mask it is tested
937
+ * by its bounding box in the mask's frame: exact for a turn that is a multiple
938
+ * of a quarter, generous by the box's corners for any other. Zero-alloc.
939
+ */
940
+ function maskOverlapsBox(m, p, cx, cy, hw, hh, erode = false) {
941
+ toLocal(p, cx, cy);
942
+ const ac = Math.abs(p.cos);
943
+ const as = Math.abs(p.sin);
944
+ const lhw = (hw * ac + hh * as) / p.unit;
945
+ const lhh = (hw * as + hh * ac) / p.unit;
946
+ const x0 = LOCAL.x - lhw;
947
+ const x1 = LOCAL.x + lhw;
948
+ const y0 = LOCAL.y - lhh;
949
+ const y1 = LOCAL.y + lhh;
950
+ const c0 = Math.max(m.x, Math.floor(x0));
951
+ const c1 = Math.min(m.x + m.w - 1, Math.ceil(x1) - 1);
952
+ const r0 = Math.max(m.y, Math.floor(y0));
953
+ const r1 = Math.min(m.y + m.h - 1, Math.ceil(y1) - 1);
954
+ for (let r = r0; r <= r1; r++) {
955
+ if (!(r < y1 && r + 1 > y0)) continue;
956
+ for (let c = c0; c <= c1; c++) if (c < x1 && c + 1 > x0 && isMaskSolidAt(m, c, r, erode)) return true;
957
+ }
958
+ return false;
959
+ }
960
+ /** The most samples one sweep takes, so a runaway segment cannot stall a frame. */
961
+ const SWEEP_MAX = 256;
962
+ /**
963
+ * Whether a box swept from (`x0`, `y0`) to (`x1`, `y1`) overlaps a solid pixel
964
+ * anywhere along the segment, so a fast body cannot skip a 1 px feature. It is
965
+ * `maskOverlapsBox` sampled along the segment, both ends included: samples are
966
+ * at most half a px apart, and at most the box's smaller non-zero half extent.
967
+ * A sweep is capped at 257 samples; a segment too long for that spacing is
968
+ * sampled more coarsely and can miss. Zero-alloc.
969
+ */
970
+ function maskOverlapsSweptBox(m, p, x0, y0, x1, y1, hw, hh) {
971
+ const len = Math.hypot(x1 - x0, y1 - y0);
972
+ let step = .5 * p.unit;
973
+ if (hw > 0 && hw < step) step = hw;
974
+ if (hh > 0 && hh < step) step = hh;
975
+ const n = Math.min(SWEEP_MAX, Math.ceil(len / step));
976
+ for (let i = 0; i <= n; i++) {
977
+ const t = n === 0 ? 1 : i / n;
978
+ if (maskOverlapsBox(m, p, x0 + (x1 - x0) * t, y0 + (y1 - y0) * t, hw, hh)) return true;
979
+ }
980
+ return false;
981
+ }
982
+ /**
983
+ * Whether a world circle overlaps a solid pixel. The circle is taken into the
984
+ * mask's frame, where it is still a circle, and tested against each pixel's
985
+ * square, so the result is exact at any turn. Strict, like `shapeOverlap`:
986
+ * touching is not overlapping, and a zero radius hits only strictly inside a
987
+ * pixel. Zero-alloc.
988
+ */
989
+ function maskOverlapsCircle(m, p, cx, cy, radius) {
990
+ toLocal(p, cx, cy);
991
+ const lx = LOCAL.x;
992
+ const ly = LOCAL.y;
993
+ const lr = radius / p.unit;
994
+ const rr = lr * lr;
995
+ const c0 = Math.max(m.x, Math.floor(lx - lr));
996
+ const c1 = Math.min(m.x + m.w - 1, Math.ceil(lx + lr) - 1);
997
+ const r0 = Math.max(m.y, Math.floor(ly - lr));
998
+ const r1 = Math.min(m.y + m.h - 1, Math.ceil(ly + lr) - 1);
999
+ for (let r = r0; r <= r1; r++) {
1000
+ const dy = ly < r ? r - ly : ly > r + 1 ? ly - r - 1 : 0;
1001
+ for (let c = c0; c <= c1; c++) {
1002
+ if (!has(m, c, r)) continue;
1003
+ const dx = lx < c ? c - lx : lx > c + 1 ? lx - c - 1 : 0;
1004
+ const dd = dx * dx + dy * dy;
1005
+ if (dd > 0 ? dd < rr : lr > 0 || lx > c && lx < c + 1 && ly > r && ly < r + 1) return true;
1006
+ }
1007
+ }
1008
+ return false;
1009
+ }
1010
+ const BOUNDS = {
1011
+ x: 0,
1012
+ y: 0,
1013
+ width: 0,
1014
+ height: 0
1015
+ };
1016
+ /**
1017
+ * Whether a solid pixel of `a` overlaps a solid pixel of `b`. Each pose may be
1018
+ * turned and scaled independently. Every solid pixel of one mask inside the
1019
+ * other's world bounds is taken into the other's frame as a turned square and
1020
+ * tested against the solid pixels there by separating axes, so pixels are
1021
+ * compared as the squares they are, not by bounding boxes: exact up to
1022
+ * floating-point rounding. Touching is not overlapping; for masks at different
1023
+ * turns a contact within rounding of touching can read either way.
1024
+ *
1025
+ * Cost grows with the pixels of both masks inside the overlap of their bounds
1026
+ * — this is the narrow phase for a pair a box broadphase already passed.
1027
+ * Zero-alloc.
1028
+ */
1029
+ function maskOverlapsMask(a, pa, b, pb) {
1030
+ return a.w * a.h <= b.w * b.h ? pixelsOverlap(a, pa, b, pb) : pixelsOverlap(b, pb, a, pa);
1031
+ }
1032
+ function pixelsOverlap(a, pa, b, pb) {
1033
+ maskBoundsInto(b, pb, BOUNDS);
1034
+ const bhw = BOUNDS.width / 2;
1035
+ const bhh = BOUNDS.height / 2;
1036
+ toLocal(pa, BOUNDS.x + bhw, BOUNDS.y + bhh);
1037
+ const lhw = (bhw * Math.abs(pa.cos) + bhh * Math.abs(pa.sin)) / pa.unit;
1038
+ const lhh = (bhw * Math.abs(pa.sin) + bhh * Math.abs(pa.cos)) / pa.unit;
1039
+ const c0 = Math.max(a.x, Math.floor(LOCAL.x - lhw));
1040
+ const c1 = Math.min(a.x + a.w - 1, Math.ceil(LOCAL.x + lhw) - 1);
1041
+ const r0 = Math.max(a.y, Math.floor(LOCAL.y - lhh));
1042
+ const r1 = Math.min(a.y + a.h - 1, Math.ceil(LOCAL.y + lhh) - 1);
1043
+ if (c0 > c1 || r0 > r1) return false;
1044
+ const k = pa.unit / pb.unit;
1045
+ const cosR = pa.cos * pb.cos + pa.sin * pb.sin;
1046
+ const sinR = pa.sin * pb.cos - pa.cos * pb.sin;
1047
+ const mc = cosR * k;
1048
+ const ms = sinR * k;
1049
+ toLocal(pb, pa.x, pa.y);
1050
+ const tx = LOCAL.x - (mc * pa.px - ms * pa.py);
1051
+ const ty = LOCAL.y - (ms * pa.px + mc * pa.py);
1052
+ const half = k / 2;
1053
+ const spread = Math.abs(cosR) + Math.abs(sinR);
1054
+ const ext = half * spread + .5;
1055
+ const own = half + .5 * spread;
1056
+ const bc0 = b.x;
1057
+ const bc1 = b.x + b.w - 1;
1058
+ const br0 = b.y;
1059
+ const br1 = b.y + b.h - 1;
1060
+ for (let r = r0; r <= r1; r++) for (let c = c0; c <= c1; c++) {
1061
+ if (!has(a, c, r)) continue;
1062
+ const bx = tx + mc * (c + .5) - ms * (r + .5);
1063
+ const by = ty + ms * (c + .5) + mc * (r + .5);
1064
+ const q0 = Math.max(bc0, Math.floor(bx - ext));
1065
+ const q1 = Math.min(bc1, Math.ceil(bx + ext) - 1);
1066
+ const s0 = Math.max(br0, Math.floor(by - ext));
1067
+ const s1 = Math.min(br1, Math.ceil(by + ext) - 1);
1068
+ for (let s = s0; s <= s1; s++) {
1069
+ const dy = s + .5 - by;
1070
+ if (!(Math.abs(dy) < ext)) continue;
1071
+ for (let q = q0; q <= q1; q++) {
1072
+ const dx = q + .5 - bx;
1073
+ if (Math.abs(dx) < ext && Math.abs(dx * cosR + dy * sinR) < own && Math.abs(dy * cosR - dx * sinR) < own && has(b, q, s)) return true;
1074
+ }
1075
+ }
1076
+ }
1077
+ return false;
1078
+ }
1079
+ /**
1080
+ * The distance along a world ray from (`ox`, `oy`), unit direction (`dx`,
1081
+ * `dy`), to the first solid pixel it enters, at most `len`; `0` when it starts
1082
+ * inside one; `-1` when it meets none. A grid walk over the mask's pixels in
1083
+ * its own frame, so the distance is exact at any turn. Zero-alloc.
1084
+ *
1085
+ * Unlike `rayVsShapeInto` it reports a distance only — no point, no normal —
1086
+ * and a ray starting inside a solid pixel reads `0` rather than its exit.
1087
+ */
1088
+ function rayVsMask(m, p, ox, oy, dx, dy, len) {
1089
+ toLocal(p, ox, oy);
1090
+ const lx = LOCAL.x;
1091
+ const ly = LOCAL.y;
1092
+ const ldx = dx * p.cos + dy * p.sin;
1093
+ const ldy = -dx * p.sin + dy * p.cos;
1094
+ let t0 = 0;
1095
+ let t1 = len / p.unit;
1096
+ if (ldx === 0) {
1097
+ if (lx < m.x || lx >= m.x + m.w) return -1;
1098
+ } else {
1099
+ const ta = (m.x - lx) / ldx;
1100
+ const tb = (m.x + m.w - lx) / ldx;
1101
+ t0 = Math.max(t0, Math.min(ta, tb));
1102
+ t1 = Math.min(t1, Math.max(ta, tb));
1103
+ }
1104
+ if (ldy === 0) {
1105
+ if (ly < m.y || ly >= m.y + m.h) return -1;
1106
+ } else {
1107
+ const ta = (m.y - ly) / ldy;
1108
+ const tb = (m.y + m.h - ly) / ldy;
1109
+ t0 = Math.max(t0, Math.min(ta, tb));
1110
+ t1 = Math.min(t1, Math.max(ta, tb));
1111
+ }
1112
+ if (t0 > t1) return -1;
1113
+ const sx = lx + ldx * t0;
1114
+ const sy = ly + ldy * t0;
1115
+ let c = Math.min(m.x + m.w - 1, Math.max(m.x, Math.floor(sx + ldx * 1e-9)));
1116
+ let r = Math.min(m.y + m.h - 1, Math.max(m.y, Math.floor(sy + ldy * 1e-9)));
1117
+ const stepC = ldx > 0 ? 1 : -1;
1118
+ const stepR = ldy > 0 ? 1 : -1;
1119
+ const dtC = ldx === 0 ? Number.POSITIVE_INFINITY : Math.abs(1 / ldx);
1120
+ const dtR = ldy === 0 ? Number.POSITIVE_INFINITY : Math.abs(1 / ldy);
1121
+ let nextC = ldx === 0 ? Number.POSITIVE_INFINITY : t0 + ((ldx > 0 ? c + 1 : c) - sx) / ldx;
1122
+ let nextR = ldy === 0 ? Number.POSITIVE_INFINITY : t0 + ((ldy > 0 ? r + 1 : r) - sy) / ldy;
1123
+ let t = t0;
1124
+ const cells = m.w + m.h + 2;
1125
+ for (let i = 0; i < cells && t <= t1; i++) {
1126
+ if (has(m, c, r)) return t * p.unit;
1127
+ if (nextC < nextR) {
1128
+ t = nextC;
1129
+ nextC += dtC;
1130
+ c += stepC;
1131
+ } else {
1132
+ t = nextR;
1133
+ nextR += dtR;
1134
+ r += stepR;
1135
+ }
1136
+ if (c < m.x || c >= m.x + m.w || r < m.y || r >= m.y + m.h) return -1;
1137
+ }
1138
+ return -1;
1139
+ }
1140
+ /**
1141
+ * Where a beam filling the world rect [`x0`, `x1`] × [`y0`, `y1`] and
1142
+ * travelling along one axis — (`dirX`, `dirY`) is one of (0, -1), (0, 1),
1143
+ * (1, 0) and (-1, 0) — first meets the mask: the near edge of the nearest
1144
+ * solid pixel that overlaps the rect, as a world coordinate on the beam's
1145
+ * axis. `NaN` when no solid pixel overlaps it. A turned pixel counts by its
1146
+ * bounding box. Visits every pixel of the mask. Zero-alloc.
1147
+ */
1148
+ function maskStripStop(m, p, x0, y0, x1, y1, dirX, dirY) {
1149
+ let stop = NaN;
1150
+ const u = p.unit;
1151
+ const h = (Math.abs(p.cos) + Math.abs(p.sin)) * u / 2;
1152
+ const far = dirY < 0 || dirY === 0 && dirX < 0;
1153
+ for (let r = m.y; r < m.y + m.h; r++) for (let c = m.x; c < m.x + m.w; c++) {
1154
+ if (!has(m, c, r)) continue;
1155
+ const lx = c + .5 - p.px;
1156
+ const ly = r + .5 - p.py;
1157
+ const wx = p.x + (lx * p.cos - ly * p.sin) * u;
1158
+ const wy = p.y + (lx * p.sin + ly * p.cos) * u;
1159
+ if (!(wx - h < x1 && wx + h > x0 && wy - h < y1 && wy + h > y0)) continue;
1160
+ const edge = dirY < 0 ? wy + h : dirY > 0 ? wy - h : dirX > 0 ? wx - h : wx + h;
1161
+ if (Number.isNaN(stop)) stop = edge;
1162
+ else stop = far ? Math.max(stop, edge) : Math.min(stop, edge);
1163
+ }
1164
+ return stop;
1165
+ }
763
1166
  // src/solid-grid.ts
764
1167
  /**
765
1168
  * Build a `SolidGrid` from a list of solid tile positions.
@@ -843,18 +1246,172 @@ function moveAndSlideInto(grid, x, y, dx, dy, halfW, halfH, out) {
843
1246
  out.y = ny;
844
1247
  return out;
845
1248
  }
1249
+ // src/spatial-index.ts
1250
+ /**
1251
+ * Uniform spatial-hash broadphase.
1252
+ * `insert`, `remove`, and `update` are O(cells touched) — O(1) for typical entities.
1253
+ * `query` walks only the cells overlapping the given rect; result order is unspecified.
1254
+ * Zero-alloc in the query hot-path: duplicate suppression uses a monotone stamp counter,
1255
+ * not a per-call Set.
1256
+ */
1257
+ var SpatialIndex = class {
1258
+ _data = [];
1259
+ _slots = /* @__PURE__ */ new Map();
1260
+ _cells = /* @__PURE__ */ new Map();
1261
+ _gen = 0;
1262
+ /** Number of items in the index. */
1263
+ get size() {
1264
+ return this._data.length;
1265
+ }
1266
+ /**
1267
+ * Insert an item with a bounding rect. Inserting an item already in the index
1268
+ * replaces its bounds (upsert) — same as `update`.
1269
+ */
1270
+ insert(item, bounds) {
1271
+ if (this._slots.has(item)) {
1272
+ this.update(item, bounds);
1273
+ return;
1274
+ }
1275
+ const maxX = bounds.x + bounds.width;
1276
+ const maxY = bounds.y + bounds.height;
1277
+ const entry = {
1278
+ item,
1279
+ minX: bounds.x,
1280
+ minY: bounds.y,
1281
+ maxX,
1282
+ maxY,
1283
+ cxMin: cellMin(bounds.x),
1284
+ cxMax: cellMax(maxX),
1285
+ cyMin: cellMin(bounds.y),
1286
+ cyMax: cellMax(maxY),
1287
+ _at: [],
1288
+ _stamp: 0
1289
+ };
1290
+ this._slots.set(item, this._data.length);
1291
+ this._data.push(entry);
1292
+ this._link(entry);
1293
+ }
1294
+ /** Remove an item. Returns false when the item was not present. */
1295
+ remove(item) {
1296
+ const slot = this._slots.get(item);
1297
+ if (slot === void 0) return false;
1298
+ const entry = this._data[slot];
1299
+ this._unlink(entry);
1300
+ this._slots.delete(item);
1301
+ const last = this._data.pop();
1302
+ if (slot < this._data.length) {
1303
+ this._data[slot] = last;
1304
+ this._slots.set(last.item, slot);
1305
+ }
1306
+ return true;
1307
+ }
1308
+ /** Update the bounds for an existing item. No-op when the item is absent. */
1309
+ update(item, bounds) {
1310
+ const slot = this._slots.get(item);
1311
+ if (slot === void 0) return;
1312
+ const entry = this._data[slot];
1313
+ const maxX = bounds.x + bounds.width;
1314
+ const maxY = bounds.y + bounds.height;
1315
+ entry.minX = bounds.x;
1316
+ entry.minY = bounds.y;
1317
+ entry.maxX = maxX;
1318
+ entry.maxY = maxY;
1319
+ const cxMin = cellMin(bounds.x);
1320
+ const cxMax = cellMax(maxX);
1321
+ const cyMin = cellMin(bounds.y);
1322
+ const cyMax = cellMax(maxY);
1323
+ if (cxMin === entry.cxMin && cxMax === entry.cxMax && cyMin === entry.cyMin && cyMax === entry.cyMax) return;
1324
+ this._unlink(entry);
1325
+ entry.cxMin = cxMin;
1326
+ entry.cxMax = cxMax;
1327
+ entry.cyMin = cyMin;
1328
+ entry.cyMax = cyMax;
1329
+ this._link(entry);
1330
+ }
1331
+ /**
1332
+ * Query all items whose bounds overlap the given rect.
1333
+ * Result order is unspecified. Appends to `result` when provided and returns it.
1334
+ */
1335
+ query(bounds, result) {
1336
+ const out = result ?? [];
1337
+ const gen = ++this._gen;
1338
+ const qMinX = bounds.x;
1339
+ const qMinY = bounds.y;
1340
+ const qMaxX = bounds.x + bounds.width;
1341
+ const qMaxY = bounds.y + bounds.height;
1342
+ const cxMin = cellMin(qMinX);
1343
+ const cxMax = cellMax(qMaxX);
1344
+ const cyMin = cellMin(qMinY);
1345
+ const cyMax = cellMax(qMaxY);
1346
+ for (let cx = cxMin; cx <= cxMax; cx++) for (let cy = cyMin; cy <= cyMax; cy++) {
1347
+ const bucket = this._cells.get(cellKey(cx, cy));
1348
+ if (bucket === void 0) continue;
1349
+ for (let i = 0; i < bucket.length; i++) {
1350
+ const e = bucket[i];
1351
+ if (e._stamp === gen) continue;
1352
+ e._stamp = gen;
1353
+ if (e.maxX > qMinX && e.minX < qMaxX && e.maxY > qMinY && e.minY < qMaxY) out.push(e.item);
1354
+ }
1355
+ }
1356
+ return out;
1357
+ }
1358
+ /** Remove all items. */
1359
+ clear() {
1360
+ this._data.length = 0;
1361
+ this._slots.clear();
1362
+ this._cells.clear();
1363
+ }
1364
+ _link(entry) {
1365
+ const { cxMin, cxMax, cyMin, cyMax, _at } = entry;
1366
+ let n = 0;
1367
+ for (let cx = cxMin; cx <= cxMax; cx++) for (let cy = cyMin; cy <= cyMax; cy++) {
1368
+ const k = cellKey(cx, cy);
1369
+ let b = this._cells.get(k);
1370
+ if (b === void 0) {
1371
+ b = [];
1372
+ this._cells.set(k, b);
1373
+ }
1374
+ _at[n++] = b.length;
1375
+ b.push(entry);
1376
+ }
1377
+ }
1378
+ _unlink(entry) {
1379
+ const { cxMin, cxMax, cyMin, cyMax, _at } = entry;
1380
+ let n = 0;
1381
+ for (let cx = cxMin; cx <= cxMax; cx++) for (let cy = cyMin; cy <= cyMax; cy++) {
1382
+ const i = _at[n++];
1383
+ const b = this._cells.get(cellKey(cx, cy));
1384
+ if (b === void 0) continue;
1385
+ const last = b.pop();
1386
+ if (last === entry) continue;
1387
+ b[i] = last;
1388
+ last._at[(cx - last.cxMin) * (last.cyMax - last.cyMin + 1) + (cy - last.cyMin)] = i;
1389
+ }
1390
+ }
1391
+ };
846
1392
  exports.AABB = AABB;
847
1393
  exports.CircleShape = CircleShape;
848
1394
  exports.CollisionWorld = CollisionWorld;
849
1395
  exports.SpatialIndex = SpatialIndex;
850
1396
  exports.buildSolidGrid = buildSolidGrid;
851
1397
  exports.createCollider = createCollider;
1398
+ exports.createMaskPose = createMaskPose;
1399
+ exports.createMaskShape = createMaskShape;
852
1400
  exports.createOverlap = createOverlap;
853
1401
  exports.isBlockedAABB = isBlockedAABB;
1402
+ exports.isMaskSolidAt = isMaskSolidAt;
854
1403
  exports.isSolidAt = isSolidAt;
1404
+ exports.maskBounds = maskBounds;
1405
+ exports.maskBoundsInto = maskBoundsInto;
1406
+ exports.maskOverlapsBox = maskOverlapsBox;
1407
+ exports.maskOverlapsCircle = maskOverlapsCircle;
1408
+ exports.maskOverlapsMask = maskOverlapsMask;
1409
+ exports.maskOverlapsSweptBox = maskOverlapsSweptBox;
1410
+ exports.maskStripStop = maskStripStop;
855
1411
  exports.moveAndSlideInto = moveAndSlideInto;
856
1412
  exports.overlap = overlap;
857
1413
  exports.overlapInto = overlapInto;
1414
+ exports.rayVsMask = rayVsMask;
858
1415
  exports.rayVsShapeInto = rayVsShapeInto;
859
1416
  exports.raycast = raycast;
860
1417
  exports.setSolidAt = setSolidAt;