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