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.

feat: Add UI text rendering framework

esengine03faa74b8bec
diff --git a/scripts/build-playable.bat b/scripts/build-playable.bat
new file mode 100644
index 000000000..9e3fac4c7
--- /dev/null
+++ b/scripts/build-playable.bat
@@ -0,0 +1,57 @@
+@echo off
+setlocal
+
+cd /d "%~dp0\.."
+
+echo === Building Playable HTML ===
+echo.
+
+REM Step 1: Build SDK
+echo [1/4] Building SDK...
+cd sdk
+call npm run build
+if errorlevel 1 goto :error
+cd ..
+
+REM Step 2: Build Playground (IIFE format)
+echo [2/4] Building Playground (IIFE)...
+cd sdk\examples\playground
+call npm run build:playable
+if errorlevel 1 goto :error
+cd ..\..\..
+
+REM Step 3: Check if WASM SDK exists
+echo [3/4] Checking WASM SDK...
+if not exist "build-web-single\sdk\esengine.single.js" (
+ echo.
+ echo WARNING: Single-file WASM SDK not found!
+ echo Please run: scripts\build-web-single.bat first
+ echo.
+ echo Or if you have a regular WASM build, you can manually run:
+ echo node tools/bundle-playable.js --wasm YOUR_WASM.js --game sdk/examples/playground/build/playable/game.js --output playable.html
+ goto :end
+)
+
+REM Step 4: Bundle into single HTML
+echo [4/4] Bundling into single HTML...
+node tools\bundle-playable.js ^
+ --wasm build-web-single\sdk\esengine.single.js ^
+ --game sdk\examples\playground\build\playable\game.js ^
+ --output playable.html
+
+if errorlevel 1 goto :error
+
+echo.
+echo === Success! ===
+echo Output: playable.html
+goto :end
+
+:error
+echo.
+echo === Build Failed ===
+pause
+exit /b 1
+
+:end
+endlocal
+pause
diff --git a/sdk/examples/playground/src/main.ts b/sdk/examples/playground/src/main.ts
index dbe22958e..dd321bd26 100644
--- a/sdk/examples/playground/src/main.ts
+++ b/sdk/examples/playground/src/main.ts
@@ -9,6 +9,7 @@ import {
App,
createWebApp,
defineSystem,
+ defineTag,
Schedule,
Commands,
LocalTransform,
@@ -19,9 +20,15 @@ import {
Time,
Query,
Mut,
- type Entity
+ type Entity,
+ Text,
+ TextAlign,
+ textPlugin,
+ INVALID_TEXTURE
} from 'esengine';
+const Animated = defineTag('Animated');
+
// =============================================================================
// Main Entry Point
// =============================================================================
@@ -32,6 +39,9 @@ export async function main(Module: ESEngineModule): Promise<void> {
// Create the app with WASM module (handles renderer init + render loop)
const app = createWebApp(Module);
+ // Add the text plugin for automatic Text -> Sprite texture sync
+ app.addPlugin(textPlugin);
+
// Add startup system - runs once at beginning
app.addSystemToSchedule(Schedule.Startup, defineSystem(
[Commands()],
@@ -59,8 +69,9 @@ export async function main(Module: ESEngineModule): Promise<void> {
// Create a test sprite
const sprite = cmds.spawn()
+ .insert(Animated)
.insert(Sprite, {
- texture: 0,
+ texture: INVALID_TEXTURE,
color: { x: 1, y: 0.5, z: 0.2, w: 1 },
size: { x: 100, y: 100 },
uvOffset: { x: 0, y: 0 },
@@ -76,18 +87,43 @@ export async function main(Module: ESEngineModule): Promise<void> {
})
.id();
- console.log(`Created camera: ${camera}, sprite: ${sprite}`);
+ const textEntity = cmds.spawn()
+ .insert(Text, {
+ content: 'Hello ESEngine!',
+ fontFamily: 'Arial',
+ fontSize: 32,
+ color: { x: 1, y: 1, z: 1, w: 1 },
+ align: TextAlign.Center,
+ baseline: 0,
+ maxWidth: 0,
+ lineHeight: 1.2,
+ dirty: true
+ })
+ .insert(Sprite, {
+ texture: 0,
+ color: { x: 1, y: 1, z: 1, w: 1 },
+ size: { x: 200, y: 50 },
+ uvOffset: { x: 0, y: 0 },
+ uvScale: { x: 1, y: 1 },
+ layer: 10,
+ flipX: false,
+ flipY: false
+ })
+ .insert(LocalTransform, {
+ position: { x: 0, y: 150, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 }
+ })
+ .id();
+
+ console.log(`Created camera: ${camera}, sprite: ${sprite}, text: ${textEntity}`);
}
));
- // Add update system - runs every frame
- // Use Mut() to mark components that will be modified (auto-commits on iteration end)
app.addSystemToSchedule(Schedule.Update, defineSystem(
- [Res(Time), Query(Mut(LocalTransform), Sprite)],
+ [Res(Time), Query(Animated, Mut(LocalTransform))],
(time, query) => {
- for (const [entity, transform, sprite] of query) {
- // Move the sprite in a circle
- // Set the whole position object (nested properties are copies)
+ for (const [entity, _, transform] of query) {
transform.position = {
x: Math.sin(time.elapsed) * 100,
y: Math.cos(time.elapsed) * 100,
diff --git a/sdk/src/index.ts b/sdk/src/index.ts
index 763ae83a6..715ea5f62 100644
--- a/sdk/src/index.ts
+++ b/sdk/src/index.ts
@@ -10,6 +10,8 @@
export {
type Entity,
INVALID_ENTITY,
+ type TextureHandle,
+ INVALID_TEXTURE,
type Vec2,
type Vec3,
type Vec4,
@@ -134,3 +136,18 @@ export type {
CppRegistry,
CppResourceManager,
} from './wasm';
+
+// =============================================================================
+// UI
+// =============================================================================
+
+export {
+ Text,
+ TextAlign,
+ TextBaseline,
+ TextRenderer,
+ TextPlugin,
+ textPlugin,
+ type TextData,
+ type TextRenderResult,
+} from './ui';
diff --git a/sdk/src/types.ts b/sdk/src/types.ts
index 0f0760504..19f7074de 100644
--- a/sdk/src/types.ts
+++ b/sdk/src/types.ts
@@ -10,6 +10,9 @@
export type Entity = number;
export const INVALID_ENTITY = 0 as Entity;
+export type TextureHandle = number;
+export const INVALID_TEXTURE = 0xFFFFFFFF as TextureHandle;
+
// =============================================================================
// Math Types
// =============================================================================
diff --git a/sdk/src/ui/TextPlugin.ts b/sdk/src/ui/TextPlugin.ts
new file mode 100644
index 000000000..194347c67
--- /dev/null
+++ b/sdk/src/ui/TextPlugin.ts
@@ -0,0 +1,72 @@
+/**
+ * @file TextPlugin.ts
+ * @brief Plugin that automatically syncs Text components to Sprite textures
+ */
+
+import type { App, Plugin } from '../app';
+import { defineSystem, Schedule } from '../system';
+import { Query, Mut } from '../query';
+import { Sprite, type SpriteData } from '../component';
+import { Text, type TextData } from './text';
+import { TextRenderer } from './TextRenderer';
+import { defineResource, Res } from '../resource';
+
+// =============================================================================
+// TextRenderer Resource
+// =============================================================================
+
+export interface TextRendererData {
+ renderer: TextRenderer | null;
+}
+
+export const TextRendererRes = defineResource<TextRendererData>(
+ { renderer: null },
+ 'TextRenderer'
+);
+
+// =============================================================================
+// Text Plugin
+// =============================================================================
+
+export class TextPlugin implements Plugin {
+ build(app: App): void {
+ const module = app.wasmModule;
+ if (!module) {
+ console.warn('TextPlugin: No WASM module available');
+ return;
+ }
+
+ const renderer = new TextRenderer(module);
+
+ app.addSystemToSchedule(Schedule.Startup, defineSystem(
+ [],
+ () => {
+ // Initialization if needed
+ }
+ ));
+
+ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
+ [Query(Text, Mut(Sprite))],
+ (query) => {
+ for (const [entity, text, sprite] of query) {
+ const textData = text as TextData;
+ const spriteData = sprite as SpriteData;
+
+ if (!textData.dirty) continue;
+
+ const result = renderer.renderForEntity(entity, textData);
+
+ spriteData.texture = result.textureHandle;
+ spriteData.size = { x: result.width, y: result.height };
+ spriteData.color = { x: 1, y: 1, z: 1, w: 1 };
+ spriteData.uvOffset = { x: 0, y: 0 };
+ spriteData.uvScale = { x: 1, y: 1 };
+
+ textData.dirty = false;
+ }
+ }
+ ));
+ }
+}
+
+export const textPlugin = new TextPlugin();
diff --git a/sdk/src/ui/TextRenderer.ts b/sdk/src/ui/TextRenderer.ts
new file mode 100644
index 000000000..67b3c302a
--- /dev/null
+++ b/sdk/src/ui/TextRenderer.ts
@@ -0,0 +1,229 @@
+/**
+ * @file TextRenderer.ts
+ * @brief Renders text to GPU textures using Canvas 2D API
+ */
+
+import type { Entity } from '../types';
+import type { ESEngineModule, CppResourceManager } from '../wasm';
+import { TextAlign, TextBaseline, type TextData } from './text';
+
+// =============================================================================
+// 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>();
+
+ constructor(module: ESEngineModule) {
+ this.module = module;
+
+ if (typeof OffscreenCanvas !== 'undefined') {
+ this.canvas = new OffscreenCanvas(512, 512);
+ this.ctx = this.canvas.getContext('2d')!;
+ } else {
+ this.canvas = document.createElement('canvas');
+ this.canvas.width = 512;
+ this.canvas.height = 512;
+ this.ctx = this.canvas.getContext('2d')!;
+ }
+ }
+
+ /**
+ * Renders text to a texture and returns the handle
+ */
+ renderText(text: TextData): TextRenderResult {
+ const ctx = this.ctx;
+ const canvas = this.canvas;
+
+ ctx.font = `${text.fontSize}px ${text.fontFamily}`;
+
+ const lines = this.wrapText(text.content, text.maxWidth);
+ const lineHeight = Math.ceil(text.fontSize * text.lineHeight);
+ const padding = Math.ceil(text.fontSize * 0.2);
+ const width = Math.ceil(this.measureWidth(lines)) + padding * 2;
+ const height = Math.ceil(lines.length * lineHeight) + padding * 2;
+
+ if (canvas.width < width || canvas.height < height) {
+ const newWidth = Math.max(canvas.width, this.nextPowerOf2(width));
+ const newHeight = Math.max(canvas.height, this.nextPowerOf2(height));
+ canvas.width = newWidth;
+ canvas.height = newHeight;
+ }
+
+ ctx.clearRect(0, 0, width, height);
+
+ ctx.font = `${text.fontSize}px ${text.fontFamily}`;
+ ctx.textAlign = this.mapAlign(text.align);
+ ctx.textBaseline = 'top';
+
+ const r = Math.round(text.color.x * 255);
+ const g = Math.round(text.color.y * 255);
+ const b = Math.round(text.color.z * 255);
+ const a = text.color.w;
+ ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
+
+ let y = padding;
+ for (const line of lines) {
+ 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;
+ }
+ ctx.fillText(line, x, y);
+ y += lineHeight;
+ }
+
+ const imageData = ctx.getImageData(0, 0, width, height);
+ const pixels = new Uint8Array(imageData.data.buffer);
+ const flipped = this.flipVertically(pixels, width, height);
+
+ const rm = this.module.getResourceManager();
+ const ptr = this.module._malloc(flipped.length);
+ this.module.HEAPU8.set(flipped, ptr);
+
+ const textureHandle = rm.createTexture(width, height, ptr, flipped.length, 1);
+
+ this.module._free(ptr);
+
+ return { textureHandle, width, height };
+ }
+
+ /**
+ * Renders text for an entity and caches the result
+ */
+ renderForEntity(entity: Entity, text: TextData): TextRenderResult {
+ const existing = this.cache.get(entity);
+ if (existing) {
+ const rm = this.module.getResourceManager();
+ rm.releaseTexture(existing.textureHandle);
+ }
+
+ const result = this.renderText(text);
+ this.cache.set(entity, result);
+ return result;
+ }
+
+ /**
+ * Gets cached render result for entity
+ */
+ getCached(entity: Entity): TextRenderResult | undefined {
+ return this.cache.get(entity);
+ }
+
+ /**
+ * Releases texture for entity
+ */
+ release(entity: Entity): void {
+ const cached = this.cache.get(entity);
+ if (cached) {
+ const rm = this.module.getResourceManager();
+ rm.releaseTexture(cached.textureHandle);
+ this.cache.delete(entity);
+ }
+ }
+
+ /**
+ * Releases all cached textures
+ */
+ releaseAll(): void {
+ const rm = this.module.getResourceManager();
+ for (const result of this.cache.values()) {
+ rm.releaseTexture(result.textureHandle);
+ }
+ this.cache.clear();
+ }
+
+ // =========================================================================
+ // Private Methods
+ // =========================================================================
+
+ private wrapText(text: string, maxWidth: number): string[] {
+ if (!text) return [''];
+ if (maxWidth <= 0) return text.split('\n');
+
+ const paragraphs = text.split('\n');
+ const lines: string[] = [];
+
+ for (const paragraph of paragraphs) {
+ const words = paragraph.split(' ');
+ let currentLine = '';
+
+ for (const word of words) {
+ const testLine = currentLine ? `${currentLine} ${word}` : word;
+ const metrics = this.ctx.measureText(testLine);
+
+ if (metrics.width > maxWidth && currentLine) {
+ lines.push(currentLine);
+ currentLine = word;
+ } else {
+ currentLine = testLine;
+ }
+ }
+ lines.push(currentLine);
+ }
+
+ return lines;
+ }
+
+ private measureWidth(lines: string[]): number {
+ let maxWidth = 0;
+ for (const line of lines) {
+ const metrics = this.ctx.measureText(line);
+ const width = metrics.actualBoundingBoxLeft !== undefined
+ ? metrics.actualBoundingBoxLeft + metrics.actualBoundingBoxRight
+ : metrics.width;
+ maxWidth = Math.max(maxWidth, 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';
+ }
+ }
+
+ private nextPowerOf2(n: number): number {
+ let p = 1;
+ while (p < n) p *= 2;
+ return p;
+ }
+
+ private flipVertically(pixels: Uint8Array, width: number, height: number): Uint8Array {
+ const rowSize = width * 4; // RGBA
+ const flipped = new Uint8Array(pixels.length);
+
+ for (let y = 0; y < height; y++) {
+ const srcOffset = y * rowSize;
+ const dstOffset = (height - 1 - y) * rowSize;
+ flipped.set(pixels.subarray(srcOffset, srcOffset + rowSize), dstOffset);
+ }
+
+ return flipped;
+ }
+}
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
new file mode 100644
index 000000000..53959cefd
--- /dev/null
+++ b/sdk/src/ui/index.ts
@@ -0,0 +1,26 @@
+/**
+ * @file ui/index.ts
+ * @brief UI module exports
+ */
+
+// Text Component
+export {
+ Text,
+ TextAlign,
+ TextBaseline,
+ type TextData,
+} from './text';
+
+// Text Renderer
+export {
+ TextRenderer,
+ type TextRenderResult,
+} from './TextRenderer';
+
+// Text Plugin
+export {
+ TextPlugin,
+ textPlugin,
+ TextRendererRes,
+ type TextRendererData,
+} from './TextPlugin';
diff --git a/sdk/src/ui/text.ts b/sdk/src/ui/text.ts
new file mode 100644
index 000000000..715d1e304
--- /dev/null
+++ b/sdk/src/ui/text.ts
@@ -0,0 +1,55 @@
+/**
+ * @file text.ts
+ * @brief Text component definition for UI text rendering
+ */
+
+import { defineComponent } from '../component';
+import type { Vec4 } from '../types';
+
+// =============================================================================
+// Text Alignment Enums
+// =============================================================================
+
+export enum TextAlign {
+ Left = 0,
+ Center = 1,
+ Right = 2,
+}
+
+export enum TextBaseline {
+ Top = 0,
+ Middle = 1,
+ Bottom = 2,
+}
+
+// =============================================================================
+// Text Component Data
+// =============================================================================
+
+export interface TextData {
+ content: string;
+ fontFamily: string;
+ fontSize: number;
+ color: Vec4;
+ align: TextAlign;
+ baseline: TextBaseline;
+ maxWidth: number;
+ lineHeight: number;
+ dirty: boolean;
+}
+
+// =============================================================================
+// Text Component Definition
+// =============================================================================
+
+export const Text = defineComponent<TextData>('Text', {
+ content: '',
+ fontFamily: 'Arial',
+ fontSize: 24,
+ color: { x: 1, y: 1, z: 1, w: 1 },
+ align: TextAlign.Left,
+ baseline: TextBaseline.Top,
+ maxWidth: 0,
+ lineHeight: 1.2,
+ dirty: true,
+});