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