Skip to content

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

feat(editor): editor-mode registry + design-resolution viewport

esengine98e0c76c09d0
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index 049dbe0ba..d6b29fe16 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -18,7 +18,10 @@ import { SettingsDialog } from '@/components/SettingsDialog';
import { TilemapPickerDialog } from '@/components/TilemapPickerDialog';
import { useEditorStore } from '@/store/editorStore';
import { commands } from '@/commands';
-import { handleTilePaintKey, isTilemapSelected } from '@/tools/tileMode';
+import { handleTilePaintKey } from '@/tools/tileMode';
+import { suggestedMode } from '@/mode/activeMode';
+import { useEditorMode } from '@/store/editorModeStore';
+import type { EditorModeId } from '@/mode/editorModes';
import { useSelection } from '@/store/selectionStore';
import { PlayRealms } from '@/engine/PlayRealm';
import { PlayInspect } from '@/engine/PlayInspect';
@@ -63,15 +66,22 @@ export function App() {
return () => window.removeEventListener('keydown', onKey);
}, []);
- // Surface the Tilemap painter when a tilemap entity becomes the selection (only on
- // the transition INTO one, so switching between tilemaps doesn't keep yanking focus).
- // "Select a tilemap → here's how you paint it" then needs no hunting for the panel.
+ // Reveal a mode's companion panels when the selection enters that mode (only on the
+ // transition INTO one, so moving within a mode doesn't keep yanking focus). This
+ // generalizes the old tilemap-painter auto-open: "select a tilemap → here's how you
+ // paint it" is now one instance of "enter a mode → here are its panels". A selection
+ // that implies a new mode also drops a stale explicit pin.
useEffect(() => {
- let wasTilemap = false;
+ let prevMode: EditorModeId | null = null;
return useSelection.subscribe(() => {
- const isTm = isTilemapSelected();
- if (isTm && !wasTilemap) dockApi.openSidePanel('tilemap', 'tilemap', 'Tilemap', 'left', 300);
- wasTilemap = isTm;
+ const mode = suggestedMode();
+ if (mode.id !== prevMode) {
+ useEditorMode.getState().clearPin();
+ for (const p of mode.panels ?? []) {
+ dockApi.openSidePanel(p.id, p.component, p.title, p.side ?? 'left', p.width ?? 300);
+ }
+ }
+ prevMode = mode.id;
});
}, []);
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index 1f3b3e5e1..47790956e 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -17,6 +17,10 @@ import { SceneModel } from '@/engine/SceneModel';
import { hasEntityClipboard } from '@/engine/entityClipboard';
import { ViewportController } from '@/engine/ViewportController';
import { createTilemapFromTileset } from '@/tilemap/createTilemap';
+import { dockApi } from '@/layout/dockApi';
+import { EDITOR_MODES } from '@/mode/editorModes';
+import { activeMode } from '@/mode/activeMode';
+import { useEditorMode } from '@/store/editorModeStore';
import { useEditorStore } from '@/store/editorStore';
import { useSelection } from '@/store/selectionStore';
import { Toasts } from '@/store/Toasts';
@@ -211,6 +215,25 @@ 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') });
+// — Editor modes — pin an explicit editing context (Scene/UI/Tilemap) and reveal its
+// companion panels. Without a pin the mode follows the selection; a pin holds until the
+// selection implies another mode. Opening the panels here folds in the old dedicated
+// Tilemap-painter launcher (clicking Tilemap mode reveals the painter).
+for (const m of EDITOR_MODES) {
+ commands.register({
+ id: `mode.${m.id}`,
+ label: `${m.label} Mode`,
+ category: 'Tools',
+ isChecked: () => activeMode().id === m.id,
+ run: () => {
+ useEditorMode.getState().setMode(m.id);
+ for (const p of m.panels ?? []) {
+ dockApi.openSidePanel(p.id, p.component, p.title, p.side ?? 'left', p.width ?? 300);
+ }
+ },
+ });
+}
+
// — 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).
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index 938ecb063..136274803 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -467,6 +467,44 @@ export const ViewportController = {
return 100;
},
+ /**
+ * The scene's Canvas singleton — the design-resolution preview source — or null.
+ * Reads the first entity carrying a Canvas (the same singleton-per-scene assumption
+ * as the runtime's registry_getCanvasEntity), centered on its Transform.
+ */
+ canvasInfo(): {
+ cx: number; cy: number;
+ designResolution: { x: number; y: number };
+ pixelsPerUnit: number;
+ scaleMode: number;
+ matchWidthOrHeight: number;
+ backgroundColor: { r: number; g: number; b: number; a: number };
+ } | null {
+ const world = EngineHost.world;
+ if (!world) return null;
+ for (const e of world.getAllEntities()) {
+ if (!world.has(e, Canvas)) continue;
+ const c = world.get(e, Canvas) as {
+ designResolution: { x: number; y: number };
+ pixelsPerUnit: number;
+ scaleMode: number;
+ matchWidthOrHeight: number;
+ backgroundColor: { r: number; g: number; b: number; a: number };
+ };
+ const t = world.has(e, Transform) ? world.get(e, Transform) : null;
+ return {
+ cx: t?.worldPosition.x ?? 0,
+ cy: t?.worldPosition.y ?? 0,
+ designResolution: c.designResolution,
+ pixelsPerUnit: c.pixelsPerUnit || 100,
+ scaleMode: c.scaleMode,
+ matchWidthOrHeight: c.matchWidthOrHeight,
+ backgroundColor: c.backgroundColor,
+ };
+ }
+ return null;
+ },
+
/**
* Screen-space collider outline for the gizmo: a 4-corner polygon (box) or a
* center + radius (circle), in CSS px. The collider lives at the entity's world
diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.ts
index c46e583f3..8a1cf56da 100644
--- a/desktop/src/engine/entitySources.ts
+++ b/desktop/src/engine/entitySources.ts
@@ -100,6 +100,14 @@ function presetSource(id: string, label: string, category: string, icon: LucideI
return { id, label, category, icon, build: () => prefab };
}
+// Project reference resolution provider (ProjectStore wires this on open). A new
+// Canvas seeds its designResolution from it; injected rather than imported so
+// entitySources doesn't cycle with ProjectStore (as setPrefabBaseResolver does).
+let canvasDesignSeed: (() => { width: number; height: number }) | null = null;
+export function setCanvasDesignSeed(fn: () => { width: number; height: number }): void {
+ canvasDesignSeed = fn;
+}
+
const UI_WIDGET_ICON: Record<string, LucideIcon> = {
Button: SquareMousePointer,
Toggle: ToggleLeft,
@@ -148,7 +156,16 @@ function anchorSources(): EntitySource[] {
export const ENTITY_SOURCES: EntitySource[] = [
presetSource('empty', 'Empty', 'Basic', CircleDot, ['Transform']),
...anchorSources(),
- presetSource('canvas', 'Canvas', 'UI', LayoutPanelTop, ['Transform', ['Canvas', { designResolution: { x: 800, y: 600 }, scaleMode: 2 }], 'UINode']),
+ {
+ id: 'canvas',
+ label: 'Canvas',
+ category: 'UI',
+ icon: LayoutPanelTop,
+ build: () => {
+ const d = canvasDesignSeed?.() ?? { width: 1920, height: 1080 };
+ return preset('Canvas', ['Transform', ['Canvas', { designResolution: { x: d.width, y: d.height } }], 'UINode']);
+ },
+ },
...BUILTIN_UI_WIDGET_NAMES.map((name): EntitySource => ({
id: `ui-${name.toLowerCase()}`,
label: name,
diff --git a/desktop/src/layout/ActivityBar.tsx b/desktop/src/layout/ActivityBar.tsx
index 3be9c9452..e7fa38d6c 100644
--- a/desktop/src/layout/ActivityBar.tsx
+++ b/desktop/src/layout/ActivityBar.tsx
@@ -1,18 +1,42 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-// Far-left icon rail (activity bar). Reveals docked panels and toggles the
-// Content Drawer — the summoned quick-access surface.
-import { ListTree, SlidersHorizontal, FolderOpen, Terminal, Clapperboard, Grid3x3, Gauge, Settings } from 'lucide-react';
+// Far-left icon rail (activity bar). Switches the editing mode, reveals docked
+// panels, and toggles the Content Drawer — the summoned quick-access surface.
+import { ListTree, SlidersHorizontal, FolderOpen, Terminal, Clapperboard, Gauge, Settings } from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
+import { useEditorMode } from '@/store/editorModeStore';
+import { useSelection } from '@/store/selectionStore';
+import { EDITOR_MODES } from '@/mode/editorModes';
+import { activeMode } from '@/mode/activeMode';
import { dockApi } from '@/layout/dockApi';
import { commands } from '@/commands';
export function ActivityBar() {
const contentDrawer = useEditorStore((s) => s.contentDrawer);
const toggleContentDrawer = useEditorStore((s) => s.toggleContentDrawer);
+ // The active mode is derived from the pin + selection; subscribe to both so the
+ // highlighted mode button tracks selection-driven changes, not just explicit pins.
+ useEditorMode((s) => s.pinned);
+ useSelection((s) => s.selectedId);
+ const current = activeMode().id;
return (
<div className="activity">
+ {EDITOR_MODES.map((m) => {
+ const Icon = m.icon;
+ return (
+ <button
+ key={m.id}
+ type="button"
+ className={`act${current === m.id ? ' active' : ''}`}
+ title={`${m.label} Mode`}
+ onClick={() => commands.run(`mode.${m.id}`)}
+ >
+ <Icon size={19} strokeWidth={1.7} />
+ </button>
+ );
+ })}
+ <span className="act-sep" />
<button
type="button"
className="act"
@@ -53,14 +77,6 @@ export function ActivityBar() {
>
<Clapperboard size={19} strokeWidth={1.7} />
</button>
- <button
- type="button"
- className="act"
- title="Tilemap Painter (binds to the selected Tilemap)"
- onClick={() => dockApi.openSidePanel('tilemap', 'tilemap', 'Tilemap', 'left', 300)}
- >
- <Grid3x3 size={19} strokeWidth={1.7} />
- </button>
<button
type="button"
className="act"
diff --git a/desktop/src/mode/activeMode.ts b/desktop/src/mode/activeMode.ts
new file mode 100644
index 000000000..6d3d99f04
--- /dev/null
+++ b/desktop/src/mode/activeMode.ts
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file activeMode.ts — derives the active editor mode from the selection + an
+ * optional pin. Mirrors tileMode.ts: reads live store state (never a
+ * subscription) so callers in the pointer path / rAF stay allocation-cheap.
+ */
+import { SceneModel } from '@/engine/SceneModel';
+import { useSelection } from '@/store/selectionStore';
+import { useEditorMode } from '@/store/editorModeStore';
+import { EDITOR_MODES, EDITOR_MODE_BY_ID, type EditorModeDef, type SelectionProbe } from './editorModes';
+
+/** The active selection's component membership, for a mode's `suggestFor`. */
+function probe(): SelectionProbe {
+ const id = useSelection.getState().selectedId;
+ const comps = id != null ? SceneModel.entityBySource(id)?.components : undefined;
+ return { hasComponent: (type) => !!comps?.some((c) => c.type === type) };
+}
+
+/** The mode the current selection implies (first matching in priority order, else Scene). */
+export function suggestedMode(): EditorModeDef {
+ const p = probe();
+ return EDITOR_MODES.find((m) => m.suggestFor?.(p)) ?? EDITOR_MODE_BY_ID.scene;
+}
+
+/** The effective mode: an explicit pin wins, else the selection-suggested mode. */
+export function activeMode(): EditorModeDef {
+ const pinned = useEditorMode.getState().pinned;
+ return pinned ? EDITOR_MODE_BY_ID[pinned] : suggestedMode();
+}
+
+/** The active mode's overlay flags, never undefined (for the viewport rAF gate). */
+export function activeModeOverlays(): NonNullable<EditorModeDef['overlays']> {
+ return activeMode().overlays ?? {};
+}
diff --git a/desktop/src/mode/editorModes.ts b/desktop/src/mode/editorModes.ts
new file mode 100644
index 000000000..55a64be37
--- /dev/null
+++ b/desktop/src/mode/editorModes.ts
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file editorModes.ts — THE authority for editor editing modes (the sibling of
+ * entitySources' ENTITY_SOURCES). One data-driven table replaces the
+ * implicit "which editing context am I in" logic that used to be scattered
+ * across resolveActiveTool / isTilePaintMode / App's tilemap auto-open.
+ *
+ * A mode declares its tool family, the companion panels it reveals on entry, the
+ * viewport overlays it turns on, and a `suggestFor` predicate over the current
+ * selection. The active mode is selection-derived (see activeMode.ts) with an
+ * optional explicit pin (editorModeStore) — adding a mode here wires it everywhere.
+ */
+import type { LucideIcon } from 'lucide-react';
+import { MousePointer2, LayoutPanelTop, Grid3x3 } from 'lucide-react';
+
+export type EditorModeId = 'scene' | 'ui' | 'tilemap';
+
+/** The current selection's component membership — all a mode's `suggestFor` needs. */
+export interface SelectionProbe {
+ hasComponent(type: string): boolean;
+}
+
+/** A companion panel a mode reveals when entered (routed through dockApi.openSidePanel). */
+export interface ModePanel {
+ id: string;
+ component: string;
+ title: string;
+ side?: 'left' | 'right';
+ width?: number;
+}
+
+export interface EditorModeDef {
+ id: EditorModeId;
+ label: string;
+ icon: LucideIcon;
+ /** Which tool family the viewport routes pointer input to (resolveActiveTool). */
+ toolset: 'transform' | 'tilemap';
+ /** Companion panels revealed on entering the mode. */
+ panels?: ModePanel[];
+ /** Viewport overlays this mode turns on. */
+ overlays?: { designFrame?: boolean; safeArea?: boolean; letterbox?: boolean };
+ /** True when the selection should suggest this mode. Omitted ⇒ the fallback (always last). */
+ suggestFor?(sel: SelectionProbe): boolean;
+}
+
+const tilemapMode: EditorModeDef = {
+ id: 'tilemap',
+ label: 'Tilemap',
+ icon: Grid3x3,
+ toolset: 'tilemap',
+ panels: [{ id: 'tilemap', component: 'tilemap', title: 'Tilemap', side: 'left', width: 300 }],
+ suggestFor: (s) => s.hasComponent('TilemapLayer'),
+};
+
+const uiMode: EditorModeDef = {
+ id: 'ui',
+ label: 'UI',
+ icon: LayoutPanelTop,
+ toolset: 'transform',
+ overlays: { designFrame: true, safeArea: true, letterbox: true },
+ suggestFor: (s) => s.hasComponent('Canvas') || s.hasComponent('UINode'),
+};
+
+const sceneMode: EditorModeDef = {
+ id: 'scene',
+ label: 'Scene',
+ icon: MousePointer2,
+ toolset: 'transform',
+};
+
+/** Suggestion priority: the first mode whose `suggestFor` matches wins; sceneMode is the fallback. */
+export const EDITOR_MODES: EditorModeDef[] = [tilemapMode, uiMode, sceneMode];
+
+export const EDITOR_MODE_BY_ID: Record<EditorModeId, EditorModeDef> = {
+ scene: sceneMode,
+ ui: uiMode,
+ tilemap: tilemapMode,
+};
diff --git a/desktop/src/mode/resolutionPresets.ts b/desktop/src/mode/resolutionPresets.ts
new file mode 100644
index 000000000..223d4bef6
--- /dev/null
+++ b/desktop/src/mode/resolutionPresets.ts
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file resolutionPresets.ts — target-device presets for the UI-mode viewport
+ * preview (the sibling of the Snap step table). These do NOT change a
+ * Canvas' authored design resolution; they set a simulated screen the
+ * viewport fits the design into, so the letterbox/safe-area preview shows
+ * how the UI adapts on that device. Dimensions are portrait (w ≤ h); the
+ * orientation toggle swaps them at render time.
+ */
+
+export type DevicePresetId = 'design' | 'iphone' | 'ipad' | '1080p' | '720p';
+
+export interface DeviceInsets {
+ top: number;
+ bottom: number;
+ left: number;
+ right: number;
+}
+
+export interface DevicePreset {
+ id: DevicePresetId;
+ label: string;
+ /** Portrait pixel dimensions. The `design` sentinel (0×0) means "use the Canvas' own aspect" (no letterbox). */
+ w: number;
+ h: number;
+ /** Safe-area insets in device pixels (notch / home indicator), if any. */
+ safe?: DeviceInsets;
+}
+
+export const RESOLUTION_PRESETS: DevicePreset[] = [
+ { id: 'design', label: 'Design', w: 0, h: 0 },
+ { id: 'iphone', label: 'iPhone', w: 1170, h: 2532, safe: { top: 141, bottom: 102, left: 0, right: 0 } },
+ { id: 'ipad', label: 'iPad', w: 1640, h: 2360, safe: { top: 48, bottom: 48, left: 0, right: 0 } },
+ { id: '1080p', label: '1080p', w: 1080, h: 1920 },
+ { id: '720p', label: '720p', w: 720, h: 1280 },
+];
+
+export const RESOLUTION_PRESET_BY_ID: Record<DevicePresetId, DevicePreset> = Object.fromEntries(
+ RESOLUTION_PRESETS.map((p) => [p.id, p]),
+) as Record<DevicePresetId, DevicePreset>;
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index b242b0785..989fa266b 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -4,14 +4,17 @@ import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'reac
import type { PointerEvent as ReactPointerEvent, DragEvent as ReactDragEvent, ReactNode } from 'react';
import {
MousePointer2, Move, RotateCw, Scale3d, Grid3x3, Eye, Frame,
- Camera, Check, ChevronDown, Loader2, TriangleAlert, Lightbulb, Sparkles, Globe, Crosshair, type LucideIcon,
+ Camera, Check, ChevronDown, Loader2, TriangleAlert, Lightbulb, Sparkles, Globe, Crosshair, Smartphone, type LucideIcon,
} from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import { useSelection } from '@/store/selectionStore';
import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';
import { exitTilePaint, isTilePaintMode, selectedTilemapCellSize } from '@/tools/tileMode';
+import { activeMode, activeModeOverlays } from '@/mode/activeMode';
+import { useEditorMode } from '@/store/editorModeStore';
+import { RESOLUTION_PRESETS, RESOLUTION_PRESET_BY_ID } from '@/mode/resolutionPresets';
import { buildStampGhost } from '@/tools/tileStampGhost';
-import { TilemapAPI, tileIdOf } from 'esengine';
+import { TilemapAPI, tileIdOf, UINode, DimensionUnit, computeEffectiveOrthoSize } from 'esengine';
import { commands } from '@/commands';
import { MOD_LABEL } from '@/commands/keybinding';
import { EngineHost } from '@/engine/EngineHost';
@@ -106,6 +109,74 @@ function startSizeHandleDrag(
window.addEventListener('pointerup', onUp);
}
+// Project a world-space, axis-aligned rect (center + half extents) to a CSS-px
+// screen rect. The editor camera is 2D ortho (no rotation), so projecting two
+// opposite corners and taking their AABB is exact. Null if off-camera / no view.
+function worldRectToScreen(
+ cx: number,
+ cy: number,
+ halfW: number,
+ halfH: number,
+): { x: number; y: number; w: number; h: number } | null {
+ const a = ViewportController.worldToClient(cx - halfW, cy + halfH);
+ const b = ViewportController.worldToClient(cx + halfW, cy - halfH);
+ if (!a || !b) return null;
+ return { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), w: Math.abs(b.x - a.x), h: Math.abs(b.y - a.y) };
+}
+
+function setRectAttrs(el: Element | null, r: { x: number; y: number; w: number; h: number }): void {
+ if (!el) return;
+ el.setAttribute('x', String(r.x));
+ el.setAttribute('y', String(r.y));
+ el.setAttribute('width', String(Math.max(0, r.w)));
+ el.setAttribute('height', String(Math.max(0, r.h)));
+}
+
+// A UINode length field ({ value, unit }) from the model, or null.
+function uiDim(src: number, key: 'width' | 'height'): { value: number; unit: number } | null {
+ const d = SceneModel.entityBySource(src)?.components.find((c) => c.type === 'UINode')?.data as
+ | Record<string, unknown>
+ | undefined;
+ const v = d?.[key];
+ return v && typeof v === 'object' && 'value' in v && 'unit' in v ? (v as { value: number; unit: number }) : null;
+}
+
+// Drag a UI box edge/corner handle → its px width/height (UINode dimension). Screen
+// space: the box's on-screen size over its px value gives screen-px-per-UI-px, so the
+// drag tracks the cursor 1:1. Only px-unit sides resize (percent/auto have no fixed px);
+// writes go through the SAME setField + begin/endGesture channel the Inspector uses.
+function startUiResizeDrag(rt: number, edge: 'e' | 's' | 'se', e: ReactPointerEvent): void {
+ if (e.button !== 0) return;
+ const src = SceneModel.sourceFor(rt);
+ const rect0 = ViewportController.getEntityScreenRect(rt);
+ if (src == null || !rect0) return;
+ e.stopPropagation();
+ const w0 = uiDim(src, 'width');
+ const h0 = uiDim(src, 'height');
+ const sx = w0 && w0.unit === DimensionUnit.Px && w0.value > 0 ? rect0.w / w0.value : null;
+ const sy = h0 && h0.unit === DimensionUnit.Px && h0.value > 0 ? rect0.h / h0.value : null;
+ const startX = e.clientX;
+ const startY = e.clientY;
+ SceneCommands.beginGesture('Resize UI');
+ const onMove = (ev: PointerEvent) => {
+ if ((edge === 'e' || edge === 'se') && sx && w0) {
+ const nw = Math.max(0, Math.round(w0.value + (ev.clientX - startX) / sx));
+ SceneCommands.setField(src, 'UINode', 'width', 'dimension', { value: nw, unit: DimensionUnit.Px });
+ }
+ if ((edge === 's' || edge === 'se') && sy && h0) {
+ const nh = Math.max(0, Math.round(h0.value + (ev.clientY - startY) / sy));
+ SceneCommands.setField(src, 'UINode', 'height', 'dimension', { value: nh, unit: DimensionUnit.Px });
+ }
+ };
+ const onUp = () => {
+ SceneCommands.endGesture();
+ window.removeEventListener('pointermove', onMove);
+ window.removeEventListener('pointerup', onUp);
+ };
+ window.addEventListener('pointermove', onMove);
+ window.addEventListener('pointerup', onUp);
+}
+
// Drag a cone's edge handle → its spread angle (ParticleEmitter.shapeAngle, degrees).
// The cursor's angle off local +Y is the half-angle; shapeAngle is the full spread.
function startAngleHandleDrag(rt: number, e: ReactPointerEvent): void {
@@ -407,6 +478,15 @@ export function Viewport() {
const tilemapSelected = primaryId != null
&& !!SceneModel.entityBySource(primaryId)?.components.some((c) => c.type === 'TilemapLayer');
const inTilePaint = paintTool != null && tilemapSelected;
+ // Active editing mode drives the viewport badge and the design-resolution overlay.
+ // Derived from the pin + selection, so subscribe to the pin here.
+ useEditorMode((s) => s.pinned);
+ const mode = activeMode();
+ // Device-preview controls for the UI-mode design-resolution overlay (the rAF reads
+ // these via getState(); the subscriptions keep the device dropdown label current).
+ const device = useEditorMode((s) => s.device);
+ const orientation = useEditorMode((s) => s.orientation);
+ const showSafeArea = useEditorMode((s) => s.showSafeArea);
// WYSIWYG brush ghost: the actual stamp tiles, built once per stamp/atlas change and
// laid out at natural tile pixels; the rAF scales the container to the hovered
// footprint each frame (see the tile-preview block). Empty (null) → the plain box shows.
@@ -426,6 +506,8 @@ export function Viewport() {
const stageRef = useRef<HTMLDivElement>(null);
const playHostRef = useRef<HTMLDivElement>(null);
const gizmoRef = useRef<HTMLDivElement>(null);
+ const uiGizmoRef = useRef<HTMLDivElement>(null);
+ const designSvgRef = useRef<SVGSVGElement>(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);
@@ -563,6 +645,92 @@ export function Viewport() {
}
}
+ // UI resize gizmo: a single selected UINode gets edge/corner handles on its
+ // screen rect (getEntityScreenRect — the same rect the selection outline uses).
+ const uig = uiGizmoRef.current;
+ if (uig) {
+ const pid = useSelection.getState().selectedId;
+ const prt = ready && pid != null && selIds.length === 1 ? SceneModel.runtimeFor(pid) : undefined;
+ const uir = prt != null && EngineHost.world?.has(prt, UINode) ? ViewportController.getEntityScreenRect(prt) : null;
+ if (uir && showG) {
+ uig.style.transform = `translate(${uir.x}px, ${uir.y}px)`;
+ uig.style.width = `${uir.w}px`;
+ uig.style.height = `${uir.h}px`;
+ uig.style.opacity = '1';
+ } else {
+ uig.style.opacity = '0';
+ }
+ }
+
+ // Design-resolution overlay (UI mode): the Canvas' authored design frame, the
+ // simulated device's visible frame, its letterbox bars, and the safe-area inset,
+ // all projected from world each frame so they lock to pan/zoom.
+ const dsvg = designSvgRef.current;
+ if (dsvg) {
+ const ci = ready && showG && activeModeOverlays().designFrame ? ViewportController.canvasInfo() : null;
+ const ppu = ci ? ci.pixelsPerUnit : 100;
+ const des = ci
+ ? worldRectToScreen(ci.cx, ci.cy, ci.designResolution.x / (2 * ppu), ci.designResolution.y / (2 * ppu))
+ : null;
+ if (ci && des) {
+ dsvg.style.opacity = '1';
+ const ms = useEditorMode.getState();
+ const preset = RESOLUTION_PRESET_BY_ID[ms.device];
+ // Device visible frame: the design resolution fit into the simulated device's
+ // aspect per the Canvas scaleMode. The 'design' sentinel (w/h 0) = no device.
+ let dev = des;
+ if (preset.w > 0 && preset.h > 0) {
+ const [dw, dh] = ms.orientation === 'landscape' ? [preset.h, preset.w] : [preset.w, preset.h];
+ const deviceAspect = dw / dh;
+ const designAspect = ci.designResolution.x / ci.designResolution.y;
+ const halfH = computeEffectiveOrthoSize(
+ ci.designResolution.y / 2 / ppu, designAspect, deviceAspect, ci.scaleMode, ci.matchWidthOrHeight,
+ );
+ dev = worldRectToScreen(ci.cx, ci.cy, halfH * deviceAspect, halfH) ?? des;
+ }
+ setRectAttrs(dsvg.querySelector('.df-design'), des);
+ setRectAttrs(dsvg.querySelector('.df-device'), dev);
+ // Letterbox bars = the device frame minus the design frame, drawn only when the
+ // device contains the design (Expand / fixed-axis reveal); a crop shows no bars.
+ const lb = dsvg.querySelector('.df-letterbox') as SVGPathElement | null;
+ if (lb) {
+ const contains =
+ dev.w >= des.w - 0.5 && dev.h >= des.h - 0.5 && (dev.w > des.w + 0.5 || dev.h > des.h + 0.5);
+ if (contains) {
+ lb.setAttribute(
+ 'd',
+ `M${dev.x},${dev.y}h${dev.w}v${dev.h}h${-dev.w}Z M${des.x},${des.y}h${des.w}v${des.h}h${-des.w}Z`,
+ );
+ const bg = ci.backgroundColor;
+ lb.style.fill = `rgba(${Math.round(bg.r * 255)},${Math.round(bg.g * 255)},${Math.round(bg.b * 255)},0.55)`;
+ lb.style.opacity = '1';
+ } else {
+ lb.style.opacity = '0';
+ }
+ }
+ // Safe-area inset within the device frame (device px → screen px by the frame ratio).
+ const safe = dsvg.querySelector('.df-safe') as SVGRectElement | null;
+ if (safe) {
+ if (ms.showSafeArea && preset.safe && preset.w > 0) {
+ const [dwPx, dhPx] = ms.orientation === 'landscape' ? [preset.h, preset.w] : [preset.w, preset.h];
+ const sx = dev.w / dwPx;
+ const sy = dev.h / dhPx;
+ setRectAttrs(safe, {
+ x: dev.x + preset.safe.left * sx,
+ y: dev.y + preset.safe.top * sy,
+ w: dev.w - (preset.safe.left + preset.safe.right) * sx,
+ h: dev.h - (preset.safe.top + preset.safe.bottom) * sy,
+ });
+ safe.style.opacity = '1';
+ } else {
+ safe.style.opacity = '0';
+ }
+ }
+ } else {
+ dsvg.style.opacity = '0';
+ }
+ }
+
// The transform gizmo sits at the selection pivot (centroid or active-entity
// pivot per pivotMode), rotated to the active entity's axes in local space.
// Only for the move/rotate/scale tools — select shows just the outline.
@@ -1059,6 +1227,34 @@ export function Viewport() {
<Crosshair size={13} strokeWidth={1.9} />
<span className="val">{pivotMode === 'pivot' ? 'Pivot' : 'Center'}</span>
</button>
+ {mode.overlays?.designFrame && (
+ <>
+ <span className="ov-divider" />
+ <OvDropdown
+ icon={Smartphone}
+ label={<span className="val">{RESOLUTION_PRESET_BY_ID[device].label}</span>}
+ title="Preview Device (design-resolution fit)"
+ >
+ <div className="ovmenu-lbl">Device</div>
+ {RESOLUTION_PRESETS.map((p) => (
+ <DdRadio key={p.id} on={device === p.id} label={p.label} onClick={() => useEditorMode.getState().setDevice(p.id)} />
+ ))}
+ <div className="ovmenu-lbl">Orientation</div>
+ <DdRadio
+ on={orientation === 'landscape'}
+ label="Landscape"
+ onClick={() => orientation !== 'landscape' && useEditorMode.getState().toggleOrientation()}
+ />
+ <DdRadio
+ on={orientation === 'portrait'}
+ label="Portrait"
+ onClick={() => orientation !== 'portrait' && useEditorMode.getState().toggleOrientation()}
+ />
+ <div className="ovmenu-lbl">Overlay</div>
+ <DdCheck on={showSafeArea} label="Safe area" onClick={() => useEditorMode.getState().toggleSafeArea()} />
+ </OvDropdown>
+ </>
+ )}
</div>
</div>
@@ -1337,6 +1533,39 @@ export function Viewport() {
</div>
<div ref={tilePaintRef} className="viewport__tilepaint" aria-hidden="true" />
+ <svg ref={designSvgRef} className="viewport__design-svg" style={{ opacity: 0 }} aria-hidden="true">
+ <path className="df-letterbox" fillRule="evenodd" />
+ <rect className="df-device" />
+ <rect className="df-safe" />
+ <rect className="df-design" />
+ </svg>
+
+ <div ref={uiGizmoRef} className="viewport__ui-gizmo" style={{ opacity: 0 }}>
+ <span
+ className="uig-h uig-e"
+ onPointerDown={(e) => {
+ const p = useSelection.getState().selectedId;
+ const rt = p != null ? SceneModel.runtimeFor(p) : undefined;
+ if (rt != null) startUiResizeDrag(rt, 'e', e);
+ }}
+ />
+ <span
+ className="uig-h uig-s"
+ onPointerDown={(e) => {
+ const p = useSelection.getState().selectedId;
+ const rt = p != null ? SceneModel.runtimeFor(p) : undefined;
+ if (rt != null) startUiResizeDrag(rt, 's', e);
+ }}
+ />
+ <span
+ className="uig-h uig-se"
+ onPointerDown={(e) => {
+ const p = useSelection.getState().selectedId;
+ const rt = p != null ? SceneModel.runtimeFor(p) : undefined;
+ if (rt != null) startUiResizeDrag(rt, 'se', e);
+ }}
+ />
+ </div>
<div ref={gizmoRef} className="viewport__gizmo" aria-hidden="true">
<GizmoOverlay tool={tool} active={activeGizmoAxis} />
</div>
@@ -1369,8 +1598,11 @@ export function Viewport() {
/>
{perfVisible && <Perf id="viewport.perfhud"><PerfOverlay /></Perf>}
- {inTilePaint && paintTool && (
- <div className="viewport__tileflag">◧ Tile paint · {TILE_TOOL_LABEL[paintTool]}</div>
+ {mode.id !== 'scene' && (
+ <div className="viewport__tileflag">
+ ◧ {mode.label}
+ {inTilePaint && paintTool ? ` · ${TILE_TOOL_LABEL[paintTool]}` : ''}
+ </div>
)}
{isPlaying && <div className="viewport__playflag">● PLAY</div>}
</div>
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 0d643ecb8..b50dcc44f 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -12,7 +12,7 @@ import { EditorHistory } from '@/engine/EditorHistory';
import { expandScenePrefabs, collapseScenePrefabs } from '@/engine/PrefabInstance';
import { SceneCommands } from '@/engine/SceneCommands';
import { Boxes } from 'lucide-react';
-import { spritePrefab, type EntitySource } from '@/engine/entitySources';
+import { spritePrefab, setCanvasDesignSeed, type EntitySource } from '@/engine/entitySources';
import { setPrefabBaseResolver } from '@/engine/SceneQuery';
import { setUserSchemas, userSchema, setBitmaskSource, setEnumSource, type UserComponentSchema } from '@/engine/schema';
import { installSpineSync, type SpineTransport } from '@/engine/spineSync';
@@ -21,7 +21,7 @@ import { Toasts } from '@/store/Toasts';
import { confirmDiscard } from './discardGuard';
import { assetTypeOf } from '@/project/assetMeta';
import type { AssetType } from '@/types';
-import { resolveLayout, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type WorkspaceState } from './format';
+import { resolveLayout, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type WorkspaceState, type DesignResolution } from './format';
/** Pad/truncate collision-layer names to the 16 Box2D filter bits (layer 0 = Default). */
function normalizeLayers(layers?: string[]): string[] {
@@ -100,6 +100,8 @@ interface ProjectState {
features?: ProjectFeatures;
/** Persisted Package Project settings (last target/config/output). */
packaging?: ProjectPackaging;
+ /** Reference resolution new Canvas entities seed from; per-scene Canvas stays authoritative. */
+ designResolution?: DesignResolution;
/** The scene currently loaded into the world (project-relative path). */
currentScene: string | null;
}
@@ -155,6 +157,8 @@ class ProjectStoreImpl {
setBitmaskSource('collisionLayers', () => this.collisionLayerOptions());
// Render `layer` fields become a dropdown once the project names sorting layers.
setEnumSource('sortingLayers', () => this.sortingLayerOptions());
+ // New Canvas entities seed their design resolution from the project setting.
+ setCanvasDesignSeed(() => this.designResolution());
}
/** Read accessor so existing `this.state` reads stay unchanged after the move. */
@@ -262,6 +266,7 @@ class ProjectStoreImpl {
defaultScene: opened.manifest.defaultScene,
features: opened.manifest.features,
packaging: opened.manifest.packaging,
+ designResolution: opened.manifest.designResolution,
currentScene: null,
},
});
@@ -872,6 +877,29 @@ class ProjectStoreImpl {
}
}
+ /** Project reference resolution — the seed for new Canvas entities. Falls back to
+ * the engine's own Canvas default (1920×1080), not the old create-preset hardcode. */
+ designResolution(): DesignResolution {
+ return this.state?.designResolution ?? { width: 1920, height: 1080 };
+ }
+
+ /** Set the project reference resolution and persist to the manifest root. Mirrors
+ * {@link setRendering}; the value only seeds newly created Canvases. */
+ async setDisplay(patch: Partial<DesignResolution>): Promise<void> {
+ const st = this.state;
+ if (!st) return;
+ const designResolution: DesignResolution = { ...this.designResolution(), ...patch };
+ this.store.setState({ project: { ...st, designResolution } });
+ try {
+ const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;
+ raw.designResolution = designResolution;
+ await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');
+ } catch (e) {
+ Toasts.push('Failed to save design resolution', 'error');
+ console.error('[project] setDisplay write failed', e);
+ }
+ }
+
/** Persisted Package Project settings (last target/config/output), or {}. */
packagingSettings(): ProjectPackaging {
return this.state?.packaging ?? {};
diff --git a/desktop/src/settings/projectSettings.ts b/desktop/src/settings/projectSettings.ts
index 3f09d4f66..427314a33 100644
--- a/desktop/src/settings/projectSettings.ts
+++ b/desktop/src/settings/projectSettings.ts
@@ -10,6 +10,32 @@
import { settingsRegistry } from './registry';
import { ProjectStore } from '@/project/ProjectStore';
+// ── Display (design/reference resolution; seeds new Canvas entities) ──
+settingsRegistry.registerSection({ id: 'display', label: 'Display', category: 'project', order: 0 });
+
+settingsRegistry.register({
+ id: 'project.display.width',
+ type: 'number', scope: 'project', section: 'display', group: 'Design Resolution',
+ label: 'Width', suffix: 'px',
+ description: 'Reference resolution new Canvas entities are created at; each Canvas keeps its own value afterwards.',
+ default: 1920, min: 1, step: 1,
+ bind: {
+ get: () => ProjectStore.designResolution().width,
+ set: (v) => void ProjectStore.setDisplay({ width: Math.round(v) }),
+ },
+});
+
+settingsRegistry.register({
+ id: 'project.display.height',
+ type: 'number', scope: 'project', section: 'display', group: 'Design Resolution',
+ label: 'Height', suffix: 'px',
+ default: 1080, min: 1, step: 1,
+ bind: {
+ get: () => ProjectStore.designResolution().height,
+ set: (v) => void ProjectStore.setDisplay({ height: Math.round(v) }),
+ },
+});
+
// ── Physics (the enable flag = UE Plugins-Browser analog; gravity = Project Settings) ──
settingsRegistry.registerSection({ id: 'physics', label: 'Physics', category: 'project', order: 1 });
diff --git a/desktop/src/store/editorModeStore.ts b/desktop/src/store/editorModeStore.ts
new file mode 100644
index 000000000..7fd82af2a
--- /dev/null
+++ b/desktop/src/store/editorModeStore.ts
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file editorModeStore.ts — transient editor-mode UI state (never serialized).
+ * `pinned` is an explicit mode override that follows-selection when null;
+ * the device/orientation/safe-area fields drive the UI-mode design-resolution
+ * viewport preview (consumed by the Viewport overlay + device dropdown).
+ */
+import { create } from 'zustand';
+import type { EditorModeId } from '@/mode/editorModes';
+import type { DevicePresetId } from '@/mode/resolutionPresets';
+
+interface EditorModeState {
+ /** Explicit mode override; null ⇒ follow the selection-suggested mode. */
+ pinned: EditorModeId | null;
+ /** Simulated target device for the design-resolution preview ('design' = no letterbox). */
+ device: DevicePresetId;
+ orientation: 'portrait' | 'landscape';
+ showSafeArea: boolean;
+ setMode(id: EditorModeId): void;
+ clearPin(): void;
+ setDevice(id: DevicePresetId): void;
+ toggleOrientation(): void;
+ toggleSafeArea(): void;
+}
+
+export const useEditorMode = create<EditorModeState>((set) => ({
+ pinned: null,
+ device: 'design',
+ orientation: 'landscape',
+ showSafeArea: false,
+ setMode: (id) => set({ pinned: id }),
+ clearPin: () => set({ pinned: null }),
+ setDevice: (device) => set({ device }),
+ toggleOrientation: () => set((s) => ({ orientation: s.orientation === 'portrait' ? 'landscape' : 'portrait' })),
+ toggleSafeArea: () => set((s) => ({ showSafeArea: !s.showSafeArea })),
+}));
diff --git a/desktop/src/theme/chrome.css b/desktop/src/theme/chrome.css
index 359c4e145..c10bb7359 100644
--- a/desktop/src/theme/chrome.css
+++ b/desktop/src/theme/chrome.css
@@ -249,6 +249,7 @@
to { transform: translateY(-50%) scaleY(1); opacity: 1; }
}
.act-spacer { flex: 1; }
+.act-sep { width: 20px; height: 1px; background: var(--border); margin: 4px 0; flex-shrink: 0; }
/* ── Content Drawer (slides up over the workspace) ── */
.scrim {
diff --git a/desktop/src/theme/viewport.css b/desktop/src/theme/viewport.css
index fbed84236..0b2421b0b 100644
--- a/desktop/src/theme/viewport.css
+++ b/desktop/src/theme/viewport.css
@@ -105,6 +105,22 @@
.ovmenu-item.on .chk { background: var(--acc); border-color: var(--acc); color: var(--on-accent); }
.ovmenu-item .l { flex: 1; }
+/* UI resize gizmo: accent edge/corner handles laid over a selected UINode's screen
+ rect. Container is inert; only the handles take pointer events. */
+.viewport__ui-gizmo { position: absolute; top: 0; left: 0; pointer-events: none; z-index: 6; }
+.viewport__ui-gizmo .uig-h { position: absolute; pointer-events: auto; background: var(--acc); border: 1px solid var(--on-accent); box-sizing: border-box; border-radius: 1px; }
+.uig-e { right: -4px; top: 50%; width: 8px; height: 14px; transform: translateY(-50%); cursor: ew-resize; }
+.uig-s { bottom: -4px; left: 50%; width: 14px; height: 8px; transform: translateX(-50%); cursor: ns-resize; }
+.uig-se { right: -4px; bottom: -4px; width: 10px; height: 10px; cursor: nwse-resize; }
+
+/* Design-resolution overlay (UI mode): the authored design frame (solid accent), the
+ simulated device's visible frame (dashed), the letterbox bars (Canvas background
+ fill), and the safe-area inset (dotted). Inert; laid over the world each frame. */
+.viewport__design-svg { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; z-index: 5; overflow: visible; }
+.viewport__design-svg .df-design { fill: none; stroke: var(--acc); stroke-width: 1.5; }
+.viewport__design-svg .df-device { fill: none; stroke: var(--text-mute); stroke-width: 1; stroke-dasharray: 5 4; }
+.viewport__design-svg .df-safe { fill: none; stroke: var(--acc); stroke-width: 1; stroke-dasharray: 2 3; opacity: 0.6; }
+
/* perf widget (bottom-right) */
.vp-perf {
position: absolute;
diff --git a/desktop/src/tools/index.ts b/desktop/src/tools/index.ts
index 4ae320575..56ec4e99f 100644
--- a/desktop/src/tools/index.ts
+++ b/desktop/src/tools/index.ts
@@ -2,20 +2,23 @@
// 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.
+ * @brief Resolves the active viewport tool from the active editor mode. Tilemap
+ * mode routes to a paint tool (when one is set — it must not re-pick/select);
+ * every other mode routes to the transform tool (select/move/rotate/scale).
+ * The Viewport calls this per pointer-down and routes the stroke to it.
*/
import { useEditorStore } from '@/store/editorStore';
import { useTilemapPaint } from '@/store/tilemapPaintStore';
+import { activeMode } from '@/mode/activeMode';
import { TRANSFORM_TOOLS } from './transformTools';
import { TILE_TOOLS } from './tileTools';
-import { isTilePaintMode } from './tileMode';
import type { EditorTool } from './EditorTool';
export function resolveActiveTool(): EditorTool {
- if (isTilePaintMode()) return TILE_TOOLS[useTilemapPaint.getState().tool!];
+ if (activeMode().toolset === 'tilemap') {
+ const tool = useTilemapPaint.getState().tool;
+ if (tool) return TILE_TOOLS[tool];
+ }
return TRANSFORM_TOOLS[useEditorStore.getState().tool] ?? TRANSFORM_TOOLS.select;
}
diff --git a/desktop/src/tools/tileMode.ts b/desktop/src/tools/tileMode.ts
index f7e0b34ab..1207db7b6 100644
--- a/desktop/src/tools/tileMode.ts
+++ b/desktop/src/tools/tileMode.ts
@@ -20,6 +20,7 @@ import { SceneModel } from '@/engine/SceneModel';
import { useSelection } from '@/store/selectionStore';
import { useEditorStore } from '@/store/editorStore';
import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';
+import { activeMode } from '@/mode/activeMode';
import { copySelection, cutSelection, deleteSelection, pasteClipboard } from './tileClipboard';
import type { ToolMode } from '@/types';
@@ -30,9 +31,9 @@ export function isTilemapSelected(): boolean {
&& !!SceneModel.entityBySource(id)?.components.some((c) => c.type === 'TilemapLayer');
}
-/** True when a paint tool is active over a selected tilemap — i.e. clicks paint, not select. */
+/** True when a paint tool is active in tilemap mode — i.e. clicks paint, not select. */
export function isTilePaintMode(): boolean {
- return useTilemapPaint.getState().tool != null && isTilemapSelected();
+ return activeMode().toolset === 'tilemap' && useTilemapPaint.getState().tool != null;
}
/** The selected tilemap layer's authoring cell size, or null if none is selected. */
diff --git a/desktop/tests/editor-mode.test.ts b/desktop/tests/editor-mode.test.ts
new file mode 100644
index 000000000..7c58118d7
--- /dev/null
+++ b/desktop/tests/editor-mode.test.ts
@@ -0,0 +1,106 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The editor-mode registry + derivation (editorModes / activeMode). The mode
+ * is selection-derived with an optional explicit pin; it must reproduce the
+ * old implicit tilemap/transform behavior exactly (a tile tool wins ONLY when
+ * a tilemap is selected AND a paint tool is set), so resolveActiveTool stays
+ * byte-equivalent. SceneModel is mocked to drive the selection probe.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const model = vi.hoisted(() => ({
+ entity: null as null | { components: { type: string; data: unknown }[] },
+}));
+vi.mock('@/engine/SceneModel', () => ({
+ SceneModelImpl: class {},
+ SceneModel: {
+ subscribe: () => () => {},
+ entityBySource: (id: number) => (id === 1 ? model.entity : null),
+ },
+}));
+
+import { EDITOR_MODES, EDITOR_MODE_BY_ID } from '@/mode/editorModes';
+import { suggestedMode, activeMode } from '@/mode/activeMode';
+import { resolveActiveTool } from '@/tools';
+import { TILE_TOOLS } from '@/tools/tileTools';
+import { useSelection } from '@/store/selectionStore';
+import { useTilemapPaint } from '@/store/tilemapPaintStore';
+import { useEditorMode } from '@/store/editorModeStore';
+import { useEditorStore } from '@/store/editorStore';
+
+const withComponents = (...types: string[]) => {
+ model.entity = { components: types.map((type) => ({ type, data: {} })) };
+ useSelection.getState().select(1);
+};
+
+describe('editor-mode registry + derivation', () => {
+ beforeEach(() => {
+ model.entity = null;
+ useSelection.getState().select(1);
+ useTilemapPaint.getState().setTool(null);
+ useEditorMode.getState().clearPin();
+ useEditorStore.getState().setTool('move');
+ });
+
+ it('has unique ids and exactly one fallback mode (Scene, last, no suggestFor)', () => {
+ const ids = EDITOR_MODES.map((m) => m.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ const fallbacks = EDITOR_MODES.filter((m) => !m.suggestFor);
+ expect(fallbacks).toHaveLength(1);
+ expect(fallbacks[0].id).toBe('scene');
+ expect(EDITOR_MODES[EDITOR_MODES.length - 1].id).toBe('scene');
+ });
+
+ it('suggests the mode implied by the selection', () => {
+ withComponents('TilemapLayer');
+ expect(suggestedMode().id).toBe('tilemap');
+ withComponents('Canvas');
+ expect(suggestedMode().id).toBe('ui');
+ withComponents('UINode');
+ expect(suggestedMode().id).toBe('ui');
+ withComponents('Sprite');
+ expect(suggestedMode().id).toBe('scene');
+ model.entity = null; // nothing recognized selected
+ expect(suggestedMode().id).toBe('scene');
+ });
+
+ it('resolves the highest-priority mode when a selection matches several (tilemap over ui)', () => {
+ withComponents('TilemapLayer', 'Canvas');
+ expect(suggestedMode().id).toBe('tilemap');
+ });
+
+ it('an explicit pin overrides the suggestion; clearPin reverts to it', () => {
+ withComponents('TilemapLayer');
+ expect(activeMode().id).toBe('tilemap');
+ useEditorMode.getState().setMode('ui');
+ expect(activeMode().id).toBe('ui');
+ expect(EDITOR_MODE_BY_ID.ui.overlays?.designFrame).toBe(true);
+ useEditorMode.getState().clearPin();
+ expect(activeMode().id).toBe('tilemap');
+ });
+
+ it('resolveActiveTool routes to a paint tool ONLY in tilemap mode with a paint tool set', () => {
+ const tileTools = Object.values(TILE_TOOLS);
+
+ // tilemap selected, no paint tool → a transform tool, never a tile tool
+ withComponents('TilemapLayer');
+ useTilemapPaint.getState().setTool(null);
+ expect(tileTools).not.toContain(resolveActiveTool());
+
+ // tilemap selected + paint tool → that tile tool
+ useTilemapPaint.getState().setTool('brush');
+ expect(resolveActiveTool()).toBe(TILE_TOOLS.brush);
+
+ // non-tilemap selection with a paint tool still set → transform (paint can't leak out)
+ withComponents('Sprite');
+ useTilemapPaint.getState().setTool('brush');
+ expect(tileTools).not.toContain(resolveActiveTool());
+
+ // pinned away from tilemap while a tilemap is selected → transform (pin wins)
+ withComponents('TilemapLayer');
+ useTilemapPaint.getState().setTool('brush');
+ useEditorMode.getState().setMode('scene');
+ expect(tileTools).not.toContain(resolveActiveTool());
+ });
+});
diff --git a/desktop/tests/project-display.test.ts b/desktop/tests/project-display.test.ts
new file mode 100644
index 000000000..9ff888af7
--- /dev/null
+++ b/desktop/tests/project-display.test.ts
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Project Display settings + Canvas design-resolution seed. The project's
+ * reference resolution is a create-time seed for new Canvas entities (the
+ * per-scene Canvas component stays authoritative afterwards), injected into
+ * entitySources to avoid an entitySources ↔ ProjectStore import cycle.
+ */
+import { describe, it, expect, afterEach } from 'vitest';
+import '@/settings';
+import { settingsRegistry } from '@/settings/registry';
+import { ENTITY_SOURCES, setCanvasDesignSeed } from '@/engine/entitySources';
+import { ProjectStore } from '@/project/ProjectStore';
+
+async function canvasDesign(): Promise<{ x: number; y: number }> {
+ const src = ENTITY_SOURCES.find((s) => s.id === 'canvas')!;
+ const prefab = await src.build({ parent: null });
+ const canvas = prefab.entities[0].components.find((c) => c.type === 'Canvas')!.data as Record<string, unknown>;
+ return canvas.designResolution as { x: number; y: number };
+}
+
+describe('project Display settings + Canvas design-resolution seed', () => {
+ // ProjectStore wires this in its constructor; restore it so ordering can't leak a stub.
+ afterEach(() => setCanvasDesignSeed(() => ProjectStore.designResolution()));
+
+ it('registers a Display section with width/height design-resolution rows', () => {
+ expect(settingsRegistry.allSections().map((s) => s.id)).toContain('display');
+ const w = settingsRegistry.get('project.display.width');
+ const h = settingsRegistry.get('project.display.height');
+ expect(w?.type).toBe('number');
+ expect(w?.default).toBe(1920);
+ expect(h?.default).toBe(1080);
+ });
+
+ it('ProjectStore.designResolution() defaults to the engine Canvas default with no project open', () => {
+ expect(ProjectStore.designResolution()).toEqual({ width: 1920, height: 1080 });
+ });
+
+ it('the Canvas create source seeds designResolution from the injected project provider', async () => {
+ setCanvasDesignSeed(() => ({ width: 1280, height: 720 }));
+ expect(await canvasDesign()).toEqual({ x: 1280, y: 720 });
+ });
+
+ it('the Canvas seed falls back to 1920×1080 when no project resolution is set', async () => {
+ setCanvasDesignSeed(() => ProjectStore.designResolution());
+ expect(await canvasDesign()).toEqual({ x: 1920, y: 1080 });
+ });
+});
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index ad99278cb..04391e6ef 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -50,6 +50,8 @@ export { FollowTarget } from './camera/FollowTarget';
export type { FollowTargetData } from './camera/FollowTarget';
export type { CameraDirectorState } from './camera/CameraDirector';
export type { CameraPOV } from './camera/CameraPlugin';
+export { computeEffectiveOrthoSize, uiLayoutRect, EDITOR_VIEW_ENTITY } from './camera/uiLayoutRect';
+export type { CameraExtents, CanvasScale, WorldRect } from './camera/uiLayoutRect';
// =============================================================================
// Draw API