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): a glyph's outline costs what its size does, and text too large for a bitmap glyph draws from a distance field

yhhf5ec6b78b7bd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6b3a97b65..48060b317 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -36,6 +36,7 @@ published separately; it ships inside the editor.
### Fixed
+- **Zooming in on outlined text no longer freezes the editor.** Growing a bitmap glyph into its outline cost the fourth power of its size on screen, and a label did it again for every glyph at each step of the zoom: past 1500% a single frame took more than 15 seconds, and showing a hidden label at full zoom hung the editor. The outline now costs what the glyph's size does and looks the same, a frame stays under about 70 ms through the whole zoom, and `Auto` text at 128 screen pixels or more draws from a distance field wide enough to hold its outline. `Bitmap` is still honored where it is set, at the new cost.
- **Labels no longer come back as black boxes after a change between Plays.** Stopping left each label's geometry in the engine, by entity number. Adding, removing or dragging anything before pressing Play again moved those numbers, so the old labels drew on other entities from an atlas already released.
- **Particles and plain sprites in a Canvas paint by their place in its tree.** An emitter listed after a panel went under it, and one listed before a plain `Sprite` went over it. Both now follow the hierarchy like the controls round them, and the `layer` they were authored with is no longer overwritten. A `Sprite` with no `UINode` under a Canvas may change place as a result; a non-zero `layer` keeps the old order.
diff --git a/docs/astro/src/content/docs/ui/text.mdx b/docs/astro/src/content/docs/ui/text.mdx
index 9507757d5..6a56273e3 100644
--- a/docs/astro/src/content/docs/ui/text.mdx
+++ b/docs/astro/src/content/docs/ui/text.mdx
@@ -44,6 +44,9 @@ Every glyph is rasterized once into a shared atlas and drawn as textured quads.
configuration. Under a perspective camera world text is always SDF: a world
unit covers a different number of pixels at every depth, so there is no size a
bitmap glyph could be drawn at to land 1:1.
+ Text at 128 screen pixels or more (far zoomed in, say) is also SDF, from a field
+ wide enough for an outline of about a quarter of the font size, and returns to
+ bitmap when it shrinks again.
So a pulsing "LEVEL UP!" banner needs nothing special — `Auto` switches it to
SDF while it scales:
diff --git a/docs/astro/src/content/docs/zh-cn/ui/text.mdx b/docs/astro/src/content/docs/zh-cn/ui/text.mdx
index 81c4e5c3c..81c8c687f 100644
--- a/docs/astro/src/content/docs/zh-cn/ui/text.mdx
+++ b/docs/astro/src/content/docs/zh-cn/ui/text.mdx
@@ -39,6 +39,8 @@ addStartupSystem(buildHud);
中补偿)用位图,一旦实体缩放立即切 SDF。静态 UI 如 DOM 般锐利,动画文本缩放
稳定,零配置。透视相机下的世界文本一律用 SDF:每个深度上一个世界单位占的像素都
不同,不存在一个能让位图字形 1:1 落到屏幕上的尺寸。
+ 字号在屏幕上达到 128 像素及以上时(比如编辑器里放大很多)也用 SDF,此时距离场的
+ 范围足够容纳约 1/4 字号宽的描边;缩回去后自动回到位图。
所以一个脉动的 "LEVEL UP!" 横幅什么都不用设——`Auto` 会在它缩放时切到 SDF:
diff --git a/sdk/src/ui/text/glyph-atlas.ts b/sdk/src/ui/text/glyph-atlas.ts
index f778de014..81a08a94d 100644
--- a/sdk/src/ui/text/glyph-atlas.ts
+++ b/sdk/src/ui/text/glyph-atlas.ts
@@ -118,6 +118,8 @@ interface GlyphIdentity {
pixelSize: number;
}
+const DILATE_LEVELS = [1, 32, 64, 96, 128, 160, 192, 224, 255];
+
/**
* Grow a coverage glyph by @p radius texels: every texel takes the strongest
* coverage within the radius, faded over its last texel so the ring's edge is
@@ -138,29 +140,62 @@ export function dilateCoverage(alpha: Uint8Array, width: number, height: number,
const w = width + margin * 2;
const h = height + margin * 2;
const out = new Uint8Array(w * h);
- // The disk's offsets and their weights, once: a texel at distance d inside
- // r - 0.5 counts whole, one past r + 0.5 not at all.
- const reach = Math.ceil(r + 0.5);
- const taps: number[] = [];
- for (let dy = -reach; dy <= reach; dy++) {
- for (let dx = -reach; dx <= reach; dx++) {
- const weight = Math.min(1, Math.max(0, r + 0.5 - Math.hypot(dx, dy)));
- if (weight > 0) taps.push(dx, dy, weight);
- }
- }
- for (let y = 0; y < h; y++) {
- const sy = y - margin;
+ const size = w * h;
+ const nearestRow = new Int32Array(size);
+ const inkX = new Int32Array(w);
+ const inkY = new Int32Array(w);
+ const hull = new Int32Array(w);
+ const hullStart = new Float64Array(w + 1);
+ const none = 2 * (w + h);
+ for (const level of DILATE_LEVELS) {
for (let x = 0; x < w; x++) {
- const sx = x - margin;
- let best = 0;
- for (let t = 0; t < taps.length; t += 3) {
- const ix = sx + taps[t];
- const iy = sy + taps[t + 1];
- if (ix < 0 || iy < 0 || ix >= width || iy >= height) continue;
- const v = alpha[iy * width + ix] * taps[t + 2];
- if (v > best) best = v;
+ let row = -none;
+ for (let y = 0; y < h; y++) {
+ const sx = x - margin, sy = y - margin;
+ if (sx >= 0 && sy >= 0 && sx < width && sy < height && alpha[sy * width + sx] >= level) row = y;
+ nearestRow[y * w + x] = row;
+ }
+ row = none + h;
+ for (let y = h - 1; y >= 0; y--) {
+ const sx = x - margin, sy = y - margin;
+ if (sx >= 0 && sy >= 0 && sx < width && sy < height && alpha[sy * width + sx] >= level) row = y;
+ const above = nearestRow[y * w + x];
+ if (row - y < y - above) nearestRow[y * w + x] = row;
+ }
+ }
+ for (let y = 0; y < h; y++) {
+ const line = y * w;
+ let top = -1;
+ for (let x = 0; x < w; x++) {
+ const row = nearestRow[line + x];
+ const dy = y - row;
+ if (Math.abs(dy) >= none) continue;
+ const f = x * x + dy * dy;
+ let start = 0;
+ while (top >= 0) {
+ const q = hull[top];
+ const qy = y - nearestRow[line + q];
+ start = (f - (q * q + qy * qy)) / (2 * (x - q));
+ if (start > hullStart[top]) break;
+ top--;
+ }
+ top++;
+ hull[top] = x;
+ hullStart[top] = top === 0 ? -Infinity : start;
+ }
+ if (top < 0) continue;
+ let at = 0;
+ for (let x = 0; x < w; x++) {
+ while (at < top && hullStart[at + 1] <= x) at++;
+ inkX[x] = hull[at];
+ inkY[x] = nearestRow[line + hull[at]];
+ }
+ for (let x = 0; x < w; x++) {
+ const weight = Math.min(1, Math.max(0, r + 0.5 - Math.hypot(x - inkX[x], y - inkY[x])));
+ if (weight <= 0) continue;
+ const v = alpha[(inkY[x] - margin) * width + inkX[x] - margin] * weight + 0.5;
+ if (v > out[line + x]) out[line + x] = v;
}
- out[y * w + x] = best + 0.5;
}
}
return { alpha: out, width: w, height: h, margin };
diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.ts
index 0150f2e0d..4d44ee7f8 100644
--- a/sdk/src/ui/text/plugin.ts
+++ b/sdk/src/ui/text/plugin.ts
@@ -44,6 +44,8 @@ const GLYPH_BASE_SIZE = 64;
// Auto tolerance: a bitmap glyph still reads as pixel-exact within ±2% of 1:1.
const BITMAP_SCALE_EPSILON = 0.02;
+const LARGE_GLYPH_PX = 128;
+export const LARGE_GLYPH_ATLAS = { sdf: true, renderSize: 64, padding: 16 };
/**
* Pure: which glyph pipeline a Text draws with. `effectiveScale` is the
@@ -96,9 +98,18 @@ export function domainViewOf(viewProjection: ArrayLike<number> | undefined, vpW:
return { contentScale: glyphContentScale(viewProjection?.[0] ?? 0, vpW, dpr), perspective: false };
}
-export function glyphKind(t: Pick<TextData, 'renderMode'>, tr: Pick<TransformData, 'worldScale'>, family: string, view: DomainView): 'bitmap' | 'sdf' {
+export type GlyphKind = 'bitmap' | 'sdf' | 'large';
+
+export function drawsLarge(t: Pick<TextData, 'renderMode' | 'fontSize'>, family: string, view: DomainView, dpr: number): boolean {
+ if (t.renderMode === TextRenderMode.Bitmap || t.renderMode === TextRenderMode.Sdf) return false;
+ if (view.perspective || bitmapFontOf(family)) return false;
+ return t.fontSize * dpr * view.contentScale >= LARGE_GLYPH_PX;
+}
+
+export function glyphKind(t: Pick<TextData, 'renderMode' | 'fontSize'>, tr: Pick<TransformData, 'worldScale'>, family: string, view: DomainView, dpr = 1): GlyphKind {
if (bitmapFontOf(family)) return 'bitmap';
- return resolveTextRenderMode(t.renderMode, tr.worldScale.x, view.perspective);
+ const kind = resolveTextRenderMode(t.renderMode, tr.worldScale.x, view.perspective);
+ return kind === 'bitmap' && drawsLarge(t, family, view, dpr) ? 'large' : kind;
}
export function glyphContentScale(projScaleX: number, vpW: number, dpr: number): number {
@@ -145,6 +156,7 @@ interface RetainedLabel {
screen: boolean;
gen: number;
renderer: SdfTextRenderer;
+ kind: GlyphKind;
}
export function snapshotOf(t: TextData, family: string): TextSnapshot {
@@ -187,6 +199,7 @@ interface PreloadRun {
interface TextDomainState {
bitmap: SdfTextRenderer | null;
sdf: SdfTextRenderer | null;
+ large: SdfTextRenderer | null;
}
export class TextPlugin implements Plugin {
@@ -208,8 +221,8 @@ export class TextPlugin implements Plugin {
let state = this.states_.get(app);
if (!state) {
state = {
- world: { bitmap: null, sdf: null },
- screen: { bitmap: null, sdf: null },
+ world: { bitmap: null, sdf: null, large: null },
+ screen: { bitmap: null, sdf: null, large: null },
matrix: new Float32Array(16), matrixHeap: null,
retained: new Map(),
preloads: [],
@@ -232,7 +245,7 @@ export class TextPlugin implements Plugin {
for (const entity of state.retained.keys()) {
try { api?.renderer_retainedTextClear?.(entity); } catch (error) { errors.push(error); }
}
- for (const renderer of [state.world.bitmap, state.world.sdf, state.screen.bitmap, state.screen.sdf]) {
+ for (const renderer of [state.world.bitmap, state.world.sdf, state.world.large, state.screen.bitmap, state.screen.sdf, state.screen.large]) {
try { renderer?.dispose(); } catch (error) { errors.push(error); }
}
if (errors.length) throw new Error(`Failed to release text resources: ${errors.map(String).join('; ')}`);
@@ -247,7 +260,7 @@ export class TextPlugin implements Plugin {
app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([], () => {
const state = this.states_.get(app);
if (!state) return;
- for (const renderer of [state.world.bitmap, state.world.sdf, state.screen.bitmap, state.screen.sdf]) {
+ for (const renderer of [state.world.bitmap, state.world.sdf, state.world.large, state.screen.bitmap, state.screen.sdf, state.screen.large]) {
renderer?.beginFrame();
}
}, { name: 'TextPageLifetimeSystem', runWhenPaused: true }));
@@ -348,7 +361,8 @@ export class TextPlugin implements Plugin {
const world = app.world;
const registry = world.getCppRegistry() as CppRegistry;
const dpr = platformDevicePixelRatio();
- const contentScale = this.domainView(app, screen, dpr).contentScale;
+ const view = this.domainView(app, screen, dpr);
+ const contentScale = view.contentScale;
const state = screen ? appState.screen : appState.world;
const retained = appState.retained;
// The atlas rasterizes for the projection that draws it: bring each existing renderer up to this pass's before asking whether its
@@ -373,7 +387,8 @@ export class TextPlugin implements Plugin {
seen.add(entity as number);
// Which glyph pipeline an automatic label gets follows its world scale, which the engine watches (renderer_retainedTextStale): the
// transform is not read here every frame for every label to find out.
- if (label && label.gen === label.renderer.atlas.generation && sameSnapshot(label.snap, t, family)) {
+ if (label && label.gen === label.renderer.atlas.generation && sameSnapshot(label.snap, t, family)
+ && (label.kind === 'sdf' || (label.kind === 'large') === drawsLarge(t, family, view, dpr))) {
label.renderer.markDrawn(entity as number);
continue;
}
@@ -437,7 +452,7 @@ export class TextPlugin implements Plugin {
const state = screen ? appState.screen : appState.world;
const tr = world.get(entity, Transform) as TransformData;
const family = resolveTextFamily(t.font, t.fontFamily);
- const kind = glyphKind(t, tr, family, view);
+ const kind = glyphKind(t, tr, family, view, dpr);
const renderer = this.rendererFor(app, state, kind, view.contentScale, dpr);
const previous = appState.retained.get(entity as number);
if (previous && previous.renderer !== renderer) previous.renderer.forget(entity as number);
@@ -503,7 +518,7 @@ export class TextPlugin implements Plugin {
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 && !bitmapFontOf(family),
);
- appState.retained.set(entity as number, { snap: snapshotOf(t, family), screen, gen: renderer.atlas.generation, renderer });
+ appState.retained.set(entity as number, { snap: snapshotOf(t, family), screen, gen: renderer.atlas.generation, renderer, kind });
// A box that grows to its text: the rectangle the entity occupies takes the height the lines laid out to. The sprite and text follow the
// rectangle on the next frame, where the box is the same height and nothing changes again.
if (t.overflow === TextOverflow.ResizeHeight && blockHeight > 0) {
@@ -546,7 +561,7 @@ export class TextPlugin implements Plugin {
const tr = world.get(entity, Transform) as TransformData;
const renderer = this.rendererFor(
app, state,
- glyphKind(t, tr, resolveTextFamily(t.font, t.fontFamily), view),
+ glyphKind(t, tr, resolveTextFamily(t.font, t.fontFamily), view, dpr),
view.contentScale,
dpr,
);
@@ -639,6 +654,7 @@ export class TextPlugin implements Plugin {
// would have each pass evict the other's glyphs every frame.
state.bitmap?.retainOnly(seen);
state.sdf?.retainOnly(seen);
+ state.large?.retainOnly(seen);
}
/**
@@ -687,7 +703,7 @@ export class TextPlugin implements Plugin {
const dpr = platformDevicePixelRatio();
const view = this.domainView(app, screen, dpr);
const appState = this.stateFor(app);
- const renderer = this.rendererFor(app, screen ? appState.screen : appState.world, glyphKind(t, tr, family, view), view.contentScale, dpr);
+ const renderer = this.rendererFor(app, screen ? appState.screen : appState.world, glyphKind(t, tr, family, view, dpr), view.contentScale, dpr);
run.renderer = renderer;
const style = (t.bold ? UI_TEXT_BOLD : 0) | (t.italic ? UI_TEXT_ITALIC : 0);
run.job.step((codepoint) => renderer.preloadGlyph(run, codepoint, family, style, t.fontSize), platformNow);
@@ -714,7 +730,7 @@ export class TextPlugin implements Plugin {
private rendererFor(
app: App,
state: TextDomainState,
- kind: 'bitmap' | 'sdf',
+ kind: GlyphKind,
contentScale: number,
dpr: number,
): SdfTextRenderer {
@@ -723,6 +739,10 @@ export class TextPlugin implements Plugin {
if (!state.sdf) state.sdf = new SdfTextRenderer(module, { sdf: true });
return state.sdf;
}
+ if (kind === 'large') {
+ if (!state.large) state.large = new SdfTextRenderer(module, LARGE_GLYPH_ATLAS);
+ return state.large;
+ }
if (!state.bitmap) {
state.bitmap = new SdfTextRenderer(module, {
sdf: false, dpr, renderSize: Math.round(GLYPH_BASE_SIZE * dpr),
diff --git a/sdk/tests/glyph-dilate.test.ts b/sdk/tests/glyph-dilate.test.ts
index 208d1df25..a509a8459 100644
--- a/sdk/tests/glyph-dilate.test.ts
+++ b/sdk/tests/glyph-dilate.test.ts
@@ -25,6 +25,54 @@ describe('growing a coverage glyph into its outline', () => {
expect(alpha[margin * width + margin + 1]).toBe(50); // on the radius: half
});
+ function inkedGlyph(size: number): Uint8Array {
+ const ss = 16, a = new Uint8Array(size * size);
+ const inside = (u: number, v: number) => {
+ const ring = Math.hypot(u - 0.62, v - 0.62);
+ return (u > 0.15 && u < 0.3 && v > 0.1 && v < 0.9) || (u > 0.15 && u < 0.75 && v > 0.1 && v < 0.22)
+ || (ring < 0.24 && ring > 0.13) || (Math.abs((u - 0.3) - (v - 0.3) * 0.8) < 0.03 && v > 0.3 && v < 0.75);
+ };
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
+ let hits = 0;
+ for (let j = 0; j < ss; j++) for (let i = 0; i < ss; i++) if (inside((x + (i + 0.5) / ss) / size, (y + (j + 0.5) / ss) / size)) hits++;
+ a[y * size + x] = Math.round(255 * hits / (ss * ss));
+ }
+ return a;
+ }
+
+ function everyTapAnswer(alpha: Uint8Array, size: number, r: number, margin: number, x: number, y: number): number {
+ const reach = Math.ceil(r + 0.5);
+ let best = 0;
+ for (let dy = -reach; dy <= reach; dy++) for (let dx = -reach; dx <= reach; dx++) {
+ const sx = x - margin + dx, sy = y - margin + dy;
+ if (sx < 0 || sy < 0 || sx >= size || sy >= size) continue;
+ const v = alpha[sy * size + sx] * Math.min(1, Math.max(0, r + 0.5 - Math.hypot(dx, dy)));
+ if (v > best) best = v;
+ }
+ return best + 0.5;
+ }
+
+ it.each([[10, 0.5], [16, 2], [24, 3.5], [48, 9], [96, 20]])('draws the ring every tap would, a %i px glyph grown by %f', (size, r) => {
+ const source = inkedGlyph(size);
+ const { alpha, width, height, margin } = dilateCoverage(source, size, size, r);
+ let off = 0, worst = 0;
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
+ const d = Math.abs(alpha[y * width + x] - Math.floor(everyTapAnswer(source, size, r, margin, x, y)));
+ if (d > 2) off++;
+ if (d > worst) worst = d;
+ }
+ expect(worst).toBeLessThanOrEqual(32);
+ expect(off / (width * height)).toBeLessThan(0.02);
+ });
+
+ it('keeps growing a glyph cheap however wide the ring is', () => {
+ const source = inkedGlyph(512);
+ const start = performance.now();
+ const { alpha, width, margin } = dilateCoverage(source, 512, 512, 102);
+ expect(performance.now() - start).toBeLessThan(2000);
+ expect(alpha[(margin + 256) * width + margin + 77 - 102 + 1]).toBe(255);
+ });
+
it('places a grown glyph as its own cell, and repaints it grown', () => {
const ink = new Uint8Array(4 * 4 * 4);
for (let i = 3; i < ink.length; i += 4) ink[i] = 255;
diff --git a/sdk/tests/ui-text-render-mode.test.ts b/sdk/tests/ui-text-render-mode.test.ts
index d446f518f..b4abb2df3 100644
--- a/sdk/tests/ui-text-render-mode.test.ts
+++ b/sdk/tests/ui-text-render-mode.test.ts
@@ -28,6 +28,34 @@ describe('TextRenderMode', () => {
});
});
+describe('text too large on screen for a bitmap glyph', () => {
+ const flat = (contentScale: number) => ({ contentScale, perspective: false });
+ const unscaled = { worldScale: { x: 1, y: 1, z: 1 } } as never;
+
+ it('leaves the bitmap pipeline once it would rasterize past the limit', async () => {
+ const { glyphKind } = await import('../src/ui/text/plugin');
+ const label = { renderMode: TextRenderMode.Auto, fontSize: 10 };
+ expect(glyphKind(label, unscaled, 'Arial', flat(1))).toBe('bitmap');
+ expect(glyphKind(label, unscaled, 'Arial', flat(12.7))).toBe('bitmap');
+ expect(glyphKind(label, unscaled, 'Arial', flat(12.8))).toBe('large');
+ expect(glyphKind(label, unscaled, 'Arial', flat(58))).toBe('large');
+ expect(glyphKind(label, unscaled, 'Arial', flat(6.4), 2)).toBe('large');
+ expect(glyphKind(label, unscaled, 'Arial', flat(1))).toBe('bitmap');
+ });
+
+ it('does not override a mode the author chose, or a view it does not apply to', async () => {
+ const { glyphKind, drawsLarge } = await import('../src/ui/text/plugin');
+ expect(glyphKind({ renderMode: TextRenderMode.Bitmap, fontSize: 10 }, unscaled, 'Arial', flat(58))).toBe('bitmap');
+ expect(glyphKind({ renderMode: TextRenderMode.Sdf, fontSize: 10 }, unscaled, 'Arial', flat(58))).toBe('sdf');
+ expect(drawsLarge({ renderMode: TextRenderMode.Auto, fontSize: 200 }, 'Arial', { contentScale: 1, perspective: true }, 1)).toBe(false);
+ });
+
+ it('holds a ring as wide as a fifth of the em in its distance field', async () => {
+ const { LARGE_GLYPH_ATLAS } = await import('../src/ui/text/plugin');
+ expect(LARGE_GLYPH_ATLAS.padding).toBeGreaterThanOrEqual(0.2 * LARGE_GLYPH_ATLAS.renderSize);
+ });
+});
+
describe('resolveTextRenderMode', () => {
it('forced modes win regardless of scale', () => {
expect(resolveTextRenderMode(TextRenderMode.Bitmap, 3)).toBe('bitmap');
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 8a88c3a64..4c101c64d 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -4246,4 +4246,6 @@ export const NOTED = {
{"note": "A texture stays on a scene that rescans as it is placed."},
"feat(rig): the 2D rig editor, from an image to a character in the scene":
{"note": "A 2D character can be rigged in the editor, with no other program."},
+ "fix(text): a glyph's outline costs what its size does, and text too large for a bitmap glyph draws from a distance field":
+ {"note": "Zooming in on outlined text no longer freezes the editor."},
};