@flare-engine/physics 0.2.1 → 0.3.1

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
@@ -1,428 +1,540 @@
1
- // src/shape.ts
1
+ import { Signal } from "@flare-engine/events";
2
+ //#region src/collider.ts
3
+ /** Create a collider with default settings. */
4
+ function createCollider(shape, opts) {
5
+ return {
6
+ shape,
7
+ isTrigger: opts?.isTrigger ?? false,
8
+ layer: opts?.layer ?? 1,
9
+ mask: opts?.mask ?? 4294967295
10
+ };
11
+ }
12
+ //#endregion
13
+ //#region src/shape.ts
14
+ /** Create an AABB shape from width and height. */
2
15
  function AABB(width, height) {
3
- return { type: "aabb", hw: width * 0.5, hh: height * 0.5 };
16
+ return {
17
+ type: "aabb",
18
+ hw: width * .5,
19
+ hh: height * .5
20
+ };
4
21
  }
22
+ /** Create a circle shape from radius. */
5
23
  function CircleShape(radius) {
6
- return { type: "circle", radius };
24
+ return {
25
+ type: "circle",
26
+ radius
27
+ };
7
28
  }
29
+ /** Compute the bounding rect of a shape at a given position. */
8
30
  function shapeBounds(shape, x, y) {
9
- if (shape.type === "aabb") {
10
- return { x: x - shape.hw, y: y - shape.hh, width: shape.hw * 2, height: shape.hh * 2 };
11
- }
12
- return {
13
- x: x - shape.radius,
14
- y: y - shape.radius,
15
- width: shape.radius * 2,
16
- height: shape.radius * 2
17
- };
31
+ if (shape.type === "aabb") return {
32
+ x: x - shape.hw,
33
+ y: y - shape.hh,
34
+ width: shape.hw * 2,
35
+ height: shape.hh * 2
36
+ };
37
+ return {
38
+ x: x - shape.radius,
39
+ y: y - shape.radius,
40
+ width: shape.radius * 2,
41
+ height: shape.radius * 2
42
+ };
18
43
  }
44
+ /** Zero-alloc variant — writes the shape bounds into the provided output rect. */
19
45
  function shapeBoundsInto(shape, x, y, out) {
20
- if (shape.type === "aabb") {
21
- out.x = x - shape.hw;
22
- out.y = y - shape.hh;
23
- out.width = shape.hw * 2;
24
- out.height = shape.hh * 2;
25
- return out;
26
- }
27
- out.x = x - shape.radius;
28
- out.y = y - shape.radius;
29
- out.width = shape.radius * 2;
30
- out.height = shape.radius * 2;
31
- return out;
46
+ if (shape.type === "aabb") {
47
+ out.x = x - shape.hw;
48
+ out.y = y - shape.hh;
49
+ out.width = shape.hw * 2;
50
+ out.height = shape.hh * 2;
51
+ return out;
52
+ }
53
+ out.x = x - shape.radius;
54
+ out.y = y - shape.radius;
55
+ out.width = shape.radius * 2;
56
+ out.height = shape.radius * 2;
57
+ return out;
32
58
  }
59
+ /** Test overlap between two positioned shapes. Returns true if overlapping. */
33
60
  function shapeOverlap(shapeA, ax, ay, shapeB, bx, by) {
34
- if (shapeA.type === "aabb" && shapeB.type === "aabb") {
35
- return aabbVsAabb(ax, ay, shapeA.hw, shapeA.hh, bx, by, shapeB.hw, shapeB.hh);
36
- }
37
- if (shapeA.type === "circle" && shapeB.type === "circle") {
38
- return circleVsCircle(ax, ay, shapeA.radius, bx, by, shapeB.radius);
39
- }
40
- if (shapeA.type === "aabb" && shapeB.type === "circle") {
41
- return aabbVsCircle(ax, ay, shapeA.hw, shapeA.hh, bx, by, shapeB.radius);
42
- }
43
- return aabbVsCircle(
44
- bx,
45
- by,
46
- shapeB.hw,
47
- shapeB.hh,
48
- ax,
49
- ay,
50
- shapeA.radius
51
- );
61
+ if (shapeA.type === "aabb" && shapeB.type === "aabb") return aabbVsAabb(ax, ay, shapeA.hw, shapeA.hh, bx, by, shapeB.hw, shapeB.hh);
62
+ if (shapeA.type === "circle" && shapeB.type === "circle") return circleVsCircle(ax, ay, shapeA.radius, bx, by, shapeB.radius);
63
+ if (shapeA.type === "aabb" && shapeB.type === "circle") return aabbVsCircle(ax, ay, shapeA.hw, shapeA.hh, bx, by, shapeB.radius);
64
+ return aabbVsCircle(bx, by, shapeB.hw, shapeB.hh, ax, ay, shapeA.radius);
52
65
  }
53
66
  function aabbVsAabb(ax, ay, ahw, ahh, bx, by, bhw, bhh) {
54
- return Math.abs(ax - bx) < ahw + bhw && Math.abs(ay - by) < ahh + bhh;
67
+ return Math.abs(ax - bx) < ahw + bhw && Math.abs(ay - by) < ahh + bhh;
55
68
  }
56
69
  function circleVsCircle(ax, ay, ar, bx, by, br) {
57
- const dx = bx - ax;
58
- const dy = by - ay;
59
- const radSum = ar + br;
60
- return dx * dx + dy * dy < radSum * radSum;
70
+ const dx = bx - ax;
71
+ const dy = by - ay;
72
+ const radSum = ar + br;
73
+ return dx * dx + dy * dy < radSum * radSum;
61
74
  }
62
75
  function aabbVsCircle(ax, ay, ahw, ahh, cx, cy, cr) {
63
- const left = ax - ahw;
64
- const right = ax + ahw;
65
- const top = ay - ahh;
66
- const bottom = ay + ahh;
67
- const closestX = cx < left ? left : cx > right ? right : cx;
68
- const closestY = cy < top ? top : cy > bottom ? bottom : cy;
69
- const dx = cx - closestX;
70
- const dy = cy - closestY;
71
- return dx * dx + dy * dy <= cr * cr;
76
+ const left = ax - ahw;
77
+ const right = ax + ahw;
78
+ const top = ay - ahh;
79
+ const bottom = ay + ahh;
80
+ const closestX = cx < left ? left : cx > right ? right : cx;
81
+ const closestY = cy < top ? top : cy > bottom ? bottom : cy;
82
+ const dx = cx - closestX;
83
+ const dy = cy - closestY;
84
+ return dx * dx + dy * dy <= cr * cr;
72
85
  }
73
-
74
- // src/spatial-index.ts
86
+ //#endregion
87
+ //#region src/spatial-index.ts
88
+ const CELL = 64;
89
+ const KEY_RANGE = 65536;
90
+ const KEY_OFFSET = 32768;
91
+ function _key(cx, cy) {
92
+ return (cx + KEY_OFFSET) * KEY_RANGE + (cy + KEY_OFFSET);
93
+ }
94
+ function _cMin(v) {
95
+ return Math.floor(v / CELL);
96
+ }
97
+ function _cMax(v) {
98
+ return Math.ceil(v / CELL) - 1;
99
+ }
100
+ /**
101
+ * Uniform spatial-hash broadphase.
102
+ * `insert`, `remove`, and `update` are O(cells touched) — O(1) for typical entities.
103
+ * `query` walks only the cells overlapping the given rect; result order is unspecified.
104
+ * Zero-alloc in the query hot-path: duplicate suppression uses a monotone stamp counter,
105
+ * not a per-call Set.
106
+ */
75
107
  var SpatialIndex = class {
76
- entries = [];
77
- /** Number of items in the index. */
78
- get size() {
79
- return this.entries.length;
80
- }
81
- /** Insert an item with a bounding rect. */
82
- insert(item, bounds) {
83
- this.entries.push({
84
- item,
85
- minX: bounds.x,
86
- minY: bounds.y,
87
- maxX: bounds.x + bounds.width,
88
- maxY: bounds.y + bounds.height
89
- });
90
- }
91
- /** Remove an item. */
92
- remove(item) {
93
- const idx = this.entries.findIndex((e) => e.item === item);
94
- if (idx === -1) return false;
95
- const last = this.entries.pop();
96
- if (idx < this.entries.length) {
97
- this.entries[idx] = last;
98
- }
99
- return true;
100
- }
101
- /** Update the bounds for an existing item. */
102
- update(item, bounds) {
103
- const entry = this.entries.find((e) => e.item === item);
104
- if (entry) {
105
- entry.minX = bounds.x;
106
- entry.minY = bounds.y;
107
- entry.maxX = bounds.x + bounds.width;
108
- entry.maxY = bounds.y + bounds.height;
109
- }
110
- }
111
- /** Query all items whose bounds overlap the given rect. */
112
- query(bounds, result) {
113
- const out = result ?? [];
114
- const qMinX = bounds.x;
115
- const qMinY = bounds.y;
116
- const qMaxX = bounds.x + bounds.width;
117
- const qMaxY = bounds.y + bounds.height;
118
- for (let i = 0; i < this.entries.length; i++) {
119
- const e = this.entries[i];
120
- if (e.maxX > qMinX && e.minX < qMaxX && e.maxY > qMinY && e.minY < qMaxY) {
121
- out.push(e.item);
122
- }
123
- }
124
- return out;
125
- }
126
- /** Remove all items. */
127
- clear() {
128
- this.entries.length = 0;
129
- }
108
+ _data = [];
109
+ _slots = /* @__PURE__ */ new Map();
110
+ _cells = /* @__PURE__ */ new Map();
111
+ _gen = 0;
112
+ /** Number of items in the index. */
113
+ get size() {
114
+ return this._data.length;
115
+ }
116
+ /** Insert an item with a bounding rect. */
117
+ insert(item, bounds) {
118
+ const entry = {
119
+ item,
120
+ minX: bounds.x,
121
+ minY: bounds.y,
122
+ maxX: bounds.x + bounds.width,
123
+ maxY: bounds.y + bounds.height,
124
+ _stamp: 0
125
+ };
126
+ this._slots.set(item, this._data.length);
127
+ this._data.push(entry);
128
+ this._link(entry);
129
+ }
130
+ /** Remove an item. Returns false when the item was not present. */
131
+ remove(item) {
132
+ const slot = this._slots.get(item);
133
+ if (slot === void 0) return false;
134
+ const entry = this._data[slot];
135
+ this._unlink(entry);
136
+ this._slots.delete(item);
137
+ const last = this._data.pop();
138
+ if (slot < this._data.length) {
139
+ this._data[slot] = last;
140
+ this._slots.set(last.item, slot);
141
+ }
142
+ return true;
143
+ }
144
+ /** Update the bounds for an existing item. No-op when the item is absent. */
145
+ update(item, bounds) {
146
+ const slot = this._slots.get(item);
147
+ if (slot === void 0) return;
148
+ const entry = this._data[slot];
149
+ this._unlink(entry);
150
+ entry.minX = bounds.x;
151
+ entry.minY = bounds.y;
152
+ entry.maxX = bounds.x + bounds.width;
153
+ entry.maxY = bounds.y + bounds.height;
154
+ this._link(entry);
155
+ }
156
+ /**
157
+ * Query all items whose bounds overlap the given rect.
158
+ * Result order is unspecified. Appends to `result` when provided and returns it.
159
+ */
160
+ query(bounds, result) {
161
+ const out = result ?? [];
162
+ const gen = ++this._gen;
163
+ const qMinX = bounds.x;
164
+ const qMinY = bounds.y;
165
+ const qMaxX = bounds.x + bounds.width;
166
+ const qMaxY = bounds.y + bounds.height;
167
+ const cxMin = _cMin(qMinX);
168
+ const cxMax = _cMax(qMaxX);
169
+ const cyMin = _cMin(qMinY);
170
+ const cyMax = _cMax(qMaxY);
171
+ for (let cx = cxMin; cx <= cxMax; cx++) for (let cy = cyMin; cy <= cyMax; cy++) {
172
+ const bucket = this._cells.get(_key(cx, cy));
173
+ if (bucket === void 0) continue;
174
+ for (let i = 0; i < bucket.length; i++) {
175
+ const e = bucket[i];
176
+ if (e._stamp === gen) continue;
177
+ e._stamp = gen;
178
+ if (e.maxX > qMinX && e.minX < qMaxX && e.maxY > qMinY && e.minY < qMaxY) out.push(e.item);
179
+ }
180
+ }
181
+ return out;
182
+ }
183
+ /** Remove all items. */
184
+ clear() {
185
+ this._data.length = 0;
186
+ this._slots.clear();
187
+ this._cells.clear();
188
+ }
189
+ _link(entry) {
190
+ const cxMin = _cMin(entry.minX);
191
+ const cxMax = _cMax(entry.maxX);
192
+ const cyMin = _cMin(entry.minY);
193
+ const cyMax = _cMax(entry.maxY);
194
+ for (let cx = cxMin; cx <= cxMax; cx++) for (let cy = cyMin; cy <= cyMax; cy++) {
195
+ const k = _key(cx, cy);
196
+ let b = this._cells.get(k);
197
+ if (b === void 0) {
198
+ b = [];
199
+ this._cells.set(k, b);
200
+ }
201
+ b.push(entry);
202
+ }
203
+ }
204
+ _unlink(entry) {
205
+ const cxMin = _cMin(entry.minX);
206
+ const cxMax = _cMax(entry.maxX);
207
+ const cyMin = _cMin(entry.minY);
208
+ const cyMax = _cMax(entry.maxY);
209
+ for (let cx = cxMin; cx <= cxMax; cx++) for (let cy = cyMin; cy <= cyMax; cy++) {
210
+ const b = this._cells.get(_key(cx, cy));
211
+ if (b === void 0) continue;
212
+ const i = b.indexOf(entry);
213
+ if (i !== -1) {
214
+ const last = b.pop();
215
+ if (i < b.length) b[i] = last;
216
+ }
217
+ }
218
+ }
130
219
  };
131
-
132
- // src/collision-world.ts
133
- import { Signal } from "@flare-engine/events";
134
- var ENTITY_SHIFT = 2 ** 26;
220
+ //#endregion
221
+ //#region src/collision-world.ts
222
+ const ENTITY_SHIFT = 2 ** 26;
135
223
  function encodePair(a, b) {
136
- const lo = a < b ? a : b;
137
- const hi = a < b ? b : a;
138
- return lo * ENTITY_SHIFT + hi;
224
+ const lo = a < b ? a : b;
225
+ const hi = a < b ? b : a;
226
+ return lo * ENTITY_SHIFT + hi;
139
227
  }
140
228
  function decodeLo(key) {
141
- return Math.floor(key / ENTITY_SHIFT);
229
+ return Math.floor(key / ENTITY_SHIFT);
142
230
  }
143
231
  function decodeHi(key) {
144
- return key - Math.floor(key / ENTITY_SHIFT) * ENTITY_SHIFT;
232
+ return key - Math.floor(key / ENTITY_SHIFT) * ENTITY_SHIFT;
145
233
  }
234
+ /**
235
+ * AABB collision world. Manages entities with shapes, detects overlaps each step,
236
+ * and emits collision/trigger signals.
237
+ */
146
238
  var CollisionWorld = class {
147
- onCollisionStart = new Signal();
148
- onCollisionEnd = new Signal();
149
- onTriggerEnter = new Signal();
150
- onTriggerExit = new Signal();
151
- entries = /* @__PURE__ */ new Map();
152
- spatial = new SpatialIndex();
153
- /**
154
- * Two pre-allocated pair buffers — swapped each step (no per-frame allocation).
155
- * Keys are packed numbers via `encodePair(a, b)`.
156
- */
157
- pairBufA = /* @__PURE__ */ new Set();
158
- pairBufB = /* @__PURE__ */ new Set();
159
- activePairs = this.pairBufA;
160
- /** Reusable query result buffer. */
161
- queryBuf = [];
162
- /** Reusable bounds rect — avoids per-entity Rect allocation in step(). */
163
- boundsBuf = { x: 0, y: 0, width: 0, height: 0 };
164
- /** Add an entity with a shape. */
165
- add(entity, shape, x, y, isTrigger = false, layer = 1, mask = 4294967295) {
166
- const entry = { entity, shape, x, y, isTrigger, layer, mask };
167
- this.entries.set(entity, entry);
168
- shapeBoundsInto(shape, x, y, this.boundsBuf);
169
- this.spatial.insert(entity, this.boundsBuf);
170
- }
171
- /** Remove an entity from the world. Emits exit signals for any active pairs. */
172
- remove(entity) {
173
- const entry = this.entries.get(entity);
174
- if (!entry) return;
175
- this.entries.delete(entity);
176
- this.spatial.remove(entity);
177
- for (const key of this.activePairs) {
178
- const lo = decodeLo(key);
179
- const hi = decodeHi(key);
180
- if (lo !== entity && hi !== entity) continue;
181
- this.activePairs.delete(key);
182
- const otherEntity = lo === entity ? hi : lo;
183
- const otherEntry = this.entries.get(otherEntity);
184
- const pair = { entityA: lo, entityB: hi };
185
- if (entry.isTrigger || otherEntry?.isTrigger) {
186
- this.onTriggerExit.emit(pair);
187
- } else {
188
- this.onCollisionEnd.emit(pair);
189
- }
190
- }
191
- }
192
- /** Update an entity's position. */
193
- setPosition(entity, x, y) {
194
- const entry = this.entries.get(entity);
195
- if (!entry) return;
196
- entry.x = x;
197
- entry.y = y;
198
- shapeBoundsInto(entry.shape, x, y, this.boundsBuf);
199
- this.spatial.update(entity, this.boundsBuf);
200
- }
201
- /** Number of entities in the world. */
202
- get size() {
203
- return this.entries.size;
204
- }
205
- /** Run one collision detection step. */
206
- step() {
207
- const newPairs = this.activePairs === this.pairBufA ? this.pairBufB : this.pairBufA;
208
- newPairs.clear();
209
- for (const [entityA, entryA] of this.entries) {
210
- shapeBoundsInto(entryA.shape, entryA.x, entryA.y, this.boundsBuf);
211
- this.queryBuf.length = 0;
212
- this.spatial.query(this.boundsBuf, this.queryBuf);
213
- for (let i = 0; i < this.queryBuf.length; i++) {
214
- const entityB = this.queryBuf[i];
215
- if (entityB <= entityA) continue;
216
- const entryB = this.entries.get(entityB);
217
- if (!entryB) continue;
218
- if ((entryA.layer & entryB.mask) === 0 && (entryB.layer & entryA.mask) === 0) continue;
219
- if (!shapeOverlap(entryA.shape, entryA.x, entryA.y, entryB.shape, entryB.x, entryB.y)) {
220
- continue;
221
- }
222
- newPairs.add(encodePair(entityA, entityB));
223
- }
224
- }
225
- for (const key of newPairs) {
226
- if (!this.activePairs.has(key)) {
227
- const lo = decodeLo(key);
228
- const hi = decodeHi(key);
229
- const a = this.entries.get(lo);
230
- const b = this.entries.get(hi);
231
- const pair = { entityA: lo, entityB: hi };
232
- if (a?.isTrigger || b?.isTrigger) {
233
- this.onTriggerEnter.emit(pair);
234
- } else {
235
- this.onCollisionStart.emit(pair);
236
- }
237
- }
238
- }
239
- for (const key of this.activePairs) {
240
- if (!newPairs.has(key)) {
241
- const lo = decodeLo(key);
242
- const hi = decodeHi(key);
243
- const a = this.entries.get(lo);
244
- const b = this.entries.get(hi);
245
- const pair = { entityA: lo, entityB: hi };
246
- if (a?.isTrigger || b?.isTrigger) {
247
- this.onTriggerExit.emit(pair);
248
- } else {
249
- this.onCollisionEnd.emit(pair);
250
- }
251
- }
252
- }
253
- this.activePairs = newPairs;
254
- }
255
- /** Remove all entities. */
256
- clear() {
257
- this.entries.clear();
258
- this.spatial.clear();
259
- this.pairBufA.clear();
260
- this.pairBufB.clear();
261
- this.activePairs = this.pairBufA;
262
- }
239
+ onCollisionStart = new Signal();
240
+ onCollisionEnd = new Signal();
241
+ onTriggerEnter = new Signal();
242
+ onTriggerExit = new Signal();
243
+ entries = /* @__PURE__ */ new Map();
244
+ spatial = new SpatialIndex();
245
+ /**
246
+ * Two pre-allocated pair buffers — swapped each step (no per-frame allocation).
247
+ * Keys are packed numbers via `encodePair(a, b)`.
248
+ */
249
+ pairBufA = /* @__PURE__ */ new Set();
250
+ pairBufB = /* @__PURE__ */ new Set();
251
+ activePairs = this.pairBufA;
252
+ /** Reusable query result buffer. */
253
+ queryBuf = [];
254
+ /** Reusable bounds rect — avoids per-entity Rect allocation in step(). */
255
+ boundsBuf = {
256
+ x: 0,
257
+ y: 0,
258
+ width: 0,
259
+ height: 0
260
+ };
261
+ /** Add an entity with a shape. */
262
+ add(entity, shape, x, y, isTrigger = false, layer = 1, mask = 4294967295) {
263
+ const entry = {
264
+ entity,
265
+ shape,
266
+ x,
267
+ y,
268
+ isTrigger,
269
+ layer,
270
+ mask
271
+ };
272
+ const exists = this.entries.has(entity);
273
+ this.entries.set(entity, entry);
274
+ shapeBoundsInto(shape, x, y, this.boundsBuf);
275
+ if (exists) this.spatial.update(entity, this.boundsBuf);
276
+ else this.spatial.insert(entity, this.boundsBuf);
277
+ }
278
+ /** Remove an entity from the world. Emits exit signals for any active pairs. */
279
+ remove(entity) {
280
+ const entry = this.entries.get(entity);
281
+ if (!entry) return;
282
+ this.entries.delete(entity);
283
+ this.spatial.remove(entity);
284
+ for (const key of this.activePairs) {
285
+ const lo = decodeLo(key);
286
+ const hi = decodeHi(key);
287
+ if (lo !== entity && hi !== entity) continue;
288
+ this.activePairs.delete(key);
289
+ const otherEntity = lo === entity ? hi : lo;
290
+ const otherEntry = this.entries.get(otherEntity);
291
+ const pair = {
292
+ entityA: lo,
293
+ entityB: hi
294
+ };
295
+ if (entry.isTrigger || otherEntry?.isTrigger) this.onTriggerExit.emit(pair);
296
+ else this.onCollisionEnd.emit(pair);
297
+ }
298
+ }
299
+ /** Update an entity's position. */
300
+ setPosition(entity, x, y) {
301
+ const entry = this.entries.get(entity);
302
+ if (!entry) return;
303
+ entry.x = x;
304
+ entry.y = y;
305
+ shapeBoundsInto(entry.shape, x, y, this.boundsBuf);
306
+ this.spatial.update(entity, this.boundsBuf);
307
+ }
308
+ /** Number of entities in the world. */
309
+ get size() {
310
+ return this.entries.size;
311
+ }
312
+ /** Number of broadphase records (one per live entity after add/remove). Diagnostic for broadphase growth. */
313
+ get broadphaseSize() {
314
+ return this.spatial.size;
315
+ }
316
+ /** Run one collision detection step. */
317
+ step() {
318
+ const newPairs = this.activePairs === this.pairBufA ? this.pairBufB : this.pairBufA;
319
+ newPairs.clear();
320
+ for (const entryA of this.entries.values()) {
321
+ const entityA = entryA.entity;
322
+ shapeBoundsInto(entryA.shape, entryA.x, entryA.y, this.boundsBuf);
323
+ this.queryBuf.length = 0;
324
+ this.spatial.query(this.boundsBuf, this.queryBuf);
325
+ for (let i = 0; i < this.queryBuf.length; i++) {
326
+ const entityB = this.queryBuf[i];
327
+ if (entityB <= entityA) continue;
328
+ const entryB = this.entries.get(entityB);
329
+ if (!entryB) continue;
330
+ if ((entryA.layer & entryB.mask) === 0 && (entryB.layer & entryA.mask) === 0) continue;
331
+ if (!shapeOverlap(entryA.shape, entryA.x, entryA.y, entryB.shape, entryB.x, entryB.y)) continue;
332
+ newPairs.add(encodePair(entityA, entityB));
333
+ }
334
+ }
335
+ for (const key of newPairs) if (!this.activePairs.has(key)) {
336
+ const lo = decodeLo(key);
337
+ const hi = decodeHi(key);
338
+ const a = this.entries.get(lo);
339
+ const b = this.entries.get(hi);
340
+ const pair = {
341
+ entityA: lo,
342
+ entityB: hi
343
+ };
344
+ if (a?.isTrigger || b?.isTrigger) this.onTriggerEnter.emit(pair);
345
+ else this.onCollisionStart.emit(pair);
346
+ }
347
+ for (const key of this.activePairs) if (!newPairs.has(key)) {
348
+ const lo = decodeLo(key);
349
+ const hi = decodeHi(key);
350
+ const a = this.entries.get(lo);
351
+ const b = this.entries.get(hi);
352
+ const pair = {
353
+ entityA: lo,
354
+ entityB: hi
355
+ };
356
+ if (a?.isTrigger || b?.isTrigger) this.onTriggerExit.emit(pair);
357
+ else this.onCollisionEnd.emit(pair);
358
+ }
359
+ this.activePairs = newPairs;
360
+ }
361
+ /** Zero-alloc collider bounds — writes the AABB of entity's shape into `out`. Returns null when entity is absent. */
362
+ getColliderBoundsInto(entity, out) {
363
+ const entry = this.entries.get(entity);
364
+ if (!entry) return null;
365
+ shapeBoundsInto(entry.shape, entry.x, entry.y, out);
366
+ return out;
367
+ }
368
+ /** Allocating convenience wrapper — returns a fresh Rect or null when entity is absent. */
369
+ getColliderBounds(entity) {
370
+ const entry = this.entries.get(entity);
371
+ if (!entry) return null;
372
+ return shapeBoundsInto(entry.shape, entry.x, entry.y, {
373
+ x: 0,
374
+ y: 0,
375
+ width: 0,
376
+ height: 0
377
+ });
378
+ }
379
+ /** Remove all entities. */
380
+ clear() {
381
+ this.entries.clear();
382
+ this.spatial.clear();
383
+ this.pairBufA.clear();
384
+ this.pairBufB.clear();
385
+ this.activePairs = this.pairBufA;
386
+ }
263
387
  };
264
-
265
- // src/collider.ts
266
- function createCollider(shape, opts) {
267
- return {
268
- shape,
269
- isTrigger: opts?.isTrigger ?? false,
270
- layer: opts?.layer ?? 1,
271
- mask: opts?.mask ?? 4294967295
272
- };
273
- }
274
-
275
- // src/raycast.ts
388
+ //#endregion
389
+ //#region src/raycast.ts
390
+ /**
391
+ * Cast a ray against a list of targets. Returns the closest hit, or null.
392
+ * @param ox Ray origin X
393
+ * @param oy Ray origin Y
394
+ * @param dx Ray direction X (should be normalized)
395
+ * @param dy Ray direction Y (should be normalized)
396
+ * @param maxDist Maximum raycast distance
397
+ * @param targets Array of entities to test against
398
+ */
276
399
  function raycast(ox, oy, dx, dy, maxDist, targets) {
277
- let closest = null;
278
- for (let i = 0; i < targets.length; i++) {
279
- const t = targets[i];
280
- const hit = rayVsShape(ox, oy, dx, dy, maxDist, t);
281
- if (hit && (closest === null || hit.distance < closest.distance)) {
282
- closest = hit;
283
- }
284
- }
285
- return closest;
400
+ let closest = null;
401
+ for (let i = 0; i < targets.length; i++) {
402
+ const t = targets[i];
403
+ const hit = rayVsShape(ox, oy, dx, dy, maxDist, t);
404
+ if (hit && (closest === null || hit.distance < closest.distance)) closest = hit;
405
+ }
406
+ return closest;
286
407
  }
287
408
  function rayVsShape(ox, oy, dx, dy, maxDist, target) {
288
- if (target.shape.type === "aabb") {
289
- return rayVsAABB(
290
- ox,
291
- oy,
292
- dx,
293
- dy,
294
- maxDist,
295
- target.entity,
296
- target.x,
297
- target.y,
298
- target.shape.hw,
299
- target.shape.hh
300
- );
301
- }
302
- return rayVsCircle(
303
- ox,
304
- oy,
305
- dx,
306
- dy,
307
- maxDist,
308
- target.entity,
309
- target.x,
310
- target.y,
311
- target.shape.radius
312
- );
409
+ if (target.shape.type === "aabb") return rayVsAABB(ox, oy, dx, dy, maxDist, target.entity, target.x, target.y, target.shape.hw, target.shape.hh);
410
+ return rayVsCircle(ox, oy, dx, dy, maxDist, target.entity, target.x, target.y, target.shape.radius);
313
411
  }
314
412
  function rayVsAABB(ox, oy, dx, dy, maxDist, entity, cx, cy, hw, hh) {
315
- const minX = cx - hw;
316
- const maxX = cx + hw;
317
- const minY = cy - hh;
318
- const maxY = cy + hh;
319
- const invDx = dx !== 0 ? 1 / dx : dx >= 0 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
320
- const invDy = dy !== 0 ? 1 / dy : dy >= 0 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
321
- const tx1 = (minX - ox) * invDx;
322
- const tx2 = (maxX - ox) * invDx;
323
- const ty1 = (minY - oy) * invDy;
324
- const ty2 = (maxY - oy) * invDy;
325
- const tMinX = Math.min(tx1, tx2);
326
- const tMaxX = Math.max(tx1, tx2);
327
- const tMinY = Math.min(ty1, ty2);
328
- const tMaxY = Math.max(ty1, ty2);
329
- const tMin = Math.max(tMinX, tMinY);
330
- const tMax = Math.min(tMaxX, tMaxY);
331
- if (tMax < 0 || tMin > tMax || tMin > maxDist) return null;
332
- const t = tMin >= 0 ? tMin : tMax;
333
- if (t > maxDist || t < 0) return null;
334
- const px = ox + dx * t;
335
- const py = oy + dy * t;
336
- let nx = 0;
337
- let ny = 0;
338
- if (tMinX > tMinY) {
339
- nx = dx < 0 ? 1 : -1;
340
- } else {
341
- ny = dy < 0 ? 1 : -1;
342
- }
343
- return {
344
- entity,
345
- distance: t,
346
- point: { x: px, y: py },
347
- normal: { x: nx, y: ny }
348
- };
413
+ const minX = cx - hw;
414
+ const maxX = cx + hw;
415
+ const minY = cy - hh;
416
+ const maxY = cy + hh;
417
+ const invDx = dx !== 0 ? 1 / dx : dx >= 0 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
418
+ const invDy = dy !== 0 ? 1 / dy : dy >= 0 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
419
+ const tx1 = (minX - ox) * invDx;
420
+ const tx2 = (maxX - ox) * invDx;
421
+ const ty1 = (minY - oy) * invDy;
422
+ const ty2 = (maxY - oy) * invDy;
423
+ const tMinX = Math.min(tx1, tx2);
424
+ const tMaxX = Math.max(tx1, tx2);
425
+ const tMinY = Math.min(ty1, ty2);
426
+ const tMaxY = Math.max(ty1, ty2);
427
+ const tMin = Math.max(tMinX, tMinY);
428
+ const tMax = Math.min(tMaxX, tMaxY);
429
+ if (tMax < 0 || tMin > tMax || tMin > maxDist) return null;
430
+ const t = tMin >= 0 ? tMin : tMax;
431
+ if (t > maxDist || t < 0) return null;
432
+ const px = ox + dx * t;
433
+ const py = oy + dy * t;
434
+ let nx = 0;
435
+ let ny = 0;
436
+ if (tMinX > tMinY) nx = dx < 0 ? 1 : -1;
437
+ else ny = dy < 0 ? 1 : -1;
438
+ return {
439
+ entity,
440
+ distance: t,
441
+ point: {
442
+ x: px,
443
+ y: py
444
+ },
445
+ normal: {
446
+ x: nx,
447
+ y: ny
448
+ }
449
+ };
349
450
  }
350
451
  function rayVsCircle(ox, oy, dx, dy, maxDist, entity, cx, cy, radius) {
351
- const fx = ox - cx;
352
- const fy = oy - cy;
353
- const a = dx * dx + dy * dy;
354
- const b = 2 * (fx * dx + fy * dy);
355
- const c = fx * fx + fy * fy - radius * radius;
356
- if (a < 1e-12) return null;
357
- const discriminant = b * b - 4 * a * c;
358
- if (discriminant < 0) return null;
359
- const sqrtDisc = Math.sqrt(discriminant);
360
- let t = (-b - sqrtDisc) / (2 * a);
361
- if (t < 0) {
362
- t = (-b + sqrtDisc) / (2 * a);
363
- }
364
- if (t < 0 || t > maxDist) return null;
365
- const px = ox + dx * t;
366
- const py = oy + dy * t;
367
- const nx = px - cx;
368
- const ny = py - cy;
369
- const len = Math.sqrt(nx * nx + ny * ny);
370
- return {
371
- entity,
372
- distance: t,
373
- point: { x: px, y: py },
374
- normal: len > 0 ? { x: nx / len, y: ny / len } : { x: 0, y: 0 }
375
- };
452
+ const fx = ox - cx;
453
+ const fy = oy - cy;
454
+ const a = dx * dx + dy * dy;
455
+ const b = 2 * (fx * dx + fy * dy);
456
+ const c = fx * fx + fy * fy - radius * radius;
457
+ if (a < 1e-12) return null;
458
+ const discriminant = b * b - 4 * a * c;
459
+ if (discriminant < 0) return null;
460
+ const sqrtDisc = Math.sqrt(discriminant);
461
+ let t = (-b - sqrtDisc) / (2 * a);
462
+ if (t < 0) t = (-b + sqrtDisc) / (2 * a);
463
+ if (t < 0 || t > maxDist) return null;
464
+ const px = ox + dx * t;
465
+ const py = oy + dy * t;
466
+ const nx = px - cx;
467
+ const ny = py - cy;
468
+ const len = Math.sqrt(nx * nx + ny * ny);
469
+ return {
470
+ entity,
471
+ distance: t,
472
+ point: {
473
+ x: px,
474
+ y: py
475
+ },
476
+ normal: len > 0 ? {
477
+ x: nx / len,
478
+ y: ny / len
479
+ } : {
480
+ x: 0,
481
+ y: 0
482
+ }
483
+ };
376
484
  }
377
-
378
- // src/solid-grid.ts
485
+ //#endregion
486
+ //#region src/solid-grid.ts
487
+ /**
488
+ * Build a `SolidGrid` from a list of solid tile positions.
489
+ * Input is structurally typed (`readonly SolidTile[]`) so the caller does not
490
+ * need to import `@flare-engine/tilemap` — physics stays tilemap-free.
491
+ */
379
492
  function buildSolidGrid(width, height, tileSize, tiles) {
380
- const solid = /* @__PURE__ */ new Set();
381
- for (const t of tiles) {
382
- solid.add(t.row * width + t.col);
383
- }
384
- return { width, height, tileSize, solid };
493
+ const solid = /* @__PURE__ */ new Set();
494
+ for (const t of tiles) solid.add(t.row * width + t.col);
495
+ return {
496
+ width,
497
+ height,
498
+ tileSize,
499
+ solid
500
+ };
385
501
  }
386
- var EDGE = 1e-4;
502
+ /**
503
+ * Half-open boundary constant: the AABB is treated as [min, max) so a box
504
+ * whose max edge lands exactly on a tile boundary does NOT overlap that tile.
505
+ */
506
+ const EDGE = 1e-4;
507
+ /**
508
+ * Returns `true` when an axis-aligned box centered at (`x`, `y`) with
509
+ * half-extents (`halfW`, `halfH`) overlaps a solid tile or lies outside the
510
+ * map boundary. Uses half-open EDGE semantics on max edges.
511
+ */
387
512
  function isBlockedAABB(grid, x, y, halfW, halfH) {
388
- const ts = grid.tileSize;
389
- const minCol = Math.floor((x - halfW) / ts);
390
- const maxCol = Math.floor((x + halfW - EDGE) / ts);
391
- const minRow = Math.floor((y - halfH) / ts);
392
- const maxRow = Math.floor((y + halfH - EDGE) / ts);
393
- if (minCol < 0 || minRow < 0 || maxCol >= grid.width || maxRow >= grid.height) {
394
- return true;
395
- }
396
- for (let row = minRow; row <= maxRow; row++) {
397
- for (let col = minCol; col <= maxCol; col++) {
398
- if (grid.solid.has(row * grid.width + col)) {
399
- return true;
400
- }
401
- }
402
- }
403
- return false;
513
+ const ts = grid.tileSize;
514
+ const minCol = Math.floor((x - halfW) / ts);
515
+ const maxCol = Math.floor((x + halfW - EDGE) / ts);
516
+ const minRow = Math.floor((y - halfH) / ts);
517
+ const maxRow = Math.floor((y + halfH - EDGE) / ts);
518
+ if (minCol < 0 || minRow < 0 || maxCol >= grid.width || maxRow >= grid.height) return true;
519
+ for (let row = minRow; row <= maxRow; row++) for (let col = minCol; col <= maxCol; col++) if (grid.solid.has(row * grid.width + col)) return true;
520
+ return false;
404
521
  }
522
+ /**
523
+ * Axis-separated slide movement. Attempts to move by (`dx`, `dy`); each axis
524
+ * is applied independently so a blocked diagonal input slides along the wall.
525
+ * The y-check uses the already-updated x position.
526
+ * Zero-alloc: writes result into the provided `out` Vec2 and returns it.
527
+ */
405
528
  function moveAndSlideInto(grid, x, y, dx, dy, halfW, halfH, out) {
406
- let nx = x;
407
- let ny = y;
408
- if (dx !== 0 && !isBlockedAABB(grid, nx + dx, ny, halfW, halfH)) nx += dx;
409
- if (dy !== 0 && !isBlockedAABB(grid, nx, ny + dy, halfW, halfH)) ny += dy;
410
- out.x = nx;
411
- out.y = ny;
412
- return out;
529
+ let nx = x;
530
+ let ny = y;
531
+ if (dx !== 0 && !isBlockedAABB(grid, nx + dx, ny, halfW, halfH)) nx += dx;
532
+ if (dy !== 0 && !isBlockedAABB(grid, nx, ny + dy, halfW, halfH)) ny += dy;
533
+ out.x = nx;
534
+ out.y = ny;
535
+ return out;
413
536
  }
414
- export {
415
- AABB,
416
- CircleShape,
417
- CollisionWorld,
418
- SpatialIndex,
419
- buildSolidGrid,
420
- createCollider,
421
- isBlockedAABB,
422
- moveAndSlideInto,
423
- raycast,
424
- shapeBounds,
425
- shapeBoundsInto,
426
- shapeOverlap
427
- };
537
+ //#endregion
538
+ export { AABB, CircleShape, CollisionWorld, SpatialIndex, buildSolidGrid, createCollider, isBlockedAABB, moveAndSlideInto, raycast, shapeBounds, shapeBoundsInto, shapeOverlap };
539
+
428
540
  //# sourceMappingURL=index.mjs.map