Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
Draw optimization: scene-kit merges, cached shadows and stand-ins across the three scenes (#131)
Matthew Kissingerb1ac6ee210e2
diff --git a/docs/plans/2026-10-01-draw-optimization-cycle.md b/docs/plans/2026-10-01-draw-optimization-cycle.mdnew file mode 100644index 00000000..62d78b16--- /dev/null+++ b/docs/plans/2026-10-01-draw-optimization-cycle.md@@ -0,0 +1,316 @@+# Draw-call and frame-time optimization cycle: plan of record++Status: waiting for the owner to pass the goal statement at the end of this file. Nothing is implemented,+committed or timed until then. Written 2026-10-01 22:20 -04:00.++## Purpose++Make Kiln's scenes cheaper to render without losing their look, starting with the shadow pass and the+hazards the research found. This serves every scene (Farm, Foundry Floor, Golden Gate), not only the+Farm. It must also produce a report that feeds back into the tooling, skills and project conventions+for authoring scenes and assets.++## Inputs++- Research report (24-agent sweep with verification, repo map and experiments):+ `tmp/drawcalls/research/asset-optimization-frontier.md`. This file is gitignored and copied from the+ main checkout. Its section 3 ranks the levers and section 8 is the roadmap; this cycle is its Phases 0 and 1.+- Measured Farm baseline (desktop RTX, headless Chrome, 1920x1080, high tier, PC under load, indicative):+ - 583 draws per frame: 270 in the 2048² sun shadow pass and 313 in the main pass.+ - About 2.3M triangles per frame and about 6.3 ms per frame.+ - 14 hero placements hold 195 meshes, which account for about 390 of the 583 draws.+ - What-if tests:++ | Variant | Draws per frame | Frame time |+ |---|---|---|+ | Shadow frozen | ~313 | 4.3 ms |+ | Heroes hidden | ~188 | 3.5 ms |+ | Casters under 300 triangles off | ~378 | 5.4 ms |+- Tablet (Galaxy Tab S9 FE), economy tier, from the research follow-up:+ - The GPU is the limit, with an unlocked frame of 24.9 ms.+ - Shares of that frame: vegetation ~37%, 4x MSAA ~21%, shadow pass ~12%, heroes 0.9 ms.+ - p95 is 33.6 ms against the 33.3 ms rule.+- Count snapshots of the other scenes (2026-10-01 22:40; built standalones in `scenes/.cache/site-inputs`;+ headless 1920x1080; one camera each; counts only; scratch probe `tmp/drawcalls/scene-snapshot.mjs`,+ ignored, local only):++ | Scene and view | Draws per frame | Per pass | Triangles | Notes |+ |---|---|---|---|---|+ | Golden Gate overview | 432 | shadow 74, main (MSAA 4x) 179, planar water reflection at half resolution 178 | 1.54M | No instancing; bridge has 165 meshes (150 cast); terrain 464k triangles |+ | Golden Gate "Drive the sedan" | 410 | shadow 148, main 133, reflection 128 | 1.69M | Traffic is 13 meshes |+ | Foundry Floor campus | 102 | main 101, no shadows | 137k | 17 instanced meshes |+ | Foundry Floor fab ("Enter the fab") | 129 | main 128, no shadows | 205k | Already merged per (class, part, LOD), with detail and lod pairs; 21 transparent meshes |++ Each scene has a different dominant cost:+ - **Farm:** the shadow pass and its 14 moving hero objects.+ - **Golden Gate:** three full scene passes, of which the water reflection is a second extra pass.+ - **Foundry Floor:** already lean. It is the reference pattern (anchor bake) and the control scene.+- Confirmed hazard: `consolidateMaterials` in `src/render.ts:1451-1489`.+ - With `mode:'full'` it runs `flatten()` and then `join({keepNamed:true})`.+ - Every Kiln node is named, so the join merges nothing.+ - Flatten moves the farmhouse door out from under `Joint_FrontDoor`, and that pivot is then pruned.+ - Result: 16 → 16 draws, and the pivot is lost.++## Owner decisions (2026-10-01, about 22:00-22:18 -04:00)++| Id | Decision |+|---|---|+| OD-1 | Work in a new worktree off `main`: `C:/Users/Mattm/X/kiln-draw-optimization`, branch `draw-optimization`. Scene work goes ahead now; it does not overlap `v1-readiness`, which changes no file under `scenes/`. Model-facing engine changes (tool output, authoring and QA skills) wait until `v1-readiness` merges, then rebase. |+| OD-2 | This cycle covers Phases 0-1 of the research roadmap, then stops and reports. Owner note: the work is for **all scenes**, and its findings must feed a report that upgrades or aligns the tooling, projects and skills for authoring scenes. |+| OD-3 | Success measure: frame time first, with draw count also reported as a headline metric ("a metric that a lot of devs look at"). This PC is often under load, so timing must come from clean data. |+| OD-4 | Look: **small shadow changes are OK**. Tiny parts may stop casting, and stand-in shadow outlines may differ slightly. Everything else stays at parity (D-20 baseline). |+| OD-5 | Measurement: count metrics (draws, triangles, pipelines, CPU draw-call counts) may run anytime on this PC. Timing comes only from quiet hosts, with interleaved before/after (A/B/A/B) runs. |+| OD-6 | Tablet: the coordinator may schedule tablet timing runs. Use the device kit, only while the tablet is quiet and cool, and remove port mappings after each run. |+| OD-7 | The tablet rule stays p95 ≤ 33.3 ms. Also report the share of frames within one and within two display refreshes, so a restatement can be decided with data. |+| OD-8 | X-02 (draws and triangles within 2% of the sealed pilot at high) is re-baselined on the optimized build. Pixel parity against the pilot remains. |+| OD-9 | Moving objects: a cached static sun shadow plus a small live map for movers, with both sampled. |+| OD-10 | MSAA store-op: first confirm it is a real issue, with an adversarial review. If confirmed, implement an elegant solution and make a **private** artifact covering the issue, how it was found and what a fix would be. Never open a three.js issue or PR. Owner's words: "i don't want to slop spam AI generated PRs or issues for three.js". |+| OD-11 | The shadow work applies to all three scenes: Farm, Foundry Floor and Golden Gate. |+| OD-12 | The tablet stays on the minimal tier (D-25). Bring economy before/after numbers; any tier change is the owner's call. |+| OD-13 | Commit locally on `draw-optimization` in logical steps. No push. Push and PR are decided by the owner afterwards. |+| OD-14 | No changes to `site/` and no deployment. Scene builds and staging happen only inside the worktree. |+| OD-15 | End report: a private artifact page (per-scene before/after, quiet-host timing, parity images, open decisions, feedback map), plus a dated `docs/reviews/` record on the branch. |+| OD-16 | Feedback is applied now to `skills/kiln-compose-scene/` and its runtime-scenes reference, which `v1-readiness` does not touch. Authoring and QA skill changes, tool-output changes and project-convention changes are written as proposals in the report. |+| OD-17 | (22:35) Analyse and implement across **all** scenes, not only the Farm. Testing Foundry Floor and Golden Gate (robots, cars) gives more useful perf data and a better feedback loop for judging whether the approach is right. |+| OD-18 | (22:45) Beyond Phases 0-1, also implement the scene-side merges that each scene's diagnosis proves look-neutral, in scene-kit and scene code only, with no engine changes. Examples: Golden Gate bridge parts merged by material; a Foundry-style anchor merge for the Farm's moving heroes, with each moving group kept separate. Stand-ins cover every extra pass: the shadow pass and Golden Gate's planar reflection. |++## Defaults set by the coordinator (owner may edit)++- **Pivot fix (Phase 0).** `optimize:'full'` merges primitives by material only within rigid groups. Boundaries are:+ - nodes targeted by animations;+ - `Joint_*` pivots;+ - nodes carrying Kiln semantic extras;+ - LOD and node-visibility nodes.++ `off` and `palette` outputs stay byte-identical. Proof uses the farmhouse: `Joint_FrontDoor` is kept, draws are ≤ 11, and triangles and world bounds are equal.+- **Extension compatibility check (Phase 0).** A library function, with tests, that flags extensions marked required against per-destination allowlists (Godot, Bevy, Blender, Unity glTFast, three). It adds no new tool output or schema, because that is model-facing (OD-1). How to surface it is proposed in the report.+- **Count probe.** A committed scenes script that builds each scene in test mode and records, per tier and named view:+ - draws per render pass (by instrumenting the WebGPU encoder);+ - pipelines and triangles.++ It uses the kit's existing test hooks instead of the ad-hoc React-devtools probe used in research.+- **Parity.** Reuse the existing B-06 parity tooling and thresholds per scene. Any shadow difference beyond the thresholds is captured as before/after images and listed for owner review under OD-4.+- **Timing hosts and rules:**+ - **Hub:** headed, 120 Hz, quiet check over SSH recorded beside each result.+ - **Tablet:** device kit, quiet and cool.+ - **This PC:** only when the kit's quiet check passes (CPU < 20%, GPU < 10%), and labelled indicative otherwise.+ - Results go under `scenes/evidence/perf/<host>-<date>/`, which is ignored; summaries go into the report.+- **Inputs.** Copy the ignored scene inputs (`scenes/.cache/site-inputs`, `scenes/packages/*/staged`, `scenes/packages/scene-kit/demo/staged`) read-only from the main checkout. Never write to the main checkout.+- **Toolchain.** Run `bun install --frozen-lockfile` at the root and in `scenes/`, then `node scripts/build-runtime.mjs all`. Run `bun run check:toolchain` first. This PC has Node 24.20.0 while the maintainer pin is 22.23.2; record what the check says and stop if it blocks a gate.+- **Process.**+ - Strict TDD for behaviour changes.+ - Opus orchestrates; Sonnet 5.5 subagents handle well-specified implementation.+ - An independent agent adversarially reviews each lever and the MSAA claim.+- **No live model runs.** No model-visible output changes this cycle, so no dogfood runs.+- **Decision record.** OD-1..OD-18 and the X-02 re-baseline are recorded as D-46 onward in `scenes/DECISIONS.md` in the branch.++## Boundaries++- Never edit, stash, switch branches or clean in `C:/Users/Mattm/X/kiln-oss` (main checkout) or `C:/Users/Mattm/X/kiln-v1-readiness`.+- Do not edit files that `v1-readiness` changes. Check with `git -C ../kiln-v1-readiness diff --name-only main...v1-readiness`. Typical ones:+ - `src/tools/*`+ - `src/tools/review-detail.ts`+ - `skills/kiln-author-asset/*`+ - `skills/kiln-qa-asset/*`+ - the export-profiles references+ - the setup skills+- `src/render.ts` is touched there by 24 lines. Keep the Phase 0 edit inside `consolidateMaterials` and nearby helpers, and note the overlap in the report.+- Never push, never touch `site/`, never deploy, never post upstream, never spend money.++## Steps++**S0. Provision**+- Install, build the runtime and copy the inputs.+- Run the engine gates (`bun run typecheck`, `lint`, `test`, `test:render-service`, `test:coverage`) and the scenes gates (`bun run typecheck`, `lint`, `test` in `scenes/`) to confirm a green baseline.+- Record anything already red as pre-existing.++**S1. Per-scene diagnosis (OD-17)**+- Turn the scratch probe into a committed scenes script.+- For Farm, Foundry Floor and Golden Gate, at every tier, run every named view and workload rather than only the landing camera:+ - Farm: overview, walk, tractor drive.+ - Foundry Floor: campus, the fab, One pair, Arrival, The split, the sedan drive.+ - Golden Gate: overview, the sedan drive, flyovers, golden hour, fog.+- For each, record:+ - draws per pass;+ - pipelines;+ - triangles;+ - attribution by system and asset;+ - count-only what-if toggles (hide a system, freeze shadow, freeze reflection, drop small casters).+- Then rank each scene's levers from its own data.+- Foundry Floor is the control scene and the reference pattern (anchor bake, LOD pairs). Record what it does that the others should borrow.++**S2. Phase 0 engine**+- Pivot fix by TDD.+- Extension compatibility check by TDD.+- Commit.++**S3. MSAA investigation (OD-10)**+- Read the three r186 WebGPU backend source for render-pass store ops on multisampled colour and depth when a resolve target exists.+- Count encoder store/discard ops in the Farm.+- Measure on the tablet only within OD-6.+- An independent agent tries to refute the claim.+- If confirmed: implement in scene-kit through the narrowest stable surface, with a test that fails loudly if three changes; make the private artifact; commit.+- If refuted: record why and drop it.++**S4. scene-kit shadow features, by TDD**+1. Shadow-layer stand-ins: material-free merged depth meshes per rigid group, with source meshes excluded from the shadow pass.+2. A cached static shadow map plus a small live mover map, sampled together. It must handle the first-frame `needsUpdate` hazard and never share one light between two shadow nodes.+3. A texel-size small-caster threshold.++Each is a kit option, off by default. Commit.++**S4b. Extra-pass stand-ins and look-neutral scene merges (OD-18), by TDD**+- Generalise the shadow stand-ins to any extra pass. Golden Gate's planar water reflection draws stand-ins, or only large silhouettes, instead of the full scene; its update cadence is only reduced if parity holds.+- Scene-side merges proven look-neutral by S1:+ - Golden Gate bridge parts merged by material.+ - Farm heroes merged Foundry-style per anchor and material, with every moving group (doors, wheels, limbs, gates) kept as its own node so colliders, doors and the frame graph keep working.+- Each merge keeps per-object interaction intact and passes B-06.+- Foundry Floor gets no new shadows, since that would change its look. It receives the MSAA fix if S3 confirms it, plus counts and timing.++**S5. Enable per scene**+- Turn the features on in Farm, Foundry Floor and Golden Gate (Golden Gate already moves its shadow with the focus; integrate rather than replace).+- Build standalones in the worktree.+- Run the count probe and B-06 parity per scene.+- Show any shadow differences as images.+- Commit.++**S6. Timing (OD-3, OD-5, OD-6, OD-7)**+- Interleaved A/B on quiet hosts per scene and tier.+- Report p50/p95, the refresh-share view, hitch-rule counts (D-41) and load samples.+- Measure tablet economy before/after (OD-12).+- If no quiet window opens, list the pending runs with their exact commands.++**S7. Feedback (OD-16)**+- Update `skills/kiln-compose-scene/` and its runtime-scenes reference with the proven techniques and their measured effect. Run `bun run check:skills`.+- Record the X-02 re-baseline and OD-1..OD-18 as D-46 onward.++**S8. Report (OD-15)**+- Write `docs/reviews/2026-10-0X-draw-optimization.md`:+ - per-scene before/after, timing and parity;+ - a cross-scene comparison: which lever worked where, which did not, and why;+ - a feedback map of proposed changes (engine tools, authoring/QA skills, scene-kit, project conventions) with evidence.+- Publish a private artifact page with the same content.+- Run the final gates in both workspaces.+- Commit.+- Stop.++## Progress log++The `tmp/` and `scenes/evidence/` paths cited in this log are ignored and local only.++- 2026-10-01 22:20: Worktree created at `c734e2a` (main = origin/main). Plan written. Waiting for the goal.+- 2026-10-01 22:50: OD-17 and OD-18 added after count snapshots of Golden Gate and Foundry Floor. S1 widened to a per-scene diagnosis; S4b added. Goal statement updated.+- 2026-10-01 23:00: Goal passed; cycle started.+- S0 toolchain and install: `check:toolchain` passes (metadata Bun 1.4.2, Node 22.23.2, npm 12.0.2; this PC runs Node 24.20.0). Root install took 249 packages and `scenes/` took 73. `node scripts/build-runtime.mjs all` rebuilt `dist/` byte-identical (no git diff).+- S0 inputs: copied read-only from the main checkout:+ - `scenes/.cache/site-inputs`: 246 files+ - `foundry-floor/staged`: 87 files+ - `golden-gate/staged`: 105 files+ - `scene-kit/demo/staged`: 7 files+- S0 scenes gates: typecheck, lint and test are green (378 pass, 22 skip, 0 fail).+- S0 engine gates: all green.+ - typecheck and lint pass.+ - test: 3,042 pass, 2 skip, 0 fail.+ - test:render-service: 78/78.+ - test:coverage: functions 95.22% (minimum 94.00%), lines 92.48% (minimum 92.10%).+- S1-S4 code maps launched (read-only workflow): probe infra, shadow internals, Farm, Golden Gate, Foundry, MSAA, engine Phase 0.+- 23:25: Code maps done; the MSAA, shadow and engine maps were also reviewed adversarially. Files are in `tmp/drawcalls/understand/`.++ **MSAA:** confirmed with a narrower scope. three r186 always stores the 4x colour and depth of the canvas frame-buffer target. That is wasted where the main pass is never split (Farm, Foundry Floor, Golden Gate low tiers) and required where `viewportDepthTexture` splits it (Golden Gate medium and high). It is a conservative default, not a three.js bug. Use the corrected design with trip-wires.++ **Shadows:**+ - Combine the two maps with `min` rather than `mul` (exact at shadow intensity below 1).+ - Classify movers per node from observed motion, not per frame-graph root.+ - Build stand-ins before freezing transforms.+ - Re-arm the static map at reveal.+ - Pin tests against `build/three.webgpu.js`.++ **Golden Gate:**+ - The shadow map renders twice per frame (the reflector's camera triggers a second render). Rendering it once per frame is look-neutral.+ - The reflection draws traffic and fog banks, against its own spec. Fixing that changes pixels: **owner decision, not applied.**+ - The texel-snapped shadow camera moves on almost every drive frame, so S is re-rendered by fit key.++ **Engine:**+ - Editing `src/render.ts` forces a `dist/` rebuild, which `src/__tests__/mcp-bundle.test.ts` checks byte for byte. `dist/*` are v1-readiness files.+ - **Stop rule:** the `optimize:'full'` wiring is held for an owner decision. Phase 0 ships as new unbundled modules: `src/rigid-merge.ts` and `src/extension-compat.ts`.+ - The merge must handle tangents itself (gltf-transform's helper corrupts rotated ones), lock BLEND materials, and treat relationship targets as boundaries.+- 23:29: Wave A launched: S1 probe and baseline diagnosis, S2 engine modules, S3 MSAA policy. Each is adversarially reviewed and fixed.+- 2026-10-02 00:19, S2 tangent deviation (reviewer accepted): `mergeMirroredTangents` defaults to false. The spec's unconditional `w *= sign(det)` would flip three's bitangents on mirrored normal-mapped parts. three r186 builds the bitangent as `cross(N, T) * w` with no determinant term: `src/renderers/shaders/ShaderChunk/normal_vertex.glsl.js:9-15` negates it only under `FLIP_SIDED`, and `src/nodes/accessors/Bitangent.js:18,58` matches. So by default a tangent-bearing primitive joins only parts of the same world handedness, which both renderer conventions draw the same way. The opt-in applies the spec's rule.+- 2026-10-02 01:03-01:06: Wave A committed after review and fixes.+ - `417da63`, S1 probe. 204 fixtures, all stable. GPU draws equal JS draws everywhere, and every what-if restores its baseline. Baseline is `scenes/evidence/counts/draw-base/`.+ - `e72b610`, S2 modules: `src/rigid-merge.ts` and `src/extension-compat.ts`.+ - farmhouse: 16 → 11 draws; `Joint_FrontDoor` keeps 2 primitives and 132 triangles; triangles equal at 4,080; bounds drift 0; validator 0/0.+ - The test failed first: `rigid-merge.red.log`, expected 11, received 16.+ - The `optimize:'full'` wiring is held for the owner; the patch is in `tmp/drawcalls/phase0/wiring.patch`.+ - `ced34bb`, S3 MSAA discard knob.+ - Browser: 190 frames with discard active, 0 errors.+ - Golden Gate balanced/high fail loudly when discard is forced.+ - Pixel diff within noise; B-06 144/144.+ - Mutation tests: 14/14 caught.+ - Hygiene on the three `wavea` public builds: 12 files, 0 hits.+ - Private page: private report page (owner).+ - Scenes gates on the combined tree: typecheck, lint 0, test 433 pass / 22 skip / 0 fail.+- 01:35: Wave B launched (workflow): kit rigid merge, kit shadow cache/once/threshold, kit stand-ins, then Farm and Golden Gate wiring, with Foundry planting in parallel. The S6 timing kit was built in parallel. Owner decisions recorded as D-46 to D-63 (`57177cf`). The probe gained `--query` (`5042a16`).+- 02:13, S6 timing kit committed (`67cafa4`). MSAA-only A/B, `draw-base` against `wavea`: 60 s runs, 3 interleaved pairs, quiet checks recorded. Evidence is in `scenes/evidence/perf/{hub,tablet}-2026-10-02/`.+ - **Hub** (GTX 1660 Ti, 120 Hz): no measurable effect. p50/p95 8.3/8.4 ms both sides; GPU busy unchanged; D-41 pass 18/18.+ - **Tablet** (Mali-G68, 60 Hz):+ - Farm minimal: GPU busy 93% → 85%.+ - Golden Gate minimal: GPU busy 85% → 82%.+ - Farm economy: within one refresh 39.9% → 48.8%, 37.5 → 39.8 fps; p95 33.3 ms on both sides.+ - three r186 makes the 4x attachments transient when the store flags are false, and the tablet supports `TRANSIENT_ATTACHMENT`.+ - This PC was not quiet (CPU 81.5%, GPU 27%), so it was not used for timing.+- 02:30: Wave B built and committed. Scenes gates on the combined tree: typecheck, lint 0, test 513 pass / 22 skip / 0 fail.+ - `2bd021e` kit rigid merge.+ - `0806baa` kit shadows: cache, once, threshold, stand-ins, pass stand-ins.+ - `95996dc` Foundry planting:+ - campus 101 → 95 draws, 21 → 10 pipelines;+ - near views −18 to −25 draws, about −30 pipelines;+ - B-06 22/22.+ - `1c4ae4f` Farm:+ - settled hero view at economy, balanced and high: 583 → 283 (shadow 270 → 0 per frame; the live map holds 31-54 draws with ambient life);+ - minimal: 345 → 315;+ - B-06 144/144 on 3 views at high.+ - `d2d1cfd` Golden Gate:+ - arrival at high: 432 → 103; at minimal: 180 → 52;+ - B-06 37/37;+ - the opt-in cache stays off because it gains nothing while driving.+- 02:38: Wave B review launched (workflow). Kit, Farm, and Golden Gate plus Foundry each get an adversarial reviewer; fixes follow, kit first.+- 04:18: Review done and fixed.+ - Commits: `8d95fec` (kit), `0174e7d` (Farm), `892d103` (Golden Gate and Foundry).+ - One major finding: Golden Gate's kerb stipple, a coplanar depth tie the merge reordered, missed by B-06. Fixed at no draw cost, and parity gained a thin-line budget (pixels over 32 levels).+ - Kit guards: shadow mask, late install, drift tolerance and untrack. The Farm adopts `layout:'source'`, which saves 2-3 pipelines.+- 05:10: S5 done. Commits `4383a1a`, `dc77f27`, `bf4b2dd`; D-64 `75751ec`.+ - Cross-build parity: Farm 86/86, Golden Gate 488/489 (golden-hour side-full, 193 px tower depth tie, held for the owner), Foundry 160/160.+ Correction (2 October): 488/489 is too high. S5's parity run covered golden side-full only at high on WebGPU; the view also fails at economy and balanced (193 px) and on High WebGL2 (200 px).+ - X-02 re-baselined per scene.+- 05:12-05:45: Final engine gates green: test 3,070/2/0, render-service 78/78, coverage functions 95.28% and lines 92.55%, check:skills.+- 07:15: S6 done (`69f92fe` fixes the timing probe). 196/198 runs valid.+ - **Tablet:**+ - Minimal holds 60 Hz in both builds, with GPU busy −2 to −9 points.+ - Economy: within one refresh 39.9 → 61.2% (Farm hero), 39.0 → 81.9% (tractor drive), 86.4 → 97.9% (Golden Gate). The tractor drive's p95 goes from 33.4 ms (over OD-7) to 33.3 ms.+ - **Hub:** vsync-locked at 8.3/8.4 ms in both builds. CPU render 5.5 → 1.6 ms on the Farm hero at high. D-41 131/132; the one failure is a flyover hitch shared by both builds.+ - **Pending:** the remaining hub balanced/economy cells; commands are in `tmp/drawcalls/s6/timing-full.report.md`.+- 07:25: S7/S8.+ - Scenes gates green: test 533/22/0, scripts 58/58.+ - Review record `docs/reviews/2026-10-02-draw-optimization.md`.+ - Private report page (owner).+ - The skill gains the measured frame-time effect.++## Goal statement++<!-- goal:start -->+Run the draw-optimization cycle in docs/plans/2026-10-01-draw-optimization-cycle.md inside the worktree C:/Users/Mattm/X/kiln-draw-optimization (branch draw-optimization), following owner decisions OD-1..OD-18 and the plan's defaults and boundaries, across all scenes (Farm, Foundry Floor, Golden Gate). Never edit, stash, switch or clean C:/Users/Mattm/X/kiln-oss or C:/Users/Mattm/X/kiln-v1-readiness; never edit files the v1-readiness branch changes; never touch site/, deploy, push, post upstream, run live models or spend money. Commit locally in logical steps.++Done when each item is shown by printed output in this conversation:+1. Diagnosis: a committed count probe gives, per scene, tier and named view or workload, draws per pass, pipelines, triangles, attribution by system and count-only what-ifs, with each scene's levers ranked from its own data.+2. Phase 0: a test that failed first and now passes proves optimize:'full' keeps Joint_* pivots and semantic nodes and merges by material within rigid groups (farmhouse.glb keeps Joint_FrontDoor, draws <= 11, triangles and bounds equal); a required-extension compatibility check has tests.+3. MSAA: an adversarial verdict, confirmed or refuted, on whether three r186 stores multisampled attachments needlessly; if confirmed, a scene-kit implementation with a test and a private artifact page (issue, how found, fix); nothing posted upstream.+4. scene-kit has extra-pass stand-ins (shadow and reflection), a cached static shadow plus a small live mover map and a texel-size small-caster threshold, with tests, enabled where each scene has the pass; plus the look-neutral scene merges S1 justifies (OD-18), with doors, colliders and moving groups intact.+5. Per scene, before/after count tables and B-06 parity; every difference beyond parity is shown as images for owner review.+6. Timing from quiet hosts only (hub after its quiet check; tablet via the device kit when quiet and cool, mappings removed; this PC only when the kit's quiet check passes), interleaved A/B: p50/p95, share of frames within one and two refreshes, D-41 hitch counts, load samples, tablet economy before/after; or the pending runs with exact commands.+7. scenes/DECISIONS.md records OD-1..OD-18 and the X-02 re-baseline as D-46 onward; skills/kiln-compose-scene and its runtime-scenes reference carry the proven techniques; bun run check:skills passes.+8. Final gates pass: engine bun run typecheck, lint, test, test:render-service, test:coverage; scenes bun run typecheck, lint, test.+9. docs/reviews/2026-10-0X-draw-optimization.md and a private artifact page give per-scene before/after, timing, parity, a cross-scene comparison of what worked where, open decisions and a feedback map of proposed tool, skill, scene-kit and project-convention changes.++Stop and report, rather than treat as unmet, when: a gate cannot pass without changing an owner decision; a change needs a file v1-readiness modifies; a lever fails parity beyond small shadow changes or shows no gain (record it, continue with the rest); the MSAA suspicion is refuted (record, continue); the hub or tablet stays unavailable (report counts and pending timing instead of waiting); anything would need a push, site change, upstream post, live model run or spend.+<!-- goal:end -->diff --git a/docs/plans/2026-10-02-draw-optimization-landing.md b/docs/plans/2026-10-02-draw-optimization-landing.mdnew file mode 100644index 00000000..87423766--- /dev/null+++ b/docs/plans/2026-10-02-draw-optimization-landing.md@@ -0,0 +1,289 @@+# Draw optimization landing (PR 1): plan of record++Status: waiting for the owner to pass the goal statement at the end of this file. Nothing below is implemented+until then. Written 2026-10-02 at 13:17 -04:00.++## Purpose++Land the draw-optimization cycle's scene work as PR 1 against `main`. It carries the owner's answers of 2 October+to the decision sweep, the gates, the timing and the dogfood run, and records corrected before the push.++The engine part (`e72b610`, the `optimize: 'full'` wiring and decisions D1-D3, D23 and D34) is not in this plan. It+is PR 2, which the 0.10.0 engine agent builds after PR #129 merges, from+`docs/reviews/2026-10-02-draw-optimization-engine-handoff.md`.++## Inputs++The `tmp/` and `scenes/evidence/` paths below are ignored and local only.++- **The cycle's records:** the plan `docs/plans/2026-10-01-draw-optimization-cycle.md`, the review+ `docs/reviews/2026-10-02-draw-optimization.md` and the engine handoff above.+- **Decision briefs** (ignored, `tmp/drawcalls/decisions/`): `decide-sweep.brief.md` (D15-D34 and the batch+ order), `summary.txt` (D1-D14), the `decide-*.brief.md` files, and `answers.md`, which holds the owner's answers+ in the owner's order.+- **The reversed-depth prototype:** `tmp/drawcalls/flicker/README.md`, `tmp/drawcalls/flicker/build-variant.ts` and+ `tmp/drawcalls/flicker/variants/revz2.diff` (build label `flicker-revz2`). The tablet A/B is in+ `scenes/evidence/perf/tablet-2026-10-02/tablet-revz-2026-10-02/`.+- **Pilot parity:** `tmp/drawcalls/decisions/decide-sweep/e2-samephase.ts`, the prototype of the paired audit, and+ its 17 same-phase pairs.+- **v1-readiness:** PR #129 (`966c8d6`) shares no file with this branch. It merged as `9375d04` (Kiln 0.10.0) at+ 13:04 on 2 October (corrected: this line first said it was open).++## Owner decisions (2026-10-02, 12:53-13:08 -04:00)++The owner took the recommended option on every question.++### The rules++- **D16, the tablet bar.** p95 at most 33.3 ms and D-41 stay the gate. Adopting a change on the tablet also needs:+ - the share of frames within one refresh not to fall by more than 1 point in 3 of 3 pairs;+ - busy × clock not to rise by more than 3% in 3 of 3 pairs.++ A miss needs the owner's explicit acceptance. The timing runner reports the Mali clock and busy × clock.+- **D18, thin lines.** The thin-line budget becomes part of B-06 for every scene: at most 100 pixels over 32 levels+ beyond the repeat capture, per 1280×720 view. It is defined in this repository. `compareParityImages` gains the+ check and all three parity tools use it. The accepted residuals are ratified:+ - golden arrival, 74 px;+ - day span, 52 px;+ - low shore reflections, 21-35 px.+- **D17, re-baselines.** A change that an owner decision adopts re-records its scene's count baseline in the same+ commit. The commit records provenance (build, commit, views, backends) and adds a one-line DECISIONS note naming+ the decision.+- **D20, the Farm pilot.** Before/after parity gates every change. At each Farm release, a paired audit runs on+ WebGPU and on WebGL2:+ - the new build and the last accepted build are captured at the same pilot phase;+ - a view fails only where the new build fails and the accepted build passes.++ This amends D-53 and D-64. The sweep's 17 of 17 same-phase pairs are recorded as this cycle's pilot evidence.++### Golden Gate++- **D15, the skyline flicker.** Golden Gate adopts reversed depth through a scene-kit renderer option. The option is+ off by default and Golden Gate opts in. It comes with three adaptations, each with unit tests:+ - the sky is drawn first, without a depth test;+ - the reflector's oblique projection is rebuilt for reversed depth;+ - the polygon-offset sign is flipped.++ The 17 thin-line flags are accepted as corrections. The change lands in PR 1.+- **D7 and D7b are moot.** There is no tower split.+- **D5, the reflection.** The High reflection drops the traffic, including the driven car, and the fog banks, as+ WATER-SPEC says.+- **Vegetation cards** stay in the reflection. WATER-SPEC's "cards" is read as the fog cards it names at its line+ 36. The reading is recorded in DECISIONS.+- **D6, the banks hook.** The fog banks get a `hidden` flag that their update respects, in its own commit.++### The Farm++- **D10:** variant A stays.+- **D8:** economy exempts the trailer from the small-caster rule: `keepSmallCasters: ['farmer', 'trailer']`.+- **D9:** the live map stays at full tier size.+- **D11 and D11b:** minimal keeps its 64 woodland cells. DECISIONS records the tablet's GPU cost as the gate's+ reason: busy × clock was +4.5% to +27.2%, higher in 12 of 12 pairs. That replaces SPEC section 15's D-03 reason.+- **D12:** no hero instancing.+- **D28:** the tractor's kinematics stay as they are.++### Tiers, scenes and backlog++- **D14:** minimal stays in every scene on the tablet. Golden Gate at economy may be revisited after the flyover+ stall is fixed.+- **D13:** the Foundry structures stay as they are.+- **D22:** the three pre-existing stalls are worked on after PR 1. The Golden Gate flyover fix comes before any+ Golden Gate tier change.+- **D25:** the R8 shadow target goes to the backlog.+- **D26:** scene-kit correctness comes soon after PR 1 (anchor names, and morph-target and `positionNode` motion+ detection).+- **D27:** Golden Gate loads `data/layout.json` at run time, after PR 1. Golden Gate's other deferred items stay in+ the backlog.+- **D33:** the next performance cycle targets GPU work: per-tree culled packing, then vegetation LOD.++### Landing++- **D1 and D4.** There are two PRs:+ - PR 1, from this plan: every `draw-optimization` commit except `e72b610`, plus the work below;+ - PR 2: the engine work, built by the engine agent after 0.10.0.+- **D30, records.** One record commit:+ - fixes the six known errors;+ - adds the pilot result and this decision round;+ - replaces the two private links with "private report page (owner)" in every file that is pushed.++ The records ride PR 1. The private page gets the same corrections.+- **D29, the site.** The Farm ships at the next site build, after the site's own Farm build check. Golden Gate and+ Foundry Floor are resealed later, in one site change, with an approved upload (D-12).+- **D19, checks.**+ - `scenes/scripts/tests` joins the portable test runner.+ - Golden Gate's count baseline is committed as JSON.+ - glb-world's staged path is fixed.+ - A release checklist runs the three live count checks and the bundle ceilings before any site pack.+- **D21, hub timing.** The 14 hub cells at balanced and economy, and the Golden Gate hero orbit, run before PR 1.+ They run on the final PR 1 build, only after a recorded quiet check. At 13:03 another project's CI held the hub,+ and its fans were audible. Per-frame GPU timestamps are added only if the balanced rise reproduces.+- **D24, skills.** The compose-scene corrections go in PR 1:+ - the instanced-pipeline sentence;+ - split buckets where the per-part draw order matters;+ - read mobile GPU work as busy × clock;+ - a note on depth precision over long view distances.++ The authoring and QA proposals go to the engine agent.+- **D31, dogfood.** One compose-scene dogfood run before PR 1, and the usual runs before PR 2. Both use Agy and+ OpenCode (the owner's words: "use agy and opencode for dogfood").+- **D32, scratch.** The leaked browser profiles were removed on 2 October (see the progress log). The `decide-*`,+ `review-*` and `fix-*` builds and snapshots are removed once this goal is passed. In PR 1, `launchChrome` removes+ its profile on close, with a test.+- **D20 follow-through.** The tool work comes after PR 1: the busy-port fix, a paired mode promoted from the+ prototype, and the B-07 texture-golden re-baseline (39 at every view since the prewarm pass, 41 with the shadow+ cache). PR 1's own audit uses the prototype script.++## Defaults set by the coordinator (owner may edit)++- **Tablet scope.** The D16 bar applies to this tablet, the only X-07 device measured. A higher GPU clock at the+ same frame rate counts as more GPU work.+- **No kiln-commons edits.** `kiln-commons` (SPEC, WATER-SPEC) is not edited. DECISIONS holds the in-repo+ definitions.+- **No tablet rerun for D15.** The final Golden Gate build must match `flicker-revz2` in parity at minimal and+ economy (B-06, and the thin-line count within the repeat-capture noise). A larger difference triggers a tablet A/B+ rerun under D16.+- **The landing branch.** It is `draw-optimization-landing`, cut from `origin/main`. `draw-optimization` stays+ intact as the engine agent's source for `e72b610`. If PR #129 merges before the final gates, the landing branch is+ rebased onto the new `origin/main` and the gates rerun.+- **Numbering.** New DECISIONS entries start at D-65. Answers that change nothing are listed together in one entry.+- **Dogfood sessions.**+ - They use the frozen-runtime runner in `C:/Users/Mattm/X/kiln-dogfood/v1-readiness-2026-10/tools/`+ (`make-runtime.ps1` on the landing branch, then `session.mjs`), with one compose-scene task.+ - Harnesses and models: OpenCode on Meta Muse Spark 1.3 Contributor (the owner's dogfood preference), and Agy on+ `gemini-3.8-flash-high` (the v1 cycle's Agy model), in a fresh empty Agy home.+ - Every trace is read; exit codes are not trusted.+- **Commits** stay local in logical steps until the final push step, with the usual trailer.++## Boundaries++- **Checkouts.** Never edit, stash, switch or clean `C:/Users/Mattm/X/kiln-oss` or `C:/Users/Mattm/X/kiln-v1-readiness`.+ Never edit a file that PR #129 changes. Never touch `site/` in any checkout. The site's Farm build check runs in a+ fresh clone outside both.+- **Outward actions.** No deploy, no asset upload (D-12) and no upstream posts (OD-10). Artifacts stay private.+- **Spend.** The D31 dogfood runs are the only live spend.+- **Timing** runs only on quiet hosts: the hub headed at 120 Hz after a recorded quiet check; the tablet only quiet+ and cool, with its mappings removed afterwards.+- **Push and PR** happen only as the goal's last item, and PR 1 is not merged.++## Steps++**L0, branch.**+- Cut `draw-optimization-landing` from `origin/main` and cherry-pick every `draw-optimization` commit except+ `e72b610`.+- Show that `node scripts/build-runtime.mjs all` leaves `dist/` byte-identical to its base.+- Run `check:skills`, the typecheck and lint.++**L1, decisions.** Add DECISIONS entries from D-65:+- the rules: D16, D17, D18, D20;+- Golden Gate: D15, D5, the vegetation-card reading;+- the Farm: D8, D11;+- the tiers: D14;+- one entry listing the answers that change nothing (D7, D7b, D9, D10, D12, D13, D28) and the backlog (D22, D25,+ D26, D27, D33).++**L2, scene changes, test first.**+- D15: the kit option and Golden Gate's opt-in, with the three adaptations under unit tests.+ - Parity against `draw-after` on WebGPU, with exactly the 17 accepted flags, plus WebGL2.+ - Equivalence with `flicker-revz2` at minimal and economy.+- D5: reflection content; parity, and the counts re-baselined under D17.+- D6: the banks' hidden flag.+- D8: the trailer exemption at economy, with image pairs, and counts if they move.+- D18: the thin-line check in `compareParityImages`, used by all three parity tools.+- D16: clock and busy × clock in the timing runner.+- D19:+ - the portable runner includes `scenes/scripts/tests`;+ - Golden Gate's baseline JSON is committed;+ - glb-world's staged path is fixed;+ - the release checklist is written.+- D32: `launchChrome` removes its profile on close.++**L3, skills.** Add the D24 corrections to `skills/kiln-compose-scene/references/runtime-scenes.md` (and to+`SKILL.md` if needed), then run `bun run check:skills`.++**L4, records.**+- Apply the D30 corrections to the review and the cycle plan, and add the pilot result and this decision round.+- Replace the links.+- Update the private report page.++**L5, evidence.**+- The paired pilot audit of the final Farm build against `draw-base`, on WebGPU and WebGL2, using the prototype.+- The count probe on the final builds.+- The hub timing (D21) against `draw-base`, using the commands in `tmp/drawcalls/s6/timing-full.report.md` (ignored,+ local only).++**L6, gates on a quiet host.**+- Engine: typecheck, lint, test, `test:render-service`, `test:coverage` and `check:skills`.+- Scenes: typecheck, lint and test, which now includes `scripts/tests`.+- A fresh clone with `bun install --frozen-lockfile`, a byte-identical `dist/`, the site's Farm build check, and the+ bundle ceilings.++**L7, dogfood.**+- One compose-scene session each in Agy and OpenCode; read the traces.+- Fix any guidance the runs show is wrong, then rerun the affected gates.++**L8, clean-up.** Remove the `decide-*`, `review-*` and `fix-*` builds and the `scenes/.tmp/build-src` snapshots.+Keep `draw-base`, `draw-after`, `flicker-revz2`, the evidence and the reports.++**L9, PR.**+- Push `draw-optimization-landing` and open PR 1 against `main`.+- Bind it, and read its CI; do not merge.++## After PR 1 (not in this goal)++- **Engine PR 2,** by the engine agent: D1, D2 (a), D3 (a), D23 (b), D34 (a), the authoring and QA proposals, and+ dogfood in Agy and OpenCode.+- **Scenes:**+ - the D20 tool work;+ - the D22 stalls;+ - D26 correctness;+ - D27's run-time layout;+ - the D29 reseal of Golden Gate and Foundry Floor, with an approved upload;+ - the D33 GPU-work cycle.++## Progress log++- 13:17: plan written. The answers are in `tmp/drawcalls/decisions/answers.md` (ignored, local only), and the engine+ handoff gained the owner's engine answers.+- 13:17-13:19: D32 clean-up, approved as "clean now".+ - 352 of the 356 leaked Chrome folders in `scenes/.tmp` were removed (`*-chrome-XXXXXX` profiles and Chrome's+ `chrome_chrome_BITS_*` temp folders). C: gained 13,661 MB.+ - Four `rgf-gg-*` profiles, about 1 MB in all, are left. Some of their files deny access, even to reading their+ permissions. Removing them needs an ownership or permission change, which is left to the owner.+ - No Chrome, Bun or Node process was using the worktree. No record cites a profile path.+- 13:20: the batch times in `answers.md`, this plan and the handoff were corrected from the session transcript.+ They had been stamped 2-22 minutes too late.+- 13:58: the landing was split, by the owner's direction of 2 October ("avoid tedium and ceremony; get this over the+ line"). PR 1 carries the existing commits (every `draw-optimization` commit except `e72b610`, cherry-picked onto+ `draw-optimization-landing` from `origin/main` at `9375d04`), the records corrections and the D24 skill+ corrections. The new scene work (L2), the hub timing (D21) and the dogfood sessions (D31) are deferred to after the+ owner's trip; DECISIONS D-65 to D-76 mark each deferred answer.+- 14:02: PR #130 (docs and site only, no shared file) merged as `a396612` at 13:53, so the landing branch was rebased+ onto it before the push and its gates were rerun.++## Goal statement++<!-- goal:start -->+Land the draw-optimization scene work as PR 1 by following docs/plans/2026-10-02-draw-optimization-landing.md (owner answers of 2 October to sweep decisions D1-D34). Work on a new branch, draw-optimization-landing, cut from origin/main in the worktree C:/Users/Mattm/X/kiln-draw-optimization, with every draw-optimization commit except e72b610 cherry-picked (the engine modules are for the engine agent's PR 2). Never edit, stash, switch or clean C:/Users/Mattm/X/kiln-oss or C:/Users/Mattm/X/kiln-v1-readiness. Never edit a file PR #129 changes. Never touch site/, deploy, upload assets or post upstream. Artifacts stay private. The only live spend is the D31 dogfood runs.++Done when each item is shown by printed output in this conversation:+1. The landing branch rebuilds dist/ byte-identical to its base.+2. Golden Gate has a scene-kit reversed-depth option, off by default, that Golden Gate opts into, with the sky, reflector and polygon-offset adaptations under unit tests. Its High reflection drops traffic and fog banks, and the banks get a hidden flag. Parity against draw-after passes B-06 on WebGPU and WebGL2, with thin-line flags limited to the 17 accepted ones, and it matches flicker-revz2 at minimal and economy.+3. The Farm's economy tier keeps the trailer's small shadows, shown as image pairs.+4. compareParityImages enforces the thin-line budget for all three parity tools. The timing runner reports clock and busy x clock. scenes/scripts/tests runs in bun run test. Golden Gate's count baseline JSON is committed. glb-world's budget test runs. launchChrome removes its profile on close, with a test.+5. scenes/DECISIONS.md records the 2 October answers from D-65 onward, with re-baselines in the commits that move counts.+6. kiln-compose-scene carries the D24 corrections, and bun run check:skills passes.+7. The records are corrected per D30, with no private links, and the private report page is updated.+8. Evidence: a paired pilot audit of the final Farm build on WebGPU and WebGL2, and the 14 hub cells plus the Golden Gate hero orbit on a quiet hub (headed, 120 Hz, load recorded).+9. Final gates on a quiet host pass: engine typecheck, lint, test, test:render-service, test:coverage and check:skills; scenes typecheck, lint and test; a fresh clone with bun install --frozen-lockfile; the site's Farm build check in that clone; and the bundle ceilings.+10. One compose-scene dogfood session each in Agy and OpenCode, with the traces read and the findings fixed or recorded.+11. The decide, review and fix scratch builds are removed; draw-base, draw-after, flicker-revz2, the evidence and the reports are kept.+12. The landing branch is pushed and PR 1 is opened against main, with its CI read. It is not merged.++Stop and report, rather than treat as unmet, when:+- a gate or budget test fails in a way that needs an owner decision;+- a change would touch a PR #129 file;+- parity differs beyond the accepted flags;+- the hub or tablet is not quiet (report the pending timing with commands instead of waiting);+- a dogfood session fails for harness or account reasons;+- CI fails for reasons outside this branch.+<!-- goal:end -->diff --git a/docs/reviews/2026-10-02-draw-optimization-engine-handoff.md b/docs/reviews/2026-10-02-draw-optimization-engine-handoff.mdnew file mode 100644index 00000000..cf555881--- /dev/null+++ b/docs/reviews/2026-10-02-draw-optimization-engine-handoff.md@@ -0,0 +1,539 @@+# Draw optimization: handoff to the engine and 0.10.0 work++This record is for the agent that owns the engine and the 0.10.0 release (branch `v1-readiness`,+PR #129). It lists what the draw-optimization cycle changed or found that touches the engine,+its skills, assets or projects. That covers what is ready to apply, what is only proposed, and+which decisions are still the owner's.++It was written on 2026-10-02 at about 12:45 -04:00, in the worktree+`C:/Users/Mattm/X/kiln-draw-optimization`. That worktree is on branch `draw-optimization`: 25+local commits on `main` `c734e2a` (this record and the landing plan are the last two), none+pushed. Every claim about `v1-readiness` was rechecked against its tip `966c8d6` at the time of+writing. PR #129 has since merged as `9375d04` (Kiln 0.10.0) on 2 October; the engine PR comes+after it.++Like every dated record, it does not override current code, `AGENTS.md` or the changelog. The+decision IDs (D1 to D34) come from this cycle's decision briefs. They are not the `D-` numbers in+`scenes/DECISIONS.md`. The owner answered the engine decisions at 13:00 and 13:05; the answers are in+the next section.++## Owner answers (2026-10-02, 13:00 and 13:05 -04:00)++The owner took the recommended option on every engine decision:+- **D1 (a):** wire the merge into `optimize: 'full'` after 0.10.0 (PR #129) merges, as one+ engine PR. The engine agent does it from this record.+- **D4 (a):** two PRs. PR 1 is this branch's scene, skill and record work without `e72b610`, and+ comes from the draw-optimization session. PR 2 is the engine work: `e72b610`, the wiring, D2,+ D3, the texts, the CHANGELOG and one `dist/` rebuild.+- **D2 (a):** copy a shared mesh only when it costs at most 4 KB per saved draw.+- **D3 (a):** split a merged bucket at 65,534 vertices to keep 16-bit indices.+- **D23 (b):** output only. The export summary and `kiln_inspect` gain draws per anchor, a draw+ estimate and the two flags. The `kiln_render` compact result and every input schema stay as+ they are.+- **D24 (a):** the compose-scene corrections ride PR 1. The authoring and QA proposals (section+ 6.4) go to the engine agent after 0.10.0, with dogfood.+- **D31 (a):** live dogfood before each PR. The owner wants Agy and OpenCode for the dogfood+ runs.+- **D34 (a):** fix the three hazards in the engine PR, with a test for the occlusion UV set.++The owner-only questions at the end of section 5 were not asked in this round. Put them to the+owner before or during the engine PR.++## In short++- **Engine code.** One commit (`e72b610`) adds two modules: `src/rigid-merge.ts` and+ `src/extension-compat.ts`, with tests. They are standalone: nothing imports them, and the+ branch changes no export, `package.json`, `dist/` bundle or changelog.+- **Ready patch.** A patch wires the merge into `optimize: 'full'`. It still applies to+ `966c8d6`. The recommendation is to land it after 0.10.0 merges, in one engine PR with a+ single `dist/` rebuild.+- **Skills.** Only `kiln-compose-scene` changed, in two commits.+- **Unchanged.** Assets, GLBs, sealed packs, `packs/`, Kiln projects, materials, the library,+ `render-service/` and `site/`. Every scene optimization is runtime code under `scenes/`.+- **No overlap.** `v1-readiness` changes 220 files since `c734e2a` and this branch changes 114;+ no file is in both.+- **Engine decisions** D1, D2, D3, D23, D34 and the authoring and QA half of D24 are answered: the+ owner took every recommendation. Sections 4 and 5 give the facts behind them.++## 1. What changed outside `scenes/`++| Commit | Files | Lines | What |+|---|---|---|---|+| `e72b610` | `src/rigid-merge.ts`, `src/extension-compat.ts`, `src/__tests__/rigid-merge.test.ts`, `src/__tests__/extension-compat.test.ts` | +476, +382, +908, +268 | Standalone modules. 28 tests pass (16 and 12; rerun at 12:42 today with `KILN_RENDER=cpu`) |+| `7db7325`, `00c4de8` | `skills/kiln-compose-scene/SKILL.md`, `skills/kiln-compose-scene/references/runtime-scenes.md` | +3, +66 | Draw-call techniques proven in the scenes, with their measured effect |+| `0aa3d28`, `6feac7b` | `docs/plans/2026-10-01-draw-optimization-cycle.md`, `docs/reviews/2026-10-02-draw-optimization.md` | +312, +486 | Plan of record and review |+| this commit | this file | | Handoff |++The other 104 changed files are all under `scenes/`:+- scene-kit: merge by material within anchors, the shadow cache and stand-ins, multisample+ discard, and the count probe;+- the three scenes;+- the scene scripts.++That code runs in the browser at load and rewrites no GLB.++**Build identity.** `dist/` was not rebuilt. `scripts/build-runtime.mjs:52` hashes every file+under `src/`, so `e72b610` alone makes `dist/build.json` stale:+- the `identity` and `sourceHash` of all five entries change;+- the bundles stay byte-identical, because nothing imports the new modules;+- no test catches it, but `scripts/qualify-project-foundation.mjs:247-248` compares the hash and+ would fail.++Whichever PR carries `e72b610` must run `node scripts/build-runtime.mjs all`.++## 2. Against `v1-readiness` (`966c8d6`, PR #129)++- **Files.** No file is in both branches. `v1-readiness` touches the author, QA, refine and+ setup skills; this branch touches only compose-scene.+- **The patches still apply.** `wiring.patch` and `wiring-tests.patch` pass `git apply --check`+ against copies of `966c8d6`'s `src/render.ts` and the four test files (taken with `git show`+ at about 12:40 today). `v1-readiness` changed `src/render.ts` (+26/−4: strict-mode generated code+ and bounded floater warnings) but not the optimize path.+- **Merged-tree gates, earlier, at `6ec32a1`.**+ - A scratch merge of this branch into `v1-readiness` had no conflict. Typecheck, lint (872+ files) and `check:skills` passed.+ - With both patches applied, typecheck and lint passed and 439 of 441 tests passed. The run+ covered the optimize-related test files plus the module, bundle and package tests.+ - The 2 failures were 20 s timeouts in `migration-rebuild.test.ts`. They also failed without+ the patches on that loaded host.+ - These gates were not rerun on `966c8d6`.+- **`dist/`.** A `dist/` built on this branch does not apply onto `v1-readiness`'s `dist/`.+ Regenerate it; never merge bundles by hand.++## 3. The modules++### `src/rigid-merge.ts`++The module header is the specification.++**API**+- `mergeRigidGroups(doc, options?)` (line 332) merges in place and returns a+ `RigidMergeSummary`.+- `rigidMerge(options?, onSummary?)` (line 468) is the gltf-transform `Transform` form.+- `RigidMergeOptions`:+ - `keep`: names to keep as boundaries;+ - `mergeTransparent`;+ - `mergeMirroredTangents`;+ - `expandSharedMeshes`, which defaults to `true`.+- The summary reports:+ - `primitivesBefore` and `primitivesAfter`;+ - `groups` and `merges`;+ - `boundaries`, with reasons;+ - `locked`, with reason and primitive count;+ - `rejected` buckets, with errors;+ - `unmatchedKeep`;+ - `skipped: 'unbounded-animation'`.++**Rigid groups.** A rigid group is a scene or boundary node plus every non-boundary descendant.+Primitives that share a material and vertex layout are baked into the frame of the group's+first contributing node and joined. No node is removed, renamed or reparented.++**Boundaries:**+- animation targets and skin joints;+- `Joint_*` pivots;+- nodes with any extras;+- semantic relationship targets;+- `KHR_node_visibility` and `MSFT_lod` nodes;+- `keep` names.++**Locked, never moved or joined:**+- skinned or GPU-instanced nodes;+- meshes with extras;+- nodes with a singular world matrix;+- morph targets;+- primitives with extensions or extras;+- strip, fan and loop modes;+- primitives without POSITION;+- `KHR_materials_volume`;+- BLEND or transmissive materials, unless `mergeTransparent`.++**Contract.** Every node name and every boundary's geometry survive. A named non-boundary+node's geometry does not: Golden Gate's `Roadway` goes from 164 to 660 triangles, and stays at+164 with `keep: ['Roadway']`.++**Tangents** are baked by the module, not by gltf-transform (section 6.2). By default,+mirrored tangent-bearing parts join only parts of the same world handedness;+`mergeMirroredTangents` lifts that.++**Detached checks.** Each bucket is built and checked detached from the graph. A bucket that+fails leaves its primitives untouched and is reported in `rejected`.++**Measured on the real Farm `farmhouse.glb`:**++| | Draws | Notes |+|---|---|---|+| Merge alone | 16 → 11 | |+| Palette, then merge | 16 → 9 | `Joint_FrontDoor` keeps its 2 primitives |+| Today's `full` | 16 → 16 | Loses the door pivot |++With the merge, nodes stay at 24, triangles at 4,080, and the Khronos validator reports 0+errors and 0 warnings.++### `src/extension-compat.ts`++**Purpose.** It answers one question: does a destination's stock glTF importer load this file?+It is pure and bytes-first: no filesystem, network or renderer. It is a library function only,+with no tool output and no schema change.++**API**+- `readGltfExtensions(input)` (line 285) reads `extensionsUsed` and `extensionsRequired` from+ GLB bytes, a `Document` or the lists themselves. It parses the JSON chunk itself, because+ gltf-transform 4.5.0's reader throws on an unknown required extension.+- `checkExtensionCompat(input, destination, {available?})` (line 344) returns a report:+ - each required extension gets `ok`, `conditional` (it needs a named decoder, add-on or+ plugin; `available` lists the ones the caller has wired) or `blocked`;+ - warnings name optional extensions that an importer ignores although that changes what+ draws.+- `GLTF_DESTINATIONS`:+ - `three`, `godot`, `unity` (profiled as glTFast), `unreal`, `bevy` and `blender`;+ - the ids follow the project delivery targets in `projects.ts`;+ - `roblox`, `sbox`, `usdz` and `custom` have no sourced allowlist and are not profiled;+ - each allowlist cites the importer source it was read from (read on 2026-10-01).++**Scan of the scene site inputs and their staged copies** (203 files, 107 unique):++| Unique GLBs (files) | Extensions | Result |+|---|---|---|+| 44 (65) | none | ok everywhere |+| 42 (96) | `MSFT_lod`, optional only | ok everywhere |+| 20 (40) | Golden Gate terrain tiles: `KHR_mesh_quantization` and `EXT_meshopt_compression` required | blocked in Godot and Bevy; conditional in three, glTFast and Unreal; ok in Blender |+| 1 (2) | Foundry FOUP, `KHR_node_visibility` | warning in three, glTFast, Bevy and Blender |++**Correction to the research report's acceptance line.** That line says the lint should flag+the kit pass for the Godot profile. The kit pass marks `KHR_texture_basisu` as required+(`src/kit.ts:381`). The check finds that pass:+- ok for Godot 4.7.2;+- blocked for Bevy and Blender;+- conditional for glTFast and for three (`KTX2Loader`);+- unverified for Unreal.++## 4. The `optimize: 'full'` wiring: ready, not applied++### Why change it++Today `full` runs `flatten()` + `join()` on static, semantics-free graphs, and degrades to+`palette` otherwise. On the 86 `examples/*.kiln.js`:+- 35 degrade to `palette`;+- the other 51 flatten, and every one of them loses its hierarchy;+- 27 lose `Joint_*` pivots;+- none saves a draw, and 31 grow.++### The patch++`C:/Users/Mattm/X/kiln-draw-optimization/tmp/drawcalls/phase0/wiring.patch` (ignored, local+only) changes `src/render.ts` by +21/−35:+- `full` now degrades only when an animation channel has no target node (a pointer);+- `flatten()` + `join({keepNamed: true})` becomes `rigidMerge()`. The order inside+ `consolidateMaterials` is palette (behind the same material-extras guard), the merge, `weld`,+ then `prune`;+- it drops the unused `flatten` and `join` imports, and the citation of the missing+ `docs/kiln-material-consolidation-cycle.md`;+- `off`, `auto` and `palette` stay byte-identical: 49 of 49 outputs were checked.++The full description is in `tmp/drawcalls/phase0/wiring.md` (ignored, local only).++### Test expectations++`wiring-tests.patch` changes 4 files (+9/−9). Five tests expected `palette` where `full` now+runs:+- `msft-lod`, twice;+- the `optimize` test "auto-degrades to palette when the asset is animated";+- the `qa/architecture` test;+- the `views/architecture` test.++Only the mode expectation and the "degrades" titles change. Every other assertion in those tests+passes under the merge.++### Outputs on the examples++Rendered through `renderGLBInProcess`:++| Output | Draws | Bytes | Nodes with a parent | `Joint_*` nodes |+|---|---|---|---|---|+| `palette` | 26,989 | 46,920,396 | 27,699 | 619 |+| `full` today | 26,989 | 47,077,288 | 10,630 | 368 |+| `full` wired, module default | 1,672 | 69,427,992 | 27,699 | 619 |++- Triangles are unchanged and the validator reports 0 errors.+- The +48% bytes comes from the shared-mesh default; see D2.+- `composeSceneGLB(…, {optimize: 'full', keepAnimations: true})` on seven Farm placements goes+ from 72 to 31 draws, at +17.0% bytes, with all 9 `Joint_*` nodes kept.++### Who reaches `full` today++No tool, CLI or site path does. Line numbers are on `966c8d6`:+- `evaluateGeneratedSource` defaults to `'off'` (`src/tools/registry.ts:417`).+- The CLI render passes `'off'` (`src/cli.ts:318`).+- `KILN_BAKE_OPTIMIZE` only sets a default, and tool calls override it+ (`src/local-runtime.ts:127-131`).++`full` is reached only through `@kiln/engine/render`:+- `renderGLB` and `renderSceneToGLB`, with `optimize` or the env (`src/render.ts:1334`);+- `optimizeGlbBytes({mode})` (`:2008`). Its comment names Kiln Studio's web tier as a caller;+- `composeSceneGLB({optimize})` (`:2288`), which defaults to `palette`.++### What landing it also needs++- **A `dist/` rebuild:** `node scripts/build-runtime.mjs all`. On `v1-readiness`'s layout the+ merge lands in `agent-run`, `cli`, `evaluator-worker` and `mcp-engine`, adding about 12.0 KB+ raw and 3.1 KB gzip each. The thin `mcp-server.mjs` does not change; `build.json` does.+- **Three texts** that still say full optimisation falls back to palette. Line numbers are on+ `966c8d6`:+ - `docs/engine-handoff.md:210`;+ - `docs/migration.md:173`;+ - `skills/kiln-qa-asset/references/engine-handoff.md:211`.++ The author-asset copy is deleted on `v1-readiness`. The QA skill is model-facing.+- **A stale citation.** `src/__tests__/optimize.test.ts:4` also cites the missing doc.+- **A CHANGELOG entry.** Proposed text: "`optimize: 'full'` merges primitives by material inside+ rigid groups instead of `flatten()` + `join()`. `Joint_*` pivots, animation targets,+ metadata-bearing, LOD and visibility nodes keep their own geometry and every node keeps its+ name; the farmhouse drops from 16 to 9 draws with its door pivot intact."+- **The D2 and D3 choices**, so that `full` output changes only once.++### Reproduce++```bash+KILN_RENDER=cpu bun test ./src/__tests__/rigid-merge.test.ts ./src/__tests__/extension-compat.test.ts+KILN_RENDER=cpu bun tmp/drawcalls/phase0/rigid-merge-evidence.ts+bun tmp/drawcalls/phase0/extension-compat-scan.ts+```++The two scripts under `tmp/` are ignored, local only, and need the ignored scene inputs, so run+them from the draw-optimization worktree.+`bun test src scripts` matches any path containing `src`, including copies under `tmp/`. Delete+any scratch copy of `src/` before running the gate.++## 5. Open decisions for the engine work++### Where they come from++A decision sweep found 36 open decisions in all: D1 to D34, plus D7b and D11b. The owner answered+them in ten batches on 2026-10-02 between 12:53 and 13:08. The engine items were in batch 6+(D1, with D4) and batch 8 (D2, D3, D23 and D34). The table keeps the options as they were put;+the chosen option is the recommended one in every row.++| ID | Question | Recommendation | Key numbers |+|---|---|---|---|+| D1 | When does `full` switch to the merge? | (a) After 0.10.0 merges: rebase, wire, apply D2 and D3, fix the texts, add the CHANGELOG entry, rebuild `dist/` once, in one engine PR | (b) Wiring now causes a measured `dist/` conflict at rebase. (c) Putting it into `v1-readiness` voids PR #129's recorded gate and fresh clone |+| D2 | Which shared meshes may `full` copy? | (a) Copy a mesh when it costs at most 4 KB per saved draw | Examples: draws −90%, raw +33.6%. Scene assets: −81%, +2.1%. Golden Gate web: 148 → 33 draws. Expand all (module default): −94%, +48.0%. Lock shared users: −12.5%, −5.7% |+| D3 | Cap merged indices at 16 bits? | (a) Split a merged bucket at 65,534 vertices | Only Golden Gate web triggers it: +1 draw, raw −8%, index bytes −44%, brotli −1.8% to −3.0%, gzip +4% |+| D4 | Landing order | (a) PR 1 now carries the 24 non-engine commits (scene, skill and record). PR 2, after `v1-readiness`, carries `e72b610`, the wiring, D2, D3, the texts, the CHANGELOG and `dist/` | PR 1's tree rebuilds `dist/` byte-identical, `build.json` included |+| D23 | Model-facing additions | (b) Output only: the export summary and `kiln_inspect` gain draws per anchor, a draw estimate and flags; the `kiln_render` compact result stays as is | No input-schema change |+| D24 | Skill proposals | (a) Compose-scene corrections in PR 1, on this branch. Authoring and QA proposals after 0.10.0, with dogfood | See sections 6.4 and 6.5 |+| D34 | Phase 0 hazards | (a) Fix them in the engine PR | See below |+| D31 | Dogfood | (a) One compose-scene run before PR 1, and the usual runs before PR 2 | Two spends |++The D2 measurements cover 96 readable scene assets and all 86 examples. The main table compares+eight policies with the palette baseline. It is+`C:/Users/Mattm/X/kiln-draw-optimization/tmp/drawcalls/decisions/decide-engine/d2-table.md` and+the chart is `d2-policies.png`. The scratch module variant with the per-mesh price rule and the+D3 split is `decide-engine/rigid-merge-variant.ts`, +38/−7 lines against `src/rigid-merge.ts`.+All three files are ignored and local only.++**D34 hazards.** All three are present on `main`, on `966c8d6` and on this branch.+1. **Occlusion UV set.** `src/kit.ts:204`: after `packOcclusionIntoMetallicRoughness` folds+ occlusion into the metallic-roughness image, it points the occlusion texture at the+ metallic-roughness UV set. It never checks that the two sets match. A baked AO map on UV1+ would then be sampled with UV0. The packed R channel is still laid out for the occlusion's+ own UV set.+2. **Missing doc.** `src/render.ts:1103` and `src/__tests__/optimize.test.ts:4` cite+ `docs/kiln-material-consolidation-cycle.md`, which exists on no branch. The wiring patch+ removes the `render.ts` citation.+3. **Undocumented variables.** `KILN_BAKE_OPTIMIZE` and `KILN_BAKE_INSTANCE` are read in+ `src/local-runtime.ts:127-131`, `src/render.ts:1334, 1346` and+ `src/tools/registry.ts:2352-2353`. No doc, README, skill, `AGENTS.md` or CHANGELOG mentions+ them.++**Only the owner can answer** (from the D1 to D4 brief):+- **Outside callers.** Does anything outside this repository call `full`? Kiln Studio's web tier+ calls `optimizeGlbBytes`, and its mode is not visible here.+- **Release line.** Which release line carries the change?+- **Placement wrappers.** `composeSceneGLB(…, 'full')` now merges across placement wrappers,+ which carry no extras. Make them boundaries (one `keep` at that call site), or accept it.+- **Named nodes.** Accept the named-node contract, or plumb `keep` through `RenderSceneOptions`.+ That plumbing is an API change.+- **Caller knob.** A knob for the D2 threshold would touch `RenderSceneOptions`, the evaluator+ protocol (`src/evaluator/protocol.ts`) and the rebuild schema (`src/rebuild-options.ts`).+- **Served encoding.** Whether GLBs are served with brotli or gzip decides whether D3 also saves+ wire bytes.+- **Rebuilt revisions.** A revision saved with `KILN_BAKE_OPTIMIZE=full` rebuilds to different+ bytes, so `matchesSavedArtifact` becomes false. Tool paths record only `off` or `auto`.++## 6. Findings the engine and skills can use++### 6.1 three r186++This is the version both the engine and the scenes install. None of these findings was reported+upstream; the owner's policy is no AI-generated issues or PRs to three.js.++1. **Every instanced mesh binds its own pipeline.**+ - `RenderObject.getMaterialCacheKey()` appends each `InstancedMesh`'s uuid+ (`src/renderers/common/RenderObject.js:846-851`, next to an upstream TODO).+ - Measured: instancing Foundry Floor's campus structures with their exported materials took+ summed main-pass pipelines from 77 to 346.+ - So `EXT_mesh_gpu_instancing` saves draws in three's WebGPU renderer but adds a pipeline per+ instanced group.+ - `skills/kiln-compose-scene/references/runtime-scenes.md:111-114` is wrong on this point. It+ says groups that differ only by a material constant compile one pipeline each. Correcting it+ is D24 (a), in PR 1.+ - The fix that worked in the scenes was one shared material reading per-part data. Campus+ planting went from 21 to 10 pipelines at the overview.+2. **Mirrored tangent frames.** three builds the bitangent as `cross(N, T) * w` with no+ determinant term (`src/renderers/shaders/ShaderChunk/normal_vertex.glsl.js:9-15`;+ `src/nodes/accessors/Bitangent.js:18, 58`). So baking a mirrored normal-mapped part with+ `w *= sign(det)` changes its shading in three. That is why the merge joins only parts of the+ same handedness by default.+3. **Reversed depth** (`reversedDepthBuffer: true`, which gives a depth32float buffer).++ three handles:+ - depth reads (`perspectiveDepthToViewZ`, `src/nodes/display/ViewportDepthNode.js:227-239`);+ - shadow bias and comparison (`src/nodes/lighting/ShadowNode.js:314, 338`);+ - depth functions, the clear value and the frustum.++ three does not handle:+ - `SkyMesh`, which pins clip z to w (`examples/jsm/objects/SkyMesh.js:215`). That is the far+ plane only in a standard buffer.+ - `ReflectorNode`'s oblique near plane, which assumes a standard buffer+ (`src/nodes/utils/ReflectorNode.js:515-537`). Distant geometry drops out of the reflection.+ - Polygon offset, which both backends pass through unchanged+ (`src/renderers/webgpu/utils/WebGPUPipelineUtils.js:238-242`,+ `src/renderers/webgl-fallback/utils/WebGLState.js:997-1007`). Its sign must flip.++ The WebGL2 backend needs `EXT_clip_control`. Without it, three warns and falls back to a+ standard buffer (`src/renderers/webgl-fallback/WebGLBackend.js:276-288`).++ This matters to long-range scenes (Golden Gate's skyline flicker, D15), not to asset review+ captures, whose clip planes fit the asset.+4. **Multisample store.**+ - r186 stores the 4x canvas colour and depth after the resolve. With the store flags false,+ the attachments become transient.+ - Scene-kit discards them per tier (`ced34bb`). On the tablet, GPU busy fell by 3 to 8+ points; the desktop showed no change.+ - The store is required where a mid-pass `viewportDepthTexture` copy restarts the pass with+ Load.+ - No engine change is proposed.++### 6.2 gltf-transform 4.5.0 and the engine's IO++- **Tangents.** `transformPrimitive`'s `applyTangentMatrix` reads x after overwriting it, and+ never flips w. `rigid-merge.ts` bakes tangents itself.+- **Unknown required extensions.** The reader throws on them, so `extension-compat.ts` parses+ the JSON chunk instead.+- **Index width.** `createIndicesEmpty` writes 16-bit indices when the largest index is at most+ 65,534, and `weld` rebuilds indices after the merge (D3).+- **Meshopt.** The engine's IO registers no meshopt decoder. It therefore cannot read Golden+ Gate's 20 terrain tiles, which require `EXT_meshopt_compression`.++### 6.3 Merging assets++- **Coplanar faces.** Merging changes the draw order of coplanar faces. On Golden Gate:+ - The bridge merge put the curbs after the coplanar walks in one draw. The curbs then won+ the depth ties and stippled both kerbs, and tile-mean parity missed it. `892d103` puts the+ curbs first in the merged mesh, at no extra draws.+ - Tower ribs against panels changed 193 px by more than 32 levels at golden-hour side-full.+ With reversed depth, that tie is gone (0 px over 8 levels).++ A merge cannot see these ties; authoring guidance and an inspection flag can (D23, D24).+- **Compression.** Baked world-space coordinates compress worse. With no copies at all, gzip+ still grows by 5.1% on scene assets and 7.0% on examples while raw bytes fall.+- **Shared meshes.** They dominate Kiln exports: their users account for 85.5% of example draws+ (3,548 shared meshes in 85 of 86 examples, none instanced). That is why the shared-mesh policy+ (D2) decides both draws and bytes.+- **Passes.** In scenes, shadow and reflection passes draw the asset again:+ - Farm: 270 of 583 draws were in the shadow pass.+ - Golden Gate: the reflection redrew 50 to 180.++ A draw estimate should state which passes it covers (D23).++### 6.4 Authoring and QA proposals (D24, after 0.10.0)++These come from the review's feedback map (`docs/reviews/2026-10-02-draw-optimization.md`,+lines 391-441).+- **`kiln-author-asset` geometry recipes** (`references/geometry-recipes.md`):+ - keep moving parts as named `Joint_*` pivots;+ - budget materials per rigid group, because draws per anchor equal its material count;+ - avoid coplanar faces across separate parts;+ - fold tiny parts that never move (eyes, bolts, hubs) into their parent's material.+- **`kiln-qa-asset`:** in the destination, check draws per anchor and material, and check that+ interaction survives a merge.++### 6.5 Compose-scene corrections planned for PR 1 (D24 (a), this branch)++- The pipeline sentence (section 6.1, item 1).+- Split merge buckets where the per-part draw order matters (the tower tie).+- Read mobile GPU work as busy × clock, not busy alone. Measured that way, the tablet's GPU+ savings were larger than the busy column showed: Farm walk −15% and Foundry campus −24%.+- If D15 is adopted, a note on depth precision over long view distances. With a 0.5 m near+ plane, the depth step grows with distance squared: about 0.12 m at 1 km, 3 m at 5 km and 48 m+ at 20 km. The note would cover reversed depth and the three r186 adaptations above.++These edits touch only `skills/kiln-compose-scene/`, which `v1-readiness` does not change.++## 7. Assets, packs and projects++- **Nothing changed.** No GLB, sealed pack, `packs/` entry, Kiln project, material, library+ collection or Live Review item changed. The scenes optimize their existing GLBs at load in+ scene-kit (merge by material within anchors, shadow and reflection stand-ins, the shadow+ cache), so no asset file grows.+- **The site.** It still serves the old Golden Gate and Foundry Floor builds from sealed packs+ pinned in `site/src/data/scene-packs.json`. Farm is bundled from `scenes/` source, so the next+ site build after a merge ships the optimized Farm. New packs and pins are D29, which belongs+ to the scenes and site work, not the engine.+- **Asset-level optimization** exists only as the unwired `full` merge (section 4) and the+ proposals in section 6.4.+- **Golden Gate's reversed depth (D15)** would be a scene-kit renderer option plus scene code. It+ needs no engine or asset change.++## 8. Known errors in the committed records (D30)++Do not copy these from the review or plan:+1. **"488 of 489"** (review line 229) is too high. Golden side-full also fails at economy and+ balanced (193 px) and on High WebGL2 (200 px).+2. **"Keep the tower ribs unmerged"**, open decision 5's alternative, also fails, at 177 px.+3. **The S6 tablet table understates GPU savings** (section 6.5).+4. **"Foundry Floor economy on the tablet"** (review line 352) has since run.+5. **The Farm pilot parity** (D-53, D-64) is missing from the review. The sweep ran it as D20.+6. **`scenes/packages/foundry-floor/REPORT.md:939`** gives 23-28 programs and 15-18 pipelines.+ The campus now measures 87-92 programs and 78-81 pipelines. That is `main` before this+ branch: with this branch's shared plant material, the campus view measures 27 programs and+ 17 pipelines.++The review (lines 9 and 138) and the plan (lines 248 and 292) also carry two private links.+D30 recommends replacing them before any push.++The records commit on `draw-optimization-landing` (PR 1) corrects all six and replaces the+links; the line numbers above are those before it.++## 9. Where the evidence is++The paths are under `C:/Users/Mattm/X/kiln-draw-optimization/`. Everything not marked committed+is ignored and exists only on this machine.++| Path | What |+|---|---|+| `docs/reviews/2026-10-02-draw-optimization.md` (committed) | The review. The feedback map is at lines 391-441 and the gates at 454 onward |+| `docs/plans/2026-10-01-draw-optimization-cycle.md` (committed) | Plan of record, OD-1 to OD-18 and the progress log |+| `scenes/DECISIONS.md` (committed) | D-46 to D-64 |+| `tmp/drawcalls/phase0/` | `wiring.md`, `wiring.patch`, `wiring-tests.patch`, `rigid-merge-evidence.{ts,log}`, `extension-compat-scan.{ts,log}`, `size-probe.{ts,log}`, `wire-*.ab.json` |+| `tmp/drawcalls/decisions/decide-engine.brief.md` and `decide-engine/` | The D1 to D4 brief and its evidence: corpus, policy tables and chart, merged-tree gates, `dist/` sizes, fresh-clone logs |+| `tmp/drawcalls/decisions/decide-sweep.brief.md` | D15 to D34, and the order for asking all 36 |+| `tmp/drawcalls/decisions/summary.txt` | Summary of D1 to D14 |+| `tmp/drawcalls/decisions/decide-gg-depth.brief.md`, `tmp/drawcalls/flicker/README.md` | D15: depth precision and the reversed-depth prototype (`flicker/variants/revz2.diff`) |+| `tmp/drawcalls/decisions/decide-foundry-tablet.brief.md` | The instanced-mesh pipeline measurement (section 6.1) |+| `tmp/drawcalls/research/asset-optimization-frontier.md` | The research report, copied from the main checkout: Phase 0 hazards and model-facing proposals |+| `tmp/drawcalls/gates/final/` | Gate logs on `69f92fe` |+| `scenes/evidence/` | Counts, parity images and timing |++## 10. Suggested order for the engine PR++1. Merge 0.10.0 (PR #129).+2. Bring `e72b610` onto it, then apply `wiring.patch` and `wiring-tests.patch`.+3. Add D2's per-mesh price rule and D3's split to `src/rigid-merge.ts`, tests first. The scratch+ variant shows the shape of both.+4. Fix the D34 hazards, with a test for the occlusion UV set.+5. Update the three texts, the test citation and the CHANGELOG.+6. Run `node scripts/build-runtime.mjs all`, then the full gate including coverage.+7. Add D23's outputs as a separate model-facing change. Then run the D31 dogfood sessions in+ Agy and OpenCode.+8. The authoring and QA skill proposals (section 6.4) follow the same dogfood rule.diff --git a/docs/reviews/2026-10-02-draw-optimization.md b/docs/reviews/2026-10-02-draw-optimization.mdnew file mode 100644index 00000000..5db2e9fc--- /dev/null+++ b/docs/reviews/2026-10-02-draw-optimization.md@@ -0,0 +1,520 @@+# Draw optimization across the three scenes++The draw-optimization cycle ran on branch `draw-optimization` in the worktree+`C:/Users/Mattm/X/kiln-draw-optimization`, following+`docs/plans/2026-10-01-draw-optimization-cycle.md`. Owner decisions OD-1 to OD-18+are recorded as D-46 to D-63 in `scenes/DECISIONS.md`, and the X-02 re-baseline+as D-64.++The parity images are on the private report page (owner). This record covers counts, look parity, quiet-host timing, what worked where, the+open decisions and a feedback map. The commits are local only: nothing was pushed,+deployed, posted upstream, or run against a live model. No owner acceptance is+implied.++## Headline++Draws are summed over every count fixture of a tier. BEFORE is `draw-base` (main+at `c734e2a`) and AFTER is `draw-after` (this branch).++| Scene | Tier | Draws BEFORE → AFTER | Pipelines bound, summed | Triangles |+|---|---|---|---|---|+| Farm (18 fixtures) | minimal | 3,712 → 3,424 (−7.8%) | 470 → 470 | equal |+| Farm | economy, balanced, high | 8,161 → 3,025 (−62.9%) | 1,039 → 517 | −22% to −24% (no per-frame shadow pass when settled) |+| Golden Gate (18) | minimal, economy | 2,207 → 786 (−64%) | 435 → 238 | +0.4% (coarser culling) |+| Golden Gate | balanced | 2,238 → 817 (−64%) | 440 → 243 | +0.2% |+| Golden Gate | high | 6,158 → 1,706 (−72%) | 1,014 → 447 | −9% |+| Foundry Floor (15) | minimal to high | 1,579–1,677 → 1,474–1,572 (−6.3% to −6.6%) | 303–305 → 138–140 | equal |++Representative views, draws per frame:++| View | BEFORE | AFTER |+|---|---|---|+| Farm landing view, high, settled | 583 (main 312, shadow 270, output 1) | 283 (main 282, shadow 0, output 1) |+| Farm landing view, high, clock running | 583 | 337 (live map for animals and rotors; 12-17 static re-renders over 3,600 frames) |+| Farm landing view, minimal | 345 | 315 |+| Golden Gate arrival, high | 432 (main 179, shadow 37+37, reflection 178, output 1) | 103 (main 51, shadow 2 in one pass, reflection 49, output 1) |+| Golden Gate arrival, minimal | 180 | 52 |+| Foundry Floor campus, high | 101 main | 95 main; pipelines bound 21 → 10 |++## What changed++The hashes are those of the source branch `draw-optimization`. PR 1 lands every+commit except `e72b610` as a cherry-pick under a new hash; the engine modules of+`e72b610` land in the separate engine PR.++| Commit | Step |+|---|---|+| `417da63` | Committed per-pass count probe for every scene (S1) |+| `e72b610` | Engine: `src/rigid-merge.ts` and `src/extension-compat.ts`, unbundled modules (S2) |+| `ced34bb` | Scene-kit multisample discard knob, per-scene tiers (S3) |+| `5042a16` | Probe `--query` for same-build A/B |+| `57177cf`, `75751ec` | D-46 to D-63, D-64 |+| `67cafa4` | Interleaved A/B timing runner and kit (S6) |+| `2bd021e`, `0806baa`, `8d95fec` | Kit: rigid merge; shadow cache, once-per-frame, threshold, stand-ins, pass stand-ins; review hardening |+| `95996dc` | Foundry Floor planting through one material graph |+| `1c4ae4f`, `0174e7d` | Farm hero merge, stand-ins, cached shadow, threshold; review tuning |+| `d2d1cfd`, `892d103` | Golden Gate bridge merge, once-per-frame shadow, stand-ins, reflection stand-ins; kerb depth-tie fix |+| `4383a1a`, `dc77f27`, `bf4b2dd` | Before/after parity tools and the X-02 re-baselines (S5) |+| `7db7325` | `kiln-compose-scene` skill and runtime-scenes reference (S7) |++## Diagnosis (S1)++The committed probe (`scenes/scripts/count-probe.ts`, kit `probeFrames`) records the+following for every scene, tier and named view or workload:+- draws per render pass;+- pipelines and triangles;+- attribution by system;+- count-only what-ifs.++It covered 204 fixtures, all stable. GPU draws equal JS draws everywhere, and every+what-if restores its baseline. The ranked levers are in+`scenes/evidence/counts/draw-base/levers.md` (ignored, local only). The short version:++- **Farm:**+ - The shadow pass was 270 of 583 draws at the landing view. A cached static map+ removes all of it while nothing moves.+ - Heroes were 198 main and 198 shadow draws.+ - A 2-texel small-caster threshold drops 59, 25 or 2 casters (economy, balanced,+ high).+ - Woodland packing at minimal would save up to 48 draws. That is an owner tier+ decision.+- **Golden Gate:**+ - The bridge web was 148 of 180 draws at minimal and 366 of 432 at high, and+ the only lever on the low tiers.+ - The shadow map rendered twice a frame, because the planar reflector's camera+ triggers a second render.+ - The reflection redrew 50-180 draws.+- **Foundry Floor** is the control scene:+ - The fab already draws 39-134 in 6-7 pipelines, using an anchor bake per entity+ and material.+ - Campus planting compiled one pipeline per draw.++## Phase 0 engine (S2)++These modules (`e72b610`) are not in PR 1; they land in the engine PR described in+`docs/reviews/2026-10-02-draw-optimization-engine-handoff.md`.++`mergeRigidGroups` merges by material inside rigid groups. Its boundaries are:+- animation targets;+- `Joint_*` pivots;+- nodes with Kiln semantic extras;+- relationship targets;+- LOD and visibility nodes.++It also locks blended and transmissive materials and validates each bucket before+changing anything. A test failed first (expected 11, received 16) and now passes.+For `farmhouse.glb`:+- draws go from 16 to 11;+- `Joint_FrontDoor` keeps its 2 primitives and 132 triangles;+- triangles stay at 4,080;+- bounds drift is 0.++`extension-compat.ts` flags extensions marked required against six destinations+(three, Godot, Unity glTFast, Unreal, Bevy, Blender), with 12 tests.++Wiring the merge into `optimize:'full'` is held (see the open decisions).+`src/render.ts` and `dist/` are `v1-readiness` files, and the bundle test checks+`dist/` byte for byte. The patch and its test updates are in+`tmp/drawcalls/phase0/wiring.patch` (ignored, local only); all 401 optimize-related+tests pass with it.++## Multisample store (S3, OD-10)++**Verdict: confirmed, narrower than first suspected.**++three r186 always stores the 4x colour and depth of the canvas frame-buffer target+after the resolve. That is a conservative default, not a three.js bug:+- the store is wasted where the main pass is never split;+- it is required where a mid-pass `viewportDepthTexture` copy restarts the pass+ with Load (Golden Gate medium and high water).++Scene-kit sets the store flags per tier. Trip-wires fail loudly in test and dev+when a pass would reload the attachments. Pin tests read three's build.++| Check | Result |+|---|---|+| Browser frames sampled | 190 |+| Mutations caught | 14/14 |+| Pixel parity | B-06 144/144; every Foundry fab and planting-off capture byte-identical |+| Hub timing | no measurable change |+| Tablet, Farm minimal | GPU busy 93% → 85% at 60 fps |+| Tablet, Golden Gate minimal | GPU busy 85% → 82% |+| Tablet, Farm economy (GPU-bound) | frames within one refresh 39.9% → 48.8%, 37.5 → 39.8 fps |++three r186 makes the attachments transient when the store flags are false, and the+tablet supports `TRANSIENT_ATTACHMENT`. The issue, how it was found and the fix+are on a private report page (owner). Nothing was posted upstream.++## Scene-kit features (S4, S4b)++All are opt-in, covered by tests, and pinned to three r186 where they rely on its+internals.++- **`mergeRigidByMaterial`** merges per (anchor, material, attribute layout,+ shadow and render flags).+ - Anchors keep their identity, transform and children; sources are hidden, not+ removed.+ - The bake is bit-exact on identity and translation paths.+ - Options:+ - `layout: 'source'` mirrors the source interleaving, which saves the Farm 2-3+ pipelines;+ - an `order` hook settles coplanar depth ties.+- **`shadowStandIns`** builds position-only depth proxies per anchor, side and+ optional cell.+ - Excluded materials are counted by reason, and sources outside `shadowMask` are+ skipped.+ - Pass stand-ins (`mainOnly`, `passStandIn`, `passCameraLayers`) route content+ between the main pass and an extra pass by layer.+- **`cachedSunShadow`** keeps a static map rendered only when armed and a live map+ for casters observed to move.+ - Casters return to the static map after 30 still frames; the two maps are+ sampled as `min`.+ - `prime()` is called when the world is revealed; `track()` returns `untrack`,+ and a `live()` option marks motion the watch cannot see.+ - It throws on a late install.+- **`shadowOncePerFrame`** renders the sun map once a frame when a second camera+ would render it again. It throws when three would fall back to each viewing+ camera's mask.+- **`smallCasterThreshold`** stops casters under N shadow texels from casting,+ measured with the same bounding sphere as the probe.++Where each one is on:++| Feature | Farm | Golden Gate | Foundry Floor |+|---|---|---|---|+| Rigid merge | heroes per anchor and material, source layout | bridge per (south, north, span) × material, curb order | no (control scene) |+| Shadow stand-ins | 71 hero proxies (shadow tiers) | 7 bridge and approach proxies (high) | no shadows |+| Cached static + live shadow | on (shadow tiers) | wired, off: no gain while driving | no shadows |+| Once-per-frame shadow | not needed (one camera) | on (high) | no shadows |+| Small-caster threshold | 2 texels (shadow tiers; farmers keep detail) | not applicable once stand-ins cover every caster | no shadows |+| Reflection stand-ins | no reflection | far approaches in the reflection (high) | no reflection |+| Multisample discard | every tier | low tiers (no mid-pass copy) | every tier |+| Shared material graph | — | — | campus planting |++## Per scene (S5)++### Farm++- **Counts:** see the headline.+ - The static map re-renders only on events: 115 / 128 / 141 draws in 12+ pipelines (economy / balanced / high).+ - With the clock running, the landing view draws 315 / 313 / 326 / 337 a frame+ (minimal to high), against 345 / 583 / 583 / 583 before.+ - B-07 is unchanged: batching 83/54/2000/2004/11, frozen 555/4191, hidden roots+ 575, dynamic roots 34.+- **Interaction:** the adversarial review exercised every door and gate, the+ rotors, tractor drive, farmer play and walk on WebGPU and WebGL2.+ - Leaf and shadow both move, and settle back into the static map.+ - Colliders are identical: 13 / 95,382 / 14,468.+ - Seven tier remounts gave no errors and no growth.+ - Nothing is created after ready.+- **Parity:** 86/86 cases pass B-06 and the thin-line check (pixels over 32 levels,+ budget 100):+ - WebGPU: 20 views at 4 tiers;+ - WebGL2: 6.+- **Pilot parity** (D-53, D-64) did not run in S5. The decision sweep of 2 October+ ran it as D20 against the sealed r34 pilot, on WebGPU and WebGL2. Standalone runs+ failed a different view for each build, for reasons in the tool (a loose phase+ capture, animations it cannot align). Captured at the same pilot phase,+ draw-after and draw-base got the same verdict in 17 of 17 pairs, so all 17+ same-phase pairs pass: the cycle did not change pilot parity. The pairs came+ from a prototype script,+ `tmp/drawcalls/decisions/decide-sweep/e2-samephase.ts` (ignored, local only).+- **OD-4 shadow changes** at economy (2 texels = 34 cm):+ - the trailer drawbar, hitch ring and hitch pin stop casting (146 px over 8+ levels);+ - sheep leg segments and other herd parts drop a few one-texel blocks (up to 69+ px);+ - one texel of a trailer hub goes;+ - balanced changes 5 px or fewer.++ The farmers keep their small parts, so the player's shadow keeps its neck and boot+ contact. Images: `tmp/drawcalls/s5/images/farm/` (ignored, local only; also on+ the private report page).+- **Merge pixels** (OD-18): isolated flips on the barn cupola louvres and the+ watermill corner speckle, up to 153 px over 8 levels; they pass both checks.+- **X-02** now compares against `packages/farm/fixtures/x02-baseline.json` (D-64).++### Golden Gate++- **Counts:** see the headline.+ - High shadow passes go from 36 to 18 over the fixtures; shadow draws go from+ 1,746 to 104.+ - Reflection draws go from 2,163 to 773.+ - Main-pass draws at high go from 2,231 to 811.+- **Parity:** 488 of 489 cases pass in the S5 parity run, over day, golden and fog+ presets on WebGPU and WebGL2. That count is too high: the run covered golden-hour+ side-full only at high on WebGPU, and the view also fails at economy and+ balanced (193 px) and on High WebGL2 (200 px).+ - **The failure:** golden-hour side-full has 193 px over 32 levels at high (200+ on WebGL2), against a budget of 100; B-06 passes. It comes from the tower ribs+ against their panels: a depth tie that the merge settles in one fixed order+ where the per-mesh sort used to vary with the view.+ - **Accepted residuals:** golden arrival 74 px, day span 52, low shore+ reflections 21-35.+ - **Kerb stipple:** the review found it (the merge put the curbs after the+ coplanar walks). It is fixed at no extra draws.+- **F2** is not applied. Traffic and fog banks appear in the reflection exactly as+ before; the image pair is on the private page.+- **The cached shadow stays off.** While driving, the static map re-arms on 104 of+ 120 frames, so it adds a pass and a second shadow lookup for nothing.+- **X-02** has a new baseline from `perf-local.ts`, recorded in+ `packages/golden-gate/PERFORMANCE.md`.++### Foundry Floor (control)++- **Counts:** campus fixtures fall 11-13%; planting goes from 12 to 6 draws at the+ campus view and from 39 to 14 at the roundabout. Pipelines bound fall by about+ half; triangles are equal. The fab is unchanged (745 draws over its fixtures).+- **Parity:** 160/160 cases pass.+ - The worst is 181 of 921,600 px, at planting part edges.+ - All 48 fab captures and all 40 planting-off captures are byte-identical to+ the old build.+- **Count baseline:** a first one, in `packages/foundry-floor/fixtures/count-baseline.json`.++## Timing (S6)++The timing uses quiet hosts only (OD-5).+- **Hub:** quiet checks before and after every block, and headed runs at 120.114 Hz.+- **Tablet:** a Samsung SM-X518U (Mali-G68, Chrome 154, 60 Hz) on the device kit.+ - Thermal status stayed at none, with the battery at 24.3-28.1 °C.+ - Every adb mapping was removed and verified empty.+- **This PC:** it failed its quiet check twice (CPU 65% and 29.8%), so it was not+ timed.++**Method:** draw-base (A) against draw-after (B).+- Each cell runs 3 interleaved pairs (A B, B A, A B).+- Each run is a fresh page, a 5 s warm-up, then a 60 s sample.+- 196 of 198 runs were valid. The two invalid runs came from a display-rate probe+ that Chrome throttled; the probe is fixed in `69f92fe`, and the cells were rerun+ at 12/12.+- "Within 1" and "Within 2" are the shares of frames that land within one and two+ display refreshes.++The full tables, load samples and draw cross-checks are in+`tmp/drawcalls/s6/timing-full.report.md` (ignored, local only). Evidence is in+`scenes/evidence/perf/{hub,tablet}-2026-10-02/` (ignored, local only).++**Tablet, minimal** (its tier, D-25). Both builds hold 60 Hz, p95 stays within OD-7+(33.3 ms), and D-41 passes in every run.++| Cell | p95 ms A → B | Within 1 refresh A → B | Within 2 refreshes A → B | Mali GPU busy A → B (pairs lower) | Draws A → B |+|---|---|---|---|---|---|+| Farm hero | 16.7 → 16.7 | 100 → 100% | 100 → 100% | 92 → 87 (3/3) | 280 → 255 |+| Farm walk | 16.7 → 16.7 | 100 → 100% | 100 → 100% | 84 → 83 (mixed) | 110 → 102 |+| Foundry Floor campus | 16.7 → 16.7 | 100 → 100% | 100 → 100% | 82 → 80 (mixed) | 77 → 72 |+| Foundry Floor drive | 17.2 → 16.7 | 96.3 → 100% | 100 → 100% | 92 → 82 (3/3) | 148 → 135 |+| Golden Gate arrival | 16.7 → 16.7 | 100 → 100% | 100 → 100% | 87 → 83 (3/3) | 140 → 36 |+| Golden Gate drive | 16.7 → 16.8 | 98.4 → 98.3% | 100 → 100% | 93 → 90 (3/3) | 128 → 50 |++Busy alone understates the GPU savings. The Mali clock changes with load, so the+same busy share at a higher clock is more work; read as busy × clock, Farm walk+falls by 15% and Foundry Floor campus by 24%, where the busy column reads mixed.++In the Foundry Floor drive, the old build misses vsync throughout: its longest frame+is 33.8 ms, against 17.8 ms after.++**Tablet, economy** (OD-12). This tier is GPU-bound in both builds, with GPU busy at+91-95%. The new build delivers more frames from the same GPU budget.++| Cell | p50 ms A → B | p95 ms A → B (OD-7 ≤ 33.3) | Within 1 refresh A → B | Within 2 refreshes A → B | fps per run A → B | D-41 runs passing A → B |+|---|---|---|---|---|---|---|+| Farm hero | 33.2 → 16.7 | 33.3 → 33.3 | 39.9 → 61.2% | 99.9 → 99.9% | 37.5 → about 43.4 | 2/3 → 3/3 |+| Farm tractor-drive | 33.1 → 16.6 | **33.4 (over)** → 33.3 | 39.0 → 81.9% | 99.9 → 100% | 35.7-44.4 → 49.5-56.5 | 3/3 → 3/3 |+| Golden Gate arrival | 16.6 → 16.6 | 33.2 → 16.7 | 86.4 → 97.9% | 99.8 → 100% | 52.9 → 58.9 | 3/3 → 3/3 |++The old build broke OD-7 on the Farm tractor drive at economy; the new build meets+it. Farm hero still misses about 39% of refreshes at economy, so the tablet tier+stays the owner's call.++**Hub** (GTX 1660 Ti Max-Q, 120 Hz). Every run in both builds sits at p50 8.3 and+p95 8.4 ms, because the hub is vsync-limited. The change shows in CPU render time,+draws and pacing instead.++| Cell | CPU render ms A → B | Draws A → B | Within 1 refresh A → B | GPU busy A → B |+|---|---|---|---|---|+| Farm hero, high | 5.5 → 1.6 | 583 → 330 | 98.6 → 99.9% (longest 25.0 → 16.8 ms) | 53 → 53 |+| Farm hero, balanced | 5.1 → 1.6 | 583 → 321 | 96.9 → 99.9% | 50 → 52 |+| Farm hero, economy | 5.2 → 1.3 | 583 → 313 | 99.7 → 99.9% | 44 → 43 |+| Farm walk, high | 3.9 → 2.0 | 365 → 153 | 99.8 → 99.9% | 52 → 46 |+| Farm tractor-drive, high | 4.0 → 2.0 | 399 → 190 | 99.8 → 99.9% | 55 → 52 |+| Golden Gate arrival, high | 1.7 → 1.1 | 432 → 103 | 99.9 → 99.7% | 58 → 55 |+| Golden Gate flyover, high | 1.5 → 1.1 | 324 → 93 | 99.8 → 99.9% | 57 → 52 |+| Golden Gate arrival, minimal | 2.2 → 1.6 | 180 → 52 | 99.9 → 99.9% | 39 → 39 |+| Foundry Floor campus, high | 2.0 → 1.8 | 102 → 96 | 99.9 → 99.8% | 39 → 39 |++Within 2 refreshes is 100% in both builds in every hub cell.++- **D-41:** 131 of 132 hub runs pass. The failure is Golden Gate flyover at minimal,+ B pair 3: one frame of 50.1 ms, 0.1 ms over. Every flyover run in both builds has+ its longest frame at the same moment, 25 s in, when the flight changes (A 41.6 /+ 33.2 / 41.7 ms; B 41.6 / 41.7 / 50.1 ms). So three pairs cannot attribute it to+ the change.++ A 5-pair rerun on the quiet hub settled it: 20 of 20 runs were valid. The stall+ appears in every run of both builds at 24.9-25.1 s.+ - Median stall: minimal 41.6 ms (before) and 41.7 ms (after); high 33.3 and+ 25.0 ms.+ - The after build was shorter in 3 of 5 pairs.+ - At minimal, both builds hit six-refresh stalls: before 49.9 and 50.0 ms, after+ 50.0 and 50.1 ms. Six refreshes take 49.95 ms, so the same stall passes or+ fails the 50 ms rule on jitter.+ - D-41: before 5/5 and 5/5; after 4/5 at minimal and 5/5 at high.++ The flight-change stall is a pre-existing scene hitch, not caused by this cycle.+ Fixing it is separate work.+- **GPU busy at balanced** rose 2-4 points in all three pairs, at matching clocks.+ This metric is a 5 s share-of-time sample from `nvidia-smi`. GPU timestamp+ queries would measure GPU time per frame; the adapter exposes `timestamp-query`.++**Pending runs**, with exact commands in the timing report:+- Hub balanced and economy beyond Farm hero and Golden Gate arrival: 14 cells,+ about 1 h 45 min.+- Golden Gate hero orbit (arrival was run instead).+- Foundry Floor economy on the tablet: no longer pending; it has since run.+- Any run on this PC, once it passes its quiet check.++## What worked where++| Lever | Farm | Golden Gate | Foundry Floor | Lesson |+|---|---|---|---|---|+| Cached static shadow + live map | Biggest win: 270 → 0 settled, 31-54 with life | No gain: the fitted shadow box follows the car | — | Pays only where the shadow frustum is still |+| Depth stand-ins | 198 hero shadow draws → about 71 proxies; matters on static re-renders and movers | 150 casters → 7 proxies | — | Build before merging; chunk long structures |+| Once-per-frame shadow | — | Halves the shadow cost with a reflector | — | Needs a shadow mask with a bit above layer 0 |+| Merge by material within anchors | −30 main draws, look-neutral, interaction intact | The only low-tier lever: 148 → 20 bridge draws | — | Check coplanar faces across parts: merge order decides depth ties |+| Reflection stand-ins | — | Reflection 178 → 49 at arrival | — | Keep the reflection's content contract (F2) separate |+| Small-caster threshold | −59 casters at economy | Not applicable | — | Exempt actors whose contact shadows read |+| Multisample discard | Tablet GPU busy −8 points | −3 points at minimal | Pixel-neutral control | No desktop effect; pays on tile-based mobile GPUs |+| Shared material graph | — (heroes are textured) | — | Pipelines −50% on campus | Pipelines, not draws, were the cost |++## Open decisions for the owner++The owner answered all ten on 2 October in a wider decision sweep: the scene+answers are in `scenes/DECISIONS.md` from D-65, the engine answers in+`docs/reviews/2026-10-02-draw-optimization-engine-handoff.md`.++1. **Engine wiring** of `mergeRigidGroups` into `optimize:'full'`:+ - (a) commit regenerated `dist/` here and regenerate at rebase; or+ - (b) wait until `v1-readiness` merges (recommended, OD-1).+2. **`expandSharedMeshes` default.** Golden Gate gets either:+ - 11 draws with a 25% larger file (shared meshes copied, today's default); or+ - 104 draws with an 8% larger file.+3. **F2:** remove traffic and fog banks from Golden Gate's reflection, per its spec.+ That is a visible change.+4. **OD-4 images:** accept the economy small-caster changes on the private page (or+ exempt the trailer hitch).+5. **Golden Gate tower depth tie:** accept 193 px at golden-hour side-full, or keep+ the tower ribs unmerged for a few draws. Correction: keeping the ribs unmerged+ also fails, at 177 px.+6. **OD-9 live map size:** full size is the default. `?liveMapSize=1024` at high+ saves 25.2 MB at a small look risk.+7. **Woodland packing at minimal** (Farm, up to −48 draws on the tablet tier).+8. **Cross-placement hero instancing:** gates 24 → 4 and farmers 60 → 30. It+ changes B-07 counts and pitchfork visibility handling.+9. **Foundry campus structures instancing** (78 → about 16 draws). It replaces+ exported materials.+10. **The tablet's default tier** (OD-12), with the economy numbers above.++## Feedback map++Proposals unless marked as applied. Engine and model-facing changes wait for+`v1-readiness` (OD-1).++**Engine tools**+- Wire `mergeRigidGroups` (decisions 1 and 2) and report merged draws per anchor in+ the export summary.+- Surface `extension-compat` results in `kiln_export` and `kiln_inspect` output.+ This changes the schema, so it needs versioning.+- Add a per-asset draw estimate to inspection: draws as authored, after a merge+ within anchors, and the shadow casters below 2 texels at a stated texel.+- Flag mirrored tangent-bearing parts and coplanar faces shared across parts or+ materials. The Golden Gate kerb shows both are depth-tie risks once merged.++**Authoring and QA skills** (`v1-readiness` owns them; proposals)+- `kiln-author-asset` geometry recipes:+ - keep moving parts as named `Joint_*` pivots;+ - budget materials per rigid group (draws per anchor equal its material count);+ - avoid coplanar faces across separate parts;+ - fold tiny separate parts (eyes, bolts, hubs) into their parent's material when+ they never move.+- `kiln-qa-asset`: in the destination, check draws per anchor and material, and+ check that interaction survives a merge.++**Scene-kit**+- Applied: the rigid merge, the shadows module, pass stand-ins, the multisample+ knob, and the probe with `--query` and settled probing.+- Proposed:+ - choose `layout: 'source'` per bucket automatically;+ - add a probe what-if that pauses kit-installed shadow re-arms;+ - detect morph-target motion;+ - verify the cache on WebGL2 hardware beyond the Farm;+ - add an R8 shadow colour target after a WebGL2 check.++**Compose-scene skill** (applied, OD-16)+- `skills/kiln-compose-scene` and its runtime-scenes reference now carry the proven+ techniques and their measured effect.++**Project conventions**+- Every scene keeps a committed count baseline with provenance and runs it before+ release. Foundry Floor's new check should join the portable gate.+- Count tests under `scenes/scripts/tests/` are not in `bun run test` (the portable+ runner reads package test folders only). Move the offline ones, or add the+ folder.+- Parity uses B-06 plus a thin-line budget (pixels over 32 levels), the same build+ with each lever off, and a repeat for the noise floor.+- Report cached features settled and with the clock running.+- Probe and time workloads at pinned poses. Drive fixtures that run on wall-clock+ delta are workload state, not evidence of change.++## Evidence++The following are ignored local paths in the worktree:+- `scenes/evidence/counts/{draw-base,draw-after,...}`;+- `scenes/evidence/draw-after/<scene>/` (count tables, parity, images);+- `scenes/evidence/perf/{hub,tablet}-2026-10-02/`.++Reports are under `tmp/drawcalls/` (`understand/`, `wave-a/`, `wave-b/`,+`wave-b-review/`, `s5/`, `s6/`), which is ignored and local only too.++Gates are listed in the last section.++## Gates++All gates were run on HEAD `69f92fe`. Logs are in `tmp/drawcalls/gates/final/`+(ignored, local only).++On 2 October the landing branch `draw-optimization-landing` (on `main` `a396612`)+reran `bun run check:skills` (pass) and the scenes gates: typecheck pass, lint 0+findings, test 525 pass, 30 skip, 0 fail. The 8 skips beyond the 22 below are+suites whose ignored staged inputs a fresh worktree does not have (Golden Gate's+vehicle models, 7; Foundry Floor's saved plants, 1).++**Engine**++| Gate | Result |+|---|---|+| `bun run typecheck` | pass |+| `bun run lint` | pass |+| `bun run test` | 3,070 pass, 2 skip, 0 fail |+| `bun run test:render-service` | 78/78 |+| `bun run test:coverage` | functions 95.28% (minimum 94.00%), lines 92.55% (minimum 92.10%) |+| `bun run check:skills` | pass |++**Scenes**++| Gate | Result |+|---|---|+| `bun run typecheck` | pass |+| `bun run lint` | 0 findings |+| `bun run test` | 533 pass, 22 skip, 0 fail |+| `bun test scripts/tests` (not part of `bun run test`) | 58/58 |++Public builds stay within the D-15 ceilings:++| Scene | Size change, bytes / gzip | Gzip headroom left |+|---|---|---|+| Farm | +18,939 / +7,158 | 35,468 |+| Golden Gate | +14,183 / +5,628 | 6,347 |+| Foundry Floor | +4,200 / +1,580 | startup chunk 1,414,442 of 1,750,625 |++Bundle hygiene finds 0 hits in all 12 public files.diff --git a/scenes/DECISIONS.md b/scenes/DECISIONS.mdindex 33ce5e61..f3be8205 100644--- a/scenes/DECISIONS.md+++ b/scenes/DECISIONS.md@@ -85,6 +85,37 @@ This file is read-only for the builder. Where it and SPEC.md differ, this file w| D-43 | **Owner decision (2026-09-30, 09:38).** The model-sanity band is re-based on the twin at the adopted 4,500 wafer starts a month: the band becomes a regression band around the measured values (cycle time 8.32 d, WIP 50.1, 180 lots out, 61.8 moves an hour over days 30 to 60, seed 1), the three `test.failing` criteria become passing tests that guard drift, and the spec's band (14 to 23 d, 57 to 91, 110 to 130, 45 to 75) is recorded as superseded with the report's finding that the release rate alone cannot meet it. FF3 carries the change; the band width is set from the release sweep in `evidence/sim/retunes.json`. | Owner's words: "Re-band to the twin". Throughput equals the release rate, and the twin's variability does not produce the band's x-factor short of saturation. || D-44 | **Owner decision (2026-09-30, 09:38).** FF3 (the floor robots' moves and hand-offs, the humanoid mover class, with D-42 and D-43) starts today, once FF-C1 lands and passes the coordinator's review, on the fifth long-subagent slot of D-36, in parallel with the engine contracts. The site keeps the FF2 page until the owner switches it. | Owner's words: "After FF-C1 lands and passes review". The brief is `scenes/TASK-FF3.md`. || D-45 | **Owner decision (2026-09-30, recorded 12:09).** The campus gets a vegetation set (three broad-crown trees, two conifers, an ornamental tree, a shrub and a hedge segment, each with three declared LOD tiers) and freight vehicles (a day-cab tractor, dry-van, flatbed and tanker trailers, a delivery van), authored now in parallel by Codex `gpt-6.1-sol` at high effort in kiln-init workspaces on the 0.9.0 tarball (`showcase/authors/sol-ff-vegetation`, `sol-ff-freight`; briefs `pack2-research/terafab/briefs/campus-vegetation.md` and `campus-freight-vehicles.md`; sessions launched 12:06; events and final messages under `engine-work/dogfood-v09/codex-runs/`). After they land and pass the coordinator's review, a campus round (FF-C2) plants them from the campus data (avenue verges on the split road, windbreak belts behind the parking loops, parking aisle islands, the roundabout island with a ring of twelve conifers, a central grove of five broad trees and low hedges inside the kerb) and adds the truck classes to the traffic with a trailer follower. Owner's words: "dogfood should go to sol 6.1 on high - update codex cli to find this model and author now in parallel. everything is happening today." E-7 in `engine-work/v09/DECISIONS.md` records the dogfood split behind it. |+| D-46 | **Owner decision (2026-10-01, about 22:00).** Draw optimization runs in its own worktree off `main` (`C:/Users/Mattm/X/kiln-draw-optimization`, branch `draw-optimization`). Scene work goes ahead now. Model-facing engine changes (tool output, authoring and QA skills) wait for `v1-readiness` to merge, then rebase. | `v1-readiness` changes no file under `scenes/`, so scene work cannot collide with it. Plan of record: `docs/plans/2026-10-01-draw-optimization-cycle.md`. |+| D-47 | **Owner decision (2026-10-01, about 22:00).** The cycle covers Phases 0-1 of the draw-call research roadmap, then stops and reports. It covers all scenes, and its findings feed a report that upgrades or aligns the tooling, projects and skills for authoring scenes. | Owner's note on scope. |+| D-48 | **Owner decision (2026-10-01, about 22:05).** The success measure is frame time first. Draw count is also reported as a headline. Timing must come from clean data, because this PC is often under load. | Owner's words: draw count is "a metric that a lot of devs look at". |+| D-49 | **Owner decision (2026-10-01, about 22:05).** Small shadow changes are acceptable: tiny parts may stop casting, and stand-in outlines may differ slightly. Everything else stays at parity with the D-20 baseline, and every difference beyond parity is shown as images. | |+| D-50 | **Owner decision (2026-10-01, about 22:10).** Count metrics (draws, triangles, pipelines, CPU draw-call counts) may run anytime on this PC. Timing comes only from quiet hosts, with interleaved before/after (A/B/A/B) runs. | Counts are deterministic under load; frame times are not. |+| D-51 | **Owner decision (2026-10-01, about 22:10).** The coordinator may schedule tablet timing runs, using the device kit only while the tablet is quiet and cool, and removes the port mappings after each run. | |+| D-52 | **Owner decision (2026-10-01, about 22:10).** The tablet rule stays p95 ≤ 33.3 ms. Reports also give the share of frames within one and within two display refreshes, so that any restatement can be decided with data. | |+| D-53 | **Owner decision (2026-10-01, about 22:10).** X-02 (draws and triangles within 2% of the sealed pilot at high) is re-baselined on the optimized build. Pixel parity against the pilot remains. | The optimized build lowers draws on purpose, so a ±2% band around the pilot would fail by design. The re-baseline itself is recorded as a later decision. |+| D-54 | **Owner decision (2026-10-01, about 22:15).** Moving objects get a cached static sun shadow plus a small live map for movers, and both maps are sampled. | |+| D-55 | **Owner decision (2026-10-01, about 22:15).** The MSAA store-op suspicion must be confirmed by an adversarial review before anything is done. If it is confirmed, the scenes get an elegant fix, and a **private** artifact covers the issue, how it was found and what a fix would be. No three.js issue or PR is opened. | Owner's words: "i don't want to slop spam AI generated PRs or issues for three.js". |+| D-56 | **Owner decision (2026-10-01, about 22:15).** The shadow work applies to all three scenes: Farm, Foundry Floor and Golden Gate. | |+| D-57 | **Owner decision (2026-10-01, about 22:15).** The tablet stays on the minimal tier (D-25). The cycle brings economy before/after numbers; any tier change is the owner's call. | |+| D-58 | **Owner decision (2026-10-01, about 22:18).** Commits stay local on `draw-optimization`, made in logical steps. No push: push and PR are decided by the owner afterwards. | |+| D-59 | **Owner decision (2026-10-01, about 22:18).** No changes to `site/` and no deployment. Scene builds and staging happen only inside the worktree. | |+| D-60 | **Owner decision (2026-10-01, about 22:18).** The end report is a private artifact page (per-scene before/after, quiet-host timing, parity images, open decisions, feedback map) plus a dated `docs/reviews/` record on the branch. | |+| D-61 | **Owner decision (2026-10-01, about 22:18).** Feedback is applied now to `skills/kiln-compose-scene/` and its runtime-scenes reference. Changes to authoring and QA skills, tool output and project conventions are written as proposals in the report. | `v1-readiness` does not touch the compose-scene skill. |+| D-62 | **Owner decision (2026-10-01, 22:35).** The cycle analyses and implements across all scenes, not only the Farm. Foundry Floor and Golden Gate (robots, cars) give more useful performance data and a better feedback loop for judging whether the approach is right. | Owner's words: test the other scenes to get "more useful information and feedback into our feedback loop". |+| D-63 | **Owner decision (2026-10-01, 22:45).** Beyond Phases 0-1, the cycle also implements the scene-side merges that each scene's diagnosis proves look-neutral, in scene-kit and scene code only, with no engine changes. Examples are the Golden Gate bridge parts merged by material, and a Foundry-style anchor merge for the Farm's moving heroes with each moving group kept separate. Stand-ins cover every extra pass: the shadow pass and Golden Gate's planar reflection. | |+| D-64 | **Re-baseline under D-53 (2026-10-02, recorded by the coordinator).** X-02 compares each scene against its optimized `draw-after` build, keeping the rules: draws and triangles within ±2%, pipelines at most +5%.<br>• **Farm:** `packages/farm/fixtures/x02-baseline.json`. 16 views at high, 1280×720, one fresh page per view, settled shadow, WebGPU and WebGL2. Farm and kit sources at `0174e7d`. Pixel parity against the sealed pilot remains.<br>• **Golden Gate:** the `perf-local.ts` baseline, recorded in `packages/golden-gate/PERFORMANCE.md`. It has no pilot.<br>• **Foundry Floor:** `packages/foundry-floor/fixtures/count-baseline.json`. Its first count baseline, checked by `scripts/check-foundry-counts.ts`. | The optimized builds cut draws by design, so ±2% against the old counts fails everywhere: the Farm's old build is flagged on 16/16 views, and Golden Gate's old baseline passes 0/32 high views. Cross-build parity against `draw-base`: Farm 86/86, Golden Gate 488/489 (one thin-line case held for owner review), Foundry Floor 160/160. **Corrected 2026-10-02:** Golden Gate's 488/489 is too high. S5's parity run covered golden side-full only at high on WebGPU; the view also fails at economy and balanced (193 px) and on High WebGL2 (200 px). |+| D-65 | **Owner decision (2026-10-02, 12:53; sweep D16).** Sweep IDs (D1 to D34, D7b, D11b) are those of the 2 October decision sweep as `docs/plans/2026-10-02-draw-optimization-landing.md` lists them, not D- numbers of this file. **The tablet bar.** p95 at most 33.3 ms (D-52) and the D-41 hitch limits stay the gate. Adopting a change on the tablet also needs, in 3 of 3 interleaved pairs, the share of frames within one refresh not to fall by more than 1 point and busy × clock not to rise by more than 3%. A miss needs the owner's explicit acceptance. The bar applies to this tablet, the only X-07 device measured, and a higher GPU clock at the same frame rate counts as more GPU work. The timing runner's Mali clock and busy × clock columns: adopted; implementation follows in a later PR after the owner's trip. | On a 60 Hz tablet, frame time stays at 16.7 ms until the GPU runs out of headroom, so p95 moves only when it is too late. The Mali governor changes clock with load, so busy × clock, not busy alone, is the leading signal of GPU work. |+| D-66 | **Owner decision (2026-10-02, 12:53; sweep D17).** **Re-baselines.** A change that an owner decision adopts re-records its scene's count baseline in the same commit, without a decision of its own (D-53). The commit records provenance (build, commit, views, backends) and adds a one-line DECISIONS note naming the decision. | The owner already decides the change; the baseline records its consequence. D-64's bands still catch drift between decisions. |+| D-67 | **Owner decision (2026-10-02, 12:53; sweep D18).** **Thin lines in B-06.** The thin-line budget becomes part of B-06 for every scene, defined here: at most 100 pixels that differ by more than 32 levels beyond the repeat capture, per 1280×720 view. The accepted Golden Gate residuals are ratified: golden arrival 74 px, day span 52 px, low shore reflections 21-35 px. The check runs today as `--over32-budget 100` in the three draw-parity tools; moving it into `compareParityImages` for all three: adopted; implementation follows in a later PR after the owner's trip. | Tile-mean B-06 passed the Golden Gate kerb stipple and the tower tie; the thin-line count caught both. B-06's text is in kiln-commons, which is not versioned and is not edited, so the rule is defined in this repository. |+| D-68 | **Owner decision (2026-10-02, 12:53 and 13:08; sweep D20).** **Farm pilot parity.** Before/after parity gates every change. At each Farm release a paired audit runs on WebGPU and on WebGL2: the new build and the last accepted build are captured at the same pilot phase, and a view fails only where the new build fails and the accepted build passes. This amends "pixel parity against the pilot remains" in D-53 and D-64. The sweep's run is this cycle's pilot evidence: against the sealed r34 pilot, draw-after and draw-base got the same verdict in 17 of 17 same-phase pairs. The tool work (the busy-port fix, a paired mode promoted from the sweep's prototype script, and the re-baseline of B-07's texture golden: 39 at every view since the prewarm pass, 41 with the shadow cache) follows after PR 1, before the next Farm change. | Standalone pilot runs failed a different view for each build, for reasons in the tool (a loose phase capture, animations it cannot align). A pair cancels both and still audits drift from the pilot at every release. |+| D-69 | **Owner decision (2026-10-02, 12:54; sweep D15).** **Golden Gate reversed depth.** Golden Gate adopts reversed depth through a scene-kit renderer option, off by default, that Golden Gate opts into, with three adaptations under unit tests: the sky is drawn first without a depth test; the reflector's oblique projection is rebuilt for reversed depth; the polygon-offset sign is flipped. The 17 thin-line flags it raises against draw-after are accepted as corrections under D-67. It removes the tower depth tie, so sweep D7 and D7b are moot (D-75). Adopted; implementation follows in a later PR after the owner's trip. | The skyline flicker the owner saw on the hub and the tablet is depth precision: a standard buffer with a 0.5 m near plane and a 160 km far plane steps about 3 m at 5 km and 48 m at 20 km. The prototype took the tower tie from 193 px over 32 levels to 0 px over 8. |+| D-70 | **Owner decision (2026-10-02, 12:54 and 12:59; sweep D5 and D6).** **Golden Gate High reflection.** The High reflection drops the traffic, including the driven car, and the fog banks, as WATER-SPEC says (D5). The fog banks get a `hidden` flag that their update respects, in its own commit (D6). Both: adopted; implementation follows in a later PR after the owner's trip, with the count re-baseline under D-66. | WATER-SPEC leaves traffic and fog banks out of the reflection. The cycle kept them there (F2), because removing them is a visible change for the owner to decide. |+| D-71 | **Owner decision (2026-10-02, 13:08).** **Vegetation cards in the reflection.** Vegetation impostor cards stay in Golden Gate's High reflection. WATER-SPEC's "cards" is read as the fog cards it names at its line 36. No code change. | kiln-commons is not edited, so the reading is recorded here. |+| D-72 | **Owner decision (2026-10-02, 12:57; sweep D8).** **Farm economy small casters.** Economy exempts the trailer from the small-caster rule: `keepSmallCasters: ['farmer', 'trailer']`. Adopted; implementation follows in a later PR after the owner's trip, with image pairs, and the counts if they move. | At economy the 2-texel threshold stopped the trailer drawbar, hitch ring and hitch pin from casting (146 px over 8 levels). |+| D-73 | **Owner decision (2026-10-02, 12:58; sweep D11 and D11b).** **Farm woodland at minimal.** Minimal keeps its 64 woodland cells; woodland packing is not adopted. The gate's reason is the tablet's GPU cost: packing raised busy × clock by 4.5% to 27.2%, higher in 12 of 12 pairs. That replaces SPEC section 15's D-03 reason. No code change. | Packing saved up to 48 draws, but D-65 counts GPU work on the tablet, and packing added it in every pair. |+| D-74 | **Owner decision (2026-10-02, 12:58; sweep D14).** **Tablet tier.** Minimal stays the tablet's tier in every scene; D-25 and D-57 stand. Golden Gate at economy may be revisited after its flyover stall is fixed (D-75). No code change. | Golden Gate at economy held 97.7-98.2% of frames within one refresh against 100% at minimal, about 2 points, outside D-65's margin. |+| D-75 | **Owner decisions (2026-10-02, 12:54 to 13:06).** **Answers that change nothing:** sweep D7 and D7b (moot: reversed depth removes the tower tie, so there is no tower split); D9 (the live map stays at full tier size); D10 (the Farm hero merge stays variant A); D12 (no hero instancing across placements); D13 (the Foundry Floor campus structures stay as they are); D28 (the tractor's sealed kinematics stay).<br>**Backlog:** D22 (the three pre-existing stalls, after PR 1; the Golden Gate flyover fix comes before any Golden Gate tier change); D25 (an R8 shadow colour target); D26 (scene-kit correctness soon after PR 1: anchor names, and morph-target and `positionNode` motion detection); D27 (Golden Gate loads `data/layout.json` at run time after PR 1; its other deferred items stay in the backlog); D33 (the next performance cycle targets GPU work: per-tree culled packing, then vegetation LOD). | The owner took the recommended option on every question. |+| D-76 | **Owner decisions (2026-10-02, 13:00 to 13:06; sweep D1, D4, D19, D21, D24, D29, D30, D31, D32).** **Landing.** Two PRs (D1, D4). PR 1 carries every `draw-optimization` commit except `e72b610`, the records corrections (D30) and the compose-scene corrections (D24). PR 2, the engine work (`e72b610`, the `optimize: 'full'` wiring, D2, D3, D23 and D34), follows 0.10.0, which merged as `9375d04`; `docs/reviews/2026-10-02-draw-optimization-engine-handoff.md` describes it. The Farm ships at the next site build after the site's own Farm build check; Golden Gate and Foundry Floor are resealed later in one site change with an approved upload (D29, D-12). The leaked browser profiles were removed on 2 October (D32).<br>D19 (the portable runner includes `scenes/scripts/tests`, Golden Gate's count baseline JSON, glb-world's staged path, a release checklist), D21 (the 14 hub cells at balanced and economy and the Golden Gate hero orbit, on a quiet hub), D31 (one compose-scene dogfood session each in Agy and OpenCode) and D32 (`launchChrome` removes its profile on close, with a test): adopted; implementation follows in a later PR after the owner's trip. | The owner split the landing on 2 October: "avoid tedium and ceremony; get this over the line". |## D-18: the look of the scenesdiff --git a/scenes/package.json b/scenes/package.jsonindex af3449f0..82d459fd 100644--- a/scenes/package.json+++ b/scenes/package.json@@ -22,6 +22,8 @@"check:site-compat": "bun scripts/check-site-compat.ts","stage:farm": "bun packages/farm/scripts/stage-assets.ts","perf:farm": "bun packages/farm/scripts/perf.ts",+ "build:scene": "bun scripts/build-scene.ts",+ "probe:counts": "bun scripts/count-probe.ts","spike:build": "vite build --config packages/scene-kit/spike/vite.config.ts","spike:test": "bun scripts/run-m0.ts"},diff --git a/scenes/packages/farm/fixtures/x02-baseline.json b/scenes/packages/farm/fixtures/x02-baseline.jsonnew file mode 100644index 00000000..43314ec9--- /dev/null+++ b/scenes/packages/farm/fixtures/x02-baseline.json@@ -0,0 +1,322 @@+{+ "schema": "kiln.farm-x02-baseline/1",+ "decision": "OD-8 (D-53): X-02 re-baselined on the optimized build; pixel parity against the sealed pilot (B-06) is unchanged",+ "rule": "Inclusive ±2% draws (renderer.info drawCalls of one frame, shadow passes included) and triangles; pipeline cache at most +5% of this reference",+ "provenance": {+ "build": "draw-after",+ "commit": "0174e7da6a75f3abf57c49b93db872bc03c6713c",+ "chunks": [+ "index-oAhThwe1.js"+ ],+ "source": "working tree; Farm and kit sources last changed in 0174e7d, clean at HEAD 7db7325 when measured",+ "tool": "scripts/farm-x02-baseline.ts measure --build draw-after",+ "date": "2026-10-02",+ "browser": "headless Chrome/154.0.8037.58",+ "viewport": "1280x720 CSS at device scale 1 (B-06 normalization)",+ "pagePolicy": "one fresh page per view and backend"+ },+ "conditions": {+ "tier": "high",+ "viewport": [+ 1280,+ 720+ ],+ "freshPage": true,+ "clock": "frozen",+ "settled": true+ },+ "backends": {+ "webgpu": {+ "hero": {+ "kind": "named view",+ "drawCalls": 283,+ "triangles": 1884297,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "opposite": {+ "kind": "named view",+ "drawCalls": 283,+ "triangles": 1884297,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "top": {+ "kind": "named view",+ "drawCalls": 283,+ "triangles": 1884297,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "eye-height": {+ "kind": "named view",+ "drawCalls": 239,+ "triangles": 1832662,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "crops": {+ "kind": "named view",+ "drawCalls": 263,+ "triangles": 1875737,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "fences": {+ "kind": "named view",+ "drawCalls": 280,+ "triangles": 1879969,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "props": {+ "kind": "named view",+ "drawCalls": 104,+ "triangles": 1532872,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "watermill-wheel": {+ "kind": "named view",+ "drawCalls": 42,+ "triangles": 877726,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "watermill-interior": {+ "kind": "named view",+ "drawCalls": 35,+ "triangles": 833520,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "house-interior": {+ "kind": "named view",+ "drawCalls": 123,+ "triangles": 1701084,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "house-porch": {+ "kind": "named view",+ "drawCalls": 258,+ "triangles": 1805146,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "house-window-out": {+ "kind": "named view",+ "drawCalls": 52,+ "triangles": 881794,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "play-yard": {+ "kind": "play fixture",+ "drawCalls": 91,+ "triangles": 1504427,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "play-house": {+ "kind": "play fixture",+ "drawCalls": 201,+ "triangles": 1676329,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "play-bridge": {+ "kind": "play fixture",+ "drawCalls": 69,+ "triangles": 865551,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "play-house-door": {+ "kind": "play fixture",+ "drawCalls": 201,+ "triangles": 1676329,+ "pipelines": 52,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ }+ },+ "webgl2": {+ "hero": {+ "kind": "named view",+ "drawCalls": 283,+ "triangles": 1884297,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "opposite": {+ "kind": "named view",+ "drawCalls": 283,+ "triangles": 1884297,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "top": {+ "kind": "named view",+ "drawCalls": 283,+ "triangles": 1884297,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "eye-height": {+ "kind": "named view",+ "drawCalls": 239,+ "triangles": 1832662,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "crops": {+ "kind": "named view",+ "drawCalls": 263,+ "triangles": 1875737,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "fences": {+ "kind": "named view",+ "drawCalls": 280,+ "triangles": 1879969,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "props": {+ "kind": "named view",+ "drawCalls": 104,+ "triangles": 1532872,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "watermill-wheel": {+ "kind": "named view",+ "drawCalls": 42,+ "triangles": 877726,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "watermill-interior": {+ "kind": "named view",+ "drawCalls": 35,+ "triangles": 833520,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "house-interior": {+ "kind": "named view",+ "drawCalls": 123,+ "triangles": 1701084,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "house-porch": {+ "kind": "named view",+ "drawCalls": 258,+ "triangles": 1805146,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "house-window-out": {+ "kind": "named view",+ "drawCalls": 52,+ "triangles": 881794,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "play-yard": {+ "kind": "play fixture",+ "drawCalls": 91,+ "triangles": 1504427,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "play-house": {+ "kind": "play fixture",+ "drawCalls": 201,+ "triangles": 1676329,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "play-bridge": {+ "kind": "play fixture",+ "drawCalls": 69,+ "triangles": 865551,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ },+ "play-house-door": {+ "kind": "play fixture",+ "drawCalls": 201,+ "triangles": 1676329,+ "pipelines": 21,+ "programs": 40,+ "geometries": 269,+ "textures": 41+ }+ }+ }+}diff --git a/scenes/packages/farm/src/World.tsx b/scenes/packages/farm/src/World.tsxindex 732525c5..2d7f3173 100644--- a/scenes/packages/farm/src/World.tsx+++ b/scenes/packages/farm/src/World.tsx@@ -1,6 +1,6 @@import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';import { useThree } from '@react-three/fiber';-import { asWebGPU, assertInstancingSafe, defineDevParams, readDevParams, SystemOrder, useBuilt, useLoadedPack, useQuality, useRegisterTestHooks, useSceneBuilt, useSceneClock, useSystem } from '@kiln-scenes/scene-kit';+import { asWebGPU, assertInstancingSafe, SystemOrder, useBuilt, useLoadedPack, useQuality, useRegisterTestHooks, useSceneBuilt, useSceneClock, useSystem } from '@kiln-scenes/scene-kit';import { buildFarmWorld } from './world/build-world';import { useFarmSession } from './state';import { FarmCameras } from './play/camera';@@ -9,6 +9,9 @@ import { useFarmWorkloads } from './play/workloads';import { bindFarmFrameGraph } from './world/frame-graph';import { startWarmPass, type WarmPass } from './world/prewarm';import { installInstanceAttributes, type InstanceAttributeRenderer } from './world/instance-attributes';+import { farmProbeHooks } from './world/probe-systems';+import { bindFarmShadow, farmShadowOptions } from './world/shadows';+import { readFarmDevParams } from './dev-params';import type { FarmWorld } from './world/build-world';export function FarmWorldContent() {@@ -16,17 +19,23 @@ export function FarmWorldContent() {const scene = useThree(state => state.scene), gl = useThree(state => state.gl), camera = useThree(state => state.camera), readyWorld = useRef<FarmWorld | null>(null);// SPEC 6.4 warm pass (owner decision 2026-09-29 22:05): the first world of a mount stays hidden until its pipelines are compiled.const warm = useRef<{ world: FarmWorld; pass: WarmPass } | null>(null), revealed = useRef(false);- const params = useMemo(() => readDevParams(defineDevParams({ woodlandTangents: { kind: 'boolean' }, staticBaseline: { kind: 'boolean' }, instanceUniforms: { kind: 'boolean' }, warmConcurrency: { kind: 'number' } })), []);+ const params = useMemo(readFarmDevParams, []), shadowOptions = useMemo(() => farmShadowOptions(params), [params]);// M4 item 1: instanced meshes read their matrices as vertex attributes (shared programs; uploads only when they change).// Test and dev builds keep three's per-mesh uniform buffers with ?instanceUniforms=1, and take ?warmConcurrency=<n>// (chains the warm pass compiles at once, default WARM_CONCURRENCY), for A/B checks.useLayoutEffect(() => params.instanceUniforms === true ? undefined : installInstanceAttributes(asWebGPU(gl) as unknown as InstanceAttributeRenderer), [gl, params]);const world = useBuilt(() => {- const built = buildFarmWorld(pack, quality.knobs, clock, { woodlandTangents: params.woodlandTangents !== false, prepared: session.prepared, optimize: params.staticBaseline !== true });+ // S4b/S4 (OD-18, OD-4): hero merge and, on tiers with shadows, stand-ins and the small-caster threshold; ?heroMerge=0,+ // ?standIns=0 and ?casterTexels=0 turn them off for A/B counts.+ const built = buildFarmWorld(pack, quality.knobs, clock, { woodlandTangents: params.woodlandTangents !== false, prepared: session.prepared, optimize: params.staticBaseline !== true,+ heroMerge: params.heroMerge !== false, shadow: { standIns: shadowOptions.standIns, minCasterTexels: shadowOptions.minCasterTexels } });if (!revealed.current) built.root.visible = false;return built;}, value => value.dispose(), [pack, quality.knobs, clock]);const frameGraph = useBuilt(() => world?.optimization ? bindFarmFrameGraph(scene, { root: world.root, registry: world.registry, optimization: world.optimization }, () => !!scene.getObjectByName('Farm lighting')) : null, binding => binding?.dispose(), [world, scene]);+ // OD-9: the lights' cached sun shadow (session.shadow, tiers with shadows) tracks this world once it shows.+ const shadow = useMemo(() => world ? bindFarmShadow(world, () => session.shadow) : null, [world, session]);+ useEffect(() => () => shadow?.dispose(), [shadow]);useEffect(() => { session.world = world; return () => { if (session.world === world) session.world = null; readyWorld.current = null; markBuilt(false); }; }, [world, session, markBuilt]);useEffect(() => () => { if (warm.current && warm.current.world === world) { warm.current.pass.dispose(); warm.current = null; } }, [world]);useSystem('farm-herd', SystemOrder.herd, () => {@@ -51,19 +60,27 @@ export function FarmWorldContent() {if (warm.current?.world !== world) {if (!scene.getObjectByName('Farm lighting')) return;warm.current?.pass.dispose();- warm.current = { world, pass: startWarmPass(asWebGPU(gl), scene, camera, world.root, { reveal: !revealed.current, concurrency: params.warmConcurrency }) };+ // The drawing frame is the reveal: the cached shadow re-arms its static map and draws every caster into its live map+ // once, so both maps' pipelines exist before ready (a later door, drive or walk compiles nothing).+ warm.current = { world, pass: startWarmPass(asWebGPU(gl), scene, camera, world.root, { reveal: !revealed.current, concurrency: params.warmConcurrency, onDraw: () => shadow?.prime() }) };}if (!warm.current.pass.step() || !session.orbit.current) return;readyWorld.current = world; revealed.current = true; markBuilt(true);}});+ // After every motion and visibility change of the frame (the follow rig hides Rowan at SystemOrder.camera).+ useSystem('farm-shadow', SystemOrder.shadows, () => { shadow?.update(); });const hooks = useMemo((): Record<string, (...args: any[]) => unknown> => { if (!world) return {}; return {counts: () => ({ ...world.stats,optimization: world.optimization ? { ...world.optimization.stats, frameGraph: frameGraph?.worldRoot === world.root ? frameGraph.stats : null } : null,frameGraph: frameGraph?.worldRoot === world.root ? frameGraph.stats : null, tangentOffenders: assertInstancingSafe(world.root),- warmPass: warm.current?.world === world ? { phase: warm.current.pass.phase, ...warm.current.pass.stats } : null }),+ warmPass: warm.current?.world === world ? { phase: warm.current.pass.phase, ...warm.current.pass.stats } : null,+ shadow: session.shadow ? { ...session.shadow.stats, reasons: { ...session.shadow.stats.reasons } } : null }),setAmbient: (enabled: boolean) => { session.ambientEnabled = enabled; if (!enabled) world.herd.stop(); },initialClips: () => world.placements.initialClips,+ // Count-probe systems and asset names (scene-kit testing/probe.ts), and a static-map re-arm so a probe can count one+ // static render; both fold away in public builds.+ ...(import.meta.env.KILN_TEST || import.meta.env.KILN_DEV ? { ...farmProbeHooks(world), shadowRearm: () => { session.shadow?.invalidate('probe'); return !!session.shadow; } } : {}),}; }, [world, session, frameGraph]);useRegisterTestHooks(import.meta.env.KILN_TEST || import.meta.env.KILN_DEV ? hooks : {});return world ? <><primitive object={world.root} dispose={null}/><FarmCameras layout={world.layout} sim={world.sim}/></> : null;diff --git a/scenes/packages/farm/src/constants.ts b/scenes/packages/farm/src/constants.tsindex f0975f09..4061d688 100644--- a/scenes/packages/farm/src/constants.ts+++ b/scenes/packages/farm/src/constants.ts@@ -41,4 +41,12 @@ export const FARM_DESTINATIONS = {paddocks: { position: [9.7, 0, 1.1], yaw: -Math.PI / 2 },bridge: { position: [19, 0, -22.7], yaw: Math.PI / 2 },} as const;+/**+ * S4/S5 on tiers with shadows (OD-9, OD-18): the cached static sun shadow with a live map for casters that moved (static+ * again after `settleFrames` still frames), hero depth stand-ins on `standInLayer` (never 0, below the kit's 30 and 31),+ * and casters under `minCasterTexels` shadow texels of the tier's map dropped inside stand-ins and from the herd batches.+ * Heroes of `keepSmallCasters` keep every part through that threshold: the player's own shadow is on screen in every play+ * frame, so at economy his neck, cuffs and boot contact stay in it (review RF-1); their parts still bake into stand-ins.+ */+export const FARM_SHADOW = { cache: true, standIns: true, minCasterTexels: 2, settleFrames: 30, standInLayer: 1, keepSmallCasters: ['farmer'] as readonly string[] };export const FARM_STRUCTURE = { batchingCell: 96, batchingOffset: 48, woodlandTrees: 843, woodlandCell: 64, woodlandSourceMeshes: 4, bvhLeafSize: 10, resolvePasses: 3, floorDrop: .35, porchFloorDrop: .25, routeSeconds: 30 };diff --git a/scenes/packages/farm/src/dev-params.ts b/scenes/packages/farm/src/dev-params.tsnew file mode 100644index 00000000..798c1c45--- /dev/null+++ b/scenes/packages/farm/src/dev-params.ts@@ -0,0 +1,16 @@+import { defineDevParams, readDevParams } from '@kiln-scenes/scene-kit';++export interface FarmDevParams {+ woodlandTangents?: boolean; staticBaseline?: boolean; instanceUniforms?: boolean; warmConcurrency?: number;+ heroMerge?: boolean; shadowCache?: boolean; standIns?: boolean; casterTexels?: number; liveMapSize?: number;+}+/**+ * Test and dev builds only (the literal folds away in public builds): A/B switches read from the page URL. M2-M4: woodland+ * tangents, the unbatched static baseline, three's per-mesh instance uniforms and the warm pass's concurrency. S4/S5: the+ * hero anchor merge, the cached sun shadow, hero shadow stand-ins, the small-caster threshold in texels (0 = off) and the+ * live map's size (unset = the tier's map size).+ */+export function readFarmDevParams(): FarmDevParams {+ return import.meta.env.KILN_TEST || import.meta.env.KILN_DEV ? readDevParams(defineDevParams({ woodlandTangents: { kind: 'boolean' }, staticBaseline: { kind: 'boolean' }, instanceUniforms: { kind: 'boolean' }, warmConcurrency: { kind: 'number' },+ heroMerge: { kind: 'boolean' }, shadowCache: { kind: 'boolean' }, standIns: { kind: 'boolean' }, casterTexels: { kind: 'number' }, liveMapSize: { kind: 'number' } })) : {};+}diff --git a/scenes/packages/farm/src/state.ts b/scenes/packages/farm/src/state.tsindex 40cf412c..3b0aa320 100644--- a/scenes/packages/farm/src/state.ts+++ b/scenes/packages/farm/src/state.ts@@ -1,6 +1,6 @@import { createContext, useContext } from 'react';import { createHudStore } from '@kiln-scenes/scene-kit';-import type { RigHandle } from '@kiln-scenes/scene-kit';+import type { CachedSunShadow, RigHandle } from '@kiln-scenes/scene-kit';import type { FarmWorld } from './world/build-world';import type { PreparedFarm } from './world/prepare';import { FARM_STRINGS } from './ui/strings';@@ -10,8 +10,10 @@ export function createFarmSession() {const hud = createHudStore<FarmHudState>({ status: '', interact: FARM_STRINGS.approach, canInteract: false, driving: false });return {hud, world: null as FarmWorld | null, prepared: null as PreparedFarm | null, orbit: { current: null as RigHandle | null },+ /** The lights' cached sun shadow on tiers with shadows (FarmLighting publishes it; the world tracks and updates it). */+ shadow: null as CachedSunShadow | null,view: 'hero', ambientEnabled: true,- dispose() { hud.dispose(); this.world = null; this.orbit.current = null; },+ dispose() { hud.dispose(); this.world = null; this.shadow = null; this.orbit.current = null; },};}export type FarmSession = ReturnType<typeof createFarmSession>;diff --git a/scenes/packages/farm/src/tiers.ts b/scenes/packages/farm/src/tiers.tsindex 0d725863..32187b3d 100644--- a/scenes/packages/farm/src/tiers.ts+++ b/scenes/packages/farm/src/tiers.ts@@ -22,6 +22,8 @@ const tier = (pixelRatioCap: number, pixelRatioMin: number, vegetationDensity: ndrawDistance: { far: 250, fogNear: 120, fogFar: 220, lodBias: 1, streamRadiusScale: 1, zoneHops: 1 },effects: { water: enabled ? 'full' : 'simple', wind: enabled, ambientAnimation: enabled },ladder: vegetationLadder(pixelRatioCap, vegetationDensity),+ // OD-10: no viewport-texture node or transmission splits the main pass at any tier.+ multisample: { discard: true },});export const farmTiers = defineTiers({order: ['minimal', 'economy', 'balanced', 'high'],diff --git a/scenes/packages/farm/src/world/build-world.ts b/scenes/packages/farm/src/world/build-world.tsindex 097f1f5a..bb53af3d 100644--- a/scenes/packages/farm/src/world/build-world.ts+++ b/scenes/packages/farm/src/world/build-world.ts@@ -18,7 +18,8 @@ import { optimizeFarmWorld } from './optimize';import { buildFarmColliders } from './colliders';import { createFarmSim } from '../play/sim';-export interface FarmBuildOptions { woodlandTangents?: boolean; prepared?: PreparedFarm | null; optimize?: boolean }+/** S4b `heroMerge` (default on); S4 `shadow`, hero stand-ins and the small-caster threshold, applied on tiers with shadows. */+export interface FarmBuildOptions { woodlandTangents?: boolean; prepared?: PreparedFarm | null; optimize?: boolean; heroMerge?: boolean; shadow?: { standIns: boolean; minCasterTexels: number } }export function readFarmLayout(pack: LoadedPack) {const bytes = pack.data.get('layout');if (!bytes) throw new Error('Farm layout is missing from the verified pack');@@ -68,7 +69,8 @@ export function buildFarmWorld(pack: LoadedPack, knobs: TierKnobs, clock: SceneC// independently of whether placement batching has been enabled yet.setCropShadows(placements.instances, false, false);root.updateMatrixWorld(true);- const optimization = options.optimize === false ? null : optimizeFarmWorld(root, placements.instances, woodland, { packWoodland: knobs.shadows.enabled });+ const optimization = options.optimize === false ? null : optimizeFarmWorld(root, placements.instances, woodland, { packWoodland: knobs.shadows.enabled,+ heroMerge: options.heroMerge, shadow: knobs.shadows.enabled && options.shadow ? { mapSize: knobs.shadows.mapSize, ...options.shadow } : null });if (optimization) registry.add(optimization.restore);if ((import.meta.env.KILN_TEST || import.meta.env.KILN_DEV) && !(options.optimize === false && options.woodlandTangents === false)) {const offenders = assertInstancingSafe(root);diff --git a/scenes/packages/farm/src/world/lighting.tsx b/scenes/packages/farm/src/world/lighting.tsxindex 55228ebe..2fad7851 100644--- a/scenes/packages/farm/src/world/lighting.tsx+++ b/scenes/packages/farm/src/world/lighting.tsx@@ -1,32 +1,41 @@+import { useMemo } from 'react';import { useThree } from '@react-three/fiber';-import { Group, HemisphereLight, DirectionalLight } from 'three/webgpu';+import { Group, HemisphereLight } from 'three/webgpu';+import type { Scene, Texture } from 'three/webgpu';import { asWebGPU, buildRoomEnvironment, useBuilt, useQuality } from '@kiln-scenes/scene-kit';+import type { TierKnobs } from '@kiln-scenes/scene-kit';+import { cachedSunShadow } from '@kiln-scenes/scene-kit/shadows';+import type { CachedSunShadow } from '@kiln-scenes/scene-kit/shadows';import { FARM_LOOK } from '../constants';+import { readFarmDevParams } from '../dev-params';+import { useFarmSession } from '../state';+import { createFarmSun, farmShadowMask, farmShadowOptions } from './shadows';+import type { FarmShadowOptions } from './shadows';-/** INV 4.1; the shadow projection is updated after every bound is assigned. */+/**+ * INV 4.1 lights. On tiers with shadows the OD-9 cached sun shadow is installed here, before any receiver builds (three r186+ * reads a light's custom shadow node once), and published on the session; it is disposed after the lights leave the scene.+ * With stand-ins the sun's own camera also sees their layer (a mask with a bit above 0 keeps its own layers).+ */+export function buildFarmLighting(scene: Scene, shadows: TierKnobs['shadows'], environment: () => { texture: Texture; dispose(): void }, o: FarmShadowOptions, session: { shadow: CachedSunShadow | null }) {+ const root = new Group(); root.name = 'Farm lighting';+ const hemisphere = new HemisphereLight(FARM_LOOK.hemisphereSky, FARM_LOOK.hemisphereGround, FARM_LOOK.hemisphereIntensity);+ const sun = createFarmSun(shadows.mapSize); sun.castShadow = shadows.enabled;+ sun.shadow.camera.layers.mask = farmShadowMask(shadows.enabled && o.standIns);+ const shadow = shadows.enabled && o.cache ? cachedSunShadow({ light: sun, settleFrames: o.settleFrames, ...(o.liveMapSize ? { liveMapSize: Math.min(o.liveMapSize, shadows.mapSize) } : {}) }) : null;+ session.shadow = shadow;+ const env = environment();+ scene.environment = env.texture; scene.environmentIntensity = FARM_LOOK.environmentIntensity;+ root.add(hemisphere, sun, sun.target);+ return { root, sun, shadow, dispose() {+ root.removeFromParent(); if (session.shadow === shadow) session.shadow = null; shadow?.dispose(); sun.shadow.dispose();+ if (scene.environment === env.texture) scene.environment = null;+ env.dispose(); root.clear();+ } };+}export function FarmLighting() {- const state = useThree(), quality = useQuality();- const lights = useBuilt(() => {- const root = new Group(); root.name = 'Farm lighting';- const hemisphere = new HemisphereLight(FARM_LOOK.hemisphereSky, FARM_LOOK.hemisphereGround, FARM_LOOK.hemisphereIntensity);- const sun = new DirectionalLight(FARM_LOOK.sunColor, FARM_LOOK.sunIntensity);- sun.position.fromArray(FARM_LOOK.sunPosition); sun.castShadow = quality.knobs.shadows.enabled;- sun.shadow.mapSize.setScalar(quality.knobs.shadows.mapSize);- Object.assign(sun.shadow.camera, {- left: -FARM_LOOK.shadowExtent, right: FARM_LOOK.shadowExtent,- top: FARM_LOOK.shadowExtent, bottom: -FARM_LOOK.shadowExtent,- near: FARM_LOOK.shadowNear, far: FARM_LOOK.shadowFar,- });- sun.shadow.normalBias = FARM_LOOK.shadowNormalBias;- sun.shadow.camera.updateProjectionMatrix();- const environment = buildRoomEnvironment(asWebGPU(state.gl), { blur: FARM_LOOK.environmentBlur, intensity: FARM_LOOK.environmentIntensity });- state.scene.environment = environment.texture; state.scene.environmentIntensity = FARM_LOOK.environmentIntensity;- root.add(hemisphere, sun, sun.target);- return { root, dispose() {- root.removeFromParent(); sun.shadow.dispose();- if (state.scene.environment === environment.texture) state.scene.environment = null;- environment.dispose(); root.clear();- } };- }, value => value.dispose(), [state.gl, state.scene, quality.knobs.shadows]);+ const state = useThree(), quality = useQuality(), session = useFarmSession(), options = useMemo(() => farmShadowOptions(readFarmDevParams()), []);+ const lights = useBuilt(() => buildFarmLighting(state.scene, quality.knobs.shadows, () => buildRoomEnvironment(asWebGPU(state.gl), { blur: FARM_LOOK.environmentBlur, intensity: FARM_LOOK.environmentIntensity }), options, session),+ value => value.dispose(), [state.gl, state.scene, quality.knobs.shadows]);return lights ? <primitive object={lights.root} dispose={null}/> : null;}diff --git a/scenes/packages/farm/src/world/optimize.ts b/scenes/packages/farm/src/world/optimize.tsindex 7f154657..99e62076 100644--- a/scenes/packages/farm/src/world/optimize.ts+++ b/scenes/packages/farm/src/world/optimize.ts@@ -1,8 +1,11 @@-import {StaticDrawUsage,type InstancedMesh,type Scene} from 'three/webgpu';+import {StaticDrawUsage,type BufferGeometry,type InstancedMesh,type Mesh,type Object3D,type Scene} from 'three/webgpu';import {DisposeRegistry} from '@kiln-scenes/scene-kit/lifecycle';-import {batchStaticMeshes,freezeTransforms,packInstancedMeshes} from '@kiln-scenes/scene-kit/instancing';+import {batchStaticMeshes,freezeTransforms,mergeRigidByMaterial,packInstancedMeshes} from '@kiln-scenes/scene-kit/instancing';+import {shadowStandIns,shadowTexelSize,smallCasterThreshold} from '@kiln-scenes/scene-kit/shadows';+import {FARM_SHADOW} from '../constants';import type {FarmInstance} from './types';import {countPlacementSources,farmBatchPolicy,farmInstanceOwners,isFixedFarmOwner} from './optimize-policy';+import {createFarmSun,farmHeroAnchors,farmShadowMask} from './shadows';export interface FarmOptimizationStats {woodland:{packed:boolean;groups:number;instances:number;sourceMeshes:number;tangentDerivatives:number};@@ -10,12 +13,23 @@ export interface FarmOptimizationStats {frozen:{placements:number;nodes:number};/** Attached only after the imperative Farm root joins the outer R3F scene. */frameGraph:{hiddenRoots:number;dynamicRoots:number}|null;+ /** S4b anchor merge over the heroes; outside `batching`, which B-07 checks field by field. Null when ?heroMerge=0. */+ heroes:{owners:number;sourceMeshes:number;mergedMeshes:number;keptMeshes:number;groups:number}|null;+ /** S4 on tiers with shadows: hero depth stand-ins and parts they dropped, herd batches under the threshold, texel in metres. */+ shadow:{proxies:number;sourceMeshes:number;groups:number;dropped:number;triangles:number;smallCasters:number;texel:number}|null;}+/** Tier shadow inputs: map size (the texel), stand-ins on or off, and the small-caster threshold in texels (0 = off). */+export interface FarmShadowBuild {mapSize:number;standIns:boolean;minCasterTexels:number}/** Pack before batching and freeze last. Register restore after original owners;* the outer scene frame graph must register its restoration after this owner.* Pack geometry/materials and prepared geometry are borrowed throughout.+ * Heroes (non-fixed owners with no batch source: the policy-excluded placements and the windmill) are merged per anchor and+ * material after batching, so every B-07 count is taken first, then given shadow stand-ins before freezing (stand-ins copy+ * their anchor's matrix flags). Merged geometry is shared per asset, anchor path and group through one cache (the gates), and+ * keeps the GLB's interleaved vertex layout, so a merged mesh shares the pipeline of unmerged meshes (review RK-1).+ * Stand-ins bake only sources the sun's shadow camera draws (farmShadowMask); farmers keep their small parts (RF-1).*/-export function optimizeFarmWorld(root:Scene,instances:readonly FarmInstance[],woodland:{meshes:InstancedMesh[];derivatives:number},options:{packWoodland:boolean}){+export function optimizeFarmWorld(root:Scene,instances:readonly FarmInstance[],woodland:{meshes:InstancedMesh[];derivatives:number},options:{packWoodland:boolean;heroMerge?:boolean;shadow?:FarmShadowBuild|null}){const owners=farmInstanceOwners(instances),policy=farmBatchPolicy(),registry=new DisposeRegistry();// Fail before mutation: a misplaced wrapper otherwise escapes frame-graph ownership.for(const owner of owners)if(owner.object.parent!==root)throw new Error(`Farm owner ${owner.id} must be a direct world-root child`);@@ -30,12 +44,34 @@ export function optimizeFarmWorld(root:Scene,instances:readonly FarmInstance[],w// (FARM-006), so static usage uploads exactly the batches that moved (none on minimal, where nothing moves).for(const batch of batches.batches)if(batch.dynamic)batch.mesh.instanceMatrix.setUsage(StaticDrawUsage);const derived=new Set(batches.batches.filter(batch=>batch.mesh.geometry!==batch.sources[0]!.o.geometry).map(batch=>batch.mesh.geometry));+ const sources=new Set<Object3D>(batches.batches.flatMap(b=>b.sources.map(s=>s.o))),batched=(o:Object3D)=>{let found=false;o.traverse(n=>{found||=sources.has(n);});return found;};+ const heroes=instances.filter((h,i)=>!isFixedFarmOwner(owners[i]!)&&!batched(h.object)),anchors=new Map(heroes.map(h=>[h,farmHeroAnchors(h)]));+ const sum=<K extends string>(into:Record<K,number>,from:Record<K,number>,keys:readonly K[])=>{for(const k of keys)into[k]+=from[k];};+ let heroStats:FarmOptimizationStats['heroes']=null,shadow:FarmOptimizationStats['shadow']=null;+ if(options.heroMerge!==false){+ const cache=new Map<string,BufferGeometry>();registry.add(()=>{for(const g of cache.values())g.dispose();cache.clear();});+ heroStats={owners:heroes.length,sourceMeshes:0,mergedMeshes:0,keptMeshes:0,groups:0};+ for(const hero of heroes){+ const keep=anchors.get(hero)!,path=(n:Object3D)=>{const names:string[]=[];for(let x:Object3D|null=n;x&&x!==hero.object;x=x.parent)names.push(x.name);return hero.asset.id+':'+names.reverse().join('/');};+ const merge=mergeRigidByMaterial(hero.object,{isAnchor:n=>keep.has(n),cache,cacheKey:path,layout:'source'});registry.add(()=>merge.restore());+ sum(heroStats,merge.stats,['sourceMeshes','mergedMeshes','keptMeshes','groups']);+ }+ }+ if(options.shadow){+ const sun=createFarmSun(options.shadow.mapSize),texel=shadowTexelSize(sun.shadow),minTexels=options.shadow.minCasterTexels;+ shadow={proxies:0,sourceMeshes:0,groups:0,dropped:0,triangles:0,smallCasters:0,texel};+ if(options.shadow.standIns)for(const hero of heroes){+ const keep=anchors.get(hero)!,s=shadowStandIns(hero.object,{layer:FARM_SHADOW.standInLayer,shadowMask:farmShadowMask(true),isAnchor:n=>keep.has(n),texel,minCasterTexels:FARM_SHADOW.keepSmallCasters.includes(hero.asset.id)?0:minTexels});registry.add(()=>s.restore());+ sum(shadow,s.stats,['proxies','sourceMeshes','groups','dropped','triangles']);+ }+ if(minTexels>0){const herd=new Set<Mesh>(batches.batches.filter(b=>b.dynamic).map(b=>b.mesh)),t=smallCasterThreshold(root,sun,{minTexels,include:m=>herd.has(m)});registry.add(()=>t.restore());shadow.smallCasters=t.stats.dropped;}+ }const frozen=freezeTransforms(owners,isFixedFarmOwner);registry.add(()=>frozen.restore());const stats:FarmOptimizationStats={woodland:{packed:!!packed,groups:packed?.groups??0,instances:woodland.meshes.reduce((n,mesh)=>n+mesh.count,0),sourceMeshes:woodland.meshes.length,tangentDerivatives:woodland.derivatives},- batching:{...batches.stats,...observed,tangentDerivatives:derived.size},frozen:{placements:frozen.placements,nodes:frozen.nodes},frameGraph:null,+ batching:{...batches.stats,...observed,tangentDerivatives:derived.size},frozen:{placements:frozen.placements,nodes:frozen.nodes},frameGraph:null,heroes:heroStats,shadow,};- return{owners,batches,isFixed:isFixedFarmOwner,stats,restore};+ return{owners,batches,isFixed:isFixedFarmOwner,heroes,stats,restore};}catch(error){registry.disposeAll();if(registry.errors.length)throw new AggregateError([error,...registry.errors],'Farm optimization construction and restoration failed');throw error;}}export type FarmOptimization=ReturnType<typeof optimizeFarmWorld>;diff --git a/scenes/packages/farm/src/world/prewarm.ts b/scenes/packages/farm/src/world/prewarm.tsindex 2d24dbbd..3983d41a 100644--- a/scenes/packages/farm/src/world/prewarm.ts+++ b/scenes/packages/farm/src/world/prewarm.ts@@ -1,4 +1,4 @@-import type { Camera, Material, Object3D, Scene } from 'three/webgpu';+import type { Camera, Layers, Material, Object3D, Scene } from 'three/webgpu';/** The part of three's WebGPURenderer (WebGPU and WebGL2 backends alike) that the warm pass uses. */export interface WarmPassRenderer { compileAsync(object: Object3D, camera: Camera, targetScene?: Scene | null): Promise<unknown> }@@ -42,14 +42,19 @@ export interface WarmPassOptions {reveal: boolean;/** Chains compiled at once; defaults to WARM_CONCURRENCY. */concurrency?: number;+ /** Called once as the drawing frame starts, with the world shown and culling off (S5: the cached shadow's prime). */+ onDraw?(): void;}const drawable = (object: Object3D) => { const o = object as unknown as Record<string, unknown>; return !!(o.isMesh || o.isLine || o.isPoints || o.isSprite); };-/** Every drawable node below root whose own visibility and that of its ancestors below root is true (root's own flag is ignored). */-export function warmRenderables(root: Object3D): Object3D[] {+/**+ * Every drawable node below root whose own visibility and that of its ancestors below root is true (root's own flag is+ * ignored); with `layers`, only those a camera on them draws (three tests layers per object: shadow stand-ins are not).+ */+export function warmRenderables(root: Object3D, layers?: Layers): Object3D[] {const found: Object3D[] = [];- const visit = (object: Object3D) => { if (!object.visible) return; if (drawable(object)) found.push(object); for (const child of object.children) visit(child); };+ const visit = (object: Object3D) => { if (!object.visible) return; if (drawable(object) && (!layers || object.layers.test(layers))) found.push(object); for (const child of object.children) visit(child); };for (const child of root.children) visit(child);return found;}@@ -84,11 +89,12 @@ export function warmChainKey(object: Object3D): string {* shown when the compiles are done; the lights are outside the world, so the pipelines match the lit frame.* 2. drawing: the world is shown and one frame is drawn with frustum culling off for every drawable, which compiles* what compileAsync does not (shadow-map pipelines, which three skips while pre-compiling) and makes every- * first-draw driver variant happen before ready.+ * first-draw driver variant happen before ready. Drawables off the camera's layers (shadow stand-ins) are not compiled+ * but draw unculled here too; `onDraw` runs as this frame starts (the cached shadow re-arms at the reveal).* 3. done: culling is restored; the next frame is the first complete frame.*/export function startWarmPass(renderer: WarmPassRenderer, scene: Scene, camera: Camera, root: Object3D, options: WarmPassOptions): WarmPass {- const renderables = warmRenderables(root), chains = new Map<string, Object3D[]>();+ const drawables = warmRenderables(root), renderables = drawables.filter(o => o.layers.test(camera.layers)), chains = new Map<string, Object3D[]>();for (const object of renderables) { const key = warmChainKey(object); (chains.get(key) ?? chains.set(key, []).get(key)!).push(object); }const concurrency = Math.max(1, Math.min(Math.floor(options.concurrency ?? WARM_CONCURRENCY), chains.size));const stats: WarmPassStats = { renderables: renderables.length, chains: chains.size, concurrency: chains.size ? concurrency : 0, failed: 0, compileFrames: 0, revealed: options.reveal };@@ -122,9 +128,9 @@ export function startWarmPass(renderer: WarmPassRenderer, scene: Scene, camera:if (phase === 'compiling') {if (!compiled) { stats.compileFrames++; return false; }if (options.reveal) root.visible = true;- unculled = renderables.filter(object => object.frustumCulled);+ unculled = drawables.filter(object => object.frustumCulled);for (const object of unculled) object.frustumCulled = false;- phase = 'drawing';+ phase = 'drawing'; options.onDraw?.();return false;}if (phase === 'drawing') {diff --git a/scenes/packages/farm/src/world/probe-systems.ts b/scenes/packages/farm/src/world/probe-systems.tsnew file mode 100644index 00000000..3d1fc12c--- /dev/null+++ b/scenes/packages/farm/src/world/probe-systems.ts@@ -0,0 +1,30 @@+import type { InstancedMesh, Object3D } from 'three/webgpu';+import { farmBatchPolicy } from './optimize-policy';+import type { FarmWorld } from './build-world';++const ANIMALS = new Set(['cow', 'sheep', 'chicken']);+/**+ * Test and dev builds only (World.tsx registers these behind the build flags): the count probe's systems and asset names+ * (scene-kit testing/probe.ts). Heroes are the policy-excluded placements plus the windmill, whose four meshes never+ * batch; animals are their dynamic batches; batched is every other batch; placements are the owners left drawing their+ * own meshes. A batch is named by the asset of its first source.+ */+export function farmProbeHooks(world: FarmWorld): Record<string, (...args: any[]) => unknown> {+ const excluded = farmBatchPolicy().excludeAssets, owners = new Map<Object3D, string>();+ for (const instance of world.placements.instances) owners.set(instance.object, instance.asset.id);+ const ownerAsset = (object: Object3D | null) => { for (let node = object; node; node = node.parent) { const id = owners.get(node); if (id) return id; } return null; };+ const batches = (world.optimization?.batches.batches ?? []).map(batch => ({ mesh: batch.mesh as Object3D, asset: ownerAsset(batch.sources[0]?.o ?? null) }));+ const named = new Map<Object3D, string>(batches.map(batch => [batch.mesh, batch.asset ?? batch.mesh.name]));+ const woodland = () => [...world.woodland.meshes, ...world.root.children.filter(child => (child as InstancedMesh).isInstancedMesh && child.name.startsWith('Packed '))];+ const isHero = (asset: string) => excluded.has(asset) || asset === 'windmill';+ return {+ probeSystems: () => ({+ terrain: [world.ground, world.surrounding], woodland: woodland(), stream: world.water, bridge: world.bridge, grass: world.grass.layers.map(layer => layer.mesh),+ heroes: world.placements.instances.filter(i => isHero(i.asset.id)).map(i => i.object),+ animals: [...world.placements.instances.filter(i => ANIMALS.has(i.asset.id)).map(i => i.object), ...batches.filter(b => b.asset && ANIMALS.has(b.asset)).map(b => b.mesh)],+ placements: world.placements.instances.filter(i => !isHero(i.asset.id) && !ANIMALS.has(i.asset.id)).map(i => i.object),+ batched: batches.filter(b => !b.asset || !ANIMALS.has(b.asset)).map(b => b.mesh),+ }),+ probeAsset: (object: Object3D) => named.get(object) ?? (woodland().includes(object) ? 'faceted-tree' : ownerAsset(object)),+ };+}diff --git a/scenes/packages/farm/src/world/shadows.ts b/scenes/packages/farm/src/world/shadows.tsnew file mode 100644index 00000000..4bcdb0a6--- /dev/null+++ b/scenes/packages/farm/src/world/shadows.ts@@ -0,0 +1,75 @@+import { DirectionalLight, PropertyBinding } from 'three/webgpu';+import type { InstancedMesh, Object3D } from 'three/webgpu';+import type { CachedSunShadow, TrackedCasters } from '@kiln-scenes/scene-kit/shadows';+import { FARM_LOOK, FARM_SHADOW } from '../constants';+import type { FarmInstance } from './types';++/** `liveMapSize` unset keeps the live map at the tier's map size (the same texel as the static map). */+export interface FarmShadowOptions { cache: boolean; standIns: boolean; minCasterTexels: number; settleFrames: number; liveMapSize?: number }+/**+ * FARM_SHADOW with the test and dev A/B switches ?shadowCache, ?standIns, ?casterTexels (0 = no threshold) and ?liveMapSize,+ * the OD-9 "small live map" option for the owner (review RF-5: a full-size live map is a second full-size render target).+ */+export function farmShadowOptions(p: { shadowCache?: boolean; standIns?: boolean; casterTexels?: number; liveMapSize?: number }): FarmShadowOptions {+ return { cache: p.shadowCache ?? FARM_SHADOW.cache, standIns: p.standIns ?? FARM_SHADOW.standIns, minCasterTexels: Math.max(0, p.casterTexels ?? FARM_SHADOW.minCasterTexels), settleFrames: FARM_SHADOW.settleFrames,+ ...(p.liveMapSize && p.liveMapSize > 0 ? { liveMapSize: p.liveMapSize } : {}) };+}+/**+ * The layers the sun's shadow camera draws: layer 0, plus the stand-in layer when stand-ins are on (three r186 keeps a shadow+ * camera's own mask once it has a bit above 0). Lighting sets it, and the stand-ins bake only sources it draws.+ */+export function farmShadowMask(standIns: boolean): number { return 1 | (standIns ? 1 << FARM_SHADOW.standInLayer : 0); }+/** INV 4.1 sun at the tier's map size; the shadow projection is updated after every bound is assigned. */+export function createFarmSun(mapSize: number): DirectionalLight {+ const sun = new DirectionalLight(FARM_LOOK.sunColor, FARM_LOOK.sunIntensity), e = FARM_LOOK.shadowExtent;+ sun.position.fromArray(FARM_LOOK.sunPosition); sun.shadow.mapSize.setScalar(mapSize);+ Object.assign(sun.shadow.camera, { left: -e, right: e, top: e, bottom: -e, near: FARM_LOOK.shadowNear, far: FARM_LOOK.shadowFar });+ sun.shadow.normalBias = FARM_LOOK.shadowNormalBias; sun.shadow.camera.updateProjectionMatrix();+ return sun;+}+/**+ * farm.md section 4: what a hero keeps through the anchor merge and where its stand-ins cut. The placement wrapper, the GLB+ * clone root (the mixer root), every clip track target (mixer bindings were cached before optimization) and every node the+ * play code finds by name in a clone (Joint_*, DoorPivot). Crop soil and plant names belong to fixed owners, never merged;+ * Mesh_Building_Wood is read from the pack's original scene.+ */+export function farmHeroAnchors(instance: FarmInstance): Set<Object3D> {+ const root = instance.mixer.getRoot() as Object3D, keep = new Set<Object3D>([instance.object, root]);+ for (const clip of instance.clips) for (const track of clip.tracks) { const node = PropertyBinding.findNode(root, PropertyBinding.parseTrackName(track.name).nodeName) as Object3D | undefined; if (node) keep.add(node); }+ root.traverse(n => { if (n.name.startsWith('Joint_') || n.name === 'DoorPivot') keep.add(n); });+ return keep;+}+export interface FarmShadowWorld {+ root: Object3D; placements: { instances: readonly FarmInstance[] }; sim: { doors: readonly { pivots: readonly Object3D[] }[] };+ optimization: { heroes: readonly FarmInstance[]; batches: { batches: readonly { mesh: InstancedMesh; dynamic: boolean }[] } } | null;+}+/**+ * What the cached shadow watches (shadow-internals.check: classify per node by observed motion). Whole hero subtrees (rotors,+ * doors and gates, the tractor, both farmers, also the trailer should anything move it), the herd's dynamic batches and door+ * pivots; a watched caster goes live only when its own matrix, visibility or casting changes, so still hero parts stay in the+ * static map. Without optimization (?staticBaseline) the animated, driven and walked owners themselves.+ */+export function farmShadowMovers(world: FarmShadowWorld): Set<Object3D> {+ const o = world.optimization, movers = new Set<Object3D>(o ? o.heroes.map(h => h.object) : world.placements.instances.filter(i => i.action || i.asset.id === 'tractor' || i.asset.id === 'farmer').map(i => i.object));+ for (const b of o?.batches.batches ?? []) if (b.dynamic) movers.add(b.mesh);+ for (const door of world.sim.doors) for (const pivot of door.pivots) movers.add(pivot);+ return movers;+}+/**+ * Binds a world to the session's cached sun shadow. It tracks the world once its root is shown (a first world tracked while+ * hidden would go live wholesale at reveal), and again for a new cache (lights rebuilt), then updates it each frame after all+ * motion and visibility (SystemOrder.shadows). `prime` belongs to the warm pass's drawing frame, the reveal. `dispose` (the+ * world leaving) untracks it, so a cache that outlives its world never keeps that world's casters (review RF-7).+ */+export function bindFarmShadow(world: FarmShadowWorld, cache: () => CachedSunShadow | null) {+ let bound: CachedSunShadow | null = null, movers: Set<Object3D> | null = null, tracked: TrackedCasters | null = null, disposed = false;+ return {+ update() {+ const s = disposed ? null : cache(); if (!s) return;+ if (s !== bound) { if (!world.root.visible) return; const m = movers ??= farmShadowMovers(world); tracked = s.track(world.root, { movable: n => m.has(n) }); s.invalidate('track'); bound = s; }+ s.update();+ },+ prime() { if (!disposed) cache()?.prime(); },+ dispose() { disposed = true; tracked?.untrack(); tracked = bound = null; },+ };+}diff --git a/scenes/packages/farm/tests/unit/optimize.test.ts b/scenes/packages/farm/tests/unit/optimize.test.tsindex 37303034..76bcc109 100644--- a/scenes/packages/farm/tests/unit/optimize.test.ts+++ b/scenes/packages/farm/tests/unit/optimize.test.ts@@ -1,10 +1,14 @@import {expect,test} from 'bun:test';-import {AnimationClip,AnimationMixer,BoxGeometry,Float32BufferAttribute,Group,InstancedMesh,Matrix4,Mesh,MeshStandardMaterial,Scene,StaticDrawUsage,Texture} from 'three/webgpu';+import {AnimationClip,AnimationMixer,BoxGeometry,BufferGeometry,Float32BufferAttribute,Group,InstancedMesh,InterleavedBuffer,InterleavedBufferAttribute,Matrix4,Mesh,MeshStandardMaterial,QuaternionKeyframeTrack,Scene,StaticDrawUsage,Texture,Vector3,VectorKeyframeTrack} from 'three/webgpu';+import type {Material,Object3D} from 'three/webgpu';import type {FarmInstance} from '../../src/world/types';await import('three');const {DisposeRegistry,createFrameGraph}=await import('@kiln-scenes/scene-kit');const {farmBatchPolicy,farmInstanceOwners,isFixedFarmOwner,countPlacementSources}=await import('../../src/world/optimize-policy');const {optimizeFarmWorld}=await import('../../src/world/optimize');+const {findDoor,doorCenter}=await import('../../src/play/doors');+const {FARM_SHADOW}=await import('../../src/constants');+const shadowsModule=await import('../../src/world/shadows');function fixture(asset:string,geometry:BoxGeometry,material:MeshStandardMaterial,x=0,clips:AnimationClip[]=[]):FarmInstance{const object=new Group(),mesh=new Mesh(geometry,material);object.name=asset;object.position.x=x;object.add(mesh);@@ -80,6 +84,105 @@ test('M4: dynamic batches take static usage and upload only when one of their ma}finally{geometry.dispose();material.dispose();}});+// S4b/S4: a farmhouse-like hero (root parts sharing materials, a glass pane, Joint_FrontDoor with leaf, hardware and a 1 cm+// pin), two fence gates (posts, a clip-targeted Latch that is not a Joint_, Joint_GateLeaf), two fixed barrels and a herd of+// two cows with a large hide and a tiny eye. Geometry and materials are shared like pack resources.+// Glb primitives carry no draw groups (a BoxGeometry has six, which the merge leaves alone).+const shared=(()=>{const m=(name:string,o={})=>new MeshStandardMaterial({name,...o}),g=(s:number)=>{const b=new BoxGeometry(s,s,s);b.clearGroups();return b;};return{unit:g(1),pin:g(.01),masonry:m('masonry'),trim:m('trim'),glass:m('glass',{transparent:true}),leaf:m('leaf'),iron:m('iron'),brass:m('brass'),post:m('post'),hide:m('hide'),eye:m('eye')};})();+function hero(asset:string,x:number,parts:[string,MeshStandardMaterial,number,string?][],pivots:string[],clips:AnimationClip[]=[]):FarmInstance{+ const object=new Group(),clone=new Group();object.name=`${asset}-${x}`;clone.name=asset;object.position.set(x,0,3);object.rotation.y=.4;object.add(clone);+ for(const name of pivots){const p=new Group();p.name=name;p.position.set(1,0,.5);clone.add(p);}+ for(const[name,material,at,parent]of parts){const m=new Mesh(name==='pin'?shared.pin:shared.unit,material);m.name=name;m.position.set(at,.25,0);(parent?clone.getObjectByName(parent)!:clone).add(m);}+ return{id:object.name,asset:{id:asset},object,mixer:new AnimationMixer(clone),clips,action:null,clipIndex:''};+}+function heroWorld(){+ const outer=new Scene(),root=new Scene();outer.add(root);+ const house=hero('farmhouse',0,[['wall-a',shared.masonry,0],['wall-b',shared.masonry,2],['wall-c',shared.masonry,4],['trim-a',shared.trim,1],['trim-b',shared.trim,3],['pane',shared.glass,5],['door-leaf',shared.leaf,0,'Joint_FrontDoor'],['door-hardware',shared.iron,.5,'Joint_FrontDoor'],['pin',shared.brass,.8,'Joint_FrontDoor']],['Joint_FrontDoor']);+ const open=()=>[new AnimationClip('Open',1,[new QuaternionKeyframeTrack('Joint_GateLeaf.quaternion',[0,1],[0,0,0,1,0,.7071,0,.7071]),new VectorKeyframeTrack('Latch.position',[0,1],[1,0,.5,1,.2,.5])])];+ const gates=[10,20].map(x=>hero('fence-gate',x,[['post-a',shared.post,0],['post-b',shared.post,3],['latch-a',shared.post,0,'Latch'],['latch-b',shared.post,.3,'Latch'],['gate-leaf',shared.leaf,1,'Joint_GateLeaf'],['keeper',shared.iron,2,'Joint_GateLeaf']],['Latch','Joint_GateLeaf'],open()));+ const barrels=[30,31].map(x=>fixture('barrel',shared.unit,shared.masonry,x));+ const cows=[40,42].map(x=>{const cow=fixture('cow',shared.unit,shared.hide,x,[new AnimationClip('Graze',1,[])]),eye=new Mesh(shared.pin,shared.eye);eye.position.y=1;cow.object.add(eye);return cow;});+ const instances=[house,...gates,...barrels,...cows];for(const i of instances)root.add(i.object);+ // Every placement mesh casts and receives (placements.ts).+ root.traverse(n=>{if((n as Mesh).isMesh)n.castShadow=n.receiveShadow=true;});root.updateMatrixWorld(true);+ return{outer,root,instances,house,gates,cows};+}+const meshes=(o:Object3D)=>{const out:Mesh[]=[];o.traverseVisible(n=>{if((n as Mesh).isMesh)out.push(n as Mesh);});return out;};+const graphStats=(w:ReturnType<typeof heroWorld>,o:ReturnType<typeof optimizeFarmWorld>)=>{const g=createFrameGraph({scene:w.outer,worldRoot:w.root,owners:o.owners,batches:o.batches,isFixed:o.isFixed});const s={...g.stats};g.restore();return s;};+test('S4b: hero anchor merge keeps doors, pivots and B-07 counts, shares gate geometry and restores',()=>{+ const off=heroWorld(),plain=optimizeFarmWorld(off.root,off.instances,{meshes:[],derivatives:0},{packWoodland:false,heroMerge:false});+ const w=heroWorld(),house=w.house,pivot=house.object.getObjectByName('Joint_FrontDoor')!,center=doorCenter(findDoor(house)!,new Vector3());+ const geometries=new Set<BufferGeometry>(),o=optimizeFarmWorld(w.root,w.instances,{meshes:[],derivatives:0},{packWoodland:false});+ expect(plain.stats.heroes).toBeNull();+ expect(o.stats.heroes).toEqual({owners:3,sourceMeshes:13,mergedMeshes:6,keptMeshes:8,groups:13});+ expect(o.heroes).toEqual([house,...w.gates]);+ // B-07: batching, frozen and frame-graph counts are taken before and around the merge, so they do not move.+ expect([o.stats.batching,o.stats.frozen,graphStats(w,o)]).toEqual([plain.stats.batching,plain.stats.frozen,graphStats(off,plain)]);+ expect(meshes(house.object).map(m=>m.name).sort()).toEqual(['Merged farmhouse/masonry','Merged farmhouse/trim','door-hardware','door-leaf','pane','pin']);+ // Doors: the same pivot, the same interaction centre, and apply still swings the leaf.+ const door=findDoor(house)!,leaf=house.object.getObjectByName('door-leaf')!,before=leaf.matrixWorld.clone();+ expect(door.pivots[0]).toBe(pivot);expect(doorCenter(door,new Vector3()).distanceTo(center)).toBeLessThan(1e-9);+ door.apply(1);expect(leaf.matrixWorld.equals(before)).toBe(false);expect(leaf.parent).toBe(pivot);door.apply(0);+ // Gates: the clip-targeted Latch is an anchor of its own, and both gates draw one shared geometry per anchor and material.+ const latch=w.gates.map(g=>g.object.getObjectByName('Merged Latch/post') as Mesh),posts=w.gates.map(g=>g.object.getObjectByName('Merged fence-gate/post') as Mesh);+ expect(latch.map(m=>m.parent?.name)).toEqual(['Latch','Latch']);expect(latch[0]!.geometry).toBe(latch[1]!.geometry);expect(posts[0]!.geometry).toBe(posts[1]!.geometry);+ for(const m of [...latch,...posts])geometries.add(m.geometry);let disposed=0;for(const g of geometries)g.addEventListener('dispose',()=>disposed++);+ o.restore();expect(disposed).toBe(2);expect(meshes(w.root).some(m=>m.name.startsWith('Merged'))).toBe(false);expect(meshes(house.object).length).toBe(9);plain.restore();+});+test('S4: shadow tiers build hero depth stand-ins and drop herd batches under two texels, leaving frozen and graph counts alone',()=>{+ const off=heroWorld(),plain=optimizeFarmWorld(off.root,off.instances,{meshes:[],derivatives:0},{packWoodland:false});+ const w=heroWorld(),o=optimizeFarmWorld(w.root,w.instances,{meshes:[],derivatives:0},{packWoodland:false,shadow:{mapSize:2048,standIns:true,minCasterTexels:2}});+ expect(plain.stats.shadow).toBeNull();+ expect(o.stats.shadow).toMatchObject({proxies:8,dropped:1,smallCasters:1});expect(o.stats.shadow!.texel).toBeCloseTo(88/2048,12);+ expect([o.stats.frozen,graphStats(w,o)]).toEqual([plain.stats.frozen,graphStats(off,plain)]);+ const proxies:Mesh[]=[];w.root.traverse(n=>{if(n.userData.kilnShadowStandIn)proxies.push(n as Mesh);});+ expect(proxies.map(p=>p.parent!.name).sort()).toEqual(['Joint_FrontDoor','Joint_GateLeaf','Joint_GateLeaf','Latch','Latch','farmhouse','fence-gate','fence-gate']);+ expect(proxies.every(p=>p.layers.mask===1<<FARM_SHADOW.standInLayer&&p.castShadow)).toBe(true);+ // Main-pass meshes stop casting (the pane too: one opaque depth draw); the 1 cm pin is under two texels and drops.+ expect(meshes(w.house.object).filter(m=>!m.userData.kilnShadowStandIn).every(m=>!m.castShadow)).toBe(true);+ const herd=o.batches.batches.filter(b=>b.dynamic).map(b=>[(b.mesh.material as Material).name,b.mesh.castShadow]);+ expect(herd.sort()).toEqual([['eye',false],['hide',true]]);+ o.restore();expect(meshes(w.root).every(m=>m.castShadow)).toBe(true);expect(proxies.every(p=>!p.parent)).toBe(true);plain.restore();+});++// RK-1: a glTF primitive with a byte stride (position, normal and uv in one Float32 buffer), as the Farm GLBs load.+function interleavedBox(){+ const box=new BoxGeometry(),n=box.getAttribute('position').count,data=new Float32Array(n*8),g=new BufferGeometry();+ for(let i=0;i<n;i++){let at=i*8;for(const[k,s]of[['position',3],['normal',3],['uv',2]]as const)for(let c=0;c<s;c++)data[at++]=box.getAttribute(k).getComponent(i,c);}+ const ib=new InterleavedBuffer(data,8);g.setAttribute('position',new InterleavedBufferAttribute(ib,3,0));g.setAttribute('normal',new InterleavedBufferAttribute(ib,3,3));g.setAttribute('uv',new InterleavedBufferAttribute(ib,2,6));g.setIndex(box.index);+ return g;+}+test('S4b: the hero merge keeps the source vertex layout (RK-1), so a merged mesh shares the pipeline key of unmerged ones',()=>{+ const root=new Scene(),g=interleavedBox(),house=hero('farmhouse',0,[['wall-a',shared.masonry,0],['wall-b',shared.masonry,2]],[]);root.add(house.object);+ house.object.traverse(n=>{if((n as Mesh).isMesh)(n as Mesh).geometry=g;});root.updateMatrixWorld(true);+ const o=optimizeFarmWorld(root,[house],{meshes:[],derivatives:0},{packWoodland:false}),merged=house.object.getObjectByName('Merged farmhouse/masonry') as Mesh;+ const layout=(geometry:BufferGeometry)=>Object.entries(geometry.attributes).map(([k,a])=>{const i=a as InterleavedBufferAttribute;return[k,!!i.isInterleavedBufferAttribute,i.data?.stride,i.offset,a.itemSize];});+ expect(merged).toBeDefined();expect(layout(merged.geometry)).toEqual(layout(g));+ const buffers=new Set(Object.values(merged.geometry.attributes).map(a=>(a as InterleavedBufferAttribute).data));expect(buffers.size).toBe(1);+ o.restore();g.dispose();+});+test('S4: stand-ins bake exactly what the sun shadow camera draws, and every farmer part stays a caster at economy (RF-1)',()=>{+ const root=new Scene(),{farmShadowMask}=shadowsModule;+ const house=hero('farmhouse',0,[['wall-a',shared.masonry,0],['pin',shared.brass,.8],['seen',shared.trim,1],['unseen',shared.trim,3]],[]);+ // The player rig: a 1 cm neck alone under its joint, and a 1 cm cuff beside a boot under the ankle.+ const farmer=hero('farmer',10,[['Mesh_Body',shared.hide,0],['Mesh_Neck',shared.brass,0,'Joint_Neck'],['Mesh_Cuff',shared.brass,.2,'Joint_Ankle'],['Mesh_Boot',shared.leaf,0,'Joint_Ankle']],['Joint_Neck','Joint_Ankle']);+ const part=(o:FarmInstance,name:string)=>o.object.getObjectByName(name) as Mesh;+ for(const name of['Mesh_Neck','Mesh_Cuff'])part(farmer,name).geometry=shared.pin;+ part(house,'seen').layers.set(FARM_SHADOW.standInLayer);part(house,'unseen').layers.set(5);+ root.add(house.object,farmer.object);root.traverse(n=>{if((n as Mesh).isMesh)n.castShadow=true;});root.updateMatrixWorld(true);+ const o=optimizeFarmWorld(root,[house,farmer],{meshes:[],derivatives:0},{packWoodland:false,shadow:{mapSize:512,standIns:true,minCasterTexels:2}});+ // The sun's shadow camera sees layer 0 and the stand-in layer; a caster on another layer is never drawn, so it is left alone.+ expect(farmShadowMask(true)).toBe(1|1<<FARM_SHADOW.standInLayer);expect(farmShadowMask(false)).toBe(1);+ expect([part(house,'seen').castShadow,part(house,'unseen').castShadow]).toEqual([false,true]);+ // Economy's two texels are 0.34 m: the house pin drops, the farmer's neck and cuff bake into their joints' stand-ins.+ expect(o.stats.shadow).toMatchObject({dropped:1});expect(part(house,'pin').castShadow).toBe(false);+ const proxies:string[]=[];farmer.object.traverse(n=>{if(n.userData.kilnShadowStandIn)proxies.push(n.parent!.name);});+ expect(proxies.sort()).toEqual(['Joint_Ankle','Joint_Neck','farmer']);+ const ankle=part(farmer,'Joint_Ankle').children.find(n=>n.userData.kilnShadowStandIn) as Mesh;+ expect(ankle.geometry.getAttribute('position').count).toBe(2*shared.pin.getAttribute('position').count);+ o.restore();expect(meshes(root).every(m=>m.castShadow)).toBe(true);+});+if(process.env.ORACLE==='1')test('B-07 count-only sealed r33 oracle matches Farm optimization and the frozen historical/current counts',async()=>{await import('../../scripts/audit-optimization-counts');});diff --git a/scenes/packages/farm/tests/unit/prewarm.test.ts b/scenes/packages/farm/tests/unit/prewarm.test.tsindex ebf19b44..91d2cea5 100644--- a/scenes/packages/farm/tests/unit/prewarm.test.ts+++ b/scenes/packages/farm/tests/unit/prewarm.test.ts@@ -100,4 +100,18 @@ describe('SPEC 6.4 warm pass', () => {expect(r2.calls.map(c => c.name)).not.toContain('b');expect(pass.step()).toBe(false);});++ test('S5: onDraw runs once as drawing starts (after the reveal, culling off); drawables the camera layers miss are not compiled but draw unculled', async () => {+ const f = fixture(), r = recorder(f.root), proxy = new Mesh(new BoxGeometry(), new MeshStandardMaterial()), seen: string[] = [];+ proxy.name = 'stand-in'; proxy.layers.set(1); f.b.add(proxy);+ expect(warmRenderables(f.root, f.camera.layers).map(o => o.name)).toEqual(['a', 'child', 'b', 'batch1', 'batch2']);+ expect(warmRenderables(f.root).map(o => o.name)).toEqual(['a', 'child', 'b', 'stand-in', 'batch1', 'batch2']);+ const pass = startWarmPass(r.renderer, f.scene, f.camera, f.root, { reveal: true, onDraw: () => seen.push(`${pass.phase} ${f.root.visible} ${f.a.frustumCulled} ${proxy.frustumCulled}`) });+ expect(pass.stats.renderables).toBe(5);+ for (let i = 0; i < 3; i++) { for (const p of r.pending.splice(0)) p.settle(); await flush(); }+ expect(r.calls.map(c => c.name)).not.toContain('stand-in');+ expect(pass.step()).toBe(false); expect(seen).toEqual(['drawing true false false']);+ expect(pass.step()).toBe(true); expect(proxy.frustumCulled && f.a.frustumCulled).toBe(true); expect(pass.step()).toBe(true);+ expect(seen.length).toBe(1);+ });});diff --git a/scenes/packages/farm/tests/unit/probe-systems.test.ts b/scenes/packages/farm/tests/unit/probe-systems.test.tsnew file mode 100644index 00000000..c8965510--- /dev/null+++ b/scenes/packages/farm/tests/unit/probe-systems.test.ts@@ -0,0 +1,50 @@+import { expect, test } from 'bun:test';+import { farmProbeHooks } from '../../src/world/probe-systems';++// Count-probe systems over a stubbed FarmWorld: only parents, names and the instanced flag are read.+const node = (name: string, parent: any = null, extra: Record<string, unknown> = {}): any => { const n = { name, parent, children: [] as any[], ...extra }; parent?.children.push(n); return n; };+function world() {+ const root = node('farm-root'), placed = (id: string) => { const object = node(id, root), mesh = node(`${id}-mesh`, object); return { instance: { object, asset: { id } }, mesh }; };+ const [house, windmill, gate, cow, sheep, fence, barrel] = ['farmhouse', 'windmill', 'fence-gate', 'cow', 'sheep', 'fence-straight', 'barrel'].map(placed);+ const batch = (name: string, source: any) => ({ mesh: node(name, root, { isInstancedMesh: true }), sources: source ? [{ o: source }] : [] });+ const batches = [batch('Repeated sheep-mesh', sheep!.mesh), batch('Repeated fence-mesh', fence!.mesh), batch('Repeated orphan', null)];+ const trees = node('woodland-lod0', root, { isInstancedMesh: true }), packed = node('Packed tree-a', root, { isInstancedMesh: true }), notPacked = node('Packed but plain', root);+ const parts = { ground: node('ground', root), surrounding: node('surrounding', root), water: node('stream', root), bridge: node('bridge', root), grass: node('grass', root) };+ const farm = {+ root, ground: parts.ground, surrounding: parts.surrounding, water: parts.water, bridge: parts.bridge, grass: { layers: [{ mesh: parts.grass }] },+ woodland: { meshes: [trees] }, placements: { instances: [house, windmill, gate, cow, sheep, fence, barrel].map(p => p!.instance) },+ optimization: { batches: { batches } },+ };+ return { farm: farm as unknown as Parameters<typeof farmProbeHooks>[0], house: house!, windmill: windmill!, gate: gate!, cow: cow!, sheep: sheep!, fence: fence!, barrel: barrel!, batches, trees, packed, notPacked, parts };+}+const names = (list: any[]) => list.map(o => o.name);++test('farm probe systems split heroes, animals, placements and batches by asset', () => {+ const w = world(), systems = farmProbeHooks(w.farm).probeSystems!() as Record<string, any>;+ expect(Object.keys(systems)).toEqual(['terrain', 'woodland', 'stream', 'bridge', 'grass', 'heroes', 'animals', 'placements', 'batched']);+ // Heroes are the batch policy's excluded assets plus the windmill, which never batches.+ expect(names(systems.heroes)).toEqual(['farmhouse', 'windmill', 'fence-gate']);+ // Animals are the animal placements plus the batches whose first source an animal owns.+ expect(names(systems.animals)).toEqual(['cow', 'sheep', 'Repeated sheep-mesh']);+ expect(names(systems.placements)).toEqual(['fence-straight', 'barrel']);+ expect(names(systems.batched)).toEqual(['Repeated fence-mesh', 'Repeated orphan']);+ // Woodland is its own meshes plus the instanced 'Packed …' children of the root.+ expect(names(systems.woodland)).toEqual(['woodland-lod0', 'Packed tree-a']);+ expect([names(systems.terrain), systems.stream.name, systems.grass.map((m: any) => m.name)]).toEqual([['ground', 'surrounding'], 'stream', ['grass']]);+});++test('farm probe assets name batches by their first source, woodland as the tree and meshes by their placement', () => {+ const w = world(), asset = farmProbeHooks(w.farm).probeAsset!;+ expect(w.batches.map(b => asset(b.mesh))).toEqual(['sheep', 'fence-straight', 'Repeated orphan']);+ expect([asset(w.trees), asset(w.packed)]).toEqual(['faceted-tree', 'faceted-tree']);+ expect([asset(w.house.mesh), asset(w.cow.instance.object), asset(node('deep', w.barrel.mesh))]).toEqual(['farmhouse', 'cow', 'barrel']);+ expect([asset(w.parts.ground), asset(w.notPacked)]).toEqual([null, null]);+});++test('S4b/S4: merged hero meshes and shadow stand-ins sit under their hero, so they count as heroes and as its asset', () => {+ const w = world(), hooks = farmProbeHooks(w.farm), pivot = node('Joint_GateLeaf', w.gate.mesh);+ const merged = node('Merged farmhouse/masonry', w.house.mesh, { isMesh: true }), proxy = node('Shadow stand-in Joint_GateLeaf', pivot, { isMesh: true, userData: { kilnShadowStandIn: true } });+ expect([hooks.probeAsset!(merged), hooks.probeAsset!(proxy)]).toEqual(['farmhouse', 'fence-gate']);+ const heroes = (hooks.probeSystems!() as Record<string, any>).heroes as any[], under = (o: any) => { for (let n = o; n; n = n.parent) if (heroes.includes(n)) return n.name; return null; };+ expect([under(merged), under(proxy)]).toEqual(['farmhouse', 'fence-gate']);+});diff --git a/scenes/packages/farm/tests/unit/shadows.test.ts b/scenes/packages/farm/tests/unit/shadows.test.tsnew file mode 100644index 00000000..1c0c34b2--- /dev/null+++ b/scenes/packages/farm/tests/unit/shadows.test.ts@@ -0,0 +1,123 @@+import { expect, test } from 'bun:test';+import { AnimationClip, AnimationMixer, BoxGeometry, Group, InstancedMesh, Mesh, MeshStandardMaterial, Scene, Texture } from 'three/webgpu';+import type { Object3D } from 'three/webgpu';+import type { CachedSunShadow } from '@kiln-scenes/scene-kit/shadows';+import type { FarmInstance } from '../../src/world/types';+// Finish the pinned ESM three load before R3F's CJS entry requires it in Bun.+await import('three');+const { cachedSunShadow } = await import('@kiln-scenes/scene-kit/shadows');+const { buildFarmLighting } = await import('../../src/world/lighting');+const { bindFarmShadow, createFarmSun, farmShadowMovers, farmShadowOptions } = await import('../../src/world/shadows');+const { FARM_LOOK, FARM_SHADOW } = await import('../../src/constants');++const S_BIT = 1 << 30, D_BIT = 1 << 31, STAND_IN = 1 << FARM_SHADOW.standInLayer;+const tier = (enabled: boolean, mapSize: number) => ({ enabled, type: enabled ? 'pcf' as const : 'basic' as const, mapSize, maxCasters: enabled ? 1 : 0 });+const environment = () => { const texture = new Texture(); return { texture, dispose: () => texture.dispose() }; };+const on = { cache: true, standIns: true, minCasterTexels: 2, settleFrames: 30 };++test('S5 options: FARM_SHADOW defaults, overridden by the dev parameters (casterTexels 0 turns the threshold off)', () => {+ expect(FARM_SHADOW).toMatchObject({ cache: true, standIns: true, minCasterTexels: 2, settleFrames: 30 });+ expect(FARM_SHADOW.standInLayer).toBeGreaterThanOrEqual(1); expect(FARM_SHADOW.standInLayer).toBeLessThan(30);+ expect(farmShadowOptions({})).toEqual(on);+ expect(farmShadowOptions({ shadowCache: false, standIns: false, casterTexels: 0 })).toEqual({ cache: false, standIns: false, minCasterTexels: 0, settleFrames: 30 });+});++test('S5 sun: the INV 4.1 shadow frame at the tier map size', () => {+ const sun = createFarmSun(1024), c = sun.shadow.camera;+ expect([sun.position.toArray(), sun.color.getHex(), sun.intensity, sun.shadow.mapSize.toArray(), sun.shadow.normalBias]).toEqual([FARM_LOOK.sunPosition, FARM_LOOK.sunColor, FARM_LOOK.sunIntensity, [1024, 1024], FARM_LOOK.shadowNormalBias]);+ expect([c.left, c.right, c.top, c.bottom, c.near, c.far]).toEqual([-44, 44, 44, -44, 1, 115]);+ expect(c.projectionMatrix.elements[0]).toBeCloseTo(1 / 44, 12);+});++test('S5 lighting: the cached sun shadow exists only on shadow tiers, is published on the session and goes with its lights', () => {+ const scene = new Scene(), session: { shadow: CachedSunShadow | null } = { shadow: null };+ const high = buildFarmLighting(scene, tier(true, 2048), environment, on, session);+ expect(high.root.name).toBe('Farm lighting'); expect(high.sun.castShadow).toBe(true);+ expect(high.shadow).not.toBeNull(); expect(session.shadow).toBe(high.shadow);+ expect((high.sun.shadow as { shadowNode?: unknown }).shadowNode).toBeDefined();+ expect([high.shadow!.staticShadow.mapSize.x, high.shadow!.liveShadow.mapSize.x]).toEqual([2048, 2048]);+ // Without the cache the sun's own camera must see the stand-in layer as well as layer 0.+ expect(high.sun.shadow.camera.layers.mask).toBe(1 | STAND_IN);+ // A tier change: React disposes the old lights, then builds the new ones.+ high.dispose();+ expect(session.shadow).toBeNull(); expect((high.sun.shadow as { shadowNode?: unknown }).shadowNode).toBeUndefined(); expect(high.root.parent).toBeNull();+ const economy = buildFarmLighting(scene, tier(true, 512), environment, on, session);+ expect(session.shadow).toBe(economy.shadow); expect(economy.shadow!.staticShadow.mapSize.x).toBe(512);+ // Built before the old one is disposed: disposing the older build never unpublishes the newer cache.+ const balanced = buildFarmLighting(scene, tier(true, 1024), environment, on, session);+ expect(session.shadow).toBe(balanced.shadow); economy.dispose(); expect(session.shadow).toBe(balanced.shadow);+ balanced.dispose(); expect(session.shadow).toBeNull();+ const minimal = buildFarmLighting(scene, tier(false, 512), environment, on, session);+ expect([minimal.shadow, session.shadow, minimal.sun.castShadow, minimal.sun.shadow.camera.layers.mask]).toEqual([null, null, false, 1]);+ expect((minimal.sun.shadow as { shadowNode?: unknown }).shadowNode).toBeUndefined(); minimal.dispose();+ const plain = buildFarmLighting(scene, tier(true, 2048), environment, { ...on, cache: false, standIns: false }, session);+ expect([plain.shadow, session.shadow, plain.sun.shadow.camera.layers.mask]).toEqual([null, null, 1]); plain.dispose();+ expect(scene.environment).toBeNull();+});++test('S5 live map size (RF-5): full size by default; ?liveMapSize offers OD-9 a smaller live map, never above the tier map', () => {+ expect(farmShadowOptions({ liveMapSize: 1024 })).toEqual({ ...on, liveMapSize: 1024 });+ const scene = new Scene(), session: { shadow: CachedSunShadow | null } = { shadow: null };+ const sizes = (o: typeof on & { liveMapSize?: number }, mapSize: number) => { const l = buildFarmLighting(scene, tier(true, mapSize), environment, o, session), s = [l.shadow!.staticShadow.mapSize.x, l.shadow!.liveShadow.mapSize.x]; l.dispose(); return s; };+ expect([sizes(on, 2048), sizes({ ...on, liveMapSize: 1024 }, 2048), sizes({ ...on, liveMapSize: 1024 }, 512)]).toEqual([[2048, 2048], [2048, 1024], [512, 512]]);+});++// A world as World.tsx binds it: a farmhouse with a door, a fixed fence, the herd's dynamic batch.+function world(optimized = true) {+ const geometry = new BoxGeometry(), material = new MeshStandardMaterial(), root = new Scene();+ const cast = (m: Mesh) => { m.castShadow = true; return m; };+ const place = (id: string, extra?: (clone: Group) => void, action = false): FarmInstance => {+ const object = new Group(), clone = new Group(); object.name = `${id}-0`; clone.name = id; object.add(clone); clone.add(cast(new Mesh(geometry, material))); extra?.(clone); root.add(object);+ const mixer = new AnimationMixer(clone), clips = action ? [new AnimationClip('Spin', 1, [])] : [];+ return { id: object.name, asset: { id }, object, mixer, clips, action: action ? mixer.clipAction(clips[0]!) : null, clipIndex: action ? '0' : '' };+ };+ const pivot = new Group(); pivot.name = 'Joint_FrontDoor'; pivot.position.set(1, 0, 0);+ const leaf = cast(new Mesh(geometry, material)); pivot.add(leaf);+ const house = place('farmhouse', clone => clone.add(pivot)), fence = place('fence-straight'), windmill = place('windmill', undefined, true), tractor = place('tractor'), cow = place('cow', undefined, true);+ const herd = cast(new InstancedMesh(geometry, material, 2)), still = cast(new InstancedMesh(geometry, material, 2)); root.add(herd, still);+ root.updateMatrixWorld(true);+ const batches = { batches: [{ mesh: herd, sources: [], dynamic: true }, { mesh: still, sources: [], dynamic: false }] };+ return { root, house, fence, windmill, tractor, cow, pivot, leaf, herd, still, body: house.object.children[0]!.children[0] as Mesh,+ farm: { root, placements: { instances: [house, fence, windmill, tractor, cow] }, sim: { doors: [{ pivots: [pivot] }] }, optimization: optimized ? { heroes: [house, windmill, tractor], batches } : null } };+}++test('S5 movers: hero wrappers, dynamic batches and door pivots; without optimization every animated, driven or walked owner', () => {+ const w = world(), names = (set: Set<Object3D>) => [...set].map(o => o.name || (o === w.herd ? 'herd' : '?')).sort();+ expect(names(farmShadowMovers(w.farm))).toEqual(['Joint_FrontDoor', 'farmhouse-0', 'herd', 'tractor-0', 'windmill-0']);+ const b = world(false);+ expect([...farmShadowMovers(b.farm)].map(o => o.name).sort()).toEqual(['Joint_FrontDoor', 'cow-0', 'tractor-0', 'windmill-0']);+});++test('S5 binding: tracks once the world shows (a hidden first world would all go live at reveal), promotes only what moves and re-tracks a new cache', () => {+ const w = world(), light = createFarmSun(2048); light.castShadow = true;+ let cache: CachedSunShadow | null = cachedSunShadow({ light, settleFrames: 2 });+ const binding = bindFarmShadow(w.farm, () => cache);+ w.root.visible = false; binding.update();+ expect(w.body.layers.mask).toBe(1); expect(cache.stats.reasons.track).toBeUndefined();+ w.root.visible = true; binding.update();+ expect([w.body.layers.mask, w.leaf.layers.mask, w.herd.layers.mask, w.still.layers.mask]).toEqual([1 | S_BIT, 1 | S_BIT, 1 | S_BIT, 1 | S_BIT]);+ expect(cache.stats.reasons.track).toBe(1); binding.update(); expect(cache.stats.reasons.track).toBe(1);+ // The door swings: only its leaf goes live and the static map re-arms; two still frames later it is static again.+ const armed = cache.stats.staticRenders;+ w.pivot.rotation.y = 1; w.root.updateMatrixWorld(true); binding.update();+ expect([w.leaf.layers.mask, w.body.layers.mask]).toEqual([1 | D_BIT, 1 | S_BIT]); expect(cache.stats.staticRenders).toBe(armed + 1);+ binding.update(); binding.update(); expect(w.leaf.layers.mask).toBe(1 | S_BIT); expect(cache.stats.pendingSettle).toBeGreaterThanOrEqual(0);+ // The herd's instance matrices change: the batch goes live; a static batch never does.+ w.herd.instanceMatrix.needsUpdate = true; w.still.instanceMatrix.needsUpdate = true; binding.update();+ expect([w.herd.layers.mask, w.still.layers.mask]).toEqual([1 | D_BIT, 1 | S_BIT]);+ binding.prime(); expect(cache.liveShadow.camera.layers.mask).toBe(S_BIT | D_BIT);+ // Lights rebuilt: a new cache tracks the same world again.+ cache.dispose(); const next = cachedSunShadow({ light, settleFrames: 2 }); cache = next; binding.update();+ expect(next.stats.reasons.track).toBe(1); expect(w.body.layers.mask).toBe(1 | S_BIT);+ cache = null; binding.update(); next.dispose();+});++test('S5 binding dispose (RF-7): a world that leaves while the cache stays is untracked, and its casters return to their own layers', () => {+ const w = world(), light = createFarmSun(2048); light.castShadow = true;+ const cache = cachedSunShadow({ light, settleFrames: 2 }), binding = bindFarmShadow(w.farm, () => cache);+ binding.update(); expect([w.body.layers.mask, cache.stats.staticCasters]).toEqual([1 | S_BIT, 8]);+ binding.dispose(); expect([w.body.layers.mask, w.leaf.layers.mask, w.herd.layers.mask, cache.stats.staticCasters, cache.stats.reasons.untrack]).toEqual([1, 1, 1, 0, 1]);+ // Disposed: the next frame neither re-tracks the old world nor touches the cache; a second dispose is a no-op.+ binding.update(); binding.dispose(); expect([w.body.layers.mask, cache.stats.reasons.track, cache.stats.reasons.untrack]).toEqual([1, 1, 1]);+ cache.dispose();+});diff --git a/scenes/packages/farm/tests/unit/tiers.test.ts b/scenes/packages/farm/tests/unit/tiers.test.tsindex 076ffa4a..6ad35520 100644--- a/scenes/packages/farm/tests/unit/tiers.test.ts+++ b/scenes/packages/farm/tests/unit/tiers.test.ts@@ -19,6 +19,9 @@ describe('P-16 Farm tier table (SPEC 15)', () => {expect(k.drawDistance).toEqual({ far: 250, fogNear: 120, fogFar: 220, lodBias: 1, streamRadiusScale: 1, zoneHops: 1 });expect(k.effects).toEqual({ water, wind, ambientAnimation: wind });});+ test('OD-10: every tier discards the canvas pass 4x attachments (no viewport-texture node or transmission splits the Farm pass)', () => {+ for (const name of farmTiers.order) expect(knobsOf(name).multisample).toEqual({ discard: true });+ });test('classification start tiers: S24+ high, Tab S9 FE minimal on WebGPU (X-07, both adapter spellings), unknown tablet economy, desktop high, mobile WebGL2 minimal', () => {const tierOf = (patch: Partial<DeviceProbe>) => classifyDevice({ ...phone, ...patch }, farmTiers).tier;expect(tierOf({ adapter: { vendor: 'qualcomm', architecture: 'adreno-7xx', device: '', description: '' } })).toBe('high');diff --git a/scenes/packages/foundry-floor/REPORT.md b/scenes/packages/foundry-floor/REPORT.mdindex 197062f6..3c312fe4 100644--- a/scenes/packages/foundry-floor/REPORT.md+++ b/scenes/packages/foundry-floor/REPORT.md@@ -936,7 +936,10 @@ Each cell gives draw calls / triangles, the full shells drawn (f) and the traffi- Driven views at the high tier: drive start 131 / 218,647; under a bridge 123 / 204,629; at the roundabout 83 /178,999. The traffic takes 13 draws in each driven view, 49,582 to 52,508 triangles.-- Programs 23 to 28 on both backends; pipelines 15 to 18 on WebGPU and 13 to 16 on WebGL2, by view.+- Programs 23 to 28 on both backends; pipelines 15 to 18 on WebGPU and 13 to 16 on WebGL2, by view. Corrected+ 2026-10-02: these are the FF-C1 counts. With the campus vegetation, the campus views measured 87 to 92 programs+ and 78 to 81 pipelines on WebGPU (`main` at `c734e2a`); the draw-optimization shared plant material brings the+ campus view to 27 programs and 17 pipelines.- Inside, FF2's counts are unchanged: landing 117 / 185,631, overview 72 / 104,103, spine 121 / 220,453, litho 37 /58,943, cluster 42 / 82,815, stocker 100 / 183,799, gallery 94 / 142,067, section 88 / 121,465.diff --git a/scenes/packages/foundry-floor/fixtures/count-baseline.json b/scenes/packages/foundry-floor/fixtures/count-baseline.jsonnew file mode 100644index 00000000..04e06ede--- /dev/null+++ b/scenes/packages/foundry-floor/fixtures/count-baseline.json@@ -0,0 +1,583 @@+{+ "schema": "kiln.foundry-floor-count-baseline/1",+ "decision": "OD-8 (D-53)",+ "rule": "Inclusive ±2% draws and triangles; pipelines bound per frame at most +5% of this reference (the cache too under the same page policy); workload fixtures listed, not judged",+ "provenance": {+ "build": "draw-after",+ "commit": "892d103",+ "chunks": [+ "data-DsjFnmns.js",+ "exterior-D40Deo1z.js",+ "index-DFDCL5v-.js",+ "interior-CMvuQhmn.js"+ ],+ "source": "test build draw-after of the working tree at HEAD 892d103 (no uncommitted source changes; build.json source: working tree)",+ "tool": "scripts/check-foundry-counts.ts --record",+ "probe": "scripts/count-probe.ts --scenes foundry-floor --what-if none --build draw-after (summary draw-after-ff)",+ "date": "2026-10-02"+ },+ "conditions": {+ "viewport": [+ 1920,+ 1080+ ],+ "freshPage": false,+ "clock": "frozen",+ "backend": "webgpu",+ "settled": true+ },+ "tiers": {+ "minimal": {+ "campus-bridge": {+ "drawCalls": 68,+ "triangles": 97053,+ "pipelines": 12,+ "pipelineCache": 18,+ "geometries": 121,+ "textures": 8,+ "programs": 29+ },+ "campus-campus": {+ "drawCalls": 96,+ "triangles": 97619,+ "pipelines": 11,+ "pipelineCache": 17,+ "geometries": 104,+ "textures": 8,+ "programs": 27+ },+ "campus-canopy": {+ "drawCalls": 120,+ "triangles": 142057,+ "pipelines": 12,+ "pipelineCache": 18,+ "geometries": 114,+ "textures": 8,+ "programs": 29+ },+ "campus-pair": {+ "drawCalls": 96,+ "triangles": 97619,+ "pipelines": 11,+ "pipelineCache": 17,+ "geometries": 104,+ "textures": 8,+ "programs": 27+ },+ "campus-roundabout": {+ "drawCalls": 112,+ "triangles": 124749,+ "pipelines": 12,+ "pipelineCache": 18,+ "geometries": 123,+ "textures": 8,+ "programs": 29+ },+ "campus-split": {+ "drawCalls": 118,+ "triangles": 139045,+ "pipelines": 12,+ "pipelineCache": 18,+ "geometries": 118,+ "textures": 8,+ "programs": 29+ },+ "drive": {+ "drawCalls": 119,+ "triangles": 150635,+ "pipelines": 14,+ "pipelineCache": 20,+ "geometries": 128,+ "textures": 8,+ "programs": 32,+ "workload": true+ },+ "fab-cluster": {+ "drawCalls": 40,+ "triangles": 75135,+ "pipelines": 6,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ },+ "fab-gallery": {+ "drawCalls": 103,+ "triangles": 164308,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ },+ "fab-landing": {+ "drawCalls": 134,+ "triangles": 203476,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 135,+ "textures": 5,+ "programs": 16+ },+ "fab-litho": {+ "drawCalls": 39,+ "triangles": 59061,+ "pipelines": 6,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ },+ "fab-overview": {+ "drawCalls": 81,+ "triangles": 125806,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 146,+ "textures": 5,+ "programs": 16+ },+ "fab-section": {+ "drawCalls": 99,+ "triangles": 140862,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 165,+ "textures": 5,+ "programs": 16+ },+ "fab-spine": {+ "drawCalls": 130,+ "triangles": 237960,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 157,+ "textures": 5,+ "programs": 16+ },+ "fab-stocker": {+ "drawCalls": 119,+ "triangles": 203424,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ }+ },+ "economy": {+ "campus-bridge": {+ "drawCalls": 75,+ "triangles": 134292,+ "pipelines": 14,+ "pipelineCache": 20,+ "geometries": 119,+ "textures": 8,+ "programs": 32+ },+ "campus-campus": {+ "drawCalls": 96,+ "triangles": 108683,+ "pipelines": 11,+ "pipelineCache": 17,+ "geometries": 104,+ "textures": 8,+ "programs": 27+ },+ "campus-canopy": {+ "drawCalls": 120,+ "triangles": 156289,+ "pipelines": 12,+ "pipelineCache": 18,+ "geometries": 114,+ "textures": 8,+ "programs": 29+ },+ "campus-pair": {+ "drawCalls": 96,+ "triangles": 108683,+ "pipelines": 11,+ "pipelineCache": 17,+ "geometries": 104,+ "textures": 8,+ "programs": 27+ },+ "campus-roundabout": {+ "drawCalls": 116,+ "triangles": 143631,+ "pipelines": 12,+ "pipelineCache": 20,+ "geometries": 125,+ "textures": 8,+ "programs": 32+ },+ "campus-split": {+ "drawCalls": 133,+ "triangles": 175029,+ "pipelines": 12,+ "pipelineCache": 18,+ "geometries": 117,+ "textures": 8,+ "programs": 29+ },+ "drive": {+ "drawCalls": 136,+ "triangles": 193929,+ "pipelines": 14,+ "pipelineCache": 20,+ "geometries": 127,+ "textures": 8,+ "programs": 32,+ "workload": true+ },+ "fab-cluster": {+ "drawCalls": 40,+ "triangles": 75135,+ "pipelines": 6,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ },+ "fab-gallery": {+ "drawCalls": 103,+ "triangles": 164308,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ },+ "fab-landing": {+ "drawCalls": 134,+ "triangles": 203476,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 135,+ "textures": 5,+ "programs": 16+ },+ "fab-litho": {+ "drawCalls": 39,+ "triangles": 59061,+ "pipelines": 6,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ },+ "fab-overview": {+ "drawCalls": 81,+ "triangles": 125806,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 146,+ "textures": 5,+ "programs": 16+ },+ "fab-section": {+ "drawCalls": 99,+ "triangles": 140862,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 165,+ "textures": 5,+ "programs": 16+ },+ "fab-spine": {+ "drawCalls": 130,+ "triangles": 237960,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 157,+ "textures": 5,+ "programs": 16+ },+ "fab-stocker": {+ "drawCalls": 119,+ "triangles": 203424,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ }+ },+ "balanced": {+ "campus-bridge": {+ "drawCalls": 87,+ "triangles": 177141,+ "pipelines": 14,+ "pipelineCache": 20,+ "geometries": 124,+ "textures": 8,+ "programs": 32+ },+ "campus-campus": {+ "drawCalls": 96,+ "triangles": 122987,+ "pipelines": 11,+ "pipelineCache": 17,+ "geometries": 104,+ "textures": 8,+ "programs": 27+ },+ "campus-canopy": {+ "drawCalls": 137,+ "triangles": 200867,+ "pipelines": 12,+ "pipelineCache": 18,+ "geometries": 115,+ "textures": 8,+ "programs": 29+ },+ "campus-pair": {+ "drawCalls": 96,+ "triangles": 122987,+ "pipelines": 11,+ "pipelineCache": 17,+ "geometries": 104,+ "textures": 8,+ "programs": 27+ },+ "campus-roundabout": {+ "drawCalls": 117,+ "triangles": 169503,+ "pipelines": 12,+ "pipelineCache": 20,+ "geometries": 127,+ "textures": 8,+ "programs": 32+ },+ "campus-split": {+ "drawCalls": 138,+ "triangles": 200917,+ "pipelines": 12,+ "pipelineCache": 18,+ "geometries": 121,+ "textures": 8,+ "programs": 29+ },+ "drive": {+ "drawCalls": 143,+ "triangles": 232993,+ "pipelines": 14,+ "pipelineCache": 20,+ "geometries": 132,+ "textures": 8,+ "programs": 32,+ "workload": true+ },+ "fab-cluster": {+ "drawCalls": 40,+ "triangles": 75135,+ "pipelines": 6,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ },+ "fab-gallery": {+ "drawCalls": 103,+ "triangles": 164308,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ },+ "fab-landing": {+ "drawCalls": 134,+ "triangles": 203476,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 135,+ "textures": 5,+ "programs": 16+ },+ "fab-litho": {+ "drawCalls": 39,+ "triangles": 59061,+ "pipelines": 6,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ },+ "fab-overview": {+ "drawCalls": 81,+ "triangles": 125806,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 146,+ "textures": 5,+ "programs": 16+ },+ "fab-section": {+ "drawCalls": 99,+ "triangles": 140862,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 165,+ "textures": 5,+ "programs": 16+ },+ "fab-spine": {+ "drawCalls": 130,+ "triangles": 237960,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 157,+ "textures": 5,+ "programs": 16+ },+ "fab-stocker": {+ "drawCalls": 119,+ "triangles": 203424,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ }+ },+ "high": {+ "campus-bridge": {+ "drawCalls": 88,+ "triangles": 207075,+ "pipelines": 14,+ "pipelineCache": 20,+ "geometries": 125,+ "textures": 8,+ "programs": 32+ },+ "campus-campus": {+ "drawCalls": 96,+ "triangles": 137051,+ "pipelines": 11,+ "pipelineCache": 17,+ "geometries": 104,+ "textures": 8,+ "programs": 27+ },+ "campus-canopy": {+ "drawCalls": 140,+ "triangles": 225941,+ "pipelines": 12,+ "pipelineCache": 18,+ "geometries": 117,+ "textures": 8,+ "programs": 29+ },+ "campus-pair": {+ "drawCalls": 103,+ "triangles": 154280,+ "pipelines": 11,+ "pipelineCache": 17,+ "geometries": 104,+ "textures": 8,+ "programs": 27+ },+ "campus-roundabout": {+ "drawCalls": 118,+ "triangles": 202129,+ "pipelines": 12,+ "pipelineCache": 20,+ "geometries": 129,+ "textures": 8,+ "programs": 32+ },+ "campus-split": {+ "drawCalls": 138,+ "triangles": 227157,+ "pipelines": 12,+ "pipelineCache": 18,+ "geometries": 120,+ "textures": 8,+ "programs": 29+ },+ "drive": {+ "drawCalls": 144,+ "triangles": 262555,+ "pipelines": 14,+ "pipelineCache": 20,+ "geometries": 133,+ "textures": 8,+ "programs": 32,+ "workload": true+ },+ "fab-cluster": {+ "drawCalls": 40,+ "triangles": 75135,+ "pipelines": 6,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ },+ "fab-gallery": {+ "drawCalls": 103,+ "triangles": 164308,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ },+ "fab-landing": {+ "drawCalls": 134,+ "triangles": 203476,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 135,+ "textures": 5,+ "programs": 16+ },+ "fab-litho": {+ "drawCalls": 39,+ "triangles": 59061,+ "pipelines": 6,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ },+ "fab-overview": {+ "drawCalls": 81,+ "triangles": 125806,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 146,+ "textures": 5,+ "programs": 16+ },+ "fab-section": {+ "drawCalls": 99,+ "triangles": 140862,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 165,+ "textures": 5,+ "programs": 16+ },+ "fab-spine": {+ "drawCalls": 130,+ "triangles": 237960,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 157,+ "textures": 5,+ "programs": 16+ },+ "fab-stocker": {+ "drawCalls": 119,+ "triangles": 203424,+ "pipelines": 7,+ "pipelineCache": 8,+ "geometries": 158,+ "textures": 5,+ "programs": 16+ }+ }+ }+}diff --git a/scenes/packages/foundry-floor/src/campus/World.tsx b/scenes/packages/foundry-floor/src/campus/World.tsxindex c50f6a7a..4df21dff 100644--- a/scenes/packages/foundry-floor/src/campus/World.tsx+++ b/scenes/packages/foundry-floor/src/campus/World.tsx@@ -9,6 +9,7 @@ import { SystemOrder, useFade, useLoadedPack, usePlayMode, useRegisterTestHooks,import { useThree } from '@react-three/fiber';import { useCampusSession } from './session';import type { CampusPlace } from './session';+import { foundryProbeAsset, foundryProbeSystems } from './probe-systems';const TEST = !!(import.meta.env.KILN_TEST || import.meta.env.KILN_DEV);const FADE_MS = 350;@@ -67,6 +68,9 @@ export function CampusWorld() {campusResources:()=>({models:[...pack.models.keys()],exterior:!!scene.getObjectByName('campus-exterior'),context:!!scene.getObjectByName('campus-interior-context')}),campusEnter: () => { campus.enter(); return true; },campusExit: () => { campus.exit(); return true; },+ /** Count-probe systems and fab entity names (scene-kit testing/probe.ts), found by name for either place. */+ probeSystems: () => foundryProbeSystems(scene),+ probeAsset: foundryProbeAsset,};}, [campus,pack,scene]);useRegisterTestHooks(hooks);diff --git a/scenes/packages/foundry-floor/src/campus/exterior/Exterior.tsx b/scenes/packages/foundry-floor/src/campus/exterior/Exterior.tsxindex c0671831..76655a3b 100644--- a/scenes/packages/foundry-floor/src/campus/exterior/Exterior.tsx+++ b/scenes/packages/foundry-floor/src/campus/exterior/Exterior.tsx@@ -10,7 +10,7 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { useThree } from '@react-three/fiber';import { Box3, Group, Vector3 } from 'three/webgpu';import type { PerspectiveCamera } from 'three/webgpu';-import { asWebGPU, OrbitRig, SystemOrder, useFade, useLoadedPack, usePlayMode, useQuality, useReducedMotion, useRegisterTestHooks, useSceneBuilt, useSceneClock, useSystem } from '@kiln-scenes/scene-kit';+import { asWebGPU, OrbitRig, readDevParams, SystemOrder, useFade, useLoadedPack, usePlayMode, useQuality, useReducedMotion, useRegisterTestHooks, useSceneBuilt, useSceneClock, useSystem } from '@kiln-scenes/scene-kit';import { CAMPUS_DATA_ID, CAMPUS_VIEW_NAMES, parseCampus } from '../data';import type { CampusData, CampusTierName, CampusViewName } from '../data';import { useCampusSession } from '../session';@@ -125,7 +125,9 @@ export function CampusExterior() {if(hasPlants&&!bytes)throw new Error('The scene pack has plants but no campus-assets data');placements=hasPlants?parseCampusPlantings(bytes!,data):[];} catch(error){setFailure(error);return;}- buildCampusVegetation(data, pack.models, placements).then(value => {+ // Test and dev builds take ?plantingShared=false (the per-material planting) for A/B counts and captures.+ const shared = (TEST ? readDevParams({ plantingShared: { kind: 'boolean' } }).plantingShared : undefined) !== false;+ buildCampusVegetation(data, pack.models, placements, { shared }).then(value => {if (!alive) { value?.dispose(); return; }planted = value; if (value) world.root.add(value.root); setVegetation(value);}, error => { if (alive) setFailure(error); });diff --git a/scenes/packages/foundry-floor/src/campus/exterior/plant-material.ts b/scenes/packages/foundry-floor/src/campus/exterior/plant-material.tsnew file mode 100644index 00000000..a0bc1476--- /dev/null+++ b/scenes/packages/foundry-floor/src/campus/exterior/plant-material.ts@@ -0,0 +1,55 @@+// SPDX-License-Identifier: MIT+// One material graph for every campus plant. Each part's colour and roughness arrive as vertex data (`plantLook`, linear+// rgb then roughness), so the leaf, needle and bark materials of eight plant types draw through one material. Instancing is+// the material's, as in the fab's baked groups (scene/glb/materials.ts): each instance's matrix arrives as four instanced+// vec4 attributes (PLANT_COLUMNS) on a plain Mesh, so every plant mesh shares one node build, one program pair and one+// pipeline, where three 0.186 gives every InstancedMesh of at most 1,024 instances a uniform buffer named after its node id+// and its uuid in the cache key (a pipeline per mesh).+import { FrontSide, MeshStandardNodeMaterial } from 'three/webgpu';+import type { Material, MeshStandardMaterial, Node, NodeBuilder } from 'three/webgpu';+import { attribute, mat4, normalLocal, positionLocal, transformNormal, vec4 } from 'three/tsl';++// TSL's node types are loose; one alias keeps the calls readable (as the fab's materials do).+type N = any; // eslint-disable-line @typescript-eslint/no-explicit-any++/** The instance matrix columns (column-major, as Matrix4.elements) of a plant mesh's instances. */+export const PLANT_COLUMNS = ['plantI0', 'plantI1', 'plantI2', 'plantI3'] as const;++/**+ * The instance transform lives in setupPosition, which only this material's own build runs: a pass that draws with an override+ * material (shadow depth, a depth prepass, picking) would put every plant at its origin. Shared plant meshes therefore never+ * cast shadows (tests/unit/campus-vegetation-shared.test.ts); a pass like that needs the transform in a node it carries over.+ */+class InstancedPlantMaterial extends MeshStandardNodeMaterial {+ override customProgramCacheKey(): string { return super.customProgramCacheKey() + ':plant-instanced'; }+ override setupPosition(builder: NodeBuilder): Node {+ const [c0, c1, c2, c3] = PLANT_COLUMNS.map(name => attribute(name, 'vec4') as N);+ const m = (mat4 as N)(c0, c1, c2, c3) as N;+ (positionLocal as N).assign(m.mul(positionLocal).xyz);+ (normalLocal as N).assign(transformNormal(normalLocal as N, m));+ return super.setupPosition(builder);+ }+}++/** The one material every shared plant mesh uses: opaque, matte, FrontSide, colour and roughness from `plantLook`. */+export function createPlantMaterial(): MeshStandardNodeMaterial {+ const material = new InstancedPlantMaterial(), look = attribute('plantLook', 'vec4') as N;+ material.name = 'foundry-floor-plant';+ material.side = FrontSide;+ material.colorNode = vec4(look.xyz, 1);+ material.roughnessNode = look.w;+ return material;+}++/**+ * A part's look as vertex data: the linear colour and roughness of a plain opaque matte standard material (what the saved+ * plants use, no maps, no emission), or null for any material that data cannot reproduce exactly. The float32 values are+ * the ones the material's own uniforms would hold.+ */+export function plantLook(material: Material): [number, number, number, number] | null {+ const m = material as MeshStandardMaterial;+ if (!m.isMeshStandardMaterial || (m as { isMeshPhysicalMaterial?: boolean }).isMeshPhysicalMaterial || (m as { isNodeMaterial?: boolean }).isNodeMaterial) return null;+ if (m.metalness !== 0 || m.emissive.r + m.emissive.g + m.emissive.b !== 0 || m.transparent || m.opacity !== 1 || m.side !== FrontSide || m.vertexColors || m.alphaTest !== 0 || m.flatShading || m.envMapIntensity !== 1) return null;+ for (const key in m) if ((m as unknown as Record<string, { isTexture?: boolean } | null>)[key]?.isTexture) return null;+ return [Math.fround(m.color.r), Math.fround(m.color.g), Math.fround(m.color.b), Math.fround(m.roughness)];+}diff --git a/scenes/packages/foundry-floor/src/campus/exterior/vegetation.ts b/scenes/packages/foundry-floor/src/campus/exterior/vegetation.tsindex 8ca9f631..dedebfcb 100644--- a/scenes/packages/foundry-floor/src/campus/exterior/vegetation.ts+++ b/scenes/packages/foundry-floor/src/campus/exterior/vegetation.ts@@ -1,23 +1,31 @@// SPDX-License-Identifier: MIT-// Shared geometry per saved model/material/LOD. No per-tree clones or geometry generated in the frame loop.-import { Box3, Frustum, Group, InstancedMesh, Matrix4, Sphere, Vector3 } from 'three/webgpu';-import type { BufferGeometry, Material, Mesh, Object3D, PerspectiveCamera } from 'three/webgpu';+// Shared geometry per saved model/LOD. No per-tree clones or geometry generated in the frame loop. Shared planting (the+// default; dev parameter plantingShared=false keeps the per-material path) merges a level's parts into one geometry with+// each part's colour and roughness as vertex data and draws it through the one material of ./plant-material: one draw per+// plant type and level, one pipeline for all of them. The per-material path (one InstancedMesh per type, level and+// material) still serves a level whose material the vertex data cannot reproduce exactly.+import { Box3, Float32BufferAttribute, Frustum, Group, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, InterleavedBufferAttribute, Matrix4, Mesh, Sphere, Vector3 } from 'three/webgpu';+import type { BufferGeometry, Material, MeshStandardNodeMaterial, Object3D, PerspectiveCamera } from 'three/webgpu';import type { GLTF } from 'three/addons/loaders/GLTFLoader.js';import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';import { plantLod } from './plant-lod';+import { createPlantMaterial, PLANT_COLUMNS, plantLook } from './plant-material';import type { CampusData } from '../data';import { PLANT_SIZES, type PlantPlacement, type PlantType } from './planting';-interface Bucket { mesh: InstancedMesh; count: number; triangles: number }+/** A shared mesh's instance buffer: the placement row in each slot, so a slot is rewritten only when its row changes. */+interface Slots { geometry: InstancedBufferGeometry; data: InstancedInterleavedBuffer; rows: Int32Array; changed: boolean }+interface Bucket { mesh: Mesh; count: number; triangles: number; slots?: Slots }interface PlantModel { levels: Bucket[][]; centre: Vector3; radius: number; height:number }-export async function buildCampusVegetation(data:CampusData,models:ReadonlyMap<string,GLTF>,placements:readonly PlantPlacement[]) {- const types=Object.keys(PLANT_SIZES) as PlantType[];+export async function buildCampusVegetation(data:CampusData,models:ReadonlyMap<string,GLTF>,placements:readonly PlantPlacement[],options:{shared?:boolean}={}) {+ const types=Object.keys(PLANT_SIZES) as PlantType[], shared=options.shared!==false;if(!types.some(type=>models.has(`plant-${type}`)))return null;const root=new Group();root.name='campus-planting';const materials=new Map<Material,Material>(), geometry:BufferGeometry[]=[];+ let plantMaterial:MeshStandardNodeMaterial|null=null;const extracted=new Map<PlantType,PlantModel>();- const dispose=()=>{root.removeFromParent();for(const mesh of root.children as InstancedMesh[])mesh.dispose();root.clear();geometry.forEach(g=>g.dispose());materials.forEach(m=>m.dispose());};+ const dispose=()=>{root.removeFromParent();for(const mesh of root.children as InstancedMesh[])if(mesh.isInstancedMesh)mesh.dispose();root.clear();geometry.forEach(g=>g.dispose());materials.forEach(m=>m.dispose());plantMaterial?.dispose();};try {for(const type of types){const gltf=models.get(`plant-${type}`);if(!gltf)throw new Error(`Missing plant-${type} in the campus pack`);@@ -27,7 +35,7 @@ export async function buildCampusVegetation(data:CampusData,models:ReadonlyMap<sconst ids=index===undefined?undefined:gltf.parser.json.nodes?.[index]?.extensions?.MSFT_lod?.ids;if(!Array.isArray(ids)||ids.length!==2)throw new Error(`${type}: expected three declared plant levels`);const levels=[base,...await Promise.all(ids.map(id=>gltf.parser.getDependency('node',id) as Promise<Object3D>))];- const bounds=new Box3(), capacity=placements.filter(p=>p.model===type).length;+ const bounds=new Box3(), capacity=Math.max(1,placements.filter(p=>p.model===type).length);const buckets:Bucket[][]=[];for(const [level,object] of levels.entries()){const parts=new Map<Material,BufferGeometry[]>();@@ -44,13 +52,30 @@ export async function buildCampusVegetation(data:CampusData,models:ReadonlyMap<sfor(const child of node.children)visit(child,world);};visit(object,base.parent?.matrixWorld??new Matrix4());- const levelBuckets:Bucket[]=[];- for(const [material,partsForMaterial] of parts){+ const levelBuckets:Bucket[]=[], triangles=(g:BufferGeometry)=>(g.index?.count??g.getAttribute('position').count)/3;+ const looks=shared?[...parts.keys()].map(plantLook):[];+ if(shared&&parts.size&&looks.every(Boolean)){+ // One geometry for the level: each part's look as a vertex attribute, then one instanced draw on the shared material.+ const all:BufferGeometry[]=[];+ [...parts.values()].forEach((list,k)=>{for(const part of list){+ const n=part.getAttribute('position').count,look=new Float32Array(n*4);for(let i=0;i<n;i++)look.set(looks[k]!,i*4);+ part.setAttribute('plantLook',new Float32BufferAttribute(look,4));all.push(part);+ }});+ const merged=mergeGeometries(all);all.forEach(p=>p.dispose());+ if(!merged)throw new Error(`${type}: plant geometry could not be merged`);+ const instanced=new InstancedBufferGeometry();instanced.name=`${type}-lod${level}`;+ for(const [name,attribute] of Object.entries(merged.attributes))instanced.setAttribute(name,attribute);+ const buffer=new InstancedInterleavedBuffer(new Float32Array(capacity*16),16,1);+ PLANT_COLUMNS.forEach((column,k)=>instanced.setAttribute(column,new InterleavedBufferAttribute(buffer,4,k*4)));+ instanced.instanceCount=0;geometry.push(instanced);+ const mesh=new Mesh(instanced,plantMaterial??=createPlantMaterial());mesh.name=instanced.name;mesh.frustumCulled=false;mesh.matrixAutoUpdate=false;mesh.visible=false;root.add(mesh);+ levelBuckets.push({mesh,count:0,triangles:triangles(merged),slots:{geometry:instanced,data:buffer,rows:new Int32Array(capacity).fill(-1),changed:true}});+ } else for(const [material,partsForMaterial] of parts){const merged=mergeGeometries(partsForMaterial);partsForMaterial.forEach(p=>p.dispose());if(!merged)throw new Error(`${type}: plant geometry could not be merged`);geometry.push(merged);let owned=materials.get(material);if(!owned){owned=material.clone();materials.set(material,owned);}- const mesh=new InstancedMesh(merged,owned,Math.max(1,capacity));mesh.name=`${type}-lod${level}-${material.name}`;mesh.frustumCulled=false;mesh.count=0;root.add(mesh);- levelBuckets.push({mesh,count:0,triangles:(merged.index?.count??merged.getAttribute('position').count)/3});+ const mesh=new InstancedMesh(merged,owned,capacity);mesh.name=`${type}-lod${level}-${material.name}`;mesh.frustumCulled=false;mesh.count=0;root.add(mesh);+ levelBuckets.push({mesh,count:0,triangles:triangles(merged)});}buckets.push(levelBuckets);}@@ -67,23 +92,33 @@ export async function buildCampusVegetation(data:CampusData,models:ReadonlyMap<sfrustum.setFromProjectionMatrix(projection.multiplyMatrices(camera.projectionMatrix,camera.matrixWorldInverse));for(const model of extracted.values())for(const level of model.levels)for(const bucket of level)bucket.count=0;visible=0;draws=0;triangles=0;perLevel.fill(0);- for(const row of rows){- const {p}=row,model=extracted.get(p.model)!;+ for(let i=0;i<rows.length;i++){+ const row=rows[i]!,{p}=row,model=extracted.get(p.model)!;sphere.center.copy(model.centre).applyMatrix4(row.matrix);sphere.radius=model.radius;const distance=eye.distanceTo(sphere.center),small=p.model==='shrub-mound'||p.model==='hedge-4m';if((small&&distance>600)||!frustum.intersectsSphere(sphere))continue;// Camera-space depth and the live projection include the drive camera's speed-dependent FOV.const depth=Math.max(.1,-cameraPoint.copy(sphere.center).applyMatrix4(camera.matrixWorldInverse).z);row.level=plantLod(model.height*camera.projectionMatrix.elements[5]!/(2*depth),lodBias,row.level);- for(const bucket of model.levels[row.level]!)bucket.mesh.setMatrixAt(bucket.count++,row.matrix);+ for(const bucket of model.levels[row.level]!){+ const slot=bucket.count++,slots=bucket.slots;+ if(!slots)(bucket.mesh as InstancedMesh).setMatrixAt(slot,row.matrix);+ else if(slots.rows[slot]!==i){slots.rows[slot]=i;row.matrix.toArray(slots.data.array as Float32Array,slot*16);slots.changed=true;}+ }visible++;perLevel[row.level]!++;}for(const model of extracted.values())for(const level of model.levels)for(const bucket of level){- bucket.mesh.count=bucket.count;bucket.mesh.visible=bucket.count>0;- if(bucket.count){bucket.mesh.instanceMatrix.needsUpdate=true;draws++;triangles+=bucket.count*bucket.triangles;}+ const {mesh,count,slots}=bucket;mesh.visible=count>0;+ if(slots){+ // Upload only when a slot's row or the count changed, and only the slots in use.+ if(slots.geometry.instanceCount!==count){slots.geometry.instanceCount=count;slots.changed=true;}+ if(slots.changed&&count){slots.data.clearUpdateRanges();slots.data.addUpdateRange(0,count*16);slots.data.needsUpdate=true;}+ slots.changed=false;+ } else {(mesh as InstancedMesh).count=count;if(count)(mesh as InstancedMesh).instanceMatrix.needsUpdate=true;}+ if(count){draws++;triangles+=count*bucket.triangles;}}},- stats:()=>({placed:placements.length,visible,draws,triangles,perLevel:[...perLevel],byZone:Object.fromEntries(['avenue','windbreak','parking','island','arrival'].map(zone=>[zone,placements.filter(p=>p.zone===zone).length]))}),+ stats:()=>({placed:placements.length,visible,draws,triangles,perLevel:[...perLevel],shared,byZone:Object.fromEntries(['avenue','windbreak','parking','island','arrival'].map(zone=>[zone,placements.filter(p=>p.zone===zone).length]))}),dispose,};}diff --git a/scenes/packages/foundry-floor/src/campus/probe-systems.ts b/scenes/packages/foundry-floor/src/campus/probe-systems.tsnew file mode 100644index 00000000..51643ec5--- /dev/null+++ b/scenes/packages/foundry-floor/src/campus/probe-systems.ts@@ -0,0 +1,28 @@+// SPDX-License-Identifier: MIT+import type { Object3D } from 'three/webgpu';++/** Baked fab groups are named `<entity>:…` (scene/glb/bake.ts); the count probe groups them by role. */+const FAB_ROLES: Record<string, string> = {+ floorModule: 'fab-building', ceilingModule: 'fab-building', sectionModule: 'fab-building', gallerySegment: 'fab-building', subfabKit: 'fab-building', wallKit: 'fab-building',+ tool: 'fab-tools', loadPort: 'fab-tools', signalTower: 'fab-tools',+ vehicle: 'fab-movers', amrFloorRobot: 'fab-movers', humanoidWorkRobot: 'fab-movers', technician: 'fab-movers', toolFrontRobotArm: 'fab-movers', foup: 'fab-movers', stocker: 'fab-movers',+ railCurve: 'fab-transport', railSwitch: 'fab-transport', railStraight: 'fab-transport', uts: 'fab-transport',+};+const CAMPUS = ['campus-sky', 'campus-ground', 'campus-structures', 'campus-planting', 'campus-traffic', 'campus-interior-context'];++/**+ * Test and dev builds only (campus/World.tsx registers it behind TEST): count-probe systems (scene-kit testing/probe.ts),+ * found by name at call time so one hook serves the exterior and the interior. Exterior systems are the campus groups;+ * inside, the baked fab groups are grouped by role and the proxies and pulses keep their own names.+ */+export function foundryProbeSystems(scene: Object3D): Record<string, Object3D[]> {+ const systems: Record<string, Object3D[]> = {}, add = (name: string, object: Object3D) => (systems[name] ??= []).push(object);+ for (const name of CAMPUS) { const object = scene.getObjectByName(name); if (object) add(name.replace(/^campus-/, ''), object); }+ for (const child of scene.getObjectByName('foundry-floor-world')?.children ?? []) add(FAB_ROLES[child.name.split(':')[0]!] ?? (child.name ? child.name.replace(/^foundry-floor-/, 'fab-') : 'fab-unnamed'), child);+ return systems;+}+/** Fab groups name their entity (`tool:<type>` or the class); campus meshes keep the default (pack model or mesh name). */+export function foundryProbeAsset(object: Object3D): string | null {+ const parts = object.name.split(':');+ return parts.length > 2 && object.parent?.name === 'foundry-floor-world' ? parts[0] === 'tool' ? `tool:${parts[1]}` : parts[0]! : null;+}diff --git a/scenes/packages/foundry-floor/src/definition.ts b/scenes/packages/foundry-floor/src/definition.tsindex 15605213..f0469397 100644--- a/scenes/packages/foundry-floor/src/definition.ts+++ b/scenes/packages/foundry-floor/src/definition.ts@@ -11,6 +11,8 @@ function tier(pixelRatioCap: number): TierKnobs {vegetationDensity: 0, instanceDensity: 1,drawDistance: { far: 400, fogNear: 300, fogFar: 400, lodBias: 1, streamRadiusScale: 1, zoneHops: 1 },effects: { water: 'off', wind: false, ambientAnimation: true },+ // OD-10: no viewport-texture node or transmission splits the main pass.+ multisample: { discard: true },};}diff --git a/scenes/packages/foundry-floor/tests/unit/campus-vegetation-shared.test.ts b/scenes/packages/foundry-floor/tests/unit/campus-vegetation-shared.test.tsnew file mode 100644index 00000000..6ee25c28--- /dev/null+++ b/scenes/packages/foundry-floor/tests/unit/campus-vegetation-shared.test.ts@@ -0,0 +1,187 @@+// The shared planting path (dev parameter plantingShared): one material graph for every plant, each part's colour and+// roughness carried in its vertices, one instanced draw per plant type and LOD level. Synthetic plants (the real GLBs+// are not in a fresh clone), built the way the saved ones are: three declared levels, material objects shared by level.+import { describe, expect, test } from 'bun:test';+import { existsSync, readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { BoxGeometry, Group, InstancedBufferGeometry, InstancedMesh, InterleavedBufferAttribute, Mesh, MeshStandardMaterial, PerspectiveCamera } from 'three/webgpu';+import type { Object3D } from 'three/webgpu';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import type { GLTF } from 'three/addons/loaders/GLTFLoader.js';+import { parseCampus } from '../../src/campus/data';+import { campusPlantings, PLANT_SIZES } from '../../src/campus/exterior/planting';+import type { PlantType } from '../../src/campus/exterior/planting';+import { buildCampusVegetation } from '../../src/campus/exterior/vegetation';+import { PLANT_COLUMNS, plantLook } from '../../src/campus/exterior/plant-material';++const PACKAGE = resolve(import.meta.dir, '../..');+const data = parseCampus(readFileSync(resolve(PACKAGE, 'data/campus.json'), 'utf8')), placements = campusPlantings(data);+const BARK = { color: 0x6b6259, roughness: 0.95 }, MID = { color: 0x4f7a3a, roughness: 0.9 }, LIGHT = { color: 0x6e9a47, roughness: 0.9 }, DARK = { color: 0x37592b, roughness: 0.9 };+const LAYERS: Record<string, { name: string; look: { color: number; roughness: number } }[][]> = {+ broad: [[{ name: 'Trunk', look: BARK }, { name: 'CrownMid', look: MID }, { name: 'CrownLight', look: LIGHT }, { name: 'CrownDark', look: DARK }], [{ name: 'Trunk', look: BARK }, { name: 'CrownMid', look: MID }, { name: 'CrownDark', look: DARK }], [{ name: 'Trunk', look: BARK }, { name: 'CrownMid', look: MID }]],+ bush: [[{ name: 'Foliage', look: MID }], [{ name: 'Foliage', look: MID }], [{ name: 'Foliage', look: MID }]],+};++/** A plant shaped like the saved ones: LOD0 under the scene root, the two lower levels reached through MSFT_lod. */+function plant(type: PlantType, layers = LAYERS[type.startsWith('shrub') || type.startsWith('hedge') ? 'bush' : 'broad']!, extra?: (material: MeshStandardMaterial) => void): GLTF {+ const height = PLANT_SIZES[type][1], materials = new Map<string, MeshStandardMaterial>(), root = new Group(), levels: Object3D[] = [];+ root.name = `${type}_1`;+ layers.forEach((parts, level) => {+ const node = new Group(); node.name = `LOD${level}`;+ parts.forEach((part, k) => {+ const key = `${part.look.color}`;+ let material = materials.get(key);+ if (!material) { material = new MeshStandardMaterial({ color: part.look.color, roughness: part.look.roughness, name: part.name }); extra?.(material); materials.set(key, material); }+ const geometry = new BoxGeometry(1 + k, height / (k + 2), 1 + k).translate(0, height * (k + 1) / (k + 3), 0);+ const mesh = new Mesh(geometry, material); mesh.name = `${part.name}_${level}`; node.add(mesh);+ });+ levels.push(node);+ });+ root.add(levels[0]!);+ return { scene: root, parser: { associations: new Map([[levels[0], { nodes: 0 }]]), json: { nodes: [{ extensions: { MSFT_lod: { ids: [1, 2] } } }] }, getDependency: async (_: string, id: number) => levels[id]! } } as unknown as GLTF;+}+const models = (make: (type: PlantType) => GLTF = type => plant(type)) => new Map(Object.keys(PLANT_SIZES).map(type => [`plant-${type}`, make(type as PlantType)]));++const near = () => { const c = new PerspectiveCamera(50, 1, .1, 20000); c.position.set(0, 50, 110); c.lookAt(0, 0, 0); c.updateMatrixWorld(); return c; };+const far = () => { const c = new PerspectiveCamera(50, 1, .1, 20000); c.position.set(0, 2200, 2800); c.lookAt(0, 0, 0); c.updateMatrixWorld(); return c; };+const meshes = (root: Group) => root.children as Mesh[];+const columnsOf = (mesh: Mesh) => PLANT_COLUMNS.map(name => (mesh.geometry.getAttribute(name) as InterleavedBufferAttribute));++describe('plantLook: the parts one vertex material can carry', () => {+ test('a plain opaque matte standard material is carried as its linear colour and roughness', () => {+ const material = new MeshStandardMaterial({ color: 0x4f7a3a, roughness: 0.9 });+ expect(plantLook(material)).toEqual([Math.fround(material.color.r), Math.fround(material.color.g), Math.fround(material.color.b), Math.fround(0.9)]);+ });+ test('anything it cannot reproduce exactly is refused: maps, emission, metal, translucency, two sides, vertex colours', () => {+ const base = () => new MeshStandardMaterial({ color: 0x4f7a3a, roughness: 0.9 });+ const refused = [(m: MeshStandardMaterial) => { m.metalness = 0.5; }, (m: MeshStandardMaterial) => { m.emissive.set(0x101010); }, (m: MeshStandardMaterial) => { m.transparent = true; },+ (m: MeshStandardMaterial) => { m.opacity = 0.5; }, (m: MeshStandardMaterial) => { m.side = 2; }, (m: MeshStandardMaterial) => { m.vertexColors = true; },+ (m: MeshStandardMaterial) => { m.alphaTest = 0.5; }, (m: MeshStandardMaterial) => { m.flatShading = true; }, (m: MeshStandardMaterial) => { m.envMapIntensity = 2; }];+ for (const change of refused) { const m = base(); change(m); expect(plantLook(m)).toBeNull(); }+ const textured = base(); textured.map = { isTexture: true } as never; expect(plantLook(textured)).toBeNull();+ });+});++describe('shared planting', () => {+ test('every plant draws through one material and one instanced draw per type and level, none an InstancedMesh', async () => {+ const shared = (await buildCampusVegetation(data, models(), placements, { shared: true }))!;+ expect(meshes(shared.root)).toHaveLength(Object.keys(PLANT_SIZES).length * 3);+ expect(new Set(meshes(shared.root).map(m => m.material)).size).toBe(1);+ for (const mesh of meshes(shared.root)) {+ expect((mesh as unknown as InstancedMesh).isInstancedMesh).not.toBe(true);+ expect((mesh.geometry as InstancedBufferGeometry).isInstancedBufferGeometry).toBe(true);+ expect(mesh.frustumCulled).toBe(false);+ }+ expect(shared.stats().shared).toBe(true);+ const classic = (await buildCampusVegetation(data, models(), placements, { shared: false }))!;+ expect(meshes(classic.root).length).toBeGreaterThan(meshes(shared.root).length);+ expect(meshes(classic.root).every(m => (m as unknown as InstancedMesh).isInstancedMesh)).toBe(true);+ expect(classic.stats().shared).toBe(false);+ shared.dispose(); classic.dispose();+ });++ test('each vertex carries exactly the colour and roughness of the material its part had', async () => {+ const gltfs = models(), shared = (await buildCampusVegetation(data, gltfs, placements, { shared: true }))!;+ for (const [type, level, parts] of [['tree-broad-l', 0, [BARK, MID, LIGHT, DARK]], ['tree-broad-s', 1, [BARK, MID, DARK]], ['tree-ornamental', 2, [BARK, MID]], ['shrub-mound', 0, [MID]]] as const) {+ const mesh = meshes(shared.root).find(m => m.name === `${type}-lod${level}`)!, look = mesh.geometry.getAttribute('plantLook');+ expect(look.itemSize).toBe(4);+ const tuples = new Map<string, number>();+ for (let i = 0; i < look.count; i++) { const key = [0, 1, 2, 3].map(k => look.array[i * 4 + k]).join(','); tuples.set(key, (tuples.get(key) ?? 0) + 1); }+ const expected = parts.map(p => plantLook(new MeshStandardMaterial(p))!.join(','));+ expect([...tuples.keys()].sort()).toEqual([...expected].sort());+ // Each part is one box, 36 vertices once drawn without an index.+ for (const count of tuples.values()) expect(count).toBe(36);+ }+ shared.dispose();+ });++ test('the instances and counts equal the per-material path: same rows, same slots, same matrices, fewer draws', async () => {+ const shared = (await buildCampusVegetation(data, models(), placements, { shared: true }))!, classic = (await buildCampusVegetation(data, models(), placements, { shared: false }))!;+ for (const camera of [near(), far(), near()]) {+ shared.update(camera, 1); classic.update(camera, 1);+ const a = shared.stats(), b = classic.stats();+ expect({ ...a, draws: 0, shared: false }).toEqual({ ...b, draws: 0, shared: false });+ expect(a.visible).toBeGreaterThan(10);+ expect(a.draws).toBeLessThan(b.draws);+ let drawn = 0;+ for (const mesh of meshes(shared.root)) {+ const [type, level] = mesh.name.split('-lod') as [string, string], count = (mesh.geometry as InstancedBufferGeometry).instanceCount;+ expect(mesh.visible).toBe(count > 0);+ const twins = meshes(classic.root).filter(m => m.name.startsWith(`${type}-lod${level}-`)) as InstancedMesh[];+ for (const twin of twins) expect(twin.count).toBe(count);+ if (!count) continue;+ drawn++;+ const [c0, c1, c2, c3] = columnsOf(mesh), data = c0!.data.array as Float32Array;+ expect([c1!.data, c2!.data, c3!.data]).toEqual([c0!.data, c0!.data, c0!.data]);+ expect([c0!.offset, c1!.offset, c2!.offset, c3!.offset]).toEqual([0, 4, 8, 12]);+ expect(c0!.data.stride).toBe(16);+ expect(Array.from(data.subarray(0, count * 16))).toEqual(Array.from((twins[0]!.instanceMatrix.array as Float32Array).subarray(0, count * 16)));+ }+ expect(drawn).toBe(a.draws);+ }+ shared.dispose(); classic.dispose();+ });++ test('no shared plant casts a shadow: its instancing runs in the material setupPosition, which override-material passes skip', async () => {+ // A shadow, depth-prepass or picking pass draws with an override material that never runs setupPosition, so there every+ // plant would sit at its origin (wave-B review R7). Foundry Floor has no such pass; this fails if a shared plant joins one.+ const shared = (await buildCampusVegetation(data, models(), placements, { shared: true }))!;+ shared.update(near(), 1);+ expect(meshes(shared.root).filter(m => !(m as unknown as InstancedMesh).isInstancedMesh && m.castShadow).map(m => m.name)).toEqual([]);+ shared.dispose();+ });++ test('a still camera uploads nothing: the instance buffer is rewritten only when a slot or the count changes', async () => {+ const shared = (await buildCampusVegetation(data, models(), placements, { shared: true }))!, camera = near();+ shared.update(camera, 1);+ const versions = () => meshes(shared.root).map(m => columnsOf(m)[0]!.data.version);+ const first = versions();+ expect(first.some(v => v > 0)).toBe(true);+ shared.update(camera, 1); expect(versions()).toEqual(first);+ shared.update(far(), 1); expect(versions()).not.toEqual(first);+ shared.dispose();+ });++ test('only the slots in use are uploaded', async () => {+ const shared = (await buildCampusVegetation(data, models(), placements, { shared: true }))!;+ shared.update(near(), 1);+ for (const mesh of meshes(shared.root)) {+ const count = (mesh.geometry as InstancedBufferGeometry).instanceCount, data = columnsOf(mesh)[0]!.data;+ if (count) expect(data.updateRanges).toEqual([{ start: 0, count: count * 16 }]);+ }+ shared.dispose();+ });++ test('a level one vertex material cannot reproduce stays on the per-material path, beside the shared ones', async () => {+ const odd = (type: PlantType) => plant(type, undefined, type === 'tree-broad-m' ? m => { m.emissive.set(0x202020); } : undefined);+ const mixed = (await buildCampusVegetation(data, models(odd), placements, { shared: true }))!;+ const own = meshes(mixed.root).filter(m => (m as unknown as InstancedMesh).isInstancedMesh);+ expect(own.length).toBeGreaterThan(0);+ expect(own.every(m => m.name.startsWith('tree-broad-m-lod'))).toBe(true);+ expect(meshes(mixed.root).filter(m => !(m as unknown as InstancedMesh).isInstancedMesh).length).toBeGreaterThan(0);+ mixed.update(near(), 1);+ expect(mixed.stats().visible).toBeGreaterThan(10);+ mixed.dispose(); expect(mixed.root.children).toHaveLength(0);+ });++ test('dispose removes every mesh and frees the geometries and the material', async () => {+ const shared = (await buildCampusVegetation(data, models(), placements, { shared: true }))!, root = shared.root, kept = meshes(root).map(m => m.geometry);+ let disposed = 0; for (const g of kept) g.addEventListener('dispose', () => { disposed++; });+ const material = meshes(root)[0]!.material as { addEventListener(type: string, fn: () => void): void }; let materialDisposed = 0; material.addEventListener('dispose', () => { materialDisposed++; });+ shared.dispose();+ expect(root.children).toHaveLength(0); expect(disposed).toBe(kept.length); expect(materialDisposed).toBe(1);+ });+});++// With the saved plants (staged in the repository's pack, not in a fresh clone): every part of every level is carried.+const STAGED = resolve(PACKAGE, 'staged/revision2/models/vegetation'), saved = existsSync(STAGED);+describe.skipIf(!saved)('shared planting with the saved plants', () => {+ test('every part of the eight saved plants is carried, so every plant draws through one material', async () => {+ const real = new Map<string, GLTF>();+ for (const type of Object.keys(PLANT_SIZES)) { const bytes = readFileSync(resolve(STAGED, `${type}.glb`)); real.set(`plant-${type}`, await new GLTFLoader().parseAsync(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer, '')); }+ const shared = (await buildCampusVegetation(data, real, placements, { shared: true }))!;+ expect(meshes(shared.root)).toHaveLength(24);+ expect(new Set(meshes(shared.root).map(m => m.material)).size).toBe(1);+ shared.dispose();+ });+});diff --git a/scenes/packages/foundry-floor/tests/unit/campus-vegetation.test.ts b/scenes/packages/foundry-floor/tests/unit/campus-vegetation.test.tsindex 6cb812da..38b045bc 100644--- a/scenes/packages/foundry-floor/tests/unit/campus-vegetation.test.ts+++ b/scenes/packages/foundry-floor/tests/unit/campus-vegetation.test.ts@@ -7,21 +7,23 @@ import { buildCampusVegetation } from '../../src/campus/exterior/vegetation';import { campusPlantings } from '../../src/campus/exterior/planting';import { campusModels } from '../../scripts/campus-assets';-test('saved plants draw as shared instances with real near and far GLB levels', async () => {+// Both paths: the per-material one (plantingShared=false: every planting mesh an InstancedMesh) and the shared one (the+// default: one plain instanced mesh per type and level on one material). Same rows, so the same visible and triangle counts.+for(const shared of [false,true])test(`saved plants draw as shared instances with real near and far GLB levels (${shared?'shared material':'per material'})`, async () => {const data=parseCampus(readFileSync(new URL('../../data/campus.json',import.meta.url),'utf8'));const models=new Map();for(const model of campusModels().filter(m=>m.kind==='vegetation')){const bytes=readFileSync(model.from);models.set(model.id,await new GLTFLoader().parseAsync(bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.byteLength),'') );}- const planting=await buildCampusVegetation(data,models,campusPlantings(data)); expect(planting).not.toBeNull();+ const planting=await buildCampusVegetation(data,models,campusPlantings(data),{shared}); expect(planting).not.toBeNull();const camera=new PerspectiveCamera(50,1,.1,20000);camera.position.set(0,50,110);camera.lookAt(0,0,0);camera.updateMatrixWorld();planting!.update(camera,1); const near=planting!.stats();- expect(near.placed).toBeGreaterThan(500);expect(near.visible).toBeGreaterThan(10);expect(near.draws).toBeLessThanOrEqual(81);+ expect(near.placed).toBeGreaterThan(500);expect(near.visible).toBeGreaterThan(10);expect(near.draws).toBeLessThanOrEqual(shared?24:81);expect(near.perLevel[0]).toBeGreaterThan(0);camera.position.set(0,2200,2800);camera.lookAt(0,0,0);camera.updateMatrixWorld();planting!.update(camera,1);const far=planting!.stats();expect(far.perLevel[0]).toBe(0);expect(far.perLevel[2]).toBeGreaterThan(100);expect(far.triangles).toBeLessThan(near.triangles+far.visible*80);- expect(planting!.root.children.every(mesh=>(mesh as any).isInstancedMesh)).toBe(true);+ expect(planting!.root.children.every(mesh=>!!(mesh as any).isInstancedMesh===!shared)).toBe(true);planting!.dispose(); expect(planting!.root.children.length).toBe(0);});diff --git a/scenes/packages/foundry-floor/tests/unit/msaa-tiers.test.ts b/scenes/packages/foundry-floor/tests/unit/msaa-tiers.test.tsnew file mode 100644index 00000000..95ae6465--- /dev/null+++ b/scenes/packages/foundry-floor/tests/unit/msaa-tiers.test.ts@@ -0,0 +1,13 @@+// SPDX-License-Identifier: MIT+import { expect, test } from 'bun:test';+import { resolveTier } from '@kiln-scenes/scene-kit';+import type { DeviceClass } from '@kiln-scenes/scene-kit';+import { foundryFloorDefinition } from '../../src/definition';++test('OD-10: every tier discards the canvas pass 4x attachments (no viewport-texture node or transmission splits the pass)', () => {+ const tiers = foundryFloorDefinition.tiers;+ for (const form of ['desktop', 'phone'] as const) {+ const device: DeviceClass = { form, backend: 'webgpu', gpu: 'high', devicePixelRatio: 1 };+ for (const name of tiers.order) expect(resolveTier(tiers, name, device).multisample).toEqual({ discard: true });+ }+});diff --git a/scenes/packages/foundry-floor/tests/unit/probe-systems.test.ts b/scenes/packages/foundry-floor/tests/unit/probe-systems.test.tsnew file mode 100644index 00000000..83201ee3--- /dev/null+++ b/scenes/packages/foundry-floor/tests/unit/probe-systems.test.ts@@ -0,0 +1,34 @@+// SPDX-License-Identifier: MIT+import { expect, test } from 'bun:test';+import { Object3D } from 'three';+import { foundryProbeAsset, foundryProbeSystems } from '../../src/campus/probe-systems';++const named = (name: string, parent?: Object3D) => { const o = new Object3D(); o.name = name; parent?.add(o); return o; };+const names = (systems: Record<string, Object3D[]>) => Object.fromEntries(Object.entries(systems).map(([k, v]) => [k, v.map(o => o.name)]));++test('exterior probe systems are the campus groups found by name, without the campus- prefix', () => {+ const scene = named('scene'), exterior = named('campus-exterior', scene);+ for (const name of ['campus-ground', 'campus-structures', 'campus-planting', 'campus-traffic']) named(name, exterior);+ named('campus-unlisted', exterior);+ expect(names(foundryProbeSystems(scene))).toEqual({ ground: ['campus-ground'], structures: ['campus-structures'], planting: ['campus-planting'], traffic: ['campus-traffic'] });+});++test('fab groups are grouped by entity role; unmapped groups keep their own name, with foundry-floor- shortened to fab-', () => {+ const scene = named('scene'), world = named('foundry-floor-world', scene);+ for (const name of ['wallKit:a:b', 'floorModule:1:2', 'tool:euv-scanner:3', 'loadPort:7:0', 'vehicle:sedan:1', 'foup:12:0', 'railStraight:4:1', 'foundry-floor-pulses', 'proxies:2:0', '']) named(name, world);+ named('campus-interior-context', scene);+ expect(names(foundryProbeSystems(scene))).toEqual({+ 'interior-context': ['campus-interior-context'],+ 'fab-building': ['wallKit:a:b', 'floorModule:1:2'], 'fab-tools': ['tool:euv-scanner:3', 'loadPort:7:0'], 'fab-movers': ['vehicle:sedan:1', 'foup:12:0'],+ 'fab-transport': ['railStraight:4:1'], 'fab-pulses': ['foundry-floor-pulses'], 'proxies:2:0': ['proxies:2:0'], 'fab-unnamed': [''],+ });+});++test('fab assets are named by entity (tools by type) only for three-part names directly under the fab world', () => {+ const scene = named('scene'), world = named('foundry-floor-world', scene), elsewhere = named('campus-structures', scene);+ expect(foundryProbeAsset(named('tool:euv-scanner:3', world))).toBe('tool:euv-scanner');+ expect(foundryProbeAsset(named('wallKit:a:b', world))).toBe('wallKit');+ expect(foundryProbeAsset(named('tool:euv-scanner', world))).toBeNull();+ expect(foundryProbeAsset(named('tool:euv-scanner:3', elsewhere))).toBeNull();+ expect(foundryProbeAsset(named('wallKit:a:b'))).toBeNull();+});diff --git a/scenes/packages/golden-gate/PERFORMANCE.md b/scenes/packages/golden-gate/PERFORMANCE.mdindex bf243abf..15d53cc5 100644--- a/scenes/packages/golden-gate/PERFORMANCE.md+++ b/scenes/packages/golden-gate/PERFORMANCE.md@@ -16,7 +16,7 @@ State on 2026-09-29, 16:56:| Id | Check | Where | Method for Golden Gate | Pass rule | State ||---|---|---|---|---|---|| X-01 | CPU frame time versus the pilot | none | none | not applicable: Golden Gate has no pilot | n/a |-| X-02 | Draw calls, triangles, geometries, textures, pipelines | dev PC, counts only | `renderer.info` at 15 views: the ten named views, four hero-orbit points and the drive chase fixture. Frozen clock (Day, time 12), tiers high, balanced and economy, WebGPU and WebGL2. A count is kept once two samples 20 frames apart agree. | no pilot: recorded as the baseline; draw calls and triangles must match across backends | done; `evidence/perf/x02-counts.json`; g3: `evidence/build/g3/` |+| X-02 | Draw calls, triangles, geometries, textures, pipelines | dev PC, counts only | `renderer.info` at 15 views: the ten named views, four hero-orbit points and the drive chase fixture. Frozen clock (Day, time 12), tiers high, balanced and economy, WebGPU and WebGL2. A count is kept once two samples 20 frames apart agree. | no pilot: recorded as the baseline; draw calls and triangles must match across backends | done; `evidence/perf/x02-counts.json`; g3: `evidence/build/g3/`; re-baselined 2026-10-02 on the draw-optimized build (OD-8, D-53; section "X-02 re-baseline" below) || X-03 | Leaks | dev PC, counts only | The kit's B-05 protocol (R2-13/C-04) for this scene: a cold teardown, two 120-frame cycles, ten initialization cycles, then ten measured mount and unmount cycles alternating automatic (WebGPU) and forced WebGL2 | heap after a forced collection within 5 percent; every receipt disposed with 0 resources and a lost device or context; no listener, canvas or HUD left | **pass**; `x03-leaks.json`; g3 pass, `evidence/build/g3/` || X-04 | Time to `onReady` | hub | cold (a new profile per run) and warm, both backends, 5 runs each | WebGL2 worst run at most 45 s; medians recorded | **pass** 2026-09-29 (hub session 1, g1 kit): WebGL2 worst run 3585 ms against 45 s; median (worst of 5) WebGPU cold 3929 (4056) ms, warm 3823 (3865); WebGL2 cold 3542 (3585), warm 3335 (3575); `evidence/perf/hub-2026-09-29/` || X-05 | Desktop tier qualification | hub | tiers high, balanced and economy, both backends, workloads orbit, flyover and drive, 60 s each, 5 runs, governor held at the tier's level 0 | recorded per tier, including which tiers reach 60 FPS (no pilot) | **recorded 2026-09-29** (hub session 2, g2 kit): all three tiers reach 60 FPS on both backends and all three workloads (18 of 18 groups, 90 of 90 runs valid and quiet); median interval 8.3 ms and 119.8 to 119.9 FPS at the panel's 120.11 Hz refresh, so no headroom is visible; table under "Hub session 2"; `evidence/perf/hub-2026-09-29-session-2/` |@@ -153,6 +153,51 @@ Fix round 2 staged g3 (bridge review 3, the approach roads) and reran `tests/too- D-15 still holds and was not re-frozen.- The g3 hub kit's README and MANIFEST copies are in the same directory.+### X-02 re-baseline on the draw-optimized build (OD-8, D-53; 2026-10-02)++The draw-optimization cycle (`docs/plans/2026-10-01-draw-optimization-cycle.md`) lowers draw calls on purpose: the bridge is merged by material at every tier, and at High the sun shadow renders once per frame from depth stand-ins and the planar reflection draws far-approach stand-ins. Golden Gate has no pilot, so its own X-02 run is the baseline, and OD-8 re-baselines it on the optimized build. Pixel parity is checked separately (S5 parity, two builds).++- **New baseline.** `tests/tools/perf-local.ts x02 --build=draw-after` on the draw-after test build (HEAD `892d103`; chunks `index-D-gELBet.js`, `route-contact-CxuZU847.js`; staged g9, `pack.json` sha256 `c2a1d83f…`), headless Chrome 1920 x 1080, frozen clock (Day, time 12), captured 2026-10-02 08:42:56 UTC. File: `scenes/evidence/draw-after/golden-gate/x02/draw-after/x02-counts.json` (ignored; it names the build).+- **Old baseline, measured the same way** on draw-base (main `c734e2a` plus the count-probe overlay; chunks `index-CdjtRS9C.js`, `route-contact-Ck7E03By.js`; the same pack) at 08:39:05 UTC: `…/x02/draw-base/x02-counts.json`.+- **Views.** 16: the eleven named views (`arrival` joined layout.json's cameras after the g3 run, which had ten), four hero-orbit points and the drive chase.++| Tier (feature set) | Backend | Draw calls | Triangles | Pipelines | Programs | Geometries |+|---|---|---|---|---|---|---|+| high (High) | WebGPU | 176 to 486 → 45 to 116 | 1,068,907 to 1,709,297 → 954,385 to 1,547,917 | 69 to 70 → 31 to 32 | 40 to 42 → 38 to 40 | 129 to 140 → 81 to 93 |+| high (High) | WebGL2 | 176 to 486 → 45 to 116 | 1,068,907 to 1,709,297 → 954,385 to 1,547,917 | 20 to 21 → 19 to 20 | 39 to 41 → 37 to 39 | 129 to 140 → 82 to 93 |+| balanced (Medium) | WebGPU | 52 to 182 → 23 to 54 | 391,612 to 631,479 (same range) | 29 to 31 → 17 to 19 | 30 to 32 | 126 to 137 → 68 to 80 |+| balanced (Medium) | WebGL2 | 52 to 182 → 23 to 54 | 391,612 to 631,479 (same range) | 15 to 16 | 30 to 32 | 126 to 137 → 68 to 79 |+| economy (Low) | WebGPU | 52 to 180 → 23 to 52 | 232,289 to 344,564 (same range) | 29 to 31 → 17 to 19 | 30 to 32 | 127 to 136 → 69 to 78 |+| economy (Low) | WebGL2 | 52 to 180 → 23 to 52 | 232,289 to 344,564 (same range) | 15 to 16 | 30 to 32 | 127 to 136 → 69 to 78 |++High, WebGPU, per view (old → new baseline; the check run's values last):++| View | Draw calls | Triangles | Check run |+|---|---|---|---|+| arrival | 432 → 103 | 1,540,569 → 1,426,047 | 103, 1,426,047 |+| postcard | 407 → 101 | 1,442,209 → 1,329,477 | 101, 1,329,477 |+| pier | 270 → 75 | 1,234,833 → 1,104,205 | 75, 1,104,205 |+| topdown | 212 → 64 | 1,349,785 → 1,235,407 | 64, 1,235,407 |+| horizon | 176 → 45 | 1,068,907 → 954,385 | 45, 954,385 |+| deck | 354 → 116 | 1,666,885 → 1,516,537 | 116, 1,516,537 |+| tower | 379 → 94 | 1,142,113 → 1,009,189 | 94, 1,009,189 |+| span | 436 → 107 | 1,531,157 → 1,416,635 | 107, 1,416,635 |+| lanes | 350 → 113 | 1,708,781 → 1,546,855 | 113, 1,546,855 |+| sidewalk | 354 → 116 | 1,709,297 → 1,547,917 | 116, 1,547,917 |+| traffic | 318 → 106 | 1,647,561 → 1,503,153 | 106, 1,503,153 |+| hero-orbit-0deg | 444 → 94 | 1,427,621 → 1,305,259 | 94, 1,305,259 |+| hero-orbit-90deg | 398 → 93 | 1,417,181 → 1,302,707 | 93, 1,302,707 |+| hero-orbit-180deg | 486 → 101 | 1,555,953 → 1,434,847 | 101, 1,434,847 |+| hero-orbit-270deg | 396 → 91 | 1,408,069 → 1,293,595 | 91, 1,293,595 |+| drive-chase | 350 → 113 | 1,683,369 → 1,523,583 | 113, 1,520,825 |++- **The old baseline fails against the new counts.** `--baseline=…/x02/draw-base/x02-counts.json` on draw-after: 0 of 32 High views within 2 percent (0 of 96 over all tiers), exit 1 (`…/x02/draw-after/x02-check.json`).+- **The new baseline passes.** A second draw-after run with `--baseline=…/x02/draw-after/x02-counts.json`: 32 of 32 High views within 2 percent (96 of 96), exit 0 (`…/x02/draw-after-check/x02-check.json`).+- **Triangles.** High falls 7.4 to 11.6 percent per view: one sun-shadow pass instead of two, and the far-approach stand-ins in the reflection. Medium and Low move by −0.06 to +1.51 percent (the pier view most): the merged meshes span whole bridge groups, so frustum culling is coarser.+- **Backends.** Draw calls and triangles match on both backends at every view except the drive chase, before and after.+- **The drive chase is workload state.** It runs 90 frames of real time before the clock freezes, so the car stops between z −274 and −293 m in these runs, and the traffic around it varies. That moves its triangles by up to 1.4 percent and its draws by 1 between runs and backends, which is within the 2 percent rule.+- **`ggStats.bridge.webMeshes` keeps its meaning.** It counts the meshes in the authored web model before any merge: 148 in both builds. It no longer equals what the bridge draws. X-02 records now carry both `webMeshes` and `bridgeDraws`, the meshes the merged views draw: web 20, far 18.+## Tablet (X-07): pass**Device and setup.**@@ -314,12 +359,12 @@ Reproduce the local parts from the scenes root:```./scripts/toolchain-run.ps1 packages/golden-gate/tests/tools/build.ts public test-./scripts/toolchain-run.ps1 packages/golden-gate/tests/tools/perf-local.ts [x02] [x03] [x11] [x12] [--out=<dir>]+./scripts/toolchain-run.ps1 packages/golden-gate/tests/tools/perf-local.ts [x02] [x03] [x11] [x12] [--out=<dir>] [--build=<label>] [--baseline=<x02-counts.json>]./scripts/toolchain-run.ps1 packages/golden-gate/tests/tools/make-hub-kit.ts [--copies=<dir>]./scripts/toolchain-run.ps1 packages/golden-gate/tests/tools/tablet-check.ts [--seconds 60]```-`--out=<dir>` and `--copies=<dir>` default to `evidence/perf`. Each is one token: `toolchain-run.ps1` is an advanced PowerShell script, so a separate `--out` is read as its ambiguous `-OutVariable`/`-OutBuffer`.+`--out=<dir>` and `--copies=<dir>` default to `evidence/perf`. `--build=<label>` measures a labelled build from `scripts/build-scene.ts` (`dist/<label>/test`), and `--baseline=<file>` checks X-02 against an earlier `x02-counts.json` (2 percent per view; the verdict is High's). Each is one token: `toolchain-run.ps1` is an advanced PowerShell script, so a separate `--out` is read as its ambiguous `-OutVariable`/`-OutBuffer`.## Deferred, with reasonsdiff --git a/scenes/packages/golden-gate/src/World.tsx b/scenes/packages/golden-gate/src/World.tsxindex d9bcab3e..4d01956d 100644--- a/scenes/packages/golden-gate/src/World.tsx+++ b/scenes/packages/golden-gate/src/World.tsx@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';import { useThree } from '@react-three/fiber';import { Raycaster, Vector3 } from 'three/webgpu';import type { PerspectiveCamera, WebGPURenderer } from 'three/webgpu';-import { SystemOrder, useLoadedPack, usePackReader, usePresets, useQuality, useReducedMotion, useRegisterTestHooks, useSceneBuilt, useSceneClock, useSystem } from '@kiln-scenes/scene-kit';+import { readDevParams, SystemOrder, useLoadedPack, usePackReader, usePresets, useQuality, useReducedMotion, useRegisterTestHooks, useSceneBuilt, useSceneClock, useSystem } from '@kiln-scenes/scene-kit';import type { Vec3 } from '@kiln-scenes/scene-kit';import { buildGoldenGateWorld } from './world/build-world';import type { GoldenGateWorld } from './world/build-world';@@ -18,14 +18,21 @@ import { sightlineClearance, surfaceHeight } from './world/heightfield';import { GoldenGateCameras } from './camera/GoldenGateCameras';import { Driving } from './play/Driving';import { LAYOUT } from './data';+import type { DrawOptions } from './world/draw-options';const TEST = !!(import.meta.env.KILN_TEST || import.meta.env.KILN_DEV);+/** Test and dev builds: draw optimisation switches for A/B counts and parity captures (./world/draw-options; each defaults on where its pass exists, shadowCache off). */+function drawOverrides(): Partial<DrawOptions> {+ if (!TEST) return {};+ const B = { kind: 'boolean' } as const, p = readDevParams({ bridgeMerge: B, shadowOnce: B, standIns: B, reflectionStandIns: B, shadowCache: B });+ return { merge: p.bridgeMerge, once: p.shadowOnce, depth: p.standIns, reflection: p.reflectionStandIns, cache: p.shadowCache };+}export function GoldenGateWorldContent() {const pack = useLoadedPack(), reader = usePackReader(), quality = useQuality<GoldenGateKnobs>(), markBuilt = useSceneBuilt(), session = useGoldenGateSession(), reduced = useReducedMotion(), clock = useSceneClock();const gl = useThree(state => state.gl) as unknown as WebGPURenderer, scene = useThree(state => state.scene), camera = useThree(state => state.camera) as PerspectiveCamera;const size = useThree(state => state.size);- const params = useMemo(() => readGoldenGateParams(), []);+ const params = useMemo(() => readGoldenGateParams(), []), draw = useMemo(drawOverrides, []);// The kit applies the development-only `preset` URL parameter (WATER-SPEC determinism) on mount.const presets = usePresets<GoldenGatePreset>(PRESETS, 'day');const [world, setWorld] = useState<GoldenGateWorld | null>(null), [failure, setFailure] = useState<unknown>(null);@@ -44,7 +51,7 @@ export function GoldenGateWorldContent() {useEffect(() => {const abort = new AbortController(); let built: GoldenGateWorld | null = null;- buildGoldenGateWorld({ pack, reader, renderer: gl, scene, camera, knobs: quality.knobs, signal: abort.signal,+ buildGoldenGateWorld({ pack, reader, renderer: gl, scene, camera, knobs: quality.knobs, signal: abort.signal, draw,traffic: { enabled: params.traffic !== false, density: typeof params.density === 'string' ? params.density as TrafficDensity : undefined },onProgress: (loaded, total, text) => session.progress?.({ phase: 'build', loaded, total, text }) }).then(value => {@@ -101,6 +108,11 @@ export function GoldenGateWorldContent() {const target = { terrain: world.terrain.root, bridge: world.bridge.root, water: world.water.mesh, banks: world.banks?.sprite, sky: world.atmosphere.sky, traffic: world.traffic.root }[part];if (!target) return false; target.visible = visible; return true;},+ /** Count-probe systems (scene-kit testing/probe.ts): the setPartVisible parts, with the bridge split into its web and+ * far models, the approaches and the vegetation carried under the near approaches. */+ probeSystems: () => ({ terrain: world.terrain.root, vegetation: world.terrain.vegetation.root, bridge: world.bridge.views.web, 'bridge-far': world.bridge.views.far,+ approaches: [world.bridge.approachMeshes.near.group, world.bridge.approachMeshes.far.group], water: world.water.mesh, banks: world.banks?.sprite ?? null,+ sky: world.atmosphere.sky, traffic: world.traffic.root }),/** The point on the water plane (y = 0) under a screen pixel, or null above the horizon. */groundPoint: (sx: number, sy: number) => { camera.updateMatrixWorld(); v.set(sx / size.width * 2 - 1, 1 - sy / size.height * 2, .5).unproject(camera).sub(camera.position); if (v.y >= 0) return null; const t = -camera.position.y / v.y; return [camera.position.x + v.x * t, camera.position.z + v.z * t]; },project: (point: Vec3) => { camera.updateMatrixWorld(); v.fromArray(point).project(camera); return [(v.x + 1) / 2 * size.width, (1 - v.y) / 2 * size.height, v.z]; },diff --git a/scenes/packages/golden-gate/src/constants.ts b/scenes/packages/golden-gate/src/constants.tsindex 37f466f8..353782ba 100644--- a/scenes/packages/golden-gate/src/constants.ts+++ b/scenes/packages/golden-gate/src/constants.ts@@ -40,5 +40,9 @@ export const INTERNATIONAL_ORANGE = [1, 3, 5].map(i => parseInt(LAYOUT.reference/** Credits shown in the scene (full text lives in the staged licences and credits.json). */export const TRADEMARK_NOTE = 'The Golden Gate Bridge name and likeness are trademarks of the Golden Gate Bridge, Highway and Transportation District. The CC0 dedication covers copyright in this model only and grants no trademark rights.';-/** Render layers: 0 reflected world, 1 water, 2 dynamic objects kept out of reflections (traffic, player car, fog banks). */-export const LAYERS = { world: 0, water: 1, dynamic: 2 } as const;+/**+ * Render layers: 0 reflected world, 1 water, 2 dynamic objects kept out of reflections (traffic, player car, fog banks).+ * Draw optimisation (High): 3 shadow depth stand-ins (the sun's shadow camera only), 4 drawn by the main and shadow cameras+ * but not the reflection (the near approaches), 5 drawn only in the reflection (the far approaches standing in for them).+ */+export const LAYERS = { world: 0, water: 1, dynamic: 2, shadowStandIn: 3, mainOnly: 4, reflectionOnly: 5 } as const;diff --git a/scenes/packages/golden-gate/src/tiers.ts b/scenes/packages/golden-gate/src/tiers.tsindex c6aec0e0..59e9e5c7 100644--- a/scenes/packages/golden-gate/src/tiers.ts+++ b/scenes/packages/golden-gate/src/tiers.ts@@ -21,6 +21,9 @@ function knobs(features: GoldenGateFeatures, pixelRatioCap: number, pixelRatioMivegetationDensity: 0, instanceDensity: 1,drawDistance: { far: LAYOUT.cameras.clip.far, fogNear: 0, fogFar: LAYOUT.cameras.clip.far, lodBias: 1, streamRadiusScale: 1, zoneHops: 0 },effects: { water: features.feature === 'low' ? 'simple' : 'full', wind: false, ambientAnimation: true },+ // OD-10: water depth contact and fog banks read viewportDepthTexture, a mid-pass copy of the 4x depth, so only a+ // feature set with neither may discard. Derived from the features, so high on a phone (Medium) keeps store.+ multisample: { discard: !features.water.depthContact && features.fogBanks === 0 },gg: features,};}diff --git a/scenes/packages/golden-gate/src/world/atmosphere.ts b/scenes/packages/golden-gate/src/world/atmosphere.tsindex 5fec6c91..576e5a20 100644--- a/scenes/packages/golden-gate/src/world/atmosphere.ts+++ b/scenes/packages/golden-gate/src/world/atmosphere.ts@@ -15,6 +15,9 @@ import { createAtmosphereUniforms, skyWithFog, type AtmosphereUniforms } from '.import { normalizedSun, type GoldenGatePreset } from '../presets';import { LAYERS } from '../constants';+/** The cached sun shadow's fit tracking is a development option (build-world.ts): public builds leave it out. */+const TEST = !!(import.meta.env.KILN_TEST || import.meta.env.KILN_DEV);+export interface AtmosphereOptions { envSize: number; shadows: boolean; shadowMapSize: number; shadowExtent: readonly [number, number] }export interface Atmosphere {readonly uniforms: AtmosphereUniforms;@@ -30,6 +33,11 @@ export interface Atmosphere {update(camera: Camera, focus: Vector3, nowSeconds: number): void;/** Cameras for which the sky must hide its sun disc (planar reflection). */hideSunFor(camera: Camera | null): void;+ /**+ * The shadow cascade's fit (snapped centre in light space, extent and sun direction): a cached shadow re-renders when it+ * changes. Test and dev builds only, where the cached shadow exists; '' in public builds.+ */+ readonly shadowFit: string;readonly stats: { environmentRenders: number };dispose(): void;}@@ -72,6 +80,7 @@ export function createAtmosphere(renderer: WebGPURenderer, scene: Scene, o: Atmoconst pmrem = new PMREMGenerator(renderer);let envTarget: RenderTarget = pmrem.fromScene(envScene, 0, .1, 1000, { size: o.envSize });const stats = { environmentRenders: 1 };+ let fitR = 0, fitV = 0, fitExtent = 0;const sun = new DirectionalLight(0xffffff, 3);sun.name = 'sun';@@ -93,6 +102,7 @@ export function createAtmosphere(renderer: WebGPURenderer, scene: Scene, o: Atmoconst atmosphere: Atmosphere = {uniforms: u, sky, sun,+ get shadowFit() { return TEST ? `${fitR}|${fitV}|${fitExtent}|${sunDir.x}|${sunDir.y}|${sunDir.z}` : ''; },get environment() { return envTarget.texture; },stats,apply(p, now, force = false) {@@ -137,6 +147,8 @@ export function createAtmosphere(renderer: WebGPURenderer, scene: Scene, o: Atmosun.position.copy(snapped).addScaledVector(sunDir, 4000); sun.target.position.copy(snapped);const cam = sun.shadow.camera;if (cam.right !== extent) { cam.left = -extent; cam.right = extent; cam.top = extent; cam.bottom = -extent; cam.updateProjectionMatrix(); }+ // The depth along the sun is left out: an orthographic map shifted along its own axis covers the same casters.+ if (TEST) { fitR = r; fitV = v; fitExtent = extent; }},hideSunFor(camera) { hiddenFor = camera; },dispose() {diff --git a/scenes/packages/golden-gate/src/world/bridge.ts b/scenes/packages/golden-gate/src/world/bridge.tsindex 650fe232..a3bb73aa 100644--- a/scenes/packages/golden-gate/src/world/bridge.ts+++ b/scenes/packages/golden-gate/src/world/bridge.ts@@ -3,11 +3,20 @@// the roadway height grid used by traffic and the player car, and the chase-camera colliders. The// approach roads (./approach-mesh, fix round 2) are built here on the bridge's own materials, near and// far representations switching by the camera's distance to the route (deck axis and approach centrelines).+// Draw optimisation (OD-18; tmp/drawcalls/understand/golden-gate.md sections 2-3): the scene draws a render copy of each+// model that shares the pack's geometry and materials, its parts regrouped under south, north and span groups and merged+// by material inside each group. The pack's scene graphs are never changed, so a second build from the same pack (React+// StrictMode, tests) starts from the authored graph; a tier change remounts and reloads the pack. Their shared materials do+// carry the joint-plate polygon offset and the current lamp level. A detached copy of the web model keeps the authored graph+// for the Roadway raster, the colliders and route contact. Two draw orders keep depth ties the merge would flip: the curbs+// before the walks (DRAWN_FIRST) and the span's paint after the roadway (drawnLast). On High, shadow depth stand-ins replace+// the web model's and the near approaches' casters, and in the planar reflection a copy of the far approaches stands in for+// the near ones.import { Color, Group, MeshStandardMaterial } from 'three/webgpu';import type { Material, Mesh, Object3D, Vector3 } from 'three/webgpu';import type { GLTF } from 'three/addons/loaders/GLTFLoader.js';-import { createCollisionWorld } from '@kiln-scenes/scene-kit';-import type { CollisionWorld } from '@kiln-scenes/scene-kit';+import { createCollisionWorld, mainOnly, mergeRigidByMaterial, passStandIn, shadowStandIns } from '@kiln-scenes/scene-kit';+import type { CollisionWorld, PassLayers, RigidMerge, ShadowStandIns } from '@kiln-scenes/scene-kit';import { BRIDGE, LAYERS } from '../constants';import { LAYOUT } from '../data';import type { Vec3 } from '../data';@@ -24,10 +33,37 @@ export type { RoadGrid } from './road';/** layout.json lights.bridgeLamps and bridge.obstructionNodes (D-21). */const LAMP_MATERIALS = new Set(LAYOUT.lights.bridgeLamps.materials);const OBSTRUCTION = new RegExp(`^(${LAYOUT.bridge.obstructionNodes.join('|')})`);+/** The lamp materials' authored emissive intensity: the pack's materials are shared by every build, and setLamps scales them. */+const AUTHORED = /*@__PURE__*/ new WeakMap<MeshStandardMaterial, number>();+/** Top-level parts of GoldenGateBridge by group (staged/g9/bridge): the south tower, fender and anchorage, the north tower and anchorage, and the span parts (cables, deck, suspenders, bracing and trusses) that run deck end to deck end. */+const SIDES = [/^South/, /^North/] as const, GROUPS = ['south', 'north', 'span'] as const;+/** Shadow stand-in anchors below the groups, so each tower and anchorage casts through its own proxy and keeps shadow-frustum culling. */+const PROXY_ANCHOR = /^(South|North)(Tower|Anchorage)$/;+/**+ * Parts first in their merged mesh. The curbs share Concrete with the walks and their road-facing faces are coplanar; unmerged,+ * three drew the curbs first and the walks won the depth ties. In one draw later triangles win, so the curbs' come first.+ */+const DRAWN_FIRST = /^Curbs(East|West)$/;+/**+ * The span's merged paint draws after the other opaque draws. Far out the depth buffer cannot separate the deck's stacked+ * surfaces (the underdeck's top is 0.45 m below the roadway); unmerged and seen from above, three drew the lower painted parts+ * after the roadway by their centre depth, so the paint won those ties. Merged, the span's paint centre rises to the cables+ * and it would draw first.+ */+const drawnLast = (m: Mesh) => m.parent?.name === 'span' && (m.material as Material).name === 'Paint';-export interface BridgeOptions { farSwitch: number; castShadow: boolean }+export interface BridgeOptions {+ farSwitch: number; castShadow: boolean;+ /** Merge each model's parts by material inside its south, north and span groups (the `bridgeMerge` development parameter). */+ merge?: boolean;+ /** Shadow depth stand-ins on this layer for the web model and the near approaches; the sun's shadow camera must enable it. */+ standInLayer?: number;+ /** Planar reflection: the near approaches move to `main`, which main and shadow cameras enable, and a copy of the far approaches on `pass` stands in for them in the reflection. */+ passLayers?: PassLayers;+}export interface Bridge {- root: Group; web: Object3D; far: Object3D; road: RoadGrid; colliders: CollisionWorld;+ /** Web model as authored, detached and never drawn: named nodes and world matrices for the Roadway, the colliders and route contact. */+ root: Group; web: Object3D; views: { web: Object3D; far: Object3D }; road: RoadGrid; colliders: CollisionWorld;/** The approach roads (data/layout.json approaches) and their near and far meshes. */approaches: Approach[]; approachMeshes: { near: ApproachMeshes; far: ApproachMeshes };/** The drivable route: the Roadway's road grid joined to both approach roads (traffic and the player's car). */@@ -37,7 +73,12 @@ export interface Bridge {/** Distance LOD with 12 % hysteresis around the tier's switch distance. */update(camera: Vector3): void;setLamps(level: number): void;- stats: { webMeshes: number; farMeshes: number; jointMaterials: number; colliders: number; roadCells: number; approachTriangles: { near: number; far: number }; approachDraws: { near: number; far: number } };+ stats: {+ webMeshes: number; farMeshes: number; jointMaterials: number; colliders: number; roadCells: number; approachTriangles: { near: number; far: number }; approachDraws: { near: number; far: number };+ /** Meshes each view draws on the world layer; the merge and the stand-ins as built (null when off). */+ draws: { web: number; far: number }; merged: { web: RigidMerge['stats']; far: RigidMerge['stats'] } | null;+ shadowProxies: { proxies: number; sourceMeshes: number; triangles: number } | null; reflectionProxies: number;+ };dispose(): void;}@@ -58,7 +99,7 @@ export function offsetJointPlates(scene: Object3D): number {return done.size;}-function prepare(scene: Object3D, castShadow: boolean, lamps: Set<MeshStandardMaterial>, emissive: Map<MeshStandardMaterial, number>): number {+function prepare(scene: Object3D, castShadow: boolean, lamps: Set<MeshStandardMaterial>): number {let meshes = 0;scene.traverse(node => {node.layers.set(LAYERS.world);@@ -66,11 +107,25 @@ function prepare(scene: Object3D, castShadow: boolean, lamps: Set<MeshStandardMameshes++; mesh.castShadow = castShadow; mesh.receiveShadow = castShadow;for (const material of (Array.isArray(mesh.material) ? mesh.material : [mesh.material]) as Material[]) {const standard = material as MeshStandardMaterial;- if (LAMP_MATERIALS.has(material.name) && standard.emissive) { lamps.add(standard); if (!emissive.has(standard)) emissive.set(standard, standard.emissiveIntensity); }+ if (LAMP_MATERIALS.has(material.name) && standard.emissive) { lamps.add(standard); if (!AUTHORED.has(standard)) AUTHORED.set(standard, standard.emissiveIntensity); }}});return meshes;}+/** A render copy of a model (shared geometry and materials) with GoldenGateBridge's parts regrouped under identity south, north and span groups. */+function view(model: Object3D, which: string): { root: Object3D; groups: Set<Object3D> } {+ const root = model.clone(), bridge = root.getObjectByName('GoldenGateBridge');+ if (!bridge) throw new Error(`Bridge ${which} runtime has no GoldenGateBridge node`);+ const groups = GROUPS.map(name => Object.assign(new Group(), { name }));+ for (const part of [...bridge.children]) { const side = SIDES.findIndex(s => s.test(part.name)); groups[side < 0 ? 2 : side]!.add(part); }+ bridge.add(...groups); root.name = `bridge-${which}`;+ return { root, groups: new Set(groups) };+}+/** Meshes drawn on the world layer below root, ignoring root's own visibility. */+function draws(root: Object3D): number {+ let n = 0; const visit = (o: Object3D) => { if (o !== root && !o.visible) return; if ((o as Mesh).isMesh && o.layers.isEnabled(LAYERS.world)) n++; o.children.forEach(visit); };+ visit(root); return n;+}/** The bridge runtime's Asphalt, RoadMarkings, Concrete and LampGlass materials, by name, and the scene's painted steel (layout.json dressing.paint). */function approachMaterials(scene: Object3D, which: string, paint: Material): ApproachMaterials {@@ -92,42 +147,64 @@ function polylineDistance(p: Vector3, line: readonly Vec3[]): number {export function createBridge(web: GLTF, far: GLTF, o: BridgeOptions): Bridge {const root = new Group(); root.name = 'bridge';- const lamps = new Set<MeshStandardMaterial>(), emissive = new Map<MeshStandardMaterial, number>();- const webMeshes = prepare(web.scene, o.castShadow, lamps, emissive), farMeshes = prepare(far.scene, false, lamps, emissive);- const jointMaterials = offsetJointPlates(web.scene) + offsetJointPlates(far.scene);- root.add(web.scene, far.scene); far.scene.visible = false;+ const lamps = new Set<MeshStandardMaterial>(), source = web.scene.clone(), views = { web: view(web.scene, 'web'), far: view(far.scene, 'far') };+ source.updateMatrixWorld(true);+ const webMeshes = prepare(views.web.root, o.castShadow, lamps), farMeshes = prepare(views.far.root, false, lamps);+ const jointMaterials = offsetJointPlates(views.web.root) + offsetJointPlates(views.far.root);+ root.add(views.web.root, views.far.root); views.far.root.visible = false;root.updateMatrixWorld(true);- const roadway = web.scene.getObjectByName('Roadway');+ const roadway = source.getObjectByName('Roadway');if (!roadway) throw new Error('Bridge runtime has no Roadway node');const road = rasterizeRoad(roadway), route = createRoute(road, LAYOUT.approaches, BRIDGE.roadEndZ);const cs = LAYOUT.approaches.crossSection, approaches = [route.south, route.north], dressing = LAYOUT.dressing;const paint = new MeshStandardMaterial({ name: 'PaintedSteel', color: new Color(dressing.paint.color), roughness: dressing.paint.roughness, metalness: 0 });const meshes = {- near: approachMeshes(approaches, cs, BRIDGE.roadEndZ, BRIDGE.medianHalfWidth, 'near', approachMaterials(web.scene, 'web', paint), { castShadow: o.castShadow, layer: LAYERS.world }, dressing),- far: approachMeshes(approaches, cs, BRIDGE.roadEndZ, BRIDGE.medianHalfWidth, 'far', approachMaterials(far.scene, 'far', paint), { castShadow: false, layer: LAYERS.world }, dressing),+ near: approachMeshes(approaches, cs, BRIDGE.roadEndZ, BRIDGE.medianHalfWidth, 'near', approachMaterials(views.web.root, 'web', paint), { castShadow: o.castShadow, layer: LAYERS.world }, dressing),+ far: approachMeshes(approaches, cs, BRIDGE.roadEndZ, BRIDGE.medianHalfWidth, 'far', approachMaterials(views.far.root, 'far', paint), { castShadow: false, layer: LAYERS.world }, dressing),};root.add(meshes.near.group, meshes.far.group); meshes.far.group.visible = false;+ // Stand-ins before the merge: a merged mesh spans its whole group, so proxies built after it could not split per tower.+ const layer = o.standInLayer, proxies: ShadowStandIns[] = o.castShadow && layer !== undefined+ ? [shadowStandIns(views.web.root, { layer, isAnchor: n => views.web.groups.has(n) || PROXY_ANCHOR.test(n.name) }), shadowStandIns(meshes.near.group, { layer, isAnchor: () => false })] : [];+ const merged: RigidMerge[] = o.merge ? [views.web, views.far].map(v => mergeRigidByMaterial(v.root, { isAnchor: n => v.groups.has(n), order: m => DRAWN_FIRST.test(m.name) ? -1 : 0 })) : [];+ for (const m of merged) for (const mesh of m.merged) if (drawnLast(mesh)) mesh.renderOrder = 1;+ let reflection: ReturnType<typeof passStandIn> | null = null;+ if (o.passLayers) {+ // Before the vegetation joins the near group (build-world), so it stays reflected.+ mainOnly([meshes.near.group], o.passLayers.main);+ reflection = passStandIn(meshes.far.group, { layer: o.passLayers.pass, parent: meshes.near.group }); reflection.object.visible = true;+ reflection.object.traverse(n => { (n as Mesh).receiveShadow = o.castShadow; });+ }const centrelines = approaches.map(a => a.data.centreline);const colliders = createCollisionWorld();- colliders.addStatic('bridge-obstruction', web.scene, mesh => { let node: Object3D | null = mesh; while (node && node !== web.scene) { if (OBSTRUCTION.test(node.name)) return true; node = node.parent; } return false; });+ colliders.addStatic('bridge-obstruction', source, mesh => { let node: Object3D | null = mesh; while (node && node !== source) { if (OBSTRUCTION.test(node.name)) return true; node = node.parent; } return false; });let usingFar = false, approachesFar = false;const bridge: Bridge = {- root, web: web.scene, far: far.scene, road, colliders, approaches, approachMeshes: meshes, route,+ root, web: source, views: { web: views.web.root, far: views.far.root }, road, colliders, approaches, approachMeshes: meshes, route,get usingFar() { return usingFar; },get approachesFar() { return approachesFar; },update(camera) {// Distance to the bridge's bounding segment (the deck axis from anchorage to anchorage).const z = Math.max(-BRIDGE.roadEndZ, Math.min(BRIDGE.roadEndZ, camera.z)), d = Math.hypot(camera.x, camera.y - 100, camera.z - z);const next = usingFar ? d > o.farSwitch * .88 : d > o.farSwitch * 1.12;- if (next !== usingFar) { usingFar = next; web.scene.visible = !next; far.scene.visible = next; }+ if (next !== usingFar) { usingFar = next; views.web.root.visible = !next; views.far.root.visible = next; }// The approaches switch by the distance to the whole route, with the same hysteresis.const r = Math.min(Math.hypot(camera.x, camera.y - 62, camera.z - z), ...centrelines.map(line => polylineDistance(camera, line)));const nextApproach = approachesFar ? r > o.farSwitch * .88 : r > o.farSwitch * 1.12;if (nextApproach !== approachesFar) { approachesFar = nextApproach; meshes.near.group.visible = !nextApproach; meshes.far.group.visible = nextApproach; }},- setLamps(level) { for (const material of lamps) material.emissiveIntensity = (emissive.get(material) ?? 1) * level; },- stats: { webMeshes, farMeshes, jointMaterials, colliders: colliders.colliders.length, roadCells: road.nx * road.nz, approachTriangles: { near: meshes.near.triangles, far: meshes.far.triangles }, approachDraws: { near: meshes.near.draws, far: meshes.far.draws } },- dispose() { root.removeFromParent(); colliders.dispose(); meshes.near.dispose(); meshes.far.dispose(); paint.dispose(); root.remove(web.scene, far.scene); },+ setLamps(level) { for (const material of lamps) material.emissiveIntensity = (AUTHORED.get(material) ?? 1) * level; },+ stats: { webMeshes, farMeshes, jointMaterials, colliders: colliders.colliders.length, roadCells: road.nx * road.nz, approachTriangles: { near: meshes.near.triangles, far: meshes.far.triangles }, approachDraws: { near: meshes.near.draws, far: meshes.far.draws },+ draws: { web: draws(views.web.root), far: draws(views.far.root) }, merged: merged.length ? { web: merged[0]!.stats, far: merged[1]!.stats } : null,+ shadowProxies: proxies.length ? proxies.reduce((s, p) => ({ proxies: s.proxies + p.stats.proxies, sourceMeshes: s.sourceMeshes + p.stats.sourceMeshes, triangles: s.triangles + p.stats.triangles }), { proxies: 0, sourceMeshes: 0, triangles: 0 }) : null,+ reflectionProxies: reflection?.stats.meshes ?? 0 },+ dispose() {+ root.removeFromParent(); colliders.dispose();+ for (const m of merged) m.restore();+ for (const p of proxies) p.restore();+ reflection?.restore(); meshes.near.dispose(); meshes.far.dispose(); paint.dispose();+ bridge.setLamps(1);+ },};return bridge;}diff --git a/scenes/packages/golden-gate/src/world/build-world.ts b/scenes/packages/golden-gate/src/world/build-world.tsindex 1f72de6b..6860fb1a 100644--- a/scenes/packages/golden-gate/src/world/build-world.ts+++ b/scenes/packages/golden-gate/src/world/build-world.ts@@ -4,6 +4,7 @@// failed or aborted build releases everything it created.import { Group, Vector3 } from 'three/webgpu';import type { PerspectiveCamera, Scene, WebGPURenderer } from 'three/webgpu';+import { cachedSunShadow, passCameraLayers, shadowOncePerFrame } from '@kiln-scenes/scene-kit';import type { LoadedPack, PackReader } from '@kiln-scenes/scene-kit';import type { GoldenGateKnobs } from '../tiers';import { createAtmosphere } from './atmosphere';@@ -13,7 +14,9 @@ import { approachCorridorPlans } from './corridor';import { parkedVehicles } from './dressing';import { vegetationCandidates } from './vegetation';import { LAYOUT } from '../data';-import { BRIDGE } from '../constants';+import { BRIDGE, LAYERS } from '../constants';+import { drawOptions } from './draw-options';+import type { DrawOptions } from './draw-options';import type { SceneIndex, Terrain } from './terrain';import { decodeWaterLevel } from './water-maps';import { decodePng } from './png16';@@ -38,8 +41,14 @@ export interface BuildContext {knobs: GoldenGateKnobs; signal: AbortSignal;/** Deck traffic (on unless the `traffic` development parameter empties the lanes); density defaults to the tier's. */traffic?: { enabled: boolean; density?: TrafficDensity };+ /** Draw optimisation overrides (test and dev builds); the feature level's defaults otherwise (./draw-options). */+ draw?: Partial<DrawOptions>;onProgress?(loaded: number, total: number, text: string): void;}+/** Reflection stand-in layers (High): the near approaches draw for main and shadow cameras, the far-approach stand-ins in the reflection. */+const PASS = { main: LAYERS.mainOnly, pass: LAYERS.reflectionOnly } as const;+/** The cached sun shadow is a development option (World.tsx shadowCache): public builds leave its code out. */+const TEST = !!(import.meta.env.KILN_TEST || import.meta.env.KILN_DEV);function abortIfNeeded(signal: AbortSignal): void { if (signal.aborted) throw signal.reason ?? new DOMException('Golden Gate build aborted', 'AbortError'); }export function readSceneIndex(pack: LoadedPack): SceneIndex {const bytes = pack.data.get('scene');@@ -57,14 +66,21 @@ export async function readCollisionField(pack: LoadedPack, index: SceneIndex): P}export async function buildGoldenGateWorld(c: BuildContext) {- const features = c.knobs.gg, index = readSceneIndex(c.pack), owned: { dispose(): void }[] = [];+ const features = c.knobs.gg, draw = drawOptions(features, c.draw ?? {}), index = readSceneIndex(c.pack), owned: { dispose(): void }[] = [];const release = () => { for (const item of owned.splice(0).reverse()) { try { item.dispose(); } catch { /* keep releasing */ } } };const tiles = index.terrain.sets[features.terrainSet].reduce((sum, level) => sum + (index.terrain.levels[level]?.tiles.length ?? 0), 0);const total = tiles + 7; let loaded = 0;const step = (text: string) => c.onProgress?.(++loaded, total, text);try {const atmosphere: Atmosphere = createAtmosphere(c.renderer, c.scene, { envSize: features.envSize, shadows: c.knobs.shadows.enabled, shadowMapSize: c.knobs.shadows.mapSize, shadowExtent: features.shadowExtent });- owned.push(atmosphere); step('Sky and light');+ // Draw optimisation (High): the sun's shadow camera sees the depth stand-ins and the main-only near approaches; the map+ // renders once per frame (the reflector's camera rendered it again), or through the opt-in cached static and live maps,+ // whose shadow node must be in place before any receiver builds and which are disposed after the light leaves the scene.+ const sun = atmosphere.sun, pass = draw.reflection ? PASS : undefined;+ if (draw.depth) sun.shadow.camera.layers.enable(LAYERS.shadowStandIn);+ if (pass && c.knobs.shadows.enabled) sun.shadow.camera.layers.enable(pass.main);+ const once = draw.once ? shadowOncePerFrame(sun) : null, cache = TEST && draw.cache ? cachedSunShadow({ light: sun }) : null;+ owned.push({ dispose() { atmosphere.dispose(); once?.restore(); cache?.dispose(); } }); step('Sky and light');const fogNode = sceneFogNode(atmosphere.uniforms);const maps = index.terrain.water[features.terrainSet];const fetch = (path: string) => c.reader.fetchFile(path, c.signal);@@ -90,11 +106,11 @@ export async function buildGoldenGateWorld(c: BuildContext) {abortIfNeeded(c.signal); step('Water maps');const web = c.pack.models.get(index.bridge.web.model), far = c.pack.models.get(index.bridge.far.model);if (!web || !far) throw new Error('Bridge models are missing from the verified pack');- const bridge: Bridge = createBridge(web, far, { farSwitch: features.bridgeFarSwitch, castShadow: c.knobs.shadows.enabled });+ const bridge: Bridge = createBridge(web, far, { farSwitch: features.bridgeFarSwitch, castShadow: c.knobs.shadows.enabled, merge: draw.merge, standInLayer: draw.depth ? LAYERS.shadowStandIn : undefined, passLayers: pass });owned.push(bridge); step('Bridge');// The vegetation impostors switch with the approaches' near representation (fix round 3 item 5).bridge.approachMeshes.near.group.add(terrain.vegetation.root);- const water: Water = createWater(c.scene, { features: features.water, atmosphere, near: near.level, mid: mid.level, midGrid: mid.grid });+ const water: Water = createWater(c.scene, { features: features.water, atmosphere, near: near.level, mid: mid.level, midGrid: mid.grid, passLayers: pass });owned.push(water); step('Water');const banks: FogBanks | null = features.fogBanks > 0 ? createFogBanks(atmosphere.uniforms, water.textures.macroNoise, features.fogBanks) : null;if (banks) owned.push(banks);@@ -117,6 +133,10 @@ export async function buildGoldenGateWorld(c: BuildContext) {const traffic: Traffic = createTraffic({ models, route: bridge.route, density: c.traffic?.density ?? features.traffic.density,perLaneMax: c.traffic?.enabled === false ? 0 : features.traffic.perLaneMax, lod: features.traffic.lod, shadows: c.knobs.shadows.enabled, contactShadow: features.traffic.contactShadow, parked });owned.push(traffic);+ // Traffic moves through instance attributes, which the cache's watch cannot see: its casters draw in the live map, which+ // renders while any of them is shown with instances and once more to clear it.+ let fit = '';+ if (cache) { cache.track(bridge.root); cache.track(traffic.root, { live: () => true }); }step('Traffic');const root = new Group(); root.name = 'golden-gate-world';root.add(terrain.root, bridge.root, traffic.root); if (banks) root.add(banks.sprite);@@ -128,7 +148,7 @@ export async function buildGoldenGateWorld(c: BuildContext) {const focus = new Vector3();const stats = {tier: features.feature, terrainTiles: terrain.tiles, terrainTriangles: terrain.triangles, terrainTextureBytes: terrain.textureBytes, terrainUvFlipped: terrain.uvFlipped, terrainCorridor: terrain.corridor,- bridge: bridge.stats, fogBankPuffs: banks?.puffs ?? 0, water: water.stats,+ bridge: bridge.stats, draw, sunCache: cache?.stats ?? null, fogBankPuffs: banks?.puffs ?? 0, water: water.stats,vegetation: { candidates: terrain.vegetation.candidates, cards: terrain.vegetation.cards, dropped: terrain.vegetation.dropped, meshes: terrain.vegetation.meshes, bytes: terrain.vegetation.bytes, atlasBytes: terrain.vegetation.atlasBytes },vehicles: [...models.values()].map(m => ({ type: m.type, triangles: m.triangles, length: +m.length.toFixed(3), wheelRadius: m.wheelRadius })),};@@ -145,12 +165,20 @@ export async function buildGoldenGateWorld(c: BuildContext) {/** Per frame after the cameras: view-dependent state. */update(camera: PerspectiveCamera, time: number, bankOpacity: number, delta: number) {if (c.scene.fogNode !== fogNode) c.scene.fogNode = fogNode; // the kit's look may reset it+ if (pass) passCameraLayers(camera, pass, 'main');atmosphere.hideSunFor(water.reflectionCamera(camera));atmosphere.update(camera, focus, performance.now() / 1000); // wall clock: environment throttle onlywater.update(camera, time);bridge.update(camera.position);banks?.update(time, bankOpacity);traffic.update(camera, delta, vehicleLights);+ once?.update();+ if (cache) {+ // The static map re-renders when its fit or the bridge and approach representations change.+ const key = `${atmosphere.shadowFit}|${bridge.usingFar}|${bridge.approachesFar}`;+ if (key !== fit) { fit = key; cache.invalidate('fit'); }+ cache.update();+ }},dispose() { if (c.scene.fogNode === fogNode) c.scene.fogNode = null; release(); },};diff --git a/scenes/packages/golden-gate/src/world/draw-options.ts b/scenes/packages/golden-gate/src/world/draw-options.tsnew file mode 100644index 00000000..22620b53--- /dev/null+++ b/scenes/packages/golden-gate/src/world/draw-options.ts@@ -0,0 +1,14 @@+// Draw optimisation switches (docs/plans/2026-10-01-draw-optimization-cycle.md S4/S4b, OD-18): what each feature level+// takes by default. The bridge merge applies at every level; the shadow and reflection features exist only where the pass+// does (High). The cached sun shadow is opt-in: Golden Gate's texel-snapped sun moves on almost every drive frame+// (tmp/drawcalls/understand/shadow-internals.check.md claim 22). Its maps render once per frame by construction, so it+// replaces the once-per-frame render. Test and dev builds override each switch through development parameters read in+// World.tsx (bridgeMerge, shadowOnce, standIns, reflectionStandIns, shadowCache), whose names stay out of public builds.+import type { GoldenGateFeatures } from '../tiers';++/** merge: bridge parts by material; once: the sun map once per frame; depth: shadow depth stand-ins; reflection: far-approach stand-ins in the planar reflection; cache: the cached static plus live sun shadow. */+export interface DrawOptions { merge: boolean; once: boolean; depth: boolean; reflection: boolean; cache: boolean }+export function drawOptions(f: GoldenGateFeatures, o: Partial<DrawOptions>): DrawOptions {+ const shadows = f.shadows.enabled, cache = shadows && o.cache === true;+ return { merge: o.merge !== false, once: shadows && !cache && o.once !== false, depth: shadows && o.depth !== false, reflection: f.water.reflection === 'planar' && o.reflection !== false, cache };+}diff --git a/scenes/packages/golden-gate/src/world/water.ts b/scenes/packages/golden-gate/src/world/water.tsindex 5c8b68f6..72740237 100644--- a/scenes/packages/golden-gate/src/world/water.ts+++ b/scenes/packages/golden-gate/src/world/water.ts@@ -13,17 +13,21 @@ import type { WaterGrid, WaterMapLevel } from './water-maps';import { macroNoiseTexture, slopeMomentTexture, synthesizeSlopes } from './detail-textures';import type { Atmosphere } from './atmosphere';import type { GoldenGateFeatures } from '../tiers';+import { passCameraLayers } from '@kiln-scenes/scene-kit';+import type { PassLayers } from '@kiln-scenes/scene-kit';import { LAYERS } from '../constants';export interface WaterOptions {features: GoldenGateFeatures['water'];atmosphere: Atmosphere;near: WaterMapLevel; mid: WaterMapLevel; midGrid: WaterGrid;+ /** Reflection stand-ins (High): the virtual camera drops `main` and takes `pass`; its other bits stay as cloned from the main camera. */+ passLayers?: PassLayers;}export interface Water {mesh: Mesh; uniforms: WaterUniforms; clipmap: ClipmapOptions;textures: { macroNoise: DataTexture; slopeMoments: DataTexture; flow: DataTexture };- /** The reflector's virtual camera (High), so the sky can hide its sun disc there. */+ /** The reflector's virtual camera (High), so the sky can hide its sun disc there; with pass layers, its two pass bits are set on every call (three may recreate it). */reflectionCamera(camera: Camera): Camera | null;update(camera: PerspectiveCamera, time: number): void;readonly stats: { tiles: number; maxTiles: number; vertices: number; reflection: string; description: ReturnType<typeof describeWater> };@@ -63,7 +67,12 @@ export function createWater(scene: Scene, o: WaterOptions): Water {const stats = { tiles: 0, maxTiles: maxTiles(clipmap), vertices: 0, reflection: f.reflection, description: describeWater(options) };return {mesh, uniforms, clipmap, textures: { macroNoise, slopeMoments, flow },- reflectionCamera(camera) { return reflection ? (reflection as unknown as { reflector: { getVirtualCamera(c: Camera): Camera } }).reflector.getVirtualCamera(camera) : null; },+ reflectionCamera(camera) {+ if (!reflection) return null;+ const virtual = (reflection as unknown as { reflector: { getVirtualCamera(c: Camera): Camera } }).reflector.getVirtualCamera(camera);+ if (o.passLayers) passCameraLayers(virtual, o.passLayers, 'pass');+ return virtual;+ },update(camera, time) {camera.updateMatrixWorld();projection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); frustum.setFromProjectionMatrix(projection);diff --git a/scenes/packages/golden-gate/tests/tools/draw-parity.ts b/scenes/packages/golden-gate/tests/tools/draw-parity.tsnew file mode 100644index 00000000..6f5a1b27--- /dev/null+++ b/scenes/packages/golden-gate/tests/tools/draw-parity.ts@@ -0,0 +1,229 @@+// Draw optimisation parity (docs/plans/2026-10-01-draw-optimization-cycle.md S4b/S5, OD-4, OD-18): frozen-clock captures of+// Golden Gate views with every draw optimisation off (bridgeMerge, shadowOnce, standIns and reflectionStandIns false), a+// second capture of the same as the noise floor, and the build's defaults (or one variant), compared with the B-06 comparer+// (scripts/parity-images.ts compareParityImages). A test-mode build is required:+// bun scripts/build-scene.ts --scene golden-gate --mode test --label <l>+// bun packages/golden-gate/tests/tools/draw-parity.ts --build <l> [--before <label>] [--tiers high,minimal] [--presets day]+// [--views arrival,postcard,pier,send-side,deck,lanes,drive-nb-0|@set,...] [--variant defaults|<query>] [--backend webgl2]+// [--over32-budget 100] [--write all|changed|none] [--page fresh|shared] [--out <dir>]+// Two-build mode (S5): `--before <label>` captures that build twice (the reference and its repeat, the noise floor) and+// `--build` once, each at its own defaults on its own server for the whole run, and checks every page's code chunk against+// its build's build.json, so a page can never be served by the other build. Without it, all three captures come from+// `--build`: optimisations off twice, then its defaults or `--variant`, a query added to the "on" capture (for example+// `standIns=false` to isolate a feature).+// Views are scene cameras (`cam`), review poses held with setPose (POSES below, from tests/tools/capture.ts and the wave-B+// review's shore and far-LOD poses) or chase-camera drive placements (`drive-<lane>-<station>`, the car at rest on an empty+// road). `@<set>` expands to a named list (VIEW_SETS). `--presets` takes day, golden and fog (the scene has no night).+// `--page fresh` (default) loads a page per capture; `--page shared` holds each run's cases on one page per tier (see+// sharedRun), about ten times faster, with the same path through the views in every run.+// A case passes when B-06 passes and the "on" capture has at most `--over32-budget` more pixels over 32 levels than the+// repeat: B-06 judges tile means, which thin-line regressions such as a kerb stipple never move far enough (wave-B review+// R1, R4). The default budget sits above the merge's measured residual (depth-tie specks far out: at most 74 px over 32+// levels, at the golden-hour arrival; 52 at the day span view) and below the kerb stipple it must catch (878 to 1,555 px+// in daylight).+// Output per case <tier>-<preset>-<view>[-<variant>][-webgl2]: -off.png, -repeat.png, -on.png and -diff.png (B-06 luminance+// x4) in same-build mode, -before.png, -repeat.png, -after.png and -diff.png in two-build mode (`--write changed` keeps them+// only for cases that fail or have at least 20 more pixels over 32 levels than the repeat), and parity.json and parity.md accumulating every+// run's rows. Pages load from the owned loopback server; nothing here reads time.+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { PNG } from 'pngjs';+import type { Page } from 'puppeteer-core';+import { assertOwnedUrl, launchChrome, serveOwned, waitForReady, waitFrames } from '../../../scene-kit/src/testing/node';+import { sceneOutput } from '../../../../scripts/build-scene';+import { compareParityImages, type RgbaImage } from '../../../../scripts/parity-images';++const SCENES = resolve(import.meta.dir, '../../../..'), WIDTH = 1280, HEIGHT = 720, TIMEOUT = 180_000;+const OFF = { bridgeMerge: 'false', shadowOnce: 'false', standIns: 'false', reflectionStandIns: 'false' };+type Pose = { position: [number, number, number]; target: [number, number, number]; fov: number };+const POSES: Record<string, Pose> = {+ // tests/tools/capture.ts (SCENE-REVIEW-2): the south pier poses, the side poses and the deck ends.+ 'sp-high-w': { position: [90, 70, -560], target: [0, 4, -640], fov: 55 },+ 'sp-high-e': { position: [-90, 70, -720], target: [0, 4, -640], fov: 55 },+ 'sp-top': { position: [30, 150, -600], target: [0, 2, -640], fov: 55 },+ 'sp-deck': { position: [0, 95, -480], target: [0, 5, -640], fov: 55 },+ 'side-span': { position: [450, 85, -300], target: [0, 68, -300], fov: 55 },+ 'side-full': { position: [900, 120, 0], target: [0, 70, 0], fov: 55 },+ 'send-side': { position: [140, 110, -1000], target: [0, 70, -1040], fov: 55 },+ 'send-high': { position: [0, 200, -900], target: [0, 60, -1060], fov: 55 },+ 'send-drive': { position: [0, 78.5, -960], target: [0, 74, -1100], fov: 55 },+ 'send-back': { position: [20, 90, -1150], target: [0, 72, -1000], fov: 55 },+ 'nend-side': { position: [140, 110, 1000], target: [0, 70, 1040], fov: 55 },+ 'nend-high': { position: [0, 200, 900], target: [0, 60, 1060], fov: 55 },+ 'nend-drive': { position: [0, 78.5, 960], target: [0, 74, 1100], fov: 55 },+ 'nend-back': { position: [20, 90, 1150], target: [0, 72, 1000], fov: 55 },+ // tests/tools/capture.ts: the driver's eye 1.2 m above the middle lane entering and leaving the deck (g3 route).+ 'send-enter': { position: [-13.34, 60.2, -1151.59], target: [-5.95, 61.71, -1092.63], fov: 55 },+ 'send-leave': { position: [4.8, 65.66, -972.98], target: [4.8, 62.92, -1052.98], fov: 55 },+ 'nend-enter': { position: [4.8, 65.22, 1152.98], target: [4.8, 63.13, 1092.98], fov: 55 },+ 'nend-leave': { position: [-4.8, 65.66, 972.98], target: [-4.8, 63.08, 1052.98], fov: 55 },+ // Wave-B review (review-golden-gate-foundry gg-ab.ts): low over the water near the shores, so the anchorages', approaches'+ // and traffic's reflections fill the frame, and beyond the far-LOD switch at High (5,200 m x 1.12) and Low (1,900 m x 1.12).+ 'fp-east-low': { position: [-260, 6, -760], target: [0, 30, -1100], fov: 55 },+ 'fp-west-low': { position: [260, 6, -760], target: [0, 30, -1100], fov: 55 },+ 'n-east-low': { position: [-260, 6, 760], target: [0, 30, 1100], fov: 55 },+ 'n-west-low': { position: [260, 6, 760], target: [0, 30, 1100], fov: 55 },+ 'pier-reflect': { position: [-60, 3, -520], target: [0, 60, -700], fov: 55 },+ 'far-high': { position: [6600, 900, -500], target: [0, 100, 0], fov: 40 },+ 'far-low': { position: [2700, 600, -300], target: [0, 100, 0], fov: 50 },+};+/** Named view lists for `--views @<set>`: the scene cameras, the capture tool's water, pier and approaches sets, the review's deck, shore and drive sets. */+const VIEW_SETS: Record<string, string[]> = {+ defaults: ['arrival', 'postcard', 'pier', 'send-side', 'deck', 'lanes', 'drive-nb-0'],+ views: ['arrival', 'postcard', 'pier', 'topdown', 'horizon', 'deck', 'tower', 'span', 'lanes', 'sidewalk', 'traffic'],+ deck: ['deck', 'lanes', 'traffic', 'sidewalk', 'tower'],+ water: ['postcard', 'pier', 'topdown', 'horizon', 'deck'],+ pier: ['sp-high-w', 'sp-high-e', 'sp-top', 'sp-deck', 'side-span', 'side-full'],+ approaches: ['send-side', 'send-high', 'send-drive', 'send-back', 'nend-side', 'nend-high', 'nend-drive', 'nend-back', 'send-enter', 'send-leave', 'nend-enter', 'nend-leave'],+ shore: ['fp-east-low', 'fp-west-low', 'n-east-low', 'n-west-low', 'pier-reflect'],+ drive: ['drive-nb--1300', 'drive-nb--640', 'drive-nb-0', 'drive-nb-660', 'drive-nb-1300', 'drive-sb--400', 'drive-sb-400'],+};+/** Chase-camera drive placements: `drive-<lane>-<station>` puts the car at rest in the lane's middle (nb-middle, sb-middle) at that route station (m). */+const DRIVE = /^drive-(nb|sb)-(-?\d+)$/;+const args = process.argv.slice(2), option = (name: string, fallback: string) => { const at = args.indexOf(name); return at < 0 ? fallback : args[at + 1] ?? fallback; };+const build = option('--build', ''), before = option('--before', ''), tiers = option('--tiers', 'high,minimal').split(','), presets = option('--presets', 'day').split(',');+const views = option('--views', '@defaults').split(',').flatMap(v => { if (!v.startsWith('@')) return [v]; const set = VIEW_SETS[v.slice(1)]; if (!set) throw new Error(`Unknown view set ${v}; sets: ${Object.keys(VIEW_SETS).join(', ')}`); return set; });+const variant = option('--variant', 'defaults'), backend = option('--backend', '') === 'webgl2' ? { backend: 'webgl2' } : {}, out = resolve(SCENES, option('--out', '../tmp/drawcalls/wave-b/gg/parity'));+/** `--write changed` keeps a case's images when it fails or has at least this many more pixels over 32 levels than its repeat (the wave-B review's "cases with > 20 px over 32"). */+const CHANGED = 20;+const budget = Number(option('--over32-budget', '100')), writeMode = option('--write', 'all'), pageMode = option('--page', 'fresh');+if (!build) throw new Error('--build <label> is required');+if (!(budget >= 0)) throw new Error('--over32-budget must be 0 or more');+if (!['all', 'changed', 'none'].includes(writeMode)) throw new Error('--write is all, changed or none');+if (!['fresh', 'shared'].includes(pageMode)) throw new Error('--page is fresh or shared');+for (const p of presets) if (!['day', 'golden', 'fog'].includes(p)) throw new Error(`Unknown preset ${p}; the scene has day, golden and fog`);+if (before && variant !== 'defaults') throw new Error('--variant applies to same-build runs only');++/* eslint-disable @typescript-eslint/no-explicit-any */+const invoke = (page: Page, name: string, ...a: unknown[]) => page.evaluate((n, v) => (window as any).__kilnScene.invoke(n, ...v), name, a) as Promise<any>;+const api = (page: Page, name: string, ...a: unknown[]) => page.evaluate((n, v) => (window as any).__kilnScene[n](...v), name, a) as Promise<any>;+/** Waits until two reads 10 frames apart agree (the orbit, pose and chase camera ease in). */+async function settle(page: Page, read: () => Promise<unknown>) { for (let i = 0, last = ''; i < 30; i++) { const now = JSON.stringify(await read()); if (now === last) break; last = now; await waitFrames(page, 10); } }+/** Enters the car (play mode) and places it at rest; traffic is off for drive views, so the road is the same in every capture. */+async function placeCar(page: Page, lane: string, station: number) {+ await api(page, 'setPlaying', true);+ for (let i = 0; i < 300 && !(await invoke(page, 'driveState')); i++) await waitFrames(page, 5);+ if (!(await invoke(page, 'driveState'))) { await api(page, 'setTimeScale', 1); for (let i = 0; i < 300 && !(await invoke(page, 'driveState')); i++) await waitFrames(page, 5); await api(page, 'setTimeScale', 0); }+ if (!(await invoke(page, 'driveState'))) throw new Error('Could not enter the car');+ await invoke(page, 'setDriveInput', { throttle: 0 });+ if (!(await invoke(page, 'placeCar', `${lane}-middle`, station, 0))) throw new Error(`placeCar ${lane}-middle ${station} failed`);+ await waitFrames(page, 30); await settle(page, async () => (await invoke(page, 'driveState'))?.camera.position);+}+interface Hosted { url: string; label: string; chunk: string }+/** The build's entry chunk (index-*.js) from its build.json, which each page must have loaded. */+function entryChunk(label: string): string {+ const built = JSON.parse(readFileSync(resolve(sceneOutput('golden-gate', label, 'test'), 'build.json'), 'utf8')) as { chunks: { name: string }[] };+ const entry = built.chunks.map(c => c.name).find(n => /^index-.*\.js$/.test(n)); if (!entry) throw new Error(`No index chunk in ${label}'s build.json`);+ return entry;+}+type Browser = Awaited<ReturnType<typeof launchChrome>>;+/** Opens a page of one build at a tier and preset, with the camera at `cam`; drive pages run with traffic off. */+async function load(hosted: Hosted, owned: ReadonlySet<number>, browser: Browser, tier: string, preset: string, cam: string, drives: boolean, extra: Record<string, string>) {+ const url = `${hosted.url}/?${new URLSearchParams({ capture: '1', hud: '0', tier, preset, cam, time: '12', ...(drives ? { traffic: 'false' } : {}), ...backend, ...extra })}`;+ assertOwnedUrl(url, owned);+ const page = await browser.newPage(); page.setDefaultTimeout(TIMEOUT); await page.setCacheEnabled(false);+ try {+ await page.setViewport({ width: WIDTH, height: HEIGHT, deviceScaleFactor: 1 });+ await page.goto(url, { waitUntil: 'load', timeout: TIMEOUT }); await waitForReady(page);+ const scripts = await page.$$eval('script[src]', list => list.map(s => (s as HTMLScriptElement).src));+ if (!scripts.some(s => s.endsWith(`/${hosted.chunk}`))) throw new Error(`Page for ${hosted.label} loaded ${scripts.join(', ')}, not ${hosted.chunk}`);+ await waitFrames(page, 12);+ return page;+ } catch (error) { await page.close().catch(() => {}); throw error; }+}+/** Holds a view on an open page (a pose, a drive placement or, on a shared page, a scene camera) and captures it. */+async function capture(page: Page, view: string, shared: boolean) {+ const pose = POSES[view], drive = DRIVE.exec(view);+ if (pose && await invoke(page, 'setPose', pose) !== 'pose') throw new Error(`setPose ${view} failed`);+ if (shared && !pose && !drive) { await invoke(page, 'setView', view); await waitFrames(page, 20); }+ if (drive) await placeCar(page, drive[1]!, Number(drive[2]));+ else await settle(page, async () => (await invoke(page, 'ggStats')).camera.position);+ await waitFrames(page, shared ? 6 : 4);+ const stats = await invoke(page, 'ggStats'), canvas = await page.$('canvas');+ const png = PNG.sync.read(Buffer.from(await canvas!.screenshot({ type: 'png' })));+ if (png.width !== WIDTH || png.height !== HEIGHT) throw new Error(`Capture is ${png.width}x${png.height}, expected ${WIDTH}x${HEIGHT}`);+ return { png: { width: png.width, height: png.height, data: new Uint8Array(png.data) } as RgbaImage, draw: stats.draw ?? null, usingFar: stats.usingFarBridge, preset: stats.preset,+ bridge: { webMeshes: stats.bridge.webMeshes, draws: stats.bridge.draws ?? null, proxies: stats.bridge.shadowProxies?.proxies ?? 0, reflection: stats.bridge.reflectionProxies ?? 0 },+ camera: stats.camera.position, backend: await page.$eval('.ks-root', root => root.getAttribute('data-kiln-backend')) };+}+type Shot = Awaited<ReturnType<typeof capture>>;+interface Case { tier: string; preset: string; view: string }+/** Fresh pages: every capture loads its own page, whose URL fixes the preset and the camera. */+async function freshShot(hosted: Hosted, owned: ReadonlySet<number>, browser: Browser, c: Case, extra: Record<string, string>): Promise<Shot> {+ const special = !!POSES[c.view] || DRIVE.test(c.view), page = await load(hosted, owned, browser, c.tier, c.preset, special ? 'postcard' : c.view, DRIVE.test(c.view), extra);+ try { return await capture(page, c.view, false); } finally { await page.close().catch(() => {}); }+}+/**+ * Shared pages: one page per build, tier and kind (scene views and poses on one, drive placements with traffic off on+ * another) holds every case in the same order in each run, changing the preset with `setPreset` and the camera with+ * `setView` or `setPose`; the governor is held (`feedFrameTimes`), as the count probe does, so a slow frame cannot change+ * the tier. Each of the three runs takes the same path, so LOD hysteresis and other view history match between them.+ */+async function sharedRun(hosted: Hosted, owned: ReadonlySet<number>, browser: Browser, cases: Case[], extra: Record<string, string>): Promise<Shot[]> {+ const shots: Shot[] = new Array(cases.length);+ const groups = new Map<string, number[]>();+ cases.forEach((c, i) => { const k = `${c.tier}|${DRIVE.test(c.view)}`; groups.set(k, [...(groups.get(k) ?? []), i]); });+ for (const [k, indices] of groups) {+ const [tier, drives] = k.split('|') as [string, string], first = cases[indices[0]!]!;+ const page = await load(hosted, owned, browser, tier, first.preset, 'arrival', drives === 'true', extra);+ try {+ await page.evaluate(() => (window as any).__kilnScene.feedFrameTimes([]));+ let preset = first.preset;+ for (const i of indices) {+ const c = cases[i]!;+ if (c.preset !== preset) { await invoke(page, 'setPreset', c.preset); preset = c.preset; await waitFrames(page, 6); }+ shots[i] = await capture(page, c.view, true);+ if (shots[i]!.preset !== c.preset) throw new Error(`${c.view}: preset ${shots[i]!.preset}, expected ${c.preset}`);+ }+ } finally { await page.close().catch(() => {}); }+ }+ return shots;+}+const write = (path: string, image: RgbaImage) => { const png = new PNG({ width: image.width, height: image.height }); png.data = Buffer.from(image.data); writeFileSync(path, PNG.sync.write(png)); };+/** Exact pixel differences: pixels differing at all, by more than 8 and by more than 32 levels in any channel, the largest channel delta and the box of the over-32 pixels. */+const exact = (a: RgbaImage, b: RgbaImage) => {+ let differing = 0, over8 = 0, over32 = 0, max = 0, x0 = Infinity, y0 = Infinity, x1 = -1, y1 = -1;+ for (let i = 0; i < a.data.length; i += 4) {+ let d = 0; for (let c = 0; c < 3; c++) d = Math.max(d, Math.abs(a.data[i + c]! - b.data[i + c]!));+ if (!d) continue;+ differing++; if (d > 8) over8++; if (d > max) max = d;+ if (d > 32) { over32++; const p = i / 4, x = p % a.width, y = Math.floor(p / a.width); x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }+ }+ return { differingPixels: differing, over8, over32, maxChannelDelta: max, over32Box: x1 < 0 ? null : [x0, y0, x1, y1] };+};++mkdirSync(out, { recursive: true });+const on = before || variant === 'defaults' ? {} : Object.fromEntries(new URLSearchParams(variant)), tag = (variant === 'defaults' ? '' : `-${variant.replace(/[^a-zA-Z0-9]+/g, '_')}`) + (backend.backend ? '-webgl2' : '');+// One server per build for the whole run, on distinct ports: a closed server's keep-alive sockets can otherwise answer for the next one.+const servedB = await serveOwned(sceneOutput('golden-gate', build, 'test')), servedA = before ? await serveOwned(sceneOutput('golden-gate', before, 'test')) : servedB;+const hostB: Hosted = { url: servedB.url, label: build, chunk: entryChunk(build) }, hostA: Hosted = before ? { url: servedA.url, label: before, chunk: entryChunk(before) } : hostB;+const owned = new Set([servedA.port, servedB.port]), browser = await launchChrome({ workspace: SCENES, name: 'gg-draw-parity', windowSize: [WIDTH, HEIGHT] });+const reference = before ? {} : OFF, [nameA, nameB] = before ? ['before', 'after'] : ['off', 'on'];+const results: any[] = [], cases: Case[] = tiers.flatMap(tier => presets.flatMap(preset => views.map(view => ({ tier, preset, view }))));+try {+ // Shared pages capture each run as a whole (reference, repeat, then the build under test); fresh pages go case by case.+ const runs = pageMode === 'shared' ? await (async () => { const a = await sharedRun(hostA, owned, browser, cases, reference), r = await sharedRun(hostA, owned, browser, cases, reference); return { a, r, b: await sharedRun(hostB, owned, browser, cases, on) }; })() : null;+ for (const [index, { tier, preset, view }] of cases.entries()) {+ const c = cases[index]!;+ const a = runs ? runs.a[index]! : await freshShot(hostA, owned, browser, c, reference), r = runs ? runs.r[index]! : await freshShot(hostA, owned, browser, c, reference), b = runs ? runs.b[index]! : await freshShot(hostB, owned, browser, c, on);+ const parity = compareParityImages(a.png, r.png, b.png), name = `${tier}-${preset}-${view}${tag}`, onVsOff = exact(a.png, b.png), repeatVsOff = exact(a.png, r.png);+ const lines = { over32: onVsOff.over32, noise: repeatVsOff.over32, budget, pass: onVsOff.over32 <= repeatVsOff.over32 + budget };+ const pass = parity.pass && lines.pass;+ if (writeMode === 'all' || (writeMode === 'changed' && (!pass || onVsOff.over32 >= repeatVsOff.over32 + CHANGED))) {+ write(resolve(out, `${name}-${nameA}.png`), a.png); write(resolve(out, `${name}-repeat.png`), r.png); write(resolve(out, `${name}-${nameB}.png`), b.png); write(resolve(out, `${name}-diff.png`), parity.diff);+ }+ const row = { tier, preset, view, variant, before: before || null, page: pageMode, backend: b.backend, pass, b06: parity.pass, lines, globalMean: parity.globalMean, noiseGlobalMean: parity.noiseGlobalMean, passingTiles: parity.passingTiles, tiles: parity.tiles.length,+ failingTiles: parity.tiles.filter(t => !t.pass).map(t => ({ x: t.x, y: t.y, mean: +t.mean.toExponential(2), threshold: +t.threshold.toExponential(2) })),+ onVsOff, repeatVsOff, draw: { off: a.draw, on: b.draw }, bridge: { off: a.bridge, on: b.bridge }, usingFar: { off: a.usingFar, on: b.usingFar }, camera: { off: a.camera, on: b.camera } };+ results.push(row);+ console.log(`${name} (${b.backend}${before ? `, ${before} vs ${build}` : ''}): ${row.pass ? 'PASS' : 'FAIL'} B-06 ${parity.pass ? 'pass' : 'FAIL'} mean ${parity.globalMean.toExponential(2)} noise ${parity.noiseGlobalMean.toExponential(2)} tiles ${parity.passingTiles}/${parity.tiles.length}; over 32 ${onVsOff.over32} vs repeat ${repeatVsOff.over32} (budget ${budget}) ${lines.pass ? 'ok' : 'OVER'}; differing ${onVsOff.differingPixels} (max ${onVsOff.maxChannelDelta}), repeat differing ${repeatVsOff.differingPixels}`);+ }+} finally { await browser.close(); await servedB.close(); if (servedA !== servedB) await servedA.close(); }+// parity.json accumulates rows across runs (keyed by build, reference build, tier, preset, view, variant and backend); parity.md lists them all.+const json = resolve(out, 'parity.json'), key = (r: any) => `${r.build}|${r.before ?? ''}|${r.tier}|${r.preset ?? 'day'}|${r.view}|${r.variant}|${r.backend}`;+const previous: any[] = existsSync(json) ? (JSON.parse(readFileSync(json, 'utf8')).results ?? []).filter((r: any) => r.build) : [], fresh = new Set(results.map(r => key({ ...r, build })));+const all = [...previous.filter(r => !fresh.has(key(r))), ...results.map(r => ({ build, ...r }))];+writeFileSync(json, JSON.stringify({ size: [WIDTH, HEIGHT], off: OFF, results: all }, null, 1) + '\n');+writeFileSync(resolve(out, 'parity.md'), ['| build | reference | backend | tier | preset | view | variant | pass | B-06 | mean luminance delta | repeat noise | tiles passing | over 32 (on vs reference) | over 32 (repeat vs reference) | pixels differing (on vs reference) | max channel delta | pixels differing (repeat vs reference) |', '|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|',+ ...all.map(r => `| ${r.build} | ${r.before ?? 'off'} | ${r.backend} | ${r.tier} | ${r.preset ?? 'day'} | ${r.view} | ${r.variant} | ${r.pass ? 'yes' : 'NO'} | ${(r.b06 ?? r.pass) ? 'yes' : 'NO'} | ${r.globalMean.toExponential(2)} | ${r.noiseGlobalMean.toExponential(2)} | ${r.passingTiles}/${r.tiles} | ${r.onVsOff.over32 ?? '-'} | ${r.repeatVsOff.over32 ?? '-'} | ${r.onVsOff.differingPixels} | ${r.onVsOff.maxChannelDelta} | ${r.repeatVsOff.differingPixels} |`)].join('\n') + '\n');+process.exitCode = results.every(r => r.pass) ? 0 : 1;diff --git a/scenes/packages/golden-gate/tests/tools/perf-local.ts b/scenes/packages/golden-gate/tests/tools/perf-local.tsindex aea6405f..eb7df59b 100644--- a/scenes/packages/golden-gate/tests/tools/perf-local.ts+++ b/scenes/packages/golden-gate/tests/tools/perf-local.ts@@ -1,7 +1,13 @@// SPEC 20.3's local evidence for Golden Gate: the count, byte and memory checks that do not depend on// machine load (no timing is taken or kept). Headless Chrome (owner rule 11:40) on this builder's ports.-// X-02 renderer.info at the ten named views, four hero-orbit points and the drive fixture, on the-// frozen clock (WATER-SPEC time 12, Day), tiers high, balanced and economy, WebGPU and WebGL2+// X-02 renderer.info at the named views (eleven since `arrival` joined layout.json's cameras, so 16 views in+// all), four hero-orbit points and the drive fixture, on the frozen clock (WATER-SPEC time 12, Day),+// tiers high, balanced and economy, WebGPU and WebGL2. Golden Gate has no pilot, so its own run is the+// baseline: `--baseline=<x02-counts.json>` checks every view's draw calls and triangles against one+// within 2 percent (OD-8 / D-53: the rule binds at High; the other tiers are reported). Since the draw+// optimisation (OD-18) each view also records the bridge's `webMeshes` (meshes in the authored web+// model, counted before the merge: unchanged at 148) and `bridgeDraws` (meshes the merged web and far+// views draw: 20 and 18); webMeshes no longer equals the bridge's draws.// X-03 the kit's B-05 protocol for this scene: initialization cycles, then ten measured mount and// unmount cycles alternating WebGPU and WebGL2; heap after a forced collection within 5 percent,// one released backend per mount, no canvas, HUD, callback or extra listener left@@ -10,11 +16,16 @@// X-12 per-frame allocation: 1,000 frames of each workload (orbit, flyover, drive) between forced// collections; growth under 2 MB// ./scripts/toolchain-run.ps1 packages/golden-gate/tests/tools/perf-local.ts [x02] [x03] [x11] [x12] [--out=<dir>]+// [--build=<label>] [--baseline=<x02-counts.json>]// --out= writes the files to another directory under the package (default evidence/perf; fix round 2 wrote// nothing there while the hub session owned it). One token with "=": toolchain-run.ps1 is an advanced PowerShell-// script, which reads a separate "--out" as its ambiguous -OutVariable/-OutBuffer.+// script, which reads a separate "--out" as its ambiguous -OutVariable/-OutBuffer. --build= measures a labelled+// build from scripts/build-scene.ts (dist/<label>/test and dist/<label>/public) instead of dist/test and+// dist/standalone; x02-counts.json names the build's chunks and source either way. --baseline= (a path from the+// working directory) writes x02-check.json beside the counts and exits 1 when a High view is outside 2 percent.import assert from 'node:assert/strict';-import { readFileSync } from 'node:fs';+import { createHash } from 'node:crypto';+import { existsSync, readFileSync } from 'node:fs';import { resolve } from 'node:path';import type { CDPSession, Page } from 'puppeteer-core';import { assertTeardownListenerAudit } from '@kiln-scenes/scene-kit';@@ -29,7 +40,21 @@ const WIDTH = 1920, HEIGHT = 1080, TIME = 12, TIMEOUT = 180_000;const wanted = new Set(process.argv.slice(2).filter(a => /^x\d\d$/.test(a))); const run = (id: string) => !wanted.size || wanted.has(id);const servers: Hosted[] = [], owned = new Set<number>();const serve = async (root: string) => { const hosted = await serveOwned(root, owned); servers.push(hosted); owned.add(hosted.port); return hosted; };-const test = await serve(outputFor('test')), publicBuild = await serve(outputFor('public'));+const argValue = (name: string) => process.argv.find(a => a.startsWith(`--${name}=`))?.slice(name.length + 3);+const label = argValue('build'), baselinePath = argValue('baseline');+if (label !== undefined && !/^[a-z0-9-]+$/.test(label)) throw new Error('--build=<label> takes lowercase letters, numbers and hyphens');+/** A labelled build from scripts/build-scene.ts keeps its public output in dist/<label>/public; tests/tools/build.ts writes dist/standalone. */+const testRoot = label ? resolve(PACKAGE_ROOT, 'dist', label, 'test') : outputFor('test');+const publicRoot = label ? [resolve(PACKAGE_ROOT, 'dist', label, 'public'), outputFor('public', label)].find(p => existsSync(resolve(p, 'index.html'))) ?? resolve(PACKAGE_ROOT, 'dist', label, 'public') : outputFor('public');+if (!existsSync(resolve(testRoot, 'index.html'))) throw new Error(`No test build at ${testRoot}`);+const test = await serve(testRoot), publicBuild = run('x11') ? await serve(publicRoot) : null;+/** What was measured: the test build's code chunks and source (build.json, when the build wrote one) and the staged pack it carries. */+const measured = (() => {+ const built = existsSync(resolve(testRoot, 'build.json')) ? JSON.parse(readFileSync(resolve(testRoot, 'build.json'), 'utf8')) as { chunks: { name: string }[]; source?: unknown } : null;+ const pack = resolve(testRoot, 'assets/pack.json');+ return { label: label ?? null, root: testRoot.replace(/\\/g, '/'), chunks: built?.chunks.map(c => c.name).sort() ?? null, source: built?.source ?? null,+ release: JSON.parse(readFileSync(resolve(testRoot, 'assets/data/scene.json'), 'utf8')).release as string, packSha256: existsSync(pack) ? createHash('sha256').update(readFileSync(pack)).digest('hex') : null };+})();const chrome = await launchHeadless('gg-perf-local', WIDTH, HEIGHT);const outArg = process.argv.find(a => a.startsWith('--out=')), outDir = outArg ? outArg.slice('--out='.length) : 'evidence/perf';const out = (name: string) => resolve(PACKAGE_ROOT, outDir, name);@@ -44,6 +69,19 @@ async function open(url: string, messages: ConsoleRecord[]): Promise<Page> {const ready = (page: Page) => page.waitForFunction(() => { const s = (window as any).__kilnHarness?.snapshot(); if (s?.errors?.length) throw new Error(JSON.stringify(s.errors[0])); return (s?.readyCount ?? 0) > 0; }, { timeout: TIMEOUT, polling: 100 });const frames = (page: Page, n: number) => page.evaluate(count => (window as any).__kilnScene.waitFrames(count), n);const call = (page: Page, name: string, ...args: unknown[]) => page.evaluate((n, a) => (window as any).__kilnScene.invoke(n, ...a), name, args);+interface X02View { view: string; drawCalls: number | null; triangles: number | null }+interface X02Case { backend: string; tier: string; views: X02View[] }+/** X-02 against a baseline run (OD-8 / D-53): each view's draw calls and triangles within 2 percent, matched by backend, tier and view; the verdict is High's. */+function compareX02(baseline: X02Case[], current: X02Case[]) {+ const near = (value: number | null, base: number | null) => value !== null && base !== null && Math.abs(value - base) <= .02 * base;+ const rows = current.flatMap(c => {+ const b = baseline.find(x => x.backend === c.backend && x.tier === c.tier);+ return b ? c.views.flatMap(v => { const w = b.views.find(x => x.view === v.view); return w ? [{ backend: c.backend, tier: c.tier, view: v.view, drawCalls: [w.drawCalls, v.drawCalls], triangles: [w.triangles, v.triangles], within: near(v.drawCalls, w.drawCalls) && near(v.triangles, w.triangles) }] : []; }) : [];+ });+ const tally = (list: typeof rows) => ({ views: list.length, within: list.filter(r => r.within).length });+ const high = tally(rows.filter(r => r.tier === 'high'));+ return { rule: 'draw calls and triangles within 2 percent of the baseline at each view (OD-8 / D-53; the verdict is High, the other tiers are reported)', pass: high.views > 0 && high.within === high.views, high, all: tally(rows), rows };+}async function heap(client: CDPSession, collect: boolean) { if (collect) await client.send('HeapProfiler.collectGarbage'); return client.send('Runtime.getHeapUsage'); }/** renderer.info and the scene's own counters for the frame just rendered. */@@ -51,6 +89,8 @@ const counts = (page: Page) => page.evaluate(() => {const api = (window as any).__kilnScene, s = api.stats(), gg = api.invoke('ggStats'), t = api.invoke('trafficStats');return { drawCalls: s.render?.drawCalls ?? null, triangles: s.render?.triangles ?? null, geometries: s.memory?.geometries ?? null, textures: s.memory?.textures ?? null, pipelines: s.pipelines, programs: s.programs,mode: gg?.camera?.mode ?? null, terrainTiles: gg?.terrainTiles ?? null, farBridge: gg?.usingFarBridge ?? null,+ // webMeshes: meshes in the authored web model (before any merge); bridgeDraws: meshes the web and far views draw (null before the merge existed).+ webMeshes: gg?.bridge?.webMeshes ?? null, bridgeDraws: gg?.bridge?.draws ?? null,traffic: t ? { vehicles: t.vehicles, drawn: t.drawn, draws: t.draws, triangles: t.triangles, perLevel: t.perLevel, contactShadows: t.contactShadows } : null };});/** Counts once the view has settled: two samples 20 frames apart must agree (terrain and LOD selection follow the camera). */@@ -88,14 +128,22 @@ try {} finally { await page.close(); }}const unexpected = unexpectedMessages(messages);- writeJson(out('x02-counts.json'), { id: 'X-02', captured: new Date().toISOString(), note: 'Counts only (renderer.info for the frame just rendered, after two equal samples 20 frames apart); no timing. Golden Gate has no pilot, so these are the baseline.', window: { width: WIDTH, height: HEIGHT, deviceScaleFactor: 1 }, preset: 'day', time: TIME, unexpectedMessages: unexpected, cases });+ writeJson(out('x02-counts.json'), { id: 'X-02', captured: new Date().toISOString(), note: 'Counts only (renderer.info for the frame just rendered, after two equal samples 20 frames apart); no timing. Golden Gate has no pilot, so these are the baseline. The drive-chase view runs 90 frames of real time before the clock freezes, so where the car stops (drive.z) and the traffic around it vary between runs.', build: measured, window: { width: WIDTH, height: HEIGHT, deviceScaleFactor: 1 }, preset: 'day', time: TIME, unexpectedMessages: unexpected, cases });summary['X-02'] = { cases: cases.length, unexpectedMessages: unexpected.length };+ if (baselinePath) {+ const baseline = JSON.parse(readFileSync(resolve(baselinePath), 'utf8')) as { captured: string; build?: typeof measured; cases: X02Case[] }, check = compareX02(baseline.cases, cases as X02Case[]);+ writeJson(out('x02-check.json'), { id: 'X-02', checked: new Date().toISOString(), baseline: { path: resolve(baselinePath).replace(/\\/g, '/'), captured: baseline.captured, build: baseline.build ?? null }, build: measured, ...check });+ console.log(`X-02 against ${baselinePath}: High ${check.high.within}/${check.high.views} views within 2 percent (${check.pass ? 'pass' : 'FAIL'}); all tiers ${check.all.within}/${check.all.views}`);+ for (const r of check.rows.filter(x => !x.within && x.tier === 'high').slice(0, 20)) console.log(` outside: ${r.backend} ${r.tier} ${r.view} draws ${r.drawCalls.join(' -> ')} triangles ${r.triangles.join(' -> ')}`);+ summary['X-02 check'] = { pass: check.pass, high: check.high, all: check.all };+ if (!check.pass) process.exitCode = 1;+ }}if (run('x11')) {const staging = JSON.parse(readFileSync(resolve(PACKAGE_ROOT, `evidence/staging/${STAGED_RELEASE}.json`), 'utf8')), bundle = JSON.parse(readFileSync(resolve(PACKAGE_ROOT, 'evidence/build/bundle-public.json'), 'utf8'));const loads: unknown[] = [], messages: ConsoleRecord[] = [];- const cases = [{ build: 'public', tier: 'auto (high on this desktop)', url: `${publicBuild.url}/` },+ const cases = [{ build: 'public', tier: 'auto (high on this desktop)', url: `${publicBuild!.url}/` },...(['high', 'balanced', 'economy'] as const).map(tier => ({ build: 'test', tier, url: `${test.url}/?tier=${tier}` }))];for (const c of cases) {const page = await chrome.browser.newPage(); page.setDefaultTimeout(TIMEOUT); await page.setViewport({ width: WIDTH, height: HEIGHT, deviceScaleFactor: 1 });diff --git a/scenes/packages/golden-gate/tests/unit/bridge-draws.test.ts b/scenes/packages/golden-gate/tests/unit/bridge-draws.test.tsnew file mode 100644index 00000000..216eebe3--- /dev/null+++ b/scenes/packages/golden-gate/tests/unit/bridge-draws.test.ts@@ -0,0 +1,212 @@+// SPDX-License-Identifier: MIT+// Draw optimisation (docs/plans/2026-10-01-draw-optimization-cycle.md S4b, OD-18; tmp/drawcalls/understand/golden-gate.md+// sections 2-3): the bridge draws a render copy of each pack model, merged by material inside its south, north and span+// groups, with shadow depth stand-ins per tower, anchorage and span on High and far-approach stand-ins in the planar+// reflection. The pack's scene graphs are never changed (a second build from the same pack starts from the authored graph;+// its shared materials carry the joint-plate offset and the lamp level), the semantic web model keeps its node names for+// route contact and the colliders, and the merge keeps the same triangles, world bounds, materials and coplanar depth ties,+// with the material-level lamp and joint-plate edits still applied.+import { describe, expect, test } from 'bun:test';+import { Box3, BoxGeometry, FrontSide, Group, Mesh, MeshStandardMaterial, PlaneGeometry, Vector3 } from 'three/webgpu';+import type { BufferGeometry, Material, Object3D } from 'three/webgpu';+import type { GLTF } from 'three/addons/loaders/GLTFLoader.js';+import { BRIDGE, LAYERS } from '../../src/constants';+import { LAYOUT } from '../../src/data';+import { createBridge } from '../../src/world/bridge';+import type { BridgeOptions } from '../../src/world/bridge';+import { drawOptions } from '../../src/world/draw-options';+import { FEATURES } from '../../src/tiers';++const NAMES = ['Paint', 'Concrete', 'AnchorageConcrete', 'Asphalt', 'RoadMarkings', 'LampGlass', 'JointSteel', 'BeaconEmissive'] as const;+type Materials = Record<typeof NAMES[number], MeshStandardMaterial>;+/**+ * A bridge model in the runtime GLBs' layout (staged/g9/bridge): GoldenGateBridge holding the towers, the south fender and+ * the anchorages (translated parts) and the span parts (cables and the deck with the Roadway, joints, markings and lamps).+ * 21 meshes: south 7, north 6, span 8.+ */+function model(materials: Materials): GLTF {+ const scene = new Group(), bridge = new Group(); scene.name = 'Scene'; bridge.name = 'GoldenGateBridge'; scene.add(bridge);+ const node = (name: string, parent: Object3D, at: [number, number, number] = [0, 0, 0]) => { const g = new Group(); g.name = name; g.position.set(...at); parent.add(g); return g; };+ const mesh = (name: string, parent: Object3D, material: keyof Materials, at: [number, number, number], size: [number, number, number]) => {+ // One primitive per mesh, as in the GLBs: BoxGeometry's per-face groups would keep a part out of the merge.+ const g = new BoxGeometry(...size).translate(...at); g.clearGroups();+ const m = new Mesh(g, materials[material]); m.name = name; parent.add(m); return m;+ };+ for (const [side, z] of [['South', -640.08], ['North', 640.08]] as const) {+ const tower = node(`${side}Tower`, bridge, [0, 0, z]), leg = node(`${side}Tower_LegWest`, tower, [13.7, 0, 0]), pier = node(`${side}Tower_Pier`, tower);+ mesh(`${side}Tower_LegWest_Mesh_Shaft`, leg, 'Paint', [0, 110, 0], [3, 220, 5]); mesh(`${side}Tower_LegWest_Mesh_Cap`, leg, 'Paint', [0, 225, 0], [4, 4, 6]);+ mesh(`${side}Tower_Pier_Mesh_Pier`, pier, 'Concrete', [0, 5, 0], [40, 10, 20]); mesh(`${side}Tower_Mesh_Beacon`, tower, 'BeaconEmissive', [0, 230, 0], [1, 1, 1]);+ const anchorage = node(`${side}Anchorage`, bridge, [0, 0, side === 'South' ? -1008 : 1008]);+ mesh(`${side}Anchorage_Mesh_AnchorageHousing`, anchorage, 'AnchorageConcrete', [0, 20, 0], [40, 40, 60]); mesh(`${side}Anchorage_Mesh_HousingPilasters`, anchorage, 'AnchorageConcrete', [21, 20, 0], [2, 40, 60]);+ }+ mesh('SouthFender_Mesh_EllipticalWall', node('SouthFender', bridge, [0, 0, -640.08]), 'Concrete', [0, 3, 0], [60, 6, 40]);+ for (const side of ['West', 'East']) mesh(`MainCable${side}_Mesh_ContinuousCable`, node(`MainCable${side}`, bridge), 'Paint', [side === 'West' ? 13.7 : -13.7, 150, 0], [1, 1, 2700]);+ const deck = node('Deck', bridge);+ const road = new Mesh(new PlaneGeometry(2 * BRIDGE.roadHalfWidth + 4, 2 * BRIDGE.roadEndZ + 4).rotateX(-Math.PI / 2).translate(0, 62.55, 0), materials.Asphalt); road.name = 'Roadway'; deck.add(road);+ mesh('Deck_Mesh_ExpansionJoints', deck, 'JointSteel', [0, 62.6, 0], [20, .05, 1]);+ mesh('Deck_LaneMarkings_Mesh_Lines', node('Deck_LaneMarkings', deck), 'RoadMarkings', [0, 62.56, 0], [.1, .01, 2000]);+ const lamps = node('Deck_ArtDecoLampStandards', deck);+ mesh('Deck_ArtDecoLampStandards_Mesh_West', lamps, 'LampGlass', [12, 68, 0], [.5, .5, 2000]); mesh('Deck_ArtDecoLampStandards_Mesh_East', lamps, 'LampGlass', [-12, 68, 0], [.5, .5, 2000]);+ mesh('CurbsEast', deck, 'Concrete', [-10, 62.7, 0], [.3, .3, 2000]);+ return { scene } as unknown as GLTF;+}+function pack() {+ const materials = Object.fromEntries(NAMES.map(name => [name, new MeshStandardMaterial({ name, emissive: name === 'LampGlass' || name === 'BeaconEmissive' ? 0xffcc88 : 0, emissiveIntensity: 2 })])) as Materials;+ return { materials, web: model(materials), far: model(materials) };+}+const HIGH: BridgeOptions = { farSwitch: 5200, castShadow: true, merge: true, standInLayer: LAYERS.shadowStandIn, passLayers: { main: LAYERS.mainOnly, pass: LAYERS.reflectionOnly } };+const triangles = (g: BufferGeometry) => (g.index ? g.index.count : g.attributes.position!.count) / 3;+/** What a camera on layer `layer` draws under root: visible meshes on that layer, their triangles, materials and world bounds. */+function drawn(root: Object3D, layer = LAYERS.world, cast = false) {+ root.updateMatrixWorld(true);+ const out = { draws: 0, triangles: 0, materials: new Set<Material>(), bounds: new Box3(), meshes: [] as Mesh[] }, v = new Vector3();+ root.traverseVisible(node => {+ const m = node as Mesh; if (!m.isMesh || !m.layers.isEnabled(layer) || (cast && !m.castShadow)) return;+ out.draws++; out.triangles += triangles(m.geometry); out.materials.add(m.material as Material); out.meshes.push(m);+ const p = m.geometry.attributes.position!; for (let i = 0; i < p.count; i++) out.bounds.expandByPoint(v.fromBufferAttribute(p, i).applyMatrix4(m.matrixWorld));+ });+ return out;+}+/** Everything a build could change on a pack model: graph, flags, layers, transforms and shared resources. */+function snapshot(gltf: GLTF) {+ const rows: string[] = [`parent:${gltf.scene.parent?.name ?? null}`];+ gltf.scene.traverse(n => { const m = n as Mesh; rows.push([n.name, n.parent?.name, n.children.map(c => c.name).join('+'), n.visible, n.layers.mask, n.castShadow, n.receiveShadow, n.matrixAutoUpdate, n.position.toArray(), m.isMesh ? m.geometry.uuid : '', m.isMesh ? (m.material as Material).uuid : ''].join('|')); });+ return rows;+}+const near = new Vector3(300, 120, 900), distant = new Vector3(0, 100, 8000);++describe('bridge draws', () => {+ test('the merge draws south, north and span parts by material with the same triangles, bounds and materials', () => {+ const p = pack(), bridge = createBridge(p.web, p.far, { ...HIGH, standInLayer: undefined, passLayers: undefined });+ const source = drawn(bridge.web), web = drawn(bridge.views.web);+ // South: Paint (2), Concrete (pier and fender), AnchorageConcrete (2) merged, the beacon alone; north: Paint and+ // AnchorageConcrete merged, the pier and beacon alone; span: the cables and the lamps merged, four single parts.+ expect(source.draws).toBe(21); expect(web.draws).toBe(14); expect(bridge.stats.draws).toEqual({ web: 14, far: 14 });+ expect(bridge.stats.webMeshes).toBe(21); expect(bridge.stats.merged?.web).toMatchObject({ sourceMeshes: 14, mergedMeshes: 7 });+ expect(web.triangles).toBe(source.triangles); expect(web.materials).toEqual(source.materials);+ for (const k of ['min', 'max'] as const) expect(web.bounds[k].distanceTo(source.bounds[k])).toBeLessThan(1e-4);+ expect(web.meshes.filter(m => m.userData.kilnMerged).map(m => m.name).sort()).toEqual(['Merged south/AnchorageConcrete', 'Merged south/Concrete', 'Merged south/Paint', 'Merged north/AnchorageConcrete', 'Merged north/Paint', 'Merged span/LampGlass', 'Merged span/Paint'].sort());+ // Every merged mesh keeps the flags of its parts: High receives and casts (no stand-ins here).+ for (const m of web.meshes) expect([m.castShadow, m.receiveShadow, m.layers.mask]).toEqual([true, true, 1]);+ bridge.dispose();+ });++ test('the pack scene graphs are untouched after two builds, and the semantic web model keeps names for route contact and colliders', () => {+ const p = pack(), before = [snapshot(p.web), snapshot(p.far)], authored = NAMES.map(n => p.materials[n].emissiveIntensity);+ for (let i = 0; i < 2; i++) {+ const bridge = createBridge(p.web, p.far, HIGH);+ expect(bridge.web).not.toBe(p.web.scene); expect(bridge.web.parent).toBeNull();+ expect(bridge.web.getObjectByName('Roadway')).toBeDefined(); expect(bridge.web.getObjectByName('SouthTower_Pier_Mesh_Pier')?.visible).toBe(true);+ // Obstruction colliders come from the semantic model: towers, cables and lamp standards (no stand-ins or merged copies).+ expect(bridge.stats.colliders).toBe(1); expect(bridge.colliders.colliders[0]!.root).toBe(bridge.web); expect(bridge.colliders.colliders[0]!.geometry.attributes.position!.count / 3).toBe(drawn(bridge.web).meshes.filter(m => /^(SouthTower|NorthTower|MainCable|Deck_ArtDecoLampStandards)/.test(m.name)).reduce((n, m) => n + triangles(m.geometry), 0));+ bridge.setLamps(.5);+ bridge.dispose();+ expect([snapshot(p.web), snapshot(p.far)]).toEqual(before);+ }+ // Lamp levels scale the authored intensity on every build and return to it on dispose, also when a rebuild overlaps+ // the old bridge with its lamps off (the day preset).+ expect(NAMES.map(n => p.materials[n].emissiveIntensity)).toEqual(authored);+ const old = createBridge(p.web, p.far, HIGH); old.setLamps(0);+ const next = createBridge(p.web, p.far, HIGH); next.setLamps(.5); expect(p.materials.LampGlass.emissiveIntensity).toBe(1);+ old.dispose(); next.dispose();+ });++ test('lamp and joint-plate material edits apply to the merged meshes, the LOD switch toggles the views and dispose frees the merged geometry', () => {+ const p = pack(), bridge = createBridge(p.web, p.far, HIGH), lamp = p.materials.LampGlass, joint = p.materials.JointSteel;+ expect(joint.polygonOffset).toBe(true); expect(joint.polygonOffsetFactor).toBe(LAYOUT.bridge.jointPlates.polygonOffset.factor);+ const lamps = drawn(bridge.views.web).meshes.filter(m => m.material === lamp);+ expect(lamps.map(m => m.name)).toEqual(['Merged span/LampGlass']);+ bridge.setLamps(0); expect(lamp.emissiveIntensity).toBe(0); bridge.setLamps(.5); expect(lamp.emissiveIntensity).toBe(1); expect(p.materials.BeaconEmissive.emissiveIntensity).toBe(1);+ bridge.update(near); expect([bridge.usingFar, bridge.views.web.visible, bridge.views.far.visible]).toEqual([false, true, false]);+ bridge.update(distant); expect([bridge.usingFar, bridge.views.web.visible, bridge.views.far.visible]).toEqual([true, false, true]);+ expect(drawn(bridge.root).meshes.every(m => bridge.views.far.getObjectById(m.id) || bridge.approachMeshes.far.group.getObjectById(m.id))).toBe(true);+ const merged = [bridge.views.web, bridge.views.far].flatMap(v => drawn(v).meshes).filter(m => m.userData.kilnMerged);+ bridge.update(near); expect(bridge.views.web.visible).toBe(true);+ let freed = 0; for (const m of merged) m.geometry.addEventListener('dispose', () => freed++);+ bridge.dispose();+ expect(freed).toBe(merged.length); expect(bridge.root.parent).toBeNull();+ // Shared pack geometry is never disposed by the bridge.+ let shared = 0; p.web.scene.traverse(n => { const m = n as Mesh; if (m.isMesh) m.geometry.addEventListener('dispose', () => shared++); });+ createBridge(p.web, p.far, HIGH).dispose(); expect(shared).toBe(0);+ });++ test('the merge puts the curbs before the walks in their shared Concrete mesh, so the walks keep winning their coplanar depth ties', () => {+ // GoldenGateBridge's CurbsEast/West share Concrete with Deck_Mesh_EastWalk/WestWalk and their road-facing faces are coplanar+ // (x = +/-9.449). Unmerged, three drew the curbs first and the walks won the LessEqual ties; inside one merged draw later+ // triangles win, so the curbs' triangles must come first, whatever the scene order (wave-B review R1: a kerb stipple).+ const p = pack();+ for (const gltf of [p.web, p.far]) {+ const deck = gltf.scene.getObjectByName('Deck')!, curb = deck.getObjectByName('CurbsEast')!;+ const part = (name: string, x: number, size: [number, number, number]) => { const g = new BoxGeometry(...size).translate(x, 62.65, 0); g.clearGroups(); return Object.assign(new Mesh(g, p.materials.Concrete), { name }); };+ // As in the runtime GLB, the walks come before the curbs.+ deck.add(part('Deck_Mesh_EastWalk', -11.5, [2, .2, 2000]), part('Deck_Mesh_WestWalk', 11.5, [2, .2, 2000])); deck.remove(curb); deck.add(curb, part('CurbsWest', 10, [.3, .3, 2000]));+ }+ const bridge = createBridge(p.web, p.far, HIGH);+ for (const view of [bridge.views.web, bridge.views.far]) {+ const concrete = view.getObjectByName('Merged span/Concrete') as Mesh, g = concrete.geometry, x = g.attributes.position!, index = g.index!, kinds: string[] = [];+ for (let i = 0; i < index.count; i += 3) kinds.push(Math.abs(x.getX(index.getX(i)) + x.getX(index.getX(i + 1)) + x.getX(index.getX(i + 2))) / 3 < 10.3 ? 'curb' : 'walk');+ expect(kinds.filter(k => k === 'curb').length).toBe(24); expect(kinds.filter(k => k === 'walk').length).toBe(24);+ expect(kinds.lastIndexOf('curb')).toBeLessThan(kinds.indexOf('walk'));+ }+ // The order costs no draw: one Concrete mesh in the span, as without it.+ expect(bridge.stats.draws).toEqual({ web: 14, far: 14 });+ bridge.dispose();+ });++ test('the span\'s merged paint draws after the other opaque draws, as the deck\'s lower painted parts did when far out', () => {+ // The underdeck's top lies 0.45 m below the roadway; from 2 km the depth buffer cannot separate them, and unmerged three+ // drew the lower underdeck after the roadway (its centre is farther), so the paint won the ties. Merged, the span's paint+ // centre rises to the cables and would draw first (wave-B review R2 residual: arrival 256 px over 32 levels on WebGL2).+ const p = pack(), bridge = createBridge(p.web, p.far, HIGH), merged = [bridge.views.web, bridge.views.far].flatMap(v => { const out: Mesh[] = []; v.traverse(n => { if (n.userData.kilnMerged) out.push(n as Mesh); }); return out; });+ expect(merged.filter(m => m.renderOrder !== 0).map(m => [m.name, m.renderOrder])).toEqual([['Merged span/Paint', 1], ['Merged span/Paint', 1]]);+ bridge.dispose();+ const off = createBridge(p.web, p.far, { ...HIGH, merge: false }); let ordered = 0; off.root.traverse(n => { if ((n as Mesh).renderOrder) ordered++; }); expect(ordered).toBe(0); off.dispose();+ });++ test('bridgeMerge off draws every part as authored', () => {+ const p = pack(), bridge = createBridge(p.web, p.far, { ...HIGH, merge: false, standInLayer: undefined, passLayers: undefined });+ expect(drawn(bridge.views.web).draws).toBe(21); expect(bridge.stats.draws).toEqual({ web: 21, far: 21 }); expect(bridge.stats.merged).toBeNull();+ bridge.dispose();+ });++ test('shadow stand-ins: one front-sided depth proxy per tower, anchorage, fender group and span plus one for the near approaches, on the stand-in layer only', () => {+ const p = pack(), bridge = createBridge(p.web, p.far, HIGH), plain = createBridge(pack().web, pack().far, { ...HIGH, standInLayer: undefined, merge: false, passLayers: undefined });+ const casters = drawn(plain.root, LAYERS.world, true), proxies = drawn(bridge.root, LAYERS.shadowStandIn, true);+ expect(proxies.meshes.map(m => m.name).sort()).toEqual(['Shadow stand-in NorthAnchorage', 'Shadow stand-in NorthTower', 'Shadow stand-in SouthAnchorage', 'Shadow stand-in SouthTower', 'Shadow stand-in approaches-near', 'Shadow stand-in south', 'Shadow stand-in span'].sort());+ expect(bridge.stats.shadowProxies).toMatchObject({ proxies: 7, sourceMeshes: casters.draws });+ // The same depth: every caster's triangles and world bounds, now in 7 draws.+ expect(proxies.triangles).toBe(casters.triangles);+ for (const k of ['min', 'max'] as const) expect(proxies.bounds[k].distanceTo(casters.bounds[k])).toBeLessThan(1e-4);+ for (const m of proxies.meshes) { expect(m.layers.mask).toBe(1 << LAYERS.shadowStandIn); expect((m.material as Material).side).toBe(FrontSide); }+ // Visible sources and the merged meshes no longer cast; they still receive.+ expect(drawn(bridge.root, LAYERS.world, true).draws).toBe(0); expect(drawn(bridge.root, LAYERS.mainOnly, true).draws).toBe(0);+ expect(drawn(bridge.views.web).meshes.every(m => m.receiveShadow && !m.castShadow)).toBe(true);+ // Merge after stand-ins: the main pass still draws 14, and no proxy was merged.+ expect(drawn(bridge.views.web).draws).toBe(14);+ bridge.dispose(); plain.dispose();+ });++ test('reflection stand-ins: the near approaches draw only for main cameras, a far-approach clone only in the reflection, switching with the near representation', () => {+ const p = pack(), bridge = createBridge(p.web, p.far, HIGH), { near: n, far: f } = bridge.approachMeshes;+ const main = drawn(n.group, LAYERS.mainOnly), reflected = drawn(n.group, LAYERS.reflectionOnly);+ expect(drawn(n.group, LAYERS.world).draws).toBe(0); expect(main.draws).toBe(n.draws);+ expect(reflected.draws).toBe(f.draws); expect(bridge.stats.reflectionProxies).toBe(f.draws);+ const farGeometries = new Set<BufferGeometry>(); f.group.traverse(o => { if ((o as Mesh).isMesh) farGeometries.add((o as Mesh).geometry); });+ for (const m of reflected.meshes) { expect(farGeometries.has(m.geometry)).toBe(true); expect([m.castShadow, m.layers.mask]).toEqual([false, 1 << LAYERS.reflectionOnly]); }+ // Vegetation joins the near group after the bridge is built and stays reflected (layer 0).+ const vegetation = new Mesh(new BoxGeometry(), new MeshStandardMaterial()); n.group.add(vegetation); expect(vegetation.layers.mask).toBe(1);+ bridge.update(distant); expect(drawn(bridge.root, LAYERS.reflectionOnly).draws).toBe(0); expect(drawn(f.group).draws).toBe(f.draws);+ bridge.dispose(); expect(drawn(n.group, LAYERS.reflectionOnly).draws).toBe(0);+ });+});++describe('draw options', () => {+ test('High takes every look-neutral option and no cached shadow; Low and Medium only the merge; overrides switch each off', () => {+ expect(drawOptions(FEATURES.high, {})).toEqual({ merge: true, once: true, depth: true, reflection: true, cache: false });+ for (const level of ['medium', 'low'] as const) expect(drawOptions(FEATURES[level], {})).toEqual({ merge: true, once: false, depth: false, reflection: false, cache: false });+ expect(drawOptions(FEATURES.high, { merge: false, once: false, depth: false, reflection: false })).toEqual({ merge: false, once: false, depth: false, reflection: false, cache: false });+ // The cached sun shadow replaces the once-per-frame render (its maps render once per frame by construction).+ expect(drawOptions(FEATURES.high, { cache: true })).toMatchObject({ once: false, cache: true });+ expect(drawOptions(FEATURES.low, { cache: true, once: true, depth: true, reflection: true })).toEqual({ merge: true, once: false, depth: false, reflection: false, cache: false });+ });+});diff --git a/scenes/packages/golden-gate/tests/unit/tiers.test.ts b/scenes/packages/golden-gate/tests/unit/tiers.test.tsindex ea4b6b52..10243a56 100644--- a/scenes/packages/golden-gate/tests/unit/tiers.test.ts+++ b/scenes/packages/golden-gate/tests/unit/tiers.test.ts@@ -93,6 +93,17 @@ describe('tier selection through the kit', () => {expect(differ(k => k.shadows.enabled)).toBe(true); // one cascade at High, contact shadows elsewhereexpect(differ(k => k.pixelRatioCap)).toBe(true); // pixel ratio});+ test('OD-10: MSAA discard only where no viewport depth copy splits the main pass, phones included', () => {+ // Depth contact (water) and fog banks read viewportDepthTexture, which copies the 4x depth mid-pass.+ for (const probe of [rtx3070, s24plus, tabS9fe]) for (const tier of goldenGateTiers.order) {+ const k = select(probe, tier).knobs;+ expect(k.multisample).toEqual({ discard: !k.gg.water.depthContact && k.gg.fogBanks === 0 });+ }+ const discard = (probe: DeviceProbe, tier: TierName) => select(probe, tier).knobs.multisample?.discard;+ expect(goldenGateTiers.order.map(tier => discard(rtx3070, tier))).toEqual([true, true, false, false]);+ expect(discard(s24plus, 'high')).toBe(false); // high on a phone is Medium, which keeps depth contact+ expect(discard(tabS9fe, 'minimal')).toBe(true);+ });test('Low fades its per-pixel waves with view distance; High and Medium keep the accepted water', () => {// SCENE-REVIEW-1 item 2: the Low waves banded across the bay at mid distance. The fade adds no pass,// texture or wave; High and Medium (accepted) carry no fade.diff --git a/scenes/packages/scene-kit/README.md b/scenes/packages/scene-kit/README.mdindex b0d4238b..8a0c3460 100644--- a/scenes/packages/scene-kit/README.md+++ b/scenes/packages/scene-kit/README.md@@ -158,6 +158,8 @@ Under D-05, automatic classification, Save-Data adjustments, persisted learningThe default ladder first reduces vegetation, then LOD distance, streaming radius and instance density. Scenes may supply a custom ladder containing their permitted live levels. Shadow configuration, far/fog distances and water material variants remain structural.+`multisample.discard` is structural too (OD-10). The default is store. Set it only for a WebGPU tier whose main pass is never split by a framebuffer copy (viewport depth or texture nodes, transmission). The 4x canvas attachments are then resolved and discarded, and three creates them transient. Anything that would load or store them trips the policy back to store for the mount; in test and dev builds a trip is a fatal `SceneError` with code `msaa-discard`.+## Modules and build boundaries| Entry | Main APIs |@@ -180,3 +182,9 @@ Browser imports resolve to `src/index.browser.ts`; Node/build imports also exposUnder DECISIONS C-03, React DOM 19.3.0 retains one shared nonpassive document `selectionchange` listener for the page lifetime. Scene teardown removes every scene-owned listener; the contract suite verifies that this single React infrastructure listener, identified by its document marker, never grows across mounts. Do not remove it or intercept document methods. The pinned source locations and cold-mount evidence are recorded in `evidence/m1/stop-rule-03.md` and REPORT's website handoff.Farm keeps its ACES Filmic appearance. Golden Gate and Foundry Floor use Neutral under D-18, with AgX reserved for the documented fallback. Consult the M0 tone-map evidence in PROGRESS before changing a scene’s authored look. Presets blend exposure, linear color components and other numbers while keeping tone mapping and fog kind fixed.++`mergeRigidByMaterial(root, { isAnchor })` (in `instancing`) merges rigid parts by material inside each anchor: the nearest `isAnchor` ancestor, with the root always counting. Anchors keep their identity, transform and children, and the merged meshes become their children with identity transforms. Sources stay in the graph, hidden, so name lookups, mixers and colliders keep working, and `restore()` undoes the merge. These are never merged: transparent, multi-material, skinned, morphed, instanced, hidden and extras-carrying meshes, and parts that carry tangents and are mirrored against their anchor. An optional `cache` with `cacheKey` lets identical placements share merged geometry. `bakeRigidGeometry(meshes, anchor, { attributes: 'position' })` makes the same anchor-frame bake for material-free stand-ins.++`shadows` holds the opt-in sun-shadow features. `cachedSunShadow({ light, liveMapSize?, settleFrames? })` splits the sun map into a static map, rendered only when armed, and a live map for casters that moved, sampled as `min` through `light.shadow.shadowNode`. Install it before receivers build and keep `castShadow` on. `track(root, { movable })` puts casters on kit layer 30 (`ShadowLayers`; scenes keep 0-29), and casters under `movable` nodes move to layer 31 while they change. Call `update()` every frame at `SystemOrder.shadows` (800), `prime()` when a warm pass starts drawing, and `invalidate(reason)` for static changes the watch cannot see. `shadowOncePerFrame(light)` lets a second camera, such as a planar reflector, reuse the frame's map. `smallCasterThreshold(root, light, { minTexels: 2 })` switches off casters below two shadow texels by the count probe's measure, and `restore()` brings them back. The three r186 behaviour these rely on is pinned in `tests/shadows/shadow-contract.test.ts`.++`shadowStandIns(root, { layer, isAnchor, chunk?, texel?, minCasterTexels? })` bakes eligible casters into one position-only depth proxy per anchor, shadow side and optional x/z cell, with an optional triangle cap. Each proxy is a child of its anchor, so it moves and hides with it. It sits on `layer` only, never on layer 0, so the shadow camera must enable that layer. Its sources stop casting. Small parts can be dropped first, and `stats.skipped` counts each excluded mesh by reason. Build stand-ins after batching. Each proxy copies its anchor's `matrixWorldAutoUpdate`, so a frozen owner stays frozen. For other passes, such as a planar reflection, `mainOnly(roots, layer)` moves drawables off layer 0, and `passStandIn(source, { layer })` adds a coloured clone that shares geometry and materials. `passCameraLayers(camera, { main, pass }, role)` sets just those two bits on each camera. Collision skips both kinds of stand-in.diff --git a/scenes/packages/scene-kit/package.json b/scenes/packages/scene-kit/package.jsonindex 8d2e214c..bf33a989 100644--- a/scenes/packages/scene-kit/package.json+++ b/scenes/packages/scene-kit/package.json@@ -17,6 +17,7 @@"./input": "./src/input/index.tsx","./camera": "./src/camera/index.tsx","./collision": "./src/collision/index.ts",+ "./shadows": "./src/shadows/index.ts","./ui": "./src/ui/index.tsx","./testing": "./src/testing/index.ts","./testing/node": "./src/testing/node.ts",diff --git a/scenes/packages/scene-kit/src/collision/index.ts b/scenes/packages/scene-kit/src/collision/index.tsindex cae9977d..bd13ab0d 100644--- a/scenes/packages/scene-kit/src/collision/index.ts+++ b/scenes/packages/scene-kit/src/collision/index.ts@@ -49,7 +49,9 @@ export function createCollisionWorld(): CollisionWorld {const meshes: Mesh[] = []; let count = 0;root.traverse(node => {const mesh = node as Mesh;- if (!mesh.isMesh || !mesh.geometry?.getAttribute('position') || (o.filter && !o.filter(mesh))) return;+ // Shadow and pass stand-ins (src/shadows) duplicate geometry for other passes, and a rigid merge (src/instancing) copies+ // sources it keeps hidden in the graph, which this traversal already reads; none of the copies is solid.+ if (!mesh.isMesh || mesh.userData.kilnShadowStandIn || mesh.userData.kilnPassStandIn || mesh.userData.kilnMerged || !mesh.geometry?.getAttribute('position') || (o.filter && !o.filter(mesh))) return;meshes.push(mesh); count += mesh.geometry.index?.count ?? mesh.geometry.getAttribute('position').count;});if (!count) return null;diff --git a/scenes/packages/scene-kit/src/contract/core.ts b/scenes/packages/scene-kit/src/contract/core.tsindex ac3c78e3..0147460c 100644--- a/scenes/packages/scene-kit/src/contract/core.ts+++ b/scenes/packages/scene-kit/src/contract/core.ts@@ -1,4 +1,4 @@-export type SceneErrorCode = 'no-container' | 'renderer-init' | 'asset-fetch' | 'asset-hash' | 'asset-parse' | 'pack-invalid' | 'three-version' | 'context-lost' | 'runtime';+export type SceneErrorCode = 'no-container' | 'renderer-init' | 'asset-fetch' | 'asset-hash' | 'asset-parse' | 'pack-invalid' | 'three-version' | 'context-lost' | 'msaa-discard' | 'runtime';export class SceneError extends Error {readonly code: SceneErrorCode; override readonly cause?: unknown;constructor(code: SceneErrorCode, message: string, cause?: unknown) { super(message); this.name = 'SceneError'; this.code = code; this.cause = cause; }diff --git a/scenes/packages/scene-kit/src/contract/index.tsx b/scenes/packages/scene-kit/src/contract/index.tsxindex 7e7ea7d9..5f2fde29 100644--- a/scenes/packages/scene-kit/src/contract/index.tsx+++ b/scenes/packages/scene-kit/src/contract/index.tsx@@ -13,11 +13,12 @@ import { prepareSceneData } from './prepare-data';import type { SceneDefinition, SceneHandle, SceneProps } from './types';import { createSceneClock, createSystemLoop, DisposeRegistry, SceneSystemLoop, usePauseWhenHidden, useReducedMotion } from '../lifecycle';import { configureRenderer, createGlFactory, releaseRendererLook } from '../renderer';+import { installMsaaStorePolicy, resolveMsaaDiscard } from '../renderer/msaa-store';import { createQualityController, probeDevice } from '../quality';import { createPackReader, disposeLoadedModels, loadPack } from '../assets';import { createInputApi, InputProvider } from '../input';import { createFadeController, createHudStore, FadeOverlay, HudLayer, SceneStyles } from '../ui';-import { applyProbeOverride, installTestHooks, KIT_DEV_PARAMS, readDevParams } from '../testing';+import { applyProbeOverride, installTestHooks, KIT_DEV_PARAMS, readDevParams, registerTestHooks } from '../testing';export * from './core';export * from './types';@@ -230,15 +231,30 @@ export function SceneRoot({ options, definition, children }: { options: SceneProif(rt.disposed)return;const device = (renderer.backend as unknown as { device?: { lost: Promise<{ reason: string }> } }).device;deviceLoss = device?.lost.then(() => { deviceLost = true; if (!rt.disposed) rt.fatal(new SceneError('context-lost', 'Graphics device lost')); }).catch(error => { if (!rt.disposed) rt.fatal(error); });+ // OD-10: the MSAA store policy is decided once per mount from the structural tier, before the first frame.+ let forced: 'store' | 'discard' | undefined;+ if (import.meta.env.KILN_TEST || import.meta.env.KILN_DEV) forced = readDevParams({ msaa: { kind: 'enum', values: ['store', 'discard'] } } as const).msaa as typeof forced;+ const discard = resolveMsaaDiscard(tier, forced);+ const msaa = installMsaaStorePolicy(renderer, _roots.get(canvas)!.store.getState().scene, { discard, onTrip: reason => {+ // A trip can fire inside three's pass, so the failure waits for it; public builds recover silently with store.+ if (import.meta.env.KILN_TEST || import.meta.env.KILN_DEV) queueMicrotask(() => rt.fatal(new SceneError('msaa-discard', `MSAA discard tripped: ${reason}`)));+ } });+ // Its remover is in place from here, and a failing remove cannot skip the rest of the release.+ const removeMsaa = () => { try { msaa.remove(); } catch (error) { registry.errors.push(error); } };+ restoreRender = removeMsaa;+ if (import.meta.env.KILN_TEST || import.meta.env.KILN_DEV) registerTestHooks({ msaaPolicy: () => ({ discard, active: msaa.active, tripped: msaa.tripped }) }, rt);// Catch only this renderer's synchronous submission errors; no global handler.const render = renderer.render.bind(renderer);- restoreRender = () => { renderer.render=render; };+ restoreRender = () => { renderer.render=render; removeMsaa(); };renderer.render = ((...args: Parameters<WebGPURenderer['render']>) => {if (rt.disposed || rt.failed || rt.paused) return;let began = 0;if ((import.meta.env.KILN_TEST || import.meta.env.KILN_DEV) && rt.data.get('measure')) began = performance.now();- try { return render(...args); } catch (error) { rt.fatal(error); }- finally { if ((import.meta.env.KILN_TEST || import.meta.env.KILN_DEV) && began) (rt.data.get('cpuRecorder') as {push(ms:number):void} | undefined)?.push(performance.now()-began); }+ try { msaa.beforeRender(args[0]); return render(...args); } catch (error) { rt.fatal(error); }+ finally {+ try { msaa.afterRender(); } catch (error) { rt.fatal(error); }+ if ((import.meta.env.KILN_TEST || import.meta.env.KILN_DEV) && began) (rt.data.get('cpuRecorder') as {push(ms:number):void} | undefined)?.push(performance.now()-began);+ }}) as WebGPURenderer['render'];await packTask;if (rt.disposed) return;diff --git a/scenes/packages/scene-kit/src/index.browser.ts b/scenes/packages/scene-kit/src/index.browser.tsindex 101d8895..5791af3d 100644--- a/scenes/packages/scene-kit/src/index.browser.ts+++ b/scenes/packages/scene-kit/src/index.browser.ts@@ -8,5 +8,6 @@ export * from './instancing';export * from './input';export * from './camera';export * from './collision';+export * from './shadows';export * from './ui';export * from './testing';diff --git a/scenes/packages/scene-kit/src/instancing/index.tsx b/scenes/packages/scene-kit/src/instancing/index.tsxindex 2b9bb96e..559e3a08 100644--- a/scenes/packages/scene-kit/src/instancing/index.tsx+++ b/scenes/packages/scene-kit/src/instancing/index.tsx@@ -10,6 +10,7 @@ import type { CellStreamerOptions, Zone } from './streaming';import type { Object3D, Vector3 } from 'three/webgpu';import { useRuntime } from '../internal/runtime';export * from './core';export * from './instances';export * from './streaming';+export * from './rigid-merge';function assignRef<T>(ref:Ref<T>|undefined,value:T|null){if(typeof ref==='function')ref(value);else if(ref)ref.current=value;}export function InstancedGroup(p:{set:InstanceSet;drawDistance?:number;handleRef?:Ref<InstanceHandle>;maxCellsPerFrame?:number}):JSX.Element{const quality=useQuality(),built=useBuilt(()=>{const value=buildInstanceSet(p.set);if(import.meta.env.KILN_DEV){const offenders=assertInstancingSafe(value.root);if(offenders.length){value.dispose();throw new Error(`Unsafe instanced geometry: ${offenders.join(', ')}`);}}return value;},value=>value.dispose(),[p.set]);diff --git a/scenes/packages/scene-kit/src/instancing/rigid-merge.ts b/scenes/packages/scene-kit/src/instancing/rigid-merge.tsnew file mode 100644index 00000000..4201df1b--- /dev/null+++ b/scenes/packages/scene-kit/src/instancing/rigid-merge.ts@@ -0,0 +1,79 @@+import { BufferAttribute, BufferGeometry, InterleavedBuffer, InterleavedBufferAttribute, Matrix3, Matrix4, Mesh, Vector3 } from 'three/webgpu';+import type { Material, Object3D } from 'three/webgpu';+export interface RigidMergeOptions {+ isAnchor(n:Object3D):boolean;keepMesh?(m:Mesh):boolean;cache?:Map<string,BufferGeometry>;cacheKey?(anchor:Object3D):string|undefined;minGroup?:number;+ /**+ * Merged vertex layout. 'canonical' (default): one Float32 attribute each, so parts of any layout share a pipeline. 'source':+ * the first part's interleaved Float32 buffers keep their stride and offsets, so the merged mesh shares three r186's geometry+ * pipeline key (RenderObject.getGeometryCacheKey) with unmerged meshes of that layout; other attributes stay canonical.+ */+ layout?:'canonical'|'source';+ /** Parts with a lower value come first in their merged mesh (ties keep scene order): one draw resolves coplanar depth ties by index order. */+ order?(m:Mesh):number;+}+export interface RigidMerge {merged:Mesh[];sources:Mesh[];stats:{sourceMeshes:number;mergedMeshes:number;keptMeshes:number;groups:number;triangles:number};restore():void}+interface Part {m:Mesh;r:Matrix4}+const LINEAR=[1,0,0,0,0,1,0,0,0,0,1,0],is=(x:object,k:string)=>!!(x as Record<string,unknown>)[k];+function local(n:Object3D,out:Matrix4):Matrix4{if(!n.matrixAutoUpdate)return out.copy(n.matrix);out.compose(n.position,n.quaternion,n.scale);const p=n.pivot,e=out.elements;if(p){e[12]+=p.x-e[0]*p.x-e[4]*p.y-e[8]*p.z;e[13]+=p.y-e[1]*p.x-e[5]*p.y-e[9]*p.z;e[14]+=p.z-e[2]*p.x-e[6]*p.y-e[10]*p.z;}return out;}+/** Local matrices from the mesh up to, not including, the anchor: pose-independent. */+function relative(m:Object3D,anchor:Object3D):Matrix4{const out=new Matrix4(),l=new Matrix4();for(let n:Object3D|null=m;n!==anchor;n=n.parent){if(!n)throw new Error(`${m.name} is not under ${anchor.name}`);out.premultiply(local(n,l));}return out;}+/**+ * Concatenates parts into one indexed Float32 geometry in the anchor frame, reading through the attribute accessors (interleaved,+ * normalised and quantised inputs). A pure translation copies normals and tangents bit for bit and only offsets positions; other+ * matrices transform positions, normals (normal matrix) and tangent xyz (w kept) and reverse the winding when mirrored.+ */+function build(parts:Part[],names:string[],mirror=false):BufferGeometry{+ const first=parts[0]!.m.geometry,sizes=names.map(n=>first.getAttribute(n).itemSize);let verts=0,indices=0;+ for(const{m}of parts){const g=m.geometry,c=g.attributes.position!.count;verts+=c;indices+=g.index?g.index.count:c;}+ const arrays=sizes.map(s=>new Float32Array(verts*s)),index=verts>65535?new Uint32Array(indices):new Uint16Array(indices),v=new Vector3(),nm=new Matrix3(),lin=new Matrix3();let v0=0,i0=0;+ for(const{m,r}of parts){+ const g=m.geometry,count=g.attributes.position!.count,e=r.elements,shift=LINEAR.every((x,i)=>e[i]===x),flip=r.determinant()<0,src=g.index,n=src?src.count:count;+ if(!shift){nm.getNormalMatrix(r);lin.setFromMatrix4(r);}+ names.forEach((name,j)=>{+ const a=g.getAttribute(name),s=sizes[j]!,o=arrays[j]!;if(a?.itemSize!==s)throw new Error(`${m.name}: attribute ${name} differs`);+ for(let k=0;k<count;k++)for(let c=0;c<s;c++)o[(v0+k)*s+c]=a.getComponent(k,c);+ if(name==='position'){if(!shift)for(let k=v0;k<v0+count;k++)v.fromArray(o,k*3).applyMatrix4(r).toArray(o,k*3);else for(let c=0;c<3;c++)if(e[12+c])for(let k=v0;k<v0+count;k++)o[k*3+c]+=e[12+c]!;}+ else if(!shift&&(name==='normal'||name==='tangent'))for(let k=v0;k<v0+count;k++)v.fromArray(o,k*s).applyMatrix3(name==='normal'?nm:lin).normalize().toArray(o,k*s);+ });+ for(let k=0;k<n;k+=3){const a=src?src.getX(k):k,b=src?src.getX(k+1):k+1,c=src?src.getX(k+2):k+2;index[i0+k]=v0+a;index[i0+k+1]=v0+(flip?c:b);index[i0+k+2]=v0+(flip?b:c);}+ v0+=count;i0+=n;+ }+ const out=new BufferGeometry(),buffers=new Map<InterleavedBuffer,InterleavedBuffer>();+ names.forEach((n,j)=>{+ const a=first.getAttribute(n) as InterleavedBufferAttribute,s=sizes[j]!,o=arrays[j]!;+ if(!(mirror&&a.isInterleavedBufferAttribute&&a.data.array instanceof Float32Array&&!a.normalized)){out.setAttribute(n,new BufferAttribute(o,s));return;}+ let ib=buffers.get(a.data);if(!ib)buffers.set(a.data,ib=new InterleavedBuffer(new Float32Array(verts*a.data.stride),a.data.stride));+ const d=ib.array as Float32Array,st=ib.stride;for(let k=0;k<verts;k++)for(let c=0;c<s;c++)d[k*st+a.offset+c]=o[k*s+c]!;+ out.setAttribute(n,new InterleavedBufferAttribute(ib,s,a.offset,false));+ });+ out.setIndex(new BufferAttribute(index,1));out.computeBoundingBox();out.computeBoundingSphere();return out;+}+/** One geometry for meshes baked into the anchor frame; `position` alone serves material-free stand-ins. The caller owns it. */+export function bakeRigidGeometry(meshes:Mesh[],anchor:Object3D,o:{attributes:'all'|'position'}):BufferGeometry{if(!meshes.length)throw new Error('No meshes to bake');return build(meshes.map(m=>({m,r:relative(m,anchor)})),o.attributes==='position'?['position']:Object.keys(meshes[0]!.geometry.attributes));}+/**+ * Merges rigid parts by material inside each anchor: a mesh belongs to its nearest isAnchor ancestor (the root always counts) and+ * merges with parts of the same anchor, material, attribute layout, shadow flags, render order, layers and culling. Anchors keep+ * their identity, transform and children; merged meshes are their children with identity transforms; sources stay in the graph,+ * hidden. Never merged: transparent or transmissive, multi-material or grouped, skinned, morphed or instanced meshes, meshes with+ * children, anchors, meshes with userData beyond name, a partial drawRange, hidden meshes (directly or below their anchor),+ * keepMesh, and tangent-bearing parts mirrored against their anchor (three r186 builds the bitangent with no determinant term).+ * Merged meshes copy their anchor's matrix flags, so a merge after freezeTransforms keeps a frozen owner frozen.+ */+export function mergeRigidByMaterial(root:Object3D,o:RigidMergeOptions):RigidMerge{+ const min=o.minGroup??2,buckets=new Map<string,{anchor:Object3D;key:string;parts:Part[]}>();let all=0;+ const solo=(m:Mesh)=>{const g=m.geometry,mat=m.material as Material&{transmission?:number};return Array.isArray(mat)||g.groups.length>0||mat.transparent||(mat.transmission??0)>0||['isSkinnedMesh','isInstancedMesh','isBatchedMesh'].some(k=>is(m,k))||is(g,'isInstancedBufferGeometry')||Object.keys(g.morphAttributes).length>0||m.children.length>0||Object.keys(m.userData).some(k=>k!=='name')||g.drawRange.start!==0||g.drawRange.count!==Infinity||!g.attributes.position||!!o.keepMesh?.(m);};+ const visit=(node:Object3D,anchor:Object3D,hidden:boolean)=>{for(const c of node.children){const own=o.isAnchor(c),m=c as Mesh;+ if(m.isMesh){all++;if(!own&&!hidden&&m.visible&&!solo(m)){const r=relative(m,anchor),g=m.geometry;if(!(r.determinant()<0&&g.attributes.tangent)){+ const sig=Object.keys(g.attributes).sort().map(n=>`${n}:${g.attributes[n]!.itemSize}:${g.attributes[n]!.normalized}`).join(),key=[(m.material as Material).uuid,sig,m.castShadow,m.receiveShadow,m.renderOrder,m.layers.mask,m.frustumCulled].join('|'),id=anchor.id+'|'+key;+ let b=buckets.get(id);if(!b)buckets.set(id,b={anchor,key,parts:[]});b.parts.push({m,r});}}}+ visit(c,own?c:anchor,!own&&(hidden||!c.visible));}};+ visit(root,root,false);+ const owned:BufferGeometry[]=[],plan=[...buckets.values()].filter(b=>b.parts.length>=min).map(b=>{+ if(o.order){const k=new Map(b.parts.map(p=>[p,o.order!(p.m)]));b.parts.sort((x,y)=>k.get(x)!-k.get(y)!);}+ const name=o.cache&&o.cacheKey?.(b.anchor),k=name===undefined?undefined:name+'|'+b.key+(o.layout==='source'?'|source':''),verts=b.parts.reduce((n,p)=>n+p.m.geometry.attributes.position!.count,0);let g=k===undefined?undefined:o.cache!.get(k);+ if(g){if(g.attributes.position!.count!==verts)throw new Error(`Cached merge ${k} does not fit ${b.anchor.name}`);}else{g=build(b.parts,Object.keys(b.parts[0]!.m.geometry.attributes),o.layout==='source');if(k===undefined)owned.push(g);else o.cache!.set(k,g);}+ return{b,g};});+ const merged:Mesh[]=[],sources:Mesh[]=[];let triangles=0,restored=false;+ for(const{b,g}of plan){const f=b.parts[0]!.m,mat=f.material as Material,m=new Mesh(g,mat);m.name=`Merged ${b.anchor.name}/${mat.name}`;m.castShadow=f.castShadow;m.receiveShadow=f.receiveShadow;m.renderOrder=f.renderOrder;m.layers.mask=f.layers.mask;m.frustumCulled=f.frustumCulled;m.userData.kilnMerged=true;m.matrixAutoUpdate=b.anchor.matrixAutoUpdate;m.matrixWorldAutoUpdate=b.anchor.matrixWorldAutoUpdate;b.anchor.add(m);m.matrixWorld.copy(b.anchor.matrixWorld);merged.push(m);triangles+=g.index!.count/3;for(const p of b.parts){p.m.visible=false;sources.push(p.m);}}+ return{merged,sources,stats:{sourceMeshes:sources.length,mergedMeshes:merged.length,keptMeshes:all-sources.length,groups:buckets.size,triangles},restore(){if(restored)return;restored=true;for(const s of sources)s.visible=true;for(const m of merged)m.removeFromParent();for(const g of owned)g.dispose();}};+}diff --git a/scenes/packages/scene-kit/src/lifecycle/core.ts b/scenes/packages/scene-kit/src/lifecycle/core.tsindex 797761f6..1c5100df 100644--- a/scenes/packages/scene-kit/src/lifecycle/core.ts+++ b/scenes/packages/scene-kit/src/lifecycle/core.ts@@ -28,7 +28,7 @@ export function disposeObject3D(root: Object3D, opts: { textures?: boolean; skip});}export interface SceneClock { time: number; ambient: number; delta: number; timeScale: number; readonly frame: number }-export const SystemOrder = { input: 100, path: 200, herd: 300, mixers: 400, sim: 500, frameGraph: 600, camera: 700, governor: 900 } as const;+export const SystemOrder = { input: 100, path: 200, herd: 300, mixers: 400, sim: 500, frameGraph: 600, camera: 700, shadows: 800, governor: 900 } as const;export function createSceneClock(): SceneClock { return { time: 0, ambient: 0, delta: 0, timeScale: 1, frame: 0 }; }export function advanceSceneClock(clock: SceneClock, dt: number, flags: { paused: boolean; reduced: boolean }): void {clock.delta = flags.paused ? 0 : Math.max(0, Math.min(.1, dt)) * clock.timeScale;diff --git a/scenes/packages/scene-kit/src/quality/core.ts b/scenes/packages/scene-kit/src/quality/core.tsindex 7f030a0a..aecbb993 100644--- a/scenes/packages/scene-kit/src/quality/core.ts+++ b/scenes/packages/scene-kit/src/quality/core.ts@@ -11,6 +11,8 @@ export interface TierKnobs {drawDistance: { far: number; fogNear: number; fogFar: number; lodBias: number; streamRadiusScale: number; zoneHops: number };effects: { water: 'off' | 'simple' | 'full'; wind: boolean; ambientAnimation: boolean };ladder?: LadderLevel[];+ /** OD-10: discard the canvas pass's 4x attachments after resolve. Only for a tier whose main pass is never split by a framebuffer copy (viewport depth or texture nodes, transmission). Default store. */+ multisample?: { discard: boolean };}export interface DeviceClass { form: 'desktop' | 'tablet' | 'phone'; backend: 'webgpu' | 'webgl2'; gpu: 'high' | 'mid' | 'low' | 'unknown'; devicePixelRatio: number }export type TierEntry<K extends TierKnobs = TierKnobs> = K | ((d: DeviceClass) => K);diff --git a/scenes/packages/scene-kit/src/renderer/msaa-store.ts b/scenes/packages/scene-kit/src/renderer/msaa-store.tsnew file mode 100644index 00000000..f0759176--- /dev/null+++ b/scenes/packages/scene-kit/src/renderer/msaa-store.ts@@ -0,0 +1,106 @@+import type { Object3D, RenderTarget, Scene, WebGPURenderer } from 'three/webgpu';+import type { TierKnobs } from '../quality/core';+/**+ * OD-10. With antialias and tone mapping, three r186 renders the canvas through an internal 4x frame-buffer target+ * and resets its public storeMultisampled* flags to `true` on every call (Renderer._getFrameBufferTarget); nothing+ * public reaches that target. Storing is three's conservative default, needed only when a mid-pass framebuffer copy+ * splits the pass (viewport depth/texture nodes, transmission). For a scene whose main pass is never split, this+ * policy writes the flags `false` from scene.onBeforeRender, which runs after that reset and before texture creation+ * and beginRender: the pass resolves, then discards, and three creates the 4x attachments transient. Public members,+ * private contract; tests/renderer/msaa-contract.test.ts pins the order in three.webgpu.js.+ * Transient attachments allow only clear/discard passes, so anything that would load or store them trips the policy+ * for the rest of the mount, restores store and disposes the target (three recreates storable attachments): mid-pass,+ * after the frame; otherwise before the call. So does an outermost canvas render of the scene that never reached the+ * hook (a later non-chaining onBeforeRender), once that frame ends. A trip is never a silent decline.+ */+type Target = RenderTarget & { isPostProcessingRenderTarget?: boolean };+type Renderer = WebGPURenderer & { needsFrameBufferTarget: boolean; stencil: boolean };+type Hook = (this: unknown, ...args: unknown[]) => unknown;+export type MsaaTrip = 'autoClear' | 'copyFramebufferToTexture' | 'clear' | 'clearColor' | 'clearDepth' | 'clearStencil' | 'render' | 'hook-lost';+export interface MsaaStorePolicy {+ readonly active: boolean; readonly tripped: MsaaTrip | null;+ /** The kit's renderer.render wrapper brackets every render: beforeRender first, afterRender in its finally. */+ beforeRender(object: Object3D): void;+ afterRender(): void;+ remove(): void;+}+export interface MsaaStoreOptions { discard: boolean; onTrip(reason: MsaaTrip): void }+/** Store unless the structural tier opts in; KILN_TEST/KILN_DEV may force either way. */+export function resolveMsaaDiscard(knobs: TierKnobs, forced?: 'store' | 'discard'): boolean {+ return forced ? forced === 'discard' : knobs.multisample?.discard === true;+}+function patch<T extends object>(object: T, key: keyof T & string, wrap: (original: Hook) => Hook): () => void {+ const own = Object.prototype.hasOwnProperty.call(object, key), original = object[key] as unknown as Hook, wrapped = wrap(original);+ (object as Record<string, unknown>)[key] = wrapped;+ return () => { if ((object as Record<string, unknown>)[key] !== wrapped) return; if (own) (object as Record<string, unknown>)[key] = original; else delete (object as Record<string, unknown>)[key]; };+}+const policies = new WeakMap<WebGPURenderer, MsaaStorePolicy>();+/** Once per renderer: a second call returns the first policy, so it is decided once per mount and never toggled. */+export function installMsaaStorePolicy(renderer: WebGPURenderer, scene: Scene, o: MsaaStoreOptions): MsaaStorePolicy {+ const existing = policies.get(renderer); if (existing) return existing;+ const r = renderer as Renderer;+ if (!o.discard || (r.backend as unknown as { isWebGPUBackend?: boolean }).isWebGPUBackend !== true || !(r.samples > 1)) {+ const inert: MsaaStorePolicy = { active: false, tripped: null, beforeRender() {}, afterRender() {}, remove() { if (policies.get(renderer) === inert) policies.delete(renderer); } };+ policies.set(renderer, inert); return inert;+ }+ let current: Target | null = null, pending: Target | null = null, tripped: MsaaTrip | null = null, removed = false;+ // Wrapper depth; whether the outermost render is the scene on the canvas path, and whether the hook saw its target.+ let depth = 0, canvasFrame = false, hooked = false;+ const live = () => !removed && tripped === null;+ const onCanvas = () => r.getRenderTarget() === null && r.getOutputRenderTarget() === null && r.needsFrameBufferTarget;+ // Store again before disposing: a clear or copy that recreates the attachments outside _getFrameBufferTarget reads these.+ const release = (target: Target | null) => {+ if (!target) return;+ target.storeMultisampledColorBuffer = target.storeMultisampledDepthBuffer = target.storeMultisampledStencilBuffer = true; target.dispose();+ };+ const trip = (reason: MsaaTrip, midPass: boolean) => {+ tripped = reason; const target = current; current = null;+ if (midPass) pending = target; else release(target);+ o.onTrip(reason);+ };+ const guard = (reason: MsaaTrip) => {+ if (!live()) return;+ if (current !== null && r.getRenderTarget() === current) trip(reason, true);+ else if (onCanvas()) trip(reason, false);+ };+ // Only at the canvas target's own frame boundaries: a nested render into another target (a reflector) runs mid-pass.+ const settle = (target: unknown) => { if (pending !== null && target === pending) { pending = null; release(target as Target); } };+ const restores = [+ patch(scene, 'onBeforeRender', before => function (this: unknown, ...args: unknown[]) {+ settle(args[3]);+ const t = args[3] as Target | null | undefined;+ if (live() && t?.isPostProcessingRenderTarget === true && t.samples > 1 && r.getOutputRenderTarget() === null) {+ hooked = true;+ if (!(r.autoClear && r.autoClearColor && r.autoClearDepth && (r.autoClearStencil || !r.stencil))) trip('autoClear', false);+ else { t.storeMultisampledColorBuffer = t.storeMultisampledDepthBuffer = t.storeMultisampledStencilBuffer = false; current = t; }+ }+ return before.apply(this, args);+ }),+ patch(scene, 'onAfterRender', after => function (this: unknown, ...args: unknown[]) {+ try { return after.apply(this, args); } finally { settle(args[3]); }+ }),+ ...(['copyFramebufferToTexture', 'clear', 'clearColor', 'clearDepth', 'clearStencil'] as const).map(key =>+ patch(r, key, original => function (this: unknown, ...args: unknown[]) { guard(key); return original.apply(this, args); })),+ ];+ const policy: MsaaStorePolicy = {+ get active() { return live(); }, get tripped() { return tripped; },+ beforeRender(object) {+ if (removed) return;+ if (depth++ === 0) { hooked = false; canvasFrame = object === scene && onCanvas(); }+ if (object !== scene) guard('render');+ },+ // The outermost render is over, even one that threw: a pending target goes now, and a canvas frame of the scene+ // that the hook never saw encoded three's store onto transient attachments.+ afterRender() {+ if (removed || depth === 0 || --depth > 0) return;+ settle(pending);+ if (canvasFrame && live() && !hooked) trip('hook-lost', false);+ },+ remove() {+ if (removed) return; removed = true; policies.delete(renderer);+ for (const restore of restores) restore();+ const target = pending ?? current; pending = current = null; release(target);+ },+ };+ policies.set(renderer, policy); return policy;+}diff --git a/scenes/packages/scene-kit/src/shadows/cache.ts b/scenes/packages/scene-kit/src/shadows/cache.tsnew file mode 100644index 00000000..0721374b--- /dev/null+++ b/scenes/packages/scene-kit/src/shadows/cache.ts@@ -0,0 +1,143 @@+import { Object3D } from 'three/webgpu';+import type { DirectionalLight, InstancedMesh, Light, LightShadow, Mesh, Node, OrthographicCamera, SkinnedMesh } from 'three/webgpu';+import { min, shadow } from 'three/tsl';+import { keepsShadowMask, layerBit, ShadowLayers, suppressedCasters } from './layers';+import type { ShadowLayerSet } from './layers';++type Shadow = LightShadow & { shadowNode?: Node; filterNode?: unknown; map?: unknown };+interface Watch { m: Float64Array; v: boolean; c: boolean; iv: number; n: number; live: boolean; quiet: number }+export interface CachedSunShadowOptions {+ light: DirectionalLight; liveMapSize?: number; settleFrames?: number; layers?: ShadowLayerSet;+ /**+ * The largest change of any watched matrixWorld element (world units for translation) that is not motion; default 1e-6, 0 is+ * exact. Drift is measured from the pose last counted as motion, so a static map is never more than about twice this out of date.+ */+ tolerance?: number;+}+export interface CachedSunShadowStats { staticRenders: number; liveRenders: number; staticCasters: number; liveCasters: number; readonly pendingSettle: number; invalidations: number; reasons: Record<string, number> }+export interface CachedSunShadowTrackOptions {+ /** Casters under a movable() node are watched: one whose matrix, visibility, casting or instances change goes live until still. */+ movable?(n: Object3D): boolean;+ /** Casters under a live() node always draw in the live map: motion the watch cannot see (instance attributes, vertex or morph animation). */+ live?(n: Object3D): boolean;+}+export interface TrackedCasters { readonly added: number; untrack(): void }+export interface CachedSunShadow {+ readonly staticShadow: LightShadow; readonly liveShadow: LightShadow; readonly stats: CachedSunShadowStats;+ /**+ * Tags the casters under root (castShadow, kit-suppressed or a stand-in) that the light's shadow camera draws: those sharing a+ * layer with its mask, or layer 0 when the mask has no bit above 0 (three would use each viewing camera's mask). A mesh keeps+ * the role of the call that tagged it; one that starts casting later joins on the next track(). `untrack()` restores exactly+ * the meshes this call tagged and re-arms the static map (a world replaced while the cache survives).+ */+ track(root: Object3D, o?: CachedSunShadowTrackOptions): TrackedCasters;+ invalidate(reason: string): void; prime(): void; update(): void; dispose(): void;+}+const CAMERA = ['left', 'right', 'top', 'bottom', 'near', 'far', 'zoom'] as const, VALUES = ['bias', 'normalBias', 'radius', 'intensity', 'blurSamples'] as const;+const shown = (o: Object3D) => { for (let n: Object3D | null = o; n; n = n.parent) if (!n.visible) return false; return true; };+const draws = (o: Object3D) => { const im = o as InstancedMesh; return o.castShadow && (!im.isInstancedMesh || im.count > 0) && shown(o); };+/**+ * OD-9 cached sun shadow: a static map S rendered only when armed, plus a live map D for casters that moved, sampled as+ * min(S, D) through `light.shadow.shadowNode` (three r186 AnalyticLightNode reads it once, so install before any receiver+ * builds, which the light's stock map betrays; keep light.castShadow true). Each map is a clone of the configured+ * light.shadow on its own placeholder light that shares the sun's matrixWorld and target. Both are armed at install, the+ * only safe first render (a later first render leaves shared-refresh receivers bound to a destroyed texture); the kit never+ * clears a flag itself. `update()` runs every frame after all motion and visibility (SystemOrder.shadows): watched casters+ * that changed move to the live bit and re-arm S; after `settleFrames` quiet frames they return. The sampling values (bias,+ * normal bias, radius, intensity) reach both maps every frame; S takes the camera extents when it re-arms (a VSM blur takes+ * its radius then too). Call `prime()` when a warm pass starts drawing (D draws every caster once, so a later promotion+ * creates nothing) and `invalidate()` on any static change the watch cannot see (doors, LOD, visibility, threshold,+ * stand-ins, sun moves, layer changes after track). Square maps only. Dispose after the light has left the scene: three+ * would render a disposed node.+ */+export function cachedSunShadow(o: CachedSunShadowOptions): CachedSunShadow {+ const { light } = o, template = light.shadow as Shadow, L = o.layers ?? ShadowLayers, settle = o.settleFrames ?? 30, tol = o.tolerance ?? 1e-6;+ if (template.shadowNode) throw new Error('Light already has a custom shadow node');+ if (template.map) throw new Error('Install the cached sun shadow before any receiver renders: the light already has a stock shadow map');+ if (!(L.static >= 1 && L.live >= 1 && L.static <= 31 && L.live <= 31 && L.static !== L.live)) throw new Error('Shadow layers must be distinct bits 1..31');+ if (!(tol >= 0)) throw new Error('Shadow motion tolerance must be 0 or more');+ const sBit = layerBit(L.static), dBit = layerBit(L.live), kit = sBit | dBit;+ const values = (s: Shadow) => { for (const k of VALUES) s[k] = template[k]; };+ const sync = (s: Shadow) => { const c = s.camera as OrthographicCamera, t = template.camera as OrthographicCamera; for (const k of CAMERA) c[k] = t[k]; c.updateProjectionMatrix(); values(s); };+ const make = (mask: number, label: string) => {+ const s = template.clone() as Shadow; s.filterNode = template.filterNode; s.mapType = template.mapType; s.autoUpdate = false; s.needsUpdate = true; s.camera.layers.mask = mask;+ const placeholder = Object.assign(new Object3D(), { name: `${light.name || 'sun'} ${label}`, castShadow: true, shadow: s, target: light.target, matrixWorld: light.matrixWorld });+ return { s, node: shadow(placeholder as unknown as Light, s) };+ };+ const S = make(sBit, 'static'), D = make(dBit, 'live');+ if (o.liveMapSize) D.s.mapSize.setScalar(o.liveMapSize);+ template.shadowNode = min(S.node as unknown as Node<'float'>, D.node as unknown as Node<'float'>);+ const tagged = new Map<Object3D, number>(), watched = new Map<Object3D, Watch>(), pinned = new Set<Object3D>();+ let size = template.mapSize.x, sentinel = template.mapSize.y, resized = false, priming = false, hadLive = false, armLive = false, disposed = false, watchedLive = 0;+ const stats: CachedSunShadowStats = { staticRenders: 1, liveRenders: 1, staticCasters: 0, liveCasters: 0, invalidations: 0, reasons: {},+ get pendingSettle() { return watchedLive + (S.s.needsUpdate || D.s.needsUpdate || priming ? 1 : 0); } };+ const rearm = () => { sync(S.s); S.s.needsUpdate = true; stats.staticRenders++; };+ const invalidate = (reason: string) => { if (disposed) return; stats.invalidations++; stats.reasons[reason] = (stats.reasons[reason] ?? 0) + 1; rearm(); };+ const changed = (n: Object3D, w: Watch) => {+ const e = n.matrixWorld.elements, im = n as InstancedMesh, v = shown(n), iv = im.isInstancedMesh ? im.instanceMatrix.version : 0, count = im.isInstancedMesh ? im.count : 0;+ let d = v !== w.v || n.castShadow !== w.c || iv !== w.iv || count !== w.n || !!(n as SkinnedMesh).isSkinnedMesh;+ for (let i = 0; i < 16; i++) if (!(Math.abs(w.m[i]! - e[i]!) <= tol)) { w.m.set(e); d = true; break; }+ w.v = v; w.c = n.castShadow; w.iv = iv; w.n = count; return d;+ };+ /** Live casters now: watched ones that are live plus live() casters that draw. */+ const tally = (live: number) => {+ let drawn = 0; for (const n of pinned) if (draws(n)) drawn++;+ watchedLive = live; stats.liveCasters = live + drawn; stats.staticCasters = tagged.size - pinned.size - live; return live + drawn;+ };+ return { staticShadow: S.s, liveShadow: D.s, stats,+ track(root, t = {}) {+ if (disposed) throw new Error('Cached sun shadow has been disposed');+ const mine: Object3D[] = [], mask = template.camera.layers.mask, sees = keepsShadowMask(mask) ? mask : 1;let done = false;+ const visit = (n: Object3D, watch: boolean, pin: boolean) => {+ pin ||= !!t.live?.(n); watch ||= !!t.movable?.(n); const m = n as Mesh;+ if (m.isMesh && (m.castShadow || suppressedCasters.has(m) || m.userData.kilnShadowStandIn) && (m.layers.mask & sees) !== 0) {+ if (!tagged.has(m)) {+ tagged.set(m, m.layers.mask & kit); mine.push(m);+ if (pin) { pinned.add(m); m.layers.mask = m.layers.mask & ~sBit | dBit; } else m.layers.mask |= sBit;+ }+ if (watch && !pinned.has(m) && !watched.has(m)) { const w = { m: new Float64Array(16), v: false, c: false, iv: 0, n: 0, live: false, quiet: 0 }; changed(m, w); watched.set(m, w); }+ }+ for (const c of n.children) visit(c, watch, pin);+ };+ visit(root, false, false); tally(watchedLive);+ return { added: mine.length, untrack() {+ if (done || disposed) return; done = true;let gone = 0;+ for (const m of mine) {+ const had = tagged.get(m); if (had === undefined) continue;+ m.layers.mask = m.layers.mask & ~kit | had; tagged.delete(m); watched.delete(m); pinned.delete(m); gone++;+ }+ if (!gone) return;+ let live = 0; for (const w of watched.values()) if (w.live) live++;+ tally(live); invalidate('untrack');+ } };+ },+ invalidate,+ prime() { if (disposed) return; rearm(); priming = true; D.s.camera.layers.mask = kit; D.s.needsUpdate = true; stats.liveRenders++; },+ update() {+ if (disposed) return;+ if (priming && !D.s.needsUpdate) { priming = false; D.s.camera.layers.mask = dBit; armLive = true; }+ if (template.mapSize.x !== size) {+ // Placeholders are not scene lights, so receivers rebind only when the real light's mapSize changes (NodeMaterialObserver).+ size = template.mapSize.x; S.s.mapSize.setScalar(size); if (!o.liveMapSize) D.s.mapSize.setScalar(size);+ template.mapSize.y = sentinel = Math.max(sentinel, template.mapSize.y) + 1; resized = armLive = true; rearm();+ }+ let moved = false, live = 0;+ for (const [n, w] of watched) {+ if (changed(n, w)) { w.quiet = 0; if (!w.live) { w.live = moved = true; n.layers.mask = n.layers.mask & ~sBit | dBit; } }+ else if (w.live && ++w.quiet >= settle) { w.live = false; moved = true; n.layers.mask = n.layers.mask & ~dBit | sBit; }+ if (w.live) live++;+ }+ if (moved) rearm();+ sync(D.s); values(S.s);+ const now = tally(live);+ if (now || hadLive || armLive) { D.s.needsUpdate = true; stats.liveRenders++; }+ hadLive = now > 0; armLive = false;+ },+ dispose() {+ if (disposed) return; disposed = true;+ S.node.dispose(); D.node.dispose(); S.s.dispose(); D.s.dispose(); delete template.shadowNode;+ if (resized) template.mapSize.y = template.mapSize.x;+ for (const [n, had] of tagged) n.layers.mask = n.layers.mask & ~kit | had;+ tagged.clear(); watched.clear(); pinned.clear();+ } };+}diff --git a/scenes/packages/scene-kit/src/shadows/index.ts b/scenes/packages/scene-kit/src/shadows/index.tsnew file mode 100644index 00000000..ced08c85--- /dev/null+++ b/scenes/packages/scene-kit/src/shadows/index.ts@@ -0,0 +1,8 @@+// Shadow and extra-pass features: cached static plus live sun shadow, small-caster threshold, depth stand-ins and pass+// stand-ins. Every feature is off until a scene installs it.+export * from './layers';+export * from './cache';+export * from './once';+export * from './threshold';+export * from './stand-ins';+export * from './pass';diff --git a/scenes/packages/scene-kit/src/shadows/layers.ts b/scenes/packages/scene-kit/src/shadows/layers.tsnew file mode 100644index 00000000..612f254c--- /dev/null+++ b/scenes/packages/scene-kit/src/shadows/layers.ts@@ -0,0 +1,9 @@+import type { Object3D } from 'three/webgpu';+/** Kit-reserved layer bits for the cached sun shadow; scenes keep 0..29 (Golden Gate uses 0-2). */+export const ShadowLayers = { static: 30, live: 31 } as const;+export interface ShadowLayerSet { static: number; live: number }+/** three r186 swaps a shadow camera mask with no bit at layer 1 or above for the viewing camera's (ShadowNode.updateShadow). */+export const keepsShadowMask = (mask: number): boolean => (mask & 0xFFFFFFFE) !== 0;+export const layerBit = (layer: number): number => 1 << layer | 0;+/** Casters a kit feature switched off (small-caster threshold, stand-in sources): they keep shadow layer bits so a restore casts again. */+export const suppressedCasters = /*@__PURE__*/ new WeakSet<Object3D>();diff --git a/scenes/packages/scene-kit/src/shadows/once.ts b/scenes/packages/scene-kit/src/shadows/once.tsnew file mode 100644index 00000000..cb651361--- /dev/null+++ b/scenes/packages/scene-kit/src/shadows/once.ts@@ -0,0 +1,16 @@+import type { Light, LightShadow } from 'three/webgpu';+import { keepsShadowMask } from './layers';+/**+ * Renders a light's shadow map at most once per frame. three r186 re-renders an auto-updating map for every camera that+ * draws a receiver in a frame (ShadowNode.updateBefore dedupes per camera and frame only), so Golden Gate's planar+ * reflector drew the sun map twice. Call `update()` every frame before rendering (SystemOrder.shadows): the first camera+ * renders and three clears the flag, later cameras reuse the map. Armed at install for the first-frame bind. The shadow+ * camera must keep its own layers (a bit above layer 0, checked at install): with none, three draws the map with each+ * viewing camera's mask, so cameras that see different layers need their own map and one shared map is not look-neutral.+ */+export function shadowOncePerFrame(light: Light & { shadow: LightShadow }): { update(): void; restore(): void } {+ const s = light.shadow, auto = s.autoUpdate;let restored = false;+ if (!keepsShadowMask(s.camera.layers.mask)) throw new Error('Shadow once per frame needs a shadow camera layer above 0: three r186 otherwise renders the map with each camera\'s own mask');+ s.autoUpdate = false; s.needsUpdate = true;+ return { update() { if (!restored) s.needsUpdate = true; }, restore() { if (restored) return; restored = true; s.autoUpdate = auto; s.needsUpdate = true; } };+}diff --git a/scenes/packages/scene-kit/src/shadows/pass.ts b/scenes/packages/scene-kit/src/shadows/pass.tsnew file mode 100644index 00000000..97cd4199--- /dev/null+++ b/scenes/packages/scene-kit/src/shadows/pass.ts@@ -0,0 +1,37 @@+import type { Camera, InstancedMesh, Mesh, Object3D } from 'three/webgpu';+/** Layer bits for an extra pass: `main` holds drawables only main (and shadow) cameras draw, `pass` holds pass stand-ins. */+export interface PassLayers { main: number; pass: number }+const bit = (layer: number) => { if (!(Number.isInteger(layer) && layer >= 1 && layer <= 31)) throw new Error('Pass layers must be 1..31'); return 1 << layer | 0; };+const drawable = (n: Object3D) => { const d = n as Mesh & { isLine?: boolean; isPoints?: boolean; isSprite?: boolean }; return !!(d.isMesh || d.isLine || d.isPoints || d.isSprite); };+/**+ * Moves every drawable under `roots` from layer 0 to a main-only layer, so a pass camera cloned from the main camera stops+ * drawing it (three r186 ReflectorNode clones its virtual camera once and never copies layers again). Cameras that keep+ * drawing it, the main camera and a shadow camera while it casts, take passCameraLayers(camera, l, 'main'). Restore puts+ * bit 0 back and clears only the bits it set.+ */+export function mainOnly(roots: Object3D[], layer: number): { stats: { objects: number }; restore(): void } {+ const b = bit(layer), moved = new Map<Object3D, boolean>();let restored = false;+ for (const root of roots) root.traverse(n => { if (drawable(n) && n.layers.mask & 1 && !moved.has(n)) { moved.set(n, !!(n.layers.mask & b)); n.layers.mask = n.layers.mask & ~1 | b; } });+ return { stats: { objects: moved.size }, restore() { if (restored) return; restored = true; for (const [n, had] of moved) n.layers.mask = (had ? n.layers.mask : n.layers.mask & ~b) | 1; } };+}+/**+ * A coloured stand-in for an extra pass (OD-18): a clone of `source` that shares its geometry, materials and instance data,+ * with every node on the pass-only layer, no shadow casting, no raycast and userData.kilnPassStandIn. Never a shadow depth+ * proxy, which writes no colour. Added to `parent` (default the source's parent) with the source's local transform.+ */+export function passStandIn(source: Object3D, o: { layer: number; parent?: Object3D }): { object: Object3D; stats: { meshes: number }; restore(): void } {+ const b = bit(o.layer), from: Object3D[] = [];source.traverse(n => { if ((n as Object3D & { isLight?: boolean }).isLight) throw new Error(`Pass stand-in ${source.name} holds a light`); from.push(n); });+ const object = source.clone();let i = 0, meshes = 0, restored = false;+ object.traverse(n => {+ const s = from[i++] as InstancedMesh, m = n as InstancedMesh; n.layers.mask = b;+ if (m.isInstancedMesh) { m.instanceMatrix = s.instanceMatrix; m.instanceColor = s.instanceColor; }+ if (drawable(n)) { m.castShadow = false; m.raycast = () => {}; m.userData.kilnPassStandIn = true; meshes++; }+ });+ object.name = `Pass stand-in ${source.name}`; (o.parent ?? source.parent)?.add(object);+ return { object, stats: { meshes }, restore() { if (restored) return; restored = true; object.removeFromParent(); } };+}+/** Sets only a camera's two pass bits: 'pass' sees pass stand-ins and not main-only drawables, 'main' the reverse. Idempotent, so it can run every frame on a pass camera three may recreate. */+export function passCameraLayers(camera: Camera, l: PassLayers, role: 'main' | 'pass' = 'pass'): number {+ const m = bit(l.main), p = bit(l.pass); if (m === p) throw new Error('Pass layers must differ');+ return camera.layers.mask = camera.layers.mask & ~(m | p) | (role === 'pass' ? p : m);+}diff --git a/scenes/packages/scene-kit/src/shadows/stand-ins.ts b/scenes/packages/scene-kit/src/shadows/stand-ins.tsnew file mode 100644index 00000000..5bbd8680--- /dev/null+++ b/scenes/packages/scene-kit/src/shadows/stand-ins.ts@@ -0,0 +1,95 @@+import { BackSide, Box3, DoubleSide, FrontSide, Mesh, MeshBasicNodeMaterial, Vector3 } from 'three/webgpu';+import type { BufferGeometry, Material, Object3D, Side } from 'three/webgpu';+import { bakeRigidGeometry } from '../instancing/rigid-merge';+import { layerBit, suppressedCasters } from './layers';+export interface ShadowStandInOptions {+ layer: number; isAnchor(n: Object3D): boolean; include?(m: Mesh): boolean; texel?: number; minCasterTexels?: number; chunk?: { cell: number; maxTriangles?: number };+ /** The shadow camera's layer mask: sources sharing no bit with it are skipped as `layer`, since three never draws them. Default layer 0 only; it must include `layer`. */+ shadowMask?: number;+}+export interface ShadowStandIns {+ readonly proxies: Mesh[]; readonly sources: Mesh[]; readonly dropped: Mesh[];+ readonly stats: { groups: number; sourceMeshes: number; proxies: number; triangles: number; dropped: number; skipped: Record<string, number> }; restore(): void;+}+interface Bucket { anchor: Object3D; side: Side; parts: Mesh[] }+/** The side three r186 gives a PCF or basic shadow override: `shadowSide ?? {Front: Back, Back: Front, Double: Double}[side]` (Renderer._shadowSide). */+const FLIP: Side[] = [BackSide, FrontSide, DoubleSide];+/** Material inputs the shadow override carries into its depth draw (alpha, discard, position, depth or transparency nodes). */+const OWN = ['alphaMap', 'alphaHash', 'positionNode', 'castShadowPositionNode', 'displacementMap', 'maskNode', 'maskShadowNode', 'castShadowNode', 'transmissionNode', 'backdropNode', 'depthNode'] as const;+const has = (o: object, k: string) => !!(o as Record<string, unknown>)[k], triangles = (g: BufferGeometry) => (g.index ? g.index.count : g.attributes.position!.count) / 3;+function excluded(m: Mesh): string | undefined {+ const g = m.geometry, mat = m.material as Material & { transmission?: number };+ if (Array.isArray(mat)) return 'multiMaterial';+ if (has(m, 'isInstancedMesh') || has(g, 'isInstancedBufferGeometry')) return 'instanced';+ if (has(m, 'isBatchedMesh')) return 'batched';+ if (has(m, 'isSkinnedMesh')) return 'skinned';+ if (Object.keys(g.morphAttributes).length) return 'morphed';+ if (!g.attributes.position || g.drawRange.start !== 0 || g.drawRange.count !== Infinity) return 'drawRange';+ if (Object.hasOwn(m, 'onBeforeShadow') || Object.hasOwn(m, 'onBeforeRender')) return 'hook';+ if (!mat.visible) return 'materialHidden';+ if (mat.allowOverride === false) return 'allowOverride';+ if (mat.alphaTest > 0) return 'alphaTest';+ if ((mat.transmission ?? 0) > 0) return 'transmission';+ return OWN.find(k => has(mat, k));+}+/**+ * OD-18 shadow stand-ins. Eligible casters bake, positions only, into one proxy per anchor (nearest isAnchor ancestor; the+ * root counts), effective shadow side and optional world x/z cell, split at `maxTriangles`. A proxy is an identity child of+ * its anchor, so it inherits the anchor's motion and visibility; it sits on `layer` alone (never 0: main cameras and+ * raycasters never see it) with a material-free node material per side that writes no colour or depth outside a shadow+ * pass. Sources stop casting and stay on shadow layers through suppressedCasters. Eligible: visible below its anchor,+ * castShadow, on a layer the shadow camera sees (`shadowMask`, default layer 0), one material, a plain mesh with the default draw range and no own render hooks, not under a LOD or+ * ClippingGroup below its anchor, and a material the override draws as plain depth. Plain transparency qualifies: three+ * r186 draws it with NoBlending, depth written and no discard (twice when double-sided). Parts whose sphere diameter is under+ * `minCasterTexels` texels drop before the merge. Build after batching. The proxy's matrixWorld is set once and it copies+ * the anchor's matrixWorldAutoUpdate, so a frozen owner stays frozen. Assumes a non-VSM map and shadowMap.transmitted off.+ */+export function shadowStandIns(root: Object3D, o: ShadowStandInOptions): ShadowStandIns {+ if (!(Number.isInteger(o.layer) && o.layer >= 1 && o.layer <= 31)) throw new Error('Stand-in layer must be 1..31');+ if (o.shadowMask !== undefined && !(o.shadowMask & layerBit(o.layer))) throw new Error('The shadow camera mask must include the stand-in layer');+ const sees = o.shadowMask ?? 1;+ root.updateWorldMatrix(true, true);+ const skipped: Record<string, number> = {}, groups = new Map<string, Bucket>(), dropped: Mesh[] = [], min = (o.texel ?? 0) * (o.minCasterTexels ?? 0), cell = o.chunk?.cell, box = new Box3(), c = new Vector3();+ const visit = (n: Object3D, anchor: Object3D, hidden: boolean, cut?: string) => {+ if (n !== anchor && o.isAnchor(n)) { anchor = n; hidden = false; cut = undefined; }+ if (n !== anchor) { hidden ||= !n.visible; if (has(n, 'isClippingGroup')) cut ??= 'clipping'; }+ if (has(n, 'isLOD')) cut ??= 'lod';+ const m = n as Mesh;+ if (m.isMesh) {+ const why = m.userData.kilnShadowStandIn || m.userData.kilnPassStandIn ? 'standIn' : hidden ? 'hidden' : !m.castShadow ? 'noCast' : !(m.layers.mask & sees) ? 'layer' : cut ?? (o.include?.(m) === false ? 'include' : excluded(m));+ const g = m.geometry; if (!why && !g.boundingSphere) g.computeBoundingSphere();+ if (why) skipped[why] = (skipped[why] ?? 0) + 1;+ else if (2 * g.boundingSphere!.radius * m.matrixWorld.getMaxScaleOnAxis() < min) dropped.push(m);+ else {+ const mat = m.material as Material, side = mat.shadowSide ?? FLIP[mat.side];let key = `${anchor.id}|${side}`;+ if (cell) { if (!g.boundingBox) g.computeBoundingBox(); box.copy(g.boundingBox!).applyMatrix4(m.matrixWorld).getCenter(c); key += `|${Math.floor(c.x / cell)}|${Math.floor(c.z / cell)}`; }+ let group = groups.get(key); if (!group) groups.set(key, group = { anchor, side, parts: [] }); group.parts.push(m);+ }+ }+ for (const child of n.children) visit(child, anchor, hidden, cut);+ };+ visit(root, root, false);+ const max = o.chunk?.maxTriangles ?? Infinity, plan: Bucket[] = [];+ for (const g of groups.values()) {+ let parts: Mesh[] = [], t = 0;+ for (const m of g.parts) { const n = triangles(m.geometry); if (parts.length && t + n > max) { plan.push({ ...g, parts }); parts = []; t = 0; } parts.push(m); t += n; }+ plan.push({ ...g, parts });+ }+ const materials = new Map<Side, MeshBasicNodeMaterial>(), proxies: Mesh[] = [], sources: Mesh[] = [];let total = 0, restored = false;+ for (const p of plan) {+ let material = materials.get(p.side);+ if (!material) materials.set(p.side, material = new MeshBasicNodeMaterial({ name: 'Shadow stand-in', side: FLIP[p.side], shadowSide: p.side, colorWrite: false, depthWrite: false }));+ const m = new Mesh(bakeRigidGeometry(p.parts, p.anchor, { attributes: 'position' }), material);+ m.name = `Shadow stand-in ${p.anchor.name}`; m.layers.set(o.layer); m.castShadow = true; m.userData.kilnShadowStandIn = true; m.raycast = () => {};+ m.matrixAutoUpdate = false; m.matrixWorldAutoUpdate = p.anchor.matrixWorldAutoUpdate; p.anchor.add(m); m.matrixWorld.copy(p.anchor.matrixWorld);+ proxies.push(m); sources.push(...p.parts); total += triangles(m.geometry);+ }+ const off = [...sources, ...dropped]; for (const m of off) { m.castShadow = false; suppressedCasters.add(m); }+ return { proxies, sources, dropped, stats: { groups: groups.size, sourceMeshes: sources.length, proxies: proxies.length, triangles: total, dropped: dropped.length, skipped },+ restore() {+ if (restored) return; restored = true;+ for (const m of off) { m.castShadow = true; suppressedCasters.delete(m); }+ for (const m of proxies) { m.removeFromParent(); m.geometry.dispose(); }+ for (const m of materials.values()) m.dispose();+ } };+}diff --git a/scenes/packages/scene-kit/src/shadows/threshold.ts b/scenes/packages/scene-kit/src/shadows/threshold.tsnew file mode 100644index 00000000..1d3ba82e--- /dev/null+++ b/scenes/packages/scene-kit/src/shadows/threshold.ts@@ -0,0 +1,50 @@+import { Matrix4 } from 'three/webgpu';+import type { DirectionalLight, InstancedMesh, LightShadow, Mesh, Object3D, OrthographicCamera } from 'three/webgpu';+import { suppressedCasters } from './layers';+/** 'sphere': bounding-sphere diameter under the world scale and the largest instance, as the count probe sizes casters; orientation-free. 'light': geometry box extent across the sun's view. */+export type CasterMeasure = 'sphere' | 'light';+/** World size of one shadow texel for an orthographic (directional) shadow; 0 otherwise, so nothing reads as small. */+export function shadowTexelSize(shadow: LightShadow): number {+ const c = shadow.camera as OrthographicCamera; return c.isOrthographicCamera ? (c.right - c.left) / c.zoom / shadow.mapSize.x : 0;+}+const _view = /*@__PURE__*/ new Matrix4(), _instance = /*@__PURE__*/ new Matrix4();+/** Caster size in shadow texels; an InstancedMesh is its largest drawn instance. The caster's world matrix must be current; the 'light' measure brings the light's and target's up to date. */+export function casterTexels(o: Mesh, light: DirectionalLight, texel: number, measure: CasterMeasure = 'light'): number {+ const g = o.geometry, im = o as InstancedMesh, n = im.isInstancedMesh ? im.count : 1;let size = 0;+ if (measure === 'sphere') {+ if (!g.boundingSphere) g.computeBoundingSphere();+ for (let i = 0; i < n; i++) size = Math.max(size, im.isInstancedMesh ? im.getMatrixAt(i, _instance).getMaxScaleOnAxis() : 1);+ return 2 * g.boundingSphere!.radius * o.matrixWorld.getMaxScaleOnAxis() * (n ? size : 1) / texel;+ }+ if (!g.boundingBox) g.computeBoundingBox();+ const { min, max } = g.boundingBox!, hx = (max.x - min.x) / 2, hy = (max.y - min.y) / 2, hz = (max.z - min.z) / 2;+ // A light that never joined a rendered scene (a measuring copy) has stale world matrices; three updates them only when it renders.+ light.updateWorldMatrix(true, false); light.target.updateWorldMatrix(true, false); light.shadow.updateMatrices(light);+ for (let i = 0; i < n; i++) {+ _view.multiplyMatrices(light.shadow.camera.matrixWorldInverse, o.matrixWorld); if (im.isInstancedMesh) _view.multiply(im.getMatrixAt(i, _instance));+ const e = _view.elements; size = Math.max(size, Math.abs(e[0]!) * hx + Math.abs(e[4]!) * hy + Math.abs(e[8]!) * hz, Math.abs(e[1]!) * hx + Math.abs(e[5]!) * hy + Math.abs(e[9]!) * hz);+ }+ return 2 * size / texel;+}+export interface SmallCasterOptions { minTexels?: number; measure?: CasterMeasure; include?(m: Mesh): boolean; onChange?(): void }+export interface SmallCasterThreshold { readonly dropped: Mesh[]; update(): void; restore(): void; readonly stats: { casters: number; dropped: number; texel: number } }+/**+ * Switches castShadow off on visible casters under `minTexels` (default 2) shadow texels and restores them. The default+ * sphere measure matches the count probe's casters-under-N-texels what-if. `update()` re-evaluates after a texel, tier or+ * sun change (not per frame); `onChange` (a cached shadow's invalidate) runs whenever the dropped set changes.+ */+export function smallCasterThreshold(root: Object3D, light: DirectionalLight, o: SmallCasterOptions = {}): SmallCasterThreshold {+ const minTexels = o.minTexels ?? 2, measure = o.measure ?? 'sphere', set = new Set<Mesh>(), dropped: Mesh[] = [], stats = { casters: 0, dropped: 0, texel: 0 };let restored = false;+ const toggle = (m: Mesh, small: boolean) => { m.castShadow = !small; if (small) { set.add(m); suppressedCasters.add(m); } else { set.delete(m); suppressedCasters.delete(m); } };+ const visit = (n: Object3D, fn: (m: Mesh) => void) => { if (!n.visible) return; if ((n as Mesh).isMesh) fn(n as Mesh); for (const c of n.children) visit(c, fn); };+ const evaluate = () => {+ const texel = shadowTexelSize(light.shadow);let changed = false;stats.casters = 0;+ visit(root, m => { if (!(m.castShadow || set.has(m)) || o.include?.(m) === false) return; stats.casters++; const small = casterTexels(m, light, texel, measure) < minTexels; if (small !== set.has(m)) { toggle(m, small); changed = true; } });+ dropped.splice(0, dropped.length, ...set); stats.dropped = set.size; stats.texel = texel;+ if (changed) o.onChange?.();+ };+ evaluate();+ return { dropped, stats,+ update() { if (restored) throw new Error('Small-caster threshold has been restored'); evaluate(); },+ restore() { if (restored) return; restored = true; const any = set.size > 0; for (const m of [...set]) toggle(m, false); dropped.length = 0; stats.dropped = 0; if (any) o.onChange?.(); } };+}diff --git a/scenes/packages/scene-kit/src/testing/index.ts b/scenes/packages/scene-kit/src/testing/index.tsindex be5c2e39..4466522b 100644--- a/scenes/packages/scene-kit/src/testing/index.ts+++ b/scenes/packages/scene-kit/src/testing/index.ts@@ -3,6 +3,7 @@ import { useRuntime, type SceneRuntime } from '../internal/runtime';import { rendererProgramCounts } from './counts';import { KIT_DEV_PARAMS, readDevParams, FrameTimeRecorder } from './core';import type { DeviceProbe } from '../quality/core';+import { createRenderProbe, type ProbeOptions } from './probe';export * from './core';const live=new Set<SceneRuntime>();const context=(runtime?:SceneRuntime)=>runtime??Array.from(live).at(-1);@@ -46,6 +47,7 @@ export function installTestHooks(runtime:SceneRuntime) {if(typeof runtime.devParams.time==='number'){runtime.clock.time=runtime.clock.ambient=runtime.devParams.time;runtime.clock.timeScale=0;}if(runtime.devParams.freeze)runtime.clock.timeScale=0;if((window as unknown as {__kilnMeasureRequested?:boolean}).__kilnMeasureRequested){runtime.data.set('startupAt',performance.now());measurement(true);}+ const probe=createRenderProbe(runtime);const api={whenReady:()=>runtime.ready?Promise.resolve():new Promise<void>((accept,reject)=>{if(runtime.failed||runtime.disposed){reject(new Error('Scene did not become ready'));return;}@@ -69,6 +71,18 @@ export function installTestHooks(runtime:SceneRuntime) {runWorkload:(name:string)=>{runtime.data.set('workload',name);},events,invoke:(name:string,...args:unknown[])=>runtime.testHooks[name]?.(...args),+ // S1 count probe (probe.ts): per-pass draws, triangles and pipelines once K frames agree, with count-only what-ifs.+ // `timeoutMs` cancels the probe in the page (restoring its what-if), so a caller's own timeout never leaves one running.+ probeFrames:({timeoutMs,...options}:ProbeOptions&{timeoutMs?:number}={})=>new Promise((accept,reject)=>{+ if(runtime.disposed){reject(new Error('Scene disposed'));return;}+ let cancel=()=>{},timer:ReturnType<typeof setTimeout>|undefined;+ const settle=()=>{clearTimeout(timer);pending.delete(fail);},fail=(error:Error)=>{cancel();settle();reject(error);};+ try{cancel=probe.run(options,result=>{settle();accept({...result,tier:api.tierState()});},error=>{settle();reject(error);});}catch(error){reject(error);return;}+ pending.add(fail);+ if(timeoutMs!==undefined)timer=setTimeout(()=>fail(new Error(`probeFrames timed out after ${timeoutMs} ms`)),timeoutMs);+ }),+ sceneSummary:()=>probe.sceneSummary(),+ get frame(){return runtime.clock.frame;},get disposed(){return runtime.disposed;},};const proxy=new Proxy(api,{get(target,key,receiver){if(typeof key==='string'&&runtime.testHooks[key])return runtime.testHooks[key];return Reflect.get(target,key,receiver);}});diff --git a/scenes/packages/scene-kit/src/testing/probe-core.ts b/scenes/packages/scene-kit/src/testing/probe-core.tsnew file mode 100644index 00000000..709d61e7--- /dev/null+++ b/scenes/packages/scene-kit/src/testing/probe-core.ts@@ -0,0 +1,100 @@+// Pure, duck-typed helpers for the count probe (probe.ts in the page, scripts/count-probe.ts in Node). No three import:+// everything here reads plain fields, so the Node runner and unit tests share it without a renderer.+export type RenderKind = 'main' | 'shadow' | 'reflection' | 'offscreen';+export type PassKind = RenderKind | 'output';+export const PASS_KINDS: readonly PassKind[] = ['main', 'shadow', 'reflection', 'output', 'offscreen'];+const SHADOW = /^(?:Shadow Map|Point Light Shadow) \[/, REFLECTION = / \[ Reflector \]$/;+/** three r186 names its nested renders through `scene.name` (ShadowNode.js:652, PointShadowNode.js:302, ReflectorNode.js:561). */+export function classifyRender(sceneName: string, depth: number, mainScene = depth === 0): RenderKind {+ if (SHADOW.test(sceneName)) return 'shadow';+ if (REFLECTION.test(sceneName)) return 'reflection';+ return depth === 0 && mainScene ? 'main' : 'offscreen';+}+export interface TargetLike { width: number; height: number; isPostProcessingRenderTarget?: boolean }+export function classifyTarget(rt: TargetLike | null | undefined, shadowMaps: ReadonlySet<unknown>): string {+ if (!rt) return 'canvas';+ if (rt.isPostProcessingRenderTarget) return 'framebuffer';+ if (shadowMaps.has(rt)) return 'shadow-map';+ return `rt ${rt.width}x${rt.height}`;+}+export interface NodeLike { name: string; parent: NodeLike | null }+/** Named ancestors of `object` (itself included) from just below `root` down, cut to `depth` names. */+export function attributionPath(object: NodeLike, root: NodeLike | null, depth = 3): string {+ const names: string[] = [];let node: NodeLike | null = object;+ while (node && node !== root) { if (node.name) names.unshift(node.name); node = node.parent; }+ if (!node && root) names.unshift('(detached)');+ return names.length ? names.slice(0, depth).join('/') : '(unnamed)';+}+export interface InstancedLike { isInstancedMesh?: boolean; count?: number; instanceMatrix?: { array: ArrayLike<number> } }+export interface CasterLike extends InstancedLike {+ geometry: { index?: { count: number } | null; attributes: { position?: { count: number } }; boundingSphere?: { radius: number } | null; computeBoundingSphere?(): void };+ matrixWorld: { getMaxScaleOnAxis(): number };+}+/** Largest axis scale over the first `count` instance matrices of an InstancedMesh; 1 for anything else or no instances. */+export function maxInstanceScale(mesh: InstancedLike): number {+ const a = mesh.isInstancedMesh ? mesh.instanceMatrix?.array : undefined, n = a ? Math.min(mesh.count ?? 0, Math.floor(a.length / 16)) : 0;+ let max = 0;+ for (let i = 0; i < n; i++) for (const c of [0, 4, 8]) { const o = i * 16 + c; max = Math.max(max, a![o]! ** 2 + a![o + 1]! ** 2 + a![o + 2]! ** 2); }+ return n ? Math.sqrt(max) : 1;+}+/**+ * Triangles per draw (per instance for instanced meshes) and the bounding-sphere diameter in shadow texels (null without a+ * texel size). An InstancedMesh is sized by its largest instance, so a batch counts as small only when every instance is.+ */+export function casterSize(mesh: CasterLike, texelWorld: number | null | undefined): { triangles: number; texels: number | null } {+ const g = mesh.geometry, triangles = Math.floor((g.index ? g.index.count : g.attributes.position?.count ?? 0) / 3);+ if (!texelWorld) return { triangles, texels: null };+ if (!g.boundingSphere) g.computeBoundingSphere?.();+ const radius = g.boundingSphere?.radius ?? 0;+ return { triangles, texels: 2 * radius * mesh.matrixWorld.getMaxScaleOnAxis() * maxInstanceScale(mesh) / texelWorld };+}+/** Small when under either threshold given; a texel threshold needs `texelWorld`. */+export function isSmallCaster(mesh: CasterLike, o: { triangles?: number; texels?: number; texelWorld?: number | null }): boolean {+ const size = casterSize(mesh, o.texels === undefined ? null : o.texelWorld);+ return (o.triangles !== undefined && size.triangles < o.triangles) || (o.texels !== undefined && size.texels !== null && size.texels < o.texels);+}+export interface ShadowLike { camera?: { isOrthographicCamera?: boolean; isPerspectiveCamera?: boolean; left?: number; right?: number }; mapSize?: { x: number } }+/** World size of one shadow texel for an orthographic (directional) shadow; null otherwise. */+export function shadowTexelWorld(shadow: ShadowLike | null | undefined): number | null {+ const c = shadow?.camera, size = shadow?.mapSize?.x;+ if (!c?.isOrthographicCamera || !size || c.left === undefined || c.right === undefined) return null;+ return (c.right - c.left) / size;+}+/** `stable`: the last `stableFrames` frames share a key; `stableAfter` is the first index of that trailing run. */+export function summarizeFrames<T>(frames: readonly T[], o: { stableFrames?: number; key?: (frame: T) => string } = {}): { stable: boolean; identical: boolean; stableAfter: number | null; frame: T | null } {+ const need = o.stableFrames ?? 3, key = o.key ?? ((frame: T) => JSON.stringify(frame));+ if (!frames.length) return { stable: false, identical: false, stableAfter: null, frame: null };+ const keys = frames.map(key), last = keys.at(-1)!;let start = keys.length - 1;+ while (start > 0 && keys[start - 1] === last) start--;+ const stable = keys.length - start >= need;+ return { stable, identical: start === 0 && stable, stableAfter: stable ? start : null, frame: frames.at(-1)! };+}+type Counts = { [key: string]: unknown };+/** variant − base over numeric leaves of plain objects; a side missing a leaf counts as zero. Strings and arrays are dropped. */+export function diffCounts(base: Counts, variant: Counts): Counts {+ const out: Counts = {};+ for (const key of new Set([...Object.keys(base), ...Object.keys(variant)])) {+ const a = base[key], b = variant[key];+ if ((typeof a === 'number' || a === undefined) && (typeof b === 'number' || b === undefined) && (a !== undefined || b !== undefined)) out[key] = (b as number ?? 0) - (a as number ?? 0);+ else if (isPlain(a) || isPlain(b)) { if ((a === undefined || isPlain(a)) && (b === undefined || isPlain(b))) out[key] = diffCounts((a ?? {}) as Counts, (b ?? {}) as Counts); }+ }+ return out;+}+const isPlain = (value: unknown): value is Counts => typeof value === 'object' && value !== null && !Array.isArray(value);+/** A main render that also drew a frame-buffer pass draws its canvas pass as the output quad. */+export function passKinds(passes: readonly { render: RenderKind; target: string }[]): PassKind[] {+ const buffered = passes.some(p => p.render === 'main' && p.target === 'framebuffer');+ return passes.map(p => p.render === 'main' && p.target === 'canvas' && buffered ? 'output' : p.render);+}+export interface KindTotals { passes: number; draws: number; triangles: number; pipelines: number }+export function totalsByKind(passes: readonly { kind: PassKind; draws: number; triangles: number; pipelines: ReadonlySet<unknown> }[]): { draws: number; triangles: number; pipelinesUsed: number; byKind: Partial<Record<PassKind, KindTotals>> } {+ const all = new Set<unknown>(), sets = new Map<PassKind, Set<unknown>>(), byKind: Partial<Record<PassKind, KindTotals>> = {};+ let draws = 0, triangles = 0;+ for (const p of passes) {+ const k = byKind[p.kind] ??= { passes: 0, draws: 0, triangles: 0, pipelines: 0 }, set = sets.get(p.kind) ?? new Set();+ k.passes++; k.draws += p.draws; k.triangles += p.triangles; draws += p.draws; triangles += p.triangles;+ for (const pipeline of p.pipelines) { set.add(pipeline); all.add(pipeline); }+ sets.set(p.kind, set); k.pipelines = set.size;+ }+ return { draws, triangles, pipelinesUsed: all.size, byKind };+}diff --git a/scenes/packages/scene-kit/src/testing/probe-report.ts b/scenes/packages/scene-kit/src/testing/probe-report.tsnew file mode 100644index 00000000..dee50fbd--- /dev/null+++ b/scenes/packages/scene-kit/src/testing/probe-report.ts@@ -0,0 +1,57 @@+// Node-side, pure helpers for the count-probe runner (scenes/scripts/count-probe.ts): the per-frame join of GPU encoder+// passes to JS pass records, the standard what-ifs, the compact shape what-ifs are diffed in, and run provenance. They+// live beside probe-core so the portable gate tests them; no page code imports this file.+import type { ProbeResult, ProbeWhatIf } from './probe';++export interface GpuAttachment { w: number; h: number; samples: number; format: string; mip: number; loadOp?: string; storeOp?: string; resolve?: boolean; depthLoadOp?: string; depthStoreOp?: string; stencilLoadOp?: string; stencilStoreOp?: string }+export interface GpuPass { frame: number; encoder: string; color: GpuAttachment[]; depth: GpuAttachment | null; draws: number; setPipeline: number; pipelines: number; bundles: number; bundledDraws: number }+export interface GpuFrame { passes: GpuPass[]; copies: number; submits: number }++/** Per-frame join: renderContext_<id> GPU draws against JS-level draws summed per context id (records split by render call share one). */+export function crossCheck(gpu: GpuFrame, js: readonly { id: number; draws: number }[]) {+ const byContext = new Map<number, number>(), jsById = new Map<number, number>();+ for (const p of gpu.passes) { const m = /^renderContext_(\d+)$/.exec(p.encoder); if (m) byContext.set(Number(m[1]), (byContext.get(Number(m[1])) ?? 0) + p.draws); }+ for (const p of js) jsById.set(p.id, (jsById.get(p.id) ?? 0) + p.draws);+ const jsDraws = js.reduce((n, p) => n + p.draws, 0), gpuDraws = [...byContext.values()].reduce((n, d) => n + d, 0);+ const mismatches = [...jsById].filter(([id, draws]) => (byContext.get(id) ?? 0) !== draws).map(([id, draws]) => ({ id, js: draws, gpu: byContext.get(id) ?? 0 }));+ for (const [id, draws] of byContext) if (!jsById.has(id) && draws) mismatches.push({ id, js: 0, gpu: draws });+ const other = gpu.passes.filter(p => !/^renderContext_\d+$/.test(p.encoder));+ return { equal: jsDraws === gpuDraws && !mismatches.length, jsDraws, gpuDraws, mismatches, gpuPasses: gpu.passes.length,+ splitContexts: [...new Set(gpu.passes.map(p => p.encoder))].filter(e => /^renderContext_/.test(e) && gpu.passes.filter(p => p.encoder === e).length > 1),+ otherPasses: other.length, otherEncoders: [...new Set(other.map(p => p.encoder))], bundledDraws: gpu.passes.reduce((n, p) => n + p.bundledDraws, 0), copies: gpu.copies };+}++export const compact = (r: Pick<ProbeResult, 'totals' | 'bySystem'>) => ({+ draws: r.totals.draws, triangles: r.totals.triangles, pipelinesUsed: r.totals.pipelinesUsed,+ byKind: Object.fromEntries(Object.entries(r.totals.byKind).map(([k, v]) => [k, { draws: v!.draws, triangles: v!.triangles, pipelines: v!.pipelines }])),+ // Systems with no draws this frame are left out, so an empty bucket appearing or not is not a change.+ bySystem: Object.fromEntries(Object.entries(r.bySystem).filter(([, v]) => v.draws).map(([k, v]) => [k, v.draws])),+});+/** The standard count-only what-ifs for a settled baseline: shadow levers where a shadow pass drew, reflection where one drew, every drawing system. */+export function standardWhatIfs(base: Pick<ProbeResult, 'totals' | 'bySystem'>, systems: readonly string[]): { name: string; whatIf: ProbeWhatIf }[] {+ const list: { name: string; whatIf: ProbeWhatIf }[] = [];+ if (base.totals.byKind.shadow) list.push({ name: 'freeze-shadow', whatIf: { freezeShadows: true } }, { name: 'casters-under-300-triangles', whatIf: { dropCasters: { triangles: 300 } } }, { name: 'casters-under-2-texels', whatIf: { dropCasters: { texels: 2 } } });+ if (base.totals.byKind.reflection) list.push({ name: 'skip-reflection', whatIf: { skipRenders: ['reflection'] } });+ for (const system of systems) if (base.bySystem[system]?.draws) list.push({ name: `hide-${system}`, whatIf: { hide: [system] } });+ return list;+}++/**+ * What a run's records were measured on: per scene the build's code chunks (content-hashed names), the viewports and+ * the page policy. `freshPage` is null when records disagree or do not say; `mixed` flags any of that.+ */+export interface RunProvenance { builds: Record<string, string[]>; viewports: string[]; freshPage: boolean | null; mixed: boolean }+export function runProvenance(records: readonly { scene: string; build?: { chunks: readonly string[] }; run?: { viewport: readonly number[]; freshPage: boolean } }[]): RunProvenance {+ const builds: Record<string, string[]> = {}, viewports: string[] = [], pages = new Set<boolean | null>();+ for (const r of records) {+ const build = r.build ? r.build.chunks.join('+') : '(unknown)', list = builds[r.scene] ??= [];+ if (!list.includes(build)) list.push(build);+ const viewport = r.run ? r.run.viewport.join('x') : '(unknown)';+ if (!viewports.includes(viewport)) viewports.push(viewport);+ pages.add(r.run ? r.run.freshPage : null);+ }+ const freshPage = pages.size === 1 ? [...pages][0]! : null;+ return { builds, viewports, freshPage, mixed: freshPage === null || viewports.length > 1 || Object.values(builds).some(list => list.length > 1) };+}+/** The cumulative pipeline cache depends on what the page drew before, so it compares only between two fresh-page runs. */+export const pipelinesComparable = (a: RunProvenance | null | undefined, b: RunProvenance | null | undefined) => a?.freshPage === true && b?.freshPage === true;diff --git a/scenes/packages/scene-kit/src/testing/probe.ts b/scenes/packages/scene-kit/src/testing/probe.tsnew file mode 100644index 00000000..e6f3825d--- /dev/null+++ b/scenes/packages/scene-kit/src/testing/probe.ts@@ -0,0 +1,236 @@+// Test/dev count probe (installTestHooks only; public builds drop it). Wraps the instance `renderer.render` (nested+// shadow and reflection renders re-enter through it), `backend.draw` (renderer.info deltas per RenderContext) and+// `_pipelines.isReady` (draws skipped while a pipeline compiles), records one frame at a time and stops once K frames+// agree. What-ifs are count-only, applied for one probe and always restored, also when installing the probe fails.+// A pass record is one RenderContext within one render call: three keys contexts by attachment format, MRT and call+// depth (RenderContexts.js:41-67), so two same-format renders at one depth (two shadow maps) share a context id.+import { attributionPath, casterSize, classifyRender, classifyTarget, isSmallCaster, passKinds, shadowTexelWorld, summarizeFrames, totalsByKind } from './probe-core';+import type { KindTotals, PassKind, RenderKind } from './probe-core';+/* eslint-disable @typescript-eslint/no-explicit-any */+type Node = any;+export interface ProbeWhatIf { hide?: string[]; freezeShadows?: boolean; skipRenders?: RenderKind[]; dropCasters?: { triangles?: number; texels?: number } }+export interface ProbeOptions { frames?: number; maxFrames?: number; stableFrames?: number; whatIf?: ProbeWhatIf; objects?: number }+export interface ProbeRuntime {+ renderer: any; state: { scene: Node; camera: Node } | null; clock: { frame: number }; pack: { models: Map<string, { scene: Node }> } | null;+ testHooks: Record<string, ((...args: any[]) => unknown) | undefined>; systems: { add(name: string, order: number, fn: () => void): () => void };+}+interface Tally { draws: number; triangles: number; byKind: Partial<Record<PassKind, { draws: number; triangles: number }>> }+export interface ProbeObject { path: string; system: string; asset: string; draws: number; triangles: number; castShadow: boolean; instances: number; skinned: boolean; transparent: boolean }+/** `call` indexes `renders`: the render call that drew the pass. */+export interface ProbePass { id: number; call: number; kind: PassKind; label: string; target: string; width: number; height: number; samples: number; draws: number; triangles: number; pipelines: number; bySystem: Record<string, { draws: number; triangles: number }>; byAsset: Record<string, { draws: number; triangles: number }>; objects?: ProbeObject[] }+export interface ProbeResult {+ frame: number; stable: boolean; stableAfter: number | null; framesObserved: number; notReady: number;+ renders: { label: string; kind: RenderKind; depth: number; parent: number; camera: string }[];+ passes: ProbePass[]; totals: { draws: number; triangles: number; pipelinesUsed: number; byKind: Partial<Record<PassKind, KindTotals>> };+ bySystem: Record<string, Tally>; byAsset: Record<string, Tally>;+ info: { render: Record<string, number>; memory: Record<string, number> }; pipelineCache: number; programs: number;+ drawingBuffer: { width: number; height: number; pixelRatio: number }; whatIf: { applied: ProbeWhatIf; affected: Record<string, number>; dropped?: DroppedCaster[] };+}+/** A caster the small-caster what-if dropped (the first 64 are listed; `affected` counts all): an InstancedMesh drops every instance, and `triangles` covers them all. */+export interface DroppedCaster { path: string; instances: number; triangles: number; texels: number | null }+const DROPPED_LISTED = 64;+interface PassRecord { id: number; call: number; render: RenderKind; label: string; target: string; width: number; height: number; samples: number; draws: number; triangles: number; pipelines: Set<unknown>; objects: Map<Node, { draws: number; triangles: number }> }+interface FrameRecord { frame: number; renders: ProbeResult['renders']; passes: Map<string, PassRecord>; notReady: number; skipped: number; info: Record<string, number> | null }++function walk(root: Node, fn: (node: Node) => void, visibleOnly = false): void {+ const stack = [root];+ while (stack.length) { const node = stack.pop(); if (!node || (visibleOnly && !node.visible)) continue; fn(node); for (let i = node.children?.length - 1; i >= 0; i--) stack.push(node.children[i]); }+}+const triangles = (mesh: Node) => Math.floor((mesh.geometry?.index ? mesh.geometry.index.count : mesh.geometry?.attributes?.position?.count ?? 0) / 3);+const instances = (mesh: Node) => mesh.isInstancedMesh ? mesh.count : mesh.geometry?.isInstancedBufferGeometry ? mesh.geometry.instanceCount ?? 0 : 1;+const transparent = (mesh: Node) => Array.isArray(mesh.material) ? mesh.material.some((m: Node) => m?.transparent) : !!mesh.material?.transparent;+/** Replaces an own or inherited method for the probe; the returned function puts back exactly what was there. */+function patch(target: any, key: string, make: (previous: any) => any): () => void {+ const own = Object.hasOwn(target, key), previous = target[key];+ target[key] = make(previous);+ return () => { if (own) target[key] = previous; else delete target[key]; };+}+const add = (tally: Record<string, Tally>, name: string, kind: PassKind, draws: number, tris: number) => {+ const t = tally[name] ??= { draws: 0, triangles: 0, byKind: {} }, k = t.byKind[kind] ??= { draws: 0, triangles: 0 };+ t.draws += draws; t.triangles += tris; k.draws += draws; k.triangles += tris;+};++export function createRenderProbe(runtime: ProbeRuntime) {+ let active = false, assetGeometry: { pack: unknown; map: Map<unknown, string> } | null = null;+ const scene = () => { const s = runtime.state?.scene; if (!s) throw new Error('Render probe needs a mounted scene'); return s; };+ const lights = () => { const out: Node[] = []; walk(scene(), node => { if (node.isLight && node.shadow) out.push(node); }); return out; };+ const systemRoots = (): Map<Node, string> | null => {+ const hook = runtime.testHooks.probeSystems;if (!hook) return null;+ const map = new Map<Node, string>();+ for (const [name, value] of Object.entries((hook() ?? {}) as Record<string, Node>)) for (const root of Array.isArray(value) ? value : [value]) if (root) map.set(root, name);+ return map;+ };+ const resolver = (systems: Map<Node, string> | null) => {+ const root = scene(), seen = new Map<Node, string>(), named = new Map<Node, string>();+ const system = (o: Node): string => {+ let s = seen.get(o);+ if (s === undefined) {+ if (systems) { let node = o; s = '(unattributed)'; while (node) { const hit = systems.get(node); if (hit) { s = hit; break; } node = node.parent; } }+ else s = attributionPath(o, root, 2);+ seen.set(o, s);+ }+ return s;+ };+ const models = () => {+ if (assetGeometry?.pack !== runtime.pack) { const map = new Map<unknown, string>(); for (const [id, model] of runtime.pack?.models ?? []) walk(model.scene, node => { if (node.isMesh) map.set(node.geometry, id); }); assetGeometry = { pack: runtime.pack, map }; }+ return assetGeometry!.map;+ };+ const asset = (o: Node): string => {+ const known = named.get(o);if (known !== undefined) return known;+ const hooked = runtime.testHooks.probeAsset?.(o);+ const a: string = typeof hooked === 'string' ? hooked : models().get(o.geometry) ?? (o.name || attributionPath(o, root, 8));+ named.set(o, a);return a;+ };+ return { system, asset };+ };+ const signature = (f: FrameRecord) => [...f.passes.values()].map(p => `${p.render}|${p.target}|${p.draws}|${p.triangles}`).join(';') + `;nr${f.notReady}`;++ function applyWhatIf(whatIf: ProbeWhatIf, systems: Map<Node, string> | null, affected: Record<string, number>, dropped: DroppedCaster[]): (() => void)[] {+ const undo: (() => void)[] = [];+ try { applyInto(whatIf, systems, affected, dropped, undo); } catch (error) { for (const step of undo.reverse()) step(); throw error; }+ return undo;+ }+ function applyInto(whatIf: ProbeWhatIf, systems: Map<Node, string> | null, affected: Record<string, number>, dropped: DroppedCaster[], undo: (() => void)[]): void {+ if (whatIf.hide?.length) {+ const named = new Map<string, Node[]>();+ for (const [root, name] of systems ?? []) named.set(name, [...named.get(name) ?? [], root]);+ for (const name of whatIf.hide) if (!named.has(name)) throw new Error(`Unknown probe system ${name}`);+ affected.hidden = 0;+ // Scenes that write visibility every frame (Foundry's entity sets) cannot undo the hide: `visible` reads false for+ // the probe while writes are kept, and the last write is restored as a plain property.+ for (const name of whatIf.hide) for (const root of named.get(name)!) {+ let kept = root.visible;+ Object.defineProperty(root, 'visible', { configurable: true, enumerable: true, get: () => false, set: (value: boolean) => { kept = value; } });+ affected.hidden++; undo.push(() => { delete root.visible; root.visible = kept; });+ }+ }+ if (whatIf.freezeShadows) {+ affected.frozenLights = 0;+ for (const light of lights()) if (light.castShadow) {+ const s = light.shadow, was = s.autoUpdate; s.autoUpdate = false; s.needsUpdate = false; affected.frozenLights++;+ undo.push(() => { s.autoUpdate = was; s.needsUpdate = true; });+ }+ }+ if (whatIf.dropCasters) {+ const texelWorld = shadowTexelWorld(lights().find(l => l.castShadow)?.shadow);+ Object.assign(affected, { casters: 0, dropped: 0, droppedInstanced: 0, droppedInstances: 0, droppedTriangles: 0 });+ if (whatIf.dropCasters.texels !== undefined) affected.texelWorld = texelWorld ?? 0;+ walk(scene(), node => {+ if (!node.isMesh || !node.castShadow) return;+ affected.casters!++;+ if (!isSmallCaster(node, { ...whatIf.dropCasters, texelWorld })) return;+ const n = instances(node), tris = triangles(node) * n;+ node.castShadow = false; affected.dropped!++; affected.droppedInstances! += n; affected.droppedTriangles! += tris;+ if (node.isInstancedMesh || node.geometry?.isInstancedBufferGeometry) affected.droppedInstanced!++;+ if (dropped.length < DROPPED_LISTED) dropped.push({ path: attributionPath(node, scene(), 8), instances: n, triangles: tris, texels: casterSize(node, texelWorld).texels });+ undo.push(() => { node.castShadow = true; });+ }, true);+ }+ }++ /** Starts a probe; `done` or `fail` is called once from the system loop. Returns a cancel that restores without finishing. */+ function run(options: ProbeOptions, done: (result: ProbeResult) => void, fail: (error: Error) => void): () => void {+ if (active) throw new Error('A render probe is already running');+ const renderer = runtime.renderer;if (!renderer) throw new Error('Render probe needs a renderer');+ const frames = options.frames ?? 8, maxFrames = options.maxFrames ?? 600, stableFrames = options.stableFrames ?? 3, whatIf = options.whatIf ?? {};+ const systems = systemRoots(), affected: Record<string, number> = {}, dropped: DroppedCaster[] = [], skip = new Set(whatIf.skipRenders ?? []);+ const undo = applyWhatIf(whatIf, systems, affected, dropped);+ const stack: { kind: RenderKind; index: number }[] = [], signatures: string[] = [], restores: (() => void)[] = [];+ let cur: FrameRecord | null = null, last: FrameRecord | null = null, observed = 0, finished = false, shadowLights: Node[] = [];+ // Removes the system and the patches, then undoes the what-if, in reverse: on finish, on cancel and on a failed install.+ const cleanup = () => { finished = true; active = false; for (const restore of restores.splice(0).reverse()) restore(); for (const step of undo.splice(0).reverse()) step(); };+ try {+ shadowLights = lights();+ restores.push(patch(renderer, 'render', previous => function (this: unknown, ...args: any[]) {+ const s = args[0], depth = stack.length, kind = classifyRender(s?.name ?? '', depth, s === runtime.state?.scene);+ if (depth > 0 && skip.has(kind)) { if (cur) cur.skipped++; return undefined; }+ let index = -1;+ if (cur) { index = cur.renders.length; cur.renders.push({ label: s?.name || '(root)', kind, depth, parent: stack.at(-1)?.index ?? -1, camera: args[1] === runtime.state?.camera ? 'main' : args[1]?.type ?? 'camera' }); }+ stack.push({ kind, index });+ try { return previous.apply(this, args); }+ finally { stack.pop(); if (!stack.length && cur) { const r = renderer.info?.render; if (r) cur.info = { calls: r.calls, drawCalls: r.drawCalls, triangles: r.triangles, frame: renderer.info.frame }; } }+ }));+ restores.push(patch(renderer.backend, 'draw', previous => function (this: unknown, ro: any, info: any) {+ const d0 = info.render.drawCalls, t0 = info.render.triangles, result = previous.call(this, ro, info);+ if (cur) {+ const ctx = ro.context, top = stack.at(-1), call = top?.index ?? -1, key = `${ctx.id}|${call}`;let p = cur.passes.get(key);+ if (!p) {+ const maps = new Set(shadowLights.map(l => l.shadow.map).filter(Boolean));+ p = { id: ctx.id, call, render: top?.kind ?? 'offscreen', label: top && cur.renders[top.index]?.label || '?', target: classifyTarget(ctx.renderTarget, maps), width: ctx.width, height: ctx.height, samples: ctx.sampleCount ?? 1, draws: 0, triangles: 0, pipelines: new Set(), objects: new Map() };+ cur.passes.set(key, p);+ }+ const dd = info.render.drawCalls - d0, dt = info.render.triangles - t0, o = p.objects.get(ro.object) ?? { draws: 0, triangles: 0 };+ p.draws += dd; p.triangles += dt; p.pipelines.add(ro.pipeline); o.draws += dd; o.triangles += dt; p.objects.set(ro.object, o);+ }+ return result;+ }));+ restores.push(patch(renderer._pipelines, 'isReady', previous => function (this: unknown, ro: any) { const ok = previous.call(this, ro); if (!ok && cur) cur.notReady++; return ok; }));+ restores.push(runtime.systems.add('kiln-render-probe', 10001, () => {+ if (finished) return;+ try {+ if (cur) {+ signatures.push(signature(cur)); last = cur; observed++;+ const s = summarizeFrames(signatures, { stableFrames, key: x => x });+ if ((observed >= frames && s.stable && cur.notReady === 0) || observed >= maxFrames) {+ const result = build(last, s.stable && cur.notReady === 0, s.stable ? s.stableAfter : null, observed);+ cleanup(); done(result); return;+ }+ }+ cur = { frame: runtime.clock.frame, renders: [], passes: new Map(), notReady: 0, skipped: 0, info: null };+ } catch (error) { cleanup(); fail(error as Error); }+ }));+ } catch (error) { cleanup(); throw error; }+ active = true;++ function build(f: FrameRecord, stable: boolean, stableAfter: number | null, framesObserved: number): ProbeResult {+ const names = resolver(systems), list = [...f.passes.values()], kinds = passKinds(list.map(p => ({ render: p.render, target: p.target })));+ const bySystem: Record<string, Tally> = {}, byAsset: Record<string, Tally> = {};+ const passes = list.map((p, i): ProbePass => {+ const kind = kinds[i]!, sys: Record<string, { draws: number; triangles: number }> = {}, assets: Record<string, { draws: number; triangles: number }> = {}, objects: ProbeObject[] = [];+ for (const [o, n] of p.objects) {+ const system = kind === 'output' ? '(output)' : names.system(o), asset = kind === 'output' ? '(output)' : names.asset(o);+ (sys[system] ??= { draws: 0, triangles: 0 }).draws += n.draws; sys[system]!.triangles += n.triangles;+ (assets[asset] ??= { draws: 0, triangles: 0 }).draws += n.draws; assets[asset]!.triangles += n.triangles;+ add(bySystem, system, kind, n.draws, n.triangles); add(byAsset, asset, kind, n.draws, n.triangles);+ if (options.objects) objects.push({ path: attributionPath(o, runtime.state?.scene ?? null, 8), system, asset, draws: n.draws, triangles: n.triangles, castShadow: !!o.castShadow, instances: instances(o), skinned: !!o.isSkinnedMesh, transparent: transparent(o) });+ }+ objects.sort((a, b) => b.draws - a.draws || b.triangles - a.triangles);+ return { id: p.id, call: p.call, kind, label: p.label, target: p.target, width: p.width, height: p.height, samples: p.samples, draws: p.draws, triangles: p.triangles, pipelines: p.pipelines.size, bySystem: sys, byAsset: assets, ...(options.objects ? { objects: objects.slice(0, options.objects) } : {}) };+ });+ if (whatIf.skipRenders?.length) affected.skippedRenders = f.skipped;+ const memory = renderer.info?.memory ?? {};+ return {+ frame: f.frame, stable, stableAfter, framesObserved, notReady: f.notReady, renders: f.renders, passes,+ totals: totalsByKind(list.map((p, i) => ({ kind: kinds[i]!, draws: p.draws, triangles: p.triangles, pipelines: p.pipelines }))), bySystem, byAsset,+ info: { render: f.info ?? {}, memory: { ...memory } }, pipelineCache: renderer._pipelines?.caches?.size ?? 0, programs: memory.programs ?? 0,+ drawingBuffer: { width: renderer.domElement?.width ?? 0, height: renderer.domElement?.height ?? 0, pixelRatio: renderer.getPixelRatio?.() ?? 1 },+ whatIf: { applied: whatIf, affected, ...(whatIf.dropCasters ? { dropped } : {}) },+ };+ }+ return () => { if (!finished) cleanup(); };+ }++ /** Meshes, casters, instancing and shadow lights, overall and per probe system (replaces the devtools-hook census). */+ function sceneSummary() {+ const root = scene(), names = resolver(systemRoots()), visible = new Set<Node>();+ walk(root, node => visible.add(node), true);+ const empty = () => ({ meshes: 0, visibleMeshes: 0, casters: 0, instanced: 0, instances: 0, skinned: 0, transparent: 0, triangles: 0 });+ const total = { ...empty(), receivers: 0 }, bySystem: Record<string, ReturnType<typeof empty>> = {};+ walk(root, node => {+ if (!node.isMesh) return;+ const shown = visible.has(node), n = instances(node), s = bySystem[runtime.testHooks.probeSystems ? names.system(node) : attributionPath(node, root, 2)] ??= empty();+ for (const t of [total, s]) {+ t.meshes++; if (!shown) continue;+ t.visibleMeshes++; t.instances += n; t.triangles += triangles(node) * n;+ if (node.castShadow) t.casters++;+ if (node.isInstancedMesh || node.geometry?.isInstancedBufferGeometry) t.instanced++;+ if (node.isSkinnedMesh) t.skinned++;+ if (transparent(node)) t.transparent++;+ }+ if (shown && node.receiveShadow) total.receivers++;+ });+ const pick = (c: Node) => Object.fromEntries(['type', 'left', 'right', 'top', 'bottom', 'fov', 'near', 'far'].filter(k => c?.[k] !== undefined).map(k => [k, c[k]]));+ return { ...total, lights: lights().map(l => ({ name: l.name, type: l.type, castShadow: !!l.castShadow, mapSize: [l.shadow.mapSize?.x, l.shadow.mapSize?.y], autoUpdate: l.shadow.autoUpdate, camera: pick(l.shadow.camera), texelWorld: shadowTexelWorld(l.shadow) })), bySystem };+ }+ return { run, sceneSummary };+}diff --git a/scenes/packages/scene-kit/tests/collision/collision.test.ts b/scenes/packages/scene-kit/tests/collision/collision.test.tsindex 259a6343..d39b2b14 100644--- a/scenes/packages/scene-kit/tests/collision/collision.test.ts+++ b/scenes/packages/scene-kit/tests/collision/collision.test.ts@@ -2,6 +2,9 @@ import { describe, expect, test } from 'bun:test';import { BoxGeometry, Group, Mesh, MeshBasicMaterial, Vector3 } from 'three/webgpu';import { createCollisionWorld, fixedStep, stepCapsule } from '../../src/collision/index';import fixture from './pilot-boxes.json';+import { shadowStandIns } from '../../src/shadows/stand-ins';+import { passStandIn } from '../../src/shadows/pass';+import { mergeRigidByMaterial } from '../../src/instancing/rigid-merge';function box(x: number, y: number, z: number, width = 2, height = 2, depth = 2) {const mesh = new Mesh(new BoxGeometry(width, height, depth), new MeshBasicMaterial());@@ -61,6 +64,23 @@ describe('U-09 collision', () => {expect(world.rayDistance(new Vector3(0, 1, 0), new Vector3(5, 1, 0))).toBeCloseTo(1, 6);world.dispose(); world.dispose(); expect(world.add(box(0, 0, 0))).toBeNull();});+ test('shadow and pass stand-ins never become colliders', () => {+ const world = createCollisionWorld(), root = new Group(), wall = box(0, 1, 0); wall.castShadow = true; root.add(wall);+ const holder = new Group(); holder.position.x = 10; root.add(holder);+ const shadow = shadowStandIns(root, { layer: 29, isAnchor: () => false }), pass = passStandIn(wall, { layer: 28, parent: holder });+ expect(shadow.proxies).toHaveLength(1); expect(pass.stats.meshes).toBe(1);+ const c = world.add(root)!; expect(c.geometry.getAttribute('position').count).toBe(36);+ expect(world.rayDistance(new Vector3(10, 1, -5), new Vector3(10, 1, 5))).toBeCloseTo(10, 6);+ expect(world.rayDistance(new Vector3(0, 1, -5), new Vector3(0, 1, 5))).toBeCloseTo(4, 6);+ world.dispose(); shadow.restore(); pass.restore();+ });+ test('RF-6 a collider built after a rigid merge holds the hidden sources once, never the merged copy', () => {+ const world = createCollisionWorld(), root = new Group(), material = new MeshBasicMaterial();+ for (const x of [0, 4]) { const g = new BoxGeometry(2, 2, 2); g.clearGroups(); const m = new Mesh(g, material); m.position.x = x; root.add(m); }+ const merge = mergeRigidByMaterial(root, { isAnchor: () => false }); expect(merge.merged).toHaveLength(1);+ expect(world.add(root)!.geometry.getAttribute('position').count).toBe(72);+ world.dispose(); merge.restore();+ });});const rules = { radius: .3, height: 1.9, pace: 1.05, runPace: 1.8, gravity: 18, terminal: -10, stepUp: .22, stepProbe: .25, clampX: 34.8, clampZ: 34.8 };const state = () => ({ position: new Vector3(0, 10, 0), velocityY: 0, yaw: 0, speedXZ: 0, status: '' });diff --git a/scenes/packages/scene-kit/tests/instancing/rigid-merge.test.ts b/scenes/packages/scene-kit/tests/instancing/rigid-merge.test.tsnew file mode 100644index 00000000..3887575c--- /dev/null+++ b/scenes/packages/scene-kit/tests/instancing/rigid-merge.test.ts@@ -0,0 +1,183 @@+import { expect, test } from 'bun:test';+import { Box3, BoxGeometry, BufferAttribute, BufferGeometry, Group, InstancedMesh, InterleavedBuffer, InterleavedBufferAttribute, Matrix3, Matrix4, Mesh, MeshPhysicalMaterial, MeshStandardMaterial, Scene, SkinnedMesh, SphereGeometry, Vector3 } from 'three/webgpu';+import type { Material, Object3D } from 'three/webgpu';+import { bakeRigidGeometry, mergeRigidByMaterial } from '../../src/instancing/rigid-merge';+import { createFrameGraph, freezeTransforms } from '../../src/instancing/core';+import type { InstanceOwner } from '../../src/instancing/core';+const isAnchor=(n:Object3D)=>/^Joint_/.test(n.name);+const box=(x=1,y=1,z=1)=>{const g=new BoxGeometry(x,y,z);g.clearGroups();return g;};+const node=(name:string,parent:Object3D|null,x=0,y=0,z=0)=>{const g=new Group();g.name=name;g.position.set(x,y,z);parent?.add(g);return g;};+const mesh=(name:string,material:Material|Material[],parent:Object3D,x=0,y=0,z=0,geometry:BufferGeometry=box())=>{const m=new Mesh(geometry,material);m.name=name;m.position.set(x,y,z);parent.add(m);return m;};+const tris=(g:BufferGeometry)=>(g.index?g.index.count:g.attributes.position!.count)/3;+const drawn=(root:Object3D)=>{const out:Mesh[]=[];root.traverseVisible(o=>{if((o as Mesh).isMesh)out.push(o as Mesh);});return out;};+const allMeshes=(root:Object3D)=>{let n=0;root.traverse(o=>{if((o as Mesh).isMesh)n++;});return n;};+const worldBox=(root:Object3D)=>{root.updateMatrixWorld(true);const b=new Box3(),v=new Vector3();for(const m of drawn(root)){const p=m.geometry.attributes.position!;for(let i=0;i<p.count;i++)b.expandByPoint(v.fromBufferAttribute(p,i).applyMatrix4(m.matrixWorld));}return b;};+const anchorOf=(m:Object3D,root:Object3D)=>{let n=m.parent!;while(n!==root&&!isAnchor(n))n=n.parent!;return n;};+const bits=(a:ArrayLike<number>)=>Array.from(new Uint32Array(Float32Array.from(a).buffer));+const slice=(g:BufferGeometry,name:string,from:number,count:number)=>{const a=g.getAttribute(name)!;return Array.from(a.array as Float32Array).slice(from*a.itemSize,(from+count)*a.itemSize);};+/** A farmhouse-like placement: shell parts sharing materials, a door anchor with hardware, a nested anchor and every never-merge case. */+function house(){+ const stone=new MeshStandardMaterial({name:'Stone'}),trim=new MeshStandardMaterial({name:'Trim'}),wood=new MeshStandardMaterial({name:'Wood'}),iron=new MeshStandardMaterial({name:'Iron'});+ const glass=new MeshStandardMaterial({name:'Glass',transparent:true,opacity:.4}),clear=new MeshPhysicalMaterial({name:'Clear',transmission:1});+ const root=node('House',null,10,0,-4);root.rotation.y=.5;const shell=node('Shell',root,1,0,0);shell.rotation.z=.2;shell.scale.set(1,2,1);+ const merged=[mesh('ShellA',stone,shell),mesh('ShellB',stone,shell,2,0,0),mesh('Roof',stone,root,0,3,0)];+ const parentA=mesh('ParentA',stone,root,0,0,5),parentB=mesh('ParentB',stone,root,1,0,5);merged.push(mesh('ChildA',stone,parentA,0,1,0),mesh('ChildB',stone,parentB,0,1,0));+ const shadowed=[mesh('ShadowA',stone,root,0,0,8),mesh('ShadowB',stone,root,2,0,8)];for(const m of shadowed)m.castShadow=true;+ const kept=[mesh('Trim',trim,shell,0,1,0),parentA,parentB,mesh('GlassA',glass,shell,0,0,1),mesh('GlassB',glass,shell,1,0,1),mesh('ClearA',clear,root,0,1,1),mesh('ClearB',clear,root,1,1,1),+ mesh('ExtrasA',stone,root,0,2,2),mesh('ExtrasB',stone,root,1,2,2),mesh('MultiA',[stone,trim],root,0,0,3),mesh('MultiB',[stone,trim],root,1,0,3),mesh('GroupedA',stone,root,0,0,4,new BoxGeometry()),mesh('GroupedB',stone,root,1,0,4,new BoxGeometry()),+ mesh('Hidden',stone,shell,0,-2,0),mesh('Veiled',stone,node('Shutters',root,0,0,6),0,0,0),mesh('MorphA',stone,root,0,4,0,box()),mesh('MorphB',stone,root,1,4,0,box()),mesh('Ranged',stone,root,2,4,0,box()),mesh('Kept',stone,root,3,4,0),+ mesh('Ordered',stone,root,0,5,0),mesh('Layered',stone,root,1,5,0),mesh('Unculled',stone,root,2,5,0),mesh('Joint_LampA',stone,root,0,6,0),mesh('Joint_LampB',stone,root,1,6,0)];+ const byName=(n:string)=>kept.find(m=>m.name===n)!;+ byName('ExtrasA').userData={name:'ExtrasA',rowanComponents:{}};byName('ExtrasB').userData={optimization:{}};byName('Hidden').visible=false;byName('Veiled').parent!.visible=false;merged[0]!.userData={name:'ShellA'};+ for(const n of ['MorphA','MorphB'])byName(n).geometry.morphAttributes.position=[new BufferAttribute(new Float32Array(72),3)];+ byName('Ranged').geometry.setDrawRange(0,12);byName('Ordered').renderOrder=1;byName('Layered').layers.set(2);byName('Unculled').frustumCulled=false;+ for(const n of ['SkinA','SkinB']){const s=new SkinnedMesh(box(),stone);s.name=n;root.add(s);kept.push(s);}+ for(const n of ['InstA','InstB']){const s=new InstancedMesh(box(),stone,2);s.name=n;root.add(s);kept.push(s);}+ const door=node('Joint_FrontDoor',root,3,0,0);door.rotation.y=.3;kept.push(mesh('Leaf',wood,door,.5,1,0));+ merged.push(mesh('HingeA',iron,door,0,.5,0),mesh('HingeB',iron,door,0,1.5,0),mesh('KnobPlate',iron,node('Knob',door,.8,1,.1)));+ const inner=node('Joint_Inner',door,0,2,0);merged.push(mesh('InnerA',stone,inner),mesh('InnerB',stone,inner,0,1,0));+ root.updateMatrixWorld(true);+ return{root,door,inner,anchors:[root,door,inner] as Object3D[],merged:[...merged,...shadowed],kept,materials:{stone,iron}};+}+const keepKept=(m:Object3D)=>m.name==='Kept';+test('anchors keep identity, names, transforms and children; no merged mesh spans two anchors',()=>{+ const h=house(),before=h.anchors.map(a=>({a,name:a.name,parent:a.parent,children:[...a.children],matrix:a.matrix.clone(),flags:[a.matrixAutoUpdate,a.matrixWorldAutoUpdate]})),total=allMeshes(h.root);+ const r=mergeRigidByMaterial(h.root,{isAnchor,keepMesh:keepKept});+ for(const b of before){expect(b.a.name).toBe(b.name);expect(b.a.parent).toBe(b.parent);expect(b.children.every((c,i)=>b.a.children[i]===c)).toBe(true);expect(b.a.matrix.equals(b.matrix)).toBe(true);expect([b.a.matrixAutoUpdate,b.a.matrixWorldAutoUpdate]).toEqual(b.flags);}+ expect(h.root.getObjectByName('Joint_FrontDoor')).toBe(h.door);expect(h.root.getObjectByName('ShellA')).toBe(h.merged[0]!);+ expect(r.stats).toEqual({sourceMeshes:12,mergedMeshes:4,keptMeshes:total-12,groups:9,triangles:12*12});+ expect(r.sources.map(s=>s.name).sort()).toEqual(h.merged.map(m=>m.name).sort());+ for(const m of r.merged){+ expect(h.anchors).toContain(m.parent!);expect(m.name).toMatch(/^Merged (House|Joint_FrontDoor|Joint_Inner)\/(Stone|Iron)$/);expect(m.matrix.equals(new Matrix4())).toBe(true);+ expect(m.userData.kilnMerged).toBe(true);expect(m.matrixWorld.equals(m.parent!.matrixWorld)).toBe(true);expect(m.geometry.boundingBox).not.toBeNull();expect(m.geometry.boundingSphere).not.toBeNull();+ const own=r.sources.filter(s=>anchorOf(s,h.root)===m.parent&&s.material===m.material&&s.castShadow===m.castShadow);+ expect(own.reduce((n,s)=>n+tris(s.geometry),0)).toBe(tris(m.geometry));+ }+ expect(r.merged.filter(m=>m.castShadow).length).toBe(1);+});+test('singletons, transparent, transmissive, extras, multi-material, grouped, skinned, morphed, instanced, parent, anchor, hidden, ranged and kept meshes are left alone',()=>{+ const h=house(),r=mergeRigidByMaterial(h.root,{isAnchor,keepMesh:keepKept});+ const names=r.sources.map(s=>s.name);for(const m of h.kept){expect(names).not.toContain(m.name);expect(m.visible).toBe(m.name!=='Hidden');}+ for(const m of h.merged)expect(m.visible).toBe(false);+});+test('triangle totals and world-space bounds are equal before and after',()=>{+ const h=house(),count=(root:Object3D)=>drawn(root).reduce((n,m)=>n+tris(m.geometry),0),t0=count(h.root),b0=worldBox(h.root);+ const r=mergeRigidByMaterial(h.root,{isAnchor});expect(r.stats.triangles).toBeGreaterThan(0);+ expect(count(h.root)).toBe(t0);const b1=worldBox(h.root);+ for(const k of ['x','y','z'] as const){expect(b1.min[k]).toBeCloseTo(b0.min[k],5);expect(b1.max[k]).toBeCloseTo(b0.max[k],5);}+ const door=new Box3(),probe=new Box3();h.door.updateMatrixWorld(true);for(const m of r.merged.filter(m=>m.parent===h.door))door.union(probe.setFromObject(m,true));+ const src=new Box3();for(const s of r.sources.filter(s=>anchorOf(s,h.root)===h.door))src.union(probe.setFromObject(s,true));+ expect(door.min.distanceTo(src.min)).toBeLessThan(1e-5);expect(door.max.distanceTo(src.max)).toBeLessThan(1e-5);+});+test('identity and pure-translation paths are bit-exact; tangent w is kept',()=>{+ const root=node('R',null),mat=new MeshStandardMaterial(),g1=box(),g2=box(1,2,3);g1.computeTangents();g2.computeTangents();+ const tw=g1.getAttribute('tangent')!;tw.setW(0,-1);g1.attributes.normal!.setXYZ(0,.3,.4,0);g1.attributes.position!.setY(0,-0);// a short normal and a negative zero survive only a copy+ const a=mesh('a',mat,root,0,0,0,g1),b=mesh('b',mat,root,0,0,0,g2),c=mesh('c',mat,node('T',root,.1,-2.7,3.3),1.5,0,0,g1);root.updateMatrixWorld(true);+ const r=mergeRigidByMaterial(root,{isAnchor});expect(r.merged.length).toBe(1);const g=r.merged[0]!.geometry,n=g1.attributes.position!.count;+ for(const name of ['position','normal','uv','tangent'])for(const [src,at] of [[a,0],[b,n]] as const)expect(bits(slice(g,name,at,src.geometry.attributes.position!.count))).toEqual(bits(src.geometry.getAttribute(name)!.array as Float32Array));+ for(const name of ['normal','uv','tangent'])expect(bits(slice(g,name,2*n,n))).toEqual(bits(g1.getAttribute(name)!.array as Float32Array));+ const t=new Vector3().setFromMatrixPosition(c.matrixWorld),p=g1.attributes.position!.array as Float32Array;+ expect(bits(slice(g,'position',2*n,n))).toEqual(bits(Array.from(p,(v,i)=>v+t.getComponent(i%3))));+ expect(slice(g,'tangent',0,1)[3]).toBe(-1);expect(Array.from(g.index!.array).slice(0,g1.index!.count)).toEqual(Array.from(g1.index!.array));+});+test('a mirrored transform flips winding so faces stay front-facing',()=>{+ const root=node('R',null),mat=new MeshStandardMaterial(),m=node('M',root);m.scale.set(-1,1,1);m.rotation.y=.4;mesh('a',mat,m,1,0,0);mesh('b',mat,m,-1,0,0);root.updateMatrixWorld(true);+ const facing=(g:BufferGeometry,matrix=m.matrixWorld)=>{const p=g.attributes.position!,nn=g.attributes.normal!,i=g.index!,nm=new Matrix3().getNormalMatrix(matrix),v=[0,1,2].map(()=>new Vector3()),nv=new Vector3();let agree=0,count=0;for(let k=0;k<i.count;k+=3){for(let j=0;j<3;j++)v[j]!.fromBufferAttribute(p,i.getX(k+j)).applyMatrix4(matrix);nv.fromBufferAttribute(nn,i.getX(k)).applyMatrix3(nm);const f=v[1]!.clone().sub(v[0]!).cross(v[2]!.clone().sub(v[0]!));if(f.dot(nv)>0)agree++;count++;}return agree/count;};+ expect(facing(box())).toBe(0);+ const r=mergeRigidByMaterial(root,{isAnchor});expect(r.merged.length).toBe(1);expect(facing(r.merged[0]!.geometry,root.matrixWorld)).toBe(1);+});+test('other transforms carry normals by the normal matrix and tangent xyz by the linear part, keeping w',()=>{+ const root=node('R',null),mat=new MeshStandardMaterial(),s=node('S',root,1,2,3),g=new SphereGeometry(1,6,4);s.rotation.set(.3,.5,.1);s.scale.set(1,3,.5);g.computeTangents();g.getAttribute('tangent')!.setW(1,-1);+ const a=mesh('a',mat,s,0,0,0,g);mesh('b',mat,s,2,0,0,g);root.updateMatrixWorld(true);const out=mergeRigidByMaterial(root,{isAnchor}).merged[0]!.geometry;+ const nm=new Matrix3().getNormalMatrix(a.matrixWorld),lin=new Matrix3().setFromMatrix4(a.matrixWorld),u=new Vector3(),w=new Vector3(),t=g.getAttribute('tangent')!,o=out.getAttribute('tangent')!;+ for(let i=0;i<g.attributes.position!.count;i++){u.fromBufferAttribute(g.attributes.normal!,i).applyMatrix3(nm).normalize();w.fromBufferAttribute(out.attributes.normal!,i);expect(u.distanceTo(w)).toBeLessThan(1e-6);+ u.set(t.getX(i),t.getY(i),t.getZ(i)).applyMatrix3(lin).normalize();w.set(o.getX(i),o.getY(i),o.getZ(i));expect(u.distanceTo(w)).toBeLessThan(1e-6);expect(o.getW(i)).toBe(t.getW(i));}+});+test('a mirrored tangent-bearing part stays unmerged',()=>{+ const root=node('R',null),mat=new MeshStandardMaterial(),g=box();g.computeTangents();const a=mesh('a',mat,root,0,0,0,g),b=mesh('b',mat,root,2,0,0,g),c=mesh('c',mat,root,4,0,0,g);c.scale.x=-1;+ const r=mergeRigidByMaterial(root,{isAnchor});expect(r.sources.map(s=>s.name)).toEqual([a.name,b.name]);expect(c.visible).toBe(true);expect(r.stats.keptMeshes).toBe(1);+});+test('interleaved, normalised and non-indexed input is read through the accessors into Float32 attributes',()=>{+ const interleaved=()=>{const s=box(),n=s.attributes.position!.count,data=new Float32Array(n*8);for(let i=0;i<n;i++){data.set([s.attributes.position!.getX(i),s.attributes.position!.getY(i),s.attributes.position!.getZ(i)],i*8);data.set([s.attributes.normal!.getX(i),s.attributes.normal!.getY(i),s.attributes.normal!.getZ(i)],i*8+3);data.set([s.attributes.uv!.getX(i),s.attributes.uv!.getY(i)],i*8+6);}+ const ib=new InterleavedBuffer(data,8),g=new BufferGeometry();g.setAttribute('position',new InterleavedBufferAttribute(ib,3,0));g.setAttribute('normal',new InterleavedBufferAttribute(ib,3,3));g.setAttribute('uv',new InterleavedBufferAttribute(ib,2,6));+ g.setAttribute('color',new BufferAttribute(new Uint8Array(n*4).map((_,i)=>i%256),4,true));g.setIndex(s.index);return g;};+ const root=node('R',null),mat=new MeshStandardMaterial(),g=interleaved(),before=Float32Array.from((g.attributes.position as InterleavedBufferAttribute).data.array);+ const a=mesh('a',mat,root,0,0,0,g),b=mesh('b',mat,root,0,2,0,interleaved());b.rotation.x=.7;root.updateMatrixWorld(true);+ const r=mergeRigidByMaterial(root,{isAnchor}),m=r.merged[0]!.geometry,n=g.attributes.position!.count;expect(r.sources.map(s=>s.name)).toEqual([a.name,b.name]);+ for(const name of ['position','normal','uv','color']){const out=m.getAttribute(name)!;expect(out.array).toBeInstanceOf(Float32Array);expect(out.normalized).toBe(false);expect((out as InterleavedBufferAttribute).isInterleavedBufferAttribute).toBeUndefined();}+ for(let i=0;i<n;i++){expect(m.attributes.position!.getY(i)).toBe(g.attributes.position!.getY(i));expect(m.attributes.uv!.getX(n+i)).toBe(g.attributes.uv!.getX(i));expect(m.attributes.color!.getW(n+i)).toBeCloseTo(g.attributes.color!.getW(i),7);}+ const v=new Vector3();for(let i=0;i<n;i++){v.fromBufferAttribute(b.geometry.attributes.position!,i).applyMatrix4(b.matrix);expect(m.attributes.position!.getY(n+i)).toBeCloseTo(v.y,6);}+ expect((g.attributes.position as InterleavedBufferAttribute).data.array).toEqual(before);+ const flat=new BufferGeometry();flat.setAttribute('position',new BufferAttribute(new Float32Array([0,0,0,1,0,0,0,1,0]),3));+ const baked=bakeRigidGeometry([mesh('f1',mat,root,0,0,0,flat),mesh('f2',mat,root,5,0,0,flat)],root,{attributes:'all'});expect(Array.from(baked.index!.array)).toEqual([0,1,2,3,4,5]);expect(baked.attributes.position!.getX(4)).toBe(6);+});+test('the index switches to Uint32 above 65535 vertices',()=>{+ const root=node('R',null),mat=new MeshStandardMaterial(),soup=(n:number)=>{const g=new BufferGeometry();g.setAttribute('position',new BufferAttribute(new Float32Array(n*3).map((_,i)=>i%7),3));return g;};+ const small=bakeRigidGeometry([mesh('a',mat,root,0,0,0,soup(32766)),mesh('b',mat,root,0,0,0,soup(32769))],root,{attributes:'all'});+ expect(small.index!.array).toBeInstanceOf(Uint16Array);expect(small.index!.count).toBe(65535);expect(small.index!.getX(65534)).toBe(65534);+ const large=bakeRigidGeometry([mesh('c',mat,root,0,0,0,soup(32766)),mesh('d',mat,root,0,0,0,soup(32772))],root,{attributes:'all'});+ expect(large.index!.array).toBeInstanceOf(Uint32Array);expect(large.index!.getX(65537)).toBe(65537);+});+test('position bakes recompose auto-updated nodes, read frozen matrices and leave the graph untouched',()=>{+ const root=node('R',null),mat=new MeshStandardMaterial(),a=node('A',root),f=node('F',root);a.position.x=5;f.matrixAutoUpdate=false;f.matrix.makeTranslation(7,0,0);+ const g1=box();g1.computeTangents();const g=bakeRigidGeometry([mesh('a',mat,a,0,0,0,g1),mesh('f',mat,f)],root,{attributes:'position'});+ expect(Object.keys(g.attributes)).toEqual(['position']);expect(g.index!.count).toBe(72);expect(a.matrix.elements[12]).toBe(0);expect(f.position.x).toBe(0);+ const xs=(from:number)=>{const b=new Box3();for(let i=from;i<from+24;i++)b.expandByPoint(new Vector3().fromBufferAttribute(g.attributes.position!,i));return(b.min.x+b.max.x)/2;};+ expect(xs(0)).toBe(5);expect(xs(24)).toBe(7);expect(()=>bakeRigidGeometry([mesh('x',mat,node('Other',null))],root,{attributes:'position'})).toThrow();+});+test('restore shows sources, removes merged meshes and disposes only owned geometry',()=>{+ const h=house(),r=mergeRigidByMaterial(h.root,{isAnchor,keepMesh:keepKept});let owned=0,borrowed=0;+ for(const m of r.merged)m.geometry.addEventListener('dispose',()=>owned++);for(const s of r.sources)s.geometry.addEventListener('dispose',()=>borrowed++);let materials=0;h.materials.stone.addEventListener('dispose',()=>materials++);+ r.restore();r.restore();expect(owned).toBe(4);expect(borrowed).toBe(0);expect(materials).toBe(0);+ expect(r.sources.every(s=>s.visible)).toBe(true);expect(r.merged.every(m=>m.parent===null)).toBe(true);expect(h.kept.find(m=>m.name==='Hidden')!.visible).toBe(false);+});+test('identical placements share cached geometry that restore never disposes',()=>{+ const wood=new MeshStandardMaterial({name:'Wood'}),iron=new MeshStandardMaterial({name:'Iron'});+ const gate=(x:number)=>{const g=node('Gate',null,x,0,0);g.rotation.y=x;mesh('PostL',wood,g,-1,0,0);mesh('PostR',wood,g,1,0,0);const leaf=node('Joint_GateLeaf',g,-1,0,0);mesh('Plank',wood,leaf,1,0,0);mesh('Rail',wood,leaf,1,1,0);mesh('HingeA',iron,leaf);mesh('HingeB',iron,leaf,0,1,0);g.updateMatrixWorld(true);return g;};+ const cache=new Map<string,BufferGeometry>(),cacheKey=(a:Object3D)=>a.name==='Gate'?'gate':a.name==='Joint_GateLeaf'?'gate/leaf':undefined;+ const r1=mergeRigidByMaterial(gate(3),{isAnchor,cache,cacheKey}),r2=mergeRigidByMaterial(gate(-4),{isAnchor,cache,cacheKey});+ expect(r1.merged.length).toBe(3);expect(cache.size).toBe(3);r1.merged.forEach((m,i)=>expect(r2.merged[i]!.geometry).toBe(m.geometry));+ let disposed=0;for(const g of cache.values())g.addEventListener('dispose',()=>disposed++);r1.restore();r2.restore();expect(disposed).toBe(0);+ const r3=mergeRigidByMaterial(gate(1),{isAnchor,cache,cacheKey:()=>undefined});expect(r3.merged.every(m=>![...cache.values()].includes(m.geometry))).toBe(true);+ const odd=gate(2);mesh('Extra',wood,odd,0,3,0);expect(()=>mergeRigidByMaterial(odd,{isAnchor,cache,cacheKey})).toThrow();+});+test('minGroup sets the smallest group that merges',()=>{+ const scene=()=>{const root=node('R',null),stone=new MeshStandardMaterial(),iron=new MeshStandardMaterial();for(let i=0;i<3;i++)mesh('S'+i,stone,root,i,0,0);for(let i=0;i<2;i++)mesh('I'+i,iron,root,i,1,0);return root;};+ expect(mergeRigidByMaterial(scene(),{isAnchor}).stats).toMatchObject({mergedMeshes:2,sourceMeshes:5,keptMeshes:0,groups:2});+ expect(mergeRigidByMaterial(scene(),{isAnchor,minGroup:3}).stats).toMatchObject({mergedMeshes:1,sourceMeshes:3,keptMeshes:2,groups:2});+});+// Wave-B review fixes (tmp/drawcalls/wave-b-review/fix-kit). Finding ids name the review items.+test('RK-7d merged meshes copy their anchor matrix flags, so a merge after freezeTransforms leaves the owner frozen',()=>{+ const scene=new Scene(),world=new Group();scene.add(world);const owner=node('barn',world),mat=new MeshStandardMaterial();for(let i=0;i<3;i++)mesh('part'+i,mat,owner,i);+ const owners:InstanceOwner[]=[{id:'barn',object:owner,dynamic:false,assetId:'barn'}];scene.updateMatrixWorld(true);+ const frozen=freezeTransforms(owners,()=>true),merge=mergeRigidByMaterial(owner,{isAnchor});expect(merge.merged).toHaveLength(1);+ expect([merge.merged[0]!.matrixAutoUpdate,merge.merged[0]!.matrixWorldAutoUpdate]).toEqual([false,false]);expect(merge.merged[0]!.matrixWorld.equals(owner.matrixWorld)).toBe(true);+ const graph=createFrameGraph({scene,worldRoot:world,owners,batches:null,isFixed:()=>true});expect(graph.stats.dynamicRoots).toBe(0);+ graph.restore();merge.restore();frozen.restore();+ expect(mergeRigidByMaterial(house().root,{isAnchor}).merged.every(m=>m.matrixAutoUpdate&&m.matrixWorldAutoUpdate)).toBe(true);+});+/** A box whose position, normal and uv share one Float32 InterleavedBuffer of stride 8, as GLTFLoader builds a strided bufferView. */+const interleavedBox=()=>{const s=box(),n=s.attributes.position!.count,data=new Float32Array(n*8);for(let i=0;i<n;i++){data.set([s.attributes.position!.getX(i),s.attributes.position!.getY(i),s.attributes.position!.getZ(i)],i*8);data.set([s.attributes.normal!.getX(i),s.attributes.normal!.getY(i),s.attributes.normal!.getZ(i)],i*8+3);data.set([s.attributes.uv!.getX(i),s.attributes.uv!.getY(i)],i*8+6);}+ const ib=new InterleavedBuffer(data,8),g=new BufferGeometry();g.setAttribute('position',new InterleavedBufferAttribute(ib,3,0));g.setAttribute('normal',new InterleavedBufferAttribute(ib,3,3));g.setAttribute('uv',new InterleavedBufferAttribute(ib,2,6));g.setIndex(s.index);return g;};+/** three r186 RenderObject.getGeometryCacheKey, which the WebGPU pipeline key includes. */+const geometryKey=(g:BufferGeometry)=>Object.keys(g.attributes).sort().map(n=>{const a=g.attributes[n] as BufferAttribute&{data?:{stride:number};offset?:number};return n+','+(a.data?a.data.stride+',':'')+(a.offset?a.offset+',':'')+a.itemSize+','+(a.normalized?'n,':'');}).join('');+test("RK-1 layout 'source' mirrors the first part's interleaved Float32 layout, so the pipeline geometry key matches its parts; values equal the canonical merge",()=>{+ const merge=(layout?:'canonical'|'source',cache?:Map<string,BufferGeometry>)=>{const root=node('R',null),mat=new MeshStandardMaterial({name:'M'});mesh('a',mat,root,0,0,0,interleavedBox());const b=mesh('b',mat,root,0,2,0,interleavedBox());b.rotation.x=.7;root.updateMatrixWorld(true);return mergeRigidByMaterial(root,{isAnchor,layout,cache,cacheKey:cache&&(()=>'r')}).merged[0]!.geometry;};+ const source=merge('source'),canonical=merge(),part=interleavedBox();+ expect(geometryKey(source)).toBe(geometryKey(part));expect(geometryKey(canonical)).not.toBe(geometryKey(part));expect(geometryKey(merge('canonical'))).toBe(geometryKey(canonical));+ const p=source.attributes.position as InterleavedBufferAttribute;expect(p.isInterleavedBufferAttribute).toBe(true);expect(p.data).toBe((source.attributes.uv as InterleavedBufferAttribute).data);expect(p.data.array).toBeInstanceOf(Float32Array);expect(p.data.count).toBe(2*part.attributes.position!.count);+ for(const name of ['position','normal','uv']){const s=source.getAttribute(name)!,c=canonical.getAttribute(name)!;expect(s.count).toBe(c.count);for(let i=0;i<s.count;i++)for(let k=0;k<s.itemSize;k++)expect(s.getComponent(i,k)).toBe(c.getComponent(i,k));}+ expect(Array.from(source.index!.array)).toEqual(Array.from(canonical.index!.array));expect(source.boundingSphere!.equals(canonical.boundingSphere!)).toBe(true);+ const shared=new Map<string,BufferGeometry>(),a=merge('canonical',shared),b=merge('source',shared);expect(shared.size).toBe(2);expect(geometryKey(b)).toBe(geometryKey(part));expect(a).not.toBe(b);+ // Plain and normalised inputs keep the canonical non-interleaved Float32 output in either layout.+ const plain=()=>{const root=node('R',null),mat=new MeshStandardMaterial();mesh('a',mat,root);mesh('b',mat,root,2);return mergeRigidByMaterial(root,{isAnchor,layout:'source'}).merged[0]!.geometry;};+ expect(geometryKey(plain())).toBe(geometryKey(box()));+});+test('R1 order puts parts with a lower value first in the merged vertex and index ranges; ties keep scene order',()=>{+ const build=(order?:(m:Mesh)=>number)=>{const root=node('R',null),mat=new MeshStandardMaterial();mesh('Walk',mat,root,0,0,0);mesh('Curb',mat,root,5,0,0);mesh('Rail',mat,root,10,0,0);root.updateMatrixWorld(true);return mergeRigidByMaterial(root,{isAnchor,order});};+ const centres=(g:BufferGeometry)=>[0,1,2].map(k=>{let x=0;for(let i=24*k;i<24*k+24;i++)x+=g.attributes.position!.getX(i);return x/24;});+ const firstTriangles=(g:BufferGeometry)=>Array.from(g.index!.array).slice(0,36).every(i=>i<24);+ const plain=build(),ordered=build(m=>m.name==='Curb'?-1:0);+ expect(centres(plain.merged[0]!.geometry)).toEqual([0,5,10]);expect(centres(ordered.merged[0]!.geometry)).toEqual([5,0,10]);expect(firstTriangles(ordered.merged[0]!.geometry)).toBe(true);+ expect(ordered.sources.map(s=>s.name)).toEqual(['Curb','Walk','Rail']);expect(ordered.stats).toEqual(plain.stats);+});diff --git a/scenes/packages/scene-kit/tests/renderer/msaa-contract.test.ts b/scenes/packages/scene-kit/tests/renderer/msaa-contract.test.tsnew file mode 100644index 00000000..cb474ecd--- /dev/null+++ b/scenes/packages/scene-kit/tests/renderer/msaa-contract.test.ts@@ -0,0 +1,193 @@+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { REVISION } from 'three/webgpu';++// OD-10: the private three contract src/renderer/msaa-store.ts relies on, pinned as source snippets and their order in+// the build that `three/webgpu` resolves to (not three/src). A three upgrade that moves any of these fails here before+// the policy can encode a wrong load or store op. Line numbers are deliberately not pinned.+const BUILD = Bun.resolveSync('three/webgpu', import.meta.dir);+const SOURCE = readFileSync(BUILD, 'utf8');++/** One class member, from its one-tab-indented signature to its closing brace, searched after `anchor`. */+function member(src: string, anchor: string, signature: string): string {+ const from = src.indexOf(anchor); if (from < 0) return '';+ const start = src.indexOf(`\n\t${signature}`, from); if (start < 0) return '';+ const end = src.indexOf('\n\t}\n', start); return end < 0 ? '' : src.slice(start, end);+}+/** A whole class, up to the next top-level class. */+function classBody(src: string, anchor: string): string {+ const start = src.indexOf(anchor); if (start < 0) return '';+ const end = src.indexOf('\nclass ', start + 1); return src.slice(start, end < 0 ? undefined : end);+}+/** Snippets absent from `body` or out of the given order. */+function unordered(body: string, snippets: string[]): string[] {+ const bad: string[] = []; let at = -1;+ for (const snippet of snippets) { const i = body.indexOf(snippet, at + 1); if (i < 0) bad.push(snippet); else at = i; }+ return bad;+}+const RENDERER = 'class Renderer {', BACKEND = 'class WebGPUBackend extends Backend {';++function pinFailures(src: string): Record<string, string[]> {+ const frameBufferTarget = member(src, RENDERER, '_getFrameBufferTarget() {');+ const pins: Record<string, string[]> = {+ // The canvas target is created multisampled and flagged, and its store flags reset to true on every call.+ frameBufferTargetReset: unordered(frameBufferTarget, [+ 'samples: this.samples',+ 'frameBufferTarget.isPostProcessingRenderTarget = true;',+ 'const outputRenderTarget = this.getOutputRenderTarget();',+ 'frameBufferTarget.setSize(',+ 'frameBufferTarget.storeMultisampledColorBuffer = outputRenderTarget !== null ? outputRenderTarget.storeMultisampledColorBuffer : true;',+ 'frameBufferTarget.storeMultisampledDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.storeMultisampledDepthBuffer : true;',+ 'frameBufferTarget.storeMultisampledStencilBuffer = outputRenderTarget !== null ? outputRenderTarget.storeMultisampledStencilBuffer : true;',+ 'return frameBufferTarget;',+ ]),+ // Reset, bind, the scene callback with the target, texture creation, the pass, output, the after callback.+ renderSceneOrder: unordered(member(src, RENDERER, '_renderScene( scene, camera, useFrameBufferTarget = true ) {'), [+ 'const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;',+ "const sceneRef = ( scene.isScene === true ) ? scene : _scene;",+ 'this.setRenderTarget( renderTarget );',+ 'sceneRef.onBeforeRender( this, scene, camera, renderTarget );',+ 'this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );',+ 'this.backend.beginRender( renderContext );',+ 'this.backend.finishRender( renderContext );',+ 'this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );',+ 'this._renderOutput( renderTarget );',+ 'sceneRef.onAfterRender( this, scene, camera, renderTarget );',+ ]),+ // compileAsync runs the scene callback with the canvas target before creating its textures, with no pass.+ compileAsyncOrder: unordered(member(src, RENDERER, 'async compileAsync( scene, camera, targetScene = null'), [+ 'const renderTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : outputRenderTarget;',+ 'sceneRef.onBeforeRender( this, scene, camera, renderTarget );',+ 'this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );',+ ]),+ // Every canvas render goes through the instance's render(), where the kit wraps it.+ renderEntry: unordered(member(src, RENDERER, 'render( scene, camera ) {'), ['this._renderScene( scene, camera );']),+ needsFrameBufferTarget: unordered(member(src, RENDERER, 'get needsFrameBufferTarget() {'), [+ 'const useToneMapping = this.currentToneMapping !== NoToneMapping;',+ 'const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;',+ 'return useToneMapping || useColorSpace;',+ ]),+ // Manual clears reach the canvas target, and the backend's clear always stores.+ clearPath: [+ ...unordered(member(src, RENDERER, 'clear( color = true, depth = true, stencil = true ) {'), ['const renderTarget = this._renderTarget || this._getFrameBufferTarget();', 'this.backend.clear( color, depth, stencil, renderContext );']),+ ...unordered(member(src, BACKEND, 'clear( color, depth, stencil, renderTargetContext = null ) {'), ['clearConfig.depthStoreOp = GPUStoreOp.Store;', 'depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;']),+ ...(member(src, BACKEND, 'clear( color, depth, stencil, renderTargetContext = null ) {').includes('GPUStoreOp.Discard') ? ['backend clear discards'] : []),+ ],+ // An out-of-pass copy reads the canvas target; in a pass it uses the current context.+ rendererCopy: unordered(member(src, RENDERER, 'copyFramebufferToTexture( framebufferTexture, rectangle = null ) {'), [+ 'let renderContext = this._currentRenderContext;',+ 'renderTarget = this._renderTarget || this._getFrameBufferTarget();',+ 'this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );',+ ]),+ // Discard comes only from the flags, and discard forces a clear load.+ discardFromFlags: unordered(member(src, BACKEND, 'beginRender( renderContext ) {'), [+ 'const discardColor = renderContext.sampleCount > 1 && renderTarget?.storeMultisampledColorBuffer === false;',+ 'const discardDepth = renderContext.sampleCount > 1 && renderTarget?.storeMultisampledDepthBuffer === false;',+ 'const discardStencil = renderContext.sampleCount > 1 && renderTarget?.storeMultisampledStencilBuffer === false;',+ 'if ( renderContext.clearColor || discardColor || clearExternalColor ) {',+ 'colorAttachment.storeOp = GPUStoreOp.Discard;',+ 'if ( renderContext.clearDepth || discardDepth ) {',+ 'depthStencilAttachment.depthStoreOp = GPUStoreOp.Discard;',+ 'if ( renderContext.clearStencil || discardStencil ) {',+ 'depthStencilAttachment.stencilStoreOp = GPUStoreOp.Discard;',+ ]),+ // A mid-pass copy ends the pass and restarts the same descriptor with Load and an unchanged storeOp.+ copyRestartsWithLoad: [+ ...unordered(member(src, BACKEND, 'copyFramebufferToTexture( texture, renderContext, rectangle ) {'), [+ 'if ( renderContextData.currentPass ) {',+ 'renderContextData.currentPass.end();',+ 'this._copyFramebufferToTexture( encoder, texture, sourceGPU, destinationGPU, rectangle );',+ 'descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;',+ 'if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;',+ 'renderContextData.currentPass = encoder.beginRenderPass( descriptor );',+ ]),+ ...(/storeOp\s*=/i.test(member(src, BACKEND, 'copyFramebufferToTexture( texture, renderContext, rectangle ) {')) ? ['copy rewrites a storeOp'] : []),+ ],+ // Flags false at texture creation make the 4x attachments transient: RENDER_ATTACHMENT only, clear/discard only.+ transientRule: unordered(member(src, 'class WebGPUTextureUtils {', 'createTexture( texture, options = {} ) {'), [+ 'const supportsTransientAttachments = GPUTextureUsage.TRANSIENT_ATTACHMENT !== undefined;',+ 'renderTarget?.storeMultisampledDepthBuffer === false &&',+ 'renderTarget?.storeMultisampledColorBuffer === false;',+ 'usage = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TRANSIENT_ATTACHMENT;',+ 'msaaTextureDescriptorGPU.usage = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TRANSIENT_ATTACHMENT;',+ ]),+ // Viewport depth, shared and mip textures copy through the renderer's public method, once per render.+ viewportTextureCopy: [+ ...unordered(classBody(src, 'class ViewportTextureNode extends TextureNode {'), [+ 'this.updateBeforeType = NodeUpdateType.RENDER;',+ '\tupdateBefore( frame ) {',+ 'renderer.copyFramebufferToTexture( framebufferTexture );',+ ]),+ ...['class ViewportDepthTextureNode extends ViewportTextureNode {', 'class ViewportSharedTextureNode extends ViewportTextureNode {'].filter(s => !src.includes(s)),+ ],+ // RenderPipeline draws its quad without tone mapping, so it never touches the canvas target.+ pipelineQuad: unordered(member(src, 'class RenderPipeline {', 'render() {'), [+ 'renderer.toneMapping = NoToneMapping;',+ 'renderer.outputColorSpace = ColorManagement.workingColorSpace;',+ 'this._quadMesh.render( renderer );',+ ]),+ // A render into any other target is not output, so it needs no frame-buffer target (shadows, reflectors, passes).+ outputTarget: [+ ...unordered(member(src, RENDERER, 'get isOutputTarget() {'), ['return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;']),+ ...unordered(member(src, RENDERER, 'get currentToneMapping() {'), ['return this.isOutputTarget ? this.toneMapping : NoToneMapping;']),+ ...unordered(member(src, RENDERER, 'get currentColorSpace() {'), ['return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;']),+ ],+ // The reflector clears and renders into its own target mid-pass, which the guards' target check leaves alone.+ reflectorOwnTarget: unordered(member(src, 'class ReflectorBaseNode extends Node {', 'updateBefore( frame ) {'), [+ 'renderer.setRenderTarget( renderTarget );',+ 'renderer.clear();',+ 'renderer.render( scene, virtualCamera );',+ 'renderer.setRenderTarget( currentRenderTarget );',+ ]),+ // Every trip relies on dispose: colour, MSAA and own depth textures are destroyed and the target forgotten, so three+ // recreates them from the flags at its next updateRenderTarget.+ disposeRecreates: [+ ...unordered(member(src, 'class Textures extends DataMap {', 'updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {'), [+ 'depthTexture.renderTarget = renderTarget;',+ 'renderTargetData.onDispose = () => {',+ 'this._destroyRenderTarget( renderTarget );',+ "renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );",+ ]),+ ...unordered(member(src, 'class Textures extends DataMap {', '_destroyRenderTarget( renderTarget ) {'), [+ 'this._destroyTexture( textures[ i ] );',+ 'if ( depthTexture && depthTexture.renderTarget === renderTarget ) {',+ 'this._destroyTexture( depthTexture );',+ 'this.delete( renderTarget );',+ ]),+ ...unordered(member(src, 'class WebGPUTextureUtils {', 'destroyTexture( texture, isDefaultTexture = false ) {'), [+ 'if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();',+ ]),+ ],+ };+ // _getFrameBufferTarget is the only writer of isPostProcessingRenderTarget.+ const writers = [...src.matchAll(/\.isPostProcessingRenderTarget\s*=(?!=)/g)].map(m => m.index!);+ const start = src.indexOf(frameBufferTarget);+ pins.singleWriter = writers.length === 1 && frameBufferTarget && writers[0]! > start && writers[0]! < start + frameBufferTarget.length ? [] : [`${writers.length} writers`];+ return pins;+}+const clean = (pins: Record<string, string[]>) => Object.fromEntries(Object.entries(pins).filter(([, bad]) => bad.length));++describe('OD-10 three r186 contract for the MSAA store policy', () => {+ test('the build three/webgpu resolves to is r186', () => {+ expect(BUILD.replaceAll('\\', '/')).toEndWith('three/build/three.webgpu.js');+ expect(REVISION).toBe('186');+ });+ test('every pinned snippet is present and in order', () => {+ expect(clean(pinFailures(SOURCE))).toEqual({});+ });+ test('the pins notice a reorder, a changed reset, a second writer, a non-output getter and a dispose that keeps the target', () => {+ const body = member(SOURCE, RENDERER, '_renderScene( scene, camera, useFrameBufferTarget = true ) {');+ const hook = 'sceneRef.onBeforeRender( this, scene, camera, renderTarget );', begin = 'this.backend.beginRender( renderContext );';+ const swapped = SOURCE.replace(body, body.replace(hook, '').replace(begin, `${begin}\n\t\t${hook}`));+ expect(Object.keys(clean(pinFailures(swapped)))).toContain('renderSceneOrder');+ const reset = SOURCE.replace('outputRenderTarget.storeMultisampledDepthBuffer : true;', 'outputRenderTarget.storeMultisampledDepthBuffer : false;');+ expect(Object.keys(clean(pinFailures(reset)))).toEqual(['frameBufferTargetReset']);+ const writer = SOURCE.replace('class RenderPipeline {', 'class RenderPipeline {\n\tx() { this.target.isPostProcessingRenderTarget = true; }');+ expect(Object.keys(clean(pinFailures(writer)))).toEqual(['singleWriter']);+ const output = SOURCE.replace('return this.isOutputTarget ? this.toneMapping : NoToneMapping;', 'return this.toneMapping;');+ expect(Object.keys(clean(pinFailures(output)))).toEqual(['outputTarget']);+ const destroy = member(SOURCE, 'class Textures extends DataMap {', '_destroyRenderTarget( renderTarget ) {');+ const kept = SOURCE.replace(destroy, destroy.replace('this.delete( renderTarget );', ''));+ expect(Object.keys(clean(pinFailures(kept)))).toEqual(['disposeRecreates']);+ });+});diff --git a/scenes/packages/scene-kit/tests/renderer/msaa-store.test.ts b/scenes/packages/scene-kit/tests/renderer/msaa-store.test.tsnew file mode 100644index 00000000..f60557f5--- /dev/null+++ b/scenes/packages/scene-kit/tests/renderer/msaa-store.test.ts@@ -0,0 +1,234 @@+import { describe, expect, test } from 'bun:test';+import { PerspectiveCamera, RenderTarget, Scene } from 'three/webgpu';+import { installMsaaStorePolicy, resolveMsaaDiscard, type MsaaStorePolicy } from '../../src/renderer/msaa-store';+import type { TierKnobs } from '../../src/quality/core';++// OD-10 on fake objects. `frame` mirrors r186 Renderer._renderScene for the canvas path, in the order the contract+// test pins in three.webgpu.js: _getFrameBufferTarget resets the flags, setRenderTarget, scene.onBeforeRender, texture+// creation and beginRender read the flags, the pass ends, setRenderTarget(null), scene.onAfterRender. The kit's render+// wrapper brackets it: beforeRender first, afterRender in its finally.+class FakeRenderer {+ backend: object = { isWebGPUBackend: true }; samples = 4; stencil = false; toneMapped = true; output: RenderTarget | null = null;+ autoClear = true; autoClearColor = true; autoClearDepth = true; autoClearStencil = true;+ target: RenderTarget | null = null; log: string[] = [];+ get needsFrameBufferTarget() { return this.toneMapped && (this.target === null || this.target === this.output); }+ getRenderTarget() { return this.target; }+ setRenderTarget(t: RenderTarget | null) { this.target = t; }+ getOutputRenderTarget() { return this.output; }+ copyFramebufferToTexture(_texture: unknown) { this.log.push('copy'); }+ clear(_c = true, _d = true, _s = true) { this.log.push('clear'); }+ clearColor() { this.log.push('clearColor'); this.clear(true, false, false); }+ clearDepth() { this.log.push('clearDepth'); this.clear(false, true, false); }+ clearStencil() { this.log.push('clearStencil'); this.clear(false, false, true); }+}+const camera = new PerspectiveCamera();+function setup(o: { discard?: boolean; webgpu?: boolean; samples?: number } = {}) {+ const r = new FakeRenderer(), scene = new Scene(), trips: string[] = [];+ if (o.webgpu === false) r.backend = { isWebGLBackend: true };+ if (o.samples !== undefined) r.samples = o.samples;+ const fb = Object.assign(new RenderTarget(4, 4, { samples: r.samples }), { isPostProcessingRenderTarget: true });+ fb.addEventListener('dispose', () => r.log.push('dispose'));+ let p: MsaaStorePolicy;+ const install = () => (p = installMsaaStorePolicy(r as any, scene, { discard: o.discard ?? true, onTrip: reason => trips.push(reason) }));+ const policy = install();+ const reset = () => { fb.storeMultisampledColorBuffer = fb.storeMultisampledDepthBuffer = fb.storeMultisampledStencilBuffer = true; };+ const ops = () => [fb.storeMultisampledColorBuffer, fb.storeMultisampledDepthBuffer, fb.storeMultisampledStencilBuffer].map(s => s ? 'store' : 'discard').join('/');+ const frame = (during?: () => void) => {+ p.beforeRender(scene);+ try {+ reset(); r.setRenderTarget(fb); scene.onBeforeRender(r as any, scene, camera, fb as any, null as any, null as any);+ const encoded = ops(); during?.(); r.log.push('pass-end');+ r.setRenderTarget(null); scene.onAfterRender(r as any, scene, camera, fb as any, null as any, null as any);+ return encoded;+ } finally { p.afterRender(); }+ };+ return { r, scene, fb, trips, policy, install, frame, reset, ops };+}++describe('OD-10 MSAA store policy', () => {+ test('default is store: only an explicit knob (or a test override) discards', () => {+ const base = {} as TierKnobs;+ expect(resolveMsaaDiscard(base)).toBe(false);+ expect(resolveMsaaDiscard({ ...base, multisample: { discard: false } })).toBe(false);+ expect(resolveMsaaDiscard({ ...base, multisample: { discard: true } })).toBe(true);+ expect(resolveMsaaDiscard({ ...base, multisample: { discard: true } }, 'store')).toBe(false);+ expect(resolveMsaaDiscard(base, 'discard')).toBe(true);+ });++ test('flags go false on the canvas frame-buffer target every frame, after three resets them; callbacks chain', () => {+ const r = new FakeRenderer(), scene = new Scene(), before: unknown[][] = [], after: unknown[][] = [];+ scene.onBeforeRender = (...args: unknown[]) => { before.push(args); };+ scene.onAfterRender = (...args: unknown[]) => { after.push(args); };+ const fb = Object.assign(new RenderTarget(4, 4, { samples: 4 }), { isPostProcessingRenderTarget: true });+ const policy = installMsaaStorePolicy(r as any, scene, { discard: true, onTrip: () => { throw new Error('no trip expected'); } });+ for (let i = 0; i < 2; i++) {+ fb.storeMultisampledColorBuffer = fb.storeMultisampledDepthBuffer = fb.storeMultisampledStencilBuffer = true;+ r.setRenderTarget(fb); scene.onBeforeRender(r as any, scene, camera, fb as any, null as any, null as any);+ expect([fb.storeMultisampledColorBuffer, fb.storeMultisampledDepthBuffer, fb.storeMultisampledStencilBuffer]).toEqual([false, false, false]);+ r.setRenderTarget(null); scene.onAfterRender(r as any, scene, camera, fb as any, null as any, null as any);+ }+ expect(before.length).toBe(2); expect(after.length).toBe(2); expect(before[0]![3]).toBe(fb); expect(after[1]![0]).toBe(r);+ expect(policy.active).toBe(true); expect(policy.tripped).toBeNull();+ });++ test('other targets keep store: user targets, single-sample, an output render target set', () => {+ const { r, scene, fb } = setup();+ const user = new RenderTarget(4, 4, { samples: 4 }), single = Object.assign(new RenderTarget(4, 4), { isPostProcessingRenderTarget: true });+ for (const t of [user, single]) { r.setRenderTarget(t); scene.onBeforeRender(r as any, scene, camera, t as any, null as any, null as any); expect(t.storeMultisampledColorBuffer).toBe(true); }+ r.output = new RenderTarget(4, 4); r.setRenderTarget(fb); scene.onBeforeRender(r as any, scene, camera, fb as any, null as any, null as any);+ expect([fb.storeMultisampledColorBuffer, fb.storeMultisampledDepthBuffer]).toEqual([true, true]);+ });++ test('autoClear off trips at the frame start: disposes before texture creation and encodes store, never declines silently', () => {+ for (const key of ['autoClear', 'autoClearColor', 'autoClearDepth'] as const) {+ const { r, frame, trips, policy } = setup();+ expect(frame()).toBe('discard/discard/discard');+ r[key] = false; r.log.length = 0;+ expect(frame()).toBe('store/store/store');+ expect(r.log).toEqual(['dispose', 'pass-end']); expect(trips).toEqual(['autoClear']);+ expect(policy.active).toBe(false); expect(policy.tripped).toBe('autoClear');+ r[key] = true; expect(frame()).toBe('store/store/store'); expect(trips.length).toBe(1);+ }+ const stencil = setup(); stencil.r.stencil = true; stencil.r.autoClearStencil = false;+ expect(stencil.frame()).toBe('store/store/store'); expect(stencil.trips).toEqual(['autoClear']);+ });++ test('a mid-pass framebuffer copy still runs, and the target is disposed only after the frame', () => {+ const { r, frame, trips, policy } = setup();+ frame(); r.log.length = 0;+ expect(frame(() => r.copyFramebufferToTexture({}))).toBe('discard/discard/discard');+ expect(r.log).toEqual(['copy', 'pass-end', 'dispose']); expect(trips).toEqual(['copyFramebufferToTexture']); expect(policy.active).toBe(false);+ r.log.length = 0; expect(frame(() => r.copyFramebufferToTexture({}))).toBe('store/store/store');+ expect(r.log).toEqual(['copy', 'pass-end']); expect(trips.length).toBe(1);+ });++ test('a nested render into another target (a reflector) never disposes mid-pass; the next frame start does if onAfterRender was missed', () => {+ const { r, scene, fb, frame, policy } = setup(), mirror = new RenderTarget(4, 4);+ frame(); r.log.length = 0;+ frame(() => {+ r.copyFramebufferToTexture({});+ // ReflectorBaseNode.updateBefore: its own target, a clear, then the scene through the kit wrapper.+ r.setRenderTarget(mirror); r.clear(); policy.beforeRender(scene);+ scene.onBeforeRender(r as any, scene, camera, mirror as any, null as any, null as any);+ scene.onAfterRender(r as any, scene, camera, mirror as any, null as any, null as any); policy.afterRender(); r.setRenderTarget(fb);+ });+ expect(r.log).toEqual(['copy', 'clear', 'pass-end', 'dispose']);+ const other = setup(); other.frame(); other.r.log.length = 0;+ other.reset(); other.r.setRenderTarget(other.fb); other.scene.onBeforeRender(other.r as any, other.scene, camera, other.fb as any, null as any, null as any);+ other.r.copyFramebufferToTexture({}); other.r.log.push('pass-end'); other.r.setRenderTarget(null); // the frame threw: no onAfterRender+ other.frame(); expect(other.r.log).toEqual(['copy', 'pass-end', 'dispose', 'pass-end']);+ });++ test('a frame that throws after a mid-pass trip: the wrapper\'s afterRender restores store and disposes before any later clear', () => {+ const { r, scene, fb, frame, reset, ops, policy, trips } = setup();+ frame(); r.log.length = 0;+ policy.beforeRender(scene); reset(); r.setRenderTarget(fb); scene.onBeforeRender(r as any, scene, camera, fb as any, null as any, null as any);+ r.copyFramebufferToTexture({}); // the frame then throws: no pass end, no onAfterRender, and three leaves the target bound+ policy.afterRender();+ expect(r.log).toEqual(['copy', 'dispose']); expect(ops()).toBe('store/store/store');+ r.clear(); expect(r.log).toEqual(['copy', 'dispose', 'clear']); expect(trips).toEqual(['copyFramebufferToTexture']);+ });++ test('a later non-chaining overwrite of scene.onBeforeRender trips hook-lost when that frame ends: store again, target disposed', () => {+ const { r, scene, frame, trips, policy } = setup();+ expect(frame()).toBe('discard/discard/discard'); r.log.length = 0;+ scene.onBeforeRender = () => {};+ expect(frame()).toBe('store/store/store'); // three's reset, unhooked, encodes store onto attachments created transient+ expect(r.log).toEqual(['pass-end', 'dispose']); expect(trips).toEqual(['hook-lost']); expect(policy.tripped).toBe('hook-lost');+ expect(policy.active).toBe(false); expect(frame()).toBe('store/store/store'); expect(trips.length).toBe(1);+ });++ test('hook-lost needs an outermost canvas render of the hooked scene: a pipeline quad around a scene pass, or a user target, never trips', () => {+ const { r, scene, frame, trips, policy } = setup(), quad = new Scene(), user = new RenderTarget(4, 4);+ frame(); r.log.length = 0;+ const into = (target: RenderTarget) => {+ const before = r.getRenderTarget(); r.setRenderTarget(target); policy.beforeRender(scene);+ scene.onBeforeRender(r as any, scene, camera, target as any, null as any, null as any);+ scene.onAfterRender(r as any, scene, camera, target as any, null as any, null as any); policy.afterRender(); r.setRenderTarget(before);+ };+ r.toneMapped = false; policy.beforeRender(quad); into(user); policy.afterRender(); r.toneMapped = true; // RenderPipeline: quad, then its scene pass+ into(user); // the scene into a user target at the top level+ expect(trips).toEqual([]); expect(r.log).toEqual([]); expect(frame()).toBe('discard/discard/discard');+ });++ test('a canvas-path clear (each of the four) or an out-of-pass copy disposes before the call', () => {+ for (const call of ['clear', 'clearColor', 'clearDepth', 'clearStencil', 'copyFramebufferToTexture'] as const) {+ const { r, frame, trips } = setup();+ frame(); r.log.length = 0;+ (r[call] as (arg?: unknown) => void)({});+ expect(r.log[0]).toBe('dispose'); expect(r.log.filter(entry => entry === 'dispose').length).toBe(1);+ expect(trips).toEqual([call]);+ expect(frame()).toBe('store/store/store');+ }+ });++ test('clears and copies elsewhere do not trip: into a user target, or a canvas without the frame-buffer target', () => {+ const { r, frame, trips } = setup();+ frame(); r.log.length = 0;+ r.setRenderTarget(new RenderTarget(4, 4)); r.clear(); r.copyFramebufferToTexture({});+ r.setRenderTarget(null); r.toneMapped = false; r.clearColor(); r.copyFramebufferToTexture({}); r.toneMapped = true;+ expect(trips).toEqual([]); expect(r.log).not.toContain('dispose'); expect(frame()).toBe('discard/discard/discard');+ });++ test('inside the kit render wrapper: a canvas render of another object trips and disposes first; the hooked scene, render targets and a pipeline quad do not', () => {+ const { r, scene, frame, trips, policy } = setup();+ frame(); r.log.length = 0;+ const render = (object: Scene) => { policy.beforeRender(object); policy.afterRender(); };+ frame(); r.log.length = 0; // the hooked scene, through the wrapper+ r.setRenderTarget(new RenderTarget(4, 4)); render(new Scene()); r.setRenderTarget(null);+ r.toneMapped = false; render(new Scene()); r.toneMapped = true; // RenderPipeline renders its quad untone-mapped+ expect(trips).toEqual([]); expect(r.log).toEqual([]);+ render(new Scene());+ expect(r.log).toEqual(['dispose']); expect(trips).toEqual(['render']); expect(frame()).toBe('store/store/store');+ });++ test('WebGL, single-sample and store decisions install nothing', () => {+ for (const o of [{ webgpu: false }, { samples: 1 }, { samples: 0 }, { discard: false }]) {+ const { r, scene, frame, policy } = setup(o);+ expect(Object.hasOwn(scene, 'onBeforeRender')).toBe(false);+ for (const key of ['copyFramebufferToTexture', 'clear', 'clearColor', 'clearDepth', 'clearStencil']) expect(Object.hasOwn(r, key)).toBe(false);+ expect(frame()).toBe('store/store/store'); expect(policy.active).toBe(false); expect(policy.tripped).toBeNull();+ policy.beforeRender(new Scene()); policy.afterRender(); policy.remove();+ }+ });++ test('idempotent across the two configure calls: one chain, one policy', () => {+ const r = new FakeRenderer(), scene = new Scene(), fb = Object.assign(new RenderTarget(4, 4, { samples: 4 }), { isPostProcessingRenderTarget: true });+ let before = 0, after = 0;+ scene.onBeforeRender = () => { before++; }; scene.onAfterRender = () => { after++; };+ const install = () => installMsaaStorePolicy(r as any, scene, { discard: true, onTrip: () => {} });+ const policy = install(), hook = scene.onBeforeRender, clear = r.clear;+ expect(install()).toBe(policy); expect(scene.onBeforeRender).toBe(hook); expect(r.clear).toBe(clear);+ r.setRenderTarget(fb); scene.onBeforeRender(r as any, scene, camera, fb as any, null as any, null as any);+ r.setRenderTarget(null); scene.onAfterRender(r as any, scene, camera, fb as any, null as any, null as any);+ expect([before, after]).toEqual([1, 1]); expect(fb.storeMultisampledColorBuffer).toBe(false);+ });++ test('compileAsync: onBeforeRender without a pass or onAfterRender, on a sub-object, is harmless', () => {+ const { r, scene, fb, frame, reset, ops, trips } = setup(), mesh = new Scene();+ reset(); scene.onBeforeRender(r as any, mesh, camera, fb as any, null as any, null as any);+ expect(ops()).toBe('discard/discard/discard'); // three creates the attachments transient here+ expect(trips).toEqual([]); expect(r.log).toEqual([]);+ expect(frame()).toBe('discard/discard/discard'); expect(trips).toEqual([]);+ });++ test('remove restores three, disposes the discard target and is final', () => {+ const { r, scene, frame, policy, install, trips } = setup();+ frame(); r.log.length = 0;+ policy.remove(); policy.remove();+ expect(r.log).toEqual(['dispose']);+ expect(Object.hasOwn(scene, 'onBeforeRender')).toBe(false); expect(Object.hasOwn(scene, 'onAfterRender')).toBe(false);+ for (const key of ['copyFramebufferToTexture', 'clear', 'clearColor', 'clearDepth', 'clearStencil']) expect(Object.hasOwn(r, key)).toBe(false);+ expect(policy.active).toBe(false); expect(frame()).toBe('store/store/store'); r.clear(); policy.beforeRender(new Scene()); policy.afterRender();+ expect(trips).toEqual([]);+ const again = install(); expect(again).not.toBe(policy); expect(frame()).toBe('discard/discard/discard'); again.remove();+ });++ test('a wrapper added on top after install survives remove, and ours passes through', () => {+ const { scene, frame, policy } = setup();+ const ours = scene.onBeforeRender, seen: string[] = [];+ scene.onBeforeRender = function (...args: Parameters<Scene['onBeforeRender']>) { seen.push('outer'); return ours.apply(this, args); };+ policy.remove();+ expect(seen.length).toBe(0); expect(frame()).toBe('store/store/store'); expect(seen).toEqual(['outer']);+ });+});diff --git a/scenes/packages/scene-kit/tests/shadows/cache.test.ts b/scenes/packages/scene-kit/tests/shadows/cache.test.tsnew file mode 100644index 00000000..211fb067--- /dev/null+++ b/scenes/packages/scene-kit/tests/shadows/cache.test.ts@@ -0,0 +1,274 @@+import { expect, test } from 'bun:test';+import { BoxGeometry, DirectionalLight, Group, HalfFloatType, InstancedMesh, Layers, Mesh, MeshStandardMaterial, OrthographicCamera, PerspectiveCamera, Scene, SkinnedMesh } from 'three/webgpu';+import { cachedSunShadow } from '../../src/shadows/cache';+import type { CachedSunShadowOptions } from '../../src/shadows/cache';+import { keepsShadowMask, layerBit, ShadowLayers, suppressedCasters } from '../../src/shadows/layers';++const material = new MeshStandardMaterial(), geometry = new BoxGeometry();+const S_BIT = 1 << 30, D_BIT = 1 << 31;+const box = (name: string, cast = true) => { const m = new Mesh(geometry, material); m.name = name; m.castShadow = cast; return m; };+const main = Object.assign(new PerspectiveCamera(), { name: 'main' }), mirror = Object.assign(new PerspectiveCamera(), { name: 'mirror' });++function farmSun() {+ const light = new DirectionalLight(); light.name = 'sun'; light.position.set(25, 42, 20); light.castShadow = true; light.shadow.mapSize.setScalar(2048);+ Object.assign(light.shadow.camera, { left: -44, right: 44, top: 44, bottom: -44, near: 1, far: 115 }); light.shadow.camera.updateProjectionMatrix();+ return light;+}+/**+ * Drives one child ShadowNode through three r186's own updateBefore gating (per camera and frame dedupe, never during+ * pre-compile, needsUpdate cleared only when the depth version held). updateShadow is stubbed: it logs the casters the+ * shadow camera would draw (visible through ancestors, on a camera layer, castShadow) and bumps the depth version on the+ * first render, as the first updateRenderTarget does.+ */+function drive(node: any, scene: Scene) {+ let first = true;const log: (string | number)[][] = [];+ node.shadowMap = { depthTexture: { version: 0 }, dispose() {} };+ node.updateShadow = (frame: { frameId: number }) => {+ node._depthVersionCached = node.shadowMap.depthTexture.version; if (first) { node.shadowMap.depthTexture.version++; first = false; }+ const drawn: (string | number)[] = [frame.frameId]; const layers: Layers = node.shadow.camera.layers;+ scene.traverseVisible(o => { if ((o as Mesh).isMesh && o.castShadow && o.layers.test(layers)) drawn.push(o.name); });+ log.push(drawn);+ };+ return { log, draw: (frameId: number, camera: PerspectiveCamera) => node.updateBefore({ renderer: { _isPreCompiling: false }, camera, frameId }) };+}+function setup(o: Partial<CachedSunShadowOptions> = {}) {+ const scene = new Scene(), light = farmSun(); scene.add(light, light.target); scene.updateMatrixWorld(true);+ const cache = cachedSunShadow({ light, settleFrames: 3, ...o }), composite = (light.shadow as any).shadowNode.node;+ const S = drive(composite.aNode, scene), D = drive(composite.bNode, scene);let frame = 0;+ /** One frame: the scene's update at SystemOrder.shadows, then every camera that draws a receiver. */+ const step = (cameras = [main]) => { cache.update(); for (const c of cameras) { S.draw(frame, c); D.draw(frame, c); } frame++; };+ return { scene, light, cache, S, D, step, composite };+}++test('mask math: kit bits sit above every scene layer and keep their own shadow masks', () => {+ expect(ShadowLayers).toEqual({ static: 30, live: 31 });+ const l = new Layers(); l.set(31); expect(l.test({ mask: layerBit(31) } as Layers)).toBe(true);+ expect([layerBit(30), layerBit(31)]).toEqual([S_BIT, D_BIT]);+ expect([keepsShadowMask(0), keepsShadowMask(1), keepsShadowMask(5), keepsShadowMask(S_BIT), keepsShadowMask(D_BIT), keepsShadowMask(S_BIT | D_BIT)]).toEqual([false, false, true, true, true, true]);+ for (const layers of [{ static: 0, live: 2 }, { static: 3, live: 3 }, { static: 1, live: 32 }]) expect(() => cachedSunShadow({ light: farmSun(), layers })).toThrow('distinct');+ const custom = cachedSunShadow({ light: farmSun(), layers: { static: 1, live: 2 } });+ expect([custom.staticShadow.camera.layers.mask, custom.liveShadow.camera.layers.mask]).toEqual([2, 4]);+});++test('install: two armed clones with their own placeholder lights, combined with min; one custom node per light', () => {+ const light = farmSun(), filter = () => 0; Object.assign(light.shadow, { filterNode: filter, mapType: HalfFloatType });+ const cache = cachedSunShadow({ light, liveMapSize: 1024 }), template = light.shadow as any, composite = template.shadowNode.node;+ const S = cache.staticShadow as any, D = cache.liveShadow as any;+ expect(composite.method).toBe('min');+ const nodes = [composite.aNode, composite.bNode];+ expect(nodes.map(n => [n.isShadowNode, n.shadow])).toEqual([[true, S], [true, D]]);+ expect(nodes[0].light).not.toBe(nodes[1].light);+ for (const n of nodes) {+ expect(n.light).not.toBe(light); expect(n.light.shadow).toBe(n.shadow); expect(n.light.castShadow).toBe(true);+ expect(n.light.matrixWorld).toBe(light.matrixWorld); expect(n.light.target).toBe(light.target); expect(n.light.parent).toBeNull();+ }+ expect(nodes.map(n => n.light.name)).toEqual(['sun static', 'sun live']);+ expect(new Set([template, S, D]).size).toBe(3); expect(new Set([template.camera, S.camera, D.camera]).size).toBe(3);+ expect([S.filterNode, D.filterNode, S.mapType, D.mapType]).toEqual([filter, filter, HalfFloatType, HalfFloatType]);+ expect([S.autoUpdate, S.needsUpdate, D.autoUpdate, D.needsUpdate]).toEqual([false, true, false, true]);+ expect([S.camera.layers.mask, D.camera.layers.mask]).toEqual([S_BIT, D_BIT]);+ expect([S.mapSize.x, D.mapSize.x, template.mapSize.x, template.mapSize.y]).toEqual([2048, 1024, 2048, 2048]);+ expect(light.castShadow).toBe(true); expect(template.map).toBeNull();+ expect(() => cachedSunShadow({ light })).toThrow('custom shadow node');+});++test('track adds the static bit per object to casters, suppressed casters and stand-ins, once', () => {+ const { scene, light, cache } = setup(), group = new Group(), caster = box('caster'), quiet = box('quiet', false), dropped = box('dropped', false), standIn = box('standIn');+ const batch = new InstancedMesh(geometry, material, 2); batch.castShadow = true; suppressedCasters.add(dropped);+ standIn.userData.kilnShadowStandIn = true; standIn.castShadow = false; standIn.layers.set(29); light.shadow.camera.layers.enable(29);+ group.add(caster, quiet, dropped, standIn, batch); scene.add(group);+ expect(cache.track(scene).added).toBe(4);+ expect([caster, dropped, batch].map(m => m.layers.mask)).toEqual([1 | S_BIT, 1 | S_BIT, 1 | S_BIT]);+ expect([standIn.layers.mask, quiet.layers.mask, group.layers.mask]).toEqual([1 << 29 | S_BIT, 1, 1]);+ expect(cache.track(scene).added).toBe(0); expect(cache.track(group, { movable: () => true }).added).toBe(0);+ expect(cache.stats).toMatchObject({ staticCasters: 4, liveCasters: 0 });+});++test('arming: both maps render on the first two frames, a mover goes live and back, the live map clears once', () => {+ const { scene, cache, S, D, step } = setup(), still = box('still'), mover = box('mover'), rig = new Group();+ rig.add(mover); scene.add(still, rig); scene.updateMatrixWorld(true); cache.track(scene, { movable: n => n === rig });+ step([]); step([]); // no receiver drawn yet: the arms wait+ step(); step(); step();+ expect(S.log).toEqual([[2, 'still', 'mover'], [3, 'still', 'mover']]); // first render recreates the texture: two frames+ expect(D.log).toEqual([[2], [3]]);+ rig.position.x = 1; rig.updateMatrixWorld(true); step(); // frame 5: promote, static map re-armed without it+ expect(mover.layers.mask).toBe(1 | D_BIT);+ expect([S.log.at(-1), D.log.at(-1)]).toEqual([[5, 'still'], [5, 'mover']]);+ expect(cache.stats).toMatchObject({ staticCasters: 1, liveCasters: 1, staticRenders: 2 });+ expect(cache.stats.pendingSettle).toBeGreaterThan(0);+ rig.position.x = 2; rig.updateMatrixWorld(true); step([main, mirror]); // frame 6: live map only, once for two cameras+ expect(S.log.length).toBe(3); expect(D.log.slice(-2)).toEqual([[5, 'mover'], [6, 'mover']]);+ step(); step(); // frames 7, 8: unchanged, still live+ expect(D.log.at(-1)).toEqual([8, 'mover']);+ step(); // frame 9: settled, back to static, live map cleared+ expect(mover.layers.mask).toBe(1 | S_BIT);+ expect([S.log.at(-1), D.log.at(-1)]).toEqual([[9, 'still', 'mover'], [9]]);+ step(); step();+ expect([S.log.length, D.log.length]).toEqual([4, 7]);+ expect(cache.stats).toMatchObject({ staticCasters: 2, liveCasters: 0, staticRenders: 3, pendingSettle: 0 });+});++test('watched casters also go live on ancestor visibility, castShadow and instance changes; unwatched never do', () => {+ const { scene, cache, S, step } = setup(), still = box('still'), mover = box('mover'), rig = new Group(), batch = new InstancedMesh(geometry, material, 3);+ batch.name = 'batch'; batch.castShadow = true; rig.add(mover); scene.add(still, rig, batch); scene.updateMatrixWorld(true);+ cache.track(scene, { movable: n => n === rig || n === batch }); step(); step();+ const live = (m: Mesh, change: () => void) => { change(); step(); const promoted = (m.layers.mask & D_BIT) !== 0; for (let i = 0; i < 3; i++) step(); return promoted && (m.layers.mask & S_BIT) !== 0; };+ expect(live(mover, () => { rig.visible = false; })).toBe(true);+ expect(live(mover, () => { rig.visible = true; })).toBe(true);+ expect(live(mover, () => { mover.castShadow = false; })).toBe(true);+ expect(live(batch, () => { batch.instanceMatrix.needsUpdate = true; })).toBe(true);+ expect(live(batch, () => { batch.count = 1; })).toBe(true);+ const renders = cache.stats.staticRenders, logged = S.log.length;+ still.position.x = 3; still.updateMatrixWorld(true); step(); step();+ expect([still.layers.mask, cache.stats.staticRenders, S.log.length]).toEqual([1 | S_BIT, renders, logged]);+ const skinned = new SkinnedMesh(geometry, material); skinned.castShadow = true; rig.add(skinned); cache.track(rig, { movable: () => true });+ for (let i = 0; i < 6; i++) step();+ expect(skinned.layers.mask).toBe(1 | D_BIT); // bones move without a matrixWorld change+});++test('invalidate re-arms the static map and records why; prime fills the live map once, then clears it', () => {+ const { scene, cache, S, D, step } = setup(), still = box('still'), mover = box('mover'), rig = new Group();+ rig.add(mover); scene.add(still, rig); scene.updateMatrixWorld(true); cache.track(scene, { movable: n => n === rig });+ step(); step(); step();+ cache.invalidate('door'); cache.invalidate('door'); cache.invalidate('tier');+ expect(cache.stats).toMatchObject({ invalidations: 3, reasons: { door: 2, tier: 1 }, staticRenders: 4 });+ step(); step();+ expect(S.log.slice(2)).toEqual([[3, 'still', 'mover']]);+ cache.prime();+ expect(cache.liveShadow.camera.layers.mask).toBe(S_BIT | D_BIT);+ step();+ expect([S.log.at(-1), D.log.at(-1)]).toEqual([[5, 'still', 'mover'], [5, 'still', 'mover']]);+ step();+ expect(cache.liveShadow.camera.layers.mask).toBe(D_BIT); expect(D.log.at(-1)).toEqual([6]);+ step(); expect(D.log.at(-1)).toEqual([6]);+ expect(cache.stats.pendingSettle).toBe(0);+});++test('a prime before the first frame holds its mask until three clears the flag', () => {+ const { scene, cache, D, step } = setup(), still = box('still');+ scene.add(still); scene.updateMatrixWorld(true); cache.track(scene); cache.prime();+ step(); step(); step(); step();+ expect(D.log).toEqual([[0, 'still'], [1, 'still'], [2]]);+});++test('template sync: extents, depth range and zoom reach the live map every frame, the static map on re-arm; sampling values reach both every frame', () => {+ const { light, cache, step } = setup(), S = cache.staticShadow, D = cache.liveShadow; step();+ Object.assign(light.shadow.camera, { left: -30, right: 30, top: 20, bottom: -20, near: 2, far: 90, zoom: 2 });+ Object.assign(light.shadow, { bias: -.001, normalBias: .05, radius: 3, intensity: .6 });+ cache.update();+ const expected = new OrthographicCamera(-30, 30, 20, -20, 2, 90); expected.zoom = 2;+ const pick = (s: typeof S) => { const c = s.camera as OrthographicCamera; return [c.left, c.right, c.top, c.bottom, c.near, c.far, c.zoom, s.bias, s.normalBias, s.radius, s.intensity]; };+ expect(pick(D)).toEqual([-30, 30, 20, -20, 2, 90, 2, -.001, .05, 3, .6]);+ expected.coordinateSystem = D.camera.coordinateSystem; expected.updateProjectionMatrix();+ expect(D.camera.projectionMatrix.elements).toEqual(expected.projectionMatrix.elements);+ // RK-7b: bias, normal bias, radius and intensity are sampling uniforms (ShadowNode reference()), so the static map's+ // receivers take them at once; its camera keeps the extents its depth was rendered with until a re-arm.+ expect(pick(S)).toEqual([-44, 44, 44, -44, 1, 115, 1, -.001, .05, 3, .6]);+ cache.invalidate('extent');+ expect(pick(S)).toEqual(pick(D)); expect(S.camera.projectionMatrix.elements).toEqual(expected.projectionMatrix.elements);+});++test('a resize re-arms both maps and moves the real light mapSize sentinel monotonically', () => {+ const { light, cache, step } = setup(), S = cache.staticShadow, D = cache.liveShadow, seen = [light.shadow.mapSize.y];+ step(); step();+ for (const size of [1024, 2048, 1024]) {+ light.shadow.mapSize.setScalar(size); cache.update();+ expect([S.mapSize.x, S.mapSize.y, D.mapSize.x, D.mapSize.y, S.needsUpdate, D.needsUpdate, light.shadow.mapSize.x]).toEqual([size, size, size, size, true, true, size]);+ expect(light.shadow.mapSize.y).toBeGreaterThan(Math.max(...seen, size)); seen.push(light.shadow.mapSize.y);+ step(); step(); cache.update(); expect(light.shadow.mapSize.y).toBe(seen.at(-1)!);+ }+ cache.dispose(); expect(light.shadow.mapSize.toArray()).toEqual([1024, 1024]);+ const small = setup({ liveMapSize: 512 }); small.light.shadow.mapSize.setScalar(1024); small.cache.update();+ expect([small.cache.staticShadow.mapSize.x, small.cache.liveShadow.mapSize.x]).toEqual([1024, 512]);+});++test('dispose: both shadow nodes, both shadows, then the custom node; only the bits it added come off', () => {+ const scene = new Scene(), light = farmSun(), cache = cachedSunShadow({ light, settleFrames: 1 }), composite = (light.shadow as any).shadowNode.node, order: string[] = [];+ const spy = (o: any, name: string) => { const original = o.dispose.bind(o); o.dispose = () => { order.push(name); original(); }; };+ spy(composite.aNode, 'static node'); spy(composite.bNode, 'live node'); spy(cache.staticShadow, 'static shadow'); spy(cache.liveShadow, 'live shadow');+ const plain = box('plain'), owned = box('owned'), mover = box('mover'), rig = new Group(); owned.layers.enable(30); rig.add(mover); scene.add(light, plain, owned, rig); scene.updateMatrixWorld(true);+ cache.track(scene, { movable: n => n === rig }); mover.position.y = 1; mover.updateMatrixWorld(); cache.update();+ expect(mover.layers.mask).toBe(1 | D_BIT);+ cache.dispose(); cache.dispose();+ expect(order).toEqual(['static node', 'live node', 'static shadow', 'live shadow']);+ expect('shadowNode' in light.shadow).toBe(false);+ expect([plain.layers.mask, owned.layers.mask, mover.layers.mask]).toEqual([1, 1 | S_BIT, 1]);+ expect(() => { cache.update(); cache.invalidate('late'); cache.prime(); }).not.toThrow();+ expect(cache.stats.invalidations).toBe(0);+ expect(() => cache.track(scene)).toThrow('disposed');+ expect(() => cachedSunShadow({ light }).dispose()).not.toThrow();+});++// Wave-B review fixes (tmp/drawcalls/wave-b-review/fix-kit). Finding ids name the review items.+test('RK-3 track tags only casters the shadow camera draws: its own layers, or layer 0 where three would use the viewing camera mask', () => {+ const { scene, light, cache, S, step } = setup(), kept = box('onLayer0'), two = box('onLayer2'), five = box('onLayer5');+ light.shadow.camera.layers.mask = 1 | 1 << 2; two.layers.set(2); five.layers.set(5);+ scene.add(kept, two, five); scene.updateMatrixWorld(true);+ expect(cache.track(scene).added).toBe(2); step(); step();+ expect(S.log.at(-1)!.slice(1)).toEqual(['onLayer0', 'onLayer2']);+ expect(five.layers.mask).toBe(1 << 5);+ const fallback = setup(), zero = box('zero'), other = box('other'); other.layers.set(5); fallback.scene.add(zero, other); fallback.scene.updateMatrixWorld(true);+ expect(fallback.cache.track(fallback.scene).added).toBe(1); expect([zero.layers.mask, other.layers.mask]).toEqual([1 | S_BIT, 1 << 5]);+});++test('RK-5 install refuses a light whose stock shadow map a receiver already built', () => {+ const light = farmSun(); (light.shadow as any).map = { isRenderTarget: true };+ expect(() => cachedSunShadow({ light })).toThrow('before any receiver');+ expect('shadowNode' in light.shadow).toBe(false);+});++test('RK-6 drift under the tolerance is not motion: a creeping caster settles; creep past it from the last counted pose goes live', () => {+ const { scene, cache, D, step } = setup(), rig = new Group(), rowan = box('rowan'); rig.add(rowan); scene.add(rig); rig.position.set(4, 0, 4); scene.updateMatrixWorld(true);+ cache.track(scene, { movable: n => n === rig }); step(); step(); step();+ const renders = D.log.length;+ for (let i = 0; i < 60; i++) { rig.position.x += (i % 2 ? -1 : 1) * 1e-14; rig.updateMatrixWorld(true); step(); }+ expect([cache.stats.liveCasters, D.log.length - renders, rowan.layers.mask]).toEqual([0, 0, 1 | S_BIT]);+ for (let i = 0; i < 2; i++) { rig.position.x += 4e-7; rig.updateMatrixWorld(true); step(); }+ expect(rowan.layers.mask).toBe(1 | S_BIT); // 0.8 µm from the counted pose+ rig.position.x += 4e-7; rig.updateMatrixWorld(true); step();+ expect(rowan.layers.mask).toBe(1 | D_BIT); // 1.2 µm: motion+ const exact = setup({ tolerance: 0 }), r2 = new Group(), m2 = box('m2'); r2.add(m2); exact.scene.add(r2); exact.scene.updateMatrixWorld(true);+ exact.cache.track(exact.scene, { movable: n => n === r2 }); exact.step(); exact.step();+ r2.position.x += 1e-14; r2.updateMatrixWorld(true); exact.step(); expect(m2.layers.mask).toBe(1 | D_BIT);+ expect(() => cachedSunShadow({ light: farmSun(), tolerance: -1 })).toThrow('tolerance');+});++test('RK-7a a mesh that starts casting after track() joins on the next track() of its root', () => {+ const { scene, cache, S, step } = setup(), late = box('late', false); scene.add(late); scene.updateMatrixWorld(true);+ expect(cache.track(scene).added).toBe(0); late.castShadow = true;+ expect(cache.track(scene).added).toBe(1); cache.invalidate('castShadow'); step(); step();+ expect(S.log.at(-1)!.slice(1)).toEqual(['late']);+});++test('RK-7c track returns an untrack that clears only the casters that call tagged and re-arms the static map', () => {+ const { scene, cache, S, D, step } = setup(), old = new Group(), next = new Group(), rig = new Group(), mover = box('mover'), wall = box('wall'), kept = box('kept');+ rig.add(mover); old.add(rig, wall); next.add(kept); scene.add(old, next); scene.updateMatrixWorld(true);+ const a = cache.track(old, { movable: n => n === rig }), b = cache.track(next);+ expect([a.added, b.added]).toEqual([2, 1]); step(); step();+ rig.position.x = 1; rig.updateMatrixWorld(true); step(); // frame 2: the mover goes live+ expect(mover.layers.mask).toBe(1 | D_BIT);+ const renders = cache.stats.staticRenders; scene.remove(old); a.untrack(); a.untrack();+ expect([mover.layers.mask, wall.layers.mask, kept.layers.mask]).toEqual([1, 1, 1 | S_BIT]);+ expect(cache.stats).toMatchObject({ staticCasters: 1, liveCasters: 0, staticRenders: renders + 1, reasons: { untrack: 1 } });+ step(); // frame 3: the static map without the old world, the live map cleared once+ expect([S.log.at(-1), D.log.at(-1)]).toEqual([[3, 'kept'], [3]]);+ rig.position.x = 2; rig.updateMatrixWorld(true); step(); expect(mover.layers.mask).toBe(1);+ expect(cache.track(old).added).toBe(2);+ b.untrack(); cache.dispose(); expect([kept.layers.mask, mover.layers.mask]).toEqual([1, 1]);+});++test('live() casters, whose motion the watch cannot see, draw in the live map every frame they are shown, then once more to clear', () => {+ const { scene, cache, S, D, step } = setup(), still = box('still'), cars = new Group(), car = new InstancedMesh(geometry, material, 4);+ car.name = 'car'; car.castShadow = true; cars.add(car); scene.add(still, cars); scene.updateMatrixWorld(true);+ const t = cache.track(scene, { live: n => n === cars, movable: () => true });+ expect([t.added, still.layers.mask, car.layers.mask]).toEqual([2, 1 | S_BIT, 1 | D_BIT]);+ step(); step(); step();+ expect(S.log).toEqual([[0, 'still'], [1, 'still']]); expect(D.log).toEqual([[0, 'car'], [1, 'car'], [2, 'car']]);+ expect(cache.stats).toMatchObject({ staticCasters: 1, liveCasters: 1, pendingSettle: 0 });+ cars.visible = false; step(); step();+ expect(D.log.slice(-2)).toEqual([[2, 'car'], [3]]); expect(cache.stats.liveCasters).toBe(0);+ car.count = 0; cars.visible = true; step(); expect(D.log.length).toBe(4); // nothing to draw: no render+ car.count = 4; step(); expect(D.log.at(-1)).toEqual([6, 'car']);+ expect(S.log.length).toBe(2); // live casters never re-arm the static map+ cache.dispose(); expect([car.layers.mask, still.layers.mask]).toEqual([1, 1]);+});diff --git a/scenes/packages/scene-kit/tests/shadows/once.test.ts b/scenes/packages/scene-kit/tests/shadows/once.test.tsnew file mode 100644index 00000000..b9074951--- /dev/null+++ b/scenes/packages/scene-kit/tests/shadows/once.test.ts@@ -0,0 +1,55 @@+import { expect, test } from 'bun:test';+import { DirectionalLight, PerspectiveCamera } from 'three/webgpu';+import { shadow } from 'three/tsl';+import { shadowOncePerFrame } from '../../src/shadows/once';++/**+ * three r186's own ShadowNode.updateBefore gating with the GPU work stubbed out: updateShadow counts renders and bumps the+ * depth version on the first one, as the first updateRenderTarget does, so the first update spans two frames.+ */+function counted(light: DirectionalLight) {+ const node = shadow(light) as any;let first = true;const renders: string[] = [];+ node.shadowMap = { depthTexture: { version: 0 } };+ node.updateShadow = (frame: any) => { node._depthVersionCached = node.shadowMap.depthTexture.version; if (first) { node.shadowMap.depthTexture.version++; first = false; } renders.push(`${frame.frameId}:${frame.camera.name}`); };+ return { renders, draw: (frameId: number, camera: PerspectiveCamera, precompiling = false) => node.updateBefore({ renderer: { _isPreCompiling: precompiling }, camera, frameId }) };+}+const main = Object.assign(new PerspectiveCamera(), { name: 'main' }), mirror = Object.assign(new PerspectiveCamera(), { name: 'mirror' });+/** A sun whose shadow camera keeps its own layers (a bit above 0), as Golden Gate's enables LAYERS.dynamic. */+const layered = () => { const light = new DirectionalLight(); light.shadow.camera.layers.enable(2); return light; };++test('without the helper a second camera re-renders the map every frame (the Golden Gate reflector duplicate)', () => {+ const light = new DirectionalLight(), { renders, draw } = counted(light);+ for (let f = 0; f < 3; f++) { draw(f, main); draw(f, main); draw(f, mirror); }+ expect(renders).toEqual(['0:main', '0:mirror', '1:main', '1:mirror', '2:main', '2:mirror']);+});++test('once per frame: armed at install, re-armed by update, reused by the second camera', () => {+ const light = layered(), { renders, draw } = counted(light), once = shadowOncePerFrame(light);+ expect([light.shadow.autoUpdate, light.shadow.needsUpdate]).toEqual([false, true]);+ draw(0, main, true); expect(renders).toEqual([]); // compileAsync never renders shadows+ for (let f = 0; f < 4; f++) { once.update(); draw(f, main); draw(f, mirror); }+ // Frame 0 is the first render, whose depth-texture recreation keeps needsUpdate for the mirror; then one render a frame.+ expect(renders).toEqual(['0:main', '0:mirror', '1:main', '2:main', '3:main']);+ draw(4, main); expect(renders.length).toBe(5); // no update(): nothing armed, nothing rendered+ once.restore(); once.restore();+ expect([light.shadow.autoUpdate, light.shadow.needsUpdate]).toEqual([true, true]);+ light.shadow.needsUpdate = false; once.update(); expect(light.shadow.needsUpdate).toBe(false);+ draw(5, main); draw(5, mirror); expect(renders.slice(5)).toEqual(['5:main', '5:mirror']);+});++test('restore keeps an author-frozen shadow frozen', () => {+ const light = layered(); light.shadow.autoUpdate = false;+ const once = shadowOncePerFrame(light); once.restore();+ expect(light.shadow.autoUpdate).toBe(false);+});++test('RK-2 refuses a shadow camera mask three swaps for each viewing camera mask, where cameras with other layers need their own map', () => {+ // ShadowNode.updateShadow: a mask with no bit at layer 1 or above becomes the rendering camera's mask, so one shared map+ // would carry the first camera's casters into the second camera's view.+ for (const mask of [1, 0]) {+ const light = new DirectionalLight(); light.shadow.camera.layers.mask = mask;+ expect(() => shadowOncePerFrame(light)).toThrow('layer above 0');+ expect([light.shadow.autoUpdate, light.shadow.needsUpdate]).toEqual([true, false]);+ }+ expect(() => shadowOncePerFrame(layered()).restore()).not.toThrow();+});diff --git a/scenes/packages/scene-kit/tests/shadows/pass.test.ts b/scenes/packages/scene-kit/tests/shadows/pass.test.tsnew file mode 100644index 00000000..bf5c3863--- /dev/null+++ b/scenes/packages/scene-kit/tests/shadows/pass.test.ts@@ -0,0 +1,75 @@+import { expect, test } from 'bun:test';+import { BoxGeometry, Group, InstancedMesh, LineSegments, Mesh, MeshStandardMaterial, PerspectiveCamera, PointLight, Raycaster, Vector3 } from 'three/webgpu';+import type { Material, Object3D } from 'three/webgpu';+import { mainOnly, passCameraLayers, passStandIn } from '../../src/shadows/pass';++const MAIN = 27, PASS = 28, L = { main: MAIN, pass: PASS };+const node = (name: string, parent: Object3D | null, x = 0) => { const g = new Group(); g.name = name; g.position.x = x; parent?.add(g); return g; };+/** Golden Gate-like approaches: a near set that should stay out of the reflection and a far set that stands in for it. */+function approaches() {+ const concrete = new MeshStandardMaterial({ name: 'Concrete' }), paint = new MeshStandardMaterial({ name: 'Paint' });+ const world = node('World', null), near = node('approaches-near', world), far = node('approaches-far', world, 2);+ const deck = new Mesh(new BoxGeometry(), concrete); deck.name = 'Deck'; deck.castShadow = deck.receiveShadow = true; deck.layers.enable(2); near.add(deck);+ const rail = new Mesh(new BoxGeometry(), [concrete, paint]); rail.name = 'Rail'; near.add(rail);+ const lamps = new InstancedMesh(new BoxGeometry(), paint, 3); lamps.name = 'Lamps'; near.add(lamps);+ const wire = new LineSegments(new BoxGeometry(), concrete); wire.name = 'Wire'; near.add(wire);+ const shadowOnly = new Mesh(new BoxGeometry(), concrete); shadowOnly.layers.set(29); shadowOnly.userData.kilnShadowStandIn = true; near.add(shadowOnly);+ const farDeck = new Mesh(new BoxGeometry(), concrete); farDeck.name = 'FarDeck'; farDeck.castShadow = true; farDeck.position.y = 1; far.add(node('Span', far)); far.children[0]!.add(farDeck);+ const farLamps = new InstancedMesh(new BoxGeometry(), paint, 2); farLamps.name = 'FarLamps'; far.add(farLamps);+ world.updateMatrixWorld(true);+ return { world, near, far, deck, rail, lamps, wire, shadowOnly, farDeck, farLamps };+}++test('mainOnly moves every drawable on layer 0 to the main-only layer and keeps other bits; restore puts back only what it moved', () => {+ const a = approaches(), groups = [a.world.layers.mask, a.near.layers.mask], r = mainOnly([a.near], MAIN);+ expect(r.stats).toEqual({ objects: 4 });+ expect(a.deck.layers.mask).toBe(1 << MAIN | 1 << 2); for (const o of [a.rail, a.lamps, a.wire]) expect(o.layers.mask).toBe(1 << MAIN);+ expect(a.shadowOnly.layers.mask).toBe(1 << 29); expect([a.world.layers.mask, a.near.layers.mask]).toEqual(groups); expect(a.farDeck.layers.mask).toBe(1);+ a.deck.layers.enable(30); // a later feature's bit survives restore+ r.restore(); r.restore();+ expect(a.deck.layers.mask).toBe(1 | 1 << 2 | 1 << 30); for (const o of [a.rail, a.lamps, a.wire]) expect(o.layers.mask).toBe(1);+ expect(a.shadowOnly.layers.mask).toBe(1 << 29);+ const pre = new Mesh(new BoxGeometry()); pre.layers.enable(MAIN); const again = mainOnly([pre], MAIN); expect(pre.layers.mask).toBe(1 << MAIN); again.restore(); expect(pre.layers.mask).toBe(1 | 1 << MAIN);+});++test('passStandIn clones a representation that shares geometry and materials onto the pass-only layer without changing the source', () => {+ const a = approaches(), before = new Map<Object3D, [number, boolean, string]>();+ a.far.traverse(o => before.set(o, [o.layers.mask, (o as Mesh).castShadow, JSON.stringify(o.userData)]));+ const r = passStandIn(a.far, { layer: PASS }), clone = r.object;+ expect(clone).not.toBe(a.far); expect(clone.parent).toBe(a.world); expect(r.stats).toEqual({ meshes: 2 });+ const deck = clone.getObjectByName('FarDeck') as Mesh, lamps = clone.getObjectByName('FarLamps') as InstancedMesh;+ expect(deck).not.toBe(a.farDeck); expect(deck.geometry).toBe(a.farDeck.geometry); expect(deck.material).toBe(a.farDeck.material);+ expect(lamps.geometry).toBe(a.farLamps.geometry); expect(lamps.material).toBe(a.farLamps.material); expect(lamps.instanceMatrix).toBe(a.farLamps.instanceMatrix);+ clone.traverse(o => expect(o.layers.mask).toBe(1 << PASS));+ for (const m of [deck, lamps]) {+ expect(m.castShadow).toBe(false); expect(m.userData.kilnPassStandIn).toBe(true);+ const ray = new Raycaster(new Vector3(2, 50, 0), new Vector3(0, -1, 0)); ray.layers.enableAll(); expect(ray.intersectObject(m)).toEqual([]);+ }+ clone.updateMatrixWorld(true); expect(deck.matrixWorld.equals(a.farDeck.matrixWorld)).toBe(true);+ for (const [o, [mask, cast, data]] of before) { expect(o.layers.mask).toBe(mask); expect((o as Mesh).castShadow).toBe(cast); expect(JSON.stringify(o.userData)).toBe(data); }+ r.restore(); r.restore(); expect(clone.parent).toBeNull(); expect(a.world.children).not.toContain(clone);+ const holder = node('Reflection stand-ins', a.world), other = passStandIn(a.far, { layer: PASS, parent: holder });+ expect(other.object.parent).toBe(holder); other.restore();+});++test('a multi-material source keeps every material by reference; a source holding a light is refused', () => {+ const a = approaches(), r = passStandIn(a.rail, { layer: PASS }), rail = r.object as Mesh;+ expect((rail.material as Material[]).every((m, i) => m === (a.rail.material as Material[])[i])).toBe(true); r.restore();+ const lit = node('Lit', a.world); lit.add(new Mesh(new BoxGeometry()), new PointLight());+ expect(() => passStandIn(lit, { layer: PASS })).toThrow(); expect(lit.children.length).toBe(2); expect(a.world.children.filter(c => c.name.includes('Lit')).length).toBe(1);+});++test('passCameraLayers sets only the two pass bits, idempotently, for a pass camera cloned from the main camera', () => {+ const main = new PerspectiveCamera(); main.layers.enable(1); main.layers.enable(2);+ expect(passCameraLayers(main, L, 'main')).toBe(1 | 2 | 4 | 1 << MAIN); expect(main.layers.mask).toBe(1 | 2 | 4 | 1 << MAIN);+ const virtual = main.clone(); // three r186 ReflectorNode clones the main camera once and never copies its layers again+ expect(passCameraLayers(virtual, L)).toBe(1 | 2 | 4 | 1 << PASS); expect(passCameraLayers(virtual, L)).toBe(1 | 2 | 4 | 1 << PASS);+ expect(main.layers.mask).toBe(1 | 2 | 4 | 1 << MAIN);+ const a = approaches(), moved = mainOnly([a.near], MAIN), stand = passStandIn(a.far, { layer: PASS });+ const sees = (camera: PerspectiveCamera, o: Object3D) => o.layers.test(camera.layers);+ expect([sees(main, a.rail), sees(main, stand.object.getObjectByName('FarDeck')!), sees(main, a.farDeck)]).toEqual([true, false, true]);+ expect([sees(virtual, a.rail), sees(virtual, stand.object.getObjectByName('FarDeck')!), sees(virtual, a.farDeck)]).toEqual([false, true, true]);+ moved.restore(); stand.restore();+ for (const bad of [{ main: 0, pass: PASS }, { main: MAIN, pass: MAIN }, { main: MAIN, pass: 32 }]) expect(() => passCameraLayers(main, bad)).toThrow();+ expect(() => mainOnly([a.near], 0)).toThrow(); expect(() => passStandIn(a.far, { layer: 0 })).toThrow();+});diff --git a/scenes/packages/scene-kit/tests/shadows/shadow-contract.test.ts b/scenes/packages/scene-kit/tests/shadows/shadow-contract.test.tsnew file mode 100644index 00000000..147a5eda--- /dev/null+++ b/scenes/packages/scene-kit/tests/shadows/shadow-contract.test.ts@@ -0,0 +1,144 @@+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { REVISION } from 'three/webgpu';++// The private three r186 contract src/shadows/{cache,once,threshold}.ts rely on, pinned as source snippets and their order+// in the builds `three/webgpu` and `three/tsl` resolve to (not three/src). An upgrade that moves any of them fails here+// before a cached map can bind a destroyed texture, share a light or render twice. Line numbers are deliberately not pinned.+const BUILD = Bun.resolveSync('three/webgpu', import.meta.dir), TSL_BUILD = Bun.resolveSync('three/tsl', import.meta.dir);+const SOURCE = readFileSync(BUILD, 'utf8'), CORE = readFileSync(join(dirname(BUILD), 'three.core.js'), 'utf8'), TSL = readFileSync(TSL_BUILD, 'utf8');+const VERSION = JSON.parse(readFileSync(join(dirname(BUILD), '..', 'package.json'), 'utf8')).version as string;++/** One class member, from its one-tab-indented signature to its closing brace, searched after `anchor`. */+function member(src: string, anchor: string, signature: string): string {+ const from = src.indexOf(anchor); if (from < 0) return '';+ const start = src.indexOf(`\n\t${signature}`, from); if (start < 0) return '';+ const end = src.indexOf('\n\t}\n', start); return end < 0 ? '' : src.slice(start, end);+}+/** Snippets absent from `body` or out of the given order. */+function unordered(body: string, snippets: string[]): string[] {+ const bad: string[] = []; let at = -1;+ for (const snippet of snippets) { const i = body.indexOf(snippet, at + 1); if (i < 0) bad.push(snippet); else at = i; }+ return bad;+}+const count = (src: string, s: string) => src.split(s).length - 1;+const SHADOW_NODE = 'class ShadowNode extends ShadowBaseNode {', LIGHT_NODE = 'class AnalyticLightNode extends LightingNode {', OBSERVER = 'class NodeMaterialObserver {';++function pinFailures(src: string, core: string, tsl: string): Record<string, string[]> {+ const pins: Record<string, string[]> = {+ // A shadow camera mask with no bit at layer 1 or above is swapped for the viewing camera's for the render.+ maskFallback: unordered(member(src, SHADOW_NODE, 'updateShadow( frame ) {'), [+ 'const depthVersion = shadowMap.depthTexture.version;',+ 'this._depthVersionCached = depthVersion;',+ 'const _shadowCameraLayer = shadow.camera.layers.mask;',+ 'if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {',+ 'shadow.camera.layers.mask = camera.layers.mask;',+ 'scene.overrideMaterial = this.getShadowMaterial();',+ 'this.renderShadow( frame );',+ 'shadow.camera.layers.mask = _shadowCameraLayer;',+ ]),+ // Never during pre-compile; once per (camera, frameId) while armed; the flag clears only when the depth version held.+ updateBefore: [+ ...unordered(member(src, SHADOW_NODE, 'updateBefore( frame ) {'), [+ 'if ( frame.renderer._isPreCompiling === true ) return;',+ 'let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;',+ 'if ( needsUpdate ) {',+ 'if ( this._cameraFrameId.get( frame.camera ) === frame.frameId ) {',+ 'needsUpdate = false;',+ 'this._cameraFrameId.set( frame.camera, frame.frameId );',+ 'this.updateShadow( frame );',+ 'if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {',+ 'shadow.needsUpdate = false;',+ ]),+ ...(count(member(src, SHADOW_NODE, 'updateBefore( frame ) {'), 'needsUpdate = ') === 3 ? [] : ['another needsUpdate write']),+ ],+ // Each render projects with the node's own shadow and light (the placeholder) and names the pass after it.+ renderShadow: unordered(member(src, SHADOW_NODE, 'renderShadow( frame ) {'), [+ 'const { shadow, shadowMap, light } = this;',+ 'shadow.updateMatrices( light );',+ 'shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );',+ "scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;",+ 'renderer.render( scene, shadow.camera );',+ ]),+ // shadow(light, S) samples S through its own node; dispose frees the node's map and the per-light material.+ shadowNode: [+ ...unordered(src, ['this.shadow = shadow || light.shadow;', 'const shadow = ( light, shadow ) => new ShadowNode( light, shadow );']),+ ...unordered(member(src, SHADOW_NODE, 'setupShadow( builder ) {'), ['shadow.camera.coordinateSystem = camera.coordinateSystem;', 'shadow.camera.updateProjectionMatrix();', 'this.shadow.map = shadowMap;']),+ ...unordered(member(src, SHADOW_NODE, '_reset() {'), ['this.disposeShadowMaterial();', 'this.shadowMap.dispose();', 'this.shadowMap = null;']),+ ...unordered(src, ['const _getShadowMaterial = ( light ) => {', 'let material = _shadowMaterialLib.get( light );']),+ ...unordered(src, ['if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {']),+ ],+ // light.shadow.shadowNode is read once per light node (its only reader); castShadow off disposes the node it built.+ customShadowNode: [+ ...unordered(member(src, LIGHT_NODE, 'setupShadow( builder ) {'), [+ 'let shadowColorNode = this.shadowColorNode;',+ 'if ( shadowColorNode === null ) {',+ 'const customShadowNode = this.light.shadow.shadowNode;',+ 'if ( customShadowNode !== undefined ) {',+ 'shadowNode = nodeObject( customShadowNode );',+ 'this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );',+ ]),+ ...unordered(member(src, LIGHT_NODE, 'setup( builder ) {'), ['if ( this.light.castShadow ) {', '} else if ( this.shadowNode !== null ) {', 'this.shadowNode.dispose();']),+ ...(count(src, 'shadow.shadowNode') === 1 ? [] : ['another shadowNode reader']),+ ],+ // Receivers rebind on a shadow map resize only through the scene light's mapSize (the kit's sentinel).+ observerSentinel: [+ ...unordered(member(src, OBSERVER, 'getLightsData( materialLights, lights ) {'), [+ 'if ( light.castShadow === true && light.shadow !== undefined ) {',+ 'data.shadowMapWidth = light.shadow.mapSize.width;',+ 'data.shadowMapHeight = light.shadow.mapSize.height;',+ ]),+ ...unordered(member(src, OBSERVER, 'equals( renderObject, lightsData, renderId ) {'), ['lightData.shadowMapWidth !== currentLightData.shadowMapWidth || lightData.shadowMapHeight !== currentLightData.shadowMapHeight']),+ ...unordered(src, ['this.getLightsData( lightsNode.getBuiltinLights(), cached.lightsData );']),+ ],+ // A casting light's shadow matrix is whatever its last shadow render left (a cached map keeps its own frame).+ shadowMatrix: unordered(src.slice(src.indexOf('function lightShadowMatrix( light ) {')), [+ 'if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {',+ 'light.shadow.updateMatrices( light );',+ 'return light.shadow.matrix;',+ ]),+ // Visibility is inherited, layers are tested per object, children are always visited.+ projectObject: unordered(member(src, 'class Renderer {', '_projectObject( object, camera, groupOrder, renderList, clippingContext ) {'), [+ 'if ( object.visible === false ) return;',+ 'const visible = object.layers.test( camera.layers );',+ 'const children = object.children;',+ 'this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );',+ ]),+ // Clones get their own camera (and mask); matrices come from the light's and target's world matrices, and the+ // projection is not recomputed there, so synced extents need updateProjectionMatrix.+ lightShadow: [+ ...unordered(member(core, 'class LightShadow {', 'copy( source ) {'), ['this.camera = source.camera.clone();', 'this.mapSize.copy( source.mapSize );']),+ ...unordered(member(core, 'class LightShadow {', 'clone() {'), ['return new this.constructor().copy( this );']),+ ...unordered(member(core, 'class LightShadow {', 'updateMatrices( light ) {'), ['_lightPositionWorld.setFromMatrixPosition( light.matrixWorld );', '_lookTarget.setFromMatrixPosition( light.target.matrixWorld );', 'shadowCamera.updateMatrixWorld();']),+ ...(member(core, 'class LightShadow {', 'updateMatrices( light ) {').includes('updateProjectionMatrix') ? ['updateMatrices recomputes the projection'] : []),+ ],+ layers: unordered(core.slice(core.indexOf('class Layers {')), ['this.mask |= 1 << layer | 0;', 'return ( this.mask & layers.mask ) !== 0;']),+ tsl: unordered(tsl, ['const min = TSL.min;', 'const shadow = TSL.shadow;']),+ };+ return pins;+}+const clean = (pins: Record<string, string[]>) => Object.fromEntries(Object.entries(pins).filter(([, bad]) => bad.length));++describe('three r186 contract for the cached sun shadow, once-per-frame and threshold', () => {+ test('the builds three/webgpu and three/tsl resolve to are 0.186.0', () => {+ expect(BUILD.replaceAll('\\', '/')).toEndWith('three/build/three.webgpu.js');+ expect(TSL_BUILD.replaceAll('\\', '/')).toEndWith('three/build/three.tsl.js');+ expect(VERSION).toBe('0.186.0'); expect(REVISION).toBe('186');+ });+ test('every pinned snippet is present and in order', () => {+ expect(clean(pinFailures(SOURCE, CORE, TSL))).toEqual({});+ });+ test('the pins notice a dropped mask fallback, pre-compile guard, frame dedupe, sentinel, second reader or projection change', () => {+ const fails = (src: string, core = CORE) => Object.keys(clean(pinFailures(src, core, TSL)));+ expect(fails(SOURCE.replace('if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {', 'if ( shadow.camera.layers.mask === 0 ) {'))).toEqual(['maskFallback']);+ expect(fails(SOURCE.replace('if ( frame.renderer._isPreCompiling === true ) return;', ''))).toEqual(['updateBefore']);+ expect(fails(SOURCE.replace('if ( this._cameraFrameId.get( frame.camera ) === frame.frameId ) {', 'if ( false ) {'))).toEqual(['updateBefore']);+ const before = member(SOURCE, SHADOW_NODE, 'updateBefore( frame ) {');+ expect(fails(SOURCE.replace(before, before.replace('this.updateShadow( frame );', 'this.updateShadow( frame ); shadow.needsUpdate = false;')))).toEqual(['updateBefore']);+ expect(fails(SOURCE.replace('data.shadowMapWidth = light.shadow.mapSize.width;', 'data.shadowMapWidth = light.shadow.map?.width;'))).toEqual(['observerSentinel']);+ expect(fails(SOURCE.replace('class Renderer {', 'class Renderer {\n\tx( l ) { return l.shadow.shadowNode; }'))).toEqual(['customShadowNode']);+ const update = member(CORE, 'class LightShadow {', 'updateMatrices( light ) {');+ expect(fails(SOURCE, CORE.replace(update, update.replace('shadowCamera.updateMatrixWorld();', 'shadowCamera.updateProjectionMatrix(); shadowCamera.updateMatrixWorld();')))).toEqual(['lightShadow']);+ });+});diff --git a/scenes/packages/scene-kit/tests/shadows/stand-ins.test.ts b/scenes/packages/scene-kit/tests/shadows/stand-ins.test.tsnew file mode 100644index 00000000..8252d0b6--- /dev/null+++ b/scenes/packages/scene-kit/tests/shadows/stand-ins.test.ts@@ -0,0 +1,272 @@+import { expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import {+ BackSide, BatchedMesh, Box3, BoxGeometry, BufferAttribute, BufferGeometry, ClippingGroup, DoubleSide, FrontSide, Group, InstancedBufferGeometry, InstancedMesh, InterleavedBuffer,+ InterleavedBufferAttribute, LOD, Matrix4, Mesh, MeshPhysicalMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, Raycaster, Scene, SkinnedMesh, Texture, Vector3,+} from 'three/webgpu';+import type { Material, Object3D } from 'three/webgpu';+import { float, positionLocal, vec4 } from 'three/tsl';+import { shadowStandIns } from '../../src/shadows/stand-ins';+import { suppressedCasters } from '../../src/shadows/layers';+import { createFrameGraph, freezeTransforms } from '../../src/instancing/core';+import type { InstanceOwner } from '../../src/instancing/core';++const LAYER = 29, isAnchor = (n: Object3D) => /^Joint_/.test(n.name);+const box = (x = 1, y = 1, z = 1) => { const g = new BoxGeometry(x, y, z); g.clearGroups(); return g; };+const node = (name: string, parent: Object3D | null, x = 0, y = 0, z = 0) => { const g = new Group(); g.name = name; g.position.set(x, y, z); parent?.add(g); return g; };+const mesh = (name: string, material: Material | Material[], parent: Object3D, x = 0, y = 0, z = 0, geometry: BufferGeometry = box()) => {+ const m = new Mesh(geometry, material); m.name = name; m.position.set(x, y, z); m.castShadow = true; parent.add(m); return m;+};+const tris = (g: BufferGeometry) => (g.index ? g.index.count : g.attributes.position!.count) / 3;+const sum = (meshes: Mesh[]) => meshes.reduce((n, m) => n + tris(m.geometry), 0);+const worldBox = (meshes: Mesh[]) => {+ const b = new Box3(), v = new Vector3();+ for (const m of meshes) { const p = m.geometry.attributes.position!; for (let i = 0; i < p.count; i++) b.expandByPoint(v.fromBufferAttribute(p, i).applyMatrix4(m.matrixWorld)); }+ return b;+};+const closeBox = (a: Box3, b: Box3) => { expect(a.min.distanceTo(b.min)).toBeLessThan(1e-5); expect(a.max.distanceTo(b.max)).toBeLessThan(1e-5); };+/** World-space triangles in draw order, each as the geometric normal of its winding. */+const normals = (m: Mesh) => {+ const g = m.geometry, p = g.attributes.position!, out: Vector3[] = [], a = new Vector3(), b = new Vector3(), c = new Vector3();+ for (let i = 0; i < tris(g) * 3; i += 3) {+ const at = (k: number) => g.index ? g.index.getX(k) : k;+ a.fromBufferAttribute(p, at(i)).applyMatrix4(m.matrixWorld); b.fromBufferAttribute(p, at(i + 1)).applyMatrix4(m.matrixWorld); c.fromBufferAttribute(p, at(i + 2)).applyMatrix4(m.matrixWorld);+ out.push(b.clone().sub(a).cross(c.clone().sub(a)).normalize());+ }+ return out;+};+/** A ray that hits the mesh's first triangle on its front face from one metre out, whatever layers the mesh is on. */+const aimed = (m: Mesh) => {+ const g = m.geometry, p = g.attributes.position!, at = (k: number) => new Vector3().fromBufferAttribute(p, g.index ? g.index.getX(k) : k).applyMatrix4(m.matrixWorld);+ const centre = at(0).add(at(1)).add(at(2)).divideScalar(3), n = normals(m)[0]!, ray = new Raycaster(centre.clone().addScaledVector(n, 1), n.clone().negate()); ray.layers.enableAll(); return ray;+};++/** A farmhouse-like placement: a rotated root, a scaled shell, single- and double-sided parts, glass, a door anchor and a non-caster. */+function farmhouse() {+ const stone = new MeshStandardMaterial({ name: 'Stone' }), wood = new MeshStandardMaterial({ name: 'Wood', side: DoubleSide });+ const glass = new MeshStandardMaterial({ name: 'Glass', transparent: true, opacity: .4, side: DoubleSide });+ const root = node('House', null, 10, 0, -4); root.rotation.y = .5;+ const shell = node('Shell', root, 1, 0, 0); shell.rotation.z = .2; shell.scale.set(1, 2, 1);+ const front = [mesh('WallA', stone, shell), mesh('WallB', stone, shell, 2), mesh('Roof', stone, root, 0, 3)];+ const double = [mesh('Fence', wood, root, 0, 0, 5), mesh('Window', glass, shell, 0, 0, 1)];+ const door = node('Joint_FrontDoor', root, 3); door.rotation.y = .3;+ const leaf = [mesh('Leaf', stone, door, .5, 1), mesh('Hinge', stone, node('Hardware', door, 0, .5), 0, 0, 0, box(.1, .2, .1))];+ const rug = mesh('Rug', stone, root, 0, -.1); rug.castShadow = false;+ root.updateMatrixWorld(true);+ return { root, shell, door, front, double, leaf, rug, eligible: [...front, ...double, ...leaf], materials: { stone, wood, glass } };+}++test('one proxy per anchor and effective shadow side, sharing one material per side; sources stop casting', () => {+ const h = farmhouse(), r = shadowStandIns(h.root, { layer: LAYER, isAnchor });+ expect(r.stats).toEqual({ groups: 3, sourceMeshes: 7, proxies: 3, triangles: 7 * 12, dropped: 0, skipped: { noCast: 1 } });+ expect(r.sources.map(s => s.name).sort()).toEqual(h.eligible.map(m => m.name).sort());+ const of = (anchor: Object3D, side: number) => r.proxies.filter(p => p.parent === anchor && (p.material as Material).shadowSide === side);+ expect(of(h.root, BackSide).length).toBe(1); expect(of(h.root, DoubleSide).length).toBe(1); expect(of(h.door, BackSide).length).toBe(1);+ expect(sum(of(h.root, BackSide))).toBe(sum(h.front)); expect(sum(of(h.root, DoubleSide))).toBe(sum(h.double)); expect(sum(of(h.door, BackSide))).toBe(sum(h.leaf));+ const back = of(h.root, BackSide)[0]!.material as Material;+ expect(of(h.door, BackSide)[0]!.material).toBe(back);+ expect([back.side, back.shadowSide, back.colorWrite, back.depthWrite, back.transparent]).toEqual([FrontSide, BackSide, false, false, false]);+ expect([(of(h.root, DoubleSide)[0]!.material as Material).side, (of(h.root, DoubleSide)[0]!.material as Material).transparent]).toEqual([DoubleSide, false]);+ for (const p of r.proxies) {+ expect(p.layers.mask).toBe(1 << LAYER); expect([p.castShadow, p.receiveShadow]).toEqual([true, false]); expect(p.userData.kilnShadowStandIn).toBe(true);+ expect(p.matrix.equals(new Matrix4())).toBe(true); expect(p.matrixAutoUpdate).toBe(false); expect(p.matrixWorld.equals(p.parent!.matrixWorld)).toBe(true);+ expect(Object.keys(p.geometry.attributes)).toEqual(['position']); expect((p.material as Material & { isNodeMaterial?: boolean }).isNodeMaterial).toBe(true);+ const ray = aimed(p), control = new Mesh(p.geometry, new MeshStandardMaterial()); control.matrixWorld.copy(p.matrixWorld);+ expect(ray.intersectObject(control).length).toBeGreaterThan(0); expect(ray.intersectObject(p)).toEqual([]);+ }+ for (const m of h.eligible) { expect(m.castShadow).toBe(false); expect(suppressedCasters.has(m)).toBe(true); expect(m.visible).toBe(true); expect(m.layers.mask).toBe(1); }+ expect(h.rug.castShadow).toBe(false); expect(suppressedCasters.has(h.rug)).toBe(false);+ r.restore();+});++test('an explicit shadowSide groups with the side three derives: Front with shadowSide Front joins Back', () => {+ const root = node('R', null), a = mesh('A', new MeshStandardMaterial({ side: BackSide }), root), b = mesh('B', new MeshStandardMaterial({ shadowSide: FrontSide }), root, 2);+ const c = mesh('C', new MeshStandardMaterial(), root, 4);+ const r = shadowStandIns(root, { layer: LAYER, isAnchor });+ expect(r.stats.proxies).toBe(2);+ const front = r.proxies.find(p => (p.material as Material).shadowSide === FrontSide)!, back = r.proxies.find(p => (p.material as Material).shadowSide === BackSide)!;+ expect(sum([front])).toBe(sum([a, b])); expect(sum([back])).toBe(sum([c])); expect((front.material as Material).side).toBe(BackSide);+});++test('world-space depth silhouette: proxy bounds and triangle totals equal the eligible sources', () => {+ const h = farmhouse(), b0 = worldBox(h.eligible), t0 = sum(h.eligible), r = shadowStandIns(h.root, { layer: LAYER, isAnchor });+ h.root.updateMatrixWorld(true);+ expect(r.stats.triangles).toBe(t0); expect(sum(r.proxies)).toBe(t0); closeBox(worldBox(r.proxies), b0);+ for (const anchor of [h.root, h.door]) {+ const own = r.proxies.filter(p => p.parent === anchor), src = r.sources.filter(s => { let n = s.parent!; while (n !== h.root && !isAnchor(n)) n = n.parent!; return n === anchor; });+ closeBox(worldBox(own), worldBox(src));+ }+ r.restore();+});++test('proxies follow anchor motion through world updates', () => {+ const h = farmhouse(), r = shadowStandIns(h.root, { layer: LAYER, isAnchor }), door = r.proxies.find(p => p.parent === h.door)!;+ h.door.rotation.y = 1.4; h.root.position.x = -6; h.root.updateWorldMatrix(true, true); // as the Farm's door.apply does+ expect(door.matrixWorld.equals(h.door.matrixWorld)).toBe(true); closeBox(worldBox([door]), worldBox(h.leaf));+ h.door.visible = false; expect(door.parent!.visible).toBe(false);+ r.restore();+ // An anchor hidden at build time (Joint_Pitchfork, the play-only farmer) still gets its proxy, which inherits the anchor's visibility.+ const again = shadowStandIns(h.root, { layer: LAYER, isAnchor });+ expect(again.proxies.filter(p => p.parent === h.door).length).toBe(1); expect(again.stats.skipped).toEqual({ noCast: 1 }); again.restore();+});++test('a mirrored part has its winding reversed so its depth faces match the source', () => {+ const root = node('R', null), mirror = node('Mirror', root, 2); mirror.scale.set(-1, 1, 1);+ const tri = new BufferGeometry(); tri.setAttribute('position', new BufferAttribute(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), 3));+ const plain = mesh('Plain', new MeshStandardMaterial(), root, 0, 0, 0, tri), flipped = mesh('Flipped', new MeshStandardMaterial(), mirror, 0, 0, 0, tri);+ root.updateMatrixWorld(true);+ const r = shadowStandIns(root, { layer: LAYER, isAnchor }), p = r.proxies[0]!;+ expect(normals(plain)[0]!.z).toBeCloseTo(1); expect(normals(flipped)[0]!.z).toBeCloseTo(-1); // three draws the mirrored source front face towards +z (frontFaceCW)+ expect(normals(p).map(n => Math.round(n.z))).toEqual([1, 1]);+});++test('dequantised, interleaved and non-indexed positions bake to the source world positions', () => {+ const root = node('R', null, 1, 2, 3), q = new BufferGeometry(), i = new BufferGeometry();+ q.setAttribute('position', new BufferAttribute(new Int16Array([0, 0, 0, 32767, 0, 0, 0, 32767, 0, 0, 0, -32767, 16384, 0, 0, 0, 0, 32767]), 3, true));+ const buffer = new InterleavedBuffer(new Float32Array([0, 0, 0, 9, 1, 0, 0, 9, 0, 1, 0, 9]), 4); i.setAttribute('position', new InterleavedBufferAttribute(buffer, 3, 0)); i.setIndex([0, 1, 2]);+ const quantised = mesh('Quantised', new MeshStandardMaterial(), root, 0, 0, 0, q); quantised.scale.setScalar(4);+ const interleaved = mesh('Interleaved', new MeshStandardMaterial(), root, 3, 0, 0, i); root.updateMatrixWorld(true);+ const r = shadowStandIns(root, { layer: LAYER, isAnchor }), p = r.proxies[0]!, pos = p.geometry.attributes.position!, v = new Vector3(), w = new Vector3();+ expect(pos.array).toBeInstanceOf(Float32Array); expect(pos.count).toBe(9);+ let k = 0;+ for (const m of [quantised, interleaved]) for (let j = 0; j < m.geometry.attributes.position!.count; j++, k++) {+ v.fromBufferAttribute(pos, k).applyMatrix4(p.matrixWorld); w.fromBufferAttribute(m.geometry.attributes.position!, j).applyMatrix4(m.matrixWorld);+ expect(v.distanceTo(w)).toBeLessThan(1e-5);+ }+ expect(Array.from(p.geometry.index!.array)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]);+});++test('spatial chunks split a group by the world-bounds centre cell, then by the triangle cap', () => {+ const root = node('Bridge', null), paint = new MeshStandardMaterial(), parts = [0, 10, 40, 120, 130, 260].map((x, k) => mesh(`P${k}`, paint, root, x, k === 5 ? -500 : 0, 0));+ const big = mesh('Big', paint, root, 270, 0, 0, new BoxGeometry(1, 1, 1, 4, 4, 4)); big.geometry.clearGroups(); root.updateMatrixWorld(true);+ const r = shadowStandIns(root, { layer: LAYER, isAnchor, chunk: { cell: 100, maxTriangles: 24 } });+ // Cells 0 (P0, P1, P2: 36 triangles, capped into 24 + 12), 1 (P3, P4) and 2 (P5 at any height, then Big alone: one part over the cap).+ expect(r.stats.groups).toBe(3); expect(r.proxies.map(p => tris(p.geometry))).toEqual([24, 12, 24, 12, tris(big.geometry)]);+ expect(r.stats.proxies).toBe(5); expect(r.stats.triangles).toBe(sum([...parts, big]));+ const unchunked = (r.restore(), shadowStandIns(root, { layer: LAYER, isAnchor, chunk: { cell: 1000 } }));+ expect(unchunked.stats.proxies).toBe(1); unchunked.restore();+});++test('more than 65,535 proxy vertices take a Uint32 index; smaller proxies keep Uint16', () => {+ const soup = () => { const g = new BufferGeometry(); g.setAttribute('position', new BufferAttribute(new Float32Array(39999 * 3).map((_, k) => k % 7), 3)); return g; };+ const root = node('R', null), a = mesh('A', new MeshStandardMaterial(), root, 0, 0, 0, soup()); mesh('B', a.material as Material, root, 1, 0, 0, soup());+ const door = node('Joint_Small', root); mesh('C', a.material as Material, door);+ const r = shadowStandIns(root, { layer: LAYER, isAnchor });+ expect(r.proxies.find(p => p.parent === root)!.geometry.index!.array).toBeInstanceOf(Uint32Array);+ expect(r.proxies.find(p => p.parent === door)!.geometry.index!.array).toBeInstanceOf(Uint16Array);+});++test('every exclusion is counted by reason and left casting as it was', () => {+ const root = node('R', null), basic = () => new MeshStandardNodeMaterial(), with_ = (k: string, v: unknown) => Object.assign(new MeshStandardNodeMaterial(), { [k]: v });+ const cases: Record<string, Object3D[]> = {};+ const add = (reason: string, o: Object3D) => { (cases[reason] ??= []).push(o); if (!o.parent) root.add(o); return o; };+ add('hidden', Object.assign(mesh('Hidden', basic(), root), { visible: false })); const shut = node('Shutters', root); shut.visible = false; add('hidden', mesh('Veiled', basic(), shut));+ add('noCast', Object.assign(mesh('NoCast', basic(), root), { castShadow: false }));+ add('include', mesh('Excluded', basic(), root));+ add('multiMaterial', mesh('Multi', [basic(), basic()], root));+ const inst = new InstancedMesh(box(), basic(), 2); inst.castShadow = true; add('instanced', inst);+ add('instanced', mesh('InstGeo', basic(), root, 0, 0, 0, Object.assign(new InstancedBufferGeometry(), { attributes: box().attributes, index: box().index })));+ const batched = new BatchedMesh(1, 24, 36, basic()); batched.castShadow = true; add('batched', batched);+ const skin = new SkinnedMesh(box(), basic()); skin.castShadow = true; add('skinned', skin);+ const morph = box(); morph.morphAttributes.position = [new BufferAttribute(new Float32Array(72), 3)]; add('morphed', mesh('Morph', basic(), root, 0, 0, 0, morph));+ const ranged = box(); ranged.setDrawRange(0, 12); add('drawRange', mesh('Ranged', basic(), root, 0, 0, 0, ranged));+ add('hook', Object.assign(mesh('Hooked', basic(), root), { onBeforeShadow() {} }));+ add('materialHidden', mesh('Invisible', Object.assign(basic(), { visible: false }), root));+ add('allowOverride', mesh('OwnShadow', Object.assign(basic(), { allowOverride: false }), root));+ add('alphaTest', mesh('Cutout', Object.assign(basic(), { alphaTest: .5 }), root));+ add('alphaMap', mesh('AlphaMap', with_('alphaMap', new Texture()), root));+ add('alphaHash', mesh('AlphaHash', with_('alphaHash', true), root));+ add('transmission', mesh('Clear', new MeshPhysicalMaterial({ transmission: 1 }), root));+ add('displacementMap', mesh('Displaced', with_('displacementMap', new Texture()), root));+ for (const k of ['positionNode', 'castShadowPositionNode', 'maskNode', 'maskShadowNode', 'castShadowNode', 'transmissionNode', 'backdropNode', 'depthNode'])+ add(k, mesh(k, with_(k, k === 'castShadowNode' || k === 'backdropNode' ? vec4(1) : k.startsWith('position') || k.startsWith('castShadowP') ? positionLocal : float(1)), root));+ const lod = new LOD(); lod.addLevel(Object.assign(new Mesh(box(), basic()), { castShadow: true, name: 'Level' }), 0); add('lod', lod);+ const clip = new ClippingGroup(); clip.add(Object.assign(new Mesh(box(), basic()), { castShadow: true })); add('clipping', clip);+ add('standIn', Object.assign(mesh('Proxy', basic(), root), { userData: { kilnShadowStandIn: true } }));+ const kept = mesh('Kept', basic(), root), lodded = new LOD(), level = node('Joint_Level', null), inLevel = mesh('InLevel', basic(), level);+ lodded.addLevel(level, 0); root.add(lodded); // a LOD above an anchor is fine: the proxy lives inside the level+ const casting = new Map<Mesh, boolean>(); root.traverse(o => { if ((o as Mesh).isMesh) casting.set(o as Mesh, (o as Mesh).castShadow); });+ const r = shadowStandIns(root, { layer: LAYER, isAnchor, include: m => m.name !== 'Excluded' });+ const expected = Object.fromEntries(Object.entries(cases).map(([k, v]) => [k, v.length]));+ expect(r.stats.skipped).toEqual(expected);+ expect(r.sources).toEqual([kept, inLevel]); expect(r.stats.proxies).toBe(2); expect(r.proxies[1]!.parent).toBe(level);+ for (const [m, was] of casting) if (m !== kept && m !== inLevel) { expect(m.castShadow).toBe(was); expect(suppressedCasters.has(m)).toBe(false); }+ r.restore();+});++test('plain transparent glass is included as opaque depth; three r186 draws it so in the shadow pass', () => {+ // The shadow material blends nothing and writes depth, and a transparent source only adds a second (back) draw when double-sided.+ const src = readFileSync(Bun.resolveSync('three/webgpu', import.meta.dir), 'utf8');+ expect(src).toContain("material.name = 'ShadowMaterial';\n\t\tmaterial.blending = NoBlending;");+ expect(src).toContain('overrideMaterial.side = ( material.shadowSide !== null ) ? material.shadowSide : _shadowSide[ material.side ];');+ expect(src).toContain('overrideMaterial.alphaTest = material.alphaTest;');+ expect(src).toContain('if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {');+ const h = farmhouse(), r = shadowStandIns(h.root, { layer: LAYER, isAnchor }), pane = h.double[1]!;+ expect(r.sources).toContain(pane); expect(pane.castShadow).toBe(false);+ expect((r.proxies.find(p => (p.material as Material).shadowSide === DoubleSide)!.material as Material).transparent).toBe(false);+});++test('parts under the texel threshold are measured per part, dropped from the geometry and stop casting', () => {+ const h = farmhouse(), bolt = mesh('Bolt', h.materials.stone, h.door, 0, 0, 0, box(.02, .02, .02)), scaled = node('Scaled', h.door); scaled.scale.setScalar(10);+ const big = mesh('BigBolt', h.materials.stone, scaled, 0, 0, 0, box(.02, .02, .02)), lone = node('Joint_Lone', h.root), only = mesh('OnlyTiny', h.materials.stone, lone, 0, 0, 0, box(.01, .01, .01));+ // No world update here: the build brings world matrices current before it measures, so BigBolt's parent scale counts.+ const r = shadowStandIns(h.root, { layer: LAYER, isAnchor, texel: .05, minCasterTexels: 2 }); // diameter under 0.1 m drops; the hinge is 0.24 m+ expect(r.dropped.map(m => m.name).sort()).toEqual([bolt.name, only.name].sort()); expect(r.stats.dropped).toBe(2);+ expect(r.sources).toContain(big); expect(r.sources).not.toContain(bolt);+ expect(r.proxies.some(p => p.parent === lone)).toBe(false); expect(r.stats.groups).toBe(3);+ expect(r.stats.triangles).toBe(sum([...h.eligible, big]));+ for (const m of [bolt, only]) { expect(m.castShadow).toBe(false); expect(suppressedCasters.has(m)).toBe(true); }+ r.restore();+ for (const m of [bolt, only, big]) { expect(m.castShadow).toBe(true); expect(suppressedCasters.has(m)).toBe(false); }+ const off = shadowStandIns(h.root, { layer: LAYER, isAnchor, texel: .05 }); expect(off.stats.dropped).toBe(0); off.restore();+});++test('frozen owners stay immutable in the frame graph whether stand-ins come before or after freezing; dynamic owners carry their proxies', () => {+ for (const order of ['before', 'after'] as const) {+ const scene = new Scene(), world = node('World', scene), fixed = node('Fixed', world, 5, 0, 2), cart = node('Cart', world, -3), stone = new MeshStandardMaterial();+ mesh('PostA', stone, fixed); mesh('PostB', stone, fixed, 1); mesh('Bed', stone, cart); mesh('Wheel', stone, cart, 1);+ const owners: InstanceOwner[] = [{ id: 'fixed', object: fixed, dynamic: false, assetId: 'post' }, { id: 'cart', object: cart, dynamic: true, assetId: 'cart' }];+ const isFixed = (o: InstanceOwner) => o.id === 'fixed', owner = (n: Object3D) => n === fixed || n === cart;+ let r: ReturnType<typeof shadowStandIns>, frozen: ReturnType<typeof freezeTransforms>;+ if (order === 'before') { r = shadowStandIns(world, { layer: LAYER, isAnchor: owner }); frozen = freezeTransforms(owners, isFixed); }+ else { frozen = freezeTransforms(owners, isFixed); r = shadowStandIns(world, { layer: LAYER, isAnchor: owner }); }+ const graph = createFrameGraph({ scene, worldRoot: world, owners, batches: null, isFixed, validateStatic: true });+ expect(graph.stats.dynamicRoots).toBe(1);+ const still = r.proxies.find(p => p.parent === fixed)!, moving = r.proxies.find(p => p.parent === cart)!;+ expect([still.matrixAutoUpdate, still.matrixWorldAutoUpdate]).toEqual([false, false]);+ expect(still.matrixWorld.equals(fixed.matrixWorld)).toBe(true); expect(still.matrixWorld.elements[12]).toBe(5);+ cart.position.x = 7; graph.update();+ expect(moving.matrixWorld.equals(cart.matrixWorld)).toBe(true); expect(moving.matrixWorld.elements[12]).toBe(7);+ graph.restore(); frozen.restore(); r.restore();+ }+});++test('restore removes proxies, disposes their geometry and materials, and brings casting back; it runs once', () => {+ const h = farmhouse(), r = shadowStandIns(h.root, { layer: LAYER, isAnchor }), disposed: string[] = [];+ for (const p of r.proxies) p.geometry.addEventListener('dispose', () => disposed.push('geometry'));+ for (const m of new Set(r.proxies.map(p => p.material as Material))) m.addEventListener('dispose', () => disposed.push('material'));+ const parents = r.proxies.map(p => p.parent);+ r.restore(); r.restore();+ expect(parents.every(p => p !== null)).toBe(true); for (const p of r.proxies) expect(p.parent).toBeNull();+ expect(disposed.filter(d => d === 'geometry').length).toBe(3); expect(disposed.filter(d => d === 'material').length).toBe(2);+ for (const m of h.eligible) { expect(m.castShadow).toBe(true); expect(suppressedCasters.has(m)).toBe(false); }+ expect(h.rug.castShadow).toBe(false);+ let n = 0; h.root.traverse(o => { if (o.userData.kilnShadowStandIn) n++; }); expect(n).toBe(0);+});++test('stand-ins never take layer 0 or an out-of-range layer', () => {+ const h = farmhouse();+ for (const layer of [0, 32, 1.5]) expect(() => shadowStandIns(h.root, { layer, isAnchor })).toThrow();+ for (const m of h.eligible) expect(m.castShadow).toBe(true);+});++test('RK-4 sources the shadow camera cannot see are skipped as layer (default: layer 0 only); the camera must see the stand-in layer', () => {+ const root = new Group(), stone = new MeshStandardMaterial(), a = mesh('onLayer0', stone, root), b = mesh('onLayer5', stone, root, 3), c = mesh('onLayer2', stone, root, 6);+ b.layers.set(5); c.layers.set(2); root.updateMatrixWorld(true);+ const r = shadowStandIns(root, { layer: LAYER, isAnchor });+ expect(r.sources).toEqual([a]); expect(r.stats.skipped).toEqual({ layer: 2 }); expect([b.castShadow, c.castShadow, suppressedCasters.has(b)]).toEqual([true, true, false]);+ r.restore();+ const seen = shadowStandIns(root, { layer: LAYER, isAnchor, shadowMask: 1 | 1 << 2 | 1 << LAYER });+ expect(seen.sources).toEqual([a, c]); expect(seen.stats.skipped).toEqual({ layer: 1 }); seen.restore();+ expect(() => shadowStandIns(root, { layer: LAYER, isAnchor, shadowMask: 1 | 1 << 2 })).toThrow('stand-in layer');+});diff --git a/scenes/packages/scene-kit/tests/shadows/threshold.test.ts b/scenes/packages/scene-kit/tests/shadows/threshold.test.tsnew file mode 100644index 00000000..66144271--- /dev/null+++ b/scenes/packages/scene-kit/tests/shadows/threshold.test.ts@@ -0,0 +1,103 @@+import { expect, test } from 'bun:test';+import { BoxGeometry, CylinderGeometry, DirectionalLight, Group, InstancedMesh, Matrix4, Mesh, MeshStandardMaterial, Scene, SpotLight } from 'three/webgpu';+import { casterTexels, shadowTexelSize, smallCasterThreshold } from '../../src/shadows/threshold';+import { suppressedCasters } from '../../src/shadows/layers';+import { casterSize } from '../../src/testing/probe-core';++const material = new MeshStandardMaterial();+/** A Farm-like sun: ±44 m orthographic box, looking down from `position` at the origin. */+function sun(position: [number, number, number], mapSize = 2048) {+ const light = new DirectionalLight(); light.position.set(...position); light.castShadow = true; light.shadow.mapSize.setScalar(mapSize);+ Object.assign(light.shadow.camera, { left: -44, right: 44, top: 44, bottom: -44, near: 1, far: 115 }); light.shadow.camera.updateProjectionMatrix();+ light.updateMatrixWorld(true); light.target.updateMatrixWorld(true); return light;+}+const mesh = (w: number, h: number, d: number, cast = true) => { const m = new Mesh(new BoxGeometry(w, h, d), material); m.castShadow = cast; return m; };++test('texel size is the orthographic width over zoom and map width; other shadows never read as small', () => {+ const light = sun([25, 42, 20]);+ expect(shadowTexelSize(light.shadow)).toBe(88 / 2048);+ light.shadow.camera.zoom = 2; expect(shadowTexelSize(light.shadow)).toBe(44 / 2048);+ light.shadow.mapSize.setScalar(512); expect(shadowTexelSize(light.shadow)).toBe(44 / 512);+ expect(shadowTexelSize(new SpotLight().shadow)).toBe(0);+ expect(casterTexels(mesh(.01, .01, .01), light, 0)).toBe(Infinity);+});++test('light measure: box extent across the sun view, through world scale; sphere measure ignores orientation', () => {+ const overhead = sun([0, 50, 0]), side = sun([50, 0, 0]), box = mesh(1, 2, 4), parent = new Group();+ parent.add(box); parent.updateMatrixWorld(true);+ expect(casterTexels(box, overhead, .5)).toBeCloseTo(8); // x 1, z 4 seen from above+ expect(casterTexels(box, side, .5)).toBeCloseTo(8); // y 2, z 4 seen from the side+ box.rotation.y = Math.PI / 2; parent.scale.setScalar(2); parent.updateMatrixWorld(true);+ expect(casterTexels(box, side, .5)).toBeCloseTo(8); // z now lies along the sun: y 2 × 2 = 4 m+ const diameter = 2 * Math.sqrt(.25 + 1 + 4) * 2;+ expect(casterTexels(box, side, .5, 'sphere')).toBeCloseTo(diameter / .5);+ expect(casterTexels(box, overhead, .5, 'sphere')).toBeCloseTo(diameter / .5);+});++test('an InstancedMesh is sized by its largest drawn instance in both measures, aligned with the count probe', () => {+ const light = sun([0, 50, 0]), batch = new InstancedMesh(new BoxGeometry(1, 1, 1), material, 3);+ batch.setMatrixAt(0, new Matrix4().makeScale(1, 1, 1)); batch.setMatrixAt(1, new Matrix4().makeScale(2, 2, 2)); batch.setMatrixAt(2, new Matrix4().makeScale(5, 5, 5));+ batch.scale.setScalar(.5); batch.updateMatrixWorld(true);+ expect(casterTexels(batch, light, .1)).toBeCloseTo(25);+ batch.count = 2;+ expect(casterTexels(batch, light, .1)).toBeCloseTo(10);+ expect(casterTexels(batch, light, .1, 'sphere')).toBeCloseTo(Math.sqrt(3) * 10);+ // The sphere measure is the count probe's casters-under-N-texels measure (probe-core casterSize).+ const single = mesh(.3, 2, .1); single.scale.set(1, 3, 1); single.updateMatrixWorld(true);+ for (const m of [batch, single]) expect(casterTexels(m, light, .1, 'sphere')).toBeCloseTo(casterSize(m, .1).texels!);+});++test('threshold drops visible small casters, keeps the rest, marks them suppressed and restores', () => {+ const scene = new Scene(), light = sun([25, 42, 20], 512), texel = 88 / 512;+ const big = mesh(2, 2, 2), small = mesh(.1, .1, .1), quiet = mesh(.1, .1, .1, false), hidden = mesh(.1, .1, .1), kept = mesh(.1, .1, .1), hiddenParent = new Group();+ const batch = new InstancedMesh(new BoxGeometry(.1, .1, .1), material, 2); batch.castShadow = true; batch.setMatrixAt(1, new Matrix4().makeScale(40, 40, 40));+ const tiny = new InstancedMesh(new BoxGeometry(.1, .1, .1), material, 2); tiny.castShadow = true;+ hiddenParent.visible = false; hiddenParent.add(hidden); kept.name = 'keep';+ scene.add(big, small, quiet, hiddenParent, kept, batch, tiny); scene.updateMatrixWorld(true);+ let changes = 0;+ const t = smallCasterThreshold(scene, light, { include: m => m.name !== 'keep', onChange: () => changes++ });+ expect(new Set(t.dropped)).toEqual(new Set<Mesh>([small, tiny]));+ expect(t.stats).toEqual({ casters: 4, dropped: 2, texel });+ expect([small.castShadow, tiny.castShadow, big.castShadow, batch.castShadow, hidden.castShadow, kept.castShadow, quiet.castShadow]).toEqual([false, false, true, true, true, true, false]);+ expect(suppressedCasters.has(small) && suppressedCasters.has(tiny) && !suppressedCasters.has(big)).toBe(true);+ expect(changes).toBe(1);+ t.restore(); t.restore();+ expect([small.castShadow, tiny.castShadow, quiet.castShadow]).toEqual([true, true, false]);+ expect(suppressedCasters.has(small)).toBe(false);+ expect(t.dropped).toEqual([]);+ expect(changes).toBe(2);+ expect(() => t.update()).toThrow('restored');+});++test('update re-evaluates on a texel change in both directions and reports only real changes', () => {+ const scene = new Scene(), light = sun([25, 42, 20], 2048), a = mesh(.04, .04, .04), b = mesh(.15, .15, .15);+ scene.add(a, b); scene.updateMatrixWorld(true);+ let changes = 0;+ const t = smallCasterThreshold(scene, light, { minTexels: 2, onChange: () => changes++ });+ expect(t.dropped).toEqual([a]); expect(changes).toBe(1);+ t.update(); expect(changes).toBe(1);+ light.shadow.mapSize.setScalar(512); t.update();+ expect(new Set(t.dropped)).toEqual(new Set([a, b])); expect(b.castShadow).toBe(false); expect(changes).toBe(2);+ light.shadow.mapSize.setScalar(4096); t.update();+ expect(t.dropped).toEqual([]); expect([a.castShadow, b.castShadow]).toEqual([true, true]); expect(changes).toBe(3);+ expect(t.stats.dropped).toBe(0);+});++test('the default sphere measure keeps a rod pointed at the sun; the light measure drops it', () => {+ const scene = new Scene(), light = sun([0, 50, 0], 512), rod = new Mesh(new CylinderGeometry(.02, .02, 3), material);+ rod.castShadow = true; scene.add(rod); scene.updateMatrixWorld(true);+ const sphere = smallCasterThreshold(scene, light);+ expect(sphere.dropped).toEqual([]); sphere.restore();+ const projected = smallCasterThreshold(scene, light, { measure: 'light' });+ expect(projected.dropped).toEqual([rod]); projected.restore();+ expect(rod.castShadow).toBe(true);+});++test('RK-7e the light measure brings a light and target whose world matrices are stale up to date first', () => {+ const light = new DirectionalLight(); light.position.set(25, 42, 20); light.shadow.mapSize.setScalar(2048); // never added or updated+ Object.assign(light.shadow.camera, { left: -44, right: 44, top: 44, bottom: -44, near: 1, far: 115 }); light.shadow.camera.updateProjectionMatrix();+ const m = mesh(4, .2, .2); m.updateMatrixWorld(true);+ const texel = shadowTexelSize(light.shadow), stale = casterTexels(m, light, texel);+ light.updateMatrixWorld(true); light.target.updateMatrixWorld(true);+ expect(stale).toBeCloseTo(casterTexels(m, light, texel), 9);+});diff --git a/scenes/packages/scene-kit/tests/testing/probe-core.test.ts b/scenes/packages/scene-kit/tests/testing/probe-core.test.tsnew file mode 100644index 00000000..3a1a897c--- /dev/null+++ b/scenes/packages/scene-kit/tests/testing/probe-core.test.ts@@ -0,0 +1,110 @@+import { expect, test } from 'bun:test';+import { attributionPath, casterSize, classifyRender, classifyTarget, diffCounts, isSmallCaster, maxInstanceScale, passKinds, shadowTexelWorld, summarizeFrames, totalsByKind } from '../../src/testing/probe-core';++test('renders classify by three r186 nested scene names, then by depth', () => {+ expect(classifyRender('', 0)).toBe('main');+ expect(classifyRender('Farm', 0)).toBe('main');+ expect(classifyRender('Shadow Map [ sun ]', 1)).toBe('shadow');+ expect(classifyRender('Shadow Map [ ID: 547 ]', 2)).toBe('shadow');+ expect(classifyRender('Point Light Shadow [ lamp ] - Face 3', 1)).toBe('shadow');+ expect(classifyRender('Scene [ Reflector ]', 1)).toBe('reflection');+ expect(classifyRender('water [ Reflector ]', 1)).toBe('reflection');+ expect(classifyRender('PMREM', 1)).toBe('offscreen');+ // A depth-0 render of another scene (an environment bake from a system) is not the main pass.+ expect(classifyRender('environment', 0, false)).toBe('offscreen');+ expect(classifyRender('Shadow Map [ sun ]', 0, false)).toBe('shadow');+});++test('targets classify as canvas, frame buffer, shadow map or sized render target', () => {+ const map = { width: 2048, height: 2048 }, maps = new Set([map]);+ expect(classifyTarget(null, maps)).toBe('canvas');+ expect(classifyTarget(undefined, maps)).toBe('canvas');+ expect(classifyTarget({ width: 1920, height: 988, isPostProcessingRenderTarget: true }, maps)).toBe('framebuffer');+ expect(classifyTarget(map, maps)).toBe('shadow-map');+ expect(classifyTarget({ width: 960, height: 494 }, maps)).toBe('rt 960x494');+});++test('attribution path names ancestors from the root down, skipping unnamed nodes', () => {+ const root = { name: '', parent: null } as any;+ const world = { name: 'golden-gate-world', parent: root }, bridge = { name: 'bridge', parent: world }, unnamed = { name: '', parent: bridge };+ const scene = { name: 'Golden_Gate_Bridge', parent: unnamed }, mesh = { name: 'Paint_12', parent: scene };+ expect(attributionPath(mesh, root)).toBe('golden-gate-world/bridge/Golden_Gate_Bridge');+ expect(attributionPath(mesh, root, 2)).toBe('golden-gate-world/bridge');+ expect(attributionPath(mesh, root, 9)).toBe('golden-gate-world/bridge/Golden_Gate_Bridge/Paint_12');+ expect(attributionPath({ name: '', parent: root }, root)).toBe('(unnamed)');+ expect(attributionPath({ name: 'loose', parent: null }, root)).toBe('(detached)/loose');+});++test('caster size uses index or position triangles and the shadow texel', () => {+ const sphere = (radius: number) => ({ radius });+ const indexed = { geometry: { index: { count: 900 }, attributes: { position: { count: 400 } }, boundingSphere: sphere(.5) }, matrixWorld: { getMaxScaleOnAxis: () => 2 } };+ const soup = { geometry: { index: null, attributes: { position: { count: 300 } }, boundingSphere: sphere(.01) }, matrixWorld: { getMaxScaleOnAxis: () => 1 } };+ // diameter 2·0.5·2 = 2 m over a 0.5 m texel = 4 texels+ expect(casterSize(indexed, .5)).toEqual({ triangles: 300, texels: 4 });+ expect(casterSize(soup, .5)).toEqual({ triangles: 100, texels: .04 });+ expect(casterSize(soup, null)).toEqual({ triangles: 100, texels: null });+ expect(isSmallCaster(indexed, { triangles: 300 })).toBe(false);+ expect(isSmallCaster(indexed, { triangles: 301 })).toBe(true);+ expect(isSmallCaster(indexed, { texels: 4, texelWorld: .5 })).toBe(false);+ expect(isSmallCaster(indexed, { texels: 4.5, texelWorld: .5 })).toBe(true);+ expect(isSmallCaster(soup, { texels: 2 })).toBe(false); // no texel size: never small by texels+ expect(isSmallCaster(soup, {})).toBe(false);+ let computed = 0;+ const lazy = { geometry: { index: null, attributes: { position: { count: 3 } }, boundingSphere: null as { radius: number } | null, computeBoundingSphere() { computed++; this.boundingSphere = sphere(1); } }, matrixWorld: { getMaxScaleOnAxis: () => 1 } };+ expect(casterSize(lazy, 1)).toEqual({ triangles: 1, texels: 2 });+ expect(computed).toBe(1);+});++test('an instanced caster is sized by its largest instance within count', () => {+ const scaled = (...scales: number[]) => { const a = new Float32Array(scales.length * 16); scales.forEach((s, i) => a.set([s, 0, 0, 0, 0, s * .5, 0, 0, 0, 0, s, 0, i, i, i, 1], i * 16)); return a; };+ const batch = { geometry: { index: null, attributes: { position: { count: 3 } }, boundingSphere: { radius: .5 } }, matrixWorld: { getMaxScaleOnAxis: () => 2 }, isInstancedMesh: true, count: 2, instanceMatrix: { array: scaled(1, 3, 10) } };+ expect(maxInstanceScale(batch)).toBe(3); // the third matrix is past count+ expect(casterSize(batch, .5)).toEqual({ triangles: 1, texels: 2 * .5 * 2 * 3 / .5 });+ expect(maxInstanceScale({ isInstancedMesh: true, count: 0, instanceMatrix: { array: scaled(4) } })).toBe(1);+ expect(maxInstanceScale({})).toBe(1);+});++test('orthographic shadow texel is frustum width over map width; perspective shadows have none', () => {+ expect(shadowTexelWorld({ camera: { isOrthographicCamera: true, left: -44, right: 44 }, mapSize: { x: 2048 } })).toBeCloseTo(88 / 2048, 12);+ expect(shadowTexelWorld({ camera: { isPerspectiveCamera: true }, mapSize: { x: 1024 } })).toBeNull();+ expect(shadowTexelWorld(undefined)).toBeNull();+});++test('frame summaries report identical, trailing-stable and the settled frame', () => {+ expect(summarizeFrames([])).toEqual({ stable: false, identical: false, stableAfter: null, frame: null });+ expect(summarizeFrames([{ d: 1 }, { d: 1 }, { d: 1 }])).toEqual({ stable: true, identical: true, stableAfter: 0, frame: { d: 1 } });+ expect(summarizeFrames([{ d: 3 }, { d: 5 }, { d: 5 }, { d: 5 }])).toEqual({ stable: true, identical: false, stableAfter: 1, frame: { d: 5 } });+ expect(summarizeFrames([{ d: 3 }, { d: 5 }, { d: 5 }])).toEqual({ stable: false, identical: false, stableAfter: null, frame: { d: 5 } });+ expect(summarizeFrames([{ d: 3 }, { d: 5 }, { d: 5 }], { stableFrames: 2 }).stableAfter).toBe(1);+ expect(summarizeFrames([{ d: 1, t: 9 }, { d: 1, t: 8 }], { stableFrames: 2, key: f => String(f.d) }).stable).toBe(true);+});++test('count diffs subtract numeric leaves, treating a missing side as zero', () => {+ const base = { draws: 583, triangles: 2.3e6, byKind: { main: { draws: 313 }, shadow: { draws: 270 } }, label: 'base', list: [1, 2] };+ const variant = { draws: 313, triangles: 2.1e6, byKind: { main: { draws: 313 } }, label: 'variant', list: [9] };+ expect(diffCounts(base, variant)).toEqual({ draws: -270, triangles: -2e5, byKind: { main: { draws: 0 }, shadow: { draws: -270 } } });+ expect(diffCounts({ a: 1 }, { a: 1, b: { c: 4 } })).toEqual({ a: 0, b: { c: 4 } });+});++test('pass kinds mark the canvas pass of a framebuffer render as output', () => {+ const passes = [+ { render: 'main', target: 'framebuffer' }, { render: 'shadow', target: 'shadow-map' }, { render: 'reflection', target: 'rt 960x494' }, { render: 'main', target: 'canvas' },+ ] as const;+ expect(passKinds(passes)).toEqual(['main', 'shadow', 'reflection', 'output']);+ // Without a frame-buffer target the scene draws straight to the canvas: that pass is the main pass.+ expect(passKinds([{ render: 'main', target: 'canvas' }])).toEqual(['main']);+ expect(passKinds([{ render: 'offscreen', target: 'rt 256x256' }])).toEqual(['offscreen']);+});++test('totals by kind sum draws and triangles and union pipelines', () => {+ const a = {}, b = {}, c = {};+ const totals = totalsByKind([+ { kind: 'main', draws: 10, triangles: 100, pipelines: new Set([a, b]) },+ { kind: 'main', draws: 1, triangles: 2, pipelines: new Set([b]) },+ { kind: 'shadow', draws: 5, triangles: 50, pipelines: new Set([c]) },+ ]);+ expect(totals).toEqual({+ draws: 16, triangles: 152, pipelinesUsed: 3,+ byKind: { main: { passes: 2, draws: 11, triangles: 102, pipelines: 2 }, shadow: { passes: 1, draws: 5, triangles: 50, pipelines: 1 } },+ });+});diff --git a/scenes/packages/scene-kit/tests/testing/probe-fixture.ts b/scenes/packages/scene-kit/tests/testing/probe-fixture.tsnew file mode 100644index 00000000..64fb03c4--- /dev/null+++ b/scenes/packages/scene-kit/tests/testing/probe-fixture.ts@@ -0,0 +1,52 @@+// A fake renderer shaped like three r186's for the count-probe tests: nested renders re-enter through the instance+// `render`, every draw goes through `backend.draw(renderObject, info)` after `_pipelines.isReady`, shadow renders rename+// the scene, and every shadow map shares one render context (RenderContexts.js keys by format and call depth).+export function probeFixture(o: { lamp?: boolean } = {}) {+ const node = (name: string, parent: any = null, extra: Record<string, unknown> = {}): any => {+ const n = { name, parent, children: [] as any[], visible: true, ...extra }; parent?.children.push(n); return n;+ };+ const scene = node('', null, { isScene: true }), world = node('world', scene), terrain = node('terrain', world), heroes = node('heroes', world);+ const mesh = (name: string, parent: any, tris: number, cast: boolean, radius: number) => node(name, parent, { isMesh: true, castShadow: cast, receiveShadow: true,+ geometry: { index: { count: tris * 3 }, attributes: { position: { count: tris * 3 } }, boundingSphere: { radius } }, matrixWorld: { getMaxScaleOnAxis: () => 1 }, material: { transparent: false } });+ const ground = mesh('ground', terrain, 1000, false, 50), house = mesh('house', heroes, 500, true, 1), bolt = mesh('bolt', heroes, 12, true, .01);+ const light = (name: string, size: number, half: number) => node(name, scene, { isLight: true, isDirectionalLight: true, type: 'DirectionalLight', castShadow: true,+ shadow: { autoUpdate: true, needsUpdate: false, map: { width: size, height: size }, camera: { type: 'OrthographicCamera', isOrthographicCamera: true, left: -half, right: half, top: half, bottom: -half, near: 1, far: 115 }, mapSize: { x: size, y: size } } });+ const sun = light('sun', 2048, 44), lights = o.lamp ? [sun, light('lamp', 1024, 10)] : [sun];+ const camera = { type: 'PerspectiveCamera' }, quad = { name: '', parent: null, isMesh: true, geometry: { index: null, attributes: { position: { count: 3 } } } };+ const contexts = {+ main: { id: 3, renderTarget: { width: 1920, height: 988, isPostProcessingRenderTarget: true } as any, width: 1920, height: 988, sampleCount: 4 },+ shadow: { id: 5, renderTarget: sun.shadow.map, width: 2048, height: 2048, sampleCount: 1 },+ output: { id: 4, renderTarget: null, width: 1920, height: 988, sampleCount: 1 },+ };+ const pipelines = { ground: {}, lit: {}, depth: {}, output: {} };+ const triangles = (m: any) => m.geometry.index ? m.geometry.index.count / 3 : m.geometry.attributes.position.count / 3;+ let compiling = 2;+ const visibleMeshes = (root: any, out: any[] = []) => { if (!root.visible) return out; if (root.isMesh) out.push(root); for (const c of root.children) visibleMeshes(c, out); return out; };+ const renderer: any = {+ info: { render: { calls: 0, frame: 0, drawCalls: 0, triangles: 0 }, memory: { geometries: 4, textures: 1 } },+ _pipelines: { caches: new Map([[1, {}], [2, {}]]), isReady(ro: any) { return !(compiling > 0 && ro.object === house); } },+ domElement: { width: 1920, height: 988 }, getPixelRatio: () => 1,+ backend: { draw(ro: any, info: any) { info.render.drawCalls++; info.render.triangles += triangles(ro.object); } },+ render(s: any, c: any) {+ const caster = lights.find(l => l.shadow.camera === c);+ if (!caster) for (const l of lights) if (l.castShadow && (l.shadow.autoUpdate || l.shadow.needsUpdate)) { const n = s.name; s.name = `Shadow Map [ ${l.name} ]`; this.render(s, l.shadow.camera); s.name = n; l.shadow.needsUpdate = false; }+ const context = caster ? Object.assign(contexts.shadow, { renderTarget: caster.shadow.map, width: caster.shadow.map.width, height: caster.shadow.map.height }) : contexts.main;+ for (const m of visibleMeshes(s)) {+ if (caster && !m.castShadow) continue;+ const ro = { object: m, context, pipeline: caster ? pipelines.depth : m === ground ? pipelines.ground : pipelines.lit };+ if (this._pipelines.isReady(ro)) this.backend.draw(ro, this.info);+ }+ if (!caster) { this.backend.draw({ object: quad, context: contexts.output, pipeline: pipelines.output }, this.info); compiling--; }+ },+ };+ const systems: { order: number; fn: () => void }[] = [], clock = { frame: 0 };+ const runtime: any = {+ renderer, state: { scene, camera }, clock, disposed: false, pack: null, data: new Map(), devParams: {}, workloads: new Map(), quality: null,+ testHooks: { probeSystems: () => ({ terrain, heroes }), probeAsset: (o: any) => o === house ? 'farmhouse' : null },+ systems: { add(_name: string, order: number, fn: () => void) { const entry = { order, fn }; systems.push(entry); return () => { const i = systems.indexOf(entry); if (i >= 0) systems.splice(i, 1); }; } },+ };+ const tick = () => { clock.frame++; renderer.info.render.drawCalls = renderer.info.render.triangles = 0; for (const s of [...systems].sort((a, b) => a.order - b.order)) s.fn(); renderer.render(scene, camera); };+ const original = { render: renderer.render, isReady: renderer._pipelines.isReady, draw: renderer.backend.draw };+ return { runtime, renderer, scene, sun, ground, house, bolt, heroes, tick, original, systems };+}+export type ProbeFixture = ReturnType<typeof probeFixture>;diff --git a/scenes/packages/scene-kit/tests/testing/probe-frames.test.ts b/scenes/packages/scene-kit/tests/testing/probe-frames.test.tsnew file mode 100644index 00000000..78b92850--- /dev/null+++ b/scenes/packages/scene-kit/tests/testing/probe-frames.test.ts@@ -0,0 +1,47 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { installTestHooks } from '../../src/testing';+import { probeFixture } from './probe-fixture';++// `__kilnScene.probeFrames` (testing/index.ts) installs only in test and dev builds; under Bun `import.meta.env` reads+// process.env, and the page global is a plain object for these tests.+const saved = { env: process.env.KILN_TEST, window: Object.getOwnPropertyDescriptor(globalThis, 'window') };+beforeAll(() => { process.env.KILN_TEST = '1'; Object.defineProperty(globalThis, 'window', { configurable: true, writable: true, value: {} }); });+afterAll(() => {+ if (saved.env === undefined) delete process.env.KILN_TEST; else process.env.KILN_TEST = saved.env;+ if (saved.window) Object.defineProperty(globalThis, 'window', saved.window); else delete (globalThis as { window?: unknown }).window;+});+const page = () => (globalThis as unknown as { window: { __kilnScene?: any } }).window.__kilnScene!;+const settled = <T,>(promise: Promise<T>, ms: number) => Promise.race([promise.then(value => ({ value }), (error: Error) => ({ error })), Bun.sleep(ms).then(() => ({ running: true }))]);++test('probeFrames times out in the page: the probe is cancelled, its what-if restored and the probe freed', async () => {+ const f = probeFixture(), dispose = installTestHooks(f.runtime);+ const outcome = await settled(page().probeFrames({ whatIf: { hide: ['heroes'] }, timeoutMs: 10 }), 300) as { error?: Error };+ expect(String(outcome.error)).toContain('probeFrames timed out after 10 ms');+ expect([f.heroes.visible, f.renderer.render === f.original.render, f.renderer.backend.draw === f.original.draw, f.systems.length]).toEqual([true, true, true, 0]);+ const next = page().probeFrames({ frames: 4, timeoutMs: 50 });+ for (let i = 0; i < 20; i++) f.tick();+ expect((await next).stable).toBe(true);+ dispose();+});++test('a probe that settles first is unaffected by its timeout', async () => {+ const f = probeFixture(), dispose = installTestHooks(f.runtime);+ const first = page().probeFrames({ frames: 4, timeoutMs: 20 });+ for (let i = 0; i < 20; i++) f.tick();+ expect((await first).totals.draws).toBe(6);+ const second = page().probeFrames({ whatIf: { hide: ['heroes'] } });+ await Bun.sleep(40);+ expect(f.heroes.visible).toBe(false);+ for (let i = 0; i < 20; i++) f.tick();+ expect((await second).totals.draws).toBe(2);+ dispose();+});++test('disposing the scene rejects a running probe and restores the renderer and the hidden system', async () => {+ const f = probeFixture(), dispose = installTestHooks(f.runtime), running = page().probeFrames({ whatIf: { hide: ['heroes'] } }).catch((error: Error) => error);+ f.tick();+ expect(f.heroes.visible).toBe(false);+ dispose();+ expect(String(await running)).toContain('Scene disposed');+ expect([f.heroes.visible, f.renderer.render === f.original.render, f.systems.length, page()]).toEqual([true, true, 0, undefined]);+});diff --git a/scenes/packages/scene-kit/tests/testing/probe-report.test.ts b/scenes/packages/scene-kit/tests/testing/probe-report.test.tsnew file mode 100644index 00000000..b22deef2--- /dev/null+++ b/scenes/packages/scene-kit/tests/testing/probe-report.test.ts@@ -0,0 +1,40 @@+import { expect, test } from 'bun:test';+import { compact, crossCheck, pipelinesComparable, runProvenance, standardWhatIfs } from '../../src/testing/probe-report';++const pass = (encoder: string, draws: number, bundledDraws = 0) => ({ frame: 7, encoder, color: [], depth: null, draws, setPipeline: draws, pipelines: 1, bundles: bundledDraws ? 1 : 0, bundledDraws });++test('GPU renderContext draws join JS passes by context id, across a split pass', () => {+ const gpu = { copies: 1, submits: 1, passes: [pass('renderContext_3', 178), pass('renderContext_5', 37), pass('renderContext_3', 1), pass('mipmapEncoder', 0, 1), pass('renderContext_4', 1)] };+ expect(crossCheck(gpu, [{ id: 5, draws: 37 }, { id: 3, draws: 179 }, { id: 4, draws: 1 }])).toEqual({+ equal: true, jsDraws: 217, gpuDraws: 217, mismatches: [], gpuPasses: 5, splitContexts: ['renderContext_3'], otherPasses: 1, otherEncoders: ['mipmapEncoder'], bundledDraws: 1, copies: 1 });+ const off = crossCheck(gpu, [{ id: 5, draws: 37 }, { id: 3, draws: 178 }]);+ expect([off.equal, off.mismatches]).toEqual([false, [{ id: 3, js: 178, gpu: 179 }, { id: 4, js: 0, gpu: 1 }]]);+});++test('JS passes that share a render context (two shadow maps) are summed before the join', () => {+ const gpu = { copies: 0, submits: 1, passes: [pass('renderContext_5', 30), pass('renderContext_5', 12), pass('renderContext_3', 100)] };+ const check = crossCheck(gpu, [{ id: 5, draws: 30 }, { id: 5, draws: 12 }, { id: 3, draws: 100 }]);+ expect([check.equal, check.jsDraws, check.gpuDraws, check.mismatches]).toEqual([true, 142, 142, []]);+});++test('standard what-ifs follow the passes and systems that drew', () => {+ const totals = (byKind: Record<string, number>) => ({ draws: 0, triangles: 0, pipelinesUsed: 0, byKind: Object.fromEntries(Object.entries(byKind).map(([k, d]) => [k, { passes: 1, draws: d, triangles: 0, pipelines: 0 }])) });+ const bySystem = { heroes: { draws: 4, triangles: 0, byKind: {} }, placements: { draws: 0, triangles: 0, byKind: {} } };+ expect(standardWhatIfs({ totals: totals({ main: 3 }), bySystem }, ['heroes', 'placements']).map(w => w.name)).toEqual(['hide-heroes']);+ expect(standardWhatIfs({ totals: totals({ main: 3, shadow: 2, reflection: 1 }), bySystem }, ['heroes']).map(w => w.name))+ .toEqual(['freeze-shadow', 'casters-under-300-triangles', 'casters-under-2-texels', 'skip-reflection', 'hide-heroes']);+ expect(compact({ totals: totals({ main: 3 }), bySystem })).toEqual({ draws: 0, triangles: 0, pipelinesUsed: 0, byKind: { main: { draws: 3, triangles: 0, pipelines: 0 } }, bySystem: { heroes: 4 } });+});++test('run provenance names each scene build, the viewports and the page policy; pipelines compare only between fresh-page runs', () => {+ const record = (scene: string, chunks: string[], freshPage: boolean, viewport: [number, number] = [1920, 1080]) => ({ scene, build: { label: 'b', chunks }, run: { viewport, freshPage } });+ const shared = runProvenance([record('farm', ['index-a.js'], false), record('farm', ['index-a.js'], false), record('golden-gate', ['index-g.js'], false)]);+ expect(shared).toEqual({ builds: { farm: ['index-a.js'], 'golden-gate': ['index-g.js'] }, viewports: ['1920x1080'], freshPage: false, mixed: false });+ const fresh = runProvenance([record('farm', ['index-b.js'], true)]);+ expect(fresh.freshPage).toBe(true);+ expect([pipelinesComparable(fresh, fresh), pipelinesComparable(shared, fresh), pipelinesComparable(fresh, undefined)]).toEqual([true, false, false]);+ // A rebuilt scene, a second viewport or a mix of page policies marks the run mixed.+ const mixed = runProvenance([record('farm', ['index-a.js'], true), record('farm', ['index-b.js'], true), { scene: 'farm' }, record('farm', ['index-a.js'], false, [1280, 720])]);+ expect(mixed).toEqual({ builds: { farm: ['index-a.js', 'index-b.js', '(unknown)'] }, viewports: ['1920x1080', '(unknown)', '1280x720'], freshPage: null, mixed: true });+ expect(pipelinesComparable(mixed, mixed)).toBe(false);+});diff --git a/scenes/packages/scene-kit/tests/testing/probe.test.ts b/scenes/packages/scene-kit/tests/testing/probe.test.tsnew file mode 100644index 00000000..057213bd--- /dev/null+++ b/scenes/packages/scene-kit/tests/testing/probe.test.ts@@ -0,0 +1,157 @@+import { expect, test } from 'bun:test';+import { createRenderProbe, type ProbeOptions, type ProbeResult } from '../../src/testing/probe';+import { probeFixture as fixture, type ProbeFixture as Fixture } from './probe-fixture';++function run(f: Fixture, probe: ReturnType<typeof createRenderProbe>, options: ProbeOptions = {}): ProbeResult {+ let result: ProbeResult | null = null, error: unknown = null;+ probe.run(options, value => { result = value; }, value => { error = value; });+ for (let i = 0; i < 200 && !result && !error; i++) f.tick();+ if (error) throw error;+ if (!result) throw new Error('probe did not finish');+ return result;+}+const kind = (r: ProbeResult, k: string) => r.totals.byKind[k as keyof typeof r.totals.byKind];++test('groups draws by render context, waits for compiled pipelines and attributes by system and asset', () => {+ const f = fixture(), probe = createRenderProbe(f.runtime);+ const r = run(f, probe, { frames: 4, stableFrames: 3, objects: 5 });+ expect(r.stable).toBe(true);+ expect(r.stableAfter).toBe(2); // frames 0 and 1 skipped the uncompiled house+ expect(r.notReady).toBe(0);+ expect(r.renders).toEqual([+ { label: '(root)', kind: 'main', depth: 0, parent: -1, camera: 'main' },+ { label: 'Shadow Map [ sun ]', kind: 'shadow', depth: 1, parent: 0, camera: 'OrthographicCamera' },+ ]);+ expect(r.passes.map(p => [p.id, p.kind, p.target, p.samples, p.draws, p.triangles, p.pipelines])).toEqual([+ [5, 'shadow', 'shadow-map', 1, 2, 512, 1], [3, 'main', 'framebuffer', 4, 3, 1512, 2], [4, 'output', 'canvas', 1, 1, 1, 1],+ ]);+ expect(r.totals).toEqual({ draws: 6, triangles: 2025, pipelinesUsed: 4, byKind: {+ shadow: { passes: 1, draws: 2, triangles: 512, pipelines: 1 }, main: { passes: 1, draws: 3, triangles: 1512, pipelines: 2 }, output: { passes: 1, draws: 1, triangles: 1, pipelines: 1 } } });+ expect(r.info.render.drawCalls).toBe(6);+ expect(r.bySystem).toEqual({+ heroes: { draws: 4, triangles: 1024, byKind: { shadow: { draws: 2, triangles: 512 }, main: { draws: 2, triangles: 512 } } },+ terrain: { draws: 1, triangles: 1000, byKind: { main: { draws: 1, triangles: 1000 } } },+ '(output)': { draws: 1, triangles: 1, byKind: { output: { draws: 1, triangles: 1 } } },+ });+ expect(r.byAsset.farmhouse).toEqual({ draws: 2, triangles: 1000, byKind: { shadow: { draws: 1, triangles: 500 }, main: { draws: 1, triangles: 500 } } });+ expect(r.byAsset.bolt?.draws).toBe(2);+ const main = r.passes.find(p => p.kind === 'main')!;+ expect(main.objects![0]).toEqual({ path: 'world/terrain/ground', system: 'terrain', asset: 'ground', draws: 1, triangles: 1000, castShadow: false, instances: 1, skinned: false, transparent: false });+ expect(r.pipelineCache).toBe(2);+ expect(r.drawingBuffer).toEqual({ width: 1920, height: 988, pixelRatio: 1 });+ expect(f.renderer.render).toBe(f.original.render);+ expect(f.renderer.backend.draw).toBe(f.original.draw);+ expect(f.renderer._pipelines.isReady).toBe(f.original.isReady);+ expect(f.systems.length).toBe(0);+});++test('what-ifs apply for the probe and restore afterwards', () => {+ const f = fixture(), probe = createRenderProbe(f.runtime);+ const base = run(f, probe, { frames: 4 });+ const hidden = run(f, probe, { whatIf: { hide: ['heroes'] } });+ expect(f.heroes.visible).toBe(true);+ expect(hidden.whatIf).toEqual({ applied: { hide: ['heroes'] }, affected: { hidden: 1 } });+ expect([kind(hidden, 'main')?.draws, kind(hidden, 'shadow')]).toEqual([1, undefined]);+ const frozen = run(f, probe, { whatIf: { freezeShadows: true } });+ expect(kind(frozen, 'shadow')).toBeUndefined();+ expect(frozen.whatIf.affected).toEqual({ frozenLights: 1 });+ expect(f.sun.shadow.autoUpdate).toBe(true); // needsUpdate was re-armed and consumed by the frame that finished the probe+ const small = run(f, probe, { whatIf: { dropCasters: { triangles: 300 } } });+ expect(kind(small, 'shadow')?.draws).toBe(1);+ expect(small.whatIf.affected).toEqual({ casters: 2, dropped: 1, droppedInstanced: 0, droppedInstances: 1, droppedTriangles: 12 });+ expect(small.whatIf.dropped).toEqual([{ path: 'world/heroes/bolt', instances: 1, triangles: 12, texels: 2 * .01 / (88 / 2048) }]);+ expect(f.bolt.castShadow).toBe(true);+ const texels = run(f, probe, { whatIf: { dropCasters: { texels: 2 } } });+ expect(texels.whatIf.affected).toEqual({ casters: 2, dropped: 1, droppedInstanced: 0, droppedInstances: 1, droppedTriangles: 12, texelWorld: 88 / 2048 });+ const skipped = run(f, probe, { whatIf: { skipRenders: ['shadow'] } });+ expect(kind(skipped, 'shadow')).toBeUndefined();+ expect(skipped.whatIf.affected).toEqual({ skippedRenders: 1 });+ const again = run(f, probe, {});+ expect(again.totals).toEqual(base.totals);+});++test('hiding holds against a scene that writes visibility every frame, and keeps its last write for the restore', () => {+ const f = fixture(), probe = createRenderProbe(f.runtime);+ let show = true;+ f.runtime.systems.add('scene-visibility', 50, () => { f.heroes.visible = show; });+ const hidden = run(f, probe, { whatIf: { hide: ['heroes'] } });+ expect(kind(hidden, 'main')?.draws).toBe(1);+ expect(f.heroes.visible).toBe(true);+ show = false; f.tick();+ expect([f.heroes.visible, Object.getOwnPropertyDescriptor(f.heroes, 'visible')?.writable]).toEqual([false, true]);+});++test('unknown systems fail the probe before anything changes; cancel restores without finishing', () => {+ const f = fixture(), probe = createRenderProbe(f.runtime);+ expect(() => run(f, probe, { whatIf: { hide: ['nope'] } })).toThrow('Unknown probe system nope');+ expect(f.renderer.render).toBe(f.original.render);+ let finished = false;+ const cancel = probe.run({ whatIf: { hide: ['heroes'] } }, () => { finished = true; }, () => { finished = true; });+ f.tick(); f.tick();+ expect(f.heroes.visible).toBe(false);+ expect(() => probe.run({}, () => {}, () => {})).toThrow('A render probe is already running');+ cancel();+ expect([f.heroes.visible, finished, f.renderer.render === f.original.render, f.systems.length]).toEqual([true, false, true, 0]);+});++test('maxFrames ends an unsettled probe as unstable', () => {+ const f = fixture(), probe = createRenderProbe(f.runtime);+ let n = 0;+ f.runtime.testHooks.probeSystems = undefined;+ const draw = f.renderer.backend.draw;+ f.renderer.backend.draw = (ro: any, info: any) => { draw(ro, info); if (ro.context.id === 3) info.render.triangles += n++; };+ const r = run(f, probe, { frames: 2, maxFrames: 6 });+ expect([r.stable, r.stableAfter, r.framesObserved]).toEqual([false, null, 6]);+ // Without a probeSystems hook, systems fall back to the two-level attribution path.+ expect(Object.keys(r.bySystem).sort()).toEqual(['(output)', 'world/heroes', 'world/terrain']);+});++test('scene summary counts meshes, casters and shadow lights by system', () => {+ const f = fixture(), probe = createRenderProbe(f.runtime);+ expect(probe.sceneSummary()).toEqual({+ meshes: 3, visibleMeshes: 3, casters: 2, receivers: 3, instanced: 0, instances: 3, skinned: 0, transparent: 0, triangles: 1512,+ lights: [{ name: 'sun', type: 'DirectionalLight', castShadow: true, mapSize: [2048, 2048], autoUpdate: true, camera: { type: 'OrthographicCamera', left: -44, right: 44, top: 44, bottom: -44, near: 1, far: 115 }, texelWorld: 88 / 2048 }],+ bySystem: {+ terrain: { meshes: 1, visibleMeshes: 1, casters: 0, instanced: 0, instances: 1, skinned: 0, transparent: 0, triangles: 1000 },+ heroes: { meshes: 2, visibleMeshes: 2, casters: 2, instanced: 0, instances: 2, skinned: 0, transparent: 0, triangles: 512 },+ },+ });+});++test('a probe that fails while installing restores what it changed and leaves the probe free', () => {+ const f = fixture(), probe = createRenderProbe(f.runtime), pipelines = f.renderer._pipelines;+ delete f.renderer._pipelines;+ expect(() => probe.run({ whatIf: { hide: ['heroes'] } }, () => {}, () => {})).toThrow();+ expect([f.renderer.render === f.original.render, f.renderer.backend.draw === f.original.draw, f.heroes.visible, Object.getOwnPropertyDescriptor(f.heroes, 'visible')?.writable, f.systems.length])+ .toEqual([true, true, true, true, 0]);+ f.renderer._pipelines = pipelines;+ expect(run(f, probe, { frames: 4 }).stable).toBe(true);+});++test('two shadow maps sharing a render context stay separate passes, labelled and sized by their own render', () => {+ const f = fixture({ lamp: true }), r = run(f, createRenderProbe(f.runtime), { frames: 4 });+ expect(r.passes.filter(p => p.kind === 'shadow').map(p => [p.id, p.call, p.label, p.width, p.draws])).toEqual([[5, 1, 'Shadow Map [ sun ]', 2048, 2], [5, 2, 'Shadow Map [ lamp ]', 1024, 2]]);+ expect(kind(r, 'shadow')).toEqual({ passes: 2, draws: 4, triangles: 1024, pipelines: 1 });+});++test('the texel threshold sizes an instanced caster by its largest instance and drops every instance with it', () => {+ const f = fixture(), probe = createRenderProbe(f.runtime), matrices = new Float32Array(64);+ // Four instances; the third is scaled 3x: 0.02 m × 3 over an 88/2048 m texel is 1.4 texels, still under 2.+ for (let i = 0; i < 4; i++) { const s = i === 2 ? 3 : 1; matrices.set([s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0, i, 0, 0, 1], i * 16); }+ Object.assign(f.bolt, { isInstancedMesh: true, count: 4, instanceMatrix: { array: matrices } });+ const small = run(f, probe, { whatIf: { dropCasters: { texels: 2 } } });+ expect(small.whatIf.affected).toEqual({ casters: 2, dropped: 1, droppedInstanced: 1, droppedInstances: 4, droppedTriangles: 48, texelWorld: 88 / 2048 });+ expect(small.whatIf.dropped?.map(d => [d.path, d.instances, d.triangles, +d.texels!.toFixed(3)])).toEqual([['world/heroes/bolt', 4, 48, +(.06 / (88 / 2048)).toFixed(3)]]);+ matrices.set([5, 0, 0, 0, 0, 5, 0, 0, 0, 0, 5, 0], 32); // 0.1 m at 2.3 texels: the batch keeps its shadow+ expect(run(f, probe, { whatIf: { dropCasters: { texels: 2 } } }).whatIf.affected).toEqual({ casters: 2, dropped: 0, droppedInstanced: 0, droppedInstances: 0, droppedTriangles: 0, texelWorld: 88 / 2048 });+ expect(f.bolt.castShadow).toBe(true);+});++test('asset names follow the loaded pack when it changes', () => {+ const f = fixture(), probe = createRenderProbe(f.runtime), packOf = (id: string) => ({ models: new Map([[id, { scene: { children: [{ isMesh: true, geometry: f.ground.geometry, children: [] }] } }]]) });+ f.runtime.pack = packOf('terrain-a');+ expect(run(f, probe, { frames: 4 }).byAsset['terrain-a']?.draws).toBe(1);+ f.runtime.pack = packOf('terrain-b');+ const r = run(f, probe, {});+ expect([r.byAsset['terrain-b']?.draws, r.byAsset['terrain-a']]).toEqual([1, undefined]);+});diff --git a/scenes/scripts/build-scene.ts b/scenes/scripts/build-scene.tsnew file mode 100644index 00000000..7e6992c1--- /dev/null+++ b/scenes/scripts/build-scene.ts@@ -0,0 +1,108 @@+// Builds one scene's standalone page from source against a sealed pack, for count probes and A/B captures (S1, OD-17).+// bun scripts/build-scene.ts --scene farm|foundry-floor|golden-gate --mode test|public|dev --label <l> [--pack <dir>]+// Output: packages/<scene>/dist/<label>/<mode>, with serve.mjs, THIRD-PARTY-NOTICES.txt and build.json beside the page.+// The pack defaults to the pinned site input (.cache/site-inputs/<scene>/standalone/assets) minus its top-level code+// chunks; it is checked against its pack.json and SHA256SUMS (verifyStaged) before copying and never restaged. The+// scenes' own builders (build-farm.ts, golden-gate tests/tools/build.ts, foundry-floor rebuild-code.ts) stay as they are.+// `--base <git ref> [--overlay <path,…>]` builds from a snapshot of scenes/packages at that ref (under .tmp/build-src) with+// only the listed working-tree files laid over it, so a baseline is not mixed with other work in progress in the tree.+// This is a build, not a qualification: no browser runs here.+import { build } from 'vite';+import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { existsSync, readdirSync, realpathSync, symlinkSync } from 'node:fs';+import { cp, mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';+import { relative, resolve, sep } from 'node:path';+import { gzipSync } from 'node:zlib';+import { sceneStandaloneConfig, type SceneBuildMode } from '../packages/scene-kit/src/build';+import { verifyStaged } from '../packages/scene-kit/src/staging';+import { auditLicenses, renderNotices } from './check-licenses';++export const SCENES = { farm: 'packages/farm/standalone', 'foundry-floor': 'packages/foundry-floor/standalone-campus', 'golden-gate': 'packages/golden-gate/standalone' } as const;+export type SceneId = keyof typeof SCENES;+const ROOT = resolve(import.meta.dir, '..');+const CODE_CHUNK = /^[^/]+\.(?:js|css): extra staged file$/;+export const sceneOutput = (scene: SceneId, label: string, mode: SceneBuildMode) => resolve(ROOT, 'packages', scene, 'dist', label, mode);++const run = (command: string, args: string[], cwd: string) => { const r = spawnSync(command, args, { cwd, encoding: 'utf8' }); if (r.status !== 0) throw new Error(`${command} ${args.join(' ')}: ${r.stderr || r.error}`); return r.stdout; };+/**+ * scenes/packages at `ref` plus `overlay` (paths relative to scenes/, copied from the working tree), with each package's+ * node_modules rebuilt from junctions to the installed ones, except workspace links, which point into the snapshot.+ */+export async function snapshotPackages(ref: string, overlay: string[], label: string): Promise<{ root: string; overlay: { path: string; sha256: string }[]; commit: string }> {+ const root = resolve(ROOT, '.tmp/build-src', label), archive = resolve(ROOT, '.tmp/build-src', `${label}.tar`);+ await rm(root, { recursive: true, force: true }); await mkdir(root, { recursive: true });+ const commit = run('git', ['rev-parse', ref], ROOT).trim();+ // From scenes/, `git archive <commit> packages` holds paths relative to scenes/. Relative tar paths: GNU tar reads `C:` as a host.+ run('git', ['archive', '--format=tar', '-o', archive, commit, 'packages'], ROOT);+ run('tar', ['-xf', `../${label}.tar`], root); await rm(archive);+ if (!existsSync(resolve(root, 'packages/scene-kit/package.json'))) throw new Error(`Snapshot of ${ref} has no packages`);+ const laid = [];+ for (const path of overlay) {+ if (!/^packages\//.test(path)) throw new Error(`Overlay ${path} must be under packages/`);+ const bytes = await readFile(resolve(ROOT, path)); await mkdir(resolve(root, path, '..'), { recursive: true }); await writeFile(resolve(root, path), bytes);+ laid.push({ path, sha256: createHash('sha256').update(bytes).digest('hex') });+ }+ for (const name of readdirSync(resolve(root, 'packages'))) {+ const live = resolve(ROOT, 'packages', name, 'node_modules'), mine = resolve(root, 'packages', name, 'node_modules');+ if (!existsSync(live)) continue;+ await mkdir(mine, { recursive: true });+ for (const entry of readdirSync(live)) {+ if (entry !== '@kiln-scenes') { symlinkSync(realpathSync(resolve(live, entry)), resolve(mine, entry), 'junction'); continue; }+ await mkdir(resolve(mine, entry));+ for (const workspace of readdirSync(resolve(live, entry))) symlinkSync(resolve(root, 'packages', workspace), resolve(mine, entry, workspace), 'junction');+ }+ }+ return { root, overlay: laid, commit };+}++/** Problems with a sealed pack, ignoring only the sealed build's own top-level code chunks. */+export function packProblems(dir: string): string[] { return verifyStaged(dir).problems.filter(problem => !CODE_CHUNK.test(problem)); }++export async function buildScene(o: { scene: SceneId; mode: SceneBuildMode; label: string; pack?: string; quiet?: boolean; source?: string; provenance?: unknown }) {+ if (!(o.scene in SCENES)) throw new Error(`Unknown scene ${o.scene}; expected ${Object.keys(SCENES).join(', ')}`);+ if (!['public', 'test', 'dev'].includes(o.mode)) throw new Error(`Unknown build mode ${o.mode}`);+ if (!/^[a-z0-9-]+$/.test(o.label)) throw new Error('A build label uses lowercase letters, numbers and hyphens');+ const pack = resolve(ROOT, o.pack ?? `.cache/site-inputs/${o.scene}/standalone/assets`), problems = packProblems(pack);+ if (problems.length) throw new Error(`Pack ${pack} fails verification:\n${problems.join('\n')}`);+ const output = sceneOutput(o.scene, o.label, o.mode);+ await rm(output, { recursive: true, force: true });+ await build({ ...sceneStandaloneConfig({ root: resolve(o.source ?? ROOT, SCENES[o.scene]), outDir: output, mode: o.mode }), configFile: false, logLevel: o.quiet ? 'warn' : 'info' });+ const chunks = [];+ for (const name of await readdir(resolve(output, 'assets'))) {+ if (!/\.(?:js|css)$/.test(name)) continue;+ const bytes = await readFile(resolve(output, 'assets', name));+ chunks.push({ name, bytes: bytes.length, gzipBytes: gzipSync(bytes).length });+ }+ let files = 0;+ for (const entry of await readdir(pack, { withFileTypes: true })) {+ if (entry.isFile() && /\.(?:js|css)$/.test(entry.name)) continue;+ await cp(resolve(pack, entry.name), resolve(output, 'assets', entry.name), { recursive: true }); files++;+ }+ await writeFile(resolve(output, 'serve.mjs'), await readFile(resolve(ROOT, 'scripts/static-server.mjs'), 'utf8'));+ const graph = JSON.parse(await readFile(resolve(output, 'bundle-modules.json'), 'utf8')) as { modules: string[] };+ const licenses = auditLicenses(ROOT, graph.modules);+ if (licenses.problems.length) throw new Error(licenses.problems.join('\n'));+ await writeFile(resolve(output, 'THIRD-PARTY-NOTICES.txt'), renderNotices(licenses.records));+ const manifest = await readFile(resolve(pack, 'pack.json'));+ const record = { scene: o.scene, mode: o.mode, label: o.label, output: relative(ROOT, output).split(sep).join('/'), pack: relative(ROOT, pack).split(sep).join('/'),+ release: (JSON.parse(new TextDecoder().decode(manifest)) as { release: string }).release, packSha256: createHash('sha256').update(manifest).digest('hex'), packEntries: files,+ chunks, codeBytes: chunks.reduce((n, c) => n + c.bytes, 0), codeGzipBytes: chunks.reduce((n, c) => n + c.gzipBytes, 0), licenses: licenses.records.length, source: o.provenance ?? 'working tree' };+ await mkdir(output, { recursive: true });+ await writeFile(resolve(output, 'build.json'), JSON.stringify(record, null, 2) + '\n');+ return record;+}++if (import.meta.main) {+ const args = process.argv.slice(2);+ const option = (name: string) => { const at = args.indexOf(name); if (at < 0) return undefined; const value = args[at + 1]; if (!value || value.startsWith('--')) throw new Error(`${name} needs a value`); return value; };+ const scenes = (option('--scene') ?? '').split(',').filter(Boolean) as SceneId[], label = option('--label');+ if (!scenes.length || !label) throw new Error('Usage: bun scripts/build-scene.ts --scene farm|foundry-floor|golden-gate[,…] --mode test|public|dev --label <l> [--pack <dir>]');+ if (scenes.length > 1 && option('--pack')) throw new Error('--pack applies to one scene');+ const base = option('--base'), snapshot = base ? await snapshotPackages(base, (option('--overlay') ?? '').split(',').filter(Boolean), label) : null;+ for (const scene of scenes) {+ const record = await buildScene({ scene, mode: (option('--mode') ?? 'test') as SceneBuildMode, label, pack: option('--pack'), quiet: true,+ ...(snapshot ? { source: snapshot.root, provenance: { base, commit: snapshot.commit, overlay: snapshot.overlay } } : {}) });+ console.log(JSON.stringify({ scene: record.scene, mode: record.mode, output: record.output, release: record.release, codeBytes: record.codeBytes, codeGzipBytes: record.codeGzipBytes }));+ }+}diff --git a/scenes/scripts/capture-farm-draw-parity.ts b/scenes/scripts/capture-farm-draw-parity.tsnew file mode 100644index 00000000..18b8c165--- /dev/null+++ b/scenes/scripts/capture-farm-draw-parity.ts@@ -0,0 +1,160 @@+// S5 cross-build parity for the Farm (docs/plans/2026-10-01-draw-optimization-cycle.md S5, OD-4, OD-18): two test builds,+// BEFORE and AFTER, at the same frozen-clock views, compared with the B-06 metric (scripts/parity-images.ts+// compareParityImages: 16x9 linear-luminance tiles, tile threshold max(3 x repeat noise, 0.02), pass fraction 0.97, global+// mean < 0.02) and the thin-line check of the Golden Gate review (packages/golden-gate/tests/tools/draw-parity.ts: pixels+// differing by more than 32 levels in any channel, at most --over32-budget more than the BEFORE repeat). Per tier and view:+// BEFORE, a second BEFORE page (the noise floor) and AFTER, each on its own page. When AFTER differs from BEFORE, the AFTER+// build is captured again with its levers switched by dev parameters, so each difference is attributed by measurement:+// off heroMerge=false&shadowCache=false&standIns=false&casterTexels=0 (the AFTER build with every lever off)+// merge shadowCache=false&standIns=false&casterTexels=0 (OD-18 hero anchor merge alone)+// shadow heroMerge=false (OD-4/OD-9 cache, stand-ins and 2-texel threshold)+// Views: the count probe's Farm fixtures (scripts/scene-fixtures.ts) plus play destinations (dest-tractor, dest-paddocks)+// for close views of the hero shadows. The walk and tractor-drive workloads step on the frame's own delta, so their end+// state differs run to run (the tractor's wheel angle comes from its accumulated travel): each is run once on a BEFORE page+// to find its end pose, and every capture then places Rowan (walk) or mounts the tractor and places it (tractor-drive) there.+// bun scripts/capture-farm-draw-parity.ts --before draw-base --after draw-after [--tiers minimal,economy,balanced,high]+// [--views all|id,…] [--backend webgpu|webgl2] [--out evidence/draw-after/farm/parity] [--over32-budget 100]+// [--decompose auto|never|always]+// Output in --out: parity.json and parity.md (rows accumulate across runs, keyed by tier, view and backend) and, for every+// view where AFTER differs from BEFORE: <tier>-<view>[-webgl2]-before.png, -after.png, -diff.png (B-06, x4 luminance),+// -crop.png (zoomed BEFORE | AFTER over x8 difference | frame) and the lever captures that differ. Pixels only, no timing.+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { PNG } from 'pngjs';+import type { Browser } from 'puppeteer-core';+import { launchChrome, serveOwned } from '../packages/scene-kit/src/testing/node';+import { sceneOutput } from './build-scene';+import { compareParityImages, type RgbaImage } from './parity-images';+import { FARM_VIEWS } from './scene-fixtures';+import { enterFarmView, FARM_PARITY_VIEWS, FARM_WORKLOADS, openFarmPage, settleFarmShadow, shootFarm, type FarmBackend, type FarmPose } from './farm-capture-pages';++/* eslint-disable @typescript-eslint/no-explicit-any */+const ROOT = resolve(import.meta.dir, '..'), args = process.argv.slice(2);+const option = (name: string, fallback: string) => { const at = args.indexOf(name); return at < 0 ? fallback : args[at + 1] ?? fallback; };+export const LEVERS = { off: 'heroMerge=false&shadowCache=false&standIns=false&casterTexels=0', merge: 'shadowCache=false&standIns=false&casterTexels=0', shadow: 'heroMerge=false' } as const;+export type Lever = keyof typeof LEVERS;++/** Exact differences: pixels differing at all, by more than 8 and by more than 32 levels in any channel, the largest delta, and where. */+export function exactDifference(a: RgbaImage, b: RgbaImage) {+ let differing = 0, over8 = 0, over32 = 0, max = 0, x0 = Infinity, y0 = Infinity, x1 = -1, y1 = -1;+ for (let p = 0, i = 0; i < a.data.length; i += 4, p++) {+ let d = 0; for (let c = 0; c < 3; c++) d = Math.max(d, Math.abs(a.data[i + c]! - b.data[i + c]!));+ if (!d) continue; differing++; if (d > max) max = d;+ if (d > 8) { over8++; const x = p % a.width, y = Math.floor(p / a.width); x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }+ if (d > 32) over32++;+ }+ return { differing, over8, over32, max, box: over8 ? { x0, y0, x1, y1 } : null };+}+/** The window (w x h) holding the most differing pixels (over 8 levels when there are any), for a zoomed crop. */+export function densestWindow(a: RgbaImage, b: RgbaImage, w = 160, h = 90) {+ const cell = 10, cols = Math.ceil(a.width / cell), rows = Math.ceil(a.height / cell), strong = new Float64Array(cols * rows), weak = new Float64Array(cols * rows);+ for (let p = 0, i = 0; i < a.data.length; i += 4, p++) {+ let d = 0; for (let c = 0; c < 3; c++) d = Math.max(d, Math.abs(a.data[i + c]! - b.data[i + c]!));+ if (!d) continue; const k = Math.floor(Math.floor(p / a.width) / cell) * cols + Math.floor((p % a.width) / cell);+ weak[k]! += d; if (d > 8) strong[k]! += d;+ }+ const grid = strong.some(v => v > 0) ? strong : weak, cw = Math.ceil(w / cell), ch = Math.ceil(h / cell);+ let best = -1, bx = 0, by = 0;+ for (let y = 0; y + ch <= rows; y++) for (let x = 0; x + cw <= cols; x++) {+ let sum = 0; for (let j = 0; j < ch; j++) for (let i = 0; i < cw; i++) sum += grid[(y + j) * cols + x + i]!;+ if (sum > best) { best = sum; bx = x; by = y; }+ }+ // Centre the window on the weighted centroid of the differences inside the best one.+ let sx = 0, sy = 0, sw = 0;+ for (let j = 0; j < ch; j++) for (let i = 0; i < cw; i++) { const v = grid[(by + j) * cols + bx + i]!; sx += v * ((bx + i + .5) * cell); sy += v * ((by + j + .5) * cell); sw += v; }+ const cx = sw ? sx / sw : (bx + cw / 2) * cell, cy = sw ? sy / sw : (by + ch / 2) * cell;+ return { x: Math.max(0, Math.min(Math.round(cx - w / 2), a.width - w)), y: Math.max(0, Math.min(Math.round(cy - h / 2), a.height - h)), width: w, height: h };+}+const blank = (width: number, height: number): RgbaImage => ({ width, height, data: new Uint8Array(width * height * 4).fill(255) });+/** Nearest-neighbour copy of `rect` from `src` into `dst` at (dx, dy), scaled to (dw, dh); `pixel` may remap each value. */+function blit(dst: RgbaImage, src: RgbaImage, rect: { x: number; y: number; width: number; height: number }, dx: number, dy: number, dw: number, dh: number, pixel?: (i: number) => [number, number, number]) {+ for (let y = 0; y < dh; y++) for (let x = 0; x < dw; x++) {+ const sx = rect.x + Math.min(rect.width - 1, Math.floor(x * rect.width / dw)), sy = rect.y + Math.min(rect.height - 1, Math.floor(y * rect.height / dh)), s = (sy * src.width + sx) * 4, d = ((dy + y) * dst.width + dx + x) * 4;+ const [r, g, b] = pixel ? pixel(s) : [src.data[s]!, src.data[s + 1]!, src.data[s + 2]!];+ dst.data[d] = r; dst.data[d + 1] = g; dst.data[d + 2] = b; dst.data[d + 3] = 255;+ }+}+/** 640x360: BEFORE | AFTER zoomed 2.5x on top; the x8 channel difference of the crop | the AFTER frame with the crop outlined below. */+export function cropSheet(before: RgbaImage, after: RgbaImage) {+ const rect = densestWindow(before, after, 128, 72), out = blank(640, 360);+ blit(out, before, rect, 0, 0, 320, 180); blit(out, after, rect, 320, 0, 320, 180);+ blit(out, after, rect, 0, 180, 320, 180, s => { let d = 0; for (let c = 0; c < 3; c++) d = Math.max(d, Math.abs(after.data[s + c]! - before.data[s + c]!)); const v = Math.min(255, d * 8); return [v, v, v]; });+ blit(out, after, { x: 0, y: 0, width: after.width, height: after.height }, 320, 180, 320, 180);+ const sx = 320 / after.width, sy = 180 / after.height, rx0 = 320 + Math.floor(rect.x * sx), ry0 = 180 + Math.floor(rect.y * sy), rx1 = 320 + Math.ceil((rect.x + rect.width) * sx), ry1 = 180 + Math.ceil((rect.y + rect.height) * sy);+ const mark = (x: number, y: number) => { if (x < 320 || x >= 640 || y < 180 || y >= 360) return; const d = (y * 640 + x) * 4; out.data[d] = 255; out.data[d + 1] = 40; out.data[d + 2] = 40; };+ for (let x = rx0; x <= rx1; x++) { mark(x, ry0); mark(x, ry1); } for (let y = ry0; y <= ry1; y++) { mark(rx0, y); mark(rx1, y); }+ for (let y = 0; y < 360; y++) for (const x of [319, 320]) { const d = (y * 640 + x) * 4; out.data[d] = out.data[d + 1] = out.data[d + 2] = 255; }+ for (let x = 0; x < 640; x++) for (const y of [179, 180]) { const d = (y * 640 + x) * 4; out.data[d] = out.data[d + 1] = out.data[d + 2] = 255; }+ return { image: out, rect };+}+export const writePng = (path: string, image: RgbaImage) => { const png = new PNG({ width: image.width, height: image.height }); png.data = Buffer.from(image.data); writeFileSync(path, PNG.sync.write(png)); };++interface Shot { png: RgbaImage; pose: FarmPose | null; settle: unknown; counts: unknown; messages: string[] }+/** A workload's end pose: the workload run once on a BEFORE page (as the count probe runs it), not captured. */+async function discover(browser: Browser, server: { url: string; port: number }, tier: string, backend: FarmBackend, view: string): Promise<FarmPose> {+ const { page } = await openFarmPage({ browser, base: server.url, owned: new Set([server.port]), tier, backend, view: 'hero' });+ try { const pose = await enterFarmView(page, view, null); if (!pose) throw new Error(`${view}: no pose`); return pose; } finally { await page.close().catch(() => {}); }+}+async function capture(browser: Browser, server: { url: string; port: number }, tier: string, backend: FarmBackend, view: string, pin: FarmPose | null, extra?: string): Promise<Shot> {+ const named = (FARM_VIEWS as readonly string[]).includes(view);+ const { page, messages } = await openFarmPage({ browser, base: server.url, owned: new Set([server.port]), tier, backend, view: named ? view : 'hero', ...(extra ? { extra: Object.fromEntries(new URLSearchParams(extra)) } : {}) });+ try {+ const pose = await enterFarmView(page, view, pin), settle = await settleFarmShadow(page), png = await shootFarm(page);+ const counts = await page.evaluate(() => { const s = (window as any).__kilnScene, st = s.stats(); return { drawCalls: st.render?.drawCalls, triangles: st.render?.triangles, pipelines: st.pipelines, shadow: st.counts?.shadow ? { staticRenders: st.counts.shadow.staticRenders, liveCasters: st.counts.shadow.liveCasters, pendingSettle: st.counts.shadow.pendingSettle } : null }; });+ return { png, pose, settle, counts, messages };+ } finally { await page.close().catch(() => {}); }+}++if (import.meta.main) {+ const before = option('--before', 'draw-base'), after = option('--after', 'draw-after'), tiers = option('--tiers', 'minimal,economy,balanced,high').split(',');+ const views = option('--views', 'all') === 'all' ? FARM_PARITY_VIEWS : option('--views', '').split(','), backend = (option('--backend', 'webgpu') === 'webgl2' ? 'webgl2' : 'webgpu') as FarmBackend;+ const out = resolve(ROOT, option('--out', 'evidence/draw-after/farm/parity')), budget = Number(option('--over32-budget', '100')), decompose = option('--decompose', 'auto');+ for (const v of views) if (!FARM_PARITY_VIEWS.includes(v)) throw new Error(`Unknown Farm parity view ${v}`);+ if (!(budget >= 0)) throw new Error('--over32-budget must be 0 or more');+ mkdirSync(out, { recursive: true });+ const servers = { before: await serveOwned(sceneOutput('farm', before, 'test')), after: await serveOwned(sceneOutput('farm', after, 'test')) };+ const browser = await launchChrome({ workspace: ROOT, name: 'farm-draw-parity', windowSize: [1280, 720] }), results: any[] = [], tag = backend === 'webgl2' ? '-webgl2' : '';+ const json = resolve(out, 'parity.json'), key = (r: any) => `${r.tier}|${r.view}|${r.backend}`;+ const flush = () => {+ const previous: any[] = existsSync(json) ? JSON.parse(readFileSync(json, 'utf8')).results ?? [] : [], fresh = new Set(results.map(key));+ const all = [...previous.filter(r => !fresh.has(key(r))), ...results];+ writeFileSync(json, JSON.stringify({ before, after, size: [1280, 720], levers: LEVERS, over32Budget: budget, results: all }, null, 1) + '\n');+ const lever = (r: any, name: Lever) => r.levers?.[name] ? `${r.levers[name].vsBefore.over8}/${r.levers[name].vsBefore.over32}` : '-';+ writeFileSync(resolve(out, 'parity.md'), ['| Backend | Tier | View | Pass | B-06 | Tiles | Mean Δ | Repeat mean | >32 levels (after / repeat) | Pixels differing (after / repeat) | Max Δ | >8 / >32 with levers off | merge alone | shadow alone |', '|---|---|---|---|---|---|---|---|---|---|---|---|---|---|',+ ...all.sort((a, b) => a.backend.localeCompare(b.backend) || tiers.indexOf(a.tier) - tiers.indexOf(b.tier) || FARM_PARITY_VIEWS.indexOf(a.view) - FARM_PARITY_VIEWS.indexOf(b.view)).map(r => `| ${r.backend} | ${r.tier} | ${r.view} | ${r.pass ? 'yes' : '**NO**'} | ${r.b06 ? 'yes' : 'NO'} | ${r.passingTiles}/144 | ${r.globalMean.toExponential(2)} | ${r.noiseGlobalMean.toExponential(2)} | ${r.afterVsBefore.over32} / ${r.repeatVsBefore.over32} | ${r.afterVsBefore.differing} / ${r.repeatVsBefore.differing} | ${r.afterVsBefore.max} | ${lever(r, 'off')} | ${lever(r, 'merge')} | ${lever(r, 'shadow')} |`)].join('\n') + '\n');+ };+ try {+ for (const tier of tiers) for (const view of views) {+ const name = `${tier}-${view}${tag}`;+ try {+ const pin = FARM_WORKLOADS.has(view) ? await discover(browser, servers.before, tier, backend, view) : null;+ const a = await capture(browser, servers.before, tier, backend, view, pin), r = await capture(browser, servers.before, tier, backend, view, pin), b = await capture(browser, servers.after, tier, backend, view, pin);+ const metric = compareParityImages(a.png, r.png, b.png), afterVsBefore = exactDifference(a.png, b.png), repeatVsBefore = exactDifference(a.png, r.png);+ const lines = { over32: afterVsBefore.over32, noise: repeatVsBefore.over32, budget, pass: afterVsBefore.over32 <= repeatVsBefore.over32 + budget };+ const differs = afterVsBefore.differing > repeatVsBefore.differing || afterVsBefore.over8 > repeatVsBefore.over8;+ const row: any = { tier, view, backend, pass: metric.pass && lines.pass, b06: metric.pass, lines, globalMean: metric.globalMean, noiseGlobalMean: metric.noiseGlobalMean, passingTiles: metric.passingTiles,+ failingTiles: metric.tiles.filter(t => !t.pass).map(t => ({ x: t.x, y: t.y, mean: +t.mean.toExponential(2), threshold: +t.threshold.toExponential(2) })), afterVsBefore, repeatVsBefore, differs,+ pose: a.pose, settle: { before: a.settle, after: b.settle }, counts: { before: a.counts, after: b.counts }, messages: { before: a.messages, repeat: r.messages, after: b.messages } };+ if (differs || !row.pass) {+ writePng(resolve(out, `${name}-before.png`), a.png); writePng(resolve(out, `${name}-after.png`), b.png); writePng(resolve(out, `${name}-diff.png`), metric.diff);+ if (repeatVsBefore.differing) writePng(resolve(out, `${name}-repeat.png`), r.png);+ const sheet = cropSheet(a.png, b.png); writePng(resolve(out, `${name}-crop.png`), sheet.image); row.crop = sheet.rect;+ }+ if (decompose === 'always' || (decompose === 'auto' && differs)) {+ row.levers = {};+ for (const [lever, query] of Object.entries(LEVERS) as [Lever, string][]) {+ const c = await capture(browser, servers.after, tier, backend, view, a.pose, query), m = compareParityImages(a.png, r.png, c.png), vs = exactDifference(a.png, c.png);+ row.levers[lever] = { query, b06: m.pass, passingTiles: m.passingTiles, globalMean: m.globalMean, vsBefore: vs, vsAfter: exactDifference(b.png, c.png), counts: c.counts, messages: c.messages };+ if (vs.differing > repeatVsBefore.differing) { writePng(resolve(out, `${name}-${lever}.png`), c.png); writePng(resolve(out, `${name}-${lever}-crop.png`), cropSheet(a.png, c.png).image); }+ }+ }+ results.push(row);+ console.log(`${name}: ${row.pass ? 'PASS' : 'FAIL'} B-06 ${metric.pass ? 'pass' : 'FAIL'} ${metric.passingTiles}/144 mean ${metric.globalMean.toExponential(2)} noise ${metric.noiseGlobalMean.toExponential(2)}; >32 ${afterVsBefore.over32} vs repeat ${repeatVsBefore.over32} ${lines.pass ? 'ok' : 'OVER'}; differing ${afterVsBefore.differing} (>8 ${afterVsBefore.over8}, max ${afterVsBefore.max}) repeat ${repeatVsBefore.differing}${row.levers ? `; off ${row.levers.off.vsBefore.over8}, merge ${row.levers.merge.vsBefore.over8}, shadow ${row.levers.shadow.vsBefore.over8} px >8` : ''}`);+ } catch (error) {+ results.push({ tier, view, backend, pass: false, b06: false, error: String((error as Error)?.stack ?? error).slice(0, 1500), lines: {}, afterVsBefore: {}, repeatVsBefore: {}, globalMean: NaN, noiseGlobalMean: NaN, passingTiles: 0 });+ console.log(`${name}: ERROR ${String(error).split('\n')[0]}`);+ }+ flush();+ }+ } finally { await browser.close(); await servers.before.close(); await servers.after.close(); flush(); }+}diff --git a/scenes/scripts/capture-farm-parity.ts b/scenes/scripts/capture-farm-parity.tsindex fd07d987..19c0e1e4 100644--- a/scenes/scripts/capture-farm-parity.ts+++ b/scenes/scripts/capture-farm-parity.ts@@ -9,7 +9,7 @@ import { assertOwnedUrl, launchChrome, serveOwned, waitForReady, waitFrames, worimport { compareParityImages } from './parity-images';import { cropImage, type CropRectangle } from './capture-woodland-ab';import { readPilotRendererCounts, readPilotShaderClock } from './farm-renderer-counts';-import { compareFarmOptimizationCounts, compareStaticRendererCounts, summarizeStaticCountCoverage, type ColliderCounts } from './farm-count-gates';+import { compareFarmOptimizationCounts, compareStaticRendererCounts, compareX02Reference, summarizeStaticCountCoverage, validateX02Baseline, X02_BASELINE_PATH, type ColliderCounts, type X02Baseline } from './farm-count-gates';const TIMEOUT = 120_000, WIDTH = 1280, HEIGHT = 720;const fallbackWarning = /^THREE\.WebGPURenderer: WebGPU is not available, running under WebGL2 backend\.$/;@@ -231,11 +231,14 @@ export async function runFarmParity(options: { workspace?: string; release?: 'r3// M2d calibration (PROGRESS R4-07): the pilot's 3 s old-old pair cannot bound grass-wind and stream// differences between time 0 and its elapsed shader clock, so the frozen rewrite takes that phase.const alignPhase = options.stage === 'm2d';- const results: any[] = [], ledger: any = { runnerPid: process.pid, closed: false }, report: any = { schema: 'kiln.farm-parity/1', date: new Date().toISOString(), release, stage: options.stage ?? 'm2a', conditions: { width: WIDTH, height: HEIGHT, dpr: 1, tier: 'high', captureDelay: '3 seconds after readiness; repeat 3 seconds later', rewriteTime: alignPhase ? "the pilot's shader clock at its first capture (midpoint of a read-only bracket), then frozen: grass wind and stream phase match; clip mixers are not aligned and stay within the old-old noise rule" : 0, rewriteHerd: false, liveGovernor: 'disabled with empty synthetic trace', oracle: 'unmodified sealed serve.mjs verifies delivery.json', normalizationCss: normalizedCss, imageMetric: 'sRGB-decoded linear luminance, Rec.709 coefficients, 16×9 tiles', tileThreshold: 'max(3 * old-old tile noise, 0.02)', tilePassFraction: .97, globalMeanExclusiveLimit: .02, diffVisualGain: 4, performanceTiming: 'not collected', countGate: countGateEnabled ? 'B-07 optimization goldens and collider counts (frozen pilot fixture) and X-02 counts at every named view and play fixture: inclusive ±2% draws/triangles, pipelines <=105% of both independent pilot samples; qualification requires every named view and play fixture on both backends' : 'Not applied: this stage records observations only',+ const results: any[] = [], ledger: any = { runnerPid: process.pid, closed: false }, report: any = { schema: 'kiln.farm-parity/1', date: new Date().toISOString(), release, stage: options.stage ?? 'm2a', conditions: { width: WIDTH, height: HEIGHT, dpr: 1, tier: 'high', captureDelay: '3 seconds after readiness; repeat 3 seconds later', rewriteTime: alignPhase ? "the pilot's shader clock at its first capture (midpoint of a read-only bracket), then frozen: grass wind and stream phase match; clip mixers are not aligned and stay within the old-old noise rule" : 0, rewriteHerd: false, liveGovernor: 'disabled with empty synthetic trace', oracle: 'unmodified sealed serve.mjs verifies delivery.json', normalizationCss: normalizedCss, imageMetric: 'sRGB-decoded linear luminance, Rec.709 coefficients, 16×9 tiles', tileThreshold: 'max(3 * old-old tile noise, 0.02)', tilePassFraction: .97, globalMeanExclusiveLimit: .02, diffVisualGain: 4, performanceTiming: 'not collected', countGate: countGateEnabled ? 'B-07 optimization goldens and collider counts (frozen pilot fixture) and X-02 counts at every named view and play fixture: inclusive ±2% draws/triangles, pipelines <=105% of the committed reference of the optimized build (' + X02_BASELINE_PATH + ', OD-8/D-53; the two pilot samples are recorded beside it, not gated); qualification requires every named view and play fixture on both backends' : 'Not applied: this stage records observations only',playFixtures: Object.fromEntries(playViews.map(view => [view, PLAY_FIXTURES[view]])), playConditions: 'Rewrite: setPlaying(true) then the teleport hook (the pilot visit) under the frozen clock; the player clip is held at its start. Pilot: its #visit destination menu; E on the canvas for the door; its play status line records the farmer position',streamCrop: views.includes('watermill-wheel') ? { view: 'watermill-wheel', rectangle: STREAM_CROP, rule: 'Same tile metric on the crop (16 by 9 tiles of 40 by 28 px)' } : undefined }, views, backends, results, ledger };const save = () => writeFile(resolve(out, 'results.json'), JSON.stringify(report, null, 2));let pilot: Awaited<ReturnType<typeof serveSealedPilot>> | undefined, hosted: Awaited<ReturnType<typeof serveOwned>> | undefined, browser: Browser | undefined;+ // OD-8 (D-53): X-02 compares against the committed reference of the optimized build; B-06 pixels and B-07 still use the pilot.+ const x02Reference = countGateEnabled ? JSON.parse(await readFile(workspacePath(workspace, X02_BASELINE_PATH), 'utf8')) as X02Baseline : null;+ if (x02Reference) { const problems = validateX02Baseline(x02Reference); assert(problems.length === 0, `X-02 reference ${X02_BASELINE_PATH}: ${problems.join('; ')}`); }// Each release is judged against its own sealed collision world (SPEC 19.8; r34 differs only by its farmhouse, D-07).const colliderFixture = JSON.parse(await readFile(workspacePath(workspace, `packages/farm/fixtures/${release === 'r33' ? 'play-colliders.json' : `play-colliders-${release}.json`}`), 'utf8')) as ColliderCounts;try {@@ -275,9 +278,10 @@ export async function runFarmParity(options: { workspace?: string; release?: 'r3const rewriteCounts = { drawCalls: fresh.stats.render.drawCalls, triangles: fresh.stats.render.triangles,geometries: fresh.stats.memory.geometries, textures: fresh.stats.memory.textures, pipelines: fresh.stats.pipelines, programs: fresh.stats.programs };const kind = play ? 'play fixture' : 'named view';+ const x02 = compareX02Reference(x02Reference!, { view, backend, tier: 'high', viewport: [WIDTH, HEIGHT], freshPage: true }, rewriteCounts);const first = compareStaticRendererCounts(old.firstStats, rewriteCounts, kind), repeat = compareStaticRendererCounts(old.repeatStats, rewriteCounts, kind);const b07 = compareFarmOptimizationCounts({ release, counts: fresh.stats.counts, pilot: old.firstStats, pilotRepeat: old.repeatStats, rewrite: rewriteCounts, colliders: { actual: fresh.stats.colliders, fixture: colliderFixture } });- result.countChecks = { b07, x02: { pass: first.pass && repeat.pass, first, repeat, baseline: 'Both independently captured pilot samples; no favorable sample selection' } };+ result.countChecks = { b07, x02: { ...x02, baseline: `${X02_BASELINE_PATH} (OD-8, D-53: re-baselined on the optimized build)`, pilotObservation: { first, repeat, gated: false, note: 'Both pilot samples, recorded only: the optimized build lowers draws on purpose' } } };if (!b07.pass) failures.push('B-07 optimization statistics failed');if (!result.countChecks.x02.pass) failures.push(`X-02 renderer count limits failed at this ${kind}`);}diff --git a/scenes/scripts/capture-foundry-draw-parity.ts b/scenes/scripts/capture-foundry-draw-parity.tsnew file mode 100644index 00000000..1be5abb5--- /dev/null+++ b/scenes/scripts/capture-foundry-draw-parity.ts@@ -0,0 +1,176 @@+// Foundry Floor cross-build parity (draw-optimization step S5): the same frozen-clock views captured on a BEFORE build+// (draw-base, main at c734e2a) and an AFTER build (draw-after, HEAD 892d103), plus a second BEFORE capture as the noise floor,+// judged by the B-06 comparer (scripts/parity-images.ts compareParityImages: 16x9 luminance tiles, tile threshold max(3x repeat+// noise, 0.02), pass fraction 0.97, global mean < 0.02) and by the thin-line check the Golden Gate review added (pixels differing+// by more than 32 levels in a channel, at most `--over32-budget` (100 per 1280x720 view) more than the BEFORE repeat has). Both+// builds are test-mode standalones of the campus (bun scripts/build-scene.ts --scene foundry-floor --mode test --label <l>) and are+// served side by side from owned loopback ports. Nothing is passed to either build but the shared frozen-clock parameters, so the+// AFTER build runs its own defaults (shared planting, MSAA discard on WebGPU).+// bun scripts/capture-foundry-draw-parity.ts [--before draw-base] [--after draw-after] [--tiers minimal,economy,balanced,high]+// [--views campus,pair,canopy,split,bridge,roundabout,close-island,close-avenue,close-parking,close-windbreak,close-arrival,drive,fab-landing,…]+// [--backend webgl2] [--after-query plantingShared=false] [--over32-budget 100] [--save high|all|fail] [--out evidence/draw-after/foundry-floor/parity]+// bun scripts/capture-foundry-draw-parity.ts --merge [--out <dir>] (rebuilds parity.md and parity-summary.json from every parity-*.json)+// `--after-query` adds dev parameters to the AFTER captures only (for example plantingShared=false, which restores the per-material+// planting): with it the AFTER build differs from BEFORE by the MSAA discard alone, so a view that matches BEFORE exactly then proves+// that every pixel the defaults changed belongs to the planting.+// Views: the count fixtures of scripts/scene-fixtures.ts (six campus views, the drive placement, eight fab views) and the five+// planting close-ups of capture-foundry-planting-parity.ts. `drive` puts the sedan down at rest at a fixed place on the split road,+// where the count fixture's two seconds at throttle .8 end to within about 4 m (that fixture's own end point is a workload state:+// it moves by metres between loads, which a pixel comparison cannot absorb); `fab-<view>` enters the fab from Arrival and sets one+// of its eight views.+// Output: <out>/captures/<backend>/<tier>-<view>[-<variant>]-{before,after,repeat,diff}.png (after, before and the x4 B-06 diff for every case at high+// WebGPU and for every failing case, repeat only for failing cases), parity-<backend>-<tiers>.json and, after --merge, parity.md. Pages load from the owned loopback+// servers; nothing here reads time. The exit code is 1 when a case fails either check.+import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { PNG } from 'pngjs';+import type { Page } from 'puppeteer-core';+import { assertOwnedUrl, launchChrome, serveOwned, waitForReady, waitFrames } from '../packages/scene-kit/src/testing/node';+import { parseCampus } from '../packages/foundry-floor/src/campus/data';+import { campusPlantings, PLANT_SIZES } from '../packages/foundry-floor/src/campus/exterior/planting';+import { sceneOutput } from './build-scene';+import { compareParityImages, type RgbaImage } from './parity-images';++const ROOT = resolve(import.meta.dir, '..'), WIDTH = 1280, HEIGHT = 720, TIMEOUT = 180_000;+const HIDE_UI = '.ks-hud,.ks-help,.ks-credits,.ks-fade,.ks-dev-panel,#page-status{visibility:hidden!important}';+const CAMPUS_VIEWS = ['campus', 'pair', 'canopy', 'split', 'bridge', 'roundabout'], CLOSE_VIEWS = ['close-island', 'close-avenue', 'close-parking', 'close-windbreak', 'close-arrival'];+const FAB_VIEWS = ['landing', 'overview', 'spine', 'litho', 'cluster', 'stocker', 'gallery', 'section'].map(v => `fab-${v}`);+const ALL_VIEWS = [...CAMPUS_VIEWS, ...CLOSE_VIEWS, 'drive', ...FAB_VIEWS];+const args = process.argv.slice(2), option = (name: string, fallback: string) => { const at = args.indexOf(name); return at < 0 ? fallback : args[at + 1] ?? fallback; };+const out = resolve(ROOT, option('--out', 'evidence/draw-after/foundry-floor/parity'));++/* eslint-disable @typescript-eslint/no-explicit-any */+const invoke = (page: Page, name: string, ...a: unknown[]) => page.evaluate((n, v) => (window as any).__kilnScene.invoke(n, ...v), name, a) as Promise<any>;+const write = (path: string, image: RgbaImage) => { const png = new PNG({ width: image.width, height: image.height }); png.data = Buffer.from(image.data); writeFileSync(path, PNG.sync.write(png)); };+/** Exact pixel differences: pixels differing at all, by more than 8 and by more than 32 levels in any channel, and the largest channel delta. */+const exact = (a: RgbaImage, b: RgbaImage) => {+ let differing = 0, over8 = 0, over32 = 0, max = 0;+ for (let i = 0; i < a.data.length; i += 4) { let d = 0; for (let c = 0; c < 3; c++) d = Math.max(d, Math.abs(a.data[i + c]! - b.data[i + c]!)); if (d) { differing++; if (d > 8) over8++; if (d > 32) over32++; if (d > max) max = d; } }+ return { differingPixels: differing, over8, over32, maxChannelDelta: max };+};++function summarize(root: string) {+ // Every parity-*.json contributes; a case run again (the same variant, backend, tier and view) is taken from the newest file.+ const files = readdirSync(root).filter(f => /^parity-(webgpu|webgl2)-.*\.json$/.test(f)).sort((a, b) => statSync(resolve(root, a)).mtimeMs - statSync(resolve(root, b)).mtimeMs), newest = new Map<string, any>();+ for (const f of files) for (const r of JSON.parse(readFileSync(resolve(root, f), 'utf8')).results as any[]) newest.set(`${r.variant ?? 'defaults'}|${r.backend}|${r.tier}|${r.view}`, r);+ const rows = [...newest.values()];+ for (const r of rows) r.variant ??= 'defaults';+ const key = (r: any) => `${r.variant === 'defaults' ? 0 : 1}${r.variant}|${r.backend}|${TIER_ORDER.indexOf(r.tier)}|${ALL_VIEWS.indexOf(r.view)}`;+ rows.sort((a, b) => key(a) < key(b) ? -1 : 1);+ const by = (pick: (r: any) => string) => { const m = new Map<string, { cases: number; pass: number; b06: number; lines: number }>(); for (const r of rows) { const c = m.get(pick(r)) ?? { cases: 0, pass: 0, b06: 0, lines: 0 }; c.cases++; if (r.pass) c.pass++; if (r.b06) c.b06++; if (r.lines.pass) c.lines++; m.set(pick(r), c); } return [...m.entries()].map(([k, v]) => ({ key: k, ...v })); };+ const md = ['| variant | backend | tier | view | pass | B-06 | tiles | mean luminance delta | noise mean | over 32 (after vs before) | over 32 (repeat vs before) | pixels differing (after vs before) | max channel delta | pixels differing (repeat vs before) |', '|---|---|---|---|---|---|---|---|---|---|---|---|---|---|',+ ...rows.map(r => `| ${r.variant} | ${r.backend} | ${r.tier} | ${r.view} | ${r.pass ? 'yes' : 'NO'} | ${r.b06 ? 'yes' : 'NO'} | ${r.passingTiles}/${r.tiles} | ${r.globalMean.toExponential(2)} | ${r.noiseGlobalMean.toExponential(2)} | ${r.lines.over32} | ${r.lines.noise} | ${r.afterVsBefore.differingPixels} | ${r.afterVsBefore.maxChannelDelta} | ${r.repeatVsBefore.differingPixels} |`)];+ const totals = { cases: rows.length, pass: rows.filter(r => r.pass).length, b06: rows.filter(r => r.b06).length, lines: rows.filter(r => r.lines.pass).length, byVariantBackendTier: by(r => `${r.variant} ${r.backend} ${r.tier}`), byVariantBackend: by(r => `${r.variant} ${r.backend}`) };+ writeFileSync(resolve(root, 'parity.md'), md.join('\n') + '\n'); writeFileSync(resolve(root, 'parity-summary.json'), JSON.stringify({ totals, results: rows }, null, 1) + '\n');+ return totals;+}+const TIER_ORDER = ['minimal', 'economy', 'balanced', 'high'];+if (args.includes('--merge')) { console.log(JSON.stringify(summarize(out))); process.exit(0); }++const beforeBuild = option('--before', 'draw-base'), afterBuild = option('--after', 'draw-after'), tiers = option('--tiers', TIER_ORDER.join(',')).split(',');+const afterQuery = option('--after-query', ''), variant = afterQuery ? afterQuery.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_|_$/g, '') : 'defaults', variantTag = afterQuery ? `-${variant}` : '';+const views = option('--views', ALL_VIEWS.join(',')).split(','), backend = option('--backend', '') === 'webgl2' ? 'webgl2' : 'webgpu', save = option('--save', 'high'), budget = Number(option('--over32-budget', '100'));+if (!(budget >= 0)) throw new Error('--over32-budget must be 0 or more');+for (const v of views) if (!ALL_VIEWS.includes(v)) throw new Error(`Unknown view ${v}`);+for (const t of tiers) if (!TIER_ORDER.includes(t)) throw new Error(`Unknown tier ${t}`);++const plants = campusPlantings(parseCampus(readFileSync(resolve(ROOT, 'packages/foundry-floor/data/campus.json'), 'utf8')));+/** Camera 28 m from the first plant of the zone (the island's first conifer, past x = 300 on the avenue), eye 6 m up, looking at its middle, from the campus-centre side (the island's from outside it, 22 m); as capture-foundry-planting-parity.ts. */+function closePose(zone: string): { position: [number, number, number]; target: [number, number, number] } {+ const p = plants.find(q => q.zone === zone && (zone !== 'island' || q.model === 'tree-conifer-m') && (zone !== 'avenue' || Math.abs(q.x) > 300))!, d = Math.hypot(p.x, p.z) || 1, h = PLANT_SIZES[p.model][1];+ const away = zone === 'island' ? 22 : -28;+ return { position: [p.x + p.x / d * away, 6, p.z + p.z / d * away], target: [p.x, h * 0.45, p.z] };+}+/** Waits until two reads 10 frames apart agree (the orbit, chase camera and fab camera ease in). */+async function settle(page: Page, read: () => Promise<unknown>) { for (let i = 0, last = ''; i < 40; i++) { const now = JSON.stringify(await read()); if (now === last) break; last = now; await waitFrames(page, 10); } }+interface Shot { png: RgbaImage; backend: string | null; messages: string[]; msaa: unknown }+async function open(browser: Awaited<ReturnType<typeof launchChrome>>, base: string, owned: ReadonlySet<number>, tier: string, messages: string[], extra: Record<string, string>): Promise<Page> {+ const url = `${base}/?${new URLSearchParams({ freeze: '1', time: '0', capture: '1', tier, ...(backend === 'webgl2' ? { backend } : {}), ...extra })}`;+ assertOwnedUrl(url, owned);+ const page = await browser.newPage(); page.setDefaultTimeout(TIMEOUT);+ page.on('console', m => { if (m.type() === 'error' || m.type() === 'warn') messages.push(`${m.type()}: ${m.text().slice(0, 300)}`); });+ page.on('pageerror', e => messages.push(`pageerror: ${String(e).slice(0, 300)}`));+ await page.setViewport({ width: WIDTH, height: HEIGHT, deviceScaleFactor: 1 });+ await page.emulateMediaFeatures([{ name: 'prefers-reduced-motion', value: 'no-preference' }]);+ await page.goto(url, { waitUntil: 'load', timeout: TIMEOUT }); await waitForReady(page);+ await page.addStyleTag({ content: HIDE_UI });+ await page.waitForFunction(() => (window as any).__kilnScene.invoke('driveTraffic', 1) !== null, { timeout: TIMEOUT, polling: 100 });+ return page;+}+async function grab(page: Page, messages: string[]): Promise<Shot> {+ await waitFrames(page, 4);+ const canvas = await page.$('canvas'), png = PNG.sync.read(Buffer.from(await canvas!.screenshot({ type: 'png' })));+ if (png.width !== WIDTH || png.height !== HEIGHT) throw new Error(`Capture is ${png.width}x${png.height}, expected ${WIDTH}x${HEIGHT}`);+ const msaa = await invoke(page, 'msaaPolicy').catch(() => null);+ return { png: { width: png.width, height: png.height, data: new Uint8Array(png.data) }, backend: await page.$eval('.ks-root', root => root.getAttribute('data-kiln-backend')), messages: messages.splice(0), msaa };+}+const campusShot = async (browser: Awaited<ReturnType<typeof launchChrome>>, base: string, owned: ReadonlySet<number>, tier: string, view: string, extra: Record<string, string> = {}): Promise<Shot> => {+ const messages: string[] = [], page = await open(browser, base, owned, tier, messages, extra);+ try {+ if (view.startsWith('close-')) { const pose = closePose(view.slice(6)); await invoke(page, 'campusPose', pose.position, pose.target, 50); }+ else if (view === 'drive') {+ // The sedan set down at rest at a fixed place on the split road, where the count fixture's two seconds at throttle .8 end to within+ // about 4 m (the fixture's own end point moves by metres between loads, because the car starts on the wall clock); the chase camera settles behind it.+ await page.evaluate(() => (window as any).__kilnScene.setPlaying(true));+ await page.waitForFunction(() => (window as any).__kilnScene.invoke('driveState') !== null, { timeout: TIMEOUT, polling: 100 });+ await invoke(page, 'setDriveInput', { throttle: 0 }); await invoke(page, 'placeCar', -3820, 7.25, 0, 0);+ } else await invoke(page, 'campusView', view);+ await waitFrames(page, 40);+ await settle(page, async () => view === 'drive' ? (await invoke(page, 'driveState'))?.camera.position : (await invoke(page, 'campusState')).camera);+ return await grab(page, messages);+ } finally { await page.close().catch(() => {}); }+};+/** One page enters the fab from Arrival (as tests/tools/capture-local-v09.ts) and captures each requested fab view. */+async function fabShots(browser: Awaited<ReturnType<typeof launchChrome>>, base: string, owned: ReadonlySet<number>, tier: string, wanted: string[], extra: Record<string, string> = {}): Promise<Map<string, Shot>> {+ const messages: string[] = [], page = await open(browser, base, owned, tier, messages, extra), shots = new Map<string, Shot>();+ try {+ await invoke(page, 'campusView', 'canopy');+ await page.waitForFunction(() => (window as any).__kilnScene.invoke('campusState')?.canEnter, { timeout: TIMEOUT, polling: 100 });+ await invoke(page, 'campusEnter');+ await page.waitForFunction(() => { const s = (window as any).__kilnScene.invoke('campusPlace'); return s.interiorReady && !s.moving; }, { timeout: TIMEOUT, polling: 100 });+ await page.evaluate(() => (window as any).__kilnScene.setTimeScale(0));+ await waitFrames(page, 12);+ for (const view of wanted) {+ await invoke(page, 'ffSetView', view.slice(4)); await waitFrames(page, 12);+ await settle(page, () => invoke(page, 'ffCamera'));+ shots.set(view, await grab(page, messages));+ }+ return shots;+ } finally { await page.close().catch(() => {}); }+}++mkdirSync(resolve(out, 'captures', backend), { recursive: true });+const hostedBefore = await serveOwned(sceneOutput('foundry-floor', beforeBuild, 'test')), hostedAfter = await serveOwned(sceneOutput('foundry-floor', afterBuild, 'test'));+const owned = new Set([hostedBefore.port, hostedAfter.port]), browser = await launchChrome({ workspace: ROOT, name: 'ff-draw-parity', windowSize: [WIDTH, HEIGHT] });+const results: any[] = [], afterParams = Object.fromEntries(new URLSearchParams(afterQuery));+function record(tier: string, view: string, before: Shot, repeat: Shot, after: Shot) {+ const parity = compareParityImages(before.png, repeat.png, after.png), name = `${tier}-${view}${variantTag}`;+ const afterVsBefore = exact(before.png, after.png), repeatVsBefore = exact(before.png, repeat.png);+ const lines = { over32: afterVsBefore.over32, noise: repeatVsBefore.over32, budget, pass: afterVsBefore.over32 <= repeatVsBefore.over32 + budget };+ const pass = parity.pass && lines.pass;+ if (save === 'all' || (save === 'high' && tier === 'high' && backend === 'webgpu') || !pass) {+ const dir = resolve(out, 'captures', backend); write(resolve(dir, `${name}-before.png`), before.png); write(resolve(dir, `${name}-after.png`), after.png); write(resolve(dir, `${name}-diff.png`), parity.diff);+ if (!pass) write(resolve(dir, `${name}-repeat.png`), repeat.png);+ }+ const row = { variant, backend, tier, view, pass, b06: parity.pass, lines, globalMean: parity.globalMean, noiseGlobalMean: parity.noiseGlobalMean, passingTiles: parity.passingTiles, tiles: parity.tiles.length,+ failingTiles: parity.tiles.filter(t => !t.pass).map(t => ({ x: t.x, y: t.y, mean: +t.mean.toExponential(2), threshold: +t.threshold.toExponential(2) })), afterVsBefore, repeatVsBefore,+ backends: { before: before.backend, after: after.backend }, msaaPolicyAfter: after.msaa, messages: { before: before.messages, repeat: repeat.messages, after: after.messages } };+ results.push(row);+ console.log(`${backend}${variantTag} ${tier}-${view}: ${pass ? 'PASS' : 'FAIL'} B-06 ${parity.pass ? 'pass' : 'FAIL'} mean ${parity.globalMean.toExponential(2)} noise ${parity.noiseGlobalMean.toExponential(2)} tiles ${parity.passingTiles}/${parity.tiles.length}; over 32 ${afterVsBefore.over32} vs repeat ${repeatVsBefore.over32} (budget ${budget}) ${lines.pass ? 'ok' : 'OVER'}; differing ${afterVsBefore.differingPixels} (max ${afterVsBefore.maxChannelDelta}), repeat differing ${repeatVsBefore.differingPixels}${after.messages.length || before.messages.length ? ` MESSAGES ${before.messages.length}/${after.messages.length}` : ''}`);+}+try {+ for (const tier of tiers) {+ for (const view of views.filter(v => !v.startsWith('fab-'))) {+ const before = await campusShot(browser, hostedBefore.url, owned, tier, view), repeat = await campusShot(browser, hostedBefore.url, owned, tier, view), after = await campusShot(browser, hostedAfter.url, owned, tier, view, afterParams);+ record(tier, view, before, repeat, after);+ }+ const fab = views.filter(v => v.startsWith('fab-'));+ if (fab.length) {+ const before = await fabShots(browser, hostedBefore.url, owned, tier, fab), repeat = await fabShots(browser, hostedBefore.url, owned, tier, fab), after = await fabShots(browser, hostedAfter.url, owned, tier, fab, afterParams);+ for (const view of fab) record(tier, view, before.get(view)!, repeat.get(view)!, after.get(view)!);+ }+ }+} finally { await browser.close(); await hostedBefore.close(); await hostedAfter.close(); }+writeFileSync(resolve(out, `parity-${backend}-${tiers.join('+')}${variantTag}${views.length === ALL_VIEWS.length ? '' : '-subset'}.json`), JSON.stringify({ before: beforeBuild, after: afterBuild, size: [WIDTH, HEIGHT], backend, budget, results }, null, 1) + '\n');+console.log(JSON.stringify(summarize(out)));+process.exitCode = results.every(r => r.pass) ? 0 : 1;diff --git a/scenes/scripts/capture-foundry-planting-parity.ts b/scenes/scripts/capture-foundry-planting-parity.tsnew file mode 100644index 00000000..72bdd3ba--- /dev/null+++ b/scenes/scripts/capture-foundry-planting-parity.ts@@ -0,0 +1,78 @@+// Foundry Floor planting parity (draw-optimization wave B, OD-18): frozen-clock captures of the campus views with the shared+// planting (the default) and with ?plantingShared=false, compared with the B-06 comparer (compareParityImages): the shared+// planting must be look-neutral, so a second capture of the per-material planting is the noise floor and the shared one must+// stay inside it. A test-mode build of the campus standalone is required (bun scripts/build-scene.ts --scene foundry-floor+// --mode test --label <l>).+// bun scripts/capture-foundry-planting-parity.ts --build <label> [--tiers high,minimal] [--views campus,pair,canopy,split,bridge,roundabout] [--backend webgl2] [--out <dir>]+// Besides the named campus views, `close-<zone>` views put the camera 22 to 28 m from a plant of that zone (island, avenue, parking,+// windbreak, arrival), where the crowns fill the frame at their finest level: the demanding case for colour and shading.+// Output per tier and view: <tier>-<view>-off.png, -repeat.png (off again), -on.png and -diff.png (the on/off difference x4),+// plus parity.json and parity.md. Pages load from the owned loopback server; nothing here reads time.+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { PNG } from 'pngjs';+import type { Page } from 'puppeteer-core';+import { assertOwnedUrl, launchChrome, serveOwned, waitForReady, waitFrames } from '../packages/scene-kit/src/testing/node';+import { parseCampus } from '../packages/foundry-floor/src/campus/data';+import { campusPlantings, PLANT_SIZES } from '../packages/foundry-floor/src/campus/exterior/planting';+import { sceneOutput } from './build-scene';+import { compareParityImages, type RgbaImage } from './parity-images';++const ROOT = resolve(import.meta.dir, '..'), WIDTH = 1280, HEIGHT = 720, TIMEOUT = 120_000;+const HIDE_UI = '.ks-hud,.ks-help,.ks-credits,.ks-fade,.ks-dev-panel,#page-status{visibility:hidden!important}';+const args = process.argv.slice(2), option = (name: string, fallback: string) => { const at = args.indexOf(name); return at < 0 ? fallback : args[at + 1] ?? fallback; };+const build = option('--build', ''), tiers = option('--tiers', 'high,minimal').split(','), views = option('--views', 'campus,pair,canopy,split,bridge,roundabout,close-island,close-avenue,close-parking,close-windbreak,close-arrival').split(',');+const backend = option('--backend', '') === 'webgl2' ? 'webgl2' : '';+const out = resolve(ROOT, option('--out', '../tmp/drawcalls/wave-b/foundry/parity'));+if (!build) throw new Error('--build <label> is required');++/* eslint-disable @typescript-eslint/no-explicit-any */+const invoke = (page: Page, name: string, ...a: unknown[]) => page.evaluate((n, v) => (window as any).__kilnScene.invoke(n, ...v), name, a);+async function shoot(base: string, owned: ReadonlySet<number>, browser: Awaited<ReturnType<typeof launchChrome>>, tier: string, view: string, shared: boolean): Promise<{ png: RgbaImage; stats: unknown; backend: string | null }> {+ const url = `${base}/?${new URLSearchParams({ freeze: '1', time: '0', capture: '1', tier, plantingShared: String(shared), ...(backend ? { backend } : {}) })}`;+ assertOwnedUrl(url, owned);+ const page = await browser.newPage(); page.setDefaultTimeout(TIMEOUT);+ try {+ await page.setViewport({ width: WIDTH, height: HEIGHT, deviceScaleFactor: 1 });+ await page.emulateMediaFeatures([{ name: 'prefers-reduced-motion', value: 'no-preference' }]);+ await page.goto(url, { waitUntil: 'load', timeout: TIMEOUT }); await waitForReady(page);+ await page.addStyleTag({ content: HIDE_UI });+ await page.waitForFunction(() => (window as any).__kilnScene.invoke('driveTraffic', 1) !== null, { timeout: TIMEOUT, polling: 100 });+ if (view.startsWith('close-')) { const pose = closePose(view.slice(6)); await invoke(page, 'campusPose', pose.position, pose.target, 50); } else await invoke(page, 'campusView', view);+ await waitFrames(page, 40);+ // The orbit eases into the view: wait until two reads 10 frames apart agree.+ for (let i = 0, last = ''; i < 30; i++) { const now = JSON.stringify((await invoke(page, 'campusState') as any).camera); if (now === last) break; last = now; await waitFrames(page, 10); }+ await waitFrames(page, 4);+ const stats = (await invoke(page, 'campusState') as any).vegetation, canvas = await page.$('canvas');+ const png = PNG.sync.read(Buffer.from(await canvas!.screenshot({ type: 'png' })));+ if (png.width !== WIDTH || png.height !== HEIGHT) throw new Error(`Capture is ${png.width}x${png.height}, expected ${WIDTH}x${HEIGHT}`);+ return { png: { width: png.width, height: png.height, data: new Uint8Array(png.data) }, stats, backend: await page.$eval('.ks-root', root => root.getAttribute('data-kiln-backend')) };+ } finally { await page.close().catch(() => {}); }+}+const plants = campusPlantings(parseCampus(readFileSync(resolve(ROOT, 'packages/foundry-floor/data/campus.json'), 'utf8')));+/** Camera 28 m from the first plant of the zone (the island's first conifer, past x = 300 on the avenue), eye 6 m up, looking at its middle, from the campus-centre side (the island's from outside it, 22 m). */+function closePose(zone: string): { position: [number, number, number]; target: [number, number, number] } {+ const p = plants.find(q => q.zone === zone && (zone !== 'island' || q.model === 'tree-conifer-m') && (zone !== 'avenue' || Math.abs(q.x) > 300))!, d = Math.hypot(p.x, p.z) || 1, h = PLANT_SIZES[p.model][1];+ const away = zone === 'island' ? 22 : -28;+ return { position: [p.x + p.x / d * away, 6, p.z + p.z / d * away], target: [p.x, h * 0.45, p.z] };+}+const write = (path: string, image: RgbaImage) => { const png = new PNG({ width: image.width, height: image.height }); png.data = Buffer.from(image.data); writeFileSync(path, PNG.sync.write(png)); };+const exact = (a: RgbaImage, b: RgbaImage) => { let differing = 0, max = 0; for (let i = 0; i < a.data.length; i += 4) { let d = 0; for (let c = 0; c < 3; c++) d = Math.max(d, Math.abs(a.data[i + c]! - b.data[i + c]!)); if (d) { differing++; if (d > max) max = d; } } return { differingPixels: differing, maxChannelDelta: max }; };++mkdirSync(out, { recursive: true });+const dir = sceneOutput('foundry-floor', build, 'test'), hosted = await serveOwned(dir), owned = new Set([hosted.port]), browser = await launchChrome({ workspace: ROOT, name: 'planting-parity', windowSize: [WIDTH, HEIGHT] });+const results: any[] = [];+try {+ for (const tier of tiers) for (const view of views) {+ const off = await shoot(hosted.url, owned, browser, tier, view, false), repeat = await shoot(hosted.url, owned, browser, tier, view, false), on = await shoot(hosted.url, owned, browser, tier, view, true);+ const parity = compareParityImages(off.png, repeat.png, on.png), name = `${tier}-${view}`;+ write(resolve(out, `${name}-off.png`), off.png); write(resolve(out, `${name}-repeat.png`), repeat.png); write(resolve(out, `${name}-on.png`), on.png); write(resolve(out, `${name}-diff.png`), parity.diff);+ const row = { tier, view, backend: on.backend, pass: parity.pass, globalMean: parity.globalMean, noiseGlobalMean: parity.noiseGlobalMean, passingTiles: parity.passingTiles, tiles: parity.tiles.length,+ onVsOff: exact(off.png, on.png), repeatVsOff: exact(off.png, repeat.png), planting: { off: off.stats, on: on.stats } };+ results.push(row); console.log(`${name} (${on.backend}): ${parity.pass ? 'PASS' : 'FAIL'} mean ${parity.globalMean.toExponential(2)} noise ${parity.noiseGlobalMean.toExponential(2)} tiles ${parity.passingTiles}/${parity.tiles.length} differing ${row.onVsOff.differingPixels} (max ${row.onVsOff.maxChannelDelta}), repeat differing ${row.repeatVsOff.differingPixels}`);+ }+} finally { await browser.close(); await hosted.close(); }+writeFileSync(resolve(out, 'parity.json'), JSON.stringify({ build, size: [WIDTH, HEIGHT], results }, null, 1) + '\n');+writeFileSync(resolve(out, 'parity.md'), ['| tier | view | pass | mean luminance delta | repeat noise | tiles passing | pixels differing (on vs off) | max channel delta | pixels differing (repeat vs off) |', '|---|---|---|---|---|---|---|---|---|',+ ...results.map(r => `| ${r.tier} | ${r.view} | ${r.pass ? 'yes' : 'NO'} | ${r.globalMean.toExponential(2)} | ${r.noiseGlobalMean.toExponential(2)} | ${r.passingTiles}/${r.tiles} | ${r.onVsOff.differingPixels} | ${r.onVsOff.maxChannelDelta} | ${r.repeatVsOff.differingPixels} |`)].join('\n') + '\n');+process.exitCode = results.every(r => r.pass) ? 0 : 1;diff --git a/scenes/scripts/check-bundle-hygiene.ts b/scenes/scripts/check-bundle-hygiene.tsindex 1922f0a5..fb02039e 100644--- a/scenes/scripts/check-bundle-hygiene.ts+++ b/scenes/scripts/check-bundle-hygiene.ts@@ -2,7 +2,7 @@ import { existsSync, readFileSync } from 'node:fs';import { join, relative, resolve } from 'node:path';import { filesUnder, printCheck, ROOT, slash, workspaceManifests } from './check-common';-export const DENYLIST = ['__kilnScene', '__kilnProbeOverride', 'DevPanel', 'registerWorkload', 'feedFrameTimes', 'Preview farm activity', 'suite-client', 'createMeasurement', 'sample-case', '#view-quality', 'Look exploration', 'Unknown look option'] as const;+export const DENYLIST = ['__kilnScene', '__kilnProbeOverride', 'DevPanel', 'registerWorkload', 'feedFrameTimes', 'probeFrames', 'sceneSummary', 'probeSystems', 'probeAsset', 'msaaPolicy', 'MSAA discard tripped', 'kiln-render-probe', 'Preview farm activity', 'suite-client', 'createMeasurement', 'sample-case', '#view-quality', 'Look exploration', 'Unknown look option', 'plantingShared', 'bridgeMerge', 'reflectionStandIns', 'shadowOnce', 'shadowRearm'] as const;export interface HygieneHit { file: string; token: string; line: number }export function findHygieneHits(file: string, text: string): HygieneHit[] {return DENYLIST.flatMap(token => {diff --git a/scenes/scripts/check-foundry-counts.ts b/scenes/scripts/check-foundry-counts.tsnew file mode 100644index 00000000..a4271099--- /dev/null+++ b/scenes/scripts/check-foundry-counts.ts@@ -0,0 +1,59 @@+// Foundry Floor X-02 check and baseline recorder (OD-8, D-53): compares a count-probe summary of the scene against the committed+// reference (packages/foundry-floor/fixtures/count-baseline.json) with X-02's rule (draws and triangles ±2% inclusive, pipelines+// at most +5%; scripts/foundry-count-gates.ts), or records that reference from a summary.+// bun scripts/check-foundry-counts.ts --summary <label|path> check an existing probe run (evidence/counts/<label>/summary.json)+// bun scripts/check-foundry-counts.ts --run --build <label> probe a test-mode build (bun scripts/build-scene.ts --scene foundry-floor --mode test --label <l>) at every tier, then check+// bun scripts/check-foundry-counts.ts --record --summary <label|path> --commit <hash> [--source <text>] [--build <label>] [--date <yyyy-mm-dd>] [--out <path>]+// The reference's conditions are the probe's own: 1920x1080, device scale 1, WebGPU, frozen clock, settled frames, one page per+// query group (so the cumulative pipeline cache depends on fixture order; the run is judged on it only under that policy). The exit+// code is 1 when any judged fixture falls outside the rule, a reference fixture is missing or the viewport has another aspect ratio.+import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { runCountProbe, summarize } from './count-probe';+import { checkFoundryCounts, buildFoundryCountBaseline, FOUNDRY_COUNT_BASELINE_PATH, FOUNDRY_COUNT_TIERS, validateFoundryCountBaseline, type FoundryCountBaseline, type FoundryCountRow } from './foundry-count-gates';+import { sceneOutput } from './build-scene';++const ROOT = resolve(import.meta.dir, '..');+const args = process.argv.slice(2), option = (name: string, fallback = '') => { const at = args.indexOf(name); if (at < 0) return fallback; const v = args[at + 1]; if (!v || v.startsWith('--')) throw new Error(`${name} needs a value`); return v; };+interface Summary { label: string; provenance: { builds: Record<string, string[]>; viewports: string[]; freshPage: boolean | null; mixed: boolean }; rows: FoundryCountRow[] }+const summaryPath = (label: string) => { const path = resolve(label); return existsSync(path) && statSync(path).isFile() ? path : resolve(ROOT, 'evidence/counts', label, 'summary.json'); };+const readSummary = (label: string) => JSON.parse(readFileSync(summaryPath(label), 'utf8')) as Summary;+const viewportOf = (s: Summary): [number, number] => { const [w, h] = (s.provenance.viewports[0] ?? '').split('x').map(Number); return [w!, h!]; };++if (args.includes('--record')) {+ const summary = readSummary(option('--summary')), commit = option('--commit'), out = resolve(ROOT, option('--out', FOUNDRY_COUNT_BASELINE_PATH));+ if (summary.provenance.mixed || summary.provenance.viewports.length !== 1) throw new Error('The summary mixes builds or viewports; record from a single run');+ const chunks = summary.provenance.builds['foundry-floor'] ?? []; if (!chunks.length) throw new Error('The summary names no foundry-floor build');+ const build = option('--build', 'draw-after'), buildJson = resolve(sceneOutput('foundry-floor', build, 'test'), 'build.json');+ const built = existsSync(buildJson) ? JSON.parse(readFileSync(buildJson, 'utf8')) as { source?: unknown } : null;+ const baseline = buildFoundryCountBaseline(summary.rows, {+ provenance: { build, commit, chunks: chunks[0]!.split('+'), source: option('--source', built?.source === 'working tree' ? `test build ${build} of the working tree at ${commit}` : `test build ${build}`), tool: 'scripts/check-foundry-counts.ts --record',+ probe: `scripts/count-probe.ts --scenes foundry-floor --what-if none --build ${build} (summary ${summary.label})`, date: option('--date', new Date().toISOString().slice(0, 10)) },+ conditions: { viewport: viewportOf(summary), freshPage: summary.provenance.freshPage === true, clock: 'frozen', backend: 'webgpu', settled: true }, workloads: ['drive'] });+ const problems = validateFoundryCountBaseline(baseline); if (problems.length) throw new Error(problems.join('\n'));+ writeFileSync(out, JSON.stringify(baseline, null, 1) + '\n');+ console.log(`Recorded ${Object.values(baseline.tiers).reduce((n, t) => n + Object.keys(t).length, 0)} rows (${Object.keys(baseline.tiers).join(', ')}) to ${out}`);+ process.exit(0);+}++let label = option('--summary');+if (args.includes('--run')) {+ label = option('--label', 'x02-foundry-floor');+ await runCountProbe({ label, build: option('--build'), scenes: ['foundry-floor'], tiers: [...FOUNDRY_COUNT_TIERS], fixtures: 'all', whatIfs: false, size: [1920, 1080], freshPage: false });+ summarize(label);+}+if (!label) throw new Error('--summary <label|path> or --run --build <label> is required');+const baseline = JSON.parse(readFileSync(resolve(ROOT, option('--baseline', FOUNDRY_COUNT_BASELINE_PATH)), 'utf8')) as FoundryCountBaseline, problems = validateFoundryCountBaseline(baseline);+if (problems.length) throw new Error(`The reference is unusable:\n${problems.join('\n')}`);+const summary = readSummary(label), tiers = option('--tiers', FOUNDRY_COUNT_TIERS.join(',')).split(',');+const result = checkFoundryCounts(baseline, summary.rows, { freshPage: summary.provenance.freshPage, viewport: viewportOf(summary), tiers });+const fmt = (a: number, b: number) => a === b ? `${a}` : `${a} → ${b}`;+console.log(`X-02 Foundry Floor against ${baseline.provenance.build} ${baseline.provenance.commit} (${baseline.provenance.date}): ${result.pass ? 'PASS' : 'FAIL'}; ${result.rows.filter(r => r.judged).length} judged, ${result.rows.filter(r => !r.judged).length} workload, missing ${result.missing.length}, extra ${result.extra.length}; cache ${result.conditions.cacheJudged ? 'judged' : 'not judged (another page policy)'}`);+for (const r of result.rows) {+ const row = summary.rows.find(x => x.tier === r.tier && x.fixture === r.fixture)!, ref = baseline.tiers[r.tier]![r.fixture]!;+ console.log(`${r.pass ? (r.judged ? 'ok ' : 'info') : 'FAIL'} ${r.tier} ${r.fixture}: draws ${fmt(ref.drawCalls, row.draws)}, triangles ${fmt(ref.triangles, row.triangles)}, pipelines ${fmt(ref.pipelines, row.pipelinesUsed)}${r.cache ? `, cache ${fmt(r.cache.reference, r.cache.observed)}` : ''}${r.judged ? '' : ' (workload, not judged)'}`);+}+for (const m of result.missing) console.log(`FAIL missing from the run: ${m}`);+for (const e of result.extra) console.log(`note not in the reference: ${e}`);+for (const d of result.conditions.differences) console.log(`FAIL condition: ${d}`);+process.exitCode = result.pass ? 0 : 1;diff --git a/scenes/scripts/count-probe-gpu.ts b/scenes/scripts/count-probe-gpu.tsnew file mode 100644index 00000000..5cf4e66c--- /dev/null+++ b/scenes/scripts/count-probe-gpu.ts@@ -0,0 +1,70 @@+// GPU-level half of the count probe (S1): installed with evaluateOnNewDocument before any page script, it records every+// render pass three encodes while armed, stamped with the scene clock's frame (`__kilnScene.frame`), so the Node runner+// can join it to the JS-level probe by frame and by RenderContext id (three labels its command encoders+// 'renderContext_<id>', WebGPUBackend.js:1080). Per pass: attachments with size, samples, format, load and store ops and+// resolve; direct draws (the four draw variants); setPipeline calls and distinct pipelines; executeBundles and the+// draws inside the bundles (three's mipmap passes, invisible to renderer.info). Uncaptured device errors are kept.+// Counts only: no clock is read. The join itself (crossCheck) and the record types live in scene-kit testing/probe-report.ts.+import type { Page } from 'puppeteer-core';+import type { GpuFrame } from '../packages/scene-kit/src/testing/probe-report';+export type { GpuAttachment, GpuFrame, GpuPass } from '../packages/scene-kit/src/testing/probe-report';++/** Self-contained: serialized into the page. */+export function installGpuCounters(): void {+ const w = window as any; // eslint-disable-line @typescript-eslint/no-explicit-any+ if (w.__kilnGpuProbe || !w.GPUCommandEncoder) return;+ const G: any = w.__kilnGpuProbe = { armed: false, keep: 32, frames: {}, errors: [] }; // eslint-disable-line @typescript-eslint/no-explicit-any+ const views = new WeakMap<object, object>(), bundleDraws = new WeakMap<object, number>(), encoderDraws = new WeakMap<object, number>();+ const frameNow = () => { try { const f = w.__kilnScene?.frame; return typeof f === 'number' ? f : -1; } catch { return -1; } };+ const slot = () => {+ const f = frameNow(), entry = G.frames[f] ??= { passes: [], copies: 0, submits: 0 };+ const keys = Object.keys(G.frames).map(Number).sort((a, b) => a - b);+ while (keys.length > G.keep) delete G.frames[keys.shift()!];+ return { f, entry };+ };+ const wrap = (proto: any, name: string, make: (original: any) => any) => { const original = proto?.[name]; if (typeof original === 'function') proto[name] = make(original); }; // eslint-disable-line @typescript-eslint/no-explicit-any+ wrap(w.GPUTexture.prototype, 'createView', original => function (this: any, d?: any) { // eslint-disable-line @typescript-eslint/no-explicit-any+ const view = original.call(this, d);+ views.set(view, { w: this.width, h: this.height, samples: this.sampleCount, format: this.format, mip: d?.baseMipLevel ?? 0 });+ return view;+ });+ wrap(w.GPUCommandEncoder.prototype, 'beginRenderPass', original => function (this: any, d: any) { // eslint-disable-line @typescript-eslint/no-explicit-any+ const pass = original.call(this, d);+ if (G.armed) {+ const { f, entry } = slot(), z = d?.depthStencilAttachment;+ const color = [...(d?.colorAttachments ?? [])].filter(Boolean).map((c: any) => ({ ...(views.get(c.view) ?? {}), loadOp: c.loadOp, storeOp: c.storeOp, resolve: !!c.resolveTarget })); // eslint-disable-line @typescript-eslint/no-explicit-any+ const rec = { frame: f, encoder: String(this.label ?? ''), color, depth: z ? { ...(views.get(z.view) ?? {}), depthLoadOp: z.depthLoadOp, depthStoreOp: z.depthStoreOp, stencilLoadOp: z.stencilLoadOp, stencilStoreOp: z.stencilStoreOp } : null,+ draws: 0, setPipeline: 0, pipelines: new Set(), bundles: 0, bundledDraws: 0 };+ entry.passes.push(rec); pass.__kilnPass = rec;+ }+ return pass;+ });+ wrap(w.GPUCommandEncoder.prototype, 'copyTextureToTexture', original => function (this: any, ...args: any[]) { if (G.armed) slot().entry.copies++; return original.apply(this, args); }); // eslint-disable-line @typescript-eslint/no-explicit-any+ wrap(w.GPUQueue.prototype, 'submit', original => function (this: any, ...args: any[]) { if (G.armed) slot().entry.submits++; return original.apply(this, args); }); // eslint-disable-line @typescript-eslint/no-explicit-any+ const P = w.GPURenderPassEncoder.prototype, B = w.GPURenderBundleEncoder?.prototype;+ for (const name of ['draw', 'drawIndexed', 'drawIndirect', 'drawIndexedIndirect']) {+ wrap(P, name, original => function (this: any, ...args: any[]) { if (this.__kilnPass) this.__kilnPass.draws++; return original.apply(this, args); }); // eslint-disable-line @typescript-eslint/no-explicit-any+ if (B) wrap(B, name, original => function (this: any, ...args: any[]) { encoderDraws.set(this, (encoderDraws.get(this) ?? 0) + 1); return original.apply(this, args); }); // eslint-disable-line @typescript-eslint/no-explicit-any+ }+ if (B) wrap(B, 'finish', original => function (this: any, ...args: any[]) { const bundle = original.apply(this, args); bundleDraws.set(bundle, encoderDraws.get(this) ?? 0); return bundle; }); // eslint-disable-line @typescript-eslint/no-explicit-any+ wrap(P, 'setPipeline', original => function (this: any, pipeline: any) { const r = this.__kilnPass; if (r) { r.setPipeline++; r.pipelines.add(pipeline); } return original.call(this, pipeline); }); // eslint-disable-line @typescript-eslint/no-explicit-any+ wrap(P, 'executeBundles', original => function (this: any, bundles: any) { // eslint-disable-line @typescript-eslint/no-explicit-any+ const r = this.__kilnPass;+ if (r) for (const bundle of bundles ?? []) { r.bundles++; r.bundledDraws += bundleDraws.get(bundle) ?? 0; }+ return original.call(this, bundles);+ });+ wrap(w.GPUAdapter?.prototype, 'requestDevice', original => async function (this: any, ...args: any[]) { // eslint-disable-line @typescript-eslint/no-explicit-any+ const device = await original.apply(this, args);+ device.addEventListener?.('uncapturederror', (event: any) => { if (G.errors.length < 50) G.errors.push(String(event?.error?.message ?? event).slice(0, 400)); }); // eslint-disable-line @typescript-eslint/no-explicit-any+ return device;+ });+}++export const armGpu = (page: Page, armed: boolean) => page.evaluate(on => { const g = (window as any).__kilnGpuProbe; if (g) { g.armed = on; if (on) g.frames = {}; } return !!g; }, armed); // eslint-disable-line @typescript-eslint/no-explicit-any+/** The recorded passes of one frame with pipeline sets reduced to counts, plus device errors so far. */+export function readGpuFrame(page: Page, frame: number): Promise<{ frame: GpuFrame | null; errors: string[] }> {+ return page.evaluate(f => {+ const g = (window as any).__kilnGpuProbe, entry = g?.frames[f]; // eslint-disable-line @typescript-eslint/no-explicit-any+ return { frame: entry ? { copies: entry.copies, submits: entry.submits, passes: entry.passes.map((p: any) => ({ ...p, pipelines: p.pipelines.size })) } : null, errors: g ? [...g.errors] : [] }; // eslint-disable-line @typescript-eslint/no-explicit-any+ }, frame);+}diff --git a/scenes/scripts/count-probe-settled.ts b/scenes/scripts/count-probe-settled.tsnew file mode 100644index 00000000..a73a9827--- /dev/null+++ b/scenes/scripts/count-probe-settled.ts@@ -0,0 +1,80 @@+// S5 (OD-9) count probe for the Farm's cached sun shadow: scripts/count-probe.ts with every probe (base, what-ifs and the+// return check) taken only once the cache has settled, so a probe never stops on a run of identical frames in which casters+// that moved during a fixture (a door, the drive, the walk) are still in the live map. A settled frame has no shadow+// pass; the static map's cost is reported separately: per fixture the static map is re-armed (test hook shadowRearm) and the+// one frame that redraws it is probed on its own. Without a cache (?shadowCache=0, minimal) it runs exactly as count-probe.+// bun scripts/count-probe-settled.ts --label <l> [--build <label>] [--tiers …] [--fixtures all|id,…] [--what-if none|standard]+// [--query 'k=v&…'] [--compare <baseline summary.json>] [--fresh-page] [--size 1920x1080]+// Output: as count-probe (records carry base.settle.frames), plus evidence/counts/<label>/farm-static-shadow.json and a section+// appended to summary.md. Counts only.+import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';+import { resolve } from 'node:path';+import type { Page } from 'puppeteer-core';+import { runCountProbe, summarize } from './count-probe';+import { FARM_FIXTURES } from './scene-fixtures';++const ROOT = resolve(import.meta.dir, '..'), SETTLE_FRAMES = 900, QUIET = 45;+interface StaticRow { tier: string; fixture: string; settle: { frames: number; live: number; pending: number; unsettled?: true }; staticRender: { draws: number; triangles: number; pipelines: number; label: string } | null; live: number; stats: unknown }+const rows: StaticRow[] = [];+/**+ * Wraps the page's probe once: each probe first waits until counts().shadow.pendingSettle is 0 (or there is no cache). The+ * probe's clock is frozen and ambient life is off, and the kit ignores sub-micrometre drift, so every fixture settles; the+ * tractor coasts on the frame's own delta (its damped speed never reaches 0) for a few hundred frames after a drive. Only a+ * caster still moving after SETTLE_FRAMES falls back to the cache's counters held for QUIET frames, marked `unsettled`. (A+ * quiet run alone is not settled: the coasting tractor holds the counters still while it creeps, then settles mid-what-if,+ * review RF-3.)+ */+async function installSettle(page: Page) {+ await page.evaluate((limit, quiet) => {+ const s = (window as any).__kilnScene; if (s.__settledProbe) return; // eslint-disable-line @typescript-eslint/no-explicit-any+ const probe = s.probeFrames, settle = async () => {+ let last = '', same = 0;+ for (let i = 0; ; i++) {+ const c = s.invoke('counts')?.shadow; if (!c || c.pendingSettle === 0) return { frames: i, live: c?.liveCasters ?? 0, pending: 0 };+ const key = [c.staticRenders, c.liveCasters, c.invalidations, c.pendingSettle].join('|');+ if (key !== last) { last = key; same = 0; } else same++;+ if (i >= limit) { if (same >= quiet) return { frames: i, live: c.liveCasters, pending: c.pendingSettle, unsettled: true }; if (i >= limit + 4 * quiet) break; }+ await s.waitFrames(1);+ }+ throw new Error(`Cached shadow did not settle within ${limit} frames`);+ };+ s.__settledProbe = { probe, settle };+ s.probeFrames = async (o: unknown) => { const settled = await settle(); return { ...await probe(o), settle: settled }; };+ }, SETTLE_FRAMES, QUIET);+}+/** One static re-render: re-arm, then probe exactly the next frame with the unwrapped probe. */+async function staticRender(page: Page) {+ return page.evaluate(async () => {+ const s = (window as any).__kilnScene, w = s.__settledProbe, settled = await w.settle(); // eslint-disable-line @typescript-eslint/no-explicit-any+ if (!s.invoke('shadowRearm')) return { settled, pass: null, live: 0, stats: null };+ const r = await w.probe({ frames: 1, stableFrames: 1, maxFrames: 1 }), pass = r.passes.find((p: any) => /sun static/.test(p.label)); // eslint-disable-line @typescript-eslint/no-explicit-any+ const live = r.passes.filter((p: any) => /sun live/.test(p.label)).reduce((n: number, p: any) => n + p.draws, 0); // eslint-disable-line @typescript-eslint/no-explicit-any+ await w.settle();+ return { settled, pass: pass ? { draws: pass.draws, triangles: pass.triangles, pipelines: pass.pipelines, label: pass.label } : null, live, stats: s.invoke('counts')?.shadow ?? null };+ });+}+for (const fixture of FARM_FIXTURES.fixtures) {+ const enter = fixture.enter;+ fixture.enter = async page => {+ const value = await enter(page); await installSettle(page);+ const tier = new URL(page.url()).searchParams.get('tier') ?? '?', r = await staticRender(page);+ rows.push({ tier, fixture: fixture.id, settle: r.settled, staticRender: r.pass, live: r.live, stats: r.stats });+ return value;+ };+}++if (import.meta.main) {+ const args = process.argv.slice(2), option = (name: string, fallback: string) => { const at = args.indexOf(name); return at < 0 ? fallback : args[at + 1] ?? fallback; };+ const label = option('--label', ''); if (!/^[a-z0-9-]+$/.test(label)) throw new Error('--label <lowercase-label> is required');+ const fixtures = option('--fixtures', 'all'), tiers = option('--tiers', 'minimal,economy,balanced,high').split(',') as ('minimal' | 'economy' | 'balanced' | 'high')[];+ await runCountProbe({ label, build: option('--build', label), scenes: ['farm'], tiers, fixtures: fixtures === 'all' ? 'all' : fixtures.split(','), whatIfs: option('--what-if', 'standard') === 'standard',+ size: option('--size', '1920x1080').split('x').map(Number) as [number, number], freshPage: args.includes('--fresh-page'), ...(args.includes('--query') ? { query: Object.fromEntries(new URLSearchParams(option('--query', ''))) } : {}) });+ const dir = resolve(ROOT, 'evidence/counts', label); mkdirSync(dir, { recursive: true });+ writeFileSync(resolve(dir, 'farm-static-shadow.json'), JSON.stringify({ label, rule: `Settled first (pendingSettle 0; only after ${SETTLE_FRAMES} frames, the cache's counters still for ${QUIET} frames, marked unsettled); then one re-armed static render probed alone. live = live-map draws in that frame.`, rows }, null, 1) + '\n');+ console.log(JSON.stringify(summarize(label, args.includes('--compare') ? option('--compare', '') : undefined)));+ const md = ['', '## farm · cached sun shadow: settle state and one static re-render', '',+ `Each probe waits until the cache is settled: pendingSettle 0 (the live map empty, no map armed); only a caster still moving after ${SETTLE_FRAMES} frames falls back to the cache's counters still for ${QUIET} frames (marked unsettled, live casters listed). The static map re-renders only on events (a caster settling, a re-arm); here it is re-armed once and that frame is probed alone.`, '',+ '| Tier | Fixture | Frames waited | Live casters (pending) | Static render draws | Triangles | Pipelines | Live draws that frame |', '|---|---|---|---|---|---|---|---|',+ ...rows.map(r => `| ${r.tier} | ${r.fixture} | ${r.settle.frames} | ${r.settle.live} (${r.settle.pending})${r.settle.unsettled ? ' unsettled' : ''} | ${r.staticRender?.draws ?? '-'} | ${r.staticRender?.triangles.toLocaleString('en-US') ?? '-'} | ${r.staticRender?.pipelines ?? '-'} | ${r.live} |`), ''];+ appendFileSync(resolve(dir, 'summary.md'), md.join('\n'));+}diff --git a/scenes/scripts/count-probe.ts b/scenes/scripts/count-probe.tsnew file mode 100644index 00000000..1d9955a7--- /dev/null+++ b/scenes/scripts/count-probe.ts@@ -0,0 +1,271 @@+// S1 count probe runner (OD-17): per scene, tier and named view or workload, draws per render pass, pipelines used,+// triangles, attribution by system and asset, and count-only what-ifs, from a test-mode standalone built by+// scripts/build-scene.ts. The page half is the kit's `__kilnScene.probeFrames` (scene-kit testing/probe.ts); the GPU+// half (count-probe-gpu.ts) counts the encoder's passes, draws, pipelines and load/store ops and is joined per frame.+// bun scripts/count-probe.ts --label <l> [--build <label>] [--scenes farm,foundry-floor,golden-gate]+// [--tiers minimal,economy,balanced,high] [--fixtures all|id,…] [--what-if none|standard] [--size 1920x1080]+// [--fresh-page] [--compare <baseline summary.json or evidence label>] [--summary-only]+// Output: evidence/counts/<label>/<scene>/<tier>/<fixture>.json, scene-summary.json per scene and tier, and+// summary.json + summary.md (plus levers.md appended when present). Each record names its build (code chunks and+// source) and run (viewport, fresh page or shared), and summary.json carries that provenance; --compare checks pipelines+// only between two fresh-page runs. Counts only: nothing here reads or reports time.+// Ports 4400-4499 are try-bound by serveOwned; the runner closes every page, server and browser it starts.+import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { resolve } from 'node:path';+import type { BrowserContext, Page } from 'puppeteer-core';+import { assertOwnedUrl, launchChrome, serveOwned, waitForReady } from '../packages/scene-kit/src/testing/node';+import { diffCounts, PASS_KINDS } from '../packages/scene-kit/src/testing/probe-core';+import type { DroppedCaster, ProbeResult, ProbeWhatIf } from '../packages/scene-kit/src/testing/probe';+import { compact, crossCheck, pipelinesComparable, runProvenance, standardWhatIfs, type GpuFrame, type RunProvenance } from '../packages/scene-kit/src/testing/probe-report';+import { sceneOutput, type SceneId } from './build-scene';+import { armGpu, installGpuCounters, readGpuFrame } from './count-probe-gpu';+import { SCENE_FIXTURES, type ProbeFixture } from './scene-fixtures';+import { compareStaticRendererCounts } from './farm-count-gates';++// The page cancels its own probe (restoring the what-if) before puppeteer's 180 s protocol timeout would give up on it.+const ROOT = resolve(import.meta.dir, '..'), TIERS = ['minimal', 'economy', 'balanced', 'high'] as const, TIMEOUT = 180_000, PROBE_TIMEOUT = 150_000;+type Tier = typeof TIERS[number];+interface WhatIfRun { name: string; whatIf: ProbeWhatIf; stable: boolean; frame: number; totals: ProbeResult['totals']; affected: Record<string, number>; dropped?: DroppedCaster[]; delta: Record<string, unknown>; error?: string }+export interface BuildIdentity { label: string; chunks: string[]; source: unknown }+export interface FixtureRecord {+ scene: SceneId; tier: Tier; fixture: { id: string; hudLabel: string | null }; url: string; build?: BuildIdentity; run?: { viewport: [number, number]; freshPage: boolean; query?: Record<string, string> }; base: ProbeResult & { tier?: unknown };+ gpu: { passes: GpuFrame['passes']; check: ReturnType<typeof crossCheck>; errors: string[] } | null; whatIfs: WhatIfRun[];+ returned: { equal: boolean; totals: ProbeResult['totals'] } | null; messages: { type: string; text: string }[]; error?: string;+ systems?: string[]; census?: Census;+}+interface Census { meshes: number; visibleMeshes: number; casters: number; instanced: number; instances: number; transparent: number; skinned: number; triangles: number; lights: { name: string; type: string; castShadow: boolean; mapSize: number[]; texelWorld: number | null }[]; bySystem: Record<string, { visibleMeshes: number; casters: number; triangles: number }> }+async function probe(page: Page, options: Record<string, unknown>): Promise<ProbeResult> {+ return page.evaluate(o => (window as any).__kilnScene.probeFrames(o), { ...options, timeoutMs: PROBE_TIMEOUT }) as Promise<ProbeResult>; // eslint-disable-line @typescript-eslint/no-explicit-any+}+const PAGE_CSS = 'body>header,body>footer{display:none!important}';+async function openPage(browser: BrowserContext, url: string, owned: ReadonlySet<number>, size: [number, number], messages: { type: string; text: string }[]): Promise<Page> {+ const page = await browser.newPage(); page.setDefaultTimeout(TIMEOUT);+ page.on('console', m => { if (m.type() === 'error' || m.type() === 'warn') messages.push({ type: m.type(), text: m.text().slice(0, 400) }); });+ page.on('pageerror', e => messages.push({ type: 'pageerror', text: String(e).slice(0, 400) }));+ await page.setViewport({ width: size[0], height: size[1], deviceScaleFactor: 1 });+ await page.evaluateOnNewDocument(installGpuCounters);+ // Farm has no ?capture=1; every page hides its header and footer so the canvas fills the viewport.+ await page.evaluateOnNewDocument(css => { const add = () => { const s = document.createElement('style'); s.textContent = css; document.head.append(s); }; if (document.head) add(); else document.addEventListener('DOMContentLoaded', add, { once: true }); }, PAGE_CSS);+ assertOwnedUrl(url, owned);+ await page.goto(url, { waitUntil: 'load', timeout: TIMEOUT }); await waitForReady(page);+ const backend = await page.$eval('.ks-root', root => root.getAttribute('data-kiln-backend'));+ if (backend !== 'webgpu') throw new Error(`Expected the WebGPU backend, got ${backend}`);+ return page;+}++type RecordContext = Pick<FixtureRecord, 'build' | 'run'>;+async function runFixture(page: Page, scene: SceneId, tier: Tier, fixture: ProbeFixture, url: string, whatIfs: boolean, messages: { type: string; text: string }[], stamp: RecordContext): Promise<FixtureRecord> {+ const record: FixtureRecord = { scene, tier, fixture: { id: fixture.id, hudLabel: fixture.hudLabel }, url, ...stamp, base: null as never, gpu: null, whatIfs: [], returned: null, messages };+ await fixture.enter(page);+ // Systems and the census are read per fixture: a place change (the Foundry fab) brings a different world.+ const systems = record.systems = await page.evaluate(() => Object.keys((window as any).__kilnScene.invoke('probeSystems') ?? {})) as string[]; // eslint-disable-line @typescript-eslint/no-explicit-any+ record.census = await page.evaluate(() => (window as any).__kilnScene.sceneSummary()) as Census; // eslint-disable-line @typescript-eslint/no-explicit-any+ await armGpu(page, true);+ record.base = await probe(page, { frames: 8, stableFrames: 3, maxFrames: 900, objects: 12 });+ const gpu = await readGpuFrame(page, record.base.frame);+ await armGpu(page, false);+ if (gpu.frame) record.gpu = { passes: gpu.frame.passes, check: crossCheck(gpu.frame, record.base.passes), errors: gpu.errors };+ if (whatIfs) {+ const base = compact(record.base);+ for (const w of standardWhatIfs(record.base, systems)) {+ try {+ const r = await probe(page, { frames: 6, stableFrames: 3, maxFrames: 600, whatIf: w.whatIf });+ record.whatIfs.push({ name: w.name, whatIf: w.whatIf, stable: r.stable, frame: r.frame, totals: r.totals, affected: r.whatIf.affected, ...(r.whatIf.dropped ? { dropped: r.whatIf.dropped } : {}), delta: diffCounts(base, compact(r)) });+ } catch (error) { record.whatIfs.push({ name: w.name, whatIf: w.whatIf, stable: false, frame: -1, totals: null as never, affected: {}, delta: {}, error: String(error) }); }+ }+ const again = await probe(page, { frames: 6, stableFrames: 3, maxFrames: 900 });+ record.returned = { equal: JSON.stringify(compact(again)) === JSON.stringify(base), totals: again.totals };+ }+ await fixture.exit?.(page);+ return record;+}++const evidence = (label: string, ...parts: string[]) => resolve(ROOT, 'evidence/counts', label, ...parts);+const writeJson = (path: string, value: unknown) => { mkdirSync(resolve(path, '..'), { recursive: true }); writeFileSync(path, JSON.stringify(value, null, 1) + '\n'); };++export async function runCountProbe(o: { label: string; build: string; scenes: SceneId[]; tiers: Tier[]; fixtures: string[] | 'all'; whatIfs: boolean; size: [number, number]; freshPage: boolean; query?: Record<string, string> }) {+ const browser = await launchChrome({ workspace: ROOT, name: 'count-probe', windowSize: o.size }), log: string[] = [];+ try {+ for (const scene of o.scenes) {+ const table = SCENE_FIXTURES[scene], dir = sceneOutput(scene, o.build, 'test');+ if (!existsSync(resolve(dir, 'index.html'))) throw new Error(`No test build at ${dir}; run scripts/build-scene.ts --scene ${scene} --mode test --label ${o.build}`);+ const built = existsSync(resolve(dir, 'build.json')) ? JSON.parse(readFileSync(resolve(dir, 'build.json'), 'utf8')) as { chunks: { name: string }[]; source?: unknown } : null;+ // Every record names the build it measured (code chunks are content-hashed) and the viewport and page policy.+ const stamp: RecordContext = { ...(built ? { build: { label: o.build, chunks: built.chunks.map(c => c.name).sort(), source: built.source ?? null } } : {}), run: { viewport: o.size, freshPage: o.freshPage, ...(o.query ? { query: o.query } : {}) } };+ // Scenes reuse the same port one after another and share asset paths (assets/pack.json): one browser context per+ // scene keeps one scene's cache out of the next.+ const hosted = await serveOwned(dir), owned = new Set([hosted.port]), context = await browser.createBrowserContext();+ try {+ for (const tier of o.tiers) {+ const chosen = table.fixtures.filter(f => o.fixtures === 'all' || o.fixtures.includes(f.id));+ const groups: ProbeFixture[][] = [];+ for (const f of chosen) { const last = groups.at(-1); if (!o.freshPage && last && JSON.stringify(last[0]!.query ?? null) === JSON.stringify(f.query ?? null)) last.push(f); else groups.push([f]); }+ let summarized = false;+ for (const group of groups) {+ const query = new URLSearchParams({ ...(group[0]!.query ?? table.query), ...o.query, tier }), url = `${hosted.url}/?${query}`, messages: { type: string; text: string }[] = [];+ let page: Page | null = null;+ try {+ page = await openPage(context, url, owned, o.size, messages);+ await table.prepare(page);+ if (!summarized) { writeJson(evidence(o.label, scene, tier, 'scene-summary.json'), { scene, tier, url, summary: await page.evaluate(() => (window as any).__kilnScene.sceneSummary()), tierState: await page.evaluate(() => (window as any).__kilnScene.tierState()) }); summarized = true; } // eslint-disable-line @typescript-eslint/no-explicit-any+ for (const fixture of group) {+ let record: FixtureRecord;+ try { record = await runFixture(page, scene, tier, fixture, url, o.whatIfs, messages.splice(0), stamp); }+ catch (error) { record = { scene, tier, fixture: { id: fixture.id, hudLabel: fixture.hudLabel }, url, ...stamp, base: null as never, gpu: null, whatIfs: [], returned: null, messages: messages.splice(0), error: String((error as Error)?.stack ?? error).slice(0, 2000) }; }+ writeJson(evidence(o.label, scene, tier, `${fixture.id}.json`), record);+ const t = record.base?.totals, line = record.error ? `${scene} ${tier} ${fixture.id}: ERROR ${record.error.split('\n')[0]}`+ : `${scene} ${tier} ${fixture.id}: draws ${t.draws} (${PASS_KINDS.filter(k => t.byKind[k]).map(k => `${k} ${t.byKind[k]!.draws}`).join(', ')}) pipelines ${t.pipelinesUsed} triangles ${t.triangles} stable ${record.base.stable} gpu=js ${record.gpu?.check.equal ?? 'n/a'} what-ifs ${record.whatIfs.length} returned ${record.returned?.equal ?? 'n/a'}`;+ console.log(line); log.push(line);+ }+ } catch (error) {+ const line = `${scene} ${tier} [${group.map(f => f.id).join(',')}]: PAGE ERROR ${String(error).split('\n')[0]}`; console.log(line); log.push(line);+ for (const fixture of group) if (!existsSync(evidence(o.label, scene, tier, `${fixture.id}.json`))) writeJson(evidence(o.label, scene, tier, `${fixture.id}.json`), { scene, tier, fixture: { id: fixture.id, hudLabel: fixture.hudLabel }, url, ...stamp, base: null, gpu: null, whatIfs: [], returned: null, messages, error: String((error as Error)?.stack ?? error).slice(0, 2000) });+ } finally { await page?.close().catch(() => {}); }+ }+ }+ } finally { await context.close(); await hosted.close(); }+ }+ } finally { await browser.close(); }+ return log;+}++// ---------- summary ----------+const SUMMARY_KINDS = ['main', 'shadow', 'reflection'] as const;+const other = (t: ProbeResult['totals']) => PASS_KINDS.filter(k => !(SUMMARY_KINDS as readonly string[]).includes(k)).reduce((n, k) => n + (t.byKind[k]?.draws ?? 0), 0);+const LOOK_RISK: Record<string, string> = {+ 'freeze-shadow': 'none while nothing moves; movers need the live map (OD-9)',+ 'casters-under-300-triangles': 'small shadow changes (OD-4); thin limbs can lose shadow',+ 'casters-under-2-texels': 'lowest: sub-2-texel casters barely resolve in the map',+ 'skip-reflection': 'bound only: removes the reflection; stand-ins or cadence recover part of it',+ hide: 'bound only: the lever is a look-neutral merge or stand-in of that system',+};+function readRecords(label: string): FixtureRecord[] {+ const out: FixtureRecord[] = [], root = evidence(label);+ for (const scene of readdirSync(root, { withFileTypes: true }).filter(d => d.isDirectory())) for (const tier of TIERS) {+ const dir = resolve(root, scene.name, tier); if (!existsSync(dir)) continue;+ for (const file of readdirSync(dir).filter(f => f.endsWith('.json') && f !== 'scene-summary.json')) out.push(JSON.parse(readFileSync(resolve(dir, file), 'utf8')));+ }+ return out;+}+const fixtureOrder = (scene: SceneId) => SCENE_FIXTURES[scene].fixtures.map(f => f.id);+const desc = (a: { samples?: number; format?: string } | null | undefined, load?: string, store?: string, resolveTarget?: boolean) => a ? `${a.samples ?? 1}x ${a.format ?? '?'} ${load}/${store}${resolveTarget ? ' +resolve' : ''}` : '-';++/** The `--compare` baseline: a summary.json path (relative to the working directory) or a label under evidence/counts. */+export function baselineSummary(compareWith: string): string {+ const path = resolve(compareWith);+ return existsSync(path) && statSync(path).isFile() ? path : evidence(compareWith, 'summary.json');+}+export function summarize(label: string, compareWith?: string) {+ const records = readRecords(label), scenes = [...new Set(records.map(r => r.scene))].sort();+ const rows = records.filter(r => r.base).map(r => ({+ scene: r.scene, tier: r.tier, fixture: r.fixture.id, hudLabel: r.fixture.hudLabel, stable: r.base.stable, stableAfter: r.base.stableAfter, frame: r.base.frame,+ draws: r.base.totals.draws, byKind: Object.fromEntries(Object.entries(r.base.totals.byKind).map(([k, v]) => [k, { passes: v!.passes, draws: v!.draws, triangles: v!.triangles, pipelines: v!.pipelines }])),+ pipelinesUsed: r.base.totals.pipelinesUsed, pipelineCache: r.base.pipelineCache, programs: r.base.programs, memory: { geometries: r.base.info.memory.geometries ?? 0, textures: r.base.info.memory.textures ?? 0 }, triangles: r.base.totals.triangles, drawingBuffer: r.base.drawingBuffer,+ bySystem: Object.fromEntries(Object.entries(r.base.bySystem).sort((a, b) => b[1].draws - a[1].draws).map(([k, v]) => [k, { draws: v.draws, triangles: v.triangles, byKind: v.byKind }])),+ topAssets: Object.entries(r.base.byAsset).sort((a, b) => b[1].draws - a[1].draws).slice(0, 8).map(([k, v]) => ({ asset: k, draws: v.draws, triangles: v.triangles })),+ gpu: r.gpu ? { equal: r.gpu.check.equal, jsDraws: r.gpu.check.jsDraws, gpuDraws: r.gpu.check.gpuDraws, passes: r.gpu.check.gpuPasses, split: r.gpu.check.splitContexts, otherEncoders: r.gpu.check.otherEncoders, bundledDraws: r.gpu.check.bundledDraws, copies: r.gpu.check.copies, errors: r.gpu.errors.length,+ ops: r.gpu.passes.filter(p => /^renderContext_/.test(p.encoder)).map(p => { const js = r.base.passes.find(x => `renderContext_${x.id}` === p.encoder); return { kind: js?.kind ?? '?', color: p.color.map(c => desc(c, c.loadOp, c.storeOp, c.resolve)).join(', '), depth: p.depth ? desc(p.depth, p.depth.depthLoadOp, p.depth.depthStoreOp) : '-' }; }) } : null,+ whatIfs: Object.fromEntries(r.whatIfs.map(w => [w.name, w.error ? { error: w.error } : { draws: (w.delta as { draws: number }).draws, triangles: (w.delta as { triangles: number }).triangles, pipelines: (w.delta as { pipelinesUsed: number }).pipelinesUsed, byKind: Object.fromEntries(Object.entries((w.delta as { byKind: Record<string, { draws: number }> }).byKind ?? {}).map(([k, v]) => [k, v.draws])), stable: w.stable, affected: w.affected }])),+ returned: r.returned?.equal ?? null, messages: r.messages.length,+ }));+ const errors = records.filter(r => r.error).map(r => ({ scene: r.scene, tier: r.tier, fixture: r.fixture.id, error: r.error!.split('\n')[0] }));+ const provenance = runProvenance(records), before = compareWith ? JSON.parse(readFileSync(baselineSummary(compareWith), 'utf8')) as { rows: CountRow[]; provenance?: RunProvenance } : null;+ const comparison = before ? compareRows(rows, before.rows, pipelinesComparable(before.provenance, provenance)) : null;+ writeJson(evidence(label, 'summary.json'), { label, provenance, rows, errors, comparison });+ const builds = [...new Map(records.filter(r => r.build).map(r => [`${r.scene} ${r.build!.chunks.join('+')}`, r])).values()].map(r => {+ const source = r.build!.source as { commit?: string; overlay?: unknown[] } | null;+ return `${r.scene} ${r.build!.chunks.join(', ')} (build ${r.build!.label}${source?.commit ? `, ${source.commit.slice(0, 7)} plus ${source.overlay?.length ?? 0} overlay files` : ''})`;+ });+ const md: string[] = [`# Count probe ${label}: per-scene draw diagnosis`, '',+ `Test-mode standalones built from source (scripts/build-scene.ts), headless Chrome, WebGPU, frozen scene clock, device scale 1. Counts only: draws, triangles and pipelines, never timings. Each row is one settled frame (three identical frames in a row, no draw skipped for a compiling pipeline). "Other" is the output-quad pass plus any off-screen render. Pipelines are those bound in that frame. The GPU column checks that the encoder's renderContext draws equal the JS-level draws of the same frame.`, '',+ `Provenance: ${builds.join('; ') || 'builds not recorded'}. Viewport ${provenance.viewports.join(', ')}; ${provenance.freshPage === true ? 'one fresh page per fixture' : provenance.freshPage === false ? 'fixtures with the same query share a page, so the cumulative pipeline cache depends on fixture order and is not compared' : 'page policy mixed or not recorded'}.${provenance.mixed ? ' **Mixed provenance: records come from more than one build, viewport or page policy.**' : ''}`, '',+ `Records: ${records.length} fixtures, ${rows.length} probed, ${errors.length} failed. Probes stable: ${rows.filter(r => r.stable).length}/${rows.length}. GPU = JS: ${rows.filter(r => r.gpu?.equal).length}/${rows.filter(r => r.gpu).length}. Baseline returned after what-ifs: ${rows.filter(r => r.returned).length}/${rows.filter(r => r.returned !== null).length}.`, ''];+ for (const scene of scenes) {+ const order = fixtureOrder(scene), sceneRows = rows.filter(r => r.scene === scene).sort((a, b) => TIERS.indexOf(a.tier) - TIERS.indexOf(b.tier) || order.indexOf(a.fixture) - order.indexOf(b.fixture));+ md.push(`## ${scene}`, '');+ for (const tier of TIERS) {+ // One census line per distinct world in this tier (the Foundry fab differs from the campus).+ let previous = '';+ for (const r of records.filter(x => x.scene === scene && x.tier === tier && x.census).sort((a, b) => fixtureOrder(scene).indexOf(a.fixture.id) - fixtureOrder(scene).indexOf(b.fixture.id))) {+ const s = r.census!, key = Object.keys(s.bySystem).join(); if (key === previous) continue; previous = key;+ md.push(`- **${tier} census at ${r.fixture.id}:** ${s.visibleMeshes} visible meshes (${s.meshes} total), ${s.casters} casters, ${s.instanced} instanced (${s.instances} instances), ${s.transparent} transparent, ${s.skinned} skinned, ${Math.round(s.triangles).toLocaleString('en-US')} triangles; lights ${s.lights.map(l => `${l.name || l.type}${l.castShadow ? ` casts ${l.mapSize.join('×')}${l.texelWorld ? `, texel ${(l.texelWorld * 100).toFixed(1)} cm` : ''}` : ' no shadow'}`).join('; ') || 'none with shadows'}. Visible meshes/casters by system: ${Object.entries(s.bySystem).sort((a, b) => b[1].visibleMeshes - a[1].visibleMeshes).map(([k, v]) => `${k} ${v.visibleMeshes}/${v.casters}`).join(', ')}.`);+ }+ }+ md.push('');+ for (const tier of TIERS) {+ const tierRows = sceneRows.filter(r => r.tier === tier); if (!tierRows.length) continue;+ md.push(`### ${scene} · ${tier}`, '', '| Fixture | Draws | Main | Shadow | Reflection | Other | Pipelines (main/shadow/refl) | Triangles | Buffer | Top systems (draws) | GPU=JS |', '|---|---|---|---|---|---|---|---|---|---|---|');+ for (const r of tierRows) md.push(`| ${r.fixture}${r.hudLabel ? ` (${r.hudLabel})` : ''}${r.stable ? '' : ' ⚠ unstable'} | ${r.draws} | ${r.byKind.main?.draws ?? 0} | ${r.byKind.shadow ? `${r.byKind.shadow.draws}${r.byKind.shadow.passes > 1 ? ` (${r.byKind.shadow.passes} passes)` : ''}` : '-'} | ${r.byKind.reflection?.draws ?? '-'} | ${other({ byKind: r.byKind } as never)} | ${r.pipelinesUsed} (${SUMMARY_KINDS.map(k => r.byKind[k]?.pipelines ?? '-').join('/')}) | ${Math.round(r.triangles).toLocaleString('en-US')} | ${r.drawingBuffer.width}×${r.drawingBuffer.height} | ${Object.entries(r.bySystem).filter(([k]) => k !== '(output)').slice(0, 4).map(([k, v]) => `${k} ${v.draws}`).join(', ')} | ${r.gpu ? r.gpu.equal ? 'yes' : `NO ${r.gpu.jsDraws}/${r.gpu.gpuDraws}` : 'n/a'} |`);+ const names = [...new Set(tierRows.flatMap(r => Object.keys(r.whatIfs)))];+ if (names.length) {+ md.push('', `What-ifs at ${tier} (Δ draws per frame; shadow/main/reflection share in brackets where the delta is split):`, '', `| Fixture | ${names.join(' | ')} |`, `|---|${names.map(() => '---').join('|')}|`);+ for (const r of tierRows) md.push(`| ${r.fixture} | ${names.map(n => { const w = r.whatIfs[n] as { draws?: number; byKind?: Record<string, number>; error?: string; stable?: boolean } | undefined; if (!w) return ''; if (w.error) return 'error'; const parts = Object.entries(w.byKind ?? {}).filter(([, v]) => v); return `${w.draws}${parts.length > 1 ? ` [${parts.map(([k, v]) => `${k[0]}${v}`).join(' ')}]` : ''}${w.stable ? '' : '⚠'}`; }).join(' | ')} |`);+ }+ md.push('');+ }+ // What-ifs ranked by mean draws saved over this scene's fixtures, per tier, with mean pipelines saved and the pass that carries the saving.+ const tiers = TIERS.filter(t => sceneRows.some(r => r.tier === t)), lever = new Map<string, { cells: Map<Tier, { saves: number[]; pipes: number[] }>; byKind: Map<string, number> }>();+ for (const r of sceneRows) for (const [name, w] of Object.entries(r.whatIfs) as [string, { draws?: number; pipelines?: number; byKind?: Record<string, number> }][]) {+ if (w.draws === undefined) continue;+ const entry = lever.get(name) ?? { cells: new Map(), byKind: new Map<string, number>() }, cell = entry.cells.get(r.tier) ?? { saves: [] as number[], pipes: [] as number[] };+ cell.saves.push(-w.draws); cell.pipes.push(-(w.pipelines ?? 0)); entry.cells.set(r.tier, cell);+ for (const [k, v] of Object.entries(w.byKind ?? {})) entry.byKind.set(k, (entry.byKind.get(k) ?? 0) - v);+ lever.set(name, entry);+ }+ const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / xs.length;+ const ranked = [...lever.entries()].map(([name, e]) => ({ name, e, best: Math.max(...[...e.cells.values()].map(c => mean(c.saves))), pass: [...e.byKind.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '-' })).filter(l => l.best > 0).sort((a, b) => b.best - a.best);+ if (ranked.length) {+ md.push(`### ${scene} · what-ifs ranked (draws saved per frame: mean / max over fixtures, mean pipelines saved in brackets; count-only upper bounds)`, '',+ `| What-if | ${tiers.join(' | ')} | Pass carrying it | Look risk |`, `|---|${tiers.map(() => '---').join('|')}|---|---|`);+ for (const l of ranked) md.push(`| ${l.name} | ${tiers.map(t => { const c = l.e.cells.get(t); if (!c) return '–'; const p = mean(c.pipes); return `${mean(c.saves).toFixed(0)} / ${Math.max(...c.saves)}${p >= .5 ? ` (${p.toFixed(0)})` : ''}`; }).join(' | ')} | ${l.pass} | ${LOOK_RISK[l.name] ?? LOOK_RISK[l.name.startsWith('hide-') ? 'hide' : ''] ?? ''} |`);+ md.push('');+ }+ // MSAA and attachment store ops observed per pass kind (S3 input).+ const ops = new Map<string, Set<string>>();+ for (const r of sceneRows) for (const p of r.gpu?.ops ?? []) { const key = `${r.tier} ${p.kind}`; const set = ops.get(key) ?? new Set(); set.add(`colour ${p.color}; depth ${p.depth}`); ops.set(key, set); }+ if (ops.size) {+ md.push(`### ${scene} · render-pass load/store ops observed (renderContext passes)`, '', '| Tier and pass | Attachments (samples, format, load/store) |', '|---|---|');+ for (const [key, set] of [...ops.entries()].sort()) md.push(`| ${key} | ${[...set].join('<br>')} |`);+ const extras = [...new Set(sceneRows.flatMap(r => r.gpu?.otherEncoders ?? []))], split = [...new Set(sceneRows.filter(r => r.gpu?.split.length).map(r => `${r.tier}/${r.fixture}`))];+ md.push('', `Other encoders: ${extras.join(', ') || 'none'}; bundled (mipmap) draws per frame up to ${Math.max(0, ...sceneRows.map(r => r.gpu?.bundledDraws ?? 0))}; texture copies per frame up to ${Math.max(0, ...sceneRows.map(r => r.gpu?.copies ?? 0))}; main pass split into more than one GPU pass in ${split.length} probes${split.length ? ` (${split.slice(0, 6).join(', ')}${split.length > 6 ? ', …' : ''})` : ''}; uncaptured GPU errors ${Math.max(0, ...sceneRows.map(r => r.gpu?.errors ?? 0))}.`, '');+ }+ }+ if (errors.length) { md.push('## Failed fixtures', '', ...errors.map(e => `- ${e.scene} ${e.tier} ${e.fixture}: ${e.error}`), ''); }+ if (comparison) md.push('## Comparison with ' + compareWith, '', comparison.some(c => !c.pipelinesComparable) ? 'Pipelines are the cumulative pipeline cache; it is compared only when both runs used a fresh page per fixture, so here it is shown but not checked (n/c).' : 'Both runs used a fresh page per fixture, so the pipeline cache is compared.', '',+ '| Scene | Tier | Fixture | Draws | Triangles | Pipelines | X-02 (±2% draws and triangles, pipelines ≤ +5%) |', '|---|---|---|---|---|---|---|', ...comparison.map(c => `| ${c.scene} | ${c.tier} | ${c.fixture} | ${c.before.draws} → ${c.after.draws} | ${c.before.triangles} → ${c.after.triangles} | ${c.before.pipelines} → ${c.after.pipelines}${c.pipelinesComparable ? '' : ' (n/c)'} | ${c.pass ? 'within' : 'outside'} |`), '');+ const levers = evidence(label, 'levers.md');+ if (existsSync(levers)) md.push(readFileSync(levers, 'utf8').trim(), '');+ writeFileSync(evidence(label, 'summary.md'), md.join('\n'));+ return { rows: rows.length, errors: errors.length };+}+/**+ * X-02 against a baseline summary (OD-8 re-baseline). The cumulative pipeline cache depends on what the page drew before,+ * so its +5% bound applies only when both runs used a fresh page per fixture (`pipelinesComparable`); otherwise a row+ * passes on draws and triangles and its pipelines are shown as not compared.+ */+export function compareRows(after: CountRow[], before: CountRow[], pipelines: boolean) {+ const snapshot = (r: CountRow) => ({ drawCalls: r.draws, triangles: r.triangles, pipelines: r.pipelineCache, geometries: r.memory.geometries, textures: r.memory.textures, programs: r.programs });+ return after.flatMap(a => {+ const b = before.find(x => x.scene === a.scene && x.tier === a.tier && x.fixture === a.fixture); if (!b) return [];+ const x02 = compareStaticRendererCounts(snapshot(b), snapshot(a)), pass = pipelines ? x02.pass : x02.validObservations && x02.checks.drawCalls.pass && x02.checks.triangles.pass;+ return [{ scene: a.scene, tier: a.tier, fixture: a.fixture, before: { draws: b.draws, triangles: b.triangles, pipelines: b.pipelineCache }, after: { draws: a.draws, triangles: a.triangles, pipelines: a.pipelineCache }, pipelinesComparable: pipelines, pass }];+ });+}+export interface CountRow { scene: string; tier: string; fixture: string; draws: number; triangles: number; pipelineCache: number; programs: number; memory: { geometries: number; textures: number } }++if (import.meta.main) {+ const args = process.argv.slice(2);+ const option = (name: string, fallback: string) => { const at = args.indexOf(name); if (at < 0) return fallback; const v = args[at + 1]; if (!v || v.startsWith('--')) throw new Error(`${name} needs a value`); return v; };+ const label = option('--label', ''); if (!/^[a-z0-9-]+$/.test(label)) throw new Error('--label <lowercase-label> is required');+ const compareWith = args.includes('--compare') ? option('--compare', '') : undefined;+ if (!args.includes('--summary-only')) {+ const scenes = option('--scenes', 'farm,foundry-floor,golden-gate').split(',') as SceneId[], tiers = option('--tiers', TIERS.join(',')).split(',') as Tier[];+ for (const s of scenes) if (!SCENE_FIXTURES[s]) throw new Error(`Unknown scene ${s}`);+ for (const t of tiers) if (!TIERS.includes(t)) throw new Error(`Unknown tier ${t}`);+ const fixtures = option('--fixtures', 'all'), size = option('--size', '1920x1080').split('x').map(Number) as [number, number];+ await runCountProbe({ label, build: option('--build', label), scenes, tiers, fixtures: fixtures === 'all' ? 'all' : fixtures.split(','), whatIfs: option('--what-if', 'standard') === 'standard', size, freshPage: args.includes('--fresh-page'),+ // --query adds dev parameters (for example heroMerge=false) to every fixture URL, for A/B counts within one build.+ ...(args.includes('--query') ? { query: Object.fromEntries(new URLSearchParams(option('--query', ''))) } : {}) });+ }+ console.log(JSON.stringify(summarize(label, compareWith)));+}diff --git a/scenes/scripts/farm-capture-pages.ts b/scenes/scripts/farm-capture-pages.tsnew file mode 100644index 00000000..6555d2f1--- /dev/null+++ b/scenes/scripts/farm-capture-pages.ts@@ -0,0 +1,128 @@+// S5 Farm page helpers shared by scripts/capture-farm-draw-parity.ts (cross-build parity) and scripts/farm-x02-baseline.ts+// (the OD-8 X-02 reference): one fresh page per capture at any tier and backend, the B-06 page normalization (1280x720+// canvas, HUD hidden), the count probe's fixtures (scripts/scene-fixtures.ts FARM_FIXTURES) plus play destinations, a wait+// for the cached sun shadow to settle, and pinned end poses for the two workloads. Counts and pixels only, never timing.+import type { Browser, Page } from 'puppeteer-core';+import { PNG } from 'pngjs';+import { assertOwnedUrl, waitForReady, waitFrames } from '../packages/scene-kit/src/testing/node';+import { FARM_FIXTURES } from './scene-fixtures';+import type { RgbaImage } from './parity-images';++/* eslint-disable @typescript-eslint/no-explicit-any */+const TIMEOUT = 180_000;+export type FarmBackend = 'webgpu' | 'webgl2';+/** scripts/capture-farm-parity.ts normalizedCss (B-06): a 1280x720 canvas at the page origin, HUD and chrome hidden. */+export const FARM_PARITY_CSS = `+html,body{margin:0!important;padding:0!important;width:1280px!important;height:720px!important;overflow:hidden!important;display:block!important}+body>header,body>footer,aside{display:none!important}+main,#farm-view,#scene-shell,#farm,.ks-root{margin:0!important;padding:0!important;border:0!important;border-radius:0!important;max-width:none!important;max-height:none!important;min-height:0!important;width:1280px!important;height:720px!important;box-sizing:border-box!important}+main,#farm-view,#scene-shell,#farm{position:absolute!important;left:0!important;top:0!important;display:block!important}+canvas{display:block!important;width:1280px!important;height:720px!important;border:0!important;border-radius:0!important}+#farm-view>:not(canvas),#page-status,.ks-hud,.ks-help,.ks-credits,.ks-fade,.ks-dev-panel{visibility:hidden!important}+canvas,.ks-root{outline:none!important}+`;+const FALLBACK = /^THREE\.WebGPURenderer: WebGPU is not available, running under WebGL2 backend\.$/;++/** Opens one page on an owned server with the Farm's frozen-clock query and the B-06 normalization; checks the backend. */+export async function openFarmPage(o: { browser: Browser; base: string; owned: ReadonlySet<number>; tier: string; backend: FarmBackend; view: string; extra?: Record<string, string> }) {+ const page = await o.browser.newPage(), messages: string[] = [];+ page.setDefaultTimeout(TIMEOUT);+ page.on('console', m => { if ((m.type() === 'error' || m.type() === 'warn') && !FALLBACK.test(m.text())) messages.push(`${m.type()}: ${m.text().slice(0, 300)}`); });+ page.on('pageerror', e => messages.push(`pageerror: ${String(e).slice(0, 300)}`));+ await page.setViewport({ width: 1280, height: 720, deviceScaleFactor: 1 });+ await page.emulateMediaFeatures([{ name: 'prefers-reduced-motion', value: 'no-preference' }]);+ await page.evaluateOnNewDocument(css => {+ const apply = () => { if (!document.head) return false; const s = document.createElement('style'); s.textContent = css; document.head.append(s); return true; };+ if (!apply()) { const observer = new MutationObserver(() => { if (apply()) observer.disconnect(); }); observer.observe(document, { childList: true, subtree: true }); }+ }, FARM_PARITY_CSS);+ const query = new URLSearchParams({ freeze: '1', time: '0', view: o.view, tier: o.tier, ...(o.backend === 'webgl2' ? { backend: 'webgl2' } : {}), ...o.extra });+ const url = `${o.base}/?${query}`; assertOwnedUrl(url, o.owned);+ try {+ await page.goto(url, { waitUntil: 'load', timeout: TIMEOUT }); await waitForReady(page);+ const backend = await page.$eval('.ks-root', root => root.getAttribute('data-kiln-backend'));+ if (backend !== o.backend) throw new Error(`Expected the ${o.backend} backend, got ${backend}`);+ await FARM_FIXTURES.prepare(page);+ return { page, messages, url };+ } catch (error) { await page.close().catch(() => {}); throw error; }+}++const invoke = (page: Page, name: string, ...a: unknown[]) => page.evaluate((n, x) => (window as any).__kilnScene.invoke(n, ...x), name, a) as Promise<any>;+const frames = (page: Page, n: number) => waitFrames(page, n);+/** Polls simState 20 frames apart until the follow camera, Rowan and the tractor repeat (to 1e-4, the hook's rounding). */+async function rest(page: Page) {+ for (let i = 0, last = ''; i < 60; i++) {+ const s = await invoke(page, 'simState'), now = JSON.stringify([s.player.position, s.player.yaw, s.tractor.position, s.tractor.yaw, s.camera.position, s.camera.quaternion]);+ if (now === last) return; last = now; await frames(page, 20);+ }+ throw new Error('The Farm did not come to rest');+}+/** A workload's end pose, pinned so every build and repeat is captured at the same place (the workloads step on the frame's own delta). */+export interface FarmPose { player: { position: number[]; yaw: number }; tractor: { position: number[]; yaw: number }; driving: boolean }+/**+ * Fixtures: the count probe's FARM_FIXTURES (12 named views, 4 play fixtures, the walk and tractor-drive workloads) plus+ * play destinations (`dest-<name>`, the follow camera at an INV A.1 start point) for close views of the heroes' shadows.+ */+export const FARM_DESTINATION_VIEWS = ['dest-tractor', 'dest-paddocks'] as const;+export const FARM_PARITY_VIEWS = [...FARM_FIXTURES.fixtures.map(f => f.id), ...FARM_DESTINATION_VIEWS];+export const FARM_WORKLOADS = new Set(['walk', 'tractor-drive']);+/**+ * Enters a fixture. A workload without `pin` runs as the count probe runs it and returns the pose it reached. With `pin`+ * it does not run: play starts, Rowan is placed at the pinned pose (walk), or mounts the tractor at its INV A.1 start point+ * with E and the tractor is placed at the pinned pose (tractor-drive). The drive accumulates wheel travel on the frame's own+ * delta, so only a mount without driving gives every build and repeat the same wheel angle (travel 0, steer 0).+ */+export async function enterFarmView(page: Page, view: string, pin?: FarmPose | null): Promise<FarmPose | null> {+ const play = async (to: string) => {+ await page.evaluate(() => (window as any).__kilnScene.setPlaying(true)); await frames(page, 2);+ if (await invoke(page, 'teleport', to) !== true) throw new Error(`Farm destination ${to}`);+ await frames(page, 3);+ };+ if (view.startsWith('dest-')) { await play(view.slice(5)); await rest(page); return null; }+ const fixture = FARM_FIXTURES.fixtures.find(f => f.id === view); if (!fixture) throw new Error(`Unknown Farm view ${view}`);+ if (!FARM_WORKLOADS.has(view)) { await fixture.enter(page); return null; }+ if (!pin) {+ await fixture.enter(page);+ const s = await invoke(page, 'simState');+ return { player: { position: s.player.position, yaw: s.player.yaw }, tractor: { position: s.tractor.position, yaw: s.tractor.yaw }, driving: s.driving };+ }+ if (view === 'walk') { await play('yard'); await invoke(page, 'placePlayer', ...pin.player.position, pin.player.yaw); }+ else {+ await play('tractor');+ if ((await invoke(page, 'simState')).nearest !== 'tractor') throw new Error('Rowan is not beside the tractor at its start point');+ await page.focus('.ks-root'); await page.keyboard.press('KeyE');+ await page.waitForFunction(() => (window as any).__kilnScene.invoke('simState').driving === true, { timeout: TIMEOUT, polling: 'raf' });+ await invoke(page, 'placeTractor', ...pin.tractor.position, pin.tractor.yaw);+ }+ await frames(page, 3); await rest(page);+ const s = await invoke(page, 'simState');+ if (s.driving !== pin.driving) throw new Error(`${view}: driving ${s.driving}, pinned pose driving ${pin.driving}`);+ return pin;+}+/** Waits until the cached sun shadow has settled (pendingSettle 0); a build without the cache returns at once. */+export async function settleFarmShadow(page: Page, limit = 900) {+ return page.evaluate(async lim => {+ const s = (window as any).__kilnScene;+ for (let i = 0; i < lim; i++) { const c = s.invoke('counts')?.shadow; if (!c) return { frames: i, cache: false }; if (c.pendingSettle === 0) return { frames: i, cache: true, live: c.liveCasters, staticRenders: c.staticRenders }; await s.waitFrames(1); }+ const c = s.invoke('counts')?.shadow; return { frames: lim, cache: true, live: c?.liveCasters, pending: c?.pendingSettle, unsettled: true };+ }, limit);+}+/** renderer.info totals of the last frame, read once a frame until three reads agree (X-02 counts, including shadow passes). */+export async function stableFarmCounts(page: Page, limit = 300) {+ return page.evaluate(async lim => {+ const s = (window as any).__kilnScene; let last = '', same = 0, read: any = null;+ for (let i = 0; i < lim; i++) {+ await s.waitFrames(1); const st = s.stats();+ read = { drawCalls: st.render.drawCalls, triangles: st.render.triangles, pipelines: st.pipelines, programs: st.programs, geometries: st.memory.geometries, textures: st.memory.textures };+ const key = JSON.stringify(read); if (key === last) { if (++same >= 2) return { ...read, frames: i, stable: true }; } else { last = key; same = 0; }+ }+ return { ...read, frames: lim, stable: false };+ }, limit);+}+/** The 1280x720 canvas as RGBA. */+export async function shootFarm(page: Page): Promise<RgbaImage> {+ await frames(page, 6);+ const bytes = await page.screenshot({ type: 'png', clip: { x: 0, y: 0, width: 1280, height: 720 }, captureBeyondViewport: false });+ const png = PNG.sync.read(Buffer.from(bytes));+ if (png.width !== 1280 || png.height !== 720) throw new Error(`Capture is ${png.width}x${png.height}, expected 1280x720`);+ return { width: png.width, height: png.height, data: new Uint8Array(png.data) };+}diff --git a/scenes/scripts/farm-count-gates.ts b/scenes/scripts/farm-count-gates.tsindex 87e9b6d5..78603198 100644--- a/scenes/scripts/farm-count-gates.ts+++ b/scenes/scripts/farm-count-gates.ts@@ -36,6 +36,72 @@ export function compareStaticRendererCounts(pilot: RendererCountSnapshot, rewritvalidObservations };}+/**+ * OD-8 (D-53): X-02 is re-baselined on the optimized build. The reference is a committed file of that build's fresh-page+ * high counts per view and backend (`packages/farm/fixtures/x02-baseline.json`, written by `scripts/farm-x02-baseline.ts`),+ * and an observation passes on the same rule as before: draws and triangles within an inclusive ±2%, the pipeline cache at+ * most +5%. Pixel parity against the sealed pilot (B-06) and the B-07 goldens are unchanged.+ */+export const X02_BASELINE_SCHEMA = 'kiln.farm-x02-baseline/1';+export const X02_BASELINE_PATH = 'packages/farm/fixtures/x02-baseline.json';+/** The X-02 fixtures: every named view of the layout and the SPEC 19.3/19.7 play fixtures (workloads are not X-02 views). */+export const FARM_X02_VIEWS = ['hero', 'opposite', 'top', 'eye-height', 'crops', 'fences', 'props', 'watermill-wheel', 'watermill-interior', 'house-interior', 'house-porch', 'house-window-out',+ 'play-yard', 'play-house', 'play-bridge', 'play-house-door'] as const;+export type X02Backend = 'webgpu' | 'webgl2';+export interface X02ReferenceEntry extends RendererCountSnapshot { kind: CountFixtureKind }+export interface X02Baseline {+ schema: string; decision: string; rule: string;+ provenance: { build: string; commit: string; chunks: string[]; source: string; tool: string; date: string; [key: string]: unknown };+ /** One page per view (the pipeline cache is cumulative), the scene clock frozen, the cached shadow settled. */+ conditions: { tier: string; viewport: [number, number]; freshPage: boolean; clock: 'frozen'; settled: boolean };+ backends: Partial<Record<X02Backend, Record<string, X02ReferenceEntry>>>;+}+export interface X02Run { tier: string; backend: X02Backend; viewport: [number, number]; freshPage: boolean }+/** Problems with a reference file; an empty list means it can be used. */+export function validateX02Baseline(value: X02Baseline): string[] {+ const problems: string[] = [];+ if (value?.schema !== X02_BASELINE_SCHEMA) problems.push(`schema is not ${X02_BASELINE_SCHEMA}`);+ for (const key of ['build', 'commit', 'source', 'tool', 'date'] as const) if (typeof value?.provenance?.[key] !== 'string' || !value.provenance[key]) problems.push(`provenance.${key} is missing`);+ if (!Array.isArray(value?.provenance?.chunks) || !value.provenance.chunks.length) problems.push('provenance.chunks is missing');+ const c = value?.conditions;+ if (c?.tier !== 'high') problems.push('conditions.tier is not high');+ if (c?.freshPage !== true) problems.push('conditions are not one fresh page per view');+ if (c?.clock !== 'frozen' || c?.settled !== true) problems.push('conditions are not a frozen, settled clock');+ if (!Array.isArray(c?.viewport) || c.viewport.length !== 2 || !c.viewport.every(n => validCount(n) && n > 0)) problems.push('conditions.viewport is missing');+ const backends = Object.entries(value?.backends ?? {});+ if (!backends.length) problems.push('no backend has reference counts');+ for (const [backend, views] of backends) for (const [view, e] of Object.entries(views ?? {})) {+ for (const key of ['drawCalls', 'triangles', 'pipelines', 'geometries', 'textures', 'programs'] as const) if (!validCount(e?.[key])) problems.push(`${backend}/${view}.${key} is not a count`);+ if (e?.kind !== 'named view' && e?.kind !== 'play fixture') problems.push(`${backend}/${view}.kind is not a fixture kind`);+ }+ return problems;+}+/** Conditions that would make a count incomparable with the reference. Viewports compare by aspect ratio (frustum culling). */+function x02Differences(reference: X02Baseline['conditions'], run: X02Run) {+ const differences: string[] = [];+ if (run.tier !== reference.tier) differences.push(`tier ${run.tier}, reference ${reference.tier}`);+ if (run.freshPage !== reference.freshPage) differences.push(`${run.freshPage ? 'a fresh page' : 'a shared page'} per view, reference ${reference.freshPage ? 'a fresh page' : 'a shared page'}`);+ const [w, h] = run.viewport, [rw, rh] = reference.viewport;+ if (!(w > 0 && h > 0) || w * rh !== h * rw) differences.push(`viewport ${w}x${h} has another aspect ratio than the reference ${rw}x${rh}`);+ return differences;+}+/** One view and backend against the committed reference: X-02's bounds, refusing a missing entry or other run conditions. */+export function compareX02Reference(baseline: X02Baseline, o: X02Run & { view: string }, observed: RendererCountSnapshot) {+ const reference = baseline.backends[o.backend]?.[o.view], differences = x02Differences(baseline.conditions, o);+ const head = { id: 'X-02' as const, view: o.view, backend: o.backend, reference: { file: X02_BASELINE_PATH, build: baseline.provenance.build, commit: baseline.provenance.commit, date: baseline.provenance.date }, conditions: { match: differences.length === 0, differences } };+ if (!reference) return { ...head, missing: true, pass: false, fixture: null, checks: null, observed: null, validObservations: false, scope: `No reference counts for ${o.view} on ${o.backend}` };+ const { kind, ...counts } = reference, result = compareStaticRendererCounts(counts, observed, kind);+ return { ...head, ...result, missing: false, pass: result.pass && differences.length === 0 };+}+/** Count-probe rows (summary.json) against the reference: every reference view at the reference tier must be present and pass. */+export function checkX02Rows(baseline: X02Baseline, rows: readonly { tier: string; fixture: string; draws: number; triangles: number; pipelineCache: number; programs: number; memory: { geometries: number; textures: number } }[], run: X02Run) {+ const reference = baseline.backends[run.backend] ?? {}, tierRows = rows.filter(r => r.tier === baseline.conditions.tier);+ const views = tierRows.filter(r => Object.hasOwn(reference, r.fixture)).map(r => compareX02Reference(baseline, { ...run, tier: r.tier, view: r.fixture },+ { drawCalls: r.draws, triangles: r.triangles, pipelines: r.pipelineCache, geometries: r.memory.geometries, textures: r.memory.textures, programs: r.programs }));+ const missing = Object.keys(reference).filter(view => !tierRows.some(r => r.fixture === view)), extra = tierRows.filter(r => !Object.hasOwn(reference, r.fixture)).map(r => r.fixture);+ return { pass: missing.length === 0 && views.length > 0 && views.every(v => v.pass), conditions: x02Differences(baseline.conditions, { ...run, tier: baseline.conditions.tier }), views, missing, extra };+}+interface PilotOptimizationReference extends RendererCountSnapshot { assetTexturePool: { uniqueBefore: number; uniqueAfter: number } | null }export interface ColliderCounts { colliders: number; dynamic: number; staticTriangles: number; dynamicTriangles: number; doors: number; doorPivots: number; keys: { key: string; dynamic: boolean; triangles: number }[] }/** B-07 collider portion: the live collision world against the frozen sealed-pilot fixture (`packages/farm/fixtures/play-colliders.json`). */diff --git a/scenes/scripts/farm-x02-baseline.ts b/scenes/scripts/farm-x02-baseline.tsnew file mode 100644index 00000000..36f3581e--- /dev/null+++ b/scenes/scripts/farm-x02-baseline.ts@@ -0,0 +1,98 @@+// OD-8 (D-53) X-02 re-baseline for the Farm. `measure` writes the committed reference (packages/farm/fixtures/x02-baseline.json)+// from a test build: per backend and X-02 view (every named view and the four play fixtures), one fresh page at high with the+// scene clock frozen and ambient life off, the fixture entered as the count probe enters it, the cached sun shadow settled,+// then renderer.info totals (draws including shadow passes, triangles, the pipeline cache) read until three frames agree.+// `check` compares a count-probe run (its summary.json, fresh-page) or a `measure` output against the reference with+// X-02's rule (inclusive ±2% draws and triangles, pipeline cache at most +5%); it exits 1 when the run is flagged.+// bun scripts/farm-x02-baseline.ts measure --build <label> [--backends webgpu,webgl2] [--out packages/farm/fixtures/x02-baseline.json] [--log <json>]+// bun scripts/farm-x02-baseline.ts check --summary <count-probe summary.json or a measure output> [--reference …] [--backend webgpu] [--json <out>]+// Counts only: nothing here reads or reports time.+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import type { Browser } from 'puppeteer-core';+import { launchChrome, serveOwned } from '../packages/scene-kit/src/testing/node';+import { sceneOutput } from './build-scene';+import { checkX02Rows, FARM_X02_VIEWS, validateX02Baseline, X02_BASELINE_PATH, X02_BASELINE_SCHEMA, type X02Backend, type X02Baseline, type X02ReferenceEntry } from './farm-count-gates';+import { enterFarmView, openFarmPage, settleFarmShadow, stableFarmCounts } from './farm-capture-pages';++const ROOT = resolve(import.meta.dir, '..'), args = process.argv.slice(2), command = args[0];+const option = (name: string, fallback: string) => { const at = args.indexOf(name); return at < 0 ? fallback : args[at + 1] ?? fallback; };+const PLAY = new Set(['play-yard', 'play-house', 'play-bridge', 'play-house-door']);++async function measure(build: string, backends: X02Backend[], out: string) {+ const dir = sceneOutput('farm', build, 'test'), built = JSON.parse(readFileSync(resolve(dir, 'build.json'), 'utf8')) as { chunks: { name: string }[]; source?: unknown };+ // A working-tree build names no commit: record the last commit that changed the scene sources, and whether they are clean now.+ const git = (...a: string[]) => execFileSync('git', a, { cwd: ROOT, encoding: 'utf8' }).trim();+ const fromBuild = (built.source as { commit?: string } | null)?.commit, head = git('rev-parse', 'HEAD'), commit = fromBuild ?? git('log', '-1', '--format=%H', '--', 'packages/scene-kit/src', 'packages/farm/src', 'packages/farm/fixtures/layout.json');+ const dirty = git('status', '--porcelain', '--', 'packages/scene-kit/src', 'packages/farm/src');+ const hosted = await serveOwned(dir), owned = new Set([hosted.port]), browser: Browser = await launchChrome({ workspace: ROOT, name: 'farm-x02-baseline', windowSize: [1280, 720] });+ const reference: X02Baseline['backends'] = {}, details: Record<string, unknown>[] = [], version = await browser.version();+ try {+ for (const backend of backends) {+ const views: Record<string, X02ReferenceEntry> = reference[backend] = {};+ for (const view of FARM_X02_VIEWS) {+ const { page, messages } = await openFarmPage({ browser, base: hosted.url, owned, tier: 'high', backend, view: PLAY.has(view) ? 'hero' : view });+ try {+ await enterFarmView(page, view);+ const settle = await settleFarmShadow(page), counts = await stableFarmCounts(page);+ if (!counts.stable || settle.unsettled) throw new Error(`${backend} ${view}: counts did not settle (${JSON.stringify({ settle, counts })})`);+ if (messages.length) throw new Error(`${backend} ${view}: browser errors or warnings: ${messages.join(' | ')}`);+ const { frames: _f, stable: _s, ...snapshot } = counts;+ views[view] = { kind: PLAY.has(view) ? 'play fixture' : 'named view', ...snapshot };+ details.push({ backend, view, settle, frames: counts.frames });+ console.log(`${backend} ${view}: draws ${snapshot.drawCalls} triangles ${snapshot.triangles} pipelines ${snapshot.pipelines} programs ${snapshot.programs} (settled after ${settle.frames} frames, cache ${settle.cache})`);+ } finally { await page.close().catch(() => {}); }+ }+ }+ } finally { await browser.close(); await hosted.close(); }+ const value: X02Baseline = {+ schema: X02_BASELINE_SCHEMA, decision: 'OD-8 (D-53): X-02 re-baselined on the optimized build; pixel parity against the sealed pilot (B-06) is unchanged',+ rule: 'Inclusive ±2% draws (renderer.info drawCalls of one frame, shadow passes included) and triangles; pipeline cache at most +5% of this reference',+ provenance: { build, commit, chunks: built.chunks.map(c => c.name).sort(), source: fromBuild ? JSON.stringify(built.source) : `${String(built.source)}; Farm and kit sources last changed in ${commit.slice(0, 7)}, ${dirty ? 'with uncommitted changes' : 'clean'} at HEAD ${head.slice(0, 7)} when measured`,+ tool: `scripts/farm-x02-baseline.ts measure --build ${build}`, date: new Date().toISOString().slice(0, 10), browser: `headless ${version}`, viewport: '1280x720 CSS at device scale 1 (B-06 normalization)', pagePolicy: 'one fresh page per view and backend' },+ conditions: { tier: 'high', viewport: [1280, 720], freshPage: true, clock: 'frozen', settled: true },+ backends: reference,+ };+ const problems = validateX02Baseline(value); if (problems.length) throw new Error(`Reference is not valid: ${problems.join('; ')}`);+ mkdirSync(dirname(out), { recursive: true }); writeFileSync(out, JSON.stringify(value, null, 1) + '\n');+ return { value, details };+}++function check(referencePath: string, summaryPath: string, backend: X02Backend) {+ const baseline = JSON.parse(readFileSync(referencePath, 'utf8')) as X02Baseline, problems = validateX02Baseline(baseline);+ if (problems.length) throw new Error(`Reference ${referencePath} is not valid: ${problems.join('; ')}`);+ type Row = { scene: string; tier: string; fixture: string; draws: number; triangles: number; pipelineCache: number; programs: number; memory: { geometries: number; textures: number } };+ const raw = JSON.parse(readFileSync(summaryPath, 'utf8')) as { schema?: string; label?: string; provenance?: { viewports?: string[]; freshPage?: boolean | null; build?: string }; rows?: Row[] } & Partial<X02Baseline>;+ // A count-probe summary.json, or another `measure` output (the same shape as the reference) taken as the run.+ const summary = raw.schema === X02_BASELINE_SCHEMA+ ? { label: `measure of ${raw.provenance!.build}`, provenance: { viewports: [raw.conditions!.viewport.join('x')], freshPage: raw.conditions!.freshPage },+ rows: Object.entries(raw.backends?.[backend] ?? {}).map(([fixture, e]): Row => ({ scene: 'farm', tier: raw.conditions!.tier, fixture, draws: e.drawCalls, triangles: e.triangles, pipelineCache: e.pipelines, programs: e.programs, memory: { geometries: e.geometries, textures: e.textures } })) }+ : raw as { label: string; provenance?: { viewports?: string[]; freshPage?: boolean | null }; rows: Row[] };+ const viewport = (summary.provenance?.viewports?.[0] ?? '0x0').split('x').map(Number) as [number, number];+ const result = checkX02Rows(baseline, summary.rows.filter(r => r.scene === 'farm'), { tier: baseline.conditions.tier, backend, viewport, freshPage: summary.provenance?.freshPage === true });+ const pct = (c: { relativeChange: number | null } | undefined) => c?.relativeChange === null || c?.relativeChange === undefined ? '-' : `${(c.relativeChange * 100).toFixed(1)}%`;+ const md = [`X-02 check of ${summary.label} (${summaryPath}) against ${referencePath} (build ${baseline.provenance.build}, ${baseline.provenance.commit.slice(0, 7)}, ${baseline.provenance.date}), ${backend}: **${result.pass ? 'PASS' : 'FLAGGED'}**.`,+ result.conditions.length ? `Run conditions differ from the reference: ${result.conditions.join('; ')}.` : 'Run conditions match the reference (high, one fresh page per view, 16:9).',+ result.missing.length ? `Reference views missing from the run: ${result.missing.join(', ')}.` : '', result.extra.length ? `Rows not judged (not X-02 views): ${result.extra.join(', ')}.` : '', '',+ '| View | Draws (reference → run) | Δ | Triangles | Δ | Pipeline cache | Δ | X-02 |', '|---|---|---|---|---|---|---|---|',+ ...result.views.map(v => `| ${v.view} | ${v.checks!.drawCalls.pilot} → ${v.checks!.drawCalls.rewrite} | ${pct(v.checks!.drawCalls)} | ${v.checks!.triangles.pilot} → ${v.checks!.triangles.rewrite} | ${pct(v.checks!.triangles)} | ${v.checks!.pipelines.pilot} → ${v.checks!.pipelines.rewrite} | ${pct(v.checks!.pipelines)} | ${v.pass ? 'within' : 'outside'} |`)].filter((line, i, all) => line !== '' || all[i - 1] !== '');+ return { result, md: md.join('\n') + '\n' };+}++if (import.meta.main) {+ if (command === 'measure') {+ const build = option('--build', ''); if (!build) throw new Error('--build <label> is required');+ const out = resolve(ROOT, option('--out', X02_BASELINE_PATH)), backends = option('--backends', 'webgpu,webgl2').split(',') as X02Backend[];+ const { details } = await measure(build, backends, out), log = resolve(ROOT, option('--log', `evidence/x02-baseline/${build}-measure-log.json`));+ mkdirSync(dirname(log), { recursive: true }); writeFileSync(log, JSON.stringify(details, null, 1) + '\n');+ console.log(`Reference written: ${out}`);+ } else if (command === 'check') {+ const reference = resolve(ROOT, option('--reference', X02_BASELINE_PATH)), summary = resolve(option('--summary', ''));+ if (!existsSync(summary)) throw new Error('--summary <count-probe summary.json> is required');+ const { result, md } = check(reference, summary, option('--backend', 'webgpu') as X02Backend);+ console.log(md);+ if (args.includes('--json')) { const out = resolve(option('--json', '')); mkdirSync(dirname(out), { recursive: true }); writeFileSync(out, JSON.stringify(result, null, 1) + '\n'); writeFileSync(out.replace(/\.json$/, '.md'), md); }+ process.exitCode = result.pass ? 0 : 1;+ } else console.log('Usage: bun scripts/farm-x02-baseline.ts measure --build <label> [--backends webgpu,webgl2] [--out <file>] | check --summary <summary.json> [--reference <file>] [--backend webgpu] [--json <out>]');+}diff --git a/scenes/scripts/foundry-count-gates.ts b/scenes/scripts/foundry-count-gates.tsnew file mode 100644index 00000000..ea5adc5a--- /dev/null+++ b/scenes/scripts/foundry-count-gates.ts@@ -0,0 +1,98 @@+/**+ * Foundry Floor X-02 (OD-8, D-53). Foundry Floor had no X-02 pin: its draw and triangle budgets (tests/unit/glb-world.test.ts)+ * need authored inputs and never ran in the gate. The reference is a committed count baseline of the optimized build+ * (`packages/foundry-floor/fixtures/count-baseline.json`, written by `scripts/check-foundry-counts.ts --record` from a+ * count-probe summary) and an observation passes on X-02's rule: draws and triangles within an inclusive ±2%, pipelines at+ * most +5%. Pipelines are those bound in the settled frame (order independent); the cumulative pipeline cache, which depends on+ * what the page drew before, is judged too, but only when the run used the reference's page policy; another policy skips that+ * one bound and the rest stand. This module neither starts a+ * renderer nor reads timing data.+ */+import { compareStaticRendererCounts } from './farm-count-gates';++export const FOUNDRY_COUNT_BASELINE_SCHEMA = 'kiln.foundry-floor-count-baseline/1';+export const FOUNDRY_COUNT_BASELINE_PATH = 'packages/foundry-floor/fixtures/count-baseline.json';+export const FOUNDRY_COUNT_TIERS = ['minimal', 'economy', 'balanced', 'high'] as const;+const validCount = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;++export interface FoundryCountEntry {+ drawCalls: number; triangles: number;+ /** Pipelines bound in the settled frame (the main pass and the output quad). */+ pipelines: number;+ /** The kit's cumulative pipeline cache; comparable only under the reference page policy. */+ pipelineCache: number;+ geometries: number; textures: number; programs: number;+ /** A workload fixture (the drive) reaches a representative state on the wall clock, so its counts are listed and never judged. */+ workload?: true;+}+export interface FoundryCountConditions { viewport: [number, number]; freshPage: boolean; clock: string; backend: string; settled: boolean }+export interface FoundryCountProvenance { build: string; commit: string; chunks: string[]; source: string; tool: string; date: string; [key: string]: unknown }+export interface FoundryCountBaseline {+ schema: string; decision: string; rule: string; provenance: FoundryCountProvenance; conditions: FoundryCountConditions;+ tiers: Record<string, Record<string, FoundryCountEntry>>;+}+/** The count-probe summary row fields this check reads (scripts/count-probe.ts summary.json rows). */+export interface FoundryCountRow { scene: string; tier: string; fixture: string; draws: number; triangles: number; pipelinesUsed: number; pipelineCache: number; programs: number; memory: { geometries: number; textures: number } }+export interface FoundryCountRun { freshPage: boolean | null; viewport: [number, number]; tiers?: readonly string[] }++/** The reference from a count-probe run: every Foundry Floor row, in tier order, with the workload fixtures marked. */+export function buildFoundryCountBaseline(rows: readonly FoundryCountRow[], o: { provenance: FoundryCountProvenance; conditions: FoundryCountConditions; workloads: readonly string[] }): FoundryCountBaseline {+ const tiers: FoundryCountBaseline['tiers'] = {};+ for (const tier of FOUNDRY_COUNT_TIERS) {+ const own = rows.filter(r => r.tier === tier && r.scene === 'foundry-floor'); if (!own.length) continue;+ tiers[tier] = Object.fromEntries(own.map(r => [r.fixture, { drawCalls: r.draws, triangles: r.triangles, pipelines: r.pipelinesUsed, pipelineCache: r.pipelineCache, geometries: r.memory.geometries, textures: r.memory.textures, programs: r.programs,+ ...(o.workloads.includes(r.fixture) ? { workload: true as const } : {}) }]));+ }+ return { schema: FOUNDRY_COUNT_BASELINE_SCHEMA, decision: 'OD-8 (D-53)', rule: 'Inclusive ±2% draws and triangles; pipelines bound per frame at most +5% of this reference (the cache too under the same page policy); workload fixtures listed, not judged',+ provenance: o.provenance, conditions: o.conditions, tiers };+}++/** Problems with a reference file; an empty list means it can be used. */+export function validateFoundryCountBaseline(value: FoundryCountBaseline): string[] {+ const problems: string[] = [];+ if (value?.schema !== FOUNDRY_COUNT_BASELINE_SCHEMA) problems.push(`schema is not ${FOUNDRY_COUNT_BASELINE_SCHEMA}`);+ for (const key of ['build', 'commit', 'source', 'tool', 'date'] as const) if (typeof value?.provenance?.[key] !== 'string' || !value.provenance[key]) problems.push(`provenance.${key} is missing`);+ if (!Array.isArray(value?.provenance?.chunks) || !value.provenance.chunks.length) problems.push('provenance.chunks is missing');+ const c = value?.conditions;+ if (c?.clock !== 'frozen' || c?.settled !== true) problems.push('conditions are not a frozen, settled clock');+ if (typeof c?.freshPage !== 'boolean') problems.push('conditions.freshPage is missing');+ if (typeof c?.backend !== 'string' || !c.backend) problems.push('conditions.backend is missing');+ if (!Array.isArray(c?.viewport) || c.viewport.length !== 2 || !c.viewport.every(n => validCount(n) && n > 0)) problems.push('conditions.viewport is missing');+ const tiers = Object.entries(value?.tiers ?? {});+ if (!tiers.length) problems.push('no tier has reference counts');+ for (const [tier, fixtures] of tiers) for (const [fixture, e] of Object.entries(fixtures ?? {})) for (const key of ['drawCalls', 'triangles', 'pipelines', 'pipelineCache', 'geometries', 'textures', 'programs'] as const) if (!validCount(e?.[key])) problems.push(`${tier}/${fixture}.${key} is not a count`);+ return problems;+}++/** Conditions that would make a count incomparable with the reference. Viewports compare by aspect ratio (frustum culling). */+function differences(reference: FoundryCountConditions, run: FoundryCountRun) {+ const out: string[] = [], [w, h] = run.viewport, [rw, rh] = reference.viewport;+ if (!(w > 0 && h > 0) || w * rh !== h * rw) out.push(`viewport ${w}x${h} has another aspect ratio than the reference ${rw}x${rh}`);+ return out;+}+/** The cumulative cache depends on what the page drew before, so a run with another page policy skips that one bound (the others stand). */+const pageDiffers = (reference: FoundryCountConditions, run: FoundryCountRun) => run.freshPage !== null && run.freshPage !== reference.freshPage;++/**+ * Count-probe rows against the reference: every reference fixture at every checked tier must be present and pass. A fixture the+ * reference marks as a workload is listed (`judged: false`) and never fails; a fixture the reference lacks is reported as extra.+ */+export function checkFoundryCounts(baseline: FoundryCountBaseline, rows: readonly FoundryCountRow[], run: FoundryCountRun) {+ const tiers = (run.tiers ?? FOUNDRY_COUNT_TIERS).filter(t => baseline.tiers[t] || run.tiers), diff = differences(baseline.conditions, run), samePolicy = !pageDiffers(baseline.conditions, run);+ const checked: { tier: string; fixture: string; workload: boolean; judged: boolean; pass: boolean; checks: ReturnType<typeof compareStaticRendererCounts>['checks'] | null; cache: { reference: number; observed: number; pass: boolean } | null }[] = [];+ const missing: string[] = [], extra: string[] = [];+ for (const tier of tiers) {+ const reference = baseline.tiers[tier] ?? {}, own = rows.filter(r => r.tier === tier && r.scene === 'foundry-floor');+ for (const [fixture, e] of Object.entries(reference)) {+ const { workload, pipelineCache, ...counts } = e, r = own.find(x => x.fixture === fixture); if (!r) { if (workload !== true) missing.push(`${tier}/${fixture}`); continue; }+ const result = compareStaticRendererCounts(counts, { drawCalls: r.draws, triangles: r.triangles, pipelines: r.pipelinesUsed, geometries: r.memory.geometries, textures: r.memory.textures, programs: r.programs });+ // The cache: at most +5%, compared by integer arithmetic like the other bounds, and only under the reference's page policy.+ const cache = samePolicy ? { reference: pipelineCache, observed: r.pipelineCache, pass: r.pipelineCache * 100 <= pipelineCache * 105 } : null;+ checked.push({ tier, fixture, workload: workload === true, judged: workload !== true, pass: workload === true || (result.pass && (cache?.pass ?? true)), checks: result.checks, cache });+ }+ for (const r of own) if (!Object.hasOwn(reference, r.fixture)) extra.push(`${tier}/${r.fixture}`);+ }+ const conditions = { match: diff.length === 0, differences: diff, cacheJudged: samePolicy };+ return { id: 'X-02', reference: { file: FOUNDRY_COUNT_BASELINE_PATH, build: baseline.provenance.build, commit: baseline.provenance.commit, date: baseline.provenance.date },+ pass: missing.length === 0 && checked.length > 0 && checked.every(c => c.pass) && conditions.match, conditions, rows: checked, missing, extra };+}diff --git a/scenes/scripts/foundry-floor-count-table.ts b/scenes/scripts/foundry-floor-count-table.tsnew file mode 100644index 00000000..7001700c--- /dev/null+++ b/scenes/scripts/foundry-floor-count-table.ts@@ -0,0 +1,101 @@+// Foundry Floor before/after count table (draw-optimization step S5): reads two count-probe summaries (scripts/count-probe.ts,+// evidence/counts/<label>/summary.json) and writes the per-tier, per-fixture table the report needs: draws per pass, total+// draws, pipelines bound per frame and in the cache, triangles, per-tier sums, and the per-system attribution that shows what+// else changed. Foundry Floor is the control scene, so its AFTER differs from BEFORE only by the campus planting (shared+// material graph) and the MSAA multisample discard; every other system must match exactly. Counts only: nothing reads time.+// bun scripts/foundry-floor-count-table.ts [--before draw-base] [--after draw-after-ff] [--after-off draw-after-ff-off] [--out evidence/draw-after/foundry-floor]+// Output: <out>/counts-table.md and <out>/counts-table.json. Exits 1 when a system other than planting differs between BEFORE and+// AFTER outside the drive workload (whose traffic depends on the wall clock), or when AFTER with the planting switched off+// (--after-off) does not equal BEFORE on draws, pipelines used and triangles in every non-drive fixture.+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { resolve } from 'node:path';++const ROOT = resolve(import.meta.dir, '..'), TIERS = ['minimal', 'economy', 'balanced', 'high'] as const;+const args = process.argv.slice(2), option = (name: string, fallback: string) => { const at = args.indexOf(name); return at < 0 ? fallback : args[at + 1] ?? fallback; };+const read = (label: string) => JSON.parse(readFileSync(resolve(ROOT, 'evidence/counts', label, 'summary.json'), 'utf8')) as Summary;+interface SystemCount { draws: number; triangles: number }+interface Row {+ scene: string; tier: string; fixture: string; hudLabel: string | null; stable: boolean; draws: number; triangles: number; pipelinesUsed: number; pipelineCache: number; programs: number;+ byKind: Record<string, { passes: number; draws: number; triangles: number; pipelines: number }>; bySystem: Record<string, SystemCount>; drawingBuffer: { width: number; height: number };+ gpu: { equal: boolean; ops: { kind: string; color: string; depth: string }[] } | null;+}+interface Summary { label: string; provenance: { builds: Record<string, string[]>; viewports: string[]; freshPage: boolean | null }; rows: Row[] }+const before = read(option('--before', 'draw-base')), after = read(option('--after', 'draw-after-ff')), offLabel = option('--after-off', 'draw-after-ff-off');+const off = (() => { try { return read(offLabel); } catch { return null; } })();+const out = resolve(ROOT, option('--out', 'evidence/draw-after/foundry-floor')); mkdirSync(out, { recursive: true });++const rowsOf = (s: Summary, scene = 'foundry-floor') => s.rows.filter(r => r.scene === scene);+const find = (s: Summary, tier: string, fixture: string) => s.rows.find(r => r.tier === tier && r.fixture === fixture);+const fixtures = [...new Set(rowsOf(before).map(r => r.fixture))];+const kind = (r: Row, k: string) => r.byKind[k]?.draws ?? 0;+const delta = (a: number, b: number) => b === a ? '=' : `${b - a > 0 ? '+' : ''}${b - a}`;+const arrow = (a: number, b: number) => a === b ? `${a}` : `${a} → ${b}`;+const num = (n: number) => Math.round(n).toLocaleString('en-US');+const WORKLOAD = new Set(['drive']);++interface Line { tier: string; fixture: string; label: string | null; place: 'campus' | 'fab'; before: Row; after: Row; changedSystems: string[]; note: string }+const lines: Line[] = [], problems: string[] = [];+for (const tier of TIERS) for (const fixture of fixtures) {+ const b = find(before, tier, fixture), a = find(after, tier, fixture); if (!b || !a) { problems.push(`${tier} ${fixture}: missing in ${!b ? before.label : after.label}`); continue; }+ const systems = [...new Set([...Object.keys(b.bySystem), ...Object.keys(a.bySystem)])].filter(s => s !== '(output)');+ const changedSystems = systems.filter(s => JSON.stringify(b.bySystem[s] ?? null) !== JSON.stringify(a.bySystem[s] ?? null));+ const unexpected = changedSystems.filter(s => s !== 'planting');+ if (unexpected.length && !WORKLOAD.has(fixture)) problems.push(`${tier} ${fixture}: systems other than planting changed: ${unexpected.join(', ')}`);+ if (a.triangles !== b.triangles && !WORKLOAD.has(fixture)) problems.push(`${tier} ${fixture}: triangles ${b.triangles} → ${a.triangles}`);+ if (a.gpu && !a.gpu.equal) problems.push(`${tier} ${fixture}: GPU draws differ from JS draws`);+ const base = changedSystems.length === 0 ? 'unchanged' : unexpected.length === 0 ? 'planting only' : WORKLOAD.has(fixture) ? `workload state (${unexpected.join(', ')} moved with the wall clock)` : `OTHER: ${unexpected.join(', ')}`;+ const note = WORKLOAD.has(fixture) && !base.startsWith('workload') ? `${base}; workload fixture, its traffic can differ between runs` : base;+ lines.push({ tier, fixture, label: a.hudLabel, place: fixture.startsWith('fab-') ? 'fab' : 'campus', before: b, after: a, changedSystems, note });+}+// AFTER with the planting off must equal BEFORE (draws, pipelines used, triangles, per-system draws) in every non-drive fixture.+const offChecks: { tier: string; fixture: string; equal: boolean; detail: string }[] = [];+if (off) for (const tier of TIERS) for (const fixture of fixtures) {+ const b = find(before, tier, fixture), o = find(off, tier, fixture); if (!b || !o) continue;+ const mismatch = [b.draws !== o.draws && `draws ${b.draws} → ${o.draws}`, b.pipelinesUsed !== o.pipelinesUsed && `pipelines ${b.pipelinesUsed} → ${o.pipelinesUsed}`, b.triangles !== o.triangles && `triangles ${b.triangles} → ${o.triangles}`,+ JSON.stringify(b.bySystem) !== JSON.stringify(o.bySystem) && 'bySystem'].filter(Boolean);+ offChecks.push({ tier, fixture, equal: mismatch.length === 0, detail: mismatch.join('; ') });+ if (mismatch.length && !WORKLOAD.has(fixture)) problems.push(`planting-off ${tier} ${fixture}: ${mismatch.join('; ')}`);+}++const sum = (xs: Line[], pick: (r: Row) => number, which: 'before' | 'after') => xs.reduce((n, l) => n + pick(l[which]), 0);+const md: string[] = [`# Foundry Floor counts: ${before.label} (BEFORE) against ${after.label} (AFTER)`, '',+ `BEFORE: ${(before.provenance.builds['foundry-floor'] ?? []).join(', ')} (viewport ${before.provenance.viewports.join(', ')}, ${before.provenance.freshPage ? 'fresh page per fixture' : 'fixtures share a page'}). AFTER: ${(after.provenance.builds['foundry-floor'] ?? []).join(', ')} (viewport ${after.provenance.viewports.join(', ')}, ${after.provenance.freshPage ? 'fresh page per fixture' : 'fixtures share a page'}). Same policy on both sides: 1920x1080, device scale 1, frozen clock, WebGPU, one page per query group, so the cumulative pipeline cache depends on fixture order and is shown but not compared. "Pipelines" is the number bound in the settled frame (main pass / whole frame). Foundry Floor has no shadow or reflection pass at any tier; the passes are main and the output quad.`, ''];+for (const tier of TIERS) {+ const tl = lines.filter(l => l.tier === tier); if (!tl.length) continue;+ const buffer = tl[0]!.after.drawingBuffer;+ md.push(`## ${tier} (drawing buffer ${buffer.width}×${buffer.height})`, '', '| Fixture | Main draws | Output | Total draws | Pipelines bound (main) | Pipeline cache (n/c) | Triangles | Difference |', '|---|---|---|---|---|---|---|---|');+ for (const l of tl) {+ const b = l.before, a = l.after;+ md.push(`| ${l.fixture}${l.label ? ` (${l.label})` : ''} | ${arrow(kind(b, 'main'), kind(a, 'main'))} | ${arrow(kind(b, 'output'), kind(a, 'output'))} | ${arrow(b.draws, a.draws)} (${delta(b.draws, a.draws)}) | ${arrow(b.pipelinesUsed, a.pipelinesUsed)} (${arrow(b.byKind.main?.pipelines ?? 0, a.byKind.main?.pipelines ?? 0)}) | ${arrow(b.pipelineCache, a.pipelineCache)} | ${arrow(b.triangles, a.triangles)} | ${l.note} |`);+ }+ md.push('');+ for (const [name, group] of [['campus (7 fixtures)', tl.filter(l => l.place === 'campus')], ['fab (8 fixtures)', tl.filter(l => l.place === 'fab')], ['all 15 fixtures', tl]] as const) {+ md.push(`- **${tier} sum, ${name}:** main draws ${arrow(sum(group, r => kind(r, 'main'), 'before'), sum(group, r => kind(r, 'main'), 'after'))}; total draws ${arrow(sum(group, r => r.draws, 'before'), sum(group, r => r.draws, 'after'))} (${((sum(group, r => r.draws, 'after') / sum(group, r => r.draws, 'before') - 1) * 100).toFixed(1)}%); pipelines bound ${arrow(sum(group, r => r.pipelinesUsed, 'before'), sum(group, r => r.pipelinesUsed, 'after'))}; triangles ${num(sum(group, r => r.triangles, 'before'))} → ${num(sum(group, r => r.triangles, 'after'))}.`);+ }+ md.push('');+}+// Per-system attribution: what changed where (draws, then triangles).+md.push('## Per-system draws (BEFORE → AFTER), campus fixtures, high tier', '');+const sysNames = ['structures', 'planting', 'ground', 'traffic', 'sky'], campusHigh = lines.filter(l => l.tier === 'high' && l.place === 'campus');+md.push(`| Fixture | ${sysNames.join(' | ')} |`, `|---|${sysNames.map(() => '---').join('|')}|`);+for (const l of campusHigh) md.push(`| ${l.fixture} | ${sysNames.map(s => { const b = l.before.bySystem[s], a = l.after.bySystem[s]; return `${arrow(b?.draws ?? 0, a?.draws ?? 0)}${(b?.triangles ?? 0) !== (a?.triangles ?? 0) ? ' (tris differ)' : ''}`; }).join(' | ')} |`);+const fabHigh = lines.filter(l => l.tier === 'high' && l.place === 'fab'), fabSystems = ['fab-tools', 'fab-movers', 'fab-building', 'fab-transport', 'interior-context', 'fab-proxies', 'fab-pulses'];+md.push('', '## Per-system draws (BEFORE → AFTER), fab fixtures, high tier', '', `| Fixture | ${fabSystems.join(' | ')} |`, `|---|${fabSystems.map(() => '---').join('|')}|`);+for (const l of fabHigh) md.push(`| ${l.fixture} | ${fabSystems.map(s => { const b = l.before.bySystem[s], a = l.after.bySystem[s]; return `${arrow(b?.draws ?? 0, a?.draws ?? 0)}${(b?.triangles ?? 0) !== (a?.triangles ?? 0) ? ' (tris differ)' : ''}`; }).join(' | ')} |`);+// Systems unchanged over every fixture and tier.+const everywhere = (system: string) => { const ls = lines.filter(l => l.before.bySystem[system] || l.after.bySystem[system]); return { fixtures: ls.length, equal: ls.filter(l => JSON.stringify(l.before.bySystem[system] ?? null) === JSON.stringify(l.after.bySystem[system] ?? null)).length }; };+md.push('', '## Systems compared over every tier and fixture that draws them', '', '| System | Rows | Identical draws and triangles | Note |', '|---|---|---|---|');+for (const s of [...sysNames, ...fabSystems]) { const e = everywhere(s); if (e.fixtures) md.push(`| ${s} | ${e.fixtures} | ${e.equal} | ${e.equal === e.fixtures ? 'identical' : s === 'planting' ? 'changed by the shared planting material' : s === 'traffic' ? 'drive workload (wall-clock traffic)' : 'DIFFERS'} |`); }+// Load and store ops of the main and output passes.+const ops = (s: Summary) => [...new Set(rowsOf(s).flatMap(r => (r.gpu?.ops ?? []).map(o => `${o.kind}: colour ${o.color}; depth ${o.depth}`)))].sort();+md.push('', '## Render-pass attachments observed', '', `- BEFORE (${before.label}):`, ...ops(before).map(o => ` - ${o}`), `- AFTER (${after.label}):`, ...ops(after).map(o => ` - ${o}`));+if (off) {+ md.push('', `## AFTER with the planting switched off (${off.label}, \`plantingShared=false\`) against BEFORE`, '',+ `${offChecks.filter(c => c.equal).length} of ${offChecks.length} fixtures are identical on draws, pipelines bound, triangles and per-system draws.${offChecks.some(c => !c.equal) ? ' Differences: ' + offChecks.filter(c => !c.equal).map(c => `${c.tier} ${c.fixture} (${c.detail})`).join('; ') + '.' : ''} This isolates the planting: with it off, the MSAA discard and every kit change leave the counts of the scene exactly where BEFORE had them.`);+}+md.push('', problems.length ? `## Problems\n\n${problems.map(p => `- ${p}`).join('\n')}` : '## Problems\n\nNone: every fixture outside the drive workload differs from BEFORE in the planting system only.', '');+writeFileSync(resolve(out, 'counts-table.md'), md.join('\n'));+writeFileSync(resolve(out, 'counts-table.json'), JSON.stringify({ before: before.label, after: after.label, afterOff: off?.label ?? null, lines: lines.map(l => ({ tier: l.tier, fixture: l.fixture, note: l.note,+ main: [kind(l.before, 'main'), kind(l.after, 'main')], draws: [l.before.draws, l.after.draws], pipelinesUsed: [l.before.pipelinesUsed, l.after.pipelinesUsed], pipelineCache: [l.before.pipelineCache, l.after.pipelineCache], triangles: [l.before.triangles, l.after.triangles] })), offChecks, problems }, null, 1) + '\n');+console.log(`${lines.length} rows; ${problems.length} problems${problems.length ? '\n' + problems.join('\n') : ''}`);+process.exitCode = problems.length ? 1 : 0;diff --git a/scenes/scripts/foundry-floor-parity-images.ts b/scenes/scripts/foundry-floor-parity-images.tsnew file mode 100644index 00000000..5ba4ec05--- /dev/null+++ b/scenes/scripts/foundry-floor-parity-images.ts@@ -0,0 +1,84 @@+// Foundry Floor parity images (draw-optimization step S5): from the captures of scripts/capture-foundry-draw-parity.ts, picks the+// cases that fail either check first and then the passing WebGPU cases with the most differing pixels (Foundry Floor has no shadow,+// so the OD-4 shadow differences are none: what differs is the shared planting's edge pixels), and writes for each four PNGs:+// BEFORE and AFTER at 640 px wide, an amplified difference (the largest channel delta x16 in red over the dimmed AFTER) and a zoomed+// crop of the densest changed area (BEFORE | AFTER side by side, nearest-neighbour x4). The full-size set goes to --out; the same set+// (at most --max images, 640 px wide) goes to --share with images.md, a caption list.+// bun scripts/foundry-floor-parity-images.ts [--parity evidence/draw-after/foundry-floor/parity] [--out evidence/draw-after/foundry-floor/images]+// [--share ../tmp/drawcalls/s5/images/foundry-floor] [--max 12] [--backend webgpu] [--variant defaults]+import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { PNG } from 'pngjs';++const ROOT = resolve(import.meta.dir, '..');+const args = process.argv.slice(2), option = (name: string, fallback: string) => { const at = args.indexOf(name); return at < 0 ? fallback : args[at + 1] ?? fallback; };+const parityDir = resolve(ROOT, option('--parity', 'evidence/draw-after/foundry-floor/parity')), out = resolve(ROOT, option('--out', 'evidence/draw-after/foundry-floor/images')), share = resolve(ROOT, option('--share', '../tmp/drawcalls/s5/images/foundry-floor'));+const max = Number(option('--max', '12')), backend = option('--backend', 'webgpu'), variant = option('--variant', 'defaults');+interface Image { width: number; height: number; data: Uint8Array }+const read = (path: string): Image => { const png = PNG.sync.read(readFileSync(path)); return { width: png.width, height: png.height, data: new Uint8Array(png.data) }; };+const write = (path: string, image: Image) => { const png = new PNG({ width: image.width, height: image.height }); png.data = Buffer.from(image.data); writeFileSync(path, PNG.sync.write(png)); };+const blank = (width: number, height: number): Image => ({ width, height, data: new Uint8Array(width * height * 4).fill(255) });+/** 2x2 box average down to half size. */+function half(image: Image): Image {+ const w = image.width >> 1, h = image.height >> 1, o = blank(w, h);+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) for (let c = 0; c < 3; c++) {+ const at = (dx: number, dy: number) => image.data[((y * 2 + dy) * image.width + x * 2 + dx) * 4 + c]!;+ o.data[(y * w + x) * 4 + c] = Math.round((at(0, 0) + at(1, 0) + at(0, 1) + at(1, 1)) / 4);+ }+ return o;+}+const delta = (a: Image, b: Image, i: number) => Math.max(Math.abs(a.data[i]! - b.data[i]!), Math.abs(a.data[i + 1]! - b.data[i + 1]!), Math.abs(a.data[i + 2]! - b.data[i + 2]!));+/** The largest channel delta x16 in red over the dimmed AFTER; each changed pixel is grown by two pixels so a lone edge pixel still reads after the 2x reduction. */+function amplified(before: Image, after: Image): Image {+ const w = after.width, h = after.height, o = blank(w, h), grown = new Uint8Array(w * h);+ for (let p = 0; p < w * h; p++) {+ const d = delta(before, after, p * 4); if (!d) continue;+ const x = p % w, y = (p / w) | 0;+ for (let yy = Math.max(0, y - 2); yy <= Math.min(h - 1, y + 2); yy++) for (let xx = Math.max(0, x - 2); xx <= Math.min(w - 1, x + 2); xx++) grown[yy * w + xx] = Math.max(grown[yy * w + xx]!, Math.min(255, d * 16));+ }+ for (let p = 0; p < w * h; p++) {+ const i = p * 4, g = grown[p]!;+ if (g) { o.data[i] = 255; o.data[i + 1] = o.data[i + 2] = 255 - g; } else for (let c = 0; c < 3; c++) o.data[i + c] = Math.round(after.data[i + c]! * .35);+ }+ return o;+}+/** The 80x45 window with the most changed pixels (weighted by delta), on a stride of 8. */+function densest(before: Image, after: Image, w = 80, h = 45): { x: number; y: number; pixels: number } {+ let best = { x: 0, y: 0, pixels: -1 };+ const weight = new Float64Array(before.width * before.height);+ for (let p = 0; p < weight.length; p++) weight[p] = delta(before, after, p * 4) ? 1 : 0;+ for (let y = 0; y + h <= before.height; y += 8) for (let x = 0; x + w <= before.width; x += 8) {+ let n = 0; for (let yy = y; yy < y + h; yy++) for (let xx = x; xx < x + w; xx++) n += weight[yy * before.width + xx]!;+ if (n > best.pixels) best = { x, y, pixels: n };+ }+ return best;+}+/** BEFORE | AFTER crops, each 80x45 scaled x4 (320x180), with a 2 px white gutter. */+function zoom(before: Image, after: Image, at: { x: number; y: number }, w = 80, h = 45, k = 4): Image {+ const o = blank(w * k * 2 + 2, h * k);+ for (const [panel, image] of [[0, before], [1, after]] as const) for (let y = 0; y < h * k; y++) for (let x = 0; x < w * k; x++) for (let c = 0; c < 3; c++) {+ o.data[(y * o.width + panel * (w * k + 2) + x) * 4 + c] = image.data[((at.y + (y / k | 0)) * image.width + at.x + (x / k | 0)) * 4 + c]!;+ }+ return o;+}++const summary = JSON.parse(readFileSync(resolve(parityDir, 'parity-summary.json'), 'utf8')) as { results: any[] }; // eslint-disable-line @typescript-eslint/no-explicit-any+const cases = summary.results.filter(r => r.backend === backend && r.variant === variant && existsSync(resolve(parityDir, 'captures', r.backend, `${r.tier}-${r.view}${variant === 'defaults' ? '' : `-${variant}`}-before.png`)));+const failing = cases.filter(r => !r.pass), passing = cases.filter(r => r.pass && r.afterVsBefore.differingPixels > 0).sort((a, b) => b.afterVsBefore.differingPixels - a.afterVsBefore.differingPixels);+// One case per view (the worst tier of it), failing cases first; four images per case, at most --max images.+const picked: any[] = []; // eslint-disable-line @typescript-eslint/no-explicit-any+for (const r of [...failing, ...passing]) if (!picked.some(p => p.view === r.view) && (picked.length + 1) * 4 <= max) picked.push(r);+mkdirSync(out, { recursive: true }); mkdirSync(share, { recursive: true });+const captions: string[] = ['# Foundry Floor parity images', '', `BEFORE is draw-base (main at c734e2a), AFTER is draw-after (HEAD 892d103), ${backend}, 1280x720, frozen clock. Foundry Floor has no shadow pass, so there are no OD-4 shadow differences; what these show is the largest B-06 and thin-line residual, which is the shared planting's edge pixels. Shared files are 640 px wide.`, ''];+for (const r of picked) {+ const name = `${r.tier}-${r.view}${variant === 'defaults' ? '' : `-${variant}`}`, dir = resolve(parityDir, 'captures', r.backend), before = read(resolve(dir, `${name}-before.png`)), after = read(resolve(dir, `${name}-after.png`));+ const at = densest(before, after), diff = amplified(before, after), crop = zoom(before, after, at), files: [string, Image][] = [[`${name}-before.png`, half(before)], [`${name}-after.png`, half(after)], [`${name}-diff.png`, half(diff)], [`${name}-crop.png`, crop]];+ for (const [file, image] of files) { write(resolve(out, file), image); copyFileSync(resolve(out, file), resolve(share, file)); }+ write(resolve(out, `${name}-before-full.png`), before); write(resolve(out, `${name}-after-full.png`), after); write(resolve(out, `${name}-diff-full.png`), diff);+ const dxy = `${r.afterVsBefore.differingPixels} of ${before.width * before.height} pixels differ (max channel delta ${r.afterVsBefore.maxChannelDelta}, ${r.afterVsBefore.over32} over 32 levels; the BEFORE repeat differs in ${r.repeatVsBefore.differingPixels}); B-06 ${r.passingTiles}/${r.tiles} tiles, mean luminance delta ${r.globalMean.toExponential(1)}; ${r.pass ? 'passes both checks' : 'FAILS'}`;+ captions.push(`## ${r.tier} ${r.view}`, '', `- \`${name}-before.png\`: BEFORE (draw-base).`, `- \`${name}-after.png\`: AFTER (draw-after).`, `- \`${name}-diff.png\`: every changed pixel in red, the largest channel delta times 16, over the dimmed AFTER.`,+ `- \`${name}-crop.png\`: BEFORE (left) and AFTER (right) of the densest changed area, the 80x45 window at (${at.x}, ${at.y}) of the 1280x720 frame, magnified 4x without smoothing.`, `- ${dxy}.`, '');+}+if (!picked.length) captions.push('No case differs between BEFORE and AFTER on this backend and variant.', '');+writeFileSync(resolve(share, 'images.md'), captions.join('\n')); writeFileSync(resolve(out, 'images.md'), captions.join('\n'));+console.log(`${picked.length} cases, ${picked.length * 4} images: ${picked.map(p => `${p.tier}-${p.view}`).join(', ')}`);diff --git a/scenes/scripts/make-timing-kit.ts b/scenes/scripts/make-timing-kit.tsnew file mode 100644index 00000000..c042e03f--- /dev/null+++ b/scenes/scripts/make-timing-kit.ts@@ -0,0 +1,241 @@+// S6 timing kit (docs/plans/2026-10-01-draw-optimization-cycle.md): packs two build labels' test outputs per scene+// (packages/<scene>/dist/<label>/test, from scripts/build-scene.ts --mode test), the interleaved A/B runner+// (scripts/timing-ab.ts) bundled for Node 22, the hub helpers (session environment, display mode record/ensure/restore,+// run wrapper), README.txt with the exact commands and MANIFEST.json with every file's size and SHA-256.+// It builds and copies only; it never serves, launches a browser or times anything.+// bun scripts/make-timing-kit.ts [--a draw-base] [--b wavea] [--scenes farm,foundry-floor,golden-gate] [--out dist/timing-kit/<a>-vs-<b>]+import { createHash } from 'node:crypto';+import { cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';+import { existsSync, readdirSync, readFileSync } from 'node:fs';+import { join, relative, resolve, sep } from 'node:path';+import { execFileSync } from 'node:child_process';++const root = resolve(import.meta.dir, '..'), args = process.argv.slice(2);+const option = (name: string, fallback: string) => { const at = args.indexOf(name); return at >= 0 && args[at + 1] && !args[at + 1]!.startsWith('--') ? args[at + 1]! : fallback; };+const a = option('--a', 'draw-base'), b = option('--b', 'wavea'), scenes = option('--scenes', 'farm,foundry-floor,golden-gate').split(',');+const kit = resolve(root, option('--out', `dist/timing-kit/${a}-vs-${b}`));+const sha256 = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex');+const walk = (dir: string): string[] => readdirSync(dir, { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(join(dir, e.name)) : [join(dir, e.name)]);+const posix = (base: string, file: string) => relative(base, file).split(sep).join('/');+const today = (d => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`)(new Date());++for (const label of [a, b]) if (!/^[a-z0-9-]+$/.test(label)) throw new Error(`Label ${label} uses lowercase letters, numbers and hyphens`);+if (existsSync(resolve(kit, 'results')) && readdirSync(resolve(kit, 'results')).length) throw new Error('The existing kit holds results; copy them to evidence/perf before rebuilding the kit');+const builds: Record<string, Record<string, unknown>> = { [a]: {}, [b]: {} };+for (const label of [a, b]) for (const scene of scenes) {+ const source = resolve(root, 'packages', scene, 'dist', label, 'test');+ if (!existsSync(resolve(source, 'index.html'))) throw new Error(`No ${label} test build for ${scene}: bun scripts/build-scene.ts --scene ${scene} --mode test --label ${label}`);+ const record = JSON.parse(readFileSync(resolve(source, 'build.json'), 'utf8'));+ if (record.mode !== 'test' || record.scene !== scene) throw new Error(`${source} is not the ${scene} test build`);+ builds[label]![scene] = { source: posix(root, source), release: record.release, packSha256: record.packSha256, chunks: record.chunks.map((c: { name: string }) => c.name), buildSource: record.source };+}+for (const scene of scenes) if (JSON.stringify((builds[a]![scene] as { packSha256: string }).packSha256) !== JSON.stringify((builds[b]![scene] as { packSha256: string }).packSha256)) throw new Error(`${scene}: ${a} and ${b} carry different asset packs; an A/B compares code on one pack`);++await rm(kit, { recursive: true, force: true }); await mkdir(resolve(kit, 'runner'), { recursive: true }); await mkdir(resolve(kit, 'hub'), { recursive: true });+for (const label of [a, b]) for (const scene of scenes) await cp(resolve(root, 'packages', scene, 'dist', label, 'test'), resolve(kit, 'builds', label, scene), { recursive: true });+const bundle = await Bun.build({ entrypoints: [resolve(root, 'scripts/timing-ab.ts')], target: 'node', format: 'esm', outdir: resolve(kit, 'runner'), naming: 'timing-ab.mjs' });+if (!bundle.success) throw new AggregateError(bundle.logs, 'Runner bundle failed');++// Hub helpers: the 2026-09-30 hub campaign's session-environment method (tools/mkenv.py, common.session_env) and display+// record/restore (tools/env-record.sh, display-restore.sh), made standalone; plus a wrapper that holds off screen blanking.+await writeFile(resolve(kit, 'hub/mkenv.py'), `#!/usr/bin/env python3+"""Print export lines for the running Plasma session's display variables plus PRIME render offload, for eval in a shell.+The method of the 2026-09-30 hub campaign (tools/mkenv.py and common.session_env): plasmashell's environment is readable,+kwin_wayland's is not. Never substitutes headless."""+import pathlib, shlex, sys+KEYS = ['DISPLAY', 'XAUTHORITY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR', 'DBUS_SESSION_BUS_ADDRESS', 'XDG_SESSION_TYPE', 'XDG_CURRENT_DESKTOP', 'XDG_SESSION_ID']+for comm in ('plasmashell', 'kwin_wayland'):+ for proc in sorted(pathlib.Path('/proc').glob('[0-9]*/comm')):+ try:+ if proc.read_text().strip() != comm:+ continue+ data = dict(item.split('=', 1) for item in (proc.parent / 'environ').read_bytes().decode().split('\\0') if '=' in item)+ except (OSError, UnicodeError):+ continue+ if data.get('WAYLAND_DISPLAY') and data.get('DISPLAY'):+ for key in KEYS:+ if data.get(key):+ print(f'export {key}={shlex.quote(data[key])}')+ print('export __NV_PRIME_RENDER_OFFLOAD=1')+ print('export __GLX_VENDOR_LIBRARY_NAME=nvidia')+ print(f'# session from {comm} pid {proc.parent.name}')+ sys.exit(0)+sys.exit('No readable Plasma session process; no display to use and no headless substitution')+`);+await writeFile(resolve(kit, 'hub/display.sh'), `#!/bin/bash+# Display mode for headed timing on the hub (owner rule: 120 Hz on its own display; record before, restore after).+# hub/display.sh record <dir> <tag> kscreen-doctor -o and -j into <dir>/<tag>-display-*+# hub/display.sh ensure <dir> <tag> [hz=120] record, then if an enabled output is not at ~hz, switch it to the mode of+# the same size at ~hz (prints what it did); otherwise changes nothing+# hub/display.sh restore <dir> <before> <now> record <now>; set any output whose mode, scale or position differs back+# Adapted from evidence/perf/hub-2026-09-30/tools (env-record.sh, display-restore.sh). User space only.+set -u+cmd="$1"; dir="$2"; tag="$3"; mkdir -p "$dir"+eval "$(python3 "$(dirname "$0")/mkenv.py")"+record() { kscreen-doctor -o 2>&1 | sed 's/\\x1b\\[[0-9;]*m//g' > "$dir/$1-display-outputs.txt"; kscreen-doctor -j > "$dir/$1-display.json" 2>&1; }+record "$tag"+case "$cmd" in+ record) python3 - "$dir/$tag-display.json" <<'PY'+import json, sys+for o in json.load(open(sys.argv[1]))['outputs']:+ cur = [m for m in o['modes'] if m['id'] == o['currentModeId']]+ print(o['name'], 'enabled', o['enabled'], 'mode', o['currentModeId'], cur[0]['name'] if cur else None, cur[0]['refreshRate'] if cur else None, 'scale', o.get('scale'), 'pos', o.get('pos'))+PY+ ;;+ ensure) python3 - "$dir/$tag-display.json" "\${4:-120}" <<'PY'+import json, subprocess, sys+want = float(sys.argv[2])+for o in json.load(open(sys.argv[1]))['outputs']:+ if not o['enabled']:+ continue+ cur = [m for m in o['modes'] if m['id'] == o['currentModeId']][0]+ if abs(cur['refreshRate'] - want) < 1.5:+ print(f"{o['name']}: mode {cur['id']} {cur['name']} at {cur['refreshRate']:.3f} Hz, already ~{want:g} Hz; nothing changed"); continue+ same = [m for m in o['modes'] if m['size'] == cur['size'] and abs(m['refreshRate'] - want) < 1.5]+ if not same:+ print(f"{o['name']}: no {cur['size']} mode at ~{want:g} Hz; left at {cur['refreshRate']:.3f} Hz"); continue+ cmd = ['kscreen-doctor', f"output.{o['name']}.mode.{same[0]['id']}"]+ print(f"{o['name']}: {cur['refreshRate']:.3f} Hz -> mode {same[0]['id']} at {same[0]['refreshRate']:.3f} Hz:", ' '.join(cmd))+ print(subprocess.run(cmd, capture_output=True, text=True).stdout)+PY+ ;;+ restore) now="$4"; record "$now"; python3 - "$dir/$tag-display.json" "$dir/$now-display.json" <<'PY'+import json, subprocess, sys+before = {o['name']: o for o in json.load(open(sys.argv[1]))['outputs']}+now = {o['name']: o for o in json.load(open(sys.argv[2]))['outputs']}+def mode(o):+ cur = [m for m in o['modes'] if m['id'] == o['currentModeId']]+ return f"{o['currentModeId']} {cur[0]['name'] if cur else None}@{cur[0]['refreshRate'] if cur else None}"+for name, b in before.items():+ n = now.get(name)+ if n is None:+ print(f'{name}: output missing now'); continue+ same = b['currentModeId'] == n['currentModeId'] and b.get('scale') == n.get('scale') and b.get('pos') == n.get('pos') and b['enabled'] == n['enabled']+ print(f"{name}: before {mode(b)} scale {b.get('scale')} pos {b.get('pos')}; now {mode(n)} scale {n.get('scale')} pos {n.get('pos')}; {'UNCHANGED, nothing to restore' if same else 'CHANGED, restoring'}")+ if not same:+ cmd = ['kscreen-doctor', f"output.{name}.mode.{b['currentModeId']}"]+ print(' '.join(cmd)); print(subprocess.run(cmd, capture_output=True, text=True).stdout)+PY+ ;;+ *) echo "usage: display.sh record|ensure|restore <dir> <tag> [...]"; exit 2;;+esac+`);+await writeFile(resolve(kit, 'hub/run.sh'), `#!/bin/bash+# Runs the timing runner headed on the hub's own display, from an SSH shell: the Plasma session's environment with PRIME+# offload (hub/mkenv.py), screen blanking, locking and notifications held off by kde-inhibit (which exits 0 whatever its+# child does, so the runner's exit code is echoed), and the hub's Chrome flags from the 2026-09-30 campaign (flags.txt):+# --ozone-platform=x11 --enable-features=Vulkan (the real NVIDIA WebGPU adapter) --start-fullscreen (the window is the panel).+# hub/run.sh ab --cells farm:high:hero --pairs 3 --seconds 60 --block <name>+cd "$(dirname "$0")/.." || exit 2+eval "$(python3 hub/mkenv.py)" || exit 2+CHROME="\${CHROME:-/opt/google/chrome/chrome}"+kde-inhibit --power --screenSaver --notifications -- sh -c 'node runner/timing-ab.mjs "$@"; echo runner-exit=$?' sh "$@" \\+ --chrome "$CHROME" --chrome-arg --ozone-platform=x11 --chrome-arg --enable-features=Vulkan --chrome-arg --start-fullscreen+`);++const commit = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim();+const status = execFileSync('git', ['status', '--porcelain', '--', 'scripts/timing-ab.ts', 'scripts/make-timing-kit.ts', 'scripts/device-kit.ts', 'scripts/static-server.mjs'], { cwd: root, encoding: 'utf8' }).trim();+const kitName = posix(root, kit), kitDir = kitName.split('/').at(-1)!;+const cellsHub = 'farm:high:hero,golden-gate:minimal:arrival,foundry-floor:high:campus';+const fullHub = (t: string) => [`farm:${t}:hero`, `farm:${t}:living-orbit`, `farm:${t}:tractor-drive`, `golden-gate:${t}:arrival`, `golden-gate:${t}:orbit`, `golden-gate:${t}:drive`, `foundry-floor:${t}:campus`, `foundry-floor:${t}:drive`].join(',');+const readme = `Kiln scenes timing kit (S6, docs/plans/2026-10-01-draw-optimization-cycle.md): interleaved A/B frame time+A = ${a} (before), B = ${b} (after); scenes ${scenes.join(', ')}+Assembled ${today} (local date) by scripts/make-timing-kit.ts from the scenes workspace at ${commit.slice(0, 7)}${status ? ' (runner files uncommitted)' : ''}.+Nothing in this kit has been timed by the assembler.++WHAT IT MEASURES (owner decisions OD-3, OD-5, OD-6, OD-7, OD-12; D-25, D-28, D-41)+ For each cell (scene, tier, view or workload) the runner serves A and B itself on two loopback ports (4400-4489) and runs+ them interleaved, pair by pair, with the order alternating (A B, B A, A B, ...), each run on a fresh page load:+ idle display-rate probe on about:blank, load, ready, governor held at the tier's level 0, the view or workload engaged+ (scene clock running), a warm-up (5 s), then the sample (60 s for evidence; D-41 applies only to 60 s runs).+ Per run: rAF frame interval p50, p95, p99 and max; the share of frames within one and within two display refreshes+ (OD-7: interval < 1.5 and < 2.5 measured periods); D-41 hitch counts (frames over 50 ms, over 100 ms, longest frame);+ load samples during the run (hub: CPU and NVIDIA GPU utilisation every 5 s and the busiest processes outside the+ benchmark; tablet: battery temperature, thermal status and Mali GPU busy every 15 s); the kit's CPU time around+ renderer.render; renderer.info draw calls and triangles sampled every 30 frames (a cross-check that A and B draw the+ same content); the MSAA policy hook (msaaPolicy: absent in ${a}, {discard, active, tripped} where present).+ Before each block: the host preflight (hub: the sealed pilot's 8 x 2 s window, CPU mean < 5 %, max < 12 %, GPU <= 3 %,+ no screen locker, retried every 30 s up to --wait-quiet minutes; this PC: CPU < 20 %, GPU < 10 %; tablet: thermal+ status none or light, battery <= 35 C, then the pilot's tablet window CPU mean < 8 %, max < 12 %, GPU busy <= 3 %).+ Nothing is timed when it fails. Views and workloads per scene:+ farm views ${['hero', 'opposite', 'top', 'eye-height', 'crops', 'fences', 'props', 'watermill-wheel', 'watermill-interior', 'house-interior', 'house-porch', 'house-window-out'].join(' ')}+ workloads living-orbit living-route walk tractor-drive (src/play/workloads.ts)+ golden-gate views arrival postcard pier topdown horizon deck tower span lanes sidewalk traffic (Day preset, capture=1)+ workloads orbit flyover drive (src/camera/workloads.ts, src/play/Driving.tsx)+ foundry-floor views campus pair canopy split bridge roundabout, fab-landing fab-overview fab-spine fab-litho fab-cluster+ fab-stocker fab-gallery fab-section (entered through the arrival canopy); workload drive (the sedan)++CONTENTS+ builds/${a}/<scene>/ ${a} test builds (packages/<scene>/dist/${a}/test), served as A+ builds/${b}/<scene>/ ${b} test builds, served as B (same asset pack per scene as A; checked when the kit was made)+ runner/timing-ab.mjs scripts/timing-ab.ts bundled for Node (ESM; puppeteer-core inside); Node 22.23.2 is the pin+ hub/run.sh headed runner on the hub's display from SSH (session env, PRIME offload, kde-inhibit, hub flags)+ hub/mkenv.py the Plasma session environment (2026-09-30 campaign method)+ hub/display.sh display mode record / ensure 120 Hz / restore (kscreen-doctor)+ MANIFEST.json every file with size and SHA-256, and each build's provenance++HUB (ssh hub; CachyOS, Plasma on Wayland, GTX 1660 Ti Max-Q with PRIME offload, eDP-1 1920x1080 at 120.11 Hz)+ Copy: scp -r ${kitName} hub:kiln-hub/${kitDir} (from the scenes workspace; then on the hub: cd ~/kiln-hub/${kitDir})+ 0. node runner/timing-ab.mjs verify+ Each timing block (D=results/<block>):+ 1. node runner/timing-ab.mjs quiet --out $D/quiet-before.json (also run from this PC over ssh and kept beside the results)+ 2. hub/display.sh ensure $D display-before 120 (records the mode; switches to 120 Hz only if needed)+ 3. hub/run.sh ab --a builds/${a} --b builds/${b} --cells <cells> --pairs <n> --seconds <s> --block <block>+ 4. hub/display.sh restore $D display-before display-after+ Dry run (plumbing, 10 s, 1 pair, numbers not evidence):+ hub/run.sh ab --cells farm:high:hero,golden-gate:minimal:arrival,foundry-floor:high:campus --pairs 1 --seconds 10 --prime 0 --block dry-<date>+ MSAA-only A/B (${a} vs ${b}), 60 s, 3 pairs (about 35 minutes):+ hub/run.sh ab --cells ${cellsHub} --pairs 3 --seconds 60 --block msaa-<date>++TABLET (from this PC; Samsung SM-X518U, serial R52X405L12T; the device kit's adb at+ C:/Users/Mattm/AppData/Local/Microsoft/WinGet/Packages/Google.PlatformTools_Microsoft.Winget.Source_8wekyb3d8bbwe/platform-tools/adb.exe)+ Run from this kit directory with the maintainer Node (C:/Users/Mattm/AppData/Roaming/fnm/node-versions/v22.23.2/installation/node.exe):+ node runner/timing-ab.mjs transient --device tablet --out results/transient-tablet.json (read-only WebGPU check)+ node runner/timing-ab.mjs ab --device tablet --cells farm:minimal:hero --pairs 1 --seconds 10 --prime 0 --block tablet-dry-<date>+ node runner/timing-ab.mjs ab --device tablet --cells farm:minimal:hero,farm:economy:hero,golden-gate:minimal:arrival --pairs 3 --seconds 60 --block tablet-msaa-<date>+ Per run the runner maps only that run's port (adb reverse tcp:P tcp:P) and a DevTools forward (4495-4499), connects,+ opens one tab, measures, closes it, removes both mappings and records that the forward and reverse lists are empty;+ it refuses to start when mappings exist. It waits up to --cool-wait minutes (10) for thermal status none/light and a+ battery at or under 35 C before each run, stops the block if the tablet warms past that, and records battery+ temperature, thermal status and GPU busy before, during (every 15 s) and after each run. The tablet stays on its+ tier per D-25 (minimal); economy is measured for OD-12 only. Frame time is the tablet's own (vsync-bound at its panel+ rate, measured per run); readyMs is indicative (served from this PC over USB).++THIS PC (only when its quiet check passes; it is often under load)+ node runner/timing-ab.mjs quiet --rule pc (exit 3 when not quiet: then do not time here)+ node runner/timing-ab.mjs ab --cells <cells> --pairs 3 --seconds 60 --block pc-<date> (the block preflight applies the same rule)++FULL BEFORE/AFTER (pending the final optimized builds, label draw-after)+ In the scenes workspace:+ bun scripts/build-scene.ts --scene farm,foundry-floor,golden-gate --mode test --label draw-after+ bun scripts/make-timing-kit.ts --a draw-base --b draw-after+ Hub, per tier t in high balanced economy minimal (8 cells x 3 pairs x 2 sides x ~75 s, about 1 h per tier):+ hub/run.sh ab --a builds/draw-base --b builds/draw-after --cells <fullHub(t)> --pairs 3 --seconds 60 --block full-<t>-<date>+ with <fullHub(t)> = ${fullHub('<t>')}+ Tablet: --cells farm:minimal:hero,farm:minimal:tractor-drive,golden-gate:minimal:arrival,golden-gate:minimal:drive,foundry-floor:minimal:campus,foundry-floor:minimal:drive+ then the OD-12 economy row: --cells farm:economy:hero,farm:economy:tractor-drive,golden-gate:economy:arrival,foundry-floor:economy:campus++OUTPUT (results/<block>/)+ block.json options, plan, builds (label, chunks, source), preflight or tablet cool/quiet records, browser, every run's+ headline values and, on the tablet, the mapping lists after each run+ runs/<scene>-<tier>-<name>-pair<k>-<A|B>.json one run: checks and validity, display rate, frame stats, refresh shares,+ hitches and D-41 verdict, CPU render, draws, load before/during/after, busiest external processes,+ environment (adapter, user agent, canvas buffer), every frame interval (frameIntervalsMs)+ summary.json, summary.md per cell and side: median (min-max) over valid runs; paired B - A per pair with the median+ difference and how many pairs B was lower or higher; p95 ratio B/A+ node runner/timing-ab.mjs summary --dir results/<block> rebuilds the summary from runs/+ A run is valid only when the tier held at level 0, the scene clock advanced, the workload was engaged (and the camera+ moved for workloads), the page stayed visible without scene errors, the sample covered at least 90 % of its time and+ the display rate was measured and consistent with the frames. Repeat an invalid run's block; do not shorten it.++COPY BACK+ Copy results/<block>/ unchanged, with the quiet and display records, to+ C:/Users/Mattm/X/kiln-draw-optimization/scenes/evidence/perf/<host>-<YYYY-MM-DD>/ (ignored).+`;+await writeFile(resolve(kit, 'README.txt'), readme);+const files = walk(kit).map(f => posix(kit, f)).filter(p => p !== 'MANIFEST.json').sort().map(path => { const data = readFileSync(resolve(kit, path)); return { path, bytes: data.length, sha256: sha256(data) }; });+const runnerSource = await readFile(resolve(root, 'scripts/timing-ab.ts'));+await writeFile(resolve(kit, 'MANIFEST.json'), JSON.stringify({ schema: 'kiln.timing-kit/1', created: new Date().toISOString(), scenesCommit: commit, runnerFilesStatus: status || 'committed',+ labels: { A: a, B: b }, scenes, builds, runner: { source: 'scripts/timing-ab.ts', sourceSha256: sha256(runnerSource), bundled: 'runner/timing-ab.mjs', nodePin: '22.23.2' },+ totals: { files: files.length, bytes: files.reduce((s, f) => s + f.bytes, 0) }, files }, null, 2) + '\n');+console.log(JSON.stringify({ kit: kitName, files: files.length, bytes: files.reduce((s, f) => s + f.bytes, 0), runnerBytes: files.find(f => f.path === 'runner/timing-ab.mjs')?.bytes }));diff --git a/scenes/scripts/run-farm-shadow-ab.ts b/scenes/scripts/run-farm-shadow-ab.tsnew file mode 100644index 00000000..0d0f0b0c--- /dev/null+++ b/scenes/scripts/run-farm-shadow-ab.ts@@ -0,0 +1,125 @@+// S5 Farm checks for the wave-B shadow and merge wiring, on one test build with its dev parameters as the A/B switch+// (OFF = ?heroMerge=false&shadowCache=false&standIns=false&casterTexels=0). Counts and pixels only, no timing.+// creations: after ready (live clock, ambient on), a door toggle, the tractor-drive workload and the walk workload must+// create no render pipeline or shader module (GPUDevice wraps installed before any page script, and three's pipeline+// cache); bind groups and buffers are listed beside them for both settings.+// live: per shadow tier at the hero view with ambient life on (the live clock), draws per pass on a stable frame (the live+// map carries the herd and the rotors) and the static-map re-arms over --live-frames frames (default 600; review RF-4+// measured 12 in 3600 frames, about one every 5 s, so use 3600 for a rate).+// parity: B-06 conditions (scripts/capture-farm-parity.ts: 1280x720, high, frozen clock, ambient off, 3 s settle) at the+// hero view, the house interior and the open front door; OFF, OFF repeat and ON, judged by compareParityImages with the+// OFF repeat as noise, plus exact pixel counts. Each lever set is also captured alone (review RF-2): MERGE (the hero merge,+// shadow levers off) and SHADOW (cache, stand-ins and threshold, ?heroMerge=false), so a difference is attributed to the+// OD-18 merge or the OD-4 shadow allowance by measurement.+// bun scripts/run-farm-shadow-ab.ts [--build packages/farm/dist/waveb-farm/test] [--dest ../tmp/drawcalls/wave-b/farm] [--only creations,live,parity]+// [--live-frames 600] [--live-tiers economy,balanced,high] [--views hero,house-interior,play-house-door]+import { readFileSync } from 'node:fs';+import { mkdir, writeFile } from 'node:fs/promises';+import { resolve } from 'node:path';+import { PNG } from 'pngjs';+import type { Browser, Page } from 'puppeteer-core';+import { launchChrome, serveOwned, waitForReady, workspacePath } from '../packages/scene-kit/src/testing/node';+import { captureFarmNew, PLAY_FIXTURES, type CapturedFarm } from './capture-farm-parity';+import { compareParityImages } from './parity-images';++const args = process.argv.slice(2), value = (key: string, fallback: string) => { const at = args.indexOf(key); return at < 0 ? fallback : args[at + 1] ?? fallback; };+const workspace = resolve(import.meta.dir, '..'), build = value('--build', 'packages/farm/dist/waveb-farm/test'), dest = resolve(workspace, value('--dest', '../tmp/drawcalls/wave-b/farm'));+const only = new Set(value('--only', 'creations,live,parity').split(',')), liveFrames = Number(value('--live-frames', '600'));+const views = value('--views', 'hero,house-interior,play-house-door').split(','), liveTiers = value('--live-tiers', 'economy,balanced,high').split(',');+const OFF = 'heroMerge=false&shadowCache=false&standIns=false&casterTexels=0', SETTINGS = { on: '', off: OFF } as const;+/** One lever set alone against OFF (RF-2): the merge without the shadow levers, the shadow levers without the merge. */+const ALONE = { merge: 'shadowCache=false&standIns=false&casterTexels=0', shadow: 'heroMerge=false' } as const;+// A partial run (--only) keeps the other sections of an earlier report for the same build.+const previous = (() => { try { const r = JSON.parse(readFileSync(resolve(dest, 'shadow-ab.json'), 'utf8')); return r.build === build ? r : {}; } catch { return {}; } })();+const report: Record<string, unknown> = { ...previous, schema: 'kiln.farm-shadow-ab/1', build, off: OFF };+delete report.error;+const save = () => writeFile(resolve(dest, 'shadow-ab.json'), JSON.stringify(report, null, 1) + '\n');++/** Installed before any page script: creation counts on the WebGPU device. */+function installCreations() {+ const w = window as any, c: Record<string, number> = w.__kilnCreations = {}; // eslint-disable-line @typescript-eslint/no-explicit-any+ for (const m of ['createRenderPipeline', 'createRenderPipelineAsync', 'createShaderModule', 'createBindGroup', 'createBuffer', 'createTexture']) {+ const p = w.GPUDevice?.prototype, original = p?.[m]; if (typeof original !== 'function') continue;+ p[m] = function (this: unknown, ...a: unknown[]) { c[m] = (c[m] ?? 0) + 1; return original.apply(this, a); };+ }+}+const scene = (page: Page) => ({+ frames: (n: number) => page.evaluate(k => (window as any).__kilnScene.waitFrames(k), n), // eslint-disable-line @typescript-eslint/no-explicit-any+ invoke: (name: string, ...a: unknown[]) => page.evaluate((n, x) => (window as any).__kilnScene.invoke(n, ...x), name, a), // eslint-disable-line @typescript-eslint/no-explicit-any+ run: (fn: string, ...a: unknown[]) => page.evaluate((f, x) => (window as any).__kilnScene[f](...x), fn, a), // eslint-disable-line @typescript-eslint/no-explicit-any+ snapshot: () => page.evaluate(() => { const s = (window as any).__kilnScene, st = s.stats(); return { gpu: { ...(window as any).__kilnCreations }, pipelines: st.pipelines, programs: st.programs, shadow: st.counts?.shadow ?? null }; }), // eslint-disable-line @typescript-eslint/no-explicit-any+});+async function open(browser: Browser, url: string, size: [number, number]) {+ const page = await browser.newPage(), messages: string[] = [];+ page.on('console', m => { if (m.type() === 'error' || m.type() === 'warn') messages.push(`${m.type()}: ${m.text().slice(0, 300)}`); });+ page.on('pageerror', e => messages.push(`pageerror: ${String(e).slice(0, 300)}`));+ await page.setViewport({ width: size[0], height: size[1], deviceScaleFactor: 1 }); await page.evaluateOnNewDocument(installCreations);+ await page.goto(url, { waitUntil: 'load', timeout: 180_000 }); await waitForReady(page);+ return { page, messages };+}+const delta = (a: Awaited<ReturnType<ReturnType<typeof scene>['snapshot']>>, b: typeof a) => ({ ...Object.fromEntries([...new Set([...Object.keys(a.gpu), ...Object.keys(b.gpu)])].map(k => [k, (b.gpu[k] ?? 0) - (a.gpu[k] ?? 0)])), pipelineCache: b.pipelines - a.pipelines, programs: b.programs - a.programs });++let hosted: Awaited<ReturnType<typeof serveOwned>> | undefined, browser: Browser | undefined;+try {+ await mkdir(dest, { recursive: true });+ hosted = await serveOwned(workspacePath(workspace, build)); browser = await launchChrome({ workspace, name: 'farm-shadow-ab', windowSize: [1280, 720] });+ report.browser = await browser.version();+ if (only.has('creations')) {+ const rows: unknown[] = []; report.creations = rows;+ for (const tier of ['high', 'economy']) for (const [setting, query] of Object.entries(SETTINGS)) {+ const { page, messages } = await open(browser, `${hosted.url}/?tier=${tier}&view=hero${query ? '&' + query : ''}`, [1280, 720]), s = scene(page);+ try {+ await s.frames(60); const ready = await s.snapshot(), phases: Record<string, unknown> = {};+ let last = ready; const phase = async (name: string) => { await s.frames(60); const now = await s.snapshot(), sim = await s.invoke('simState') as any; phases[name] = { ...delta(last, now), staticReArms: (now.shadow?.staticRenders ?? 0) - (last.shadow?.staticRenders ?? 0), liveCasters: now.shadow?.liveCasters ?? null, tractor: sim.tractor.position, player: sim.player.position, drivenMeters: sim.drivenMeters }; last = now; }; // eslint-disable-line @typescript-eslint/no-explicit-any+ await s.run('setPlaying', true); await s.frames(2); await s.invoke('teleport', 'house'); await s.frames(3); await phase('enter play at the house');+ await s.invoke('toggleDoor', 'home-0');+ await page.waitForFunction(() => (window as any).__kilnScene.invoke('simState').doors.some((d: any) => d.id === 'home-0' && Math.abs(d.amount - 1) < 1e-3), { timeout: 60_000 }); // eslint-disable-line @typescript-eslint/no-explicit-any+ await phase('front door opened');+ await s.invoke('toggleDoor', 'home-0'); await page.waitForFunction(() => (window as any).__kilnScene.invoke('simState').doors.some((d: any) => d.id === 'home-0' && Math.abs(d.amount) < 1e-3), { timeout: 60_000 }); // eslint-disable-line @typescript-eslint/no-explicit-any+ await phase('front door closed');+ await s.run('setPlaying', false); await s.frames(3);+ await s.run('runWorkload', 'tractor-drive'); await s.frames(300); await s.run('runWorkload', ''); await phase('tractor-drive workload, 300 frames');+ await s.run('setPlaying', false); await s.frames(3);+ await s.run('runWorkload', 'walk'); await s.frames(300); await s.run('runWorkload', ''); await phase('walk workload, 300 frames');+ const total = delta(ready, last);+ rows.push({ tier, setting, ready, phases, total, noPipelineOrShader: !(total.createRenderPipeline || total.createRenderPipelineAsync || total.createShaderModule || total.pipelineCache || total.programs), messages });+ console.log(`creations ${tier} ${setting}: ${JSON.stringify(total)}`);+ } finally { await page.close(); }+ await save();+ }+ }+ if (only.has('live')) {+ const rows: unknown[] = []; report.live = rows;+ for (const tier of liveTiers) for (const [setting, query] of Object.entries(SETTINGS)) {+ const { page, messages } = await open(browser, `${hosted.url}/?tier=${tier}&view=hero${query ? '&' + query : ''}`, [1920, 1080]), s = scene(page);+ try {+ await s.frames(120); const before = await s.snapshot(); await s.frames(liveFrames); const after = await s.snapshot();+ const r = await page.evaluate(() => (window as any).__kilnScene.probeFrames({ frames: 8, stableFrames: 3, maxFrames: 600, timeoutMs: 150_000 })) as any; // eslint-disable-line @typescript-eslint/no-explicit-any+ const passes = r.passes.map((p: any) => ({ kind: p.kind, label: p.label, draws: p.draws, pipelines: p.pipelines, bySystem: Object.fromEntries(Object.entries(p.bySystem).map(([k, v]: [string, any]) => [k, v.draws])) })); // eslint-disable-line @typescript-eslint/no-explicit-any+ rows.push({ tier, setting, stable: r.stable, passes, totals: { draws: r.totals.draws, pipelines: r.totals.pipelinesUsed }, frames: liveFrames, staticReArms: after.shadow && before.shadow ? after.shadow.staticRenders - before.shadow.staticRenders : null, shadow: after.shadow, messages });+ console.log(`live ${tier} ${setting}: ${passes.map((p: any) => `${p.label} ${p.draws}`).join(', ')}; static re-arms in ${liveFrames} frames ${after.shadow ? after.shadow.staticRenders - before.shadow.staticRenders : '-'}`); // eslint-disable-line @typescript-eslint/no-explicit-any+ } finally { await page.close(); }+ await save();+ }+ }+ if (only.has('parity')) {+ const rows: unknown[] = []; report.parity = rows; const ports = new Set([hosted.port]), dir = resolve(dest, 'parity'); await mkdir(dir, { recursive: true });+ const exact = (a: CapturedFarm['png'], b: CapturedFarm['png']) => { let pixels = 0, max = 0; for (let i = 0; i < a.data.length; i += 4) { let d = 0; for (let c = 0; c < 3; c++) d = Math.max(d, Math.abs(a.data[i + c]! - b.data[i + c]!)); if (d) { pixels++; max = Math.max(max, d); } } return { differingPixels: pixels, differingFraction: pixels / (a.width * a.height), maxChannelDifference: max }; };+ for (const view of views) {+ const play = PLAY_FIXTURES[view], shot = (query: string, file: string) => captureFarmNew({ browser: browser!, url: `${hosted!.url}/${query ? '?' + query : ''}`, ports, backend: 'webgpu', view, file: resolve(dir, `${view}-${file}.png`), ...(play ? { play } : {}) });+ const off = await shot(SETTINGS.off, 'off'), repeat = await shot(SETTINGS.off, 'off-repeat'), on = await shot(SETTINGS.on, 'on');+ const metric = compareParityImages(off.png, repeat.png, on.png), { diff, tiles, ...numbers } = metric;+ await writeFile(resolve(dir, `${view}-diff.png`), PNG.sync.write({ width: diff.width, height: diff.height, data: Buffer.from(diff.data) }));+ const counts = (c: CapturedFarm) => ({ drawCalls: (c.stats.render as any)?.drawCalls, triangles: (c.stats.render as any)?.triangles, pipelines: c.stats.pipelines, programs: c.stats.programs, shadow: (c.stats.counts as any)?.shadow ?? null }); // eslint-disable-line @typescript-eslint/no-explicit-any+ const alone: Record<string, { pass: boolean; passingTiles: number; globalMean: number; exactVsOff: ReturnType<typeof exact>; exactVsOn: ReturnType<typeof exact>; counts: ReturnType<typeof counts> }> = {};+ for (const [name, query] of Object.entries(ALONE)) {+ const one = await shot(query, name), m = compareParityImages(off.png, repeat.png, one.png);+ alone[name] = { pass: m.pass, passingTiles: m.passingTiles, globalMean: m.globalMean, exactVsOff: exact(off.png, one.png), exactVsOn: exact(on.png, one.png), counts: counts(one) };+ }+ rows.push({ view, metric: numbers, failingTiles: tiles.filter(t => !t.pass).map(t => ({ x: t.x, y: t.y, mean: t.mean, threshold: t.threshold })), exactOnOff: exact(off.png, on.png), exactOffRepeat: exact(off.png, repeat.png), alone, counts: { off: counts(off), on: counts(on) } });+ console.log(`parity ${view}: pass ${numbers.pass} (tiles ${numbers.passingTiles}/144, global mean ${numbers.globalMean.toExponential(3)}); on vs off differing pixels ${exact(off.png, on.png).differingPixels}, max ${exact(off.png, on.png).maxChannelDifference}; off repeat ${exact(off.png, repeat.png).differingPixels}; merge alone ${alone.merge!.exactVsOff.differingPixels}, shadow alone ${alone.shadow!.exactVsOff.differingPixels}`);+ await save();+ }+ }+} catch (error) { report.error = error instanceof Error ? error.stack : String(error); throw error; }+finally { await browser?.close(); await hosted?.close(); await save(); }diff --git a/scenes/scripts/scene-fixtures.ts b/scenes/scripts/scene-fixtures.tsnew file mode 100644index 00000000..7882d94b--- /dev/null+++ b/scenes/scripts/scene-fixtures.ts@@ -0,0 +1,123 @@+// Named views and workloads per scene, as hook-driven fixtures (S1 count probe; reusable by a B-06 A/B runner).+// Each table gives the page query shared by its fixtures, a prepare step after ready, and the fixtures in run order. A+// fixture with its own `query` gets its own page load (Golden Gate flyovers are sought from the URL). Every fixture+// leaves the scene clock frozen (timeScale 0) before it returns, so the probe settles on a still frame; workloads run+// the clock only long enough to reach their state, so their counts are a representative state, not a pinned pose.+import assert from 'node:assert/strict';+import type { Page } from 'puppeteer-core';+import type { SceneId } from './build-scene';++export interface ProbeFixture { id: string; hudLabel: string | null; query?: Record<string, string>; enter(page: Page): Promise<unknown>; exit?(page: Page): Promise<void> }+export interface SceneFixtureTable { scene: SceneId; query: Record<string, string>; prepare(page: Page): Promise<void>; fixtures: ProbeFixture[] }+const TIMEOUT = 120_000;++export const invoke = (page: Page, name: string, ...args: unknown[]) => page.evaluate((n, a) => (window as any).__kilnScene.invoke(n, ...a), name, args); // eslint-disable-line @typescript-eslint/no-explicit-any+export const frames = (page: Page, n: number) => page.evaluate(count => (window as any).__kilnScene.waitFrames(count), n); // eslint-disable-line @typescript-eslint/no-explicit-any+const timeScale = (page: Page, scale: number) => page.evaluate(s => (window as any).__kilnScene.setTimeScale(s), scale); // eslint-disable-line @typescript-eslint/no-explicit-any+const playing = (page: Page, on: boolean) => page.evaluate(v => (window as any).__kilnScene.setPlaying(v), on); // eslint-disable-line @typescript-eslint/no-explicit-any+const workload = (page: Page, name: string) => page.evaluate(n => (window as any).__kilnScene.runWorkload(n), name); // eslint-disable-line @typescript-eslint/no-explicit-any+/** Polls a hook through the page until `test` holds on its result. */+async function until(page: Page, hook: string, args: unknown[], test: string) {+ await page.waitForFunction((n, a, t) => { const value = (window as any).__kilnScene.invoke(n, ...a); return new Function('v', `return (${t});`)(value); }, { timeout: TIMEOUT, polling: 100 }, hook, args, test); // eslint-disable-line @typescript-eslint/no-explicit-any+}+/**+ * Runs a workload on a live clock for `n` frames once `ready` holds, then stops it, releases its held input (a blur of+ * the scene root clears the kit's input) and freezes the clock. Play systems step on the frame's own delta, not the+ * scaled clock, so `still` (a hook read compared 20 frames apart) waits until whatever the input moved has stopped.+ */+async function runFor(page: Page, name: string, hook: string, ready: string, n: number, still?: (value: any) => unknown) { // eslint-disable-line @typescript-eslint/no-explicit-any+ await timeScale(page, 1); await workload(page, name);+ await until(page, hook, [], ready); await frames(page, n);+ await workload(page, ''); await page.focus('.ks-root'); await page.evaluate(() => (document.querySelector('.ks-root') as HTMLElement).blur());+ await timeScale(page, 0); await frames(page, 2);+ if (still) await rest(page, hook, still);+}+const farmRest = (s: any) => [s.player.position, s.player.yaw, s.tractor.position, s.tractor.yaw, s.camera.position]; // eslint-disable-line @typescript-eslint/no-explicit-any+/** Polls `hook` 20 frames apart until `pick` of it repeats (a chase camera's lag runs on the frame's own delta). */+async function rest(page: Page, hook: string, pick: (value: any) => unknown) { // eslint-disable-line @typescript-eslint/no-explicit-any+ for (let i = 0, last = ''; i < 60; i++) { const now = JSON.stringify(pick(await invoke(page, hook))); if (now === last) return; last = now; await frames(page, 20); }+ throw new Error(`${hook}: the scene did not come to rest`);+}++export const FARM_VIEWS = ['hero', 'opposite', 'top', 'eye-height', 'crops', 'fences', 'props', 'watermill-wheel', 'watermill-interior', 'house-interior', 'house-porch', 'house-window-out'] as const;+const FARM_PLAY = { 'play-yard': { to: 'yard' }, 'play-house': { to: 'house' }, 'play-bridge': { to: 'bridge' }, 'play-house-door': { to: 'house', door: 'home-0' } } as const;+export const FARM_FIXTURES: SceneFixtureTable = {+ scene: 'farm', query: { freeze: '1', time: '0', view: 'hero' },+ async prepare(page) {+ await page.evaluate(() => { const s = (window as any).__kilnScene; s.feedFrameTimes([]); s.setAmbient(false); s.setTimeScale(0); s.setTime(0); }); // eslint-disable-line @typescript-eslint/no-explicit-any+ const names = await invoke(page, 'viewNames') as string[];+ assert.deepEqual([...names].sort(), [...FARM_VIEWS].sort(), 'Farm layout views match the fixture table');+ },+ fixtures: [+ ...FARM_VIEWS.map((view): ProbeFixture => ({ id: view, hudLabel: view === 'hero' ? 'Overview (landing)' : null, enter: page => invoke(page, 'setView', view) })),+ ...Object.entries(FARM_PLAY).map(([id, f]): ProbeFixture => ({ id, hudLabel: id === 'play-yard' ? 'Walk the farm' : null, async enter(page) {+ await playing(page, true); await frames(page, 2);+ assert.equal(await invoke(page, 'teleport', f.to), true, `Farm destination ${f.to}`); await frames(page, 3);+ if ('door' in f) {+ await invoke(page, 'toggleDoor', f.door); await timeScale(page, 1);+ await until(page, 'simState', [], `v.doors.some(d => d.id === '${f.door}' && d.target === 1 && Math.abs(d.amount - 1) < 1e-3)`);+ await timeScale(page, 0);+ }+ }, async exit(page) { if ('door' in f) { await invoke(page, 'toggleDoor', f.door); await timeScale(page, 1); await until(page, 'simState', [], `v.doors.some(d => d.id === '${f.door}' && Math.abs(d.amount) < 1e-3)`); await timeScale(page, 0); } } })),+ { id: 'walk', hudLabel: 'Walk the farm (walk workload)', enter: page => runFor(page, 'walk', 'simState', 'v.active', 120, farmRest), exit: page => playing(page, false).then(() => frames(page, 3)) },+ { id: 'tractor-drive', hudLabel: 'Drive tractor', enter: page => runFor(page, 'tractor-drive', 'simState', 'v.driving', 120, farmRest), exit: page => playing(page, false).then(() => frames(page, 3)) },+ ],+};++export const FOUNDRY_CAMPUS_VIEWS = { campus: 'Campus', pair: 'One pair', canopy: 'Arrival', split: 'The split', bridge: null, roundabout: null } as const;+export const FOUNDRY_FAB_VIEWS = { landing: 'Gallery', overview: 'Overview', spine: null, litho: null, cluster: null, stocker: 'Transfers', gallery: null, section: null } as const;+export const FOUNDRY_FIXTURES: SceneFixtureTable = {+ scene: 'foundry-floor', query: { freeze: '1', time: '0', capture: '1' },+ async prepare(page) {+ await page.evaluate(() => (window as any).__kilnScene.feedFrameTimes([])); // eslint-disable-line @typescript-eslint/no-explicit-any+ await until(page, 'driveTraffic', [1], 'v !== null');+ },+ fixtures: [+ ...Object.entries(FOUNDRY_CAMPUS_VIEWS).map(([view, label]): ProbeFixture => ({ id: `campus-${view}`, hudLabel: label, async enter(page) { await invoke(page, 'campusView', view); await frames(page, 18); } })),+ { id: 'drive', hudLabel: 'Drive the sedan', async enter(page) {+ // Two seconds of fixed steps at throttle .8, then the car is set down where it got to at rest (the drive steps on the+ // frame's own delta, so a moving car would never settle) and the chase camera comes to rest behind it.+ await playing(page, true); await until(page, 'driveState', [], 'v !== null');+ const at = await invoke(page, 'driveAdvance', 2, { throttle: .8 }) as { centre: [number, number]; headingDeg: number };+ await invoke(page, 'setDriveInput', { throttle: 0 }); await invoke(page, 'placeCar', at.centre[0], at.centre[1], at.headingDeg, 0);+ await rest(page, 'driveState', v => [v.centre, v.camera.position]);+ }, async exit(page) { await invoke(page, 'setDriveInput', null); await playing(page, false); await until(page, 'driveState', [], 'v === null'); await frames(page, 6); } },+ ...Object.entries(FOUNDRY_FAB_VIEWS).map(([view, label], index): ProbeFixture => ({ id: `fab-${view}`, hudLabel: index === 0 ? `Enter the fab → ${label}` : label, async enter(page) {+ if (index === 0) {+ // tests/tools/capture-local-v09.ts enter(): Arrival, wait for the canopy prompt, enter, wait for the interior.+ await invoke(page, 'campusView', 'canopy'); await until(page, 'campusState', [], 'v && v.canEnter');+ await invoke(page, 'campusEnter'); await until(page, 'campusPlace', [], 'v.interiorReady && !v.moving');+ await page.evaluate(() => (window as any).__kilnScene.setTimeScale(0)); // eslint-disable-line @typescript-eslint/no-explicit-any+ }+ await invoke(page, 'ffSetView', view); await frames(page, 12);+ } })),+ ],+};++export const GG_CAMERAS = ['arrival', 'postcard', 'pier', 'topdown', 'horizon', 'deck', 'tower', 'span', 'lanes', 'sidewalk', 'traffic'] as const;+const GG_FLIGHTS = { 'postcard-sweep': 'Postcard sweep', 'tower-rise': 'Tower rise', 'deck-run': 'Deck run', 'fog-roll': 'Fog roll' } as const;+const GG_QUERY = { capture: '1', hud: '0', preset: 'day', cam: 'arrival', time: '12' };+export const GOLDEN_GATE_FIXTURES: SceneFixtureTable = {+ scene: 'golden-gate', query: GG_QUERY,+ async prepare(page) { await page.evaluate(() => (window as any).__kilnScene.feedFrameTimes([])); }, // eslint-disable-line @typescript-eslint/no-explicit-any+ fixtures: [+ ...GG_CAMERAS.map((cam): ProbeFixture => ({ id: cam, hudLabel: cam === 'arrival' ? 'Overview (landing)' : null, async enter(page) { await invoke(page, 'setView', cam); await frames(page, 20); } })),+ ...(['golden', 'fog'] as const).map((preset): ProbeFixture => ({ id: `preset-${preset}`, hudLabel: preset === 'golden' ? 'Golden hour' : 'Fog', async enter(page) {+ await invoke(page, 'setView', 'arrival'); await invoke(page, 'setPreset', preset); await frames(page, 20);+ }, async exit(page) { await invoke(page, 'setPreset', 'day'); await frames(page, 6); } })),+ { id: 'drive', hudLabel: 'Drive the sedan', async enter(page) {+ // tests/tools/perf-local.ts X-02 drive fixture (northbound middle lane 300 m south of midspan at 25 m/s, 90 live+ // frames), then the car is set down at rest where it got to and the chase camera settles (the drive steps on the+ // frame's own delta, so a moving car would never give a still frame).+ await timeScale(page, 1); await playing(page, true); await until(page, 'driveState', [], 'v !== null');+ await invoke(page, 'placeCar', 'nb-middle', -300, 25); await frames(page, 90); await timeScale(page, 0);+ const at = await invoke(page, 'driveState') as { sigma: number };+ await invoke(page, 'setDriveInput', { throttle: 0 }); await invoke(page, 'placeCar', 'nb-middle', at.sigma, 0);+ await rest(page, 'driveState', v => [v.x, v.z, v.camera.position]);+ }, async exit(page) { await invoke(page, 'setDriveInput', null); await playing(page, false); await frames(page, 6); } },+ ...Object.entries(GG_FLIGHTS).map(([flight, label]): ProbeFixture => ({ id: `flight-${flight}`, hudLabel: label,+ query: { ...GG_QUERY, preset: flight === 'fog-roll' ? 'fog' : 'day', flight, flightAt: '0.5' }, async enter(page) { await frames(page, 20); } })),+ ],+};++export const SCENE_FIXTURES: Readonly<Record<SceneId, SceneFixtureTable>> = { farm: FARM_FIXTURES, 'foundry-floor': FOUNDRY_FIXTURES, 'golden-gate': GOLDEN_GATE_FIXTURES };diff --git a/scenes/scripts/tests/count-probe.test.ts b/scenes/scripts/tests/count-probe.test.tsnew file mode 100644index 00000000..2a60bf14--- /dev/null+++ b/scenes/scripts/tests/count-probe.test.ts@@ -0,0 +1,21 @@+import { expect, test } from 'bun:test';+import { compareRows, type CountRow } from '../count-probe';+import { packProblems } from '../build-scene';+import { existsSync } from 'node:fs';+import { resolve } from 'node:path';++// The runner's pure helpers (GPU join, standard what-ifs, provenance) are tested in scene-kit tests/testing/probe-report.test.ts.+test('X-02 rows check pipelines only between fresh-page runs', () => {+ const row = (draws: number, pipelineCache: number): CountRow => ({ scene: 'farm', tier: 'high', fixture: 'hero', draws, triangles: 1000, pipelineCache, programs: 0, memory: { geometries: 1, textures: 1 } });+ const [fresh] = compareRows([row(100, 70)], [row(100, 60)], true), [shared] = compareRows([row(100, 70)], [row(100, 60)], false);+ expect([fresh!.pass, fresh!.pipelinesComparable, shared!.pass, shared!.pipelinesComparable]).toEqual([false, true, true, false]);+ expect(compareRows([row(103, 60)], [row(100, 60)], false)[0]!.pass).toBe(false); // draws +3% still fails+ expect(compareRows([row(100, 60)], [{ ...row(100, 60), fixture: 'top' }], true)).toEqual([]);+});++const sealed = resolve(import.meta.dir, '../../.cache/site-inputs/golden-gate/standalone/assets');+test.skipIf(!existsSync(sealed))('a sealed site pack verifies apart from its own code chunks', () => {+ const pack = sealed;+ expect(packProblems(pack)).toEqual([]);+ expect(packProblems(resolve(import.meta.dir, 'missing-pack')).length).toBe(1);+});diff --git a/scenes/scripts/tests/farm-x02-baseline.test.ts b/scenes/scripts/tests/farm-x02-baseline.test.tsnew file mode 100644index 00000000..635825b2--- /dev/null+++ b/scenes/scripts/tests/farm-x02-baseline.test.ts@@ -0,0 +1,74 @@+import { expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { checkX02Rows, compareX02Reference, FARM_X02_VIEWS, validateX02Baseline, type X02Baseline } from '../farm-count-gates';+import { FARM_VIEWS } from '../scene-fixtures';++// OD-8 (D-53): X-02 compares against a committed reference of the optimized build's fresh-page high counts per view+// (packages/farm/fixtures/x02-baseline.json) instead of the sealed pilot, with the same inclusive ±2% draw and triangle+// band and the +5% pipeline-cache ceiling.+const entry = (drawCalls = 300, triangles = 1_000_000, pipelines = 60, kind: 'named view' | 'play fixture' = 'named view') => ({ kind, drawCalls, triangles, pipelines, geometries: 200, textures: 30, programs: 40 });+function baseline(): X02Baseline {+ return {+ schema: 'kiln.farm-x02-baseline/1', decision: 'OD-8 (D-53)',+ rule: 'Inclusive ±2% draws and triangles, pipeline cache at most +5% of this reference',+ provenance: { build: 'draw-after', commit: '892d103', chunks: ['index-x.js'], source: 'git HEAD, clean', tool: 'scripts/farm-x02-baseline.ts measure', date: '2026-10-02' },+ conditions: { tier: 'high', viewport: [1280, 720], freshPage: true, clock: 'frozen', settled: true },+ backends: { webgpu: { hero: entry(), 'play-yard': entry(90, 1_500_000, 23, 'play fixture') }, webgl2: { hero: entry(300, 1_000_000, 21) } },+ };+}+const run = { tier: 'high', backend: 'webgpu' as const, viewport: [1920, 1080] as [number, number], freshPage: true };+const observed = (drawCalls = 300, triangles = 1_000_000, pipelines = 60) => ({ drawCalls, triangles, pipelines, geometries: 200, textures: 30, programs: 40 });++test('X-02 compares a view against the committed reference with the ±2% and +5% bounds', () => {+ const ok = compareX02Reference(baseline(), { view: 'hero', ...run }, observed(306, 980_000, 63));+ expect(ok).toMatchObject({ id: 'X-02', view: 'hero', backend: 'webgpu', pass: true, missing: false, conditions: { match: true } });+ expect(ok.checks!.drawCalls).toMatchObject({ pilot: 300, rewrite: 306, pass: true });+ for (const counts of [observed(307), observed(293), observed(300, 1_020_001), observed(300, 1_000_000, 64)]) expect(compareX02Reference(baseline(), { view: 'hero', ...run }, counts).pass).toBe(false);+ // The pre-optimization build (583 draws at the hero view) is flagged; its per-backend entry is used, not the other backend's.+ expect(compareX02Reference(baseline(), { view: 'hero', ...run }, observed(583, 2_300_000, 69)).pass).toBe(false);+ expect(compareX02Reference(baseline(), { view: 'hero', ...run, backend: 'webgl2' }, observed(300, 1_000_000, 22)).pass).toBe(true);+ expect(compareX02Reference(baseline(), { view: 'play-yard', ...run }, observed(90, 1_500_000, 23))).toMatchObject({ pass: true, fixture: 'play fixture' });+});++test('X-02 fails a view or backend missing from the reference instead of passing it', () => {+ expect(compareX02Reference(baseline(), { view: 'top', ...run }, observed())).toMatchObject({ pass: false, missing: true });+ expect(compareX02Reference(baseline(), { view: 'play-yard', ...run, backend: 'webgl2' }, observed())).toMatchObject({ pass: false, missing: true });+});++test('X-02 refuses observations taken under conditions other than the reference', () => {+ const shared = compareX02Reference(baseline(), { view: 'hero', ...run, freshPage: false }, observed());+ expect(shared).toMatchObject({ pass: false, conditions: { match: false } });+ expect(shared.conditions.differences.join(' ')).toContain('fresh page');+ expect(compareX02Reference(baseline(), { view: 'hero', ...run, tier: 'economy' }, observed()).pass).toBe(false);+ // Frustum culling depends on the aspect ratio only, so a 16:9 viewport of another size is the same condition.+ expect(compareX02Reference(baseline(), { view: 'hero', ...run, viewport: [1280, 720] }, observed()).pass).toBe(true);+ expect(compareX02Reference(baseline(), { view: 'hero', ...run, viewport: [1280, 1024] }, observed()).pass).toBe(false);+});++test('X-02 checks a count-probe run: every reference view at high, workloads listed but not judged', () => {+ const row = (fixture: string, draws: number, triangles: number, pipelineCache: number, tier = 'high') => ({ scene: 'farm', tier, fixture, draws, triangles, pipelineCache, programs: 40, memory: { geometries: 200, textures: 30 } });+ const after = checkX02Rows(baseline(), [row('hero', 300, 1_000_000, 60), row('play-yard', 91, 1_500_000, 23), row('walk', 91, 1_500_000, 23), row('hero', 999, 1, 1, 'economy')], run);+ expect(after).toMatchObject({ pass: true, missing: [], extra: ['walk'] });+ expect(after.views.map(v => v.view)).toEqual(['hero', 'play-yard']);+ const before = checkX02Rows(baseline(), [row('hero', 583, 1_884_260, 69), row('play-yard', 119, 1_600_000, 30)], run);+ expect(before.pass).toBe(false);+ expect(before.views.filter(v => !v.pass).map(v => v.view)).toEqual(['hero', 'play-yard']);+ expect(checkX02Rows(baseline(), [row('hero', 300, 1_000_000, 60)], run)).toMatchObject({ pass: false, missing: ['play-yard'] });+ expect(checkX02Rows(baseline(), [row('hero', 300, 1_000_000, 60), row('play-yard', 90, 1_500_000, 23)], { ...run, freshPage: false }).pass).toBe(false);+});++test('a reference without provenance, fresh-page high conditions or valid counts is rejected', () => {+ expect(validateX02Baseline(baseline())).toEqual([]);+ const b = baseline() as any; delete b.provenance.commit; b.conditions.freshPage = false; b.backends.webgpu.hero.drawCalls = -1;+ expect(validateX02Baseline(b)).toEqual(expect.arrayContaining([expect.stringContaining('provenance.commit'), expect.stringContaining('fresh page'), expect.stringContaining('webgpu/hero')]));+ expect(validateX02Baseline({ ...baseline(), schema: 'other' } as any).length).toBeGreaterThan(0);+});++test('the committed Farm reference covers every named view and play fixture on both backends', () => {+ const committed = JSON.parse(readFileSync(resolve(import.meta.dir, '../../packages/farm/fixtures/x02-baseline.json'), 'utf8')) as X02Baseline;+ expect(validateX02Baseline(committed)).toEqual([]);+ expect([...FARM_X02_VIEWS].sort()).toEqual([...FARM_VIEWS, 'play-yard', 'play-house', 'play-bridge', 'play-house-door'].sort());+ for (const backend of ['webgpu', 'webgl2'] as const) expect(Object.keys(committed.backends[backend] ?? {}).sort()).toEqual([...FARM_X02_VIEWS].sort());+ expect(committed.conditions).toMatchObject({ tier: 'high', freshPage: true, clock: 'frozen', settled: true });+});diff --git a/scenes/scripts/tests/foundry-floor-count-baseline.test.ts b/scenes/scripts/tests/foundry-floor-count-baseline.test.tsnew file mode 100644index 00000000..e4487d27--- /dev/null+++ b/scenes/scripts/tests/foundry-floor-count-baseline.test.ts@@ -0,0 +1,87 @@+import { expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { buildFoundryCountBaseline, checkFoundryCounts, FOUNDRY_COUNT_TIERS, validateFoundryCountBaseline, type FoundryCountBaseline, type FoundryCountRow } from '../foundry-count-gates';+import { FOUNDRY_FIXTURES } from '../scene-fixtures';++// OD-8 (D-53), Foundry Floor: it had no X-02 pin, so its draw and triangle budgets never ran in the gate. The reference is a+// committed count baseline of the optimized build (packages/foundry-floor/fixtures/count-baseline.json) with the same inclusive+// ±2% draw and triangle band and the +5% pipeline ceiling as X-02.+const row = (fixture: string, draws: number, triangles = 100_000, pipelinesUsed = 10, pipelineCache = 20, tier = 'high'): FoundryCountRow => ({ scene: 'foundry-floor', tier, fixture, draws, triangles, pipelinesUsed, pipelineCache, programs: 30, memory: { geometries: 100, textures: 8 } });+const provenance = { build: 'draw-after', commit: '892d103', chunks: ['index-x.js'], source: 'git HEAD, clean', tool: 'scripts/check-foundry-counts.ts --record', probe: 'scripts/count-probe.ts --label draw-after-ff', date: '2026-10-02' };+const conditions = { viewport: [1920, 1080] as [number, number], freshPage: false, clock: 'frozen', backend: 'webgpu', settled: true };+function baseline(): FoundryCountBaseline {+ return buildFoundryCountBaseline([row('campus-campus', 100), row('fab-landing', 134, 200_000, 7, 8), row('drive', 140, 250_000, 14, 20), row('campus-campus', 90, 80_000, 9, 15, 'minimal')], { provenance, conditions, workloads: ['drive'] });+}+const run = { freshPage: false, viewport: [1920, 1080] as [number, number] };++test('the reference keeps every row, with provenance, conditions and the workload fixtures marked', () => {+ const b = baseline();+ expect(validateFoundryCountBaseline(b)).toEqual([]);+ expect(b).toMatchObject({ schema: 'kiln.foundry-floor-count-baseline/1', decision: 'OD-8 (D-53)', provenance: { commit: '892d103' } });+ expect(b.tiers.high!['campus-campus']).toMatchObject({ drawCalls: 100, triangles: 100_000, pipelines: 10, pipelineCache: 20 });+ expect(b.tiers.high!.drive).toMatchObject({ workload: true });+ expect(b.tiers.high!['fab-landing']!.workload).toBeUndefined();+});++test('X-02 holds the ±2% draw and triangle band and the +5% pipeline ceiling, inclusive', () => {+ const ok = checkFoundryCounts(baseline(), [row('campus-campus', 102, 98_000, 10), row('fab-landing', 134, 200_000, 7, 8), row('drive', 999, 1, 99)], { ...run, tiers: ['high'] });+ expect(ok).toMatchObject({ pass: true, missing: [], extra: [] });+ // 100 draws: 98 and 102 pass, 97 and 103 fail; triangles likewise; pipelines 10 -> 10 passes (10.5 allowed), 11 fails.+ for (const bad of [row('campus-campus', 103), row('campus-campus', 97), row('campus-campus', 100, 102_001), row('campus-campus', 100, 97_999), row('campus-campus', 100, 100_000, 11)]) {+ const result = checkFoundryCounts(baseline(), [bad, row('fab-landing', 134, 200_000, 7, 8)], { ...run, tiers: ['high'] });+ expect(result.pass).toBe(false);+ expect(result.rows.filter(r => !r.pass).map(r => r.fixture)).toEqual(['campus-campus']);+ }+ // Small pipeline counts have no slack: 7 + 5% is 7.35, so one more pipeline in the fab fails.+ expect(checkFoundryCounts(baseline(), [row('campus-campus', 100), row('fab-landing', 134, 200_000, 8, 8)], { ...run, tiers: ['high'] }).pass).toBe(false);+});++test('the cumulative pipeline cache is judged only when the run used the reference page policy', () => {+ const grown = [row('campus-campus', 100, 100_000, 10, 25), row('fab-landing', 134, 200_000, 7, 8)];+ const same = checkFoundryCounts(baseline(), grown, { ...run, tiers: ['high'] });+ expect(same).toMatchObject({ pass: false, conditions: { cacheJudged: true } });+ expect(same.rows.find(r => r.fixture === 'campus-campus')!.cache).toEqual({ reference: 20, observed: 25, pass: false });+ // One fresh page per view fills the cache differently: that bound is skipped, draws, triangles and pipelines bound still stand.+ expect(checkFoundryCounts(baseline(), grown, { ...run, freshPage: true, tiers: ['high'] })).toMatchObject({ pass: true, conditions: { match: true, cacheJudged: false } });+ expect(checkFoundryCounts(baseline(), [row('campus-campus', 100, 100_000, 11, 25), row('fab-landing', 134, 200_000, 7, 8)], { ...run, freshPage: true, tiers: ['high'] }).pass).toBe(false);+});++test('the pre-optimization build is flagged where the planting changed and passes where nothing did', () => {+ const before = checkFoundryCounts(baseline(), [row('campus-campus', 108, 100_000, 22, 78), row('fab-landing', 134, 200_000, 7, 8)], { ...run, tiers: ['high'] });+ expect(before.pass).toBe(false);+ expect(before.rows.filter(r => !r.pass).map(r => r.fixture)).toEqual(['campus-campus']);+});++test('a fixture missing from the run fails, a workload fixture is listed but not judged, an unknown one is reported', () => {+ expect(checkFoundryCounts(baseline(), [row('campus-campus', 100)], { ...run, tiers: ['high'] })).toMatchObject({ pass: false, missing: ['high/fab-landing'] }); // the missing drive is a workload+ const result = checkFoundryCounts(baseline(), [row('campus-campus', 100), row('fab-landing', 134, 200_000, 7, 8), row('drive', 500, 9, 99), row('campus-new', 5)], { ...run, tiers: ['high'] });+ expect(result).toMatchObject({ pass: true, extra: ['high/campus-new'] });+ expect(result.rows.find(r => r.fixture === 'drive')).toMatchObject({ workload: true, pass: true, judged: false });+ expect(checkFoundryCounts(baseline(), [row('campus-campus', 100), row('fab-landing', 134, 200_000, 7, 8)], { ...run, tiers: ['minimal'] })).toMatchObject({ pass: false, missing: ['minimal/campus-campus'] });+});++test('observations taken under other conditions than the reference are refused', () => {+ const rows = [row('campus-campus', 100), row('fab-landing', 134, 200_000, 7, 8)];+ expect(checkFoundryCounts(baseline(), rows, { ...run, tiers: ['high'], viewport: [1280, 1024] })).toMatchObject({ pass: false, conditions: { match: false } });+ // The aspect ratio decides culling, so another 16:9 size is the same condition.+ expect(checkFoundryCounts(baseline(), rows, { ...run, tiers: ['high'], viewport: [1280, 720] }).pass).toBe(true);+});++test('a reference without provenance, valid counts or its schema is rejected', () => {+ const b = baseline() as any; delete b.provenance.commit; b.tiers.high['campus-campus'].drawCalls = -1;+ expect(validateFoundryCountBaseline(b)).toEqual(expect.arrayContaining([expect.stringContaining('provenance.commit'), expect.stringContaining('high/campus-campus')]));+ expect(validateFoundryCountBaseline({ ...baseline(), schema: 'other' } as any).length).toBeGreaterThan(0);+});++test('the committed reference covers every Foundry Floor count fixture at every tier', () => {+ const committed = JSON.parse(readFileSync(resolve(import.meta.dir, '../../packages/foundry-floor/fixtures/count-baseline.json'), 'utf8')) as FoundryCountBaseline;+ expect(validateFoundryCountBaseline(committed)).toEqual([]);+ const ids = FOUNDRY_FIXTURES.fixtures.map(f => f.id).sort();+ expect(ids.length).toBe(15);+ for (const tier of FOUNDRY_COUNT_TIERS) expect(Object.keys(committed.tiers[tier] ?? {}).sort()).toEqual(ids);+ expect(committed.conditions).toMatchObject({ backend: 'webgpu', clock: 'frozen', settled: true });+ // The optimized build's planting is in the reference: the Campus view draws 96, not the pre-optimization 102.+ expect(committed.tiers.high!['campus-campus']!.drawCalls).toBe(96);+ expect(Object.entries(committed.tiers.high!).filter(([, e]) => e.workload).map(([id]) => id)).toEqual(['drive']);+});diff --git a/scenes/scripts/tests/timing-ab.test.ts b/scenes/scripts/tests/timing-ab.test.tsnew file mode 100644index 00000000..832a7ac2--- /dev/null+++ b/scenes/scripts/tests/timing-ab.test.ts@@ -0,0 +1,144 @@+import { expect, test } from 'bun:test';+import { cellKind, cellUrl, cpuPercent, d41Verdict, displayRate, frameStats, gpuBusyMedian, hitchCounts, HUB_RULE, interleaveOrder, parseBattery, parseCell, parseLoadavg, parseNvidiaSmi, parseProcStat,+ parseThermalStatus, parseTop, parseWho, PC_RULE, percentile, planRuns, quietVerdict, refreshShare, summarizeCell, tabletCool, type RunMetrics } from '../timing-ab';++test('percentile uses the pilot rule (ceil(n q)-th smallest) and frame stats keep count, fps and sampled time', () => {+ const values = [10, 1, 9, 2, 8, 3, 7, 4, 6, 5];+ expect([percentile(values, .5), percentile(values, .95), percentile(values, 1), percentile([], .5)]).toEqual([5, 10, 10, null]);+ const s = frameStats([8, 8, 8, 16]);+ expect([s.count, s.p50, s.p95, s.max, s.sampledMs, s.fps]).toEqual([4, 8, 16, 16, 40, 100]);+ expect(frameStats([NaN, 10]).count).toBe(1);+});++test('the display rate is the lower-quartile probe interval, robust to a throttled half window', () => {+ const r = displayRate([8.33, 8.34, 8.32, 16.67, 8.33]);+ expect(r.periodMs).toBe(8.33); expect(r.hz).toBeCloseTo(120.05, 1);+ expect(displayRate([]).periodMs).toBeNull();+ // The tablet case: an idle page at 60 Hz, then throttled to 30 Hz for most of the window.+ const throttled = [...Array(12).fill(16.6), ...Array(30).fill(33.3)];+ expect(displayRate(throttled).periodMs).toBe(16.6); // the median would read 33.3+ expect(displayRate([...Array(15).fill(16.6), ...Array(25).fill(33.3)]).periodMs).toBe(16.6);+});++test('refresh share counts frames within one (< 1.5 P) and within two (< 2.5 P) display periods', () => {+ const P = 1000 / 120;+ const intervals = [8.2, 8.4, 8.5, 12.4, 12.6, 16.7, 20.8, 21, 25, 33.4];+ // < 12.5: 8.2 8.4 8.5 12.4 → 4; < 20.83: plus 12.6 16.7 20.8 → 7.+ const s = refreshShare(intervals, P);+ expect(s.withinOne).toBe(.4); expect(s.withinTwo).toBe(.7); expect(s.frames).toBe(10);+ expect(refreshShare([], P).withinOne).toBeNull();+ expect(refreshShare([10], NaN).withinTwo).toBeNull();+ // A 60 Hz tablet: 16.7 is one refresh, 33.3 two, 50 three.+ expect(refreshShare([16.6, 16.8, 33.3, 50.1], 1000 / 60)).toMatchObject({ withinOne: .5, withinTwo: .75 });+});++test('hitch counts and the D-41 rule (desktop 0/0/<=50 ms; tablet <=2 over 50, 0 over 100; only on 60 s runs)', () => {+ const c = hitchCounts([8, 50, 50.1, 99, 100.5]);+ expect(c).toEqual({ over50: 3, over100: 1, longestMs: 100.5 });+ expect(d41Verdict(c, { row: 'desktop', seconds: 60 }).pass).toBe(false);+ expect(d41Verdict(hitchCounts([8, 33.4, 50]), { row: 'desktop', seconds: 60 }).pass).toBe(true);+ expect(d41Verdict(hitchCounts([8, 50.2]), { row: 'desktop', seconds: 60 }).pass).toBe(false);+ expect(d41Verdict(hitchCounts([8, 51, 70]), { row: 'tablet', seconds: 60 }).pass).toBe(true);+ expect(d41Verdict(hitchCounts([8, 51, 70, 60]), { row: 'tablet', seconds: 60 }).pass).toBe(false);+ expect(d41Verdict(hitchCounts([8, 101]), { row: 'tablet', seconds: 60 }).pass).toBe(false);+ const dry = d41Verdict(hitchCounts([8, 101]), { row: 'desktop', seconds: 10 });+ expect([dry.applies, dry.pass]).toEqual([false, null]);+ expect(hitchCounts([]).longestMs).toBeNull();+});++test('interleave order alternates which side runs first in each pair', () => {+ expect(interleaveOrder(1)).toEqual(['A', 'B']);+ expect(interleaveOrder(3)).toEqual(['A', 'B', 'B', 'A', 'A', 'B']);+ expect(() => interleaveOrder(0)).toThrow();+ const plan = planRuns([parseCell('farm:high:hero'), parseCell('golden-gate:minimal:arrival')], 2);+ expect(plan.map(p => `${p.cell.scene}/${p.pair}/${p.side}`)).toEqual(['farm/1/A', 'farm/1/B', 'farm/2/B', 'farm/2/A', 'golden-gate/1/A', 'golden-gate/1/B', 'golden-gate/2/B', 'golden-gate/2/A']);+ expect(plan.map(p => p.position)).toEqual([1, 2, 3, 4, 1, 2, 3, 4]);+});++test('cells parse as scene:tier:name and resolve to the scene own views and workloads', () => {+ expect(parseCell('foundry-floor:high:campus')).toEqual({ scene: 'foundry-floor', tier: 'high', name: 'campus' });+ expect(() => parseCell('farm:ultra:hero')).toThrow(); expect(() => parseCell('mill:high:hero')).toThrow(); expect(() => parseCell('farm:high')).toThrow();+ expect(cellKind(parseCell('farm:high:hero'))).toBe('view');+ expect(cellKind(parseCell('farm:economy:tractor-drive'))).toBe('workload');+ expect(cellKind(parseCell('golden-gate:minimal:drive'))).toBe('workload');+ expect(cellKind(parseCell('foundry-floor:high:fab-overview'))).toBe('view');+ expect(() => cellKind(parseCell('golden-gate:high:hero'))).toThrow(/no view or workload/);+ // The clock is never frozen: no freeze or time parameter; tier and A/B extras are added.+ const url = new URL(cellUrl('http://127.0.0.1:4400/', parseCell('golden-gate:minimal:arrival'), { msaa: 'store' }));+ expect(Object.fromEntries(url.searchParams)).toEqual({ capture: '1', hud: '0', preset: 'day', cam: 'arrival', tier: 'minimal', msaa: 'store' });+ expect(new URL(cellUrl('http://x', parseCell('farm:high:hero'))).search).toBe('?view=hero&tier=high');+ expect(new URL(cellUrl('http://x', parseCell('foundry-floor:economy:drive'))).search).toBe('?capture=1&tier=economy');+});++test('quiet-check parsing: loadavg, /proc/stat, nvidia-smi, who and top', () => {+ expect(parseLoadavg('0.37 0.40 0.37 1/589 1685215\n')).toEqual({ one: .37, five: .4, fifteen: .37, running: 1, total: 589 });+ const a = parseProcStat('cpu 100 0 50 1000 50 0 0 0 0 0\ncpu0 1 2 3'), b = parseProcStat('cpu 110 0 60 1170 50 0 0 0 0 0\n');+ expect(a).toEqual({ total: 1200, idle: 1050 }); expect(cpuPercent(a, b)).toBeCloseTo(100 * 20 / 190, 6);+ expect(cpuPercent(a, a)).toBeNull();+ expect(parseNvidiaSmi('0, 39, 300, 5, P8\n', ['utilization.gpu', 'temperature.gpu', 'clocks.gr', 'memory.used', 'pstate'])).toEqual([{ 'utilization.gpu': 0, 'temperature.gpu': 39, 'clocks.gr': 300, 'memory.used': 5, pstate: 'P8' }]);+ expect(parseNvidiaSmi('[N/A], 40\n', ['a', 'b'])[0]).toEqual({ a: null, b: 40 });+ expect(parseWho('\n')).toEqual([]); expect(parseWho('matthewk tty2 2026-09-30 01:00\n')).toHaveLength(1);+ const top = `top - 01:19:44 up 6 days, 16:51, 3 users, load average: 0.37, 0.40, 0.37+Tasks: 300 total, 1 running, 299 sleeping, 0 stopped, 0 zombie++ PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND+ 1234 matthewk 20 0 3400000 200000 90000 S 6.2 1.3 1:23.45 kwin_wayland --xwayland+ 1 root 20 0 22000 12000 9000 S 0.0 0.1 0:05.00 systemd+`;+ expect(parseTop(top)).toEqual([{ pid: 1234, user: 'matthewk', cpuPercent: 6.2, memPercent: 1.3, command: 'kwin_wayland --xwayland' }, { pid: 1, user: 'root', cpuPercent: 0, memPercent: .1, command: 'systemd' }]);+ expect(parseTop('no header')).toEqual([]);+});++test('quiet verdicts: the hub pilot rule and this PC rule', () => {+ const calm = { cpu: [1, 1.5, .8, 2, 1, 1, 1, 1], gpu: [0, 0, 1, 0, 0, 0, 0, 0] };+ expect(quietVerdict(calm, HUB_RULE).quiet).toBe(true);+ expect(quietVerdict({ ...calm, gpu: [0, 0, 4, 0, 0, 0, 0, 0] }, HUB_RULE).reasons).toEqual(['GPU max 4 % > 3 %']);+ expect(quietVerdict({ ...calm, cpu: [1, 1, 1, 13, 1, 1, 1, 1] }, HUB_RULE).reasons[0]).toMatch(/CPU max 13/);+ expect(quietVerdict({ ...calm, screenLocked: true }, HUB_RULE).quiet).toBe(false);+ expect(quietVerdict({ cpu: [1, 1], gpu: [] }, HUB_RULE).reasons).toEqual(['2 of 8 CPU samples']);+ const busyPc = { cpu: [35, 40, 38, 36, 37, 39, 41, 36], gpu: [22, 25, 24, 23, 22, 21, 20, 25] };+ expect(quietVerdict(busyPc, PC_RULE).reasons).toEqual(['CPU mean 37.75 % >= 20 %', 'GPU max 25 % > 9.999 %']);+ expect(quietVerdict({ cpu: [10, 12, 15, 11, 9, 14, 13, 12], gpu: [5, 5, 5, 5, 5, 5, 5, 9] }, PC_RULE).quiet).toBe(true);+});++test('tablet readings and the cool rule (thermal none or light, battery at most 35 C)', () => {+ const battery = `Current Battery Service state:+ AC powered: false+ USB powered: true+ status: 5+ level: 100+ temperature: 240+09-30 02:00:19.688 Sending ACTION_BATTERY_CHANGED: level:100, temperature:228`;+ expect(parseBattery(battery)).toEqual({ level: 100, temperatureC: 24, status: 5, usbPowered: true, acPowered: false });+ expect(parseThermalStatus('IsStatusOverride: false\nThermal Status: 1\n')).toBe(1);+ expect(parseThermalStatus('nothing')).toBeNull();+ expect(tabletCool({ thermalStatus: 1, batteryC: 34.9 }).cool).toBe(true);+ expect(tabletCool({ thermalStatus: 2, batteryC: 30 }).reasons).toEqual(['thermal status moderate (2) above light']);+ expect(tabletCool({ thermalStatus: 0, batteryC: 35.2 }).reasons).toEqual(['battery 35.2 C above 35 C']);+ expect(tabletCool({ thermalStatus: null, batteryC: null }).reasons).toHaveLength(2);+});++test('a cell summary gives per-side medians over valid runs and paired B - A differences', () => {+ const m = (p50: number, p95: number, withinOne: number, over50 = 0): RunMetrics => ({ p50, p95, p99: p95, max: p95, fps: 1000 / p50, withinOne, withinTwo: 1, over50, over100: 0, longestMs: p95, cpuRenderP50: p50 / 2, cpuRenderP95: p95 / 2, drawsMedian: 583, trianglesMedian: 2e6, gpuBusy: p50 * 4 });+ const runs = [+ { side: 'A' as const, pair: 1, valid: true, metrics: m(10, 20, .9) }, { side: 'B' as const, pair: 1, valid: true, metrics: m(9, 18, .95) },+ { side: 'B' as const, pair: 2, valid: true, metrics: m(9.5, 19, .94) }, { side: 'A' as const, pair: 2, valid: true, metrics: m(10.5, 21, .9) },+ { side: 'A' as const, pair: 3, valid: true, metrics: m(11, 22, .88, 1) }, { side: 'B' as const, pair: 3, valid: false, metrics: m(30, 60, .1, 9) },+ ];+ const s = summarizeCell(runs);+ expect([s.A.valid, s.B.valid, s.A.runs, s.B.runs]).toEqual([3, 2, 3, 3]);+ expect(s.A.p50).toEqual({ median: 10.5, min: 10, max: 11 });+ expect(s.B.p95?.max).toBe(19); // the invalid run is left out+ expect(s.pairs).toBe(2);+ expect(s.paired.map(p => p.p95)).toEqual([-2, -2]);+ expect(s.deltas.p50).toEqual({ medianDelta: -1, bLower: 2, bHigher: 0, equal: 0 });+ expect(s.deltas.drawsMedian).toEqual({ medianDelta: 0, bLower: 0, bHigher: 0, equal: 2 });+ expect(s.ratios.p95).toBeCloseTo(18 / 21, 6);+ expect(s.deltas.gpuBusy?.medianDelta).toBe(-4);+});++test('GPU busy during a run is the median of nvidia-smi or Mali gpu_busy samples', () => {+ expect(gpuBusyMedian([{ gpu: { 'utilization.gpu': 50 } }, { gpu: { 'utilization.gpu': 40 } }, { gpu: null }, { gpu: { 'utilization.gpu': 60 } }])).toBe(50);+ expect(gpuBusyMedian([{ gpuBusyPercent: 31 }, { batteryC: 25, gpuBusyPercent: 29 }, { gpuBusyPercent: null }])).toBe(29);+ expect(gpuBusyMedian([])).toBeNull();+});diff --git a/scenes/scripts/timing-ab.ts b/scenes/scripts/timing-ab.tsnew file mode 100644index 00000000..2e5ca795--- /dev/null+++ b/scenes/scripts/timing-ab.ts@@ -0,0 +1,751 @@+// S6 timing (docs/plans/2026-10-01-draw-optimization-cycle.md; OD-3, OD-5, OD-6, OD-7, OD-12): one interleaved A/B+// frame-time runner for Farm, Foundry Floor and Golden Gate. Two test builds (A = before, B = after) are served by this+// runner on two loopback ports; every cell (scene, tier, view or workload) runs A/B/B/A/A/B… (order alternating per pair)+// on one host: the hub (a local headed Chrome) or the tablet (the device kit's adb reverse and DevTools forward from this+// PC). Timing is taken only when a person runs it on a quiet host; `quiet` and the block preflight say whether it is.+// Per run it records the rAF frame interval (p50, p95, p99, max), the share of frames within one and within two display+// refreshes (OD-7; the period comes from the display rate measured on a blank page just before), the D-41 hitch counts+// (frames over 50 ms and over 100 ms, longest frame), load samples during the run (hub: CPU and NVIDIA GPU utilisation+// and the busiest processes outside the benchmark; tablet: battery temperature, thermal status and Mali GPU busy), the+// kit's CPU time around renderer.render, and renderer.info's per-frame draw count sampled every 30 frames as a cross-check.+// Runs under Node 22 (bundled by scripts/make-timing-kit.ts) or Bun; needs no network beyond loopback and adb.+// node runner/timing-ab.mjs ab --a builds/<A> --b builds/<B> --cells farm:high:hero,golden-gate:minimal:arrival [--pairs 3]+// [--seconds 60] [--device local|tablet] [--block <name>] [--out results] [--chrome <path>] [--chrome-arg <flag>]…+// node runner/timing-ab.mjs quiet [--out <file>] host quiet check (load average, busiest processes, GPU, logins, 8 x 2 s window)+// node runner/timing-ab.mjs summary --dir results/<block>+// node runner/timing-ab.mjs transient [--device tablet] WebGPU TRANSIENT_ATTACHMENT support (read-only)+// node runner/timing-ab.mjs verify+import { execFile } from 'node:child_process';+import { existsSync, readdirSync, readFileSync } from 'node:fs';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { createHash } from 'node:crypto';+import { cpus, hostname, release, type as osType } from 'node:os';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import puppeteer, { type Browser, type Page } from 'puppeteer-core';+// @ts-ignore Node-builtins-only static server shared with the standalone outputs (no-store aside, the same policy for A and B).+import { startStaticServer } from './static-server.mjs';+import { adbDevices, adbFor, connectDevtools, deviceState, forwardDevtools, listMappings, removeForward, removeReverse, reversePort, wakeAndOpenChrome, type Adb } from './device-kit';++// ---------------------------------------------------------------- pure logic (tests/timing-ab.test.ts)++export type Side = 'A' | 'B';+export const SCENE_IDS = ['farm', 'foundry-floor', 'golden-gate'] as const;+export type SceneId = typeof SCENE_IDS[number];+export const TIERS = ['minimal', 'economy', 'balanced', 'high'] as const;+export type Tier = typeof TIERS[number];++/** The Farm and Golden Gate runners' percentile rule (the sealed pilot's summarize()): the ceil(n q)-th smallest value. */+export function percentile(values: readonly number[], q: number): number | null {+ const sorted = values.filter(Number.isFinite).slice().sort((a, b) => a - b);+ return sorted.length ? sorted[Math.max(0, Math.ceil(sorted.length * q) - 1)]! : null;+}+export const median = (values: readonly number[]) => percentile(values, .5);+const round = (value: number | null | undefined, digits = 3) => typeof value === 'number' && Number.isFinite(value) ? Math.round(value * 10 ** digits) / 10 ** digits : null;++export function frameStats(intervals: readonly number[]) {+ const finite = intervals.filter(Number.isFinite), sum = finite.reduce((s, v) => s + v, 0);+ return { count: finite.length, p50: percentile(finite, .5), p95: percentile(finite, .95), p99: percentile(finite, .99), max: percentile(finite, 1),+ mean: finite.length ? sum / finite.length : null, fps: sum > 0 ? 1000 * finite.length / sum : null, sampledMs: sum };+}+/**+ * Display rate from rAF intervals on a probe page: the lower quartile. Throttling and skipped vsyncs only lengthen an+ * interval (the tablet's Chrome dropped an idle about:blank to 30 Hz part-way through the probe in 2 of 36 runs), so the+ * shorter intervals carry the refresh period; the median does not when half the window is throttled.+ */+export function displayRate(intervals: readonly number[]) {+ const periodMs = percentile(intervals.filter(v => v > 0), .25);+ return { periodMs, hz: periodMs ? 1000 / periodMs : null, samples: intervals.length };+}+/**+ * OD-7: the share of frames presented within one and within two display refreshes. A rAF interval is a whole number of+ * vsync periods plus timer jitter, so an interval counts as k refreshes when it rounds to k periods: within one means+ * interval < 1.5 P, within two means interval < 2.5 P.+ */+export function refreshShare(intervals: readonly number[], periodMs: number) {+ const finite = intervals.filter(Number.isFinite), n = finite.length;+ if (!(periodMs > 0) || !n) return { periodMs: periodMs > 0 ? periodMs : null, withinOne: null, withinTwo: null, frames: n };+ const one = finite.filter(v => v < 1.5 * periodMs).length, two = finite.filter(v => v < 2.5 * periodMs).length;+ return { periodMs, withinOne: one / n, withinTwo: two / n, frames: n };+}+export function hitchCounts(intervals: readonly number[]) {+ const finite = intervals.filter(Number.isFinite);+ return { over50: finite.filter(v => v > 50).length, over100: finite.filter(v => v > 100).length, longestMs: finite.length ? Math.max(...finite) : null };+}+/**+ * D-41 (owner, 2026-09-30, keeping D-28's limits): per 60 s run at every tier, 0 frames over 100 ms, 0 over 50 ms and a+ * longest frame of at most 50 ms; the tablet row allows at most 2 frames over 50 ms and 0 over 100 ms. It is judged+ * only on a run of at least 60 s; shorter (dry) runs report the counts with `applies: false`.+ */+export function d41Verdict(counts: ReturnType<typeof hitchCounts>, o: { row: 'desktop' | 'tablet'; seconds: number }) {+ const applies = o.seconds >= 60;+ const limits = o.row === 'tablet' ? { over50AtMost: 2, over100AtMost: 0, longestMsAtMost: null } : { over50AtMost: 0, over100AtMost: 0, longestMsAtMost: 50 };+ const pass = counts.over50 <= limits.over50AtMost && counts.over100 <= limits.over100AtMost && (limits.longestMsAtMost === null || (counts.longestMs ?? 0) <= limits.longestMsAtMost);+ return { row: o.row, applies, limits, pass: applies ? pass : null };+}+/** A/B order per pair, alternating so neither side always runs first: pair 1 A B, pair 2 B A, pair 3 A B, … */+export function interleaveOrder(pairs: number): Side[] {+ if (!Number.isInteger(pairs) || pairs < 1) throw new Error('pairs must be a positive integer');+ return Array.from({ length: pairs }, (_, i) => (i % 2 === 0 ? ['A', 'B'] : ['B', 'A']) as Side[]).flat();+}+export interface Cell { scene: SceneId; tier: Tier; name: string }+export const cellId = (c: Cell) => `${c.scene}-${c.tier}-${c.name}`;+/** "scene:tier:view-or-workload", for example farm:high:hero or golden-gate:minimal:arrival. */+export function parseCell(text: string): Cell {+ const [scene, tier, name, ...rest] = text.trim().split(':');+ if (!scene || !tier || !name || rest.length) throw new Error(`Cell ${text} is not scene:tier:name`);+ if (!(SCENE_IDS as readonly string[]).includes(scene)) throw new Error(`Unknown scene ${scene}`);+ if (!(TIERS as readonly string[]).includes(tier)) throw new Error(`Unknown tier ${tier}`);+ if (!/^[a-z0-9-]+$/.test(name)) throw new Error(`View or workload ${name} uses lowercase letters, numbers and hyphens`);+ return { scene: scene as SceneId, tier: tier as Tier, name };+}+export interface PlannedRun { cell: Cell; pair: number; position: number; side: Side }+/** Every cell runs its own interleaved pairs in turn; position counts runs within the cell from 1. */+export function planRuns(cells: readonly Cell[], pairs: number): PlannedRun[] {+ const order = interleaveOrder(pairs);+ return cells.flatMap(cell => order.map((side, i) => ({ cell, pair: Math.floor(i / 2) + 1, position: i + 1, side })));+}++// Host readings, parsed from the text the tools print.+export function parseLoadavg(text: string) {+ const [one, five, fifteen, tasks] = text.trim().split(/\s+/); const [running, total] = (tasks ?? '').split('/').map(Number);+ return { one: Number(one), five: Number(five), fifteen: Number(fifteen), running: running ?? null, total: total ?? null };+}+/** The first line of /proc/stat: total and idle (idle + iowait) jiffies. */+export function parseProcStat(text: string) {+ const values = text.split(/\r?\n/)[0]!.trim().split(/\s+/).slice(1, 9).map(Number);+ return { total: values.reduce((s, v) => s + v, 0), idle: values[3]! + values[4]! };+}+export const cpuPercent = (a: { total: number; idle: number }, b: { total: number; idle: number }) => b.total > a.total ? 100 * (1 - (b.idle - a.idle) / (b.total - a.total)) : null;+/** One `nvidia-smi --query-gpu=<fields> --format=csv,noheader,nounits` row per GPU; "[N/A]" reads null. */+export function parseNvidiaSmi(text: string, fields: readonly string[]) {+ return text.trim().split(/\r?\n/).filter(Boolean).map(line => Object.fromEntries(line.split(',').map((value, i) => {+ const v = value.trim(), n = Number(v); return [fields[i] ?? `field${i}`, v === '' || /N\/A/.test(v) ? null : Number.isFinite(n) ? n : v];+ })) as Record<string, number | string | null>);+}+export const parseWho = (text: string) => text.split(/\r?\n/).map(line => line.trim()).filter(Boolean);+/** `top -b -n 1` process rows (after the PID header): pid, user, %CPU, %MEM, command. */+export function parseTop(text: string, limit = 8) {+ const lines = text.split(/\r?\n/), header = lines.findIndex(line => /^\s*PID\s+USER/.test(line));+ if (header < 0) return [];+ const columns = lines[header]!.trim().split(/\s+/), cpu = columns.indexOf('%CPU'), mem = columns.indexOf('%MEM'), command = columns.length - 1;+ return lines.slice(header + 1).map(line => line.trim().split(/\s+/)).filter(f => f.length >= columns.length && /^\d+$/.test(f[0]!))+ .map(f => ({ pid: Number(f[0]), user: f[1]!, cpuPercent: Number(f[cpu]), memPercent: Number(f[mem]), command: f.slice(command).join(' ') })).slice(0, limit);+}+/** The sealed pilot's hub preflight rule (8 samples of 2 s; CPU mean < 5 %, CPU max < 12 %, NVIDIA GPU <= 3 %, no screen locker). */+export const HUB_RULE = { samples: 8, intervalSeconds: 2, cpuMeanBelow: 5, cpuMaxBelow: 12, gpuMaxAtMost: 3, source: 'sealed pilot ops/run-hub-performance.py preflight (hub-2026-09-30 tools/common.py)' } as const;+/** This PC (plan default): CPU < 20 % and GPU < 10 %, judged on the same 8 x 2 s window. */+export const PC_RULE = { samples: 8, intervalSeconds: 2, cpuMeanBelow: 20, cpuMaxBelow: 100, gpuMaxAtMost: 9.999, source: 'plan default for this PC: CPU < 20 %, GPU < 10 %' } as const;+/** The pilot's tablet preflight (farm-pilot ops/tablet-observe.py): CPU mean < 8 %, CPU max < 12 %, Mali GPU busy <= 3 %. */+export const TABLET_RULE = { samples: 8, intervalSeconds: 2, cpuMeanBelow: 8, cpuMaxBelow: 12, gpuMaxAtMost: 3, source: 'farm-pilot ops/tablet-observe.py (golden-gate tests/tools/tablet-check.ts)' } as const;+export type QuietRule = { samples: number; intervalSeconds: number; cpuMeanBelow: number; cpuMaxBelow: number; gpuMaxAtMost: number; source: string };+export function quietVerdict(window: { cpu: readonly number[]; gpu: readonly (number | null)[]; screenLocked?: boolean | null }, rule: QuietRule) {+ const cpu = window.cpu.filter(Number.isFinite), gpu = window.gpu.filter((v): v is number => typeof v === 'number' && Number.isFinite(v));+ const cpuMean = cpu.length ? cpu.reduce((s, v) => s + v, 0) / cpu.length : null, cpuMax = cpu.length ? Math.max(...cpu) : null, gpuMax = gpu.length ? Math.max(...gpu) : null;+ const reasons: string[] = [];+ if (cpu.length < rule.samples) reasons.push(`${cpu.length} of ${rule.samples} CPU samples`);+ if (cpuMean !== null && cpuMean >= rule.cpuMeanBelow) reasons.push(`CPU mean ${cpuMean.toFixed(2)} % >= ${rule.cpuMeanBelow} %`);+ if (cpuMax !== null && cpuMax >= rule.cpuMaxBelow) reasons.push(`CPU max ${cpuMax.toFixed(2)} % >= ${rule.cpuMaxBelow} %`);+ if (gpuMax !== null && gpuMax > rule.gpuMaxAtMost) reasons.push(`GPU max ${gpuMax} % > ${rule.gpuMaxAtMost} %`);+ if (window.screenLocked) reasons.push('screen locker active');+ return { quiet: reasons.length === 0, cpuMean, cpuMax, gpuMax, reasons, rule };+}+// Tablet readings (dumpsys battery and thermalservice; the Mali sysfs nodes used by golden-gate tablet-check.ts).+export function parseBattery(text: string) {+ const get = (key: string) => new RegExp(`^\\s*${key}:\\s*(.+)$`, 'm').exec(text)?.[1]?.trim() ?? null;+ const temperature = get('temperature');+ return { level: get('level') === null ? null : Number(get('level')), temperatureC: temperature === null ? null : Number(temperature) / 10, status: get('status') === null ? null : Number(get('status')),+ usbPowered: get('USB powered') === 'true', acPowered: get('AC powered') === 'true' };+}+export const THERMAL_NAMES = ['none', 'light', 'moderate', 'severe', 'critical', 'emergency', 'shutdown'] as const;+export function parseThermalStatus(text: string): number | null { const m = /Thermal Status:\s*(\d+)/.exec(text); return m ? Number(m[1]) : null; }+/** OD-6 and this step's rule: start and continue only while thermal status is none or light and the battery is at most about 35 C. */+export const TABLET_COOL = { maxThermalStatus: 1, maxBatteryC: 35 } as const;+export function tabletCool(state: { thermalStatus: number | null; batteryC: number | null }, rule: { maxThermalStatus: number; maxBatteryC: number } = TABLET_COOL) {+ const reasons: string[] = [];+ if (state.thermalStatus === null) reasons.push('thermal status unreadable');+ else if (state.thermalStatus > rule.maxThermalStatus) reasons.push(`thermal status ${THERMAL_NAMES[state.thermalStatus] ?? state.thermalStatus} (${state.thermalStatus}) above ${THERMAL_NAMES[rule.maxThermalStatus]}`);+ if (state.batteryC === null) reasons.push('battery temperature unreadable');+ else if (state.batteryC > rule.maxBatteryC) reasons.push(`battery ${state.batteryC} C above ${rule.maxBatteryC} C`);+ return { cool: reasons.length === 0, reasons, rule };+}++/** The per-run values a cell summary compares (one RunRecord carries them under `metrics`). */+export interface RunMetrics { p50: number | null; p95: number | null; p99: number | null; max: number | null; fps: number | null; withinOne: number | null; withinTwo: number | null;+ over50: number; over100: number; longestMs: number | null; cpuRenderP50: number | null; cpuRenderP95: number | null; drawsMedian: number | null; trianglesMedian: number | null;+ /** Median GPU busy % over the load samples taken during the sample (hub: nvidia-smi utilization.gpu; tablet: Mali gpu_busy). At a locked refresh it shows a cost difference the frame interval cannot. */+ gpuBusy?: number | null }+export interface RunSummaryInput { side: Side; pair: number; valid: boolean; metrics: RunMetrics }+const METRIC_KEYS = ['p50', 'p95', 'p99', 'max', 'fps', 'withinOne', 'withinTwo', 'over50', 'over100', 'longestMs', 'cpuRenderP50', 'cpuRenderP95', 'drawsMedian', 'trianglesMedian', 'gpuBusy'] as const;+/** GPU busy % from load samples taken during a run: nvidia-smi rows (hub, this PC) or Mali gpu_busy readings (tablet). */+export function gpuBusyMedian(samples: readonly unknown[]): number | null {+ const values = samples.map(s => { const x = s as { gpu?: Record<string, unknown> | null; gpuBusyPercent?: number | null }; return x.gpu ? x.gpu['utilization.gpu'] : x.gpuBusyPercent; })+ .filter((v): v is number => typeof v === 'number' && Number.isFinite(v));+ return values.length ? median(values) : null;+}+/**+ * One cell: per side, the median (and range) over its valid runs of each per-run value; per pair, B - A for each value+ * (both runs of the pair valid), with the median paired difference and how many pairs went each way. Lower is better+ * for times and hitch counts; higher for fps and the refresh shares.+ */+export function summarizeCell(runs: readonly RunSummaryInput[]) {+ const side = (s: Side) => {+ const list = runs.filter(r => r.side === s && r.valid);+ return { runs: runs.filter(r => r.side === s).length, valid: list.length, ...Object.fromEntries(METRIC_KEYS.map(k => {+ const values = list.map(r => r.metrics[k]).filter((v): v is number => typeof v === 'number' && Number.isFinite(v));+ return [k, values.length ? { median: median(values), min: Math.min(...values), max: Math.max(...values) } : null];+ })) } as { runs: number; valid: number } & Record<typeof METRIC_KEYS[number], { median: number | null; min: number; max: number } | null>;+ };+ const a = side('A'), b = side('B'), pairs = [...new Set(runs.map(r => r.pair))].sort((x, y) => x - y);+ const paired = pairs.flatMap(pair => {+ const ra = runs.find(r => r.pair === pair && r.side === 'A'), rb = runs.find(r => r.pair === pair && r.side === 'B');+ if (!ra || !rb || !ra.valid || !rb.valid) return [];+ return [{ pair, ...Object.fromEntries(METRIC_KEYS.map(k => [k, typeof ra.metrics[k] === 'number' && typeof rb.metrics[k] === 'number' ? (rb.metrics[k] as number) - (ra.metrics[k] as number) : null])) } as { pair: number } & Record<typeof METRIC_KEYS[number], number | null>];+ });+ const deltas = Object.fromEntries(METRIC_KEYS.map(k => {+ const values = paired.map(p => p[k]).filter((v): v is number => typeof v === 'number');+ return [k, values.length ? { medianDelta: median(values), bLower: values.filter(v => v < 0).length, bHigher: values.filter(v => v > 0).length, equal: values.filter(v => v === 0).length } : null];+ }));+ const ratio = (k: typeof METRIC_KEYS[number]) => { const ra = a[k]?.median, rb = b[k]?.median; return typeof ra === 'number' && typeof rb === 'number' && ra !== 0 ? rb / ra : null; };+ return { A: a, B: b, pairs: paired.length, paired, deltas, ratios: { p50: ratio('p50'), p95: ratio('p95'), cpuRenderP50: ratio('cpuRenderP50'), gpuBusy: ratio('gpuBusy') } };+}++// ---------------------------------------------------------------- scenes: views, workloads and the page setup per scene++type Kind = 'view' | 'workload';+interface SceneTiming {+ views: readonly string[]; workloads: readonly string[];+ /** Page query for a cell (tier and backend are added by the runner); never `freeze` or `time`, so the scene clock runs. */+ query(kind: Kind, name: string): Record<string, string>;+ /** After ready and the governor hold: puts the camera on the view or starts the workload. */+ engage(page: Page, kind: Kind, name: string): Promise<void>;+ /** Camera position and any workload state, read at the start and end of sampling. */+ state(page: Page): Promise<{ pose: unknown; workload: Record<string, unknown> | null }>;+ /** True when the workload is running as named (views: always true). */+ engaged(kind: Kind, name: string, state: { pose: unknown; workload: Record<string, unknown> | null }): boolean;+}+const invoke = (page: Page, name: string, ...args: unknown[]) => page.evaluate((n, a) => (window as any).__kilnScene.invoke(n, ...a), name, args); // eslint-disable-line @typescript-eslint/no-explicit-any+const waitFrames = (page: Page, n: number) => page.evaluate(count => (window as any).__kilnScene.waitFrames(count), n); // eslint-disable-line @typescript-eslint/no-explicit-any+async function until(page: Page, hook: string, args: unknown[], test: string, timeout = 120_000) {+ await page.waitForFunction((n, a, t) => { const value = (window as any).__kilnScene.invoke(n, ...a); return new Function('v', `return (${t});`)(value); }, { timeout, polling: 200 }, hook, args, test); // eslint-disable-line @typescript-eslint/no-explicit-any+}+// Views and workloads are the scenes' own: Farm layout views (scene-fixtures FARM_VIEWS) and src/play/workloads.ts; Foundry+// Floor campus views (FOUNDRY_CAMPUS_VIEWS), fab views (FOUNDRY_FAB_VIEWS, entered through the arrival canopy) and the sedan+// drive (campus/exterior/Drive.tsx); Golden Gate cameras (GG_CAMERAS) and src/camera/workloads.ts orbit, flyover, drive.+const FARM_VIEWS = ['hero', 'opposite', 'top', 'eye-height', 'crops', 'fences', 'props', 'watermill-wheel', 'watermill-interior', 'house-interior', 'house-porch', 'house-window-out'] as const;+const FF_CAMPUS = ['campus', 'pair', 'canopy', 'split', 'bridge', 'roundabout'] as const;+const FF_FAB = ['landing', 'overview', 'spine', 'litho', 'cluster', 'stocker', 'gallery', 'section'] as const;+const GG_CAMERAS = ['arrival', 'postcard', 'pier', 'topdown', 'horizon', 'deck', 'tower', 'span', 'lanes', 'sidewalk', 'traffic'] as const;+export const SCENES: Readonly<Record<SceneId, SceneTiming>> = {+ farm: {+ views: FARM_VIEWS, workloads: ['living-orbit', 'living-route', 'walk', 'tractor-drive'],+ query: (kind, name) => ({ view: kind === 'view' ? name : 'hero' }),+ async engage(page, kind, name) { if (kind === 'view') await invoke(page, 'setView', name); else await page.evaluate(n => (window as any).__kilnScene.runWorkload(n), name); }, // eslint-disable-line @typescript-eslint/no-explicit-any+ async state(page) { const s = await invoke(page, 'simState') as any; return { pose: s?.camera ?? await invoke(page, 'cameraPose') ?? null, workload: s ? { active: s.active, driving: s.driving, drivenMeters: s.drivenMeters ?? null } : null }; }, // eslint-disable-line @typescript-eslint/no-explicit-any+ engaged: (kind, name, s) => kind === 'view' || (name === 'tractor-drive' ? s.workload?.driving === true : name === 'walk' ? s.workload?.active === true && s.workload.driving === false : true),+ },+ 'foundry-floor': {+ views: [...FF_CAMPUS, ...FF_FAB.map(v => `fab-${v}`)], workloads: ['drive'],+ query: () => ({ capture: '1' }),+ async engage(page, kind, name) {+ await until(page, 'driveTraffic', [1], 'v !== null');+ if (kind === 'workload') { await page.evaluate(n => (window as any).__kilnScene.runWorkload(n), name); return; } // eslint-disable-line @typescript-eslint/no-explicit-any+ if (name.startsWith('fab-')) {+ // scene-fixtures FOUNDRY_FIXTURES fab entry: Arrival, the canopy prompt, enter, the interior ready.+ await invoke(page, 'campusView', 'canopy'); await until(page, 'campusState', [], 'v && v.canEnter');+ await invoke(page, 'campusEnter'); await until(page, 'campusPlace', [], 'v.interiorReady && !v.moving');+ await invoke(page, 'ffSetView', name.slice(4)); await waitFrames(page, 12); return;+ }+ await invoke(page, 'campusView', name); await waitFrames(page, 18);+ },+ async state(page) { const c = await invoke(page, 'campusState') as any, d = await invoke(page, 'driveState') as any; return { pose: d?.camera?.position ?? c?.camera?.position ?? null, workload: d ? { u: d.u, v: d.v, speed: d.speed } : null }; }, // eslint-disable-line @typescript-eslint/no-explicit-any+ engaged: (kind, _name, s) => kind === 'view' || (s.workload !== null && Math.abs(Number(s.workload.speed)) > .5),+ },+ 'golden-gate': {+ views: GG_CAMERAS, workloads: ['orbit', 'flyover', 'drive'],+ query: (kind, name) => ({ capture: '1', hud: '0', preset: 'day', cam: kind === 'view' ? name : 'arrival' }),+ async engage(page, kind, name) { if (kind === 'view') { await invoke(page, 'setView', name); await waitFrames(page, 20); } else await page.evaluate(n => (window as any).__kilnScene.runWorkload(n), name); }, // eslint-disable-line @typescript-eslint/no-explicit-any+ async state(page) { const g = await invoke(page, 'ggStats') as any, d = await invoke(page, 'driveState') as any; return { pose: g?.camera?.position ?? null, workload: { mode: g?.camera?.mode ?? null, drive: d ? { z: d.z, speed: d.speed } : null } }; }, // eslint-disable-line @typescript-eslint/no-explicit-any+ engaged: (kind, name, s) => kind === 'view' || (name === 'orbit' ? s.workload?.mode === 'orbit' : name === 'flyover' ? s.workload?.mode === 'flight' : Math.abs(Number((s.workload?.drive as any)?.speed ?? 0)) > 1), // eslint-disable-line @typescript-eslint/no-explicit-any+ },+};+export function cellKind(cell: Cell): Kind {+ const s = SCENES[cell.scene];+ if (s.views.includes(cell.name)) return 'view';+ if (s.workloads.includes(cell.name)) return 'workload';+ throw new Error(`${cell.scene} has no view or workload ${cell.name}; views ${s.views.join(', ')}; workloads ${s.workloads.join(', ')}`);+}+export function cellUrl(base: string, cell: Cell, extra: Record<string, string> = {}): string {+ const query = new URLSearchParams({ ...SCENES[cell.scene].query(cellKind(cell), cell.name), tier: cell.tier, ...extra });+ return `${base.replace(/[/]+$/, '')}/?${query}`;+}++// ---------------------------------------------------------------- CLI options++const argv = process.argv.slice(2), command = argv[0] ?? 'help';+const flag = (name: string) => argv.includes(name);+const option = (name: string, fallback?: string) => { const at = argv.indexOf(name); if (at < 0) return fallback; const value = argv[at + 1]; if (value === undefined || value.startsWith('--')) throw new Error(`${name} needs a value`); return value; };+const many = (name: string) => argv.flatMap((value, at) => argv[at - 1] === name ? [value] : []);+const here = dirname(fileURLToPath(import.meta.url));+const kitRoot = () => resolve(option('--kit', resolve(here, '..'))!);+const sleep = (ms: number) => new Promise(done => setTimeout(done, ms));+const run = (file: string, args: string[], timeout = 10_000) => new Promise<string | null>(done => execFile(file, args, { timeout, windowsHide: true, maxBuffer: 8 << 20 }, (error, stdout) => done(error ? null : String(stdout))));+const now = () => new Date().toISOString();+async function writeJson(path: string, value: unknown) { await mkdir(dirname(path), { recursive: true }); await writeFile(path, JSON.stringify(value, null, 1) + '\n'); return path; }++// ---------------------------------------------------------------- host load (hub, this PC) and tablet state++const GPU_FIELDS = ['utilization.gpu', 'temperature.gpu', 'clocks.gr', 'memory.used', 'pstate'] as const;+async function gpuRow() { const out = await run('nvidia-smi', [`--query-gpu=${GPU_FIELDS.join(',')}`, '--format=csv,noheader,nounits'], 8000); return out ? parseNvidiaSmi(out, GPU_FIELDS)[0] ?? null : null; }+async function cpuCounters() {+ if (process.platform === 'linux') return parseProcStat(await readFile('/proc/stat', 'utf8'));+ return cpus().reduce((s, c) => { const t = c.times; return { total: s.total + t.user + t.nice + t.sys + t.idle + t.irq, idle: s.idle + t.idle }; }, { total: 0, idle: 0 });+}+/** Per-process CPU jiffies (Linux): the busiest processes over a window, outside a set of excluded process trees. */+async function procTicks() {+ const out = new Map<number, { parent: number; name: string; ticks: number; start: number }>();+ if (process.platform !== 'linux') return out;+ for (const entry of readdirSync('/proc')) {+ if (!/^\d+$/.test(entry)) continue;+ try { const text = await readFile(`/proc/${entry}/stat`, 'utf8'), end = text.lastIndexOf(')'), f = text.slice(end + 2).split(' ');+ out.set(Number(entry), { parent: Number(f[1]), name: text.slice(text.indexOf('(') + 1, end), ticks: Number(f[11]) + Number(f[12]), start: Number(f[19]) }); } catch { /* exited */ }+ }+ return out;+}+function externalBusiest(before: Map<number, { parent: number; name: string; ticks: number; start: number }>, after: typeof before, seconds: number, roots: number[]) {+ const mine = new Set(roots), descends = (pid: number): boolean => { for (let p = pid, hops = 0; p > 1 && hops < 64; hops++) { if (mine.has(p)) return true; p = after.get(p)?.parent ?? before.get(p)?.parent ?? 0; } return false; };+ const hz = 100, logical = cpus().length;+ return [...after.entries()].flatMap(([pid, p]) => { const b = before.get(pid); if (!b || b.start !== p.start || descends(pid)) return []; const pct = 100 * (p.ticks - b.ticks) / hz / (seconds * logical); return pct > .05 ? [{ pid, name: p.name, machineCpuPercent: round(pct, 3) }] : []; })+ .sort((x, y) => (y.machineCpuPercent ?? 0) - (x.machineCpuPercent ?? 0)).slice(0, 8);+}+async function hostState() {+ const read = async (path: string) => { try { return (await readFile(path, 'utf8')).trim(); } catch { return null; } };+ const linux = process.platform === 'linux';+ const temp = linux ? await (async () => { for (const hw of readdirSync('/sys/class/hwmon')) { if (await read(`/sys/class/hwmon/${hw}/name`) === 'k10temp') return Number(await read(`/sys/class/hwmon/${hw}/temp1_input`)) / 1000; } return null; })().catch(() => null) : null;+ const locker = linux ? await run('gdbus', ['call', '--session', '--dest', 'org.freedesktop.ScreenSaver', '--object-path', '/ScreenSaver', '--method', 'org.freedesktop.ScreenSaver.GetActive'], 5000) : null;+ return { host: hostname(), os: `${osType()} ${release()}`, cpu: cpus()[0]?.model ?? null, logicalCpus: cpus().length,+ loadavg: linux ? parseLoadavg(await read('/proc/loadavg') ?? '') : null, cpuTempC: temp, acOnline: linux ? await read('/sys/class/power_supply/AC0/online') : null,+ governor: linux ? await read('/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor') : null, who: linux ? parseWho(await run('who', []) ?? '') : null,+ loginctlSessions: linux ? parseWho(await run('loginctl', ['list-sessions', '--no-legend']) ?? '') : null,+ top: linux ? parseTop(await run('top', ['-b', '-n', '1', '-o', '%CPU', '-w', '200']) ?? '') : null,+ screenLockerActive: locker === null ? null : /true/.test(locker), gpu: await gpuRow() };+}+/** The quiet window: `samples` readings `intervalSeconds` apart of whole-machine CPU and NVIDIA GPU, with the busiest processes over it. */+async function quietWindow(rule: QuietRule) {+ const ticks = await procTicks(), started = Date.now(); let previous = await cpuCounters(); const rows: { at: string; cpuPercent: number | null; gpu: Record<string, unknown> | null }[] = [];+ for (let i = 0; i < rule.samples; i++) { await sleep(rule.intervalSeconds * 1000); const current = await cpuCounters(); rows.push({ at: now(), cpuPercent: round(cpuPercent(previous, current)), gpu: await gpuRow() }); previous = current; }+ const state = await hostState();+ const verdict = quietVerdict({ cpu: rows.map(r => r.cpuPercent ?? NaN), gpu: rows.map(r => (r.gpu?.['utilization.gpu'] as number | null) ?? null), screenLocked: state.screenLockerActive }, rule);+ return { at: now(), ...verdict, busiestProcesses: externalBusiest(ticks, await procTicks(), (Date.now() - started) / 1000, [process.pid]), hostState: state, samples: rows };+}+const hostRule = (): QuietRule => process.platform === 'linux' ? HUB_RULE : PC_RULE;+/** Waits for a quiet window (retrying every 30 s up to `minutes`); never times on a busy machine. */+async function preflight(rule: QuietRule, minutes: number) {+ const attempts = []; const until = Date.now() + minutes * 60_000;+ for (;;) {+ const w = await quietWindow(rule); attempts.push(w);+ console.log(JSON.stringify({ event: 'preflight', attempt: attempts.length, quiet: w.quiet, cpuMean: round(w.cpuMean, 2), cpuMax: round(w.cpuMax, 2), gpuMax: w.gpuMax, reasons: w.reasons, busiest: w.busiestProcesses.slice(0, 3) }));+ if (w.quiet || Date.now() > until) return { quiet: w.quiet, attempts: attempts.length, final: w, earlier: attempts.slice(0, -1).map(a => ({ at: a.at, quiet: a.quiet, cpuMean: a.cpuMean, cpuMax: a.cpuMax, gpuMax: a.gpuMax, reasons: a.reasons })) };+ await sleep(30_000);+ }+}+async function tabletReading(adb: Adb) {+ const text = await adb.shell('dumpsys battery; echo @@thermal; dumpsys thermalservice | grep -m1 "Thermal Status"; echo @@gpu; cat /sys/kernel/gpu/gpu_busy /sys/kernel/gpu/gpu_clock /sys/kernel/gpu/gpu_tmu 2>/dev/null').catch(error => `error ${String(error)}`);+ const [battery = '', rest = ''] = text.split('@@thermal'), [thermal = '', gpu = ''] = rest.split('@@gpu'), g = gpu.trim().split(/\s+/);+ const b = parseBattery(battery);+ return { at: now(), batteryC: b.temperatureC, batteryLevel: b.level, thermalStatus: parseThermalStatus(thermal), gpuBusyPercent: g[0] ? parseFloat(g[0]) : null, gpuClockKHz: g[1] ? Number(g[1]) : null, gpuTemperatureC: g[2] ? Number(g[2]) : null };+}+async function tabletQuietWindow(adb: Adb) {+ const snap = async () => { const lines = (await adb.shell('cat /proc/stat; echo @@; cat /sys/kernel/gpu/gpu_busy 2>/dev/null')).split('@@'); return { cpu: parseProcStat(lines[0]!), gpu: parseFloat(lines[1]?.trim() ?? '') }; };+ let previous = await snap(); const rows: { cpuPercent: number | null; gpuBusyPercent: number | null }[] = [];+ for (let i = 0; i < TABLET_RULE.samples; i++) { await sleep(TABLET_RULE.intervalSeconds * 1000); const current = await snap(); rows.push({ cpuPercent: round(cpuPercent(previous.cpu, current.cpu)), gpuBusyPercent: Number.isFinite(current.gpu) ? current.gpu : null }); previous = current; }+ return { at: now(), ...quietVerdict({ cpu: rows.map(r => r.cpuPercent ?? NaN), gpu: rows.map(r => r.gpuBusyPercent) }, TABLET_RULE), samples: rows };+}+/** Samples load every `everyMs` while a run samples frames; stopped by the returned function. */+function startLoadSampler(device: 'local' | 'tablet', adb: Adb | null, everyMs: number) {+ const samples: unknown[] = []; let stopped = false, previous: { total: number; idle: number } | null = null, tick = 0;+ const loop = (async () => {+ if (device === 'local') previous = await cpuCounters();+ while (!stopped) {+ await sleep(everyMs); if (stopped) break; tick++;+ // Tablet: Mali GPU busy and clock every tick (two sysfs reads); battery, thermal status and GPU temperature every 15 s.+ if (device === 'tablet' && adb) {+ if (tick % Math.max(1, Math.round(15_000 / everyMs)) === 0) samples.push(await tabletReading(adb));+ else { const g = (await adb.shell('cat /sys/kernel/gpu/gpu_busy /sys/kernel/gpu/gpu_clock 2>/dev/null').catch(() => '')).trim().split(/\s+/); samples.push({ at: now(), gpuBusyPercent: g[0] ? parseFloat(g[0]) : null, gpuClockKHz: g[1] ? Number(g[1]) : null }); }+ } else { const current = await cpuCounters(); samples.push({ at: now(), cpuPercent: round(cpuPercent(previous!, current)), gpu: await gpuRow() }); previous = current; }+ }+ })();+ return async () => { stopped = true; await loop; return samples; };+}++// ---------------------------------------------------------------- page measurement++const PAGE_CSS = 'body>header,body>footer{display:none!important}';+/** Before any page script: the rAF interval recorder (the Farm and Golden Gate runners' method), readiness seen on the first frame after onReady, and renderer.info sampled every 30 recorded frames. */+function installRecorder() {+ const w = window as any; // eslint-disable-line @typescript-eslint/no-explicit-any+ if (w.__ab) return;+ const rec = w.__ab = { readyAt: null as number | null, error: null as unknown, recording: false, intervals: [] as number[], last: null as number | null, draws: [] as number[], triangles: [] as number[], idle: [] as number[], idleLast: null as number | null, idleOn: false };+ const tick = (t: number) => {+ if (rec.idleOn) { if (rec.idleLast !== null) rec.idle.push(t - rec.idleLast); rec.idleLast = t; }+ if (rec.readyAt === null && !rec.error) { try { const s = w.__kilnHarness?.snapshot(); if (s?.errors?.length) rec.error = s.errors[0]; else if ((s?.readyCount ?? 0) > 0) rec.readyAt = t; } catch { /* booting */ } }+ if (rec.recording) {+ if (rec.last !== null) rec.intervals.push(t - rec.last);+ rec.last = t;+ if (rec.intervals.length % 30 === 0) { const r = w.__kilnScene?.stats()?.render; if (r) { rec.draws.push(r.drawCalls); rec.triangles.push(r.triangles); } }+ } else rec.last = null;+ requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+}+function installCss(css: string) { const add = () => { const s = document.createElement('style'); s.textContent = css; document.head.append(s); }; if (document.head) add(); else document.addEventListener('DOMContentLoaded', add, { once: true }); }+/** The display rate on an idle page (about:blank) just before the run: 1.5 s of rAF intervals. */+async function measureDisplay(page: Page) {+ await page.goto('about:blank');+ // Every frame repaints a small box, so the compositor has damage each frame and does not throttle an idle page.+ const intervals = await page.evaluate(() => new Promise<number[]>(done => { const out: number[] = []; let last: number | null = null, start: number | null = null, n = 0;+ const box = document.createElement('div'); box.style.cssText = 'position:fixed;left:0;top:0;width:8px;height:8px'; document.documentElement.append(box);+ const tick = (t: number) => { start ??= t; if (last !== null) out.push(t - last); last = t; box.style.background = ++n % 2 ? '#000' : '#fff'; if (t - start < 1500) requestAnimationFrame(tick); else { box.remove(); done(out); } }; requestAnimationFrame(tick); }));+ return { ...displayRate(intervals), method: 'lower-quartile rAF interval over 1.5 s on about:blank in the same tab just before the run, a box repainted every frame', intervalsMs: intervals.map(v => round(v)) };+}++interface Served { side: Side; label: string; root: string; base: string; port: number; build: unknown; close(): Promise<void> }+async function serve(side: Side, root: string, ports: [number, number], taken: Set<number>): Promise<Served> {+ if (!existsSync(resolve(root, 'index.html'))) throw new Error(`No test build at ${root}`);+ const buildFile = resolve(root, 'build.json'), build = existsSync(buildFile) ? JSON.parse(readFileSync(buildFile, 'utf8')) : null;+ for (let port = ports[0]; port <= ports[1]; port++) {+ if (taken.has(port)) continue;+ try { const s = await startStaticServer({ root, port }); taken.add(port);+ // Chrome keeps connections alive (on the tablet through adb reverse), so they are cut before the server closes.+ const close = () => Promise.race([(s.server.closeAllConnections?.(), s.close()), sleep(5000)]) as Promise<void>;+ return { side, label: build?.label ?? root, root, base: s.url, port, build: build && { label: build.label, scene: build.scene, mode: build.mode, release: build.release, chunks: build.chunks?.map((c: { name: string }) => c.name), source: build.source }, close };+ } catch (error) { if ((error as { code?: string }).code !== 'EADDRINUSE') throw error; }+ }+ throw new Error(`No free port in ${ports[0]}-${ports[1]}`);+}++interface MeasureOptions { device: 'local' | 'tablet'; seconds: number; warmupMs: number; width: number; height: number; backend: 'webgpu'; extra: Record<string, string>; adb: Adb | null; loadEveryMs: number; browserPid: number | null }+async function measure(browser: Browser, served: Served, cell: Cell, o: MeasureOptions) {+ const page = await browser.newPage(), messages: { type: string; text: string }[] = [];+ page.on('console', m => { if ((m.type() === 'error' || m.type() === 'warn') && messages.length < 100) messages.push({ type: m.type(), text: m.text().slice(0, 400) }); });+ page.on('pageerror', e => { if (messages.length < 100) messages.push({ type: 'pageerror', text: String(e).slice(0, 400) }); });+ try {+ await page.bringToFront().catch(() => undefined);+ if (o.device === 'local') await page.setViewport({ width: o.width, height: o.height, deviceScaleFactor: 1 });+ await page.evaluateOnNewDocument(installRecorder); await page.evaluateOnNewDocument(installCss, PAGE_CSS);+ const display = await measureDisplay(page);+ const url = cellUrl(served.base, cell, o.extra), started = Date.now();+ await page.goto(url, { waitUntil: 'load', timeout: 180_000 });+ await page.waitForFunction(() => (window as any).__ab.readyAt !== null || (window as any).__ab.error, { timeout: 180_000, polling: 100 }); // eslint-disable-line @typescript-eslint/no-explicit-any+ const setup = await page.evaluate(() => {+ const w = window as any, api = w.__kilnScene, host = w.__kilnHarness.snapshot(); // eslint-disable-line @typescript-eslint/no-explicit-any+ if (w.__ab.error) return { error: w.__ab.error };+ api.feedFrameTimes([]); // the governor is held at the tier's level 0 (as perf.ts and perf-core.ts X-05)+ return { error: null, errors: host.errors, readyAt: w.__ab.readyAt, backend: document.querySelector('.ks-root')?.getAttribute('data-kiln-backend') ?? null, tier: api.tierState(), msaaPolicy: api.invoke('msaaPolicy') ?? null };+ });+ if (setup.error) throw new Error(`Scene failed: ${JSON.stringify(setup.error)}`);+ if (setup.backend !== o.backend) throw new Error(`${served.side} runs ${setup.backend}, not ${o.backend}`);+ if (setup.tier?.tier !== cell.tier || setup.tier.level !== 0) throw new Error(`${served.side} tier is ${setup.tier?.tier} level ${setup.tier?.level}, not ${cell.tier} level 0`);+ // The page holds a screen wake lock (run-farm-tablet.ts openTab), so the tablet panel stays on through the sample.+ const wakeLock = await page.evaluate(async () => { try { (window as any).__abWakeLock = await (navigator as any).wakeLock.request('screen'); return 'held'; } catch (error) { return String(error); } }); // eslint-disable-line @typescript-eslint/no-explicit-any+ const kind = cellKind(cell), scene = SCENES[cell.scene];+ await scene.engage(page, kind, cell.name);+ if (o.warmupMs) await sleep(o.warmupMs);+ const before = await scene.state(page), clock0 = await page.evaluate(() => (window as any).__kilnScene.motionPolicy().time as number); // eslint-disable-line @typescript-eslint/no-explicit-any+ const ticks = await procTicks(), t0 = Date.now();+ await page.evaluate(() => { const w = window as any, rec = w.__ab; w.__kilnScene.beginMeasurement(); rec.intervals = []; rec.draws = []; rec.triangles = []; rec.last = null; rec.recording = true; }); // eslint-disable-line @typescript-eslint/no-explicit-any+ const stopLoad = startLoadSampler(o.device, o.adb, o.loadEveryMs);+ await sleep(o.seconds * 1000);+ const end = await page.evaluate(() => {+ const w = window as any, api = w.__kilnScene, rec = w.__ab, host = w.__kilnHarness.snapshot(); // eslint-disable-line @typescript-eslint/no-explicit-any+ rec.recording = false; api.recordFrames(false); const s = api.stats();+ const canvas = document.querySelector('.ks-root canvas') as HTMLCanvasElement | null;+ return { intervals: rec.intervals as number[], draws: rec.draws as number[], triangles: rec.triangles as number[], cpu: api.cpuRenderTimes() as number[], tier: api.tierState(), clock: api.motionPolicy().time as number,+ errors: host.errors, visibility: document.visibilityState, longTasks: s.longTasks ?? null, pipelines: s.pipelines ?? null, msaaPolicy: api.invoke('msaaPolicy') ?? null,+ canvas: canvas ? { buffer: [canvas.width, canvas.height], css: [canvas.clientWidth, canvas.clientHeight], dpr: devicePixelRatio } : null };+ });+ const during = await stopLoad(), seconds = (Date.now() - t0) / 1000;+ const after = await scene.state(page);+ const external = process.platform === 'linux' && o.device === 'local' ? externalBusiest(ticks, await procTicks(), seconds, [process.pid, ...(o.browserPid ? [o.browserPid] : [])]) : null;+ const env = await page.evaluate(async () => { const a = await (navigator as any).gpu?.requestAdapter?.().catch(() => null), i = a?.info; return { userAgent: navigator.userAgent, adapter: i ? { vendor: i.vendor, architecture: i.architecture, device: i.device, description: i.description } : null, inner: [innerWidth, innerHeight], dpr: devicePixelRatio }; }); // eslint-disable-line @typescript-eslint/no-explicit-any+ const stats = frameStats(end.intervals), cpu = frameStats(end.cpu), share = refreshShare(end.intervals, display.periodMs ?? NaN), hitches = hitchCounts(end.intervals);+ const checks = { backend: setup.backend, tierHeldAtLevel0: end.tier?.tier === cell.tier && end.tier?.level === 0, clockAdvanced: end.clock > clock0, engaged: scene.engaged(kind, cell.name, before),+ movedForWorkload: kind === 'view' ? null : JSON.stringify(before.pose) !== JSON.stringify(after.pose), noErrors: end.errors.length === 0, pageVisible: end.visibility === 'visible',+ coverage: round(stats.sampledMs / (o.seconds * 1000), 3), displayMeasured: !!display.periodMs,+ refreshMismatch: !!display.periodMs && stats.p50 !== null && stats.p50 < .75 * display.periodMs };+ const valid = checks.tierHeldAtLevel0 && checks.clockAdvanced && checks.engaged && checks.movedForWorkload !== false && checks.noErrors && checks.pageVisible && (checks.coverage ?? 0) >= .9 && checks.displayMeasured && !checks.refreshMismatch;+ const metrics: RunMetrics = { p50: stats.p50, p95: stats.p95, p99: stats.p99, max: stats.max, fps: stats.fps, withinOne: share.withinOne, withinTwo: share.withinTwo, over50: hitches.over50, over100: hitches.over100,+ longestMs: hitches.longestMs, cpuRenderP50: cpu.p50, cpuRenderP95: cpu.p95, drawsMedian: median(end.draws), trianglesMedian: median(end.triangles), gpuBusy: gpuBusyMedian(during) };+ return { valid, checks, url, readyMs: round(setup.readyAt, 1), wakeLock, display, frames: stats, refresh: share, hitches, d41: d41Verdict(hitches, { row: o.device === 'tablet' ? 'tablet' : 'desktop', seconds: o.seconds }),+ cpuRenderMs: { ...cpu, sampledMs: undefined }, draws: { median: median(end.draws), min: end.draws.length ? Math.min(...end.draws) : null, max: end.draws.length ? Math.max(...end.draws) : null, samples: end.draws.length },+ triangles: { median: median(end.triangles), samples: end.triangles.length }, metrics, msaaPolicy: { atStart: setup.msaaPolicy, atEnd: end.msaaPolicy }, tier: { start: setup.tier && { tier: setup.tier.tier, level: setup.tier.level, device: setup.tier.device }, end: end.tier && { tier: end.tier.tier, level: end.tier.level } },+ workload: { kind, before, after }, canvas: end.canvas, longTasks: end.longTasks, pipelines: end.pipelines, environment: env, loadDuring: during, externalBusiest: external, messages, sampleWallSeconds: round(seconds, 2), startedToSampleMs: t0 - started,+ frameIntervalsMs: end.intervals.map(v => round(v)), cpuRenderTimesMs: end.cpu.map(v => round(v)) };+ } finally { await page.close().catch(() => undefined); }+}++// ---------------------------------------------------------------- the A/B block++async function launchLocal(profile: string, headless: boolean, width: number, height: number) {+ const chrome = option('--chrome', process.platform === 'win32' ? 'C:/Program Files/Google/Chrome/Application/chrome.exe' : '/opt/google/chrome/chrome')!;+ if (!existsSync(chrome)) throw new Error(`No Chrome at ${chrome}; pass --chrome <path>`);+ // perf.ts and perf-gg.mjs: a headed window pinned to the primary display's origin; the hub adds --ozone-platform=x11+ // --enable-features=Vulkan --start-fullscreen through --chrome-arg (two tokens each), with the session's DISPLAY and PRIME offload.+ const args = ['--no-first-run', '--no-default-browser-check', '--enable-unsafe-webgpu', `--window-size=${width},${height}`, ...(headless ? [] : ['--window-position=0,0']), ...many('--chrome-arg')];+ const browser = await puppeteer.launch({ executablePath: chrome, headless, pipe: true, userDataDir: profile, defaultViewport: null, args, protocolTimeout: 300_000 });+ return { browser, args, chrome };+}+interface TabletSession { browser: Browser; forward: number; reversed: number[]; anchor: Page | null }+async function tabletConnect(adb: Adb, ports: number[]): Promise<TabletSession> {+ const reversed: number[] = []; let forward: { port: number; browserURL: string } | null = null;+ try {+ for (const port of ports) { await reversePort(adb, port); reversed.push(port); }+ await wakeAndOpenChrome(adb); forward = await forwardDevtools(adb);+ const browser = await connectDevtools(forward.browserURL, 30_000);+ return { browser, forward: forward.port, reversed, anchor: null };+ } catch (error) {+ if (forward) await removeForward(adb, forward.port).catch(() => undefined);+ for (const port of reversed) await removeReverse(adb, port).catch(() => undefined);+ throw error;+ }+}+async function tabletRelease(adb: Adb, s: TabletSession | null) {+ const problems: string[] = [];+ if (!s) return { problems, mappings: await listMappings(adb).catch(e => String(e)) };+ try { await s.browser.disconnect(); } catch (e) { problems.push(`disconnect: ${String(e)}`); }+ try { await removeForward(adb, s.forward); } catch (e) { problems.push(`forward ${s.forward}: ${String(e)}`); }+ for (const port of s.reversed) try { await removeReverse(adb, port); } catch (e) { problems.push(`reverse ${port}: ${String(e)}`); }+ const mappings = await listMappings(adb).catch(e => String(e));+ const empty = typeof mappings !== 'string' && mappings.forward.length === 0 && mappings.reverse.length === 0;+ if (!empty) problems.push(`mappings left: ${JSON.stringify(mappings)}`);+ return { problems, mappings, empty };+}+async function waitCool(adb: Adb, minutes: number) {+ const until = Date.now() + minutes * 60_000, readings = [];+ for (;;) { const r = await tabletReading(adb), v = tabletCool(r); readings.push({ ...r, cool: v.cool, reasons: v.reasons }); if (v.cool || Date.now() > until) return { ...v, readings }; await sleep(30_000); }+}++async function abBlock() {+ const kit = kitRoot(), device = (option('--device', 'local') as 'local' | 'tablet');+ if (device !== 'local' && device !== 'tablet') throw new Error('--device is local or tablet');+ const cells = option('--cells', '')!.split(',').filter(Boolean).map(parseCell); if (!cells.length) throw new Error('--cells scene:tier:name[,…] is required');+ for (const c of cells) cellKind(c);+ const pairs = Number(option('--pairs', '3')), seconds = Number(option('--seconds', '60')), warmupMs = Number(option('--warmup', '5')) * 1000, primeSeconds = Number(option('--prime', '3'));+ const [width, height] = option('--size', '1920x1080')!.split('x').map(Number) as [number, number];+ // --a and --b are build-label folders holding one test build per scene (<label>/<scene>/index.html, as the kit packs them).+ const rootA = resolve(kit, option('--a', 'builds/draw-base')!), rootB = resolve(kit, option('--b', 'builds/wavea')!);+ const block = option('--block', `ab-${now().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')}`)!, out = resolve(option('--out', resolve(kit, 'results'))!, block);+ if (existsSync(resolve(out, 'block.json'))) throw new Error(`${out} already holds a block; choose another --block`);+ const extra = (name: string) => Object.fromEntries(new URLSearchParams(option(name, '') ?? ''));+ const query = { A: { ...extra('--query'), ...extra('--query-a') }, B: { ...extra('--query'), ...extra('--query-b') } };+ const plan = planRuns(cells, pairs);+ const record: Record<string, unknown> = { schema: 'kiln.timing-ab-block/1', block, device, startedAt: now(), runner: 'scripts/timing-ab.ts', node: process.version, platform: process.platform, host: hostname(),+ options: { pairs, seconds, warmupSeconds: warmupMs / 1000, primeSeconds, size: device === 'local' ? [width, height] : 'device viewport', query, headless: flag('--headless'), chromeArgs: many('--chrome-arg') },+ cells: cells.map(c => ({ ...c, kind: cellKind(c) })), plan: plan.map(p => ({ cell: cellId(p.cell), pair: p.pair, position: p.position, side: p.side })), runs: [] as unknown[] };+ const save = () => writeJson(resolve(out, 'block.json'), record);+ await mkdir(resolve(out, 'runs'), { recursive: true });+ // Two builds, two owned loopback ports (4400-4499: the device kit's range, so adb reverse maps the same numbers on the tablet).+ const taken = new Set<number>(), ports = (option('--ports', '4400-4489')!.split('-').map(Number)) as [number, number];+ const served = {} as Record<SceneId, { A: Served; B: Served }>;+ for (const scene of [...new Set(cells.map(c => c.scene))]) served[scene] = { A: await serve('A', resolve(rootA, scene), ports, taken), B: await serve('B', resolve(rootB, scene), ports, taken) };+ record.builds = Object.fromEntries(Object.entries(served).map(([scene, s]) => [scene, { A: { root: s.A.root, port: s.A.port, build: s.A.build }, B: { root: s.B.root, port: s.B.port, build: s.B.build } }]));+ let browser: Browser | null = null, profile: string | null = null, browserPid: number | null = null; const adb = device === 'tablet' ? adbFor() : null;+ let stopped: string | null = null;+ try {+ if (device === 'local') {+ record.preflight = flag('--no-preflight') ? { skipped: 'Not evidence: --no-preflight' } : await preflight(hostRule(), Number(option('--wait-quiet', '10')));+ await save();+ if (!flag('--no-preflight') && !(record.preflight as { quiet: boolean }).quiet) { stopped = 'host not quiet: nothing timed'; throw new Error(`STOP: ${stopped}`); }+ profile = await mkdtemp(resolve(kit, 'tmp-profile-')); const launched = await launchLocal(profile, flag('--headless'), width, height);+ browser = launched.browser; browserPid = launched.browser.process()?.pid ?? null;+ record.browser = { version: await browser.version(), chrome: launched.chrome, args: launched.args, pid: browserPid };+ } else {+ const devices = await adbDevices(); record.adbDevices = devices.devices;+ if (!devices.devices.some(d => d.serial === adb!.serial && d.state === 'device')) throw new Error(`Tablet ${adb!.serial} is not attached`);+ const before = await listMappings(adb!); record.mappingsBefore = before;+ if (before.forward.length || before.reverse.length) throw new Error(`The tablet already has port mappings ${JSON.stringify(before)}; not starting`);+ record.deviceBefore = await deviceState(adb!);+ const cool = await waitCool(adb!, Number(option('--cool-wait', '10'))); record.coolBefore = cool;+ if (!cool.cool) { stopped = `tablet not cool: ${cool.reasons.join('; ')}`; throw new Error(`STOP: ${stopped}`); }+ // The pilot's tablet window, retried every 30 s for up to --wait-quiet minutes (golden-gate tablet-check.ts preflight).+ const attempts: Awaited<ReturnType<typeof tabletQuietWindow>>[] = [], quietUntil = Date.now() + Number(option('--wait-quiet', '10')) * 60_000;+ for (;;) {+ const w = await tabletQuietWindow(adb!); attempts.push(w);+ console.log(JSON.stringify({ event: 'tablet-preflight', attempt: attempts.length, quiet: w.quiet, cpuMean: round(w.cpuMean, 2), cpuMax: w.cpuMax, gpuMax: w.gpuMax, reasons: w.reasons }));+ if (w.quiet || Date.now() > quietUntil) break; await sleep(30_000);+ }+ const quiet = attempts.at(-1)!; record.tabletPreflight = { ...quiet, attempts: attempts.length, earlier: attempts.slice(0, -1).map(a => ({ at: a.at, quiet: a.quiet, cpuMean: a.cpuMean, cpuMax: a.cpuMax, gpuMax: a.gpuMax, reasons: a.reasons })) };+ if (!quiet.quiet && !flag('--no-preflight')) { stopped = `tablet not quiet: ${quiet.reasons.join('; ')}`; throw new Error(`STOP: ${stopped}`); }+ }+ await save();+ // One discarded load per side warms the HTTP and shader caches equally before the first measured run.+ if (primeSeconds > 0) {+ const primes = [];+ for (const cell of cells) for (const side of ['A', 'B'] as const) {+ let session: TabletSession | null = null; const prime: Record<string, unknown> = { cell: cellId(cell), side };+ try {+ session = device === 'tablet' ? await tabletConnect(adb!, [served[cell.scene][side].port]) : null;+ const page = await (session?.browser ?? browser!).newPage();+ try { if (device === 'local') await page.setViewport({ width, height, deviceScaleFactor: 1 }); await page.evaluateOnNewDocument(installRecorder); await page.evaluateOnNewDocument(installCss, PAGE_CSS);+ await page.goto(cellUrl(served[cell.scene][side].base, cell, query[side]), { waitUntil: 'load', timeout: 180_000 });+ await page.waitForFunction(() => (window as any).__ab.readyAt !== null || (window as any).__ab.error, { timeout: 180_000, polling: 200 }); await sleep(primeSeconds * 1000); // eslint-disable-line @typescript-eslint/no-explicit-any+ prime.ok = true; } finally { await page.close().catch(() => undefined); }+ } catch (error) { prime.ok = false; prime.error = String(error).slice(0, 300); }+ finally { if (device === 'tablet') { const r = await tabletRelease(adb!, session); prime.mappingsEmpty = r.empty ?? null; if (r.problems.length) stopped ??= `mapping cleanup after prime: ${r.problems.join('; ')}`; } }+ primes.push(prime); console.log(JSON.stringify({ event: 'prime', ...prime }));+ if (stopped) throw new Error(`STOP: ${stopped}`);+ }+ record.primes = primes; await save();+ }+ for (const planned of plan) {+ const cell = planned.cell, side = planned.side, label = `${cellId(cell)}-pair${planned.pair}-${side}`;+ let session: TabletSession | null = null, cool: unknown = null;+ const entry: Record<string, unknown> = { label, cell: cellId(cell), pair: planned.pair, position: planned.position, side };+ try {+ if (device === 'tablet') {+ const c = await waitCool(adb!, Number(option('--cool-wait', '10'))); cool = c;+ if (!c.cool) { stopped = `tablet not cool before ${label}: ${c.reasons.join('; ')}`; throw new Error(`STOP: ${stopped}`); }+ session = await tabletConnect(adb!, [served[cell.scene][side].port]);+ }+ const loadBefore = device === 'local' ? { at: now(), cpuPercent: null, gpu: await gpuRow(), loadavg: process.platform === 'linux' ? parseLoadavg(await readFile('/proc/loadavg', 'utf8')) : null } : await tabletReading(adb!);+ const result = await measure(session?.browser ?? browser!, served[cell.scene][side], cell, { device, seconds, warmupMs, width, height, backend: 'webgpu', extra: query[side], adb, loadEveryMs: device === 'tablet' ? 2_000 : 5_000, browserPid });+ const loadAfter = device === 'local' ? { at: now(), gpu: await gpuRow(), loadavg: process.platform === 'linux' ? parseLoadavg(await readFile('/proc/loadavg', 'utf8')) : null } : await tabletReading(adb!);+ const fileRecord = { schema: 'kiln.timing-ab-run/1', block, device, cell: { ...cell, kind: cellKind(cell) }, side, label: served[cell.scene][side].label, pair: planned.pair, position: planned.position, seconds, warmupSeconds: warmupMs / 1000,+ build: served[cell.scene][side].build, query: query[side], startedAt: now(), loadBefore, loadAfter, coolBefore: cool, ...result };+ await writeJson(resolve(out, 'runs', `${label}.json`), fileRecord);+ Object.assign(entry, { valid: result.valid, p50: round(result.frames.p50, 2), p95: round(result.frames.p95, 2), withinOne: round(result.refresh.withinOne, 4), withinTwo: round(result.refresh.withinTwo, 4), over50: result.hitches.over50, over100: result.hitches.over100, longestMs: round(result.hitches.longestMs, 1), draws: result.draws.median, periodMs: round(result.display.periodMs, 3), msaa: result.msaaPolicy.atEnd });+ console.log(JSON.stringify({ event: 'run', ...entry }));+ if (device === 'tablet') { const t = tabletCool(loadAfter as { thermalStatus: number | null; batteryC: number | null }); if (!t.cool) { stopped = `tablet warmed during ${label}: ${t.reasons.join('; ')}`; } }+ } catch (error) {+ entry.error = String((error as Error)?.message ?? error).slice(0, 1000); console.log(JSON.stringify({ event: 'run-failed', ...entry }));+ if (/STOP:/.test(String(error))) stopped ??= String(error);+ } finally {+ if (device === 'tablet') { const r = await tabletRelease(adb!, session); entry.mappingsAfter = r.mappings; entry.mappingsEmpty = r.empty ?? null; if (r.problems.length) { stopped ??= `mapping cleanup: ${r.problems.join('; ')}`; } }+ (record.runs as unknown[]).push(entry); await save();+ }+ if (stopped) break;+ }+ } catch (error) { stopped ??= String((error as Error)?.message ?? error); console.error(String((error as Error)?.stack ?? error)); }+ finally {+ if (browser) await browser.close().catch(() => undefined);+ if (profile) await rm(profile, { recursive: true, force: true }).catch(() => undefined);+ for (const s of Object.values(served)) { await s.A.close().catch(() => undefined); await s.B.close().catch(() => undefined); }+ if (device === 'tablet' && adb) { record.deviceAfter = await deviceState(adb).catch(e => String(e)); record.mappingsAtEnd = await listMappings(adb).catch(e => String(e)); }+ record.finishedAt = now(); record.stopped = stopped; await save();+ }+ const summary = await summarizeBlock(out);+ console.log(JSON.stringify({ event: 'block', block, out, stopped, cells: summary.cells.map(c => ({ cell: c.cell, A: c.A.valid, B: c.B.valid, p95: [c.A.p95?.median, c.B.p95?.median] })) }));+ if (stopped) process.exitCode = 2;+}++// ---------------------------------------------------------------- summary++const pct = (v: number | null | undefined) => typeof v === 'number' ? `${(100 * v).toFixed(1)}%` : '-';+const ms = (v: number | null | undefined, d = 2) => typeof v === 'number' ? v.toFixed(d) : '-';+export async function summarizeBlock(dir: string) {+ const files = existsSync(resolve(dir, 'runs')) ? readdirSync(resolve(dir, 'runs')).filter(f => f.endsWith('.json')).sort() : [];+ const runs = files.map(f => JSON.parse(readFileSync(resolve(dir, 'runs', f), 'utf8')));+ const block = existsSync(resolve(dir, 'block.json')) ? JSON.parse(readFileSync(resolve(dir, 'block.json'), 'utf8')) : {};+ const ids = [...new Set(runs.map(r => `${r.cell.scene}-${r.cell.tier}-${r.cell.name}`))];+ const cells = ids.map(id => {+ const list = runs.filter(r => `${r.cell.scene}-${r.cell.tier}-${r.cell.name}` === id);+ const s = summarizeCell(list.map(r => ({ side: r.side, pair: r.pair, valid: r.valid, metrics: { ...r.metrics, gpuBusy: r.metrics.gpuBusy ?? gpuBusyMedian(r.loadDuring ?? []) } })));+ const sideFacts = (side: Side) => { const l = list.filter(r => r.side === side); return { label: l[0]?.build?.label ?? null, chunks: l[0]?.build?.chunks ?? null, msaa: [...new Set(l.map(r => JSON.stringify(r.msaaPolicy?.atEnd ?? null)))], periodMs: median(l.map(r => r.display?.periodMs).filter(Number.isFinite)),+ d41: l.map(r => r.d41?.pass ?? null), invalid: l.filter(r => !r.valid).map(r => ({ pair: r.pair, checks: r.checks })) }; };+ return { cell: id, scene: list[0].cell.scene, tier: list[0].cell.tier, name: list[0].cell.name, kind: list[0].cell.kind, seconds: [...new Set(list.map(r => r.seconds))], facts: { A: sideFacts('A'), B: sideFacts('B') }, ...s };+ });+ const out = { schema: 'kiln.timing-ab-summary/1', block: block.block ?? null, device: block.device ?? null, generatedAt: now(), runs: runs.length, stopped: block.stopped ?? null,+ method: 'Per run: rAF frame intervals over the sample after a warm-up, governor held at the tier level 0. Per side: median (min-max) over valid runs. Paired: B - A within each interleaved pair (both runs valid), median over pairs, and how many pairs B was lower or higher. Refresh shares (OD-7): interval < 1.5 and < 2.5 measured display periods. D-41: 0 over 100 ms, 0 over 50 ms, longest <= 50 ms per 60 s run (tablet: at most 2 over 50 ms, 0 over 100 ms); judged only on runs of at least 60 s.',+ cells };+ await writeJson(resolve(dir, 'summary.json'), out);+ const md = [`# Timing A/B ${out.block ?? dir} (${out.device ?? '?'})`, '', out.method, '', `Runs: ${runs.length}.${out.stopped ? ` **Stopped: ${out.stopped}**` : ''}`, '',+ '| Cell | Side (label) | Valid | p50 ms | p95 ms | Within 1 refresh | Within 2 | >50 ms | >100 ms | Longest ms | CPU render p50 ms | GPU busy % | Draws | Period ms |', '|---|---|---|---|---|---|---|---|---|---|---|---|---|---|'];+ for (const c of cells) for (const side of ['A', 'B'] as const) {+ const x = c[side], f = c.facts[side];+ md.push(`| ${c.cell} | ${side} (${f.label}) | ${x.valid}/${x.runs} | ${ms(x.p50?.median)} (${ms(x.p50?.min)}-${ms(x.p50?.max)}) | ${ms(x.p95?.median)} (${ms(x.p95?.min)}-${ms(x.p95?.max)}) | ${pct(x.withinOne?.median)} | ${pct(x.withinTwo?.median)} | ${x.over50 ? `${x.over50.median} (max ${x.over50.max})` : '-'} | ${x.over100 ? `${x.over100.median} (max ${x.over100.max})` : '-'} | ${ms(x.longestMs?.max, 1)} | ${ms(x.cpuRenderP50?.median)} | ${x.gpuBusy ? `${ms(x.gpuBusy.median, 1)} (${ms(x.gpuBusy.min, 0)}-${ms(x.gpuBusy.max, 0)})` : '-'} | ${x.drawsMedian?.median ?? '-'} | ${ms(f.periodMs, 3)} |`);+ }+ md.push('', '| Cell | Pairs | Δp50 ms (B-A, median; B lower/higher) | Δp95 ms | Δ within 1 | Δ CPU render p50 ms | Δ GPU busy pt | p95 ratio B/A |', '|---|---|---|---|---|---|---|---|');+ for (const c of cells) {+ const d = c.deltas as Record<string, { medianDelta: number | null; bLower: number; bHigher: number } | null>;+ const cellText = (k: string, f: (v: number | null) => string) => d[k] ? `${f(d[k]!.medianDelta)} (${d[k]!.bLower}/${d[k]!.bHigher})` : '-';+ md.push(`| ${c.cell} | ${c.pairs} | ${cellText('p50', v => ms(v, 3))} | ${cellText('p95', v => ms(v, 3))} | ${cellText('withinOne', v => typeof v === 'number' ? `${(100 * v).toFixed(2)} pt` : '-')} | ${cellText('cpuRenderP50', v => ms(v, 3))} | ${cellText('gpuBusy', v => ms(v, 1))} | ${typeof c.ratios.p95 === 'number' ? c.ratios.p95.toFixed(3) : '-'} |`);+ }+ await writeFile(resolve(dir, 'summary.md'), md.join('\n') + '\n');+ return out;+}++// ---------------------------------------------------------------- quiet, transient, verify++async function quietCommand() {+ const rule = option('--rule', process.platform === 'linux' ? 'hub' : 'pc') === 'hub' ? HUB_RULE : PC_RULE;+ const w = await quietWindow(rule), outFile = option('--out');+ const record = { schema: 'kiln.timing-ab-quiet/1', ...w };+ if (outFile) await writeJson(resolve(outFile), record);+ const s = w.hostState;+ console.log(JSON.stringify({ quiet: w.quiet, reasons: w.reasons, cpuMean: round(w.cpuMean, 2), cpuMax: round(w.cpuMax, 2), gpuMax: w.gpuMax, loadavg: s.loadavg, gpu: s.gpu, cpuTempC: s.cpuTempC, who: s.who, sessions: s.loginctlSessions?.length ?? null,+ top: s.top?.slice(0, 5), busiest: w.busiestProcesses.slice(0, 5), screenLocker: s.screenLockerActive, out: outFile ?? null }));+ if (!w.quiet) process.exitCode = 3;+}+/** WebGPU transient (memoryless) attachments: GPUTextureUsage.TRANSIENT_ATTACHMENT and whether a 4x clear/discard pass validates. Read-only. */+async function transientProbe(page: Page, url: string) {+ // navigator.gpu exists only in a secure context: a loopback page (127.0.0.1), not about:blank.+ await page.goto(url, { waitUntil: 'load' });+ return page.evaluate(async () => {+ const g = (globalThis as any).GPUTextureUsage, out: Record<string, unknown> = { usageFlags: g ? Object.fromEntries(Object.entries(g)) : null, transientFlag: g?.TRANSIENT_ATTACHMENT ?? null }; // eslint-disable-line @typescript-eslint/no-explicit-any+ const adapter = await (navigator as any).gpu?.requestAdapter?.(); // eslint-disable-line @typescript-eslint/no-explicit-any+ if (!adapter) return { ...out, adapter: null };+ out.adapter = { vendor: adapter.info?.vendor, architecture: adapter.info?.architecture, device: adapter.info?.device, description: adapter.info?.description };+ out.features = [...adapter.features].sort(); out.wgslFeatures = [...((navigator as any).gpu.wgslLanguageFeatures ?? [])].sort(); // eslint-disable-line @typescript-eslint/no-explicit-any+ const device = await adapter.requestDevice();+ const attempt = async (usage: number, label: string) => {+ device.pushErrorScope('validation');+ let created = false;+ try {+ const tex = device.createTexture({ label, size: [64, 64], format: 'rgba8unorm', sampleCount: 4, usage }), resolveTex = device.createTexture({ size: [64, 64], format: 'rgba8unorm', usage: g.RENDER_ATTACHMENT });+ const enc = device.createCommandEncoder(), pass = enc.beginRenderPass({ colorAttachments: [{ view: tex.createView(), resolveTarget: resolveTex.createView(), loadOp: 'clear', storeOp: 'discard', clearValue: [0, 0, 0, 1] }] });+ pass.end(); device.queue.submit([enc.finish()]); created = true; tex.destroy(); resolveTex.destroy();+ } catch (error) { return { label, created, thrown: String(error) }; }+ const e = await device.popErrorScope(); return { label, created, validationError: e ? e.message : null };+ };+ out.renderAttachment = await attempt(g.RENDER_ATTACHMENT, 'msaa-render-attachment');+ out.transient = typeof g.TRANSIENT_ATTACHMENT === 'number' ? await attempt(g.RENDER_ATTACHMENT | g.TRANSIENT_ATTACHMENT, 'msaa-transient') : { skipped: 'GPUTextureUsage.TRANSIENT_ATTACHMENT is undefined in this browser' };+ device.destroy(); out.userAgent = navigator.userAgent; return out;+ });+}+async function transientCommand() {+ const device = option('--device', 'tablet'), outFile = option('--out');+ // Any static page of the kit on an owned loopback port (the A build's notices file) gives the secure context.+ const anchor = resolve(kitRoot(), option('--a', 'builds/draw-base')!, 'farm'), served = await serve('A', anchor, [4400, 4489], new Set()), url = `${served.base}/THIRD-PARTY-NOTICES.txt`;+ let result: unknown;+ try {+ if (device === 'tablet') {+ const adb = adbFor(), before = await listMappings(adb); if (before.forward.length || before.reverse.length) throw new Error(`Existing mappings ${JSON.stringify(before)}`);+ let session: TabletSession | null = null, release: unknown = null;+ try { session = await tabletConnect(adb, [served.port]); const page = await session.browser.newPage(); try { result = { chrome: await session.browser.version(), ...(await transientProbe(page, url)) }; } finally { await page.close().catch(() => undefined); } }+ finally { release = await tabletRelease(adb, session); }+ result = { ...(result as object), mappingsAfter: release };+ } else {+ const profile = await mkdtemp(resolve(kitRoot(), 'tmp-profile-')), { browser } = await launchLocal(profile, flag('--headless'), 800, 600);+ try { const page = await browser.newPage(); result = { chrome: await browser.version(), ...(await transientProbe(page, url)) }; } finally { await browser.close(); await rm(profile, { recursive: true, force: true }); }+ }+ } finally { await served.close(); }+ const record = { schema: 'kiln.timing-ab-transient/1', at: now(), device, result };+ if (outFile) await writeJson(resolve(outFile), record);+ console.log(JSON.stringify(record, null, 1));+}+async function verifyCommand() {+ const kit = kitRoot(), manifest = JSON.parse(await readFile(resolve(kit, 'MANIFEST.json'), 'utf8')) as { files: { path: string; bytes: number; sha256: string }[] };+ const problems: string[] = [];+ for (const f of manifest.files) { const p = resolve(kit, f.path); if (!existsSync(p)) { problems.push(`missing ${f.path}`); continue; } const data = await readFile(p); if (data.length !== f.bytes || createHash('sha256').update(data).digest('hex') !== f.sha256) problems.push(`changed ${f.path}`); }+ console.log(JSON.stringify({ files: manifest.files.length, problems, node: process.version })); if (problems.length) process.exitCode = 1;+}++const isMain = typeof (import.meta as { main?: boolean }).main === 'boolean' ? (import.meta as { main?: boolean }).main : !!process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url);+if (isMain) {+ if (command === 'ab') await abBlock();+ else if (command === 'quiet') await quietCommand();+ else if (command === 'summary') { const r = await summarizeBlock(resolve(option('--dir')!)); console.log(JSON.stringify({ cells: r.cells.length, runs: r.runs })); }+ else if (command === 'transient') await transientCommand();+ else if (command === 'verify') await verifyCommand();+ else console.log('Usage: timing-ab <ab|quiet|summary|transient|verify> [--a builds/<A>] [--b builds/<B>] [--cells scene:tier:name,…] [--pairs 3] [--seconds 60] [--warmup 5] [--prime 3] [--device local|tablet] [--block name] [--out dir] [--chrome path] [--chrome-arg flag]… [--headless] [--size 1920x1080] [--query k=v&…] [--query-a …] [--query-b …] [--wait-quiet min] [--cool-wait min] [--no-preflight (not evidence)]');+}diff --git a/skills/kiln-compose-scene/SKILL.md b/skills/kiln-compose-scene/SKILL.mdindex b01e27c0..b2dfd659 100644--- a/skills/kiln-compose-scene/SKILL.md+++ b/skills/kiln-compose-scene/SKILL.md@@ -19,6 +19,9 @@ application have different requirements; exporting a monolithic GLB is optional.For terrain, animated environments, traversal or measured optimization, read[runtime scene guidance](references/runtime-scenes.md). Keep those systems inthe consuming scene rather than adding them to every asset-authoring task.+To reduce draw calls, count them per render pass first. Then merge by material+within each animation and interaction anchor, and give shadow and reflection+passes their own stand-ins. Do not flatten an asset into one mesh.Inspect each GLB with `inspectGlbIntegration(bytes)` and confirm it returned a usable manifest. Use units, axes, bounds, and ground information to place the object deliberately. Give instances stable names and explicit transforms.diff --git a/skills/kiln-compose-scene/references/runtime-scenes.md b/skills/kiln-compose-scene/references/runtime-scenes.mdindex 6bd1262a..371be4ef 100644--- a/skills/kiln-compose-scene/references/runtime-scenes.md+++ b/skills/kiln-compose-scene/references/runtime-scenes.md@@ -65,6 +65,93 @@ a shared shadow map also freezes their shadows. Compare filtering, shadow-mapresolution and caster geometry explicitly rather than assuming a smaller mainrender buffer removes shadow cost.+### Draw calls and extra passes++Count before changing anything. Record draws, bound pipelines and triangles per+render pass (main, each shadow map, reflections, output) for every quality tier+and named view or workload, not only the landing camera. Attribute draws to+scene systems. Count-only what-ifs (hide a system, freeze a pass, drop small+casters) give upper bounds for each lever before you build it. In the three.js+proving scenes, one farm view drew 583: 312 main, 270 shadow and 1 output. A+bridge drew 148 of the 180 draws at the lowest tier. Rank levers per scene from+its own numbers; the same lever can matter in one scene and be absent in another.++Merge rigid parts by material inside anchors, and keep every anchor as a real+node with its name, transform and children. Anchors are animation targets,+pivots the application moves, nodes it looks up by name, nodes carrying+semantic data, and visibility or LOD switches. Leave transparent, multi-material,+skinned and morphed parts separate. A per-material merge kept doors, wheels,+limbs, colliders and the frame graph working while a farmhouse went from 16 to+11 draws and a bridge from 148 to 20. Split very long structures into a few+spatial groups so culling still works. Two side effects need checks:+- Keeping the source vertex layout can avoid extra pipelines. It saved 2-3 per+ view in one scene and cost 5-10 in another, so measure it.+- Merging changes the draw order of coplanar and nearly coplanar faces. A curb+ that now won the depth tie against a walkway stippled the kerbs; ordering the+ curbs first inside the merged mesh fixed it at no extra draw. Parts in+ different buckets keep one fixed order for every view, so split a bucket+ where the per-part draw order matters: splitting a bridge's tower panels at+ the ribs' height, one draw per tower, brought a 193 px tie under a 100 px+ budget.++Treat each extra pass as its own budget:+- **Shadow pass.** Use material-free depth stand-ins per anchor and shadow side.+ Cache a static sun map, and keep a separate live map for casters observed to+ move, with a settle period. Render the map once per frame when a second camera,+ such as a planar reflector, would render it again. Stop casters smaller than+ about two shadow texels from casting. Together these took one farm's shadow+ pass from 270 draws a frame to 0 when settled, and to 31-54 with ambient+ animal life. A bridge scene went from two 37-draw shadow passes to one 2-draw+ pass. On a GPU-bound mobile tier, the combined changes raised frames within one+ display refresh from 39% to 61-82%. On a desktop locked to 120 Hz, frame time+ did not move; CPU render time fell from 5.5 ms to 1.6 ms.+- **Reflection pass.** Draw a cheaper representation, such as a far LOD, on a+ layer that only the reflection camera sees. Keep which moving objects appear+ in the reflection as a look decision of its own.++A cached shadow only pays where its frustum stays still. A shadow box that+follows a driven car re-renders every frame, so measure moving workloads before+enabling it.++In three r186's WebGPU renderer every `InstancedMesh` binds its own pipeline,+because its uuid is part of the material cache key. `EXT_mesh_gpu_instancing`+therefore saves draws but adds a pipeline per instanced group: instancing one+campus's structures raised its main-pass pipelines, summed over its views, from+77 to 346. What worked was one shared material reading per-part data: colour+and roughness as vertex data, instance matrices as attributes of plain meshes.+That took a campus planting from 21 pipelines to 10 at the overview and from+40-49 to 11-13 near the ground, with pixel parity.++When a frame's main pass is never split by a mid-pass copy (for example a+depth-texture read for water), its multisampled attachments need not be stored+after the resolve. Discarding them changed nothing measurable on a desktop GPU.+On a mobile GPU, GPU busy at the same frame rate fell by 3-8 points, and frames+within one refresh at a GPU-bound tier rose from 40% to 49%. Fail loudly when+something would reload the attachments.++Read mobile GPU work as busy × clock, not busy alone. The governor changes the+clock with load, so the same busy share at a higher clock is more work. Where a+tablet's busy column read mixed, busy × clock fell by 15% and 24%.++Over long view distances, a 24-bit depth buffer with a 0.5 m near plane steps+by about 0.12 m at 1 km, 3 m at 5 km and 48 m at 20 km, growing with distance+squared, so distant near-coplanar surfaces flicker as the camera moves.+Reversed depth is the remedy. In three r186 it needs three adaptations: draw+the sky first without a depth test, rebuild a planar reflector's oblique+projection, and flip the sign of polygon offsets. On WebGL2 it also needs+`EXT_clip_control`, or three falls back to a standard buffer.++Report cached features in both their settled and their running state. With the+clock running, the farm view that drew 583 drew 314-337, with about ten static+re-renders a minute. Check look parity three ways:+- the same build with each lever switched off;+- the build before the change against the build after;+- a repeat capture of the same build, for the noise floor.++Tile-mean metrics can miss thin-line regressions, so also count the pixels that+differ strongly. Show every intended shadow change, such as small parts that stop+casting, as image pairs for review.+Profile transform updates as well as draw submission. Cache matrices only forplacements the application knows will remain fixed. Keep animated and controlledhierarchies live, and restore or rebuild the cache before placement or variant