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