@pixerate/flair 0.28.0 → 0.29.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 (59) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +48 -6
  3. package/dist/catalog/index.d.ts +11 -6
  4. package/dist/catalog/index.js +1 -1
  5. package/dist/{chunk-4LKAPRFM.js → chunk-6GFOLHCT.js} +920 -34
  6. package/dist/chunk-6GFOLHCT.js.map +1 -0
  7. package/dist/{chunk-JL6TI6II.js → chunk-7KYQ4R76.js} +2 -2
  8. package/dist/chunk-7KYQ4R76.js.map +1 -0
  9. package/dist/{chunk-STKEKXCK.js → chunk-AUH3PEFW.js} +2 -2
  10. package/dist/{chunk-PFGGPIMT.js → chunk-DA4UUSDO.js} +58 -3
  11. package/dist/chunk-DA4UUSDO.js.map +1 -0
  12. package/dist/{chunk-RDU63CDO.js → chunk-HDYBY3PQ.js} +380 -1
  13. package/dist/chunk-HDYBY3PQ.js.map +1 -0
  14. package/dist/{chunk-VLQLRKGW.js → chunk-KZYZX3V5.js} +260 -33
  15. package/dist/chunk-KZYZX3V5.js.map +1 -0
  16. package/dist/{chunk-GXP4YLAP.js → chunk-MBKNTXQX.js} +9 -9
  17. package/dist/chunk-MBKNTXQX.js.map +1 -0
  18. package/dist/{chunk-H6VDFBIO.js → chunk-SMR2MJXB.js} +156 -5
  19. package/dist/chunk-SMR2MJXB.js.map +1 -0
  20. package/dist/{chunk-YBGRXVAE.js → chunk-X3C2VFTM.js} +3 -3
  21. package/dist/{chunk-CK6EV37I.js → chunk-ZULFHADW.js} +69 -6
  22. package/dist/chunk-ZULFHADW.js.map +1 -0
  23. package/dist/cli.js +6 -6
  24. package/dist/editor/index.d.ts +3 -3
  25. package/dist/editor/index.js +3 -3
  26. package/dist/{effect-GGP66JI6.js → effect-YBWDNIYG.js} +10 -10
  27. package/dist/embed/index.d.ts +36 -8
  28. package/dist/embed/index.js +5 -5
  29. package/dist/{frames-VEcqa40g.d.ts → frames-CGJudAbu.d.ts} +11 -1
  30. package/dist/index.d.ts +69 -6
  31. package/dist/index.js +35 -7
  32. package/dist/index.js.map +1 -1
  33. package/dist/node.d.ts +4 -4
  34. package/dist/node.js +9 -9
  35. package/dist/react/index.d.ts +4 -4
  36. package/dist/react/index.js +7 -7
  37. package/dist/react/index.js.map +1 -1
  38. package/dist/{recorder-CDPPTJMG.js → recorder-TYMEZHOT.js} +3 -3
  39. package/dist/{renderer-teaa98RE.d.ts → renderer-tk1nbVkW.d.ts} +252 -2
  40. package/dist/svelte/index.d.ts +4 -4
  41. package/dist/svelte/index.js +7 -7
  42. package/dist/svelte/index.js.map +1 -1
  43. package/dist/{svg-BhRboN9q.d.ts → svg-DaKRPA9v.d.ts} +39 -7
  44. package/dist/{types-DUOMxZaq.d.ts → types-wh28fXW4.d.ts} +2 -2
  45. package/dist/vector/index.d.ts +2 -2
  46. package/dist/vector/index.js +5 -3
  47. package/package.json +1 -1
  48. package/dist/chunk-4LKAPRFM.js.map +0 -1
  49. package/dist/chunk-CK6EV37I.js.map +0 -1
  50. package/dist/chunk-GXP4YLAP.js.map +0 -1
  51. package/dist/chunk-H6VDFBIO.js.map +0 -1
  52. package/dist/chunk-JL6TI6II.js.map +0 -1
  53. package/dist/chunk-PFGGPIMT.js.map +0 -1
  54. package/dist/chunk-RDU63CDO.js.map +0 -1
  55. package/dist/chunk-VLQLRKGW.js.map +0 -1
  56. /package/dist/{chunk-STKEKXCK.js.map → chunk-AUH3PEFW.js.map} +0 -0
  57. /package/dist/{chunk-YBGRXVAE.js.map → chunk-X3C2VFTM.js.map} +0 -0
  58. /package/dist/{effect-GGP66JI6.js.map → effect-YBWDNIYG.js.map} +0 -0
  59. /package/dist/{recorder-CDPPTJMG.js.map → recorder-TYMEZHOT.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/shader/thumbnails.ts","../src/shader/gif.ts","../src/shader/standalone.ts","../src/shader/blend.ts","../src/scene/validate.ts","../src/scene/standalone.ts"],"sourcesContent":["import { imageUrls, parseControls, type ControlDef, type ControlValue } from \"./controls.js\";\nimport {\n compileShader,\n createContext,\n drawFrame,\n resetGlCaches,\n type CompiledShader,\n} from \"./program.js\";\nimport { TextureCache } from \"./textures.js\";\n\n/** Controls a registered thumbnail. */\nexport interface ThumbnailHandle {\n /** Shows another source or other values. A new source is recompiled; new values only redraw. */\n update(source: string, values?: Record<string, ControlValue>): void;\n /** With reduced motion, a hovered thumbnail animates and the others hold a still frame. */\n setHovered(hovered: boolean): void;\n /** Stops drawing into the canvas and frees its program. */\n dispose(): void;\n}\n\nexport interface ThumbnailPoolOptions {\n /** Size of the shared render canvas (default 480 × 270). Thumbnails are drawn at most this large, then scaled. */\n renderWidth?: number;\n renderHeight?: number;\n /** Animation rate (default 30). */\n fps?: number;\n /** `iTime` of the still frame shown with reduced motion or hover-only mode (default 2). */\n stillTime?: number;\n /** Hold still frames unless hovered (default: the `prefers-reduced-motion` media query). */\n reducedMotion?: boolean;\n /** Only animate hovered thumbnails, holding `stillTime` on all others (default false). */\n hoverOnly?: boolean;\n /** Animation policy: `\"always\"` (animate all visible), `\"hover\"` (only animate hovered), or `\"reduced-motion\"` (default: follow `reducedMotion` / `prefers-reduced-motion`). */\n animateMode?: \"always\" | \"hover\" | \"reduced-motion\";\n /** Enable a transparent WebGL drawing buffer and clear each thumbnail canvas before copying (default false). */\n alpha?: boolean;\n}\n\ninterface Entry {\n canvas: HTMLCanvasElement;\n ctx: CanvasRenderingContext2D;\n source: string;\n values?: Record<string, ControlValue>;\n controls: ControlDef[];\n shader: CompiledShader | null;\n failed: boolean;\n dirty: boolean;\n visible: boolean;\n hovered: boolean;\n onStatus?: (ok: boolean) => void;\n}\n\n/**\n * Animated thumbnails from a single WebGL context. Browsers cap live WebGL\n * contexts (about 16), so a gallery cannot give every card its own: the pool\n * renders each visible thumbnail in turn on one hidden canvas and copies the\n * frame into the thumbnail's own 2D canvas, cropped to its aspect ratio like\n * `object-fit: cover`. Thumbnails off screen (by `IntersectionObserver`) cost\n * nothing, and programs compile once per source.\n *\n * Nothing is created until the first `register`.\n */\nexport class ThumbnailPool {\n private readonly renderWidth: number;\n private readonly renderHeight: number;\n private readonly interval: number;\n private readonly fps: number;\n private readonly stillTime: number;\n private readonly reducedMotion: boolean;\n private readonly alpha: boolean;\n private readonly entries = new Set<Entry>();\n private readonly byCanvas = new WeakMap<Element, Entry>();\n private observer: IntersectionObserver | null | undefined;\n private glCanvas: HTMLCanvasElement | null = null;\n private gl: WebGL2RenderingContext | null = null;\n private textures: TextureCache | null = null;\n private raf = 0;\n private last = 0;\n private start: number | null = null;\n\n constructor(options: ThumbnailPoolOptions = {}) {\n this.renderWidth = options.renderWidth ?? 480;\n this.renderHeight = options.renderHeight ?? 270;\n this.fps = options.fps ?? 30;\n this.interval = 1000 / this.fps;\n this.stillTime = options.stillTime ?? 2;\n this.alpha = Boolean(options.alpha);\n const mode = options.animateMode ?? (options.hoverOnly ? \"hover\" : \"reduced-motion\");\n this.reducedMotion =\n mode === \"hover\"\n ? true\n : mode === \"always\"\n ? false\n : (options.reducedMotion ??\n (typeof matchMedia !== \"undefined\" &&\n matchMedia(\"(prefers-reduced-motion: reduce)\").matches));\n }\n\n /**\n * Starts drawing `source` into `canvas`, which should be sized with CSS; its\n * drawing buffer follows its CSS size and the device pixel ratio (up to 2).\n * `onStatus` hears whether the source compiled (and `false` without WebGL2).\n */\n register(\n canvas: HTMLCanvasElement,\n source: string,\n values?: Record<string, ControlValue>,\n onStatus?: (ok: boolean) => void,\n ): ThumbnailHandle {\n const observer = this.intersection();\n const entry: Entry = {\n canvas,\n ctx: canvas.getContext(\"2d\")!,\n source,\n values,\n controls: [],\n shader: null,\n failed: false,\n dirty: true,\n visible: observer === null,\n hovered: false,\n onStatus,\n };\n this.entries.add(entry);\n this.byCanvas.set(canvas, entry);\n observer?.observe(canvas);\n if (!this.context()) onStatus?.(false);\n this.schedule();\n return {\n update: (nextSource, nextValues) => {\n if (nextSource !== entry.source) {\n this.release(entry);\n entry.source = nextSource;\n entry.failed = false;\n }\n entry.values = nextValues;\n entry.dirty = true;\n this.retainTextures();\n this.schedule();\n },\n setHovered: (hovered) => {\n entry.hovered = hovered;\n entry.dirty = true;\n this.schedule();\n },\n dispose: () => {\n observer?.unobserve(canvas);\n this.entries.delete(entry);\n this.byCanvas.delete(canvas);\n this.release(entry);\n this.retainTextures();\n },\n };\n }\n\n /** The number of registered thumbnails. */\n get size(): number {\n return this.entries.size;\n }\n\n private intersection(): IntersectionObserver | null {\n if (this.observer !== undefined) return this.observer;\n this.observer =\n typeof IntersectionObserver === \"undefined\"\n ? null\n : new IntersectionObserver(\n (records) => {\n for (const r of records) {\n const entry = this.byCanvas.get(r.target);\n if (!entry) continue;\n entry.visible = r.isIntersecting;\n if (entry.visible) entry.dirty = true;\n }\n this.schedule();\n },\n { rootMargin: \"100px\" },\n );\n return this.observer;\n }\n\n private context(): WebGL2RenderingContext | null {\n if (this.gl && !this.gl.isContextLost()) return this.gl;\n const canvas = document.createElement(\"canvas\");\n canvas.width = this.renderWidth;\n canvas.height = this.renderHeight;\n canvas.addEventListener(\"webglcontextlost\", (e) => {\n e.preventDefault();\n for (const entry of this.entries) entry.shader = null;\n this.textures?.dispose();\n });\n canvas.addEventListener(\"webglcontextrestored\", () => {\n resetGlCaches();\n if (this.gl) this.textures = this.textureCache(this.gl);\n for (const entry of this.entries) entry.dirty = true;\n this.schedule();\n });\n resetGlCaches();\n this.glCanvas = canvas;\n this.gl = createContext(canvas, false, this.alpha);\n this.textures = this.gl && this.textureCache(this.gl);\n return this.gl;\n }\n\n private textureCache(gl: WebGL2RenderingContext): TextureCache {\n return new TextureCache(gl, (url) => {\n // A thumbnail showing the image redraws with it.\n for (const entry of this.entries) {\n if (imageUrls(entry.controls, entry.values).includes(url)) entry.dirty = true;\n }\n this.schedule();\n });\n }\n\n /** Frees the textures no thumbnail shows any more. */\n private retainTextures() {\n this.textures?.retain(\n [...this.entries].flatMap((entry) => imageUrls(entry.controls, entry.values)),\n );\n }\n\n private release(entry: Entry) {\n if (entry.shader) this.gl?.deleteProgram(entry.shader.program);\n entry.shader = null;\n }\n\n private compile(entry: Entry, gl: WebGL2RenderingContext) {\n entry.controls = parseControls(entry.source);\n const result = compileShader(gl, entry.source, entry.controls);\n entry.shader = result.ok ? result.shader : null;\n entry.failed = !result.ok;\n entry.onStatus?.(result.ok);\n }\n\n private renderEntry(entry: Entry, gl: WebGL2RenderingContext, time: number) {\n if (!entry.shader && !entry.failed) this.compile(entry, gl);\n if (!entry.shader) return;\n sizeCanvas(entry.canvas);\n // Fill the thumbnail the way `object-fit: cover` would, at its aspect ratio.\n const aspect = entry.canvas.width / entry.canvas.height;\n const w = Math.min(this.renderWidth, Math.round(this.renderHeight * aspect));\n const h = Math.min(this.renderHeight, Math.round(w / aspect));\n drawFrame(\n gl,\n entry.shader,\n entry.controls,\n entry.values,\n {\n width: w,\n height: h,\n time,\n delta: this.interval / 1000,\n frame: Math.floor(time * this.fps),\n mouse: [0, 0, 0, 0],\n // A hovered thumbnail is pointed at in its middle, for effects that answer hovers.\n pointer: [w / 2, h / 2, entry.hovered ? 1 : 0, 0],\n },\n this.textures ?? undefined,\n );\n // The GL canvas's drawing buffer is valid until this task ends; copy it now.\n // WebGL draws from the bottom left, so the frame sits at the bottom of the canvas.\n if (this.alpha) {\n entry.ctx.clearRect(0, 0, entry.canvas.width, entry.canvas.height);\n }\n entry.ctx.drawImage(\n this.glCanvas!,\n 0,\n this.renderHeight - h,\n w,\n h,\n 0,\n 0,\n entry.canvas.width,\n entry.canvas.height,\n );\n entry.dirty = false;\n }\n\n private schedule() {\n if (!this.raf && this.entries.size) this.raf = requestAnimationFrame(this.tick);\n }\n\n private tick = (now: number) => {\n this.raf = 0;\n const gl = this.context();\n if (!gl) return;\n this.start ??= now;\n const animate = now - this.last >= this.interval;\n const time = (now - this.start) / 1000;\n let keepGoing = false;\n // Compiling is the slow part, so a row of thumbnails scrolling into view compiles one per frame.\n let compiles = 1;\n for (const entry of this.entries) {\n if (!entry.visible) continue;\n if (!entry.shader && !entry.failed) {\n if (!compiles) {\n keepGoing = true;\n continue;\n }\n compiles--;\n }\n const moving = !this.reducedMotion || entry.hovered;\n if (entry.dirty || (moving && animate)) {\n this.renderEntry(entry, gl, moving ? time : this.stillTime);\n }\n if (moving && entry.shader) keepGoing = true;\n }\n if (animate) this.last = now;\n if (keepGoing) this.schedule();\n };\n}\n\nfunction sizeCanvas(canvas: HTMLCanvasElement) {\n // The layout size, not the bounding box: a rotated or scaled canvas keeps its own proportions.\n const ratio = Math.min(window.devicePixelRatio || 1, 2);\n const w = Math.max(1, Math.round(canvas.clientWidth * ratio));\n const h = Math.max(1, Math.round(canvas.clientHeight * ratio));\n if (canvas.width !== w || canvas.height !== h) {\n canvas.width = w;\n canvas.height = h;\n }\n}\n\nlet shared: ThumbnailPool | null = null;\n\n/** The pool `registerThumbnail` uses, created on first use. */\nexport function sharedThumbnailPool(): ThumbnailPool {\n shared ??= new ThumbnailPool();\n return shared;\n}\n\n/** Registers a thumbnail with the shared pool. See {@link ThumbnailPool.register}. */\nexport function registerThumbnail(\n canvas: HTMLCanvasElement,\n source: string,\n values?: Record<string, ControlValue>,\n onStatus?: (ok: boolean) => void,\n): ThumbnailHandle {\n return sharedThumbnailPool().register(canvas, source, values, onStatus);\n}\n","// gifenc ships without types. The reference (not an import) brings them along when a host\n// type-checks these sources through the `workspace` condition.\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// <reference path=\"./gifenc.d.ts\" />\nimport type { ControlValue } from \"./controls.js\";\nimport { ShaderFrames } from \"./frames.js\";\n\nexport interface GifOptions {\n source: string;\n values?: Record<string, ControlValue>;\n width: number;\n height: number;\n /** Frames per second. GIF delays are whole hundredths of a second, so 10, 20, 25 and 50 play back exactly. */\n fps: number;\n /** Seconds of animation to record. */\n duration: number;\n /** `iTime` of the first frame (default 0). */\n start?: number;\n /** Called after each frame with the frames done and the total. */\n onProgress?: (done: number, total: number) => void;\n /** Aborting rejects with an `AbortError` `DOMException`. */\n signal?: AbortSignal;\n}\n\n/** Lets the page repaint between frames so progress shows and Cancel works. */\nconst yieldToBrowser = () => new Promise<void>((resolve) => setTimeout(resolve, 0));\n\n/**\n * Records a shader as an animated GIF that loops forever. Frames are rendered\n * off screen at exact time steps (`start + i / fps`), so the result is smooth\n * whatever the page's frame rate, and nothing on screen is disturbed. Each\n * frame gets its own 256-colour palette. The encoder,\n * [gifenc](https://github.com/mattdesl/gifenc), is loaded on first use.\n *\n * Image controls are loaded before the first frame. Rejects with a\n * `ShaderCompileError` when the source does not compile, and an\n * `ImageLoadError` when an image cannot be loaded.\n */\nexport async function recordGif(options: GifOptions): Promise<Blob> {\n const { source, values, width, height, fps, duration, start = 0, onProgress, signal } = options;\n const { GIFEncoder, quantize, applyPalette } = await import(\"gifenc\");\n\n const frames = new ShaderFrames({ source, values, width, height });\n try {\n await frames.ready();\n const total = Math.max(1, Math.round(duration * fps));\n const delay = 1000 / fps;\n const rgba = new Uint8Array(frames.width * frames.height * 4);\n const gif = GIFEncoder();\n\n for (let i = 0; i < total; i++) {\n if (signal?.aborted) throw new DOMException(\"Cancelled\", \"AbortError\");\n frames.render(start + i / fps, { frame: i, delta: 1 / fps });\n frames.readPixels(rgba);\n const palette = quantize(rgba, 256);\n gif.writeFrame(applyPalette(rgba, palette), frames.width, frames.height, {\n palette,\n delay,\n ...(i === 0 ? { repeat: 0 } : {}),\n });\n onProgress?.(i + 1, total);\n if (i % 2 === 1) await yieldToBrowser();\n }\n\n gif.finish();\n return new Blob([gif.bytes()], { type: \"image/gif\" });\n } finally {\n frames.dispose();\n }\n}\n","import { controlValue, parseControls, type ControlValue } from \"./controls.js\";\nimport { HOVER_SECONDS, MAX_CLICKS, MAX_TRAIL, TRAIL_SECONDS } from \"./pointer.js\";\nimport { VERTEX_SOURCE, wrapSource } from \"./program.js\";\nimport { SVG_EDGE } from \"./textures.js\";\n\nconst escapeHtml = (s: string) =>\n s.replace(/[&<>\"]/g, (c) => ({ \"&\": \"&amp;\", \"<\": \"&lt;\", \">\": \"&gt;\", '\"': \"&quot;\" })[c]!);\n\n/** JSON that is safe inside a `<script>`: a `</script>` or `<!--` in a shader comment cannot end it. */\nconst scriptJson = (value: unknown) => JSON.stringify(value).replace(/</g, \"\\\\u003c\");\n\nexport interface StandaloneOptions {\n /** The comment at the top of the script, saying where the page came from. */\n credit?: string;\n}\n\n/**\n * A self-contained HTML page that runs the shader full-window, with the\n * control values baked in. It has no dependencies and opens from disk. Like\n * the live preview, it feeds `iMouse` from pointer drags and caps the pixel\n * ratio at 2.\n *\n * Images are loaded by URL when the page opens: a `data:` URL travels with\n * the page, an `https:` one needs the network and CORS, and a `blob:` one\n * only lives as long as the page that made it. SVGs are sized to\n * {@link SVG_EDGE} pixels before they are decoded, as `loadImage` does.\n */\nexport function standaloneHtml(\n title: string,\n source: string,\n values?: Record<string, ControlValue>,\n options: StandaloneOptions = {},\n): string {\n const controls = parseControls(source).map((c) => ({\n name: c.name,\n type: c.type,\n value: controlValue(c, values),\n ...(c.texture ? { texture: c.texture } : {}),\n }));\n const credit = (options.credit ?? \"Exported with Flair.\").replace(/\\n/g, \" \");\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${escapeHtml(title)}</title>\n<style>html,body{margin:0;height:100%;background:#000}canvas{display:block;width:100%;height:100%}</style>\n</head>\n<body>\n<canvas id=\"c\"></canvas>\n<script>\n// ${credit.replace(/</g, \"\\\\u003c\")} Shadertoy-style fragment shader on WebGL2.\nconst VERTEX = ${scriptJson(VERTEX_SOURCE)};\nconst FRAGMENT = ${scriptJson(wrapSource(source))};\nconst CONTROLS = ${scriptJson(controls)};\nconst canvas = document.getElementById(\"c\");\nconst gl = canvas.getContext(\"webgl2\");\nif (!gl) document.body.textContent = \"WebGL2 is not available.\";\nfunction compile(type, src) {\n const s = gl.createShader(type);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));\n return s;\n}\nconst program = gl.createProgram();\ngl.attachShader(program, compile(gl.VERTEX_SHADER, VERTEX));\ngl.attachShader(program, compile(gl.FRAGMENT_SHADER, FRAGMENT));\ngl.linkProgram(program);\ngl.useProgram(program);\nconst u = (n) => gl.getUniformLocation(program, n);\nlet unit = 0;\n// An SVG decodes at its own, often icon, size: give it ${SVG_EDGE} px on its long edge (and a\n// viewBox, so the drawing scales) to keep it sharp.\nasync function sizedSvg(url) {\n const doc = new DOMParser().parseFromString(await (await fetch(url)).text(), \"image/svg+xml\");\n const svg = doc.documentElement;\n const len = (n) => { const m = (svg.getAttribute(n) || \"\").trim().match(/^([\\\\d.]+)(px)?$/); return m && +m[1] > 0 ? +m[1] : 0; };\n const box = (svg.getAttribute(\"viewBox\") || \"\").trim().split(/[\\\\s,]+/).map(Number);\n const hasBox = box.length === 4 && box[2] > 0 && box[3] > 0;\n const w = len(\"width\") || (hasBox ? box[2] : 300), h = len(\"height\") || (hasBox ? box[3] : 150);\n const scale = ${SVG_EDGE} / Math.max(w, h);\n if (!hasBox) svg.setAttribute(\"viewBox\", \"0 0 \" + w + \" \" + h);\n svg.setAttribute(\"width\", Math.max(1, Math.round(w * scale)));\n svg.setAttribute(\"height\", Math.max(1, Math.round(h * scale)));\n return URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(svg)], { type: \"image/svg+xml\" }));\n}\nfunction image(loc, url, texture) {\n const i = unit++, t = gl.createTexture();\n const bind = () => { gl.activeTexture(gl.TEXTURE0 + i); gl.bindTexture(gl.TEXTURE_2D, t); };\n const filter = { mipmap: gl.LINEAR_MIPMAP_LINEAR, linear: gl.LINEAR, nearest: gl.NEAREST }[texture.filter];\n const wrap = { repeat: gl.REPEAT, clamp: gl.CLAMP_TO_EDGE, mirror: gl.MIRRORED_REPEAT }[texture.wrap];\n bind();\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 0, 255]));\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.filter === \"nearest\" ? gl.NEAREST : gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);\n gl.uniform1i(loc, i);\n if (!url) return;\n const img = new Image();\n if (!/^(data|blob):/i.test(url)) img.crossOrigin = \"anonymous\";\n img.onload = () => {\n bind();\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);\n gl.generateMipmap(gl.TEXTURE_2D);\n };\n if (/^data:image\\\\/svg\\\\+xml[;,]/i.test(url) || /^(?!data:)[^?#]*\\\\.svg([?#]|$)/i.test(url)) {\n sizedSvg(url).then((src) => { img.src = src; }, () => {});\n } else img.src = url;\n}\nfor (const c of CONTROLS) {\n const loc = u(c.name);\n const v = c.value;\n if (c.type === \"float\") gl.uniform1f(loc, v);\n else if (c.type === \"int\" || c.type === \"bool\") gl.uniform1i(loc, Number(v));\n else if (c.type === \"sampler2D\") image(loc, v, c.texture);\n else gl[\"uniform\" + v.length + \"fv\"](loc, v);\n}\nlet mouse = [0, 0, 0, 0];\nconst px = (e) => { const r = canvas.getBoundingClientRect(); return [(e.clientX - r.left) * canvas.width / r.width, (r.bottom - e.clientY) * canvas.height / r.height]; };\ncanvas.addEventListener(\"pointerdown\", (e) => { const [x, y] = px(e); mouse = [x, y, x, y]; });\ncanvas.addEventListener(\"pointermove\", (e) => { if (e.buttons && mouse[2] > 0) { const [x, y] = px(e); mouse = [x, y, mouse[2], mouse[3]]; } });\naddEventListener(\"pointerup\", () => { if (mouse[2] > 0) mouse = [mouse[0], mouse[1], -mouse[2], -Math.abs(mouse[3])]; });\nlet start = performance.now(), last = start, frame = 0;\n// iPointer (where, how hovered, seconds pressed), iClicks (the latest clicks) and iTrail (where it has just been), newest first.\nconst seconds = () => (performance.now() - start) / 1000;\nlet at = [0, 0], over = false, hoverFrom = 0, hoverAt = -1e9, pressedAt = -1, releasedAt = -1, clicks = [], trail = [];\nconst hovered = (t) => { const k = Math.min(1, Math.max(0, (t - hoverAt) / ${HOVER_SECONDS})); return hoverFrom + ((over ? 1 : 0) - hoverFrom) * k * k * (3 - 2 * k); };\nconst hover = (on) => { const t = seconds(); hoverFrom = hovered(t); hoverAt = t; over = on; };\ncanvas.addEventListener(\"pointerenter\", (e) => { at = px(e); hover(true); toTrail(); });\ncanvas.addEventListener(\"pointerleave\", () => hover(false));\n// A trail point at most every ${TRAIL_SECONDS.toFixed(4)} s; moves in between update the newest.\nconst toTrail = () => { const t = seconds(); if (trail.length && t - trail[0][2] < ${TRAIL_SECONDS}) trail[0] = [at[0], at[1], trail[0][2], 1]; else trail = [[at[0], at[1], t, 1], ...trail].slice(0, ${MAX_TRAIL}); };\ncanvas.addEventListener(\"pointermove\", (e) => { at = px(e); toTrail(); });\ncanvas.addEventListener(\"pointerdown\", (e) => { at = px(e); pressedAt = seconds(); clicks.unshift([at[0], at[1], pressedAt, 1]); clicks = clicks.slice(0, ${MAX_CLICKS}); });\naddEventListener(\"pointerup\", () => { if (pressedAt >= 0) releasedAt = seconds(); pressedAt = -1; });\nfunction draw(now) {\n const dpr = Math.min(devicePixelRatio || 1, 2);\n const w = Math.round(canvas.clientWidth * dpr), h = Math.round(canvas.clientHeight * dpr);\n if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; }\n gl.viewport(0, 0, w, h);\n gl.uniform3f(u(\"iResolution\"), w, h, 1);\n gl.uniform1f(u(\"iTime\"), (now - start) / 1000);\n gl.uniform1f(u(\"iTimeDelta\"), (now - last) / 1000);\n gl.uniform1i(u(\"iFrame\"), frame++);\n gl.uniform4f(u(\"iMouse\"), mouse[0], mouse[1], mouse[2], mouse[3]);\n const t = (now - start) / 1000;\n gl.uniform4f(u(\"iPointer\"), at[0], at[1], hovered(t), pressedAt >= 0 ? Math.max(0, t - pressedAt) : releasedAt >= 0 ? -Math.max(1e-3, t - releasedAt) : 0);\n const c = new Float32Array(${MAX_CLICKS * 4});\n clicks.forEach((k, i) => c.set(k, i * 4));\n gl.uniform4fv(u(\"iClicks\"), c);\n const p = new Float32Array(${MAX_TRAIL * 4});\n trail.forEach((k, i) => p.set(k, i * 4));\n gl.uniform4fv(u(\"iTrail\"), p);\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n last = now;\n requestAnimationFrame(draw);\n}\nrequestAnimationFrame(draw);\n</script>\n</body>\n</html>\n`;\n}\n","/**\n * 38 Layer Blend Modes for Compositing and WebGL Shader Generation.\n * Mathematically matching Adobe After Effects & EffectCraft blending standards.\n */\n\nexport type BlendMode =\n | 'normal'\n | 'dissolve'\n | 'dancingDissolve'\n | 'darken'\n | 'multiply'\n | 'colorBurn'\n | 'classicColorBurn'\n | 'linearBurn'\n | 'darkerColor'\n | 'add'\n | 'lighten'\n | 'screen'\n | 'colorDodge'\n | 'classicColorDodge'\n | 'linearDodge'\n | 'lighterColor'\n | 'overlay'\n | 'softLight'\n | 'hardLight'\n | 'linearLight'\n | 'vividLight'\n | 'pinLight'\n | 'hardMix'\n | 'difference'\n | 'classicDifference'\n | 'exclusion'\n | 'subtract'\n | 'divide'\n | 'hue'\n | 'saturation'\n | 'color'\n | 'luminosity'\n | 'stencilAlpha'\n | 'stencilLuma'\n | 'silhouetteAlpha'\n | 'silhouetteLuma'\n | 'alphaAdd'\n | 'luminescentPremul';\n\nexport const ALL_BLEND_MODES: readonly BlendMode[] = [\n 'normal',\n 'dissolve',\n 'dancingDissolve',\n 'darken',\n 'multiply',\n 'colorBurn',\n 'classicColorBurn',\n 'linearBurn',\n 'darkerColor',\n 'add',\n 'lighten',\n 'screen',\n 'colorDodge',\n 'classicColorDodge',\n 'linearDodge',\n 'lighterColor',\n 'overlay',\n 'softLight',\n 'hardLight',\n 'linearLight',\n 'vividLight',\n 'pinLight',\n 'hardMix',\n 'difference',\n 'classicDifference',\n 'exclusion',\n 'subtract',\n 'divide',\n 'hue',\n 'saturation',\n 'color',\n 'luminosity',\n 'stencilAlpha',\n 'stencilLuma',\n 'silhouetteAlpha',\n 'silhouetteLuma',\n 'alphaAdd',\n 'luminescentPremul',\n];\n\nexport type ColorRgba = [number, number, number, number];\n\nfunction lum(r: number, g: number, b: number): number {\n return 0.3 * r + 0.59 * g + 0.11 * b;\n}\n\nfunction sat(r: number, g: number, b: number): number {\n return Math.max(r, g, b) - Math.min(r, g, b);\n}\n\nfunction clipColor(r: number, g: number, b: number): [number, number, number] {\n const l = lum(r, g, b);\n const n = Math.min(r, g, b);\n const x = Math.max(r, g, b);\n let cr = r;\n let cg = g;\n let cb = b;\n if (n < 0.0) {\n const denom = Math.max(1e-9, l - n);\n cr = l + ((cr - l) * l) / denom;\n cg = l + ((cg - l) * l) / denom;\n cb = l + ((cb - l) * l) / denom;\n }\n if (x > 1.0) {\n const denom = Math.max(1e-9, x - l);\n cr = l + ((cr - l) * (1.0 - l)) / denom;\n cg = l + ((cg - l) * (1.0 - l)) / denom;\n cb = l + ((cb - l) * (1.0 - l)) / denom;\n }\n return [cr, cg, cb];\n}\n\nfunction setLum(r: number, g: number, b: number, l: number): [number, number, number] {\n const d = l - lum(r, g, b);\n return clipColor(r + d, g + d, b + d);\n}\n\nfunction setSat(r: number, g: number, b: number, s: number): [number, number, number] {\n const mx = Math.max(r, g, b);\n const mn = Math.min(r, g, b);\n if (mx - mn <= 1e-9) return [0, 0, 0];\n const f = (v: number) => ((v - mn) * s) / (mx - mn);\n return [f(r), f(g), f(b)];\n}\n\nfunction burn(cb: number, cs: number): number {\n if (cb >= 1.0) return 1.0;\n if (cs <= 0.0) return 0.0;\n return 1.0 - Math.min(1.0, (1.0 - cb) / cs);\n}\n\nfunction dodge(cb: number, cs: number): number {\n if (cb <= 0.0) return 0.0;\n if (cs >= 1.0) return 1.0;\n return Math.min(1.0, cb / (1.0 - cs));\n}\n\nfunction hardLight(cb: number, cs: number): number {\n if (cs <= 0.5) {\n return cb * 2.0 * cs;\n }\n const s = 2.0 * cs - 1.0;\n return cb + s - cb * s;\n}\n\nfunction softLight(cb: number, cs: number): number {\n if (cs <= 0.5) {\n return cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb);\n }\n const d = cb <= 0.25 ? ((16.0 * cb - 12.0) * cb + 4.0) * cb : Math.sqrt(Math.max(0.0, cb));\n return cb + (2.0 * cs - 1.0) * (d - cb);\n}\n\nfunction vividLight(cb: number, cs: number): number {\n return cs <= 0.5 ? burn(cb, 2.0 * cs) : dodge(cb, 2.0 * (cs - 0.5));\n}\n\nfunction separableBlend(mode: BlendMode, cb: number, cs: number): number {\n switch (mode) {\n case 'darken':\n return Math.min(cb, cs);\n case 'multiply':\n return cb * cs;\n case 'colorBurn':\n return burn(cb, cs);\n case 'classicColorBurn':\n return cs <= 0.0 ? 0.0 : 1.0 - (1.0 - cb) / cs;\n case 'linearBurn':\n return Math.max(0.0, cb + cs - 1.0);\n case 'add':\n case 'linearDodge':\n return cb + cs;\n case 'lighten':\n return Math.max(cb, cs);\n case 'screen':\n return cb + cs - cb * cs;\n case 'colorDodge':\n return dodge(cb, cs);\n case 'classicColorDodge':\n return cs >= 1.0 ? 1.0 : Math.min(1.0, cb / (1.0 - cs));\n case 'overlay':\n return hardLight(cs, cb);\n case 'softLight':\n return softLight(cb, cs);\n case 'hardLight':\n return hardLight(cb, cs);\n case 'linearLight':\n return Math.min(1.0, Math.max(0.0, cb + 2.0 * cs - 1.0));\n case 'vividLight':\n return vividLight(cb, cs);\n case 'pinLight':\n return cs <= 0.5 ? Math.min(cb, 2.0 * cs) : Math.max(cb, 2.0 * cs - 1.0);\n case 'hardMix':\n return cb + cs >= 1.0 ? 1.0 : 0.0;\n case 'difference':\n case 'classicDifference':\n return Math.abs(cb - cs);\n case 'exclusion':\n return cb + cs - 2.0 * cb * cs;\n case 'subtract':\n return Math.max(0.0, cb - cs);\n case 'divide':\n return cs <= 0.0 ? (cb > 0.0 ? 1.0 : 0.0) : cb / cs;\n default:\n return cs;\n }\n}\n\n/**\n * Evaluates CPU compositing of premultiplied RGBA source onto premultiplied RGBA destination.\n *\n * @param mode Blend mode to apply.\n * @param dst Destination premultiplied RGBA [r, g, b, a] in [0, 1].\n * @param src Source premultiplied RGBA [r, g, b, a] in [0, 1].\n * @param noise Per-pixel noise parameter in [0, 1] for Dissolve modes (default: 0).\n */\nexport function blendRgba(\n mode: BlendMode,\n dst: ColorRgba,\n src: ColorRgba,\n noise = 0,\n): ColorRgba {\n const sa = src[3];\n const da = dst[3];\n\n switch (mode) {\n case 'normal': {\n const k = 1.0 - sa;\n return [src[0] + dst[0] * k, src[1] + dst[1] * k, src[2] + dst[2] * k, sa + da * k];\n }\n case 'dissolve':\n case 'dancingDissolve': {\n if (sa <= 0.0 || noise >= sa) return [...dst];\n const inv = 1.0 / sa;\n return [src[0] * inv, src[1] * inv, src[2] * inv, 1.0];\n }\n case 'stencilAlpha':\n return [dst[0] * sa, dst[1] * sa, dst[2] * sa, dst[3] * sa];\n case 'silhouetteAlpha': {\n const k = 1.0 - sa;\n return [dst[0] * k, dst[1] * k, dst[2] * k, dst[3] * k];\n }\n case 'stencilLuma':\n case 'silhouetteLuma': {\n const l = lum(src[0], src[1], src[2]);\n const k = mode === 'stencilLuma' ? l : 1.0 - l;\n return [dst[0] * k, dst[1] * k, dst[2] * k, dst[3] * k];\n }\n case 'alphaAdd': {\n const k = 1.0 - sa;\n return [src[0] + dst[0] * k, src[1] + dst[1] * k, src[2] + dst[2] * k, Math.min(1.0, sa + da)];\n }\n case 'luminescentPremul': {\n const k = 1.0 - sa;\n return [src[0] + dst[0] * k, src[1] + dst[1] * k, src[2] + dst[2] * k, sa + da - sa * da];\n }\n }\n\n if (sa <= 0.0) return [...dst];\n if (da <= 0.0) return [...src];\n\n const cs: [number, number, number] = [src[0] / sa, src[1] / sa, src[2] / sa];\n const cb: [number, number, number] = [dst[0] / da, dst[1] / da, dst[2] / da];\n\n let b: [number, number, number];\n switch (mode) {\n case 'hue':\n b = setLum(...setSat(cs[0], cs[1], cs[2], sat(...cb)), lum(...cb));\n break;\n case 'saturation':\n b = setLum(...setSat(cb[0], cb[1], cb[2], sat(...cs)), lum(...cb));\n break;\n case 'color':\n b = setLum(cs[0], cs[1], cs[2], lum(...cb));\n break;\n case 'luminosity':\n b = setLum(cb[0], cb[1], cb[2], lum(...cs));\n break;\n case 'darkerColor':\n b = lum(...cs) < lum(...cb) ? cs : cb;\n break;\n case 'lighterColor':\n b = lum(...cs) > lum(...cb) ? cs : cb;\n break;\n default:\n b = [\n separableBlend(mode, cb[0], cs[0]),\n separableBlend(mode, cb[1], cs[1]),\n separableBlend(mode, cb[2], cs[2]),\n ];\n break;\n }\n\n const ao = sa + da - sa * da;\n return [\n (1.0 - da) * src[0] + (1.0 - sa) * dst[0] + sa * da * b[0],\n (1.0 - da) * src[1] + (1.0 - sa) * dst[1] + sa * da * b[1],\n (1.0 - da) * src[2] + (1.0 - sa) * dst[2] + sa * da * b[2],\n ao,\n ];\n}\n\n/**\n * Returns a self-contained GLSL shader function for blending two vec4 colors.\n * Useful for runtime GPU compositing across multiple shader layers or passes.\n */\nexport function getGlslBlendFunction(mode: BlendMode): string {\n switch (mode) {\n case 'multiply':\n return `vec4 blend(vec4 dst, vec4 src) {\n return vec4(src.rgb * dst.rgb * src.a + dst.rgb * (1.0 - src.a), src.a + dst.a * (1.0 - src.a));\n}`;\n case 'screen':\n return `vec4 blend(vec4 dst, vec4 src) {\n vec3 res = src.rgb + dst.rgb - src.rgb * dst.rgb;\n return vec4(mix(dst.rgb, res, src.a), src.a + dst.a * (1.0 - src.a));\n}`;\n case 'add':\n case 'linearDodge':\n return `vec4 blend(vec4 dst, vec4 src) {\n return vec4(min(vec3(1.0), dst.rgb + src.rgb * src.a), min(1.0, dst.a + src.a));\n}`;\n case 'overlay':\n return `vec4 blend(vec4 dst, vec4 src) {\n vec3 res = mix(2.0 * dst.rgb * src.rgb, 1.0 - 2.0 * (1.0 - dst.rgb) * (1.0 - src.rgb), step(vec3(0.5), dst.rgb));\n return vec4(mix(dst.rgb, res, src.a), src.a + dst.a * (1.0 - src.a));\n}`;\n case 'difference':\n return `vec4 blend(vec4 dst, vec4 src) {\n return vec4(mix(dst.rgb, abs(dst.rgb - src.rgb), src.a), src.a + dst.a * (1.0 - src.a));\n}`;\n case 'normal':\n default:\n return `vec4 blend(vec4 dst, vec4 src) {\n return src + dst * (1.0 - src.a);\n}`;\n }\n}\n","import { CAMERA_TRANSITIONS, MAX_TILT } from './camera.js';\nimport type { Scene, Shot } from './types.js';\nimport { EFFECT_TYPES } from './effects.js';\n\nexport interface SceneIssue {\n /** 1-based shot index (0 indicates whole scene level). */\n shot: number;\n message: string;\n}\n\nconst LONG_CAPTION = 120;\nconst LONG_TITLE = 60;\nconst MAX_EFFECTS_PER_SHOT = 5;\n\n/** Validates a Scene before running or rendering it. */\nexport function validateScene(scene: Scene): SceneIssue[] {\n const issues: SceneIssue[] = [];\n const say = (shot: number, message: string) => issues.push({ shot, message });\n\n if (!scene.name || typeof scene.name !== 'string') {\n say(0, 'Scene needs a string name.');\n } else if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(scene.name)) {\n say(0, `Scene name \"${scene.name}\" should be lowercase words and dashes.`);\n }\n\n if (!Array.isArray(scene.shots) || scene.shots.length === 0) {\n say(0, 'Scene needs at least one shot.');\n return issues;\n }\n\n const mediaKeys = new Set(Object.keys(scene.media ?? {}));\n const effectIds = new Set<string>();\n\n // Check media\n if (scene.media) {\n for (const [id, m] of Object.entries(scene.media)) {\n if (!m || typeof m !== 'object') {\n say(0, `Media \"${id}\" must be an object.`);\n } else if (!m.type) {\n say(0, `Media \"${id}\" needs a type.`);\n } else if (m.type === 'shader' && !m.source) {\n say(0, `Shader media \"${id}\" needs a source string.`);\n }\n }\n }\n\n for (const [idx, shot] of scene.shots.entries()) {\n const shotNum = idx + 1;\n\n // Check camera\n if (shot.camera) {\n if ('frame' in shot.camera) {\n if (!Array.isArray(shot.camera.frame) || shot.camera.frame.length === 0) {\n say(shotNum, 'Dynamic camera framing requires a non-empty frame array of element IDs.');\n }\n } else if ('width' in shot.camera && (shot.camera.width <= 0 || shot.camera.height <= 0)) {\n say(shotNum, 'Camera rectangle width and height must be positive.');\n }\n const cam = shot.camera;\n const angle = (name: 'tilt' | 'turn' | 'roll', max: number) => {\n const v = cam[name];\n if (v !== undefined && !(typeof v === 'number' && Math.abs(v) <= max))\n say(shotNum, `Camera ${name} is degrees between -${max} and ${max}.`);\n };\n angle('tilt', MAX_TILT);\n angle('turn', MAX_TILT);\n angle('roll', 180);\n if (cam.perspective !== undefined && !(typeof cam.perspective === 'number' && cam.perspective >= 0.3))\n say(shotNum, 'Camera perspective is the lens distance as a multiple of the stage width, 0.3 or more (1.2 by default).');\n if (cam.motionBlur !== undefined && !(typeof cam.motionBlur === 'number' && cam.motionBlur >= 0 && cam.motionBlur <= 3))\n say(shotNum, 'Camera motionBlur is 0 (none) to 3 (a whip); 1 is natural.');\n if (cam.transition !== undefined && !CAMERA_TRANSITIONS.includes(cam.transition))\n say(shotNum, `Camera transition is one of ${CAMERA_TRANSITIONS.map((t) => `\"${t}\"`).join(', ')}; leave it out to move.`);\n else if (idx === 0 && (cam.transition === 'whip' || cam.transition === 'zoom'))\n say(shotNum, `The first shot has no framing to ${cam.transition} from, so its camera starts in place; move the transition to a later shot or leave it out.`);\n }\n\n // Check hold\n if (shot.hold !== undefined && shot.hold < 0) {\n say(shotNum, 'Shot hold cannot be negative.');\n }\n\n // Check text lengths\n if (shot.caption && shot.caption.length > LONG_CAPTION) {\n say(shotNum, `Caption is long (${shot.caption.length} chars); consider breaking into multiple shots.`);\n }\n if (shot.title && shot.title.length > LONG_TITLE) {\n say(shotNum, `Title is long (${shot.title.length} chars); titles should be concise headings.`);\n }\n\n // Check effects\n const effects = shot.effects ?? [];\n if (effects.length > MAX_EFFECTS_PER_SHOT) {\n say(shotNum, `Shot starts ${effects.length} effects at once; consider keeping effects focused.`);\n }\n\n for (const eff of effects) {\n if (!eff.id || typeof eff.id !== 'string') {\n say(shotNum, 'Every effect needs a unique string id.');\n continue;\n }\n if (effectIds.has(eff.id)) {\n say(shotNum, `Duplicate effect id \"${eff.id}\".`);\n }\n effectIds.add(eff.id);\n\n if (!EFFECT_TYPES.includes(eff.type as any)) {\n say(shotNum, `Unknown effect type \"${(eff as any).type}\".`);\n }\n\n if (eff.type === 'media') {\n if (!eff.media) {\n say(shotNum, `Media effect \"${eff.id}\" needs a media id.`);\n } else if (!mediaKeys.has(eff.media)) {\n say(shotNum, `Media effect \"${eff.id}\" references \"${eff.media}\" which is not defined in scene.media.`);\n }\n }\n\n if (eff.type === 'flow' && !eff.along) {\n say(shotNum, `Flow effect \"${eff.id}\" needs an \"along\" element id.`);\n }\n\n if (['glow', 'ripple', 'spotlight', 'shimmer', 'timer', 'blur', 'burst'].includes(eff.type)) {\n const withIds = eff as { ids?: string[] };\n if (!Array.isArray(withIds.ids) || withIds.ids.length === 0) {\n say(shotNum, `${eff.type} effect \"${eff.id}\" needs a non-empty ids array.`);\n }\n }\n }\n }\n\n return issues;\n}\n","import type { Stage, View } from './camera.js';\nimport { CAMERA_STEP_MS, cameraAt, cameraTrack, sceneStage } from './cameratrack.js';\nimport type { SceneElement } from './geometry.js';\nimport type { Scene } from './types.js';\n\n/** What the standalone player shows for one shot: the camera's move into it and the elements on stage. */\ninterface ShotPlan {\n /** The camera at each step of its move into the shot (one view when it does not move). */\n move: View[];\n /** How long the move takes, in ms (0 when the shot cuts or stays). */\n moveMs: number;\n elements: SceneElement[];\n}\n\n/** Each shot's camera move and elements, worked out the way `playScene` plays them. */\nfunction planShots(scene: Scene, stage: Stage): ShotPlan[] {\n return cameraTrack(scene).map((entry) => {\n // The player's steps: the last one lands on the shot's view, with no blur.\n const steps = Math.round(entry.moveMs / CAMERA_STEP_MS);\n const move = Array.from({ length: Math.max(0, steps - 1) }, (_, i) => cameraAt(entry, (i + 1) * CAMERA_STEP_MS, stage));\n move.push(entry.to);\n return { move, moveMs: entry.moveMs, elements: entry.elements };\n });\n}\n\n/**\n * Generates a self-contained, standalone HTML player for an animated scene.\n * Includes interactive playback controls, camera moves (panning, zooming,\n * 3D angles and motion blur), title and caption rendering, and embedded\n * WebGL fragment shaders for bespoke motion graphics.\n */\nexport function standaloneSceneHtml(scene: Scene): string {\n const stage = sceneStage(scene);\n const serializedScene = JSON.stringify(scene).replace(/</g, '\\\\u003c');\n const serializedPlan = JSON.stringify({ stage, shots: planShots(scene, stage) }).replace(/</g, '\\\\u003c');\n const title = scene.title || scene.name;\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(title)} - Flair</title>\n <style>\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body {\n background: #0f1117;\n color: #e2e8f0;\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif;\n min-height: 100vh;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 16px;\n user-select: none;\n }\n .player-container {\n position: relative;\n width: 100%;\n max-width: 1200px;\n aspect-ratio: ${stage.width} / ${stage.height};\n background: #000;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 20px 50px rgba(0, 0, 0, 0.7), 0 0 0 1px rgba(255, 255, 255, 0.1);\n display: flex;\n flex-direction: column;\n }\n .viewport {\n position: relative;\n flex: 1;\n width: 100%;\n height: 100%;\n overflow: hidden;\n }\n .board {\n position: absolute;\n inset: 0;\n transform-origin: 50% 50%;\n will-change: transform, filter;\n }\n canvas.layer {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n }\n .overlay-title {\n position: absolute;\n top: 24px;\n left: 50%;\n transform: translateX(-50%);\n background: rgba(15, 17, 23, 0.85);\n backdrop-filter: blur(8px);\n border: 1px solid rgba(255, 255, 255, 0.15);\n padding: 8px 24px;\n border-radius: 9999px;\n font-size: 1.15rem;\n font-weight: 600;\n letter-spacing: 0.02em;\n color: #fff;\n pointer-events: none;\n transition: opacity 0.3s ease;\n opacity: 0;\n }\n .overlay-caption {\n position: absolute;\n bottom: 64px;\n left: 50%;\n transform: translateX(-50%);\n background: rgba(15, 17, 23, 0.88);\n backdrop-filter: blur(8px);\n border: 1px solid rgba(255, 255, 255, 0.15);\n padding: 10px 20px;\n border-radius: 8px;\n font-size: 1.1rem;\n color: #f1f5f9;\n max-width: 80%;\n text-align: center;\n pointer-events: none;\n transition: opacity 0.3s ease;\n opacity: 0;\n }\n .controls-bar {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n height: 52px;\n background: linear-gradient(to top, rgba(0, 0, 0, 0.9), transparent);\n display: flex;\n align-items: center;\n padding: 0 16px;\n gap: 12px;\n z-index: 10;\n }\n .btn {\n background: rgba(255, 255, 255, 0.15);\n border: none;\n color: #fff;\n padding: 6px 14px;\n border-radius: 6px;\n cursor: pointer;\n font-size: 0.9rem;\n font-weight: 500;\n transition: background 0.15s;\n }\n .btn:hover { background: rgba(255, 255, 255, 0.25); }\n .timeline {\n flex: 1;\n height: 6px;\n background: rgba(255, 255, 255, 0.2);\n border-radius: 3px;\n cursor: pointer;\n position: relative;\n }\n .timeline-progress {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n background: #3b82f6;\n border-radius: 3px;\n width: 0%;\n }\n .shot-badge {\n font-size: 0.85rem;\n color: #94a3b8;\n font-variant-numeric: tabular-nums;\n }\n </style>\n</head>\n<body>\n <div class=\"player-container\">\n <div class=\"viewport\" id=\"viewport\">\n <canvas id=\"shaderCanvas\" class=\"layer\"></canvas>\n <div id=\"board\" class=\"board\"><canvas id=\"sceneCanvas\" class=\"layer\"></canvas></div>\n <svg width=\"0\" height=\"0\" style=\"position:absolute\" aria-hidden=\"true\"><filter id=\"motionBlur\" x=\"-10%\" y=\"-10%\" width=\"120%\" height=\"120%\"><feGaussianBlur id=\"motionBlurAmount\" stdDeviation=\"0 0\"/></filter></svg>\n <div id=\"titleEl\" class=\"overlay-title\"></div>\n <div id=\"captionEl\" class=\"overlay-caption\"></div>\n </div>\n <div class=\"controls-bar\">\n <button id=\"playBtn\" class=\"btn\">Play</button>\n <button id=\"prevBtn\" class=\"btn\">⏮</button>\n <button id=\"nextBtn\" class=\"btn\">⏭</button>\n <div id=\"timeline\" class=\"timeline\">\n <div id=\"progress\" class=\"timeline-progress\"></div>\n </div>\n <div id=\"shotBadge\" class=\"shot-badge\">Shot 1 / 1</div>\n </div>\n </div>\n\n <script>\n const scene = ${serializedScene};\n // Each shot's camera move (zoom, scroll, 3D angle and blur at each step) and elements, worked out in advance.\n const plan = ${serializedPlan};\n const boardEl = document.getElementById('board');\n const sceneCanvas = document.getElementById('sceneCanvas');\n const shaderCanvas = document.getElementById('shaderCanvas');\n const ctx = sceneCanvas.getContext('2d');\n const titleEl = document.getElementById('titleEl');\n const captionEl = document.getElementById('captionEl');\n const playBtn = document.getElementById('playBtn');\n const prevBtn = document.getElementById('prevBtn');\n const nextBtn = document.getElementById('nextBtn');\n const progressEl = document.getElementById('progress');\n const shotBadge = document.getElementById('shotBadge');\n\n let currentShotIdx = 0;\n let isPlaying = false;\n let shotStartTime = performance.now();\n let moveFrom = performance.now();\n let gl = null;\n let shaderProgram = null;\n\n function resize() {\n const rect = sceneCanvas.parentElement.getBoundingClientRect();\n const dpr = window.devicePixelRatio || 1;\n sceneCanvas.width = rect.width * dpr;\n sceneCanvas.height = rect.height * dpr;\n shaderCanvas.width = rect.width * dpr;\n shaderCanvas.height = rect.height * dpr;\n }\n window.addEventListener('resize', resize);\n resize();\n\n // Setup WebGL if shader media is present\n const firstShaderKey = Object.keys(scene.media || {}).find(k => scene.media[k].type === 'shader');\n if (firstShaderKey && scene.media[firstShaderKey].source) {\n try {\n gl = shaderCanvas.getContext('webgl2');\n if (gl) {\n const vs = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vs, '#version 300 es\\\\nin vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); }');\n gl.compileShader(vs);\n\n const fs = gl.createShader(gl.FRAGMENT_SHADER);\n const fullFrag = '#version 300 es\\\\nprecision highp float;\\\\nout vec4 fragColor;\\\\nuniform vec2 u_resolution;\\\\nuniform float u_time;\\\\n' + scene.media[firstShaderKey].source + '\\\\nvoid main() { mainImage(fragColor, gl_FragCoord.xy); }';\n gl.shaderSource(fs, fullFrag);\n gl.compileShader(fs);\n\n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vs);\n gl.attachShader(shaderProgram, fs);\n gl.linkProgram(shaderProgram);\n\n const quad = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, quad);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1, 3,-1, -1,3]), gl.STATIC_DRAW);\n const pos = gl.getAttribLocation(shaderProgram, 'position');\n gl.enableVertexAttribArray(pos);\n gl.vertexAttribPointer(pos, 2, gl.FLOAT, false, 0, 0);\n }\n } catch (e) {\n console.warn('Shader setup failed:', e);\n }\n }\n\n function renderShader(timeSeconds) {\n if (!gl || !shaderProgram) return;\n gl.viewport(0, 0, shaderCanvas.width, shaderCanvas.height);\n gl.useProgram(shaderProgram);\n const resLoc = gl.getUniformLocation(shaderProgram, 'u_resolution');\n const timeLoc = gl.getUniformLocation(shaderProgram, 'u_time');\n if (resLoc) gl.uniform2f(resLoc, shaderCanvas.width, shaderCanvas.height);\n if (timeLoc) gl.uniform1f(timeLoc, timeSeconds);\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n }\n\n function updateShotUI() {\n const shot = scene.shots[currentShotIdx];\n if (!shot) return;\n\n shotBadge.textContent = 'Shot ' + (currentShotIdx + 1) + ' / ' + scene.shots.length;\n\n if (shot.title) {\n titleEl.textContent = shot.title;\n titleEl.style.opacity = '1';\n } else {\n titleEl.style.opacity = '0';\n }\n\n if (shot.caption) {\n captionEl.textContent = shot.caption;\n captionEl.style.opacity = '1';\n } else {\n captionEl.style.opacity = '0';\n }\n\n const pct = (currentShotIdx / scene.shots.length) * 100;\n progressEl.style.width = pct + '%';\n }\n\n // The camera at time 'now': a step of the current shot's move, or where it settled.\n function cameraNow(now) {\n const { move, moveMs } = plan.shots[currentShotIdx];\n const u = moveMs > 0 ? Math.min(1, (now - moveFrom) / moveMs) : 1;\n return move[Math.min(move.length - 1, Math.floor(u * move.length))];\n }\n\n function applyCamera(view) {\n const w = boardEl.clientWidth || plan.stage.width;\n const angled = view.tilt || view.turn || view.roll;\n boardEl.style.transform = angled\n ? 'perspective(' + (view.perspective || 1.2) * w + 'px) rotateX(' + (view.tilt || 0) + 'deg) rotateY(' + (view.turn || 0) + 'deg) rotateZ(' + (view.roll || 0) + 'deg)'\n : 'none';\n // Motion blur streaks along a pan (taken back through the roll, as the board is blurred before it turns).\n const blur = (view.blur || 0) * w / plan.stage.width;\n if (blur >= 0.05) {\n let sx = blur, sy = blur;\n if (view.blurAngle !== undefined) {\n const a = (view.blurAngle - (view.roll || 0)) * Math.PI / 180;\n sx = Math.max(blur * 0.15, blur * Math.abs(Math.cos(a)));\n sy = Math.max(blur * 0.15, blur * Math.abs(Math.sin(a)));\n }\n document.getElementById('motionBlurAmount').setAttribute('stdDeviation', sx.toFixed(2) + ' ' + sy.toFixed(2));\n boardEl.style.filter = 'url(#motionBlur)';\n } else {\n boardEl.style.filter = 'none';\n }\n }\n\n function draw() {\n const now = performance.now();\n renderShader(now / 1000);\n\n const view = cameraNow(now);\n applyCamera(view);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, sceneCanvas.width, sceneCanvas.height);\n const k = (sceneCanvas.width / plan.stage.width) * view.zoom;\n ctx.setTransform(k, 0, 0, k, k * view.scrollX, k * view.scrollY);\n\n for (const el of plan.shots[currentShotIdx].elements) {\n ctx.fillStyle = el.backgroundColor || 'rgba(59, 130, 246, 0.4)';\n ctx.strokeStyle = el.strokeColor || '#3b82f6';\n ctx.lineWidth = 3;\n ctx.fillRect(el.x, el.y, el.width, el.height);\n ctx.strokeRect(el.x, el.y, el.width, el.height);\n if (el.text) {\n ctx.fillStyle = '#fff';\n ctx.font = '24px sans-serif';\n ctx.fillText(el.text, el.x + 16, el.y + 40);\n }\n }\n\n // Playing moves on to the next shot once this one's move and hold are over.\n const shot = scene.shots[currentShotIdx];\n if (isPlaying && now - shotStartTime > plan.shots[currentShotIdx].moveMs + (shot.hold ?? 800) && currentShotIdx < scene.shots.length - 1) {\n goTo(currentShotIdx + 1, true);\n }\n if (isPlaying || now - moveFrom < plan.shots[currentShotIdx].moveMs) {\n requestAnimationFrame(draw);\n }\n }\n\n // Shows a shot: forwards it plays the camera's move into it, otherwise it cuts.\n function goTo(idx, animate) {\n currentShotIdx = idx;\n shotStartTime = performance.now();\n moveFrom = animate ? shotStartTime : shotStartTime - plan.shots[idx].moveMs;\n updateShotUI();\n requestAnimationFrame(draw);\n }\n\n playBtn.addEventListener('click', () => {\n isPlaying = !isPlaying;\n playBtn.textContent = isPlaying ? 'Pause' : 'Play';\n // The current shot counts as settled, so its hold runs from now.\n if (isPlaying) {\n shotStartTime = performance.now() - plan.shots[currentShotIdx].moveMs;\n requestAnimationFrame(draw);\n }\n });\n\n prevBtn.addEventListener('click', () => {\n if (currentShotIdx > 0) goTo(currentShotIdx - 1, false);\n });\n\n nextBtn.addEventListener('click', () => {\n if (currentShotIdx < scene.shots.length - 1) goTo(currentShotIdx + 1, true);\n });\n\n window.addEventListener('resize', () => requestAnimationFrame(draw));\n goTo(0, false);\n </script>\n</body>\n</html>`;\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g,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/**\n * Renders a catalog effect, applied to a subject, to a file in Node: video\n * (MP4, WebM, MOV), GIF, PNG frames, or (vector effects) an animated SVG.\n */\n\nimport { spawn } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport {\n EFFECT_CATEGORIES,\n EFFECT_INPUTS,\n EFFECT_INTERACTIONS,\n effectControls,\n effectDefaults,\n effectInputs,\n getEffect,\n renderVectorEffect,\n type EffectCategory,\n type EffectDefinition,\n type EffectInput,\n type EffectInteraction,\n type VectorEffect,\n} from '../catalog/index.js';\nimport { subjectValues, type EffectSubject } from '../embed/index.js';\nimport { checkControlValue, parseColor, type ControlDef, type ControlValue } from '../shader/controls.js';\nimport { wrapSource } from '../shader/program.js';\nimport { svgAnimatedMarkup } from '../vector/animated.js';\nimport type { SvgMotion } from '../vector/motion.js';\nimport { svgFrameMarkup, svgViewBox } from '../vector/static.js';\nimport { svgDuration } from '../vector/svg.js';\nimport {\n ffmpegPath,\n frameStates,\n imageDataUrl,\n pageControls,\n planOutput,\n runRender,\n type FrameState,\n type PointerMode,\n} from './recorder.js';\n\n/**\n * What an effect is applied to, in Node:\n * - `{ image }`: a picture's file path or URL (or a `data:` URL).\n * - `{ svg }`: an SVG's file path, URL, or markup (`\"<svg …>\"`).\n * - `{ text }`: words, for a vector effect's text, or drawn with `textImage` for a shader's text or mask.\n * - `{ path }`: SVG path data (`d`), for a shape control.\n * - `{ video }`: a video file's path, decoded to frames with ffmpeg and shown one per frame.\n */\nexport type NodeSubject =\n | { image: string }\n | { svg: string }\n | { text: string; font?: string; weight?: number | string }\n | { path: string }\n | { video: string };\n\nexport interface EffectExportOptions {\n /** What to apply it to; several fill several controls in order (a transition's from and to). */\n subject?: NodeSubject | readonly NodeSubject[];\n /** A preset by name, under `values`. */\n preset?: string;\n /** Control values over the defaults (and the subject). An image control also takes a file path. */\n values?: Record<string, ControlValue>;\n /** .mp4, .webm, .mov, .gif, .svg (vector effects), or PNG frames (a folder, or `out_%04d.png`). */\n outputPath: string;\n /** Pixels (default: 1280 × 720 for effects that show a picture, 720 × 720 for other shaders, a vector's own shape 720 px on its long edge). */\n width?: number;\n height?: number;\n fps?: number;\n /**\n * Seconds. Default: a shader's loop (when it loops in 12 s or less), a\n * video subject's length (up to 10 s), else 3; a vector effect's one\n * play-through (with its trigger acted out).\n */\n duration?: number;\n /** Keep transparency (WebM, MOV, GIF, PNG and SVG; MP4 is always opaque). */\n alpha?: boolean;\n /** CSS colour under transparent pixels without `alpha` (default black for shaders, white for vector effects). */\n background?: string;\n /**\n * The pointer, for effects that answer it: `auto` (the default for them),\n * a scripted pointer that hovers, wanders and clicks; `none` leaves it\n * still. Vector effects with a trigger have it acted out (clicked through\n * their steps, or hovered and let go).\n */\n pointer?: PointerMode;\n onProgress?: (frame: number, total: number) => void;\n}\n\nconst isUrl = (s: string) => /^(https?|data):/i.test(s);\n\n/** An SVG subject as markup: given markup stays, a URL is fetched, a path read. */\nasync function svgMarkup(svg: string): Promise<string> {\n const text = svg.trim();\n if (text.startsWith('<')) return text;\n if (/^data:image\\/svg\\+xml/i.test(text)) {\n const comma = text.indexOf(',');\n const meta = text.slice(0, comma);\n const body = text.slice(comma + 1);\n return /;base64/i.test(meta) ? Buffer.from(body, 'base64').toString('utf8') : decodeURIComponent(body);\n }\n if (/^https?:/i.test(text)) {\n const res = await fetch(text);\n if (!res.ok) throw new Error(`Could not download the SVG at ${text} (HTTP ${res.status}).`);\n return res.text();\n }\n const file = path.resolve(text);\n if (!fs.existsSync(file)) throw new Error(`There is no SVG at ${file}; give a file path, a URL, or markup starting with \"<svg\".`);\n return fs.readFileSync(file, 'utf8');\n}\n\n/** What a Node subject becomes: control values, and video files by image control. */\nexport interface NodeSubjectValues {\n values: Record<string, ControlValue>;\n /** Image control → video file. */\n video: Record<string, string>;\n}\n\n/**\n * The control values that put Node subjects in `effect` (see\n * `subjectValues` in `@pixerate/flair/embed`, which picks the controls):\n * image files and URLs become `data:` URLs, SVG files and URLs are read as\n * markup, and a video is kept as its file for its control, to be decoded to\n * frames. Throws a sentence when the effect takes no such thing.\n */\nexport async function nodeSubjectValues(effect: EffectDefinition, subject: NodeSubject | readonly NodeSubject[]): Promise<NodeSubjectValues> {\n const list = (Array.isArray(subject) ? subject : [subject]) as readonly NodeSubject[];\n const browser: EffectSubject[] = [];\n const videoFiles: string[] = [];\n for (const s of list) {\n if ('image' in s) browser.push({ image: await imageDataUrl(s.image) });\n else if ('svg' in s) browser.push({ svg: await svgMarkup(s.svg) });\n else if ('video' in s) {\n const file = path.resolve(s.video);\n if (!isUrl(s.video) && !fs.existsSync(file)) throw new Error(`There is no video at ${file}.`);\n videoFiles.push(isUrl(s.video) ? s.video : file);\n // A stand-in: subjectValues only needs to know it is a video to pick its control.\n browser.push({ video: { readyState: 0, currentTime: 0 } as unknown as HTMLVideoElement });\n } else browser.push(s);\n }\n const { values, live } = subjectValues(effect, browser);\n const video: Record<string, string> = {};\n Object.keys(live).forEach((name, i) => (video[name] = videoFiles[i]!));\n return { values, video };\n}\n\n/** The effect for an id (or the definition itself); a sentence when there is none. */\nexport function resolveEffect(effect: string | EffectDefinition): EffectDefinition {\n if (typeof effect !== 'string') return effect;\n const def = getEffect(effect);\n if (!def) throw new Error(`There is no effect \"${effect}\" in the catalog; \"flair effects\" (or findEffects()) lists them.`);\n return def;\n}\n\n/**\n * Checks control values against an effect's controls: unknown names, and\n * values a control cannot take, are sentences. Image controls take file\n * paths too (read into `data:` URLs).\n */\nexport async function checkEffectValues(effect: EffectDefinition, values: Record<string, ControlValue>): Promise<Record<string, ControlValue>> {\n const controls = new Map(effectControls(effect).map((c) => [c.name, c]));\n const out: Record<string, ControlValue> = {};\n for (const [name, raw] of Object.entries(values)) {\n const control = controls.get(name);\n if (!control) throw new Error(`\"${effect.id}\" has no control \"${name}\"; it has ${[...controls.keys()].join(', ') || 'none'}.`);\n if (control.type === 'sampler2D' && typeof raw === 'string') {\n out[name] = await imageDataUrl(raw);\n continue;\n }\n if (effect.kind === 'vector' && control.color && typeof raw === 'string' && raw.trim().toLowerCase() === 'currentcolor') {\n out[name] = raw;\n continue;\n }\n const check = checkControlValue(control, raw);\n if (!check.ok) throw new Error(check.message);\n out[name] = check.value;\n }\n return out;\n}\n\n/** How a vector effect plays over time in a recording: the frame at each ms, and its loop. */\nexport interface VectorTimeline {\n /** One play-through, ms. */\n length: number;\n /** Step start times (ms) for the whole loop, for an animated SVG. */\n steps: number[];\n /** The picture's time and steps at `ms` into the recording. */\n at(ms: number): { time: number; steps: number[] };\n}\n\n/** Ms an effect rests before its trigger is acted out. */\nconst REST = 300;\n\n/**\n * A vector effect's timeline: a loop plays and rests `hold` ms; a hover or\n * press trigger plays to the end, rests, and plays back; a click trigger is\n * clicked through each of its steps (or, with none, clicked again after\n * each play-through).\n */\nexport function vectorTimeline(effect: Pick<VectorEffect, 'hold' | 'trigger'>, motion: SvgMotion): VectorTimeline {\n const hold = effect.hold ?? 600;\n const d = svgDuration(motion);\n if (effect.trigger === 'hover' || effect.trigger === 'press') {\n const length = REST + d + hold + d;\n return {\n length,\n steps: [],\n at(ms) {\n const p = ms % length;\n const time = p < REST ? 0 : p < REST + d ? p - REST : p < REST + d + hold ? d : Math.max(0, d - (p - REST - d - hold));\n return { time, steps: [] };\n },\n };\n }\n if (effect.trigger === 'click') {\n const anims = motion.animate ?? [];\n const last = anims.reduce((n, a) => Math.max(n, a.step ?? 0), 0);\n if (last === 0) {\n const length = REST + d + hold;\n return { length, steps: [], at: (ms) => ({ time: Math.max(0, (ms % length) - REST), steps: [] }) };\n }\n // One click per step, each when the step before has played and rested.\n const clicks: number[] = [];\n let at = REST;\n for (let step = 1; step <= last; step++) {\n clicks.push(at);\n const ends = anims.filter((a) => (a.step ?? 0) === step).map((a) => (a.delay ?? 0) + (a.ms ?? 800));\n at += Math.max(0, ...ends) + hold;\n }\n const length = at;\n return {\n length,\n steps: clicks,\n at(ms) {\n const p = ms % length;\n return { time: p, steps: clicks.filter((c) => c <= p) };\n },\n };\n }\n const length = d + hold;\n return { length, steps: [], at: (ms) => ({ time: ms % length, steps: [] }) };\n}\n\nconst even = (n: number) => Math.max(2, Math.round(n / 2) * 2);\n\n/** Default pixel size for an effect (see {@link EffectExportOptions.width}). */\nexport function defaultSize(effect: EffectDefinition, motion?: SvgMotion): { width: number; height: number } {\n if (effect.kind === 'vector') {\n const box = svgViewBox((motion ?? effect.motion).svg);\n const aspect = box && box[2] > 0 && box[3] > 0 ? box[2] / box[3] : 1;\n return aspect >= 1 ? { width: 720, height: even(720 / aspect) } : { width: even(720 * aspect), height: 720 };\n }\n return effectInputs(effect).images.length ? { width: 1280, height: 720 } : { width: 720, height: 720 };\n}\n\nfunction run(bin: string, args: string[]): Promise<{ code: number; stderr: string }> {\n return new Promise((resolve, reject) => {\n const proc = spawn(bin, args, { stdio: ['ignore', 'ignore', 'pipe'] });\n let stderr = '';\n proc.stderr!.on('data', (d) => (stderr += d.toString()));\n proc.on('error', (err: NodeJS.ErrnoException) =>\n reject(err.code === 'ENOENT' ? new Error('A video subject needs ffmpeg to decode it, and it is not installed (or not on the PATH); install it, or set FFMPEG_PATH.') : err),\n );\n proc.on('close', (code) => resolve({ code: code ?? 1, stderr }));\n });\n}\n\n/** A video's length in seconds, from ffmpeg's report (undefined when it does not say). */\nexport async function videoSeconds(file: string): Promise<number | undefined> {\n const { stderr } = await run(ffmpegPath(), ['-hide_banner', '-i', file]);\n const m = /Duration:\\s*(\\d+):(\\d+):(\\d+(?:\\.\\d+)?)/.exec(stderr);\n return m ? Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]) : undefined;\n}\n\n/**\n * Decodes `frames` frames of a video at `fps` into PNGs in `dir` (looping a\n * short video), at most 2048 px on the long edge. Returns their paths.\n */\nexport async function extractVideoFrames(file: string, fps: number, frames: number, dir: string): Promise<string[]> {\n fs.mkdirSync(dir, { recursive: true });\n const { code, stderr } = await run(ffmpegPath(), [\n '-hide_banner', '-loglevel', 'error', '-y',\n '-stream_loop', '-1', '-i', file,\n '-vf', `fps=${fps},scale='if(gte(iw,ih),min(2048,iw),-2)':'if(gte(iw,ih),-2,min(2048,ih))'`,\n '-frames:v', String(frames), '-start_number', '0',\n path.join(dir, '%06d.png'),\n ]);\n const files = fs.readdirSync(dir).filter((f) => f.endsWith('.png')).sort().map((f) => path.join(dir, f));\n if (code !== 0 || !files.length) throw new Error(`ffmpeg could not decode the video at ${file}: ${stderr.trim() || `exit ${code}`}`);\n return files;\n}\n\n/**\n * Renders a catalog effect (by id or definition), applied to `subject`, to\n * a file: a shader through WebGL2 in headless Chrome, a vector effect by\n * drawing each frame's SVG there, or (to `.svg`) a vector effect as one\n * animated SVG with no browser at all. MP4, WebM, MOV and video subjects\n * need ffmpeg. Throws a sentence when the effect is unknown, takes no such\n * subject, or cannot be written in that format.\n *\n * ```ts\n * await exportEffect(\"image-duotone\", { subject: { image: \"team.jpg\" }, preset: \"Spotify\", outputPath: \"team.mp4\" });\n * await exportEffect(\"click-ripple\", { alpha: true, outputPath: \"ripple.webm\" });\n * await exportEffect(\"typewriter\", { subject: { text: \"Hello\" }, outputPath: \"hello.gif\" });\n * await exportEffect(\"toggle-switch\", { outputPath: \"toggle.svg\" });\n * ```\n */\nexport async function exportEffect(effect: string | EffectDefinition, options: EffectExportOptions): Promise<string> {\n const def = resolveEffect(effect);\n if (options.preset && !def.presets?.some((p) => p.name === options.preset)) {\n const names = def.presets?.map((p) => `\"${p.name}\"`).join(', ');\n throw new Error(`\"${def.id}\" has no preset \"${options.preset}\"; ${names ? `its presets are ${names}` : 'it has no presets'}.`);\n }\n const fromSubject = options.subject ? await nodeSubjectValues(def, options.subject) : { values: {}, video: {} };\n const explicit = await checkEffectValues(def, options.values ?? {});\n const values = { ...effectDefaults(def, options.preset ? { preset: options.preset } : {}), ...fromSubject.values, ...explicit };\n const fps = options.fps ?? 30;\n const background = options.background ?? (def.kind === 'vector' ? '#ffffff' : '#000000');\n\n if (def.kind === 'vector') {\n const motion = renderVectorEffect(def, values);\n const timeline = vectorTimeline(def, motion);\n const duration = options.duration ?? timeline.length / 1000;\n const frames = Math.max(1, Math.round(duration * fps));\n const plan = planOutput(options.outputPath, { alpha: options.alpha, frames });\n if (plan.format === 'svg') {\n const markup = svgAnimatedMarkup(motion, {\n ...(def.hold !== undefined ? { hold: def.hold } : {}),\n ...(timeline.steps.length ? { steps: timeline.steps, duration: timeline.length } : {}),\n ...(options.duration !== undefined ? { duration: options.duration * 1000 } : {}),\n fps,\n });\n if (!markup) throw new Error(`\"${def.id}\" has no <svg> to write.`);\n // A file gets a size of its own (it fills its container otherwise); a background only when asked for.\n const size = defaultSize(def, motion);\n const w = Math.round(options.width ?? size.width);\n const h = Math.round(options.height ?? (options.width ? (options.width * size.height) / size.width : size.height));\n const style = !plan.alpha && options.background ? ` style=\"background:${options.background.replace(/[\"<>&]/g, '')}\"` : '';\n const out = markup.replace(/^<svg\\b[^>]*>/, (open) =>\n open.replace(/\\swidth=\"100%\"/, ` width=\"${w}\"`).replace(/\\sheight=\"100%\"/, ` height=\"${h}\"`).replace(/>$/, `${style}>`),\n );\n fs.mkdirSync(path.dirname(plan.path), { recursive: true });\n fs.writeFileSync(plan.path, out, 'utf8');\n options.onProgress?.(1, 1);\n return plan.path;\n }\n const size = defaultSize(def, motion);\n const width = Math.max(1, Math.round(options.width ?? size.width));\n const height = Math.max(1, Math.round(options.height ?? (options.width ? (options.width * size.height) / size.width : size.height)));\n const base = frameStates(frames, fps, width, height, 'none');\n const pointer = options.pointer ?? 'auto';\n const state = (i: number): FrameState => {\n const ms = (i / fps) * 1000;\n const { time, steps } = pointer === 'none' && def.trigger ? { time: 0, steps: [] } : timeline.at(ms);\n return { ...base[i]!, svg: svgFrameMarkup(motion, { at: time, steps })! };\n };\n return runRender({\n page: { width, height, frames, alpha: plan.alpha, background, send: plan.format === 'gif' ? 'rgba' : 'png' },\n state,\n plan,\n fps,\n ...(options.onProgress ? { onProgress: options.onProgress } : {}),\n });\n }\n\n // A shader.\n const videoEntries = Object.entries(fromSubject.video);\n let duration = options.duration;\n if (duration === undefined && videoEntries.length) {\n const seconds = await videoSeconds(videoEntries[0]![1]);\n duration = seconds ? Math.min(10, seconds) : undefined;\n }\n duration ??= def.loop && def.loop <= 12 ? def.loop : 3;\n const frames = Math.max(1, Math.round(duration * fps));\n const plan = planOutput(options.outputPath, { alpha: options.alpha, frames });\n if (plan.format === 'svg') {\n throw new Error(`\"${def.id}\" is a shader effect, which draws pixels; write .mp4, .webm, .mov, .gif or .png frames (only vector effects become SVG).`);\n }\n const size = defaultSize(def);\n const width = Math.max(1, Math.round(options.width ?? size.width));\n const height = Math.max(1, Math.round(options.height ?? (options.width ? (options.width * size.height) / size.width : size.height)));\n const interactive = effectInputs(def).interactions.length > 0;\n const states = frameStates(frames, fps, width, height, options.pointer ?? (interactive ? 'auto' : 'none'));\n\n const tmp = videoEntries.length ? fs.mkdtempSync(path.join(os.tmpdir(), 'flair-video-')) : undefined;\n try {\n const videoFrames: Record<string, string[]> = {};\n for (const [name, file] of videoEntries) videoFrames[name] = await extractVideoFrames(file, fps, frames, path.join(tmp!, name));\n const state = (i: number): FrameState => {\n if (!videoEntries.length) return states[i]!;\n const video = Object.fromEntries(Object.entries(videoFrames).map(([name, files]) => [name, files[Math.min(i, files.length - 1)]!]));\n return { ...states[i]!, video };\n };\n return await runRender({\n page: {\n width,\n height,\n frames,\n alpha: plan.alpha,\n background,\n send: plan.format === 'gif' ? 'rgba' : 'png',\n shader: {\n fragment: wrapSource(def.source),\n controls: await pageControls(def.source, values),\n opaque: !plan.alpha && !def.transparent,\n },\n },\n state,\n plan,\n fps,\n ...(options.onProgress ? { onProgress: options.onProgress } : {}),\n });\n } finally {\n if (tmp) fs.rmSync(tmp, { recursive: true, force: true });\n }\n}\n\n// ==========================================\n// Command-line helpers\n// ==========================================\n\n/** `\"1280x720\"` → `{ width: 1280, height: 720 }`; a sentence for anything else. */\nexport function parseSize(size: string): { width: number; height: number } {\n const m = /^\\s*(\\d+)\\s*[x×X]\\s*(\\d+)\\s*$/.exec(size);\n if (!m || Number(m[1]) < 1 || Number(m[2]) < 1) throw new Error(`--size takes width x height in pixels, like 1280x720, not \"${size}\".`);\n return { width: Number(m[1]), height: Number(m[2]) };\n}\n\n/**\n * A `--set` value read for its control: numbers for `float` and `int`,\n * `true`/`false` (or 1/0) for `bool`, a colour (`#77C16A`, `rgb(…)`) or\n * numbers separated by commas or spaces for vectors, and the text itself\n * for images (a path or URL) and text.\n */\nexport function parseSetValue(control: ControlDef, raw: string): ControlValue {\n const text = raw.trim();\n switch (control.type) {\n case 'float':\n case 'int': {\n const n = Number(text);\n if (text === '' || !Number.isFinite(n)) throw new Error(`${control.name} takes a number, not \"${raw}\".`);\n return n;\n }\n case 'bool': {\n if (/^(true|1|yes|on)$/i.test(text)) return true;\n if (/^(false|0|no|off)$/i.test(text)) return false;\n throw new Error(`${control.name} takes true or false, not \"${raw}\".`);\n }\n case 'sampler2D':\n case 'text':\n return raw;\n default: {\n if (control.color && (parseColor(text) || /^currentcolor$/i.test(text)) && !/^[-\\d.]+([\\s,]+[-\\d.]+)*$/.test(text)) return text;\n const parts = text.split(/[\\s,]+/).filter(Boolean).map(Number);\n if (!parts.length || parts.some((n) => !Number.isFinite(n))) {\n throw new Error(`${control.name} takes ${control.type === 'vec2' ? 2 : control.type === 'vec3' ? 3 : 4} numbers separated by commas${control.color ? ', or a colour like \"#77C16A\"' : ''}, not \"${raw}\".`);\n }\n return parts;\n }\n }\n}\n\n/** `--set name=value` flags as control values for an effect; sentences for unknown names and bad values. */\nexport function parseSets(effect: EffectDefinition, sets: readonly string[]): Record<string, ControlValue> {\n const controls = new Map(effectControls(effect).map((c) => [c.name, c]));\n const out: Record<string, ControlValue> = {};\n for (const set of sets) {\n const eq = set.indexOf('=');\n if (eq <= 0) throw new Error(`--set takes name=value, like --set uSpeed=2, not \"${set}\".`);\n const name = set.slice(0, eq).trim();\n const control = controls.get(name);\n if (!control) throw new Error(`\"${effect.id}\" has no control \"${name}\"; it has ${[...controls.keys()].join(', ') || 'none'}.`);\n out[name] = parseSetValue(control, set.slice(eq + 1));\n }\n return out;\n}\n\n/** The render command's subject flags. */\nexport interface SubjectFlags {\n image?: readonly string[];\n svg?: readonly string[];\n text?: readonly string[];\n path?: readonly string[];\n video?: readonly string[];\n font?: string;\n weight?: string;\n}\n\n/** Subjects from the render command's flags, in the order images, SVGs, videos, texts, paths. */\nexport function subjectsFromFlags(flags: SubjectFlags): NodeSubject[] {\n const weight = flags.weight === undefined ? undefined : /^\\d+$/.test(flags.weight) ? Number(flags.weight) : flags.weight;\n return [\n ...(flags.image ?? []).map((image) => ({ image })),\n ...(flags.svg ?? []).map((svg) => ({ svg })),\n ...(flags.video ?? []).map((video) => ({ video })),\n ...(flags.text ?? []).map((text) => ({ text, ...(flags.font ? { font: flags.font } : {}), ...(weight !== undefined ? { weight } : {}) })),\n ...(flags.path ?? []).map((p) => ({ path: p })),\n ];\n}\n\n/** Comma-separated (or repeated) flag values checked against a list; a sentence for the rest. */\nexport function parseChoices<T extends string>(flag: string, values: readonly string[] | undefined, allowed: readonly T[]): T[] | undefined {\n if (!values?.length) return undefined;\n const list = values.flatMap((v) => v.split(',')).map((v) => v.trim()).filter(Boolean);\n const bad = list.filter((v) => !(allowed as readonly string[]).includes(v));\n if (bad.length) throw new Error(`${flag} takes ${allowed.join(', ')}; not ${bad.map((b) => `\"${b}\"`).join(', ')}.`);\n return list as T[];\n}\n\n/** The effects command's filters, checked. */\nexport function effectQueryFromFlags(flags: { accepts?: readonly string[]; interaction?: readonly string[]; category?: string; kind?: string; search?: string; transparent?: boolean }) {\n const accepts = parseChoices<EffectInput>('--accepts', flags.accepts, EFFECT_INPUTS);\n const interaction = parseChoices<EffectInteraction>('--interaction', flags.interaction, EFFECT_INTERACTIONS);\n if (flags.category && !(EFFECT_CATEGORIES as readonly string[]).includes(flags.category)) {\n throw new Error(`--category takes one of ${EFFECT_CATEGORIES.join(', ')}; not \"${flags.category}\".`);\n }\n if (flags.kind && flags.kind !== 'shader' && flags.kind !== 'vector') throw new Error(`--kind takes shader or vector; not \"${flags.kind}\".`);\n return {\n ...(accepts ? { accepts } : {}),\n ...(interaction ? { interaction } : {}),\n ...(flags.category ? { category: flags.category as EffectCategory } : {}),\n ...(flags.kind ? { kind: flags.kind as 'shader' | 'vector' } : {}),\n ...(flags.search ? { text: flags.search } : {}),\n ...(flags.transparent !== undefined ? { transparent: flags.transparent } : {}),\n };\n}\n\n/** One line about an effect for the effects command: id, kind, category, and what it takes. */\nexport function describeEffect(effect: EffectDefinition): string {\n const inputs = effectInputs(effect);\n const parts = [\n `${effect.kind}/${effect.category}`,\n `takes ${inputs.accepts.join(', ') || 'nothing'}`,\n ...(inputs.video ? [`video: ${inputs.video}`] : []),\n ...(inputs.interactions.length ? [`answers ${inputs.interactions.join(', ')}`] : []),\n ...(inputs.transparent ? ['overlay'] : []),\n ...(effect.presets?.length ? [`presets: ${effect.presets.map((p) => p.name).join(', ')}`] : []),\n ];\n return `${effect.id.padEnd(24)} ${parts.join(' · ')}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAS,aAAa;AACtB,OAAO,QAAQ;AACf,OAAO,QAAQ;AACf,OAAO,UAAU;AAkFjB,IAAM,QAAQ,CAAC,MAAc,mBAAmB,KAAK,CAAC;AAGtD,eAAe,UAAU,KAA8B;AACrD,QAAM,OAAO,IAAI,KAAK;AACtB,MAAI,KAAK,WAAW,GAAG,EAAG,QAAO;AACjC,MAAI,yBAAyB,KAAK,IAAI,GAAG;AACvC,UAAM,QAAQ,KAAK,QAAQ,GAAG;AAC9B,UAAM,OAAO,KAAK,MAAM,GAAG,KAAK;AAChC,UAAM,OAAO,KAAK,MAAM,QAAQ,CAAC;AACjC,WAAO,WAAW,KAAK,IAAI,IAAI,OAAO,KAAK,MAAM,QAAQ,EAAE,SAAS,MAAM,IAAI,mBAAmB,IAAI;AAAA,EACvG;AACA,MAAI,YAAY,KAAK,IAAI,GAAG;AAC1B,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Y,IAAI,CAAC;AAAA,EAC9E;AACF;AAGO,SAAS,eAAe,QAAkC;AAC/D,QAAM,SAAS,aAAa,MAAM;AAClC,QAAM,QAAQ;AAAA,IACZ,GAAG,OAAO,IAAI,IAAI,OAAO,QAAQ;AAAA,IACjC,SAAS,OAAO,QAAQ,KAAK,IAAI,KAAK,SAAS;AAAA,IAC/C,GAAI,OAAO,QAAQ,CAAC,UAAU,OAAO,KAAK,EAAE,IAAI,CAAC;AAAA,IACjD,GAAI,OAAO,aAAa,SAAS,CAAC,WAAW,OAAO,aAAa,KAAK,IAAI,CAAC,EAAE,IAAI,CAAC;AAAA,IAClF,GAAI,OAAO,cAAc,CAAC,SAAS,IAAI,CAAC;AAAA,IACxC,GAAI,OAAO,SAAS,SAAS,CAAC,YAAY,OAAO,QAAQ,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,IAAI,CAAC,EAAE,IAAI,CAAC;AAAA,EAC/F;AACA,SAAO,GAAG,OAAO,GAAG,OAAO,EAAE,CAAC,IAAI,MAAM,KAAK,QAAK,CAAC;AACrD;","names":["length","duration","frames","plan","size","width","height"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/shader/renderer.ts","../src/shader/frames.ts"],"sourcesContent":["import { imageUrls, parseControls, type ControlDef, type ControlValue } from \"./controls.js\";\nimport {\n compileShader,\n createContext,\n drawFrame,\n resetGlCaches,\n type CompileError,\n type CompiledShader,\n} from \"./program.js\";\nimport { PointerTracker } from \"./pointer.js\";\nimport { TextureCache, type ImageLoadError, type LiveSource } from \"./textures.js\";\n\n/** Whether the latest source compiled, and if not, why. */\nexport interface CompileStatus {\n ok: boolean;\n errors: CompileError[];\n}\n\n/** What `onStats` reports: on play, pause, seek and restart, and twice a second while running. */\nexport interface RendererStats {\n /** `iTime`, in seconds. */\n time: number;\n /** Frames drawn per second over the last half second (0 while paused). */\n fps: number;\n playing: boolean;\n /** The drawing buffer's size in device pixels. */\n width: number;\n height: number;\n}\n\nexport interface ShaderRendererOptions {\n className?: string;\n /** Enable a transparent WebGL drawing buffer so shader alpha (`fragColor.a`) composites over the page (default false). */\n alpha?: boolean;\n /** Pause rendering when scrolled out of view via IntersectionObserver (default false). */\n pauseWhenHidden?: boolean;\n /** Start playing at once (default true). Set to false to start paused. */\n autoplay?: boolean;\n /** Wait to start playing until the canvas enters the viewport via IntersectionObserver (default false). When true, autoplay is deferred until first visible. */\n playOnEnter?: boolean;\n}\n\n/**\n * Runs one shader on a canvas: the editor's live preview. A source that does\n * not compile leaves the last working program on screen, so a typo never\n * blanks the preview; the errors are reported instead.\n *\n * The renderer owns its canvas (added to `host`, removed on dispose): a\n * canvas keeps its WebGL context for life, so reusing one after disposing\n * (a remount, hot reload) would get the released, lost context back.\n */\nexport class ShaderRenderer {\n readonly canvas: HTMLCanvasElement;\n private gl: WebGL2RenderingContext | null;\n private readonly alpha: boolean;\n private shader: CompiledShader | null = null;\n private textures: TextureCache | null = null;\n /** Live sources by image control, kept to set again on a restored context. */\n private live = new Map<string, LiveSource>();\n private controls: ControlDef[] = [];\n private values: Record<string, ControlValue> | undefined;\n private source = \"\";\n private raf = 0;\n private lastNow = 0;\n private frame = 0;\n private fpsFrames = 0;\n private fpsSince = 0;\n private ownsCanvas = false;\n private resizeObserver: ResizeObserver;\n private intersectionObserver?: IntersectionObserver;\n private wasPlayingBeforeHidden = false;\n private hasEnteredViewport = false;\n private mouse: [number, number, number, number] = [0, 0, 0, 0];\n /** `iPointer` and `iClicks`. */\n private pointer = new PointerTracker();\n private disposed = false;\n /** The latest source's status. */\n status: CompileStatus = { ok: true, errors: [] };\n /** `iTime`, in seconds. Use `seek` to change it. */\n time = 0;\n /** Playback speed: 1 is real time. */\n speed = 1;\n /** Device pixels per CSS pixel; lower renders faster. Use `setPixelRatio` to change it. */\n pixelRatio = Math.min(window.devicePixelRatio || 1, 2);\n playing = true;\n fps = 0;\n onStats?: (stats: RendererStats) => void;\n /** Called with `true` when the GL context is lost and `false` once it is restored and recompiled. */\n onContextLost?: (lost: boolean) => void;\n /** Called when an image control's URL (or live video) cannot be loaded; the control shows black. */\n onImageError?: (error: ImageLoadError) => void;\n\n /**\n * Creates a canvas in `target` (with `className` or options), or attaches to an existing\n * `HTMLCanvasElement`, and starts the animation loop. Size the canvas with CSS.\n */\n constructor(target: HTMLElement | HTMLCanvasElement, options?: string | ShaderRendererOptions) {\n const opts: ShaderRendererOptions =\n typeof options === \"string\" ? { className: options } : (options ?? {});\n let canvas: HTMLCanvasElement;\n if (target instanceof HTMLCanvasElement || (\"tagName\" in target && target.tagName === \"CANVAS\")) {\n canvas = target as HTMLCanvasElement;\n if (opts.className) canvas.className = opts.className;\n } else {\n canvas = document.createElement(\"canvas\");\n if (opts.className) canvas.className = opts.className;\n target.appendChild(canvas);\n this.ownsCanvas = true;\n }\n this.canvas = canvas;\n this.alpha = Boolean(opts.alpha);\n this.gl = createContext(canvas, true, this.alpha);\n this.textures = this.gl && this.textureCache(this.gl);\n this.resizeObserver = new ResizeObserver(() => this.resize());\n this.resizeObserver.observe(canvas);\n\n const needsObserver =\n (opts.pauseWhenHidden || opts.playOnEnter) && typeof IntersectionObserver !== \"undefined\";\n\n if (needsObserver) {\n this.intersectionObserver = new IntersectionObserver(([entry]) => {\n if (!entry) return;\n if (entry.isIntersecting) {\n if (opts.playOnEnter && !this.hasEnteredViewport) {\n this.hasEnteredViewport = true;\n if (opts.autoplay ?? true) {\n this.play();\n }\n } else if (this.wasPlayingBeforeHidden) {\n this.wasPlayingBeforeHidden = false;\n this.play();\n }\n } else {\n if (this.playing && opts.pauseWhenHidden) {\n this.wasPlayingBeforeHidden = true;\n this.pause();\n }\n }\n });\n this.intersectionObserver.observe(canvas);\n }\n\n const shouldAutoplay = (opts.autoplay ?? true) && !opts.playOnEnter;\n this.playing = shouldAutoplay;\n\n canvas.addEventListener(\"webglcontextlost\", this.onLost);\n canvas.addEventListener(\"webglcontextrestored\", this.onRestored);\n canvas.addEventListener(\"pointerdown\", this.onPointerDown);\n canvas.addEventListener(\"pointermove\", this.onPointerMove);\n canvas.addEventListener(\"pointerenter\", this.onPointerEnter);\n canvas.addEventListener(\"pointerleave\", this.onPointerLeave);\n window.addEventListener(\"pointerup\", this.onPointerUp);\n this.resize();\n this.raf = requestAnimationFrame(this.tick);\n }\n\n /** False when the browser has no WebGL2. */\n get supported(): boolean {\n return this.gl !== null;\n }\n\n /** Compiles a new source; returns its status. Keeps the previous program when it fails. */\n setSource(source: string): CompileStatus {\n this.source = source;\n const controls = parseControls(source);\n if (!this.gl) {\n this.status = {\n ok: false,\n errors: [{ line: 0, message: \"WebGL2 is not available in this browser.\" }],\n };\n return this.status;\n }\n const result = compileShader(this.gl, source, controls);\n if (result.ok) {\n if (this.shader) this.gl.deleteProgram(this.shader.program);\n this.shader = result.shader;\n this.controls = controls;\n this.status = { ok: true, errors: [] };\n } else {\n this.status = { ok: false, errors: result.errors };\n }\n this.syncTextures();\n if (!this.playing) this.render();\n return this.status;\n }\n\n /**\n * Sets control values (see `controlValue`); a paused preview redraws.\n * Images load in the background and show once they arrive: await\n * `ready()` before a `capture` that needs them.\n */\n setValues(values: Record<string, ControlValue> | undefined) {\n this.values = values;\n this.syncTextures();\n if (!this.playing) this.render();\n }\n\n /**\n * Shows a `<video>` (or a canvas) in the image control `name` (the\n * uniform's name, such as `uImage`) in place of its URL, frame by frame;\n * `null` goes back to the URL. The preview follows the video even while\n * the shader's own clock is paused, and the video plays, seeks and loops\n * on its own: the renderer never controls it. A video from another site\n * needs `crossOrigin = \"anonymous\"` and CORS, or `onImageError` hears why\n * it shows black. The value stays as it is, so documents, presets and\n * agents keep seeing the URL.\n */\n setLiveSource(name: string, source: LiveSource | null) {\n if (source) this.live.set(name, source);\n else this.live.delete(name);\n this.textures?.setLive(name, source);\n if (!this.playing) this.render();\n }\n\n /**\n * Settles once the images the current controls show have loaded, and\n * every live video has a frame. Rejects with an {@link ImageLoadError}\n * when one cannot be (it shows black).\n */\n async ready(): Promise<void> {\n await Promise.all([\n this.textures?.ready(imageUrls(this.controls, this.values)),\n this.textures?.liveReady(),\n ]);\n }\n\n play() {\n this.playing = true;\n this.emit();\n }\n\n pause() {\n this.playing = false;\n this.emit();\n }\n\n /** Back to `iTime` 0 and frame 0. */\n restart() {\n this.time = 0;\n this.pointer.clear();\n this.frame = 0;\n this.render();\n this.emit();\n }\n\n /** Jumps to `time` seconds (not below 0) and draws it. */\n seek(time: number) {\n // Clicks are stamped with iTime: going back would replay them.\n if (time < this.time) this.pointer.clear();\n this.time = Math.max(0, time);\n this.render();\n this.emit();\n }\n\n setPixelRatio(ratio: number) {\n this.pixelRatio = ratio;\n this.resize();\n }\n\n /**\n * Captures the current frame (optionally at another time) as a data URL\n * (JPEG unless `type` says PNG), at most `maxEdge` pixels on the long side\n * (default 1024). Playback time is left as it was. Null when nothing has\n * compiled yet.\n */\n capture(\n options: { time?: number; maxEdge?: number; type?: \"image/jpeg\" | \"image/png\" } = {},\n ): string | null {\n if (!this.gl || !this.shader) return null;\n const saved = this.time;\n if (options.time !== undefined) this.time = Math.max(0, options.time);\n this.render();\n const { width, height } = this.canvas;\n const scale = Math.min(1, (options.maxEdge ?? 1024) / Math.max(width, height));\n const out = document.createElement(\"canvas\");\n out.width = Math.max(1, Math.round(width * scale));\n out.height = Math.max(1, Math.round(height * scale));\n out.getContext(\"2d\")!.drawImage(this.canvas, 0, 0, out.width, out.height);\n this.time = saved;\n if (options.time !== undefined) this.render();\n return out.toDataURL(options.type ?? \"image/jpeg\", 0.85);\n }\n\n /** Stops the loop, releases the context and removes the canvas. The renderer cannot be used again. */\n dispose() {\n this.disposed = true;\n cancelAnimationFrame(this.raf);\n this.resizeObserver.disconnect();\n this.intersectionObserver?.disconnect();\n this.canvas.removeEventListener(\"webglcontextlost\", this.onLost);\n this.canvas.removeEventListener(\"webglcontextrestored\", this.onRestored);\n this.canvas.removeEventListener(\"pointerdown\", this.onPointerDown);\n this.canvas.removeEventListener(\"pointermove\", this.onPointerMove);\n this.canvas.removeEventListener(\"pointerenter\", this.onPointerEnter);\n this.canvas.removeEventListener(\"pointerleave\", this.onPointerLeave);\n window.removeEventListener(\"pointerup\", this.onPointerUp);\n if (this.gl && this.shader) this.gl.deleteProgram(this.shader.program);\n this.textures?.dispose();\n this.textures = null;\n // Free the context now rather than waiting for GC (browsers cap live contexts).\n this.gl?.getExtension(\"WEBGL_lose_context\")?.loseContext();\n this.gl = null;\n if (this.ownsCanvas) this.canvas.remove();\n }\n\n private resize() {\n // The layout size, not the bounding box: a rotated or scaled canvas keeps its own proportions.\n const w = Math.max(1, Math.round(this.canvas.clientWidth * this.pixelRatio));\n const h = Math.max(1, Math.round(this.canvas.clientHeight * this.pixelRatio));\n if (this.canvas.width !== w || this.canvas.height !== h) {\n this.canvas.width = w;\n this.canvas.height = h;\n this.render();\n }\n }\n\n private render(delta = 0) {\n if (!this.gl || !this.shader || this.gl.isContextLost()) return;\n drawFrame(\n this.gl,\n this.shader,\n this.controls,\n this.values,\n {\n width: this.canvas.width,\n height: this.canvas.height,\n time: this.time,\n delta,\n frame: this.frame,\n mouse: this.mouse,\n pointer: this.pointer.pointer(this.time),\n clicks: this.pointer.clicksAt(this.time),\n trail: this.pointer.trailAt(this.time),\n },\n this.textures ?? undefined,\n );\n }\n\n private textureCache(gl: WebGL2RenderingContext): TextureCache {\n const cache = new TextureCache(gl, (_url, error) => {\n if (error) this.onImageError?.(error);\n else if (!this.playing) this.render();\n });\n for (const [name, source] of this.live) cache.setLive(name, source);\n return cache;\n }\n\n /** Starts loading the images now shown, and frees the ones no longer shown. */\n private syncTextures() {\n if (!this.textures) return;\n const urls = imageUrls(this.controls, this.values);\n this.textures.retain(urls);\n for (const url of urls) this.textures.request(url);\n }\n\n private tick = (now: number) => {\n if (this.disposed) return;\n this.raf = requestAnimationFrame(this.tick);\n const delta = this.lastNow ? Math.min((now - this.lastNow) / 1000, 0.1) : 0;\n this.lastNow = now;\n if (this.playing) {\n this.time += delta * this.speed;\n this.frame += 1;\n this.render(delta * this.speed);\n this.fpsFrames += 1;\n } else if (this.textures?.liveChanged()) {\n // A live video moved on (played, seeked or loaded) while the clock is paused.\n this.render();\n }\n if (now - this.fpsSince >= 500) {\n this.fps = this.playing\n ? Math.round((this.fpsFrames * 1000) / (now - this.fpsSince || 1))\n : 0;\n this.fpsFrames = 0;\n this.fpsSince = now;\n this.emit();\n }\n };\n\n private emit() {\n this.onStats?.({\n time: this.time,\n fps: this.fps,\n playing: this.playing,\n width: this.canvas.width,\n height: this.canvas.height,\n });\n }\n\n /** Pointer position in shader pixels (origin bottom-left, like gl_FragCoord). */\n private toPixels(e: PointerEvent): [number, number] {\n const rect = this.canvas.getBoundingClientRect();\n return [\n (e.clientX - rect.left) * (this.canvas.width / rect.width),\n (rect.bottom - e.clientY) * (this.canvas.height / rect.height),\n ];\n }\n\n private onPointerDown = (e: PointerEvent) => {\n const [x, y] = this.toPixels(e);\n this.mouse = [x, y, x, y];\n this.pointer.down(x, y, this.time);\n if (!this.playing) this.render();\n };\n\n private onPointerMove = (e: PointerEvent) => {\n const [x, y] = this.toPixels(e);\n this.pointer.move(x, y, this.time);\n if (this.mouse[2] <= 0 || e.buttons === 0) {\n if (!this.playing) this.render();\n return;\n }\n this.mouse = [x, y, this.mouse[2], this.mouse[3]];\n if (!this.playing) this.render();\n };\n\n private onPointerEnter = (e: PointerEvent) => {\n this.pointer.move(...this.toPixels(e), this.time);\n this.pointer.hover(true, this.time);\n };\n\n private onPointerLeave = () => {\n this.pointer.hover(false, this.time);\n };\n\n private onPointerUp = () => {\n this.pointer.up(this.time);\n if (this.mouse[2] > 0)\n this.mouse = [this.mouse[0], this.mouse[1], -this.mouse[2], -Math.abs(this.mouse[3])];\n };\n\n private onLost = (e: Event) => {\n e.preventDefault();\n this.shader = null;\n this.textures?.dispose();\n this.textures = null;\n this.onContextLost?.(true);\n };\n\n private onRestored = () => {\n resetGlCaches();\n this.gl = createContext(this.canvas, true, this.alpha);\n this.textures = this.gl && this.textureCache(this.gl);\n this.setSource(this.source);\n this.onContextLost?.(false);\n };\n}\n","import { imageUrls, parseControls, type ControlDef, type ControlValue } from \"./controls.js\";\nimport {\n compileShader,\n createContext,\n drawFrame,\n ShaderCompileError,\n type CompiledShader,\n} from \"./program.js\";\nimport { clicksUniform, trailUniform, type ShaderClick } from \"./pointer.js\";\nimport { TextureCache, type LiveSource } from \"./textures.js\";\n\nexport interface ShaderFramesOptions {\n source: string;\n values?: Record<string, ControlValue>;\n width: number;\n height: number;\n /** Draw on this canvas instead of a new, detached one. It is resized to `width` × `height`. */\n canvas?: HTMLCanvasElement;\n /** Keep the shader's alpha (`fragColor.a`) in the frames, for transparent recordings (default false: opaque). */\n alpha?: boolean;\n}\n\nexport interface RenderOptions {\n /** `iFrame` (default: the number of frames rendered so far). */\n frame?: number;\n /** `iTimeDelta` in seconds (default: the time since the previous `render`, else 0). */\n delta?: number;\n /** `iMouse` (default: all zero, as on a page nobody has touched). */\n mouse?: [number, number, number, number];\n /** `iPointer`: x, y, how hovered (0–1), the press (seconds held, or minus seconds since release; default all zero). */\n pointer?: [number, number, number, number];\n /** Clicks so far, for `iClicks` (the latest `MAX_CLICKS` at or before the frame's time count). */\n clicks?: readonly ShaderClick[];\n /** Where the pointer has been, oldest first, for `iTrail` (the latest `MAX_TRAIL` at or before the frame's time count). */\n trail?: readonly ShaderClick[];\n}\n\n/**\n * Renders a shader at exact times you choose, off screen. There is no\n * animation loop and no clock: frame `n` of a recording at `fps` is\n * `render(start + n / fps)`, so the output is the same on any machine. It\n * suits recorders, video pipelines and anything else stepped by its own\n * clock. The constructor throws a {@link ShaderCompileError} when the source\n * does not compile.\n *\n * Image controls load in the background: `await frames.ready()` before the\n * first `render`, or the frames show black where the images go.\n *\n * A video in an image control (see `setLiveSource`) is drawn at whatever\n * frame it is on. To step it with the shader, seek it first: `await\n * seekVideo(video, t); frames.render(t)`.\n */\nexport class ShaderFrames {\n readonly canvas: HTMLCanvasElement;\n readonly width: number;\n readonly height: number;\n readonly controls: ControlDef[];\n private gl: WebGL2RenderingContext | null;\n private shader: CompiledShader;\n private textures: TextureCache;\n private values: Record<string, ControlValue> | undefined;\n private rendered = 0;\n private lastTime: number | null = null;\n private pixels: Uint8Array;\n\n constructor(options: ShaderFramesOptions) {\n const { source, values, width, height } = options;\n this.width = Math.max(1, Math.round(width));\n this.height = Math.max(1, Math.round(height));\n this.canvas = options.canvas ?? document.createElement(\"canvas\");\n this.canvas.width = this.width;\n this.canvas.height = this.height;\n this.values = values;\n const gl = createContext(this.canvas, true, Boolean(options.alpha));\n if (!gl) throw new Error(\"WebGL2 is not available in this browser.\");\n this.gl = gl;\n this.controls = parseControls(source);\n const compiled = compileShader(gl, source, this.controls);\n if (!compiled.ok) {\n this.dispose();\n throw new ShaderCompileError(compiled.errors);\n }\n this.shader = compiled.shader;\n this.textures = new TextureCache(gl);\n this.syncTextures();\n this.pixels = new Uint8Array(this.width * this.height * 4);\n }\n\n /** Changes control values for the frames that follow. */\n setValues(values: Record<string, ControlValue> | undefined) {\n this.values = values;\n this.syncTextures();\n }\n\n /**\n * Draws a `<video>` (or a canvas) in the image control `name` instead of\n * its URL, at the frame it is on when `render` runs; `null` goes back to\n * the URL. See `ShaderRenderer.setLiveSource`.\n */\n setLiveSource(name: string, source: LiveSource | null) {\n this.textures.setLive(name, source);\n }\n\n /**\n * Settles once every image the controls show has loaded, and every live\n * video has a frame. Rejects with an {@link ImageLoadError} when one\n * cannot be.\n */\n async ready(): Promise<void> {\n await Promise.all([this.textures.ready(imageUrls(this.controls, this.values)), this.textures.liveReady()]);\n }\n\n /** Draws the frame at `time` seconds onto `canvas`. */\n render(time: number, options: RenderOptions = {}) {\n const gl = this.context();\n const delta = options.delta ?? (this.lastTime === null ? 0 : time - this.lastTime);\n drawFrame(\n gl,\n this.shader,\n this.controls,\n this.values,\n {\n width: this.width,\n height: this.height,\n time,\n delta,\n frame: options.frame ?? this.rendered,\n mouse: options.mouse ?? [0, 0, 0, 0],\n pointer: options.pointer,\n clicks: options.clicks && clicksUniform(options.clicks, time),\n trail: options.trail && trailUniform(options.trail, time),\n },\n this.textures,\n );\n this.rendered += 1;\n this.lastTime = time;\n }\n\n /**\n * The last rendered frame as RGBA bytes, rows top down (as in `ImageData`;\n * WebGL itself reads bottom up). Pass `out` to reuse a buffer of\n * `width * height * 4` bytes.\n */\n readPixels(out?: Uint8Array | Uint8ClampedArray): Uint8Array | Uint8ClampedArray {\n const gl = this.context();\n const { width, height } = this;\n const target = out ?? new Uint8Array(width * height * 4);\n if (target.length !== width * height * 4) {\n throw new RangeError(`readPixels needs a buffer of ${width * height * 4} bytes.`);\n }\n gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, this.pixels);\n const row = width * 4;\n for (let y = 0; y < height; y++) {\n target.set(this.pixels.subarray((height - 1 - y) * row, (height - y) * row), y * row);\n }\n return target;\n }\n\n /** Releases the GL context now rather than at garbage collection (browsers cap live contexts). */\n dispose() {\n if (!this.gl) return;\n if (this.shader) this.gl.deleteProgram(this.shader.program);\n this.textures?.dispose();\n this.gl.getExtension(\"WEBGL_lose_context\")?.loseContext();\n this.gl = null;\n }\n\n private syncTextures() {\n const urls = imageUrls(this.controls, this.values);\n this.textures.retain(urls);\n for (const url of urls) this.textures.request(url);\n }\n\n private context(): WebGL2RenderingContext {\n if (!this.gl) throw new Error(\"These frames have been disposed.\");\n if (this.gl.isContextLost()) throw new Error(\"The graphics context was lost.\");\n return this.gl;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmDO,IAAM,iBAAN,MAAqB;AAAA,EACjB;AAAA,EACD;AAAA,EACS;AAAA,EACT,SAAgC;AAAA,EAChC,WAAgC;AAAA;AAAA,EAEhC,OAAO,oBAAI,IAAwB;AAAA,EACnC,WAAyB,CAAC;AAAA,EAC1B;AAAA,EACA,SAAS;AAAA,EACT,MAAM;AAAA,EACN,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,aAAa;AAAA,EACb;AAAA,EACA;AAAA,EACA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;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/export/recorder.ts"],"sourcesContent":["// gifenc ships without types; the reference brings them along.\n/// <reference path=\"../shader/gifenc.d.ts\" />\nimport http from 'node:http';\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { controlValue, parseControls, type ControlValue, type TextureSettings } from '../shader/controls.js';\nimport { MAX_CLICKS, MAX_TRAIL, PointerTracker, TRAIL_SECONDS } from '../shader/pointer.js';\nimport { VERTEX_SOURCE, wrapSource } from '../shader/program.js';\nimport { SVG_EDGE } from '../shader/textures.js';\n\n// ==========================================\n// Tools: Chrome and ffmpeg\n// ==========================================\n\nconst CHROME_CANDIDATES = [\n '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',\n '/Applications/Chromium.app/Contents/MacOS/Chromium',\n 'C:\\\\Program Files\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe',\n '/usr/bin/google-chrome',\n '/usr/bin/google-chrome-stable',\n '/usr/bin/chromium',\n '/usr/bin/chromium-browser',\n];\n\n/** Chromium builds Playwright downloaded (`npx playwright install chromium`), newest first. */\nfunction playwrightChromes(): string[] {\n const roots = [\n process.env.PLAYWRIGHT_BROWSERS_PATH,\n path.join(os.homedir(), 'Library/Caches/ms-playwright'),\n path.join(os.homedir(), '.cache/ms-playwright'),\n ].filter((r): r is string => Boolean(r));\n const found: string[] = [];\n for (const root of roots) {\n let dirs: string[] = [];\n try {\n dirs = fs.readdirSync(root).filter((d) => /^chromium-\\d+$/.test(d));\n } catch {\n continue;\n }\n dirs.sort((a, b) => Number(b.split('-')[1]) - Number(a.split('-')[1]));\n for (const dir of dirs) {\n for (const bin of [\n 'chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing',\n 'chrome-mac/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing',\n 'chrome-mac/Chromium.app/Contents/MacOS/Chromium',\n 'chrome-linux/chrome',\n 'chrome-linux64/chrome',\n ]) found.push(path.join(root, dir, bin));\n }\n }\n return found;\n}\n\n/**\n * Finds a local Chrome or Chromium executable, or `null`: `CHROME_PATH` (or\n * `CHROME_BIN`), then the usual install places, then a Chromium Playwright\n * downloaded.\n */\nexport function findChrome(): string | null {\n const env = process.env.CHROME_PATH || process.env.CHROME_BIN;\n if (env) return env;\n return [...CHROME_CANDIDATES, ...playwrightChromes()].find((candidate) => fs.existsSync(candidate)) ?? null;\n}\n\n/** The ffmpeg to run: `FFMPEG_PATH`, else `ffmpeg` on the `PATH`. */\nexport function ffmpegPath(): string {\n return process.env.FFMPEG_PATH || 'ffmpeg';\n}\n\nconst NO_FFMPEG =\n 'ffmpeg is not installed (or not on the PATH). Install it (brew install ffmpeg, apt install ffmpeg), or set FFMPEG_PATH; GIF, PNG and SVG output do not need it.';\n\n// ==========================================\n// Output formats\n// ==========================================\n\n/** A file type the exporter writes, from the output path. */\nexport type OutputFormat = 'mp4' | 'webm' | 'mov' | 'gif' | 'png' | 'svg';\n\n/** What to write and how. */\nexport interface OutputPlan {\n format: OutputFormat;\n /** The output path, resolved. For a PNG sequence, a printf pattern (`…/frame_%04d.png`). */\n path: string;\n /** Whether the frames keep their alpha. */\n alpha: boolean;\n /** ffmpeg's arguments after the input (for mp4, webm and mov). */\n ffmpegArgs?: string[];\n}\n\n/**\n * Works out the format from `outputPath`'s extension and what alpha it can\n * keep. A path with no extension, or ending in a slash, is a folder of PNG\n * frames; a `.png` path with a `%d` pattern (`out_%04d.png`) names each\n * frame, and one without gets `_%04d` added (unless there is one frame).\n * Throws a sentence for formats it cannot write, and for alpha in MP4.\n */\nexport function planOutput(outputPath: string, options: { alpha?: boolean; frames?: number } = {}): OutputPlan {\n const resolved = path.resolve(process.cwd(), outputPath);\n const trailingSlash = /[\\\\/]$/.test(outputPath);\n const ext = trailingSlash ? '' : path.extname(resolved).toLowerCase();\n const alpha = Boolean(options.alpha);\n switch (ext) {\n case '': {\n return { format: 'png', path: path.join(resolved, 'frame_%04d.png'), alpha };\n }\n case '.png': {\n if (/%0?\\d*d/.test(resolved) || (options.frames ?? 2) === 1) return { format: 'png', path: resolved, alpha };\n return { format: 'png', path: resolved.replace(/\\.png$/i, '_%04d.png'), alpha };\n }\n case '.gif':\n return { format: 'gif', path: resolved, alpha };\n case '.svg':\n return { format: 'svg', path: resolved, alpha };\n case '.mp4':\n case '.m4v': {\n if (alpha) throw new Error('MP4 (H.264) cannot hold alpha; write .webm, .mov, .gif or .png frames for a transparent render, or drop --alpha.');\n return {\n format: 'mp4',\n path: resolved,\n alpha,\n ffmpegArgs: [\n // yuv420p needs even sizes; sRGB pixels go to BT.709, tagged so players show the same colours.\n '-vf', 'pad=ceil(iw/2)*2:ceil(ih/2)*2,scale=out_color_matrix=bt709:out_range=tv,format=yuv420p',\n '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '18', '-preset', 'medium',\n '-colorspace', 'bt709', '-color_primaries', 'bt709', '-color_trc', 'bt709', '-color_range', 'tv',\n '-movflags', '+faststart',\n ],\n };\n }\n case '.webm':\n return {\n format: 'webm',\n path: resolved,\n alpha,\n ffmpegArgs: alpha\n ? ['-c:v', 'libvpx-vp9', '-pix_fmt', 'yuva420p', '-b:v', '0', '-crf', '30', '-auto-alt-ref', '0', '-row-mt', '1']\n : ['-vf', 'scale=out_color_matrix=bt709:out_range=tv,format=yuv420p', '-c:v', 'libvpx-vp9', '-pix_fmt', 'yuv420p', '-b:v', '0', '-crf', '30', '-row-mt', '1',\n '-colorspace', 'bt709', '-color_primaries', 'bt709', '-color_trc', 'bt709'],\n };\n case '.mov':\n return {\n format: 'mov',\n path: resolved,\n alpha,\n ffmpegArgs: [\n '-c:v', 'prores_ks', '-profile:v', '4444', '-vendor', 'apl0',\n '-pix_fmt', alpha ? 'yuva444p10le' : 'yuv444p10le',\n ...(alpha ? ['-alpha_bits', '16'] : []),\n '-colorspace', 'bt709', '-color_primaries', 'bt709', '-color_trc', 'bt709',\n ],\n };\n default:\n throw new Error(`Flair cannot write \"${ext}\" files; write .mp4, .webm, .mov, .gif, .svg, or .png frames (a folder, or a pattern like out_%04d.png).`);\n }\n}\n\n/** A frame number put into a PNG sequence's printf pattern (`%04d`, `%d`). */\nexport function sequencePath(pattern: string, frame: number): string {\n return pattern.replace(/%(0?)(\\d*)d/, (_, zero: string, width: string) => String(frame).padStart(Number(width || 0), zero ? '0' : ' '));\n}\n\n// ==========================================\n// The pointer, scripted\n// ==========================================\n\n/** Pointer uniforms for one frame. */\nexport interface PointerFrame {\n mouse: [number, number, number, number];\n pointer: [number, number, number, number];\n /** `iClicks`, MAX_CLICKS × 4 numbers. */\n clicks: number[];\n /** `iTrail`, MAX_TRAIL × 4 numbers. */\n trail: number[];\n}\n\n/**\n * A pointer that shows off an interactive shader in a recording: it hovers\n * over the canvas from the start, wanders a figure-of-eight (so trails have\n * a path), and clicks every `interval` seconds, holding each press for a\n * moment. Returns the uniforms for each frame time, in order.\n */\nexport function scriptedPointer(width: number, height: number, times: readonly number[], options: { interval?: number; period?: number } = {}): PointerFrame[] {\n const interval = options.interval ?? 0.8;\n const period = Math.max(2, options.period ?? (times[times.length - 1] ?? 2));\n const at = (t: number): [number, number] => [\n width * (0.5 + 0.3 * Math.sin((2 * Math.PI * t) / period)),\n height * (0.5 + 0.22 * Math.sin((4 * Math.PI * t) / period)),\n ];\n const press = 0.25;\n const tracker = new PointerTracker();\n tracker.hover(true, 0);\n tracker.move(...at(0), 0);\n let clock = 0;\n let nextClick = 0.25;\n let release = Infinity;\n let mouse: [number, number, number, number] = [0, 0, 0, 0];\n const frames: PointerFrame[] = [];\n for (const time of times) {\n // Walk the script up to `time` in trail-sized steps, so the trail and clicks land where they would live.\n while (clock < time) {\n const next = Math.min(time, clock + TRAIL_SECONDS, nextClick, release);\n clock = next;\n const [x, y] = at(clock);\n tracker.move(x, y, clock);\n if (mouse[2] > 0) mouse = [x, y, mouse[2], mouse[3]];\n if (clock >= release) {\n tracker.up(clock);\n mouse = [mouse[0], mouse[1], -mouse[2], -Math.abs(mouse[3])];\n release = Infinity;\n }\n if (clock >= nextClick) {\n tracker.down(x, y, clock);\n mouse = [x, y, x, y];\n release = clock + press;\n nextClick = clock + interval;\n }\n }\n frames.push({\n mouse: [...mouse],\n pointer: tracker.pointer(time),\n clicks: [...tracker.clicksAt(time)],\n trail: [...tracker.trailAt(time)],\n });\n }\n return frames;\n}\n\n// ==========================================\n// The page\n// ==========================================\n\n/** A shader control as the page sets it. */\nexport interface PageControl {\n name: string;\n type: string;\n value: ControlValue;\n texture?: TextureSettings;\n}\n\n/** What the render page draws. */\nexport interface PageConfig {\n width: number;\n height: number;\n frames: number;\n /** Keep alpha in the frames (else they are composited over `background`). */\n alpha: boolean;\n /** CSS colour under transparent pixels when `alpha` is false. */\n background: string;\n /** How frames go back: PNG files, or raw RGBA (rows top down). */\n send: 'png' | 'rgba';\n /** A shader to run, or (when absent) SVG frame markup from `/state`. */\n shader?: {\n /** The full GLSL ES 3.00 fragment shader (see {@link fragmentSource}). */\n fragment: string;\n controls: PageControl[];\n /** Draws its frame opaque, as `ShaderRenderer` does without `alpha`: its own alpha is ignored. */\n opaque: boolean;\n };\n}\n\n/** JSON that is safe inside a `<script>`. */\nconst scriptJson = (value: unknown) => JSON.stringify(value).replace(/</g, '\\\\u003c');\n\n/**\n * The page headless Chrome runs: it compiles the shader with the same\n * wrapper as `ShaderRenderer` (`wrapSource`, so every built-in, `iPointer`,\n * `iClicks` and `iTrail` included, is declared), sets each control by its\n * type (`int` and `bool` as integers), loads image controls the way\n * `loadImage` does (SVGs sized to their long edge first) before the first\n * frame, and flips them as the renderer does. Each frame asks `/state` for\n * its time, pointer, video frames or SVG markup, draws, and posts the\n * pixels to `/frame`.\n */\nexport function renderPageHtml(config: PageConfig): string {\n return `<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<style>html,body{margin:0;background:transparent;overflow:hidden}</style>\n</head>\n<body>\n<script>\nconst CONFIG = ${scriptJson(config)};\nconst VERTEX = ${scriptJson(VERTEX_SOURCE)};\nconst W = CONFIG.width, H = CONFIG.height;\nconst report = (message) => fetch(\"/error\", { method: \"POST\", body: String(message) });\naddEventListener(\"error\", (e) => report(\"The render page failed: \" + e.message));\naddEventListener(\"unhandledrejection\", (e) => report((e.reason && e.reason.message) || String(e.reason)));\n\n// SVGs decode at their own (often icon) size: give them ${SVG_EDGE} px on the long edge, and a viewBox.\nfunction sizeSvg(markup, w0, h0) {\n const doc = new DOMParser().parseFromString(markup, \"image/svg+xml\");\n const svg = doc.documentElement;\n if (svg.localName !== \"svg\" || doc.getElementsByTagName(\"parsererror\").length) throw new Error(\"Not an SVG document.\");\n const len = (n) => { const m = (svg.getAttribute(n) || \"\").trim().match(/^([\\\\d.]+)(px)?$/); return m && +m[1] > 0 ? +m[1] : 0; };\n const box = (svg.getAttribute(\"viewBox\") || \"\").trim().split(/[\\\\s,]+/).map(Number);\n const hasBox = box.length === 4 && box[2] > 0 && box[3] > 0;\n const w = len(\"width\") || (hasBox ? box[2] : 300), h = len(\"height\") || (hasBox ? box[3] : 150);\n if (!hasBox) svg.setAttribute(\"viewBox\", \"0 0 \" + w + \" \" + h);\n const scale = w0 ? 1 : ${SVG_EDGE} / Math.max(w, h);\n svg.setAttribute(\"width\", w0 || Math.max(1, Math.round(w * scale)));\n svg.setAttribute(\"height\", h0 || Math.max(1, Math.round(h * scale)));\n return new XMLSerializer().serializeToString(svg);\n}\nconst isSvg = (url) => /^data:image\\\\/svg\\\\+xml[;,]/i.test(url) || /^(?!data:)[^?#]*\\\\.svg([?#]|$)/i.test(url);\nasync function decode(src, name) {\n const img = new Image();\n img.src = src;\n try { await img.decode(); } catch (e) { throw new Error(\"Could not load the image \" + name + \".\"); }\n return img;\n}\nasync function loadImage(url, name) {\n if (!isSvg(url)) return decode(url, name);\n const text = await (await fetch(url)).text();\n const blob = URL.createObjectURL(new Blob([sizeSvg(text)], { type: \"image/svg+xml\" }));\n try { return await decode(blob, name); } finally { URL.revokeObjectURL(blob); }\n}\n\nconst out = document.createElement(\"canvas\");\nout.width = W; out.height = H;\nconst ctx = out.getContext(\"2d\", { willReadFrequently: CONFIG.send === \"rgba\" });\nlet gl = null, glCanvas = null, u = null;\nconst textures = {};\n\nfunction setupShader() {\n glCanvas = document.createElement(\"canvas\");\n glCanvas.width = W; glCanvas.height = H;\n // As createContext: no antialiasing, depth or stencil; unpremultiplied alpha so pixels read back exactly.\n gl = glCanvas.getContext(\"webgl2\", { alpha: true, premultipliedAlpha: false, preserveDrawingBuffer: true, antialias: false, depth: false, stencil: false, powerPreference: \"high-performance\" });\n if (!gl) throw new Error(\"WebGL2 is not available in headless Chrome.\");\n const compile = (type, src) => {\n const s = gl.createShader(type);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(\"The shader does not compile: \" + gl.getShaderInfoLog(s));\n return s;\n };\n const program = gl.createProgram();\n gl.attachShader(program, compile(gl.VERTEX_SHADER, VERTEX));\n gl.attachShader(program, compile(gl.FRAGMENT_SHADER, CONFIG.shader.fragment));\n gl.linkProgram(program);\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(\"The shader does not link: \" + gl.getProgramInfoLog(program));\n gl.useProgram(program);\n u = (n) => gl.getUniformLocation(program, n);\n gl.viewport(0, 0, W, H);\n if (CONFIG.shader.opaque) {\n // An opaque canvas, as ShaderRenderer has without alpha: alpha stays 1 whatever the shader writes.\n gl.clearColor(0, 0, 0, 1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.colorMask(true, true, true, false);\n }\n}\n\nfunction makeTexture(unit, texture) {\n const t = gl.createTexture();\n const settings = texture || { filter: \"mipmap\", wrap: \"repeat\" };\n gl.activeTexture(gl.TEXTURE0 + unit);\n gl.bindTexture(gl.TEXTURE_2D, t);\n // Black until (or unless) a picture arrives, as TextureCache does.\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 0, 255]));\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, { mipmap: gl.LINEAR_MIPMAP_LINEAR, linear: gl.LINEAR, nearest: gl.NEAREST }[settings.filter]);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, settings.filter === \"nearest\" ? gl.NEAREST : gl.LINEAR);\n const wrap = { repeat: gl.REPEAT, clamp: gl.CLAMP_TO_EDGE, mirror: gl.MIRRORED_REPEAT }[settings.wrap];\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);\n return { unit, texture: t };\n}\n\nfunction upload(name, img) {\n const slot = textures[name];\n if (!slot) return;\n gl.activeTexture(gl.TEXTURE0 + slot.unit);\n gl.bindTexture(gl.TEXTURE_2D, slot.texture);\n // Rows bottom up, as the renderer's TextureCache uploads them.\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);\n gl.generateMipmap(gl.TEXTURE_2D);\n}\n\nasync function setControls() {\n let unit = 0;\n const loads = [];\n for (const c of CONFIG.shader.controls) {\n const loc = u(c.name);\n const v = c.value;\n if (c.type === \"sampler2D\") {\n textures[c.name] = makeTexture(unit, c.texture);\n if (loc) gl.uniform1i(loc, unit);\n unit++;\n if (v) loads.push(loadImage(v, \"for \" + c.name).then((img) => upload(c.name, img)));\n continue;\n }\n if (!loc) continue;\n if (c.type === \"float\") gl.uniform1f(loc, v);\n else if (c.type === \"int\") gl.uniform1i(loc, Math.round(v));\n else if (c.type === \"bool\") gl.uniform1i(loc, v ? 1 : 0);\n else if (Array.isArray(v)) gl[\"uniform\" + v.length + \"fv\"](loc, v);\n }\n await Promise.all(loads);\n}\n\nfunction drawShader(s) {\n gl.viewport(0, 0, W, H);\n const set = (n, f) => { const l = u(n); if (l) f(l); };\n set(\"iResolution\", (l) => gl.uniform3f(l, W, H, 1));\n set(\"iTime\", (l) => gl.uniform1f(l, s.time));\n set(\"iTimeDelta\", (l) => gl.uniform1f(l, s.delta));\n set(\"iFrame\", (l) => gl.uniform1i(l, s.frame));\n set(\"iMouse\", (l) => gl.uniform4fv(l, s.mouse));\n set(\"iPointer\", (l) => gl.uniform4fv(l, s.pointer));\n set(\"iClicks\", (l) => gl.uniform4fv(l, new Float32Array(s.clicks)));\n set(\"iTrail\", (l) => gl.uniform4fv(l, new Float32Array(s.trail)));\n // glslsandbox-style names, for complete programs.\n set(\"u_resolution\", (l) => gl.uniform2f(l, W, H));\n set(\"u_time\", (l) => gl.uniform1f(l, s.time));\n set(\"u_mouse\", (l) => gl.uniform2f(l, s.pointer[0], s.pointer[1]));\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n}\n\nasync function frameImage(s) {\n if (CONFIG.shader) {\n for (const [name, url] of Object.entries(s.video || {})) upload(name, await decode(url, \"of the video frame\"));\n drawShader(s);\n return glCanvas;\n }\n const markup = sizeSvg(s.svg, W, H);\n const url = URL.createObjectURL(new Blob([markup], { type: \"image/svg+xml\" }));\n try { return await decode(url, \"of the SVG frame\"); } finally { URL.revokeObjectURL(url); }\n}\n\nasync function capture(src) {\n // The WebGL canvas reads back exactly when nothing is composited under it.\n const direct = CONFIG.shader && (CONFIG.alpha || CONFIG.shader.opaque);\n if (direct) {\n if (CONFIG.send === \"png\") return new Promise((r) => glCanvas.toBlob(r, \"image/png\"));\n const px = new Uint8Array(W * H * 4);\n gl.readPixels(0, 0, W, H, gl.RGBA, gl.UNSIGNED_BYTE, px);\n const flipped = new Uint8Array(px.length), row = W * 4;\n for (let y = 0; y < H; y++) flipped.set(px.subarray((H - 1 - y) * row, (H - y) * row), y * row);\n return flipped;\n }\n ctx.clearRect(0, 0, W, H);\n if (!CONFIG.alpha) { ctx.fillStyle = CONFIG.background; ctx.fillRect(0, 0, W, H); }\n ctx.drawImage(src, 0, 0, W, H);\n if (CONFIG.send === \"png\") return new Promise((r) => out.toBlob(r, \"image/png\"));\n return ctx.getImageData(0, 0, W, H).data;\n}\n\n(async () => {\n if (CONFIG.shader) { setupShader(); await setControls(); }\n for (let i = 0; i < CONFIG.frames; i++) {\n const s = await (await fetch(\"/state?i=\" + i)).json();\n const body = await capture(await frameImage(s));\n const r = await fetch(\"/frame?i=\" + i, { method: \"POST\", body });\n if (!r.ok) return;\n }\n})().catch((e) => report((e && e.message) || String(e)));\n</script>\n</body>\n</html>\n`;\n}\n\n// ==========================================\n// The render loop\n// ==========================================\n\n/** One frame's state, as the page asks for it. */\nexport interface FrameState {\n time: number;\n delta: number;\n frame: number;\n mouse: [number, number, number, number];\n pointer: [number, number, number, number];\n clicks: number[];\n trail: number[];\n /** SVG markup to draw (vector frames). */\n svg?: string;\n /** Image control → local file to show this frame (video frames). */\n video?: Record<string, string>;\n}\n\n/** A render: the page to run, each frame's state, and where it goes. */\nexport interface RenderJob {\n page: PageConfig;\n state: (frame: number) => FrameState;\n plan: OutputPlan;\n fps: number;\n onProgress?: (frame: number, total: number) => void;\n}\n\n/** Frames written somewhere: a sink takes them in order and finishes. */\ninterface Sink {\n write(frame: number, data: Buffer): Promise<void>;\n finish(): Promise<void>;\n abort(): void;\n}\n\nfunction ffmpegSink(plan: OutputPlan, fps: number): Sink {\n const args = ['-y', '-hide_banner', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'png', '-i', '-', ...plan.ffmpegArgs!, '-r', String(fps), plan.path];\n const proc = spawn(ffmpegPath(), args, { stdio: ['pipe', 'ignore', 'pipe'] });\n let stderr = '';\n let failed: Error | null = null;\n proc.stderr!.on('data', (d) => (stderr += d.toString()));\n const done = new Promise<void>((resolve, reject) => {\n proc.on('error', (err: NodeJS.ErrnoException) => {\n failed = err.code === 'ENOENT' ? new Error(NO_FFMPEG) : new Error(`ffmpeg could not start: ${err.message}`);\n reject(failed);\n });\n proc.on('close', (code) => {\n if (code === 0) resolve();\n else reject((failed ??= new Error(`ffmpeg failed (exit ${code}): ${stderr.trim() || 'no message'}`)));\n });\n });\n done.catch(() => {});\n proc.stdin!.on('error', () => {});\n return {\n async write(_frame, data) {\n if (failed) throw failed;\n if (!proc.stdin!.write(data)) await new Promise((r) => proc.stdin!.once('drain', r));\n },\n async finish() {\n proc.stdin!.end();\n await done;\n },\n abort() {\n proc.kill('SIGKILL');\n },\n };\n}\n\nfunction pngSink(plan: OutputPlan): Sink {\n fs.mkdirSync(path.dirname(plan.path), { recursive: true });\n return {\n async write(frame, data) {\n await fs.promises.writeFile(plan.path.includes('%') ? sequencePath(plan.path, frame) : plan.path, data);\n },\n async finish() {},\n abort() {},\n };\n}\n\nasync function gifSink(plan: OutputPlan, width: number, height: number, fps: number): Promise<Sink> {\n // gifenc is CommonJS in Node: its functions may only be on the default export.\n const mod = (await import('gifenc')) as Partial<typeof import('gifenc')> & { default?: typeof import('gifenc') };\n const { GIFEncoder, quantize, applyPalette } = (typeof mod.GIFEncoder === 'function' ? mod : mod.default!) as typeof import('gifenc');\n const gif = GIFEncoder();\n const delay = 1000 / fps;\n return {\n async write(frame, data) {\n const rgba = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n const first = frame === 0 ? { repeat: 0 } : {};\n if (plan.alpha) {\n // One-bit alpha: each frame replaces the last (dispose 2), with a transparent palette entry.\n const palette = quantize(rgba, 256, { format: 'rgba4444', oneBitAlpha: true });\n const transparentIndex = palette.findIndex((c) => c[3] === 0);\n gif.writeFrame(applyPalette(rgba, palette, 'rgba4444'), width, height, {\n palette,\n delay,\n dispose: 2,\n ...(transparentIndex >= 0 ? { transparent: true, transparentIndex } : {}),\n ...first,\n });\n } else {\n const palette = quantize(rgba, 256);\n gif.writeFrame(applyPalette(rgba, palette), width, height, { palette, delay, ...first });\n }\n },\n async finish() {\n gif.finish();\n fs.mkdirSync(path.dirname(plan.path), { recursive: true });\n await fs.promises.writeFile(plan.path, gif.bytes());\n },\n abort() {},\n };\n}\n\n/** Chrome's flags: GPU WebGL where there is one (Metal on macOS), SwiftShader otherwise. */\nfunction chromeArgs(userDataDir: string, width: number, height: number, url: string): string[] {\n return [\n '--headless=new',\n `--user-data-dir=${userDataDir}`,\n `--window-size=${Math.max(64, width)},${Math.max(64, height)}`,\n '--use-gl=angle',\n ...(process.platform === 'darwin' ? ['--use-angle=metal'] : []),\n '--enable-webgl',\n '--enable-unsafe-swiftshader',\n '--ignore-gpu-blocklist',\n '--disable-gpu-sandbox',\n '--force-color-profile=srgb',\n '--no-first-run',\n '--no-default-browser-check',\n '--disable-background-networking',\n '--disable-background-timer-throttling',\n '--disable-renderer-backgrounding',\n '--disable-extensions',\n url,\n ];\n}\n\nconst STALL_MS = 60_000;\n\n/**\n * Runs a render: serves the page to headless Chrome on 127.0.0.1, hands it\n * each frame's state, and writes the frames it posts back. Resolves with the\n * output path (a PNG sequence's pattern).\n */\nexport async function runRender(job: RenderJob): Promise<string> {\n const { page, plan, fps, onProgress } = job;\n const total = page.frames;\n const chromeBin = findChrome();\n if (!chromeBin) {\n throw new Error('Chrome or Chromium is needed to render, and none was found. Install Google Chrome, run \"npx playwright install chromium\", or set CHROME_PATH.');\n }\n fs.mkdirSync(path.dirname(plan.path), { recursive: true });\n const sink = plan.format === 'gif' ? await gifSink(plan, page.width, page.height, fps) : plan.format === 'png' ? pngSink(plan) : ffmpegSink(plan, fps);\n const html = renderPageHtml(page);\n const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'flair-chrome-'));\n\n return new Promise<string>((resolve, reject) => {\n let chrome: ChildProcess | null = null;\n let finished = false;\n let written = 0;\n let stall: NodeJS.Timeout | undefined;\n const sockets = new Set<import('node:net').Socket>();\n\n const cleanup = () => {\n clearTimeout(stall);\n try {\n chrome?.kill('SIGKILL');\n } catch {}\n for (const s of sockets) s.destroy();\n server.close();\n fs.rm(userDataDir, { recursive: true, force: true }, () => {});\n };\n const fail = (err: Error) => {\n if (finished) return;\n finished = true;\n sink.abort();\n cleanup();\n reject(err);\n };\n const succeed = () => {\n if (finished) return;\n finished = true;\n cleanup();\n resolve(plan.path);\n };\n const watchdog = () => {\n clearTimeout(stall);\n stall = setTimeout(() => fail(new Error(`The render stalled: no frame for ${STALL_MS / 1000} s after frame ${written} of ${total}. Is WebGL2 available to headless Chrome?`)), STALL_MS);\n };\n\n const server = http.createServer((req, res) => {\n const url = new URL(req.url || '/', 'http://127.0.0.1');\n if (url.pathname === '/' && req.method === 'GET') {\n res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });\n res.end(html);\n return;\n }\n if (url.pathname === '/state') {\n const i = Number(url.searchParams.get('i'));\n try {\n const s = job.state(i);\n const body = { ...s, ...(s.video ? { video: Object.fromEntries(Object.keys(s.video).map((k) => [k, `/video?i=${i}&name=${encodeURIComponent(k)}`])) } : {}) };\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify(body));\n } catch (e) {\n res.writeHead(500);\n res.end();\n fail(e as Error);\n }\n return;\n }\n if (url.pathname === '/video') {\n const i = Number(url.searchParams.get('i'));\n const file = job.state(i).video?.[url.searchParams.get('name') ?? ''];\n if (!file) {\n res.writeHead(404);\n res.end();\n return;\n }\n res.writeHead(200, { 'Content-Type': 'image/png' });\n fs.createReadStream(file).pipe(res);\n return;\n }\n if (url.pathname === '/frame' && req.method === 'POST') {\n const i = Number(url.searchParams.get('i'));\n const chunks: Buffer[] = [];\n req.on('data', (c: Buffer) => chunks.push(c));\n req.on('end', () => {\n sink\n .write(i, Buffer.concat(chunks))\n .then(async () => {\n written++;\n watchdog();\n onProgress?.(written, total);\n res.writeHead(200);\n res.end('ok');\n if (written >= total) {\n await sink.finish();\n succeed();\n }\n })\n .catch((e: Error) => {\n res.writeHead(500);\n res.end();\n fail(e);\n });\n });\n return;\n }\n if (url.pathname === '/error' && req.method === 'POST') {\n let message = '';\n req.on('data', (c) => (message += c));\n req.on('end', () => {\n res.writeHead(200);\n res.end();\n fail(new Error(message || 'The render page failed.'));\n });\n return;\n }\n res.writeHead(404);\n res.end();\n });\n server.on('connection', (s) => {\n sockets.add(s);\n s.on('close', () => sockets.delete(s));\n });\n\n server.listen(0, '127.0.0.1', () => {\n const { port } = server.address() as import('node:net').AddressInfo;\n chrome = spawn(chromeBin, chromeArgs(userDataDir, page.width, page.height, `http://127.0.0.1:${port}/`), { stdio: 'ignore' });\n chrome.on('error', (err) => fail(new Error(`Could not launch Chrome at ${chromeBin}: ${err.message}`)));\n chrome.on('exit', (code) => {\n if (!finished && written < total) fail(new Error(`Chrome quit (exit ${code}) after ${written} of ${total} frames.`));\n });\n watchdog();\n });\n });\n}\n\n// ==========================================\n// Shader export\n// ==========================================\n\n/** Where the pointer is in a recording: nowhere (`none`), or the scripted pointer of {@link scriptedPointer} (`auto`). */\nexport type PointerMode = 'none' | 'auto';\n\nexport interface ExportOptions {\n /** GLSL fragment shader source (Shadertoy-style `mainImage`). */\n source: string;\n /**\n * Control values over the declared defaults. An image control takes a\n * URL, a `data:` URL, or a local file path (read into a `data:` URL).\n */\n values?: Record<string, ControlValue>;\n /** Destination: .mp4, .webm, .mov, .gif, or PNG frames (a folder or `out_%04d.png`). */\n outputPath: string;\n width?: number;\n height?: number;\n fps?: number;\n /** Seconds (default 3). */\n duration?: number;\n /** Keep the shader's alpha (WebM, MOV, GIF and PNG; MP4 is always opaque). */\n alpha?: boolean;\n /**\n * The shader draws over other content (`fragColor.a` is coverage): without\n * `alpha` it is composited over `background`. Otherwise its alpha is\n * ignored without `alpha`, as on an opaque canvas.\n */\n transparent?: boolean;\n /** CSS colour under transparent pixels when `alpha` is off (default black). */\n background?: string;\n /** The pointer: `none` (default) or `auto`, a scripted pointer that hovers, wanders and clicks. */\n pointer?: PointerMode;\n onProgress?: (frame: number, total: number) => void;\n}\n\nconst MIME: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.bmp': 'image/bmp',\n '.svg': 'image/svg+xml',\n};\n\n/**\n * An image for the page, as a `data:` URL: a local file is read, an\n * `http(s):` URL fetched (so CORS does not matter); `data:` URLs stay.\n */\nexport async function imageDataUrl(source: string, cwd = process.cwd()): Promise<string> {\n if (/^data:/i.test(source) || source === '') return source;\n if (/^https?:/i.test(source)) {\n const res = await fetch(source);\n if (!res.ok) throw new Error(`Could not download the image at ${source} (HTTP ${res.status}).`);\n const type = res.headers.get('content-type')?.split(';')[0] || MIME[path.extname(new URL(source).pathname).toLowerCase()] || 'application/octet-stream';\n return `data:${type};base64,${Buffer.from(await res.arrayBuffer()).toString('base64')}`;\n }\n const file = path.resolve(cwd, source.replace(/^file:\\/\\//, ''));\n if (!fs.existsSync(file)) throw new Error(`There is no image at ${file}.`);\n const type = MIME[path.extname(file).toLowerCase()];\n if (!type) throw new Error(`${path.basename(file)} is not an image Flair can show; give it a PNG, JPEG, GIF, WebP, AVIF, BMP or SVG.`);\n return `data:${type};base64,${fs.readFileSync(file).toString('base64')}`;\n}\n\n/**\n * The fragment shader the page compiles: a Shadertoy-style `mainImage`\n * source goes in `wrapSource`, as `ShaderRenderer` compiles it. A complete\n * program (one with its own `void main()`, glslsandbox-style, reading\n * `u_time` and `u_resolution`) is kept as written, with `#version 300 es`\n * added when it has none.\n */\nexport function fragmentSource(source: string): string {\n if (!/\\bvoid\\s+main\\s*\\(\\s*\\)/.test(source)) return wrapSource(source);\n return /^\\s*#version\\b/.test(source) ? source : `#version 300 es\\n#line 1\\n${source}`;\n}\n\n/** Shader controls with their values, images as `data:` URLs, ready for the page. */\nexport async function pageControls(source: string, values: Record<string, ControlValue> = {}): Promise<PageControl[]> {\n return Promise.all(\n parseControls(source).map(async (c) => {\n let value = controlValue(c, values);\n if (c.type === 'sampler2D' && typeof value === 'string') value = await imageDataUrl(value);\n return { name: c.name, type: c.type, value, ...(c.texture ? { texture: c.texture } : {}) };\n }),\n );\n}\n\n/** Frame times and pointer uniforms for `frames` frames at `fps`. */\nexport function frameStates(frames: number, fps: number, width: number, height: number, pointer: PointerMode): FrameState[] {\n const times = Array.from({ length: frames }, (_, i) => i / fps);\n const scripted = pointer === 'auto' ? scriptedPointer(width, height, times) : undefined;\n const none = { mouse: [0, 0, 0, 0] as [number, number, number, number], pointer: [0, 0, 0, 0] as [number, number, number, number], clicks: new Array(MAX_CLICKS * 4).fill(0), trail: new Array(MAX_TRAIL * 4).fill(0) };\n return times.map((time, i) => ({ time, delta: i === 0 ? 0 : 1 / fps, frame: i, ...(scripted?.[i] ?? none) }));\n}\n\n/**\n * Renders a shader animation frame by frame with WebGL2 in headless Chrome,\n * the way `ShaderRenderer` draws it (the same GLSL wrapper and built-ins,\n * images, int and bool controls), and writes MP4 (H.264), WebM (VP9, with\n * alpha when asked), MOV (ProRes 4444), GIF or PNG frames. MP4, WebM and\n * MOV need ffmpeg; GIF and PNG do not.\n */\nexport async function exportMotionGraphic(options: ExportOptions): Promise<string> {\n const { source, values = {}, outputPath, fps = 30, duration = 3, onProgress } = options;\n const width = Math.max(1, Math.round(options.width ?? 720));\n const height = Math.max(1, Math.round(options.height ?? 720));\n const frames = Math.max(1, Math.round(duration * fps));\n const plan = planOutput(outputPath, { alpha: options.alpha, frames });\n if (plan.format === 'svg') throw new Error('A shader cannot be written as SVG; write .mp4, .webm, .mov, .gif or .png frames.');\n const states = frameStates(frames, fps, width, height, options.pointer ?? 'none');\n return runRender({\n page: {\n width,\n height,\n frames,\n alpha: plan.alpha,\n background: options.background ?? '#000000',\n send: plan.format === 'gif' ? 'rgba' : 'png',\n shader: {\n fragment: fragmentSource(source),\n controls: await pageControls(source, values),\n opaque: !plan.alpha && !options.transparent,\n },\n },\n state: (i) => states[i]!,\n plan,\n fps,\n onProgress,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAEA,OAAO,UAAU;AACjB,SAAS,aA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