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 shipped game records its own frames
yhhb5433b56d505
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9af0df9b4..8a9877cd5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -129,6 +129,25 @@ published separately; it ships inside the editor.frames that are not frames, a version newer than this editor reads — instead ofthrowing where a panel cannot say why.+- **A shipped game records its own frames.** `ProfileRecorder` writes the same+ capture the panel opens, from a running build, so the answer to "why is the+ boss fight 40fps on that phone" is measured on that phone. It measures nothing+ of its own — every number comes from a channel the engine already publishes —+ and `start()` turns on both halves of the instrumentation, because a capture+ missing the engine's C++ scopes reads as an engine that costs nothing rather+ than one that was not measured.++ It chooses no destination. `take()` returns an object and the engine opens no+ socket, has no endpoint and writes no file, which is also why there is nothing+ per-platform to wire: a recorder that never saves anything runs wherever the+ engine does.++- **`app.onFrameEnd` — the frame, once its timings are final.** The recorder+ needed a moment that did not exist: inside a system a frame is half-measured,+ and the last schedule is only last until something else registers there. The+ observer fires after the frame, and is a broadcast rather than a slot, so a+ game's own budget alarm can watch beside the recorder instead of replacing it.+- **One derivation, three readers.** `buildFrameProfile` is a pure function overplain per-frame data, so the live view, a pinned frame and a recorded sessioncannot each round their own way to a different answer. The editor's owndiff --git a/docs/astro/src/content/docs/performance/profiling.mdx b/docs/astro/src/content/docs/performance/profiling.mdxindex 424a101f5..44b1b67a9 100644--- a/docs/astro/src/content/docs/performance/profiling.mdx+++ b/docs/astro/src/content/docs/performance/profiling.mdx@@ -137,6 +137,78 @@ Two small utilities back the plugin and are exported for custom tooling:| `phaseTimings` | Per-phase ms (copied at push time). || `systemTimings` | Per-system ms (copied at push time). |+## Recording a capture from a shipped game — `ProfileRecorder`++The editor's profiler only exists where the editor is attached, and what drops+to 40 fps usually drops on a player's device. `ProfileRecorder` records+frames from a running game into a **`.esprof` capture** the editor's Profiler+panel opens — the same tree, the same rows, the same totals.++```typescript+import { ProfileRecorder } from 'esengine';++const recorder = new ProfileRecorder(app, {+ maxFrames: 1800, // ~30s at 60Hz; oldest dropped after+ source: { platform: 'wechat', label: 'Redmi Note 12 · boss fight' },+});++recorder.start();+// … play the part that stutters …+recorder.stop();++const capture = recorder.take(); // a plain object+```++| `ProfileRecorderOptions` | Type | Default | Description |+|---|---|---|---|+| `maxFrames` | number | `1800` | Frames kept before the oldest is dropped. |+| `budgetMs` | number | `1000 / 60` | The budget a reader judges the capture against. |+| `source` | `CaptureSource` | `{}` | Device, build, scene — whatever identifies this capture later. |++`start()` turns on the instrumentation it reads — both the JS-side stats and the+engine's C++ profiling, since a capture missing the second looks like an engine+that costs nothing rather than one that was not measured — and `stop()` puts them+back down. Nothing is recorded, and nothing is measured, until you start it.++<Aside type="tip" title="The engine never chooses a destination">+`take()` hands back an object and stops there. The engine opens no socket, has+no endpoint and writes no file, so a capture goes wherever your game sends it —+a download, your own upload, a log line. That is also why there is nothing+platform-specific to wire up: the recorder itself runs anywhere the engine does.+</Aside>++Saving it from a web build is ordinary DOM:++```typescript+const blob = new Blob([JSON.stringify(recorder.take())], { type: 'application/json' });+const a = document.createElement('a');+a.href = URL.createObjectURL(blob);+a.download = 'boss-fight.esprof';+a.click();+```++Then open it with **Profiler ▸ Open…** in the editor. `parseProfileCapture`+refuses a file that is not a capture with the reason (not JSON, no version,+frames that are not frames, a version newer than the editor reads) rather than+throwing, and `summarizeCapture` is the same function the live view uses — so a+file recorded on a phone and the editor's own last second cannot report a+different frame rate from the same frames.++### Watching frames yourself — `app.onFrameEnd`++The recorder is an ordinary consumer of `app.onFrameEnd(fn)`, which fires once+per frame after its systems have run and its timings are final. It is a+broadcast, so your own frame-budget alarm can watch alongside the recorder:++```typescript+const off = app.onFrameEnd((dtMs) => {+ if (dtMs > 33) console.warn(`long frame: ${dtMs.toFixed(1)}ms`);+});+```++It returns a disposer. Pair it with `app.getFrameCosts()` for the per-system and+per-scope costs of the frame that just ended.+## LoggingThe SDK routes its own diagnostics through a structured logger instead of rawdiff --git a/docs/astro/src/content/docs/zh-cn/performance/profiling.mdx b/docs/astro/src/content/docs/zh-cn/performance/profiling.mdxindex 8ef7e5c68..6ace99e7a 100644--- a/docs/astro/src/content/docs/zh-cn/performance/profiling.mdx+++ b/docs/astro/src/content/docs/zh-cn/performance/profiling.mdx@@ -128,6 +128,71 @@ console.log(`${rs.drawCalls} draw calls, ${rs.triangles} triangles`);| `phaseTimings` | 逐阶段毫秒数(push 时拷贝)。 || `systemTimings` | 逐系统毫秒数(push 时拷贝)。 |+## 从发行版游戏录制捕获 —— `ProfileRecorder`++编辑器的性能分析器只存在于编辑器连着的地方,而掉到 40 fps 通常是掉在玩家的设备上。+`ProfileRecorder` 把运行中游戏的帧录制成一份 **`.esprof` 捕获**,用编辑器的 Profiler+面板打开——同一棵树、同样的行、同样的合计。++```typescript+import { ProfileRecorder } from 'esengine';++const recorder = new ProfileRecorder(app, {+ maxFrames: 1800, // 60Hz 下约 30 秒,超出后丢最旧的+ source: { platform: 'wechat', label: 'Redmi Note 12 · boss 战' },+});++recorder.start();+// …… 把卡顿的那一段玩一遍 ……+recorder.stop();++const capture = recorder.take(); // 一个普通对象+```++| `ProfileRecorderOptions` | 类型 | 默认值 | 说明 |+|---|---|---|---|+| `maxFrames` | number | `1800` | 保留多少帧,超出后丢弃最旧的。 |+| `budgetMs` | number | `1000 / 60` | 读者据以判断这份捕获的帧预算。 |+| `source` | `CaptureSource` | `{}` | 设备、构建、场景——任何日后能认出这份捕获的信息。 |++`start()` 会打开它要读的插桩——JS 侧的统计和引擎 C++ 侧的性能分析都要开,因为缺了后者的捕获+看起来会像"引擎不花时间",而不是"这部分没被测量"——`stop()` 再把它们放下。+在你启动它之前,不录制任何东西,也不测量任何东西。++<Aside type="tip" title="引擎绝不选择目的地">+`take()` 交还一个对象,到此为止。引擎不开 socket、没有内置端点、不写文件,+所以捕获去哪儿完全由你的游戏决定——下载、你自己的上传、一行日志。+这也是为什么没有任何平台相关的接线要做:录制器本身在引擎能跑的地方都能跑。+</Aside>++在 web 构建里保存它就是普通的 DOM 操作:++```typescript+const blob = new Blob([JSON.stringify(recorder.take())], { type: 'application/json' });+const a = document.createElement('a');+a.href = URL.createObjectURL(blob);+a.download = 'boss-fight.esprof';+a.click();+```++然后在编辑器里用 **Profiler ▸ 打开…** 打开它。`parseProfileCapture` 遇到不是捕获的文件会+**带理由拒绝**(不是 JSON、没有版本、帧不是帧、版本比编辑器能读的更新)而不是抛异常;+`summarizeCapture` 就是实时视图用的那个函数——所以一份在手机上录的文件和编辑器自己的最近一秒,+不可能从同一批帧算出不同的帧率。++### 自己观察每一帧 —— `app.onFrameEnd`++录制器只是 `app.onFrameEnd(fn)` 的一个普通消费者。这个回调在每帧的系统跑完、耗时已成定局之后+触发一次。它是**广播**,所以你自己的帧预算告警可以和录制器一起看:++```typescript+const off = app.onFrameEnd((dtMs) => {+ if (dtMs > 33) console.warn(`长帧:${dtMs.toFixed(1)}ms`);+});+```++它返回一个解除函数。配合 `app.getFrameCosts()` 就能拿到刚结束那一帧的逐系统、逐 scope 开销。+## 日志SDK 自身的诊断信息走结构化日志器而不是裸 `console.*`,你的游戏代码可以用同一条diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 3f5a0b114..db731b298 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": 1482,+ "experimental": 1485,"deprecated": 3},- "total": 1654,+ "total": 1657,"subsystems": [{"id": "ecs",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex be68e4467..dce296718 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 · 1367 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1370 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -534,6 +534,7 @@ isPaused: () => booleanisPhysicsReady: booleanmeasureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => TonError: (handler: (error: unknown, systemName: string) => void) => App+onFrameEnd: (fn: (dtMs: number) => void) => () => voidonSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => ApponWasmError: (handler: (error: unknown, context: string) => void) => Apppipeline: RenderPipeline | null@@ -5471,6 +5472,36 @@ query: QueryCost | undefined'domain' | 'system' | 'scope' | 'rest'```+## ProfileRecorder — class @experimental+```+clear: () => void+frameCount: number+recording: boolean+start: () => void+stop: () => void+take: () => ProfileCapture+static new (app: App, options?: ProfileRecorderOptions): ProfileRecorder+static prototype: ProfileRecorder+```++## ProfileRecorderOptions — interface @experimental+```+budgetMs: number | undefined+maxFrames: number | undefined+source: CaptureSource | undefined+```++## ProfileRecorderPlugin — class @experimental+```+build: (app: App) => void+cleanup: () => void+name: "profileRecorder"+profileDomain: "diagnostics"+recorder: ProfileRecorder | null+static new (options_?: ProfileRecorderOptions, onReady_?: ((recorder: ProfileRecorder) => void) | undefined): ProfileRecorderPlugin+static prototype: ProfileRecorderPlugin+```+## ProgressHandle — interface @experimental```dispose: () => voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 04111d28f..4fc473972 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 · 1386 experimental · 3 deprecated+Symbols: 112 public · 58 beta · 1389 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -534,6 +534,7 @@ isPaused: () => booleanisPhysicsReady: booleanmeasureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => TonError: (handler: (error: unknown, systemName: string) => void) => App+onFrameEnd: (fn: (dtMs: number) => void) => () => voidonSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => ApponWasmError: (handler: (error: unknown, context: string) => void) => Apppipeline: RenderPipeline | null@@ -5654,6 +5655,36 @@ query: QueryCost | undefined'domain' | 'system' | 'scope' | 'rest'```+## ProfileRecorder — class @experimental+```+clear: () => void+frameCount: number+recording: boolean+start: () => void+stop: () => void+take: () => ProfileCapture+static new (app: App, options?: ProfileRecorderOptions): ProfileRecorder+static prototype: ProfileRecorder+```++## ProfileRecorderOptions — interface @experimental+```+budgetMs: number | undefined+maxFrames: number | undefined+source: CaptureSource | undefined+```++## ProfileRecorderPlugin — class @experimental+```+build: (app: App) => void+cleanup: () => void+name: "profileRecorder"+profileDomain: "diagnostics"+recorder: ProfileRecorder | null+static new (options_?: ProfileRecorderOptions, onReady_?: ((recorder: ProfileRecorder) => void) | undefined): ProfileRecorderPlugin+static prototype: ProfileRecorderPlugin+```+## ProgressHandle — interface @experimental```dispose: () => voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex e60451c2b..3e2516a82 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 · 1366 experimental · 3 deprecated+Symbols: 112 public · 55 beta · 1369 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -529,6 +529,7 @@ isPaused: () => booleanisPhysicsReady: booleanmeasureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => TonError: (handler: (error: unknown, systemName: string) => void) => App+onFrameEnd: (fn: (dtMs: number) => void) => () => voidonSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => ApponWasmError: (handler: (error: unknown, context: string) => void) => Apppipeline: RenderPipeline | null@@ -5466,6 +5467,36 @@ query: QueryCost | undefined'domain' | 'system' | 'scope' | 'rest'```+## ProfileRecorder — class @experimental+```+clear: () => void+frameCount: number+recording: boolean+start: () => void+stop: () => void+take: () => ProfileCapture+static new (app: App, options?: ProfileRecorderOptions): ProfileRecorder+static prototype: ProfileRecorder+```++## ProfileRecorderOptions — interface @experimental+```+budgetMs: number | undefined+maxFrames: number | undefined+source: CaptureSource | undefined+```++## ProfileRecorderPlugin — class @experimental+```+build: (app: App) => void+cleanup: () => void+name: "profileRecorder"+profileDomain: "diagnostics"+recorder: ProfileRecorder | null+static new (options_?: ProfileRecorderOptions, onReady_?: ((recorder: ProfileRecorder) => void) | undefined): ProfileRecorderPlugin+static prototype: ProfileRecorderPlugin+```+## ProgressHandle — interface @experimental```dispose: () => voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex f57f52b26..b1325d8b2 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 · 1387 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1390 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -529,6 +529,7 @@ isPaused: () => booleanisPhysicsReady: booleanmeasureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => TonError: (handler: (error: unknown, systemName: string) => void) => App+onFrameEnd: (fn: (dtMs: number) => void) => () => voidonSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => ApponWasmError: (handler: (error: unknown, context: string) => void) => Apppipeline: RenderPipeline | null@@ -5711,6 +5712,36 @@ query: QueryCost | undefined'domain' | 'system' | 'scope' | 'rest'```+## ProfileRecorder — class @experimental+```+clear: () => void+frameCount: number+recording: boolean+start: () => void+stop: () => void+take: () => ProfileCapture+static new (app: App, options?: ProfileRecorderOptions): ProfileRecorder+static prototype: ProfileRecorder+```++## ProfileRecorderOptions — interface @experimental+```+budgetMs: number | undefined+maxFrames: number | undefined+source: CaptureSource | undefined+```++## ProfileRecorderPlugin — class @experimental+```+build: (app: App) => void+cleanup: () => void+name: "profileRecorder"+profileDomain: "diagnostics"+recorder: ProfileRecorder | null+static new (options_?: ProfileRecorderOptions, onReady_?: ((recorder: ProfileRecorder) => void) | undefined): ProfileRecorderPlugin+static prototype: ProfileRecorderPlugin+```+## ProgressHandle — interface @experimental```dispose: () => voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 45a71f2f9..1712d080d 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 · 1377 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1380 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -529,6 +529,7 @@ isPaused: () => booleanisPhysicsReady: booleanmeasureFrameScope: <T>(name: string, fn: () => T, options?: { remainder?: ScopeRemainder; }) => TonError: (handler: (error: unknown, systemName: string) => void) => App+onFrameEnd: (fn: (dtMs: number) => void) => () => voidonSystemError: (handler: (error: Error, systemName?: string) => "continue" | "pause") => ApponWasmError: (handler: (error: unknown, context: string) => void) => Apppipeline: RenderPipeline | null@@ -5473,6 +5474,36 @@ query: QueryCost | undefined'domain' | 'system' | 'scope' | 'rest'```+## ProfileRecorder — class @experimental+```+clear: () => void+frameCount: number+recording: boolean+start: () => void+stop: () => void+take: () => ProfileCapture+static new (app: App, options?: ProfileRecorderOptions): ProfileRecorder+static prototype: ProfileRecorder+```++## ProfileRecorderOptions — interface @experimental+```+budgetMs: number | undefined+maxFrames: number | undefined+source: CaptureSource | undefined+```++## ProfileRecorderPlugin — class @experimental+```+build: (app: App) => void+cleanup: () => void+name: "profileRecorder"+profileDomain: "diagnostics"+recorder: ProfileRecorder | null+static new (options_?: ProfileRecorderOptions, onReady_?: ((recorder: ProfileRecorder) => void) | undefined): ProfileRecorderPlugin+static prototype: ProfileRecorderPlugin+```+## ProgressHandle — interface @experimental```dispose: () => voiddiff --git a/sdk/src/app/app.ts b/sdk/src/app/app.tsindex 9a74e45ad..73d3985dd 100644--- a/sdk/src/app/app.ts+++ b/sdk/src/app/app.ts@@ -156,6 +156,7 @@ export class App {private frameScopes_: Map<string, ScopeCost> | null = null;/** The system being run, so a scope opened inside one is filed under it. */private currentSystem_ = '';+ private readonly frameObservers_: Array<(dtMs: number) => void> = [];private frame_paused_ = false;private user_paused_ = false;private step_pending_ = false;@@ -743,6 +744,21 @@ export class App {}}+ /**+ * Observe the end of every frame, once its systems have run and its timings+ * are final. Returns a disposer.+ *+ * A broadcast, not a slot: a recorder and a game's own budget alarm both+ * watch without either taking the hook from the other.+ */+ onFrameEnd(fn: (dtMs: number) => void): () => void {+ this.frameObservers_.push(fn);+ return () => {+ const i = this.frameObservers_.indexOf(fn);+ if (i >= 0) this.frameObservers_.splice(i, 1);+ };+ }+getEntityCount(): number {return this.world_.entityCount();}@@ -1004,6 +1020,12 @@ export class App {const REMOVED_BUFFER_RETENTION = 2;this.world_.cleanRemovedBuffer(this.world_.getWorldTick() - REMOVED_BUFFER_RETENTION);++ for (const observe of this.frameObservers_) {+ try { observe(delta * 1000); } catch (e) {+ log.error('app', 'Frame observer error', e);+ }+ }}private finishPlugins_(): void {diff --git a/sdk/src/app/profileRecorder.ts b/sdk/src/app/profileRecorder.tsnew file mode 100644index 000000000..98958d69d--- /dev/null+++ b/sdk/src/app/profileRecorder.ts@@ -0,0 +1,165 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file profileRecorder.ts — a shipped game recording its own frames.+ */+import type { App, Plugin } from './app';+import { Renderer } from '../render/renderer';+import {+ PROFILE_CAPTURE_VERSION,+ type CaptureSource,+ type CapturedFrame,+ type ProfileCapture,+} from './profileCapture';+import type { ScopeCost } from './frameProfile';++export interface ProfileRecorderOptions {+ /** Frames kept before the oldest is dropped. 1800 is ~30s at 60Hz. */+ maxFrames?: number;+ /** The budget a reader judges the capture against. Defaults to 60Hz. */+ budgetMs?: number;+ /** Device, build, scene — whatever makes a capture identifiable later. */+ source?: CaptureSource;+}++const DEFAULT_MAX_FRAMES = 1800;++function parseScopes(json: string | undefined): Record<string, number> {+ if (!json) return {};+ try {+ return JSON.parse(json) as Record<string, number>;+ } catch {+ return {};+ }+}++function nativeScopesOf(json: string | undefined): ScopeCost[] {+ const raw = parseScopes(json);+ const out: ScopeCost[] = [];+ for (const name in raw) out.push({ name, ms: raw[name], system: '', remainder: 'work' });+ return out;+}++/**+ * Records frames into a capture the game can hand anywhere. Measures nothing of+ * its own, so a capture cannot disagree with the profiler panel; and chooses no+ * destination — `take()` returns an object, the engine opens no socket.+ */+export class ProfileRecorder {+ private readonly app_: App;+ private readonly options_: ProfileRecorderOptions;+ private readonly frames_: CapturedFrame[] = [];+ private recording_ = false;+ private detach_: (() => void) | null = null;+ private seq_ = 0;++ constructor(app: App, options: ProfileRecorderOptions = {}) {+ this.app_ = app;+ this.options_ = options;+ }++ get recording(): boolean {+ return this.recording_;+ }++ get frameCount(): number {+ return this.frames_.length;+ }++ /**+ * Begin recording, turning on the instrumentation it reads — both sides of+ * it, since the C++ scopes are behind their own switch and a capture missing+ * them looks like an engine that costs nothing rather than one not measured.+ */+ start(): void {+ if (this.recording_) return;+ this.frames_.length = 0;+ this.seq_ = 0;+ this.app_.enableStats();+ this.app_.wasmModule?.engine_setCpuProfiling?.(true);+ this.recording_ = true;+ this.detach_ = this.app_.onFrameEnd((dtMs) => this.capture_(dtMs));+ }++ /** Stop recording and put the engine's own profiling back down. */+ stop(): void {+ if (!this.recording_) return;+ this.recording_ = false;+ this.detach_?.();+ this.detach_ = null;+ this.app_.wasmModule?.engine_setCpuProfiling?.(false);+ }++ /** Throw away what has been recorded, keeping the recorder running. */+ clear(): void {+ this.frames_.length = 0;+ }++ /**+ * The capture so far. Recording may continue; the frames are copied out, so+ * the returned document does not change under a reader.+ */+ take(): ProfileCapture {+ return {+ version: PROFILE_CAPTURE_VERSION,+ generatedAt: new Date().toISOString(),+ source: this.options_.source ?? {},+ budgetMs: this.options_.budgetMs ?? 1000 / 60,+ frames: this.frames_.slice(),+ };+ }++ private capture_(dtMs: number): void {+ const costs = this.app_.getFrameCosts();+ if (!costs) return;+ const m = this.app_.wasmModule;+ const render = Renderer.getStats();+ const frame: CapturedFrame = {+ id: this.seq_++,+ dtMs,+ systems: costs.systems,+ scopes: costs.scopes,+ nativeScopes: nativeScopesOf(m?.engine_getCpuScopes?.()),+ gpuMs: m?.renderer_getGpuTimeMs?.() ?? -1,+ counters: parseScopes(m?.engine_getCounters?.()),+ drawCalls: render.drawCalls,+ triangles: render.triangles,+ entities: this.app_.getEntityCount(),+ memory: { wasmBytes: m?.HEAPU8?.byteLength ?? 0 },+ };+ this.frames_.push(frame);+ const cap = this.options_.maxFrames ?? DEFAULT_MAX_FRAMES;+ if (this.frames_.length > cap) this.frames_.shift();+ }+}++/**+ * Installs a {@link ProfileRecorder} and hands it to the game. Recording is NOT+ * started: a shipped build pays for the instrumentation only from the moment+ * something asks it to.+ */+export class ProfileRecorderPlugin implements Plugin {+ readonly name = 'profileRecorder';+ readonly profileDomain = 'diagnostics';+ private recorder_: ProfileRecorder | null = null;++ constructor(+ private readonly options_: ProfileRecorderOptions = {},+ private readonly onReady_?: (recorder: ProfileRecorder) => void,+ ) {}++ /** The recorder, once the plugin has been built into an App. */+ get recorder(): ProfileRecorder | null {+ return this.recorder_;+ }++ build(app: App): void {+ this.recorder_ = new ProfileRecorder(app, this.options_);+ this.onReady_?.(this.recorder_);+ }++ cleanup(): void {+ this.recorder_?.stop();+ this.recorder_ = null;+ }+}diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.tsindex c69b61600..a0ffc0abe 100644--- a/sdk/src/core-sys.ts+++ b/sdk/src/core-sys.ts@@ -201,6 +201,12 @@ export {export { StatsOverlay, type StatsPosition } from './stats-overlay';+export {+ ProfileRecorder,+ ProfileRecorderPlugin,+ type ProfileRecorderOptions,+} from './app/profileRecorder';+export {PROFILE_CAPTURE_VERSION,parseProfileCapture,diff --git a/sdk/tests/profile-recorder.test.ts b/sdk/tests/profile-recorder.test.tsnew file mode 100644index 000000000..c55fdbd80--- /dev/null+++ b/sdk/tests/profile-recorder.test.ts@@ -0,0 +1,186 @@+// 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 { ProfileRecorder, ProfileRecorderPlugin } from '../src/app/profileRecorder';+import { parseProfileCapture, summarizeCapture } from '../src/app/profileCapture';++function appWithSystem(name = 'Worker'): App {+ const app = App.new();+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {}, { name }));+ return app;+}++describe('App.onFrameEnd', () => {+ it('fires once a frame, after the systems ran', async () => {+ const app = App.new();+ const order: string[] = [];+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => order.push('system'), { name: 'S' }));+ app.onFrameEnd(() => order.push('frameEnd'));++ await app.tick(1 / 60);++ expect(order).toEqual(['system', 'frameEnd']);+ });++ it('is a broadcast, so one watcher never takes the hook from another', async () => {+ const app = App.new();+ const seen: string[] = [];+ app.onFrameEnd(() => seen.push('a'));+ app.onFrameEnd(() => seen.push('b'));++ await app.tick(1 / 60);++ expect(seen).toEqual(['a', 'b']);+ });++ it('stops calling a disposed observer', async () => {+ const app = App.new();+ let calls = 0;+ const off = app.onFrameEnd(() => { calls++; });+ await app.tick(1 / 60);+ off();+ await app.tick(1 / 60);++ expect(calls).toBe(1);+ });++ it('reports the frame delta in milliseconds', async () => {+ const app = App.new();+ let dt = 0;+ app.onFrameEnd((ms) => { dt = ms; });+ await app.tick(1 / 60);++ expect(dt).toBeCloseTo(1000 / 60, 3);+ });++ it('does not let one throwing observer stop the next', async () => {+ const app = App.new();+ let reached = false;+ app.onFrameEnd(() => { throw new Error('boom'); });+ app.onFrameEnd(() => { reached = true; });++ await expect(app.tick(1 / 60)).resolves.toBeUndefined();+ expect(reached).toBe(true);+ });+});++describe('ProfileRecorder', () => {+ it('records nothing until it is started', async () => {+ const app = appWithSystem();+ const rec = new ProfileRecorder(app);+ await app.tick(1 / 60);++ expect(rec.recording).toBe(false);+ expect(rec.frameCount).toBe(0);+ });++ it('turns on the stats it reads, so a capture is not empty of engine cost', async () => {+ const app = appWithSystem();+ new ProfileRecorder(app).start();+ await app.tick(1 / 60);++ expect(app.getFrameCosts()).not.toBeNull();+ });++ it('records a frame per frame, with the systems attributed', async () => {+ const app = appWithSystem('Worker');+ const rec = new ProfileRecorder(app);+ rec.start();+ await app.tick(1 / 60);+ await app.tick(1 / 60);++ expect(rec.frameCount).toBe(2);+ const capture = rec.take();+ expect(capture.frames[0].systems.some((s) => s.name === 'Worker')).toBe(true);+ });++ it('stops recording when told, and keeps what it has', async () => {+ const app = appWithSystem();+ const rec = new ProfileRecorder(app);+ rec.start();+ await app.tick(1 / 60);+ rec.stop();+ await app.tick(1 / 60);++ expect(rec.recording).toBe(false);+ expect(rec.frameCount).toBe(1);+ });++ it('drops the oldest frame rather than growing without bound', async () => {+ const app = appWithSystem();+ const rec = new ProfileRecorder(app, { maxFrames: 3 });+ rec.start();+ for (let i = 0; i < 6; i++) await app.tick(1 / 60);++ expect(rec.frameCount).toBe(3);+ // The ring kept the LAST three, which is what a hitch is at the end of.+ expect(rec.take().frames.map((f) => f.id)).toEqual([3, 4, 5]);+ });++ it('hands back a document that does not change under its reader', async () => {+ const app = appWithSystem();+ const rec = new ProfileRecorder(app);+ rec.start();+ await app.tick(1 / 60);+ const capture = rec.take();+ await app.tick(1 / 60);++ expect(capture.frames).toHaveLength(1);+ expect(rec.frameCount).toBe(2);+ });++ it('carries the source it was told, so a capture says where it is from', async () => {+ const app = appWithSystem();+ const rec = new ProfileRecorder(app, { source: { platform: 'wechat', label: 'Redmi Note 12' } });+ rec.start();+ await app.tick(1 / 60);++ expect(rec.take().source).toEqual({ platform: 'wechat', label: 'Redmi Note 12' });+ });++ it('writes a capture the editor reads back', async () => {+ const app = appWithSystem('Worker');+ const rec = new ProfileRecorder(app, { budgetMs: 1000 / 30 });+ rec.start();+ for (let i = 0; i < 4; i++) await app.tick(1 / 60);++ const parsed = parseProfileCapture(JSON.stringify(rec.take()));+ expect('capture' in parsed).toBe(true);+ if ('capture' in parsed) {+ const s = summarizeCapture(parsed.capture);+ expect(s.frames).toBe(4);+ expect(s.budgetMs).toBeCloseTo(1000 / 30, 4);+ expect(s.mean.cpuMs + s.mean.waitMs + s.mean.idleMs).toBeCloseTo(s.mean.frameMs, 4);+ }+ });++ it('clears on demand without stopping', async () => {+ const app = appWithSystem();+ const rec = new ProfileRecorder(app);+ rec.start();+ await app.tick(1 / 60);+ rec.clear();+ await app.tick(1 / 60);++ expect(rec.recording).toBe(true);+ expect(rec.frameCount).toBe(1);+ });+});++describe('ProfileRecorderPlugin', () => {+ it('hands the game its recorder and starts nothing', async () => {+ let handed: ProfileRecorder | null = null;+ const app = App.new();+ app.addPlugin(new ProfileRecorderPlugin({}, (r) => { handed = r; }));+ await app.tick(1 / 60);++ expect(handed).toBeInstanceOf(ProfileRecorder);+ expect(handed!.recording).toBe(false);+ });++ it('files its own cost under diagnostics rather than a domain of its own', () => {+ expect(new ProfileRecorderPlugin().profileDomain).toBe('diagnostics');+ });+});