Skip to content

Open source CapCut alternative.

TypeScript

fix(site): repair group camera and blur [rebuild]

David Le1cd4bd1d5819
diff --git a/site/packages/effects-kit/src/camera.test.ts b/site/packages/effects-kit/src/camera.test.ts
index ee28ce4f..093a8725 100644
--- a/site/packages/effects-kit/src/camera.test.ts
+++ b/site/packages/effects-kit/src/camera.test.ts
@@ -155,9 +155,9 @@ describe("blur on the pose track", () => {
expect(evalOverlayFrame(o, 1).blur).toBeCloseTo(2);
});
- test("a still blurred element draws through the evaluator", () => {
- expect(isOverlayAnimated(el({ blur: 3 }))).toBe(true);
- expect(isOverlayAnimated(el({ blur: 0 }))).toBe(false);
+ test("a still blurred element renders as one picture", () => {
+ expect(isOverlayAnimated(el({ blur: 3 }))).toBe(false);
+ expect(isOverlayAnimated(el({ blur: 3, kf: [key(0), key(2, { blur: 0 })] }))).toBe(true);
});
});
diff --git a/site/packages/effects-kit/src/camera.ts b/site/packages/effects-kit/src/camera.ts
index a1021013..b1c829f3 100644
--- a/site/packages/effects-kit/src/camera.ts
+++ b/site/packages/effects-kit/src/camera.ts
@@ -49,6 +49,11 @@ export interface CameraPose {
export const REST_CAMERA: CameraPose = { x: 0.5, y: 0.5, scale: 1, rotation: 0 };
+/** The world a group's camera films, in frame fractions: the frame and one
+ * frame beyond each edge. Its look-at point and its members sit inside it. */
+export const CAMERA_WORLD_MIN = -1;
+export const CAMERA_WORLD_MAX = 2;
+
/** How far the camera may pull back and push in. */
export const CAMERA_SCALE_MIN = 0.25;
export const CAMERA_SCALE_MAX = 8;
@@ -97,13 +102,10 @@ export function worldPoint(
return { x: cam.x + v.x / aspect, y: cam.y + v.y };
}
-/** A screen-space offset as a world-space one: the inverse of `cameraVector`. */
-export function worldVector(cam: CameraPose, dx: number, dy: number): { x: number; y: number } {
- const r = (-cam.rotation * Math.PI) / 180;
- const k = 1 / Math.max(1e-6, cam.scale);
- const c = Math.cos(r) * k;
- const s = Math.sin(r) * k;
- return { x: c * dx - s * dy, y: s * dx + c * dy };
+/** A screen-space offset as a world-space one: `cameraVector` through the
+ * inverse pose (the turn undone, the zoom inverted). */
+function worldVector(cam: CameraPose, dx: number, dy: number): { x: number; y: number } {
+ return cameraVector({ ...cam, rotation: -cam.rotation, scale: 1 / Math.max(1e-6, cam.scale) }, dx, dy);
}
/**
@@ -151,7 +153,7 @@ export const STREAK_MIN = 0.75;
* either way, and the cap bounds what a frame costs to draw. */
export const STREAK_MAX = 96;
/** Design px between two taps along a streak. */
-export const STREAK_TAP_SPACING = 4;
+const STREAK_TAP_SPACING = 4;
/** The most copies one streak is drawn from. */
export const STREAK_TAPS_MAX = 24;
diff --git a/site/packages/effects-kit/src/elementFx.ts b/site/packages/effects-kit/src/elementFx.ts
index 3bd8e4a9..6fcab7ba 100644
--- a/site/packages/effects-kit/src/elementFx.ts
+++ b/site/packages/effects-kit/src/elementFx.ts
@@ -51,10 +51,20 @@ export function elementLook(
};
}
+/** A context back to plain drawing: identity transform, full alpha,
+ * source-over, no filter. */
+function reset(c: Ctx): void {
+ c.setTransform(1, 0, 0, 1, 0, 0);
+ c.globalAlpha = 1;
+ c.globalCompositeOperation = "source-over";
+ if ("filter" in c) c.filter = "none";
+}
+
/**
* Draw `src` along the streak onto a cleared `ctx`, with (x, y) the place it
* would sit with no streak. The caller's transform applies, so a streak given
- * in an element's own space smears in that space.
+ * in an element's own space smears in that space. A streak has at least two
+ * taps (`streakTaps`).
*/
export function drawStreak(
ctx: Ctx,
@@ -64,10 +74,6 @@ export function drawStreak(
look: Pick<ElementLook, "streakX" | "streakY" | "taps">
): void {
const n = look.taps;
- if (n < 2) {
- ctx.drawImage(src, x, y);
- return;
- }
const op = ctx.globalCompositeOperation;
const alpha = ctx.globalAlpha;
ctx.globalCompositeOperation = "lighter";
@@ -109,10 +115,7 @@ export class ElementFx {
if (!look) return ctx;
this.picture = this.fit(this.picture, width, height);
const c = this.picture.getContext("2d") as Ctx;
- c.setTransform(1, 0, 0, 1, 0, 0);
- c.globalAlpha = 1;
- c.globalCompositeOperation = "source-over";
- if ("filter" in c) c.filter = "none";
+ reset(c);
c.clearRect(0, 0, this.picture.width, this.picture.height);
return c;
}
@@ -126,18 +129,13 @@ export class ElementFx {
if (look.taps >= 2) {
this.smear = this.fit(this.smear, src.width, src.height);
const s = this.smear.getContext("2d") as Ctx;
- s.setTransform(1, 0, 0, 1, 0, 0);
- s.globalAlpha = 1;
- s.globalCompositeOperation = "source-over";
- if ("filter" in s) s.filter = "none";
+ reset(s);
s.clearRect(0, 0, this.smear.width, this.smear.height);
drawStreak(s, src, 0, 0, look);
src = this.smear;
}
ctx.save();
- ctx.setTransform(1, 0, 0, 1, 0, 0);
- ctx.globalAlpha = 1;
- ctx.globalCompositeOperation = "source-over";
+ reset(ctx);
if (look.blur > 0 && "filter" in ctx) ctx.filter = `blur(${look.blur.toFixed(2)}px)`;
ctx.drawImage(src, 0, 0);
ctx.restore();
diff --git a/site/packages/effects-kit/src/keys.ts b/site/packages/effects-kit/src/keys.ts
index 07736ad1..5b79f9c4 100644
--- a/site/packages/effects-kit/src/keys.ts
+++ b/site/packages/effects-kit/src/keys.ts
@@ -105,15 +105,13 @@ export function hasOverlayKeys(o: Posable): boolean {
}
/** Whether the element is drawn through the per-frame evaluator: something
- * moves it (a preset, pose keys, its group's camera, a keyframed mask), or it
- * is blurred, which every renderer applies to the posed picture as it draws.
- * Any other element renders as one still picture. */
+ * moves it (a preset, pose keys, its group's camera, a keyframed mask). Any
+ * other element renders as one still picture, its own blur baked in. */
export function isOverlayAnimated(o: Posable): boolean {
return (
hasOverlayAnim(o.anim) ||
hasOverlayKeys(o) ||
hasCameraKeys(o.camera) ||
- (o.blur ?? 0) > 0 ||
!!(o.mask?.kf && o.mask.kf.length > 0)
);
}
diff --git a/site/packages/effects-kit/src/render.ts b/site/packages/effects-kit/src/render.ts
index 1268f624..557df5af 100644
--- a/site/packages/effects-kit/src/render.ts
+++ b/site/packages/effects-kit/src/render.ts
@@ -1060,6 +1060,31 @@ export async function renderElementCanvas(
return canvas;
}
+/** The picture of an element that holds still: the full-frame picture with
+ * the element's own blur baked in, so a blurred element that never moves
+ * costs one picture for its whole span. */
+export async function renderStillCanvas(
+ overlay: Overlay,
+ width: number,
+ height: number,
+ env: RenderEnv
+): Promise<HTMLCanvasElement> {
+ const canvas = await renderElementCanvas(overlay, width, height, env);
+ const look = elementLook({ blur: overlay.blur }, Math.min(width, height) / 1080);
+ if (!look) return canvas;
+ const soft = newCanvas(env, width, height);
+ const ctx = soft.getContext("2d")!;
+ if ("filter" in ctx) ctx.filter = `blur(${look.blur.toFixed(2)}px)`;
+ ctx.drawImage(canvas, 0, 0);
+ canvas.width = canvas.height = 1;
+ return soft;
+}
+
+/** `renderStillCanvas` as a PNG. */
+export async function renderStillPng(overlay: Overlay, width: number, height: number, env: RenderEnv): Promise<Blob> {
+ return pngBlob(await renderStillCanvas(overlay, width, height, env), env);
+}
+
/** Paint one element over the whole of a canvas the caller owns, cleared
* first — the full-frame picture `renderElementPng` encodes, drawn into a
* surface that is reused frame after frame. */
@@ -1342,7 +1367,8 @@ export function elementAtMoment(
* box in a `width` × `height` frame, its shape mask applied. Returns where the
* crop's top-left sits in the frame. The preview's motion blur smears this
* picture: a few element-sized draws a frame where a frame-sized picture
- * would cost the whole stage.
+ * would cost the whole stage. `maskScratch` is the caller's own canvas for
+ * the mask pass, held across paints.
*/
export async function paintElementCrop(
canvas: HTMLCanvasElement,
@@ -1350,7 +1376,7 @@ export async function paintElementCrop(
width: number,
height: number,
env: RenderEnv,
- opts: { t: number; phase?: PaintPhase }
+ opts: { t: number; phase?: PaintPhase; maskScratch: HTMLCanvasElement }
): Promise<{ x: number; y: number }> {
const scale = Math.min(width, height) / 1080;
const frame: PaintFrame = { width, height, scale, t: opts.t, phase: opts.phase };
@@ -1371,7 +1397,7 @@ export async function paintElementCrop(
ctx.translate(-x, -y);
await paintElement(ctx, el, frame, env);
if (el.mask && el.mask.kind !== "subject") {
- applyMaskToCanvas(ctx, newCanvas(env, 1, 1), el.mask, opts.t, frame, { x: el.x, y: el.y }, ctx.getTransform());
+ applyMaskToCanvas(ctx, opts.maskScratch, el.mask, opts.t, frame, { x: el.x, y: el.y }, ctx.getTransform());
}
return { x, y };
}
diff --git a/site/packages/effects-kit/src/stillBlur.test.ts b/site/packages/effects-kit/src/stillBlur.test.ts
new file mode 100644
index 00000000..da90351b
--- /dev/null
+++ b/site/packages/effects-kit/src/stillBlur.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, test } from "bun:test";
+import { Canvas } from "skia-canvas";
+import { renderStillCanvas, type RenderEnv } from "./render";
+import type { ShapeOverlay } from "./types";
+
+const env: RenderEnv = {
+ fontStack: () => "Arial",
+ createCanvas: (w, h) => new Canvas(w, h) as unknown as HTMLCanvasElement,
+ canvasToPngBlob: async (c) => new Blob([new Uint8Array(await (c as unknown as Canvas).toBuffer("png"))]),
+};
+
+const box = (blur?: number): ShapeOverlay =>
+ ({ id: "s", kind: "shape", shape: "rect", start: 0, end: 4, x: 0.5, y: 0.5, w: 0.4, h: 0.4, fill: "#ffffff", ...(blur ? { blur } : {}) }) as ShapeOverlay;
+
+const alphaAt = (c: HTMLCanvasElement, x: number, y: number) =>
+ (c.getContext("2d") as CanvasRenderingContext2D).getImageData(x, y, 1, 1).data[3];
+
+describe("a still element's picture", () => {
+ test("bakes its own blur in, softening the edge", async () => {
+ const sharp = await renderStillCanvas(box(), 200, 200, env);
+ const soft = await renderStillCanvas(box(20), 200, 200, env);
+ // The box spans 60..140; just outside its edge the sharp picture is empty
+ // and the blurred one has spilled ink there.
+ expect(alphaAt(sharp, 55, 100)).toBe(0);
+ expect(alphaAt(soft, 55, 100)).toBeGreaterThan(0);
+ expect(alphaAt(soft, 100, 100)).toBe(255);
+ });
+});
diff --git a/site/src/cut/components/AnimationTiles.tools.ts b/site/src/cut/components/AnimationTiles.tools.ts
index 4d2dc047..7a224c39 100644
--- a/site/src/cut/components/AnimationTiles.tools.ts
+++ b/site/src/cut/components/AnimationTiles.tools.ts
@@ -8,7 +8,7 @@
* until every side catches up.
*/
-import { EASE_IDS, ELEMENT_BLUR_MAX } from "@donkeycut/effects-kit";
+import { CAMERA_WORLD_MAX, CAMERA_WORLD_MIN, EASE_IDS, ELEMENT_BLUR_MAX } from "@donkeycut/effects-kit";
import {
CARET_BLINK_SECONDS,
CARET_BLINKS_MAX,
@@ -120,8 +120,8 @@ export const OVERLAY_ANIMATION_TOOLS = [
items: obj(
{
t: num("Seconds from the element's start"),
- x: num("Center x, fraction of frame width 0..1"),
- y: num("Center y, fraction of frame height 0..1"),
+ x: num(`Center x, fraction of frame width 0..1 (${CAMERA_WORLD_MIN}..${CAMERA_WORLD_MAX} for a grouped element)`),
+ y: num(`Center y, fraction of frame height 0..1 (${CAMERA_WORLD_MIN}..${CAMERA_WORLD_MAX} for a grouped element)`),
scale: num("Size multiplier, 1 = the element's own size (0.1..4)"),
rotation: num("Degrees clockwise, -180..180"),
opacity: num("0..1"),
diff --git a/site/src/cut/components/GroupPanel.tools.ts b/site/src/cut/components/GroupPanel.tools.ts
index ede64da4..09aa915c 100644
--- a/site/src/cut/components/GroupPanel.tools.ts
+++ b/site/src/cut/components/GroupPanel.tools.ts
@@ -5,13 +5,13 @@
* `GroupPanelToolName`.
*/
-import { CAMERA_SCALE_MAX, CAMERA_SCALE_MIN, EASE_IDS } from "@donkeycut/effects-kit";
+import { CAMERA_SCALE_MAX, CAMERA_SCALE_MIN, CAMERA_WORLD_MAX, CAMERA_WORLD_MIN, EASE_IDS } from "@donkeycut/effects-kit";
import { bool, num, obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";
export const GROUP_PANEL_TOOLS = [
{
name: "set_group_camera",
- description: `Give a group of elements (titles, shapes, stickers) one camera that moves over them as a single world: steps from card to card, pushes onto the one being talked about, pulls back, whips. Each key is a camera pose at a time in seconds from the group's start (its earliest element): x/y is the world point at the frame's center (frame fractions, where the elements' own x/y live), scale is the zoom (1 = as laid out, 2.5 = a card a few tenths of the frame wide fills it; ${CAMERA_SCALE_MIN}..${CAMERA_SCALE_MAX}), rotation turns the whole world clockwise about the frame center. ease is the curve out of a key into the next (${EASE_IDS.join(", ")}; default linear): sine.inOut glides between cards, power3.out lands a push, power3.inOut over a short gap is a whip. Every element keeps its own keyframes and animation, composed inside the camera. To focus a card, push onto it and blur and dim its neighbours with set_overlay_keyframes keys (blur, opacity) at the same moments. motion_blur streaks what the camera's movement does (shutter sets how hard); an element's own motion_blur (update_overlay) streaks its whole on-screen movement instead. Name the group by group_id or by any member ids. Omitted fields on a key take the camera's pose at that moment; keys replace the whole track; an empty list clears the camera. Lay the cards out across the frame first (group_items groups them), then key the camera.`,
+ description: `Give a group of elements (titles, shapes, stickers) one camera that moves over them as a single world: steps from card to card, pushes onto the one being talked about, pulls back, whips. Each key is a camera pose at a time in seconds from the group's start (its earliest element): x/y is the world point at the frame's center (frame fractions, where the elements' own x/y live), scale is the zoom (1 = as laid out, 2.5 = a card a few tenths of the frame wide fills it; ${CAMERA_SCALE_MIN}..${CAMERA_SCALE_MAX}), rotation turns the whole world clockwise about the frame center. ease is the curve out of a key into the next (${EASE_IDS.join(", ")}; default linear): sine.inOut glides between cards, power3.out lands a push, power3.inOut over a short gap is a whip. Every element keeps its own keyframes and animation, composed inside the camera. To focus a card, push onto it and blur and dim its neighbours with set_overlay_keyframes keys (blur, opacity) at the same moments. motion_blur streaks what the camera's movement does (shutter sets how hard); an element's own motion_blur (update_overlay) streaks its whole on-screen movement instead. Name the group by group_id or by any member ids. Omitted fields on a key take the camera's pose at that moment; keys replace the whole track; an empty list clears the camera. Group the cards first (group_items), lay them out across and beyond the frame — a grouped element's x/y reaches ${CAMERA_WORLD_MIN}..${CAMERA_WORLD_MAX} — then key the camera.`,
inputSchema: obj(
{
group_id: str("Group id (from editor_state groupCameras or an element's groupId)"),
@@ -22,8 +22,8 @@ export const GROUP_PANEL_TOOLS = [
items: obj(
{
t: num("Seconds from the group's start"),
- x: num("World point at the frame center, fraction of frame width"),
- y: num("World point at the frame center, fraction of frame height"),
+ x: num(`World point at the frame center, fraction of frame width, ${CAMERA_WORLD_MIN}..${CAMERA_WORLD_MAX}`),
+ y: num(`World point at the frame center, fraction of frame height, ${CAMERA_WORLD_MIN}..${CAMERA_WORLD_MAX}`),
scale: num(`Zoom, ${CAMERA_SCALE_MIN}..${CAMERA_SCALE_MAX} (1 = as laid out)`),
rotation: num("Degrees the world turns clockwise, -180..180"),
ease: { type: "string", enum: [...EASE_IDS], description: "Curve into the next key" },
diff --git a/site/src/cut/components/GroupPanel.tsx b/site/src/cut/components/GroupPanel.tsx
index a53e584d..cb380384 100644
--- a/site/src/cut/components/GroupPanel.tsx
+++ b/site/src/cut/components/GroupPanel.tsx
@@ -249,12 +249,14 @@ function TransformRows({ items }: { items: { overlays: Overlay[]; clips: VideoCl
});
};
const poses = overlays.map(overlayPose);
+ // A grouped element reaches across the camera's world.
+ const grouped = overlays.find((o) => o.groupId);
const center = selectionCenter(poses);
const rotation = sharedNumber([...poses.map((p) => p.rotation), ...clips.map((c) => clipPose(c).rotation)]);
const opacity = sharedNumber([...poses.map((p) => p.opacity), ...clips.map((c) => clipPose(c).opacity)]);
const move = (axis: "x" | "y", pct: number) => {
- const target = { ...center, [axis]: clampOverlayPos(pct / 100) };
- const { dx, dy } = selectionTranslation(poses, target);
+ const target = { ...center, [axis]: pct / 100 };
+ const { dx, dy } = selectionTranslation(poses.map((p, i) => ({ ...p, groupId: overlays[i].groupId })), target);
overlays.forEach((o, i) => setOverlay(o, { x: poses[i].x + dx, y: poses[i].y + dy }));
};
const rotate = (v: number) => {
@@ -294,8 +296,8 @@ function TransformRows({ items }: { items: { overlays: Overlay[]; clips: VideoCl
label={`${axis.toUpperCase()} position`}
className="w-9 text-muted-foreground"
value={center[axis] * 100}
- min={2}
- max={98}
+ min={clampOverlayPos(-Infinity, grouped) * 100}
+ max={clampOverlayPos(Infinity, grouped) * 100}
step={0.5}
keyStep={1}
snap={[50]}
diff --git a/site/src/cut/components/Inspector.tools.ts b/site/src/cut/components/Inspector.tools.ts
index 99eb8379..b3afbc56 100644
--- a/site/src/cut/components/Inspector.tools.ts
+++ b/site/src/cut/components/Inspector.tools.ts
@@ -7,6 +7,8 @@
*/
import {
+ CAMERA_WORLD_MAX,
+ CAMERA_WORLD_MIN,
GRADE_BASIC_FIELDS,
GRADE_DETAIL_FIELDS,
GRADE_HUE_MAX,
@@ -111,8 +113,8 @@ export const INSPECTOR_TOOLS = [
text: str("New text (titles)"),
start: num("Start s"),
end: num("End s"),
- x: num("Center x 0..1"),
- y: num("Center y 0..1"),
+ x: num(`Center x 0..1; a grouped element reaches ${CAMERA_WORLD_MIN}..${CAMERA_WORLD_MAX}, off the frame, for its group camera`),
+ y: num(`Center y 0..1; a grouped element reaches ${CAMERA_WORLD_MIN}..${CAMERA_WORLD_MAX}`),
size: num("Font size px at 1080w (titles)"),
color: str("CSS text color (titles)"),
font: str("Font id (titles; see the graphics skill)"),
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index b9ac270d..b8847db8 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -3441,14 +3441,14 @@ function TransformRows({ overlay: o }: { overlay: Overlay }) {
// stores — an element sits in the same spot at any aspect, and the number
// means the same thing on a square as on a widescreen.
const setPos = (axis: "x" | "y", pct: number) => {
- const v = clampOverlayPos(pct / 100);
+ const v = clampOverlayPos(pct / 100, o);
if (keyed) return setKey({ [axis]: v });
useEditor.getState().updateOverlayTransient(o.id, { [axis]: v });
};
return (
<Section title="Transform">
<KeyframeControls overlay={o} />
- <PositionRow pose={pose} min={2} max={98} ck={posCk} onSet={setPos} />
+ <PositionRow pose={pose} min={clampOverlayPos(-Infinity, o) * 100} max={clampOverlayPos(Infinity, o) * 100} ck={posCk} onSet={setPos} />
{keyed && (
<Row label="Scale">
<ValueSlider
diff --git a/site/src/cut/components/MotionControls.tsx b/site/src/cut/components/MotionControls.tsx
index cda0237e..8badc080 100644
--- a/site/src/cut/components/MotionControls.tsx
+++ b/site/src/cut/components/MotionControls.tsx
@@ -4,6 +4,8 @@ import { useMemo } from "react";
import {
CAMERA_SCALE_MAX,
CAMERA_SCALE_MIN,
+ CAMERA_WORLD_MAX,
+ CAMERA_WORLD_MIN,
EASE_IDS,
EASE_LABELS,
ELEMENT_BLUR_MAX,
@@ -145,28 +147,15 @@ function BlurRow({
);
}
-/**
- * One element's blur, the ease of its key under the playhead, and its motion
- * blur. Blur is part of the pose: with keys in play it edits the key at the
- * playhead, like position and opacity do.
- */
+/** One element's motion rows: the ease of its key under the playhead, then
+ * the blur and motion blur rows a selection shares. */
export function ElementMotionRows({ overlay: o }: { overlay: Overlay }) {
const now = usePreviewTime();
- const blurCk = useSliderCheckpoint();
- const shutterCk = useSliderCheckpoint();
- const keyed = hasOverlayKeys(o);
const tLocal = local(o, now);
- const pose = poseAt(o, tLocal);
- const here = keyed ? keyIndexAt(o.kf, tLocal) : -1;
+ const here = hasOverlayKeys(o) ? keyIndexAt(o.kf, tLocal) : -1;
const key = here >= 0 ? o.kf![here] : undefined;
- const setBlur = (v: number) => {
- const blur = Math.max(0, Math.min(ELEMENT_BLUR_MAX, v));
- if (keyed) return st().setOverlayKey(o.id, tLocal, { blur }, { transient: true });
- st().updateOverlayTransient(o.id, { blur: blur > 0.05 ? blur : undefined });
- };
return (
<>
- <BlurRow blur={{ value: keyed ? (pose.blur ?? 0) : (o.blur ?? 0), mixed: false }} onSet={setBlur} ck={blurCk} />
{key && (
<EaseRow
ease={key.ease}
@@ -176,14 +165,7 @@ export function ElementMotionRows({ overlay: o }: { overlay: Overlay }) {
}}
/>
)}
- <MotionBlurRows
- shutter={o.motionBlur ? { value: o.motionBlur, mixed: false } : null}
- ck={shutterCk}
- onChange={(motionBlur, phase) => {
- if (phase === "once") st().pushHistory();
- st().updateOverlayTransient(o.id, { motionBlur });
- }}
- />
+ <GroupMotionRows overlays={[o]} />
</>
);
}
@@ -242,7 +224,7 @@ export function GroupCameraSection({ groupId }: { groupId: string }) {
const pose = groupCameraPoseAt(view, tGroup);
const here = keyIndexAt(view.keys, tGroup);
const key = here >= 0 ? view.keys[here] : undefined;
- const write = (keys: CameraKey[], motionBlur = view.motionBlur) =>
+ const write = (keys: CameraKey[], motionBlur: number | undefined) =>
st().setGroupCamera(groupId, { keys, ...(motionBlur ? { motionBlur } : {}) }, { transient: true });
// Read the live track at each write, so a drag layers on its own frames.
const live = () => groupCameraOf(st().overlays, groupId) ?? view;
@@ -279,8 +261,8 @@ export function GroupCameraSection({ groupId }: { groupId: string }) {
label={`Camera ${axis.toUpperCase()}`}
className="w-9 text-muted-foreground"
value={pose[axis] * 100}
- min={-100}
- max={200}
+ min={CAMERA_WORLD_MIN * 100}
+ max={CAMERA_WORLD_MAX * 100}
step={0.5}
keyStep={1}
snap={[50]}
diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsx
index b89652a8..fe4400b1 100644
--- a/site/src/cut/components/OverlayLayer.tsx
+++ b/site/src/cut/components/OverlayLayer.tsx
@@ -721,14 +721,12 @@ function OverlayItem({
// A hit that darkens dims the element's own pixels, the same multiply the
// painters run; blur softens them. The DOM content, the dive canvas and the
// streak canvas all carry the one filter.
- const blur = blurPx >= 0.1 ? `blur(${blurPx.toFixed(2)}px)` : "";
const dim = live?.brightness !== undefined ? `brightness(${live.brightness})` : "";
- const blurFilter = blur && dim ? `${blur} ${dim}` : blur || dim || undefined;
+ const filterOf = (px: number) => [px >= 0.1 ? `blur(${px.toFixed(2)}px)` : "", dim].filter(Boolean).join(" ") || undefined;
+ const blurFilter = filterOf(blurPx);
// The dive canvas sits on the stage outside the box, so its blur takes the
// radius undivided.
- const diveBlurPx = blurPx * poseZoom;
- const diveFilter =
- [diveBlurPx >= 0.1 ? `blur(${diveBlurPx.toFixed(2)}px)` : "", dim].filter(Boolean).join(" ") || undefined;
+ const diveFilter = filterOf(blurPx * poseZoom);
// Motion blur: while the element moves, the kit paints it and smears the
// picture along its streak; at rest the element is the plain DOM box.
const streakable =
@@ -813,7 +811,6 @@ function OverlayItem({
})()
: {}),
...(maskCss ?? {}),
- ...(blurFilter ? { filter: blurFilter } : {}),
...(diving || streaking ? { visibility: "hidden" as const } : {}),
...(reveal !== undefined
? { clipPath: `inset(0 ${(1 - Math.min(1, Math.max(0, reveal))) * 100}% 0 0)` }
@@ -850,7 +847,7 @@ function OverlayItem({
const all = useEditor.getState().overlays;
return o.groupId ? all.filter((x) => x.groupId === o.groupId) : [o];
};
- const clampPos = clampOverlayPos;
+ const clampPos = (v: number) => clampOverlayPos(v, o);
/**
* Commit a live transform. Position and rotation are pose: on a keyframed
@@ -925,6 +922,16 @@ function OverlayItem({
const d0 = Math.max(8, reach(e.clientX, e.clientY));
const members = groupSnapshot();
const self = members.find((m) => m.id === o.id) ?? members[0];
+ // Under a group camera the center's walk is on screen; the members move
+ // by that much of their world.
+ const cam = elementCameraAt(o, tLocal);
+ const aspect = frame.w / frame.h;
+ const seen = cam ? cameraPoint(cam, self.x, self.y, aspect) : null;
+ const worldWalk = (mx: number, my: number) => {
+ if (!cam || !seen) return { x: mx, y: my };
+ const w = worldPoint(cam, seen.x + mx, seen.y + my, aspect);
+ return { x: w.x - self.x, y: w.y - self.y };
+ };
const textSizes = new Map(members.filter(isTextOverlay).map((m) => [m.id, textBoxSize(m, frame.w)]));
const stickerSize = (v: number) => Math.min(1.5, Math.max(0.02, v));
// A sticker's resting height as a frame fraction: the one it stores, or
@@ -997,15 +1004,17 @@ function OverlayItem({
// rotated back to the screen and into frame fractions.
const wx = axis.x ? ((kx - 1) * axis.x * ow) / 2 : 0;
const wy = axis.y ? ((ky - 1) * axis.y * oh) / 2 : isTextOverlay(self) ? ((ky - 1) * oh) / 2 : 0;
- const mx = (wx * Math.cos(rad) + wy * Math.sin(rad)) / stageWidth;
- const my = (-wx * Math.sin(rad) + wy * Math.cos(rad)) / stageHeight;
+ const walk = worldWalk(
+ (wx * Math.cos(rad) + wy * Math.sin(rad)) / stageWidth,
+ (-wx * Math.sin(rad) + wy * Math.cos(rad)) / stageHeight
+ );
writeTransform(
members.map((m) => ({
id: m.id,
patch: {
...scaled(m, k),
- x: clampPos(self.x + kx * (m.x - self.x) + mx),
- y: clampPos(self.y + ky * (m.y - self.y) + my),
+ x: clampPos(self.x + kx * (m.x - self.x) + walk.x),
+ y: clampPos(self.y + ky * (m.y - self.y) + walk.y),
},
}))
);
@@ -1124,7 +1133,7 @@ function OverlayItem({
onMove: (dx, dy, ev) => {
if (cam && seen) {
const w = worldPoint(cam, seen.x + dx / stageWidth, seen.y + dy / stageHeight, aspect);
- writeTransform(members.map((m) => ({ id: m.id, patch: { x: m.x + w.x - self.x, y: m.y + w.y - self.y } })));
+ writeTransform(members.map((m) => ({ id: m.id, patch: { x: clampPos(m.x + w.x - self.x), y: clampPos(m.y + w.y - self.y) } })));
return;
}
const p = snap(o.id, self.x + dx / stageWidth, self.y + dy / stageHeight, ev);
@@ -1207,6 +1216,9 @@ function OverlayItem({
onPointerDown={beginMove}
onDoubleClick={isText ? () => setEditing(true) : undefined}
>
+ {/* The filter sits outside the mask and the wipe, so the element blurs
+ after them — the order every renderer draws in. */}
+ <div style={blurFilter ? { filter: blurFilter } : undefined}>
<div style={contentStyle}>
{behindHidden ? (
<span className="opacity-0">{shownText}</span>
@@ -1249,6 +1261,7 @@ function OverlayItem({
<StickerView sticker={o} stageWidth={stageWidth} stageHeight={stageHeight} t={t} />
) : null}
</div>
+ </div>
{streakable && live && (
<StreakCanvas
o={o}
@@ -1514,6 +1527,10 @@ function DiveCanvas({
* Lottie); each moving frame then costs a few element-sized draws. At rest it
* draws nothing and the box shows the element itself.
*/
+/** How far behind the playhead a self-moving element's streak picture may
+ * run, seconds: a few frames of paint latency. */
+const STREAK_STALE_S = 0.1;
+
function StreakCanvas({
o,
live,
@@ -1537,13 +1554,15 @@ function StreakCanvas({
onReady: (ready: boolean) => void;
}) {
const ref = useRef<HTMLCanvasElement>(null);
- const raster = useRef<{ canvas: HTMLCanvasElement; x: number; y: number } | null>(null);
+ const raster = useRef<{ canvas: HTMLCanvasElement; scratch: HTMLCanvasElement; x: number; y: number; at: number } | null>(null);
const [painted, setPainted] = useState(0);
const assets = useEditor((s) => (o.kind === "sticker" ? s.assets : null));
const dpr = typeof window === "undefined" ? 1 : Math.min(2, window.devicePixelRatio || 1);
const w = Math.max(1, Math.round(stageWidth * dpr));
const h = Math.max(1, Math.round(stageHeight * dpr));
- // Pixels that change on their own repaint every frame; the rest paint once.
+ // Pixels that change on their own repaint every frame while the element
+ // streaks; at rest the DOM box shows them and nothing paints. The rest
+ // paint once.
const selfMoving =
!!live.glyphs ||
!!live.glyphLoop ||
@@ -1551,42 +1570,51 @@ function StreakCanvas({
live.textProgress !== undefined ||
!!overlayWords(o) ||
(o.kind === "sticker" && !!o.lottie);
+ const moving = !!live.streak;
const paintAt = selfMoving ? tLocal : 0;
const pending = useRef<number | null>(null);
const busy = useRef(false);
+ // The loop reads the newest element and size at each paint, so a change
+ // that lands while a paint is in flight is the next one painted.
+ const latest = useRef({ o, w, h, assets });
useEffect(() => {
+ latest.current = { o, w, h, assets };
+ if (selfMoving && !moving && raster.current) return;
pending.current = paintAt;
if (busy.current) return;
busy.current = true;
- const env = cutRenderEnv(assets ?? []);
void (async () => {
try {
while (pending.current !== null) {
const at = pending.current;
pending.current = null;
- const ev = evalOverlayFrame(o, at, w / h);
- const { el, phase } = elementAtMoment(o, at, ev);
+ const cur = latest.current;
+ const ev = evalOverlayFrame(cur.o, at, cur.w / cur.h);
+ const { el, phase } = elementAtMoment(cur.o, at, ev);
const canvas = raster.current?.canvas ?? document.createElement("canvas");
- const origin = await paintElementCrop(canvas, el, w, h, env, { t: at, phase });
- raster.current = { canvas, ...origin };
+ const scratch = raster.current?.scratch ?? document.createElement("canvas");
+ const origin = await paintElementCrop(canvas, el, cur.w, cur.h, cutRenderEnv(cur.assets ?? []), { t: at, phase, maskScratch: scratch });
+ raster.current = { canvas, scratch, ...origin, at };
+ setPainted((n) => n + 1);
}
- setPainted((n) => n + 1);
} finally {
busy.current = false;
}
})();
- }, [o, paintAt, w, h, assets]);
- // The picture and the smear canvas count toward the memory report.
+ }, [o, paintAt, w, h, assets, selfMoving, moving]);
+ // The picture, its mask scratch and the smear canvas count toward the
+ // memory report.
useEffect(() => {
const release = holdMemory("overlayRasters", () => {
- const r = raster.current?.canvas;
+ const r = raster.current;
const c = ref.current;
- return (r ? r.width * r.height * 4 : 0) + (c ? c.width * c.height * 4 : 0);
+ const px = (x: { width: number; height: number } | null | undefined) => (x ? x.width * x.height * 4 : 0);
+ return px(r?.canvas) + px(r?.scratch) + px(c);
});
return () => {
release();
- const r = raster.current?.canvas;
- if (r) r.width = r.height = 1;
+ const r = raster.current;
+ if (r) r.canvas.width = r.canvas.height = r.scratch.width = r.scratch.height = 1;
raster.current = null;
onReady(false);
};
@@ -1598,7 +1626,9 @@ function StreakCanvas({
if (!canvas || !pic) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
- if (!streak) {
+ // A self-moving picture from another moment shows the DOM box until the
+ // paint for this one lands.
+ if (!streak || (selfMoving && Math.abs(pic.at - tLocal) > STREAK_STALE_S)) {
// At rest the box shows the element; the canvas empties once.
if (canvas.style.display !== "none") {
canvas.style.display = "none";
@@ -1637,7 +1667,7 @@ function StreakCanvas({
canvas.style.width = `${cw / dpr}px`;
canvas.style.height = `${ch / dpr}px`;
onReady(true);
- }, [streak, live.rotation, poseZoom, painted, w, h, dpr, onReady]);
+ }, [streak, live.rotation, poseZoom, painted, w, h, dpr, onReady, selfMoving, tLocal]);
return (
<div
className="pointer-events-none absolute"
@@ -1649,10 +1679,15 @@ function StreakCanvas({
// The stage in the element's unposed frame, as the dive canvas sits.
transform: `translate(${-o.x * stageWidth}px, ${-o.y * stageHeight}px)`,
filter,
- ...(mask ? { ...mask, maskPosition: "0px 0px", WebkitMaskPosition: "0px 0px" } : {}),
}}
>
- <canvas ref={ref} width={1} height={1} className="absolute" style={{ display: "none" }} />
+ {/* The mask clips inside the filter, so the streak blurs after it. */}
+ <div
+ className="absolute inset-0"
+ style={mask ? { ...mask, maskPosition: "0px 0px", WebkitMaskPosition: "0px 0px" } : undefined}
+ >
+ <canvas ref={ref} width={1} height={1} className="absolute" style={{ display: "none" }} />
+ </div>
</div>
);
}
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index fcb07215..e6112bef 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -108,7 +108,7 @@ import type { VideoGenToolName } from "@/cut/components/GeneratePanel.tools";
import type { ImageGenToolName } from "@/cut/components/ImageGenPanel.tools";
import type { InspectorToolName } from "@/cut/components/Inspector.tools";
import type { GroupPanelToolName } from "@/cut/components/GroupPanel.tools";
-import { CAMERA_SCALE_MAX, CAMERA_SCALE_MIN, ELEMENT_BLUR_MAX, isEaseId, upsertKey as upsertCameraKey, type CameraKey } from "@donkeycut/effects-kit";
+import { CAMERA_SCALE_MAX, CAMERA_SCALE_MIN, CAMERA_WORLD_MAX, CAMERA_WORLD_MIN, ELEMENT_BLUR_MAX, isEaseId, upsertKey as upsertCameraKey, type CameraKey } from "@donkeycut/effects-kit";
import { groupCameraOf, groupCameraPoseAt } from "@/cut/lib/groupCamera";
import { cutMotion } from "@/cut/lib/motionSettings";
import type { LibraryToolName } from "@/cut/components/LibraryView.tools";
@@ -721,8 +721,8 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
o.id,
clamp(k.t, 0, dur),
{
- ...(isNum(k.x) ? { x: clamp(k.x, 0.02, 0.98) } : {}),
- ...(isNum(k.y) ? { y: clamp(k.y, 0.02, 0.98) } : {}),
+ ...(isNum(k.x) ? { x: clampOverlayPos(k.x, o) } : {}),
+ ...(isNum(k.y) ? { y: clampOverlayPos(k.y, o) } : {}),
...(isNum(k.scale) ? { scale: clamp(k.scale, 0.1, 4) } : {}),
...(isNum(k.rotation) ? { rotation: clamp(Math.round(k.rotation), -180, 180) } : {}),
...(isNum(k.opacity) ? { opacity: clamp(k.opacity, 0, 1) } : {}),
@@ -757,23 +757,17 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const was = groupCameraPoseAt(view, t);
const key: CameraKey = {
t,
- x: isNum(k.x) ? clamp(k.x, -1, 2) : was.x,
- y: isNum(k.y) ? clamp(k.y, -1, 2) : was.y,
+ x: isNum(k.x) ? clamp(k.x, CAMERA_WORLD_MIN, CAMERA_WORLD_MAX) : was.x,
+ y: isNum(k.y) ? clamp(k.y, CAMERA_WORLD_MIN, CAMERA_WORLD_MAX) : was.y,
scale: isNum(k.scale) ? clamp(k.scale, CAMERA_SCALE_MIN, CAMERA_SCALE_MAX) : was.scale,
rotation: isNum(k.rotation) ? clamp(k.rotation, -180, 180) : was.rotation,
- ...(k.ease !== undefined && easeInput(k.ease) ? { ease: easeInput(k.ease) } : {}),
};
+ const ease = k.ease !== undefined ? easeInput(k.ease) : undefined;
+ if (ease) key.ease = ease;
keys = upsertCameraKey(keys, key);
}
}
- const motionBlur =
- isNum(input.shutter) && input.shutter > 0
- ? clamp(input.shutter, 0.05, 1)
- : input.motion_blur === true
- ? view.motionBlur ?? cutMotion().motionBlur
- : input.motion_blur === false || (isNum(input.shutter) && input.shutter <= 0)
- ? undefined
- : view.motionBlur;
+ const motionBlur = shutterInput(input, view.motionBlur);
s.setGroupCamera(groupId, { keys, ...(motionBlur ? { motionBlur } : {}) });
const next = groupCameraOf(useEditor.getState().overlays, groupId)!;
return {
@@ -2890,7 +2884,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const targets = (ids ?? [String(input.id)]).map((id) => requireItem(s.overlays, id, "overlay element"));
// One undo step for the whole write, however many elements it lands on.
s.pushHistory();
- for (const o of targets) applyOverlayPatchSettled(o.id, overlayPatch(input, o.kind ?? "text"));
+ for (const o of targets) applyOverlayPatchSettled(o.id, overlayPatch(input, o.kind ?? "text", o));
const report = (id: string) => {
const next = useEditor.getState().overlays.find((x) => x.id === id)!;
return {
@@ -6578,6 +6572,16 @@ async function launchVideoJob(
* position, rotation, opacity, hidden) plus the target kind's own fields.
* Outline width is em for text (scales with the type) and design px for
* shapes, so the interpretation follows the element being patched. */
+/** A shutter from a call: `shutter` (0 or less turns it off), or
+ * `motion_blur` true for the current one or the default, false for off;
+ * neither keeps `current`. */
+function shutterInput(input: Record<string, unknown>, current: number | undefined): number | undefined {
+ if (isNum(input.shutter)) return input.shutter > 0 ? clamp(input.shutter, 0.05, 1) : undefined;
+ if (input.motion_blur === true) return current ?? cutMotion().motionBlur;
+ if (input.motion_blur === false) return undefined;
+ return current;
+}
+
/** A key's ease from a call: a known curve, or linear (no ease) for
* "linear" and anything else. */
function easeInput(v: unknown) {
@@ -6585,22 +6589,24 @@ function easeInput(v: unknown) {
return v === "linear" ? undefined : v;
}
-function overlayPatch(input: Record<string, unknown>, kind: "text" | "shape" | "sticker" | "effect") {
+function overlayPatch(
+ input: Record<string, unknown>,
+ kind: "text" | "shape" | "sticker" | "effect",
+ place?: { groupId?: string }
+) {
const patch: Record<string, unknown> = {};
if (isNum(input.start)) patch.start = Math.max(0, input.start);
if (isNum(input.end)) patch.end = input.end;
if (isNum(input.lane)) patch.lane = Math.max(0, Math.round(input.lane));
- if (isNum(input.x)) patch.x = clamp(input.x, 0.02, 0.98);
- if (isNum(input.y)) patch.y = clamp(input.y, 0.02, 0.98);
+ if (isNum(input.x)) patch.x = clampOverlayPos(input.x, place);
+ if (isNum(input.y)) patch.y = clampOverlayPos(input.y, place);
if (isNum(input.rotation))
patch.rotation = Math.round(clamp(input.rotation, -180, 180)) || undefined;
if (isNum(input.opacity))
patch.opacity = input.opacity >= 0.995 ? undefined : clamp(input.opacity, 0, 1);
if (kind !== "effect") {
if (isNum(input.blur)) patch.blur = input.blur <= 0.05 ? undefined : clamp(input.blur, 0, ELEMENT_BLUR_MAX);
- if (isNum(input.shutter)) patch.motionBlur = input.shutter <= 0 ? undefined : clamp(input.shutter, 0.05, 1);
- else if (input.motion_blur === true) patch.motionBlur = cutMotion().motionBlur;
- if (input.motion_blur === false) patch.motionBlur = undefined;
+ if (isNum(input.shutter) || typeof input.motion_blur === "boolean") patch.motionBlur = shutterInput(input, undefined);
}
if (typeof input.hidden === "boolean") patch.hidden = input.hidden || undefined;
if (typeof input.name === "string") patch.name = input.name.trim().slice(0, 60) || undefined;
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 9ae36e70..0ae6265d 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -31,7 +31,7 @@ import { createRasterCanvas, rasterCanvasToPng } from "./raster";
import { clipLen, clipSpeed, getClipSpans, openedTimeline, overlayLayers, projectDuration, spanSequence, useEditor } from "./store";
import { captionStyle, cueOverlay, cueWordFrames, laneCues, laneHidden, subtitleLaneCount, trackPos } from "./subtitles";
import { isMaskAnimated, isOverlayAnimated, matteLumaToAlpha, normalizeGrade, paintMaskLuma, paintStrokeInk, retimeOf, type SpeedNode } from "@donkeycut/effects-kit";
-import { renderElementFrames, renderElementPng } from "./textRender";
+import { renderElementFrames, renderElementPng, renderStillPng } from "./textRender";
import { clipCovers, clipKeyed, clipPosed, clipPoseAt, clipZoom, contentRect, frameOf, isStickerOverlay, isTextOverlay, laneOf, overlayAnimStyle, projectBackground, rectOf, regionPx, removalActive, shadowInk, subjectMasked, parkedTimeline } from "./types";
import { liveReader } from "./liveReader";
import { soundSourceOf, spanSoundSpec, spanUsesSoundFeature, specSound } from "./soundSource";
@@ -1378,7 +1378,7 @@ export async function buildExportPayload(
});
continue;
}
- const png = await renderElementPng(o, settings.width, settings.height, doc.assets);
+ const png = await renderStillPng(o, settings.width, settings.height, doc.assets);
const key = `overlay_${i}.png`;
pngs.push({ name: key, blob: png });
overlays.push({
diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.ts
index b5cc32a7..7d8028e1 100644
--- a/site/src/cut/lib/exportRender.ts
+++ b/site/src/cut/lib/exportRender.ts
@@ -53,7 +53,7 @@ import { hasSubjectOverlays, SubjectMaskCompositor } from "./behindPass";
import { MatteAlpha, matteStamp } from "./matteAlpha";
import { createRasterCanvas, type RasterSurface } from "./raster";
import { exportFrameSynth, SYNTH_EDGE, synthWeight, type FrameSynth } from "./frameSynth";
-import { cutRenderEnv, renderElementCanvas, renderElementPng } from "./textRender";
+import { cutRenderEnv, renderElementCanvas, renderElementPng, renderStillPng } from "./textRender";
import { cardMatteKey } from "./cameraCard";
import { assetIsSilent, behindSubjectOverlay, clipCovers, frameOf, frontSubjectOverlay, isEffectOverlay, isTextOverlay, laneOf, overlayAnimStyle, projectBackground, rectOf, removalActive } from "./types";
import type { ClipAnim, ClipSpan, EffectOverlay, MediaAsset, Overlay, StickerOverlay } from "./types";
@@ -749,13 +749,11 @@ class StampCache {
async bitmapFor(layer: StampedLayer): Promise<ImageBitmap> {
let bitmap = this.drawn.get(layer);
if (!bitmap) {
- const png = await renderElementPng(
- layer.overlay,
- this.width,
- this.height,
- this.assets,
- layer.phase
- );
+ // A layer with no animation holds still, its blur baked into the
+ // picture; an animated one is neutral and softens as it is drawn.
+ const png = layer.anim
+ ? await renderElementPng(layer.overlay, this.width, this.height, this.assets, layer.phase)
+ : await renderStillPng(layer.overlay, this.width, this.height, this.assets);
bitmap = await createImageBitmap(png);
this.drawn.set(layer, bitmap);
}
diff --git a/site/src/cut/lib/groupCamera.ts b/site/src/cut/lib/groupCamera.ts
index b429688b..2562f339 100644
--- a/site/src/cut/lib/groupCamera.ts
+++ b/site/src/cut/lib/groupCamera.ts
@@ -1,4 +1,4 @@
-import { cameraAt, hasCameraKeys, type CameraKey, type CameraPose, type GroupCamera } from "@donkeycut/effects-kit";
+import { cameraAt, hasCameraKeys, shiftCamera, type CameraKey, type CameraPose, type GroupCamera } from "@donkeycut/effects-kit";
import type { Overlay } from "./types";
/**
@@ -18,7 +18,7 @@ export interface GroupCameraView {
}
/** The elements a group's camera films: every member with a pose. */
-export function cameraMembers(overlays: readonly Overlay[], groupId: string): Overlay[] {
+function cameraMembers(overlays: readonly Overlay[], groupId: string): Overlay[] {
return overlays.filter((o) => o.groupId === groupId && o.kind !== "effect");
}
@@ -76,6 +76,40 @@ export function withGroupCamera(
});
}
+/**
+ * Keep each group's camera on the timeline after some elements moved in time.
+ * A group whose filmed members all moved by the same amount carries its
+ * camera with it. A group torn apart — one member moved, or pushed aside —
+ * keeps every member filming the same timeline moments, so each moved copy
+ * shifts back by its own move. Returns `after` itself when nothing changed.
+ */
+export function settleCameras(before: readonly Overlay[], after: Overlay[]): Overlay[] {
+ const was = new Map(before.map((o) => [o.id, o.start]));
+ const moves = new Map<string, number>();
+ for (const o of after) {
+ const from = was.get(o.id);
+ if (o.camera && from !== undefined) moves.set(o.id, o.start - from);
+ }
+
+ // A group is torn when its members' moves disagree.
+ const torn = new Set<string>();
+ const first = new Map<string, number>();
+ for (const o of after) {
+ const d = moves.get(o.id);
+ if (d === undefined || !o.groupId) continue;
+ const seen = first.get(o.groupId);
+ if (seen === undefined) first.set(o.groupId, d);
+ else if (Math.abs(seen - d) > 1e-9) torn.add(o.groupId);
+ }
+ if (!torn.size) return after;
+
+ return after.map((o) => {
+ const d = moves.get(o.id) ?? 0;
+ if (!o.camera || !o.groupId || !torn.has(o.groupId) || Math.abs(d) < 1e-9) return o;
+ return { ...o, camera: shiftCamera(o.camera, -d) } as Overlay;
+ });
+}
+
/** An element with no camera field at all. */
export function withoutCamera<O extends { camera?: GroupCamera }>(o: O): O {
if (!("camera" in o)) return o;
diff --git a/site/src/cut/lib/groupEdit.test.ts b/site/src/cut/lib/groupEdit.test.ts
index bec05036..bd05fbaa 100644
--- a/site/src/cut/lib/groupEdit.test.ts
+++ b/site/src/cut/lib/groupEdit.test.ts
@@ -27,6 +27,14 @@ describe("groupEdit", () => {
expect(0.8 + edge.dy).toBeCloseTo(0.98);
});
+ test("grouped elements move across the camera's world", () => {
+ const items = [{ x: 1.4, y: 0.5, groupId: "g" }, { x: 0.6, y: 0.5, groupId: "g" }];
+ const right = selectionTranslation(items, { x: 1.1, y: 0.5 });
+ expect(1.4 + right.dx).toBeCloseTo(1.5);
+ const far = selectionTranslation(items, { x: 5, y: 0.5 });
+ expect(1.4 + far.dx).toBeCloseTo(2);
+ });
+
test("the summary counts by kind", () => {
const overlays = [
{ kind: "shape" } as Overlay, { kind: "shape" } as Overlay, { text: "hi" } as Overlay,
diff --git a/site/src/cut/lib/groupEdit.ts b/site/src/cut/lib/groupEdit.ts
index dd399cdf..91bc7a62 100644
--- a/site/src/cut/lib/groupEdit.ts
+++ b/site/src/cut/lib/groupEdit.ts
@@ -36,14 +36,17 @@ export function selectionCenter(items: readonly { x: number; y: number }[]): { x
* an element can sit at, so the set never folds in on itself.
*/
export function selectionTranslation(
- items: readonly { x: number; y: number }[], target: { x: number; y: number },
+ items: readonly { x: number; y: number; groupId?: string }[], target: { x: number; y: number },
): { dx: number; dy: number } {
if (!items.length) return { dx: 0, dy: 0 };
const center = selectionCenter(items);
- const lo = clampOverlayPos(0), hi = clampOverlayPos(1);
- const xs = items.map((it) => it.x), ys = items.map((it) => it.y);
- const dx = Math.max(lo - Math.min(...xs), Math.min(hi - Math.max(...xs), target.x - center.x));
- const dy = Math.max(lo - Math.min(...ys), Math.min(hi - Math.max(...ys), target.y - center.y));
+ const room = (axis: "x" | "y") => ({
+ lo: Math.max(...items.map((it) => clampOverlayPos(-Infinity, it) - it[axis])),
+ hi: Math.min(...items.map((it) => clampOverlayPos(Infinity, it) - it[axis])),
+ });
+ const rx = room("x"), ry = room("y");
+ const dx = Math.max(rx.lo, Math.min(rx.hi, target.x - center.x));
+ const dy = Math.max(ry.lo, Math.min(ry.hi, target.y - center.y));
return { dx, dy };
}
diff --git a/site/src/cut/lib/store.test.ts b/site/src/cut/lib/store.test.ts
index 56ce58db..b91ae159 100644
--- a/site/src/cut/lib/store.test.ts
+++ b/site/src/cut/lib/store.test.ts
@@ -3,6 +3,7 @@ import { groupRemap } from "@donkeycut/effects-kit";
import { adoptTransitionFields, assetIdsInUse, clipLen, closeMicroGaps, cutTranscribeSpec, deriveTransitionFields, docOverlays, getClipSpans, liftClipLooks, moveOverlayGroup, overlayLaneOrder, normalizeElementLanes, parkedTransitions, placeInRun, projectDuration, rippleInsert, separateOverlaps, serializeDoc, useEditor, DOC_KEYS, docFieldsEdited } from "./store";
import type React from "react";
import { runAiTool } from "./aiTools";
+import { withGroupCamera } from "./groupCamera";
import { selectedMembers, startLaneMove } from "./laneTracks";
import { expandTimelineGroups } from "./timelineGroups";
import { timelineItem } from "./timelineItems";
@@ -782,6 +783,60 @@ describe("title lanes", () => {
});
});
+ describe("group camera on a lone move", () => {
+ const push = [
+ { t: 0, x: 0.5, y: 0.5, scale: 1, rotation: 0 },
+ { t: 2, x: 0.5, y: 0.5, scale: 2, rotation: 0 },
+ ];
+
+ test("moving one member keeps its camera on the timeline", () => {
+ const a = title({ start: 0, end: 4, groupId: "g" });
+ const b = title({ start: 0, end: 4, lane: 1, groupId: "g" });
+ useEditor.setState({ overlays: withGroupCamera([a, b], "g", { keys: push }) });
+ s().updateOverlay(b.id, { start: 1 });
+ // b now starts 1s later, so the push at timeline 2s sits 1s into it.
+ expect(overlayById(a.id).camera!.kf.map((k) => k.t)).toEqual([0, 2]);
+ expect(overlayById(b.id).camera!.kf.map((k) => k.t)).toEqual([-1, 1]);
+ });
+
+ test("a member pushed clear of a moved group keeps its camera on the timeline", () => {
+ const x = title({ start: 0, end: 2, groupId: "m" });
+ const y = title({ start: 10, end: 11, lane: 1, groupId: "m" });
+ const a = title({ start: 3, end: 6, groupId: "g" });
+ const b = title({ start: 3, end: 6, lane: 1, groupId: "g" });
+ useEditor.setState({ overlays: [x, y, ...withGroupCamera([a, b], "g", { keys: push })] });
+ s().updateOverlaysTransient([{ id: x.id, patch: { start: 2, end: 4 } }]);
+ moveOverlayGroup(x, 2);
+ // a slid to 4 to clear the mover; the push still lands at timeline 5s.
+ expect(overlayById(a.id).start).toBeCloseTo(4);
+ expect(overlayById(a.id).camera!.kf.map((k) => k.t)).toEqual([-1, 1]);
+ expect(overlayById(b.id).camera!.kf.map((k) => k.t)).toEqual([0, 2]);
+ });
+
+ test("the chat places a grouped element beyond the frame", async () => {
+ const a = title({ start: 0, end: 4, groupId: "g" });
+ const b = title({ start: 0, end: 4, lane: 1 });
+ useEditor.setState({ overlays: [a, b] });
+ await runAiTool("update_overlay", { id: a.id, x: 1.4, y: -0.3 });
+ await runAiTool("update_overlay", { id: b.id, x: 1.4 });
+ expect(overlayById(a.id).x).toBeCloseTo(1.4);
+ expect(overlayById(a.id).y).toBeCloseTo(-0.3);
+ expect(overlayById(b.id).x).toBeCloseTo(0.98);
+ await runAiTool("set_overlay_keyframes", { id: a.id, keys: [{ t: 1, x: 1.8 }] });
+ expect(overlayById(a.id).kf![0].x).toBeCloseTo(1.8);
+ });
+
+ test("a whole group moving carries its camera", () => {
+ const a = title({ start: 5, end: 7, groupId: "g" });
+ const b = title({ start: 9, end: 13, lane: 1, groupId: "g" });
+ useEditor.setState({ overlays: withGroupCamera([a, b], "g", { keys: push }) });
+ s().updateOverlaysTransient([{ id: a.id, patch: { start: 6, end: 8 } }]);
+ moveOverlayGroup(a, 1);
+ expect(overlayById(a.id).camera!.kf.map((k) => k.t)).toEqual([0, 2]);
+ expect(overlayById(b.id).camera!.kf.map((k) => k.t)).toEqual([-4, -2]);
+ });
+ });
+
describe("keyframes", () => {
test("a key captures the pose and the track drops when the last one goes", () => {
const t1 = title({ start: 2, end: 6, x: 0.4, rotation: 30, opacity: 0.5 });
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 40c6ac45..fcfce8f3 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -61,7 +61,7 @@ import type {
} from "./types";
import type { VideoProject } from "./genvideo/types";
import { expandTimelineGroups, reorderTimelineClip, selectedGroupIds, setTimelineGroup } from "./timelineGroups";
-import { groupCameraOf, withGroupCamera, withoutCamera } from "./groupCamera";
+import { groupCameraOf, settleCameras, withGroupCamera, withoutCamera } from "./groupCamera";
import type { CameraKey } from "@donkeycut/effects-kit";
import { mapTimelineItems, pasteTimelineItems, splitTimelineItems, shiftedTimelineItems, timelineCopies, timelinePlacementDelta, timelineRange } from "./timelineItems";
import { fillSlot } from "./genvideo/fillSlot";
@@ -1188,8 +1188,15 @@ export function applyOverlayPatchSettled(id: string, patch: OverlayPatch) {
const p = { ...patch };
if ("start" in p && !("end" in p) && p.start !== undefined)
p.end = p.start + (before.end - before.start);
+ const was = st.overlays;
st.updateOverlayTransient(id, p);
settleOverlayFootprint(id, p);
+
+ // A member that moved alone, or pushed one aside, leaves its group's camera
+ // on the timeline.
+ const moved = useEditor.getState().overlays;
+ const settled = settleCameras(was, moved);
+ if (settled !== moved) useEditor.setState({ overlays: settled });
}
function settleOverlayFootprint(id: string, patch: OverlayPatch) {
@@ -1289,10 +1296,11 @@ function overlaysClearOf(overlays: Overlay[], ids: Set<string>): Overlay[] {
}
}
if (shifted.size === 0) return overlays;
- return overlays.map((o) => {
+ const cleared = overlays.map((o) => {
const by = shifted.get(o.id);
return by ? { ...o, start: o.start + by, end: o.end + by } : o;
});
+ return settleCameras(overlays, cleared);
}
/** Apply a source trim or speed change with the shared same-row collision rule. */
@@ -4241,12 +4249,12 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
.filter((v) => !!v && (v.keys.length > 0 || !!v.motionBlur))
.sort((a, b) => a!.start - b!.start)[0];
const fresh = grouped.overlays.map((o) => (o.groupId === groupId ? withoutCamera(o) : o));
- const overlays = filmed
- ? (() => {
- const start = Math.min(...fresh.filter((o) => o.groupId === groupId && o.kind !== "effect").map((o) => o.start));
- const keys = filmed.keys.map((k) => ({ ...k, t: k.t + filmed.start - start }));
- return withGroupCamera(fresh, groupId, { keys, motionBlur: filmed.motionBlur });
- })()
+ const at = groupCameraOf(fresh, groupId);
+ const overlays = filmed && at
+ ? withGroupCamera(fresh, groupId, {
+ keys: filmed.keys.map((k) => ({ ...k, t: k.t + filmed.start - at.start })),
+ motionBlur: filmed.motionBlur,
+ })
: fresh;
set({ ...grouped, overlays, subtitles: { ...s.subtitles, cues: grouped.subtitles.cues }, multiSelection: members });
return groupId;
diff --git a/site/src/cut/lib/textRender.ts b/site/src/cut/lib/textRender.ts
index b0f0c004..a2e8206e 100644
--- a/site/src/cut/lib/textRender.ts
+++ b/site/src/cut/lib/textRender.ts
@@ -5,6 +5,7 @@ import {
WORD_BASELINE_DROP,
renderElementCanvas as kitRenderElementCanvas,
renderElementPng as kitRenderElementPng,
+ renderStillPng as kitRenderStillPng,
renderOverlayFrames as kitRenderOverlayFrames,
LINE_HEIGHT,
type OverlayFrameSet,
@@ -182,6 +183,11 @@ export function renderElementPng(
return kitRenderElementPng(overlay, width, height, cutRenderEnv(assets), phase);
}
+/** An element that holds still as one full-frame PNG, its blur baked in. */
+export function renderStillPng(overlay: Overlay, width: number, height: number, assets: MediaAsset[] = []): Promise<Blob> {
+ return kitRenderStillPng(overlay, width, height, cutRenderEnv(assets));
+}
+
/** The element drawn on a canvas at the export resolution, for a picture
* drawn straight away. */
export function renderElementCanvas(
diff --git a/site/src/cut/lib/trackKeys.test.ts b/site/src/cut/lib/trackKeys.test.ts
index 7174cadd..0efc12ce 100644
--- a/site/src/cut/lib/trackKeys.test.ts
+++ b/site/src/cut/lib/trackKeys.test.ts
@@ -93,6 +93,13 @@ describe("a tracked mask", () => {
expect(m.points![0].x).toBeCloseTo(-0.05, 6);
});
+ test("an element with motion blur or a group camera still takes a tracked mask", () => {
+ const overlay = { id: "o1", kind: "shape", start: 0, end: 1, x: 0.3, y: 0.5, motionBlur: 0.5, groupId: "g", camera: { kf: [{ t: 0, x: 0.5, y: 0.5, scale: 2, rotation: 0 }] } } as unknown as Overlay;
+ const m = trackedMask({ kind: "overlay", overlay }, "9:16", [0], [at(0.3, 0.5)], {}, 0)!;
+ // The camera's 2× zoom about the center moves the element to x 0.1.
+ expect(m.points![0].x).toBeCloseTo(0.05, 6);
+ });
+
test("straight stretches drop their middle keys", () => {
const t = times(30);
const m = trackedMask({ kind: "clip", clip: clip() }, "9:16", t, t.map((s) => at(0.2 + s * 0.3, 0.5)), {}, 0.0015)!;
diff --git a/site/src/cut/lib/trackKeys.ts b/site/src/cut/lib/trackKeys.ts
index 8967c55b..935bf4a0 100644
--- a/site/src/cut/lib/trackKeys.ts
+++ b/site/src/cut/lib/trackKeys.ts
@@ -178,7 +178,7 @@ function toMaskSpace(item: TrackItem, aspect: Aspect, tLocal: number): (p: Pt) =
const o = item.overlay;
const fr = frameOf(aspect);
const ds = Math.min(fr.w, fr.h) / 1080;
- const ev = evalOverlayFrame(o, tLocal);
+ const ev = evalOverlayFrame(o, tLocal, fr.w / fr.h);
const turn = (-ev.rotation * Math.PI) / 180;
const scale = Math.max(1e-6, ev.scale);
return (p) => {
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index 05a255d9..a1b394c6 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -1,6 +1,8 @@
import type { GuideId, GuideLines } from "./guides";
import {
type OutputSpace,
+ CAMERA_WORLD_MAX,
+ CAMERA_WORLD_MIN,
EFFECT_LABELS,
behindSubjectMask,
overlayKind,
@@ -83,8 +85,10 @@ export function normalizeAspect(a: string | undefined | null): Aspect | null {
/** An overlay's center, held far enough inside the frame that the element it
* belongs to always has a grabbable piece on screen. Every path that writes a
* position — dragging in the preview, the inspector's own fields — passes
- * through it, so no route can strand an element off-frame. */
-export const clampOverlayPos = (v: number) => Math.min(0.98, Math.max(0.02, v));
+ * through it, so no route can strand an element off-frame. An element in a
+ * group may sit anywhere in the camera's world, for a camera to pan to. */
+export const clampOverlayPos = (v: number, o?: { groupId?: string }) =>
+ o?.groupId ? Math.min(CAMERA_WORLD_MAX, Math.max(CAMERA_WORLD_MIN, v)) : Math.min(0.98, Math.max(0.02, v));
/** Output frame in pixels. The short side is pinned to 1080 — the design
* short side that text scaling and overlay math assume — and the long side
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 28d28ebf..ae7d2fe3 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -586,7 +586,7 @@ The opening line (the hook) is a split. The call to action and everything after
**6. Graphics.** One look across the video: one background, one face, one accent color, held from the first graphic to the last. Each graphic has one dominant subject and at most one supporting cue. Show the thing being talked about — the person's own screenshots and screen recordings first (from media), then stock_search, or generate_image for an illustration or a clean card. The captions carry the words, so a graphic holds no labels restating the narration; a headline at most.
- Facts: check_facts every figure, date and release the narration states before it goes on screen. Something that happened shows through the person's own screenshot of its source; a source they gave no screenshot of is named in the closing message with the page the check found. A figure that disagrees with its sources is reported there too.
-- Motion: lay a visual's cards out as one world (titles, shapes, stickers placed across and beyond the frame), group_items them, and move a camera over it with set_group_camera — a glide (sine.inOut, zoom change ≤ 0.04), a step to the next card (0.5s power3.inOut, starting 0.25s before the word that names it), a push onto the card being talked about (1.2–2s power2.inOut, up to ~1.6×), a pull back to show the whole, and at most one whip per run (out over 0.45s power3.in, in over 0.6s power3.out). motion_blur on the camera streaks its moves and leaves every frame at rest sharp. Each run's first frame is the camera at rest.
+- Motion: lay a visual's cards out as one world (titles, shapes, stickers grouped with group_items, then placed across and beyond the frame), and move a camera over it with set_group_camera — a glide (sine.inOut, zoom change ≤ 0.04), a step to the next card (0.5s power3.inOut, starting 0.25s before the word that names it), a push onto the card being talked about (1.2–2s power2.inOut, up to ~1.6×), a pull back to show the whole, and at most one whip per run (out over 0.45s power3.in, in over 0.6s power3.out). motion_blur on the camera streaks its moves and leaves every frame at rest sharp. Each run's first frame is the camera at rest.
- Focus: as the camera pushes, the card being read stays sharp and its neighbours take set_overlay_keyframes keys of blur ~14 and opacity ~0.7; a word the viewer has to read is never blurred.
- A graphic's content keeps clear of the caption band and, on a split, of the card and the head.