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
fix(editor): don't prewarm the play realm before a project opens + trim comments
yhh2453610c85d2
diff --git a/desktop/electron/buildPlayRealm.ts b/desktop/electron/buildPlayRealm.tsindex 691702a21..a7bd8e692 100644--- a/desktop/electron/buildPlayRealm.ts+++ b/desktop/electron/buildPlayRealm.ts@@ -113,8 +113,7 @@ export async function buildPlayRealm(opts: {await mkdir(out, { recursive: true });// 1. Host module — esengine EXTERNAL (resolved by the realm's import map).- // Stamped on the entry's stat like the dir syncs below, so a repeat Play- // (the hot path — prewarmed on project open) skips esbuild entirely.+ // Stamped on the entry's stat so a repeat Play skips esbuild.const hostStamp = path.join(out, '.host-stamp');const hostOut = path.join(out, 'host.js');const entryStat = await stat(opts.playHostEntry);@@ -148,7 +147,7 @@ export async function buildPlayRealm(opts: {await syncDir(opts.sdkDistDir, path.join(out, 'sdk'), path.join(out, '.sdk-stamp'));await syncDir(opts.wasmDir, path.join(out, 'wasm'), path.join(out, '.wasm-stamp'));- // 3. Host page (only when its content actually changed — keeps mtimes stable).+ // 3. Host page (rewrite only on change — keeps mtimes stable).const htmlPath = path.join(out, 'play.html');if (!existsSync(htmlPath) || (await readFile(htmlPath, 'utf8')) !== PLAY_HTML) {await writeFile(htmlPath, PLAY_HTML);diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex eb353781b..405b8d22c 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -47,8 +47,7 @@ import type { WorkspaceState } from '../src/project/format';protocol.registerSchemesAsPrivileged([{scheme: 'estella',- // codeCache: V8 caches compiled bytecode for scripts served over this scheme- // (the play realm's SDK bundle + host), cutting repeat-Play parse time.+ // codeCache: V8 persists compiled bytecode for the play realm's scripts.privileges: { standard: true, secure: true, supportFetchAPI: true, corsEnabled: true, stream: true, codeCache: true },},{@@ -114,8 +113,7 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));// public/ > static assets (wasm, sdk, examples) in devprocess.env.APP_ROOT = path.join(__dirname, '..');-// Automation runs get their own profile dir so a shot never fights the user's-// live editor instance over the Chromium disk cache / userData locks.+// Automation gets its own profile dir — never fight the live editor over cache locks.if (process.env.ESTELLA_SHOT) {app.setPath('userData', path.join(app.getPath('temp'), 'estella-shot-profile'));}@@ -201,13 +199,10 @@ async function runScreenshot(w: BrowserWindow, out: string): Promise<void> {if (err) console.log('[play] error:', err);await settleFrames(30); // let the game loop run so animation/assets settle}- // Pointer-drag gesture inside the PLAY REALM ("x0,y0,x1,y1" in play-canvas- // px). The play iframe is estella:// — cross-origin to the editor, so- // neither SHOT_EVAL (renderer, same-origin only) nor sendInputEvent- // (doesn't route into OOPIFs) can reach it. The main process CAN: target- // the frame via mainFrame.frames and dispatch DOM pointer events from- // within its origin, spread over rAF ticks so the engine's per-frame input- // sampling sees a real gesture. Verifies drag-scroll / drag&drop e2e.+ // Pointer drag inside the play realm ("x0,y0,x1,y1" in play-canvas px).+ // The estella:// iframe is an OOPIF — unreachable by SHOT_EVAL and+ // sendInputEvent — so the gesture is dispatched from within its frame,+ // spread over rAF ticks so per-frame input sampling sees it.if (process.env.ESTELLA_SHOT_DRAG) {const [x0, y0, x1, y1] = process.env.ESTELLA_SHOT_DRAG.split(',').map(Number);const playFrame = w.webContents.mainFrame.frames.find((f) => f.url.startsWith('estella://'));@@ -277,8 +272,7 @@ function createWindow() {// Keep the renderer sandboxed; all privileged work goes through preload IPC.contextIsolation: true,nodeIntegration: false,- // An engine editor keeps simulating while occluded — and the automation- // hooks' rAF-based waits must not freeze when another window covers us.+ // rAF must keep firing while occluded (automation waits, engine loop).backgroundThrottling: false,},});@@ -302,8 +296,7 @@ function createWindow() {if (VITE_DEV_SERVER_URL) {win.loadURL(VITE_DEV_SERVER_URL + automation);- // SHOT_DEVTOOLS: open DevTools during an automation run — for measuring the- // overhead DevTools itself adds (its protocol bridge stalls the renderer).+ // SHOT_DEVTOOLS: measure the overhead DevTools itself adds to a run.if (!shotOut || process.env.ESTELLA_SHOT_DEVTOOLS) win.webContents.openDevTools({ mode: 'detach' });} else {// Load over app:// (not file://) so the engine glue + play realm resolve fromdiff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex 48d6ccbc3..171573f47 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -78,7 +78,6 @@ export function App() {return unsub;}, []);- // Schedule work for browser idle time (fallback for environments without rIC).const idle = (fn: () => void) =>typeof window.requestIdleCallback === 'function' ? window.requestIdleCallback(fn) : setTimeout(fn, 500);@@ -107,8 +106,8 @@ export function App() {PlayInspect.stop();useEditorStore.getState().setInspectWorld('editor');dockApi.closeGame();- // Re-stage the realm in idle time so the next Play skips the build wait.- idle(() => PlayRealm.prewarm());+ // Not on mount/launcher — there is no project to stage yet.+ if (!useEditorStore.getState().showLauncher) idle(() => PlayRealm.prewarm());}}, [isPlaying]);useEffect(() => {@@ -118,8 +117,7 @@ export function App() {// The editor opens on the launcher (project browser); the shell + engine mount// only once a project is opened. (Logic wiring lands with the recents IPC.)const showLauncher = useEditorStore((s) => s.showLauncher);- // Stage the play realm right after a project opens, so the first Play doesn't- // pay the esbuild + sdk/wasm sync wait.+ // Prewarm the play realm as soon as a project opens.useEffect(() => {if (!showLauncher) idle(() => PlayRealm.prewarm());// eslint-disable-next-line react-hooks/exhaustive-depsdiff --git a/desktop/src/engine/PerfMonitor.ts b/desktop/src/engine/PerfMonitor.tsindex 3d3a24062..7560573ed 100644--- a/desktop/src/engine/PerfMonitor.ts+++ b/desktop/src/engine/PerfMonitor.ts@@ -139,8 +139,7 @@ export interface SessionCapture {budgetMs: number;frameCount: number;frames: FrameSample[];- /** Recent main-thread long tasks (browser attribution) — correlate `start`- * with frame t0/t1 to name what blocked an uninstrumented hitch. */+ /** Recent main-thread long tasks — correlate `start` with frame t0/t1. */longTasks?: Array<{ start: number; ms: number; name: string }>;}diff --git a/desktop/src/engine/PlayInspect.ts b/desktop/src/engine/PlayInspect.tsindex e48746355..06fd8a994 100644--- a/desktop/src/engine/PlayInspect.ts+++ b/desktop/src/engine/PlayInspect.ts@@ -48,8 +48,7 @@ class PlayInspectImpl {subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);getSnapshot = (): PlayInspectState => this.store.getState();- /** Narrow, identity-stable slices: a per-tick selected-entity refresh must- * not re-render tree-only subscribers (the Outliner). */+ /** Identity-stable slices so Details-only ticks don't re-render the Outliner. */getTree = (): SceneData | null => this.store.getState().snapshot;getSelection = (): EntityId | null => this.store.getState().selection;@@ -101,8 +100,6 @@ class PlayInspectImpl {const sameSelected = cur.selectedEntity === res.selected|| (cur.selectedEntity != null && res.selected != null&& JSON.stringify(cur.selectedEntity) === JSON.stringify(res.selected));- // Nothing changed (idle play, no selection): don't notify — a store bump- // here re-committed every subscriber on each 16ms tick for no reason.if (sameTree && sameSelected) return;this.store.setState({snapshot: sameTree ? cur.snapshot : res.tree,diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.tsindex e5fb77aa4..e994bc73a 100644--- a/desktop/src/engine/PlayRealm.ts+++ b/desktop/src/engine/PlayRealm.ts@@ -75,15 +75,9 @@ class PlayRealmImpl {* esengine instance (custom components/systems run) and all assets are* same-origin. Init is posted on the realm's `hello`.*/- /** Stage the realm ahead of time (idle after project open / play stop), so- * Play's own preparePlayRealm hits warm stamps and returns in milliseconds.- * Fire-and-forget; the build is stamped + idempotent. */+ /** Stage the realm ahead of time so Play's prepare hits warm stamps. */prewarm(): void {- try {- void window.estella.project.preparePlayRealm();- } catch {- /* prewarm is best-effort; Play reports real errors */- }+ window.estella.project.preparePlayRealm().catch(() => {});}async start(payload: PlayPayload): Promise<void> {diff --git a/desktop/src/engine/StatsStore.ts b/desktop/src/engine/StatsStore.tsindex 8a9f20b62..ddb21d923 100644--- a/desktop/src/engine/StatsStore.ts+++ b/desktop/src/engine/StatsStore.ts@@ -43,8 +43,7 @@ const selEq = (a: SelTransform | null, b: SelTransform | null): boolean =>// a second (not per frame) to avoid churning the status bar.class StatsStoreImpl {private readonly store = createStore<StatsSnapshot>(() => ({ fps: 0, entities: 0, selection: null }));- // The cursor updates at pointer-move rate; its own store keeps that churn in- // a leaf readout instead of re-rendering every slow-stats subscriber.+ // Pointer-rate churn stays out of the slow-stats subscribers.private readonly cursorStore = createStore<{ x: number; y: number } | null>(() => null);private running = false;diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.tsindex 96bb853dc..394023a21 100644--- a/desktop/src/engine/ViewportController.ts+++ b/desktop/src/engine/ViewportController.ts@@ -117,9 +117,7 @@ export const ViewportController = {};},- /** All UI entities under the pointer, most specific first (editor pick: any- * layout box, not just raycast targets — so plain text and panels are- * selectable). Locked / hidden entries are dropped. */+ /** UI entities under the pointer, most specific first; locked/hidden dropped. */pickUIEntities(clientX: number, clientY: number): EntityId[] {const world = EngineHost.world;const module = EngineHost.module;@@ -277,7 +275,6 @@ export const ViewportController = {let maxX = -Infinity;let maxY = -Infinity;for (const id of ids) {- // UI entities have no world OBB from entityBounds; frame their layout box.const b = this.entityBounds(id) ?? this.uiEntityWorldOBB(id);if (!b) continue;for (const [wx, wy] of obbCorners(b)) {diff --git a/desktop/src/engine/backgroundThrottle.ts b/desktop/src/engine/backgroundThrottle.tsindex 0e0e37e84..3c82d954a 100644--- a/desktop/src/engine/backgroundThrottle.ts+++ b/desktop/src/engine/backgroundThrottle.ts@@ -1,12 +1,8 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file backgroundThrottle.ts — editor-side "use less CPU in background".- *- * Chromium's own background throttling is disabled (main.ts) so automation- * never freezes; this is the smart replacement: cap the engine loop at a low- * frame rate while the window is unfocused (Unreal's "Use Less CPU when in- * Background"), restore on focus. Driven by the `performance.*` setting.+ * @file backgroundThrottle.ts — cap the engine loop while the window is+ * unfocused (Chromium's own throttling is disabled for automation).*/import { EngineHost } from './EngineHost';@@ -19,15 +15,13 @@ function apply(): void {EngineHost.setTargetFrameRate(enabled && !focused ? BACKGROUND_FPS : 0);}-/** Settings backing: toggle the background cap (applies immediately). */export function setUseLessCpuInBackground(on: boolean): void {enabled = on;apply();}-/** Attach the focus listeners once at boot. Automation windows are driven- * unfocused, so `?automation=1` opts out entirely. */export function initBackgroundThrottle(): void {+ // Automation windows are driven unfocused; never throttle them.if (new URLSearchParams(location.search).has('automation')) return;focused = document.hasFocus();window.addEventListener('focus', () => { focused = true; apply(); });diff --git a/desktop/src/layout/StatusBar.tsx b/desktop/src/layout/StatusBar.tsxindex 5e24c7018..3768ed811 100644--- a/desktop/src/layout/StatusBar.tsx+++ b/desktop/src/layout/StatusBar.tsx@@ -8,8 +8,7 @@ import { StatsStore } from '@/engine/StatsStore';import { SubsystemIndicator } from './SubsystemIndicator';import { Perf } from '@/components/Perf';-// Leaf subscriber for the pointer-rate cursor readout: only this text node-// re-renders on mouse move, never the footer.+// Only this text node re-renders on mouse move, never the footer.function CursorReadout() {const cursor = useSyncExternalStore(StatsStore.subscribeCursor, StatsStore.getCursor);return <>{cursor ? `${cursor.x}, ${cursor.y}` : '—'}</>;diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex 2b7f7bff7..d0fb425ee 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -53,8 +53,6 @@ applySettings();// edits made outside the editor) via the main-process project watcher.initFsWatch();-// Focus-driven engine frame cap (the smart replacement for Chromium's-// disabled background throttling).initBackgroundThrottle();// Automation hook (screenshots / visual-regression): with `?automation=1`, expose thediff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsxindex ec1503d8a..9ead3d25e 100644--- a/desktop/src/panels/Outliner.tsx+++ b/desktop/src/panels/Outliner.tsx@@ -38,8 +38,6 @@ const entityIds = (items: OutlinerItem[]): EntityId[] =>// One row of the live "Game" tree: a read-only, always-expanded// view of the running realm, sharing the editor's virtualization. No folders.function GameTree() {- // Narrow slices: identity-stable between ticks, so React bails out of the- // re-render while only the selected entity's live values are refreshing.const snapshot = useSyncExternalStore(PlayInspect.subscribe, PlayInspect.getTree);const selection = useSyncExternalStore(PlayInspect.subscribe, PlayInspect.getSelection);const items = useMemo(() => buildOutlinerItems(snapshot, { expanded: NO_EXPANSION, expandAll: true }), [snapshot]);diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex 60d769834..552388c57 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -206,8 +206,7 @@ function DdRadio({ on, label, onClick }: { on: boolean; label: string; onClick:);}-// Pointer-rate cursor text as its own leaf: only this node re-renders per-// mouse move; the HUD itself follows the slow (333ms) stats cadence.+// Only this node re-renders per mouse move; the HUD follows the slow stats cadence.function HudCursor() {const cursor = useSyncExternalStore(StatsStore.subscribeCursor, StatsStore.getCursor);if (!cursor) return null;diff --git a/sdk/src/ui/util/ui-pick.ts b/sdk/src/ui/util/ui-pick.tsindex e93b078c0..0e3a626a9 100644--- a/sdk/src/ui/util/ui-pick.ts+++ b/sdk/src/ui/util/ui-pick.ts@@ -33,11 +33,8 @@ export function uiHitTestWorld(return hit === NO_HIT ? null : hit;}-/**- * Editor pick: topmost UI entity whose layout box contains the point,- * regardless of Interactable, without touching interaction state. Use this- * for editor selection; `uiHitTestWorld` is the runtime raycast.- */+/** Editor pick: topmost UI entity under the point, regardless of Interactable;+ * `uiHitTestWorld` is the runtime raycast. */export function uiPickWorld(module: ESEngineModule,registry: CppRegistry,@@ -49,8 +46,7 @@ export function uiPickWorld(return hit === NO_HIT ? null : hit;}-/** All editor-pickable UI entities under the point, most specific first- * (backs click-through cycling). */+/** All editor-pickable UI entities under the point, most specific first. */export function uiPickAllWorld(module: ESEngineModule,registry: CppRegistry,diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 56453fd98..ef5b3ccbf 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -592,13 +592,10 @@ u32 uiHitTest_getHitEntityPrev() {return ctx().require<ecs::UISystem>().getPrevHitEntity();}-// Editor pick: ignores Interactable and mutates no interaction state, so the-// editor can select plain text / panels without polluting runtime hover.u32 uiHitTest_pick(ecs::Registry& registry, f32 worldX, f32 worldY) {return ctx().require<ecs::UISystem>().pick(registry, worldX, worldY);}-// Editor pick list (click-through cycling): count + indexed results.u32 uiHitTest_pickAll(ecs::Registry& registry, f32 worldX, f32 worldY) {return ctx().require<ecs::UISystem>().pickAll(registry, worldX, worldY);}diff --git a/src/esengine/ecs/UISystem.cpp b/src/esengine/ecs/UISystem.cppindex 06572c805..5021411a0 100644--- a/src/esengine/ecs/UISystem.cpp+++ b/src/esengine/ecs/UISystem.cpp@@ -77,9 +77,7 @@ u32 UISystem::pickAll(Registry& registry, f32 worldX, f32 worldY) {pickResults_.clear();const auto& nodes = tree.nodes_;- // Rank hits by hierarchy depth (the most specific element under the- // cursor — clicking a label picks the label, not its panel), breaking- // ties by draw order.+ // Depth-first ranking (a label beats its panel), draw order breaking ties.struct Hit {Entity entity;i32 depth;diff --git a/src/esengine/ecs/UISystem.hpp b/src/esengine/ecs/UISystem.hppindex ceb9db5e0..b8c9ba3c2 100644--- a/src/esengine/ecs/UISystem.hpp+++ b/src/esengine/ecs/UISystem.hpp@@ -74,20 +74,12 @@ public:f32 mouseWorldX, f32 mouseWorldY,bool mouseDown, bool mousePressed, bool mouseReleased);- /**- * @brief Editor pick: the most specific UI entity whose layout box contains- * the point (hierarchy depth desc, draw order breaking ties).- *- * Unlike hitTestUpdate this ignores Interactable — plain text and panels- * are selectable — and mutates no interaction state.- */+ /** @brief Editor pick: the most specific UI entity under the point. Unlike+ * hitTestUpdate it ignores Interactable and mutates no state. */u32 pick(Registry& registry, f32 worldX, f32 worldY);- /**- * @brief Editor pick list: ALL UI entities under the point, most specific- * first. Returns the count; read entries via pickResult (the list- * backs click-through cycling).- */+ /** @brief All UI entities under the point, most specific first. Returns the+ * count; read entries via pickResult. */u32 pickAll(Registry& registry, f32 worldX, f32 worldY);/** @brief Entry `index` of the last pickAll (or INVALID_ENTITY). */