Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

refactor(ui): SDF TextInput, retire the Canvas2D TextRenderer (REARCH_GUI F8)

esengined9f8717009f4
diff --git a/desktop/public/scenes/ui-textinput.esscene b/desktop/public/scenes/ui-textinput.esscene
new file mode 100644
index 000000000..95a08741a
--- /dev/null
+++ b/desktop/public/scenes/ui-textinput.esscene
@@ -0,0 +1,60 @@
+{
+ "version": "1.0",
+ "name": "SDF TextInput (REARCH_GUI F8)",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },
+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }
+ ],
+ "visible": true
+ },
+ {
+ "id": 1,
+ "name": "Canvas",
+ "parent": null,
+ "children": [2],
+ "components": [
+ { "type": "Transform", "data": {} },
+ { "type": "Canvas", "data": { "designResolution": { "x": 800, "y": 600 }, "scaleMode": 2 } },
+ { "type": "UINode", "data": {} }
+ ],
+ "visible": true
+ },
+ {
+ "id": 2,
+ "name": "Field",
+ "parent": 1,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "insetLeft": { "value": 200, "unit": 0 },
+ "insetTop": { "value": 270, "unit": 0 },
+ "width": { "value": 400, "unit": 0 },
+ "height": { "value": 48, "unit": 0 }
+ }
+ },
+ {
+ "type": "TextInput",
+ "data": {
+ "value": "SDF 输入框 hello",
+ "fontFamily": "sans-serif",
+ "fontSize": 28,
+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },
+ "backgroundColor": { "r": 0.12, "g": 0.13, "b": 0.18, "a": 1 },
+ "padding": 10
+ }
+ }
+ ],
+ "visible": true
+ }
+ ]
+}
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index 3bb66f4b5..5265d6c3f 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -22,7 +22,6 @@ export {
UIVisualType,
UILayoutGeneration,
UIMask,
- TextRenderer,
textPlugin,
DefaultImageResolver,
setImageResolver,
@@ -61,7 +60,6 @@ export {
type TextData,
type UIMaskData,
type MaskMode,
- type TextRenderResult,
type ScreenRect,
type InteractableData,
type UIInteractionData,
diff --git a/sdk/src/ui/TextInputPlugin.ts b/sdk/src/ui/TextInputPlugin.ts
index aac412811..888c9ecbd 100644
--- a/sdk/src/ui/TextInputPlugin.ts
+++ b/sdk/src/ui/TextInputPlugin.ts
@@ -2,26 +2,31 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { App, Plugin } from '../app';
import type { Entity } from '../types';
-import { RuntimeConfig } from '../defaults';
import { defineSystem, Schedule } from '../system';
import { registerComponent } from '../component';
import { TextInput, type TextInputData } from './TextInput';
-import { UINode } from './core/ui-node';
+import { UINode, UIPositionType, type UINodeData } from './core/ui-node';
import { UIVisual, UIVisualType } from './core/ui-visual';
import type { UIVisualData } from './core/ui-visual';
+import { Text, TextAlign, TextVerticalAlign, type TextData } from './core/text';
import { Interactable } from './behavior/interactable';
import { Focusable } from './behavior/focusable';
import { FocusManager, FocusManagerState } from './behavior/focusable';
import { UIEvents, UIEventQueue } from './core/events';
import { Res } from '../resource';
-import { platformCreateCanvas } from '../platform';
-import { requireResourceManager } from '../resourceManager';
import { playModeOnly } from '../env';
-import { wrapText, nextPowerOf2, ensureComponent, colorToRgba, getUINodeWidth, getUINodeHeight } from './uiHelpers';
-import { CURSOR_BLINK_INTERVAL, TEXT_INPUT_LINE_HEIGHT_RATIO } from './uiConstants';
+import { ensureComponent, getUINodeWidth, getUINodeHeight } from './uiHelpers';
+import { spawnUIEntity } from './widgets/helpers';
+import { px } from './core/dimension';
+import { SdfTextRenderer } from './text/text-renderer';
+import { measureWidth } from './text/layout';
+import { CURSOR_BLINK_INTERVAL } from './uiConstants';
import { SystemLabel, PluginName } from '../systemLabels';
import { log } from '../logger';
+/** Masking bullet for password fields. */
+const PASSWORD_CHAR = '●';
+
export class TextInputPlugin implements Plugin {
name = PluginName.TextInput;
dependencies = [PluginName.Focus];
@@ -48,17 +53,19 @@ export class TextInputPlugin implements Plugin {
const module = moduleOrNull;
const world = app.world;
- const textureCache = new Map<Entity, number>();
- const canvas = platformCreateCanvas(RuntimeConfig.textCanvasSize, 64);
- const ctxOrNull = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctxOrNull) {
- log.warn('ui', 'TextInputPlugin: failed to create 2D canvas context');
- return;
- }
- const ctx = ctxOrNull as CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
- let wasmPixelPtr = 0;
- let wasmPixelSize = 0;
+ // REARCH_GUI F8: the editable text renders through the shared SDF glyph
+ // atlas — a child Text entity (drawn by textPlugin) + a child UIVisual
+ // caret quad, composited over the entity's background UIVisual. No more
+ // per-entity Canvas2D rasterization / texture upload. `measureRenderer`
+ // owns an atlas used only to position the caret (measureWidth); its glyph
+ // advances match the child Text's atlas (same font config).
+ const childrenOf = new Map<Entity, { text: Entity; caret: Entity }>();
+ let measureRenderer: SdfTextRenderer | null = null;
+ const ensureMeasure = (): SdfTextRenderer => {
+ if (!measureRenderer) measureRenderer = new SdfTextRenderer(module);
+ return measureRenderer;
+ };
let composing = false;
let cursorVisible = true;
@@ -155,16 +162,11 @@ export class TextInputPlugin implements Plugin {
textarea.removeEventListener('keydown', onKeyDown);
textarea.removeEventListener('blur', onBlur);
textarea.remove();
- const rm = requireResourceManager();
- for (const tex of textureCache.values()) {
- rm.releaseTexture(tex);
- }
- textureCache.clear();
- if (wasmPixelPtr !== 0) {
- module._free(wasmPixelPtr);
- wasmPixelPtr = 0;
- wasmPixelSize = 0;
+ for (const ch of childrenOf.values()) {
+ if (world.valid(ch.text)) world.despawn(ch.text);
+ if (world.valid(ch.caret)) world.despawn(ch.caret);
}
+ childrenOf.clear();
};
function syncFromTextarea(): void {
@@ -251,7 +253,10 @@ export class TextInputPlugin implements Plugin {
{ name: 'TextInputFocusSystem' }
), { runAfter: [SystemLabel.Focus] });
- // Render system
+ // Render system — composite the input from SDF child entities (a child
+ // Text drawn by textPlugin + a child caret quad) over the entity's
+ // background UIVisual. Tree-DFS render order layers bg < text < caret. No
+ // Canvas2D, no per-entity texture (REARCH_GUI F8).
app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
[],
() => {
@@ -266,170 +271,118 @@ export class TextInputPlugin implements Plugin {
if (cursorTimer >= CURSOR_BLINK_INTERVAL) {
cursorTimer -= CURSOR_BLINK_INTERVAL;
cursorVisible = !cursorVisible;
- const ti = world.get(focused, TextInput) as TextInputData;
- ti.dirty = true;
}
}
- const rm = requireResourceManager();
- for (const [e, tex] of textureCache) {
+ // Reap the child entities of removed inputs.
+ for (const [e, ch] of childrenOf) {
if (!world.valid(e) || !world.has(e, TextInput)) {
- rm.releaseTexture(tex);
- textureCache.delete(e);
+ if (world.valid(ch.text)) world.despawn(ch.text);
+ if (world.valid(ch.caret)) world.despawn(ch.caret);
+ childrenOf.delete(e);
}
}
- const entities = world.getEntitiesWithComponents([TextInput, UINode]);
- for (const entity of entities) {
+ for (const entity of world.getEntitiesWithComponents([TextInput, UINode])) {
const ti = world.get(entity, TextInput) as TextInputData;
- if (!ti.dirty) continue;
-
- // Texture size = the UINode's resolved (Yoga-computed) box.
- const w = Math.ceil(getUINodeWidth(entity));
- const h = Math.ceil(getUINodeHeight(entity));
- if (w <= 0 || h <= 0) continue;
-
- if (!world.has(entity, UIVisual)) {
- world.insert(entity, UIVisual, {
- visualType: UIVisualType.None,
- texture: 0,
- color: { r: 1, g: 1, b: 1, a: 1 },
- uvOffset: { x: 0, y: 0 },
- uvScale: { x: 1, y: 1 },
- sliceBorder: { x: 0, y: 0, z: 0, w: 0 },
- tileSize: { x: 32, y: 32 },
- fillMethod: 0,
- fillOrigin: 0,
- fillAmount: 1,
- material: 0,
- enabled: true,
- });
- }
+ const h = getUINodeHeight(entity);
+ if (getUINodeWidth(entity) <= 0 || h <= 0) continue;
- renderTextInput(entity, ti, w, h);
- ti.dirty = false;
+ ensureBackground(entity, ti);
+ const ch = ensureChildren(entity, ti);
+ syncTextChild(ch.text, ti);
+ syncCaretChild(ch.caret, ti, h);
}
},
{ name: 'TextInputRenderSystem' }
));
- function renderTextInput(entity: Entity, ti: TextInputData, w: number, h: number): void {
- if (canvas.width < w || canvas.height < h) {
- canvas.width = nextPowerOf2(Math.max(canvas.width, w));
- canvas.height = nextPowerOf2(Math.max(canvas.height, h));
- }
-
- ctx.clearRect(0, 0, canvas.width, canvas.height);
-
- ctx.fillStyle = colorToRgba(ti.backgroundColor);
- ctx.fillRect(0, 0, w, h);
-
- ctx.save();
- ctx.beginPath();
- ctx.rect(ti.padding, 0, w - ti.padding * 2, h);
- ctx.clip();
-
- ctx.font = `${ti.fontSize}px ${ti.fontFamily}`;
- ctx.textBaseline = 'top';
- ctx.textAlign = 'left';
-
- const isEmpty = ti.value.length === 0;
- const displayText = isEmpty
- ? ti.placeholder
- : ti.password
- ? '\u25CF'.repeat(ti.value.length)
+ /** Visible string: placeholder when empty, bullets when password. */
+ const displayString = (ti: TextInputData): string =>
+ ti.value.length === 0 ? ti.placeholder
+ : ti.password ? PASSWORD_CHAR.repeat(ti.value.length)
: ti.value;
- ctx.fillStyle = colorToRgba(isEmpty ? ti.placeholderColor : ti.color);
-
- const lineHeight = Math.ceil(ti.fontSize * TEXT_INPUT_LINE_HEIGHT_RATIO);
- const padding = ti.padding;
-
- if (ti.multiline) {
- const lines = wrapText(ctx, displayText, w - padding * 2);
- let y = padding;
- for (const line of lines) {
- ctx.fillText(line, padding, y);
- y += lineHeight;
- }
- } else {
- const textY = (h - ti.fontSize) / 2;
- ctx.fillText(displayText, padding, textY);
+ function ensureBackground(entity: Entity, ti: TextInputData): void {
+ if (!world.has(entity, UIVisual)) {
+ world.insert(entity, UIVisual, {
+ visualType: UIVisualType.SolidColor, texture: 0,
+ color: { ...ti.backgroundColor },
+ uvOffset: { x: 0, y: 0 }, uvScale: { x: 1, y: 1 },
+ sliceBorder: { x: 0, y: 0, z: 0, w: 0 }, tileSize: { x: 32, y: 32 },
+ fillMethod: 0, fillOrigin: 0, fillAmount: 1, material: 0, enabled: true,
+ });
+ return;
}
-
- if (ti.focused && cursorVisible) {
- const cursorText = ti.password
- ? '\u25CF'.repeat(ti.cursorPos)
- : ti.value.substring(0, ti.cursorPos);
-
- let cursorX: number;
- let cursorY: number;
- let cursorH: number;
-
- if (ti.multiline) {
- const lines = wrapText(ctx, ti.value, w - padding * 2);
- let charCount = 0;
- let cursorLine = 0;
- let cursorCol = 0;
- for (let i = 0; i < lines.length; i++) {
- const lineLen = lines[i].length;
- if (charCount + lineLen >= ti.cursorPos) {
- cursorLine = i;
- cursorCol = ti.cursorPos - charCount;
- break;
- }
- charCount += lineLen;
- if (i < lines.length - 1 && charCount < ti.value.length && ti.value[charCount] === '\n') {
- charCount++;
- }
- cursorLine = i + 1;
- cursorCol = 0;
- }
- const partialLine = cursorLine < lines.length ? lines[cursorLine].substring(0, cursorCol) : '';
- cursorX = padding + ctx.measureText(partialLine).width;
- cursorY = padding + cursorLine * lineHeight;
- cursorH = lineHeight;
- } else {
- cursorX = padding + ctx.measureText(cursorText).width;
- cursorY = (h - ti.fontSize) / 2;
- cursorH = ti.fontSize;
- }
-
- ctx.fillStyle = colorToRgba(ti.color);
- ctx.fillRect(cursorX, cursorY, 2, cursorH);
+ const bg = world.get(entity, UIVisual) as UIVisualData;
+ const c = ti.backgroundColor;
+ if (bg.visualType !== UIVisualType.SolidColor || !bg.enabled
+ || bg.color.r !== c.r || bg.color.g !== c.g || bg.color.b !== c.b || bg.color.a !== c.a) {
+ bg.visualType = UIVisualType.SolidColor;
+ bg.color = { ...c };
+ bg.enabled = true;
+ world.insert(entity, UIVisual, bg);
}
+ }
- ctx.restore();
-
- const imageData = ctx.getImageData(0, 0, w, h);
- const pixels = new Uint8Array(imageData.data.buffer);
- const rm = requireResourceManager();
+ function ensureChildren(entity: Entity, ti: TextInputData): { text: Entity; caret: Entity } {
+ const existing = childrenOf.get(entity);
+ if (existing && world.valid(existing.text) && world.valid(existing.caret)) return existing;
+ const pad = px(ti.padding);
+ const text = spawnUIEntity({
+ world, parent: entity,
+ node: { position: UIPositionType.Absolute, insetLeft: pad, insetTop: px(0), insetRight: pad, insetBottom: px(0) },
+ text: {
+ content: '', fontFamily: ti.fontFamily, fontSize: ti.fontSize,
+ align: TextAlign.Left, verticalAlign: TextVerticalAlign.Middle, wordWrap: ti.multiline,
+ },
+ });
+ const caret = spawnUIEntity({
+ world, parent: entity,
+ node: { position: UIPositionType.Absolute, width: px(2), height: px(ti.fontSize), insetLeft: px(ti.padding), insetTop: px(0) },
+ visual: { visualType: UIVisualType.SolidColor, color: ti.color, enabled: false },
+ });
+ const ch = { text, caret };
+ childrenOf.set(entity, ch);
+ return ch;
+ }
- if (pixels.length > wasmPixelSize) {
- if (wasmPixelPtr !== 0) {
- module._free(wasmPixelPtr);
- }
- wasmPixelPtr = module._malloc(pixels.length);
- wasmPixelSize = pixels.length;
+ function syncTextChild(textEntity: Entity, ti: TextInputData): void {
+ const t = world.get(textEntity, Text) as TextData;
+ const show = displayString(ti);
+ const col = ti.value.length === 0 ? ti.placeholderColor : ti.color;
+ if (t.content !== show || t.fontFamily !== ti.fontFamily || t.fontSize !== ti.fontSize
+ || t.wordWrap !== ti.multiline
+ || t.color.r !== col.r || t.color.g !== col.g || t.color.b !== col.b || t.color.a !== col.a) {
+ t.content = show;
+ t.fontFamily = ti.fontFamily;
+ t.fontSize = ti.fontSize;
+ t.wordWrap = ti.multiline;
+ t.color = { ...col };
+ world.insert(textEntity, Text, t);
}
- module.HEAPU8.set(pixels, wasmPixelPtr);
+ }
- const existingTex = textureCache.get(entity);
- if (existingTex !== undefined) {
- rm.releaseTexture(existingTex);
+ function syncCaretChild(caretEntity: Entity, ti: TextInputData, boxH: number): void {
+ const cursorText = ti.password
+ ? PASSWORD_CHAR.repeat(ti.cursorPos)
+ : ti.value.substring(0, ti.cursorPos);
+ const caretX = ti.padding + measureWidth(cursorText, ensureMeasure().atlas, ti.fontFamily, ti.fontSize, 0);
+ const caretTop = Math.max(0, (boxH - ti.fontSize) / 2);
+ const node = world.get(caretEntity, UINode) as UINodeData;
+ if (node.insetLeft.value !== caretX || node.insetTop.value !== caretTop || node.height.value !== ti.fontSize) {
+ node.insetLeft = px(caretX);
+ node.insetTop = px(caretTop);
+ node.height = px(ti.fontSize);
+ world.insert(caretEntity, UINode, node);
+ }
+ const v = world.get(caretEntity, UIVisual) as UIVisualData;
+ const show = ti.focused && cursorVisible;
+ if (v.enabled !== show || v.color.r !== ti.color.r || v.color.g !== ti.color.g || v.color.b !== ti.color.b) {
+ v.enabled = show;
+ v.color = { ...ti.color };
+ world.insert(caretEntity, UIVisual, v);
}
-
- const textureHandle = rm.createTexture(w, h, wasmPixelPtr, pixels.length, 1, true);
- textureCache.set(entity, textureHandle);
-
- const renderer = world.get(entity, UIVisual) as UIVisualData;
- renderer.texture = textureHandle;
- renderer.visualType = UIVisualType.Image;
- renderer.uvOffset = { x: 0, y: 0 };
- renderer.uvScale = { x: 1, y: 1 };
- renderer.color = { r: 1, g: 1, b: 1, a: 1 };
- renderer.enabled = true;
- world.insert(entity, UIVisual, renderer);
}
}
}
diff --git a/sdk/src/ui/TextRenderer.ts b/sdk/src/ui/TextRenderer.ts
deleted file mode 100644
index 267414e93..000000000
--- a/sdk/src/ui/TextRenderer.ts
+++ /dev/null
@@ -1,455 +0,0 @@
-// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file TextRenderer.ts
- * @brief Renders text to GPU textures using Canvas 2D API
- */
-
-import type { Entity } from '../types';
-import { RuntimeConfig } from '../defaults';
-import type { ESEngineModule } from '../wasm';
-import { TextAlign, TextVerticalAlign, TextOverflow, type TextData } from './core/text';
-import { platformCreateCanvas } from '../platform';
-import { requireResourceManager } from '../resourceManager';
-import { wrapText, nextPowerOf2, colorToRgba } from './uiHelpers';
-import { TEXT_PADDING_RATIO, TEXT_CANVAS_SHRINK_FRAMES, TEXT_CANVAS_OVERSIZE_RATIO, TEXT_ASCENT_RATIO } from './uiConstants';
-import { parseRichText } from './RichTextParser';
-import { createFontSet, fontIndex, layoutRichText, measureLayoutWidth, type LayoutLine } from './RichTextLayout';
-import type { ImageResolver } from './ImageResolver';
-import { log } from '../logger';
-import { withMalloc } from '../wasmScratch';
-
-interface SizedRect {
- size: { x: number; y: number };
-}
-
-function buildFontString(text: TextData): string {
- const set = createFontSet(text.fontSize, text.fontFamily);
- return set.fonts[fontIndex(text.bold, text.italic)];
-}
-
-// =============================================================================
-// Text Render Result
-// =============================================================================
-
-export interface TextRenderResult {
- textureHandle: number;
- width: number;
- height: number;
-}
-
-// =============================================================================
-// Text Renderer
-// =============================================================================
-
-export class TextRenderer {
- private canvas: OffscreenCanvas | HTMLCanvasElement;
- private ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
- private module: ESEngineModule;
- private cache = new Map<Entity, TextRenderResult>();
- private shrinkCounter_ = 0;
- private frameMaxW_ = 0;
- private frameMaxH_ = 0;
- private imageResolver_: ImageResolver | null = null;
-
- constructor(module: ESEngineModule) {
- this.module = module;
- this.canvas = platformCreateCanvas(RuntimeConfig.textCanvasSize, RuntimeConfig.textCanvasSize);
- const ctx = this.canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) throw new Error('TextRenderer: failed to create 2D canvas context');
- this.ctx = ctx;
- }
-
- beginFrame(): void {
- const canvas = this.canvas;
- if (this.frameMaxW_ > 0) {
- if (canvas.width < this.frameMaxW_ || canvas.height < this.frameMaxH_) {
- canvas.width = Math.max(canvas.width, nextPowerOf2(this.frameMaxW_));
- canvas.height = Math.max(canvas.height, nextPowerOf2(this.frameMaxH_));
- this.shrinkCounter_ = 0;
- } else if (canvas.width > this.frameMaxW_ * TEXT_CANVAS_OVERSIZE_RATIO || canvas.height > this.frameMaxH_ * TEXT_CANVAS_OVERSIZE_RATIO) {
- this.shrinkCounter_++;
- if (this.shrinkCounter_ >= TEXT_CANVAS_SHRINK_FRAMES) {
- canvas.width = nextPowerOf2(this.frameMaxW_);
- canvas.height = nextPowerOf2(this.frameMaxH_);
- this.shrinkCounter_ = 0;
- }
- } else {
- this.shrinkCounter_ = 0;
- }
- }
- this.frameMaxW_ = 0;
- this.frameMaxH_ = 0;
- }
-
- setImageResolver(resolver: ImageResolver | null): void {
- this.imageResolver_ = resolver;
- }
-
- private renderText(text: TextData, uiRect?: SizedRect | null): TextRenderResult {
- try {
- return this.renderTextInner(text, uiRect);
- } catch (e) {
- log.error('ui', 'TextRenderer: render failed', e);
- return { textureHandle: 0, width: 0, height: 0 };
- }
- }
-
- private renderTextInner(text: TextData, uiRect?: SizedRect | null): TextRenderResult {
- const ctx = this.ctx;
- const canvas = this.canvas;
-
- const hasContainer = uiRect && uiRect.size.x > 0 && uiRect.size.y > 0;
- const containerWidth = hasContainer ? uiRect!.size.x : 0;
- const containerHeight = hasContainer ? uiRect!.size.y : 0;
-
- const hasStroke = text.strokeWidth > 0;
- const hasShadow = text.shadowBlur > 0 || text.shadowOffsetX !== 0 || text.shadowOffsetY !== 0;
- const strokeExpand = hasStroke ? Math.ceil(text.strokeWidth) : 0;
- const shadowExpand = hasShadow ? Math.ceil(text.shadowBlur + Math.max(Math.abs(text.shadowOffsetX), Math.abs(text.shadowOffsetY))) : 0;
- const effectPadding = Math.max(strokeExpand, shadowExpand);
-
- const lineHeightPx = Math.ceil(text.fontSize * text.lineHeight);
- const padding = Math.ceil(text.fontSize * TEXT_PADDING_RATIO) + effectPadding;
- const shouldWrap = text.wordWrap && hasContainer;
-
- let richLines: LayoutLine[] | null = null;
- let plainLines: string[] | null = null;
- let fontSet: ReturnType<typeof createFontSet> | null = null;
- let measuredWidth: number;
- let measuredHeight: number;
-
- if (text.richText) {
- const runs = parseRichText(text.content);
- fontSet = createFontSet(text.fontSize, text.fontFamily);
- richLines = layoutRichText(ctx, runs, fontSet, text.color, shouldWrap ? containerWidth : 0, text.fontSize);
- measuredWidth = Math.ceil(measureLayoutWidth(richLines));
- let totalH = 0;
- for (const line of richLines) {
- totalH += line.height ? Math.max(lineHeightPx, line.height) : lineHeightPx;
- }
- measuredHeight = Math.ceil(totalH);
- } else {
- ctx.font = buildFontString(text);
- plainLines = wrapText(ctx, text.content, shouldWrap ? containerWidth : 0);
- measuredWidth = Math.ceil(this.measureWidth(plainLines));
- measuredHeight = Math.ceil(plainLines.length * lineHeightPx);
- }
-
- const contentWidth = measuredWidth + padding * 2;
- const contentHeight = measuredHeight + padding * 2;
- let width: number;
- let height: number;
- if (hasContainer) {
- const isVisible = text.overflow === TextOverflow.Visible;
- width = isVisible ? Math.max(Math.ceil(containerWidth), contentWidth) : Math.ceil(containerWidth);
- height = isVisible ? Math.max(Math.ceil(containerHeight), contentHeight) : Math.ceil(containerHeight);
- } else {
- width = contentWidth;
- height = contentHeight;
- }
-
- if (hasContainer && text.overflow === TextOverflow.Ellipsis && measuredHeight > containerHeight) {
- const maxLines = Math.floor(containerHeight / lineHeightPx);
- if (maxLines > 0) {
- if (richLines && richLines.length > maxLines) {
- richLines = richLines.slice(0, maxLines);
- this.truncateRichLine(richLines[maxLines - 1], containerWidth, fontSet!);
- } else if (plainLines && plainLines.length > maxLines) {
- plainLines = plainLines.slice(0, maxLines);
- plainLines[maxLines - 1] = this.truncateWithEllipsis(plainLines[maxLines - 1], containerWidth);
- }
- }
- }
-
- this.frameMaxW_ = Math.max(this.frameMaxW_, width);
- this.frameMaxH_ = Math.max(this.frameMaxH_, height);
-
- if (canvas.width < width || canvas.height < height) {
- canvas.width = Math.max(canvas.width, nextPowerOf2(width));
- canvas.height = Math.max(canvas.height, nextPowerOf2(height));
- }
-
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.textBaseline = 'top';
-
- if (hasContainer && text.overflow === TextOverflow.Clip) {
- ctx.save();
- ctx.beginPath();
- ctx.rect(0, 0, width, height);
- ctx.clip();
- }
-
- let textBlockHeight: number;
- if (richLines) {
- textBlockHeight = 0;
- for (const line of richLines) {
- textBlockHeight += line.height ? Math.max(lineHeightPx, line.height) : lineHeightPx;
- }
- } else {
- textBlockHeight = plainLines!.length * lineHeightPx;
- }
- let startY: number;
- if (hasContainer) {
- switch (text.verticalAlign) {
- case TextVerticalAlign.Top: startY = padding; break;
- case TextVerticalAlign.Middle: startY = padding + (height - 2 * padding - textBlockHeight) / 2; break;
- case TextVerticalAlign.Bottom: startY = height - textBlockHeight - padding; break;
- default: startY = padding;
- }
- if (startY < 0) startY = 0;
- } else {
- startY = padding;
- }
-
- if (hasStroke) {
- ctx.strokeStyle = colorToRgba(text.strokeColor);
- ctx.lineWidth = text.strokeWidth * 2;
- ctx.lineJoin = 'round';
- }
-
- if (hasShadow) {
- ctx.shadowColor = colorToRgba(text.shadowColor);
- ctx.shadowBlur = text.shadowBlur;
- ctx.shadowOffsetX = text.shadowOffsetX;
- ctx.shadowOffsetY = text.shadowOffsetY;
- }
-
- if (richLines) {
- ctx.textAlign = 'left';
- let lastFI = -1;
- let y = startY;
-
- const resolver = this.imageResolver_;
-
- if (hasStroke) {
- for (const line of richLines) {
- const lh = line.height ? Math.max(lineHeightPx, line.height) : lineHeightPx;
- const baseX = this.lineBaseX(text.align, width, line.width, padding);
- for (const run of line.runs) {
- if (run.type !== 'text') continue;
- if (run.fontIndex !== lastFI) {
- ctx.font = fontSet!.fonts[run.fontIndex];
- lastFI = run.fontIndex;
- }
- ctx.strokeText(run.text, baseX + run.x, y);
- }
- y += lh;
- }
- lastFI = -1;
- y = startY;
- }
-
- const ascent = text.fontSize * TEXT_ASCENT_RATIO;
-
- for (const line of richLines) {
- const lh = line.height ? Math.max(lineHeightPx, line.height) : lineHeightPx;
- let baseX: number;
- switch (text.align) {
- case TextAlign.Left: baseX = padding; break;
- case TextAlign.Center: baseX = (width - line.width) / 2; break;
- case TextAlign.Right: baseX = width - padding - line.width; break;
- default: baseX = padding;
- }
- for (const run of line.runs) {
- if (run.type !== 'text') continue;
- if (run.fontIndex !== lastFI) {
- ctx.font = fontSet!.fonts[run.fontIndex];
- lastFI = run.fontIndex;
- }
- ctx.fillStyle = colorToRgba(run.color);
- ctx.fillText(run.text, baseX + run.x, y);
- }
- y += lh;
- }
-
- if (hasShadow) {
- ctx.shadowColor = 'transparent';
- ctx.shadowBlur = 0;
- ctx.shadowOffsetX = 0;
- ctx.shadowOffsetY = 0;
- }
-
- if (resolver) {
- y = startY;
- lastFI = -1;
- for (const line of richLines) {
- const lh = line.height ? Math.max(lineHeightPx, line.height) : lineHeightPx;
- const baseX = this.lineBaseX(text.align, width, line.width, padding);
- for (const run of line.runs) {
- if (run.type !== 'image') continue;
- const img = resolver.resolve(run.src);
- if (!img) continue;
- let imgY: number;
- switch (run.valign) {
- case 'top': imgY = y; break;
- case 'middle': imgY = y + (lineHeightPx - run.height) / 2; break;
- case 'bottom': imgY = y + lineHeightPx - run.height; break;
- case 'baseline':
- default: imgY = y + ascent - run.height; break;
- }
- const dx = baseX + run.x + run.offsetX;
- const dy = imgY + run.offsetY;
- if (run.tint) ctx.globalAlpha = run.tint.a;
- ctx.drawImage(img, dx, dy, run.width, run.height);
- if (run.tint) ctx.globalAlpha = 1;
- }
- y += lh;
- }
- }
- } else {
- ctx.font = buildFontString(text);
- ctx.textAlign = this.mapAlign(text.align);
- ctx.fillStyle = colorToRgba(text.color);
- let y = startY;
- for (const line of plainLines!) {
- let x: number;
- switch (text.align) {
- case TextAlign.Left: x = padding; break;
- case TextAlign.Center: x = width / 2; break;
- case TextAlign.Right: x = width - padding; break;
- default: x = padding;
- }
- if (hasStroke) ctx.strokeText(line, x, y);
- ctx.fillText(line, x, y);
- y += lineHeightPx;
- }
- }
-
- if (hasShadow) {
- ctx.shadowColor = 'transparent';
- ctx.shadowBlur = 0;
- ctx.shadowOffsetX = 0;
- ctx.shadowOffsetY = 0;
- }
-
- if (hasContainer && text.overflow === TextOverflow.Clip) {
- ctx.restore();
- }
-
- const imageData = ctx.getImageData(0, 0, width, height);
- const pixels = new Uint8Array(imageData.data.buffer);
-
- const rm = requireResourceManager();
- const textureHandle = withMalloc(this.module, pixels.length, ptr => {
- this.module.HEAPU8.set(pixels, ptr);
- return rm.createTexture(width, height, ptr, pixels.length, 1, true);
- });
-
- return { textureHandle, width, height };
- }
-
- private truncateWithEllipsis(text: string, maxWidth: number): string {
- const ellipsis = '...';
- if (this.ctx.measureText(text).width <= maxWidth) return text;
- let truncated = text;
- while (truncated.length > 0 && this.ctx.measureText(truncated + ellipsis).width > maxWidth) {
- truncated = truncated.slice(0, -1);
- }
- return truncated + ellipsis;
- }
-
- private truncateRichLine(line: LayoutLine, maxWidth: number, fontSet: ReturnType<typeof createFontSet>): void {
- const ctx = this.ctx;
- const ellipsis = '...';
- const ellipsisWidth = ctx.measureText(ellipsis).width;
- const target = maxWidth - ellipsisWidth;
- if (target <= 0) {
- line.runs = [];
- line.width = 0;
- return;
- }
- let accum = 0;
- for (let i = 0; i < line.runs.length; i++) {
- const run = line.runs[i];
- if (accum + run.width > target) {
- if (run.type === 'image') {
- line.runs = line.runs.slice(0, i);
- line.width = accum;
- return;
- }
- ctx.font = fontSet.fonts[run.fontIndex];
- const available = target - accum;
- let fitLen = 0;
- for (let j = 1; j <= run.text.length; j++) {
- if (ctx.measureText(run.text.slice(0, j)).width > available) break;
- fitLen = j;
- }
- const truncText = run.text.slice(0, fitLen) + ellipsis;
- const truncWidth = this.ctx.measureText(truncText).width;
- line.runs = line.runs.slice(0, i + 1);
- line.runs[i] = { ...run, text: truncText, width: truncWidth };
- line.width = accum + truncWidth;
- return;
- }
- accum += run.width;
- }
- }
-
- private lineBaseX(align: TextAlign, totalWidth: number, lineWidth: number, pad: number): number {
- switch (align) {
- case TextAlign.Left: return pad;
- case TextAlign.Center: return (totalWidth - lineWidth) / 2;
- case TextAlign.Right: return totalWidth - pad - lineWidth;
- default: return pad;
- }
- }
-
- renderForEntity(entity: Entity, text: TextData, uiRect?: SizedRect | null): TextRenderResult {
- const result = this.renderText(text, uiRect);
- const existing = this.cache.get(entity);
- if (existing) {
- const rm = requireResourceManager();
- rm.releaseTexture(existing.textureHandle);
- }
- this.cache.set(entity, result);
- return result;
- }
-
- getCached(entity: Entity): TextRenderResult | undefined {
- return this.cache.get(entity);
- }
-
- release(entity: Entity): void {
- const cached = this.cache.get(entity);
- if (cached) {
- const rm = requireResourceManager();
- rm.releaseTexture(cached.textureHandle);
- this.cache.delete(entity);
- }
- }
-
- cleanupOrphaned(isAlive: (entity: Entity) => boolean): void {
- const rm = requireResourceManager();
- for (const [entity, result] of this.cache) {
- if (!isAlive(entity)) {
- rm.releaseTexture(result.textureHandle);
- this.cache.delete(entity);
- }
- }
- }
-
- releaseAll(): void {
- const rm = requireResourceManager();
- for (const result of this.cache.values()) {
- rm.releaseTexture(result.textureHandle);
- }
- this.cache.clear();
- }
-
- private measureWidth(lines: string[]): number {
- let maxWidth = 0;
- for (const line of lines) {
- maxWidth = Math.max(maxWidth, this.ctx.measureText(line).width);
- }
- return maxWidth;
- }
-
- private mapAlign(align: TextAlign): CanvasTextAlign {
- switch (align) {
- case TextAlign.Left: return 'left';
- case TextAlign.Center: return 'center';
- case TextAlign.Right: return 'right';
- }
- }
-}
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 5e03c6dc3..f769ec78c 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -231,13 +231,8 @@ export {
// ─── Rendering / text helpers ───────────────────────────────────────────────
-// TextRenderer (Canvas2D) is retained only for TextInput until P1.5 migrates it.
-export {
- TextRenderer,
- type TextRenderResult,
-} from './TextRenderer';
-
-// The canonical Text component is now rendered via the SDF glyph atlas (P1.4d).
+// All text — display (Text) and editable (TextInput) — now renders through the
+// SDF glyph atlas; the Canvas2D TextRenderer was retired in REARCH_GUI F8.
export { TextPlugin, textPlugin } from './text/plugin';
// UI Math Utilities
diff --git a/sdk/src/ui/text/layout.ts b/sdk/src/ui/text/layout.ts
index 0f089ca0b..63801112b 100644
--- a/sdk/src/ui/text/layout.ts
+++ b/sdk/src/ui/text/layout.ts
@@ -88,7 +88,7 @@ export interface GlyphVertexData {
/**
* Build interleaved vertices (x,y,u,v,r,g,b,a) + indices for a set of laid-out
- * glyphs (typically the subset that shares one atlas page — see TextRenderer).
+ * glyphs (typically the subset that shares one atlas page).
* Atlas v0 (top) maps to the screen-top corner, v1 (bottom) to screen-bottom,
* so the quad samples the glyph upright. `originX/Y` offsets all glyphs (e.g. to
* place the text by its UINode-resolved box origin).