@blackbelt-technology/pi-dashboard-deck3d 0.9.0 → 0.10.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 (105) hide show
  1. package/.pi/skills/deck3d/SKILL.agent.md +78 -0
  2. package/.pi/skills/deck3d/SKILL.md +68 -0
  3. package/.pi/skills/deck3d/reference/effects.md +185 -2
  4. package/.pi/skills/deck3d/reference/ir-fields.md +26 -3
  5. package/.pi/skills/deck3d-from-pptx/SKILL.md +134 -0
  6. package/.pi/skills/deck3d-from-pptx/reference/steps.md +72 -0
  7. package/README.md +30 -2
  8. package/assets/preview/stub-chrome.png +0 -0
  9. package/assets/preview/stub-icon.json +59 -0
  10. package/assets/preview/stub-layout.json +195 -0
  11. package/assets/preview/stub-outline.json +48 -0
  12. package/dist/cli.js +11780 -5934
  13. package/dist/runtime.js +5916 -4007
  14. package/fixtures/business-2031/assets/stub-chrome.png +0 -0
  15. package/fixtures/business-2031/assets/stub-icon.json +59 -0
  16. package/fixtures/business-2031/assets/stub-layout.json +195 -0
  17. package/fixtures/business-2031/assets/stub-outline.json +48 -0
  18. package/fixtures/business-2031/build-overrides.mjs +58 -13
  19. package/fixtures/business-2031/deck.agent.md +60 -0
  20. package/fixtures/business-2031/deck.json +133 -8
  21. package/fixtures/business-2031/overrides.json +133 -8
  22. package/package.json +8 -4
  23. package/scripts/gen-stub-assets.ts +31 -0
  24. package/src/art/cutout.ts +97 -0
  25. package/src/art/decode.ts +169 -0
  26. package/src/art/icon.ts +380 -0
  27. package/src/art/png.ts +232 -0
  28. package/src/art/trace.ts +288 -0
  29. package/src/check/rules.ts +13 -8
  30. package/src/cli.ts +313 -51
  31. package/src/compare/index.ts +131 -0
  32. package/src/compare/ssim.ts +91 -0
  33. package/src/fx/art-geometry.ts +137 -0
  34. package/src/fx/art3d.meta.json +30 -0
  35. package/src/fx/art3d.ts +131 -0
  36. package/src/fx/bank.meta.json +26 -0
  37. package/src/fx/bank.ts +8 -0
  38. package/src/fx/compose.ts +5 -4
  39. package/src/fx/crane.meta.json +26 -0
  40. package/src/fx/crane.ts +8 -0
  41. package/src/fx/dolly.ts +5 -1
  42. package/src/fx/fade.ts +5 -1
  43. package/src/fx/flythrough.ts +5 -1
  44. package/src/fx/frame-chrome.meta.json +17 -0
  45. package/src/fx/frame-chrome.ts +134 -0
  46. package/src/fx/haze.meta.json +19 -0
  47. package/src/fx/haze.ts +91 -0
  48. package/src/fx/icon3d.meta.json +21 -0
  49. package/src/fx/icon3d.ts +167 -0
  50. package/src/fx/index.ts +96 -66
  51. package/src/fx/iris.ts +5 -1
  52. package/src/fx/meta.schema.json +10 -2
  53. package/src/fx/path.meta.json +25 -0
  54. package/src/fx/path.ts +8 -0
  55. package/src/fx/persistent.ts +11 -0
  56. package/src/fx/revolve.meta.json +26 -0
  57. package/src/fx/revolve.ts +8 -0
  58. package/src/fx/slide-layer.meta.json +26 -0
  59. package/src/fx/slide-layer.ts +557 -0
  60. package/src/fx/slide-space.ts +142 -0
  61. package/src/fx/stub-assets.ts +117 -0
  62. package/src/fx/swing.meta.json +26 -0
  63. package/src/fx/swing.ts +8 -0
  64. package/src/fx/types.ts +63 -2
  65. package/src/ir/merge.ts +5 -2
  66. package/src/ir/schema.json +140 -3
  67. package/src/ir/types.ts +54 -0
  68. package/src/ir/validate.ts +91 -3
  69. package/src/parse/harvest/index.ts +4 -1
  70. package/src/parse/markdown.ts +38 -7
  71. package/src/pptx/baseline.ts +183 -0
  72. package/src/pptx/extract.ts +161 -0
  73. package/src/pptx/fallback.ts +70 -0
  74. package/src/pptx/import.ts +256 -0
  75. package/src/pptx/master.ts +135 -0
  76. package/src/pptx/media.ts +81 -0
  77. package/src/pptx/package.ts +109 -0
  78. package/src/pptx/ref.ts +100 -0
  79. package/src/pptx/shapes.ts +276 -0
  80. package/src/pptx/stage.ts +82 -0
  81. package/src/pptx/text.ts +202 -0
  82. package/src/pptx/theme.ts +194 -0
  83. package/src/pptx/types.ts +159 -0
  84. package/src/pptx/xfrm.ts +93 -0
  85. package/src/pptx/xml.ts +106 -0
  86. package/src/pptx/zip.ts +239 -0
  87. package/src/render/assets.ts +57 -0
  88. package/src/render/build.ts +75 -0
  89. package/src/render/index.ts +7 -2
  90. package/src/render/template.html +1 -1
  91. package/src/runtime/assets.ts +75 -0
  92. package/src/runtime/fade.ts +110 -0
  93. package/src/runtime/hud.ts +37 -9
  94. package/src/runtime/index.ts +431 -67
  95. package/src/runtime/post.ts +11 -5
  96. package/src/runtime/scene.ts +25 -2
  97. package/src/runtime/transition.ts +222 -0
  98. package/src/runtime/types.ts +13 -2
  99. package/src/serve/index.ts +199 -16
  100. package/src/util/cleanup.ts +13 -0
  101. package/src/util/confine.ts +15 -0
  102. package/src/variants/pick.ts +282 -0
  103. package/src/variants/render.ts +179 -0
  104. package/src/variants/schema.json +48 -0
  105. package/src/variants/style.ts +318 -0
@@ -0,0 +1,26 @@
1
+ {
2
+ "id": "revolve",
3
+ "kind": "transition",
4
+ "tags": {
5
+ "mood": [
6
+ "cinematic",
7
+ "dramatic"
8
+ ],
9
+ "content": [
10
+ "motion"
11
+ ]
12
+ },
13
+ "cost": 2,
14
+ "modes": "both",
15
+ "params": {
16
+ "intensity": {
17
+ "type": "number",
18
+ "default": 1,
19
+ "minimum": 0,
20
+ "maximum": 2
21
+ }
22
+ },
23
+ "conflicts": [],
24
+ "source": "https://threejs.org/examples/",
25
+ "licence": "MIT"
26
+ }
@@ -0,0 +1,8 @@
1
+ import type { FxFactory, FxHandle } from "./types.js";
2
+
3
+ /**
4
+ * Camera transition `revolve`: swings wide to the travel-right side and arcs in around the arriving slide.
5
+ * Motion lives in `runtime/transition.ts` (`makeMotion`); this card only
6
+ * registers the id. Scale with the IR knob `transitionAmount`.
7
+ */
8
+ export const create: FxFactory = (): FxHandle => ({ pass: "transition:revolve", dispose: () => {} });
@@ -0,0 +1,26 @@
1
+ {
2
+ "id": "slide-layer",
3
+ "kind": "layer",
4
+ "tags": {
5
+ "mood": ["faithful", "editorial"],
6
+ "content": ["imported-slide", "pptx", "layout"]
7
+ },
8
+ "cost": 2,
9
+ "modes": "both",
10
+ "replacesContent": true,
11
+ "params": {
12
+ "layout": { "type": "string", "default": "pptx-layout" },
13
+ "slide": { "type": "string" },
14
+ "mode": { "type": "string", "enum": ["screen", "panel", "free"], "default": "free" },
15
+ "depths": { "type": "object", "default": { "body": 0, "icon": 0.6, "title": 0.9, "image": 1.2 } },
16
+ "panel": { "type": "object", "default": { "material": "glass", "tilt": 0 } },
17
+ "halo": { "type": "number", "default": 0, "minimum": 0, "maximum": 1 },
18
+ "background": { "type": "boolean", "default": true },
19
+ "skip": { "type": "array", "default": [] },
20
+ "retext": { "type": "object", "default": {} },
21
+ "widen": { "type": "object", "default": {} }
22
+ },
23
+ "conflicts": [],
24
+ "source": "https://github.com/BlackBeltTechnology/pi-agent-dashboard/tree/develop/packages/deck3d/src/fx/slide-layer.ts",
25
+ "licence": "MIT"
26
+ }
@@ -0,0 +1,557 @@
1
+ /**
2
+ * `slide-layer` — draws one slide of an imported `layout.json` as up to four
3
+ * depth layers (body, icon, title, image), each a single camera-facing plane
4
+ * that exactly fills the slide frame from the settled pose (design D4, spec
5
+ * deck3d-slide-layers). Each layer's content is painted into an offscreen
6
+ * canvas at frame resolution, so at rest every item sits on its mapped rect;
7
+ * in flight the layers' different depths give parallax.
8
+ *
9
+ * Text items are registered with `measure()` (kind `layer-text`) through
10
+ * `FxHandle.measure`, so `check`'s rules apply to imported text.
11
+ */
12
+ import type * as THREE_NS from "three";
13
+ import type { FallbackItem, ImgItem, Layout, LayoutItem, LayoutParagraph, LayoutSlide, RectItem, TextItem } from "../pptx/types.js";
14
+ import { type Basis, cameraBasis, fontAssetId, type PlaneMap, planeMap, poseBasis, projectPoints } from "./slide-space.js";
15
+ import type { FxContext, FxFactory, FxHandle, FxMeasure, FxParams, FxView } from "./types.js";
16
+
17
+ type LayerName = "body" | "icon" | "title" | "image";
18
+ const LAYERS: LayerName[] = ["body", "icon", "title", "image"];
19
+ const DEFAULT_DEPTHS: Record<LayerName, number> = { body: 0, icon: 0.6, title: 0.9, image: 1.2 };
20
+ const MAX_CANVAS = 4096;
21
+ const CAP_RATIO = 0.7;
22
+
23
+ /** Axis-aligned bounds of an item's (possibly rotated) rect. */
24
+ function boundsOf(item: LayoutItem): { x1: number; y1: number; x2: number; y2: number } {
25
+ const r = item.rect;
26
+ const a = (item.rotation * Math.PI) / 180;
27
+ const w = Math.abs(r.w * Math.cos(a)) + Math.abs(r.h * Math.sin(a));
28
+ const h = Math.abs(r.w * Math.sin(a)) + Math.abs(r.h * Math.cos(a));
29
+ const cx = r.x + r.w / 2;
30
+ const cy = r.y + r.h / 2;
31
+ return { x1: cx - w / 2, y1: cy - h / 2, x2: cx + w / 2, y2: cy + h / 2 };
32
+ }
33
+
34
+ /**
35
+ * Which plane each item is drawn on. By default the kind decides (body, icon,
36
+ * title, image), but the original draw ORDER wins wherever two items overlap:
37
+ * an item is never placed in front of an overlapping item that sits above it
38
+ * in the pptx (a picture under a title must not cover the title). Walking the
39
+ * z-order top-down, each item takes the deepest rank among its default and the
40
+ * ranks of the overlapping items above it. Items on one plane paint in z-order.
41
+ * `order` lists the layer names back to front.
42
+ */
43
+ export function assignLayers(items: LayoutItem[], order: LayerName[]): Map<string, LayerName> {
44
+ const rankOf = new Map(order.map((n, i) => [n, i]));
45
+ const rank = items.map((i) => rankOf.get(layerOf(i)) ?? 0);
46
+ const bounds = items.map(boundsOf);
47
+ for (let i = items.length - 1; i >= 0; i--) {
48
+ for (let j = i + 1; j < items.length; j++) {
49
+ const a = bounds[i];
50
+ const b = bounds[j];
51
+ const overlap = a.x1 < b.x2 && b.x1 < a.x2 && a.y1 < b.y2 && b.y1 < a.y2;
52
+ if (overlap && rank[i] > rank[j]) rank[i] = rank[j];
53
+ }
54
+ }
55
+ return new Map(items.map((it, i) => [it.id, order[rank[i]]]));
56
+ }
57
+
58
+ function layerOf(item: LayoutItem): LayerName {
59
+ if (item.kind === "text") return item.placeholder === "title" || item.placeholder === "ctrTitle" ? "title" : "body";
60
+ if (item.kind === "img") return item.svg ? "icon" : "image";
61
+ if (item.kind === "fallback") return "image";
62
+ return "body";
63
+ }
64
+
65
+ // ── font availability ────────────────────────────────────────────────────────
66
+
67
+ const fontCache = new Map<string, boolean>();
68
+
69
+ /** True when the browser renders `name` itself (width differs from both generic fallbacks). */
70
+ function hasFont(name: string): boolean {
71
+ const cached = fontCache.get(name);
72
+ if (cached !== undefined) return cached;
73
+ const c = document.createElement("canvas").getContext("2d") as CanvasRenderingContext2D;
74
+ const probe = "mmmmmmmmmmlli WQ@#0123456789";
75
+ const width = (font: string) => {
76
+ c.font = `64px ${font}`;
77
+ return c.measureText(probe).width;
78
+ };
79
+ const quoted = `"${name.replace(/"/g, "")}"`;
80
+ const ok = ["monospace", "serif"].some((g) => width(`${quoted}, ${g}`) !== width(g));
81
+ fontCache.set(name, ok);
82
+ return ok;
83
+ }
84
+
85
+ // ── text layout ──────────────────────────────────────────────────────────────
86
+
87
+ interface Token {
88
+ text: string;
89
+ font: string;
90
+ color: string;
91
+ size: number;
92
+ underline: boolean;
93
+ width: number;
94
+ space: boolean;
95
+ newline: boolean;
96
+ }
97
+
98
+ interface Line {
99
+ tokens: Token[];
100
+ width: number;
101
+ height: number;
102
+ ascent: number;
103
+ align: LayoutParagraph["align"];
104
+ indent: number;
105
+ }
106
+
107
+ function cssFont(run: { bold: boolean; italic: boolean }, px: number, family: string): string {
108
+ return `${run.italic ? "italic " : ""}${run.bold ? "700" : "400"} ${px}px ${family}, "Poppins", sans-serif`;
109
+ }
110
+
111
+ export const create: FxFactory = (ctx: FxContext, params: FxParams): FxHandle => {
112
+ const THREE = ctx.THREE;
113
+ if (!ctx.view) throw new Error("slide-layer needs the runtime view (corpus layer effect)");
114
+ const view: FxView = ctx.view;
115
+ const layoutId = typeof params.layout === "string" ? params.layout : "pptx-layout";
116
+ const layout = ctx.assets.get(layoutId) as Layout;
117
+ const slideId = typeof params.slide === "string" ? params.slide : ctx.slide.id;
118
+ const found = layout.slides?.find((s: LayoutSlide) => s.id === slideId);
119
+ if (!found) throw new Error(`slide-layer: layout '${layoutId}' has no slide '${slideId}'`);
120
+ const slide: LayoutSlide = found;
121
+
122
+ const mode = params.mode === "screen" || params.mode === "panel" ? params.mode : "free";
123
+ const depths = { ...DEFAULT_DEPTHS, ...((params.depths as Record<string, number> | undefined) ?? {}) };
124
+ const panel = (params.panel as { tilt?: number; material?: string } | undefined) ?? {};
125
+ const tilt = mode === "panel" ? Number(panel.tilt ?? 0) : 0;
126
+ const halo = Math.min(1, Math.max(0, Number(params.halo ?? 0)));
127
+ const skip = new Set(Array.isArray(params.skip) ? (params.skip as string[]) : []);
128
+ const retext = (params.retext as Record<string, string> | undefined) ?? {};
129
+ const widen = (params.widen as Record<string, number> | undefined) ?? {};
130
+ const drawBackground = params.background !== false;
131
+ const size = layout.size;
132
+ const tier = ctx.quality.shadowMapSize >= 4096 ? 2 : ctx.quality.shadowMapSize >= 2048 ? 1.5 : 1;
133
+ const fallbacks = new Set<string>();
134
+
135
+ /** Family to draw `name` with: the font itself, a `font-*` asset, else the deck font. */
136
+ const familyCache = new Map<string, string>();
137
+ const familyFor = (name: string): string => {
138
+ const hit = familyCache.get(name);
139
+ if (hit) return hit;
140
+ let family: string;
141
+ if (name && hasFont(name)) family = `"${name.replace(/"/g, "")}"`;
142
+ else if (ctx.assets.has(fontAssetId(name))) family = `"${String(ctx.assets.get(fontAssetId(name)))}"`;
143
+ else {
144
+ family = '"Poppins"';
145
+ if (name) fallbacks.add(name);
146
+ }
147
+ familyCache.set(name, family);
148
+ return family;
149
+ };
150
+
151
+ const items = slide.items.filter((i) => !skip.has(i.id));
152
+ // Planes back to front by their depth (a deck may reorder them with `depths`).
153
+ const order = [...LAYERS].sort((a, b) => depths[a] - depths[b] || LAYERS.indexOf(a) - LAYERS.indexOf(b));
154
+ const planeOf = assignLayers(items, order);
155
+ // A text item inside a shape fallback is hidden while that fallback's crop is drawn:
156
+ // the crop already contains the text, and painting it again doubles every glyph.
157
+ const drawnFallbacks = new Set(items.filter((i) => i.kind === "fallback" && i.asset && ctx.assets.has(i.asset)).map((i) => i.id));
158
+ const underCrop = (i: LayoutItem): boolean => i.kind === "text" && i.coveredBy !== undefined && drawnFallbacks.has(i.coveredBy);
159
+ const textItems = items.filter((i): i is TextItem => i.kind === "text" && !underCrop(i));
160
+ const haloColor = slide.background?.color ?? ctx.palette.bg;
161
+
162
+ const root = new THREE.Group();
163
+ root.userData.part = "layers";
164
+ const meshes = new Map<LayerName, THREE_NS.Mesh>();
165
+ const canvases = new Map<LayerName, HTMLCanvasElement>();
166
+ for (const name of LAYERS) {
167
+ if (!items.some((i) => planeOf.get(i.id) === name) && !(name === "body" && drawBackground && slide.background)) continue;
168
+ const canvas = document.createElement("canvas");
169
+ const tex = new THREE.CanvasTexture(canvas);
170
+ tex.colorSpace = THREE.SRGBColorSpace;
171
+ tex.anisotropy = 4;
172
+ const mat = new THREE.MeshBasicMaterial({ map: tex, transparent: true, toneMapped: false, depthWrite: false, side: THREE.DoubleSide, fog: false });
173
+ const mesh = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), mat);
174
+ mesh.renderOrder = 3 + order.indexOf(name);
175
+ mesh.userData.layer = name;
176
+ root.add(mesh);
177
+ meshes.set(name, mesh);
178
+ canvases.set(name, canvas);
179
+ }
180
+ let glass: THREE_NS.Mesh | undefined;
181
+ if (mode === "panel") {
182
+ glass = new THREE.Mesh(
183
+ new THREE.PlaneGeometry(1, 1),
184
+ new THREE.MeshPhysicalMaterial({
185
+ color: ctx.palette.card,
186
+ transparent: true,
187
+ opacity: panel.material === "matte" ? 0.92 : 0.55,
188
+ roughness: panel.material === "matte" ? 0.8 : 0.15,
189
+ transmission: panel.material === "matte" ? 0 : 0.4,
190
+ thickness: 0.2,
191
+ depthWrite: false,
192
+ }),
193
+ );
194
+ glass.renderOrder = 2;
195
+ root.add(glass);
196
+ }
197
+
198
+ // ── painting ────────────────────────────────────────────────────────────────
199
+ const image = (asset: string | undefined): CanvasImageSource | undefined => {
200
+ if (!asset || !ctx.assets.has(asset)) return undefined;
201
+ return ctx.assets.get(asset) as CanvasImageSource;
202
+ };
203
+
204
+ function withTransform(g: CanvasRenderingContext2D, item: LayoutItem, k: number, draw: (w: number, h: number) => void): void {
205
+ const r = item.rect;
206
+ g.save();
207
+ g.translate((r.x + r.w / 2) * k, (r.y + r.h / 2) * k);
208
+ if (item.rotation) g.rotate((item.rotation * Math.PI) / 180);
209
+ g.scale(item.flipH ? -1 : 1, item.flipV ? -1 : 1);
210
+ g.translate((-r.w / 2) * k, (-r.h / 2) * k);
211
+ draw(r.w * k, r.h * k);
212
+ g.restore();
213
+ }
214
+
215
+ function paintRect(g: CanvasRenderingContext2D, item: RectItem, k: number): void {
216
+ withTransform(g, item, k, (w, h) => {
217
+ g.beginPath();
218
+ if (item.preset === "ellipse") g.ellipse(w / 2, h / 2, w / 2, h / 2, 0, 0, Math.PI * 2);
219
+ else if (item.preset === "roundRect") g.roundRect(0, 0, w, h, Math.min(w, h) / 6);
220
+ else if (item.preset === "line") {
221
+ g.moveTo(0, 0);
222
+ g.lineTo(w, h);
223
+ } else g.rect(0, 0, w, h);
224
+ if (item.fill && item.alpha > 0 && item.preset !== "line") {
225
+ g.globalAlpha = item.alpha;
226
+ g.fillStyle = item.fill;
227
+ g.fill();
228
+ g.globalAlpha = 1;
229
+ }
230
+ if (item.line) {
231
+ g.strokeStyle = item.line.color;
232
+ g.lineWidth = Math.max(1, item.line.width * k);
233
+ g.stroke();
234
+ }
235
+ });
236
+ }
237
+
238
+ function paintImg(g: CanvasRenderingContext2D, item: ImgItem, k: number): void {
239
+ const src = image(item.svgAsset) ?? image(item.asset);
240
+ if (!src) return;
241
+ const sw = (src as HTMLImageElement).naturalWidth || (src as ImageBitmap).width || 1;
242
+ const sh = (src as HTMLImageElement).naturalHeight || (src as ImageBitmap).height || 1;
243
+ // Crop fractions apply to the raster; an SVG alternative draws whole.
244
+ const c = item.svgAsset && src === image(item.svgAsset) ? { l: 0, t: 0, r: 0, b: 0 } : item.crop;
245
+ withTransform(g, item, k, (w, h) => {
246
+ g.drawImage(src, c.l * sw, c.t * sh, sw * (1 - c.l - c.r), sh * (1 - c.t - c.b), 0, 0, w, h);
247
+ });
248
+ }
249
+
250
+ function paintFallback(g: CanvasRenderingContext2D, item: FallbackItem, k: number): void {
251
+ const src = image(item.asset);
252
+ if (src) {
253
+ // The crop was taken at the rotated bounding rect: draw it upright there.
254
+ const a = (item.rotation * Math.PI) / 180;
255
+ const w = Math.abs(item.rect.w * Math.cos(a)) + Math.abs(item.rect.h * Math.sin(a));
256
+ const h = Math.abs(item.rect.w * Math.sin(a)) + Math.abs(item.rect.h * Math.cos(a));
257
+ const cx = item.rect.x + item.rect.w / 2;
258
+ const cy = item.rect.y + item.rect.h / 2;
259
+ g.drawImage(src, (cx - w / 2) * k, (cy - h / 2) * k, w * k, h * k);
260
+ return;
261
+ }
262
+ withTransform(g, item, k, (w, h) => {
263
+ g.setLineDash([8, 6]);
264
+ g.strokeStyle = ctx.palette.accent;
265
+ g.lineWidth = 2;
266
+ g.strokeRect(1, 1, w - 2, h - 2);
267
+ g.setLineDash([]);
268
+ g.fillStyle = ctx.palette.text;
269
+ g.font = `400 ${Math.max(10, Math.min(28, h / 6))}px "Poppins", sans-serif`;
270
+ g.textAlign = "center";
271
+ g.textBaseline = "middle";
272
+ g.fillText(item.construct, w / 2, h / 2);
273
+ });
274
+ }
275
+
276
+ function paragraphsOf(item: TextItem): LayoutParagraph[] {
277
+ const replacement = retext[item.id];
278
+ if (replacement === undefined) return item.paragraphs;
279
+ const first = item.paragraphs.find((p) => p.runs.length) ?? item.paragraphs[0];
280
+ const run = first?.runs[0];
281
+ if (!first || !run) return item.paragraphs;
282
+ return [{ ...first, runs: [{ ...run, text: replacement }] }];
283
+ }
284
+
285
+ function layoutText(g: CanvasRenderingContext2D, item: TextItem, k: number, boxW: number): Line[] {
286
+ const lines: Line[] = [];
287
+ const paras = paragraphsOf(item);
288
+ let lastSize = 18;
289
+ paras.forEach((p, pi) => {
290
+ const bulletW = p.bullet ? (p.runs[0]?.size ?? lastSize) * 0.9 * k : 0;
291
+ const indent = p.level * 0.5 * (p.runs[0]?.size ?? lastSize) * k + bulletW;
292
+ const tokens: Token[] = [];
293
+ for (const run of p.runs) {
294
+ const px = run.size * k;
295
+ lastSize = run.size;
296
+ const font = cssFont(run, px, familyFor(run.font));
297
+ for (const piece of run.text.split(/(\n|\s+)/)) {
298
+ if (!piece) continue;
299
+ g.font = font;
300
+ tokens.push({
301
+ text: piece,
302
+ font,
303
+ color: run.color,
304
+ size: px,
305
+ underline: run.underline,
306
+ width: piece === "\n" ? 0 : g.measureText(piece).width,
307
+ space: /^\s+$/.test(piece) && piece !== "\n",
308
+ newline: piece === "\n",
309
+ });
310
+ }
311
+ }
312
+ const height = (sz: number) => sz * 1.2 * p.lineSpacing;
313
+ const before = pi === 0 ? 0 : p.spaceBefore * k;
314
+ let cur: Line = { tokens: [], width: 0, height: 0, ascent: 0, align: p.align, indent };
315
+ const push = (): void => {
316
+ while (cur.tokens.length && cur.tokens[cur.tokens.length - 1].space) cur.width -= (cur.tokens.pop() as Token).width;
317
+ const maxSize = Math.max(lastSize * k, ...cur.tokens.map((t) => t.size));
318
+ cur.height = height(maxSize);
319
+ cur.ascent = maxSize * 0.95;
320
+ lines.push(cur);
321
+ cur = { tokens: [], width: 0, height: 0, ascent: 0, align: p.align, indent };
322
+ };
323
+ const firstLine = lines.length;
324
+ for (const t of tokens) {
325
+ if (t.newline) {
326
+ push();
327
+ continue;
328
+ }
329
+ if (cur.tokens.length && !t.space && cur.width + t.width > boxW - indent) push();
330
+ if (!cur.tokens.length && t.space) continue;
331
+ cur.tokens.push(t);
332
+ cur.width += t.width;
333
+ }
334
+ push();
335
+ if (lines[firstLine]) {
336
+ lines[firstLine].height += before;
337
+ lines[firstLine].ascent += before;
338
+ if (p.bullet) (lines[firstLine] as Line & { bullet?: { char: string; token?: Token } }).bullet = { char: p.bullet, token: tokens[0] };
339
+ }
340
+ const last = lines[lines.length - 1];
341
+ if (last) last.height += p.spaceAfter * k;
342
+ });
343
+ return lines;
344
+ }
345
+
346
+ function paintText(g: CanvasRenderingContext2D, item: TextItem, k: number): void {
347
+ const r = item.rect;
348
+ const extra = Number(widen[item.id] ?? 0);
349
+ const ins = item.insets;
350
+ // PowerPoint never mirrors text: `flipH` leaves it alone and `flipV` turns it upside
351
+ // down (180°). Vertical text reads along the box's HEIGHT, top-down (`vert`) or
352
+ // bottom-up (`vert270`), so its layout frame has the box's width and height swapped.
353
+ const vertical = item.vertical ? (item.textRotation ?? 90) : 0;
354
+ const turn = vertical + (item.flipV ? 180 : 0);
355
+ const frameW = vertical ? r.h : r.w;
356
+ const frameH = vertical ? r.w : r.h;
357
+ const boxW = Math.max(1, (frameW + extra - ins.l - ins.r) * k);
358
+ const boxH = (frameH - ins.t - ins.b) * k;
359
+ const lines = layoutText(g, item, k, boxW);
360
+ const total = lines.reduce((a, l) => a + l.height, 0);
361
+ const top = item.anchor === "b" ? boxH - total : item.anchor === "ctr" ? (boxH - total) / 2 : 0;
362
+ g.save();
363
+ // Rotate about the SHAPE's centre by the shape rotation plus the text turn, then
364
+ // step to the top-left of the text area in the (possibly swapped) frame.
365
+ g.translate((r.x + r.w / 2) * k, (r.y + r.h / 2) * k);
366
+ const angle = item.rotation + turn;
367
+ if (angle) g.rotate((angle * Math.PI) / 180);
368
+ g.translate((-frameW / 2 + ins.l) * k, (-frameH / 2 + ins.t) * k);
369
+ g.textBaseline = "alphabetic";
370
+ let y = top;
371
+ for (const line of lines) {
372
+ const base = y + line.ascent;
373
+ const free = boxW - line.indent - line.width;
374
+ let x = line.indent + (line.align === "ctr" ? free / 2 : line.align === "r" ? free : 0);
375
+ const bullet = (line as Line & { bullet?: { char: string; token?: Token } }).bullet;
376
+ if (bullet?.token) {
377
+ g.font = bullet.token.font;
378
+ g.fillStyle = bullet.token.color;
379
+ g.fillText(bullet.char, line.indent - bullet.token.size * 0.9, base);
380
+ }
381
+ for (const t of line.tokens) {
382
+ g.font = t.font;
383
+ if (halo > 0 && !t.space) {
384
+ g.save();
385
+ g.shadowColor = haloColor;
386
+ g.shadowBlur = t.size * 0.5;
387
+ g.globalAlpha = halo;
388
+ g.fillStyle = haloColor;
389
+ g.fillText(t.text, x, base);
390
+ g.restore();
391
+ }
392
+ g.fillStyle = t.color;
393
+ g.fillText(t.text, x, base);
394
+ if (t.underline) g.fillRect(x, base + t.size * 0.1, t.width, Math.max(1, t.size * 0.06));
395
+ x += t.width;
396
+ }
397
+ y += line.height;
398
+ }
399
+ g.restore();
400
+ }
401
+
402
+ let paintedFor = "";
403
+ function paint(frameH: number): void {
404
+ const key = String(Math.round(frameH));
405
+ if (key === paintedFor) return;
406
+ paintedFor = key;
407
+ const height = Math.min(MAX_CANVAS * (size.h / size.w), Math.max(64, frameH * tier));
408
+ const k = height / size.h;
409
+ for (const [name, canvas] of canvases) {
410
+ canvas.width = Math.round(size.w * k);
411
+ canvas.height = Math.round(size.h * k);
412
+ const g = canvas.getContext("2d") as CanvasRenderingContext2D;
413
+ g.clearRect(0, 0, canvas.width, canvas.height);
414
+ if (name === "body" && drawBackground && slide.background) {
415
+ if (slide.background.color) {
416
+ g.fillStyle = slide.background.color;
417
+ g.fillRect(0, 0, canvas.width, canvas.height);
418
+ }
419
+ const bg = image(slide.background.asset);
420
+ if (bg) g.drawImage(bg, 0, 0, canvas.width, canvas.height);
421
+ }
422
+ for (const item of items) {
423
+ if (planeOf.get(item.id) !== name) continue;
424
+ if (item.kind === "rect") paintRect(g, item, k);
425
+ else if (item.kind === "img") paintImg(g, item, k);
426
+ else if (item.kind === "fallback") paintFallback(g, item, k);
427
+ else if (!underCrop(item)) paintText(g, item, k);
428
+ }
429
+ const mat = meshes.get(name)?.material as THREE_NS.MeshBasicMaterial;
430
+ if (mat.map) mat.map.needsUpdate = true;
431
+ }
432
+ }
433
+
434
+ // ── placement ──────────────────────────────────────────────────────────────
435
+ const maps = new Map<LayerName, PlaneMap>();
436
+ let placedFor = "";
437
+ const basisFor = (): Basis => {
438
+ const settled = poseBasis(THREE, view);
439
+ return mode === "screen" ? cameraBasis(THREE, settled.distance) : settled;
440
+ };
441
+
442
+ function place(): void {
443
+ const { width, height } = view.viewport();
444
+ const key = `${width}x${height}`;
445
+ if (key === placedFor) return;
446
+ placedFor = key;
447
+ const basis = basisFor();
448
+ for (const [name, mesh] of meshes) {
449
+ const map = planeMap(THREE, basis, view.pose.fov, width, height, size, depths[name]);
450
+ maps.set(name, map);
451
+ mesh.position.copy(map.centre);
452
+ mesh.quaternion.copy(map.quaternion);
453
+ mesh.scale.set(map.width, map.height, 1);
454
+ }
455
+ if (glass) {
456
+ const map = planeMap(THREE, basis, view.pose.fov, width, height, size, depths.body - 0.05);
457
+ glass.position.copy(map.centre);
458
+ glass.quaternion.copy(map.quaternion);
459
+ glass.scale.set(map.width * 1.04, map.height * 1.06, 1);
460
+ }
461
+ if (tilt) {
462
+ // Tilt the whole panel about its horizontal axis through the body plane.
463
+ const pivot = planeMap(THREE, basis, view.pose.fov, width, height, size, depths.body).centre;
464
+ const q = new THREE.Quaternion().setFromAxisAngle(basis.right, tilt);
465
+ for (const o of root.children) {
466
+ o.position.sub(pivot).applyQuaternion(q).add(pivot);
467
+ o.quaternion.premultiply(q);
468
+ }
469
+ }
470
+ const frameH = Math.min(height, width * (size.h / size.w));
471
+ paint(frameH);
472
+ }
473
+
474
+ const parentInverse = new THREE.Matrix4();
475
+ /** Camera-pinned mode: re-derive the root from the live camera each frame. */
476
+ function pin(): void {
477
+ if (mode !== "screen" || !root.parent) return;
478
+ root.matrixAutoUpdate = false;
479
+ view.camera.updateMatrixWorld();
480
+ root.parent.updateMatrixWorld();
481
+ parentInverse.copy(root.parent.matrixWorld).invert();
482
+ root.matrix.copy(parentInverse).multiply(view.camera.matrixWorld);
483
+ root.matrixWorldNeedsUpdate = true;
484
+ }
485
+
486
+ place();
487
+
488
+ // ── measurement ────────────────────────────────────────────────────────────
489
+ function corners(item: LayoutItem, extraW = 0): Array<[number, number]> {
490
+ const r = item.rect;
491
+ const w = r.w + extraW;
492
+ const cx = r.x + w / 2;
493
+ const cy = r.y + r.h / 2;
494
+ const a = (item.rotation * Math.PI) / 180;
495
+ return [
496
+ [-w / 2, -r.h / 2],
497
+ [w / 2, -r.h / 2],
498
+ [w / 2, r.h / 2],
499
+ [-w / 2, r.h / 2],
500
+ ].map(([x, y]) => [cx + x * Math.cos(a) - y * Math.sin(a), cy + x * Math.sin(a) + y * Math.cos(a)]);
501
+ }
502
+
503
+ function projected(item: LayoutItem, camera: THREE_NS.Camera, width: number, height: number, extraW = 0) {
504
+ const mesh = meshes.get(planeOf.get(item.id) as LayerName);
505
+ if (!mesh) return undefined;
506
+ mesh.updateWorldMatrix(true, false);
507
+ const pts = corners(item, extraW).map(([sx, sy]) => new THREE.Vector3(sx / size.w - 0.5, 0.5 - sy / size.h, 0).applyMatrix4(mesh.matrixWorld));
508
+ return projectPoints(pts, camera, width, height);
509
+ }
510
+
511
+ function measure(camera: unknown, width: number, height: number): FxMeasure[] {
512
+ place();
513
+ pin();
514
+ const cam = camera as THREE_NS.Camera;
515
+ const out: FxMeasure[] = [];
516
+ for (const item of textItems) {
517
+ const extra = Number(widen[item.id] ?? 0);
518
+ const rect = projected(item, cam, width, height, extra);
519
+ if (!rect) continue;
520
+ const paras = paragraphsOf(item);
521
+ const text = paras.map((p) => p.runs.map((r) => r.text).join("")).join("\n");
522
+ const run = paras.find((p) => p.runs.length)?.runs[0];
523
+ const k = rect.h / Math.max(1e-6, item.rect.h);
524
+ out.push({ id: item.id, text, rect, capHeight: (run?.size ?? 0) * CAP_RATIO * k, ...(run ? { color: run.color } : {}) });
525
+ }
526
+ return out;
527
+ }
528
+
529
+ return {
530
+ object: root,
531
+ tick: () => {
532
+ place();
533
+ pin();
534
+ },
535
+ measure,
536
+ fontFallbacks: () => [...fallbacks],
537
+ // Probe for tests: every drawn item's projected rect at the current camera.
538
+ debug: () => {
539
+ const { width, height } = view.viewport();
540
+ return {
541
+ mode,
542
+ frame: maps.get("body") ? { width: maps.get("body")?.width, height: maps.get("body")?.height } : null,
543
+ items: items.map((i) => ({ id: i.id, kind: i.kind, layer: planeOf.get(i.id), rect: projected(i, view.camera, width, height, Number(widen[i.id] ?? 0)) })),
544
+ };
545
+ },
546
+ dispose: () => {
547
+ for (const mesh of meshes.values()) {
548
+ mesh.geometry.dispose();
549
+ const mat = mesh.material as THREE_NS.MeshBasicMaterial;
550
+ mat.map?.dispose();
551
+ mat.dispose();
552
+ }
553
+ glass?.geometry.dispose();
554
+ (glass?.material as THREE_NS.Material | undefined)?.dispose();
555
+ },
556
+ } as FxHandle;
557
+ };