@pixerate/flair 0.24.0 → 0.25.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.
- package/CHANGELOG.md +12 -0
- package/dist/catalog/index.js +2 -2
- package/dist/chunk-DBTLCXKY.js +332 -0
- package/dist/chunk-DBTLCXKY.js.map +1 -0
- package/dist/{chunk-VP6IEWIK.js → chunk-H6L67KHI.js} +1 -1
- package/dist/chunk-H6VDFBIO.js +498 -0
- package/dist/chunk-H6VDFBIO.js.map +1 -0
- package/dist/chunk-JL6TI6II.js +724 -0
- package/dist/chunk-JL6TI6II.js.map +1 -0
- package/dist/{chunk-NGKNI3QX.js → chunk-O44ZJTGG.js} +5 -485
- package/dist/chunk-O44ZJTGG.js.map +1 -0
- package/dist/chunk-OKYMKSXK.js +414 -0
- package/dist/chunk-OKYMKSXK.js.map +1 -0
- package/dist/{chunk-OHW7UG6D.js → chunk-ORAFCHX3.js} +26 -2
- package/dist/{chunk-OHW7UG6D.js.map → chunk-ORAFCHX3.js.map} +1 -1
- package/dist/{chunk-OQ4EWZ3B.js → chunk-PYDN5G2P.js} +5 -5
- package/dist/{chunk-ARKC7LDW.js → chunk-RDU63CDO.js} +2 -331
- package/dist/chunk-RDU63CDO.js.map +1 -0
- package/dist/chunk-S2RGHHKZ.js +902 -0
- package/dist/chunk-S2RGHHKZ.js.map +1 -0
- package/dist/{chunk-LVPIIWPP.js → chunk-STKEKXCK.js} +18 -8
- package/dist/chunk-STKEKXCK.js.map +1 -0
- package/dist/chunk-YBGRXVAE.js +407 -0
- package/dist/chunk-YBGRXVAE.js.map +1 -0
- package/dist/cli.js +68 -5
- package/dist/cli.js.map +1 -1
- package/dist/editor/index.d.ts +1 -1
- package/dist/editor/index.js +14 -12
- package/dist/editor/index.js.map +1 -1
- package/dist/effect-26CPF5HS.js +47 -0
- package/dist/embed/index.d.ts +215 -0
- package/dist/embed/index.js +21 -0
- package/dist/embed/index.js.map +1 -0
- package/dist/frames-VEcqa40g.d.ts +161 -0
- package/dist/index.d.ts +6 -163
- package/dist/index.js +86 -78
- package/dist/index.js.map +1 -1
- package/dist/node.d.ts +167 -7
- package/dist/node.js +25 -3
- package/dist/react/index.d.ts +33 -2
- package/dist/react/index.js +54 -9
- package/dist/react/index.js.map +1 -1
- package/dist/recorder-CDPPTJMG.js +31 -0
- package/dist/recorder-CDPPTJMG.js.map +1 -0
- package/dist/{renderer-C2P1qGzP.d.ts → renderer-teaa98RE.d.ts} +1 -1
- package/dist/svelte/index.d.ts +33 -4
- package/dist/svelte/index.js +51 -9
- package/dist/svelte/index.js.map +1 -1
- package/dist/vector/index.d.ts +52 -1
- package/dist/vector/index.js +8 -4
- package/package.json +1 -1
- package/dist/chunk-ARKC7LDW.js.map +0 -1
- package/dist/chunk-LVPIIWPP.js.map +0 -1
- package/dist/chunk-NGKNI3QX.js.map +0 -1
- package/dist/chunk-UP6QQVRS.js +0 -331
- package/dist/chunk-UP6QQVRS.js.map +0 -1
- package/dist/recorder-HKFFHQES.js +0 -10
- /package/dist/{chunk-VP6IEWIK.js.map → chunk-H6L67KHI.js.map} +0 -0
- /package/dist/{chunk-OQ4EWZ3B.js.map → chunk-PYDN5G2P.js.map} +0 -0
- /package/dist/{recorder-HKFFHQES.js.map → effect-26CPF5HS.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
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,aAAgC;AACzC,OAAO,QAAQ;AACf,OAAO,QAAQ;AACf,OAAO,UAAU;AAUjB,IAAM,oBAAoB;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGA,SAAS,oBAA8B;AACrC,QAAM,QAAQ;AAAA,IACZ,QAAQ,IAAI;AAAA,IACZ,KAAK,KAAK,GAAG,QAAQ,GAAG,8BAA8B;AAAA,IACtD,KAAK,KAAK,GAAG,QAAQ,GAAG,sBAAsB;AAAA,EAChD,EAAE,OAAO,CAAC,MAAmB,QAAQ,CAAC,CAAC;AACvC,QAAM,QAAkB,CAAC;AAC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ACvC,QAAQ;AAAA,QACN,UAAU,eAAe,MAAM;AAAA,QAC/B,UAAU,MAAM,aAAa,QAAQ,MAAM;AAAA,QAC3C,QAAQ,CAAC,KAAK,SAAS,CAAC,QAAQ;AAAA,MAClC;AAAA,IACF;AAAA,IACA,OAAO,CAAC,MAAM,OAAO,CAAC;AAAA,IACtB;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACH;","names":["type"]}
|
|
@@ -7,387 +7,29 @@ import {
|
|
|
7
7
|
cameraTrack,
|
|
8
8
|
sceneStage
|
|
9
9
|
} from "./chunk-WAMA45G3.js";
|
|
10
|
+
import {
|
|
11
|
+
ShaderFrames
|
|
12
|
+
} from "./chunk-H6VDFBIO.js";
|
|
10
13
|
import {
|
|
11
14
|
HOVER_SECONDS,
|
|
12
15
|
MAX_CLICKS,
|
|
13
16
|
MAX_TRAIL,
|
|
14
|
-
PointerTracker,
|
|
15
17
|
SVG_EDGE,
|
|
16
|
-
ShaderCompileError,
|
|
17
18
|
TRAIL_SECONDS,
|
|
18
19
|
TextureCache,
|
|
19
20
|
VERTEX_SOURCE,
|
|
20
|
-
clicksUniform,
|
|
21
21
|
compileShader,
|
|
22
22
|
createContext,
|
|
23
23
|
drawFrame,
|
|
24
24
|
resetGlCaches,
|
|
25
|
-
trailUniform,
|
|
26
25
|
wrapSource
|
|
27
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-RDU63CDO.js";
|
|
28
27
|
import {
|
|
29
28
|
controlValue,
|
|
30
29
|
imageUrls,
|
|
31
30
|
parseControls
|
|
32
31
|
} from "./chunk-VYOMXE6I.js";
|
|
33
32
|
|
|
34
|
-
// src/shader/renderer.ts
|
|
35
|
-
var ShaderRenderer = class {
|
|
36
|
-
canvas;
|
|
37
|
-
gl;
|
|
38
|
-
alpha;
|
|
39
|
-
shader = null;
|
|
40
|
-
textures = null;
|
|
41
|
-
/** Live sources by image control, kept to set again on a restored context. */
|
|
42
|
-
live = /* @__PURE__ */ new Map();
|
|
43
|
-
controls = [];
|
|
44
|
-
values;
|
|
45
|
-
source = "";
|
|
46
|
-
raf = 0;
|
|
47
|
-
lastNow = 0;
|
|
48
|
-
frame = 0;
|
|
49
|
-
fpsFrames = 0;
|
|
50
|
-
fpsSince = 0;
|
|
51
|
-
ownsCanvas = false;
|
|
52
|
-
resizeObserver;
|
|
53
|
-
intersectionObserver;
|
|
54
|
-
wasPlayingBeforeHidden = false;
|
|
55
|
-
hasEnteredViewport = false;
|
|
56
|
-
mouse = [0, 0, 0, 0];
|
|
57
|
-
/** `iPointer` and `iClicks`. */
|
|
58
|
-
pointer = new PointerTracker();
|
|
59
|
-
disposed = false;
|
|
60
|
-
/** The latest source's status. */
|
|
61
|
-
status = { ok: true, errors: [] };
|
|
62
|
-
/** `iTime`, in seconds. Use `seek` to change it. */
|
|
63
|
-
time = 0;
|
|
64
|
-
/** Playback speed: 1 is real time. */
|
|
65
|
-
speed = 1;
|
|
66
|
-
/** Device pixels per CSS pixel; lower renders faster. Use `setPixelRatio` to change it. */
|
|
67
|
-
pixelRatio = Math.min(window.devicePixelRatio || 1, 2);
|
|
68
|
-
playing = true;
|
|
69
|
-
fps = 0;
|
|
70
|
-
onStats;
|
|
71
|
-
/** Called with `true` when the GL context is lost and `false` once it is restored and recompiled. */
|
|
72
|
-
onContextLost;
|
|
73
|
-
/** Called when an image control's URL (or live video) cannot be loaded; the control shows black. */
|
|
74
|
-
onImageError;
|
|
75
|
-
/**
|
|
76
|
-
* Creates a canvas in `target` (with `className` or options), or attaches to an existing
|
|
77
|
-
* `HTMLCanvasElement`, and starts the animation loop. Size the canvas with CSS.
|
|
78
|
-
*/
|
|
79
|
-
constructor(target, options) {
|
|
80
|
-
const opts = typeof options === "string" ? { className: options } : options ?? {};
|
|
81
|
-
let canvas;
|
|
82
|
-
if (target instanceof HTMLCanvasElement || "tagName" in target && target.tagName === "CANVAS") {
|
|
83
|
-
canvas = target;
|
|
84
|
-
if (opts.className) canvas.className = opts.className;
|
|
85
|
-
} else {
|
|
86
|
-
canvas = document.createElement("canvas");
|
|
87
|
-
if (opts.className) canvas.className = opts.className;
|
|
88
|
-
target.appendChild(canvas);
|
|
89
|
-
this.ownsCanvas = true;
|
|
90
|
-
}
|
|
91
|
-
this.canvas = canvas;
|
|
92
|
-
this.alpha = Boolean(opts.alpha);
|
|
93
|
-
this.gl = createContext(canvas, true, this.alpha);
|
|
94
|
-
this.textures = this.gl && this.textureCache(this.gl);
|
|
95
|
-
this.resizeObserver = new ResizeObserver(() => this.resize());
|
|
96
|
-
this.resizeObserver.observe(canvas);
|
|
97
|
-
const needsObserver = (opts.pauseWhenHidden || opts.playOnEnter) && typeof IntersectionObserver !== "undefined";
|
|
98
|
-
if (needsObserver) {
|
|
99
|
-
this.intersectionObserver = new IntersectionObserver(([entry]) => {
|
|
100
|
-
if (!entry) return;
|
|
101
|
-
if (entry.isIntersecting) {
|
|
102
|
-
if (opts.playOnEnter && !this.hasEnteredViewport) {
|
|
103
|
-
this.hasEnteredViewport = true;
|
|
104
|
-
if (opts.autoplay ?? true) {
|
|
105
|
-
this.play();
|
|
106
|
-
}
|
|
107
|
-
} else if (this.wasPlayingBeforeHidden) {
|
|
108
|
-
this.wasPlayingBeforeHidden = false;
|
|
109
|
-
this.play();
|
|
110
|
-
}
|
|
111
|
-
} else {
|
|
112
|
-
if (this.playing && opts.pauseWhenHidden) {
|
|
113
|
-
this.wasPlayingBeforeHidden = true;
|
|
114
|
-
this.pause();
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
});
|
|
118
|
-
this.intersectionObserver.observe(canvas);
|
|
119
|
-
}
|
|
120
|
-
const shouldAutoplay = (opts.autoplay ?? true) && !opts.playOnEnter;
|
|
121
|
-
this.playing = shouldAutoplay;
|
|
122
|
-
canvas.addEventListener("webglcontextlost", this.onLost);
|
|
123
|
-
canvas.addEventListener("webglcontextrestored", this.onRestored);
|
|
124
|
-
canvas.addEventListener("pointerdown", this.onPointerDown);
|
|
125
|
-
canvas.addEventListener("pointermove", this.onPointerMove);
|
|
126
|
-
canvas.addEventListener("pointerenter", this.onPointerEnter);
|
|
127
|
-
canvas.addEventListener("pointerleave", this.onPointerLeave);
|
|
128
|
-
window.addEventListener("pointerup", this.onPointerUp);
|
|
129
|
-
this.resize();
|
|
130
|
-
this.raf = requestAnimationFrame(this.tick);
|
|
131
|
-
}
|
|
132
|
-
/** False when the browser has no WebGL2. */
|
|
133
|
-
get supported() {
|
|
134
|
-
return this.gl !== null;
|
|
135
|
-
}
|
|
136
|
-
/** Compiles a new source; returns its status. Keeps the previous program when it fails. */
|
|
137
|
-
setSource(source) {
|
|
138
|
-
this.source = source;
|
|
139
|
-
const controls = parseControls(source);
|
|
140
|
-
if (!this.gl) {
|
|
141
|
-
this.status = {
|
|
142
|
-
ok: false,
|
|
143
|
-
errors: [{ line: 0, message: "WebGL2 is not available in this browser." }]
|
|
144
|
-
};
|
|
145
|
-
return this.status;
|
|
146
|
-
}
|
|
147
|
-
const result = compileShader(this.gl, source, controls);
|
|
148
|
-
if (result.ok) {
|
|
149
|
-
if (this.shader) this.gl.deleteProgram(this.shader.program);
|
|
150
|
-
this.shader = result.shader;
|
|
151
|
-
this.controls = controls;
|
|
152
|
-
this.status = { ok: true, errors: [] };
|
|
153
|
-
} else {
|
|
154
|
-
this.status = { ok: false, errors: result.errors };
|
|
155
|
-
}
|
|
156
|
-
this.syncTextures();
|
|
157
|
-
if (!this.playing) this.render();
|
|
158
|
-
return this.status;
|
|
159
|
-
}
|
|
160
|
-
/**
|
|
161
|
-
* Sets control values (see `controlValue`); a paused preview redraws.
|
|
162
|
-
* Images load in the background and show once they arrive: await
|
|
163
|
-
* `ready()` before a `capture` that needs them.
|
|
164
|
-
*/
|
|
165
|
-
setValues(values) {
|
|
166
|
-
this.values = values;
|
|
167
|
-
this.syncTextures();
|
|
168
|
-
if (!this.playing) this.render();
|
|
169
|
-
}
|
|
170
|
-
/**
|
|
171
|
-
* Shows a `<video>` (or a canvas) in the image control `name` (the
|
|
172
|
-
* uniform's name, such as `uImage`) in place of its URL, frame by frame;
|
|
173
|
-
* `null` goes back to the URL. The preview follows the video even while
|
|
174
|
-
* the shader's own clock is paused, and the video plays, seeks and loops
|
|
175
|
-
* on its own: the renderer never controls it. A video from another site
|
|
176
|
-
* needs `crossOrigin = "anonymous"` and CORS, or `onImageError` hears why
|
|
177
|
-
* it shows black. The value stays as it is, so documents, presets and
|
|
178
|
-
* agents keep seeing the URL.
|
|
179
|
-
*/
|
|
180
|
-
setLiveSource(name, source) {
|
|
181
|
-
if (source) this.live.set(name, source);
|
|
182
|
-
else this.live.delete(name);
|
|
183
|
-
this.textures?.setLive(name, source);
|
|
184
|
-
if (!this.playing) this.render();
|
|
185
|
-
}
|
|
186
|
-
/**
|
|
187
|
-
* Settles once the images the current controls show have loaded, and
|
|
188
|
-
* every live video has a frame. Rejects with an {@link ImageLoadError}
|
|
189
|
-
* when one cannot be (it shows black).
|
|
190
|
-
*/
|
|
191
|
-
async ready() {
|
|
192
|
-
await Promise.all([
|
|
193
|
-
this.textures?.ready(imageUrls(this.controls, this.values)),
|
|
194
|
-
this.textures?.liveReady()
|
|
195
|
-
]);
|
|
196
|
-
}
|
|
197
|
-
play() {
|
|
198
|
-
this.playing = true;
|
|
199
|
-
this.emit();
|
|
200
|
-
}
|
|
201
|
-
pause() {
|
|
202
|
-
this.playing = false;
|
|
203
|
-
this.emit();
|
|
204
|
-
}
|
|
205
|
-
/** Back to `iTime` 0 and frame 0. */
|
|
206
|
-
restart() {
|
|
207
|
-
this.time = 0;
|
|
208
|
-
this.pointer.clear();
|
|
209
|
-
this.frame = 0;
|
|
210
|
-
this.render();
|
|
211
|
-
this.emit();
|
|
212
|
-
}
|
|
213
|
-
/** Jumps to `time` seconds (not below 0) and draws it. */
|
|
214
|
-
seek(time) {
|
|
215
|
-
if (time < this.time) this.pointer.clear();
|
|
216
|
-
this.time = Math.max(0, time);
|
|
217
|
-
this.render();
|
|
218
|
-
this.emit();
|
|
219
|
-
}
|
|
220
|
-
setPixelRatio(ratio) {
|
|
221
|
-
this.pixelRatio = ratio;
|
|
222
|
-
this.resize();
|
|
223
|
-
}
|
|
224
|
-
/**
|
|
225
|
-
* Captures the current frame (optionally at another time) as a data URL
|
|
226
|
-
* (JPEG unless `type` says PNG), at most `maxEdge` pixels on the long side
|
|
227
|
-
* (default 1024). Playback time is left as it was. Null when nothing has
|
|
228
|
-
* compiled yet.
|
|
229
|
-
*/
|
|
230
|
-
capture(options = {}) {
|
|
231
|
-
if (!this.gl || !this.shader) return null;
|
|
232
|
-
const saved = this.time;
|
|
233
|
-
if (options.time !== void 0) this.time = Math.max(0, options.time);
|
|
234
|
-
this.render();
|
|
235
|
-
const { width, height } = this.canvas;
|
|
236
|
-
const scale = Math.min(1, (options.maxEdge ?? 1024) / Math.max(width, height));
|
|
237
|
-
const out = document.createElement("canvas");
|
|
238
|
-
out.width = Math.max(1, Math.round(width * scale));
|
|
239
|
-
out.height = Math.max(1, Math.round(height * scale));
|
|
240
|
-
out.getContext("2d").drawImage(this.canvas, 0, 0, out.width, out.height);
|
|
241
|
-
this.time = saved;
|
|
242
|
-
if (options.time !== void 0) this.render();
|
|
243
|
-
return out.toDataURL(options.type ?? "image/jpeg", 0.85);
|
|
244
|
-
}
|
|
245
|
-
/** Stops the loop, releases the context and removes the canvas. The renderer cannot be used again. */
|
|
246
|
-
dispose() {
|
|
247
|
-
this.disposed = true;
|
|
248
|
-
cancelAnimationFrame(this.raf);
|
|
249
|
-
this.resizeObserver.disconnect();
|
|
250
|
-
this.intersectionObserver?.disconnect();
|
|
251
|
-
this.canvas.removeEventListener("webglcontextlost", this.onLost);
|
|
252
|
-
this.canvas.removeEventListener("webglcontextrestored", this.onRestored);
|
|
253
|
-
this.canvas.removeEventListener("pointerdown", this.onPointerDown);
|
|
254
|
-
this.canvas.removeEventListener("pointermove", this.onPointerMove);
|
|
255
|
-
this.canvas.removeEventListener("pointerenter", this.onPointerEnter);
|
|
256
|
-
this.canvas.removeEventListener("pointerleave", this.onPointerLeave);
|
|
257
|
-
window.removeEventListener("pointerup", this.onPointerUp);
|
|
258
|
-
if (this.gl && this.shader) this.gl.deleteProgram(this.shader.program);
|
|
259
|
-
this.textures?.dispose();
|
|
260
|
-
this.textures = null;
|
|
261
|
-
this.gl?.getExtension("WEBGL_lose_context")?.loseContext();
|
|
262
|
-
this.gl = null;
|
|
263
|
-
if (this.ownsCanvas) this.canvas.remove();
|
|
264
|
-
}
|
|
265
|
-
resize() {
|
|
266
|
-
const w = Math.max(1, Math.round(this.canvas.clientWidth * this.pixelRatio));
|
|
267
|
-
const h = Math.max(1, Math.round(this.canvas.clientHeight * this.pixelRatio));
|
|
268
|
-
if (this.canvas.width !== w || this.canvas.height !== h) {
|
|
269
|
-
this.canvas.width = w;
|
|
270
|
-
this.canvas.height = h;
|
|
271
|
-
this.render();
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
render(delta = 0) {
|
|
275
|
-
if (!this.gl || !this.shader || this.gl.isContextLost()) return;
|
|
276
|
-
drawFrame(
|
|
277
|
-
this.gl,
|
|
278
|
-
this.shader,
|
|
279
|
-
this.controls,
|
|
280
|
-
this.values,
|
|
281
|
-
{
|
|
282
|
-
width: this.canvas.width,
|
|
283
|
-
height: this.canvas.height,
|
|
284
|
-
time: this.time,
|
|
285
|
-
delta,
|
|
286
|
-
frame: this.frame,
|
|
287
|
-
mouse: this.mouse,
|
|
288
|
-
pointer: this.pointer.pointer(this.time),
|
|
289
|
-
clicks: this.pointer.clicksAt(this.time),
|
|
290
|
-
trail: this.pointer.trailAt(this.time)
|
|
291
|
-
},
|
|
292
|
-
this.textures ?? void 0
|
|
293
|
-
);
|
|
294
|
-
}
|
|
295
|
-
textureCache(gl) {
|
|
296
|
-
const cache = new TextureCache(gl, (_url, error) => {
|
|
297
|
-
if (error) this.onImageError?.(error);
|
|
298
|
-
else if (!this.playing) this.render();
|
|
299
|
-
});
|
|
300
|
-
for (const [name, source] of this.live) cache.setLive(name, source);
|
|
301
|
-
return cache;
|
|
302
|
-
}
|
|
303
|
-
/** Starts loading the images now shown, and frees the ones no longer shown. */
|
|
304
|
-
syncTextures() {
|
|
305
|
-
if (!this.textures) return;
|
|
306
|
-
const urls = imageUrls(this.controls, this.values);
|
|
307
|
-
this.textures.retain(urls);
|
|
308
|
-
for (const url of urls) this.textures.request(url);
|
|
309
|
-
}
|
|
310
|
-
tick = (now) => {
|
|
311
|
-
if (this.disposed) return;
|
|
312
|
-
this.raf = requestAnimationFrame(this.tick);
|
|
313
|
-
const delta = this.lastNow ? Math.min((now - this.lastNow) / 1e3, 0.1) : 0;
|
|
314
|
-
this.lastNow = now;
|
|
315
|
-
if (this.playing) {
|
|
316
|
-
this.time += delta * this.speed;
|
|
317
|
-
this.frame += 1;
|
|
318
|
-
this.render(delta * this.speed);
|
|
319
|
-
this.fpsFrames += 1;
|
|
320
|
-
} else if (this.textures?.liveChanged()) {
|
|
321
|
-
this.render();
|
|
322
|
-
}
|
|
323
|
-
if (now - this.fpsSince >= 500) {
|
|
324
|
-
this.fps = this.playing ? Math.round(this.fpsFrames * 1e3 / (now - this.fpsSince || 1)) : 0;
|
|
325
|
-
this.fpsFrames = 0;
|
|
326
|
-
this.fpsSince = now;
|
|
327
|
-
this.emit();
|
|
328
|
-
}
|
|
329
|
-
};
|
|
330
|
-
emit() {
|
|
331
|
-
this.onStats?.({
|
|
332
|
-
time: this.time,
|
|
333
|
-
fps: this.fps,
|
|
334
|
-
playing: this.playing,
|
|
335
|
-
width: this.canvas.width,
|
|
336
|
-
height: this.canvas.height
|
|
337
|
-
});
|
|
338
|
-
}
|
|
339
|
-
/** Pointer position in shader pixels (origin bottom-left, like gl_FragCoord). */
|
|
340
|
-
toPixels(e) {
|
|
341
|
-
const rect = this.canvas.getBoundingClientRect();
|
|
342
|
-
return [
|
|
343
|
-
(e.clientX - rect.left) * (this.canvas.width / rect.width),
|
|
344
|
-
(rect.bottom - e.clientY) * (this.canvas.height / rect.height)
|
|
345
|
-
];
|
|
346
|
-
}
|
|
347
|
-
onPointerDown = (e) => {
|
|
348
|
-
const [x, y] = this.toPixels(e);
|
|
349
|
-
this.mouse = [x, y, x, y];
|
|
350
|
-
this.pointer.down(x, y, this.time);
|
|
351
|
-
if (!this.playing) this.render();
|
|
352
|
-
};
|
|
353
|
-
onPointerMove = (e) => {
|
|
354
|
-
const [x, y] = this.toPixels(e);
|
|
355
|
-
this.pointer.move(x, y, this.time);
|
|
356
|
-
if (this.mouse[2] <= 0 || e.buttons === 0) {
|
|
357
|
-
if (!this.playing) this.render();
|
|
358
|
-
return;
|
|
359
|
-
}
|
|
360
|
-
this.mouse = [x, y, this.mouse[2], this.mouse[3]];
|
|
361
|
-
if (!this.playing) this.render();
|
|
362
|
-
};
|
|
363
|
-
onPointerEnter = (e) => {
|
|
364
|
-
this.pointer.move(...this.toPixels(e), this.time);
|
|
365
|
-
this.pointer.hover(true, this.time);
|
|
366
|
-
};
|
|
367
|
-
onPointerLeave = () => {
|
|
368
|
-
this.pointer.hover(false, this.time);
|
|
369
|
-
};
|
|
370
|
-
onPointerUp = () => {
|
|
371
|
-
this.pointer.up(this.time);
|
|
372
|
-
if (this.mouse[2] > 0)
|
|
373
|
-
this.mouse = [this.mouse[0], this.mouse[1], -this.mouse[2], -Math.abs(this.mouse[3])];
|
|
374
|
-
};
|
|
375
|
-
onLost = (e) => {
|
|
376
|
-
e.preventDefault();
|
|
377
|
-
this.shader = null;
|
|
378
|
-
this.textures?.dispose();
|
|
379
|
-
this.textures = null;
|
|
380
|
-
this.onContextLost?.(true);
|
|
381
|
-
};
|
|
382
|
-
onRestored = () => {
|
|
383
|
-
resetGlCaches();
|
|
384
|
-
this.gl = createContext(this.canvas, true, this.alpha);
|
|
385
|
-
this.textures = this.gl && this.textureCache(this.gl);
|
|
386
|
-
this.setSource(this.source);
|
|
387
|
-
this.onContextLost?.(false);
|
|
388
|
-
};
|
|
389
|
-
};
|
|
390
|
-
|
|
391
33
|
// src/shader/thumbnails.ts
|
|
392
34
|
var ThumbnailPool = class {
|
|
393
35
|
renderWidth;
|
|
@@ -623,126 +265,6 @@ function registerThumbnail(canvas, source, values, onStatus) {
|
|
|
623
265
|
return sharedThumbnailPool().register(canvas, source, values, onStatus);
|
|
624
266
|
}
|
|
625
267
|
|
|
626
|
-
// src/shader/frames.ts
|
|
627
|
-
var ShaderFrames = class {
|
|
628
|
-
canvas;
|
|
629
|
-
width;
|
|
630
|
-
height;
|
|
631
|
-
controls;
|
|
632
|
-
gl;
|
|
633
|
-
shader;
|
|
634
|
-
textures;
|
|
635
|
-
values;
|
|
636
|
-
rendered = 0;
|
|
637
|
-
lastTime = null;
|
|
638
|
-
pixels;
|
|
639
|
-
constructor(options) {
|
|
640
|
-
const { source, values, width, height } = options;
|
|
641
|
-
this.width = Math.max(1, Math.round(width));
|
|
642
|
-
this.height = Math.max(1, Math.round(height));
|
|
643
|
-
this.canvas = options.canvas ?? document.createElement("canvas");
|
|
644
|
-
this.canvas.width = this.width;
|
|
645
|
-
this.canvas.height = this.height;
|
|
646
|
-
this.values = values;
|
|
647
|
-
const gl = createContext(this.canvas, true, Boolean(options.alpha));
|
|
648
|
-
if (!gl) throw new Error("WebGL2 is not available in this browser.");
|
|
649
|
-
this.gl = gl;
|
|
650
|
-
this.controls = parseControls(source);
|
|
651
|
-
const compiled = compileShader(gl, source, this.controls);
|
|
652
|
-
if (!compiled.ok) {
|
|
653
|
-
this.dispose();
|
|
654
|
-
throw new ShaderCompileError(compiled.errors);
|
|
655
|
-
}
|
|
656
|
-
this.shader = compiled.shader;
|
|
657
|
-
this.textures = new TextureCache(gl);
|
|
658
|
-
this.syncTextures();
|
|
659
|
-
this.pixels = new Uint8Array(this.width * this.height * 4);
|
|
660
|
-
}
|
|
661
|
-
/** Changes control values for the frames that follow. */
|
|
662
|
-
setValues(values) {
|
|
663
|
-
this.values = values;
|
|
664
|
-
this.syncTextures();
|
|
665
|
-
}
|
|
666
|
-
/**
|
|
667
|
-
* Draws a `<video>` (or a canvas) in the image control `name` instead of
|
|
668
|
-
* its URL, at the frame it is on when `render` runs; `null` goes back to
|
|
669
|
-
* the URL. See `ShaderRenderer.setLiveSource`.
|
|
670
|
-
*/
|
|
671
|
-
setLiveSource(name, source) {
|
|
672
|
-
this.textures.setLive(name, source);
|
|
673
|
-
}
|
|
674
|
-
/**
|
|
675
|
-
* Settles once every image the controls show has loaded, and every live
|
|
676
|
-
* video has a frame. Rejects with an {@link ImageLoadError} when one
|
|
677
|
-
* cannot be.
|
|
678
|
-
*/
|
|
679
|
-
async ready() {
|
|
680
|
-
await Promise.all([this.textures.ready(imageUrls(this.controls, this.values)), this.textures.liveReady()]);
|
|
681
|
-
}
|
|
682
|
-
/** Draws the frame at `time` seconds onto `canvas`. */
|
|
683
|
-
render(time, options = {}) {
|
|
684
|
-
const gl = this.context();
|
|
685
|
-
const delta = options.delta ?? (this.lastTime === null ? 0 : time - this.lastTime);
|
|
686
|
-
drawFrame(
|
|
687
|
-
gl,
|
|
688
|
-
this.shader,
|
|
689
|
-
this.controls,
|
|
690
|
-
this.values,
|
|
691
|
-
{
|
|
692
|
-
width: this.width,
|
|
693
|
-
height: this.height,
|
|
694
|
-
time,
|
|
695
|
-
delta,
|
|
696
|
-
frame: options.frame ?? this.rendered,
|
|
697
|
-
mouse: options.mouse ?? [0, 0, 0, 0],
|
|
698
|
-
pointer: options.pointer,
|
|
699
|
-
clicks: options.clicks && clicksUniform(options.clicks, time),
|
|
700
|
-
trail: options.trail && trailUniform(options.trail, time)
|
|
701
|
-
},
|
|
702
|
-
this.textures
|
|
703
|
-
);
|
|
704
|
-
this.rendered += 1;
|
|
705
|
-
this.lastTime = time;
|
|
706
|
-
}
|
|
707
|
-
/**
|
|
708
|
-
* The last rendered frame as RGBA bytes, rows top down (as in `ImageData`;
|
|
709
|
-
* WebGL itself reads bottom up). Pass `out` to reuse a buffer of
|
|
710
|
-
* `width * height * 4` bytes.
|
|
711
|
-
*/
|
|
712
|
-
readPixels(out) {
|
|
713
|
-
const gl = this.context();
|
|
714
|
-
const { width, height } = this;
|
|
715
|
-
const target = out ?? new Uint8Array(width * height * 4);
|
|
716
|
-
if (target.length !== width * height * 4) {
|
|
717
|
-
throw new RangeError(`readPixels needs a buffer of ${width * height * 4} bytes.`);
|
|
718
|
-
}
|
|
719
|
-
gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, this.pixels);
|
|
720
|
-
const row = width * 4;
|
|
721
|
-
for (let y = 0; y < height; y++) {
|
|
722
|
-
target.set(this.pixels.subarray((height - 1 - y) * row, (height - y) * row), y * row);
|
|
723
|
-
}
|
|
724
|
-
return target;
|
|
725
|
-
}
|
|
726
|
-
/** Releases the GL context now rather than at garbage collection (browsers cap live contexts). */
|
|
727
|
-
dispose() {
|
|
728
|
-
if (!this.gl) return;
|
|
729
|
-
if (this.shader) this.gl.deleteProgram(this.shader.program);
|
|
730
|
-
this.textures?.dispose();
|
|
731
|
-
this.gl.getExtension("WEBGL_lose_context")?.loseContext();
|
|
732
|
-
this.gl = null;
|
|
733
|
-
}
|
|
734
|
-
syncTextures() {
|
|
735
|
-
const urls = imageUrls(this.controls, this.values);
|
|
736
|
-
this.textures.retain(urls);
|
|
737
|
-
for (const url of urls) this.textures.request(url);
|
|
738
|
-
}
|
|
739
|
-
context() {
|
|
740
|
-
if (!this.gl) throw new Error("These frames have been disposed.");
|
|
741
|
-
if (this.gl.isContextLost()) throw new Error("The graphics context was lost.");
|
|
742
|
-
return this.gl;
|
|
743
|
-
}
|
|
744
|
-
};
|
|
745
|
-
|
|
746
268
|
// src/shader/gif.ts
|
|
747
269
|
var yieldToBrowser = () => new Promise((resolve) => setTimeout(resolve, 0));
|
|
748
270
|
async function recordGif(options) {
|
|
@@ -1649,11 +1171,9 @@ function escapeHtml2(str) {
|
|
|
1649
1171
|
}
|
|
1650
1172
|
|
|
1651
1173
|
export {
|
|
1652
|
-
ShaderRenderer,
|
|
1653
1174
|
ThumbnailPool,
|
|
1654
1175
|
sharedThumbnailPool,
|
|
1655
1176
|
registerThumbnail,
|
|
1656
|
-
ShaderFrames,
|
|
1657
1177
|
recordGif,
|
|
1658
1178
|
standaloneHtml,
|
|
1659
1179
|
ALL_BLEND_MODES,
|
|
@@ -1662,4 +1182,4 @@ export {
|
|
|
1662
1182
|
validateScene,
|
|
1663
1183
|
standaloneSceneHtml
|
|
1664
1184
|
};
|
|
1665
|
-
//# sourceMappingURL=chunk-
|
|
1185
|
+
//# sourceMappingURL=chunk-O44ZJTGG.js.map
|