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: extract walkParentChain and simplify sync paths
esengine03533e68d552
diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.tsindex e549f155d..12fe4a5c5 100644--- a/editor/src/scene/EditorSceneManager.ts+++ b/editor/src/scene/EditorSceneManager.ts@@ -25,6 +25,7 @@ import {syncFillSpriteSize,computeFillAnchors,computeHandleAnchors,+ computeFillSize,DEFAULT_SPRITE_SIZE,DEFAULT_FONT_FAMILY,DEFAULT_FONT_SIZE,@@ -273,6 +274,7 @@ export class EditorSceneManager {uiRectComp.data.anchorMax = anchors.anchorMax;uiRectComp.data.offsetMin = anchors.offsetMin;uiRectComp.data.offsetMax = anchors.offsetMax;+ uiRectComp.data.size = computeFillSize(direction, normalizedValue, parentW, parentH);}}this.syncEntityTransform(fillEntityId);diff --git a/editor/src/sync/RuntimeSyncService.ts b/editor/src/sync/RuntimeSyncService.tsindex 6d73ad794..f5e8a74a3 100644--- a/editor/src/sync/RuntimeSyncService.ts+++ b/editor/src/sync/RuntimeSyncService.ts@@ -120,6 +120,10 @@ export class RuntimeSyncService {this.syncButtonTransitionColor(event.entity);}+ if (event.componentType === 'TextInput' && event.propertyName === 'backgroundColor') {+ this.store_.updatePropertyDirect(event.entity, 'Sprite', 'color', event.newValue);+ }+if (event.componentType === 'Slider') {this.syncSliderChildren(event.entity);}diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex 710bd5194..bdba467c6 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -19,7 +19,7 @@ import { initPostProcessAPI, shutdownPostProcessAPI } from './postprocess';import { initRendererAPI, shutdownRendererAPI } from './renderer';import { initGLDebugAPI, shutdownGLDebugAPI } from './glDebug';import { setWasmErrorHandler } from './wasmError';-import { platformNow } from './platform';+import { platformNow, platformDevicePixelRatio } from './platform';import { ProjectionType, ScaleMode, SceneOwner } from './component';import type { Entity } from './types';import { RenderPipeline, type SpineRendererFn } from './renderPipeline';@@ -37,6 +37,7 @@ export interface Plugin {name?: string;dependencies?: ResourceDef<any>[];build(app: App): void;+ cleanup?(): void;}// =============================================================================@@ -359,6 +360,13 @@ export class App {this.running_ = false;clearDrawCallbacks();+ for (const plugin of this.installed_plugins_) {+ try { plugin.cleanup?.(); } catch (e) {+ console.error('[ESEngine] Plugin cleanup error:', e);+ }+ }+ this.installed_plugins_.clear();+const shutdowns = [shutdownGLDebugAPI,shutdownRendererAPI,@@ -527,10 +535,13 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): Aapp.setPipeline(pipeline);let startTime = platformNow();- const getViewportSize = options?.getViewportSize ?? (() => ({- width: window.innerWidth * (window.devicePixelRatio || 1),- height: window.innerHeight * (window.devicePixelRatio || 1)- }));+ const getViewportSize = options?.getViewportSize ?? (() => {+ const dpr = platformDevicePixelRatio();+ return {+ width: window.innerWidth * dpr,+ height: window.innerHeight * dpr,+ };+ });app.insertResource(UICameraInfo, {viewProjection: new Float32Array(16),diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsindex a014b47a2..d6970c364 100644--- a/sdk/src/platform/base.ts+++ b/sdk/src/platform/base.ts@@ -101,3 +101,11 @@ export function platformCreateImage(): HTMLImageElement {export function platformNow(): number {return getPlatform().now();}++export function platformDevicePixelRatio(): number {+ if (currentPlatform?.name === 'wechat') {+ const g = globalThis as any;+ return g.wx?.getSystemInfoSync?.()?.pixelRatio ?? 1;+ }+ return typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;+}diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.tsindex 261ce9e71..18574b11e 100644--- a/sdk/src/platform/index.ts+++ b/sdk/src/platform/index.ts@@ -28,6 +28,7 @@ export {platformCreateCanvas,platformCreateImage,platformNow,+ platformDevicePixelRatio,} from './base';// Note: webAdapter is exported here for initializationdiff --git a/sdk/src/scene.ts b/sdk/src/scene.tsindex f3a7cd6d9..55adff8f9 100644--- a/sdk/src/scene.ts+++ b/sdk/src/scene.ts@@ -236,6 +236,65 @@ export async function loadSceneWithAssets(return entityMap;}+interface AssetFieldHandler {+ load(paths: Set<string>, assetServer: AssetServer, baseUrl: string | undefined,+ texturePathToUrl: Map<string, string>): Promise<Map<string, number>>;+}++const ASSET_FIELD_HANDLERS = new Map<AssetFieldType, AssetFieldHandler>([+ ['texture', {+ async load(paths, assetServer, baseUrl, texturePathToUrl) {+ const handles = new Map<string, number>();+ const promises = [...paths].map(async (texturePath) => {+ try {+ const isDataUrl = texturePath.startsWith('data:');+ const url = isDataUrl ? texturePath : baseUrl ? `${baseUrl}/${texturePath}` : `/${texturePath}`;+ const info = await assetServer.loadTexture(url);+ handles.set(texturePath, info.handle);+ texturePathToUrl.set(texturePath, url);+ } catch (err) {+ console.warn(`Failed to load texture: ${texturePath}`, err);+ handles.set(texturePath, 0);+ }+ });+ await Promise.all(promises);+ return handles;+ },+ }],+ ['material', {+ async load(paths, assetServer, baseUrl) {+ const handles = new Map<string, number>();+ const promises = [...paths].map(async (materialPath) => {+ try {+ const loaded = await assetServer.loadMaterial(materialPath, baseUrl);+ handles.set(materialPath, loaded.handle);+ } catch (err) {+ console.warn(`Failed to load material: ${materialPath}`, err);+ handles.set(materialPath, 0);+ }+ });+ await Promise.all(promises);+ return handles;+ },+ }],+ ['font', {+ async load(paths, assetServer, baseUrl) {+ const handles = new Map<string, number>();+ const promises = [...paths].map(async (fontPath) => {+ try {+ const handle = await assetServer.loadBitmapFont(fontPath, baseUrl);+ handles.set(fontPath, handle);+ } catch (err) {+ console.warn(`Failed to load bitmap font: ${fontPath}`, err);+ handles.set(fontPath, 0);+ }+ });+ await Promise.all(promises);+ return handles;+ },+ }],+]);+async function preloadSceneAssets(sceneData: SceneData,assetServer: AssetServer,@@ -244,9 +303,10 @@ async function preloadSceneAssets(): Promise<void> {sceneData = JSON.parse(JSON.stringify(sceneData));- const textures = new Set<string>();- const materials = new Set<string>();- const fonts = new Set<string>();+ const assetPaths = new Map<AssetFieldType, Set<string>>();+ for (const type of ASSET_FIELD_HANDLERS.keys()) {+ assetPaths.set(type, new Set());+ }const spines: { skeleton: string; atlas: string }[] = [];const spineKeys = new Set<string>();@@ -275,74 +335,26 @@ async function preloadSceneAssets(for (const desc of config.fields) {const value = data[desc.field];if (typeof value !== 'string' || !value) continue;-- switch (desc.type) {- case 'texture': textures.add(value); break;- case 'material': materials.add(value); break;- case 'font': fonts.add(value); break;- }+ assetPaths.get(desc.type)?.add(value);}}}}- const textureHandles = new Map<string, number>();- const materialHandles = new Map<string, number>();- const fontHandles = new Map<string, number>();-- const promises: Promise<void>[] = [];-- for (const texturePath of textures) {- promises.push((async () => {- try {- const isDataUrl = texturePath.startsWith('data:');- const url = isDataUrl- ? texturePath- : baseUrl ? `${baseUrl}/${texturePath}` : `/${texturePath}`;- const info = await assetServer.loadTexture(url);- textureHandles.set(texturePath, info.handle);- texturePathToUrl.set(texturePath, url);- } catch (err) {- console.warn(`Failed to load texture: ${texturePath}`, err);- textureHandles.set(texturePath, 0);- }- })());- }+ const assetHandles = new Map<AssetFieldType, Map<string, number>>();+ const loadPromises = [...ASSET_FIELD_HANDLERS.entries()].map(async ([type, handler]) => {+ const handles = await handler.load(assetPaths.get(type)!, assetServer, baseUrl, texturePathToUrl);+ assetHandles.set(type, handles);+ });- for (const materialPath of materials) {- promises.push((async () => {- try {- const loaded = await assetServer.loadMaterial(materialPath, baseUrl);- materialHandles.set(materialPath, loaded.handle);- } catch (err) {- console.warn(`Failed to load material: ${materialPath}`, err);- materialHandles.set(materialPath, 0);- }- })());- }-- for (const fontPath of fonts) {- promises.push((async () => {- try {- const handle = await assetServer.loadBitmapFont(fontPath, baseUrl);- fontHandles.set(fontPath, handle);- } catch (err) {- console.warn(`Failed to load bitmap font: ${fontPath}`, err);- fontHandles.set(fontPath, 0);- }- })());- }-- for (const spine of spines) {- promises.push((async () => {- const result = await assetServer.loadSpine(spine.skeleton, spine.atlas, baseUrl);- if (!result.success) {- console.warn(`Failed to load Spine: ${result.error}`);- }- })());- }+ const spinePromises = spines.map(async (spine) => {+ const result = await assetServer.loadSpine(spine.skeleton, spine.atlas, baseUrl);+ if (!result.success) {+ console.warn(`Failed to load Spine: ${result.error}`);+ }+ });- await Promise.all(promises);+ await Promise.all([...loadPromises, ...spinePromises]);for (const entityData of sceneData.entities) {if (entityData.visible === false) continue;@@ -355,18 +367,7 @@ async function preloadSceneAssets(for (const desc of config.fields) {const value = data[desc.field];if (typeof value !== 'string' || !value) continue;-- switch (desc.type) {- case 'texture':- data[desc.field] = textureHandles.get(value) ?? 0;- break;- case 'material':- data[desc.field] = materialHandles.get(value) ?? 0;- break;- case 'font':- data[desc.field] = fontHandles.get(value) ?? 0;- break;- }+ data[desc.field] = assetHandles.get(desc.type)?.get(value) ?? 0;}}}diff --git a/sdk/src/ui/SafeAreaPlugin.ts b/sdk/src/ui/SafeAreaPlugin.tsindex b5f39da94..a4b7719ed 100644--- a/sdk/src/ui/SafeAreaPlugin.ts+++ b/sdk/src/ui/SafeAreaPlugin.ts@@ -1,5 +1,5 @@import type { App, Plugin } from '../app';-import { isWeChat } from '../platform';+import { isWeChat, platformDevicePixelRatio } from '../platform';import { registerComponent } from '../component';import { Res } from '../resource';import { defineSystem, Schedule } from '../system';@@ -90,7 +90,7 @@ export class SafeAreaPlugin implements Plugin {if (!dirty) return;dirty = false;- const dpr = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;+ const dpr = platformDevicePixelRatio();const insetScale = isWeChat() ? (worldH / camera.screenH) : (dpr * worldH / camera.screenH);const entities = world.getEntitiesWithComponents([SafeArea, UIRect]);diff --git a/sdk/src/ui/UIInteractionPlugin.ts b/sdk/src/ui/UIInteractionPlugin.tsindex b58591e51..726aaa3c9 100644--- a/sdk/src/ui/UIInteractionPlugin.ts+++ b/sdk/src/ui/UIInteractionPlugin.ts@@ -22,6 +22,7 @@ import type { UICameraData } from './UICameraInfo';import { UIMask } from './UIMask';import type { UIMaskData } from './UIMask';import { screenToWorld, pointInOBB, createInvVPCache } from './uiMath';+import { platformDevicePixelRatio } from '../platform';import { applyColorTransition, getEffectiveWidth, getEffectiveHeight, ensureComponent, walkParentChain } from './uiHelpers';const vpCache = createInvVPCache();@@ -100,7 +101,7 @@ export class UIInteractionPlugin implements Plugin {if (!camera.valid) return;- const dpr = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;+ const dpr = platformDevicePixelRatio();const mouseGLX = input.mouseX * dpr;const mouseGLY = camera.screenH - input.mouseY * dpr;diff --git a/sdk/src/world.ts b/sdk/src/world.tsindex 18c5cc737..c2e58b985 100644--- a/sdk/src/world.ts+++ b/sdk/src/world.ts@@ -95,6 +95,7 @@ export class World {}this.entities_.add(entity);+ this.worldVersion_++;return entity;}@@ -299,6 +300,7 @@ export class World {}}+ this.worldVersion_++;return merged;}@@ -335,6 +337,7 @@ export class World {} catch (e) {handleWasmError(e, `removeBuiltin(${component._name}, entity=${entity})`);}+ this.worldVersion_++;}// =========================================================================@@ -416,7 +419,6 @@ export class World {resetQueryPool(): void {this.queryPoolIdx_ = 0;- this.queryCache_.clear();}getComponentTypes(entity: Entity): string[] {@@ -505,7 +507,7 @@ export class World {}}- this.queryCache_.set(cacheKey, { version: this.worldVersion_, result: entities });+ this.queryCache_.set(cacheKey, { version: this.worldVersion_, result: entities.slice() });return entities;}