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): unified frame profiler

esenginec00c1bcc3a3e
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index 418fe9d90..604ad37e7 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -10,6 +10,8 @@ import { ContentDrawer } from '@/layout/ContentDrawer';
import '@/engine/EditorSession'; // side effect: constructs defaultSession → wires the editor engine
import { Launcher } from '@/launcher/Launcher';
import { Toaster } from '@/components/Toaster';
+import { Perf } from '@/components/Perf';
+import { PerfRealmBridge } from '@/components/PerfRealmBridge';
import { BuildDialog } from '@/components/BuildDialog';
import { SettingsDialog } from '@/components/SettingsDialog';
import { useEditorStore } from '@/store/editorStore';
@@ -116,14 +118,15 @@ export function App() {
return (
<div className="shell">
- <MenuBar />
- <Toolbar />
+ <Perf id="menubar"><MenuBar /></Perf>
+ <Perf id="toolbar"><Toolbar /></Perf>
<main className="shell__workspace">
- <ActivityBar />
+ <Perf id="activitybar"><ActivityBar /></Perf>
<DockLayout />
</main>
- <StatusBar />
- <ContentDrawer />
+ <Perf id="statusbar"><StatusBar /></Perf>
+ <Perf id="contentdrawer"><ContentDrawer /></Perf>
+ <PerfRealmBridge />
{buildOpen && <BuildDialog />}
{settingsOpen && <SettingsDialog />}
<Toaster />
diff --git a/desktop/src/commands/registry.ts b/desktop/src/commands/registry.ts
index 094aac1c2..58f7bfbcb 100644
--- a/desktop/src/commands/registry.ts
+++ b/desktop/src/commands/registry.ts
@@ -10,6 +10,7 @@
*/
import type { Command, Keybinding } from './types';
import { chordMatches } from './keybinding';
+import { PerfMonitor } from '@/engine/PerfMonitor';
const OVERRIDE_KEY = 'estella.keybindings';
@@ -87,7 +88,7 @@ class CommandRegistry {
/** Run a command by id (no-op if missing or currently disabled). */
run(id: string): void {
const c = this.map.get(id);
- if (c && (c.isEnabled?.() ?? true)) c.run();
+ if (c && (c.isEnabled?.() ?? true)) PerfMonitor.measure(`cmd.${id}`, () => c.run());
}
/** The enabled command bound to a key event, if any (honors overrides). */
diff --git a/desktop/src/components/Perf.tsx b/desktop/src/components/Perf.tsx
new file mode 100644
index 000000000..27c0785ff
--- /dev/null
+++ b/desktop/src/components/Perf.tsx
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Perf.tsx — one React-commit instrumentation wrapper.
+ *
+ * `<Perf id="x">…</Perf>` reports its subtree's commit time to the profiler as
+ * `react.x`, so a panel/chrome region that stalls a frame is named, not lumped
+ * into an unattributed spike. Use it around each independently-committing region
+ * (dock panels, menu/tool/status bars) — siblings never nest, so no double-count.
+ */
+import { Profiler, type ReactNode } from 'react';
+import { PerfMonitor } from '@/engine/PerfMonitor';
+
+const onCommit = (id: string, _phase: unknown, actual: number) => PerfMonitor.reactCommit(id, actual);
+
+export function Perf({ id, children }: { id: string; children: ReactNode }) {
+ return (
+ <Profiler id={id} onRender={onCommit}>
+ {children}
+ </Profiler>
+ );
+}
diff --git a/desktop/src/components/PerfOverlay.tsx b/desktop/src/components/PerfOverlay.tsx
index 020c392ee..6eea43296 100644
--- a/desktop/src/components/PerfOverlay.tsx
+++ b/desktop/src/components/PerfOverlay.tsx
@@ -1,15 +1,19 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file PerfOverlay.tsx — the frame-timing readout (View ▸ Perf).
+ * @file PerfOverlay.tsx — the viewport fps glance (View ▸ Perf).
*
- * A leaf that subscribes to PerfMonitor so its twice-a-second updates never
- * re-render the viewport. Shows p50/p95/p99 frame time, dropped-frame count,
- * the worst frame + its dominant phase, and any long task (GC / long JS).
+ * A deliberately TINY corner readout — the UE `stat fps` analog — so it never
+ * obstructs the scene: just fps + frame percentiles, dropped frames, and any
+ * long task. The detailed `stat unit` breakdown / render counters / systems live
+ * in the dockable Profiler panel, not on top of the scene. A leaf subscriber, so
+ * its twice-a-second updates never re-render the viewport.
*/
import { useSyncExternalStore } from 'react';
import { PerfMonitor } from '@/engine/PerfMonitor';
+const mute = 'var(--text-mute, #888)';
+
export function PerfOverlay() {
const s = useSyncExternalStore(PerfMonitor.subscribe, PerfMonitor.getSnapshot);
const warn = 'var(--warn, #e5a33b)';
@@ -37,21 +41,15 @@ export function PerfOverlay() {
}}
>
<div>
- <span style={{ color: 'var(--text-mute, #888)' }}>fps</span> <b>{s.fps}</b>
+ <span style={{ color: mute }}>fps</span> <b>{s.fps}</b>
{' · p50 '}{s.p50}{' p95 '}{s.p95}{' '}
<span style={{ color: p99Bad ? warn : 'inherit' }}>p99 {s.p99}ms</span>
</div>
- <div>
- <span style={{ color: 'var(--text-mute, #888)' }}>long frames</span> <b>{s.longFrames}</b>
- {s.worstMs > 0 ? (
- <>
- {' · worst '}{s.worstMs}ms{' '}
- <span style={{ color: 'var(--text-mute, #888)' }}>({s.worstPhase ?? 'other'})</span>
- </>
- ) : null}
- </div>
- {s.longTaskMs > 0 ? (
- <div style={{ color: warn }}>long task {s.longTaskMs}ms · GC / long JS</div>
+ {s.longFrames > 0 || s.longTaskMs > 0 ? (
+ <div>
+ <span style={{ color: mute }}>long frames</span> <b>{s.longFrames}</b>
+ {s.longTaskMs > 0 ? <span style={{ color: warn }}>{' · task '}{s.longTaskMs}ms</span> : null}
+ </div>
) : null}
</div>
);
diff --git a/desktop/src/components/PerfRealmBridge.tsx b/desktop/src/components/PerfRealmBridge.tsx
new file mode 100644
index 000000000..c49406310
--- /dev/null
+++ b/desktop/src/components/PerfRealmBridge.tsx
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file PerfRealmBridge.tsx — feeds the profiler the RIGHT engine each realm.
+ *
+ * The sole owner of PerfMonitor's engine source: the edit App in edit mode, and
+ * the running game (play iframe) while playing — so the Profiler panel shows the
+ * game's real per-system / draw-call cost during Play, not the frozen edit App.
+ * One profiling surface across both realms, mirroring the Modules indicator.
+ *
+ * Renderless. The cross-iframe stats query is async, so it polls into a cache the
+ * synchronous engine source reads (the profiler samples once per frame).
+ */
+import { useSyncExternalStore, useEffect } from 'react';
+import { EngineHost } from '@/engine/EngineHost';
+import { PlayRealm } from '@/engine/PlayRealm';
+import { PerfMonitor, type EngineFrame } from '@/engine/PerfMonitor';
+
+export function PerfRealmBridge() {
+ const play = useSyncExternalStore(PlayRealm.subscribe, PlayRealm.getSnapshot);
+ const inPlay = play.playing && play.ready;
+
+ useEffect(() => {
+ if (!inPlay) {
+ PerfMonitor.setEngineSource(() => EngineHost.readEngineFrame(), 'edit');
+ return;
+ }
+ // Playing: poll the running game's stats into a cache the source reads sync.
+ let alive = true;
+ let cache: EngineFrame | null = null;
+ const poll = async () => {
+ const s = await PlayRealm.stats();
+ if (!alive) return;
+ cache = s
+ ? { phaseMs: s.phases, systemMs: s.systems, drawCalls: s.drawCalls, triangles: s.triangles, sprites: s.sprites, entities: s.entities, gpuMs: s.gpuMs }
+ : null;
+ };
+ void poll();
+ const t = setInterval(() => void poll(), 250);
+ PerfMonitor.setEngineSource(() => cache, 'play');
+ return () => {
+ alive = false;
+ clearInterval(t);
+ };
+ }, [inPlay]);
+
+ return null;
+}
diff --git a/desktop/src/engine/EngineHost.ts b/desktop/src/engine/EngineHost.ts
index 721d90723..4bc9916c8 100644
--- a/desktop/src/engine/EngineHost.ts
+++ b/desktop/src/engine/EngineHost.ts
@@ -108,6 +108,37 @@ class EngineHostImpl {
return this.canvas_;
}
+ /**
+ * The engine's last-frame telemetry for the profiler: per-phase / per-system
+ * wall-clock (ms, requires the boot-time `enableStats()`) plus render counters.
+ * Null until booted. Reads the live values without allocating beyond the two
+ * timing maps, so PerfMonitor can fold it into a frame once per rAF.
+ */
+ readEngineFrame(): {
+ phaseMs: Record<string, number>;
+ systemMs: Record<string, number>;
+ drawCalls: number;
+ triangles: number;
+ sprites: number;
+ entities: number;
+ gpuMs: number;
+ } | null {
+ const app = this.app_;
+ if (!app) return null;
+ const m = this.module_;
+ const phases = app.getPhaseTimings();
+ const systems = app.getSystemTimings();
+ return {
+ phaseMs: phases ? Object.fromEntries(phases) : {},
+ systemMs: systems ? Object.fromEntries(systems) : {},
+ drawCalls: m?.renderer_getDrawCalls?.() ?? 0,
+ triangles: m?.renderer_getTriangles?.() ?? 0,
+ sprites: m?.renderer_getSprites?.() ?? 0,
+ entities: this.world?.getAllEntities().length ?? 0,
+ gpuMs: m?.renderer_getGpuTimeMs?.() ?? -1,
+ };
+ }
+
// — Status as an external store (for useSyncExternalStore) —
subscribe = (fn: () => void): (() => void) => this.statusStore.subscribe(fn);
getSnapshot = (): EngineSnapshot => this.statusStore.getState();
@@ -394,6 +425,11 @@ class EngineHostImpl {
});
this.app_ = app;
+ // Per-phase / per-system wall-clock timing for the editor profiler
+ // (PerfMonitor reads it each frame). Cheap — a couple performance.now() per
+ // system — so left on in edit; the Perf overlay decides what to surface.
+ app.enableStats();
+
// Subsystem observability: phase changes push immediately; the sampler
// refreshes derived liveness (stepping↔idle) a couple of times a second.
this.syncSubsystems(app);
diff --git a/desktop/src/engine/PerfMonitor.ts b/desktop/src/engine/PerfMonitor.ts
index 51064a921..1c2d1638a 100644
--- a/desktop/src/engine/PerfMonitor.ts
+++ b/desktop/src/engine/PerfMonitor.ts
@@ -33,6 +33,68 @@ export function dominantPhase(phases: Record<string, number>): { phase: string;
return best;
}
+/** Sum a phase/system timing map (ms). */
+export function sumMs(rec: Record<string, number>): number {
+ let s = 0;
+ for (const k in rec) s += rec[k];
+ return s;
+}
+
+/** The n costliest entries of a timing map, descending — for the systems table. */
+export function topSystems(rec: Record<string, number>, n: number): Array<{ name: string; ms: number }> {
+ return Object.entries(rec)
+ .map(([name, ms]) => ({ name, ms }))
+ .sort((a, b) => b.ms - a.ms)
+ .slice(0, n);
+}
+
+/**
+ * The engine's last-frame telemetry the profiler folds into a frame: per-phase /
+ * per-system wall-clock (ms) + render counters. Supplied by a source callback so
+ * PerfMonitor stays decoupled from the engine host (and unit-testable).
+ */
+export interface EngineFrame {
+ phaseMs: Record<string, number>;
+ systemMs: Record<string, number>;
+ drawCalls: number;
+ triangles: number;
+ sprites: number;
+ entities: number;
+ /** GPU time (ms) via EXT_disjoint_timer_query, or -1 when unavailable. */
+ gpuMs: number;
+}
+
+/**
+ * One frame's FULL breakdown, captured every frame into a ring so any past frame
+ * (especially a hitch) can be inspected after the fact — the trace/scrub model
+ * Unreal Insights uses, rather than pausing the app. Values are per-frame, not
+ * windowed averages, so a spike's real attribution survives.
+ */
+export interface FrameSample {
+ id: number; // monotonic frame id (stable across ring scroll)
+ dt: number;
+ /** Frame window on the performance timeline, for correlating long tasks. */
+ t0: number;
+ t1: number;
+ engineMs: number;
+ editorMs: number;
+ gpuMs: number;
+ editorPhases: Record<string, number>;
+ enginePhases: Record<string, number>;
+ systems: Array<{ name: string; ms: number }>;
+ drawCalls: number;
+ triangles: number;
+ entities: number;
+}
+
+/** A main-thread long task overlapping a frame (GC / long JS the profiler can't
+ * name from inside), captured from the Long Tasks API — the usual cause of a
+ * spike that the instrumented phases don't account for. */
+export interface FrameLongTask {
+ ms: number;
+ name: string;
+}
+
export interface PerfSnapshot {
fps: number;
p50: number;
@@ -46,9 +108,37 @@ export interface PerfSnapshot {
longTaskMs: number;
visible: boolean;
enabled: boolean;
+ // stat-unit breakdown (windowed avg ms): Frame ≈ engine + editor + idle/present.
+ /** Engine CPU per frame (sum of app.run phase timings) — the "Game" analog. */
+ engineMs: number;
+ /** Editor CPU per frame (gizmo.update + react.commit + …) — the "Draw" analog. */
+ editorMs: number;
+ // Render counters (last sampled frame), UE `stat scenerendering` analog.
+ drawCalls: number;
+ triangles: number;
+ entities: number;
+ /** Costliest engine systems over the window (name + windowed-max ms). */
+ systemsTop: Array<{ name: string; ms: number }>;
+ /** Which realm the engine numbers come from. */
+ realm: 'edit' | 'play';
+ /** GPU time (ms), or -1 when the timer isn't available. */
+ gpuMs: number;
+ /** Recent frame intervals (ms, oldest→newest) for the history graph. */
+ frames: number[];
+ // Frame capture (PP6): freeze the rolling capture and inspect one frame.
+ /** True when the capture is frozen (graph static; sections show the pinned frame). */
+ frozen: boolean;
+ /** The inspected frame's id, or null for the live rolling window. */
+ pinnedId: number | null;
+ /** Auto-freeze + pin the next frame that exceeds the hitch threshold. */
+ autoHitch: boolean;
+ /** Bumps when a long task is observed — a refresh trigger so the pinned frame's
+ * long-task list updates even while the capture is frozen. */
+ longTaskRev: number;
}
const LONG_FRAME_MS = 24; // missed a 60Hz frame
+const HITCH_MS = 50; // auto-freeze threshold — a real hitch (below 20fps)
const WINDOW_MS = 500;
const CAP = 240;
const r1 = (n: number) => Math.round(n * 10) / 10;
@@ -56,6 +146,8 @@ const r1 = (n: number) => Math.round(n * 10) / 10;
class PerfMonitorImpl {
private readonly store = createStore<PerfSnapshot>(() => ({
fps: 0, p50: 0, p95: 0, p99: 0, longFrames: 0, worstMs: 0, worstPhase: null, longTaskMs: 0, visible: false, enabled: true,
+ engineMs: 0, editorMs: 0, drawCalls: 0, triangles: 0, entities: 0, systemsTop: [], realm: 'edit', gpuMs: -1, frames: [],
+ frozen: false, pinnedId: null, autoHitch: false, longTaskRev: 0,
}));
private enabled = true;
private running = false;
@@ -69,6 +161,23 @@ class PerfMonitorImpl {
private worstMs = 0;
private worstPhase: string | null = null;
private longTaskMs = 0;
+ // Engine-frame ingest (PP1): a source the host wires so PerfMonitor stays
+ // decoupled. Accumulated per frame, averaged/reduced at the window flush.
+ private engineSource: (() => EngineFrame | null) | null = null;
+ private engineSum = 0;
+ private editorSum = 0;
+ private winFrames = 0;
+ private systemMax: Record<string, number> = {};
+ private counters = { drawCalls: 0, triangles: 0, entities: 0, gpuMs: -1 };
+ private realm: 'edit' | 'play' = 'edit';
+ // Frame capture ring (PP6): full per-frame breakdown for pin-a-frame inspection.
+ private readonly samples: FrameSample[] = [];
+ private sampleSeq = 0;
+ private frozen = false;
+ private autoHitch = false;
+ // Long-task ring (PP7): correlate GC / long-JS spikes to the frame they hit.
+ private readonly longTasks: Array<{ start: number; ms: number; name: string }> = [];
+ private longTaskRev = 0;
start(): void {
if (this.running) return;
@@ -77,7 +186,15 @@ class PerfMonitorImpl {
if (typeof PerformanceObserver !== 'undefined') {
try {
this.obs = new PerformanceObserver((list) => {
- for (const e of list.getEntries()) this.longTaskMs = Math.max(this.longTaskMs, e.duration);
+ for (const e of list.getEntries()) {
+ this.longTaskMs = Math.max(this.longTaskMs, e.duration);
+ const attr = (e as PerformanceEntry & { attribution?: Array<{ containerName?: string; name?: string }> }).attribution?.[0];
+ this.longTasks.push({ start: e.startTime, ms: e.duration, name: attr?.containerName || attr?.name || e.name || 'self' });
+ if (this.longTasks.length > 60) this.longTasks.shift();
+ }
+ // Bump so a pinned/frozen view refreshes to include the just-arrived task
+ // (long tasks are observed a tick after the frame that caused them).
+ this.patch({ longTaskRev: ++this.longTaskRev });
});
this.obs.observe({ entryTypes: ['longtask'] });
} catch { /* longtask unsupported — frame timing still works */ }
@@ -94,6 +211,67 @@ class PerfMonitorImpl {
setEnabled(on: boolean): void { this.enabled = on; this.patch({ enabled: on }); }
toggleOverlay(): void { this.patch({ visible: !this.store.getState().visible }); }
+ // — Frame capture (PP6): freeze + inspect a specific frame —
+
+ /** Freeze the rolling capture and pin a frame for inspection (clicking a bar). */
+ pin(id: number): void {
+ this.frozen = true;
+ // Snapshot the static ring's dt into `frames` so the graph holds at this moment.
+ this.patch({ frozen: true, pinnedId: id, frames: this.samples.map((s) => s.dt) });
+ }
+
+ /** Resume live rolling capture (un-freeze + un-pin). */
+ resumeLive(): void {
+ this.frozen = false;
+ this.patch({ frozen: false, pinnedId: null });
+ }
+
+ /** Freeze at the latest captured frame without picking a specific one. */
+ freezeLatest(): void {
+ const last = this.samples[this.samples.length - 1];
+ this.pin(last ? last.id : -1);
+ }
+
+ toggleFrozen(): void {
+ if (this.store.getState().frozen) this.resumeLive();
+ else this.freezeLatest();
+ }
+
+ setAutoHitch(on: boolean): void {
+ this.autoHitch = on;
+ this.patch({ autoHitch: on });
+ }
+
+ /** The capture ring (oldest→newest). Aligned 1:1 with the snapshot's `frames`. */
+ getSamples(): readonly FrameSample[] { return this.samples; }
+
+ /** The pinned/queried frame's full breakdown, or null if it scrolled out. */
+ getSample(id: number): FrameSample | null {
+ for (let i = this.samples.length - 1; i >= 0; i--) if (this.samples[i].id === id) return this.samples[i];
+ return null;
+ }
+
+ /** Main-thread long tasks (GC / long JS) overlapping a frame's window — usually
+ * the cause of a spike the instrumented phases don't explain. Descending by ms. */
+ getFrameLongTasks(id: number): FrameLongTask[] {
+ const s = this.getSample(id);
+ if (!s) return [];
+ return this.longTasks
+ .filter((lt) => lt.start < s.t1 && lt.start + lt.ms > s.t0)
+ .map((lt) => ({ ms: r1(lt.ms), name: lt.name }))
+ .sort((a, b) => b.ms - a.ms);
+ }
+
+ /**
+ * Wire the per-frame engine telemetry source (edit App or the play iframe).
+ * `realm` labels where the numbers come from. Pass null to fold in editor
+ * phases only (no engine segment).
+ */
+ setEngineSource(source: (() => EngineFrame | null) | null, realm: 'edit' | 'play' = 'edit'): void {
+ this.engineSource = source;
+ this.realm = realm;
+ }
+
/** Time `fn` as a named frame phase (accumulates + emits a User Timing measure). */
measure<T>(phase: string, fn: () => T): T {
if (!this.enabled) return fn();
@@ -113,9 +291,14 @@ class PerfMonitorImpl {
try { performance.measure(`perf:${phase}`, { start: startMs, end }); } catch { /* ignore */ }
}
- /** Report a React commit's duration (from a <Profiler onRender>). */
- reactCommit(ms: number): void {
- if (this.enabled) this.phase['react.commit'] = (this.phase['react.commit'] ?? 0) + ms;
+ /** Report a React commit's duration, attributed to its panel (from a per-panel
+ * <Profiler onRender>). So a panel that stalls a frame (e.g. the Details tree
+ * rebuilding on selection) shows as `react.<id>` instead of the void. */
+ reactCommit(id: string, ms: number): void {
+ if (this.enabled) {
+ const key = `react.${id}`;
+ this.phase[key] = (this.phase[key] ?? 0) + ms;
+ }
}
subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);
@@ -125,31 +308,90 @@ class PerfMonitorImpl {
if (!this.running) return;
this.raf = requestAnimationFrame(this.loop);
- if (this.last) {
- const dt = now - this.last;
- this.frames.push(dt);
- if (this.frames.length > CAP) this.frames.shift();
- if (dt >= LONG_FRAME_MS) {
- this.longFrames += 1;
- if (dt > this.worstMs) {
- this.worstMs = dt;
- this.worstPhase = dominantPhase(this.phase)?.phase ?? 'other';
+ const prev = this.last;
+ this.last = now;
+ const editorPhases = this.phase;
+ this.phase = {};
+
+ // Frozen: hold the capture completely so the pinned frame stays put (the graph
+ // and sections read a static ring). First frame: no interval yet.
+ if (this.frozen || !prev) return;
+ const dt = now - prev;
+
+ this.frames.push(dt);
+ if (this.frames.length > CAP) this.frames.shift();
+ if (dt >= LONG_FRAME_MS) {
+ this.longFrames += 1;
+ if (dt > this.worstMs) {
+ this.worstMs = dt;
+ this.worstPhase = dominantPhase(editorPhases)?.phase ?? 'other';
+ }
+ }
+
+ if (this.enabled) {
+ // stat-unit ingest: editor phases + the engine's last frame.
+ const editorFrameMs = sumMs(editorPhases);
+ this.editorSum += editorFrameMs;
+ const ef = this.engineSource?.();
+ let engineFrameMs = 0;
+ let enginePhases: Record<string, number> = {};
+ let systemsFrame: Array<{ name: string; ms: number }> = [];
+ if (ef) {
+ enginePhases = ef.phaseMs;
+ engineFrameMs = sumMs(enginePhases);
+ this.engineSum += engineFrameMs;
+ for (const k in ef.systemMs) {
+ if (ef.systemMs[k] > (this.systemMax[k] ?? 0)) this.systemMax[k] = ef.systemMs[k];
}
+ systemsFrame = topSystems(ef.systemMs, 8).map((s) => ({ name: s.name, ms: r1(s.ms) }));
+ this.counters = { drawCalls: ef.drawCalls, triangles: ef.triangles, entities: ef.entities, gpuMs: ef.gpuMs };
+ }
+ this.winFrames += 1;
+
+ // Capture this frame's full breakdown so it can be inspected later.
+ const sample: FrameSample = {
+ id: this.sampleSeq++,
+ dt: r1(dt),
+ t0: prev,
+ t1: now,
+ engineMs: r1(engineFrameMs),
+ editorMs: r1(editorFrameMs),
+ gpuMs: this.counters.gpuMs >= 0 ? r1(this.counters.gpuMs) : -1,
+ editorPhases: { ...editorPhases },
+ enginePhases: { ...enginePhases },
+ systems: systemsFrame,
+ drawCalls: this.counters.drawCalls,
+ triangles: this.counters.triangles,
+ entities: this.counters.entities,
+ };
+ this.samples.push(sample);
+ if (this.samples.length > CAP) this.samples.shift();
+
+ // A hitch catches itself: freeze + pin so the culprit is right there.
+ if (this.autoHitch && dt >= HITCH_MS) {
+ this.pin(sample.id);
+ return;
}
}
- this.phase = {};
- this.last = now;
if (this.windowStart === 0) this.windowStart = now;
if (now - this.windowStart >= WINDOW_MS) {
const p50 = percentile(this.frames, 50);
+ const wf = this.winFrames || 1;
this.patch({
fps: p50 > 0 ? Math.round(1000 / p50) : 0,
p50: r1(p50), p95: r1(percentile(this.frames, 95)), p99: r1(percentile(this.frames, 99)),
longFrames: this.longFrames, worstMs: r1(this.worstMs), worstPhase: this.worstPhase, longTaskMs: r1(this.longTaskMs),
+ engineMs: r1(this.engineSum / wf), editorMs: r1(this.editorSum / wf),
+ drawCalls: this.counters.drawCalls, triangles: this.counters.triangles, entities: this.counters.entities,
+ systemsTop: topSystems(this.systemMax, 5).map((s) => ({ name: s.name, ms: r1(s.ms) })),
+ realm: this.realm,
+ gpuMs: this.counters.gpuMs >= 0 ? r1(this.counters.gpuMs) : -1,
+ frames: this.samples.map((s) => s.dt),
});
this.windowStart = now;
this.longFrames = 0; this.worstMs = 0; this.worstPhase = null; this.longTaskMs = 0;
+ this.engineSum = 0; this.editorSum = 0; this.winFrames = 0; this.systemMax = {};
}
};
diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.ts
index 20ecde56f..2eb1039b0 100644
--- a/desktop/src/engine/PlayRealm.ts
+++ b/desktop/src/engine/PlayRealm.ts
@@ -15,7 +15,7 @@ import { createStore } from 'zustand/vanilla';
import type { SubsystemStatus } from 'esengine';
import { LogStore } from '@/store/LogStore';
import { playProtocolMismatch } from './playProtocol';
-import type { PlayOutbound, PlayInbound, PlayPayload, PlaySnapshot } from './playProtocol';
+import type { PlayOutbound, PlayInbound, PlayPayload, PlaySnapshot, PlayStatsReply } from './playProtocol';
export type { PlayPayload, PlaySnapshot } from './playProtocol';
@@ -148,6 +148,18 @@ class PlayRealmImpl {
});
}
+ /** The running game's frame telemetry (phases/systems/counters) for the editor
+ * profiler's engine segment while playing. Null if not ready. */
+ stats(): Promise<PlayStatsReply | null> {
+ if (!this.iframe?.contentWindow || !this.store.getState().ready) return Promise.resolve(null);
+ const reqId = ++this.reqSeq;
+ return new Promise((resolve) => {
+ this.pending.set(reqId, (data) => resolve((data as PlayStatsReply) ?? null));
+ this.post({ type: 'estella:play:query', kind: 'stats', reqId });
+ setTimeout(() => { if (this.pending.delete(reqId)) resolve(null); }, 2000);
+ });
+ }
+
/** Live-edit a field of a running entity (debug; reverts on Stop). */
setField(entityId: number, comp: string, key: string, value: unknown): void {
this.post({ type: 'estella:play:setField', entityId, comp, key, value });
diff --git a/desktop/src/engine/Reconciler.ts b/desktop/src/engine/Reconciler.ts
index a7fbae009..99b280f65 100644
--- a/desktop/src/engine/Reconciler.ts
+++ b/desktop/src/engine/Reconciler.ts
@@ -4,6 +4,7 @@ import { Name, Parent, getComponent, resetWorldTo } from 'esengine';
import type { SceneData } from 'esengine';
import type { EntityId } from '@/types';
import { EngineHost } from './EngineHost';
+import { PerfMonitor } from './PerfMonitor';
import { SceneModel, SceneModelImpl, type ModelEvent } from './SceneModel';
import { componentByName, componentDefaults, isRenderComponent, componentEnable, type AnyComp, type WorldT } from './schema';
@@ -77,7 +78,9 @@ export class ReconcilerImpl {
/** Begin projecting model changes to the World. Idempotent. */
attach(): void {
if (this.unsubscribe) return;
- this.unsubscribe = this.model.subscribe((ev) => this.onEvent(ev));
+ // Time model→World projection as a profiler zone, so an edit that stalls a
+ // frame (a big reconcile) attributes to 'reconcile' instead of the void.
+ this.unsubscribe = this.model.subscribe((ev) => PerfMonitor.measure('reconcile', () => this.onEvent(ev)));
}
detach(): void {
@@ -118,9 +121,11 @@ export class ReconcilerImpl {
const world = EngineHost.mutableWorld();
const data = this.model.current;
if (!world || !data) return;
- const resolved = this.resolveRefs(data) as SceneData;
- const map = resetWorldTo(world, worldProjection(resolved) as never) as Map<number, EntityId>;
- this.model.adopt(data, map);
+ PerfMonitor.measure('world.rebuild', () => {
+ const resolved = this.resolveRefs(data) as SceneData;
+ const map = resetWorldTo(world, worldProjection(resolved) as never) as Map<number, EntityId>;
+ this.model.adopt(data, map);
+ });
}
// ── Event projection ──────────────────────────────────────────────────────
diff --git a/desktop/src/engine/SceneLoader.ts b/desktop/src/engine/SceneLoader.ts
index e240cb183..6b3b24e8d 100644
--- a/desktop/src/engine/SceneLoader.ts
+++ b/desktop/src/engine/SceneLoader.ts
@@ -5,6 +5,7 @@ import type { App, SceneData } from 'esengine';
import { SceneModel } from './SceneModel';
import { Reconciler } from './Reconciler';
import { EditorHistory } from './EditorHistory';
+import { PerfMonitor } from './PerfMonitor';
import { loadEditorSpine } from './spineLoad';
type SceneDataArg = Parameters<typeof loadSceneData>[1];
@@ -49,7 +50,7 @@ export const SceneLoader = {
Reconciler.setAssetResolver((uuid) => assets.getTexture(UUID_PREFIX + uuid)?.handle ?? 0);
}
- const map = loadSceneData(app.world, resolved as SceneDataArg);
+ const map = PerfMonitor.measure('scene.load', () => loadSceneData(app.world, resolved as SceneDataArg));
// Spine renders through its side modules, loaded separately from Assets (skel
// /atlas/textures + per-entity instances). Refs are the scene's own paths or
// @uuid: (resolved via the manifest).
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index e4ccc84e3..6cd617f07 100644
--- a/desktop/src/engine/playProtocol.ts
+++ b/desktop/src/engine/playProtocol.ts
@@ -55,6 +55,18 @@ export interface PlaySnapshot {
export type PlayQueryKind = 'snapshot' | 'subsystems' | 'stats';
+/** The running game's frame telemetry — reply payload of `query { kind: 'stats' }`.
+ * Feeds the editor profiler's engine segment while playing (PerfMonitor). */
+export interface PlayStatsReply {
+ phases: Record<string, number>;
+ systems: Record<string, number>;
+ drawCalls: number;
+ triangles: number;
+ sprites: number;
+ entities: number;
+ gpuMs: number;
+}
+
/** editor → realm. Discriminated by `type`. */
export type PlayOutbound =
| ({ type: 'estella:play:init' } & PlayPayload)
diff --git a/desktop/src/layout/ActivityBar.tsx b/desktop/src/layout/ActivityBar.tsx
index 80c203685..3be9c9452 100644
--- a/desktop/src/layout/ActivityBar.tsx
+++ b/desktop/src/layout/ActivityBar.tsx
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
// Far-left icon rail (activity bar). Reveals docked panels and toggles the
// Content Drawer — the summoned quick-access surface.
-import { ListTree, SlidersHorizontal, FolderOpen, Terminal, Clapperboard, Grid3x3, Settings } from 'lucide-react';
+import { ListTree, SlidersHorizontal, FolderOpen, Terminal, Clapperboard, Grid3x3, Gauge, Settings } from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import { dockApi } from '@/layout/dockApi';
import { commands } from '@/commands';
@@ -61,6 +61,14 @@ export function ActivityBar() {
>
<Grid3x3 size={19} strokeWidth={1.7} />
</button>
+ <button
+ type="button"
+ className="act"
+ title="Profiler"
+ onClick={() => dockApi.revealAndExpand('profiler')}
+ >
+ <Gauge size={19} strokeWidth={1.7} />
+ </button>
<span className="act-spacer" />
diff --git a/desktop/src/layout/DockLayout.tsx b/desktop/src/layout/DockLayout.tsx
index 5d369ed49..3d8acb8ac 100644
--- a/desktop/src/layout/DockLayout.tsx
+++ b/desktop/src/layout/DockLayout.tsx
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { useEffect, useState, type FC } from 'react';
+import { useEffect, useState, type FC, type ReactNode } from 'react';
import {
DockviewReact,
type DockviewReadyEvent,
@@ -18,21 +18,29 @@ import { Sequencer } from '@/panels/Sequencer';
import { TilesetEditor } from '@/panels/TilesetEditor';
import { TilemapPainter } from '@/panels/TilemapPainter';
import { MaterialGraphEditor } from '@/panels/MaterialGraphEditor';
+import { ProfilerPanel } from '@/panels/ProfilerPanel';
+import { Perf } from '@/components/Perf';
import { dockApi } from '@/layout/dockApi';
+// Each dock panel is wrapped so its commit time attributes to `react.<id>` — a
+// spike from one panel rebuilding (e.g. Details on selection) is named by panel,
+// not lumped into an unattributed frame.
+const panel = (id: string, node: ReactNode) => <Perf id={id}>{node}</Perf>;
+
// Each dock panel is a thin wrapper so dockview owns mount/unmount.
const components: Record<string, FC<IDockviewPanelProps>> = {
- outliner: () => <Outliner />,
- viewport: () => <Viewport />,
- details: () => <Details />,
- content: () => <ContentBrowser />,
- log: () => <OutputLog />,
- sequencer: () => <Sequencer />,
- tileset: () => <TilesetEditor />,
- tilemap: () => <TilemapPainter />,
- materialgraph: () => <MaterialGraphEditor />,
+ outliner: () => panel('outliner', <Outliner />),
+ viewport: () => panel('viewport', <Viewport />),
+ details: () => panel('details', <Details />),
+ content: () => panel('content', <ContentBrowser />),
+ log: () => panel('log', <OutputLog />),
+ sequencer: () => panel('sequencer', <Sequencer />),
+ tileset: () => panel('tileset', <TilesetEditor />),
+ tilemap: () => panel('tilemap', <TilemapPainter />),
+ materialgraph: () => panel('materialgraph', <MaterialGraphEditor />),
+ profiler: () => <ProfilerPanel />,
// The "Game" view (isolated play realm) — added on Play, removed on Stop.
- game: () => <GamePanel />,
+ game: () => panel('game', <GamePanel />),
};
// Bumped to v6 (document-area editors): Viewport center, right column Outliner-
@@ -86,6 +94,7 @@ function buildDefaultLayout(api: DockviewReadyEvent['api']) {
// Sequencer belongs in the bottom utility row (UE convention).
const BOTTOM_TABS: { id: string; component: string; title: string; refs: string[] }[] = [
{ id: 'sequencer', component: 'sequencer', title: 'Sequencer', refs: ['content', 'log'] },
+ { id: 'profiler', component: 'profiler', title: 'Profiler', refs: ['log', 'content'] },
];
function ensureBottomTabs(api: DockviewReadyEvent['api']) {
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index 78c7447b2..55be16d73 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -22,6 +22,7 @@ import './theme/log.css';
import './theme/viewport.css';
import './theme/content.css';
import './theme/sequencer.css';
+import './theme/profiler.css';
import './theme/tileset.css';
import './theme/tilemap.css';
import './theme/material.css';
diff --git a/desktop/src/panels/ProfilerPanel.tsx b/desktop/src/panels/ProfilerPanel.tsx
new file mode 100644
index 000000000..3dc4e1a2f
--- /dev/null
+++ b/desktop/src/panels/ProfilerPanel.tsx
@@ -0,0 +1,281 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ProfilerPanel.tsx — the dockable profiler (Unreal Insights analog).
+ *
+ * The full frame readout lives in a docked panel, not an overlay on the scene.
+ * Beyond the live window it captures every frame's full breakdown into a ring, so
+ * a hitch is inspectable AFTER the fact (the Insights scrub model, not pausing the
+ * app): click any bar in the history graph to freeze + pin that frame and see what
+ * cost it that frame; "Pause on hitch" auto-freezes the culprit when it happens.
+ */
+import { useSyncExternalStore, useRef, useEffect, useCallback } from 'react';
+import type { MouseEvent as ReactMouseEvent } from 'react';
+import { PerfMonitor } from '@/engine/PerfMonitor';
+
+const BUDGET_MS = 1000 / 60; // 60 Hz frame budget (16.6ms)
+const BUDGET_30 = 1000 / 30; // 30 Hz (33.3ms) — the hitch threshold
+
+function kfmt(n: number): string {
+ return n >= 1000 ? `${(n / 1000).toFixed(n >= 10000 ? 0 : 1)}k` : String(n);
+}
+
+const cssVar = (el: Element, name: string, fallback: string): string =>
+ getComputedStyle(el).getPropertyValue(name).trim() || fallback;
+
+/**
+ * Frame-time history — the Insights timeline analog: each recent frame as a bar,
+ * 60/30 Hz budgets as reference lines, hitches amber→red, the pinned frame marked.
+ * Click a bar to pin it. Canvas (not 240 DOM nodes) so the profiler never janks.
+ */
+function FrameGraph({ frames, pinnedId }: { frames: number[]; pinnedId: number | null }) {
+ const ref = useRef<HTMLCanvasElement>(null);
+
+ useEffect(() => {
+ const cv = ref.current;
+ if (!cv) return;
+ const w = cv.clientWidth;
+ const h = cv.clientHeight;
+ if (!w || !h) return;
+ const dpr = window.devicePixelRatio || 1;
+ cv.width = Math.round(w * dpr);
+ cv.height = Math.round(h * dpr);
+ const ctx = cv.getContext('2d');
+ if (!ctx) return;
+ ctx.scale(dpr, dpr);
+ ctx.clearRect(0, 0, w, h);
+
+ const accent = cssVar(cv, '--star', '#2f88d6');
+ const warn = cssVar(cv, '--warn', '#d3a23c');
+ const err = cssVar(cv, '--error', '#d3564b');
+ const grid = cssVar(cv, '--text-faint', '#696a71');
+ const hi = cssVar(cv, '--text-hi', '#e8e9eb');
+
+ let maxObserved = 0;
+ for (const f of frames) if (f > maxObserved) maxObserved = f;
+ const maxMs = Math.max(BUDGET_30 * 1.2, maxObserved * 1.1);
+ const yOf = (ms: number) => h - (Math.min(ms, maxMs) / maxMs) * h;
+
+ ctx.strokeStyle = grid;
+ ctx.globalAlpha = 0.5;
+ ctx.beginPath(); ctx.moveTo(0, yOf(BUDGET_MS)); ctx.lineTo(w, yOf(BUDGET_MS)); ctx.stroke();
+ ctx.setLineDash([3, 3]);
+ ctx.beginPath(); ctx.moveTo(0, yOf(BUDGET_30)); ctx.lineTo(w, yOf(BUDGET_30)); ctx.stroke();
+ ctx.setLineDash([]);
+ ctx.globalAlpha = 1;
+
+ const n = frames.length;
+ if (!n) return;
+ const bw = w / n;
+ // Index of the pinned frame within the (lockstep) capture ring, for the marker.
+ const samples = PerfMonitor.getSamples();
+ let pinnedIdx = -1;
+ if (pinnedId != null) for (let i = 0; i < samples.length; i++) if (samples[i].id === pinnedId) { pinnedIdx = i; break; }
+
+ for (let i = 0; i < n; i++) {
+ const ms = frames[i];
+ const y = yOf(ms);
+ ctx.fillStyle = ms >= BUDGET_30 ? err : ms >= BUDGET_MS * 1.05 ? warn : accent;
+ ctx.fillRect(i * bw, y, Math.max(1, bw - 0.4), h - y);
+ }
+ if (pinnedIdx >= 0) {
+ const x = pinnedIdx * bw + bw / 2;
+ ctx.strokeStyle = hi;
+ ctx.globalAlpha = 0.9;
+ ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke();
+ ctx.globalAlpha = 1;
+ }
+ }, [frames, pinnedId]);
+
+ const onClick = useCallback((e: ReactMouseEvent<HTMLCanvasElement>) => {
+ const cv = ref.current;
+ if (!cv) return;
+ const rect = cv.getBoundingClientRect();
+ const samples = PerfMonitor.getSamples();
+ const n = samples.length;
+ if (!n) return;
+ const i = Math.min(n - 1, Math.max(0, Math.floor(((e.clientX - rect.left) / rect.width) * n)));
+ PerfMonitor.pin(samples[i].id);
+ }, []);
+
+ return <canvas ref={ref} className="prof-graph" title="Click a frame to inspect it" onClick={onClick} />;
+}
+
+/** One "Frame = a + b + …" bar segment, width ∝ its share of the frame. */
+function Seg({ label, ms, frame, color }: { label: string; ms: number; frame: number; color: string }) {
+ const pct = frame > 0 ? Math.min(100, (ms / frame) * 100) : 0;
+ return (
+ <div className="prof-row">
+ <span className="prof-key" style={{ color }}>{label}</span>
+ <span className="prof-val">{ms.toFixed(1)}<span className="prof-unit">ms</span></span>
+ <span className="prof-bar"><span className="prof-fill" style={{ width: `${pct}%`, background: color }} /></span>
+ </div>
+ );
+}
+
+export function ProfilerPanel() {
+ const s = useSyncExternalStore(PerfMonitor.subscribe, PerfMonitor.getSnapshot);
+ const pinned = s.pinnedId != null ? PerfMonitor.getSample(s.pinnedId) : null;
+
+ // Sections read the pinned frame when one is inspected, else the live window.
+ const v = pinned
+ ? {
+ frameMs: pinned.dt, engineMs: pinned.engineMs, editorMs: pinned.editorMs, gpuMs: pinned.gpuMs,
+ drawCalls: pinned.drawCalls, triangles: pinned.triangles, entities: pinned.entities, systems: pinned.systems,
+ }
+ : {
+ frameMs: s.p50, engineMs: s.engineMs, editorMs: s.editorMs, gpuMs: s.gpuMs,
+ drawCalls: s.drawCalls, triangles: s.triangles, entities: s.entities, systems: s.systemsTop,
+ };
+ const frame = Math.max(v.frameMs, v.engineMs + v.editorMs);
+ const other = Math.max(0, frame - v.engineMs - v.editorMs);
+ const p99Bad = s.p99 >= BUDGET_MS * 1.5;
+
+ // Pinned-frame attribution (PP7): the long tasks that hit this frame (the usual
+ // cause of an un-instrumented spike) + every measured phase, ranked. `longTaskRev`
+ // on the snapshot re-runs this when a task arrives after the frame froze.
+ const longTasks = pinned ? PerfMonitor.getFrameLongTasks(pinned.id) : [];
+ const measuredMs = pinned ? pinned.engineMs + pinned.editorMs : 0;
+ const unattributedMs = pinned ? Math.max(0, pinned.dt - measuredMs) : 0;
+ const breakdown: Array<[string, number]> = pinned
+ ? [
+ ...Object.entries(pinned.editorPhases),
+ ...Object.entries(pinned.enginePhases).map(([n, m]) => [`engine.${n}`, m] as [string, number]),
+ ]
+ .filter(([, ms]) => ms >= 0.1)
+ .sort((a, b) => b[1] - a[1])
+ : [];
+
+ return (
+ <div className="prof">
+ {/* Capture controls — freeze/live + auto-freeze on hitch. */}
+ <div className="prof-controls">
+ <button
+ type="button"
+ className={`prof-btn${s.frozen ? ' on' : ''}`}
+ onClick={() => PerfMonitor.toggleFrozen()}
+ title={s.frozen ? 'Resume live capture' : 'Freeze capture to inspect frames'}
+ >
+ {s.frozen ? 'Live' : 'Pause'}
+ </button>
+ <label className="prof-check">
+ <input type="checkbox" checked={s.autoHitch} onChange={(e) => PerfMonitor.setAutoHitch(e.target.checked)} />
+ Pause on hitch
+ </label>
+ <span className="prof-spacer" />
+ {pinned ? (
+ <span className="prof-pinned">frame #{pinned.id} · {pinned.dt}ms</span>
+ ) : (
+ <span className="prof-live">live</span>
+ )}
+ </div>
+
+ {/* Frame timing — history graph + percentiles (live) or the pinned frame. */}
+ <section className="prof-sec">
+ <h4>Frame</h4>
+ <FrameGraph frames={s.frames} pinnedId={s.pinnedId} />
+ {pinned ? (
+ <div className="prof-budget">
+ inspecting frame #{pinned.id} · {pinned.dt}ms
+ {pinned.dt >= BUDGET_30 ? <span className="prof-warn"> · hitch</span> : null}
+ {' · '}<button type="button" className="prof-link" onClick={() => PerfMonitor.resumeLive()}>back to live</button>
+ </div>
+ ) : (
+ <>
+ <div className="prof-stat-grid">
+ <div><span>fps</span><b>{s.fps}</b></div>
+ <div><span>p50</span><b>{s.p50}<i>ms</i></b></div>
+ <div><span>p95</span><b>{s.p95}<i>ms</i></b></div>
+ <div><span>p99</span><b style={{ color: p99Bad ? 'var(--warn, #e5a33b)' : undefined }}>{s.p99}<i>ms</i></b></div>
+ </div>
+ <div className="prof-budget">
+ budget {BUDGET_MS.toFixed(1)}ms · {s.longFrames} long frame{s.longFrames === 1 ? '' : 's'}
+ {s.worstMs > 0 ? <> · worst {s.worstMs}ms <em>({s.worstPhase ?? 'other'})</em></> : null}
+ {s.longTaskMs > 0 ? <span className="prof-warn"> · long task {s.longTaskMs}ms (GC/JS)</span> : null}
+ </div>
+ </>
+ )}
+ </section>
+
+ {/* stat unit: Frame = engine (app.run) + editor (gizmo/react) + present/idle.
+ GPU is a parallel track (overlaps CPU), shown separately. */}
+ <section className="prof-sec">
+ <h4>Unit <span className="prof-realm">· {s.realm}</span></h4>
+ <Seg label="engine" ms={v.engineMs} frame={frame} color="var(--run, #46a04a)" />
+ <Seg label="editor" ms={v.editorMs} frame={frame} color="var(--star, #2f88d6)" />
+ <Seg label="present" ms={other} frame={frame} color="var(--text-mute, #888)" />
+ {v.gpuMs >= 0 ? (
+ <Seg label="gpu" ms={v.gpuMs} frame={frame} color="#3fb2b2" />
+ ) : (
+ <div className="prof-row">
+ <span className="prof-key">gpu</span>
+ <span className="prof-val prof-na">n/a</span>
+ <span className="prof-bar" />
+ </div>
+ )}
+ </section>
+
+ {/* Render counters — UE `stat scenerendering` analog. */}
+ <section className="prof-sec">
+ <h4>Render</h4>
+ <div className="prof-stat-grid">
+ <div><span>draw calls</span><b>{v.drawCalls}</b></div>
+ <div><span>triangles</span><b>{kfmt(v.triangles)}</b></div>
+ <div><span>entities</span><b>{v.entities}</b></div>
+ </div>
+ </section>
+
+ {/* Pinned-frame attribution: the long task that hit it (the usual spike
+ cause the phases can't name) + every measured phase, ranked. */}
+ {pinned ? (
+ <section className="prof-sec">
+ <h4>Breakdown · frame #{pinned.id}</h4>
+ {longTasks.map((lt, i) => {
+ // The dominant same-frame zone that plausibly IS this long task.
+ const cause = breakdown.find(([, ms]) => ms >= lt.ms * 0.5);
+ return (
+ <div className="prof-brk prof-lt" key={`lt${i}`}>
+ <span className="prof-brk-name" title={lt.name}>
+ ⚠ long task {cause ? <>→ <b>{cause[0]}</b></> : '· GC / uninstrumented JS'}
+ </span>
+ <span className="prof-brk-val">{lt.ms}ms</span>
+ </div>
+ );
+ })}
+ {breakdown.map(([name, ms]) => (
+ <div className="prof-brk" key={name}>
+ <span className="prof-brk-name" title={name}>{name}</span>
+ <span className="prof-brk-val">{ms.toFixed(1)}ms</span>
+ </div>
+ ))}
+ <div className="prof-budget">
+ measured {measuredMs.toFixed(1)}ms of {pinned.dt}ms
+ {unattributedMs >= 1 ? (
+ <em> · {unattributedMs.toFixed(1)}ms unattributed{longTasks.length ? '' : ' · browser paint / GC'}</em>
+ ) : null}
+ </div>
+ </section>
+ ) : null}
+
+ {/* Costliest engine systems — windowed max (live) or this frame's actual cost
+ (pinned), so a hitch names the system that caused it. UE `stat game`. */}
+ <section className="prof-sec">
+ <h4>Systems{pinned ? ' · this frame' : ''}</h4>
+ {v.systems.length ? (
+ <table className="prof-sys">
+ <tbody>
+ {v.systems.map((sys) => (
+ <tr key={sys.name}>
+ <td>{sys.name}</td>
+ <td className="prof-sys-ms">{sys.ms}<i>ms</i></td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ ) : (
+ <p className="prof-empty">No system timings yet.</p>
+ )}
+ </section>
+ </div>
+ );
+}
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index fe3d7e3df..d229894fa 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { Profiler, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
+import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import type { PointerEvent as ReactPointerEvent, DragEvent as ReactDragEvent, ReactNode } from 'react';
import {
MousePointer2, Move, RotateCw, Scale3d, Grid3x3, Eye, Frame,
@@ -670,7 +670,6 @@ export function Viewport() {
};
return (
- <Profiler id="viewport" onRender={(_id, _phase, actual) => PerfMonitor.reactCommit(actual)}>
<div className="viewport">
{/* Top-left: view menus (UE5 layout) — Show Flags dropdown + Frame. */}
<div className="ov ov-tl">
@@ -891,6 +890,5 @@ export function Viewport() {
{isPlaying && <div className="viewport__playflag">● PLAY</div>}
</div>
- </Profiler>
);
}
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index ad5c0b98f..e3bda4feb 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -323,10 +323,24 @@ window.addEventListener('message', (e: MessageEvent) => {
const reply = app ? liveSnapshot(app.world, data.selectedId ?? null) : null;
post({ type: 'estella:play:reply', reqId: data.reqId, data: reply });
} else if (data.kind === 'stats') {
- // Per-phase + per-system frame timing for the editor profiler panel.
+ // Per-phase + per-system timing + render counters — the running game's
+ // engine segment for the editor profiler (PerfMonitor, realm 'play').
const phases = app ? Object.fromEntries(app.getPhaseTimings() ?? []) : {};
const systems = app ? Object.fromEntries(app.getSystemTimings() ?? []) : {};
- post({ type: 'estella:play:reply', reqId: data.reqId, data: { phases, systems } });
+ const m = engineModule;
+ post({
+ type: 'estella:play:reply',
+ reqId: data.reqId,
+ data: {
+ phases,
+ systems,
+ drawCalls: m?.renderer_getDrawCalls?.() ?? 0,
+ triangles: m?.renderer_getTriangles?.() ?? 0,
+ sprites: m?.renderer_getSprites?.() ?? 0,
+ entities: app?.world.getAllEntities().length ?? 0,
+ gpuMs: m?.renderer_getGpuTimeMs?.() ?? -1,
+ },
+ });
} else if (data.kind === 'subsystems') {
// The running game's module health (for the editor's Modules indicator).
post({ type: 'estella:play:reply', reqId: data.reqId, data: app ? app.subsystems.getStatuses() : [] });
diff --git a/desktop/src/store/selectionStore.ts b/desktop/src/store/selectionStore.ts
index e1422191e..05fa21111 100644
--- a/desktop/src/store/selectionStore.ts
+++ b/desktop/src/store/selectionStore.ts
@@ -2,6 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { create } from 'zustand';
import { SceneModel, SceneModelImpl } from '@/engine/SceneModel';
+import { PerfMonitor } from '@/engine/PerfMonitor';
import type { EntityId } from '@/types';
/**
@@ -55,32 +56,38 @@ export function createSelectionStore(model: SceneModelImpl) {
selectedAsset: null,
// Selecting an entity clears the asset selection (unified inspector).
+ // Wrapped in a 'select' profiler zone: zustand notifies subscribers synchronously,
+ // so any non-React work a selection triggers is attributed here, not to the void.
select: (selectedId) =>
- set({
- selectedId,
- selectedIds: selectedId != null ? new Set([selectedId]) : new Set(),
- selectedAsset: null,
- }),
+ PerfMonitor.measure('select', () =>
+ set({
+ selectedId,
+ selectedIds: selectedId != null ? new Set([selectedId]) : new Set(),
+ selectedAsset: null,
+ }),
+ ),
toggleSelect: (id) =>
- set((s) => {
- const next = new Set(s.selectedIds);
- if (next.has(id)) {
- next.delete(id);
- const primary =
- s.selectedId === id ? (next.size ? [...next][next.size - 1] : null) : s.selectedId;
- return { selectedIds: next, selectedId: primary, selectedAsset: null };
- }
- next.add(id);
- return { selectedIds: next, selectedId: id, selectedAsset: null };
- }),
+ PerfMonitor.measure('select', () =>
+ set((s) => {
+ const next = new Set(s.selectedIds);
+ if (next.has(id)) {
+ next.delete(id);
+ const primary =
+ s.selectedId === id ? (next.size ? [...next][next.size - 1] : null) : s.selectedId;
+ return { selectedIds: next, selectedId: primary, selectedAsset: null };
+ }
+ next.add(id);
+ return { selectedIds: next, selectedId: id, selectedAsset: null };
+ }),
+ ),
selectMany: (ids, primary) =>
- set({ selectedIds: new Set(ids), selectedId: primary, selectedAsset: null }),
+ PerfMonitor.measure('select', () => set({ selectedIds: new Set(ids), selectedId: primary, selectedAsset: null })),
// Selecting an asset clears any entity selection (mutually exclusive).
selectAsset: (selectedAsset) =>
- set({ selectedAsset, selectedId: null, selectedIds: new Set() }),
+ PerfMonitor.measure('select', () => set({ selectedAsset, selectedId: null, selectedIds: new Set() })),
dropId: (id) =>
set((s) => {
diff --git a/desktop/src/theme/profiler.css b/desktop/src/theme/profiler.css
new file mode 100644
index 000000000..57b0de7cc
--- /dev/null
+++ b/desktop/src/theme/profiler.css
@@ -0,0 +1,123 @@
+/* SPDX-License-Identifier: Apache-2.0
+ Profiler panel — the docked frame readout (Unreal Insights analog). Derives
+ from tokens.css; kept visually quiet so it reads as instrumentation. */
+
+.prof {
+ height: 100%;
+ overflow: auto;
+ padding: 10px 12px;
+ font: var(--fs-xs, 11px) var(--mono, ui-monospace, monospace);
+ color: var(--text-dim);
+ background: var(--panel);
+}
+
+.prof-sec {
+ padding: 8px 0;
+ border-bottom: 1px solid var(--border-line);
+}
+.prof-sec:last-child { border-bottom: 0; }
+
+.prof-sec h4 {
+ margin: 0 0 7px;
+ font-size: 10px;
+ font-weight: 600;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--text-mute);
+}
+.prof-realm { text-transform: none; letter-spacing: 0; color: var(--text-faint); }
+
+/* Frame-time history graph (Insights timeline analog). */
+.prof-graph {
+ display: block;
+ width: 100%;
+ height: 56px;
+ margin-bottom: 8px;
+ border-radius: var(--r-md, 4px);
+ background: var(--srf-1, rgba(0, 0, 0, 0.22));
+ border: 1px solid var(--border-line);
+ cursor: crosshair; /* click a frame to inspect it */
+}
+
+/* Capture controls (freeze / live / pause-on-hitch). */
+.prof-controls {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding-bottom: 8px;
+ border-bottom: 1px solid var(--border-line);
+}
+.prof-spacer { flex: 1; }
+.prof-btn {
+ font: 600 var(--fs-xs, 11px) var(--mono, ui-monospace, monospace);
+ color: var(--text);
+ background: var(--srf-1, rgba(255, 255, 255, 0.05));
+ border: 1px solid var(--border-line);
+ border-radius: var(--r-md, 4px);
+ padding: 2px 10px;
+ cursor: pointer;
+}
+.prof-btn:hover { color: var(--text-hi); border-color: var(--star-line, var(--star)); }
+.prof-btn.on { color: var(--star-hi, var(--star)); border-color: var(--star); } /* frozen → "Live" is armed */
+.prof-check { display: flex; align-items: center; gap: 4px; color: var(--text-mute); cursor: pointer; }
+.prof-check input { accent-color: var(--star); }
+.prof-live { color: var(--run, #46a04a); }
+.prof-pinned { color: var(--star-hi, var(--star)); }
+.prof-link {
+ background: none; border: 0; padding: 0; cursor: pointer;
+ color: var(--star-hi, var(--star)); font: inherit; text-decoration: underline;
+}
+
+/* fps / p50 / p95 / p99 and render counters — a compact label-over-value grid. */
+.prof-stat-grid {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 4px 10px;
+}
+.prof-stat-grid > div { display: flex; flex-direction: column; gap: 1px; }
+.prof-stat-grid span { color: var(--text-mute); font-size: 10px; }
+.prof-stat-grid b { color: var(--text-hi); font-weight: 600; font-size: 13px; }
+.prof-stat-grid i { color: var(--text-faint); font-style: normal; font-size: 10px; margin-left: 1px; }
+
+/* stat-unit bars: label · value · proportional fill. */
+.prof-row { display: grid; grid-template-columns: 4.5em 4em 1fr; align-items: center; gap: 8px; margin: 3px 0; }
+.prof-key { font-weight: 600; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.prof-val { color: var(--text-hi); text-align: right; }
+.prof-na { color: var(--text-faint); }
+.prof-unit { color: var(--text-faint); margin-left: 1px; }
+.prof-bar { height: 6px; border-radius: 3px; background: var(--srf-1, rgba(255, 255, 255, 0.05)); overflow: hidden; }
+.prof-fill { display: block; height: 100%; border-radius: 3px; transition: width 0.25s var(--e-out, ease-out); }
+
+/* Pinned-frame breakdown rows — name (ellipsis) + right-aligned value, so the two
+ never collide however long the zone/system name is. */
+.prof-brk {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ gap: 10px;
+ align-items: baseline;
+ margin: 2px 0;
+}
+.prof-brk-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text); }
+.prof-brk-val { color: var(--text-hi); font-variant-numeric: tabular-nums; white-space: nowrap; }
+.prof-brk.prof-lt .prof-brk-name,
+.prof-brk.prof-lt .prof-brk-val { color: var(--warn); }
+.prof-brk-name b { color: var(--text-hi); font-weight: 600; }
+
+.prof-budget { margin-top: 7px; color: var(--text-mute); }
+.prof-budget em { font-style: normal; color: var(--text-faint); }
+.prof-warn { color: var(--warn); }
+
+.prof-sys { width: 100%; table-layout: fixed; border-collapse: collapse; }
+.prof-sys td { padding: 2px 0; color: var(--text-dim); }
+.prof-sys td:first-child {
+ color: var(--text);
+ max-width: 0; /* with table-layout:fixed, lets the name cell ellipsize */
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ padding-right: 10px;
+}
+.prof-sys-ms { width: 5em; text-align: right; color: var(--text-hi); font-variant-numeric: tabular-nums; white-space: nowrap; }
+.prof-sys-ms i { color: var(--text-faint); font-style: normal; margin-left: 1px; }
+
+.prof-empty { color: var(--text-faint); margin: 2px 0 0; }
diff --git a/desktop/tests/perf-monitor.test.ts b/desktop/tests/perf-monitor.test.ts
index 562f130a0..80874f85b 100644
--- a/desktop/tests/perf-monitor.test.ts
+++ b/desktop/tests/perf-monitor.test.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect } from 'vitest';
-import { percentile, dominantPhase } from '@/engine/PerfMonitor';
+import { percentile, dominantPhase, sumMs, topSystems } from '@/engine/PerfMonitor';
describe('percentile', () => {
const v = Array.from({ length: 100 }, (_, i) => i + 1); // 1..100
@@ -26,3 +26,18 @@ describe('dominantPhase', () => {
});
it('is null for no phases', () => expect(dominantPhase({})).toBeNull());
});
+
+describe('sumMs', () => {
+ it('sums a timing map', () => expect(sumMs({ a: 1.5, b: 2, c: 0.5 })).toBe(4));
+ it('is 0 for an empty map', () => expect(sumMs({})).toBe(0));
+});
+
+describe('topSystems', () => {
+ it('returns the n costliest, descending', () => {
+ const got = topSystems({ Render: 3, Physics: 8, Animation: 1, UI: 5 }, 2);
+ expect(got).toEqual([{ name: 'Physics', ms: 8 }, { name: 'UI', ms: 5 }]);
+ });
+ it('caps at the map size', () => {
+ expect(topSystems({ a: 1 }, 5)).toEqual([{ name: 'a', ms: 1 }]);
+ });
+});