@babylonjs-toolkit/agent 1.1.86 → 1.1.99
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 +5 -6
- package/package.json +1 -1
- package/skills/bt-execute/SKILL.md +17 -15
- package/skills/bt-execute/scripts/dashboard.mjs +297 -5
- package/skills/bt-execute/templates/dashboard/dashboard.html +29 -3
- package/skills/bt-execute/templates/dashboard/dashboard.template.js +1 -2
- package/skills/bt-execute/templates/dashboard/data-schema.md +8 -6
- package/skills/bt-gauntlet/references/spec-composition.md +3 -1
- package/skills/bt-plan/SKILL.md +2 -2
- package/skills/bt-profile/SKILL.md +21 -1
- package/skills/bt-profile/scripts/analyze.mjs +160 -0
- package/skills/bt-profile/scripts/lib/probe.mjs +119 -2
- package/skills/bt-profile/scripts/report.mjs +46 -1
- package/skills/bt-spec/SKILL.md +7 -7
|
@@ -1725,11 +1725,37 @@
|
|
|
1725
1725
|
if (typeof value === 'string' && value) return [{ note: value }];
|
|
1726
1726
|
return asList(value).map((update) => (typeof update === 'string' ? { note: update } : update)).filter((update) => update && typeof update === 'object');
|
|
1727
1727
|
};
|
|
1728
|
+
// An image written under `path` (or `file`, `image`, `url`) instead of `src` would show "No snapshot": read it
|
|
1729
|
+
// from there and say so in the console, so the slip shows its picture and still gets fixed at the source.
|
|
1730
|
+
const imageKeys = ['path', 'file', 'image', 'url'];
|
|
1731
|
+
const repairImage = (image) => {
|
|
1732
|
+
if (!image || typeof image !== 'object' || image.src) return image;
|
|
1733
|
+
const wrongKey = imageKeys.find((key) => typeof image[key] === 'string' && image[key]);
|
|
1734
|
+
if (wrongKey) {
|
|
1735
|
+
console.warn(`Dashboard: a snapshot has its image under "${wrongKey}" instead of "src" (${image[wrongKey]}) — write snapshots with dashboard.mjs snapshot.`);
|
|
1736
|
+
image.src = image[wrongKey];
|
|
1737
|
+
}
|
|
1738
|
+
return image;
|
|
1739
|
+
};
|
|
1728
1740
|
const repairSnapshots = (snapshots) => asList(snapshots)
|
|
1729
1741
|
.filter((snapshot) => snapshot && typeof snapshot === 'object')
|
|
1730
|
-
.map((snapshot) =>
|
|
1742
|
+
.map((snapshot) => {
|
|
1743
|
+
repairImage(snapshot);
|
|
1744
|
+
repairImage(snapshot.before);
|
|
1745
|
+
repairImage(snapshot.after);
|
|
1746
|
+
return Object.assign(snapshot, { updates: asUpdates(snapshot.updates) }, snapshot.frames !== undefined ? { frames: asList(snapshot.frames).map(repairImage) } : {});
|
|
1747
|
+
});
|
|
1731
1748
|
data.phases = asList(data.phases);
|
|
1732
|
-
|
|
1749
|
+
// A decision written as plain text ("D3 — …") would render as an empty row: split off its id and show the text.
|
|
1750
|
+
const asDecision = (decision) => {
|
|
1751
|
+
if (typeof decision !== 'string') return decision;
|
|
1752
|
+
const match = decision.match(/^([A-Z]+\d+[a-z]?)(\s*\([^)]*\))?\s+[—–-]\s+([\s\S]*)$/);
|
|
1753
|
+
if (!match) return { id: '', text: decision };
|
|
1754
|
+
return { id: match[1], text: `${match[2] ? `${match[2].trim()} ` : ''}${match[3]}` };
|
|
1755
|
+
};
|
|
1756
|
+
data.decisions = asList(data.decisions).map(asDecision)
|
|
1757
|
+
.filter((decision) => decision && typeof decision === 'object')
|
|
1758
|
+
.map((decision) => Object.assign(decision, { updates: asUpdates(decision.updates) }));
|
|
1733
1759
|
data.followUps = asList(data.followUps);
|
|
1734
1760
|
data.activity = asList(data.activity);
|
|
1735
1761
|
if (data.afterAction && typeof data.afterAction === 'object') {
|
|
@@ -1906,7 +1932,7 @@
|
|
|
1906
1932
|
|
|
1907
1933
|
const presets = starting
|
|
1908
1934
|
? [
|
|
1909
|
-
['Every task, unattended', 'Auto-pilot builds
|
|
1935
|
+
['Every task, unattended', 'Auto-pilot builds and verifies each task in turn without stopping to ask, and commits nothing', runCommand(['--auto-pilot'], 'ALL')],
|
|
1910
1936
|
['Every task, with you on hand', 'Runs them all, and stops when it needs your decision', runCommand([], 'ALL')],
|
|
1911
1937
|
nextPhase ? [`${phaseLabel(nextPhase)} only`, `Tasks ${phaseRange(nextPhase)}`, runCommand([], phaseRange(nextPhase))] : null,
|
|
1912
1938
|
firstTask ? [`The first task only — ${firstTask.id}`, firstTask.title || '', runCommand([], firstTask.id)] : null,
|
|
@@ -3,7 +3,7 @@ window.FEATURE_DASHBOARD = {
|
|
|
3
3
|
"feature": {
|
|
4
4
|
"title": "Feature Title",
|
|
5
5
|
"slug": "feature-slug",
|
|
6
|
-
"branch": "
|
|
6
|
+
"branch": "",
|
|
7
7
|
"origin": "spec",
|
|
8
8
|
"size": "medium",
|
|
9
9
|
"proof": "functional",
|
|
@@ -64,7 +64,6 @@ window.FEATURE_DASHBOARD = {
|
|
|
64
64
|
"tests": null,
|
|
65
65
|
"verifier": "",
|
|
66
66
|
"attempts": 0,
|
|
67
|
-
"commit": "",
|
|
68
67
|
"doneAt": "",
|
|
69
68
|
"deferredReason": "",
|
|
70
69
|
"decisions": [],
|
|
@@ -81,7 +81,7 @@ instead of a blank page if something still cannot render — it keeps checking a
|
|
|
81
81
|
*Interim* while paused), with *Continue this plan* — the commands that pick up where it stopped — above it.
|
|
82
82
|
- **Cadence is per task.** A task's entry changes the moment it starts (`in-progress`), the moment it is built
|
|
83
83
|
(`built` — summary, files, tests and snapshots filled in right then), while the verifier checks it
|
|
84
|
-
(`verifying`) and when it passes (`done` — verifier,
|
|
84
|
+
(`verifying`) and when it passes (`done` — verifier, done time).
|
|
85
85
|
|
|
86
86
|
## `<slug>_dashboard.js` fields
|
|
87
87
|
|
|
@@ -90,7 +90,7 @@ Top level:
|
|
|
90
90
|
| Field | Meaning |
|
|
91
91
|
|---|---|
|
|
92
92
|
| `schema` | `1` |
|
|
93
|
-
| `feature` | `{ "title", "slug", "branch", "origin": "spec" \| "quick-plan", "size", "proof", "summary" }` — `summary` is one plain-language paragraph |
|
|
93
|
+
| `feature` | `{ "title", "slug", "branch", "origin": "spec" \| "quick-plan", "size", "proof", "summary" }` — `branch` is the branch that was checked out when the feature was specced (skills never create one); `summary` is one plain-language paragraph |
|
|
94
94
|
| `documents` | `[{ "label", "path" }]` — Spec (omitted for a Quick Plan), Plan, and Run log once bt-execute has run |
|
|
95
95
|
| `status` | see *Status* |
|
|
96
96
|
| `detail` | `"normal"`, or `"verbose"` once any run used `bt-execute --verbose` (never set back) |
|
|
@@ -100,7 +100,7 @@ Top level:
|
|
|
100
100
|
| `runs` | number of bt-execute runs so far |
|
|
101
101
|
| `afterAction` | the After Action Report (below) |
|
|
102
102
|
| `phases` | the plan's phases, each with its tasks (below) |
|
|
103
|
-
| `decisions` | `[{ "id": "D1" \| "T7", "text", "source", "updates" }]` |
|
|
103
|
+
| `decisions` | `[{ "id": "D1" \| "T7", "text", "source", "updates" }]` — objects, never plain `"D1 — …"` strings (the page and `check` repair one, but it is a slip) |
|
|
104
104
|
| `followUps` | plain strings — what a human should look at next |
|
|
105
105
|
| `activity` | `[{ "at", "text" }]`, oldest first — the milestones (the page shows newest first) |
|
|
106
106
|
|
|
@@ -156,7 +156,7 @@ Each task:
|
|
|
156
156
|
| `tests` | `{ "passed", "failed", "files": [".agents/specs/<slug>/tests/…"], "note" }` or `null`. `files` holds **paths only**, each from the project root (a test outside the feature folder: its real path, e.g. `BtMarioKartWeb/tests/RaceConfig.test.ts`), because the page links each one to the file. Counts, suite names and commands go in `note` |
|
|
157
157
|
| `verifier` | `"PASS — independent subagent; live check in Chrome"` |
|
|
158
158
|
| `checkedLive` | every run, not only `--verbose`: one line on what the verifier ran live and where — `"two-tab Shared race in headless Chrome, 150 ms lag"`; `""` when it was proven by tests alone. The page's *live check* badge and column read it (a task the plan marked `live` always counts) |
|
|
159
|
-
| `attempts`, `
|
|
159
|
+
| `attempts`, `doneAt` | as recorded (bt-execute never commits, so there is no commit to record) |
|
|
160
160
|
| `deferredReason` | why it was deferred, if it was |
|
|
161
161
|
| `decisions` | `"DECISION T1: … — source"` lines |
|
|
162
162
|
| `snapshots` | this task's progression, comparisons and stills |
|
|
@@ -178,6 +178,8 @@ Each task:
|
|
|
178
178
|
|
|
179
179
|
## Snapshot shapes
|
|
180
180
|
|
|
181
|
+
**Add snapshots with `node <skills>/bt-execute/scripts/dashboard.mjs snapshot <feature-folder> <T3|P1|plan> --src snapshots/… --caption "…"`** (`--before`/`--after` for a comparison, `--frame "src|stage|caption"` repeated for a progression) — never by writing the JSON yourself. The image key is **`src`**, relative to the feature folder; an entry with `path` (or `file`, `image`, `url`, `href`) instead would render as "No snapshot", so every helper write repairs it to `src` (and an unknown `source` to `"browser"`), `check` repairs any already in the file, the watchdog repairs one written around the helper within a minute, and the page reads those keys too. An image that is not on disk is refused — `check` fails on it. **The snapshots are the chronicle of the build: `check` passing is part of every phase boundary and of run end.**
|
|
182
|
+
|
|
181
183
|
Any list of snapshots may mix them. `source` names where the image came from: `"browser"`, `"unity"`,
|
|
182
184
|
`"blender"`, `"reference"`.
|
|
183
185
|
|
|
@@ -192,7 +194,7 @@ Any list of snapshots may mix them. `source` names where the image came from: `"
|
|
|
192
194
|
"What are you doing right now?" — answered on the page without asking. Whoever is doing the work rewrites
|
|
193
195
|
this file whole: the implementer while it builds, the verifier while it checks, the orchestrator between them —
|
|
194
196
|
at every meaningful step (starting a task, each milestone inside it, before a build / export / bake / capture /
|
|
195
|
-
test run, a fix attempt, the hand-over to the verifier, the
|
|
197
|
+
test run, a fix attempt, the hand-over to the verifier, the phase closing). A 20-minute silence shows as a warning.
|
|
196
198
|
The page shows it only while `status` is `in-progress`.
|
|
197
199
|
|
|
198
200
|
| Field | Meaning |
|
|
@@ -200,7 +202,7 @@ The page shows it only while `status` is `in-progress`.
|
|
|
200
202
|
| `updatedAt` | `"YYYY-MM-DD HH:MM"` from the shell clock |
|
|
201
203
|
| `phase` | the current phase number |
|
|
202
204
|
| `task` | the task being worked on; `""` between tasks |
|
|
203
|
-
| `title` | only when there is no task: `"Verifying phase 1"`, `"
|
|
205
|
+
| `title` | only when there is no task: `"Verifying phase 1"`, `"Closing phase 1"` |
|
|
204
206
|
| `role` | `implementer` · `verifier` · `orchestrator` |
|
|
205
207
|
| `activity` | one plain-language sentence on what is happening this minute |
|
|
206
208
|
| `source` | `agent` (an agent wrote it) or `watchdog` (a heartbeat written because the agent was quiet — the page tags it) |
|
|
@@ -51,7 +51,9 @@ idiom bt-prototype uses with bt-hero — **pre-resolve everything at spec time s
|
|
|
51
51
|
job genuinely reports DONE (or a loop-card boundary fires and the user accepts the parked result — record
|
|
52
52
|
which). The gauntlet's own critic evidence IS the acceptance evidence; the bt-execute verifier reads
|
|
53
53
|
`progress.md` + the last round journal rather than re-judging the art. bt-execute copies the gauntlet's best
|
|
54
|
-
evidence frames, round by round, into the feature's `snapshots/`
|
|
54
|
+
evidence frames, round by round, into the feature's `snapshots/` and adds them to the feature dashboard as a
|
|
55
|
+
progression only through `node <skills>/bt-execute/scripts/dashboard.mjs snapshot <feature-folder> T<n> --frame "snapshots/…|<stage>|<caption>"`
|
|
56
|
+
(repeated per frame), then runs `dashboard.mjs check <feature-folder>` — never by writing snapshot JSON.
|
|
55
57
|
|
|
56
58
|
bt-gauntlet never orchestrates bt-spec itself — composition is always initiated from the spec side.
|
|
57
59
|
|
package/skills/bt-plan/SKILL.md
CHANGED
|
@@ -48,7 +48,7 @@ Execution time is mostly *how the work is proven*, not the code. Keep proof stro
|
|
|
48
48
|
3. **`Verify level`** per task: `standard` (build, named tests, diff review) or `live` (needs the dev server, a browser, Unity or Blender to observe). Mark `live` whenever correctness shows only at runtime — rendering, UI, interaction, Unity↔Babylon parity. The last feature task carries one `live` end-to-end check of the whole feature when it has anything on screen — write it into that task's Acceptance, not as a separate task; a read-and-confirm check likewise belongs in the Acceptance of the task that made the change. bt-execute's verifier performs the live checks, and does all of a phase's live tasks in **one** session. So mark as many tasks `live` as truly need it, but never schedule a capture, screenshot or page session **per task** in the Steps — the phase gets one session covering all of them, and any second engine or full-resolution pass happens once, in the final end-to-end task. A plan with more planned looks than phases is the single most expensive mistake this skill can make. If a live check may be impossible where the plan runs (needs credentials, data or hardware), say in the task what to report instead.
|
|
49
49
|
4. **Named tests** with expected outcomes for every task that has a testable surface, in test files under the feature folder's `tests/` (`.agents/specs/<slug>/tests/` — never a root `tests/` folder). No probe suites, fuzzing or mutation testing unless the risk calls for it.
|
|
50
50
|
5. **Functional proof by default:** unit tests; for anything on screen, one look per visual phase — the running result in the browser, judged against the spec and DESIGN.md, or beside a reference image when one exists (a mockup, the original site, the Unity view) — on one browser/engine at reduced resolution, with any second engine checked once in the final end-to-end task; cheap value fixtures sampled once from a reference implementation where there is one. Keep Acceptance to what a user of the feature would notice. **Numeric parity gates** (pixel thresholds, repeats, several engines) only under `--parity` / `proof: parity` or when the brief states a number — and then planned to run once per phase (iteration inside the phase uses the quick look), never loosened.
|
|
51
|
-
6. **Proportional safety.** When the spec requires a safety outcome (nothing unfinished reaches the user's folders, the app keeps working between tasks), pick the cheapest mechanism that achieves it — normally a
|
|
51
|
+
6. **Proportional safety.** When the spec requires a safety outcome (nothing unfinished reaches the user's folders, the app keeps working between tasks), pick the cheapest mechanism that achieves it — normally a build output the user's folders do not read, and one copy across at the end after the live check — never a branch or a commit (the user owns git; they create branches and commit when they choose). Add staged promotions, per-step archives or hash records only if the brief asks for them by name.
|
|
52
52
|
7. **Minimal exports.** A task's Steps re-export only the Unity project the task tests and only the scenes it works on, and only when the change alters that scene's export. Never write "re-export every scene" or "re-export all projects" for consistency — other scenes pick the change up at their next natural export. Name the scenes explicitly.
|
|
53
53
|
8. **No ceremony.** No standalone "verification sweep / open the review / final check" tasks, and no ledgers, md5 or environment records, archives, checked-in capture trees, standing evidence suites, doc-integrity registration or staged promotions — unless the brief asks.
|
|
54
54
|
9. **No brittle pins.** Never pin counts later tasks will change (tests passed, suite sizes, hashes). Say "the named tests pass, no new failures versus the baseline".
|
|
@@ -149,7 +149,7 @@ Each task above is a checkbox. To implement:
|
|
|
149
149
|
Print `🗂️ [bt-plan] Writing the feature dashboard …`. **A spec from bt-spec already has a dashboard, in its `specified` state** (showing the bt-plan commands): read its `<slug>_dashboard.js` first and keep its `feature`, `decisions` and `activity`; everything below then fills it in and moves it to `planned`. A Quick Plan, or a spec with no dashboard, creates it here. From bt-execute's `templates/dashboard/` *(where skills load through a tool: `load_skill('bt-execute')` + `read_skill_resource`; where they are files: the sibling `bt-execute/` folder in the skills directory this skill was loaded from)*:
|
|
150
150
|
|
|
151
151
|
- copy `dashboard.html` to `.agents/specs/<slug>/dashboard.html`, replacing `{{slug}}` with the slug and changing nothing else (always — over a copy bt-spec wrote too, so the page is the current template);
|
|
152
|
-
- write `.agents/specs/<slug>/documents/<slug>_dashboard.js` from the starter `dashboard.template.js`, written whole as strict JSON behind its `window.FEATURE_DASHBOARD =` prefix — double-quoted keys, no comments, no trailing commas (`data-schema.md` documents every field): `feature` (title, slug, branch, `origin` `spec` or `quick-plan`, size, proof, a plain-language summary), `documents` (Spec — omitted for a Quick Plan — and Plan), `status: "planned"`, `updatedAt` from the shell clock (`date '+%Y-%m-%d %H:%M'`; with no shell, the current local time), `estimate` (the Total line), every phase and task from the plan as `pending` (id, title, kind from the estimate table, verify level), an empty `afterAction` and no snapshots, the plan
|
|
152
|
+
- write `.agents/specs/<slug>/documents/<slug>_dashboard.js` from the starter `dashboard.template.js`, written whole as strict JSON behind its `window.FEATURE_DASHBOARD =` prefix — double-quoted keys, no comments, no trailing commas (`data-schema.md` documents every field): `feature` (title, slug, branch, `origin` `spec` or `quick-plan`, size, proof, a plain-language summary), `documents` (Spec — omitted for a Quick Plan — and Plan), `status: "planned"`, `updatedAt` from the shell clock (`date '+%Y-%m-%d %H:%M'`; with no shell, the current local time), `estimate` (the Total line), every phase and task from the plan as `pending` (id, title, kind from the estimate table, verify level), an empty `afterAction` and no snapshots, the plan’s Decisions as `decisions` (Heavy Plan; otherwise the spec’s), each an object `{ "id": "D1", "text": "…", "updates": [] }` (never a plain `"D1 — …"` string, which shows as an empty row), and one more `activity` line: `Plan written — <n> tasks in <k> phases, estimated <range>` (after bt-spec's `Spec written` line when there is one);
|
|
153
153
|
- write `.agents/specs/<slug>/documents/<slug>_live.js` from `live.template.js`, the same way (whole, strict JSON): no task, `role: "orchestrator"`, `title: "Plan written — waiting for bt-execute"`, no steps (bt-execute rewrites it at every step of a run).
|
|
154
154
|
- in a git repository, make sure `.gitignore` (at the repository root) contains the line `.agents/*/*/documents/*_live.js` — append it once if missing. The live file is rewritten at every step of a run and is not history worth keeping; `<slug>_dashboard.js` is, and stays tracked. A live file git already tracks is left as it is.
|
|
155
155
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: bt-profile
|
|
3
|
-
description: "The Babylon Toolkit Profile Skill finds what makes a web app slow and lists the fixes (applying them one at a time with --auto-fix) — built for BabylonJS / Babylon Toolkit games, and just as usable on any front end with no Babylon in it (point it at a URL and the project folder). It drives the running game in a real Chrome over the DevTools protocol through a repeatable scenario (a cold load, a level start, a countdown, a boss fight), records a full CPU profile, per-phase allocation profiles, every frame's CPU work and Babylon timers, and maps every sampled millisecond back to the original source line and its owner — your game code, a project-owned script bundle (e.g. the Unity exporter's project bundle), the Babylon Toolkit runtime, BabylonJS, Havok, shader translation, React, the browser. It charges library work to the code of yours that triggered it, splits everything by phase and by second, then diagnoses each bottleneck and lists the fixes — each with its expected gain and risk, ready to spec one by one or as a group with bt-spec, with a bt-recon command per subsystem that maps the code behind them for the spec — and, with --recon, runs bt-recon itself to map the code behind the slow moment and confirm each inferred cause in the code; with --auto-fix (which always turns --recon on), applies them one at a time, re-measuring the same scenario to prove each gain (reverting anything that does not help), and writes a code-dashboard report to `.agents/profile/<slug>/dashboard.html` (everything the slug's runs produced sits beside it in `.agents/profile/<slug>/data/`). Use when the user says the game is slow, stutters, crawls at a moment (load, start, many particles), or wants a performance analysis (e.g. `/bt-profile the race start crawls for a minute`, `/bt-profile --auto-fix the race start crawls`, `/bt-profile http://localhost:5173/play --scenario level-start`)."
|
|
3
|
+
description: "The Babylon Toolkit Profile Skill finds what makes a web app slow and lists the fixes (applying them one at a time with --auto-fix) — built for BabylonJS / Babylon Toolkit games, and just as usable on any front end with no Babylon in it (point it at a URL and the project folder). It drives the running game in a real Chrome over the DevTools protocol through a repeatable scenario (a cold load, a level start, a countdown, a boss fight), records a full CPU profile, per-phase allocation profiles, every frame's CPU work and Babylon timers, and every late-stutter source after the loading screen lifts (the Babylon Toolkit's late shader compiles with their cause and render pass, GPU pipelines, textures, downloads, audio decodes, garbage collection), and maps every sampled millisecond back to the original source line and its owner — your game code, a project-owned script bundle (e.g. the Unity exporter's project bundle), the Babylon Toolkit runtime, BabylonJS, Havok, shader translation, React, the browser. It charges library work to the code of yours that triggered it, splits everything by phase and by second, then diagnoses each bottleneck and lists the fixes — each with its expected gain and risk, ready to spec one by one or as a group with bt-spec, with a bt-recon command per subsystem that maps the code behind them for the spec — and, with --recon, runs bt-recon itself to map the code behind the slow moment and confirm each inferred cause in the code; with --auto-fix (which always turns --recon on), applies them one at a time, re-measuring the same scenario to prove each gain (reverting anything that does not help), and writes a code-dashboard report to `.agents/profile/<slug>/dashboard.html` (everything the slug's runs produced sits beside it in `.agents/profile/<slug>/data/`). Use when the user says the game is slow, stutters, crawls at a moment (load, start, many particles), or wants a performance analysis (e.g. `/bt-profile the race start crawls for a minute`, `/bt-profile --auto-fix the race start crawls`, `/bt-profile http://localhost:5173/play --scenario level-start`)."
|
|
4
4
|
allowed-tools: Read, Grep, Glob, Edit, Write, Bash, Agent, Task
|
|
5
5
|
---
|
|
6
6
|
|
|
@@ -208,10 +208,28 @@ Work from the brief's phases outward. For each phase that misses the target:
|
|
|
208
208
|
5. **Count, live, when the profile cannot say why.** A function that is cheap per call but runs too often needs a census: copy `templates/census.template.mjs` to the scratchpad (outside the project), adapt how it reaches the moment, and run it with `--args method=TransformNode.prototype.computeWorldMatrix,seconds=1`: it wraps the method for that long and counts calls per object with a sample stack. It names the object and the caller in one run — the Mario Kart run found 16,000 world-matrix recomputes per frame this way. GPU pipelines need no census: every capture records each shader module / pipeline / program with its time (`gpuCompiles` in `analysis.json`, per phase in the summary); line them up with the marks and the scenario's own progress (a distance, a spawn) to name what first drew them.
|
|
209
209
|
6. **Read the code.** Open the files and lines named (`yoursTop`, `excerpts`, `hotLines`) and the library function the time lands in. Find the mechanism — what runs, how often, on how many objects, why. A finding is not done until you can say *why* it costs what it costs.
|
|
210
210
|
7. **Worst frames** name the spikes (a spawn, a burst, a compile) that averages hide.
|
|
211
|
+
8. **Late stutter — read the summary's `LATE STUTTER` section every run** (the report's *Late stutter — after the reveal*). The reveal comes from the Babylon Toolkit itself (`SceneManager.OnSceneRevealedObservable`), else the scenario's `reveal` mark. Every hitch after it (a frame over 3× the median and 50 ms) is listed with its likely cause and suspects. On a toolkit game the probe also listens to the toolkit's late-compile detector, which names every shader or pipeline built after the reveal by mesh and material, particle system, post process or render pass, turning it on even in a production build. **A finished game has zero late compiles**, so each cause is a finding, even under the WebGPU safety net, where a late pipeline shows as a frame or two of pop-in instead of a freeze. Read them three ways:
|
|
212
|
+
- **By render pass first.** Many compiles in one pass other than `main` (`Camera <name>.Rig` is the camera the toolkit creates for a Unity camera; or a render target) mean a camera or target the pre-warm never drew. Toolkit 1.1.88+ warms every screen camera in the scene at the reveal (`SceneShaderWarmup.WarmAllCamerasOnReveal`, on by default). So the cause is a camera or target created after the reveal (create it at load), the switch turned off, or a toolkit older than 1.1.88, which warms only the camera active while it runs. One fix covers the whole pass. BtMarioKartWeb's race start had 34 late compiles and a 1.1 s countdown freeze on the old toolkit, every one in the race camera's pass, because the intro camera was the one active during the pre-warm; 1.1.88 removed them.
|
|
213
|
+
- **By cause.** Particles mean a system never pre-warmed (`WarmParticleSystem`, or the prefab that spawns it registered with `WarmPrefab`). A mesh spawned during play means its prefab was never registered (`WarmPrefab`). A mesh already in the scene means a variant change during play, covered by the toolkit's authoring rules: a light added or enabled, fog or clip planes toggled, a first instance, a texture transform moved off the identity, a look-alike material. Post processes and render passes created during play should be created at load.
|
|
214
|
+
- **The other first-use sources.** Downloads finished during play (a texture, model or sound fetched late: preload it behind the splash). Textures created during play (first-use uploads). Audio decodes (decode at load). A GC spike (allocation churn at a moment: phase `heap`). Scene growth (content created during play: pool it or create it at load). A page without the toolkit still gets every hitch, its GPU pipelines, downloads, textures and audio decodes; only the causes of its compiles are missing.
|
|
215
|
+
|
|
216
|
+
Re-capture with `--gpu-cold true` whenever a hitch or a late compile appears: it makes every capture a first visit, so the fix can be proven.
|
|
211
217
|
8. **Allocations**: phase `heap` lists show who feeds the garbage collector while playing.
|
|
212
218
|
|
|
213
219
|
9. **Trace every inferred cause in the code** (with `--recon`). Group the findings by the code they live in (`subsystem`). For each group with a finding whose cause is still `inferred`, run a quick bt-recon of that subsystem (*Recon* below), then re-read the finding against it: the cause becomes `confirmed` with `path:line` evidence, or the finding changes. Copy into each finding's `guards` what the recon says a change there must not break: callers, invariants, the tests that cover it.
|
|
214
220
|
|
|
221
|
+
**Where each late-stutter fix goes** — say it in the finding's `fix`. The Agent Reference's *Prewarming Content* guide (`references/prewarming-content.md`) is the authority on registrations: register only what a late-compile record names, one `WarmPrefab` per container, never speculatively.
|
|
222
|
+
|
|
223
|
+
| Cause | Fixed in | How |
|
|
224
|
+
|---|---|---|
|
|
225
|
+
| Content spawned during play that was never registered (a prefab, an idle particle system) | Game code | `--auto-fix`: `WarmPrefab` / `WarmParticleSystem` before the reveal — small, code-only, proven by a GPU-cold re-capture |
|
|
226
|
+
| A variant change during play (a light, fog, an instance, a texture transform, a look-alike material) | The Unity scene or the game's setup | A spec (`bt-spec` from the report): Unity authoring and a re-export, following the toolkit's authoring rules |
|
|
227
|
+
| A camera or render target created after the reveal | Game code | Create it at load and switch to it later |
|
|
228
|
+
| A case the pre-warm misses | The Babylon Toolkit runtime | The user owns it: fix it there with a regression test (Phase 3 step 2), or spec it in the runtime repo |
|
|
229
|
+
| A late download, decode or texture upload | Game code or the export settings | Preload behind the splash, or ship it in the scene |
|
|
230
|
+
|
|
231
|
+
`bt-optimize` is not the tool for late stutter: it lowers the GPU cost of every frame (bakes, merges, fewer draws), not one-off first-use work.
|
|
232
|
+
|
|
215
233
|
Write `$DATA/findings.json` (schema in `scripts/report.mjs`): per finding a severity, the phases, the cost in ms/frame and % of the phase, the cause in plain language and its `confidence` (`confirmed` once traced in the code, else `inferred`), the evidence (numbers from the analysis), the code locations, the `subsystem` it lives in (fixes in the same code share one name, and so one recon), its `recon` path when one exists, its `guards`, and the planned fix. Rank by the time it would win in the phases the user cares about.
|
|
216
234
|
|
|
217
235
|
## Phase 3 — Fix, one at a time (only with `--auto-fix`)
|
|
@@ -296,6 +314,8 @@ What a heavy function usually means, and where to look. Always confirm with `cal
|
|
|
296
314
|
| `HavokPlugin.setPhysicsBodyTransformation` / `_getTransformInfos` | Havok TELEPORT pre-step: each body whose `disablePreStep` is false is force-synced from its node before every step. Should only be bodies that move by transform (kinematic) | Count bodies by motion type × pre-step live. Static colliders with pre-step on are pure cost (the Babylon Toolkit runtime turned it on for every exported collider before 9.30.x) |
|
|
297
315
|
| `Node._getDescendants` / `getChildMeshes` / `getChildren` | A hierarchy walk — expensive when done per frame or per object | Per-frame lookups that should be cached at start |
|
|
298
316
|
| **Long frame, almost no script** — a `wait` in WORST FRAMES (LoAF `blockingMs` ≈ 0), right after new pipelines / programs were created (`pipelines near`, `gpu:` per phase) | **The GPU process compiling pipelines** for shaders drawn for the first time. The main thread is idle, so the CPU profile shows nothing; the browser's and the OS's shader caches hide it on later visits, so it is a **first-visit** stutter — every capture after the first may be smooth | Reproduce with `--gpu-cold true`. Which materials / effects are first drawn after the loading screen lifts (the car, the road 10 m in, a first particle burst). Fix: compile them behind the loading screen — wait for the scene and those materials to be ready (`scene.whenReadyAsync()`, `material.forceCompilationAsync(mesh)`, the toolkit's shader warm-up) and render a few frames hidden before revealing, instead of revealing on a fixed timer |
|
|
317
|
+
| A hitch after the reveal with toolkit late compiles near it (`LATE STUTTER`) | **A shader the pre-warm missed** — the cause names it: the mesh and material, particle system, post process or render pass | By render pass first (one pass other than `main` = a camera or target the pre-warm never drew), then by cause — see Phase 2 › *Late stutter* |
|
|
318
|
+
| A hitch after the reveal with a download, texture creation or audio decode near it | **First-use asset work during play**: fetched, decoded or uploaded on that frame | Preload it behind the splash; create its texture or decode its sound at load |
|
|
299
319
|
| `ProcessIncludes`, `MaterialPluginManager` code injection, `Effect` / `ShaderProcessor`, shader regexes, `glslang` / `twgsl` wasm | A **new shader variant** being built: a material's defines changed, a new material / particle system appeared, a plugin toggled | New materials or defines appearing after load (first particle burst, boost flames, item effects) — pre-warm them at load |
|
|
300
320
|
| `WebGPUEngine._draw`, `getBindGroups`, `setSubData`, `UniformBuffer.update*`, `Mesh.render`, `SubMesh.render` | Per-draw CPU cost: the frame has too many draws (meshes × passes) | Draw counts per phase, shadow casters, hidden-but-rendered meshes, instancing / merging (`bt-optimize`) |
|
|
301
321
|
| `ShadowGenerator._renderSubMeshForShadowMap` | Shadow passes re-drawing casters every frame | Casters list, refresh rate, number of shadowed lights |
|
|
@@ -467,6 +467,129 @@ function summarizeLoafs(loafs, top) {
|
|
|
467
467
|
return { longFrames: (loafs || []).length, scripts: [...groups.values()].sort((a, b) => b.ms - a.ms).slice(0, top).map((group) => ({ ...group, ms: round(group.ms) })) };
|
|
468
468
|
}
|
|
469
469
|
|
|
470
|
+
/** Frames slower than this many times the run's median frame interval, and at least HITCH_MIN_MS, count as hitches. */
|
|
471
|
+
const HITCH_FACTOR = 3;
|
|
472
|
+
/** The shortest frame interval (ms) that counts as a hitch the player can see. */
|
|
473
|
+
const HITCH_MIN_MS = 50;
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* The late-stutter view: everything that happened for the first time after the game was revealed, and the hitches it
|
|
477
|
+
* lined up with. The reveal is the Babylon Toolkit's own (OnSceneRevealedObservable), else the scenario's `reveal` mark.
|
|
478
|
+
* Every hitch after it gets its suspects — late compiles with their cause, GPU pipelines, textures created, downloads
|
|
479
|
+
* that finished, audio decodes, garbage collection, scene growth and the script that ran — and a likely cause.
|
|
480
|
+
* @returns {object|null} null when the run has no frames
|
|
481
|
+
*/
|
|
482
|
+
function lateStutter(probe, frames, counters, prepared, info, phases, startMs, endMs) {
|
|
483
|
+
if (!frames.length) return null;
|
|
484
|
+
const toolkitReveal = (probe.reveals || []).find((reveal) => reveal.at != null && reveal.at >= startMs);
|
|
485
|
+
const revealMark = (probe.marks || []).find((mark) => /reveal/i.test(mark.name));
|
|
486
|
+
const revealAt = toolkitReveal ? toolkitReveal.at : revealMark ? revealMark.at : null;
|
|
487
|
+
const after = (at) => at != null && (revealAt == null || at >= revealAt) && at <= endMs;
|
|
488
|
+
const t = (at) => (at == null ? null : round((at - startMs) / 1000, 2));
|
|
489
|
+
|
|
490
|
+
// Late compiles the toolkit named, grouped by what caused them.
|
|
491
|
+
const groups = new Map();
|
|
492
|
+
for (const record of probe.lateCompiles || []) {
|
|
493
|
+
const key = record.cause || `${record.causeKind} (no cause)`;
|
|
494
|
+
if (!groups.has(key)) {
|
|
495
|
+
groups.set(key, {
|
|
496
|
+
cause: key, causeKind: record.causeKind, meshName: record.meshName || "", materialName: record.materialName || "",
|
|
497
|
+
particleSystemName: record.particleSystemName || "", postProcessName: record.postProcessName || "", renderPassName: record.renderPassName || "",
|
|
498
|
+
effects: new Set(), kinds: {}, count: 0, firstT: null, firstMsAfterReveal: null,
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
const group = groups.get(key);
|
|
502
|
+
group.count++;
|
|
503
|
+
group.kinds[record.kind] = (group.kinds[record.kind] || 0) + 1;
|
|
504
|
+
if (record.effectName) group.effects.add(record.effectName);
|
|
505
|
+
const recordT = record.at != null ? t(record.at) : null;
|
|
506
|
+
if (group.firstT == null || (recordT != null && recordT < group.firstT)) group.firstT = recordT;
|
|
507
|
+
if (group.firstMsAfterReveal == null || record.msSinceReveal < group.firstMsAfterReveal) group.firstMsAfterReveal = round(record.msSinceReveal, 0);
|
|
508
|
+
}
|
|
509
|
+
const lateCompiles = [...groups.values()].map((group) => ({ ...group, effects: [...group.effects] })).sort((a, b) => b.count - a.count);
|
|
510
|
+
// The same late compiles by render pass: many compiles in one pass other than the main one mean a camera, rig or render
|
|
511
|
+
// target first drawn after the reveal — the pre-warm builds pipelines only for the passes it draws.
|
|
512
|
+
const passes = new Map();
|
|
513
|
+
for (const record of probe.lateCompiles || []) {
|
|
514
|
+
const name = record.renderPassName || "(unknown pass)";
|
|
515
|
+
const pass = passes.get(name) || { pass: name, count: 0, causes: new Set(), firstMsAfterReveal: null };
|
|
516
|
+
pass.count++;
|
|
517
|
+
pass.causes.add(record.cause || record.causeKind);
|
|
518
|
+
if (pass.firstMsAfterReveal == null || record.msSinceReveal < pass.firstMsAfterReveal) pass.firstMsAfterReveal = round(record.msSinceReveal, 0);
|
|
519
|
+
passes.set(name, pass);
|
|
520
|
+
}
|
|
521
|
+
const lateCompilePasses = [...passes.values()].map((pass) => ({ ...pass, causes: pass.causes.size })).sort((a, b) => b.count - a.count);
|
|
522
|
+
|
|
523
|
+
// Frame intervals: a hitch is a frame far slower than the run's typical one.
|
|
524
|
+
const intervals = [];
|
|
525
|
+
for (let index = 1; index < frames.length; index++) intervals.push(frames[index].at - frames[index - 1].at);
|
|
526
|
+
const sorted = [...intervals].sort((a, b) => a - b);
|
|
527
|
+
const median = sorted.length ? sorted[Math.floor(sorted.length / 2)] : 16.7;
|
|
528
|
+
const threshold = Math.max(HITCH_MIN_MS, median * HITCH_FACTOR);
|
|
529
|
+
const hitchFrames = [];
|
|
530
|
+
for (let index = 1; index < frames.length; index++) {
|
|
531
|
+
const interval = frames[index].at - frames[index - 1].at;
|
|
532
|
+
if (interval >= threshold && after(frames[index].at)) hitchFrames.push({ from: frames[index - 1].at, to: frames[index].at, intervalMs: interval });
|
|
533
|
+
}
|
|
534
|
+
const counterAt = (at) => {
|
|
535
|
+
let found = null;
|
|
536
|
+
for (const counter of counters || []) { if (counter.at <= at) found = counter; else break; }
|
|
537
|
+
return found;
|
|
538
|
+
};
|
|
539
|
+
const inWindow = (list, from, to) => (list || []).filter((entry) => entry.at != null && entry.at >= from && entry.at <= to);
|
|
540
|
+
const hitches = hitchFrames.sort((a, b) => b.intervalMs - a.intervalMs).slice(0, 25).map((hitch) => {
|
|
541
|
+
const aggregate = aggregateWindow(prepared, info, hitch.from, hitch.to);
|
|
542
|
+
const gcMs = aggregate.owners.get("gc") || 0;
|
|
543
|
+
const compiles = inWindow(probe.lateCompiles, hitch.from - 1000, hitch.to);
|
|
544
|
+
const pipelines = inWindow(probe.gpuCompiles, hitch.from - 2000, hitch.to).filter((entry) => entry.kind !== "shaderModule").length;
|
|
545
|
+
const textures = inWindow(probe.textures, hitch.from - 500, hitch.to);
|
|
546
|
+
const downloads = inWindow(probe.resources, hitch.from - 1000, hitch.to);
|
|
547
|
+
const decodes = (probe.audioDecodes || []).filter((entry) => entry.at >= hitch.from - 1000 && entry.startAt <= hitch.to);
|
|
548
|
+
const before = counterAt(hitch.from - 500);
|
|
549
|
+
const afterCounter = counterAt(hitch.to + 600);
|
|
550
|
+
const growth = {};
|
|
551
|
+
if (before && afterCounter) {
|
|
552
|
+
for (const name of ["meshes", "materials", "particleSystems", "textures"]) {
|
|
553
|
+
const delta = (afterCounter[name] ?? 0) - (before[name] ?? 0);
|
|
554
|
+
if (delta > 0) growth[name] = delta;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
const scriptMs = aggregate.busyMs - gcMs;
|
|
558
|
+
// The likely cause, strongest evidence first; the agent confirms it.
|
|
559
|
+
let likely = "GPU or browser work (little script, nothing new)";
|
|
560
|
+
if (compiles.length || (pipelines && scriptMs < hitch.intervalMs * 0.4)) likely = "shader / pipeline compile";
|
|
561
|
+
else if (gcMs >= hitch.intervalMs * 0.3) likely = "garbage collection";
|
|
562
|
+
else if (downloads.length || decodes.length || textures.length) likely = "first-use asset: download, decode or texture upload";
|
|
563
|
+
else if (Object.keys(growth).length) likely = "content created during play";
|
|
564
|
+
else if (scriptMs >= hitch.intervalMs * 0.5) likely = "script";
|
|
565
|
+
const phase = phases.find((candidate) => hitch.to >= candidate.from && hitch.to < candidate.to);
|
|
566
|
+
return {
|
|
567
|
+
t: t(hitch.to), msAfterReveal: revealAt != null ? round(hitch.to - revealAt, 0) : null, phase: phase ? phase.name : null,
|
|
568
|
+
intervalMs: round(hitch.intervalMs), scriptMs: round(scriptMs), gcMs: round(gcMs), likely,
|
|
569
|
+
lateCompiles: [...new Set(compiles.map((record) => record.cause || record.causeKind))].slice(0, 6), lateCompileCount: compiles.length,
|
|
570
|
+
pipelines, textures: textures.length, downloads: downloads.slice(0, 5).map((entry) => ({ name: entry.name.split(/[?#]/)[0].split("/").slice(-1)[0] || entry.name, type: entry.type, kb: entry.kb })),
|
|
571
|
+
audioDecodes: decodes.length, growth,
|
|
572
|
+
top: [...aggregate.self].sort((a, b) => b[1] - a[1]).slice(0, 4).map(([key, ms]) => ({ name: aggregate.symbols.get(key).name, owner: aggregate.symbols.get(key).owner, ms: round(ms) })),
|
|
573
|
+
yours: [...aggregate.responsible.values()].sort((a, b) => b.totalMs - a.totalMs).slice(0, 3).map((blame) => ({ name: blame.symbol.name, file: blame.symbol.file, line: blame.symbol.line, ms: round(blame.totalMs) })),
|
|
574
|
+
};
|
|
575
|
+
}).sort((a, b) => a.t - b.t);
|
|
576
|
+
|
|
577
|
+
const laterDownloads = (probe.resources || []).filter((entry) => after(entry.at)).sort((a, b) => b.kb - a.kb).slice(0, 15)
|
|
578
|
+
.map((entry) => ({ t: t(entry.at), name: entry.name, type: entry.type, kb: entry.kb, ms: entry.ms }));
|
|
579
|
+
return {
|
|
580
|
+
revealT: t(revealAt), revealSource: toolkitReveal ? "toolkit" : revealMark ? `mark "${revealMark.name}"` : null,
|
|
581
|
+
toolkit: probe.toolkit || null,
|
|
582
|
+
medianFrameMs: round(median), hitchThresholdMs: round(threshold),
|
|
583
|
+
hitchCount: hitchFrames.length, hitchMs: round(hitchFrames.reduce((sum, hitch) => sum + hitch.intervalMs, 0)),
|
|
584
|
+
hitches,
|
|
585
|
+
lateCompileCount: (probe.lateCompiles || []).length, lateCompiles, lateCompilePasses,
|
|
586
|
+
pipelinesAfterReveal: (probe.gpuCompiles || []).filter((entry) => entry.kind !== "shaderModule" && after(entry.at)).length,
|
|
587
|
+
texturesAfterReveal: (probe.textures || []).filter((entry) => after(entry.at)).length,
|
|
588
|
+
audioDecodesAfterReveal: (probe.audioDecodes || []).filter((entry) => after(entry.at)).length,
|
|
589
|
+
downloadsAfterReveal: laterDownloads,
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
|
|
470
593
|
/** Plain-language signals the agent should look at first. They point; the agent diagnoses. */
|
|
471
594
|
function signals(analysis) {
|
|
472
595
|
const notes = [];
|
|
@@ -488,6 +611,18 @@ function signals(analysis) {
|
|
|
488
611
|
notes.push(`${waits.length} frame(s) of ${waits.map((frame) => `${frame.intervalMs} ms at ${frame.t}s`).slice(0, 4).join(", ")} were spent waiting, not running script (main thread ${waits.map((frame) => frame.scriptMs).slice(0, 4).join(" / ")} ms)` +
|
|
489
612
|
(withCompiles.length ? ` — ${withCompiles.length} of them right after new GPU pipelines / programs were created: the GPU process compiling shaders.${analysis.gpuCold ? " This capture was GPU-cold (--gpu-cold), as on a first visit." : " A later visit may hide it (shader caches): confirm with --gpu-cold true."}` : ` — GPU-bound frames or browser work; check draws and the GPU timers.`));
|
|
490
613
|
}
|
|
614
|
+
const late = analysis.lateStutter;
|
|
615
|
+
if (late && late.lateCompileCount) {
|
|
616
|
+
notes.push(`${late.lateCompileCount} shader / pipeline compile(s) after the reveal${late.revealT != null ? ` (${late.revealT}s)` : ""}, from ${late.lateCompiles.length} cause(s): ${late.lateCompiles.slice(0, 4).map((group) => `${group.cause} ×${group.count}`).join("; ")}. Each is a first-use stutter the pre-warm missed (see LATE STUTTER).`);
|
|
617
|
+
} else if (late && late.pipelinesAfterReveal) {
|
|
618
|
+
notes.push(`${late.pipelinesAfterReveal} GPU pipelines / programs were created after the reveal${late.toolkit ? "" : " (no Babylon Toolkit late-compile detector on this page, so no causes)"} — first-use shader work during play.`);
|
|
619
|
+
}
|
|
620
|
+
if (late && late.hitchCount) {
|
|
621
|
+
const byCause = {};
|
|
622
|
+
for (const hitch of late.hitches) byCause[hitch.likely] = (byCause[hitch.likely] || 0) + 1;
|
|
623
|
+
notes.push(`${late.hitchCount} hitch(es) after the reveal (frames over ${late.hitchThresholdMs} ms; ${late.hitchMs} ms in all). Likely causes of the worst: ${Object.entries(byCause).map(([cause, count]) => `${cause} ×${count}`).join(" · ")}.`);
|
|
624
|
+
}
|
|
625
|
+
if (late && late.downloadsAfterReveal.length) notes.push(`${late.downloadsAfterReveal.length} download(s) finished after the reveal, largest ${late.downloadsAfterReveal[0].name.split(/[?#]/)[0].split("/").slice(-1)[0]} (${late.downloadsAfterReveal[0].kb} KB) — fetched, decoded and uploaded during play instead of behind the loading screen.`);
|
|
491
626
|
const shaderBuckets = analysis.timeline.filter((bucket) => bucket.newShaders > 0);
|
|
492
627
|
if (shaderBuckets.length) {
|
|
493
628
|
const late = shaderBuckets.filter((bucket) => bucket.t > 0.6 * analysis.timeline.length);
|
|
@@ -585,6 +720,30 @@ function printSummary(analysis) {
|
|
|
585
720
|
line(` ${String(frame.t + "s").padStart(8)} ${cost.padEnd(16)} ${String(frame.phase || "-").padEnd(14)} script ${frame.scriptMs} ms · ${frame.pipelinesNear} pipelines near · ${frame.top.slice(0, 2).map((entry) => `${entry.name} ${entry.ms}`).join(", ") || "-"}`);
|
|
586
721
|
}
|
|
587
722
|
if (analysis.gpuCold) line(` (--gpu-cold: ${analysis.gpuCold.tagged} fragment shaders made unique, so every pipeline compiled as on a first visit)`);
|
|
723
|
+
const late = analysis.lateStutter;
|
|
724
|
+
if (late) {
|
|
725
|
+
line();
|
|
726
|
+
line(`LATE STUTTER — after the reveal (${late.revealT != null ? `${late.revealT}s, from the ${late.revealSource}` : "no reveal found: mark one in the scenario"}) · median frame ${late.medianFrameMs} ms · hitch = over ${late.hitchThresholdMs} ms`);
|
|
727
|
+
if (late.toolkit) line(` toolkit: late-compile detector ${late.toolkit.lateCompileDetector ? (late.toolkit.forcedReporting ? "on (turned on by the probe)" : "on") : "not in this toolkit version"} · safety net ${late.toolkit.safetyNet == null ? "n/a" : late.toolkit.safetyNet ? "on (a late pipeline skips its draw: pop-in, not a freeze)" : "off"}`);
|
|
728
|
+
line(` ${late.hitchCount} hitch(es), ${late.hitchMs} ms · ${late.lateCompileCount} late compile(s) · ${late.pipelinesAfterReveal} pipelines · ${late.texturesAfterReveal} textures · ${late.audioDecodesAfterReveal} audio decodes · ${late.downloadsAfterReveal.length} downloads after the reveal`);
|
|
729
|
+
for (const hitch of late.hitches.slice(0, 12)) {
|
|
730
|
+
const suspects = [
|
|
731
|
+
hitch.lateCompileCount ? `${hitch.lateCompileCount} late compile(s): ${hitch.lateCompiles.slice(0, 2).join("; ")}` : "",
|
|
732
|
+
hitch.pipelines ? `${hitch.pipelines} pipelines` : "", hitch.gcMs ? `gc ${hitch.gcMs} ms` : "", hitch.textures ? `${hitch.textures} textures` : "",
|
|
733
|
+
hitch.downloads.length ? `downloads ${hitch.downloads.map((entry) => entry.name).join(", ")}` : "", hitch.audioDecodes ? `${hitch.audioDecodes} audio decode(s)` : "",
|
|
734
|
+
Object.keys(hitch.growth).length ? `new ${Object.entries(hitch.growth).map(([name, count]) => `${count} ${name}`).join(", ")}` : "",
|
|
735
|
+
].filter(Boolean).join(" · ");
|
|
736
|
+
line(` ${String(hitch.t + "s").padStart(8)} ${String(hitch.intervalMs + " ms").padEnd(10)} ${String(hitch.phase || "-").padEnd(12)} ${hitch.likely} — script ${hitch.scriptMs} ms${suspects ? " · " + suspects : ""}`);
|
|
737
|
+
}
|
|
738
|
+
if (late.lateCompilePasses.length) {
|
|
739
|
+
line(" late compiles by render pass (a pass other than \"main\" with many: a camera or render target the pre-warm never drew — created after the reveal, WarmAllCamerasOnReveal off, or a toolkit before 1.1.88):");
|
|
740
|
+
for (const pass of late.lateCompilePasses.slice(0, 6)) line(` ×${String(pass.count).padEnd(4)} pass "${pass.pass}" — ${pass.causes} cause(s), first ${pass.firstMsAfterReveal} ms after the reveal`);
|
|
741
|
+
}
|
|
742
|
+
if (late.lateCompiles.length) {
|
|
743
|
+
line(" late compiles by cause:");
|
|
744
|
+
for (const group of late.lateCompiles.slice(0, 12)) line(` ×${String(group.count).padEnd(4)} ${group.cause} [${group.effects.join(", ") || "?"}] first ${group.firstMsAfterReveal} ms after the reveal`);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
588
747
|
line();
|
|
589
748
|
line("YOUR CODE — time spent, including the library work it triggers (whole run)");
|
|
590
749
|
for (const entry of analysis.overall.lists.yoursTop.slice(0, 15)) {
|
|
@@ -699,6 +858,7 @@ function main() {
|
|
|
699
858
|
shots: fs.existsSync(path.join(captureDir, "shots")) ? fs.readdirSync(path.join(captureDir, "shots")).filter((name) => name.endsWith(".png")) : [],
|
|
700
859
|
filmstrip: fs.existsSync(path.join(captureDir, "filmstrip.json")) ? JSON.parse(fs.readFileSync(path.join(captureDir, "filmstrip.json"), "utf8")).map((frame) => ({ ...frame, t: round((frame.at - startMs) / 1000, 2) })) : [],
|
|
701
860
|
};
|
|
861
|
+
analysis.lateStutter = lateStutter(probe, frames, probe.counters, prepared, info, phases, startMs, endMs);
|
|
702
862
|
analysis.signals = signals(analysis);
|
|
703
863
|
if (flags.drill) {
|
|
704
864
|
analysis.drill = flags.drill.split(",").map((name) => ({
|
|
@@ -10,7 +10,9 @@
|
|
|
10
10
|
* programs / pipelines), JS heap;
|
|
11
11
|
* - long animation frames (LoAF) with their script attribution, when the browser supports them;
|
|
12
12
|
* - every shader module / pipeline (WebGPU) and program (WebGL) the page creates, with its time (`gpuCompiles`);
|
|
13
|
-
* - phase marks set by the scenario (`__btProfile.mark("countdown")`)
|
|
13
|
+
* - phase marks set by the scenario (`__btProfile.mark("countdown")`);
|
|
14
|
+
* - the late-stutter sources: the Babylon Toolkit's reveal and every late compile it names with its cause (`reveals`,
|
|
15
|
+
* `lateCompiles`), downloads (`resources`), GPU textures created (`textures`) and audio decodes (`audioDecodes`).
|
|
14
16
|
*
|
|
15
17
|
* Every time is an epoch time in milliseconds (`performance.timeOrigin + performance.now()`), so frames, marks and
|
|
16
18
|
* the CPU profile line up across page navigations.
|
|
@@ -183,6 +185,104 @@ export function installProbe() {
|
|
|
183
185
|
if (typeof window[name] !== "undefined") wrapCompile(window[name].prototype, "linkProgram", "program");
|
|
184
186
|
}
|
|
185
187
|
|
|
188
|
+
// First-use work that lands after the game is revealed — the late-stutter sources. The Babylon Toolkit announces its
|
|
189
|
+
// reveal (SceneManager.OnSceneRevealedObservable) and names every shader / pipeline built after it with its cause
|
|
190
|
+
// (SceneShaderWarmup.OnLateCompileObservable). The probe turns that detector on even in a production build, so a
|
|
191
|
+
// profiled deployed game reports its late compiles too.
|
|
192
|
+
state.reveals = [];
|
|
193
|
+
state.lateCompiles = [];
|
|
194
|
+
state.toolkit = null;
|
|
195
|
+
const MAX_LATE_RECORDS = 5000;
|
|
196
|
+
const hookToolkit = () => {
|
|
197
|
+
const toolkit = window.TOOLKIT;
|
|
198
|
+
if (state.toolkit || !toolkit || !toolkit.SceneShaderWarmup || !toolkit.SceneManager) return;
|
|
199
|
+
const warmup = toolkit.SceneShaderWarmup;
|
|
200
|
+
state.toolkit = { warmup: true, lateCompileDetector: !!warmup.OnLateCompileObservable, forcedReporting: false };
|
|
201
|
+
try {
|
|
202
|
+
if (warmup.OnLateCompileObservable && typeof warmup.IsLateCompileReportingEnabled === "function" && !warmup.IsLateCompileReportingEnabled()) {
|
|
203
|
+
warmup.LateCompileReporting = true;
|
|
204
|
+
state.toolkit.forcedReporting = true;
|
|
205
|
+
}
|
|
206
|
+
} catch { /* an older toolkit without the switch */ }
|
|
207
|
+
try {
|
|
208
|
+
if (toolkit.SceneManager.OnSceneRevealedObservable) {
|
|
209
|
+
toolkit.SceneManager.OnSceneRevealedObservable.add((scene) => {
|
|
210
|
+
state.reveals.push({ at: epochNow(), sceneUniqueId: scene ? scene.uniqueId : null });
|
|
211
|
+
try { state.toolkit.safetyNet = typeof warmup.IsSafetyNetEnabled === "function" && scene ? warmup.IsSafetyNetEnabled(scene.getEngine()) : null; } catch { /* not on WebGL */ }
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
} catch { /* an older toolkit without the reveal observable */ }
|
|
215
|
+
try {
|
|
216
|
+
if (warmup.OnLateCompileObservable) {
|
|
217
|
+
warmup.OnLateCompileObservable.add((record) => {
|
|
218
|
+
if (state.lateCompiles.length >= MAX_LATE_RECORDS) return;
|
|
219
|
+
state.lateCompiles.push({
|
|
220
|
+
at: epochNow(), kind: record.kind, causeKind: record.causeKind, cause: record.cause, meshName: record.meshName,
|
|
221
|
+
materialName: record.materialName, particleSystemName: record.particleSystemName, postProcessName: record.postProcessName,
|
|
222
|
+
renderPassName: record.renderPassName, effectName: record.effectName, effectKey: String(record.effectKey || "").slice(0, 400),
|
|
223
|
+
msSinceReveal: record.msSinceReveal, sceneUniqueId: record.sceneUniqueId,
|
|
224
|
+
});
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
} catch { /* an older toolkit without the detector */ }
|
|
228
|
+
};
|
|
229
|
+
setInterval(hookToolkit, ATTACH_POLL_MS);
|
|
230
|
+
|
|
231
|
+
// Downloads: what the page fetched and when it finished — a texture, model or sound fetched during play is decoded and
|
|
232
|
+
// uploaded right after it arrives, often in one long frame.
|
|
233
|
+
state.resources = [];
|
|
234
|
+
try {
|
|
235
|
+
const resourceObserver = new PerformanceObserver((list) => {
|
|
236
|
+
for (const entry of list.getEntries()) {
|
|
237
|
+
if (state.resources.length >= MAX_LATE_RECORDS) return;
|
|
238
|
+
state.resources.push({
|
|
239
|
+
startAt: performance.timeOrigin + entry.startTime, at: performance.timeOrigin + entry.responseEnd,
|
|
240
|
+
name: String(entry.name || "").slice(0, 300), type: entry.initiatorType,
|
|
241
|
+
kb: +(((entry.encodedBodySize || entry.transferSize || 0)) / 1024).toFixed(1), ms: +entry.duration.toFixed(1),
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
resourceObserver.observe({ type: "resource", buffered: true });
|
|
246
|
+
} catch { /* resource timing unavailable */ }
|
|
247
|
+
|
|
248
|
+
// GPU textures created (WebGPU createTexture, WebGL texture storage / compressed uploads): a first-time texture during
|
|
249
|
+
// play costs its decode and upload on that frame.
|
|
250
|
+
state.textures = [];
|
|
251
|
+
const recordTexture = (width, height) => { if (state.textures.length < MAX_GPU_COMPILES) state.textures.push({ at: epochNow(), width: width || null, height: height || null }); };
|
|
252
|
+
const wrapTexture = (prototype, method, size) => {
|
|
253
|
+
if (!prototype || typeof prototype[method] !== "function") return;
|
|
254
|
+
const original = prototype[method];
|
|
255
|
+
prototype[method] = function (...args) { try { const [width, height] = size(args); recordTexture(width, height); } catch { recordTexture(null, null); } return original.apply(this, args); };
|
|
256
|
+
};
|
|
257
|
+
if (typeof GPUDevice !== "undefined") {
|
|
258
|
+
wrapTexture(GPUDevice.prototype, "createTexture", (args) => {
|
|
259
|
+
const size = args[0] && args[0].size;
|
|
260
|
+
return Array.isArray(size) ? [size[0], size[1]] : size ? [size.width, size.height] : [null, null];
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
if (typeof WebGL2RenderingContext !== "undefined") {
|
|
264
|
+
wrapTexture(WebGL2RenderingContext.prototype, "texStorage2D", (args) => [args[3], args[4]]);
|
|
265
|
+
wrapTexture(WebGL2RenderingContext.prototype, "compressedTexImage2D", (args) => (args[1] === 0 ? [args[3], args[4]] : [null, null]));
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Audio decoding: a sound decoded the first time it plays stalls that moment (decodeAudioData runs off the main thread,
|
|
269
|
+
// but its arrival and the buffer it creates land on a frame).
|
|
270
|
+
state.audioDecodes = [];
|
|
271
|
+
try {
|
|
272
|
+
const audioPrototype = typeof BaseAudioContext !== "undefined" ? BaseAudioContext.prototype : null;
|
|
273
|
+
if (audioPrototype && typeof audioPrototype.decodeAudioData === "function") {
|
|
274
|
+
const decode = audioPrototype.decodeAudioData;
|
|
275
|
+
audioPrototype.decodeAudioData = function (data, ...rest) {
|
|
276
|
+
const startAt = epochNow();
|
|
277
|
+
const kb = data && data.byteLength ? +(data.byteLength / 1024).toFixed(1) : null;
|
|
278
|
+
const result = decode.call(this, data, ...rest);
|
|
279
|
+
const done = () => { if (state.audioDecodes.length < MAX_LATE_RECORDS) state.audioDecodes.push({ startAt, at: epochNow(), kb }); };
|
|
280
|
+
if (result && typeof result.then === "function") result.then(done, done);
|
|
281
|
+
return result;
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
} catch { /* no Web Audio */ }
|
|
285
|
+
|
|
186
286
|
// Long Animation Frames name the script, function and invoker behind every frame over 50 ms.
|
|
187
287
|
try {
|
|
188
288
|
const observer = new PerformanceObserver((list) => {
|
|
@@ -249,7 +349,24 @@ export function installProbe() {
|
|
|
249
349
|
};
|
|
250
350
|
|
|
251
351
|
/** Everything the probe recorded, for the capture script to save. */
|
|
252
|
-
state.dump = () =>
|
|
352
|
+
state.dump = () => {
|
|
353
|
+
// A toolkit found only after its reveal: take the late compiles it kept (their own reveal-relative times).
|
|
354
|
+
try {
|
|
355
|
+
const toolkit = window.TOOLKIT;
|
|
356
|
+
const scene = currentScene();
|
|
357
|
+
if (toolkit && toolkit.SceneShaderWarmup && scene && state.lateCompiles.length === 0 && typeof toolkit.SceneShaderWarmup.GetLateCompiles === "function") {
|
|
358
|
+
for (const record of toolkit.SceneShaderWarmup.GetLateCompiles(scene) || []) state.lateCompiles.push({ ...record, at: null });
|
|
359
|
+
}
|
|
360
|
+
} catch { /* nothing to recover */ }
|
|
361
|
+
return state.snapshot();
|
|
362
|
+
};
|
|
363
|
+
state.snapshot = () => ({
|
|
364
|
+
reveals: state.reveals,
|
|
365
|
+
lateCompiles: state.lateCompiles,
|
|
366
|
+
toolkit: state.toolkit,
|
|
367
|
+
resources: state.resources,
|
|
368
|
+
textures: state.textures,
|
|
369
|
+
audioDecodes: state.audioDecodes,
|
|
253
370
|
engine: state.engine || null,
|
|
254
371
|
engineAttachedAt: state.engineAttachedAt,
|
|
255
372
|
scenesSeen: state.scenesSeen,
|