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
fix(editor): place the gizmo at the entity's world position, not its local offset
yhhe21bae4495bd
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex 8644a0490..7b9207e00 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -198,7 +198,7 @@ function nudgeSelection(ux: number, uy: number, big: boolean): void {SceneCommands.transact('Nudge', () => {for (const sid of ids) {const rt = SceneModel.runtimeFor(sid);- const pos = rt != null ? ViewportController.getEntityXY(rt) : null;+ const pos = rt != null ? ViewportController.getEntityWorldXY(rt) : null;if (pos) SceneCommands.setEntityXY(sid, pos.x + ux * step, pos.y + uy * step);}});diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 73e1e8536..43af14cf7 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -5,6 +5,7 @@ import { TilemapAPI } from 'esengine';import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types';import { EditorHistory, EditorHistoryImpl } from './EditorHistory';import { SceneModel, SceneModelImpl } from './SceneModel';+import { ViewportController } from './ViewportController';import { expandInstance } from './PrefabInstance';import { setEntityClipboard, getEntityClipboard, remapClipboardEntities } from './entityClipboard';import {@@ -273,11 +274,19 @@ export class SceneCommandsImpl {);}- /** Move an entity to a world position (keeps Z). Undoable like any field edit. */+ /**+ * Move an entity to a world position (keeps local Z). Undoable like any field+ * edit. `Transform.position` is parent-local, so a parented entity's world+ * target is re-expressed in its parent's live world frame before the write —+ * viewport tools speak world space; the model invariant stays local.+ */setEntityXY(sourceId: EntityId, x: number, y: number): void {+ const entity = this.model.entityBySource(sourceId);const pos = this.modelFieldValue(sourceId, 'Transform', 'position') as { z?: number } | undefined;- if (pos === undefined && !this.model.entityBySource(sourceId)) return;- this.setField(sourceId, 'Transform', 'position', 'vec3', [x, y, pos?.z ?? 0]);+ if (pos === undefined && !entity) return;+ const parentRt = entity?.parent != null ? this.model.runtimeFor(entity.parent) : undefined;+ const local = ViewportController.worldToParentLocalXY(parentRt, x, y);+ this.setField(sourceId, 'Transform', 'position', 'vec3', [local.x, local.y, pos?.z ?? 0]);}// — Undoable entity lifecycle (model ops; the Reconciler re-spawns/-despawns) —diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.tsindex 394023a21..73680ce71 100644--- a/desktop/src/engine/ViewportController.ts+++ b/desktop/src/engine/ViewportController.ts@@ -16,6 +16,7 @@ import {rectsIntersect,screenAABB,clamp,+ worldToLocal2D,} from './viewportMath';// World half-size of the pick/outline box for entities without renderable bounds@@ -83,7 +84,8 @@ export const ViewportController = {* `size × scale` about their pivot; entities without renderable bounds (cameras,* lights, empties) get a fixed icon box so they're still selectable. The center is* the geometric center, which for an off-center pivot orbits the rotation pivot- * (= transform position).+ * (= transform position). Reads the parent-composed world transform — the same+ * fields the renderer draws from — so parented entities pick where they render.*/entityBounds(id: EntityId): OBB | null {const world = EngineHost.world;@@ -91,7 +93,7 @@ export const ViewportController = {// UI nodes are screen-space; they're picked via the UI hit-test, not a world OBB.if (world.has(id, UINode)) return null;const t = world.get(id, Transform);- const rot = quatAngleZ(t.rotation as { w: number; x: number; y: number; z: number });+ const rot = quatAngleZ(t.worldRotation as { w: number; x: number; y: number; z: number });let w = ICON_WORLD_HALF * 2;let h = ICON_WORLD_HALF * 2;@@ -99,8 +101,8 @@ export const ViewportController = {let py = 0.5;if (world.has(id, Sprite)) {const sp = world.get(id, Sprite);- w = sp.size.x * t.scale.x;- h = sp.size.y * t.scale.y;+ w = sp.size.x * t.worldScale.x;+ h = sp.size.y * t.worldScale.y;px = sp.pivot?.x ?? 0.5;py = sp.pivot?.y ?? 0.5;}@@ -109,8 +111,8 @@ export const ViewportController = {const c = Math.cos(rot);const s = Math.sin(rot);return {- cx: t.position.x + ox * c - oy * s,- cy: t.position.y + ox * s + oy * c,+ cx: t.worldPosition.x + ox * c - oy * s,+ cy: t.worldPosition.y + ox * s + oy * c,hw: Math.abs(w) / 2,hh: Math.abs(h) / 2,rot,@@ -185,11 +187,45 @@ export const ViewportController = {return out;},- getEntityXY(id: EntityId): { x: number; y: number } | null {+ /**+ * The entity's world-space position — parent-composed, the same value the+ * renderer places it at. For UI nodes this is the laid-out box center (the+ * Yoga pass writes local `position`; the transform pass composes it), so the+ * gizmo lands on the element, not on its parent-relative offset.+ */+ getEntityWorldXY(id: EntityId): { x: number; y: number } | null {const world = EngineHost.world;if (!world || !world.valid(id) || !world.has(id, Transform)) return null;const t = world.get(id, Transform);- return { x: t.position.x, y: t.position.y };+ return { x: t.worldPosition.x, y: t.worldPosition.y };+ },++ /** The entity's world rotation about Z (radians) — drives the local-space gizmo frame. */+ getEntityWorldAngleRad(id: EntityId): number {+ const world = EngineHost.world;+ if (!world || !world.valid(id) || !world.has(id, Transform)) return 0;+ const t = world.get(id, Transform);+ return quatAngleZ(t.worldRotation as { w: number; x: number; y: number; z: number });+ },++ /**+ * A world point re-expressed in `parentId`'s live world frame — the local+ * `Transform.position` a child at that world spot must hold. No/invalid+ * parent ⇒ the point is already root-local.+ */+ worldToParentLocalXY(parentId: EntityId | null | undefined, wx: number, wy: number): { x: number; y: number } {+ const world = EngineHost.world;+ if (parentId == null || !world || !world.valid(parentId) || !world.has(parentId, Transform)) {+ return { x: wx, y: wy };+ }+ const t = world.get(parentId, Transform);+ return worldToLocal2D(wx, wy, {+ x: t.worldPosition.x,+ y: t.worldPosition.y,+ rot: quatAngleZ(t.worldRotation as { w: number; x: number; y: number; z: number }),+ sx: t.worldScale.x,+ sy: t.worldScale.y,+ });},/** A UI-camera world point → CSS px relative to the canvas (UI is screen-space). */@@ -325,8 +361,8 @@ export const ViewportController = {const halfH = c.orthoSize ?? 360;const aspect = canvas.height > 0 ? canvas.width / canvas.height : 1;const halfW = halfH * aspect;- const x = t.position.x;- const y = t.position.y;+ const x = t.worldPosition.x;+ const y = t.worldPosition.y;const center = this.worldToClient(x, y);if (!center) return null;const corners = [@@ -369,13 +405,13 @@ export const ViewportController = {type: number; color: { r: number; g: number; b: number }; radius: number;direction: { x: number; y: number }; outerAngle: number;};- const center = this.worldToClient(t.position.x, t.position.y);+ const center = this.worldToClient(t.worldPosition.x, t.worldPosition.y);if (!center) return null;// Point (0) / Spot (3) have a falloff radius; project a world-radius offset to CSS px.let radiusPx = 0;if (l.type === 0 || l.type === 3) {- const edge = this.worldToClient(t.position.x + l.radius, t.position.y);+ const edge = this.worldToClient(t.worldPosition.x + l.radius, t.worldPosition.y);if (edge) radiusPx = Math.hypot(edge.x - center.x, edge.y - center.y);}// Directional (1) / Spot (3) point along `direction`; flip world-Y to screen space. A Spotdiff --git a/desktop/src/engine/viewportMath.ts b/desktop/src/engine/viewportMath.tsindex 66785a57d..9d798659e 100644--- a/desktop/src/engine/viewportMath.ts+++ b/desktop/src/engine/viewportMath.ts@@ -49,6 +49,31 @@ export function pointInOBB(px: number, py: number, b: OBB): boolean {return Math.abs(lx) <= b.hw && Math.abs(ly) <= b.hh;}+/** A 2D world frame: translation, Z rotation (radians), per-axis scale. */+export interface Frame2D {+ x: number;+ y: number;+ rot: number;+ sx: number;+ sy: number;+}++/**+ * A world-space point re-expressed in `frame`'s local coordinates — the inverse+ * of the engine's TRS compose (world = T + R(rot)·(S·local)), so+ * local = S⁻¹·R(−rot)·(world − T). A zero scale axis passes through undivided+ * (a degenerate frame has no inverse; don't explode to Infinity).+ */+export function worldToLocal2D(wx: number, wy: number, frame: Frame2D): { x: number; y: number } {+ const dx = wx - frame.x;+ const dy = wy - frame.y;+ const c = Math.cos(-frame.rot);+ const s = Math.sin(-frame.rot);+ const rx = dx * c - dy * s;+ const ry = dx * s + dy * c;+ return { x: frame.sx ? rx / frame.sx : rx, y: frame.sy ? ry / frame.sy : ry };+}+/** Whether two client rects overlap (touching edges count as overlap). */export function rectsIntersect(a: ClientRect, b: ClientRect): boolean {return a.x <= b.x + b.w && b.x <= a.x + a.w && a.y <= b.y + b.h && b.y <= a.y + a.h;diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex 552388c57..1e89c16cd 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -442,7 +442,7 @@ export function Viewport() {? SceneModel.entityBySource(sid)?.components.find((c) => c.type === 'TilemapLayer'): undefined;const cs = layer?.data as { cellSize?: { x: number; y: number } } | undefined;- const origin = ready && rt != null ? ViewportController.getEntityXY(rt) : null;+ const origin = ready && rt != null ? ViewportController.getEntityWorldXY(rt) : null;if (tsel && cs?.cellSize && origin) {const x0 = Math.min(tsel.x0, tsel.x1);const y0 = Math.min(tsel.y0, tsel.y1);diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.tsindex 9c5167707..fe0eb0dce 100644--- a/desktop/src/tools/tileTools.ts+++ b/desktop/src/tools/tileTools.ts@@ -27,7 +27,7 @@ import type { EditorTool, PointerInput } from './EditorTool';export 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;+ const ep = rt != null ? ViewportController.getEntityWorldXY(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) };diff --git a/desktop/src/tools/transformTools.ts b/desktop/src/tools/transformTools.tsindex f3431d9b3..1b953cf0e 100644--- a/desktop/src/tools/transformTools.ts+++ b/desktop/src/tools/transformTools.ts@@ -76,15 +76,30 @@ function canvasOrigin(): { left: number; top: number } | null {function readTarget(sourceId: EntityId): Target | null {const rtId = SceneModel.runtimeFor(sourceId);if (rtId == null) return null;- const pos = ViewportController.getEntityXY(rtId);+ const pos = ViewportController.getEntityWorldXY(rtId);if (!pos) return null;const rotDeg = (SceneQuery.getFieldValue(sourceId, 'Transform', 'rotation') as number) ?? 0;const sc = (SceneQuery.getFieldValue(sourceId, 'Transform', 'scale') as number[]) ?? [1, 1, 1];return { sourceId, start: { x: pos.x, y: pos.y, rotDeg, sx: sc[0] ?? 1, sy: sc[1] ?? 1, sz: sc[2] ?? 1 } };}+/**+ * Drop ids whose ancestor is also selected: transforming the ancestor already+ * carries its subtree, so transforming the descendant too would apply the+ * gesture twice (once directly, once through the parent).+ */+function pruneDescendants(ids: readonly EntityId[]): EntityId[] {+ const set = new Set(ids);+ return ids.filter((id) => {+ for (let p = SceneModel.entityBySource(id)?.parent; p != null; p = SceneModel.entityBySource(p)?.parent) {+ if (set.has(p)) return false;+ }+ return true;+ });+}+function captureTargets(ids: readonly EntityId[]): Target[] {- return ids.map(readTarget).filter((t): t is Target => t !== null);+ return pruneDescendants(ids).map(readTarget).filter((t): t is Target => t !== null);}/** Selection centroid = mean of the live world positions of `ids`. */@@ -93,7 +108,7 @@ function pivotOf(ids: readonly EntityId[]): Pt | null {for (const sid of ids) {const rtId = SceneModel.runtimeFor(sid);if (rtId == null) continue;- const pos = ViewportController.getEntityXY(rtId);+ const pos = ViewportController.getEntityWorldXY(rtId);if (pos) pts.push(pos);}return pts.length ? groupPivot(pts) : null;@@ -105,12 +120,12 @@ function primaryOf(ids: readonly EntityId[]): EntityId | null {return primary != null && ids.includes(primary) ? primary : (ids[0] ?? null);}-/** The active entity's world rotation in radians (drives local-axis frame). */+/** The active entity's world rotation in radians (drives the local-axis frame —+ * the on-screen orientation is the parent-composed rotation, not the local one). */function primaryRotationRad(ids: readonly EntityId[]): number {const id = primaryOf(ids);- if (id == null) return 0;- const deg = (SceneQuery.getFieldValue(id, 'Transform', 'rotation') as number) ?? 0;- return (deg * Math.PI) / 180;+ const rt = id != null ? SceneModel.runtimeFor(id) : null;+ return rt != null ? ViewportController.getEntityWorldAngleRad(rt) : 0;}/**@@ -122,7 +137,7 @@ export function selectionPivot(ids: readonly EntityId[]): Pt | null {if (useEditorStore.getState().pivotMode === 'pivot') {const id = primaryOf(ids);const rt = id != null ? SceneModel.runtimeFor(id) : null;- const pos = rt != null ? ViewportController.getEntityXY(rt) : null;+ const pos = rt != null ? ViewportController.getEntityWorldXY(rt) : null;if (pos) return pos;}return pivotOf(ids);@@ -143,7 +158,7 @@ export function gizmoScreenAngleRad(ids: readonly EntityId[]): number {function altDuplicateTargets(ids: readonly EntityId[]): { targets: Target[]; pivot: Pt | null } {const targets: Target[] = [];const pts: Pt[] = [];- for (const sid of ids) {+ for (const sid of pruneDescendants(ids)) {const t = readTarget(sid);if (!t) continue;const copy = SceneCommands.duplicateEntity(sid);diff --git a/desktop/tests/transform-tool.test.ts b/desktop/tests/transform-tool.test.tsindex 160fde224..3fb1e440b 100644--- a/desktop/tests/transform-tool.test.ts+++ b/desktop/tests/transform-tool.test.ts@@ -23,7 +23,8 @@ vi.mock('@/engine/ViewportController', () => ({ViewportController: {canvasToWorld: (x: number, y: number) => ({ x, y }), // identity: world == client pxworldToClient: (x: number, y: number) => ({ x, y }),- getEntityXY: (rt: number) => h.pos.get(rt) ?? { x: 0, y: 0 },+ getEntityWorldXY: (rt: number) => h.pos.get(rt) ?? { x: 0, y: 0 },+ getEntityWorldAngleRad: () => 0,pickEntity: () => h.pick.entity,pickEntitiesAt: () => (h.pick.stack ?? (h.pick.entity != null ? [h.pick.entity] : [])),pickInRect: () => h.pick.rect,@@ -43,7 +44,12 @@ vi.mock('@/engine/SceneQuery', () => ({},}));vi.mock('@/engine/SceneModel', () => ({- SceneModel: { runtimeFor: (s: number) => s, sourceFor: (r: number) => r, subscribe: () => {} },+ SceneModel: {+ runtimeFor: (s: number) => s,+ sourceFor: (r: number) => r,+ entityBySource: () => undefined, // no hierarchy in these tests+ subscribe: () => {},+ },}));import { TRANSFORM_TOOLS } from '@/tools/transformTools';diff --git a/desktop/tests/viewport-math.test.ts b/desktop/tests/viewport-math.test.tsindex 031dd6404..93dcedc45 100644--- a/desktop/tests/viewport-math.test.ts+++ b/desktop/tests/viewport-math.test.ts@@ -15,6 +15,7 @@ import {screenAABB,snapTo,clamp,+ worldToLocal2D,} from '@/engine/viewportMath';const box = (cx: number, cy: number, hw: number, hh: number, rot = 0): OBB => ({ cx, cy, hw, hh, rot });@@ -95,3 +96,31 @@ describe('snapTo / clamp', () => {expect(clamp(99, 0, 10)).toBe(10);});});++describe('worldToLocal2D', () => {+ it('identity frame passes the point through', () => {+ expect(worldToLocal2D(3, 4, { x: 0, y: 0, rot: 0, sx: 1, sy: 1 })).toEqual({ x: 3, y: 4 });+ });++ it('inverts translation', () => {+ expect(worldToLocal2D(13, 24, { x: 10, y: 20, rot: 0, sx: 1, sy: 1 })).toEqual({ x: 3, y: 4 });+ });++ it('round-trips the TRS compose (world = T + R·(S·local))', () => {+ const f = { x: 10, y: -5, rot: Math.PI / 3, sx: 2, sy: 0.5 };+ const local = { x: 3, y: -7 };+ const c = Math.cos(f.rot);+ const s = Math.sin(f.rot);+ const wx = f.x + local.x * f.sx * c - local.y * f.sy * s;+ const wy = f.y + local.x * f.sx * s + local.y * f.sy * c;+ const back = worldToLocal2D(wx, wy, f);+ expect(back.x).toBeCloseTo(local.x, 9);+ expect(back.y).toBeCloseTo(local.y, 9);+ });++ it('a zero scale axis passes through undivided instead of exploding', () => {+ const p = worldToLocal2D(5, 6, { x: 0, y: 0, rot: 0, sx: 0, sy: 2 });+ expect(p.x).toBe(5);+ expect(p.y).toBe(3);+ });+});