Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): a rotate gizmo with three rings

esengine94b30850a79d
diff --git a/desktop/src/engine/entityOps.ts b/desktop/src/engine/entityOps.ts
index 4b6eecedf..0c0f175a2 100644
--- a/desktop/src/engine/entityOps.ts
+++ b/desktop/src/engine/entityOps.ts
@@ -20,7 +20,8 @@ import { PlayInspect } from './PlayInspect';
import { PlayRealm } from './PlayRealm';
import { srcIdOf, type EntityRef } from './entityRef';
import { SceneQuery } from './SceneQuery';
-import { turnQuat2D, scaleVecBy } from './viewportMath';
+import { scaleVecBy } from './viewportMath';
+import { eulerToQuat } from './schema';
import { PlayEdits } from './playEdits';
/** The value vocabulary every inspector control commits in. */
@@ -117,8 +118,11 @@ export const EntityOps = {
}
const src = srcIdOf(ref);
if (src == null) return null;
- const q = SceneQuery.getFieldValue(src, 'Transform', 'rotation') as { z?: number; w?: number } | null;
- SceneCommands.setFieldValue(src, 'Transform', 'rotation', turnQuat2D(q ?? undefined, radians));
+ // The field reads as three degrees; this op turns about Z, so it adds to that
+ // one and leaves the other two — a 3D pose must survive an agent's nudge.
+ const e = (SceneQuery.getFieldValue(src, 'Transform', 'rotation') as number[] | null) ?? [0, 0, 0];
+ const turned = [e[0] ?? 0, e[1] ?? 0, (e[2] ?? 0) + radians * (180 / Math.PI)];
+ SceneCommands.setFieldValue(src, 'Transform', 'rotation', eulerToQuat(turned));
return 'document';
},
diff --git a/desktop/src/engine/viewportMath.ts b/desktop/src/engine/viewportMath.ts
index 5a88b7019..ace132ba6 100644
--- a/desktop/src/engine/viewportMath.ts
+++ b/desktop/src/engine/viewportMath.ts
@@ -121,10 +121,37 @@ export function rankPickCandidates<T>(candidates: ReadonlyArray<PickCandidate<T>
.map((c) => c.entity);
}
-/** A 2D rotation quaternion turned by `radians`. */
-export function turnQuat2D(q: { z?: number; w?: number } | undefined, radians: number): { x: number; y: number; z: number; w: number } {
- const angle = quatAngleZ2D(q) + radians;
- return { x: 0, y: 0, z: Math.sin(angle / 2), w: Math.cos(angle / 2) };
+export interface Quat { x: number; y: number; z: number; w: number }
+
+/** Quaternion for a turn of `rad` about a world axis. */
+export function axisQuat(axis: 'x' | 'y' | 'z', rad: number): Quat {
+ const s = Math.sin(rad / 2);
+ return {
+ x: axis === 'x' ? s : 0,
+ y: axis === 'y' ? s : 0,
+ z: axis === 'z' ? s : 0,
+ w: Math.cos(rad / 2),
+ };
+}
+
+/** `a` applied after `b` (a·b) — a WORLD-space turn composes on the left. */
+export function quatMul(a: Quat, b: Quat): Quat {
+ return {
+ x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
+ y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
+ z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
+ w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
+ };
+}
+
+/**
+ * A rotation turned by `radians` about Z. Composed as an increment rather than
+ * rebuilt from a Z angle, so whatever the other two axes say survives it — a
+ * model imported with a 3D pose keeps that pose through a nudge.
+ */
+export function turnQuat2D(q: { x?: number; y?: number; z?: number; w?: number } | undefined, radians: number): Quat {
+ const cur: Quat = { x: q?.x ?? 0, y: q?.y ?? 0, z: q?.z ?? 0, w: q?.w ?? 1 };
+ return quatMul(axisQuat('z', radians), cur);
}
/** The Z angle of a 2D rotation quaternion; 0 for one that isn't there. */
diff --git a/desktop/src/i18n/messages/viewport.ts b/desktop/src/i18n/messages/viewport.ts
index b77bca8c1..353e09fc7 100644
--- a/desktop/src/i18n/messages/viewport.ts
+++ b/desktop/src/i18n/messages/viewport.ts
@@ -21,7 +21,7 @@ export const viewportMessages = defineMessages({
en: 'Drag a gizmo axis or its center · Alt-drag duplicates · arrows nudge',
zh: '拖动 Gizmo 轴或中心方块 · Alt 拖动创建副本 · 方向键微移',
},
- 'vp.hint.rotate': { en: 'Drag the ring to rotate the selection', zh: '拖动圆环旋转所选' },
+ 'vp.hint.rotate': { en: 'Drag a ring to turn the selection about that axis', zh: '拖动圆环绕该轴旋转所选' },
'vp.hint.scale': {
en: 'Drag a handle for per-axis scale · center for uniform',
zh: '拖动手柄按轴缩放 · 拖动中心等比缩放',
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index fb1ff554f..36ecf424d 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -20,7 +20,7 @@ import { useEditorMode } from '@/store/editorModeStore';
import { screenPresetById, DESIGN_RESOLUTION_PRESETS, deviceDims } from '@/mode/resolutionPresets';
import { buildStampGhost } from '@/tools/tileStampGhost';
import { alignSelection, distributeSelection } from '@/tools/alignTools';
-import { TilemapAPI, tileIdOf, isNonOrthogonal, isCollisionPaletteRef, buildCollisionPaletteModel, UINode, DimensionUnit, computeEffectiveOrthoSize, type TileCollisionPiece, type TilesetModel } from 'esengine';
+import { TilemapAPI, tileIdOf, isNonOrthogonal, isCollisionPaletteRef, buildCollisionPaletteModel, UINode, DimensionUnit, computeEffectiveOrthoSize, type TileCollisionPiece, type TilesetModel, type ScreenAxis } from 'esengine';
import { commands } from '@/commands';
import { MOD_LABEL } from '@/commands/keybinding';
import { EngineHost } from '@/engine/EngineHost';
@@ -50,7 +50,7 @@ import { usePanelWindow, eventWindow } from '@/components/PanelWindow';
import type { ToolMode, EntityId } from '@/types';
import { resolveActiveTool, type EditorTool, type ToolContext, type PointerInput } from '@/tools';
import { cursorTile } from '@/tools/tileTools';
-import { GIZMO, colliderHandleClass, pivotDrag, type GizmoAxis } from '@/tools/gizmo';
+import { GIZMO, colliderHandleClass, pivotDrag, rotateRings, ringPoint, type GizmoAxis, type RotateRing } from '@/tools/gizmo';
import { selectionPivot, gizmoScreenAngleRad } from '@/tools/transformTools';
import { Marquee } from '@/tools/marquee';
import { TilePaintPreview } from '@/tools/tilePreview';
@@ -425,7 +425,28 @@ const gizmoViewBox = `${-GIZMO_SVG / 2} ${-GIZMO_SVG / 2} ${GIZMO_SVG} ${GIZMO_S
// and thrash layout at N divs/frame. Below it the per-entity path is untouched.
const SELECTION_OUTLINE_MERGE_THRESHOLD = 200;
-function GizmoOverlay({ tool, active }: { tool: ToolMode; active: GizmoAxis | null }) {
+// Head-on world axes, for the moment before the engine can answer: +X right,
+// +Y up (screen y is down), +Z straight at the eye.
+const HEAD_ON_AXES = {
+ x: { dx: 1, dy: 0, depth: 0 }, y: { dx: 0, dy: -1, depth: 0 }, z: { dx: 0, dy: 0, depth: 1 },
+};
+
+/** A ring as an SVG path, sampled around its own parameter. */
+function ringPath(ring: RotateRing, radius: number): string {
+ const steps = 48;
+ let d = '';
+ for (let i = 0; i < steps; i++) {
+ const p = ringPoint(ring, (i / steps) * Math.PI * 2, radius);
+ d += `${i === 0 ? 'M' : 'L'}${p.x.toFixed(2)} ${p.y.toFixed(2)}`;
+ }
+ return `${d}Z`;
+}
+
+function GizmoOverlay({ tool, active, axes }: {
+ tool: ToolMode;
+ active: GizmoAxis | null;
+ axes: { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis } | null;
+}) {
const L = GIZMO.axisLen;
const B = GIZMO.boxSize;
const P = GIZMO.planeSize;
@@ -438,9 +459,22 @@ function GizmoOverlay({ tool, active }: { tool: ToolMode; active: GizmoAxis | nu
const axW = (on: boolean) => (on ? 4 : 2.5);
const planeOp = (on: boolean) => (on ? 1 : 0.85);
if (tool === 'rotate') {
+ // One ring per world axis, drawn where that axis's plane actually projects —
+ // an ellipse once the eye is off-axis. Edge-on rings are dropped by
+ // rotateRings, which is what leaves a head-on gizmo the single Z circle.
+ const rings = rotateRings(axes ?? HEAD_ON_AXES);
+ const hot: Record<string, boolean> = { x: active === 'x', y: active === 'y', z: active === 'xy' };
return (
<svg className="gizmo-svg" width={GIZMO_SVG} height={GIZMO_SVG} viewBox={gizmoViewBox}>
- <circle cx="0" cy="0" r={GIZMO.ringRadius} fill="none" stroke="var(--run)" strokeWidth={active ? 3.5 : 2} />
+ {rings.map((ring) => (
+ <path
+ key={ring.axis}
+ className={`gz-ring gz-${ring.axis}`}
+ d={ringPath(ring, GIZMO.ringRadius)}
+ fill="none"
+ strokeWidth={hot[ring.axis] ? 3.5 : 2}
+ />
+ ))}
<circle cx="0" cy="0" r="2.5" fill="var(--star)" />
</svg>
);
@@ -922,6 +956,11 @@ export function Viewport() {
release: (id) => stageRef.current?.releasePointerCapture(id),
}), []);
const [zoomPct, setZoomPct] = useState(100);
+ // Where the world axes project, for the rotate gizmo's rings. Polled (like the
+ // zoom readout) rather than mirrored, and only while that tool is up: it changes
+ // when the eye turns, and re-rendering the viewport per orbit frame is not free.
+ const [viewAxes, setViewAxes] = useState<{ x: ScreenAxis; y: ScreenAxis; z: ScreenAxis } | null>(null);
+ const viewAxesKey = useRef('');
// Last-published zoom %, so the rAF only re-renders the HUD when it actually changes.
const zoomPctRef = useRef(100);
const engine = useSyncExternalStore(EngineHost.subscribe, EngineHost.getSnapshot);
@@ -1168,6 +1207,12 @@ export function Viewport() {
// door all move it, so a flag each of them must remember to set is a mirror
// that drifts. The setter no-ops on an unchanged value, so this costs a call.
useEditorStore.getState().setViewOrbited(ViewportController.isOrbited());
+
+ if (toolMode === 'rotate') {
+ const a = ViewportController.viewAxes();
+ const k = a ? [a.x, a.y, a.z].map((v) => `${v.dx.toFixed(3)},${v.dy.toFixed(3)}`).join('|') : '';
+ if (k !== viewAxesKey.current) { viewAxesKey.current = k; setViewAxes(a); }
+ }
}
// Selection outlines. Below the merge threshold: one div per selected source
@@ -2779,7 +2824,7 @@ export function Viewport() {
))}
</div>
<div ref={gizmoRef} className="viewport__gizmo" aria-hidden="true">
- <GizmoOverlay tool={tool} active={activeGizmoAxis} />
+ <GizmoOverlay tool={tool} active={activeGizmoAxis} axes={viewAxes} />
</div>
{engine.status !== 'ready' && (
diff --git a/desktop/src/theme/viewport.css b/desktop/src/theme/viewport.css
index 8b2cdfa57..9ad6f6f7e 100644
--- a/desktop/src/theme/viewport.css
+++ b/desktop/src/theme/viewport.css
@@ -189,6 +189,14 @@
/* Design-resolution readout pinned to the frame's top-left corner (rAF-positioned). */
.viewport__design-label { position: absolute; top: 0; left: 0; z-index: 6; pointer-events: none; padding: 1px 5px; font-size: var(--fs-2xs); font-variant-numeric: tabular-nums; color: var(--on-accent); background: var(--acc); border-radius: var(--r-sm); white-space: nowrap; }
+/* The rotate gizmo's rings, one per world axis, in the same colour language the
+ move/scale arrows use. An edge-on ring is not drawn at all (see rotateRings),
+ so a head-on 2D gizmo is the single green Z circle it has always been. */
+.gz-ring { stroke-linejoin: round; }
+.gz-x { stroke: var(--error); }
+.gz-y { stroke: var(--run); }
+.gz-z { stroke: var(--gizmo-axis-z); }
+
/* View axis indicator (top-right, below the docked toolbar) — the world axes as they
point on screen, each end a click that stands the eye on that axis. Present only
while the eye can be turned, so a 2D project never sees it. */
diff --git a/desktop/src/tools/gizmo.ts b/desktop/src/tools/gizmo.ts
index 48488b50a..a879c3bc3 100644
--- a/desktop/src/tools/gizmo.ts
+++ b/desktop/src/tools/gizmo.ts
@@ -13,6 +13,10 @@
* applies the world-space delta the cursor traveled, constrained to the axis.
*/
+import { axisQuat, quatMul, type Quat } from '@/engine/viewportMath';
+
+export { axisQuat, quatMul, type Quat };
+
export type GizmoMode = 'move' | 'rotate' | 'scale';
/** Which world axes a handle drag affects. */
export type GizmoAxis = 'x' | 'y' | 'xy';
@@ -69,7 +73,7 @@ function rotDir(dir: Pt, a: number): Pt {
* gizmo's on-screen orientation (0 = world-aligned; non-zero in local space, and it
* must match the gizmo's render rotation so the handle you aim at is the one hit).
*/
-export function hitTestGizmo(mode: GizmoMode, pivot: Pt, cursor: Pt, axisAngleRad = 0): GizmoHandle | null {
+export function hitTestGizmo(mode: 'move' | 'scale', pivot: Pt, cursor: Pt, axisAngleRad = 0): GizmoHandle | null {
const xEnd = along(pivot, rotDir(X_DIR, axisAngleRad), GIZMO.axisLen);
const yEnd = along(pivot, rotDir(Y_DIR, axisAngleRad), GIZMO.axisLen);
@@ -87,9 +91,7 @@ export function hitTestGizmo(mode: GizmoMode, pivot: Pt, cursor: Pt, axisAngleRa
return { id: 'scale.y', mode, axis: 'y' };
return null;
}
- // rotate: a ring of radius ringRadius around the pivot.
- const d = Math.hypot(cursor.x - pivot.x, cursor.y - pivot.y);
- if (Math.abs(d - GIZMO.ringRadius) <= GIZMO.hitTol) return { id: 'rotate.ring', mode, axis: 'xy' };
+ // rotate aims at rings, which need the view's axes — see hitTestRings.
return null;
}
@@ -184,3 +186,72 @@ export function scaleAround(p: Pt, c: Pt, fx: number, fy: number): Pt {
export function colliderHandleClass(selected: boolean, mode: GizmoMode | 'select'): string {
return (selected ? ' is-live' : '') + (mode === 'select' ? '' : ' gizmo-owns-centre');
}
+
+/** One rotation ring, as it projects: the two screen vectors its plane spans (each
+ * a unit world axis, so each already carries its own foreshortening). */
+export interface RotateRing {
+ axis: 'x' | 'y' | 'z';
+ u: Pt;
+ v: Pt;
+}
+
+/**
+ * How flat a ring may be projected and still be worth drawing or aiming at. Below
+ * it the circle is edge-on — a line, where a cursor names no angle. It is also
+ * what leaves the head-on 2D gizmo with the single Z ring it always had.
+ */
+const RING_MIN_DET = 0.12;
+
+/**
+ * The rotate gizmo's three rings, from where the world axes point on screen.
+ *
+ * Each ring spans the plane its axis is normal to, in that axis's own right-handed
+ * order (Y×Z = X, Z×X = Y, X×Y = Z) — so a drag from `u` toward `v` is a POSITIVE
+ * turn about the axis, and the sign needs no separate table.
+ */
+export function rotateRings(axes: {
+ x: { dx: number; dy: number }; y: { dx: number; dy: number }; z: { dx: number; dy: number };
+}): RotateRing[] {
+ const pt = (a: { dx: number; dy: number }): Pt => ({ x: a.dx, y: a.dy });
+ return ([
+ { axis: 'x', u: pt(axes.y), v: pt(axes.z) },
+ { axis: 'y', u: pt(axes.z), v: pt(axes.x) },
+ { axis: 'z', u: pt(axes.x), v: pt(axes.y) },
+ ] as const).filter((r) => Math.abs(r.u.x * r.v.y - r.u.y * r.v.x) >= RING_MIN_DET);
+}
+
+/** A point on `ring` at parameter `t`, in screen offsets from the pivot. */
+export function ringPoint(ring: RotateRing, t: number, radius: number): Pt {
+ const c = Math.cos(t);
+ const s = Math.sin(t);
+ return { x: radius * (ring.u.x * c + ring.v.x * s), y: radius * (ring.u.y * c + ring.v.y * s) };
+}
+
+/**
+ * Where on `ring` a cursor points, as the ring's own parameter — solved from the
+ * two spanning vectors rather than from the screen angle, which an ellipse and a
+ * circle only agree on when the ring faces the eye.
+ */
+export function ringAngleAt(ring: RotateRing, offset: Pt, radius: number): number | null {
+ const det = ring.u.x * ring.v.y - ring.u.y * ring.v.x;
+ if (Math.abs(det) < RING_MIN_DET || radius <= 0) return null;
+ const a = (offset.x * ring.v.y - offset.y * ring.v.x) / (radius * det);
+ const b = (ring.u.x * offset.y - ring.u.y * offset.x) / (radius * det);
+ return Math.atan2(b, a);
+}
+
+/** The ring under `cursor`, or null — the nearest one within the hit tolerance. */
+export function hitTestRings(rings: readonly RotateRing[], pivot: Pt, cursor: Pt,
+ radius = GIZMO.ringRadius): RotateRing | null {
+ const offset = { x: cursor.x - pivot.x, y: cursor.y - pivot.y };
+ let best: RotateRing | null = null;
+ let bestDist: number = GIZMO.hitTol;
+ for (const ring of rings) {
+ const t = ringAngleAt(ring, offset, radius);
+ if (t === null) continue;
+ const on = ringPoint(ring, t, radius);
+ const d = Math.hypot(offset.x - on.x, offset.y - on.y);
+ if (d < bestDist) { bestDist = d; best = ring; }
+ }
+ return best;
+}
diff --git a/desktop/src/tools/transformTools.ts b/desktop/src/tools/transformTools.ts
index dc3866671..5d6a6f061 100644
--- a/desktop/src/tools/transformTools.ts
+++ b/desktop/src/tools/transformTools.ts
@@ -19,18 +19,24 @@ import { SceneModel } from '@/engine/SceneModel';
import { SceneStore } from '@/engine/SceneStore';
import { EngineHost } from '@/engine/EngineHost';
import { snapTo } from '@/engine/viewportMath';
+import { eulerToQuat, quatToEuler } from '@/engine/schema';
import { useSelection } from '@/store/selectionStore';
import { useEditorStore } from '@/store/editorStore';
import type { ToolMode, EntityId } from '@/types';
import {
type GizmoAxis,
- type GizmoMode,
type Pt,
GIZMO,
hitTestGizmo,
constrainLocalDelta,
groupPivot,
- rotateAround,
+ rotateRings,
+ ringAngleAt,
+ hitTestRings,
+ axisQuat,
+ quatMul,
+ type Quat,
+ type RotateRing,
scaleAround,
} from './gizmo';
import { Marquee } from './marquee';
@@ -43,7 +49,12 @@ type Kind = 'move' | 'rotate' | 'scale';
/** Captured start transform of one drag target (in inspector units: degrees, scale factor). */
interface Target {
sourceId: EntityId;
- start: { x: number; y: number; rotDeg: number; sx: number; sy: number; sz: number };
+ start: {
+ x: number; y: number; z: number;
+ /** The whole pose, so a turn about ANY axis composes onto what was there. */
+ rot: Quat;
+ sx: number; sy: number; sz: number;
+ };
}
interface Drag {
@@ -65,7 +76,11 @@ interface Drag {
downWorld: Pt;
/** Where the press landed, in window-client px — what the slop is measured from. */
downClient: Pt;
- startAngle: number; // rotate: cursor screen-angle around the pivot
+ /** rotate: where the press landed — the ring's own parameter, or the screen
+ * angle around the pivot when no ring took the press. */
+ startAngle: number;
+ /** rotate: which ring was grabbed. Absent = the 2D screen-angle drag. */
+ ring: RotateRing | null;
startDist: number; // scale: cursor screen-distance from the pivot
/** Local-frame angle (world radians) for axis-constrained move; 0 = world axes. */
angleRad: number;
@@ -104,9 +119,18 @@ function readTarget(sourceId: EntityId): Target | null {
if (rtId == null) return null;
const pos = ViewportController.getEntityWorldXY(rtId);
if (!pos) return null;
- const rotDeg = (SceneQuery.getFieldValue(sourceId, 'Transform', 'rotation') as number) ?? 0;
+ // The rotation field reads as three degrees; a drag composes onto the pose they
+ // describe, which is why the whole quaternion is captured and not just its Z.
+ const rot = (SceneQuery.getFieldValue(sourceId, 'Transform', 'rotation') as number[]) ?? [0, 0, 0];
+ const p = (SceneQuery.getFieldValue(sourceId, 'Transform', 'position') as number[]) ?? [0, 0, 0];
const sc = (SceneQuery.getFieldValue(sourceId, 'Transform', 'scale') as number[]) ?? [1, 1, 1];
- return { sourceId, start: { x: pos.x, y: pos.y, rotDeg, sx: sc[0] ?? 1, sy: sc[1] ?? 1, sz: sc[2] ?? 1 } };
+ return {
+ sourceId,
+ start: {
+ x: pos.x, y: pos.y, z: p[2] ?? 0, rot: eulerToQuat(rot),
+ sx: sc[0] ?? 1, sy: sc[1] ?? 1, sz: sc[2] ?? 1,
+ },
+ };
}
/**
@@ -287,6 +311,7 @@ function beginDrag(
cur: Pt,
angleRad = 0,
armed = true,
+ ring: RotateRing | null = null,
): Drag {
const label = kind === 'rotate' ? 'Rotate' : kind === 'scale' ? 'Scale' : 'Move';
// The active target is the one the gizmo sits on, so it is the plane the user
@@ -308,7 +333,12 @@ function beginDrag(
planeZ,
downWorld,
downClient: { x: p.clientX, y: p.clientY },
- startAngle: Math.atan2(cur.y - pivotClient.y, cur.x - pivotClient.x),
+ ring,
+ // A grabbed ring measures in its own parameter; without one this is the
+ // screen angle around the pivot, which is what the 2D drag always used.
+ startAngle: ring
+ ? (ringAngleAt(ring, { x: cur.x - pivotClient.x, y: cur.y - pivotClient.y }, GIZMO.ringRadius) ?? 0)
+ : Math.atan2(cur.y - pivotClient.y, cur.x - pivotClient.x),
// The grab point's screen distance from the pivot. Scale is now delta-based off
// this (not a ratio), so it needs no floor and can't blow up when you grab near
// the pivot (the center box / an entity's body).
@@ -337,24 +367,56 @@ function applyMove(d: Drag, curWorld: Pt): void {
}
function applyRotate(d: Drag, cur: Pt): void {
- const ang = Math.atan2(cur.y - d.pivotClient.y, cur.x - d.pivotClient.x);
- // Screen y is down, so a clockwise screen drag is a negative world rotation.
- let worldDeltaDeg = (-(ang - d.startAngle) * 180) / Math.PI;
+ const offset = { x: cur.x - d.pivotClient.x, y: cur.y - d.pivotClient.y };
+ // The ring's OWN parameter, not the screen angle: the two agree only where the
+ // ring faces the eye, and everywhere else the projection is an ellipse.
+ const now = d.ring ? ringAngleAt(d.ring, offset, GIZMO.ringRadius) : null;
+ let deltaRad = d.ring
+ ? (now === null ? 0 : wrapPi(now - d.startAngle))
+ // Screen y is down, so a clockwise screen drag is a negative world rotation.
+ : -(Math.atan2(offset.y, offset.x) - d.startAngle);
+
const ed = useEditorStore.getState();
if (ed.snapping) {
// Snap the primary's RESULTING absolute angle to the grid, then apply that delta
// to all (like move-snap) — so a 7°-rotated object lands on 15/30/45, not 22/37.
- const r0 = d.targets[0].start.rotDeg;
- worldDeltaDeg = snapTo(r0 + worldDeltaDeg, ed.snapAngle) - r0;
+ const r0 = axisAngleOf(d.targets[0].start.rot, d.ring?.axis ?? 'z');
+ const deg = snapTo(r0 + (deltaRad * 180) / Math.PI, ed.snapAngle) - r0;
+ deltaRad = (deg * Math.PI) / 180;
}
- const rad = (worldDeltaDeg * Math.PI) / 180;
+ const turn = axisQuat(d.ring?.axis ?? 'z', deltaRad);
for (const t of d.targets) {
- const np = rotateAround({ x: t.start.x, y: t.start.y }, d.pivotWorld, rad);
- SceneCommands.setEntityXY(t.sourceId, np.x, np.y);
- SceneCommands.setField(t.sourceId, 'Transform', 'rotation', 'angle', t.start.rotDeg + worldDeltaDeg);
+ // The whole offset from the pivot turns, not just its x/y: about X or Y a
+ // group rotation moves its members through depth.
+ const rel = rotateVecByQuat(
+ { x: t.start.x - d.pivotWorld.x, y: t.start.y - d.pivotWorld.y, z: 0 }, turn);
+ SceneCommands.setField(t.sourceId, 'Transform', 'position', 'vec3',
+ [d.pivotWorld.x + rel.x, d.pivotWorld.y + rel.y, t.start.z + rel.z]);
+ SceneCommands.setField(t.sourceId, 'Transform', 'rotation', 'euler',
+ quatToEuler(quatMul(turn, t.start.rot)));
}
}
+/** An angle folded into (-pi, pi] — a drag past the seam is a small turn, not a full one. */
+function wrapPi(a: number): number {
+ return a - 2 * Math.PI * Math.floor((a + Math.PI) / (2 * Math.PI));
+}
+
+/** How far a pose already turns about one axis, in degrees — what snapping rounds. */
+function axisAngleOf(q: Quat, axis: 'x' | 'y' | 'z'): number {
+ return quatToEuler(q)[axis === 'x' ? 0 : axis === 'y' ? 1 : 2];
+}
+
+/** A vector turned by a quaternion (q·v·q⁻¹, expanded). */
+function rotateVecByQuat(v: { x: number; y: number; z: number }, q: Quat): { x: number; y: number; z: number } {
+ const t = { x: 2 * (q.y * v.z - q.z * v.y), y: 2 * (q.z * v.x - q.x * v.z), z: 2 * (q.x * v.y - q.y * v.x) };
+ return {
+ x: v.x + q.w * t.x + q.y * t.z - q.z * t.y,
+ y: v.y + q.w * t.y + q.z * t.x - q.x * t.z,
+ z: v.z + q.w * t.z + q.x * t.y - q.y * t.x,
+ };
+}
+
function applyScale(d: Drag, cur: Pt): void {
const curDist = Math.hypot(cur.x - d.pivotClient.x, cur.y - d.pivotClient.y);
// Delta-based, referenced to the gizmo's on-screen length — f is exactly 1 at the
@@ -438,9 +500,15 @@ function makeTransformTool(mode: ToolMode): EditorTool {
const pc = pivotWorld ? ViewportController.worldToClient(pivotWorld.x, pivotWorld.y) : null;
if (pivotWorld && pc) {
const localAngle = ed.coordSpace === 'local' ? primaryRotationRad(ids) : 0;
- const handle = hitTestGizmo(mode as GizmoMode, pc, cur, -localAngle);
+ // Rotate aims at rings, which are where the world axes actually project;
+ // a head-on view leaves only the Z one, so a 2D aim is unchanged.
+ const axes = ViewportController.viewAxes();
+ const ring = mode === 'rotate' && axes ? hitTestRings(rotateRings(axes), pc, cur) : null;
+ const handle = mode === 'rotate'
+ ? (ring && { id: `rotate.${ring.axis}`, mode, axis: (ring.axis === 'z' ? 'xy' : ring.axis) as GizmoAxis })
+ : hitTestGizmo(mode as 'move' | 'scale', pc, cur, -localAngle);
if (handle) {
- drag = beginDrag(kind, handle.axis, captureTargets(ids, kind), pivotWorld, pc, p, cur, localAngle);
+ drag = beginDrag(kind, handle.axis, captureTargets(ids, kind), pivotWorld, pc, p, cur, localAngle, true, ring);
ed.setActiveGizmoAxis(handle.axis); // light up the grabbed handle
// Alt-duplicate rides the handle too, now that the body no longer
// transforms — otherwise Alt+drag would have nowhere to happen in the
diff --git a/desktop/tests/entity-ops.test.ts b/desktop/tests/entity-ops.test.ts
index 370bab328..7c5f99480 100644
--- a/desktop/tests/entity-ops.test.ts
+++ b/desktop/tests/entity-ops.test.ts
@@ -24,6 +24,7 @@ vi.mock('@/engine/PlayRealm', () => ({
}));
import { EntityOps } from '@/engine/entityOps';
+import { quatToEuler } from '@/engine/schema';
import { SceneCommands } from '@/engine/SceneCommands';
import { PlayRealm } from '@/engine/PlayRealm';
import { PlayInspect } from '@/engine/PlayInspect';
@@ -118,8 +119,8 @@ describe('while playing', () => {
describe('turning and resizing', () => {
it('composes onto what the document already has', () => {
- const q = Math.SQRT1_2; // a quarter turn
- vi.spyOn(SceneQuery, 'getFieldValue').mockReturnValue({ z: q, w: q } as never);
+ // The field reads as three degrees (X, Y, Z), so a quarter turn adds to the Z.
+ vi.spyOn(SceneQuery, 'getFieldValue').mockReturnValue([0, 0, 90] as never);
expect(EntityOps.turnBy(authoredRef(3), Math.PI / 2)).toBe('document');
const [, , , value] = vi.mocked(SceneCommands.setFieldValue).mock.calls[0];
// Quarter + quarter = half: z 1, w 0.
@@ -127,6 +128,18 @@ describe('turning and resizing', () => {
expect((value as { w: number }).w).toBeCloseTo(0);
});
+ it('keeps a 3D pose while turning about Z', () => {
+ // A model imported with a tilt must survive a nudge — the turn is about Z,
+ // not a fresh rotation built from a Z angle alone.
+ vi.spyOn(SceneQuery, 'getFieldValue').mockReturnValue([30, -45, 10] as never);
+ EntityOps.turnBy(authoredRef(3), Math.PI / 4);
+ const [, , , value] = vi.mocked(SceneCommands.setFieldValue).mock.calls[0];
+ const back = quatToEuler(value as { x: number; y: number; z: number; w: number });
+ expect(back[0]).toBeCloseTo(30, 2);
+ expect(back[1]).toBeCloseTo(-45, 2);
+ expect(back[2]).toBeCloseTo(55, 2);
+ });
+
it('multiplies a resize rather than replacing it', () => {
vi.spyOn(SceneQuery, 'getFieldValue').mockReturnValue({ x: 2, y: 3, z: 1 } as never);
EntityOps.resizeBy(authoredRef(3), { x: 2, y: 0.5 });
diff --git a/desktop/tests/gizmo.test.ts b/desktop/tests/gizmo.test.ts
index f92a7ac91..66df1ea54 100644
--- a/desktop/tests/gizmo.test.ts
+++ b/desktop/tests/gizmo.test.ts
@@ -13,6 +13,12 @@ import {
groupPivot,
rotateAround,
scaleAround,
+ rotateRings,
+ ringPoint,
+ ringAngleAt,
+ hitTestRings,
+ axisQuat,
+ quatMul,
distToSegment,
} from '@/tools/gizmo';
@@ -46,15 +52,6 @@ describe('hitTestGizmo — scale', () => {
});
});
-describe('hitTestGizmo — rotate', () => {
- it('a point on the ring hits the ring', () => {
- expect(hitTestGizmo('rotate', pivot, { x: pivot.x + GIZMO.ringRadius, y: pivot.y })?.id).toBe('rotate.ring');
- });
- it('inside the ring misses', () => {
- expect(hitTestGizmo('rotate', pivot, pivot)).toBeNull();
- });
-});
-
describe('constrainWorldDelta', () => {
it('x axis keeps only dx', () => expect(constrainWorldDelta('x', 5, 9)).toEqual([5, 0]));
it('y axis keeps only dy', () => expect(constrainWorldDelta('y', 5, 9)).toEqual([0, 9]));
@@ -117,3 +114,59 @@ describe('colliderHandleClass', () => {
expect(cls).not.toContain('gizmo-owns-centre');
});
});
+
+describe('the rotate gizmo\'s rings', () => {
+ // Head-on: +X right, +Y up (screen y is down), +Z straight at the eye.
+ const HEAD_ON = { x: { dx: 1, dy: 0 }, y: { dx: 0, dy: -1 }, z: { dx: 0, dy: 0 } };
+ // Orbited 35/22, from the view basis — the same numbers editorViewAxes gives.
+ const TURNED = {
+ x: { dx: 0.8189, dy: 0.2148 },
+ y: { dx: 0, dy: -0.9266 },
+ z: { dx: -0.5733, dy: 0.3068 },
+ };
+
+ it('leaves a head-on gizmo the single Z ring it always had', () => {
+ // The other two are edge-on there — a line, where a cursor names no angle.
+ // So turning three rings on cannot change what a 2D user aims at.
+ expect(rotateRings(HEAD_ON).map((r) => r.axis)).toEqual(['z']);
+ });
+
+ it('offers all three once the eye has turned', () => {
+ expect(rotateRings(TURNED).map((r) => r.axis).sort()).toEqual(['x', 'y', 'z']);
+ });
+
+ it('reads a cursor on a ring back as the parameter that put it there', () => {
+ const ring = rotateRings(TURNED).find((r) => r.axis === 'x')!;
+ for (const t of [0, 0.9, -2.4, 3.0]) {
+ const p = ringPoint(ring, t, GIZMO.ringRadius);
+ expect(ringAngleAt(ring, p, GIZMO.ringRadius)).toBeCloseTo(t, 6);
+ }
+ });
+
+ it('picks the ring the cursor is on, and nothing off them', () => {
+ const rings = rotateRings(TURNED);
+ for (const want of ['x', 'y', 'z'] as const) {
+ const ring = rings.find((r) => r.axis === want)!;
+ const on = ringPoint(ring, 0.6, GIZMO.ringRadius);
+ expect(hitTestRings(rings, { x: 0, y: 0 }, on)?.axis).toBe(want);
+ }
+ expect(hitTestRings(rings, { x: 0, y: 0 }, { x: 0, y: 0 })).toBeNull();
+ });
+
+ it('turns positively from u toward v, so the ring names its own sign', () => {
+ // A quarter turn about +X takes +Y to +Z, which is what the ring's own
+ // parameter runs through — the reason no per-axis sign table exists.
+ const q = axisQuat('x', Math.PI / 2);
+ const rotated = quatMul(quatMul(q, { x: 0, y: 1, z: 0, w: 0 }),
+ { x: -q.x, y: -q.y, z: -q.z, w: q.w });
+ expect(rotated.x).toBeCloseTo(0, 6);
+ expect(rotated.y).toBeCloseTo(0, 6);
+ expect(rotated.z).toBeCloseTo(1, 6);
+ });
+
+ it('composes a world turn on the LEFT of the pose it is applied to', () => {
+ const pose = axisQuat('z', 0.4);
+ const turned = quatMul(axisQuat('z', 0.3), pose);
+ expect(2 * Math.atan2(turned.z, turned.w)).toBeCloseTo(0.7, 6);
+ });
+});
diff --git a/desktop/tests/transform-tool.test.ts b/desktop/tests/transform-tool.test.ts
index 02e8acf85..75c59b183 100644
--- a/desktop/tests/transform-tool.test.ts
+++ b/desktop/tests/transform-tool.test.ts
@@ -23,6 +23,8 @@ vi.mock('@/engine/EngineHost', () => ({
vi.mock('@/engine/ViewportController', () => ({
ViewportController: {
canvasToWorld: (x: number, y: number) => ({ x, y }), // identity: world == client px
+ // Head-on: the rings the rotate tool aims at reduce to the single Z one.
+ viewAxes: () => ({ x: { dx: 1, dy: 0, depth: 0 }, y: { dx: 0, dy: -1, depth: 0 }, z: { dx: 0, dy: 0, depth: 1 } }),
// Flat scene: every plane is z = 0, which is what the orthographic editor
// answers anyway — the drag plane must not change these expectations.
entityPlaneZ: () => 0,