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
feat(sdk): boot an exported project on the native host
esengine0927a09c0e05
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 88c036572..ac9587aa7 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -3476,7 +3476,7 @@ mouse: boolean | undefined## LoadRuntimeSceneOptions — interface```app: App-module: ESEngineModule+module: ESEngineModule | nullphysicsConfig: PhysicsPluginConfig | undefinedphysicsEnabled: boolean | undefinedphysicsModule: PhysicsWasmModule | null | undefined@@ -5366,7 +5366,7 @@ audioConfig: AudioProjectConfig | undefinedcatalog: Catalog | undefinedfirstScene: stringmanifest: AddressableManifest | ManifestModel | null | undefined-module: ESEngineModule+module: ESEngineModule | nullpersistUpdateKey: string | undefinedphysicsConfig: PhysicsPluginConfig | undefinedphysicsEnabled: boolean | undefineddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex db8891b10..afdb65248 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1330 stable · 22 beta · 0 deprecated+Symbols: 1338 stable · 22 beta · 0 deprecated## ABI_LAYOUT_HASH — const```@@ -3484,7 +3484,7 @@ mouse: boolean | undefined## LoadRuntimeSceneOptions — interface```app: App-module: ESEngineModule+module: ESEngineModule | nullphysicsConfig: PhysicsPluginConfig | undefinedphysicsEnabled: boolean | undefinedphysicsModule: PhysicsWasmModule | null | undefined@@ -3958,6 +3958,33 @@ statusText: string | undefinedtext: string | undefined```+## NativeGame — interface+```+app: App+config: NativeGameConfig+```++## NativeGameConfig — interface+```+colorSpace: "gamma" | "linear" | undefined+entryScene: string+hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined+scenes: { name: string; path: string; }[] | undefined+screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined+uiTheme: "light" | undefined+uiThemeColors: Record<string, string> | undefined+ySortLayers: number | undefined+```++## NativeGameOptions — interface+```+bridge: NativeBridge+configPath: string | undefined+height: number+scope: Record<string, unknown> | undefined+width: number+```+## NativeInputListener — interface @beta```onKeyDown: ((code: string) => void) | undefined@@ -4180,6 +4207,15 @@ width: number | undefinedRecord<string, PtrLayout>```+## PackagedAssetIndex — interface+```+assetPaths: () => string[]+catalog: Catalog | undefined+manifest: AddressableManifest+model: ManifestModel+resolvePath: (ref: string) => string+```+## Parent — const```BuiltinComponentDef<ParentData>@@ -5457,7 +5493,7 @@ audioConfig: AudioProjectConfig | undefinedcatalog: Catalog | undefinedfirstScene: stringmanifest: AddressableManifest | ManifestModel | null | undefined-module: ESEngineModule+module: ESEngineModule | nullpersistUpdateKey: string | undefinedphysicsConfig: PhysicsPluginConfig | undefinedphysicsEnabled: boolean | undefined@@ -8235,6 +8271,11 @@ BtPlugin(mode: TerrainMode, mask: number): number```+## catalogFromManifest — function+```+(manifest: AddressableManifest): Catalog | undefined+```+## clearAllCaches — function```(): void@@ -8965,11 +9006,21 @@ FsmPlugin(flip: boolean): ImageBitmapOptions```+## indexPackagedManifest — function+```+(manifest: AddressableManifest): PackagedAssetIndex+```+## info — function```(category: string, message: string, data?: unknown): void```+## initNativeGame — function+```+(options: NativeGameOptions): Promise<NativeGame>+```+## initPlayRealmRuntime — function```(config: PlayRealmRuntimeConfig): Promise<void>@@ -9155,6 +9206,11 @@ LifecyclePlugin(asset: InputMapAsset): InputMap```+## loadPackagedAssetIndex — function+```+(manifestPath?: string): Promise<PackagedAssetIndex>+```+## loadPhysicsModule — function```(wasmUrl: string, factory?: PhysicsModuleFactory): Promise<PhysicsWasmModule>diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 619c09b1e..92740f195 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -3471,7 +3471,7 @@ mouse: boolean | undefined## LoadRuntimeSceneOptions — interface```app: App-module: ESEngineModule+module: ESEngineModule | nullphysicsConfig: PhysicsPluginConfig | undefinedphysicsEnabled: boolean | undefinedphysicsModule: PhysicsWasmModule | null | undefined@@ -5361,7 +5361,7 @@ audioConfig: AudioProjectConfig | undefinedcatalog: Catalog | undefinedfirstScene: stringmanifest: AddressableManifest | ManifestModel | null | undefined-module: ESEngineModule+module: ESEngineModule | nullpersistUpdateKey: string | undefinedphysicsConfig: PhysicsPluginConfig | undefinedphysicsEnabled: boolean | undefineddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex bf705d535..4023b9412 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -3478,7 +3478,7 @@ mouse: boolean | undefined## LoadRuntimeSceneOptions — interface```app: App-module: ESEngineModule+module: ESEngineModule | nullphysicsConfig: PhysicsPluginConfig | undefinedphysicsEnabled: boolean | undefinedphysicsModule: PhysicsWasmModule | null | undefined@@ -5368,7 +5368,7 @@ audioConfig: AudioProjectConfig | undefinedcatalog: Catalog | undefinedfirstScene: stringmanifest: AddressableManifest | ManifestModel | null | undefined-module: ESEngineModule+module: ESEngineModule | nullpersistUpdateKey: string | undefinedphysicsConfig: PhysicsPluginConfig | undefinedphysicsEnabled: boolean | undefineddiff --git a/sdk/src/index.native.ts b/sdk/src/index.native.tsindex 8dc8c02ec..9af30e8ff 100644--- a/sdk/src/index.native.ts+++ b/sdk/src/index.native.ts@@ -63,6 +63,16 @@ export { createNativeWorld } from './ecs/nativeRuntime';// NativeBridge) + native ECS. The system-binding layer (Stage B) over the World.export { createNativeApp } from './ecs/nativeRuntime';+// Boot an EXPORTED project (cooked assets + scenes + game.config.json read off+// the device) rather than a hand-written game script — the native sibling of the+// WeChat runtime and the web game host.+export { initNativeGame } from './nativeGameRuntime';+export type { NativeGame, NativeGameConfig, NativeGameOptions } from './nativeGameRuntime';++// The packaged-realm asset assembly the native and WeChat runtimes share.+export { loadPackagedAssetIndex, indexPackagedManifest, catalogFromManifest } from './packagedRuntime';+export type { PackagedAssetIndex } from './packagedRuntime';+// ABI layout hash of the component schema this bundle was generated from — the// native shell compares it against the wasm build it loads (same as the editor).export { ABI_LAYOUT_HASH } from './component.generated';diff --git a/sdk/src/nativeGameRuntime.ts b/sdk/src/nativeGameRuntime.tsnew file mode 100644index 000000000..f5e912b73--- /dev/null+++ b/sdk/src/nativeGameRuntime.ts@@ -0,0 +1,107 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file nativeGameRuntime.ts+ * @brief Boot an exported project on the native (embedded-Dawn) host — the+ * native sibling of initWeChatRuntime / the web game host.+ * @details The native app ships this runtime inside the host binary, so an export+ * is content only: cooked assets, the addressable manifest, the scenes+ * and `game.config.json`. Everything arrives through the host's+ * `NativeBridge` (packaged files), and rendering belongs to the native+ * C++ core — there is no wasm module and no canvas here.+ *+ * The host drives the frame: call {@link initNativeGame} once, then+ * `app.tick(dt)` per frame (the returned handle tolerates being ticked+ * before the async boot settles).+ */++import type { App } from './app';+import { initRuntime } from './runtimeLoader';+import { createNativeApp } from './ecs/nativeRuntime';+import type { NativeBridge } from './platform/native';+import { FileSystemBackend } from './asset/Backend';+import { platformReadTextFile, platformLoadImagePixels } from './platform';+import { loadPackagedAssetIndex } from './packagedRuntime';+import type { RuntimeAssetSource } from './runtimeAssets';+import type { SceneData } from './scene';+import type { ThemeOverrides } from './ui';+import { parseThemeOverrides } from './ui';+import { log } from './logger';++/** `game.config.json` — what the export bakes about the project. */+export interface NativeGameConfig {+ entryScene: string;+ /** Every switchable scene (SceneManager name + cooked path); includes the entry. */+ scenes?: Array<{ name: string; path: string }>;+ ySortLayers?: number;+ colorSpace?: 'gamma' | 'linear';+ screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };+ uiTheme?: 'light';+ uiThemeColors?: Record<string, string>;+ hotUpdate?: { remoteRoot?: string; persistUpdateKey?: string };+}++export interface NativeGameOptions {+ /** The host's capability bridge (packaged files, image decode, input). */+ bridge: NativeBridge;+ /** Where the host installed its `es_*` bindings; the JS global by default. */+ scope?: Record<string, unknown>;+ /** Surface size in pixels — the camera's aspect comes from it. */+ width: number;+ height: number;+ /** Overrides the packaged config path (default `game.config.json`). */+ configPath?: string;+}++export interface NativeGame {+ app: App;+ config: NativeGameConfig;+}++/**+ * Boot the exported project: read the config + manifest off the device, index+ * the assets, register every shipped scene and load the entry one.+ */+export async function initNativeGame(options: NativeGameOptions): Promise<NativeGame> {+ const { bridge, scope, width, height } = options;+ const app = createNativeApp(bridge, scope);++ const config = JSON.parse(+ await platformReadTextFile(options.configPath ?? 'game.config.json'),+ ) as NativeGameConfig;++ const index = await loadPackagedAssetIndex();+ const source: RuntimeAssetSource = {+ backend: new FileSystemBackend(),+ decodePixels: (path) => platformLoadImagePixels(path),+ resolveRef: (ref) => index.resolvePath(ref),+ listAssetPaths: () => index.assetPaths(),+ };++ const scenes = config.scenes ?? [{ name: 'main', path: config.entryScene }];+ const entry = scenes.find((s) => s.path === config.entryScene) ?? scenes[0];+ const entryData = JSON.parse(+ await platformReadTextFile(index.resolvePath(config.entryScene)),+ ) as SceneData;++ await initRuntime({+ app,+ module: null, // the engine core is native here+ source,+ manifest: index.manifest,+ catalog: index.catalog,+ remoteRoot: config.hotUpdate?.remoteRoot,+ persistUpdateKey: config.hotUpdate?.persistUpdateKey,+ scenes: [+ { name: entry.name, data: entryData },+ ...scenes.filter((s) => s.name !== entry.name).map((s) => ({ name: s.name, path: s.path })),+ ],+ firstScene: entry.name,+ aspectRatio: height > 0 ? width / height : undefined,+ uiTheme: config.uiTheme,+ uiThemeOverrides: parseThemeOverrides(config.uiThemeColors) as ThemeOverrides | undefined,+ });++ log.info('native', `game up — ${scenes.length} scene(s), entry "${entry.name}"`);+ return { app, config };+}diff --git a/sdk/src/packagedRuntime.ts b/sdk/src/packagedRuntime.tsnew file mode 100644index 000000000..7a1dd62cf--- /dev/null+++ b/sdk/src/packagedRuntime.ts@@ -0,0 +1,79 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file packagedRuntime.ts+ * @brief The asset assembly every PACKAGED realm shares — a WeChat mini-game,+ * a native app: realms that ship cooked content beside the runtime and+ * read it off the device rather than over HTTP.+ * @details The addressable manifest is the single source: it resolves a ref to a+ * staged path, and its atlas metadata builds the catalog the loaders+ * consult for their inner text refs (a material's shader). Everything+ * here is DOM-free and transport-free — the platform layer decides how+ * the bytes arrive, so the same code serves both realms.+ */++import { toBuildPath } from './assetTypes';+import { platformReadTextFile } from './platform';+import { ManifestModel, type AddressableManifest } from './asset/AddressableManifest';+import { Catalog, atlasCatalogFields, type CatalogEntry } from './asset/Catalog';++/** The packaged realm's resolved asset index — manifest, catalog, resolution. */+export interface PackagedAssetIndex {+ manifest: AddressableManifest;+ model: ManifestModel;+ /** Logical → staged mapping for the loaders' inner refs; absent when the+ * build stages assets under their logical paths (nothing to remap). */+ catalog?: Catalog;+ /** Resolve any ref spelling (`@uuid:`, logical, "/"-rooted) to a staged path. */+ resolvePath(ref: string): string;+ /** Every staged asset path — content-driven discovery (locale tables). */+ assetPaths(): string[];+}++/**+ * Build the catalog from an addressable manifest. Content-addressed packs rename+ * physical files, so assets carrying an `address` (their logical source path) get+ * a catalog buildPath. Atlas-packed frames additionally register frame/uv, keyed+ * by every ref spelling a scene can use.+ */+export function catalogFromManifest(manifest: AddressableManifest): Catalog | undefined {+ const entries: Record<string, CatalogEntry> = {};+ for (const group of Object.values(manifest.groups)) {+ for (const [uuid, asset] of Object.entries(group.assets)) {+ const md = asset.metadata;+ const atlasFields = md?.atlasFrame && md.atlasPageWidth && md.atlasPageHeight+ ? atlasCatalogFields(+ { page: md.atlasPage, frame: md.atlasFrame, pageWidth: md.atlasPageWidth, pageHeight: md.atlasPageHeight },+ asset.path,+ )+ : null;+ if (atlasFields) {+ entries[`@uuid:${uuid}`] = { type: asset.type, buildPath: asset.path, ...atlasFields };+ }+ if (!asset.address || asset.address === asset.path) continue;+ entries[asset.address] = { type: asset.type, buildPath: asset.path, ...(atlasFields ?? {}) };+ entries[`/${asset.address}`] = { type: asset.type, buildPath: asset.path, ...(atlasFields ?? {}) };+ }+ }+ return Object.keys(entries).length > 0 ? Catalog.fromJson({ version: 1, entries }) : undefined;+}++/** Read + index the packaged addressable manifest through the platform's reader. */+export async function loadPackagedAssetIndex(+ manifestPath = 'asset-manifest.json',+): Promise<PackagedAssetIndex> {+ const manifest = JSON.parse(await platformReadTextFile(manifestPath)) as AddressableManifest;+ return indexPackagedManifest(manifest);+}++/** {@link loadPackagedAssetIndex} over an already-parsed manifest. */+export function indexPackagedManifest(manifest: AddressableManifest): PackagedAssetIndex {+ const model = ManifestModel.fromJson(manifest);+ return {+ manifest,+ model,+ catalog: catalogFromManifest(manifest),+ resolvePath: (ref) => model.resolvePath(ref, toBuildPath),+ assetPaths: () => model.allAssets().map((a) => a.path),+ };+}diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex 0e4e2fc55..40be83db9 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -34,7 +34,7 @@ import { installHotUpdateRebind } from './hotUpdateRebind';import { requireResourceManager } from './resourceManager';import { log } from './logger';import { type RuntimeAssetSource, type TextureParams } from './runtimeAssets';-import { loadSpineAssets, applySpineEntities } from './spine/loadSpineScene';+import { loadSpineAssets, applySpineEntities, type SpineAssetInfo } from './spine/loadSpineScene';import type { AddressableManifest, ManifestModel } from './asset/AddressableManifest';import type { Catalog } from './asset/Catalog';@@ -77,7 +77,7 @@ const runtimeImportSettings = new WeakMap<AssetsClass, Record<string, TextureImp* neither and applied no atlas-frame indirection).*/function ensureRuntimeAssets(- app: App, module: ESEngineModule, source: RuntimeAssetSource, catalog?: Catalog,+ app: App, module: ESEngineModule | null, source: RuntimeAssetSource, catalog?: Catalog,): AssetsClass {if (app.hasResource(AssetsResource)) {const existing = app.getResource(AssetsResource);@@ -162,7 +162,9 @@ function applyTextureMetadata(export interface LoadRuntimeSceneOptions {app: App;- module: ESEngineModule;+ /** The wasm module, or null on a native host — the engine core is arm64 there,+ * so there is no Module to reach through. */+ module: ESEngineModule | null;sceneData: SceneData;source: RuntimeAssetSource;spineModule?: SpineWasmModule | null;@@ -259,12 +261,18 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis// KTX2 atlas pages transcode through the realm's basis module, acquired the// same lazy way the TextureLoader's provider does (AssetPlugin).- const spineAssetInfo = await loadSpineAssets(module, source, spineManager, discovered.spines, async () => {- const host = app.sideModules;- if (!host) return null;- const mod = await host.acquire('basis');- return mod ? transcoderFromModule(mod as unknown as BasisWasmModule) : null;- });+ // Spine rides the wasm side-module host, which a native host does not have.+ if (!module && discovered.spines.length > 0) {+ log.warn('scene', `${discovered.spines.length} spine asset(s) skipped — this realm has no wasm module`);+ }+ const spineAssetInfo = module+ ? await loadSpineAssets(module, source, spineManager, discovered.spines, async () => {+ const host = app.sideModules;+ if (!host) return null;+ const mod = await host.acquire('basis');+ return mod ? transcoderFromModule(mod as unknown as BasisWasmModule) : null;+ })+ : new Map<string, SpineAssetInfo>();// Self-gating: install physics when the project declares it OR the scene uses// it, so no runtime entry can forget to wire it. The module comes from the@@ -341,8 +349,10 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis}const cppRegistry = app.world.getCppRegistry();- if (cppRegistry) {- (module as ESEngineModule).transform_update(cppRegistry);+ // Fold the loaded transforms into world matrices once, before the first frame.+ // Native hosts run their own TransformSystem each frame instead.+ if (cppRegistry && module) {+ module.transform_update(cppRegistry);}if (spineManager && cppRegistry) {@@ -385,7 +395,8 @@ export function createRuntimeSceneConfig(export interface RuntimeInitConfig {app: App;- module: ESEngineModule;+ /** The wasm module, or null on a native host (see LoadRuntimeSceneOptions). */+ module: ESEngineModule | null;source: RuntimeAssetSource;/*** Addressable manifest for the app's Assets, enabling `Assets.loadGroup`diff --git a/sdk/src/spine/loadSpineScene.ts b/sdk/src/spine/loadSpineScene.tsindex c39214ec5..29b8b00cb 100644--- a/sdk/src/spine/loadSpineScene.ts+++ b/sdk/src/spine/loadSpineScene.ts@@ -62,7 +62,7 @@ export type TranscoderProvider = () => Promise<BasisTranscoder | null>;/** The opaque C++ registry handle SpineManager.loadEntity expects (app.world.getCppRegistry()). */type CppRegistry = Parameters<SpineManager['loadEntity']>[4];-interface SpineAssetInfo {+export interface SpineAssetInfo {version: SpineVersion | null;skelData: Uint8Array | string;atlasText: string;diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.tsindex 61a31dd2e..59fe64896 100644--- a/sdk/src/wechatRuntime.ts+++ b/sdk/src/wechatRuntime.ts@@ -16,9 +16,7 @@ import type { RuntimeAssetSource } from './runtimeAssets';import { FileSystemBackend } from './asset/Backend';import { applyBuildRuntimeConfig, type RuntimeBuildConfig } from './defaults';import { platformReadTextFile, platformInstantiateWasm, platformLoadImagePixels } from './platform';-import { toBuildPath } from './assetTypes';-import { ManifestModel, type AddressableManifest } from './asset/AddressableManifest';-import { Catalog, atlasCatalogFields, type CatalogEntry } from './asset/Catalog';+import { loadPackagedAssetIndex } from './packagedRuntime';import { createWeChatSideModuleHost, type WeChatSideModuleFactories } from './sideModules';import type { Vec2 } from './types';import type { SceneData } from './scene';@@ -93,40 +91,9 @@ export interface WeChatRuntimeConfig {}export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<void> {- const manifestText = await platformReadTextFile('asset-manifest.json');- const manifest: AddressableManifest = JSON.parse(manifestText);- // Single manifest model — same query/resolution core the SDK Assets channel- // uses, instead of a hand-rolled index walk duplicated here.- const manifestModel = ManifestModel.fromJson(manifest);- const resolvePath = (ref: string): string => manifestModel.resolvePath(ref, toBuildPath);-- // Content-addressed packs: assets whose manifest entry carries an `address`- // (the logical source path) get a catalog buildPath, so the loaders' inner- // text refs (a material's shader) map logical → staged at their fetch- // boundary — the same two-map contract the cooked web host wires.- // Atlas-packed frames additionally register their frame/uv fields, keyed by- // every ref spelling a scene can use (`@uuid:`, logical, "/"-rooted).- const catalogEntries: Record<string, CatalogEntry> = {};- for (const group of Object.values(manifest.groups)) {- for (const [uuid, asset] of Object.entries(group.assets)) {- const md = asset.metadata;- const atlasFields = md?.atlasFrame && md.atlasPageWidth && md.atlasPageHeight- ? atlasCatalogFields(- { page: md.atlasPage, frame: md.atlasFrame, pageWidth: md.atlasPageWidth, pageHeight: md.atlasPageHeight },- asset.path,- )- : null;- if (atlasFields) {- catalogEntries[`@uuid:${uuid}`] = { type: asset.type, buildPath: asset.path, ...atlasFields };- }- if (!asset.address || asset.address === asset.path) continue;- catalogEntries[asset.address] = { type: asset.type, buildPath: asset.path, ...(atlasFields ?? {}) };- catalogEntries[`/${asset.address}`] = { type: asset.type, buildPath: asset.path, ...(atlasFields ?? {}) };- }- }- const catalog = Object.keys(catalogEntries).length > 0- ? Catalog.fromJson({ version: 1, entries: catalogEntries })- : undefined;+ // The packaged-realm asset assembly, shared with the native runtime: read the+ // addressable manifest off the device, index it, build the catalog.+ const { manifest, model: manifestModel, catalog, resolvePath } = await loadPackagedAssetIndex();const canvas = wx.createCanvas();const info = wx.getSystemInfoSync();