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-ad target (single-file HTML) + fix single-file GL export
esengine0f5a41565789
diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmakeindex 831966419..e6751f4aa 100644--- a/cmake/Emscripten.cmake+++ b/cmake/Emscripten.cmake@@ -238,7 +238,9 @@ set(ES_EMSCRIPTEN_SINGLE_FILE_FLAGS"-sEXPORT_NAME='ESEngineModule'"-sFORCE_FILESYSTEM=1"-sEXPORTED_FUNCTIONS=['_malloc','_free']"- "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','HEAPF32','HEAPU8','HEAPU32','FS']"+ # 'GL' is required for the WebGL2 context binding (module.GL.registerContext),+ # same as the web/wechat SDK builds — the playable host registers its canvas GL.+ "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','HEAPF32','HEAPU8','HEAPU32','GL','FS']"-Oz-flto-Wl,--gc-sectionsdiff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.tsindex 115826eb6..9c7d01b9e 100644--- a/desktop/electron/exportGame.ts+++ b/desktop/electron/exportGame.ts@@ -26,8 +26,9 @@ import path from 'node:path';import { cookAssets } from './cookAssets';import { IMPORT_MAP_JSON, IMPORT_MAP_CSP_HASH } from './buildPlayRealm';import { exportWeChat } from './exportWeChat';+import { exportPlayable } from './exportPlayable';-export type ExportPlatform = 'web' | 'desktop' | 'wechat';+export type ExportPlatform = 'web' | 'desktop' | 'wechat' | 'playable';export interface ExportGameResult {ok: boolean;@@ -204,6 +205,10 @@ export async function exportGame(opts: {platform?: ExportPlatform;/** Built wechat SDK (dist/index.wechat.js) the WeChat bundle aliases `esengine` to. */wechatSdkEntry?: string;+ /** Playable host source (src/playableHost.ts). */+ playableHostEntry?: string;+ /** SINGLE_FILE engine glue (esengine.single.js from `-t playable`) for playable ads. */+ glueFile?: string;/** Shipping config: minify the bundles, no sourcemap. Default off (dev). */minify?: boolean;sourcemap?: boolean;@@ -225,6 +230,20 @@ export async function exportGame(opts: {});}+ // Playable ads are a single inlined HTML (SINGLE_FILE glue + base64 assets).+ if (platform === 'playable') {+ return exportPlayable({+ root: opts.root,+ entryScene: opts.entryScene,+ scriptsEntry: opts.scriptsEntry,+ playableHostEntry: opts.playableHostEntry ?? path.join(path.dirname(opts.gameHostEntry), 'playableHost.ts'),+ glueFile: opts.glueFile ?? path.join(opts.wasmDir, 'esengine.single.js'),+ outDir: opts.outDir,+ title,+ minify: opts.minify,+ });+ }+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;diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.tsnew file mode 100644index 000000000..75fd551f1--- /dev/null+++ b/desktop/electron/exportPlayable.ts@@ -0,0 +1,167 @@+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Playable-ad export (REARCH_EXPORT E3). Produces ONE self-contained+ * `index.html` (no external requests — ad networks require single-file):+ * - the SINGLE_FILE engine glue (esengine.single.js, global ESEngineModule+ * with the wasm embedded as base64) inlined as a <script>;+ * - assets as base64 data URLs + scenes inlined as <script> globals+ * (keyed by the scene's @uuid: refs — EmbeddedAssetProvider resolves them);+ * - the playable host + esengine + project scripts esbuilt to ONE IIFE.+ * Boots the SAME shipping runtime via initPlayableRuntime (play == ship).+ *+ * Correct-by-construction against initPlayableRuntime + the SINGLE_FILE glue+ * contract (no playable simulator here — runtime is validated by the user in+ * a browser / ad preview). Pure Node (esbuild + fs); IPC wiring in main.ts.+ */+import { build } from 'esbuild';+import { writeFile, mkdir, readFile, stat, rm } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import path from 'node:path';+import { cookAssets } from './cookAssets';++export interface ExportPlayableResult {+ ok: boolean;+ platform: 'playable';+ outDir: string;+ included: number;+ /** Final index.html size in bytes (for ad-network size limits). */+ bytes: number;+ warnings: string[];+ errors: string[];+}++interface CookManifest {+ entries: { uuid: string; path: string; type: string }[];+}++const MIME: Record<string, string> = {+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif',+ svg: 'image/svg+xml', ktx2: 'image/ktx2', json: 'application/json', esscene: 'application/json',+ fnt: 'text/plain', txt: 'text/plain', ogg: 'audio/ogg', mp3: 'audio/mpeg', wav: 'audio/wav',+ m4a: 'audio/mp4', aac: 'audio/aac', ttf: 'font/ttf', woff: 'font/woff', woff2: 'font/woff2',+};+const mimeOf = (p: string): string => MIME[path.extname(p).slice(1).toLowerCase()] ?? 'application/octet-stream';++/** 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 {+ return `<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <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>${inlineSafe(glue)}</script>+ <script>${inlineSafe(globals)}</script>+ <script>${inlineSafe(bundle)}</script>+ </body>+</html>+`;+}++/**+ * 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 async function exportPlayable(opts: {+ root: string;+ entryScene: string;+ scriptsEntry?: string;+ playableHostEntry: string;+ glueFile: string;+ outDir: string;+ title?: string;+ minify?: boolean;+}): Promise<ExportPlayableResult> {+ const title = opts.title ?? 'Game';+ 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 });+ const cookDir = path.join(absOut, '.playable-cook');++ // 1. Cook reachable assets to a temp dir (everything ends up inlined → removed after).+ const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: cookDir });+ warnings.push(...cook.warnings);++ // 2. Assets → base64 data URLs, keyed by the scene's @uuid: refs.+ const assets: Record<string, string> = {};+ try {+ const manifest = JSON.parse(await readFile(path.join(cookDir, 'assets.manifest.json'), 'utf8')) as CookManifest;+ for (const e of manifest.entries) {+ const buf = await readFile(path.join(cookDir, e.path));+ assets[`@uuid:${e.uuid}`] = `data:${mimeOf(e.path)};base64,${buf.toString('base64')}`;+ }+ } catch (err) {+ errors.push(`assets: ${err instanceof Error ? err.message : String(err)}`);+ }++ // 3. Scene inlined (keeps @uuid: refs — EmbeddedAssetProvider resolves them).+ const sceneName = path.basename(opts.entryScene).replace(/\.[^.]+$/, '');+ let scenes: Array<{ name: string; data: unknown }> = [];+ try {+ const data = JSON.parse(await readFile(path.join(cookDir, opts.entryScene), 'utf8'));+ scenes = [{ name: sceneName, data }];+ } catch (err) {+ errors.push(`scene: ${err instanceof Error ? err.message : String(err)}`);+ }++ // 4. Host + esengine + project scripts → ONE IIFE (esengine INLINED; no import map).+ const scriptsAbs = opts.scriptsEntry ? path.join(opts.root, opts.scriptsEntry) : null;+ const entrySrc =+ (scriptsAbs && existsSync(scriptsAbs) ? `import ${JSON.stringify(scriptsAbs)};\n` : '') ++ `import ${JSON.stringify(opts.playableHostEntry)};\n`;+ let bundle = '';+ try {+ const res = await build({+ stdin: { contents: entrySrc, resolveDir: opts.root, loader: 'js', sourcefile: 'playable-entry.js' },+ bundle: true,+ format: 'iife',+ platform: 'browser',+ target: 'es2020',+ minify: opts.minify ?? false,+ write: false,+ outfile: 'game-bundle.js',+ logLevel: 'silent',+ });+ errors.push(...res.errors.map((e) => e.text));+ bundle = res.outputFiles?.[0]?.text ?? '';+ } catch (err) {+ const e = err as { errors?: { text: string }[]; message?: string };+ errors.push(...(e.errors?.map((x) => x.text) ?? [String(e.message ?? err)]));+ }++ // 5. The SINGLE_FILE glue (global ESEngineModule, wasm embedded).+ let glue = '';+ if (existsSync(opts.glueFile)) glue = await readFile(opts.glueFile, 'utf8');+ else warnings.push(`single-file engine glue not found: ${opts.glueFile} — run \`node build-tools/cli.js build -t playable\``);++ // 6. Assemble the single HTML, then drop the temp cook dir.+ const globals =+ `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 rm(cookDir, { recursive: true, force: true });++ const bytes = (await stat(outFile)).size;+ // Ad networks cap playable size (Facebook ~2MB, Google ~5MB). A full WASM engine+ // + assets typically exceeds this — surface it rather than silently ship a reject.+ if (bytes > 2 * 1024 * 1024) {+ warnings.push(`playable is ~${(bytes / 1024 / 1024).toFixed(1)}MB — likely over ad-network limits (Facebook ~2MB, Google ~5MB).`);+ }++ return { ok: errors.length === 0, platform: 'playable', outDir: absOut, included: cook.included.length, bytes, warnings, errors };+}diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex fbfd3c09a..ac9eea20f 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -287,14 +287,23 @@ 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 (esengine.single.js); build it with+ // `node build-tools/cli.js build -t playable`. Absent → exportPlayable warns.+ const glueFile = [+ path.join(VITE_PUBLIC, 'esengine.single.js'),+ path.join(process.env.APP_ROOT!, '..', 'build', 'wasm', 'playable', 'esengine.single.js'),+ path.join(process.env.APP_ROOT!, '..', 'build-playable', 'sdk', 'esengine.single.js'),+ ].find(existsSync) ?? path.join(VITE_PUBLIC, 'esengine.single.js');return exportGame({root,entryScene,gameHostEntry: path.join(process.env.APP_ROOT!, 'src', 'gameHost.ts'),+ playableHostEntry: path.join(process.env.APP_ROOT!, 'src', 'playableHost.ts'),scriptsEntry: resolveScripts(manifest).main,sdkDistDir,wasmDir: opts?.platform === 'wechat' ? wechatWasm : webWasm,wechatSdkEntry: path.join(sdkDistDir, 'index.wechat.js'),+ glueFile,outDir: opts?.outDir || 'dist-game',title: manifest.name,platform: opts?.platform,diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex 0bc365ef7..79fa26fdc 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -41,7 +41,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' }): Promise<ExportGameResult> =>+ exportGame: (opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' | 'playable' }): Promise<ExportGameResult> =>ipcRenderer.invoke('project:exportGame', opts),/** Stage the isolated play realm (host + SDK + wasm + project bundle) under* `.esengine/play/`; returns the project-relative host page path. */diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsxindex a47c73dff..85014b400 100644--- a/desktop/src/components/BuildDialog.tsx+++ b/desktop/src/components/BuildDialog.tsx@@ -27,10 +27,10 @@ const PLATFORMS = [{ id: 'web', label: 'Web', ready: true },{ id: 'desktop', label: 'Desktop', ready: true },{ id: 'wechat', label: 'WeChat', ready: true },- { id: 'playable', label: 'Playable', ready: false },+ { id: 'playable', label: 'Playable', ready: true },] as const;-type Platform = 'web' | 'desktop' | 'wechat';+type Platform = 'web' | 'desktop' | 'wechat' | 'playable';export function BuildDialog() {const close = () => useEditorStore.getState().setBuildOpen(false);diff --git a/desktop/src/playableHost.ts b/desktop/src/playableHost.tsnew file mode 100644index 000000000..9fefc18d8--- /dev/null+++ b/desktop/src/playableHost.ts@@ -0,0 +1,67 @@+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file playableHost.ts — the exported playable ad's host (single-HTML build).+ * esbuilt to an IIFE by exportPlayable with esengine + the project scripts+ * INLINED. The engine runs from the SINGLE_FILE glue (esengine.single.js —+ * a global `ESEngineModule` factory with the wasm embedded as base64), which+ * is a sibling inline <script>; assets + scenes are inlined globals. Boots+ * the SAME shipping runtime via initPlayableRuntime (play == ship). Nothing+ * is fetched — the whole game is one self-contained .html (ad-network ready).+ */+import { createWebApp, setEditorMode, setPlayMode, initPlayableRuntime } from 'esengine';+import type { ESEngineModule as EngineModule, SceneData } from 'esengine';++// The SINGLE_FILE glue exposes this global (MODULARIZE + EXPORT_ES6=0 → IIFE),+// wasm embedded, so no locateFile / instantiateWasm wiring is needed here.+declare const ESEngineModule: (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).+declare const __GAME_ASSETS__: Record<string, string>;+declare const __GAME_SCENES__: Array<{ name: string; data: SceneData }>;+declare const __GAME_FIRST__: string;++async function boot(): Promise<void> {+ const canvas = document.getElementById('canvas') as HTMLCanvasElement;+ const resize = (): void => {+ 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 module = await ESEngineModule({ canvas });++ 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 }),+ });+ setEditorMode(false);+ setPlayMode(true);++ await initPlayableRuntime({+ app,+ module,+ canvas,+ assets: __GAME_ASSETS__,+ scenes: __GAME_SCENES__,+ firstScene: __GAME_FIRST__,+ });+}++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('[playable] boot failed', err);+});diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 83368cb9b..3308bcdf4 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -695,7 +695,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' }) {+ async exportGame(opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' | 'playable' }) {if (!this.state) return null;return window.estella.project.exportGame(opts);}diff --git a/desktop/tests/export-playable.test.ts b/desktop/tests/export-playable.test.tsnew file mode 100644index 000000000..f583ef969--- /dev/null+++ b/desktop/tests/export-playable.test.ts@@ -0,0 +1,81 @@+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Playable-ad export — structure. Asserts ONE self-contained index.html+ * inlines the SINGLE_FILE glue, the host+scripts IIFE bundle, and the+ * assets (base64 data URLs keyed by @uuid:) + scenes as globals; and that+ * the temp cook dir is cleaned (single-file output). Runtime is validated+ * by the user in a browser / ad preview (no playable simulator here).+ */+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 { exportGame } from '../electron/exportGame';++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(() => {+ root = mkdtempSync(path.join(tmpdir(), 'estella-export-playable-'));+ 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'));+ 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'));+ // Stub project script + stub host that DON'T import esengine (keeps the test+ // bundle trivial; real bundling is the same esbuild path the web/wechat tests use).+ mkdirSync(path.join(root, 'src'), { recursive: true });+ writeFileSync(path.join(root, 'src', 'main.ts'), `globalThis.__PROJ__ = 'SpawnMarker';\n`);+ writeFileSync(path.join(root, '_host.ts'), `globalThis.__HOST__ = 'playable-host-boot';\n`);+ // Stub SINGLE_FILE glue (real one comes from `-t playable`).+ writeFileSync(path.join(root, '_glue.js'), `globalThis.ESEngineModule = function(){};/*SINGLE_FILE_GLUE*/\n`);++ out = path.join(root, 'dist-playable');+}, 60_000);++afterAll(() => rmSync(root, { recursive: true, force: true }));++describe('exportGame (playable)', () => {+ it('produces one self-contained index.html with everything inlined', async () => {+ const res = await exportGame({+ root,+ entryScene: 'scenes/main.esscene',+ gameHostEntry: 'unused-for-playable',+ playableHostEntry: path.join(root, '_host.ts'),+ glueFile: path.join(root, '_glue.js'),+ scriptsEntry: 'src/main.ts',+ sdkDistDir: path.join(root, '_sdk'),+ wasmDir: path.join(root, '_wasm'),+ outDir: out,+ title: 'Playable Demo',+ platform: 'playable',+ });++ expect(res.ok).toBe(true);+ expect(res.platform).toBe('playable');++ // Single file: only index.html, temp cook dir removed, no staged assets dir.+ expect(existsSync(path.join(out, 'index.html'))).toBe(true);+ expect(existsSync(path.join(out, '.playable-cook'))).toBe(false);+ 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('SpawnMarker'); // project script bundled+ expect(html).toContain(`@uuid:${TEX}`); // asset keyed by ref+ expect(html).toContain('data:image/png;base64,'); // asset inlined as data URL+ expect(html).toContain('__GAME_FIRST__');+ expect(html).toContain('"main"'); // first scene name+ expect(html).toContain('__GAME_SCENES__');+ expect(html).toContain('<title>Playable Demo</title>');+ }, 60_000);+});