@flare-engine/debug 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,485 +1,497 @@
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
- DebugOverlay: () => DebugOverlay,
24
- PERF_BENCH_TAG: () => PERF_BENCH_TAG,
25
- StatsTracker: () => StatsTracker,
26
- TimeControl: () => TimeControl,
27
- createBootTrace: () => createBootTrace,
28
- createFpsWidget: () => createFpsWidget,
29
- createFrameBudget: () => createFrameBudget,
30
- createPerfRecorder: () => createPerfRecorder,
31
- emitPerfReport: () => emitPerfReport
32
- });
33
- module.exports = __toCommonJS(index_exports);
34
-
35
- // src/stats.ts
36
- var StatsTracker = class {
37
- /** Current frame stats (read-only snapshot). */
38
- stats = {
39
- fps: 0,
40
- rawDt: 0,
41
- dt: 0,
42
- frame: 0,
43
- entityCount: 0,
44
- drawCalls: 0
45
- };
46
- /** Update timing stats from the clock. */
47
- updateFromClock(fps, rawDt, dt, frame) {
48
- this.stats.fps = fps;
49
- this.stats.rawDt = rawDt;
50
- this.stats.dt = dt;
51
- this.stats.frame = frame;
52
- }
53
- /** Set entity count for this frame. */
54
- setEntityCount(count) {
55
- this.stats.entityCount = count;
56
- }
57
- /** Set draw call count for this frame. */
58
- setDrawCalls(count) {
59
- this.stats.drawCalls = count;
60
- }
61
- /** Reset all counters to zero. */
62
- reset() {
63
- this.stats.fps = 0;
64
- this.stats.rawDt = 0;
65
- this.stats.dt = 0;
66
- this.stats.frame = 0;
67
- this.stats.entityCount = 0;
68
- this.stats.drawCalls = 0;
69
- }
70
- };
71
-
72
- // src/time-control.ts
73
- var TimeControl = class {
74
- _clock;
75
- _savedTimescale = 1;
76
- _paused = false;
77
- _stepRequested = false;
78
- constructor(clock) {
79
- this._clock = clock;
80
- }
81
- /** Whether the game is currently paused. */
82
- get paused() {
83
- return this._paused;
84
- }
85
- /** Current time scale. */
86
- get timescale() {
87
- return this._clock.timescale;
88
- }
89
- /** Pause the game (sets timescale to 0). */
90
- pause() {
91
- if (this._paused) return;
92
- this._savedTimescale = this._clock.timescale;
93
- this._clock.timescale = 0;
94
- this._paused = true;
95
- }
96
- /** Resume the game (restores previous timescale). */
97
- resume() {
98
- if (!this._paused) return;
99
- this._clock.timescale = this._savedTimescale;
100
- this._paused = false;
101
- this._stepRequested = false;
102
- }
103
- /** Toggle pause/resume. */
104
- toggle() {
105
- if (this._paused) {
106
- this.resume();
107
- } else {
108
- this.pause();
109
- }
110
- }
111
- /**
112
- * Request a single-frame step while paused.
113
- * Call this, then on the next update check `consumeStep()`.
114
- */
115
- step() {
116
- if (!this._paused) return;
117
- this._stepRequested = true;
118
- }
119
- /**
120
- * Consume a pending step request. Returns true if a step was requested.
121
- * When true, the caller should run one frame with the saved timescale,
122
- * then re-pause.
123
- */
124
- consumeStep() {
125
- if (!this._stepRequested) return false;
126
- this._stepRequested = false;
127
- return true;
128
- }
129
- /** Set slow-motion multiplier (e.g., 0.5 for half-speed). */
130
- setTimescale(scale) {
131
- if (this._paused) {
132
- this._savedTimescale = scale;
133
- } else {
134
- this._clock.timescale = scale;
135
- }
136
- }
137
- };
138
-
139
- // src/overlay.ts
140
- var DebugOverlay = class {
141
- /** Active overlay flags. */
142
- flags = {
143
- showCollisionBounds: false,
144
- showEntityOrigins: false,
145
- showVelocityVectors: false,
146
- showStats: false
147
- };
148
- /** Queued debug draw commands for the current frame. */
149
- _commands = [];
150
- /** Number of queued commands. */
151
- get commandCount() {
152
- return this._commands.length;
153
- }
154
- /** Get all commands (read-only view). */
155
- get commands() {
156
- return this._commands;
157
- }
158
- /** Add a debug rectangle. */
159
- drawRect(x, y, width, height, color = "#00ff00") {
160
- this._commands.push({ type: "rect", x, y, width, height, color });
161
- }
162
- /** Add a debug circle. */
163
- drawCircle(x, y, radius, color = "#00ff00") {
164
- this._commands.push({ type: "circle", x, y, radius, color });
165
- }
166
- /** Add a debug line. */
167
- drawLine(x1, y1, x2, y2, color = "#ffff00") {
168
- this._commands.push({ type: "line", x1, y1, x2, y2, color });
169
- }
170
- /** Clear all commands. Call at the start of each frame. */
171
- clear() {
172
- this._commands.length = 0;
173
- }
174
- /** Toggle a specific overlay flag. */
175
- toggleFlag(flag) {
176
- this.flags[flag] = !this.flags[flag];
177
- }
178
- /** Enable all overlays. */
179
- enableAll() {
180
- this.flags.showCollisionBounds = true;
181
- this.flags.showEntityOrigins = true;
182
- this.flags.showVelocityVectors = true;
183
- this.flags.showStats = true;
184
- }
185
- /** Disable all overlays. */
186
- disableAll() {
187
- this.flags.showCollisionBounds = false;
188
- this.flags.showEntityOrigins = false;
189
- this.flags.showVelocityVectors = false;
190
- this.flags.showStats = false;
191
- }
192
- };
193
-
194
- // src/fps-widget.ts
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/boot-trace.ts
3
+ function nowMs$1() {
4
+ if (typeof performance !== "undefined" && typeof performance.now === "function") return performance.now();
5
+ return Date.now();
6
+ }
7
+ function createBootTrace(label = "boot-trace") {
8
+ const entries = [];
9
+ let startT = null;
10
+ function mark(name) {
11
+ if (startT === null) {
12
+ startT = nowMs$1();
13
+ entries.push({
14
+ name,
15
+ t: 0
16
+ });
17
+ } else entries.push({
18
+ name,
19
+ t: nowMs$1() - startT
20
+ });
21
+ }
22
+ function dump() {
23
+ if (entries.length === 0) return null;
24
+ const parts = [];
25
+ for (let i = 1; i < entries.length; i++) {
26
+ const prev = entries[i - 1];
27
+ const cur = entries[i];
28
+ if (!prev || !cur) continue;
29
+ parts.push(`${prev.name}->${cur.name}=${(cur.t - prev.t).toFixed(1)}ms`);
30
+ }
31
+ const last = entries[entries.length - 1];
32
+ return `[${label}] total=${last ? last.t.toFixed(1) : "0.0"}ms${parts.length > 0 ? ` ${parts.join(" ")}` : ""}`;
33
+ }
34
+ function reset() {
35
+ entries.length = 0;
36
+ startT = null;
37
+ }
38
+ function getEntries() {
39
+ return entries.slice();
40
+ }
41
+ return {
42
+ mark,
43
+ dump,
44
+ reset,
45
+ getEntries
46
+ };
47
+ }
48
+ //#endregion
49
+ //#region src/fps-widget.ts
50
+ /** Create a new FPS widget formatter. */
195
51
  function createFpsWidget(options = {}) {
196
- const showEntities = options.showEntities ?? true;
197
- const showDrawCalls = options.showDrawCalls ?? true;
198
- const msPrecision = options.msPrecision ?? 1;
199
- const lines = [];
200
- const widget = {
201
- line: "",
202
- lines,
203
- update(stats) {
204
- const fps = Math.round(stats.fps);
205
- const ms = (stats.rawDt * 1e3).toFixed(msPrecision);
206
- let summary = `${fps} FPS | ${ms}ms`;
207
- if (showEntities) summary += ` | e:${stats.entityCount}`;
208
- if (showDrawCalls) summary += ` d:${stats.drawCalls}`;
209
- widget.line = summary;
210
- lines.length = 0;
211
- lines.push(`FPS: ${fps}`);
212
- lines.push(`dt: ${ms}ms`);
213
- lines.push(`frame: ${stats.frame}`);
214
- lines.push(`entities: ${stats.entityCount}`);
215
- lines.push(`draws: ${stats.drawCalls}`);
216
- }
217
- };
218
- return widget;
52
+ const showEntities = options.showEntities ?? true;
53
+ const showDrawCalls = options.showDrawCalls ?? true;
54
+ const msPrecision = options.msPrecision ?? 1;
55
+ const lines = [];
56
+ const widget = {
57
+ line: "",
58
+ lines,
59
+ update(stats) {
60
+ const fps = Math.round(stats.fps);
61
+ const ms = (stats.rawDt * 1e3).toFixed(msPrecision);
62
+ let summary = `${fps} FPS | ${ms}ms`;
63
+ if (showEntities) summary += ` | e:${stats.entityCount}`;
64
+ if (showDrawCalls) summary += ` d:${stats.drawCalls}`;
65
+ widget.line = summary;
66
+ lines.length = 0;
67
+ lines.push(`FPS: ${fps}`);
68
+ lines.push(`dt: ${ms}ms`);
69
+ lines.push(`frame: ${stats.frame}`);
70
+ lines.push(`entities: ${stats.entityCount}`);
71
+ lines.push(`draws: ${stats.drawCalls}`);
72
+ }
73
+ };
74
+ return widget;
219
75
  }
220
-
221
- // src/frame-budget.ts
76
+ //#endregion
77
+ //#region src/frame-budget.ts
222
78
  function createFrameBudget(opts) {
223
- const { limits, onWatchdog, debug = false } = opts;
224
- const fpsThreshold = opts.fpsThreshold ?? 55;
225
- const ringSize = opts.ringSize ?? 180;
226
- const ring = new Float32Array(ringSize);
227
- const limitKeys = Object.keys(limits);
228
- const _lastSnapshot = {};
229
- for (const k of limitKeys) {
230
- _lastSnapshot[k] = 0;
231
- }
232
- let head = 0;
233
- let filled = 0;
234
- let watchdogFired = false;
235
- function recordFrame(dtSec) {
236
- ring[head] = dtSec;
237
- head = (head + 1) % ringSize;
238
- if (filled < ringSize) filled += 1;
239
- if (filled === ringSize && !watchdogFired) {
240
- if (getAvgFps() < fpsThreshold) {
241
- watchdogFired = true;
242
- onWatchdog?.();
243
- }
244
- }
245
- }
246
- function recordCounters(snapshot) {
247
- for (let i = 0; i < limitKeys.length; i++) {
248
- const k = limitKeys[i];
249
- const v = snapshot[k] ?? 0;
250
- _lastSnapshot[k] = v;
251
- if (debug && v > limits[k]) {
252
- console.warn(`[frame-budget] ${k} over limit: ${v} > ${limits[k]}`);
253
- }
254
- }
255
- }
256
- function getSnapshot() {
257
- return _lastSnapshot;
258
- }
259
- function getAvgFps() {
260
- if (filled < ringSize) return 0;
261
- let sum = 0;
262
- for (let i = 0; i < ringSize; i++) {
263
- sum += ring[i];
264
- }
265
- const avgDt = sum / ringSize;
266
- return avgDt > 0 ? 1 / avgDt : 0;
267
- }
268
- function resetFpsRing() {
269
- ring.fill(0);
270
- head = 0;
271
- filled = 0;
272
- watchdogFired = false;
273
- }
274
- return { recordFrame, recordCounters, getSnapshot, getAvgFps, resetFpsRing };
275
- }
276
-
277
- // src/boot-trace.ts
278
- function nowMs() {
279
- if (typeof performance !== "undefined" && typeof performance.now === "function") {
280
- return performance.now();
281
- }
282
- return Date.now();
79
+ const { limits, onWatchdog, debug = false } = opts;
80
+ const fpsThreshold = opts.fpsThreshold ?? 55;
81
+ const ringSize = opts.ringSize ?? 180;
82
+ const ring = new Float32Array(ringSize);
83
+ const limitKeys = Object.keys(limits);
84
+ const _lastSnapshot = {};
85
+ for (const k of limitKeys) _lastSnapshot[k] = 0;
86
+ let head = 0;
87
+ let filled = 0;
88
+ let watchdogFired = false;
89
+ function recordFrame(dtSec) {
90
+ ring[head] = dtSec;
91
+ head = (head + 1) % ringSize;
92
+ if (filled < ringSize) filled += 1;
93
+ if (filled === ringSize && !watchdogFired) {
94
+ if (getAvgFps() < fpsThreshold) {
95
+ watchdogFired = true;
96
+ onWatchdog?.();
97
+ }
98
+ }
99
+ }
100
+ function recordCounters(snapshot) {
101
+ for (let i = 0; i < limitKeys.length; i++) {
102
+ const k = limitKeys[i];
103
+ const v = snapshot[k] ?? 0;
104
+ _lastSnapshot[k] = v;
105
+ if (debug && v > limits[k]) console.warn(`[frame-budget] ${k} over limit: ${v} > ${limits[k]}`);
106
+ }
107
+ }
108
+ function getSnapshot() {
109
+ return _lastSnapshot;
110
+ }
111
+ function getAvgFps() {
112
+ if (filled < ringSize) return 0;
113
+ let sum = 0;
114
+ for (let i = 0; i < ringSize; i++) sum += ring[i];
115
+ const avgDt = sum / ringSize;
116
+ return avgDt > 0 ? 1 / avgDt : 0;
117
+ }
118
+ function resetFpsRing() {
119
+ ring.fill(0);
120
+ head = 0;
121
+ filled = 0;
122
+ watchdogFired = false;
123
+ }
124
+ return {
125
+ recordFrame,
126
+ recordCounters,
127
+ getSnapshot,
128
+ getAvgFps,
129
+ resetFpsRing
130
+ };
283
131
  }
284
- function createBootTrace(label = "boot-trace") {
285
- const entries = [];
286
- let startT = null;
287
- function mark(name) {
288
- if (startT === null) {
289
- startT = nowMs();
290
- entries.push({ name, t: 0 });
291
- } else {
292
- entries.push({ name, t: nowMs() - startT });
293
- }
294
- }
295
- function dump() {
296
- if (entries.length === 0) return null;
297
- const parts = [];
298
- for (let i = 1; i < entries.length; i++) {
299
- const prev = entries[i - 1];
300
- const cur = entries[i];
301
- if (!prev || !cur) continue;
302
- parts.push(`${prev.name}->${cur.name}=${(cur.t - prev.t).toFixed(1)}ms`);
303
- }
304
- const last = entries[entries.length - 1];
305
- const totalMs = last ? last.t.toFixed(1) : "0.0";
306
- const stepStr = parts.length > 0 ? ` ${parts.join(" ")}` : "";
307
- return `[${label}] total=${totalMs}ms${stepStr}`;
308
- }
309
- function reset() {
310
- entries.length = 0;
311
- startT = null;
312
- }
313
- function getEntries() {
314
- return entries.slice();
315
- }
316
- return { mark, dump, reset, getEntries };
132
+ //#endregion
133
+ //#region src/overlay.ts
134
+ /**
135
+ * DebugOverlay — collects debug draw commands for the current frame.
136
+ * Commands are generated based on active overlay flags, then consumed
137
+ * by the renderer.
138
+ */
139
+ var DebugOverlay = class {
140
+ /** Active overlay flags. */
141
+ flags = {
142
+ showCollisionBounds: false,
143
+ showEntityOrigins: false,
144
+ showVelocityVectors: false,
145
+ showStats: false
146
+ };
147
+ /** Queued debug draw commands for the current frame. */
148
+ _commands = [];
149
+ /** Number of queued commands. */
150
+ get commandCount() {
151
+ return this._commands.length;
152
+ }
153
+ /** Get all commands (read-only view). */
154
+ get commands() {
155
+ return this._commands;
156
+ }
157
+ /** Add a debug rectangle. */
158
+ drawRect(x, y, width, height, color = "#00ff00") {
159
+ this._commands.push({
160
+ type: "rect",
161
+ x,
162
+ y,
163
+ width,
164
+ height,
165
+ color
166
+ });
167
+ }
168
+ /** Add a debug circle. */
169
+ drawCircle(x, y, radius, color = "#00ff00") {
170
+ this._commands.push({
171
+ type: "circle",
172
+ x,
173
+ y,
174
+ radius,
175
+ color
176
+ });
177
+ }
178
+ /** Add a debug line. */
179
+ drawLine(x1, y1, x2, y2, color = "#ffff00") {
180
+ this._commands.push({
181
+ type: "line",
182
+ x1,
183
+ y1,
184
+ x2,
185
+ y2,
186
+ color
187
+ });
188
+ }
189
+ /** Clear all commands. Call at the start of each frame. */
190
+ clear() {
191
+ this._commands.length = 0;
192
+ }
193
+ /** Toggle a specific overlay flag. */
194
+ toggleFlag(flag) {
195
+ this.flags[flag] = !this.flags[flag];
196
+ }
197
+ /** Enable all overlays. */
198
+ enableAll() {
199
+ this.flags.showCollisionBounds = true;
200
+ this.flags.showEntityOrigins = true;
201
+ this.flags.showVelocityVectors = true;
202
+ this.flags.showStats = true;
203
+ }
204
+ /** Disable all overlays. */
205
+ disableAll() {
206
+ this.flags.showCollisionBounds = false;
207
+ this.flags.showEntityOrigins = false;
208
+ this.flags.showVelocityVectors = false;
209
+ this.flags.showStats = false;
210
+ }
211
+ };
212
+ //#endregion
213
+ //#region src/perf-output.ts
214
+ const PERF_BENCH_TAG = "[perf-bench]";
215
+ function emitPerfReport(report) {
216
+ console.log(`${PERF_BENCH_TAG} ${JSON.stringify(report)}`);
317
217
  }
318
-
319
- // src/perf-recorder.ts
320
- function nowMs2() {
321
- if (typeof performance !== "undefined" && typeof performance.now === "function") {
322
- return performance.now();
323
- }
324
- return Date.now();
218
+ //#endregion
219
+ //#region src/perf-recorder.ts
220
+ function nowMs() {
221
+ if (typeof performance !== "undefined" && typeof performance.now === "function") return performance.now();
222
+ return Date.now();
325
223
  }
326
224
  function percentile(sorted, n, p) {
327
- if (n === 0) return 0;
328
- if (n === 1) return sorted[0];
329
- const idx = p / 100 * (n - 1);
330
- const lo = Math.floor(idx);
331
- const hi = Math.ceil(idx);
332
- const a = sorted[lo];
333
- const b = sorted[hi];
334
- return a + (b - a) * (idx - lo);
225
+ if (n === 0) return 0;
226
+ if (n === 1) return sorted[0];
227
+ const idx = p / 100 * (n - 1);
228
+ const lo = Math.floor(idx);
229
+ const hi = Math.ceil(idx);
230
+ const a = sorted[lo];
231
+ return a + (sorted[hi] - a) * (idx - lo);
335
232
  }
336
233
  function createPerfRecorder(opts = {}) {
337
- const label = opts.label ?? "perf";
338
- const ringSize = opts.ringSize ?? 1800;
339
- const sections = /* @__PURE__ */ new Map();
340
- const counters = /* @__PURE__ */ new Map();
341
- let frameCount = 0;
342
- let startT = null;
343
- let sortBuf = new Float32Array(ringSize);
344
- function getOrCreateSection(name) {
345
- let s = sections.get(name);
346
- if (s === void 0) {
347
- s = {
348
- name,
349
- ring: new Float32Array(ringSize),
350
- ringSize,
351
- head: 0,
352
- filled: 0,
353
- startT: 0
354
- };
355
- sections.set(name, s);
356
- }
357
- return s;
358
- }
359
- function getOrCreateCounter(name) {
360
- let c = counters.get(name);
361
- if (c === void 0) {
362
- c = { name, count: 0, min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY, sum: 0 };
363
- counters.set(name, c);
364
- }
365
- return c;
366
- }
367
- function beginSection(name) {
368
- const s = getOrCreateSection(name);
369
- s.startT = nowMs2();
370
- }
371
- function endSection(name) {
372
- const s = sections.get(name);
373
- if (s === void 0) return;
374
- const elapsed = nowMs2() - s.startT;
375
- s.ring[s.head] = elapsed;
376
- s.head = (s.head + 1) % s.ringSize;
377
- if (s.filled < s.ringSize) s.filled += 1;
378
- }
379
- function recordFrame(frameCounters) {
380
- if (startT === null) startT = nowMs2();
381
- frameCount += 1;
382
- if (frameCounters === void 0) return;
383
- for (const name in frameCounters) {
384
- const v = frameCounters[name];
385
- const c = getOrCreateCounter(name);
386
- c.count += 1;
387
- if (v < c.min) c.min = v;
388
- if (v > c.max) c.max = v;
389
- c.sum += v;
390
- }
391
- }
392
- function flush() {
393
- const now = nowMs2();
394
- const durationMs = startT !== null ? now - startT : 0;
395
- const sectionStats = [];
396
- for (const s of sections.values()) {
397
- const n = s.filled;
398
- if (n === 0) {
399
- sectionStats.push({
400
- name: s.name,
401
- count: 0,
402
- min: 0,
403
- max: 0,
404
- mean: 0,
405
- p50: 0,
406
- p95: 0,
407
- p99: 0
408
- });
409
- continue;
410
- }
411
- if (sortBuf.length < n) sortBuf = new Float32Array(n);
412
- let sum = 0;
413
- let minV = Number.POSITIVE_INFINITY;
414
- let maxV = Number.NEGATIVE_INFINITY;
415
- const start = s.filled < s.ringSize ? 0 : s.head;
416
- for (let i = 0; i < n; i++) {
417
- const v = s.ring[(start + i) % s.ringSize];
418
- sortBuf[i] = v;
419
- sum += v;
420
- if (v < minV) minV = v;
421
- if (v > maxV) maxV = v;
422
- }
423
- const slice = sortBuf.subarray(0, n);
424
- slice.sort();
425
- sectionStats.push({
426
- name: s.name,
427
- count: n,
428
- min: minV,
429
- max: maxV,
430
- mean: sum / n,
431
- p50: percentile(slice, n, 50),
432
- p95: percentile(slice, n, 95),
433
- p99: percentile(slice, n, 99)
434
- });
435
- }
436
- const counterStats = [];
437
- for (const c of counters.values()) {
438
- counterStats.push({
439
- name: c.name,
440
- count: c.count,
441
- min: c.count > 0 ? c.min : 0,
442
- max: c.count > 0 ? c.max : 0,
443
- sum: c.sum,
444
- mean: c.count > 0 ? c.sum / c.count : 0
445
- });
446
- }
447
- return { label, durationMs, frameCount, sections: sectionStats, counters: counterStats };
448
- }
449
- function reset() {
450
- for (const s of sections.values()) {
451
- s.ring.fill(0);
452
- s.head = 0;
453
- s.filled = 0;
454
- s.startT = 0;
455
- }
456
- for (const c of counters.values()) {
457
- c.count = 0;
458
- c.min = Number.POSITIVE_INFINITY;
459
- c.max = Number.NEGATIVE_INFINITY;
460
- c.sum = 0;
461
- }
462
- frameCount = 0;
463
- startT = null;
464
- }
465
- return { beginSection, endSection, recordFrame, flush, reset };
234
+ const label = opts.label ?? "perf";
235
+ const ringSize = opts.ringSize ?? 1800;
236
+ const sections = /* @__PURE__ */ new Map();
237
+ const counters = /* @__PURE__ */ new Map();
238
+ let frameCount = 0;
239
+ let startT = null;
240
+ let sortBuf = new Float32Array(ringSize);
241
+ function getOrCreateSection(name) {
242
+ let s = sections.get(name);
243
+ if (s === void 0) {
244
+ s = {
245
+ name,
246
+ ring: new Float32Array(ringSize),
247
+ ringSize,
248
+ head: 0,
249
+ filled: 0,
250
+ startT: 0
251
+ };
252
+ sections.set(name, s);
253
+ }
254
+ return s;
255
+ }
256
+ function getOrCreateCounter(name) {
257
+ let c = counters.get(name);
258
+ if (c === void 0) {
259
+ c = {
260
+ name,
261
+ count: 0,
262
+ min: Number.POSITIVE_INFINITY,
263
+ max: Number.NEGATIVE_INFINITY,
264
+ sum: 0
265
+ };
266
+ counters.set(name, c);
267
+ }
268
+ return c;
269
+ }
270
+ function beginSection(name) {
271
+ const s = getOrCreateSection(name);
272
+ s.startT = nowMs();
273
+ }
274
+ function endSection(name) {
275
+ const s = sections.get(name);
276
+ if (s === void 0) return;
277
+ const elapsed = nowMs() - s.startT;
278
+ s.ring[s.head] = elapsed;
279
+ s.head = (s.head + 1) % s.ringSize;
280
+ if (s.filled < s.ringSize) s.filled += 1;
281
+ }
282
+ function recordFrame(frameCounters) {
283
+ if (startT === null) startT = nowMs();
284
+ frameCount += 1;
285
+ if (frameCounters === void 0) return;
286
+ for (const name in frameCounters) {
287
+ const v = frameCounters[name];
288
+ const c = getOrCreateCounter(name);
289
+ c.count += 1;
290
+ if (v < c.min) c.min = v;
291
+ if (v > c.max) c.max = v;
292
+ c.sum += v;
293
+ }
294
+ }
295
+ function flush() {
296
+ const now = nowMs();
297
+ const durationMs = startT !== null ? now - startT : 0;
298
+ const sectionStats = [];
299
+ for (const s of sections.values()) {
300
+ const n = s.filled;
301
+ if (n === 0) {
302
+ sectionStats.push({
303
+ name: s.name,
304
+ count: 0,
305
+ min: 0,
306
+ max: 0,
307
+ mean: 0,
308
+ p50: 0,
309
+ p95: 0,
310
+ p99: 0
311
+ });
312
+ continue;
313
+ }
314
+ if (sortBuf.length < n) sortBuf = new Float32Array(n);
315
+ let sum = 0;
316
+ let minV = Number.POSITIVE_INFINITY;
317
+ let maxV = Number.NEGATIVE_INFINITY;
318
+ const start = s.filled < s.ringSize ? 0 : s.head;
319
+ for (let i = 0; i < n; i++) {
320
+ const v = s.ring[(start + i) % s.ringSize];
321
+ sortBuf[i] = v;
322
+ sum += v;
323
+ if (v < minV) minV = v;
324
+ if (v > maxV) maxV = v;
325
+ }
326
+ const slice = sortBuf.subarray(0, n);
327
+ slice.sort();
328
+ sectionStats.push({
329
+ name: s.name,
330
+ count: n,
331
+ min: minV,
332
+ max: maxV,
333
+ mean: sum / n,
334
+ p50: percentile(slice, n, 50),
335
+ p95: percentile(slice, n, 95),
336
+ p99: percentile(slice, n, 99)
337
+ });
338
+ }
339
+ const counterStats = [];
340
+ for (const c of counters.values()) counterStats.push({
341
+ name: c.name,
342
+ count: c.count,
343
+ min: c.count > 0 ? c.min : 0,
344
+ max: c.count > 0 ? c.max : 0,
345
+ sum: c.sum,
346
+ mean: c.count > 0 ? c.sum / c.count : 0
347
+ });
348
+ return {
349
+ label,
350
+ durationMs,
351
+ frameCount,
352
+ sections: sectionStats,
353
+ counters: counterStats
354
+ };
355
+ }
356
+ function reset() {
357
+ for (const s of sections.values()) {
358
+ s.ring.fill(0);
359
+ s.head = 0;
360
+ s.filled = 0;
361
+ s.startT = 0;
362
+ }
363
+ for (const c of counters.values()) {
364
+ c.count = 0;
365
+ c.min = Number.POSITIVE_INFINITY;
366
+ c.max = Number.NEGATIVE_INFINITY;
367
+ c.sum = 0;
368
+ }
369
+ frameCount = 0;
370
+ startT = null;
371
+ }
372
+ return {
373
+ beginSection,
374
+ endSection,
375
+ recordFrame,
376
+ flush,
377
+ reset
378
+ };
466
379
  }
380
+ //#endregion
381
+ //#region src/stats.ts
382
+ /**
383
+ * StatsTracker — collects and exposes per-frame debug statistics.
384
+ * Wrap in `__DEV__` checks at the call site for tree-shaking.
385
+ */
386
+ var StatsTracker = class {
387
+ /** Current frame stats (read-only snapshot). */
388
+ stats = {
389
+ fps: 0,
390
+ rawDt: 0,
391
+ dt: 0,
392
+ frame: 0,
393
+ entityCount: 0,
394
+ drawCalls: 0
395
+ };
396
+ /** Update timing stats from the clock. */
397
+ updateFromClock(fps, rawDt, dt, frame) {
398
+ this.stats.fps = fps;
399
+ this.stats.rawDt = rawDt;
400
+ this.stats.dt = dt;
401
+ this.stats.frame = frame;
402
+ }
403
+ /** Set entity count for this frame. */
404
+ setEntityCount(count) {
405
+ this.stats.entityCount = count;
406
+ }
407
+ /** Set draw call count for this frame. */
408
+ setDrawCalls(count) {
409
+ this.stats.drawCalls = count;
410
+ }
411
+ /** Reset all counters to zero. */
412
+ reset() {
413
+ this.stats.fps = 0;
414
+ this.stats.rawDt = 0;
415
+ this.stats.dt = 0;
416
+ this.stats.frame = 0;
417
+ this.stats.entityCount = 0;
418
+ this.stats.drawCalls = 0;
419
+ }
420
+ };
421
+ //#endregion
422
+ //#region src/time-control.ts
423
+ /**
424
+ * TimeControl — pause, step-frame, and slow-motion via Clock.timescale.
425
+ * Wrap in `__DEV__` checks at the call site for tree-shaking.
426
+ */
427
+ var TimeControl = class {
428
+ _clock;
429
+ _savedTimescale = 1;
430
+ _paused = false;
431
+ _stepRequested = false;
432
+ constructor(clock) {
433
+ this._clock = clock;
434
+ }
435
+ /** Whether the game is currently paused. */
436
+ get paused() {
437
+ return this._paused;
438
+ }
439
+ /** Current time scale. */
440
+ get timescale() {
441
+ return this._clock.timescale;
442
+ }
443
+ /** Pause the game (sets timescale to 0). */
444
+ pause() {
445
+ if (this._paused) return;
446
+ this._savedTimescale = this._clock.timescale;
447
+ this._clock.timescale = 0;
448
+ this._paused = true;
449
+ }
450
+ /** Resume the game (restores previous timescale). */
451
+ resume() {
452
+ if (!this._paused) return;
453
+ this._clock.timescale = this._savedTimescale;
454
+ this._paused = false;
455
+ this._stepRequested = false;
456
+ }
457
+ /** Toggle pause/resume. */
458
+ toggle() {
459
+ if (this._paused) this.resume();
460
+ else this.pause();
461
+ }
462
+ /**
463
+ * Request a single-frame step while paused.
464
+ * Call this, then on the next update check `consumeStep()`.
465
+ */
466
+ step() {
467
+ if (!this._paused) return;
468
+ this._stepRequested = true;
469
+ }
470
+ /**
471
+ * Consume a pending step request. Returns true if a step was requested.
472
+ * When true, the caller should run one frame with the saved timescale,
473
+ * then re-pause.
474
+ */
475
+ consumeStep() {
476
+ if (!this._stepRequested) return false;
477
+ this._stepRequested = false;
478
+ return true;
479
+ }
480
+ /** Set slow-motion multiplier (e.g., 0.5 for half-speed). */
481
+ setTimescale(scale) {
482
+ if (this._paused) this._savedTimescale = scale;
483
+ else this._clock.timescale = scale;
484
+ }
485
+ };
486
+ //#endregion
487
+ exports.DebugOverlay = DebugOverlay;
488
+ exports.PERF_BENCH_TAG = PERF_BENCH_TAG;
489
+ exports.StatsTracker = StatsTracker;
490
+ exports.TimeControl = TimeControl;
491
+ exports.createBootTrace = createBootTrace;
492
+ exports.createFpsWidget = createFpsWidget;
493
+ exports.createFrameBudget = createFrameBudget;
494
+ exports.createPerfRecorder = createPerfRecorder;
495
+ exports.emitPerfReport = emitPerfReport;
467
496
 
468
- // src/perf-output.ts
469
- var PERF_BENCH_TAG = "[perf-bench]";
470
- function emitPerfReport(report) {
471
- console.log(`${PERF_BENCH_TAG} ${JSON.stringify(report)}`);
472
- }
473
- // Annotate the CommonJS export names for ESM import in node:
474
- 0 && (module.exports = {
475
- DebugOverlay,
476
- PERF_BENCH_TAG,
477
- StatsTracker,
478
- TimeControl,
479
- createBootTrace,
480
- createFpsWidget,
481
- createFrameBudget,
482
- createPerfRecorder,
483
- emitPerfReport
484
- });
485
497
  //# sourceMappingURL=index.js.map