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 runnable web build — play == ship (S)
esenginebc93b421fab2
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.tsnew file mode 100644index 000000000..c87995a85--- /dev/null+++ b/desktop/electron/exportGame.ts@@ -0,0 +1,111 @@+/**+ * @file Game export (REARCH_EDITOR_REALM Phase S — play == ship). Produces a+ * self-contained, static-servable web build of the open project:+ * - cookAssets → reachable assets (paths preserved) + assets.manifest.json+ * - esbuild the game host (gameHost.ts, esengine INLINED) → game.js+ * - copy the /wasm runtime+ * - emit index.html + game.config.json (the entry scene)+ * The host boots the SAME runtime the editor's play realm uses+ * (initPlayRealmRuntime), so the shipped game is what was played.+ *+ * Pure Node (esbuild + fs) — IPC wiring is in main.ts.+ */+import { build } from 'esbuild';+import { writeFile, mkdir, cp } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import path from 'node:path';+import { cookAssets } from './cookAssets';++export interface ExportGameResult {+ ok: boolean;+ outDir: string;+ /** Count of assets included (reachable from the entry scene). */+ included: number;+ warnings: string[];+ errors: string[];+}++function indexHtml(title: string): string {+ return `<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta+ http-equiv="Content-Security-Policy"+ content="default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self' data: blob:; worker-src 'self' blob:;"+ />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />+ <title>${title}</title>+ <style>+ * { margin: 0; padding: 0; box-sizing: border-box; }+ html, body { width: 100%; height: 100%; overflow: hidden; background: #0e121b; }+ #canvas { display: block; width: 100%; height: 100%; touch-action: none; }+ </style>+ </head>+ <body>+ <canvas id="canvas"></canvas>+ <script type="module" src="./game.js"></script>+ </body>+</html>+`;+}++/**+ * Export the open project to a runnable web build in `outDir`. `entryScene` is+ * the project-relative scene to boot; `gameHostEntry` the gameHost.ts source;+ * `wasmDir` the engine runtime to copy.+ */+export async function exportGame(opts: {+ root: string;+ entryScene: string;+ gameHostEntry: string;+ wasmDir: string;+ outDir: string;+ title?: string;+}): Promise<ExportGameResult> {+ const absOut = path.isAbsolute(opts.outDir) ? opts.outDir : path.join(opts.root, opts.outDir);+ const warnings: string[] = [];+ const errors: string[] = [];+ await mkdir(absOut, { recursive: true });++ // 1. Cook reachable assets + manifest (the entry scene file is staged too).+ const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: absOut });+ warnings.push(...cook.warnings);++ // 2. Bundle the game host (esengine inlined → self-contained game.js).+ try {+ const res = await build({+ entryPoints: [opts.gameHostEntry],+ bundle: true,+ format: 'esm',+ platform: 'browser',+ target: 'es2020',+ outfile: path.join(absOut, 'game.js'),+ sourcemap: false,+ write: true,+ logLevel: 'silent',+ });+ errors.push(...res.errors.map((e) => e.text));+ warnings.push(...res.warnings.map((w) => w.text));+ } catch (err) {+ const e = err as { errors?: { text: string }[]; message?: string };+ errors.push(...(e.errors?.map((x) => x.text) ?? [String(e.message ?? err)]));+ return { ok: false, outDir: absOut, included: cook.included.length, warnings, errors };+ }++ // 3. Copy the wasm runtime (glue + binary + side modules).+ if (existsSync(opts.wasmDir)) {+ await cp(opts.wasmDir, path.join(absOut, 'wasm'), { recursive: true });+ } else {+ warnings.push(`wasm runtime dir not found: ${opts.wasmDir}`);+ }++ // 4. Host page + entry-scene config.+ await writeFile(path.join(absOut, 'index.html'), indexHtml(opts.title ?? 'Game'));+ await writeFile(+ path.join(absOut, 'game.config.json'),+ JSON.stringify({ entryScene: opts.entryScene }, null, 2) + '\n',+ );++ return { ok: errors.length === 0, outDir: absOut, included: cook.included.length, warnings, errors };+}diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 5d183fd10..1713c56f6 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -24,6 +24,7 @@ import { scanAssetDatabase } from './assetDb';import { cookAssets } from './cookAssets';import { startProjectWatch, stopProjectWatch } from './projectWatcher';import { importAssets, IMPORT_EXTENSIONS } from './importAssets';+import { exportGame } from './exportGame';import { resolveScripts } from '../src/project/format';import type { WorkspaceState } from '../src/project/format';@@ -255,6 +256,24 @@ ipcMain.handle('project:cookAssets', async (_e, outDir?: string) => {return cookAssets(root, { entryScenes: entry ? [entry] : [], outDir: outDir ?? 'build' });});+// Export a runnable web build (play == ship): cook + game host + wasm + index.html.+ipcMain.handle('project:exportGame', async (_e, outDir?: string) => {+ const root = requireRoot();+ const manifest = await readManifest(root);+ const entryScene = manifest.defaultScene;+ if (!entryScene) throw new Error('project has no defaultScene to export');+ const publicWasm = path.join(VITE_PUBLIC, 'wasm');+ const wasmDir = existsSync(publicWasm) ? publicWasm : path.join(RENDERER_DIST, 'wasm');+ return exportGame({+ root,+ entryScene,+ gameHostEntry: path.join(process.env.APP_ROOT!, 'src', 'gameHost.ts'),+ wasmDir,+ outDir: outDir ?? 'dist-game',+ title: manifest.name,+ });+});+ipcMain.handle('recents:list', () => listRecents());ipcMain.handle('recents:add', (_e, root: string, name: string) => addRecent(root, name));diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex 54aa6f64c..a7736a6a8 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -4,6 +4,7 @@ import type { BuildScriptsResult } from './buildScripts';import type { ExtractSchemasResult } from './extractSchemas';import type { ScanAssetsResult } from './assetDb';import type { CookResult } from './cookAssets';+import type { ExportGameResult } from './exportGame';// The privileged bridge the renderer is allowed to touch. Keep this surface small// and explicit — anything the editor needs from the OS or Node goes through here.@@ -36,6 +37,8 @@ const api = {scanAssets: (): Promise<ScanAssetsResult> => ipcRenderer.invoke('project:scanAssets'),/** 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: (outDir?: string): Promise<ExportGameResult> => ipcRenderer.invoke('project:exportGame', outDir),/** Show a file picker and import the chosen files into `destDir` (writes .meta);* null if cancelled. */importAssets: (destDir: string): Promise<{ imported: string[]; skipped: string[] } | null> =>diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex 26cab3426..158f5b2c6 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -44,6 +44,13 @@ commands.register({isEnabled: () => !!ProjectStore.getSnapshot(),run: () => void ProjectStore.saveAsViaDialog(),});+commands.register({+ id: 'project.export',+ label: 'Export Game…',+ category: 'File',+ isEnabled: () => !!ProjectStore.getSnapshot(),+ run: () => void ProjectStore.exportGame(),+});commands.register({id: 'project.close',label: 'Close Project',diff --git a/desktop/src/gameHost.ts b/desktop/src/gameHost.tsnew file mode 100644index 000000000..c100893f5--- /dev/null+++ b/desktop/src/gameHost.ts@@ -0,0 +1,74 @@+/**+ * @file gameHost.ts — the exported game's runtime host (REARCH_EDITOR_REALM+ * Phase S). Bundled by exportGame (esbuild, esengine inlined) into a+ * self-contained game.js. Boots the SAME shipping runtime the editor's+ * play realm uses (createWebApp → initPlayRealmRuntime), but loads the+ * scene + asset manifest from the COOKED files next to index.html — so the+ * shipped game is what the editor played (play == ship).+ *+ * Builtin scenes run as-is; project custom-script bundles are a follow-up+ * (shared with the play realm's import-map work).+ */+import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime } from 'esengine';+import type { ESEngineModule, SceneData } from 'esengine';++interface GameConfig {+ entryScene: string;+}+interface CookedManifest {+ entries: { uuid: string; path: string; type: string }[];+}++async function boot(): Promise<void> {+ const canvas = document.getElementById('canvas') as HTMLCanvasElement;+ const resize = () => {+ const dpr = window.devicePixelRatio || 1;+ canvas.width = Math.max(1, Math.floor(window.innerWidth * dpr));+ canvas.height = Math.max(1, Math.floor(window.innerHeight * dpr));+ };+ window.addEventListener('resize', resize);+ resize();++ const cfg = (await (await fetch('./game.config.json')).json()) as GameConfig;+ const manifest = (await (await fetch('./assets.manifest.json')).json()) as CookedManifest;+ const sceneData = (await (await fetch(`./${cfg.entryScene}`)).json()) as SceneData;+ const assetManifest: Record<string, string> = {};+ for (const e of manifest.entries) assetManifest[e.uuid.toLowerCase()] = `./${e.path}`;++ const wasmBase = `${location.origin}/wasm`;+ const { default: createModule } = (await import(/* @vite-ignore */ `${wasmBase}/esengine.js`)) as {+ default: (options?: Record<string, unknown>) => Promise<ESEngineModule>;+ };+ const module = await createModule({+ canvas,+ locateFile: (p: string) => `${wasmBase}/${p}`,+ print: (t: string) => console.log(t),+ printErr: (t: string) => console.error(t),+ });++ const gl = canvas.getContext('webgl2', {+ alpha: false,+ antialias: true,+ depth: true,+ stencil: true,+ premultipliedAlpha: false,+ }) as WebGL2RenderingContext | null;+ if (!gl) throw new Error('WebGL2 is not available.');+ const glHandle = module.GL.registerContext(gl, { majorVersion: 2, minorVersion: 0, enableExtensionsByDefault: true });++ const app = createWebApp(module, {+ glContextHandle: glHandle,+ getViewportSize: () => ({ width: canvas.width, height: canvas.height }),+ wasmBaseUrl: wasmBase,+ });+ setEditorMode(false);+ setPlayMode(true);+ await initPlayRealmRuntime({ app, module, canvas, sceneData, assetManifest });+}++boot().catch((err) => {+ const message = err instanceof Error ? err.message : String(err);+ if (err === 'unwind' || message.includes('unwind')) return; // emscripten loop took over — success+ console.error('[game] boot failed', err);+ document.body.innerHTML = `<pre style="color:#f87171;padding:20px;font:13px monospace">${message}</pre>`;+});diff --git a/desktop/src/layout/MenuBar.tsx b/desktop/src/layout/MenuBar.tsxindex eb0178938..b54564de9 100644--- a/desktop/src/layout/MenuBar.tsx+++ b/desktop/src/layout/MenuBar.tsx@@ -78,6 +78,8 @@ export function MenuBar() {cmdItem('project.save'),cmdItem('project.saveAs'),{ sep: true },+ cmdItem('project.export'),+ { sep: true },cmdItem('project.close'),],},diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 7eaeb9158..e2032cc78 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -479,6 +479,26 @@ class ProjectStoreImpl {Toasts.push(`Saved ${relPath.split('/').pop()}`, 'success');}+ /**+ * Export a runnable web build of the project (play == ship): cook reachable+ * assets + bundle the game host + copy the runtime → a self-contained dir+ * (default `dist-game/`). Toasts the outcome.+ */+ async exportGame(): Promise<void> {+ if (!this.state) return;+ Toasts.push('Exporting game…', 'info', 2000);+ try {+ const res = await window.estella.project.exportGame();+ if (res.ok) {+ Toasts.push(`Exported ${res.included} assets → ${res.outDir.split('/').pop()}/`, 'success');+ } else {+ Toasts.push(`Export failed: ${res.errors[0] ?? 'unknown error'}`, 'error');+ }+ } catch (err) {+ Toasts.push(`Export failed: ${err instanceof Error ? err.message : String(err)}`, 'error');+ }+ }+/** Prompt for a destination (Save-As) and write there. Returns the path or null. */async saveAsViaDialog(): Promise<string | null> {const st = this.state;diff --git a/desktop/tests/export-game.test.ts b/desktop/tests/export-game.test.tsnew file mode 100644index 000000000..1ca4cc5b6--- /dev/null+++ b/desktop/tests/export-game.test.ts@@ -0,0 +1,83 @@+/**+ * @file Game export orchestration (REARCH_EDITOR_REALM Phase S). Asserts+ * exportGame produces a self-contained web build: cooked assets + manifest,+ * the esbuild'd game host (esengine inlined, not external), the copied wasm+ * runtime, index.html, and the entry-scene config. (The host RENDERING is+ * proven separately by play:verify — gameHost reuses initPlayRealmRuntime.)+ */+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } 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-'));+ // A texture asset + sidecar.+ mkdirSync(path.join(root, 'assets'), { recursive: true });+ writeFileSync(path.join(root, 'assets', 'hero.png'), 'PNGDATA');+ writeFileSync(path.join(root, 'assets', 'hero.png.meta'), meta(TEX, 'texture'));+ // A scene that references the texture by @uuid: + its sidecar.+ 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'));+ // A stand-in wasm runtime dir to copy.+ mkdirSync(path.join(root, '_wasm'), { recursive: true });+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'export default () => {};');+ writeFileSync(path.join(root, '_wasm', 'esengine.wasm'), 'wasmbytes');++ out = path.join(root, 'dist-game');+}, 60_000);++afterAll(() => rmSync(root, { recursive: true, force: true }));++describe('exportGame', () => {+ it('produces a self-contained web build (cook + host + wasm + html)', async () => {+ const res = await exportGame({+ root,+ entryScene: 'scenes/main.esscene',+ gameHostEntry: GAME_HOST,+ wasmDir: path.join(root, '_wasm'),+ outDir: out,+ title: 'My Game',+ });++ expect(res.ok).toBe(true);+ expect(res.errors).toEqual([]);+ // Reachability pulled the scene + its referenced texture into the build.+ expect(res.included).toBe(2);++ const has = (p: string) => existsSync(path.join(out, p));+ expect(has('index.html')).toBe(true);+ expect(has('game.js')).toBe(true);+ expect(has('game.config.json')).toBe(true);+ expect(has('assets.manifest.json')).toBe(true);+ expect(has('scenes/main.esscene')).toBe(true);+ expect(has('assets/hero.png')).toBe(true);+ expect(has('wasm/esengine.js')).toBe(true);+ expect(has('wasm/esengine.wasm')).toBe(true);++ // The host is real + esengine-INLINED (self-contained): an external build is+ // ~1-2 KB with a bare `import "esengine"`; the inlined SDK is hundreds of KB.+ const gameJs = readFileSync(path.join(out, 'game.js'), 'utf8');+ expect(gameJs.length).toBeGreaterThan(100_000);+ expect(gameJs).not.toMatch(/^\s*import\s*[^;]*from\s*["']esengine["']/m);++ // index.html loads the host; config points at the entry scene.+ expect(readFileSync(path.join(out, 'index.html'), 'utf8')).toContain('./game.js');+ expect(JSON.parse(readFileSync(path.join(out, 'game.config.json'), 'utf8')).entryScene).toBe('scenes/main.esscene');+ }, 60_000);+});