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(text): isolate App glyph caches and release owned pages
yhhef75c8db3937
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 77bb3424f..33b738b56 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,8 +14,12 @@ published separately; it ships inside the editor.## [Unreleased]+## [0.83.0] - 2026-10-14+### Fixed+- **Text atlases belong to each App and release their pages on exit.** Preview restarts and separate runtime instances rasterize their own glyphs instead of reusing foreign texture IDs. Cleanup clears cached geometry, releases all owned pages and removes their restore callbacks without deleting a newer owner's registration.+- **SDK text follows the full parent transform and skips collapsed labels.** Bitmap and SDF labels copy the engine's complete matrix instead of reconstructing decomposed TRS, retaining shear and mirrors. The shared Web/native bridge rejects known zero-area labels before atlas creation or layout, uses one reusable scratch matrix per render pass and handles childless roots without a stale matrix cache. Legacy cores retain their existing fallback.- **Collapsed 2D hierarchies skip geometry and recover reliably.** Transform composition propagates authored zero-area state through planar rotations and transformless groups, preventing floating-point residue from reviving degenerate boxes. Sprite, UI, native bitmap text, picking and empty scissor/stencil subtrees share the guard. Valid tiny spans and children that regain area through a 3D tilt remain available; hidden bitmap runs skip font layout and submission.@@ -14263,7 +14267,8 @@ not kept before this file was introduced — see the Git history at`github.com/esengine/estella` for the full commit-level record since the firstcommit on 2026-01-25.-[Unreleased]: https://github.com/esengine/estella/compare/v0.82.0...HEAD+[Unreleased]: https://github.com/esengine/estella/compare/v0.83.0...HEAD+[0.83.0]: https://github.com/esengine/estella/compare/v0.82.0...v0.83.0[0.82.0]: https://github.com/esengine/estella/compare/v0.81.0...v0.82.0[0.81.0]: https://github.com/esengine/estella/compare/v0.80.0...v0.81.0[0.80.0]: https://github.com/esengine/estella/compare/v0.79.0...v0.80.0diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 56083c4e0..58f0c0899 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -8749,6 +8749,7 @@ width: number## TextPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voidname: stringstatic new (): TextPluginstatic prototype: TextPlugindiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 40b5b5ec7..cfadedcf8 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -8962,6 +8962,7 @@ width: number## TextPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voidname: stringstatic new (): TextPluginstatic prototype: TextPlugindiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 6b9c9dd12..df483c4f3 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -8744,6 +8744,7 @@ width: number## TextPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voidname: stringstatic new (): TextPluginstatic prototype: TextPlugindiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 48329769a..5591eb80b 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -9037,6 +9037,7 @@ width: number## TextPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voidname: stringstatic new (): TextPluginstatic prototype: TextPlugindiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 5facc1e8d..cff5da43e 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -8751,6 +8751,7 @@ width: number## TextPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voidname: stringstatic new (): TextPluginstatic prototype: TextPlugindiff --git a/sdk/src/runtime/runtimeAssets.ts b/sdk/src/runtime/runtimeAssets.tsindex 112417611..46f354969 100644--- a/sdk/src/runtime/runtimeAssets.ts+++ b/sdk/src/runtime/runtimeAssets.ts@@ -8,7 +8,7 @@* drives the same load path). Kept in its own module so neither the* runtime loader nor the spine loader has to import the other.*/-import { TextureContent, type ESEngineModule } from '../wasm';+import { TextureContent, type ESEngineModule, type CppResourceManager } from '../wasm';import { samplesAsSrgb } from '../ecs/env';import type { Backend } from '../asset/Backend';import type { ParsedTextureImportSettings } from '../asset/textureImportSettings';@@ -153,8 +153,9 @@ export function createTextureFromPixels(content: TextureContent,flipY: boolean = true,params?: TextureParams,+ owner?: CppResourceManager,): number {- const rm = requireResourceManager();+ const rm = owner ?? requireResourceManager();// Format code 2 = sRGB-encoded color (linear pipeline); 1 = plain RGBA8.const format = samplesAsSrgb(params?.srgb) ? 2 : 1;// Native path: no wasm heap — the ResourceManager uploads the bytes itself.@@ -194,9 +195,10 @@ export function updateTextureSubregion(width: number,height: number,pixels: Uint8Array,+ owner?: CppResourceManager,): void {if (width <= 0 || height <= 0 || pixels.length === 0) return;- const rm = requireResourceManager();+ const rm = owner ?? requireResourceManager();// Native byte path (no wasm heap); web embind lacks it and takes the heap path.if (rm.updateTextureSubregionFromBytes) {rm.updateTextureSubregionFromBytes(handle, x, y, width, height, pixels);diff --git a/sdk/src/ui/text/atlas-page-store.ts b/sdk/src/ui/text/atlas-page-store.tsindex 312a6fd9e..d29674889 100644--- a/sdk/src/ui/text/atlas-page-store.ts+++ b/sdk/src/ui/text/atlas-page-store.ts@@ -9,13 +9,15 @@*/import { TextureContent, type ESEngineModule } from '../../wasm';import { createTextureFromPixels, updateTextureSubregion } from '../../runtime/runtimeAssets';-import { provideTextureContent, requireResourceManager } from '../../wasm/resourceManager';+import { provideTextureContent, requireResourceManager, textureRefill, withdrawTextureContent,+ evictTextureDimensions, getResourceManager, type TextureRefill } from '../../wasm/resourceManager';import type { AtlasPageStore } from './glyph-atlas';export class EngineAtlasPageStore implements AtlasPageStore {// pageId is the GL texture id (what the batch binds); uploads need the engine// handle, so keep the mapping.- private readonly handleByGlId = new Map<number, number>();+ private readonly handleByGlId = new Map<number, { handle: number; refill: TextureRefill }>();+ private readonly owner = requireResourceManager();/** `module` is the wasm-heap marshalling vehicle; null on the native* (embedded-Dawn) core, whose ResourceManager takes the bytes directly. */@@ -31,24 +33,36 @@ export class EngineAtlasPageStore implements AtlasPageStore {TextureContent.GlyphPage,/* flipY */ false,{ filterMode: 'linear', wrapMode: 'clamp' },+ this.owner,);// Repainting on demand instead of the device keeping a copy: a page is// 4 MiB of wasm heap at the default size, for an event most sessions never see.- provideTextureContent(handle, () => {+ const refill: TextureRefill = () => {const page = new Uint8Array(size * size * 4);paint(page);- updateTextureSubregion(this.module, handle, 0, 0, size, size, page);+ updateTextureSubregion(this.module, handle, 0, 0, size, size, page, this.owner);return true;- });+ };+ provideTextureContent(handle, refill);// The batch binds by GL texture id (mirrors how spine resolves its atlas// pages); submitTextBatch gets this id as the page id.- const glId = requireResourceManager().getTextureGLId(handle);- this.handleByGlId.set(glId, handle);+ const glId = this.owner.getTextureGLId(handle);+ this.handleByGlId.set(glId, { handle, refill });return glId;}uploadSubRegion(pageId: number, x: number, y: number, w: number, h: number, pixels: Uint8Array): void {- const handle = this.handleByGlId.get(pageId) ?? pageId;- updateTextureSubregion(this.module, handle, x, y, w, h, pixels);+ const handle = this.handleByGlId.get(pageId)?.handle;+ if (handle === undefined) return;+ updateTextureSubregion(this.module, handle, x, y, w, h, pixels, this.owner);+ }++ releasePage(pageId: number): void {+ const entry = this.handleByGlId.get(pageId);+ if (!entry) return;+ this.handleByGlId.delete(pageId);+ if (textureRefill(entry.handle) === entry.refill) withdrawTextureContent(entry.handle);+ if (getResourceManager() === this.owner) evictTextureDimensions(entry.handle);+ this.owner.releaseTexture(entry.handle);}}diff --git a/sdk/src/ui/text/glyph-atlas.ts b/sdk/src/ui/text/glyph-atlas.tsindex 16a4ad2b6..1b3ce5b9a 100644--- a/sdk/src/ui/text/glyph-atlas.ts+++ b/sdk/src/ui/text/glyph-atlas.ts@@ -57,6 +57,8 @@ export interface AtlasPageStore {createPage(size: number, paint: (pixels: Uint8Array) => void): number;/** Upload `pixels` into the [x,y,w,h] sub-rect of page `pageId`. */uploadSubRegion(pageId: number, x: number, y: number, w: number, h: number, pixels: Uint8Array): void;+ /** Release an owned page. Optional for stores whose page lifetime is external. */+ releasePage?(pageId: number): void;}/** A cached glyph's atlas location (normalized UVs) + metrics. */@@ -127,6 +129,21 @@ export class GlyphAtlas {/** Number of atlas pages currently allocated. */get pageCount(): number { return this.pages.length; }+ /** Release all pages and cached glyphs; repeated cleanup has no effect. */+ dispose(): void {+ const pages = this.pages.splice(0);+ this.packers.length = 0;+ this.placements.length = 0;+ this.cache.clear();+ this.mute_.clear();+ this.generation_++;+ const errors: unknown[] = [];+ for (const page of pages) {+ try { this.store.releasePage?.(page); } catch (error) { errors.push(error); }+ }+ if (errors.length) throw new Error(`Failed to release glyph atlas pages: ${errors.map(String).join('; ')}`);+ }+/*** Bumped only when a change can alter the atlas coordinates of glyphs that* are already placed — i.e. a bitmap content-scale change (glyphs re-rasterizediff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.tsindex b3a7c1689..fb9f8c4d4 100644--- a/sdk/src/ui/text/plugin.ts+++ b/sdk/src/ui/text/plugin.ts@@ -88,13 +88,37 @@ interface TextDomainState {export class TextPlugin implements Plugin {name = 'text';- // One pair per DOMAIN: a bitmap atlas is rasterized at ONE content scale, and- // the two ask for different ones the moment a camera stops being the screen.- // Lazy, so text in only one domain pays for one pair.- private readonly world_: TextDomainState = { bitmap: null, sdf: null };- private readonly screen_: TextDomainState = { bitmap: null, sdf: null };- private readonly matrix_ = new Float32Array(16);- private matrixHeap_: Float32Array | null = null;+ private readonly states_ = new WeakMap<App, {+ world: TextDomainState;+ screen: TextDomainState;+ matrix: Float32Array;+ matrixHeap: Float32Array | null;+ }>();++ private stateFor(app: App) {+ let state = this.states_.get(app);+ if (!state) {+ state = {+ world: { bitmap: null, sdf: null },+ screen: { bitmap: null, sdf: null },+ matrix: new Float32Array(16), matrixHeap: null,+ };+ this.states_.set(app, state);+ }+ return state;+ }++ cleanup(app?: App): void {+ if (!app) return;+ const state = this.states_.get(app);+ if (!state) return;+ this.states_.delete(app);+ const errors: unknown[] = [];+ for (const renderer of [state.world.bitmap, state.world.sdf, state.screen.bitmap, state.screen.sdf]) {+ try { renderer?.dispose(); } catch (error) { errors.push(error); }+ }+ if (errors.length) throw new Error(`Failed to release text resources: ${errors.map(String).join('; ')}`);+ }build(app: App): void {registerComponent('Text', Text);@@ -137,6 +161,7 @@ export class TextPlugin implements Plugin {* spelling of that rule in TS is a second rule.*/private drawDomain(app: App, screen: boolean): void {+ const appState = this.stateFor(app);const api = engineApi(app);if (!api?.transform_copyFlatRenderMatrix || !api.HEAPU8 || !api._malloc || !api._free) {this.drawDomainWithMatrix(app, screen);@@ -150,15 +175,16 @@ export class TextPlugin implements Plugin {if (!pointer) throw new Error('Could not allocate text transform scratch.');if (!api.transform_copyFlatRenderMatrix!(registry, entity, pointer)) return false;const heap = api.HEAPU8!;- if (this.matrixHeap_?.buffer !== heap.buffer) this.matrixHeap_ = new Float32Array(heap.buffer);+ if (appState.matrixHeap?.buffer !== heap.buffer) appState.matrixHeap = new Float32Array(heap.buffer);const offset = (heap.byteOffset + pointer) / 4;- for (let i = 0; i < 16; i++) this.matrix_[i] = this.matrixHeap_[offset + i]!;+ for (let i = 0; i < 16; i++) appState.matrix[i] = appState.matrixHeap[offset + i]!;return true;});});}private drawDomainWithMatrix(app: App, screen: boolean, readMatrix?: (entity: number) => boolean): void {+ const appState = this.stateFor(app);const world = app.world;const registry = world.getCppRegistry() as CppRegistry;// Through engineApi, not app.wasmModule: a device has no wasm module, and@@ -174,7 +200,7 @@ export class TextPlugin implements Plugin {const contentScale = screen? this.screenContentScale(app, dpr): this.worldContentScale(app, dpr);- const state = screen ? this.screen_ : this.world_;+ const state = screen ? appState.screen : appState.world;const seen = new Set<number>();for (const e of world.getEntitiesWithComponents([Text, Transform])) {@@ -196,7 +222,7 @@ export class TextPlugin implements Plugin {resolveTextRenderMode(t.renderMode, tr.worldScale.x),contentScale,);- if (!readMatrix) composeTRS(this.matrix_, tr.worldPosition, tr.worldRotation, tr.worldScale);+ if (!readMatrix) composeTRS(appState.matrix, tr.worldPosition, tr.worldRotation, tr.worldScale);const style = (t.bold ? UI_TEXT_BOLD : 0) | (t.italic ? UI_TEXT_ITALIC : 0);// Text.lineHeight is a ratio of fontSize (legacy convention).@@ -271,7 +297,7 @@ export class TextPlugin implements Plugin {shadow,outline,},- this.matrix_,+ appState.matrix,entity as number,layer,// Screen draws all share one depth: their order is the UI tree's,diff --git a/sdk/src/ui/text/text-renderer.ts b/sdk/src/ui/text/text-renderer.tsindex 04b2e5940..1ca572fcd 100644--- a/sdk/src/ui/text/text-renderer.ts+++ b/sdk/src/ui/text/text-renderer.ts@@ -308,6 +308,11 @@ export class SdfTextRenderer {this.atlas.setContentScale(scale);}+ dispose(): void {+ this.cache_.clear();+ this.atlas.dispose();+ }+/*** Draw a line of text. `transform` is the entity's column-major world mat4;* glyph local positions (baseline y=0, y-up) are transformed at submit.diff --git a/sdk/tests/native-text.test.ts b/sdk/tests/native-text.test.tsindex f213c9fa0..6d7c7435d 100644--- a/sdk/tests/native-text.test.ts+++ b/sdk/tests/native-text.test.ts@@ -127,7 +127,7 @@ function makeHostScope() {};installMockEcs(scope);return {- scope, uploads, calls, rasterizeSpy, submitSpy, beginSpy,+ scope, uploads, calls, rasterizeSpy, submitSpy, beginSpy, textures,setScene: (canvas: number, cameras: number[]) => { canvasEntity = canvas; cameraEntities = cameras; },};}@@ -177,6 +177,30 @@ function buildScene(app: ReturnType<typeof createNativeApp>, setScene: (canvas:}describe('a frame on the native core', () => {+ it('isolates glyph pages between apps and releases only the quitting owner', async () => {+ const first = makeHostScope();+ const appA = createNativeApp(makeBridge(first.scope), first.scope);+ await appA.tick(0);+ const labelA = buildScene(appA, first.setScene);+ appA.world.insert(labelA, Text, { content: 'Ω', fontSize: 32, renderMode: TextRenderMode.Sdf });+ await appA.tick(1 / 60);+ expect(first.rasterizeSpy).toHaveBeenCalled();+ expect(first.textures.size).toBe(1);+ const second = makeHostScope();+ const appB = createNativeApp(makeBridge(second.scope), second.scope);+ await appB.tick(0);+ const labelB = buildScene(appB, second.setScene);+ appB.world.insert(labelB, Text, { content: 'Ω', fontSize: 32, renderMode: TextRenderMode.Sdf });+ await appB.tick(1 / 60);+ expect(second.rasterizeSpy).toHaveBeenCalled();+ expect(second.textures.size).toBe(1);+ appA.quit({ keepRenderer: true });+ expect(first.textures.size).toBe(0);+ expect(second.textures.size).toBe(1);+ appB.quit({ keepRenderer: true });+ expect(second.textures.size).toBe(0);+ });+it('copies the full text basis and skips collapsed labels before rasterization', async () => {const { scope, submitSpy, rasterizeSpy, setScene } = makeHostScope();const heap = new ArrayBuffer(65536), frees = vi.fn();diff --git a/sdk/tests/ui-glyph-atlas.test.ts b/sdk/tests/ui-glyph-atlas.test.tsindex 10bd8b80f..c2785438a 100644--- a/sdk/tests/ui-glyph-atlas.test.ts+++ b/sdk/tests/ui-glyph-atlas.test.ts@@ -43,6 +43,25 @@ function makeStore() {}describe('REARCH_GUI P1.1c: GlyphAtlas', () => {+ it('releases every page once, including when one release fails, and clears cached glyphs', () => {+ const rasterizer = makeRasterizer();+ const store = makeStore();+ const releasePage = vi.fn((id: number) => {+ if (id === 100) throw new Error('release failed');+ });+ const atlas = new GlyphAtlas(rasterizer, { ...store, releasePage }, { pageSize: 64, padding: 1 });+ for (let i = 0; i < 25; i++) atlas.getGlyph(0x100 + i, 'Arial');+ expect(atlas.pageCount).toBe(2);+ expect(() => atlas.dispose()).toThrow('Failed to release glyph atlas pages');+ expect(releasePage.mock.calls).toEqual([[100], [101]]);+ expect(atlas.pageCount).toBe(0);+ atlas.dispose();+ expect(releasePage).toHaveBeenCalledTimes(2);+ const calls = rasterizer.rasterize.mock.calls.length;+ expect(atlas.getGlyph(0x100, 'Arial')!.pageId).toBe(102);+ expect(rasterizer.rasterize).toHaveBeenCalledTimes(calls + 1);+ });+it('rasterizes, packs and uploads on first use; returns UVs + metrics', () => {const r = makeRasterizer();const s = makeStore();diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex e7c844fae..565ddfd79 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(text): isolate App glyph caches and release owned pages':+ { note: 'Text atlases belong to each App and release their pages on exit.' },'fix(audio): preserve latest Web device suspension intent':{ note: 'Web audio preserves the latest device pause intent.' },'feat(poki): add authored training gameplay flow':