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(sdk): cache tessellated text geometry per entity
esenginef7bb5b151abc
diff --git a/sdk/src/ui/text/glyph-atlas.ts b/sdk/src/ui/text/glyph-atlas.tsindex 8e416de0b..1ae799f23 100644--- a/sdk/src/ui/text/glyph-atlas.ts+++ b/sdk/src/ui/text/glyph-atlas.ts@@ -87,6 +87,7 @@ export class GlyphAtlas {private readonly sdf: boolean;private readonly dpr: number;private contentScale_ = 1;+ private generation_ = 0;private readonly cache = new Map<string, GlyphEntry | null>();private readonly pages: number[] = [];private readonly packers: Packer[] = [];@@ -105,6 +106,14 @@ export class GlyphAtlas {/** Number of atlas pages currently allocated. */get pageCount(): number { return this.pages.length; }+ /**+ * 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+ * at a new pixel size). Placement is append-only, so adding a *new* glyph never+ * moves an existing one; callers cache laid-out geometry against this counter.+ */+ get generation(): number { return this.generation_; }+/** The px size glyphs are rasterized at; layout scales by displaySize/renderSize. */get renderSize(): number { return this.rasterizer.renderSize; }@@ -115,7 +124,11 @@ export class GlyphAtlas {* pixelSizeFor dedupes near-equal scales.*/setContentScale(scale: number): void {- this.contentScale_ = Number.isFinite(scale) && scale > 0 ? scale : 1;+ const next = Number.isFinite(scale) && scale > 0 ? scale : 1;+ if (next !== this.contentScale_) {+ this.contentScale_ = next;+ this.generation_++;+ }}/** Rasterization size for a display size: SDF uses one fixed source;diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.tsindex beecedd4d..7a4491275 100644--- a/sdk/src/ui/text/plugin.ts+++ b/sdk/src/ui/text/plugin.ts@@ -88,11 +88,13 @@ export class TextPlugin implements Plugin {? uiCamera.vpW / (span * dpr): 1;+ const seen = new Set<number>();for (const e of world.getEntitiesWithComponents([Text, Transform])) {const entity = e as Entity;const t = world.get(entity, Text) as TextData;// enabled === false: pre-upgrade data lacks the field → visible.if (!t.content || t.enabled === false) continue;+ seen.add(entity as number);const tr = world.get(entity, Transform) as TransformData;const renderer = this.rendererFor(@@ -175,6 +177,10 @@ export class TextPlugin implements Plugin {tr.worldPosition.z,);}++ // Release cached geometry for text that vanished / hid this frame.+ this.bitmapRenderer_?.retainOnly(seen);+ this.sdfRenderer_?.retainOnly(seen);});}diff --git a/sdk/src/ui/text/text-renderer.ts b/sdk/src/ui/text/text-renderer.tsindex 89a8c3a38..f07f76fbd 100644--- a/sdk/src/ui/text/text-renderer.ts+++ b/sdk/src/ui/text/text-renderer.ts@@ -136,9 +136,24 @@ export interface TextRendererOptions extends CanvasGlyphRasterizerOptions {dpr?: number;}+/** One laid-out, tessellated page batch in the entity's local (untransformed) space. */+interface CachedTextBatch {+ vertices: Float32Array;+ indices: Uint16Array;+ pageId: number;+}++interface TextCacheEntry {+ sig: string;+ /** Atlas generation the geometry was built against (bitmap content-scale). */+ gen: number;+ batches: CachedTextBatch[];+}+export class SdfTextRenderer {readonly atlas: GlyphAtlas;private readonly sdf: boolean;+ private readonly cache_ = new Map<number, TextCacheEntry>();constructor(private readonly module: ESEngineModule, opts: TextRendererOptions = {}) {this.sdf = opts.sdf ?? true;@@ -157,6 +172,11 @@ export class SdfTextRenderer {/*** 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.+ *+ * The tessellated geometry is local-space (transform-independent), so it is+ * cached per entity keyed by the layout signature + atlas generation: a static+ * label re-submits its cached quads with the current transform each frame+ * instead of re-laying-out and re-tessellating every glyph.*/drawText(p: DrawTextParams,@@ -165,8 +185,41 @@ export class SdfTextRenderer {layer: number,depth: number,): void {- drawTextWith(this.atlas, (vertices, indices, pageId) => {- submitTextBatch(this.module, vertices, indices, pageId, transform, entity, layer, depth, this.sdf);- }, p);+ const gen = this.atlas.generation;+ const sig = signatureOf(p);+ let entry = this.cache_.get(entity);+ if (!entry || entry.gen !== gen || entry.sig !== sig) {+ const batches: CachedTextBatch[] = [];+ drawTextWith(this.atlas, (vertices, indices, pageId) => {+ batches.push({ vertices, indices, pageId });+ }, p);+ entry = { sig, gen, batches };+ this.cache_.set(entity, entry);+ }+ for (const b of entry.batches) {+ submitTextBatch(this.module, b.vertices, b.indices, b.pageId, transform, entity, layer, depth, this.sdf);+ }}++ /** Drop cached geometry for entities not drawn this frame (despawned / hidden / no longer text). */+ retainOnly(live: Set<number>): void {+ if (this.cache_.size === 0) return;+ for (const e of this.cache_.keys()) {+ if (!live.has(e)) this.cache_.delete(e);+ }+ }+}++/** Serialize every DrawTextParams field that affects the laid-out, colored geometry. */+export function signatureOf(p: DrawTextParams): string {+ const shadow = p.shadow ? `${p.shadow.color.join(',')}:${p.shadow.dx}:${p.shadow.dy}` : '';+ const outline = p.outline ? `${p.outline.color.join(',')}:${p.outline.width}` : '';+ return [+ p.text, p.fontFamily, p.fontSizePx, p.style ?? 0,+ p.richText ? 1 : 0, p.align ?? 0, p.verticalAlign ?? 0,+ p.lineHeight ?? 0, p.letterSpacing ?? 0,+ p.maxWidth ?? 0, p.boxWidth ?? 0, p.boxHeight ?? 0,+ p.originX ?? 0, p.originY ?? 0,+ p.color.join(','), shadow, outline,+ ].join('|');}diff --git a/sdk/tests/ui-text-renderer.test.ts b/sdk/tests/ui-text-renderer.test.tsindex 5ade999fa..4e46cd51d 100644--- a/sdk/tests/ui-text-renderer.test.ts+++ b/sdk/tests/ui-text-renderer.test.ts@@ -9,7 +9,8 @@ import { describe, it, expect, vi } from 'vitest';import {GlyphAtlas, type GlyphRasterizer, type AtlasPageStore, type RasterGlyph,} from '../src/ui/text/glyph-atlas';-import { drawTextWith } from '../src/ui/text/text-renderer';+import { drawTextWith, signatureOf } from '../src/ui/text/text-renderer';+import type { DrawTextParams } from '../src/ui/text/text-renderer';function makeAtlas(pageSize: number): GlyphAtlas {const rasterizer: GlyphRasterizer = {@@ -117,3 +118,37 @@ describe('REARCH_GUI P1.3b: drawTextWith', () => {expect(rightInBox).toBeGreaterThan(leftInBox + 100); // pushed toward the box's right edge});});++describe('text cache signature completeness', () => {+ const base: DrawTextParams = {+ text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1],+ };++ it('is stable for identical params (so a static label stays a cache hit)', () => {+ expect(signatureOf({ ...base })).toBe(signatureOf({ ...base }));+ });++ // Every field that changes the laid-out, colored geometry MUST change the+ // signature — otherwise a mutated label would reuse stale cached quads.+ it.each<[string, Partial<DrawTextParams>]>([+ ['text', { text: 'AC' }],+ ['fontFamily', { fontFamily: 'Times' }],+ ['fontSizePx', { fontSizePx: 25 }],+ ['style', { style: 1 }],+ ['richText', { richText: true }],+ ['align', { align: 2 }],+ ['verticalAlign', { verticalAlign: 1 }],+ ['lineHeight', { lineHeight: 30 }],+ ['letterSpacing', { letterSpacing: 2 }],+ ['maxWidth', { maxWidth: 200 }],+ ['boxWidth', { boxWidth: 400 }],+ ['boxHeight', { boxHeight: 100 }],+ ['originX', { originX: 5 }],+ ['originY', { originY: 5 }],+ ['color', { color: [1, 0, 0, 1] }],+ ['shadow', { shadow: { color: [0, 0, 0, 1], dx: 2, dy: 2 } }],+ ['outline', { outline: { color: [0, 0, 0, 1], width: 1 } }],+ ])('changes when %s changes', (_field, override) => {+ expect(signatureOf({ ...base, ...override })).not.toBe(signatureOf(base));+ });+});