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.

fix(ui): FGUI-grade text sharpness — 1px SDF coverage ramp + hinted bitmap at final pixels

yhh655a0f56f1e5
diff --git a/docs/astro/src/content/docs/guides/ui.mdx b/docs/astro/src/content/docs/guides/ui.mdx
index dfb775719..819cbbeed 100644
--- a/docs/astro/src/content/docs/guides/ui.mdx
+++ b/docs/astro/src/content/docs/guides/ui.mdx
@@ -116,16 +116,16 @@ Add a `FlexContainer` to a node to lay out its children. The enums mirror CSS.
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.
+- **`Bitmap`** — glyphs rasterize at the **effective on-screen pixel size**
+ (device pixels × the canvas design-resolution fit) with Canvas-native
+ antialiasing and font hinting, and blit 1:1 — DOM-crisp at any window size.
- **`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.
+ shader lays a **1px screen-space coverage ramp** on the edge (the
+ msdfgen/TextMeshPro technique), so text stays crisp under **dynamic** scaling
+ — animated zoom, scale tweens, world-space labels.
+- **`Auto`** (default) — bitmap while the entity itself is unscaled (the canvas
+ fit is already compensated in the bitmap), SDF the moment the entity scales.
+ DOM-crisp static UI *and* zoom-stable animated text, no configuration.
| Property | Type | Default | Description |
|---|---|---|---|
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 3a5d45729..f5684c854 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/ui.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/ui.mdx
@@ -111,13 +111,14 @@ addStartupSystem(buildPauseMenu);
文本从动态字形图集渲染,有**两条管线**,由 `renderMode` 逐 Text 选择:
-- **`Bitmap`** —— 字形按设备分辨率光栅化(Canvas 原生抗锯齿)并 1:1 贴屏:
- 最锐利,但一旦被缩放就会模糊。
-- **`Sdf`** —— 每个字形只光栅化一次为有向距离场(SDF),着色器用屏幕空间导数
- (`fwidth`)推导出稳定的 ~1px 抗锯齿边缘,任何缩放下都清晰——相机变焦、
- 实体缩放、画布设计分辨率适配都不在话下。
-- **`Auto`**(默认)—— 文本真正 1:1 落屏时用 Bitmap,一旦有任何缩放立即切换
- SDF。菜单像 DOM 一样锐利,世界文本随缩放稳定,无需操心。
+- **`Bitmap`** —— 字形按**最终屏幕像素尺寸**(设备像素 × 画布设计分辨率适配)
+ 光栅化,带 Canvas 原生抗锯齿与字体 hinting,1:1 贴屏——任何窗口尺寸下都像
+ DOM 一样锐利。
+- **`Sdf`** —— 每个字形只光栅化一次为有向距离场(SDF),着色器在边缘铺一条
+ **1px 屏幕空间覆盖率斜坡**(msdfgen / TextMeshPro 的标准做法),**动态**缩放
+ 下保持清晰——变焦动画、缩放补间、世界空间标签。
+- **`Auto`**(默认)—— 实体自身未缩放时用 Bitmap(画布适配已在位图内补偿),
+ 实体一旦缩放立即切 SDF。静态 UI 像 DOM 一样锐利,动态文本随缩放稳定,零配置。
| 属性 | 类型 | 默认 | 说明 |
|---|---|---|---|
diff --git a/sdk/src/ui/text/glyph-atlas.ts b/sdk/src/ui/text/glyph-atlas.ts
index dfeff4c0c..30f1f70be 100644
--- a/sdk/src/ui/text/glyph-atlas.ts
+++ b/sdk/src/ui/text/glyph-atlas.ts
@@ -86,6 +86,7 @@ export class GlyphAtlas {
private readonly padding: number;
private readonly sdf: boolean;
private readonly dpr: number;
+ private contentScale_ = 1;
private readonly cache = new Map<string, GlyphEntry | null>();
private readonly pages: number[] = [];
private readonly packers: Packer[] = [];
@@ -107,10 +108,25 @@ export class GlyphAtlas {
/** The px size glyphs are rasterized at; layout scales by displaySize/renderSize. */
get renderSize(): number { return this.rasterizer.renderSize; }
+ /**
+ * On-screen device px per design px beyond DPR (the canvas design-resolution
+ * fit / camera scale). Bitmap glyphs fold it into the rasterization size so
+ * they land 1:1 on *screen* pixels — hinted at the final size, like DOM
+ * text — instead of rasterizing at design px and being resampled by the
+ * quad scale. Integer-px rounding in pixelSizeFor dedupes near-equal
+ * scales, so a window resize re-rasterizes only when sizes actually change.
+ */
+ setContentScale(scale: number): void {
+ this.contentScale_ = Number.isFinite(scale) && scale > 0 ? scale : 1;
+ }
+
/** Rasterization size for a display size: SDF uses one fixed resolution-independent
- * source; bitmap rasterizes per size at device density for a crisp 1:1 blit. */
+ * source; bitmap rasterizes per size at the effective on-screen density
+ * (DPR × content scale) for a crisp 1:1 blit. */
pixelSizeFor(displaySize: number): number {
- return this.sdf ? this.renderSize : Math.max(1, Math.round(displaySize * this.dpr));
+ return this.sdf
+ ? this.renderSize
+ : Math.max(1, Math.round(displaySize * this.dpr * this.contentScale_));
}
private key(codepoint: number, fontFamily: string, style: number, pixelSize: number): string {
diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.ts
index 3eaf61c7d..2bd9ff049 100644
--- a/sdk/src/ui/text/plugin.ts
+++ b/sdk/src/ui/text/plugin.ts
@@ -40,11 +40,13 @@ 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.
+ * residual scale the bitmap path CANNOT fold into rasterization — the entity's
+ * own world scale. (The canvas design-fit / camera scale is compensated by
+ * rasterizing bitmap glyphs at the effective on-screen size, see
+ * {@link GlyphAtlas.setContentScale} — so a static UI stays on hinted,
+ * pixel-exact bitmaps at any window size, like DOM/FGUI text.) Auto sends
+ * genuinely scaled text to SDF, whose screen-px-ramp AA is stable at every
+ * zoom. Non-finite or unknown scales keep the bitmap path.
*/
export function resolveTextRenderMode(
mode: TextRenderMode | undefined,
@@ -85,13 +87,15 @@ 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.
+ // Design→device scale of one design px this frame beyond DPR (vpW
+ // is device px). The bitmap atlas folds it into rasterization so
+ // static text is hinted at the final on-screen size regardless of
+ // the window/design fit. 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
+ const contentScale = uiCamera?.valid && span > 0
? uiCamera.vpW / (span * dpr)
: 1;
@@ -101,9 +105,12 @@ export class TextPlugin implements Plugin {
if (!t.content) continue;
const tr = world.get(entity, Transform) as TransformData;
+ // Auto routes on the entity's own scale only — the canvas fit
+ // is already compensated in the bitmap rasterization size.
const renderer = this.rendererFor(
app,
- resolveTextRenderMode(t.renderMode, designToTexel * tr.worldScale.x),
+ resolveTextRenderMode(t.renderMode, tr.worldScale.x),
+ contentScale,
);
composeTRS(this.matrix_, tr.worldPosition, tr.worldRotation, tr.worldScale);
@@ -188,7 +195,7 @@ export class TextPlugin implements Plugin {
* 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 {
+ private rendererFor(app: App, kind: 'bitmap' | 'sdf', contentScale: number): SdfTextRenderer {
const module = app.wasmModule as ESEngineModule;
if (kind === 'sdf') {
if (!this.sdfRenderer_) {
@@ -202,6 +209,7 @@ export class TextPlugin implements Plugin {
sdf: false, dpr, renderSize: Math.round(GLYPH_BASE_SIZE * dpr),
});
}
+ this.bitmapRenderer_.setContentScale(contentScale);
return this.bitmapRenderer_;
}
}
diff --git a/sdk/src/ui/text/text-renderer.ts b/sdk/src/ui/text/text-renderer.ts
index ad46b087b..30b3756b3 100644
--- a/sdk/src/ui/text/text-renderer.ts
+++ b/sdk/src/ui/text/text-renderer.ts
@@ -134,6 +134,11 @@ export class SdfTextRenderer {
);
}
+ /** See {@link GlyphAtlas.setContentScale} — no-op for the SDF atlas. */
+ setContentScale(scale: number): void {
+ this.atlas.setContentScale(scale);
+ }
+
/**
* 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/src/ui/widgets/prefabs/Button.esprefab b/sdk/src/ui/widgets/prefabs/Button.esprefab
index 222d2a1c3..bdfa410e3 100644
--- a/sdk/src/ui/widgets/prefabs/Button.esprefab
+++ b/sdk/src/ui/widgets/prefabs/Button.esprefab
@@ -364,7 +364,8 @@
"shadowBlur": 0,
"shadowOffsetX": 0,
"shadowOffsetY": 0,
- "richText": false
+ "richText": false,
+ "renderMode": 0
}
}
],
diff --git a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab b/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
index 66ce35657..3298b7e0f 100644
--- a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
+++ b/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
@@ -364,7 +364,8 @@
"shadowBlur": 0,
"shadowOffsetX": 0,
"shadowOffsetY": 0,
- "richText": false
+ "richText": false,
+ "renderMode": 0
}
}
],
diff --git a/sdk/src/ui/widgets/prefabs/ListView.esprefab b/sdk/src/ui/widgets/prefabs/ListView.esprefab
index 8c38ee176..1e132b002 100644
--- a/sdk/src/ui/widgets/prefabs/ListView.esprefab
+++ b/sdk/src/ui/widgets/prefabs/ListView.esprefab
@@ -329,7 +329,8 @@
"shadowBlur": 0,
"shadowOffsetX": 0,
"shadowOffsetY": 0,
- "richText": false
+ "richText": false,
+ "renderMode": 0
}
}
],
diff --git a/sdk/src/ui/widgets/prefabs/generated.ts b/sdk/src/ui/widgets/prefabs/generated.ts
index 979c11c89..b4e993080 100644
--- a/sdk/src/ui/widgets/prefabs/generated.ts
+++ b/sdk/src/ui/widgets/prefabs/generated.ts
@@ -368,7 +368,8 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"shadowBlur": 0,
"shadowOffsetX": 0,
"shadowOffsetY": 0,
- "richText": false
+ "richText": false,
+ "renderMode": 0
}
}
],
@@ -1888,7 +1889,8 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"shadowBlur": 0,
"shadowOffsetX": 0,
"shadowOffsetY": 0,
- "richText": false
+ "richText": false,
+ "renderMode": 0
}
}
],
@@ -2227,7 +2229,8 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"shadowBlur": 0,
"shadowOffsetX": 0,
"shadowOffsetY": 0,
- "richText": false
+ "richText": false,
+ "renderMode": 0
}
}
],
diff --git a/sdk/tests/ui-text-render-mode.test.ts b/sdk/tests/ui-text-render-mode.test.ts
index 7e811ef97..c06446412 100644
--- a/sdk/tests/ui-text-render-mode.test.ts
+++ b/sdk/tests/ui-text-render-mode.test.ts
@@ -28,15 +28,17 @@ describe('resolveTextRenderMode', () => {
expect(resolveTextRenderMode(TextRenderMode.Sdf, 1)).toBe('sdf');
});
- it('Auto keeps bitmap at (or within 2% of) pixel-exact 1:1', () => {
+ it('Auto keeps bitmap for unscaled entities (within 2% of 1)', () => {
+ // The canvas design-fit is NOT part of this input — the bitmap atlas
+ // compensates it via setContentScale, so only the entity's own world
+ // scale routes here.
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.
+ it('Auto switches to SDF once the entity itself is scaled', () => {
+ // e.g. a pressed-state scale tween or an animated pop-in.
expect(resolveTextRenderMode(TextRenderMode.Auto, 0.82)).toBe('sdf');
expect(resolveTextRenderMode(TextRenderMode.Auto, 1.5)).toBe('sdf');
expect(resolveTextRenderMode(TextRenderMode.Auto, 0.5)).toBe('sdf');
@@ -54,3 +56,22 @@ describe('resolveTextRenderMode', () => {
expect(resolveTextRenderMode(undefined, 0.82)).toBe('sdf');
});
});
+
+describe('GlyphAtlas content scale (bitmap rasterization density)', () => {
+ it('folds the content scale into bitmap pixel sizes, but never SDF', async () => {
+ const { GlyphAtlas } = await import('../src/ui/text/glyph-atlas');
+ const fakeRasterizer = { renderSize: 48, rasterize: () => null };
+ const fakeStore = { createPage: () => 1, uploadRegion: () => {} };
+
+ const bitmap = new GlyphAtlas(fakeRasterizer as never, fakeStore as never, { sdf: false, dpr: 2 });
+ expect(bitmap.pixelSizeFor(13)).toBe(26); // 13 × dpr2
+ bitmap.setContentScale(0.823); // 800×600 design in a smaller view
+ expect(bitmap.pixelSizeFor(13)).toBe(21); // 13 × 2 × 0.823 ≈ 21.4 → hinted at final px
+ bitmap.setContentScale(NaN); // degenerate input resets to 1
+ expect(bitmap.pixelSizeFor(13)).toBe(26);
+
+ const sdf = new GlyphAtlas(fakeRasterizer as never, fakeStore as never, { sdf: true });
+ sdf.setContentScale(0.5);
+ expect(sdf.pixelSizeFor(13)).toBe(48); // SDF is one fixed source
+ });
+});
diff --git a/src/esengine/data/shaders/batch.esshader b/src/esengine/data/shaders/batch.esshader
index 793da15f5..1807293fc 100644
--- a/src/esengine/data/shaders/batch.esshader
+++ b/src/esengine/data/shaders/batch.esshader
@@ -56,12 +56,13 @@ void main() {
else texColor = texture(u_textures[7], v_texCoord);
#ifdef SDF
// The glyph atlas stores a signed distance in the alpha channel (RGB = 1).
- // fwidth tracks the on-screen scale, so a full-fwidth smoothstep band keeps a
- // stable ~1px antialiased edge at any size (this is the scalable SDF path;
- // crisp UI text uses the device-resolution bitmap batch instead).
+ // Dividing the signed distance by its screen-space derivative converts it
+ // to *screen pixels from the edge*; a ±0.5px clamp is then exactly one
+ // pixel of linear coverage ramp — the msdfgen/TMP standard. (A full-fwidth
+ // smoothstep band spans ~2px and reads as blur, not antialiasing.)
float dist = texColor.a;
- float aa = fwidth(dist);
- float coverage = smoothstep(0.5 - aa, 0.5 + aa, dist);
+ float screenPxDist = (dist - 0.5) / max(fwidth(dist), 1e-6);
+ float coverage = clamp(screenPxDist + 0.5, 0.0, 1.0);
fragColor = vec4(v_color.rgb, v_color.a * coverage);
#else
fragColor = texColor * v_color;
diff --git a/src/esengine/renderer/ShaderEmbeds.generated.hpp b/src/esengine/renderer/ShaderEmbeds.generated.hpp
index 930b0d175..55cdb1c08 100644
--- a/src/esengine/renderer/ShaderEmbeds.generated.hpp
+++ b/src/esengine/renderer/ShaderEmbeds.generated.hpp
@@ -60,12 +60,13 @@ void main() {
else texColor = texture(u_textures[7], v_texCoord);
#ifdef SDF
// The glyph atlas stores a signed distance in the alpha channel (RGB = 1).
- // fwidth tracks the on-screen scale, so a full-fwidth smoothstep band keeps a
- // stable ~1px antialiased edge at any size (this is the scalable SDF path;
- // crisp UI text uses the device-resolution bitmap batch instead).
+ // Dividing the signed distance by its screen-space derivative converts it
+ // to *screen pixels from the edge*; a ±0.5px clamp is then exactly one
+ // pixel of linear coverage ramp — the msdfgen/TMP standard. (A full-fwidth
+ // smoothstep band spans ~2px and reads as blur, not antialiasing.)
float dist = texColor.a;
- float aa = fwidth(dist);
- float coverage = smoothstep(0.5 - aa, 0.5 + aa, dist);
+ float screenPxDist = (dist - 0.5) / max(fwidth(dist), 1e-6);
+ float coverage = clamp(screenPxDist + 0.5, 0.0, 1.0);
fragColor = vec4(v_color.rgb, v_color.a * coverage);
#else
fragColor = texColor * v_color;