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
feat(editor): the viewport gets a perspective eye, for authoring 2.5D
esengine6ab8e1a87064
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex 8cc5e4512..8a5193a01 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -136,6 +136,17 @@ export function App() {return () => { unsubMode(); unsubEngine(); };}, []);+ // Same shape as the aspect sync above, and for the same reason: the store owns+ // the toggle a person clicks, EditorView is what the renderer reads, and a+ // fresh engine boots with a default-off view that has to be re-told.+ useEffect(() => {+ const apply = () => EngineHost.setViewPerspective(useEditorStore.getState().viewPerspective);+ apply();+ const unsubStore = useEditorStore.subscribe(apply);+ const unsubEngine = EngineHost.subscribe(apply);+ return () => { unsubStore(); unsubEngine(); };+ }, []);+// Route otherwise-silent renderer faults (rejected promises, uncaught errors)// into the Output Log + a rate-limited toast — LogStore only patches console.*.useEffect(() => installGlobalErrorHandlers(), []);diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex 29f51a69d..5d46d58d5 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -471,6 +471,13 @@ commands.register({isChecked: () => editor().coordSpace === 'local',run: () => editor().toggleCoordSpace(),});+commands.register({+ id: 'view.toggleViewPerspective',+ label: t('cmd.view.toggleViewPerspective'),+ category: t('cat.view'),+ isChecked: () => editor().viewPerspective,+ run: () => editor().toggleViewPerspective(),+});commands.register({id: 'view.togglePivotMode',label: t('cmd.view.togglePivotMode'),diff --git a/desktop/src/engine/EngineHost.ts b/desktop/src/engine/EngineHost.tsindex ed749275c..8cfa3e06d 100644--- a/desktop/src/engine/EngineHost.ts+++ b/desktop/src/engine/EngineHost.ts@@ -348,6 +348,17 @@ class EngineHostImpl {if (view) view.uiPreviewAspect = aspect;}+ /**+ * Whether the editor's own eye is a perspective one — the only way to look at+ * 2.5D content while authoring it. Editor-only and never serialized, like the+ * rest of EditorView; the shipped game sees its own scene camera. No-op+ * pre-boot, and re-applied on each boot since a fresh EditorView defaults off.+ */+ setViewPerspective(on: boolean): void {+ const view = this.getResource(EditorView);+ if (view) view.perspective = on;+ }+/** The active (or first) scene camera's center + ortho half-height, for seeding. */private readSceneCamera(): { x: number; y: number; orthoSize: number } | null {const world = this.world;diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.tsindex 5073b58f8..162000f29 100644--- a/desktop/src/engine/ViewportController.ts+++ b/desktop/src/engine/ViewportController.ts@@ -6,6 +6,7 @@ import {ParticleEmitter, OneWayPlatform, RigidBody,RevoluteJoint, DistanceJoint, PrismaticJoint, WeldJoint, WheelJoint, MotorJoint,UINode, UICameraInfo, screenToUiWorld, uiWorldToScreen, uiPickAllWorld, type UICameraData,+ type EditorViewData,Marker,TilemapLayer, TilemapAPI, decodeTilemapChunks, CHUNK_SIZE, tileCollisionOutlines,tileCellCenter, tileCellOutline, isNonOrthogonal,@@ -77,10 +78,29 @@ function cameraView(): CameraViewLike | null {// Navigation mutates this in place; the camera system renders + resolves// screen<->world through it in edit mode (see sdk EditorView / CameraPlugin), so// panning/zooming/framing never touches — or dirties — the scene's game Camera.-function editorView(): { active: boolean; x: number; y: number; orthoSize: number } | null {+function editorView(): EditorViewData | null {return EngineHost.getResource(EditorView) ?? null;}+/**+ * The quantity zoom scales, which differs by projection but behaves the same.+ *+ * Orthographically it is the half-height of the view box. In perspective it is+ * the camera's distance — and on the z = 0 plane, where 2D content lives, the+ * visible extent is proportional to distance exactly as it is to orthoSize. That+ * is what lets one zoom formula serve both instead of two that drift.+ */+const ZOOM_MIN = 8;+const ZOOM_MAX = 40000;+function zoomAmount(view: EditorViewData): number {+ return view.perspective ? view.distance : view.orthoSize;+}+function setZoomAmount(view: EditorViewData, value: number): void {+ const v = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, value));+ if (view.perspective) view.distance = v;+ else view.orthoSize = v;+}+/** DOM pointer position → engine screen space (buffer px, y-up). */function clientToScreen(clientX: number, clientY: number): { sx: number; sy: number } | null {const canvas = EngineHost.canvas;@@ -375,7 +395,7 @@ export const ViewportController = {zoomBy(factor: number): void {const view = editorView();if (!view) return;- view.orthoSize = Math.max(8, Math.min(40000, view.orthoSize * factor));+ setZoomAmount(view, zoomAmount(view) * factor);},/** Zoom about the cursor: the world point under (clientX, clientY) stays put, so@@ -387,9 +407,9 @@ export const ViewportController = {const view = editorView();if (!view) return;const w = this.canvasToWorld(clientX, clientY); // current matrices — read BEFORE zoom- const next = Math.max(8, Math.min(40000, view.orthoSize * factor));- const applied = next / view.orthoSize; // clamped factor- view.orthoSize = next;+ const before = zoomAmount(view);+ setZoomAmount(view, before * factor);+ const applied = zoomAmount(view) / before; // clamped factorif (w) {view.x += (w.x - view.x) * (1 - applied);view.y += (w.y - view.y) * (1 - applied);diff --git a/desktop/src/i18n/messages/commands.ts b/desktop/src/i18n/messages/commands.tsindex 92bf10a38..002eee5ba 100644--- a/desktop/src/i18n/messages/commands.ts+++ b/desktop/src/i18n/messages/commands.ts@@ -55,6 +55,7 @@ export const commandMessages = defineMessages({'cmd.view.toggleColliders': { en: 'Show Physics Gizmos', zh: '显示物理 Gizmo' },'cmd.view.toggleTileCollision': { en: 'Show Tile Collision', zh: '显示瓦片碰撞' },'cmd.view.toggleCoordSpace': { en: 'Local Axes', zh: '局部坐标轴' },+ 'cmd.view.toggleViewPerspective': { en: 'Perspective View', zh: '透视视图' },'cmd.view.togglePivotMode': { en: 'Pivot (vs Center)', zh: '轴心(而非中心)' },'cmd.view.toggleSnapping': { en: 'Snapping', zh: '吸附' },'cmd.view.toggleMinimap': { en: 'Minimap', zh: '小地图' },diff --git a/desktop/src/i18n/messages/viewport.ts b/desktop/src/i18n/messages/viewport.tsindex 3e0598e41..82dc2f3af 100644--- a/desktop/src/i18n/messages/viewport.ts+++ b/desktop/src/i18n/messages/viewport.ts@@ -98,6 +98,9 @@ export const viewportMessages = defineMessages({},'vp.pivot.pivot': { en: 'Pivot', zh: '轴心' },'vp.pivot.center': { en: 'Center', zh: '中心' },+ 'vp.projectionTitle': { en: 'Editor viewport projection — perspective makes depth visible for 2.5D authoring. Does not change the game camera.', zh: '编辑器视口投影——透视可在编辑 2.5D 时看见深度。不影响游戏相机。' },+ 'vp.proj.ortho': { en: '2D', zh: '2D' },+ 'vp.proj.perspective': { en: '3D', zh: '3D' },// — Design-resolution + device-preview dropdowns (UI mode) —'vp.designResTitle': {diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex 730c7319e..2d79175b1 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -4,7 +4,7 @@ import { memo, useEffect, useMemo, useRef, useState, useSyncExternalStore } fromimport type { PointerEvent as ReactPointerEvent, DragEvent as ReactDragEvent } from 'react';import {MousePointer2, Move, RotateCw, Scale3d, Grid3x3, Frame,- Camera, Loader2, TriangleAlert, Lightbulb, Sparkles, Globe, Crosshair, Monitor, Magnet, Axis3d, Hexagon, MapPin, type LucideIcon,+ Camera, Loader2, TriangleAlert, Lightbulb, Sparkles, Globe, Crosshair, Monitor, Magnet, Axis3d, Hexagon, MapPin, Box, type LucideIcon,AlignStartVertical, AlignCenterVertical, AlignEndVertical,AlignStartHorizontal, AlignCenterHorizontal, AlignEndHorizontal,AlignHorizontalDistributeCenter, AlignVerticalDistributeCenter,@@ -690,6 +690,7 @@ export function Viewport() {const activeGizmoAxis = useEditorStore((s) => s.activeGizmoAxis);const coordSpace = useEditorStore((s) => s.coordSpace);const pivotMode = useEditorStore((s) => s.pivotMode);+ const viewPerspective = useEditorStore((s) => s.viewPerspective);const snapping = useEditorStore((s) => s.snapping);const snapStep = useEditorStore((s) => s.snapStep);const snapAngle = useEditorStore((s) => s.snapAngle);@@ -2027,6 +2028,18 @@ export function Viewport() {<Crosshair size={13} strokeWidth={1.9} /><span className="val">{pivotMode === 'pivot' ? t('vp.pivot.pivot') : t('vp.pivot.center')}</span></button>+ {/* The editor's own eye. Orthographic is the 2D default; perspective is+ what makes depth visible while authoring 2.5D. It changes only this+ view — the Game view always shows the scene's own camera. */}+ <button+ type="button"+ className={`ovbtn${viewPerspective ? ' active' : ''}`}+ title={t('vp.projectionTitle')}+ onClick={() => commands.run('view.toggleViewPerspective')}+ >+ <Box size={13} strokeWidth={1.9} />+ <span className="val">{viewPerspective ? t('vp.proj.perspective') : t('vp.proj.ortho')}</span>+ </button>{/* Screen controls — available in EVERY editor mode. Design resolution editsthe scene Canvas when present, else the project reference resolution; thedevice dropdown simulates a real screen regardless of any UI layer. */}diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.tsindex a59a9562f..c15bd041d 100644--- a/desktop/src/store/editorStore.ts+++ b/desktop/src/store/editorStore.ts@@ -74,6 +74,9 @@ interface EditorState {/** Gizmo pivot: the selection's centroid (center), or the active entity's own pivot. */pivotMode: 'center' | 'pivot';toggleCoordSpace: () => void;+ /** Editor viewport projection: a perspective eye for authoring 2.5D. */+ viewPerspective: boolean;+ toggleViewPerspective: () => void;togglePivotMode: () => void;/** Axis of the gizmo handle currently being dragged (null = none) — drives the* handle's active highlight. Set by the transform tool on grab, cleared on release. */@@ -196,6 +199,8 @@ export const useEditorStore = create<EditorState>((set) => ({coordSpace: 'world',pivotMode: 'center',toggleCoordSpace: () => set((s) => ({ coordSpace: s.coordSpace === 'world' ? 'local' : 'world' })),+ viewPerspective: false,+ toggleViewPerspective: () => set((s) => ({ viewPerspective: !s.viewPerspective })),togglePivotMode: () => set((s) => ({ pivotMode: s.pivotMode === 'center' ? 'pivot' : 'center' })),activeGizmoAxis: null,setActiveGizmoAxis: (activeGizmoAxis) => set({ activeGizmoAxis }),diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex fb1d57db5..e4c848a08 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -2669,7 +2669,10 @@ ResourceDef<EditorViewData>## EditorViewData — interface```active: boolean+distance: number+fov: numberorthoSize: number+perspective: booleanuiPreviewAspect: numberx: numbery: numberdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex bff739286..15f41aa8f 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -2677,7 +2677,10 @@ ResourceDef<EditorViewData>## EditorViewData — interface```active: boolean+distance: number+fov: numberorthoSize: number+perspective: booleanuiPreviewAspect: numberx: numbery: numberdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 923e8b03c..ce8c7d1eb 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -2664,7 +2664,10 @@ ResourceDef<EditorViewData>## EditorViewData — interface```active: boolean+distance: number+fov: numberorthoSize: number+perspective: booleanuiPreviewAspect: numberx: numbery: numberdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex f91da0210..d7552c104 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -2664,7 +2664,10 @@ ResourceDef<EditorViewData>## EditorViewData — interface```active: boolean+distance: number+fov: numberorthoSize: number+perspective: booleanuiPreviewAspect: numberx: numbery: numberdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex db61d0176..cc6b86f7f 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -2664,7 +2664,10 @@ ResourceDef<EditorViewData>## EditorViewData — interface```active: boolean+distance: number+fov: numberorthoSize: number+perspective: booleanuiPreviewAspect: numberx: numbery: numberdiff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.tsindex 911453b09..3f5c98f28 100644--- a/sdk/src/camera/CameraPlugin.ts+++ b/sdk/src/camera/CameraPlugin.ts@@ -305,12 +305,16 @@ export function editorCameraInfo(isActive: true,x: view.x,y: view.y,- z: 0,+ // Perspective needs the camera to stand somewhere: it is the distance that+ // makes content near or far, where orthographically nothing depends on z.+ z: view.perspective ? view.distance : 0,rotation: 0,- projection: ProjectionType.Orthographic,+ projection: view.perspective ? ProjectionType.Perspective : ProjectionType.Orthographic,orthoSize: view.orthoSize,- fov: 0,- near: 0,+ fov: view.fov,+ // A perspective projection divides by z, so near must be > 0 — the+ // orthographic path builds a symmetric [-far, far] box and ignores it.+ near: view.perspective ? 0.1 : 0,far: 100000,viewport: { x: 0, y: 0, z: 1, w: 1 },clearFlags: ClearFlags.ColorAndDepth,diff --git a/sdk/src/camera/EditorView.ts b/sdk/src/camera/EditorView.tsindex b502b5bf4..c013f0e00 100644--- a/sdk/src/camera/EditorView.ts+++ b/sdk/src/camera/EditorView.ts@@ -26,6 +26,27 @@ export interface EditorViewData {y: number;/** Half-height of the view in world units (zoom; smaller = more zoomed in). */orthoSize: number;+ /**+ * `false` (default) is the 2D view: an orthographic projection where zoom is+ * `orthoSize` and depth cannot be seen. `true` previews the scene the way a+ * perspective game camera would — the only way to look at 2.5D content while+ * authoring it.+ *+ * The view keeps its OWN projection rather than following the scene's camera,+ * which is the same choice UE and Unity make: an orthographic view of a+ * perspective scene is a working mode (a top-down or side elevation), not a+ * mismatch to be corrected. What the game will look like is the Game view's+ * job; this is the editor's own eye.+ */+ perspective: boolean;+ /** Vertical field of view in degrees, used only when `perspective`. */+ fov: number;+ /**+ * Camera distance along +z, used only when `perspective`. This is what zoom+ * moves in that mode — a perspective view cannot zoom by widening a box, and+ * changing the fov instead would alter the projection the user is previewing.+ */+ distance: number;/*** Aspect ratio the editor lays UI out against, so the editor previews how UI adapts* on a simulated device: `> 0` fits the design resolution into this aspect (the device@@ -35,6 +56,10 @@ export interface EditorViewData {uiPreviewAspect: number;}-export const DEFAULT_EDITOR_VIEW: EditorViewData = { active: false, x: 0, y: 0, orthoSize: 360, uiPreviewAspect: 0 };+export const DEFAULT_EDITOR_VIEW: EditorViewData = {+ active: false, x: 0, y: 0, orthoSize: 360, uiPreviewAspect: 0,+ // Off by default: an existing project opens on exactly the view it always had.+ perspective: false, fov: 60, distance: 1000,+};export const EditorView = defineResource<EditorViewData>({ ...DEFAULT_EDITOR_VIEW }, 'EditorView');diff --git a/sdk/tests/editor-view.test.ts b/sdk/tests/editor-view.test.tsindex 723cd9711..b06ca6a49 100644--- a/sdk/tests/editor-view.test.ts+++ b/sdk/tests/editor-view.test.ts@@ -54,3 +54,60 @@ describe('EditorView camera', () => {);});});++// =============================================================================+// Perspective preview (2.5D authoring)+// =============================================================================++import { DEFAULT_EDITOR_VIEW } from '../src/camera/EditorView';++const view = (over: Partial<typeof DEFAULT_EDITOR_VIEW>) =>+ ({ ...DEFAULT_EDITOR_VIEW, active: true, ...over });++/** Projects a world point INCLUDING its z — the whole point of a perspective view. */+function ndc3(vp: Float32Array, x: number, y: number, z: number) {+ const cx = vp[0] * x + vp[4] * y + vp[8] * z + vp[12];+ const cy = vp[1] * x + vp[5] * y + vp[9] * z + vp[13];+ const cw = vp[3] * x + vp[7] * y + vp[11] * z + vp[15];+ return { x: cx / cw, y: cy / cw };+}++describe('EditorView perspective preview', () => {+ // The default has to be the view every existing project already had, to the bit.+ it('is off by default, and the orthographic view is untouched', () => {+ expect(DEFAULT_EDITOR_VIEW.perspective).toBe(false);+ const a = editorCameraInfo(view({ x: 100, y: 50, orthoSize: 300 }), 800, 600, []);+ const b = editorCameraInfo({ active: true, x: 100, y: 50, orthoSize: 300 } as never, 800, 600, []);+ expect(Array.from(a.viewProjection)).toEqual(Array.from(b.viewProjection));+ });++ // What an orthographic view fundamentally cannot show: two things the same size+ // at different depths are the same size on screen. Here they must not be.+ it('makes depth visible — nearer content projects larger', () => {+ const cam = editorCameraInfo(view({ perspective: true, distance: 1000, fov: 60 }), 800, 600, []);++ const near = ndc3(cam.viewProjection, 100, 0, 0);+ const far = ndc3(cam.viewProjection, 100, 0, -900);++ // Same world x, different depth ⇒ different screen x. The nearer one is+ // further from the centre, which IS the perspective divide.+ expect(Math.abs(near.x)).toBeGreaterThan(Math.abs(far.x) * 1.5);+ });++ it('zooms by moving the camera, not by widening a box', () => {+ const close = editorCameraInfo(view({ perspective: true, distance: 500 }), 800, 600, []);+ const away = editorCameraInfo(view({ perspective: true, distance: 2000 }), 800, 600, []);++ // The same world point fills more of the screen from closer up.+ expect(Math.abs(ndc3(close.viewProjection, 100, 0, 0).x))+ .toBeGreaterThan(Math.abs(ndc3(away.viewProjection, 100, 0, 0).x));+ });++ it('leaves orthoSize meaningless in perspective, and fov in charge', () => {+ const narrow = editorCameraInfo(view({ perspective: true, fov: 30 }), 800, 600, []);+ const wide = editorCameraInfo(view({ perspective: true, fov: 90 }), 800, 600, []);+ // A wider field sees more world, so a given point sits closer to the centre.+ expect(Math.abs(ndc3(narrow.viewProjection, 100, 0, 0).x))+ .toBeGreaterThan(Math.abs(ndc3(wide.viewProjection, 100, 0, 0).x));+ });+});