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): frame instrumentation (PerfMonitor) to attribute viewport jank

yhh801f521c0709
diff --git a/desktop/src/components/PerfOverlay.tsx b/desktop/src/components/PerfOverlay.tsx
new file mode 100644
index 000000000..23ca0f0d7
--- /dev/null
+++ b/desktop/src/components/PerfOverlay.tsx
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file PerfOverlay.tsx — the frame-timing readout (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).
+ */
+import { useSyncExternalStore } from 'react';
+import { PerfMonitor } from '@/engine/PerfMonitor';
+
+export function PerfOverlay() {
+ const s = useSyncExternalStore(PerfMonitor.subscribe, PerfMonitor.getSnapshot);
+ const warn = 'var(--warn, #e5a33b)';
+ const p99Bad = s.p99 >= 24;
+ return (
+ <div
+ style={{
+ position: 'absolute',
+ top: 8,
+ left: 8,
+ zIndex: 60,
+ pointerEvents: 'none',
+ font: '11px var(--font-mono, ui-monospace, monospace)',
+ lineHeight: 1.55,
+ color: 'var(--text-dim, #cfcfcf)',
+ background: 'var(--srf-3, #17171b)',
+ border: '1px solid var(--border-line, #333)',
+ borderRadius: 6,
+ padding: '6px 9px',
+ boxShadow: 'var(--shadow-3, 0 6px 18px rgba(0,0,0,0.4))',
+ }}
+ >
+ <div>
+ <span style={{ color: 'var(--text-mute, #888)' }}>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>
+ ) : null}
+ </div>
+ );
+}
diff --git a/desktop/src/engine/PerfMonitor.ts b/desktop/src/engine/PerfMonitor.ts
new file mode 100644
index 000000000..51064a921
--- /dev/null
+++ b/desktop/src/engine/PerfMonitor.ts
@@ -0,0 +1,161 @@
+// 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.
+ */
+import { createStore } from 'zustand/vanilla';
+
+/** p-th percentile (0..100) of an unsorted sample; 0 for an empty set. */
+export function percentile(values: readonly number[], p: number): number {
+ if (values.length === 0) return 0;
+ const s = [...values].sort((a, b) => a - b);
+ const i = Math.min(s.length - 1, Math.max(0, Math.round((p / 100) * (s.length - 1))));
+ return s[i];
+}
+
+/** The phase with the most accumulated time in a frame, or null. */
+export function dominantPhase(phases: Record<string, number>): { phase: string; ms: number } | null {
+ let best: { phase: string; ms: number } | null = null;
+ for (const phase in phases) {
+ const ms = phases[phase];
+ if (!best || ms > best.ms) best = { phase, ms };
+ }
+ return best;
+}
+
+export interface PerfSnapshot {
+ fps: number;
+ p50: number;
+ p95: number;
+ p99: number;
+ /** Frames over the long-frame budget in the last window. */
+ longFrames: number;
+ worstMs: number;
+ worstPhase: string | null;
+ /** Longest main-thread task (ms) seen in the window (GC / long JS). */
+ longTaskMs: number;
+ visible: boolean;
+ enabled: boolean;
+}
+
+const LONG_FRAME_MS = 24; // missed a 60Hz frame
+const WINDOW_MS = 500;
+const CAP = 240;
+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,
+ }));
+ private enabled = true;
+ private running = false;
+ private raf = 0;
+ private obs: PerformanceObserver | null = null;
+ private last = 0;
+ private windowStart = 0;
+ private readonly frames: number[] = [];
+ private phase: Record<string, number> = {};
+ private longFrames = 0;
+ private worstMs = 0;
+ private worstPhase: string | null = null;
+ private longTaskMs = 0;
+
+ start(): void {
+ if (this.running) return;
+ this.running = true;
+ this.raf = requestAnimationFrame(this.loop);
+ if (typeof PerformanceObserver !== 'undefined') {
+ try {
+ this.obs = new PerformanceObserver((list) => {
+ for (const e of list.getEntries()) this.longTaskMs = Math.max(this.longTaskMs, e.duration);
+ });
+ this.obs.observe({ entryTypes: ['longtask'] });
+ } catch { /* longtask unsupported — frame timing still works */ }
+ }
+ }
+
+ stop(): void {
+ this.running = false;
+ cancelAnimationFrame(this.raf);
+ this.obs?.disconnect();
+ this.obs = null;
+ }
+
+ setEnabled(on: boolean): void { this.enabled = on; this.patch({ enabled: on }); }
+ toggleOverlay(): void { this.patch({ visible: !this.store.getState().visible }); }
+
+ /** 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();
+ const t0 = performance.now();
+ try {
+ return fn();
+ } finally {
+ this.mark(phase, t0);
+ }
+ }
+
+ /** Record a phase that ran from `startMs` to now (accumulate + User Timing). */
+ mark(phase: string, startMs: number): void {
+ if (!this.enabled) return;
+ const end = performance.now();
+ this.phase[phase] = (this.phase[phase] ?? 0) + (end - startMs);
+ 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;
+ }
+
+ subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);
+ getSnapshot = (): PerfSnapshot => this.store.getState();
+
+ private loop = (now: number): void => {
+ 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';
+ }
+ }
+ }
+ this.phase = {};
+ this.last = now;
+
+ if (this.windowStart === 0) this.windowStart = now;
+ if (now - this.windowStart >= WINDOW_MS) {
+ const p50 = percentile(this.frames, 50);
+ 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),
+ });
+ this.windowStart = now;
+ this.longFrames = 0; this.worstMs = 0; this.worstPhase = null; this.longTaskMs = 0;
+ }
+ };
+
+ private patch(p: Partial<PerfSnapshot>): void {
+ this.store.setState({ ...this.store.getState(), ...p });
+ }
+}
+
+export const PerfMonitor = new PerfMonitorImpl();
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 6aeff652f..fe3d7e3df 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 { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
+import { Profiler, 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,
@@ -18,6 +18,8 @@ import { IMAGE_RE } from '@/project/assetMeta';
import { SceneModel } from '@/engine/SceneModel';
import { SceneStore } from '@/engine/SceneStore';
import { StatsStore } from '@/engine/StatsStore';
+import { PerfMonitor } from '@/engine/PerfMonitor';
+import { PerfOverlay } from '@/components/PerfOverlay';
import type { ToolMode } from '@/types';
import { resolveActiveTool, type EditorTool, type ToolContext, type PointerInput } from '@/tools';
import { cursorTile } from '@/tools/tileTools';
@@ -286,6 +288,9 @@ export function Viewport() {
const [zoomPct, setZoomPct] = useState(100);
const engine = useSyncExternalStore(EngineHost.subscribe, EngineHost.getSnapshot);
const realm = useSyncExternalStore(PlayRealm.subscribe, PlayRealm.getSnapshot);
+ // Selector snapshot: re-renders only when the Perf overlay is toggled, not on
+ // its twice-a-second stat updates (those re-render only <PerfOverlay>).
+ const perfVisible = useSyncExternalStore(PerfMonitor.subscribe, () => PerfMonitor.getSnapshot().visible);
// Scene cameras don't render in edit mode (the viewport is the editor camera),
// so draw each as a gizmo (icon + authored view rect). The id set updates on
@@ -317,6 +322,7 @@ export function Viewport() {
if (!stage) return;
EngineHost.attach(stage);
StatsStore.start();
+ PerfMonitor.start();
return () => EngineHost.detach();
}, []);
@@ -358,6 +364,7 @@ export function Viewport() {
let raf = 0;
const tick = () => {
raf = requestAnimationFrame(tick);
+ const perfT0 = performance.now();
const g = gizmoRef.current;
if (!g) return;
const ready = EngineHost.getSnapshot().status === 'ready';
@@ -554,6 +561,7 @@ export function Viewport() {
wrap.style.opacity = '0';
}
}
+ PerfMonitor.mark('gizmo.update', perfT0);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
@@ -662,6 +670,7 @@ 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">
@@ -671,6 +680,7 @@ export function Viewport() {
<DdCheck on={showGrid} label="Grid" onClick={() => commands.run('view.toggleGrid')} />
<DdCheck on={showGizmos} label="Gizmos" onClick={() => commands.run('view.toggleGizmos')} />
<DdCheck on={showColliders} label="Colliders" onClick={() => commands.run('view.toggleColliders')} />
+ <DdCheck on={perfVisible} label="Perf" onClick={() => PerfMonitor.toggleOverlay()} />
</OvDropdown>
<span className="ov-divider" />
<OvTool icon={Frame} label="Frame Selected (F)" kbd="F" onClick={() => commands.run('view.frameSelected')} />
@@ -877,8 +887,10 @@ export function Viewport() {
)}
<ViewportHud ready={engine.status === 'ready'} selCount={selCount} zoomPct={zoomPct} tool={tool} />
+ {perfVisible && <PerfOverlay />}
{isPlaying && <div className="viewport__playflag">● PLAY</div>}
</div>
+ </Profiler>
);
}
diff --git a/desktop/tests/perf-monitor.test.ts b/desktop/tests/perf-monitor.test.ts
new file mode 100644
index 000000000..562f130a0
--- /dev/null
+++ b/desktop/tests/perf-monitor.test.ts
@@ -0,0 +1,28 @@
+// 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';
+
+describe('percentile', () => {
+ const v = Array.from({ length: 100 }, (_, i) => i + 1); // 1..100
+
+ it('is 0 for an empty sample', () => expect(percentile([], 50)).toBe(0));
+ it('returns the value for a single sample', () => expect(percentile([42], 95)).toBe(42));
+ it('pins the ends', () => {
+ expect(percentile(v, 0)).toBe(1);
+ expect(percentile(v, 100)).toBe(100);
+ });
+ it('is non-decreasing and order-independent', () => {
+ const shuffled = [...v].reverse();
+ expect(percentile(shuffled, 50)).toBeLessThanOrEqual(percentile(shuffled, 95));
+ expect(percentile(shuffled, 95)).toBeLessThanOrEqual(percentile(shuffled, 99));
+ expect(percentile(shuffled, 99)).toBeGreaterThan(percentile(shuffled, 50));
+ });
+});
+
+describe('dominantPhase', () => {
+ it('picks the heaviest phase', () => {
+ expect(dominantPhase({ 'gizmo.update': 3, 'react.commit': 7, other: 1 })).toEqual({ phase: 'react.commit', ms: 7 });
+ });
+ it('is null for no phases', () => expect(dominantPhase({})).toBeNull());
+});