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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor(editor): viewport input as pluggable EditorTools
esengine5a0ffde40cbb
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex 7d8d1e640..f1c0b893d 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -12,27 +12,18 @@ import { commands } from '@/commands';import { EngineHost } from '@/engine/EngineHost';import { PlayRealm } from '@/engine/PlayRealm';import { ViewportController } from '@/engine/ViewportController';-import { SceneCommands } from '@/engine/SceneCommands';-import { SceneQuery } from '@/engine/SceneQuery';import { ProjectStore } from '@/project/ProjectStore';import { SceneModel } from '@/engine/SceneModel';import { SceneStore } from '@/engine/SceneStore';import { StatsStore } from '@/engine/StatsStore';import type { ToolMode } from '@/types';-import { TilemapAPI } from 'esengine';-import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';-import type { TilePaint } from '@/engine/SceneCommands';--// Cursor (client px) → tile grid coords on a TilemapLayer entity: client→world via the-// editor camera, then world→tile around the layer's world origin (its Transform).-function cursorTile(clientX: number, clientY: number, sourceId: number): { x: number; y: number } | null {- const rt = SceneModel.runtimeFor(sourceId);- const wp = ViewportController.canvasToWorld(clientX, clientY);- const ep = rt != null ? ViewportController.getEntityXY(rt) : null;- if (rt == null || !wp || !ep) return null;- const t = TilemapAPI.worldToTile(rt, wp.x, wp.y, ep.x, ep.y);- return { x: Math.floor(t.x), y: Math.floor(t.y) };-}+import { resolveActiveTool, type EditorTool, type ToolContext, type PointerInput } from '@/tools';++// A React pointer event → the tool-facing PointerInput (no DOM coupling in tools).+const toInput = (e: ReactPointerEvent): PointerInput => ({+ clientX: e.clientX, clientY: e.clientY, pointerId: e.pointerId,+ 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.@@ -77,12 +68,6 @@ function GizmoGlyph({ tool }: { tool: ToolMode }) {);}-type Drag =- | { kind: 'move'; id: number; dx: number; dy: number }- | { kind: 'rotate'; id: number; cx: number; cy: number; startAngle: number; startRot: number }- | { kind: 'scale'; id: number; cx: number; cy: number; startDist: number; sx: number; sy: number; sz: number }- | { kind: 'pan'; px: number; py: number };-const TOOLS: { mode: ToolMode; icon: LucideIcon; label: string; key: string }[] = [{ mode: 'select', icon: MousePointer2, label: 'Select', key: 'Q' },{ mode: 'move', icon: Move, label: 'Move', key: 'W' },@@ -90,13 +75,8 @@ const TOOLS: { mode: ToolMode; icon: LucideIcon; label: string; key: string }[]{ mode: 'scale', icon: Scale3d, label: 'Scale', key: 'R' },];-// Angle/scale snap increments applied while Snapping is on. Fixed for now — a-// future Preferences panel will make these user-configurable. The Move step is-// the user-chosen `snapStep` (viewport Snap dropdown), not a constant here.-const SNAP_ROTATE = 15; // degrees-const SNAP_SCALE = 0.1; // uniform scale step-const SNAP_STEPS = [16, 32, 64]; // world units offered by the Snap dropdown-const snap = (v: number, step: number) => Math.round(v / step) * step;+// World units offered by the viewport Snap dropdown (move snap step).+const SNAP_STEPS = [16, 32, 64];// One-line hint shown under the coord readout, reflecting the active tool.const TOOL_HINT: Record<ToolMode, string> = {@@ -106,17 +86,6 @@ const TOOL_HINT: Record<ToolMode, string> = {scale: 'Drag out from the entity to scale',};-// Entity's screen-center in viewport (client) coordinates.-function entityClientCenter(id: number): { cx: number; cy: number } | null {- const pos = ViewportController.getEntityXY(id);- 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 };-}-function OvTool({icon: Icon,label,@@ -227,9 +196,15 @@ export function Viewport() {const playHostRef = useRef<HTMLDivElement>(null);const gizmoRef = useRef<HTMLDivElement>(null);const selectionRef = useRef<HTMLDivElement>(null);- const dragRef = useRef<Drag | null>(null);- // Active tilemap paint stroke (kept separate from the transform drag union above).- const paintRef = useRef<{ sourceId: number; tool: PaintTool; last: string; startX?: number; startY?: number } | null>(null);+ // Camera pan (middle/right drag) is built-in navigation, separate from tools.+ const panRef = useRef<{ px: number; py: number } | null>(null);+ // The tool that owns the in-progress left-button stroke (move/up route to it).+ const activeToolRef = useRef<EditorTool | null>(null);+ // Host services handed to tools during a stroke; stable across renders.+ const toolCtx = useMemo<ToolContext>(() => ({+ capture: (id) => stageRef.current?.setPointerCapture(id),+ release: (id) => stageRef.current?.releasePointerCapture(id),+ }), []);const [zoomPct, setZoomPct] = useState(100);const engine = useSyncExternalStore(EngineHost.subscribe, EngineHost.getSnapshot);const realm = useSyncExternalStore(PlayRealm.subscribe, PlayRealm.getSnapshot);@@ -349,82 +324,24 @@ export function Viewport() {const onPointerDown = (e: ReactPointerEvent) => {if (engine.status !== 'ready') return;- // Middle / right drag = pan the view.+ // Middle / right drag = pan the view (camera navigation, always available+ // regardless of the active tool).if (e.button === 1 || e.button === 2) {e.preventDefault();- dragRef.current = { kind: 'pan', px: e.clientX, py: e.clientY };+ panRef.current = { px: e.clientX, py: e.clientY };stageRef.current?.setPointerCapture(e.pointerId);return;}if (e.button !== 0) return;- // Tile painting: when a paint tool is active over the SELECTED TilemapLayer, the- // left button paints (it must NOT re-pick/select another entity).- const paint = useTilemapPaint.getState();- const selId = useSelection.getState().selectedId;- const isTilemap = selId != null- && !!SceneModel.entityBySource(selId)?.components.some((c) => c.type === 'TilemapLayer');- if (paint.tool && isTilemap && selId != null) {+ // Left button → the active tool owns the stroke (resolveActiveTool picks the+ // tilemap paint tool over a selected layer, else the transform tool).+ const t = resolveActiveTool();+ if (t.onPointerDown(toInput(e), toolCtx)) {e.preventDefault();- const tile = cursorTile(e.clientX, e.clientY, selId);- if (!tile) return;- if (paint.tool === 'eyedropper') {- const rt = SceneModel.runtimeFor(selId);- const id = rt != null ? TilemapAPI.getTile(rt, tile.x, tile.y) : 0;- if (id > 0) paint.setBrush(id);- return;- }- if (paint.tool === 'rect') {- paintRef.current = { sourceId: selId, tool: 'rect', last: '', startX: tile.x, startY: tile.y };- stageRef.current?.setPointerCapture(e.pointerId);- return;- }- // brush / erase — a live stroke committed as one undo step on release.- const tileId = paint.tool === 'erase' ? 0 : paint.brushTileId;- SceneCommands.beginTilePaint(selId);- SceneCommands.paintTileLive(selId, tile.x, tile.y, tileId);- paintRef.current = { sourceId: selId, tool: paint.tool, last: `${tile.x},${tile.y}` };- stageRef.current?.setPointerCapture(e.pointerId);- return;- }-- // Pick returns a runtime World entity (rendering domain); the editor selects- // and commands by stable source id. Resolve once: source id drives selection- // + SceneCommands; the runtime id drives ViewportController screen geometry.- const rtId = ViewportController.pickEntity(e.clientX, e.clientY);- const sourceId = rtId != null ? SceneModel.sourceFor(rtId) ?? null : null;- useSelection.getState().select(sourceId);- if (rtId == null || sourceId == null) return;-- if (tool === 'rotate') {- const c = entityClientCenter(rtId);- const startRot = (SceneQuery.getFieldValue(sourceId, 'Transform', 'rotation') as number) ?? 0;- if (!c) return;- SceneCommands.beginGesture('Rotate');- dragRef.current = {- kind: 'rotate', id: sourceId, cx: c.cx, cy: c.cy,- startAngle: Math.atan2(e.clientY - c.cy, e.clientX - c.cx), startRot,- };- stageRef.current?.setPointerCapture(e.pointerId);- } else if (tool === 'scale') {- const c = entityClientCenter(rtId);- const s = (SceneQuery.getFieldValue(sourceId, 'Transform', 'scale') as number[]) ?? [1, 1, 1];- if (!c) return;- SceneCommands.beginGesture('Scale');- dragRef.current = {- kind: 'scale', id: sourceId, cx: c.cx, cy: c.cy,- startDist: Math.max(1, Math.hypot(e.clientX - c.cx, e.clientY - c.cy)),- sx: s[0] ?? 1, sy: s[1] ?? 1, sz: s[2] ?? 1,- };- stageRef.current?.setPointerCapture(e.pointerId);+ activeToolRef.current = t;} else {- const wp = ViewportController.canvasToWorld(e.clientX, e.clientY);- const ep = ViewportController.getEntityXY(rtId);- if (wp && ep) {- SceneCommands.beginGesture('Move');- dragRef.current = { kind: 'move', id: sourceId, dx: ep.x - wp.x, dy: ep.y - wp.y };- stageRef.current?.setPointerCapture(e.pointerId);- }+ activeToolRef.current = null;}};@@ -432,87 +349,25 @@ export function Viewport() {const wp = ViewportController.canvasToWorld(e.clientX, e.clientY);if (wp) StatsStore.setCursor(wp.x, wp.y);- // Live brush/erase stroke: paint each newly-entered tile (rect previews on release).- const p = paintRef.current;- if (p) {- if (p.tool === 'brush' || p.tool === 'erase') {- const tile = cursorTile(e.clientX, e.clientY, p.sourceId);- if (tile) {- const key = `${tile.x},${tile.y}`;- if (key !== p.last) {- const tileId = p.tool === 'erase' ? 0 : useTilemapPaint.getState().brushTileId;- SceneCommands.paintTileLive(p.sourceId, tile.x, tile.y, tileId);- p.last = key;- }- }- }- return; // painting overrides transform drag- }-- const drag = dragRef.current;- if (!drag) return;- const snapOn = useEditorStore.getState().snapping;-- if (drag.kind === 'pan') {- ViewportController.panByClient(drag.px, drag.py, e.clientX, e.clientY);- drag.px = e.clientX;- drag.py = e.clientY;- } else if (drag.kind === 'move') {- if (wp) {- let x = wp.x + drag.dx;- let y = wp.y + drag.dy;- if (snapOn) {- const step = useEditorStore.getState().snapStep;- x = snap(x, step);- y = snap(y, step);- }- SceneCommands.setEntityXY(drag.id, x, y);- }- } else if (drag.kind === 'rotate') {- const angle = Math.atan2(e.clientY - drag.cy, e.clientX - drag.cx);- const deltaDeg = ((angle - drag.startAngle) * 180) / Math.PI;- // Screen y is down, so a clockwise screen drag is a negative world rotation.- let rot = drag.startRot - deltaDeg;- if (snapOn) rot = snap(rot, SNAP_ROTATE);- SceneCommands.setField(drag.id, 'Transform', 'rotation', 'angle', rot);- } else if (drag.kind === 'scale') {- const dist = Math.hypot(e.clientX - drag.cx, e.clientY - drag.cy);- const f = dist / drag.startDist;- let sx = drag.sx * f;- let sy = drag.sy * f;- if (snapOn) { sx = snap(sx, SNAP_SCALE); sy = snap(sy, SNAP_SCALE); }- SceneCommands.setField(drag.id, 'Transform', 'scale', 'vec3', [sx, sy, drag.sz]);+ if (panRef.current) {+ ViewportController.panByClient(panRef.current.px, panRef.current.py, e.clientX, e.clientY);+ panRef.current.px = e.clientX;+ panRef.current.py = e.clientY;+ return;}+ activeToolRef.current?.onPointerMove(toInput(e), toolCtx);};const endDrag = (e: ReactPointerEvent) => {- // Commit an in-progress tile paint stroke first.- const p = paintRef.current;- if (p) {+ if (panRef.current) {stageRef.current?.releasePointerCapture(e.pointerId);- paintRef.current = null;- if (p.tool === 'rect' && p.startX != null && p.startY != null) {- const tile = cursorTile(e.clientX, e.clientY, p.sourceId);- if (tile) {- const x0 = Math.min(p.startX, tile.x), x1 = Math.max(p.startX, tile.x);- const y0 = Math.min(p.startY, tile.y), y1 = Math.max(p.startY, tile.y);- const tileId = useTilemapPaint.getState().brushTileId;- const edits: TilePaint[] = [];- for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) edits.push({ x, y, tileId });- SceneCommands.paintTiles(p.sourceId, edits);- }- } else {- SceneCommands.endTilePaint();- }+ panRef.current = null;return;}-- const drag = dragRef.current;- if (!drag) return;- stageRef.current?.releasePointerCapture(e.pointerId);- dragRef.current = null;- // Camera pan is a direct view write (no undo); edits close their gesture.- if (drag.kind !== 'pan') SceneCommands.endGesture();+ const t = activeToolRef.current;+ if (!t) return;+ activeToolRef.current = null;+ t.onPointerUp(toInput(e), toolCtx);};// Drag a `.esprefab` from the Content Browser into the scene → instantiate itdiff --git a/desktop/src/tools/EditorTool.ts b/desktop/src/tools/EditorTool.tsnew file mode 100644index 000000000..53d828aa8--- /dev/null+++ b/desktop/src/tools/EditorTool.ts@@ -0,0 +1,44 @@+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file EditorTool.ts+ * @brief The viewport interactive-tool contract (the editor's Interactive Tools+ * Framework). Every pointer interaction — select/move/rotate/scale, tile+ * brush/erase/rect/eyedropper, and future tools — is an EditorTool, so the+ * Viewport is a thin router (resolve active tool, dispatch the stroke)+ * instead of one growing if-cascade. A tool owns its per-stroke state and+ * drives one undo transaction per stroke; the host owns pointer capture.+ */++/** A pointer event normalized to what tools need (no React/DOM coupling). */+export interface PointerInput {+ clientX: number;+ clientY: number;+ pointerId: number;+ button: number;+ shift: boolean;+ alt: boolean;+}++/** Host-owned services a tool needs during a stroke (everything else — picking,+ * commands, stores — are app singletons the tools import directly). */+export interface ToolContext {+ /** Capture the pointer on the viewport stage so the stroke keeps receiving+ * move/up events outside the element. */+ capture(pointerId: number): void;+ release(pointerId: number): void;+}++export interface EditorTool {+ readonly id: string;+ /**+ * Begin a stroke. Return true if the tool took it — the host then routes this+ * stroke's move/up to this tool. Return false for a one-shot action (e.g. the+ * eyedropper) or a no-op (clicked empty space).+ */+ onPointerDown(p: PointerInput, ctx: ToolContext): boolean;+ onPointerMove(p: PointerInput, ctx: ToolContext): void;+ onPointerUp(p: PointerInput, ctx: ToolContext): void;+ /** Cancel an in-progress stroke (tool switch / Esc), rolling back live edits. */+ cancel?(ctx: ToolContext): void;+}diff --git a/desktop/src/tools/index.ts b/desktop/src/tools/index.tsnew file mode 100644index 000000000..35fbb519f--- /dev/null+++ b/desktop/src/tools/index.ts@@ -0,0 +1,27 @@+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file tools/index.ts+ * @brief Resolves the active viewport tool from editor state. A tilemap paint tool+ * wins when a TilemapLayer is selected (it must not re-pick/select); else+ * the transform tool (select/move/rotate/scale) is active. The Viewport+ * calls this per pointer-down and routes the stroke to the returned tool.+ */+import { SceneModel } from '@/engine/SceneModel';+import { useSelection } from '@/store/selectionStore';+import { useEditorStore } from '@/store/editorStore';+import { useTilemapPaint } from '@/store/tilemapPaintStore';+import { TRANSFORM_TOOLS } from './transformTools';+import { TILE_TOOLS } from './tileTools';+import type { EditorTool } from './EditorTool';++export function resolveActiveTool(): EditorTool {+ const paint = useTilemapPaint.getState();+ const selId = useSelection.getState().selectedId;+ const isTilemap = selId != null+ && !!SceneModel.entityBySource(selId)?.components.some((c) => c.type === 'TilemapLayer');+ if (paint.tool && isTilemap) return TILE_TOOLS[paint.tool];+ return TRANSFORM_TOOLS[useEditorStore.getState().tool] ?? TRANSFORM_TOOLS.select;+}++export type { EditorTool, PointerInput, ToolContext } from './EditorTool';diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.tsnew file mode 100644index 000000000..0dcbf840d--- /dev/null+++ b/desktop/src/tools/tileTools.ts@@ -0,0 +1,135 @@+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file tileTools.ts+ * @brief The tilemap paint tools — brush / erase / rect / eyedropper. Active only+ * when a TilemapLayer is selected (the host resolves that); each operates+ * on the selected layer via SceneCommands' tile-paint stroke API.+ */+import { TilemapAPI } from 'esengine';+import { ViewportController } from '@/engine/ViewportController';+import { SceneCommands, type TilePaint } from '@/engine/SceneCommands';+import { SceneModel } from '@/engine/SceneModel';+import { useSelection } from '@/store/selectionStore';+import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';+import type { EditorTool, PointerInput } from './EditorTool';++// Cursor (client px) → tile grid coords on a TilemapLayer entity: client→world via+// the editor camera, then world→tile around the layer's world origin (its Transform).+function cursorTile(clientX: number, clientY: number, sourceId: number): { x: number; y: number } | null {+ const rt = SceneModel.runtimeFor(sourceId);+ const wp = ViewportController.canvasToWorld(clientX, clientY);+ const ep = rt != null ? ViewportController.getEntityXY(rt) : null;+ if (rt == null || !wp || !ep) return null;+ const t = TilemapAPI.worldToTile(rt, wp.x, wp.y, ep.x, ep.y);+ return { x: Math.floor(t.x), y: Math.floor(t.y) };+}++const selectedTilemap = (): number | null => useSelection.getState().selectedId;++/** Brush (paints brushTileId) / Erase (paints 0): a live stroke, one undo step. */+function makeBrushTool(id: string, erase: boolean): EditorTool {+ let stroke: { sourceId: number; last: string } | null = null;+ const tileId = () => (erase ? 0 : useTilemapPaint.getState().brushTileId);+ return {+ id,+ onPointerDown(p, ctx) {+ const selId = selectedTilemap();+ if (selId == null) return false;+ const tile = cursorTile(p.clientX, p.clientY, selId);+ if (!tile) return false;+ SceneCommands.beginTilePaint(selId);+ SceneCommands.paintTileLive(selId, tile.x, tile.y, tileId());+ stroke = { sourceId: selId, last: `${tile.x},${tile.y}` };+ ctx.capture(p.pointerId);+ return true;+ },+ onPointerMove(p) {+ if (!stroke) return;+ const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);+ if (!tile) return;+ const key = `${tile.x},${tile.y}`;+ if (key === stroke.last) return;+ SceneCommands.paintTileLive(stroke.sourceId, tile.x, tile.y, tileId());+ stroke.last = key;+ },+ onPointerUp(p, ctx) {+ if (!stroke) return;+ ctx.release(p.pointerId);+ SceneCommands.endTilePaint();+ stroke = null;+ },+ cancel() {+ if (!stroke) return;+ // No mid-stroke tile rollback yet; commit what is painted (matches pointercancel).+ SceneCommands.endTilePaint();+ stroke = null;+ },+ };+}++/** Rect fill: drag a rectangle, fill it with brushTileId on release (one step). */+function makeRectTool(): EditorTool {+ let stroke: { sourceId: number; startX: number; startY: number } | null = null;+ return {+ id: 'tilemap.rect',+ onPointerDown(p, ctx) {+ const selId = selectedTilemap();+ if (selId == null) return false;+ const tile = cursorTile(p.clientX, p.clientY, selId);+ if (!tile) return false;+ stroke = { sourceId: selId, startX: tile.x, startY: tile.y };+ ctx.capture(p.pointerId);+ return true;+ },+ onPointerMove() {+ // Rect previews on release (no live fill) — matches the prior behavior.+ },+ onPointerUp(p, ctx) {+ if (!stroke) return;+ ctx.release(p.pointerId);+ const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);+ if (tile) {+ const x0 = Math.min(stroke.startX, tile.x);+ const x1 = Math.max(stroke.startX, tile.x);+ const y0 = Math.min(stroke.startY, tile.y);+ const y1 = Math.max(stroke.startY, tile.y);+ const tileId = useTilemapPaint.getState().brushTileId;+ const edits: TilePaint[] = [];+ for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) edits.push({ x, y, tileId });+ SceneCommands.paintTiles(stroke.sourceId, edits);+ }+ stroke = null;+ },+ cancel() {+ stroke = null;+ },+ };+}++/** Eyedropper: one-shot — read the tile under the cursor into the active brush. */+const eyedropperTool: EditorTool = {+ id: 'tilemap.eyedropper',+ onPointerDown(p) {+ const selId = selectedTilemap();+ if (selId == null) return false;+ const tile = cursorTile(p.clientX, p.clientY, selId);+ if (!tile) return false;+ const rt = SceneModel.runtimeFor(selId);+ const id = rt != null ? TilemapAPI.getTile(rt, tile.x, tile.y) : 0;+ if (id > 0) useTilemapPaint.getState().setBrush(id);+ return false; // no ongoing stroke+ },+ onPointerMove() {},+ onPointerUp() {},+};++/** Tile tools keyed by PaintTool (brush/erase/rect/eyedropper). */+export const TILE_TOOLS: Record<PaintTool, EditorTool> = {+ brush: makeBrushTool('tilemap.brush', false),+ erase: makeBrushTool('tilemap.erase', true),+ rect: makeRectTool(),+ eyedropper: eyedropperTool,+};++export type { PointerInput };diff --git a/desktop/src/tools/transformTools.ts b/desktop/src/tools/transformTools.tsnew file mode 100644index 000000000..045c2b080--- /dev/null+++ b/desktop/src/tools/transformTools.ts@@ -0,0 +1,179 @@+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0+// 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.+ */+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 { useSelection } from '@/store/selectionStore';+import { useEditorStore } from '@/store/editorStore';+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;++// Entity's screen-center in viewport (client) coordinates.+function entityClientCenter(rtId: number): { cx: number; cy: number } | 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 };+}++/** 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 };+}++/** 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;+ },+ };+}++function makeRotateTool(): EditorTool {+ let stroke: { id: number; cx: number; cy: number; startAngle: number; startRot: number; tx: EditorTransaction } | null = null;+ 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;+ },+ };+}++function makeScaleTool(): EditorTool {+ let stroke: { id: number; cx: number; cy: number; startDist: number; sx: number; sy: number; sz: number; tx: EditorTransaction } | null = null;+ return {+ id: 'transform.scale',+ 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'),+ };+ 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);+ }+ 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;+ },+ cancel() {+ if (!stroke) return;+ stroke.tx.abort();+ stroke = 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(),+};diff --git a/desktop/tests/editor-tools.test.ts b/desktop/tests/editor-tools.test.tsnew file mode 100644index 000000000..cf4306644--- /dev/null+++ b/desktop/tests/editor-tools.test.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Editor tool registry shape — every transform/tile tool exists, is keyed+ * by the editor's ToolMode / PaintTool, implements the EditorTool contract,+ * and has a unique namespaced id. Guards the Viewport router's lookups.+ */+import { describe, it, expect } from 'vitest';+import { TRANSFORM_TOOLS } from '@/tools/transformTools';+import { TILE_TOOLS } from '@/tools/tileTools';+import type { EditorTool } from '@/tools/EditorTool';++const implementsContract = (t: EditorTool) =>+ typeof t.onPointerDown === 'function' &&+ typeof t.onPointerMove === 'function' &&+ typeof t.onPointerUp === 'function';++describe('editor tool registry', () => {+ it('has the transform tools keyed by ToolMode', () => {+ for (const k of ['select', 'move', 'rotate', 'scale']) {+ expect(TRANSFORM_TOOLS[k]).toBeDefined();+ expect(implementsContract(TRANSFORM_TOOLS[k])).toBe(true);+ }+ });++ it('has the tile tools keyed by PaintTool', () => {+ for (const k of ['brush', 'erase', 'rect', 'eyedropper'] as const) {+ expect(TILE_TOOLS[k]).toBeDefined();+ expect(implementsContract(TILE_TOOLS[k])).toBe(true);+ }+ });++ it('tool ids are unique and namespaced', () => {+ const ids = [...Object.values(TRANSFORM_TOOLS), ...Object.values(TILE_TOOLS)].map((t) => t.id);+ expect(new Set(ids).size).toBe(ids.length);+ expect(ids).toContain('transform.move');+ expect(ids).toContain('tilemap.brush');+ });+});