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(export): playable reuses the shipped web wasm (no separate -t playable build)
esenginea7a2a4c596e9
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.tsindex ce7f011ca..56452fe75 100644--- a/desktop/electron/exportGame.ts+++ b/desktop/electron/exportGame.ts@@ -208,8 +208,6 @@ export async function exportGame(opts: {platform?: ExportPlatform;/** Playable host source (src/playableHost.ts). */playableHostEntry?: string;- /** SINGLE_FILE engine glue (esengine.single.js from `-t playable`) for playable ads. */- glueFile?: string;/** Desktop installer id (Project Settings → Packaging → Desktop); default com.estella.<slug>. */desktopAppId?: string;/** Desktop product/display name (Project Settings); default the project title. */@@ -252,7 +250,7 @@ export async function exportGame(opts: {scriptsEntry: opts.scriptsEntry,playableHostEntry: opts.playableHostEntry ?? path.join(path.dirname(opts.gameHostEntry), 'playableHost.ts'),sdkDir: opts.sdkDistDir,- glueFile: opts.glueFile ?? path.join(opts.wasmDir, 'esengine.single.js'),+ wasmDir: opts.wasmDir,outDir: opts.outDir,title,minify: opts.minify,diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.tsindex abca0d7e6..f3ee6131c 100644--- a/desktop/electron/exportPlayable.ts+++ b/desktop/electron/exportPlayable.ts@@ -48,7 +48,7 @@ const mimeOf = (p: string): string => MIME[path.extname(p).slice(1).toLowerCase(/** Escape `</script` so inlined content can't close the host <script> early. */const inlineSafe = (s: string): string => s.replace(/<\/script/gi, '<\\/script');-function indexHtml(title: string, glue: string, globals: string, bundle: string): string {+function indexHtml(title: string, globals: string, bundle: string): string {return `<!doctype html><html lang="en"><head>@@ -63,7 +63,6 @@ function indexHtml(title: string, glue: string, globals: string, bundle: string)</head><body><canvas id="canvas"></canvas>- <script>${inlineSafe(glue)}</script><script>${inlineSafe(globals)}</script><script>${inlineSafe(bundle)}</script></body>@@ -72,9 +71,9 @@ function indexHtml(title: string, glue: string, globals: string, bundle: string)}/**- * Export the open project as a single-file playable ad. `playableHostEntry` is the- * host source (src/playableHost.ts); `glueFile` the SINGLE_FILE engine glue- * (esengine.single.js from `-t playable`).+ * Export the open project as a single-file playable ad. Reuses the shipped WEB+ * engine runtime (esengine.js glue + esengine.wasm) inlined — no separate+ * SINGLE_FILE build. `playableHostEntry` is the host source; `wasmDir` the web wasm dir.*/export async function exportPlayable(opts: {root: string;@@ -84,7 +83,8 @@ export async function exportPlayable(opts: {/** Web SDK dist dir — `esengine` is INLINED for playable (no import map), so the* bundle aliases it here (the project root has no esengine to resolve). */sdkDir: string;- glueFile: string;+ /** Web wasm dir (esengine.js glue + esengine.wasm) — inlined into the single HTML. */+ wasmDir: string;outDir: string;title?: string;minify?: boolean;@@ -155,20 +155,31 @@ export async function exportPlayable(opts: {errors.push(...(e.errors?.map((x) => x.text) ?? [String(e.message ?? err)]));}- // 5. The SINGLE_FILE glue (global ESEngineModule, wasm embedded). Required — a- // playable can't run without it, so a miss is an ERROR (not a broken bundle).+ // 5. Engine runtime: reuse the shipped WEB build (esengine.js glue + esengine.wasm),+ // inlined — the host loads the glue via a blob module + feeds the wasm (base64)+ // through instantiateWasm. No separate single-file build needed.+ progress({ phase: 'Inlining engine' });let glue = '';- if (existsSync(opts.glueFile)) glue = await readFile(opts.glueFile, 'utf8');- else errors.push(`single-file engine runtime missing — run \`node build-tools/cli.js build -t playable\` (expected ${opts.glueFile})`);+ let wasmB64 = '';+ const gluePath = path.join(opts.wasmDir, 'esengine.js');+ const wasmPath = path.join(opts.wasmDir, 'esengine.wasm');+ if (existsSync(gluePath) && existsSync(wasmPath)) {+ glue = await readFile(gluePath, 'utf8');+ wasmB64 = (await readFile(wasmPath)).toString('base64');+ } else {+ errors.push(`engine runtime not found in ${opts.wasmDir} (need esengine.js + esengine.wasm)`);+ }// 6. Assemble the single HTML, then drop the temp cook dir.progress({ phase: 'Assembling HTML' });const globals =+ `window.__ENGINE_GLUE__=${JSON.stringify(glue)};` ++ `window.__ENGINE_WASM__=${JSON.stringify(wasmB64)};` +`window.__GAME_ASSETS__=${JSON.stringify(assets)};` +`window.__GAME_SCENES__=${JSON.stringify(scenes)};` +`window.__GAME_FIRST__=${JSON.stringify(sceneName)};`;const outFile = path.join(absOut, 'index.html');- await writeFile(outFile, indexHtml(title, glue, globals, bundle));+ await writeFile(outFile, indexHtml(title, globals, bundle));await rm(cookDir, { recursive: true, force: true });const bytes = (await stat(outFile)).size;diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex c557b8630..024f21162 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -287,9 +287,6 @@ ipcMain.handle(// `node build-tools/cli.js build -t wechat`. Absent → exportWeChat warns.const wechatWasm = [path.join(VITE_PUBLIC, 'wasm-wechat'), path.join(process.env.APP_ROOT!, '..', 'build', 'wasm', 'wechat')].find(existsSync) ?? path.join(VITE_PUBLIC, 'wasm-wechat');- // Playable's SINGLE_FILE glue lives in the wasm runtime dir (sibling of- // esengine.js), synced there by `build -t playable`. Absent → exportPlayable errors.- const glueFile = path.join(webWasm, 'esengine.single.js');const plat = manifest.packaging?.platforms;return exportGame({root,@@ -299,7 +296,6 @@ ipcMain.handle(scriptsEntry: resolveScripts(manifest).main,sdkDistDir,wasmDir: opts?.platform === 'wechat' ? wechatWasm : webWasm,- glueFile,outDir: opts?.outDir || 'dist-game',title: manifest.name,platform: opts?.platform,diff --git a/desktop/src/playableHost.ts b/desktop/src/playableHost.tsindex 079611b3a..3b2509ff4 100644--- a/desktop/src/playableHost.ts+++ b/desktop/src/playableHost.ts@@ -12,15 +12,23 @@import { createWebApp, setEditorMode, setPlayMode, initPlayableRuntime } from 'esengine';import type { ESEngineModule as EngineModule, SceneData } from 'esengine';-// The SINGLE_FILE glue exposes ESEngineModule as a global (MODULARIZE +-// EXPORT_ES6=0), wasm embedded, so no locateFile / instantiateWasm wiring here.type EngineFactory = (opts?: Record<string, unknown>) => Promise<EngineModule>;// Inlined by exportPlayable as <script> globals (kept out of the bundle so the-// large base64 asset blob isn't re-parsed as code).+// large base64 blobs aren't re-parsed as code). The glue is the WEB esengine.js+// (ESM) text; the wasm is base64-encoded esengine.wasm.+declare const __ENGINE_GLUE__: string;+declare const __ENGINE_WASM__: string;declare const __GAME_ASSETS__: Record<string, string>;declare const __GAME_SCENES__: Array<{ name: string; data: SceneData }>;declare const __GAME_FIRST__: string;+function decodeBase64(b64: string): Uint8Array {+ const raw = atob(b64);+ const bytes = new Uint8Array(raw.length);+ for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);+ return bytes;+}+async function boot(): Promise<void> {const canvas = document.getElementById('canvas') as HTMLCanvasElement;const resize = (): void => {@@ -31,11 +39,22 @@ async function boot(): Promise<void> {window.addEventListener('resize', resize);resize();- const factory = (globalThis as unknown as { ESEngineModule?: EngineFactory }).ESEngineModule;- if (typeof factory !== 'function') {- throw new Error('Engine runtime (esengine.single.js) not loaded — rebuild the playable: `node build-tools/cli.js build -t playable`.');- }- const module = await factory({ canvas });+ if (!__ENGINE_GLUE__ || !__ENGINE_WASM__) throw new Error('Engine runtime not inlined — re-export the playable.');+ // The esengine.js glue is ESM, so run it via a blob module (own scope); feed the+ // embedded wasm through instantiateWasm so nothing is fetched (single-file).+ const blobUrl = URL.createObjectURL(new Blob([__ENGINE_GLUE__], { type: 'text/javascript' }));+ const { default: createEngine } = (await import(/* @vite-ignore */ blobUrl)) as { default: EngineFactory };+ const wasmBytes = decodeBase64(__ENGINE_WASM__);+ const module = await createEngine({+ canvas,+ instantiateWasm(imports: WebAssembly.Imports, cb: (inst: WebAssembly.Instance, mod?: WebAssembly.Module) => void) {+ WebAssembly.instantiate(wasmBytes.buffer as ArrayBuffer, imports).then(+ (r) => cb(r.instance, r.module),+ (err) => console.error('[playable] wasm instantiate failed', err),+ );+ return {};+ },+ });const gl = canvas.getContext('webgl2', {alpha: false,diff --git a/desktop/tests/export-playable.test.ts b/desktop/tests/export-playable.test.tsindex a13689a29..433e30852 100644--- a/desktop/tests/export-playable.test.ts+++ b/desktop/tests/export-playable.test.ts@@ -11,8 +11,12 @@ 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 PLAYABLE_HOST = path.join(HERE, '..', 'src', 'playableHost.ts');+let root: string;let out: string;const TEX = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';@@ -30,16 +34,19 @@ beforeAll(() => {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'));- // Host + project script BOTH import 'esengine' (aliased to the stub SDK below) —- // exercises the real esengine resolution, so a missing alias fails the build.+ // Project script imports 'esengine' (aliased to the stub SDK below); the REAL+ // playableHost is bundled too — so this exercises actual esengine resolution ++ // host bundling (the old stub host hid the resolution bug).mkdirSync(path.join(root, 'src'), { recursive: true });writeFileSync(path.join(root, 'src', 'main.ts'), `import { defineComponent } from 'esengine';\ndefineComponent('SpawnMarker', {});\n`);- writeFileSync(path.join(root, '_host.ts'), `import { createWebApp } from 'esengine';\nvoid createWebApp;\nglobalThis.__HOST__ = 'playable-host-boot';\n`);- // Stub SDK dist (the bundle aliases `esengine` → <sdkDir>/index.js).+ // Stub SDK dist exporting what the real host + scripts import (bundles for real).mkdirSync(path.join(root, '_sdk'), { recursive: true });- writeFileSync(path.join(root, '_sdk', 'index.js'), `export function createWebApp(){return{};}\nexport function defineComponent(){}\n`);- // Stub SINGLE_FILE glue (real one comes from `-t playable`).- writeFileSync(path.join(root, '_glue.js'), `globalThis.ESEngineModule = function(){};/*SINGLE_FILE_GLUE*/\n`);+ writeFileSync(path.join(root, '_sdk', 'index.js'),+ `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function defineComponent(){}\n`);+ // Stub web wasm runtime (glue text + wasm) — playable inlines these, no separate build.+ mkdirSync(path.join(root, '_wasm'), { recursive: true });+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), `export default function(){}/*WEB_GLUE*/\n`);+ writeFileSync(path.join(root, '_wasm', 'esengine.wasm'), 'WASMBYTES');out = path.join(root, 'dist-playable');}, 60_000);@@ -52,8 +59,7 @@ describe('exportGame (playable)', () => {root,entryScene: 'scenes/main.esscene',gameHostEntry: 'unused-for-playable',- playableHostEntry: path.join(root, '_host.ts'),- glueFile: path.join(root, '_glue.js'),+ playableHostEntry: PLAYABLE_HOST,scriptsEntry: 'src/main.ts',sdkDistDir: path.join(root, '_sdk'),wasmDir: path.join(root, '_wasm'),@@ -71,8 +77,10 @@ describe('exportGame (playable)', () => {expect(existsSync(path.join(out, 'assets'))).toBe(false);const html = readFileSync(path.join(out, 'index.html'), 'utf8');- expect(html).toContain('SINGLE_FILE_GLUE'); // glue inlined- expect(html).toContain('playable-host-boot'); // host bundled+ expect(html).toContain('WEB_GLUE'); // web glue text inlined+ expect(html).toContain('__ENGINE_GLUE__'); // glue + wasm inlined as globals+ expect(html).toContain('__ENGINE_WASM__');+ expect(html).toContain('createObjectURL'); // real host bundled (blob loader)expect(html).toContain('SpawnMarker'); // project script bundledexpect(html).toContain(`@uuid:${TEX}`); // asset keyed by refexpect(html).toContain('data:image/png;base64,'); // asset inlined as data URL