Skip to content

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.

feat(editor): isolated play-realm host page (R1)

esengine6fc7b455bb8c
diff --git a/desktop/package.json b/desktop/package.json
index c8df125ad..f8fc91269 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -14,6 +14,7 @@
"test:watch": "vitest",
"verify:render": "vite build && electron scripts/headless-verify.mjs",
"verify:smoke": "vite build && electron scripts/headless-smoke.mjs",
+ "play:verify": "vite build && electron scripts/play-realm-verify.mjs",
"mcp": "electron electron/mcp/server.mjs",
"mcp:smoke": "vite build && node electron/mcp/smoke.mjs"
},
diff --git a/desktop/play.html b/desktop/play.html
new file mode 100644
index 000000000..93601b57d
--- /dev/null
+++ b/desktop/play.html
@@ -0,0 +1,23 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <!-- Same CSP as the editor shell: 'unsafe-eval' for the emscripten glue, and
+ estella: in img/connect so the realm can fetch project assets. -->
+ <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: estella:; font-src 'self' data:; connect-src 'self' ws: estella:; worker-src 'self' blob:;"
+ />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
+ <title>Estella Play</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; outline: none; }
+ </style>
+ </head>
+ <body>
+ <canvas id="canvas"></canvas>
+ <script type="module" src="/src/play.ts"></script>
+ </body>
+</html>
diff --git a/desktop/scripts/play-realm-verify.mjs b/desktop/scripts/play-realm-verify.mjs
new file mode 100644
index 000000000..8dcfcdcd6
--- /dev/null
+++ b/desktop/scripts/play-realm-verify.mjs
@@ -0,0 +1,104 @@
+/**
+ * @file Play-realm verification runner (REARCH_EDITOR_REALM Phase R1).
+ *
+ * Proves the isolated play realm boots the SHIPPING runtime against a posted
+ * scene snapshot + a fetched asset manifest — the play==ship path, in isolation
+ * from the editor. Static-serves dist/ over loopback http, opens a show:false
+ * window on play.html, posts an `estella:play:init` with a real scene snapshot +
+ * uuid→url manifest, and waits for the realm's `estella:play:ready` handshake
+ * (reaching ready means createWebApp + initRuntime + asset fetch + app.run all
+ * succeeded). A capturePage spread check is reported as bonus evidence.
+ *
+ * Runs by Electron (real WebGL2). `pnpm --filter ./desktop play:verify`.
+ */
+import { app, BrowserWindow } from 'electron';
+import http from 'node:http';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const DIST = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist');
+const SCENE = process.env.ESTELLA_VERIFY_SCENE ?? '/scenes/sprite-rendering.esscene';
+const MANIFEST = process.env.ESTELLA_VERIFY_MANIFEST ?? '/scenes/sprite-rendering.textures.json';
+const W = 640;
+const H = 480;
+
+app.commandLine.appendSwitch('enable-unsafe-swiftshader');
+process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';
+
+const MIME = {
+ '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
+ '.css': 'text/css', '.json': 'application/json', '.esscene': 'application/json',
+ '.wasm': 'application/wasm', '.png': 'image/png', '.jpg': 'image/jpeg',
+ '.webp': 'image/webp', '.woff': 'font/woff', '.woff2': 'font/woff2', '.svg': 'image/svg+xml',
+};
+
+function serveDist() {
+ const server = http.createServer(async (req, res) => {
+ try {
+ const rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '') || 'index.html';
+ const abs = path.join(DIST, rel);
+ if (!abs.startsWith(DIST)) return void res.writeHead(403).end();
+ const bytes = await readFile(abs);
+ res.writeHead(200, { 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream' });
+ res.end(bytes);
+ } catch {
+ res.writeHead(404).end('not found');
+ }
+ });
+ return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)));
+}
+
+function finish(result, server) {
+ const ok = result.ok && result.handshake === 'estella:play:ready';
+ console.log(`\n[play:verify] ${ok ? 'PASS' : 'FAIL'} — ${SCENE}`);
+ console.log('DRIVE_RESULT ' + JSON.stringify(result));
+ process.exitCode = ok ? 0 : 1;
+ try { server?.close(); } catch { /* ignore */ }
+ app.quit();
+}
+
+app.whenReady().then(async () => {
+ let server;
+ try {
+ server = await serveDist();
+ const base = `http://127.0.0.1:${server.address().port}`;
+ const sceneData = JSON.parse(await readFile(path.join(DIST, SCENE.replace(/^\//, '')), 'utf8'));
+ const assetManifest = JSON.parse(await readFile(path.join(DIST, MANIFEST.replace(/^\//, '')), 'utf8'));
+
+ const win = new BrowserWindow({ show: false, width: W, height: H, webPreferences: { offscreen: false } });
+ win.webContents.on('console-message', (...a) => {
+ const m = a.map((x) => (x && typeof x === 'object' ? x.message ?? '' : String(x))).join(' ');
+ if (/error|fail|exception|webgl/i.test(m) && !/unwind/i.test(m)) console.log('[realm]', m.slice(0, 240));
+ });
+ await win.loadURL(`${base}/play.html`);
+ const exec = (code) => win.webContents.executeJavaScript(code, true);
+
+ // Record the realm's outbound handshake, then post the scene snapshot in.
+ await exec(`window.__msgs=[];addEventListener('message',e=>{if(e.data&&String(e.data.type||'').startsWith('estella:play:'))window.__msgs.push(e.data)});true`);
+ await exec(`window.postMessage(${JSON.stringify({ type: 'estella:play:init', sceneData, assetManifest })},'*');true`);
+
+ const msg = await exec(`(async()=>{for(let i=0;i<400;i++){const m=(window.__msgs||[]).find(x=>x.type==='estella:play:ready'||x.type==='estella:play:error');if(m)return m;await new Promise(r=>setTimeout(r,50));}return{type:'timeout'};})()`);
+
+ let capture = null;
+ try {
+ const img = await win.capturePage();
+ const b = img.toBitmap(); // BGRA
+ const min = [255, 255, 255], max = [0, 0, 0];
+ let nonZero = 0;
+ for (let i = 0; i < b.length; i += 4) {
+ for (let k = 0; k < 3; k++) { const v = b[i + k]; if (v < min[k]) min[k] = v; if (v > max[k]) max[k] = v; }
+ if (b[i] | b[i + 1] | b[i + 2]) nonZero++;
+ }
+ capture = { spread: (max[0] - min[0]) + (max[1] - min[1]) + (max[2] - min[2]), nonZeroPixels: nonZero };
+ } catch (e) {
+ capture = { error: String(e) };
+ }
+
+ finish({ ok: true, handshake: msg.type, detail: msg, capture }, server);
+ } catch (e) {
+ finish({ ok: false, error: String((e && e.stack) || e) }, server);
+ }
+});
+
+setTimeout(() => finish({ ok: false, error: 'timeout' }), 45000);
diff --git a/desktop/src/play.ts b/desktop/src/play.ts
new file mode 100644
index 000000000..e062bd522
--- /dev/null
+++ b/desktop/src/play.ts
@@ -0,0 +1,113 @@
+/**
+ * @file play.ts — the isolated play-realm host page (REARCH_EDITOR_REALM Phase R).
+ *
+ * Runs inside the editor's "Game" iframe as a SEPARATE realm (its own wasm + GL +
+ * World). It boots the SHIPPING runtime (createWebApp → initPlayRealmRuntime) and
+ * runs the scene SNAPSHOT the editor posts in — so what you play is what you ship.
+ * Control + handshake go over postMessage; the realm never touches `window.estella`.
+ *
+ * Builtin components/systems run as-is. Project-defined components/systems (a
+ * bundle with esengine external + an import map) are a layered follow-up.
+ */
+import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime } from 'esengine';
+import type { App, ESEngineModule, SceneData } from 'esengine';
+
+interface InitMessage {
+ type: 'estella:play:init';
+ sceneData: SceneData;
+ assetManifest: Record<string, string>;
+}
+
+const canvas = document.getElementById('canvas') as HTMLCanvasElement;
+
+function 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();
+
+let app: App | null = null;
+let booted = false;
+
+function post(message: Record<string, unknown>): void {
+ parent.postMessage(message, '*');
+}
+
+async function boot(msg: InitMessage): Promise<void> {
+ if (booted) return;
+ booted = true;
+ try {
+ // Glue + binary load from this realm's origin (dev http / packaged app://).
+ const glueUrl = `${location.origin}/wasm/esengine.js`;
+ const { default: createModule } = (await import(/* @vite-ignore */ glueUrl)) as {
+ default: (options?: Record<string, unknown>) => Promise<ESEngineModule>;
+ };
+ const module = await createModule({
+ canvas,
+ locateFile: (p: string) => `/wasm/${p}`,
+ print: (t: string) => console.log('[wasm]', t),
+ printErr: (t: string) => console.warn('[wasm]', 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 in this realm.');
+ const glHandle = module.GL.registerContext(gl, {
+ majorVersion: 2,
+ minorVersion: 0,
+ enableExtensionsByDefault: true,
+ });
+
+ app = createWebApp(module, {
+ glContextHandle: glHandle,
+ getViewportSize: () => ({ width: canvas.width, height: canvas.height }),
+ wasmBaseUrl: '/wasm',
+ });
+
+ // Real shipping mode — NOT editor mode. Gameplay systems run.
+ setEditorMode(false);
+ setPlayMode(true);
+
+ await initPlayRealmRuntime({
+ app,
+ module,
+ canvas,
+ sceneData: msg.sceneData,
+ assetManifest: msg.assetManifest,
+ });
+ post({ type: 'estella:play:ready' });
+ } catch (err) {
+ // Emscripten throws 'unwind' when its main loop takes over — that's success.
+ const message = err instanceof Error ? err.message : String(err);
+ if (err === 'unwind' || message.includes('unwind')) {
+ post({ type: 'estella:play:ready' });
+ return;
+ }
+ console.error('[play] boot failed', err);
+ post({ type: 'estella:play:error', message });
+ }
+}
+
+window.addEventListener('message', (e: MessageEvent) => {
+ const data = e.data as { type?: string; paused?: boolean } | null;
+ if (!data || typeof data !== 'object') return;
+ switch (data.type) {
+ case 'estella:play:init':
+ void boot(e.data as InitMessage);
+ break;
+ case 'estella:play:setPaused':
+ app?.setPaused(!!data.paused);
+ break;
+ // 'dispose' = the editor removes the iframe; the whole realm is torn down.
+ }
+});
+
+// Tell the editor the realm is mounted and ready to receive the scene snapshot.
+post({ type: 'estella:play:hello' });
diff --git a/desktop/vite.config.ts b/desktop/vite.config.ts
index 3d3551588..d83773656 100644
--- a/desktop/vite.config.ts
+++ b/desktop/vite.config.ts
@@ -14,11 +14,13 @@ export default defineConfig({
},
build: {
rollupOptions: {
- // Two renderer entries: the editor shell (index) and the headless render
- // host (headless) used for automation/verification — see headless.html.
+ // Renderer entries: the editor shell (index), the headless render host
+ // (headless, for automation/verification), and the isolated play realm
+ // host (play, REARCH_EDITOR_REALM Phase R).
input: {
index: fileURLToPath(new URL('./index.html', import.meta.url)),
headless: fileURLToPath(new URL('./headless.html', import.meta.url)),
+ play: fileURLToPath(new URL('./play.html', import.meta.url)),
},
},
},