@playcanvas/inspector 0.3.0 → 0.4.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.
@@ -0,0 +1,2034 @@
1
+ /** @import { AppBase, Asset, GraphicsDevice } from 'playcanvas' */
2
+
3
+ /**
4
+ * @typedef {object} PerfEvent
5
+ * @ignore
6
+ * @property {'long'|'marker'|'bake'} kind - What happened: the browser reported a long animation
7
+ * frame, the app measured a span with `performance.measure`, or the lightmapper baked lightmaps.
8
+ * @property {string} name - What it was: the script that ran longest, the measure, or the bake.
9
+ * @property {number} start - When it started, as a `performance.now()` time.
10
+ * @property {number} duration - How long it took in milliseconds, zero for an instant.
11
+ * @property {string} [detail] - More about it, such as the blocking time of a long frame.
12
+ * @property {PerfBake} [bake] - The figures of a bake of lightmaps.
13
+ */
14
+
15
+ /**
16
+ * @typedef {object} PerfBake
17
+ * @ignore
18
+ * @property {number} lightmaps - How many lightmaps it baked.
19
+ * @property {number} passes - How many render passes it took.
20
+ * @property {number} targets - The time creating render targets, in milliseconds.
21
+ * @property {number} shaders - How many shaders it linked.
22
+ * @property {number} compile - The time compiling and linking them.
23
+ */
24
+
25
+ /**
26
+ * @typedef {object} PerfScript
27
+ * @ignore
28
+ * @property {number} id - Its index into {@link PerfCapture#scriptNames}.
29
+ * @property {string} name - The name the script type is registered under.
30
+ * @property {number} update - Its own time in its update, in milliseconds.
31
+ * @property {number} post - Its own time in its post-update.
32
+ * @property {number} init - Its own time initializing and post-initializing, as new instances do,
33
+ * and swapping in when hot-reloaded.
34
+ * @property {number} calls - How many of its methods were called.
35
+ * @property {number} updateCalls - How many times its update was called, once an instance.
36
+ * @property {number} postCalls - How many times its post-update was called.
37
+ * @property {number} initCalls - How many times it was initialized, post-initialized or swapped.
38
+ */
39
+
40
+ /**
41
+ * @typedef {object} PerfLoad
42
+ * @ignore
43
+ * @property {'asset'|'request'|'milestone'} kind - What it is: an asset loading, a request the
44
+ * page made, or a moment of the app or the page, such as its first paint.
45
+ * @property {string} name - The asset, the file requested, or the moment.
46
+ * @property {number} start - When it began, as a `performance.now()` time; NaN for an asset that
47
+ * began loading before recording did.
48
+ * @property {number} end - When it ended; the same as its start for a moment.
49
+ * @property {string} [type] - The type of an asset.
50
+ * @property {number} [id] - The id of an asset.
51
+ * @property {boolean} [failed] - Whether an asset failed to load.
52
+ * @property {number} [netStart] - When the request of an asset or a request began on the network.
53
+ * @property {number} [netEnd] - When its last byte arrived.
54
+ * @property {number} [firstByte] - When its first byte arrived.
55
+ * @property {number} [bytes] - Its size over the network, the size of the file where it came
56
+ * from the cache.
57
+ * @property {boolean} [cached] - Whether it came from the cache.
58
+ * @property {string} [url] - The file requested.
59
+ */
60
+
61
+ /**
62
+ * @typedef {object} PerfPass
63
+ * @ignore
64
+ * @property {string} name - The profiler name of the pass. Passes sharing a name are summed.
65
+ * @property {number} time - Its GPU time in milliseconds.
66
+ */
67
+
68
+ /**
69
+ * @typedef {object} PerfGpuPass
70
+ * @ignore
71
+ * @property {string} name - The profiler name of the pass.
72
+ * @property {number} time - Its GPU time in milliseconds.
73
+ * @property {string|null} owner - The profiler name of the effect running it, the pass of the
74
+ * frame graph it is a before or after pass of, or null for a pass of its own.
75
+ * @property {number} occurrence - Which of the passes of the frame graph with its name it is, 0
76
+ * for the first, or -1 where it was not matched to one.
77
+ * @property {number} ownerOccurrence - Which of the passes with its owner's name its owner is,
78
+ * or -1.
79
+ */
80
+
81
+ /**
82
+ * How many frames a capture keeps, about 17 seconds at 60 Hz: few enough that the charts show
83
+ * them without squeezing many frames into each pixel. The oldest frames make way once it is full.
84
+ */
85
+ const CAPTURE_FRAMES = 1000;
86
+
87
+ // how many frames back the GPU timings of a frame are looked for: they resolve a few frames late
88
+ const GPU_LATENCY_FRAMES = 16;
89
+
90
+ // the figures kept per GPU pass of a frame: the id of its name, its time, the id of its owner's
91
+ // name or -1, and which of the passes of the frame graph with its name, and with its owner's, it
92
+ // matched, or -1
93
+ const PASS_STRIDE = 5;
94
+
95
+ // the share of a frame's timed passes that have to match passes of the frame graph for their
96
+ // owners to be trusted
97
+ const PASS_MATCH_SHARE = 0.6;
98
+
99
+ // the events kept per frame, so an app measuring heavily cannot grow a frame without bound
100
+ const MAX_FRAME_EVENTS = 64;
101
+
102
+ // the most counters of `app.stats.user` kept, as an app could set any number
103
+ const MAX_COUNTERS = 64;
104
+
105
+ // the loads kept per entry: a startup can make hundreds of requests
106
+ const MAX_ENTRY_LOADS = 4096;
107
+
108
+ // a time between two entries longer than this, in milliseconds, as between two recordings, is
109
+ // folded to FOLDED_GAP on the time axis, so it does not squeeze everything else
110
+ const GAP_FOLD = 1000;
111
+ const FOLDED_GAP = 250;
112
+
113
+ // the kinds of entry of the capture: a frame, or the start of the app, from the page opening to
114
+ // its first frame
115
+ const ENTRY_FRAME = 0;
116
+ const ENTRY_STARTUP = 1;
117
+
118
+ // the figures kept per script type in a frame: its own time in its update, its post-update and its
119
+ // initializing; how many times each was called, from SCRIPT_CALLS on; and from SCRIPT_ORDER on, the
120
+ // place of its first update and its first post-update among the types', 1 for the first, which is
121
+ // the order the types ran in
122
+ const SCRIPT_STRIDE = 8;
123
+ const SCRIPT_CALLS = 3;
124
+ const SCRIPT_ORDER = 6;
125
+
126
+ // how many calls the cost of timing a script call is measured over, the best of a few rounds
127
+ const PROBE_CALLS = 2000;
128
+ const PROBE_ROUNDS = 3;
129
+
130
+ /**
131
+ * The figures recorded for every frame, each in a ring of its own. Durations are in milliseconds,
132
+ * timestamps are `performance.now()` times, memory is in bytes and a figure the engine did not
133
+ * provide is NaN.
134
+ *
135
+ * @type {string[]}
136
+ */
137
+ const CHANNELS = [
138
+ // the tick: when it began, how long until the next one began, and when its work ended
139
+ 'tick', 'interval', 'end', 'appFrame', 'version',
140
+ // CPU phases on the main thread, and when each began
141
+ 'update', 'updateStart', 'systems', 'systemsStart', 'physics', 'physicsStart', 'anim', 'animStart',
142
+ 'post', 'postStart', 'render', 'renderStart', 'inspector', 'inspectorStart', 'cpu',
143
+ // the CPU time without the inspector's own, and the parts of the update the CPU chart stacks
144
+ // that are worked out from the others: the systems without the physics they include, and the
145
+ // rest of the update
146
+ 'cpuApp', 'cpuSystems', 'cpuOther',
147
+ // reported by the splat sort worker, off the main thread
148
+ 'splatSort',
149
+ // render phases, with the profiler and debug engines only; the batching is the batcher
150
+ // updating the dynamic batches and creating those of groups changed, the second part apart
151
+ 'batching', 'batchCreate', 'cull', 'sort', 'skin', 'morph', 'shadows', 'forward', 'clusters', 'clusterCount',
152
+ // the work submitted
153
+ 'draws', 'drawsForward', 'drawsShadow', 'drawsMisc', 'drawsSkinned', 'primitives',
154
+ 'materialSwitches', 'shaderSwitches', 'cameras', 'shadowUpdates', 'dispatches', 'computePasses', 'splats',
155
+ // filled in when the GPU timings of the frame resolve
156
+ 'gpu',
157
+ // memory, as the frame left it
158
+ 'vram', 'vramTex', 'vramVb', 'vramIb', 'vramUb', 'vramSb', 'heap',
159
+ // resources on the device, as the frame left them
160
+ 'textures', 'targets', 'shaders', 'buffers', 'pipelines',
161
+ // shader compiles and links the device reported, with the profiler and debug engines only
162
+ 'compiles', 'compileTime',
163
+ // while scripts are timed, NaN otherwise: their own time in the update of the systems and in
164
+ // the post-update, with when the first call of each began; all their time, wherever it ran;
165
+ // the part of it initializing; their calls; and the estimated cost of timing them, which
166
+ // counts as the inspector's. The CPU chart stacks the first two as Scripts, and the
167
+ // post-update without them
168
+ 'scripts', 'scriptsUpdate', 'scriptsUpdateStart', 'scriptsPost', 'scriptsPostStart', 'scriptsTotal',
169
+ 'scriptsInit', 'scriptCalls', 'scriptCost', 'cpuPost',
170
+ // the entry on the time axis: what it is, where it starts and how wide it is there, in
171
+ // milliseconds, and the time before it that is folded away
172
+ 'kind', 'pos', 'width', 'gap'
173
+ ];
174
+
175
+ // the channels of the scripts, NaN for a frame they were not timed in
176
+ const SCRIPT_CHANNELS = ['scripts', 'scriptsUpdate', 'scriptsPost', 'scriptsTotal', 'scriptsInit', 'scriptCalls', 'scriptCost'];
177
+
178
+ // the channels a detailed engine publishes, NaN in the others
179
+ const DETAILED_CHANNELS = [
180
+ 'cull', 'sort', 'skin', 'morph', 'shadows', 'forward', 'clusters', 'clusterCount', 'drawsForward',
181
+ 'drawsShadow', 'drawsMisc', 'drawsSkinned', 'primitives', 'materialSwitches', 'shaderSwitches',
182
+ 'cameras', 'shadowUpdates'
183
+ ];
184
+
185
+ // the running count of pipelineCount, and the callback adding a cache bucket to it
186
+ let pipelineTotal = 0;
187
+ const addBucket = (bucket) => {
188
+ pipelineTotal += bucket.length;
189
+ };
190
+
191
+ // the events of the many frames without any, shared
192
+ const NO_EVENTS = Object.freeze(/** @type {PerfEvent[]} */ ([]));
193
+
194
+ // the loads of the many entries without any, shared
195
+ const NO_LOADS = Object.freeze(/** @type {PerfLoad[]} */ ([]));
196
+
197
+ /**
198
+ * @param {string|null} url - A URL, relative to the page or absolute.
199
+ * @returns {string|null} The URL absolute, as the browser names its requests.
200
+ */
201
+ function absoluteUrl(url) {
202
+ if (!url) return null;
203
+ try {
204
+ return new URL(url, typeof document !== 'undefined' ? document.baseURI : undefined).href;
205
+ } catch (e) {
206
+ return url;
207
+ }
208
+ }
209
+
210
+ /**
211
+ * @param {string} url - An absolute URL.
212
+ * @returns {string} The file it names, without the folders and the query.
213
+ */
214
+ function fileName(url) {
215
+ const path = url.split(/[?#]/)[0];
216
+ return decodeURIComponent(path.slice(path.lastIndexOf('/') + 1)) || path;
217
+ }
218
+
219
+ /**
220
+ * @param {GraphicsDevice} device - The device.
221
+ * @returns {number} The render and compute pipelines the device has created and caches, or NaN on a
222
+ * device that creates none.
223
+ */
224
+ function pipelineCount(device) {
225
+ const webgpu = /** @type {any} */ (device);
226
+ const render = webgpu.renderPipeline?.cache;
227
+ if (!render) return NaN;
228
+ // counted through a callback made once, as this runs every frame while recording; hash
229
+ // collisions share a bucket, so the size of the map is not the count
230
+ pipelineTotal = 0;
231
+ render.forEach(addBucket);
232
+ webgpu.computePipeline?.cache?.forEach(addBucket);
233
+ return pipelineTotal;
234
+ }
235
+
236
+ /**
237
+ * @param {AppBase} app - The app.
238
+ * @returns {{ createTime: number, updateLastFrameTime: number }|null} The times of its batcher,
239
+ * which the profiler and debug engines keep, or null.
240
+ */
241
+ function batcherStats(app) {
242
+ const stats = /** @type {any} */ (app.stats);
243
+ return (stats && 'batcher' in stats ? stats.batcher : /** @type {any} */ (app)._batcher?._stats) ?? null;
244
+ }
245
+
246
+ /**
247
+ * @param {AppBase} app - An app.
248
+ * @returns {any} The prototype of its script components, through whose `_scriptMethod` the
249
+ * engine calls every method of a script, or null when the app has no script system or the engine
250
+ * calls them some other way.
251
+ */
252
+ function scriptPrototype(app) {
253
+ const proto = /** @type {any} */ (app.systems)?.script?.ComponentType?.prototype;
254
+ return typeof proto?._scriptMethod === 'function' ? proto : null;
255
+ }
256
+
257
+ /**
258
+ * @returns {number} The smallest step the clock moves by, in milliseconds, NaN for a clock that
259
+ * did not move. Browsers coarsen it on pages that are not cross-origin isolated, to a tenth of a
260
+ * millisecond in Chromium.
261
+ */
262
+ function clockStep() {
263
+ let step = Infinity;
264
+ let last = performance.now();
265
+ const until = last + 5;
266
+ for (let steps = 0, reads = 0; steps < 4 && reads < 1e6; reads++) {
267
+ const now = performance.now();
268
+ if (now > last) {
269
+ step = Math.min(step, now - last);
270
+ last = now;
271
+ steps++;
272
+ }
273
+ if (now > until) break;
274
+ }
275
+ return Number.isFinite(step) ? step : NaN;
276
+ }
277
+
278
+ /**
279
+ * @param {any} pass - A frame pass.
280
+ * @returns {string} The name the GPU profiler times it under.
281
+ */
282
+ function profilerName(pass) {
283
+ const name = pass.name;
284
+ return name.startsWith('RenderPass') ? name.slice(10) : name;
285
+ }
286
+
287
+ /**
288
+ * @param {any} pass - A frame pass.
289
+ * @returns {any[]} The passes it runs around itself as an effect does: its before and after
290
+ * passes, and the passes of each view of a multi-view pass. Its internal before-passes are left
291
+ * out: they are what the frame needs ahead of it, such as the directional shadows of a forward
292
+ * pass, so they stay passes of their own rather than grouping the pass as an effect.
293
+ */
294
+ function nestedPasses(pass) {
295
+ return [...pass.beforePasses ?? [], ...pass.afterPasses ?? [], ...(Array.isArray(pass.children) ? pass.children : [])];
296
+ }
297
+
298
+ /**
299
+ * @param {string} type - A performance entry type.
300
+ * @returns {boolean} Whether the browser reports entries of that type to an observer.
301
+ */
302
+ function observable(type) {
303
+ return typeof PerformanceObserver !== 'undefined' && !!PerformanceObserver.supportedEntryTypes?.includes(type);
304
+ }
305
+
306
+ /**
307
+ * @returns {number} The used JavaScript heap in bytes, or NaN where the browser does not say.
308
+ * Only Chromium browsers do, and coarsely.
309
+ */
310
+ function heapSize() {
311
+ return /** @type {any} */ (performance).memory?.usedJSHeapSize ?? NaN;
312
+ }
313
+
314
+ /**
315
+ * Records the performance of an app frame by frame, while asked to, into rings holding the last
316
+ * {@link CAPTURE_FRAMES} frames. A frame is recorded in two steps: its CPU timings when its work
317
+ * ends, and its frame interval and the counters of the work it submitted as the next frame begins,
318
+ * when the engine publishes them. GPU timings resolve a few frames later still and are matched to
319
+ * their frame by the render version they describe. Frames are numbered by sequence from the last
320
+ * clear, so a number stays put while older frames make way.
321
+ *
322
+ * Nothing is hooked into the app while not recording.
323
+ *
324
+ * @ignore
325
+ */
326
+ class PerfCapture {
327
+ /**
328
+ * The rings, one per channel of {@link CHANNELS}, indexed by {@link slot}.
329
+ *
330
+ * @type {Record<string, Float64Array>}
331
+ */
332
+ data = {};
333
+
334
+ /**
335
+ * How many frames are kept.
336
+ *
337
+ * @type {number}
338
+ */
339
+ capacity;
340
+
341
+ /**
342
+ * Whether the engine publishes the render phase timings and the breakdown of the draw calls:
343
+ * the profiler and debug engines do.
344
+ *
345
+ * @type {boolean}
346
+ */
347
+ detailed;
348
+
349
+ /**
350
+ * Bumped whenever the recorded data changes, so a view can tell when to redraw.
351
+ *
352
+ * @type {number}
353
+ */
354
+ version = 0;
355
+
356
+ /**
357
+ * The names of the GPU passes seen, indexed by the ids the frames keep.
358
+ *
359
+ * @type {string[]}
360
+ */
361
+ names = [];
362
+
363
+ /**
364
+ * Whether the GPU timings come with the frame they describe, so each lands on its own frame.
365
+ * Older engines leave it to the newest frame when the timings change, a few frames late.
366
+ *
367
+ * @type {boolean}
368
+ */
369
+ gpuExact = false;
370
+
371
+ /**
372
+ * What the browser, the device and the app report: long animation frames, the spans measured by
373
+ * the app, the size of the JavaScript heap, the pipelines created, which only WebGPU has, the
374
+ * calls of scripts, which an app without a script system has none of, the counters of
375
+ * `app.stats.user`, which engines before 2.24 have none of, and the bakes of the lightmapper,
376
+ * which an app without one has none of.
377
+ *
378
+ * @type {{ longFrames: boolean, measures: boolean, heap: boolean, pipelines: boolean, scripts: boolean, counters: boolean, lightmapper: boolean }}
379
+ */
380
+ supports;
381
+
382
+ /**
383
+ * The names of the script types timed, indexed by the ids the frames keep.
384
+ *
385
+ * @type {string[]}
386
+ */
387
+ scriptNames = [];
388
+
389
+ /**
390
+ * The names of the counters the app keeps in `app.stats.user`, indexed by the ids of
391
+ * {@link PerfCapture#counterRings}, in the order the app first set them.
392
+ *
393
+ * @type {string[]}
394
+ */
395
+ counterNames = [];
396
+
397
+ /**
398
+ * The value of each counter as each frame ended, a ring of {@link PerfCapture#slots} each,
399
+ * NaN in a frame the app did not set it in.
400
+ *
401
+ * @type {Float64Array[]}
402
+ */
403
+ counterRings = [];
404
+
405
+ /**
406
+ * @type {Map<string, number>}
407
+ * @private
408
+ */
409
+ _counterIds = new Map();
410
+
411
+ /**
412
+ * The slot the counters are being taken into.
413
+ *
414
+ * @type {number}
415
+ * @private
416
+ */
417
+ _counterSlot = 0;
418
+
419
+ /**
420
+ * The batcher's time creating batches as the last frame ended, so a frame takes what it
421
+ * created.
422
+ *
423
+ * @type {number}
424
+ * @private
425
+ */
426
+ _batchCreated = NaN;
427
+
428
+ /**
429
+ * When the lightmapper began the bake in progress, NaN while none is.
430
+ *
431
+ * @type {number}
432
+ * @private
433
+ */
434
+ _bakeStart = NaN;
435
+
436
+ /**
437
+ * The class of each script type timed, by the same ids: the one it last ran as, as a
438
+ * hot-reloaded script swaps in a new class under the same name.
439
+ *
440
+ * @type {Function[]}
441
+ */
442
+ scriptClasses = [];
443
+
444
+ /**
445
+ * The estimated cost of timing a script call in milliseconds, NaN until scripts are first
446
+ * timed.
447
+ *
448
+ * @type {number}
449
+ */
450
+ callCost = NaN;
451
+
452
+ /**
453
+ * The smallest step the clock moves by in milliseconds, which the times of single calls are
454
+ * made of, NaN until scripts are first timed.
455
+ *
456
+ * @type {number}
457
+ */
458
+ clockStep = NaN;
459
+
460
+ /**
461
+ * @type {AppBase}
462
+ * @private
463
+ */
464
+ _app;
465
+
466
+ /**
467
+ * One slot more than {@link capacity}, for the frame being recorded.
468
+ *
469
+ * @private
470
+ */
471
+ _slots;
472
+
473
+ /**
474
+ * The sequence number the frame being recorded gets once complete.
475
+ *
476
+ * @private
477
+ */
478
+ _end = 0;
479
+
480
+ /** @private */
481
+ _recording = false;
482
+
483
+ /**
484
+ * Whether the frame in the next slot has begun, and whether its work has ended.
485
+ *
486
+ * @private
487
+ */
488
+ _begun = false;
489
+
490
+ /** @private */
491
+ _ended = false;
492
+
493
+ /**
494
+ * The render version of the last frame recorded, to tell a frame that rendered nothing.
495
+ *
496
+ * @private
497
+ */
498
+ _lastVersion = -1;
499
+
500
+ /**
501
+ * The render version of the last GPU timings taken, or their frame time on older engines.
502
+ *
503
+ * @private
504
+ */
505
+ _gpuSeen = -1;
506
+
507
+ /**
508
+ * @type {Map<string, number>}
509
+ * @private
510
+ */
511
+ _nameIds = new Map();
512
+
513
+ /**
514
+ * The GPU passes of each slot in the order they ran, {@link PASS_STRIDE} figures each, written
515
+ * in place as the ring turns over, so recording makes no garbage; {@link _passCounts} says how
516
+ * many of them the slot has.
517
+ *
518
+ * @type {number[][]}
519
+ * @private
520
+ */
521
+ _passFigures = [];
522
+
523
+ /**
524
+ * @type {number[]}
525
+ * @private
526
+ */
527
+ _passCounts = [];
528
+
529
+ /**
530
+ * The owners last matched to the timed passes, by the names of the passes of the frame graph
531
+ * and of the timed passes they were matched for. The frame graph rarely changes, though some
532
+ * of its passes are made anew every frame, so most frames reuse them.
533
+ *
534
+ * @private
535
+ */
536
+ _match = { graph: /** @type {string[]} */ ([]), timed: /** @type {number[]} */ ([]), result: /** @type {number[]} */ ([]) };
537
+
538
+ /**
539
+ * The events of each slot, null for the many frames without any.
540
+ *
541
+ * @type {(PerfEvent[]|null)[]}
542
+ * @private
543
+ */
544
+ _events = [];
545
+
546
+ /**
547
+ * The loads of each slot, those that ended in its entry, null for the many without any.
548
+ *
549
+ * @type {(PerfLoad[]|null)[]}
550
+ * @private
551
+ */
552
+ _loads = [];
553
+
554
+ /**
555
+ * The assets loading, by id, from when they began: they go to the entry they end in.
556
+ *
557
+ * @type {Map<number, PerfLoad>}
558
+ * @private
559
+ */
560
+ _pending = new Map();
561
+
562
+ /**
563
+ * Whether the entry being recorded is the start of the app: the inspector began recording
564
+ * before the app ran its first frame.
565
+ *
566
+ * @private
567
+ */
568
+ _startup = false;
569
+
570
+ /**
571
+ * The latest request of each file, by URL, and the assets that ended loading before the
572
+ * browser reported the request of their file, which it does a little later: each is linked
573
+ * to the other as the second of them comes.
574
+ *
575
+ * @private
576
+ */
577
+ _requests = /** @type {Map<string, PerfLoad>} */ (new Map());
578
+
579
+ /** @private */
580
+ _awaitingRequest = /** @type {Map<string, PerfLoad>} */ (new Map());
581
+
582
+ /**
583
+ * Whether the capture began with the start of the app, so its frames count from the one after.
584
+ *
585
+ * @type {boolean}
586
+ */
587
+ startedAtStartup = false;
588
+
589
+ /**
590
+ * The slot the GPU timings being taken go to.
591
+ *
592
+ * @private
593
+ */
594
+ _gpuSlot = 0;
595
+
596
+ /**
597
+ * Whether to time scripts while recording.
598
+ *
599
+ * @private
600
+ */
601
+ _timeScripts = false;
602
+
603
+ /**
604
+ * Puts back the engine's own way of calling script methods, while scripts are timed.
605
+ *
606
+ * @type {(() => void)|null}
607
+ * @private
608
+ */
609
+ _unhook = null;
610
+
611
+ /**
612
+ * @type {Map<string, number>}
613
+ * @private
614
+ */
615
+ _scriptIds = new Map();
616
+
617
+ /**
618
+ * The figures of each script type of each slot, {@link SCRIPT_STRIDE} per type by id, reused
619
+ * as the ring turns over and grown as new types appear. Single precision, which times to well
620
+ * under a microsecond, as an app can have hundreds of types.
621
+ *
622
+ * @type {Float32Array[]}
623
+ * @private
624
+ */
625
+ _scriptTimes = [];
626
+
627
+ /**
628
+ * How many script types have had their first update, and their first post-update, in the frame
629
+ * being recorded.
630
+ *
631
+ * @private
632
+ */
633
+ _scriptOrder = [0, 0];
634
+
635
+ /**
636
+ * How deep the script call under way is nested in others, as a script creating an entity
637
+ * initializes its scripts within its own call; the time of the calls nested in it so far; and
638
+ * the phase the outermost call is in: 0 the update, 1 the post-update, 2 anywhere else.
639
+ *
640
+ * @private
641
+ */
642
+ _depth = 0;
643
+
644
+ /** @private */
645
+ _nested = 0;
646
+
647
+ /** @private */
648
+ _phase = 2;
649
+
650
+ /**
651
+ * The script calls of the frame being recorded in each phase, for the cost of timing them.
652
+ *
653
+ * @private
654
+ */
655
+ _phaseCalls = [0, 0, 0];
656
+
657
+ /**
658
+ * Whether calls are being timed to measure their cost, rather than for the frame.
659
+ *
660
+ * @private
661
+ */
662
+ _probing = false;
663
+
664
+ /** @private */
665
+ _compileStart = NaN;
666
+
667
+ /** @private */
668
+ _linkStart = NaN;
669
+
670
+ /**
671
+ * @type {PerformanceObserver[]}
672
+ * @private
673
+ */
674
+ _observers = [];
675
+
676
+ /**
677
+ * @param {AppBase} app - The app to record.
678
+ * @param {number} [capacity] - How many frames to keep. Defaults to {@link CAPTURE_FRAMES}.
679
+ */
680
+ constructor(app, capacity = CAPTURE_FRAMES) {
681
+ this._app = app;
682
+ this.capacity = capacity;
683
+ this._slots = capacity + 1;
684
+ for (const key of CHANNELS) this.data[key] = new Float64Array(this._slots);
685
+ // only the profiler and debug engines count primitives, as they do the other details
686
+ this.detailed = !!app.stats?.frame && 'primitives' in app.stats.frame;
687
+ this.supports = {
688
+ longFrames: observable('long-animation-frame'),
689
+ measures: observable('measure'),
690
+ heap: Number.isFinite(heapSize()),
691
+ pipelines: Number.isFinite(pipelineCount(app.graphicsDevice)),
692
+ scripts: !!scriptPrototype(app),
693
+ counters: app.stats?.user instanceof Map,
694
+ lightmapper: !!app.lightmapper
695
+ };
696
+ }
697
+
698
+ /**
699
+ * Stops recording and lets go of the app.
700
+ */
701
+ destroy() {
702
+ this.stop();
703
+ }
704
+
705
+ /**
706
+ * Whether frames are being recorded.
707
+ *
708
+ * @type {boolean}
709
+ */
710
+ get recording() {
711
+ return this._recording;
712
+ }
713
+
714
+ /**
715
+ * Whether to time each script type while recording: every method of a script the engine calls
716
+ * is timed, which costs the app about half a microsecond a call, counted as the inspector's
717
+ * time. A frame recorded while it is off has no script times.
718
+ *
719
+ * @type {boolean}
720
+ */
721
+ set timeScripts(on) {
722
+ this._timeScripts = on;
723
+ if (!this._recording) return;
724
+ if (on) this._hookScripts();
725
+ else this._unhookScripts();
726
+ }
727
+
728
+ get timeScripts() {
729
+ return this._timeScripts;
730
+ }
731
+
732
+ /**
733
+ * The length of the rings of {@link data}: {@link slot} is a frame's sequence number modulo
734
+ * this.
735
+ *
736
+ * @type {number}
737
+ */
738
+ get slots() {
739
+ return this._slots;
740
+ }
741
+
742
+ /**
743
+ * The sequence number of the oldest frame kept.
744
+ *
745
+ * @type {number}
746
+ */
747
+ get first() {
748
+ return Math.max(0, this._end - this.capacity);
749
+ }
750
+
751
+ /**
752
+ * One past the sequence number of the newest complete frame.
753
+ *
754
+ * @type {number}
755
+ */
756
+ get end() {
757
+ return this._end;
758
+ }
759
+
760
+ /**
761
+ * How many complete frames are kept.
762
+ *
763
+ * @type {number}
764
+ */
765
+ get count() {
766
+ return this._end - this.first;
767
+ }
768
+
769
+ /**
770
+ * Starts recording, adding to the frames kept. The frame in progress is left out, as its start
771
+ * was missed.
772
+ */
773
+ start() {
774
+ if (this._recording) return;
775
+ this._recording = true;
776
+ this._begun = false;
777
+ const app = this._app;
778
+ const device = app.graphicsDevice;
779
+ this._lastVersion = device.renderVersion;
780
+ this._gpuSeen = -1;
781
+ this.gpuExact = typeof device.gpuProfiler?.renderVersion === 'number';
782
+
783
+ app.on('frameupdate', this._onFrameUpdate, this);
784
+ app.on('frameend', this._onFrameEnd, this);
785
+ app.on('preload:start', this._onPreloadStart, this);
786
+ app.on('preload:end', this._onPreloadEnd, this);
787
+ app.on('start', this._onAppStart, this);
788
+ app.assets?.on('load:start', this._onAssetLoadStart, this);
789
+ app.assets?.on('load', this._onAssetLoad, this);
790
+ app.assets?.on('error', this._onAssetError, this);
791
+ device.on('shader:compile:start', this._onCompileStart, this);
792
+ device.on('shader:compile:end', this._onCompileEnd, this);
793
+ device.on('shader:link:start', this._onLinkStart, this);
794
+ device.on('shader:link:end', this._onLinkEnd, this);
795
+ device.on('lightmapper:start', this._onBakeStart, this);
796
+ device.on('lightmapper:end', this._onBakeEnd, this);
797
+ this._batchCreated = batcherStats(app)?.createTime ?? NaN;
798
+ this._bakeStart = NaN;
799
+ // recording from before the app's first frame records its start too, as an entry of its own
800
+ const startup = this._end === 0 && !(app.frame > 0);
801
+ if (startup) this._beginStartup();
802
+ // what the browser kept from before then only for the start of the app
803
+ this._observe('long-animation-frame', this._onLongFrames, startup);
804
+ this._observe('measure', this._onMeasures);
805
+ this._observe('resource', this._onResources);
806
+ this._observe('paint', this._onPaints, startup);
807
+ if (this._timeScripts) this._hookScripts();
808
+ }
809
+
810
+ /**
811
+ * Stops recording, keeping the frames recorded. The frame in progress is dropped.
812
+ */
813
+ stop() {
814
+ if (!this._recording) return;
815
+ this._recording = false;
816
+ this._begun = false;
817
+ const app = this._app;
818
+ const device = app.graphicsDevice;
819
+ app.off('frameupdate', this._onFrameUpdate, this);
820
+ app.off('frameend', this._onFrameEnd, this);
821
+ app.off('preload:start', this._onPreloadStart, this);
822
+ app.off('preload:end', this._onPreloadEnd, this);
823
+ app.off('start', this._onAppStart, this);
824
+ app.assets?.off('load:start', this._onAssetLoadStart, this);
825
+ app.assets?.off('load', this._onAssetLoad, this);
826
+ app.assets?.off('error', this._onAssetError, this);
827
+ device.off('shader:compile:start', this._onCompileStart, this);
828
+ device.off('shader:compile:end', this._onCompileEnd, this);
829
+ device.off('shader:link:start', this._onLinkStart, this);
830
+ device.off('shader:link:end', this._onLinkEnd, this);
831
+ device.off('lightmapper:start', this._onBakeStart, this);
832
+ device.off('lightmapper:end', this._onBakeEnd, this);
833
+ for (const observer of this._observers) observer.disconnect();
834
+ this._observers.length = 0;
835
+ this._unhookScripts();
836
+ this._startup = false;
837
+ this._pending.clear();
838
+ this._requests.clear();
839
+ this._awaitingRequest.clear();
840
+ this.version++;
841
+ }
842
+
843
+ /**
844
+ * Forgets every frame, and numbers the next one zero.
845
+ */
846
+ clear() {
847
+ this._end = 0;
848
+ this.startedAtStartup = false;
849
+ this._begun = false;
850
+ this._gpuSeen = -1;
851
+ this.version++;
852
+ }
853
+
854
+ /**
855
+ * @param {number} seq - The sequence number of a frame.
856
+ * @returns {boolean} Whether that frame is kept.
857
+ */
858
+ has(seq) {
859
+ return seq >= this.first && seq < this._end;
860
+ }
861
+
862
+ /**
863
+ * @param {number} seq - The sequence number of a kept frame.
864
+ * @returns {number} Its index into the rings of {@link data}.
865
+ */
866
+ slot(seq) {
867
+ return seq % this._slots;
868
+ }
869
+
870
+ /**
871
+ * @param {string} key - A channel of {@link CHANNELS}.
872
+ * @param {number} seq - The sequence number of a kept frame.
873
+ * @returns {number} Its figure.
874
+ */
875
+ get(key, seq) {
876
+ return this.data[key][seq % this._slots];
877
+ }
878
+
879
+ /**
880
+ * @param {number} seq - The sequence number of a kept frame.
881
+ * @returns {PerfPass[]} The GPU passes of the frame, longest first, empty until its timings
882
+ * resolve.
883
+ */
884
+ passes(seq) {
885
+ // passes sharing a name summed, as the profiler of an older engine reports them
886
+ const totals = new Map();
887
+ for (const pass of this.passesInOrder(seq)) totals.set(pass.name, (totals.get(pass.name) ?? 0) + pass.time);
888
+ return [...totals].map(([name, time]) => ({ name, time })).sort((a, b) => b.time - a.time);
889
+ }
890
+
891
+ /**
892
+ * @param {number} seq - The sequence number of a kept frame.
893
+ * @returns {PerfGpuPass[]} The GPU passes of the frame in the order they ran, each apart, with
894
+ * the effect running it where the frame graph says. An engine whose profiler sums the passes
895
+ * sharing a name gives one for each name.
896
+ */
897
+ passesInOrder(seq) {
898
+ const slot = seq % this._slots;
899
+ const figures = this._passFigures[slot];
900
+ const count = this._passCounts[slot] ?? 0;
901
+ /** @type {PerfGpuPass[]} */
902
+ const passes = [];
903
+ for (let i = 0, base = 0; i < count; i++, base += PASS_STRIDE) {
904
+ const owner = figures[base + 2];
905
+ passes.push({
906
+ name: this.names[figures[base]],
907
+ time: figures[base + 1],
908
+ owner: owner >= 0 ? this.names[owner] : null,
909
+ occurrence: figures[base + 3],
910
+ ownerOccurrence: figures[base + 4]
911
+ });
912
+ }
913
+ return passes;
914
+ }
915
+
916
+ /**
917
+ * @param {number} seq - The sequence number of a kept frame.
918
+ * @returns {PerfScript[]} The script types whose methods were called in the frame, with their
919
+ * own times, the longest first; empty for a frame scripts were not timed in.
920
+ */
921
+ scripts(seq) {
922
+ const slot = seq % this._slots;
923
+ const times = this._scriptTimes[slot];
924
+ /** @type {PerfScript[]} */
925
+ const list = [];
926
+ if (!times || !(this.data.scriptsTotal[slot] >= 0)) return list;
927
+ for (let id = 0, base = 0; base < times.length; id++, base += SCRIPT_STRIDE) {
928
+ const updateCalls = times[base + SCRIPT_CALLS];
929
+ const postCalls = times[base + SCRIPT_CALLS + 1];
930
+ const initCalls = times[base + SCRIPT_CALLS + 2];
931
+ const calls = updateCalls + postCalls + initCalls;
932
+ if (calls > 0) {
933
+ list.push({ id, name: this.scriptNames[id], update: times[base], post: times[base + 1], init: times[base + 2], calls, updateCalls, postCalls, initCalls });
934
+ }
935
+ }
936
+ return list.sort((a, b) => b.update + b.post + b.init - a.update - a.post - a.init);
937
+ }
938
+
939
+ /**
940
+ * @param {number} seq - The sequence number of a kept frame.
941
+ * @returns {Float32Array|null} The figures of each script type in the frame,
942
+ * {@link SCRIPT_STRIDE} a type by its index into {@link scriptNames}: its own update,
943
+ * post-update and initialize time, how many times each was called, and the order of its first
944
+ * update and post-update among the types'. A type past the end of it had none. Null for a
945
+ * frame scripts were not timed in. Read only.
946
+ */
947
+ scriptFigures(seq) {
948
+ const slot = seq % this._slots;
949
+ return this.data.scriptsTotal[slot] >= 0 ? this._scriptTimes[slot] ?? null : null;
950
+ }
951
+
952
+ /**
953
+ * @param {number} seq - The sequence number of a kept frame.
954
+ * @param {number} id - A script type, by its index into {@link scriptNames}.
955
+ * @returns {number} The type's own time in the frame, zero when none of its methods were
956
+ * called, NaN when scripts were not timed in it.
957
+ */
958
+ scriptTime(seq, id) {
959
+ const times = this.scriptFigures(seq);
960
+ if (!times) return NaN;
961
+ const base = id * SCRIPT_STRIDE;
962
+ return base < times.length ? times[base] + times[base + 1] + times[base + 2] : 0;
963
+ }
964
+
965
+ /**
966
+ * @param {number} seq - The sequence number of a kept frame.
967
+ * @returns {readonly PerfEvent[]} What happened during the frame.
968
+ */
969
+ events(seq) {
970
+ return this._events[seq % this._slots] ?? NO_EVENTS;
971
+ }
972
+
973
+ /**
974
+ * @param {number} seq - The sequence number of a kept entry.
975
+ * @returns {readonly PerfLoad[]} What finished loading in the entry, and the moments in it.
976
+ */
977
+ loads(seq) {
978
+ return this._loads[seq % this._slots] ?? NO_LOADS;
979
+ }
980
+
981
+ /**
982
+ * @returns {PerfLoad[]} The assets loading now, which have not ended yet.
983
+ */
984
+ pendingLoads() {
985
+ return [...this._pending.values()];
986
+ }
987
+
988
+ /**
989
+ * @param {number} seq - The sequence number of an entry.
990
+ * @returns {number} The number of the frame it is, counting from 1: from the frame after the
991
+ * start of the app, where the capture began with it. It stays as frames make way.
992
+ */
993
+ frameNumber(seq) {
994
+ return this.startedAtStartup ? seq : seq + 1;
995
+ }
996
+
997
+ /**
998
+ * @param {number} seq - The sequence number of a kept entry.
999
+ * @returns {string} What it is called: Startup, or Frame and its number.
1000
+ */
1001
+ label(seq) {
1002
+ return this.isStartup(seq) ? 'Startup' : `Frame ${this.frameNumber(seq)}`;
1003
+ }
1004
+
1005
+ /**
1006
+ * @param {number} from - The first kept entry.
1007
+ * @param {number} to - The last, inclusive.
1008
+ * @returns {string} What they are called together, as Frames 3–40, or Startup to frame 40.
1009
+ */
1010
+ rangeLabel(from, to) {
1011
+ return this.isStartup(from) ? `Startup to frame ${this.frameNumber(to)}` : `Frames ${this.frameNumber(from)}–${this.frameNumber(to)}`;
1012
+ }
1013
+
1014
+ /**
1015
+ * @param {number} seq - The sequence number of a kept entry.
1016
+ * @returns {boolean} Whether it is the start of the app rather than a frame.
1017
+ */
1018
+ isStartup(seq) {
1019
+ return this.data.kind[seq % this._slots] === ENTRY_STARTUP;
1020
+ }
1021
+
1022
+ /**
1023
+ * Where the kept entries begin on the time axis, in milliseconds.
1024
+ *
1025
+ * @type {number}
1026
+ */
1027
+ get startPos() {
1028
+ return this.count ? this.data.pos[this.first % this._slots] : 0;
1029
+ }
1030
+
1031
+ /**
1032
+ * Where the kept entries end on the time axis, in milliseconds.
1033
+ *
1034
+ * @type {number}
1035
+ */
1036
+ get endPos() {
1037
+ if (!this.count) return 0;
1038
+ const slot = (this._end - 1) % this._slots;
1039
+ return this.data.pos[slot] + this.data.width[slot];
1040
+ }
1041
+
1042
+ /**
1043
+ * @param {number} pos - A place on the time axis.
1044
+ * @returns {number} The kept entry there or before it, the first one before them all, or -1
1045
+ * while none is kept.
1046
+ */
1047
+ seqAtPos(pos) {
1048
+ if (!this.count) return -1;
1049
+ const posRing = this.data.pos;
1050
+ let lo = this.first;
1051
+ let hi = this._end - 1;
1052
+ while (lo < hi) {
1053
+ const mid = (lo + hi + 1) >> 1;
1054
+ if (posRing[mid % this._slots] <= pos) lo = mid;
1055
+ else hi = mid - 1;
1056
+ }
1057
+ return lo;
1058
+ }
1059
+
1060
+ /**
1061
+ * @param {number} time - A `performance.now()` time.
1062
+ * @returns {number} Where it is on the time axis: within the entry it falls in, in proportion
1063
+ * across a folded gap, and before the first kept entry at its start.
1064
+ */
1065
+ posAt(time) {
1066
+ if (!this.count) return 0;
1067
+ const d = this.data;
1068
+ const slots = this._slots;
1069
+ let lo = this.first;
1070
+ let hi = this._end - 1;
1071
+ if (time < d.tick[lo % slots]) return d.pos[lo % slots];
1072
+ while (lo < hi) {
1073
+ const mid = (lo + hi + 1) >> 1;
1074
+ if (d.tick[mid % slots] <= time) lo = mid;
1075
+ else hi = mid - 1;
1076
+ }
1077
+ const slot = lo % slots;
1078
+ const into = time - d.tick[slot];
1079
+ const width = d.width[slot];
1080
+ if (into <= width || lo === this._end - 1) return d.pos[slot] + into;
1081
+ // in the gap before the next entry, folded on the axis
1082
+ const next = (lo + 1) % slots;
1083
+ const realGap = d.tick[next] - d.tick[slot] - width;
1084
+ const shownGap = d.pos[next] - d.pos[slot] - width;
1085
+ return d.pos[slot] + width + (realGap > 0 ? ((into - width) / realGap) * shownGap : 0);
1086
+ }
1087
+
1088
+ /**
1089
+ * Counts time the inspector spent inside the frame being recorded, so it can be told apart from
1090
+ * the app's own.
1091
+ *
1092
+ * @param {number} start - When the inspector's work began, as a `performance.now()` time.
1093
+ * @param {number} duration - How long it took in milliseconds.
1094
+ */
1095
+ addOverhead(start, duration) {
1096
+ if (!this._begun) return;
1097
+ const slot = this._end % this._slots;
1098
+ const data = this.data;
1099
+ data.inspector[slot] += duration;
1100
+ if (Number.isNaN(data.inspectorStart[slot])) data.inspectorStart[slot] = start;
1101
+ }
1102
+
1103
+ /**
1104
+ * @param {string} type - A performance entry type.
1105
+ * @param {(list: PerformanceObserverEntryList) => void} callback - Takes the entries.
1106
+ * @param {boolean} [buffered] - Whether to take the entries the browser kept from before too.
1107
+ * @private
1108
+ */
1109
+ _observe(type, callback, buffered = false) {
1110
+ if (!observable(type)) return;
1111
+ const observer = new PerformanceObserver(callback);
1112
+ observer.observe({ type, buffered });
1113
+ this._observers.push(observer);
1114
+ }
1115
+
1116
+ /**
1117
+ * The next frame begins: the previous one is complete now that the engine has published the
1118
+ * counters of the work it submitted.
1119
+ *
1120
+ * @private
1121
+ */
1122
+ _onFrameUpdate() {
1123
+ const now = performance.now();
1124
+ if (this._startup) {
1125
+ // the moment that ends the start of the app, kept with it
1126
+ this._addMilestone('First frame', now);
1127
+ this._endStartup(now);
1128
+ } else if (this._begun && this._ended) {
1129
+ this._complete(now);
1130
+ }
1131
+ this._resolveGpu();
1132
+ this._begin(now);
1133
+ }
1134
+
1135
+ /**
1136
+ * Begins the entry of the start of the app, from when the page opened. Takes what the browser
1137
+ * kept from before recording began: the requests of the page and its milestones.
1138
+ *
1139
+ * @private
1140
+ */
1141
+ _beginStartup() {
1142
+ const slot = this._end % this._slots;
1143
+ const data = this.data;
1144
+ for (const key of CHANNELS) data[key][slot] = NaN;
1145
+ data.kind[slot] = ENTRY_STARTUP;
1146
+ data.tick[slot] = 0;
1147
+ data.pos[slot] = 0;
1148
+ data.gap[slot] = 0;
1149
+ data.compiles[slot] = 0;
1150
+ data.compileTime[slot] = 0;
1151
+ data.inspector[slot] = 0;
1152
+ (this._passFigures[slot] ??= []);
1153
+ this._passCounts[slot] = 0;
1154
+ this._events[slot] = null;
1155
+ this._loads[slot] = null;
1156
+ this._startup = true;
1157
+ this.startedAtStartup = true;
1158
+ this._begun = true;
1159
+ this._ended = false;
1160
+
1161
+ if (typeof performance.getEntriesByType === 'function') {
1162
+ for (const entry of performance.getEntriesByType('resource')) this._addRequest(entry);
1163
+ const page = /** @type {any} */ (performance.getEntriesByType('navigation')[0]);
1164
+ if (page) {
1165
+ for (const [name, time] of [['Page received', page.responseEnd], ['DOM interactive', page.domInteractive], ['DOM ready', page.domContentLoadedEventEnd], ['Page load', page.loadEventEnd]]) {
1166
+ if (time > 0) this._addMilestone(name, time);
1167
+ }
1168
+ }
1169
+ }
1170
+ this.version++;
1171
+ }
1172
+
1173
+ /**
1174
+ * Ends the entry of the start of the app, as its first frame begins.
1175
+ *
1176
+ * @param {number} now - When the first frame began.
1177
+ * @private
1178
+ */
1179
+ _endStartup(now) {
1180
+ const slot = this._end % this._slots;
1181
+ this.data.width[slot] = now;
1182
+ this._startup = false;
1183
+ this._end++;
1184
+ this.version++;
1185
+ }
1186
+
1187
+ /**
1188
+ * @param {number} now - When the frame began.
1189
+ * @private
1190
+ */
1191
+ _begin(now) {
1192
+ const slot = this._end % this._slots;
1193
+ const data = this.data;
1194
+ data.tick[slot] = now;
1195
+ data.interval[slot] = NaN;
1196
+ data.inspector[slot] = 0;
1197
+ data.inspectorStart[slot] = NaN;
1198
+ data.compiles[slot] = 0;
1199
+ data.compileTime[slot] = 0;
1200
+ data.gpu[slot] = NaN;
1201
+ this._passFigures[slot] ??= [];
1202
+ this._passCounts[slot] = 0;
1203
+ this._events[slot] = null;
1204
+ this._loads[slot] = null;
1205
+ data.kind[slot] = ENTRY_FRAME;
1206
+ data.width[slot] = NaN;
1207
+ const scripts = this._unhook ? 0 : NaN;
1208
+ for (const key of SCRIPT_CHANNELS) data[key][slot] = scripts;
1209
+ data.scriptsUpdateStart[slot] = NaN;
1210
+ data.scriptsPostStart[slot] = NaN;
1211
+ const figures = this._scriptTimes[slot];
1212
+ const needed = this.scriptNames.length * SCRIPT_STRIDE;
1213
+ if (figures && figures.length >= needed) figures.fill(0);
1214
+ else this._scriptTimes[slot] = new Float32Array(needed);
1215
+ this._scriptOrder[0] = 0;
1216
+ this._scriptOrder[1] = 0;
1217
+ this._phaseCalls.fill(0);
1218
+ this._begun = true;
1219
+ this._ended = false;
1220
+ }
1221
+
1222
+ /**
1223
+ * The work of the frame has ended: takes its CPU timings, and memory and resources as it left
1224
+ * them.
1225
+ *
1226
+ * @private
1227
+ */
1228
+ _onFrameEnd() {
1229
+ if (!this._begun) return;
1230
+ this._ended = true;
1231
+
1232
+ const app = this._app;
1233
+ const device = app.graphicsDevice;
1234
+ const stats = app.stats;
1235
+ const frame = stats.frame;
1236
+ const data = this.data;
1237
+ const slot = this._end % this._slots;
1238
+
1239
+ data.end[slot] = performance.now();
1240
+ data.appFrame[slot] = app.frame ?? NaN;
1241
+
1242
+ // a frame that rendered nothing leaves the render time of the last one that did
1243
+ const version = device.renderVersion;
1244
+ const rendered = version !== this._lastVersion;
1245
+ this._lastVersion = version;
1246
+ data.version[slot] = rendered ? version : -1;
1247
+
1248
+ data.update[slot] = frame.updateTime;
1249
+ data.updateStart[slot] = frame.updateStart;
1250
+ data.systems[slot] = frame.scriptUpdate;
1251
+ data.systemsStart[slot] = frame.scriptUpdateStart;
1252
+ // the physics time stays from the last step, so it counts only when this frame stepped
1253
+ const physicsStart = frame.physicsStart;
1254
+ const stepped = physicsStart >= frame.scriptUpdateStart && physicsStart <= frame.scriptUpdateStart + frame.scriptUpdate;
1255
+ data.physics[slot] = stepped ? frame.physicsTime : 0;
1256
+ data.physicsStart[slot] = stepped ? physicsStart : NaN;
1257
+ data.anim[slot] = frame.animUpdate;
1258
+ data.animStart[slot] = frame.animUpdateStart;
1259
+ data.post[slot] = frame.scriptPostUpdate;
1260
+ data.postStart[slot] = frame.scriptPostUpdateStart;
1261
+ data.render[slot] = rendered ? frame.renderTime : 0;
1262
+ data.renderStart[slot] = rendered ? frame.renderStart : NaN;
1263
+ data.cpu[slot] = data.update[slot] + data.render[slot];
1264
+ // the inspector's time inside the update is all counted by the time the frame's work ends
1265
+ data.cpuOther[slot] = Math.max(0, data.update[slot] - data.systems[slot] - data.anim[slot] - data.post[slot] - data.inspector[slot]);
1266
+ if (data.scriptsTotal[slot] >= 0) {
1267
+ // the scripts' own time comes out of the update of the systems and the post-update
1268
+ // they ran in, and so does the cost of timing them, which is the inspector's
1269
+ const updateCost = this._phaseCalls[0] * this.callCost;
1270
+ const postCost = this._phaseCalls[1] * this.callCost;
1271
+ data.scriptCost[slot] = updateCost + postCost;
1272
+ data.scripts[slot] = data.scriptsUpdate[slot] + data.scriptsPost[slot];
1273
+ data.cpuSystems[slot] = Math.max(0, data.systems[slot] - data.physics[slot] - data.scriptsUpdate[slot] - updateCost);
1274
+ data.cpuPost[slot] = Math.max(0, data.post[slot] - data.scriptsPost[slot] - postCost);
1275
+ data.inspector[slot] += updateCost + postCost;
1276
+ } else {
1277
+ data.cpuSystems[slot] = Math.max(0, data.systems[slot] - data.physics[slot]);
1278
+ data.cpuPost[slot] = data.post[slot];
1279
+ }
1280
+ data.cpuApp[slot] = data.cpu[slot] - data.inspector[slot];
1281
+ // accumulated through the frame from the worker's reports, and reset once it ends
1282
+ data.splatSort[slot] = frame.gsplatSort ?? 0;
1283
+
1284
+ // the batcher works at the start of the render, timed by the profiler and debug engines:
1285
+ // the dynamic batches updated, and the batches created of the groups changed since
1286
+ const batcher = batcherStats(app);
1287
+ if (batcher && Number.isFinite(batcher.updateLastFrameTime)) {
1288
+ const created = Number.isFinite(this._batchCreated) ? Math.max(0, batcher.createTime - this._batchCreated) : 0;
1289
+ this._batchCreated = batcher.createTime;
1290
+ data.batchCreate[slot] = created;
1291
+ data.batching[slot] = (rendered ? batcher.updateLastFrameTime : 0) + created;
1292
+ } else {
1293
+ data.batching[slot] = NaN;
1294
+ data.batchCreate[slot] = NaN;
1295
+ }
1296
+
1297
+ // the app's own counters, as the frame left them
1298
+ const user = stats.user;
1299
+ if (user instanceof Map) {
1300
+ const rings = this.counterRings;
1301
+ for (let i = 0; i < rings.length; i++) rings[i][slot] = NaN;
1302
+ this._counterSlot = slot;
1303
+ user.forEach(this._takeCounter);
1304
+ }
1305
+
1306
+ const vram = stats.vram;
1307
+ data.vramTex[slot] = vram?.tex ?? NaN;
1308
+ data.vramVb[slot] = vram?.vb ?? NaN;
1309
+ data.vramIb[slot] = vram?.ib ?? NaN;
1310
+ data.vramUb[slot] = vram?.ub ?? 0;
1311
+ data.vramSb[slot] = vram?.sb ?? 0;
1312
+ data.vram[slot] = data.vramTex[slot] + data.vramVb[slot] + data.vramIb[slot] + data.vramUb[slot] + data.vramSb[slot];
1313
+ data.heap[slot] = heapSize();
1314
+
1315
+ data.textures[slot] = device.textures?.size ?? NaN;
1316
+ data.targets[slot] = device.targets?.size ?? NaN;
1317
+ data.shaders[slot] = device.shaders?.length ?? NaN;
1318
+ data.buffers[slot] = device.buffers?.size ?? NaN;
1319
+ data.pipelines[slot] = pipelineCount(device);
1320
+ }
1321
+
1322
+ /**
1323
+ * Completes the frame being recorded with its interval, which ends now, and the counters the
1324
+ * engine has just published for it.
1325
+ *
1326
+ * @param {number} now - When the next frame began.
1327
+ * @private
1328
+ */
1329
+ _complete(now) {
1330
+ const stats = this._app.stats;
1331
+ const frame = stats.frame;
1332
+ const drawCalls = stats.drawCalls;
1333
+ const data = this.data;
1334
+ const slot = this._end % this._slots;
1335
+
1336
+ data.interval[slot] = now - data.tick[slot];
1337
+ // on the time axis, after the entry before it, with a long time between them folded
1338
+ data.width[slot] = data.interval[slot];
1339
+ if (this.has(this._end - 1)) {
1340
+ const prev = (this._end - 1) % this._slots;
1341
+ const gap = Math.max(0, data.tick[slot] - data.tick[prev] - data.width[prev]);
1342
+ data.gap[slot] = gap > GAP_FOLD ? gap : 0;
1343
+ data.pos[slot] = data.pos[prev] + data.width[prev] + (gap > GAP_FOLD ? FOLDED_GAP : gap);
1344
+ } else {
1345
+ data.gap[slot] = 0;
1346
+ data.pos[slot] = 0;
1347
+ }
1348
+ data.draws[slot] = drawCalls?.total ?? NaN;
1349
+ data.dispatches[slot] = frame.computeDispatches ?? NaN;
1350
+ data.computePasses[slot] = frame.computePasses ?? NaN;
1351
+ data.splats[slot] = frame.gsplats ?? NaN;
1352
+
1353
+ if (this.detailed) {
1354
+ data.cull[slot] = frame.cullTime;
1355
+ data.sort[slot] = frame.sortTime;
1356
+ data.skin[slot] = frame.skinTime;
1357
+ data.morph[slot] = frame.morphTime;
1358
+ data.shadows[slot] = frame.shadowMapTime;
1359
+ data.forward[slot] = frame.forwardTime;
1360
+ data.clusters[slot] = frame.lightClustersTime;
1361
+ data.clusterCount[slot] = frame.lightClusters;
1362
+ data.drawsForward[slot] = drawCalls.forward;
1363
+ data.drawsShadow[slot] = drawCalls.shadow;
1364
+ data.drawsMisc[slot] = drawCalls.misc;
1365
+ data.drawsSkinned[slot] = drawCalls.skinned;
1366
+ data.primitives[slot] = frame.primitives;
1367
+ data.materialSwitches[slot] = frame.materials;
1368
+ data.shaderSwitches[slot] = frame.shaders;
1369
+ data.cameras[slot] = frame.cameras;
1370
+ data.shadowUpdates[slot] = frame.shadowMapUpdates;
1371
+ } else {
1372
+ for (const key of DETAILED_CHANNELS) data[key][slot] = NaN;
1373
+ }
1374
+
1375
+ this._end++;
1376
+ this.version++;
1377
+ }
1378
+
1379
+ /**
1380
+ * Times every method of a script the engine calls from now on, by wrapping the one method of
1381
+ * the script components that calls them. Measures what timing a call costs the first time.
1382
+ *
1383
+ * @private
1384
+ */
1385
+ _hookScripts() {
1386
+ if (this._unhook) return;
1387
+ const proto = scriptPrototype(this._app);
1388
+ if (!proto) return;
1389
+ const original = proto._scriptMethod;
1390
+ const app = this._app;
1391
+ const capture = this;
1392
+ let on = true;
1393
+ // a call's own time leaves out the calls nested in it, which are timed apart
1394
+ const timed = function (script, method, arg) {
1395
+ if (!on || this.system?.app !== app) return original.call(this, script, method, arg);
1396
+ const outer = capture._nested;
1397
+ const outermost = capture._depth === 0;
1398
+ if (outermost) capture._phase = method === 'update' ? 0 : method === 'postUpdate' ? 1 : 2;
1399
+ capture._nested = 0;
1400
+ capture._depth++;
1401
+ const start = performance.now();
1402
+ try {
1403
+ return original.call(this, script, method, arg);
1404
+ } finally {
1405
+ const total = performance.now() - start;
1406
+ capture._depth--;
1407
+ capture._addScript(script, method, start, total - capture._nested, outermost);
1408
+ capture._nested = outer + total;
1409
+ }
1410
+ };
1411
+ if (Number.isNaN(this.callCost)) {
1412
+ this.callCost = this._measureCallCost(timed, original);
1413
+ this.clockStep = clockStep();
1414
+ }
1415
+ proto._scriptMethod = timed;
1416
+ this._unhook = () => {
1417
+ on = false;
1418
+ // another tool that wrapped the method since keeps this wrapper, which now only passes
1419
+ // calls on
1420
+ if (proto._scriptMethod === timed) proto._scriptMethod = original;
1421
+ };
1422
+ }
1423
+
1424
+ /**
1425
+ * Stops timing scripts. The frame under way was timed only in part, so it has no script times.
1426
+ *
1427
+ * @private
1428
+ */
1429
+ _unhookScripts() {
1430
+ if (!this._unhook) return;
1431
+ this._unhook();
1432
+ this._unhook = null;
1433
+ this._depth = 0;
1434
+ this._nested = 0;
1435
+ if (this._begun) {
1436
+ const slot = this._end % this._slots;
1437
+ for (const key of SCRIPT_CHANNELS) this.data[key][slot] = NaN;
1438
+ }
1439
+ }
1440
+
1441
+ /**
1442
+ * @param {Function} timed - The wrapper timing script calls.
1443
+ * @param {Function} original - The engine's own method it wraps.
1444
+ * @returns {number} What timing a call costs, in milliseconds: an empty call made through the
1445
+ * wrapper less one made directly, the best of a few rounds.
1446
+ * @private
1447
+ */
1448
+ _measureCallCost(timed, original) {
1449
+ const component = { system: { app: this._app } };
1450
+ const script = { __scriptType: { __name: '' }, update() {} };
1451
+ const round = (method) => {
1452
+ const start = performance.now();
1453
+ for (let i = 0; i < PROBE_CALLS; i++) method.call(component, script, 'update', 0);
1454
+ return (performance.now() - start) / PROBE_CALLS;
1455
+ };
1456
+ this._probing = true;
1457
+ let wrapped = Infinity;
1458
+ let bare = Infinity;
1459
+ for (let i = 0; i < PROBE_ROUNDS; i++) {
1460
+ wrapped = Math.min(wrapped, round(timed));
1461
+ bare = Math.min(bare, round(original));
1462
+ }
1463
+ this._probing = false;
1464
+ return Math.max(0, wrapped - bare);
1465
+ }
1466
+
1467
+ /**
1468
+ * Adds a timed script call to the frame being recorded.
1469
+ *
1470
+ * @param {any} script - The script instance.
1471
+ * @param {string} method - The method called.
1472
+ * @param {number} start - When the call began.
1473
+ * @param {number} self - Its own time, without the calls nested in it.
1474
+ * @param {boolean} outermost - Whether it was not nested in another.
1475
+ * @private
1476
+ */
1477
+ _addScript(script, method, start, self, outermost) {
1478
+ if (!this._begun || this._probing) return;
1479
+ const slot = this._end % this._slots;
1480
+ const data = this.data;
1481
+ // a frame begun before scripts were timed has none of their times
1482
+ if (!(data.scriptsTotal[slot] >= 0)) return;
1483
+ const type = script.__scriptType;
1484
+ const name = type?.__name ?? 'script';
1485
+ let id = this._scriptIds.get(name);
1486
+ if (id === undefined) {
1487
+ id = this.scriptNames.length;
1488
+ this.scriptNames.push(name);
1489
+ this._scriptIds.set(name, id);
1490
+ }
1491
+ if (this.scriptClasses[id] !== type) this.scriptClasses[id] = type;
1492
+ let times = this._scriptTimes[slot];
1493
+ const base = id * SCRIPT_STRIDE;
1494
+ if (times.length < base + SCRIPT_STRIDE) {
1495
+ // a type new to the capture: room for every type known
1496
+ const grown = new Float32Array(this.scriptNames.length * SCRIPT_STRIDE);
1497
+ grown.set(times);
1498
+ this._scriptTimes[slot] = times = grown;
1499
+ }
1500
+ const column = method === 'update' ? 0 : method === 'postUpdate' ? 1 : 2;
1501
+ times[base + column] += self;
1502
+ if (column < 2 && times[base + SCRIPT_CALLS + column] === 0) times[base + SCRIPT_ORDER + column] = ++this._scriptOrder[column];
1503
+ times[base + SCRIPT_CALLS + column]++;
1504
+ data.scriptsTotal[slot] += self;
1505
+ data.scriptCalls[slot]++;
1506
+ if (column === 2) data.scriptsInit[slot] += self;
1507
+ const phase = this._phase;
1508
+ this._phaseCalls[phase]++;
1509
+ if (phase === 0) {
1510
+ data.scriptsUpdate[slot] += self;
1511
+ if (outermost && Number.isNaN(data.scriptsUpdateStart[slot])) data.scriptsUpdateStart[slot] = start;
1512
+ } else if (phase === 1) {
1513
+ data.scriptsPost[slot] += self;
1514
+ if (outermost && Number.isNaN(data.scriptsPostStart[slot])) data.scriptsPostStart[slot] = start;
1515
+ }
1516
+ }
1517
+
1518
+ /**
1519
+ * Takes GPU timings that have resolved since the last frame, and stores them with the frame
1520
+ * they describe.
1521
+ *
1522
+ * @private
1523
+ */
1524
+ _resolveGpu() {
1525
+ const profiler = this._app.graphicsDevice.gpuProfiler;
1526
+ if (!profiler?.enabled) return;
1527
+ const frameTime = profiler.frameTime;
1528
+ if (frameTime === undefined) return;
1529
+
1530
+ let seq = -1;
1531
+ if (this.gpuExact) {
1532
+ const version = profiler.renderVersion;
1533
+ if (version < 0 || version === this._gpuSeen) return;
1534
+ this._gpuSeen = version;
1535
+ const first = Math.max(this.first, this._end - GPU_LATENCY_FRAMES);
1536
+ for (let s = this._end - 1; s >= first; s--) {
1537
+ if (this.data.version[s % this._slots] === version) {
1538
+ seq = s;
1539
+ break;
1540
+ }
1541
+ }
1542
+ } else {
1543
+ // the engine does not say which frame the timings describe: a change in them is a new
1544
+ // result, given to the newest frame
1545
+ if (frameTime === this._gpuSeen) return;
1546
+ this._gpuSeen = frameTime;
1547
+ seq = this._end - 1;
1548
+ }
1549
+ if (!this.has(seq)) return;
1550
+
1551
+ const slot = seq % this._slots;
1552
+ this.data.gpu[slot] = frameTime;
1553
+ this._gpuSlot = slot;
1554
+ this._passCounts[slot] = 0;
1555
+ // each pass apart where the engine keeps them so, else those sharing a name summed
1556
+ const inOrder = profiler.passTimingsInOrder;
1557
+ if (inOrder) {
1558
+ for (let i = 0; i < inOrder.names.length; i++) this._addPass(inOrder.times[i], inOrder.names[i]);
1559
+ } else {
1560
+ profiler.passTimings.forEach(this._addPass);
1561
+ }
1562
+ this._matchOwners(slot);
1563
+ this.version++;
1564
+ }
1565
+
1566
+ /**
1567
+ * Finds the effect running each timed pass of a slot in the frame graph: the pass it is a
1568
+ * before or after pass of, where that pass runs only passes of its own. A pass running effects
1569
+ * that run passes, as a camera frame does, is a frame rather than an effect, so what it runs
1570
+ * directly counts as passes of their own. The passes are matched by name in the order they
1571
+ * ran, against the frame graph as it is now, as the timings arrive a few frames late; where
1572
+ * too few match, as when the frame graph has changed, no pass gets an owner.
1573
+ *
1574
+ * @param {number} slot - The slot.
1575
+ * @private
1576
+ */
1577
+ _matchOwners(slot) {
1578
+ const figures = this._passFigures[slot];
1579
+ const count = this._passCounts[slot];
1580
+ const frameGraph = /** @type {any} */ (this._app).frameGraph;
1581
+ // engines before 2.24 name the list renderPasses
1582
+ const passes = frameGraph?.passes ?? frameGraph?.renderPasses ?? [];
1583
+ const match = this._match;
1584
+
1585
+ // the frame graph and the timed names as the owners were last matched for
1586
+ let same = match.graph.length === passes.length && match.timed.length === count;
1587
+ for (let i = 0; same && i < passes.length; i++) same = match.graph[i] === passes[i].name;
1588
+ for (let i = 0; same && i < count; i++) same = match.timed[i] === figures[i * PASS_STRIDE];
1589
+ if (!same) {
1590
+ match.graph = passes.map(pass => pass.name);
1591
+ match.timed = [];
1592
+ for (let i = 0; i < count; i++) match.timed.push(figures[i * PASS_STRIDE]);
1593
+ match.result = this._findOwners(passes, figures, count);
1594
+ }
1595
+ for (let i = 0; i < count; i++) {
1596
+ const base = i * PASS_STRIDE;
1597
+ figures[base + 2] = match.result[i * 3];
1598
+ figures[base + 3] = match.result[i * 3 + 1];
1599
+ figures[base + 4] = match.result[i * 3 + 2];
1600
+ }
1601
+ }
1602
+
1603
+ /**
1604
+ * @param {any[]} passes - The passes of the frame graph.
1605
+ * @param {number[]} figures - The figures of the timed passes.
1606
+ * @param {number} count - How many passes were timed.
1607
+ * @returns {number[]} For each timed pass, the id of its owner's name, which of the passes of
1608
+ * the frame graph with its name it is, and which with its owner's name its owner is; -1 for
1609
+ * each where unknown.
1610
+ * @private
1611
+ */
1612
+ _findOwners(passes, figures, count) {
1613
+ // the passes in the order they ran, the passes of the views of a multi-view pass after it
1614
+ const graph = [];
1615
+ for (const pass of passes) {
1616
+ graph.push(pass);
1617
+ if (Array.isArray(pass.children)) graph.push(...pass.children);
1618
+ }
1619
+ const parentOf = new Map();
1620
+ const mark = (pass) => {
1621
+ for (const child of nestedPasses(pass)) {
1622
+ parentOf.set(child, pass);
1623
+ mark(child);
1624
+ }
1625
+ };
1626
+ passes.forEach(mark);
1627
+ // an effect runs passes that run none of their own
1628
+ const isEffect = pass => nestedPasses(pass).length > 0 && nestedPasses(pass).every(child => nestedPasses(child).length === 0);
1629
+ const names = graph.map(profilerName);
1630
+ const occurrences = [];
1631
+ const seen = new Map();
1632
+ for (const name of names) {
1633
+ occurrences.push(seen.get(name) ?? 0);
1634
+ seen.set(name, (seen.get(name) ?? 0) + 1);
1635
+ }
1636
+
1637
+ const result = [];
1638
+ let cursor = 0;
1639
+ let matched = 0;
1640
+ for (let i = 0; i < count; i++) {
1641
+ const name = this.names[figures[i * PASS_STRIDE]];
1642
+ let j = cursor;
1643
+ while (j < graph.length && names[j] !== name) j++;
1644
+ if (j === graph.length) {
1645
+ result.push(-1, -1, -1);
1646
+ continue;
1647
+ }
1648
+ matched++;
1649
+ cursor = j + 1;
1650
+ const pass = graph[j];
1651
+ const parent = parentOf.get(pass);
1652
+ const owner = isEffect(pass) ? pass : parent && isEffect(parent) ? parent : null;
1653
+ const ownerIndex = owner ? graph.indexOf(owner) : -1;
1654
+ result.push(owner ? this._nameId(profilerName(owner)) : -1, occurrences[j], ownerIndex >= 0 ? occurrences[ownerIndex] : -1);
1655
+ }
1656
+ if (matched < count * PASS_MATCH_SHARE) result.fill(-1);
1657
+ return result;
1658
+ }
1659
+
1660
+ /**
1661
+ * @param {string} name - The name of a GPU pass or an effect.
1662
+ * @returns {number} Its index into {@link names}, added there when new.
1663
+ * @private
1664
+ */
1665
+ _nameId(name) {
1666
+ let id = this._nameIds.get(name);
1667
+ if (id === undefined) {
1668
+ id = this.names.length;
1669
+ this.names.push(name);
1670
+ this._nameIds.set(name, id);
1671
+ }
1672
+ return id;
1673
+ }
1674
+
1675
+ /**
1676
+ * Adds a GPU pass to the frame its timings were resolved for. A callback made once, as an
1677
+ * iterator over the map of pass timings would make garbage on every frame.
1678
+ *
1679
+ * @param {number} time - The GPU time of the pass.
1680
+ * @param {string} name - Its name.
1681
+ * @private
1682
+ */
1683
+ _addPass = (time, name) => {
1684
+ const slot = this._gpuSlot;
1685
+ const figures = this._passFigures[slot];
1686
+ const base = this._passCounts[slot]++ * PASS_STRIDE;
1687
+ figures[base] = this._nameId(name);
1688
+ figures[base + 1] = time;
1689
+ figures[base + 2] = -1;
1690
+ figures[base + 3] = -1;
1691
+ figures[base + 4] = -1;
1692
+ };
1693
+
1694
+ /**
1695
+ * @param {PerfEvent} event - An event of the frame being recorded.
1696
+ * @private
1697
+ */
1698
+ _addEvent(event) {
1699
+ if (!this._begun) return;
1700
+ this._addEventTo(this._end % this._slots, event);
1701
+ }
1702
+
1703
+ /**
1704
+ * @param {number} slot - The slot of a frame.
1705
+ * @param {PerfEvent} event - An event of the frame.
1706
+ * @private
1707
+ */
1708
+ _addEventTo(slot, event) {
1709
+ const events = (this._events[slot] ??= []);
1710
+ if (events.length < MAX_FRAME_EVENTS) events.push(event);
1711
+ this.version++;
1712
+ }
1713
+
1714
+ /**
1715
+ * Finds the frame, complete or being recorded, that began at or before a time and was still
1716
+ * going on at it.
1717
+ *
1718
+ * @param {number} time - A `performance.now()` time.
1719
+ * @returns {number} The slot of the frame, or -1 when no frame kept covers the time.
1720
+ * @private
1721
+ */
1722
+ _slotAt(time) {
1723
+ const data = this.data;
1724
+ if (this._begun) {
1725
+ const slot = this._end % this._slots;
1726
+ if (time >= data.tick[slot]) return slot;
1727
+ }
1728
+ for (let s = this._end - 1; s >= this.first; s--) {
1729
+ const slot = s % this._slots;
1730
+ if (time >= data.tick[slot]) return time < data.tick[slot] + data.width[slot] ? slot : -1;
1731
+ }
1732
+ return -1;
1733
+ }
1734
+
1735
+ /**
1736
+ * @param {Asset} asset - An asset that began loading.
1737
+ * @private
1738
+ */
1739
+ _onAssetLoadStart(asset) {
1740
+ this._pending.set(asset.id, { kind: 'asset', name: asset.name, type: asset.type, id: asset.id, start: performance.now(), end: NaN });
1741
+ }
1742
+
1743
+ /**
1744
+ * @param {Asset} asset - An asset that finished loading.
1745
+ * @private
1746
+ */
1747
+ _onAssetLoad(asset) {
1748
+ this._endAsset(asset, performance.now(), false);
1749
+ }
1750
+
1751
+ /**
1752
+ * @param {*} err - The error.
1753
+ * @param {Asset} asset - An asset that failed to load.
1754
+ * @private
1755
+ */
1756
+ _onAssetError(err, asset) {
1757
+ if (asset) this._endAsset(asset, performance.now(), true);
1758
+ }
1759
+
1760
+ /**
1761
+ * Adds an asset that ended loading to the entry it ended in, with the request of its file
1762
+ * where the browser kept it: how long the network took, and so how long the asset took after.
1763
+ *
1764
+ * @param {Asset} asset - The asset.
1765
+ * @param {number} end - When it ended.
1766
+ * @param {boolean} failed - Whether it failed.
1767
+ * @private
1768
+ */
1769
+ _endAsset(asset, end, failed) {
1770
+ const pending = this._pending.get(asset.id);
1771
+ this._pending.delete(asset.id);
1772
+ /** @type {PerfLoad} */
1773
+ const load = pending ?? { kind: 'asset', name: asset.name, type: asset.type, id: asset.id, start: NaN, end };
1774
+ load.end = end;
1775
+ if (failed) load.failed = true;
1776
+ const url = absoluteUrl(/** @type {any} */ (asset).getFileUrl?.() ?? null);
1777
+ if (url) {
1778
+ load.url = url;
1779
+ const request = this._requests.get(url);
1780
+ if (request && request.end <= end + 1) PerfCapture._linkRequest(load, request);
1781
+ else this._awaitingRequest.set(url, load);
1782
+ }
1783
+ this._addLoad(load);
1784
+ }
1785
+
1786
+ /**
1787
+ * @param {PerfLoad} asset - An asset load.
1788
+ * @param {PerfLoad} request - The request of its file.
1789
+ * @private
1790
+ */
1791
+ static _linkRequest(asset, request) {
1792
+ asset.netStart = request.netStart;
1793
+ asset.netEnd = request.netEnd;
1794
+ asset.firstByte = request.firstByte;
1795
+ asset.bytes = request.bytes;
1796
+ asset.cached = request.cached;
1797
+ }
1798
+
1799
+ /**
1800
+ * @param {string} name - A moment of the app or the page.
1801
+ * @param {number} time - When it was.
1802
+ * @private
1803
+ */
1804
+ _addMilestone(name, time) {
1805
+ this._addLoad({ kind: 'milestone', name, start: time, end: time });
1806
+ }
1807
+
1808
+ /**
1809
+ * Adds a load to the entry it ended in, where it is kept.
1810
+ *
1811
+ * @param {PerfLoad} load - The load.
1812
+ * @private
1813
+ */
1814
+ _addLoad(load) {
1815
+ const slot = this._slotAt(load.end);
1816
+ if (slot < 0) return;
1817
+ const loads = (this._loads[slot] ??= []);
1818
+ if (loads.length < MAX_ENTRY_LOADS) loads.push(load);
1819
+ this.version++;
1820
+ }
1821
+
1822
+ /**
1823
+ * @param {any} entry - A request the browser timed.
1824
+ * @private
1825
+ */
1826
+ _addRequest(entry) {
1827
+ /** @type {PerfLoad} */
1828
+ const request = {
1829
+ kind: 'request',
1830
+ name: fileName(entry.name),
1831
+ url: entry.name,
1832
+ type: entry.initiatorType,
1833
+ start: entry.startTime,
1834
+ end: entry.responseEnd,
1835
+ netStart: entry.startTime,
1836
+ netEnd: entry.responseEnd,
1837
+ firstByte: entry.responseStart,
1838
+ bytes: entry.transferSize || entry.encodedBodySize || 0,
1839
+ cached: entry.transferSize === 0 && entry.encodedBodySize > 0
1840
+ };
1841
+ this._addLoad(request);
1842
+ // the asset of the file, if it ended loading first; the maps keep the recent ones only
1843
+ const asset = this._awaitingRequest.get(entry.name);
1844
+ if (asset) {
1845
+ PerfCapture._linkRequest(asset, request);
1846
+ this._awaitingRequest.delete(entry.name);
1847
+ this.version++;
1848
+ }
1849
+ this._requests.set(entry.name, request);
1850
+ for (const map of [this._requests, this._awaitingRequest]) {
1851
+ if (map.size > MAX_ENTRY_LOADS) map.delete(map.keys().next().value);
1852
+ }
1853
+ }
1854
+
1855
+ /**
1856
+ * @param {PerformanceObserverEntryList} list - The requests the browser timed.
1857
+ * @private
1858
+ */
1859
+ _onResources = (list) => {
1860
+ for (const entry of list.getEntries()) this._addRequest(entry);
1861
+ };
1862
+
1863
+ /**
1864
+ * @param {PerformanceObserverEntryList} list - The paints the browser timed: its first paint and
1865
+ * its first paint of content.
1866
+ * @private
1867
+ */
1868
+ _onPaints = (list) => {
1869
+ for (const entry of list.getEntries()) {
1870
+ this._addMilestone(entry.name === 'first-contentful-paint' ? 'First content paint' : entry.name === 'first-paint' ? 'First paint' : entry.name, entry.startTime);
1871
+ }
1872
+ };
1873
+
1874
+ /** @private */
1875
+ _onPreloadStart() {
1876
+ this._addMilestone('Preload start', performance.now());
1877
+ }
1878
+
1879
+ /** @private */
1880
+ _onPreloadEnd() {
1881
+ this._addMilestone('Preload end', performance.now());
1882
+ }
1883
+
1884
+ /** @private */
1885
+ _onAppStart() {
1886
+ this._addMilestone('App start', performance.now());
1887
+ }
1888
+
1889
+ /**
1890
+ * Takes a counter of `app.stats.user` into the frame ending, keeping a ring for it the first
1891
+ * time the app sets it.
1892
+ *
1893
+ * @param {*} value - Its value.
1894
+ * @param {string} name - Its name.
1895
+ * @private
1896
+ */
1897
+ _takeCounter = (value, name) => {
1898
+ let id = this._counterIds.get(name);
1899
+ if (id === undefined) {
1900
+ if (this.counterRings.length >= MAX_COUNTERS) return;
1901
+ id = this.counterRings.length;
1902
+ this._counterIds.set(name, id);
1903
+ this.counterNames.push(String(name));
1904
+ this.counterRings.push(new Float64Array(this._slots).fill(NaN));
1905
+ }
1906
+ this.counterRings[id][this._counterSlot] = typeof value === 'number' ? value : NaN;
1907
+ };
1908
+
1909
+ /**
1910
+ * @param {{ timestamp: number }} e - The event.
1911
+ * @private
1912
+ */
1913
+ _onBakeStart(e) {
1914
+ this._bakeStart = e?.timestamp ?? performance.now();
1915
+ }
1916
+
1917
+ /**
1918
+ * Adds a bake of lightmaps to the frame it ran in, with the figures the lightmapper kept of it.
1919
+ *
1920
+ * @param {{ timestamp: number, target: { stats: object } }} e - The event.
1921
+ * @private
1922
+ */
1923
+ _onBakeEnd(e) {
1924
+ const end = e?.timestamp ?? performance.now();
1925
+ const start = Number.isFinite(this._bakeStart) ? this._bakeStart : end;
1926
+ this._bakeStart = NaN;
1927
+ const stats = /** @type {any} */ (e?.target?.stats ?? this._app.lightmapper?.stats ?? {});
1928
+ // not its times rendering shadow maps and the lightmaps, which add the renderer's running
1929
+ // totals for the frame after each pass, so they count the earlier passes again
1930
+ /** @type {PerfBake} */
1931
+ const bake = {
1932
+ lightmaps: stats.lightmapCount ?? NaN,
1933
+ passes: stats.renderPasses ?? NaN,
1934
+ targets: stats.fboTime ?? NaN,
1935
+ shaders: stats.shadersLinked ?? NaN,
1936
+ compile: stats.compileTime ?? NaN
1937
+ };
1938
+ this._addEvent({ kind: 'bake', name: 'Lightmaps', start, duration: end - start, bake });
1939
+ }
1940
+
1941
+ /**
1942
+ * @param {{ timestamp: number }} e - The event.
1943
+ * @private
1944
+ */
1945
+ _onCompileStart(e) {
1946
+ this._compileStart = e.timestamp;
1947
+ }
1948
+
1949
+ /**
1950
+ * @param {{ timestamp: number }} e - The event.
1951
+ * @private
1952
+ */
1953
+ _onCompileEnd(e) {
1954
+ this._countCompile(e.timestamp - this._compileStart);
1955
+ }
1956
+
1957
+ /**
1958
+ * @param {{ timestamp: number }} e - The event.
1959
+ * @private
1960
+ */
1961
+ _onLinkStart(e) {
1962
+ this._linkStart = e.timestamp;
1963
+ }
1964
+
1965
+ /**
1966
+ * @param {{ timestamp: number }} e - The event.
1967
+ * @private
1968
+ */
1969
+ _onLinkEnd(e) {
1970
+ this._countCompile(e.timestamp - this._linkStart);
1971
+ }
1972
+
1973
+ /**
1974
+ * @param {number} duration - How long a shader compile or link took.
1975
+ * @private
1976
+ */
1977
+ _countCompile(duration) {
1978
+ if (!this._begun) return;
1979
+ const slot = this._end % this._slots;
1980
+ this.data.compiles[slot]++;
1981
+ if (duration >= 0) this.data.compileTime[slot] += duration;
1982
+ }
1983
+
1984
+ /**
1985
+ * Gives each long animation frame the browser reports to the app frame that ran in it, naming
1986
+ * the script that ran longest.
1987
+ *
1988
+ * @param {PerformanceObserverEntryList} list - The entries.
1989
+ * @private
1990
+ */
1991
+ _onLongFrames = (list) => {
1992
+ for (const entry of /** @type {any[]} */ (list.getEntries())) {
1993
+ const start = entry.startTime;
1994
+ const scripts = [...(entry.scripts ?? [])].sort((a, b) => b.duration - a.duration);
1995
+ const top = scripts[0];
1996
+ const name = top ? `${top.invoker || top.name || 'script'}${top.sourceFunctionName ? ` ${top.sourceFunctionName}` : ''}` : 'long animation frame';
1997
+ const detail = [
1998
+ `blocking ${entry.blockingDuration?.toFixed(0) ?? '?'} ms`,
1999
+ ...scripts.slice(0, 3).map(script => `${script.invoker || script.name}${script.sourceURL ? ` (${script.sourceURL.split('/').pop()})` : ''} ${script.duration.toFixed(0)} ms`)
2000
+ ].join(' · ');
2001
+ // the app's tick runs inside the browser's frame: find the frames that began within it
2002
+ const data = this.data;
2003
+ const frames = this._begun ? [this._end] : [];
2004
+ for (let s = this._end - 1; s >= this.first && data.tick[s % this._slots] >= start; s--) frames.push(s);
2005
+ let added = false;
2006
+ for (const seq of frames) {
2007
+ const slot = seq % this._slots;
2008
+ const tick = data.tick[slot];
2009
+ if (tick >= start && tick <= start + entry.duration) {
2010
+ this._addEventTo(slot, { kind: 'long', name, start, duration: entry.duration, detail });
2011
+ added = true;
2012
+ }
2013
+ }
2014
+ // before the first frame, the start of the app has it
2015
+ const slot = this._slotAt(start);
2016
+ if (!added && slot >= 0 && data.kind[slot] === ENTRY_STARTUP) this._addEventTo(slot, { kind: 'long', name, start, duration: entry.duration, detail });
2017
+ }
2018
+ };
2019
+
2020
+ /**
2021
+ * Gives each span the app measured with `performance.measure` to the frame it started in.
2022
+ *
2023
+ * @param {PerformanceObserverEntryList} list - The entries.
2024
+ * @private
2025
+ */
2026
+ _onMeasures = (list) => {
2027
+ for (const entry of list.getEntries()) {
2028
+ const slot = this._slotAt(entry.startTime);
2029
+ if (slot >= 0) this._addEventTo(slot, { kind: 'marker', name: entry.name, start: entry.startTime, duration: entry.duration });
2030
+ }
2031
+ };
2032
+ }
2033
+
2034
+ export { CAPTURE_FRAMES, CHANNELS, ENTRY_STARTUP, PerfCapture, SCRIPT_CALLS, SCRIPT_ORDER, SCRIPT_STRIDE };