@flare-engine/core 0.2.1 → 0.3.0

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,459 +1,573 @@
1
- // src/clock.ts
2
- var Clock = class {
3
- /** Unscaled delta time in seconds since last frame. */
4
- rawDt = 0;
5
- /** Scaled delta time in seconds (rawDt * timescale). */
6
- dt = 0;
7
- /** Fixed timestep in seconds for physics updates (default 1/60). */
8
- fixedDt = 1 / 60;
9
- /** Total elapsed time in seconds (scaled). */
10
- elapsed = 0;
11
- /** Smoothed frames per second. */
12
- fps = 0;
13
- /** Time scale multiplier. 1 = normal, 0 = paused, 0.5 = slow-mo. */
14
- timescale = 1;
15
- /** Current frame number (monotonically increasing). */
16
- frame = 0;
17
- schedules = [];
18
- fpsAlpha = 0.9;
19
- /** Called once per frame by the GameLoop with raw unscaled dt. */
20
- update(rawDt) {
21
- this.rawDt = rawDt;
22
- this.dt = rawDt * this.timescale;
23
- this.elapsed += this.dt;
24
- this.frame++;
25
- if (rawDt > 0) {
26
- const instantFps = 1 / rawDt;
27
- this.fps = this.fps === 0 ? instantFps : this.fps * this.fpsAlpha + instantFps * (1 - this.fpsAlpha);
28
- }
29
- this.tickSchedules(this.dt);
30
- }
31
- /** Schedule a one-shot callback after `delay` seconds (scaled time). */
32
- schedule(delay, callback) {
33
- const entry = { remaining: delay, callback, interval: 0 };
34
- this.schedules.push(entry);
35
- return () => {
36
- const idx = this.schedules.indexOf(entry);
37
- if (idx !== -1) this.schedules.splice(idx, 1);
38
- };
39
- }
40
- /** Schedule a repeating callback every `interval` seconds (scaled time). */
41
- repeat(interval, callback) {
42
- const entry = { remaining: interval, callback, interval };
43
- this.schedules.push(entry);
44
- return () => {
45
- const idx = this.schedules.indexOf(entry);
46
- if (idx !== -1) this.schedules.splice(idx, 1);
47
- };
48
- }
49
- /** Reset clock to initial state. */
50
- reset() {
51
- this.rawDt = 0;
52
- this.dt = 0;
53
- this.elapsed = 0;
54
- this.fps = 0;
55
- this.frame = 0;
56
- this.timescale = 1;
57
- this.schedules.length = 0;
58
- }
59
- tickSchedules(dt) {
60
- for (let i = this.schedules.length - 1; i >= 0; i--) {
61
- const entry = this.schedules[i];
62
- entry.remaining -= dt;
63
- if (entry.remaining <= 0) {
64
- entry.callback();
65
- if (entry.interval > 0) {
66
- entry.remaining += entry.interval;
67
- } else {
68
- this.schedules.splice(i, 1);
69
- }
70
- }
71
- }
72
- }
73
- };
74
-
75
- // src/game-loop.ts
76
1
  import { Signal } from "@flare-engine/events";
77
- var GameLoop = class {
78
- clock = new Clock();
79
- /** Fixed-timestep update (physics, deterministic logic). */
80
- onFixedUpdate = new Signal();
81
- /** Variable-timestep update (movement, AI, game logic). */
82
- onUpdate = new Signal();
83
- /** Runs after onUpdate (camera follow, post-processing logic). */
84
- onLateUpdate = new Signal();
85
- /** Runs before rendering. */
86
- onPreRender = new Signal();
87
- /** Runs after rendering. */
88
- onPostRender = new Signal();
89
- running = false;
90
- paused = false;
91
- accumulator = 0;
92
- maxDt;
93
- rafId = 0;
94
- lastTime = 0;
95
- /** External tick function — set this for testing or custom scheduling. */
96
- tick;
97
- /** External cancel function — paired with tick. */
98
- cancelTick;
99
- constructor(config) {
100
- this.maxDt = config?.maxDt ?? 0.25;
101
- if (config?.fixedDt !== void 0) {
102
- this.clock.fixedDt = config.fixedDt;
103
- }
104
- }
105
- /** Start the game loop. */
106
- start() {
107
- if (this.running) return;
108
- this.running = true;
109
- this.paused = false;
110
- this.lastTime = 0;
111
- this.accumulator = 0;
112
- this.scheduleFrame();
113
- }
114
- /** Stop the game loop entirely and reset. */
115
- stop() {
116
- this.running = false;
117
- this.paused = false;
118
- if (this.rafId !== 0) {
119
- const cancel = this.cancelTick ?? cancelAnimationFrame;
120
- cancel(this.rafId);
121
- this.rafId = 0;
122
- }
123
- }
124
- /** Pause — signals stop firing but loop stays alive. */
125
- pause() {
126
- if (!this.running || this.paused) return;
127
- this.paused = true;
128
- }
129
- /** Resume from pause. */
130
- resume() {
131
- if (!this.running || !this.paused) return;
132
- this.paused = false;
133
- this.lastTime = 0;
134
- }
135
- /** Whether the loop is currently running (started and not stopped). */
136
- get isRunning() {
137
- return this.running;
138
- }
139
- /** Whether the loop is paused. */
140
- get isPaused() {
141
- return this.paused;
142
- }
143
- /** Process a single frame. Exposed for testing. */
144
- step(rawDt) {
145
- if (this.paused) return;
146
- const capped = Math.min(rawDt, this.maxDt);
147
- this.clock.update(capped);
148
- const dt = this.clock.dt;
149
- const fixedDt = this.clock.fixedDt;
150
- this.accumulator += dt;
151
- while (this.accumulator >= fixedDt) {
152
- this.onFixedUpdate.emit(fixedDt);
153
- this.accumulator -= fixedDt;
154
- }
155
- this.onUpdate.emit(dt);
156
- this.onLateUpdate.emit(dt);
157
- this.onPreRender.emit();
158
- this.onPostRender.emit();
159
- }
160
- scheduleFrame() {
161
- const request = this.tick ?? requestAnimationFrame;
162
- this.rafId = request((time) => {
163
- if (!this.running) return;
164
- if (this.lastTime === 0) {
165
- this.lastTime = time;
166
- this.scheduleFrame();
167
- return;
168
- }
169
- const rawDt = (time - this.lastTime) / 1e3;
170
- this.lastTime = time;
171
- this.step(rawDt);
172
- this.scheduleFrame();
173
- });
174
- }
175
- };
176
-
177
- // src/app-lifecycle.ts
178
- import { Signal as Signal2 } from "@flare-engine/events";
2
+ //#region src/app-lifecycle.ts
3
+ /**
4
+ * AppLifecycle bridges React Native AppState to the game loop.
5
+ *
6
+ * - Auto-pauses the loop when app goes to background
7
+ * - Auto-resumes when app returns to foreground
8
+ * - Caps dt on resume to prevent huge time jumps
9
+ *
10
+ * In non-RN environments (tests, web), use the manual methods.
11
+ */
179
12
  var AppLifecycle = class {
180
- /** Fires when app enters background. */
181
- onBackground = new Signal2();
182
- /** Fires when app returns to foreground. */
183
- onForeground = new Signal2();
184
- /** Fires on memory warning (RN-specific). */
185
- onMemoryWarning = new Signal2();
186
- loop;
187
- wasRunningBeforeBackground = false;
188
- constructor(loop) {
189
- this.loop = loop;
190
- }
191
- /** Call when app goes to background. */
192
- background() {
193
- this.wasRunningBeforeBackground = this.loop.isRunning && !this.loop.isPaused;
194
- if (this.wasRunningBeforeBackground) {
195
- this.loop.pause();
196
- }
197
- this.onBackground.emit();
198
- }
199
- /** Call when app returns to foreground. */
200
- foreground() {
201
- if (this.wasRunningBeforeBackground) {
202
- this.loop.resume();
203
- }
204
- this.onForeground.emit();
205
- }
206
- /** Call on memory warning. */
207
- memoryWarning() {
208
- this.onMemoryWarning.emit();
209
- }
13
+ /** Fires when app enters background. */
14
+ onBackground = new Signal();
15
+ /** Fires when app returns to foreground. */
16
+ onForeground = new Signal();
17
+ /** Fires on memory warning (RN-specific). */
18
+ onMemoryWarning = new Signal();
19
+ loop;
20
+ wasRunningBeforeBackground = false;
21
+ _inBackground = false;
22
+ constructor(loop) {
23
+ this.loop = loop;
24
+ }
25
+ /** Call when app goes to background. */
26
+ background() {
27
+ if (this._inBackground) return;
28
+ this._inBackground = true;
29
+ this.wasRunningBeforeBackground = this.loop.isRunning && !this.loop.isPaused;
30
+ if (this.wasRunningBeforeBackground) this.loop.pause();
31
+ this.onBackground.emit();
32
+ }
33
+ /** Call when app returns to foreground. */
34
+ foreground() {
35
+ this._inBackground = false;
36
+ if (this.wasRunningBeforeBackground) this.loop.resume();
37
+ this.onForeground.emit();
38
+ }
39
+ /** Call on memory warning. */
40
+ memoryWarning() {
41
+ this.onMemoryWarning.emit();
42
+ }
210
43
  };
211
-
212
- // src/screen.ts
213
- import { Signal as Signal3 } from "@flare-engine/events";
214
- var ScreenManager = class {
215
- /** Design resolution width. */
216
- designWidth;
217
- /** Design resolution height. */
218
- designHeight;
219
- /** Current scale mode. */
220
- scaleMode;
221
- /** Device pixel ratio. */
222
- pixelRatio = 1;
223
- /** Safe area insets (top, right, bottom, left) in device pixels. */
224
- safeArea = { x: 0, y: 0, width: 0, height: 0 };
225
- /** Fires when screen dimensions change. */
226
- onResize = new Signal3();
227
- /** Computed scale factor X (design → screen). */
228
- scaleX = 1;
229
- /** Computed scale factor Y (design → screen). */
230
- scaleY = 1;
231
- /** Offset X in screen pixels (for letterboxing). */
232
- offsetX = 0;
233
- /** Offset Y in screen pixels (for letterboxing). */
234
- offsetY = 0;
235
- screenWidth = 0;
236
- screenHeight = 0;
237
- constructor(config) {
238
- this.designWidth = config.designWidth;
239
- this.designHeight = config.designHeight;
240
- this.scaleMode = config.scaleMode ?? "fit";
241
- }
242
- safeInsetTop = 0;
243
- safeInsetRight = 0;
244
- safeInsetBottom = 0;
245
- safeInsetLeft = 0;
246
- /** Update with actual device screen dimensions. Call on mount and resize. */
247
- resize(screenWidth, screenHeight, pixelRatio) {
248
- this.screenWidth = screenWidth;
249
- this.screenHeight = screenHeight;
250
- if (pixelRatio !== void 0) this.pixelRatio = pixelRatio;
251
- this.recalculate();
252
- this.recalculateSafeArea();
253
- this.onResize.emit();
254
- }
255
- /**
256
- * Set safe-area insets in screen pixels. Call this from the RN host with values from
257
- * `react-native-safe-area-context`. Populates `safeArea` as the usable region.
258
- */
259
- setSafeAreaInsets(top, right, bottom, left) {
260
- this.safeInsetTop = top;
261
- this.safeInsetRight = right;
262
- this.safeInsetBottom = bottom;
263
- this.safeInsetLeft = left;
264
- this.recalculateSafeArea();
265
- this.onResize.emit();
266
- }
267
- recalculateSafeArea() {
268
- this.safeArea.x = this.safeInsetLeft;
269
- this.safeArea.y = this.safeInsetTop;
270
- this.safeArea.width = Math.max(0, this.screenWidth - this.safeInsetLeft - this.safeInsetRight);
271
- this.safeArea.height = Math.max(
272
- 0,
273
- this.screenHeight - this.safeInsetTop - this.safeInsetBottom
274
- );
275
- }
276
- /** Convert design-space point to screen-space. */
277
- designToScreen(point) {
278
- return {
279
- x: point.x * this.scaleX + this.offsetX,
280
- y: point.y * this.scaleY + this.offsetY
281
- };
282
- }
283
- /** Convert screen-space point to design-space. */
284
- screenToDesign(point) {
285
- return {
286
- x: (point.x - this.offsetX) / this.scaleX,
287
- y: (point.y - this.offsetY) / this.scaleY
288
- };
289
- }
290
- /** Viewport rect in design coordinates (visible area). */
291
- get viewport() {
292
- if (this.scaleMode === "fill") {
293
- const visibleW = this.screenWidth / this.scaleX;
294
- const visibleH = this.screenHeight / this.scaleY;
295
- return {
296
- x: (this.designWidth - visibleW) / 2,
297
- y: (this.designHeight - visibleH) / 2,
298
- width: visibleW,
299
- height: visibleH
300
- };
301
- }
302
- return { x: 0, y: 0, width: this.designWidth, height: this.designHeight };
303
- }
304
- recalculate() {
305
- const ratioX = this.screenWidth / this.designWidth;
306
- const ratioY = this.screenHeight / this.designHeight;
307
- switch (this.scaleMode) {
308
- case "fit": {
309
- const scale = Math.min(ratioX, ratioY);
310
- this.scaleX = scale;
311
- this.scaleY = scale;
312
- this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;
313
- this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;
314
- break;
315
- }
316
- case "fill": {
317
- const scale = Math.max(ratioX, ratioY);
318
- this.scaleX = scale;
319
- this.scaleY = scale;
320
- this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;
321
- this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;
322
- break;
323
- }
324
- case "stretch": {
325
- this.scaleX = ratioX;
326
- this.scaleY = ratioY;
327
- this.offsetX = 0;
328
- this.offsetY = 0;
329
- break;
330
- }
331
- }
332
- }
44
+ //#endregion
45
+ //#region src/clock.ts
46
+ var Clock = class {
47
+ /** Unscaled delta time in seconds since last frame. */
48
+ rawDt = 0;
49
+ /** Scaled delta time in seconds (rawDt * timescale). */
50
+ dt = 0;
51
+ /** Fixed timestep in seconds for physics updates (default 1/60). */
52
+ fixedDt = 1 / 60;
53
+ /** Total elapsed time in seconds (scaled). */
54
+ elapsed = 0;
55
+ /** Smoothed frames per second. */
56
+ fps = 0;
57
+ /** Time scale multiplier. 1 = normal, 0 = paused, 0.5 = slow-mo. */
58
+ timescale = 1;
59
+ /** Current frame number (monotonically increasing). */
60
+ frame = 0;
61
+ schedules = [];
62
+ fpsAlpha = .9;
63
+ /** Called once per frame by the GameLoop with raw unscaled dt. */
64
+ update(rawDt) {
65
+ this.rawDt = rawDt;
66
+ this.dt = rawDt * this.timescale;
67
+ this.elapsed += this.dt;
68
+ this.frame++;
69
+ if (rawDt > 0) {
70
+ const instantFps = 1 / rawDt;
71
+ this.fps = this.fps === 0 ? instantFps : this.fps * this.fpsAlpha + instantFps * (1 - this.fpsAlpha);
72
+ }
73
+ this.tickSchedules(this.dt);
74
+ }
75
+ /** Schedule a one-shot callback after `delay` seconds (scaled time). */
76
+ schedule(delay, callback) {
77
+ const entry = {
78
+ remaining: delay,
79
+ callback,
80
+ interval: 0
81
+ };
82
+ this.schedules.push(entry);
83
+ return () => {
84
+ const idx = this.schedules.indexOf(entry);
85
+ if (idx !== -1) this.schedules.splice(idx, 1);
86
+ };
87
+ }
88
+ /** Schedule a repeating callback every `interval` seconds (scaled time). */
89
+ repeat(interval, callback) {
90
+ const entry = {
91
+ remaining: interval,
92
+ callback,
93
+ interval
94
+ };
95
+ this.schedules.push(entry);
96
+ return () => {
97
+ const idx = this.schedules.indexOf(entry);
98
+ if (idx !== -1) this.schedules.splice(idx, 1);
99
+ };
100
+ }
101
+ /** Reset clock to initial state. */
102
+ reset() {
103
+ this.rawDt = 0;
104
+ this.dt = 0;
105
+ this.elapsed = 0;
106
+ this.fps = 0;
107
+ this.frame = 0;
108
+ this.timescale = 1;
109
+ this.schedules.length = 0;
110
+ }
111
+ tickSchedules(dt) {
112
+ for (let i = this.schedules.length - 1; i >= 0; i--) {
113
+ const entry = this.schedules[i];
114
+ if (entry === void 0) continue;
115
+ entry.remaining -= dt;
116
+ if (entry.remaining <= 0) {
117
+ entry.callback();
118
+ if (entry.interval > 0) entry.remaining += entry.interval;
119
+ else {
120
+ const idx = this.schedules.indexOf(entry);
121
+ if (idx !== -1) this.schedules.splice(idx, 1);
122
+ }
123
+ }
124
+ }
125
+ }
333
126
  };
334
-
335
- // src/coroutine.ts
127
+ //#endregion
128
+ //#region src/coroutine.ts
129
+ /**
130
+ * CoroutineManager runs generator-based coroutines.
131
+ * Call update(dt) each frame to advance all active coroutines.
132
+ */
336
133
  var CoroutineManager = class {
337
- coroutines = [];
338
- /** Start a new coroutine. Returns a handle to check status or cancel. */
339
- start(gen) {
340
- const state = {
341
- gen,
342
- waitTime: 0,
343
- waitingForPromise: false,
344
- done: false
345
- };
346
- this.coroutines.push(state);
347
- this.advance(state);
348
- const handle = {
349
- get done() {
350
- return state.done;
351
- },
352
- cancel() {
353
- state.done = true;
354
- }
355
- };
356
- return handle;
357
- }
358
- /** Update all running coroutines. Call once per frame with scaled dt. */
359
- update(dt) {
360
- for (let i = this.coroutines.length - 1; i >= 0; i--) {
361
- const state = this.coroutines[i];
362
- if (state.done) {
363
- this.coroutines.splice(i, 1);
364
- continue;
365
- }
366
- if (state.waitingForPromise) continue;
367
- if (state.waitTime > 0) {
368
- state.waitTime -= dt;
369
- if (state.waitTime > 0) continue;
370
- }
371
- this.advance(state);
372
- if (state.done) {
373
- this.coroutines.splice(i, 1);
374
- }
375
- }
376
- }
377
- /** Cancel all running coroutines. */
378
- clear() {
379
- for (const state of this.coroutines) {
380
- state.done = true;
381
- }
382
- this.coroutines.length = 0;
383
- }
384
- /** Number of active coroutines. */
385
- get count() {
386
- return this.coroutines.length;
387
- }
388
- advance(state) {
389
- const result = state.gen.next();
390
- if (result.done) {
391
- state.done = true;
392
- return;
393
- }
394
- const value = result.value;
395
- if (typeof value === "number") {
396
- state.waitTime = value;
397
- } else if (value instanceof Promise) {
398
- state.waitingForPromise = true;
399
- value.then(
400
- () => {
401
- state.waitingForPromise = false;
402
- },
403
- () => {
404
- state.done = true;
405
- }
406
- );
407
- }
408
- }
134
+ coroutines = [];
135
+ /** Start a new coroutine. Returns a handle to check status or cancel. */
136
+ start(gen) {
137
+ const state = {
138
+ gen,
139
+ waitTime: 0,
140
+ waitingForPromise: false,
141
+ done: false
142
+ };
143
+ this.coroutines.push(state);
144
+ this.advance(state);
145
+ return {
146
+ get done() {
147
+ return state.done;
148
+ },
149
+ cancel() {
150
+ state.done = true;
151
+ }
152
+ };
153
+ }
154
+ /** Update all running coroutines. Call once per frame with scaled dt. */
155
+ update(dt) {
156
+ for (let i = this.coroutines.length - 1; i >= 0; i--) {
157
+ const state = this.coroutines[i];
158
+ if (state === void 0) continue;
159
+ if (state.done) {
160
+ this.coroutines.splice(i, 1);
161
+ continue;
162
+ }
163
+ if (state.waitingForPromise) continue;
164
+ if (state.waitTime > 0) {
165
+ state.waitTime -= dt;
166
+ if (state.waitTime > 0) continue;
167
+ }
168
+ this.advance(state);
169
+ if (state.done) this.coroutines.splice(i, 1);
170
+ }
171
+ }
172
+ /** Cancel all running coroutines. */
173
+ clear() {
174
+ for (const state of this.coroutines) state.done = true;
175
+ this.coroutines.length = 0;
176
+ }
177
+ /** Number of active coroutines. */
178
+ get count() {
179
+ return this.coroutines.length;
180
+ }
181
+ advance(state) {
182
+ const result = state.gen.next();
183
+ if (result.done) {
184
+ state.done = true;
185
+ return;
186
+ }
187
+ const value = result.value;
188
+ if (typeof value === "number") state.waitTime = value;
189
+ else if (value instanceof Promise) {
190
+ state.waitingForPromise = true;
191
+ value.then(() => {
192
+ state.waitingForPromise = false;
193
+ }, () => {
194
+ state.done = true;
195
+ });
196
+ }
197
+ }
409
198
  };
410
-
411
- // src/pool.ts
199
+ //#endregion
200
+ //#region src/game-loop.ts
201
+ /**
202
+ * GameLoop drives the update cycle using fixed + variable timestep.
203
+ *
204
+ * Fixed updates run at a constant rate (accumulator pattern).
205
+ * Variable updates run once per frame with the actual dt.
206
+ */
207
+ var GameLoop = class {
208
+ clock = new Clock();
209
+ /** Fixed-timestep update (physics, deterministic logic). */
210
+ onFixedUpdate = new Signal();
211
+ /** Variable-timestep update (movement, AI, game logic). */
212
+ onUpdate = new Signal();
213
+ /** Runs after onUpdate (camera follow, post-processing logic). */
214
+ onLateUpdate = new Signal();
215
+ /** Runs before rendering. */
216
+ onPreRender = new Signal();
217
+ /** Runs after rendering. */
218
+ onPostRender = new Signal();
219
+ running = false;
220
+ paused = false;
221
+ accumulator = 0;
222
+ maxDt;
223
+ rafId = 0;
224
+ lastTime = 0;
225
+ _hasFixedDt = false;
226
+ /** External tick function — set this for testing or custom scheduling. */
227
+ tick;
228
+ /** External cancel function — paired with tick. */
229
+ cancelTick;
230
+ constructor(config) {
231
+ this.maxDt = config?.maxDt ?? .25;
232
+ if (config?.fixedDt !== void 0) {
233
+ if (config.fixedDt <= 0) throw new Error("GameLoop: fixedDt must be > 0");
234
+ this.clock.fixedDt = config.fixedDt;
235
+ this._hasFixedDt = true;
236
+ }
237
+ }
238
+ /** Start the game loop. */
239
+ start() {
240
+ if (this.running) return;
241
+ this.running = true;
242
+ this.paused = false;
243
+ this.lastTime = 0;
244
+ this.accumulator = 0;
245
+ this.scheduleFrame();
246
+ }
247
+ /** Stop the game loop entirely and reset. */
248
+ stop() {
249
+ this.running = false;
250
+ this.paused = false;
251
+ if (this.rafId !== 0) {
252
+ (this.cancelTick ?? cancelAnimationFrame)(this.rafId);
253
+ this.rafId = 0;
254
+ }
255
+ }
256
+ /** Pause — signals stop firing but loop stays alive. */
257
+ pause() {
258
+ if (!this.running || this.paused) return;
259
+ this.paused = true;
260
+ }
261
+ /** Resume from pause. */
262
+ resume() {
263
+ if (!this.running || !this.paused) return;
264
+ this.paused = false;
265
+ this.lastTime = 0;
266
+ }
267
+ /** Whether the loop is currently running (started and not stopped). */
268
+ get isRunning() {
269
+ return this.running;
270
+ }
271
+ /** Whether the loop is paused. */
272
+ get isPaused() {
273
+ return this.paused;
274
+ }
275
+ /**
276
+ * Post-step residual fraction for physics interpolation.
277
+ *
278
+ * After fixed updates drain the accumulator, `alpha` is the fraction of a
279
+ * fixed step that has elapsed since the last fixed tick — always in [0, 1).
280
+ * Read in `onPreRender` to lerp between the previous and current physics
281
+ * state for smooth visuals at any display refresh rate.
282
+ *
283
+ * Returns 0 when no fixed step was configured (i.e. `fixedDt` was not
284
+ * passed to the constructor).
285
+ */
286
+ get alpha() {
287
+ return this._hasFixedDt ? this.accumulator / this.clock.fixedDt : 0;
288
+ }
289
+ /** Process a single frame. Exposed for testing. */
290
+ step(rawDt) {
291
+ if (this.paused) return;
292
+ const capped = Math.min(rawDt, this.maxDt);
293
+ this.clock.update(capped);
294
+ const dt = this.clock.dt;
295
+ const fixedDt = this.clock.fixedDt;
296
+ if (fixedDt <= 0) throw new Error("GameLoop: fixedDt must be > 0");
297
+ this.accumulator += dt;
298
+ while (this.accumulator >= fixedDt) {
299
+ this.onFixedUpdate.emit(fixedDt);
300
+ this.accumulator -= fixedDt;
301
+ }
302
+ this.onUpdate.emit(dt);
303
+ this.onLateUpdate.emit(dt);
304
+ this.onPreRender.emit();
305
+ this.onPostRender.emit();
306
+ }
307
+ scheduleFrame() {
308
+ const request = this.tick ?? requestAnimationFrame;
309
+ this.rafId = request((time) => {
310
+ if (!this.running) return;
311
+ if (this.lastTime === 0) {
312
+ this.lastTime = time;
313
+ this.scheduleFrame();
314
+ return;
315
+ }
316
+ const rawDt = (time - this.lastTime) / 1e3;
317
+ this.lastTime = time;
318
+ this.step(rawDt);
319
+ this.scheduleFrame();
320
+ });
321
+ }
322
+ };
323
+ //#endregion
324
+ //#region src/pool.ts
325
+ /**
326
+ * Dev-flag access for `release()`, which runs once per released object.
327
+ *
328
+ * JSC has no inline cache for an unresolvable global identifier, so reading the
329
+ * bare `__DEV__` identifier behind a `typeof` guard costs ~270 ns *per
330
+ * evaluation* wherever the global is undeclared. React Native always defines it;
331
+ * web/CanvasKit and any Node or Bun consumer does not. A property miss on
332
+ * `globalThis` is inline-cached at ~0.46 ns and stays togglable at runtime
333
+ * exactly as before. Measured B28 (on JSC — V8 was never measured), PERF-10.
334
+ *
335
+ * Phrased without the literal old expression so `tests/pool-dist.test.ts` can
336
+ * count its occurrences in the built artifact: exactly one must survive, the
337
+ * constructor's.
338
+ *
339
+ * The constructor below deliberately keeps the identifier form: it runs once
340
+ * per pool, where ~270 ns is free, and it is the site a bundler can
341
+ * constant-fold for dead-code elimination.
342
+ */
343
+ const G = globalThis;
344
+ /**
345
+ * Generic object pool for zero-alloc gameplay.
346
+ *
347
+ * - acquire() returns a recycled or newly created object (uncapped)
348
+ * - tryAcquire() returns null when the live count is at capacity
349
+ * - release(obj) returns it to the pool
350
+ * - prewarm(count) pre-allocates objects
351
+ */
412
352
  var Pool = class {
413
- items = [];
414
- factory;
415
- resetFn;
416
- /**
417
- * @param factory Function to create a new instance.
418
- * @param reset Optional function to reset an object before reuse.
419
- */
420
- constructor(factory, reset) {
421
- this.factory = factory;
422
- this.resetFn = reset;
423
- }
424
- /** Get an object from the pool (or create a new one). */
425
- acquire() {
426
- if (this.items.length > 0) {
427
- return this.items.pop();
428
- }
429
- return this.factory();
430
- }
431
- /** Return an object to the pool. Calls reset if configured. */
432
- release(item) {
433
- if (this.resetFn) this.resetFn(item);
434
- this.items.push(item);
435
- }
436
- /** Pre-allocate objects into the pool. */
437
- prewarm(count) {
438
- for (let i = 0; i < count; i++) {
439
- this.items.push(this.factory());
440
- }
441
- }
442
- /** Number of available objects in the pool. */
443
- get available() {
444
- return this.items.length;
445
- }
446
- /** Clear all pooled objects. */
447
- clear() {
448
- this.items.length = 0;
449
- }
353
+ items = [];
354
+ factory;
355
+ resetFn;
356
+ _capacity;
357
+ _live = 0;
358
+ _created = 0;
359
+ _liveSet;
360
+ /**
361
+ * @param factory Function to create a new instance.
362
+ * @param reset Optional function to reset an object before reuse.
363
+ * @param options Optional pool configuration (capacity cap).
364
+ */
365
+ constructor(factory, reset, options) {
366
+ this.factory = factory;
367
+ this.resetFn = reset;
368
+ this._capacity = options?.capacity;
369
+ if (typeof __DEV__ !== "undefined" && __DEV__) this._liveSet = /* @__PURE__ */ new Set();
370
+ }
371
+ /** Get an object from the pool (or create a new one). Never throws; may exceed capacity. */
372
+ acquire() {
373
+ this._live++;
374
+ let item;
375
+ if (this.items.length > 0) item = this.items.pop();
376
+ else {
377
+ this._created++;
378
+ item = this.factory();
379
+ }
380
+ this._liveSet?.delete(item);
381
+ return item;
382
+ }
383
+ /**
384
+ * Get an object from the pool only if the live count is below capacity.
385
+ * Returns null when at cap — the caller must handle null (no allocation occurs).
386
+ * When no capacity was configured, behaves identically to acquire().
387
+ */
388
+ tryAcquire() {
389
+ if (this._capacity !== void 0 && this._live >= this._capacity) return null;
390
+ this._live++;
391
+ let item;
392
+ if (this.items.length > 0) item = this.items.pop();
393
+ else {
394
+ this._created++;
395
+ item = this.factory();
396
+ }
397
+ this._liveSet?.delete(item);
398
+ return item;
399
+ }
400
+ /** Return an object to the pool. Calls reset if configured. */
401
+ release(item) {
402
+ if (G.__DEV__) {
403
+ if (!this._liveSet) this._liveSet = /* @__PURE__ */ new Set();
404
+ if (this._liveSet.has(item)) throw new Error("[Pool] double-release detected");
405
+ this._liveSet.add(item);
406
+ }
407
+ this._live--;
408
+ if (this.resetFn) this.resetFn(item);
409
+ this.items.push(item);
410
+ }
411
+ /** Pre-allocate objects into the pool. Does not count toward live. */
412
+ prewarm(count) {
413
+ for (let i = 0; i < count; i++) this.items.push(this.factory());
414
+ }
415
+ /** Number of available objects currently in the pool (not live). */
416
+ get available() {
417
+ return this.items.length;
418
+ }
419
+ /** Number of currently live (acquired, not yet released) objects. */
420
+ get live() {
421
+ return this._live;
422
+ }
423
+ /** Cumulative number of factory calls made by acquire()/tryAcquire().
424
+ * prewarm() is deliberately excluded: this counter exists to detect
425
+ * steady-state allocation, so compare it before and after a frame. */
426
+ get created() {
427
+ return this._created;
428
+ }
429
+ /** Clear all pooled objects. Does not affect live count. */
430
+ clear() {
431
+ this.items.length = 0;
432
+ this._liveSet?.clear();
433
+ }
450
434
  };
451
- export {
452
- AppLifecycle,
453
- Clock,
454
- CoroutineManager,
455
- GameLoop,
456
- Pool,
457
- ScreenManager
435
+ //#endregion
436
+ //#region src/screen.ts
437
+ /**
438
+ * ScreenManager maps a fixed design resolution to the actual device screen.
439
+ *
440
+ * - FIT: letterbox (scale to fit, black bars)
441
+ * - FILL: crop (scale to fill, content cropped)
442
+ * - STRETCH: distort (stretch to fill, aspect ratio distorted)
443
+ */
444
+ var ScreenManager = class {
445
+ /** Design resolution width. */
446
+ designWidth;
447
+ /** Design resolution height. */
448
+ designHeight;
449
+ /** Current scale mode. */
450
+ scaleMode;
451
+ /** Device pixel ratio. */
452
+ pixelRatio = 1;
453
+ /** Safe area insets (top, right, bottom, left) in device pixels. */
454
+ safeArea = {
455
+ x: 0,
456
+ y: 0,
457
+ width: 0,
458
+ height: 0
459
+ };
460
+ /** Fires when screen dimensions change. */
461
+ onResize = new Signal();
462
+ /** Computed scale factor X (design → screen). */
463
+ scaleX = 1;
464
+ /** Computed scale factor Y (design → screen). */
465
+ scaleY = 1;
466
+ /** Offset X in screen pixels (for letterboxing). */
467
+ offsetX = 0;
468
+ /** Offset Y in screen pixels (for letterboxing). */
469
+ offsetY = 0;
470
+ screenWidth = 0;
471
+ screenHeight = 0;
472
+ constructor(config) {
473
+ this.designWidth = config.designWidth;
474
+ this.designHeight = config.designHeight;
475
+ this.scaleMode = config.scaleMode ?? "fit";
476
+ }
477
+ safeInsetTop = 0;
478
+ safeInsetRight = 0;
479
+ safeInsetBottom = 0;
480
+ safeInsetLeft = 0;
481
+ /** Update with actual device screen dimensions. Call on mount and resize. */
482
+ resize(screenWidth, screenHeight, pixelRatio) {
483
+ this.screenWidth = screenWidth;
484
+ this.screenHeight = screenHeight;
485
+ if (pixelRatio !== void 0) this.pixelRatio = pixelRatio;
486
+ this.recalculate();
487
+ this.recalculateSafeArea();
488
+ this.onResize.emit();
489
+ }
490
+ /**
491
+ * Set safe-area insets in screen pixels. Call this from the RN host with values from
492
+ * `react-native-safe-area-context`. Populates `safeArea` as the usable region.
493
+ */
494
+ setSafeAreaInsets(top, right, bottom, left) {
495
+ this.safeInsetTop = top;
496
+ this.safeInsetRight = right;
497
+ this.safeInsetBottom = bottom;
498
+ this.safeInsetLeft = left;
499
+ this.recalculateSafeArea();
500
+ this.onResize.emit();
501
+ }
502
+ recalculateSafeArea() {
503
+ this.safeArea.x = this.safeInsetLeft;
504
+ this.safeArea.y = this.safeInsetTop;
505
+ this.safeArea.width = Math.max(0, this.screenWidth - this.safeInsetLeft - this.safeInsetRight);
506
+ this.safeArea.height = Math.max(0, this.screenHeight - this.safeInsetTop - this.safeInsetBottom);
507
+ }
508
+ /** Convert design-space point to screen-space. */
509
+ designToScreen(point) {
510
+ return {
511
+ x: point.x * this.scaleX + this.offsetX,
512
+ y: point.y * this.scaleY + this.offsetY
513
+ };
514
+ }
515
+ /** Convert screen-space point to design-space. */
516
+ screenToDesign(point) {
517
+ return {
518
+ x: (point.x - this.offsetX) / this.scaleX,
519
+ y: (point.y - this.offsetY) / this.scaleY
520
+ };
521
+ }
522
+ /** Viewport rect in design coordinates (visible area). */
523
+ get viewport() {
524
+ if (this.scaleMode === "fill") {
525
+ const visibleW = this.screenWidth / this.scaleX;
526
+ const visibleH = this.screenHeight / this.scaleY;
527
+ return {
528
+ x: (this.designWidth - visibleW) / 2,
529
+ y: (this.designHeight - visibleH) / 2,
530
+ width: visibleW,
531
+ height: visibleH
532
+ };
533
+ }
534
+ return {
535
+ x: 0,
536
+ y: 0,
537
+ width: this.designWidth,
538
+ height: this.designHeight
539
+ };
540
+ }
541
+ recalculate() {
542
+ const ratioX = this.screenWidth / this.designWidth;
543
+ const ratioY = this.screenHeight / this.designHeight;
544
+ switch (this.scaleMode) {
545
+ case "fit": {
546
+ const scale = Math.min(ratioX, ratioY);
547
+ this.scaleX = scale;
548
+ this.scaleY = scale;
549
+ this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;
550
+ this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;
551
+ break;
552
+ }
553
+ case "fill": {
554
+ const scale = Math.max(ratioX, ratioY);
555
+ this.scaleX = scale;
556
+ this.scaleY = scale;
557
+ this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;
558
+ this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;
559
+ break;
560
+ }
561
+ case "stretch":
562
+ this.scaleX = ratioX;
563
+ this.scaleY = ratioY;
564
+ this.offsetX = 0;
565
+ this.offsetY = 0;
566
+ break;
567
+ }
568
+ }
458
569
  };
570
+ //#endregion
571
+ export { AppLifecycle, Clock, CoroutineManager, GameLoop, Pool, ScreenManager };
572
+
459
573
  //# sourceMappingURL=index.mjs.map