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(editor): export a project to the native app
esengineea30a512fb90
diff --git a/.gitignore b/.gitignoreindex a49498dd7..3f770a009 100644--- a/.gitignore+++ b/.gitignore@@ -9,6 +9,7 @@ dist/dist-web/dist-playable/dist-wechat/+dist-native/# MCP config (user-specific).mcp.json@@ -125,3 +126,5 @@ docs/REARCH_*.md# Generated by xcodegen from native/ios/project.ymlnative/ios/*.xcodeproj/+native/ios/Content/*+!native/ios/Content/.gitkeepdiff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.tsindex ba71c37b3..a0ec9a450 100644--- a/desktop/electron/exportGame.ts+++ b/desktop/electron/exportGame.ts@@ -19,7 +19,7 @@** Pure Node (esbuild + fs) — IPC wiring is in main.ts.*/-import type { BuildOptions } from 'esbuild';+import type { BuildOptions, Plugin } from 'esbuild';import { loadEsbuild } from './esbuildRuntime';import { writeFile, mkdir, cp, readdir } from 'node:fs/promises';import { existsSync } from 'node:fs';@@ -34,7 +34,8 @@ import type { OnExportProgress } from './exportProgress';import { ESENGINE_EXTERNAL } from './esengineResolve';import { orientationCss, orientationOverlayHtml, orientationLockScript, type ScreenOrientation } from './orientationHtml';-export type ExportPlatform = 'web' | 'desktop' | 'wechat' | 'playable';+import type { ExportPlatform } from '../src/project/format';+export type { ExportPlatform };/** A switchable scene the export ships: SceneManager name + project-relative path. */export interface ExportScene {@@ -125,6 +126,22 @@ function indexHtml(title: string, orientation?: ScreenOrientation): string {}/** A filesystem-safe slug for the app id / package name. */+/** Resolve every `esengine` import to the host's global SDK. A native build has+ * no module loader and no second copy of the SDK: the engine bundle the host+ * already evaluated installs `globalThis.ESEngine`, and the project's scripts+ * must bind to THAT instance or their components land in a rival registry. */+function esengineGlobalPlugin(): Plugin {+ return {+ name: 'esengine-global',+ setup(build) {+ build.onResolve({ filter: /^esengine(\/.*)?$/ }, (args) => ({ path: args.path, namespace: 'esengine-global' }));+ build.onLoad({ filter: /.*/, namespace: 'esengine-global' }, () => ({+ contents: 'module.exports = globalThis.ESEngine;', loader: 'js',+ }));+ },+ };+}+function slugify(title: string): string {return title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'game';}@@ -375,6 +392,10 @@ export async function exportGame(opts: {const absOut = path.isAbsolute(opts.outDir) ? opts.outDir : path.join(opts.root, opts.outDir);// Desktop nests the web build under app/; the Electron shell sits beside it.const payloadDir = platform === 'desktop' ? path.join(absOut, 'app') : absOut;+ // The native app carries the runtime in its binary (engine core + SDK bundle),+ // so its export is CONTENT: cooked assets, manifests, scenes, config — no host+ // page, no SDK/wasm tree, and project scripts as a plain script the host evals.+ const nativeContent = platform === 'native';const warnings: string[] = [];const errors: string[] = [];await mkdir(payloadDir, { recursive: true });@@ -417,15 +438,24 @@ export async function exportGame(opts: {// 2. Game host — esengine EXTERNAL (resolved by the index.html import map),// so the shipped game shares one SDK with the project bundle and runs// custom systems (same shape as the play realm).- progress({ phase: 'Bundling game host' });const { build } = await loadEsbuild();- const host = await build({ ...common, entryPoints: [opts.gameHostEntry], outfile: path.join(payloadDir, 'game.js') });- errors.push(...host.errors.map((e) => e.text));- // 3. Project bundle (defineComponent/defineSystem) → scripts.mjs, esengine external.+ if (!nativeContent) {+ progress({ phase: 'Bundling game host' });+ const host = await build({ ...common, entryPoints: [opts.gameHostEntry], outfile: path.join(payloadDir, 'game.js') });+ errors.push(...host.errors.map((e) => e.text));+ }+ // 3. Project bundle (defineComponent/defineSystem). ESM + esengine external on+ // the web (the import map resolves it); on native an IIFE the host evals,+ // where `esengine` is the globalThis.ESEngine the host installed.const scriptsAbs = opts.scriptsEntry ? path.join(opts.root, opts.scriptsEntry) : null;if (scriptsAbs && existsSync(scriptsAbs)) {progress({ phase: 'Bundling project scripts' });- const proj = await build({ ...common, entryPoints: [scriptsAbs], outfile: path.join(payloadDir, 'scripts.mjs') });+ const proj = nativeContent+ ? await build({+ ...common, format: 'iife', external: [], plugins: [esengineGlobalPlugin()],+ entryPoints: [scriptsAbs], outfile: path.join(payloadDir, 'scripts.js'),+ })+ : await build({ ...common, entryPoints: [scriptsAbs], outfile: path.join(payloadDir, 'scripts.mjs') });errors.push(...proj.errors.map((e) => e.text));}} catch (err) {@@ -437,16 +467,20 @@ export async function exportGame(opts: {// 4. SDK (import-map target) + wasm runtime. The import map and the game// host reference both unconditionally — a missing tree is not a degraded// export but a package that cannot boot, so it fails the export.- progress({ phase: 'Copying SDK + runtime' });- if (existsSync(opts.sdkDistDir)) await cp(opts.sdkDistDir, path.join(payloadDir, 'sdk'), { recursive: true });- else errors.push(`sdk dist not found: ${opts.sdkDistDir}`);- if (existsSync(opts.wasmDir)) await cp(opts.wasmDir, path.join(payloadDir, 'wasm'), { recursive: true });- else errors.push(`wasm runtime dir not found: ${opts.wasmDir}`);+ if (!nativeContent) {+ progress({ phase: 'Copying SDK + runtime' });+ if (existsSync(opts.sdkDistDir)) await cp(opts.sdkDistDir, path.join(payloadDir, 'sdk'), { recursive: true });+ else errors.push(`sdk dist not found: ${opts.sdkDistDir}`);+ if (existsSync(opts.wasmDir)) await cp(opts.wasmDir, path.join(payloadDir, 'wasm'), { recursive: true });+ else errors.push(`wasm runtime dir not found: ${opts.wasmDir}`);+ }// 5. Host page + entry-scene config. Web pins orientation (rotate-to-fit overlay);// desktop omits it — the Electron shell sizes its own window to the orientation.progress({ phase: 'Writing host page' });- await writeFile(path.join(payloadDir, 'index.html'), indexHtml(title, platform === 'web' ? orientation : undefined));+ if (!nativeContent) {+ await writeFile(path.join(payloadDir, 'index.html'), indexHtml(title, platform === 'web' ? orientation : undefined));+ }await writeFile(path.join(payloadDir, 'game.config.json'),JSON.stringify(diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex bdbb2deb2..71d32ab98 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -39,7 +39,7 @@ import { ensureProjectShaderTwins } from './shaderTwins';import { installCrashCapture, logsDir } from './resilience';import { mcpMode, startMcpEndpoint } from './mcpEndpoint';import { checkForUpdate } from './updateCheck';-import { resolveLayout, resolveScripts, resolveOrientation, resolveScreenFit } from '../src/project/format';+import { resolveLayout, resolveScripts, resolveOrientation, resolveScreenFit, type ExportPlatform } from '../src/project/format';import type { WorkspaceState } from '../src/project/format';// Enable WebGPU in the renderer so the viewport's WebGPU backend (Settings →@@ -758,7 +758,7 @@ ipcMain.handle('project:cookAssets', async (_e, outDir?: string) => {// Export a runnable web build (play == ship): cook + game host + wasm + index.html.ipcMain.handle('project:exportGame',- async (e, opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' | 'playable'; compressTextures?: boolean; compressAudio?: boolean; atlasTextures?: boolean }) => {+ async (e, opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: ExportPlatform; compressTextures?: boolean; compressAudio?: boolean; atlasTextures?: boolean }) => {const root = requireRoot();const manifest = await readManifest(root);const entryScene = manifest.defaultScene;diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex 5e12432bc..fd149ea4e 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { contextBridge, ipcRenderer, webUtils } from 'electron';-import type { OpenedProject, WorkspaceState, DirEntry, RecentEntry, TemplateEntry } from '../src/project/format';+import type { OpenedProject, WorkspaceState, DirEntry, RecentEntry, TemplateEntry, ExportPlatform } from '../src/project/format';import type { BuildScriptsResult } from './buildScripts';import type { ExtractSchemasResult } from './extractSchemas';import type { ScanAssetsResult, AssetIndex, IncrementalScanResult } from './assetDb';@@ -94,7 +94,7 @@ const api = {/** Cook reachable assets for shipping → staged files + runtime manifest in `outDir`. */cookAssets: (outDir?: string): Promise<CookResult> => ipcRenderer.invoke('project:cookAssets', outDir),/** Export a runnable web build (play==ship) → self-contained `outDir` (default dist-game/). */- exportGame: (opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' | 'playable'; compressTextures?: boolean; compressAudio?: boolean; atlasTextures?: boolean }): Promise<ExportGameResult> =>+ exportGame: (opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: ExportPlatform; compressTextures?: boolean; compressAudio?: boolean; atlasTextures?: boolean }): Promise<ExportGameResult> =>ipcRenderer.invoke('project:exportGame', opts),/** Serve a built export dir (web / playable) over loopback http and open it in the* default browser — the build's real deployment surface, so no file:// origindiff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsxindex fe6aa25f5..84c33c35c 100644--- a/desktop/src/components/BuildDialog.tsx+++ b/desktop/src/components/BuildDialog.tsx@@ -12,13 +12,14 @@* per-asset optimization. Texture compression / Max Size / audio bitrate are* authored per asset in the Inspector's Import Settings; the build only* chooses whether to HONOR those settings (`assetCompression: 'auto'`) or- * skip them for fast iteration (`'skip'`). All four targets are live.+ * skip them for fast iteration (`'skip'`). Every target is live.*/import { useState, useSyncExternalStore, type ReactNode } from 'react';import {Loader2, FolderOpen, CheckCircle2, AlertCircle, Boxes, Info, Copy, ExternalLink, Play,- Globe, Monitor, MessageSquare, ChevronRight,+ Globe, Monitor, MessageSquare, ChevronRight, Smartphone,} from 'lucide-react';+import type { ExportPlatform } from '@/project/format';import { Modal } from '@/components/Modal';import { Segmented } from '@/components/Segmented';import { Button } from '@/components/Button';@@ -28,7 +29,7 @@ import { t } from '@/i18n';type Phase = 'idle' | 'running' | 'done' | 'error';type Config = 'development' | 'shipping';-type Platform = 'web' | 'desktop' | 'wechat' | 'playable';+type Platform = ExportPlatform;type AssetCompression = 'auto' | 'skip';interface Result {@@ -89,6 +90,13 @@ const PLATFORMS: PlatformDef[] = [prereq: t('build.prereq.playable'),next: () => t('build.next.playable'),},+ {+ id: 'native', label: t('build.plat.native'), ready: true, icon: <Smartphone size={17} />,+ blurb: t('build.blurb.native'),+ defaultOut: 'dist-native', sourceMaps: false,+ prereq: t('build.prereq.native'),+ next: (o) => t('build.next.native', { out: o }),+ },];const mb = (bytes: number): string => `${(bytes / 1024 / 1024).toFixed(1)} MB`;diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.tsindex 72b7e9fff..51a174700 100644--- a/desktop/src/i18n/messages/project.ts+++ b/desktop/src/i18n/messages/project.ts@@ -13,6 +13,7 @@ export const projectMessages = defineMessages({'build.plat.desktop': { en: 'Desktop', zh: '桌面' },'build.plat.wechat': { en: 'WeChat', zh: '微信小游戏' },'build.plat.playable': { en: 'Playable', zh: 'Playable' },+ 'build.plat.native': { en: 'Mobile', zh: '移动原生' },'build.comingSoon': { en: 'Coming soon', zh: '即将推出' },'build.soon': { en: 'soon', zh: '即将' },'build.blurb.web': {@@ -28,6 +29,10 @@ export const projectMessages = defineMessages({en: 'Single-file HTML playable ad — everything inlined, no requests.',zh: '单文件 HTML 试玩广告——所有内容内联,无网络请求。',},+ 'build.blurb.native': {+ en: 'Content for the native iOS / Android app — a real app, not a WebView.',+ zh: '原生 iOS / Android 应用的内容——真正的原生应用,而非 WebView。',+ },'build.prereq.wechat': {en: 'Requires the WeChat runtime — run: node build-tools/cli.js build -t wechat',zh: '需要微信运行时——请运行:node build-tools/cli.js build -t wechat',@@ -36,6 +41,10 @@ export const projectMessages = defineMessages({en: 'Requires the single-file runtime — run: node build-tools/cli.js build -t playable',zh: '需要单文件运行时——请运行:node build-tools/cli.js build -t playable',},+ 'build.prereq.native': {+ en: 'Needs the native host — see native/README.md (embedded Dawn + QuickJS).',+ zh: '需要原生宿主——见 native/README.md(内嵌 Dawn + QuickJS)。',+ },'build.next.web': {en: "Preview over http below, or upload {out}/ to any static host. (A web build needs an http origin — opening index.html directly won't stream the wasm.)",zh: '在下方通过 http 预览,或将 {out}/ 上传到任意静态托管。(网页构建需要 http 源——直接打开 index.html 无法流式加载 wasm。)',@@ -53,6 +62,11 @@ export const projectMessages = defineMessages({zh: '在下方通过 http 预览(其真实运行环境是广告网络的 iframe)。注意:完整引擎通常会超出广告网络的体积限制。',},+ 'build.next.native': {+ en: 'Package it into the app: node build-tools/cli.js native --package --content {out} (Android), or point the Xcode project at {out} (iOS).',+ zh: '将其打进应用:node build-tools/cli.js native --package --content {out}(Android),或让 Xcode 工程指向 {out}(iOS)。',+ },+// — Options —'build.configuration': { en: 'Configuration', zh: '配置' },'build.development': { en: 'Development', zh: '开发' },diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex f17371c00..e7ff9cd49 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -31,7 +31,7 @@ import { t } from '@/i18n';import { assetTypeOf } from '@/project/assetMeta';import { ASSET_SLOTS, metaTypeToSlot } from '@/project/assetSlots';import type { AssetType } from '@/types';-import { resolveLayout, orientationFromDesignResolution, resolveOrientation, cameraScaleModeValue, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type WorkspaceState, type DesignResolution, type ScreenOrientation, type CameraScaleMode } from './format';+import { resolveLayout, orientationFromDesignResolution, resolveOrientation, cameraScaleModeValue, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type WorkspaceState, type DesignResolution, type ScreenOrientation, type CameraScaleMode, type ExportPlatform } from './format';import { useEditorMode } from '@/store/editorModeStore';import { PlayRealms } from '@/engine/PlayRealm';import { PlayInspect } from '@/engine/PlayInspect';@@ -2338,7 +2338,7 @@ class ProjectStoreImpl {* (default `dist-game/`). Returns the bridge result so the Build dialog can* render status/log; null if no project is open.*/- async exportGame(opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' | 'playable'; compressTextures?: boolean; compressAudio?: boolean; atlasTextures?: boolean }) {+ async exportGame(opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: ExportPlatform; compressTextures?: boolean; compressAudio?: boolean; atlasTextures?: boolean }) {if (!this.state) return null;return window.estella.project.exportGame(opts);}diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.tsindex 17972ea6b..6520b07e6 100644--- a/desktop/src/project/format.ts+++ b/desktop/src/project/format.ts@@ -123,11 +123,15 @@ export type CameraScaleMode = 'none' | 'fixed-width' | 'fixed-height' | 'expand'export interface WeChatPackaging { appid?: string; }export interface DesktopPackaging { appId?: string; productName?: string; }+/** Every export target. The single source: the electron export pipeline, the IPC+ * surface and the build dialog all name their platforms from here. */+export type ExportPlatform = 'web' | 'desktop' | 'wechat' | 'playable' | 'native';+/** Persisted Package Project settings (UE's ProjectPackagingSettings analog) —* committed with the project so the build dialog restores the last target/config* and the export reads per-platform config. */export interface ProjectPackaging {- platform?: 'web' | 'desktop' | 'wechat' | 'playable';+ platform?: ExportPlatform;config?: 'development' | 'shipping';sourceMaps?: boolean;openFolder?: boolean;@@ -157,7 +161,7 @@ export interface ProjectPackaging {* always ships regardless. */excludeScenes?: string[];/** Per-platform output-dir overrides (else the per-platform default). */- outDir?: Partial<Record<'web' | 'desktop' | 'wechat' | 'playable', string>>;+ outDir?: Partial<Record<ExportPlatform, string>>;/** Per-platform packaging config (appid, app id, …). */platforms?: { wechat?: WeChatPackaging; desktop?: DesktopPackaging };}diff --git a/desktop/tests/export-native.test.ts b/desktop/tests/export-native.test.tsnew file mode 100644index 000000000..ac6d17cb1--- /dev/null+++ b/desktop/tests/export-native.test.ts@@ -0,0 +1,88 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Native export (Stage C). The native app carries the runtime in its+ * binary — engine core, SDK bundle and game runtime all ship inside the+ * host — so its export is CONTENT: cooked assets, both manifests, the+ * scenes and game.config.json. Asserts exactly that, and that the web-only+ * payload (host page, SDK/wasm trees, an ESM host bundle) stays out.+ */+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, copyFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { exportGame } from '../electron/exportGame';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const GAME_HOST = path.join(HERE, '..', 'src', 'gameHost.ts');++let root: string;+let out: string;+const TEX = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';+const SCN = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';+const meta = (uuid: string, type: string) => JSON.stringify({ uuid, version: '2.0', type, importer: {} });++beforeAll(async () => {+ root = mkdtempSync(path.join(tmpdir(), 'estella-export-native-'));+ mkdirSync(path.join(root, 'assets'), { recursive: true });+ copyFileSync(path.resolve(HERE, '..', '..', 'examples', 'hello-world', 'assets', 'textures', 'logo.png'),+ path.join(root, 'assets', 'hero.png'));+ writeFileSync(path.join(root, 'assets', 'hero.png.meta'), meta(TEX, 'texture'));+ mkdirSync(path.join(root, 'scenes'), { recursive: true });+ writeFileSync(+ path.join(root, 'scenes', 'main.esscene'),+ JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }),+ );+ writeFileSync(path.join(root, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));+ mkdirSync(path.join(root, 'src'), { recursive: true });+ writeFileSync(path.join(root, 'src', 'main.ts'), `import { defineComponent } from 'esengine';\ndefineComponent('SpawnMarker', { rate: 1 });\n`);+ mkdirSync(path.join(root, '_sdk'), { recursive: true });+ writeFileSync(path.join(root, '_sdk', 'index.js'), 'export const x = 1;');+ mkdirSync(path.join(root, '_wasm'), { recursive: true });+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'export default () => {};');++ out = path.join(root, 'dist-native');+}, 60_000);++afterAll(() => rmSync(root, { recursive: true, force: true }));++describe('exportGame (native)', () => {+ it('ships content only — cooked assets, manifests, scene, config', async () => {+ const res = await exportGame({+ root, entryScene: 'scenes/main.esscene', gameHostEntry: GAME_HOST, scriptsEntry: 'src/main.ts',+ sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'), outDir: out,+ platform: 'native', title: 'NativeGame',+ });+ expect(res.errors).toEqual([]);+ expect(res.ok).toBe(true);++ // What the native runtime reads off the device.+ expect(existsSync(path.join(out, 'game.config.json'))).toBe(true);+ expect(existsSync(path.join(out, 'assets.manifest.json'))).toBe(true);+ expect(existsSync(path.join(out, 'asset-manifest.json'))).toBe(true);+ expect(JSON.parse(readFileSync(path.join(out, 'game.config.json'), 'utf8')).entryScene)+ .toBe('scenes/main.esscene');++ // The runtime lives in the app binary — none of the web payload ships.+ expect(existsSync(path.join(out, 'index.html'))).toBe(false);+ expect(existsSync(path.join(out, 'game.js'))).toBe(false);+ expect(existsSync(path.join(out, 'sdk'))).toBe(false);+ expect(existsSync(path.join(out, 'wasm'))).toBe(false);+ }, 90_000);++ it("binds the project's scripts to the host's SDK instance, not a second copy", async () => {+ // QuickJS has no module loader: the scripts bundle is an IIFE, and its+ // `esengine` imports must resolve to the globalThis.ESEngine the host already+ // installed — a bundled-in second SDK would register components into a rival+ // registry the engine never sees.+ const scripts = path.join(out, 'scripts.js');+ expect(existsSync(scripts)).toBe(true);+ expect(existsSync(path.join(out, 'scripts.mjs'))).toBe(false);+ const js = readFileSync(scripts, 'utf8');+ expect(js).toContain('globalThis.ESEngine');+ expect(js).toContain('SpawnMarker');+ // An IIFE, not ESM — nothing for the host to import.+ expect(js).not.toMatch(/^\s*(import|export)\s/m);+ }, 90_000);+});