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
perf(text): reclaim unused glyph pages at frame boundaries
yhhd1eb4f25a6c4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 50705513e..5dde4802f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,8 @@ published separately; it ships inside the editor.### Fixed+- **Unused text atlas pages retire at frame boundaries.** Cached layouts retain their referenced pages while obsolete sizes, replaced labels, hidden text and inactive bitmap/SDF modes release unreferenced GPU pages on a subsequent frame. Page restore callbacks capture their own placement lists, preserving live UVs after other pages are removed; stable text keeps its raster and geometry caches.+- **Bitmap glyphs survive enlarged text and camera zoom.** Canvas scratch surfaces grow to fit glyphs within the configured atlas dimensions instead of dropping tiles larger than their initial size. Resizing restores font, bold/italic style and alignment before drawing; smaller requests reuse the grown surface, and oversized tiles remain bounded by the atlas limit.- **AudioPlugin checks platform initialization before subscribing to host mute.** Independent audio backend tests and direct construction no longer fail while reading an optional platform capability.diff --git a/sdk/src/ui/text/glyph-atlas.ts b/sdk/src/ui/text/glyph-atlas.tsindex 23b1d6c18..39285549d 100644--- a/sdk/src/ui/text/glyph-atlas.ts+++ b/sdk/src/ui/text/glyph-atlas.ts@@ -147,6 +147,27 @@ export class GlyphAtlas {if (errors.length) throw new Error(`Failed to release glyph atlas pages: ${errors.map(String).join('; ')}`);}+ /** Release pages not referenced by retained layouts, at a submitted-frame boundary. */+ retainPages(live: ReadonlySet<number>): void {+ const removed = new Set<number>();+ for (let i = this.pages.length - 1; i >= 0; i--) {+ if (live.has(this.pages[i])) continue;+ removed.add(this.pages[i]);+ this.pages.splice(i, 1);+ this.packers.splice(i, 1);+ this.placements.splice(i, 1);+ }+ if (removed.size === 0) return;+ for (const [key, glyph] of this.cache) {+ if (glyph && removed.has(glyph.pageId)) this.cache.delete(key);+ }+ const errors: unknown[] = [];+ for (const page of removed) {+ try { this.store?.releasePage?.(page); } catch (error) { errors.push(error); }+ }+ if (errors.length) throw new Error(`Failed to release unused glyph 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-rasterize@@ -296,9 +317,9 @@ export class GlyphAtlas {private addPage(): void {if (!this.store) throw new Error('Measurement atlases cannot allocate pages.');- const page = this.pages.length;- this.placements.push([]);- this.pages.push(this.store.createPage(this.pageSize, (pixels) => this.paintPage(page, pixels)));+ const glyphs: GlyphPlacement[] = [];+ this.placements.push(glyphs);+ this.pages.push(this.store.createPage(this.pageSize, (pixels) => this.paintPage(glyphs, pixels)));this.packers.push(new ShelfPacker(this.pageSize, this.pageSize));}@@ -307,9 +328,9 @@ export class GlyphAtlas {* glyph that now comes out larger (its font finished loading) is clipped to* its cell rather than drawn over a neighbour's.*/- private paintPage(page: number, pixels: Uint8Array): void {+ private paintPage(glyphs: readonly GlyphPlacement[], pixels: Uint8Array): void {const size = this.pageSize;- for (const g of this.placements[page]) {+ for (const g of glyphs) {const raster = this.rasterizer.rasterize(g.codepoint, g.fontFamily, g.style, g.pixelSize);if (!raster) continue;const width = Math.min(raster.width, g.width);diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.tsindex 83e48532d..dff1181ff 100644--- a/sdk/src/ui/text/plugin.ts+++ b/sdk/src/ui/text/plugin.ts@@ -125,6 +125,14 @@ export class TextPlugin implements Plugin {const world = app.world;+ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([], () => {+ const state = this.states_.get(app);+ if (!state) return;+ for (const renderer of [state.world.bitmap, state.world.sdf, state.screen.bitmap, state.screen.sdf]) {+ renderer?.beginFrame();+ }+ }, { name: 'TextPageLifetimeSystem' }));+// A Text node inside a UINode is a UI render node: ensure it carries a// UIVisual (visualType None — not drawn as a quad) so the UI// render-order pass assigns it a uiOrder and the SDF glyphs sort withdiff --git a/sdk/src/ui/text/text-renderer.ts b/sdk/src/ui/text/text-renderer.tsindex 6ea38f015..62c5fc26b 100644--- a/sdk/src/ui/text/text-renderer.ts+++ b/sdk/src/ui/text/text-renderer.ts@@ -291,6 +291,7 @@ export class SdfTextRenderer {private readonly sdf: boolean;private readonly cache_ = new Map<number, TextCacheEntry>();private readonly clipPlanes_ = new Float64Array(36);+ private readonly drawn_ = new Set<number>();/** `module` is null on the native core (no wasm heap); the glyph source is* then the platform's own rasterizer, since there is no 2D canvas to draw@@ -313,7 +314,22 @@ export class SdfTextRenderer {this.atlas.setContentScale(scale);}+ /** Previous frame has submitted; remove unused layouts and their GPU pages. */+ beginFrame(): void {+ if (this.atlas.metricsOnly) return;+ for (const entity of this.cache_.keys()) {+ if (!this.drawn_.has(entity)) this.cache_.delete(entity);+ }+ const pages = new Set<number>();+ for (const entry of this.cache_.values()) {+ for (const batch of entry.batches) pages.add(batch.pageId);+ }+ this.drawn_.clear();+ this.atlas.retainPages(pages);+ }+dispose(): void {+ this.drawn_.clear();this.cache_.clear();this.atlas.dispose();}@@ -339,6 +355,7 @@ export class SdfTextRenderer {if (this.atlas.metricsOnly) throw new Error('Measurement atlases cannot submit text.');const opacity = p.opacity ?? 1;if (opacity <= 0) return;+ this.drawn_.add(entity);const gen = this.atlas.generation;const sig = textSignature(p, 1);let entry = this.cache_.get(entity);diff --git a/sdk/tests/native-text.test.ts b/sdk/tests/native-text.test.tsindex a71844978..d9e9a75fa 100644--- a/sdk/tests/native-text.test.ts+++ b/sdk/tests/native-text.test.ts@@ -178,6 +178,33 @@ function buildScene(app: ReturnType<typeof createNativeApp>, setScene: (canvas:}describe('a frame on the native core', () => {+ it('reclaims obsolete glyph pages at frame boundaries without rerasterizing live text', async () => {+ const host = makeHostScope();+ const app = createNativeApp(makeBridge(host.scope), host.scope);+ await app.tick(0);+ const renderer = new SdfTextRenderer(null, { sdf: false, pageSize: 16 });+ const matrix = new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);+ const parameters = { text: 'A', fontFamily: 'Arial', fontSizePx: 32, color: [1,1,1,1] as const };+ renderer.beginFrame();+ renderer.drawText(parameters, matrix, 1, 0, 0);+ renderer.beginFrame();+ renderer.drawText({ ...parameters, fontFamily: 'Other' }, matrix, 1, 0, 0);+ expect(host.textures.size).toBe(2);+ renderer.beginFrame();+ expect(host.textures.size).toBe(1);+ const requests = host.rasterizeSpy.mock.calls.length;+ renderer.drawText({ ...parameters, fontFamily: 'Other' }, matrix, 1, 0, 0);+ expect(host.rasterizeSpy).toHaveBeenCalledTimes(requests);+ renderer.beginFrame();+ expect(host.textures.size).toBe(1);+ // No label drew this frame: the following boundary reclaims its layout.+ renderer.beginFrame();+ expect(host.textures.size).toBe(0);+ renderer.drawText(parameters, matrix, 1, 0, 0);+ expect(host.textures.size).toBe(1);+ renderer.dispose(); app.quit({keepRenderer:true});+ });+it.each([true, false])('culls long cached glyphs and restores the complete layout (sdf=%s)', async sdf => {const host = makeHostScope();const app = createNativeApp(makeBridge(host.scope), host.scope);diff --git a/sdk/tests/ui-glyph-atlas.test.ts b/sdk/tests/ui-glyph-atlas.test.tsindex 7cb84b9f6..6094ce216 100644--- a/sdk/tests/ui-glyph-atlas.test.ts+++ b/sdk/tests/ui-glyph-atlas.test.ts@@ -207,6 +207,29 @@ describe('GlyphAtlas: a page painted again is the page that was uploaded', () =>return { store, images, painters };}+ it('prunes unused pages without changing live UVs or their restore painter', () => {+ const { store, images, painters } = imageStore();+ const releasePage = vi.fn();+ const atlas = new GlyphAtlas(patternRasterizer(), { ...store, releasePage }, { pageSize: PAGE, padding: 1 });+ for (let i = 0; i < 30; i++) atlas.getGlyph(0x100 + i, 'Arial');+ const retired = atlas.getGlyph(0x100, 'Arial')!;+ const kept = atlas.getGlyph(0x11d, 'Arial')!;+ expect(retired.pageId).not.toBe(kept.pageId);+ const generation = atlas.generation;+ atlas.retainPages(new Set([kept.pageId]));+ expect(atlas.pageCount).toBe(1);+ expect(releasePage).toHaveBeenCalledWith(retired.pageId);+ expect(atlas.generation).toBe(generation);+ expect(atlas.getGlyph(0x11d, 'Arial')).toBe(kept);+ const repaint = new Uint8Array(PAGE * PAGE * 4);+ painters[kept.pageId](repaint);+ expect(repaint).toEqual(images[kept.pageId]);+ expect(atlas.getGlyph(0x100, 'Arial')!.pageId).not.toBe(retired.pageId);+ atlas.retainPages(new Set());+ expect(atlas.pageCount).toBe(0);+ expect(atlas.getGlyph(0x100, 'Arial')).not.toBeNull();+ });+it('repaints every page byte for byte, across pages, skipping blanks', () => {const { store, images, painters } = imageStore();const atlas = new GlyphAtlas(patternRasterizer(), store, { pageSize: PAGE, padding: 1 });diff --git a/sdk/tests/ui-text-overflow-cache.test.ts b/sdk/tests/ui-text-overflow-cache.test.tsindex 27bfc5117..a508fbfc0 100644--- a/sdk/tests/ui-text-overflow-cache.test.ts+++ b/sdk/tests/ui-text-overflow-cache.test.ts@@ -4,6 +4,17 @@ import { GlyphAtlas } from '../src/ui/text/glyph-atlas';import { SdfTextRenderer, drawTextWith, type DrawTextParams } from '../src/ui/text/text-renderer';import { TextOverflow } from '../src/ui/core/text';import { submitTextBatch } from '../src/ui/text/submit';+vi.mock('../src/platform', () => ({+ platformHasGlyphRasterizer: () => false,+ platformCreateCanvas: (width: number, height: number) => ({ width, height, getContext: () => null }),+}));++function rendererWithAtlas(atlas: GlyphAtlas, sdf: boolean): SdfTextRenderer {+ const renderer = new SdfTextRenderer(null, { sdf, metricsOnly: true });+ Object.defineProperty(renderer, 'atlas', { value: atlas });+ return renderer;+}+vi.mock('../src/ui/text/submit', async importOriginal => ({...await importOriginal<typeof import('../src/ui/text/submit')>(), submitTextBatch: vi.fn(),}));@@ -14,9 +25,7 @@ it.each([false, true])('reuses multi-page fading geometry without cumulative alppixels: new Uint8Array(10 * 12 * 4), width: 10, height: 12,advance: 11, bearingX: 1, bearingY: 10,}) }, { createPage: () => nextPage++, uploadSubRegion: () => {} }, { pageSize: 32, padding: 1, sdf });- const renderer = Object.assign(Object.create(SdfTextRenderer.prototype), {- atlas, sdf, module: null, cache_: new Map(),- }) as SdfTextRenderer;+ const renderer = rendererWithAtlas(atlas, sdf);const p: DrawTextParams = {text: '<color=#ff000080>ABC</color>DEF', richText: true, fontFamily: 'Arial', fontSizePx: 24,color: [1, 1, 1, 0.8], shadow: { color: [0, 0, 0, 0.6], dx: 1, dy: 1 },@@ -54,9 +63,7 @@ it('rebuilds only changed overflow geometry while other static text keeps its caadvance: 11, bearingX: 1, bearingY: 10,}) }, { createPage: () => 1000, uploadSubRegion: () => {} }, { pageSize: 1024, padding: 1, sdf: false });// Inject an atlas and submission sink, preserving the real renderer cache path.- const renderer = Object.assign(Object.create(SdfTextRenderer.prototype), {- atlas, sdf: false, module: null, cache_: new Map(),- }) as SdfTextRenderer;+ const renderer = rendererWithAtlas(atlas, false);const transform = new Float32Array(16);const params: DrawTextParams = { text: 'ABCDEF', fontFamily: 'Arial', fontSizePx: 48,color: [1, 1, 1, 1], boxWidth: 24, boxHeight: 60, overflow: TextOverflow.Visible };@@ -86,9 +93,7 @@ it('invalidates cached geometry when text and font names contain field delimiterpixels: new Uint8Array(10 * 12 * 4), width: 10, height: 12,advance: 11, bearingX: 1, bearingY: 10,}) }, { createPage: () => 1000, uploadSubRegion: () => {} }, { pageSize: 1024, padding: 1, sdf: false });- const renderer = Object.assign(Object.create(SdfTextRenderer.prototype), {- atlas, sdf: false, module: null, cache_: new Map(),- }) as SdfTextRenderer;+ const renderer = rendererWithAtlas(atlas, false);const transform = new Float32Array(16);const submit = vi.mocked(submitTextBatch);const first: DrawTextParams = { text: 'A|B', fontFamily: 'Arial', fontSizePx: 48, color: [1, 1, 1, 1] };diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex f4eea465f..844db23de 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 = {+ 'perf(text): reclaim unused glyph pages at frame boundaries':+ { note: 'Unused text atlas pages retire at frame boundaries.' },'feat(storage): await asynchronous host persistence':{ note: 'Storage exposes asynchronous write acknowledgment.' },'fix(text): rasterize enlarged bitmap glyphs within atlas limits':