Skip to content

The VS Code of video editing, built for agents.

TypeScript

Add ellipse and polygon shapes to drawing tools

konstantin-pauluseaacc15fc87e
diff --git a/apps/desktop/src/source.ts b/apps/desktop/src/source.ts
index faf1d3bc..5fced69b 100644
--- a/apps/desktop/src/source.ts
+++ b/apps/desktop/src/source.ts
@@ -29,7 +29,7 @@ const COMPOSITION_COMPONENTS = new Map<string, string>(
// These composition names also exist in SVG. An SVG fragment is DOM content
// only while it has an SVG container in the same JSX tree; elsewhere the tag
// keeps its composition meaning.
-const AMBIGUOUS_SVG_TAGS: ReadonlySet<string> = new Set(["rect", "text", "image"]);
+const AMBIGUOUS_SVG_TAGS: ReadonlySet<string> = new Set(["rect", "ellipse", "polygon", "text", "image"]);
const SVG_CONTAINERS: ReadonlySet<string> = new Set([
"svg", "g", "defs", "symbol", "marker", "mask", "clipPath", "pattern",
"filter", "linearGradient", "radialGradient", "textPath", "tspan", "switch",
diff --git a/apps/web/src/assets/icons/tool.polygon-small.svg b/apps/web/src/assets/icons/tool.polygon-small.svg
new file mode 100644
index 00000000..8f64a9f3
--- /dev/null
+++ b/apps/web/src/assets/icons/tool.polygon-small.svg
@@ -0,0 +1,3 @@
+<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path transform="translate(3 3) scale(0.75)" d="M10.995 5.74028C11.4415 4.96694 12.5583 4.96694 13.0048 5.74028L19.2226 16.5098C19.6691 17.2831 19.1107 18.25 18.2177 18.25V17.0899L11.9999 6.32036L5.78215 17.0899V18.25L5.61809 18.2393C4.82286 18.13 4.35875 17.2347 4.77727 16.5098L10.995 5.74028ZM18.2177 17.0899V18.25H5.78215V17.0899H18.2177Z" fill="currentColor"/>
+</svg>
diff --git a/apps/web/src/components/canvas/toolbar.tsx b/apps/web/src/components/canvas/toolbar.tsx
index f49d29a2..1d248d84 100644
--- a/apps/web/src/components/canvas/toolbar.tsx
+++ b/apps/web/src/components/canvas/toolbar.tsx
@@ -18,7 +18,7 @@ import { PromptInput } from "../genai/prompt-input";
import { ActionBar } from "../genai/action-bar";
import { ObjectMaskBar } from "./object-mask-bar";
import { ClipPathBar } from "./clip-path-bar";
-import { For, Match, Show, Switch, createEffect, createMemo } from "solid-js";
+import { For, Match, Show, Switch, createEffect, createMemo, createSignal } from "solid-js";
import { Tool, ToolType } from "@diffusionstudio/runtime";
import { useWorld } from "@diffusionstudio/koota-solid";
import { clearClipPathTarget, useTool } from "@/engine";
@@ -30,11 +30,29 @@ const CURSOR_TOOLS = [
{ tool: ToolType.OBJECT_MASK, label: 'Object Mask', shortcut: 'M', icon: 'object-mask', menuIcon: 'object-mask' },
] as const;
+const SHAPE_TOOLS = [
+ { tool: ToolType.RECT, label: 'Rectangle', shortcut: 'R', icon: 'tool.rectangle', menuIcon: 'tool.rectangle-small' },
+ { tool: ToolType.ELLIPSE, label: 'Ellipse', shortcut: 'O', icon: 'tool.ellipse', menuIcon: 'tool.ellipse-small' },
+ { tool: ToolType.POLYGON, label: 'Polygon', shortcut: undefined, icon: 'tool.polygon', menuIcon: 'tool.polygon-small' },
+] as const;
+
+type ShapeTool = (typeof SHAPE_TOOLS)[number];
+
+// The shape the toolbar offers: the one last picked, however it was picked.
+// Outlives the toolbar, which unmounts with the canvas.
+const [lastShapeTool, setLastShapeTool] = createSignal<ShapeTool>(SHAPE_TOOLS[0]);
+
export function Toolbar() {
const world = useWorld();
const { promptInputOpen, promptInputConfig, openPromptInput, setPromptInputOpen } = usePromptInput();
const selectedTool = useTool();
const cursorTool = createMemo(() => CURSOR_TOOLS.find((cursor) => cursor.tool === selectedTool()));
+ const shapeTool = createMemo(() => SHAPE_TOOLS.find((shape) => shape.tool === selectedTool()));
+
+ createEffect(() => {
+ const shape = shapeTool();
+ if (shape) setLastShapeTool(shape);
+ });
createEffect(() => {
if (selectedTool() !== ToolType.CLIP_PATH) {
@@ -124,18 +142,53 @@ export function Toolbar() {
</TooltipTrigger>
<TooltipContent shortcut="F">Frame</TooltipContent>
</Tooltip>
- <Tooltip>
- <TooltipTrigger
- as={Button}
- size="icon-square"
- variant={selectedTool() === ToolType.RECT ? 'default' : 'ghost'}
- onClick={() => handleToolChange(ToolType.RECT)}
- class={selectedTool() === ToolType.RECT ? 'text-foreground' : 'text-muted-foreground'}
- >
- <Icon name="tool.rectangle" />
- </TooltipTrigger>
- <TooltipContent shortcut="R">Rectangle</TooltipContent>
- </Tooltip>
+ <div class="flex gap-1">
+ <Tooltip>
+ <TooltipTrigger
+ as={Button}
+ size="icon-square"
+ variant={shapeTool() ? 'default' : 'ghost'}
+ onClick={() => handleToolChange(lastShapeTool().tool)}
+ class={shapeTool() ? 'text-foreground' : 'text-muted-foreground'}
+ >
+ <Icon name={lastShapeTool().icon} />
+ </TooltipTrigger>
+ <TooltipContent shortcut={lastShapeTool().shortcut}>{lastShapeTool().label}</TooltipContent>
+ </Tooltip>
+ <DropdownMenu placement="top-start">
+ <Tooltip>
+ <TooltipTrigger<typeof DropdownMenuTrigger>
+ as={(triggerProps: object) => (
+ <DropdownMenuTrigger<typeof Button>
+ {...triggerProps}
+ as={(buttonProps) => (
+ <Button {...buttonProps} size="icon-select" variant="ghost" class="text-muted-foreground">
+ <Icon name="chevron-down" />
+ </Button>
+ )}
+ />
+ )}
+ />
+ <TooltipContent>Shape tools</TooltipContent>
+ </Tooltip>
+ <DropdownMenuPortal>
+ <DropdownMenuContent>
+ <For each={SHAPE_TOOLS}>
+ {(shape) => (
+ <DropdownMenuItem class="px-0 pr-2 gap-0.5" onSelect={() => handleToolChange(shape.tool)}>
+ <div classList={{ "visible": selectedTool() === shape.tool }} class="invisible">
+ <Icon name="confirm-check" class="text-foreground" />
+ </div>
+ <Icon name={shape.menuIcon} class="text-foreground" />
+ <span class="mx-1 flex-1 whitespace-nowrap">{shape.label}</span>
+ <DropdownMenuShortcut class="pl-6">{shape.shortcut}</DropdownMenuShortcut>
+ </DropdownMenuItem>
+ )}
+ </For>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenu>
+ </div>
<Tooltip>
<TooltipTrigger
as={Button}
diff --git a/apps/web/src/components/sidebar-left/project-menu/tool-menu.tsx b/apps/web/src/components/sidebar-left/project-menu/tool-menu.tsx
index d3e378c2..3d1e3546 100644
--- a/apps/web/src/components/sidebar-left/project-menu/tool-menu.tsx
+++ b/apps/web/src/components/sidebar-left/project-menu/tool-menu.tsx
@@ -40,6 +40,13 @@ export function ToolMenu() {
Rectangle
<DropdownMenuShortcut>R</DropdownMenuShortcut>
</DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => setTool(ToolType.ELLIPSE)}>
+ Ellipse
+ <DropdownMenuShortcut>O</DropdownMenuShortcut>
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => setTool(ToolType.POLYGON)}>
+ Polygon
+ </DropdownMenuItem>
<DropdownMenuItem onSelect={() => setTool(ToolType.OBJECT_MASK)}>
Object Mask
<DropdownMenuShortcut>M</DropdownMenuShortcut>
diff --git a/apps/web/src/components/sidebar-right/inspector/appearance.tsx b/apps/web/src/components/sidebar-right/inspector/appearance.tsx
index 1ec01169..4401987b 100644
--- a/apps/web/src/components/sidebar-right/inspector/appearance.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/appearance.tsx
@@ -20,6 +20,7 @@ import {
} from "@/components/ui/select";
import { SliderInput } from "@/components/ui/slider-input";
import { ControlledTextField } from "@/components/ui/text-field";
+import { IncrementDecrementControl } from "@/components/ui/increment-decrement-control";
import { PanelSection } from "@/components/ui/panel-section";
import { Show, createMemo, createSignal } from "solid-js";
import { Icon } from "@/components/ui/icon";
@@ -33,7 +34,9 @@ import {
CornerRadius,
Hidden,
MixedCornerRadius,
+ PointCount,
isAudio,
+ isPolygon,
isRect,
} from "@diffusionstudio/runtime";
import { useDerived, useEditor } from "@/engine/hooks";
@@ -98,6 +101,9 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {
const mixedBR = useDerived(() => entity().get(Computed)?.cornerRadiusBottomRight ?? 0);
const mixedBL = useDerived(() => entity().get(Computed)?.cornerRadiusBottomLeft ?? 0);
+ const pointCountTrait = useTrait(entity, PointCount);
+ const pointCount = () => pointCountTrait()?.value ?? 3;
+
const [selectedBlendMode, setSelectedBlendMode] = createSignal(blendMode());
const [radiusMode, setRadiusMode] = createSignal<RadiusMode>(entity().has(MixedCornerRadius) ? 'separate' : 'uniform');
@@ -132,6 +138,11 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {
}
};
+ const handlePointCountChange = (v: number) => {
+ const count = Math.max(3, Math.round(v));
+ editor.editProperty(entity(), 'pointCount', count === 3 ? false : count);
+ };
+
const handleVisibilityChange = () => {
editor.editProperty(entity(), 'hidden', !hidden());
};
@@ -333,6 +344,27 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {
</ControlRow>
</Show>
</Show>
+
+ <Show when={isPolygon(entity())}>
+ <ControlRow label="Count" contentClass="grid grid-cols-2 gap-2 min-w-0">
+ <ControlledTextField
+ value={pointCount()}
+ autoSelect
+ step={1}
+ min={3}
+ onNumber={handlePointCountChange}
+ icon={<Icon name="tool.polygon-small" />}
+ sliderEnabled
+ limitEvents
+ />
+ <IncrementDecrementControl
+ decrementLabel="Fewer corners"
+ incrementLabel="More corners"
+ onDecrement={() => handlePointCountChange(pointCount() - 1)}
+ onIncrement={() => handlePointCountChange(pointCount() + 1)}
+ />
+ </ControlRow>
+ </Show>
</PanelSection>
);
}
diff --git a/apps/web/src/components/sidebar-right/inspector/clip-paths.tsx b/apps/web/src/components/sidebar-right/inspector/clip-paths.tsx
index e1ca205c..17aa72d9 100644
--- a/apps/web/src/components/sidebar-right/inspector/clip-paths.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/clip-paths.tsx
@@ -23,11 +23,12 @@ type ClipPathsSettingsProps = {
};
/**
- * The `<rect clipPath>` children of the selected node: the boxes it is
- * clipped to (several intersect). A clip path is a rect like any other, so it
+ * The clip path children of the selected node (`<rect clipPath>`,
+ * `<ellipse clipPath>`, `<polygon clipPath>`): the shapes it is clipped to
+ * (several intersect). A clip path is a shape like any other, so it
* has no inspector of its own — a row selects it and the transform, time and
* appearance panels are then its own. The plus picks up the clip path tool,
- * whose bar over the canvas turns the rects selected there into clip paths
+ * whose bar over the canvas turns the shapes selected there into clip paths
* of this node.
*/
export function ClipPathsSettings(props: ClipPathsSettingsProps) {
diff --git a/apps/web/src/components/timeline/layers/node.tsx b/apps/web/src/components/timeline/layers/node.tsx
index 367e3504..5be8127e 100644
--- a/apps/web/src/components/timeline/layers/node.tsx
+++ b/apps/web/src/components/timeline/layers/node.tsx
@@ -20,6 +20,8 @@ import {
isCaption,
isGroup,
isClipPath,
+ isEllipse,
+ isPolygon,
isScene,
isSequence,
isText,
@@ -358,6 +360,8 @@ function getLayerIcon(world: World, layer: TimelineNode) {
if (isGroup(entity)) return "group";
if (isCaption(entity)) return "captions-small";
if (isText(entity)) return "text-small";
+ if (isEllipse(entity)) return "tool.ellipse-small";
+ if (isPolygon(entity)) return "tool.polygon-small";
switch (findGeometryAsset(world, entity)?.type) {
case 'IMAGE':
diff --git a/apps/web/src/engine/clip-path.ts b/apps/web/src/engine/clip-path.ts
index cd801e2c..de644ebc 100644
--- a/apps/web/src/engine/clip-path.ts
+++ b/apps/web/src/engine/clip-path.ts
@@ -35,7 +35,7 @@ const round2 = (value: number): number => Math.round(value * 100) / 100;
// The node the tool is aimed at, reactive so the bar follows it.
const [clipPathTarget, setClipPathTarget] = createSignal<Entity | null>(null);
-/** The node the picked rects will clip, reactive; null while the tool is down. */
+/** The node the picked shapes will clip, reactive; null while the tool is down. */
export { clipPathTarget };
export function getClipPathTarget(): Entity | null {
@@ -43,7 +43,7 @@ export function getClipPathTarget(): Entity | null {
return target?.isAlive() ? target : null;
}
-/** Picks the tool to add clip paths to `target`. The selection stays on it until a rect is picked. */
+/** Picks the tool to add clip paths to `target`. The selection stays on it until a shape is picked. */
export function beginClipPathFor(world: World, target: Entity): void {
setClipPathTarget(target);
world.set(Tool, { value: ToolType.CLIP_PATH });
@@ -55,8 +55,9 @@ export function clearClipPathTarget(): void {
}
/**
- * Whether `entity` can become a clip path of `target`: a plain rect (a clip
- * path is always a `<rect>`, so media, text and containers are out), not one
+ * Whether `entity` can become a clip path of `target`: a plain shape (a clip
+ * path is a `<rect>`, `<ellipse>` or `<polygon>`, so media, text and
+ * containers are out), not one
* already, and not the target or something the target sits inside — a node
* cannot be moved into its own subtree.
*/
@@ -66,7 +67,7 @@ export function canClipWith(world: World, target: Entity, entity: Entity): boole
return !getEntityTree(world, entity).includes(target);
}
-/** The selected rects Confirm would apply to the target, in selection order. */
+/** The selected shapes Confirm would apply to the target, in selection order. */
export function getClipPathPicks(world: World): Entity[] {
const target = getClipPathTarget();
if (!target) return [];
@@ -74,8 +75,8 @@ export function getClipPathPicks(world: World): Entity[] {
}
/**
- * Makes the picked rects clip paths of the target, one undo step, and puts
- * the tool down with the target selected. Each rect keeps its place on the
+ * Makes the picked shapes clip paths of the target, one undo step, and puts
+ * the tool down with the target selected. Each shape keeps its place on the
* canvas: its matrix is carried from the parent it had into the target's
* space and written back as `x`, `y` and `rotation`, with whatever scale the
* move adds (a target drawn at half size, say) folded into its `width` and
@@ -91,29 +92,29 @@ export function applyClipPaths(world: World): void {
const flip = store(world, Flip);
const targetInverse = invert2D(entityWorldMat(world, target));
- for (const rect of picks) {
- const eid = rect.id();
+ for (const shape of picks) {
+ const eid = shape.id();
const width = computed.width[eid] ?? 0;
const height = computed.height[eid] ?? 0;
- const anchor = entityAnchor(world, rect);
+ const anchor = entityAnchor(world, shape);
// Where it is drawn now, pivot folded in (see `bakeContainerInto`),
// taken into the target's space before the move changes its parent.
const placed = decompose2D(multiply2D(
targetInverse,
- multiply2D(entityWorldMat(world, rect), translate2D(anchor.x * width, anchor.y * height)),
+ multiply2D(entityWorldMat(world, shape), translate2D(anchor.x * width, anchor.y * height)),
));
- if (!editor.reparent(rect, target)) continue;
- editor.editProperty(rect, 'clipPath', true);
+ if (!editor.reparent(shape, target)) continue;
+ editor.editProperty(shape, 'clipPath', true);
- // The scale the rect carries of its own stays its own; the rest is the move's.
+ // The scale the shape carries of its own stays its own; the rest is the move's.
const ownX = (computed.scaleX[eid] ?? 1) * (flip.x[eid] ?? 1);
const ownY = (computed.scaleY[eid] ?? 1) * (flip.y[eid] ?? 1);
const nextWidth = ownX === 0 ? width : Math.round(width * Math.abs(placed.scaleX / ownX));
const nextHeight = ownY === 0 ? height : Math.round(height * Math.abs(placed.scaleY / ownY));
- const offset = entityOffset(world, rect);
+ const offset = entityOffset(world, shape);
const x = Math.round(placed.x - anchor.x * nextWidth - offset.x);
const y = Math.round(placed.y - anchor.y * nextHeight - offset.y);
const rotation = round2(placed.rotation);
@@ -124,7 +125,7 @@ export function applyClipPaths(world: World): void {
if (rotation !== round2(computed.rotation[eid] ?? 0)) writes.push(['rotation', rotation]);
if (nextWidth !== Math.round(width)) writes.push(['width', nextWidth]);
if (nextHeight !== Math.round(height)) writes.push(['height', nextHeight]);
- if (writes.length) editTransform(world, editor, rect, writes);
+ if (writes.length) editTransform(world, editor, shape, writes);
}
leaveClipPathTool(world, target);
diff --git a/apps/web/src/engine/draw-tool.tsx b/apps/web/src/engine/draw-tool.tsx
index 0de972ed..3afd84e4 100644
--- a/apps/web/src/engine/draw-tool.tsx
+++ b/apps/web/src/engine/draw-tool.tsx
@@ -3,16 +3,16 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
- * The tools that put a new node on the stage: rect, scene and text. A drag
- * draws the node's box, a click drops one of a default size centered on the
- * pointer. A rect or text lands in the scene the press was in, a scene always
- * at the root.
+ * The tools that put a new node on the stage: the shapes (rect, ellipse,
+ * polygon), scene and text. A drag draws the node's box, a click drops one of
+ * a default size centered on the pointer. A shape or text lands in the scene
+ * the press was in, a scene always at the root.
*/
-import { Rect, Scene, SolidPaint, Text } from '@diffusionstudio/reconciler';
+import { Ellipse, Polygon, Rect, Scene, SolidPaint, Text } from '@diffusionstudio/reconciler';
import {
- Computed, HitRegions, RenderSurface, Root, Source, Tool, ToolType,
- findSceneAt, getNextName, identity2D, rectToQuad, screenToWorld, store, worldToLocal,
+ Computed, GeometryType, HitRegions, RenderSurface, Root, Source, Tool, ToolType,
+ findSceneAt, getNextName, identity2D, rectToQuad, screenToWorld, store, traceShape, worldToLocal,
} from '@diffusionstudio/runtime';
import { getDocumentEditor } from './editor';
@@ -25,6 +25,8 @@ type Ctx2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
type DrawConfig = {
namePrefix: string;
+ /** The outline the preview traces. */
+ geometry: GeometryType;
fillColor: string;
/** What the box is filled with while it is drawn; null for an outline only. */
previewColor: string | null;
@@ -36,6 +38,23 @@ type DrawConfig = {
const DRAW_CONFIG: Partial<Record<ToolType, DrawConfig>> = {
[ToolType.RECT]: {
namePrefix: 'Rect',
+ geometry: GeometryType.RECT,
+ fillColor: '#E0E0E0',
+ previewColor: '#E0E0E0',
+ defaultWidth: 300,
+ defaultHeight: 300,
+ },
+ [ToolType.ELLIPSE]: {
+ namePrefix: 'Ellipse',
+ geometry: GeometryType.ELLIPSE,
+ fillColor: '#E0E0E0',
+ previewColor: '#E0E0E0',
+ defaultWidth: 300,
+ defaultHeight: 300,
+ },
+ [ToolType.POLYGON]: {
+ namePrefix: 'Polygon',
+ geometry: GeometryType.POLYGON,
fillColor: '#E0E0E0',
previewColor: '#E0E0E0',
defaultWidth: 300,
@@ -43,6 +62,7 @@ const DRAW_CONFIG: Partial<Record<ToolType, DrawConfig>> = {
},
[ToolType.SCENE]: {
namePrefix: 'Scene',
+ geometry: GeometryType.RECT,
fillColor: '#000000',
previewColor: '#000000',
defaultWidth: 1920,
@@ -50,6 +70,7 @@ const DRAW_CONFIG: Partial<Record<ToolType, DrawConfig>> = {
},
[ToolType.TEXT]: {
namePrefix: 'Text',
+ geometry: GeometryType.RECT,
fillColor: '#FFFFFF',
previewColor: null,
// A clicked-in text sizes itself to its glyphs.
@@ -106,7 +127,9 @@ export function drawDrawTool(world: World, ctx: Ctx2D, resolution: number): void
ctx.resetTransform();
ctx.beginPath();
- ctx.rect(rect.x, rect.y, rect.width, rect.height);
+ ctx.translate(rect.x, rect.y);
+ traceShape(ctx, config.geometry, rect.width, rect.height, 3);
+ ctx.translate(-rect.x, -rect.y);
if (config.previewColor) {
ctx.fillStyle = config.previewColor;
ctx.fill();
@@ -193,7 +216,7 @@ export function handleDrawInteraction(world: World, event: DispatchedPointerEven
let posX = isClick ? topLeft.x - width / 2 : topLeft.x;
let posY = isClick ? topLeft.y - height / 2 : topLeft.y;
- // Scenes always live at the root; rect/text may parent into a hovered scene.
+ // Scenes always live at the root; anything else may parent into a hovered scene.
const parentScene = tool === ToolType.SCENE ? null : targetScene;
if (parentScene !== null) {
const local = worldToLocal(world, parentScene, posX, posY);
@@ -229,6 +252,20 @@ export function handleDrawInteraction(world: World, event: DispatchedPointerEven
</Text>
);
}
+ if (tool === ToolType.ELLIPSE) {
+ return (
+ <Ellipse name={name} x={x} y={y} {...size}>
+ <SolidPaint color={config.fillColor} />
+ </Ellipse>
+ );
+ }
+ if (tool === ToolType.POLYGON) {
+ return (
+ <Polygon name={name} x={x} y={y} {...size}>
+ <SolidPaint color={config.fillColor} />
+ </Polygon>
+ );
+ }
return (
<Rect name={name} x={x} y={y} {...size}>
<SolidPaint color={config.fillColor} />
diff --git a/apps/web/src/engine/input/cursor.ts b/apps/web/src/engine/input/cursor.ts
index 27a4fe2c..87adce2d 100644
--- a/apps/web/src/engine/input/cursor.ts
+++ b/apps/web/src/engine/input/cursor.ts
@@ -89,6 +89,8 @@ const TOOL_CURSORS: Record<ToolType, { idle: CursorType; pressed?: CursorType }>
[ToolType.BLADE]: { idle: 'crosshair' },
[ToolType.SCENE]: { idle: 'crosshair' },
[ToolType.RECT]: { idle: 'crosshair' },
+ [ToolType.ELLIPSE]: { idle: 'crosshair' },
+ [ToolType.POLYGON]: { idle: 'crosshair' },
[ToolType.TEXT]: { idle: 'crosshair' },
[ToolType.TEXT_EDIT]: { idle: 'text' },
[ToolType.OBJECT_MASK]: { idle: 'crosshair' },
diff --git a/apps/web/src/engine/input/shortcuts.ts b/apps/web/src/engine/input/shortcuts.ts
index 1433275f..590164ca 100644
--- a/apps/web/src/engine/input/shortcuts.ts
+++ b/apps/web/src/engine/input/shortcuts.ts
@@ -487,6 +487,7 @@ const PRESSED_SHORTCUTS: readonly Shortcut[] = [
{ keys: ['f', '!mod'], action: selectTool(ToolType.SCENE) },
{ keys: ['t', '!mod'], action: selectTool(ToolType.TEXT) },
{ keys: ['r', '!mod'], action: selectTool(ToolType.RECT) },
+ { keys: ['o', '!mod'], action: selectTool(ToolType.ELLIPSE) },
{ keys: ['m', '!mod'], action: selectTool(ToolType.OBJECT_MASK) },
{ keys: ['a', '!mod'], action: seekFrames(-1) },
{ keys: ['d', '!mod'], action: seekFrames(1) },
diff --git a/apps/web/src/engine/timeline/style.ts b/apps/web/src/engine/timeline/style.ts
index 8e6c8639..b8050b29 100644
--- a/apps/web/src/engine/timeline/style.ts
+++ b/apps/web/src/engine/timeline/style.ts
@@ -11,6 +11,8 @@ import {
isCaption,
isGroup,
isClipPath,
+ isEllipse,
+ isPolygon,
isRect,
isScene,
isSequence,
@@ -85,6 +87,8 @@ export function getClipFallbackName(world: World, entity: Entity): string {
return 'Audio';
}
+ if (isEllipse(entity)) return 'Ellipse';
+ if (isPolygon(entity)) return 'Polygon';
return isRect(entity) ? 'Rectangle' : 'Layer';
}
diff --git a/docs/reference/jsx/README.md b/docs/reference/jsx/README.md
index 4ad9799e..42ee8d22 100644
--- a/docs/reference/jsx/README.md
+++ b/docs/reference/jsx/README.md
@@ -33,7 +33,7 @@ export default function Project() {
| [stage.md](./stage.md) | `<stage>`: the root, canvas background and camera, canvas placement |
| [scene.md](./scene.md) | `<scene>`: the clipped, playable frame and the timeline its children sit on |
| [elements.md](./elements.md) | Element-to-node mapping, coordinates and sizing, the shared property table |
-| [group.md](./group.md), [rect.md](./rect.md), [text.md](./text.md), [video.md](./video.md), [image.md](./image.md), [audio.md](./audio.md) | Per-element props |
+| [group.md](./group.md), [rect.md](./rect.md), [ellipse.md](./ellipse.md), [polygon.md](./polygon.md), [text.md](./text.md), [video.md](./video.md), [image.md](./image.md), [audio.md](./audio.md) | Per-element props |
| [fonts.md](./fonts.md) | Fonts for `<text>` and HTML: local families, the `fonts` tool |
| [paints.md](./paints.md) | `<solidPaint>`, gradients, `<colorStop>`, `<imagePaint>` / `<videoPaint>` |
| [styles.md](./styles.md) | `<stroke>`, `<shadow>`, `<effect>`: outlines, drop shadows and filters |
diff --git a/docs/reference/jsx/elements.md b/docs/reference/jsx/elements.md
index d6b9bc51..803c049c 100644
--- a/docs/reference/jsx/elements.md
+++ b/docs/reference/jsx/elements.md
@@ -16,6 +16,8 @@ camelCase composition elements map 1:1 onto entities. Lowercase DOM vocabulary i
| Element | What it is |
| ------- | ---------- |
| [`<rect>`](./rect.md) | A rectangle. Takes paints, strokes, shadows and effects. With `clipPath` it clips its parent instead of drawing. |
+| [`<ellipse>`](./ellipse.md) | An ellipse inscribed in its box. Takes what a rect takes. |
+| [`<polygon>`](./polygon.md) | A regular polygon (`pointCount` corners, a triangle by default) stretched to fill its box. Takes what a rect takes. |
| [`<text>`](./text.md) | Text; its children are the glyphs. Sizes itself to them unless given a box. |
| [`<textRange>`](./text.md#textrange) | A style override over a run of the parent `<text>`'s glyphs, by character index. |
| [`<video>`](./video.md) | A video clip: a rect whose intrinsic paint is the media `src` names. |
@@ -65,7 +67,7 @@ User-defined components are ordinary Solid components; they compose the elements
| ------- | ----------- |
| `<video>`, `<image>`, `<adjustmentLayer>` | 1920 × 1080 |
| `<scene>` | required — the frame's own size |
-| `<rect>`, `<html>`, `<surface>` | 100 × 100 |
+| `<rect>`, `<ellipse>`, `<polygon>`, `<html>`, `<surface>` | 100 × 100 |
| `<audio>` | 500 × 150 (the waveform box on the canvas) |
| `<rect clipPath>` | 500 × 500 |
| `<text>` | fits its glyphs |
diff --git a/docs/reference/jsx/ellipse.md b/docs/reference/jsx/ellipse.md
new file mode 100644
index 00000000..dbb16c5a
--- /dev/null
+++ b/docs/reference/jsx/ellipse.md
@@ -0,0 +1,18 @@
+# `<ellipse>`
+
+An ellipse inscribed in its box: a circle when `width` and `height` are equal. Takes the same children as [`<rect>`](./rect.md): [paint children](./paints.md), plus [`<stroke>`, `<shadow>`, `<effect>`](./styles.md), [`<animation>`](./animations.md) and [`<keyframeTrack>`](./keyframes.md).
+
+```tsx
+<ellipse x={760} y={340} width={400} height={400} fill="#FF0055" />
+```
+
+## Props
+
+All [common props](./elements.md#common-props), plus:
+
+| Prop | Type | Default | Meaning |
+| ---- | ---- | ------- | ------- |
+| `fill` | `string` | none | Any CSS color; alpha is ignored (use `opacity`). Shorthand for a solid paint child, drawn beneath any paint children. |
+| `clipPath` | `boolean` | `false` | Makes the ellipse a clip path of its parent instead of a drawn shape: the parent shows only inside the curve. Works like [`<rect clipPath>`](./rect.md#clip-paths). |
+
+Without `width`/`height` an ellipse is 100×100. Fills, strokes, shadows and [masked effects](./styles.md) follow the curve, and the canvas only picks it up inside the curve rather than anywhere in its box.
diff --git a/docs/reference/jsx/polygon.md b/docs/reference/jsx/polygon.md
new file mode 100644
index 00000000..2988625b
--- /dev/null
+++ b/docs/reference/jsx/polygon.md
@@ -0,0 +1,21 @@
+# `<polygon>`
+
+A regular polygon stretched to fill its box, its first corner at the top center: a triangle by default, apex up and base along the bottom edge. Takes the same children as [`<rect>`](./rect.md): [paint children](./paints.md), plus [`<stroke>`, `<shadow>`, `<effect>`](./styles.md), [`<animation>`](./animations.md) and [`<keyframeTrack>`](./keyframes.md).
+
+```tsx
+<polygon x={760} y={340} width={400} height={400} pointCount={6} fill="#FFFFFF">
+ <stroke color="#000000" width={8} join="round" />
+</polygon>
+```
+
+## Props
+
+All [common props](./elements.md#common-props), plus:
+
+| Prop | Type | Default | Meaning |
+| ---- | ---- | ------- | ------- |
+| `pointCount` | `number` | `3` | How many corners. Rounded to a whole number; anything under 3 is 3. Not animatable. |
+| `fill` | `string` | none | Any CSS color; alpha is ignored (use `opacity`). Shorthand for a solid paint child, drawn beneath any paint children. |
+| `clipPath` | `boolean` | `false` | Makes the polygon a clip path of its parent instead of a drawn shape: the parent shows only inside its outline. Works like [`<rect clipPath>`](./rect.md#clip-paths). |
+
+Without `width`/`height` a polygon is 100×100. The corners sit on an ellipse and are then stretched so the outline touches every side of the box, so a triangle fills its box's full height rather than leaving a gap below its base. The canvas only picks it up inside the outline.
diff --git a/docs/reference/jsx/rect.md b/docs/reference/jsx/rect.md
index 47925c11..847a558a 100644
--- a/docs/reference/jsx/rect.md
+++ b/docs/reference/jsx/rect.md
@@ -19,7 +19,7 @@ A rect with neither `fill` nor a paint child draws nothing; it is still a box: i
## Clip paths
-A `<rect clipPath>` clips the element holding it instead of drawing: the parent's fills, strokes, shadows and children show only inside the rect's box. It is still a rect — same coordinates, `cornerRadius`, transform and timing — so it can be moved, rotated, keyframed and animated independently of what it clips: a clip path whose `width` is keyframed across a text is a wipe, one that starts later than its parent is a reveal.
+A `<rect clipPath>` clips the element holding it instead of drawing: the parent's fills, strokes, shadows and children show only inside the rect's box. [`<ellipse clipPath>`](./ellipse.md) and [`<polygon clipPath>`](./polygon.md) work the same way and clip to their curve or outline; everything below applies to them too. It is still a rect — same coordinates, `cornerRadius`, transform and timing — so it can be moved, rotated, keyframed and animated independently of what it clips: a clip path whose `width` is keyframed across a text is a wipe, one that starts later than its parent is a reveal.
```tsx
<text fontSize={120} color="#FFFFFF" textAlign="center" textBaseline="middle">
diff --git a/docs/reference/jsx/styles.md b/docs/reference/jsx/styles.md
index 3885f28b..40a82a34 100644
--- a/docs/reference/jsx/styles.md
+++ b/docs/reference/jsx/styles.md
@@ -12,7 +12,7 @@ Three sub-entity children a node takes alongside its [paints](./paints.md): an o
## `<stroke>`
-An outline of the parent's box — or of its glyphs, on a `<text>` or a `<textRange>`. `color` is its paint, the rest its line style.
+An outline of the parent's shape (its box, or the curve of an `<ellipse>`, the corners of a `<polygon>`) — or of its glyphs, on a `<text>` or a `<textRange>`. `color` is its paint, the rest its line style.
| Prop | Type | Default | Meaning |
| ---- | ---- | ------- | ------- |
diff --git a/packages/jsx/src/index.ts b/packages/jsx/src/index.ts
index 4f6bc173..6d6c940a 100644
--- a/packages/jsx/src/index.ts
+++ b/packages/jsx/src/index.ts
@@ -48,6 +48,7 @@ export type {
LinearGradientPaintProps,
RadialGradientPaintProps,
AngularGradientPaintProps,
+ EllipseProps,
GroupProps,
HorizontalConstraint,
HtmlPaintProps,
@@ -56,6 +57,7 @@ export type {
KeyframeProps,
KeyframeTrackProps,
MediaPaintProps,
+ PolygonProps,
RectProps,
SceneNode,
SceneProps,
diff --git a/packages/jsx/src/jsx-runtime.ts b/packages/jsx/src/jsx-runtime.ts
index d5d8fe54..a1b83cb0 100644
--- a/packages/jsx/src/jsx-runtime.ts
+++ b/packages/jsx/src/jsx-runtime.ts
@@ -31,12 +31,14 @@ import type {
RadialGradientPaintProps,
AngularGradientPaintProps,
MediaPaintProps,
+ EllipseProps,
GroupProps,
HtmlPaintProps,
HtmlProps,
ImageProps,
KeyframeProps,
KeyframeTrackProps,
+ PolygonProps,
RectProps,
SceneProps,
SequenceProps,
@@ -66,7 +68,7 @@ type HtmlElementTags = Omit<SolidJSX.HTMLElementTags, "canvas" | "audio" | "vide
type ImgTag = Omit<SolidJSX.HTMLElementTags["img"], "src"> & { src?: string };
// The shared names are re-declared below as unions with the composition props.
-type SvgElementTags = Omit<SolidJSX.SVGElementTags, "rect" | "text" | "image">;
+type SvgElementTags = Omit<SolidJSX.SVGElementTags, "rect" | "ellipse" | "polygon" | "text" | "image">;
export declare namespace JSX {
// Solid's Element type keeps Solid's control flow (<For>, <Show>, …) and
@@ -83,6 +85,8 @@ export declare namespace JSX {
scene: SceneProps & SourceProps;
group: GroupProps & SourceProps;
rect: (RectProps & SourceProps) | SolidJSX.SVGElementTags["rect"];
+ ellipse: (EllipseProps & SourceProps) | SolidJSX.SVGElementTags["ellipse"];
+ polygon: (PolygonProps & SourceProps) | SolidJSX.SVGElementTags["polygon"];
video: VideoProps & SourceProps;
image: (ImageProps & SourceProps) | SolidJSX.SVGElementTags["image"];
audio: AudioProps & SourceProps;
diff --git a/packages/jsx/src/source.ts b/packages/jsx/src/source.ts
index 0a4c6b84..f57c3d4c 100644
--- a/packages/jsx/src/source.ts
+++ b/packages/jsx/src/source.ts
@@ -93,6 +93,8 @@ export const COMPOSITION_TAGS = [
"scene",
"group",
"rect",
+ "ellipse",
+ "polygon",
"video",
"image",
"audio",
diff --git a/packages/jsx/src/types.ts b/packages/jsx/src/types.ts
index 71c2e806..979b41cf 100644
--- a/packages/jsx/src/types.ts
+++ b/packages/jsx/src/types.ts
@@ -570,6 +570,41 @@ export type RectProps = CommonProps & FillProps & {
children?: SolidJSX.Element;
};
+/** `<ellipse>` — an ellipse inscribed in its box. Takes the same children as `<rect>`. */
+export type EllipseProps = CommonProps & FillProps & {
+ /**
+ * Makes the ellipse a clip path of its parent, as `<rect clipPath>` does:
+ * the parent shows only inside the curve. Never rendered or hit.
+ */
+ clipPath?: boolean;
+ /**
+ * Paint children (`<SolidPaint>`, `<LinearGradientPaint>`,
+ * `<RadialGradientPaint>`, `<AngularGradientPaint>`), plus `<Stroke>`, `<Shadow>`, `<Effect>`,
+ * `<Animation>` and `<KeyframeTrack>` children.
+ */
+ children?: SolidJSX.Element;
+};
+
+/**
+ * `<polygon>` — a regular polygon stretched to fill its box, its first
+ * corner at the top center: a triangle by default.
+ */
+export type PolygonProps = CommonProps & FillProps & {
+ /** How many corners, a whole number of at least 3. Default 3. */
+ pointCount?: number;
+ /**
+ * Makes the polygon a clip path of its parent, as `<rect clipPath>` does:
+ * the parent shows only inside its outline. Never rendered or hit.
+ */
+ clipPath?: boolean;
+ /**
+ * Paint children (`<SolidPaint>`, `<LinearGradientPaint>`,
+ * `<RadialGradientPaint>`, `<AngularGradientPaint>`), plus `<Stroke>`, `<Shadow>`, `<Effect>`,
+ * `<Animation>` and `<KeyframeTrack>` children.
+ */
+ children?: SolidJSX.Element;
+};
+
/**
* `<stroke>` — an outline of the parent's box (or glyphs), a sub-entity like a
* paint: `color` is its own solid paint, `width`/`join`/`cap`/`miterLimit` its
diff --git a/packages/reconciler/src/document.ts b/packages/reconciler/src/document.ts
index 219a6a1c..5af188de 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, 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 { 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, clampPointCount, 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, PointCount, 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';
@@ -533,6 +533,16 @@ export class RuntimeDocument implements ProjectDocument<SceneNode> {
resizeEntity(this.world, entity, { width: 100, height: 100 });
break;
}
+ case 'ellipse':
+ case 'polygon': {
+ entity = createEntity(this.world);
+ entity.add(Geometry);
+ entity.set(Geometry, { value: name === 'ellipse' ? GeometryType.ELLIPSE : GeometryType.POLYGON });
+ entity.add(Position);
+ entity.set(Position, { x: 0, y: 0 });
+ resizeEntity(this.world, entity, { width: 100, height: 100 });
+ break;
+ }
case 'text': {
// No Size: a text without one sizes itself to its glyphs.
entity = createEntity(this.world);
@@ -959,6 +969,17 @@ export class RuntimeDocument implements ProjectDocument<SceneNode> {
this.syncCornerRadii(node);
return;
}
+ case 'pointCount': {
+ if (entity.get(Geometry)?.value !== GeometryType.POLYGON) return;
+ const count = toNumber(value);
+ if (count === undefined) {
+ entity.remove(PointCount);
+ } else {
+ entity.add(PointCount);
+ entity.set(PointCount, { value: clampPointCount(count) });
+ }
+ return;
+ }
case 'blendMode': {
const mode = typeof value === 'string' ? BLEND_MODES[value] : undefined;
if (mode === undefined || mode === BlendModeType.SOURCE_OVER) {
diff --git a/packages/reconciler/src/elements.ts b/packages/reconciler/src/elements.ts
index 3c371c4c..fa031cc6 100644
--- a/packages/reconciler/src/elements.ts
+++ b/packages/reconciler/src/elements.ts
@@ -25,6 +25,7 @@ import type {
CaptionsProps,
ColorStopProps,
EffectProps,
+ EllipseProps,
MaskProps,
LinearGradientPaintProps,
RadialGradientPaintProps,
@@ -36,6 +37,7 @@ import type {
KeyframeProps,
KeyframeTrackProps,
MediaPaintProps,
+ PolygonProps,
RectProps,
SceneProps,
SequenceProps,
@@ -92,6 +94,8 @@ export const Stage = hostElement<StageProps>("Stage");
export const Scene = hostElement<SceneProps>("Scene");
export const Group = hostElement<GroupProps>("Group");
export const Rect = hostElement<RectProps>("Rect");
+export const Ellipse = hostElement<EllipseProps>("Ellipse");
+export const Polygon = hostElement<PolygonProps>("Polygon");
export const Video = hostElement<VideoProps>("Video");
export const Image = hostElement<ImageProps>("Image");
export const Audio = hostElement<AudioProps>("Audio");
diff --git a/packages/runtime/src/constants.ts b/packages/runtime/src/constants.ts
index eef32c9e..7118be10 100644
--- a/packages/runtime/src/constants.ts
+++ b/packages/runtime/src/constants.ts
@@ -68,6 +68,8 @@ export enum ConstraintType {
export enum GeometryType {
RECT,
TEXT,
+ ELLIPSE,
+ POLYGON,
}
export enum PaintType {
@@ -185,4 +187,6 @@ export enum ToolType {
LINEAR_GRADIENT,
RADIAL_GRADIENT,
ANGULAR_GRADIENT,
+ ELLIPSE,
+ POLYGON,
}
diff --git a/packages/runtime/src/math/index.ts b/packages/runtime/src/math/index.ts
index 7366f8d0..5259ec30 100644
--- a/packages/runtime/src/math/index.ts
+++ b/packages/runtime/src/math/index.ts
@@ -5,3 +5,4 @@
export * from './common';
export * from './matrix2d';
export * from './aabb';
+export * from './shape';
diff --git a/packages/runtime/src/math/shape.ts b/packages/runtime/src/math/shape.ts
new file mode 100644
index 00000000..f8d49468
--- /dev/null
+++ b/packages/runtime/src/math/shape.ts
@@ -0,0 +1,93 @@
+/* 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/. */
+
+// The outlines of the box-drawn shapes (ellipse, polygon) in their own
+// `w` × `h` box, px from its top-left. Shared by the renderer, the hit test
+// and an editor's draw preview so all three agree on where the edge is.
+
+import { GeometryType } from '../constants';
+
+import type { Point } from './aabb';
+
+/** The fewest corners a polygon has; fewer is not a polygon. */
+export const MIN_POLYGON_POINTS = 3;
+
+/** A polygon's corner count as the renderer takes it: a whole number, at least 3. */
+export function clampPointCount(count: number): number {
+ return Number.isFinite(count) ? Math.max(MIN_POLYGON_POINTS, Math.round(count)) : MIN_POLYGON_POINTS;
+}
+
+/**
+ * The corners of a regular polygon stretched to fill a `w` × `h` box, its
+ * first corner at the top and the rest clockwise from there: a triangle is
+ * apex up, base along the bottom edge.
+ */
+export function polygonVertices(count: number, w: number, h: number): Point[] {
+ const n = clampPointCount(count);
+ const unit: Point[] = [];
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+
+ for (let i = 0; i < n; i++) {
+ const angle = -Math.PI / 2 + (2 * Math.PI * i) / n;
+ const x = Math.cos(angle);
+ const y = Math.sin(angle);
+ unit.push({ x, y });
+ minX = Math.min(minX, x);
+ minY = Math.min(minY, y);
+ maxX = Math.max(maxX, x);
+ maxY = Math.max(maxY, y);
+ }
+
+ const sx = w / (maxX - minX);
+ const sy = h / (maxY - minY);
+ return unit.map(({ x, y }) => ({ x: (x - minX) * sx, y: (y - minY) * sy }));
+}
+
+/**
+ * Traces the outline of an ellipse or polygon onto `path` as a closed
+ * subpath (the caller begins the path). Rects are traced by the renderer,
+ * which knows their corner radii.
+ */
+export function traceShape(path: CanvasPath, type: GeometryType, w: number, h: number, pointCount: number): void {
+ switch (type) {
+ case GeometryType.ELLIPSE: {
+ path.ellipse(w / 2, h / 2, w / 2, h / 2, 0, 0, Math.PI * 2);
+ path.closePath();
+ return;
+ }
+ case GeometryType.POLYGON: {
+ const vertices = polygonVertices(pointCount, w, h);
+ path.moveTo(vertices[0]!.x, vertices[0]!.y);
+ for (let i = 1; i < vertices.length; i++) path.lineTo(vertices[i]!.x, vertices[i]!.y);
+ path.closePath();
+ return;
+ }
+ default:
+ path.rect(0, 0, w, h);
+ }
+}
+
+/** Whether a point in the shape's box (px from its top-left) is inside the ellipse or polygon. */
+export function pointInShape(type: GeometryType, x: number, y: number, w: number, h: number, pointCount: number): boolean {
+ if (type === GeometryType.ELLIPSE) {
+ if (w <= 0 || h <= 0) return false;
+ const dx = (x - w / 2) / (w / 2);
+ const dy = (y - h / 2) / (h / 2);
+ return dx * dx + dy * dy <= 1;
+ }
+
+ if (type === GeometryType.POLYGON) {
+ const vertices = polygonVertices(pointCount, w, h);
+ let inside = false;
+ for (let i = 0, j = vertices.length - 1; i < vertices.length; j = i++) {
+ const a = vertices[i]!, b = vertices[j]!;
+ if (((a.y > y) !== (b.y > y)) && (x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x)) {
+ inside = !inside;
+ }
+ }
+ return inside;
+ }
+
+ return x >= 0 && x <= w && y >= 0 && y <= h;
+}
diff --git a/packages/runtime/src/queries/interaction.ts b/packages/runtime/src/queries/interaction.ts
index 4f3fd63c..409adf0f 100644
--- a/packages/runtime/src/queries/interaction.ts
+++ b/packages/runtime/src/queries/interaction.ts
@@ -13,14 +13,15 @@
import { Not, Or } from 'koota';
import {
- Anchor, Computed, Geometry, Group, LocalTransform, Offset, Selected,
+ Anchor, Computed, Geometry, Group, LocalTransform, Offset, PointCount, Selected,
Sequential, WorldBounds, WorldTransform,
} from '../traits';
+import { GeometryType } from '../constants';
import { store } from '../world/store';
import { isStage } from './predicates';
import { getViewMatrix } from './camera';
import {
- decompose2D, identity2D, invert2D, multiply2D, rectToQuad, rotate2D,
+ decompose2D, identity2D, invert2D, multiply2D, pointInShape, rectToQuad, rotate2D,
scale2D, skew2D, transformPoint, translate2D,
} from '../math';
@@ -101,8 +102,17 @@ export function isPointerInEntity(world: World, entity: Entity, point: Point): b
const originX = computed.originX[eid] ?? 0;
const originY = computed.originY[eid] ?? 0;
- return local.x >= originX && local.x <= originX + (computed.width[eid] ?? 0)
- && local.y >= originY && local.y <= originY + (computed.height[eid] ?? 0);
+ const width = computed.width[eid] ?? 0;
+ const height = computed.height[eid] ?? 0;
+
+ const type = entity.has(Geometry) ? store(world, Geometry).value[eid] : undefined;
+ if (type === GeometryType.ELLIPSE || type === GeometryType.POLYGON) {
+ const pointCount = entity.has(PointCount) ? store(world, PointCount).value[eid]! : 3;
+ return pointInShape(type, local.x - originX, local.y - originY, width, height, pointCount);
+ }
+
+ return local.x >= originX && local.x <= originX + width
+ && local.y >= originY && local.y <= originY + height;
}
/** The entities a selection mask spans: sequences are not spatial, so they never do. */
diff --git a/packages/runtime/src/queries/predicates.ts b/packages/runtime/src/queries/predicates.ts
index a41e351c..72aa581b 100644
--- a/packages/runtime/src/queries/predicates.ts
+++ b/packages/runtime/src/queries/predicates.ts
@@ -50,10 +50,26 @@ export function isRect(entity: Entity): boolean {
return entity.get(Geometry)?.value === GeometryType.RECT;
}
-/** A vanilla rect — not a container (group/scene/sequence) or audio clip.
- * (Captions live on TEXT geometry, so they're naturally excluded.) */
+export function isEllipse(entity: Entity): boolean {
+ return entity.get(Geometry)?.value === GeometryType.ELLIPSE;
+}
+
+export function isPolygon(entity: Entity): boolean {
+ return entity.get(Geometry)?.value === GeometryType.POLYGON;
+}
+
+/** Whether a geometry draws a filled and stroked outline: everything but text. */
+export function isShapeGeometry(type: GeometryType | undefined): boolean {
+ return type === GeometryType.RECT
+ || type === GeometryType.ELLIPSE
+ || type === GeometryType.POLYGON;
+}
+
+/** A vanilla shape (rect, ellipse or polygon) — not a container
+ * (group/scene/sequence) or audio clip. (Captions live on TEXT geometry, so
+ * they're naturally excluded.) */
export function isShape(entity: Entity): boolean {
- return entity.get(Geometry)?.value === GeometryType.RECT
+ return isShapeGeometry(entity.get(Geometry)?.value)
&& !entity.has(Group)
&& !entity.has(Scene)
&& !entity.has(Audio);
diff --git a/packages/runtime/src/systems/render.ts b/packages/runtime/src/systems/render.ts
index e7089d9e..5b77e8be 100644
--- a/packages/runtime/src/systems/render.ts
+++ b/packages/runtime/src/systems/render.ts
@@ -19,7 +19,7 @@ import {
import {
ChildOf, Hidden, Culled, Interactive, IsClipPath, AssetId,
ClipsContent, Geometry, Group, Paint, Color, Caption, ScaleMode, Shader,
- BlendMode, Effect, Mask, Transition, MixedCornerRadius,
+ BlendMode, Effect, Mask, Transition, MixedCornerRadius, PointCount,
LocalTransform, WorldTransform, Computed, Cache,
Host, Scene, Shimmering,
Mode, FrameRate, Camera, Background, RenderSurface,
@@ -27,6 +27,8 @@ import {
Root, Time,
} from '../traits';
import { getParentNode } from '../queries/hierarchy';
+import { isShapeGeometry } from '../queries/predicates';
+import { traceShape } from '../math';
import { getViewMatrix } from '../queries/camera';
import { colorToHex } from '../utils/color';
import { FAILED_COLOR, getSourceFailure } from '../utils/source-failure';
@@ -60,13 +62,27 @@ function getCtx(world: World): Ctx2D {
return getSurfaceContext(world)!;
}
-export function drawRectPath(world: World, entity: Entity): void {
+/**
+ * Begins the current path with the outline of `entity` in its own box: a
+ * rect with its corner radii, or the ellipse, line or polygon its geometry
+ * names. Everything that fills, strokes or clips by the node's shape reads it
+ * from here.
+ */
+export function drawShapePath(world: World, entity: Entity): void {
const ctx = getCtx(world);
const computed = store(world, Computed);
const eid = entity.id();
const w = computed.width[eid]!;
const h = computed.height[eid]!;
+ const type = entity.has(Geometry) ? store(world, Geometry).value[eid]! : GeometryType.RECT;
+ if (type !== GeometryType.RECT && isShapeGeometry(type)) {
+ const pointCount = entity.has(PointCount) ? store(world, PointCount).value[eid]! : 3;
+ ctx.beginPath();
+ traceShape(ctx, type, w, h, pointCount);
+ return;
+ }
+
const hasMixed = entity.has(MixedCornerRadius);
let tl = hasMixed ? computed.cornerRadiusTopLeft[eid]! : computed.cornerRadius[eid]!;
let tr = hasMixed ? computed.cornerRadiusTopRight[eid]! : tl;
@@ -807,7 +823,7 @@ function renderWaveform(world: World, entity: Entity, fill: Entity): void {
}
function renderShapeNode(world: World, entity: Entity): void {
- drawRectPath(world, entity);
+ drawShapePath(world, entity);
renderShadows(world, entity);
renderIntrinsicFill(world, entity);
renderFills(world, entity);
@@ -973,7 +989,7 @@ function clipTo(world: World, clipPath: Entity): void {
const ctx = getCtx(world);
ctx.save();
setWorldTransform(world, ctx, clipPath);
- drawRectPath(world, clipPath);
+ drawShapePath(world, clipPath);
ctx.restore();
ctx.clip();
}
@@ -1007,7 +1023,7 @@ function renderContent(world: World, entity: Entity, effects: string | null): vo
renderCaptionNode(world, entity);
} else if (store(world, Geometry).value[eid] === GeometryType.TEXT) {
renderTextNode(world, entity);
- } else if (store(world, Geometry).value[eid] === GeometryType.RECT) {
+ } else if (isShapeGeometry(store(world, Geometry).value[eid])) {
renderShapeNode(world, entity);
}
@@ -1201,7 +1217,7 @@ function applyMaskedEffect(world: World, entity: Entity, pass: Extract<EffectPas
try {
resetLayer(coverage, local);
- drawOnto(coverage.ctx, () => drawRectPath(world, entity));
+ drawOnto(coverage.ctx, () => drawShapePath(world, entity));
coverage.ctx.fillStyle = '#000000';
coverage.ctx.fill();
for (const mask of pass.masks) {
@@ -1254,7 +1270,7 @@ function drawMaskRemoval(world: World, entity: Entity, mask: Entity, layer: Laye
const { ctx } = layer;
resetLayer(layer, local);
ctx.save();
- drawOnto(ctx, () => drawRectPath(world, entity));
+ drawOnto(ctx, () => drawShapePath(world, entity));
if (!inverted) {
ctx.fillStyle = '#000000';
ctx.fill();
diff --git a/packages/runtime/src/traits/node.ts b/packages/runtime/src/traits/node.ts
index 37c2c4c7..23dde3e5 100644
--- a/packages/runtime/src/traits/node.ts
+++ b/packages/runtime/src/traits/node.ts
@@ -7,7 +7,7 @@ import { trait } from 'koota';
import { GeometryType, PaintType, CaptionType, CaptionAlign } from '../constants';
-// Geometric primitive: RECT or TEXT (see GeometryType). Other node-like roles
+// Geometric primitive: RECT, ELLIPSE, POLYGON or TEXT (see GeometryType). Other node-like roles
// (group, audio, scene, caption) are layered on top via tag traits.
export const Geometry = trait({ value: GeometryType.RECT as GeometryType });
diff --git a/packages/runtime/src/traits/style.ts b/packages/runtime/src/traits/style.ts
index c7b958c9..f01ca7fc 100644
--- a/packages/runtime/src/traits/style.ts
+++ b/packages/runtime/src/traits/style.ts
@@ -27,6 +27,9 @@ export const MixedCornerRadius = trait({
bottomLeft: 0,
});
+// A polygon's corner count, at least 3 (see `clampPointCount`). Absent means 3.
+export const PointCount = trait({ value: 3 });
+
export const Blur = trait({ value: 0 });
// Scale mode for image fills and any other scaled asset display.
diff --git a/packages/runtime/src/world/serialize.ts b/packages/runtime/src/world/serialize.ts
index 7a33e481..051dbe58 100644
--- a/packages/runtime/src/world/serialize.ts
+++ b/packages/runtime/src/world/serialize.ts
@@ -9,7 +9,7 @@ import {
Caption,
Position, Offset, Rotation, Scale, UniformScale, Anchor, Skew, Size, Flip,
Constraint, KeepAspectRatio,
- Opacity, BlendMode, Color, CornerRadius, MixedCornerRadius, Blur, ScaleMode, Effect, Mask,
+ Opacity, BlendMode, Color, CornerRadius, MixedCornerRadius, PointCount, Blur, ScaleMode, Effect, Mask,
ColorStop, LinearGradient, EllipticalGradient, StrokeStyle, Shader,
Chars, TextStyle,
Delay, Trim, PlaybackRate, SourceFrameRate,
@@ -107,6 +107,7 @@ export interface EntityRecord {
bottomRight: number;
bottomLeft: number;
};
+ PointCount?: number;
Color?: number;
Blur?: number;
AssetId?: string;
@@ -299,6 +300,9 @@ export function serializeEntity(entity: Entity): EntityRecord {
if (entity.has(CornerRadius)) {
record.CornerRadius = entity.get(CornerRadius)!.value;
}
+ if (entity.has(PointCount)) {
+ record.PointCount = entity.get(PointCount)!.value;
+ }
if (entity.has(MixedCornerRadius)) {
const radius = entity.get(MixedCornerRadius)!;
record.MixedCornerRadius = {
@@ -558,6 +562,10 @@ export function deserializeEntity(entity: Entity, e: Partial<EntityRecord>): voi
entity.add(CornerRadius);
entity.set(CornerRadius, { value: e.CornerRadius });
}
+ if (e.PointCount !== undefined) {
+ entity.add(PointCount);
+ entity.set(PointCount, { value: e.PointCount });
+ }
if (e.MixedCornerRadius !== undefined) {
entity.add(MixedCornerRadius);
entity.set(MixedCornerRadius, defined(e.MixedCornerRadius));