The VS Code of video editing, built for agents.
TypeScript
Add angular gradient support in fill-picker and related components
konstantin-paulusacb7092faa36
diff --git a/apps/web/src/components/sidebar-right/inspector/fill-picker.tsx b/apps/web/src/components/sidebar-right/inspector/fill-picker.tsxindex 9dfdd5cd..7a0bdf35 100644--- a/apps/web/src/components/sidebar-right/inspector/fill-picker.tsx+++ b/apps/web/src/components/sidebar-right/inspector/fill-picker.tsx@@ -27,16 +27,18 @@ import {ImagePaint,LinearGradientPaint,RadialGradientPaint,+ AngularGradientPaint,SolidPaint,VideoPaint,} from "@diffusionstudio/reconciler";-import { BlendMode, BlendModeType, Cache, Paint, PaintType, Rotation, ScaleMode, ScaleModeType } from "@diffusionstudio/runtime";+import { BlendMode, BlendModeType, Cache, ELLIPTICAL_GRADIENT_DEFAULTS, EllipticalGradient, Paint, PaintType, Rotation, ScaleMode, ScaleModeType } from "@diffusionstudio/runtime";import { useEditor } from "@/engine/hooks";import { BLEND_MODE_ORDER, BLEND_MODE_SEPARATORS, blendModeName, displayBlendMode } from "./blend-modes";import { readStopProps } from "./gradient-stops";import { SolidFillPicker } from "./solid-picker";import { GradientFillPicker } from "./gradient-picker";import { AssetFillPicker } from "./asset-picker";+import { assert } from "@/utils";import type { Fit } from "@diffusionstudio/jsx";import type { Asset } from "@diffusionstudio/assets";@@ -80,10 +82,19 @@ export type FillPickerProps = {tabs?: FillTab[];};+export type GradientKind = PaintType.LINEAR_GRADIENT | PaintType.RADIAL_GRADIENT | PaintType.ANGULAR_GRADIENT;++const GRADIENT_ELEMENTS = {+ [PaintType.LINEAR_GRADIENT]: LinearGradientPaint,+ [PaintType.RADIAL_GRADIENT]: RadialGradientPaint,+ [PaintType.ANGULAR_GRADIENT]: AngularGradientPaint,+};+export function getFillTab(paint: PaintType): FillTab {if (paint === PaintType.SOLID) return "solid";if (paint === PaintType.LINEAR_GRADIENT) return "gradient";if (paint === PaintType.RADIAL_GRADIENT) return "gradient";+ if (paint === PaintType.ANGULAR_GRADIENT) return "gradient";return "asset";}@@ -145,21 +156,20 @@ export function FillPicker(props: FillPickerProps) {// picked there is nothing to author.};- /**- * Swaps a linear gradient for a radial one (or back). The two are separate- * elements, so the stops and the rotation are written out onto the new one- * rather than carried by it.- */- const handleGradientKindChange = (radial: boolean) => {- const isRadial = paintType() === PaintType.RADIAL_GRADIENT;- if (radial === isRadial) return;+ const handleGradientKindChange = (kind: GradientKind) => {+ if (kind === paintType()) return;const stops = readStopProps(world, props.fill);- const rotation = props.fill.get(Rotation)?.value ?? 0;- const Element = radial ? RadialGradientPaint : LinearGradientPaint;+ const Element = GRADIENT_ELEMENTS[kind];++ // switching between elliptical gradients preserves placement+ let placement: Record<string, number> = {};+ if (isEllipticalGradient(kind) && isEllipticalGradient(paintType())) {+ placement = readEllipitcalGradientProps(props.fill);+ }replaceFill(() => (- <Element {...(rotation === 0 ? {} : { rotation })}>+ <Element {...placement}>{stops.map((stop) => (<ColorStopElement offset={stop.offset} color={stop.color} opacity={stop.opacity} />))}@@ -227,7 +237,7 @@ export function FillPicker(props: FillPickerProps) {<SolidFillPicker fill={props.fill} /></Show><Show when={currentTab() === "gradient"}>- <GradientFillPicker fill={props.fill} onChangeKind={handleGradientKindChange} />+ <GradientFillPicker node={props.node} fill={props.fill} onChangeKind={handleGradientKindChange} /></Show><Show when={currentTab() === "asset"}><AssetFillPicker node={props.node} fill={props.fill} onSelectAsset={handleSelectAsset} />@@ -391,3 +401,28 @@ function BlendModeMenu(props: BlendModeMenuProps) {</DropdownMenu>);}++function isEllipticalGradient(paint: PaintType): boolean {+ return paint === PaintType.RADIAL_GRADIENT || paint === PaintType.ANGULAR_GRADIENT;+}++/** A radial or angular paint's authored placement, as the props that write it; defaults are left out. */+function readEllipitcalGradientProps(paint: Entity): Record<string, number> {+ const ellipse = paint.get(EllipticalGradient);+ const rotation = paint.get(Rotation)?.value ?? 0;+ const placement: Record<string, number> = {};++ assert(ellipse, "Elliptical gradient not found");++ for (const name of ["cx", "cy", "rx", "ry"] as const) {+ if (ellipse[name] !== ELLIPTICAL_GRADIENT_DEFAULTS[name]) {+ placement[name] = ellipse[name];+ }+ }++ if (rotation !== 0) {+ placement.rotation = rotation;+ }++ return placement;+}diff --git a/apps/web/src/components/sidebar-right/inspector/fill-row.tsx b/apps/web/src/components/sidebar-right/inspector/fill-row.tsxindex 76ebe927..72b54dd1 100644--- a/apps/web/src/components/sidebar-right/inspector/fill-row.tsx+++ b/apps/web/src/components/sidebar-right/inspector/fill-row.tsx@@ -32,6 +32,7 @@ const FILL_TYPE_LABELS: Record<PaintType, string> = {[PaintType.VIDEO]: "Video",[PaintType.LINEAR_GRADIENT]: "Gradient",[PaintType.RADIAL_GRADIENT]: "Gradient",+ [PaintType.ANGULAR_GRADIENT]: "Gradient",[PaintType.WAVEFORM]: "Waveform",[PaintType.HTML]: "Html",[PaintType.SURFACE]: "Surface",diff --git a/apps/web/src/components/sidebar-right/inspector/gradient-picker.tsx b/apps/web/src/components/sidebar-right/inspector/gradient-picker.tsxindex 0a06632a..8920527a 100644--- a/apps/web/src/components/sidebar-right/inspector/gradient-picker.tsx+++ b/apps/web/src/components/sidebar-right/inspector/gradient-picker.tsx@@ -37,23 +37,32 @@ import { useDrag } from "@/hooks/use-drag";import { clamp, mergeColorWithOpacity } from "@/utils";import { useTrait, useWorld } from "@diffusionstudio/koota-solid";import { ColorStop as ColorStopElement } from "@diffusionstudio/reconciler";-import { Computed, Paint, PaintType, colorToHex, parseColor } from "@diffusionstudio/runtime";+import { Computed, LINEAR_GRADIENT_DEFAULTS, Paint, PaintType, colorToHex, parseColor } from "@diffusionstudio/runtime";import { useDerived, useEditor } from "@/engine/hooks";import { syncKeyframe } from "@/engine/keyframes";+import { beginGradientTool, endGradientTool } from "@/engine/gradient-tool";import { readGradientStops, sameGradientStops, type GradientStop } from "./gradient-stops";import type { Entity } from "koota";+import type { GradientKind } from "./fill-picker";export type GradientPickerProps = {+ node: Entity;fill: Entity;- /** Swaps the gradient for one of the other kind, which is another element. */- onChangeKind(radial: boolean): void;+ onChangeKind(kind: GradientKind): void;};-const GRADIENT_STYLE_OPTIONS = ["Linear", "Radial"] as const;-type GradientStyleOption = (typeof GRADIENT_STYLE_OPTIONS)[number];+const GRADIENT_STYLES = {+ Linear: PaintType.LINEAR_GRADIENT,+ Radial: PaintType.RADIAL_GRADIENT,+ Angular: PaintType.ANGULAR_GRADIENT,+} as const;-/** `<colorStop>`'s and `<linearGradientPaint>`'s defaults. */+const GRADIENT_STYLE_OPTIONS = Object.keys(GRADIENT_STYLES) as GradientStyleOption[];++type GradientStyleOption = keyof typeof GRADIENT_STYLES;++/** `<colorStop>`'s and the radial and angular gradients' defaults. */const DEFAULT_OPACITY = 1;const DEFAULT_ROTATION = 0;@@ -87,7 +96,7 @@ function isPrimaryPointerButton(e: PointerEvent) {}/**- * A gradient paint: its stops, its rotation, and which of the two gradient+ * A gradient paint: its stops, its angle, and which of the two gradient* elements it is. Every stop is a `<colorStop offset color opacity>` of its* own, so adding, moving and deleting one are element edits; the values shown* are `Computed`, which the motion system writes.@@ -105,8 +114,27 @@ export function GradientFillPicker(props: GradientPickerProps) {const stops = useDerived(() => readGradientStops(world, props.fill), sameGradientStops);+ createEffect(() => {+ const { node, fill } = props;+ beginGradientTool(world, node, fill);+ onCleanup(() => endGradientTool(world, fill));+ });+const paint = useTrait(() => props.fill, Paint);- const rotation = useDerived(() => props.fill.get(Computed)?.rotation ?? DEFAULT_ROTATION);+ const isLinear = () => paint()?.value === PaintType.LINEAR_GRADIENT;++ const rotation = useDerived(() => {+ const computed = props.fill.get(Computed);+ if (!computed) {+ return DEFAULT_ROTATION;+ }+ if (!isLinear()) {+ return computed.rotation;+ }+ const { gradientX1: x1, gradientY1: y1, gradientX2: x2, gradientY2: y2 } = computed;+ const angle = (Math.atan2(y2 - y1, x2 - x1) * 180) / Math.PI;+ return Math.round((((angle % 360) + 360) % 360) * 100) / 100;+ });const editOffset = (stop: Entity, offset: number) => {editor.editProperty(stop, "offset", offset);@@ -286,10 +314,34 @@ export function GradientFillPicker(props: GradientPickerProps) {const editRotation = (value: number) => {const next = ((value % 360) + 360) % 360;+ if (isLinear()) {+ pointLine(next);+ return;+ }editor.editProperty(props.fill, "rotation", next === DEFAULT_ROTATION ? false : next);syncKeyframe(world, editor, props.fill, "rotation", next);};+ /** Turns a linear gradient's line to `degrees` about its midpoint, keeping its length. */+ const pointLine = (degrees: number) => {+ const computed = props.fill.get(Computed);+ if (!computed) return;+ const { gradientX1: x1, gradientY1: y1, gradientX2: x2, gradientY2: y2 } = computed;+ const half = Math.hypot(x2 - x1, y2 - y1) / 2;+ const angle = (degrees * Math.PI) / 180;+ const dx = Math.cos(angle) * half;+ const dy = Math.sin(angle) * half;+ const mx = (x1 + x2) / 2;+ const my = (y1 + y2) / 2;++ const points = { x1: mx - dx, y1: my - dy, x2: mx + dx, y2: my + dy };+ for (const name of ["x1", "y1", "x2", "y2"] as const) {+ const value = Math.round(points[name] * 10000) / 10000;+ editor.editProperty(props.fill, name, value === LINEAR_GRADIENT_DEFAULTS[name] ? false : value);+ syncKeyframe(world, editor, props.fill, name, value);+ }+ };+const rotateGradient = () => editRotation(rotation() + 90);const flipGradient = () => {@@ -300,16 +352,19 @@ export function GradientFillPicker(props: GradientPickerProps) {const handleGradientStyleChange = (style: GradientStyleOption | null) => {if (style === null) return;- props.onChangeKind(style === "Radial");+ props.onChangeKind(GRADIENT_STYLES[style]);};const handleRotationChange = (value: number) => {editRotation(Math.round(value * 100) / 100);};- const gradientLabel = createMemo(() =>- paint()?.value === PaintType.RADIAL_GRADIENT ? "Radial" : "Linear",- );+ const gradientLabel = createMemo((): GradientStyleOption => {+ const value = paint()?.value;+ if (value === PaintType.RADIAL_GRADIENT) return "Radial";+ if (value === PaintType.ANGULAR_GRADIENT) return "Angular";+ return "Linear";+ });const gradientBackground = createMemo(() => {const parts = stops().map((s) => {@@ -385,7 +440,7 @@ export function GradientFillPicker(props: GradientPickerProps) {<ContextMenu modal={false}><ContextMenuTriggeras="div"- class="h-7 w-full touch-none rounded-md border border-border-input"+ class="h-7 w-full touch-none rounded-md border border-border-input bg-origin-border"style={{ "background-image": gradientBackground() }}onPointerDown={beginInsertAndDragStop}/>diff --git a/apps/web/src/components/timeline/layers/keyframe.tsx b/apps/web/src/components/timeline/layers/keyframe.tsxindex ac5f43c1..aee6e4e1 100644--- a/apps/web/src/components/timeline/layers/keyframe.tsx+++ b/apps/web/src/components/timeline/layers/keyframe.tsx@@ -175,6 +175,14 @@ const PROPERTY_NAMES: Partial<Record<PropertyPath, string>> = {'mixedVertexRadius.bottomRight': 'Radius BR','mixedVertexRadius.bottomLeft': 'Radius BL','stop.offset': 'Offset',+ 'gradient.x1': 'Start X',+ 'gradient.y1': 'Start Y',+ 'gradient.x2': 'End X',+ 'gradient.y2': 'End Y',+ 'gradient.cx': 'Center X',+ 'gradient.cy': 'Center Y',+ 'gradient.rx': 'Radius X',+ 'gradient.ry': 'Radius Y','effect.value': 'Value','chars': 'Text',};diff --git a/apps/web/src/components/timeline/layers/sub-item.tsx b/apps/web/src/components/timeline/layers/sub-item.tsxindex 403a1f9b..027b6b6d 100644--- a/apps/web/src/components/timeline/layers/sub-item.tsx+++ b/apps/web/src/components/timeline/layers/sub-item.tsx@@ -29,6 +29,7 @@ import type { LayerRowProps } from './layer';const PAINT_NAMES: Partial<Record<PaintType, string>> = {[PaintType.LINEAR_GRADIENT]: 'Gradient',[PaintType.RADIAL_GRADIENT]: 'Gradient',+ [PaintType.ANGULAR_GRADIENT]: 'Gradient',[PaintType.SOLID]: 'Solid',[PaintType.IMAGE]: 'Image',[PaintType.VIDEO]: 'Video',diff --git a/apps/web/src/components/ui/fill-item.tsx b/apps/web/src/components/ui/fill-item.tsxindex a8c9121b..f1bfe343 100644--- a/apps/web/src/components/ui/fill-item.tsx+++ b/apps/web/src/components/ui/fill-item.tsx@@ -393,7 +393,7 @@ function PaintItemIcon(props: PaintItemIconProps) {/></Show>- <Show when={type() === PaintType.LINEAR_GRADIENT || type() === PaintType.RADIAL_GRADIENT}>+ <Show when={type() === PaintType.LINEAR_GRADIENT || type() === PaintType.RADIAL_GRADIENT || type() === PaintType.ANGULAR_GRADIENT}><divclass="size-full"style={{ "background-image": getGradientBackground(stops(), type()) }}@@ -433,6 +433,8 @@ function FillLabel(props: FillLabelProps) {return "Linear";} else if (type() === PaintType.RADIAL_GRADIENT) {return "Radial";+ } else if (type() === PaintType.ANGULAR_GRADIENT) {+ return "Angular";} else if (type() === PaintType.HTML) {return "HTML";} else if (type() === PaintType.SURFACE) {@@ -464,5 +466,9 @@ function getGradientBackground(stops: GradientStop[], style: PaintType) {return `radial-gradient(circle, ${parts.join(", ")})`;}+ if (style === PaintType.ANGULAR_GRADIENT) {+ return `conic-gradient(from 90deg, ${parts.join(", ")})`;+ }+return `linear-gradient(90deg, ${parts.join(", ")})`;}diff --git a/apps/web/src/engine/create-engine.ts b/apps/web/src/engine/create-engine.tsindex 40c28b0a..c77e2aba 100644--- a/apps/web/src/engine/create-engine.ts+++ b/apps/web/src/engine/create-engine.ts@@ -5,7 +5,7 @@import { assetSystem, renderSystem, transformSystem, playbackSystem, motionSystem, AudioEngine, createRuntimeWorld, Geometry, Mode, RenderSurface, Time, ChildOf, syncInteractiveState } from '@diffusionstudio/runtime';import { hudSystem } from './hud';import { createSignal, type Accessor, type Setter } from 'solid-js';-import { AssetSelection, Hud, Keys, MODIFIER_KEYS, ObjectMaskTool, Pointer, PointerEvents, ProjectConfig, SnapLines } from './traits';+import { AssetSelection, GradientTool, Hud, Keys, MODIFIER_KEYS, ObjectMaskTool, Pointer, PointerEvents, ProjectConfig, SnapLines } from './traits';import { inputSystem } from './input/input-system';import { clearClipFrames, clearClipPeaks, clearMedia, clearPeaks, timelineSystem, TimelineSurface } from './timeline';import { clearObjectTrackOf, clearObjectTracks } from './object-mask';@@ -49,7 +49,7 @@ class Engine {public constructor(projectId: string, options: EngineOptions = {}) {this.world = createRuntimeWorld(projectId);- this.world.add(Pointer, Keys, SnapLines, Hud, ObjectMaskTool, PointerEvents, AssetSelection, ProjectConfig, TimelineSurface);+ this.world.add(Pointer, Keys, SnapLines, Hud, ObjectMaskTool, GradientTool, PointerEvents, AssetSelection, ProjectConfig, TimelineSurface);this.unsubscribe.push(this.world.onAdd(ChildOf('*'), () => (this.interactiveDirty = true)),diff --git a/apps/web/src/engine/gradient-tool.ts b/apps/web/src/engine/gradient-tool.tsnew file mode 100644index 00000000..bd122f25--- /dev/null+++ b/apps/web/src/engine/gradient-tool.ts@@ -0,0 +1,255 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import {+ Computed,+ Culled,+ Hidden,+ HitRegions,+ LINEAR_GRADIENT_DEFAULTS,+ Paint,+ PaintType,+ ELLIPTICAL_GRADIENT_DEFAULTS,+ Tool,+ ToolType,+ entityWorldMat,+ getLinearGradientLine,+ getGradientEllipse,+ getGradientEllipseMatrix,+ invert2D,+ multiply2D,+ store,+ transformPoint,+} from '@diffusionstudio/runtime';++import { getDocumentEditor } from './editor';+import { syncKeyframe } from './keyframes';+import { GradientTool } from './traits';++import type { Entity, World } from 'koota';+import type { AnimatableProperty } from '@diffusionstudio/jsx';+import type { DispatchedPointerEvent, Mat2D, Point } from '@diffusionstudio/runtime';++type Ctx2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;++const ACCENT = '#008CFF';+const HALO = 'rgba(0, 0, 0, 0.35)';+const LINE_WIDTH = 1.5;+const LINE_HALO = 3.5;+const HANDLE_RADIUS = 5;+/** The square around a handle that takes the press, CSS px a side. */+const HANDLE_HIT = 16;++export type GradientHandle = 'start' | 'end' | 'center' | 'rx' | 'ry';++type GradientTarget = { node: Entity; paint: Entity };++/**+ * Picks the tool for `paint`'s kind of gradient, aimed at it: the HUD puts+ * its handles on `node`. The inspector does this while the paint's gradient+ * picker is open.+ */+export function beginGradientTool(world: World, node: Entity, paint: Entity): void {+ const tool = toolFor(paint);+ if (tool === null) return;+ world.set(GradientTool, { node, paint, held: null });+ world.set(Tool, { value: tool });+}++/** Puts the tool down if it is aimed at `paint`; another paint's tool stays up. */+export function endGradientTool(world: World, paint: Entity): void {+ if (world.get(GradientTool)?.paint !== paint) return;+ world.set(GradientTool, { node: null, paint: null, held: null });+ if (isGradientTool(world)) world.set(Tool, { value: ToolType.MOVE });+}++export function isGradientTool(world: World): boolean {+ const tool = world.get(Tool)?.value;+ return tool === ToolType.LINEAR_GRADIENT || tool === ToolType.RADIAL_GRADIENT || tool === ToolType.ANGULAR_GRADIENT;+}++function toolFor(paint: Entity): ToolType | null {+ const type = paint.get(Paint)?.value;+ if (type === PaintType.LINEAR_GRADIENT) return ToolType.LINEAR_GRADIENT;+ if (type === PaintType.RADIAL_GRADIENT) return ToolType.RADIAL_GRADIENT;+ if (type === PaintType.ANGULAR_GRADIENT) return ToolType.ANGULAR_GRADIENT;+ return null;+}++/** The target while the tool for its kind is up and both it and its node can be drawn on. */+function activeTarget(world: World): GradientTarget | null {+ const { node, paint } = world.get(GradientTool) ?? {};+ if (!node?.isAlive() || !paint?.isAlive()) return null;+ if (world.get(Tool)?.value !== toolFor(paint)) return null;+ if (node.has(Culled) || node.has(Hidden)) return null;+ return { node, paint };+}++/**+ * The gradient's handles on its node while the tool is up: a linear one's+ * line with a handle at each end, a radial or angular one's ellipse with a+ * handle at the center and at the end of each radius. Each handle pushes the+ * region that takes its drag.+ */+export function drawGradientTool(world: World, ctx: Ctx2D, resolution: number): void {+ const target = activeTarget(world);+ if (!target) return;++ const computed = store(world, Computed);+ const nid = target.node.id();+ const w = computed.width[nid]!;+ const h = computed.height[nid]!;+ if (!w || !h) return;++ const mat = entityWorldMat(world, target.node);+ const toDevice = (point: Point): Point => transformPoint(mat, point.x, point.y);++ ctx.save();+ ctx.resetTransform();++ let handles: [GradientHandle, Point][];+ if (world.get(Tool)?.value === ToolType.LINEAR_GRADIENT) {+ const line = getLinearGradientLine(world, target.paint, w, h);+ const start = toDevice(line.start);+ const end = toDevice(line.end);++ ctx.beginPath();+ ctx.moveTo(start.x, start.y);+ ctx.lineTo(end.x, end.y);+ strokeGuide(ctx, resolution);++ handles = [['start', start], ['end', end]];+ } else {+ const ellipse = getGradientEllipse(world, target.paint, w, h);+ const center = toDevice(ellipse.center);+ const rxEnd = toDevice(ellipse.rxEnd);+ const ryEnd = toDevice(ellipse.ryEnd);++ // The unit circle placed by the paint's matrix, then stroked at the+ // identity so the line keeps its width.+ const placed: Mat2D = multiply2D(mat, getGradientEllipseMatrix(world, target.paint, w, h));+ ctx.setTransform(placed.a, placed.b, placed.c, placed.d, placed.e, placed.f);+ ctx.beginPath();+ ctx.arc(0, 0, 1, 0, Math.PI * 2);+ ctx.resetTransform();+ ctx.moveTo(center.x, center.y);+ ctx.lineTo(rxEnd.x, rxEnd.y);+ ctx.moveTo(center.x, center.y);+ ctx.lineTo(ryEnd.x, ryEnd.y);+ strokeGuide(ctx, resolution);++ handles = [['center', center], ['rx', rxEnd], ['ry', ryEnd]];+ }++ const regions = world.get(HitRegions)!.list;+ const radius = HANDLE_RADIUS * resolution;+ const hit = HANDLE_HIT * resolution;++ ctx.beginPath();+ for (const [handle, point] of handles) {+ ctx.moveTo(point.x + radius, point.y);+ ctx.arc(point.x, point.y, radius, 0, Math.PI * 2);++ const x = point.x - hit / 2;+ const y = point.y - hit / 2;+ regions.push({+ target: {+ kind: 'hud',+ id: handle,+ entity: target.paint,+ quad: [{ x, y }, { x: x + hit, y }, { x: x + hit, y: y + hit }, { x, y: y + hit }],+ },+ callback: handleGradientInteraction,+ });+ }+ ctx.fillStyle = '#FFFFFF';+ ctx.fill();+ ctx.strokeStyle = ACCENT;+ ctx.lineWidth = LINE_WIDTH * resolution;+ ctx.stroke();++ ctx.restore();+}++/** Strokes the current path as an accent line over a dark halo, legible on any paint. */+function strokeGuide(ctx: Ctx2D, resolution: number): void {+ ctx.strokeStyle = HALO;+ ctx.lineWidth = LINE_HALO * resolution;+ ctx.stroke();+ ctx.strokeStyle = ACCENT;+ ctx.lineWidth = LINE_WIDTH * resolution;+ ctx.stroke();+}++/**+ * Dragging a handle: a linear gradient's end goes where the pointer is; a+ * radial or angular one's center moves the ellipse, and a radius end sets+ * that radius and turns the ellipse with it, the other radius keeping its+ * length. An angular one's sweep starts at the x radius, so dragging that+ * end turns where it starts.+ */+export function handleGradientInteraction(world: World, event: DispatchedPointerEvent): void {+ if (event.target.kind !== 'hud') return;++ if (event.type === 'dragstart') {+ world.set(GradientTool, { held: event.target.id as GradientHandle });+ return;+ }+ if (event.type === 'dragend') {+ world.set(GradientTool, { held: null });+ return;+ }+ const held = world.get(GradientTool)?.held;+ if (event.type !== 'drag' || !held) return;++ const target = activeTarget(world);+ if (!target) return;++ const computed = store(world, Computed);+ const nid = target.node.id();+ const pid = target.paint.id();+ const w = computed.width[nid]!;+ const h = computed.height[nid]!;+ if (!w || !h) return;++ // The pointer as fractions of the node's box, the space the props are in.+ const local = transformPoint(invert2D(entityWorldMat(world, target.node)), event.clientX, event.clientY);+ const u = local.x / w;+ const v = local.y / h;++ const editor = getDocumentEditor(world);+ const write = (name: AnimatableProperty, value: number, fallback: number) => {+ editor.editProperty(target.paint, name, value === fallback ? false : value);+ syncKeyframe(world, editor, target.paint, name, value);+ };+ const fraction = (value: number) => Math.round(value * 10000) / 10000;++ switch (held) {+ case 'start':+ write('x1', fraction(u), LINEAR_GRADIENT_DEFAULTS.x1);+ write('y1', fraction(v), LINEAR_GRADIENT_DEFAULTS.y1);+ return;+ case 'end':+ write('x2', fraction(u), LINEAR_GRADIENT_DEFAULTS.x2);+ write('y2', fraction(v), LINEAR_GRADIENT_DEFAULTS.y2);+ return;+ case 'center':+ write('cx', fraction(u), ELLIPTICAL_GRADIENT_DEFAULTS.cx);+ write('cy', fraction(v), ELLIPTICAL_GRADIENT_DEFAULTS.cy);+ return;+ case 'rx':+ case 'ry': {+ const dx = u - computed.gradientCX[pid]!;+ const dy = v - computed.gradientCY[pid]!;+ // The y radius points a quarter turn on from the x radius.+ const angle = (Math.atan2(dy, dx) * 180) / Math.PI - (held === 'ry' ? 90 : 0);+ const current = computed.rotation[pid]!;+ const rotation = Math.round((angle + Math.round((current - angle) / 360) * 360) * 100) / 100;++ write(held, fraction(Math.hypot(dx, dy)), ELLIPTICAL_GRADIENT_DEFAULTS[held]);+ write('rotation', rotation, 0);+ return;+ }+ }+}diff --git a/apps/web/src/engine/hud/hud-system.ts b/apps/web/src/engine/hud/hud-system.tsindex 7d035571..5f8f11e1 100644--- a/apps/web/src/engine/hud/hud-system.ts+++ b/apps/web/src/engine/hud/hud-system.ts@@ -21,6 +21,7 @@ import {import { getMarqueeQuad } from '../input/snapping';import { getMountedNameInput } from './name-input';import { drawObjectMasks } from '../object-mask';+import { drawGradientTool, isGradientTool } from '../gradient-tool';import type { Entity, World } from 'koota';import type { Mat2D } from '@diffusionstudio/runtime';@@ -48,8 +49,9 @@ export function hudSystem(world: World): void {}// The mask is in the way of the thing it is around while that thing is- // being moved, so it steps aside for the gesture.- const mask = world.get(Hud)?.mode === 'moving' ? null : getSelectionMask(world);+ // being moved, so it steps aside for the gesture; its handles would sit+ // on a gradient's while that is being placed.+ const mask = world.get(Hud)?.mode === 'moving' || isGradientTool(world) ? null : getSelectionMask(world);if (mask) {drawSelectionMask(world, ctx, mask, resolution);@@ -58,6 +60,7 @@ export function hudSystem(world: World): void {drawMarquee(world, ctx, resolution);drawObjectMasks(world, ctx, resolution);+ drawGradientTool(world, ctx, resolution);}function drawSnapLines(world: World, ctx: Ctx2D, resolution: number): void {diff --git a/apps/web/src/engine/input/cursor.ts b/apps/web/src/engine/input/cursor.tsindex 6e7f42c5..27a4fe2c 100644--- a/apps/web/src/engine/input/cursor.ts+++ b/apps/web/src/engine/input/cursor.ts@@ -93,6 +93,9 @@ const TOOL_CURSORS: Record<ToolType, { idle: CursorType; pressed?: CursorType }>[ToolType.TEXT_EDIT]: { idle: 'text' },[ToolType.OBJECT_MASK]: { idle: 'crosshair' },[ToolType.CLIP_PATH]: { idle: 'default' },+ [ToolType.LINEAR_GRADIENT]: { idle: 'default' },+ [ToolType.RADIAL_GRADIENT]: { idle: 'default' },+ [ToolType.ANGULAR_GRADIENT]: { idle: 'default' },};/** The cursor the armed tool asks for, pressed or at rest. The object mask's brush draws its own ring, so it hides the cursor. */diff --git a/apps/web/src/engine/traits.ts b/apps/web/src/engine/traits.tsindex 7aec44a3..2849ef4a 100644--- a/apps/web/src/engine/traits.ts+++ b/apps/web/src/engine/traits.ts@@ -12,6 +12,8 @@import { trait } from 'koota';import type { CanvasPointerEvent, Point } from '@diffusionstudio/runtime';+import type { Entity } from 'koota';+import type { GradientHandle } from './gradient-tool';import type { ObjectMaskMode, ObjectMaskOp } from './object-mask/store';import type { ProjectConfig as ProjectConfigStore } from './project-config';@@ -88,6 +90,17 @@ export const ObjectMaskTool = trait({brushShown: false,});+/**+ * What the gradient tools are aimed at: the paint whose handles the HUD+ * draws and the node whose box places it, both null while no gradient+ * picker is open, and the handle a press landed on, until its release.+ */+export const GradientTool = trait({+ node: null as Entity | null,+ paint: null as Entity | null,+ held: null as GradientHandle | null,+});+/*** Queue of pointer events to be processed by the input system.*/diff --git a/docs/reference/jsx/elements.md b/docs/reference/jsx/elements.mdindex 2996151d..e221e5aa 100644--- a/docs/reference/jsx/elements.md+++ b/docs/reference/jsx/elements.md@@ -33,7 +33,7 @@ Children of a node, stacked in document order over its intrinsic fill. See [pain| Element | What it is || ------- | ---------- || `<solidPaint>` | A solid color; what the `fill` prop is shorthand for. |-| `<linearGradientPaint>` / `<radialGradientPaint>` | A gradient; takes `<colorStop>` children. |+| `<linearGradientPaint>` / `<radialGradientPaint>` / `<angularGradientPaint>` | A gradient; takes `<colorStop>` children. || `<colorStop>` | One gradient stop. Valid only inside a gradient paint. || `<imagePaint>` / `<videoPaint>` | Media painted into another element's box — a rect or a text filled with a picture. || [`<htmlPaint>`](./html.md) | The paint form of `<html>`. |diff --git a/docs/reference/jsx/paints.md b/docs/reference/jsx/paints.mdindex d0aadcf4..9d5013c3 100644--- a/docs/reference/jsx/paints.md+++ b/docs/reference/jsx/paints.md@@ -4,7 +4,7 @@ Internally a node's fill is not a property but a **paint child**: a sub-entity a```tsx<rect width={640} height={360} cornerRadius={24}>- <linearGradientPaint rotation={90}>+ <linearGradientPaint x1={0.5} y1={0} x2={0.5} y2={1}><colorStop offset={0} color="#FF0055" /><colorStop offset={1} color="#0055FF" /></linearGradientPaint>@@ -16,8 +16,9 @@ Paint elements are valid inside any filled visual element (`<rect>`, `<text>`, `| Element | Props | Meaning || ------- | ----- | ------- || `<solidPaint>` | `color` (**required**), `opacity` | Solid fill; equivalent to the `fill` prop. |-| `<linearGradientPaint>` | `rotation`, `opacity` | Linear gradient across the parent's box; `rotation` in degrees, `0` = left to right. |-| `<radialGradientPaint>` | `rotation`, `opacity` | Radial gradient centered in the parent's box. |+| `<linearGradientPaint>` | `x1`, `y1`, `x2`, `y2`, `opacity` | Linear gradient along a line in the parent's box — see below. |+| `<radialGradientPaint>` | `cx`, `cy`, `rx`, `ry`, `rotation`, `opacity` | Radial gradient out to an ellipse in the parent's box — see below. |+| `<angularGradientPaint>` | `cx`, `cy`, `rx`, `ry`, `rotation`, `opacity` | Angular (conic) gradient sweeping around a center in the parent's box — see below. || `<colorStop>` | `offset` (**required**, `0`–`1`), `color` (**required**), `opacity` | Gradient color stop. Valid only inside gradient paints, which take no other children. || `<imagePaint>` / `<videoPaint>` | `src` (**required**), `objectFit`, `frameRate`, `opacity` | Media painted into the parent's box — see below. || [`<htmlPaint>`](./html.md) | `opacity`, HTML children | Reactive HTML laid out and drawn into the parent's box (flagged Chromium API). `<html>` is shorthand for a `<rect>` carrying one. |@@ -26,7 +27,63 @@ Paint elements are valid inside any filled visual element (`<rect>`, `<text>`, `Every paint also takes `blendMode` and `hidden`, which mean on a paint what they mean on a node.-Colors accept any CSS color; alpha is ignored (use `opacity`). `color`, `opacity`, and `offset` are animatable with `<keyframeTrack>` children (see [keyframes.md](./keyframes.md)), so gradients can animate. Paints have no spatial or timing props of their own and cannot be roots.+Colors accept any CSS color; alpha is ignored (use `opacity`). `color`, `opacity`, `offset`, and a gradient's placement props are animatable with `<keyframeTrack>` children (see [keyframes.md](./keyframes.md)), so gradients can animate. Paints have no timing props of their own and cannot be roots.++## Placing a gradient++Gradients are placed the way SVG places them by default (`gradientUnits="objectBoundingBox"`): in fractions of the parent's box, not px. `0`–`1` spans the box's width horizontally and its height vertically, so a gradient keeps its place when the box is resized. Values outside `0`–`1` reach past the edges.++A `<linearGradientPaint>` draws stop `0` at (`x1`, `y1`) and stop `1` at (`x2`, `y2`), SVG's names:++| Prop | Default | Meaning |+| ---- | ------- | ------- |+| `x1`, `y1` | `0`, `0.5` | Start of the line. |+| `x2`, `y2` | `1`, `0.5` | End of the line. |++Unplaced, the line runs across the middle of the box, left to right, edge to edge. A gradient from the top-left corner to the bottom-right one:++```tsx+<rect width={1920} height={1080}>+ <linearGradientPaint x1={0} y1={0} x2={1} y2={1}>+ <colorStop offset={0} color="#FF0055" />+ <colorStop offset={1} color="#0055FF" />+ </linearGradientPaint>+</rect>+```++A `<radialGradientPaint>` draws stop `0` at its center and stop `1` on an ellipse around it: SVG's `cx`/`cy`, with the `rx`/`ry` of SVG's `<ellipse>`:++| Prop | Default | Meaning |+| ---- | ------- | ------- |+| `cx`, `cy` | `0.5` | Center. |+| `rx`, `ry` | `0.5` | Radii; `rx` is a fraction of the box's width, `ry` of its height. |+| `rotation` | `0` | Turns the radii, degrees clockwise. |++Unplaced, the ellipse is centered and touches the middle of each edge, so it is a circle only on a square box. A glow in the top-left quarter of the box:++```tsx+<rect width={1920} height={1080}>+ <radialGradientPaint cx={0.25} cy={0.25} rx={0.25} ry={0.25}>+ <colorStop offset={0} color="#FFFFFF" />+ <colorStop offset={1} color="#000000" />+ </radialGradientPaint>+</rect>+```++Keyframing the points moves each one in a straight line, so a linear gradient turned by keyframes shortens on the way (a half turn collapses at its midpoint); key a quarter turn at a time to keep its length. A radial gradient's `rotation` turns along an arc.++An `<angularGradientPaint>` sweeps its stops once around a center, like Figma's angular gradient or CSS's `conic-gradient`: stop `0` starts along the `rx` radius (to the right of the center when unrotated) and the sweep turns clockwise through `ry` back to the start. It takes the radial gradient's props with the same defaults; `rotation` turns where the sweep starts, and the radii shape it: on a stretched ellipse the stops spread out across its short ends and crowd toward its long ends. A color wheel:++```tsx+<rect width={1080} height={1080}>+ <angularGradientPaint>+ <colorStop offset={0} color="#FF0000" />+ <colorStop offset={0.33} color="#00FF00" />+ <colorStop offset={0.67} color="#0000FF" />+ <colorStop offset={1} color="#FF0000" />+ </angularGradientPaint>+</rect>+```## Media paintsdiff --git a/packages/jsx/src/index.ts b/packages/jsx/src/index.tsindex a0ec6f0c..4f6bc173 100644--- a/packages/jsx/src/index.ts+++ b/packages/jsx/src/index.ts@@ -45,6 +45,9 @@ export type {EffectType,Fit,GradientPaintProps,+ LinearGradientPaintProps,+ RadialGradientPaintProps,+ AngularGradientPaintProps,GroupProps,HorizontalConstraint,HtmlPaintProps,diff --git a/packages/jsx/src/jsx-runtime.ts b/packages/jsx/src/jsx-runtime.tsindex 358be176..d5d8fe54 100644--- a/packages/jsx/src/jsx-runtime.ts+++ b/packages/jsx/src/jsx-runtime.ts@@ -27,7 +27,9 @@ import type {ColorStopProps,EffectProps,MaskProps,- GradientPaintProps,+ LinearGradientPaintProps,+ RadialGradientPaintProps,+ AngularGradientPaintProps,MediaPaintProps,GroupProps,HtmlPaintProps,@@ -90,8 +92,9 @@ export declare namespace JSX {captions: CaptionsProps & SourceProps;adjustmentLayer: AdjustmentLayerProps & SourceProps;solidPaint: SolidPaintProps & SourceProps;- linearGradientPaint: GradientPaintProps & SourceProps;- radialGradientPaint: GradientPaintProps & SourceProps;+ linearGradientPaint: LinearGradientPaintProps & SourceProps;+ radialGradientPaint: RadialGradientPaintProps & SourceProps;+ angularGradientPaint: AngularGradientPaintProps & SourceProps;imagePaint: MediaPaintProps & SourceProps;videoPaint: MediaPaintProps & SourceProps;colorStop: ColorStopProps & SourceProps;diff --git a/packages/jsx/src/source.ts b/packages/jsx/src/source.tsindex c9ccce5a..0a4c6b84 100644--- a/packages/jsx/src/source.ts+++ b/packages/jsx/src/source.ts@@ -104,6 +104,7 @@ export const COMPOSITION_TAGS = ["solidPaint","linearGradientPaint","radialGradientPaint",+ "angularGradientPaint","imagePaint","videoPaint","colorStop",diff --git a/packages/jsx/src/types.ts b/packages/jsx/src/types.tsindex 14f7347f..5bcafe70 100644--- a/packages/jsx/src/types.ts+++ b/packages/jsx/src/types.ts@@ -118,6 +118,14 @@ export type AnimatableProperty =| "volume"| "color"| "offset"+ | "x1"+ | "y1"+ | "x2"+ | "y2"+ | "cx"+ | "cy"+ | "rx"+ | "ry"| "blur"| "value";@@ -556,7 +564,7 @@ export type RectProps = CommonProps & FillProps & {mask?: boolean;/*** Paint children (`<SolidPaint>`, `<LinearGradientPaint>`,- * `<RadialGradientPaint>`), plus `<Stroke>`, `<Shadow>`, `<Effect>`,+ * `<RadialGradientPaint>`, `<AngularGradientPaint>`), plus `<Stroke>`, `<Shadow>`, `<Effect>`,* `<Animation>` and `<KeyframeTrack>` children.*/children?: SolidJSX.Element;@@ -690,12 +698,69 @@ export type KeyframeProps = {export type SolidPaintProps = ColorProps & PaintProps & TrackChildren;export type GradientPaintProps = PaintProps & {- /** Gradient rotation in degrees. Defaults to 0 (left to right). */- rotation?: number;/** `<ColorStop>` children — the gradient's color stops. */children?: SolidJSX.Element;};+/**+ * `<linearGradientPaint>` — a gradient along a line in the parent's box, from+ * stop 0 at (`x1`, `y1`) to stop 1 at (`x2`, `y2`). As in SVG's default+ * `objectBoundingBox` units, the points are fractions of the box, not px:+ * 0–1 spans its width horizontally and its height vertically. Unplaced, the+ * line runs across the middle of the box, left to right, edge to edge.+ */+export type LinearGradientPaintProps = GradientPaintProps & {+ /** Start of the line, as a fraction of the box width. Default 0. */+ x1?: number;+ /** Start of the line, as a fraction of the box height. Default 0.5. */+ y1?: number;+ /** End of the line, as a fraction of the box width. Default 1. */+ x2?: number;+ /** End of the line, as a fraction of the box height. Default 0.5. */+ y2?: number;+};++/**+ * `<radialGradientPaint>` — a gradient from stop 0 at a center out to stop 1+ * on an ellipse in the parent's box: SVG's `cx`/`cy` plus the `rx`/`ry` of+ * `<ellipse>`, as fractions of the box (0–1 spans its width horizontally and+ * its height vertically). Unplaced, the ellipse is centered and touches the+ * middle of each edge of the box.+ */+export type RadialGradientPaintProps = GradientPaintProps & {+ /** Center, as a fraction of the box width. Default 0.5. */+ cx?: number;+ /** Center, as a fraction of the box height. Default 0.5. */+ cy?: number;+ /** Radius along the ellipse's first axis, as a fraction of the box width. Default 0.5. */+ rx?: number;+ /** Radius along the ellipse's second axis, as a fraction of the box height. Default 0.5. */+ ry?: number;+ /** Turns the radii, degrees clockwise. Default 0. */+ rotation?: number;+};++/**+ * `<angularGradientPaint>` — a gradient that sweeps its stops once around a+ * center, like Figma's angular gradient and CSS `conic-gradient`: stop 0+ * along the ellipse's first radius, turning clockwise through the second.+ * Placed like `<radialGradientPaint>`, by the same props in fractions of the+ * box; the ellipse's shape spreads the sweep, so on a stretched one the+ * stops crowd toward its long ends.+ */+export type AngularGradientPaintProps = GradientPaintProps & {+ /** Center, as a fraction of the box width. Default 0.5. */+ cx?: number;+ /** Center, as a fraction of the box height. Default 0.5. */+ cy?: number;+ /** Radius along the ellipse's first axis, where the sweep starts, as a fraction of the box width. Default 0.5. */+ rx?: number;+ /** Radius along the ellipse's second axis, as a fraction of the box height. Default 0.5. */+ ry?: number;+ /** Turns the radii, and with them where the sweep starts, degrees clockwise. Default 0 (stop 0 to the right of the center). */+ rotation?: number;+};+export type ColorStopProps = ColorProps & OpacityProps & TrackChildren & {/** Position along the gradient, 0–1. */offset: number;diff --git a/packages/reconciler/src/document.ts b/packages/reconciler/src/document.tsindex 50da72d8..8f3e3e06 100644--- a/packages/reconciler/src/document.ts+++ b/packages/reconciler/src/document.ts@@ -3,7 +3,7 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-import { Active, AdjustmentLayer, Animation, AnimationPhase, AnimationType, appendChild, AssetId, Audio, Background, bindAsset, BlendMode, BlendModeType, Blur, Caption, CaptionAlign, CAPTION_PRESET_FILLS, CAPTION_PRESET_STYLES, CaptionType, Chars, ClipHeight, ClipsContent, Computed, Constraint, ConstraintCache, ConstraintType, CornerRadius, createEntity, DEFAULT_BACKGROUND, Color, ColorStop, Delay, Effect, EffectType, Expanded, FontStyle, FramePromises, FrameRate, getActiveEntity, Loop, LoadRequest, Mask, Geometry, GeometryType, getEntityTree, getParentEntity, getParentNode, Hidden, Host, IsClipPath, isText, ItemIndex, KeepAspectRatio, Keyframe, KeyframeTrack, MixedCornerRadius, Mode, Muted, Name, Offset, Opacity, Paint, PaintType, parseColor, PendingSource, PendingSync, Playback, PlaybackRate, Position, removeChild, RenderSurface, resizeEntity, Scale, ScaleMode, ScaleModeType, secondsToFrames, getAsset, getEntityChildren, Group, Sequential, Shader, Size, Stage, Root, Rotation, Scene, Selected, Shadow, Source, SourceFrameRate, setCameraMatrix, setPlayhead, setTimelineView, Stroke, StrokeCap, StrokeJoin, StrokeStyle, SyncRequest, TextAlign, TextBaseline, TextCase, TextRange, TextStyle, Transition, TransitionType, Trim, UniformScale, Volume, Workarea } from '@diffusionstudio/runtime';+import { Active, AdjustmentLayer, Animation, AnimationPhase, AnimationType, appendChild, AssetId, Audio, Background, bindAsset, BlendMode, BlendModeType, Blur, Caption, CaptionAlign, CAPTION_PRESET_FILLS, CAPTION_PRESET_STYLES, CaptionType, Chars, ClipHeight, ClipsContent, Computed, Constraint, ConstraintCache, ConstraintType, CornerRadius, createEntity, DEFAULT_BACKGROUND, Color, ColorStop, Delay, Effect, EffectType, Expanded, FontStyle, FramePromises, FrameRate, getActiveEntity, Loop, LoadRequest, Mask, Geometry, GeometryType, getEntityTree, getParentEntity, getParentNode, Hidden, Host, IsClipPath, isText, ItemIndex, KeepAspectRatio, Keyframe, KeyframeTrack, LINEAR_GRADIENT_DEFAULTS, LinearGradient, MixedCornerRadius, Mode, Muted, Name, Offset, Opacity, Paint, PaintType, parseColor, PendingSource, PendingSync, Playback, PlaybackRate, Position, ELLIPTICAL_GRADIENT_DEFAULTS, EllipticalGradient, removeChild, RenderSurface, resizeEntity, Scale, ScaleMode, ScaleModeType, secondsToFrames, getAsset, getEntityChildren, Group, Sequential, Shader, Size, Stage, Root, Rotation, Scene, Selected, Shadow, Source, SourceFrameRate, setCameraMatrix, setPlayhead, setTimelineView, Stroke, StrokeCap, StrokeJoin, StrokeStyle, SyncRequest, TextAlign, TextBaseline, TextCase, TextRange, TextStyle, Transition, TransitionType, Trim, UniformScale, Volume, Workarea } from '@diffusionstudio/runtime';import { DEFAULT_MASK_SMOOTHING } from '@diffusionstudio/assets';import { LOOP_ATTR, parseTime, SOURCE_ATTR } from '@diffusionstudio/jsx';import { createSignal } from 'solid-js';@@ -116,6 +116,7 @@ const PAINT_TYPES: Record<string, PaintType> = {solidPaint: PaintType.SOLID,linearGradientPaint: PaintType.LINEAR_GRADIENT,radialGradientPaint: PaintType.RADIAL_GRADIENT,+ angularGradientPaint: PaintType.ANGULAR_GRADIENT,shaderPaint: PaintType.SHADER,surfacePaint: PaintType.SURFACE,htmlPaint: PaintType.HTML,@@ -196,6 +197,14 @@ const TRACK_PROPERTIES: Record<string, PropertyPath> = {volume: 'volume',color: 'color',offset: 'stop.offset',+ x1: 'gradient.x1',+ y1: 'gradient.y1',+ x2: 'gradient.x2',+ y2: 'gradient.y2',+ cx: 'gradient.cx',+ cy: 'gradient.cy',+ rx: 'gradient.rx',+ ry: 'gradient.ry',blur: 'blur',value: 'effect.value',};@@ -579,6 +588,7 @@ export class RuntimeDocument implements ProjectDocument<SceneNode> {case 'solidPaint':case 'linearGradientPaint':case 'radialGradientPaint':+ case 'angularGradientPaint':case 'shaderPaint':case 'surfacePaint':case 'htmlPaint':@@ -1282,6 +1292,25 @@ export class RuntimeDocument implements ProjectDocument<SceneNode> {}return;}+ case 'x1':+ case 'y1':+ case 'x2':+ case 'y2': {+ if (entity.get(Paint)?.value !== PaintType.LINEAR_GRADIENT) return;+ entity.add(LinearGradient);+ entity.set(LinearGradient, { [name]: toNumber(value) ?? LINEAR_GRADIENT_DEFAULTS[name as keyof typeof LINEAR_GRADIENT_DEFAULTS] });+ return;+ }+ case 'cx':+ case 'cy':+ case 'rx':+ case 'ry': {+ const paint = entity.get(Paint)?.value;+ if (paint !== PaintType.RADIAL_GRADIENT && paint !== PaintType.ANGULAR_GRADIENT) return;+ entity.add(EllipticalGradient);+ entity.set(EllipticalGradient, { [name]: toNumber(value) ?? ELLIPTICAL_GRADIENT_DEFAULTS[name as keyof typeof ELLIPTICAL_GRADIENT_DEFAULTS] });+ return;+ }case 'fontSize': {const size = toNumber(value);entity.add(TextStyle);diff --git a/packages/reconciler/src/elements.ts b/packages/reconciler/src/elements.tsindex c0bf150a..3c371c4c 100644--- a/packages/reconciler/src/elements.ts+++ b/packages/reconciler/src/elements.ts@@ -26,7 +26,9 @@ import type {ColorStopProps,EffectProps,MaskProps,- GradientPaintProps,+ LinearGradientPaintProps,+ RadialGradientPaintProps,+ AngularGradientPaintProps,GroupProps,HtmlPaintProps,HtmlProps,@@ -99,8 +101,9 @@ export const Sequence = hostElement<SequenceProps>("Sequence");export const Captions = hostElement<CaptionsProps>("Captions");export const AdjustmentLayer = hostElement<AdjustmentLayerProps>("AdjustmentLayer");export const SolidPaint = hostElement<SolidPaintProps>("SolidPaint");-export const LinearGradientPaint = hostElement<GradientPaintProps>("LinearGradientPaint");-export const RadialGradientPaint = hostElement<GradientPaintProps>("RadialGradientPaint");+export const LinearGradientPaint = hostElement<LinearGradientPaintProps>("LinearGradientPaint");+export const RadialGradientPaint = hostElement<RadialGradientPaintProps>("RadialGradientPaint");+export const AngularGradientPaint = hostElement<AngularGradientPaintProps>("AngularGradientPaint");export const ImagePaint = hostElement<MediaPaintProps>("ImagePaint");export const VideoPaint = hostElement<MediaPaintProps>("VideoPaint");export const ColorStop = hostElement<ColorStopProps>("ColorStop");diff --git a/packages/runtime/src/constants.ts b/packages/runtime/src/constants.tsindex a0959441..eef32c9e 100644--- a/packages/runtime/src/constants.ts+++ b/packages/runtime/src/constants.ts@@ -6,6 +6,9 @@ export const CONONICAL_TIME_BASE = 1e6;export const DEFAULT_DURATION_FRAMES = 16 * 30;+export const LINEAR_GRADIENT_DEFAULTS = { x1: 0, y1: 0.5, x2: 1, y2: 0.5 };+export const ELLIPTICAL_GRADIENT_DEFAULTS = { cx: 0.5, cy: 0.5, rx: 0.5, ry: 0.5 };+// Stage camera zoom limits (1 = 100%).export const MIN_CAMERA_ZOOM = 0.01;export const MAX_CAMERA_ZOOM = 10;@@ -77,6 +80,7 @@ export enum PaintType {HTML,SURFACE,SHADER,+ ANGULAR_GRADIENT,}export enum EffectType {@@ -178,4 +182,7 @@ export enum ToolType {TEXT_EDIT,OBJECT_MASK,CLIP_PATH,+ LINEAR_GRADIENT,+ RADIAL_GRADIENT,+ ANGULAR_GRADIENT,}diff --git a/packages/runtime/src/systems/gradients.ts b/packages/runtime/src/systems/gradients.tsindex d42f56ef..853374d1 100644--- a/packages/runtime/src/systems/gradients.ts+++ b/packages/runtime/src/systems/gradients.ts@@ -7,10 +7,11 @@// render system moves in).import { store } from '../world/store';-import { ChildOf, ColorStop, Position, Computed } from '../traits';+import { ChildOf, ColorStop, Computed } from '../traits';import { colorToCss } from '../utils/color';import type { Entity, World } from 'koota';+import type { Point } from '../math';type Ctx2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;@@ -32,6 +33,31 @@ function addStopsTo(world: World, fill: Entity, gradient: CanvasGradient): void}}+/** A linear gradient's line in its holder's box, px: stop 0 sits on `start`, stop 1 on `end`. */+export type GradientLine = { start: Point; end: Point };++/** The paint props that place a linear gradient: SVG's x1/y1/x2/y2, as fractions of the box. */+export type LinearGradientPlacement = { x1: number; y1: number; x2: number; y2: number };++/** Where a linear gradient paint draws its line in a `w` × `h` box, px from the box's top-left. */+export function getLinearGradientLine(world: World, paint: Entity, w: number, h: number): GradientLine {+ const computed = store(world, Computed);+ const pid = paint.id();++ return {+ start: { x: computed.gradientX1[pid]! * w, y: computed.gradientY1[pid]! * h },+ end: { x: computed.gradientX2[pid]! * w, y: computed.gradientY2[pid]! * h },+ };+}++/**+ * The paint props that draw a linear gradient from `start` to `end` in a+ * `w` × `h` box (px from its top-left): the inverse of `getLinearGradientLine`.+ */+export function linearGradientFromLine({ start, end }: GradientLine, w: number, h: number): LinearGradientPlacement {+ return { x1: start.x / w, y1: start.y / h, x2: end.x / w, y2: end.y / h };+}+/** Create a canvas linear gradient from a gradient paint sub-entity. */export function createLinearGradient(world: World,@@ -40,80 +66,234 @@ export function createLinearGradient(w: number,h: number,): CanvasGradient {+ const { start, end } = getLinearGradientLine(world, fill, w, h);+ const gradient = ctx.createLinearGradient(start.x, start.y, end.x, end.y);++ addStopsTo(world, fill, gradient);+ return gradient;+}++/** Fill the current path with a linear gradient paint. */+export function fillLinearGradient(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number): void {+ ctx.fillStyle = createLinearGradient(world, paint, ctx, w, h);+ ctx.fill();+}++/** Stroke the current path with a linear gradient paint, in the stroke style already set on `ctx`. */+export function strokeLinearGradient(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number): void {+ ctx.strokeStyle = createLinearGradient(world, paint, ctx, w, h);+ ctx.stroke();+}++/**+ * A radial or angular gradient's ellipse in its holder's box, px: the+ * gradient sits on `center`, and the ellipse runs through `rxEnd` and+ * `ryEnd`, the ends of its two radii. A radial gradient goes from stop 0 at+ * the center to stop 1 on the ellipse; an angular one sweeps its stops once+ * around the center, from the `rxEnd` side toward the `ryEnd` side.+ */+export type GradientEllipse = { center: Point; rxEnd: Point; ryEnd: Point };++/**+ * The paint props that place a radial or angular gradient: SVG's cx/cy plus+ * the rx/ry of `<ellipse>`, as fractions of the box, and the rotation of the+ * radii.+ */+export type EllipticalGradientPlacement = { cx: number; cy: number; rx: number; ry: number; rotation: number };++/**+ * The matrix that takes a radial or angular gradient paint's unit circle+ * onto its ellipse in a `w` × `h` box, px from the box's top-left.+ * cx/cy/rx/ry are fractions of the box and rotation turns the radii, so+ * rotated radii are perpendicular in the box's 0–1 space, as in SVG's+ * objectBoundingBox.+ */+export function getGradientEllipseMatrix(world: World, paint: Entity, w: number, h: number): DOMMatrix {const computed = store(world, Computed);- const fid = fill.id();-- // (px, py) is the gradient center in normalized shape-local space. Fills- // without a Position trait (the default for stock gradient fills) get- // (0.5, 0.5) so the gradient spans the shape. With Position present, the- // motion-system-sampled Computed values are used (keyframeable).- const hasPos = fill.has(Position);- const px = hasPos ? computed.positionX[fid]! : 0.5;- const py = hasPos ? computed.positionY[fid]! : 0.5;- const sx = computed.scaleX[fid]!;- const sy = computed.scaleY[fid]!;- const angle = (computed.rotation[fid]! * Math.PI) / 180;+ const pid = paint.id();++ const rx = computed.gradientRX[pid]!;+ const ry = computed.gradientRY[pid]!;+ const angle = (computed.rotation[pid]! * Math.PI) / 180;const cos = Math.cos(angle);const sin = Math.sin(angle);- // Transform normalized start (0, 0.5) and end (1, 0.5) points- const startLocalX = (0 - 0.5) * sx;- const startLocalY = (0.5 - 0.5) * sy;- const x0 = (px + startLocalX * cos - startLocalY * sin) * w;- const y0 = (py + startLocalX * sin + startLocalY * cos) * h;+ return new DOMMatrix([+ cos * rx * w, sin * rx * h,+ -sin * ry * w, cos * ry * h,+ computed.gradientCX[pid]! * w, computed.gradientCY[pid]! * h,+ ]);+}- const endLocalX = (1 - 0.5) * sx;- const endLocalY = (0.5 - 0.5) * sy;- const x1 = (px + endLocalX * cos - endLocalY * sin) * w;- const y1 = (py + endLocalX * sin + endLocalY * cos) * h;+/** Where a radial or angular gradient paint draws its ellipse in a `w` × `h` box — see `getGradientEllipseMatrix`. */+export function getGradientEllipse(world: World, paint: Entity, w: number, h: number): GradientEllipse {+ const { a, b, c, d, e, f } = getGradientEllipseMatrix(world, paint, w, h);+ return {+ center: { x: e, y: f },+ rxEnd: { x: e + a, y: f + b },+ ryEnd: { x: e + c, y: f + d },+ };+}++/**+ * The paint props that place a radial or angular gradient on an ellipse in a+ * `w` × `h` box (px from its top-left): the inverse of `getGradientEllipse`.+ * The radii are perpendicular in the box's 0–1 space, so `ryEnd` only counts+ * for its distance from the line through `center` and `rxEnd`. Of the equal+ * angles, rotation comes out as the one nearest `near` (the paint's current+ * rotation), so keyframes between two placements turn the short way.+ */+export function gradientFromEllipse(+ { center, rxEnd, ryEnd }: GradientEllipse,+ w: number,+ h: number,+ near = 0,+): EllipticalGradientPlacement {+ const ax = (rxEnd.x - center.x) / w;+ const ay = (rxEnd.y - center.y) / h;+ const bx = (ryEnd.x - center.x) / w;+ const by = (ryEnd.y - center.y) / h;+ const rx = Math.hypot(ax, ay);- const gradient = ctx.createLinearGradient(x0, y0, x1, y1);+ // With no x radius to measure from, the y radius alone sets the angle.+ const angle = rx > 0+ ? (Math.atan2(ay, ax) * 180) / Math.PI+ : (Math.atan2(by, bx) * 180) / Math.PI - 90;+ const ry = rx > 0+ ? Math.abs(ax * by - ay * bx) / rx+ : Math.hypot(bx, by);- addStopsTo(world, fill, gradient);+ return {+ cx: center.x / w,+ cy: center.y / h,+ rx,+ ry,+ rotation: nearestAngle(angle, near),+ };+}++/** A canvas gradient of a paint's stops in its unit circle's space, made on the context it will be drawn with. */+type UnitGradient = (world: World, paint: Entity, ctx: Ctx2D) => CanvasGradient;++/** Stop 0 at the center, stop 1 on the unit circle. */+const unitRadialGradient: UnitGradient = (world, paint, ctx) => {+ const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);+ addStopsTo(world, paint, gradient);+ return gradient;+};++/** The stops swept once around the center, starting along +x (the rx radius) and turning toward +y. */+const unitAngularGradient: UnitGradient = (world, paint, ctx) => {+ const gradient = ctx.createConicGradient(0, 0, 0);+ addStopsTo(world, paint, gradient);return gradient;+};++/**+ * Fill the current path with a gradient drawn in its unit circle's space+ * under the paint's ellipse matrix. Canvas gradients are circles; the+ * ellipse comes from the matrix, which bends only the paint: the path was+ * placed when it was built.+ */+function fillThroughEllipse(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number, unit: UnitGradient): void {+ const { a, b, c, d, e, f } = getGradientEllipseMatrix(world, paint, w, h);+ ctx.save();+ ctx.transform(a, b, c, d, e, f);+ ctx.fillStyle = unit(world, paint, ctx);+ ctx.fill();+ ctx.restore();}-/** Create a canvas radial gradient from a gradient paint sub-entity. */-export function createRadialGradient(+// Where createPatternThroughEllipse draws; a pattern keeps a copy of what+// its canvas held when it was made, so one canvas serves every pattern.+let scratch: { canvas: OffscreenCanvas; ctx: OffscreenCanvasRenderingContext2D } | null = null;++/**+ * A gradient drawn under the paint's ellipse matrix as a pattern, for+ * strokes and glyphs: their shapes are made when drawn, under the current+ * matrix, so `fillThroughEllipse`'s matrix would bend them along with the+ * paint. The gradient is drawn once over the whole of `ctx`'s canvas, pixel+ * for pixel, so anything drawn on it meets the paint at full resolution+ * wherever it lands.+ */+function createPatternThroughEllipse(world: World,- fill: Entity,+ paint: Entity,ctx: Ctx2D,w: number,h: number,-): CanvasGradient {- const computed = store(world, Computed);- const fid = fill.id();-- const hasPos = fill.has(Position);- const px = hasPos ? computed.positionX[fid]! : 0.5;- const py = hasPos ? computed.positionY[fid]! : 0.5;- const sx = computed.scaleX[fid]!;- const sy = computed.scaleY[fid]!;- const angle = (computed.rotation[fid]! * Math.PI) / 180;- const cos = Math.cos(angle);- const sin = Math.sin(angle);+ unit: UnitGradient,+): CanvasPattern | CanvasGradient {+ const local = ctx.getTransform();+ // A collapsed node draws nothing, and its matrix has no inverse to place a pattern with.+ if (local.a * local.d - local.b * local.c === 0) {+ return unit(world, paint, ctx);+ }++ const { width, height } = ctx.canvas;+ if (!scratch) {+ const canvas = new OffscreenCanvas(width, height);+ scratch = { canvas, ctx: canvas.getContext('2d')! };+ } else if (scratch.canvas.width !== width || scratch.canvas.height !== height) {+ scratch.canvas.width = width;+ scratch.canvas.height = height;+ }- // Center point (0.5, 0.5) in normalized space- const cx = px * w;- const cy = py * h;+ const target = scratch.ctx;+ target.setTransform(1, 0, 0, 1, 0, 0);+ target.clearRect(0, 0, width, height);+ target.beginPath();+ target.rect(0, 0, width, height);+ target.setTransform(local.multiply(getGradientEllipseMatrix(world, paint, w, h)));+ target.fillStyle = unit(world, paint, target);+ target.fill();- // Edge points to determine radius- const edgeXLocalX = (1 - 0.5) * sx;- const edgeXLocalY = (0.5 - 0.5) * sy;- const edgeXAbsX = (px + edgeXLocalX * cos - edgeXLocalY * sin) * w;- const edgeXAbsY = (py + edgeXLocalX * sin + edgeXLocalY * cos) * h;+ const pattern = ctx.createPattern(scratch.canvas, 'no-repeat')!;+ pattern.setTransform(local.inverse());+ return pattern;+}- const edgeYLocalX = (0.5 - 0.5) * sx;- const edgeYLocalY = (1 - 0.5) * sy;- const edgeYAbsX = (px + edgeYLocalX * cos - edgeYLocalY * sin) * w;- const edgeYAbsY = (py + edgeYLocalX * sin + edgeYLocalY * cos) * h;+/** Fill the current path with a radial gradient paint. */+export function fillRadialGradient(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number): void {+ fillThroughEllipse(world, paint, ctx, w, h, unitRadialGradient);+}- const distX = Math.hypot(edgeXAbsX - cx, edgeXAbsY - cy);- const distY = Math.hypot(edgeYAbsX - cx, edgeYAbsY - cy);- const outerRadius = Math.max(0.0001, distX, distY);+/**+ * A radial gradient paint as a pattern for strokes and glyphs, which the+ * ellipse matrix would bend (see `fillRadialGradient`). Make it once per+ * matrix of `ctx` and reuse it: each one costs a canvas-sized draw.+ */+export function createRadialGradientPattern(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number): CanvasPattern | CanvasGradient {+ return createPatternThroughEllipse(world, paint, ctx, w, h, unitRadialGradient);+}- const gradient = ctx.createRadialGradient(cx, cy, 0, cx, cy, outerRadius);+/** Stroke the current path with a radial gradient paint, in the stroke style already set on `ctx`. */+export function strokeRadialGradient(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number): void {+ ctx.strokeStyle = createRadialGradientPattern(world, paint, ctx, w, h);+ ctx.stroke();+}- addStopsTo(world, fill, gradient);- return gradient;+/** Fill the current path with an angular gradient paint. */+export function fillAngularGradient(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number): void {+ fillThroughEllipse(world, paint, ctx, w, h, unitAngularGradient);+}++/**+ * An angular gradient paint as a pattern for strokes and glyphs, which the+ * ellipse matrix would bend (see `fillAngularGradient`). Make it once per+ * matrix of `ctx` and reuse it: each one costs a canvas-sized draw.+ */+export function createAngularGradientPattern(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number): CanvasPattern | CanvasGradient {+ return createPatternThroughEllipse(world, paint, ctx, w, h, unitAngularGradient);+}++/** Stroke the current path with an angular gradient paint, in the stroke style already set on `ctx`. */+export function strokeAngularGradient(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number): void {+ ctx.strokeStyle = createAngularGradientPattern(world, paint, ctx, w, h);+ ctx.stroke();+}++/** `angle` turned by whole turns to land within half a turn of `near`, degrees. */+function nearestAngle(angle: number, near: number): number {+ return angle + Math.round((near - angle) / 360) * 360;}diff --git a/packages/runtime/src/systems/motion.ts b/packages/runtime/src/systems/motion.tsindex 568cf9d9..b157226b 100644--- a/packages/runtime/src/systems/motion.ts+++ b/packages/runtime/src/systems/motion.ts@@ -11,9 +11,9 @@ import {Computed, Cache, Animation, KeyframeTrack, Keyframe, Chars,UniformScale, Position, Offset, Rotation, Scale, Skew, Size, Opacity,Color, Blur, Volume, Effect, StrokeStyle, CornerRadius, MixedCornerRadius,- ColorStop,+ ColorStop, LinearGradient, EllipticalGradient,} from '../traits';-import { AnimationType, AnimationPhase } from '../constants';+import { AnimationType, AnimationPhase, LINEAR_GRADIENT_DEFAULTS, ELLIPTICAL_GRADIENT_DEFAULTS } from '../constants';import { revealChars, revealWords, scrambleChars } from '../utils/text-motion';import { getLocalWindow } from '../utils/time';@@ -55,6 +55,14 @@ export function resetAnimatedValues(world: World, entity: Entity | null, ignore?computed.cornerRadiusBottomRight[eid] = read(MixedCornerRadius, 'bottomRight', 0);computed.cornerRadiusBottomLeft[eid] = read(MixedCornerRadius, 'bottomLeft', 0);computed.stopOffset[eid] = read(ColorStop, 'offset', 0);+ computed.gradientX1[eid] = read(LinearGradient, 'x1', LINEAR_GRADIENT_DEFAULTS.x1);+ computed.gradientY1[eid] = read(LinearGradient, 'y1', LINEAR_GRADIENT_DEFAULTS.y1);+ computed.gradientX2[eid] = read(LinearGradient, 'x2', LINEAR_GRADIENT_DEFAULTS.x2);+ computed.gradientY2[eid] = read(LinearGradient, 'y2', LINEAR_GRADIENT_DEFAULTS.y2);+ computed.gradientCX[eid] = read(EllipticalGradient, 'cx', ELLIPTICAL_GRADIENT_DEFAULTS.cx);+ computed.gradientCY[eid] = read(EllipticalGradient, 'cy', ELLIPTICAL_GRADIENT_DEFAULTS.cy);+ computed.gradientRX[eid] = read(EllipticalGradient, 'rx', ELLIPTICAL_GRADIENT_DEFAULTS.rx);+ computed.gradientRY[eid] = read(EllipticalGradient, 'ry', ELLIPTICAL_GRADIENT_DEFAULTS.ry);if (entity.has(UniformScale) && ignore !== UniformScale) {computed.scaleX[eid] = read(UniformScale, 'value', 1);@@ -361,6 +369,38 @@ export function getPropertyPaths(world: World) {computed: computed.stopOffset,authored: store(world, ColorStop).offset,},+ 'gradient.x1': {+ computed: computed.gradientX1,+ authored: store(world, LinearGradient).x1,+ },+ 'gradient.y1': {+ computed: computed.gradientY1,+ authored: store(world, LinearGradient).y1,+ },+ 'gradient.x2': {+ computed: computed.gradientX2,+ authored: store(world, LinearGradient).x2,+ },+ 'gradient.y2': {+ computed: computed.gradientY2,+ authored: store(world, LinearGradient).y2,+ },+ 'gradient.cx': {+ computed: computed.gradientCX,+ authored: store(world, EllipticalGradient).cx,+ },+ 'gradient.cy': {+ computed: computed.gradientCY,+ authored: store(world, EllipticalGradient).cy,+ },+ 'gradient.rx': {+ computed: computed.gradientRX,+ authored: store(world, EllipticalGradient).rx,+ },+ 'gradient.ry': {+ computed: computed.gradientRY,+ authored: store(world, EllipticalGradient).ry,+ },'chars': {computed: computed.chars,authored: store(world, Chars).value,diff --git a/packages/runtime/src/systems/render.ts b/packages/runtime/src/systems/render.tsindex 0865cfc3..5a7b6817 100644--- a/packages/runtime/src/systems/render.ts+++ b/packages/runtime/src/systems/render.ts@@ -36,7 +36,14 @@ import { renderText } from '../utils/text';import { getTransitionWindow } from '../utils/transition';import { drawOnto, getSurfaceContext } from '../utils/surface';import { findGeometryAssetSource, getIntrinsicPaint } from '../utils/time';-import { createLinearGradient, createRadialGradient } from './gradients';+import {+ fillAngularGradient,+ fillLinearGradient,+ fillRadialGradient,+ strokeAngularGradient,+ strokeLinearGradient,+ strokeRadialGradient,+} from './gradients';import {MaskDecoder, resolveImageDecoder, resolveVideoDecoder,resolveCaptionDecoder, resolveShaderHost, resolveWaveformPeaks,@@ -387,13 +394,15 @@ export function renderFills(world: World, entity: Entity): void {} else if (paint === PaintType.LINEAR_GRADIENT) {const w = computed.width[eid]!;const h = computed.height[eid]!;- ctx.fillStyle = createLinearGradient(world, fill, ctx, w, h);- ctx.fill();+ fillLinearGradient(world, fill, ctx, w, h);} else if (paint === PaintType.RADIAL_GRADIENT) {const w = computed.width[eid]!;const h = computed.height[eid]!;- ctx.fillStyle = createRadialGradient(world, fill, ctx, w, h);- ctx.fill();+ fillRadialGradient(world, fill, ctx, w, h);+ } else if (paint === PaintType.ANGULAR_GRADIENT) {+ const w = computed.width[eid]!;+ const h = computed.height[eid]!;+ fillAngularGradient(world, fill, ctx, w, h);} else if (paint === PaintType.WAVEFORM) {renderWaveform(world, entity, fill);} else if (paint === PaintType.SHADER) {@@ -582,15 +591,19 @@ function renderStrokes(world: World, entity: Entity): void {if (paintType === PaintType.LINEAR_GRADIENT) {const w = computed.width[eid]!;const h = computed.height[eid]!;- ctx.strokeStyle = createLinearGradient(world, stroke, ctx, w, h);+ strokeLinearGradient(world, stroke, ctx, w, h);} else if (paintType === PaintType.RADIAL_GRADIENT) {const w = computed.width[eid]!;const h = computed.height[eid]!;- ctx.strokeStyle = createRadialGradient(world, stroke, ctx, w, h);+ strokeRadialGradient(world, stroke, ctx, w, h);+ } else if (paintType === PaintType.ANGULAR_GRADIENT) {+ const w = computed.width[eid]!;+ const h = computed.height[eid]!;+ strokeAngularGradient(world, stroke, ctx, w, h);} else {ctx.strokeStyle = colorToHex(computed.color[sid]!);+ ctx.stroke();}- ctx.stroke();ctx.globalCompositeOperation = savedCO;ctx.globalAlpha = savedAlpha;diff --git a/packages/runtime/src/traits/derived.ts b/packages/runtime/src/traits/derived.tsindex 0ba136d0..1832c541 100644--- a/packages/runtime/src/traits/derived.ts+++ b/packages/runtime/src/traits/derived.ts@@ -4,6 +4,8 @@import { trait, type Entity } from 'koota';+import { LINEAR_GRADIENT_DEFAULTS, ELLIPTICAL_GRADIENT_DEFAULTS } from '../constants';+// Fully resolved per-frame values (base state + constraints + animations +// keyframes). Written by the motion and transform systems, read by render and// UI code. Never serialized.@@ -33,6 +35,14 @@ export const Computed = trait({cornerRadiusBottomRight: 0,cornerRadiusBottomLeft: 0,stopOffset: 0,+ gradientX1: LINEAR_GRADIENT_DEFAULTS.x1,+ gradientY1: LINEAR_GRADIENT_DEFAULTS.y1,+ gradientX2: LINEAR_GRADIENT_DEFAULTS.x2,+ gradientY2: LINEAR_GRADIENT_DEFAULTS.y2,+ gradientCX: ELLIPTICAL_GRADIENT_DEFAULTS.cx,+ gradientCY: ELLIPTICAL_GRADIENT_DEFAULTS.cy,+ gradientRX: ELLIPTICAL_GRADIENT_DEFAULTS.rx,+ gradientRY: ELLIPTICAL_GRADIENT_DEFAULTS.ry,width: 0,height: 0,chars: undefined as string | undefined,diff --git a/packages/runtime/src/traits/style.ts b/packages/runtime/src/traits/style.tsindex 63fc1b64..c7b958c9 100644--- a/packages/runtime/src/traits/style.ts+++ b/packages/runtime/src/traits/style.ts@@ -5,7 +5,7 @@import { DEFAULT_MASK_SMOOTHING } from '@diffusionstudio/assets';import { trait } from 'koota';-import { BlendModeType, EffectType, ScaleModeType, StrokeJoin, StrokeCap } from '../constants';+import { BlendModeType, EffectType, ScaleModeType, StrokeJoin, StrokeCap, LINEAR_GRADIENT_DEFAULTS, ELLIPTICAL_GRADIENT_DEFAULTS } from '../constants';// Opacity of whatever the entity is: a node, a paint, a stroke, a shadow, a// gradient stop's color. Absent means opaque.@@ -53,6 +53,18 @@ export const Mask = trait({// cross-fade.export const ColorStop = trait({ offset: 0 });+// Where a linear gradient paint draws its line, SVG's x1/y1/x2/y2 in its+// holder's box as fractions of it (objectBoundingBox): stop 0 at (x1, y1),+// stop 1 at (x2, y2). Absent means LINEAR_GRADIENT_DEFAULTS.+export const LinearGradient = trait({ ...LINEAR_GRADIENT_DEFAULTS });++// Where a radial or angular gradient paint draws its ellipse, SVG's cx/cy+// plus the rx/ry of <ellipse>, in its holder's box as fractions of it: a+// radial one goes from stop 0 at the center to stop 1 on the ellipse, an+// angular one sweeps around the center. The entity's Rotation turns the radii.+// Absent means ELLIPTICAL_GRADIENT_DEFAULTS.+export const EllipticalGradient = trait({ ...ELLIPTICAL_GRADIENT_DEFAULTS });+// How a stroke sub-entity is drawn: line width, joins, caps. Lives on the// stroke itself (next to its Paint/Color/Opacity), so each stroke of a node// has its own width. Absent means a 1px miter/butt line.diff --git a/packages/runtime/src/utils/text.ts b/packages/runtime/src/utils/text.tsindex f20edca1..e9a3905f 100644--- a/packages/runtime/src/utils/text.ts+++ b/packages/runtime/src/utils/text.ts@@ -18,7 +18,7 @@ import { clamp } from '../math/common';import { colorToHex } from './color';import { applyStrokeStyle, findWidestStroke } from './stroke';import { getSurfaceContext } from './surface';-import { createLinearGradient, createRadialGradient } from '../systems/gradients';+import { createAngularGradientPattern, createLinearGradient, createRadialGradientPattern } from '../systems/gradients';import type { Entity, World } from 'koota';@@ -265,6 +265,32 @@ function tokenizeText(world: World, entity: Entity) {store(world, TextCache).tokens[entity.id()] = lines;}+type EllipticalPatterns = Map<Entity, CanvasPattern | CanvasGradient>;++/**+ * A radial or angular paint's pattern, made once per text render and kept in+ * `patterns`: one costs a canvas-sized draw, and it holds for every word,+ * since the words share the box and the matrix.+ */+function getEllipticalPattern(+ world: World,+ ctx: Ctx,+ patterns: EllipticalPatterns,+ paint: Entity,+ paintType: PaintType,+ w: number,+ h: number,+): CanvasPattern | CanvasGradient {+ let pattern = patterns.get(paint);+ if (!pattern) {+ pattern = paintType === PaintType.ANGULAR_GRADIENT+ ? createAngularGradientPattern(world, paint, ctx, w, h)+ : createRadialGradientPattern(world, paint, ctx, w, h);+ patterns.set(paint, pattern);+ }+ return pattern;+}+/** Renders text tokens directly to the given canvas context. */function renderTokens(ctx: Ctx, world: World, entity: Entity): void {const eid = entity.id();@@ -282,6 +308,9 @@ function renderTokens(ctx: Ctx, world: World, entity: Entity): void {const savedAlpha = ctx.globalAlpha;+ // Radial and angular paints' patterns, made on first use.+ let patterns: EllipticalPatterns | null = null;+// Draw all text shadows{ctx.save();@@ -368,8 +397,8 @@ function renderTokens(ctx: Ctx, world: World, entity: Entity): void {const paintType = paintStore.value[sid];if (paintType === PaintType.LINEAR_GRADIENT) {ctx.strokeStyle = createLinearGradient(world, stroke, ctx, w, h);- } else if (paintType === PaintType.RADIAL_GRADIENT) {- ctx.strokeStyle = createRadialGradient(world, stroke, ctx, w, h);+ } else if (paintType === PaintType.RADIAL_GRADIENT || paintType === PaintType.ANGULAR_GRADIENT) {+ ctx.strokeStyle = getEllipticalPattern(world, ctx, patterns ??= new Map(), stroke, paintType, w, h);} else {ctx.strokeStyle = colorToHex(colorStore.value[sid] ?? 0x000000);}@@ -420,8 +449,8 @@ function renderTokens(ctx: Ctx, world: World, entity: Entity): void {const paintType = paintStore.value[fid];if (paintType === PaintType.LINEAR_GRADIENT) {ctx.fillStyle = createLinearGradient(world, fill, ctx, w, h);- } else if (paintType === PaintType.RADIAL_GRADIENT) {- ctx.fillStyle = createRadialGradient(world, fill, ctx, w, h);+ } else if (paintType === PaintType.RADIAL_GRADIENT || paintType === PaintType.ANGULAR_GRADIENT) {+ ctx.fillStyle = getEllipticalPattern(world, ctx, patterns ??= new Map(), fill, paintType, w, h);} else {ctx.fillStyle = colorToHex(colorStore.value[fid] ?? 0x000000);}diff --git a/packages/runtime/src/world/observers.ts b/packages/runtime/src/world/observers.tsindex d4cdcc67..a0d4351d 100644--- a/packages/runtime/src/world/observers.ts+++ b/packages/runtime/src/world/observers.ts@@ -9,7 +9,7 @@ import {Delay, Trim, PlaybackRate, SourceFrameRate, Keyframe, ItemIndex,Position, Offset, Rotation, Scale, UniformScale, Skew, Anchor, Flip,Opacity, Color, Blur, Volume, Effect, CornerRadius, MixedCornerRadius,- ColorStop, StrokeStyle, Size, Computed, Active, Stage, IsClipPath,+ ColorStop, LinearGradient, EllipticalGradient, StrokeStyle, Size, Computed, Active, Stage, IsClipPath,ImageDecoderHandle, VideoDecoderHandle,AudioDecoderHandle, CaptionDecoderHandle, WaveformHandle,ShaderHostHandle, AudioBusHandle, TextStyle, TextRange,@@ -271,6 +271,24 @@ export function observeWorld(world: World): () => void {store(world, Computed).stopOffset[entity.id()] = entity.get(ColorStop)!.offset;});+ mirror(LinearGradient, (entity) => {+ const computed = store(world, Computed);+ const { x1, y1, x2, y2 } = entity.get(LinearGradient)!;+ computed.gradientX1[entity.id()] = x1;+ computed.gradientY1[entity.id()] = y1;+ computed.gradientX2[entity.id()] = x2;+ computed.gradientY2[entity.id()] = y2;+ });++ mirror(EllipticalGradient, (entity) => {+ const computed = store(world, Computed);+ const { cx, cy, rx, ry } = entity.get(EllipticalGradient)!;+ computed.gradientCX[entity.id()] = cx;+ computed.gradientCY[entity.id()] = cy;+ computed.gradientRX[entity.id()] = rx;+ computed.gradientRY[entity.id()] = ry;+ });+mirror(StrokeStyle, (entity) => {store(world, Computed).strokeWidth[entity.id()] = entity.get(StrokeStyle)!.width;});diff --git a/packages/runtime/src/world/serialize.ts b/packages/runtime/src/world/serialize.tsindex 7900a973..7a33e481 100644--- a/packages/runtime/src/world/serialize.ts+++ b/packages/runtime/src/world/serialize.ts@@ -10,7 +10,7 @@ import {Position, Offset, Rotation, Scale, UniformScale, Anchor, Skew, Size, Flip,Constraint, KeepAspectRatio,Opacity, BlendMode, Color, CornerRadius, MixedCornerRadius, Blur, ScaleMode, Effect, Mask,- ColorStop, StrokeStyle, Shader,+ ColorStop, LinearGradient, EllipticalGradient, StrokeStyle, Shader,Chars, TextStyle,Delay, Trim, PlaybackRate, SourceFrameRate,Playback, Sequential, Transition, ClipHeight, Expanded,@@ -120,6 +120,18 @@ export interface EntityRecord {ColorStop?: {offset?: number;};+ LinearGradient?: {+ x1?: number;+ y1?: number;+ x2?: number;+ y2?: number;+ };+ EllipticalGradient?: {+ cx?: number;+ cy?: number;+ rx?: number;+ ry?: number;+ };StrokeStyle?: {width?: number;join?: number;@@ -321,6 +333,14 @@ export function serializeEntity(entity: Entity): EntityRecord {if (entity.has(ColorStop)) {record.ColorStop = { offset: entity.get(ColorStop)!.offset };}+ if (entity.has(LinearGradient)) {+ const { x1, y1, x2, y2 } = entity.get(LinearGradient)!;+ record.LinearGradient = { x1, y1, x2, y2 };+ }+ if (entity.has(EllipticalGradient)) {+ const { cx, cy, rx, ry } = entity.get(EllipticalGradient)!;+ record.EllipticalGradient = { cx, cy, rx, ry };+ }if (entity.has(StrokeStyle)) {const stroke = entity.get(StrokeStyle)!;record.StrokeStyle = {@@ -576,6 +596,14 @@ export function deserializeEntity(entity: Entity, e: Partial<EntityRecord>): voientity.add(ColorStop);entity.set(ColorStop, defined(e.ColorStop));}+ if (e.LinearGradient !== undefined) {+ entity.add(LinearGradient);+ entity.set(LinearGradient, defined(e.LinearGradient));+ }+ if (e.EllipticalGradient !== undefined) {+ entity.add(EllipticalGradient);+ entity.set(EllipticalGradient, defined(e.EllipticalGradient));+ }if (e.StrokeStyle !== undefined) {entity.add(StrokeStyle);entity.set(StrokeStyle, defined(e.StrokeStyle));