The VS Code of video editing, built for agents.
TypeScript
Add PivotRow component and integrate pivot functionality into transform settings
konstantin-paulus2c736e5f4ad6
diff --git a/apps/web/src/components/sidebar-right/inspector/transform/pivot-row.tsx b/apps/web/src/components/sidebar-right/inspector/transform/pivot-row.tsxnew file mode 100644index 00000000..6c192a9e--- /dev/null+++ b/apps/web/src/components/sidebar-right/inspector/transform/pivot-row.tsx@@ -0,0 +1,95 @@+/* 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 { ControlRow } from "@/components/ui/control-group";+import { Icon } from "@/components/ui/icon";+import { ControlledTextField } from "@/components/ui/text-field";+import {+ ContextMenu,+ ContextMenuTrigger,+ ContextMenuContent,+ ContextMenuItem,+} from "@/components/ui/context-menu";+import { useTrait, useWorld } from "@diffusionstudio/koota-solid";+import { Computed, Pivot, isGroup, store } from "@diffusionstudio/runtime";+import { useEditor } from "@/engine/hooks";++import type { Entity } from "koota";++export type PivotRowProps = {+ node: Entity;+ onRemoveAddon(): void;+};++const round2 = (value: number): number => Math.round(value * 100) / 100;++/**+ * `pivotX`/`pivotY`: the point rotation, scale and skew turn about, px in+ * the node's own space. Shown in place of the anchor for a group, which has+ * no box of its own to take a fraction of, and for a node given a pivot.+ * Resetting a group puts its pivot back at the center of what it holds now;+ * resetting any other node unsets it, and the node turns about its anchor+ * again.+ */+export function PivotRow(props: PivotRowProps) {+ const world = useWorld();+ const editor = useEditor();+ const pivot = useTrait(() => props.node, Pivot);+ const pivotX = () => round2(pivot()?.x ?? 0);+ const pivotY = () => round2(pivot()?.y ?? 0);++ const updatePivotX = (x: number) => editor.editProperty(props.node, 'pivotX', x);+ const updatePivotY = (y: number) => editor.editProperty(props.node, 'pivotY', y);++ const reset = () => {+ const node = props.node;+ if (!isGroup(node)) {+ editor.editProperty(node, 'pivotX', false);+ editor.editProperty(node, 'pivotY', false);+ return;+ }++ // The box the transform system last built from the children, in the+ // group's own space.+ const computed = store(world, Computed);+ const eid = node.id();+ updatePivotX(round2((computed.originX[eid] ?? 0) + (computed.width[eid] ?? 0) / 2));+ updatePivotY(round2((computed.originY[eid] ?? 0) + (computed.height[eid] ?? 0) / 2));+ };++ return (+ <ContextMenu>+ <ContextMenuTrigger<typeof ControlRow>+ as={ControlRow}+ label="Pivot"+ contentClass="grid grid-cols-2 gap-2"+ >+ <ControlledTextField+ icon={<Icon name="prop-x-position" />}+ value={pivotX()}+ onNumber={updatePivotX}+ step={1}+ autoSelect+ sliderEnabled+ />+ <ControlledTextField+ icon={<Icon name="prop-y-position" />}+ value={pivotY()}+ onNumber={updatePivotY}+ step={1}+ autoSelect+ sliderEnabled+ />+ </ContextMenuTrigger>+ <ContextMenuContent>+ <ContextMenuItem onSelect={reset}>+ {isGroup(props.node) ? "Center Pivot" : "Reset to Anchor"}+ </ContextMenuItem>+ <ContextMenuItem onSelect={props.onRemoveAddon}>+ Remove row+ </ContextMenuItem>+ </ContextMenuContent>+ </ContextMenu>+ );+}diff --git a/apps/web/src/components/sidebar-right/inspector/transform/transform-settings.tsx b/apps/web/src/components/sidebar-right/inspector/transform/transform-settings.tsxindex 0bc1d988..e9d9efbe 100644--- a/apps/web/src/components/sidebar-right/inspector/transform/transform-settings.tsx+++ b/apps/web/src/components/sidebar-right/inspector/transform/transform-settings.tsx@@ -16,11 +16,13 @@ import {DropdownMenuItem,} from "@/components/ui/dropdown-menu";import { Keyframe } from "@/components/ui/keyframe";-import { useWorld } from "@diffusionstudio/koota-solid";+import { useTrait, useWorld } from "@diffusionstudio/koota-solid";import {Computed,+ Pivot,getParentEntity,isAdjustmentLayer,+ isGroup,isScene,isSequence,} from "@diffusionstudio/runtime";@@ -28,6 +30,7 @@ import { useDerived, useEditor } from "@/engine/hooks";import { syncKeyframe } from "@/engine/keyframes";import { RotateRow } from "./rotate-row";import { AnchorRow } from "./anchor-row";+import { PivotRow } from "./pivot-row";import { OffsetRow } from "./offset-row";import { ScaleRow } from "./scale-row";import { SkewRow } from "./skew-row";@@ -47,11 +50,13 @@ type TransformAddons = Partial<Record<TransformAddon, boolean>>;/*** Where a node sits and how it is transformed there. Position, rotation,* offset, scale and constraints are props (`x`/`y`, `rotation`,- * `offsetX`/`offsetY`, `scale` or `scaleX`/`scaleY`,+ * `offsetX`/`offsetY`, `scale` or `scaleX`/`scaleY`, `pivotX`/`pivotY`,* `constrainX`/`constrainY`) written through the editor; anchor, flip and* skew have no JSX spelling and are written to their traits alone, so they do- * not survive a recompile. The rows below Position are opt-in and which ones- * are shown is app state, kept per user rather than per node.+ * not survive a recompile. A pivot replaces the anchor: a group always turns+ * about one, any other node once it has one, and the anchor slot shows it+ * instead. The rows below Position are opt-in and which ones are shown is app+ * state, kept per user rather than per node.*/export function TransformSettings(props: TransformSettingsProps) {const world = useWorld();@@ -62,6 +67,9 @@ export function TransformSettings(props: TransformSettingsProps) {store.define<TransformAddons>('transform.addons', {}));+ const pivot = useTrait(() => entity(), Pivot);+ const usesPivot = () => isGroup(entity()) || pivot() !== undefined;+const positionX = useDerived(() => entity().get(Computed)?.positionX ?? 0);const positionY = useDerived(() => entity().get(Computed)?.positionY ?? 0);@@ -131,7 +139,7 @@ export function TransformSettings(props: TransformSettingsProps) {</Show><Show when={!showAddon('anchor')}><DropdownMenuItem onSelect={() => toggleAddon('anchor', true)}>- Anchor+ {usesPivot() ? 'Pivot' : 'Anchor'}</DropdownMenuItem></Show><Show when={!showAddon('offset')}>@@ -188,7 +196,12 @@ export function TransformSettings(props: TransformSettingsProps) {</Show><Show when={showAddon('anchor')}>- <AnchorRow node={entity()} onRemoveAddon={() => toggleAddon('anchor', false)} />+ <Show+ when={usesPivot()}+ fallback={<AnchorRow node={entity()} onRemoveAddon={() => toggleAddon('anchor', false)} />}+ >+ <PivotRow node={entity()} onRemoveAddon={() => toggleAddon('anchor', false)} />+ </Show></Show><Show when={showAddon('offset')}>diff --git a/apps/web/src/engine/clip-path.ts b/apps/web/src/engine/clip-path.tsindex fd268e98..a7f1e267 100644--- a/apps/web/src/engine/clip-path.ts+++ b/apps/web/src/engine/clip-path.ts@@ -9,7 +9,7 @@ import {Tool,ToolType,decompose2D,- entityAnchor,+ entityPivot,entityOffset,entityWorldMat,getEntityTree,@@ -96,13 +96,13 @@ export function applyClipPaths(world: World): void {const eid = shape.id();const width = computed.width[eid] ?? 0;const height = computed.height[eid] ?? 0;- const anchor = entityAnchor(world, shape);+ const pivot = entityPivot(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, shape), translate2D(anchor.x * width, anchor.y * height)),+ multiply2D(entityWorldMat(world, shape), translate2D(pivot.x, pivot.y)),));if (!editor.reparent(shape, target)) continue;@@ -115,8 +115,9 @@ export function applyClipPaths(world: World): void {const nextHeight = ownY === 0 ? height : Math.round(height * Math.abs(placed.scaleY / ownY));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 nextPivot = entityPivot(world, shape, nextWidth, nextHeight);+ const x = Math.round(placed.x - nextPivot.x - offset.x);+ const y = Math.round(placed.y - nextPivot.y - offset.y);const rotation = round2(placed.rotation);const writes: TransformWrite[] = [];diff --git a/apps/web/src/engine/group.tsx b/apps/web/src/engine/group.tsxindex 1a6e6fc5..6f970415 100644--- a/apps/web/src/engine/group.tsx+++ b/apps/web/src/engine/group.tsx@@ -19,7 +19,7 @@ import {aabbFromTransformedRect,computeLocalMatrix,decompose2D,- entityAnchor,+ entityPivot,entityLocalMat,entityOffset,framesToSeconds,@@ -63,16 +63,31 @@ function isIdentity(mat: Mat2D): boolean {* Puts the selection into a new group where it stands. The group is authored* with no transform of its own, so the members keep the coordinates they had* and nothing moves; its box is derived from theirs (see `computeGroupBounds`),- * so there is no size to author either. Only the members sharing the first- * one's parent go in — a wrap has one place to put things (see `wrap`). The- * selection moves to the group.+ * so there is no size to author either. What it is authored with is a pivot+ * at the members' center as they stand now — the group's space being their+ * parent's, their box's center is the pivot as is — fixed from here on, so+ * the group turns about the same point however its contents change later.+ * Only the members sharing the first one's parent go in — a wrap has one+ * place to put things (see `wrap`). The selection moves to the group.*/export function groupSelection(world: World): void {const editor = getDocumentEditor(world);- const selected = [...world.query(Selected, NODES, Not(IsClipPath))];- if (!selected.length) return;+ const selected = new Set(world.query(Selected, NODES, Not(IsClipPath)));+ const first = [...selected][0];+ if (!first) return;++ const parent = getParentEntity(first);+ if (!parent) return;- const group = editor.wrap(selected, () => <GroupElement name={getNextName(world, 'Group')} />);+ // The same members `wrap` will take.+ const members = getEntityChildren(world, parent).filter((entity) => selected.has(entity));+ const box = measure(world, members.flatMap((member) => spatialLeaves(world, member)));+ const pivotX = box ? round2((box.minX + box.maxX) / 2) : undefined;+ const pivotY = box ? round2((box.minY + box.maxY) / 2) : undefined;++ const group = editor.wrap([...selected], () => (+ <GroupElement name={getNextName(world, 'Group')} pivotX={pivotX} pivotY={pivotY} />+ ));if (group) editor.select(group);}@@ -115,6 +130,37 @@ function spatialLeaves(world: World, entity: Entity): Entity[] {return nodeChildren(world, entity).flatMap((child) => spatialLeaves(world, child));}+/**+ * The upright box `entities` make in their parent's space, or null for none.+ */+function measure(world: World, entities: Entity[]): { minX: number; minY: number; maxX: number; maxY: number } | null {+ if (!entities.length) return null;++ const computed = store(world, Computed);+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;++ for (const entity of entities) {+ const eid = entity.id();+ computeLocalMatrix(world, entity);+ // The box the way computeWorldBounds frames it: the origin folded into+ // the matrix, so a group's children-derived rect sits where it is drawn.+ const bounds = aabbFromTransformedRect(+ multiply2D(entityLocalMat(world, entity), translate2D(computed.originX[eid] ?? 0, computed.originY[eid] ?? 0)),+ computed.width[eid] ?? 0,+ computed.height[eid] ?? 0,+ );+ if (bounds.minX < minX) minX = bounds.minX;+ if (bounds.minY < minY) minY = bounds.minY;+ if (bounds.maxX > maxX) maxX = bounds.maxX;+ if (bounds.maxY > maxY) maxY = bounds.maxY;+ }++ return { minX, minY, maxX, maxY };+}+/*** Puts the selection into a new scene. Unlike a group or a sequence, a scene* has a place and a size of its own, so it is authored around the members —@@ -140,34 +186,14 @@ export function wrapSelectionInScene(world: World): void {// parent's children.const members = getEntityChildren(world, parent).filter((entity) => selected.has(entity));const measured = members.flatMap((member) => spatialLeaves(world, member));- if (!measured.length) return;+ const box = measure(world, measured);+ if (!box) return;const computed = store(world, Computed);- let minX = Infinity;- let minY = Infinity;- let maxX = -Infinity;- let maxY = -Infinity;-- for (const entity of measured) {- const eid = entity.id();- computeLocalMatrix(world, entity);- // The box the way computeWorldBounds frames it: the origin folded into- // the matrix, so a group's children-derived rect sits where it is drawn.- const bounds = aabbFromTransformedRect(- multiply2D(entityLocalMat(world, entity), translate2D(computed.originX[eid] ?? 0, computed.originY[eid] ?? 0)),- computed.width[eid] ?? 0,- computed.height[eid] ?? 0,- );- if (bounds.minX < minX) minX = bounds.minX;- if (bounds.minY < minY) minY = bounds.minY;- if (bounds.maxX > maxX) maxX = bounds.maxX;- if (bounds.maxY > maxY) maxY = bounds.maxY;- }-- const x = Math.floor(minX);- const y = Math.floor(minY);- const width = Math.max(1, Math.ceil(maxX) - x);- const height = Math.max(1, Math.ceil(maxY) - y);+ const x = Math.floor(box.minX);+ const y = Math.floor(box.minY);+ const width = Math.max(1, Math.ceil(box.maxX) - x);+ const height = Math.max(1, Math.ceil(box.maxY) - y);const scene = editor.wrap([...selected], () => (<SceneElement name={getNextName(world, 'Scene')} x={x} y={y} width={width} height={height} />@@ -282,9 +308,7 @@ function bakeContainerInto(if (containerLocal) {computeLocalMatrix(world, child);- const anchor = entityAnchor(world, child);- const pivotX = anchor.x * (computed.width[cid] ?? 0);- const pivotY = anchor.y * (computed.height[cid] ?? 0);+ const { x: pivotX, y: pivotY } = entityPivot(world, child);// The pivot folded in before decomposing, as `resizeNode` folds// it: the translation that comes out is position + pivot, cleardiff --git a/apps/web/src/engine/input/interactions.ts b/apps/web/src/engine/input/interactions.tsindex 1aa37df8..211b8c89 100644--- a/apps/web/src/engine/input/interactions.ts+++ b/apps/web/src/engine/input/interactions.ts@@ -20,7 +20,7 @@ import {ChildOf, Computed, Culled, Geometry, Group, Hovering,Interactive, KeepAspectRatio, RenderSurface, Root, Scene,Selected, Skew, Time,- computeGroupBounds, computeLocalMatrix, decompose2D, entityAnchor,+ decompose2D, entityPivot,entityOffset, entityQuad, entityWorldMat, enterEntity,findKeyframeTrackEntity, getParentEntity, getParentNode, getSceneAncestor,getSelection, getSelectionMask, identity2D, invert2D, isPath, isPointerInEntity,@@ -447,8 +447,10 @@ export function handleResizeInteraction(world: World, event: DispatchedPointerEvconst localScale = scaleAbout(pivotX, pivotY, newWidth / snapshot.width, newHeight / snapshot.height);// Groups have no Size of their own, so a group resize transforms its- // direct children instead; the group's own transform is left alone and- // the transform system rebuilds its box from where the children ended up.+ // direct children instead; the group's own transform is left alone+ // (it turns about its pivot, not its box, so nothing about it moves)+ // and the transform system rebuilds its box from where the children+ // ended up.const hasGroup = selection.some((entity) => entity.has(Group));// The single-node wobble guard does not apply to a group's children:// they are scaled in the group's space, not their own, so their@@ -462,15 +464,6 @@ export function handleResizeInteraction(world: World, event: DispatchedPointerEvfor (const entity of targets) {resizeNode(world, entity, oldTr, localScale, writeAngles);-- // The walk is parent-first, so a group's box is built from its- // children's transforms as of the previous frame. Refresh this one- // now, or a rotated group's box lags a frame behind and drifts.- if (hasGroup) computeLocalMatrix(world, entity);- }-- if (selected.has(Group)) {- keepGroupPlaced(world, selected);}}@@ -496,14 +489,11 @@ function resizeNode(world: World, entity: Entity, oldTr: Mat2D, localScale: Mat2if (!snapshot) return;const editor = getDocumentEditor(world);- const anchor = entityAnchor(world, entity);+ const oldPivot = entityPivot(world, entity, snapshot.width, snapshot.height);// Take the pivot out of the old local transform: the decomposition puts it// back from the new size.- const oldLocal = multiply2D(- snapshot.localTransform,- translate2D(snapshot.width * anchor.x, snapshot.height * anchor.y),- );+ const oldLocal = multiply2D(snapshot.localTransform, translate2D(oldPivot.x, oldPivot.y));const decomposed = decompose2D(inParentSpace(oldTr, localScale, snapshot.parentTransform, oldLocal));@@ -512,12 +502,13 @@ function resizeNode(world: World, entity: Entity, oldTr: Mat2D, localScale: Mat2const width = snapshot.width * (decomposed.scaleX / snapshot.scaleX);const height = snapshot.height * (decomposed.scaleY / snapshot.scaleY);const offset = entityOffset(world, entity);+ const pivot = entityPivot(world, entity, width, height);const writes: TransformWrite[] = [['width', Math.round(width)],['height', Math.round(height)],- ['x', Math.round(decomposed.x - width * anchor.x - offset.x)],- ['y', Math.round(decomposed.y - height * anchor.y - offset.y)],+ ['x', Math.round(decomposed.x - pivot.x - offset.x)],+ ['y', Math.round(decomposed.y - pivot.y - offset.y)],];if (writeAngles) writes.push(['rotation', Math.round(decomposed.rotation * 100) / 100]);// A path's outline stretches with its box rather than staying put in it.@@ -536,40 +527,17 @@ function resizeNode(world: World, entity: Entity, oldTr: Mat2D, localScale: Mat2}/**- * Holds a resized group where the gesture found it. Its local matrix pivots- * about anchor x box size, and resizing the children moves that pivot; with a- * rotation, the (I - R)·pivot term then shifts the group's translation and- * drags the whole group off the pointer. The children were computed against- * the group's transform as of dragstart, so put it back.+ * Where `entity`'s pivot sits in the space of the selection mask `maskTr`,+ * as of the gesture's start: its own px, taken out through the transforms+ * snapshotted then and back in through the mask's.*/-function keepGroupPlaced(world: World, group: Entity): void {- const snapshot = getTransformSnapshot(group);- if (!snapshot) return;-- // Rebuild the box from the children that just moved, so the new pivot is- // the one the group will actually be drawn with.- computeGroupBounds(world, group);+function maskPivot(world: World, entity: Entity, maskTr: Mat2D): Point {+ const state = getTransformSnapshot(entity);+ if (!state) return { x: 0, y: 0 };- const computed = store(world, Computed);- const gid = group.id();- const anchor = entityAnchor(world, group);- const pivotX = anchor.x * (computed.width[gid] ?? 0);- const pivotY = anchor.y * (computed.height[gid] ?? 0);-- // computeLocalMatrix builds L = T(position) · K, K = T(pivot)·linear·T(-pivot).- // The resize leaves `linear` alone, so solve T(position) = L · K⁻¹ for the- // new pivot and the rebuilt matrix comes out equal to the snapshot again.- const desired = snapshot.localTransform;- const linear: Mat2D = { a: desired.a, b: desired.b, c: desired.c, d: desired.d, e: 0, f: 0 };- const position = multiply2D(desired, invert2D(scaleFree(pivotX, pivotY, linear)));- const offset = entityOffset(world, group);- const editor = getDocumentEditor(world);-- editTransform(world, editor, group, [- ['x', Math.round(position.e - offset.x)],- ['y', Math.round(position.f - offset.y)],- ]);- computeLocalMatrix(world, group);+ const pivot = entityPivot(world, entity, state.width, state.height);+ const placed = transformPoint(multiply2D(state.parentTransform, state.localTransform), pivot.x, pivot.y);+ return transformPoint(invert2D(maskTr), placed.x, placed.y);}/** A rotation handle, just outside a corner of the selection mask. */@@ -586,11 +554,11 @@ export function handleRotateInteraction(world: World, event: DispatchedPointerEvconst editor = getDocumentEditor(world);const selection = getSelection(world);- // One node turns about its own anchor, several about the center of the+ // One node turns about its own pivot, several about the center of the// box they share.- const single = selection.length === 1 ? entityAnchor(world, selection[0]!) : null;- const pivotX = snapshot.width * (single?.x ?? 0.5);- const pivotY = snapshot.height * (single?.y ?? 0.5);+ const { x: pivotX, y: pivotY } = selection.length === 1+ ? maskPivot(world, selection[0]!, oldTr)+ : { x: snapshot.width / 2, y: snapshot.height / 2 };const current = pointerPoint(world, oldTr);const origin = pointerOrigin(world, oldTr);@@ -603,10 +571,8 @@ export function handleRotateInteraction(world: World, event: DispatchedPointerEvconst state = getTransformSnapshot(entity);if (!state) continue;- const anchor = entityAnchor(world, entity);- const anchorX = state.width * anchor.x;- const anchorY = state.height * anchor.y;- const oldLocal = multiply2D(state.localTransform, translate2D(anchorX, anchorY));+ const own = entityPivot(world, entity, state.width, state.height);+ const oldLocal = multiply2D(state.localTransform, translate2D(own.x, own.y));let newLocal = inParentSpace(oldTr, localRotate, state.parentTransform, oldLocal);let decomposed = decompose2D(newLocal);@@ -614,10 +580,10 @@ export function handleRotateInteraction(world: World, event: DispatchedPointerEv// Shift snaps to global 15 degree steps. The snap has to turn about// the pivot the gesture used, and the position has to be re-derived// from the snapped matrix: reusing the unsnapped one works for a- // single node (its own matrix pivots about the same anchor, so its- // position is rotation-invariant) but a group's matrix pivots about- // its box center, which the mask's center is offset from, and the- // mask jumps.+ // single node (its own matrix pivots about the same point, so its+ // position is rotation-invariant) but several nodes turn about the+ // center of the box they share, which is none of their own pivots,+ // and the mask jumps.if (keys(world).has('shift')) {const snapped = Math.round(decomposed.rotation / 15) * 15;@@ -631,8 +597,8 @@ export function handleRotateInteraction(world: World, event: DispatchedPointerEvconst offset = entityOffset(world, entity);editTransform(world, editor, entity, [- ['x', Math.round(decomposed.x - anchorX - offset.x)],- ['y', Math.round(decomposed.y - anchorY - offset.y)],+ ['x', Math.round(decomposed.x - own.x - offset.x)],+ ['y', Math.round(decomposed.y - own.y - offset.y)],['rotation', Math.round(decomposed.rotation * 100) / 100],]);}@@ -724,10 +690,8 @@ export function handleMaskInteraction(world: World, event: DispatchedPointerEvenif (drop !== undefined) reparentTo(world, entity, drop);- const anchor = entityAnchor(world, entity);- const anchorX = state.width * anchor.x;- const anchorY = state.height * anchor.y;- const oldLocal = multiply2D(state.localTransform, translate2D(anchorX, anchorY));+ const own = entityPivot(world, entity, state.width, state.height);+ const oldLocal = multiply2D(state.localTransform, translate2D(own.x, own.y));// The snapshot is against the parent the drag started under, so a// node that changed parents mid-drag carries the correction that// undoes the difference between them.@@ -737,8 +701,8 @@ export function handleMaskInteraction(world: World, event: DispatchedPointerEvenconst offset = entityOffset(world, entity);editTransform(world, editor, entity, [- ['x', Math.round(decomposed.x - anchorX - offset.x)],- ['y', Math.round(decomposed.y - anchorY - offset.y)],+ ['x', Math.round(decomposed.x - own.x - offset.x)],+ ['y', Math.round(decomposed.y - own.y - offset.y)],]);}}@@ -911,11 +875,6 @@ function rotateAbout(x: number, y: number, degrees: number): Mat2D {return multiply2D(mat, translate2D(-x, -y));}-/** The pivot part of `computeLocalMatrix`: T(pivot) · linear · T(-pivot). */-function scaleFree(pivotX: number, pivotY: number, linear: Mat2D): Mat2D {- return multiply2D(multiply2D(translate2D(pivotX, pivotY), linear), translate2D(-pivotX, -pivotY));-}-/** A mask-space delta as the parent sees it: parent⁻¹ · mask · delta · mask⁻¹ · parent. */function inParent(parentTransform: Mat2D, deltaWorld: Mat2D): Mat2D {return multiply2D(multiply2D(invert2D(parentTransform), deltaWorld), parentTransform);diff --git a/apps/web/src/engine/path-tool.tsx b/apps/web/src/engine/path-tool.tsxindex 43b22558..acaa46ed 100644--- a/apps/web/src/engine/path-tool.tsx+++ b/apps/web/src/engine/path-tool.tsx@@ -21,9 +21,9 @@import { Path, Stroke } from '@diffusionstudio/reconciler';import {- Cache, Computed, HitRegions, Keyframe, LocalTransform, Position, RenderSurface, Root, Selected, Source, Tool, ToolType,- VectorPath, ViewBox,- entityAnchor, entityWorldMat, findSceneAt, formatPath, getNextName, getPathGeometry, getPathTransform,+ Cache, Computed, HitRegions, Keyframe, LocalTransform, Pivot, Position, RenderSurface, Root, Selected, Source, Tool,+ ToolType, VectorPath, ViewBox,+ entityPivot, entityWorldMat, findSceneAt, formatPath, getNextName, getPathGeometry, getPathTransform,getViewMatrix, identity2D, invert2D, isPath, multiply2D, nearestOnPath, pathBounds, pointInPath,pointOnPath, rectToQuad, removeVertex, screenToWorld, segmentCount, splitSegment, store, transformPath,transformPoint, unionPathBounds, vertexCount, worldToLocal,@@ -746,12 +746,19 @@ export function fitPathBox(world: World, editor: DocumentEditor, entity: Entity)if (tight) return;// The box's position moves by the shift as its linear part takes it, the- // pivot (anchor × size) moving with the new size: L(p) = pos + pivot + A(p − pivot).- const anchor = entityAnchor(world, entity);+ // pivot moving with the box: L(p) = pos + pivot + A(p − pivot). An anchor's+ // pivot is a fraction of the new size; a pivot of the path's own stays on+ // the point of the outline it was on, which the box's corner moved off by+ // the shift.+ const ownPivot = entity.has(Pivot);+ const oldPivot = entityPivot(world, entity, oldWidth, oldHeight);+ const newPivot = ownPivot+ ? { x: round2(oldPivot.x - shiftX), y: round2(oldPivot.y - shiftY) }+ : entityPivot(world, entity, width, height);const local = store(world, LocalTransform);const a = local.a[eid]!, b = local.b[eid]!, c = local.c[eid]!, d = local.d[eid]!;- const pivotX = anchor.x * (width - oldWidth);- const pivotY = anchor.y * (height - oldHeight);+ const pivotX = newPivot.x - oldPivot.x;+ const pivotY = newPivot.y - oldPivot.y;const vx = shiftX + pivotX;const vy = shiftY + pivotY;const position = entity.get(Position) ?? { x: 0, y: 0 };@@ -765,6 +772,11 @@ export function fitPathBox(world: World, editor: DocumentEditor, entity: Entity)editor.editProperty(keyframe, 'value', formatPath(transformPath(keyframe.get(Keyframe)!.path!, shift)));}+ if (ownPivot) {+ editor.editProperty(entity, 'pivotX', newPivot.x);+ editor.editProperty(entity, 'pivotY', newPivot.y);+ }+const writes: TransformWrite[] = [['width', width], ['height', height], ['x', x], ['y', y]];editTransform(world, editor, entity, writes);}diff --git a/docs/reference/jsx/adjustment-layer.md b/docs/reference/jsx/adjustment-layer.mdindex 964e6a65..8d7a9720 100644--- a/docs/reference/jsx/adjustment-layer.md+++ b/docs/reference/jsx/adjustment-layer.md@@ -32,8 +32,9 @@ Inside a [`<sequence>`](./sequences.md) the layer acts on what sits below the *s| ---- | ---- | ------- | ------- || `x`, `y` | `number` | `0` | Translation applied to the clip below, px. || `offsetX`, `offsetY` | `number` | `0` | Render-time translation on top of `x`/`y`, px. |-| `rotation` | `number` | `0` | Rotation in degrees, about the box centre. |-| `scale` | `number` | `1` | Uniform scale about the box centre. Overrides `scaleX`/`scaleY` while set. |+| `rotation` | `number` | `0` | Rotation in degrees, about the pivot. |+| `scale` | `number` | `1` | Uniform scale about the pivot. Overrides `scaleX`/`scaleY` while set. |+| `pivotX`, `pivotY` | `number` | box centre | The point the transform turns about, px from the box's top-left. || `scaleX`, `scaleY` | `number` | `1` | Per-axis scale. || `width`, `height` | `number` | `1920` × `1080` | **Never drawn**: the box the transform pivots around. Set them to the scene's own size on a frame shaped otherwise, so `rotation` and `scale` turn about its middle. || `hidden` | `boolean` | absent | Excludes the layer without removing it: the clip below is left alone and the layer keeps its place in the timeline. |diff --git a/docs/reference/jsx/elements.md b/docs/reference/jsx/elements.mdindex bf0493cd..665a5ce0 100644--- a/docs/reference/jsx/elements.md+++ b/docs/reference/jsx/elements.md@@ -94,8 +94,9 @@ Every node accepts:| `keepAspectRatio` | `boolean` | absent | Locks the box to its authored proportions: resizing one bound (an editor handle, a layout row) drives the other so the ratio `width`:`height` has is kept — or, with neither authored, the ratio the box currently has. || `constrainX` | `"left" \| "right" \| "center" \| "stretch" \| "scale"` | `"left"` | How the element follows its scene's frame when that frame is resized, horizontally — see below. || `constrainY` | `"top" \| "bottom" \| "center" \| "stretch" \| "scale"` | `"top"` | The same vertically. |-| `rotation` | `number` | `0` | Rotation in degrees. |-| `scale` | `number` | `1` | Uniform scale about the box origin. Overrides `scaleX`/`scaleY` while set. |+| `rotation` | `number` | `0` | Rotation in degrees, about the pivot. |+| `pivotX`, `pivotY` | `number` | box centre (`<group>`: `0`) | The point `rotation` and scale turn about, px in the element's own space — from its box's top-left, or for a [`<group>`](./group.md#pivot) in its children's coordinates — like SVG's `rotate(angle cx cy)`. An axis left out of a pivot that has the other is `0`. Not animatable. |+| `scale` | `number` | `1` | Uniform scale about the pivot. Overrides `scaleX`/`scaleY` while set. || `scaleX`, `scaleY` | `number` | `1` | Per-axis scale. || `opacity` | `number` | `1` | `0`–`1`; out-of-range values clamp, like CSS. || `cornerRadius` | `number` | `0` | Uniform corner radius, px. |diff --git a/docs/reference/jsx/group.md b/docs/reference/jsx/group.mdindex 7d5643f8..8d3cc74d 100644--- a/docs/reference/jsx/group.md+++ b/docs/reference/jsx/group.md@@ -10,10 +10,22 @@ A container with a transform but no box of its own: a group derives its bounds f## Props-A group takes the [common](./elements.md#common-props) **transform** (`x`, `y`, `offsetX`, `offsetY`, `rotation`, `scale`, `scaleX`, `scaleY`, `opacity`), **composite** (`blendMode`, `hidden`) and **timing** (`start`, `end`) props.+A group takes the [common](./elements.md#common-props) **transform** (`x`, `y`, `offsetX`, `offsetY`, `pivotX`, `pivotY`, `rotation`, `scale`, `scaleX`, `scaleY`, `opacity`), **composite** (`blendMode`, `hidden`) and **timing** (`start`, `end`) props.It has **no `fill`, no `width` and no `height`**, and takes no [paint children](./paints.md): its box is the union of its children's. `<effect>`, `<animation>` and `<keyframeTrack>` children are valid — an effect on a group filters the group as a whole.+## Pivot++A group turns about its **pivot** — `pivotX`/`pivotY`, px in its children's coordinates — not about its box. Without one it turns about its origin, as an SVG `<g>` does:++```tsx+<group x={100} y={100} rotation={45} pivotX={200} pivotY={150}>+ <rect x={100} y={100} width={200} height={100} />+</group>+```++The pivot is fixed where it is written: moving, adding or animating children never moves the point the group turns about. The editor's group action writes one at the center of the members as they stand when the group is made.+## TimingA group with no `end` of its own **spans its children**: it begins where the earliest one begins and ends where the last one ends, and follows them as they move. Give it an `end` and it trims them instead — children outside the window do not play. See [timing.md](./timing.md).diff --git a/packages/jsx/src/types.ts b/packages/jsx/src/types.tsindex f31cb956..5a377885 100644--- a/packages/jsx/src/types.ts+++ b/packages/jsx/src/types.ts@@ -255,7 +255,20 @@ type SizeProps = {keepAspectRatio?: boolean;};-type TransformProps = PositionProps & OffsetProps & SizeProps & {+type PivotProps = {+ /**+ * The point `rotation`, `scale` and skew turn about, px in the element's+ * own space (from its box's top-left; for a `<group>`, its children's+ * coordinates), like SVG's `rotate(angle cx cy)`. Absent, an element turns+ * about the center of its box and a `<group>` about its origin; the+ * editor's group action sets one at the members' center. An axis left out+ * of a pivot that has the other is 0.+ */+ pivotX?: number;+ pivotY?: number;+};++type TransformProps = PositionProps & OffsetProps & SizeProps & PivotProps & {/*** How the element follows its scene's frame when that frame is resized —* horizontally, then vertically. They are read only against a frame that@@ -268,7 +281,7 @@ type TransformProps = PositionProps & OffsetProps & SizeProps & {constrainY?: VerticalConstraint;/** Rotation in degrees. */rotation?: number;- /** Uniform scale about the box origin, 1 = natural size. Overrides `scaleX`/`scaleY` while set. */+ /** Uniform scale about the pivot, 1 = natural size. Overrides `scaleX`/`scaleY` while set. */scale?: number;/** Per-axis scale, 1 = natural size. */scaleX?: number;diff --git a/packages/reconciler/src/document.ts b/packages/reconciler/src/document.tsindex 0a8806b4..221a52e6 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, clampPointCount, createEntity, DEFAULT_BACKGROUND, Color, ColorStop, Delay, Effect, EffectType, EvenOdd, 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, parsePath, PathTrim, 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, VectorPath, ViewBox, 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, EvenOdd, 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, Pivot, Paint, PaintType, parseColor, parsePath, PathTrim, 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, VectorPath, ViewBox, 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';@@ -948,6 +948,25 @@ export class RuntimeDocument implements ProjectDocument<SceneNode> {entity.set(Scale, { [name === 'scaleX' ? 'x' : 'y']: toNumber(value) ?? 1 });return;}+ case 'pivotX':+ case 'pivotY': {+ const { entity, props } = node;+ if (entity.has(Sequential)) return;++ // One trait for both axes: absent, the node turns about its+ // anchor (a group about its origin), so an axis left out of a+ // pivot that has the other is 0, like an unset x.+ const x = toNumber(props.pivotX);+ const y = toNumber(props.pivotY);+ if (x === undefined && y === undefined) {+ entity.remove(Pivot);+ return;+ }++ entity.add(Pivot);+ entity.set(Pivot, { x: x ?? 0, y: y ?? 0 });+ return;+ }case 'constrainX':case 'constrainY': {const { entity, props } = node;diff --git a/packages/runtime/src/actions/frame.ts b/packages/runtime/src/actions/frame.tsindex a1b67e83..c4abbf68 100644--- a/packages/runtime/src/actions/frame.ts+++ b/packages/runtime/src/actions/frame.ts@@ -2,26 +2,14 @@* 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/. */-// Frame and scene actions (was api/frame.ts, plus switchActiveScene from-// api/base.ts). The app reacts to Active changes (clearing timeline buffers,-// rebuilding its index) through its own trait observer.+// Active scene actions (switchActiveScene was api/base.ts). The app reacts to+// Active changes (clearing timeline buffers, rebuilding its index) through its+// own trait observer.-import { Or } from 'koota';--import { store } from '../world/store';-import { GeometryType, PaintType } from '../constants';-import {- Geometry, Group, Scene, ClipsContent, Playback, Paint, Color, Selected,- Position, Name, LocalTransform, Computed, Active,-} from '../traits';+import { Active } from '../traits';import { isScene } from '../queries/predicates';-import { getNextName, getParentNode } from '../queries/hierarchy';-import { aabbFromTransformedRect } from '../math';-import { computeLocalMatrix } from '../systems/transform';+import { getParentNode } from '../queries/hierarchy';import { assert } from '../utils/assert';-import { createEntity } from './entities';-import { appendChild, removeChild } from './hierarchy';-import { resizeEntity } from './resize';import type { Entity, World } from 'koota';@@ -45,88 +33,3 @@ export function setActive(world: World, entity: Entity | null): void {assert(getParentNode(entity) === null, 'Only root entities can be active');entity.add(Active);}--/**- * Wrap the current node selection in a new SCENE (a clipped, playable frame).- * Mirrors `groupSelection`, but the wrapper is a Scene with its own fixed Size- * derived from the selection's bounding box, plus the clipping/playback/fill a- * scene needs. Already-existing scenes in the selection are skipped; scenes- * can't be nested. Children's positions are rewritten into the scene's local- * space so their on-canvas position is preserved. Returns the new scene's- * entity, or null if there was nothing to frame.- */-export function frameSelection(world: World): Entity | null {- const selection = [...world.query(Selected, Or(Geometry, Group))]- .filter(entity => !isScene(entity));- if (selection.length === 0) return null;-- const computed = store(world, Computed);-- const targetParent = getParentNode(selection[0]!);- const frameables = selection.filter(entity => getParentNode(entity) === targetParent);-- // Bounding box of children in target-parent local space.- let minX = Infinity;- let minY = Infinity;- let maxX = -Infinity;- let maxY = -Infinity;- for (const entity of frameables) {- const mat = entity.get(LocalTransform) ?? { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };- const w = computed.width[entity.id()]!;- const h = computed.height[entity.id()]!;- const bounds = aabbFromTransformedRect(mat, w, h);- if (bounds.minX < minX) minX = bounds.minX;- if (bounds.minY < minY) minY = bounds.minY;- if (bounds.maxX > maxX) maxX = bounds.maxX;- if (bounds.maxY > maxY) maxY = bounds.maxY;- }-- const x = Math.round(minX);- const y = Math.round(minY);- const width = Math.max(1, Math.round(maxX - minX));- const height = Math.max(1, Math.round(maxY - minY));-- // A scene is a RECT geometry carrying the Scene/ClipsContent/Playback- // tags plus a solid fill; the same recipe the scene draw tool uses.- const scene = createEntity(world);- scene.add(Geometry);- scene.set(Geometry, { value: GeometryType.RECT });- scene.add(Scene);- scene.add(ClipsContent);- scene.add(Playback);- scene.add(Name);- scene.set(Name, { value: getNextName(world, 'Scene') });- scene.add(Position);- scene.set(Position, { x, y });- if (targetParent) appendChild(world, scene, targetParent);- resizeEntity(world, scene, { width, height });-- const fill = createEntity(world);- fill.add(Paint);- fill.set(Paint, { value: PaintType.SOLID });- fill.add(Color);- fill.set(Color, { value: 0x000000 });- appendChild(world, fill, scene);-- for (const child of frameables) {- const prevX = child.get(Position)?.x ?? 0;- const prevY = child.get(Position)?.y ?? 0;- const parent = getParentNode(child);- if (parent) removeChild(world, child, parent);- appendChild(world, child, scene);- child.add(Position);- child.set(Position, { x: prevX - x, y: prevY - y });- // Refresh the child's cached local matrix now; the next transform pass- // re-derives world transforms from it.- computeLocalMatrix(world, child);- }-- for (const entity of world.query(Selected)) entity.remove(Selected);- scene.add(Selected);-- // Make the freshly created frame the active scene (mirrors the scene tool),- // so the timeline retargets to it.- setActive(world, scene);-- return scene;-}diff --git a/packages/runtime/src/actions/group.ts b/packages/runtime/src/actions/group.tsdeleted file mode 100644index 3606ea6c..00000000--- a/packages/runtime/src/actions/group.ts+++ /dev/null@@ -1,139 +0,0 @@-/* 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/. */--// Group and ungroup actions (was api/group.ts).--import { Or } from 'koota';--import { store } from '../world/store';-import {- ChildOf, Geometry, Group, Sequential, Selected, Position, Name,- ItemIndex, LocalTransform, Computed,-} from '../traits';-import { getNextName, getParentNode } from '../queries/hierarchy';-import { aabbFromTransformedRect } from '../math';-import { computeLocalMatrix } from '../systems/transform';-import { sortByItemIndex } from '../utils/sort';-import { createEntity, deleteEntity } from './entities';-import { appendChild, removeChild } from './hierarchy';-import { resolveNewSequenceOverlaps } from './overlap';--import type { Entity, World } from 'koota';--/**- * Wrap the current node selection in a new GROUP. All selected nodes must- * share the same parent; scenes are skipped. Children's positions are- * rewritten into the group's local space so their on-canvas position is- * preserved.- */-export function groupSelection(world: World, sequential: boolean = false): Entity | null {- const selection = [...world.query(Selected, Or(Geometry, Group))];- if (selection.length === 0) return null;-- const computed = store(world, Computed);-- const targetParent = getParentNode(selection[0]!);-- const groupables = selection- .filter(entity => getParentNode(entity) === targetParent)- .sort(sortByItemIndex);-- // Bounding box of children in target-parent local space.- let minX = Infinity;- let minY = Infinity;- let maxX = -Infinity;- let maxY = -Infinity;- for (const entity of groupables) {- const mat = entity.get(LocalTransform) ?? { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };- const w = computed.width[entity.id()]!;- const h = computed.height[entity.id()]!;- const bounds = aabbFromTransformedRect(mat, w, h);- if (bounds.minX < minX) minX = bounds.minX;- if (bounds.minY < minY) minY = bounds.minY;- if (bounds.maxX > maxX) maxX = bounds.maxX;- if (bounds.maxY > maxY) maxY = bounds.maxY;- }-- // Sequences sit at the parent's origin (they're passthrough); plain- // groups sit at the children's AABB origin so their own pivot lines up.- const x = sequential ? 0 : Math.round(minX);- const y = sequential ? 0 : Math.round(minY);-- const topItemIndex = groupables[groupables.length - 1]!.get(ItemIndex)?.value ?? 0;-- const group = createEntity(world);- group.add(Group);- if (sequential) {- group.add(Sequential);- }- group.add(Position);- group.set(Position, { x, y });- group.add(Name);- group.set(Name, { value: getNextName(world, sequential ? 'Sequence' : 'Group') });- if (targetParent) appendChild(world, group, targetParent);- group.add(ItemIndex);- group.set(ItemIndex, { value: topItemIndex });-- for (const [index, entity] of groupables.entries()) {- const prevX = entity.get(Position)?.x ?? 0;- const prevY = entity.get(Position)?.y ?? 0;- const parent = getParentNode(entity);- if (parent) removeChild(world, entity, parent);- appendChild(world, entity, group);- entity.add(ItemIndex);- entity.set(ItemIndex, { value: index });- entity.add(Position);- entity.set(Position, { x: prevX - x, y: prevY - y });- // Refresh the child's cached local matrix now; the next transform pass- // re-derives world transforms from it.- computeLocalMatrix(world, entity);- }-- if (sequential) {- resolveNewSequenceOverlaps(world, group);- }-- for (const entity of world.query(Selected)) entity.remove(Selected);- group.add(Selected);-- return group;-}--/**- * Inverse of `groupSelection`. For every GROUP in the current selection,- * lift its direct children up to the group's parent and remove the group.- * Children's positions are rewritten so they stay put on canvas.- */-export function ungroupSelection(world: World): void {- const groups = [...world.query(Selected, Group)];- if (groups.length === 0) return;-- const promoted: Entity[] = [];-- for (const group of groups) {- const targetParent = getParentNode(group);- const groupX = group.get(Position)?.x ?? 0;- const groupY = group.get(Position)?.y ?? 0;- // Spread is important here: the query result changes while re-parenting.- const children = [...world.query(ChildOf(group))];- for (const child of children) {- removeChild(world, child, group);- child.add(Position);- child.set(Position, {- x: (child.get(Position)?.x ?? 0) + groupX,- y: (child.get(Position)?.y ?? 0) + groupY,- });-- if (targetParent) {- appendChild(world, child, targetParent);- }- promoted.push(child);- }-- deleteEntity(world, group);- }-- for (const entity of world.query(Selected)) entity.remove(Selected);- promoted.forEach(entity => entity.add(Selected));-}diff --git a/packages/runtime/src/actions/index.ts b/packages/runtime/src/actions/index.tsindex 4f64904b..49ba609b 100644--- a/packages/runtime/src/actions/index.ts+++ b/packages/runtime/src/actions/index.ts@@ -18,7 +18,6 @@ export * from './timing';export * from './resize';export * from './keyframe';export * from './overlap';-export * from './group';export * from './frame';export * from './playback';export * from './clipboard';diff --git a/packages/runtime/src/actions/overlap.ts b/packages/runtime/src/actions/overlap.tsindex 47ad30eb..8adee3e1 100644--- a/packages/runtime/src/actions/overlap.ts+++ b/packages/runtime/src/actions/overlap.ts@@ -61,48 +61,6 @@ export function resolveSequentialOverlaps(world: World, dragged: Entity[]): void}}-/**- * Enforce the no-overlap invariant on a *freshly created* Sequential container.- *- * resolveSequentialOverlaps has an authoritative set: the clips the user just- * dragged. On creation there is none: every child is a peer that merely happened- * to overlap on the canvas. We pick a deterministic precedence instead; earlier- * clips win and keep their full extent; later clips yield, trimmed back to start- * after the clip preceding them (fully-covered clips are removed).- *- * Children are processed in start-frame order with each one authoritative over- * all later siblings. Because every authoritative pass trims *all* later- * siblings uniformly, each clip's start stays monotonic by rank, so the "dropped- * clip lands inside a sibling" split case from resolveEntityOverlap cannot arise- * here; only edge trims and removals.- */-export function resolveNewSequenceOverlaps(world: World, sequence: Entity): void {- if (!sequence.has(Sequential)) return;-- const computed = store(world, Computed);-- const children = [...world.query(Or(Geometry, Group), ChildOf(sequence))]- .sort((a, b) => (computed.start[a.id()] ?? 0) - (computed.start[b.id()] ?? 0));-- // No dragged clips to protect; group recursion has no leaves to skip.- const ignore = new Set<Entity>();-- for (let i = 0; i < children.length; i++) {- const entity = children[i]!;- // An earlier authoritative clip may have removed or trimmed this one.- if (!world.has(entity)) continue;- const occStart = computed.start[entity.id()];- const occEnd = computed.end[entity.id()];- if (occStart === undefined || occEnd === undefined || occEnd <= occStart) continue;-- for (let j = i + 1; j < children.length; j++) {- const sibling = children[j]!;- if (!world.has(sibling)) continue;- resolveEntityOverlap(world, sibling, occStart, occEnd, ignore);- }- }-}-/*** Resolve a single entity against the occupied [occStart, occEnd) span.* Groups recurse to their children; leaf clips are trimmed, removed, or split.diff --git a/packages/runtime/src/queries/interaction.ts b/packages/runtime/src/queries/interaction.tsindex c2fa8275..83c71f44 100644--- a/packages/runtime/src/queries/interaction.ts+++ b/packages/runtime/src/queries/interaction.ts@@ -13,7 +13,7 @@import { Not, Or } from 'koota';import {- Anchor, Cache, Computed, EvenOdd, Geometry, Group, LocalTransform, Offset, PointCount, Selected,+ Anchor, Cache, Computed, EvenOdd, Geometry, Group, LocalTransform, Offset, Pivot, PointCount, Selected,Sequential, WorldBounds, WorldTransform,} from '../traits';import { GeometryType } from '../constants';@@ -65,11 +65,30 @@ export function entityOffset(world: World, entity: Entity): Point {return { x: offset.x[eid] ?? 0, y: offset.y[eid] ?? 0 };}-export function entityAnchor(world: World, entity: Entity): Point {- const anchor = store(world, Anchor);+/**+ * The point the node's rotation, scale and skew turn about, px in its own+ * space: its `Pivot` while it has one, else its anchor's fraction of its box+ * — of `width` × `height` when given, for a gesture that is changing the+ * size. A group has no box of its own to take a fraction of (its box follows+ * its children), so without a pivot it turns about its origin, as an SVG+ * `<g>` does.+ */+export function entityPivot(world: World, entity: Entity, width?: number, height?: number): Point {const eid = entity.id();- return { x: anchor.x[eid] ?? 0.5, y: anchor.y[eid] ?? 0.5 };+ if (entity.has(Pivot)) {+ const pivot = store(world, Pivot);+ return { x: pivot.x[eid] ?? 0, y: pivot.y[eid] ?? 0 };+ }++ if (entity.has(Group)) return { x: 0, y: 0 };++ const anchor = store(world, Anchor);+ const computed = store(world, Computed);+ return {+ x: (anchor.x[eid] ?? 0.5) * (width ?? computed.width[eid] ?? 0),+ y: (anchor.y[eid] ?? 0.5) * (height ?? computed.height[eid] ?? 0),+ };}/** The entity's box in device pixels, as [TL, TR, BR, BL]. */diff --git a/packages/runtime/src/systems/transform.ts b/packages/runtime/src/systems/transform.tsindex 2a00e688..a7decad7 100644--- a/packages/runtime/src/systems/transform.ts+++ b/packages/runtime/src/systems/transform.ts@@ -7,12 +7,13 @@ import { Not, Or } from 'koota';import { store } from '../world/store';import {ChildOf, Geometry, Group, Hidden, IsClipPath, Sequential, AdjustmentLayer,- Culled, Flip, Anchor, Computed, Cache, LocalTransform, WorldTransform,+ Culled, Flip, Computed, Cache, LocalTransform, WorldTransform,WorldBounds, RenderSurface,Root,} from '../traits';import { getParentNode } from '../queries/hierarchy';import { getViewMatrix } from '../queries/camera';+import { entityPivot } from '../queries/interaction';import {multiply2D,@@ -32,20 +33,20 @@ import type { Entity, World } from 'koota';// snapshots, no change events./**- * Compute the local 2D affine matrix from Offset, Rotation, Scale,- * Anchor, Skew and Size. Stores the result in LocalTransform.+ * Compute the local 2D affine matrix from Offset, Rotation, Scale, Skew and+ * the pivot they turn about (see `entityPivot`). Stores the result in+ * LocalTransform. Nothing here reads a group's box: a group turns about its+ * own pivot, so its matrix does not depend on where its children are.*/export function computeLocalMatrix(world: World, entity: Entity): void {const flip = store(world, Flip);- const anchor = store(world, Anchor);const computed = store(world, Computed);const local = store(world, LocalTransform);const eid = entity.id();const positionX = computed.positionX[eid] + computed.offsetX[eid];const positionY = computed.positionY[eid] + computed.offsetY[eid];- const pivotX = (anchor.x[eid] ?? 0.5) * computed.width[eid];- const pivotY = (anchor.y[eid] ?? 0.5) * computed.height[eid];+ const { x: pivotX, y: pivotY } = entityPivot(world, entity);const scaleX = (flip.x[eid] ?? 1) * computed.scaleX[eid];const scaleY = (flip.y[eid] ?? 1) * computed.scaleY[eid];const rotation = computed.rotation[eid];@@ -136,16 +137,25 @@ export function computeWorldBounds(world: World, entity: Entity): void {boundsStore.maxY[eid] = bounds.maxY;}-function cullEntity(world: World, entity: Entity, parentEntity: Entity | null): void {- // Inherit cull from the parent: the renderer already skips entire- // subtrees of culled parents, so descendants are effectively invisible- // even when their own AABB intersects the parent's. Propagating the tag- // down lets us free their decoders too. Pre-order DFS guarantees the- // parent's tag is already settled by the time we reach the child.+/**+ * How a node is culled: `null` tests its own bounds against the canvas, a+ * boolean is the verdict it inherits. Top-level nodes are tested; below a+ * node with a box of its own, children inherit its tag: the renderer already+ * skips entire subtrees of culled parents, so descendants are effectively+ * invisible even when their own AABB intersects the parent's, and+ * propagating the tag down lets us free their decoders too. A group is+ * spatially transparent — its box is only its children's — so its children+ * are culled the way it would be, and it is tested only once they have been,+ * against the box they make.+ */+type CullMode = boolean | null;+function cullEntity(world: World, entity: Entity, mode: CullMode): void {let intersect = true;- if (parentEntity === null) {+ if (mode !== null) {+ intersect = !mode;+ } else {// Without a render surface (headless world) nothing is culled.const canvas = world.get(RenderSurface)?.canvas;if (canvas) {@@ -163,8 +173,6 @@ function cullEntity(world: World, entity: Entity, parentEntity: Entity | null):maxY: canvas.height,});}- } else {- intersect = !parentEntity.has(Culled);}const wasCulled = entity.has(Culled);@@ -178,12 +186,26 @@ function cullEntity(world: World, entity: Entity, parentEntity: Entity | null):}}+/** The cull mode `entity`'s children are walked with (see CullMode). */+function childCullMode(entity: Entity, mode: CullMode): CullMode {+ return entity.has(Group) ? mode : entity.has(Culled);+}++/** The cull mode `entity` is walked with: what its parents hand down to it. */+function cullModeOf(entity: Entity): CullMode {+ const parent = getParentNode(entity);+ return parent === null ? null : childCullMode(parent, cullModeOf(parent));+}+/*** Recompute a Group entity's Computed bounds from the union of its children's- * transformed boxes. Sequences aren't spatial constructs: they mirror their- * parent's frame instead (the walk is parent-first, so the parent's Computed- * values are already settled). Leaf entities own an absolute Size and need no- * resolution here.+ * transformed boxes. The box is derived data for whatever measures the group+ * (selection, hit-testing, snapping, culling); the group's own matrix never+ * reads it. The walk visits a group's children first, so their matrices are+ * the ones of this frame. A sequence under a node with a box of its own is+ * not a spatial construct: it mirrors that frame instead (a Geometry's+ * Computed size is settled before the walk). Leaf entities own an absolute+ * Size and need no resolution here.*/export function computeGroupBounds(world: World, entity: Entity): void {const computed = store(world, Computed);@@ -192,7 +214,7 @@ export function computeGroupBounds(world: World, entity: Entity): void {if (entity.has(Sequential)) {const parent = getParentNode(entity);- if (parent !== null) {+ if (parent !== null && !parent.has(Group)) {const pid = parent.id();computed.width[eid] = computed.width[pid];computed.height[eid] = computed.height[pid];@@ -284,37 +306,45 @@ function adjustLayers(world: World, adjust: Entity): void {localStore.e[tid] = composed.e;localStore.f[tid] = composed.f;- const reworld = (entity: Entity, parentEntity: Entity | null) => {- computeWorldTransform(world, entity, parentEntity);+ // Children keep their local matrices: one may hold another layer's+ // composition already.+ placeSubtree(world, target, parent, cullModeOf(target), false);+}++/**+ * Derives the world transform, bounds and cull tag of `entity` and its+ * subtree, its local matrix (and its descendants') first when `local` is set.+ * A node with a box of its own is placed before its children, since they+ * inherit its cull tag; a group after them, since its box is theirs.+ */+function placeSubtree(world: World, entity: Entity, parentEntity: Entity | null, mode: CullMode, local: boolean): void {+ if (local) computeLocalMatrix(world, entity);+ computeWorldTransform(world, entity, parentEntity);++ const group = entity.has(Group);+ if (!group) {computeWorldBounds(world, entity);- cullEntity(world, entity, parentEntity);+ cullEntity(world, entity, mode);+ }- for (const child of world.query(Or(Geometry, Group), ChildOf(entity))) {- reworld(child, entity);- }- };+ const childMode = childCullMode(entity, mode);+ for (const child of world.query(Or(Geometry, Group), ChildOf(entity))) {+ placeSubtree(world, child, entity, childMode, local);+ }- reworld(target, parent);+ if (group) {+ computeGroupBounds(world, entity);+ computeWorldBounds(world, entity);+ cullEntity(world, entity, mode);+ }}/*** Transform system entry point. Call once per frame before the render system.*/export function transformSystem(world: World): void {- const walk = (entity: Entity, parentEntity: Entity | null) => {- computeGroupBounds(world, entity);- computeLocalMatrix(world, entity);- computeWorldTransform(world, entity, parentEntity);- computeWorldBounds(world, entity);- cullEntity(world, entity, parentEntity);-- for (const child of world.query(Or(Geometry, Group), ChildOf(entity))) {- walk(child, entity);- }- };-for (const entity of world.query(Or(Geometry, Group), ChildOf(world.get(Root)!))) {- walk(entity, null);+ placeSubtree(world, entity, null, null, true);}for (const adjust of world.query(AdjustmentLayer)) {diff --git a/packages/runtime/src/traits/transform.ts b/packages/runtime/src/traits/transform.tsindex d1e1c62a..6bc0171d 100644--- a/packages/runtime/src/traits/transform.ts+++ b/packages/runtime/src/traits/transform.ts@@ -18,6 +18,8 @@ export const UniformScale = trait({ value: 1 });export const Anchor = trait({ x: 0, y: 0 });+export const Pivot = trait({ x: 0, y: 0 });+export const Skew = trait({ x: 0, y: 0 });export const Size = trait({ width: 0, height: 0 });@@ -35,7 +37,7 @@ export const KeepAspectRatio = trait({ width: 0, height: 0 });// Derived state below: written by the transform system, never serialized.-// Local 2D affine matrix from Offset, Rotation, Scale, Anchor, Skew and Size.+// Local 2D affine matrix from Offset, Rotation, Scale, Pivot (or Anchor), Skew and Size.export const LocalTransform = trait({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });export const WorldTransform = trait({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });diff --git a/packages/runtime/src/world/observers.ts b/packages/runtime/src/world/observers.tsindex 65ddd056..5c061f7f 100644--- a/packages/runtime/src/world/observers.ts+++ b/packages/runtime/src/world/observers.ts@@ -7,7 +7,7 @@ import { store } from './store';import {ChildOf, Culled, Sequential, Group, Scene, Audio, Paint, AssetId,Delay, Trim, PlaybackRate, SourceFrameRate, Keyframe, ItemIndex,- Position, Offset, Rotation, Scale, UniformScale, Skew, Anchor, Flip,+ Position, Offset, Rotation, Scale, UniformScale, Skew, Anchor, Pivot, Flip,Opacity, Color, Blur, Volume, Effect, CornerRadius, MixedCornerRadius,ColorStop, LinearGradient, EllipticalGradient, PathTrim, StrokeStyle, Size, Computed, Active, Stage, IsClipPath,ImageDecoderHandle, VideoDecoderHandle,@@ -103,7 +103,7 @@ export function observeWorld(world: World): () => void {// A sequence is a group without spatial identity of its own.subs.push(world.onAdd(Sequential, (entity) => {entity.add(Group);- entity.remove(Position, Offset, Rotation, Scale, Skew, Anchor, Flip);+ entity.remove(Position, Offset, Rotation, Scale, Skew, Anchor, Pivot, Flip);}));const refile = (clipPath: boolean) => (entity: Entity) => {diff --git a/packages/runtime/src/world/serialize.ts b/packages/runtime/src/world/serialize.tsindex 78dbca03..9e681472 100644--- a/packages/runtime/src/world/serialize.ts+++ b/packages/runtime/src/world/serialize.ts@@ -7,7 +7,7 @@ import {Geometry, Paint, Group, Scene, Audio, AdjustmentLayer, IsClipPath, Shadow, Stroke,Hidden, ClipsContent, Name, Key, AssetId, ItemIndex, MountScript, MountPath,Caption,- Position, Offset, Rotation, Scale, UniformScale, Anchor, Skew, Size, Flip,+ Position, Offset, Rotation, Scale, UniformScale, Anchor, Pivot, Skew, Size, Flip,Constraint, KeepAspectRatio,Opacity, BlendMode, Color, CornerRadius, MixedCornerRadius, PointCount, Blur, ScaleMode, Effect, Mask,VectorPath, EvenOdd, ViewBox, PathTrim,@@ -88,6 +88,10 @@ export interface EntityRecord {x?: number;y?: number;};+ Pivot?: {+ x?: number;+ y?: number;+ };Skew?: {x?: number;y?: number;@@ -288,6 +292,10 @@ export function serializeEntity(entity: Entity): EntityRecord {const anchor = entity.get(Anchor)!;record.Anchor = { x: anchor.x, y: anchor.y };}+ if (entity.has(Pivot)) {+ const pivot = entity.get(Pivot)!;+ record.Pivot = { x: pivot.x, y: pivot.y };+ }if (entity.has(Skew)) {const skew = entity.get(Skew)!;record.Skew = { x: skew.x, y: skew.y };@@ -568,6 +576,10 @@ export function deserializeEntity(entity: Entity, e: Partial<EntityRecord>): voientity.add(Anchor);entity.set(Anchor, defined(e.Anchor));}+ if (e.Pivot !== undefined) {+ entity.add(Pivot);+ entity.set(Pivot, defined(e.Pivot));+ }if (e.Skew !== undefined) {entity.add(Skew);entity.set(Skew, defined(e.Skew));