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
fix: resolve text disappearing after entity creation due to C++ entity ID recycling
esengine152acac21752
diff --git a/sdk/src/ui/DropdownPlugin.ts b/sdk/src/ui/DropdownPlugin.tsindex 628ec7d33..1935e17a6 100644--- a/sdk/src/ui/DropdownPlugin.ts+++ b/sdk/src/ui/DropdownPlugin.ts@@ -53,13 +53,16 @@ export class DropdownPlugin implements Plugin {if (!state) {state = { optionEntities: [], textEntities: [], highlightIndex: -1, ddWidth: 0, ddLayer: 0 };dropdownStates.set(entity, state);- normalizeListTransform(dropdown.listEntity);- if (!dropdown.isOpen) {- setListVisible(dropdown.listEntity, false);- }- initDropdownAppearance(entity);}+ normalizeListTransform(dropdown.listEntity);+ initDropdownAppearance(entity);+ if (!dropdown.isOpen) {+ setListVisible(dropdown.listEntity, false);+ }++ syncLabel(dropdown);+if (editorSceneView) continue;ensureComponent(world, entity, Interactable, { enabled: true, blockRaycast: true });@@ -128,8 +131,6 @@ export class DropdownPlugin implements Plugin {}}}-- syncLabel(dropdown);}},{ name: 'DropdownSystem' }diff --git a/sdk/src/ui/ListViewPlugin.ts b/sdk/src/ui/ListViewPlugin.tsindex 472d9c186..f11a82d88 100644--- a/sdk/src/ui/ListViewPlugin.ts+++ b/sdk/src/ui/ListViewPlugin.ts@@ -58,7 +58,8 @@ export class ListViewPlugin implements Plugin {app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([Res(Input)],(input: InputState) => {- if (isEditor() && !isPlayMode()) return;+ const editorSceneView = isEditor() && !isPlayMode();+for (const [e, st] of listViewStates) {if (!world.valid(e)) {for (const itemEntity of st.itemEntities.values()) {@@ -91,14 +92,16 @@ export class ListViewPlugin implements Plugin {const viewHeight = getEffectiveHeight(rect, entity);const viewWidth = getEffectiveWidth(rect, entity);- const interaction = world.has(entity, UIInteraction)- ? world.get(entity, UIInteraction) as UIInteractionData- : null;+ if (!editorSceneView) {+ const interaction = world.has(entity, UIInteraction)+ ? world.get(entity, UIInteraction) as UIInteractionData+ : null;- if (interaction?.hovered) {- const scroll = input.getScrollDelta();- if (scroll.y !== 0) {- lv.scrollY += scroll.y * SCROLL_WHEEL_SENSITIVITY;+ if (interaction?.hovered) {+ const scroll = input.getScrollDelta();+ if (scroll.y !== 0) {+ lv.scrollY += scroll.y * SCROLL_WHEEL_SENSITIVITY;+ }}}diff --git a/sdk/src/ui/ScrollViewPlugin.ts b/sdk/src/ui/ScrollViewPlugin.tsindex 4708ab612..2b71e7cd1 100644--- a/sdk/src/ui/ScrollViewPlugin.ts+++ b/sdk/src/ui/ScrollViewPlugin.ts@@ -44,24 +44,23 @@ export class ScrollViewPlugin implements Plugin {app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([Res(Input), Res(UICameraInfo)],(input: InputState, camera: UICameraData) => {- if (isEditor() && !isPlayMode()) return;+ const editorSceneView = isEditor() && !isPlayMode();const now = performance.now() / 1000;const dt = lastTime > 0 ? Math.min(now - lastTime, SCROLL_MAX_DT) : 0;lastTime = now;- if (!camera.valid) return;-for (const [e] of states) {if (!world.valid(e)) states.delete(e);}- worldMouse.x = camera.worldMouseX;- worldMouse.y = camera.worldMouseY;+ if (camera.valid) {+ worldMouse.x = camera.worldMouseX;+ worldMouse.y = camera.worldMouseY;+ }const entities = world.getEntitiesWithComponents([ScrollView, UIRect]);for (const entity of entities) {- ensureComponent(world, entity, Interactable, { enabled: true, blockRaycast: true });ensureComponent(world, entity, UIMask, { enabled: true, mode: MaskMode.Scissor });const sv = world.get(entity, ScrollView) as ScrollViewData;@@ -73,66 +72,70 @@ export class ScrollViewPlugin implements Plugin {states.set(entity, state);}- const interaction = world.has(entity, UIInteraction)- ? world.get(entity, UIInteraction) as UIInteractionData- : null;+ if (!editorSceneView && camera.valid) {+ ensureComponent(world, entity, Interactable, { enabled: true, blockRaycast: true });- if (interaction?.justPressed) {- state.isDragging = true;- state.lastWorldX = worldMouse.x;- state.lastWorldY = worldMouse.y;- state.velocityX = 0;- state.velocityY = 0;- }+ const interaction = world.has(entity, UIInteraction)+ ? world.get(entity, UIInteraction) as UIInteractionData+ : null;- if (state.isDragging && input.isMouseButtonDown(0)) {- const dx = worldMouse.x - state.lastWorldX;- const dy = worldMouse.y - state.lastWorldY;-- if (sv.horizontalEnabled) {- sv.scrollX -= dx;- const instantVx = dt > 0 ? -dx / dt : 0;- state.velocityX = state.velocityX * SCROLL_VELOCITY_SMOOTHING + instantVx * SCROLL_VELOCITY_NEW_WEIGHT;- }- if (sv.verticalEnabled) {- sv.scrollY -= dy;- const instantVy = dt > 0 ? -dy / dt : 0;- state.velocityY = state.velocityY * SCROLL_VELOCITY_SMOOTHING + instantVy * SCROLL_VELOCITY_NEW_WEIGHT;+ if (interaction?.justPressed) {+ state.isDragging = true;+ state.lastWorldX = worldMouse.x;+ state.lastWorldY = worldMouse.y;+ state.velocityX = 0;+ state.velocityY = 0;}- state.lastWorldX = worldMouse.x;- state.lastWorldY = worldMouse.y;- }-- if (state.isDragging && input.isMouseButtonReleased(0)) {- state.isDragging = false;- }-- if (interaction?.hovered) {- const scroll = input.getScrollDelta();- if (sv.verticalEnabled && scroll.y !== 0) {- sv.scrollY += scroll.y * SCROLL_WHEEL_SENSITIVITY;- state.velocityY = 0;+ if (state.isDragging && input.isMouseButtonDown(0)) {+ const dx = worldMouse.x - state.lastWorldX;+ const dy = worldMouse.y - state.lastWorldY;++ if (sv.horizontalEnabled) {+ sv.scrollX -= dx;+ const instantVx = dt > 0 ? -dx / dt : 0;+ state.velocityX = state.velocityX * SCROLL_VELOCITY_SMOOTHING + instantVx * SCROLL_VELOCITY_NEW_WEIGHT;+ }+ if (sv.verticalEnabled) {+ sv.scrollY -= dy;+ const instantVy = dt > 0 ? -dy / dt : 0;+ state.velocityY = state.velocityY * SCROLL_VELOCITY_SMOOTHING + instantVy * SCROLL_VELOCITY_NEW_WEIGHT;+ }++ state.lastWorldX = worldMouse.x;+ state.lastWorldY = worldMouse.y;}- if (sv.horizontalEnabled && scroll.x !== 0) {- sv.scrollX += scroll.x * SCROLL_WHEEL_SENSITIVITY;- state.velocityX = 0;++ if (state.isDragging && input.isMouseButtonReleased(0)) {+ state.isDragging = false;}- }- if (!state.isDragging && sv.inertia && dt > 0) {- const decay = Math.pow(sv.decelerationRate, dt * SCROLL_FPS_REFERENCE);- if (sv.horizontalEnabled && Math.abs(state.velocityX) > SCROLL_VELOCITY_THRESHOLD) {- sv.scrollX += state.velocityX * dt;- state.velocityX *= decay;- } else {- state.velocityX = 0;+ if (interaction?.hovered) {+ const scroll = input.getScrollDelta();+ if (sv.verticalEnabled && scroll.y !== 0) {+ sv.scrollY += scroll.y * SCROLL_WHEEL_SENSITIVITY;+ state.velocityY = 0;+ }+ if (sv.horizontalEnabled && scroll.x !== 0) {+ sv.scrollX += scroll.x * SCROLL_WHEEL_SENSITIVITY;+ state.velocityX = 0;+ }}- if (sv.verticalEnabled && Math.abs(state.velocityY) > SCROLL_VELOCITY_THRESHOLD) {- sv.scrollY += state.velocityY * dt;- state.velocityY *= decay;- } else {- state.velocityY = 0;++ if (!state.isDragging && sv.inertia && dt > 0) {+ const decay = Math.pow(sv.decelerationRate, dt * SCROLL_FPS_REFERENCE);+ if (sv.horizontalEnabled && Math.abs(state.velocityX) > SCROLL_VELOCITY_THRESHOLD) {+ sv.scrollX += state.velocityX * dt;+ state.velocityX *= decay;+ } else {+ state.velocityX = 0;+ }+ if (sv.verticalEnabled && Math.abs(state.velocityY) > SCROLL_VELOCITY_THRESHOLD) {+ sv.scrollY += state.velocityY * dt;+ state.velocityY *= decay;+ } else {+ state.velocityY = 0;+ }}}diff --git a/sdk/src/ui/TextPlugin.ts b/sdk/src/ui/TextPlugin.tsindex 009790601..8667c5fc5 100644--- a/sdk/src/ui/TextPlugin.ts+++ b/sdk/src/ui/TextPlugin.ts@@ -54,9 +54,19 @@ export class TextPlugin implements Plugin {for (const entity of snapshots.keys()) {if (!world.valid(entity) || !world.has(entity, Text)) {if (world.valid(entity) && world.has(entity, Sprite)) {- const sprite = world.get(entity, Sprite) as SpriteData;- sprite.texture = INVALID_TEXTURE;- world.insert(entity, Sprite, sprite);+ const s = world.get(entity, Sprite) as SpriteData;+ world.insert(entity, Sprite, {+ texture: INVALID_TEXTURE,+ color: { r: s.color.r, g: s.color.g, b: s.color.b, a: s.color.a },+ size: { x: s.size.x, y: s.size.y },+ uvOffset: { x: s.uvOffset.x, y: s.uvOffset.y },+ uvScale: { x: s.uvScale.x, y: s.uvScale.y },+ layer: s.layer,+ flipX: s.flipX,+ flipY: s.flipY,+ material: s.material,+ enabled: s.enabled,+ });}snapshots.delete(entity);}@@ -72,21 +82,35 @@ export class TextPlugin implements Plugin {const source: TextSource = { text, uiRect, entity };const prev = snapshots.get(entity);- if (prev && !textSnapshot.changed(prev, source)) continue;+ if (prev && !textSnapshot.changed(prev, source)) {+ const hasValidSprite = world.has(entity, Sprite)+ && (world.get(entity, Sprite) as SpriteData).texture !== INVALID_TEXTURE;+ if (hasValidSprite) continue;+ }ensureSprite(world, entity);- const result = renderer.renderForEntity(entity, text, uiRect);+ const effectiveRect = uiRect ? {+ size: {+ x: getEffectiveWidth(uiRect, entity),+ y: getEffectiveHeight(uiRect, entity),+ },+ } : null;+ const result = renderer.renderForEntity(entity, text, effectiveRect);- const sprite = world.get(entity, Sprite) as SpriteData;- sprite.texture = result.textureHandle;- sprite.size.x = result.width;- sprite.size.y = result.height;- sprite.uvOffset.x = 0;- sprite.uvOffset.y = 0;- sprite.uvScale.x = 1;- sprite.uvScale.y = 1;- world.insert(entity, Sprite, sprite);+ const s = world.get(entity, Sprite) as SpriteData;+ world.insert(entity, Sprite, {+ texture: result.textureHandle,+ color: { r: s.color.r, g: s.color.g, b: s.color.b, a: s.color.a },+ size: { x: result.width, y: result.height },+ uvOffset: { x: 0, y: 0 },+ uvScale: { x: 1, y: 1 },+ layer: s.layer,+ flipX: s.flipX,+ flipY: s.flipY,+ material: s.material,+ enabled: s.enabled,+ });snapshots.set(entity, textSnapshot.take(source));}diff --git a/sdk/tests/text-multi-render.test.ts b/sdk/tests/text-multi-render.test.tsnew file mode 100644index 000000000..8e6826363--- /dev/null+++ b/sdk/tests/text-multi-render.test.ts@@ -0,0 +1,278 @@+/**+ * 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 { existsSync } from 'fs';+import { resolve } from 'path';+import { App } from '../src/app';+import { Transform, Sprite } from '../src/component';+import type { SpriteData } from '../src/component';+import { UIRect } from '../src/ui/UIRect';+import { ScreenSpace } from '../src/ui/ScreenSpace';+import { UICameraInfo } from '../src/ui/UICameraInfo';+import { Input, InputState } from '../src/input';+import { UIEvents, UIEventQueue } from '../src/ui/UIEvents';+import { uiLayoutPlugin } from '../src/ui/UILayoutPlugin';+import { uiRenderOrderPlugin } from '../src/ui/UIRenderOrderPlugin';+import { textPlugin } from '../src/ui/TextPlugin';+import { Text } from '../src/ui/text';+import { INVALID_TEXTURE } from '../src/types';+import type { ESEngineModule, CppRegistry } from '../src/wasm';+import { loadWasmModule } from './helpers/loadWasm';++const WASM_PATH = resolve(__dirname, '../../desktop/public/wasm/esengine.wasm');+const HAS_WASM = existsSync(WASM_PATH);++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 createScreenSpaceRoot(app: App) {+ const world = app.world;+ const root = world.spawn();+ world.insert(root, ScreenSpace, {});+ 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 = createScreenSpaceRoot(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 = createScreenSpaceRoot(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 = createScreenSpaceRoot(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 = createScreenSpaceRoot(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);+ });+});