Skip to content

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.

feat(ui): Text.renderMode — auto-route glyphs between bitmap and SDF AA

yhh7240b1f1aab7
diff --git a/docs/astro/src/content/docs/guides/ui.mdx b/docs/astro/src/content/docs/guides/ui.mdx
index f76f3df7d..dfb775719 100644
--- a/docs/astro/src/content/docs/guides/ui.mdx
+++ b/docs/astro/src/content/docs/guides/ui.mdx
@@ -113,7 +113,19 @@ Add a `FlexContainer` to a node to lay out its children. The enums mirror CSS.
## `Text`
-Text is rendered from an SDF glyph atlas, so it scales crisply.
+Text draws from a dynamic glyph atlas with **two pipelines**, chosen per Text by
+`renderMode`:
+
+- **`Bitmap`** — glyphs rasterize at device resolution with Canvas-native
+ antialiasing and blit 1:1: the sharpest possible text, but it blurs the moment
+ it's scaled.
+- **`Sdf`** — each glyph rasterizes once into a signed-distance field and the
+ shader derives a stable ~1px antialiased edge from screen-space derivatives
+ (`fwidth`), so text stays crisp at **any** scale — camera zoom, entity scale,
+ or the canvas design-resolution fit.
+- **`Auto`** (default) — bitmap while the text truly lands 1:1 on screen, SDF as
+ soon as any scaling applies. You get DOM-crisp menus *and* zoom-stable world
+ text without thinking about it.
| Property | Type | Default | Description |
|---|---|---|---|
@@ -130,6 +142,7 @@ Text is rendered from an SDF glyph atlas, so it scales crisply.
| `strokeColor` / `strokeWidth` | Color / number | — | Outline. |
| `shadowColor` / `shadowBlur` / `shadowOffsetX` / `shadowOffsetY` | — | Drop shadow. |
| `richText` | boolean | `false` | Parse inline rich-text markup. |
+| `renderMode` | `TextRenderMode` | `Auto` | Glyph pipeline: `Auto` / `Bitmap` / `Sdf` (see above). |
## `UIVisual` — the fill
diff --git a/docs/astro/src/content/docs/zh-cn/guides/ui.mdx b/docs/astro/src/content/docs/zh-cn/guides/ui.mdx
index 497e7c3c6..3a5d45729 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/ui.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/ui.mdx
@@ -109,7 +109,15 @@ addStartupSystem(buildPauseMenu);
## `Text`
-文本从 SDF 字形图集渲染,所以缩放清晰。
+文本从动态字形图集渲染,有**两条管线**,由 `renderMode` 逐 Text 选择:
+
+- **`Bitmap`** —— 字形按设备分辨率光栅化(Canvas 原生抗锯齿)并 1:1 贴屏:
+ 最锐利,但一旦被缩放就会模糊。
+- **`Sdf`** —— 每个字形只光栅化一次为有向距离场(SDF),着色器用屏幕空间导数
+ (`fwidth`)推导出稳定的 ~1px 抗锯齿边缘,任何缩放下都清晰——相机变焦、
+ 实体缩放、画布设计分辨率适配都不在话下。
+- **`Auto`**(默认)—— 文本真正 1:1 落屏时用 Bitmap,一旦有任何缩放立即切换
+ SDF。菜单像 DOM 一样锐利,世界文本随缩放稳定,无需操心。
| 属性 | 类型 | 默认 | 说明 |
|---|---|---|---|
@@ -126,6 +134,7 @@ addStartupSystem(buildPauseMenu);
| `strokeColor` / `strokeWidth` | Color / number | — | 描边。 |
| `shadowColor` / `shadowBlur` / `shadowOffsetX` / `shadowOffsetY` | — | 投影。 |
| `richText` | boolean | `false` | 解析内联富文本标记。 |
+| `renderMode` | `TextRenderMode` | `Auto` | 字形管线:`Auto` / `Bitmap` / `Sdf`(见上)。 |
## `UIVisual` —— 填充
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index 62cb1c7fa..c42532f98 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -20,6 +20,7 @@ export {
TextAlign,
TextVerticalAlign,
TextOverflow,
+ TextRenderMode,
UINode,
UIVisual,
UIVisualType,
diff --git a/sdk/src/ui/core/text.ts b/sdk/src/ui/core/text.ts
index 7ec65b5ed..9a2493c9c 100644
--- a/sdk/src/ui/core/text.ts
+++ b/sdk/src/ui/core/text.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { defineComponent } from '../../component';
+import { defineComponent, enumOptions } from '../../component';
import type { Color } from '../../types';
export const TextAlign = {
@@ -24,6 +24,25 @@ export const TextOverflow = {
} as const;
export type TextOverflow = (typeof TextOverflow)[keyof typeof TextOverflow];
+/**
+ * Glyph pipeline for a Text (mirrors Unity's TMP-vs-UI-Text split, unified in
+ * one component). Both pipelines share the atlas, layout, and batch path —
+ * the difference is what the atlas stores and how the shader derives coverage.
+ */
+export const TextRenderMode = {
+ /**
+ * Per-frame choice: device-resolution bitmap when the text lands ~1:1 on
+ * screen (crisp like the DOM), SDF whenever it's scaled — by the canvas
+ * design-resolution fit, a zooming camera, or the entity transform.
+ */
+ Auto: 0,
+ /** Canvas2D native AA at device resolution. Sharpest at 1:1; blurs when scaled. */
+ Bitmap: 1,
+ /** Signed-distance field, fwidth-smoothstep AA — a stable ~1px edge at any scale. */
+ Sdf: 2,
+} as const;
+export type TextRenderMode = (typeof TextRenderMode)[keyof typeof TextRenderMode];
+
export interface TextData {
content: string;
fontFamily: string;
@@ -43,6 +62,8 @@ export interface TextData {
shadowOffsetX: number;
shadowOffsetY: number;
richText: boolean;
+ /** Glyph pipeline: Auto (default) picks bitmap at 1:1, SDF when scaled. */
+ renderMode: TextRenderMode;
}
export const Text = defineComponent<TextData>('Text', {
@@ -64,4 +85,14 @@ export const Text = defineComponent<TextData>('Text', {
shadowOffsetX: 0,
shadowOffsetY: 0,
richText: false,
+ renderMode: TextRenderMode.Auto,
+}, {
+ // Editor dropdowns from the same constants the runtime switches on, so the
+ // labels can never drift (the ParticleEmitter TS-enum precedent).
+ fields: {
+ align: { enum: enumOptions(TextAlign) },
+ verticalAlign: { enum: enumOptions(TextVerticalAlign) },
+ overflow: { enum: enumOptions(TextOverflow) },
+ renderMode: { enum: enumOptions(TextRenderMode) },
+ },
});
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index db8b957ac..d8d222fbf 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -80,6 +80,7 @@ export {
TextAlign,
TextVerticalAlign,
TextOverflow,
+ TextRenderMode,
type TextData,
} from './core/text';
@@ -251,7 +252,7 @@ export { BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES } from './widgets/prefabs/g
// All text — display (Text) and editable (TextInput) — now renders through the
// SDF glyph atlas; the Canvas2D TextRenderer was retired.
-export { TextPlugin, textPlugin } from './text/plugin';
+export { TextPlugin, textPlugin, resolveTextRenderMode } from './text/plugin';
// UI Math Utilities
export {
diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.ts
index 7e5bc1e9a..3eaf61c7d 100644
--- a/sdk/src/ui/text/plugin.ts
+++ b/sdk/src/ui/text/plugin.ts
@@ -2,12 +2,17 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file ui/text/plugin.ts
- * @brief TextPlugin — renders the `Text` component via the dynamic SDF glyph
- * atlas, replacing the legacy Canvas2D-per-entity
- * path. A pre-flush callback scans Text entities, composes the world
- * transform, places the text inside its UINode box (no auto-size — the
- * UINode is the box; rendering never mutates layout) and draws batched
- * SDF glyph quads, layered to interleave with sibling UI elements.
+ * @brief TextPlugin — renders the `Text` component via the dynamic glyph
+ * atlas, replacing the legacy Canvas2D-per-entity path. A pre-flush
+ * callback scans Text entities, composes the world transform, places
+ * the text inside its UINode box (no auto-size — the UINode is the
+ * box; rendering never mutates layout) and draws batched glyph quads,
+ * layered to interleave with sibling UI elements.
+ *
+ * Two glyph pipelines, routed per Text by {@link resolveTextRenderMode}
+ * (Text.renderMode, default Auto): device-resolution bitmaps when the
+ * text lands 1:1 on screen, SDF + fwidth AA whenever it's scaled by
+ * the design-resolution fit, a camera zoom, or the entity transform.
*/
import type { App, Plugin } from '../../app';
import { Transform, type TransformData, registerComponent } from '../../component';
@@ -17,8 +22,9 @@ import type { Entity } from '../../types';
import { SdfTextRenderer } from './text-renderer';
import type { RGBA } from './layout';
import { composeTRS, rectTextBox, UI_TEXT_BOLD, UI_TEXT_ITALIC } from './text-transform';
-import { Text, type TextData } from '../core/text';
+import { Text, TextRenderMode, type TextData } from '../core/text';
import { UINode } from '../core/ui-node';
+import { UICameraInfo, type UICameraData } from '../core/ui-camera-info';
import { getUINodeWidth, getUINodeHeight, ensureUIVisual } from '../util/helpers';
import { platformDevicePixelRatio } from '../../platform';
@@ -29,10 +35,32 @@ const GLYPH_BASE_SIZE = 64;
// Matches C++ UIElementPlugin::UI_BASE_LAYER — UI quads use layer = base + uiOrder.
const UI_BASE_LAYER = 1000;
+// Auto tolerance: a bitmap glyph still reads as pixel-exact within ±2% of 1:1.
+const BITMAP_SCALE_EPSILON = 0.02;
+
+/**
+ * Pure: which glyph pipeline a Text draws with. `effectiveScale` is the
+ * on-screen texels-per-source-texel ratio of a bitmap glyph (1 = pixel-exact:
+ * design→device scale ÷ DPR × entity world scale). Auto keeps the crisp
+ * device-resolution bitmaps only while they truly land 1:1; any real scaling
+ * switches to SDF, whose fwidth AA is stable at every zoom. Non-finite or
+ * unknown scales (no camera yet) keep the bitmap path.
+ */
+export function resolveTextRenderMode(
+ mode: TextRenderMode | undefined,
+ effectiveScale: number,
+): 'bitmap' | 'sdf' {
+ if (mode === TextRenderMode.Bitmap) return 'bitmap';
+ if (mode === TextRenderMode.Sdf) return 'sdf';
+ if (!Number.isFinite(effectiveScale) || effectiveScale <= 0) return 'bitmap';
+ return Math.abs(effectiveScale - 1) <= BITMAP_SCALE_EPSILON ? 'bitmap' : 'sdf';
+}
+
export class TextPlugin implements Plugin {
name = 'text';
- private renderer_: SdfTextRenderer | null = null;
+ private bitmapRenderer_: SdfTextRenderer | null = null;
+ private sdfRenderer_: SdfTextRenderer | null = null;
private readonly matrix_ = new Float32Array(16);
build(app: App): void {
@@ -57,21 +85,26 @@ export class TextPlugin implements Plugin {
const registry = world.getCppRegistry() as CppRegistry;
pipeline.addPreFlushCallback(() => {
+ // Design→device scale of one UI px this frame (vpW is device px);
+ // ÷DPR gives the bitmap texel:pixel ratio Auto switches on.
+ // Resolved per frame — the camera plugin may build after this one.
+ const uiCamera = app.getResource(UICameraInfo) as UICameraData | undefined;
+ const dpr = platformDevicePixelRatio();
+ const span = uiCamera ? uiCamera.worldRight - uiCamera.worldLeft : 0;
+ const designToTexel = uiCamera?.valid && span > 0
+ ? uiCamera.vpW / (span * dpr)
+ : 1;
+
for (const e of world.getEntitiesWithComponents([Text, Transform])) {
const entity = e as Entity;
const t = world.get(entity, Text) as TextData;
if (!t.content) continue;
- if (!this.renderer_) {
- // Device-resolution bitmap text: glyphs rasterize per size at DPR
- // and blit 1:1, keeping Canvas's native AA — crisp like the DOM.
- // (SDF stays available via sdf:true for scalable / world text.)
- const dpr = platformDevicePixelRatio();
- this.renderer_ = new SdfTextRenderer(app.wasmModule as ESEngineModule, {
- sdf: false, dpr, renderSize: Math.round(GLYPH_BASE_SIZE * dpr),
- });
- }
const tr = world.get(entity, Transform) as TransformData;
+ const renderer = this.rendererFor(
+ app,
+ resolveTextRenderMode(t.renderMode, designToTexel * tr.worldScale.x),
+ );
composeTRS(this.matrix_, tr.worldPosition, tr.worldRotation, tr.worldScale);
const style = (t.bold ? UI_TEXT_BOLD : 0) | (t.italic ? UI_TEXT_ITALIC : 0);
@@ -120,7 +153,7 @@ export class TextPlugin implements Plugin {
}
: undefined;
- this.renderer_.drawText(
+ renderer.drawText(
{
text: t.content,
fontFamily: t.fontFamily,
@@ -146,6 +179,31 @@ export class TextPlugin implements Plugin {
}
});
}
+
+ /**
+ * The two glyph pipelines, created lazily and kept for the app's lifetime.
+ * Bitmap: per-size rasterization at DPR, Canvas-native AA, blits 1:1.
+ * SDF: one fixed-size rasterization per glyph, fwidth-AA in the shader —
+ * resolution-independent, so scaled/zoomed text stays crisp. Both share
+ * the same layout, page-store, and batch-submit path; only the atlas
+ * contents and the shader's coverage derivation differ.
+ */
+ private rendererFor(app: App, kind: 'bitmap' | 'sdf'): SdfTextRenderer {
+ const module = app.wasmModule as ESEngineModule;
+ if (kind === 'sdf') {
+ if (!this.sdfRenderer_) {
+ this.sdfRenderer_ = new SdfTextRenderer(module, { sdf: true });
+ }
+ return this.sdfRenderer_;
+ }
+ if (!this.bitmapRenderer_) {
+ const dpr = platformDevicePixelRatio();
+ this.bitmapRenderer_ = new SdfTextRenderer(module, {
+ sdf: false, dpr, renderSize: Math.round(GLYPH_BASE_SIZE * dpr),
+ });
+ }
+ return this.bitmapRenderer_;
+ }
}
export const textPlugin = new TextPlugin();
diff --git a/sdk/src/ui/widgets/helpers.ts b/sdk/src/ui/widgets/helpers.ts
index 671573f69..1ae50575c 100644
--- a/sdk/src/ui/widgets/helpers.ts
+++ b/sdk/src/ui/widgets/helpers.ts
@@ -10,7 +10,7 @@ import type { World } from '../../world';
import { UINode, UIPositionType, type UINodeData } from '../core/ui-node';
import { px, percent, auto, type Dimension } from '../core/dimension';
import { UIVisual, UIVisualType, FillMethod, FillOrigin, type UIVisualData } from '../core/ui-visual';
-import { Text, TextAlign, TextVerticalAlign, type TextData } from '../core/text';
+import { Text, TextAlign, TextVerticalAlign, TextRenderMode, type TextData } from '../core/text';
/** Identity Transform. Fresh object per call — safe to insert into ECS. */
export function identityTransform(): TransformData {
@@ -148,6 +148,7 @@ export function buildText(init: TextInit = {}): TextData {
shadowOffsetX: init.shadowOffsetX ?? 0,
shadowOffsetY: init.shadowOffsetY ?? 0,
richText: init.richText ?? false,
+ renderMode: init.renderMode ?? TextRenderMode.Auto,
};
}
diff --git a/sdk/tests/ui-text-render-mode.test.ts b/sdk/tests/ui-text-render-mode.test.ts
new file mode 100644
index 000000000..7e811ef97
--- /dev/null
+++ b/sdk/tests/ui-text-render-mode.test.ts
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { Text, TextRenderMode, resolveTextRenderMode, buildText } from '../src/ui';
+
+describe('TextRenderMode', () => {
+ it('defines Auto / Bitmap / Sdf', () => {
+ expect(TextRenderMode.Auto).toBe(0);
+ expect(TextRenderMode.Bitmap).toBe(1);
+ expect(TextRenderMode.Sdf).toBe(2);
+ });
+
+ it('Text defaults to Auto and declares the editor dropdown', () => {
+ expect((Text._default as { renderMode: number }).renderMode).toBe(TextRenderMode.Auto);
+ const meta = Text.fieldMeta['renderMode'];
+ expect(meta?.enum?.map(o => o.label)).toEqual(['Auto', 'Bitmap', 'Sdf']);
+ });
+
+ it('buildText defaults renderMode to Auto and passes overrides through', () => {
+ expect(buildText().renderMode).toBe(TextRenderMode.Auto);
+ expect(buildText({ renderMode: TextRenderMode.Sdf }).renderMode).toBe(TextRenderMode.Sdf);
+ });
+});
+
+describe('resolveTextRenderMode', () => {
+ it('forced modes win regardless of scale', () => {
+ expect(resolveTextRenderMode(TextRenderMode.Bitmap, 3)).toBe('bitmap');
+ expect(resolveTextRenderMode(TextRenderMode.Sdf, 1)).toBe('sdf');
+ });
+
+ it('Auto keeps bitmap at (or within 2% of) pixel-exact 1:1', () => {
+ expect(resolveTextRenderMode(TextRenderMode.Auto, 1)).toBe('bitmap');
+ expect(resolveTextRenderMode(TextRenderMode.Auto, 1.019)).toBe('bitmap');
+ expect(resolveTextRenderMode(TextRenderMode.Auto, 0.981)).toBe('bitmap');
+ });
+
+ it('Auto switches to SDF once the text is actually scaled', () => {
+ // The design-fit case that motivated the mode: 800×600 design in a
+ // 1070×494 viewport lands at ~0.82 texels per pixel.
+ expect(resolveTextRenderMode(TextRenderMode.Auto, 0.82)).toBe('sdf');
+ expect(resolveTextRenderMode(TextRenderMode.Auto, 1.5)).toBe('sdf');
+ expect(resolveTextRenderMode(TextRenderMode.Auto, 0.5)).toBe('sdf');
+ });
+
+ it('Auto falls back to bitmap on unknown / degenerate scales', () => {
+ expect(resolveTextRenderMode(TextRenderMode.Auto, 0)).toBe('bitmap');
+ expect(resolveTextRenderMode(TextRenderMode.Auto, -1)).toBe('bitmap');
+ expect(resolveTextRenderMode(TextRenderMode.Auto, NaN)).toBe('bitmap');
+ expect(resolveTextRenderMode(TextRenderMode.Auto, Infinity)).toBe('bitmap');
+ });
+
+ it('treats a missing mode (pre-upgrade scene data) as Auto', () => {
+ expect(resolveTextRenderMode(undefined, 1)).toBe('bitmap');
+ expect(resolveTextRenderMode(undefined, 0.82)).toBe('sdf');
+ });
+});