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): profiler memory pillar + stat groups

esenginec38ee44e2edb
diff --git a/desktop/src/components/Perf.tsx b/desktop/src/components/Perf.tsx
index 27c0785ff..59c87244e 100644
--- a/desktop/src/components/Perf.tsx
+++ b/desktop/src/components/Perf.tsx
@@ -1,12 +1,8 @@
// 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.
+ * @file Perf.tsx — `<Perf id="x">` reports its subtree's React commit time as
+ * `react.x`. Wrap each independently-committing region (never nest siblings).
*/
import { Profiler, type ReactNode } from 'react';
import { PerfMonitor } from '@/engine/PerfMonitor';
diff --git a/desktop/src/components/PerfOverlay.tsx b/desktop/src/components/PerfOverlay.tsx
index 6eea43296..bcc28f112 100644
--- a/desktop/src/components/PerfOverlay.tsx
+++ b/desktop/src/components/PerfOverlay.tsx
@@ -1,13 +1,8 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file PerfOverlay.tsx — the viewport fps glance (View ▸ Perf).
- *
- * 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.
+ * @file PerfOverlay.tsx — a tiny fps glance in the viewport corner; the detail
+ * lives in the dockable Profiler panel. Leaf subscriber (no viewport re-render).
*/
import { useSyncExternalStore } from 'react';
import { PerfMonitor } from '@/engine/PerfMonitor';
diff --git a/desktop/src/components/PerfRealmBridge.tsx b/desktop/src/components/PerfRealmBridge.tsx
index 148dc6420..f0587f7cc 100644
--- a/desktop/src/components/PerfRealmBridge.tsx
+++ b/desktop/src/components/PerfRealmBridge.tsx
@@ -1,15 +1,8 @@
// 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).
+ * @file PerfRealmBridge.tsx — routes PerfMonitor's engine source to the edit App
+ * or, while playing, the play iframe (polled into a cache read synchronously).
*/
import { useSyncExternalStore, useEffect } from 'react';
import { EngineHost } from '@/engine/EngineHost';
@@ -32,7 +25,7 @@ export function PerfRealmBridge() {
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, cppScopes: s.cppScopes }
+ ? { phaseMs: s.phases, systemMs: s.systems, drawCalls: s.drawCalls, triangles: s.triangles, sprites: s.sprites, entities: s.entities, gpuMs: s.gpuMs, cppScopes: s.cppScopes, wasmBytes: s.wasmBytes, vramBytes: s.vramBytes }
: null;
};
void poll();
diff --git a/desktop/src/engine/EngineHost.ts b/desktop/src/engine/EngineHost.ts
index 2981abd6d..4a315760b 100644
--- a/desktop/src/engine/EngineHost.ts
+++ b/desktop/src/engine/EngineHost.ts
@@ -108,12 +108,7 @@ 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.
- */
+ /** The engine's last-frame telemetry for the profiler; null until booted. */
readEngineFrame(): {
phaseMs: Record<string, number>;
systemMs: Record<string, number>;
@@ -123,6 +118,8 @@ class EngineHostImpl {
entities: number;
gpuMs: number;
cppScopes: Record<string, number>;
+ wasmBytes: number;
+ vramBytes: number;
} | null {
const app = this.app_;
if (!app) return null;
@@ -143,6 +140,8 @@ class EngineHostImpl {
entities: this.world?.getAllEntities().length ?? 0,
gpuMs: m?.renderer_getGpuTimeMs?.() ?? -1,
cppScopes,
+ wasmBytes: m?.HEAPU8?.byteLength ?? 0,
+ vramBytes: m?.renderer_getTextureBytes?.() ?? 0,
};
}
@@ -432,11 +431,7 @@ 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();
- // Per-frame C++ CPU scope profiling (render passes → `cpp.*` in the breakdown).
module.engine_setCpuProfiling?.(true);
// Subsystem observability: phase changes push immediately; the sampler
diff --git a/desktop/src/engine/PerfMonitor.ts b/desktop/src/engine/PerfMonitor.ts
index 89379031d..c374e6ba8 100644
--- a/desktop/src/engine/PerfMonitor.ts
+++ b/desktop/src/engine/PerfMonitor.ts
@@ -1,17 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file PerfMonitor.ts — the editor's frame instrumentation.
- *
- * One place every per-frame phase reports into, so viewport jank is an
- * ATTRIBUTED measurement, not a guess:
- * - measure(phase, fn) / mark(phase, t0) time a phase, accumulate it per frame,
- * and emit a User Timing measure (labeled tracks in the DevTools Performance
- * panel).
- * - a rAF samples the real frame interval → p50/p95/p99 + dropped-frame count,
- * and attributes each long frame to its dominant phase.
- * - a PerformanceObserver surfaces main-thread long tasks (GC / long JS).
- * Near-free when disabled (the timers short-circuit). Drives the Perf overlay.
+ * @file PerfMonitor.ts — the editor's per-frame instrumentation hub.
*/
import { createStore } from 'zustand/vanilla';
@@ -33,14 +23,12 @@ 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 }))
@@ -48,11 +36,8 @@ export function topSystems(rec: Record<string, number>, n: number): Array<{ name
.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).
- */
+/** The engine's last-frame telemetry, supplied by a source callback so PerfMonitor
+ * stays decoupled from the engine host. */
export interface EngineFrame {
phaseMs: Record<string, number>;
systemMs: Record<string, number>;
@@ -64,26 +49,24 @@ export interface EngineFrame {
gpuMs: number;
/** Per-frame C++ CPU scopes (render passes etc.), name → ms — the `cpp.*` rows. */
cppScopes: Record<string, number>;
+ /** Total wasm linear memory (bytes) — the engine's heap. */
+ wasmBytes: number;
+ /** Resident texture VRAM (bytes, estimate). */
+ vramBytes: 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.
- */
+/** One frame's full per-frame breakdown, kept in a ring so any past frame can be
+ * inspected after the fact. */
export interface FrameSample {
- id: number; // monotonic frame id (stable across ring scroll)
+ id: number;
dt: number;
- /** Frame window on the performance timeline, for correlating long tasks. */
- t0: number;
+ t0: number; // frame window on the performance timeline (for long-task overlap)
t1: number;
engineMs: number;
editorMs: number;
gpuMs: number;
editorPhases: Record<string, number>;
enginePhases: Record<string, number>;
- /** C++ CPU scopes for this frame (render.collect/submit/…), name → ms. */
cppScopes: Record<string, number>;
systems: Array<{ name: string; ms: number }>;
drawCalls: number;
@@ -91,9 +74,6 @@ export interface FrameSample {
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;
@@ -112,12 +92,8 @@ 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;
@@ -129,16 +105,18 @@ export interface PerfSnapshot {
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. */
+ /** Bumps when a long task arrives, so a frozen pinned view refreshes to include it. */
longTaskRev: number;
+ wasmMB: number;
+ jsHeapMB: number;
+ jsHeapLimitMB: number;
+ vramMB: number;
+ /** Recent memory samples (oldest→newest) for the memory graph. */
+ memHist: Array<{ wasm: number; js: number; vram: number }>;
}
const LONG_FRAME_MS = 24; // missed a 60Hz frame
@@ -152,6 +130,7 @@ class PerfMonitorImpl {
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,
+ wasmMB: 0, jsHeapMB: 0, jsHeapLimitMB: 0, vramMB: 0, memHist: [],
}));
private enabled = true;
private running = false;
@@ -165,21 +144,19 @@ 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 mem = { wasmBytes: 0, vramBytes: 0 };
+ private readonly memHist: Array<{ wasm: number; js: number; vram: number }> = [];
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;
@@ -215,9 +192,7 @@ 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). */
+ /** Freeze the rolling capture and pin a frame for inspection. */
pin(id: number): void {
this.frozen = true;
// Snapshot the static ring's dt into `frames` so the graph holds at this moment.
@@ -276,7 +251,7 @@ class PerfMonitorImpl {
this.realm = realm;
}
- /** Time `fn` as a named frame phase (accumulates + emits a User Timing measure). */
+ /** Time `fn` as a named frame phase. */
measure<T>(phase: string, fn: () => T): T {
if (!this.enabled) return fn();
const t0 = performance.now();
@@ -287,7 +262,7 @@ class PerfMonitorImpl {
}
}
- /** Record a phase that ran from `startMs` to now (accumulate + User Timing). */
+ /** Record a phase that ran from `startMs` to now. */
mark(phase: string, startMs: number): void {
if (!this.enabled) return;
const end = performance.now();
@@ -333,7 +308,6 @@ class PerfMonitorImpl {
}
if (this.enabled) {
- // stat-unit ingest: editor phases + the engine's last frame.
const editorFrameMs = sumMs(editorPhases);
this.editorSum += editorFrameMs;
const ef = this.engineSource?.();
@@ -351,6 +325,7 @@ class PerfMonitorImpl {
}
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.mem = { wasmBytes: ef.wasmBytes, vramBytes: ef.vramBytes };
}
this.winFrames += 1;
@@ -385,6 +360,14 @@ class PerfMonitorImpl {
if (now - this.windowStart >= WINDOW_MS) {
const p50 = percentile(this.frames, 50);
const wf = this.winFrames || 1;
+ const MB = 1 / (1024 * 1024);
+ const jsMem = (performance as Performance & { memory?: { usedJSHeapSize: number; jsHeapSizeLimit: number } }).memory;
+ const wasmMB = r1(this.mem.wasmBytes * MB);
+ const vramMB = r1(this.mem.vramBytes * MB);
+ const jsHeapMB = jsMem ? r1(jsMem.usedJSHeapSize * MB) : 0;
+ const jsHeapLimitMB = jsMem ? Math.round(jsMem.jsHeapSizeLimit * MB) : 0;
+ this.memHist.push({ wasm: wasmMB, js: jsHeapMB, vram: vramMB });
+ if (this.memHist.length > CAP) this.memHist.shift();
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)),
@@ -395,6 +378,7 @@ class PerfMonitorImpl {
realm: this.realm,
gpuMs: this.counters.gpuMs >= 0 ? r1(this.counters.gpuMs) : -1,
frames: this.samples.map((s) => s.dt),
+ wasmMB, jsHeapMB, jsHeapLimitMB, vramMB, memHist: this.memHist.slice(),
});
this.windowStart = now;
this.longFrames = 0; this.worstMs = 0; this.worstPhase = null; this.longTaskMs = 0;
diff --git a/desktop/src/engine/Reconciler.ts b/desktop/src/engine/Reconciler.ts
index 99b280f65..548ff3aaa 100644
--- a/desktop/src/engine/Reconciler.ts
+++ b/desktop/src/engine/Reconciler.ts
@@ -78,8 +78,6 @@ export class ReconcilerImpl {
/** Begin projecting model changes to the World. Idempotent. */
attach(): void {
if (this.unsubscribe) return;
- // 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)));
}
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index 7dde6a03b..6480197a9 100644
--- a/desktop/src/engine/playProtocol.ts
+++ b/desktop/src/engine/playProtocol.ts
@@ -66,6 +66,8 @@ export interface PlayStatsReply {
entities: number;
gpuMs: number;
cppScopes: Record<string, number>;
+ wasmBytes: number;
+ vramBytes: number;
}
/** editor → realm. Discriminated by `type`. */
diff --git a/desktop/src/layout/DockLayout.tsx b/desktop/src/layout/DockLayout.tsx
index 3d8acb8ac..83d0eb99f 100644
--- a/desktop/src/layout/DockLayout.tsx
+++ b/desktop/src/layout/DockLayout.tsx
@@ -22,9 +22,6 @@ 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.
diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsx
index a370eecbd..d1faf0342 100644
--- a/desktop/src/panels/Outliner.tsx
+++ b/desktop/src/panels/Outliner.tsx
@@ -24,8 +24,7 @@ import { CreatePopover } from '@/components/CreatePopover';
// Must match .row height in outliner.css — the fixed row size the virtual list windows by.
const ROW_H = 24;
const NO_EXPANSION: ReadonlySet<string> = new Set();
-// Stable references for the read-only game tree, so its memoized rows re-render
-// only on a selection change of the affected row (not the whole window).
+// Stable props so the memoized game-tree rows don't all re-render on selection.
const GAME_COLUMNS = [TYPE_COLUMN];
const EMPTY_COL_CTX: OutlinerColumnContext = {};
const NOOP = () => {};
@@ -535,11 +534,7 @@ export function Outliner() {
// between the edit scene and the live running game.
const gameMode = inspectWorld === 'game';
- // OutlinerRow is memoized, so it must get referentially-stable handlers or every
- // visible row re-renders on any parent render (e.g. a selection change → the whole
- // window rebuilds, ~38ms). These wrappers never change identity yet always call the
- // latest closure (latest-ref), so a selection change re-renders ONLY the rows whose
- // `selected`/`cursored` actually flipped.
+ // Stable handlers (latest-ref) so the memoized rows skip on a selection change.
const rowFns = {
onRowClick, onContextMenu, onStartRename, commitRename, onDragStartRow, onDragOverRow, onDropRow,
onDragEnd: () => { dragIds.current = null; dragFolder.current = null; setDrop(null); },
diff --git a/desktop/src/panels/ProfilerPanel.tsx b/desktop/src/panels/ProfilerPanel.tsx
index b3bcedfe2..310146955 100644
--- a/desktop/src/panels/ProfilerPanel.tsx
+++ b/desktop/src/panels/ProfilerPanel.tsx
@@ -1,15 +1,9 @@
// 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.
+ * @file ProfilerPanel.tsx — the dockable profiler panel.
*/
-import { useSyncExternalStore, useRef, useEffect, useCallback } from 'react';
+import { useSyncExternalStore, useRef, useEffect, useCallback, useState } from 'react';
import type { MouseEvent as ReactMouseEvent } from 'react';
import { PerfMonitor } from '@/engine/PerfMonitor';
@@ -23,11 +17,71 @@ function kfmt(n: number): string {
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.
- */
+const GROUPS = [
+ { id: 'frame', label: 'Frame' },
+ { id: 'unit', label: 'CPU/GPU' },
+ { id: 'render', label: 'Render' },
+ { id: 'memory', label: 'Memory' },
+ { id: 'systems', label: 'Systems' },
+] as const;
+const GROUPS_KEY = 'estella.profiler.hiddenGroups';
+
+function useHiddenGroups(): [Set<string>, (id: string) => void] {
+ const [hidden, setHidden] = useState<Set<string>>(() => {
+ try { return new Set(JSON.parse(localStorage.getItem(GROUPS_KEY) ?? '[]') as string[]); } catch { return new Set(); }
+ });
+ const toggle = useCallback((id: string) => {
+ setHidden((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id); else next.add(id);
+ localStorage.setItem(GROUPS_KEY, JSON.stringify([...next]));
+ return next;
+ });
+ }, []);
+ return [hidden, toggle];
+}
+
+/** Memory over time — wasm heap / JS heap / texture VRAM as autoscaled lines. */
+function MemGraph({ hist }: { hist: Array<{ wasm: number; js: number; vram: number }> }) {
+ 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 n = hist.length;
+ if (!n) return;
+ let max = 1;
+ for (const m of hist) max = Math.max(max, m.wasm, m.js, m.vram);
+ const colors = { wasm: cssVar(cv, '--warn', '#d3a23c'), js: cssVar(cv, '--star', '#2f88d6'), vram: '#3fb2b2' };
+ const line = (key: 'wasm' | 'js' | 'vram') => {
+ ctx.strokeStyle = colors[key];
+ ctx.lineWidth = 1.25;
+ ctx.beginPath();
+ for (let i = 0; i < n; i++) {
+ const x = (i / (n - 1 || 1)) * w;
+ const y = h - (hist[i][key] / max) * h;
+ if (i) ctx.lineTo(x, y); else ctx.moveTo(x, y);
+ }
+ ctx.stroke();
+ };
+ line('wasm');
+ line('vram');
+ line('js');
+ }, [hist]);
+ return <canvas ref={ref} className="prof-graph" />;
+}
+
+/** Frame-time history: each recent frame as a bar with 60/30 Hz budget lines,
+ * hitches amber→red, the pinned frame marked. Click a bar to pin it. */
function FrameGraph({ frames, pinnedId }: { frames: number[]; pinnedId: number | null }) {
const ref = useRef<HTMLCanvasElement>(null);
@@ -116,6 +170,8 @@ function Seg({ label, ms, frame, color }: { label: string; ms: number; frame: nu
export function ProfilerPanel() {
const s = useSyncExternalStore(PerfMonitor.subscribe, PerfMonitor.getSnapshot);
const pinned = s.pinnedId != null ? PerfMonitor.getSample(s.pinnedId) : null;
+ const [hidden, toggleGroup] = useHiddenGroups();
+ const show = (id: string) => !hidden.has(id);
// Sections read the pinned frame when one is inspected, else the live window.
const v = pinned
@@ -135,9 +191,7 @@ export function ProfilerPanel() {
const isIdle = v.frameMs <= BUDGET_MS * 1.25;
const presentLabel = isIdle ? 'idle' : 'present';
- // 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.
+ // The long tasks that hit the pinned frame + its measured phases, ranked.
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;
@@ -175,7 +229,21 @@ export function ProfilerPanel() {
)}
</div>
+ <div className="prof-groups">
+ {GROUPS.map((g) => (
+ <button
+ key={g.id}
+ type="button"
+ className={`prof-chip${hidden.has(g.id) ? '' : ' on'}`}
+ onClick={() => toggleGroup(g.id)}
+ >
+ {g.label}
+ </button>
+ ))}
+ </div>
+
{/* Frame timing — history graph + percentiles (live) or the pinned frame. */}
+ {show('frame') && (
<section className="prof-sec">
<h4>Frame</h4>
<FrameGraph frames={s.frames} pinnedId={s.pinnedId} />
@@ -201,9 +269,10 @@ export function ProfilerPanel() {
</>
)}
</section>
+ )}
- {/* stat unit: Frame = engine (app.run) + editor (gizmo/react) + present/idle.
- GPU is a parallel track (overlaps CPU), shown separately. */}
+ {/* Frame = engine + editor + present; GPU is a parallel track. */}
+ {show('unit') && (
<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)" />
@@ -219,8 +288,9 @@ export function ProfilerPanel() {
</div>
)}
</section>
+ )}
- {/* Render counters — UE `stat scenerendering` analog. */}
+ {show('render') && (
<section className="prof-sec">
<h4>Render</h4>
<div className="prof-stat-grid">
@@ -229,6 +299,20 @@ export function ProfilerPanel() {
<div><span>entities</span><b>{v.entities}</b></div>
</div>
</section>
+ )}
+
+ {show('memory') && (
+ <section className="prof-sec">
+ <h4>Memory</h4>
+ <MemGraph hist={s.memHist} />
+ <div className="prof-stat-grid">
+ <div><span style={{ color: 'var(--warn, #d3a23c)' }}>wasm</span><b>{s.wasmMB}<i>MB</i></b></div>
+ <div><span style={{ color: 'var(--star, #2f88d6)' }}>js heap</span><b>{s.jsHeapMB || '—'}<i>{s.jsHeapMB ? 'MB' : ''}</i></b></div>
+ <div><span style={{ color: '#3fb2b2' }}>vram</span><b>{s.vramMB}<i>MB</i></b></div>
+ </div>
+ {s.jsHeapLimitMB ? <div className="prof-budget">js heap limit {s.jsHeapLimitMB}MB</div> : null}
+ </section>
+ )}
{/* Pinned-frame attribution: the long task that hit it (the usual spike
cause the phases can't name) + every measured phase, ranked. */}
@@ -262,8 +346,8 @@ export function ProfilerPanel() {
</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`. */}
+ {/* Costliest engine systems — windowed max (live) or this frame's cost (pinned). */}
+ {show('systems') && (
<section className="prof-sec">
<h4>Systems{pinned ? ' · this frame' : ''}</h4>
{v.systems.length ? (
@@ -281,6 +365,7 @@ export function ProfilerPanel() {
<p className="prof-empty">No system timings yet.</p>
)}
</section>
+ )}
</div>
);
}
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index a0c52069f..560184f15 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -155,7 +155,7 @@ async function ensureEngine(): Promise<void> {
}) as WebGL2RenderingContext | null;
if (!gl) throw new Error('WebGL2 is not available in this realm.');
glHandle = module.GL.registerContext(gl, { majorVersion: 2, minorVersion: 0, enableExtensionsByDefault: true });
- module.engine_setCpuProfiling?.(true); // C++ scope profiling for the editor profiler
+ module.engine_setCpuProfiling?.(true);
engineModule = module;
}
@@ -348,6 +348,8 @@ window.addEventListener('message', (e: MessageEvent) => {
entities: app?.world.getAllEntities().length ?? 0,
gpuMs: m?.renderer_getGpuTimeMs?.() ?? -1,
cppScopes: parseCppScopes(m),
+ wasmBytes: m?.HEAPU8?.byteLength ?? 0,
+ vramBytes: m?.renderer_getTextureBytes?.() ?? 0,
},
});
} else if (data.kind === 'subsystems') {
diff --git a/desktop/src/store/selectionStore.ts b/desktop/src/store/selectionStore.ts
index 05fa21111..5a859169f 100644
--- a/desktop/src/store/selectionStore.ts
+++ b/desktop/src/store/selectionStore.ts
@@ -55,9 +55,7 @@ export function createSelectionStore(model: SceneModelImpl) {
selectedIds: new Set<EntityId>(),
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' zone captures the synchronous subscriber work a selection triggers.
select: (selectedId) =>
PerfMonitor.measure('select', () =>
set({
diff --git a/desktop/src/theme/profiler.css b/desktop/src/theme/profiler.css
index 57b0de7cc..51a09ba96 100644
--- a/desktop/src/theme/profiler.css
+++ b/desktop/src/theme/profiler.css
@@ -1,6 +1,5 @@
/* 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. */
+ Profiler panel styles. Derives from tokens.css. */
.prof {
height: 100%;
@@ -27,7 +26,7 @@
}
.prof-realm { text-transform: none; letter-spacing: 0; color: var(--text-faint); }
-/* Frame-time history graph (Insights timeline analog). */
+/* Frame-time history graph. */
.prof-graph {
display: block;
width: 100%;
@@ -63,6 +62,26 @@
.prof-check input { accent-color: var(--star); }
.prof-live { color: var(--run, #46a04a); }
.prof-pinned { color: var(--star-hi, var(--star)); }
+
+/* Stat-group toggle chips. */
+.prof-groups {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ padding: 7px 0;
+ border-bottom: 1px solid var(--border-line);
+}
+.prof-chip {
+ font: var(--fs-xs, 11px) var(--mono, ui-monospace, monospace);
+ color: var(--text-faint);
+ background: transparent;
+ border: 1px solid var(--border-line);
+ border-radius: 999px;
+ padding: 1px 9px;
+ cursor: pointer;
+}
+.prof-chip:hover { color: var(--text); }
+.prof-chip.on { color: var(--text-hi); border-color: var(--star-line, var(--star)); background: var(--star-dim, rgba(47, 136, 214, 0.18)); }
.prof-link {
background: none; border: 0; padding: 0; cursor: pointer;
color: var(--star-hi, var(--star)); font: inherit; text-decoration: underline;