A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(profiler): a frame folds into a tree that adds up, and says why
yhh62040ea6e13c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 354f07a75..345e57ccf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,69 @@ Version numbers here track the **Estella release** — the engine + editor + SDKshipped together, matching the Git tags and GitHub Releases. The SDK is notpublished separately; it ships inside the editor.+## [Unreleased]++### Added++- **The profiler answers "where did this frame go", and its rows add up.** The+ numbers were all being measured already — per-system CPU, sub-frame scopes, the+ engine's C++ scopes — and the panel listed them side by side as one flat ranking,+ which is how a scope nested inside a system got counted twice and how "Systems"+ came to mean the windowed maximum of each while "Frame" meant one frame. There+ was no way to ask which subsystem a cost belonged to at all: `EnemyAISystem` and+ `TilemapSyncSystem` were two names in a list.++ A frame now folds into a tree of cost domains, each domain the sum of its+ systems, each system the sum of the scopes measured inside it with the+ unaccounted remainder named as such. `frame = cpu + wait + idle` holds, and so+ does every node against its children — asserted, because a tree whose rows do+ not sum is a worse answer than a list that never claimed to.++- **A system's domain comes from where it was registered, not from a table.** The+ scheduler already knew — a system added during `plugin.build()` carries that+ plugin, and the project bundle's drain is what tells user code from engine code.+ That fact only ever reached the liveness watchdog. It now reaches the profiler,+ so a project's own systems appear under `scripts` and every plugin's under its+ own name with nothing to declare and nothing to keep in sync. A plugin whose+ cost is not its name says so once at its declaration — `camera` produces+ `render` — rather than the profiler keeping a list of who really means what.++- **Blocking is not work, and a scope says which it is.** `measureFrameScope` takes+ `remainder: 'wait'`: whatever is left under that scope once the native scopes+ inside it are subtracted is CPU blocked, not a hotspot. The swapchain block the+ render submit absorbs — the 2.1ms that used to read as an empty scene's most+ expensive system — is now the only thing that reclassification is spelled as,+ instead of a subtraction the editor did to one hard-coded scope name. It keeps+ the same numbers on the same capture, and an `await` can now be declared the+ same way.++- **A system's time now comes with the reason for it.** "ProjectileSystem: 7.3ms"+ is where every profiler stops and where the actual question starts. Each system+ now reports what its queries walked that frame — how many times they were asked,+ how many entities that came to, and how many of those an `Added`/`Changed`+ filter then discarded — so 7.3ms reads as 7.3ms over 18,400 entities of which+ none had changed, which names the fix instead of the symptom.++ It is measured at `candidates_()`, the one seam every way of asking a query+ goes through, so `count()`, `toArray()`, `isEmpty()`, `single()`, `forEach` and+ iteration are all covered by construction rather than by six call sites+ remembering to. The switch is per-`World`, not a module flag: the editor realm+ and the play realm are separate Apps in one process and a shared one would have+ each turn the other's accounting on.++- **A system that runs four fixed steps is charged for four.** `flushSystem_`+ assigned each system's time rather than adding to it, so a system on a fixed+ schedule reported its last catch-up step and nothing else — a physics-bound+ frame read as a quarter of its real cost. It accumulates now, which is also+ what makes the frame tree's claim to add up true on any frame the accumulator+ had a backlog for.++- **One derivation, three readers.** `buildFrameProfile` is a pure function over+ plain per-frame data, so the live view, a pinned frame and a recorded session+ cannot each round their own way to a different answer. The editor's own+ `presentWait` subtraction is gone; the panel, the unit bar and the systems table+ now all read the tree.+## [0.50.0] - 2026-08-11### Addeddiff --git a/desktop/src/components/PerfRealmBridge.tsx b/desktop/src/components/PerfRealmBridge.tsxindex a3225a275..04505ed7a 100644--- a/desktop/src/components/PerfRealmBridge.tsx+++ b/desktop/src/components/PerfRealmBridge.tsx@@ -25,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, cppCounters: s.cppCounters, gpuScopes: s.gpuScopes, jsScopes: s.jsScopes, wasmBytes: s.wasmBytes, vramBytes: s.vramBytes }+ ? { phaseMs: s.phases, costs: s.costs, drawCalls: s.drawCalls, triangles: s.triangles, sprites: s.sprites, entities: s.entities, gpuMs: s.gpuMs, cppScopes: s.cppScopes, cppCounters: s.cppCounters, gpuScopes: s.gpuScopes, wasmBytes: s.wasmBytes, vramBytes: s.vramBytes }: null;};void poll();diff --git a/desktop/src/engine/EngineHost.ts b/desktop/src/engine/EngineHost.tsindex cacd55cbf..e96ca788e 100644--- a/desktop/src/engine/EngineHost.ts+++ b/desktop/src/engine/EngineHost.ts@@ -15,7 +15,7 @@ import {setEditorMode,setPlayMode,} from 'esengine';-import type { App, ResourceDef, SubsystemStatus, SceneData, RenderSurfaceSource } from 'esengine';+import type { App, ResourceDef, SubsystemStatus, SceneData, RenderSurfaceSource, FrameCosts } from 'esengine';import type { ESEngineModule } from 'esengine/wasm';import { SpinePlugin } from 'esengine/spine';import type { SpineManager } from 'esengine/spine';@@ -140,7 +140,7 @@ class EngineHostImpl {/** The engine's last-frame telemetry for the profiler; null until booted. */readEngineFrame(): {phaseMs: Record<string, number>;- systemMs: Record<string, number>;+ costs: FrameCosts | null;drawCalls: number;triangles: number;sprites: number;@@ -149,7 +149,6 @@ class EngineHostImpl {cppScopes: Record<string, number>;cppCounters: Record<string, number>;gpuScopes: Record<string, number>;- jsScopes: Record<string, number>;wasmBytes: number;vramBytes: number;} | null {@@ -157,8 +156,6 @@ class EngineHostImpl {if (!app) return null;const m = this.module_;const phases = app.getPhaseTimings();- const systems = app.getSystemTimings();- const jsScopes = app.getFrameScopes();let cppScopes: Record<string, number> = {};const scopesJson = m?.engine_getCpuScopes?.();if (scopesJson) {@@ -176,7 +173,7 @@ class EngineHostImpl {}return {phaseMs: phases ? Object.fromEntries(phases) : {},- systemMs: systems ? Object.fromEntries(systems) : {},+ costs: app.getFrameCosts(),drawCalls: m?.renderer_getDrawCalls?.() ?? 0,triangles: m?.renderer_getTriangles?.() ?? 0,sprites: m?.renderer_getSprites?.() ?? 0,@@ -185,7 +182,6 @@ class EngineHostImpl {cppScopes,cppCounters,gpuScopes,- jsScopes: jsScopes ? Object.fromEntries(jsScopes) : {},wasmBytes: m?.HEAPU8?.byteLength ?? 0,vramBytes: m?.renderer_getTextureBytes?.() ?? 0,};diff --git a/desktop/src/engine/PerfMonitor.ts b/desktop/src/engine/PerfMonitor.tsindex 1eed79147..df32b5e7d 100644--- a/desktop/src/engine/PerfMonitor.ts+++ b/desktop/src/engine/PerfMonitor.ts@@ -4,6 +4,7 @@* @file PerfMonitor.ts — the editor's per-frame instrumentation hub.*/import { createStore } from 'zustand/vanilla';+import { buildFrameProfile, type FrameCosts, type FrameProfile, type ScopeCost } from 'esengine';/** p-th percentile (0..100) of an unsorted sample; 0 for an empty set. */export function percentile(values: readonly number[], p: number): number {@@ -40,7 +41,9 @@ export function topSystems(rec: Record<string, number>, n: number): Array<{ name* stays decoupled from the engine host. */export interface EngineFrame {phaseMs: Record<string, number>;- systemMs: Record<string, number>;+ /** Per-system and per-scope CPU cost, each carrying the domain/system it+ * belongs to. The profile tree is folded from this. */+ costs: FrameCosts | null;drawCalls: number;triangles: number;sprites: number;@@ -53,15 +56,32 @@ export interface EngineFrame {cppCounters: Record<string, number>;/** Per-frame per-pass GPU times (submit, postprocess), name → ms. */gpuScopes: Record<string, number>;- /** Per-frame JS-side sub-system CPU scopes (render.resolveCameras etc.) — the- * `js.*` rows; the JS sibling of cppScopes. */- jsScopes: Record<string, number>;/** Total wasm linear memory (bytes) — the engine's heap. */wasmBytes: number;/** Resident texture VRAM (bytes, estimate). */vramBytes: number;}+/** The engine's C++ scopes as the profile model's native scopes. */+function nativeScopesOf(cppScopes: Record<string, number>): ScopeCost[] {+ return Object.entries(cppScopes).map(([name, ms]) => ({ name, ms, system: '', remainder: 'work' as const }));+}++/**+ * Fold a captured frame into the tree the panel and the agent both read. Kept+ * here rather than in the panel so a pinned frame, a recorded session and a+ * tool call cannot each derive a different number from the same sample.+ */+export function profileOf(sample: FrameSample): FrameProfile {+ return buildFrameProfile({+ frameMs: sample.dt,+ systems: sample.costs?.systems ?? [],+ scopes: sample.costs?.scopes ?? [],+ nativeScopes: nativeScopesOf(sample.cppScopes),+ gpuMs: sample.gpuMs,+ });+}+/** One frame's full per-frame breakdown, kept in a ring so any past frame can be* inspected after the fact. */export interface FrameSample {@@ -80,9 +100,9 @@ export interface FrameSample {enginePhases: Record<string, number>;cppScopes: Record<string, number>;gpuScopes: Record<string, number>;- jsScopes: Record<string, number>;+ /** This frame's attributed engine costs — what `profileOf` folds into a tree. */+ costs: FrameCosts | null;counters: Record<string, number>;- systems: Array<{ name: string; ms: number }>;drawCalls: number;triangles: number;entities: number;@@ -116,6 +136,9 @@ export interface PerfSnapshot {entities: number;/** Costliest engine systems over the window (name + windowed-max ms). */systemsTop: Array<{ name: string; ms: number }>;+ /** The latest captured frame folded into its cost tree. One real frame, so+ * its rows add up — unlike the windowed maxima above. */+ profile: FrameProfile | null;/** Which realm the engine numbers come from. */realm: 'edit' | 'play';/** GPU time (ms), or -1 when the timer isn't available. */@@ -154,23 +177,6 @@ export interface SessionCapture {longTasks?: Array<{ start: number; ms: number; name: string }>;}-// The render system's JS scope that wraps the GPU submit + implicit present. Its-// wall-clock minus the C++ render CPU inside it is the swapchain/vsync wait the-// last GPU-submitting system absorbs — reclassified out of engine CPU (see loop).-const RENDER_SUBMIT_SCOPE = 'render.submit';--/**- * Present/vsync wait absorbed by the render system: the render submit scope's- * JS wall-clock minus the C++ render CPU dispatched inside it (`cppScopes`).- * What's left is the CPU blocked on the swapchain — not work. Returns 0 when the- * submit scope is absent (an SDK without the render.submit instrumentation), so- * the profiler degrades to the old lumped view rather than inventing a number.- */-export function presentWait(jsScopes: Record<string, number>, cppScopes: Record<string, number>): number {- const submitWall = jsScopes[RENDER_SUBMIT_SCOPE] ?? 0;- return submitWall > 0 ? Math.max(0, submitWall - sumMs(cppScopes)) : 0;-}-const LONG_FRAME_MS = 24; // missed a 60Hz frameconst HITCH_MS = 50; // auto-freeze threshold — a real hitch (below 20fps)const WINDOW_MS = 500;@@ -181,7 +187,7 @@ 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, presentWaitMs: 0, drawCalls: 0, triangles: 0, entities: 0, systemsTop: [], realm: 'edit', gpuMs: -1, frames: [],+ engineMs: 0, editorMs: 0, presentWaitMs: 0, drawCalls: 0, triangles: 0, entities: 0, systemsTop: [], profile: null, realm: 'edit', gpuMs: -1, frames: [],frozen: false, pinnedId: null, autoHitch: false, longTaskRev: 0,wasmMB: 0, jsHeapMB: 0, jsHeapLimitMB: 0, vramMB: 0, memHist: [], counters: {},recording: false, recordedFrames: 0,@@ -429,26 +435,16 @@ class PerfMonitorImpl {let enginePhases: Record<string, number> = {};let cppScopes: Record<string, number> = {};let gpuScopes: Record<string, number> = {};- let jsScopes: Record<string, number> = {};+ let costs: FrameCosts | null = null;let engineCounters: Record<string, number> = {};- let systemsFrame: Array<{ name: string; ms: number }> = [];- let presentWaitMs = 0;if (ef) {enginePhases = ef.phaseMs;cppScopes = ef.cppScopes;gpuScopes = ef.gpuScopes;- jsScopes = ef.jsScopes;+ costs = ef.costs;engineCounters = ef.cppCounters;engineFrameMs = sumMs(enginePhases);this.engineSum += engineFrameMs;- // Split the swapchain/vsync block out of engine CPU (see presentWait): the- // render system reads as ~0, not a phantom multi-ms hotspot.- presentWaitMs = presentWait(jsScopes, cppScopes);- this.presentWaitSum += presentWaitMs;- 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.mem = { wasmBytes: ef.wasmBytes, vramBytes: ef.vramBytes };}@@ -462,19 +458,28 @@ class PerfMonitorImpl {t1: now,engineMs: r1(engineFrameMs),editorMs: r1(editorFrameMs),- presentWaitMs: r1(presentWaitMs),+ presentWaitMs: 0,gpuMs: this.counters.gpuMs >= 0 ? r1(this.counters.gpuMs) : -1,editorPhases: { ...editorPhases },enginePhases: { ...enginePhases },cppScopes: { ...cppScopes },gpuScopes: { ...gpuScopes },- jsScopes: { ...jsScopes },+ costs,counters: { ...engineCounters, ...editorCounters },- systems: systemsFrame,drawCalls: this.counters.drawCalls,triangles: this.counters.triangles,entities: this.counters.entities,};+ // The wait is the tree's, so the windowed unit bar and the pinned tree can+ // never disagree about how much of this frame was work.+ const profile = profileOf(sample);+ sample.presentWaitMs = r1(profile.waitMs);+ this.presentWaitSum += profile.waitMs;+ for (const domain of profile.domains) {+ for (const sys of domain.children) {+ if (sys.ms > (this.systemMax[sys.label] ?? 0)) this.systemMax[sys.label] = sys.ms;+ }+ }this.lastCounters = sample.counters;this.samples.push(sample);if (this.samples.length > CAP) this.samples.shift();@@ -509,6 +514,7 @@ class PerfMonitorImpl {engineMs: r1(this.engineSum / wf), editorMs: r1(this.editorSum / wf), presentWaitMs: r1(this.presentWaitSum / 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) })),+ profile: this.samples.length ? profileOf(this.samples[this.samples.length - 1]) : null,realm: this.realm,gpuMs: this.counters.gpuMs >= 0 ? r1(this.counters.gpuMs) : -1,frames: this.samples.map((s) => s.dt),diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.tsindex f553e983b..9f679f2f1 100644--- a/desktop/src/engine/playProtocol.ts+++ b/desktop/src/engine/playProtocol.ts@@ -11,7 +11,7 @@* import of an editor module here would break the realm bundle. Type-only* imports are erased before resolution and are safe.*/-import type { SceneData, PhysicsPluginConfig, AudioProjectConfig, ThemeOverrides, AddressableManifest } from 'esengine';+import type { SceneData, PhysicsPluginConfig, AudioProjectConfig, ThemeOverrides, AddressableManifest, FrameCosts } from 'esengine';/*** Editor↔realm message-contract version. The realm reports it in `hello`; the editor@@ -136,7 +136,9 @@ export interface PlayStepReply {* Feeds the editor profiler's engine segment while playing (PerfMonitor). */export interface PlayStatsReply {phases: Record<string, number>;- systems: Record<string, number>;+ /** Per-system and per-scope cost with the domain/system attribution the+ * profile tree is folded from. Null while the realm has stats off. */+ costs: FrameCosts | null;drawCalls: number;triangles: number;sprites: number;@@ -145,7 +147,6 @@ export interface PlayStatsReply {cppScopes: Record<string, number>;cppCounters: Record<string, number>;gpuScopes: Record<string, number>;- jsScopes: Record<string, number>;wasmBytes: number;vramBytes: number;}diff --git a/desktop/src/i18n/messages/logs.ts b/desktop/src/i18n/messages/logs.tsindex df3082287..6fcfc63e8 100644--- a/desktop/src/i18n/messages/logs.ts+++ b/desktop/src/i18n/messages/logs.ts@@ -61,6 +61,7 @@ export const logsMessages = defineMessages({'prof.groupCounters': { en: 'Counters', zh: '计数器' },'prof.groupMemory': { en: 'Memory', zh: '内存' },'prof.groupSystems': { en: 'Systems', zh: '系统' },+ 'prof.groupTree': { en: 'Where the frame went', zh: '这一帧花在哪' },// — Profiler: Frame section —'prof.clickToInspect': { en: 'Click a frame to inspect it', zh: '点击某一帧以查看详情' },@@ -102,8 +103,18 @@ export const logsMessages = defineMessages({'prof.unattributed': { en: '{ms}ms unattributed', zh: '{ms}ms 未归因' },'prof.browserPaintGc': { en: 'browser paint / GC', zh: '浏览器绘制 / GC' },+ // — Profiler: cost tree —+ 'prof.lastFrame': { en: 'last frame', zh: '最近一帧' },+ 'prof.queryScanned': { en: 'query walked {n} entities in {calls}', zh: '查询遍历 {n} 个实体,{calls} 次' },+ 'prof.queryFiltered': { en: '{n} discarded unchanged', zh: '其中 {n} 个没变被丢弃' },+ 'prof.treeTotals': {+ en: 'frame {frame}ms = cpu {cpu} + wait {wait} + idle {idle}',+ zh: '帧 {frame}ms = CPU {cpu} + 等待 {wait} + 空闲 {idle}',+ },+// — Profiler: Systems section —'prof.thisFrame': { en: 'this frame', zh: '当前帧' },+ 'prof.windowMax': { en: 'window max', zh: '窗口最大值' },'prof.noSystemTimings': { en: 'No system timings yet.', zh: '暂无系统耗时数据。' },// — Diagnostic bundle (Help ▸ Export Diagnostics) —diff --git a/desktop/src/panels/ProfilerPanel.tsx b/desktop/src/panels/ProfilerPanel.tsxindex 60ba54c5b..add2d84ee 100644--- a/desktop/src/panels/ProfilerPanel.tsx+++ b/desktop/src/panels/ProfilerPanel.tsx@@ -5,7 +5,8 @@*/import { useSyncExternalStore, useRef, useEffect, useCallback, useState } from 'react';import type { MouseEvent as ReactMouseEvent } from 'react';-import { PerfMonitor } from '@/engine/PerfMonitor';+import { PerfMonitor, profileOf } from '@/engine/PerfMonitor';+import type { ProfileNode } from 'esengine';import { t } from '@/i18n';const BUDGET_MS = 1000 / 60; // 60 Hz frame budget (16.6ms)@@ -37,6 +38,7 @@ function downloadSession(): void {const GROUPS = [{ id: 'frame', label: t('prof.groupFrame') },{ id: 'unit', label: t('prof.groupUnit') },+ { id: 'tree', label: t('prof.groupTree') },{ id: 'render', label: t('prof.groupRender') },{ id: 'counters', label: t('prof.groupCounters') },{ id: 'memory', label: t('prof.groupMemory') },@@ -173,6 +175,56 @@ function FrameGraph({ frames, pinnedId }: { frames: number[]; pinnedId: number |return <canvas ref={ref} className="prof-graph" title={t('prof.clickToInspect')} onClick={onClick} />;}+// A query that walks the world every frame and then discards nearly all of it is+// the shape behind most "why is this system 7ms" — so the ratio is called out,+// not left for the reader to divide.+const MOSTLY_DISCARDED = 0.9;++/** What a system's queries walked, under the system whose time it explains. */+function QueryNote({ query, depth }: { query: NonNullable<ProfileNode['query']>; depth: number }) {+ const wasteful = query.scanned > 0 && query.filtered / query.scanned >= MOSTLY_DISCARDED;+ return (+ <div className={`prof-tree-row prof-tree-query${wasteful ? ' waste' : ''}`}>+ <span className="prof-tree-name" style={{ paddingLeft: `${(depth + 1) * 12 + 11}px` }}>+ {t('prof.queryScanned', { n: kfmt(query.scanned), calls: query.calls })}+ {query.filtered > 0 ? ` · ${t('prof.queryFiltered', { n: kfmt(query.filtered) })}` : ''}+ </span>+ <span />+ <span />+ </div>+ );+}++/** A domain / system / scope row, indented by depth and expandable while it has+ * children. Share is of the whole frame, so depths stay comparable. */+function TreeRow({ node, frameMs, depth }: { node: ProfileNode; frameMs: number; depth: number }) {+ const [open, setOpen] = useState(depth === 0);+ const pct = frameMs > 0 ? Math.min(100, (node.ms / frameMs) * 100) : 0;+ const hasKids = node.children.length > 0;+ return (+ <>+ <div className={`prof-tree-row prof-tree-${node.kind}`}>+ <button+ type="button"+ className="prof-tree-name"+ style={{ paddingLeft: `${depth * 12}px` }}+ onClick={() => hasKids && setOpen(!open)}+ disabled={!hasKids}+ >+ <span className="prof-tree-caret">{hasKids ? (open ? '▾' : '▸') : ''}</span>+ {node.label}+ </button>+ <span className="prof-tree-ms">{node.ms.toFixed(1)}<i>ms</i></span>+ <span className="prof-bar"><span className="prof-fill" style={{ width: `${pct}%` }} /></span>+ </div>+ {node.query ? <QueryNote query={node.query} depth={depth} /> : null}+ {open && node.children.map((c) => (+ <TreeRow key={c.id} node={c} frameMs={frameMs} depth={depth + 1} />+ ))}+ </>+ );+}+/** One "Frame = a + b + …" bar segment, width ∝ its share of the frame. */function Seg({ label, ms, frame, color, title }: { label: string; ms: number; frame: number; color: string; title?: string }) {const pct = frame > 0 ? Math.min(100, (ms / frame) * 100) : 0;@@ -194,10 +246,13 @@ export function ProfilerPanel() {const show = (id: string) => !hidden.has(id);// Sections read the pinned frame when one is inspected, else the live window.+ const profile = pinned ? profileOf(pinned) : s.profile;const v = pinned? {frameMs: pinned.dt, engineMs: pinned.engineMs, editorMs: pinned.editorMs, presentWaitMs: pinned.presentWaitMs, gpuMs: pinned.gpuMs,- drawCalls: pinned.drawCalls, triangles: pinned.triangles, entities: pinned.entities, systems: pinned.systems, counters: pinned.counters,+ drawCalls: pinned.drawCalls, triangles: pinned.triangles, entities: pinned.entities, counters: pinned.counters,+ systems: profile ? profile.domains.flatMap((d) => d.children).sort((a, b) => b.ms - a.ms).slice(0, 8)+ .map((n) => ({ name: n.label, ms: n.ms })) : [],}: {frameMs: s.p50, engineMs: s.engineMs, editorMs: s.editorMs, presentWaitMs: s.presentWaitMs, gpuMs: s.gpuMs,@@ -226,12 +281,11 @@ export function ProfilerPanel() {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;+ // Editor phases and GPU passes only: the engine's own CPU is the tree's, and+ // listing its systems and scopes flat beside it double-counts every scope.const breakdown: Array<[string, number]> = pinned? [...Object.entries(pinned.editorPhases),- ...Object.entries(pinned.enginePhases).map(([n, m]) => [`engine.${n}`, m] as [string, number]),- ...Object.entries(pinned.jsScopes).map(([n, m]) => [`js.${n}`, m] as [string, number]),- ...Object.entries(pinned.cppScopes).map(([n, m]) => [`cpp.${n}`, m] as [string, number]),...Object.entries(pinned.gpuScopes).map(([n, m]) => [`gpu.${n}`, m] as [string, number]),].filter(([, ms]) => ms >= 0.1)@@ -337,6 +391,35 @@ export function ProfilerPanel() {</section>)}+ {/* Where the frame went, by cost domain. One frame, so the rows add up. */}+ {show('tree') && (+ <section className="prof-sec">+ <h4>+ {t('prof.groupTree')}+ <span className="prof-realm"> · {pinned ? t('prof.thisFrame') : t('prof.lastFrame')}</span>+ </h4>+ {profile && profile.domains.length > 0 ? (+ <>+ <div className="prof-tree">+ {profile.domains.map((d) => (+ <TreeRow key={d.id} node={d} frameMs={profile.frameMs} depth={0} />+ ))}+ </div>+ <div className="prof-budget">+ {t('prof.treeTotals', {+ frame: profile.frameMs.toFixed(1),+ cpu: profile.cpuMs.toFixed(1),+ wait: profile.waitMs.toFixed(1),+ idle: profile.idleMs.toFixed(1),+ })}+ </div>+ </>+ ) : (+ <p className="prof-empty">{t('prof.noSystemTimings')}</p>+ )}+ </section>+ )}+{show('render') && (<section className="prof-sec"><h4>{t('prof.groupRender')}</h4>@@ -408,7 +491,7 @@ export function ProfilerPanel() {{/* Costliest engine systems — windowed max (live) or this frame's cost (pinned). */}{show('systems') && (<section className="prof-sec">- <h4>{t('prof.groupSystems')}{pinned ? ` · ${t('prof.thisFrame')}` : ''}</h4>+ <h4>{t('prof.groupSystems')} <span className="prof-realm">· {pinned ? t('prof.thisFrame') : t('prof.windowMax')}</span></h4>{sysRows.length ? (<table className="prof-sys"><tbody>diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.tsindex fa4677b4a..ecdf14bc9 100644--- a/desktop/src/playHost.ts+++ b/desktop/src/playHost.ts@@ -759,15 +759,13 @@ window.addEventListener('message', (e: MessageEvent) => {// 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() ?? []) : {};- const jsScopes = app ? Object.fromEntries(app.getFrameScopes() ?? []) : {};const m = engineModule;post({type: 'estella:play:reply',reqId: data.reqId,data: {phases,- systems,+ costs: app?.getFrameCosts() ?? null,drawCalls: m?.renderer_getDrawCalls?.() ?? 0,triangles: m?.renderer_getTriangles?.() ?? 0,sprites: m?.renderer_getSprites?.() ?? 0,@@ -776,7 +774,6 @@ window.addEventListener('message', (e: MessageEvent) => {cppScopes: jsonMap(m?.engine_getCpuScopes?.()),cppCounters: jsonMap(m?.engine_getCounters?.()),gpuScopes: jsonMap(m?.engine_getGpuScopes?.()),- jsScopes,wasmBytes: m?.HEAPU8?.byteLength ?? 0,vramBytes: m?.renderer_getTextureBytes?.() ?? 0,},diff --git a/desktop/src/theme/profiler.css b/desktop/src/theme/profiler.cssindex 397938967..5907e94d9 100644--- a/desktop/src/theme/profiler.css+++ b/desktop/src/theme/profiler.css@@ -101,6 +101,52 @@.prof-bar { height: 6px; border-radius: var(--r-sm); background: var(--srf-1); overflow: hidden; }.prof-fill { display: block; height: 100%; border-radius: var(--r-sm); transition: width var(--t-slow) var(--e-out); }+/* Cost tree: domain ▸ system ▸ scope. One grid for every depth so the ms column+ and the share bar stay aligned however deep a row sits. */+.prof-tree { margin-top: 2px; }+.prof-tree-row {+ display: grid;+ grid-template-columns: minmax(0, 1fr) 4.5em 5em;+ align-items: center;+ gap: 8px;+ margin: 1px 0;+}+.prof-tree-name {+ display: flex;+ align-items: center;+ gap: 3px;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ background: none;+ border: 0;+ padding: 0;+ font: inherit;+ text-align: left;+ color: var(--text);+ cursor: pointer;+}+.prof-tree-name:disabled { cursor: default; }+.prof-tree-caret { display: inline-block; width: 8px; color: var(--text-faint); flex: none; }+.prof-tree-ms { color: var(--text-hi); text-align: right; font-variant-numeric: tabular-nums; }+.prof-tree-ms i { color: var(--text-faint); font-style: normal; font-size: 10px; margin-left: 1px; }++.prof-tree-domain .prof-tree-name { color: var(--text-hi); font-weight: 600; }+.prof-tree-domain .prof-fill { background: var(--star); }+.prof-tree-system .prof-fill { background: var(--run); }+.prof-tree-scope .prof-tree-name { color: var(--text-dim); }+.prof-tree-scope .prof-fill { background: var(--text-mute); }+.prof-tree-wait .prof-tree-name,+.prof-tree-wait .prof-tree-ms { color: var(--warn); }+.prof-tree-wait .prof-fill { background: var(--warn); }+.prof-tree-rest .prof-tree-name,+.prof-tree-rest .prof-tree-ms { color: var(--text-faint); }+.prof-tree-rest .prof-fill { background: var(--text-faint); }++.prof-tree-query .prof-tree-name { color: var(--text-faint); font-size: 10px; cursor: default; }+.prof-tree-query.waste .prof-tree-name { color: var(--warn); }+/* Pinned-frame breakdown rows — name (ellipsis) + right-aligned value, so the twonever collide however long the zone/system name is. */.prof-brk {diff --git a/desktop/tests/perf-monitor.test.ts b/desktop/tests/perf-monitor.test.tsindex 3d2852735..41d2b5dc9 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 Teamimport { describe, it, expect } from 'vitest';-import { percentile, dominantPhase, sumMs, topSystems, presentWait } from '@/engine/PerfMonitor';+import { percentile, dominantPhase, sumMs, topSystems, profileOf, type FrameSample } from '@/engine/PerfMonitor';describe('percentile', () => {const v = Array.from({ length: 100 }, (_, i) => i + 1); // 1..100@@ -42,21 +42,69 @@ describe('topSystems', () => {});});-describe('presentWait', () => {- it('is the submit wall-clock minus the C++ render CPU inside it', () => {- // Real numbers from an empty-scene capture: 2.1ms submit, ~0.02ms C++ work.- const js = { 'render.submit': 2.1, 'render.resolveCameras': 0.007 };- const cpp = { 'render.collect': 0.013, 'render.submit': 0.006, 'render.finalize': 0.002 };- expect(presentWait(js, cpp)).toBeCloseTo(2.079, 3);+describe('profileOf', () => {+ const sample = (over: Partial<FrameSample>): FrameSample => ({+ id: 0, dt: 16.7, t0: 0, t1: 16.7,+ engineMs: 0, editorMs: 0, presentWaitMs: 0, gpuMs: -1,+ editorPhases: {}, enginePhases: {}, cppScopes: {}, gpuScopes: {},+ costs: null, counters: {}, drawCalls: 0, triangles: 0, entities: 0,+ ...over,});- it('is 0 when the submit scope is absent (old SDK, no instrumentation)', () => {- expect(presentWait({}, { 'render.submit': 0.5 })).toBe(0);- expect(presentWait({ 'render.resolveCameras': 0.1 }, {})).toBe(0);++ // Real numbers from an empty-scene capture: 2.1ms submit, ~0.02ms C++ work.+ const emptyScene = sample({+ costs: {+ systems: [{ name: 'RenderSystem', ms: 2.107, domain: 'render' }],+ scopes: [+ { name: 'render.submit', ms: 2.1, system: 'RenderSystem', remainder: 'wait' },+ { name: 'render.resolveCameras', ms: 0.007, system: 'RenderSystem', remainder: 'work' },+ ],+ },+ cppScopes: { 'render.collect': 0.013, 'render.submit': 0.006, 'render.finalize': 0.002 },+ });++ it('reads the submit wall minus the C++ render CPU inside it as wait', () => {+ expect(profileOf(emptyScene).waitMs).toBeCloseTo(2.079, 3);});++ it('leaves the render system its real CPU once the wait is out', () => {+ expect(profileOf(emptyScene).cpuMs).toBeCloseTo(0.028, 3);+ });++ it('reports no wait when nothing declared one (an SDK without the instrumentation)', () => {+ const plain = sample({+ costs: {+ systems: [{ name: 'RenderSystem', ms: 0.5, domain: 'render' }],+ scopes: [{ name: 'render.resolveCameras', ms: 0.1, system: 'RenderSystem', remainder: 'work' }],+ },+ cppScopes: { 'render.submit': 0.5 },+ });+ expect(profileOf(plain).waitMs).toBe(0);+ });+it('never goes negative when C++ work exceeds the (tiny) submit wall', () => {- expect(presentWait({ 'render.submit': 0.1 }, { 'render.submit': 0.5 })).toBe(0);+ const inverted = sample({+ costs: {+ systems: [{ name: 'RenderSystem', ms: 0.1, domain: 'render' }],+ scopes: [{ name: 'render.submit', ms: 0.1, system: 'RenderSystem', remainder: 'wait' }],+ },+ cppScopes: { 'render.submit': 0.5 },+ });+ expect(profileOf(inverted).waitMs).toBe(0);});- it('equals the full submit wall when no C++ scopes are reported', () => {- expect(presentWait({ 'render.submit': 1.8 }, {})).toBe(1.8);++ it('is the whole submit wall when no C++ scopes are reported', () => {+ const noNative = sample({+ costs: {+ systems: [{ name: 'RenderSystem', ms: 1.8, domain: 'render' }],+ scopes: [{ name: 'render.submit', ms: 1.8, system: 'RenderSystem', remainder: 'wait' }],+ },+ });+ expect(profileOf(noNative).waitMs).toBeCloseTo(1.8, 4);+ });++ it('adds up to the frame even with nothing measured', () => {+ const p = profileOf(sample({}));+ expect(p.cpuMs + p.waitMs + p.idleMs).toBeCloseTo(16.7, 4);});});diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 5a9ce1b5a..2c4009948 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 112,"beta": 60,- "experimental": 1458,+ "experimental": 1470,"deprecated": 3},- "total": 1630,+ "total": 1642,"subsystems": [{"id": "ecs",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 47c9ef58d..471d372df 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 53 beta · 1343 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1355 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -516,6 +516,7 @@ addSystemToSchedule: (schedule: Schedule, system: SystemDef, options?: { runBefoenableStats: () => AppgetEntityCount: () => numbergetFixedTimestep: () => number+getFrameCosts: () => FrameCosts | nullgetFrameScopes: () => ReadonlyMap<string, number> | nullgetPhaseTimings: () => ReadonlyMap<string, number> | nullgetPlaySpeed: () => number@@ -531,7 +532,7 @@ hotSwapSystems: (incoming: ReadonlyArray<{ schedule: number; system: SystemDef;insertResource: <T>(resource: ResourceDef<T>, value: T) => AppisPaused: () => booleanisPhysicsReady: boolean-measureFrameScope: <T>(name: string, fn: () => T) => T+measureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => TonError: (handler: (error: unknown, systemName: string) => void) => ApponSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => ApponWasmError: (handler: (error: unknown, context: string) => void) => App@@ -2087,6 +2088,16 @@ ScreenScalingData{ readonly viewProjection: Float32Array<ArrayBuffer>; readonly vpX: 0; readonly vpY: 0; readonly vpW: 0; readonly vpH: 0; readonly screenW: 0; readonly screenH: 0; readonly worldLeft: 0; readonly worldBottom: 0; readonly worldRight: 0; readonly worldTop: 0; readonly worldMouseX: 0; readonly worldMouseY: 0; readonly valid: false; }```+## DOMAIN_SCRIPTS — const @experimental+```+"scripts"+```++## DOMAIN_UNATTRIBUTED — const @experimental+```+"unattributed"+```+## DataSource — interface @experimental```getCount: () => number@@ -2929,6 +2940,12 @@ cameraCount: numberdrawCalls: DrawCallInfo[]```+## FrameCosts — interface @experimental+```+scopes: ScopeCost[]+systems: SystemCost[]+```+## FrameHistory — class @experimental```count: number@@ -2940,6 +2957,25 @@ static new (capacity?: number): FrameHistorystatic prototype: FrameHistory```+## FrameProfile — interface @experimental+```+cpuMs: number+domains: readonly ProfileNode[]+frameMs: number+gpuMs: number+idleMs: number+waitMs: number+```++## FrameProfileInput — interface @experimental+```+frameMs: number+gpuMs: number | undefined+nativeScopes: readonly ScopeCost[] | undefined+scopes: readonly ScopeCost[]+systems: readonly SystemCost[]+```+## FrameSnapshot — interface @experimental```frameTimeMs: number@@ -5075,6 +5111,7 @@ cleanup: ((app?: App) => void) | undefineddependencies: PluginDependency[] | undefinedfinish: ((app: App) => void) | undefinedname: string | undefined+profileDomain: string | undefined```## PluginDependency — type @experimental@@ -5352,6 +5389,21 @@ prefabEntityId: stringvisible: boolean```+## ProfileNode — interface @experimental+```+children: readonly ProfileNode[]+id: string+kind: ProfileNodeKind+label: string+ms: number+query: QueryCost | undefined+```++## ProfileNodeKind — type @experimental+```+'domain' | 'system' | 'scope' | 'wait' | 'rest'+```+## ProgressHandle — interface @experimental```dispose: () => void@@ -5448,6 +5500,7 @@ without: (...components: AnyComponentDef[]) => QueryBuilder<C>## QueryInstance — class @public```@internal resetTick: (tick: number) => void+@internal takeCost: () => QueryCost[Symbol.iterator]: () => Iterator<QueryResult<C>>count: () => numberforEach: (callback: (entity: Entity, ...components: ComponentsData<C>) => void) => void@@ -6165,6 +6218,19 @@ Startup = 0Update = 3```+## ScopeCost — interface @experimental+```+ms: number+name: string+remainder: ScopeRemainder+system: string+```++## ScopeRemainder — type @experimental+```+'work' | 'wait'+```+## ScreenInfo — class @experimental```dpr: number@@ -6820,6 +6886,14 @@ phaseAgeMs: number(path: string) => PrefabData | null```+## SystemCost — interface @experimental+```+domain: string+ms: number+name: string+query: QueryCost | undefined+```+## SystemDef — interface @public```@internal _fn: (...args: never[]) => void | Promise<void>@@ -6853,6 +6927,7 @@ runBefore: string[] | undefined```clearTimings: () => voidevict: (systemId: symbol) => void+getQueryCosts: () => ReadonlyMap<string, QueryCost> | nullgetTimings: () => ReadonlyMap<string, number> | nullreset: () => voidrun: (system: SystemDef) => void | Promise<void>@@ -8447,6 +8522,7 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal markChanged: (entity: Entity, component: AnyComponentDef) => void@internal queries_: QueryCache+@internal queryCostEnabled: boolean@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -8454,6 +8530,7 @@ tabIndex: number | undefined@internal resolveGetter: (component: AnyComponentDef) => ((entity: Entity) => unknown) | null@internal resolveHas: (component: AnyComponentDef) => ((entity: Entity) => boolean) | null@internal resolveSetter: (component: AnyComponentDef) => ((entity: Entity, data: unknown) => void) | null+@internal setQueryCostEnabled: (enabled: boolean) => voiddespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | null@@ -8755,6 +8832,11 @@ BtPlugin(material?: CollisionMaterial): TilesetModel```+## buildFrameProfile — function @experimental+```+(input: FrameProfileInput): FrameProfile+```+## buildTerrainIndices — function @experimental```(asset: TilesetAsset): TerrainIndices@@ -10560,6 +10642,11 @@ Plugin(sceneData: SceneData): boolean```+## scopeDomain — function @experimental+```+(name: string): string+```+## screenToUiWorld — function @experimental```(camera: UICameraData, screenGLX: number, screenGLY: number): { x: number; y: number; }diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 91c14d475..480a87594 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 58 beta · 1362 experimental · 3 deprecated+Symbols: 112 public · 58 beta · 1374 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -516,6 +516,7 @@ addSystemToSchedule: (schedule: Schedule, system: SystemDef, options?: { runBefoenableStats: () => AppgetEntityCount: () => numbergetFixedTimestep: () => number+getFrameCosts: () => FrameCosts | nullgetFrameScopes: () => ReadonlyMap<string, number> | nullgetPhaseTimings: () => ReadonlyMap<string, number> | nullgetPlaySpeed: () => number@@ -531,7 +532,7 @@ hotSwapSystems: (incoming: ReadonlyArray<{ schedule: number; system: SystemDef;insertResource: <T>(resource: ResourceDef<T>, value: T) => AppisPaused: () => booleanisPhysicsReady: boolean-measureFrameScope: <T>(name: string, fn: () => T) => T+measureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => TonError: (handler: (error: unknown, systemName: string) => void) => ApponSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => ApponWasmError: (handler: (error: unknown, context: string) => void) => App@@ -2095,6 +2096,16 @@ ScreenScalingData{ readonly viewProjection: Float32Array<ArrayBuffer>; readonly vpX: 0; readonly vpY: 0; readonly vpW: 0; readonly vpH: 0; readonly screenW: 0; readonly screenH: 0; readonly worldLeft: 0; readonly worldBottom: 0; readonly worldRight: 0; readonly worldTop: 0; readonly worldMouseX: 0; readonly worldMouseY: 0; readonly valid: false; }```+## DOMAIN_SCRIPTS — const @experimental+```+"scripts"+```++## DOMAIN_UNATTRIBUTED — const @experimental+```+"unattributed"+```+## DataSource — interface @experimental```getCount: () => number@@ -2937,6 +2948,12 @@ cameraCount: numberdrawCalls: DrawCallInfo[]```+## FrameCosts — interface @experimental+```+scopes: ScopeCost[]+systems: SystemCost[]+```+## FrameHistory — class @experimental```count: number@@ -2948,6 +2965,25 @@ static new (capacity?: number): FrameHistorystatic prototype: FrameHistory```+## FrameProfile — interface @experimental+```+cpuMs: number+domains: readonly ProfileNode[]+frameMs: number+gpuMs: number+idleMs: number+waitMs: number+```++## FrameProfileInput — interface @experimental+```+frameMs: number+gpuMs: number | undefined+nativeScopes: readonly ScopeCost[] | undefined+scopes: readonly ScopeCost[]+systems: readonly SystemCost[]+```+## FrameSnapshot — interface @experimental```frameTimeMs: number@@ -5258,6 +5294,7 @@ cleanup: ((app?: App) => void) | undefineddependencies: PluginDependency[] | undefinedfinish: ((app: App) => void) | undefinedname: string | undefined+profileDomain: string | undefined```## PluginDependency — type @experimental@@ -5535,6 +5572,21 @@ prefabEntityId: stringvisible: boolean```+## ProfileNode — interface @experimental+```+children: readonly ProfileNode[]+id: string+kind: ProfileNodeKind+label: string+ms: number+query: QueryCost | undefined+```++## ProfileNodeKind — type @experimental+```+'domain' | 'system' | 'scope' | 'wait' | 'rest'+```+## ProgressHandle — interface @experimental```dispose: () => void@@ -5631,6 +5683,7 @@ without: (...components: AnyComponentDef[]) => QueryBuilder<C>## QueryInstance — class @public```@internal resetTick: (tick: number) => void+@internal takeCost: () => QueryCost[Symbol.iterator]: () => Iterator<QueryResult<C>>count: () => numberforEach: (callback: (entity: Entity, ...components: ComponentsData<C>) => void) => void@@ -6358,6 +6411,19 @@ Startup = 0Update = 3```+## ScopeCost — interface @experimental+```+ms: number+name: string+remainder: ScopeRemainder+system: string+```++## ScopeRemainder — type @experimental+```+'work' | 'wait'+```+## ScreenInfo — class @experimental```dpr: number@@ -7013,6 +7079,14 @@ phaseAgeMs: number(path: string) => PrefabData | null```+## SystemCost — interface @experimental+```+domain: string+ms: number+name: string+query: QueryCost | undefined+```+## SystemDef — interface @public```@internal _fn: (...args: never[]) => void | Promise<void>@@ -7046,6 +7120,7 @@ runBefore: string[] | undefined```clearTimings: () => voidevict: (systemId: symbol) => void+getQueryCosts: () => ReadonlyMap<string, QueryCost> | nullgetTimings: () => ReadonlyMap<string, number> | nullreset: () => voidrun: (system: SystemDef) => void | Promise<void>@@ -8640,6 +8715,7 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal markChanged: (entity: Entity, component: AnyComponentDef) => void@internal queries_: QueryCache+@internal queryCostEnabled: boolean@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -8647,6 +8723,7 @@ tabIndex: number | undefined@internal resolveGetter: (component: AnyComponentDef) => ((entity: Entity) => unknown) | null@internal resolveHas: (component: AnyComponentDef) => ((entity: Entity) => boolean) | null@internal resolveSetter: (component: AnyComponentDef) => ((entity: Entity, data: unknown) => void) | null+@internal setQueryCostEnabled: (enabled: boolean) => voiddespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | null@@ -8963,6 +9040,11 @@ BtPlugin(material?: CollisionMaterial): TilesetModel```+## buildFrameProfile — function @experimental+```+(input: FrameProfileInput): FrameProfile+```+## buildTerrainIndices — function @experimental```(asset: TilesetAsset): TerrainIndices@@ -10803,6 +10885,11 @@ Plugin(sceneData: SceneData): boolean```+## scopeDomain — function @experimental+```+(name: string): string+```+## screenToUiWorld — function @experimental```(camera: UICameraData, screenGLX: number, screenGLY: number): { x: number; y: number; }diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 8e6814740..dcd30f2d9 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 55 beta · 1342 experimental · 3 deprecated+Symbols: 112 public · 55 beta · 1354 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -511,6 +511,7 @@ addSystemToSchedule: (schedule: Schedule, system: SystemDef, options?: { runBefoenableStats: () => AppgetEntityCount: () => numbergetFixedTimestep: () => number+getFrameCosts: () => FrameCosts | nullgetFrameScopes: () => ReadonlyMap<string, number> | nullgetPhaseTimings: () => ReadonlyMap<string, number> | nullgetPlaySpeed: () => number@@ -526,7 +527,7 @@ hotSwapSystems: (incoming: ReadonlyArray<{ schedule: number; system: SystemDef;insertResource: <T>(resource: ResourceDef<T>, value: T) => AppisPaused: () => booleanisPhysicsReady: boolean-measureFrameScope: <T>(name: string, fn: () => T) => T+measureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => TonError: (handler: (error: unknown, systemName: string) => void) => ApponSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => ApponWasmError: (handler: (error: unknown, context: string) => void) => App@@ -2082,6 +2083,16 @@ ScreenScalingData{ readonly viewProjection: Float32Array<ArrayBuffer>; readonly vpX: 0; readonly vpY: 0; readonly vpW: 0; readonly vpH: 0; readonly screenW: 0; readonly screenH: 0; readonly worldLeft: 0; readonly worldBottom: 0; readonly worldRight: 0; readonly worldTop: 0; readonly worldMouseX: 0; readonly worldMouseY: 0; readonly valid: false; }```+## DOMAIN_SCRIPTS — const @experimental+```+"scripts"+```++## DOMAIN_UNATTRIBUTED — const @experimental+```+"unattributed"+```+## DataSource — interface @experimental```getCount: () => number@@ -2924,6 +2935,12 @@ cameraCount: numberdrawCalls: DrawCallInfo[]```+## FrameCosts — interface @experimental+```+scopes: ScopeCost[]+systems: SystemCost[]+```+## FrameHistory — class @experimental```count: number@@ -2935,6 +2952,25 @@ static new (capacity?: number): FrameHistorystatic prototype: FrameHistory```+## FrameProfile — interface @experimental+```+cpuMs: number+domains: readonly ProfileNode[]+frameMs: number+gpuMs: number+idleMs: number+waitMs: number+```++## FrameProfileInput — interface @experimental+```+frameMs: number+gpuMs: number | undefined+nativeScopes: readonly ScopeCost[] | undefined+scopes: readonly ScopeCost[]+systems: readonly SystemCost[]+```+## FrameSnapshot — interface @experimental```frameTimeMs: number@@ -5070,6 +5106,7 @@ cleanup: ((app?: App) => void) | undefineddependencies: PluginDependency[] | undefinedfinish: ((app: App) => void) | undefinedname: string | undefined+profileDomain: string | undefined```## PluginDependency — type @experimental@@ -5347,6 +5384,21 @@ prefabEntityId: stringvisible: boolean```+## ProfileNode — interface @experimental+```+children: readonly ProfileNode[]+id: string+kind: ProfileNodeKind+label: string+ms: number+query: QueryCost | undefined+```++## ProfileNodeKind — type @experimental+```+'domain' | 'system' | 'scope' | 'wait' | 'rest'+```+## ProgressHandle — interface @experimental```dispose: () => void@@ -5443,6 +5495,7 @@ without: (...components: AnyComponentDef[]) => QueryBuilder<C>## QueryInstance — class @public```@internal resetTick: (tick: number) => void+@internal takeCost: () => QueryCost[Symbol.iterator]: () => Iterator<QueryResult<C>>count: () => numberforEach: (callback: (entity: Entity, ...components: ComponentsData<C>) => void) => void@@ -6160,6 +6213,19 @@ Startup = 0Update = 3```+## ScopeCost — interface @experimental+```+ms: number+name: string+remainder: ScopeRemainder+system: string+```++## ScopeRemainder — type @experimental+```+'work' | 'wait'+```+## ScreenInfo — class @experimental```dpr: number@@ -6815,6 +6881,14 @@ phaseAgeMs: number(path: string) => PrefabData | null```+## SystemCost — interface @experimental+```+domain: string+ms: number+name: string+query: QueryCost | undefined+```+## SystemDef — interface @public```@internal _fn: (...args: never[]) => void | Promise<void>@@ -6848,6 +6922,7 @@ runBefore: string[] | undefined```clearTimings: () => voidevict: (systemId: symbol) => void+getQueryCosts: () => ReadonlyMap<string, QueryCost> | nullgetTimings: () => ReadonlyMap<string, number> | nullreset: () => voidrun: (system: SystemDef) => void | Promise<void>@@ -8442,6 +8517,7 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal markChanged: (entity: Entity, component: AnyComponentDef) => void@internal queries_: QueryCache+@internal queryCostEnabled: boolean@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -8449,6 +8525,7 @@ tabIndex: number | undefined@internal resolveGetter: (component: AnyComponentDef) => ((entity: Entity) => unknown) | null@internal resolveHas: (component: AnyComponentDef) => ((entity: Entity) => boolean) | null@internal resolveSetter: (component: AnyComponentDef) => ((entity: Entity, data: unknown) => void) | null+@internal setQueryCostEnabled: (enabled: boolean) => voiddespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | null@@ -8750,6 +8827,11 @@ BtPlugin(material?: CollisionMaterial): TilesetModel```+## buildFrameProfile — function @experimental+```+(input: FrameProfileInput): FrameProfile+```+## buildTerrainIndices — function @experimental```(asset: TilesetAsset): TerrainIndices@@ -10565,6 +10647,11 @@ Plugin(sceneData: SceneData): boolean```+## scopeDomain — function @experimental+```+(name: string): string+```+## screenToUiWorld — function @experimental```(camera: UICameraData, screenGLX: number, screenGLY: number): { x: number; y: number; }diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex dfa33d4a1..981218bc1 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 53 beta · 1363 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1375 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -511,6 +511,7 @@ addSystemToSchedule: (schedule: Schedule, system: SystemDef, options?: { runBefoenableStats: () => AppgetEntityCount: () => numbergetFixedTimestep: () => number+getFrameCosts: () => FrameCosts | nullgetFrameScopes: () => ReadonlyMap<string, number> | nullgetPhaseTimings: () => ReadonlyMap<string, number> | nullgetPlaySpeed: () => number@@ -526,7 +527,7 @@ hotSwapSystems: (incoming: ReadonlyArray<{ schedule: number; system: SystemDef;insertResource: <T>(resource: ResourceDef<T>, value: T) => AppisPaused: () => booleanisPhysicsReady: boolean-measureFrameScope: <T>(name: string, fn: () => T) => T+measureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => TonError: (handler: (error: unknown, systemName: string) => void) => ApponSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => ApponWasmError: (handler: (error: unknown, context: string) => void) => App@@ -2082,6 +2083,16 @@ ScreenScalingData{ readonly viewProjection: Float32Array<ArrayBuffer>; readonly vpX: 0; readonly vpY: 0; readonly vpW: 0; readonly vpH: 0; readonly screenW: 0; readonly screenH: 0; readonly worldLeft: 0; readonly worldBottom: 0; readonly worldRight: 0; readonly worldTop: 0; readonly worldMouseX: 0; readonly worldMouseY: 0; readonly valid: false; }```+## DOMAIN_SCRIPTS — const @experimental+```+"scripts"+```++## DOMAIN_UNATTRIBUTED — const @experimental+```+"unattributed"+```+## DataSource — interface @experimental```getCount: () => number@@ -2924,6 +2935,12 @@ cameraCount: numberdrawCalls: DrawCallInfo[]```+## FrameCosts — interface @experimental+```+scopes: ScopeCost[]+systems: SystemCost[]+```+## FrameHistory — class @experimental```count: number@@ -2935,6 +2952,25 @@ static new (capacity?: number): FrameHistorystatic prototype: FrameHistory```+## FrameProfile — interface @experimental+```+cpuMs: number+domains: readonly ProfileNode[]+frameMs: number+gpuMs: number+idleMs: number+waitMs: number+```++## FrameProfileInput — interface @experimental+```+frameMs: number+gpuMs: number | undefined+nativeScopes: readonly ScopeCost[] | undefined+scopes: readonly ScopeCost[]+systems: readonly SystemCost[]+```+## FrameSnapshot — interface @experimental```frameTimeMs: number@@ -5315,6 +5351,7 @@ cleanup: ((app?: App) => void) | undefineddependencies: PluginDependency[] | undefinedfinish: ((app: App) => void) | undefinedname: string | undefined+profileDomain: string | undefined```## PluginDependency — type @experimental@@ -5592,6 +5629,21 @@ prefabEntityId: stringvisible: boolean```+## ProfileNode — interface @experimental+```+children: readonly ProfileNode[]+id: string+kind: ProfileNodeKind+label: string+ms: number+query: QueryCost | undefined+```++## ProfileNodeKind — type @experimental+```+'domain' | 'system' | 'scope' | 'wait' | 'rest'+```+## ProgressHandle — interface @experimental```dispose: () => void@@ -5688,6 +5740,7 @@ without: (...components: AnyComponentDef[]) => QueryBuilder<C>## QueryInstance — class @public```@internal resetTick: (tick: number) => void+@internal takeCost: () => QueryCost[Symbol.iterator]: () => Iterator<QueryResult<C>>count: () => numberforEach: (callback: (entity: Entity, ...components: ComponentsData<C>) => void) => void@@ -6405,6 +6458,19 @@ Startup = 0Update = 3```+## ScopeCost — interface @experimental+```+ms: number+name: string+remainder: ScopeRemainder+system: string+```++## ScopeRemainder — type @experimental+```+'work' | 'wait'+```+## ScreenInfo — class @experimental```dpr: number@@ -7060,6 +7126,14 @@ phaseAgeMs: number(path: string) => PrefabData | null```+## SystemCost — interface @experimental+```+domain: string+ms: number+name: string+query: QueryCost | undefined+```+## SystemDef — interface @public```@internal _fn: (...args: never[]) => void | Promise<void>@@ -7093,6 +7167,7 @@ runBefore: string[] | undefined```clearTimings: () => voidevict: (systemId: symbol) => void+getQueryCosts: () => ReadonlyMap<string, QueryCost> | nullgetTimings: () => ReadonlyMap<string, number> | nullreset: () => voidrun: (system: SystemDef) => void | Promise<void>@@ -8687,6 +8762,7 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal markChanged: (entity: Entity, component: AnyComponentDef) => void@internal queries_: QueryCache+@internal queryCostEnabled: boolean@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -8694,6 +8770,7 @@ tabIndex: number | undefined@internal resolveGetter: (component: AnyComponentDef) => ((entity: Entity) => unknown) | null@internal resolveHas: (component: AnyComponentDef) => ((entity: Entity) => boolean) | null@internal resolveSetter: (component: AnyComponentDef) => ((entity: Entity, data: unknown) => void) | null+@internal setQueryCostEnabled: (enabled: boolean) => voiddespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | null@@ -8995,6 +9072,11 @@ BtPlugin(material?: CollisionMaterial): TilesetModel```+## buildFrameProfile — function @experimental+```+(input: FrameProfileInput): FrameProfile+```+## buildTerrainIndices — function @experimental```(asset: TilesetAsset): TerrainIndices@@ -10815,6 +10897,11 @@ Plugin(sceneData: SceneData): boolean```+## scopeDomain — function @experimental+```+(name: string): string+```+## screenToUiWorld — function @experimental```(camera: UICameraData, screenGLX: number, screenGLY: number): { x: number; y: number; }diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 0f5e03750..e2f1357fe 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 53 beta · 1353 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1365 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -511,6 +511,7 @@ addSystemToSchedule: (schedule: Schedule, system: SystemDef, options?: { runBefoenableStats: () => AppgetEntityCount: () => numbergetFixedTimestep: () => number+getFrameCosts: () => FrameCosts | nullgetFrameScopes: () => ReadonlyMap<string, number> | nullgetPhaseTimings: () => ReadonlyMap<string, number> | nullgetPlaySpeed: () => number@@ -526,7 +527,7 @@ hotSwapSystems: (incoming: ReadonlyArray<{ schedule: number; system: SystemDef;insertResource: <T>(resource: ResourceDef<T>, value: T) => AppisPaused: () => booleanisPhysicsReady: boolean-measureFrameScope: <T>(name: string, fn: () => T) => T+measureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => TonError: (handler: (error: unknown, systemName: string) => void) => ApponSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => ApponWasmError: (handler: (error: unknown, context: string) => void) => App@@ -2082,6 +2083,16 @@ ScreenScalingData{ readonly viewProjection: Float32Array<ArrayBuffer>; readonly vpX: 0; readonly vpY: 0; readonly vpW: 0; readonly vpH: 0; readonly screenW: 0; readonly screenH: 0; readonly worldLeft: 0; readonly worldBottom: 0; readonly worldRight: 0; readonly worldTop: 0; readonly worldMouseX: 0; readonly worldMouseY: 0; readonly valid: false; }```+## DOMAIN_SCRIPTS — const @experimental+```+"scripts"+```++## DOMAIN_UNATTRIBUTED — const @experimental+```+"unattributed"+```+## DataSource — interface @experimental```getCount: () => number@@ -2924,6 +2935,12 @@ cameraCount: numberdrawCalls: DrawCallInfo[]```+## FrameCosts — interface @experimental+```+scopes: ScopeCost[]+systems: SystemCost[]+```+## FrameHistory — class @experimental```count: number@@ -2935,6 +2952,25 @@ static new (capacity?: number): FrameHistorystatic prototype: FrameHistory```+## FrameProfile — interface @experimental+```+cpuMs: number+domains: readonly ProfileNode[]+frameMs: number+gpuMs: number+idleMs: number+waitMs: number+```++## FrameProfileInput — interface @experimental+```+frameMs: number+gpuMs: number | undefined+nativeScopes: readonly ScopeCost[] | undefined+scopes: readonly ScopeCost[]+systems: readonly SystemCost[]+```+## FrameSnapshot — interface @experimental```frameTimeMs: number@@ -5077,6 +5113,7 @@ cleanup: ((app?: App) => void) | undefineddependencies: PluginDependency[] | undefinedfinish: ((app: App) => void) | undefinedname: string | undefined+profileDomain: string | undefined```## PluginDependency — type @experimental@@ -5354,6 +5391,21 @@ prefabEntityId: stringvisible: boolean```+## ProfileNode — interface @experimental+```+children: readonly ProfileNode[]+id: string+kind: ProfileNodeKind+label: string+ms: number+query: QueryCost | undefined+```++## ProfileNodeKind — type @experimental+```+'domain' | 'system' | 'scope' | 'wait' | 'rest'+```+## ProgressHandle — interface @experimental```dispose: () => void@@ -5450,6 +5502,7 @@ without: (...components: AnyComponentDef[]) => QueryBuilder<C>## QueryInstance — class @public```@internal resetTick: (tick: number) => void+@internal takeCost: () => QueryCost[Symbol.iterator]: () => Iterator<QueryResult<C>>count: () => numberforEach: (callback: (entity: Entity, ...components: ComponentsData<C>) => void) => void@@ -6167,6 +6220,19 @@ Startup = 0Update = 3```+## ScopeCost — interface @experimental+```+ms: number+name: string+remainder: ScopeRemainder+system: string+```++## ScopeRemainder — type @experimental+```+'work' | 'wait'+```+## ScreenInfo — class @experimental```dpr: number@@ -6822,6 +6888,14 @@ phaseAgeMs: number(path: string) => PrefabData | null```+## SystemCost — interface @experimental+```+domain: string+ms: number+name: string+query: QueryCost | undefined+```+## SystemDef — interface @public```@internal _fn: (...args: never[]) => void | Promise<void>@@ -6855,6 +6929,7 @@ runBefore: string[] | undefined```clearTimings: () => voidevict: (systemId: symbol) => void+getQueryCosts: () => ReadonlyMap<string, QueryCost> | nullgetTimings: () => ReadonlyMap<string, number> | nullreset: () => voidrun: (system: SystemDef) => void | Promise<void>@@ -8469,6 +8544,7 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal markChanged: (entity: Entity, component: AnyComponentDef) => void@internal queries_: QueryCache+@internal queryCostEnabled: boolean@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -8476,6 +8552,7 @@ tabIndex: number | undefined@internal resolveGetter: (component: AnyComponentDef) => ((entity: Entity) => unknown) | null@internal resolveHas: (component: AnyComponentDef) => ((entity: Entity) => boolean) | null@internal resolveSetter: (component: AnyComponentDef) => ((entity: Entity, data: unknown) => void) | null+@internal setQueryCostEnabled: (enabled: boolean) => voiddespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | null@@ -8777,6 +8854,11 @@ BtPlugin(material?: CollisionMaterial): TilesetModel```+## buildFrameProfile — function @experimental+```+(input: FrameProfileInput): FrameProfile+```+## buildTerrainIndices — function @experimental```(asset: TilesetAsset): TerrainIndices@@ -10587,6 +10669,11 @@ Plugin(sceneData: SceneData): boolean```+## scopeDomain — function @experimental+```+(name: string): string+```+## screenToUiWorld — function @experimental```(camera: UICameraData, screenGLX: number, screenGLY: number): { x: number; y: number; }diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.tsindex bc60e62b5..9a74e45ad 100644--- a/sdk/src/app/app.ts+++ b/sdk/src/app/app.ts@@ -29,6 +29,7 @@ import { cameraPlugin } from '../camera/CameraPlugin';import { ScreenScaling, SCREEN_FIT_OFF, type ScreenScalingData } from '../camera/ScreenScaling';import { PhysicsRuntime } from '../physics/PhysicsRuntime';import { SubsystemRegistry } from './subsystems';+import { DOMAIN_SCRIPTS, DOMAIN_UNATTRIBUTED, type ScopeCost, type ScopeRemainder, type SystemCost } from './frameProfile';import type { SideModuleHost } from '../sideModules/host';import { watchWebGPUDeviceLoss } from '../render/renderer';import { log } from '../util/logger';@@ -44,6 +45,9 @@ export interface Plugin {dependencies?: PluginDependency[];before?: string[];after?: string[];+ /** Cost domain the profiler files this plugin's systems under. Defaults to+ * `name`; declare it where the two differ, as `camera` producing `render`. */+ profileDomain?: string;build(app: App): void;finish?(app: App): void;cleanup?(app?: App): void;@@ -55,6 +59,12 @@ export interface Plugin {export type { RunCondition };+/** One frame's costs, attributed. The input `buildFrameProfile` folds. */+export interface FrameCosts {+ systems: SystemCost[];+ scopes: ScopeCost[];+}+interface SystemEntry {system: SystemDef;runBefore?: string[];@@ -69,6 +79,8 @@ interface SystemEntry {* hot-update rebind) carry no subsystem either, and mistaking them for* user systems vetoed every hot swap in any project that had physics. */fromBundle?: boolean;+ /** Cost domain, from the building plugin or the door it came through. */+ domain: string;}/**@@ -124,6 +136,8 @@ export class App {/** The plugin currently in build(), so systems it adds inherit its name for* liveness reporting. Null outside a build. */private buildingPlugin_: string | null = null;+ /** The cost domain of that plugin, which is its name unless it declared one. */+ private buildingDomain_: string | null = null;private addingBundleSystems_ = false;// The realm's acquirer for optional native modules (physics, spine). Set once// at app creation; physics/spine self-gate off it. Null in headless/test apps.@@ -139,7 +153,9 @@ export class App {// resolveCameras / submit split) — the JS-side sibling of the engine's C++// ES_PROFILE_SCOPE. Null unless stats are on; same per-frame lifecycle as// phaseTimings_ (cleared at tick start, read after the tick).- private frameScopes_: Map<string, number> | null = null;+ private frameScopes_: Map<string, ScopeCost> | null = null;+ /** The system being run, so a scope opened inside one is filed under it. */+ private currentSystem_ = '';private frame_paused_ = false;private user_paused_ = false;private step_pending_ = false;@@ -225,7 +241,9 @@ export class App {});}const prevBuilding = this.buildingPlugin_;+ const prevDomain = this.buildingDomain_;this.buildingPlugin_ = plugin.name ?? null;+ this.buildingDomain_ = plugin.profileDomain ?? plugin.name ?? null;try {plugin.build(this);// Sync plugin: live once build() returns → promote. An async plugin@@ -244,6 +262,7 @@ export class App {throw e;} finally {this.buildingPlugin_ = prevBuilding;+ this.buildingDomain_ = prevDomain;}return this;}@@ -272,6 +291,11 @@ export class App {* read properties of undefined (reading 'push')" thrown from inside a* minified bundle, naming neither the system nor the value.*/+ private registeringDomain_(): string {+ if (this.buildingDomain_) return this.buildingDomain_;+ return this.addingBundleSystems_ ? DOMAIN_SCRIPTS : DOMAIN_UNATTRIBUTED;+ }+private scheduleBucket_(schedule: Schedule, systemName: string): SystemEntry[] {const bucket = this.systems_.get(schedule);if (bucket) return bucket;@@ -314,6 +338,7 @@ export class App {runIf: options?.runIf,subsystem: this.buildingPlugin_ ?? undefined,fromBundle: this.addingBundleSystems_ || undefined,+ domain: this.registeringDomain_(),});this.sortedSystemsCache_.delete(schedule);return this;@@ -463,6 +488,7 @@ export class App {runAfter: mergedRunAfter,runIf,subsystem: this.buildingPlugin_ ?? undefined,+ domain: this.registeringDomain_(),});}this.sortedSystemsCache_.delete(schedule);@@ -657,22 +683,63 @@ export class App {* {@link getPhaseTimings}; surfaces as the profiler's `js.*` rows.*/getFrameScopes(): ReadonlyMap<string, number> | null {- return this.frameScopes_;+ if (!this.frameScopes_) return null;+ const flat = new Map<string, number>();+ for (const [name, scope] of this.frameScopes_) flat.set(name, scope.ms);+ return flat;+ }++ /**+ * This frame's costs with the attribution a profile tree needs: which domain+ * owns each system, which system each scope ran inside. Null when stats are+ * off. Feed to `buildFrameProfile`, which is where the tree is derived.+ */+ getFrameCosts(): FrameCosts | null {+ if (!this.frameScopes_) return null;+ const timings = this.runner_?.getTimings();+ const domains = new Map<string, string>();+ for (const entries of this.systems_.values()) {+ for (const entry of entries) domains.set(entry.system._name, entry.domain);+ }+ const queryCosts = this.runner_?.getQueryCosts();+ const systems: SystemCost[] = [];+ for (const [name, ms] of timings ?? []) {+ const query = queryCosts?.get(name);+ systems.push({+ name,+ ms,+ domain: domains.get(name) ?? DOMAIN_UNATTRIBUTED,+ ...(query ? { query } : {}),+ });+ }+ return { systems, scopes: [...this.frameScopes_.values()] };}/*** Time `fn` as a named sub-frame scope (accumulated if the name repeats in a* frame). A no-op passthrough when stats are off, so shipped games pay only a* single branch. Use it to split a heavy system into attributable pieces.+ *+ * `remainder: 'wait'` declares that whatever time is left under this scope+ * once its native scopes are subtracted is CPU blocked, not work — the+ * swapchain block a GPU submit absorbs, or an await. The profiler keeps such+ * time out of every cost total instead of reporting it as a hotspot.*/- measureFrameScope<T>(name: string, fn: () => T): T {+ measureFrameScope<T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder }): T {const scopes = this.frameScopes_;if (!scopes) return fn();const t0 = performance.now();try {return fn();} finally {- scopes.set(name, (scopes.get(name) ?? 0) + (performance.now() - t0));+ const elapsed = performance.now() - t0;+ const prev = scopes.get(name);+ scopes.set(name, {+ name,+ ms: (prev?.ms ?? 0) + elapsed,+ system: prev?.system ?? this.currentSystem_,+ remainder: options?.remainder ?? 'work',+ });}}@@ -1144,6 +1211,7 @@ export class App {for (const entry of systems) {if (entry.runIf && !entry.runIf()) continue;try {+ this.currentSystem_ = entry.system._name;const result = this.runner_.run(entry.system);if (result instanceof Promise) {await result;@@ -1164,6 +1232,8 @@ export class App {return;}}+ } finally {+ this.currentSystem_ = '';}}diff --git a/sdk/src/app/frameProfile.ts b/sdk/src/app/frameProfile.tsnew file mode 100644index 000000000..cd611b4fc--- /dev/null+++ b/sdk/src/app/frameProfile.ts@@ -0,0 +1,191 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file frameProfile.ts — the per-frame cost model every profiler view reads.+ */+import type { QueryCost } from '../ecs/query';++export type { QueryCost };++/** Systems a project registered, as opposed to any engine plugin's. */+export const DOMAIN_SCRIPTS = 'scripts';++/** Systems registered outside both a plugin build and the project bundle. */+export const DOMAIN_UNATTRIBUTED = 'unattributed';++/** Time under a scope that none of its children claimed. */+export type ScopeRemainder = 'work' | 'wait';++export interface SystemCost {+ readonly name: string;+ readonly ms: number;+ readonly domain: string;+ /** Absent when the system ran no query, or when accounting was off. */+ readonly query?: QueryCost;+}++export interface ScopeCost {+ readonly name: string;+ readonly ms: number;+ /** The system this ran inside; '' when it ran outside every system. */+ readonly system: string;+ readonly remainder: ScopeRemainder;+}++export interface FrameProfileInput {+ readonly frameMs: number;+ readonly systems: readonly SystemCost[];+ readonly scopes: readonly ScopeCost[];+ /** Scopes measured inside wasm. Adopted by the wait scope of their domain. */+ readonly nativeScopes?: readonly ScopeCost[];+ readonly gpuMs?: number;+}++export type ProfileNodeKind = 'domain' | 'system' | 'scope' | 'wait' | 'rest';++export interface ProfileNode {+ readonly id: string;+ readonly label: string;+ readonly ms: number;+ readonly kind: ProfileNodeKind;+ readonly children: readonly ProfileNode[];+ /** On a system node that ran a query — why its time is what it is. */+ readonly query?: QueryCost;+}++/**+ * `frameMs === cpuMs + waitMs + idleMs`, and every node's ms equals the sum of+ * its children. `gpuMs` is a parallel track and is in none of those sums.+ */+export interface FrameProfile {+ readonly frameMs: number;+ readonly cpuMs: number;+ readonly waitMs: number;+ readonly idleMs: number;+ readonly gpuMs: number;+ readonly domains: readonly ProfileNode[];+}++/** Below this a row is noise, and a `rest` row for it would be rounding dust. */+const EPS_MS = 0.05;++/** The part of a dotted scope name that names its domain. */+export function scopeDomain(name: string): string {+ const dot = name.indexOf('.');+ return dot > 0 ? name.slice(0, dot) : name;+}++function sumMs(nodes: readonly ProfileNode[]): number {+ let total = 0;+ for (const n of nodes) total += n.ms;+ return total;+}++function byMsDesc(a: ProfileNode, b: ProfileNode): number {+ return b.ms - a.ms;+}++/**+ * Fold one frame's flat measurements into the tree the profiler renders.+ *+ * Pure, so the live editor view, an imported capture and the agent all derive+ * the same numbers from the same rule rather than each rounding their own way.+ */+export function buildFrameProfile(input: FrameProfileInput): FrameProfile {+ const nativeByDomain = new Map<string, ScopeCost[]>();+ for (const n of input.nativeScopes ?? []) {+ const d = scopeDomain(n.name);+ const list = nativeByDomain.get(d);+ if (list) list.push(n); else nativeByDomain.set(d, [n]);+ }++ const scopesBySystem = new Map<string, ScopeCost[]>();+ for (const s of input.scopes) {+ const list = scopesBySystem.get(s.system);+ if (list) list.push(s); else scopesBySystem.set(s.system, [s]);+ }++ let waitTotal = 0;+ const domains = new Map<string, ProfileNode[]>();++ for (const sys of input.systems) {+ const children: ProfileNode[] = [];+ let systemWait = 0;++ for (const scope of scopesBySystem.get(sys.name) ?? []) {+ const adopted = scope.remainder === 'wait'+ ? (nativeByDomain.get(scopeDomain(scope.name)) ?? [])+ : [];+ const grandChildren = adopted.map((n): ProfileNode => ({+ id: `${sys.name}/${scope.name}/${n.name}`,+ label: n.name,+ ms: n.ms,+ kind: 'scope',+ children: [],+ }));+ const rest = Math.max(0, scope.ms - sumMs(grandChildren));+ if (rest >= EPS_MS) {+ grandChildren.push({+ id: `${sys.name}/${scope.name}/~`,+ label: scope.remainder === 'wait' ? 'wait' : 'rest',+ ms: rest,+ kind: scope.remainder === 'wait' ? 'wait' : 'rest',+ children: [],+ });+ if (scope.remainder === 'wait') systemWait += rest;+ }+ grandChildren.sort(byMsDesc);+ children.push({+ id: `${sys.name}/${scope.name}`,+ label: scope.name,+ ms: scope.ms,+ kind: 'scope',+ children: grandChildren,+ });+ }++ const work = Math.max(0, sys.ms - systemWait);+ const measured = sumMs(children) - systemWait;+ const rest = Math.max(0, work - measured);+ if (children.length > 0 && rest >= EPS_MS) {+ children.push({ id: `${sys.name}/~`, label: 'rest', ms: rest, kind: 'rest', children: [] });+ }+ children.sort(byMsDesc);++ waitTotal += systemWait;+ const node: ProfileNode = {+ id: sys.name,+ label: sys.name,+ ms: work,+ kind: 'system',+ children,+ ...(sys.query ? { query: sys.query } : {}),+ };+ const list = domains.get(sys.domain);+ if (list) list.push(node); else domains.set(sys.domain, [node]);+ }++ const domainNodes: ProfileNode[] = [];+ for (const [domain, systems] of domains) {+ systems.sort(byMsDesc);+ domainNodes.push({+ id: domain,+ label: domain,+ ms: sumMs(systems),+ kind: 'domain',+ children: systems,+ });+ }+ domainNodes.sort(byMsDesc);++ const cpuMs = sumMs(domainNodes);+ const frameMs = Math.max(input.frameMs, cpuMs + waitTotal);+ return {+ frameMs,+ cpuMs,+ waitMs: waitTotal,+ idleMs: Math.max(0, frameMs - cpuMs - waitTotal),+ gpuMs: input.gpuMs ?? -1,+ domains: domainNodes,+ };+}diff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.tsindex 34398f8ea..9e45f7010 100644--- a/sdk/src/camera/CameraPlugin.ts+++ b/sdk/src/camera/CameraPlugin.ts@@ -497,6 +497,7 @@ export function cameraPlugin(): Plugin {return {name: 'camera',+ profileDomain: 'render',build(app: App) {// Null on the native core: the two engine queries this plugin makes are// answered by the registry there (see canvasEntityOf / cameraEntitiesOf),@@ -616,7 +617,7 @@ export function cameraPlugin(pipeline.endScreenCapture();Renderer.setViewport(0, 0, width, height);}- });+ }, { remainder: 'wait' });},};diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.tsindex 7757f85fb..7effe9d42 100644--- a/sdk/src/core-runtime.ts+++ b/sdk/src/core-runtime.ts@@ -395,6 +395,7 @@ export { writePtrField, readPtrField } from './ecs/bridge/BuiltinBridge';export {App,flushPendingSystems,+ type FrameCosts,type Plugin,type PluginDependency,type WebAppOptions,diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.tsindex c4bed5b94..bc37f4e80 100644--- a/sdk/src/core-sys.ts+++ b/sdk/src/core-sys.ts@@ -201,6 +201,20 @@ export {export { StatsOverlay, type StatsPosition } from './stats-overlay';+export {+ buildFrameProfile,+ scopeDomain,+ DOMAIN_SCRIPTS,+ DOMAIN_UNATTRIBUTED,+ type FrameProfile,+ type FrameProfileInput,+ type ProfileNode,+ type ProfileNodeKind,+ type ScopeCost,+ type ScopeRemainder,+ type SystemCost,+} from './app/frameProfile';+// =============================================================================// Timer// =============================================================================diff --git a/sdk/src/ecs/query.ts b/sdk/src/ecs/query.tsindex c6c60ef36..c893b52c7 100644--- a/sdk/src/ecs/query.ts+++ b/sdk/src/ecs/query.ts@@ -374,6 +374,16 @@ export type QueryResult<C extends readonly QueryArg[]> = [// Query Instance (Runtime)// =============================================================================+/** What a system's queries walked in a frame, and what they then discarded. */+export interface QueryCost {+ /** Times the system asked a query for its entities. */+ calls: number;+ /** Entities those calls walked, summed. */+ scanned: number;+ /** Of those, entities an Added/Changed filter rejected. */+ filtered: number;+}+/*** A live query, as a system body receives it. Iterate it — each step yields the* entity followed by its components — or use `forEach`, `single`, `toArray`,@@ -394,6 +404,9 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu// precomputed like cacheKey_ so per-call query iteration allocates no array.private readonly depIds_: symbol[];private lastRunTick_: number;+ private calls_ = 0;+ private scanned_ = 0;+ private filtered_ = 0;private readonly getters_: Array<((entity: Entity) => unknown) | null>;private readonly mutSetters_: Array<((entity: Entity, data: unknown) => void) | null>;private readonly mutIsBuiltin_: boolean[];@@ -458,7 +471,7 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu* so none of them can disagree about the cache key or the dep set.*/private candidates_(): readonly Entity[] {- return this.world_.queryEntities(+ const entities = this.world_.queryEntities(this.allRequired_,this.descriptor_._with,this.descriptor_._without,@@ -466,6 +479,24 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Quthis.compiledFilter_ ?? undefined,this.depIds_,);+ if (this.world_.queryCostEnabled) {+ this.calls_++;+ this.scanned_ += entities.length;+ }+ return entities;+ }++ /**+ * @internal What this query cost since the last read: how many times it was+ * asked, how many entities that walked, and how many of those a change filter+ * then threw away. Reset by the read, so a frame's figure is that frame's.+ */+ takeCost(): QueryCost {+ const cost = { calls: this.calls_, scanned: this.scanned_, filtered: this.filtered_ };+ this.calls_ = 0;+ this.scanned_ = 0;+ this.filtered_ = 0;+ return cost;}private hasChangeFilters_(): boolean {@@ -477,14 +508,19 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Quif (_addedFilters.length === 0 && _changedFilters.length === 0) return true;const tick = this.lastRunTick_;for (const f of _addedFilters) {- if (!this.world_.isAddedSince(entity, f.component, tick)) return false;+ if (!this.world_.isAddedSince(entity, f.component, tick)) return this.rejected_();}for (const f of _changedFilters) {- if (!this.world_.isChangedSince(entity, f.component, tick)) return false;+ if (!this.world_.isChangedSince(entity, f.component, tick)) return this.rejected_();}return true;}+ private rejected_(): false {+ if (this.world_.queryCostEnabled) this.filtered_++;+ return false;+ }+/*** Write buffered Mut() data back to storage for one entity and record a* Changed tick for each mutated component. This is the single write-back pathdiff --git a/sdk/src/ecs/system.ts b/sdk/src/ecs/system.tsindex 6ce9848ad..d493aec7c 100644--- a/sdk/src/ecs/system.ts+++ b/sdk/src/ecs/system.ts@@ -7,7 +7,7 @@import { AnyComponentDef } from './component';import { getDefaultContext } from './context';-import { QueryDescriptor, QueryInstance, QueryArg, RemovedQueryDescriptor, RemovedQueryInstance } from './query';+import { QueryDescriptor, QueryInstance, QueryArg, RemovedQueryDescriptor, RemovedQueryInstance, type QueryCost } from './query';import { ResDescriptor, ResMutDescriptor, ResMutInstance, ResourceStorage } from './resource';import { CommandsDescriptor, CommandsInstance } from './commands';import {@@ -353,6 +353,7 @@ export class SystemRunner {private readonly removedCache_ = new Map<symbol, RemovedQueryInstance<any>[]>();private currentLastRunTick_ = -1;private timings_: Map<string, number> | null = null;+ private queryCosts_: Map<string, QueryCost> | null = null;constructor(world: World, resources: ResourceStorage, eventRegistry?: EventRegistry) {this.world_ = world;@@ -362,15 +363,27 @@ export class SystemRunner {setTimingEnabled(enabled: boolean): void {this.timings_ = enabled ? new Map() : null;+ this.queryCosts_ = enabled ? new Map() : null;+ this.world_.setQueryCostEnabled(enabled);}getTimings(): ReadonlyMap<string, number> | null {return this.timings_;}+ /**+ * Per-system query cost for the frame: what each system's queries walked, and+ * how much of that a change filter then discarded. This is what turns "7ms"+ * into "7ms over 18,400 entities, none of which had changed".+ */+ getQueryCosts(): ReadonlyMap<string, QueryCost> | null {+ return this.queryCosts_;+ }+/** @brief Clear timing data for the current frame */clearTimings(): void {this.timings_?.clear();+ this.queryCosts_?.clear();}/** @brief Remove cached state for a single system */@@ -475,13 +488,34 @@ export class SystemRunner {(args[i] as CommandsInstance).flush();}}+ if (this.queryCosts_) {+ this.harvestQueryCost_(system);+ }if (this.timings_) {- this.timings_.set(system._name, performance.now() - t0);+ // Accumulated, not assigned: a fixed schedule runs as many times in one+ // frame as the accumulator has steps for, and the frame cost of such a+ // system is all of them. Assigning reported the last step alone.+ const name = system._name;+ this.timings_.set(name, (this.timings_.get(name) ?? 0) + (performance.now() - t0));}this.world_.resetIterationDepth();this.systemTicks_.set(system._id, this.world_.getWorldTick());}+ private harvestQueryCost_(system: SystemDef): void {+ const queries = this.queryCache_.get(system._id);+ if (!queries || queries.length === 0) return;+ const name = system._name;+ const total = this.queryCosts_!.get(name) ?? { calls: 0, scanned: 0, filtered: 0 };+ for (const q of queries) {+ const cost = q.takeCost();+ total.calls += cost.calls;+ total.scanned += cost.scanned;+ total.filtered += cost.filtered;+ }+ if (total.calls > 0) this.queryCosts_!.set(name, total);+ }+private resolveParam(param: SystemParam): unknown {switch (param._type) {case 'res':diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex 165171d93..5c5ec8338 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -134,6 +134,7 @@ export class World {private entities_ = new Map<Entity, number>();private indexGeneration_ = new Map<number, number>(); // index -> current generation (for isStale detection)private iterationDepth_ = 0;+ private queryCostEnabled_ = false;private nextEntityIndex_ = 0; // pure-JS fallback: monotonic index counterprivate nextGeneration_ = 0;private spawnCallbacks_: Array<(entity: Entity) => void> = [];@@ -405,6 +406,20 @@ export class World {this.queries_.resetStats();}+ /**+ * @internal Whether queries count what they scan. Per-World rather than a+ * module flag: the editor realm and the play realm are separate Apps in one+ * process, and a shared switch would have each turn the other's accounting on.+ */+ setQueryCostEnabled(enabled: boolean): void {+ this.queryCostEnabled_ = enabled;+ }++ /** @internal */+ get queryCostEnabled(): boolean {+ return this.queryCostEnabled_;+ }+/** @internal Iteration depth is what makes spawn/despawn refuse mid-query. */beginIteration(): void {this.iterationDepth_++;diff --git a/sdk/tests/frame-costs.test.ts b/sdk/tests/frame-costs.test.tsnew file mode 100644index 000000000..1dfa4eede--- /dev/null+++ b/sdk/tests/frame-costs.test.ts@@ -0,0 +1,164 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { App, type Plugin } from '../src/app/app';+import { Schedule, defineSystem, defineSystemSet } from '../src/ecs/system';+import { DOMAIN_SCRIPTS, DOMAIN_UNATTRIBUTED, buildFrameProfile } from '../src/app/frameProfile';++function domainOf(app: App, systemName: string): string | undefined {+ return app.getFrameCosts()?.systems.find((s) => s.name === systemName)?.domain;+}++function pluginAdding(name: string, systemName: string, extra?: Partial<Plugin>): Plugin {+ return {+ name,+ ...extra,+ build(app) {+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {}, { name: systemName }));+ },+ };+}++describe('App.getFrameCosts', () => {+ it('is null until stats are enabled', async () => {+ const app = App.new();+ await app.tick(1 / 60);+ expect(app.getFrameCosts()).toBeNull();+ });++ it('files the systems of a plugin under the plugin name', async () => {+ const app = App.new().enableStats();+ app.addPlugin(pluginAdding('physics', 'PhysicsStep'));+ await app.tick(1 / 60);++ expect(domainOf(app, 'PhysicsStep')).toBe('physics');+ });++ it('files them under profileDomain where a plugin declares one', async () => {+ const app = App.new().enableStats();+ app.addPlugin(pluginAdding('camera', 'RenderSystem', { profileDomain: 'render' }));+ await app.tick(1 / 60);++ expect(domainOf(app, 'RenderSystem')).toBe('render');+ });++ it('files project systems under scripts', async () => {+ const app = App.new().enableStats();+ app.addBundleSystems([+ { schedule: Schedule.Update, system: defineSystem([], () => {}, { name: 'EnemyAI' }) },+ ]);+ await app.tick(1 / 60);++ expect(domainOf(app, 'EnemyAI')).toBe(DOMAIN_SCRIPTS);+ });++ it('files a project system SET under scripts too', async () => {+ const app = App.new().enableStats();+ app.addBundleSystems([+ {+ schedule: Schedule.Update,+ system: defineSystemSet('ai', {+ systems: [defineSystem([], () => {}, { name: 'EnemyAI' })],+ }),+ },+ ]);+ await app.tick(1 / 60);++ expect(domainOf(app, 'EnemyAI')).toBe(DOMAIN_SCRIPTS);+ });++ it('says so rather than guessing when a system came through neither door', async () => {+ const app = App.new().enableStats();+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {}, { name: 'Loose' }));+ await app.tick(1 / 60);++ expect(domainOf(app, 'Loose')).toBe(DOMAIN_UNATTRIBUTED);+ });++ it('restores the outer domain after a nested plugin build', async () => {+ const inner = pluginAdding('audio', 'AudioUpdate');+ const outer: Plugin = {+ name: 'camera',+ profileDomain: 'render',+ build(app) {+ app.addPlugin(inner);+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {}, { name: 'RenderSystem' }));+ },+ };+ const app = App.new().enableStats();+ app.addPlugin(outer);+ await app.tick(1 / 60);++ expect(domainOf(app, 'AudioUpdate')).toBe('audio');+ expect(domainOf(app, 'RenderSystem')).toBe('render');+ });+});++describe('measureFrameScope attribution', () => {+ it('files a scope under the system it was opened inside', async () => {+ const app = App.new().enableStats();+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {+ app.measureFrameScope('render.submit', () => {});+ }, { name: 'RenderSystem' }));+ await app.tick(1 / 60);++ const scope = app.getFrameCosts()?.scopes.find((s) => s.name === 'render.submit');+ expect(scope?.system).toBe('RenderSystem');+ expect(scope?.remainder).toBe('work');+ });++ it('leaves a scope opened outside every system unattributed', async () => {+ const app = App.new().enableStats();+ await app.tick(1 / 60);+ app.measureFrameScope('boot.warmup', () => {});++ expect(app.getFrameCosts()?.scopes.find((s) => s.name === 'boot.warmup')?.system).toBe('');+ });++ it('does not leak the last system onto a scope opened after the schedule', async () => {+ const app = App.new().enableStats();+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {}, { name: 'RenderSystem' }));+ await app.tick(1 / 60);+ app.measureFrameScope('after.frame', () => {});++ expect(app.getFrameCosts()?.scopes.find((s) => s.name === 'after.frame')?.system).toBe('');+ });++ it('carries the declared remainder through to the profile', async () => {+ const app = App.new().enableStats();+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {+ app.measureFrameScope('render.submit', () => {}, { remainder: 'wait' });+ }, { name: 'RenderSystem' }));+ await app.tick(1 / 60);++ const costs = app.getFrameCosts()!;+ expect(costs.scopes.find((s) => s.name === 'render.submit')?.remainder).toBe('wait');+ const profile = buildFrameProfile({ frameMs: 16.7, ...costs });+ expect(profile.cpuMs + profile.waitMs + profile.idleMs).toBeCloseTo(profile.frameMs, 4);+ });++ it('accumulates a repeated scope name without losing its system', async () => {+ const app = App.new().enableStats();+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {+ app.measureFrameScope('ui.layout', () => {});+ app.measureFrameScope('ui.layout', () => {});+ }, { name: 'UILayoutSystem' }));+ await app.tick(1 / 60);++ const scopes = app.getFrameCosts()!.scopes.filter((s) => s.name === 'ui.layout');+ expect(scopes).toHaveLength(1);+ expect(scopes[0].system).toBe('UILayoutSystem');+ });++ it('keeps getFrameScopes as the flat view of the same measurements', async () => {+ const app = App.new().enableStats();+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {+ app.measureFrameScope('ui.layout', () => {});+ }, { name: 'UILayoutSystem' }));+ await app.tick(1 / 60);++ const flat = app.getFrameScopes()!;+ const costs = app.getFrameCosts()!;+ expect(flat.get('ui.layout')).toBe(costs.scopes.find((s) => s.name === 'ui.layout')!.ms);+ });+});diff --git a/sdk/tests/frame-profile.test.ts b/sdk/tests/frame-profile.test.tsnew file mode 100644index 000000000..8c25ddc96--- /dev/null+++ b/sdk/tests/frame-profile.test.ts@@ -0,0 +1,181 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import {+ buildFrameProfile,+ scopeDomain,+ DOMAIN_SCRIPTS,+ type FrameProfileInput,+ type ProfileNode,+} from '../src/app/frameProfile';++function findNode(nodes: readonly ProfileNode[], id: string): ProfileNode | null {+ for (const n of nodes) {+ if (n.id === id) return n;+ const hit = findNode(n.children, id);+ if (hit) return hit;+ }+ return null;+}++function assertChildrenSum(node: ProfileNode): void {+ if (node.children.length === 0) return;+ const sum = node.children.reduce((acc, c) => acc + c.ms, 0);+ expect(sum).toBeCloseTo(node.ms, 4);+ for (const c of node.children) assertChildrenSum(c);+}++describe('scopeDomain', () => {+ it('takes the segment before the first dot', () => {+ expect(scopeDomain('render.submit')).toBe('render');+ expect(scopeDomain('render.gl.upload')).toBe('render');+ });++ it('treats an undotted name as its own domain', () => {+ expect(scopeDomain('layout')).toBe('layout');+ });+});++describe('buildFrameProfile', () => {+ it('groups systems under their domain and sums the domain from them', () => {+ const profile = buildFrameProfile({+ frameMs: 16.7,+ systems: [+ { name: 'EnemyAI', ms: 1.8, domain: DOMAIN_SCRIPTS },+ { name: 'ProjectileSystem', ms: 0.9, domain: DOMAIN_SCRIPTS },+ { name: 'PhysicsStep', ms: 3.2, domain: 'physics' },+ ],+ scopes: [],+ });++ const scripts = findNode(profile.domains, DOMAIN_SCRIPTS);+ expect(scripts?.ms).toBeCloseTo(2.7, 4);+ expect(scripts?.children.map((c) => c.label)).toEqual(['EnemyAI', 'ProjectileSystem']);+ expect(findNode(profile.domains, 'physics')?.ms).toBeCloseTo(3.2, 4);+ });++ it('ranks domains and their systems by cost', () => {+ const profile = buildFrameProfile({+ frameMs: 16.7,+ systems: [+ { name: 'Cheap', ms: 0.2, domain: DOMAIN_SCRIPTS },+ { name: 'Dear', ms: 4.0, domain: DOMAIN_SCRIPTS },+ { name: 'PhysicsStep', ms: 3.2, domain: 'physics' },+ ],+ scopes: [],+ });++ expect(profile.domains.map((d) => d.id)).toEqual([DOMAIN_SCRIPTS, 'physics']);+ expect(profile.domains[0].children.map((c) => c.label)).toEqual(['Dear', 'Cheap']);+ });++ it('keeps frameMs = cpu + wait + idle', () => {+ const profile = buildFrameProfile({+ frameMs: 16.7,+ systems: [{ name: 'PhysicsStep', ms: 3.2, domain: 'physics' }],+ scopes: [],+ });++ expect(profile.cpuMs + profile.waitMs + profile.idleMs).toBeCloseTo(profile.frameMs, 4);+ expect(profile.idleMs).toBeCloseTo(13.5, 4);+ });++ it('never reports negative idle when the frame is shorter than its measurements', () => {+ const profile = buildFrameProfile({+ frameMs: 1,+ systems: [{ name: 'PhysicsStep', ms: 9, domain: 'physics' }],+ scopes: [],+ });++ expect(profile.idleMs).toBe(0);+ expect(profile.frameMs).toBeCloseTo(9, 4);+ });++ it('nests a scope under the system it ran inside, with the rest accounted for', () => {+ const profile = buildFrameProfile({+ frameMs: 16.7,+ systems: [{ name: 'RenderSystem', ms: 4, domain: 'render' }],+ scopes: [+ { name: 'render.resolveCameras', ms: 1, system: 'RenderSystem', remainder: 'work' },+ ],+ });++ const sys = findNode(profile.domains, 'RenderSystem');+ expect(sys?.ms).toBeCloseTo(4, 4);+ expect(sys?.children.map((c) => c.label)).toEqual(['rest', 'render.resolveCameras']);+ assertChildrenSum(profile.domains[0]);+ });++ it('reads an empty frame as all idle', () => {+ const profile = buildFrameProfile({ frameMs: 16.7, systems: [], scopes: [] });++ expect(profile.domains).toEqual([]);+ expect(profile.cpuMs).toBe(0);+ expect(profile.idleMs).toBeCloseTo(16.7, 4);+ });++ it('carries gpu as a parallel track outside the cpu sums', () => {+ const profile = buildFrameProfile({+ frameMs: 16.7,+ systems: [{ name: 'RenderSystem', ms: 2, domain: 'render' }],+ scopes: [],+ gpuMs: 5.6,+ });++ expect(profile.gpuMs).toBeCloseTo(5.6, 4);+ expect(profile.cpuMs).toBeCloseTo(2, 4);+ expect(profile.cpuMs + profile.waitMs + profile.idleMs).toBeCloseTo(profile.frameMs, 4);+ });++ it('reports gpu as unavailable rather than zero when no timer answered', () => {+ const profile = buildFrameProfile({ frameMs: 16.7, systems: [], scopes: [] });+ expect(profile.gpuMs).toBe(-1);+ });++ // The empty-scene reading this model has to reproduce: a 2.1ms RenderSystem+ // that is 0.03ms of work and the rest blocked on the swapchain.+ describe('a scope whose remainder is a wait', () => {+ const emptyScene: FrameProfileInput = {+ frameMs: 16.7,+ systems: [{ name: 'RenderSystem', ms: 2.1, domain: 'render' }],+ scopes: [{ name: 'render.submit', ms: 2.1, system: 'RenderSystem', remainder: 'wait' }],+ nativeScopes: [+ { name: 'render.collect', ms: 0.02, system: '', remainder: 'work' },+ { name: 'render.finalize', ms: 0.01, system: '', remainder: 'work' },+ ],+ };++ it('keeps the wait out of the system, the domain and the cpu total', () => {+ const profile = buildFrameProfile(emptyScene);++ expect(findNode(profile.domains, 'RenderSystem')?.ms).toBeCloseTo(0.03, 4);+ expect(findNode(profile.domains, 'render')?.ms).toBeCloseTo(0.03, 4);+ expect(profile.cpuMs).toBeCloseTo(0.03, 4);+ expect(profile.waitMs).toBeCloseTo(2.07, 4);+ });++ it('still adds up to the frame', () => {+ const profile = buildFrameProfile(emptyScene);+ expect(profile.cpuMs + profile.waitMs + profile.idleMs).toBeCloseTo(16.7, 4);+ });++ it('shows the native work under the scope that blocked on it', () => {+ const profile = buildFrameProfile(emptyScene);+ const scope = findNode(profile.domains, 'RenderSystem/render.submit');++ expect(scope?.children.map((c) => c.label)).toEqual(['wait', 'render.collect', 'render.finalize']);+ assertChildrenSum(scope!);+ });++ it('does not hand the same native scope to a work scope', () => {+ const profile = buildFrameProfile({+ ...emptyScene,+ scopes: [{ name: 'render.submit', ms: 2.1, system: 'RenderSystem', remainder: 'work' }],+ });++ expect(profile.waitMs).toBe(0);+ expect(findNode(profile.domains, 'RenderSystem/render.submit')?.children.map((c) => c.label))+ .toEqual(['rest']);+ });+ });+});diff --git a/sdk/tests/query-cost.test.ts b/sdk/tests/query-cost.test.tsnew file mode 100644index 000000000..35cb9bf12--- /dev/null+++ b/sdk/tests/query-cost.test.ts@@ -0,0 +1,140 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { App } from '../src/app/app';+import { Schedule, defineSystem } from '../src/ecs/system';+import { defineComponent } from '../src/ecs/component';+import { Query, Mut, Changed } from '../src/ecs/query';+import type { QueryCost } from '../src/ecs/query';++const Position = defineComponent('QueryCostPosition', { x: 0, y: 0 });++function spawn(app: App, n: number): void {+ for (let i = 0; i < n; i++) {+ app.world.insert(app.world.spawn(), Position, { x: i, y: 0 });+ }+}++function costOf(app: App, systemName: string): QueryCost | undefined {+ return app.getFrameCosts()?.systems.find((s) => s.name === systemName)?.query;+}++describe('per-system query cost', () => {+ it('reports the entities a system walked', async () => {+ const app = App.new().enableStats();+ spawn(app, 40);+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Position)], (q) => {+ for (const _ of q) { /* walk */ }+ }, { name: 'Walker' }));+ await app.tick(1 / 60);++ expect(costOf(app, 'Walker')).toEqual({ calls: 1, scanned: 40, filtered: 0 });+ });++ it('counts every entry point, not just the iterator', async () => {+ const app = App.new().enableStats();+ spawn(app, 10);+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Position)], (q) => {+ q.count();+ q.toArray();+ q.isEmpty();+ }, { name: 'Asker' }));+ await app.tick(1 / 60);++ expect(costOf(app, 'Asker')).toMatchObject({ calls: 3, scanned: 30 });+ });++ it('separates what a change filter discarded from what it walked', async () => {+ const app = App.new().enableStats();+ spawn(app, 30);+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Changed(Position))], (q) => {+ for (const _ of q) { /* only the changed ones */ }+ }, { name: 'Reactor' }));++ await app.tick(1 / 60);+ await app.tick(1 / 60);+ const cost = costOf(app, 'Reactor')!;++ // The filter is doing its job and the walk is still the whole set — the+ // finding a Changed() query exists to make visible.+ expect(cost.scanned).toBe(30);+ expect(cost.filtered).toBe(30);+ });++ it('shows nothing discarded when the changes are real', async () => {+ const app = App.new().enableStats();+ spawn(app, 5);+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Mut(Position))], (q) => {+ for (const [, p] of q) p.x += 1;+ }, { name: 'Mover' }));+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Changed(Position))], (q) => {+ for (const _ of q) { /* every one of them changed */ }+ }, { name: 'Reactor' }));++ await app.tick(1 / 60);+ await app.tick(1 / 60);++ expect(costOf(app, 'Reactor')).toMatchObject({ scanned: 5, filtered: 0 });+ });++ it('leaves a system that runs no query without a cost', async () => {+ const app = App.new().enableStats();+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {}, { name: 'Quiet' }));+ await app.tick(1 / 60);++ expect(costOf(app, 'Quiet')).toBeUndefined();+ });++ it('does not carry a frame of cost into the next one', async () => {+ const app = App.new().enableStats();+ spawn(app, 12);+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Position)], (q) => {+ q.count();+ }, { name: 'Walker' }));++ await app.tick(1 / 60);+ await app.tick(1 / 60);++ expect(costOf(app, 'Walker')).toEqual({ calls: 1, scanned: 12, filtered: 0 });+ });++ it('counts nothing while stats are off', async () => {+ const app = App.new();+ spawn(app, 10);+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Position)], (q) => {+ q.count();+ }, { name: 'Walker' }));+ await app.tick(1 / 60);++ expect(app.getFrameCosts()).toBeNull();+ expect(app.world.queryCostEnabled).toBe(false);+ });+});++describe('a system that runs several times in one frame', () => {+ it('is charged for all of its fixed steps, not just the last', async () => {+ const app = App.new().enableStats();+ app.setFixedTimestep(1 / 60);+ spawn(app, 8);+ app.addSystemToSchedule(Schedule.FixedUpdate, defineSystem([Query(Position)], (q) => {+ q.count();+ }, { name: 'FixedWalker' }));++ // Four timesteps' worth of delta in one frame.+ await app.tick(4 / 60);++ expect(costOf(app, 'FixedWalker')).toMatchObject({ calls: 4, scanned: 32 });+ });++ it('sums its time over those steps too', async () => {+ const app = App.new().enableStats();+ app.setFixedTimestep(1 / 60);+ let runs = 0;+ app.addSystemToSchedule(Schedule.FixedUpdate, defineSystem([], () => { runs++; }, { name: 'FixedTimed' }));++ await app.tick(4 / 60);++ expect(runs).toBe(4);+ expect(app.getSystemTimings()?.has('FixedTimed')).toBe(true);+ });+});