@combos-fun/plugin-stats 0.0.0-stage → 0.1.27
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/README.md +117 -2
- package/combos-plugin.json +11 -0
- package/dist/plugin-stats.cjs.js +599 -0
- package/dist/plugin-stats.cjs.js.map +1 -0
- package/dist/plugin-stats.cjs.prod.js +1 -0
- package/dist/plugin-stats.d.ts +157 -0
- package/dist/plugin-stats.esm.js +587 -0
- package/dist/plugin-stats.esm.js.map +1 -0
- package/index.js +7 -0
- package/package.json +33 -3
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
import { System, runtimeNow, isAllowedMessageOrigin, mergeAllowedMessageOrigins, COMBOS_GAME_READY, COMBOS_GAME_STATE_CHANGED, observeRuntimeMessages, COMBOS_GAME_RESOURCES_READY, getLatestResourcesReady, postRuntimeMessage } from '@combos-fun/engine';
|
|
2
|
+
|
|
3
|
+
/** Exact count/mean/extrema; percentile storage is bounded for very long windows. */
|
|
4
|
+
class Samples {
|
|
5
|
+
constructor(capacity = 4096) {
|
|
6
|
+
this.capacity = capacity;
|
|
7
|
+
this.values = [];
|
|
8
|
+
this.count = 0;
|
|
9
|
+
this.sum = 0;
|
|
10
|
+
this.min = Infinity;
|
|
11
|
+
this.max = 0;
|
|
12
|
+
}
|
|
13
|
+
add(value) {
|
|
14
|
+
if (value === null || !Number.isFinite(value) || value < 0)
|
|
15
|
+
return;
|
|
16
|
+
this.values[this.count % this.capacity] = value;
|
|
17
|
+
this.count++;
|
|
18
|
+
this.sum += value;
|
|
19
|
+
this.min = Math.min(this.min, value);
|
|
20
|
+
this.max = Math.max(this.max, value);
|
|
21
|
+
}
|
|
22
|
+
summary() {
|
|
23
|
+
if (!this.count)
|
|
24
|
+
return null;
|
|
25
|
+
const sorted = [...this.values].sort((a, b) => a - b);
|
|
26
|
+
const percentile = (p) => sorted[Math.max(0, Math.ceil(p * sorted.length) - 1)];
|
|
27
|
+
return {
|
|
28
|
+
avg: this.sum / this.count, min: this.min, max: this.max,
|
|
29
|
+
p95: percentile(.95), p99: percentile(.99), sampleCount: this.count,
|
|
30
|
+
retainedSampleCount: sorted.length, percentilesApproximate: this.count > sorted.length,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
class RendererWindow {
|
|
35
|
+
constructor() {
|
|
36
|
+
this.count = 0;
|
|
37
|
+
this.submit = new Samples();
|
|
38
|
+
this.drawCalls = new Samples();
|
|
39
|
+
this.canvasDrawOps = new Samples();
|
|
40
|
+
this.triangles = new Samples();
|
|
41
|
+
this.gpuMs = new Samples();
|
|
42
|
+
}
|
|
43
|
+
add(sample) {
|
|
44
|
+
this.count++;
|
|
45
|
+
this.submit.add(sample.submitMs);
|
|
46
|
+
this.drawCalls.add(sample.metrics.drawCalls);
|
|
47
|
+
this.canvasDrawOps.add(sample.metrics.canvasDrawOps);
|
|
48
|
+
this.triangles.add(sample.metrics.triangles);
|
|
49
|
+
this.gpuMs.add(sample.metrics.gpuMs);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
class StatsWindow {
|
|
53
|
+
constructor(start, active) {
|
|
54
|
+
this.start = start;
|
|
55
|
+
this.rafCount = 0;
|
|
56
|
+
this.updateCount = 0;
|
|
57
|
+
this.intervals = new Samples();
|
|
58
|
+
this.cpu = new Samples();
|
|
59
|
+
this.inputDelay = new Samples();
|
|
60
|
+
this.inputDispatch = new Samples();
|
|
61
|
+
this.inputToSubmit = new Samples();
|
|
62
|
+
this.slowFrames = 0;
|
|
63
|
+
this.over50 = 0;
|
|
64
|
+
this.over100 = 0;
|
|
65
|
+
this.intervalCount = 0;
|
|
66
|
+
this.renderers = new Map();
|
|
67
|
+
this.activeMs = 0;
|
|
68
|
+
this.activeSince = active ? start : null;
|
|
69
|
+
}
|
|
70
|
+
setActive(active, now) {
|
|
71
|
+
if (this.activeSince !== null)
|
|
72
|
+
this.activeMs += Math.max(0, now - this.activeSince);
|
|
73
|
+
this.activeSince = active ? now : null;
|
|
74
|
+
}
|
|
75
|
+
activeDuration(now) { return this.activeMs + (this.activeSince === null ? 0 : Math.max(0, now - this.activeSince)); }
|
|
76
|
+
interval(ms, targetFps) {
|
|
77
|
+
this.intervals.add(ms);
|
|
78
|
+
this.intervalCount++;
|
|
79
|
+
if (ms > 1000 / targetFps * 1.5)
|
|
80
|
+
this.slowFrames++;
|
|
81
|
+
if (ms > 50)
|
|
82
|
+
this.over50++;
|
|
83
|
+
if (ms > 100)
|
|
84
|
+
this.over100++;
|
|
85
|
+
}
|
|
86
|
+
render(sample) {
|
|
87
|
+
let renderer = this.renderers.get(sample.provider.id);
|
|
88
|
+
if (!renderer)
|
|
89
|
+
this.renderers.set(sample.provider.id, renderer = new RendererWindow());
|
|
90
|
+
renderer.add(sample);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Renderer-independent DOM/Canvas 2D HUD; no Pixi/Three import or game objects. */
|
|
95
|
+
class StatsPanel {
|
|
96
|
+
constructor(instanceId, options) {
|
|
97
|
+
this.instanceId = instanceId;
|
|
98
|
+
this.options = options;
|
|
99
|
+
this.history = [];
|
|
100
|
+
this.gpuSamples = new Map();
|
|
101
|
+
this.width = 300;
|
|
102
|
+
this.height = 360;
|
|
103
|
+
this.element = document.createElement('div');
|
|
104
|
+
this.element.dataset.combosStats = instanceId;
|
|
105
|
+
this.element.setAttribute('role', 'status');
|
|
106
|
+
this.element.style.cssText = 'position:fixed;z-index:2147483600;pointer-events:none;max-width:calc(100vw - 24px);border:1px solid #365068;border-radius:12px;overflow:hidden;box-shadow:0 12px 40px #0006;';
|
|
107
|
+
this.canvas = document.createElement('canvas');
|
|
108
|
+
const ratio = Math.min(window.devicePixelRatio || 1, 2);
|
|
109
|
+
this.canvas.width = this.width * ratio;
|
|
110
|
+
this.canvas.height = this.height * ratio;
|
|
111
|
+
this.canvas.style.cssText = `display:block;width:${this.width}px;height:${this.height}px;max-width:100%;`;
|
|
112
|
+
this.element.appendChild(this.canvas);
|
|
113
|
+
document.body.appendChild(this.element);
|
|
114
|
+
this.position(options);
|
|
115
|
+
}
|
|
116
|
+
position(options) {
|
|
117
|
+
this.options = options;
|
|
118
|
+
const position = options.position ?? 'top-left';
|
|
119
|
+
for (const side of ['top', 'bottom', 'left', 'right'])
|
|
120
|
+
this.element.style[side] = 'auto';
|
|
121
|
+
this.element.style[position.includes('top') ? 'top' : 'bottom'] = '12px';
|
|
122
|
+
this.element.style[position.includes('left') ? 'left' : 'right'] = '12px';
|
|
123
|
+
}
|
|
124
|
+
draw(snapshot) {
|
|
125
|
+
const ctx = this.canvas.getContext('2d');
|
|
126
|
+
if (!ctx)
|
|
127
|
+
return;
|
|
128
|
+
const ratio = this.canvas.width / this.width;
|
|
129
|
+
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
|
|
130
|
+
ctx.fillStyle = '#0b1624f5';
|
|
131
|
+
ctx.fillRect(0, 0, this.width, this.height);
|
|
132
|
+
ctx.font = '12px ui-monospace, SFMono-Regular, monospace';
|
|
133
|
+
ctx.textBaseline = 'top';
|
|
134
|
+
const value = (n, digits = 1) => n == null ? 'N/A' : n.toFixed(digits);
|
|
135
|
+
const avg = (s) => value(s?.avg);
|
|
136
|
+
const status = snapshot.paused ? 'PAUSED' : snapshot.hidden ? 'HIDDEN' : 'LIVE';
|
|
137
|
+
ctx.fillStyle = '#65efba';
|
|
138
|
+
ctx.fillText(`COMBOS STATS · ${status}`, 16, 16);
|
|
139
|
+
ctx.fillStyle = '#809bb2';
|
|
140
|
+
ctx.fillText(`${this.instanceId} · ${snapshot.game.gameObjects} objects`, 16, 37);
|
|
141
|
+
const renderer = snapshot.renderers.find(r => r.id === this.options.rendererId) ?? snapshot.renderers[0];
|
|
142
|
+
if (renderer?.gpuMs)
|
|
143
|
+
this.gpuSamples.set(renderer.id, { value: renderer.gpuMs.avg, at: snapshot.timestamp });
|
|
144
|
+
const gpu = renderer ? this.gpuSamples.get(renderer.id) : undefined;
|
|
145
|
+
const gpuValue = gpu && renderer.capabilities.gpuMs?.supported && snapshot.timestamp - gpu.at < 5000 ? gpu.value : null;
|
|
146
|
+
const rows = [
|
|
147
|
+
['fps', 'Update / Render FPS', `${value(snapshot.game.updateFps)} / ${value(renderer?.renderFps)}`],
|
|
148
|
+
['frameIntervalMs', 'Frame p95 / max ms', `${value(snapshot.game.frameIntervalMs?.p95)} / ${value(snapshot.game.frameIntervalMs?.max)}`],
|
|
149
|
+
['updateCpuMs', 'Main thread avg ms', avg(snapshot.game.updateCpuMs)],
|
|
150
|
+
['renderSubmitMs', 'Render submit ms', avg(renderer?.renderSubmitMs)],
|
|
151
|
+
['gpuMs', 'GPU last sample ms', value(gpuValue)],
|
|
152
|
+
['drawCalls', renderer?.backend === 'canvas' ? 'Canvas draw ops' : 'Draw calls / frame', avg(renderer?.backend === 'canvas' ? renderer?.canvasDrawOps : renderer?.drawCalls)],
|
|
153
|
+
['triangles', 'Triangles / frame', avg(renderer?.triangles)],
|
|
154
|
+
['textures', 'Textures / Geometry', `${value(renderer?.textures, 0)} / ${value(renderer?.geometries, 0)}`],
|
|
155
|
+
['memory', 'JS heap MB (page)', value(snapshot.memory.usedJSHeapBytes === null ? null : snapshot.memory.usedJSHeapBytes / 1048576)],
|
|
156
|
+
['inputDelayMs', 'Input delay ms', avg(snapshot.input.inputDelayMs)],
|
|
157
|
+
['inputToNextSubmitMs', 'Input → submit ms', avg(snapshot.input.inputToNextSubmitMs)],
|
|
158
|
+
];
|
|
159
|
+
let y = 65;
|
|
160
|
+
for (const [key, label, content] of rows) {
|
|
161
|
+
if (this.options.metrics?.length && !this.options.metrics.includes(key))
|
|
162
|
+
continue;
|
|
163
|
+
ctx.fillStyle = '#91a9be';
|
|
164
|
+
ctx.fillText(label, 16, y);
|
|
165
|
+
ctx.fillStyle = '#e4f2ff';
|
|
166
|
+
ctx.textAlign = 'right';
|
|
167
|
+
ctx.fillText(content, 284, y);
|
|
168
|
+
ctx.textAlign = 'left';
|
|
169
|
+
y += 20;
|
|
170
|
+
}
|
|
171
|
+
this.history.push(snapshot.game.frameIntervalMs?.avg ?? 0);
|
|
172
|
+
if (this.history.length > 80)
|
|
173
|
+
this.history.shift();
|
|
174
|
+
ctx.strokeStyle = '#46d3c8';
|
|
175
|
+
ctx.lineWidth = 1.5;
|
|
176
|
+
ctx.beginPath();
|
|
177
|
+
this.history.forEach((ms, index) => {
|
|
178
|
+
const x = 16 + index * 268 / 79, graphY = 337 - Math.min(ms, 100) * .27;
|
|
179
|
+
if (index)
|
|
180
|
+
ctx.lineTo(x, graphY);
|
|
181
|
+
else
|
|
182
|
+
ctx.moveTo(x, graphY);
|
|
183
|
+
});
|
|
184
|
+
ctx.stroke();
|
|
185
|
+
ctx.fillStyle = '#658299';
|
|
186
|
+
ctx.font = '10px ui-monospace, monospace';
|
|
187
|
+
ctx.fillText(`${renderer?.dimension ?? '—'} / ${renderer?.backend ?? 'no renderer'} · N/A = no sample / unsupported`, 16, 345);
|
|
188
|
+
this.element.setAttribute('aria-label', `Performance ${status}; FPS ${value(snapshot.game.updateFps)}; draw calls ${avg(renderer?.drawCalls)}`);
|
|
189
|
+
}
|
|
190
|
+
destroy() { this.element.remove(); }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Lifecycle snapshots are independent of the non-overlapping interval windows. */
|
|
194
|
+
class ReportScheduler {
|
|
195
|
+
constructor(report) {
|
|
196
|
+
this.report = report;
|
|
197
|
+
this.timer = null;
|
|
198
|
+
this.enabled = false;
|
|
199
|
+
this.intervalMs = 10000;
|
|
200
|
+
}
|
|
201
|
+
configure(enabled, intervalMs = this.intervalMs) {
|
|
202
|
+
const changed = intervalMs !== this.intervalMs;
|
|
203
|
+
this.enabled = enabled;
|
|
204
|
+
this.intervalMs = intervalMs;
|
|
205
|
+
if (!enabled || changed)
|
|
206
|
+
this.stopTimer();
|
|
207
|
+
}
|
|
208
|
+
lifecycle(reason, payload, replayed = false) {
|
|
209
|
+
if (!this.enabled)
|
|
210
|
+
return;
|
|
211
|
+
this.report(reason, replayed, payload);
|
|
212
|
+
this.arm();
|
|
213
|
+
}
|
|
214
|
+
arm() {
|
|
215
|
+
if (!this.enabled || this.timer !== null)
|
|
216
|
+
return;
|
|
217
|
+
this.timer = setInterval(() => this.report('interval'), this.intervalMs);
|
|
218
|
+
}
|
|
219
|
+
stopTimer() {
|
|
220
|
+
if (this.timer !== null)
|
|
221
|
+
clearInterval(this.timer);
|
|
222
|
+
this.timer = null;
|
|
223
|
+
}
|
|
224
|
+
destroy() { this.enabled = false; this.stopTimer(); }
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const COMBOS_STATS_SET_PANEL = 'combos-development-tool:set-stats-panel';
|
|
228
|
+
const COMBOS_STATS_SET_REPORTING = 'combos-game:set-performance-reporting';
|
|
229
|
+
const COMBOS_STATS_PERFORMANCE = 'combos-game:performance';
|
|
230
|
+
const COMBOS_STATS_GET_STATE = 'combos-development-tool:get-stats-state';
|
|
231
|
+
const COMBOS_STATS_STATE_CHANGED = 'combos-development-tool:stats-state-changed';
|
|
232
|
+
const COMBOS_STATS_GET_SNAPSHOT = 'combos-development-tool:get-stats-snapshot';
|
|
233
|
+
const COMBOS_STATS_SNAPSHOT = 'combos-development-tool:stats-snapshot';
|
|
234
|
+
const COMBOS_STATS_READY = 'combos-development-tool:stats-ready';
|
|
235
|
+
const COMBOS_STATS_ERROR = 'combos-development-tool:stats-error';
|
|
236
|
+
const STATS_COMMANDS = [COMBOS_STATS_SET_PANEL, COMBOS_STATS_SET_REPORTING, COMBOS_STATS_GET_STATE, COMBOS_STATS_GET_SNAPSHOT];
|
|
237
|
+
|
|
238
|
+
let nextInstance = 1;
|
|
239
|
+
class StatsSystem extends System {
|
|
240
|
+
constructor() {
|
|
241
|
+
super(...arguments);
|
|
242
|
+
this.panelOptions = {};
|
|
243
|
+
this.panel = null;
|
|
244
|
+
this.panelTimer = null;
|
|
245
|
+
this.origin = '*';
|
|
246
|
+
this.allowedOrigins = [];
|
|
247
|
+
this.gameHandlers = new Map();
|
|
248
|
+
this.windowHandlers = new Map();
|
|
249
|
+
this.lastRaf = null;
|
|
250
|
+
this.lastSample = null;
|
|
251
|
+
this.pendingInputs = [];
|
|
252
|
+
this.seq = 0;
|
|
253
|
+
this.destroyed = false;
|
|
254
|
+
this.scheduler = new ReportScheduler((reason, replayed, lifecycle) => this.report(reason, replayed, lifecycle));
|
|
255
|
+
this.sampleWindows = [];
|
|
256
|
+
this.observer = {
|
|
257
|
+
raf: at => {
|
|
258
|
+
if (!this.active)
|
|
259
|
+
return;
|
|
260
|
+
for (const window of this.windows()) {
|
|
261
|
+
window.rafCount++;
|
|
262
|
+
if (this.lastRaf !== null)
|
|
263
|
+
window.interval(at - this.lastRaf, this.game.ticker.frameRate);
|
|
264
|
+
}
|
|
265
|
+
this.lastRaf = at;
|
|
266
|
+
this.lastSample = at;
|
|
267
|
+
},
|
|
268
|
+
update: (at, ms) => {
|
|
269
|
+
if (!this.active)
|
|
270
|
+
return;
|
|
271
|
+
for (const window of this.windows()) {
|
|
272
|
+
window.updateCount++;
|
|
273
|
+
window.cpu.add(ms);
|
|
274
|
+
}
|
|
275
|
+
this.lastSample = at;
|
|
276
|
+
},
|
|
277
|
+
render: sample => this.renderSample(sample),
|
|
278
|
+
input: (_at, delay, dispatch) => {
|
|
279
|
+
if (!this.active)
|
|
280
|
+
return;
|
|
281
|
+
for (const window of this.windows()) {
|
|
282
|
+
window.inputDelay.add(delay);
|
|
283
|
+
window.inputDispatch.add(dispatch);
|
|
284
|
+
}
|
|
285
|
+
},
|
|
286
|
+
};
|
|
287
|
+
this.onReady = () => { this.scheduler.lifecycle('ready', this.readyPayload()); };
|
|
288
|
+
this.onRunState = () => {
|
|
289
|
+
const now = runtimeNow();
|
|
290
|
+
for (const window of this.windows())
|
|
291
|
+
window.setActive(this.active, now);
|
|
292
|
+
this.lastRaf = null;
|
|
293
|
+
this.pendingInputs = [];
|
|
294
|
+
};
|
|
295
|
+
this.onInput = (event) => {
|
|
296
|
+
if (!this.active || event.repeat)
|
|
297
|
+
return;
|
|
298
|
+
const target = event.target;
|
|
299
|
+
const provider = [...this.game.diagnostics.providers.values()].find(p => p.canvas === target);
|
|
300
|
+
if (!provider?.canvas)
|
|
301
|
+
return;
|
|
302
|
+
const now = runtimeNow();
|
|
303
|
+
const timestamp = event.timeStamp > 1e12 ? event.timeStamp - performance.timeOrigin : event.timeStamp;
|
|
304
|
+
if (Number.isFinite(timestamp)) {
|
|
305
|
+
if (this.pendingInputs.length >= 128)
|
|
306
|
+
this.pendingInputs.shift();
|
|
307
|
+
this.pendingInputs.push({ canvas: provider.canvas, at: Math.min(now, timestamp) });
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
this.onMessage = (event) => {
|
|
311
|
+
if (event.source !== window && event.source !== window.parent)
|
|
312
|
+
return;
|
|
313
|
+
if (!isAllowedMessageOrigin(event.origin, this.allowedOrigins))
|
|
314
|
+
return;
|
|
315
|
+
if (event.data && STATS_COMMANDS.includes(event.data.type))
|
|
316
|
+
this.command(event.data.type, event.data);
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
static { this.systemName = 'Stats'; }
|
|
320
|
+
get visible() { return typeof document === 'undefined' || !document.hidden; }
|
|
321
|
+
get active() { return !!this.game.playing && this.visible && !!this.unsubscribe; }
|
|
322
|
+
windows() {
|
|
323
|
+
this.sampleWindows[0] = this.reportWindow;
|
|
324
|
+
if (this.panelOptions.enabled) {
|
|
325
|
+
this.sampleWindows[1] = this.viewWindow;
|
|
326
|
+
this.sampleWindows.length = 2;
|
|
327
|
+
}
|
|
328
|
+
else
|
|
329
|
+
this.sampleWindows.length = 1;
|
|
330
|
+
return this.sampleWindows;
|
|
331
|
+
}
|
|
332
|
+
init(params = {}) {
|
|
333
|
+
this.instanceId = params.instanceId ?? `game-${nextInstance++}`;
|
|
334
|
+
this.observer.gpuTiming = params.gpuTiming === true;
|
|
335
|
+
this.origin = params.postMessageOrigin ?? this.game.pluginInitNotifyTargetOrigin ?? '*';
|
|
336
|
+
this.allowedOrigins = mergeAllowedMessageOrigins(params.allowedMessageOrigins);
|
|
337
|
+
this.panelOptions = { enabled: false, position: 'top-left', refreshIntervalMs: 250, ...params.panel };
|
|
338
|
+
const now = runtimeNow();
|
|
339
|
+
this.reportWindow = new StatsWindow(now, false);
|
|
340
|
+
this.viewWindow = new StatsWindow(now, false);
|
|
341
|
+
this.scheduler.configure(params.reporting?.enabled !== false, this.validInterval(params.reporting?.intervalMs ?? 10000));
|
|
342
|
+
this.bindCommands();
|
|
343
|
+
this.game.on(COMBOS_GAME_READY, this.onReady);
|
|
344
|
+
this.game.on(COMBOS_GAME_STATE_CHANGED, this.onRunState);
|
|
345
|
+
this.unsubscribeMessages = observeRuntimeMessages(message => {
|
|
346
|
+
if (message.type === COMBOS_GAME_RESOURCES_READY)
|
|
347
|
+
this.scheduler.lifecycle('resources-ready', message);
|
|
348
|
+
});
|
|
349
|
+
if (typeof window !== 'undefined') {
|
|
350
|
+
window.addEventListener('message', this.onMessage);
|
|
351
|
+
window.addEventListener('pointerdown', this.onInput, true);
|
|
352
|
+
window.addEventListener('pointerup', this.onInput, true);
|
|
353
|
+
window.addEventListener('keydown', this.onInput, true);
|
|
354
|
+
document.addEventListener('visibilitychange', this.onRunState);
|
|
355
|
+
}
|
|
356
|
+
this.syncSampling();
|
|
357
|
+
this.syncPanel();
|
|
358
|
+
this.send({ type: COMBOS_STATS_READY, ...this.state() });
|
|
359
|
+
if (this.game.ready)
|
|
360
|
+
this.scheduler.lifecycle('ready', this.readyPayload(), true);
|
|
361
|
+
const resourcesReady = getLatestResourcesReady();
|
|
362
|
+
if (resourcesReady)
|
|
363
|
+
this.scheduler.lifecycle('resources-ready', resourcesReady, true);
|
|
364
|
+
}
|
|
365
|
+
readyPayload() {
|
|
366
|
+
return { error: this.game.readyError === undefined ? null : String(this.game.readyError) };
|
|
367
|
+
}
|
|
368
|
+
renderSample(sample) {
|
|
369
|
+
if (!this.active)
|
|
370
|
+
return;
|
|
371
|
+
for (const window of this.windows())
|
|
372
|
+
window.render(sample);
|
|
373
|
+
this.pendingInputs = this.pendingInputs.filter(input => {
|
|
374
|
+
if (sample.at - input.at > 10000)
|
|
375
|
+
return false;
|
|
376
|
+
if (input.canvas !== sample.provider.canvas)
|
|
377
|
+
return true;
|
|
378
|
+
for (const window of this.windows())
|
|
379
|
+
window.inputToSubmit.add(Math.max(0, sample.at - input.at));
|
|
380
|
+
return false;
|
|
381
|
+
});
|
|
382
|
+
this.lastSample = sample.at;
|
|
383
|
+
}
|
|
384
|
+
syncSampling() {
|
|
385
|
+
const enabled = this.scheduler.enabled || this.panelOptions.enabled;
|
|
386
|
+
if (enabled && !this.unsubscribe)
|
|
387
|
+
this.unsubscribe = this.game.diagnostics.subscribe(this.observer);
|
|
388
|
+
if (!enabled && this.unsubscribe) {
|
|
389
|
+
this.unsubscribe();
|
|
390
|
+
this.unsubscribe = undefined;
|
|
391
|
+
}
|
|
392
|
+
this.onRunState();
|
|
393
|
+
}
|
|
394
|
+
syncPanel() {
|
|
395
|
+
if (this.panelTimer !== null)
|
|
396
|
+
clearInterval(this.panelTimer);
|
|
397
|
+
this.panelTimer = null;
|
|
398
|
+
if (!this.panelOptions.enabled || typeof document === 'undefined') {
|
|
399
|
+
this.panel?.destroy();
|
|
400
|
+
this.panel = null;
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (!this.panel)
|
|
404
|
+
this.panel = new StatsPanel(this.instanceId, this.panelOptions);
|
|
405
|
+
else
|
|
406
|
+
this.panel.position(this.panelOptions);
|
|
407
|
+
this.panel.draw(this.snapshot(this.viewWindow));
|
|
408
|
+
this.panelTimer = setInterval(() => {
|
|
409
|
+
const now = runtimeNow();
|
|
410
|
+
this.panel?.draw(this.snapshot(this.viewWindow));
|
|
411
|
+
this.viewWindow = new StatsWindow(now, this.active);
|
|
412
|
+
}, this.panelOptions.refreshIntervalMs);
|
|
413
|
+
}
|
|
414
|
+
setPanel(options) {
|
|
415
|
+
if (this.destroyed)
|
|
416
|
+
throw new Error('StatsSystem has been destroyed');
|
|
417
|
+
if (typeof options.enabled !== 'boolean')
|
|
418
|
+
throw new Error('enabled must be boolean');
|
|
419
|
+
if (options.position !== undefined && !['top-left', 'top-right', 'bottom-left', 'bottom-right'].includes(options.position))
|
|
420
|
+
throw new Error('invalid panel position');
|
|
421
|
+
if (options.refreshIntervalMs !== undefined && (!Number.isFinite(options.refreshIntervalMs) || options.refreshIntervalMs < 100 || options.refreshIntervalMs > 10000))
|
|
422
|
+
throw new Error('panel refreshIntervalMs must be 100–10000');
|
|
423
|
+
if (options.metrics !== undefined && (!Array.isArray(options.metrics) || options.metrics.length > 32 || options.metrics.some(metric => typeof metric !== 'string')))
|
|
424
|
+
throw new Error('metrics must be an array of strings');
|
|
425
|
+
if (options.rendererId !== undefined && typeof options.rendererId !== 'string')
|
|
426
|
+
throw new Error('rendererId must be a string');
|
|
427
|
+
if (options.enabled && !this.panelOptions.enabled)
|
|
428
|
+
this.viewWindow = new StatsWindow(runtimeNow(), false);
|
|
429
|
+
this.panelOptions = { ...this.panelOptions, ...Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined)) };
|
|
430
|
+
this.syncSampling();
|
|
431
|
+
this.syncPanel();
|
|
432
|
+
}
|
|
433
|
+
setReporting(enabled, intervalMs = this.scheduler.intervalMs) {
|
|
434
|
+
if (this.destroyed)
|
|
435
|
+
throw new Error('StatsSystem has been destroyed');
|
|
436
|
+
if (typeof enabled !== 'boolean')
|
|
437
|
+
throw new Error('enabled must be boolean');
|
|
438
|
+
const wasEnabled = this.scheduler.enabled;
|
|
439
|
+
const changed = intervalMs !== this.scheduler.intervalMs;
|
|
440
|
+
this.scheduler.configure(enabled, this.validInterval(intervalMs));
|
|
441
|
+
if (enabled && (!wasEnabled || changed)) {
|
|
442
|
+
this.reportWindow = new StatsWindow(runtimeNow(), false);
|
|
443
|
+
this.syncSampling();
|
|
444
|
+
if (this.game.ready)
|
|
445
|
+
this.scheduler.lifecycle('ready', this.readyPayload(), true);
|
|
446
|
+
const resourcesReady = getLatestResourcesReady();
|
|
447
|
+
if (resourcesReady && !wasEnabled)
|
|
448
|
+
this.scheduler.lifecycle('resources-ready', resourcesReady, true);
|
|
449
|
+
}
|
|
450
|
+
else
|
|
451
|
+
this.syncSampling();
|
|
452
|
+
}
|
|
453
|
+
validInterval(value) {
|
|
454
|
+
if (!Number.isFinite(value) || value < 1000 || value > 3600000)
|
|
455
|
+
throw new Error('report intervalMs must be 1000–3600000');
|
|
456
|
+
return value;
|
|
457
|
+
}
|
|
458
|
+
bindCommands() {
|
|
459
|
+
for (const type of STATS_COMMANDS) {
|
|
460
|
+
const handler = (payload) => this.command(type, payload);
|
|
461
|
+
this.gameHandlers.set(type, handler);
|
|
462
|
+
this.game.on(type, handler);
|
|
463
|
+
if (typeof window !== 'undefined') {
|
|
464
|
+
const windowHandler = (event) => this.command(type, event.detail);
|
|
465
|
+
this.windowHandlers.set(type, windowHandler);
|
|
466
|
+
window.addEventListener(type, windowHandler);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
command(type, payload) {
|
|
471
|
+
if (!payload || typeof payload !== 'object' || payload.instanceId !== this.instanceId || this.destroyed)
|
|
472
|
+
return;
|
|
473
|
+
const requestId = typeof payload.requestId === 'string' || typeof payload.requestId === 'number' ? payload.requestId : undefined;
|
|
474
|
+
try {
|
|
475
|
+
if (type === COMBOS_STATS_SET_PANEL) {
|
|
476
|
+
this.setPanel({ enabled: payload.enabled, position: payload.position, refreshIntervalMs: payload.refreshIntervalMs, metrics: payload.metrics, rendererId: payload.rendererId });
|
|
477
|
+
}
|
|
478
|
+
else if (type === COMBOS_STATS_SET_REPORTING)
|
|
479
|
+
this.setReporting(payload.enabled, payload.intervalMs);
|
|
480
|
+
else if (type === COMBOS_STATS_GET_SNAPSHOT) {
|
|
481
|
+
this.send({ type: COMBOS_STATS_SNAPSHOT, ...this.getSnapshot(), requestId });
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
else if (type !== COMBOS_STATS_GET_STATE)
|
|
485
|
+
return;
|
|
486
|
+
this.send({ type: COMBOS_STATS_STATE_CHANGED, ...this.state(), requestId });
|
|
487
|
+
}
|
|
488
|
+
catch (error) {
|
|
489
|
+
this.send({ type: COMBOS_STATS_ERROR, requestId, error: String(error) });
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
state() {
|
|
493
|
+
return {
|
|
494
|
+
instanceId: this.instanceId, sampling: !!this.unsubscribe, gpuTiming: !!this.observer.gpuTiming, panel: { ...this.panelOptions },
|
|
495
|
+
reporting: { enabled: this.scheduler.enabled, intervalMs: this.scheduler.intervalMs },
|
|
496
|
+
renderers: [...this.game.diagnostics.providers.values()].map(p => ({ id: p.id, dimension: p.dimension, backend: p.backend, capabilities: p.capabilities })),
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
getSnapshot() { return this.snapshot(this.reportWindow); }
|
|
500
|
+
snapshot(window) {
|
|
501
|
+
const now = runtimeNow(), activeMs = window.activeDuration(now);
|
|
502
|
+
const fps = (count) => count > 0 && activeMs > 0 ? count * 1000 / activeMs : null;
|
|
503
|
+
const gameObjects = this.game.gameObjects;
|
|
504
|
+
const memory = globalThis.performance?.memory;
|
|
505
|
+
return {
|
|
506
|
+
schemaVersion: 1, instanceId: this.instanceId, timestamp: Date.now(),
|
|
507
|
+
windowStartMs: window.start, windowEndMs: now, activeDurationMs: activeMs,
|
|
508
|
+
sampling: !!this.unsubscribe, lastSampleAtMs: this.lastSample,
|
|
509
|
+
stale: !this.active || this.lastSample === null || now - this.lastSample > 1000,
|
|
510
|
+
paused: !this.game.playing, hidden: !this.visible, panelVisible: !!this.panel,
|
|
511
|
+
game: {
|
|
512
|
+
targetFps: this.game.ticker?.frameRate ?? 60,
|
|
513
|
+
rafFps: fps(window.rafCount), updateFps: fps(window.updateCount), updateCount: window.updateCount,
|
|
514
|
+
frameIntervalMs: window.intervals.summary(), updateCpuMs: window.cpu.summary(),
|
|
515
|
+
slowFrames: window.slowFrames, slowFrameRatio: window.intervalCount ? window.slowFrames / window.intervalCount : null,
|
|
516
|
+
framesOver50Ms: window.over50, framesOver100Ms: window.over100,
|
|
517
|
+
gameObjects: gameObjects.length, components: gameObjects.reduce((count, go) => count + go.components.length, 0),
|
|
518
|
+
},
|
|
519
|
+
renderers: [...this.game.diagnostics.providers.values()].map(provider => {
|
|
520
|
+
const r = window.renderers.get(provider.id), resources = provider.resources();
|
|
521
|
+
return {
|
|
522
|
+
id: provider.id, dimension: provider.dimension, backend: provider.backend, ...resources,
|
|
523
|
+
capabilities: JSON.parse(JSON.stringify(provider.capabilities)),
|
|
524
|
+
renderCount: r?.count ?? 0, renderFps: fps(r?.count ?? 0),
|
|
525
|
+
renderSubmitMs: r?.submit.summary() ?? null, drawCalls: r?.drawCalls.summary() ?? null,
|
|
526
|
+
canvasDrawOps: r?.canvasDrawOps.summary() ?? null, triangles: r?.triangles.summary() ?? null,
|
|
527
|
+
gpuMs: r?.gpuMs.summary() ?? null,
|
|
528
|
+
};
|
|
529
|
+
}),
|
|
530
|
+
input: { inputDelayMs: window.inputDelay.summary(), engineInputDispatchMs: window.inputDispatch.summary(), inputToNextSubmitMs: window.inputToSubmit.summary() },
|
|
531
|
+
memory: { scope: 'page', supported: !!memory, usedJSHeapBytes: memory?.usedJSHeapSize ?? null, heapLimitBytes: memory?.jsHeapSizeLimit ?? null },
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
report(reason, replayed = false, lifecycle) {
|
|
535
|
+
if (this.destroyed)
|
|
536
|
+
return;
|
|
537
|
+
const snapshot = this.snapshot(this.reportWindow);
|
|
538
|
+
// Swap before emitting: consumers may synchronously change reporting configuration.
|
|
539
|
+
if (reason === 'interval')
|
|
540
|
+
this.reportWindow = new StatsWindow(snapshot.windowEndMs, this.active);
|
|
541
|
+
const report = { type: COMBOS_STATS_PERFORMANCE, ...snapshot, seq: ++this.seq, reason, replayed, lifecycle };
|
|
542
|
+
this.send(report);
|
|
543
|
+
}
|
|
544
|
+
send(message) {
|
|
545
|
+
const envelope = { instanceId: this.instanceId, schemaVersion: 1, ...message };
|
|
546
|
+
postRuntimeMessage(envelope, this.origin);
|
|
547
|
+
this.game.emit(envelope.type, envelope);
|
|
548
|
+
if (typeof window !== 'undefined')
|
|
549
|
+
window.dispatchEvent(new CustomEvent(envelope.type, { detail: envelope }));
|
|
550
|
+
}
|
|
551
|
+
onDestroy() {
|
|
552
|
+
this.destroyed = true;
|
|
553
|
+
this.scheduler.destroy();
|
|
554
|
+
this.unsubscribe?.();
|
|
555
|
+
this.unsubscribeMessages?.();
|
|
556
|
+
this.unsubscribe = undefined;
|
|
557
|
+
if (this.panelTimer !== null)
|
|
558
|
+
clearInterval(this.panelTimer);
|
|
559
|
+
this.panel?.destroy();
|
|
560
|
+
this.panel = null;
|
|
561
|
+
this.game.off(COMBOS_GAME_READY, this.onReady);
|
|
562
|
+
this.game.off(COMBOS_GAME_STATE_CHANGED, this.onRunState);
|
|
563
|
+
for (const [type, handler] of this.gameHandlers)
|
|
564
|
+
this.game.off(type, handler);
|
|
565
|
+
if (typeof window !== 'undefined') {
|
|
566
|
+
for (const [type, handler] of this.windowHandlers)
|
|
567
|
+
window.removeEventListener(type, handler);
|
|
568
|
+
window.removeEventListener('message', this.onMessage);
|
|
569
|
+
window.removeEventListener('pointerdown', this.onInput, true);
|
|
570
|
+
window.removeEventListener('pointerup', this.onInput, true);
|
|
571
|
+
window.removeEventListener('keydown', this.onInput, true);
|
|
572
|
+
document.removeEventListener('visibilitychange', this.onRunState);
|
|
573
|
+
}
|
|
574
|
+
this.pendingInputs = [];
|
|
575
|
+
this.gameHandlers.clear();
|
|
576
|
+
this.windowHandlers.clear();
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** Auto-generated by scripts/build-package.mjs — do not edit. */
|
|
581
|
+
Object.assign(StatsSystem, {
|
|
582
|
+
packageName: "@combos-fun/plugin-stats",
|
|
583
|
+
packageVersion: "0.1.27",
|
|
584
|
+
});
|
|
585
|
+
|
|
586
|
+
export { COMBOS_STATS_ERROR, COMBOS_STATS_GET_SNAPSHOT, COMBOS_STATS_GET_STATE, COMBOS_STATS_PERFORMANCE, COMBOS_STATS_READY, COMBOS_STATS_SET_PANEL, COMBOS_STATS_SET_REPORTING, COMBOS_STATS_SNAPSHOT, COMBOS_STATS_STATE_CHANGED, STATS_COMMANDS, StatsSystem };
|
|
587
|
+
//# sourceMappingURL=plugin-stats.esm.js.map
|