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(text): Text draws a bitmap font (.fnt) from its page texture, through the same layout as any font; widget prefabs regenerated for the Text box defaults

yhh1f497c035bd4
diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.ts
index 0a5abf085..8c02d77a0 100644
--- a/pipeline/src/import/cocos/components.ts
+++ b/pipeline/src/import/cocos/components.ts
@@ -195,7 +195,10 @@ function label(c: CocosComponent, siblings: CocosComponent[], box: UiBox | null,
}
const outline = siblings.find((s) => s.type === 'cc.LabelOutline' && s.enabled);
- if (outline) {
+ // A bitmap font carries its own outline in the page, so a stroke drawn round it would be a second ring.
+ if (outline && data.font && String(data.font).endsWith('.fnt')) {
+ ctx.report.note('label-outline-baked-in-font', where);
+ } else if (outline) {
data.strokeColor = color(outline.data._color);
data.strokeWidth = num(outline.data._width, 0);
}
diff --git a/sdk/src/asset/loaders/FontAssetLoader.ts b/sdk/src/asset/loaders/FontAssetLoader.ts
index 69b737d1a..c7766c258 100644
--- a/sdk/src/asset/loaders/FontAssetLoader.ts
+++ b/sdk/src/asset/loaders/FontAssetLoader.ts
@@ -8,6 +8,8 @@ import { getPlatform } from '../../platform/base';
import {
freshProjectFontFamily, projectFontFamily, registerProjectFontEra, releaseProjectFontEra,
} from '../../ui/text/font-registry';
+import { parseBmFont, registerBitmapFont, unregisterBitmapFont } from '../../ui/text/bitmap-font';
+import { log } from '../../util/logger';
import type { FontHandle } from '../../types';
/** Outline fonts — rasterized per glyph by the text stack, not pre-baked pages. */
@@ -36,6 +38,7 @@ export class FontAssetLoader implements AssetLoader<FontResult> {
releaseProjectFontEra(asset.handle);
return;
}
+ unregisterBitmapFont(asset.handle);
const rm = requireResourceManager();
rm.releaseBitmapFont(asset.handle);
}
@@ -88,6 +91,15 @@ export class FontAssetLoader implements AssetLoader<FontResult> {
fntContent, texResult.handle, texResult.width, texResult.height,
) as FontHandle;
+ // The same font serves `Text`, which draws it from the page texture with this table — `BitmapText` keeps using the
+ // C++ resource above. A font the parser cannot read still loads for BitmapText; Text just will not find it.
+ try {
+ // the batch binds a page by GL texture id, as it does for the glyph atlas's own pages
+ registerBitmapFont(handle, parseBmFont(fntContent), rm.getTextureGLId(texResult.handle));
+ } catch (err) {
+ log.warn('text', `${path}: not usable by Text as a bitmap font — ${err instanceof Error ? err.message : String(err)}`);
+ }
+
return { handle };
}
}
diff --git a/sdk/src/ui/text/bitmap-font.ts b/sdk/src/ui/text/bitmap-font.ts
new file mode 100644
index 000000000..5bc039a7d
--- /dev/null
+++ b/sdk/src/ui/text/bitmap-font.ts
@@ -0,0 +1,164 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/text/bitmap-font.ts
+ * @brief Bitmap fonts (`.fnt`) as a glyph source for `Text`.
+ *
+ * A `.fnt` is a page image the artist drew plus a table saying where each glyph sits on it. The page is already
+ * a texture the engine holds, so a bitmap font needs nothing the dynamic glyph atlas does: no rasterizing, no
+ * packing, no second copy of the pixels. It answers the atlas's one question — "where is this glyph, and how does
+ * it advance" — straight from the table, with the page's own texture handle as the page id. Everything downstream
+ * of the atlas (wrapping, alignment, the layout box, Shrink, shadow, the outline stamps) then works on a bitmap
+ * font exactly as it does on a system one.
+ *
+ * Metrics stay in the font's own pixels, and the layout scales them by `fontSize / font.size` — the scale a
+ * bitmap-font label has always had in Cocos and Unity.
+ *
+ * This file holds no component and touches no engine: the parser is pure and the registry is a map.
+ */
+import type { GlyphEntry } from './glyph-atlas';
+
+/** One `char` line of a `.fnt`, in the font's pixels (page origin top-left). */
+export interface BmGlyph {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ xoffset: number;
+ yoffset: number;
+ xadvance: number;
+}
+
+/** A parsed `.fnt`: the table and the few numbers the layout needs, with no reference to a texture. */
+export interface BmFont {
+ /** The size the glyphs were drawn at; a label's `fontSize` is a multiple of this. */
+ size: number;
+ /** Distance between two lines, in font pixels. */
+ lineHeight: number;
+ /** Distance from the top of a line to its baseline. */
+ base: number;
+ pageWidth: number;
+ pageHeight: number;
+ /** The first page's image file, as the `.fnt` spells it. */
+ page: string;
+ glyphs: Map<number, BmGlyph>;
+}
+
+function attrs(line: string): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const m of line.matchAll(/(\w+)=("([^"]*)"|\S+)/g)) out[m[1]!] = m[3] ?? m[2]!;
+ return out;
+}
+
+const int = (v: string | undefined, d = 0): number => {
+ const n = v === undefined ? NaN : Number.parseInt(v, 10);
+ return Number.isFinite(n) ? n : d;
+};
+
+/**
+ * Read the text form of a BMFont file. Only the first page is kept — a font spread over several pages would
+ * need one draw per page, and nothing here ships one. Kerning is not applied.
+ * @throws when there is no `common` line or no page: there is nothing to draw from.
+ */
+export function parseBmFont(text: string): BmFont {
+ let size = 0, lineHeight = 0, base = 0, pageWidth = 0, pageHeight = 0, page = '';
+ let sawCommon = false;
+ const glyphs = new Map<number, BmGlyph>();
+ for (const raw of text.split(/\r?\n/)) {
+ const line = raw.trim();
+ if (line.startsWith('info ')) size = Math.abs(int(attrs(line).size));
+ else if (line.startsWith('common ')) {
+ const a = attrs(line);
+ lineHeight = int(a.lineHeight);
+ base = int(a.base);
+ pageWidth = int(a.scaleW);
+ pageHeight = int(a.scaleH);
+ sawCommon = true;
+ } else if (line.startsWith('page ')) {
+ const a = attrs(line);
+ if (!page && int(a.id) === 0) page = a.file ?? '';
+ } else if (line.startsWith('char ')) {
+ const a = attrs(line);
+ if (int(a.page) !== 0) continue;
+ glyphs.set(int(a.id), {
+ x: int(a.x), y: int(a.y), width: int(a.width), height: int(a.height),
+ xoffset: int(a.xoffset), yoffset: int(a.yoffset), xadvance: int(a.xadvance),
+ });
+ }
+ }
+ if (!sawCommon || !page || pageWidth <= 0 || pageHeight <= 0) throw new Error('not a bitmap font: no common line or page');
+ return { size: size || lineHeight, lineHeight, base, pageWidth, pageHeight, page, glyphs };
+}
+
+/** A registered font: the table, and the GL texture id its glyphs are on (what a text batch binds). */
+interface Registered {
+ font: BmFont;
+ texture: number;
+ family: string;
+ entries: Map<number, GlyphEntry | null>;
+}
+
+const byHandle = new Map<number, Registered>();
+const byFamily = new Map<string, Registered>();
+
+/**
+ * Make a loaded bitmap font usable by `Text`. @p handle is the resource handle the asset loader hands back — what
+ * `Text.font` holds — and @p texture the page's GL texture id. Re-registering a handle replaces it.
+ */
+export function registerBitmapFont(handle: number, font: BmFont, texture: number): void {
+ unregisterBitmapFont(handle);
+ const family = `bmfont:${handle}`;
+ const reg: Registered = { font, texture, family, entries: new Map() };
+ byHandle.set(handle, reg);
+ byFamily.set(family, reg);
+}
+
+export function unregisterBitmapFont(handle: number): void {
+ const reg = byHandle.get(handle);
+ if (!reg) return;
+ byHandle.delete(handle);
+ byFamily.delete(reg.family);
+}
+
+/** The family name `Text` lays out with for this font handle, or null when it is not a registered bitmap font. */
+export function bitmapFontFamily(handle: number): string | null {
+ return byHandle.get(handle)?.family ?? null;
+}
+
+/** The font a family names, or null when the family is an ordinary (outline) one. */
+export function bitmapFontOf(family: string): BmFont | null {
+ return byFamily.get(family)?.font ?? null;
+}
+
+/**
+ * Where a glyph is and how it advances, in the font's pixels — the shape the glyph atlas hands to the layout. A
+ * character the font does not draw is null, as it is for a system font with no glyph for it.
+ */
+export function bitmapGlyph(family: string, codepoint: number): GlyphEntry | null {
+ const reg = byFamily.get(family);
+ if (!reg) return null;
+ const cached = reg.entries.get(codepoint);
+ if (cached !== undefined) return cached;
+ const g = reg.font.glyphs.get(codepoint);
+ let entry: GlyphEntry | null = null;
+ if (g) {
+ const { pageWidth: w, pageHeight: h, base } = reg.font;
+ entry = {
+ pageId: reg.texture,
+ u0: g.x / w, v0: g.y / h, u1: (g.x + g.width) / w, v1: (g.y + g.height) / h,
+ width: g.width, height: g.height,
+ advance: g.xadvance,
+ bearingX: g.xoffset,
+ // yoffset runs down from the top of the line; the layout wants the glyph's top above the baseline.
+ bearingY: base - g.yoffset,
+ };
+ }
+ reg.entries.set(codepoint, entry);
+ return entry;
+}
+
+/** Test seam: forget every registration. */
+export function resetBitmapFonts(): void {
+ byHandle.clear();
+ byFamily.clear();
+}
diff --git a/sdk/src/ui/text/font-registry.ts b/sdk/src/ui/text/font-registry.ts
index eaa8d03b2..318a5828f 100644
--- a/sdk/src/ui/text/font-registry.ts
+++ b/sdk/src/ui/text/font-registry.ts
@@ -25,6 +25,7 @@
*/
import { RuntimeConfig } from '../../defaults';
+import { bitmapFontFamily } from './bitmap-font';
/** Distinct from any ResourceManager handle (those count up from small ints). */
const HANDLE_BASE = 0x4000_0000;
@@ -107,7 +108,7 @@ export function unregisterProjectFont(path: string): void {
* "whatever this project uses", which is what makes that project setting real.
*/
export function resolveTextFamily(font: number | undefined, fontFamily: string): string {
- return (font ? projectFontFamily(font) : null) ?? (fontFamily || RuntimeConfig.defaultFontFamily);
+ return (font ? projectFontFamily(font) ?? bitmapFontFamily(font) : null) ?? (fontFamily || RuntimeConfig.defaultFontFamily);
}
/** Test seam: drop every registration. */
diff --git a/sdk/src/ui/text/glyph-atlas.ts b/sdk/src/ui/text/glyph-atlas.ts
index 03ca8d38b..77927fc0a 100644
--- a/sdk/src/ui/text/glyph-atlas.ts
+++ b/sdk/src/ui/text/glyph-atlas.ts
@@ -18,6 +18,7 @@
*/
import { ShelfPacker, type Packer } from '../../util/shelfPack';
import { log } from '../../util/logger';
+import { bitmapFontOf, bitmapGlyph } from './bitmap-font';
/** A glyph rendered to an upload-ready bitmap plus its layout metrics (in render-size px). */
export interface RasterGlyph {
@@ -225,7 +226,10 @@ export class GlyphAtlas {
/** Rasterization size for a display size: SDF uses one fixed source;
* bitmap rasterizes per size at the effective on-screen density. */
- pixelSizeFor(displaySize: number): number {
+ pixelSizeFor(displaySize: number, fontFamily?: string): number {
+ // A bitmap font has one size: the one it was drawn at, which the layout scales from.
+ const bitmap = fontFamily === undefined ? null : bitmapFontOf(fontFamily);
+ if (bitmap) return bitmap.size;
return this.sdf
? this.renderSize
: Math.max(1, Math.round(displaySize * this.dpr * this.contentScale_));
@@ -244,6 +248,8 @@ export class GlyphAtlas {
* Drawable entries follow page lifetime; page-free entries use a bounded LRU.
*/
getGlyph(codepoint: number, fontFamily: string, style = 0, pixelSize = this.renderSize): GlyphEntry | null {
+ // A bitmap font is its own atlas: the glyph is already on a page the engine holds.
+ if (bitmapFontOf(fontFamily)) return bitmapGlyph(fontFamily, codepoint);
const k = this.key(codepoint, fontFamily, style, pixelSize);
const hit = this.cache.get(k);
if (hit !== undefined) return hit;
diff --git a/sdk/src/ui/text/layout.ts b/sdk/src/ui/text/layout.ts
index 72de95bf1..05943a555 100644
--- a/sdk/src/ui/text/layout.ts
+++ b/sdk/src/ui/text/layout.ts
@@ -74,7 +74,7 @@ export function layoutLine(
opts: TextLayoutOptions,
style = 0,
): TextLayout {
- const pixelSize = atlas.pixelSizeFor(opts.fontSizePx);
+ const pixelSize = atlas.pixelSizeFor(opts.fontSizePx, fontFamily);
const scale = opts.fontSizePx / pixelSize;
const spacing = opts.letterSpacing ?? 0;
const glyphs: LaidGlyph[] = [];
@@ -220,7 +220,7 @@ function truncateLine(
export function measureWidth(
text: string, atlas: GlyphAtlas, fontFamily: string, fontSizePx: number, style: number, letterSpacing = 0,
): number {
- const pixelSize = atlas.pixelSizeFor(fontSizePx);
+ const pixelSize = atlas.pixelSizeFor(fontSizePx, fontFamily);
const scale = fontSizePx / pixelSize;
let w = 0;
for (const ch of text) {
@@ -236,7 +236,7 @@ export function measureWidth(
export function measurePrefixWidths(
text: string, atlas: GlyphAtlas, fontFamily: string, fontSizePx: number, style: number, letterSpacing = 0,
): number[] {
- const pixelSize = atlas.pixelSizeFor(fontSizePx);
+ const pixelSize = atlas.pixelSizeFor(fontSizePx, fontFamily);
const scale = fontSizePx / pixelSize;
const advance = (cp: number): number => {
const glyph = atlas.getGlyph(cp, fontFamily, style, pixelSize);
@@ -328,7 +328,7 @@ export function wrapLine(
text: string, atlas: GlyphAtlas, fontFamily: string, fontSizePx: number,
style: number, maxWidth: number, letterSpacing = 0,
): string[] {
- const pixelSize = atlas.pixelSizeFor(fontSizePx);
+ const pixelSize = atlas.pixelSizeFor(fontSizePx, fontFamily);
const scale = fontSizePx / pixelSize;
const append = (width: number, suffix: string): number => {
for (const ch of suffix) {
@@ -509,7 +509,7 @@ function measureRun(
baseSizePx: number, baseStyle: number, spacing: number,
): number {
const runSize = run.fontSize ?? baseSizePx;
- const pixelSize = atlas.pixelSizeFor(runSize);
+ const pixelSize = atlas.pixelSizeFor(runSize, fontFamily);
const scale = runSize / pixelSize;
const style = baseStyle | (run.bold ? UI_TEXT_BOLD : 0) | (run.italic ? UI_TEXT_ITALIC : 0);
let w = 0;
@@ -644,7 +644,7 @@ export function layoutRichRuns(
continue;
}
const runSize = run.fontSize ?? opts.fontSizePx;
- const pixelSize = atlas.pixelSizeFor(runSize);
+ const pixelSize = atlas.pixelSizeFor(runSize, fontFamily);
const scale = runSize / pixelSize;
const style = baseStyle | (run.bold ? UI_TEXT_BOLD : 0) | (run.italic ? UI_TEXT_ITALIC : 0);
const color: RGBA = run.color
diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.ts
index 105ffdcc9..55d64b928 100644
--- a/sdk/src/ui/text/plugin.ts
+++ b/sdk/src/ui/text/plugin.ts
@@ -20,6 +20,7 @@ import { SdfTextRenderer } from './text-renderer';
import type { RGBA } from './layout';
import { composeTRS, rectTextBox, UI_TEXT_BOLD, UI_TEXT_ITALIC } from './text-transform';
import { Text, TextRenderMode, type TextData } from '../core/text';
+import { bitmapFontOf } from './bitmap-font';
import { UINode } from '../core/ui-node';
import { Localization } from '../../i18n/Localization';
import { applyTextLocalization, type TextWorldView } from './localize';
@@ -379,7 +380,9 @@ export class TextPlugin implements Plugin {
const contentScale = screen ? this.screenContentScale(app, dpr) : this.worldContentScale(app, dpr);
const state = screen ? appState.screen : appState.world;
const tr = world.get(entity, Transform) as TransformData;
- const kind = resolveTextRenderMode(t.renderMode, tr.worldScale.x);
+ const family = resolveTextFamily(t.font, t.fontFamily);
+ // A bitmap font has no distance field and one size, so it draws as a bitmap whatever the scale.
+ const kind = bitmapFontOf(family) ? 'bitmap' : resolveTextRenderMode(t.renderMode, tr.worldScale.x);
const renderer = this.rendererFor(app, state, kind, contentScale, dpr);
const previous = appState.retained.get(entity as number);
if (previous && previous.renderer !== renderer) previous.renderer.forget(entity as number);
@@ -418,7 +421,6 @@ export class TextPlugin implements Plugin {
width: t.strokeWidth,
}
: undefined;
- const family = resolveTextFamily(t.font, t.fontFamily);
renderer.retain(
api,
{
@@ -443,7 +445,7 @@ export class TextPlugin implements Plugin {
// The engine orders a boxed label by the UI tree and re-lays it out when the node's size changes; a box
// that is the Text's own is neither, so it is reported as no box (its size reaches layout above).
entity as number, screen, hasBox && frame.ui, t.layer | 0, frame.ui ? w : 0, frame.ui ? h : 0,
- t.renderMode !== TextRenderMode.Bitmap && t.renderMode !== TextRenderMode.Sdf,
+ t.renderMode !== TextRenderMode.Bitmap && t.renderMode !== TextRenderMode.Sdf && !bitmapFontOf(family),
);
appState.retained.set(entity as number, { snap: snapshotOf(t, family), screen, gen: renderer.atlas.generation, renderer });
}
@@ -484,7 +486,7 @@ export class TextPlugin implements Plugin {
const tr = world.get(entity, Transform) as TransformData;
const renderer = this.rendererFor(
app, state,
- resolveTextRenderMode(t.renderMode, tr.worldScale.x),
+ bitmapFontOf(resolveTextFamily(t.font, t.fontFamily)) ? 'bitmap' : resolveTextRenderMode(t.renderMode, tr.worldScale.x),
contentScale,
dpr,
);
diff --git a/sdk/src/ui/widgets/prefabs/Button.esprefab b/sdk/src/ui/widgets/prefabs/Button.esprefab
index 6fe1c76a8..d031d0afe 100644
--- a/sdk/src/ui/widgets/prefabs/Button.esprefab
+++ b/sdk/src/ui/widgets/prefabs/Button.esprefab
@@ -404,6 +404,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
diff --git a/sdk/src/ui/widgets/prefabs/ColorPicker.esprefab b/sdk/src/ui/widgets/prefabs/ColorPicker.esprefab
index 837ffa487..ca46ca76e 100644
--- a/sdk/src/ui/widgets/prefabs/ColorPicker.esprefab
+++ b/sdk/src/ui/widgets/prefabs/ColorPicker.esprefab
@@ -538,6 +538,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
}
@@ -1868,6 +1874,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -2214,6 +2226,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -2560,6 +2578,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -2906,6 +2930,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -3677,6 +3707,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
diff --git a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab b/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
index 7bd68271d..ef5b9db4a 100644
--- a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
+++ b/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
@@ -401,6 +401,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
diff --git a/sdk/src/ui/widgets/prefabs/ListView.esprefab b/sdk/src/ui/widgets/prefabs/ListView.esprefab
index cced7c879..362251311 100644
--- a/sdk/src/ui/widgets/prefabs/ListView.esprefab
+++ b/sdk/src/ui/widgets/prefabs/ListView.esprefab
@@ -336,6 +336,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
diff --git a/sdk/src/ui/widgets/prefabs/TabView.esprefab b/sdk/src/ui/widgets/prefabs/TabView.esprefab
index 88f9c5a74..6efc394fa 100644
--- a/sdk/src/ui/widgets/prefabs/TabView.esprefab
+++ b/sdk/src/ui/widgets/prefabs/TabView.esprefab
@@ -772,6 +772,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -1472,6 +1478,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -2172,6 +2184,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
diff --git a/sdk/src/ui/widgets/prefabs/Tooltip.esprefab b/sdk/src/ui/widgets/prefabs/Tooltip.esprefab
index e2df6c06d..84056f5fe 100644
--- a/sdk/src/ui/widgets/prefabs/Tooltip.esprefab
+++ b/sdk/src/ui/widgets/prefabs/Tooltip.esprefab
@@ -195,6 +195,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
diff --git a/sdk/src/ui/widgets/prefabs/VirtualButton.esprefab b/sdk/src/ui/widgets/prefabs/VirtualButton.esprefab
index 3813b3186..cc83fb569 100644
--- a/sdk/src/ui/widgets/prefabs/VirtualButton.esprefab
+++ b/sdk/src/ui/widgets/prefabs/VirtualButton.esprefab
@@ -404,6 +404,12 @@
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
diff --git a/sdk/src/ui/widgets/prefabs/generated.ts b/sdk/src/ui/widgets/prefabs/generated.ts
index 9a699a4e7..b8dc48dd6 100644
--- a/sdk/src/ui/widgets/prefabs/generated.ts
+++ b/sdk/src/ui/widgets/prefabs/generated.ts
@@ -739,6 +739,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
}
@@ -2069,6 +2075,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -2415,6 +2427,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -2761,6 +2779,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -3107,6 +3131,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -3878,6 +3908,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -4939,6 +4975,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -5639,6 +5681,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -6339,6 +6387,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -6668,6 +6722,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -7590,6 +7650,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -8010,6 +8076,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -10238,6 +10310,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
@@ -10590,6 +10668,12 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"richText": false,
"renderMode": 0,
"layer": 0,
+ "boxWidth": 0,
+ "boxHeight": 0,
+ "boxPivot": {
+ "x": 0.5,
+ "y": 0.5
+ },
"enabled": true
}
},
diff --git a/sdk/tests/ui-text-bitmap-font.test.ts b/sdk/tests/ui-text-bitmap-font.test.ts
new file mode 100644
index 000000000..cfd1fda83
--- /dev/null
+++ b/sdk/tests/ui-text-bitmap-font.test.ts
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui-text-bitmap-font.test.ts — a `.fnt` as a font for `Text`.
+ *
+ * A bitmap font's page is a texture the engine already holds, so the whole job is answering the atlas's question
+ * from the table: where is this glyph, and how does the pen move. What a reader can be wrong about, and what these
+ * pin, is the arithmetic between the file's conventions (a glyph's `yoffset` runs DOWN from the top of the line,
+ * a rect's origin is the page's top-left) and the layout's (a glyph's top is measured UP from the baseline).
+ */
+import { afterEach, describe, expect, it } from 'vitest';
+import { GlyphAtlas, type AtlasPageStore, type GlyphRasterizer } from '../src/ui/text/glyph-atlas';
+import {
+ bitmapFontFamily, bitmapFontOf, bitmapGlyph, parseBmFont, registerBitmapFont, resetBitmapFonts, unregisterBitmapFont,
+} from '../src/ui/text/bitmap-font';
+import { resolveTextFamily } from '../src/ui/text/font-registry';
+import { layoutText, measureWidth } from '../src/ui/text/layout';
+import { TextOverflow } from '../src/ui/core/text';
+
+const FNT = [
+ 'info face="Demo" size=-40 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1',
+ 'common lineHeight=48 base=38 scaleW=512 scaleH=256 pages=1 packed=0',
+ 'page id=0 file="demo_0.png"',
+ 'chars count=4',
+ 'char id=32 x=0 y=0 width=0 height=0 xoffset=0 yoffset=38 xadvance=12 page=0 chnl=15',
+ 'char id=65 x=10 y=20 width=30 height=36 xoffset=2 yoffset=4 xadvance=34 page=0 chnl=15',
+ 'char id=66 x=50 y=20 width=26 height=36 xoffset=1 yoffset=6 xadvance=30 page=0 chnl=15',
+ 'char id=67 x=90 y=20 width=20 height=20 xoffset=0 yoffset=0 xadvance=22 page=1 chnl=15',
+ 'kernings count=0',
+].join('\r\n');
+
+const PAGE_TEXTURE = 7001;
+
+function atlas(): GlyphAtlas {
+ // A rasterizer that must never be asked: a bitmap font is not rasterized.
+ const rasterizer: GlyphRasterizer = {
+ renderSize: 48, spread: 0,
+ rasterize: () => { throw new Error('a bitmap font must not reach the rasterizer'); },
+ };
+ const store: AtlasPageStore = { createPage: () => 1, uploadSubRegion: () => {} };
+ return new GlyphAtlas(rasterizer, store, { pageSize: 256, padding: 1 });
+}
+
+afterEach(() => resetBitmapFonts());
+
+describe('parseBmFont', () => {
+ it('reads the metrics and the glyph table, taking the size as magnitude (a smooth font writes it negative)', () => {
+ const f = parseBmFont(FNT);
+ expect(f).toMatchObject({ size: 40, lineHeight: 48, base: 38, pageWidth: 512, pageHeight: 256, page: 'demo_0.png' });
+ expect(f.glyphs.get(65)).toEqual({ x: 10, y: 20, width: 30, height: 36, xoffset: 2, yoffset: 4, xadvance: 34 });
+ });
+
+ it('keeps the first page only: a glyph on another page is not in the table', () => {
+ expect(parseBmFont(FNT).glyphs.has(67)).toBe(false);
+ });
+
+ it('refuses what is not a bitmap font, rather than registering a font with nothing in it', () => {
+ expect(() => parseBmFont('hello')).toThrow(/not a bitmap font/);
+ expect(() => parseBmFont('common lineHeight=10 base=8 scaleW=64 scaleH=64')).toThrow(/not a bitmap font/);
+ });
+});
+
+describe('the glyph a bitmap font answers with', () => {
+ it('places a glyph by its rect over the page, with v counted from the page top as the atlas counts it', () => {
+ registerBitmapFont(5, parseBmFont(FNT), PAGE_TEXTURE);
+ const g = bitmapGlyph(bitmapFontFamily(5)!, 65)!;
+ expect(g.pageId).toBe(PAGE_TEXTURE);
+ expect([g.u0, g.v0, g.u1, g.v1]).toEqual([10 / 512, 20 / 256, 40 / 512, 56 / 256]);
+ expect([g.width, g.height, g.advance]).toEqual([30, 36, 34]);
+ });
+
+ it('turns yoffset (down from the line top) into a bearing (up from the baseline)', () => {
+ registerBitmapFont(5, parseBmFont(FNT), PAGE_TEXTURE);
+ // base 38, yoffset 4: the glyph's top is 34 above the baseline; the second sits 2 lower
+ expect(bitmapGlyph('bmfont:5', 65)!.bearingY).toBe(34);
+ expect(bitmapGlyph('bmfont:5', 66)!.bearingY).toBe(32);
+ expect(bitmapGlyph('bmfont:5', 65)!.bearingX).toBe(2);
+ });
+
+ it('answers a space with an advance and no quad, and a character the font lacks with nothing', () => {
+ registerBitmapFont(5, parseBmFont(FNT), PAGE_TEXTURE);
+ expect(bitmapGlyph('bmfont:5', 32)).toMatchObject({ width: 0, height: 0, advance: 12 });
+ expect(bitmapGlyph('bmfont:5', 0x4e2d)).toBeNull();
+ });
+
+ it('is not a bitmap font for a family that was never registered, or was released', () => {
+ registerBitmapFont(5, parseBmFont(FNT), PAGE_TEXTURE);
+ expect(bitmapFontOf('Arial')).toBeNull();
+ unregisterBitmapFont(5);
+ expect(bitmapFontOf('bmfont:5')).toBeNull();
+ expect(bitmapFontFamily(5)).toBeNull();
+ });
+});
+
+describe('Text laying out with a bitmap font', () => {
+ it('resolves a registered handle to its family, ahead of the authored family name', () => {
+ registerBitmapFont(5, parseBmFont(FNT), PAGE_TEXTURE);
+ expect(resolveTextFamily(5, 'Arial')).toBe('bmfont:5');
+ expect(resolveTextFamily(0, 'Arial')).toBe('Arial');
+ });
+
+ it('never rasterizes: the atlas answers from the table', () => {
+ registerBitmapFont(5, parseBmFont(FNT), PAGE_TEXTURE);
+ const a = atlas();
+ expect(a.getGlyph(65, 'bmfont:5')).not.toBeNull();
+ expect(a.pixelSizeFor(77, 'bmfont:5')).toBe(40); // the size the font was drawn at, whatever is asked
+ });
+
+ it('scales the font\'s metrics by fontSize over the size it was drawn at', () => {
+ registerBitmapFont(5, parseBmFont(FNT), PAGE_TEXTURE);
+ const a = atlas();
+ // "AB": 34 + 30 advance at the native size 40
+ expect(measureWidth('AB', a, 'bmfont:5', 40, 0)).toBeCloseTo(64);
+ expect(measureWidth('AB', a, 'bmfont:5', 20, 0)).toBeCloseTo(32);
+ expect(measureWidth('AB', a, 'bmfont:5', 80, 0)).toBeCloseTo(128);
+ });
+
+ it('lays a glyph quad out from its bearing, at the scale asked for', () => {
+ registerBitmapFont(5, parseBmFont(FNT), PAGE_TEXTURE);
+ const l = layoutText('A', atlas(), 'bmfont:5', { fontSizePx: 20 });
+ const q = l.glyphs[0]!;
+ // scale 0.5: left at xoffset*0.5, top 34*0.5 above the baseline, 15 wide, 18 tall
+ expect(q.x0).toBeCloseTo(1);
+ expect(q.x1).toBeCloseTo(16);
+ expect(q.y1).toBeCloseTo(17);
+ expect(q.y0).toBeCloseTo(-1);
+ expect(q.pageId).toBe(PAGE_TEXTURE);
+ });
+
+ it('wraps and shrinks like any font, because it goes through the same layout', () => {
+ registerBitmapFont(5, parseBmFont(FNT), PAGE_TEXTURE);
+ const a = atlas();
+ const l = layoutText('ABABAB', a, 'bmfont:5', {
+ fontSizePx: 40, lineHeight: 48, boxWidth: 100, boxHeight: 100, overflow: TextOverflow.Shrink,
+ });
+ expect(l.fontSizePx).toBeLessThan(40);
+ expect(l.width).toBeLessThanOrEqual(100 + 1e-6);
+ });
+});