@babylonjs-toolkit/agent 1.2.12 → 1.2.14

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 CHANGED
@@ -1,4 +1,4 @@
1
- # Babylon Toolkit Desktop Agent (1.2.12)
1
+ # Babylon Toolkit Desktop Agent (1.2.14)
2
2
 
3
3
  The desktop agent owns the entire pipeline end to end — frontend and UI design, gameplay code, shaders, generated art and audio, 3D models in headless Blender, whole game levels and prefabs in a terminal-driven Unity Editor, the interactive glTF export, the web build, the dev server, and visual QA by screenshotting both Unity and the running browser.
4
4
 
@@ -72,7 +72,9 @@ copy at all, the skills and persona keep the GitHub addresses and agents read th
72
72
  The persona names the local folder and keeps GitHub as the fallback for any file that is missing.
73
73
  Claude Code asks before reading outside the project, so a global install adds one read-only rule —
74
74
  `Read(~/.claude/toolkit/reference/**)` — to `~/.claude/settings.json` (uninstall removes it, and only if
75
- the installer added it). It also adds a Claude Code `PreToolUse` hook on `Bash` that blocks a `sleep N` of 3 seconds
75
+ the installer added it). A global Claude Code install also trusts the toolkit's Unity bridge commands with
76
+ `Bash(unity command bt_*)`, so `bt_status`, `bt_build_project`, `bt_export_level`, `bt_devserver_start` and the rest
77
+ run without a prompt — and are not refused as a "deploy" in auto mode. Uninstall removes it the same way. It also adds a Claude Code `PreToolUse` hook on `Bash` that blocks a `sleep N` of 3 seconds
76
78
  or more — inside `until` / `while` loops too — and points the agent at the Agent Reference's `wait.mjs`, which waits
77
79
  for a port, URL, file, log line or command output instead; uninstall removes only that hook. `bt-agent doctor` checks that every local link resolves and says when GitHub has a
78
80
  newer Reference.
@@ -13,6 +13,13 @@ const path = require('path');
13
13
  * once, in an entry of its own, and on uninstall only that hook is removed.
14
14
  */
15
15
 
16
+ /**
17
+ * Allow rule that trusts the Babylon Toolkit's Unity bridge commands (`unity command bt_status`,
18
+ * `bt_build_project`, `bt_export_level`, `bt_devserver_start` …). They build, export and serve the local
19
+ * project, yet without a rule Claude Code's auto mode can refuse one as a "deploy" mid-run.
20
+ */
21
+ const TOOLKIT_COMMAND_RULE = 'Bash(unity command bt_*)';
22
+
16
23
  /** The no-sleep hook script shipped in this package. */
17
24
  const BLOCK_SLEEP_SOURCE = path.join(__dirname, '..', 'scripts', 'hooks', 'block-sleep.js');
18
25
 
@@ -219,4 +226,4 @@ function hasHook(file, command, { event = PRE_TOOL_USE, matcher = BASH_MATCHER }
219
226
  }
220
227
  }
221
228
 
222
- module.exports = { addAllowRule, removeAllowRule, hasAllowRule, blockSleepHook, addHook, removeHook, hasHook };
229
+ module.exports = { TOOLKIT_COMMAND_RULE, addAllowRule, removeAllowRule, hasAllowRule, blockSleepHook, addHook, removeHook, hasHook };
package/lib/doctor.js CHANGED
@@ -7,7 +7,7 @@ const { resolveTargets } = require('./targets');
7
7
  const { listSkills } = require('./payload');
8
8
  const { hasPersona } = require('./persona');
9
9
  const { hasCodexNetwork } = require('./codex-config');
10
- const { hasAllowRule, blockSleepHook, hasHook } = require('./claude-settings');
10
+ const { TOOLKIT_COMMAND_RULE, hasAllowRule, blockSleepHook, hasHook } = require('./claude-settings');
11
11
  const reference = require('./reference');
12
12
  const { resolveTargetPath } = require('./paths');
13
13
  const { readSettings } = require('./bridge/config');
@@ -124,6 +124,7 @@ function checkReference({ mode, projectRoot, resolved, skills, checkSkills, chec
124
124
  const claudeHome = path.dirname(resolveTargetPath(claude.global.instructions, mode, projectRoot));
125
125
  const settingsFile = path.join(claudeHome, 'settings.json');
126
126
  if (!hasAllowRule(settingsFile, reference.CLAUDE_READ_RULE)) warnings.push(`${settingsFile} has no ${reference.CLAUDE_READ_RULE} — Claude Code will ask before each read`);
127
+ if (!hasAllowRule(settingsFile, TOOLKIT_COMMAND_RULE)) warnings.push(`${settingsFile} has no ${TOOLKIT_COMMAND_RULE} — Claude Code may ask before, or in auto mode refuse, a Unity bridge command; run \`bt-agent update\``);
127
128
  hook = checkSleepHook(claudeHome, settingsFile);
128
129
  if (!hook.present) warnings.push(`${settingsFile} has no working no-sleep hook (${hook.command}) — agents can sleep-poll; run \`bt-agent update\``);
129
130
  }
package/lib/install.js CHANGED
@@ -7,7 +7,7 @@ const { resolveTargets } = require('./targets');
7
7
  const { listSkills, copyDir } = require('./payload');
8
8
  const { applyPersona, removePersona, personaText } = require('./persona');
9
9
  const { applyCodexConfig } = require('./codex-config');
10
- const { addAllowRule, removeAllowRule, blockSleepHook, addHook, removeHook } = require('./claude-settings');
10
+ const { TOOLKIT_COMMAND_RULE, addAllowRule, removeAllowRule, blockSleepHook, addHook, removeHook } = require('./claude-settings');
11
11
  const reference = require('./reference');
12
12
  const manifest = require('./manifest');
13
13
  const { manifestPath, resolveTargetPath } = require('./paths');
@@ -113,13 +113,15 @@ function install(opts = {}) {
113
113
  : null;
114
114
  }
115
115
 
116
- // Claude Code asks before reading outside the project; the global copy gets one read-only allow rule,
116
+ // A global Claude Code install trusts the toolkit's `unity command bt_*` bridge commands. With the local
117
+ // Reference it also gets one read-only rule for it (Claude Code asks before reading outside the project)
117
118
  // and the no-sleep hook that points agents at the copy's wait.mjs.
118
- if (localReference && mode === 'global') {
119
- const claude = resolved.selected.find((target) => target.id === 'claude');
120
- if (claude) {
121
- const claudeHome = path.dirname(resolveTargetPath(claude.global.instructions, mode, projectRoot));
122
- const settingsFile = path.join(claudeHome, 'settings.json');
119
+ const claude = mode === 'global' ? resolved.selected.find((target) => target.id === 'claude') : null;
120
+ if (claude) {
121
+ const claudeHome = path.dirname(resolveTargetPath(claude.global.instructions, mode, projectRoot));
122
+ const settingsFile = path.join(claudeHome, 'settings.json');
123
+ report.permissions.push(addAllowRule(settingsFile, TOOLKIT_COMMAND_RULE, { dryRun }));
124
+ if (localReference) {
123
125
  report.permissions.push(addAllowRule(settingsFile, reference.CLAUDE_READ_RULE, { dryRun }));
124
126
  report.hooks.push(installSleepHook(claudeHome, settingsFile, { dryRun }));
125
127
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babylonjs-toolkit/agent",
3
- "version": "1.2.12",
3
+ "version": "1.2.14",
4
4
  "description": "Installs the Babylon Toolkit Desktop Agent for Claude Code, Codex, GitHub Copilot, Gemini CLI and Antigravity.",
5
5
  "keywords": [
6
6
  "babylonjs",
@@ -43,7 +43,7 @@ scripts task by task. The work and its proof are the same either way.
43
43
  - **Merge controls:** `--cell:` area patch in meters (15), `--spread:` meters a merge may extend past its largest piece (3), `--atlas-share:` largest share of one lightmap atlas per merged mesh (0.45), `--no-shadergraphs` (do not merge Shader Graph materials even when they pass the scan), `--no-lods` (leave LOD groups alone), `--shaders:` extra custom shaders known to be pivot-independent.
44
44
  - **Project-wide exporter settings (opt in — they change every scene's export):** `--textures:ktx2` (KTX2 / UASTC textures: ~4–8× less GPU memory, slower export), `--resolution:css` (render at CSS pixels instead of device pixels on desktop: ¼ of the pixels on a 2× screen — only helps a GPU-bound scene).
45
45
  - **`--no-bake` / `--no-export` / `--no-browser`** — skip those phases; the report says what stayed unverified.
46
- - **`--pins:`** — seconds after the scene is ready at which the profiler pins the camera (default `40,60`; pick moments inside the scene's own flythrough / spawn view). **`--times:`** — timeline sample moments.
46
+ - **`--pins:`** — seconds after the scene is ready at which the profiler pins the camera (default `40,60`; pick moments inside the scene's own flythrough / spawn view). Each pin also **holds the scene's Timeline** at the director time it reached (the profiler's `--hold`, Phase 1), so the sun, the active light and the shot stay put while it is measured. **`--times:`** — timeline sample moments.
47
47
 
48
48
  ---
49
49
 
@@ -201,10 +201,12 @@ The exported source scene must be current: find `<exportRoot>/scenes/<source>.gl
201
201
  mkdir -p "$PROJ/.agents/optimize/$SRC_NAME/profile"
202
202
  node "$QA/profile-browser.mjs" --scene <source>.gltf --times 10,20,30,45,60,75,90 --window 4 \
203
203
  --out "$PROJ/.agents/optimize/$SRC_NAME/profile/before-timeline.json"
204
- node "$QA/profile-browser.mjs" --scene <source>.gltf --pin 40,60,75 --toggles none --window 5 --settle 8 --cpuprofile true --casters true \
204
+ node "$QA/profile-browser.mjs" --scene <source>.gltf --pin 40,60,75 --hold true --toggles none --window 5 --settle 8 --cpuprofile true --casters true \
205
205
  --shots "$PROJ/.agents/optimize/$SRC_NAME/profile/shots" --out "$PROJ/.agents/optimize/$SRC_NAME/profile/before-pinned.json"
206
206
  ```
207
207
 
208
+ **Hold the Timeline at every pin — `--hold`.** A pinned camera holds the *view*, but a scene with a Timeline keeps playing around it: the sun turns, a second sun switches on, shots cut and fade, and each of those changes the shadow maps, the light count and the draws. `--hold true` pauses the scene's `PlayableDirector` where it is when the pin lands, sets its time and evaluates every track there, re-applies the hold after the settle, and records it as the pin's `heldTimeline` (seconds; `null` when the scene has no director — the run still measures). `--hold 40:24,60:44,75:52` holds each named pin at a fixed director time instead (pin seconds : director seconds) — use it to measure two exports at the same moment of the Timeline. After the measure window the director is read again: a pin whose Timeline moved more than 0.05 s **fails** (`holdCheck.error`, `FAILED pin …` on stderr, exit 1), because its numbers mix two moments. With `--poses`, a pose file's own `heldTimeline` (the output of a held run) holds any pin `--hold` does not name, so replaying `before-pinned.json` measures the same views at the same Timeline moments; `--hold false` turns all holding off.
209
+
208
210
  When an earlier run (or a plan's `tests/poses-pinned.json`) already pinned this scene, replay those poses with `--poses <file>` instead of `--pin`, so every run of the scene is measured from the same views.
209
211
 
210
212
  `--pin` waits the given seconds after the scene is ready, then detaches the camera from its rig and **records its exact pose** (position, rotation and lens — field of view and clip planes, because Timeline / Cinemachine tracks animate the lens too; the lens fields are made read-only while pinned, because a lens track keeps writing them and TAA builds its projection from them before any observer runs). Every later run replays those poses with `--poses before-pinned.json`, so before and after are measured from the same views — pinning by time alone lands on different views, because a lighter scene loads sooner and its tour runs ahead.
@@ -246,19 +248,21 @@ bake() { # never trust lighting_bake_status alone: it can say "completed" befo
246
248
  local started; started=$(date +%s)
247
249
  unity command bake_lighting --confirm true --project-path "$PROJ"
248
250
  node "$WAIT" cmd "unity command run_script --file AgentScripts/bt-optimize/BtOptimize.cs --entry BtOptimize.BakeState --args '[\"$started\"]' --project-path '$PROJ' --format json" \
249
- --match '"result": *"done"' --fail '"result": *"stopped"' --interval 15 --timeout 5400 || return 1
251
+ --match '"result": *"done' --fail '"result": *"(stopped|empty)' --interval 15 --timeout 5400 || return 1
250
252
  unity command save_all --project-path "$PROJ" # the bake assigns new LightingData; exports refuse a dirty scene
251
253
  }
252
- bake
254
+ bake # BakeState prints "done lightmaps=N probes=M lightmapped=R probeGroups=G data=<LightingData>"
253
255
  bt_run BtCombine CorrectDensity '[]' # after a merge: merged meshes get ~84-89% of their sources' texels; raise Scale In Lightmap
254
256
  # corrected=N with N > 0 → bake once more
255
257
  bt_run BtCombine Verify '[]' # after a merge: must end with problems=0
256
258
  bt_run BtOptimize Verify "$(arg "$TUNE")" # always: must end with problems=0 (verify.md lists each problem)
257
259
  ```
258
260
 
261
+ **An empty bake fails, never passes.** A bake that fails part-way still writes its LightingData, so its write time proves nothing. `BakeState` answers `empty` when the finished bake has no lightmaps although the scene has lightmapped renderers (Contribute GI static, Receive GI Lightmaps, or a GI-contributing terrain), or no light probes although it has a `LightProbeGroup` with probes — and `bake()` fails on it. `Verify` adds the second check: every renderer or terrain whose `lightmapIndex` names a lightmap the loaded bake does not have (an empty or stale LightingData, or one from another scene) is a problem.
262
+
259
263
  ## Phase 5 — Unity side-by-side (browser poses, then LOD0 **and** LOD1)
260
264
 
261
- **First, the browser's pinned poses in Unity**, source and working copy. `PoseView` puts a capture camera named `BtOptimizePoseCamera` at a pose recorded by the profiler (position, rotation, vertical FOV; toolkit scenes keep Unity's coordinates), copying the main camera's URP data so post-processing matches. It renders above the scene's cameras by depth and never touches them, and it is never saved (DontSaveInEditor) — but it lives in the open scene until the scene is reopened, so **reopen the scene before exporting** (the last line below does). VAT crowd members draw magenta in URP / HDRP Unity captures — compare them in the browser. Comparing these with the browser shots of the same poses tells you which side of the export a difference is on:
265
+ **First, the browser's pinned poses in Unity**, source and working copy. `PoseView` puts a capture camera named `BtOptimizePoseCamera` at a pose recorded by the profiler (position, rotation, vertical FOV; toolkit scenes keep Unity's coordinates), copying the main camera's URP data so post-processing matches. It renders above the scene's cameras by depth and never touches them, and it is never saved (DontSaveInEditor) — but it lives in the open scene until the scene is reopened, so **reopen the scene before exporting** (Phase 6's `open_scene` does). A DontSaveInEditor object survives `OpenScene`, so `PoseView` first destroys **every** pose camera the Editor holds (`Resources.FindObjectsOfTypeAll`, any scene or none, never an asset) — on entry and again after it opens the scene — so capturing two scenes in a row leaves exactly one pose camera, in the scene asked for. `Verify` and the camera comparison use the same lookup. VAT crowd members draw magenta in URP / HDRP Unity captures — compare them in the browser. Comparing these with the browser shots of the same poses tells you which side of the export a difference is on:
262
266
 
263
267
  ```bash
264
268
  python3 -c "import json; [print(p['atSeconds'],*p['pinned']['position'],*p['pinned']['rotation'],p['pinned']['fov']) for p in json.load(open('$PROJ/.agents/optimize/$SRC_NAME/profile/before-pinned.json'))['pins']]" > /tmp/poses.txt
@@ -316,9 +320,10 @@ unity command open_scene --path "$OUT" --project-path "$PROJ"
316
320
  bt_run BtOptimize Verify "$(arg "$TUNE")" # problems=0 before every export
317
321
  unity command bt_export_level --scene "$OUT" --project-path "$PROJ" --timeout 3600 # record the duration
318
322
  unity command bt_devserver_start --project-path "$PROJ"
319
- node "$QA/gltf-stats.mjs" <source.gltf> <optimized.gltf>
323
+ node "$QA/gltf-stats.mjs" <source.gltf> <optimized.gltf> # .gz.gltf too (gunzipped by magic bytes); buffers on disk and uncompressed
320
324
  node "$QA/profile-browser.mjs" --scene <optimized>.gltf --times 10,20,30,45,60,75,90 --window 4 --out "$REPORT/profile/after-timeline.json"
321
325
  node "$QA/profile-browser.mjs" --scene <optimized>.gltf --poses "$PROJ/.agents/optimize/$SRC_NAME/profile/before-pinned.json" --toggles none --window 5 --settle 8 --cpuprofile true \
326
+ --casters true \
322
327
  --shots "$REPORT/profile/shots" --out "$REPORT/profile/after-pinned.json"
323
328
  node "$QA/compare-profiles.mjs" --label Original,Optimized "$PROJ/.agents/optimize/$SRC_NAME/profile/before-pinned.json" "$REPORT/profile/after-pinned.json"
324
329
  node "$QA/compare-profiles.mjs" --label Original,Optimized "$PROJ/.agents/optimize/$SRC_NAME/profile/before-timeline.json" "$REPORT/profile/after-timeline.json"
@@ -391,3 +396,8 @@ Reply in plain language with images, and write `$REPORT/report.md`. Both open wi
391
396
  | The game lost its post-processing / looks flat after the run | A camera was saved disabled: `Verify` compares every camera with the source; re-enable it, reopen, re-export |
392
397
  | A pruned caster's shadow is missing in a capture | Take it off the prune list, re-run `PruneShadowCasters` (it restores the original mode), re-bake |
393
398
  | `BakeState` keeps returning `stopped` | The bake never started or failed: `console --level error`, then `bake_lighting` again |
399
+ | `BakeState` returns `empty` (`lightmaps=0` or `probes=0`) | The bake finished but wrote nothing: `console --level error` — an unsupported denoiser (OptiX on Apple silicon: set the Lighting Settings' denoisers to OpenImageDenoise, AO included), a GPU lightmapper that ran out of memory (lower the lightmap size or use the CPU lightmapper), or no lightmapped renderers left after a merge; fix it and bake again. Never export an empty bake |
400
+ | `Verify`: "lightmapped renderer points past the baked lightmaps" | The scene's LightingData is empty, stale or another scene's — bake again (`bake()`), then Verify |
401
+ | `FAILED pin …: Timeline drifted` from `profile-browser` | Something resumed the director during the window (a seek or a script): re-run that pin; when it repeats, hold a time outside the moment that resumes it |
402
+ | `gltf-stats`: `Unexpected token` on a `.gz.gltf` | An old copy of the tool: copy `scripts/qa/*` into `.agents/optimize/.qa-tools/` again (gzipped exports are read since this version) |
403
+ | Two `BtOptimizePoseCamera`s, or a capture of the wrong scene | An old `BtOptimize.cs`: copy `scripts/*.cs` into `AgentScripts/bt-optimize/` again; `PoseView` now destroys every earlier pose camera |
@@ -1514,7 +1514,8 @@ public static class BtOptimize
1514
1514
 
1515
1515
  /// <summary>
1516
1516
  /// Checks the active working copy against its source (the scene named in working-copy.txt) and the Tune rules, and
1517
- /// writes verify.md / verify.json. Problems: unsaved changes; a pose camera left in the scene; a camera whose enabled
1517
+ /// writes verify.md / verify.json. Problems: unsaved changes; a pose camera left in the scene; a lightmapped renderer
1518
+ /// whose lightmap index names a lightmap the bake does not have (an empty or stale LightingData); a camera whose enabled
1518
1519
  /// state differs from the source (a capture step that disabled the main camera and was saved ships a game with no
1519
1520
  /// post-processing); lighting settings that differ from the source; rigid skinned meshes Tune converts that are
1520
1521
  /// still skinned; repeated meshes (instanceRepeatsFrom copies or more) that are lightmapped or probe-lit; static
@@ -1536,7 +1537,12 @@ public static class BtOptimize
1536
1537
  var checks = new Dictionary<string, object>();
1537
1538
 
1538
1539
  if (scene.isDirty) problems.Add("the scene has unsaved changes — save it before exporting");
1539
- if (scene.GetRootGameObjects().Any(root => root.name == PoseCameraName)) problems.Add(PoseCameraName + " is in the scene — reopen the scene before exporting (it would export as a camera)");
1540
+ if (FindPoseCameras().Any(camera => camera.gameObject.scene == scene)) problems.Add(PoseCameraName + " is in the scene — reopen the scene before exporting (it would export as a camera)");
1541
+
1542
+ // Read before the source is opened additively: loading it merges its lightmaps into LightmapSettings.
1543
+ var badLightmapIndices = LightmapIndexOutOfRange(scene);
1544
+ problems.AddRange(badLightmapIndices.Select(entry => "lightmapped renderer points past the baked lightmaps — re-bake: " + entry));
1545
+ checks["lightmaps"] = new Dictionary<string, object> { { "baked", LightmapSettings.lightmaps.Length }, { "indexOutOfRange", badLightmapIndices.Count } };
1540
1546
 
1541
1547
  var copyCameras = CameraStates(scene);
1542
1548
  var copyLighting = ReadLighting(scene);
@@ -1640,11 +1646,31 @@ public static class BtOptimize
1640
1646
  private static Dictionary<string, bool> CameraStates(Scene scene)
1641
1647
  {
1642
1648
  var states = new Dictionary<string, bool>();
1643
- foreach (var camera in scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Camera>(true)).Where(camera => camera.name != PoseCameraName))
1649
+ foreach (var camera in scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Camera>(true)).Where(camera => !IsPoseCamera(camera)))
1644
1650
  states[PathOf(camera.transform)] = camera.enabled && camera.gameObject.activeInHierarchy;
1645
1651
  return states;
1646
1652
  }
1647
1653
 
1654
+ /// <summary>Unity's lightmap index for "not lightmapped, but contributes to GI" (static objects baked into probes only).</summary>
1655
+ private const int LightmapIndexNotLightmappedGI = 0xFFFE;
1656
+
1657
+ /// <summary>
1658
+ /// Every renderer and terrain in the scene whose lightmap index names a lightmap the loaded bake does not have — a
1659
+ /// LightingData that is empty, stale or from another scene. Each entry is "path index=N of M". The scene must be the
1660
+ /// only loaded scene with lightmaps (an additive scene's lightmaps shift the indices).
1661
+ /// </summary>
1662
+ private static List<string> LightmapIndexOutOfRange(Scene scene)
1663
+ {
1664
+ int lightmapCount = LightmapSettings.lightmaps.Length;
1665
+ bool OutOfRange(int index) => index >= 0 && index < LightmapIndexNotLightmappedGI && index >= lightmapCount;
1666
+ var roots = scene.GetRootGameObjects();
1667
+ var renderers = roots.SelectMany(root => root.GetComponentsInChildren<Renderer>(true))
1668
+ .Where(renderer => OutOfRange(renderer.lightmapIndex)).Select(renderer => PathOf(renderer.transform) + " index=" + renderer.lightmapIndex + " of " + lightmapCount);
1669
+ var terrains = roots.SelectMany(root => root.GetComponentsInChildren<Terrain>(true))
1670
+ .Where(terrain => OutOfRange(terrain.lightmapIndex)).Select(terrain => PathOf(terrain.transform) + " index=" + terrain.lightmapIndex + " of " + lightmapCount);
1671
+ return renderers.Concat(terrains).ToList();
1672
+ }
1673
+
1648
1674
  /// <summary>
1649
1675
  /// The scene's lighting setup as text, for comparing a copy with its source: the Lighting Settings (mixed mode,
1650
1676
  /// indirect intensity, albedo boost, lightmapper, resolution), ambient and reflection settings, skybox, fog, and the
@@ -1681,10 +1707,14 @@ public static class BtOptimize
1681
1707
  private const long BakeStartGraceSeconds = 120;
1682
1708
 
1683
1709
  /// <summary>
1684
- /// Where a bake started at the given time stands, for `wait.mjs cmd` to poll: "baking" while the lightmapper runs,
1685
- /// "done" once it has stopped and the active scene's LightingData asset was written at or after the start, "stopped"
1686
- /// when it is not running and wrote nothing more than BakeStartGraceSeconds after the start, "waiting" otherwise.
1687
- /// `lighting_bake_status` alone can report "completed" before the bake has started.
1710
+ /// Where a bake started at the given time stands, for `wait.mjs cmd` to poll: "baking" while the lightmapper runs;
1711
+ /// once it has stopped and the active scene's LightingData asset was written at or after the start, "done" — or
1712
+ /// "empty" when that bake wrote no lightmaps although the scene has lightmapped renderers, or no light probes although
1713
+ /// it has a LightProbeGroup (a failed bake still writes its LightingData, so the write time alone proves nothing);
1714
+ /// "stopped" when it is not running and wrote nothing more than BakeStartGraceSeconds after the start; "waiting"
1715
+ /// otherwise. "done" and "empty" are followed by the counts (`done lightmaps=12 probes=2400 lightmapped=380
1716
+ /// probeGroups=1 data=Assets/…/LightingData.asset`). `lighting_bake_status` alone can report "completed" before the
1717
+ /// bake has started.
1688
1718
  /// </summary>
1689
1719
  /// <param name="startedUnixSeconds">When bake_lighting was called, in Unix seconds (`date +%s`).</param>
1690
1720
  public static string BakeState(string startedUnixSeconds)
@@ -1694,13 +1724,58 @@ public static class BtOptimize
1694
1724
  var data = Lightmapping.lightingDataAsset;
1695
1725
  string path = data != null ? AssetDatabase.GetAssetPath(data) : "";
1696
1726
  long written = path.Length > 0 && File.Exists(path) ? new DateTimeOffset(File.GetLastWriteTimeUtc(path)).ToUnixTimeSeconds() : 0;
1697
- if (written >= started) return "done";
1698
- return DateTimeOffset.UtcNow.ToUnixTimeSeconds() - started > BakeStartGraceSeconds ? "stopped" : "waiting";
1727
+ if (written < started) return DateTimeOffset.UtcNow.ToUnixTimeSeconds() - started > BakeStartGraceSeconds ? "stopped" : "waiting";
1728
+
1729
+ var scene = SceneManager.GetActiveScene();
1730
+ int lightmaps = LightmapSettings.lightmaps.Length;
1731
+ int probes = LightmapSettings.lightProbes != null ? LightmapSettings.lightProbes.count : 0;
1732
+ int lightmapped = CountLightmappedRenderers(scene);
1733
+ int probeGroups = scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<LightProbeGroup>(false))
1734
+ .Count(group => group.enabled && group.probePositions.Length > 0);
1735
+ bool empty = (lightmapped > 0 && lightmaps == 0) || (probeGroups > 0 && probes == 0);
1736
+ return (empty ? "empty" : "done") + " lightmaps=" + lightmaps + " probes=" + probes + " lightmapped=" + lightmapped
1737
+ + " probeGroups=" + probeGroups + " data=" + (path.Length > 0 ? path : "none");
1738
+ }
1739
+
1740
+ /// <summary>
1741
+ /// How many active renderers and terrains in the scene the lightmapper bakes into lightmaps: Contribute GI static,
1742
+ /// and (for mesh renderers) Receive GI set to Lightmaps.
1743
+ /// </summary>
1744
+ private static int CountLightmappedRenderers(Scene scene)
1745
+ {
1746
+ var roots = scene.GetRootGameObjects();
1747
+ bool ContributesGI(GameObject gameObject) => GameObjectUtility.GetStaticEditorFlags(gameObject).HasFlag(StaticEditorFlags.ContributeGI);
1748
+ int meshRenderers = roots.SelectMany(root => root.GetComponentsInChildren<MeshRenderer>(false))
1749
+ .Count(renderer => renderer.enabled && renderer.receiveGI == ReceiveGI.Lightmaps && ContributesGI(renderer.gameObject));
1750
+ int terrains = roots.SelectMany(root => root.GetComponentsInChildren<Terrain>(false)).Count(terrain => terrain.enabled && ContributesGI(terrain.gameObject));
1751
+ return meshRenderers + terrains;
1699
1752
  }
1700
1753
 
1701
1754
  /// <summary>The name of the capture camera PoseView places.</summary>
1702
1755
  private const string PoseCameraName = "BtOptimizePoseCamera";
1703
1756
 
1757
+ /// <summary>
1758
+ /// Whether a camera is a PoseView capture camera: named PoseCameraName and living in the Editor, not an asset (a
1759
+ /// prefab that happens to use the name is never touched).
1760
+ /// </summary>
1761
+ private static bool IsPoseCamera(Camera camera) => camera != null && camera.name == PoseCameraName && !EditorUtility.IsPersistent(camera);
1762
+
1763
+ /// <summary>
1764
+ /// Every PoseView capture camera the Editor holds — in the active scene, in another loaded scene, or orphaned outside
1765
+ /// any scene. The camera is DontSaveInEditor, and such an object survives OpenScene(Single), so a lookup through the
1766
+ /// active scene's roots alone misses the one left by an earlier scene.
1767
+ /// </summary>
1768
+ private static List<Camera> FindPoseCameras() => Resources.FindObjectsOfTypeAll<Camera>().Where(IsPoseCamera).ToList();
1769
+
1770
+ /// <summary>Destroys every PoseView capture camera (see FindPoseCameras), so the next capture renders through exactly one.</summary>
1771
+ /// <returns>How many were destroyed.</returns>
1772
+ private static int DestroyPoseCameras()
1773
+ {
1774
+ var cameras = FindPoseCameras();
1775
+ foreach (var camera in cameras) UnityEngine.Object.DestroyImmediate(camera.gameObject);
1776
+ return cameras.Count;
1777
+ }
1778
+
1704
1779
  /// <summary>
1705
1780
  /// Opens the scene (discarding nothing: refuses when the open scene has unsaved changes) and places a capture camera
1706
1781
  /// named "BtOptimizePoseCamera" at a pose recorded by the browser profiler (toolkit scenes keep Unity's coordinates),
@@ -1708,21 +1783,22 @@ public static class BtOptimize
1708
1783
  /// `capture_game_view --camera BtOptimizePoseCamera`. It never touches the scene's own cameras (a disabled main camera
1709
1784
  /// that got saved once shipped a game with no post-processing): the pose camera renders above them by depth and is
1710
1785
  /// flagged DontSaveInEditor, so it is never written to the scene. Reopen the scene before exporting — the exporter
1711
- /// would otherwise see it as one more camera.
1786
+ /// would otherwise see it as one more camera. Every earlier pose camera is destroyed first, wherever it is (one left
1787
+ /// by another scene survives OpenScene), so exactly one renders the capture.
1712
1788
  /// </summary>
1713
1789
  public static string PoseView(string scenePath, float px, float py, float pz, float qx, float qy, float qz, float qw, float verticalFovRadians)
1714
1790
  {
1715
1791
  var active = SceneManager.GetActiveScene();
1792
+ // The only unsaved change PoseView allows itself to discard is its own pose camera.
1793
+ bool onlyPoseCamera = FindPoseCameras().Any(camera => camera.gameObject.scene == active);
1794
+ DestroyPoseCameras();
1716
1795
  if (active.path != scenePath)
1717
1796
  {
1718
- // The only unsaved change PoseView allows itself to discard is its own pose camera.
1719
- bool onlyPoseCamera = active.GetRootGameObjects().Any(root => root.name == PoseCameraName);
1720
1797
  if (active.isDirty && !onlyPoseCamera) throw new InvalidOperationException("'" + active.path + "' has unsaved changes; save or discard them first.");
1721
1798
  EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
1799
+ DestroyPoseCameras();
1722
1800
  }
1723
1801
  var scene = SceneManager.GetActiveScene();
1724
- var existing = scene.GetRootGameObjects().FirstOrDefault(root => root.name == PoseCameraName);
1725
- if (existing != null) UnityEngine.Object.DestroyImmediate(existing);
1726
1802
  var main = Camera.main;
1727
1803
  var go = new GameObject(PoseCameraName) { hideFlags = HideFlags.DontSaveInEditor };
1728
1804
  var camera = go.AddComponent<Camera>();
@@ -1737,7 +1813,7 @@ public static class BtOptimize
1737
1813
  }
1738
1814
  }
1739
1815
  // Render above every scene camera instead of disabling any of them: the scene's cameras are never changed.
1740
- var sceneCameras = scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Camera>(true)).Where(other => other != camera).ToList();
1816
+ var sceneCameras = scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Camera>(true)).Where(other => !IsPoseCamera(other)).ToList();
1741
1817
  camera.depth = sceneCameras.Count > 0 ? sceneCameras.Max(other => other.depth) + 1f : camera.depth;
1742
1818
  foreach (var component in go.GetComponents<Component>()) component.hideFlags = HideFlags.DontSaveInEditor;
1743
1819
  go.transform.SetPositionAndRotation(new Vector3(px, py, pz), new Quaternion(qx, qy, qz, qw));
@@ -1,24 +1,82 @@
1
1
  /**
2
2
  * bt-optimize export stats: compares exported .gltf scenes — drawn mesh nodes, meshes, primitives (draw calls before
3
- * LOD selection), materials, textures, drawn vertices and the size on disk of the .gltf plus its buffers.
3
+ * LOD selection), materials, textures, drawn vertices and the size on disk of the .gltf plus its buffers. Gzipped
4
+ * exports (`.gz.gltf` / `.gz.bin`, detected by their magic bytes, not their names) are read too; each buffer reports
5
+ * its size on disk and uncompressed.
4
6
  *
5
7
  * Usage:
6
- * node gltf-stats.mjs export/scenes/original.gltf export/scenes/combined.gltf
8
+ * node gltf-stats.mjs export/scenes/original.gltf export/scenes/combined.gz.gltf
7
9
  */
8
10
  import fs from "node:fs";
9
11
  import path from "node:path";
12
+ import zlib from "node:zlib";
10
13
 
11
14
  /** Bytes per megabyte, for readable sizes. */
12
15
  const BYTES_PER_MEGABYTE = 1024 * 1024;
13
16
 
17
+ /** The two bytes every gzip stream starts with. */
18
+ const GZIP_MAGIC = [0x1f, 0x8b];
19
+
20
+ /**
21
+ * Tells whether a file starts with the gzip magic bytes.
22
+ * @param {string} filePath - path of the file to test
23
+ * @returns {boolean} true when the file is a gzip stream
24
+ */
25
+ function isGzipFile(filePath) {
26
+ const header = Buffer.alloc(GZIP_MAGIC.length);
27
+ const descriptor = fs.openSync(filePath, "r");
28
+ try {
29
+ fs.readSync(descriptor, header, 0, header.length, 0);
30
+ } finally {
31
+ fs.closeSync(descriptor);
32
+ }
33
+ return header[0] === GZIP_MAGIC[0] && header[1] === GZIP_MAGIC[1];
34
+ }
35
+
36
+ /**
37
+ * Reads a .gltf file as JSON, gunzipping it first when it is gzipped.
38
+ * @param {string} gltfPath - path of the .gltf (or .gz.gltf) file
39
+ * @returns {object} the parsed glTF document
40
+ */
41
+ function readGltf(gltfPath) {
42
+ const raw = fs.readFileSync(gltfPath);
43
+ const text = isGzipFile(gltfPath) ? zlib.gunzipSync(raw) : raw;
44
+ return JSON.parse(text.toString("utf8"));
45
+ }
46
+
47
+ /**
48
+ * Measures one external buffer: its size on disk and uncompressed. A gzipped buffer's uncompressed size is the
49
+ * glTF's declared `byteLength` (what the loader gets after inflating it), so the file is never inflated here.
50
+ * @param {string} folder - folder of the .gltf the buffer belongs to
51
+ * @param {{uri: string, byteLength: number}} buffer - the glTF buffer entry
52
+ * @returns {{uri: string, gzipped: boolean, diskBytes: number, uncompressedBytes: number}} the buffer's sizes (0 when missing)
53
+ */
54
+ function measureBuffer(folder, buffer) {
55
+ const bufferPath = path.join(folder, decodeURIComponent(buffer.uri));
56
+ if (!fs.existsSync(bufferPath)) return { uri: buffer.uri, gzipped: false, diskBytes: 0, uncompressedBytes: 0 };
57
+ const diskBytes = fs.statSync(bufferPath).size;
58
+ const gzipped = isGzipFile(bufferPath);
59
+ return { uri: buffer.uri, gzipped, diskBytes, uncompressedBytes: gzipped ? buffer.byteLength : diskBytes };
60
+ }
61
+
62
+ /**
63
+ * Converts bytes to megabytes with two decimals.
64
+ * @param {number} bytes - a size in bytes
65
+ * @returns {number} the size in megabytes
66
+ */
67
+ function toMegabytes(bytes) {
68
+ return Number((bytes / BYTES_PER_MEGABYTE).toFixed(2));
69
+ }
70
+
14
71
  /**
15
72
  * Reads one exported scene and measures it.
16
- * @param {string} gltfPath - path of the .gltf file
17
- * @returns {{file: string, nodes: number, drawnMeshNodes: number, meshes: number, primitives: number, materials: number,
18
- * textures: number, drawnVertices: number, sizeMegabytes: number}} the measurements
73
+ * @param {string} gltfPath - path of the .gltf (or gzipped .gz.gltf) file
74
+ * @returns {{file: string, gzipped: boolean, nodes: number, drawnMeshNodes: number, meshes: number, primitives: number,
75
+ * materials: number, textures: number, drawnVertices: number, sizeMegabytes: number, binMegabytesOnDisk: number,
76
+ * binMegabytesUncompressed: number, buffers: object[]}} the measurements (`sizeMegabytes` is the .gltf plus its buffers on disk)
19
77
  */
20
78
  function measure(gltfPath) {
21
- const gltf = JSON.parse(fs.readFileSync(gltfPath, "utf8"));
79
+ const gltf = readGltf(gltfPath);
22
80
  const meshes = gltf.meshes || [];
23
81
  const accessors = gltf.accessors || [];
24
82
  const nodes = gltf.nodes || [];
@@ -29,15 +87,15 @@ function measure(gltfPath) {
29
87
  const drawnVertices = drawnNodes.reduce((total, node) => total + verticesPerMesh[node.mesh], 0);
30
88
 
31
89
  const folder = path.dirname(gltfPath);
32
- const bufferBytes = (gltf.buffers || [])
90
+ const buffers = (gltf.buffers || [])
33
91
  .filter((buffer) => buffer.uri && !buffer.uri.startsWith("data:"))
34
- .reduce((total, buffer) => {
35
- const bufferPath = path.join(folder, decodeURIComponent(buffer.uri));
36
- return total + (fs.existsSync(bufferPath) ? fs.statSync(bufferPath).size : 0);
37
- }, 0);
92
+ .map((buffer) => measureBuffer(folder, buffer));
93
+ const bufferDiskBytes = buffers.reduce((total, buffer) => total + buffer.diskBytes, 0);
94
+ const bufferUncompressedBytes = buffers.reduce((total, buffer) => total + buffer.uncompressedBytes, 0);
38
95
 
39
96
  return {
40
97
  file: path.basename(gltfPath),
98
+ gzipped: isGzipFile(gltfPath),
41
99
  nodes: nodes.length,
42
100
  drawnMeshNodes: drawnNodes.length,
43
101
  meshes: meshes.length,
@@ -45,13 +103,16 @@ function measure(gltfPath) {
45
103
  materials: (gltf.materials || []).length,
46
104
  textures: (gltf.textures || []).length,
47
105
  drawnVertices,
48
- sizeMegabytes: Number(((fs.statSync(gltfPath).size + bufferBytes) / BYTES_PER_MEGABYTE).toFixed(2)),
106
+ sizeMegabytes: toMegabytes(fs.statSync(gltfPath).size + bufferDiskBytes),
107
+ binMegabytesOnDisk: toMegabytes(bufferDiskBytes),
108
+ binMegabytesUncompressed: toMegabytes(bufferUncompressedBytes),
109
+ buffers,
49
110
  };
50
111
  }
51
112
 
52
113
  const files = process.argv.slice(2);
53
114
  if (files.length === 0) {
54
- process.stderr.write("Usage: node gltf-stats.mjs <scene.gltf> [more.gltf ...]\n");
115
+ process.stderr.write("Usage: node gltf-stats.mjs <scene.gltf | scene.gz.gltf> [more ...]\n");
55
116
  process.exit(1);
56
117
  }
57
118
  process.stdout.write(JSON.stringify(files.map(measure), null, 2) + "\n");
@@ -10,6 +10,10 @@
10
10
  * node profile-browser.mjs --scene optimized.gltf --poses ./before-pinned.json --toggles none (same views as an earlier run)
11
11
  * [--headed true] [--dpr 2] [--window 3] [--settle 4] [--shots ./shots] [--cpuprofile true] [--toggles none]
12
12
  * [--casters true] (with --pin / --poses: each pin also records every shadow map's casters per cascade, `shadowCasters`)
13
+ * [--hold 40:24,60:44 | --hold true] (with --pin / --poses: holds the scene's Timeline still at each pin — pin seconds :
14
+ * director seconds, or `true` for wherever the director is when the pin lands; a pose file's `heldTimeline` is used
15
+ * for any pin the list does not name. Each pin records `heldTimeline` (null when the scene has no director) and
16
+ * fails when the director strays more than HOLD_TOLERANCE_SECONDS during the measure window.)
13
17
  */
14
18
  import fs from "node:fs";
15
19
  import os from "node:os";
@@ -25,6 +29,9 @@ const DEFAULT_WINDOW_SECONDS = 3;
25
29
  /** How long to wait for the scene to finish loading, in milliseconds. */
26
30
  const READY_TIMEOUT_MS = 600000;
27
31
 
32
+ /** How far a held Timeline may stray during a pin's measure window before that pin fails, in seconds. */
33
+ const HOLD_TOLERANCE_SECONDS = 0.05;
34
+
28
35
  /**
29
36
  * Reads `--name value` pairs from the command line.
30
37
  * @param {string[]} argv - process.argv.slice(2)
@@ -256,6 +263,40 @@ function installProbe() {
256
263
  return pose;
257
264
  };
258
265
 
266
+ /**
267
+ * Holds the scene's Timeline still: pauses its PlayableDirector, moves it to the given time and poses every track
268
+ * there, so the sun's angle, the active light and the shot on screen stop changing while a pin is measured.
269
+ * @param {number|null} timelineSeconds - director time to hold, in seconds; null holds the director's current time
270
+ * @returns {number|null} the held director time in seconds, or null (and nothing done) when the scene has no director
271
+ */
272
+ state.holdTimeline = (timelineSeconds) => {
273
+ const director = state.director();
274
+ if (!director) return null;
275
+ director.pause();
276
+ if (timelineSeconds != null) director.time = timelineSeconds;
277
+ director.evaluate();
278
+ return director.time;
279
+ };
280
+
281
+ /**
282
+ * The scene's Timeline director, when it has one.
283
+ * @returns {object|null} the toolkit PlayableDirector, or null when the scene has none (or the runtime has no Timeline)
284
+ */
285
+ state.director = () => {
286
+ const directorClass = window.TOOLKIT && TOOLKIT.PlayableDirector;
287
+ if (!directorClass || typeof directorClass.Find !== "function") return null;
288
+ return directorClass.Find(state.scene()) || null;
289
+ };
290
+
291
+ /**
292
+ * The director's current time, to prove a held Timeline did not move.
293
+ * @returns {number|null} seconds, or null when the scene has no director
294
+ */
295
+ state.directorTime = () => {
296
+ const director = state.director();
297
+ return director ? director.time : null;
298
+ };
299
+
259
300
  /**
260
301
  * Splits each frame's draw calls by pass, read from the engine's running draw counter: shadow maps, other render
261
302
  * targets before the main pass (geometry / velocity buffers for motion blur, TAA, SSAO; realtime probes), the main
@@ -876,6 +917,63 @@ async function cpuProfile(page, seconds) {
876
917
  return { totalMs: Math.round(totalMs), top };
877
918
  }
878
919
 
920
+ /**
921
+ * Reads `--hold` into a per-pin plan. `--hold true` holds every pin where the director is when the pin lands;
922
+ * `--hold 40:24,60:44` holds the named pins at those director seconds; a pose file's `heldTimeline` fills any pin the
923
+ * flag does not name (so replaying a held run's output holds the same moments). `--hold false` turns holding off.
924
+ * @param {string|undefined} holdFlag - the raw `--hold` value
925
+ * @param {{atSeconds: number, heldTimeline?: number|null}[]|null} poses - the `--poses` entries, when given
926
+ * @returns {{timeFor: (pinSeconds: number) => {hold: boolean, timelineSeconds: number|null}}} the plan
927
+ * @throws {Error} when a `--hold` entry is not `pin:seconds`
928
+ */
929
+ function parseHoldPlan(holdFlag, poses) {
930
+ const holdAll = holdFlag === "true";
931
+ const holdOff = holdFlag === "false";
932
+ const explicitTimes = new Map();
933
+ if (holdFlag && !holdAll && !holdOff) {
934
+ for (const entry of holdFlag.split(",").filter(Boolean)) {
935
+ const [pinSeconds, timelineSeconds] = entry.split(":").map(Number);
936
+ if (!Number.isFinite(pinSeconds) || !Number.isFinite(timelineSeconds)) throw new Error(`--hold entry "${entry}" is not pin:seconds (e.g. --hold 40:24,60:44)`);
937
+ explicitTimes.set(pinSeconds, timelineSeconds);
938
+ }
939
+ }
940
+ const poseFileTimes = new Map((poses || []).filter((entry) => entry.heldTimeline != null).map((entry) => [entry.atSeconds, entry.heldTimeline]));
941
+ return {
942
+ timeFor(pinSeconds) {
943
+ if (holdOff) return { hold: false, timelineSeconds: null };
944
+ if (explicitTimes.has(pinSeconds)) return { hold: true, timelineSeconds: explicitTimes.get(pinSeconds) };
945
+ if (poseFileTimes.has(pinSeconds)) return { hold: true, timelineSeconds: poseFileTimes.get(pinSeconds) };
946
+ return { hold: holdAll, timelineSeconds: null };
947
+ },
948
+ };
949
+ }
950
+
951
+ /**
952
+ * Holds the page's Timeline at a time (or where it is, for null).
953
+ * @param {object} page - the puppeteer page
954
+ * @param {number|null} timelineSeconds - director seconds to hold, or null for the current time
955
+ * @returns {Promise<number|null>} the held time, or null when the scene has no director
956
+ */
957
+ async function holdTimeline(page, timelineSeconds) {
958
+ const held = await page.evaluate((seconds) => window.__btProfile.holdTimeline(seconds), timelineSeconds);
959
+ return held == null ? null : +held.toFixed(4);
960
+ }
961
+
962
+ /**
963
+ * Re-reads the director after a measure window and refuses the window when the held Timeline moved, mirroring the
964
+ * look tests' held shots: a moved Timeline means the sun, the light or the shot changed while the frame was measured.
965
+ * @param {object} page - the puppeteer page
966
+ * @param {number|null} heldTimeline - the held time, or null when the scene has no director
967
+ * @returns {Promise<{timeAfterWindow: number|null, driftSeconds: number, error?: string}>} the check
968
+ */
969
+ async function checkHold(page, heldTimeline) {
970
+ const timeAfterWindow = await page.evaluate(() => window.__btProfile.directorTime());
971
+ if (heldTimeline == null || timeAfterWindow == null) return { timeAfterWindow, driftSeconds: 0 };
972
+ const driftSeconds = +Math.abs(timeAfterWindow - heldTimeline).toFixed(4);
973
+ if (driftSeconds <= HOLD_TOLERANCE_SECONDS) return { timeAfterWindow, driftSeconds };
974
+ return { timeAfterWindow, driftSeconds, error: `Timeline drifted: held ${heldTimeline} s, ${timeAfterWindow} s after the window` };
975
+ }
976
+
879
977
  /** Records one measurement window on the page. */
880
978
  async function measure(page, windowSeconds) {
881
979
  await page.evaluate(() => window.__btProfile.start());
@@ -895,8 +993,10 @@ async function main() {
895
993
  const scene = flags.scene;
896
994
  if (!scene) throw new Error("Pass --scene <exported scene file>, e.g. --scene level.gltf");
897
995
  const times = (flags.times || DEFAULT_TIMES).split(",").map(Number).sort((first, second) => first - second);
898
- const poses = flags.poses ? JSON.parse(fs.readFileSync(path.resolve(flags.poses), "utf8")).pins.map((pin) => ({ atSeconds: pin.atSeconds, pose: pin.pinned })) : null;
996
+ const poses = flags.poses ? JSON.parse(fs.readFileSync(path.resolve(flags.poses), "utf8")).pins.map((pin) => ({ atSeconds: pin.atSeconds, pose: pin.pinned, heldTimeline: pin.heldTimeline })) : null;
899
997
  const pins = poses ? poses.map((entry) => entry.atSeconds) : (flags.pin || "").split(",").filter(Boolean).map(Number);
998
+ const holdPlan = parseHoldPlan(flags.hold, poses);
999
+ let failedPins = 0;
900
1000
  const toggles = (flags.toggles || "dpr,taa,motionblur,bloom,post,shadows,lights").split(",").filter((key) => key && key !== "none");
901
1001
  const windowSeconds = Number(flags.window || DEFAULT_WINDOW_SECONDS);
902
1002
  const settleSeconds = Number(flags.settle || 4);
@@ -938,11 +1038,20 @@ async function main() {
938
1038
  await sleep(seconds);
939
1039
  // With --poses, the camera goes to the exact pose an earlier run pinned, so two exports are measured from one view.
940
1040
  const pinned = poses ? await page.evaluate((pose) => window.__btProfile.pose(pose), poses[index].pose) : await page.evaluate(() => window.__btProfile.pin());
1041
+ const holdRequest = holdPlan.timeFor(seconds);
1042
+ let heldTimeline = holdRequest.hold ? await holdTimeline(page, holdRequest.timelineSeconds) : undefined;
941
1043
  await settle(page, settleSeconds);
1044
+ // Settling waits on whenReadyAsync, which can let a director resume, so the hold is applied again.
1045
+ if (holdRequest.hold) heldTimeline = await holdTimeline(page, heldTimeline);
942
1046
  if (shots) await page.screenshot({ path: path.join(shots, `${tag}_pin${seconds}s.png`) });
943
1047
  const poseBefore = await page.evaluate(() => window.__btProfile.actualPose());
944
1048
  const baseline = await measure(page, windowSeconds);
945
1049
  const poseAfter = await page.evaluate(() => window.__btProfile.actualPose());
1050
+ const holdCheck = holdRequest.hold ? await checkHold(page, heldTimeline) : null;
1051
+ if (holdCheck && holdCheck.error) {
1052
+ failedPins++;
1053
+ process.stderr.write(`FAILED pin ${seconds}s: ${holdCheck.error}\n`);
1054
+ }
946
1055
  const target = pinned.position || pinned;
947
1056
  const drift = Math.max(...[poseBefore, poseAfter].map((actual) => Math.hypot(actual.position[0] - target[0], actual.position[1] - target[1], actual.position[2] - target[2])));
948
1057
  if (drift > 0.05 || (pinned.fov != null && Math.abs(poseAfter.fov - pinned.fov) > 1e-3) || poseBefore.camera !== poseAfter.camera)
@@ -962,7 +1071,7 @@ async function main() {
962
1071
  steps.push({ off: key, change, fps: off.fps, p50Ms: off.p50Ms, drawCalls: off.drawCalls, passes: off.passes, cpuRenderMs: off.cpuRenderMs, cpuFrameMs: off.cpuFrameMs });
963
1072
  }
964
1073
  const after = await measure(page, windowSeconds);
965
- report.pins.push({ atSeconds: seconds, readyMs, pinned, actual: { before: poseBefore, after: poseAfter }, baseline, lightAudit, drawOwners, shadowCasters, cpu, steps, baselineAgain: { fps: after.fps, p50Ms: after.p50Ms } });
1074
+ report.pins.push({ atSeconds: seconds, readyMs, pinned, heldTimeline, holdCheck, actual: { before: poseBefore, after: poseAfter }, baseline, lightAudit, drawOwners, shadowCasters, cpu, steps, baselineAgain: { fps: after.fps, p50Ms: after.p50Ms } });
966
1075
  await page.close();
967
1076
  }
968
1077
  }
@@ -970,6 +1079,7 @@ async function main() {
970
1079
  const text = JSON.stringify(report, null, 2);
971
1080
  if (flags.out) fs.writeFileSync(path.resolve(flags.out), text);
972
1081
  process.stdout.write(text + "\n");
1082
+ if (failedPins > 0) throw new Error(`${failedPins} pin(s) failed: the held Timeline moved during the measure window`);
973
1083
  } finally {
974
1084
  await browser.close();
975
1085
  }