Skip to content

Commit 1dcb484

Browse files
committed
fix(core): replay only where tweens overlap, and from any off-grid scene time
1 parent 6da7f6e commit 1dcb484

2 files changed

Lines changed: 139 additions & 10 deletions

File tree

‎packages/core/src/runtime/adapters/gsap.order.test.ts‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,11 @@ function overlappingZoom() {
1616
return { params, timeline: timeline as unknown as RuntimeTimelineLike };
1717
}
1818

19-
/** The zoom at each frame a renderer captures, in the order it captures them; a scene's clock starts at `hostStart`. */
20-
function capture(frames: number[], hostStart = 0): Map<number, number> {
19+
/** The zoom at each frame a renderer captures, in order; a scene's clock starts at `hostStart`. */
20+
function capture(frames: number[], hostStart = 0, seekFirst?: number): Map<number, number> {
2121
const { params, timeline } = overlappingZoom();
2222
const zoom = new Map<number, number>();
23+
if (seekFirst !== undefined) seekGsapTimeline(timeline, seekFirst, true, undefined, FPS);
2324
for (const frame of frames) {
2425
seekGsapTimeline(timeline, frame / FPS - hostStart, true, undefined, FPS);
2526
zoom.set(frame, params.z);
@@ -56,4 +57,31 @@ describe("a render that captures frames out of order", () => {
5657
}
5758
}
5859
});
60+
61+
it("gives every frame the same value when a scene held at 0 jumps to a chunk start between two frames", () => {
62+
const hostStart = 0.0125;
63+
const sceneInOrder = capture(range(1, FRAMES), hostStart);
64+
for (const [frame, z] of capture(range(53, FRAMES), hostStart, 0)) {
65+
expect(z).toBeCloseTo(sceneInOrder.get(frame)!, 9);
66+
}
67+
});
68+
69+
it("replays no frame when no two tweens write the same property at once", () => {
70+
const rendersOfTwoSeeks = (fps?: number) => {
71+
const [a, b] = [{ x: 0 }, { x: 0 }];
72+
const timeline = gsap.timeline({ paused: true });
73+
timeline
74+
.to(a, { x: 1, duration: 2 }, 0)
75+
.to(b, { x: 1, duration: 2 }, 0)
76+
.to(a, { x: 2, duration: 1 }, 2);
77+
const film = timeline as unknown as RuntimeTimelineLike;
78+
let renders = 0;
79+
const totalTime = film.totalTime!.bind(film);
80+
film.totalTime = (...args) => (args.length ? (renders++, totalTime(...args)) : totalTime());
81+
seekGsapTimeline(film, 0, true, undefined, fps);
82+
seekGsapTimeline(film, 170 / FPS, true, undefined, fps);
83+
return [renders, a.x, b.x];
84+
};
85+
expect(rendersOfTwoSeeks(FPS)).toEqual(rendersOfTwoSeeks());
86+
});
5987
});

‎packages/core/src/runtime/adapters/gsap.ts‎

Lines changed: 109 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -87,19 +87,116 @@ function gsapNeverRendered(timeline: RuntimeTimelineLike): boolean {
8787
}
8888

8989
const lastRenderSeek = new WeakMap<object, number>();
90+
const sharedPropertySpans = new WeakMap<object, { version: string; spans: [number, number][] }>();
91+
const NOT_PROPERTIES = new Set([
92+
"duration",
93+
"ease",
94+
"delay",
95+
"repeat",
96+
"repeatDelay",
97+
"yoyo",
98+
"yoyoEase",
99+
"repeatRefresh",
100+
"stagger",
101+
"overwrite",
102+
"immediateRender",
103+
"lazy",
104+
"id",
105+
"paused",
106+
"reversed",
107+
"callbackScope",
108+
"runBackwards",
109+
"data",
110+
"inherit",
111+
"defaults",
112+
]);
113+
const EVERY_PROPERTY = new Set(["keyframes", "startAt", "transform"]);
114+
const SAME_PROPERTY: Record<string, string> = {
115+
scaleX: "scale",
116+
scaleY: "scale",
117+
autoAlpha: "opacity",
118+
rotate: "rotation",
119+
};
120+
121+
type PlacedTween = GsapPlaced & {
122+
vars?: Record<string, unknown>;
123+
targets?: () => object[];
124+
totalDuration?: () => number;
125+
};
126+
type PropertyWrite = { start: number; end: number; properties: Set<string> | null };
127+
128+
function propertiesWritten(vars: Record<string, unknown>): Set<string> | null {
129+
const properties = new Set<string>();
130+
for (const key of Object.keys(vars)) {
131+
if (EVERY_PROPERTY.has(key)) return null;
132+
if (!key.startsWith("on") && !NOT_PROPERTIES.has(key))
133+
properties.add(SAME_PROPERTY[key] ?? key);
134+
}
135+
return properties;
136+
}
90137

91-
function renderFramesSkippedSinceLastSeek(
138+
function writeOf(tween: PlacedTween, timeline: RuntimeTimelineLike): PropertyWrite | null {
139+
const start = startOnOwner(tween, timeline);
140+
if (start === null) return null;
141+
let speed = 1;
142+
for (let parent = tween.parent; parent && parent !== timeline; parent = parent.parent)
143+
speed *= Number(parent._ts);
144+
const end = start + Number(tween.totalDuration?.() ?? 0) / speed;
145+
return { start, end, properties: propertiesWritten(tween.vars ?? {}) };
146+
}
147+
148+
function spansWhereTweensShareAProperty(timeline: RuntimeTimelineLike): [number, number][] {
149+
const writes = new Map<object, PropertyWrite[]>();
150+
for (const child of timeline.getChildren?.(true, true, false) ?? []) {
151+
const tween = child as PlacedTween;
152+
const write = writeOf(tween, timeline);
153+
if (!write) return [[-Infinity, Infinity]];
154+
for (const target of tween.targets?.() ?? [])
155+
writes.set(target, [...(writes.get(target) ?? []), write]);
156+
}
157+
return [...writes.values()].flatMap(overlapsOnOneTarget);
158+
}
159+
160+
function sharesAProperty(a: PropertyWrite, b: PropertyWrite): boolean {
161+
return !a.properties || !b.properties || [...a.properties].some((p) => b.properties!.has(p));
162+
}
163+
164+
function overlapsOnOneTarget(writes: PropertyWrite[]): [number, number][] {
165+
const spans: [number, number][] = [];
166+
writes.sort((x, y) => x.start - y.start);
167+
writes.forEach((first, i) => {
168+
for (const second of writes.slice(i + 1)) {
169+
if (second.start >= first.end) break;
170+
if (sharesAProperty(first, second))
171+
spans.push([second.start, Math.min(first.end, second.end)]);
172+
}
173+
});
174+
return spans;
175+
}
176+
177+
function framesSkippedSinceLastSeek(
92178
timeline: RuntimeTimelineLike,
93179
t: number,
94-
suppressEvents: boolean,
95180
fps: number,
96-
): void {
181+
version = "",
182+
): number[] {
97183
const last = lastRenderSeek.get(timeline);
98184
lastRenderSeek.set(timeline, t);
99-
const frames = last === undefined ? Math.floor(t * fps + 1e-6) + 1 : (t - last) * fps;
100-
const skipped = Math.round(frames) - 1;
101-
if (skipped < 1 || Math.abs(frames - Math.round(frames)) > 1e-6) return;
102-
for (let back = skipped; back >= 1; back--) timeline.totalTime(t - back / fps, suppressEvents);
185+
const skipped =
186+
last === undefined ? Math.floor(t * fps + 1e-6) : Math.ceil((t - last) * fps - 1e-6) - 1;
187+
if (skipped < 1) return [];
188+
let cached = sharedPropertySpans.get(timeline);
189+
if (cached?.version !== version) {
190+
cached = { version, spans: spansWhereTweensShareAProperty(timeline) };
191+
sharedPropertySpans.set(timeline, cached);
192+
}
193+
const replay = new Set<number>();
194+
for (const [from, to] of cached.spans) {
195+
const nearest = Math.max(1, Math.ceil((t - to) * fps - 1e-6) - 1);
196+
const farthest = Math.min(skipped, Math.floor((t - from) * fps + 1e-6) + 1);
197+
for (let back = nearest; back <= farthest; back++) replay.add(back);
198+
}
199+
return [...replay].sort((x, y) => y - x).map((back) => t - back / fps);
103200
}
104201

105202
export function seekGsapTimeline(
@@ -113,7 +210,11 @@ export function seekGsapTimeline(
113210
if (typeof timeline.seek === "function") timeline.seek(t, suppressEvents);
114211
return false;
115212
}
116-
if (renderFps) renderFramesSkippedSinceLastSeek(timeline, t, suppressEvents, renderFps);
213+
if (renderFps) {
214+
for (const time of framesSkippedSinceLastSeek(timeline, t, renderFps, structure?.version)) {
215+
timeline.totalTime(time, suppressEvents);
216+
}
217+
}
117218
const from = Number(timeline.totalTime());
118219
timeline.totalTime(t, suppressEvents);
119220
if (t < from && structure) reapplyStepsInAuthoredOrder(timeline, structure, t);

0 commit comments

Comments
 (0)