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(ui): transform drag deltas through full parent matrices
yhh1814652d5370
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8cf357b73..e08872191 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Pointer dragging follows sheared parent transforms.** World deltas use the inverse of the parent's complete flat transform for both local positions and UI insets, preserving pointer alignment through non-uniformly scaled, rotated hierarchies. Singular transforms end capture without modifying hidden coordinates. Per-App matrix scratch is allocated lazily, reused across frames and released with capture on plugin cleanup; cores without matrix access retain their existing fallback.+- **Web audio startup failures release pooled nodes and keep resumes retryable.** Source creation, configuration and start errors return the acquired node before propagating the error, preventing failed plays from growing the pool. Failed resumes disconnect the rejected source while preserving the paused voice and playback offset; successful retries commit playback state only after startup succeeds.- **Tilemap rectangle fills clip safely across integer coordinate bounds.** Finite layers intersect the requested rectangle before visiting cells, avoiding work outside the map. Wide endpoint arithmetic preserves unsigned extents and clips infinite writes to representable coordinates; empty intersections return immediately. Negative chunk division avoids signed overflow, preserving tile storage and chunk import at both integer edges.diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex af0d7eb47..46aa63063 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -3146,6 +3146,7 @@ parent: DocumentEntityId | null## DragPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voiddependencies: "uiInteraction"[]name: "drag"static new (): DragPlugindiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 77ebf7a01..06c8f83af 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -3154,6 +3154,7 @@ parent: DocumentEntityId | null## DragPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voiddependencies: "uiInteraction"[]name: "drag"static new (): DragPlugindiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex bf4b86850..dfc5c5b99 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -3141,6 +3141,7 @@ parent: DocumentEntityId | null## DragPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voiddependencies: "uiInteraction"[]name: "drag"static new (): DragPlugindiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 90815168d..d6607c949 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -3141,6 +3141,7 @@ parent: DocumentEntityId | null## DragPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voiddependencies: "uiInteraction"[]name: "drag"static new (): DragPlugindiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 3e650e062..4aaa141a3 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -3141,6 +3141,7 @@ parent: DocumentEntityId | null## DragPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voiddependencies: "uiInteraction"[]name: "drag"static new (): DragPlugindiff --git a/sdk/src/ui/input/drag.ts b/sdk/src/ui/input/drag.tsindex dbb9fbf4a..b753ff175 100644--- a/sdk/src/ui/input/drag.ts+++ b/sdk/src/ui/input/drag.ts@@ -10,7 +10,7 @@ import { defineSystem, Schedule } from '../../ecs/system';import { Res } from '../../ecs/resource';import { Input } from '../../input/input';import { primaryPointerCancellationVersion } from '../../input/pointerCancellation';-import { engineApi } from '../../ecs/bridge/engineApi';+import { engineApi, type EngineApi } from '../../ecs/bridge/engineApi';import type { InputState } from '../../input/input';import type { Entity } from '../../types';import type { World } from '../../ecs/world';@@ -33,8 +33,9 @@ function worldToLocalDelta(world: World,entity: Entity,dx: number,- dy: number-): { x: number; y: number } {+ dy: number,+ readParent?: (parent: Entity, dx: number, dy: number) => { x: number; y: number } | null | undefined,+): { x: number; y: number } | null {if (!world.has(entity, Parent)) {return { x: dx, y: dy };}@@ -43,6 +44,8 @@ function worldToLocalDelta(if (!world.valid(parentEntity) || !world.has(parentEntity, Transform)) {return { x: dx, y: dy };}+ const resolved = readParent?.(parentEntity, dx, dy);+ if (resolved !== undefined) return resolved;const parentWt = world.get(parentEntity, Transform) as TransformData;const sx = parentWt.worldScale.x !== 0 ? parentWt.worldScale.x : 1;const sy = parentWt.worldScale.y !== 0 ? parentWt.worldScale.y : 1;@@ -84,7 +87,22 @@ export class DragPlugin implements Plugin {name = PluginName.Drag;dependencies = [PluginName.UIInteraction];+ private readonly cleanups_ = new Map<App, () => void>();++ cleanup(app?: App): void {+ if (app) {+ const cleanup = this.cleanups_.get(app);+ this.cleanups_.delete(app);+ cleanup?.();+ } else {+ const cleanups = [...this.cleanups_.values()];+ this.cleanups_.clear();+ for (const cleanup of cleanups) cleanup();+ }+ }+build(app: App): void {+ this.cleanup(app);registerComponent('Draggable', Draggable);registerComponent('DragState', DragState);@@ -92,6 +110,34 @@ export class DragPlugin implements Plugin {const events = app.getResource(UIEvents) as UIEventQueue;const engine = engineApi(app);const registry = world.getCppRegistry();+ let matrixOwner: EngineApi | null = null;+ let matrixPointer = 0;+ let matrixHeap: Float32Array | null = null;+ const releaseMatrix = (): void => {+ const pointer = matrixPointer, owner = matrixOwner;+ matrixPointer = 0;+ matrixOwner = null;+ matrixHeap = null;+ if (pointer) owner?._free?.(pointer);+ };+ const readParentDelta = (parent: Entity, dx: number, dy: number): { x: number; y: number } | null | undefined => {+ const api = engineApi(app), registry = world.getCppRegistry();+ if (!api?.transform_copyFlatRenderMatrix || !api.HEAPU8 || !api._malloc || !api._free || !registry) return undefined;+ if (matrixOwner !== api) { releaseMatrix();matrixOwner = api; }+ if (!matrixPointer) {+ matrixPointer = api._malloc(64);+ if (!matrixPointer) throw new Error('Could not allocate drag transform scratch.');+ }+ if (!api.transform_copyFlatRenderMatrix(registry, parent, matrixPointer)) return null;+ const heap = api.HEAPU8;+ if (matrixHeap?.buffer !== heap.buffer) matrixHeap = new Float32Array(heap.buffer);+ const at = (heap.byteOffset + matrixPointer) / 4;+ const a = matrixHeap[at], b = matrixHeap[at + 1], c = matrixHeap[at + 4], d = matrixHeap[at + 5];+ const det = a * d - b * c;+ if (!Number.isFinite(det) || det === 0) return null;+ const x = (d * dx - c * dy) / det, y = (a * dy - b * dx) / det;+ return Number.isFinite(x) && Number.isFinite(y) ? { x, y } : null;+ };const eligible = (entity: Entity): boolean => world.isEntityActive(entity)&& !world.isDestructionPending(entity)&& world.has(entity, Draggable) && world.get(entity, Draggable).enabled@@ -114,6 +160,10 @@ export class DragPlugin implements Plugin {if (started) events.emit(entity, 'drag_end');};+ this.cleanups_.set(app, () => {+ try { stopCapture(); } finally { releaseMatrix(); }+ });+app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([Res(Input), Res(UICameraInfo), Res(ScreenLayout), Res(ScreenOverlay)],(input: InputState, camera: UICameraData, layout: ScreenLayoutData,@@ -226,6 +276,8 @@ export class DragPlugin implements Plugin {const prevX = dragState.currentWorldPos.x;const prevY = dragState.currentWorldPos.y;+ const localDelta = worldToLocalDelta(world, activeEntity, newWorldX - prevX, newWorldY - prevY, readParentDelta);+ if (!localDelta) { stopCapture();return; }world.update(activeEntity, DragState, (d) => {d.deltaWorld = { x: newWorldX - prevX, y: newWorldY - prevY };d.currentWorldPos = { x: newWorldX, y: newWorldY };@@ -239,20 +291,12 @@ export class DragPlugin implements Plugin {// Nudge the CSS-box absolute insets (the layout input), so// the dragged position survives the next layout pass.const node = world.get(activeEntity, UINode) as UINodeData;- const localDelta = worldToLocalDelta(- world, activeEntity,- dragState.deltaWorld.x, dragState.deltaWorld.y- );const baseL = node.insetLeft.unit === 0 ? node.insetLeft.value : 0;const baseT = node.insetTop.unit === 0 ? node.insetTop.value : 0;node.insetLeft = px(baseL + localDelta.x);node.insetTop = px(baseT - localDelta.y); // inset top is y-downworld.insert(activeEntity, UINode, node);} else if (world.has(activeEntity, Transform)) {- const localDelta = worldToLocalDelta(- world, activeEntity,- dragState.deltaWorld.x, dragState.deltaWorld.y- );world.update(activeEntity, Transform, (t) => {t.position.x += localDelta.x;t.position.y += localDelta.y;diff --git a/sdk/tests/ui-drag-cancel-wasm.test.ts b/sdk/tests/ui-drag-cancel-wasm.test.tsindex a678ec921..f444bf57b 100644--- a/sdk/tests/ui-drag-cancel-wasm.test.ts+++ b/sdk/tests/ui-drag-cancel-wasm.test.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { App, flushPendingRegistrations } from '../src/app/app';import { AppContext, setDefaultContext } from '../src/ecs/context';import { Canvas, Disabled, Draggable, Transform } from '../src/ecs/component';@@ -18,7 +18,7 @@ import type { Entity } from '../src/types';import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';describe.skipIf(!HAS_WASM)('drag cancellation on real WASM', () => {- let engine: ESEngineModule, registry: CppRegistry, app: App, input: InputState, entity: Entity;+ let engine: ESEngineModule, registry: CppRegistry, app: App, input: InputState, entity: Entity, dragPlugin: DragPlugin;beforeAll(async () => { engine = await loadWasmModule(); });beforeEach(() => {setDefaultContext(new AppContext()); registry = new engine.Registry();@@ -26,11 +26,11 @@ describe.skipIf(!HAS_WASM)('drag cancellation on real WASM', () => {input = new InputState(); app.insertResource(Input, input);app.insertResource(UIEvents, new UIEventQueue());app.insertResource(UICameraInfo, { ...UICameraInfo._default, valid: true, vpW: 100, vpH: 100 });- new DragPlugin().build(app); flushPendingRegistrations(app);+ dragPlugin = new DragPlugin();dragPlugin.build(app); flushPendingRegistrations(app);entity = app.world.spawn(); app.world.insert(entity, Transform); app.world.insert(entity, Draggable);app.world.insert(entity, UIInteraction, { hovered: true });});- afterEach(() => { app.quit({ keepRenderer: true }); registry.delete(); });+ afterEach(() => { dragPlugin.cleanup(app);app.quit({ keepRenderer: true }); registry.delete(); });async function step(x: number) {app.getResource(UICameraInfo).worldMouseX = x;await app.tick(1 / 60); input.clearFrameState();@@ -40,6 +40,45 @@ describe.skipIf(!HAS_WASM)('drag cancellation on real WASM', () => {expect(app.world.get(entity, DragState).isDragging).toBe(false);expect(app.world.get(entity, Transform).position.x).toBeCloseTo(20);}+ it('follows world-pointer movement through a sheared parent hierarchy', async () => {+ const grand = app.world.spawn(),parent = app.world.spawn();+ app.world.insert(grand, Transform, { scale: { x: 2, y: 1, z: 1 } });+ app.world.insert(parent, Transform, { rotation: { x: 0, y: 0, z: Math.sin(Math.PI / 8), w: Math.cos(Math.PI / 8) } });+ app.world.setParent(parent, grand);app.world.setParent(entity, parent);+ engine.transform_update(registry);+ input.noteMouseDown(0);await step(0);+ app.getResource(UICameraInfo).worldMouseY = 0;await step(20);+ engine.transform_update(registry);+ const moved = app.world.get(entity, Transform).worldPosition;+ expect(moved.x).toBeCloseTo(20, 4);expect(moved.y).toBeCloseTo(0, 4);+ expect(app.world.get(entity, DragState).isDragging).toBe(true);+ });++ it('ends a captured drag when its parent collapses instead of changing hidden local coordinates', async () => {+ const parent = app.world.spawn();app.world.insert(parent, Transform);app.world.setParent(entity, parent);+ engine.transform_update(registry);await drag();+ const before = app.world.get(entity, Transform).position.x;+ app.world.update(parent, Transform, t => { t.scale.x = 0; });engine.transform_update(registry);+ await step(100);+ expect(app.world.get(entity, DragState).isDragging).toBe(false);+ expect(app.world.get(entity, Transform).position.x).toBe(before);+ });++ it('reuses one parent-matrix allocation and releases it on cleanup', async () => {+ const parent = app.world.spawn();app.world.insert(parent, Transform);app.world.setParent(entity, parent);+ engine.transform_update(registry);+ const malloc = vi.spyOn(engine, '_malloc'),free = vi.spyOn(engine, '_free');+ try {+ input.noteMouseDown(0);await step(0);await step(20);await step(30);await step(40);+ const indices = malloc.mock.calls.flatMap((args, i) => args[0] === 64 ? [i] : []);+ expect(indices).toHaveLength(1);+ const pointer = malloc.mock.results[indices[0]].value;+ dragPlugin.cleanup(app);dragPlugin.cleanup(app);+ expect(app.world.get(entity, DragState).isDragging).toBe(false);+ expect(free.mock.calls.filter(args => args[0] === pointer)).toHaveLength(1);+ } finally { malloc.mockRestore();free.mockRestore(); }+ });+it('claimed release ends capture after the UI sample consumes cancellation', async () => {await drag(); const off = inputRouter.setEditorHandler({ onPointerUp: () => true });try { inputEventCallbacks(input).onPointerUp(0); } finally { off(); }diff --git a/sdk/tests/ui-drag-plugin.test.ts b/sdk/tests/ui-drag-plugin.test.tsindex 988dd48f5..c7bd7b71a 100644--- a/sdk/tests/ui-drag-plugin.test.ts+++ b/sdk/tests/ui-drag-plugin.test.ts@@ -9,7 +9,7 @@* observable state (DragState.isDragging, Transform.position) rather than* the emitted events.*/-import { describe, it, expect, beforeEach, vi } from 'vitest';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { flushPendingRegistrations } from '../src/app/app';import type { App } from '../src/app/app';import { Disabled, Transform } from '../src/ecs/component';@@ -27,6 +27,7 @@ import { bootMockApp } from './helpers/mockApp';import type { Entity } from '../src/types';let app: App;+afterEach(() => dragPlugin.cleanup(app));beforeEach(() => {app = bootMockApp().app;diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex a637430c5..c411b1d66 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(ui): transform drag deltas through full parent matrices':+ { note: 'Pointer dragging follows sheared parent transforms.' },'fix(audio): release failed starts and preserve paused retries':{ note: 'Web audio startup failures release pooled nodes and keep resumes retryable.' },'fix(tilemap): clip fills and preserve signed coordinate edges':