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(text): isolate font reload ownership and glyph caches

yhh815ae9b039b5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d0e2b12f5..1254bd2a1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Fixed
+- **Font reloads retain independent handles and glyph caches.** Each loaded revision uses its own platform family and runtime handle, so retiring an older asset cannot unregister its replacement or reuse stale glyph measurements. Failed and late registrations preserve live revisions; repeated outline-font unloads remain harmless. Platform font-face retention is unchanged.
+
- **Project font identities preserve complete asset paths.** Reversible, CSS-safe UTF-16 encoding replaces the short path hash, separating same-named files, supplementary characters and escape boundaries without retaining a name registry. Loading a second font no longer overwrites another asset's browser family. Internal family strings change; derive them through `familyNameFor` rather than persisting generated names. Asset references and runtime font handles keep their existing interface.
- **Missing-glyph warning history follows the bounded cache.** Diagnostic suppression retires when a family no longer has non-drawable glyphs in the 4096-entry CPU cache, preventing historical font names from accumulating. Cached-character queries keep their existing fast path, partial retirement and nested rasterization preserve reference counts, and cleanup releases the history. Unsupported-character warnings no longer claim the entire font cannot draw.
diff --git a/sdk/src/asset/loaders/FontAssetLoader.ts b/sdk/src/asset/loaders/FontAssetLoader.ts
index 2585ae7ec..69b737d1a 100644
--- a/sdk/src/asset/loaders/FontAssetLoader.ts
+++ b/sdk/src/asset/loaders/FontAssetLoader.ts
@@ -6,7 +6,7 @@ import { requireResourceManager } from '../../wasm/resourceManager';
import { getAssetTypeEntry } from '../../assetTypes';
import { getPlatform } from '../../platform/base';
import {
- familyNameFor, projectFontFamily, registerProjectFont, unregisterProjectFont,
+ freshProjectFontFamily, projectFontFamily, registerProjectFontEra, releaseProjectFontEra,
} from '../../ui/text/font-registry';
import type { FontHandle } from '../../types';
@@ -32,8 +32,8 @@ 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 ?? '');
+ if (asset.family !== undefined || asset.path !== undefined || projectFontFamily(asset.handle) !== null) {
+ releaseProjectFontEra(asset.handle);
return;
}
const rm = requireResourceManager();
@@ -47,10 +47,10 @@ export class FontAssetLoader implements AssetLoader<FontResult> {
* 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));
+ const family = freshProjectFontFamily(path);
await getPlatform().registerFont?.(family, bytes);
- return { handle: registerProjectFont(path, family) as FontHandle, family, path };
+ return { handle: registerProjectFontEra(path, family) as FontHandle, family, path };
}
private async loadBmfontJson(path: string, ctx: LoadContext): Promise<FontResult> {
diff --git a/sdk/src/ui/text/font-registry.ts b/sdk/src/ui/text/font-registry.ts
index 7b4e4520d..eaa8d03b2 100644
--- a/sdk/src/ui/text/font-registry.ts
+++ b/sdk/src/ui/text/font-registry.ts
@@ -30,11 +30,12 @@ import { RuntimeConfig } from '../../defaults';
const HANDLE_BASE = 0x4000_0000;
let nextHandle = HANDLE_BASE;
+let nextFontLoad = 0;
-/** 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>();
+/** Runtime handle → owned path and platform family. */
+const families = new Map<number, { path: string; family: string }>();
+/** Asset path → live handles; legacy path registration reuses the first. */
+const byPath = new Map<string, Set<number>>();
/** A CSS-safe, collision-free family name for a font asset path. */
export function familyNameFor(path: string): string {
@@ -56,26 +57,47 @@ export function familyNameFor(path: string): string {
* multiple referencing entities share one registration.
*/
export function registerProjectFont(path: string, family: string): number {
- const existing = byPath.get(path);
+ const existing = byPath.get(path)?.values().next().value;
if (existing !== undefined) return existing;
+ return registerProjectFontEra(path, family);
+}
+
+/** @internal A platform registration must not overwrite a still-owned font face. */
+export function freshProjectFontFamily(path: string): string {
+ return `${familyNameFor(path)}-load${(++nextFontLoad).toString(36)}`;
+}
+
+/** @internal Each prepared asset era owns a distinct runtime handle. */
+export function registerProjectFontEra(path: string, family: string): number {
const handle = nextHandle++;
- families.set(handle, family);
- byPath.set(path, handle);
+ families.set(handle, { path, family });
+ let handles = byPath.get(path);
+ if (!handles) byPath.set(path, handles = new Set());
+ handles.add(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;
+ return families.get(handle)?.family ?? null;
+}
+
+/** @internal Release only the registration owned by this font result. */
+export function releaseProjectFontEra(handle: number): void {
+ const record = families.get(handle);
+ if (!record) return;
+ families.delete(handle);
+ const handles = byPath.get(record.path);
+ handles?.delete(handle);
+ if (handles?.size === 0) byPath.delete(record.path);
}
/** 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);
+ const handles = byPath.get(path);
+ if (!handles) return;
+ for (const handle of handles) releaseProjectFontEra(handle);
}
/**
diff --git a/sdk/tests/font-asset-loader-lifecycle.test.ts b/sdk/tests/font-asset-loader-lifecycle.test.ts
new file mode 100644
index 000000000..2cc3e377e
--- /dev/null
+++ b/sdk/tests/font-asset-loader-lifecycle.test.ts
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { beforeEach, expect, it, vi } from 'vitest';
+import type { LoadContext } from '../src/asset/AssetLoader';
+
+const host = vi.hoisted(() => ({ registerFont: vi.fn(), releaseBitmapFont: vi.fn() }));
+vi.mock('../src/platform/base', () => ({ getPlatform: () => ({ registerFont: host.registerFont }) }));
+vi.mock('../src/wasm/resourceManager', () => ({
+ requireResourceManager: () => ({ releaseBitmapFont: host.releaseBitmapFont }),
+}));
+import { FontAssetLoader } from '../src/asset/loaders/FontAssetLoader';
+import { projectFontFamily, registerProjectFont, resetProjectFonts } from '../src/ui/text/font-registry';
+
+const path = 'assets/fonts/Body.ttf';
+const context = () => ({
+ catalog: { getBuildPath: (value: string) => value },
+ loadBinary: vi.fn(async () => new ArrayBuffer(16)),
+}) as unknown as LoadContext;
+beforeEach(() => {
+ resetProjectFonts();
+ host.registerFont.mockReset().mockResolvedValue(undefined);
+ host.releaseBitmapFont.mockReset();
+});
+
+it('keeps font eras independent when an older result retires after replacement', async () => {
+ const loader = new FontAssetLoader();
+ const old = await loader.load(path, context());
+ const current = await loader.load(path, context());
+ expect(current.handle).not.toBe(old.handle);
+ expect(current.family).not.toBe(old.family);
+ expect(projectFontFamily(old.handle)).toBe(old.family);
+ loader.unload(old);
+ expect(projectFontFamily(old.handle)).toBeNull();
+ expect(projectFontFamily(current.handle)).toBe(current.family);
+ loader.unload(old);
+ expect(host.releaseBitmapFont).not.toHaveBeenCalled();
+ loader.unload(current);
+ expect(projectFontFamily(current.handle)).toBeNull();
+ const next = registerProjectFont(path, 'next');
+ expect(next).not.toBe(current.handle);
+ expect(projectFontFamily(next)).toBe('next');
+});
+
+it('does not withdraw a live font when its replacement registration fails', async () => {
+ const loader = new FontAssetLoader();
+ const old = await loader.load(path, context());
+ host.registerFont.mockRejectedValueOnce(new Error('invalid font'));
+ await expect(loader.load(path, context())).rejects.toThrow('invalid font');
+ expect(projectFontFamily(old.handle)).toBe(old.family);
+ expect(registerProjectFont(path, old.family!)).toBe(old.handle);
+});
+
+it('retires a late superseded load without detaching the faster replacement', async () => {
+ const loader = new FontAssetLoader();
+ let finish!: () => void;
+ host.registerFont.mockImplementationOnce(() => new Promise<void>(resolve => { finish = resolve; }));
+ const pending = loader.load(path, context());
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));
+ const current = await loader.load(path, context());
+ finish();
+ const late = await pending;
+ expect(late.family).not.toBe(current.family);
+ loader.unload(late);
+ expect(projectFontFamily(current.handle)).toBe(current.family);
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 13ec719a8..6fd577248 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'fix(text): isolate font reload ownership and glyph caches':
+ { note: 'Font reloads retain independent handles and glyph caches.' },
'fix(text): encode font paths without identity collisions':
{ note: 'Project font identities preserve complete asset paths.' },
'fix(text): retire missing-glyph warnings with cached entries':