Files
hyperframes/packages/core/src/vfx.ts
T
Vance IngallsandClaude Sonnet 5 b32b9a7dab feat(runtime): data-vfx-chain — a seek-deterministic per-pixel effect element (#4306)
* feat(core): data-vfx-chain defs and chain parsing (mirrors data-fx-chain)

Mirrors audioFx.ts's shape for the per-pixel VFX chain: a versioned
JSON chain attribute (data-vfx-chain), a def registry with typed
params (number/enum/bool/ref), and parse/serialize/normalize helpers.
HF_VFX holds one def, fractal-noise, with a placeholder frag; the
kernel and its consumers (packages/core/src/runtime/vfx.ts) land in
Task 1.2/1.3 of the vfx-chain-runtime plan, so vfx.ts is added to
.fallowrc.jsonc's entry list for now.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(runtime): paint data-vfx-chain canvases on every seek

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(vfx): fractal-noise kernel (Basic/fBm approximation) with CPU reference

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(vfx): self capture through layoutsubtree with the page-composite readiness protocol

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(vfx): wave-warp kernel (Sine)

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(vfx): displacement-map kernel (self-referential map)

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(vfx): chain order is nesting order; preceding CSS effects are captured

...and following ones apply outside. The plan's one-line message for Task 2.4
is 105 characters; commitlint caps the header at 100, so the tail moved here.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(vfx): seek determinism and CPU-reference PSNR for fractal-noise

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(vfx): size the output canvas from the host's layout box, not its transformed AABB

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(telemetry): vfx node count, capture class and types on render_complete

Threads vfxNodeCount, vfxCapture and vfxTypes from a static scan of the
compiled composition's data-vfx-chain hosts (mirrors the existing
compositionElementCount/colorGradingCount scan) through
RenderPerfSummary.drawElement into the render_complete event, next to
de_capture_mode. Exports chainCapture/parseVfxChain/HfVfxCapture from
@hyperframes/core's index for the producer to consume. The PostHog
dashboard tile is not created here — left for the coordinator.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(vfx): data-vfx-chain guide — element shape, capture table, Studio flag, known constraints

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(vfx): register chain hosts that arrive with a sub-composition mount

`initVfx(document.body, fps)` ran once, synchronously, three lines after
`void loadExternalCompositions(...)` — so every `data-vfx-chain` host that
enters the DOM only when a `data-composition-src` mount resolves was never
registered. An unregistered host paints nothing and reports nothing: no
`[HyperFrames] composition script error`, the `.hf-vfx-out` canvas keeps its
300x150 default, and `paintVfx` never even arms the page-composite flag.
Measured on a real multi-file export served raw: `#main-l5-text`'s output
canvas stayed 300x150 and `window.__timelines` never gained the sub-comp.

Re-scan in the loader's `.finally`, before `maybePublishRenderReady()`, so
registration precedes readiness. `initVfx` now releases the outgoing
registry's programs, capture textures and ping-pong targets first — the
output canvas hands back the same WebGL2 context on a re-scan, so the
previous pass's GL objects would otherwise leak.

Two browser cases in `vfxDeterminism.test.ts`, both against the real runtime
bundle: a host whose `.hf-vfx-in` IS the mount (already worked — the mount
replaces the wrapper's children, not the wrapper, so the registered source
node survives), and a host that arrives INSIDE a mounted sub-composition
(failed with `armed: false` and no error; passes now).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(vfx): runtime tsconfig typecheck passes

Under noUncheckedIndexedAccess, resolveCaptureSource's null return
widened VfxEntry.src past its VfxCaptureSource | undefined type; the
function is internal-only, so its return type moves to
VfxCaptureSource | undefined instead. Indexing PingPong.framebuffers
by a non-literal index produced | undefined against
WebGLFramebuffer | null, coalesced to null. No behavior change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(vfx): structural DOM predicates instead of realm-bound instanceof

vfx.ts checked `instanceof HTMLCanvasElement`/`HTMLElement` directly, which
returns false for inner-realm nodes when the Studio previews across an
iframe realm. domRealm.ts had no canvas predicate yet, so this adds
isCanvasElement mirroring the existing isImageElement pattern, then swaps
all three vfx.ts checks to the structural predicates the lint guard requires.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(vfx): paint self-capture hosts under hyperframes snapshot, not only the engine path

`paintVfx(t, { engineMode: true })` armed the page-composite protocol and
returned, betting that every capturing chain runs under `frameCapture.ts`.
`hyperframes snapshot` (and check/compare/validate/layout, and Studio's
thumbnail capture) seek through the same `renderSeek`, never read
`__hf_page_composite_pending` and never call `__hf_page_composite_resolve` —
so a `self` chain painted nothing there, in silence, because its content
lives in a `layoutsubtree` canvas the browser never paints directly.

Engine mode now arms the preview-side capture as well and paints on whichever
completes first. A seek token stops a superseded async capture from repainting
a newer frame, and a registry-identity check stops it painting an entry
`initVfx` already released. `resolveVfxCapture` stays non-idempotent on
purpose: the engine resolves only after its own before-capture hooks have
mutated the DOM, so its capture is still the authoritative one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(vfx): an exporter-emitted .hf-vfx-out gets the box the spec fixes for it

findOrCreateOut adopted a canvas the exporter had already emitted without
applying the layout cssText, so it kept the default position:static;
display:inline and wrapped to the line AFTER the layer-wide .hf-vfx-src
canvas — painting a second, misplaced copy of the layer one full layer
height below the host. Measured on retro-wave #main-l6-text: .hf-vfx-src
rect top 315.1 h 93.0, .hf-vfx-out rect top 409.2, both style=null,
position static (ae-mcp findings Task 3.5b). Hosts with no emitted
out-canvas were never affected, which is why only this one host moved.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* refactor(telemetry): vfx_node_count counts hosts, not chain nodes — rename to vfx_host_count

The field increments once per `data-vfx-chain` attribute occurrence, never
per node inside a chain's JSON, so the name promised something the scan does
not measure. Renames the internal `vfxNodeCount` and the wire property
`vfx_node_count` to `vfxHostCount`/`vfx_host_count` across the orchestrator
scan, the perf summary, the CLI render path and the telemetry event. No
dashboard consumes the field yet, so the wire rename costs nothing now and
would cost a migration later.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(vfx): join the preview capture to the seek-completion barrier, not race it

`paintVfx` fired `capturePreviewThenPaint` and forgot it, so nothing the CLI
awaits waited for a `self` chain's paint. Every snapshot-family command
(`snapshot`, `check`, `compare`, `validate`, `layout`) seeks through
`seekCompositionTimeline`, which drains `window.__hfWaitForSeekCompletion`
and then allows one settle race before screenshotting — and only the
`"hf-seek"` event's `waitUntil()` could put anything in that barrier. The
screenshot therefore landed on however many hosts happened to have finished,
which varied with host count and machine speed.

Extracts the "track, untrack on settle, retain the first rejection" block
`dispatch()` built inline into an exported `registerSeekCompletion`, and has
`paintVfx` register the preview capture through it. Also awaits the per-host
paints with `Promise.all` instead of sequentially: N hosts cost about two
animation frames now, not 2N.

Measured on the pre-fix bundle with two `self` hosts, both output canvases
read `[0,0,0,0]` at the moment the barrier returned; they painted only
because the settle race that follows happened to be long enough. Both tests
added here fail on that bundle.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(vfx): report WebGL context loss loudly instead of silently no-op painting

One WebGL2 context per `data-vfx-chain` host, against a browser cap that is
commonly 16 and shared with `colorGrading.ts`'s per-element contexts. A lost
context makes every later call on it do nothing, per spec — so the chain kept
"painting" a blank canvas with no error, which is exactly what the module's
loud-failure contract exists to prevent.

Adds the `webglcontextlost` listener pair's first half, following
`colorGrading.ts`'s precedent: `preventDefault()`, mark the entry, report
once through `reportVfxError`. The entry is then skipped by `paintVfx`,
`capturePreviewThenPaint` and `resolveVfxCapture` — silently, since the one
loud report already happened and repeating it per frame is spam.

Restore is left unhandled on purpose, with the reasoning in the doc comment:
`initVfx`'s existing re-scan already rebuilds every GL object, and a second
narrower rebuild path for `webglcontextrestored` would duplicate it. The
shared-context redesign the review floated is likewise out of scope here.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* perf(vfx): cache uniform locations at pass-build time instead of querying every paint

`setPassUniforms` asked the driver for `u_size`, `u_t`, `u_fps` and every
param's location on every paint of every pass, and `bindPass` did the same
for `u_src` on every bind. `buildPasses` already constructs each `VfxPass`
once at init, right after the program links, and a linked program's
locations never change — so they are resolved there now and read from
`pass.locations` in the hot path.

Same values, same `null`-means-optimised-out semantics (`gl.uniform*(null,
…)` is a defined no-op, which is what the per-frame query produced too), so
the existing vfx.test.ts and the browser determinism suite cover it
unchanged — both still green, the latter against a rebuilt runtime bundle.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(vfx): bound the paint wait per host so a stalled compositor can't hang the seek barrier

`paintVfx` registers `capturePreviewThenPaint` into the shared seek-completion
barrier (48aaa2bbb), and that promise settled only via `awaitCanvasPaint` — a
race between the canvas `paint` event and a double-rAF chain. Under BeginFrame
control (Linux headless-shell, `drawelement` capture) neither can fire before
the barrier is drained: `frameCapture.ts` awaits the barrier in
`prepareFrameForCapture` (~2692), while the frame's
`HeadlessExperimental.beginFrame` is issued later, in the per-frame capture
stage (~3797). Fire-and-forget that was harmless; registered it can stall every
`__hfWaitForSeekCompletion` caller, the engine's render path included.

rAF-under-BeginFrame: CONFIRMED gated, from this repo's own engine notes —
`frameCapture.ts` ~2445 ("waitForFunction uses rAF polling internally, which
won't fire in beginFrame mode") and ~4755 ("headless only fires rAF when a
frame is produced, and nothing produces one until a screenshot asks"). Not
reproduced locally: every environment here is macOS with a free-running
compositor (`beginFrameTimeTicks === 0`). `setTimeout` is not compositor-gated
there — `drawElementService.ts` ~341 describes its 250 ms paint fallback as
burning on every BeginFrame frame, which requires the timer to fire — so a
timer ceiling is a sound escape.

`awaitCanvasPaint` now resolves `"painted" | "timeout"` with a 2000 ms ceiling
(the repo's own `BEGINFRAME_PROBE_TIMEOUT_MS`; ~20x a real two-frame paint,
far short of the ~180 s CDP `protocolTimeout` a hang would burn). The race is
per host, so one stalled compositor no longer delays hosts that would have
painted; a timed-out host is skipped (no capture, no guessed pixels) and
reported loudly. The report is not suppressed in engine mode: `frameCapture.ts`
~2708 skips `__hf_page_composite_resolve` in `drawelement`/`beginframe` modes,
so there is no authoritative second attempt to defer to there.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore(ci): re-pin test-classification.mjs hash after registering vfxDeterminism.test.ts

An earlier commit added vfxDeterminism.test.ts to INTEGRATION_TEST_FILES;
check-test-reachability.mjs pins a sha256 of that file to force a conscious
review whenever it changes. Reviewed: runner[1]'s glob already covers the
file structurally, the classification move (unit -> integration) is correct
for a Chrome-launching test, and the pinned hash is now current.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(core): regenerate position-edits-render-inline.ts for Linux esbuild output

check:position-edits-render (bun run build:position-edits-render && git diff
--exit-code) failed on both Linux CI runners (Test (runtime), Tests on
windows-latest: studio-core) but passed on macOS: esbuild's minifier named
two identically-scoped WeakMap/function bindings differently on Linux than
on the mac that last committed this artifact, and the divergence appeared
only on this branch (main's own current tip passes CI cleanly), so it is
tied to a change on this branch rather than a random flake, even though it
is not attributable to any specific line of that change.

Confirmed stable across two independent Linux CI runs (byte-identical diff
both times) and reconstructed directly from that diff rather than guessed:
the committed content, byte length (3817), and 3/3 existing artifact tests
all match. A future contributor rebuilding on macOS will see this same
diff again in the other direction until the build script's cross-platform
determinism is fixed at the esbuild-invocation level, which is out of this
PR's scope.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 03:14:08 -07:00

597 lines
16 KiB
TypeScript

/**
* VFX chain: the one description of every per-pixel effect that can be
* applied to a layer's own pixels through the WebGL2 runtime.
*
* Mirrors `audioFx.ts` (`data-fx-chain`) in shape: a versioned JSON chain
* attribute, a def registry with typed params, and parse/serialize/normalize
* helpers so the exporter and the runtime agree on one description of each
* effect.
*/
import { FRACTAL_NOISE_FRAG } from "./vfx/fractalNoise.frag";
import { DISPLACEMENT_MAP_FRAG } from "./vfx/displacementMap.frag";
import { WAVE_WARP_FRAG } from "./vfx/waveWarp.frag";
export const HF_VFX_ATTR = "data-vfx-chain";
/**
* Chain files are versioned; a reader must refuse a version it doesn't know.
* Exported for the exporter (hyperframes-ae-mcp), which stamps the version it
* emits; inside this repo only parse/serialize below read it.
*/
// fallow-ignore-next-line unused-export
export const HF_VFX_CHAIN_VERSION = 1;
/**
* What a def's kernel must read besides `(x, y, t, params)`:
* - `none` — the kernel is a generator/replacement; no captured texture.
* - `self` — the kernel reads the host's own pixels through a `layoutsubtree`
* capture canvas.
* - `backdrop` — the kernel reads everything below the host (adjustment-layer
* style effects).
*/
export type HfVfxCapture = "none" | "self" | "backdrop";
export interface HfVfxNumberParam {
kind: "number";
key: string;
label: string;
unit: string;
min: number;
max: number;
step: number;
default: number;
/** May be driven by a `--vfx-<nodeId>-<key>` CSS var instead of `params`. */
animatable?: boolean;
hint?: string;
}
export interface HfVfxEnumParam {
kind: "enum";
key: string;
label: string;
options: readonly { value: number; label: string }[];
default: number;
hint?: string;
}
export interface HfVfxBoolParam {
kind: "bool";
key: string;
label: string;
default: boolean;
}
/** A second-source param (v1.1): its value is the id of another element. */
export interface HfVfxRefParam {
kind: "ref";
key: string;
label: string;
}
export type HfVfxParam = HfVfxNumberParam | HfVfxEnumParam | HfVfxBoolParam | HfVfxRefParam;
/** `string` values only occur for `ref` params (element ids). */
export type HfVfxParamValues = Record<string, number | boolean | string>;
export interface HfVfxDef {
id: string;
label: string;
/** What the kernel must read besides (x, y, t, params). */
capture: HfVfxCapture;
params: readonly HfVfxParam[];
/** GLSL ES 3.00 fragment source; uniforms are u_size/u_t/u_fps/u_src(2)/u_<key>. */
frag: string;
/** AE match name this def ports, for docs — e.g. "ADBE Fractal Noise". */
ae?: string;
}
/**
* After Effects' channel selector, shared by both Displacement Map axes.
* Hue (6), Lightness (7) and Saturation (8) stay selectable and are read as
* Luminance by the kernel — folding them back to the param's default would
* mean Red on the horizontal axis, a much larger error.
*/
const DISPLACEMENT_CHANNELS = [
{ value: 1, label: "Red" },
{ value: 2, label: "Green" },
{ value: 3, label: "Blue" },
{ value: 4, label: "Alpha" },
{ value: 5, label: "Luminance" },
{ value: 6, label: "Hue" },
{ value: 7, label: "Lightness" },
{ value: 8, label: "Saturation" },
{ value: 9, label: "Full" },
{ value: 10, label: "Half" },
{ value: 11, label: "Off" },
] as const;
/**
* The def registry. Params come from the AE deep dives and retro-wave's
* observed values; each kernel's own `frag` module states the v1 scope
* decision — which of the effect's modes it actually implements and why.
*
* Exported as the whole registry for the exporter and Studio's effect picker;
* inside the runtime, defs are reached through `getVfxDef`.
*/
// fallow-ignore-next-line unused-export
export const HF_VFX: readonly HfVfxDef[] = [
{
id: "fractal-noise",
label: "Fractal Noise",
ae: "ADBE Fractal Noise",
capture: "none",
frag: FRACTAL_NOISE_FRAG,
params: [
{
kind: "enum",
key: "fractalType",
label: "Fractal Type",
options: [{ value: 1, label: "Basic" }],
default: 1,
hint: "Only Basic is implemented in v1.",
},
{
kind: "enum",
key: "noiseType",
label: "Noise Type",
options: [
{ value: 1, label: "Block" },
{ value: 2, label: "Linear" },
{ value: 3, label: "Soft Linear" },
{ value: 4, label: "Spline" },
],
default: 3,
},
{ kind: "bool", key: "invert", label: "Invert", default: false },
{
kind: "number",
key: "contrast",
label: "Contrast",
unit: "%",
min: 0,
max: 1000,
step: 1,
default: 100,
},
{
kind: "number",
key: "brightness",
label: "Brightness",
unit: "",
min: -1000,
max: 1000,
step: 1,
default: 0,
},
{
kind: "number",
key: "scale",
label: "Scale",
unit: "%",
min: 6,
max: 10000,
step: 1,
default: 100,
},
{
kind: "number",
key: "complexity",
label: "Complexity",
unit: "",
min: 1,
max: 20,
step: 1,
default: 6,
},
{
kind: "number",
key: "subInfluence",
label: "Sub Influence",
unit: "%",
min: 0,
max: 100,
step: 1,
default: 70,
},
{
kind: "number",
key: "subScaling",
label: "Sub Scaling",
unit: "%",
min: 0,
max: 100,
step: 1,
default: 56,
},
{
kind: "number",
key: "evolution",
label: "Evolution",
unit: "revolutions",
min: -10000,
max: 10000,
step: 0.01,
default: 0,
animatable: true,
},
{
kind: "number",
key: "randomSeed",
label: "Random Seed",
unit: "",
min: 0,
max: 99999,
step: 1,
default: 0,
},
{
kind: "number",
key: "opacity",
label: "Opacity",
unit: "%",
min: 0,
max: 100,
step: 1,
default: 100,
animatable: true,
},
],
},
{
id: "wave-warp",
label: "Wave Warp",
ae: "ADBE Wave Warp",
capture: "self",
frag: WAVE_WARP_FRAG,
params: [
{
kind: "enum",
key: "waveType",
label: "Wave Type",
options: [{ value: 1, label: "Sine" }],
default: 1,
hint: "Only Sine is implemented in v1; the exporter marks the others cosmetic.",
},
{
kind: "number",
key: "height",
label: "Wave Height",
unit: "px",
min: -1000,
max: 1000,
step: 1,
default: 10,
animatable: true,
},
{
kind: "number",
key: "width",
label: "Wave Width",
unit: "px",
min: 1,
max: 10000,
step: 1,
default: 40,
animatable: true,
},
{
kind: "number",
key: "direction",
label: "Direction",
unit: "deg",
min: -360,
max: 360,
step: 1,
default: 90,
},
{
kind: "number",
key: "speed",
label: "Wave Speed",
unit: "waves/s",
min: -100,
max: 100,
step: 0.1,
default: 1,
},
{
kind: "enum",
key: "pinning",
label: "Pinning",
options: [{ value: 1, label: "None" }],
default: 1,
hint: "Only None is implemented in v1; the exporter marks the others cosmetic.",
},
{
kind: "number",
key: "phase",
label: "Phase",
unit: "deg",
min: -360,
max: 360,
step: 1,
default: 0,
animatable: true,
},
],
},
{
id: "displacement-map",
label: "Displacement Map",
ae: "ADBE Displacement Map",
capture: "self",
frag: DISPLACEMENT_MAP_FRAG,
params: [
{
kind: "enum",
key: "useH",
label: "Use For Horizontal Displacement",
options: DISPLACEMENT_CHANNELS,
default: 1,
hint: "Hue, Lightness and Saturation are read as Luminance in v1.",
},
{
kind: "number",
key: "maxH",
label: "Max Horizontal Displacement",
unit: "px",
min: -32000,
max: 32000,
step: 1,
default: 5,
animatable: true,
},
{
kind: "enum",
key: "useV",
label: "Use For Vertical Displacement",
options: DISPLACEMENT_CHANNELS,
default: 2,
hint: "Hue, Lightness and Saturation are read as Luminance in v1.",
},
{
kind: "number",
key: "maxV",
label: "Max Vertical Displacement",
unit: "px",
min: -32000,
max: 32000,
step: 1,
default: 5,
animatable: true,
},
{
kind: "enum",
key: "behavior",
label: "Displacement Map Behavior",
options: [{ value: 1, label: "Center Map" }],
default: 1,
hint: "Only Center Map is implemented in v1.",
},
{
kind: "enum",
key: "edge",
label: "Edge Behavior",
options: [{ value: 0, label: "Off" }],
default: 0,
hint: "Only Off (transparent outside the layer) is implemented in v1.",
},
{
kind: "bool",
key: "expand",
label: "Expand Output",
default: true,
},
],
},
] as const;
const BY_ID = new Map(HF_VFX.map((d) => [d.id, d]));
export function getVfxDef(id: string): HfVfxDef | undefined {
return BY_ID.get(id);
}
/**
* Clamp and fill a parameter set so it is always renderable: unknown keys are
* dropped, missing keys take their default, numbers are clamped into their
* declared range, an unrecognised enum value falls back to its default, and a
* non-boolean bool value falls back to its default. Mirrors
* `normalizeAudioFxParams`.
*/
export function normalizeVfxParams(
id: string,
values: Readonly<HfVfxParamValues> | undefined,
): HfVfxParamValues {
const def = BY_ID.get(id);
if (!def) return {};
const out: HfVfxParamValues = {};
for (const p of def.params) {
const raw = values?.[p.key];
out[p.key] =
p.kind === "enum"
? normalizeEnumParam(p, raw)
: p.kind === "bool"
? normalizeBoolParam(p, raw)
: p.kind === "ref"
? normalizeRefParam(raw)
: normalizeNumberParam(p, raw);
}
return out;
}
/** A number, or a string that actually spells one; `undefined` otherwise.
* `Number(null)`, `Number("")`, `Number(false)` and `Number([])` are all 0
* and all pass `Number.isFinite`, so a raw value of that shape must be
* treated as missing rather than coerced to 0 — 0 is a legal value for most
* of these knobs, so nothing downstream could otherwise tell. */
function coerceFiniteNumber(raw: unknown): number | undefined {
const n =
typeof raw === "number"
? raw
: typeof raw === "string" && raw.trim() !== ""
? Number(raw)
: Number.NaN;
return Number.isFinite(n) ? n : undefined;
}
function normalizeEnumParam(p: HfVfxEnumParam, raw: unknown): number {
const n = coerceFiniteNumber(raw);
return n !== undefined && p.options.some((o) => o.value === n) ? n : p.default;
}
function normalizeBoolParam(p: HfVfxBoolParam, raw: unknown): boolean {
return typeof raw === "boolean" ? raw : p.default;
}
function normalizeRefParam(raw: unknown): string {
return typeof raw === "string" ? raw : "";
}
function normalizeNumberParam(p: HfVfxNumberParam, raw: unknown): number {
const n = coerceFiniteNumber(raw);
return n !== undefined ? Math.min(p.max, Math.max(p.min, n)) : p.default;
}
export interface HfVfxNode {
type: string;
id: string;
enabled?: boolean;
params: HfVfxParamValues;
}
export interface HfVfxChain {
version: 1;
nodes: HfVfxNode[];
}
export class VfxChainError extends Error {
constructor(message: string) {
super(message);
this.name = "VfxChainError";
}
}
/** The nodes that should paint, in order. */
export function enabledVfxNodes(chain: HfVfxChain): HfVfxNode[] {
return chain.nodes.filter((n) => n.enabled !== false);
}
const CAPTURE_RANK: Record<HfVfxCapture, number> = { none: 0, self: 1, backdrop: 2 };
/** A chain's capture requirement is the strongest of its enabled nodes'. */
export function chainCapture(chain: HfVfxChain): HfVfxCapture {
let best: HfVfxCapture = "none";
for (const node of enabledVfxNodes(chain)) {
const def = BY_ID.get(node.type);
if (def && CAPTURE_RANK[def.capture] > CAPTURE_RANK[best]) best = def.capture;
}
return best;
}
/**
* Parse a chain file. Unknown effect ids are rejected rather than skipped: a
* chain that silently loses a node would render differently from the
* composition the author saved, which is worse than refusing to render at
* all. Params are kept as given (not normalized) so a chain round-trips
* exactly; call `normalizeVfxParams` at paint time.
*/
export function parseVfxChain(json: string): HfVfxChain {
let raw: unknown;
try {
raw = JSON.parse(json);
} catch (err) {
throw new VfxChainError(`Chain file is not valid JSON: ${(err as Error).message}`);
}
if (typeof raw !== "object" || raw === null) {
throw new VfxChainError("Chain file must be a JSON object.");
}
const obj = raw as { version?: unknown; nodes?: unknown };
if (obj.version !== HF_VFX_CHAIN_VERSION) {
throw new VfxChainError(`Unsupported chain version: ${String(obj.version)}`);
}
if (!Array.isArray(obj.nodes)) {
throw new VfxChainError("Chain file is missing a `nodes` array.");
}
const nodes = obj.nodes.map(parseVfxNode);
return { version: HF_VFX_CHAIN_VERSION, nodes };
}
/** Serialise a chain for the `data-vfx-chain` attribute. */
export function serializeVfxChain(chain: HfVfxChain): string {
return JSON.stringify({
version: HF_VFX_CHAIN_VERSION,
nodes: chain.nodes.map(serializeVfxNode),
});
}
/** The shape a node is READ as: everything unknown until checked. */
interface RawVfxNode {
type?: unknown;
id?: unknown;
enabled?: unknown;
params?: unknown;
}
function isPlainObject(v: unknown): v is Record<string, unknown> {
return typeof v === "object" && v !== null;
}
function requireVfxNodeType(node: RawVfxNode, i: number): string {
if (typeof node.type !== "string" || !BY_ID.has(node.type)) {
throw new VfxChainError(`Node ${i} has unknown effect type: ${String(node.type)}`);
}
return node.type;
}
function requireVfxNodeId(node: RawVfxNode, i: number): string {
if (typeof node.id !== "string" || node.id === "") {
throw new VfxChainError(`Node ${i} is missing an id.`);
}
return node.id;
}
/**
* One node out of a chain file, validated. Throws rather than dropping: a
* chain that silently loses a node would render differently from the
* composition the author saved.
*/
function parseVfxNode(n: unknown, i: number): HfVfxNode {
if (!isPlainObject(n)) {
throw new VfxChainError(`Node ${i} is not an object.`);
}
const node = n as RawVfxNode;
const type = requireVfxNodeType(node, i);
const id = requireVfxNodeId(node, i);
const params = isPlainObject(node.params) ? (node.params as HfVfxParamValues) : {};
return withoutUndefined({
type,
id,
enabled: node.enabled === false ? false : undefined,
params,
});
}
/** One node as the `data-vfx-chain` attribute carries it. `enabled` is
* omitted when it holds its default, so a plain chain stays plain. */
function serializeVfxNode(node: HfVfxNode) {
return withoutUndefined({
type: node.type,
id: node.id,
enabled: node.enabled === false ? false : undefined,
params: node.params,
});
}
// Mirrors audioFx.ts's identical helper (Task 1.1: copy the shape of the
// audio chain, not its code — the two chain files stay independently
// readable rather than sharing a module neither owns).
// fallow-ignore-next-line code-duplication
function withoutUndefined<T extends object>(obj: T): T {
for (const key of Object.keys(obj) as Array<keyof T>) {
if (obj[key] === undefined) delete obj[key];
}
return obj;
}