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(viewport): UE-style gizmo handles, multi-select, marquee, group transforms

esenginee4295e145eb2
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index 2223b3e0e..8f7a8c480 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -12,6 +12,7 @@ import { commands } from './registry';
import { ProjectStore } from '@/project/ProjectStore';
import { EditorHistory } from '@/engine/EditorHistory';
import { SceneCommands } from '@/engine/SceneCommands';
+import { SceneModel } from '@/engine/SceneModel';
import { ViewportController } from '@/engine/ViewportController';
import { useEditorStore } from '@/store/editorStore';
import { useSelection } from '@/store/selectionStore';
@@ -137,6 +138,42 @@ commands.register({ id: 'tool.move', label: 'Move Tool', category: 'Tools', keyb
commands.register({ id: 'tool.rotate', label: 'Rotate Tool', category: 'Tools', keybinding: 'e', run: tool('rotate') });
commands.register({ id: 'tool.scale', label: 'Scale Tool', category: 'Tools', keybinding: 'r', run: tool('scale') });
+// — Keyboard nudge — arrow keys move the selection by one grid step (Shift = ×10),
+// world +Y is up so ArrowUp adds to Y. One undo step; the Outliner stops arrows from
+// reaching here while it's focused (tree nav owns them there).
+function nudgeSelection(ux: number, uy: number, big: boolean): void {
+ const ids = [...sel().selectedIds];
+ if (!ids.length) return;
+ const step = editor().snapStep * (big ? 10 : 1);
+ SceneCommands.transact('Nudge', () => {
+ for (const sid of ids) {
+ const rt = SceneModel.runtimeFor(sid);
+ const pos = rt != null ? ViewportController.getEntityXY(rt) : null;
+ if (pos) SceneCommands.setEntityXY(sid, pos.x + ux * step, pos.y + uy * step);
+ }
+ });
+}
+const NUDGES: Array<{ id: string; key: string; ux: number; uy: number; big: boolean }> = [
+ { id: 'entity.nudgeLeft', key: 'left', ux: -1, uy: 0, big: false },
+ { id: 'entity.nudgeRight', key: 'right', ux: 1, uy: 0, big: false },
+ { id: 'entity.nudgeUp', key: 'up', ux: 0, uy: 1, big: false },
+ { id: 'entity.nudgeDown', key: 'down', ux: 0, uy: -1, big: false },
+ { id: 'entity.nudgeLeftBig', key: 'shift+left', ux: -1, uy: 0, big: true },
+ { id: 'entity.nudgeRightBig', key: 'shift+right', ux: 1, uy: 0, big: true },
+ { id: 'entity.nudgeUpBig', key: 'shift+up', ux: 0, uy: 1, big: true },
+ { id: 'entity.nudgeDownBig', key: 'shift+down', ux: 0, uy: -1, big: true },
+];
+for (const n of NUDGES) {
+ commands.register({
+ id: n.id,
+ label: 'Nudge Selection',
+ category: 'Entity',
+ keybinding: n.key,
+ isEnabled: () => sel().selectedIds.size > 0,
+ run: () => nudgeSelection(n.ux, n.uy, n.big),
+ });
+}
+
// — Viewport / view —
commands.register({
id: 'view.frameSelected',
@@ -145,8 +182,8 @@ commands.register({
keybinding: 'f',
isEnabled: () => sel().selectedId != null,
run: () => {
- const id = sel().selectedId;
- if (id != null) ViewportController.frameEntity(id);
+ const ids = [...sel().selectedIds];
+ if (ids.length > 0) ViewportController.frameSelection(ids);
},
});
commands.register({
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index 426bb6ccf..06965141a 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -4,6 +4,23 @@ import { Camera, CameraView, EditorView, Light2D, Sprite, Transform } from 'esen
import type { EntityId } from '@/types';
import { EngineHost } from './EngineHost';
import { SceneModel } from './SceneModel';
+import {
+ type OBB,
+ type ClientRect,
+ quatAngleZ,
+ obbCorners,
+ pointInOBB,
+ rectsIntersect,
+ screenAABB,
+ clamp,
+} from './viewportMath';
+
+// World half-size of the pick/outline box for entities without renderable bounds
+// (cameras, lights, empties) — so they're click-selectable like any sprite.
+const ICON_WORLD_HALF = 24;
+// Pick priority for icon-only entities: above any real sprite layer, so a small
+// foreground gizmo (camera/light) wins a tie against a big sprite beneath it.
+const ICON_PICK_LAYER = 1e6;
// Structural shape of the engine's CameraView resource (screen<->world).
interface CameraViewLike {
@@ -58,7 +75,44 @@ export const ViewportController = {
return { x: s.x / dpr, y: (canvas.height - s.y) / dpr }; // un-flip, to CSS px
},
- /** Topmost sprite under a pointer (AABB test in world space), or null. */
+ /**
+ * World-space oriented bounding box of any entity (rotation-aware). Sprites use
+ * `size × scale` about their pivot; entities without renderable bounds (cameras,
+ * lights, empties) get a fixed icon box so they're still selectable. The center is
+ * the geometric center, which for an off-center pivot orbits the rotation pivot
+ * (= transform position).
+ */
+ entityBounds(id: EntityId): OBB | null {
+ const world = EngineHost.world;
+ if (!world || !world.valid(id) || !world.has(id, Transform)) return null;
+ const t = world.get(id, Transform);
+ const rot = quatAngleZ(t.rotation as { w: number; x: number; y: number; z: number });
+
+ let w = ICON_WORLD_HALF * 2;
+ let h = ICON_WORLD_HALF * 2;
+ let px = 0.5;
+ let py = 0.5;
+ if (world.has(id, Sprite)) {
+ const sp = world.get(id, Sprite);
+ w = sp.size.x * t.scale.x;
+ h = sp.size.y * t.scale.y;
+ px = sp.pivot?.x ?? 0.5;
+ py = sp.pivot?.y ?? 0.5;
+ }
+ const ox = w * (0.5 - px);
+ const oy = h * (0.5 - py);
+ const c = Math.cos(rot);
+ const s = Math.sin(rot);
+ return {
+ cx: t.position.x + ox * c - oy * s,
+ cy: t.position.y + ox * s + oy * c,
+ hw: Math.abs(w) / 2,
+ hh: Math.abs(h) / 2,
+ rot,
+ };
+ },
+
+ /** Topmost entity whose oriented bounds contain the pointer, or null. */
pickEntity(clientX: number, clientY: number): EntityId | null {
const world = EngineHost.world;
const wp = this.canvasToWorld(clientX, clientY);
@@ -67,30 +121,36 @@ export const ViewportController = {
let best: EntityId | null = null;
let bestLayer = -Infinity;
for (const e of world.getAllEntities()) {
- if (!world.has(e, Sprite) || !world.has(e, Transform)) continue;
+ if (!world.has(e, Transform)) continue;
// Locked / editor-hidden entities aren't click-selectable in the viewport.
const src = SceneModel.sourceFor(e);
if (src != null && (SceneModel.isLocked(src) || SceneModel.isHidden(src))) continue;
- const t = world.get(e, Transform);
- const sp = world.get(e, Sprite);
- const w = sp.size.x * t.scale.x;
- const h = sp.size.y * t.scale.y;
- const px = sp.pivot?.x ?? 0.5;
- const py = sp.pivot?.y ?? 0.5;
- const left = t.position.x - w * px;
- const right = t.position.x + w * (1 - px);
- const bottom = t.position.y - h * py;
- const top = t.position.y + h * (1 - py);
- if (wp.x >= left && wp.x <= right && wp.y >= bottom && wp.y <= top) {
- if (sp.layer >= bestLayer) {
- bestLayer = sp.layer;
- best = e;
- }
+ const b = this.entityBounds(e);
+ if (!b || !pointInOBB(wp.x, wp.y, b)) continue;
+ const layer = world.has(e, Sprite) ? world.get(e, Sprite).layer : ICON_PICK_LAYER;
+ if (layer >= bestLayer) {
+ bestLayer = layer;
+ best = e;
}
}
return best;
},
+ /** Entities whose screen bounds intersect a client-space rect (marquee box-select). */
+ pickInRect(rect: ClientRect): EntityId[] {
+ const world = EngineHost.world;
+ if (!world) return [];
+ const out: EntityId[] = [];
+ for (const e of world.getAllEntities()) {
+ if (!world.has(e, Transform)) continue;
+ const src = SceneModel.sourceFor(e);
+ if (src != null && (SceneModel.isLocked(src) || SceneModel.isHidden(src))) continue;
+ const r = this.getEntityScreenRect(e);
+ if (r && rectsIntersect(rect, r)) out.push(e);
+ }
+ return out;
+ },
+
getEntityXY(id: EntityId): { x: number; y: number } | null {
const world = EngineHost.world;
if (!world || !world.valid(id) || !world.has(id, Transform)) return null;
@@ -99,41 +159,10 @@ export const ViewportController = {
},
/** Screen-space bounding rect (CSS px rel. canvas) of an entity, for the selection outline. */
- getEntityScreenRect(id: EntityId): { x: number; y: number; w: number; h: number } | null {
- const world = EngineHost.world;
- if (!world || !world.valid(id) || !world.has(id, Transform)) return null;
- const t = world.get(id, Transform);
-
- let w = 40;
- let h = 40;
- let px = 0.5;
- let py = 0.5;
- if (world.has(id, Sprite)) {
- const sp = world.get(id, Sprite);
- w = sp.size.x * t.scale.x;
- h = sp.size.y * t.scale.y;
- px = sp.pivot?.x ?? 0.5;
- py = sp.pivot?.y ?? 0.5;
- }
-
- const cx = t.position.x;
- const cy = t.position.y;
- const worldCorners: Array<[number, number]> = [
- [cx - w * px, cy - h * py],
- [cx + w * (1 - px), cy - h * py],
- [cx + w * (1 - px), cy + h * (1 - py)],
- [cx - w * px, cy + h * (1 - py)],
- ];
-
- const screen = worldCorners.map(([wx, wy]) => this.worldToClient(wx, wy));
- if (screen.some((p) => !p)) return null;
- const xs = screen.map((p) => p!.x);
- const ys = screen.map((p) => p!.y);
- const minX = Math.min(...xs);
- const maxX = Math.max(...xs);
- const minY = Math.min(...ys);
- const maxY = Math.max(...ys);
- return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
+ getEntityScreenRect(id: EntityId): ClientRect | null {
+ const b = this.entityBounds(id);
+ if (!b) return null;
+ return screenAABB(obbCorners(b).map(([wx, wy]) => this.worldToClient(wx, wy)));
},
/** Pan the editor view by a CSS-pixel drag (prev→cur). Moves only the editor camera. */
@@ -154,13 +183,40 @@ export const ViewportController = {
view.orthoSize = Math.max(8, Math.min(40000, view.orthoSize * factor));
},
- /** Center the editor view on an entity (frame-selected). */
- frameEntity(id: EntityId): void {
+ /**
+ * Frame a set of entities: center the editor view on their union bounds and zoom
+ * to fit (with padding). Empty / single-point selections keep the current zoom and
+ * just re-center, so a one-entity Frame doesn't jarringly snap the zoom.
+ */
+ frameSelection(ids: readonly EntityId[]): void {
const view = editorView();
- const pos = this.getEntityXY(id);
- if (!view || !pos) return;
- view.x = pos.x;
- view.y = pos.y;
+ const canvas = EngineHost.canvas;
+ if (!view || ids.length === 0) return;
+
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ for (const id of ids) {
+ const b = this.entityBounds(id);
+ if (!b) continue;
+ for (const [wx, wy] of obbCorners(b)) {
+ minX = Math.min(minX, wx);
+ minY = Math.min(minY, wy);
+ maxX = Math.max(maxX, wx);
+ maxY = Math.max(maxY, wy);
+ }
+ }
+ if (!Number.isFinite(minX)) return;
+ view.x = (minX + maxX) / 2;
+ view.y = (minY + maxY) / 2;
+
+ const spanX = maxX - minX;
+ const spanY = maxY - minY;
+ const aspect = canvas && canvas.height > 0 ? canvas.width / canvas.height : 1;
+ // orthoSize is the view half-height; fit whichever axis is the binding constraint.
+ const halfH = Math.max(spanY / 2, aspect > 0 ? spanX / 2 / aspect : spanX / 2) * 1.2;
+ if (halfH > 1) view.orthoSize = clamp(halfH, 8, 40000);
},
/** Ids of the scene's camera entities — the camera-gizmo set (structural). */
diff --git a/desktop/src/engine/viewportMath.ts b/desktop/src/engine/viewportMath.ts
new file mode 100644
index 000000000..66785a57d
--- /dev/null
+++ b/desktop/src/engine/viewportMath.ts
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file viewportMath.ts
+ * @brief Pure 2D geometry for viewport picking, marquee, and gizmos — no engine /
+ * DOM coupling, so it unit-tests in isolation. The imperative shells
+ * (ViewportController picking, the gizmo tools) layer on top of these.
+ */
+
+/** Oriented bounding box in world space: center, half-extents, Z rotation (radians). */
+export interface OBB {
+ cx: number;
+ cy: number;
+ hw: number;
+ hh: number;
+ rot: number;
+}
+
+/** An axis-aligned rect in CSS-pixel (client) space. */
+export interface ClientRect {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+}
+
+/** Z angle (radians) of a rotation quaternion — the only DOF a 2D transform uses. */
+export function quatAngleZ(q: { w: number; x: number; y: number; z: number }): number {
+ return Math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z));
+}
+
+/** The four world-space corners of an OBB, CCW from the (−hw,−hh) local corner. */
+export function obbCorners(b: OBB): Array<[number, number]> {
+ const c = Math.cos(b.rot);
+ const s = Math.sin(b.rot);
+ return ([[-b.hw, -b.hh], [b.hw, -b.hh], [b.hw, b.hh], [-b.hw, b.hh]] as const).map(
+ ([lx, ly]) => [b.cx + lx * c - ly * s, b.cy + lx * s + ly * c] as [number, number],
+ );
+}
+
+/** Whether a world point lies inside an OBB (transform the point into the box's local frame). */
+export function pointInOBB(px: number, py: number, b: OBB): boolean {
+ const dx = px - b.cx;
+ const dy = py - b.cy;
+ const c = Math.cos(-b.rot);
+ const s = Math.sin(-b.rot);
+ const lx = dx * c - dy * s;
+ const ly = dx * s + dy * c;
+ return Math.abs(lx) <= b.hw && Math.abs(ly) <= b.hh;
+}
+
+/** Whether two client rects overlap (touching edges count as overlap). */
+export function rectsIntersect(a: ClientRect, b: ClientRect): boolean {
+ return a.x <= b.x + b.w && b.x <= a.x + a.w && a.y <= b.y + b.h && b.y <= a.y + a.h;
+}
+
+/** Screen-space (CSS-px) AABB of a set of projected points, or null if any failed to project. */
+export function screenAABB(points: Array<{ x: number; y: number } | null>): ClientRect | null {
+ if (points.some((p) => !p)) return null;
+ const xs = points.map((p) => p!.x);
+ const ys = points.map((p) => p!.y);
+ const minX = Math.min(...xs);
+ const minY = Math.min(...ys);
+ return { x: minX, y: minY, w: Math.max(...xs) - minX, h: Math.max(...ys) - minY };
+}
+
+export const clamp = (v: number, lo: number, hi: number): number => Math.max(lo, Math.min(hi, v));
+
+/** Round to the nearest multiple of `step` (snap). `step <= 0` returns `v` unchanged. */
+export const snapTo = (v: number, step: number): number => (step > 0 ? Math.round(v / step) * step : v);
diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsx
index ba2e65dfc..18f9d7708 100644
--- a/desktop/src/panels/Outliner.tsx
+++ b/desktop/src/panels/Outliner.tsx
@@ -193,6 +193,9 @@ export function Outliner() {
};
const onKeyDown = (e: React.KeyboardEvent) => {
if ((e.target as HTMLElement).tagName === 'INPUT' || renaming != null) return; // typing
+ // When the Outliner is focused it owns the arrow keys (tree nav) — stop them
+ // reaching the global keymap, where they'd also nudge the viewport selection.
+ if (e.key.startsWith('Arrow')) e.stopPropagation();
switch (e.key) {
case 'ArrowDown': e.preventDefault(); moveCursor(1); break;
case 'ArrowUp': e.preventDefault(); moveCursor(-1); break;
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index e667926e3..2fde68490 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -20,6 +20,8 @@ import { StatsStore } from '@/engine/StatsStore';
import type { ToolMode } from '@/types';
import { resolveActiveTool, type EditorTool, type ToolContext, type PointerInput } from '@/tools';
import { cursorTile } from '@/tools/tileTools';
+import { GIZMO } from '@/tools/gizmo';
+import { Marquee } from '@/tools/marquee';
// A React pointer event → the tool-facing PointerInput (no DOM coupling in tools).
const toInput = (e: ReactPointerEvent): PointerInput => ({
@@ -27,45 +29,42 @@ const toInput = (e: ReactPointerEvent): PointerInput => ({
button: e.button, shift: e.shiftKey, alt: e.altKey,
});
-// Visual manipulation glyph, centered on the selected entity, reflecting the
-// active tool. The drag itself (below) now applies move / rotate / scale.
-function GizmoGlyph({ tool }: { tool: ToolMode }) {
+// The interactive transform gizmo, drawn from the origin (= the selection pivot, the
+// wrapper is translated there each frame). Its geometry mirrors the hit zones in
+// gizmo.ts (GIZMO constants) so the handles a user aims at are the handles the tool
+// hit-tests. Screen y is down, so the world +Y handle points up (negative y). Only
+// move/rotate/scale render a gizmo; the select tool shows just the selection outline.
+function GizmoOverlay({ tool }: { tool: ToolMode }) {
+ const L = GIZMO.axisLen;
+ const B = GIZMO.boxSize;
+ const P = GIZMO.planeSize;
if (tool === 'rotate') {
return (
- <svg width="92" height="92" viewBox="0 0 92 92">
- <circle cx="46" cy="46" r="34" fill="none" stroke="var(--run)" strokeWidth="2" />
- <circle cx="46" cy="12" r="4" fill="var(--run)" />
+ <svg className="gizmo-svg" width="0" height="0" overflow="visible">
+ <circle cx="0" cy="0" r={GIZMO.ringRadius} fill="none" stroke="var(--run)" strokeWidth="2" />
+ <circle cx="0" cy="0" r="2.5" fill="var(--star)" />
</svg>
);
}
if (tool === 'scale') {
return (
- <svg width="92" height="92" viewBox="0 0 92 92">
- <line x1="46" y1="46" x2="80" y2="46" stroke="var(--error)" strokeWidth="2.5" />
- <rect x="77" y="42" width="8" height="8" fill="var(--error)" />
- <line x1="46" y1="46" x2="46" y2="12" stroke="var(--run)" strokeWidth="2.5" />
- <rect x="42" y="9" width="8" height="8" fill="var(--run)" />
- <rect x="41" y="41" width="10" height="10" fill="var(--star)" />
- </svg>
- );
- }
- if (tool === 'select') {
- return (
- <svg width="92" height="92" viewBox="0 0 92 92">
- <rect x="16" y="16" width="60" height="60" fill="none" stroke="var(--star)" strokeWidth="1.5" strokeDasharray="4 3" />
- {[[16, 16], [76, 16], [16, 76], [76, 76]].map(([x, y]) => (
- <rect key={`${x}-${y}`} x={x - 3} y={y - 3} width="6" height="6" fill="var(--star)" />
- ))}
+ <svg className="gizmo-svg" width="0" height="0" overflow="visible">
+ <line x1="0" y1="0" x2={L} y2="0" stroke="var(--error)" strokeWidth="2.5" />
+ <rect x={L - B / 2} y={-B / 2} width={B} height={B} fill="var(--error)" />
+ <line x1="0" y1="0" x2="0" y2={-L} stroke="var(--run)" strokeWidth="2.5" />
+ <rect x={-B / 2} y={-L - B / 2} width={B} height={B} fill="var(--run)" />
+ <rect x={-P / 2} y={-P / 2} width={P} height={P} fill="var(--star)" opacity="0.85" />
</svg>
);
}
+ // move (and any other) → axis arrows + a center plane square
return (
- <svg width="92" height="92" viewBox="0 0 92 92">
- <line x1="46" y1="46" x2="82" y2="46" stroke="var(--error)" strokeWidth="2.5" />
- <path d="M82 46 L74 42 L74 50 Z" fill="var(--error)" />
- <line x1="46" y1="46" x2="46" y2="10" stroke="var(--run)" strokeWidth="2.5" />
- <path d="M46 10 L42 18 L50 18 Z" fill="var(--run)" />
- <rect x="41" y="41" width="10" height="10" fill="var(--star)" opacity="0.9" />
+ <svg className="gizmo-svg" width="0" height="0" overflow="visible">
+ <line x1="0" y1="0" x2={L} y2="0" stroke="var(--error)" strokeWidth="2.5" />
+ <path d={`M${L} 0 L${L - 9} -4 L${L - 9} 4 Z`} fill="var(--error)" />
+ <line x1="0" y1="0" x2="0" y2={-L} stroke="var(--run)" strokeWidth="2.5" />
+ <path d={`M0 ${-L} L-4 ${-L + 9} L4 ${-L + 9} Z`} fill="var(--run)" />
+ <rect x={-P / 2} y={-P / 2} width={P} height={P} fill="var(--star)" opacity="0.85" />
</svg>
);
}
@@ -77,15 +76,18 @@ const TOOLS: { mode: ToolMode; icon: LucideIcon; label: string; key: string }[]
{ mode: 'scale', icon: Scale3d, label: 'Scale', key: 'R' },
];
-// World units offered by the viewport Snap dropdown (move snap step).
+// Increments offered by the viewport Snap dropdown: move (world units), rotate
+// (degrees), scale (factor). All gated by the single `snapping` master toggle.
const SNAP_STEPS = [16, 32, 64];
+const SNAP_ANGLES = [5, 15, 45, 90];
+const SNAP_SCALES = [0.1, 0.25, 0.5];
// One-line hint shown under the coord readout, reflecting the active tool.
const TOOL_HINT: Record<ToolMode, string> = {
- select: 'Click to select · drag empty to box-select',
- move: 'Drag the entity to move · Shift to multi-select',
- rotate: 'Drag around the entity to rotate',
- scale: 'Drag out from the entity to scale',
+ select: 'Click to select · Shift adds · drag empty to box-select',
+ move: 'Drag a gizmo axis or the body · Alt-drag duplicates · arrows nudge',
+ rotate: 'Drag the ring to rotate the selection',
+ scale: 'Drag a handle for per-axis scale · center for uniform',
};
function OvTool({
@@ -192,12 +194,21 @@ export function Viewport() {
const showGizmos = useEditorStore((s) => s.showGizmos);
const snapping = useEditorStore((s) => s.snapping);
const snapStep = useEditorStore((s) => s.snapStep);
+ const snapAngle = useEditorStore((s) => s.snapAngle);
+ const snapScale = useEditorStore((s) => s.snapScale);
const selCount = useSelection((s) => s.selectedIds.size);
+ // The set of selected source ids — drives one selection outline per entity. The
+ // Set is replaced (not mutated) on every selection change, so this re-renders.
+ const selectedIds = useSelection((s) => s.selectedIds);
+ const primaryId = useSelection((s) => s.selectedId);
+ const selList = useMemo(() => [...selectedIds], [selectedIds]);
const stageRef = useRef<HTMLDivElement>(null);
const playHostRef = useRef<HTMLDivElement>(null);
const gizmoRef = useRef<HTMLDivElement>(null);
- const selectionRef = useRef<HTMLDivElement>(null);
+ // One outline div per selected entity, keyed by source id and positioned by the rAF.
+ const selRefs = useRef(new Map<number, HTMLDivElement | null>());
+ const marqueeRef = useRef<HTMLDivElement>(null);
const tileSelRef = useRef<HTMLDivElement>(null);
const tilePreviewRef = useRef<HTMLDivElement>(null);
const hoverTileRef = useRef<{ x: number; y: number } | null>(null);
@@ -274,44 +285,73 @@ export function Viewport() {
return () => stage.removeEventListener('wheel', onWheel);
}, []);
- // Glue the gizmo + selection outline to the selected entity, every frame.
+ // Glue the gizmo (at the selection pivot), the per-entity outlines, and the
+ // marquee box to the World, every frame.
useEffect(() => {
let raf = 0;
const tick = () => {
raf = requestAnimationFrame(tick);
const g = gizmoRef.current;
- const sel = selectionRef.current;
- if (!g || !sel) return;
- // Selection is a source id; the gizmo/outline reads World geometry, so
- // resolve it to the runtime entity (absent if not currently spawned).
- const sid = useSelection.getState().selectedId;
- const rt = sid != null ? SceneModel.runtimeFor(sid) : undefined;
+ if (!g) return;
const ready = EngineHost.getSnapshot().status === 'ready';
const showG = useEditorStore.getState().showGizmos;
+ const toolMode = useEditorStore.getState().tool;
+
+ // Per-entity selection outlines (one div per selected source id).
+ let sumX = 0;
+ let sumY = 0;
+ let nPos = 0;
+ for (const [sid, el] of selRefs.current) {
+ if (!el) continue;
+ const rt = ready ? SceneModel.runtimeFor(sid) : undefined;
+ const rect = rt != null ? ViewportController.getEntityScreenRect(rt) : null;
+ if (rect) {
+ el.style.transform = `translate(${rect.x}px, ${rect.y}px)`;
+ 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';
+ }
+ }
- const pos = ready && rt != null ? ViewportController.getEntityXY(rt) : null;
- const sc = pos ? ViewportController.worldToClient(pos.x, pos.y) : null;
- if (sc && showG) {
- g.style.transform = `translate(${sc.x}px, ${sc.y}px)`;
+ // 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;
+ if (pivot && showG && toolMode !== 'select') {
+ g.style.transform = `translate(${pivot.x}px, ${pivot.y}px)`;
g.style.opacity = '1';
} else {
g.style.opacity = '0';
}
- const rect = ready && rt != null ? ViewportController.getEntityScreenRect(rt) : null;
- if (rect) {
- sel.style.transform = `translate(${rect.x}px, ${rect.y}px)`;
- sel.style.width = `${rect.w}px`;
- sel.style.height = `${rect.h}px`;
- sel.style.opacity = '1';
- } else {
- sel.style.opacity = '0';
+ // Marquee box (set by the transform tool's box-select drag).
+ const mq = marqueeRef.current;
+ if (mq) {
+ const r = Marquee.get();
+ if (r) {
+ mq.style.transform = `translate(${r.x}px, ${r.y}px)`;
+ mq.style.width = `${r.w}px`;
+ mq.style.height = `${r.h}px`;
+ mq.style.opacity = '1';
+ } else {
+ mq.style.opacity = '0';
+ }
}
// Tile-select marquee: an axis-aligned rect over the selected TilemapLayer's
// chosen tile range, in screen space (its world corners projected each frame).
+ // Tilemap paint targets the primary entity, so resolve just that one here.
const ts = tileSelRef.current;
if (ts) {
+ const sid = useSelection.getState().selectedId;
+ const rt = ready && sid != null ? SceneModel.runtimeFor(sid) : undefined;
const paint = useTilemapPaint.getState();
const tsel = paint.tool === 'select' ? paint.selection : null;
const layer = ready && sid != null
@@ -565,8 +605,8 @@ export function Viewport() {
align="r"
title="Grid Snap"
>
- <div className="dd-lbl">Snap (units)</div>
<DdRadio on={!snapping} label="Off" onClick={() => useEditorStore.setState({ snapping: false })} />
+ <div className="dd-lbl">Move (units)</div>
{SNAP_STEPS.map((s) => (
<DdRadio
key={s}
@@ -575,6 +615,24 @@ export function Viewport() {
onClick={() => useEditorStore.getState().setSnapStep(s)}
/>
))}
+ <div className="dd-lbl">Rotate (°)</div>
+ {SNAP_ANGLES.map((a) => (
+ <DdRadio
+ key={a}
+ on={snapping && snapAngle === a}
+ label={String(a)}
+ onClick={() => useEditorStore.setState({ snapping: true, snapAngle: a })}
+ />
+ ))}
+ <div className="dd-lbl">Scale (×)</div>
+ {SNAP_SCALES.map((s) => (
+ <DdRadio
+ key={s}
+ on={snapping && snapScale === s}
+ label={String(s)}
+ onClick={() => useEditorStore.setState({ snapping: true, snapScale: s })}
+ />
+ ))}
</OvDropdown>
</div>
</div>
@@ -651,12 +709,24 @@ export function Viewport() {
</div>
)}
- <div ref={selectionRef} className="viewport__selection" aria-hidden="true" />
+ {/* One outline per selected entity (rAF-positioned); primary gets the accent. */}
+ {selList.map((id) => (
+ <div
+ key={id}
+ ref={(el) => {
+ if (el) selRefs.current.set(id, el);
+ else selRefs.current.delete(id);
+ }}
+ className={`viewport__selection${id === primaryId ? ' primary' : ''}`}
+ aria-hidden="true"
+ />
+ ))}
+ <div ref={marqueeRef} className="viewport__marquee" aria-hidden="true" />
<div ref={tileSelRef} className="viewport__tilesel" aria-hidden="true" />
<div ref={tilePreviewRef} className="viewport__tilepreview" aria-hidden="true" />
<div ref={gizmoRef} className="viewport__gizmo" aria-hidden="true">
- <GizmoGlyph tool={tool} />
+ <GizmoOverlay tool={tool} />
</div>
{engine.status !== 'ready' && (
diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.ts
index cc0ec573c..eb18826a3 100644
--- a/desktop/src/store/editorStore.ts
+++ b/desktop/src/store/editorStore.ts
@@ -39,10 +39,17 @@ interface EditorState {
// viewport snap dropdown picks from a fixed set (16 / 32 / 64); "off" flips
// `snapping` rather than changing the step, so the last step survives a re-enable.
snapStep: number;
+ // Rotate / scale snap increments, gated by the same `snapping` master toggle as
+ // grid move-snap (degrees, and a uniform scale step). Replaces the old hardcoded
+ // 15° / 0.1 constants so they're user-tunable from the viewport snap menu.
+ snapAngle: number;
+ snapScale: number;
toggleGrid: () => void;
toggleGizmos: () => void;
toggleSnapping: () => void;
setSnapStep: (step: number) => void;
+ setSnapAngle: (deg: number) => void;
+ setSnapScale: (step: number) => void;
// Content Drawer — a quick-access overlay: the Content Browser slides up over
// the workspace (Ctrl+Space), dismissing on outside click / Esc. It sits ON
@@ -90,10 +97,14 @@ export const useEditorStore = create<EditorState>((set) => ({
showGizmos: true,
snapping: false,
snapStep: 32,
+ snapAngle: 15,
+ snapScale: 0.1,
toggleGrid: () => set((s) => ({ showGrid: !s.showGrid })),
toggleGizmos: () => set((s) => ({ showGizmos: !s.showGizmos })),
toggleSnapping: () => set((s) => ({ snapping: !s.snapping })),
setSnapStep: (snapStep) => set({ snapStep, snapping: true }),
+ setSnapAngle: (snapAngle) => set({ snapAngle }),
+ setSnapScale: (snapScale) => set({ snapScale }),
contentDrawer: false,
toggleContentDrawer: () => set((s) => ({ contentDrawer: !s.contentDrawer })),
diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.css
index 5b71b14eb..128990669 100644
--- a/desktop/src/theme/app.css
+++ b/desktop/src/theme/app.css
@@ -561,9 +561,11 @@
will-change: transform, opacity;
transition: opacity 0.1s ease;
}
+/* The interactive gizmo draws from its origin (= the pivot the wrapper is
+ translated to), so no centering transform — just the contrast shadow. */
.viewport__gizmo svg {
display: block;
- transform: translate(-50%, -50%);
+ overflow: visible;
filter: drop-shadow(0 0 6px rgba(0, 0, 0, 0.55));
}
@@ -583,6 +585,22 @@
inset 0 0 0 1px rgba(14, 15, 18, 0.4);
will-change: transform, width, height, opacity;
}
+/* The primary (active) entity in a multi-selection reads slightly stronger. */
+.viewport__selection.primary {
+ border-width: 1.5px;
+}
+/* Box-select marquee (rAF-driven by the transform tool's empty-space drag). */
+.viewport__marquee {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 3;
+ opacity: 0;
+ pointer-events: none;
+ border: 1px dashed var(--sel);
+ background: var(--sel-soft);
+ will-change: transform, width, height, opacity;
+}
.viewport__tilesel {
position: absolute;
top: 0;
diff --git a/desktop/src/tools/gizmo.ts b/desktop/src/tools/gizmo.ts
new file mode 100644
index 000000000..bf26f11ba
--- /dev/null
+++ b/desktop/src/tools/gizmo.ts
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file gizmo.ts
+ * @brief Pure geometry for the interactive transform gizmo — handle hit-testing,
+ * axis constraint, group pivot. No engine / DOM coupling, so it unit-tests
+ * in isolation; transformTools.ts is the imperative shell that drives it.
+ *
+ * Coordinate model: the gizmo lives at a screen-space (CSS px) pivot. Its axes map
+ * to world axes through the editor's ortho 2D camera, where world +X = screen +X
+ * and world +Y = screen −Y (screen y is down). So hit-testing is done in client
+ * space against fixed screen directions, while the actual transform (in the tool)
+ * applies the world-space delta the cursor traveled, constrained to the axis.
+ */
+
+export type GizmoMode = 'move' | 'rotate' | 'scale';
+/** Which world axes a handle drag affects. */
+export type GizmoAxis = 'x' | 'y' | 'xy';
+
+export interface GizmoHandle {
+ id: string;
+ mode: GizmoMode;
+ axis: GizmoAxis;
+}
+
+export interface Pt {
+ x: number;
+ y: number;
+}
+
+/** Screen-space layout of the gizmo (CSS px). Rendering (Viewport.tsx) mirrors these. */
+export const GIZMO = {
+ axisLen: 58, // axis arrow length from the pivot
+ planeSize: 20, // side of the center move-plane square (a square ±planeSize/2 around pivot)
+ ringRadius: 42, // rotate ring radius
+ boxSize: 11, // scale end-box side
+ hitTol: 7, // px tolerance for line / ring proximity
+} as const;
+
+// Screen-space unit directions of the world axes (ortho 2D camera): +X right, +Y up.
+const X_DIR: Pt = { x: 1, y: 0 };
+const Y_DIR: Pt = { x: 0, y: -1 };
+
+/** Distance from point `p` to the segment a→b (used for axis-arrow hit zones). */
+export function distToSegment(p: Pt, a: Pt, b: Pt): number {
+ const abx = b.x - a.x;
+ const aby = b.y - a.y;
+ const len2 = abx * abx + aby * aby;
+ if (len2 === 0) return Math.hypot(p.x - a.x, p.y - a.y);
+ let t = ((p.x - a.x) * abx + (p.y - a.y) * aby) / len2;
+ t = Math.max(0, Math.min(1, t));
+ return Math.hypot(p.x - (a.x + t * abx), p.y - (a.y + t * aby));
+}
+
+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 });
+
+/**
+ * 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.
+ */
+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);
+
+ if (mode === 'move') {
+ if (within(cursor, pivot, GIZMO.planeSize / 2)) return { id: 'move.xy', mode, axis: 'xy' };
+ if (distToSegment(cursor, pivot, xEnd) <= GIZMO.hitTol) return { id: 'move.x', mode, axis: 'x' };
+ if (distToSegment(cursor, pivot, yEnd) <= GIZMO.hitTol) return { id: 'move.y', mode, axis: 'y' };
+ return null;
+ }
+ if (mode === 'scale') {
+ if (within(cursor, pivot, GIZMO.planeSize / 2)) return { id: 'scale.xy', mode, axis: 'xy' };
+ if (within(cursor, xEnd, GIZMO.boxSize) || distToSegment(cursor, pivot, xEnd) <= GIZMO.hitTol)
+ return { id: 'scale.x', mode, axis: 'x' };
+ if (within(cursor, yEnd, GIZMO.boxSize) || distToSegment(cursor, pivot, yEnd) <= GIZMO.hitTol)
+ 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' };
+ return null;
+}
+
+/** Constrain a world-space delta to a handle's axis. */
+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];
+}
+
+/** 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 };
+ let sx = 0;
+ let sy = 0;
+ for (const p of points) {
+ sx += p.x;
+ sy += p.y;
+ }
+ return { x: sx / points.length, y: sy / points.length };
+}
+
+/** Rotate a point `p` around pivot `c` by `angle` radians (group rotate). */
+export function rotateAround(p: Pt, c: Pt, angle: number): Pt {
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ const dx = p.x - c.x;
+ const dy = p.y - c.y;
+ return { x: c.x + dx * cos - dy * sin, y: c.y + dx * sin + dy * cos };
+}
+
+/** Scale a point `p` away from pivot `c` by per-axis factors (group scale). */
+export function scaleAround(p: Pt, c: Pt, fx: number, fy: number): Pt {
+ return { x: c.x + (p.x - c.x) * fx, y: c.y + (p.y - c.y) * fy };
+}
diff --git a/desktop/src/tools/marquee.ts b/desktop/src/tools/marquee.ts
new file mode 100644
index 000000000..a48df591e
--- /dev/null
+++ b/desktop/src/tools/marquee.ts
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file marquee.ts
+ * @brief The in-progress box-select rect (canvas-relative CSS px), shared from the
+ * select/transform tool to the Viewport overlay. A plain module ref read by
+ * the overlay's per-frame rAF (like the tile-brush hover) — no React churn
+ * during a drag.
+ */
+import type { ClientRect } from '@/engine/viewportMath';
+
+let rect: ClientRect | null = null;
+
+export const Marquee = {
+ set(r: ClientRect | null): void {
+ rect = r;
+ },
+ get(): ClientRect | null {
+ return rect;
+ },
+};
diff --git a/desktop/src/tools/transformTools.ts b/desktop/src/tools/transformTools.ts
index 4e07aec0f..c8725c195 100644
--- a/desktop/src/tools/transformTools.ts
+++ b/desktop/src/tools/transformTools.ts
@@ -2,178 +2,335 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file transformTools.ts
- * @brief The select / move / rotate / scale viewport tools. Each picks + selects
- * the entity under the cursor, then drives a transform drag as one undo
- * transaction (T5). Select and Move share the move drag (clicking selects,
- * dragging moves) — Select is just the same stroke with the box gizmo.
+ * @brief The select / move / rotate / scale viewport tools — the imperative shell
+ * over the pure gizmo geometry (gizmo.ts). Each pointer-down resolves to one
+ * of three strokes, in priority order:
+ * 1. a gizmo-handle drag → axis-constrained transform of the whole selection;
+ * 2. an entity pick → select (Shift toggles) + a free transform of the group
+ * (Alt duplicates first);
+ * 3. empty space → a marquee box-select.
+ * A stroke is one undo transaction; group rotate/scale orbit the selection's
+ * shared pivot, so multi-select transforms behave like UE's.
*/
import { ViewportController } from '@/engine/ViewportController';
import { SceneCommands, type EditorTransaction } from '@/engine/SceneCommands';
import { SceneQuery } from '@/engine/SceneQuery';
import { SceneModel } from '@/engine/SceneModel';
import { EngineHost } from '@/engine/EngineHost';
+import { snapTo } from '@/engine/viewportMath';
import { useSelection } from '@/store/selectionStore';
import { useEditorStore } from '@/store/editorStore';
+import type { ToolMode, EntityId } from '@/types';
+import {
+ type GizmoAxis,
+ type GizmoMode,
+ type Pt,
+ hitTestGizmo,
+ constrainWorldDelta,
+ groupPivot,
+ rotateAround,
+ scaleAround,
+} from './gizmo';
+import { Marquee } from './marquee';
import type { EditorTool, PointerInput } from './EditorTool';
-// Snap increments while Snapping is on. Move uses the user-chosen `snapStep`
-// (viewport Snap dropdown); rotate/scale are fixed until a Preferences panel.
-const SNAP_ROTATE = 15; // degrees
-const SNAP_SCALE = 0.1; // uniform scale step
-const snap = (v: number, step: number) => Math.round(v / step) * step;
+type Kind = 'move' | 'rotate' | 'scale';
-// Entity's screen-center in viewport (client) coordinates.
-function entityClientCenter(rtId: number): { cx: number; cy: number } | null {
+/** 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 };
+}
+
+interface Drag {
+ tx: EditorTransaction;
+ kind: Kind;
+ axis: GizmoAxis;
+ pivotWorld: Pt;
+ pivotClient: Pt; // canvas-relative
+ downWorld: Pt;
+ startAngle: number; // rotate: cursor screen-angle around the pivot
+ startDist: number; // scale: cursor screen-distance from the pivot
+ targets: Target[];
+}
+
+interface MarqueeState {
+ downX: number;
+ downY: number;
+ additive: boolean;
+ base: Set<EntityId>;
+}
+
+// Canvas top-left in window-client coords; the overlay places gizmos / outlines in
+// this canvas-relative space, so hit-testing must convert the pointer into it too.
+function canvasOrigin(): { left: number; top: number } | null {
+ const c = EngineHost.canvas;
+ if (!c) return null;
+ const r = c.getBoundingClientRect();
+ return { left: r.left, top: r.top };
+}
+
+/** Read an entity's current start transform (world position + inspector rotation/scale). */
+function readTarget(sourceId: EntityId): Target | null {
+ const rtId = SceneModel.runtimeFor(sourceId);
+ if (rtId == null) return null;
const pos = ViewportController.getEntityXY(rtId);
- const canvas = EngineHost.canvas;
- if (!pos || !canvas) return null;
- const cv = ViewportController.worldToClient(pos.x, pos.y);
- if (!cv) return null;
- const rect = canvas.getBoundingClientRect();
- return { cx: rect.left + cv.x, cy: rect.top + cv.y };
+ if (!pos) return null;
+ const rotDeg = (SceneQuery.getFieldValue(sourceId, 'Transform', 'rotation') as number) ?? 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 } };
}
-/** Pick the entity under the cursor and select it; returns {sourceId, rtId} or null. */
-function pickSelect(p: PointerInput): { sourceId: number; rtId: number } | null {
- const rtId = ViewportController.pickEntity(p.clientX, p.clientY);
- const sourceId = rtId != null ? SceneModel.sourceFor(rtId) ?? null : null;
- useSelection.getState().select(sourceId);
- if (rtId == null || sourceId == null) return null;
- return { sourceId, rtId };
+function captureTargets(ids: readonly EntityId[]): Target[] {
+ return ids.map(readTarget).filter((t): t is Target => t !== null);
}
-/** Select + Move: click to select, drag to move (the editor's default tool). */
-function makeMoveTool(id: string): EditorTool {
- let stroke: { id: number; dx: number; dy: number; tx: EditorTransaction } | null = null;
- return {
- id,
- onPointerDown(p, ctx) {
- const hit = pickSelect(p);
- if (!hit) return false;
- const wp = ViewportController.canvasToWorld(p.clientX, p.clientY);
- const ep = ViewportController.getEntityXY(hit.rtId);
- if (!wp || !ep) return false;
- stroke = { id: hit.sourceId, dx: ep.x - wp.x, dy: ep.y - wp.y, tx: SceneCommands.transaction('Move') };
- ctx.capture(p.pointerId);
- return true;
- },
- onPointerMove(p) {
- if (!stroke) return;
- const wp = ViewportController.canvasToWorld(p.clientX, p.clientY);
- if (!wp) return;
- let x = wp.x + stroke.dx;
- let y = wp.y + stroke.dy;
- if (useEditorStore.getState().snapping) {
- const step = useEditorStore.getState().snapStep;
- x = snap(x, step);
- y = snap(y, step);
- }
- SceneCommands.setEntityXY(stroke.id, x, y);
- },
- onPointerUp(p, ctx) {
- if (!stroke) return;
- ctx.release(p.pointerId);
- stroke.tx.commit();
- stroke = null;
- },
- cancel() {
- if (!stroke) return;
- stroke.tx.abort();
- stroke = null;
- },
- };
+/** Selection pivot = centroid of the live world positions of `ids`. */
+function pivotOf(ids: readonly EntityId[]): Pt | null {
+ const pts: Pt[] = [];
+ for (const sid of ids) {
+ const rtId = SceneModel.runtimeFor(sid);
+ if (rtId == null) continue;
+ const pos = ViewportController.getEntityXY(rtId);
+ if (pos) pts.push(pos);
+ }
+ return pts.length ? groupPivot(pts) : null;
}
-function makeRotateTool(): EditorTool {
- let stroke: { id: number; cx: number; cy: number; startAngle: number; startRot: number; tx: EditorTransaction } | null = null;
+/**
+ * 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
+ * on the first move). Selects the new copies. Each clone is its own undo step,
+ * preceding the move gesture.
+ */
+function altDuplicateTargets(ids: readonly EntityId[]): { targets: Target[]; pivot: Pt | null } {
+ const targets: Target[] = [];
+ const pts: Pt[] = [];
+ for (const sid of ids) {
+ const t = readTarget(sid);
+ if (!t) continue;
+ const copy = SceneCommands.duplicateEntity(sid);
+ if (copy == null) continue;
+ targets.push({ sourceId: copy, start: t.start });
+ pts.push({ x: t.start.x, y: t.start.y });
+ }
+ if (targets.length) {
+ const ids2 = targets.map((t) => t.sourceId);
+ useSelection.getState().selectMany(ids2, ids2[ids2.length - 1]);
+ }
+ return { targets, pivot: pts.length ? groupPivot(pts) : null };
+}
+
+function beginDrag(
+ kind: Kind,
+ axis: GizmoAxis,
+ targets: Target[],
+ pivotWorld: Pt,
+ pivotClient: Pt,
+ p: PointerInput,
+ cur: Pt,
+): Drag {
+ const label = kind === 'rotate' ? 'Rotate' : kind === 'scale' ? 'Scale' : 'Move';
+ const downWorld = ViewportController.canvasToWorld(p.clientX, p.clientY) ?? { x: 0, y: 0 };
return {
- id: 'transform.rotate',
- onPointerDown(p, ctx) {
- const hit = pickSelect(p);
- if (!hit) return false;
- const c = entityClientCenter(hit.rtId);
- if (!c) return false;
- const startRot = (SceneQuery.getFieldValue(hit.sourceId, 'Transform', 'rotation') as number) ?? 0;
- stroke = {
- id: hit.sourceId, cx: c.cx, cy: c.cy,
- startAngle: Math.atan2(p.clientY - c.cy, p.clientX - c.cx), startRot,
- tx: SceneCommands.transaction('Rotate'),
- };
- ctx.capture(p.pointerId);
- return true;
- },
- onPointerMove(p) {
- if (!stroke) return;
- const angle = Math.atan2(p.clientY - stroke.cy, p.clientX - stroke.cx);
- const deltaDeg = ((angle - stroke.startAngle) * 180) / Math.PI;
- // Screen y is down, so a clockwise screen drag is a negative world rotation.
- let rot = stroke.startRot - deltaDeg;
- if (useEditorStore.getState().snapping) rot = snap(rot, SNAP_ROTATE);
- SceneCommands.setField(stroke.id, 'Transform', 'rotation', 'angle', rot);
- },
- onPointerUp(p, ctx) {
- if (!stroke) return;
- ctx.release(p.pointerId);
- stroke.tx.commit();
- stroke = null;
- },
- cancel() {
- if (!stroke) return;
- stroke.tx.abort();
- stroke = null;
- },
+ tx: SceneCommands.transaction(label),
+ kind,
+ axis,
+ pivotWorld,
+ pivotClient,
+ 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)),
+ targets,
};
}
-function makeScaleTool(): EditorTool {
- let stroke: { id: number; cx: number; cy: number; startDist: number; sx: number; sy: number; sz: number; tx: EditorTransaction } | null = null;
+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);
+ const ed = useEditorStore.getState();
+ if (ed.snapping && d.targets.length) {
+ // Snap the primary's resulting position to the grid, apply that delta to all,
+ // so the group keeps its relative layout (UE-style group grid snap).
+ const p0 = d.targets[0].start;
+ if (d.axis !== 'y') dx = snapTo(p0.x + dx, ed.snapStep) - p0.x;
+ if (d.axis !== 'x') dy = snapTo(p0.y + dy, ed.snapStep) - p0.y;
+ }
+ for (const t of d.targets) SceneCommands.setEntityXY(t.sourceId, t.start.x + dx, t.start.y + dy);
+}
+
+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 ed = useEditorStore.getState();
+ if (ed.snapping) worldDeltaDeg = snapTo(worldDeltaDeg, ed.snapAngle);
+ const rad = (worldDeltaDeg * Math.PI) / 180;
+ 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);
+ }
+}
+
+function applyScale(d: Drag, cur: Pt): void {
+ const f = Math.hypot(cur.x - d.pivotClient.x, cur.y - d.pivotClient.y) / d.startDist;
+ const ed = useEditorStore.getState();
+ let fx = d.axis === 'y' ? 1 : f;
+ let fy = d.axis === 'x' ? 1 : f;
+ if (ed.snapping) {
+ if (d.axis !== 'y') fx = Math.max(0.01, snapTo(fx, ed.snapScale));
+ if (d.axis !== 'x') fy = Math.max(0.01, snapTo(fy, ed.snapScale));
+ }
+ for (const t of d.targets) {
+ const np = scaleAround({ x: t.start.x, y: t.start.y }, d.pivotWorld, fx, fy);
+ SceneCommands.setEntityXY(t.sourceId, np.x, np.y);
+ SceneCommands.setField(t.sourceId, 'Transform', 'scale', 'vec3', [t.start.sx * fx, t.start.sy * fy, t.start.sz]);
+ }
+}
+
+function makeTransformTool(mode: ToolMode): EditorTool {
+ let drag: Drag | null = null;
+ let marquee: MarqueeState | null = null;
+ // The select tool shares the move drag (click selects, drag moves) but shows no
+ // transform gizmo; move/rotate/scale do. kind === the tool's transform.
+ const kind: Kind = mode === 'rotate' ? 'rotate' : mode === 'scale' ? 'scale' : 'move';
+
return {
- id: 'transform.scale',
+ id: `transform.${mode}`,
+
onPointerDown(p, ctx) {
- const hit = pickSelect(p);
- if (!hit) return false;
- const c = entityClientCenter(hit.rtId);
- if (!c) return false;
- const s = (SceneQuery.getFieldValue(hit.sourceId, 'Transform', 'scale') as number[]) ?? [1, 1, 1];
- stroke = {
- id: hit.sourceId, cx: c.cx, cy: c.cy,
- startDist: Math.max(1, Math.hypot(p.clientX - c.cx, p.clientY - c.cy)),
- sx: s[0] ?? 1, sy: s[1] ?? 1, sz: s[2] ?? 1,
- tx: SceneCommands.transaction('Scale'),
- };
+ const origin = canvasOrigin();
+ if (!origin) return false;
+ const cur: Pt = { x: p.clientX - origin.left, y: p.clientY - origin.top };
+ const sel = useSelection.getState();
+ const ed = useEditorStore.getState();
+
+ // 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 pc = pivotWorld ? ViewportController.worldToClient(pivotWorld.x, pivotWorld.y) : null;
+ if (pivotWorld && pc) {
+ const handle = hitTestGizmo(mode as GizmoMode, pc, cur);
+ if (handle) {
+ drag = beginDrag(kind, handle.axis, captureTargets(ids), pivotWorld, pc, p, cur);
+ ctx.capture(p.pointerId);
+ return true;
+ }
+ }
+ }
+
+ // 2) Pick an entity → select + free transform (Shift toggles, Alt duplicates).
+ const rtId = ViewportController.pickEntity(p.clientX, p.clientY);
+ const hitSource = rtId != null ? SceneModel.sourceFor(rtId) ?? null : null;
+ if (hitSource != null) {
+ if (p.shift) {
+ sel.toggleSelect(hitSource); // selection edit only; no drag
+ return false;
+ }
+ const inSel = sel.selectedIds.has(hitSource);
+ if (!inSel) sel.select(hitSource);
+ const ids = inSel ? [...sel.selectedIds] : [hitSource];
+
+ let targets: Target[];
+ let pivotWorld: Pt | null;
+ if (p.alt) {
+ const dup = altDuplicateTargets(ids);
+ targets = dup.targets;
+ pivotWorld = dup.pivot;
+ } else {
+ targets = captureTargets(ids);
+ pivotWorld = pivotOf(ids);
+ }
+ if (!targets.length || !pivotWorld) return false;
+ const pc = ViewportController.worldToClient(pivotWorld.x, pivotWorld.y) ?? cur;
+ drag = beginDrag(kind, 'xy', targets, pivotWorld, pc, p, cur);
+ ctx.capture(p.pointerId);
+ return true;
+ }
+
+ // 3) Empty space → marquee box-select (Shift = additive).
+ marquee = { downX: p.clientX, downY: p.clientY, additive: p.shift, base: new Set(sel.selectedIds) };
ctx.capture(p.pointerId);
return true;
},
+
onPointerMove(p) {
- if (!stroke) return;
- const dist = Math.hypot(p.clientX - stroke.cx, p.clientY - stroke.cy);
- const f = dist / stroke.startDist;
- let sx = stroke.sx * f;
- let sy = stroke.sy * f;
- if (useEditorStore.getState().snapping) {
- sx = snap(sx, SNAP_SCALE);
- sy = snap(sy, SNAP_SCALE);
+ if (drag) {
+ const origin = canvasOrigin();
+ const cur: Pt = origin
+ ? { x: p.clientX - origin.left, y: p.clientY - origin.top }
+ : { x: p.clientX, y: p.clientY };
+ if (drag.kind === 'move') {
+ const w = ViewportController.canvasToWorld(p.clientX, p.clientY);
+ if (w) applyMove(drag, w);
+ } else if (drag.kind === 'rotate') {
+ applyRotate(drag, cur);
+ } else {
+ applyScale(drag, cur);
+ }
+ return;
+ }
+ if (marquee) {
+ const origin = canvasOrigin();
+ const x0 = Math.min(marquee.downX, p.clientX) - (origin?.left ?? 0);
+ const y0 = Math.min(marquee.downY, p.clientY) - (origin?.top ?? 0);
+ const w = Math.abs(p.clientX - marquee.downX);
+ const h = Math.abs(p.clientY - marquee.downY);
+ Marquee.set({ x: x0, y: y0, w, h });
}
- SceneCommands.setField(stroke.id, 'Transform', 'scale', 'vec3', [sx, sy, stroke.sz]);
},
+
onPointerUp(p, ctx) {
- if (!stroke) return;
ctx.release(p.pointerId);
- stroke.tx.commit();
- stroke = null;
+ if (drag) {
+ drag.tx.commit();
+ drag = null;
+ return;
+ }
+ if (marquee) {
+ const moved = Math.abs(p.clientX - marquee.downX) > 3 || Math.abs(p.clientY - marquee.downY) > 3;
+ const origin = canvasOrigin();
+ Marquee.set(null);
+ const m = marquee;
+ marquee = null;
+ if (moved) {
+ const rect = {
+ x: Math.min(m.downX, p.clientX) - (origin?.left ?? 0),
+ y: Math.min(m.downY, p.clientY) - (origin?.top ?? 0),
+ w: Math.abs(p.clientX - m.downX),
+ h: Math.abs(p.clientY - m.downY),
+ };
+ const hits = ViewportController.pickInRect(rect)
+ .map((rt) => SceneModel.sourceFor(rt))
+ .filter((s): s is EntityId => s != null);
+ const set = m.additive ? new Set([...m.base, ...hits]) : new Set(hits);
+ const arr = [...set];
+ if (arr.length) useSelection.getState().selectMany(arr, arr[arr.length - 1]);
+ else if (!m.additive) useSelection.getState().select(null);
+ } else if (!m.additive) {
+ useSelection.getState().select(null); // a bare click on empty space clears
+ }
+ }
},
+
cancel() {
- if (!stroke) return;
- stroke.tx.abort();
- stroke = null;
+ if (drag) {
+ drag.tx.abort();
+ drag = null;
+ }
+ Marquee.set(null);
+ marquee = null;
},
};
}
/** Transform tools keyed by editor ToolMode (select/move/rotate/scale). */
export const TRANSFORM_TOOLS: Record<string, EditorTool> = {
- select: makeMoveTool('transform.select'),
- move: makeMoveTool('transform.move'),
- rotate: makeRotateTool(),
- scale: makeScaleTool(),
+ select: makeTransformTool('select'),
+ move: makeTransformTool('move'),
+ rotate: makeTransformTool('rotate'),
+ scale: makeTransformTool('scale'),
};
diff --git a/desktop/tests/gizmo.test.ts b/desktop/tests/gizmo.test.ts
new file mode 100644
index 000000000..2daf936db
--- /dev/null
+++ b/desktop/tests/gizmo.test.ts
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Pure gizmo geometry — handle hit-testing per tool, axis constraint, group
+ * pivot/rotate/scale. The unit-testable core of the interactive gizmo.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ GIZMO,
+ hitTestGizmo,
+ constrainWorldDelta,
+ groupPivot,
+ rotateAround,
+ scaleAround,
+ distToSegment,
+} from '@/tools/gizmo';
+
+const pivot = { x: 100, y: 100 };
+
+describe('hitTestGizmo — move', () => {
+ it('center hits the XY plane', () => {
+ expect(hitTestGizmo('move', pivot, pivot)?.id).toBe('move.xy');
+ });
+ it('along +X hits the X axis (screen right)', () => {
+ const h = hitTestGizmo('move', pivot, { x: pivot.x + GIZMO.axisLen - 6, y: pivot.y });
+ expect(h?.id).toBe('move.x');
+ expect(h?.axis).toBe('x');
+ });
+ it('along −screenY (up) hits the Y axis', () => {
+ const h = hitTestGizmo('move', pivot, { x: pivot.x, y: pivot.y - GIZMO.axisLen + 6 });
+ expect(h?.id).toBe('move.y');
+ expect(h?.axis).toBe('y');
+ });
+ it('empty space misses', () => {
+ expect(hitTestGizmo('move', pivot, { x: pivot.x + 200, y: pivot.y + 200 })).toBeNull();
+ });
+});
+
+describe('hitTestGizmo — scale', () => {
+ it('center hits the uniform box', () => {
+ expect(hitTestGizmo('scale', pivot, pivot)?.id).toBe('scale.xy');
+ });
+ it('the X end box hits scale.x', () => {
+ expect(hitTestGizmo('scale', pivot, { x: pivot.x + GIZMO.axisLen, y: pivot.y })?.id).toBe('scale.x');
+ });
+});
+
+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]));
+ it('xy keeps both', () => expect(constrainWorldDelta('xy', 5, 9)).toEqual([5, 9]));
+});
+
+describe('groupPivot', () => {
+ it('is the centroid', () => {
+ expect(groupPivot([{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 5, y: 9 }])).toEqual({ x: 5, y: 3 });
+ });
+ it('empty is the origin', () => expect(groupPivot([])).toEqual({ x: 0, y: 0 }));
+});
+
+describe('rotateAround / scaleAround', () => {
+ it('rotates a point 90° about a pivot', () => {
+ const r = rotateAround({ x: 10, y: 0 }, { x: 0, y: 0 }, Math.PI / 2);
+ expect(r.x).toBeCloseTo(0, 6);
+ expect(r.y).toBeCloseTo(10, 6);
+ });
+ it('scales a point away from a pivot per axis', () => {
+ expect(scaleAround({ x: 4, y: 4 }, { x: 0, y: 0 }, 2, 0.5)).toEqual({ x: 8, y: 2 });
+ });
+});
+
+describe('distToSegment', () => {
+ it('is the perpendicular distance to a segment interior', () => {
+ expect(distToSegment({ x: 5, y: 3 }, { x: 0, y: 0 }, { x: 10, y: 0 })).toBeCloseTo(3, 6);
+ });
+ it('clamps to an endpoint past the segment', () => {
+ expect(distToSegment({ x: 13, y: 0 }, { x: 0, y: 0 }, { x: 10, y: 0 })).toBeCloseTo(3, 6);
+ });
+});
diff --git a/desktop/tests/transform-tool.test.ts b/desktop/tests/transform-tool.test.ts
new file mode 100644
index 000000000..197a2d4da
--- /dev/null
+++ b/desktop/tests/transform-tool.test.ts
@@ -0,0 +1,153 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The transform tool's pointer decision tree (the imperative shell over the
+ * pure gizmo math): gizmo-handle drag → axis-constrained group transform;
+ * entity pick → select (Shift toggles) + move; empty → marquee box-select.
+ * Engine access is mocked, so this asserts the wiring, not GL geometry.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { GIZMO } from '@/tools/gizmo';
+
+// Shared mutable test state the module mocks read (hoisted above the vi.mock calls).
+const h = vi.hoisted(() => ({
+ pick: { entity: null as number | null, rect: [] as number[] },
+ pos: new Map<number, { x: number; y: number }>(),
+ calls: { setXY: [] as Array<[number, number, number]>, dup: [] as number[], commit: 0, abort: 0 },
+}));
+
+vi.mock('@/engine/EngineHost', () => ({
+ EngineHost: { canvas: { getBoundingClientRect: () => ({ left: 0, top: 0, width: 800, height: 600 }) } },
+}));
+vi.mock('@/engine/ViewportController', () => ({
+ ViewportController: {
+ canvasToWorld: (x: number, y: number) => ({ x, y }), // identity: world == client px
+ worldToClient: (x: number, y: number) => ({ x, y }),
+ getEntityXY: (rt: number) => h.pos.get(rt) ?? { x: 0, y: 0 },
+ pickEntity: () => h.pick.entity,
+ pickInRect: () => h.pick.rect,
+ },
+}));
+vi.mock('@/engine/SceneCommands', () => ({
+ SceneCommands: {
+ transaction: () => ({ commit: () => { h.calls.commit += 1; }, abort: () => { h.calls.abort += 1; } }),
+ setEntityXY: (sid: number, x: number, y: number) => { h.calls.setXY.push([sid, x, y]); },
+ setField: () => {},
+ duplicateEntity: (sid: number) => { const n = sid + 100; h.calls.dup.push(n); return n; },
+ },
+}));
+vi.mock('@/engine/SceneQuery', () => ({
+ SceneQuery: {
+ getFieldValue: (_s: number, _c: string, k: string) => (k === 'rotation' ? 0 : k === 'scale' ? [1, 1, 1] : undefined),
+ },
+}));
+vi.mock('@/engine/SceneModel', () => ({
+ SceneModel: { runtimeFor: (s: number) => s, sourceFor: (r: number) => r, subscribe: () => {} },
+}));
+
+import { TRANSFORM_TOOLS } from '@/tools/transformTools';
+import { Marquee } from '@/tools/marquee';
+import { useSelection } from '@/store/selectionStore';
+import { useEditorStore } from '@/store/editorStore';
+
+const ctx = { capture: vi.fn(), release: vi.fn() };
+const ev = (x: number, y: number, mod: Partial<{ shift: boolean; alt: boolean }> = {}) => ({
+ clientX: x, clientY: y, pointerId: 1, button: 0, shift: !!mod.shift, alt: !!mod.alt,
+});
+
+beforeEach(() => {
+ h.pick.entity = null;
+ h.pick.rect = [];
+ h.pos.clear();
+ h.calls.setXY = [];
+ h.calls.dup = [];
+ h.calls.commit = 0;
+ h.calls.abort = 0;
+ useSelection.getState().select(null);
+ useEditorStore.setState({ tool: 'move', showGizmos: true, snapping: false });
+ Marquee.set(null);
+});
+
+describe('empty space → marquee box-select', () => {
+ it('drags a box and selects what it covers', () => {
+ h.pick.entity = null;
+ h.pick.rect = [5, 6];
+ const t = TRANSFORM_TOOLS.select;
+ expect(t.onPointerDown(ev(10, 10), ctx)).toBe(true);
+ t.onPointerMove(ev(60, 70), ctx);
+ expect(Marquee.get()).toEqual({ x: 10, y: 10, w: 50, h: 60 });
+ t.onPointerUp(ev(60, 70), ctx);
+ expect([...useSelection.getState().selectedIds].sort()).toEqual([5, 6]);
+ expect(Marquee.get()).toBeNull();
+ });
+
+ it('a bare click on empty space clears the selection', () => {
+ useSelection.getState().select(9);
+ h.pick.entity = null;
+ const t = TRANSFORM_TOOLS.select;
+ t.onPointerDown(ev(10, 10), ctx);
+ t.onPointerUp(ev(10, 10), ctx); // no movement
+ expect(useSelection.getState().selectedId).toBeNull();
+ });
+});
+
+describe('entity pick → select + move', () => {
+ it('selects the clicked entity and moves it by the world delta', () => {
+ h.pick.entity = 7;
+ h.pos.set(7, { x: 100, y: 100 });
+ const t = TRANSFORM_TOOLS.move;
+ expect(t.onPointerDown(ev(100, 100), ctx)).toBe(true);
+ expect(useSelection.getState().selectedId).toBe(7);
+ t.onPointerMove(ev(130, 100), ctx); // +30 in x
+ t.onPointerUp(ev(130, 100), ctx);
+ expect(h.calls.setXY.at(-1)).toEqual([7, 130, 100]);
+ expect(h.calls.commit).toBe(1);
+ });
+
+ it('Shift-click toggles selection without starting a drag', () => {
+ useSelection.getState().select(7);
+ h.pick.entity = 9;
+ const t = TRANSFORM_TOOLS.move;
+ expect(t.onPointerDown(ev(50, 50, { shift: true }), ctx)).toBe(false);
+ expect([...useSelection.getState().selectedIds].sort()).toEqual([7, 9]);
+ });
+
+ it('Alt-drag duplicates and moves the copy', () => {
+ h.pick.entity = 7;
+ h.pos.set(7, { x: 100, y: 100 });
+ const t = TRANSFORM_TOOLS.move;
+ t.onPointerDown(ev(100, 100, { alt: true }), ctx);
+ expect(h.calls.dup).toEqual([107]); // copy id = original + 100 (mock)
+ expect(useSelection.getState().selectedId).toBe(107);
+ t.onPointerMove(ev(140, 100), ctx);
+ t.onPointerUp(ev(140, 100), ctx);
+ expect(h.calls.setXY.at(-1)).toEqual([107, 140, 100]); // copy tracks the cursor from the original's start
+ });
+});
+
+describe('gizmo handle → axis-constrained group transform', () => {
+ it('the X handle moves only in X', () => {
+ useSelection.getState().select(7);
+ h.pos.set(7, { x: 200, y: 200 });
+ const t = TRANSFORM_TOOLS.move;
+ // Pivot at (200,200); the X handle sits one axis-length to the right.
+ const downX = 200 + GIZMO.axisLen - 4;
+ expect(t.onPointerDown(ev(downX, 200), ctx)).toBe(true);
+ t.onPointerMove(ev(downX + 40, 240), ctx); // drag +40x, +40y
+ t.onPointerUp(ev(downX + 40, 240), ctx);
+ // y is constrained out: entity moves +40 in x, 0 in y.
+ expect(h.calls.setXY.at(-1)).toEqual([7, 240, 200]);
+ // Selection unchanged — a gizmo drag never re-picks.
+ expect(useSelection.getState().selectedId).toBe(7);
+ });
+
+ it('the center plane moves freely in both axes', () => {
+ useSelection.getState().select(7);
+ h.pos.set(7, { x: 200, y: 200 });
+ const t = TRANSFORM_TOOLS.move;
+ expect(t.onPointerDown(ev(200, 200), ctx)).toBe(true); // cursor on the pivot = plane handle
+ t.onPointerMove(ev(225, 215), ctx);
+ t.onPointerUp(ev(225, 215), ctx);
+ expect(h.calls.setXY.at(-1)).toEqual([7, 225, 215]);
+ });
+});
diff --git a/desktop/tests/viewport-math.test.ts b/desktop/tests/viewport-math.test.ts
new file mode 100644
index 000000000..031dd6404
--- /dev/null
+++ b/desktop/tests/viewport-math.test.ts
@@ -0,0 +1,97 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Pure viewport geometry — OBB hit-testing (rotation-aware), rect overlap,
+ * quat→angle, and snapping. These back picking / marquee / gizmo math, so
+ * they're the unit-testable core of the viewport interaction layer.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ type OBB,
+ quatAngleZ,
+ obbCorners,
+ pointInOBB,
+ rectsIntersect,
+ screenAABB,
+ snapTo,
+ clamp,
+} from '@/engine/viewportMath';
+
+const box = (cx: number, cy: number, hw: number, hh: number, rot = 0): OBB => ({ cx, cy, hw, hh, rot });
+
+describe('quatAngleZ', () => {
+ it('reads the Z angle of a pure-Z quaternion', () => {
+ const a = Math.PI / 3;
+ const q = { w: Math.cos(a / 2), x: 0, y: 0, z: Math.sin(a / 2) };
+ expect(quatAngleZ(q)).toBeCloseTo(a, 6);
+ });
+ it('identity quat is zero', () => {
+ expect(quatAngleZ({ w: 1, x: 0, y: 0, z: 0 })).toBeCloseTo(0, 6);
+ });
+});
+
+describe('pointInOBB', () => {
+ it('hits inside an axis-aligned box and misses outside', () => {
+ const b = box(0, 0, 10, 5);
+ expect(pointInOBB(0, 0, b)).toBe(true);
+ expect(pointInOBB(9, 4, b)).toBe(true);
+ expect(pointInOBB(11, 0, b)).toBe(false);
+ expect(pointInOBB(0, 6, b)).toBe(false);
+ });
+
+ it('respects rotation — a 45° box rejects a point the AABB would accept', () => {
+ const b = box(0, 0, 10, 10, Math.PI / 4);
+ // The unrotated corner (10,10) is outside the rotated box (its corners reach ±14.1 on the axes).
+ expect(pointInOBB(10, 10, b)).toBe(false);
+ // A point along the rotated local-x axis at distance 10 is on the edge → inside.
+ const c = Math.cos(Math.PI / 4);
+ expect(pointInOBB(10 * c, 10 * c, b)).toBe(true);
+ });
+});
+
+describe('obbCorners', () => {
+ it('gives the four corners of an axis-aligned box', () => {
+ const cs = obbCorners(box(5, 5, 2, 1));
+ expect(cs).toEqual([
+ [3, 4],
+ [7, 4],
+ [7, 6],
+ [3, 6],
+ ]);
+ });
+});
+
+describe('rectsIntersect', () => {
+ const r = { x: 0, y: 0, w: 10, h: 10 };
+ it('overlapping rects intersect', () => {
+ expect(rectsIntersect(r, { x: 5, y: 5, w: 10, h: 10 })).toBe(true);
+ });
+ it('disjoint rects do not', () => {
+ expect(rectsIntersect(r, { x: 20, y: 0, w: 5, h: 5 })).toBe(false);
+ });
+ it('edge-touching counts as intersecting', () => {
+ expect(rectsIntersect(r, { x: 10, y: 0, w: 5, h: 5 })).toBe(true);
+ });
+});
+
+describe('screenAABB', () => {
+ it('bounds a set of points', () => {
+ expect(screenAABB([{ x: 1, y: 2 }, { x: 5, y: 1 }, { x: 3, y: 7 }])).toEqual({ x: 1, y: 1, w: 4, h: 6 });
+ });
+ it('returns null if any point failed to project', () => {
+ expect(screenAABB([{ x: 1, y: 2 }, null])).toBeNull();
+ });
+});
+
+describe('snapTo / clamp', () => {
+ it('snaps to the nearest multiple', () => {
+ expect(snapTo(17, 8)).toBe(16);
+ expect(snapTo(20, 8)).toBe(24);
+ expect(snapTo(13.4, 0)).toBe(13.4); // step <= 0 is a no-op
+ });
+ it('clamps to range', () => {
+ expect(clamp(5, 0, 10)).toBe(5);
+ expect(clamp(-1, 0, 10)).toBe(0);
+ expect(clamp(99, 0, 10)).toBe(10);
+ });
+});