@blackbelt-technology/pi-dashboard-deck3d 0.0.0-stage → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/.pi/skills/deck3d/SKILL.md +227 -0
  2. package/.pi/skills/deck3d/examples/deck.json +388 -0
  3. package/.pi/skills/deck3d/examples/fixture.md +18 -0
  4. package/.pi/skills/deck3d/examples/snapshot-after.png +0 -0
  5. package/.pi/skills/deck3d/examples/snapshot-before.png +0 -0
  6. package/.pi/skills/deck3d/reference/effects.agent.md +78 -0
  7. package/.pi/skills/deck3d/reference/effects.md +1217 -0
  8. package/.pi/skills/deck3d/reference/ir-fields.agent.md +30 -0
  9. package/.pi/skills/deck3d/reference/ir-fields.md +246 -0
  10. package/README.md +177 -2
  11. package/assets/LICENSE-Poppins.txt +99 -0
  12. package/assets/Poppins-Bold.ttf +0 -0
  13. package/assets/props/LICENSES.txt +4 -0
  14. package/assets/props/brain.glb +0 -0
  15. package/assets/props/cloud.glb +0 -0
  16. package/assets/props/cube.glb +0 -0
  17. package/assets/props/database.glb +0 -0
  18. package/assets/props/laptop.glb +0 -0
  19. package/assets/props/manifest.json +119 -0
  20. package/assets/props/robot.glb +0 -0
  21. package/assets/props/server.glb +0 -0
  22. package/assets/props/shield.glb +0 -0
  23. package/bin/deck3d +49 -0
  24. package/dist/cli.js +10228 -0
  25. package/dist/harvest/harness.js +185718 -0
  26. package/dist/runtime.js +64597 -0
  27. package/fixtures/business-2031/build-deck.mjs +60 -0
  28. package/fixtures/business-2031/build-overrides.mjs +154 -0
  29. package/fixtures/business-2031/deck.json +4220 -0
  30. package/fixtures/business-2031/deck.md +470 -0
  31. package/fixtures/business-2031/fx/closing-mark.js +43 -0
  32. package/fixtures/business-2031/fx/closing-mark.meta.json +26 -0
  33. package/fixtures/business-2031/overrides.json +903 -0
  34. package/fixtures/harvest.md +23 -0
  35. package/fixtures/strategy-lab.json +891 -0
  36. package/fixtures/strategy-lab.md +85 -0
  37. package/package.json +80 -4
  38. package/scripts/build-cli.mjs +29 -0
  39. package/scripts/build-harvest.ts +8 -0
  40. package/scripts/build-runtime.mjs +22 -0
  41. package/scripts/gen-effects.ts +14 -0
  42. package/scripts/gen-ir-fields.ts +34 -0
  43. package/src/check/index.ts +315 -0
  44. package/src/check/rules.ts +393 -0
  45. package/src/cli-io.ts +23 -0
  46. package/src/cli.ts +823 -0
  47. package/src/fx/accent-cycle.meta.json +26 -0
  48. package/src/fx/accent-cycle.ts +8 -0
  49. package/src/fx/agent-depth.meta.json +42 -0
  50. package/src/fx/agent-depth.ts +62 -0
  51. package/src/fx/ascii.meta.json +35 -0
  52. package/src/fx/ascii.ts +4 -0
  53. package/src/fx/aurora.meta.json +26 -0
  54. package/src/fx/aurora.ts +18 -0
  55. package/src/fx/billboards.meta.json +34 -0
  56. package/src/fx/billboards.ts +67 -0
  57. package/src/fx/bloom.meta.json +26 -0
  58. package/src/fx/bloom.ts +4 -0
  59. package/src/fx/camera-drift.meta.json +26 -0
  60. package/src/fx/camera-drift.ts +8 -0
  61. package/src/fx/capital-flows.meta.json +30 -0
  62. package/src/fx/capital-flows.ts +64 -0
  63. package/src/fx/catalogue.ts +89 -0
  64. package/src/fx/chromatic-aberration.meta.json +32 -0
  65. package/src/fx/chromatic-aberration.ts +4 -0
  66. package/src/fx/city-grid.meta.json +37 -0
  67. package/src/fx/city-grid.ts +51 -0
  68. package/src/fx/clipped-solids.meta.json +49 -0
  69. package/src/fx/clipped-solids.ts +171 -0
  70. package/src/fx/cohort-grid.meta.json +48 -0
  71. package/src/fx/cohort-grid.ts +63 -0
  72. package/src/fx/compose.ts +114 -0
  73. package/src/fx/constellation.meta.json +51 -0
  74. package/src/fx/constellation.ts +103 -0
  75. package/src/fx/curve-flow.meta.json +40 -0
  76. package/src/fx/curve-flow.ts +63 -0
  77. package/src/fx/dashed-flow.meta.json +27 -0
  78. package/src/fx/dashed-flow.ts +8 -0
  79. package/src/fx/data-columns.meta.json +30 -0
  80. package/src/fx/data-columns.ts +18 -0
  81. package/src/fx/defaults.ts +92 -0
  82. package/src/fx/depth-of-field.meta.json +40 -0
  83. package/src/fx/depth-of-field.ts +4 -0
  84. package/src/fx/dolly.meta.json +26 -0
  85. package/src/fx/dolly.ts +4 -0
  86. package/src/fx/dot-screen.meta.json +35 -0
  87. package/src/fx/dot-screen.ts +4 -0
  88. package/src/fx/dynamic-instances.meta.json +40 -0
  89. package/src/fx/dynamic-instances.ts +57 -0
  90. package/src/fx/emissive.meta.json +26 -0
  91. package/src/fx/emissive.ts +8 -0
  92. package/src/fx/extruded-shapes.meta.json +62 -0
  93. package/src/fx/extruded-shapes.ts +133 -0
  94. package/src/fx/fab-wafer.meta.json +42 -0
  95. package/src/fx/fab-wafer.ts +72 -0
  96. package/src/fx/fade.meta.json +26 -0
  97. package/src/fx/fade.ts +4 -0
  98. package/src/fx/film.meta.json +26 -0
  99. package/src/fx/film.ts +4 -0
  100. package/src/fx/float.meta.json +26 -0
  101. package/src/fx/float.ts +8 -0
  102. package/src/fx/flythrough.meta.json +26 -0
  103. package/src/fx/flythrough.ts +4 -0
  104. package/src/fx/fog.meta.json +26 -0
  105. package/src/fx/fog.ts +8 -0
  106. package/src/fx/geo-fragments.meta.json +48 -0
  107. package/src/fx/geo-fragments.ts +59 -0
  108. package/src/fx/glass.meta.json +26 -0
  109. package/src/fx/glass.ts +8 -0
  110. package/src/fx/globe-arcs.meta.json +36 -0
  111. package/src/fx/globe-arcs.ts +67 -0
  112. package/src/fx/glow-tube.meta.json +26 -0
  113. package/src/fx/glow-tube.ts +8 -0
  114. package/src/fx/glyph-rain.meta.json +30 -0
  115. package/src/fx/glyph-rain.ts +18 -0
  116. package/src/fx/god-rays.meta.json +40 -0
  117. package/src/fx/god-rays.ts +4 -0
  118. package/src/fx/grid-horizon.meta.json +30 -0
  119. package/src/fx/grid-horizon.ts +18 -0
  120. package/src/fx/hex-grid.meta.json +29 -0
  121. package/src/fx/hex-grid.ts +18 -0
  122. package/src/fx/holo-fresnel.meta.json +26 -0
  123. package/src/fx/holo-fresnel.ts +8 -0
  124. package/src/fx/horizon-gates.meta.json +36 -0
  125. package/src/fx/horizon-gates.ts +60 -0
  126. package/src/fx/index.ts +258 -0
  127. package/src/fx/iridescent.meta.json +26 -0
  128. package/src/fx/iridescent.ts +8 -0
  129. package/src/fx/iris.meta.json +26 -0
  130. package/src/fx/iris.ts +4 -0
  131. package/src/fx/lightformers.meta.json +26 -0
  132. package/src/fx/lightformers.ts +8 -0
  133. package/src/fx/local.ts +200 -0
  134. package/src/fx/market-tape.meta.json +53 -0
  135. package/src/fx/market-tape.ts +97 -0
  136. package/src/fx/matcap.meta.json +26 -0
  137. package/src/fx/matcap.ts +8 -0
  138. package/src/fx/meta.schema.json +49 -0
  139. package/src/fx/metal.meta.json +26 -0
  140. package/src/fx/metal.ts +8 -0
  141. package/src/fx/mirror-floor.meta.json +26 -0
  142. package/src/fx/mirror-floor.ts +8 -0
  143. package/src/fx/neural-mesh.meta.json +54 -0
  144. package/src/fx/neural-mesh.ts +110 -0
  145. package/src/fx/orbit-agents.meta.json +36 -0
  146. package/src/fx/orbit-agents.ts +63 -0
  147. package/src/fx/orbit.meta.json +27 -0
  148. package/src/fx/orbit.ts +8 -0
  149. package/src/fx/outline.meta.json +43 -0
  150. package/src/fx/outline.ts +4 -0
  151. package/src/fx/paper-stack.meta.json +36 -0
  152. package/src/fx/paper-stack.ts +61 -0
  153. package/src/fx/particle-stream.meta.json +27 -0
  154. package/src/fx/particle-stream.ts +8 -0
  155. package/src/fx/particles.meta.json +26 -0
  156. package/src/fx/particles.ts +8 -0
  157. package/src/fx/pixelate.meta.json +28 -0
  158. package/src/fx/pixelate.ts +4 -0
  159. package/src/fx/points-on-geometry.meta.json +61 -0
  160. package/src/fx/points-on-geometry.ts +71 -0
  161. package/src/fx/proof-gate.meta.json +30 -0
  162. package/src/fx/proof-gate.ts +67 -0
  163. package/src/fx/rings.meta.json +27 -0
  164. package/src/fx/rings.ts +8 -0
  165. package/src/fx/room-ibl.meta.json +26 -0
  166. package/src/fx/room-ibl.ts +8 -0
  167. package/src/fx/sao.meta.json +32 -0
  168. package/src/fx/sao.ts +4 -0
  169. package/src/fx/scaffold.ts +172 -0
  170. package/src/fx/scatter.meta.json +49 -0
  171. package/src/fx/scatter.ts +74 -0
  172. package/src/fx/selective-bloom.meta.json +36 -0
  173. package/src/fx/selective-bloom.ts +4 -0
  174. package/src/fx/server-racks.meta.json +36 -0
  175. package/src/fx/server-racks.ts +54 -0
  176. package/src/fx/shader-particles.meta.json +46 -0
  177. package/src/fx/shader-particles.ts +75 -0
  178. package/src/fx/signal-pulse.meta.json +27 -0
  179. package/src/fx/signal-pulse.ts +8 -0
  180. package/src/fx/smaa.meta.json +19 -0
  181. package/src/fx/smaa.ts +4 -0
  182. package/src/fx/sobel.meta.json +24 -0
  183. package/src/fx/sobel.ts +4 -0
  184. package/src/fx/soft-shadows.meta.json +26 -0
  185. package/src/fx/soft-shadows.ts +8 -0
  186. package/src/fx/sprites.meta.json +40 -0
  187. package/src/fx/sprites.ts +57 -0
  188. package/src/fx/stagger-reveal.meta.json +26 -0
  189. package/src/fx/stagger-reveal.ts +8 -0
  190. package/src/fx/starfield.meta.json +32 -0
  191. package/src/fx/starfield.ts +18 -0
  192. package/src/fx/swarm.meta.json +27 -0
  193. package/src/fx/swarm.ts +8 -0
  194. package/src/fx/tessellate.meta.json +39 -0
  195. package/src/fx/tessellate.ts +79 -0
  196. package/src/fx/tokens.meta.json +27 -0
  197. package/src/fx/tokens.ts +8 -0
  198. package/src/fx/trail.meta.json +27 -0
  199. package/src/fx/trail.ts +8 -0
  200. package/src/fx/trust-ledger.meta.json +30 -0
  201. package/src/fx/trust-ledger.ts +47 -0
  202. package/src/fx/types.ts +83 -0
  203. package/src/fx/util.ts +108 -0
  204. package/src/fx/vault-glyphs.meta.json +37 -0
  205. package/src/fx/vault-glyphs.ts +55 -0
  206. package/src/fx/video-screen.meta.json +57 -0
  207. package/src/fx/video-screen.ts +99 -0
  208. package/src/fx/vignette.meta.json +32 -0
  209. package/src/fx/vignette.ts +4 -0
  210. package/src/fx/volume-cloud.meta.json +58 -0
  211. package/src/fx/volume-cloud.ts +87 -0
  212. package/src/fx/volume-perlin.meta.json +46 -0
  213. package/src/fx/volume-perlin.ts +82 -0
  214. package/src/fx/volumetric-spot.meta.json +26 -0
  215. package/src/fx/volumetric-spot.ts +8 -0
  216. package/src/fx/wireframe-overlay.meta.json +27 -0
  217. package/src/fx/wireframe-overlay.ts +8 -0
  218. package/src/ir/defaults.ts +62 -0
  219. package/src/ir/field-reference.ts +96 -0
  220. package/src/ir/hash.ts +34 -0
  221. package/src/ir/ids.ts +65 -0
  222. package/src/ir/merge.ts +155 -0
  223. package/src/ir/schema.json +1211 -0
  224. package/src/ir/types.ts +333 -0
  225. package/src/ir/validate.ts +196 -0
  226. package/src/parse/derive.ts +205 -0
  227. package/src/parse/harvest/bundle.ts +56 -0
  228. package/src/parse/harvest/harness.html +22 -0
  229. package/src/parse/harvest/harness.ts +191 -0
  230. package/src/parse/harvest/index.ts +169 -0
  231. package/src/parse/harvest/shapes.ts +75 -0
  232. package/src/parse/markdown.ts +215 -0
  233. package/src/props/embed.ts +92 -0
  234. package/src/props/fetch.ts +97 -0
  235. package/src/props/generate.ts +152 -0
  236. package/src/props/key.ts +13 -0
  237. package/src/props/search.ts +180 -0
  238. package/src/render/embed-video.ts +80 -0
  239. package/src/render/font.ts +86 -0
  240. package/src/render/index.ts +149 -0
  241. package/src/render/template.html +87 -0
  242. package/src/runtime/backgrounds.ts +146 -0
  243. package/src/runtime/builders.ts +808 -0
  244. package/src/runtime/camera.ts +73 -0
  245. package/src/runtime/hud.ts +887 -0
  246. package/src/runtime/index.ts +1168 -0
  247. package/src/runtime/local-fx.ts +151 -0
  248. package/src/runtime/materials.ts +136 -0
  249. package/src/runtime/measure.ts +73 -0
  250. package/src/runtime/node-geometry.ts +26 -0
  251. package/src/runtime/palette.ts +111 -0
  252. package/src/runtime/post.ts +649 -0
  253. package/src/runtime/props.ts +292 -0
  254. package/src/runtime/quality.ts +20 -0
  255. package/src/runtime/rng.ts +8 -0
  256. package/src/runtime/scene.ts +644 -0
  257. package/src/runtime/text.ts +174 -0
  258. package/src/runtime/types.ts +118 -0
  259. package/src/serve/index.ts +376 -0
  260. package/src/util/paths.ts +35 -0
@@ -0,0 +1,1168 @@
1
+ /**
2
+ * Runtime entry — bundled by esbuild into `dist/runtime.js` and inlined into
3
+ * `deck.html`. Reads `window.__DECK` (merged IR) + `window.__DECK_FONT`
4
+ * (base64 subset TTF), builds one 3D group per slide, and exposes the
5
+ * `window.__deck3d` measurement/debug surface (design D8).
6
+ */
7
+ import type { Font } from "opentype.js";
8
+ import * as THREE from "three";
9
+ import { composeEffects, QUALITY_BUDGET } from "../fx/compose.js";
10
+ import { REGISTRY } from "../fx/index.js";
11
+ import type { FxContext, FxParams } from "../fx/types.js";
12
+ import type { Layout } from "../ir/types.js";
13
+ import { type Animator, backgroundFor } from "./backgrounds.js";
14
+ import { buildDiagram, type DiagramBuild } from "./builders.js";
15
+ import { anchorFor, cullRadius } from "./camera.js";
16
+ import { createHud, type SlidePatch } from "./hud.js";
17
+ import { createLocalEffect, type LocalFxError, type LocalHandle, localCards, localFxRegistry } from "./local-fx.js";
18
+ import { diagramMaterial, titleEdgeMaterial, titleMaterial } from "./materials.js";
19
+ import { projectRect } from "./measure.js";
20
+ import { mixPalette, type PaletteColors, resolvePalette } from "./palette.js";
21
+ import type { PartName } from "./post.js";
22
+ import { applyProps, createPropMaterials, loadPropModels, type PropLayer, type PropMaterials } from "./props.js";
23
+ import { type QualityProfile, qualityProfile } from "./quality.js";
24
+ import { makeRng } from "./rng.js";
25
+ import { createSceneRig, markBackdrop, sortAboveVeil } from "./scene.js";
26
+ import { buildTitle, bulletTexture, loadFont } from "./text.js";
27
+ import "./types.js";
28
+ import type { Deck3dApi, Measurement, RuntimeDeck, SlideConfig } from "./types.js";
29
+
30
+ type DeckSlide = RuntimeDeck["slides"][number];
31
+
32
+ interface LabelRef {
33
+ kind: "title" | "label";
34
+ id: string;
35
+ text: string;
36
+ object: THREE.Object3D;
37
+ height: number;
38
+ color?: string;
39
+ }
40
+
41
+ interface SlideBuild {
42
+ group: THREE.Group;
43
+ anchor: ReturnType<typeof anchorFor>;
44
+ diagram: DiagramBuild | null;
45
+ background: Animator | null;
46
+ props: PropLayer | null;
47
+ labels: LabelRef[];
48
+ nodes: Array<{ id: string; object: THREE.Object3D }>;
49
+ localFx: LocalHandle[];
50
+ cfg: SlideConfig;
51
+ palette: PaletteColors;
52
+ skipped: string[];
53
+ budget: { sum: number; limit: number; warning?: string };
54
+ }
55
+
56
+ function effective(defaults: SlideConfig, slide: DeckSlide): SlideConfig {
57
+ return { ...defaults, ...slide } as SlideConfig;
58
+ }
59
+
60
+ /**
61
+ * Where the composition puts each element. `split` reproduces the v1 numbers
62
+ * exactly, so an untouched deck renders byte-identically. A vertical `stacked`
63
+ * preset was tried and dropped: floor y=-2.6 to frame top ~4.0 is 6.6 units and
64
+ * title+disc+card need 7.7, so it needs a lower-third card variant first.
65
+ */
66
+ interface LayoutSpec {
67
+ /** Title left edge; `centre` centres the text box instead. */
68
+ titleX: number | "centre";
69
+ titleY: number;
70
+ cardX: number;
71
+ cardY: number;
72
+ barX: number;
73
+ barY: number;
74
+ diagram: [number, number, number];
75
+ }
76
+
77
+ const LAYOUTS: Record<Layout, LayoutSpec> = {
78
+ split: { titleX: -5.2, titleY: 2.2, cardX: -2.4, cardY: -0.35, barX: -4.4, barY: 1.55, diagram: [2.9, 0.1, 0.9] },
79
+ // Mirrored: the title is right-ALIGNED, so its left edge depends on its width.
80
+ "split-reverse": { titleX: 5.2, titleY: 2.2, cardX: 2.4, cardY: -0.35, barX: 4.4, barY: 1.55, diagram: [-2.9, 0.1, 0.9] },
81
+ };
82
+
83
+ function layoutFor(cfg: SlideConfig): LayoutSpec {
84
+ return LAYOUTS[(cfg.layout as Layout) ?? "split"] ?? LAYOUTS.split;
85
+ }
86
+
87
+ function addTitle(g: THREE.Group, slide: DeckSlide, isTitle: boolean, font: Font, P: PaletteColors, cfg: SlideConfig, labels: LabelRef[]): void {
88
+ // `contrast` paints ExtrudeGeometry's SIDE group (walls + bevel) separately,
89
+ // which is what draws a contour around every character.
90
+ const face = titleMaterial(P, cfg);
91
+ const mat = cfg.titleEdge === "contrast" ? [face, titleEdgeMaterial(P)] : face;
92
+ const title = buildTitle(font, slide.title, isTitle ? 0.62 : 0.5, cfg.extrudeDepth ?? 0.18, mat);
93
+ const bb = new THREE.Box3().setFromObject(title.group);
94
+ const L = layoutFor(cfg);
95
+ const width = bb.max.x - bb.min.x;
96
+ // `split-reverse` pins the title's RIGHT edge; every other preset its left.
97
+ const x = L.titleX === "centre" ? -width / 2 : L.titleX > 0 ? L.titleX - width : L.titleX;
98
+ title.group.position.set(
99
+ isTitle ? -width / 2 : x,
100
+ isTitle ? 1.5 + (title.lines - 1) * 0.85 : L.titleY + (title.lines - 1) * 0.68,
101
+ 0.2,
102
+ );
103
+ g.add(title.group);
104
+ title.group.userData.ownerId = `${slide.id}/title`;
105
+ title.group.userData.part = "title";
106
+ labels.push({ kind: "title", id: `${slide.id}/title`, text: slide.title, object: title.group, height: (isTitle ? 0.62 : 0.5) * 1.4 });
107
+ }
108
+
109
+ function slabBack(P: PaletteColors, cfg: SlideConfig, slabH: number): THREE.Mesh {
110
+ const back = new THREE.Mesh(
111
+ new THREE.BoxGeometry(5.6, slabH, 0.08),
112
+ new THREE.MeshPhysicalMaterial({
113
+ color: P.card,
114
+ metalness: 0,
115
+ roughness: 0.35,
116
+ transmission: cfg.material === "glass" ? (cfg.mode === "dark" ? 0.55 : 0.25) : 0,
117
+ thickness: 0.4,
118
+ envMapIntensity: cfg.envReflections !== false ? 0.8 : 0,
119
+ transparent: true,
120
+ opacity: cfg.material === "glass" ? 0.85 : 1,
121
+ }),
122
+ );
123
+ back.receiveShadow = true;
124
+ back.castShadow = true;
125
+ return back;
126
+ }
127
+
128
+ function addBody(g: THREE.Group, slide: DeckSlide, isTitle: boolean, P: PaletteColors, cfg: SlideConfig): void {
129
+ if (!slide.bullets.length && !slide.subtitle) return;
130
+ const slabH = isTitle && !slide.bullets.length ? 1.0 : 2.9;
131
+ const slab = new THREE.Group();
132
+ slab.add(slabBack(P, cfg, slabH));
133
+ const txt = new THREE.Mesh(
134
+ new THREE.PlaneGeometry(5.2, 2.6),
135
+ new THREE.MeshBasicMaterial({ map: bulletTexture(slide, P), transparent: true, toneMapped: false, depthWrite: false }),
136
+ );
137
+ txt.position.set(0, -(2.9 - slabH) / 2, 0.06);
138
+ txt.renderOrder = 2;
139
+ slab.add(txt);
140
+ const L = layoutFor(cfg);
141
+ const nudge = cfg.cardOffset ?? {};
142
+ slab.position.set(
143
+ (isTitle ? 0 : L.cardX) + (nudge.x ?? 0),
144
+ (isTitle ? (slabH < 2 ? -0.3 : -1.1) : L.cardY) + (nudge.y ?? 0),
145
+ 0,
146
+ );
147
+ g.add(slab);
148
+ const bar = new THREE.Mesh(new THREE.BoxGeometry(isTitle ? 3 : 1.6, 0.06, 0.06), diagramMaterial(P, "accent", cfg));
149
+ bar.position.set(isTitle ? 0 : L.barX, isTitle ? 0.55 : L.barY, 0.25);
150
+ g.add(bar);
151
+ }
152
+
153
+ function addDiagram(g: THREE.Group, slide: DeckSlide, font: Font, P: PaletteColors, cfg: SlideConfig, labels: LabelRef[]): DiagramBuild | null {
154
+ if (slide.diagram.kind === "none") return null;
155
+ const holder = new THREE.Group();
156
+ holder.userData.part = "diagram";
157
+ holder.position.set(...layoutFor(cfg).diagram);
158
+ const diagram = buildDiagram(slide, P, cfg, font);
159
+ holder.add(diagram.g);
160
+ const disc = new THREE.Mesh(
161
+ new THREE.CylinderGeometry(1.7, 1.75, 0.08, 64),
162
+ // Polished, not matte: low roughness + full metalness is what makes the
163
+ // key and rim lights read as highlights sliding across the plate.
164
+ new THREE.MeshStandardMaterial({
165
+ color: P.card,
166
+ metalness: 0.95,
167
+ roughness: 0.12,
168
+ envMapIntensity: cfg.envReflections !== false ? 1.6 : 0,
169
+ }),
170
+ );
171
+ disc.position.y = -1.7;
172
+ disc.receiveShadow = true;
173
+ holder.add(disc);
174
+ g.add(holder);
175
+ for (const l of diagram.labels ?? []) labels.push({ kind: "label", id: l.id, text: l.text, object: l.object, height: l.height, color: P.text });
176
+ return diagram;
177
+ }
178
+
179
+ /** Per-slide seed: same slide id ⇒ same stream, so effects stay deterministic. */
180
+ export function fxSeedFor(slideId: string): number {
181
+ let h = 2166136261;
182
+ for (let i = 0; i < slideId.length; i++) {
183
+ h ^= slideId.charCodeAt(i);
184
+ h = Math.imul(h, 16777619);
185
+ }
186
+ return (h >>> 0) % 233280;
187
+ }
188
+
189
+ /** The context every effect (corpus or local) is constructed with. */
190
+ function fxContextFor(slide: DeckSlide, P: PaletteColors, profile: QualityProfile, mode: "dark" | "light"): FxContext {
191
+ return {
192
+ THREE,
193
+ palette: P,
194
+ mode,
195
+ quality: profile,
196
+ rng: makeRng(fxSeedFor(slide.id)),
197
+ slide: { id: slide.id, title: slide.title, kind: slide.kind ?? "content" },
198
+ };
199
+ }
200
+
201
+ /**
202
+ * Live per-effect parameter edits from the configurator, keyed
203
+ * `<slideId>|<effectId>`. The authored `ref.params` stay untouched so an
204
+ * export still diffs against the deck as written.
205
+ */
206
+ const fxParamEdits: Record<string, FxParams> = {};
207
+
208
+ function paramsFor(slideId: string, ref: { id: string; params?: unknown }): FxParams {
209
+ return { ...((ref.params ?? {}) as FxParams), ...(fxParamEdits[`${slideId}|${ref.id}`] ?? {}) };
210
+ }
211
+
212
+ /**
213
+ * Live effect-LIST edits from the configurator, keyed by slide id. Sits beside
214
+ * `fxParamEdits` for the same reason: the authored `slide.effects` stays the
215
+ * record of what was rendered, so every read goes through `effectsOf`.
216
+ */
217
+ const fxSetEdits: Record<string, string[]> = {};
218
+
219
+ /** The slide's effects as the configurator leaves them (authored, when untouched). */
220
+ function effectsOf(slide: DeckSlide): NonNullable<DeckSlide["effects"]> {
221
+ const authored = slide.effects ?? [];
222
+ const ids = fxSetEdits[slide.id];
223
+ if (!ids) return authored;
224
+ const byId = new Map(authored.map((ref) => [ref.id, ref]));
225
+ // An id the deck never listed carries no authored params — the card
226
+ // defaults, plus whatever the panel tunes, apply.
227
+ return ids.map((id) => byId.get(id) ?? { id });
228
+ }
229
+
230
+ /**
231
+ * Universal `lift` param for background effects: raise the fx box off the
232
+ * floor (y -2.6). Declared here rather than per card so every background
233
+ * effect gets it — including ones added later — with no per-fx code. Default 0
234
+ * keeps a box centred on the slide origin, half-submerged, which is correct
235
+ * for scenery (a plate field reads as terrain) and wrong for a diffuse cloud
236
+ * that just loses its lower half.
237
+ */
238
+ const LIFT_PARAM = { type: "number", default: 0, minimum: -6, maximum: 8 } as const;
239
+
240
+ function backgroundFromEffects(slide: DeckSlide, P: PaletteColors, profile: QualityProfile, mode: "dark" | "light"): Animator | null {
241
+ for (const ref of effectsOf(slide)) {
242
+ const entry = REGISTRY[ref.id];
243
+ if (entry?.card.kind !== "background") continue;
244
+ const params = paramsFor(slide.id, ref);
245
+ const handle = entry.create(fxContextFor(slide, P, profile, mode), params);
246
+ if (!handle.object) continue;
247
+ const g = handle.object as THREE.Group;
248
+ // Both the build path and the live param-edit path come through here, so
249
+ // this is the only place `lift` has to be applied.
250
+ const lift = typeof params.lift === "number" ? params.lift : 0;
251
+ g.position.y = Math.min(LIFT_PARAM.maximum, Math.max(LIFT_PARAM.minimum, lift));
252
+ return { g, tick: handle.tick ?? (() => {}), setActive: handle.setActive };
253
+ }
254
+ return null;
255
+ }
256
+
257
+ /**
258
+ * Instantiate the slide's `local:` effects. A module that throws is dropped
259
+ * (recorded in `localFxErrors`); the slide and its other effects survive.
260
+ */
261
+ function localEffectsFor(
262
+ slide: DeckSlide,
263
+ P: PaletteColors,
264
+ profile: QualityProfile,
265
+ mode: "dark" | "light",
266
+ g: THREE.Group,
267
+ index: number,
268
+ skip?: (id: string) => boolean,
269
+ ): LocalHandle[] {
270
+ const registry = localFxRegistry();
271
+ const out: LocalHandle[] = [];
272
+ const ids: string[] = [];
273
+ for (const ref of effectsOf(slide)) {
274
+ if (!ref.id.startsWith("local:")) continue;
275
+ if (skip?.(ref.id)) continue;
276
+ const module = registry[ref.id.slice("local:".length)];
277
+ const handle = createLocalEffect(
278
+ ref.id,
279
+ module,
280
+ fxContextFor(slide, P, profile, mode),
281
+ paramsFor(slide.id, ref),
282
+ localFxErrors,
283
+ );
284
+ if (!handle) continue;
285
+ ids.push(ref.id);
286
+ if (handle.object) {
287
+ // Both `background` and `motion` local effects are backdrop: nothing an
288
+ // effect draws may ever cover the text.
289
+ markBackdrop(handle.object as THREE.Object3D);
290
+ sortAboveVeil(handle.object as THREE.Object3D);
291
+ g.add(handle.object as THREE.Object3D);
292
+ }
293
+ out.push(handle);
294
+ }
295
+ localFxIds[index] = ids;
296
+ return out;
297
+ }
298
+
299
+ /** Per-slide `local:` ids, index-aligned with `SlideBuild.localFx` (for leak reporting). */
300
+ const localFxIds: string[][] = [];
301
+
302
+ /** Deck-wide local-effect failures, surfaced through `effects().errors`. */
303
+ const localFxErrors: LocalFxError[] = [];
304
+
305
+ function buildSlideGroup(
306
+ deck: RuntimeDeck,
307
+ slide: DeckSlide,
308
+ index: number,
309
+ font: Font,
310
+ models: Map<string, THREE.Object3D>,
311
+ propMaterials: PropMaterials,
312
+ /** Configurator patch, layered over the slide's own config (not persisted). */
313
+ patch?: SlideConfig,
314
+ ): SlideBuild {
315
+ const cfg = patch ? { ...effective(deck.defaults, slide), ...patch } : effective(deck.defaults, slide);
316
+ const P = resolvePalette(cfg);
317
+ const g = new THREE.Group();
318
+ const anchor = anchorFor(index, cfg.camera?.distance, cfg.spacing, cfg.rail, deck.slides.length);
319
+ g.position.copy(anchor.pos);
320
+ g.rotation.y = anchor.rotY;
321
+ const labels: LabelRef[] = [];
322
+ const isTitle = slide.kind === "title";
323
+ addTitle(g, slide, isTitle, font, P, cfg, labels);
324
+ addBody(g, slide, isTitle, P, cfg);
325
+ const diagram = addDiagram(g, slide, font, P, cfg, labels);
326
+ const props = applyProps(deck, slide.id, g, diagram, models, propMaterials);
327
+ if (props) props.group.userData.part = "props";
328
+ const nodes = diagram?.nodes ? Object.entries(diagram.nodes).map(([id, object]) => ({ id, object })) : [];
329
+ const profile = qualityProfile(cfg.quality ?? deck.defaults.quality);
330
+ const mode = (cfg.mode ?? "dark") as "dark" | "light";
331
+ const background = backgroundFromEffects(slide, P, profile, mode) ?? backgroundFor(slide.scene, P, profile) ?? null;
332
+ if (background) {
333
+ background.g.position.z = -2;
334
+ markBackdrop(background.g);
335
+ sortAboveVeil(background.g);
336
+ g.add(background.g);
337
+ }
338
+ const localFx = localEffectsFor(slide, P, profile, mode, g, index);
339
+ const quality = cfg.quality ?? deck.defaults.quality ?? "high";
340
+ const comp = composeEffects(effectsOf(slide), mode, quality, slide.id, localCards());
341
+ const skipped = comp.skipped.map((s) => `${s.id}: ${s.reason}`);
342
+ // The budget warning text is `composeEffects`' own, so the runtime and the
343
+ // render CLI agree byte-for-byte (`warn budget slide <id> <sum> > <limit>`).
344
+ const warning = comp.warnings.find((w) => w.startsWith("warn budget"));
345
+ const budget = {
346
+ sum: comp.active.reduce((total, e) => total + (REGISTRY[e.id]?.card.cost ?? 0), 0),
347
+ limit: QUALITY_BUDGET[quality],
348
+ ...(warning ? { warning } : {}),
349
+ };
350
+ return { group: g, anchor, diagram, background, props, labels, nodes, cfg, palette: P, skipped, budget, localFx };
351
+ }
352
+
353
+ async function boot(): Promise<void> {
354
+ const deck = window.__DECK;
355
+ const font = loadFont(window.__DECK_FONT ?? "");
356
+ try {
357
+ await document.fonts.load("700 16px Poppins");
358
+ } catch {
359
+ // Canvas labels fall back to a system font; titles still use the TTF.
360
+ }
361
+
362
+ // Baseline bloom follows the quality tier; a slide listing the `bloom` card
363
+ // (even at `quality: low`) is honoured per slide by the post stack.
364
+ const rig = createSceneRig(qualityProfile(deck.defaults.quality));
365
+ document.body.appendChild(rig.renderer.domElement);
366
+
367
+ const propModels = await loadPropModels(deck);
368
+ const propMaterials = createPropMaterials(resolvePalette(deck.defaults), deck.defaults);
369
+ const builds = deck.slides.map((slide, i) => buildSlideGroup(deck, slide, i, font, propModels, propMaterials));
370
+ for (const b of builds) rig.world.add(b.group);
371
+ rig.world.children.forEach((g, i) => {
372
+ g.userData.index = i;
373
+ });
374
+
375
+ const camState = { pos: new THREE.Vector3(), target: new THREE.Vector3() };
376
+ let cur = 0;
377
+ let frozen: number | null = null;
378
+ const clock = new THREE.Clock();
379
+ type Anim = {
380
+ from: { pos: THREE.Vector3; target: THREE.Vector3 };
381
+ to: ReturnType<typeof anchorFor>;
382
+ t: number;
383
+ mode: string;
384
+ dur: number;
385
+ mid: THREE.Vector3;
386
+ /** Set only when the two slides differ in palette; drives the look morph. */
387
+ look?: { from: PaletteColors; to: PaletteColors; cfg: SlideConfig };
388
+ };
389
+ let anim: Anim | null = null;
390
+ /** Slide whose local fx are reclaimed once the in-flight transition lands. */
391
+ let pendingDispose: number | null = null;
392
+
393
+ /** Root objects of a named part on slide `i` (selective post passes). */
394
+ function partsOf(i: number, name: PartName): THREE.Object3D[] {
395
+ const g = builds[i].group;
396
+ if (name === "all") return g.children.filter((c) => !c.userData.backdrop);
397
+ const out: THREE.Object3D[] = [];
398
+ g.traverse((o) => {
399
+ if (o.userData.part === name) out.push(o);
400
+ });
401
+ return out;
402
+ }
403
+
404
+ /**
405
+ * Hand the current slide's `post` cards to the rig. Called wherever the
406
+ * slide or its params change; idempotent, so landing after a fly may call
407
+ * it again without cost.
408
+ */
409
+ function syncPost(): void {
410
+ const slide = deck.slides[cur];
411
+ const build = builds[cur];
412
+ const refs = effectsOf(slide)
413
+ .filter((e) => REGISTRY[e.id]?.card.kind === "post")
414
+ .map((e) => ({ id: e.id, params: paramsFor(slide.id, e) }));
415
+ rig.setPost(refs, {
416
+ mode: (build.cfg.mode ?? "dark") as "dark" | "light",
417
+ palette: build.palette,
418
+ parts: (name) => partsOf(cur, name),
419
+ sun: () => rig.sunPosition(),
420
+ focusDistance: () => build.anchor.cam.distanceTo(build.anchor.target),
421
+ });
422
+ }
423
+
424
+ /**
425
+ * Tell the slides which one is settled. Time-based media (a `video-screen`
426
+ * clip) plays only while its slide is in position and frozen otherwise, so
427
+ * a clip never runs off-screen and a pinned time renders a stable frame.
428
+ */
429
+ function settle(active: number | null): void {
430
+ for (let i = 0; i < builds.length; i++) builds[i]?.background?.setActive?.(i === active);
431
+ }
432
+
433
+ function snapTo(i: number): void {
434
+ cur = i;
435
+ settle(i);
436
+ const a = builds[i].anchor;
437
+ camState.pos.copy(a.cam);
438
+ camState.target.copy(a.target);
439
+ anim = null;
440
+ rig.camera.position.copy(camState.pos);
441
+ rig.camera.lookAt(camState.target);
442
+ rig.applyLook(builds[i].palette, builds[i].cfg, qualityProfile(builds[i].cfg.quality));
443
+ syncPost();
444
+ }
445
+
446
+ const ease = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);
447
+
448
+ function stepAnim(dt: number): void {
449
+ if (!anim) return;
450
+ anim.t = Math.min(1, anim.t + dt / anim.dur);
451
+ const k = ease(anim.t);
452
+ if (anim.mode === "fade") {
453
+ if (anim.t >= 0.5) {
454
+ camState.pos.copy(anim.to.cam);
455
+ camState.target.copy(anim.to.target);
456
+ }
457
+ } else {
458
+ camState.pos.lerpVectors(anim.from.pos, anim.to.cam, k);
459
+ camState.target.lerpVectors(anim.from.target, anim.to.target, k);
460
+ if (anim.mode === "swing") {
461
+ const out = camState.pos.clone().sub(anim.mid).normalize();
462
+ camState.pos.addScaledVector(out, Math.sin(anim.t * Math.PI) * 6);
463
+ }
464
+ }
465
+ if (anim.look) {
466
+ const l = anim.look;
467
+ rig.applyLook(anim.t >= 1 ? l.to : mixPalette(l.from, l.to, k), l.cfg, qualityProfile(l.cfg.quality));
468
+ }
469
+ if (anim.t >= 1) {
470
+ anim = null;
471
+ settle(cur);
472
+ if (pendingDispose !== null && pendingDispose !== cur) disposeLocalFx(pendingDispose);
473
+ pendingDispose = null;
474
+ }
475
+ }
476
+
477
+ /**
478
+ * Local effects own real GPU resources, so leaving a slide disposes them.
479
+ * A throwing `dispose` is recorded and swallowed — navigation must complete.
480
+ */
481
+ function disposeLocalFx(index: number): void {
482
+ for (const handle of builds[index]?.localFx ?? []) {
483
+ handle.dispose();
484
+ // `dispose` frees GPU buffers but leaves the node attached. Detach it
485
+ // too, or reviving the slide stacks a second, frozen copy of the effect
486
+ // on top of the live one (the background renders doubled).
487
+ const object = handle.object as THREE.Object3D | undefined;
488
+ object?.parent?.remove(object);
489
+ }
490
+ if (builds[index]) builds[index].localFx = [];
491
+ }
492
+
493
+ /**
494
+ * Free a discarded slide build's GPU resources. The configurator rebuilds
495
+ * the same slide once per edit, so dropping the reference is not enough —
496
+ * three.js never frees buffers on GC.
497
+ *
498
+ * The props subtree is skipped on purpose: `applyProps` places
499
+ * `Object3D.clone()`s of shared model templates, and clones share their
500
+ * geometry and material BY REFERENCE. Disposing them here would blank the
501
+ * same prop on every other slide using it.
502
+ */
503
+ /** Free every mesh under a discarded subtree (three.js never frees on GC). */
504
+ function disposeTree(root: THREE.Object3D): void {
505
+ root.traverse((o) => {
506
+ const mesh = o as THREE.Mesh;
507
+ if (!mesh.isMesh) return;
508
+ mesh.geometry?.dispose();
509
+ const mat = mesh.material;
510
+ for (const m of Array.isArray(mat) ? mat : [mat]) m?.dispose();
511
+ });
512
+ }
513
+
514
+ function disposeBuild(build: SlideBuild): void {
515
+ const propsRoot = build.props?.group;
516
+ build.group.traverse((o) => {
517
+ if (propsRoot && (o === propsRoot || propsRoot.getObjectById(o.id))) return;
518
+ const mesh = o as THREE.Mesh;
519
+ if (!mesh.isMesh) return;
520
+ mesh.geometry?.dispose();
521
+ const mat = mesh.material;
522
+ for (const m of Array.isArray(mat) ? mat : [mat]) m?.dispose();
523
+ });
524
+ }
525
+
526
+ /**
527
+ * Re-create the local effects of a slide whose handles were disposed on the
528
+ * way out. Without this a `local:` effect animates on the FIRST visit only —
529
+ * every later visit shows a slide frozen at whatever pose it was disposed in.
530
+ */
531
+ function reviveLocalFx(index: number): void {
532
+ const build = builds[index];
533
+ if (!build || build.localFx.length > 0) return;
534
+ const slide = deck.slides[index];
535
+ if (!effectsOf(slide).some((ref) => ref.id.startsWith("local:"))) return;
536
+ const profile = qualityProfile(build.cfg.quality ?? deck.defaults.quality);
537
+ const mode = (build.cfg.mode ?? "dark") as "dark" | "light";
538
+ // A module that threw on create throws again: re-running it would only
539
+ // duplicate its entry in `effects().errors`.
540
+ const failed = new Set(localFxErrors.filter((e) => e.slide === slide.id).map((e) => e.effectId));
541
+ build.localFx = localEffectsFor(slide, build.palette, profile, mode, build.group, index, (id) => failed.has(id));
542
+ }
543
+
544
+ function goTo(i: number): void {
545
+ const target = ((i % builds.length) + builds.length) % builds.length;
546
+ reviveLocalFx(target);
547
+ const mode = builds[target].cfg.transition ?? "dolly";
548
+ // A cut leaves the old slide instantly, so its fx can go now. A fly does
549
+ // NOT: the outgoing slide stays in frame for the whole move, and disposing
550
+ // here stripped its backdrop the moment the camera started rolling while
551
+ // its content remained. Deferred to `stepAnim` completion instead.
552
+ if (target === cur || mode === "cut") {
553
+ if (target !== cur) disposeLocalFx(cur);
554
+ return snapTo(target);
555
+ }
556
+ if (pendingDispose !== null && pendingDispose !== target) disposeLocalFx(pendingDispose);
557
+ pendingDispose = cur;
558
+ const from = { pos: camState.pos.clone(), target: camState.target.clone() };
559
+ const fromPalette = builds[cur].palette;
560
+ const toPalette = builds[target].palette;
561
+ // Same palette ⇒ nothing to morph, so the look is applied once as before.
562
+ const morph = JSON.stringify(fromPalette) !== JSON.stringify(toPalette);
563
+ settle(null); // camera about to fly: freeze time-based media
564
+ anim = {
565
+ from,
566
+ to: builds[target].anchor,
567
+ t: 0,
568
+ mode,
569
+ dur: builds[target].cfg.durationSec ?? 1.4,
570
+ mid: from.target.clone().add(builds[target].anchor.target).multiplyScalar(0.5),
571
+ look: morph ? { from: fromPalette, to: toPalette, cfg: builds[target].cfg } : undefined,
572
+ };
573
+ cur = target;
574
+ if (!morph) rig.applyLook(toPalette, builds[target].cfg, qualityProfile(builds[target].cfg.quality));
575
+ syncPost();
576
+ }
577
+
578
+ // Live rail state: the configurator may move every anchor, and `window.__DECK`
579
+ // must stay the record of what was RENDERED, so the state lives here.
580
+ const railState = { spacing: deck.defaults.spacing, rail: deck.defaults.rail };
581
+
582
+ /** Re-place every slide group when the rail topology or spacing changes. */
583
+ function reanchorAll(): void {
584
+ builds.forEach((build, i) => {
585
+ const anchor = anchorFor(i, build.cfg.camera?.distance, railState.spacing, railState.rail, deck.slides.length);
586
+ build.anchor = anchor;
587
+ build.group.position.copy(anchor.pos);
588
+ build.group.rotation.y = anchor.rotY;
589
+ });
590
+ snapTo(cur);
591
+ }
592
+
593
+ function cullNeighbours(): void {
594
+ const cp = rig.camera.position;
595
+ rig.world.children.forEach((g) => {
596
+ g.visible = g.position.distanceTo(cp) < cullRadius(railState.spacing, railState.rail);
597
+ });
598
+ }
599
+
600
+ const pq = new THREE.Quaternion();
601
+ /**
602
+ * Point every diagram label at the camera. `loop`, `globe`, `swarm` and
603
+ * `orbit-cluster` spin a group that CONTAINS its labels, so once the clock
604
+ * runs the captions turn edge-on and then away — invisible in every deck,
605
+ * and invisible to `check`, which measures frozen at t=0 where they happen
606
+ * to face front. Enforced here rather than per builder so a new topology
607
+ * cannot reintroduce it. Deterministic: the camera pose at a given `t` is.
608
+ */
609
+ function billboardLabels(): void {
610
+ for (const label of builds[cur].diagram?.labels ?? []) {
611
+ const o = label.object as THREE.Object3D;
612
+ if (!o.parent) continue;
613
+ o.parent.getWorldQuaternion(pq);
614
+ o.quaternion.copy(pq.invert()).multiply(rig.camera.quaternion);
615
+ }
616
+ }
617
+
618
+ function renderAt(t: number): void {
619
+ const slide = builds[cur];
620
+ slide.diagram?.tick(t);
621
+ slide.background?.tick(t * 0.7);
622
+ slide.props?.tick(t);
623
+ for (const handle of slide.localFx) handle.tick(t);
624
+ rig.followTarget(camState.target);
625
+ cullNeighbours();
626
+ billboardLabels();
627
+ rig.render(t);
628
+ }
629
+
630
+ /**
631
+ * Pose the deck at `t` and draw one frame: camera snapped to the anchor, every
632
+ * animator ticked. Does NOT touch the clock, so boot can prime a deterministic
633
+ * first frame without pinning the deck (that was the "camera drifts but
634
+ * nothing animates" bug — `boot()` called the freezing variant).
635
+ */
636
+ function poseAt(t: number): void {
637
+ anim = null; // a deterministic time cancels any in-flight transition
638
+ const a = builds[cur].anchor;
639
+ camState.pos.copy(a.cam);
640
+ camState.target.copy(a.target);
641
+ rig.camera.position.copy(a.cam);
642
+ rig.camera.lookAt(a.target);
643
+ renderAt(t);
644
+ }
645
+
646
+ /** `setTime`: pose at `t` AND pin the clock there — `check` renders deterministically. */
647
+ function applyTime(t: number): void {
648
+ frozen = t;
649
+ poseAt(t);
650
+ }
651
+
652
+ const tmp = new THREE.Vector3();
653
+ function frame(): void {
654
+ const dt = frozen === null ? clock.getDelta() : 1 / 60;
655
+ const t = frozen === null ? clock.elapsedTime : frozen;
656
+ stepAnim(dt);
657
+ tmp.copy(camState.pos);
658
+ if (frozen === null) tmp.add(new THREE.Vector3(Math.sin(t * 0.35) * 0.25, Math.cos(t * 0.27) * 0.12, Math.sin(t * 0.2) * 0.15));
659
+ // The 0.2 smoothing exists for the idle drift ONLY. Applying it while a
660
+ // transition flies made the camera trail `camState` by seconds: `anim`
661
+ // cleared while the view still sat over the previous slide, so its
662
+ // backdrop stayed on screen well after the move was "done".
663
+ rig.camera.position.lerp(tmp, frozen === null && anim === null ? 0.2 : 1);
664
+ rig.camera.lookAt(camState.target);
665
+ cullNeighbours();
666
+ rig.followTarget(camState.target);
667
+ builds[cur].diagram?.tick(t);
668
+ builds[cur].background?.tick(t * 0.7);
669
+ builds[cur].props?.tick(t);
670
+ for (const handle of builds[cur].localFx) handle.tick(t);
671
+ // The outgoing slide is still in frame during a fly: tick it too, or its
672
+ // backdrop freezes into a still the moment the camera moves.
673
+ if (pendingDispose !== null && pendingDispose !== cur) {
674
+ for (const handle of builds[pendingDispose]?.localFx ?? []) handle.tick(t);
675
+ builds[pendingDispose]?.background?.tick(t * 0.7);
676
+ }
677
+ billboardLabels();
678
+ rig.render(t);
679
+ if (document.hidden) setTimeout(frame, 66);
680
+ else requestAnimationFrame(frame);
681
+ }
682
+
683
+ const raycaster = new THREE.Raycaster();
684
+ function ownerOf(object: THREE.Object3D): string | null {
685
+ let o: THREE.Object3D | null = object;
686
+ while (o) {
687
+ if (typeof o.userData.ownerId === "string") return o.userData.ownerId;
688
+ o = o.parent;
689
+ }
690
+ return null;
691
+ }
692
+
693
+ function raycastOwner(rect: { x: number; y: number; w: number; h: number }, width: number, height: number, target: THREE.Object3D): string | null {
694
+ const ndc = new THREE.Vector2(((rect.x + rect.w / 2) / width) * 2 - 1, -(((rect.y + rect.h / 2) / height) * 2 - 1));
695
+ raycaster.setFromCamera(ndc, rig.camera);
696
+ for (const h of raycaster.intersectObject(target, true)) {
697
+ const owner = ownerOf(h.object);
698
+ if (owner) return owner;
699
+ }
700
+ return null;
701
+ }
702
+
703
+ function labelMeasurement(ref: LabelRef, width: number, height: number, target: THREE.Object3D): Measurement | null {
704
+ const rect = projectRect(ref.object, rig.camera, width, height);
705
+ if (!rect) return null;
706
+ const box = new THREE.Box3().setFromObject(ref.object);
707
+ const worldH = Math.max(0.0001, box.max.y - box.min.y);
708
+ return {
709
+ kind: ref.kind,
710
+ id: ref.id,
711
+ text: ref.text,
712
+ rect,
713
+ capHeight: (ref.height / worldH) * rect.h,
714
+ hit: raycastOwner(rect, width, height, target),
715
+ color: ref.color ?? null,
716
+ };
717
+ }
718
+
719
+ function measure(): Measurement[] {
720
+ const width = rig.renderer.domElement.clientWidth || window.innerWidth;
721
+ const height = rig.renderer.domElement.clientHeight || window.innerHeight;
722
+ const target = builds[cur].group;
723
+ const out: Measurement[] = [];
724
+ for (const ref of builds[cur].labels) {
725
+ const m = labelMeasurement(ref, width, height, target);
726
+ if (m) out.push(m);
727
+ }
728
+ for (const node of builds[cur].nodes) {
729
+ const rect = projectRect(node.object, rig.camera, width, height);
730
+ if (rect) out.push({ kind: "node", id: node.id, text: "", rect, capHeight: 0, hit: null });
731
+ }
732
+ return out;
733
+ }
734
+
735
+ function peaks(): number[] {
736
+ const diagram = deck.slides[cur]?.diagram;
737
+ if (diagram?.kind === "sequence" && diagram.messages) return diagram.messages.map((_, k) => k * 1.1);
738
+ return [0];
739
+ }
740
+
741
+ function hashIndex(): number | null {
742
+ const raw = window.location.hash.replace(/^#/, "");
743
+ if (!raw) return null;
744
+ const n = Number.parseInt(raw, 10);
745
+ if (!Number.isFinite(n)) return null;
746
+ if (n < 1 || n > builds.length) return 0;
747
+ return n - 1;
748
+ }
749
+
750
+ /** Step to a 0-based slide, clamped at both ends, mirroring the index into the `#<n>` hash. */
751
+ function navTo(index: number, syncHash = true): void {
752
+ const target = Math.max(0, Math.min(builds.length - 1, index));
753
+ if (target === cur) return;
754
+ goTo(target);
755
+ hud?.refresh();
756
+ // Setting the hash re-enters via `hashchange`, where `target === cur` returns early.
757
+ if (syncHash) window.location.hash = `#${target + 1}`;
758
+ }
759
+
760
+ /**
761
+ * Rebuild one slide from a patched config. Colours, label sizes, the camera
762
+ * anchor and the background FX are BAKED by `buildSlideGroup`, so re-running
763
+ * `applyLook` alone reaches only the lights. `follow` moves the camera and
764
+ * the lights, which is right for the slide the viewer is on and wrong for
765
+ * the rest of the deck.
766
+ */
767
+ function rebuildSlide(i: number, patch: SlidePatch, follow: boolean): void {
768
+ // Colours, label sizes, the camera anchor and the background FX are all
769
+ // BAKED by `buildSlideGroup`. Re-running `applyLook` alone reaches only
770
+ // the lights, so the slide is rebuilt from the patched config — measured
771
+ // at ~10-21 ms for the heaviest real slide, i.e. about one frame.
772
+ const { scene, diagram: diagramPatch, ...cfgPatch } = patch;
773
+ // `scene` and `diagram.*` are properties of the SLIDE, not of the config,
774
+ // so they are layered onto a copy — `window.__DECK` is never touched.
775
+ const base = deck.slides[i];
776
+ const slide = (scene !== undefined || diagramPatch
777
+ ? { ...base, ...(scene === undefined ? {} : { scene }), ...(diagramPatch ? { diagram: { ...base.diagram, ...diagramPatch } } : {}) }
778
+ : base) as DeckSlide;
779
+ const previous = builds[i];
780
+ const cfg = { ...previous.cfg, ...cfgPatch } as SlideConfig;
781
+
782
+ // The rail moves EVERY anchor, so it is applied deck-wide before the
783
+ // current slide is rebuilt at its new place.
784
+ if (cfgPatch.rail !== undefined || cfgPatch.spacing !== undefined) {
785
+ railState.rail = cfgPatch.rail ?? railState.rail;
786
+ railState.spacing = cfgPatch.spacing ?? railState.spacing;
787
+ reanchorAll();
788
+ }
789
+ cfg.rail = railState.rail;
790
+ cfg.spacing = railState.spacing;
791
+
792
+ disposeLocalFx(i);
793
+ rig.world.remove(previous.group);
794
+
795
+ // Props are tinted from the palette too, so they get materials derived
796
+ // from the patched config rather than the deck defaults.
797
+ const mats = createPropMaterials(resolvePalette(cfg), cfg);
798
+ const rebuilt = buildSlideGroup(deck, slide, i, font, propModels, mats, cfg);
799
+ builds[i] = rebuilt;
800
+ rig.world.add(rebuilt.group);
801
+ rebuilt.group.userData.index = i;
802
+ disposeBuild(previous);
803
+
804
+ if (follow) {
805
+ // A new anchor means the camera must follow, or `camera.distance` stages
806
+ // a value the view never honours.
807
+ camState.pos.copy(rebuilt.anchor.cam);
808
+ camState.target.copy(rebuilt.anchor.target);
809
+ anim = null;
810
+ rig.camera.position.copy(camState.pos);
811
+ rig.camera.lookAt(camState.target);
812
+ }
813
+
814
+ if (follow) rig.applyLook(rebuilt.palette, cfg, qualityProfile(cfg.quality));
815
+ rebuilt.diagram?.tick(0);
816
+ if (i === cur) syncPost();
817
+ rig.render();
818
+ }
819
+
820
+ /**
821
+ * Configurator. Built after the slides so it can read the composed effect
822
+ * list, and given callbacks that re-apply the look WITHOUT touching `__DECK`.
823
+ */
824
+ const hud = createHud({
825
+ slides: deck.slides.map((s) => ({ id: s.id, title: s.title, effects: [...(s.effects ?? [])] })),
826
+ // Everything the deck can instantiate: the corpus, plus the `local:`
827
+ // modules embedded in THIS file. The panel offers exactly this.
828
+ catalogue: [
829
+ ...Object.values(REGISTRY).map((e) => ({ id: e.card.id, kind: e.card.kind as string })),
830
+ ...Object.values(localCards()).map((c) => ({ id: `local:${c.id}`, kind: c.kind as string })),
831
+ ],
832
+ deckEffects: (deck.effects ?? []).map((e) => e.id),
833
+ defaults: deck.defaults,
834
+ overridden: overriddenKeys(),
835
+ derivedHash: (window.__DECK as unknown as { derivedHash?: string }).derivedHash ?? "",
836
+ current: () => cur + 1,
837
+ gotoSlide: (index1Based) => navTo(index1Based - 1),
838
+ applySlide: (patch) => rebuildSlide(cur, patch, true),
839
+ applyDeck: (patchFor) => {
840
+ // A deck-scope value belongs to every slide, and neighbours stay in
841
+ // frame on the shared rail — rebuilding only the current slide leaves
842
+ // the rest of the deck visibly stale.
843
+ for (let i = 0; i < builds.length; i++) rebuildSlide(i, patchFor(deck.slides[i].id), i === cur);
844
+ },
845
+ /**
846
+ * Declared knobs of the current slide's effects, with the value in force.
847
+ * The panel renders itself from this, so a new effect (corpus OR local)
848
+ * gets controls by declaring params in its card — no panel code.
849
+ */
850
+ effectParams: () => {
851
+ const slide = deck.slides[cur];
852
+ const local = localCards();
853
+ const out: Array<{ id: string; schema: Record<string, unknown>; values: FxParams }> = [];
854
+ for (const ref of effectsOf(slide)) {
855
+ const card = ref.id.startsWith("local:") ? local[ref.id.slice("local:".length)] : REGISTRY[ref.id]?.card;
856
+ // `lift` is engine-level, so it is advertised to the panel here rather
857
+ // than sitting in every background card's params. Only corpus effects:
858
+ // `local:` modules run through `localEffectsFor`, which never applies
859
+ // it. Injected FIRST so a card declaring its own `lift` still wins.
860
+ const engineParams = !ref.id.startsWith("local:") && card?.kind === "background" ? { lift: LIFT_PARAM } : {};
861
+ const schema = { ...engineParams, ...((card?.params ?? {}) as Record<string, unknown>) };
862
+ if (Object.keys(schema).length === 0) continue;
863
+ out.push({ id: ref.id, schema, values: paramsFor(slide.id, ref) });
864
+ }
865
+ return out;
866
+ },
867
+ /** Re-instantiate ONE effect of the current slide under edited params. */
868
+ // Restore path: stage params for ANY slide without rebuilding. `paramsFor`
869
+ // reads `fxParamEdits` at build time, so seeding then rebuilding restores
870
+ // every slide's tuning, not just the one on screen.
871
+ seedEffectParams: (slideId, id, patch) => {
872
+ const key = `${slideId}|${id}`;
873
+ fxParamEdits[key] = { ...(fxParamEdits[key] ?? {}), ...(patch as FxParams) };
874
+ },
875
+ applyEffectParams: (id, patch) => {
876
+ const slide = deck.slides[cur];
877
+ const key = `${slide.id}|${id}`;
878
+ fxParamEdits[key] = { ...(fxParamEdits[key] ?? {}), ...(patch as FxParams) };
879
+ const build = builds[cur];
880
+ const profile = qualityProfile(build.cfg.quality ?? deck.defaults.quality);
881
+ const mode = (build.cfg.mode ?? "dark") as "dark" | "light";
882
+ if (id.startsWith("local:")) {
883
+ // Dispose and rebuild every local handle: they share one array and the
884
+ // factory is the only place params are read.
885
+ disposeLocalFx(cur);
886
+ build.localFx = localEffectsFor(slide, build.palette, profile, mode, build.group, cur);
887
+ } else {
888
+ if (build.background) {
889
+ build.group.remove(build.background.g);
890
+ disposeTree(build.background.g);
891
+ }
892
+ const next = backgroundFromEffects(slide, build.palette, profile, mode);
893
+ build.background = next;
894
+ if (next) {
895
+ next.g.position.z = -2;
896
+ markBackdrop(next.g);
897
+ sortAboveVeil(next.g);
898
+ build.group.add(next.g);
899
+ }
900
+ }
901
+ syncPost();
902
+ rig.render();
903
+ },
904
+ /**
905
+ * Recompose the current slide. Flipping `background.visible` used to stand
906
+ * in for this, which reached neither the post stack nor the `local:`
907
+ * modules — a removed `post` card kept rendering until a reload.
908
+ */
909
+ applyEffects: (ids) => {
910
+ fxSetEdits[deck.slides[cur].id] = [...ids];
911
+ rebuildSlide(cur, {}, true);
912
+ },
913
+ });
914
+
915
+ /** Override key paths, precomputed by `render` (the merged IR cannot tell). */
916
+ function overriddenKeys(): { deck: Set<string>; slides: Record<string, Set<string>> } {
917
+ const raw = (window.__DECK as unknown as { overriddenKeys?: { deck: string[]; slides: Record<string, string[]> } })
918
+ .overriddenKeys ?? { deck: [], slides: {} };
919
+ const slides: Record<string, Set<string>> = {};
920
+ for (const [id, keys] of Object.entries(raw.slides)) slides[id] = new Set(keys);
921
+ return { deck: new Set(raw.deck), slides };
922
+ }
923
+
924
+ rig.resize(window.innerWidth, window.innerHeight);
925
+ window.addEventListener("resize", () => rig.resize(window.innerWidth, window.innerHeight));
926
+ window.addEventListener("keydown", (e) => {
927
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
928
+ // A panel input owns the keyboard while it has focus — including `C`, or
929
+ // typing a palette name would toggle the panel away mid-edit.
930
+ if (hud.hasFocus()) {
931
+ if (e.key === "Escape") (document.activeElement as HTMLElement | null)?.blur();
932
+ return;
933
+ }
934
+ if (e.key === "c" || e.key === "C") {
935
+ hud.toggle();
936
+ e.preventDefault();
937
+ return;
938
+ }
939
+ if (e.key === "Escape") {
940
+ hud.close();
941
+ return;
942
+ }
943
+ switch (e.key) {
944
+ case "ArrowRight":
945
+ case "ArrowDown":
946
+ case "PageDown":
947
+ case " ":
948
+ navTo(cur + 1);
949
+ break;
950
+ case "ArrowLeft":
951
+ case "ArrowUp":
952
+ case "PageUp":
953
+ navTo(cur - 1);
954
+ break;
955
+ case "Home":
956
+ navTo(0);
957
+ break;
958
+ case "End":
959
+ navTo(builds.length - 1);
960
+ break;
961
+ default:
962
+ return;
963
+ }
964
+ e.preventDefault();
965
+ });
966
+ window.addEventListener("pointerup", (e) => {
967
+ if (e.button !== 0) return;
968
+ // Clicks on the gear or inside the panel are panel interactions.
969
+ if (hud.contains(e.target)) return;
970
+ navTo(cur + 1);
971
+ });
972
+ window.addEventListener("hashchange", () => {
973
+ const i = hashIndex();
974
+ if (i !== null) navTo(i, false);
975
+ });
976
+ snapTo(hashIndex() ?? 0);
977
+
978
+ const api: Deck3dApi = {
979
+ gotoSlide: (index1Based: number) => {
980
+ goTo(Math.max(1, Math.min(builds.length, index1Based)) - 1);
981
+ hud?.refresh();
982
+ builds[cur].diagram?.tick(0);
983
+ rig.render();
984
+ },
985
+ setTime: (seconds: number) => applyTime(seconds),
986
+ ready: () => Promise.resolve(),
987
+ measure,
988
+ peaks,
989
+ effects: () => ({
990
+ active: rig.passNames(),
991
+ skipped: builds[cur].skipped,
992
+ budget: builds[cur].budget,
993
+ errors: localFxErrors.map((e) => ({ ...e })),
994
+ }),
995
+ debug: {
996
+ titleGlyphs: () => {
997
+ const title = builds[cur].labels.find((l) => l.kind === "title");
998
+ if (!title) return 0;
999
+ let count = 0;
1000
+ title.object.traverse((o) => {
1001
+ if ((o as THREE.Mesh).isMesh) count++;
1002
+ });
1003
+ return count;
1004
+ },
1005
+ liftedMessage: () => builds[cur].diagram?.lifted?.() ?? null,
1006
+ /**
1007
+ * How squarely each diagram label faces the camera: 1 = head-on,
1008
+ * 0 = edge-on, negative = facing away. `measure()` cannot answer this —
1009
+ * its projection is rotation-invariant by design (rails rotate slides),
1010
+ * so a caption spun edge-on still measures full width. That blindness is
1011
+ * why spinning topologies shipped with unreadable captions.
1012
+ */
1013
+ labelFacing: () => {
1014
+ // Billboards are screen-aligned (parallel to the view plane), so the
1015
+ // metric is the label normal against the camera's own forward axis —
1016
+ // NOT against the direction to the label, which undershoots off-axis.
1017
+ const camForward = new THREE.Vector3();
1018
+ rig.camera.getWorldDirection(camForward);
1019
+ const q = new THREE.Quaternion();
1020
+ const labelDir = new THREE.Vector3();
1021
+ return (builds[cur].diagram?.labels ?? []).map((label) => {
1022
+ const o = label.object as THREE.Object3D;
1023
+ labelDir.set(0, 0, 1).applyQuaternion(o.getWorldQuaternion(q));
1024
+ return -labelDir.dot(camForward);
1025
+ });
1026
+ },
1027
+ /**
1028
+ * Backdrop objects whose subtree escaped onto the content layer. An
1029
+ * effect that `add()`s children during `tick` gets the default layer, and
1030
+ * those children CAN cover the text — the one hole the two-pass render
1031
+ * cannot close by construction. `check` turns this into a finding.
1032
+ */
1033
+ /**
1034
+ * Shadow-pipeline probe: what the renderer, the key light and the scene
1035
+ * actually agree on. `castShadow` flags scattered across the builders
1036
+ * say nothing about whether a shadow reaches the frame.
1037
+ */
1038
+ shadows: () => {
1039
+ const casters: string[] = [];
1040
+ const receivers: string[] = [];
1041
+ rig.scene.traverse((n) => {
1042
+ const mesh = n as THREE.Mesh;
1043
+ if (!(mesh as { isMesh?: boolean }).isMesh) return;
1044
+ const label = `${n.name || n.type}@${n.layers.mask}`;
1045
+ if (mesh.castShadow) casters.push(label);
1046
+ if (mesh.receiveShadow) receivers.push(label);
1047
+ });
1048
+ const cam = rig.shadowCamera();
1049
+ return {
1050
+ enabled: rig.renderer.shadowMap.enabled,
1051
+ autoUpdate: rig.renderer.shadowMap.autoUpdate,
1052
+ camera: cam,
1053
+ casters: casters.slice(0, 12),
1054
+ receivers: receivers.slice(0, 12),
1055
+ casterCount: casters.length,
1056
+ receiverCount: receivers.length,
1057
+ };
1058
+ },
1059
+ backdropLeaks: () => {
1060
+ const leaked: string[] = [];
1061
+ const scan = (root: THREE.Object3D | undefined, owner: string): void => {
1062
+ if (!root) return;
1063
+ root.traverse((n) => {
1064
+ if (!n.userData.backdrop && !leaked.includes(owner)) leaked.push(owner);
1065
+ });
1066
+ };
1067
+ scan(builds[cur].background?.g, "scene-background");
1068
+ for (const [i, h] of builds[cur].localFx.entries()) scan(h.object as THREE.Object3D | undefined, localFxIds[cur]?.[i] ?? `local[${i}]`);
1069
+ return leaked;
1070
+ },
1071
+ /** Fingerprint of the current slide's animated transforms, for motion probes. */
1072
+ motion: () => {
1073
+ const parts: number[] = [];
1074
+ const walk = (o: THREE.Object3D | undefined): void => {
1075
+ if (!o) return;
1076
+ o.traverse((n) => {
1077
+ parts.push(n.position.x, n.position.y, n.position.z, n.rotation.y);
1078
+ // Most fx animate by rewriting instance matrices, not node
1079
+ // transforms; without this the probe reports a busy InstancedMesh
1080
+ // background as motionless.
1081
+ const inst = (n as THREE.InstancedMesh).instanceMatrix;
1082
+ if (inst) parts.push(inst.version, inst.array[12] ?? 0, inst.array[13] ?? 0, inst.array[14] ?? 0);
1083
+ });
1084
+ };
1085
+ walk(builds[cur].diagram?.g);
1086
+ walk(builds[cur].background?.g);
1087
+ for (const h of builds[cur].localFx) walk(h.object as THREE.Object3D | undefined);
1088
+ return parts.map((n) => Math.round(n * 1e4) / 1e4).join(",");
1089
+ },
1090
+ /**
1091
+ * Local-effect liveness, scoped: `motion()` mixes in the diagram and the
1092
+ * corpus background, so a dead local handle hides behind them. Reports
1093
+ * one entry per live handle with a transform digest.
1094
+ */
1095
+ localFx: () =>
1096
+ builds[cur].localFx.map((h, i) => {
1097
+ const parts: number[] = [];
1098
+ (h.object as THREE.Object3D | undefined)?.traverse((n) => {
1099
+ parts.push(n.position.x, n.position.y, n.position.z, n.rotation.x, n.rotation.y, n.rotation.z);
1100
+ const inst = (n as THREE.InstancedMesh).instanceMatrix;
1101
+ if (inst) parts.push(inst.version, inst.array[12] ?? 0, inst.array[13] ?? 0, inst.array[14] ?? 0);
1102
+ });
1103
+ return { id: localFxIds[cur]?.[i] ?? `local[${i}]`, digest: parts.map((n) => Math.round(n * 1e4) / 1e4).join(",") };
1104
+ }),
1105
+ /**
1106
+ * Descendant count of the current slide group. Catches orphans that
1107
+ * `motion()`/`localFx()` structurally cannot see: both walk LIVE
1108
+ * handles, while a leaked node is one nothing references any more.
1109
+ */
1110
+ /** Live local-fx handle count per slide index — `localFx()` only sees `cur`. */
1111
+ localFxAt: (index: number) => builds[index]?.localFx.length ?? 0,
1112
+ sceneNodes: () => {
1113
+ let n = 0;
1114
+ builds[cur].group.traverse(() => n++);
1115
+ return n;
1116
+ },
1117
+ post: () => rig.postProbe(),
1118
+ anchors: () =>
1119
+ builds.map((b) => ({ pos: [b.group.position.x, b.group.position.y, b.group.position.z] as [number, number, number], rotY: b.group.rotation.y })),
1120
+ /**
1121
+ * Scene-side look, read from the live objects rather than from the
1122
+ * config that was *meant* to produce them. Configurator tests assert
1123
+ * on this so a control that stages a value without reaching the frame
1124
+ * still fails.
1125
+ */
1126
+ look: () => {
1127
+ const hex = (c: THREE.Color | undefined): string => (c ? `#${c.getHexString()}` : "");
1128
+ const title = builds[cur].labels.find((l) => l.kind === "title");
1129
+ let titleColor: THREE.Color | undefined;
1130
+ let edgeColor: THREE.Color | undefined;
1131
+ title?.object.traverse((o) => {
1132
+ const material = (o as THREE.Mesh).material as THREE.MeshStandardMaterial | THREE.Material[] | undefined;
1133
+ // A contoured glyph carries [face, edge]; a plain one, one material.
1134
+ const list = Array.isArray(material) ? material : material ? [material] : [];
1135
+ const face = list[0] as THREE.MeshStandardMaterial | undefined;
1136
+ const edge = list[1] as THREE.MeshStandardMaterial | undefined;
1137
+ if (!titleColor && face?.color) titleColor = face.color;
1138
+ if (!edgeColor && edge?.color) edgeColor = edge.color;
1139
+ });
1140
+ return {
1141
+ bg: hex(rig.scene.background as THREE.Color | undefined),
1142
+ fog: hex(rig.scene.fog instanceof THREE.Fog ? rig.scene.fog.color : undefined),
1143
+ rim: hex(rig.rimColor()),
1144
+ title: hex(titleColor),
1145
+ /** Contour colour on the glyph side walls, `""` when the switch is off. */
1146
+ titleEdge: hex(edgeColor),
1147
+ camZ: rig.camera.position.z,
1148
+ // Full camera + its target: the rail runs on X, so `camZ` alone
1149
+ // cannot tell a settled camera from one still travelling.
1150
+ cam: rig.camera.position.toArray() as [number, number, number],
1151
+ camTarget: camState.target.toArray() as [number, number, number],
1152
+ anim: anim === null ? null : { mode: anim.mode, t: anim.t, dur: anim.dur },
1153
+ floor: rig.floorMode(),
1154
+ reflectBackdrop: rig.reflectsBackdrop(),
1155
+ floorMatte: rig.floorMatte(),
1156
+ floorReflectivity: rig.floorReflectivity(),
1157
+ ...rig.lightRig(),
1158
+ };
1159
+ },
1160
+ },
1161
+ current: () => cur + 1,
1162
+ };
1163
+ poseAt(0);
1164
+ window.__deck3d = api;
1165
+ frame();
1166
+ }
1167
+
1168
+ void boot();