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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(text): a glyph page is read by a mode — plain, distance field, mask, fill — so a bitmap font with its outline baked into the page draws in two passes with the ring in any colour; the Cocos import declares such fonts
yhh244f7599e169
diff --git a/docs/astro/src/content/docs/ui/text.mdx b/docs/astro/src/content/docs/ui/text.mdxindex 6261aed32..92a6bb5c3 100644--- a/docs/astro/src/content/docs/ui/text.mdx+++ b/docs/astro/src/content/docs/ui/text.mdx@@ -79,8 +79,10 @@ Defaults below are the component defaults (what the inspector shows).| `color` | Color | `{1,1,1,1}` | Fill color (per-channel `0..1`). || `align` | `TextAlign` | `Left` | Horizontal alignment: `Left` / `Center` / `Right`. || `verticalAlign` | `TextVerticalAlign` | `Top` | Vertical alignment: `Top` / `Middle` / `Bottom`. |-| `wordWrap` | boolean | `true` | Wrap lines at the box width (needs a `UINode` box). |-| `overflow` | `TextOverflow` | `Visible` | `Visible` / `Clip` / `Ellipsis`. Currently the renderer always draws `Visible`; clip overflow with a [`UIMask`](/docs/ui/overview/) on the box. |+| `wordWrap` | boolean | `true` | Wrap lines at the box width (needs a box: a `UINode`, or the `Text`'s own `boxWidth`). |+| `overflow` | `TextOverflow` | `Visible` | What text too big for its box does (needs a box): `Visible` keeps it all; `Clip` and `Ellipsis` drop the lines past the box height and trim a line past its width; `Shrink` sets the type smaller, a whole pixel at a time, until it fits both (line height and letter spacing shrink with it, down to 1px). |+| `boxWidth` / `boxHeight` | number | `0` | The layout box of a `Text` with **no** `UINode`, in px. `0` means no box (the entity origin is the box). With a box, alignment, wrapping and overflow work inside it while the text stays world content, sorted by `layer`. A `UINode`, when present, decides the box instead. |+| `boxPivot` | Vec2 | `(0.5, 0.5)` | Where the entity origin sits in that box, as a fraction from its left and bottom edges: `(0.5, 0.5)` is the centre, `(0, 1)` the top-left corner. It is the anchor point of a Cocos or Unity rect transform. || `lineHeight` | number | `1.2` | Line spacing as a **ratio of `fontSize`** (baseline-to-baseline = `lineHeight × fontSize`). || `bold` / `italic` | boolean | `false` | Base font style (rich-text `<b>`/`<i>` layer on top). || `strokeColor` | Color | `{0,0,0,1}` | Outline color. |@@ -115,7 +117,11 @@ nothing.`wordWrap`, which only decides whether lines *break* at that width — and`verticalAlign` distributes the block's vertical slack (`Middle` splits it,`Bottom` pushes the block down).-- **Without a box** (no `UINode`, or a 0×0 one): the block anchors to the entity+- **With the `Text`'s own box** (no `UINode`, but `boxWidth` / `boxHeight` set): the+ same placement, wrapping and overflow, with the box standing where `boxPivot` puts+ it relative to the entity — so a world label can wrap and align inside a rectangle+ without joining a Canvas.+- **Without a box** (no `UINode`, or a 0×0 one, and no `boxWidth` / `boxHeight`): the block anchors to the entityorigin. `align: Left` puts the left edge at the origin, `Center` centers theblock on it, `Right` ends at it; `verticalAlign` anchors top/middle/bottomedge the same way. This is what you want for world-space labels — damage@@ -259,13 +265,26 @@ or its glyphs rasterize with the fallback font.alone silently falls back to a different typeface on a machine that lacks the family, andthat failure only shows up on someone else's device.-Separately, **bitmap font assets** (`.fnt` / `.bmfont`) load through the asset-pipeline — `Assets.loadFont(ref)` resolves the `.fnt`, loads its page texture,-and returns a `FontResult` (`{ handle }`). They drive the **`BitmapText`**-component: a world-space text renderer whose `font` field references the loaded-asset (assign the font asset in the inspector), with `text`, `color`,-`fontSize`, `align`, `spacing`, `parallax`, and `layer` fields. Use `BitmapText`-for pre-baked score/damage glyph art; use `Text` for UI.+**Bitmap font assets** (`.fnt` / `.bmfont`) load through the asset pipeline —+`Assets.loadFont(ref)` resolves the `.fnt`, loads its page texture, and returns a+`FontResult` (`{ handle }`). They serve both text components:++- **`Text.font`** draws the font from its page texture, through the same layout as+ any other font — wrapping, alignment, the box, `Shrink`, shadow and outline all+ work. The font's own metrics are used, scaled by `fontSize` over the size it was+ drawn at (`info size`), so a label is as big as the font's author made it at that+ size. A bitmap font always draws as a bitmap, whatever `renderMode` says.+- **`BitmapText`** is the world-space renderer for pre-baked glyph art: its `font`+ field references the loaded asset, with `text`, `color`, `fontSize`, `align`,+ `spacing`, `parallax`, and `layer` fields.++A page is a plain RGBA image to tint unless its `common` line says otherwise. A font+that **bakes its outline into the page** — the glyph in the red channel, glyph and+outline together in alpha — declares it in BMFont's own channel flags+(`alphaChnl=2 redChnl=0`). `Text` then draws it in two passes: the outline ring+first, in `strokeColor`, then the glyph in `color`. `strokeWidth` only says whether+there is a ring (the page's ring is drawn, not grown), and without one only the+glyph is drawn, so the outline can be any colour, translucent, or absent.## Localizationdiff --git a/docs/astro/src/content/docs/zh-cn/ui/text.mdx b/docs/astro/src/content/docs/zh-cn/ui/text.mdxindex c5455b9e1..f9fd5eb4d 100644--- a/docs/astro/src/content/docs/zh-cn/ui/text.mdx+++ b/docs/astro/src/content/docs/zh-cn/ui/text.mdx@@ -73,8 +73,10 @@ const pulseBanner = defineSystem([Query(Mut(Transform), Text), Res(Time)], (q, t| `color` | Color | `{1,1,1,1}` | 填充色(每通道 `0..1`)。 || `align` | `TextAlign` | `Left` | 水平对齐:`Left` / `Center` / `Right`。 || `verticalAlign` | `TextVerticalAlign` | `Top` | 垂直对齐:`Top` / `Middle` / `Bottom`。 |-| `wordWrap` | boolean | `true` | 按盒宽换行(需要 `UINode` 盒)。 |-| `overflow` | `TextOverflow` | `Visible` | `Visible` / `Clip` / `Ellipsis`。当前渲染器始终按 `Visible` 绘制;要裁剪溢出,给盒加 [`UIMask`](/docs/zh-cn/ui/overview/)。 |+| `wordWrap` | boolean | `true` | 按盒宽换行(需要盒:`UINode`,或 `Text` 自己的 `boxWidth`)。 |+| `overflow` | `TextOverflow` | `Visible` | 文本超出盒时怎么办(需要盒):`Visible` 全部保留;`Clip` 和 `Ellipsis` 丢弃超出盒高的行、截断超出盒宽的行;`Shrink` 把字一个像素一个像素地缩小,直到放进盒里(行高和字距随之缩小,最小 1px)。 |+| `boxWidth` / `boxHeight` | number | `0` | **没有** `UINode` 的 `Text` 的排版盒,单位 px。`0` 表示没有盒(实体原点就是盒)。有盒时对齐、换行、溢出都在盒内工作,而文本仍是世界内容,按 `layer` 排序。存在 `UINode` 时由它决定盒。 |+| `boxPivot` | Vec2 | `(0.5, 0.5)` | 实体原点在这个盒里的位置,按距盒左边、下边的比例:`(0.5, 0.5)` 是中心,`(0, 1)` 是左上角。相当于 Cocos / Unity 矩形变换的锚点。 || `lineHeight` | number | `1.2` | 行距,为 **`fontSize` 的比率**(基线间距 = `lineHeight × fontSize`)。 || `bold` / `italic` | boolean | `false` | 基础字体样式(富文本 `<b>`/`<i>` 在其上叠加)。 || `strokeColor` | Color | `{0,0,0,1}` | 描边颜色。 |@@ -105,7 +107,8 @@ const pulseBanner = defineSystem([Query(Mut(Transform), Text), Res(Time)], (q, t- **有 `UINode` 盒**(实体带布局尺寸非零的 `UINode`):每行在盒宽内水平对齐——与 `wordWrap` 无关,后者只决定是否在该宽度*断行*——`verticalAlign` 分配块的垂直空余(`Middle` 平分,`Bottom` 推到底)。-- **无盒**(没有 `UINode`,或 0×0):文本块锚定到实体原点。`align: Left` 让左缘+- **用 `Text` 自己的盒**(没有 `UINode`,但设置了 `boxWidth` / `boxHeight`):同样的摆放、换行和溢出,盒按 `boxPivot` 相对实体放置——世界内的文字无需加入 Canvas,也能在一个矩形里换行、对齐。+- **没有盒**(没有 `UINode`,或者是 0×0 的,也没有 `boxWidth` / `boxHeight`):文本块锚定到实体原点。`align: Left` 让左缘落在原点,`Center` 以原点居中,`Right` 结束于原点;`verticalAlign` 同理锚定顶/中/底缘。世界空间标签——伤害数字、名牌——"以实体为中心"就是一个字段,不用算。@@ -233,12 +236,21 @@ addStartupSystem(buildBubble);两者都设置时 `font` 优先。凡是品牌依赖的字体都建议用它:只写 `fontFamily` 时,缺少该字体族的机器会静默回退成另一套字体,而这种失败只会在别人的设备上暴露。-另有**位图字体资产**(`.fnt` / `.bmfont`)走资产管线——`Assets.loadFont(ref)`-解析 `.fnt`、加载其页纹理,返回 `FontResult`(`{ handle }`)。它们驱动-**`BitmapText`** 组件:世界空间文本渲染器,其 `font` 字段引用加载的资产(在-检查器里指定字体资产),另有 `text`、`color`、`fontSize`、`align`、`spacing`、-`parallax`、`layer` 字段。预烘焙的分数/伤害字形美术用 `BitmapText`;UI 用-`Text`。+**位图字体资产**(`.fnt` / `.bmfont`)走资产管线——`Assets.loadFont(ref)`+解析 `.fnt`、加载其页纹理,返回 `FontResult`(`{ handle }`)。它们同时服务两个文本组件:++- **`Text.font`** 直接从页纹理绘制该字体,与其他字体走同一套排版——换行、对齐、盒、+ `Shrink`、阴影和描边都可用。使用字体自己的度量,按 `fontSize` 与字体绘制时的字号+ (`info size`)之比缩放,所以在该字号下它和字体作者做的一样大。位图字体无论+ `renderMode` 设什么,都按位图绘制。+- **`BitmapText`** 是预烘焙字形美术的世界空间渲染器:其 `font` 字段引用加载的资产,+ 另有 `text`、`color`、`fontSize`、`align`、`spacing`、`parallax`、`layer` 字段。++除非 `common` 行另有说明,页面就是一张要染色的普通 RGBA 图。**把描边烘焙进页面**+的字体——字形在红通道,字形加描边在 alpha——用 BMFont 自己的通道标志声明+(`alphaChnl=2 redChnl=0`)。`Text` 会分两遍绘制:先用 `strokeColor` 画描边圈,+再用 `color` 画字形。`strokeWidth` 只表示有没有圈(页面里的圈是画出来的,不是长出来+的);没有它时只画字形,所以描边可以是任意颜色、半透明,或者没有。## 本地化diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.tsindex 8c02d77a0..828c6a939 100644--- a/pipeline/src/import/cocos/components.ts+++ b/pipeline/src/import/cocos/components.ts@@ -23,11 +23,22 @@ export interface ComponentData {export interface SliceBorder { left: number; right: number; top: number; bottom: number }+/** What the engine needs to know about an asset beyond its bytes, learnt from how the project uses it. */+export interface AssetHints {+ /** A bitmap font whose page carries the glyph in red and glyph-and-outline in alpha. */+ bakedOutline?: boolean;+}+export interface ComponentContext {assets: CocosAssetIndex;report: ImportReport;/** The project-relative ref of a copied asset; records that it must be copied. */- assetRef(entry: CocosAssetEntry, slice?: SliceBorder): string;+ assetRef(entry: CocosAssetEntry, slice?: SliceBorder, hints?: AssetHints): string;+ /**+ * Whether a Cocos material draws a bitmap font's page as two layers, a glyph in the red channel and its outline in alpha, with the+ * outline's colour supplied at draw time. Such a font has to say so, in the channel flags BMFont gives that layout.+ */+ drawsBakedOutline?(materialUuid: string): boolean;}type Raw = Record<string, unknown>;@@ -177,10 +188,9 @@ function label(c: CocosComponent, siblings: CocosComponent[], box: UiBox | null,if (font?.importer === 'ttf-font') {data.font = ctx.assetRef(font);} else if (font?.importer === 'bitmap-font') {- // The engine takes a .fnt in Text.font. How its glyph scale reads `fontSize` is still to be checked on screen.- data.font = ctx.assetRef(font);- status = 'partial';- ctx.report.note('label-bitmap-font', where);+ const material = uuidOf(d._customMaterial);+ const baked = material !== '' && ctx.drawsBakedOutline?.(material) === true;+ data.font = ctx.assetRef(font, undefined, baked ? { bakedOutline: true } : undefined);} else {status = 'partial';ctx.report.note(font ? 'label-font-unsupported' : 'label-font-missing', where);@@ -195,10 +205,7 @@ function label(c: CocosComponent, siblings: CocosComponent[], box: UiBox | null,}const outline = siblings.find((s) => s.type === 'cc.LabelOutline' && s.enabled);- // 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) {+ if (outline) {data.strokeColor = color(outline.data._color);data.strokeWidth = num(outline.data._width, 0);}diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.tsindex 58a2a1b66..66b51f030 100644--- a/pipeline/src/import/cocos/importProject.ts+++ b/pipeline/src/import/cocos/importProject.ts@@ -11,7 +11,7 @@import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';import path from 'node:path';import { buildCocosAssetIndex, type CocosAssetEntry } from './assets';-import type { SliceBorder } from './components';+import type { AssetHints, SliceBorder } from './components';import { convertPrefab, convertScene, type ConvertContext } from './convert';import { parseCocosDocument, type CocosDocument } from './document';import { ImportReport, type ImportReportData } from './report';@@ -77,6 +77,16 @@ function copyFontPages(fnt: string, dest: string, uuidFor: (pageFile: string) =>}}+/**+ * The `.fnt`, with its `common` line saying what the page holds, in the channel flags BMFont defines for it: glyph in red (`redChnl=0`), glyph and+ * outline in alpha (`alphaChnl=2`). That is how the engine knows to draw it in two passes, and it is what a real BMFont export of such a page says.+ */+function declareBakedOutline(fnt: string): string {+ return fnt.replace(/^(\s*common\b[^\r\n]*?)(\r?\n|$)/m, (line, head: string, eol: string) => (+ /\balphaChnl=/.test(head) ? line : `${head} alphaChnl=2 redChnl=0 greenChnl=0 blueChnl=0${eol}`+ ));+}+export function importCocosProject(opts: CocosImportOptions): ImportReportData {const source = path.resolve(opts.source);const out = path.resolve(opts.out);@@ -94,7 +104,7 @@ export function importCocosProject(opts: CocosImportOptions): ImportReportData {const outRef = (assetRel: string): string => `assets/${into}/${assetRel}`;const esRel = (assetRel: string, ext: string): string => assetRel.replace(/\.[^./]+$/, ext);- const textures = new Map<string, { entry: CocosAssetEntry; slice?: SliceBorder }>();+ const textures = new Map<string, { entry: CocosAssetEntry; slice?: SliceBorder; hints?: AssetHints }>();const docs = new Map<string, CocosDocument | null>();const pending: string[] = [];const queued = new Set<string>();@@ -119,11 +129,21 @@ export function importCocosProject(opts: CocosImportOptions): ImportReportData {assets: index,report,where: '',- assetRef(entry, slice) {- const merged = slice ?? textures.get(entry.file)?.slice;- textures.set(entry.file, merged ? { entry, slice: merged } : { entry });+ assetRef(entry, slice, hints) {+ const prev = textures.get(entry.file);+ const merged = slice ?? prev?.slice;+ // A font any label draws as two layers is declared so; the declaration is about the page, not the label.+ const bakedOutline = hints?.bakedOutline === true || prev?.hints?.bakedOutline === true;+ textures.set(entry.file, {+ entry,+ ...(merged ? { slice: merged } : {}),+ ...(bakedOutline ? { hints: { bakedOutline: true } } : {}),+ });return outRef(entry.rel);},+ drawsBakedOutline(materialUuid) {+ return materialBakesOutline(materialUuid);+ },loadPrefab(uuid) {const e = prefabEntry(uuid);return e ? loadDoc(e) : null;@@ -139,6 +159,24 @@ export function importCocosProject(opts: CocosImportOptions): ImportReportData {},};+ // A material says how its font page is read through the effect it uses; the outline effect mixes an outline colour in by the red channel.+ const bakes = new Map<string, boolean>();+ const materialBakesOutline = (materialUuid: string): boolean => {+ const known = bakes.get(materialUuid);+ if (known !== undefined) return known;+ let result = false;+ try {+ const mat = index.byUuid.get(materialUuid);+ const effectUuid = mat && JSON.parse(readFileSync(mat.file, 'utf8'))?._effectAsset?.__uuid__;+ const effect = typeof effectUuid === 'string' ? index.byUuid.get(effectUuid) : undefined;+ result = !!effect && /alphaLerp\s*=\s*o\.r/.test(readFileSync(effect.file, 'utf8'));+ } catch {+ result = false;+ }+ bakes.set(materialUuid, result);+ return result;+ };+const wanted = (relPath: string): boolean => !opts.only?.length || opts.only.some((p) => relPath.startsWith(p));const scenes: string[] = [];for (const f of walk(assetsDir)) {@@ -184,14 +222,15 @@ export function importCocosProject(opts: CocosImportOptions): ImportReportData {report.textures = textures.size;if (!opts.dryRun) {- for (const { entry, slice } of textures.values()) {+ for (const { entry, slice, hints } of textures.values()) {const dest = path.join(out, outRef(entry.rel));if (!existsSync(entry.file)) {report.missingAsset(entry.uuid);continue;}mkdirSync(path.dirname(dest), { recursive: true });- copyFileSync(entry.file, dest);+ if (entry.file.endsWith('.fnt') && hints?.bakedOutline) writeOut(dest, declareBakedOutline(readFileSync(entry.file, 'utf8')));+ else copyFileSync(entry.file, dest);if (entry.file.endsWith('.fnt')) {copyFontPages(entry.file, dest, (page) => byRel.get(norm(path.relative(assetsDir, page)))?.uuid);// The asset database ships a font's page image only for a `bitmapfont`, since nothing else names it.diff --git a/pipeline/tests/cocos-import.test.ts b/pipeline/tests/cocos-import.test.tsindex 7b6c3af2a..6bd0389cd 100644--- a/pipeline/tests/cocos-import.test.ts+++ b/pipeline/tests/cocos-import.test.ts@@ -24,6 +24,8 @@ const IMG = '11111111-1111-4111-8111-111111111111';const ITEM = '22222222-2222-4222-8222-222222222222';const PANEL = '33333333-3333-4333-8333-333333333333';const FONT = '44444444-4444-4444-8444-444444444444';+const MAT = '66666666-6666-4666-8666-666666666666';+const EFFECT = '77777777-7777-4777-8777-777777777777';const vec = (x: number, y: number, z = 0) => ({ __type__: 'cc.Vec3', x, y, z });const ident = { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 };@@ -53,7 +55,7 @@ const itemPrefab = [{ __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'itemRoot', instance: null }, // 8{ __type__: 'cc.UITransform', node: { __id__: 2 }, _enabled: true, __prefab: { __id__: 10 }, _contentSize: { width: 80, height: 20 }, _anchorPoint: { x: 0.5, y: 0.5 } }, // 9{ __type__: 'cc.CompPrefabInfo', fileId: 'ut2' }, // 10- { __type__: 'cc.Label', node: { __id__: 2 }, _enabled: true, __prefab: { __id__: 12 }, _string: 'hello', _fontSize: 20, _lineHeight: 24, _color: { r: 255, g: 0, b: 0, a: 255 }, _horizontalAlign: 1, _verticalAlign: 1, _isSystemFontUsed: false, _font: { __uuid__: FONT }, _overflow: 0, _enableWrapText: true }, // 11+ { __type__: 'cc.Label', node: { __id__: 2 }, _enabled: true, __prefab: { __id__: 12 }, _string: 'hello', _fontSize: 20, _lineHeight: 24, _color: { r: 255, g: 0, b: 0, a: 255 }, _horizontalAlign: 1, _verticalAlign: 1, _isSystemFontUsed: false, _font: { __uuid__: FONT }, _customMaterial: { __uuid__: MAT }, _overflow: 0, _enableWrapText: true }, // 11{ __type__: 'cc.CompPrefabInfo', fileId: 'lab' }, // 12{ __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'capt', instance: null }, // 13];@@ -146,9 +148,14 @@ beforeAll(async () => {put('ui/item.prefab.meta', meta(ITEM, 'prefab'));put('ui/panel.prefab', panelPrefab);put('ui/panel.prefab.meta', meta(PANEL, 'prefab'));- put('ui/f.fnt', 'info face="f"\npage id=0 file="f_0.png"\n');+ put('ui/f.fnt', 'info face="f" size=20\ncommon lineHeight=20 base=16 scaleW=64 scaleH=64 pages=1 packed=0\npage id=0 file="f_0.png"\n');put('ui/f_0.png', 'page');put('ui/f.fnt.meta', meta(FONT, 'bitmap-font'));+ // the outline effect mixes the outline colour in by the red channel; the material that uses it is what marks a font page as baked+ put('ui/font.effect', 'vec4 frag () { float alphaLerp = o.r; return mix(outlineColor, color, alphaLerp); }');+ put('ui/font.effect.meta', meta(EFFECT, 'effect'));+ put('ui/font.mtl', { __type__: 'cc.Material', _effectAsset: { __uuid__: EFFECT } });+ put('ui/font.mtl.meta', meta(MAT, 'material'));put('main.scene', scene);put('main.scene.meta', meta('55555555-5555-4555-8555-555555555555', 'scene'));before = Object.fromEntries([...files(src)].map((f) => [f, sha(f)]));@@ -191,6 +198,16 @@ describe('importing a Cocos project', () => {expect(written, written.join(',')).toContain('assets/cocos/ui/f_0.png');});+ it('declares a font page that its material draws as glyph and outline layers, in BMFont\'s own channel flags', () => {+ const fnt = readFileSync(path.join(out, 'assets/cocos/ui/f.fnt'), 'utf8');+ const common = fnt.split(/\r?\n/).find((l) => l.startsWith('common'))!;+ expect(common).toContain('alphaChnl=2');+ expect(common).toContain('redChnl=0');+ // the rest of the file is as it was+ expect(fnt).toContain('page id=0 file="f_0.png"');+ expect(common).toContain('scaleW=64');+ });+it('keeps a nested prefab nested, with the instance\'s changes as overrides', () => {const panel = readJson('assets/cocos/ui/panel.esprefab');const b = panel.entities.find((e: any) => e.prefabEntityId === 'instB');@@ -231,8 +248,8 @@ describe('importing a Cocos project', () => {it('counts what it did not map instead of dropping it', () => {expect(report.components['cc.Sprite']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });- expect(report.components['cc.Label']).toEqual({ mapped: 0, partial: 1, unmapped: 0 });- expect(report.notes['label-bitmap-font']?.count).toBe(1);+ expect(report.components['cc.Label']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });+ expect(report.notes['label-bitmap-font']).toBeUndefined();expect(report.notes['scene-globals-dropped']?.count).toBe(1);expect(report.prefabInstances).toBe(3);});diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.mdindex 7a4e1028f..29c84a512 100644--- a/sdk/etc/wasm.api.md+++ b/sdk/etc/wasm.api.md@@ -512,7 +512,7 @@ renderer_renderMeshPreview: (meshId: number, w: number, h: number) => voidrenderer_renderSkeletalPreview: (preview: number, viewProjectionPtr: number) => numberrenderer_replayToDrawCall: (drawCallIndex: number) => voidrenderer_resize: (width: number, height: number) => void-renderer_retainedTextBatch: ((entity: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, pageId: number) => void) | undefined+renderer_retainedTextBatch: ((entity: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, pageId: number, glyphMode: number) => void) | undefinedrenderer_retainedTextBegin: ((entity: number, sdf: number, screen: number, hasBox: number, layer: number, boxWidth: number, boxHeight: number, autoKind: number) => void) | undefinedrenderer_retainedTextClear: ((entity: number) => void) | undefinedrenderer_retainedTextStale: ((registry: CppRegistry, outPtr: number, capacity: number) => number) | undefined@@ -547,7 +547,7 @@ renderer_submitSkeletalBatchByEntity: ((registry: CppRegistry, verticesPtr: numbrenderer_submitSkeletalBatchByEntityEx: ((registry: CppRegistry, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, entity: number, skelScale: number, flipX: boolean, flipY: boolean, layer: number, depth: number, materialId: number, premultipliedColor: boolean) => void) | undefinedrenderer_submitSkeletalPreviewBatch: (preview: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number, layer: number, depth: number, materialId: number) => numberrenderer_submitSkeletalPreviewBatchEx: (preview: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number, layer: number, depth: number, materialId: number, premultipliedColor: boolean) => number-renderer_submitTextBatch: ((verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, transformPtr: number, entity: number, layer: number, depth: number, sdf: number, cullBit: number) => void) | undefined+renderer_submitTextBatch: ((verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, transformPtr: number, entity: number, layer: number, depth: number, glyphMode: number, cullBit: number) => void) | undefinedrenderer_takeFrameCapture: ((handle: number, dest: number, destSize: number) => boolean) | undefinedrenderer_updateTransforms: (registry: CppRegistry) => voidsdfFromAlpha: ((alphaPtr: number, outPtr: number, width: number, height: number, spread: number) => void) | undefineddiff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.tsindex 7fc1d8a70..3452c887d 100644--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts@@ -207,7 +207,7 @@ export interface NativeEngineApi {renderer_renderSkeletalPreview?(preview: number, viewProjectionPtr: number): number;renderer_replayToDrawCall?(drawCallIndex: number): void;renderer_resize?(width: number, height: number): void;- renderer_retainedTextBatch?(entity: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, pageId: number): void;+ renderer_retainedTextBatch?(entity: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, pageId: number, glyphMode: number): void;renderer_retainedTextBegin?(entity: number, sdf: number, screen: number, hasBox: number, layer: number, boxWidth: number, boxHeight: number, autoKind: number): void;renderer_retainedTextClear?(entity: number): void;renderer_retainedTextStale?(registry: unknown, outPtr: number, capacity: number): number;@@ -242,7 +242,7 @@ export interface NativeEngineApi {renderer_submitSkeletalBatchByEntityEx?(registry: unknown, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, entity: number, skelScale: number, flipX: boolean, flipY: boolean, layer: number, depth: number, materialId: number, premultipliedColor: boolean): void;renderer_submitSkeletalPreviewBatch?(preview: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number, layer: number, depth: number, materialId: number): number;renderer_submitSkeletalPreviewBatchEx?(preview: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number, layer: number, depth: number, materialId: number, premultipliedColor: boolean): number;- renderer_submitTextBatch?(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, transformPtr: number, entity: number, layer: number, depth: number, sdf: number, cullBit: number): void;+ renderer_submitTextBatch?(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, transformPtr: number, entity: number, layer: number, depth: number, glyphMode: number, cullBit: number): void;renderer_takeFrameCapture?(handle: number, dest: number, destSize: number): boolean;renderer_updateTransforms?(registry: unknown): void;rm_acquireTextureByPath?(rm: unknown, path: string): number;diff --git a/sdk/src/ecs/bridge/nativeRuntime.ts b/sdk/src/ecs/bridge/nativeRuntime.tsindex dface82e3..846e8f4ee 100644--- a/sdk/src/ecs/bridge/nativeRuntime.ts+++ b/sdk/src/ecs/bridge/nativeRuntime.ts@@ -279,11 +279,11 @@ function installNativeUI(app: App, scope: Record<string, unknown>): void {const submit = scope[TEXT_BINDINGS.submitTextBatch] as (vertices: Float32Array, vertexCount: number, indices: Uint16Array, indexCount: number,textureId: number, transform: Float32Array, entity: number, layer: number,- depth: number, sdf: number, cullBit: number,+ depth: number, glyphMode: number, cullBit: number,) => void;- setNativeTextSubmit((vertices, vertexCount, indices, textureId, transform, entity, layer, depth, sdf, cullBit) => {+ setNativeTextSubmit((vertices, vertexCount, indices, textureId, transform, entity, layer, depth, mode, cullBit) => {submit(vertices, vertexCount, indices, indices.length, textureId, transform,- entity, layer, depth, sdf ? 1 : 0, cullBit);+ entity, layer, depth, mode, cullBit);});app.addPlugin(uiPlugin);}diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.tsindex 02aa6f5ba..6ee666a32 100644--- a/sdk/src/ui/index.ts+++ b/sdk/src/ui/index.ts@@ -539,7 +539,7 @@ export {export { ShelfPacker, type Packer, type PackPos } from '../util/shelfPack';export { sdfFromAlpha } from './text/sdf';-export { submitTextBatch, TEXT_VERTEX_FLOATS } from './text/submit';+export { submitTextBatch, TEXT_VERTEX_FLOATS, TextGlyphMode } from './text/submit';export { ScreenOverlay, type ScreenOverlayData } from './core/screen-overlay';export { canvasRootEntities } from './core/canvas-roots';diff --git a/sdk/src/ui/text/bitmap-font.ts b/sdk/src/ui/text/bitmap-font.tsindex 5bc039a7d..62885d4e2 100644--- a/sdk/src/ui/text/bitmap-font.ts+++ b/sdk/src/ui/text/bitmap-font.ts@@ -41,6 +41,13 @@ export interface BmFont {pageHeight: number;/** The first page's image file, as the `.fnt` spells it. */page: string;+ /**+ * The page carries the glyph's outline in it, as BMFont's channel flags say: red is the glyph proper+ * (`redChnl=0`) and alpha is glyph and outline together (`alphaChnl=2`). Such a font is drawn in two passes —+ * the silhouette in the outline colour, the glyph on top — so the outline can be any colour, or absent.+ * A page that says nothing of its channels is a plain RGBA image to tint.+ */+ outlineInAlpha: boolean;glyphs: Map<number, BmGlyph>;}@@ -63,6 +70,7 @@ const int = (v: string | undefined, d = 0): number => {export function parseBmFont(text: string): BmFont {let size = 0, lineHeight = 0, base = 0, pageWidth = 0, pageHeight = 0, page = '';let sawCommon = false;+ let outlineInAlpha = false;const glyphs = new Map<number, BmGlyph>();for (const raw of text.split(/\r?\n/)) {const line = raw.trim();@@ -73,6 +81,8 @@ export function parseBmFont(text: string): BmFont {base = int(a.base);pageWidth = int(a.scaleW);pageHeight = int(a.scaleH);+ // BMFont's channel codes: 0 glyph, 1 outline, 2 glyph and outline.+ outlineInAlpha = int(a.alphaChnl, -1) === 2 && int(a.redChnl, -1) === 0;sawCommon = true;} else if (line.startsWith('page ')) {const a = attrs(line);@@ -87,7 +97,7 @@ export function parseBmFont(text: string): BmFont {}}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 };+ return { size: size || lineHeight, lineHeight, base, pageWidth, pageHeight, page, outlineInAlpha, glyphs };}/** A registered font: the table, and the GL texture id its glyphs are on (what a text batch binds). */diff --git a/sdk/src/ui/text/submit.ts b/sdk/src/ui/text/submit.tsindex 1c4db26b9..806eb64c1 100644--- a/sdk/src/ui/text/submit.ts+++ b/sdk/src/ui/text/submit.ts@@ -10,6 +10,23 @@import type { ESEngineModule } from '../../wasm';import { withScratch } from '../../wasm/wasmScratch';+/**+ * How a glyph page's pixels become coverage — the engine's `TextGlyphMode`, numbered as it is there. 0 and 1 are+ * what the `sdf` flag this replaced was (false, true).+ */+export const TextGlyphMode = {+ /** The page's RGBA, tinted: a rasterized atlas carrying native-AA coverage in alpha, or a colour font. */+ Color: 0,+ /** Alpha is a signed distance; coverage is derived from it. */+ Sdf: 1,+ /** Alpha alone is coverage and the page's colour is ignored: the silhouette of a glyph with its outline baked into the page. */+ Mask: 2,+ /** Red x alpha is coverage: the glyph proper of that page. Mask under Fill is the outlined glyph, its ring in any colour. */+ Fill: 3,+} as const;+/** @public */+export type TextGlyphMode = (typeof TextGlyphMode)[keyof typeof TextGlyphMode];+/** Floats per glyph vertex: position(2) + uv(2) + color(4) + sdfBias(1). */export const TEXT_VERTEX_FLOATS = 9;@@ -27,7 +44,7 @@ export type NativeTextBatchSubmit = (entity: number,layer: number,depth: number,- sdf: boolean,+ mode: number,cullBit: number,) => void;@@ -54,14 +71,16 @@ export function submitTextBatch(entity: number,layer: number,depth: number,- sdf: boolean,+ mode: TextGlyphMode | boolean,cullBit = 0,): void {+ // A caller from before there were modes passed whether the page was a distance field.+ const glyphMode: number = typeof mode === 'boolean' ? (mode ? TextGlyphMode.Sdf : TextGlyphMode.Color) : mode;const vertexCount = (vertices.length / TEXT_VERTEX_FLOATS) | 0;if (vertexCount <= 0 || indices.length <= 0 || transform.length < 16) return;// No wasm heap (the native core): the host reads the arrays as they are.if (!module?.renderer_submitTextBatch) {- nativeSubmit_?.(vertices, vertexCount, indices, textureId, transform, entity, layer, depth, sdf, cullBit);+ nativeSubmit_?.(vertices, vertexCount, indices, textureId, transform, entity, layer, depth, glyphMode, cullBit);return;}@@ -78,7 +97,7 @@ export function submitTextBatch(module.HEAPU8.set(iBytes, iPtr);module.HEAPU8.set(tBytes, tPtr);module.renderer_submitTextBatch!(- vPtr, vertexCount, iPtr, indices.length, textureId, tPtr, entity, layer, depth, sdf ? 1 : 0,+ vPtr, vertexCount, iPtr, indices.length, textureId, tPtr, entity, layer, depth, glyphMode,cullBit,);});diff --git a/sdk/src/ui/text/text-renderer.ts b/sdk/src/ui/text/text-renderer.tsindex 54a74df46..677b3671f 100644--- a/sdk/src/ui/text/text-renderer.ts+++ b/sdk/src/ui/text/text-renderer.ts@@ -19,12 +19,14 @@ import { NativeGlyphRasterizer } from './native-glyph-rasterizer';import { EngineAtlasPageStore } from './atlas-page-store';import { TextAlign, TextVerticalAlign, TextOverflow } from '../core/text';import { layoutText, buildGlyphVertices, MAX_TEXT_BATCH_GLYPHS, type LaidGlyph, type RGBA } from './layout';-import { submitTextBatch, TEXT_VERTEX_FLOATS } from './submit';+import { submitTextBatch, TEXT_VERTEX_FLOATS, TextGlyphMode } from './submit';+import { bitmapFontOf } from './bitmap-font';import { withScratch } from '../../wasm/wasmScratch';import type { EngineApi } from '../../ecs/bridge/engineApi';/** Receives index-safe glyph batches, each bound to one atlas page. */-export type GlyphBatchSink = (vertices: Float32Array, indices: Uint16Array, pageId: number) => void;+/** @p mode is how the page is read; left out, it is whatever the renderer's own kind draws (a distance field, or a plain bitmap page). */+export type GlyphBatchSink = (vertices: Float32Array, indices: Uint16Array, pageId: number, mode?: TextGlyphMode) => void;export interface DrawTextParams {text: string;@@ -229,13 +231,17 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTex// Emit the glyph set once per page, recolored + offset. All passes are SDF// glyphs in the same atlas/layer, so they batch and draw in submit order —// shadow + outline first (behind), fill last (on top).- const emitPass = (color: RGBA, dx: number, dy: number, bias = 0, useGlyphColors = false): void => {+ // A font with its outline baked into the page is read through two lenses (see BmFont.outlineInAlpha): Mask for everything+ // that is a shape — shadow, the outline ring — and Fill for the glyph. The page's own colours never show, so the ring is+ // whatever colour the outline asks for, and without an outline there is no ring at all.+ const baked = bitmapFontOf(p.fontFamily)?.outlineInAlpha === true;+ const emitPass = (color: RGBA, dx: number, dy: number, bias = 0, useGlyphColors = false, mode?: TextGlyphMode): void => {for (const [pageId, glyphs] of chunks) {const { vertices, indices } = buildGlyphVertices(glyphs, color, baseX + dx, originY + dy, bias, useGlyphColors);if (opacity !== 1) {for (let i = 7; i < vertices.length; i += TEXT_VERTEX_FLOATS) vertices[i] *= opacity;}- sink(vertices, indices, pageId);+ sink(vertices, indices, pageId, mode);}};@@ -248,24 +254,27 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTexconst a = tapAlpha(color[3], SHADOW_RING.length);const tap: RGBA = [color[0], color[1], color[2], a];for (const [rx, ry, r] of SHADOW_RING) {- emitPass(tap, dx + rx * blur * r, -dy + ry * blur * r);+ emitPass(tap, dx + rx * blur * r, -dy + ry * blur * r, 0, false, baked ? TextGlyphMode.Mask : undefined);}} else {- emitPass(color, dx, -dy);+ emitPass(color, dx, -dy, 0, false, baked ? TextGlyphMode.Mask : undefined);}}// Outline. On a distance-field atlas this is the glyph drawn once more with// its edge pushed out — a real dilation, so the shape survives any width. The// bitmap atlas has no distance to push, so it keeps the eight-way stamp, which// is only ever asked for hairlines there.- if (p.outline && p.outline.width > 0 && p.outline.color[3] > 0) {+ if (baked) {+ // The page has the ring already: it is drawn, not grown, so the width only says whether there is one.+ if (p.outline && p.outline.width > 0 && p.outline.color[3] > 0) emitPass(p.outline.color, 0, 0, 0, false, TextGlyphMode.Mask);+ } else if (p.outline && p.outline.width > 0 && p.outline.color[3] > 0) {const w = p.outline.width;const bias = outlineBias(atlas, fontSizePx, w);if (bias > 0) emitPass(p.outline.color, 0, 0, bias);else for (const [ox, oy] of OUTLINE_OFFSETS) emitPass(p.outline.color, ox * w, oy * w);}// Fill (on top).- emitPass(p.color, 0, 0, 0, true);+ emitPass(p.color, 0, 0, 0, true, baked ? TextGlyphMode.Fill : undefined);}export interface TextRendererOptions extends CanvasGlyphRasterizerOptions {@@ -282,6 +291,8 @@ interface CachedTextBatch extends TextCullGeometry {vertices: Float32Array;indices: Uint16Array;pageId: number;+ /** How the page is read; absent means the renderer's own kind. */+ mode?: TextGlyphMode;/** Original vertex alphas, retained lazily so repeated fades never compound. */alphas?: Float32Array;}@@ -297,6 +308,8 @@ interface TextCacheEntry {export class SdfTextRenderer {readonly atlas: GlyphAtlas;private readonly sdf: boolean;+ /** How a batch with no mode of its own is read: by the kind of atlas this renderer keeps. */+ private get defaultMode(): TextGlyphMode { return this.sdf ? TextGlyphMode.Sdf : TextGlyphMode.Color; }private readonly cache_ = new Map<number, TextCacheEntry>();private readonly clipPlanes_ = new Float64Array(36);private readonly drawn_ = new Set<number>();@@ -377,8 +390,8 @@ export class SdfTextRenderer {let entry = this.cache_.get(entity);if (!entry || entry.gen !== gen || entry.sig !== sig) {const batches: CachedTextBatch[] = [];- drawTextWith(this.atlas, (vertices, indices, pageId) => {- batches.push({ ...createTextCullGeometry(vertices, indices), pageId });+ drawTextWith(this.atlas, (vertices, indices, pageId, mode) => {+ batches.push({ ...createTextCullGeometry(vertices, indices), pageId, ...(mode !== undefined ? { mode } : {}) });}, { ...p, opacity: 1 });entry = { sig, gen, batches, opacity: 1 };this.cache_.set(entity, entry);@@ -395,7 +408,7 @@ export class SdfTextRenderer {}}const visible = clipTextGeometry(b, planes);- if (visible) submitTextBatch(this.module, visible.vertices, visible.indices, b.pageId, transform, entity, layer, depth, this.sdf, cullBit);+ if (visible) submitTextBatch(this.module, visible.vertices, visible.indices, b.pageId, transform, entity, layer, depth, b.mode ?? this.defaultMode, cullBit);}entry.opacity = opacity;}@@ -410,8 +423,10 @@ export class SdfTextRenderer {screen: boolean, hasBox: boolean, layer: number, boxWidth: number, boxHeight: number, autoKind: boolean,): void {if (this.atlas.metricsOnly) throw new Error('Measurement atlases cannot submit text.');- const batches: Array<{ vertices: Float32Array; indices: Uint16Array; pageId: number }> = [];- drawTextWith(this.atlas, (vertices, indices, pageId) => { batches.push({ vertices, indices, pageId }); }, { ...p, opacity: 1 });+ const batches: Array<{ vertices: Float32Array; indices: Uint16Array; pageId: number; mode?: TextGlyphMode }> = [];+ drawTextWith(this.atlas, (vertices, indices, pageId, mode) => {+ batches.push({ vertices, indices, pageId, ...(mode !== undefined ? { mode } : {}) });+ }, { ...p, opacity: 1 });api.renderer_retainedTextBegin!(entity, this.sdf ? 1 : 0, screen ? 1 : 0, hasBox ? 1 : 0, layer, boxWidth, boxHeight, autoKind ? 1 : 0);for (const b of batches) {const vertexCount = (b.vertices.length / TEXT_VERTEX_FLOATS) | 0;@@ -423,7 +438,7 @@ export class SdfTextRenderer {const iPtr = alloc(iBytes.byteLength);api.HEAPU8!.set(vBytes, vPtr);api.HEAPU8!.set(iBytes, iPtr);- api.renderer_retainedTextBatch!(entity, vPtr, vertexCount, iPtr, b.indices.length, b.pageId);+ api.renderer_retainedTextBatch!(entity, vPtr, vertexCount, iPtr, b.indices.length, b.pageId, b.mode ?? this.defaultMode);});}this.retainedPages_.set(entity, batches.map(b => b.pageId));diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 4902543a8..7d83096cb 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -428,14 +428,15 @@ export interface ESEngineModule {layer: number, depth: number, materialId: number, premultipliedColor: boolean): void;/**- * Submit pre-laid-out glyph quads. Vertex format x,y,u,v,r,g,b,a; `sdf` (1/0)- * selects the SDF variant vs the plain textured batch (device bitmap atlas).+ * Submit pre-laid-out glyph quads. Vertex format x,y,u,v,r,g,b,a,sdfBias; `glyphMode` (TextGlyphMode) says how the page's+ * pixels become coverage: 0 the plain textured batch (device bitmap atlas), 1 the SDF variant, 2 and 3 a baked-outline page's+ * silhouette and fill.*/renderer_submitTextBatch?(verticesPtr: number, vertexCount: number,indicesPtr: number, indexCount: number,textureId: number, transformPtr: number,- entity: number, layer: number, depth: number, sdf: number, cullBit: number+ entity: number, layer: number, depth: number, glyphMode: number, cullBit: number): void;/*** Retained text: glyph quads handed over once and submitted by the engine every frame (RetainedText.hpp). `Begin` starts or replaces an@@ -447,7 +448,7 @@ export interface ESEngineModule {): void;renderer_retainedTextBatch?(entity: number, verticesPtr: number, vertexCount: number,- indicesPtr: number, indexCount: number, pageId: number+ indicesPtr: number, indexCount: number, pageId: number, glyphMode: number): void;renderer_retainedTextClear?(entity: number): void;renderer_retainedTextStale?(registry: CppRegistry, outPtr: number, capacity: number): number;diff --git a/sdk/tests/nativeTextSubmit.test.ts b/sdk/tests/nativeTextSubmit.test.tsindex e943c8d8b..f3c050690 100644--- a/sdk/tests/nativeTextSubmit.test.ts+++ b/sdk/tests/nativeTextSubmit.test.ts@@ -5,7 +5,7 @@// The far side is generated from the C++ signature and opens `if (argc < 11)// return`, so a seam one argument short draws nothing and says nothing.import { describe, it, expect } from 'vitest';-import { submitTextBatch, setNativeTextSubmit, TEXT_VERTEX_FLOATS } from '../src/ui/text/submit';+import { submitTextBatch, setNativeTextSubmit, TEXT_VERTEX_FLOATS, TextGlyphMode } from '../src/ui/text/submit';function capture() {const calls: unknown[][] = [];@@ -46,4 +46,15 @@ describe('the native text submit seam', () => {expect(calls).toHaveLength(0);});++ it('hands the host the glyph mode as a number: a mode as given, and the old sdf flag as the mode it always meant', () => {+ const calls = capture();+ submitTextBatch(null, vertices, indices, 7, transform, 42, 3, 0.5, TextGlyphMode.Fill);+ submitTextBatch(null, vertices, indices, 7, transform, 42, 3, 0.5, TextGlyphMode.Mask);+ submitTextBatch(null, vertices, indices, 7, transform, 42, 3, 0.5, true);+ submitTextBatch(null, vertices, indices, 7, transform, 42, 3, 0.5, false);+ setNativeTextSubmit(null);+ // (vertices, vertexCount, indices, textureId, transform, entity, layer, depth, mode, cullBit)+ expect(calls.map((c) => c[8])).toEqual([3, 2, 1, 0]);+ });});diff --git a/sdk/tests/ui-text-bitmap-font.test.ts b/sdk/tests/ui-text-bitmap-font.test.tsindex cfd1fda83..8e5db9d16 100644--- a/sdk/tests/ui-text-bitmap-font.test.ts+++ b/sdk/tests/ui-text-bitmap-font.test.ts@@ -16,6 +16,8 @@ import {import { resolveTextFamily } from '../src/ui/text/font-registry';import { layoutText, measureWidth } from '../src/ui/text/layout';import { TextOverflow } from '../src/ui/core/text';+import { drawTextWith, type DrawTextParams } from '../src/ui/text/text-renderer';+import { TextGlyphMode } from '../src/ui/text/submit';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',@@ -137,3 +139,58 @@ describe('Text laying out with a bitmap font', () => {expect(l.width).toBeLessThanOrEqual(100 + 1e-6);});});++// A font that bakes its outline into the page says so in BMFont's own channel flags: red is the glyph, alpha is glyph and+// outline. Drawn through two lenses, the ring can be any colour — or, with no outline asked for, not drawn at all.+const BAKED = FNT.replace('pages=1 packed=0', 'pages=1 packed=0 alphaChnl=2 redChnl=0 greenChnl=0 blueChnl=0');++describe('a font with its outline baked into the page', () => {+ it('is recognised from the channel flags, and a page that says nothing is plain', () => {+ expect(parseBmFont(BAKED).outlineInAlpha).toBe(true);+ expect(parseBmFont(FNT).outlineInAlpha).toBe(false);+ // alpha as the outline alone, or as the glyph alone, is not this layout+ expect(parseBmFont(FNT.replace('pages=1 packed=0', 'pages=1 packed=0 alphaChnl=1 redChnl=0')).outlineInAlpha).toBe(false);+ expect(parseBmFont(FNT.replace('pages=1 packed=0', 'pages=1 packed=0 alphaChnl=0 redChnl=0')).outlineInAlpha).toBe(false);+ });++ const draw = (family: string, extra: Partial<DrawTextParams>): Array<{ pageId: number; mode: number | undefined }> => {+ const passes: Array<{ pageId: number; mode: number | undefined }> = [];+ drawTextWith(atlas(), (_v, _i, pageId, mode) => { passes.push({ pageId, mode }); }, {+ text: 'AB', fontFamily: family, fontSizePx: 40, color: [1, 1, 1, 1], ...extra,+ } as DrawTextParams);+ return passes;+ };+ const RING: DrawTextParams['outline'] = { color: [0, 0, 0, 0.5], width: 2 };++ it('draws the ring first, in the outline colour, then the glyph on the same page', () => {+ registerBitmapFont(5, parseBmFont(BAKED), PAGE_TEXTURE);+ expect(draw('bmfont:5', { outline: RING })).toEqual([+ { pageId: PAGE_TEXTURE, mode: TextGlyphMode.Mask },+ { pageId: PAGE_TEXTURE, mode: TextGlyphMode.Fill },+ ]);+ });++ it('draws no ring when no outline is asked for: the glyph proper only', () => {+ registerBitmapFont(5, parseBmFont(BAKED), PAGE_TEXTURE);+ expect(draw('bmfont:5', {})).toEqual([{ pageId: PAGE_TEXTURE, mode: TextGlyphMode.Fill }]);+ expect(draw('bmfont:5', { outline: { color: [0, 0, 0, 1], width: 0 } })).toHaveLength(1);+ expect(draw('bmfont:5', { outline: { color: [0, 0, 0, 0], width: 2 } })).toHaveLength(1);+ });++ it('shadows the silhouette, never the page\'s own colours', () => {+ registerBitmapFont(5, parseBmFont(BAKED), PAGE_TEXTURE);+ const passes = draw('bmfont:5', { shadow: { color: [0, 0, 0, 0.5], dx: 2, dy: 2, blur: 0 } });+ expect(passes.map((p) => p.mode)).toEqual([TextGlyphMode.Mask, TextGlyphMode.Fill]);+ });++ it('leaves a plain bitmap font and an outline font as they were: no mode of their own', () => {+ registerBitmapFont(6, parseBmFont(FNT), PAGE_TEXTURE);+ expect(draw('bmfont:6', { outline: RING }).every((p) => p.mode === undefined)).toBe(true);+ });+});++describe('the engine boundary names how a page is read', () => {+ it('numbers the modes as the engine does, with 0 and 1 what the sdf flag was', () => {+ expect(TextGlyphMode).toEqual({ Color: 0, Sdf: 1, Mask: 2, Fill: 3 });+ });+});diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex e7758d3bf..24cbefb81 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -186,7 +186,7 @@ void renderer_submitTextBatch(uintptr_t verticesPtr, i32 vertexCount,uintptr_t indicesPtr, i32 indexCount,u32 textureId, uintptr_t transformPtr,- u32 entity, i32 layer, f32 depth, i32 sdf, u32 cullBit+ u32 entity, i32 layer, f32 depth, i32 glyphMode, u32 cullBit) {if (!g_initialized || !g_renderFrame) return;if (vertexCount < 0 || indexCount < 0) return;@@ -196,7 +196,7 @@ void renderer_submitTextBatch(if (!vertices || !indices || !transform) return;g_renderFrame->submitTextBatch(vertices, vertexCount, indices, indexCount,- textureId, transform, Entity::fromRaw(entity), layer, depth, sdf != 0, cullBit);+ textureId, transform, Entity::fromRaw(entity), layer, depth, textGlyphModeFromRaw(glyphMode), cullBit);}void renderer_retainedTextBegin(@@ -208,14 +208,14 @@ void renderer_retainedTextBegin(void renderer_retainedTextBatch(u32 entity, uintptr_t verticesPtr, i32 vertexCount,- uintptr_t indicesPtr, i32 indexCount, u32 pageId+ uintptr_t indicesPtr, i32 indexCount, u32 pageId, i32 glyphMode) {if (!g_initialized || !g_renderFrame) return;if (vertexCount < 0 || indexCount < 0) return;auto* vertices = boundarySpan<f32>(verticesPtr, static_cast<u64>(vertexCount) * TEXT_VERTEX_FLOATS, "renderer_retainedTextBatch.vertices");auto* indices = boundarySpan<u16>(indicesPtr, static_cast<u64>(indexCount), "renderer_retainedTextBatch.indices");if (!vertices || !indices) return;- g_renderFrame->retainedText().add(entity, vertices, vertexCount, indices, indexCount, pageId);+ g_renderFrame->retainedText().add(entity, vertices, vertexCount, indices, indexCount, pageId, textGlyphModeFromRaw(glyphMode));}void renderer_retainedTextClear(u32 entity) {@@ -301,7 +301,7 @@ void renderer_retainedTextSubmit(ecs::Registry& registry, i32 screen, uintptr_tvertices = faded.data();}g_renderFrame->submitTextBatch(vertices, static_cast<i32>(vertexCount), indices, static_cast<i32>(vertexCount / 4 * 6),- batch.pageId, model, entity, layer, depth, text.sdf, cullBit);+ batch.pageId, model, entity, layer, depth, batch.mode, cullBit);}}}diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hppindex 90ca21806..4863a7374 100644--- a/src/esengine/bindings/RendererBindings.hpp+++ b/src/esengine/bindings/RendererBindings.hpp@@ -91,7 +91,7 @@ void renderer_submitTextBatch(uintptr_t verticesPtr, i32 vertexCount,uintptr_t indicesPtr, i32 indexCount,u32 textureId, uintptr_t transformPtr,- u32 entity, i32 layer, f32 depth, i32 sdf, u32 cullBit+ u32 entity, i32 layer, f32 depth, i32 glyphMode, u32 cullBit);/*** @name Retained text@@ -103,10 +103,11 @@ void renderer_submitTextBatch(void renderer_retainedTextBegin(u32 entity, i32 sdf, i32 screen, i32 hasBox, i32 layer, f32 boxWidth, f32 boxHeight, i32 autoKind);-/// One batch of glyph quads of the entity begun last: TEXT_VERTEX_FLOATS floats a vertex, whole quads, drawn from atlas page @p pageId.+/// One batch of glyph quads of the entity begun last: TEXT_VERTEX_FLOATS floats a vertex, whole quads, drawn from atlas page @p pageId and+/// read as @p glyphMode says (TextGlyphMode; 0 is a plain RGBA page, 1 a distance field).void renderer_retainedTextBatch(u32 entity, uintptr_t verticesPtr, i32 vertexCount,- uintptr_t indicesPtr, i32 indexCount, u32 pageId+ uintptr_t indicesPtr, i32 indexCount, u32 pageId, i32 glyphMode);/// Forgets an entity's retained text.void renderer_retainedTextClear(u32 entity);diff --git a/src/esengine/data/shaders/batch.esshader b/src/esengine/data/shaders/batch.esshaderindex 7d2785830..93086fcc5 100644--- a/src/esengine/data/shaders/batch.esshader+++ b/src/esengine/data/shaders/batch.esshader@@ -6,6 +6,14 @@// derives crisp, resolution-independent coverage instead of sampling RGBA.#pragma feature SDF+// Compile-time variants for a glyph page whose pixels are not a plain RGBA to tint (see TextGlyphMode). The tint comes from the vertices;+// the page only says how much of it each pixel covers.+// GLYPH_MASK coverage is the page's alpha and its colour is ignored: the silhouette of a glyph drawn with an outline baked into the page.+// GLYPH_FILL coverage is red x alpha: the glyph proper of that same page, where the outline ring is the part alpha covers and red does not.+// Drawn together, ring first, they are the outlined glyph with the ring in any colour, which a pre-coloured page cannot be.+#pragma feature GLYPH_MASK+#pragma feature GLYPH_FILL+// Compile-time variant: lit by the scene's 2D lights (Sprite.lit). Compiled as a// Lit-domain shader, so applyLighting2D + LightConstants are injected.#pragma feature LIT@@ -111,6 +119,10 @@ void main() {float screenPxDist = (dist - 0.5 + v_sdfBias) / max(fwidth(dist), 1e-6);float coverage = clamp(screenPxDist + 0.5, 0.0, 1.0);fragColor = vec4(tint.rgb, tint.a * coverage);+#elif defined(GLYPH_MASK)+ fragColor = vec4(tint.rgb, tint.a * texColor.a);+#elif defined(GLYPH_FILL)+ fragColor = vec4(tint.rgb, tint.a * texColor.r * texColor.a);#elif defined(LIT)// Flat normal; the tinted color is the albedo. Normal maps need a material.vec4 base = texColor * tint;@@ -233,6 +245,10 @@ struct VSOut {let screenPxDist = (dist - 0.5 + v.v_sdfBias) / max(fwidth(dist), 1e-6);let coverage = clamp(screenPxDist + 0.5, 0.0, 1.0);return vec4f(tint.rgb, tint.a * coverage);+#elif defined(GLYPH_MASK)+ return vec4f(tint.rgb, tint.a * texColor.a);+#elif defined(GLYPH_FILL)+ return vec4f(tint.rgb, tint.a * texColor.r * texColor.a);#elif defined(LIT)let base = texColor * tint;return vec4f(applyLighting2DLayer(base.rgb, vec3f(0.0, 0.0, 1.0), v.v_worldPos, v.v_lightLayer), base.a);diff --git a/src/esengine/renderer/draw/RetainedText.hpp b/src/esengine/renderer/draw/RetainedText.hppindex 9c24b9777..59dcaa297 100644--- a/src/esengine/renderer/draw/RetainedText.hpp+++ b/src/esengine/renderer/draw/RetainedText.hpp@@ -31,11 +31,12 @@ struct RetainedTextBatch {std::vector<u16> indices; ///< Six a quad, naming this batch's own vertices.std::vector<f32> blocks; ///< left, bottom, right, top of each RETAINED_TEXT_BLOCK_QUADS quads.u32 pageId = 0; ///< The atlas page, which is the draw's texture.+ TextGlyphMode mode = TextGlyphMode::Color; ///< How the page's pixels become coverage. A label may mix them: an outline's ring, then its fill.};struct RetainedText {std::vector<RetainedTextBatch> batches;- bool sdf = false;+ bool sdf = false; ///< The pipeline the label's glyphs were chosen for, by world scale (autoKind). What each batch draws with is its own `mode`.bool screen = false; ///< The domain the geometry was laid out for.bool hasBox = false; ///< Laid out in a UINode box, so ordered by the UI tree rather than by `layer`.bool autoKind = false; ///< The glyph pipeline was chosen from the entity's world scale, so a changed scale can change it.@@ -61,13 +62,15 @@ public:}/// One batch of an entity begun with begin(). False when it was not begun or the batch is not whole quads.- bool add(u32 entity, const f32* vertices, i32 vertexCount, const u16* indices, i32 indexCount, u32 pageId) {+ bool add(u32 entity, const f32* vertices, i32 vertexCount, const u16* indices, i32 indexCount, u32 pageId,+ TextGlyphMode mode = TextGlyphMode::Color) {const auto found = entries_.find(entity);if (found == entries_.end() || vertexCount <= 0 || indexCount <= 0 || vertexCount % 4 != 0 || indexCount != vertexCount / 4 * 6) return false;RetainedTextBatch& batch = found->second.batches.emplace_back();batch.vertices.assign(vertices, vertices + static_cast<usize>(vertexCount) * TEXT_VERTEX_FLOATS);batch.indices.assign(indices, indices + indexCount);batch.pageId = pageId;+ batch.mode = mode;const u32 quads = static_cast<u32>(vertexCount) / 4;batch.blocks.resize(static_cast<usize>((quads + RETAINED_TEXT_BLOCK_QUADS - 1) / RETAINED_TEXT_BLOCK_QUADS) * 4);for (u32 start = 0; start < quads; start += RETAINED_TEXT_BLOCK_QUADS) {diff --git a/src/esengine/renderer/draw/TextVertexFormat.hpp b/src/esengine/renderer/draw/TextVertexFormat.hppindex 05183cbe7..fdb505f4c 100644--- a/src/esengine/renderer/draw/TextVertexFormat.hpp+++ b/src/esengine/renderer/draw/TextVertexFormat.hpp@@ -10,4 +10,18 @@ namespace esengine {// The boundary validator and the renderer must consume the same stride.inline constexpr i32 TEXT_VERTEX_FLOATS = 9;+/// How a glyph page's pixels become coverage. The numbers are what crosses the script boundary: 0 and 1 are what the `sdf` flag it replaced was+/// (false, true), so a caller that has never heard of the others means what it always did.+enum class TextGlyphMode : u8 {+ Color = 0, ///< The page's RGBA, tinted: a rasterized atlas that carries native-AA coverage in alpha, or a font drawn in colour.+ Sdf = 1, ///< Alpha is a signed distance; coverage is derived from it, and sdfBias grows the glyph (an outline pass).+ Mask = 2, ///< Alpha alone is coverage and the page's colour is ignored: the silhouette of a glyph whose outline is baked into the page.+ Fill = 3, ///< Red x alpha is coverage: the glyph proper of that page. Mask underneath and Fill on top is the outlined glyph, ring in any colour.+};++/// The mode a raw script-side value names; anything out of range is Color, the draw that cannot be wrong about a page it does not understand.+inline TextGlyphMode textGlyphModeFromRaw(i32 raw) {+ return raw >= 0 && raw <= static_cast<i32>(TextGlyphMode::Fill) ? static_cast<TextGlyphMode>(raw) : TextGlyphMode::Color;+}+} // namespace esenginediff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex bd5864ea1..eab26ccb7 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -213,15 +213,16 @@ public:/*** Submit a batch of pre-laid-out glyph quads from TS. Same vertex format as* submitSpineBatch (x,y,u,v,r,g,b,a per vertex), RenderType::Text, atlas page- * = `textureId`. `sdf` picks the shader: true → the SDF variant (scalable SDF- * atlas); false → the plain textured batch (device-resolution bitmap atlas- * carrying native-AA coverage in alpha).+ * = `textureId`. `mode` picks the shader (see TextGlyphMode): Sdf → the SDF+ * variant (scalable SDF atlas); Color → the plain textured batch (device-resolution+ * bitmap atlas carrying native-AA coverage in alpha); Mask and Fill → the two+ * ways a bitmap font with its outline baked into the page is read.*/void submitTextBatch(const f32* vertices, i32 vertexCount,const u16* indices, i32 indexCount,u32 textureId, const f32* transform16,- Entity entity, i32 layer, f32 depth, bool sdf, u32 cullBit = 0+ Entity entity, i32 layer, f32 depth, TextGlyphMode mode, u32 cullBit = 0);/// The glyph quads of every label the text system laid out and handed over once, which the engine submits itself each frame.diff --git a/src/esengine/renderer/frame/RenderFrameSubmit.cpp b/src/esengine/renderer/frame/RenderFrameSubmit.cppindex e7d426e92..cb111787c 100644--- a/src/esengine/renderer/frame/RenderFrameSubmit.cpp+++ b/src/esengine/renderer/frame/RenderFrameSubmit.cpp@@ -45,7 +45,7 @@ void RenderFrame::submitTextBatch(const f32* vertices, i32 vertexCount,const u16* indices, i32 indexCount,u32 textureId, const f32* transform16,- Entity entity, i32 layer, f32 depth, bool sdf, u32 cullBit+ Entity entity, i32 layer, f32 depth, TextGlyphMode mode, u32 cullBit) {if (vertexCount <= 0 || indexCount <= 0|| !batchEntityVisible(draw_list_, clip_state_, entity, layer, cullBit)) return;@@ -65,13 +65,20 @@ void RenderFrame::submitTextBatch(dst[i] = { {worldPos.x, worldPos.y, worldPos.z}, pc, {v[2], v[3]}, 0.0f, v[8] };}- // sdf: the SDF variant derives coverage from the distance field; otherwise the- // featureless batch multiplies the atlas alpha (native-AA bitmap coverage) directly.+ // Sdf derives coverage from the distance field; Mask and Fill read a baked-outline page (see TextGlyphMode); Color is the featureless batch,+ // which multiplies the page's RGBA by the tint (native-AA bitmap coverage in alpha, or a colour font).+ u32 program = 0;+ switch (mode) {+ case TextGlyphMode::Sdf: program = batchProgram({"SDF"}); break;+ case TextGlyphMode::Mask: program = batchProgram({"GLYPH_MASK"}); break;+ case TextGlyphMode::Fill: program = batchProgram({"GLYPH_FILL"}); break;+ case TextGlyphMode::Color: program = batchProgram({}); break;+ }pushBatchCommand(pool_, draw_list_, clip_state_, vOff, static_cast<u32>(vertexCount), indices,static_cast<u32>(indexCount), BatchDrawKey{.stage = current_stage_,.layer = layer,- .shaderId = sdf ? batchProgram({"SDF"}) : batchProgram({}),+ .shaderId = program,.blend = BlendMode::Normal,.textureId = textureId,.depth = depth,diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hppindex e30c3c79f..b4e359f70 100644--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp@@ -12,6 +12,14 @@ inline constexpr const char* BATCH = R"esshader(#pragma shader "Batch"++++#pragma feature GLYPH_MASK+#pragma feature GLYPH_FILL+++#pragma feature LIT@@ -115,6 +123,10 @@ void main() {float screenPxDist = (dist - 0.5 + v_sdfBias) / max(fwidth(dist), 1e-6);float coverage = clamp(screenPxDist + 0.5, 0.0, 1.0);fragColor = vec4(tint.rgb, tint.a * coverage);+#elif defined(GLYPH_MASK)+ fragColor = vec4(tint.rgb, tint.a * texColor.a);+#elif defined(GLYPH_FILL)+ fragColor = vec4(tint.rgb, tint.a * texColor.r * texColor.a);#elif defined(LIT)vec4 base = texColor * tint;@@ -237,6 +249,10 @@ struct VSOut {let screenPxDist = (dist - 0.5 + v.v_sdfBias) / max(fwidth(dist), 1e-6);let coverage = clamp(screenPxDist + 0.5, 0.0, 1.0);return vec4f(tint.rgb, tint.a * coverage);+#elif defined(GLYPH_MASK)+ return vec4f(tint.rgb, tint.a * texColor.a);+#elif defined(GLYPH_FILL)+ return vec4f(tint.rgb, tint.a * texColor.r * texColor.a);#elif defined(LIT)let base = texColor * tint;return vec4f(applyLighting2DLayer(base.rgb, vec3f(0.0, 0.0, 1.0), v.v_worldPos, v.v_lightLayer), base.a);diff --git a/tests/renderer/test_batch_builder.cpp b/tests/renderer/test_batch_builder.cppindex 3080b5737..fc5449df6 100644--- a/tests/renderer/test_batch_builder.cpp+++ b/tests/renderer/test_batch_builder.cpp@@ -560,7 +560,7 @@ TEST_CASE("camera mask: hidden text and skeletal submissions upload no geometry"frame.setCullingMask(1u << 6);const int uploads = device.updateBufferCalls;for (u32 i = 0; i < 1000; ++i) {- frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], Entity(1), 4, 0, false);+ frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], Entity(1), 4, 0, TextGlyphMode::Color);frame.submitSkeletalBatch(skeletal, 4, indices, 6, 1, 0, &transform[0][0], Entity(2), 4, 0, 0, false);}frame.flush();@@ -569,7 +569,7 @@ TEST_CASE("camera mask: hidden text and skeletal submissions upload no geometry"frame.end();frame.begin(transform);frame.setCullingMask(1u << 6);- frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], Entity(1), 4, 0, false, 1u << 6);+ frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], Entity(1), 4, 0, TextGlyphMode::Color, 1u << 6);frame.submitSkeletalBatch(skeletal, 4, indices, 6, 1, 0, &transform[0][0], Entity(2), 6, 0, 0, false);frame.flush();CHECK(frame.stats().sprites == 0);@@ -816,7 +816,7 @@ TEST_CASE("UI scissor: affine corners determine the projected clip rectangle") {frame.begin(glm::ortho(-100.0f, 100.0f, -100.0f, 100.0f));frame.processMasks(registry, 0, 0, 200, 200);frame.collectAll(registry);- frame.submitTextBatch(vertices, 4, indices, 6, 1, &identity[0][0], child, 0, 0, false);+ frame.submitTextBatch(vertices, 4, indices, 6, 1, &identity[0][0], child, 0, 0, TextGlyphMode::Color);frame.flush();frame.end();CHECK(std::find(device.scissorRectangles.begin(), device.scissorRectangles.end(), expected)@@ -908,7 +908,7 @@ TEST_CASE("UI masks: collapsed parent bases clip the complete subtree") {frame.processMasks(registry, 0, 0, 64, 64);frame.collectAll(registry);const auto uploads = device.updateBufferCalls;- frame.submitTextBatch(vertices, 4, indices, 6, 1, &identity[0][0], child, 0, 0, false);+ frame.submitTextBatch(vertices, 4, indices, 6, 1, &identity[0][0], child, 0, 0, TextGlyphMode::Color);frame.flush();frame.end();CHECK(frame.stats().text == (collapsed ? 0 : 1));@@ -1267,7 +1267,7 @@ TEST_CASE("UI masks: deep grouping hierarchies reach their leaf without call-staframe.processMasks(registry, 0, 0, 64, 64);frame.collectAll(registry);const int uploads = device.updateBufferCalls;- frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], leaf, 0, 0, false);+ frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], leaf, 0, 0, TextGlyphMode::Color);frame.flush();if (empty) {CHECK(frame.stats().text == 0);@@ -1318,7 +1318,7 @@ TEST_CASE("UI stencil traversal keeps nested and sibling references in authoredframe.collectAll(registry);i32 layer = 0;for (Entity entity : {root, a, nested, b, deep, c, d, e}) {- frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], entity, layer++, 0, false);+ frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], entity, layer++, 0, TextGlyphMode::Color);}frame.flush();frame.end();@@ -1375,7 +1375,7 @@ TEST_CASE("UI stencil reference budget follows depth rather than sibling count")frame.collectAll(registry);i32 layer = 0;for (Entity entity : ordered) {- frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], entity, layer++, 0, false);+ frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], entity, layer++, 0, TextGlyphMode::Color);}frame.flush();frame.end();@@ -1702,7 +1702,7 @@ TEST_CASE("camera passes: empty text and skeletal clips recover on the next cameframe.setEntityClipRect(2, 0, 0, size.first, size.second);frame.collectAll(registry);const int uploads = device.updateBufferCalls;- frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], Entity(1), 0, 0, false);+ frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], Entity(1), 0, 0, TextGlyphMode::Color);frame.submitSkeletalBatch(skeletal, 4, indices, 6, 1, 0, &transform[0][0], Entity(2), 0, 0, 0, false);frame.flush();CHECK(device.updateBufferCalls == uploads);@@ -1712,7 +1712,7 @@ TEST_CASE("camera passes: empty text and skeletal clips recover on the next cameframe.begin(transform);frame.clearAllClipRects();frame.collectAll(registry);- frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], Entity(1), 0, 0, false);+ frame.submitTextBatch(text, 4, indices, 6, 1, &transform[0][0], Entity(1), 0, 0, TextGlyphMode::Color);frame.submitSkeletalBatch(skeletal, 4, indices, 6, 1, 0, &transform[0][0], Entity(2), 0, 0, 0, false);frame.flush();CHECK(frame.stats().text == 1);diff --git a/tests/renderer/test_retained_text.cpp b/tests/renderer/test_retained_text.cppindex dcfe0db8a..37df7d95c 100644--- a/tests/renderer/test_retained_text.cpp+++ b/tests/renderer/test_retained_text.cpp@@ -30,7 +30,34 @@ static std::vector<f32> floats(const std::string& line, usize skip) {return out;}+// How a batch's page is read travels with the batch: a label may draw an outline's ring and then its fill from the same page, so the mode is the+// batch's and not the label's. And what a script-side number means is pinned here, because 0 and 1 were once `sdf` = false, true.+static void checkGlyphModes() {+ CHECK(textGlyphModeFromRaw(0) == TextGlyphMode::Color && textGlyphModeFromRaw(1) == TextGlyphMode::Sdf, "0 and 1 are what the old sdf flag was");+ CHECK(textGlyphModeFromRaw(2) == TextGlyphMode::Mask && textGlyphModeFromRaw(3) == TextGlyphMode::Fill, "2 is the silhouette, 3 the fill");+ CHECK(textGlyphModeFromRaw(-1) == TextGlyphMode::Color && textGlyphModeFromRaw(4) == TextGlyphMode::Color, "a number no mode owns is the plain draw");++ const std::vector<f32> quad(RETAINED_TEXT_QUAD_FLOATS, 0.0f);+ const u16 indices[6] = {0, 1, 2, 2, 3, 0};+ RetainedTextStore store;+ store.begin(1, false, false, false, 0, 0.0f, 0.0f);+ CHECK(store.add(1, quad.data(), 4, indices, 6, 7), "a batch given no mode is accepted");+ CHECK(store.add(1, quad.data(), 4, indices, 6, 7, TextGlyphMode::Mask), "the ring of an outlined glyph");+ CHECK(store.add(1, quad.data(), 4, indices, 6, 7, TextGlyphMode::Fill), "and its fill");+ const auto& batches = store.entries().at(1).batches;+ CHECK(batches.size() == 3, "three batches");+ if (batches.size() == 3) {+ CHECK(batches[0].mode == TextGlyphMode::Color, "no mode is the plain draw, as before");+ CHECK(batches[1].mode == TextGlyphMode::Mask && batches[2].mode == TextGlyphMode::Fill, "each batch keeps its own mode, in order");+ }+ // The label's own flag is the pipeline chosen by world scale; it says nothing of what its batches draw with.+ store.begin(2, true, false, false, 0, 0.0f, 0.0f);+ store.add(2, quad.data(), 4, indices, 6, 7, TextGlyphMode::Fill);+ CHECK(store.entries().at(2).sdf && store.entries().at(2).batches.at(0).mode == TextGlyphMode::Fill, "the label's sdf and a batch's mode are separate things");+}+int main(int argc, char** argv) {+ checkGlyphModes();const std::string path = argc > 1 ? argv[1] : "tests/renderer/data/retained_text_cases.txt";std::ifstream file(path);if (!file) {