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.

perf(editor): warm re-Play — keep the realm engine alive across Stop

yhh29a276794429
diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.ts
index acb28a31b..ce5b23dba 100644
--- a/desktop/src/engine/PlayRealm.ts
+++ b/desktop/src/engine/PlayRealm.ts
@@ -38,6 +38,10 @@ export class PlayRealmInstance {
private payload: PlayPayload | null = null;
private netPorts: MessagePort[] | null = null;
private epoch = 0;
+ // The realm's wasm + GL are alive in the (persistent) iframe from a prior Play,
+ // so a re-Play hands over the new scene instead of cold-booting a fresh iframe
+ // (single-player primary only; multiplayer + play-in-window cold-boot as before).
+ private warm = false;
private readonly store = createStore<PlayRealmSnapshot>(() => ({ playing: false, ready: false, error: null }));
constructor(readonly id: number) {}
@@ -96,6 +100,16 @@ export class PlayRealmInstance {
if (this.id === 0) bootProfiler.begin('play (click → first frame)');
const frame = this.ensureIframe();
frame.style.visibility = 'hidden';
+
+ // Warm re-Play: the engine is alive in the persistent iframe — hand it the new
+ // scene directly (the host does a warm rebuild: no second wasm instantiate, no
+ // iframe/bundle reload). Single-player primary only; anything else cold-boots.
+ if (this.warm && this.id === 0 && !this.netPorts) {
+ bootProfiler.mark('warm re-Play (engine kept alive)');
+ this.postInit();
+ return;
+ }
+
try {
const realm = await window.estella.project.preparePlayRealm();
if (this.id === 0) bootProfiler.mark('preparePlayRealm (stage + esbuild)');
@@ -109,20 +123,38 @@ export class PlayRealmInstance {
}
}
- /** Tear the realm down (releases its wasm + GL by navigating to a blank page). */
+ /** Post the scene payload to the (loaded) realm — cold on `hello`, or directly
+ * on a warm re-Play. Transfers net MessagePorts with it for multiplayer. */
+ private postInit(): void {
+ if (!this.payload) return;
+ const ports = this.netPorts ?? undefined;
+ this.post({ type: 'estella:play:init', ...this.payload, netPorts: ports }, ports);
+ }
+
+ /** Stop the game. Single-player keeps the engine WARM (hide + pause, no reboot)
+ * so the next Play is a fast scene swap; multiplayer/other realms release the
+ * wasm + GL by navigating to a blank page. */
stop(): void {
this.payload = null;
this.netPorts = null;
+ if (this.warm && this.id === 0) {
+ if (this.iframe) this.iframe.style.visibility = 'hidden';
+ this.setPaused(true); // freeze the world so a hidden realm doesn't keep simulating
+ this.set({ playing: false, ready: false, error: null });
+ return;
+ }
if (this.iframe) {
this.iframe.style.visibility = 'hidden';
this.iframe.src = 'about:blank';
}
+ this.warm = false;
this.set({ playing: false, ready: false, error: null });
}
/** Full teardown for a session-scoped (client) realm: stop + drop the iframe
* and the window listener. The instance is not reusable afterwards. */
destroy(): void {
+ this.warm = false; // force stop() down the cold teardown path (release wasm + GL)
this.stop();
window.removeEventListener('message', this.onMessage);
this.detach();
@@ -211,10 +243,7 @@ export class PlayRealmInstance {
break;
}
if (this.id === 0) bootProfiler.mark('iframe + host bundle load (→hello)');
- if (this.payload) {
- const ports = this.netPorts ?? undefined;
- this.post({ type: 'estella:play:init', ...this.payload, netPorts: ports }, ports);
- }
+ this.postInit();
break;
}
case 'estella:play:log':
@@ -231,6 +260,9 @@ export class PlayRealmInstance {
bootProfiler.mark('realm boot: wasm + scene (→ready)');
bootProfiler.report();
}
+ // The engine is now alive in the iframe; a single-player primary keeps it
+ // warm across Stop so the next Play is a scene swap, not a cold reboot.
+ if (this.id === 0 && !this.netPorts) this.warm = true;
this.set({ ready: true });
if (this.iframe) this.iframe.style.visibility = 'visible';
// Hand the running game keyboard focus so it's playable immediately — the
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 51e5d88f3..e87c3bf47 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -725,14 +725,17 @@ export function Viewport() {
}, [showGrid, snapStep, primaryId, engine.status]);
// Play In Viewport (UE5 PIE): host the realm iframe over the stage while playing
- // here; App.start() already booted the realm — we just re-parent its iframe.
+ // here. The host div is PERSISTENT (mounted whenever the viewport is the play
+ // target, parked off-screen when not playing) so the realm's wasm + GL survive
+ // Stop and a re-Play is a warm scene swap — moving an iframe between parents
+ // reloads it, so it must never leave this host. Detach only on target switch.
const playInViewport = isPlaying && playTarget === 'viewport';
useEffect(() => {
- if (!playInViewport) return;
+ if (playTarget !== 'viewport') return;
const host = playHostRef.current;
if (host) PlayRealm.attach(host);
return () => PlayRealm.detach();
- }, [playInViewport]);
+ }, [playTarget]);
// Wheel = zoom about the view (native non-passive listener so we can preventDefault).
useEffect(() => {
@@ -1872,23 +1875,28 @@ export function Viewport() {
</svg>
))}
- {/* Play In Viewport: the realm iframe fills the stage; a thin badge marks PIE. */}
- {playInViewport && (
- <div className="viewport__play">
+ {/* Play In Viewport: the realm iframe fills the stage. The host stays mounted
+ whenever the viewport is the play target (parked when not playing) so the
+ engine survives Stop for a warm re-Play; the status + stop chrome is
+ play-only. */}
+ {playTarget === 'viewport' && (
+ <div className={`viewport__play${playInViewport ? '' : ' viewport__play--parked'}`}>
<div className="viewport__play-host" ref={playHostRef} />
- {(!realm.ready || realm.error) && (
+ {playInViewport && (!realm.ready || realm.error) && (
<div className={`viewport__play-status${realm.error ? ' error' : ''}`}>
{realm.error ? t('vp.playFailed', { error: realm.error }) : t('vp.startingGame')}
</div>
)}
- <button
- type="button"
- className="viewport__play-stop"
- title={t('vp.stopTitle')}
- onClick={() => useEditorStore.getState().stop()}
- >
- {t('vp.playingStop')}
- </button>
+ {playInViewport && (
+ <button
+ type="button"
+ className="viewport__play-stop"
+ title={t('vp.stopTitle')}
+ onClick={() => useEditorStore.getState().stop()}
+ >
+ {t('vp.playingStop')}
+ </button>
+ )}
</div>
)}
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index fdb49ba21..e6fbdf94a 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -251,14 +251,53 @@ function beginNet(msg: InitMessage): Promise<void> {
});
}
+const r1 = (n: number): number => Math.round(n * 10) / 10;
+
+/**
+ * Rebuild the World for a NEW scene on the ALREADY-LIVE wasm + GL — the warm
+ * re-Play path (the editor keeps the realm iframe persistent across Stop, so a
+ * second Play reuses this engine instead of cold-booting a fresh iframe). Same
+ * teardown as {@link reload}'s full restart, but with the new payload. Reports
+ * bundle/engine as 0 in the profile — only the scene+asset load is paid.
+ */
+async function warmRebuild(msg: InitMessage): Promise<void> {
+ try {
+ if (app) {
+ const oldRegistry = app.world.getCppRegistry();
+ app.quit({ keepRenderer: true }); // keep wasm + GL; a full quit destroys the context
+ try { (oldRegistry as { delete?: () => void } | null)?.delete?.(); } catch { /* already freed */ }
+ app = null;
+ }
+ clearUserComponents();
+ try {
+ await import(/* @vite-ignore */ `${bundleUrl}?v=${++reloadSeq}`); // cache-bust: pick up edited code
+ } catch {
+ /* no project bundle — builtin-only */
+ }
+ const t = performance.now();
+ await buildAppAndRun(msg);
+ post({ type: 'estella:play:ready', phases: { bundleImport: 0, engineInstantiate: 0, sceneAndAssets: r1(performance.now() - t) } });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ console.error('[play] warm rebuild failed', err);
+ post({ type: 'estella:play:error', message });
+ }
+}
+
async function boot(msg: InitMessage): Promise<void> {
+ lastInit = msg;
+ // Warm re-Play: wasm + GL are already alive from a prior Play, so rebuild the
+ // World on them — no second instantiate, no bundle re-parse. (A multiplayer
+ // realm can't hot-rebuild — its net ports were consumed — so it cold-boots.)
+ if (booted && engineModule && !msg.net) {
+ await warmRebuild(msg);
+ return;
+ }
if (booted) return;
booted = true;
- lastInit = msg;
try {
// Sub-phase timing reported back to the editor on `ready` — the realm runs in
// its own JS realm, so it can't write the editor's boot profiler directly.
- const r1 = (n: number): number => Math.round(n * 10) / 10;
const tBundle = performance.now();
// Register the project's own components/systems FIRST (side-effect import; its
// `import 'esengine'` resolves through the import map to the shared instance).
diff --git a/desktop/src/theme/viewport.css b/desktop/src/theme/viewport.css
index d6f3c0bcb..de85b4946 100644
--- a/desktop/src/theme/viewport.css
+++ b/desktop/src/theme/viewport.css
@@ -181,6 +181,10 @@
/* Play In Viewport (UE5 PIE): the realm iframe overlays the stage while playing. */
.viewport__play { position: absolute; inset: 0; z-index: 6; background: var(--srf-1); }
+/* Parked: the play host stays mounted (its iframe's wasm + GL survive Stop for a
+ warm re-Play) but is invisible, non-interactive, and behind the editor stage.
+ visibility (not display:none) keeps the iframe's GL context alive. */
+.viewport__play--parked { visibility: hidden; pointer-events: none; z-index: -1; }
.viewport__play-host { position: absolute; inset: 0; }
.viewport__play-host iframe { width: 100%; height: 100%; border: 0; display: block; }
.viewport__play-status {