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): Local/World gizmo axes + Center/Pivot transform pivot

esengine3a5075209bc5
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index 54a77abe4..7f146dab9 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -257,6 +257,20 @@ commands.register({
isChecked: () => editor().showColliders,
run: () => editor().toggleColliders(),
});
+commands.register({
+ id: 'view.toggleCoordSpace',
+ label: 'Local Axes',
+ category: 'View',
+ isChecked: () => editor().coordSpace === 'local',
+ run: () => editor().toggleCoordSpace(),
+});
+commands.register({
+ id: 'view.togglePivotMode',
+ label: 'Pivot (vs Center)',
+ category: 'View',
+ isChecked: () => editor().pivotMode === 'pivot',
+ run: () => editor().togglePivotMode(),
+});
commands.register({
id: 'view.toggleSnapping',
label: 'Snapping',
diff --git a/desktop/src/layout/MenuBar.tsx b/desktop/src/layout/MenuBar.tsx
index 7d9d22c32..899a7e5be 100644
--- a/desktop/src/layout/MenuBar.tsx
+++ b/desktop/src/layout/MenuBar.tsx
@@ -122,6 +122,9 @@ export function MenuBar() {
cmdItem('view.toggleGrid'),
cmdItem('view.toggleGizmos'),
cmdItem('view.toggleColliders'),
+ { sep: true },
+ cmdItem('view.toggleCoordSpace'),
+ cmdItem('view.togglePivotMode'),
cmdItem('view.toggleSnapping'),
],
},
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 1925f360f..0ea93ad85 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -4,7 +4,7 @@ import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'reac
import type { PointerEvent as ReactPointerEvent, DragEvent as ReactDragEvent, ReactNode } from 'react';
import {
MousePointer2, Move, RotateCw, Scale3d, Grid3x3, Eye, Frame,
- Camera, Check, ChevronDown, Loader2, TriangleAlert, Lightbulb, type LucideIcon,
+ Camera, Check, ChevronDown, Loader2, TriangleAlert, Lightbulb, Globe, Crosshair, type LucideIcon,
} from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import { useSelection } from '@/store/selectionStore';
@@ -22,6 +22,7 @@ import type { ToolMode } from '@/types';
import { resolveActiveTool, type EditorTool, type ToolContext, type PointerInput } from '@/tools';
import { cursorTile } from '@/tools/tileTools';
import { GIZMO, type GizmoAxis } from '@/tools/gizmo';
+import { selectionPivot, gizmoScreenAngleRad } from '@/tools/transformTools';
import { Marquee } from '@/tools/marquee';
// A React pointer event → the tool-facing PointerInput (no DOM coupling in tools).
@@ -203,6 +204,8 @@ export function Viewport() {
const showGizmos = useEditorStore((s) => s.showGizmos);
const showColliders = useEditorStore((s) => s.showColliders);
const activeGizmoAxis = useEditorStore((s) => s.activeGizmoAxis);
+ const coordSpace = useEditorStore((s) => s.coordSpace);
+ const pivotMode = useEditorStore((s) => s.pivotMode);
const snapping = useEditorStore((s) => s.snapping);
const snapStep = useEditorStore((s) => s.snapStep);
const snapAngle = useEditorStore((s) => s.snapAngle);
@@ -316,10 +319,9 @@ export function Viewport() {
const toolMode = useEditorStore.getState().tool;
// Per-entity selection outlines (one div per selected source id).
- let sumX = 0;
- let sumY = 0;
- let nPos = 0;
+ const selIds: number[] = [];
for (const [sid, el] of selRefs.current) {
+ selIds.push(sid);
if (!el) continue;
const rt = ready ? SceneModel.runtimeFor(sid) : undefined;
const rect = rt != null ? ViewportController.getEntityScreenRect(rt) : null;
@@ -328,22 +330,19 @@ export function Viewport() {
el.style.width = `${rect.w}px`;
el.style.height = `${rect.h}px`;
el.style.opacity = '1';
- const pos = ViewportController.getEntityXY(rt!);
- if (pos) {
- sumX += pos.x;
- sumY += pos.y;
- nPos += 1;
- }
} else {
el.style.opacity = '0';
}
}
- // The transform gizmo sits at the selection pivot (centroid), and only for the
- // move/rotate/scale tools — the select tool shows just the outline.
- const pivot = nPos > 0 ? ViewportController.worldToClient(sumX / nPos, sumY / nPos) : null;
+ // The transform gizmo sits at the selection pivot (centroid or active-entity
+ // pivot per pivotMode), rotated to the active entity's axes in local space.
+ // Only for the move/rotate/scale tools — select shows just the outline.
+ const pivotWorld = ready && selIds.length ? selectionPivot(selIds) : null;
+ const pivot = pivotWorld ? ViewportController.worldToClient(pivotWorld.x, pivotWorld.y) : null;
if (pivot && showG && toolMode !== 'select') {
- g.style.transform = `translate(${pivot.x}px, ${pivot.y}px)`;
+ const angDeg = (gizmoScreenAngleRad(selIds) * 180) / Math.PI;
+ g.style.transform = `translate(${pivot.x}px, ${pivot.y}px) rotate(${angDeg}deg)`;
g.style.opacity = '1';
} else {
g.style.opacity = '0';
@@ -629,6 +628,25 @@ export function Viewport() {
</OvDropdown>
<span className="ov-divider" />
<OvTool icon={Frame} label="Frame Selected (F)" kbd="F" onClick={() => commands.run('view.frameSelected')} />
+ <span className="ov-divider" />
+ <button
+ type="button"
+ className={`ovbtn${coordSpace === 'local' ? ' active' : ''}`}
+ title="Gizmo axes: World / Local (the active object's own axes)"
+ onClick={() => commands.run('view.toggleCoordSpace')}
+ >
+ <Globe size={13} strokeWidth={1.9} />
+ <span className="val">{coordSpace === 'local' ? 'Local' : 'World'}</span>
+ </button>
+ <button
+ type="button"
+ className={`ovbtn${pivotMode === 'pivot' ? ' active' : ''}`}
+ title="Gizmo pivot: Center of selection / the active object's Pivot"
+ onClick={() => commands.run('view.togglePivotMode')}
+ >
+ <Crosshair size={13} strokeWidth={1.9} />
+ <span className="val">{pivotMode === 'pivot' ? 'Pivot' : 'Center'}</span>
+ </button>
</div>
</div>
diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.ts
index 3ae8645d2..1181b61fb 100644
--- a/desktop/src/store/editorStore.ts
+++ b/desktop/src/store/editorStore.ts
@@ -47,6 +47,12 @@ interface EditorState {
// 15° / 0.1 constants so they're user-tunable from the viewport snap menu.
snapAngle: number;
snapScale: number;
+ /** Gizmo axis frame: world-aligned, or rotated to the active entity's local axes. */
+ coordSpace: 'world' | 'local';
+ /** Gizmo pivot: the selection's centroid (center), or the active entity's own pivot. */
+ pivotMode: 'center' | 'pivot';
+ toggleCoordSpace: () => void;
+ togglePivotMode: () => void;
/** Axis of the gizmo handle currently being dragged (null = none) — drives the
* handle's active highlight. Set by the transform tool on grab, cleared on release. */
activeGizmoAxis: GizmoAxis | null;
@@ -108,6 +114,10 @@ export const useEditorStore = create<EditorState>((set) => ({
snapStep: 32,
snapAngle: 15,
snapScale: 0.1,
+ coordSpace: 'world',
+ pivotMode: 'center',
+ toggleCoordSpace: () => set((s) => ({ coordSpace: s.coordSpace === 'world' ? 'local' : 'world' })),
+ togglePivotMode: () => set((s) => ({ pivotMode: s.pivotMode === 'center' ? 'pivot' : 'center' })),
activeGizmoAxis: null,
setActiveGizmoAxis: (activeGizmoAxis) => set({ activeGizmoAxis }),
toggleGrid: () => set((s) => ({ showGrid: !s.showGrid })),
diff --git a/desktop/src/tools/gizmo.ts b/desktop/src/tools/gizmo.ts
index bf26f11ba..253921939 100644
--- a/desktop/src/tools/gizmo.ts
+++ b/desktop/src/tools/gizmo.ts
@@ -55,14 +55,23 @@ export function distToSegment(p: Pt, a: Pt, b: Pt): number {
const within = (p: Pt, c: Pt, half: number): boolean => Math.abs(p.x - c.x) <= half && Math.abs(p.y - c.y) <= half;
const along = (pivot: Pt, dir: Pt, d: number): Pt => ({ x: pivot.x + dir.x * d, y: pivot.y + dir.y * d });
+/** Rotate a screen-space direction by `a` radians (screen frame). */
+function rotDir(dir: Pt, a: number): Pt {
+ const c = Math.cos(a);
+ const s = Math.sin(a);
+ return { x: dir.x * c - dir.y * s, y: dir.x * s + dir.y * c };
+}
+
/**
* The handle under `cursor` for the active gizmo at `pivot` (all CSS px), or null.
* Central handles (plane / uniform box / nothing) are tested before the axes so the
- * smaller, foreground targets win.
+ * smaller, foreground targets win. `axisAngleRad` rotates the axis arrows to the
+ * 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): GizmoHandle | null {
- const xEnd = along(pivot, X_DIR, GIZMO.axisLen);
- const yEnd = along(pivot, Y_DIR, GIZMO.axisLen);
+export function hitTestGizmo(mode: GizmoMode, 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);
if (mode === 'move') {
if (within(cursor, pivot, GIZMO.planeSize / 2)) return { id: 'move.xy', mode, axis: 'xy' };
@@ -84,13 +93,30 @@ export function hitTestGizmo(mode: GizmoMode, pivot: Pt, cursor: Pt): GizmoHandl
return null;
}
-/** Constrain a world-space delta to a handle's axis. */
+/** Constrain a world-space delta to a handle's axis (world-aligned axes). */
export function constrainWorldDelta(axis: GizmoAxis, dx: number, dy: number): [number, number] {
if (axis === 'x') return [dx, 0];
if (axis === 'y') return [0, dy];
return [dx, dy];
}
+/**
+ * Constrain a world-space delta to a handle's axis rotated into the object's local
+ * frame by `angleRad` (the entity's world rotation, +Y up). The delta is projected
+ * onto the local axis so a single-axis drag slides along the object's own X/Y.
+ * `xy` is unconstrained. With `angleRad === 0` this equals {@link constrainWorldDelta}.
+ */
+export function constrainLocalDelta(axis: GizmoAxis, dx: number, dy: number, angleRad: number): [number, number] {
+ if (axis === 'xy') return [dx, dy];
+ const c = Math.cos(angleRad);
+ const s = Math.sin(angleRad);
+ // Local X = (cosθ, sinθ); local Y = (−sinθ, cosθ) in world space (+Y up).
+ const ax = axis === 'x' ? c : -s;
+ const ay = axis === 'x' ? s : c;
+ const k = dx * ax + dy * ay; // project the delta onto the chosen local axis
+ return [k * ax, k * ay];
+}
+
/** Centroid of a set of world points — the group transform pivot for multi-select. */
export function groupPivot(points: readonly Pt[]): Pt {
if (points.length === 0) return { x: 0, y: 0 };
diff --git a/desktop/src/tools/transformTools.ts b/desktop/src/tools/transformTools.ts
index 320904947..40212206e 100644
--- a/desktop/src/tools/transformTools.ts
+++ b/desktop/src/tools/transformTools.ts
@@ -26,7 +26,7 @@ import {
type GizmoMode,
type Pt,
hitTestGizmo,
- constrainWorldDelta,
+ constrainLocalDelta,
groupPivot,
rotateAround,
scaleAround,
@@ -51,6 +51,8 @@ interface Drag {
downWorld: Pt;
startAngle: number; // rotate: cursor screen-angle around the pivot
startDist: number; // scale: cursor screen-distance from the pivot
+ /** Local-frame angle (world radians) for axis-constrained move; 0 = world axes. */
+ angleRad: number;
targets: Target[];
}
@@ -85,7 +87,7 @@ function captureTargets(ids: readonly EntityId[]): Target[] {
return ids.map(readTarget).filter((t): t is Target => t !== null);
}
-/** Selection pivot = centroid of the live world positions of `ids`. */
+/** Selection centroid = mean of the live world positions of `ids`. */
function pivotOf(ids: readonly EntityId[]): Pt | null {
const pts: Pt[] = [];
for (const sid of ids) {
@@ -97,6 +99,41 @@ function pivotOf(ids: readonly EntityId[]): Pt | null {
return pts.length ? groupPivot(pts) : null;
}
+/** The active (primary) entity of a selection — the one local space / pivot mode key off. */
+function primaryOf(ids: readonly EntityId[]): EntityId | null {
+ const primary = useSelection.getState().selectedId;
+ return primary != null && ids.includes(primary) ? primary : (ids[0] ?? null);
+}
+
+/** The active entity's world rotation in radians (drives local-axis frame). */
+function primaryRotationRad(ids: readonly EntityId[]): number {
+ const id = primaryOf(ids);
+ if (id == null) return 0;
+ const deg = (SceneQuery.getFieldValue(id, 'Transform', 'rotation') as number) ?? 0;
+ return (deg * Math.PI) / 180;
+}
+
+/**
+ * The gizmo pivot for the current `pivotMode`: the active entity's own position
+ * ('pivot'), else the selection centroid ('center'). Shared by the tool and the
+ * viewport's gizmo placement so both agree.
+ */
+export function selectionPivot(ids: readonly EntityId[]): Pt | null {
+ if (useEditorStore.getState().pivotMode === 'pivot') {
+ const id = primaryOf(ids);
+ const rt = id != null ? SceneModel.runtimeFor(id) : null;
+ const pos = rt != null ? ViewportController.getEntityXY(rt) : null;
+ if (pos) return pos;
+ }
+ return pivotOf(ids);
+}
+
+/** The gizmo's on-screen rotation (radians): the negated active rotation in local
+ * space (screen y is down), else 0. Shared with the viewport's gizmo render. */
+export function gizmoScreenAngleRad(ids: readonly EntityId[]): number {
+ return useEditorStore.getState().coordSpace === 'local' ? -primaryRotationRad(ids) : 0;
+}
+
/**
* Alt-drag: clone each id and return targets that drag from the *originals'* start
* transforms (so the copies track the cursor exactly, the clone offset overwritten
@@ -129,6 +166,7 @@ function beginDrag(
pivotClient: Pt,
p: PointerInput,
cur: Pt,
+ angleRad = 0,
): Drag {
const label = kind === 'rotate' ? 'Rotate' : kind === 'scale' ? 'Scale' : 'Move';
const downWorld = ViewportController.canvasToWorld(p.clientX, p.clientY) ?? { x: 0, y: 0 };
@@ -141,6 +179,7 @@ function beginDrag(
downWorld,
startAngle: Math.atan2(cur.y - pivotClient.y, cur.x - pivotClient.x),
startDist: Math.max(1, Math.hypot(cur.x - pivotClient.x, cur.y - pivotClient.y)),
+ angleRad,
targets,
};
}
@@ -148,7 +187,9 @@ function beginDrag(
function applyMove(d: Drag, curWorld: Pt): void {
let dx = curWorld.x - d.downWorld.x;
let dy = curWorld.y - d.downWorld.y;
- [dx, dy] = constrainWorldDelta(d.axis, dx, dy);
+ // angleRad is 0 for world axes (→ identical to constrainWorldDelta) and the
+ // entity's rotation for local axes, so the drag slides along the object's own X/Y.
+ [dx, dy] = constrainLocalDelta(d.axis, dx, dy, d.angleRad);
const ed = useEditorStore.getState();
if (ed.snapping && d.targets.length) {
// Snap the primary's resulting position to the grid, apply that delta to all,
@@ -210,12 +251,13 @@ function makeTransformTool(mode: ToolMode): EditorTool {
// 1) Gizmo handle → axis-constrained transform of the current selection.
if (mode !== 'select' && ed.showGizmos && sel.selectedIds.size > 0) {
const ids = [...sel.selectedIds];
- const pivotWorld = pivotOf(ids);
+ const pivotWorld = selectionPivot(ids);
const pc = pivotWorld ? ViewportController.worldToClient(pivotWorld.x, pivotWorld.y) : null;
if (pivotWorld && pc) {
- const handle = hitTestGizmo(mode as GizmoMode, pc, cur);
+ const localAngle = ed.coordSpace === 'local' ? primaryRotationRad(ids) : 0;
+ const handle = hitTestGizmo(mode as GizmoMode, pc, cur, -localAngle);
if (handle) {
- drag = beginDrag(kind, handle.axis, captureTargets(ids), pivotWorld, pc, p, cur);
+ drag = beginDrag(kind, handle.axis, captureTargets(ids), pivotWorld, pc, p, cur, localAngle);
ed.setActiveGizmoAxis(handle.axis); // light up the grabbed handle
ctx.capture(p.pointerId);
return true;
@@ -243,7 +285,7 @@ function makeTransformTool(mode: ToolMode): EditorTool {
pivotWorld = dup.pivot;
} else {
targets = captureTargets(ids);
- pivotWorld = pivotOf(ids);
+ pivotWorld = selectionPivot(ids);
}
if (!targets.length || !pivotWorld) return false;
const pc = ViewportController.worldToClient(pivotWorld.x, pivotWorld.y) ?? cur;
diff --git a/desktop/tests/gizmo-local-pivot.test.ts b/desktop/tests/gizmo-local-pivot.test.ts
new file mode 100644
index 000000000..83d1fe503
--- /dev/null
+++ b/desktop/tests/gizmo-local-pivot.test.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Local-space gizmo math: axis-rotated hit-testing + local-frame delta
+ * constraint (the Local/World coordinate-space toggle).
+ */
+import { describe, it, expect } from 'vitest';
+import { hitTestGizmo, constrainLocalDelta, constrainWorldDelta, GIZMO } from '@/tools/gizmo';
+
+const pivot = { x: 100, y: 100 };
+const close = (a: number, b: number, eps = 1e-9) => expect(Math.abs(a - b)).toBeLessThanOrEqual(eps);
+
+describe('constrainLocalDelta', () => {
+ it('matches constrainWorldDelta at angle 0', () => {
+ // Per-component (signed-zero: -0 is numerically equal but `toEqual` distinguishes it).
+ const [ax, ay] = constrainLocalDelta('x', 3, 4, 0);
+ close(ax, 3); close(ay, 0);
+ const [bx, by] = constrainLocalDelta('y', 3, 4, 0);
+ close(bx, 0); close(by, 4);
+ expect(constrainLocalDelta('xy', 3, 4, 0)).toEqual([3, 4]);
+ });
+
+ it('projects onto the rotated local axis (90°)', () => {
+ // Local X = (0,1): the x-handle slides along world +Y, so (3,4) → (0,4).
+ const [x1, y1] = constrainLocalDelta('x', 3, 4, Math.PI / 2);
+ close(x1, 0); close(y1, 4);
+ // Local Y = (-1,0): the y-handle slides along world −X, so (3,4) → (3,0).
+ const [x2, y2] = constrainLocalDelta('y', 3, 4, Math.PI / 2);
+ close(x2, 3); close(y2, 0);
+ });
+
+ it('leaves xy unconstrained at any angle', () => {
+ expect(constrainLocalDelta('xy', 3, 4, 1.234)).toEqual([3, 4]);
+ });
+
+ it('keeps only the component along a 45° local axis', () => {
+ // Local X = (√½, √½); a delta perpendicular to it projects to ~0.
+ const [x, y] = constrainLocalDelta('x', 1, -1, Math.PI / 4);
+ close(x, 0); close(y, 0);
+ });
+});
+
+describe('hitTestGizmo with axisAngleRad', () => {
+ it('angle 0 is unchanged (world +X hits move.x)', () => {
+ const h = hitTestGizmo('move', pivot, { x: pivot.x + GIZMO.axisLen, y: pivot.y }, 0);
+ expect(h?.axis).toBe('x');
+ });
+
+ it('rotates the x-arrow: at 90° the x-handle points along screen +Y', () => {
+ // rotDir((1,0), 90°) = (0,1) → xEnd at (100, 100+axisLen).
+ const onRotatedX = hitTestGizmo('move', pivot, { x: pivot.x, y: pivot.y + GIZMO.axisLen }, Math.PI / 2);
+ expect(onRotatedX?.axis).toBe('x');
+ // The old world +X spot is no longer the x-handle.
+ const offWorldX = hitTestGizmo('move', pivot, { x: pivot.x + GIZMO.axisLen, y: pivot.y }, Math.PI / 2);
+ expect(offWorldX?.axis).not.toBe('x');
+ });
+});