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): a game can ship its own font

yhh5641ca13cdbc
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 841ac125f..11000b454 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -64,7 +64,7 @@ _filterType: "added"
## AddressableAssetType — type
```
-| 'texture' | 'material' | 'spine' | 'bitmap-font'
+| 'texture' | 'material' | 'spine' | 'bitmap-font' | 'font'
| 'prefab' | 'json' | 'text' | 'binary' | 'audio'
```
@@ -2480,7 +2480,7 @@ ui_getRenderOrder: ((registry: CppRegistry, entity: number) => number) | undefin
```
| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'
| 'dragonbones-atlas' | 'dragonbones-skeleton'
- | 'bitmap-font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'
+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'
| 'tilemap' | 'tileset' | 'timeline'
| 'unknown'
```
@@ -4696,6 +4696,7 @@ rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | unde
readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined
readFile: (path: string) => Promise<ArrayBuffer>
readTextFile: (path: string) => Promise<string>
+registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined
removeStorageItem: (key: string) => void
setStorageItem: (key: string, value: string) => void
unbindInputEvents: (() => void) | undefined
@@ -6685,6 +6686,7 @@ bold: boolean
color: Color
content: string
enabled: boolean
+font: number
fontFamily: string
fontSize: number
i18nKey: string
@@ -6710,6 +6712,7 @@ bold: boolean | undefined
color: Color | undefined
content: string | undefined
enabled: boolean | undefined
+font: number | undefined
fontFamily: string | undefined
fontSize: number | undefined
i18nKey: string | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 0f932a21f..4a8afb2ea 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -64,7 +64,7 @@ _filterType: "added"
## AddressableAssetType — type
```
-| 'texture' | 'material' | 'spine' | 'bitmap-font'
+| 'texture' | 'material' | 'spine' | 'bitmap-font' | 'font'
| 'prefab' | 'json' | 'text' | 'binary' | 'audio'
```
@@ -2488,7 +2488,7 @@ ui_getRenderOrder: ((registry: CppRegistry, entity: number) => number) | undefin
```
| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'
| 'dragonbones-atlas' | 'dragonbones-skeleton'
- | 'bitmap-font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'
+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'
| 'tilemap' | 'tileset' | 'timeline'
| 'unknown'
```
@@ -4850,6 +4850,7 @@ rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | unde
readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined
readFile: (path: string) => Promise<ArrayBuffer>
readTextFile: (path: string) => Promise<string>
+registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined
removeStorageItem: (key: string) => void
setStorageItem: (key: string, value: string) => void
unbindInputEvents: (() => void) | undefined
@@ -6849,6 +6850,7 @@ bold: boolean
color: Color
content: string
enabled: boolean
+font: number
fontFamily: string
fontSize: number
i18nKey: string
@@ -6874,6 +6876,7 @@ bold: boolean | undefined
color: Color | undefined
content: string | undefined
enabled: boolean | undefined
+font: number | undefined
fontFamily: string | undefined
fontSize: number | undefined
i18nKey: string | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index d77989adf..bb34e28b3 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -59,7 +59,7 @@ _filterType: "added"
## AddressableAssetType — type
```
-| 'texture' | 'material' | 'spine' | 'bitmap-font'
+| 'texture' | 'material' | 'spine' | 'bitmap-font' | 'font'
| 'prefab' | 'json' | 'text' | 'binary' | 'audio'
```
@@ -2475,7 +2475,7 @@ ui_getRenderOrder: ((registry: CppRegistry, entity: number) => number) | undefin
```
| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'
| 'dragonbones-atlas' | 'dragonbones-skeleton'
- | 'bitmap-font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'
+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'
| 'tilemap' | 'tileset' | 'timeline'
| 'unknown'
```
@@ -4691,6 +4691,7 @@ rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | unde
readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined
readFile: (path: string) => Promise<ArrayBuffer>
readTextFile: (path: string) => Promise<string>
+registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined
removeStorageItem: (key: string) => void
setStorageItem: (key: string, value: string) => void
unbindInputEvents: (() => void) | undefined
@@ -6680,6 +6681,7 @@ bold: boolean
color: Color
content: string
enabled: boolean
+font: number
fontFamily: string
fontSize: number
i18nKey: string
@@ -6705,6 +6707,7 @@ bold: boolean | undefined
color: Color | undefined
content: string | undefined
enabled: boolean | undefined
+font: number | undefined
fontFamily: string | undefined
fontSize: number | undefined
i18nKey: string | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 03cef0c22..5bd35132c 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -59,7 +59,7 @@ _filterType: "added"
## AddressableAssetType — type
```
-| 'texture' | 'material' | 'spine' | 'bitmap-font'
+| 'texture' | 'material' | 'spine' | 'bitmap-font' | 'font'
| 'prefab' | 'json' | 'text' | 'binary' | 'audio'
```
@@ -2475,7 +2475,7 @@ ui_getRenderOrder: ((registry: CppRegistry, entity: number) => number) | undefin
```
| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'
| 'dragonbones-atlas' | 'dragonbones-skeleton'
- | 'bitmap-font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'
+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'
| 'tilemap' | 'tileset' | 'timeline'
| 'unknown'
```
@@ -4906,6 +4906,7 @@ rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | unde
readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined
readFile: (path: string) => Promise<ArrayBuffer>
readTextFile: (path: string) => Promise<string>
+registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined
removeStorageItem: (key: string) => void
setStorageItem: (key: string, value: string) => void
unbindInputEvents: (() => void) | undefined
@@ -6895,6 +6896,7 @@ bold: boolean
color: Color
content: string
enabled: boolean
+font: number
fontFamily: string
fontSize: number
i18nKey: string
@@ -6920,6 +6922,7 @@ bold: boolean | undefined
color: Color | undefined
content: string | undefined
enabled: boolean | undefined
+font: number | undefined
fontFamily: string | undefined
fontSize: number | undefined
i18nKey: string | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 11ac13bd6..a49203dc7 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -59,7 +59,7 @@ _filterType: "added"
## AddressableAssetType — type
```
-| 'texture' | 'material' | 'spine' | 'bitmap-font'
+| 'texture' | 'material' | 'spine' | 'bitmap-font' | 'font'
| 'prefab' | 'json' | 'text' | 'binary' | 'audio'
```
@@ -2475,7 +2475,7 @@ ui_getRenderOrder: ((registry: CppRegistry, entity: number) => number) | undefin
```
| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'
| 'dragonbones-atlas' | 'dragonbones-skeleton'
- | 'bitmap-font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'
+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'
| 'tilemap' | 'tileset' | 'timeline'
| 'unknown'
```
@@ -4698,6 +4698,7 @@ rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | unde
readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined
readFile: (path: string) => Promise<ArrayBuffer>
readTextFile: (path: string) => Promise<string>
+registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined
removeStorageItem: (key: string) => void
setStorageItem: (key: string, value: string) => void
unbindInputEvents: (() => void) | undefined
@@ -6687,6 +6688,7 @@ bold: boolean
color: Color
content: string
enabled: boolean
+font: number
fontFamily: string
fontSize: number
i18nKey: string
@@ -6712,6 +6714,7 @@ bold: boolean | undefined
color: Color | undefined
content: string | undefined
enabled: boolean | undefined
+font: number | undefined
fontFamily: string | undefined
fontSize: number | undefined
i18nKey: string | undefined
diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.ts
index da3ba66e8..ad2e6afc5 100644
--- a/sdk/src/asset/AssetLoader.ts
+++ b/sdk/src/asset/AssetLoader.ts
@@ -32,6 +32,12 @@ export interface MaterialResult {
export interface FontResult {
handle: FontHandle;
+ /** Outline fonts (.ttf/.otf/.woff) only: the family name the font was
+ * registered with, which is what `Text` rasterizes against. Absent for
+ * bitmap fonts, whose handle IS the resource. */
+ family?: string;
+ /** Outline fonts only: the source path, so unload can drop the registration. */
+ path?: string;
}
export interface AudioResult {
diff --git a/sdk/src/asset/loaders/FontAssetLoader.ts b/sdk/src/asset/loaders/FontAssetLoader.ts
index dc4f943cf..d186816cd 100644
--- a/sdk/src/asset/loaders/FontAssetLoader.ts
+++ b/sdk/src/asset/loaders/FontAssetLoader.ts
@@ -3,13 +3,25 @@
import type { AssetLoader, LoadContext, FontResult } from '../AssetLoader';
import { requireResourceManager } from '../../resourceManager';
import { getAssetTypeEntry } from '../../assetTypes';
+import { getPlatform } from '../../platform/base';
+import {
+ familyNameFor, projectFontFamily, registerProjectFont, unregisterProjectFont,
+} from '../../ui/text/font-registry';
import type { FontHandle } from '../../types';
+/** Outline fonts — rasterized per glyph by the text stack, not pre-baked pages. */
+const OUTLINE_RE = /\.(ttf|otf|woff2?)$/i;
+
export class FontAssetLoader implements AssetLoader<FontResult> {
readonly type = 'font';
- readonly extensions = ['.bmfont', '.fnt'];
+ readonly extensions = ['.bmfont', '.fnt', '.ttf', '.otf', '.woff', '.woff2'];
async load(path: string, ctx: LoadContext): Promise<FontResult> {
+ // Two genuinely different things share the `font` asset type: a bitmap
+ // font is a pre-baked page + metrics (a C++ resource, drawn by
+ // BitmapText), an outline font is a file the platform's text stack
+ // rasterizes on demand (used by Text). They diverge here and nowhere else.
+ if (OUTLINE_RE.test(path)) return this.loadOutlineFont(path, ctx);
const entry = getAssetTypeEntry(path);
if (entry?.editorType === 'bitmap-font' && entry.contentType === 'json') {
return this.loadBmfontJson(path, ctx);
@@ -18,10 +30,28 @@ export class FontAssetLoader implements AssetLoader<FontResult> {
}
unload(asset: FontResult): void {
+ // A project font has no C++ resource — only a registration and a name.
+ if (projectFontFamily(asset.handle) !== null) {
+ unregisterProjectFont(asset.path ?? '');
+ return;
+ }
const rm = requireResourceManager();
rm.releaseBitmapFont(asset.handle);
}
+ /**
+ * Hand the file to the platform's text stack under a minted family name, so
+ * `Text` can name a shipped font exactly as it names a system one. A host
+ * with no `registerFont` (a headless realm) still resolves and returns a
+ * handle — the family simply will not rasterize, and Text falls back.
+ */
+ private async loadOutlineFont(path: string, ctx: LoadContext): Promise<FontResult> {
+ const family = familyNameFor(path);
+ const bytes = await ctx.loadBinary(ctx.catalog.getBuildPath(path));
+ await getPlatform().registerFont?.(family, bytes);
+ return { handle: registerProjectFont(path, family) as FontHandle, family, path };
+ }
+
private async loadBmfontJson(path: string, ctx: LoadContext): Promise<FontResult> {
const buildPath = ctx.catalog.getBuildPath(path);
const text = await ctx.loadText(buildPath);
diff --git a/sdk/src/assetTypes.ts b/sdk/src/assetTypes.ts
index a754f459a..adff601d6 100644
--- a/sdk/src/assetTypes.ts
+++ b/sdk/src/assetTypes.ts
@@ -3,13 +3,13 @@
export type AssetContentType = 'json' | 'text' | 'binary' | 'image' | 'audio';
export type AddressableAssetType =
- | 'texture' | 'material' | 'spine' | 'bitmap-font'
+ | 'texture' | 'material' | 'spine' | 'bitmap-font' | 'font'
| 'prefab' | 'json' | 'text' | 'binary' | 'audio';
export type EditorAssetType =
| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'
| 'dragonbones-atlas' | 'dragonbones-skeleton'
- | 'bitmap-font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'
+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'
| 'tilemap' | 'tileset' | 'timeline'
| 'unknown';
@@ -63,6 +63,10 @@ const ASSET_TYPE_REGISTRY: readonly AssetTypeEntry[] = [
{ extensions: ['inputmap'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: false },
{ extensions: ['bmfont'], contentType: 'json', editorType: 'bitmap-font', addressableType: 'bitmap-font', wechatPackInclude: true, hasTransitiveDeps: true },
{ extensions: ['fnt'], contentType: 'text', editorType: 'bitmap-font', addressableType: 'bitmap-font', wechatPackInclude: true, hasTransitiveDeps: true },
+ // Outline fonts a game SHIPS (Text.font). Unlike a bitmap font these have no
+ // page texture, so no transitive deps — the file IS the asset, handed whole
+ // to the platform's text stack.
+ { extensions: ['ttf', 'otf', 'woff', 'woff2'], contentType: 'binary', editorType: 'font', addressableType: 'font', wechatPackInclude: true, hasTransitiveDeps: false },
{ extensions: ['esprefab'], contentType: 'json', editorType: 'prefab', addressableType: 'prefab', wechatPackInclude: true, hasTransitiveDeps: true },
{ extensions: ['esscene'], contentType: 'json', editorType: 'scene', addressableType: null, wechatPackInclude: false, hasTransitiveDeps: false },
{ extensions: ['esanim'], contentType: 'json', editorType: 'anim-clip', addressableType: null, wechatPackInclude: true, hasTransitiveDeps: true },
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index ca6d6c5a5..992eadc18 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -398,6 +398,20 @@ export interface PlatformAdapter {
*/
rasterizeGlyph?(request: PlatformGlyphRequest): PlatformGlyph | null;
+ /**
+ * Make a font file the app SHIPS usable under `family`, so `Text` can name
+ * it the same way it names a system font. Every platform resolves a family
+ * through its own text stack — Canvas2D on the web, the OS matcher on native
+ * — and none of them can see a file inside the project, so a shipped font
+ * has to be handed to that stack explicitly. This is that hand-off; the font
+ * asset loader calls it once per font.
+ *
+ * Optional: a host without it simply has no project fonts, and `Text` falls
+ * back to `fontFamily` (documented behaviour, not a silent failure).
+ * Resolves when the family is ready to rasterize with.
+ */
+ registerFont?(family: string, bytes: ArrayBuffer): Promise<void>;
+
/**
* The OS text-editing surface for editable fields (see
* {@link PlatformTextEditor}). Optional — a host without one (a headless
diff --git a/sdk/src/platform/web.ts b/sdk/src/platform/web.ts
index 5eecefee6..70014ca04 100644
--- a/sdk/src/platform/web.ts
+++ b/sdk/src/platform/web.ts
@@ -131,6 +131,18 @@ class WebPlatformAdapter implements PlatformAdapter {
return createWebTextEditor();
}
+ /** Hand a shipped font to the browser's font stack, which is what Canvas2D
+ * resolves `ctx.font` families against. `document.fonts` is the only route:
+ * a file on disk (or behind `estella://`) is invisible to Canvas2D until a
+ * FontFace for it is added to the document. */
+ async registerFont(family: string, bytes: ArrayBuffer): Promise<void> {
+ if (typeof FontFace === 'undefined' || typeof document === 'undefined') return;
+ const face = new FontFace(family, bytes);
+ await face.load();
+ // `FontFaceSet.add` predates the lib.dom typing we compile against.
+ (document.fonts as unknown as { add(f: FontFace): void }).add(face);
+ }
+
createCanvas(width: number, height: number): PlatformCanvas {
let canvas: HTMLCanvasElement | OffscreenCanvas;
if (typeof OffscreenCanvas !== 'undefined') {
diff --git a/sdk/src/ui/core/compose.ts b/sdk/src/ui/core/compose.ts
index 7a231642f..1af68c43f 100644
--- a/sdk/src/ui/core/compose.ts
+++ b/sdk/src/ui/core/compose.ts
@@ -136,6 +136,7 @@ export function buildText(init: TextInit = {}): TextData {
return {
content: init.content ?? '',
i18nKey: init.i18nKey ?? '',
+ font: init.font ?? 0,
fontFamily: init.fontFamily ?? 'Arial',
fontSize: init.fontSize ?? 14,
color: init.color ?? { r: 1, g: 1, b: 1, a: 1 },
diff --git a/sdk/src/ui/core/text.ts b/sdk/src/ui/core/text.ts
index 7b32fe284..f031718ae 100644
--- a/sdk/src/ui/core/text.ts
+++ b/sdk/src/ui/core/text.ts
@@ -45,6 +45,15 @@ export interface TextData {
* Localization resource ⇒ `content` stands as authored.
*/
i18nKey: string;
+ /**
+ * A font asset the game SHIPS (`.ttf` / `.otf` / `.woff`). When set it wins
+ * over {@link fontFamily}: the loader registers the file with the platform's
+ * text stack and this handle resolves back to that family. Leave it empty to
+ * name a font the host already has, through `fontFamily`.
+ */
+ font: number;
+ /** Font family resolved by the platform's text stack — a font the HOST
+ * already has. For a font you ship, use {@link font} instead. */
fontFamily: string;
fontSize: number;
color: Color;
@@ -70,6 +79,7 @@ export interface TextData {
export const Text = defineComponent<TextData>('Text', {
content: '',
i18nKey: '',
+ font: 0,
fontFamily: 'Arial',
fontSize: 24,
color: { r: 1, g: 1, b: 1, a: 1 },
@@ -90,7 +100,13 @@ export const Text = defineComponent<TextData>('Text', {
renderMode: TextRenderMode.Auto,
enabled: true,
}, {
+ // A shipped font is a real asset reference: declaring it here is what gives
+ // it dependency tracking, cook inclusion, `@uuid:` refs and hot-update for
+ // free — the same machinery every other asset slot rides.
+ assetFields: [{ field: 'font', type: 'font' }],
fields: {
+ font: { label: 'Font', tooltip: 'A font file this project ships (.ttf / .otf). Overrides Font Family when set; leave empty to use a font the host already has.' },
+ fontFamily: { tooltip: 'A font the HOST already has (system or page-loaded). Ignored when Font is set.' },
i18nKey: { label: 'I18n Key', enumSource: 'localeKeys', tooltip: 'Localization key — when set, content is resolved from the Localization catalogs (and re-resolved on locale switch). Leave empty for plain text.' },
align: { enum: enumOptions(TextAlign), tooltip: 'Horizontal alignment: within the layout box when the entity has a UINode, else it anchors the text to the entity origin (left/center/right edge).' },
verticalAlign: { enum: enumOptions(TextVerticalAlign), tooltip: 'Vertical alignment: within the layout box when the entity has a UINode, else it anchors the text to the entity origin (top/middle/bottom).' },
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 676558ea9..d5d5e9c67 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -453,6 +453,12 @@ export {
type TextRendererOptions,
} from './text/text-renderer';
+export {
+ familyNameFor,
+ projectFontFamily,
+ resolveTextFamily,
+} from './text/font-registry';
+
export {
GlyphAtlas,
type GlyphRasterizer,
diff --git a/sdk/src/ui/text/font-registry.ts b/sdk/src/ui/text/font-registry.ts
new file mode 100644
index 000000000..cb555d260
--- /dev/null
+++ b/sdk/src/ui/text/font-registry.ts
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/text/font-registry.ts
+ * @brief Project fonts: the handle ↔ family-name map for shipped font files.
+ *
+ * The whole text pipeline — layout, the glyph atlas cache key, every rasterizer
+ * — speaks ONE language for "which typeface": a family name string. A system
+ * font already has one. A font the game ships does not, until the platform's
+ * text stack is told about it (browser `FontFace`, the native host's font
+ * table), and that registration needs a name to file it under.
+ *
+ * This module owns that name. The font asset loader mints one per font asset,
+ * registers the bytes with the platform under it, and gets back a handle to
+ * store in `Text.font`; the text plugin turns that handle back into the family
+ * it passes down the pipeline. Nothing downstream of the plugin changes — which
+ * is the point: shipped fonts are not a second text path, just another way to
+ * arrive at a family name.
+ *
+ * Handles are allocated from a HIGH base so they can never be confused with the
+ * C++ bitmap-font handles `BitmapText.font` holds: both live in the same
+ * `font`-typed asset slot vocabulary, and a `.fnt` assigned to `Text.font`
+ * must miss this table (falling back to `fontFamily`) rather than alias a
+ * project font that happens to share a small integer.
+ */
+
+/** Distinct from any ResourceManager handle (those count up from small ints). */
+const HANDLE_BASE = 0x4000_0000;
+
+let nextHandle = HANDLE_BASE;
+
+/** handle → family name. */
+const families = new Map<number, string>();
+/** asset path → handle, so re-loading the same font is idempotent. */
+const byPath = new Map<string, number>();
+
+/** A CSS-safe, collision-free family name for a font asset path. */
+export function familyNameFor(path: string): string {
+ const stem = (path.split('/').pop() ?? path).replace(/\.[^.]+$/, '');
+ const safe = stem.replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '') || 'font';
+ // The path suffix keeps two same-named fonts in different folders apart —
+ // a family name is a global key in every platform's text stack.
+ const tag = Math.abs([...path].reduce((h, c) => (h * 31 + c.charCodeAt(0)) | 0, 0)).toString(36);
+ return `es-${safe}-${tag}`;
+}
+
+/**
+ * Record a registered project font and return its handle. Idempotent per path:
+ * loading the same asset twice yields the same handle, so scene reloads and
+ * multiple referencing entities share one registration.
+ */
+export function registerProjectFont(path: string, family: string): number {
+ const existing = byPath.get(path);
+ if (existing !== undefined) return existing;
+ const handle = nextHandle++;
+ families.set(handle, family);
+ byPath.set(path, handle);
+ return handle;
+}
+
+/** The family name for a handle, or null when it is not a project font. */
+export function projectFontFamily(handle: number): string | null {
+ return families.get(handle) ?? null;
+}
+
+/** Forget a project font (asset unload). The family stays registered with the
+ * platform — browsers offer no removal that is safe while glyphs may be cached. */
+export function unregisterProjectFont(path: string): void {
+ const handle = byPath.get(path);
+ if (handle === undefined) return;
+ byPath.delete(path);
+ families.delete(handle);
+}
+
+/**
+ * The family a `Text` should rasterize with: its project font when `font` names
+ * one, else the authored `fontFamily`. The single place that precedence lives.
+ */
+export function resolveTextFamily(font: number | undefined, fontFamily: string): string {
+ return (font ? projectFontFamily(font) : null) ?? fontFamily;
+}
+
+/** Test seam: drop every registration. */
+export function resetProjectFonts(): void {
+ families.clear();
+ byPath.clear();
+ nextHandle = HANDLE_BASE;
+}
diff --git a/sdk/src/ui/text/inline-image-plugin.ts b/sdk/src/ui/text/inline-image-plugin.ts
index 1a3e42d53..4f2018782 100644
--- a/sdk/src/ui/text/inline-image-plugin.ts
+++ b/sdk/src/ui/text/inline-image-plugin.ts
@@ -18,6 +18,7 @@
*/
import type { App, Plugin } from '../../app';
import { defineSystem, Schedule } from '../../system';
+import { resolveTextFamily } from './font-registry';
import type { Entity } from '../../types';
import type { ESEngineModule } from '../../wasm';
import { Text, TextVerticalAlign, type TextData } from '../core/text';
@@ -101,7 +102,7 @@ export class InlineImagePlugin implements Plugin {
const box = rectTextBox(0.5, 0.5, w, h, t.fontSize);
const style = (t.bold ? UI_TEXT_BOLD : 0) | (t.italic ? UI_TEXT_ITALIC : 0);
- const layout = layoutText(t.content, atlas(), t.fontFamily, {
+ const layout = layoutText(t.content, atlas(), resolveTextFamily(t.font, t.fontFamily), {
fontSizePx: t.fontSize,
lineHeight: t.lineHeight > 0 ? t.lineHeight * t.fontSize : undefined,
align: t.align,
diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.ts
index 01c236929..b32bb072c 100644
--- a/sdk/src/ui/text/plugin.ts
+++ b/sdk/src/ui/text/plugin.ts
@@ -23,6 +23,7 @@ import { Localization } from '../../i18n/Localization';
import { applyTextLocalization, type TextWorldView } from './localize';
import { UICameraInfo, type UICameraData } from '../core/ui-camera-info';
import { getUINodeWidth, getUINodeHeight, ensureUIVisual } from '../util/helpers';
+import { resolveTextFamily } from './font-registry';
import { platformDevicePixelRatio } from '../../platform';
import { engineApi } from '../../ecs/engineApi';
@@ -170,7 +171,7 @@ export class TextPlugin implements Plugin {
renderer.drawText(
{
text: t.content,
- fontFamily: t.fontFamily,
+ fontFamily: resolveTextFamily(t.font, t.fontFamily),
fontSizePx: t.fontSize,
color: [t.color.r, t.color.g, t.color.b, t.color.a],
style,
diff --git a/sdk/src/ui/widgets/prefabs/Button.esprefab b/sdk/src/ui/widgets/prefabs/Button.esprefab
index e43327f93..89f271fd9 100644
--- a/sdk/src/ui/widgets/prefabs/Button.esprefab
+++ b/sdk/src/ui/widgets/prefabs/Button.esprefab
@@ -364,6 +364,7 @@
"data": {
"content": "Button",
"i18nKey": "",
+ "font": 0,
"fontFamily": "Arial",
"fontSize": 14,
"color": {
diff --git a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab b/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
index 6ec74ad0b..918d0f0d0 100644
--- a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
+++ b/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
@@ -361,6 +361,7 @@
"data": {
"content": "One",
"i18nKey": "",
+ "font": 0,
"fontFamily": "Arial",
"fontSize": 14,
"color": {
diff --git a/sdk/src/ui/widgets/prefabs/ListView.esprefab b/sdk/src/ui/widgets/prefabs/ListView.esprefab
index e0e4e1a68..b48a805f5 100644
--- a/sdk/src/ui/widgets/prefabs/ListView.esprefab
+++ b/sdk/src/ui/widgets/prefabs/ListView.esprefab
@@ -296,6 +296,7 @@
"data": {
"content": "List View",
"i18nKey": "",
+ "font": 0,
"fontFamily": "Arial",
"fontSize": 14,
"color": {
diff --git a/sdk/src/ui/widgets/prefabs/generated.ts b/sdk/src/ui/widgets/prefabs/generated.ts
index 2ed991f17..00794679d 100644
--- a/sdk/src/ui/widgets/prefabs/generated.ts
+++ b/sdk/src/ui/widgets/prefabs/generated.ts
@@ -368,6 +368,7 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"data": {
"content": "Button",
"i18nKey": "",
+ "font": 0,
"fontFamily": "Arial",
"fontSize": 14,
"color": {
@@ -2560,6 +2561,7 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"data": {
"content": "One",
"i18nKey": "",
+ "font": 0,
"fontFamily": "Arial",
"fontSize": 14,
"color": {
@@ -2905,6 +2907,7 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"data": {
"content": "List View",
"i18nKey": "",
+ "font": 0,
"fontFamily": "Arial",
"fontSize": 14,
"color": {
diff --git a/sdk/tests/font-registry.test.ts b/sdk/tests/font-registry.test.ts
new file mode 100644
index 000000000..00ae43344
--- /dev/null
+++ b/sdk/tests/font-registry.test.ts
@@ -0,0 +1,90 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Project fonts: the handle ↔ family map that lets `Text` name a font the
+ * game SHIPS the same way it names a system font.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ familyNameFor, registerProjectFont, projectFontFamily, unregisterProjectFont,
+ resolveTextFamily, resetProjectFonts,
+} from '../src/ui/text/font-registry';
+
+beforeEach(() => resetProjectFonts());
+
+describe('familyNameFor', () => {
+ it('derives a CSS-safe family from the file stem', () => {
+ expect(familyNameFor('assets/fonts/PassionOne-Regular.ttf')).toMatch(/^es-PassionOne-Regular-[0-9a-z]+$/);
+ });
+
+ it('sanitizes characters a CSS family cannot carry', () => {
+ expect(familyNameFor('assets/f/My Font (bold)!.otf')).toMatch(/^es-My-Font-bold-[0-9a-z]+$/);
+ });
+
+ it('keeps same-named fonts in different folders apart', () => {
+ const a = familyNameFor('assets/a/Body.ttf');
+ const b = familyNameFor('assets/b/Body.ttf');
+ expect(a).not.toBe(b);
+ });
+
+ it('is stable for the same path', () => {
+ expect(familyNameFor('assets/x/Body.ttf')).toBe(familyNameFor('assets/x/Body.ttf'));
+ });
+
+ it('still produces a usable family for a nameless file', () => {
+ expect(familyNameFor('.ttf')).toMatch(/^es-font-[0-9a-z]+$/);
+ });
+});
+
+describe('registerProjectFont', () => {
+ it('maps a handle back to its family', () => {
+ const h = registerProjectFont('a.ttf', 'es-a');
+ expect(projectFontFamily(h)).toBe('es-a');
+ });
+
+ it('is idempotent per path, so reloads share one handle', () => {
+ const first = registerProjectFont('a.ttf', 'es-a');
+ expect(registerProjectFont('a.ttf', 'es-a')).toBe(first);
+ });
+
+ it('gives distinct fonts distinct handles', () => {
+ expect(registerProjectFont('a.ttf', 'es-a')).not.toBe(registerProjectFont('b.ttf', 'es-b'));
+ });
+
+ it('allocates clear of the ResourceManager handle space', () => {
+ // BitmapText.font holds small C++ handles in the same `font` asset slot
+ // vocabulary; a collision would make a .fnt silently resolve to a project
+ // font's family.
+ expect(registerProjectFont('a.ttf', 'es-a')).toBeGreaterThan(0x100000);
+ expect(projectFontFamily(1)).toBeNull();
+ expect(projectFontFamily(0)).toBeNull();
+ });
+
+ it('forgets a font on unload', () => {
+ const h = registerProjectFont('a.ttf', 'es-a');
+ unregisterProjectFont('a.ttf');
+ expect(projectFontFamily(h)).toBeNull();
+ });
+});
+
+describe('resolveTextFamily', () => {
+ it('prefers a project font over the authored family', () => {
+ const h = registerProjectFont('a.ttf', 'es-a');
+ expect(resolveTextFamily(h, 'Arial')).toBe('es-a');
+ });
+
+ it('falls back to the authored family when no font is set', () => {
+ expect(resolveTextFamily(0, 'Arial')).toBe('Arial');
+ expect(resolveTextFamily(undefined, 'Arial')).toBe('Arial');
+ });
+
+ it('falls back when the handle is not a project font (a bitmap font handle)', () => {
+ expect(resolveTextFamily(3, 'Arial')).toBe('Arial');
+ });
+
+ it('falls back after the font is unloaded, rather than rasterizing nothing', () => {
+ const h = registerProjectFont('a.ttf', 'es-a');
+ unregisterProjectFont('a.ttf');
+ expect(resolveTextFamily(h, 'Arial')).toBe('Arial');
+ });
+});