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
refactor(text): render Text via SDF, retire Canvas2D path + stopgap UIText (REARCH_GUI P1.4d)
esengine7a12871be5b6
diff --git a/desktop/public/scenes/ui-text-rect.esscene b/desktop/public/scenes/ui-text-rect.essceneindex ab5fb795c..d6344b1fc 100644--- a/desktop/public/scenes/ui-text-rect.esscene+++ b/desktop/public/scenes/ui-text-rect.esscene@@ -34,18 +34,15 @@{ "type": "Transform", "data": {} },{ "type": "UIRect", "data": { "anchorMin": { "x": 0.5, "y": 0.5 }, "anchorMax": { "x": 0.5, "y": 0.5 }, "size": { "x": 440, "y": 200 }, "pivot": { "x": 0.5, "y": 0.5 } } },{- "type": "UIText",+ "type": "Text","data": {- "content": "Centered in its UIRect 矩形内居中并自动换行",+ "content": "Centered in its UIRect 矩形内居中并自动换行测试","fontFamily": "sans-serif",- "fontSizePx": 40,+ "fontSize": 40,"color": { "r": 1, "g": 1, "b": 1, "a": 1 },- "style": 0,- "layer": 0,- "richText": false,"align": 1,- "lineHeight": 0,- "maxWidth": 0+ "verticalAlign": 1,+ "wordWrap": true}}],diff --git a/desktop/public/scenes/ui-text-sdf.esscene b/desktop/public/scenes/ui-text-sdf.essceneindex 8a453483b..065a53a0a 100644--- a/desktop/public/scenes/ui-text-sdf.esscene+++ b/desktop/public/scenes/ui-text-sdf.esscene@@ -15,24 +15,20 @@},{"id": 1,- "name": "SdfLabel",+ "name": "Label","parent": null,"children": [],"components": [- { "type": "Transform", "data": { "position": { "x": -180, "y": 120, "z": 0 } } },+ { "type": "Transform", "data": { "position": { "x": -150, "y": 45, "z": 0 } } },{- "type": "UIText",+ "type": "Text","data": {- "content": "The quick brown fox 中文自动换行测试字符断行",+ "content": "Ag Hi 文字\n<b>SDF</b> <color=#ff5050>rich</color>","fontFamily": "sans-serif",- "fontSizePx": 44,+ "fontSize": 56,"color": { "r": 1, "g": 1, "b": 1, "a": 1 },- "style": 0,- "layer": 0,- "richText": false,- "align": 0,- "lineHeight": 0,- "maxWidth": 360+ "align": 1,+ "richText": true}}],diff --git a/sdk/src/ui/TextPlugin.ts b/sdk/src/ui/TextPlugin.tsdeleted file mode 100644index eefbd637c..000000000--- a/sdk/src/ui/TextPlugin.ts+++ /dev/null@@ -1,135 +0,0 @@-import type { App, Plugin } from '../app';-import { type Entity } from '../types';-import { defineSystem, Schedule } from '../system';-import { registerComponent } from '../component';-import { Text, type TextData } from './core/text';-import { TextRenderer } from './TextRenderer';-import { UIRect, type UIRectData } from './core/ui-rect';-import { UIRenderer, UIVisualType } from './core/ui-renderer';-import type { UIRendererData } from './core/ui-renderer';-import { getEffectiveWidth, getEffectiveHeight, setUIRectSizeNative, ensureUIRenderer } from './uiHelpers';-import { getImageResolver, type DefaultImageResolver } from './ImageResolver';-import { parseRichText } from './RichTextParser';-import { SystemLabel, PluginName } from '../systemLabels';-import { log } from '../logger';--export class TextPlugin implements Plugin {- name = PluginName.Text;- dependencies = [PluginName.UILayout];-- build(app: App): void {- registerComponent('Text', Text);-- const module = app.wasmModule;- if (!module) {- log.warn('ui', 'TextPlugin: No WASM module available');- return;- }-- const renderer = new TextRenderer(module);- const world = app.world;- const lastRenderedTick = new Map<Entity, number>();- const lastContainerSize = new Map<Entity, string>();-- world.enableChangeTracking(Text);- world.enableChangeTracking(UIRect);-- app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [],- () => {- const resolver = getImageResolver();- renderer.setImageResolver(resolver);- if (resolver && 'retryFailed' in resolver) {- (resolver as DefaultImageResolver).retryFailed();- }- renderer.beginFrame();- renderer.cleanupOrphaned(e => world.valid(e) && world.has(e, Text));-- for (const entity of lastRenderedTick.keys()) {- if (!world.valid(entity) || !world.has(entity, Text)) {- if (world.valid(entity) && world.has(entity, UIRenderer)) {- const r = world.get(entity, UIRenderer) as UIRendererData;- r.texture = 0;- r.visualType = UIVisualType.None;- world.insert(entity, UIRenderer, r);- }- lastRenderedTick.delete(entity);- lastContainerSize.delete(entity);- }- }-- const entities = world.getEntitiesWithComponents([Text]);- for (const entity of entities) {- const text = world.get(entity, Text) as TextData;- const uiRect = world.has(entity, UIRect)- ? world.get(entity, UIRect) as UIRectData- : null;-- const prevTick = lastRenderedTick.get(entity);- const hasValidRenderer = world.has(entity, UIRenderer)- && (world.get(entity, UIRenderer) as UIRendererData).texture !== 0;-- const pendingForImage = resolver && resolver.pendingEntities.has(entity);- if (pendingForImage) resolver!.pendingEntities.delete(entity);-- if (prevTick !== undefined && hasValidRenderer && !pendingForImage) {- const textChanged = world.isChangedSince(entity, Text, prevTick);- if (!textChanged) {- const containerKey = uiRect- ? `${getEffectiveWidth(uiRect, entity)}|${getEffectiveHeight(uiRect, entity)}`- : '';- const prevKey = lastContainerSize.get(entity) ?? '';- if (containerKey === prevKey) continue;- if (!text.wordWrap) {- lastContainerSize.set(entity, containerKey);- continue;- }- }- }-- if (text.richText && resolver && 'trackEntity' in resolver) {- const runs = parseRichText(text.content);- const srcs: string[] = [];- for (const run of runs) {- if (run.type === 'image') srcs.push(run.src);- }- if (srcs.length > 0) {- (resolver as DefaultImageResolver).trackEntity(entity, srcs);- }- }-- ensureUIRenderer(world, entity);-- const effectiveRect = uiRect ? {- size: {- x: getEffectiveWidth(uiRect, entity),- y: getEffectiveHeight(uiRect, entity),- },- } : null;- const result = renderer.renderForEntity(entity, text, effectiveRect);- const r = world.get(entity, UIRenderer) as UIRendererData;- r.texture = result.textureHandle;- r.visualType = UIVisualType.Image;- r.color = { r: 1, g: 1, b: 1, a: 1 };- r.uvOffset = { x: 0, y: 0 };- r.uvScale = { x: 1, y: 1 };- world.insert(entity, UIRenderer, r);-- if (uiRect) {- setUIRectSizeNative(entity, result.width, result.height);- }-- const tick = world.getWorldTick();- lastRenderedTick.set(entity, tick);- const containerKey = uiRect- ? `${getEffectiveWidth(uiRect, entity)}|${getEffectiveHeight(uiRect, entity)}`- : '';- lastContainerSize.set(entity, containerKey);- }- },- { name: 'TextSystem' }- ), { runAfter: [SystemLabel.UILayout] });- }-}--export const textPlugin = new TextPlugin();diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.tsindex 1cd1bef7f..35544972b 100644--- a/sdk/src/ui/index.ts+++ b/sdk/src/ui/index.ts@@ -246,12 +246,14 @@ export {// ─── Rendering / text helpers ───────────────────────────────────────────────+// TextRenderer (Canvas2D) is retained only for TextInput until P1.5 migrates it.export {TextRenderer,type TextRenderResult,} from './TextRenderer';-export { TextPlugin, textPlugin } from './TextPlugin';+// The canonical Text component is now rendered via the SDF glyph atlas (P1.4d).+export { TextPlugin, textPlugin } from './text/plugin';// UI Math Utilitiesexport {@@ -368,15 +370,11 @@ export {// ─── SDF glyph-atlas text (REARCH_GUI P1) ───────────────────────────────────export {- UIText,UI_TEXT_BOLD,UI_TEXT_ITALIC,composeTRS,rectTextBox,- type UITextData,-} from './text/ui-text';--export { UITextPlugin, uiTextPlugin } from './text/plugin';+} from './text/text-transform';export {SdfTextRenderer,diff --git a/sdk/src/ui/text/layout.ts b/sdk/src/ui/text/layout.tsindex b1e55b406..e4f3e74d2 100644--- a/sdk/src/ui/text/layout.ts+++ b/sdk/src/ui/text/layout.ts@@ -14,7 +14,7 @@import type { GlyphAtlas } from './glyph-atlas';import { TEXT_VERTEX_FLOATS } from './submit';import { parseRichText } from '../RichTextParser';-import { UI_TEXT_BOLD, UI_TEXT_ITALIC } from './ui-text';+import { UI_TEXT_BOLD, UI_TEXT_ITALIC } from './text-transform';export interface TextLayoutOptions {/** Display font size in px. */diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.tsindex 79d84b252..3615ea7a8 100644--- a/sdk/src/ui/text/plugin.ts+++ b/sdk/src/ui/text/plugin.ts@@ -1,39 +1,39 @@/*** @file ui/text/plugin.ts- * @brief UITextPlugin — wires the dynamic SDF text path into the frame- * (REARCH_GUI P1.3c). A pre-flush callback scans UIText entities,- * composes each entity's world transform, and draws it through the- * TextRenderer (glyph atlas → batched SDF quads). The renderer is- * created lazily, so apps with no UIText pay nothing.+ * @brief TextPlugin — renders the `Text` component via the dynamic SDF glyph+ * atlas (REARCH_GUI P1.4d), replacing the legacy Canvas2D-per-entity+ * path. A pre-flush callback scans Text entities, composes the world+ * transform, places the text inside its UIRect box (no auto-size — the+ * UIRect is the box; rendering never mutates layout) and draws batched+ * SDF glyph quads. Renderer is created lazily.*/import type { App, Plugin } from '../../app';-import { Transform, type TransformData } from '../../component';-import { registerComponent } from '../../component';+import { Transform, type TransformData, registerComponent } from '../../component';import type { ESEngineModule } from '../../wasm';import type { Entity } from '../../types';import { SdfTextRenderer } from './text-renderer';-import { UIText, type UITextData, composeTRS, rectTextBox } from './ui-text';+import { composeTRS, rectTextBox, UI_TEXT_BOLD, UI_TEXT_ITALIC } from './text-transform';+import { Text, type TextData } from '../core/text';import { UIRect, type UIRectData } from '../core/ui-rect';import { getEffectiveWidth, getEffectiveHeight } from '../uiHelpers';-export class UITextPlugin implements Plugin {- name = 'uiText';+export class TextPlugin implements Plugin {+ name = 'text';private renderer_: SdfTextRenderer | null = null;private readonly matrix_ = new Float32Array(16);build(app: App): void {- registerComponent('UIText', UIText);+ registerComponent('Text', Text);const pipeline = app.pipeline;- if (!pipeline) return; // no render pipeline (e.g. logic-only host) → nothing to draw+ if (!pipeline) return; // logic-only host → nothing to drawconst world = app.world;pipeline.addPreFlushCallback(() => {- const entities = world.getEntitiesWithComponents([UIText, Transform]);- for (const e of entities) {+ for (const e of world.getEntitiesWithComponents([Text, Transform])) {const entity = e as Entity;- const t = world.get(entity, UIText) as UITextData;+ const t = world.get(entity, Text) as TextData;if (!t.content) continue;if (!this.renderer_) {@@ -42,38 +42,46 @@ export class UITextPlugin implements Plugin {const tr = world.get(entity, Transform) as TransformData;composeTRS(this.matrix_, tr.worldPosition, tr.worldRotation, tr.worldScale);- // In a UIRect (UI canvas), place + align + wrap the text inside the- // rect box; otherwise it's a world-space label at the entity origin.+ const style = (t.bold ? UI_TEXT_BOLD : 0) | (t.italic ? UI_TEXT_ITALIC : 0);+ // Text.lineHeight is a ratio of fontSize (legacy convention).+ const lineHeightPx = t.lineHeight > 0 ? t.lineHeight * t.fontSize : undefined;++ // A UIRect (UI canvas) is the text box: place + align + wrap inside it.+ // No UIRect ⇒ a world-space label anchored at the entity origin.let originX: number | undefined;let originY: number | undefined;- let maxWidth = t.maxWidth || undefined;+ let maxWidth: number | undefined;+ let boxHeight: number | undefined;if (world.has(entity, UIRect)) {const rect = world.get(entity, UIRect) as UIRectData;const w = getEffectiveWidth(rect, entity);const h = getEffectiveHeight(rect, entity);- const box = rectTextBox(rect.pivot.x, rect.pivot.y, w, h, t.fontSizePx);+ const box = rectTextBox(rect.pivot.x, rect.pivot.y, w, h, t.fontSize);originX = box.originX;originY = box.originY;- if (!maxWidth) maxWidth = box.maxWidth;+ boxHeight = box.boxHeight;+ if (t.wordWrap) maxWidth = box.maxWidth;}this.renderer_.drawText({text: t.content,fontFamily: t.fontFamily,- fontSizePx: t.fontSizePx,+ fontSizePx: t.fontSize,color: [t.color.r, t.color.g, t.color.b, t.color.a],- style: t.style,+ style,richText: t.richText,align: t.align,- lineHeight: t.lineHeight || undefined,+ verticalAlign: t.verticalAlign,+ lineHeight: lineHeightPx,maxWidth,+ boxHeight,originX,originY,},this.matrix_,entity as number,- t.layer,+ 0, // layer: UI z-order integration with UIElementPlugin is a follow-uptr.worldPosition.z,);}@@ -81,4 +89,4 @@ export class UITextPlugin implements Plugin {}}-export const uiTextPlugin = new UITextPlugin();+export const textPlugin = new TextPlugin();diff --git a/sdk/src/ui/text/text-renderer.ts b/sdk/src/ui/text/text-renderer.tsindex 81bddb52d..163809cc1 100644--- a/sdk/src/ui/text/text-renderer.ts+++ b/sdk/src/ui/text/text-renderer.ts@@ -36,6 +36,10 @@ export interface DrawTextParams {letterSpacing?: number;/** Word-wrap width in px (plain text); 0/undefined = no wrap. */maxWidth?: number;+ /** Vertical alignment within boxHeight: 0 top | 1 middle | 2 bottom. */+ verticalAlign?: number;+ /** Box height (px) for vertical alignment; omit for top-anchored. */+ boxHeight?: number;}/**@@ -55,6 +59,14 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTex}, p.style ?? 0);if (layout.glyphs.length === 0) return;+ // Vertical alignment within the box: shift the whole block down (y-up) by the+ // slack between the box and the content. layout.lineHeight is total block height.+ let originY = p.originY ?? 0;+ if (p.boxHeight && p.boxHeight > 0 && p.verticalAlign) {+ const slack = p.boxHeight - layout.lineHeight;+ originY -= p.verticalAlign === 1 ? slack / 2 : slack; // 1 middle, 2 bottom+ }+// A string can reference glyphs across several atlas pages; each page is a// distinct texture, so group by page and emit one batch per page.const byPage = new Map<number, LaidGlyph[]>();@@ -64,7 +76,7 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTexarr.push(g);}for (const [pageId, glyphs] of byPage) {- const { vertices, indices } = buildGlyphVertices(glyphs, p.color, p.originX ?? 0, p.originY ?? 0);+ const { vertices, indices } = buildGlyphVertices(glyphs, p.color, p.originX ?? 0, originY);sink(vertices, indices, pageId);}}diff --git a/sdk/src/ui/text/text-transform.ts b/sdk/src/ui/text/text-transform.tsnew file mode 100644index 000000000..2ef17e8d3--- /dev/null+++ b/sdk/src/ui/text/text-transform.ts@@ -0,0 +1,51 @@+/**+ * @file ui/text/text-transform.ts+ * @brief Pure placement helpers for SDF text (REARCH_GUI P1.4d): the entity+ * world matrix and the rect→text-box mapping. No component here — the+ * canonical text component is core/text.ts `Text`, rendered by the SDF+ * text plugin.+ */+import type { Vec3, Quat } from '../../types';++/** Style bit flags — bold | italic (the atlas cache-key + rasterizer style arg). */+export const UI_TEXT_BOLD = 1;+export const UI_TEXT_ITALIC = 2;++/**+ * Compose a column-major mat4 into `out` from translation, rotation quaternion,+ * and scale — the entity world transform applied to glyph local positions at+ * submit. Pure (gl-matrix fromRotationTranslationScale), unit-testable.+ */+export function composeTRS(out: Float32Array, t: Vec3, q: Quat, s: Vec3): Float32Array {+ const { x, y, z, w } = q;+ const x2 = x + x, y2 = y + y, z2 = z + z;+ const xx = x * x2, xy = x * y2, xz = x * z2;+ const yy = y * y2, yz = y * z2, zz = z * z2;+ const wx = w * x2, wy = w * y2, wz = w * z2;+ const sx = s.x, sy = s.y, sz = s.z;++ out[0] = (1 - (yy + zz)) * sx; out[1] = (xy + wz) * sx; out[2] = (xz - wy) * sx; out[3] = 0;+ out[4] = (xy - wz) * sy; out[5] = (1 - (xx + zz)) * sy; out[6] = (yz + wx) * sy; out[7] = 0;+ out[8] = (xz + wy) * sz; out[9] = (yz - wx) * sz; out[10] = (1 - (xx + yy)) * sz; out[11] = 0;+ out[12] = t.x; out[13] = t.y; out[14] = t.z; out[15] = 1;+ return out;+}++/**+ * Place a text block inside a UIRect. The entity Transform sits at the rect's+ * pivot (UI layout positions the pivot), so glyph local positions (baseline y=0,+ * y-up) are offset to the rect's top-left; the rect width is the wrap/align box+ * and `boxHeight` lets the renderer apply vertical alignment. Top-vertical by+ * default: the first line's baseline is one ascent below the rect top+ * (ascent ≈ fontSize × 0.8). Pure.+ */+export function rectTextBox(+ pivotX: number, pivotY: number, width: number, height: number, fontSizePx: number,+): { originX: number; originY: number; maxWidth: number; boxHeight: number } {+ return {+ originX: -pivotX * width,+ originY: (1 - pivotY) * height - fontSizePx * 0.8,+ maxWidth: width,+ boxHeight: height,+ };+}diff --git a/sdk/src/ui/text/ui-text.ts b/sdk/src/ui/text/ui-text.tsdeleted file mode 100644index 178371c97..000000000--- a/sdk/src/ui/text/ui-text.ts+++ /dev/null@@ -1,83 +0,0 @@-/**- * @file ui/text/ui-text.ts- * @brief UIText component — the opt-in driver for the dynamic SDF text path- * (REARCH_GUI P1.3c). Authored on entities (serializes via the scene- * system); the UITextPlugin pre-flush system renders it. Kept separate- * from the legacy core/text.ts Text (Canvas2D per-entity) so the two- * don't double-render; P1.4 migrates Text → UIText and retires the old- * path.- */-import { defineComponent } from '../../component';-import type { Color, Vec3, Quat } from '../../types';--/** Style bit flags — bold | italic. */-export const UI_TEXT_BOLD = 1;-export const UI_TEXT_ITALIC = 2;--export interface UITextData {- content: string;- fontFamily: string;- fontSizePx: number;- color: Color;- /** Bit flags: UI_TEXT_BOLD | UI_TEXT_ITALIC. */- style: number;- layer: number;- /** Parse `<b>/<i>/<color>/<font size>` markup in `content`. */- richText: boolean;- /** Horizontal alignment: 0 left | 1 center | 2 right. */- align: number;- /** Baseline-to-baseline px for multi-line text; 0 = auto (fontSizePx × 1.2). */- lineHeight: number;- /** Word-wrap width in px (plain text); 0 = no wrap. */- maxWidth: number;-}--export const UIText = defineComponent<UITextData>('UIText', {- content: '',- fontFamily: 'sans-serif',- fontSizePx: 24,- color: { r: 1, g: 1, b: 1, a: 1 },- style: 0,- layer: 0,- richText: false,- align: 0,- lineHeight: 0,- maxWidth: 0,-});--/**- * Compose a column-major mat4 into `out` from translation, rotation quaternion,- * and scale — the entity world transform applied to glyph local positions at- * submit. Pure (gl-matrix fromRotationTranslationScale), so it is unit-testable.- */-export function composeTRS(out: Float32Array, t: Vec3, q: Quat, s: Vec3): Float32Array {- const { x, y, z, w } = q;- const x2 = x + x, y2 = y + y, z2 = z + z;- const xx = x * x2, xy = x * y2, xz = x * z2;- const yy = y * y2, yz = y * z2, zz = z * z2;- const wx = w * x2, wy = w * y2, wz = w * z2;- const sx = s.x, sy = s.y, sz = s.z;-- out[0] = (1 - (yy + zz)) * sx; out[1] = (xy + wz) * sx; out[2] = (xz - wy) * sx; out[3] = 0;- out[4] = (xy - wz) * sy; out[5] = (1 - (xx + zz)) * sy; out[6] = (yz + wx) * sy; out[7] = 0;- out[8] = (xz + wy) * sz; out[9] = (yz - wx) * sz; out[10] = (1 - (xx + yy)) * sz; out[11] = 0;- out[12] = t.x; out[13] = t.y; out[14] = t.z; out[15] = 1;- return out;-}--/**- * Place a text block inside a UIRect (REARCH_GUI P1.4c). The entity Transform- * sits at the rect's pivot (UI layout positions the pivot), so glyph local- * positions (baseline y=0, y-up) need offsetting to the rect's top-left, and the- * rect width becomes the wrap/align box. Top-vertical-aligned; first line's- * baseline sits one ascent below the rect top (ascent ≈ fontSize × 0.8). Pure.- */-export function rectTextBox(- pivotX: number, pivotY: number, width: number, height: number, fontSizePx: number,-): { originX: number; originY: number; maxWidth: number } {- return {- originX: -pivotX * width, // rect left edge, local to the pivot- originY: (1 - pivotY) * height - fontSizePx * 0.8, // rect top (y-up) minus first-line ascent- maxWidth: width,- };-}diff --git a/sdk/src/uiPlugins.ts b/sdk/src/uiPlugins.tsindex 628abef29..16663a495 100644--- a/sdk/src/uiPlugins.ts+++ b/sdk/src/uiPlugins.ts@@ -1,4 +1,4 @@-import { textPlugin } from './ui/TextPlugin';+import { textPlugin } from './ui/text/plugin';import { uiMaskPlugin } from './ui/UIMaskPlugin';import { uiInteractionPlugin } from './ui/UIInteractionPlugin';import { uiBehaviorPlugin } from './ui/plugin';@@ -10,9 +10,10 @@ import { scrollViewPlugin } from './ui/ScrollViewPlugin';import { focusPlugin } from './ui/FocusPlugin';import { safeAreaPlugin } from './ui/SafeAreaPlugin';import { uiRenderOrderPlugin } from './ui/UIRenderOrderPlugin';-import { uiTextPlugin } from './ui/text/plugin';import type { Plugin } from './app';+// `textPlugin` now renders the Text component via the dynamic SDF glyph atlas+// (REARCH_GUI P1.4d); the legacy Canvas2D-per-entity path is retired.export const uiPlugins: Plugin[] = [textPlugin, uiMaskPlugin, uiLayoutPlugin,imagePlugin,@@ -20,7 +21,4 @@ export const uiPlugins: Plugin[] = [textInputPlugin,focusPlugin, safeAreaPlugin,uiRenderOrderPlugin,- // REARCH_GUI P1.3c: SDF glyph-atlas text path. Opt-in via the UIText- // component; renders nothing unless an entity carries one.- uiTextPlugin,];diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.tsindex d332ee22f..e0fef05f7 100644--- a/sdk/src/webAppFactory.ts+++ b/sdk/src/webAppFactory.ts@@ -14,7 +14,7 @@ import { SpinePlugin, WebSpineWasmProvider } from './spine';import type { SpineWasmProvider } from './spine';export { uiPlugins };-export { textPlugin, TextPlugin } from './ui/TextPlugin';+export { textPlugin, TextPlugin } from './ui/text/plugin';export { uiMaskPlugin, UIMaskPlugin } from './ui/UIMaskPlugin';export { uiInteractionPlugin, UIInteractionPlugin } from './ui/UIInteractionPlugin';export { uiLayoutPlugin, UILayoutPlugin } from './ui/UILayoutPlugin';diff --git a/sdk/tests/nested-text.test.ts b/sdk/tests/nested-text.test.tsdeleted file mode 100644index e32856b33..000000000--- a/sdk/tests/nested-text.test.ts+++ /dev/null@@ -1,302 +0,0 @@-/**- * Regression test: nested Text entities (parent Text → child Text) must- * both produce visible Sprite components with valid texture handles.- *- * Bug: when a Text entity is created as a child of another Text entity,- * only one text renders visually.- */-import { describe, it, expect, beforeAll } from 'vitest';-import { App } from '../src/app';-import { Transform, Sprite, Canvas } from '../src/component';-import type { SpriteData } from '../src/component';-import { UIRect } from '../src/ui/core/ui-rect';-import type { UIRectData } from '../src/ui/core/ui-rect';-import { UICameraInfo } from '../src/ui/UICameraInfo';-import { Input, InputState } from '../src/input';-import { UIEvents, UIEventQueue } from '../src/ui/core/events';-import { uiLayoutPlugin } from '../src/ui/UILayoutPlugin';-import { uiRenderOrderPlugin } from '../src/ui/UIRenderOrderPlugin';-import { Text } from '../src/ui/core/text';-import type { TextData } from '../src/ui/core/text';-import { textPlugin } from '../src/ui/TextPlugin';-import { INVALID_TEXTURE } from '../src/types';-import type { ESEngineModule, CppRegistry } from '../src/wasm';-import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';--describe.skipIf(!HAS_WASM)('Nested Text Entities (WASM integration)', () => {- let module: ESEngineModule;-- beforeAll(async () => {- module = await loadWasmModule();- });-- function createApp(includeTextPlugin = false) {- const app = App.new();- const registry = new module.Registry() as unknown as CppRegistry;- app.connectCpp(registry, module);-- app.insertResource(UICameraInfo, {- viewProjection: new Float32Array(16),- vpX: 0, vpY: 0, vpW: 800, vpH: 600,- screenW: 800, screenH: 600,- worldLeft: -400, worldBottom: -300, worldRight: 400, worldTop: 300,- worldMouseX: 0, worldMouseY: 0,- valid: true,- });- app.insertResource(Input, new InputState());- app.insertResource(UIEvents, new UIEventQueue());-- app.addPlugin(uiLayoutPlugin);- app.addPlugin(uiRenderOrderPlugin);- if (includeTextPlugin) {- app.addPlugin(textPlugin);- }-- return { app, registry };- }-- function disposeApp(app: App, registry: CppRegistry): void {- const world = app.world;- for (const e of world.getAllEntities()) {- try { world.despawn(e); } catch (_) {}- }- world.disconnectCpp();- (registry as any).delete();- }-- function createCanvasRoot(app: App) {- const world = app.world;- const root = world.spawn();- world.insert(root, Canvas, {});- world.insert(root, UIRect, {- anchorMin: { x: 0, y: 0 },- anchorMax: { x: 1, y: 1 },- offsetMin: { x: 0, y: 0 },- offsetMax: { x: 0, y: 0 },- size: { x: 0, y: 0 },- pivot: { x: 0.5, y: 0.5 },- });- world.insert(root, Transform, {- position: { x: 0, y: 0, z: 0 },- rotation: { x: 0, y: 0, z: 0, w: 1 },- scale: { x: 1, y: 1, z: 1 },- });- return root;- }-- function createTextEntity(app: App, parent: number, content: string) {- const world = app.world;- const entity = world.spawn();- world.setParent(entity, parent);- world.insert(entity, Transform, {- position: { x: 0, y: 0, z: 0 },- rotation: { x: 0, y: 0, z: 0, w: 1 },- scale: { x: 1, y: 1, z: 1 },- });- world.insert(entity, UIRect, {- anchorMin: { x: 0.5, y: 0.5 },- anchorMax: { x: 0.5, y: 0.5 },- offsetMin: { x: 0, y: 0 },- offsetMax: { x: 0, y: 0 },- size: { x: 100, y: 100 },- pivot: { x: 0.5, y: 0.5 },- });- world.insert(entity, Text, {- content,- fontFamily: 'Arial',- fontSize: 24,- color: { r: 0, g: 0, b: 0, a: 1 },- align: 1,- verticalAlign: 1,- wordWrap: true,- overflow: 0,- lineHeight: 1.2,- });- return entity;- }-- it('both nested text entities should have Sprite after tick (manual sprites)', () => {- const { app, registry } = createApp(false);- const world = app.world;-- const root = createCanvasRoot(app);- const parentText = createTextEntity(app, root, 'Parent');- const childText = createTextEntity(app, parentText, 'Child');-- // Manually add Sprite to both (simulating what TextPlugin would do)- world.insert(parentText, Sprite, {- texture: INVALID_TEXTURE,- color: { r: 1, g: 1, b: 1, a: 1 },- size: { x: 50, y: 20 },- uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 },- layer: 0,- flipX: false,- flipY: false,- material: 0,- enabled: true,- });- world.insert(childText, Sprite, {- texture: INVALID_TEXTURE,- color: { r: 1, g: 1, b: 1, a: 1 },- size: { x: 50, y: 20 },- uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 },- layer: 0,- flipX: false,- flipY: false,- material: 0,- enabled: true,- });-- app.tick(1 / 60);-- // Both sprites should exist and be enabled- expect(world.has(parentText, Sprite)).toBe(true);- expect(world.has(childText, Sprite)).toBe(true);-- const parentSprite = world.get(parentText, Sprite) as SpriteData;- const childSprite = world.get(childText, Sprite) as SpriteData;-- // Both should be enabled- expect(parentSprite.enabled).toBe(true);- expect(childSprite.enabled).toBe(true);-- // UILayoutLateSystem should set sizes to UIRect computed dimensions- expect(parentSprite.size.x).toBeGreaterThan(0);- expect(parentSprite.size.y).toBeGreaterThan(0);- expect(childSprite.size.x).toBeGreaterThan(0);- expect(childSprite.size.y).toBeGreaterThan(0);-- disposeApp(app, registry);- });-- it('child text entity overlaps parent at same position with default UIRect', () => {- const { app, registry } = createApp(false);- const world = app.world;-- const root = createCanvasRoot(app);- const parentText = createTextEntity(app, root, 'Parent');- const childText = createTextEntity(app, parentText, 'Child');-- // Add sprites manually- world.insert(parentText, Sprite, {- texture: INVALID_TEXTURE,- color: { r: 1, g: 1, b: 1, a: 1 },- size: { x: 50, y: 20 },- uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 },- layer: 0,- flipX: false,- flipY: false,- });- world.insert(childText, Sprite, {- texture: INVALID_TEXTURE,- color: { r: 1, g: 1, b: 1, a: 1 },- size: { x: 50, y: 20 },- uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 },- layer: 0,- flipX: false,- flipY: false,- });-- app.tick(1 / 60);-- // With default UIRect (anchorMin=0.5, anchorMax=0.5, size=100x100),- // both texts are centered in their parent rect.- // The child's local position should be (0, 0) → same world position as parent.- // This causes them to overlap perfectly, appearing as a single text.- const parentTransform = world.get(parentText, Transform) as any;- const childTransform = world.get(childText, Transform) as any;-- // Child local position should be ~0 (centered in parent)- expect(Math.abs(childTransform.position.x)).toBeLessThan(0.01);- expect(Math.abs(childTransform.position.y)).toBeLessThan(0.01);-- // Both sprites have same size (from UIRect 100x100)- const parentSprite = world.get(parentText, Sprite) as SpriteData;- const childSprite = world.get(childText, Sprite) as SpriteData;- expect(parentSprite.size.x).toBeCloseTo(childSprite.size.x, 0);- expect(parentSprite.size.y).toBeCloseTo(childSprite.size.y, 0);-- disposeApp(app, registry);- });-- it('both text entities are returned by getEntitiesWithComponents', () => {- const { app, registry } = createApp(false);- const world = app.world;-- const root = createCanvasRoot(app);- const parentText = createTextEntity(app, root, 'Parent');- const childText = createTextEntity(app, parentText, 'Child');-- const textEntities = world.getEntitiesWithComponents([Text]);- expect(textEntities).toContain(parentText);- expect(textEntities).toContain(childText);- expect(textEntities.length).toBeGreaterThanOrEqual(2);-- disposeApp(app, registry);- });-- it('TextPlugin should create sprites for both nested text entities', () => {- let canvasSupported = true;- try {- // Test if canvas is available in the test environment- const canvas = typeof OffscreenCanvas !== 'undefined'- ? new OffscreenCanvas(64, 64)- : document.createElement('canvas');- const ctx = canvas.getContext('2d');- if (!ctx) canvasSupported = false;- // Test getImageData support- if (ctx && 'getImageData' in ctx) {- ctx.getImageData(0, 0, 1, 1);- } else {- canvasSupported = false;- }- } catch {- canvasSupported = false;- }-- if (!canvasSupported) {- console.warn('Skipping TextPlugin test: Canvas 2D not supported in test env');- return;- }-- const { app, registry } = createApp(true);- const world = app.world;-- const root = createCanvasRoot(app);- const parentText = createTextEntity(app, root, 'Parent');- const childText = createTextEntity(app, parentText, 'Child');-- app.tick(1 / 60);-- // TextPlugin should have created Sprite for both entities- expect(world.has(parentText, Sprite)).toBe(true);- expect(world.has(childText, Sprite)).toBe(true);-- const parentSprite = world.get(parentText, Sprite) as SpriteData;- const childSprite = world.get(childText, Sprite) as SpriteData;-- // Both should be enabled- expect(parentSprite.enabled).toBe(true);- expect(childSprite.enabled).toBe(true);-- // Both should have non-zero sizes- expect(parentSprite.size.x).toBeGreaterThan(0);- expect(parentSprite.size.y).toBeGreaterThan(0);- expect(childSprite.size.x).toBeGreaterThan(0);- expect(childSprite.size.y).toBeGreaterThan(0);-- // Both should have valid (non-INVALID) texture handles- // TextPlugin creates real GPU textures via rm.createTexture- expect(parentSprite.texture).not.toBe(INVALID_TEXTURE);- expect(childSprite.texture).not.toBe(INVALID_TEXTURE);-- // Texture handles should be different (each entity gets its own texture)- expect(parentSprite.texture).not.toBe(childSprite.texture);-- disposeApp(app, registry);- });-});diff --git a/sdk/tests/text-multi-render.test.ts b/sdk/tests/text-multi-render.test.tsdeleted file mode 100644index 4caa658bc..000000000--- a/sdk/tests/text-multi-render.test.ts+++ /dev/null@@ -1,272 +0,0 @@-/**- * Regression test: multiple Text entities must each get distinct,- * valid GPU textures. Bug: only the last-created text is visible- * in the editor, implying earlier textures are lost or overwritten.- */-import { describe, it, expect, beforeAll } from 'vitest';-import { App } from '../src/app';-import { Transform, Sprite, Canvas } from '../src/component';-import type { SpriteData } from '../src/component';-import { UIRect } from '../src/ui/core/ui-rect';-import { UICameraInfo } from '../src/ui/UICameraInfo';-import { Input, InputState } from '../src/input';-import { UIEvents, UIEventQueue } from '../src/ui/core/events';-import { uiLayoutPlugin } from '../src/ui/UILayoutPlugin';-import { uiRenderOrderPlugin } from '../src/ui/UIRenderOrderPlugin';-import { textPlugin } from '../src/ui/TextPlugin';-import { Text } from '../src/ui/core/text';-import { INVALID_TEXTURE } from '../src/types';-import type { ESEngineModule, CppRegistry } from '../src/wasm';-import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';--describe.skipIf(!HAS_WASM)('Multiple Text Entities (WASM)', () => {- let module: ESEngineModule;-- beforeAll(async () => {- module = await loadWasmModule();- });-- function createApp(includeTextPlugin = false) {- const app = App.new();- const registry = new module.Registry() as unknown as CppRegistry;- app.connectCpp(registry, module);-- app.insertResource(UICameraInfo, {- viewProjection: new Float32Array(16),- vpX: 0, vpY: 0, vpW: 800, vpH: 600,- screenW: 800, screenH: 600,- worldLeft: -400, worldBottom: -300, worldRight: 400, worldTop: 300,- worldMouseX: 0, worldMouseY: 0,- valid: true,- });- app.insertResource(Input, new InputState());- app.insertResource(UIEvents, new UIEventQueue());-- app.addPlugin(uiLayoutPlugin);- app.addPlugin(uiRenderOrderPlugin);- if (includeTextPlugin) {- app.addPlugin(textPlugin);- }-- return { app, registry };- }-- function disposeApp(app: App, registry: CppRegistry): void {- const world = app.world;- for (const e of world.getAllEntities()) {- try { world.despawn(e); } catch (_) {}- }- world.disconnectCpp();- (registry as any).delete();- }-- function createCanvasRoot(app: App) {- const world = app.world;- const root = world.spawn();- world.insert(root, Canvas, {});- world.insert(root, UIRect, {- anchorMin: { x: 0, y: 0 }, anchorMax: { x: 1, y: 1 },- offsetMin: { x: 0, y: 0 }, offsetMax: { x: 0, y: 0 },- size: { x: 0, y: 0 }, pivot: { x: 0.5, y: 0.5 },- });- world.insert(root, Transform, {- position: { x: 0, y: 0, z: 0 },- rotation: { x: 0, y: 0, z: 0, w: 1 },- scale: { x: 1, y: 1, z: 1 },- });- return root;- }-- function createTextEntity(app: App, parent: number, content: string, yOffset: number) {- const world = app.world;- const entity = world.spawn();- world.setParent(entity, parent);- world.insert(entity, Transform, {- position: { x: 0, y: yOffset, z: 0 },- rotation: { x: 0, y: 0, z: 0, w: 1 },- scale: { x: 1, y: 1, z: 1 },- });- world.insert(entity, UIRect, {- anchorMin: { x: 0.5, y: 0.5 }, anchorMax: { x: 0.5, y: 0.5 },- offsetMin: { x: 0, y: 0 }, offsetMax: { x: 0, y: 0 },- size: { x: 200, y: 40 }, pivot: { x: 0.5, y: 0.5 },- });- world.insert(entity, Text, {- content,- fontFamily: 'Arial',- fontSize: 24,- color: { r: 0, g: 0, b: 0, a: 1 },- align: 1, verticalAlign: 1,- wordWrap: false, overflow: 0, lineHeight: 1.2,- });- return entity;- }-- it('each text entity should get a distinct, valid texture after tick', () => {- let canvasSupported = true;- try {- const canvas = typeof OffscreenCanvas !== 'undefined'- ? new OffscreenCanvas(64, 64)- : document.createElement('canvas');- const ctx = canvas.getContext('2d');- if (!ctx) canvasSupported = false;- if (ctx && 'getImageData' in ctx) {- ctx.getImageData(0, 0, 1, 1);- } else {- canvasSupported = false;- }- } catch {- canvasSupported = false;- }- if (!canvasSupported) {- console.warn('Skipping: Canvas 2D not supported in test env');- return;- }-- const { app, registry } = createApp();- const root = createCanvasRoot(app);-- const textA = createTextEntity(app, root, 'Alpha', 60);- const textB = createTextEntity(app, root, 'Beta', 0);- const textC = createTextEntity(app, root, 'Gamma', -60);-- app.tick(1 / 60);-- const world = app.world;- const entities = [textA, textB, textC];- const handles: number[] = [];-- for (const entity of entities) {- expect(world.has(entity, Sprite)).toBe(true);- const sprite = world.get(entity, Sprite) as SpriteData;- expect(sprite.enabled).toBe(true);- expect(sprite.texture).not.toBe(INVALID_TEXTURE);- handles.push(sprite.texture);- }-- // All three texture handles must be distinct- expect(new Set(handles).size).toBe(3);-- // Verify textures survive a second tick (snapshot skip path)- app.tick(1 / 60);-- for (const entity of entities) {- const sprite = world.get(entity, Sprite) as SpriteData;- expect(sprite.enabled).toBe(true);- expect(sprite.texture).not.toBe(INVALID_TEXTURE);- }-- // Handles should still be distinct after second tick- const handles2 = entities.map(e => (world.get(e, Sprite) as SpriteData).texture);- expect(new Set(handles2).size).toBe(3);-- disposeApp(app, registry);- });-- it('text entities survive scene reload with entity ID reuse', () => {- let canvasSupported = true;- try {- const canvas = typeof OffscreenCanvas !== 'undefined'- ? new OffscreenCanvas(64, 64)- : document.createElement('canvas');- const ctx = canvas.getContext('2d');- if (!ctx) canvasSupported = false;- if (ctx && 'getImageData' in ctx) {- ctx.getImageData(0, 0, 1, 1);- } else {- canvasSupported = false;- }- } catch {- canvasSupported = false;- }- if (!canvasSupported) {- console.warn('Skipping: Canvas 2D not supported in test env');- return;- }-- const { app, registry } = createApp();- const world = app.world;-- const root = createCanvasRoot(app);- const textA = createTextEntity(app, root, 'Label', 60);- const textB = createTextEntity(app, root, 'Option A', 0);- const textC = createTextEntity(app, root, 'Option B', -60);-- app.tick(1 / 60);-- for (const entity of [textA, textB, textC]) {- expect(world.has(entity, Sprite)).toBe(true);- const sprite = world.get(entity, Sprite) as SpriteData;- expect(sprite.texture).not.toBe(INVALID_TEXTURE);- }-- // Simulate scene reload: destroy all, re-spawn from scene data.- // C++ Registry reuses entity IDs from recycled queue.- for (const e of world.getAllEntities()) {- world.despawn(e);- }-- const root2 = createCanvasRoot(app);- const textA2 = createTextEntity(app, root2, 'Label', 60);- const textB2 = createTextEntity(app, root2, 'Option A', 0);- const textC2 = createTextEntity(app, root2, 'Option B', -60);-- // COMPONENT_SUPPRESS_RULES: Sprite NOT loaded for Text entities after reload.- // These entities have Text + UIRect but no Sprite.-- app.tick(1 / 60);-- // All text entities must get valid Sprites despite snapshot cache having- // stale entries from before the reload (entity ID reuse).- for (const entity of [textA2, textB2, textC2]) {- expect(world.has(entity, Sprite)).toBe(true);- const sprite = world.get(entity, Sprite) as SpriteData;- expect(sprite.texture).not.toBe(INVALID_TEXTURE);- }-- const handles = [textA2, textB2, textC2].map(- e => (world.get(e, Sprite) as SpriteData).texture- );- expect(new Set(handles).size).toBe(3);-- disposeApp(app, registry);- });-- it('text entities with manual sprites should all have unique textures', () => {- const { app, registry } = createApp();- const root = createCanvasRoot(app);- const world = app.world;-- const textA = createTextEntity(app, root, 'Alpha', 60);- const textB = createTextEntity(app, root, 'Beta', 0);- const textC = createTextEntity(app, root, 'Gamma', -60);-- // Manually add sprites (simulating what TextPlugin does)- for (const [entity, tex] of [[textA, 100], [textB, 200], [textC, 300]] as const) {- world.insert(entity, Sprite, {- texture: tex, color: { r: 1, g: 1, b: 1, a: 1 },- size: { x: 200, y: 40 }, uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 }, layer: 0,- flipX: false, flipY: false, material: 0, enabled: true,- });- }-- app.tick(1 / 60);-- // After tick, each sprite should retain its unique texture- // (UILayoutSystem and UIRenderOrderSystem should NOT overwrite textures)- const spriteA = world.get(textA, Sprite) as SpriteData;- const spriteB = world.get(textB, Sprite) as SpriteData;- const spriteC = world.get(textC, Sprite) as SpriteData;-- expect(spriteA.enabled).toBe(true);- expect(spriteB.enabled).toBe(true);- expect(spriteC.enabled).toBe(true);-- // Texture handles must be preserved (not overwritten to same value)- const uniqueTextures = new Set([spriteA.texture, spriteB.texture, spriteC.texture]);- expect(uniqueTextures.size).toBe(3);-- disposeApp(app, registry);- });-});diff --git a/sdk/tests/ui-text-richlayout.test.ts b/sdk/tests/ui-text-richlayout.test.tsindex 398adacd8..f2ae3a254 100644--- a/sdk/tests/ui-text-richlayout.test.ts+++ b/sdk/tests/ui-text-richlayout.test.ts@@ -8,7 +8,7 @@ import {GlyphAtlas, type GlyphRasterizer, type AtlasPageStore, type RasterGlyph,} from '../src/ui/text/glyph-atlas';import { layoutRichLine, buildGlyphVertices } from '../src/ui/text/layout';-import { UI_TEXT_BOLD } from '../src/ui/text/ui-text';+import { UI_TEXT_BOLD } from '../src/ui/text/text-transform';function makeAtlas(calls: Array<{ cp: number; style: number }>): GlyphAtlas {const rasterizer: GlyphRasterizer = {diff --git a/sdk/tests/ui-text-uitext.test.ts b/sdk/tests/ui-text-uitext.test.tsindex 1f7790f64..116e0f468 100644--- a/sdk/tests/ui-text-uitext.test.ts+++ b/sdk/tests/ui-text-uitext.test.ts@@ -1,10 +1,10 @@/**- * @file REARCH_GUI P1.3c — composeTRS, the world-transform matrix the UIText- * pre-flush system feeds to submitTextBatch. Pure → unit-tested here; the- * full on-screen path (UITextPlugin → render) is render-host-verified.+ * @file REARCH_GUI P1.4 — composeTRS (entity world matrix) + rectTextBox+ * (UIRect text placement) for the SDF text plugin. Pure → unit-tested+ * here; the full on-screen path (TextPlugin → render) is render-verified.*/import { describe, it, expect } from 'vitest';-import { composeTRS, rectTextBox } from '../src/ui/text/ui-text';+import { composeTRS, rectTextBox } from '../src/ui/text/text-transform';const IDQ = { x: 0, y: 0, z: 0, w: 1 };