Skip to content

Commit 9aa60a8

Browse files
fix(registry): make motion-blur match After Effects shutter-based blur (#4008)
* fix(registry): make motion-blur match After Effects shutter-based blur The motion-blur catalog snippet estimated speed from the x/y delta between consecutive timeline updates and drew three one-sided ghost copies with decaying alpha plus a Gaussian on top. After Effects does temporal supersampling: each frame integrates the layer over a shutter window (shutter angle, shutter phase, samples per frame), producing a symmetric box smear of length speed x shutter time. The snippet now does the same inside the page. After every timeline update a deferred pass seeks the GSAP timeline to N sub-frame times across the shutter window (events suppressed), reads each target's x/y, restores the frame time, and drives an SVG filter that averages N feOffset copies with equal weight (feComposite arithmetic, 1/N, sRGB). Defaults follow AE: shutterAngle 180, shutterPhase -90, samplesPerFrame 16; fps comes from the render config, then the root data-fps, then 30. Displacements are mapped through the inverse of the element's own scale/rotation; percent x/y values are resolved to px; SVG targets use their bbox; an existing inline filter is kept and the blur appended to it. The pass runs in a microtask rather than inside the tracker tween's onUpdate, because seeking GSAP from within its own render reads stale tween state and suppresses the composition's callbacks on forward seeks. The heuristic options blurScale/blurMax/stretchScale/stretchMax are removed. Reference: an AE-algorithm reconstruction of the same composition rendered without the component at an effective 960 fps and averaged over the 16 sub-frames of the 180 degree window per output frame. Against it (1920x1080, 30 fps, solid + text translating linear then power2.inOut): old mean PSNR 53.2 dB (min 26.7), SSIM 0.9930; new mean PSNR 72.4 dB (min 52.6), SSIM 0.9998. The 10-90 edge ramp at 66.7 px/frame is 26.8 px in the reference, 27.5 px new, 14.5/6.3 px (one-sided) old; at the ease peak 79.3 vs 79.5 vs 7.9/17.7 px, with smear centres matching to 0.1 px. Co-Authored-By: Miguel Ángel <[email protected]> * fix(registry): drop render-config fps probe from motion-blur and refresh its docs The snippet resolved fps by reconstructing the renderer's private seek config key so the compiler's inline-script guard would not strip it. A public catalog snippet must not depend on that key, so fps is now the explicit option, then the root data-fps, then 30; renders with an fps override pass fps explicitly. The catalog page's Usage, How it works and Options sections still described the old velocity heuristic and are rewritten for the shutter model. The 1/N weight keeps full precision. Co-Authored-By: Miguel Ángel <[email protected]> * fix(registry): match the After Effects reference export's shutter window The shutter model landed on this branch was built against a reconstruction of After Effects' algorithm, not against After Effects. A real 1920x1080 / 30 fps export of translating text disagrees with it on three points, all measurable off the export itself. The window is two frames wide, not half a frame. On the measured frame the outermost duplicate on the trailing side sits 128 px back while the previous frame is 125.8 px back, and the outermost leading duplicate sits 189 px ahead while the next frame is 184.9 px ahead: the window ends land on the neighbouring frames. Defaults become shutterAngle 720, shutterPhase -360. Duplicates sit on the sub-interval boundaries, both ends included, not at sub-interval centres. The staircase across a stroke steps every 15.6 px on a 125.8 px displacement and every 23.0 px on a 184.9 px one, i.e. an eighth of a frame, with the run closing exactly on the neighbouring frame's position. samplesPerFrame now means sub-intervals of the window, so there are N+1 copies at k/N rather than N copies at (k+0.5)/N. The frame-time instance is drawn sharp over the smear. At full ink the core bounding box is the whole word at every frame and total ink rises to 1.44x the unblurred frame's, neither of which an average can produce. A final feComposite over of SourceGraphic reproduces it. Each duplicate stays at 1/N: the staircase plateaus step by 0.063 +- 0.002 of the sharp text intensity, flat, with no taper toward the window edges, and triangle weighting scores 1.6 dB worse against the export. Verified by replaying the export's translating section as a composition whose sprite is the export's own rest-frame ink and whose eight legs follow its own measured per-frame positions, rendered at 1920x1080 / 30 fps and compared frame by frame over the text band. Mean PSNR against the export rises from 24.19 dB (min 17.07) to 32.51 dB (min 27.57) across 72 frames, and from 19.83 dB (min 17.07) to 32.03 dB (min 27.57) across the 26 frames that actually move. Ghost extents match to a few px and the rendered staircase plateaus match the export's to two decimal places. The export's later scale, skew, flip and 3D rotation sections are out of reach here: integrating anything but translation inside the shutter is engine work tracked in issue #4010. The filter region now clamps its bounds through zero. It was derived from the duplicate offsets alone, which was correct while the output was nothing but duplicates; the sharp instance draws at offset zero, so a window sitting entirely on one side of the frame time - any shutterPhase above 0 or below -shutterAngle - produced a region starting inside the element's own box and cut the instance off. The defaults straddle the frame time and were never affected, so the measured numbers above are unchanged. Co-Authored-By: Miguel Ángel <[email protected]> --------- Co-authored-by: Miguel Ángel <[email protected]>
1 parent 462f9db commit 9aa60a8

12 files changed

Lines changed: 1275 additions & 643 deletions

File tree

‎docs/catalog/components/motion-blur.mdx‎

Lines changed: 292 additions & 177 deletions
Large diffs are not rendered by default.

‎docs/public/catalog-index.json‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3340,13 +3340,14 @@
33403340
"name": "motion-blur",
33413341
"type": "component",
33423342
"title": "Motion Blur",
3343-
"description": "Velocity-driven motion blur — samples element position each frame and applies a one-sided SVG feGaussianBlur ghost trail proportional to speed",
3343+
"description": "After Effects-style motion blur — integrates each element over a shutter window (shutter angle, phase, samples per frame) by sampling the GSAP timeline at sub-frame times and averaging equal-weight SVG copies along the real trajectory",
33443344
"tags": [
33453345
"effect",
33463346
"motion-blur",
3347+
"shutter",
3348+
"after-effects",
33473349
"velocity",
3348-
"animation",
3349-
"physics"
3350+
"animation"
33503351
],
33513352
"href": "/catalog/components/motion-blur",
33523353
"preview": "https://static.heygen.ai/hyperframes-oss/docs/images/catalog/components/motion-blur.png"

‎docs/public/catalog/components/motion-blur.json‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"source": "After Effects export, 1920x1080, 30 fps, bold text translating along x, no other transforms",
3+
"howMeasured": "Frame 5 of the export. The frame-time instance renders sharp at full opacity, so the ink > 0.97 bounding box tracks the word exactly; the duplicates show up as a staircase of plateaus across a vertical stroke. Rows 470 / 540 / 600 agree.",
4+
"frame": 5,
5+
"trailingDisplacementPx": 125.8,
6+
"leadingDisplacementPx": 184.9,
7+
"comment:displacements": "Core-centre travel from frame 4 to 5 and from 5 to 6. Measured ghost reach past the core is 128 px trailing and 189 px leading (both include the anti-aliased edge), i.e. the window ends land on the neighbouring frames' positions.",
8+
"trailingCopyEdgesPx": [531, 546, 562, 578, 594, 609, 625, 640],
9+
"sharpEdgePx": 656,
10+
"comment:edges": "Rising edges of the leading stroke's duplicates on the trailing tail, row 470, outermost first; the sharp instance's edge closes the run. Mean spacing 15.6 px against a 125.8 px frame displacement = 1/8 frame per duplicate.",
11+
"subIntervalsPerWindow": 16,
12+
"windowFramesBefore": 1,
13+
"windowFramesAfter": 1,
14+
"copyOpacity": 0.0625,
15+
"measuredPlateauIncrements": [0.063, 0.065, 0.063, 0.063, 0.063],
16+
"comment:opacity": "Plateau heights across the trailing staircase, as a fraction of the sharp text intensity: 0.07 0.13 0.20 0.26 0.32 0.38. Flat, not tapered toward the window edge, and no duplicate approaches full opacity."
17+
}
Lines changed: 247 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,247 @@
1+
// @vitest-environment happy-dom
2+
import { readFileSync } from "node:fs";
3+
import { dirname, resolve } from "node:path";
4+
import { fileURLToPath } from "node:url";
5+
import { afterEach, describe, expect, it } from "vitest";
6+
import reference from "./__fixtures__/motion-blur-ae-reference.json";
7+
8+
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..");
9+
10+
function readRepoFile(relativePath: string): string {
11+
return readFileSync(resolve(repoRoot, relativePath), "utf8");
12+
}
13+
14+
const snippetHtml = readRepoFile("registry/components/motion-blur/motion-blur.html");
15+
16+
/** First line of the snippet's IIFE body, which runs to the `};` closing it at the same indent. */
17+
const BODY_FIRST_LINE = "if (!window._hfMbUid) window._hfMbUid = 0;";
18+
const SNIPPET_INDENT = " ".repeat(4);
19+
const INLINED_INDENT = " ".repeat(10);
20+
21+
/**
22+
* The snippet's IIFE body, leading whitespace dropped so the installable snippet and its inlined
23+
* copies compare regardless of how deeply each one nests it.
24+
*/
25+
function snippetBody(source: string, indent: string): string {
26+
const start = source.indexOf(indent + BODY_FIRST_LINE);
27+
const endMarker = `\n${indent}};`;
28+
const end = source.indexOf(endMarker, start);
29+
if (start < 0 || end < 0) {
30+
throw new Error(`could not locate the snippet body at indent ${indent.length}`);
31+
}
32+
return source
33+
.slice(start, end + endMarker.length)
34+
.split("\n")
35+
.map((line) => line.trimStart())
36+
.join("\n");
37+
}
38+
39+
const FPS = 30;
40+
/** Timeline time of the frame under test, and a duration long enough that no seek is clamped. */
41+
const FRAME_TIME_S = 5;
42+
const DURATION_S = 10;
43+
const WORD_WIDTH = 1046;
44+
const WORD_HEIGHT = 193;
45+
46+
/** The slice of GSAP's timeline API the snippet drives; `time()` reads, `time(value)` seeks. */
47+
interface Timeline {
48+
time(value?: number, suppressEvents?: boolean): number | Timeline;
49+
duration(): number;
50+
to(target: unknown, vars: { onUpdate?: () => void }): Timeline;
51+
}
52+
53+
/**
54+
* The reference's own trajectory around the measured frame: a parabola through the core centres of
55+
* frames 4, 5 and 6, with frame 5 at t = 0. Offsets are relative to the frame-time position, so the
56+
* shutter window's ends must land on exactly the trailing and leading displacements the fixture
57+
* records — which is the whole claim being pinned.
58+
*/
59+
function offsetAtFrames(df: number): number {
60+
const back = -reference.trailingDisplacementPx;
61+
const fwd = reference.leadingDisplacementPx;
62+
return ((fwd + back) / 2) * df * df + ((fwd - back) / 2) * df;
63+
}
64+
65+
function installSnippet(): void {
66+
const body = snippetHtml.slice(
67+
snippetHtml.indexOf("<script>") + "<script>".length,
68+
snippetHtml.indexOf("</script>"),
69+
);
70+
new Function(body)();
71+
}
72+
73+
function makeTimeline(): { tl: Timeline; currentTime: () => number; fire: () => void } {
74+
let now = FRAME_TIME_S;
75+
let onUpdate: (() => void) | undefined;
76+
const tl: Timeline = {
77+
time(value?: number) {
78+
if (value === undefined) return now;
79+
now = value;
80+
return tl;
81+
},
82+
duration: () => DURATION_S,
83+
to(_target, vars) {
84+
onUpdate = vars.onUpdate;
85+
return tl;
86+
},
87+
};
88+
return { tl, currentTime: () => now, fire: () => onUpdate?.() };
89+
}
90+
91+
function installGsap(currentTime: () => number, trajectory: (df: number) => number): void {
92+
(globalThis as unknown as { gsap: unknown }).gsap = {
93+
getProperty(_el: Element, prop: string) {
94+
if (prop === "x") return `${trajectory((currentTime() - FRAME_TIME_S) * FPS)}px`;
95+
if (prop === "scaleX" || prop === "scaleY") return 1;
96+
return 0;
97+
},
98+
};
99+
}
100+
101+
async function attach(
102+
options: Record<string, unknown>,
103+
trajectory: (df: number) => number = offsetAtFrames,
104+
): Promise<Element> {
105+
const el = document.createElement("div");
106+
el.id = "word";
107+
Object.defineProperty(el, "offsetWidth", { value: WORD_WIDTH });
108+
Object.defineProperty(el, "offsetHeight", { value: WORD_HEIGHT });
109+
document.body.appendChild(el);
110+
111+
const { tl, currentTime, fire } = makeTimeline();
112+
installGsap(currentTime, trajectory);
113+
installSnippet();
114+
(
115+
window as unknown as { attachMotionBlur: (s: string, t: Timeline, o: unknown) => void }
116+
).attachMotionBlur("#word", tl, options);
117+
118+
fire();
119+
await Promise.resolve();
120+
const filter = document.querySelector("filter");
121+
if (!filter) throw new Error("motion-blur filter was not created");
122+
return filter;
123+
}
124+
125+
/** Horizontal offset of every duplicate, in window order. */
126+
function copyOffsets(filter: Element): number[] {
127+
return [...filter.querySelectorAll("feOffset")].map((node) => Number(node.getAttribute("dx")));
128+
}
129+
130+
/** The duplicates sitting at the two ends of the shutter window. */
131+
function windowEdges(offsets: number[]): { trailing: number; leading: number } {
132+
const [trailing] = offsets;
133+
const leading = offsets.at(-1);
134+
if (trailing === undefined || leading === undefined) {
135+
throw new Error("the filter carries no duplicates");
136+
}
137+
return { trailing, leading };
138+
}
139+
140+
/** Gap between each pair of neighbouring duplicates. */
141+
function copyPitches(offsets: number[]): number[] {
142+
const pitches: number[] = [];
143+
offsets.forEach((offset, index) => {
144+
const previous = offsets[index - 1];
145+
if (previous !== undefined) pitches.push(offset - previous);
146+
});
147+
return pitches;
148+
}
149+
150+
afterEach(() => {
151+
document.body.innerHTML = "";
152+
});
153+
154+
describe("motion-blur snippet copies", () => {
155+
// The demo and the example composition have to inline the snippet — a catalog demo is a single
156+
// self-contained file and cannot import one. That makes three copies of the same shutter model, so
157+
// the copies are asserted equal here rather than left to drift silently.
158+
it.each([
159+
"registry/components/motion-blur/demo.html",
160+
"registry/examples/motion-blur/index.html",
161+
])("%s inlines the installable snippet verbatim", (relativePath) => {
162+
expect(snippetBody(readRepoFile(relativePath), INLINED_INDENT)).toBe(
163+
snippetBody(snippetHtml, SNIPPET_INDENT),
164+
);
165+
});
166+
});
167+
168+
describe("motion-blur shutter matches the After Effects reference", () => {
169+
it("opens the shutter over the frame before and the frame after, at the measured sub-interval count", async () => {
170+
const offsets = copyOffsets(await attach({ fps: FPS }));
171+
const { trailing, leading } = windowEdges(offsets);
172+
173+
expect(offsets).toHaveLength(reference.subIntervalsPerWindow + 1);
174+
expect(trailing).toBeCloseTo(-reference.trailingDisplacementPx, 1);
175+
expect(leading).toBeCloseTo(reference.leadingDisplacementPx, 1);
176+
});
177+
178+
it("spaces the duplicates at the measured staircase pitch", async () => {
179+
// The reference's staircase is even (15, 16, 16, 15, 16, 16, 16 px across a 125.8 px frame
180+
// displacement), so a constant-velocity trajectory has to come out evenly spaced at 1/8 frame.
181+
const speed = reference.trailingDisplacementPx;
182+
const offsets = copyOffsets(await attach({ fps: FPS }, (df) => speed * df));
183+
const expected = speed / (reference.subIntervalsPerWindow / 2);
184+
185+
for (const pitch of copyPitches(offsets)) expect(pitch).toBeCloseTo(expected, 3);
186+
});
187+
188+
it("gives every duplicate the measured 1/16 opacity and none full opacity", async () => {
189+
const filter = await attach({ fps: FPS });
190+
const weights = [...filter.querySelectorAll("feComposite[operator='arithmetic']")].map((node) =>
191+
Number(node.getAttribute("k3")),
192+
);
193+
194+
expect(weights).toHaveLength(reference.subIntervalsPerWindow);
195+
for (const weight of weights) expect(weight).toBeCloseTo(reference.copyOpacity, 6);
196+
// Flat, not tapered: the reference's plateau increments are all the same height.
197+
expect(new Set(weights).size).toBe(1);
198+
});
199+
200+
it("accumulates every duplicate exactly once, in one unbroken chain", async () => {
201+
const filter = await attach({ fps: FPS });
202+
const adds = [...filter.querySelectorAll("feComposite[operator='arithmetic']")];
203+
const weight = 1 / reference.subIntervalsPerWindow;
204+
205+
// The first composite is the only one that has to scale BOTH inputs, because it is the
206+
// only one whose `in` is a raw duplicate rather than the running sum. Getting its k2
207+
// wrong lets one duplicate through at full weight — the exact thing the reference rules out.
208+
expect(adds[0]?.getAttribute("in")).toBe("s0");
209+
expect(Number(adds[0]?.getAttribute("k2"))).toBeCloseTo(weight, 6);
210+
for (const add of adds.slice(1)) expect(Number(add.getAttribute("k2"))).toBe(1);
211+
212+
// Each composite must fold in the next duplicate and feed the one after it, so every
213+
// duplicate reaches the output and none is added twice.
214+
adds.forEach((add, index) => {
215+
expect(add.getAttribute("in")).toBe(index === 0 ? "s0" : `a${index}`);
216+
expect(add.getAttribute("in2")).toBe(`s${index + 1}`);
217+
expect(add.getAttribute("result")).toBe(`a${index + 1}`);
218+
});
219+
});
220+
221+
it("composites the sharp frame-time instance over the full accumulated smear", async () => {
222+
const filter = await attach({ fps: FPS });
223+
const last = filter.lastElementChild;
224+
225+
expect(last?.tagName).toBe("feComposite");
226+
expect(last?.getAttribute("operator")).toBe("over");
227+
expect(last?.getAttribute("in")).toBe("SourceGraphic");
228+
// in2 must be the END of the accumulation chain, not some intermediate or single copy.
229+
expect(last?.getAttribute("in2")).toBe(`a${reference.subIntervalsPerWindow}`);
230+
expect(last?.getAttribute("result")).toBeNull();
231+
});
232+
233+
it("keeps the sharp instance inside the filter region when the window is entirely one-sided", async () => {
234+
// shutterPhase 0 opens the shutter at the frame time, so every duplicate is ahead of the
235+
// element and no duplicate sits at offset 0 — but the sharp instance still does. A region
236+
// derived from the duplicates alone starts inside the element's own box and clips it.
237+
const filter = await attach({ fps: FPS, shutterPhase: 360 });
238+
const offsets = copyOffsets(filter);
239+
240+
expect(Math.min(...offsets)).toBeGreaterThan(0);
241+
expect(Number.parseFloat(filter.getAttribute("x") ?? "")).toBeLessThanOrEqual(0);
242+
const right =
243+
Number.parseFloat(filter.getAttribute("x") ?? "") +
244+
Number.parseFloat(filter.getAttribute("width") ?? "");
245+
expect(right).toBeGreaterThanOrEqual((Math.max(...offsets) / WORD_WIDTH) * 100 + 100);
246+
});
247+
});
0 Bytes
Binary file not shown.

‎registry/catalog-artifact/local-vectors.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"model": "bge-small-en-v1.5",
33
"modelRevision": "ea104dacec62c0de699686887e3f920caeb4f3e3",
44
"dimensions": 384,
5-
"revision": "b33b552d4f830abfcccb2bfe9495ac6284a7e7c05b3d3f4df630dfd5e753e518",
5+
"revision": "34370735fa1a93099519873178e547c43b14f3bd69491013577515f4bb4f5957",
66
"names": [
77
"ai-chat-reveal",
88
"animated-bar-chart",

0 commit comments

Comments
 (0)